filename
stringlengths 5
42
| content
stringlengths 15
319k
|
|---|---|
Action.lean
|
/-
Copyright (c) 2024 Christian Merten. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Christian Merten
-/
import Mathlib.CategoryTheory.Galois.Examples
import Mathlib.CategoryTheory.Galois.Prorepresentability
/-!
# Induced functor to finite `Aut F`-sets
Any (fiber) functor `F : C ⥤ FintypeCat` factors via the forgetful functor
from finite `Aut F`-sets to finite sets. In this file we collect basic properties
of the induced functor `H : C ⥤ Action FintypeCat (Aut F)`.
See `Mathlib/CategoryTheory/Galois/Full.lean` for the proof that `H` is (faithfully) full.
-/
universe u
namespace CategoryTheory
namespace PreGaloisCategory
open Limits Functor
variable {C : Type*} [Category C] (F : C ⥤ FintypeCat.{u})
/-- Any (fiber) functor `F : C ⥤ FintypeCat` naturally factors via
the forgetful functor from `Action FintypeCat (Aut F)` to `FintypeCat`. -/
def functorToAction : C ⥤ Action FintypeCat.{u} (Aut F) where
obj X := Action.FintypeCat.ofMulAction (Aut F) (F.obj X)
map f := {
hom := F.map f
comm := fun g ↦ symm <| g.hom.naturality f
}
lemma functorToAction_comp_forget₂_eq : functorToAction F ⋙ forget₂ _ FintypeCat = F := rfl
@[simp]
lemma functorToAction_map {X Y : C} (f : X ⟶ Y) : ((functorToAction F).map f).hom = F.map f :=
rfl
instance (X : C) : MulAction (Aut X) ((functorToAction F).obj X).V :=
inferInstanceAs <| MulAction (Aut X) (F.obj X)
variable [GaloisCategory C] [FiberFunctor F]
instance (X : C) [IsGalois X] : MulAction.IsPretransitive (Aut X) ((functorToAction F).obj X).V :=
isPretransitive_of_isGalois F X
instance : Functor.Faithful (functorToAction F) :=
have : Functor.Faithful (functorToAction F ⋙ forget₂ _ FintypeCat) :=
inferInstanceAs <| Functor.Faithful F
Functor.Faithful.of_comp (functorToAction F) (forget₂ _ FintypeCat)
instance : PreservesMonomorphisms (functorToAction F) :=
have : PreservesMonomorphisms (functorToAction F ⋙ forget₂ _ FintypeCat) :=
inferInstanceAs <| PreservesMonomorphisms F
preservesMonomorphisms_of_preserves_of_reflects (functorToAction F) (forget₂ _ FintypeCat)
instance : ReflectsMonomorphisms (functorToAction F) := reflectsMonomorphisms_of_faithful _
instance : Functor.ReflectsIsomorphisms (functorToAction F) where
reflects f _ :=
have : IsIso (F.map f) := (forget₂ _ FintypeCat).map_isIso ((functorToAction F).map f)
isIso_of_reflects_iso f F
noncomputable instance : PreservesFiniteCoproducts (functorToAction F) :=
⟨fun _ ↦ Action.preservesColimitsOfShape_of_preserves (functorToAction F)
(inferInstanceAs <| PreservesColimitsOfShape (Discrete _) F)⟩
noncomputable instance : PreservesFiniteProducts (functorToAction F) :=
⟨fun _ ↦ Action.preservesLimitsOfShape_of_preserves (functorToAction F)
(inferInstanceAs <| PreservesLimitsOfShape (Discrete _) F)⟩
noncomputable instance (G : Type*) [Group G] [Finite G] :
PreservesColimitsOfShape (SingleObj G) (functorToAction F) :=
Action.preservesColimitsOfShape_of_preserves _ <|
inferInstanceAs <| PreservesColimitsOfShape (SingleObj G) F
instance : PreservesIsConnected (functorToAction F) :=
⟨fun {X} _ ↦ FintypeCat.Action.isConnected_of_transitive (Aut F) (F.obj X)⟩
end PreGaloisCategory
end CategoryTheory
|
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.
|
WithLp.lean
|
/-
Copyright (c) 2025 Etienne Marion. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Etienne Marion
-/
import Mathlib.Analysis.Normed.Lp.PiLp
import Mathlib.MeasureTheory.SpecificCodomains.Pi
/-!
# Integrability in `WithLp`
We prove that `f : X → PiLp q E` is in `Lᵖ` if and only if for all `i`, `f · i` is in `Lᵖ`.
We do the same for `f : X → WithLp q (E × F)`.
-/
open scoped ENNReal
namespace MeasureTheory
variable {X : Type*} {mX : MeasurableSpace X} {μ : Measure X} {p q : ℝ≥0∞} [Fact (1 ≤ q)]
section Pi
variable {ι : Type*} [Fintype ι] {E : ι → Type*} [∀ i, NormedAddCommGroup (E i)] {f : X → PiLp q E}
lemma memLp_piLp_iff : MemLp f p μ ↔ ∀ i, MemLp (f · i) p μ := by
simp_rw [← PiLp.ofLp_apply, ← memLp_pi_iff, ← Function.comp_apply (f := WithLp.ofLp)]
exact (PiLp.lipschitzWith_ofLp q E).memLp_comp_iff_of_antilipschitz
(PiLp.antilipschitzWith_ofLp q E) (by simp) |>.symm
alias ⟨MemLp.eval_piLp, MemLp.of_eval_piLp⟩ := memLp_piLp_iff
lemma integrable_piLp_iff : Integrable f μ ↔ ∀ i, Integrable (f · i) μ := by
simp_rw [← memLp_one_iff_integrable, memLp_piLp_iff]
alias ⟨Integrable.eval_piLp, Integrable.of_eval_piLp⟩ := integrable_piLp_iff
variable [∀ i, NormedSpace ℝ (E i)] [∀ i, CompleteSpace (E i)]
lemma eval_integral_piLp (hf : ∀ i, Integrable (f · i) μ) (i : ι) :
(∫ x, f x ∂μ) i = ∫ x, f x i ∂μ := by
rw [← PiLp.proj_apply (𝕜 := ℝ) q E i (∫ x, f x ∂μ), ← ContinuousLinearMap.integral_comp_comm]
· simp
exact Integrable.of_eval_piLp hf
end Pi
section Prod
variable {E F : Type*} [NormedAddCommGroup E] [NormedAddCommGroup F] {f : X → WithLp q (E × F)}
lemma memLp_prodLp_iff :
MemLp f p μ ↔ MemLp (fun x ↦ (f x).fst) p μ ∧ MemLp (fun x ↦ (f x).snd) p μ := by
simp_rw [← memLp_prod_iff]
exact (WithLp.prod_lipschitzWith_ofLp q E F).memLp_comp_iff_of_antilipschitz
(WithLp.prod_antilipschitzWith_ofLp q E F) (by simp) |>.symm
lemma MemLp.prodLp_fst (h : MemLp f p μ) : MemLp (fun x ↦ (f x).fst) p μ :=
memLp_prodLp_iff.1 h |>.1
lemma MemLp.prodLp_snd (h : MemLp f p μ) : MemLp (fun x ↦ (f x).snd) p μ :=
memLp_prodLp_iff.1 h |>.2
alias ⟨_, MemLp.of_fst_of_snd_prodLp⟩ := memLp_prodLp_iff
lemma integrable_prodLp_iff :
Integrable f μ ↔
Integrable (fun x ↦ (f x).fst) μ ∧
Integrable (fun x ↦ (f x).snd) μ := by
simp_rw [← memLp_one_iff_integrable, memLp_prodLp_iff]
lemma Integrable.prodLp_fst (h : Integrable f μ) : Integrable (fun x ↦ (f x).fst) μ :=
integrable_prodLp_iff.1 h |>.1
lemma Integrable.prodLp_snd (h : Integrable f μ) : Integrable (fun x ↦ (f x).snd) μ :=
integrable_prodLp_iff.1 h |>.2
alias ⟨_, Integrable.of_fst_of_snd_prodLp⟩ := integrable_prodLp_iff
variable [NormedSpace ℝ E] [NormedSpace ℝ F]
theorem fst_integral_withLp [CompleteSpace F] (hf : Integrable f μ) :
(∫ x, f x ∂μ).fst = ∫ x, (f x).fst ∂μ := by
rw [← WithLp.ofLp_fst]
conv => enter [1, 1]; change WithLp.prodContinuousLinearEquiv q ℝ E F _
rw [← ContinuousLinearEquiv.integral_comp_comm, fst_integral]
· rfl
· simpa
theorem snd_integral_withLp [CompleteSpace E] (hf : Integrable f μ) :
(∫ x, f x ∂μ).snd = ∫ x, (f x).snd ∂μ := by
rw [← WithLp.ofLp_snd]
conv => enter [1, 1]; change WithLp.prodContinuousLinearEquiv q ℝ E F _
rw [← ContinuousLinearEquiv.integral_comp_comm, snd_integral]
· rfl
· simpa
end Prod
end MeasureTheory
|
Eigs.lean
|
/-
Copyright (c) 2023 Mohanad Ahmed. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mohanad Ahmed
-/
import Mathlib.Algebra.Polynomial.Basic
import Mathlib.FieldTheory.IsAlgClosed.Basic
/-!
# Eigenvalues are characteristic polynomial roots.
In fields we show that:
* `Matrix.det_eq_prod_roots_charpoly_of_splits`: the determinant (in the field of the matrix)
is the product of the roots of the characteristic polynomial if the polynomial splits in the field
of the matrix.
* `Matrix.trace_eq_sum_roots_charpoly_of_splits`: the trace is the sum of the roots of the
characteristic polynomial if the polynomial splits in the field of the matrix.
In an algebraically closed field we show that:
* `Matrix.det_eq_prod_roots_charpoly`: the determinant is the product of the roots of the
characteristic polynomial.
* `Matrix.trace_eq_sum_roots_charpoly`: the trace is the sum of the roots of the
characteristic polynomial.
Note that over other fields such as `ℝ`, these results can be used by using
`A.map (algebraMap ℝ ℂ)` as the matrix, and then applying `RingHom.map_det`.
The two lemmas `Matrix.det_eq_prod_roots_charpoly` and `Matrix.trace_eq_sum_roots_charpoly` are more
commonly stated as trace is the sum of eigenvalues and determinant is the product of eigenvalues.
Mathlib has already defined eigenvalues in `LinearAlgebra.Eigenspace` as the roots of the minimal
polynomial of a linear endomorphism. These do not have correct multiplicity and cannot be used in
the theorems above. Hence we express these theorems in terms of the roots of the characteristic
polynomial directly.
## TODO
The proofs of `det_eq_prod_roots_charpoly_of_splits` and
`trace_eq_sum_roots_charpoly_of_splits` closely resemble
`norm_gen_eq_prod_roots` and `trace_gen_eq_sum_roots` respectively, but the
dependencies are not general enough to unify them. We should refactor
`Polynomial.prod_roots_eq_coeff_zero_of_monic_of_split` and
`Polynomial.sum_roots_eq_nextCoeff_of_monic_of_split` to assume splitting over an arbitrary map.
-/
variable {n : Type*} [Fintype n] [DecidableEq n]
variable {R : Type*} [Field R]
variable {A : Matrix n n R}
open Matrix Polynomial
open scoped Matrix
namespace Matrix
theorem det_eq_prod_roots_charpoly_of_splits (hAps : A.charpoly.Splits (RingHom.id R)) :
A.det = (Matrix.charpoly A).roots.prod := by
rw [det_eq_sign_charpoly_coeff, ← charpoly_natDegree_eq_dim A,
Polynomial.prod_roots_eq_coeff_zero_of_monic_of_splits A.charpoly_monic hAps, ← mul_assoc,
← pow_two, pow_right_comm, neg_one_sq, one_pow, one_mul]
theorem trace_eq_sum_roots_charpoly_of_splits (hAps : A.charpoly.Splits (RingHom.id R)) :
A.trace = (Matrix.charpoly A).roots.sum := by
rcases isEmpty_or_nonempty n with h | _
· rw [Matrix.trace, Fintype.sum_empty, Matrix.charpoly,
det_eq_one_of_card_eq_zero (Fintype.card_eq_zero_iff.2 h), Polynomial.roots_one,
Multiset.empty_eq_zero, Multiset.sum_zero]
· rw [trace_eq_neg_charpoly_coeff, neg_eq_iff_eq_neg,
← Polynomial.sum_roots_eq_nextCoeff_of_monic_of_split A.charpoly_monic hAps, nextCoeff,
charpoly_natDegree_eq_dim, if_neg (Fintype.card_ne_zero : Fintype.card n ≠ 0)]
variable (A)
theorem det_eq_prod_roots_charpoly [IsAlgClosed R] : A.det = (Matrix.charpoly A).roots.prod :=
det_eq_prod_roots_charpoly_of_splits (IsAlgClosed.splits A.charpoly)
theorem trace_eq_sum_roots_charpoly [IsAlgClosed R] : A.trace = (Matrix.charpoly A).roots.sum :=
trace_eq_sum_roots_charpoly_of_splits (IsAlgClosed.splits A.charpoly)
end Matrix
|
seq.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.
(******************************************************************************)
(* The seq type is the ssreflect type for sequences; it is an alias for the *)
(* standard Coq list type. The ssreflect library equips it with many *)
(* operations, as well as eqType and predType (and, later, choiceType) *)
(* structures. The operations are geared towards reflection: they generally *)
(* expect and provide boolean predicates, e.g., the membership predicate *)
(* expects an eqType. To avoid any confusion we do not Import the Coq List *)
(* module. *)
(* As there is no true subtyping in Coq, we don't use a type for non-empty *)
(* sequences; rather, we pass explicitly the head and tail of the sequence. *)
(* The empty sequence is especially bothersome for subscripting, since it *)
(* forces us to pass a default value. This default value can often be hidden *)
(* by a notation. *)
(* Here is the list of seq operations: *)
(* ** Constructors: *)
(* seq T == the type of sequences of items of type T. *)
(* bitseq == seq bool. *)
(* [::], nil, Nil T == the empty sequence (of type T). *)
(* x :: s, cons x s, Cons T x s == the sequence x followed by s (of type T). *)
(* [:: x] == the singleton sequence. *)
(* [:: x_0; ...; x_n] == the explicit sequence of the x_i. *)
(* [:: x_0, ..., x_n & s] == the sequence of the x_i, followed by s. *)
(* rcons s x == the sequence s, followed by x. *)
(* All of the above, except rcons, can be used in patterns. We define a view *)
(* lastP and an induction principle last_ind that can be used to decompose *)
(* or traverse a sequence in a right to left order. The view lemma lastP has *)
(* a dependent family type, so the ssreflect tactic case/lastP: p => [|p' x] *)
(* will generate two subgoals in which p has been replaced by [::] and by *)
(* rcons p' x, respectively. *)
(* ** Factories: *)
(* nseq n x == a sequence of n x's. *)
(* ncons n x s == a sequence of n x's, followed by s. *)
(* seqn n x_0 ... x_n-1 == the sequence of the x_i; can be partially applied. *)
(* iota m n == the sequence m, m + 1, ..., m + n - 1. *)
(* mkseq f n == the sequence f 0, f 1, ..., f (n - 1). *)
(* ** Sequential access: *)
(* head x0 s == the head (zero'th item) of s if s is non-empty, else x0. *)
(* ohead s == None if s is empty, else Some x when the head of s is x. *)
(* behead s == s minus its head, i.e., s' if s = x :: s', else [::]. *)
(* last x s == the last element of x :: s (which is non-empty). *)
(* belast x s == x :: s minus its last item. *)
(* ** Dimensions: *)
(* size s == the number of items (length) in s. *)
(* shape ss == the sequence of sizes of the items of the sequence of *)
(* sequences ss. *)
(* ** Random access: *)
(* nth x0 s i == the item i of s (numbered from 0), or x0 if s does *)
(* not have at least i+1 items (i.e., size x <= i) *)
(* s`_i == standard notation for nth x0 s i for a default x0, *)
(* e.g., 0 for rings. *)
(* onth s i == Some x if x is the i^th idem of s (numbered from 0), *)
(* or None if size s <= i) *)
(* set_nth x0 s i y == s where item i has been changed to y; if s does not *)
(* have an item i, it is first padded with copies of x0 *)
(* to size i+1. *)
(* incr_nth s i == the nat sequence s with item i incremented (s is *)
(* first padded with 0's to size i+1, if needed). *)
(* ** Predicates: *)
(* nilp s <=> s is [::]. *)
(* := (size s == 0). *)
(* x \in s == x appears in s (this requires an eqType for T). *)
(* index x s == the first index at which x appears in s, or size s if *)
(* x \notin s. *)
(* has a s <=> a holds for some item in s, where a is an applicative *)
(* bool predicate. *)
(* all a s <=> a holds for all items in s. *)
(* 'has_aP <-> the view reflect (exists2 x, x \in s & A x) (has a s), *)
(* where aP x : reflect (A x) (a x). *)
(* 'all_aP <=> the view for reflect {in s, forall x, A x} (all a s). *)
(* all2 r s t <=> the (bool) relation r holds for all _respective_ items *)
(* in s and t, which must also have the same size, i.e., *)
(* for s := [:: x1; ...; x_m] and t := [:: y1; ...; y_n], *)
(* the condition [&& r x_1 y_1, ..., r x_n y_n & m == n]. *)
(* find p s == the index of the first item in s for which p holds, *)
(* or size s if no such item is found. *)
(* count p s == the number of items of s for which p holds. *)
(* count_mem x s == the multiplicity of x in s, i.e., count (pred1 x) s. *)
(* tally s == a tally of s, i.e., a sequence of (item, multiplicity) *)
(* pairs for all items in sequence s (without duplicates). *)
(* incr_tally bs x == increment the multiplicity of x in the tally bs, or add *)
(* x with multiplicity 1 at then end if x is not in bs. *)
(* bs \is a wf_tally <=> bs is well-formed tally, with no duplicate items or *)
(* null multiplicities. *)
(* tally_seq bs == the expansion of a tally bs into a sequence where each *)
(* (x, n) pair expands into a sequence of n x's. *)
(* constant s <=> all items in s are identical (trivial if s = [::]). *)
(* uniq s <=> all the items in s are pairwise different. *)
(* subseq s1 s2 <=> s1 is a subsequence of s2, i.e., s1 = mask m s2 for *)
(* some m : bitseq (see below). *)
(* infix s1 s2 <=> s1 is a contiguous subsequence of s2, i.e., *)
(* s ++ s1 ++ s' = s2 for some sequences s, s'. *)
(* prefix s1 s2 <=> s1 is a subchain of s2 appearing at the beginning *)
(* of s2. *)
(* suffix s1 s2 <=> s1 is a subchain of s2 appearing at the end of s2. *)
(* infix_index s1 s2 <=> the first index at which s1 appears in s2, *)
(* or (size s2).+1 if infix s1 s2 is false. *)
(* perm_eq s1 s2 <=> s2 is a permutation of s1, i.e., s1 and s2 have the *)
(* items (with the same repetitions), but possibly in a *)
(* different order. *)
(* perm_eql s1 s2 <-> s1 and s2 behave identically on the left of perm_eq. *)
(* perm_eqr s1 s2 <-> s1 and s2 behave identically on the right of perm_eq. *)
(* --> These left/right transitive versions of perm_eq make it easier to *)
(* chain a sequence of equivalences. *)
(* permutations s == a duplicate-free list of all permutations of s. *)
(* ** Filtering: *)
(* filter p s == the subsequence of s consisting of all the items *)
(* for which the (boolean) predicate p holds. *)
(* rem x s == the subsequence of s, where the first occurrence *)
(* of x has been removed (compare filter (predC1 x) s *)
(* where ALL occurrences of x are removed). *)
(* undup s == the subsequence of s containing only the first *)
(* occurrence of each item in s, i.e., s with all *)
(* duplicates removed. *)
(* mask m s == the subsequence of s selected by m : bitseq, with *)
(* item i of s selected by bit i in m (extra items or *)
(* bits are ignored. *)
(* ** Surgery: *)
(* s1 ++ s2, cat s1 s2 == the concatenation of s1 and s2. *)
(* take n s == the sequence containing only the first n items of s *)
(* (or all of s if size s <= n). *)
(* drop n s == s minus its first n items ([::] if size s <= n) *)
(* rot n s == s rotated left n times (or s if size s <= n). *)
(* := drop n s ++ take n s *)
(* rotr n s == s rotated right n times (or s if size s <= n). *)
(* rev s == the (linear time) reversal of s. *)
(* catrev s1 s2 == the reversal of s1 followed by s2 (this is the *)
(* recursive form of rev). *)
(* ** Dependent iterator: for s : seq S and t : S -> seq T *)
(* [seq E | x <- s, y <- t] := flatten [seq [seq E | x <- t] | y <- s] *)
(* == the sequence of all the f x y, with x and y drawn from *)
(* s and t, respectively, in row-major order, *)
(* and where t is possibly dependent in elements of s *)
(* allpairs_dep f s t := self expanding definition for *)
(* [seq f x y | x <- s, y <- t y] *)
(* ** Iterators: for s == [:: x_1, ..., x_n], t == [:: y_1, ..., y_m], *)
(* allpairs f s t := same as allpairs_dep but where t is non dependent, *)
(* i.e. self expanding definition for *)
(* [seq f x y | x <- s, y <- t] *)
(* := [:: f x_1 y_1; ...; f x_1 y_m; f x_2 y_1; ...; f x_n y_m] *)
(* allrel r xs ys := all [pred x | all (r x) ys] xs *)
(* <=> r x y holds whenever x is in xs and y is in ys *)
(* all2rel r xs := allrel r xs xs *)
(* <=> the proposition r x y holds for all possible x, y in xs.*)
(* pairwise r xs <=> the relation r holds for any i-th and j-th element of *)
(* xs such that i < j. *)
(* map f s == the sequence [:: f x_1, ..., f x_n]. *)
(* pmap pf s == the sequence [:: y_i1, ..., y_ik] where i1 < ... < ik, *)
(* pf x_i = Some y_i, and pf x_j = None iff j is not in *)
(* {i1, ..., ik}. *)
(* foldr f a s == the right fold of s by f (i.e., the natural iterator). *)
(* := f x_1 (f x_2 ... (f x_n a)) *)
(* sumn s == x_1 + (x_2 + ... + (x_n + 0)) (when s : seq nat). *)
(* foldl f a s == the left fold of s by f. *)
(* := f (f ... (f a x_1) ... x_n-1) x_n *)
(* scanl f a s == the sequence of partial accumulators of foldl f a s. *)
(* := [:: f a x_1; ...; foldl f a s] *)
(* pairmap f a s == the sequence of f applied to consecutive items in a :: s. *)
(* := [:: f a x_1; f x_1 x_2; ...; f x_n-1 x_n] *)
(* zip s t == itemwise pairing of s and t (dropping any extra items). *)
(* := [:: (x_1, y_1); ...; (x_mn, y_mn)] with mn = minn n m. *)
(* unzip1 s == [:: (x_1).1; ...; (x_n).1] when s : seq (S * T). *)
(* unzip2 s == [:: (x_1).2; ...; (x_n).2] when s : seq (S * T). *)
(* flatten s == x_1 ++ ... ++ x_n ++ [::] when s : seq (seq T). *)
(* reshape r s == s reshaped into a sequence of sequences whose sizes are *)
(* given by r (truncating if s is too long or too short). *)
(* := [:: [:: x_1; ...; x_r1]; *)
(* [:: x_(r1 + 1); ...; x_(r0 + r1)]; *)
(* ...; *)
(* [:: x_(r1 + ... + r(k-1) + 1); ...; x_(r0 + ... rk)]] *)
(* flatten_index sh r c == the index, in flatten ss, of the item of indexes *)
(* (r, c) in any sequence of sequences ss of shape sh *)
(* := sh_1 + sh_2 + ... + sh_r + c *)
(* reshape_index sh i == the index, in reshape sh s, of the sequence *)
(* containing the i-th item of s. *)
(* reshape_offset sh i == the offset, in the (reshape_index sh i)-th *)
(* sequence of reshape sh s of the i-th item of s *)
(* ** Notation for manifest comprehensions: *)
(* [seq x <- s | C] := filter (fun x => C) s. *)
(* [seq E | x <- s] := map (fun x => E) s. *)
(* [seq x <- s | C1 & C2] := [seq x <- s | C1 && C2]. *)
(* [seq E | x <- s & C] := [seq E | x <- [seq x | C]]. *)
(* --> The above allow optional type casts on the eigenvariables, as in *)
(* [seq x : T <- s | C] or [seq E | x : T <- s, y : U <- t]. The cast may be *)
(* needed as type inference considers E or C before s. *)
(* We are quite systematic in providing lemmas to rewrite any composition *)
(* of two operations. "rev", whose simplifications are not natural, is *)
(* protected with simpl never. *)
(* ** The following are equivalent: *)
(* [<-> P0; P1; ..; Pn] <-> P0, P1, ..., Pn are all equivalent. *)
(* := P0 -> P1 -> ... -> Pn -> P0 *)
(* if T : [<-> P0; P1; ..; Pn] is such an equivalence, and i, j are in nat *)
(* then T i j is a proof of the equivalence Pi <-> Pj between Pi and Pj; *)
(* when i (resp. j) is out of bounds, Pi (resp. Pj) defaults to P0. *)
(* The tactic tfae splits the goal into n+1 implications to prove. *)
(* An example of use can be found in fingraph theorem orbitPcycle. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Declare Scope seq_scope.
Reserved Notation "[ '<->' P0 ; P1 ; .. ; Pn ]"
(format "[ '<->' '[' P0 ; '/' P1 ; '/' .. ; '/' Pn ']' ]").
Delimit Scope seq_scope with SEQ.
Open Scope seq_scope.
(* Inductive seq (T : Type) : Type := Nil | Cons of T & seq T. *)
Notation seq := list.
Bind Scope seq_scope with list.
Arguments cons {T%_type} x s%_SEQ : rename.
Arguments nil {T%_type} : rename.
Notation Cons T := (@cons T) (only parsing).
Notation Nil T := (@nil T) (only parsing).
(* As :: and ++ are (improperly) declared in Init.datatypes, we only rebind *)
(* them here. *)
Infix "::" := cons : seq_scope.
Notation "[ :: ]" := nil (format "[ :: ]") : seq_scope.
Notation "[ :: x1 ]" := (x1 :: [::]) (format "[ :: x1 ]") : seq_scope.
Notation "[ :: x & s ]" := (x :: s) (only parsing) : seq_scope.
Notation "[ :: x1 , x2 , .. , xn & s ]" := (x1 :: x2 :: .. (xn :: s) ..)
(format
"'[hv' [ :: '[' x1 , '/' x2 , '/' .. , '/' xn ']' '/ ' & s ] ']'"
) : seq_scope.
Notation "[ :: x1 ; x2 ; .. ; xn ]" := (x1 :: x2 :: .. [:: xn] ..)
(format "[ :: '[' x1 ; '/' x2 ; '/' .. ; '/' xn ']' ]"
) : seq_scope.
Section Sequences.
Variable n0 : nat. (* numerical parameter for take, drop et al *)
Variable T : Type. (* must come before the implicit Type *)
Variable x0 : T. (* default for head/nth *)
Implicit Types x y z : T.
Implicit Types m n : nat.
Implicit Type s : seq T.
Fixpoint size s := if s is _ :: s' then (size s').+1 else 0.
Lemma size0nil s : size s = 0 -> s = [::]. Proof. by case: s. Qed.
Definition nilp s := size s == 0.
Lemma nilP s : reflect (s = [::]) (nilp s).
Proof. by case: s => [|x s]; constructor. Qed.
Definition ohead s := if s is x :: _ then Some x else None.
Definition head s := if s is x :: _ then x else x0.
Definition behead s := if s is _ :: s' then s' else [::].
Lemma size_behead s : size (behead s) = (size s).-1.
Proof. by case: s. Qed.
(* Factories *)
Definition ncons n x := iter n (cons x).
Definition nseq n x := ncons n x [::].
Lemma size_ncons n x s : size (ncons n x s) = n + size s.
Proof. by elim: n => //= n ->. Qed.
Lemma size_nseq n x : size (nseq n x) = n.
Proof. by rewrite size_ncons addn0. Qed.
(* n-ary, dependently typed constructor. *)
Fixpoint seqn_type n := if n is n'.+1 then T -> seqn_type n' else seq T.
Fixpoint seqn_rec f n : seqn_type n :=
if n is n'.+1 return seqn_type n then
fun x => seqn_rec (fun s => f (x :: s)) n'
else f [::].
Definition seqn := seqn_rec id.
(* Sequence catenation "cat". *)
Fixpoint cat s1 s2 := if s1 is x :: s1' then x :: s1' ++ s2 else s2
where "s1 ++ s2" := (cat s1 s2) : seq_scope.
Lemma cat0s s : [::] ++ s = s. Proof. by []. Qed.
Lemma cat1s x s : [:: x] ++ s = x :: s. Proof. by []. Qed.
Lemma cat_cons x s1 s2 : (x :: s1) ++ s2 = x :: s1 ++ s2. Proof. by []. Qed.
Lemma cat_nseq n x s : nseq n x ++ s = ncons n x s.
Proof. by elim: n => //= n ->. Qed.
Lemma nseqD n1 n2 x : nseq (n1 + n2) x = nseq n1 x ++ nseq n2 x.
Proof. by rewrite cat_nseq /nseq /ncons iterD. Qed.
Lemma cats0 s : s ++ [::] = s.
Proof. by elim: s => //= x s ->. Qed.
Lemma catA s1 s2 s3 : s1 ++ s2 ++ s3 = (s1 ++ s2) ++ s3.
Proof. by elim: s1 => //= x s1 ->. Qed.
Lemma size_cat s1 s2 : size (s1 ++ s2) = size s1 + size s2.
Proof. by elim: s1 => //= x s1 ->. Qed.
Lemma cat_nilp s1 s2 : nilp (s1 ++ s2) = nilp s1 && nilp s2.
Proof. by case: s1. Qed.
(* last, belast, rcons, and last induction. *)
Fixpoint rcons s z := if s is x :: s' then x :: rcons s' z else [:: z].
Lemma rcons_cons x s z : rcons (x :: s) z = x :: rcons s z.
Proof. by []. Qed.
Lemma cats1 s z : s ++ [:: z] = rcons s z.
Proof. by elim: s => //= x s ->. Qed.
Fixpoint last x s := if s is x' :: s' then last x' s' else x.
Fixpoint belast x s := if s is x' :: s' then x :: (belast x' s') else [::].
Lemma lastI x s : x :: s = rcons (belast x s) (last x s).
Proof. by elim: s x => [|y s IHs] x //=; rewrite IHs. Qed.
Lemma last_cons x y s : last x (y :: s) = last y s.
Proof. by []. Qed.
Lemma size_rcons s x : size (rcons s x) = (size s).+1.
Proof. by rewrite -cats1 size_cat addnC. Qed.
Lemma size_belast x s : size (belast x s) = size s.
Proof. by elim: s x => [|y s IHs] x //=; rewrite IHs. Qed.
Lemma last_cat x s1 s2 : last x (s1 ++ s2) = last (last x s1) s2.
Proof. by elim: s1 x => [|y s1 IHs] x //=; rewrite IHs. Qed.
Lemma last_rcons x s z : last x (rcons s z) = z.
Proof. by rewrite -cats1 last_cat. Qed.
Lemma belast_cat x s1 s2 :
belast x (s1 ++ s2) = belast x s1 ++ belast (last x s1) s2.
Proof. by elim: s1 x => [|y s1 IHs] x //=; rewrite IHs. Qed.
Lemma belast_rcons x s z : belast x (rcons s z) = x :: s.
Proof. by rewrite lastI -!cats1 belast_cat. Qed.
Lemma cat_rcons x s1 s2 : rcons s1 x ++ s2 = s1 ++ x :: s2.
Proof. by rewrite -cats1 -catA. Qed.
Lemma rcons_cat x s1 s2 : rcons (s1 ++ s2) x = s1 ++ rcons s2 x.
Proof. by rewrite -!cats1 catA. Qed.
Variant last_spec : seq T -> Type :=
| LastNil : last_spec [::]
| LastRcons s x : last_spec (rcons s x).
Lemma lastP s : last_spec s.
Proof. case: s => [|x s]; [left | rewrite lastI; right]. Qed.
Lemma last_ind P :
P [::] -> (forall s x, P s -> P (rcons s x)) -> forall s, P s.
Proof.
move=> Hnil Hlast s; rewrite -(cat0s s).
elim: s [::] Hnil => [|x s2 IHs] s1 Hs1; first by rewrite cats0.
by rewrite -cat_rcons; apply/IHs/Hlast.
Qed.
(* Sequence indexing. *)
Fixpoint nth s n {struct n} :=
if s is x :: s' then if n is n'.+1 then @nth s' n' else x else x0.
Fixpoint set_nth s n y {struct n} :=
if s is x :: s' then if n is n'.+1 then x :: @set_nth s' n' y else y :: s'
else ncons n x0 [:: y].
Lemma nth0 s : nth s 0 = head s. Proof. by []. Qed.
Lemma nth_default s n : size s <= n -> nth s n = x0.
Proof. by elim: s n => [|x s IHs] []. Qed.
Lemma if_nth s b n : b || (size s <= n) ->
(if b then nth s n else x0) = nth s n.
Proof. by case: leqP; case: ifP => //= *; rewrite nth_default. Qed.
Lemma nth_nil n : nth [::] n = x0.
Proof. by case: n. Qed.
Lemma nth_seq1 n x : nth [:: x] n = if n == 0 then x else x0.
Proof. by case: n => [|[]]. Qed.
Lemma last_nth x s : last x s = nth (x :: s) (size s).
Proof. by elim: s x => [|y s IHs] x /=. Qed.
Lemma nth_last s : nth s (size s).-1 = last x0 s.
Proof. by case: s => //= x s; rewrite last_nth. Qed.
Lemma nth_behead s n : nth (behead s) n = nth s n.+1.
Proof. by case: s n => [|x s] [|n]. Qed.
Lemma nth_cat s1 s2 n :
nth (s1 ++ s2) n = if n < size s1 then nth s1 n else nth s2 (n - size s1).
Proof. by elim: s1 n => [|x s1 IHs] []. Qed.
Lemma nth_rcons s x n :
nth (rcons s x) n =
if n < size s then nth s n else if n == size s then x else x0.
Proof. by elim: s n => [|y s IHs] [] //=; apply: nth_nil. Qed.
Lemma nth_rcons_default s i : nth (rcons s x0) i = nth s i.
Proof.
by rewrite nth_rcons; case: ltngtP => //[/ltnW ?|->]; rewrite nth_default.
Qed.
Lemma nth_ncons m x s n :
nth (ncons m x s) n = if n < m then x else nth s (n - m).
Proof. by elim: m n => [|m IHm] []. Qed.
Lemma nth_nseq m x n : nth (nseq m x) n = (if n < m then x else x0).
Proof. by elim: m n => [|m IHm] []. Qed.
Lemma eq_from_nth s1 s2 :
size s1 = size s2 -> (forall i, i < size s1 -> nth s1 i = nth s2 i) ->
s1 = s2.
Proof.
elim: s1 s2 => [|x1 s1 IHs1] [|x2 s2] //= [eq_sz] eq_s12.
by rewrite [x1](eq_s12 0) // (IHs1 s2) // => i; apply: (eq_s12 i.+1).
Qed.
Lemma size_set_nth s n y : size (set_nth s n y) = maxn n.+1 (size s).
Proof.
rewrite maxnC; elim: s n => [|x s IHs] [|n] //=.
- by rewrite size_ncons addn1.
- by rewrite IHs maxnSS.
Qed.
Lemma set_nth_nil n y : set_nth [::] n y = ncons n x0 [:: y].
Proof. by case: n. Qed.
Lemma nth_set_nth s n y : nth (set_nth s n y) =1 [eta nth s with n |-> y].
Proof.
elim: s n => [|x s IHs] [|n] [|m] //=; rewrite ?nth_nil ?IHs // nth_ncons eqSS.
case: ltngtP => // [lt_nm | ->]; last by rewrite subnn.
by rewrite nth_default // subn_gt0.
Qed.
Lemma set_set_nth s n1 y1 n2 y2 (s2 := set_nth s n2 y2) :
set_nth (set_nth s n1 y1) n2 y2 = if n1 == n2 then s2 else set_nth s2 n1 y1.
Proof.
have [-> | ne_n12] := eqVneq.
apply: eq_from_nth => [|i _]; first by rewrite !size_set_nth maxnA maxnn.
by do 2!rewrite !nth_set_nth /=; case: eqP.
apply: eq_from_nth => [|i _]; first by rewrite !size_set_nth maxnCA.
by do 2!rewrite !nth_set_nth /=; case: eqP => // ->; case: eqVneq ne_n12.
Qed.
(* find, count, has, all. *)
Section SeqFind.
Variable a : pred T.
Fixpoint find s := if s is x :: s' then if a x then 0 else (find s').+1 else 0.
Fixpoint filter s :=
if s is x :: s' then if a x then x :: filter s' else filter s' else [::].
Fixpoint count s := if s is x :: s' then a x + count s' else 0.
Fixpoint has s := if s is x :: s' then a x || has s' else false.
Fixpoint all s := if s is x :: s' then a x && all s' else true.
Lemma size_filter s : size (filter s) = count s.
Proof. by elim: s => //= x s <-; case (a x). Qed.
Lemma has_count s : has s = (0 < count s).
Proof. by elim: s => //= x s ->; case (a x). Qed.
Lemma size_filter_gt0 s : (size (filter s) > 0) = (has s).
Proof. by rewrite size_filter -has_count. Qed.
Lemma count_size s : count s <= size s.
Proof. by elim: s => //= x s; case: (a x); last apply: leqW. Qed.
Lemma all_count s : all s = (count s == size s).
Proof.
elim: s => //= x s; case: (a x) => _ //=.
by rewrite add0n eqn_leq andbC ltnNge count_size.
Qed.
Lemma filter_all s : all (filter s).
Proof. by elim: s => //= x s IHs; case: ifP => //= ->. Qed.
Lemma all_filterP s : reflect (filter s = s) (all s).
Proof.
apply: (iffP idP) => [| <-]; last exact: filter_all.
by elim: s => //= x s IHs /andP[-> Hs]; rewrite IHs.
Qed.
Lemma filter_id s : filter (filter s) = filter s.
Proof. by apply/all_filterP; apply: filter_all. Qed.
Lemma has_find s : has s = (find s < size s).
Proof. by elim: s => //= x s IHs; case (a x); rewrite ?leqnn. Qed.
Lemma find_size s : find s <= size s.
Proof. by elim: s => //= x s IHs; case (a x). Qed.
Lemma find_cat s1 s2 :
find (s1 ++ s2) = if has s1 then find s1 else size s1 + find s2.
Proof.
by elim: s1 => //= x s1 IHs; case: (a x) => //; rewrite IHs (fun_if succn).
Qed.
Lemma has_nil : has [::] = false. Proof. by []. Qed.
Lemma has_seq1 x : has [:: x] = a x.
Proof. exact: orbF. Qed.
Lemma has_nseq n x : has (nseq n x) = (0 < n) && a x.
Proof. by elim: n => //= n ->; apply: andKb. Qed.
Lemma has_seqb (b : bool) x : has (nseq b x) = b && a x.
Proof. by rewrite has_nseq lt0b. Qed.
Lemma all_nil : all [::] = true. Proof. by []. Qed.
Lemma all_seq1 x : all [:: x] = a x.
Proof. exact: andbT. Qed.
Lemma all_nseq n x : all (nseq n x) = (n == 0) || a x.
Proof. by elim: n => //= n ->; apply: orKb. Qed.
Lemma all_nseqb (b : bool) x : all (nseq b x) = b ==> a x.
Proof. by rewrite all_nseq eqb0 implybE. Qed.
Lemma filter_nseq n x : filter (nseq n x) = nseq (a x * n) x.
Proof. by elim: n => /= [|n ->]; case: (a x). Qed.
Lemma count_nseq n x : count (nseq n x) = a x * n.
Proof. by rewrite -size_filter filter_nseq size_nseq. Qed.
Lemma find_nseq n x : find (nseq n x) = ~~ a x * n.
Proof. by elim: n => /= [|n ->]; case: (a x). Qed.
Lemma nth_find s : has s -> a (nth s (find s)).
Proof. by elim: s => //= x s IHs; case a_x: (a x). Qed.
Lemma before_find s i : i < find s -> a (nth s i) = false.
Proof. by elim: s i => //= x s IHs; case: ifP => // a'x [|i] // /(IHs i). Qed.
Lemma hasNfind s : ~~ has s -> find s = size s.
Proof. by rewrite has_find; case: ltngtP (find_size s). Qed.
Lemma filter_cat s1 s2 : filter (s1 ++ s2) = filter s1 ++ filter s2.
Proof. by elim: s1 => //= x s1 ->; case (a x). Qed.
Lemma filter_rcons s x :
filter (rcons s x) = if a x then rcons (filter s) x else filter s.
Proof. by rewrite -!cats1 filter_cat /=; case (a x); rewrite /= ?cats0. Qed.
Lemma count_cat s1 s2 : count (s1 ++ s2) = count s1 + count s2.
Proof. by rewrite -!size_filter filter_cat size_cat. Qed.
Lemma has_cat s1 s2 : has (s1 ++ s2) = has s1 || has s2.
Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs orbA. Qed.
Lemma has_rcons s x : has (rcons s x) = a x || has s.
Proof. by rewrite -cats1 has_cat has_seq1 orbC. Qed.
Lemma all_cat s1 s2 : all (s1 ++ s2) = all s1 && all s2.
Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs andbA. Qed.
Lemma all_rcons s x : all (rcons s x) = a x && all s.
Proof. by rewrite -cats1 all_cat all_seq1 andbC. Qed.
End SeqFind.
Lemma find_pred0 s : find pred0 s = size s. Proof. by []. Qed.
Lemma find_predT s : find predT s = 0.
Proof. by case: s. Qed.
Lemma eq_find a1 a2 : a1 =1 a2 -> find a1 =1 find a2.
Proof. by move=> Ea; elim=> //= x s IHs; rewrite Ea IHs. Qed.
Lemma eq_filter a1 a2 : a1 =1 a2 -> filter a1 =1 filter a2.
Proof. by move=> Ea; elim=> //= x s IHs; rewrite Ea IHs. Qed.
Lemma eq_count a1 a2 : a1 =1 a2 -> count a1 =1 count a2.
Proof. by move=> Ea s; rewrite -!size_filter (eq_filter Ea). Qed.
Lemma eq_has a1 a2 : a1 =1 a2 -> has a1 =1 has a2.
Proof. by move=> Ea s; rewrite !has_count (eq_count Ea). Qed.
Lemma eq_all a1 a2 : a1 =1 a2 -> all a1 =1 all a2.
Proof. by move=> Ea s; rewrite !all_count (eq_count Ea). Qed.
Lemma all_filter (p q : pred T) xs :
all p (filter q xs) = all [pred i | q i ==> p i] xs.
Proof. by elim: xs => //= x xs <-; case: (q x). Qed.
Section SubPred.
Variable (a1 a2 : pred T).
Hypothesis s12 : subpred a1 a2.
Lemma sub_find s : find a2 s <= find a1 s.
Proof. by elim: s => //= x s IHs; case: ifP => // /(contraFF (@s12 x))->. Qed.
Lemma sub_has s : has a1 s -> has a2 s.
Proof. by rewrite !has_find; apply: leq_ltn_trans (sub_find s). Qed.
Lemma sub_count s : count a1 s <= count a2 s.
Proof.
by elim: s => //= x s; apply: leq_add; case a1x: (a1 x); rewrite // s12.
Qed.
Lemma sub_all s : all a1 s -> all a2 s.
Proof.
by rewrite !all_count !eqn_leq !count_size => /leq_trans-> //; apply: sub_count.
Qed.
End SubPred.
Lemma filter_pred0 s : filter pred0 s = [::]. Proof. by elim: s. Qed.
Lemma filter_predT s : filter predT s = s.
Proof. by elim: s => //= x s ->. Qed.
Lemma filter_predI a1 a2 s : filter (predI a1 a2) s = filter a1 (filter a2 s).
Proof. by elim: s => //= x s ->; rewrite andbC; case: (a2 x). Qed.
Lemma count_pred0 s : count pred0 s = 0.
Proof. by rewrite -size_filter filter_pred0. Qed.
Lemma count_predT s : count predT s = size s.
Proof. by rewrite -size_filter filter_predT. Qed.
Lemma count_predUI a1 a2 s :
count (predU a1 a2) s + count (predI a1 a2) s = count a1 s + count a2 s.
Proof.
elim: s => //= x s IHs; rewrite /= addnACA [RHS]addnACA IHs.
by case: (a1 x) => //; rewrite addn0.
Qed.
Lemma count_predC a s : count a s + count (predC a) s = size s.
Proof. by elim: s => //= x s IHs; rewrite addnACA IHs; case: (a _). Qed.
Lemma count_filter a1 a2 s : count a1 (filter a2 s) = count (predI a1 a2) s.
Proof. by rewrite -!size_filter filter_predI. Qed.
Lemma has_pred0 s : has pred0 s = false.
Proof. by rewrite has_count count_pred0. Qed.
Lemma has_predT s : has predT s = (0 < size s).
Proof. by rewrite has_count count_predT. Qed.
Lemma has_predC a s : has (predC a) s = ~~ all a s.
Proof. by elim: s => //= x s ->; case (a x). Qed.
Lemma has_predU a1 a2 s : has (predU a1 a2) s = has a1 s || has a2 s.
Proof. by elim: s => //= x s ->; rewrite -!orbA; do !bool_congr. Qed.
Lemma all_pred0 s : all pred0 s = (size s == 0).
Proof. by rewrite all_count count_pred0 eq_sym. Qed.
Lemma all_predT s : all predT s.
Proof. by rewrite all_count count_predT. Qed.
Lemma allT (a : pred T) s : (forall x, a x) -> all a s.
Proof. by move/eq_all->; apply/all_predT. Qed.
Lemma all_predC a s : all (predC a) s = ~~ has a s.
Proof. by elim: s => //= x s ->; case (a x). Qed.
Lemma all_predI a1 a2 s : all (predI a1 a2) s = all a1 s && all a2 s.
Proof.
apply: (can_inj negbK); rewrite negb_and -!has_predC -has_predU.
by apply: eq_has => x; rewrite /= negb_and.
Qed.
(* Surgery: drop, take, rot, rotr. *)
Fixpoint drop n s {struct s} :=
match s, n with
| _ :: s', n'.+1 => drop n' s'
| _, _ => s
end.
Lemma drop_behead : drop n0 =1 iter n0 behead.
Proof. by elim: n0 => [|n IHn] [|x s] //; rewrite iterSr -IHn. Qed.
Lemma drop0 s : drop 0 s = s. Proof. by case: s. Qed.
Lemma drop1 : drop 1 =1 behead. Proof. by case=> [|x [|y s]]. Qed.
Lemma drop_oversize n s : size s <= n -> drop n s = [::].
Proof. by elim: s n => [|x s IHs] []. Qed.
Lemma drop_size s : drop (size s) s = [::].
Proof. by rewrite drop_oversize // leqnn. Qed.
Lemma drop_cons x s :
drop n0 (x :: s) = if n0 is n.+1 then drop n s else x :: s.
Proof. by []. Qed.
Lemma size_drop s : size (drop n0 s) = size s - n0.
Proof. by elim: s n0 => [|x s IHs] []. Qed.
Lemma drop_cat s1 s2 :
drop n0 (s1 ++ s2) =
if n0 < size s1 then drop n0 s1 ++ s2 else drop (n0 - size s1) s2.
Proof. by elim: s1 n0 => [|x s1 IHs] []. Qed.
Lemma drop_size_cat n s1 s2 : size s1 = n -> drop n (s1 ++ s2) = s2.
Proof. by move <-; elim: s1 => //=; rewrite drop0. Qed.
Lemma nconsK n x : cancel (ncons n x) (drop n).
Proof. by elim: n => // -[]. Qed.
Lemma drop_drop s n1 n2 : drop n1 (drop n2 s) = drop (n1 + n2) s.
Proof. by elim: s n2 => // x s ihs [|n2]; rewrite ?drop0 ?addn0 ?addnS /=. Qed.
Fixpoint take n s {struct s} :=
match s, n with
| x :: s', n'.+1 => x :: take n' s'
| _, _ => [::]
end.
Lemma take0 s : take 0 s = [::]. Proof. by case: s. Qed.
Lemma take_oversize n s : size s <= n -> take n s = s.
Proof. by elim: s n => [|x s IHs] [|n] //= /IHs->. Qed.
Lemma take_size s : take (size s) s = s.
Proof. exact: take_oversize. Qed.
Lemma take_cons x s :
take n0 (x :: s) = if n0 is n.+1 then x :: (take n s) else [::].
Proof. by []. Qed.
Lemma drop_rcons s : n0 <= size s ->
forall x, drop n0 (rcons s x) = rcons (drop n0 s) x.
Proof. by elim: s n0 => [|y s IHs] []. Qed.
Lemma cat_take_drop s : take n0 s ++ drop n0 s = s.
Proof. by elim: s n0 => [|x s IHs] [|n] //=; rewrite IHs. Qed.
Lemma size_takel s : n0 <= size s -> size (take n0 s) = n0.
Proof.
by move/subKn; rewrite -size_drop -[in size s](cat_take_drop s) size_cat addnK.
Qed.
Lemma size_take s : size (take n0 s) = if n0 < size s then n0 else size s.
Proof.
have [le_sn | lt_ns] := leqP (size s) n0; first by rewrite take_oversize.
by rewrite size_takel // ltnW.
Qed.
Lemma size_take_min s : size (take n0 s) = minn n0 (size s).
Proof. exact: size_take. Qed.
Lemma take_cat s1 s2 :
take n0 (s1 ++ s2) =
if n0 < size s1 then take n0 s1 else s1 ++ take (n0 - size s1) s2.
Proof.
elim: s1 n0 => [|x s1 IHs] [|n] //=.
by rewrite ltnS subSS -(fun_if (cons x)) -IHs.
Qed.
Lemma take_size_cat n s1 s2 : size s1 = n -> take n (s1 ++ s2) = s1.
Proof. by move <-; elim: s1 => [|x s1 IHs]; rewrite ?take0 //= IHs. Qed.
Lemma takel_cat s1 s2 : n0 <= size s1 -> take n0 (s1 ++ s2) = take n0 s1.
Proof.
by rewrite take_cat; case: ltngtP => // ->; rewrite subnn take0 take_size cats0.
Qed.
Lemma nth_drop s i : nth (drop n0 s) i = nth s (n0 + i).
Proof.
rewrite -[s in RHS]cat_take_drop nth_cat size_take ltnNge.
case: ltnP => [?|le_s_n0]; rewrite ?(leq_trans le_s_n0) ?leq_addr ?addKn //=.
by rewrite drop_oversize // !nth_default.
Qed.
Lemma find_ltn p s i : has p (take i s) -> find p s < i.
Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs. Qed.
Lemma has_take p s i : has p s -> has p (take i s) = (find p s < i).
Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs ->. Qed.
Lemma has_take_leq (p : pred T) (s : seq T) i : i <= size s ->
has p (take i s) = (find p s < i).
Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs ->. Qed.
Lemma nth_take i : i < n0 -> forall s, nth (take n0 s) i = nth s i.
Proof.
move=> lt_i_n0 s; case lt_n0_s: (n0 < size s).
by rewrite -[s in RHS]cat_take_drop nth_cat size_take lt_n0_s /= lt_i_n0.
by rewrite -[s in LHS]cats0 take_cat lt_n0_s /= cats0.
Qed.
Lemma take_min i j s : take (minn i j) s = take i (take j s).
Proof. by elim: s i j => //= a l IH [|i] [|j] //=; rewrite minnSS IH. Qed.
Lemma take_takel i j s : i <= j -> take i (take j s) = take i s.
Proof. by move=> ?; rewrite -take_min (minn_idPl _). Qed.
Lemma take_taker i j s : j <= i -> take i (take j s) = take j s.
Proof. by move=> ?; rewrite -take_min (minn_idPr _). Qed.
Lemma take_drop i j s : take i (drop j s) = drop j (take (i + j) s).
Proof. by rewrite addnC; elim: s i j => // x s IHs [|i] [|j] /=. Qed.
Lemma takeD i j s : take (i + j) s = take i s ++ take j (drop i s).
Proof.
elim: i j s => [|i IHi] [|j] [|a s] //; first by rewrite take0 addn0 cats0.
by rewrite addSn /= IHi.
Qed.
Lemma takeC i j s : take i (take j s) = take j (take i s).
Proof. by rewrite -!take_min minnC. Qed.
Lemma take_nseq i j x : i <= j -> take i (nseq j x) = nseq i x.
Proof. by move=>/subnKC <-; rewrite nseqD take_size_cat // size_nseq. Qed.
Lemma drop_nseq i j x : drop i (nseq j x) = nseq (j - i) x.
Proof.
case: (leqP i j) => [/subnKC {1}<-|/ltnW j_le_i].
by rewrite nseqD drop_size_cat // size_nseq.
by rewrite drop_oversize ?size_nseq // (eqP j_le_i).
Qed.
(* drop_nth and take_nth below do NOT use the default n0, because the "n" *)
(* can be inferred from the condition, whereas the nth default value x0 *)
(* will have to be given explicitly (and this will provide "d" as well). *)
Lemma drop_nth n s : n < size s -> drop n s = nth s n :: drop n.+1 s.
Proof. by elim: s n => [|x s IHs] [|n] Hn //=; rewrite ?drop0 1?IHs. Qed.
Lemma take_nth n s : n < size s -> take n.+1 s = rcons (take n s) (nth s n).
Proof. by elim: s n => [|x s IHs] //= [|n] Hn /=; rewrite ?take0 -?IHs. Qed.
(* Rotation *)
Definition rot n s := drop n s ++ take n s.
Lemma rot0 s : rot 0 s = s.
Proof. by rewrite /rot drop0 take0 cats0. Qed.
Lemma size_rot s : size (rot n0 s) = size s.
Proof. by rewrite -[s in RHS]cat_take_drop /rot !size_cat addnC. Qed.
Lemma rot_oversize n s : size s <= n -> rot n s = s.
Proof. by move=> le_s_n; rewrite /rot take_oversize ?drop_oversize. Qed.
Lemma rot_size s : rot (size s) s = s.
Proof. exact: rot_oversize. Qed.
Lemma has_rot s a : has a (rot n0 s) = has a s.
Proof. by rewrite has_cat orbC -has_cat cat_take_drop. Qed.
Lemma rot_size_cat s1 s2 : rot (size s1) (s1 ++ s2) = s2 ++ s1.
Proof. by rewrite /rot take_size_cat ?drop_size_cat. Qed.
Definition rotr n s := rot (size s - n) s.
Lemma rotK : cancel (rot n0) (rotr n0).
Proof.
move=> s; rewrite /rotr size_rot -size_drop {2}/rot.
by rewrite rot_size_cat cat_take_drop.
Qed.
Lemma rot_inj : injective (rot n0). Proof. exact (can_inj rotK). Qed.
(* (efficient) reversal *)
Fixpoint catrev s1 s2 := if s1 is x :: s1' then catrev s1' (x :: s2) else s2.
Definition rev s := catrev s [::].
Lemma catrev_catl s t u : catrev (s ++ t) u = catrev t (catrev s u).
Proof. by elim: s u => /=. Qed.
Lemma catrev_catr s t u : catrev s (t ++ u) = catrev s t ++ u.
Proof. by elim: s t => //= x s IHs t; rewrite -IHs. Qed.
Lemma catrevE s t : catrev s t = rev s ++ t.
Proof. by rewrite -catrev_catr. Qed.
Lemma rev_cons x s : rev (x :: s) = rcons (rev s) x.
Proof. by rewrite -cats1 -catrevE. Qed.
Lemma size_rev s : size (rev s) = size s.
Proof. by elim: s => // x s IHs; rewrite rev_cons size_rcons IHs. Qed.
Lemma rev_nilp s : nilp (rev s) = nilp s.
Proof. by rewrite /nilp size_rev. Qed.
Lemma rev_cat s t : rev (s ++ t) = rev t ++ rev s.
Proof. by rewrite -catrev_catr -catrev_catl. Qed.
Lemma rev_rcons s x : rev (rcons s x) = x :: rev s.
Proof. by rewrite -cats1 rev_cat. Qed.
Lemma revK : involutive rev.
Proof. by elim=> //= x s IHs; rewrite rev_cons rev_rcons IHs. Qed.
Lemma nth_rev n s : n < size s -> nth (rev s) n = nth s (size s - n.+1).
Proof.
elim/last_ind: s => // s x IHs in n *.
rewrite rev_rcons size_rcons ltnS subSS -cats1 nth_cat /=.
case: n => [|n] lt_n_s; first by rewrite subn0 ltnn subnn.
by rewrite subnSK //= leq_subr IHs.
Qed.
Lemma filter_rev a s : filter a (rev s) = rev (filter a s).
Proof. by elim: s => //= x s IH; rewrite fun_if !rev_cons filter_rcons IH. Qed.
Lemma count_rev a s : count a (rev s) = count a s.
Proof. by rewrite -!size_filter filter_rev size_rev. Qed.
Lemma has_rev a s : has a (rev s) = has a s.
Proof. by rewrite !has_count count_rev. Qed.
Lemma all_rev a s : all a (rev s) = all a s.
Proof. by rewrite !all_count count_rev size_rev. Qed.
Lemma rev_nseq n x : rev (nseq n x) = nseq n x.
Proof. by elim: n => // n IHn; rewrite -[in LHS]addn1 nseqD rev_cat IHn. Qed.
End Sequences.
Prenex Implicits size ncons nseq head ohead behead last rcons belast.
Arguments seqn {T} n.
Prenex Implicits cat take drop rot rotr catrev.
Prenex Implicits find count nth all has filter.
Arguments rev {T} s : simpl never.
Arguments nth : simpl nomatch.
Arguments set_nth : simpl nomatch.
Arguments take : simpl nomatch.
Arguments drop : simpl nomatch.
Arguments nilP {T s}.
Arguments all_filterP {T a s}.
Arguments rotK n0 {T} s : rename.
Arguments rot_inj {n0 T} [s1 s2] eq_rot_s12 : rename.
Arguments revK {T} s : rename.
Notation count_mem x := (count (pred_of_simpl (pred1 x))).
Infix "++" := cat : seq_scope.
Notation "[ 'seq' x <- s | C ]" := (filter (fun x => C%B) s)
(x at level 99,
format "[ '[hv' 'seq' x <- s '/ ' | C ] ']'") : seq_scope.
Notation "[ 'seq' x <- s | C1 & C2 ]" := [seq x <- s | C1 && C2]
(format "[ '[hv' 'seq' x <- s '/ ' | C1 '/ ' & C2 ] ']'") : seq_scope.
Notation "[ 'seq' ' x <- s | C ]" := (filter (fun x => C%B) s)
(x strict pattern,
format "[ '[hv' 'seq' ' x <- s '/ ' | C ] ']'") : seq_scope.
Notation "[ 'seq' ' x <- s | C1 & C2 ]" := [seq x <- s | C1 && C2]
(x strict pattern,
format "[ '[hv' 'seq' ' x <- s '/ ' | C1 '/ ' & C2 ] ']'") : seq_scope.
Notation "[ 'seq' x : T <- s | C ]" := (filter (fun x : T => C%B) s)
(only parsing).
Notation "[ 'seq' x : T <- s | C1 & C2 ]" := [seq x : T <- s | C1 && C2]
(only parsing).
(* Double induction/recursion. *)
Lemma seq_ind2 {S T} (P : seq S -> seq T -> Type) :
P [::] [::] ->
(forall x y s t, size s = size t -> P s t -> P (x :: s) (y :: t)) ->
forall s t, size s = size t -> P s t.
Proof.
by move=> Pnil Pcons; elim=> [|x s IHs] [|y t] //= [eq_sz]; apply/Pcons/IHs.
Qed.
Section AllIff.
(* The Following Are Equivalent *)
(* We introduce a specific conjunction, used to chain the consecutive *)
(* items in a circular list of implications *)
Inductive all_iff_and (P Q : Prop) : Prop := AllIffConj of P & Q.
Definition all_iff (P0 : Prop) (Ps : seq Prop) : Prop :=
let fix loop (P : Prop) (Qs : seq Prop) : Prop :=
if Qs is Q :: Qs then all_iff_and (P -> Q) (loop Q Qs) else P -> P0 in
loop P0 Ps.
Lemma all_iffLR P0 Ps : all_iff P0 Ps ->
forall m n, nth P0 (P0 :: Ps) m -> nth P0 (P0 :: Ps) n.
Proof.
move=> iffPs; have PsS n: nth P0 Ps n -> nth P0 Ps n.+1.
elim: n P0 Ps iffPs => [|n IHn] P0 [|P [|Q Ps]] //= [iP0P] //; first by case.
by rewrite nth_nil.
by case=> iPQ iffPs; apply: IHn; split=> // /iP0P.
have{PsS} lePs: {homo nth P0 Ps : m n / m <= n >-> (m -> n)}.
by move=> m n /subnK<-; elim: {n}(n - m) => // n IHn /IHn; apply: PsS.
move=> m n P_m; have{m P_m} hP0: P0.
case: m P_m => //= m /(lePs m _ (leq_maxl m (size Ps))).
by rewrite nth_default ?leq_maxr.
case: n =>// n; apply: lePs 0 n (leq0n n) _.
by case: Ps iffPs hP0 => // P Ps [].
Qed.
Lemma all_iffP P0 Ps :
all_iff P0 Ps -> forall m n, nth P0 (P0 :: Ps) m <-> nth P0 (P0 :: Ps) n.
Proof. by move=> /all_iffLR-iffPs m n; split => /iffPs. Qed.
End AllIff.
Arguments all_iffLR {P0 Ps}.
Arguments all_iffP {P0 Ps}.
Coercion all_iffP : all_iff >-> Funclass.
(* This means "the following are all equivalent: P0, ... Pn" *)
Notation "[ '<->' P0 ; P1 ; .. ; Pn ]" :=
(all_iff P0 (@cons Prop P1 (.. (@cons Prop Pn nil) ..))) : form_scope.
Ltac tfae := do !apply: AllIffConj.
Section FindSpec.
Variable (T : Type) (a : {pred T}) (s : seq T).
Variant find_spec : bool -> nat -> Type :=
| NotFound of ~~ has a s : find_spec false (size s)
| Found (i : nat) of i < size s & (forall x0, a (nth x0 s i)) &
(forall x0 j, j < i -> a (nth x0 s j) = false) : find_spec true i.
Lemma findP : find_spec (has a s) (find a s).
Proof.
have [a_s|aNs] := boolP (has a s); last by rewrite hasNfind//; constructor.
by constructor=> [|x0|x0]; rewrite -?has_find ?nth_find//; apply: before_find.
Qed.
End FindSpec.
Arguments findP {T}.
Section RotRcons.
Variable T : Type.
Implicit Types (x : T) (s : seq T).
Lemma rot1_cons x s : rot 1 (x :: s) = rcons s x.
Proof. by rewrite /rot /= take0 drop0 -cats1. Qed.
Lemma rcons_inj s1 s2 x1 x2 :
rcons s1 x1 = rcons s2 x2 :> seq T -> (s1, x1) = (s2, x2).
Proof. by rewrite -!rot1_cons => /rot_inj[-> ->]. Qed.
Lemma rcons_injl x : injective (rcons^~ x).
Proof. by move=> s1 s2 /rcons_inj[]. Qed.
Lemma rcons_injr s : injective (rcons s).
Proof. by move=> x1 x2 /rcons_inj[]. Qed.
End RotRcons.
Arguments rcons_inj {T s1 x1 s2 x2} eq_rcons : rename.
Arguments rcons_injl {T} x [s1 s2] eq_rcons : rename.
Arguments rcons_injr {T} s [x1 x2] eq_rcons : rename.
(* Equality and eqType for seq. *)
Section EqSeq.
Variables (n0 : nat) (T : eqType) (x0 : T).
Local Notation nth := (nth x0).
Implicit Types (x y z : T) (s : seq T).
Fixpoint eqseq s1 s2 {struct s2} :=
match s1, s2 with
| [::], [::] => true
| x1 :: s1', x2 :: s2' => (x1 == x2) && eqseq s1' s2'
| _, _ => false
end.
Lemma eqseqP : Equality.axiom eqseq.
Proof.
move; elim=> [|x1 s1 IHs] [|x2 s2]; do [by constructor | simpl].
have [<-|neqx] := x1 =P x2; last by right; case.
by apply: (iffP (IHs s2)) => [<-|[]].
Qed.
HB.instance Definition _ := hasDecEq.Build (seq T) eqseqP.
Lemma eqseqE : eqseq = eq_op. Proof. by []. Qed.
Lemma eqseq_cons x1 x2 s1 s2 :
(x1 :: s1 == x2 :: s2) = (x1 == x2) && (s1 == s2).
Proof. by []. Qed.
Lemma eqseq_cat s1 s2 s3 s4 :
size s1 = size s2 -> (s1 ++ s3 == s2 ++ s4) = (s1 == s2) && (s3 == s4).
Proof.
elim: s1 s2 => [|x1 s1 IHs] [|x2 s2] //= [sz12].
by rewrite !eqseq_cons -andbA IHs.
Qed.
Lemma eqseq_rcons s1 s2 x1 x2 :
(rcons s1 x1 == rcons s2 x2) = (s1 == s2) && (x1 == x2).
Proof. by rewrite -(can_eq revK) !rev_rcons eqseq_cons andbC (can_eq revK). Qed.
Lemma size_eq0 s : (size s == 0) = (s == [::]).
Proof. exact: (sameP nilP eqP). Qed.
Lemma nilpE s : nilp s = (s == [::]). Proof. by case: s. Qed.
Lemma has_filter a s : has a s = (filter a s != [::]).
Proof. by rewrite -size_eq0 size_filter has_count lt0n. Qed.
(* mem_seq and index. *)
(* mem_seq defines a predType for seq. *)
Fixpoint mem_seq (s : seq T) :=
if s is y :: s' then xpredU1 y (mem_seq s') else xpred0.
Definition seq_eqclass := seq T.
Identity Coercion seq_of_eqclass : seq_eqclass >-> seq.
Coercion pred_of_seq (s : seq_eqclass) : {pred T} := mem_seq s.
Canonical seq_predType := PredType (pred_of_seq : seq T -> pred T).
(* The line below makes mem_seq a canonical instance of topred. *)
Canonical mem_seq_predType := PredType mem_seq.
Lemma in_cons y s x : (x \in y :: s) = (x == y) || (x \in s).
Proof. by []. Qed.
Lemma in_nil x : (x \in [::]) = false.
Proof. by []. Qed.
Lemma mem_seq1 x y : (x \in [:: y]) = (x == y).
Proof. by rewrite in_cons orbF. Qed.
(* to be repeated after the Section discharge. *)
Let inE := (mem_seq1, in_cons, inE).
Lemma forall_cons {P : T -> Prop} {a s} :
{in a::s, forall x, P x} <-> P a /\ {in s, forall x, P x}.
Proof.
split=> [A|[A B]]; last by move => x /predU1P [-> //|]; apply: B.
by split=> [|b Hb]; apply: A; rewrite !inE ?eqxx ?Hb ?orbT.
Qed.
Lemma exists_cons {P : T -> Prop} {a s} :
(exists2 x, x \in a::s & P x) <-> P a \/ exists2 x, x \in s & P x.
Proof.
split=> [[x /predU1P[->|x_s] Px]|]; [by left| by right; exists x|].
by move=> [?|[x x_s ?]]; [exists a|exists x]; rewrite ?inE ?eqxx ?x_s ?orbT.
Qed.
Lemma mem_seq2 x y z : (x \in [:: y; z]) = xpred2 y z x.
Proof. by rewrite !inE. Qed.
Lemma mem_seq3 x y z t : (x \in [:: y; z; t]) = xpred3 y z t x.
Proof. by rewrite !inE. Qed.
Lemma mem_seq4 x y z t u : (x \in [:: y; z; t; u]) = xpred4 y z t u x.
Proof. by rewrite !inE. Qed.
Lemma mem_cat x s1 s2 : (x \in s1 ++ s2) = (x \in s1) || (x \in s2).
Proof. by elim: s1 => //= y s1 IHs; rewrite !inE /= -orbA -IHs. Qed.
Lemma mem_rcons s y : rcons s y =i y :: s.
Proof. by move=> x; rewrite -cats1 /= mem_cat mem_seq1 orbC in_cons. Qed.
Lemma mem_head x s : x \in x :: s.
Proof. exact: predU1l. Qed.
Lemma mem_last x s : last x s \in x :: s.
Proof. by rewrite lastI mem_rcons mem_head. Qed.
Lemma mem_behead s : {subset behead s <= s}.
Proof. by case: s => // y s x; apply: predU1r. Qed.
Lemma mem_belast s y : {subset belast y s <= y :: s}.
Proof. by move=> x ys'x; rewrite lastI mem_rcons mem_behead. Qed.
Lemma mem_nth s n : n < size s -> nth s n \in s.
Proof.
by elim: s n => // x s IHs [_|n sz_s]; rewrite ?mem_head // mem_behead ?IHs.
Qed.
Lemma mem_take s x : x \in take n0 s -> x \in s.
Proof. by move=> s0x; rewrite -(cat_take_drop n0 s) mem_cat /= s0x. Qed.
Lemma mem_drop s x : x \in drop n0 s -> x \in s.
Proof. by move=> s0'x; rewrite -(cat_take_drop n0 s) mem_cat /= s0'x orbT. Qed.
Lemma last_eq s z x y : x != y -> z != y -> (last x s == y) = (last z s == y).
Proof. by move=> /negPf xz /negPf yz; case: s => [|t s]//; rewrite xz yz. Qed.
Section Filters.
Implicit Type a : pred T.
Lemma hasP {a s} : reflect (exists2 x, x \in s & a x) (has a s).
Proof.
elim: s => [|y s IHs] /=; first by right; case.
exact: equivP (orPP idP IHs) (iff_sym exists_cons).
Qed.
Lemma allP {a s} : reflect {in s, forall x, a x} (all a s).
Proof.
elim: s => [|/= y s IHs]; first by left.
exact: equivP (andPP idP IHs) (iff_sym forall_cons).
Qed.
Lemma hasPn a s : reflect {in s, forall x, ~~ a x} (~~ has a s).
Proof. by rewrite -all_predC; apply: allP. Qed.
Lemma allPn a s : reflect (exists2 x, x \in s & ~~ a x) (~~ all a s).
Proof. by rewrite -has_predC; apply: hasP. Qed.
Lemma allss s : all [in s] s. Proof. exact/allP. Qed.
Lemma mem_filter a x s : (x \in filter a s) = a x && (x \in s).
Proof.
rewrite andbC; elim: s => //= y s IHs.
rewrite (fun_if (fun s' : seq T => x \in s')) !in_cons {}IHs.
by case: eqP => [->|_]; case (a y); rewrite /= ?andbF.
Qed.
Variables (a : pred T) (s : seq T) (A : T -> Prop).
Hypothesis aP : forall x, reflect (A x) (a x).
Lemma hasPP : reflect (exists2 x, x \in s & A x) (has a s).
Proof. by apply: (iffP hasP) => -[x ? /aP]; exists x. Qed.
Lemma allPP : reflect {in s, forall x, A x} (all a s).
Proof. by apply: (iffP allP) => a_s x /a_s/aP. Qed.
End Filters.
Section EqIn.
Variables a1 a2 : pred T.
Lemma eq_in_filter s : {in s, a1 =1 a2} -> filter a1 s = filter a2 s.
Proof. by elim: s => //= x s IHs /forall_cons [-> /IHs ->]. Qed.
Lemma eq_in_find s : {in s, a1 =1 a2} -> find a1 s = find a2 s.
Proof. by elim: s => //= x s IHs /forall_cons [-> /IHs ->]. Qed.
Lemma eq_in_count s : {in s, a1 =1 a2} -> count a1 s = count a2 s.
Proof. by move/eq_in_filter=> eq_a12; rewrite -!size_filter eq_a12. Qed.
Lemma eq_in_all s : {in s, a1 =1 a2} -> all a1 s = all a2 s.
Proof. by move=> eq_a12; rewrite !all_count eq_in_count. Qed.
Lemma eq_in_has s : {in s, a1 =1 a2} -> has a1 s = has a2 s.
Proof. by move/eq_in_filter=> eq_a12; rewrite !has_filter eq_a12. Qed.
End EqIn.
Lemma eq_has_r s1 s2 : s1 =i s2 -> has^~ s1 =1 has^~ s2.
Proof.
by move=> Es a; apply/hasP/hasP=> -[x sx ax]; exists x; rewrite ?Es in sx *.
Qed.
Lemma eq_all_r s1 s2 : s1 =i s2 -> all^~ s1 =1 all^~ s2.
Proof. by move=> Es a; apply/negb_inj; rewrite -!has_predC (eq_has_r Es). Qed.
Lemma has_sym s1 s2 : has [in s1] s2 = has [in s2] s1.
Proof. by apply/hasP/hasP=> -[x]; exists x. Qed.
Lemma has_pred1 x s : has (pred1 x) s = (x \in s).
Proof. by rewrite -(eq_has (mem_seq1^~ x)) (has_sym [:: x]) /= orbF. Qed.
Lemma mem_rev s : rev s =i s.
Proof. by move=> a; rewrite -!has_pred1 has_rev. Qed.
(* Constant sequences, i.e., the image of nseq. *)
Definition constant s := if s is x :: s' then all (pred1 x) s' else true.
Lemma all_pred1P x s : reflect (s = nseq (size s) x) (all (pred1 x) s).
Proof.
elim: s => [|y s IHs] /=; first by left.
case: eqP => [->{y} | ne_xy]; last by right=> [] [? _]; case ne_xy.
by apply: (iffP IHs) => [<- //| []].
Qed.
Lemma all_pred1_constant x s : all (pred1 x) s -> constant s.
Proof. by case: s => //= y s /andP[/eqP->]. Qed.
Lemma all_pred1_nseq x n : all (pred1 x) (nseq n x).
Proof. by rewrite all_nseq /= eqxx orbT. Qed.
Lemma mem_nseq n x y : (y \in nseq n x) = (0 < n) && (y == x).
Proof. by rewrite -has_pred1 has_nseq eq_sym. Qed.
Lemma nseqP n x y : reflect (y = x /\ n > 0) (y \in nseq n x).
Proof. by rewrite mem_nseq andbC; apply: (iffP andP) => -[/eqP]. Qed.
Lemma constant_nseq n x : constant (nseq n x).
Proof. exact: all_pred1_constant (all_pred1_nseq x n). Qed.
(* Uses x0 *)
Lemma constantP s : reflect (exists x, s = nseq (size s) x) (constant s).
Proof.
apply: (iffP idP) => [| [x ->]]; last exact: constant_nseq.
case: s => [|x s] /=; first by exists x0.
by move/all_pred1P=> def_s; exists x; rewrite -def_s.
Qed.
(* Duplicate-freenes. *)
Fixpoint uniq s := if s is x :: s' then (x \notin s') && uniq s' else true.
Lemma cons_uniq x s : uniq (x :: s) = (x \notin s) && uniq s.
Proof. by []. Qed.
Lemma cat_uniq s1 s2 :
uniq (s1 ++ s2) = [&& uniq s1, ~~ has [in s1] s2 & uniq s2].
Proof.
elim: s1 => [|x s1 IHs]; first by rewrite /= has_pred0.
by rewrite has_sym /= mem_cat !negb_or has_sym IHs -!andbA; do !bool_congr.
Qed.
Lemma uniq_catC s1 s2 : uniq (s1 ++ s2) = uniq (s2 ++ s1).
Proof. by rewrite !cat_uniq has_sym andbCA andbA andbC. Qed.
Lemma uniq_catCA s1 s2 s3 : uniq (s1 ++ s2 ++ s3) = uniq (s2 ++ s1 ++ s3).
Proof.
by rewrite !catA -!(uniq_catC s3) !(cat_uniq s3) uniq_catC !has_cat orbC.
Qed.
Lemma rcons_uniq s x : uniq (rcons s x) = (x \notin s) && uniq s.
Proof. by rewrite -cats1 uniq_catC. Qed.
Lemma filter_uniq s a : uniq s -> uniq (filter a s).
Proof.
elim: s => //= x s IHs /andP[s'x]; case: ifP => //= a_x /IHs->.
by rewrite mem_filter a_x s'x.
Qed.
Lemma rot_uniq s : uniq (rot n0 s) = uniq s.
Proof. by rewrite /rot uniq_catC cat_take_drop. Qed.
Lemma rev_uniq s : uniq (rev s) = uniq s.
Proof.
elim: s => // x s IHs.
by rewrite rev_cons -cats1 cat_uniq /= andbT andbC mem_rev orbF IHs.
Qed.
Lemma count_memPn x s : reflect (count_mem x s = 0) (x \notin s).
Proof. by rewrite -has_pred1 has_count -eqn0Ngt; apply: eqP. Qed.
Lemma count_uniq_mem s x : uniq s -> count_mem x s = (x \in s).
Proof.
elim: s => //= y s IHs /andP[/negbTE s'y /IHs-> {IHs}].
by rewrite in_cons; case: (eqVneq y x) => // <-; rewrite s'y.
Qed.
Lemma leq_uniq_countP x s1 s2 : uniq s1 ->
reflect (x \in s1 -> x \in s2) (count_mem x s1 <= count_mem x s2).
Proof.
move/count_uniq_mem->; case: (boolP (_ \in _)) => //= _; last by constructor.
by rewrite -has_pred1 has_count; apply: (iffP idP) => //; apply.
Qed.
Lemma leq_uniq_count s1 s2 : uniq s1 -> {subset s1 <= s2} ->
(forall x, count_mem x s1 <= count_mem x s2).
Proof. by move=> s1_uniq s1_s2 x; apply/leq_uniq_countP/s1_s2. Qed.
Lemma filter_pred1_uniq s x : uniq s -> x \in s -> filter (pred1 x) s = [:: x].
Proof.
move=> uniq_s s_x; rewrite (all_pred1P _ _ (filter_all _ _)).
by rewrite size_filter count_uniq_mem ?s_x.
Qed.
(* Removing duplicates *)
Fixpoint undup s :=
if s is x :: s' then if x \in s' then undup s' else x :: undup s' else [::].
Lemma size_undup s : size (undup s) <= size s.
Proof. by elim: s => //= x s IHs; case: (x \in s) => //=; apply: ltnW. Qed.
Lemma mem_undup s : undup s =i s.
Proof.
move=> x; elim: s => //= y s IHs.
by case s_y: (y \in s); rewrite !inE IHs //; case: eqP => [->|].
Qed.
Lemma undup_uniq s : uniq (undup s).
Proof.
by elim: s => //= x s IHs; case s_x: (x \in s); rewrite //= mem_undup s_x.
Qed.
Lemma undup_id s : uniq s -> undup s = s.
Proof. by elim: s => //= x s IHs /andP[/negbTE-> /IHs->]. Qed.
Lemma ltn_size_undup s : (size (undup s) < size s) = ~~ uniq s.
Proof.
by elim: s => //= x s IHs; case s_x: (x \in s); rewrite //= ltnS size_undup.
Qed.
Lemma filter_undup p s : filter p (undup s) = undup (filter p s).
Proof.
elim: s => //= x s IHs; rewrite (fun_if undup) [_ = _]fun_if /= mem_filter /=.
by rewrite (fun_if (filter p)) /= IHs; case: ifP => -> //=; apply: if_same.
Qed.
Lemma undup_nil s : undup s = [::] -> s = [::].
Proof. by case: s => //= x s; rewrite -mem_undup; case: ifP; case: undup. Qed.
Lemma undup_cat s t :
undup (s ++ t) = [seq x <- undup s | x \notin t] ++ undup t.
Proof. by elim: s => //= x s ->; rewrite mem_cat; do 2 case: in_mem => //=. Qed.
Lemma undup_rcons s x : undup (rcons s x) = rcons [seq y <- undup s | y != x] x.
Proof.
by rewrite -!cats1 undup_cat; congr cat; apply: eq_filter => y; rewrite inE.
Qed.
Lemma count_undup s p : count p (undup s) <= count p s.
Proof. by rewrite -!size_filter filter_undup size_undup. Qed.
Lemma has_undup p s : has p (undup s) = has p s.
Proof. by apply: eq_has_r => x; rewrite mem_undup. Qed.
Lemma all_undup p s : all p (undup s) = all p s.
Proof. by apply: eq_all_r => x; rewrite mem_undup. Qed.
(* Lookup *)
Definition index x := find (pred1 x).
Lemma index_size x s : index x s <= size s.
Proof. by rewrite /index find_size. Qed.
Lemma index_mem x s : (index x s < size s) = (x \in s).
Proof. by rewrite -has_pred1 has_find. Qed.
Lemma memNindex x s : x \notin s -> index x s = size s.
Proof. by rewrite -has_pred1 => /hasNfind. Qed.
Lemma nth_index x s : x \in s -> nth s (index x s) = x.
Proof. by rewrite -has_pred1 => /(nth_find x0)/eqP. Qed.
Lemma index_inj s : {in s &, injective (index ^~ s)}.
Proof.
by move=> x y x_s y_s eidx; rewrite -(nth_index x_s) eidx nth_index.
Qed.
Lemma index_cat x s1 s2 :
index x (s1 ++ s2) = if x \in s1 then index x s1 else size s1 + index x s2.
Proof. by rewrite /index find_cat has_pred1. Qed.
Lemma index_ltn x s i : x \in take i s -> index x s < i.
Proof. by rewrite -has_pred1; apply: find_ltn. Qed.
Lemma in_take x s i : x \in s -> (x \in take i s) = (index x s < i).
Proof. by rewrite -?has_pred1; apply: has_take. Qed.
Lemma in_take_leq x s i : i <= size s -> (x \in take i s) = (index x s < i).
Proof. by rewrite -?has_pred1; apply: has_take_leq. Qed.
Lemma index_nth i s : i < size s -> index (nth s i) s <= i.
Proof.
move=> lti; rewrite -ltnS index_ltn// -(@nth_take i.+1)// mem_nth // size_take.
by case: ifP.
Qed.
Lemma nthK s: uniq s -> {in gtn (size s), cancel (nth s) (index^~ s)}.
Proof.
elim: s => //= x s IHs /andP[s'x Us] i; rewrite inE ltnS eq_sym -if_neg.
by case: i => /= [_|i lt_i_s]; rewrite ?eqxx ?IHs ?(memPn s'x) ?mem_nth.
Qed.
Lemma index_uniq i s : i < size s -> uniq s -> index (nth s i) s = i.
Proof. by move/nthK. Qed.
Lemma index_head x s : index x (x :: s) = 0.
Proof. by rewrite /= eqxx. Qed.
Lemma index_last x s : uniq (x :: s) -> index (last x s) (x :: s) = size s.
Proof.
rewrite lastI rcons_uniq -cats1 index_cat size_belast.
by case: ifP => //=; rewrite eqxx addn0.
Qed.
Lemma nth_uniq s i j :
i < size s -> j < size s -> uniq s -> (nth s i == nth s j) = (i == j).
Proof. by move=> lti ltj /nthK/can_in_eq->. Qed.
Lemma uniqPn s :
reflect (exists i j, [/\ i < j, j < size s & nth s i = nth s j]) (~~ uniq s).
Proof.
apply: (iffP idP) => [|[i [j [ltij ltjs]]]]; last first.
by apply: contra_eqN => Us; rewrite nth_uniq ?ltn_eqF // (ltn_trans ltij).
elim: s => // x s IHs /nandP[/negbNE | /IHs[i [j]]]; last by exists i.+1, j.+1.
by exists 0, (index x s).+1; rewrite !ltnS index_mem /= nth_index.
Qed.
Lemma uniqP s : reflect {in gtn (size s) &, injective (nth s)} (uniq s).
Proof.
apply: (iffP idP) => [/nthK/can_in_inj// | nth_inj].
apply/uniqPn => -[i [j [ltij ltjs /nth_inj/eqP/idPn]]].
by rewrite !inE (ltn_trans ltij ltjs) ltn_eqF //=; case.
Qed.
Lemma mem_rot s : rot n0 s =i s.
Proof. by move=> x; rewrite -[s in RHS](cat_take_drop n0) !mem_cat /= orbC. Qed.
Lemma eqseq_rot s1 s2 : (rot n0 s1 == rot n0 s2) = (s1 == s2).
Proof. exact/inj_eq/rot_inj. Qed.
Lemma drop_index s (n := index x0 s) : x0 \in s -> drop n s = x0 :: drop n.+1 s.
Proof. by move=> xs; rewrite (drop_nth x0) ?index_mem ?nth_index. Qed.
(* lemmas about the pivot pattern [_ ++ _ :: _] *)
Lemma index_pivot x s1 s2 (s := s1 ++ x :: s2) : x \notin s1 ->
index x s = size s1.
Proof. by rewrite index_cat/= eqxx addn0; case: ifPn. Qed.
Lemma take_pivot x s2 s1 (s := s1 ++ x :: s2) : x \notin s1 ->
take (index x s) s = s1.
Proof. by move=> /index_pivot->; rewrite take_size_cat. Qed.
Lemma rev_pivot x s1 s2 : rev (s1 ++ x :: s2) = rev s2 ++ x :: rev s1.
Proof. by rewrite rev_cat rev_cons cat_rcons. Qed.
Lemma eqseq_pivot2l x s1 s2 s3 s4 : x \notin s1 -> x \notin s3 ->
(s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4).
Proof.
move=> xNs1 xNs3; apply/idP/idP => [E|/andP[/eqP-> /eqP->]//].
suff S : size s1 = size s3 by rewrite eqseq_cat// eqseq_cons eqxx in E.
by rewrite -(index_pivot s2 xNs1) (eqP E) index_pivot.
Qed.
Lemma eqseq_pivot2r x s1 s2 s3 s4 : x \notin s2 -> x \notin s4 ->
(s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4).
Proof.
move=> xNs2 xNs4; rewrite -(can_eq revK) !rev_pivot.
by rewrite eqseq_pivot2l ?mem_rev // !(can_eq revK) andbC.
Qed.
Lemma eqseq_pivotl x s1 s2 s3 s4 : x \notin s1 -> x \notin s2 ->
(s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4).
Proof.
move=> xNs1 xNs2; apply/idP/idP => [E|/andP[/eqP-> /eqP->]//].
rewrite -(@eqseq_pivot2l x)//; have /eqP/(congr1 (count_mem x)) := E.
rewrite !count_cat/= eqxx !addnS (count_memPn _ _ xNs1) (count_memPn _ _ xNs2).
by move=> -[/esym/eqP]; rewrite addn_eq0 => /andP[/eqP/count_memPn].
Qed.
Lemma eqseq_pivotr x s1 s2 s3 s4 : x \notin s3 -> x \notin s4 ->
(s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4).
Proof. by move=> *; rewrite eq_sym eqseq_pivotl//; case: eqVneq => /=. Qed.
Lemma uniq_eqseq_pivotl x s1 s2 s3 s4 : uniq (s1 ++ x :: s2) ->
(s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4).
Proof.
by rewrite uniq_catC/= mem_cat => /andP[/norP[? ?] _]; rewrite eqseq_pivotl.
Qed.
Lemma uniq_eqseq_pivotr x s1 s2 s3 s4 : uniq (s3 ++ x :: s4) ->
(s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4).
Proof. by move=> ?; rewrite eq_sym uniq_eqseq_pivotl//; case: eqVneq => /=. Qed.
End EqSeq.
Arguments eqseq : simpl nomatch.
Notation "'has_ view" := (hasPP _ (fun _ => view))
(at level 4, right associativity, format "''has_' view").
Notation "'all_ view" := (allPP _ (fun _ => view))
(at level 4, right associativity, format "''all_' view").
Section RotIndex.
Variables (T : eqType).
Implicit Types x y z : T.
Lemma rot_index s x (i := index x s) : x \in s ->
rot i s = x :: (drop i.+1 s ++ take i s).
Proof. by move=> x_s; rewrite /rot drop_index. Qed.
Variant rot_to_spec s x := RotToSpec i s' of rot i s = x :: s'.
Lemma rot_to s x : x \in s -> rot_to_spec s x.
Proof. by move=> /rot_index /RotToSpec. Qed.
End RotIndex.
Definition inE := (mem_seq1, in_cons, inE).
Prenex Implicits mem_seq1 constant uniq undup index.
Arguments eqseq {T} !_ !_.
Arguments pred_of_seq {T} s x /.
Arguments eqseqP {T x y}.
Arguments hasP {T a s}.
Arguments hasPn {T a s}.
Arguments allP {T a s}.
Arguments allPn {T a s}.
Arguments nseqP {T n x y}.
Arguments count_memPn {T x s}.
Arguments uniqPn {T} x0 {s}.
Arguments uniqP {T} x0 {s}.
Arguments forall_cons {T P a s}.
Arguments exists_cons {T P a s}.
(* Since both `all [in s] s`, `all (mem s) s`, and `all (pred_of_seq s) s` *)
(* may appear in goals, the following hint has to be declared using the *)
(* `Hint Extern` command. Additionally, `mem` and `pred_of_seq` in the above *)
(* terms do not reduce to each other; thus, stating `allss` in the form of *)
(* one of them makes `apply: allss` fail for the other case. Since both `mem` *)
(* and `pred_of_seq` reduce to `mem_seq`, the following explicit type *)
(* annotation for `allss` makes it work for both cases. *)
#[export] Hint Extern 0 (is_true (all _ _)) =>
apply: (allss : forall T s, all (mem_seq s) s) : core.
Section NthTheory.
Lemma nthP (T : eqType) (s : seq T) x x0 :
reflect (exists2 i, i < size s & nth x0 s i = x) (x \in s).
Proof.
apply: (iffP idP) => [|[n Hn <-]]; last exact: mem_nth.
by exists (index x s); [rewrite index_mem | apply nth_index].
Qed.
Variable T : Type.
Implicit Types (a : pred T) (x : T).
Lemma has_nthP a s x0 :
reflect (exists2 i, i < size s & a (nth x0 s i)) (has a s).
Proof.
elim: s => [|x s IHs] /=; first by right; case.
case nax: (a x); first by left; exists 0.
by apply: (iffP IHs) => [[i]|[[|i]]]; [exists i.+1 | rewrite nax | exists i].
Qed.
Lemma all_nthP a s x0 :
reflect (forall i, i < size s -> a (nth x0 s i)) (all a s).
Proof.
rewrite -(eq_all (fun x => negbK (a x))) all_predC.
case: (has_nthP _ _ x0) => [na_s | a_s]; [right=> a_s | left=> i lti].
by case: na_s => i lti; rewrite a_s.
by apply/idPn=> na_si; case: a_s; exists i.
Qed.
Lemma set_nthE s x0 n x :
set_nth x0 s n x = if n < size s
then take n s ++ x :: drop n.+1 s
else s ++ ncons (n - size s) x0 [:: x].
Proof.
elim: s n => [|a s IH] n /=; first by rewrite subn0 set_nth_nil.
case: n => [|n]; first by rewrite drop0.
by rewrite ltnS /=; case: ltnP (IH n) => _ ->.
Qed.
Lemma count_set_nth a s x0 n x :
count a (set_nth x0 s n x) =
count a s + a x - a (nth x0 s n) * (n < size s) + (a x0) * (n - size s).
Proof.
rewrite set_nthE; case: ltnP => [nlts|nges]; last first.
rewrite -cat_nseq !count_cat count_nseq /=.
by rewrite muln0 addn0 subn0 addnAC addnA.
have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW.
rewrite -[in count a s](cat_take_drop n s) [drop n s](drop_nth x0)//.
by rewrite !count_cat/= muln1 muln0 addn0 addnAC !addnA [in RHS]addnAC addnK.
Qed.
Lemma count_set_nth_ltn a s x0 n x : n < size s ->
count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n).
Proof.
move=> nlts; rewrite count_set_nth nlts muln1.
have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW.
by rewrite muln0 addn0.
Qed.
Lemma count_set_nthF a s x0 n x : ~~ a x0 ->
count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n).
Proof.
move=> /negbTE ax0; rewrite count_set_nth ax0 mul0n addn0.
case: ltnP => [_|nges]; first by rewrite muln1.
by rewrite nth_default// ax0 subn0.
Qed.
End NthTheory.
Lemma set_nth_default T s (y0 x0 : T) n : n < size s -> nth x0 s n = nth y0 s n.
Proof. by elim: s n => [|y s' IHs] [|n] //= /IHs. Qed.
Lemma headI T s (x : T) : rcons s x = head x s :: behead (rcons s x).
Proof. by case: s. Qed.
Arguments nthP {T s x}.
Arguments has_nthP {T a s}.
Arguments all_nthP {T a s}.
Definition bitseq := seq bool.
#[hnf] HB.instance Definition _ := Equality.on bitseq.
Canonical bitseq_predType := Eval hnf in [predType of bitseq].
(* Generalizations of splitP (from path.v): split_find_nth and split_find *)
Section FindNth.
Variables (T : Type).
Implicit Types (x : T) (p : pred T) (s : seq T).
Variant split_find_nth_spec p : seq T -> seq T -> seq T -> T -> Type :=
FindNth x s1 s2 of p x & ~~ has p s1 :
split_find_nth_spec p (rcons s1 x ++ s2) s1 s2 x.
Lemma split_find_nth x0 p s (i := find p s) :
has p s -> split_find_nth_spec p s (take i s) (drop i.+1 s) (nth x0 s i).
Proof.
move=> p_s; rewrite -[X in split_find_nth_spec _ X](cat_take_drop i s).
rewrite (drop_nth x0 _) -?has_find// -cat_rcons.
by constructor; [apply: nth_find | rewrite has_take -?leqNgt].
Qed.
Variant split_find_spec p : seq T -> seq T -> seq T -> Type :=
FindSplit x s1 s2 of p x & ~~ has p s1 :
split_find_spec p (rcons s1 x ++ s2) s1 s2.
Lemma split_find p s (i := find p s) :
has p s -> split_find_spec p s (take i s) (drop i.+1 s).
Proof.
by case: s => // x ? in i * => ?; case: split_find_nth => //; constructor.
Qed.
Lemma nth_rcons_cat_find x0 p s1 s2 x (s := rcons s1 x ++ s2) :
p x -> ~~ has p s1 -> nth x0 s (find p s) = x.
Proof.
move=> pz pNs1; rewrite /s cat_rcons find_cat (negPf pNs1).
by rewrite nth_cat/= pz addn0 subnn ltnn.
Qed.
End FindNth.
(* Incrementing the ith nat in a seq nat, padding with 0's if needed. This *)
(* allows us to use nat seqs as bags of nats. *)
Fixpoint incr_nth v i {struct i} :=
if v is n :: v' then if i is i'.+1 then n :: incr_nth v' i' else n.+1 :: v'
else ncons i 0 [:: 1].
Arguments incr_nth : simpl nomatch.
Lemma nth_incr_nth v i j : nth 0 (incr_nth v i) j = (i == j) + nth 0 v j.
Proof.
elim: v i j => [|n v IHv] [|i] [|j] //=; rewrite ?eqSS ?addn0 //; try by case j.
elim: i j => [|i IHv] [|j] //=; rewrite ?eqSS //; by case j.
Qed.
Lemma size_incr_nth v i :
size (incr_nth v i) = if i < size v then size v else i.+1.
Proof.
elim: v i => [|n v IHv] [|i] //=; first by rewrite size_ncons /= addn1.
by rewrite IHv; apply: fun_if.
Qed.
Lemma incr_nth_inj v : injective (incr_nth v).
Proof.
move=> i j /(congr1 (nth 0 ^~ i)); apply: contra_eq => neq_ij.
by rewrite !nth_incr_nth eqn_add2r eqxx /nat_of_bool ifN_eqC.
Qed.
Lemma incr_nthC v i j :
incr_nth (incr_nth v i) j = incr_nth (incr_nth v j) i.
Proof.
apply: (@eq_from_nth _ 0) => [|k _]; last by rewrite !nth_incr_nth addnCA.
by do !rewrite size_incr_nth leqNgt if_neg -/(maxn _ _); apply: maxnAC.
Qed.
(* Equality up to permutation *)
Section PermSeq.
Variable T : eqType.
Implicit Type s : seq T.
Definition perm_eq s1 s2 :=
all [pred x | count_mem x s1 == count_mem x s2] (s1 ++ s2).
Lemma permP s1 s2 : reflect (count^~ s1 =1 count^~ s2) (perm_eq s1 s2).
Proof.
apply: (iffP allP) => /= [eq_cnt1 a | eq_cnt x _]; last exact/eqP.
have [n le_an] := ubnP (count a (s1 ++ s2)); elim: n => // n IHn in a le_an *.
have [/eqP|] := posnP (count a (s1 ++ s2)).
by rewrite count_cat addn_eq0; do 2!case: eqP => // ->.
rewrite -has_count => /hasP[x s12x a_x]; pose a' := predD1 a x.
have cnt_a' s: count a s = count_mem x s + count a' s.
rewrite -count_predUI -[LHS]addn0 -(count_pred0 s).
by congr (_ + _); apply: eq_count => y /=; case: eqP => // ->.
rewrite !cnt_a' (eqnP (eq_cnt1 _ s12x)) (IHn a') // -ltnS.
apply: leq_trans le_an.
by rewrite ltnS cnt_a' -add1n leq_add2r -has_count has_pred1.
Qed.
Lemma perm_refl s : perm_eq s s.
Proof. exact/permP. Qed.
Hint Resolve perm_refl : core.
Lemma perm_sym : symmetric perm_eq.
Proof. by move=> s1 s2; apply/permP/permP=> eq_s12 a. Qed.
Lemma perm_trans : transitive perm_eq.
Proof. by move=> s2 s1 s3 /permP-eq12 /permP/(ftrans eq12)/permP. Qed.
Notation perm_eql s1 s2 := (perm_eq s1 =1 perm_eq s2).
Notation perm_eqr s1 s2 := (perm_eq^~ s1 =1 perm_eq^~ s2).
Lemma permEl s1 s2 : perm_eql s1 s2 -> perm_eq s1 s2. Proof. by move->. Qed.
Lemma permPl s1 s2 : reflect (perm_eql s1 s2) (perm_eq s1 s2).
Proof.
apply: (iffP idP) => [eq12 s3 | -> //]; apply/idP/idP; last exact: perm_trans.
by rewrite -!(perm_sym s3) => /perm_trans; apply.
Qed.
Lemma permPr s1 s2 : reflect (perm_eqr s1 s2) (perm_eq s1 s2).
Proof.
by apply/(iffP idP) => [/permPl eq12 s3| <- //]; rewrite !(perm_sym s3) eq12.
Qed.
Lemma perm_catC s1 s2 : perm_eql (s1 ++ s2) (s2 ++ s1).
Proof. by apply/permPl/permP=> a; rewrite !count_cat addnC. Qed.
Lemma perm_cat2l s1 s2 s3 : perm_eq (s1 ++ s2) (s1 ++ s3) = perm_eq s2 s3.
Proof.
apply/permP/permP=> eq23 a; apply/eqP;
by move/(_ a)/eqP: eq23; rewrite !count_cat eqn_add2l.
Qed.
Lemma perm_catl s t1 t2 : perm_eq t1 t2 -> perm_eql (s ++ t1) (s ++ t2).
Proof. by move=> eq_t12; apply/permPl; rewrite perm_cat2l. Qed.
Lemma perm_cons x s1 s2 : perm_eq (x :: s1) (x :: s2) = perm_eq s1 s2.
Proof. exact: (perm_cat2l [::x]). Qed.
Lemma perm_cat2r s1 s2 s3 : perm_eq (s2 ++ s1) (s3 ++ s1) = perm_eq s2 s3.
Proof. by do 2!rewrite perm_sym perm_catC; apply: perm_cat2l. Qed.
Lemma perm_catr s1 s2 t : perm_eq s1 s2 -> perm_eql (s1 ++ t) (s2 ++ t).
Proof. by move=> eq_s12; apply/permPl; rewrite perm_cat2r. Qed.
Lemma perm_cat s1 s2 t1 t2 :
perm_eq s1 s2 -> perm_eq t1 t2 -> perm_eq (s1 ++ t1) (s2 ++ t2).
Proof. by move=> /perm_catr-> /perm_catl->. Qed.
Lemma perm_catAC s1 s2 s3 : perm_eql ((s1 ++ s2) ++ s3) ((s1 ++ s3) ++ s2).
Proof. by apply/permPl; rewrite -!catA perm_cat2l perm_catC. Qed.
Lemma perm_catCA s1 s2 s3 : perm_eql (s1 ++ s2 ++ s3) (s2 ++ s1 ++ s3).
Proof. by apply/permPl; rewrite !catA perm_cat2r perm_catC. Qed.
Lemma perm_catACA s1 s2 s3 s4 :
perm_eql ((s1 ++ s2) ++ (s3 ++ s4)) ((s1 ++ s3) ++ (s2 ++ s4)).
Proof. by apply/permPl; rewrite perm_catAC !catA perm_catAC. Qed.
Lemma perm_rcons x s : perm_eql (rcons s x) (x :: s).
Proof. by move=> /= s2; rewrite -cats1 perm_catC. Qed.
Lemma perm_rot n s : perm_eql (rot n s) s.
Proof. by move=> /= s2; rewrite perm_catC cat_take_drop. Qed.
Lemma perm_rotr n s : perm_eql (rotr n s) s.
Proof. exact: perm_rot. Qed.
Lemma perm_rev s : perm_eql (rev s) s.
Proof. by apply/permPl/permP=> i; rewrite count_rev. Qed.
Lemma perm_filter s1 s2 a :
perm_eq s1 s2 -> perm_eq (filter a s1) (filter a s2).
Proof. by move/permP=> s12_count; apply/permP=> Q; rewrite !count_filter. Qed.
Lemma perm_filterC a s : perm_eql (filter a s ++ filter (predC a) s) s.
Proof.
apply/permPl; elim: s => //= x s IHs.
by case: (a x); last rewrite /= -cat1s perm_catCA; rewrite perm_cons.
Qed.
Lemma perm_size s1 s2 : perm_eq s1 s2 -> size s1 = size s2.
Proof. by move/permP=> eq12; rewrite -!count_predT eq12. Qed.
Lemma perm_mem s1 s2 : perm_eq s1 s2 -> s1 =i s2.
Proof. by move/permP=> eq12 x; rewrite -!has_pred1 !has_count eq12. Qed.
Lemma perm_nilP s : reflect (s = [::]) (perm_eq s [::]).
Proof. by apply: (iffP idP) => [/perm_size/eqP/nilP | ->]. Qed.
Lemma perm_consP x s t :
reflect (exists i u, rot i t = x :: u /\ perm_eq u s)
(perm_eq t (x :: s)).
Proof.
apply: (iffP idP) => [eq_txs | [i [u [Dt eq_us]]]].
have /rot_to[i u Dt]: x \in t by rewrite (perm_mem eq_txs) mem_head.
by exists i, u; rewrite -(perm_cons x) -Dt perm_rot.
by rewrite -(perm_rot i) Dt perm_cons.
Qed.
Lemma perm_has s1 s2 a : perm_eq s1 s2 -> has a s1 = has a s2.
Proof. by move/perm_mem/eq_has_r. Qed.
Lemma perm_all s1 s2 a : perm_eq s1 s2 -> all a s1 = all a s2.
Proof. by move/perm_mem/eq_all_r. Qed.
Lemma perm_small_eq s1 s2 : size s2 <= 1 -> perm_eq s1 s2 -> s1 = s2.
Proof.
move=> s2_le1 eqs12; move/perm_size: eqs12 s2_le1 (perm_mem eqs12).
by case: s2 s1 => [|x []] // [|y []] // _ _ /(_ x) /[!(inE, eqxx)] /eqP->.
Qed.
Lemma uniq_leq_size s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s1 <= size s2.
Proof.
elim: s1 s2 => //= x s1 IHs s2 /andP[not_s1x Us1] /forall_cons[s2x ss12].
have [i s3 def_s2] := rot_to s2x; rewrite -(size_rot i s2) def_s2.
apply: IHs => // y s1y; have:= ss12 y s1y.
by rewrite -(mem_rot i) def_s2 inE (negPf (memPn _ y s1y)).
Qed.
Lemma leq_size_uniq s1 s2 :
uniq s1 -> {subset s1 <= s2} -> size s2 <= size s1 -> uniq s2.
Proof.
elim: s1 s2 => [[] | x s1 IHs s2] // Us1x; have /andP[not_s1x Us1] := Us1x.
case/forall_cons => /rot_to[i s3 def_s2] ss12 le_s21.
rewrite -(rot_uniq i) -(size_rot i) def_s2 /= in le_s21 *.
have ss13 y (s1y : y \in s1): y \in s3.
by have:= ss12 y s1y; rewrite -(mem_rot i) def_s2 inE (negPf (memPn _ y s1y)).
rewrite IHs // andbT; apply: contraL _ le_s21 => s3x; rewrite -leqNgt.
by apply/(uniq_leq_size Us1x)/allP; rewrite /= s3x; apply/allP.
Qed.
Lemma uniq_size_uniq s1 s2 :
uniq s1 -> s1 =i s2 -> uniq s2 = (size s2 == size s1).
Proof.
move=> Us1 eqs12; apply/idP/idP=> [Us2 | /eqP eq_sz12].
by rewrite eqn_leq !uniq_leq_size // => y; rewrite eqs12.
by apply: (leq_size_uniq Us1) => [y|]; rewrite (eqs12, eq_sz12).
Qed.
Lemma uniq_min_size s1 s2 :
uniq s1 -> {subset s1 <= s2} -> size s2 <= size s1 ->
(size s1 = size s2) * (s1 =i s2).
Proof.
move=> Us1 ss12 le_s21; have Us2: uniq s2 := leq_size_uniq Us1 ss12 le_s21.
suffices: s1 =i s2 by split; first by apply/eqP; rewrite -uniq_size_uniq.
move=> x; apply/idP/idP=> [/ss12// | s2x]; apply: contraLR le_s21 => not_s1x.
rewrite -ltnNge (@uniq_leq_size (x :: s1)) /= ?not_s1x //.
by apply/allP; rewrite /= s2x; apply/allP.
Qed.
Lemma eq_uniq s1 s2 : size s1 = size s2 -> s1 =i s2 -> uniq s1 = uniq s2.
Proof.
move=> eq_sz12 eq_s12.
by apply/idP/idP=> Us; rewrite (uniq_size_uniq Us) ?eq_sz12 ?eqxx.
Qed.
Lemma perm_uniq s1 s2 : perm_eq s1 s2 -> uniq s1 = uniq s2.
Proof. by move=> eq_s12; apply/eq_uniq; [apply/perm_size | apply/perm_mem]. Qed.
Lemma uniq_perm s1 s2 : uniq s1 -> uniq s2 -> s1 =i s2 -> perm_eq s1 s2.
Proof.
move=> Us1 Us2 eq12; apply/allP=> x _; apply/eqP.
by rewrite !count_uniq_mem ?eq12.
Qed.
Lemma perm_undup s1 s2 : s1 =i s2 -> perm_eq (undup s1) (undup s2).
Proof.
by move=> Es12; rewrite uniq_perm ?undup_uniq // => s; rewrite !mem_undup.
Qed.
Lemma count_mem_uniq s : (forall x, count_mem x s = (x \in s)) -> uniq s.
Proof.
move=> count1_s; have Uus := undup_uniq s.
suffices: perm_eq s (undup s) by move/perm_uniq->.
by apply/allP=> x _; apply/eqP; rewrite (count_uniq_mem x Uus) mem_undup.
Qed.
Lemma eq_count_undup a s1 s2 :
{in a, s1 =i s2} -> count a (undup s1) = count a (undup s2).
Proof.
move=> s1_eq_s2; rewrite -!size_filter !filter_undup.
apply/perm_size/perm_undup => x.
by rewrite !mem_filter; case: (boolP (a x)) => //= /s1_eq_s2.
Qed.
Lemma catCA_perm_ind P :
(forall s1 s2 s3, P (s1 ++ s2 ++ s3) -> P (s2 ++ s1 ++ s3)) ->
(forall s1 s2, perm_eq s1 s2 -> P s1 -> P s2).
Proof.
move=> PcatCA s1 s2 eq_s12; rewrite -[s1]cats0 -[s2]cats0.
elim: s2 nil => [|x s2 IHs] s3 in s1 eq_s12 *.
by case: s1 {eq_s12}(perm_size eq_s12).
have /rot_to[i s' def_s1]: x \in s1 by rewrite (perm_mem eq_s12) mem_head.
rewrite -(cat_take_drop i s1) -catA => /PcatCA.
rewrite catA -/(rot i s1) def_s1 /= -cat1s => /PcatCA/IHs/PcatCA; apply.
by rewrite -(perm_cons x) -def_s1 perm_rot.
Qed.
Lemma catCA_perm_subst R F :
(forall s1 s2 s3, F (s1 ++ s2 ++ s3) = F (s2 ++ s1 ++ s3) :> R) ->
(forall s1 s2, perm_eq s1 s2 -> F s1 = F s2).
Proof.
move=> FcatCA s1 s2 /catCA_perm_ind => ind_s12.
by apply: (ind_s12 (eq _ \o F)) => //= *; rewrite FcatCA.
Qed.
End PermSeq.
Notation perm_eql s1 s2 := (perm_eq s1 =1 perm_eq s2).
Notation perm_eqr s1 s2 := (perm_eq^~ s1 =1 perm_eq^~ s2).
Arguments permP {T s1 s2}.
Arguments permPl {T s1 s2}.
Arguments permPr {T s1 s2}.
Prenex Implicits perm_eq.
#[global] Hint Resolve perm_refl : core.
Section RotrLemmas.
Variables (n0 : nat) (T : Type) (T' : eqType).
Implicit Types (x : T) (s : seq T).
Lemma size_rotr s : size (rotr n0 s) = size s.
Proof. by rewrite size_rot. Qed.
Lemma mem_rotr (s : seq T') : rotr n0 s =i s.
Proof. by move=> x; rewrite mem_rot. Qed.
Lemma rotr_size_cat s1 s2 : rotr (size s2) (s1 ++ s2) = s2 ++ s1.
Proof. by rewrite /rotr size_cat addnK rot_size_cat. Qed.
Lemma rotr1_rcons x s : rotr 1 (rcons s x) = x :: s.
Proof. by rewrite -rot1_cons rotK. Qed.
Lemma has_rotr a s : has a (rotr n0 s) = has a s.
Proof. by rewrite has_rot. Qed.
Lemma rotr_uniq (s : seq T') : uniq (rotr n0 s) = uniq s.
Proof. by rewrite rot_uniq. Qed.
Lemma rotrK : cancel (@rotr T n0) (rot n0).
Proof.
move=> s; have [lt_n0s | ge_n0s] := ltnP n0 (size s).
by rewrite -{1}(subKn (ltnW lt_n0s)) -{1}[size s]size_rotr; apply: rotK.
by rewrite -[in RHS](rot_oversize ge_n0s) /rotr (eqnP ge_n0s) rot0.
Qed.
Lemma rotr_inj : injective (@rotr T n0).
Proof. exact (can_inj rotrK). Qed.
Lemma take_rev s : take n0 (rev s) = rev (drop (size s - n0) s).
Proof.
set m := _ - n0; rewrite -[s in LHS](cat_take_drop m) rev_cat take_cat.
rewrite size_rev size_drop -minnE minnC leq_min ltnn /m.
by have [_|/eqnP->] := ltnP; rewrite ?subnn take0 cats0.
Qed.
Lemma rev_take s : rev (take n0 s) = drop (size s - n0) (rev s).
Proof. by rewrite -[s in take _ s]revK take_rev revK size_rev. Qed.
Lemma drop_rev s : drop n0 (rev s) = rev (take (size s - n0) s).
Proof.
set m := _ - n0; rewrite -[s in LHS](cat_take_drop m) rev_cat drop_cat.
rewrite size_rev size_drop -minnE minnC leq_min ltnn /m.
by have [_|/eqnP->] := ltnP; rewrite ?take0 // subnn drop0.
Qed.
Lemma rev_drop s : rev (drop n0 s) = take (size s - n0) (rev s).
Proof. by rewrite -[s in drop _ s]revK drop_rev revK size_rev. Qed.
Lemma rev_rotr s : rev (rotr n0 s) = rot n0 (rev s).
Proof. by rewrite rev_cat -take_rev -drop_rev. Qed.
Lemma rev_rot s : rev (rot n0 s) = rotr n0 (rev s).
Proof. by apply: canLR revK _; rewrite rev_rotr revK. Qed.
End RotrLemmas.
Arguments rotrK n0 {T} s : rename.
Arguments rotr_inj {n0 T} [s1 s2] eq_rotr_s12 : rename.
Section RotCompLemmas.
Variable T : Type.
Implicit Type s : seq T.
Lemma rotD m n s : m + n <= size s -> rot (m + n) s = rot m (rot n s).
Proof.
move=> sz_s; rewrite [LHS]/rot -[take _ s](cat_take_drop n).
rewrite 5!(catA, =^~ rot_size_cat) !cat_take_drop.
by rewrite size_drop !size_takel ?leq_addl ?addnK.
Qed.
Lemma rotS n s : n < size s -> rot n.+1 s = rot 1 (rot n s).
Proof. exact: (@rotD 1). Qed.
Lemma rot_add_mod m n s : n <= size s -> m <= size s ->
rot m (rot n s) = rot (if m + n <= size s then m + n else m + n - size s) s.
Proof.
move=> Hn Hm; case: leqP => [/rotD // | /ltnW Hmn]; symmetry.
by rewrite -{2}(rotK n s) /rotr -rotD size_rot addnBA ?subnK ?addnK.
Qed.
Lemma rot_minn n s : rot n s = rot (minn n (size s)) s.
Proof.
by case: (leqP n (size s)) => // /leqW ?; rewrite rot_size rot_oversize.
Qed.
Definition rot_add s n m (k := size s) (p := minn m k + minn n k) :=
locked (if p <= k then p else p - k).
Lemma leq_rot_add n m s : rot_add s n m <= size s.
Proof.
by unlock rot_add; case: ifP; rewrite // leq_subLR leq_add // geq_minr.
Qed.
Lemma rot_addC n m s : rot_add s n m = rot_add s m n.
Proof. by unlock rot_add; rewrite ![minn n _ + _]addnC. Qed.
Lemma rot_rot_add n m s : rot m (rot n s) = rot (rot_add s n m) s.
Proof.
unlock rot_add.
by rewrite (rot_minn n) (rot_minn m) rot_add_mod ?size_rot ?geq_minr.
Qed.
Lemma rot_rot m n s : rot m (rot n s) = rot n (rot m s).
Proof. by rewrite rot_rot_add rot_addC -rot_rot_add. Qed.
Lemma rot_rotr m n s : rot m (rotr n s) = rotr n (rot m s).
Proof. by rewrite [RHS]/rotr size_rot rot_rot. Qed.
Lemma rotr_rotr m n s : rotr m (rotr n s) = rotr n (rotr m s).
Proof. by rewrite /rotr !size_rot rot_rot. Qed.
End RotCompLemmas.
Section Mask.
Variables (n0 : nat) (T : Type).
Implicit Types (m : bitseq) (s : seq T).
Fixpoint mask m s {struct m} :=
match m, s with
| b :: m', x :: s' => if b then x :: mask m' s' else mask m' s'
| _, _ => [::]
end.
Lemma mask_false s n : mask (nseq n false) s = [::].
Proof. by elim: s n => [|x s IHs] [|n] /=. Qed.
Lemma mask_true s n : size s <= n -> mask (nseq n true) s = s.
Proof. by elim: s n => [|x s IHs] [|n] //= Hn; congr (_ :: _); apply: IHs. Qed.
Lemma mask0 m : mask m [::] = [::].
Proof. by case: m. Qed.
Lemma mask0s s : mask [::] s = [::]. Proof. by []. Qed.
Lemma mask1 b x : mask [:: b] [:: x] = nseq b x.
Proof. by case: b. Qed.
Lemma mask_cons b m x s : mask (b :: m) (x :: s) = nseq b x ++ mask m s.
Proof. by case: b. Qed.
Lemma size_mask m s : size m = size s -> size (mask m s) = count id m.
Proof. by move: m s; apply: seq_ind2 => // -[] x m s /= _ ->. Qed.
Lemma mask_cat m1 m2 s1 s2 :
size m1 = size s1 -> mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2.
Proof. by move: m1 s1; apply: seq_ind2 => // -[] m1 x1 s1 /= _ ->. Qed.
Lemma mask_rcons b m x s : size m = size s ->
mask (rcons m b) (rcons s x) = mask m s ++ nseq b x.
Proof. by move=> ms; rewrite -!cats1 mask_cat//; case: b. Qed.
Lemma all_mask a m s : all a s -> all a (mask m s).
Proof. by elim: s m => [|x s IHs] [|[] m]//= /andP[ax /IHs->]; rewrite ?ax. Qed.
Lemma has_mask_cons a b m x s :
has a (mask (b :: m) (x :: s)) = b && a x || has a (mask m s).
Proof. by case: b. Qed.
Lemma has_mask a m s : has a (mask m s) -> has a s.
Proof. by apply/contraTT; rewrite -!all_predC; apply: all_mask. Qed.
Lemma rev_mask m s : size m = size s -> rev (mask m s) = mask (rev m) (rev s).
Proof.
move: m s; apply: seq_ind2 => //= b x m s eq_size_sm IH.
by case: b; rewrite !rev_cons mask_rcons ?IH ?size_rev// (cats1, cats0).
Qed.
Lemma mask_rot m s : size m = size s ->
mask (rot n0 m) (rot n0 s) = rot (count id (take n0 m)) (mask m s).
Proof.
move=> Ems; rewrite mask_cat ?size_drop ?Ems // -rot_size_cat.
by rewrite size_mask -?mask_cat ?size_take ?Ems // !cat_take_drop.
Qed.
Lemma resize_mask m s : {m1 | size m1 = size s & mask m s = mask m1 s}.
Proof.
exists (take (size s) m ++ nseq (size s - size m) false).
by elim: s m => [|x s IHs] [|b m] //=; rewrite (size_nseq, IHs).
by elim: s m => [|x s IHs] [|b m] //=; rewrite (mask_false, IHs).
Qed.
Lemma takeEmask i s : take i s = mask (nseq i true) s.
Proof. by elim: i s => [s|i IHi []// ? ?]; rewrite ?take0 //= IHi. Qed.
Lemma dropEmask i s :
drop i s = mask (nseq i false ++ nseq (size s - i) true) s.
Proof. by elim: i s => [s|? ? []//]; rewrite drop0/= mask_true// subn0. Qed.
End Mask.
Arguments mask _ !_ !_.
Section EqMask.
Variables (n0 : nat) (T : eqType).
Implicit Types (s : seq T) (m : bitseq).
Lemma mem_mask_cons x b m y s :
(x \in mask (b :: m) (y :: s)) = b && (x == y) || (x \in mask m s).
Proof. by case: b. Qed.
Lemma mem_mask x m s : x \in mask m s -> x \in s.
Proof. by rewrite -!has_pred1 => /has_mask. Qed.
Lemma in_mask x m s :
uniq s -> x \in mask m s = (x \in s) && nth false m (index x s).
Proof.
elim: s m => [|y s IHs] [|[] m]//= /andP[yNs ?]; rewrite ?in_cons ?IHs //=;
by have [->|neq_xy] //= := eqVneq; rewrite ?andbF // (negPf yNs).
Qed.
Lemma mask_uniq s : uniq s -> forall m, uniq (mask m s).
Proof.
elim: s => [|x s IHs] Uxs [|b m] //=.
case: b Uxs => //= /andP[s'x Us]; rewrite {}IHs // andbT.
by apply: contra s'x; apply: mem_mask.
Qed.
Lemma mem_mask_rot m s :
size m = size s -> mask (rot n0 m) (rot n0 s) =i mask m s.
Proof. by move=> Ems x; rewrite mask_rot // mem_rot. Qed.
End EqMask.
Section Subseq.
Variable T : eqType.
Implicit Type s : seq T.
Fixpoint subseq s1 s2 :=
if s2 is y :: s2' then
if s1 is x :: s1' then subseq (if x == y then s1' else s1) s2' else true
else s1 == [::].
Lemma sub0seq s : subseq [::] s. Proof. by case: s. Qed.
Lemma subseq0 s : subseq s [::] = (s == [::]). Proof. by []. Qed.
Lemma subseq_refl s : subseq s s.
Proof. by elim: s => //= x s IHs; rewrite eqxx. Qed.
Hint Resolve subseq_refl : core.
Lemma subseqP s1 s2 :
reflect (exists2 m, size m = size s2 & s1 = mask m s2) (subseq s1 s2).
Proof.
elim: s2 s1 => [|y s2 IHs2] [|x s1].
- by left; exists [::].
- by right=> -[m /eqP/nilP->].
- by left; exists (nseq (size s2).+1 false); rewrite ?size_nseq //= mask_false.
apply: {IHs2}(iffP (IHs2 _)) => [] [m sz_m def_s1].
by exists ((x == y) :: m); rewrite /= ?sz_m // -def_s1; case: eqP => // ->.
case: eqP => [_ | ne_xy]; last first.
by case: m def_s1 sz_m => [|[] m] //; [case | move=> -> [<-]; exists m].
pose i := index true m; have def_m_i: take i m = nseq (size (take i m)) false.
apply/all_pred1P; apply/(all_nthP true) => j.
rewrite size_take ltnNge geq_min negb_or -ltnNge => /andP[lt_j_i _].
rewrite nth_take //= -negb_add addbF -addbT -negb_eqb.
by rewrite [_ == _](before_find _ lt_j_i).
have lt_i_m: i < size m.
rewrite ltnNge; apply/negP=> le_m_i; rewrite take_oversize // in def_m_i.
by rewrite def_m_i mask_false in def_s1.
rewrite size_take lt_i_m in def_m_i.
exists (take i m ++ drop i.+1 m).
rewrite size_cat size_take size_drop lt_i_m.
by rewrite sz_m in lt_i_m *; rewrite subnKC.
rewrite {s1 def_s1}[s1](congr1 behead def_s1).
rewrite -[s2](cat_take_drop i) -[m in LHS](cat_take_drop i) {}def_m_i -cat_cons.
have sz_i_s2: size (take i s2) = i by apply: size_takel; rewrite sz_m in lt_i_m.
rewrite lastI cat_rcons !mask_cat ?size_nseq ?size_belast ?mask_false //=.
by rewrite (drop_nth true) // nth_index -?index_mem.
Qed.
Lemma mask_subseq m s : subseq (mask m s) s.
Proof. by apply/subseqP; have [m1] := resize_mask m s; exists m1. Qed.
Lemma subseq_trans : transitive subseq.
Proof.
move=> _ _ s /subseqP[m2 _ ->] /subseqP[m1 _ ->].
elim: s => [|x s IHs] in m2 m1 *; first by rewrite !mask0.
case: m1 => [|[] m1]; first by rewrite mask0.
case: m2 => [|[] m2] //; first by rewrite /= eqxx IHs.
case/subseqP: (IHs m2 m1) => m sz_m def_s; apply/subseqP.
by exists (false :: m); rewrite //= sz_m.
case/subseqP: (IHs m2 m1) => m sz_m def_s; apply/subseqP.
by exists (false :: m); rewrite //= sz_m.
Qed.
Lemma cat_subseq s1 s2 s3 s4 :
subseq s1 s3 -> subseq s2 s4 -> subseq (s1 ++ s2) (s3 ++ s4).
Proof.
case/subseqP=> m1 sz_m1 -> /subseqP [m2 sz_m2 ->]; apply/subseqP.
by exists (m1 ++ m2); rewrite ?size_cat ?mask_cat ?sz_m1 ?sz_m2.
Qed.
Lemma prefix_subseq s1 s2 : subseq s1 (s1 ++ s2).
Proof. by rewrite -[s1 in subseq s1]cats0 cat_subseq ?sub0seq. Qed.
Lemma suffix_subseq s1 s2 : subseq s2 (s1 ++ s2).
Proof. exact: cat_subseq (sub0seq s1) _. Qed.
Lemma take_subseq s i : subseq (take i s) s.
Proof. by rewrite -[s in X in subseq _ X](cat_take_drop i) prefix_subseq. Qed.
Lemma drop_subseq s i : subseq (drop i s) s.
Proof. by rewrite -[s in X in subseq _ X](cat_take_drop i) suffix_subseq. Qed.
Lemma mem_subseq s1 s2 : subseq s1 s2 -> {subset s1 <= s2}.
Proof. by case/subseqP=> m _ -> x; apply: mem_mask. Qed.
Lemma sub1seq x s : subseq [:: x] s = (x \in s).
Proof. by elim: s => //= y s /[1!inE]; case: ifP; rewrite ?sub0seq. Qed.
Lemma size_subseq s1 s2 : subseq s1 s2 -> size s1 <= size s2.
Proof. by case/subseqP=> m sz_m ->; rewrite size_mask -sz_m ?count_size. Qed.
Lemma size_subseq_leqif s1 s2 :
subseq s1 s2 -> size s1 <= size s2 ?= iff (s1 == s2).
Proof.
move=> sub12; split; first exact: size_subseq.
apply/idP/eqP=> [|-> //]; case/subseqP: sub12 => m sz_m ->{s1}.
rewrite size_mask -sz_m // -all_count -(eq_all eqb_id).
by move/(@all_pred1P _ true)->; rewrite sz_m mask_true.
Qed.
Lemma subseq_anti : antisymmetric subseq.
Proof.
move=> s1 s2 /andP[] /size_subseq_leqif /leqifP.
by case: eqP => [//|_] + /size_subseq; rewrite ltnNge => /negP.
Qed.
Lemma subseq_cons s x : subseq s (x :: s).
Proof. exact: suffix_subseq [:: x] s. Qed.
Lemma cons_subseq s1 s2 x : subseq (x :: s1) s2 -> subseq s1 s2.
Proof. exact/subseq_trans/subseq_cons. Qed.
Lemma subseq_rcons s x : subseq s (rcons s x).
Proof. by rewrite -cats1 prefix_subseq. Qed.
Lemma subseq_uniq s1 s2 : subseq s1 s2 -> uniq s2 -> uniq s1.
Proof. by case/subseqP=> m _ -> Us2; apply: mask_uniq. Qed.
Lemma take_uniq s n : uniq s -> uniq (take n s).
Proof. exact/subseq_uniq/take_subseq. Qed.
Lemma drop_uniq s n : uniq s -> uniq (drop n s).
Proof. exact/subseq_uniq/drop_subseq. Qed.
Lemma undup_subseq s : subseq (undup s) s.
Proof.
elim: s => //= x s; case: (_ \in _); last by rewrite eqxx.
by case: (undup s) => //= y u; case: (_ == _) => //=; apply: cons_subseq.
Qed.
Lemma subseq_rev s1 s2 : subseq (rev s1) (rev s2) = subseq s1 s2.
Proof.
wlog suff W : s1 s2 / subseq s1 s2 -> subseq (rev s1) (rev s2).
by apply/idP/idP => /W //; rewrite !revK.
by case/subseqP => m size_m ->; rewrite rev_mask // mask_subseq.
Qed.
Lemma subseq_cat2l s s1 s2 : subseq (s ++ s1) (s ++ s2) = subseq s1 s2.
Proof. by elim: s => // x s IHs; rewrite !cat_cons /= eqxx. Qed.
Lemma subseq_cat2r s s1 s2 : subseq (s1 ++ s) (s2 ++ s) = subseq s1 s2.
Proof. by rewrite -subseq_rev !rev_cat subseq_cat2l subseq_rev. Qed.
Lemma subseq_rot p s n :
subseq p s -> exists2 k, k <= n & subseq (rot k p) (rot n s).
Proof.
move=> /subseqP[m size_m ->].
exists (count id (take n m)); last by rewrite -mask_rot // mask_subseq.
by rewrite (leq_trans (count_size _ _))// size_take_min geq_minl.
Qed.
End Subseq.
Prenex Implicits subseq.
Arguments subseqP {T s1 s2}.
#[global] Hint Resolve subseq_refl : core.
Section Rem.
Variables (T : eqType) (x : T).
Fixpoint rem s := if s is y :: t then (if y == x then t else y :: rem t) else s.
Lemma rem_cons y s : rem (y :: s) = if y == x then s else y :: rem s.
Proof. by []. Qed.
Lemma remE s : rem s = take (index x s) s ++ drop (index x s).+1 s.
Proof. by elim: s => //= y s ->; case: eqVneq; rewrite ?drop0. Qed.
Lemma rem_id s : x \notin s -> rem s = s.
Proof. by elim: s => //= y s IHs /norP[neq_yx /IHs->]; case: eqVneq neq_yx. Qed.
Lemma perm_to_rem s : x \in s -> perm_eq s (x :: rem s).
Proof.
move=> xs; rewrite remE -[X in perm_eq X](cat_take_drop (index x s)).
by rewrite drop_index// -cat1s perm_catCA cat1s.
Qed.
Lemma size_rem s : x \in s -> size (rem s) = (size s).-1.
Proof. by move/perm_to_rem/perm_size->. Qed.
Lemma rem_subseq s : subseq (rem s) s.
Proof.
elim: s => //= y s IHs; rewrite eq_sym.
by case: ifP => _; [apply: subseq_cons | rewrite eqxx].
Qed.
Lemma rem_uniq s : uniq s -> uniq (rem s).
Proof. by apply: subseq_uniq; apply: rem_subseq. Qed.
Lemma mem_rem s : {subset rem s <= s}.
Proof. exact: mem_subseq (rem_subseq s). Qed.
Lemma rem_mem y s : y != x -> y \in s -> y \in rem s.
Proof.
move=> yx; elim: s => [//|z s IHs] /=.
rewrite inE => /orP[/eqP<-|ys]; first by rewrite (negbTE yx) inE eqxx.
by case: ifP => _ //; rewrite inE IHs ?orbT.
Qed.
Lemma rem_filter s : uniq s -> rem s = filter (predC1 x) s.
Proof.
elim: s => //= y s IHs /andP[not_s_y /IHs->].
by case: eqP => //= <-; apply/esym/all_filterP; rewrite all_predC has_pred1.
Qed.
Lemma mem_rem_uniq s : uniq s -> rem s =i [predD1 s & x].
Proof. by move/rem_filter=> -> y; rewrite mem_filter. Qed.
Lemma mem_rem_uniqF s : uniq s -> x \in rem s = false.
Proof. by move/mem_rem_uniq->; rewrite inE eqxx. Qed.
Lemma count_rem P s : count P (rem s) = count P s - (x \in s) && P x.
Proof.
have [/perm_to_rem/permP->|xNs]/= := boolP (x \in s); first by rewrite addKn.
by rewrite subn0 rem_id.
Qed.
Lemma count_mem_rem y s : count_mem y (rem s) = count_mem y s - (x == y).
Proof.
rewrite count_rem; have []//= := boolP (x \in s).
by case: eqP => // <- /count_memPn->.
Qed.
End Rem.
Section Map.
Variables (n0 : nat) (T1 : Type) (x1 : T1).
Variables (T2 : Type) (x2 : T2) (f : T1 -> T2).
Fixpoint map s := if s is x :: s' then f x :: map s' else [::].
Lemma map_cons x s : map (x :: s) = f x :: map s.
Proof. by []. Qed.
Lemma map_nseq x : map (nseq n0 x) = nseq n0 (f x).
Proof. by elim: n0 => // *; congr (_ :: _). Qed.
Lemma map_cat s1 s2 : map (s1 ++ s2) = map s1 ++ map s2.
Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs. Qed.
Lemma size_map s : size (map s) = size s.
Proof. by elim: s => //= x s ->. Qed.
Lemma behead_map s : behead (map s) = map (behead s).
Proof. by case: s. Qed.
Lemma nth_map n s : n < size s -> nth x2 (map s) n = f (nth x1 s n).
Proof. by elim: s n => [|x s IHs] []. Qed.
Lemma map_rcons s x : map (rcons s x) = rcons (map s) (f x).
Proof. by rewrite -!cats1 map_cat. Qed.
Lemma last_map s x : last (f x) (map s) = f (last x s).
Proof. by elim: s x => /=. Qed.
Lemma belast_map s x : belast (f x) (map s) = map (belast x s).
Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed.
Lemma filter_map a s : filter a (map s) = map (filter (preim f a) s).
Proof. by elim: s => //= x s IHs; rewrite (fun_if map) /= IHs. Qed.
Lemma find_map a s : find a (map s) = find (preim f a) s.
Proof. by elim: s => //= x s ->. Qed.
Lemma has_map a s : has a (map s) = has (preim f a) s.
Proof. by elim: s => //= x s ->. Qed.
Lemma all_map a s : all a (map s) = all (preim f a) s.
Proof. by elim: s => //= x s ->. Qed.
Lemma all_mapT (a : pred T2) s : (forall x, a (f x)) -> all a (map s).
Proof. by rewrite all_map => /allT->. Qed.
Lemma count_map a s : count a (map s) = count (preim f a) s.
Proof. by elim: s => //= x s ->. Qed.
Lemma map_take s : map (take n0 s) = take n0 (map s).
Proof. by elim: n0 s => [|n IHn] [|x s] //=; rewrite IHn. Qed.
Lemma map_drop s : map (drop n0 s) = drop n0 (map s).
Proof. by elim: n0 s => [|n IHn] [|x s] //=; rewrite IHn. Qed.
Lemma map_rot s : map (rot n0 s) = rot n0 (map s).
Proof. by rewrite /rot map_cat map_take map_drop. Qed.
Lemma map_rotr s : map (rotr n0 s) = rotr n0 (map s).
Proof. by apply: canRL (rotK n0) _; rewrite -map_rot rotrK. Qed.
Lemma map_rev s : map (rev s) = rev (map s).
Proof. by elim: s => //= x s IHs; rewrite !rev_cons -!cats1 map_cat IHs. Qed.
Lemma map_mask m s : map (mask m s) = mask m (map s).
Proof. by elim: m s => [|[|] m IHm] [|x p] //=; rewrite IHm. Qed.
Lemma inj_map : injective f -> injective map.
Proof. by move=> injf; elim=> [|x s IHs] [|y t] //= [/injf-> /IHs->]. Qed.
Lemma inj_in_map (A : {pred T1}) :
{in A &, injective f} -> {in [pred s | all [in A] s] &, injective map}.
Proof.
move=> injf; elim=> [|x s IHs] [|y t] //= /andP[Ax As] /andP[Ay At].
by case=> /injf-> // /IHs->.
Qed.
End Map.
(* Sequence indexing with error. *)
Section onth.
Variable T : Type.
Implicit Types x y z : T.
Implicit Types m n : nat.
Implicit Type s : seq T.
Fixpoint onth s n {struct n} : option T :=
if s isn't x :: s then None else
if n isn't n.+1 then Some x else onth s n.
Lemma odflt_onth x0 s n : odflt x0 (onth s n) = nth x0 s n.
Proof. by elim: n s => [|? ?] []. Qed.
Lemma onthE s : onth s =1 nth None (map Some s).
Proof. by move=> n; elim: n s => [|? ?] []. Qed.
Lemma onth_nth x0 x t n : onth t n = Some x -> nth x0 t n = x.
Proof. by move=> tn; rewrite -odflt_onth tn. Qed.
Lemma onth0n n : onth [::] n = None. Proof. by case: n. Qed.
Lemma onth1P x y n : onth [:: x] n = Some y <-> n = 0 /\ x = y.
Proof. by case: n => [|[]]; split=> // -[] // _ ->. Qed.
Lemma onthTE s n : onth s n = (n < size s) :> bool.
Proof. by elim: n s => [|? ?] []. Qed.
Lemma onthNE s n: ~~ onth s n = (size s <= n).
Proof. by rewrite onthTE -leqNgt. Qed.
Lemma onth_default n s : size s <= n -> onth s n = None.
Proof. by rewrite -onthNE; case: onth. Qed.
Lemma onth_cat s1 s2 n :
onth (s1 ++ s2) n = if n < size s1 then onth s1 n else onth s2 (n - size s1).
Proof. by elim: n s1 => [|? ?] []. Qed.
Lemma onth_nseq x n m : onth (nseq n x) m = if m < n then Some x else None.
Proof. by rewrite onthE/= -nth_nseq map_nseq. Qed.
Lemma eq_onthP {s1 s2} :
[<-> s1 = s2;
forall i : nat, i < maxn (size s1) (size s2) -> onth s1 i = onth s2 i;
forall i : nat, onth s1 i = onth s2 i].
Proof.
tfae=> [->//|eqs12 i|eqs12].
have := eqs12 i; case: ltnP => [_ ->//|].
by rewrite geq_max => /andP[is1 is2] _; rewrite !onth_default.
have /eqP eq_size_12 : size s1 == size s2.
by rewrite eqn_leq -!onthNE eqs12 onthNE -eqs12 onthNE !leqnn.
apply/(inj_map Some_inj)/(@eq_from_nth _ None); rewrite !size_map//.
by move=> i _; rewrite -!onthE eqs12.
Qed.
Lemma eq_from_onth [s1 s2 : seq T] :
(forall i : nat, onth s1 i = onth s2 i) -> s1 = s2.
Proof. by move/(eq_onthP 0 2). Qed.
Lemma eq_from_onth_le [s1 s2 : seq T] :
(forall i : nat, i < maxn (size s1) (size s2) -> onth s1 i = onth s2 i) ->
s1 = s2.
Proof. by move/(eq_onthP 0 1). Qed.
End onth.
Lemma onth_map {T S} n (s : seq T) (f : T -> S) :
onth (map f s) n = omap f (onth s n).
Proof. by elim: s n => [|x s IHs] []. Qed.
Lemma inj_onth_map {T S} n (s : seq T) (f : T -> S) x :
injective f -> onth (map f s) n = Some (f x) -> onth s n = Some x.
Proof. by rewrite onth_map => /inj_omap + fs; apply. Qed.
Section onthEqType.
Variables T : eqType.
Implicit Types x y z : T.
Implicit Types i m n : nat.
Implicit Type s : seq T.
Lemma onthP s x : reflect (exists i, onth s i = Some x) (x \in s).
Proof.
elim: s => [|y s IHs]; first by constructor=> -[] [].
rewrite in_cons; case: eqVneq => [->|/= Nxy]; first by constructor; exists 0.
apply: (iffP idP) => [/IHs[i <-]|[[|i]//=]]; first by exists i.+1.
by move=> [eq_xy]; rewrite eq_xy eqxx in Nxy.
by move=> six; apply/IHs; exists i.
Qed.
Lemma onthPn s x : reflect (forall i, onth s i != Some x) (x \notin s).
Proof.
apply: (iffP idP); first by move=> /onthP + i; apply: contra_not_neq; exists i.
by move=> nsix; apply/onthP => -[n /eqP/negPn]; rewrite nsix.
Qed.
Lemma onth_inj s n m : uniq s -> minn m n < size s ->
onth s n = onth s m -> n = m.
Proof.
elim: s m n => [|x s IHs]//= [|m] [|n]//=; rewrite ?minnSS !ltnS.
- by move=> /andP[+ _] _ /eqP => /onthPn/(_ _)/negPf->.
- by move=> /andP[+ _] _ /esym /eqP => /onthPn/(_ _)/negPf->.
by move=> /andP[xNs /IHs]/[apply]/[apply]->.
Qed.
End onthEqType.
Arguments onthP {T s x}.
Arguments onthPn {T s x}.
Arguments onth_nth {T}.
Arguments onth_inj {T}.
Notation "[ 'seq' E | i <- s ]" := (map (fun i => E) s)
(i binder, format "[ '[hv' 'seq' E '/ ' | i <- s ] ']'") : seq_scope.
Notation "[ 'seq' E | i <- s & C ]" := [seq E | i <- [seq i <- s | C]]
(i binder,
format "[ '[hv' 'seq' E '/ ' | i <- s '/ ' & C ] ']'") : seq_scope.
Notation "[ 'seq' E : R | i <- s ]" := (@map _ R (fun i => E) s)
(i binder, only parsing) : seq_scope.
Notation "[ 'seq' E : R | i <- s & C ]" := [seq E : R | i <- [seq i <- s | C]]
(i binder, only parsing) : seq_scope.
Lemma filter_mask T a (s : seq T) : filter a s = mask (map a s) s.
Proof. by elim: s => //= x s <-; case: (a x). Qed.
Lemma all_sigP T a (s : seq T) : all a s -> {s' : seq (sig a) | s = map sval s'}.
Proof.
elim: s => /= [_|x s ihs /andP [ax /ihs [s' ->]]]; first by exists [::].
by exists (exist a x ax :: s').
Qed.
Section MiscMask.
Lemma leq_count_mask T (P : {pred T}) m s : count P (mask m s) <= count P s.
Proof.
by elim: s m => [|x s IHs] [|[] m]//=;
rewrite ?leq_add2l (leq_trans (IHs _)) ?leq_addl.
Qed.
Variable (T : eqType).
Implicit Types (s : seq T) (m : bitseq).
Lemma mask_filter s m : uniq s -> mask m s = [seq i <- s | i \in mask m s].
Proof.
elim: m s => [|[] m IH] [|x s /= /andP[/negP xS uS]]; rewrite ?filter_pred0 //.
rewrite inE eqxx /=; congr cons; rewrite [LHS]IH//.
by apply/eq_in_filter => ? /[1!inE]; case: eqP => [->|].
by case: ifP => [/mem_mask //|_]; apply: IH.
Qed.
Lemma leq_count_subseq P s1 s2 : subseq s1 s2 -> count P s1 <= count P s2.
Proof. by move=> /subseqP[m _ ->]; rewrite leq_count_mask. Qed.
Lemma count_maskP s1 s2 :
(forall x, count_mem x s1 <= count_mem x s2) <->
exists2 m : bitseq, size m = size s2 & perm_eq s1 (mask m s2).
Proof.
split=> [s1_le|[m _ /permP s1ms2 x]]; last by rewrite s1ms2 leq_count_mask.
suff [m mP]: exists m, perm_eq s1 (mask m s2).
by have [m' sm' eqm] := resize_mask m s2; exists m'; rewrite -?eqm.
elim: s2 => [|x s2 IHs]//= in s1 s1_le *.
by exists [::]; apply/allP => x _/=; rewrite eqn_leq s1_le.
have [y|m s1s2] := IHs (rem x s1); first by rewrite count_mem_rem leq_subLR.
exists ((x \in s1) :: m); have [|/rem_id<-//] := boolP (x \in s1).
by move/perm_to_rem/permPl->; rewrite perm_cons.
Qed.
Lemma count_subseqP s1 s2 :
(forall x, count_mem x s1 <= count_mem x s2) <->
exists2 s, subseq s s2 & perm_eq s1 s.
Proof.
split=> [/count_maskP[m _]|]; first by exists (mask m s2); rewrite ?mask_subseq.
by move=> -[_/subseqP[m sm ->] ?]; apply/count_maskP; exists m.
Qed.
End MiscMask.
Section FilterSubseq.
Variable T : eqType.
Implicit Types (s : seq T) (a : pred T).
Lemma filter_subseq a s : subseq (filter a s) s.
Proof. by apply/subseqP; exists (map a s); rewrite ?size_map ?filter_mask. Qed.
Lemma subseq_filter s1 s2 a :
subseq s1 (filter a s2) = all a s1 && subseq s1 s2.
Proof.
elim: s2 s1 => [|x s2 IHs] [|y s1] //=; rewrite ?andbF ?sub0seq //.
by case a_x: (a x); rewrite /= !IHs /=; case: eqP => // ->; rewrite a_x.
Qed.
Lemma subseq_uniqP s1 s2 :
uniq s2 -> reflect (s1 = filter [in s1] s2) (subseq s1 s2).
Proof.
move=> uniq_s2; apply: (iffP idP) => [ss12 | ->]; last exact: filter_subseq.
apply/eqP; rewrite -size_subseq_leqif ?subseq_filter ?(introT allP) //.
apply/eqP/esym/perm_size.
rewrite uniq_perm ?filter_uniq ?(subseq_uniq ss12) // => x.
by rewrite mem_filter; apply: andb_idr; apply: (mem_subseq ss12).
Qed.
Lemma uniq_subseq_pivot x (s1 s2 s3 s4 : seq T) (s := s3 ++ x :: s4) :
uniq s -> subseq (s1 ++ x :: s2) s = (subseq s1 s3 && subseq s2 s4).
Proof.
move=> uniq_s; apply/idP/idP => [sub_s'_s|/andP[? ?]]; last first.
by rewrite cat_subseq //= eqxx.
have uniq_s' := subseq_uniq sub_s'_s uniq_s.
have/eqP {sub_s'_s uniq_s} := subseq_uniqP _ uniq_s sub_s'_s.
rewrite !filter_cat /= mem_cat inE eqxx orbT /=.
rewrite uniq_eqseq_pivotl // => /andP [/eqP -> /eqP ->].
by rewrite !filter_subseq.
Qed.
Lemma perm_to_subseq s1 s2 :
subseq s1 s2 -> {s3 | perm_eq s2 (s1 ++ s3)}.
Proof.
elim Ds2: s2 s1 => [|y s2' IHs] [|x s1] //=; try by exists s2; rewrite Ds2.
case: eqP => [-> | _] /IHs[s3 perm_s2] {IHs}.
by exists s3; rewrite perm_cons.
by exists (rcons s3 y); rewrite -cat_cons -perm_rcons -!cats1 catA perm_cat2r.
Qed.
Lemma subseq_rem x : {homo rem x : s1 s2 / @subseq T s1 s2}.
Proof.
move=> s1 s2; elim: s2 s1 => [|x2 s2 IHs2] [|x1 s1]; rewrite ?sub0seq //=.
have [->|_] := eqVneq x1 x2; first by case: eqP => //= _ /IHs2; rewrite eqxx.
move=> /IHs2/subseq_trans->//.
by have [->|_] := eqVneq x x2; [apply: rem_subseq|apply: subseq_cons].
Qed.
End FilterSubseq.
Arguments subseq_uniqP [T s1 s2].
Section EqMap.
Variables (n0 : nat) (T1 : eqType) (x1 : T1).
Variables (T2 : eqType) (x2 : T2) (f : T1 -> T2).
Implicit Type s : seq T1.
Lemma map_f s x : x \in s -> f x \in map f s.
Proof.
by elim: s => //= y s IHs /predU1P[->|/IHs]; [apply: predU1l | apply: predU1r].
Qed.
Lemma mapP s y : reflect (exists2 x, x \in s & y = f x) (y \in map f s).
Proof.
elim: s => [|x s IHs]; [by right; case|rewrite /= inE].
exact: equivP (orPP eqP IHs) (iff_sym exists_cons).
Qed.
Lemma subset_mapP (s : seq T1) (s' : seq T2) :
{subset s' <= map f s} <-> exists2 t, all (mem s) t & s' = map f t.
Proof.
split => [|[r /allP/= rE ->] _ /mapP[x xr ->]]; last by rewrite map_f ?rE.
elim: s' => [|x s' IHs'] subss'; first by exists [::].
have /mapP[y ys ->] := subss' _ (mem_head _ _).
have [x' x's'|t st ->] := IHs'; first by rewrite subss'// inE x's' orbT.
by exists (y :: t); rewrite //= ys st.
Qed.
Lemma map_uniq s : uniq (map f s) -> uniq s.
Proof.
elim: s => //= x s IHs /andP[not_sfx /IHs->]; rewrite andbT.
by apply: contra not_sfx => sx; apply/mapP; exists x.
Qed.
Lemma map_inj_in_uniq s : {in s &, injective f} -> uniq (map f s) = uniq s.
Proof.
elim: s => //= x s IHs //= injf; congr (~~ _ && _).
apply/mapP/idP=> [[y sy /injf] | ]; last by exists x.
by rewrite mem_head mem_behead // => ->.
by apply: IHs => y z sy sz; apply: injf => //; apply: predU1r.
Qed.
Lemma map_subseq s1 s2 : subseq s1 s2 -> subseq (map f s1) (map f s2).
Proof.
case/subseqP=> m sz_m ->; apply/subseqP.
by exists m; rewrite ?size_map ?map_mask.
Qed.
Lemma nth_index_map s x0 x :
{in s &, injective f} -> x \in s -> nth x0 s (index (f x) (map f s)) = x.
Proof.
elim: s => //= y s IHs inj_f s_x; rewrite (inj_in_eq inj_f) ?mem_head //.
move: s_x; rewrite inE; have [-> // | _] := eqVneq; apply: IHs.
by apply: sub_in2 inj_f => z; apply: predU1r.
Qed.
Lemma perm_map s t : perm_eq s t -> perm_eq (map f s) (map f t).
Proof. by move/permP=> Est; apply/permP=> a; rewrite !count_map Est. Qed.
Lemma sub_map s1 s2 : {subset s1 <= s2} -> {subset map f s1 <= map f s2}.
Proof. by move=> sub_s ? /mapP[x x_s ->]; rewrite map_f ?sub_s. Qed.
Lemma eq_mem_map s1 s2 : s1 =i s2 -> map f s1 =i map f s2.
Proof. by move=> Es x; apply/idP/idP; apply: sub_map => ?; rewrite Es. Qed.
Hypothesis Hf : injective f.
Lemma mem_map s x : (f x \in map f s) = (x \in s).
Proof. by apply/mapP/idP=> [[y Hy /Hf->] //|]; exists x. Qed.
Lemma index_map s x : index (f x) (map f s) = index x s.
Proof. by rewrite /index; elim: s => //= y s IHs; rewrite (inj_eq Hf) IHs. Qed.
Lemma map_inj_uniq s : uniq (map f s) = uniq s.
Proof. by apply: map_inj_in_uniq; apply: in2W. Qed.
Lemma undup_map_inj s : undup (map f s) = map f (undup s).
Proof. by elim: s => //= s0 s ->; rewrite mem_map //; case: (_ \in _). Qed.
Lemma perm_map_inj s t : perm_eq (map f s) (map f t) -> perm_eq s t.
Proof.
move/permP=> Est; apply/allP=> x _ /=.
have Dx: pred1 x =1 preim f (pred1 (f x)) by move=> y /=; rewrite inj_eq.
by rewrite !(eq_count Dx) -!count_map Est.
Qed.
End EqMap.
Arguments mapP {T1 T2 f s y}.
Arguments subset_mapP {T1 T2}.
Lemma map_of_seq (T1 : eqType) T2 (s : seq T1) (fs : seq T2) (y0 : T2) :
{f | uniq s -> size fs = size s -> map f s = fs}.
Proof.
exists (fun x => nth y0 fs (index x s)) => uAs eq_sz.
apply/esym/(@eq_from_nth _ y0); rewrite ?size_map eq_sz // => i ltis.
by have x0 : T1 by [case: (s) ltis]; rewrite (nth_map x0) // index_uniq.
Qed.
Section MapComp.
Variable S T U : Type.
Lemma map_id (s : seq T) : map id s = s.
Proof. by elim: s => //= x s ->. Qed.
Lemma eq_map (f g : S -> T) : f =1 g -> map f =1 map g.
Proof. by move=> Ef; elim=> //= x s ->; rewrite Ef. Qed.
Lemma map_comp (f : T -> U) (g : S -> T) s : map (f \o g) s = map f (map g s).
Proof. by elim: s => //= x s ->. Qed.
Lemma mapK (f : S -> T) (g : T -> S) : cancel f g -> cancel (map f) (map g).
Proof. by move=> fK; elim=> //= x s ->; rewrite fK. Qed.
Lemma mapK_in (A : {pred S}) (f : S -> T) (g : T -> S) :
{in A, cancel f g} -> {in [pred s | all [in A] s], cancel (map f) (map g)}.
Proof. by move=> fK; elim=> //= x s IHs /andP[/fK-> /IHs->]. Qed.
End MapComp.
Lemma eq_in_map (S : eqType) T (f g : S -> T) (s : seq S) :
{in s, f =1 g} <-> map f s = map g s.
Proof.
elim: s => //= x s IHs; split=> [/forall_cons[-> ?]|]; first by rewrite IHs.1.
by move=> -[? ?]; apply/forall_cons; split=> [//|]; apply: IHs.2.
Qed.
Lemma map_id_in (T : eqType) f (s : seq T) : {in s, f =1 id} -> map f s = s.
Proof. by move/eq_in_map->; apply: map_id. Qed.
(* Map a partial function *)
Section Pmap.
Variables (aT rT : Type) (f : aT -> option rT) (g : rT -> aT).
Fixpoint pmap s :=
if s is x :: s' then let r := pmap s' in oapp (cons^~ r) r (f x) else [::].
Lemma map_pK : pcancel g f -> cancel (map g) pmap.
Proof. by move=> gK; elim=> //= x s ->; rewrite gK. Qed.
Lemma size_pmap s : size (pmap s) = count [eta f] s.
Proof. by elim: s => //= x s <-; case: (f _). Qed.
Lemma pmapS_filter s : map some (pmap s) = map f (filter [eta f] s).
Proof. by elim: s => //= x s; case fx: (f x) => //= [u] <-; congr (_ :: _). Qed.
Hypothesis fK : ocancel f g.
Lemma pmap_filter s : map g (pmap s) = filter [eta f] s.
Proof. by elim: s => //= x s <-; rewrite -{3}(fK x); case: (f _). Qed.
Lemma pmap_cat s t : pmap (s ++ t) = pmap s ++ pmap t.
Proof. by elim: s => //= x s ->; case/f: x. Qed.
Lemma all_pmap (p : pred rT) s :
all p (pmap s) = all [pred i | oapp p true (f i)] s.
Proof. by elim: s => //= x s <-; case: f. Qed.
End Pmap.
Lemma eq_in_pmap (aT : eqType) rT (f1 f2 : aT -> option rT) s :
{in s, f1 =1 f2} -> pmap f1 s = pmap f2 s.
Proof. by elim: s => //= a s IHs /forall_cons [-> /IHs ->]. Qed.
Lemma eq_pmap aT rT (f1 f2 : aT -> option rT) :
f1 =1 f2 -> pmap f1 =1 pmap f2.
Proof. by move=> Ef; elim => //= a s ->; rewrite Ef. Qed.
Section EqPmap.
Variables (aT rT : eqType) (f : aT -> option rT) (g : rT -> aT).
Lemma mem_pmap s u : (u \in pmap f s) = (Some u \in map f s).
Proof. by elim: s => //= x s IHs; rewrite in_cons -IHs; case: (f x). Qed.
Hypothesis fK : ocancel f g.
Lemma can2_mem_pmap : pcancel g f -> forall s u, (u \in pmap f s) = (g u \in s).
Proof.
by move=> gK s u; rewrite -(mem_map (pcan_inj gK)) pmap_filter // mem_filter gK.
Qed.
Lemma pmap_uniq s : uniq s -> uniq (pmap f s).
Proof. move/(filter_uniq f); rewrite -(pmap_filter fK); exact: map_uniq. Qed.
Lemma perm_pmap s t : perm_eq s t -> perm_eq (pmap f s) (pmap f t).
Proof.
move=> eq_st; apply/(perm_map_inj Some_inj); rewrite !pmapS_filter.
exact/perm_map/perm_filter.
Qed.
End EqPmap.
Section PmapSub.
Variables (T : Type) (p : pred T) (sT : subType p).
Lemma size_pmap_sub s : size (pmap (insub : T -> option sT) s) = count p s.
Proof. by rewrite size_pmap (eq_count (isSome_insub _)). Qed.
End PmapSub.
Section EqPmapSub.
Variables (T : eqType) (p : pred T) (sT : subEqType p).
Let insT : T -> option sT := insub.
Lemma mem_pmap_sub s u : (u \in pmap insT s) = (val u \in s).
Proof. exact/(can2_mem_pmap (insubK _))/valK. Qed.
Lemma pmap_sub_uniq s : uniq s -> uniq (pmap insT s).
Proof. exact: (pmap_uniq (insubK _)). Qed.
End EqPmapSub.
(* Index sequence *)
Fixpoint iota m n := if n is n'.+1 then m :: iota m.+1 n' else [::].
Lemma size_iota m n : size (iota m n) = n.
Proof. by elim: n m => //= n IHn m; rewrite IHn. Qed.
Lemma iotaD m n1 n2 : iota m (n1 + n2) = iota m n1 ++ iota (m + n1) n2.
Proof. by elim: n1 m => [|n1 IHn1] m; rewrite ?addn0 // -addSnnS /= -IHn1. Qed.
Lemma iotaDl m1 m2 n : iota (m1 + m2) n = map (addn m1) (iota m2 n).
Proof. by elim: n m2 => //= n IHn m2; rewrite -addnS IHn. Qed.
Lemma nth_iota p m n i : i < n -> nth p (iota m n) i = m + i.
Proof.
by move/subnKC <-; rewrite addSnnS iotaD nth_cat size_iota ltnn subnn.
Qed.
Lemma mem_iota m n i : (i \in iota m n) = (m <= i < m + n).
Proof.
elim: n m => [|n IHn] /= m; first by rewrite addn0 ltnNge andbN.
by rewrite in_cons IHn addnS ltnS; case: ltngtP => // ->; rewrite leq_addr.
Qed.
Lemma iota_uniq m n : uniq (iota m n).
Proof. by elim: n m => //= n IHn m; rewrite mem_iota ltnn /=. Qed.
Lemma take_iota k m n : take k (iota m n) = iota m (minn k n).
Proof.
have [lt_k_n|le_n_k] := ltnP.
by elim: k n lt_k_n m => [|k IHk] [|n] //= H m; rewrite IHk.
by apply: take_oversize; rewrite size_iota.
Qed.
Lemma drop_iota k m n : drop k (iota m n) = iota (m + k) (n - k).
Proof.
by elim: k m n => [|k IHk] m [|n] //=; rewrite ?addn0 // IHk addnS subSS.
Qed.
Lemma filter_iota_ltn m n j : j <= n ->
[seq i <- iota m n | i < m + j] = iota m j.
Proof.
elim: n m j => [m j|n IHn m [|j] jlen]; first by rewrite leqn0 => /eqP ->.
rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => i.
by rewrite addn0 ltnNge mem_iota => /andP[->].
by rewrite /= addnS leq_addr -addSn IHn.
Qed.
Lemma filter_iota_leq n m j : j < n ->
[seq i <- iota m n | i <= m + j] = iota m j.+1.
Proof.
elim: n m j => [//|n IHn] m [|j] jlen /=; rewrite leq_addr.
rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => i.
by rewrite addn0 leqNgt mem_iota => /andP[->].
by rewrite addnS -addSn IHn -1?ltnS.
Qed.
(* Making a sequence of a specific length, using indexes to compute items. *)
Section MakeSeq.
Variables (T : Type) (x0 : T).
Definition mkseq f n : seq T := map f (iota 0 n).
Lemma size_mkseq f n : size (mkseq f n) = n.
Proof. by rewrite size_map size_iota. Qed.
Lemma mkseqS f n :
mkseq f n.+1 = rcons (mkseq f n) (f n).
Proof. by rewrite /mkseq -addn1 iotaD add0n map_cat cats1. Qed.
Lemma eq_mkseq f g : f =1 g -> mkseq f =1 mkseq g.
Proof. by move=> Efg n; apply: eq_map Efg _. Qed.
Lemma nth_mkseq f n i : i < n -> nth x0 (mkseq f n) i = f i.
Proof. by move=> Hi; rewrite (nth_map 0) ?nth_iota ?size_iota. Qed.
Lemma mkseq_nth s : mkseq (nth x0 s) (size s) = s.
Proof.
by apply: (@eq_from_nth _ x0); rewrite size_mkseq // => i Hi; rewrite nth_mkseq.
Qed.
Variant mkseq_spec s : seq T -> Type :=
| MapIota n f : s = mkseq f n -> mkseq_spec s (mkseq f n).
Lemma mkseqP s : mkseq_spec s s.
Proof. by rewrite -[s]mkseq_nth; constructor. Qed.
Lemma map_nth_iota0 s i :
i <= size s -> [seq nth x0 s j | j <- iota 0 i] = take i s.
Proof.
by move=> ile; rewrite -[s in RHS]mkseq_nth -map_take take_iota (minn_idPl _).
Qed.
Lemma map_nth_iota s i j : j <= size s - i ->
[seq nth x0 s k | k <- iota i j] = take j (drop i s).
Proof.
elim: i => [|i IH] in s j *; first by rewrite subn0 drop0 => /map_nth_iota0->.
case: s => [|x s /IH<-]; first by rewrite leqn0 => /eqP->.
by rewrite -add1n iotaDl -map_comp.
Qed.
End MakeSeq.
Section MakeEqSeq.
Variable T : eqType.
Lemma mkseq_uniqP (f : nat -> T) n :
reflect {in gtn n &, injective f} (uniq (mkseq f n)).
Proof.
apply: (equivP (uniqP (f 0))); rewrite size_mkseq.
by split=> injf i j lti ltj; have:= injf i j lti ltj; rewrite !nth_mkseq.
Qed.
Lemma mkseq_uniq (f : nat -> T) n : injective f -> uniq (mkseq f n).
Proof. by move/map_inj_uniq->; apply: iota_uniq. Qed.
Lemma perm_iotaP {s t : seq T} x0 (It := iota 0 (size t)) :
reflect (exists2 Is, perm_eq Is It & s = map (nth x0 t) Is) (perm_eq s t).
Proof.
apply: (iffP idP) => [Est | [Is eqIst ->]]; last first.
by rewrite -{2}[t](mkseq_nth x0) perm_map.
elim: t => [|x t IHt] in s It Est *.
by rewrite (perm_small_eq _ Est) //; exists [::].
have /rot_to[k s1 Ds]: x \in s by rewrite (perm_mem Est) mem_head.
have [|Is1 eqIst1 Ds1] := IHt s1; first by rewrite -(perm_cons x) -Ds perm_rot.
exists (rotr k (0 :: map succn Is1)).
by rewrite perm_rot /It /= perm_cons (iotaDl 1) perm_map.
by rewrite map_rotr /= -map_comp -(@eq_map _ _ (nth x0 t)) // -Ds1 -Ds rotK.
Qed.
End MakeEqSeq.
Arguments perm_iotaP {T s t}.
Section FoldRight.
Variables (T : Type) (R : Type) (f : T -> R -> R) (z0 : R).
Fixpoint foldr s := if s is x :: s' then f x (foldr s') else z0.
End FoldRight.
Section FoldRightComp.
Variables (T1 T2 : Type) (h : T1 -> T2).
Variables (R : Type) (f : T2 -> R -> R) (z0 : R).
Lemma foldr_cat s1 s2 : foldr f z0 (s1 ++ s2) = foldr f (foldr f z0 s2) s1.
Proof. by elim: s1 => //= x s1 ->. Qed.
Lemma foldr_rcons s x : foldr f z0 (rcons s x) = foldr f (f x z0) s.
Proof. by rewrite -cats1 foldr_cat. Qed.
Lemma foldr_map s : foldr f z0 (map h s) = foldr (fun x z => f (h x) z) z0 s.
Proof. by elim: s => //= x s ->. Qed.
End FoldRightComp.
(* Quick characterization of the null sequence. *)
Definition sumn := foldr addn 0.
Lemma sumn_ncons x n s : sumn (ncons n x s) = x * n + sumn s.
Proof. by rewrite mulnC; elim: n => //= n ->; rewrite addnA. Qed.
Lemma sumn_nseq x n : sumn (nseq n x) = x * n.
Proof. by rewrite sumn_ncons addn0. Qed.
Lemma sumn_cat s1 s2 : sumn (s1 ++ s2) = sumn s1 + sumn s2.
Proof. by elim: s1 => //= x s1 ->; rewrite addnA. Qed.
Lemma sumn_count T (a : pred T) s : sumn [seq a i : nat | i <- s] = count a s.
Proof. by elim: s => //= s0 s /= ->. Qed.
Lemma sumn_rcons s n : sumn (rcons s n) = sumn s + n.
Proof. by rewrite -cats1 sumn_cat /= addn0. Qed.
Lemma perm_sumn s1 s2 : perm_eq s1 s2 -> sumn s1 = sumn s2.
Proof.
by apply/catCA_perm_subst: s1 s2 => s1 s2 s3; rewrite !sumn_cat addnCA.
Qed.
Lemma sumn_rot s n : sumn (rot n s) = sumn s.
Proof. by apply/perm_sumn; rewrite perm_rot. Qed.
Lemma sumn_rev s : sumn (rev s) = sumn s.
Proof. by apply/perm_sumn; rewrite perm_rev. Qed.
Lemma natnseq0P s : reflect (s = nseq (size s) 0) (sumn s == 0).
Proof.
apply: (iffP idP) => [|->]; last by rewrite sumn_nseq.
by elim: s => //= x s IHs; rewrite addn_eq0 => /andP[/eqP-> /IHs <-].
Qed.
Lemma sumn_set_nth s x0 n x :
sumn (set_nth x0 s n x) =
sumn s + x - (nth x0 s n) * (n < size s) + x0 * (n - size s).
Proof.
rewrite set_nthE; case: ltnP => [nlts|nges]; last first.
by rewrite sumn_cat sumn_ncons /= addn0 muln0 subn0 addnAC addnA.
have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW.
rewrite -[in sumn s](cat_take_drop n s) [drop n s](drop_nth x0)//.
by rewrite !sumn_cat /= muln1 muln0 addn0 addnAC !addnA [in RHS]addnAC addnK.
Qed.
Lemma sumn_set_nth_ltn s x0 n x : n < size s ->
sumn (set_nth x0 s n x) = sumn s + x - nth x0 s n.
Proof.
move=> nlts; rewrite sumn_set_nth nlts muln1.
have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW.
by rewrite muln0 addn0.
Qed.
Lemma sumn_set_nth0 s n x : sumn (set_nth 0 s n x) = sumn s + x - nth 0 s n.
Proof.
rewrite sumn_set_nth mul0n addn0.
by case: ltnP => [_|nges]; rewrite ?muln1// nth_default.
Qed.
Section FoldLeft.
Variables (T R : Type) (f : R -> T -> R).
Fixpoint foldl z s := if s is x :: s' then foldl (f z x) s' else z.
Lemma foldl_rev z s : foldl z (rev s) = foldr (fun x z => f z x) z s.
Proof.
by elim/last_ind: s z => // s x IHs z; rewrite rev_rcons -cats1 foldr_cat -IHs.
Qed.
Lemma foldl_cat z s1 s2 : foldl z (s1 ++ s2) = foldl (foldl z s1) s2.
Proof.
by rewrite -(revK (s1 ++ s2)) foldl_rev rev_cat foldr_cat -!foldl_rev !revK.
Qed.
Lemma foldl_rcons z s x : foldl z (rcons s x) = f (foldl z s) x.
Proof. by rewrite -cats1 foldl_cat. Qed.
End FoldLeft.
Section Folds.
Variables (T : Type) (f : T -> T -> T).
Hypotheses (fA : associative f) (fC : commutative f).
Lemma foldl_foldr x0 l : foldl f x0 l = foldr f x0 l.
Proof.
elim: l x0 => [//|x1 l IHl] x0 /=; rewrite {}IHl.
by elim: l x0 x1 => [//|x2 l IHl] x0 x1 /=; rewrite IHl !fA [f x2 x1]fC.
Qed.
End Folds.
Section Scan.
Variables (T1 : Type) (x1 : T1) (T2 : Type) (x2 : T2).
Variables (f : T1 -> T1 -> T2) (g : T1 -> T2 -> T1).
Fixpoint pairmap x s := if s is y :: s' then f x y :: pairmap y s' else [::].
Lemma size_pairmap x s : size (pairmap x s) = size s.
Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed.
Lemma pairmap_cat x s1 s2 :
pairmap x (s1 ++ s2) = pairmap x s1 ++ pairmap (last x s1) s2.
Proof. by elim: s1 x => //= y s1 IHs1 x; rewrite IHs1. Qed.
Lemma nth_pairmap s n : n < size s ->
forall x, nth x2 (pairmap x s) n = f (nth x1 (x :: s) n) (nth x1 s n).
Proof. by elim: s n => [|y s IHs] [|n] //= Hn x; apply: IHs. Qed.
Fixpoint scanl x s :=
if s is y :: s' then let x' := g x y in x' :: scanl x' s' else [::].
Lemma size_scanl x s : size (scanl x s) = size s.
Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed.
Lemma scanl_cat x s1 s2 :
scanl x (s1 ++ s2) = scanl x s1 ++ scanl (foldl g x s1) s2.
Proof. by elim: s1 x => //= y s1 IHs1 x; rewrite IHs1. Qed.
Lemma scanl_rcons x s1 y :
scanl x (rcons s1 y) = rcons (scanl x s1) (foldl g x (rcons s1 y)).
Proof. by rewrite -!cats1 scanl_cat foldl_cat. Qed.
Lemma nth_cons_scanl s n : n <= size s ->
forall x, nth x1 (x :: scanl x s) n = foldl g x (take n s).
Proof. by elim: s n => [|y s IHs] [|n] Hn x //=; rewrite IHs. Qed.
Lemma nth_scanl s n : n < size s ->
forall x, nth x1 (scanl x s) n = foldl g x (take n.+1 s).
Proof. by move=> n_lt x; rewrite -nth_cons_scanl. Qed.
Lemma scanlK :
(forall x, cancel (g x) (f x)) -> forall x, cancel (scanl x) (pairmap x).
Proof. by move=> Hfg x s; elim: s x => //= y s IHs x; rewrite Hfg IHs. Qed.
Lemma pairmapK :
(forall x, cancel (f x) (g x)) -> forall x, cancel (pairmap x) (scanl x).
Proof. by move=> Hgf x s; elim: s x => //= y s IHs x; rewrite Hgf IHs. Qed.
End Scan.
Prenex Implicits mask map pmap foldr foldl scanl pairmap.
Section Zip.
Variables (S T : Type) (r : S -> T -> bool).
Fixpoint zip (s : seq S) (t : seq T) {struct t} :=
match s, t with
| x :: s', y :: t' => (x, y) :: zip s' t'
| _, _ => [::]
end.
Definition unzip1 := map (@fst S T).
Definition unzip2 := map (@snd S T).
Fixpoint all2 s t :=
match s, t with
| [::], [::] => true
| x :: s, y :: t => r x y && all2 s t
| _, _ => false
end.
Lemma zip_unzip s : zip (unzip1 s) (unzip2 s) = s.
Proof. by elim: s => [|[x y] s /= ->]. Qed.
Lemma unzip1_zip s t : size s <= size t -> unzip1 (zip s t) = s.
Proof. by elim: s t => [|x s IHs] [|y t] //= le_s_t; rewrite IHs. Qed.
Lemma unzip2_zip s t : size t <= size s -> unzip2 (zip s t) = t.
Proof. by elim: s t => [|x s IHs] [|y t] //= le_t_s; rewrite IHs. Qed.
Lemma size1_zip s t : size s <= size t -> size (zip s t) = size s.
Proof. by elim: s t => [|x s IHs] [|y t] //= Hs; rewrite IHs. Qed.
Lemma size2_zip s t : size t <= size s -> size (zip s t) = size t.
Proof. by elim: s t => [|x s IHs] [|y t] //= Hs; rewrite IHs. Qed.
Lemma size_zip s t : size (zip s t) = minn (size s) (size t).
Proof. by elim: s t => [|x s IHs] [|t2 t] //=; rewrite IHs minnSS. Qed.
Lemma zip_cat s1 s2 t1 t2 :
size s1 = size t1 -> zip (s1 ++ s2) (t1 ++ t2) = zip s1 t1 ++ zip s2 t2.
Proof. by move: s1 t1; apply: seq_ind2 => //= x y s1 t1 _ ->. Qed.
Lemma nth_zip x y s t i :
size s = size t -> nth (x, y) (zip s t) i = (nth x s i, nth y t i).
Proof. by elim: i s t => [|i IHi] [|y1 s1] [|y2 t] //= [/IHi->]. Qed.
Lemma nth_zip_cond p s t i :
nth p (zip s t) i
= (if i < size (zip s t) then (nth p.1 s i, nth p.2 t i) else p).
Proof.
rewrite size_zip ltnNge geq_min.
by elim: s t i => [|x s IHs] [|y t] [|i] //=; rewrite ?orbT -?IHs.
Qed.
Lemma zip_rcons s t x y :
size s = size t -> zip (rcons s x) (rcons t y) = rcons (zip s t) (x, y).
Proof. by move=> eq_sz; rewrite -!cats1 zip_cat //= eq_sz. Qed.
Lemma rev_zip s t : size s = size t -> rev (zip s t) = zip (rev s) (rev t).
Proof.
move: s t; apply: seq_ind2 => //= x y s t eq_sz IHs.
by rewrite !rev_cons IHs zip_rcons ?size_rev.
Qed.
Lemma all2E s t :
all2 s t = (size s == size t) && all [pred xy | r xy.1 xy.2] (zip s t).
Proof. by elim: s t => [|x s IHs] [|y t] //=; rewrite IHs andbCA. Qed.
Lemma zip_map I f g (s : seq I) :
zip (map f s) (map g s) = [seq (f i, g i) | i <- s].
Proof. by elim: s => //= i s ->. Qed.
Lemma unzip1_map_nth_zip x y s t l :
size s = size t ->
unzip1 [seq nth (x, y) (zip s t) i | i <- l] = [seq nth x s i | i <- l].
Proof. by move=> st; elim: l => [//=|n l IH /=]; rewrite nth_zip ?IH ?st. Qed.
Lemma unzip2_map_nth_zip x y s t l :
size s = size t ->
unzip2 [seq nth (x, y) (zip s t) i | i <- l] = [seq nth y t i | i <- l].
Proof. by move=> st; elim: l => [//=|n l IH /=]; rewrite nth_zip ?IH ?st. Qed.
End Zip.
Lemma zip_uniql (S T : eqType) (s : seq S) (t : seq T) :
uniq s -> uniq (zip s t).
Proof.
case: s t => [|s0 s] [|t0 t] //; apply: contraTT => /(uniqPn (s0, t0)) [i [j]].
case=> o z; rewrite !nth_zip_cond !ifT ?js ?(ltn_trans o)// => -[n _].
by apply/(uniqPn s0); exists i, j; rewrite o n (leq_trans z) ?size_zip?geq_minl.
Qed.
Lemma zip_uniqr (S T : eqType) (s : seq S) (t : seq T) :
uniq t -> uniq (zip s t).
Proof.
case: s t => [|s0 s] [|t0 t] //; apply: contraTT => /(uniqPn (s0, t0)) [i [j]].
case=> o z; rewrite !nth_zip_cond !ifT ?js ?(ltn_trans o)// => -[_ n].
by apply/(uniqPn t0); exists i, j; rewrite o n (leq_trans z) ?size_zip?geq_minr.
Qed.
Lemma perm_zip_sym (S T : eqType) (s1 s2 : seq S) (t1 t2 : seq T) :
perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq (zip t1 s1) (zip t2 s2).
Proof.
have swap t s : zip t s = map (fun u => (u.2, u.1)) (zip s t).
by elim: s t => [|x s +] [|y t]//= => ->.
by rewrite [zip t1 s1]swap [zip t2 s2]swap; apply: perm_map.
Qed.
Lemma perm_zip1 {S T : eqType} (t1 t2 : seq T) (s1 s2 : seq S):
size s1 = size t1 -> size s2 = size t2 ->
perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq s1 s2.
Proof.
wlog [x y] : s1 s2 t1 t2 / (S * T)%type => [hwlog|].
case: s2 t2 => [|x s2] [|y t2] //; last exact: hwlog.
by case: s1 t1 => [|u s1] [|v t1]//= _ _ /perm_nilP.
move=> eq1 eq2 /(perm_iotaP (x, y))[ns nsP /(congr1 (@unzip1 _ _))].
rewrite unzip1_zip ?unzip1_map_nth_zip -?eq1// => ->.
by apply/(perm_iotaP x); exists ns; rewrite // size_zip -eq2 minnn in nsP.
Qed.
Lemma perm_zip2 {S T : eqType} (s1 s2 : seq S) (t1 t2 : seq T) :
size s1 = size t1 -> size s2 = size t2 ->
perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq t1 t2.
Proof. by move=> ? ? ?; rewrite (@perm_zip1 _ _ s1 s2) 1?perm_zip_sym. Qed.
Prenex Implicits zip unzip1 unzip2 all2.
Lemma eqseq_all (T : eqType) (s t : seq T) : (s == t) = all2 eq_op s t.
Proof. by elim: s t => [|x s +] [|y t]//= => <-. Qed.
Lemma eq_map_all I (T : eqType) (f g : I -> T) (s : seq I) :
(map f s == map g s) = all [pred xy | xy.1 == xy.2] [seq (f i, g i) | i <- s].
Proof. by rewrite eqseq_all all2E !size_map eqxx zip_map. Qed.
Section Flatten.
Variable T : Type.
Implicit Types (s : seq T) (ss : seq (seq T)).
Definition flatten := foldr cat (Nil T).
Definition shape := map (@size T).
Fixpoint reshape sh s :=
if sh is n :: sh' then take n s :: reshape sh' (drop n s) else [::].
Definition flatten_index sh r c := sumn (take r sh) + c.
Definition reshape_index sh i := find (pred1 0) (scanl subn i.+1 sh).
Definition reshape_offset sh i := i - sumn (take (reshape_index sh i) sh).
Lemma size_flatten ss : size (flatten ss) = sumn (shape ss).
Proof. by elim: ss => //= s ss <-; rewrite size_cat. Qed.
Lemma flatten_cat ss1 ss2 : flatten (ss1 ++ ss2) = flatten ss1 ++ flatten ss2.
Proof. by elim: ss1 => //= s ss1 ->; rewrite catA. Qed.
Lemma size_reshape sh s : size (reshape sh s) = size sh.
Proof. by elim: sh s => //= s0 sh IHsh s; rewrite IHsh. Qed.
Lemma nth_reshape (sh : seq nat) l n :
nth [::] (reshape sh l) n = take (nth 0 sh n) (drop (sumn (take n sh)) l).
Proof.
elim: n sh l => [| n IHn] [| sh0 sh] l; rewrite ?take0 ?drop0 //=.
by rewrite addnC -drop_drop; apply: IHn.
Qed.
Lemma flattenK ss : reshape (shape ss) (flatten ss) = ss.
Proof.
by elim: ss => //= s ss IHss; rewrite take_size_cat ?drop_size_cat ?IHss.
Qed.
Lemma reshapeKr sh s : size s <= sumn sh -> flatten (reshape sh s) = s.
Proof.
elim: sh s => [[]|n sh IHsh] //= s sz_s; rewrite IHsh ?cat_take_drop //.
by rewrite size_drop leq_subLR.
Qed.
Lemma reshapeKl sh s : size s >= sumn sh -> shape (reshape sh s) = sh.
Proof.
elim: sh s => [[]|n sh IHsh] //= s sz_s.
rewrite size_takel; last exact: leq_trans (leq_addr _ _) sz_s.
by rewrite IHsh // -(leq_add2l n) size_drop -maxnE leq_max sz_s orbT.
Qed.
Lemma flatten_rcons ss s : flatten (rcons ss s) = flatten ss ++ s.
Proof. by rewrite -cats1 flatten_cat /= cats0. Qed.
Lemma flatten_seq1 s : flatten [seq [:: x] | x <- s] = s.
Proof. by elim: s => //= s0 s ->. Qed.
Lemma count_flatten ss P :
count P (flatten ss) = sumn [seq count P x | x <- ss].
Proof. by elim: ss => //= s ss IHss; rewrite count_cat IHss. Qed.
Lemma filter_flatten ss (P : pred T) :
filter P (flatten ss) = flatten [seq filter P i | i <- ss].
Proof. by elim: ss => // s ss /= <-; apply: filter_cat. Qed.
Lemma rev_flatten ss :
rev (flatten ss) = flatten (rev (map rev ss)).
Proof.
by elim: ss => //= s ss IHss; rewrite rev_cons flatten_rcons -IHss rev_cat.
Qed.
Lemma nth_shape ss i : nth 0 (shape ss) i = size (nth [::] ss i).
Proof.
rewrite /shape; case: (ltnP i (size ss)) => Hi; first exact: nth_map.
by rewrite !nth_default // size_map.
Qed.
Lemma shape_rev ss : shape (rev ss) = rev (shape ss).
Proof. exact: map_rev. Qed.
Lemma eq_from_flatten_shape ss1 ss2 :
flatten ss1 = flatten ss2 -> shape ss1 = shape ss2 -> ss1 = ss2.
Proof. by move=> Eflat Esh; rewrite -[LHS]flattenK Eflat Esh flattenK. Qed.
Lemma rev_reshape sh s :
size s = sumn sh -> rev (reshape sh s) = map rev (reshape (rev sh) (rev s)).
Proof.
move=> sz_s; apply/(canLR revK)/eq_from_flatten_shape.
rewrite reshapeKr ?sz_s // -rev_flatten reshapeKr ?revK //.
by rewrite size_rev sumn_rev sz_s.
transitivity (rev (shape (reshape (rev sh) (rev s)))).
by rewrite !reshapeKl ?revK ?size_rev ?sz_s ?sumn_rev.
rewrite shape_rev; congr (rev _); rewrite -[RHS]map_comp.
by under eq_map do rewrite /= size_rev.
Qed.
Lemma reshape_rcons s sh n (m := sumn sh) :
m + n = size s ->
reshape (rcons sh n) s = rcons (reshape sh (take m s)) (drop m s).
Proof.
move=> Dmn; apply/(can_inj revK); rewrite rev_reshape ?rev_rcons ?sumn_rcons //.
rewrite /= take_rev drop_rev -Dmn addnK revK -rev_reshape //.
by rewrite size_takel // -Dmn leq_addr.
Qed.
Lemma flatten_indexP sh r c :
c < nth 0 sh r -> flatten_index sh r c < sumn sh.
Proof.
move=> lt_c_sh; rewrite -[sh in sumn sh](cat_take_drop r) sumn_cat ltn_add2l.
suffices lt_r_sh: r < size sh by rewrite (drop_nth 0 lt_r_sh) ltn_addr.
by case: ltnP => // le_sh_r; rewrite nth_default in lt_c_sh.
Qed.
Lemma reshape_indexP sh i : i < sumn sh -> reshape_index sh i < size sh.
Proof.
rewrite /reshape_index; elim: sh => //= n sh IHsh in i *; rewrite subn_eq0.
by have [// | le_n_i] := ltnP i n; rewrite -leq_subLR subSn // => /IHsh.
Qed.
Lemma reshape_offsetP sh i :
i < sumn sh -> reshape_offset sh i < nth 0 sh (reshape_index sh i).
Proof.
rewrite /reshape_offset /reshape_index; elim: sh => //= n sh IHsh in i *.
rewrite subn_eq0; have [| le_n_i] := ltnP i n; first by rewrite subn0.
by rewrite -leq_subLR /= subnDA subSn // => /IHsh.
Qed.
Lemma reshape_indexK sh i :
flatten_index sh (reshape_index sh i) (reshape_offset sh i) = i.
Proof.
rewrite /reshape_offset /reshape_index /flatten_index -subSKn.
elim: sh => //= n sh IHsh in i *; rewrite subn_eq0; have [//|le_n_i] := ltnP.
by rewrite /= subnDA subSn // -addnA IHsh subnKC.
Qed.
Lemma flatten_indexKl sh r c :
c < nth 0 sh r -> reshape_index sh (flatten_index sh r c) = r.
Proof.
rewrite /reshape_index /flatten_index.
elim: sh r => [|n sh IHsh] [|r] //= lt_c_sh; first by rewrite ifT.
by rewrite -addnA -addnS addKn IHsh.
Qed.
Lemma flatten_indexKr sh r c :
c < nth 0 sh r -> reshape_offset sh (flatten_index sh r c) = c.
Proof.
rewrite /reshape_offset /reshape_index /flatten_index.
elim: sh r => [|n sh IHsh] [|r] //= lt_c_sh; first by rewrite ifT ?subn0.
by rewrite -addnA -addnS addKn /= subnDl IHsh.
Qed.
Lemma nth_flatten x0 ss i (r := reshape_index (shape ss) i) :
nth x0 (flatten ss) i = nth x0 (nth [::] ss r) (reshape_offset (shape ss) i).
Proof.
rewrite /reshape_offset -subSKn {}/r /reshape_index.
elim: ss => //= s ss IHss in i *; rewrite subn_eq0 nth_cat.
by have [//|le_s_i] := ltnP; rewrite subnDA subSn /=.
Qed.
Lemma reshape_leq sh i1 i2
(r1 := reshape_index sh i1) (c1 := reshape_offset sh i1)
(r2 := reshape_index sh i2) (c2 := reshape_offset sh i2) :
(i1 <= i2) = ((r1 < r2) || ((r1 == r2) && (c1 <= c2))).
Proof.
rewrite {}/r1 {}/c1 {}/r2 {}/c2 /reshape_offset /reshape_index.
elim: sh => [|s0 s IHs] /= in i1 i2 *; rewrite ?subn0 ?subn_eq0 //.
have [[] i1s0 [] i2s0] := (ltnP i1 s0, ltnP i2 s0); first by rewrite !subn0.
- by apply: leq_trans i2s0; apply/ltnW.
- by apply/negP => /(leq_trans i1s0); rewrite leqNgt i2s0.
by rewrite !subSn // !eqSS !ltnS !subnDA -IHs leq_subLR subnKC.
Qed.
End Flatten.
Prenex Implicits flatten shape reshape.
Lemma map_flatten S T (f : T -> S) ss :
map f (flatten ss) = flatten (map (map f) ss).
Proof. by elim: ss => // s ss /= <-; apply: map_cat. Qed.
Lemma flatten_map1 (S T : Type) (f : S -> T) s :
flatten [seq [:: f x] | x <- s] = map f s.
Proof. by elim: s => //= s0 s ->. Qed.
Lemma undup_flatten_nseq n (T : eqType) (s : seq T) : 0 < n ->
undup (flatten (nseq n s)) = undup s.
Proof.
elim: n => [|[|n]/= IHn]//= _; rewrite ?cats0// undup_cat {}IHn//.
rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => x.
by rewrite mem_undup mem_cat => ->.
Qed.
Lemma sumn_flatten (ss : seq (seq nat)) :
sumn (flatten ss) = sumn (map sumn ss).
Proof. by elim: ss => // s ss /= <-; apply: sumn_cat. Qed.
Lemma map_reshape T S (f : T -> S) sh s :
map (map f) (reshape sh s) = reshape sh (map f s).
Proof. by elim: sh s => //= sh0 sh IHsh s; rewrite map_take IHsh map_drop. Qed.
Section EqFlatten.
Variables S T : eqType.
Lemma flattenP (A : seq (seq T)) x :
reflect (exists2 s, s \in A & x \in s) (x \in flatten A).
Proof.
elim: A => /= [|s A IH_A]; [by right; case | rewrite mem_cat].
by apply: equivP (iff_sym exists_cons); apply: (orPP idP IH_A).
Qed.
Arguments flattenP {A x}.
Lemma flatten_mapP (A : S -> seq T) s y :
reflect (exists2 x, x \in s & y \in A x) (y \in flatten (map A s)).
Proof.
apply: (iffP flattenP) => [[_ /mapP[x sx ->]] | [x sx]] Axy; first by exists x.
by exists (A x); rewrite ?map_f.
Qed.
Lemma perm_flatten (ss1 ss2 : seq (seq T)) :
perm_eq ss1 ss2 -> perm_eq (flatten ss1) (flatten ss2).
Proof.
move=> eq_ss; apply/permP=> a; apply/catCA_perm_subst: ss1 ss2 eq_ss.
by move=> ss1 ss2 ss3; rewrite !flatten_cat !count_cat addnCA.
Qed.
End EqFlatten.
Arguments flattenP {T A x}.
Arguments flatten_mapP {S T A s y}.
Notation "[ 'seq' E | x <- s , y <- t ]" :=
(flatten [seq [seq E | y <- t] | x <- s])
(x binder, y binder,
format "[ '[hv' 'seq' E '/ ' | x <- s , '/ ' y <- t ] ']'")
: seq_scope.
Notation "[ 'seq' E : R | x <- s , y <- t ]" :=
(flatten [seq [seq E : R | y <- t] | x <- s])
(x binder, y binder, only parsing) : seq_scope.
Section PrefixSuffixInfix.
Variables T : eqType.
Implicit Type s : seq T.
Fixpoint prefix s1 s2 {struct s2} :=
if s1 isn't x :: s1' then true else
if s2 isn't y :: s2' then false else
(x == y) && prefix s1' s2'.
Lemma prefixE s1 s2 : prefix s1 s2 = (take (size s1) s2 == s1).
Proof. by elim: s2 s1 => [|y s2 +] [|x s1]//= => ->; rewrite eq_sym. Qed.
Lemma prefix_refl s : prefix s s. Proof. by rewrite prefixE take_size. Qed.
Lemma prefixs0 s : prefix s [::] = (s == [::]). Proof. by case: s. Qed.
Lemma prefix0s s : prefix [::] s. Proof. by case: s. Qed.
Lemma prefix_cons s1 s2 x y :
prefix (x :: s1) (y :: s2) = (x == y) && prefix s1 s2.
Proof. by []. Qed.
Lemma prefix_catr s1 s2 s1' s3 : size s1 = size s1' ->
prefix (s1 ++ s2) (s1' ++ s3) = (s1 == s1') && prefix s2 s3.
Proof.
elim: s1 s1' => [|x s1 IHs1] [|y s1']//= [eqs1].
by rewrite IHs1// eqseq_cons andbA.
Qed.
Lemma prefix_prefix s1 s2 : prefix s1 (s1 ++ s2).
Proof. by rewrite prefixE take_cat ltnn subnn take0 cats0. Qed.
Hint Resolve prefix_prefix : core.
Lemma prefixP {s1 s2} :
reflect (exists s2' : seq T, s2 = s1 ++ s2') (prefix s1 s2).
Proof.
apply: (iffP idP) => [|[{}s2 ->]]; last exact: prefix_prefix.
by rewrite prefixE => /eqP<-; exists (drop (size s1) s2); rewrite cat_take_drop.
Qed.
Lemma prefix_trans : transitive prefix.
Proof. by move=> _ s2 _ /prefixP[s1 ->] /prefixP[s3 ->]; rewrite -catA. Qed.
Lemma prefixs1 s x : prefix s [:: x] = (s == [::]) || (s == [:: x]).
Proof. by case: s => //= y s; rewrite prefixs0 eqseq_cons. Qed.
Lemma catl_prefix s1 s2 s3 : prefix (s1 ++ s3) s2 -> prefix s1 s2.
Proof. by move=> /prefixP [s2'] ->; rewrite -catA. Qed.
Lemma prefix_catl s1 s2 s3 : prefix s1 s2 -> prefix s1 (s2 ++ s3).
Proof. by move=> /prefixP [s2'] ->; rewrite -catA. Qed.
Lemma prefix_rcons s x : prefix s (rcons s x).
Proof. by rewrite -cats1 prefix_prefix. Qed.
Definition suffix s1 s2 := prefix (rev s1) (rev s2).
Lemma suffixE s1 s2 : suffix s1 s2 = (drop (size s2 - size s1) s2 == s1).
Proof. by rewrite /suffix prefixE take_rev (can_eq revK) size_rev. Qed.
Lemma suffix_refl s : suffix s s.
Proof. exact: prefix_refl. Qed.
Lemma suffixs0 s : suffix s [::] = (s == [::]).
Proof. by rewrite /suffix prefixs0 -!nilpE rev_nilp. Qed.
Lemma suffix0s s : suffix [::] s.
Proof. exact: prefix0s. Qed.
Lemma prefix_rev s1 s2 : prefix (rev s1) (rev s2) = suffix s1 s2.
Proof. by []. Qed.
Lemma prefix_revLR s1 s2 : prefix (rev s1) s2 = suffix s1 (rev s2).
Proof. by rewrite -prefix_rev revK. Qed.
Lemma suffix_rev s1 s2 : suffix (rev s1) (rev s2) = prefix s1 s2.
Proof. by rewrite -prefix_rev !revK. Qed.
Lemma suffix_revLR s1 s2 : suffix (rev s1) s2 = prefix s1 (rev s2).
Proof. by rewrite -prefix_rev revK. Qed.
Lemma suffix_suffix s1 s2 : suffix s2 (s1 ++ s2).
Proof. by rewrite /suffix rev_cat prefix_prefix. Qed.
Hint Resolve suffix_suffix : core.
Lemma suffixP {s1 s2} :
reflect (exists s2' : seq T, s2 = s2' ++ s1) (suffix s1 s2).
Proof.
apply: (iffP prefixP) => [[s2' rev_s2]|[s2' ->]]; exists (rev s2'); last first.
by rewrite rev_cat.
by rewrite -[s2]revK rev_s2 rev_cat revK.
Qed.
Lemma suffix_trans : transitive suffix.
Proof. by move=> _ s2 _ /suffixP[s1 ->] /suffixP[s3 ->]; rewrite catA. Qed.
Lemma suffix_rcons s1 s2 x y :
suffix (rcons s1 x) (rcons s2 y) = (x == y) && suffix s1 s2.
Proof. by rewrite /suffix 2!rev_rcons prefix_cons. Qed.
Lemma suffix_catl s1 s2 s3 s3' : size s3 = size s3' ->
suffix (s1 ++ s3) (s2 ++ s3') = (s3 == s3') && suffix s1 s2.
Proof.
by move=> eqs3; rewrite /suffix !rev_cat prefix_catr ?size_rev// (can_eq revK).
Qed.
Lemma suffix_catr s1 s2 s3 : suffix s1 s2 -> suffix s1 (s3 ++ s2).
Proof. by move=> /suffixP [s2'] ->; rewrite catA suffix_suffix. Qed.
Lemma catl_suffix s s1 s2 : suffix (s ++ s1) s2 -> suffix s1 s2.
Proof. by move=> /suffixP [s2'] ->; rewrite catA suffix_suffix. Qed.
Lemma suffix_cons s x : suffix s (x :: s).
Proof. by rewrite /suffix rev_cons prefix_rcons. Qed.
Fixpoint infix s1 s2 :=
if s2 is y :: s2' then prefix s1 s2 || infix s1 s2' else s1 == [::].
Fixpoint infix_index s1 s2 :=
if prefix s1 s2 then 0
else if s2 is y :: s2' then (infix_index s1 s2').+1 else 1.
Lemma infix0s s : infix [::] s. Proof. by case: s. Qed.
Lemma infixs0 s : infix s [::] = (s == [::]). Proof. by case: s. Qed.
Lemma infix_consl s1 y s2 :
infix s1 (y :: s2) = prefix s1 (y :: s2) || infix s1 s2.
Proof. by []. Qed.
Lemma infix_indexss s : infix_index s s = 0.
Proof. by case: s => //= x s; rewrite eqxx prefix_refl. Qed.
Lemma infix_index_le s1 s2 : infix_index s1 s2 <= (size s2).+1.
Proof. by elim: s2 => [|x s2'] /=; case: ifP. Qed.
Lemma infixTindex s1 s2 : (infix_index s1 s2 <= size s2) = infix s1 s2.
Proof. by elim: s2 s1 => [|y s2 +] [|x s1]//= => <-; case: ifP. Qed.
Lemma infixPn s1 s2 :
reflect (infix_index s1 s2 = (size s2).+1) (~~ infix s1 s2).
Proof.
rewrite -infixTindex -ltnNge; apply: (iffP idP) => [s2lt|->//].
by apply/eqP; rewrite eqn_leq s2lt infix_index_le.
Qed.
Lemma infix_index0s s : infix_index [::] s = 0.
Proof. by case: s. Qed.
Lemma infix_indexs0 s : infix_index s [::] = (s != [::]).
Proof. by case: s. Qed.
Lemma infixE s1 s2 : infix s1 s2 =
(take (size s1) (drop (infix_index s1 s2) s2) == s1).
Proof.
elim: s2 s1 => [|y s2 +] [|x s1]//= => -> /=.
by case: ifP => // /andP[/eqP-> ps1s2/=]; rewrite eqseq_cons -prefixE eqxx.
Qed.
Lemma infix_refl s : infix s s.
Proof. by rewrite infixE infix_indexss// drop0 take_size. Qed.
Lemma prefixW s1 s2 : prefix s1 s2 -> infix s1 s2.
Proof. by elim: s2 s1 => [|y s2 IHs2] [|x s1]//=->. Qed.
Lemma prefix_infix s1 s2 : infix s1 (s1 ++ s2).
Proof. exact: prefixW. Qed.
Hint Resolve prefix_infix : core.
Lemma infix_infix s1 s2 s3 : infix s2 (s1 ++ s2 ++ s3).
Proof. by elim: s1 => //= x s1 ->; rewrite orbT. Qed.
Hint Resolve infix_infix : core.
Lemma suffix_infix s1 s2 : infix s2 (s1 ++ s2).
Proof. by rewrite -[X in s1 ++ X]cats0. Qed.
Hint Resolve suffix_infix : core.
Lemma infixP {s1 s2} :
reflect (exists s s' : seq T, s2 = s ++ s1 ++ s') (infix s1 s2).
Proof.
apply: (iffP idP) => [|[p [s {s2}->]]]//=; rewrite infixE => /eqP<-.
set k := infix_index _ _; exists (take k s2), (drop (size s1 + k) s2).
by rewrite -drop_drop !cat_take_drop.
Qed.
Lemma infix_rev s1 s2 : infix (rev s1) (rev s2) = infix s1 s2.
Proof.
gen have sr : s1 s2 / infix s1 s2 -> infix (rev s1) (rev s2); last first.
by apply/idP/idP => /sr; rewrite ?revK.
by move=> /infixP[s [p ->]]; rewrite !rev_cat -catA.
Qed.
Lemma suffixW s1 s2 : suffix s1 s2 -> infix s1 s2.
Proof. by rewrite -infix_rev; apply: prefixW. Qed.
Lemma infix_trans : transitive infix.
Proof.
move=> s s1 s2 /infixP[s1p [s1s def_s]] /infixP[sp [ss def_s2]].
by apply/infixP; exists (sp ++ s1p),(s1s ++ ss); rewrite def_s2 def_s -!catA.
Qed.
Lemma infix_revLR s1 s2 : infix (rev s1) s2 = infix s1 (rev s2).
Proof. by rewrite -infix_rev revK. Qed.
Lemma infix_rconsl s1 s2 y :
infix s1 (rcons s2 y) = suffix s1 (rcons s2 y) || infix s1 s2.
Proof.
rewrite -infix_rev rev_rcons infix_consl.
by rewrite -rev_rcons prefix_rev infix_rev.
Qed.
Lemma infix_cons s x : infix s (x :: s).
Proof. by rewrite -cat1s suffix_infix. Qed.
Lemma infixs1 s x : infix s [:: x] = (s == [::]) || (s == [:: x]).
Proof. by rewrite infix_consl prefixs1 orbC orbA orbb. Qed.
Lemma catl_infix s s1 s2 : infix (s ++ s1) s2 -> infix s1 s2.
Proof. apply: infix_trans; exact/suffixW/suffix_suffix. Qed.
Lemma catr_infix s s1 s2 : infix (s1 ++ s) s2 -> infix s1 s2.
Proof.
by rewrite -infix_rev rev_cat => /catl_infix; rewrite infix_rev.
Qed.
Lemma cons2_infix s1 s2 x : infix (x :: s1) (x :: s2) -> infix s1 s2.
Proof.
by rewrite /= eqxx /= -cat1s => /orP[/prefixW//|]; exact: catl_infix.
Qed.
Lemma rcons2_infix s1 s2 x : infix (rcons s1 x) (rcons s2 x) -> infix s1 s2.
Proof. by rewrite -infix_rev !rev_rcons => /cons2_infix; rewrite infix_rev. Qed.
Lemma catr2_infix s s1 s2 : infix (s ++ s1) (s ++ s2) -> infix s1 s2.
Proof. by elim: s => //= x s IHs /cons2_infix. Qed.
Lemma catl2_infix s s1 s2 : infix (s1 ++ s) (s2 ++ s) -> infix s1 s2.
Proof. by rewrite -infix_rev !rev_cat => /catr2_infix; rewrite infix_rev. Qed.
Lemma infix_catl s1 s2 s3 : infix s1 s2 -> infix s1 (s3 ++ s2).
Proof. by move=> is12; apply: infix_trans is12 (suffix_infix _ _). Qed.
Lemma infix_catr s1 s2 s3 : infix s1 s2 -> infix s1 (s2 ++ s3).
Proof.
case: s3 => [|x s /infixP [p [sf]] ->]; first by rewrite cats0.
by rewrite -catA; apply: infix_catl; rewrite -catA prefix_infix.
Qed.
Lemma prefix_infix_trans s2 s1 s3 :
prefix s1 s2 -> infix s2 s3 -> infix s1 s3.
Proof. by move=> /prefixW/infix_trans; apply. Qed.
Lemma suffix_infix_trans s2 s1 s3 :
suffix s1 s2 -> infix s2 s3 -> infix s1 s3.
Proof. by move=> /suffixW/infix_trans; apply. Qed.
Lemma infix_prefix_trans s2 s1 s3 :
infix s1 s2 -> prefix s2 s3 -> infix s1 s3.
Proof. by move=> + /prefixW; apply: infix_trans. Qed.
Lemma infix_suffix_trans s2 s1 s3 :
infix s1 s2 -> suffix s2 s3 -> infix s1 s3.
Proof. by move=> + /suffixW; apply: infix_trans. Qed.
Lemma prefix_suffix_trans s2 s1 s3 :
prefix s1 s2 -> suffix s2 s3 -> infix s1 s3.
Proof. by move=> /prefixW + /suffixW +; apply: infix_trans. Qed.
Lemma suffix_prefix_trans s2 s1 s3 :
suffix s1 s2 -> prefix s2 s3 -> infix s1 s3.
Proof. by move=> /suffixW + /prefixW +; apply: infix_trans. Qed.
Lemma infixW s1 s2 : infix s1 s2 -> subseq s1 s2.
Proof.
move=> /infixP[sp [ss ->]].
exact: subseq_trans (prefix_subseq _ _) (suffix_subseq _ _).
Qed.
Lemma mem_infix s1 s2 : infix s1 s2 -> {subset s1 <= s2}.
Proof. by move=> /infixW subH; apply: mem_subseq. Qed.
Lemma infix1s s x : infix [:: x] s = (x \in s).
Proof. by elim: s => // x' s /= ->; rewrite in_cons prefix0s andbT. Qed.
Lemma prefix1s s x : prefix [:: x] s -> x \in s.
Proof. by rewrite -infix1s => /prefixW. Qed.
Lemma suffix1s s x : suffix [:: x] s -> x \in s.
Proof. by rewrite -infix1s => /suffixW. Qed.
Lemma infix_rcons s x : infix s (rcons s x).
Proof. by rewrite -cats1 prefix_infix. Qed.
Lemma infix_uniq s1 s2 : infix s1 s2 -> uniq s2 -> uniq s1.
Proof. by move=> /infixW /subseq_uniq subH. Qed.
Lemma prefix_uniq s1 s2 : prefix s1 s2 -> uniq s2 -> uniq s1.
Proof. by move=> /prefixW /infix_uniq preH. Qed.
Lemma suffix_uniq s1 s2 : suffix s1 s2 -> uniq s2 -> uniq s1.
Proof. by move=> /suffixW /infix_uniq preH. Qed.
Lemma prefix_take s i : prefix (take i s) s.
Proof. by rewrite -{2}[s](cat_take_drop i). Qed.
Lemma suffix_drop s i : suffix (drop i s) s.
Proof. by rewrite -{2}[s](cat_take_drop i). Qed.
Lemma infix_take s i : infix (take i s) s.
Proof. by rewrite prefixW // prefix_take. Qed.
Lemma prefix_drop_gt0 s i : ~~ prefix (drop i s) s -> i > 0.
Proof. by case: i => //=; rewrite drop0 ltnn prefix_refl. Qed.
Lemma infix_drop s i : infix (drop i s) s.
Proof. by rewrite -{2}[s](cat_take_drop i). Qed.
Lemma consr_infix s1 s2 x : infix (x :: s1) s2 -> infix [:: x] s2.
Proof. by rewrite -cat1s => /catr_infix. Qed.
Lemma consl_infix s1 s2 x : infix (x :: s1) s2 -> infix s1 s2.
Proof. by rewrite -cat1s => /catl_infix. Qed.
Lemma prefix_index s1 s2 : prefix s1 s2 -> infix_index s1 s2 = 0.
Proof. by case: s1 s2 => [|x s1] [|y s2] //= ->. Qed.
Lemma size_infix s1 s2 : infix s1 s2 -> size s1 <= size s2.
Proof. by move=> /infixW; apply: size_subseq. Qed.
Lemma size_prefix s1 s2 : prefix s1 s2 -> size s1 <= size s2.
Proof. by move=> /prefixW; apply: size_infix. Qed.
Lemma size_suffix s1 s2 : suffix s1 s2 -> size s1 <= size s2.
Proof. by move=> /suffixW; apply: size_infix. Qed.
End PrefixSuffixInfix.
Section AllPairsDep.
Variables (S S' : Type) (T T' : S -> Type) (R : Type).
Implicit Type f : forall x, T x -> R.
Definition allpairs_dep f s t := [seq f x y | x <- s, y <- t x].
Lemma size_allpairs_dep f s t :
size [seq f x y | x <- s, y <- t x] = sumn [seq size (t x) | x <- s].
Proof. by elim: s => //= x s IHs; rewrite size_cat size_map IHs. Qed.
Lemma allpairs0l f t : [seq f x y | x <- [::], y <- t x] = [::].
Proof. by []. Qed.
Lemma allpairs0r f s : [seq f x y | x <- s, y <- [::]] = [::].
Proof. by elim: s. Qed.
Lemma allpairs1l f x t :
[seq f x y | x <- [:: x], y <- t x] = [seq f x y | y <- t x].
Proof. exact: cats0. Qed.
Lemma allpairs1r f s y :
[seq f x y | x <- s, y <- [:: y x]] = [seq f x (y x) | x <- s].
Proof. exact: flatten_map1. Qed.
Lemma allpairs_cons f x s t :
[seq f x y | x <- x :: s, y <- t x] =
[seq f x y | y <- t x] ++ [seq f x y | x <- s, y <- t x].
Proof. by []. Qed.
Lemma eq_allpairs (f1 f2 : forall x, T x -> R) s t :
(forall x, f1 x =1 f2 x) ->
[seq f1 x y | x <- s, y <- t x] = [seq f2 x y | x <- s, y <- t x].
Proof. by move=> eq_f; under eq_map do under eq_map do rewrite eq_f. Qed.
Lemma eq_allpairsr (f : forall x, T x -> R) s t1 t2 : (forall x, t1 x = t2 x) ->
[seq f x y | x <- s, y <- t1 x] = [seq f x y | x <- s, y <- t2 x].
Proof. by move=> eq_t; under eq_map do rewrite eq_t. Qed.
Lemma allpairs_cat f s1 s2 t :
[seq f x y | x <- s1 ++ s2, y <- t x] =
[seq f x y | x <- s1, y <- t x] ++ [seq f x y | x <- s2, y <- t x].
Proof. by rewrite map_cat flatten_cat. Qed.
Lemma allpairs_rcons f x s t :
[seq f x y | x <- rcons s x, y <- t x] =
[seq f x y | x <- s, y <- t x] ++ [seq f x y | y <- t x].
Proof. by rewrite -cats1 allpairs_cat allpairs1l. Qed.
Lemma allpairs_mapl f (g : S' -> S) s t :
[seq f x y | x <- map g s, y <- t x] = [seq f (g x) y | x <- s, y <- t (g x)].
Proof. by rewrite -map_comp. Qed.
Lemma allpairs_mapr f (g : forall x, T' x -> T x) s t :
[seq f x y | x <- s, y <- map (g x) (t x)] =
[seq f x (g x y) | x <- s, y <- t x].
Proof. by under eq_map do rewrite -map_comp. Qed.
End AllPairsDep.
Arguments allpairs_dep {S T R} f s t /.
Lemma map_allpairs S T R R' (g : R' -> R) f s t :
map g [seq f x y | x : S <- s, y : T x <- t x] =
[seq g (f x y) | x <- s, y <- t x].
Proof. by rewrite map_flatten allpairs_mapl allpairs_mapr. Qed.
Section AllPairsNonDep.
Variables (S T R : Type) (f : S -> T -> R).
Implicit Types (s : seq S) (t : seq T).
Definition allpairs s t := [seq f x y | x <- s, y <- t].
Lemma size_allpairs s t : size [seq f x y | x <- s, y <- t] = size s * size t.
Proof. by elim: s => //= x s IHs; rewrite size_cat size_map IHs. Qed.
End AllPairsNonDep.
Arguments allpairs {S T R} f s t /.
Section EqAllPairsDep.
Variables (S : eqType) (T : S -> eqType).
Implicit Types (R : eqType) (s : seq S) (t : forall x, seq (T x)).
Lemma allpairsPdep R (f : forall x, T x -> R) s t (z : R) :
reflect (exists x y, [/\ x \in s, y \in t x & z = f x y])
(z \in [seq f x y | x <- s, y <- t x]).
Proof.
apply: (iffP flatten_mapP); first by case=> x sx /mapP[y ty ->]; exists x, y.
by case=> x [y [sx ty ->]]; exists x; last apply: map_f.
Qed.
Variable R : eqType.
Implicit Type f : forall x, T x -> R.
Lemma allpairs_f_dep f s t x y :
x \in s -> y \in t x -> f x y \in [seq f x y | x <- s, y <- t x].
Proof. by move=> sx ty; apply/allpairsPdep; exists x, y. Qed.
Lemma eq_in_allpairs_dep f1 f2 s t :
{in s, forall x, {in t x, f1 x =1 f2 x}} <->
[seq f1 x y : R | x <- s, y <- t x] = [seq f2 x y | x <- s, y <- t x].
Proof.
split=> [eq_f | eq_fst x s_x].
by congr flatten; apply/eq_in_map=> x s_x; apply/eq_in_map/eq_f.
apply/eq_in_map; apply/eq_in_map: x s_x; apply/eq_from_flatten_shape => //.
by rewrite /shape -!map_comp; apply/eq_map=> x /=; rewrite !size_map.
Qed.
Lemma perm_allpairs_dep f s1 t1 s2 t2 :
perm_eq s1 s2 -> {in s1, forall x, perm_eq (t1 x) (t2 x)} ->
perm_eq [seq f x y | x <- s1, y <- t1 x] [seq f x y | x <- s2, y <- t2 x].
Proof.
elim: s1 s2 t1 t2 => [s2 t1 t2 |a s1 IH s2 t1 t2 perm_s2 perm_t1].
by rewrite perm_sym => /perm_nilP->.
have mem_a : a \in s2 by rewrite -(perm_mem perm_s2) inE eqxx.
rewrite -[s2](cat_take_drop (index a s2)).
rewrite allpairs_cat (drop_nth a) ?index_mem //= nth_index //=.
rewrite perm_sym perm_catC -catA perm_cat //; last first.
rewrite perm_catC -allpairs_cat.
rewrite -remE perm_sym IH // => [|x xI]; last first.
by apply: perm_t1; rewrite inE xI orbT.
by rewrite -(perm_cons a) (perm_trans perm_s2 (perm_to_rem _)).
have /perm_t1 : a \in a :: s1 by rewrite inE eqxx.
rewrite perm_sym; elim: (t2 a) (t1 a) => /= [s4|b s3 IH1 s4 perm_s4].
by rewrite perm_sym => /perm_nilP->.
have mem_b : b \in s4 by rewrite -(perm_mem perm_s4) inE eqxx.
rewrite -[s4](cat_take_drop (index b s4)).
rewrite map_cat /= (drop_nth b) ?index_mem //= nth_index //=.
rewrite perm_sym perm_catC /= perm_cons // perm_catC -map_cat.
rewrite -remE perm_sym IH1 // -(perm_cons b).
by apply: perm_trans perm_s4 (perm_to_rem _).
Qed.
Lemma mem_allpairs_dep f s1 t1 s2 t2 :
s1 =i s2 -> {in s1, forall x, t1 x =i t2 x} ->
[seq f x y | x <- s1, y <- t1 x] =i [seq f x y | x <- s2, y <- t2 x].
Proof.
move=> eq_s eq_t z; apply/allpairsPdep/allpairsPdep=> -[x [y [sx ty ->]]];
by exists x, y; rewrite -eq_s in sx *; rewrite eq_t in ty *.
Qed.
Lemma allpairs_uniq_dep f s t (st := [seq Tagged T y | x <- s, y <- t x]) :
let g (p : {x : S & T x}) : R := f (tag p) (tagged p) in
uniq s -> {in s, forall x, uniq (t x)} -> {in st &, injective g} ->
uniq [seq f x y | x <- s, y <- t x].
Proof.
move=> g Us Ut; rewrite -(map_allpairs g (existT T)) => /map_inj_in_uniq->{f g}.
elim: s Us => //= x s IHs /andP[s'x Us] in st Ut *; rewrite {st}cat_uniq.
rewrite {}IHs {Us}// ?andbT => [|x1 s_s1]; last exact/Ut/mem_behead.
have injT: injective (existT T x) by move=> y z /eqP; rewrite eq_Tagged => /eqP.
rewrite (map_inj_in_uniq (in2W injT)) {injT}Ut ?mem_head // has_sym has_map.
by apply: contra s'x => /hasP[y _ /allpairsPdep[z [_ [? _ /(congr1 tag)/=->]]]].
Qed.
End EqAllPairsDep.
Arguments allpairsPdep {S T R f s t z}.
Section MemAllPairs.
Variables (S : Type) (T : S -> Type) (R : eqType).
Implicit Types (f : forall x, T x -> R) (s : seq S).
Lemma perm_allpairs_catr f s t1 t2 :
perm_eql [seq f x y | x <- s, y <- t1 x ++ t2 x]
([seq f x y | x <- s, y <- t1 x] ++ [seq f x y | x <- s, y <- t2 x]).
Proof.
apply/permPl; rewrite perm_sym; elim: s => //= x s ihs.
by rewrite perm_catACA perm_cat ?map_cat.
Qed.
Lemma mem_allpairs_catr f s y0 t :
[seq f x y | x <- s, y <- y0 x ++ t x] =i
[seq f x y | x <- s, y <- y0 x] ++ [seq f x y | x <- s, y <- t x].
Proof. exact/perm_mem/permPl/perm_allpairs_catr. Qed.
Lemma perm_allpairs_consr f s y0 t :
perm_eql [seq f x y | x <- s, y <- y0 x :: t x]
([seq f x (y0 x) | x <- s] ++ [seq f x y | x <- s, y <- t x]).
Proof.
by apply/permPl; rewrite (perm_allpairs_catr _ _ (fun=> [:: _])) allpairs1r.
Qed.
Lemma mem_allpairs_consr f s t y0 :
[seq f x y | x <- s, y <- y0 x :: t x] =i
[seq f x (y0 x) | x <- s] ++ [seq f x y | x <- s, y <- t x].
Proof. exact/perm_mem/permPl/perm_allpairs_consr. Qed.
Lemma allpairs_rconsr f s y0 t :
perm_eql [seq f x y | x <- s, y <- rcons (t x) (y0 x)]
([seq f x y | x <- s, y <- t x] ++ [seq f x (y0 x) | x <- s]).
Proof.
apply/permPl; rewrite -(eq_allpairsr _ _ (fun=> cats1 _ _)).
by rewrite perm_allpairs_catr allpairs1r.
Qed.
Lemma mem_allpairs_rconsr f s t y0 :
[seq f x y | x <- s, y <- rcons (t x) (y0 x)] =i
([seq f x y | x <- s, y <- t x] ++ [seq f x (y0 x) | x <- s]).
Proof. exact/perm_mem/permPl/allpairs_rconsr. Qed.
End MemAllPairs.
Lemma all_allpairsP
(S : eqType) (T : S -> eqType) (R : Type)
(p : pred R) (f : forall x : S, T x -> R)
(s : seq S) (t : forall x : S, seq (T x)) :
reflect (forall (x : S) (y : T x), x \in s -> y \in t x -> p (f x y))
(all p [seq f x y | x <- s, y <- t x]).
Proof.
elim: s => [|x s IHs]; first by constructor.
rewrite /= all_cat all_map /preim.
apply/(iffP andP)=> [[/allP /= ? ? x' y x'_in_xs]|p_xs_t].
by move: x'_in_xs y => /[1!inE] /predU1P [-> //|? ?]; exact: IHs.
split; first by apply/allP => ?; exact/p_xs_t/mem_head.
by apply/IHs => x' y x'_in_s; apply: p_xs_t; rewrite inE x'_in_s orbT.
Qed.
Arguments all_allpairsP {S T R p f s t}.
Section EqAllPairs.
Variables S T R : eqType.
Implicit Types (f : S -> T -> R) (s : seq S) (t : seq T).
Lemma allpairsP f s t (z : R) :
reflect (exists p, [/\ p.1 \in s, p.2 \in t & z = f p.1 p.2])
(z \in [seq f x y | x <- s, y <- t]).
Proof.
by apply: (iffP allpairsPdep) => [[x[y]]|[[x y]]]; [exists (x, y)|exists x, y].
Qed.
Lemma allpairs_f f s t x y :
x \in s -> y \in t -> f x y \in [seq f x y | x <- s, y <- t].
Proof. exact: allpairs_f_dep. Qed.
Lemma eq_in_allpairs f1 f2 s t :
{in s & t, f1 =2 f2} <->
[seq f1 x y : R | x <- s, y <- t] = [seq f2 x y | x <- s, y <- t].
Proof.
split=> [eq_f | /eq_in_allpairs_dep-eq_f x y /eq_f/(_ y)//].
by apply/eq_in_allpairs_dep=> x /eq_f.
Qed.
Lemma perm_allpairs f s1 t1 s2 t2 :
perm_eq s1 s2 -> perm_eq t1 t2 ->
perm_eq [seq f x y | x <- s1, y <- t1] [seq f x y | x <- s2, y <- t2].
Proof. by move=> perm_s perm_t; apply: perm_allpairs_dep. Qed.
Lemma mem_allpairs f s1 t1 s2 t2 :
s1 =i s2 -> t1 =i t2 ->
[seq f x y | x <- s1, y <- t1] =i [seq f x y | x <- s2, y <- t2].
Proof. by move=> eq_s eq_t; apply: mem_allpairs_dep. Qed.
Lemma allpairs_uniq f s t (st := [seq (x, y) | x <- s, y <- t]) :
uniq s -> uniq t -> {in st &, injective (uncurry f)} ->
uniq [seq f x y | x <- s, y <- t].
Proof.
move=> Us Ut inj_f; rewrite -(map_allpairs (uncurry f) (@pair S T)) -/st.
rewrite map_inj_in_uniq // allpairs_uniq_dep {Us Ut st inj_f}//.
by apply: in2W => -[x1 y1] [x2 y2] /= [-> ->].
Qed.
End EqAllPairs.
Arguments allpairsP {S T R f s t z}.
Arguments perm_nilP {T s}.
Arguments perm_consP {T x s t}.
Section AllRel.
Variables (T S : Type) (r : T -> S -> bool).
Implicit Types (x : T) (y : S) (xs : seq T) (ys : seq S).
Definition allrel xs ys := all [pred x | all (r x) ys] xs.
Lemma allrel0l ys : allrel [::] ys. Proof. by []. Qed.
Lemma allrel0r xs : allrel xs [::]. Proof. by elim: xs. Qed.
Lemma allrel_consl x xs ys : allrel (x :: xs) ys = all (r x) ys && allrel xs ys.
Proof. by []. Qed.
Lemma allrel_consr xs y ys :
allrel xs (y :: ys) = all (r^~ y) xs && allrel xs ys.
Proof. exact: all_predI. Qed.
Lemma allrel_cons2 x y xs ys :
allrel (x :: xs) (y :: ys) =
[&& r x y, all (r x) ys, all (r^~ y) xs & allrel xs ys].
Proof. by rewrite /= allrel_consr -andbA. Qed.
Lemma allrel1l x ys : allrel [:: x] ys = all (r x) ys. Proof. exact: andbT. Qed.
Lemma allrel1r xs y : allrel xs [:: y] = all (r^~ y) xs.
Proof. by rewrite allrel_consr allrel0r andbT. Qed.
Lemma allrel_catl xs xs' ys :
allrel (xs ++ xs') ys = allrel xs ys && allrel xs' ys.
Proof. exact: all_cat. Qed.
Lemma allrel_catr xs ys ys' :
allrel xs (ys ++ ys') = allrel xs ys && allrel xs ys'.
Proof.
elim: ys => /= [|y ys ihys]; first by rewrite allrel0r.
by rewrite !allrel_consr ihys andbA.
Qed.
Lemma allrel_maskl m xs ys : allrel xs ys -> allrel (mask m xs) ys.
Proof.
by elim: m xs => [|[] m IHm] [|x xs] //= /andP [xys /IHm->]; rewrite ?xys.
Qed.
Lemma allrel_maskr m xs ys : allrel xs ys -> allrel xs (mask m ys).
Proof. by elim: xs => //= x xs IHxs /andP [/all_mask->]. Qed.
Lemma allrel_filterl a xs ys : allrel xs ys -> allrel (filter a xs) ys.
Proof. by rewrite filter_mask; apply: allrel_maskl. Qed.
Lemma allrel_filterr a xs ys : allrel xs ys -> allrel xs (filter a ys).
Proof. by rewrite filter_mask; apply: allrel_maskr. Qed.
Lemma allrel_allpairsE xs ys :
allrel xs ys = all id [seq r x y | x <- xs, y <- ys].
Proof. by elim: xs => //= x xs ->; rewrite all_cat all_map. Qed.
End AllRel.
Arguments allrel {T S} r xs ys : simpl never.
Arguments allrel0l {T S} r ys.
Arguments allrel0r {T S} r xs.
Arguments allrel_consl {T S} r x xs ys.
Arguments allrel_consr {T S} r xs y ys.
Arguments allrel1l {T S} r x ys.
Arguments allrel1r {T S} r xs y.
Arguments allrel_catl {T S} r xs xs' ys.
Arguments allrel_catr {T S} r xs ys ys'.
Arguments allrel_maskl {T S} r m xs ys.
Arguments allrel_maskr {T S} r m xs ys.
Arguments allrel_filterl {T S} r a xs ys.
Arguments allrel_filterr {T S} r a xs ys.
Arguments allrel_allpairsE {T S} r xs ys.
Notation all2rel r xs := (allrel r xs xs).
Lemma sub_in_allrel
{T S : Type} (P : {pred T}) (Q : {pred S}) (r r' : T -> S -> bool) :
{in P & Q, forall x y, r x y -> r' x y} ->
forall xs ys, all P xs -> all Q ys -> allrel r xs ys -> allrel r' xs ys.
Proof.
move=> rr' + ys; elim=> //= x xs IHxs /andP [Px Pxs] Qys.
rewrite !allrel_consl => /andP [+ {}/IHxs-> //]; rewrite andbT.
by elim: ys Qys => //= y ys IHys /andP [Qy Qys] /andP [/rr'-> // /IHys->].
Qed.
Lemma sub_allrel {T S : Type} (r r' : T -> S -> bool) :
(forall x y, r x y -> r' x y) ->
forall xs ys, allrel r xs ys -> allrel r' xs ys.
Proof.
by move=> rr' xs ys; apply/sub_in_allrel/all_predT/all_predT; apply: in2W.
Qed.
Lemma eq_in_allrel {T S : Type} (P : {pred T}) (Q : {pred S}) r r' :
{in P & Q, r =2 r'} ->
forall xs ys, all P xs -> all Q ys -> allrel r xs ys = allrel r' xs ys.
Proof.
move=> rr' xs ys Pxs Qys.
by apply/idP/idP; apply/sub_in_allrel/Qys/Pxs => ? ? ? ?; rewrite rr'.
Qed.
Lemma eq_allrel {T S : Type} (r r' : T -> S -> bool) :
r =2 r' -> allrel r =2 allrel r'.
Proof. by move=> rr' xs ys; apply/eq_in_allrel/all_predT/all_predT. Qed.
Lemma allrelC {T S : Type} (r : T -> S -> bool) xs ys :
allrel r xs ys = allrel (fun y => r^~ y) ys xs.
Proof. by elim: xs => [|x xs ih]; [elim: ys | rewrite allrel_consr -ih]. Qed.
Lemma allrel_mapl {T T' S : Type} (f : T' -> T) (r : T -> S -> bool) xs ys :
allrel r (map f xs) ys = allrel (fun x => r (f x)) xs ys.
Proof. exact: all_map. Qed.
Lemma allrel_mapr {T S S' : Type} (f : S' -> S) (r : T -> S -> bool) xs ys :
allrel r xs (map f ys) = allrel (fun x y => r x (f y)) xs ys.
Proof. by rewrite allrelC allrel_mapl allrelC. Qed.
Lemma allrelP {T S : eqType} {r : T -> S -> bool} {xs ys} :
reflect {in xs & ys, forall x y, r x y} (allrel r xs ys).
Proof. by rewrite allrel_allpairsE; exact: all_allpairsP. Qed.
Lemma allrelT {T S : Type} (xs : seq T) (ys : seq S) :
allrel (fun _ _ => true) xs ys = true.
Proof. by elim: xs => //= ? ?; rewrite allrel_consl all_predT. Qed.
Lemma allrel_relI {T S : Type} (r r' : T -> S -> bool) xs ys :
allrel (fun x y => r x y && r' x y) xs ys = allrel r xs ys && allrel r' xs ys.
Proof. by rewrite -all_predI; apply: eq_all => ?; rewrite /= -all_predI. Qed.
Lemma allrel_revl {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) :
allrel r (rev s1) s2 = allrel r s1 s2.
Proof. exact: all_rev. Qed.
Lemma allrel_revr {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) :
allrel r s1 (rev s2) = allrel r s1 s2.
Proof. by rewrite allrelC allrel_revl allrelC. Qed.
Lemma allrel_rev2 {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) :
allrel r (rev s1) (rev s2) = allrel r s1 s2.
Proof. by rewrite allrel_revr allrel_revl. Qed.
Lemma eq_allrel_meml {T : eqType} {S} (r : T -> S -> bool) (s1 s1' : seq T) s2 :
s1 =i s1' -> allrel r s1 s2 = allrel r s1' s2.
Proof. by move=> eqs1; apply: eq_all_r. Qed.
Lemma eq_allrel_memr {T} {S : eqType} (r : T -> S -> bool) s1 (s2 s2' : seq S) :
s2 =i s2' -> allrel r s1 s2 = allrel r s1 s2'.
Proof. by rewrite ![allrel _ s1 _]allrelC; apply: eq_allrel_meml. Qed.
Lemma eq_allrel_mem2 {T S : eqType} (r : T -> S -> bool)
(s1 s1' : seq T) (s2 s2' : seq S) :
s1 =i s1' -> s2 =i s2' -> allrel r s1 s2 = allrel r s1' s2'.
Proof. by move=> /eq_allrel_meml -> /eq_allrel_memr ->. Qed.
Section All2Rel.
Variable (T : nonPropType) (r : rel T).
Implicit Types (x y z : T) (xs : seq T).
Hypothesis (rsym : symmetric r).
Lemma all2rel1 x : all2rel r [:: x] = r x x.
Proof. by rewrite /allrel /= !andbT. Qed.
Lemma all2rel2 x y : all2rel r [:: x; y] = r x x && r y y && r x y.
Proof. by rewrite /allrel /= rsym; do 3 case: r. Qed.
Lemma all2rel_cons x xs :
all2rel r (x :: xs) = [&& r x x, all (r x) xs & all2rel r xs].
Proof.
rewrite allrel_cons2; congr andb; rewrite andbA -all_predI; congr andb.
by elim: xs => //= y xs ->; rewrite rsym andbb.
Qed.
End All2Rel.
Section Pairwise.
Variables (T : Type) (r : T -> T -> bool).
Implicit Types (x y : T) (xs ys : seq T).
Fixpoint pairwise xs : bool :=
if xs is x :: xs then all (r x) xs && pairwise xs else true.
Lemma pairwise_cons x xs : pairwise (x :: xs) = all (r x) xs && pairwise xs.
Proof. by []. Qed.
Lemma pairwise_cat xs ys :
pairwise (xs ++ ys) = [&& allrel r xs ys, pairwise xs & pairwise ys].
Proof. by elim: xs => //= x xs ->; rewrite all_cat -!andbA; bool_congr. Qed.
Lemma pairwise_rcons xs x :
pairwise (rcons xs x) = all (r^~ x) xs && pairwise xs.
Proof. by rewrite -cats1 pairwise_cat allrel1r andbT. Qed.
Lemma pairwise2 x y : pairwise [:: x; y] = r x y.
Proof. by rewrite /= !andbT. Qed.
Lemma pairwise_mask m xs : pairwise xs -> pairwise (mask m xs).
Proof.
by elim: m xs => [|[] m IHm] [|x xs] //= /andP [? ?]; rewrite ?IHm // all_mask.
Qed.
Lemma pairwise_filter a xs : pairwise xs -> pairwise (filter a xs).
Proof. by rewrite filter_mask; apply: pairwise_mask. Qed.
Lemma pairwiseP x0 xs :
reflect {in gtn (size xs) &, {homo nth x0 xs : i j / i < j >-> r i j}}
(pairwise xs).
Proof.
elim: xs => /= [|x xs IHxs]; first exact: (iffP idP).
apply: (iffP andP) => [[r_x_xs pxs] i j|Hnth]; rewrite -?topredE /= ?ltnS.
by case: i j => [|i] [|j] //= gti gtj ij; [exact/all_nthP | exact/IHxs].
split; last by apply/IHxs => // i j; apply/(Hnth i.+1 j.+1).
by apply/(all_nthP x0) => i gti; apply/(Hnth 0 i.+1).
Qed.
Lemma pairwise_all2rel :
reflexive r -> symmetric r -> forall xs, pairwise xs = all2rel r xs.
Proof.
by move=> r_refl r_sym; elim => //= x xs ->; rewrite all2rel_cons // r_refl.
Qed.
End Pairwise.
Arguments pairwise {T} r xs.
Arguments pairwise_cons {T} r x xs.
Arguments pairwise_cat {T} r xs ys.
Arguments pairwise_rcons {T} r xs x.
Arguments pairwise2 {T} r x y.
Arguments pairwise_mask {T r} m {xs}.
Arguments pairwise_filter {T r} a {xs}.
Arguments pairwiseP {T r} x0 {xs}.
Arguments pairwise_all2rel {T r} r_refl r_sym xs.
Lemma sub_in_pairwise {T : Type} (P : {pred T}) (r r' : rel T) :
{in P &, subrel r r'} ->
forall xs, all P xs -> pairwise r xs -> pairwise r' xs.
Proof.
move=> rr'; elim=> //= x xs IHxs /andP [Px Pxs] /andP [+ {}/IHxs->] //.
rewrite andbT; elim: xs Pxs => //= x' xs IHxs /andP [? ?] /andP [+ /IHxs->] //.
by rewrite andbT; apply: rr'.
Qed.
Lemma sub_pairwise {T : Type} (r r' : rel T) xs :
subrel r r' -> pairwise r xs -> pairwise r' xs.
Proof. by move=> rr'; apply/sub_in_pairwise/all_predT; apply: in2W. Qed.
Lemma eq_in_pairwise {T : Type} (P : {pred T}) (r r' : rel T) :
{in P &, r =2 r'} -> forall xs, all P xs -> pairwise r xs = pairwise r' xs.
Proof.
move=> rr' xs Pxs.
by apply/idP/idP; apply/sub_in_pairwise/Pxs => ? ? ? ?; rewrite rr'.
Qed.
Lemma eq_pairwise {T : Type} (r r' : rel T) :
r =2 r' -> pairwise r =i pairwise r'.
Proof. by move=> rr' xs; apply/eq_in_pairwise/all_predT. Qed.
Lemma pairwise_map {T T' : Type} (f : T' -> T) (r : rel T) xs :
pairwise r (map f xs) = pairwise (relpre f r) xs.
Proof. by elim: xs => //= x xs ->; rewrite all_map. Qed.
Lemma pairwise_relI {T : Type} (r r' : rel T) (s : seq T) :
pairwise [rel x y | r x y && r' x y] s = pairwise r s && pairwise r' s.
Proof. by elim: s => //= x s ->; rewrite andbACA all_predI. Qed.
Section EqPairwise.
Variables (T : eqType) (r : T -> T -> bool).
Implicit Types (xs ys : seq T).
Lemma subseq_pairwise xs ys : subseq xs ys -> pairwise r ys -> pairwise r xs.
Proof. by case/subseqP => m _ ->; apply: pairwise_mask. Qed.
Lemma uniq_pairwise xs : uniq xs = pairwise [rel x y | x != y] xs.
Proof.
elim: xs => //= x xs ->; congr andb; rewrite -has_pred1 -all_predC.
by elim: xs => //= x' xs ->; case: eqVneq.
Qed.
Lemma pairwise_uniq xs : irreflexive r -> pairwise r xs -> uniq xs.
Proof.
move=> r_irr; rewrite uniq_pairwise; apply/sub_pairwise => x y.
by apply: contraTneq => ->; rewrite r_irr.
Qed.
Lemma pairwise_eq : antisymmetric r ->
forall xs ys, pairwise r xs -> pairwise r ys -> perm_eq xs ys -> xs = ys.
Proof.
move=> r_asym; elim=> [|x xs IHxs] [|y ys] //=; try by move=> ? ? /perm_size.
move=> /andP [r_x_xs pxs] /andP [r_y_ys pys] eq_xs_ys.
move: (mem_head y ys) (mem_head x xs).
rewrite -(perm_mem eq_xs_ys) [x \in _](perm_mem eq_xs_ys) !inE.
case: eqVneq eq_xs_ys => /= [->|ne_xy] eq_xs_ys ys_x xs_y.
by rewrite (IHxs ys) // -(perm_cons x).
by case/eqP: ne_xy; apply: r_asym; rewrite (allP r_x_xs) ?(allP r_y_ys).
Qed.
Lemma pairwise_trans s : antisymmetric r ->
pairwise r s -> {in s & &, transitive r}.
Proof.
move=> /(_ _ _ _)/eqP r_anti + y x z => /pairwiseP-/(_ y) ltP ys xs zs.
have [-> //|neqxy] := eqVneq x y; have [-> //|neqzy] := eqVneq z y.
move=> lxy lyz; move: ys xs zs lxy neqxy lyz neqzy.
move=> /(nthP y)[j jlt <-] /(nthP y)[i ilt <-] /(nthP y)[k klt <-].
have [ltij|ltji|->] := ltngtP i j; last 2 first.
- by move=> leij; rewrite r_anti// leij ltP.
- by move=> lejj; rewrite r_anti// lejj.
move=> _ _; have [ltjk|ltkj|->] := ltngtP j k; last 2 first.
- by move=> lejk; rewrite r_anti// lejk ltP.
- by move=> lekk; rewrite r_anti// lekk.
by move=> _ _; apply: (ltP) => //; apply: ltn_trans ltjk.
Qed.
End EqPairwise.
Arguments subseq_pairwise {T r xs ys}.
Arguments uniq_pairwise {T} xs.
Arguments pairwise_uniq {T r xs}.
Arguments pairwise_eq {T r} r_asym {xs ys}.
Section Permutations.
Variable T : eqType.
Implicit Types (x : T) (s t : seq T) (bs : seq (T * nat)) (acc : seq (seq T)).
Fixpoint incr_tally bs x :=
if bs isn't b :: bs then [:: (x, 1)] else
if x == b.1 then (x, b.2.+1) :: bs else b :: incr_tally bs x.
Definition tally s := foldl incr_tally [::] s.
Definition wf_tally :=
[qualify a bs : seq (T * nat) | uniq (unzip1 bs) && (0 \notin unzip2 bs)].
Definition tally_seq bs := flatten [seq nseq b.2 b.1 | b <- bs].
Local Notation tseq := tally_seq.
Lemma size_tally_seq bs : size (tally_seq bs) = sumn (unzip2 bs).
Proof.
by rewrite size_flatten /shape -map_comp; under eq_map do rewrite /= size_nseq.
Qed.
Lemma tally_seqK : {in wf_tally, cancel tally_seq tally}.
Proof.
move=> bs /andP[]; elim: bs => [|[x [|n]] bs IHbs] //= /andP[bs'x Ubs] bs'0.
rewrite inE /tseq /tally /= -[n.+1]addn1 in bs'0 *.
elim: n 1 => /= [|n IHn] m; last by rewrite eqxx IHn addnS.
rewrite -{}[in RHS]IHbs {Ubs bs'0}// /tally /tally_seq add0n.
elim: bs bs'x [::] => [|[y n] bs IHbs] //= /[1!inE] /norP[y'x bs'x].
by elim: n => [|n IHn] bs1 /=; [rewrite IHbs | rewrite eq_sym ifN // IHn].
Qed.
Lemma incr_tallyP x : {homo incr_tally^~ x : bs / bs \in wf_tally}.
Proof.
move=> bs /andP[]; rewrite unfold_in.
elim: bs => [|[y [|n]] bs IHbs] //= /andP[bs'y Ubs] /[1!inE] /= bs'0.
have [<- | y'x] /= := eqVneq y; first by rewrite bs'y Ubs.
rewrite -andbA {}IHbs {Ubs bs'0}// andbT.
elim: bs bs'y => [|b bs IHbs] /=; rewrite inE ?y'x // => /norP[b'y bs'y].
by case: ifP => _; rewrite /= inE negb_or ?y'x // b'y IHbs.
Qed.
Lemma tallyP s : tally s \is a wf_tally.
Proof.
rewrite /tally; set bs := [::]; have: bs \in wf_tally by [].
by elim: s bs => //= x s IHs bs /(incr_tallyP x)/IHs.
Qed.
Lemma tallyK s : perm_eq (tally_seq (tally s)) s.
Proof.
rewrite -[s in perm_eq _ s]cats0 -[nil]/(tseq [::]) /tally.
elim: s [::] => //= x s IHs bs; rewrite {IHs}(permPl (IHs _)).
rewrite perm_sym -cat1s perm_catCA {s}perm_cat2l.
elim: bs => //= b bs IHbs; case: eqP => [-> | _] //=.
by rewrite -cat1s perm_catCA perm_cat2l.
Qed.
Lemma tallyEl s : perm_eq (unzip1 (tally s)) (undup s).
Proof.
have /andP[Ubs bs'0] := tallyP s; set bs := tally s in Ubs bs'0 *.
rewrite uniq_perm ?undup_uniq {Ubs}// => x.
rewrite mem_undup -(perm_mem (tallyK s)) -/bs.
elim: bs => [|[y [|m]] bs IHbs] //= in bs'0 *.
by rewrite inE IHbs // mem_cat mem_nseq.
Qed.
Lemma tallyE s : perm_eq (tally s) [seq (x, count_mem x s) | x <- undup s].
Proof.
have /andP[Ubs _] := tallyP s; pose b := [fun s x => (x, count_mem x (tseq s))].
suffices /permPl->: perm_eq (tally s) (map (b (tally s)) (unzip1 (tally s))).
congr perm_eq: (perm_map (b (tally s)) (tallyEl s)).
by under eq_map do rewrite /= (permP (tallyK s)).
elim: (tally s) Ubs => [|[x m] bs IH] //= /andP[bs'x /IH-IHbs {IH}].
rewrite /tseq /= -/(tseq _) count_cat count_nseq /= eqxx mul1n.
rewrite (count_memPn _) ?addn0 ?perm_cons; last first.
apply: contra bs'x; elim: {b IHbs}bs => //= b bs IHbs.
by rewrite mem_cat mem_nseq inE andbC; case: (_ == _).
congr perm_eq: IHbs; apply/eq_in_map=> y bs_y; congr (y, _).
by rewrite count_cat count_nseq /= (negPf (memPnC bs'x y bs_y)).
Qed.
Lemma perm_tally s1 s2 : perm_eq s1 s2 -> perm_eq (tally s1) (tally s2).
Proof.
move=> eq_s12; apply: (@perm_trans _ [seq (x, count_mem x s2) | x <- undup s1]).
by congr perm_eq: (tallyE s1); under eq_map do rewrite (permP eq_s12).
by rewrite (permPr (tallyE s2)); apply/perm_map/perm_undup/(perm_mem eq_s12).
Qed.
Lemma perm_tally_seq bs1 bs2 :
perm_eq bs1 bs2 -> perm_eq (tally_seq bs1) (tally_seq bs2).
Proof. by move=> Ebs12; rewrite perm_flatten ?perm_map. Qed.
Local Notation perm_tseq := perm_tally_seq.
Lemma perm_count_undup s :
perm_eq (flatten [seq nseq (count_mem x s) x | x <- undup s]) s.
Proof.
by rewrite -(permPr (tallyK s)) (permPr (perm_tseq (tallyE s))) /tseq -map_comp.
Qed.
Local Fixpoint cons_perms_ perms_rec (s : seq T) bs bs2 acc :=
if bs isn't b :: bs1 then acc else
if b isn't (x, m.+1) then cons_perms_ perms_rec s bs1 bs2 acc else
let acc_xs := perms_rec (x :: s) ((x, m) :: bs1 ++ bs2) acc in
cons_perms_ perms_rec s bs1 (b :: bs2) acc_xs.
Local Fixpoint perms_rec n s bs acc :=
if n isn't n.+1 then s :: acc else cons_perms_ (perms_rec n) s bs [::] acc.
Local Notation cons_perms n := (cons_perms_ (perms_rec n) [::]).
Definition permutations s := perms_rec (size s) [::] (tally s) [::].
Let permsP s : exists n bs,
[/\ permutations s = perms_rec n [::] bs [::],
size (tseq bs) == n, perm_eq (tseq bs) s & uniq (unzip1 bs)].
Proof.
have /andP[Ubs _] := tallyP s; exists (size s), (tally s).
by rewrite (perm_size (tallyK s)) tallyK.
Qed.
Local Notation bsCA := (permEl (perm_catCA _ [:: _] _)).
Let cons_permsE : forall n x bs bs1 bs2,
let cp := cons_perms n bs bs2 in let perms s := perms_rec n s bs1 [::] in
cp (perms [:: x]) = cp [::] ++ [seq rcons t x | t <- perms [::]].
Proof.
pose is_acc f := forall acc, f acc = f [::] ++ acc. (* f is accumulating. *)
have cpE: forall f & forall s bs, is_acc (f s bs), is_acc (cons_perms_ f _ _ _).
move=> s bs bs2 f fE acc; elim: bs => [|[x [|m]] bs IHbs] //= in s bs2 acc *.
by rewrite fE IHbs catA -IHbs.
have prE: is_acc (perms_rec _ _ _) by elim=> //= n IHn s bs; apply: cpE.
pose has_suffix f := forall s : seq T, f s = [seq t ++ s | t <- f [::]].
suffices prEs n bs: has_suffix (fun s => perms_rec n s bs [::]).
move=> n x bs bs1 bs2 /=; rewrite cpE // prEs.
by under eq_map do rewrite cats1.
elim: n bs => //= n IHn bs s; elim: bs [::] => [|[x [|m]] bs IHbs] //= bs1.
rewrite cpE // IHbs IHn [in RHS]cpE // [in RHS]IHn map_cat -map_comp.
by congr (_ ++ _); apply: eq_map => t /=; rewrite -catA.
Qed.
Lemma mem_permutations s t : (t \in permutations s) = perm_eq t s.
Proof.
have{s} [n [bs [-> Dn /permPr<- _]]] := permsP s.
elim: n => [|n IHn] /= in t bs Dn *.
by rewrite inE (nilP Dn); apply/eqP/perm_nilP.
rewrite -[bs in tseq bs]cats0 in Dn *; have x0 : T by case: (tseq _) Dn.
rewrite -[RHS](@andb_idl (last x0 t \in tseq bs)); last first.
case/lastP: t {IHn} => [|t x] Dt; first by rewrite -(perm_size Dt) in Dn.
by rewrite -[bs]cats0 -(perm_mem Dt) last_rcons mem_rcons mem_head.
elim: bs [::] => [|[x [|m]] bs IHbs] //= bs2 in Dn *.
rewrite cons_permsE -!cat_cons !mem_cat (mem_nseq m.+1) orbC andb_orl.
rewrite {}IHbs ?(perm_size (perm_tseq bsCA)) //= (permPr (perm_tseq bsCA)).
congr (_ || _); apply/mapP/andP=> [[t1 Dt1 ->] | [/eqP]].
by rewrite last_rcons perm_rcons perm_cons IHn in Dt1 *.
case/lastP: t => [_ /perm_size//|t y]; rewrite last_rcons perm_rcons => ->.
by rewrite perm_cons; exists t; rewrite ?IHn.
Qed.
Lemma permutations_uniq s : uniq (permutations s).
Proof.
have{s} [n [bs [-> Dn _ Ubs]]] := permsP s.
elim: n => //= n IHn in bs Dn Ubs *; rewrite -[bs]cats0 /unzip1 in Dn Ubs.
elim: bs [::] => [|[x [|m]] bs IHbs] //= bs2 in Dn Ubs *.
by case/andP: Ubs => _ /IHbs->.
rewrite /= cons_permsE cat_uniq has_sym andbCA andbC.
rewrite {}IHbs; first 1 last; first by rewrite (perm_size (perm_tseq bsCA)).
by rewrite (perm_uniq (perm_map _ bsCA)).
rewrite (map_inj_uniq (rcons_injl x)) {}IHn {Dn}//=.
have: x \notin unzip1 bs by apply: contraL Ubs; rewrite map_cat mem_cat => ->.
move: {bs2 m Ubs}(perms_rec n _ _ _) (_ :: bs2) => ts.
elim: bs => [|[y [|m]] bs IHbs] //= /[1!inE] bs2 /norP[x'y /IHbs//].
rewrite cons_permsE has_cat negb_or has_map => ->.
by apply/hasPn=> t _; apply: contra x'y => /mapP[t1 _ /rcons_inj[_ ->]].
Qed.
Notation perms := permutations.
Lemma permutationsE s :
0 < size s ->
perm_eq (perms s) [seq x :: t | x <- undup s, t <- perms (rem x s)].
Proof.
move=> nt_s; apply/uniq_perm=> [||t]; first exact: permutations_uniq.
apply/allpairs_uniq_dep=> [|x _|]; rewrite ?undup_uniq ?permutations_uniq //.
by case=> [_ _] [x t] _ _ [-> ->].
rewrite mem_permutations; apply/idP/allpairsPdep=> [Dt | [x [t1 []]]].
rewrite -(perm_size Dt) in nt_s; case: t nt_s => // x t _ in Dt *.
have s_x: x \in s by rewrite -(perm_mem Dt) mem_head.
exists x, t; rewrite mem_undup mem_permutations; split=> //.
by rewrite -(perm_cons x) (permPl Dt) perm_to_rem.
rewrite mem_undup mem_permutations -(perm_cons x) => s_x Dt1 ->.
by rewrite (permPl Dt1) perm_sym perm_to_rem.
Qed.
Lemma permutationsErot x s (le_x := fun t => iota 0 (index x t + 1)) :
perm_eq (perms (x :: s)) [seq rot i (x :: t) | t <- perms s, i <- le_x t].
Proof.
have take'x t i: i <= index x t -> i <= size t /\ x \notin take i t.
move=> le_i_x; have le_i_t: i <= size t := leq_trans le_i_x (index_size x t).
case: (nthP x) => // -[j lt_j_i /eqP]; rewrite size_takel // in lt_j_i.
by rewrite nth_take // [_ == _](before_find x (leq_trans lt_j_i le_i_x)).
pose xrot t i := rot i (x :: t); pose xrotV t := index x (rev (rot 1 t)).
have xrotK t: {in le_x t, cancel (xrot t) xrotV}.
move=> i; rewrite mem_iota addn1 /xrotV => /take'x[le_i_t ti'x].
rewrite -rotD ?rev_cat //= rev_cons cat_rcons index_cat mem_rev size_rev.
by rewrite ifN // size_takel //= eqxx addn0.
apply/uniq_perm=> [||t]; first exact: permutations_uniq.
apply/allpairs_uniq_dep=> [|t _|]; rewrite ?permutations_uniq ?iota_uniq //.
move=> _ _ /allpairsPdep[t [i [_ ? ->]]] /allpairsPdep[u [j [_ ? ->]]] Etu.
have Eij: i = j by rewrite -(xrotK t i) // /xrot Etu xrotK.
by move: Etu; rewrite Eij => /rot_inj[->].
rewrite mem_permutations; apply/esym; apply/allpairsPdep/idP=> [[u [i]] | Dt].
rewrite mem_permutations => -[Du _ /(canLR (rotK i))]; rewrite /rotr.
by set j := (j in rot j _) => Dt; apply/perm_consP; exists j, u.
pose r := rev (rot 1 t); pose i := index x r; pose u := rev (take i r).
have r_x: x \in r by rewrite mem_rev mem_rot (perm_mem Dt) mem_head.
have [v Duv]: {v | rot i (x :: u ++ v) = t}; first exists (rev (drop i.+1 r)).
rewrite -rev_cat -rev_rcons -rot1_cons -cat_cons -(nth_index x r_x).
by rewrite -drop_nth ?index_mem // rot_rot !rev_rot revK rotK rotrK.
exists (u ++ v), i; rewrite mem_permutations -(perm_cons x) -(perm_rot i) Duv.
rewrite mem_iota addn1 ltnS /= index_cat mem_rev size_rev.
by have /take'x[le_i_t ti'x] := leqnn i; rewrite ifN ?size_takel ?leq_addr.
Qed.
Lemma size_permutations s : uniq s -> size (permutations s) = (size s)`!.
Proof.
move Dn: (size s) => n Us; elim: n s => [[]|n IHn s] //= in Dn Us *.
rewrite (perm_size (permutationsE _)) ?Dn // undup_id // factS -Dn.
rewrite -(size_iota 0 n`!) -(size_allpairs (fun=>id)) !size_allpairs_dep.
by apply/congr1/eq_in_map=> x sx; rewrite size_iota IHn ?size_rem ?Dn ?rem_uniq.
Qed.
Lemma permutations_all_uniq s : uniq s -> all uniq (permutations s).
Proof.
by move=> Us; apply/allP=> t; rewrite mem_permutations => /perm_uniq->.
Qed.
Lemma perm_permutations s t :
perm_eq s t -> perm_eq (permutations s) (permutations t).
Proof.
move=> Est; apply/uniq_perm; try exact: permutations_uniq.
by move=> u; rewrite !mem_permutations (permPr Est).
Qed.
End Permutations.
|
PointsPi.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.AlgebraicGeometry.Morphisms.Immersion
/-!
# `Π Rᵢ`-Points of Schemes
We show that the canonical map `X(Π Rᵢ) ⟶ Π X(Rᵢ)` (`AlgebraicGeometry.pointsPi`)
is injective and surjective under various assumptions
-/
open CategoryTheory Limits PrimeSpectrum
namespace AlgebraicGeometry
universe u v
variable {ι : Type u} (R : ι → CommRingCat.{u})
lemma Ideal.span_eq_top_of_span_image_evalRingHom
{ι} {R : ι → Type*} [∀ i, CommRing (R i)] (s : Set (Π i, R i))
(hs : s.Finite) (hs' : ∀ i, Ideal.span (Pi.evalRingHom (R ·) i '' s) = ⊤) :
Ideal.span s = ⊤ := by
simp only [Ideal.eq_top_iff_one, ← Subtype.range_val (s := s), ← Set.range_comp,
Finsupp.mem_ideal_span_range_iff_exists_finsupp] at hs' ⊢
choose f hf using hs'
have : Fintype s := hs.fintype
refine ⟨Finsupp.equivFunOnFinite.symm fun i x ↦ f x i, ?_⟩
ext i
simpa [Finsupp.sum_fintype] using hf i
lemma eq_top_of_sigmaSpec_subset_of_isCompact
(U : Spec(Π i, R i).Opens) (V : Set Spec(Π i, R i))
(hV : ↑(sigmaSpec R).opensRange ⊆ V)
(hV' : IsCompact (X := Spec(Π i, R i)) V)
(hVU : V ⊆ U) : U = ⊤ := by
obtain ⟨s, hs⟩ := (PrimeSpectrum.isOpen_iff _).mp U.2
obtain ⟨t, hts, ht, ht'⟩ : ∃ t ⊆ s, t.Finite ∧ V ⊆ ⋃ i ∈ t, (basicOpen i).1 := by
obtain ⟨t, ht⟩ := hV'.elim_finite_subcover
(fun i : s ↦ (basicOpen i.1).1) (fun _ ↦ (basicOpen _).2)
(by simpa [← Set.compl_iInter, ← zeroLocus_iUnion₂ (κ := (· ∈ s)), ← hs])
exact ⟨t.map (Function.Embedding.subtype _), by simp, Finset.finite_toSet _, by simpa using ht⟩
replace ht' : V ⊆ (zeroLocus t)ᶜ := by
simpa [← Set.compl_iInter, ← zeroLocus_iUnion₂ (κ := (· ∈ t))] using ht'
have (i : _) : Ideal.span (Pi.evalRingHom (R ·) i '' t) = ⊤ := by
rw [← zeroLocus_empty_iff_eq_top, zeroLocus_span, ← preimage_comap_zeroLocus,
← Set.compl_univ_iff, ← Set.preimage_compl, Set.preimage_eq_univ_iff]
trans (Sigma.ι _ i ≫ sigmaSpec R).opensRange.1
· simp; rfl
· rw [Scheme.Hom.opensRange_comp]
exact (Set.image_subset_range _ _).trans (hV.trans ht')
have : Ideal.span s = ⊤ := top_le_iff.mp
((Ideal.span_eq_top_of_span_image_evalRingHom _ ht this).ge.trans (Ideal.span_mono hts))
simpa [← zeroLocus_span s, zeroLocus_empty_iff_eq_top.mpr this] using hs
lemma eq_bot_of_comp_quotientMk_eq_sigmaSpec (I : Ideal (Π i, R i))
(f : (∐ fun i ↦ Spec (R i)) ⟶ Spec((Π i, R i) ⧸ I))
(hf : f ≫ Spec.map (CommRingCat.ofHom (Ideal.Quotient.mk I)) = sigmaSpec R) :
I = ⊥ := by
refine le_bot_iff.mp fun x hx ↦ ?_
ext i
simpa [← Category.assoc, Ideal.Quotient.eq_zero_iff_mem.mpr hx] using
congr((Spec.preimage (Sigma.ι (Spec <| R ·) i ≫ $hf)).hom x).symm
/-- If `V` is a locally closed subscheme of `Spec (Π Rᵢ)` containing `∐ Spec Rᵢ`, then
`V = Spec (Π Rᵢ)`. -/
lemma isIso_of_comp_eq_sigmaSpec {V : Scheme}
(f : (∐ fun i ↦ Spec (R i)) ⟶ V) (g : V ⟶ Spec(Π i, R i))
[IsImmersion g] [CompactSpace V]
(hU' : f ≫ g = sigmaSpec R) : IsIso g := by
have : g.coborderRange = ⊤ := by
apply eq_top_of_sigmaSpec_subset_of_isCompact (hVU := subset_coborder)
· simpa only [← hU'] using Set.range_comp_subset_range f.base g.base
· exact isCompact_range g.base.hom.2
have : IsClosedImmersion g := by
have : IsIso g.coborderRange.ι := by rw [this, ← Scheme.topIso_hom]; infer_instance
rw [← g.liftCoborder_ι]
infer_instance
obtain ⟨I, e, rfl⟩ := IsClosedImmersion.Spec_iff.mp this
obtain rfl := eq_bot_of_comp_quotientMk_eq_sigmaSpec R I (f ≫ e.hom) (by rwa [Category.assoc])
convert_to IsIso (e.hom ≫ Spec.map (RingEquiv.quotientBot _).toCommRingCatIso.inv)
infer_instance
variable (X : Scheme)
/-- The canonical map `X(Π Rᵢ) ⟶ Π X(Rᵢ)`.
This is injective if `X` is quasi-separated, surjective if `X` is affine,
or if `X` is compact and each `Rᵢ` is local. -/
noncomputable
def pointsPi : (Spec(Π i, R i) ⟶ X) → Π i, Spec (R i) ⟶ X :=
fun f i ↦ Spec.map (CommRingCat.ofHom (Pi.evalRingHom (R ·) i)) ≫ f
lemma pointsPi_injective [QuasiSeparatedSpace X] : Function.Injective (pointsPi R X) := by
rintro f g e
have := isIso_of_comp_eq_sigmaSpec R (V := equalizer f g)
(equalizer.lift (sigmaSpec R) (by ext1 i; simpa using congr_fun e i))
(equalizer.ι f g) (by simp)
rw [← cancel_epi (equalizer.ι f g), equalizer.condition]
lemma pointsPi_surjective_of_isAffine [IsAffine X] : Function.Surjective (pointsPi R X) := by
rintro f
refine ⟨Spec.map (CommRingCat.ofHom
(Pi.ringHom fun i ↦ (Spec.preimage (f i ≫ X.isoSpec.hom)).1)) ≫ X.isoSpec.inv, ?_⟩
ext i : 1
simp only [pointsPi, ← Spec.map_comp_assoc, Iso.comp_inv_eq]
exact Spec.map_preimage _
lemma pointsPi_surjective [CompactSpace X] [∀ i, IsLocalRing (R i)] :
Function.Surjective (pointsPi R X) := by
intro f
let 𝒰 : X.OpenCover := X.affineCover.finiteSubcover
have (i : _) : IsAffine (𝒰.obj i) := isAffine_Spec _
have (i : _) : ∃ j, Set.range (f i).base ⊆ (𝒰.map j).opensRange := by
refine ⟨𝒰.f ((f i).base (IsLocalRing.closedPoint (R i))), ?_⟩
rintro _ ⟨x, rfl⟩
exact ((IsLocalRing.specializes_closedPoint x).map (f i).base.hom.2).mem_open
(𝒰.map _).opensRange.2 (𝒰.covers _)
choose j hj using this
have (j₀ : _) := pointsPi_surjective_of_isAffine (ι := { i // j i = j₀ }) (R ·) (𝒰.obj j₀)
(fun i ↦ IsOpenImmersion.lift (𝒰.map j₀) (f i.1) (by rcases i with ⟨i, rfl⟩; exact hj i))
choose g hg using this
simp_rw [funext_iff, pointsPi] at hg
let R' (j₀) := CommRingCat.of (Π i : { i // j i = j₀ }, R i)
let e : (Π i, R i) ≃+* Π j₀, R' j₀ :=
{ toFun f _ i := f i
invFun f i := f _ ⟨i, rfl⟩
right_inv _ := funext₂ fun j₀ i ↦ by rcases i with ⟨i, rfl⟩; rfl
map_mul' _ _ := rfl
map_add' _ _ := rfl }
refine ⟨Spec.map (CommRingCat.ofHom e.symm.toRingHom) ≫ inv (sigmaSpec R') ≫
Sigma.desc fun j₀ ↦ g j₀ ≫ 𝒰.map j₀, ?_⟩
ext i : 1
have : (Pi.evalRingHom (R ·) i).comp e.symm.toRingHom =
(Pi.evalRingHom _ ⟨i, rfl⟩).comp (Pi.evalRingHom (R' ·) (j i)) := rfl
rw [pointsPi, ← Spec.map_comp_assoc, ← CommRingCat.ofHom_comp, this, CommRingCat.ofHom_comp,
Spec.map_comp_assoc, ← ι_sigmaSpec R', Category.assoc, IsIso.hom_inv_id_assoc,
Sigma.ι_desc, ← Category.assoc, hg, IsOpenImmersion.lift_fac]
end AlgebraicGeometry
|
Equiv.lean
|
/-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import Mathlib.Algebra.Algebra.Hom
import Mathlib.Algebra.Ring.Action.Group
/-!
# Isomorphisms of `R`-algebras
This file defines bundled isomorphisms of `R`-algebras.
## Main definitions
* `AlgEquiv R A B`: the type of `R`-algebra isomorphisms between `A` and `B`.
## Notations
* `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`.
-/
universe u v w u₁ v₁
/-- An equivalence of algebras (denoted as `A ≃ₐ[R] B`)
is an equivalence of rings commuting with the actions of scalars. -/
structure AlgEquiv (R : Type u) (A : Type v) (B : Type w) [CommSemiring R] [Semiring A] [Semiring B]
[Algebra R A] [Algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B where
/-- An equivalence of algebras commutes with the action of scalars. -/
protected commutes' : ∀ r : R, toFun (algebraMap R A r) = algebraMap R B r
attribute [nolint docBlame] AlgEquiv.toRingEquiv
attribute [nolint docBlame] AlgEquiv.toEquiv
attribute [nolint docBlame] AlgEquiv.toAddEquiv
attribute [nolint docBlame] AlgEquiv.toMulEquiv
@[inherit_doc]
notation:50 A " ≃ₐ[" R "] " A' => AlgEquiv R A A'
/-- `AlgEquivClass F R A B` states that `F` is a type of algebra structure preserving
equivalences. You should extend this class when you extend `AlgEquiv`. -/
class AlgEquivClass (F : Type*) (R A B : outParam Type*) [CommSemiring R] [Semiring A]
[Semiring B] [Algebra R A] [Algebra R B] [EquivLike F A B] : Prop
extends RingEquivClass F A B where
/-- An equivalence of algebras commutes with the action of scalars. -/
commutes : ∀ (f : F) (r : R), f (algebraMap R A r) = algebraMap R B r
namespace AlgEquivClass
-- See note [lower instance priority]
instance (priority := 100) toAlgHomClass (F R A B : Type*) [CommSemiring R] [Semiring A]
[Semiring B] [Algebra R A] [Algebra R B] [EquivLike F A B] [h : AlgEquivClass F R A B] :
AlgHomClass F R A B :=
{ h with }
instance (priority := 100) toLinearEquivClass (F R A B : Type*) [CommSemiring R]
[Semiring A] [Semiring B] [Algebra R A] [Algebra R B]
[EquivLike F A B] [h : AlgEquivClass F R A B] : LinearEquivClass F R A B :=
{ h with map_smulₛₗ := fun f => map_smulₛₗ f }
/-- Turn an element of a type `F` satisfying `AlgEquivClass F R A B` into an actual `AlgEquiv`.
This is declared as the default coercion from `F` to `A ≃ₐ[R] B`. -/
@[coe]
def toAlgEquiv {F R A B : Type*} [CommSemiring R] [Semiring A] [Semiring B] [Algebra R A]
[Algebra R B] [EquivLike F A B] [AlgEquivClass F R A B] (f : F) : A ≃ₐ[R] B :=
{ (f : A ≃ B), (f : A ≃+* B) with commutes' := commutes f }
instance (F R A B : Type*) [CommSemiring R] [Semiring A] [Semiring B] [Algebra R A] [Algebra R B]
[EquivLike F A B] [AlgEquivClass F R A B] : CoeTC F (A ≃ₐ[R] B) :=
⟨toAlgEquiv⟩
end AlgEquivClass
namespace AlgEquiv
universe uR uA₁ uA₂ uA₃ uA₁' uA₂' uA₃'
variable {R : Type uR}
variable {A₁ : Type uA₁} {A₂ : Type uA₂} {A₃ : Type uA₃}
variable {A₁' : Type uA₁'} {A₂' : Type uA₂'} {A₃' : Type uA₃'}
section Semiring
variable [CommSemiring R] [Semiring A₁] [Semiring A₂] [Semiring A₃]
variable [Semiring A₁'] [Semiring A₂'] [Semiring A₃']
variable [Algebra R A₁] [Algebra R A₂] [Algebra R A₃]
variable [Algebra R A₁'] [Algebra R A₂'] [Algebra R A₃']
variable (e : A₁ ≃ₐ[R] A₂)
section coe
instance : EquivLike (A₁ ≃ₐ[R] A₂) A₁ A₂ where
coe f := f.toFun
inv f := f.invFun
left_inv f := f.left_inv
right_inv f := f.right_inv
coe_injective' f g h₁ h₂ := by
obtain ⟨⟨f,_⟩,_⟩ := f
obtain ⟨⟨g,_⟩,_⟩ := g
congr
/-- Helper instance since the coercion is not always found. -/
instance : FunLike (A₁ ≃ₐ[R] A₂) A₁ A₂ where
coe := DFunLike.coe
coe_injective' := DFunLike.coe_injective'
instance : AlgEquivClass (A₁ ≃ₐ[R] A₂) R A₁ A₂ where
map_add f := f.map_add'
map_mul f := f.map_mul'
commutes f := f.commutes'
@[ext]
theorem ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : f = g :=
DFunLike.ext f g h
protected theorem congr_arg {f : A₁ ≃ₐ[R] A₂} {x x' : A₁} : x = x' → f x = f x' :=
DFunLike.congr_arg f
protected theorem congr_fun {f g : A₁ ≃ₐ[R] A₂} (h : f = g) (x : A₁) : f x = g x :=
DFunLike.congr_fun h x
@[simp]
theorem coe_mk {toEquiv map_mul map_add commutes} :
⇑(⟨toEquiv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) = toEquiv :=
rfl
@[simp]
theorem mk_coe (e : A₁ ≃ₐ[R] A₂) (e' h₁ h₂ h₃ h₄ h₅) :
(⟨⟨e, e', h₁, h₂⟩, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂) = e :=
ext fun _ => rfl
@[simp]
theorem toEquiv_eq_coe : e.toEquiv = e :=
rfl
@[simp]
protected theorem coe_coe {F : Type*} [EquivLike F A₁ A₂] [AlgEquivClass F R A₁ A₂] (f : F) :
⇑(f : A₁ ≃ₐ[R] A₂) = f :=
rfl
theorem coe_fun_injective : @Function.Injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) fun e => (e : A₁ → A₂) :=
DFunLike.coe_injective
instance hasCoeToRingEquiv : CoeOut (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) :=
⟨AlgEquiv.toRingEquiv⟩
@[simp]
theorem coe_toEquiv : ((e : A₁ ≃ A₂) : A₁ → A₂) = e :=
rfl
@[simp]
theorem toRingEquiv_eq_coe : e.toRingEquiv = e :=
rfl
@[simp, norm_cast]
lemma toRingEquiv_toRingHom : ((e : A₁ ≃+* A₂) : A₁ →+* A₂) = e :=
rfl
@[simp, norm_cast]
theorem coe_ringEquiv : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e :=
rfl
theorem coe_ringEquiv' : (e.toRingEquiv : A₁ → A₂) = e :=
rfl
theorem coe_ringEquiv_injective : Function.Injective ((↑) : (A₁ ≃ₐ[R] A₂) → A₁ ≃+* A₂) :=
fun _ _ h => ext <| RingEquiv.congr_fun h
/-- Interpret an algebra equivalence as an algebra homomorphism.
This definition is included for symmetry with the other `to*Hom` projections.
The `simp` normal form is to use the coercion of the `AlgHomClass.coeTC` instance. -/
@[coe]
def toAlgHom : A₁ →ₐ[R] A₂ :=
{ e with
map_one' := map_one e
map_zero' := map_zero e }
@[simp]
theorem toAlgHom_eq_coe : e.toAlgHom = e :=
rfl
@[simp, norm_cast]
theorem coe_algHom : DFunLike.coe (e.toAlgHom) = DFunLike.coe e :=
rfl
theorem coe_algHom_injective : Function.Injective ((↑) : (A₁ ≃ₐ[R] A₂) → A₁ →ₐ[R] A₂) :=
fun _ _ h => ext <| AlgHom.congr_fun h
@[simp, norm_cast]
lemma toAlgHom_toRingHom : ((e : A₁ →ₐ[R] A₂) : A₁ →+* A₂) = e :=
rfl
/-- The two paths coercion can take to a `RingHom` are equivalent -/
theorem coe_ringHom_commutes : ((e : A₁ →ₐ[R] A₂) : A₁ →+* A₂) = ((e : A₁ ≃+* A₂) : A₁ →+* A₂) :=
rfl
@[simp]
theorem commutes : ∀ r : R, e (algebraMap R A₁ r) = algebraMap R A₂ r :=
e.commutes'
end coe
section bijective
protected theorem bijective : Function.Bijective e :=
EquivLike.bijective e
protected theorem injective : Function.Injective e :=
EquivLike.injective e
protected theorem surjective : Function.Surjective e :=
EquivLike.surjective e
end bijective
section refl
/-- Algebra equivalences are reflexive. -/
@[refl]
def refl : A₁ ≃ₐ[R] A₁ :=
{ (.refl _ : A₁ ≃+* A₁) with commutes' := fun _ => rfl }
instance : Inhabited (A₁ ≃ₐ[R] A₁) :=
⟨refl⟩
@[simp]
theorem refl_toAlgHom : ↑(refl : A₁ ≃ₐ[R] A₁) = AlgHom.id R A₁ :=
rfl
@[simp]
theorem coe_refl : ⇑(refl : A₁ ≃ₐ[R] A₁) = id :=
rfl
end refl
section symm
/-- Algebra equivalences are symmetric. -/
@[symm]
def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ :=
{ e.toRingEquiv.symm with
commutes' := fun r => by
rw [← e.toRingEquiv.symm_apply_apply (algebraMap R A₁ r)]
congr
simp }
theorem invFun_eq_symm {e : A₁ ≃ₐ[R] A₂} : e.invFun = e.symm :=
rfl
@[simp]
theorem coe_apply_coe_coe_symm_apply {F : Type*} [EquivLike F A₁ A₂] [AlgEquivClass F R A₁ A₂]
(f : F) (x : A₂) :
f ((f : A₁ ≃ₐ[R] A₂).symm x) = x :=
EquivLike.right_inv f x
@[simp]
theorem coe_coe_symm_apply_coe_apply {F : Type*} [EquivLike F A₁ A₂] [AlgEquivClass F R A₁ A₂]
(f : F) (x : A₁) :
(f : A₁ ≃ₐ[R] A₂).symm (f x) = x :=
EquivLike.left_inv f x
/-- `simp` normal form of `invFun_eq_symm` -/
@[simp]
theorem symm_toEquiv_eq_symm {e : A₁ ≃ₐ[R] A₂} : (e : A₁ ≃ A₂).symm = e.symm :=
rfl
@[simp]
theorem symm_symm (e : A₁ ≃ₐ[R] A₂) : e.symm.symm = e := rfl
theorem symm_bijective : Function.Bijective (symm : (A₁ ≃ₐ[R] A₂) → A₂ ≃ₐ[R] A₁) :=
Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩
@[simp]
theorem mk_coe' (e : A₁ ≃ₐ[R] A₂) (f h₁ h₂ h₃ h₄ h₅) :
(⟨⟨f, e, h₁, h₂⟩, h₃, h₄, h₅⟩ : A₂ ≃ₐ[R] A₁) = e.symm :=
symm_bijective.injective <| ext fun _ => rfl
/-- Auxiliary definition to avoid looping in `dsimp` with `AlgEquiv.symm_mk`. -/
protected def symm_mk.aux (f f') (h₁ h₂ h₃ h₄ h₅) :=
(⟨⟨f, f', h₁, h₂⟩, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm
@[simp]
theorem symm_mk (f f') (h₁ h₂ h₃ h₄ h₅) :
(⟨⟨f, f', h₁, h₂⟩, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm =
{ symm_mk.aux f f' h₁ h₂ h₃ h₄ h₅ with
toFun := f'
invFun := f } :=
rfl
@[simp]
theorem refl_symm : (AlgEquiv.refl : A₁ ≃ₐ[R] A₁).symm = AlgEquiv.refl :=
rfl
--this should be a simp lemma but causes a lint timeout
theorem toRingEquiv_symm (f : A₁ ≃ₐ[R] A₁) : (f : A₁ ≃+* A₁).symm = f.symm :=
rfl
@[simp]
theorem symm_toRingEquiv : (e.symm : A₂ ≃+* A₁) = (e : A₁ ≃+* A₂).symm :=
rfl
@[simp]
theorem symm_toAddEquiv : (e.symm : A₂ ≃+ A₁) = (e : A₁ ≃+ A₂).symm :=
rfl
@[simp]
theorem symm_toMulEquiv : (e.symm : A₂ ≃* A₁) = (e : A₁ ≃* A₂).symm :=
rfl
@[simp]
theorem apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x :=
e.toEquiv.apply_symm_apply
@[simp]
theorem symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x :=
e.toEquiv.symm_apply_apply
theorem symm_apply_eq (e : A₁ ≃ₐ[R] A₂) {x y} : e.symm x = y ↔ x = e y :=
e.toEquiv.symm_apply_eq
theorem eq_symm_apply (e : A₁ ≃ₐ[R] A₂) {x y} : y = e.symm x ↔ e y = x :=
e.toEquiv.eq_symm_apply
@[simp]
theorem comp_symm (e : A₁ ≃ₐ[R] A₂) : AlgHom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = AlgHom.id R A₂ := by
ext
simp
@[simp]
theorem symm_comp (e : A₁ ≃ₐ[R] A₂) : AlgHom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = AlgHom.id R A₁ := by
ext
simp
theorem leftInverse_symm (e : A₁ ≃ₐ[R] A₂) : Function.LeftInverse e.symm e :=
e.left_inv
theorem rightInverse_symm (e : A₁ ≃ₐ[R] A₂) : Function.RightInverse e.symm e :=
e.right_inv
end symm
section simps
/-- See Note [custom simps projection] -/
def Simps.apply (e : A₁ ≃ₐ[R] A₂) : A₁ → A₂ :=
e
/-- See Note [custom simps projection] -/
def Simps.toEquiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ A₂ :=
e
/-- See Note [custom simps projection] -/
def Simps.symm_apply (e : A₁ ≃ₐ[R] A₂) : A₂ → A₁ :=
e.symm
initialize_simps_projections AlgEquiv (toFun → apply, invFun → symm_apply)
end simps
section trans
/-- Algebra equivalences are transitive. -/
@[trans]
def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ :=
{ e₁.toRingEquiv.trans e₂.toRingEquiv with
commutes' := fun r => show e₂.toFun (e₁.toFun _) = _ by rw [e₁.commutes', e₂.commutes'] }
@[simp]
theorem coe_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ :=
rfl
@[simp]
theorem trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) : (e₁.trans e₂) x = e₂ (e₁ x) :=
rfl
@[simp]
theorem symm_trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₃) :
(e₁.trans e₂).symm x = e₁.symm (e₂.symm x) :=
rfl
end trans
/-- If `A₁` is equivalent to `A₁'` and `A₂` is equivalent to `A₂'`, then the type of maps
`A₁ →ₐ[R] A₂` is equivalent to the type of maps `A₁' →ₐ[R] A₂'`. -/
@[simps apply]
def arrowCongr (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') : (A₁ →ₐ[R] A₂) ≃ (A₁' →ₐ[R] A₂') where
toFun f := (e₂.toAlgHom.comp f).comp e₁.symm.toAlgHom
invFun f := (e₂.symm.toAlgHom.comp f).comp e₁.toAlgHom
left_inv f := by
simp only [AlgHom.comp_assoc, toAlgHom_eq_coe, symm_comp]
simp only [← AlgHom.comp_assoc, symm_comp, AlgHom.id_comp, AlgHom.comp_id]
right_inv f := by
simp only [AlgHom.comp_assoc, toAlgHom_eq_coe, comp_symm]
simp only [← AlgHom.comp_assoc, comp_symm, AlgHom.id_comp, AlgHom.comp_id]
theorem arrowCongr_comp (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂')
(e₃ : A₃ ≃ₐ[R] A₃') (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₃) :
arrowCongr e₁ e₃ (g.comp f) = (arrowCongr e₂ e₃ g).comp (arrowCongr e₁ e₂ f) := by
ext
simp
@[simp]
theorem arrowCongr_refl : arrowCongr AlgEquiv.refl AlgEquiv.refl = Equiv.refl (A₁ →ₐ[R] A₂) :=
rfl
@[simp]
theorem arrowCongr_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₁' : A₁' ≃ₐ[R] A₂')
(e₂ : A₂ ≃ₐ[R] A₃) (e₂' : A₂' ≃ₐ[R] A₃') :
arrowCongr (e₁.trans e₂) (e₁'.trans e₂') = (arrowCongr e₁ e₁').trans (arrowCongr e₂ e₂') :=
rfl
@[simp]
theorem arrowCongr_symm (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') :
(arrowCongr e₁ e₂).symm = arrowCongr e₁.symm e₂.symm :=
rfl
/-- If `A₁` is equivalent to `A₂` and `A₁'` is equivalent to `A₂'`, then the type of maps
`A₁ ≃ₐ[R] A₁'` is equivalent to the type of maps `A₂ ≃ₐ[R] A₂'`.
This is the `AlgEquiv` version of `AlgEquiv.arrowCongr`. -/
@[simps apply]
def equivCongr (e : A₁ ≃ₐ[R] A₂) (e' : A₁' ≃ₐ[R] A₂') : (A₁ ≃ₐ[R] A₁') ≃ A₂ ≃ₐ[R] A₂' where
toFun ψ := e.symm.trans (ψ.trans e')
invFun ψ := e.trans (ψ.trans e'.symm)
left_inv ψ := by
ext
simp_rw [trans_apply, symm_apply_apply]
right_inv ψ := by
ext
simp_rw [trans_apply, apply_symm_apply]
@[simp]
theorem equivCongr_refl : equivCongr AlgEquiv.refl AlgEquiv.refl = Equiv.refl (A₁ ≃ₐ[R] A₁') :=
rfl
@[simp]
theorem equivCongr_symm (e : A₁ ≃ₐ[R] A₂) (e' : A₁' ≃ₐ[R] A₂') :
(equivCongr e e').symm = equivCongr e.symm e'.symm :=
rfl
@[simp]
theorem equivCongr_trans (e₁₂ : A₁ ≃ₐ[R] A₂) (e₁₂' : A₁' ≃ₐ[R] A₂')
(e₂₃ : A₂ ≃ₐ[R] A₃) (e₂₃' : A₂' ≃ₐ[R] A₃') :
(equivCongr e₁₂ e₁₂').trans (equivCongr e₂₃ e₂₃') =
equivCongr (e₁₂.trans e₂₃) (e₁₂'.trans e₂₃') :=
rfl
/-- If an algebra morphism has an inverse, it is an algebra isomorphism. -/
@[simps]
def ofAlgHom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = AlgHom.id R A₂)
(h₂ : g.comp f = AlgHom.id R A₁) : A₁ ≃ₐ[R] A₂ :=
{ f with
toFun := f
invFun := g
left_inv := AlgHom.ext_iff.1 h₂
right_inv := AlgHom.ext_iff.1 h₁ }
theorem coe_algHom_ofAlgHom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
↑(ofAlgHom f g h₁ h₂) = f :=
rfl
@[simp]
theorem ofAlgHom_coe_algHom (f : A₁ ≃ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
ofAlgHom (↑f) g h₁ h₂ = f :=
ext fun _ => rfl
theorem ofAlgHom_symm (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
(ofAlgHom f g h₁ h₂).symm = ofAlgHom g f h₂ h₁ :=
rfl
/-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/
@[simps apply]
def toLinearEquiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ₗ[R] A₂ :=
{ e with
toFun := e
map_smul' := map_smul e
invFun := e.symm }
@[simp]
theorem toLinearEquiv_refl : (AlgEquiv.refl : A₁ ≃ₐ[R] A₁).toLinearEquiv = LinearEquiv.refl R A₁ :=
rfl
@[simp]
theorem toLinearEquiv_symm (e : A₁ ≃ₐ[R] A₂) : e.symm.toLinearEquiv = e.toLinearEquiv.symm :=
rfl
@[simp]
theorem coe_toLinearEquiv (e : A₁ ≃ₐ[R] A₂) : ⇑e.toLinearEquiv = e := rfl
@[simp]
theorem coe_symm_toLinearEquiv (e : A₁ ≃ₐ[R] A₂) : ⇑e.toLinearEquiv.symm = e.symm := rfl
@[simp]
theorem toLinearEquiv_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) :
(e₁.trans e₂).toLinearEquiv = e₁.toLinearEquiv.trans e₂.toLinearEquiv :=
rfl
theorem toLinearEquiv_injective : Function.Injective (toLinearEquiv : _ → A₁ ≃ₗ[R] A₂) :=
fun _ _ h => ext <| LinearEquiv.congr_fun h
/-- Interpret an algebra equivalence as a linear map. -/
def toLinearMap : A₁ →ₗ[R] A₂ :=
e.toAlgHom.toLinearMap
@[simp]
theorem toAlgHom_toLinearMap : (e : A₁ →ₐ[R] A₂).toLinearMap = e.toLinearMap :=
rfl
theorem toLinearMap_ofAlgHom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
(ofAlgHom f g h₁ h₂).toLinearMap = f.toLinearMap :=
LinearMap.ext fun _ => rfl
@[simp]
theorem toLinearEquiv_toLinearMap : e.toLinearEquiv.toLinearMap = e.toLinearMap :=
rfl
@[simp]
theorem toLinearMap_apply (x : A₁) : e.toLinearMap x = e x :=
rfl
theorem toLinearMap_injective : Function.Injective (toLinearMap : _ → A₁ →ₗ[R] A₂) := fun _ _ h =>
ext <| LinearMap.congr_fun h
@[simp]
theorem trans_toLinearMap (f : A₁ ≃ₐ[R] A₂) (g : A₂ ≃ₐ[R] A₃) :
(f.trans g).toLinearMap = g.toLinearMap.comp f.toLinearMap :=
rfl
/-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/
noncomputable def ofBijective (f : A₁ →ₐ[R] A₂) (hf : Function.Bijective f) : A₁ ≃ₐ[R] A₂ :=
{ RingEquiv.ofBijective (f : A₁ →+* A₂) hf, f with }
@[simp]
lemma coe_ofBijective (f : A₁ →ₐ[R] A₂) (hf : Function.Bijective f) :
(ofBijective f hf : A₁ → A₂) = f := rfl
lemma ofBijective_apply (f : A₁ →ₐ[R] A₂) (hf : Function.Bijective f) (a : A₁) :
(ofBijective f hf) a = f a := rfl
@[simp]
lemma toLinearMap_ofBijective (f : A₁ →ₐ[R] A₂) (hf : Function.Bijective f) :
(ofBijective f hf).toLinearMap = f := rfl
section OfLinearEquiv
variable (l : A₁ ≃ₗ[R] A₂) (map_one : l 1 = 1) (map_mul : ∀ x y : A₁, l (x * y) = l x * l y)
/--
Upgrade a linear equivalence to an algebra equivalence,
given that it distributes over multiplication and the identity
-/
@[simps apply]
def ofLinearEquiv : A₁ ≃ₐ[R] A₂ :=
{ l with
toFun := l
invFun := l.symm
map_mul' := map_mul
commutes' := (AlgHom.ofLinearMap l map_one map_mul : A₁ →ₐ[R] A₂).commutes }
/-- Auxiliary definition to avoid looping in `dsimp` with `AlgEquiv.ofLinearEquiv_symm`. -/
protected def ofLinearEquiv_symm.aux := (ofLinearEquiv l map_one map_mul).symm
@[simp]
theorem ofLinearEquiv_symm :
(ofLinearEquiv l map_one map_mul).symm =
ofLinearEquiv l.symm
(_root_.map_one <| ofLinearEquiv_symm.aux l map_one map_mul)
(_root_.map_mul <| ofLinearEquiv_symm.aux l map_one map_mul) :=
rfl
@[simp]
theorem ofLinearEquiv_toLinearEquiv (map_mul) (map_one) :
ofLinearEquiv e.toLinearEquiv map_mul map_one = e :=
rfl
@[simp]
theorem toLinearEquiv_ofLinearEquiv : toLinearEquiv (ofLinearEquiv l map_one map_mul) = l :=
rfl
end OfLinearEquiv
section OfRingEquiv
/-- Promotes a linear `RingEquiv` to an `AlgEquiv`. -/
@[simps apply symm_apply toEquiv]
def ofRingEquiv {f : A₁ ≃+* A₂} (hf : ∀ x, f (algebraMap R A₁ x) = algebraMap R A₂ x) :
A₁ ≃ₐ[R] A₂ :=
{ f with
toFun := f
invFun := f.symm
commutes' := hf }
end OfRingEquiv
@[simps -isSimp one mul, stacks 09HR]
instance aut : Group (A₁ ≃ₐ[R] A₁) where
mul ϕ ψ := ψ.trans ϕ
mul_assoc _ _ _ := rfl
one := refl
one_mul _ := ext fun _ => rfl
mul_one _ := ext fun _ => rfl
inv := symm
inv_mul_cancel ϕ := ext <| symm_apply_apply ϕ
@[simp]
theorem one_apply (x : A₁) : (1 : A₁ ≃ₐ[R] A₁) x = x :=
rfl
@[simp]
theorem mul_apply (e₁ e₂ : A₁ ≃ₐ[R] A₁) (x : A₁) : (e₁ * e₂) x = e₁ (e₂ x) :=
rfl
lemma aut_inv (ϕ : A₁ ≃ₐ[R] A₁) : ϕ⁻¹ = ϕ.symm := rfl
@[simp] theorem coe_pow (e : A₁ ≃ₐ[R] A₁) (n : ℕ) : ⇑(e ^ n) = e^[n] :=
n.rec (by ext; simp) fun _ ih ↦ by ext; simp [pow_succ, ih]
/-- An algebra isomorphism induces a group isomorphism between automorphism groups.
This is a more bundled version of `AlgEquiv.equivCongr`. -/
@[simps apply]
def autCongr (ϕ : A₁ ≃ₐ[R] A₂) : (A₁ ≃ₐ[R] A₁) ≃* A₂ ≃ₐ[R] A₂ where
__ := equivCongr ϕ ϕ
toFun ψ := ϕ.symm.trans (ψ.trans ϕ)
invFun ψ := ϕ.trans (ψ.trans ϕ.symm)
map_mul' ψ χ := by
ext
simp only [mul_apply, trans_apply, symm_apply_apply]
@[simp]
theorem autCongr_refl : autCongr AlgEquiv.refl = MulEquiv.refl (A₁ ≃ₐ[R] A₁) := rfl
@[simp]
theorem autCongr_symm (ϕ : A₁ ≃ₐ[R] A₂) : (autCongr ϕ).symm = autCongr ϕ.symm :=
rfl
@[simp]
theorem autCongr_trans (ϕ : A₁ ≃ₐ[R] A₂) (ψ : A₂ ≃ₐ[R] A₃) :
(autCongr ϕ).trans (autCongr ψ) = autCongr (ϕ.trans ψ) :=
rfl
/-- The tautological action by `A₁ ≃ₐ[R] A₁` on `A₁`.
This generalizes `Function.End.applyMulAction`. -/
instance applyMulSemiringAction : MulSemiringAction (A₁ ≃ₐ[R] A₁) A₁ where
smul := (· <| ·)
smul_zero := map_zero
smul_add := map_add
smul_one := map_one
smul_mul := map_mul
one_smul _ := rfl
mul_smul _ _ _ := rfl
@[simp]
protected theorem smul_def (f : A₁ ≃ₐ[R] A₁) (a : A₁) : f • a = f a :=
rfl
instance apply_faithfulSMul : FaithfulSMul (A₁ ≃ₐ[R] A₁) A₁ :=
⟨AlgEquiv.ext⟩
instance apply_smulCommClass {S} [SMul S R] [SMul S A₁] [IsScalarTower S R A₁] :
SMulCommClass S (A₁ ≃ₐ[R] A₁) A₁ where
smul_comm r e a := (e.toLinearEquiv.map_smul_of_tower r a).symm
instance apply_smulCommClass' {S} [SMul S R] [SMul S A₁] [IsScalarTower S R A₁] :
SMulCommClass (A₁ ≃ₐ[R] A₁) S A₁ :=
SMulCommClass.symm _ _ _
instance : MulDistribMulAction (A₁ ≃ₐ[R] A₁) A₁ˣ where
smul := fun f => Units.map f
one_smul := fun x => by ext; rfl
mul_smul := fun x y z => by ext; rfl
smul_mul := fun x y z => by ext; exact map_mul x _ _
smul_one := fun x => by ext; exact map_one x
@[simp]
theorem smul_units_def (f : A₁ ≃ₐ[R] A₁) (x : A₁ˣ) :
f • x = Units.map f x := rfl
@[simp]
lemma _root_.MulSemiringAction.toRingEquiv_algEquiv (σ : A₁ ≃ₐ[R] A₁) :
MulSemiringAction.toRingEquiv _ A₁ σ = σ := rfl
@[simp]
theorem algebraMap_eq_apply (e : A₁ ≃ₐ[R] A₂) {y : R} {x : A₁} :
algebraMap R A₂ y = e x ↔ algebraMap R A₁ y = x :=
⟨fun h => by simpa using e.symm.toAlgHom.algebraMap_eq_apply h, fun h =>
e.toAlgHom.algebraMap_eq_apply h⟩
/-- `AlgEquiv.toAlgHom` as a `MonoidHom`. -/
@[simps] def toAlgHomHom (R A) [CommSemiring R] [Semiring A] [Algebra R A] :
(A ≃ₐ[R] A) →* A →ₐ[R] A where
toFun := AlgEquiv.toAlgHom
map_one' := rfl
map_mul' _ _ := rfl
/-- `AlgEquiv.toLinearMap` as a `MonoidHom`. -/
@[simps!]
def toLinearMapHom (R A) [CommSemiring R] [Semiring A] [Algebra R A] :
(A ≃ₐ[R] A) →* Module.End R A :=
AlgHom.toEnd.comp (toAlgHomHom R A)
lemma pow_toLinearMap (σ : A₁ ≃ₐ[R] A₁) (n : ℕ) :
(σ ^ n).toLinearMap = σ.toLinearMap ^ n :=
(AlgEquiv.toLinearMapHom R A₁).map_pow σ n
@[simp]
lemma one_toLinearMap :
(1 : A₁ ≃ₐ[R] A₁).toLinearMap = 1 := rfl
/-- The units group of `S →ₐ[R] S` is `S ≃ₐ[R] S`.
See `LinearMap.GeneralLinearGroup.generalLinearEquiv` for the linear map version. -/
@[simps]
def algHomUnitsEquiv (R S : Type*) [CommSemiring R] [Semiring S] [Algebra R S] :
(S →ₐ[R] S)ˣ ≃* (S ≃ₐ[R] S) where
toFun := fun f ↦
{ (f : S →ₐ[R] S) with
invFun := ↑(f⁻¹)
left_inv := (fun x ↦ show (↑(f⁻¹ * f) : S →ₐ[R] S) x = x by rw [inv_mul_cancel]; rfl)
right_inv := (fun x ↦ show (↑(f * f⁻¹) : S →ₐ[R] S) x = x by rw [mul_inv_cancel]; rfl) }
invFun := fun f ↦ ⟨f, f.symm, f.comp_symm, f.symm_comp⟩
map_mul' := fun _ _ ↦ rfl
/-- See also `Finite.algHom` -/
instance _root_.Finite.algEquiv [Finite (A₁ →ₐ[R] A₂)] : Finite (A₁ ≃ₐ[R] A₂) :=
Finite.of_injective _ AlgEquiv.coe_algHom_injective
end Semiring
end AlgEquiv
namespace MulSemiringAction
variable {M G : Type*} (R A : Type*) [CommSemiring R] [Semiring A] [Algebra R A]
section
variable [Group G] [MulSemiringAction G A] [SMulCommClass G R A]
/-- Each element of the group defines an algebra equivalence.
This is a stronger version of `MulSemiringAction.toRingEquiv` and
`DistribMulAction.toLinearEquiv`. -/
@[simps! apply symm_apply toEquiv]
def toAlgEquiv (g : G) : A ≃ₐ[R] A :=
{ MulSemiringAction.toRingEquiv _ _ g, MulSemiringAction.toAlgHom R A g with }
theorem toAlgEquiv_injective [FaithfulSMul G A] :
Function.Injective (MulSemiringAction.toAlgEquiv R A : G → A ≃ₐ[R] A) := fun _ _ h =>
eq_of_smul_eq_smul fun r => AlgEquiv.ext_iff.1 h r
variable (G)
/-- Each element of the group defines an algebra equivalence.
This is a stronger version of `MulSemiringAction.toRingAut` and
`DistribMulAction.toModuleEnd`. -/
@[simps]
def toAlgAut : G →* A ≃ₐ[R] A where
toFun := toAlgEquiv R A
map_one' := AlgEquiv.ext <| one_smul _
map_mul' g h := AlgEquiv.ext <| mul_smul g h
end
end MulSemiringAction
section
variable {R S T : Type*} [CommSemiring R] [Semiring S] [Semiring T] [Algebra R S] [Algebra R T]
instance [Subsingleton S] [Subsingleton T] : Unique (S ≃ₐ[R] T) where
default := AlgEquiv.ofAlgHom default default
(AlgHom.ext fun _ ↦ Subsingleton.elim _ _)
(AlgHom.ext fun _ ↦ Subsingleton.elim _ _)
uniq _ := AlgEquiv.ext fun _ ↦ Subsingleton.elim _ _
@[simp]
lemma AlgEquiv.default_apply [Subsingleton S] [Subsingleton T] (x : S) :
(default : S ≃ₐ[R] T) x = 0 :=
rfl
end
/-- The algebra equivalence between `ULift A` and `A`. -/
@[simps! -isSimp apply]
def ULift.algEquiv {R : Type u} {A : Type v} [CommSemiring R] [Semiring A] [Algebra R A] :
ULift.{w} A ≃ₐ[R] A where
__ := ULift.ringEquiv
commutes' _ := rfl
|
Order.lean
|
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau
-/
import Mathlib.Data.Finset.Defs
import Mathlib.Data.Multiset.ZeroCons
import Mathlib.Order.Directed
/-!
# Finsets of ordered types
-/
universe u v w
variable {α : Type u}
theorem Directed.finset_le {r : α → α → Prop} [IsTrans α r] {ι} [hι : Nonempty ι] {f : ι → α}
(D : Directed r f) (s : Finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) :=
show ∃ z, ∀ i ∈ s.1, r (f i) (f z) from
Multiset.induction_on s.1 (let ⟨z⟩ := hι; ⟨z, fun _ ↦ by simp⟩)
fun i _ ⟨j, H⟩ ↦
let ⟨k, h₁, h₂⟩ := D i j
⟨k, fun _ h ↦ (Multiset.mem_cons.1 h).casesOn (fun h ↦ h.symm ▸ h₁)
fun h ↦ _root_.trans (H _ h) h₂⟩
theorem Finset.exists_le [Nonempty α] [Preorder α] [IsDirected α (· ≤ ·)] (s : Finset α) :
∃ M, ∀ i ∈ s, i ≤ M :=
directed_id.finset_le _
|
NormalForms.lean
|
/-
Copyright (c) 2024 Jz Pan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jz Pan
-/
import Mathlib.AlgebraicGeometry.EllipticCurve.VariableChange
import Mathlib.Algebra.CharP.Defs
/-!
# Some normal forms of elliptic curves
This file defines some normal forms of Weierstrass equations of elliptic curves.
## Main definitions and results
The following normal forms are in [silverman2009], section III.1, page 42.
- `WeierstrassCurve.IsCharNeTwoNF` is a type class which asserts that a `WeierstrassCurve` is
of form `Y² = X³ + a₂X² + a₄X + a₆`. It is the normal form of characteristic ≠ 2.
If 2 is invertible in the ring (for example, if it is a field of characteristic ≠ 2),
then for any `WeierstrassCurve` there exists a change of variables which will change
it into such normal form (`WeierstrassCurve.exists_variableChange_isCharNeTwoNF`).
See also `WeierstrassCurve.toCharNeTwoNF` and `WeierstrassCurve.toCharNeTwoNF_spec`.
The following normal forms are in [silverman2009], Appendix A, Proposition 1.1.
- `WeierstrassCurve.IsShortNF` is a type class which asserts that a `WeierstrassCurve` is
of form `Y² = X³ + a₄X + a₆`. It is the normal form of characteristic ≠ 2 or 3, and
also the normal form of characteristic = 3 and j = 0.
If 2 and 3 are invertible in the ring (for example, if it is a field of characteristic ≠ 2 or 3),
then for any `WeierstrassCurve` there exists a change of variables which will change
it into such normal form (`WeierstrassCurve.exists_variableChange_isShortNF`).
See also `WeierstrassCurve.toShortNF` and `WeierstrassCurve.toShortNF_spec`.
If the ring is of characteristic = 3, then for any `WeierstrassCurve` with `b₂ = 0` (for an
elliptic curve, this is equivalent to j = 0), there exists a change of variables which will
change it into such normal form (see `WeierstrassCurve.toShortNFOfCharThree`
and `WeierstrassCurve.toShortNFOfCharThree_spec`).
- `WeierstrassCurve.IsCharThreeJNeZeroNF` is a type class which asserts that a `WeierstrassCurve` is
of form `Y² = X³ + a₂X² + a₆`. It is the normal form of characteristic = 3 and j ≠ 0.
If the field is of characteristic = 3, then for any `WeierstrassCurve` with `b₂ ≠ 0` (for an
elliptic curve, this is equivalent to j ≠ 0), there exists a change of variables which will
change it into such normal form (see `WeierstrassCurve.toCharThreeNF`
and `WeierstrassCurve.toCharThreeNF_spec_of_b₂_ne_zero`).
- `WeierstrassCurve.IsCharThreeNF` is the combination of the above two, that is, asserts that
a `WeierstrassCurve` is of form `Y² = X³ + a₂X² + a₆` or `Y² = X³ + a₄X + a₆`.
It is the normal form of characteristic = 3.
If the field is of characteristic = 3, then for any `WeierstrassCurve` there exists a change of
variables which will change it into such normal form
(`WeierstrassCurve.exists_variableChange_isCharThreeNF`).
See also `WeierstrassCurve.toCharThreeNF` and `WeierstrassCurve.toCharThreeNF_spec`.
- `WeierstrassCurve.IsCharTwoJEqZeroNF` is a type class which asserts that a `WeierstrassCurve` is
of form `Y² + a₃Y = X³ + a₄X + a₆`. It is the normal form of characteristic = 2 and j = 0.
If the ring is of characteristic = 2, then for any `WeierstrassCurve` with `a₁ = 0` (for an
elliptic curve, this is equivalent to j = 0), there exists a change of variables which will
change it into such normal form (see `WeierstrassCurve.toCharTwoJEqZeroNF`
and `WeierstrassCurve.toCharTwoJEqZeroNF_spec`).
- `WeierstrassCurve.IsCharTwoJNeZeroNF` is a type class which asserts that a `WeierstrassCurve` is
of form `Y² + XY = X³ + a₂X² + a₆`. It is the normal form of characteristic = 2 and j ≠ 0.
If the field is of characteristic = 2, then for any `WeierstrassCurve` with `a₁ ≠ 0` (for an
elliptic curve, this is equivalent to j ≠ 0), there exists a change of variables which will
change it into such normal form (see `WeierstrassCurve.toCharTwoJNeZeroNF`
and `WeierstrassCurve.toCharTwoJNeZeroNF_spec`).
- `WeierstrassCurve.IsCharTwoNF` is the combination of the above two, that is, asserts that
a `WeierstrassCurve` is of form `Y² + XY = X³ + a₂X² + a₆` or
`Y² + a₃Y = X³ + a₄X + a₆`. It is the normal form of characteristic = 2.
If the field is of characteristic = 2, then for any `WeierstrassCurve` there exists a change of
variables which will change it into such normal form
(`WeierstrassCurve.exists_variableChange_isCharTwoNF`).
See also `WeierstrassCurve.toCharTwoNF` and `WeierstrassCurve.toCharTwoNF_spec`.
## References
* [J Silverman, *The Arithmetic of Elliptic Curves*][silverman2009]
## Tags
elliptic curve, weierstrass equation, normal form
-/
variable {R : Type*} [CommRing R] {F : Type*} [Field F] (W : WeierstrassCurve R)
namespace WeierstrassCurve
/-! ## Normal forms of characteristic ≠ 2 -/
/-- A `WeierstrassCurve` is in normal form of characteristic ≠ 2, if its `a₁, a₃ = 0`.
In other words it is `Y² = X³ + a₂X² + a₄X + a₆`. -/
@[mk_iff]
class IsCharNeTwoNF : Prop where
a₁ : W.a₁ = 0
a₃ : W.a₃ = 0
section Quantity
variable [W.IsCharNeTwoNF]
@[simp]
theorem a₁_of_isCharNeTwoNF : W.a₁ = 0 := IsCharNeTwoNF.a₁
@[simp]
theorem a₃_of_isCharNeTwoNF : W.a₃ = 0 := IsCharNeTwoNF.a₃
@[simp]
theorem b₂_of_isCharNeTwoNF : W.b₂ = 4 * W.a₂ := by
rw [b₂, a₁_of_isCharNeTwoNF]
ring1
@[simp]
theorem b₄_of_isCharNeTwoNF : W.b₄ = 2 * W.a₄ := by
rw [b₄, a₃_of_isCharNeTwoNF]
ring1
@[simp]
theorem b₆_of_isCharNeTwoNF : W.b₆ = 4 * W.a₆ := by
rw [b₆, a₃_of_isCharNeTwoNF]
ring1
@[simp]
theorem b₈_of_isCharNeTwoNF : W.b₈ = 4 * W.a₂ * W.a₆ - W.a₄ ^ 2 := by
rw [b₈, a₁_of_isCharNeTwoNF, a₃_of_isCharNeTwoNF]
ring1
@[simp]
theorem c₄_of_isCharNeTwoNF : W.c₄ = 16 * W.a₂ ^ 2 - 48 * W.a₄ := by
rw [c₄, b₂_of_isCharNeTwoNF, b₄_of_isCharNeTwoNF]
ring1
@[simp]
theorem c₆_of_isCharNeTwoNF : W.c₆ = -64 * W.a₂ ^ 3 + 288 * W.a₂ * W.a₄ - 864 * W.a₆ := by
rw [c₆, b₂_of_isCharNeTwoNF, b₄_of_isCharNeTwoNF, b₆_of_isCharNeTwoNF]
ring1
@[simp]
theorem Δ_of_isCharNeTwoNF : W.Δ = -64 * W.a₂ ^ 3 * W.a₆ + 16 * W.a₂ ^ 2 * W.a₄ ^ 2 - 64 * W.a₄ ^ 3
- 432 * W.a₆ ^ 2 + 288 * W.a₂ * W.a₄ * W.a₆ := by
rw [Δ, b₂_of_isCharNeTwoNF, b₄_of_isCharNeTwoNF, b₆_of_isCharNeTwoNF, b₈_of_isCharNeTwoNF]
ring1
end Quantity
section VariableChange
variable [Invertible (2 : R)]
/-- There is an explicit change of variables of a `WeierstrassCurve` to
a normal form of characteristic ≠ 2, provided that 2 is invertible in the ring. -/
@[simps]
def toCharNeTwoNF : VariableChange R := ⟨1, 0, ⅟2 * -W.a₁, ⅟2 * -W.a₃⟩
instance toCharNeTwoNF_spec : (W.toCharNeTwoNF • W).IsCharNeTwoNF := by
constructor <;> simp [variableChange_a₁, variableChange_a₃]
theorem exists_variableChange_isCharNeTwoNF : ∃ C : VariableChange R, (C • W).IsCharNeTwoNF :=
⟨_, W.toCharNeTwoNF_spec⟩
end VariableChange
/-! ## Short normal form -/
/-- A `WeierstrassCurve` is in short normal form, if its `a₁, a₂, a₃ = 0`.
In other words it is `Y² = X³ + a₄X + a₆`.
This is the normal form of characteristic ≠ 2 or 3, and
also the normal form of characteristic = 3 and j = 0. -/
@[mk_iff]
class IsShortNF : Prop where
a₁ : W.a₁ = 0
a₂ : W.a₂ = 0
a₃ : W.a₃ = 0
section Quantity
variable [W.IsShortNF]
instance isCharNeTwoNF_of_isShortNF : W.IsCharNeTwoNF := ⟨IsShortNF.a₁, IsShortNF.a₃⟩
theorem a₁_of_isShortNF : W.a₁ = 0 := IsShortNF.a₁
@[simp]
theorem a₂_of_isShortNF : W.a₂ = 0 := IsShortNF.a₂
theorem a₃_of_isShortNF : W.a₃ = 0 := IsShortNF.a₃
theorem b₂_of_isShortNF : W.b₂ = 0 := by
simp
theorem b₄_of_isShortNF : W.b₄ = 2 * W.a₄ := W.b₄_of_isCharNeTwoNF
theorem b₆_of_isShortNF : W.b₆ = 4 * W.a₆ := W.b₆_of_isCharNeTwoNF
theorem b₈_of_isShortNF : W.b₈ = -W.a₄ ^ 2 := by
simp
theorem c₄_of_isShortNF : W.c₄ = -48 * W.a₄ := by
simp
theorem c₆_of_isShortNF : W.c₆ = -864 * W.a₆ := by
simp
theorem Δ_of_isShortNF : W.Δ = -16 * (4 * W.a₄ ^ 3 + 27 * W.a₆ ^ 2) := by
rw [Δ_of_isCharNeTwoNF, a₂_of_isShortNF]
ring1
variable [CharP R 3]
theorem b₄_of_isShortNF_of_char_three : W.b₄ = -W.a₄ := by
rw [b₄_of_isShortNF]
linear_combination W.a₄ * CharP.cast_eq_zero R 3
theorem b₆_of_isShortNF_of_char_three : W.b₆ = W.a₆ := by
rw [b₆_of_isShortNF]
linear_combination W.a₆ * CharP.cast_eq_zero R 3
theorem c₄_of_isShortNF_of_char_three : W.c₄ = 0 := by
rw [c₄_of_isShortNF]
linear_combination -16 * W.a₄ * CharP.cast_eq_zero R 3
theorem c₆_of_isShortNF_of_char_three : W.c₆ = 0 := by
rw [c₆_of_isShortNF]
linear_combination -288 * W.a₆ * CharP.cast_eq_zero R 3
theorem Δ_of_isShortNF_of_char_three : W.Δ = -W.a₄ ^ 3 := by
rw [Δ_of_isShortNF]
linear_combination (-21 * W.a₄ ^ 3 - 144 * W.a₆ ^ 2) * CharP.cast_eq_zero R 3
variable (W : WeierstrassCurve F) [W.IsElliptic] [W.IsShortNF]
theorem j_of_isShortNF : W.j = 6912 * W.a₄ ^ 3 / (4 * W.a₄ ^ 3 + 27 * W.a₆ ^ 2) := by
have h := W.Δ'.ne_zero
rw [coe_Δ', Δ_of_isShortNF] at h
rw [j, Units.val_inv_eq_inv_val, ← div_eq_inv_mul, coe_Δ',
c₄_of_isShortNF, Δ_of_isShortNF, div_eq_div_iff h (right_ne_zero_of_mul h)]
ring1
@[simp]
theorem j_of_isShortNF_of_char_three [CharP F 3] : W.j = 0 := by
rw [j, c₄_of_isShortNF_of_char_three]; simp
end Quantity
section VariableChange
variable [Invertible (2 : R)] [Invertible (3 : R)]
/-- There is an explicit change of variables of a `WeierstrassCurve` to
a short normal form, provided that 2 and 3 are invertible in the ring.
It is the composition of an explicit change of variables with `WeierstrassCurve.toCharNeTwoNF`. -/
def toShortNF : VariableChange R :=
⟨1, ⅟3 * -(W.toCharNeTwoNF • W).a₂, 0, 0⟩ * W.toCharNeTwoNF
instance toShortNF_spec : (W.toShortNF • W).IsShortNF := by
rw [toShortNF, mul_smul]
constructor <;> simp [variableChange_a₁, variableChange_a₂, variableChange_a₃]
theorem exists_variableChange_isShortNF : ∃ C : VariableChange R, (C • W).IsShortNF :=
⟨_, W.toShortNF_spec⟩
end VariableChange
/-! ## Normal forms of characteristic = 3 and j ≠ 0 -/
/-- A `WeierstrassCurve` is in normal form of characteristic = 3 and j ≠ 0, if its
`a₁, a₃, a₄ = 0`. In other words it is `Y² = X³ + a₂X² + a₆`. -/
@[mk_iff]
class IsCharThreeJNeZeroNF : Prop where
a₁ : W.a₁ = 0
a₃ : W.a₃ = 0
a₄ : W.a₄ = 0
section Quantity
variable [W.IsCharThreeJNeZeroNF]
instance isCharNeTwoNF_of_isCharThreeJNeZeroNF : W.IsCharNeTwoNF :=
⟨IsCharThreeJNeZeroNF.a₁, IsCharThreeJNeZeroNF.a₃⟩
theorem a₁_of_isCharThreeJNeZeroNF : W.a₁ = 0 := IsCharThreeJNeZeroNF.a₁
theorem a₃_of_isCharThreeJNeZeroNF : W.a₃ = 0 := IsCharThreeJNeZeroNF.a₃
@[simp]
theorem a₄_of_isCharThreeJNeZeroNF : W.a₄ = 0 := IsCharThreeJNeZeroNF.a₄
theorem b₂_of_isCharThreeJNeZeroNF : W.b₂ = 4 * W.a₂ := W.b₂_of_isCharNeTwoNF
theorem b₄_of_isCharThreeJNeZeroNF : W.b₄ = 0 := by
simp
theorem b₆_of_isCharThreeJNeZeroNF : W.b₆ = 4 * W.a₆ := W.b₆_of_isCharNeTwoNF
theorem b₈_of_isCharThreeJNeZeroNF : W.b₈ = 4 * W.a₂ * W.a₆ := by
simp
theorem c₄_of_isCharThreeJNeZeroNF : W.c₄ = 16 * W.a₂ ^ 2 := by
simp
theorem c₆_of_isCharThreeJNeZeroNF : W.c₆ = -64 * W.a₂ ^ 3 - 864 * W.a₆ := by
simp
theorem Δ_of_isCharThreeJNeZeroNF : W.Δ = -64 * W.a₂ ^ 3 * W.a₆ - 432 * W.a₆ ^ 2 := by
simp
variable [CharP R 3]
theorem b₂_of_isCharThreeJNeZeroNF_of_char_three : W.b₂ = W.a₂ := by
rw [b₂_of_isCharThreeJNeZeroNF]
linear_combination W.a₂ * CharP.cast_eq_zero R 3
theorem b₆_of_isCharThreeJNeZeroNF_of_char_three : W.b₆ = W.a₆ := by
rw [b₆_of_isCharThreeJNeZeroNF]
linear_combination W.a₆ * CharP.cast_eq_zero R 3
theorem b₈_of_isCharThreeJNeZeroNF_of_char_three : W.b₈ = W.a₂ * W.a₆ := by
rw [b₈_of_isCharThreeJNeZeroNF]
linear_combination W.a₂ * W.a₆ * CharP.cast_eq_zero R 3
theorem c₄_of_isCharThreeJNeZeroNF_of_char_three : W.c₄ = W.a₂ ^ 2 := by
rw [c₄_of_isCharThreeJNeZeroNF]
linear_combination 5 * W.a₂ ^ 2 * CharP.cast_eq_zero R 3
theorem c₆_of_isCharThreeJNeZeroNF_of_char_three : W.c₆ = -W.a₂ ^ 3 := by
rw [c₆_of_isCharThreeJNeZeroNF]
linear_combination (-21 * W.a₂ ^ 3 - 288 * W.a₆) * CharP.cast_eq_zero R 3
theorem Δ_of_isCharThreeJNeZeroNF_of_char_three : W.Δ = -W.a₂ ^ 3 * W.a₆ := by
rw [Δ_of_isCharThreeJNeZeroNF]
linear_combination (-21 * W.a₂ ^ 3 * W.a₆ - 144 * W.a₆ ^ 2) * CharP.cast_eq_zero R 3
variable (W : WeierstrassCurve F) [W.IsElliptic] [W.IsCharThreeJNeZeroNF] [CharP F 3]
@[simp]
theorem j_of_isCharThreeJNeZeroNF_of_char_three : W.j = -W.a₂ ^ 3 / W.a₆ := by
have h := W.Δ'.ne_zero
rw [coe_Δ', Δ_of_isCharThreeJNeZeroNF_of_char_three] at h
rw [j, Units.val_inv_eq_inv_val, ← div_eq_inv_mul, coe_Δ',
c₄_of_isCharThreeJNeZeroNF_of_char_three, Δ_of_isCharThreeJNeZeroNF_of_char_three,
div_eq_div_iff h (right_ne_zero_of_mul h)]
ring1
theorem j_ne_zero_of_isCharThreeJNeZeroNF_of_char_three : W.j ≠ 0 := by
rw [j_of_isCharThreeJNeZeroNF_of_char_three, div_ne_zero_iff]
have h := W.Δ'.ne_zero
rwa [coe_Δ', Δ_of_isCharThreeJNeZeroNF_of_char_three, mul_ne_zero_iff] at h
end Quantity
/-! ## Normal forms of characteristic = 3 -/
/-- A `WeierstrassCurve` is in normal form of characteristic = 3, if it is
`Y² = X³ + a₂X² + a₆` (`WeierstrassCurve.IsCharThreeJNeZeroNF`) or
`Y² = X³ + a₄X + a₆` (`WeierstrassCurve.IsShortNF`). -/
class inductive IsCharThreeNF : Prop
| of_j_ne_zero [W.IsCharThreeJNeZeroNF] : IsCharThreeNF
| of_j_eq_zero [W.IsShortNF] : IsCharThreeNF
instance isCharThreeNF_of_isCharThreeJNeZeroNF [W.IsCharThreeJNeZeroNF] : W.IsCharThreeNF :=
IsCharThreeNF.of_j_ne_zero
instance isCharThreeNF_of_isShortNF [W.IsShortNF] : W.IsCharThreeNF :=
IsCharThreeNF.of_j_eq_zero
instance isCharNeTwoNF_of_isCharThreeNF [W.IsCharThreeNF] : W.IsCharNeTwoNF := by
cases ‹W.IsCharThreeNF› <;> infer_instance
section VariableChange
variable [CharP R 3] [CharP F 3]
/-- For a `WeierstrassCurve` defined over a ring of characteristic = 3,
there is an explicit change of variables of it to `Y² = X³ + a₄X + a₆`
(`WeierstrassCurve.IsShortNF`) if its j = 0.
This is in fact given by `WeierstrassCurve.toCharNeTwoNF`. -/
def toShortNFOfCharThree : VariableChange R :=
have h : (2 : R) * 2 = 1 := by linear_combination CharP.cast_eq_zero R 3
letI : Invertible (2 : R) := ⟨2, h, h⟩
W.toCharNeTwoNF
lemma toShortNFOfCharThree_a₂ : (W.toShortNFOfCharThree • W).a₂ = W.b₂ := by
simp_rw [toShortNFOfCharThree, toCharNeTwoNF, variableChange_a₂, inv_one, Units.val_one, b₂]
linear_combination (-W.a₂ - W.a₁ ^ 2) * CharP.cast_eq_zero R 3
theorem toShortNFOfCharThree_spec (hb₂ : W.b₂ = 0) : (W.toShortNFOfCharThree • W).IsShortNF := by
have h : (2 : R) * 2 = 1 := by linear_combination CharP.cast_eq_zero R 3
letI : Invertible (2 : R) := ⟨2, h, h⟩
have H := W.toCharNeTwoNF_spec
exact ⟨H.a₁, hb₂ ▸ W.toShortNFOfCharThree_a₂, H.a₃⟩
variable (W : WeierstrassCurve F)
/-- For a `WeierstrassCurve` defined over a field of characteristic = 3,
there is an explicit change of variables of it to `WeierstrassCurve.IsCharThreeNF`, that is,
`Y² = X³ + a₂X² + a₆` (`WeierstrassCurve.IsCharThreeJNeZeroNF`) or
`Y² = X³ + a₄X + a₆` (`WeierstrassCurve.IsShortNF`).
It is the composition of an explicit change of variables with
`WeierstrassCurve.toShortNFOfCharThree`. -/
def toCharThreeNF : VariableChange F :=
⟨1, (W.toShortNFOfCharThree • W).a₄ /
(W.toShortNFOfCharThree • W).a₂, 0, 0⟩ * W.toShortNFOfCharThree
theorem toCharThreeNF_spec_of_b₂_ne_zero (hb₂ : W.b₂ ≠ 0) :
(W.toCharThreeNF • W).IsCharThreeJNeZeroNF := by
have h : (2 : F) * 2 = 1 := by linear_combination CharP.cast_eq_zero F 3
letI : Invertible (2 : F) := ⟨2, h, h⟩
rw [toCharThreeNF, mul_smul]
set W' := W.toShortNFOfCharThree • W
haveI : W'.IsCharNeTwoNF := W.toCharNeTwoNF_spec
constructor
· simp [variableChange_a₁]
· simp [variableChange_a₃]
· have ha₂ : W'.a₂ ≠ 0 := W.toShortNFOfCharThree_a₂ ▸ hb₂
field_simp [ha₂, variableChange_a₄]
linear_combination (W'.a₄ * W'.a₂ ^ 2 + W'.a₄ ^ 2) * CharP.cast_eq_zero F 3
theorem toCharThreeNF_spec_of_b₂_eq_zero (hb₂ : W.b₂ = 0) : (W.toCharThreeNF • W).IsShortNF := by
rw [toCharThreeNF, toShortNFOfCharThree_a₂, hb₂, div_zero, ← VariableChange.one_def, one_mul]
exact W.toShortNFOfCharThree_spec hb₂
instance toCharThreeNF_spec : (W.toCharThreeNF • W).IsCharThreeNF := by
by_cases hb₂ : W.b₂ = 0
· haveI := W.toCharThreeNF_spec_of_b₂_eq_zero hb₂
infer_instance
· haveI := W.toCharThreeNF_spec_of_b₂_ne_zero hb₂
infer_instance
theorem exists_variableChange_isCharThreeNF : ∃ C : VariableChange F, (C • W).IsCharThreeNF :=
⟨_, W.toCharThreeNF_spec⟩
end VariableChange
/-! ## Normal forms of characteristic = 2 and j ≠ 0 -/
/-- A `WeierstrassCurve` is in normal form of characteristic = 2 and j ≠ 0, if its `a₁ = 1` and
`a₃, a₄ = 0`. In other words it is `Y² + XY = X³ + a₂X² + a₆`. -/
@[mk_iff]
class IsCharTwoJNeZeroNF : Prop where
a₁ : W.a₁ = 1
a₃ : W.a₃ = 0
a₄ : W.a₄ = 0
section Quantity
variable [W.IsCharTwoJNeZeroNF]
@[simp]
theorem a₁_of_isCharTwoJNeZeroNF : W.a₁ = 1 := IsCharTwoJNeZeroNF.a₁
@[simp]
theorem a₃_of_isCharTwoJNeZeroNF : W.a₃ = 0 := IsCharTwoJNeZeroNF.a₃
@[simp]
theorem a₄_of_isCharTwoJNeZeroNF : W.a₄ = 0 := IsCharTwoJNeZeroNF.a₄
@[simp]
theorem b₂_of_isCharTwoJNeZeroNF : W.b₂ = 1 + 4 * W.a₂ := by
rw [b₂, a₁_of_isCharTwoJNeZeroNF]
ring1
@[simp]
theorem b₄_of_isCharTwoJNeZeroNF : W.b₄ = 0 := by
rw [b₄, a₃_of_isCharTwoJNeZeroNF, a₄_of_isCharTwoJNeZeroNF]
ring1
@[simp]
theorem b₆_of_isCharTwoJNeZeroNF : W.b₆ = 4 * W.a₆ := by
rw [b₆, a₃_of_isCharTwoJNeZeroNF]
ring1
@[simp]
theorem b₈_of_isCharTwoJNeZeroNF : W.b₈ = W.a₆ + 4 * W.a₂ * W.a₆ := by
rw [b₈, a₁_of_isCharTwoJNeZeroNF, a₃_of_isCharTwoJNeZeroNF, a₄_of_isCharTwoJNeZeroNF]
ring1
@[simp]
theorem c₄_of_isCharTwoJNeZeroNF : W.c₄ = W.b₂ ^ 2 := by
rw [c₄, b₄_of_isCharTwoJNeZeroNF]
ring1
@[simp]
theorem c₆_of_isCharTwoJNeZeroNF : W.c₆ = -W.b₂ ^ 3 - 864 * W.a₆ := by
rw [c₆, b₄_of_isCharTwoJNeZeroNF, b₆_of_isCharTwoJNeZeroNF]
ring1
variable [CharP R 2]
theorem b₂_of_isCharTwoJNeZeroNF_of_char_two : W.b₂ = 1 := by
rw [b₂_of_isCharTwoJNeZeroNF]
linear_combination 2 * W.a₂ * CharP.cast_eq_zero R 2
theorem b₆_of_isCharTwoJNeZeroNF_of_char_two : W.b₆ = 0 := by
rw [b₆_of_isCharTwoJNeZeroNF]
linear_combination 2 * W.a₆ * CharP.cast_eq_zero R 2
theorem b₈_of_isCharTwoJNeZeroNF_of_char_two : W.b₈ = W.a₆ := by
rw [b₈_of_isCharTwoJNeZeroNF]
linear_combination 2 * W.a₂ * W.a₆ * CharP.cast_eq_zero R 2
theorem c₄_of_isCharTwoJNeZeroNF_of_char_two : W.c₄ = 1 := by
rw [c₄_of_isCharTwoJNeZeroNF, b₂_of_isCharTwoJNeZeroNF_of_char_two]
ring1
theorem c₆_of_isCharTwoJNeZeroNF_of_char_two : W.c₆ = 1 := by
rw [c₆_of_isCharTwoJNeZeroNF, b₂_of_isCharTwoJNeZeroNF_of_char_two]
linear_combination (-1 - 432 * W.a₆) * CharP.cast_eq_zero R 2
@[simp]
theorem Δ_of_isCharTwoJNeZeroNF_of_char_two : W.Δ = W.a₆ := by
rw [Δ, b₂_of_isCharTwoJNeZeroNF_of_char_two, b₄_of_isCharTwoJNeZeroNF,
b₆_of_isCharTwoJNeZeroNF_of_char_two, b₈_of_isCharTwoJNeZeroNF_of_char_two]
linear_combination -W.a₆ * CharP.cast_eq_zero R 2
variable (W : WeierstrassCurve F) [W.IsElliptic] [W.IsCharTwoJNeZeroNF] [CharP F 2]
@[simp]
theorem j_of_isCharTwoJNeZeroNF_of_char_two : W.j = 1 / W.a₆ := by
rw [j, Units.val_inv_eq_inv_val, ← div_eq_inv_mul, coe_Δ',
c₄_of_isCharTwoJNeZeroNF_of_char_two, Δ_of_isCharTwoJNeZeroNF_of_char_two, one_pow]
theorem j_ne_zero_of_isCharTwoJNeZeroNF_of_char_two : W.j ≠ 0 := by
rw [j_of_isCharTwoJNeZeroNF_of_char_two, div_ne_zero_iff]
have h := W.Δ'.ne_zero
rw [coe_Δ', Δ_of_isCharTwoJNeZeroNF_of_char_two] at h
exact ⟨one_ne_zero, h⟩
end Quantity
/-! ## Normal forms of characteristic = 2 and j = 0 -/
/-- A `WeierstrassCurve` is in normal form of characteristic = 2 and j = 0, if its `a₁, a₂ = 0`.
In other words it is `Y² + a₃Y = X³ + a₄X + a₆`. -/
@[mk_iff]
class IsCharTwoJEqZeroNF : Prop where
a₁ : W.a₁ = 0
a₂ : W.a₂ = 0
section Quantity
variable [W.IsCharTwoJEqZeroNF]
@[simp]
theorem a₁_of_isCharTwoJEqZeroNF : W.a₁ = 0 := IsCharTwoJEqZeroNF.a₁
@[simp]
theorem a₂_of_isCharTwoJEqZeroNF : W.a₂ = 0 := IsCharTwoJEqZeroNF.a₂
@[simp]
theorem b₂_of_isCharTwoJEqZeroNF : W.b₂ = 0 := by
rw [b₂, a₁_of_isCharTwoJEqZeroNF, a₂_of_isCharTwoJEqZeroNF]
ring1
@[simp]
theorem b₄_of_isCharTwoJEqZeroNF : W.b₄ = 2 * W.a₄ := by
rw [b₄, a₁_of_isCharTwoJEqZeroNF]
ring1
@[simp]
theorem b₈_of_isCharTwoJEqZeroNF : W.b₈ = -W.a₄ ^ 2 := by
rw [b₈, a₁_of_isCharTwoJEqZeroNF, a₂_of_isCharTwoJEqZeroNF]
ring1
@[simp]
theorem c₄_of_isCharTwoJEqZeroNF : W.c₄ = -48 * W.a₄ := by
rw [c₄, b₂_of_isCharTwoJEqZeroNF, b₄_of_isCharTwoJEqZeroNF]
ring1
@[simp]
theorem c₆_of_isCharTwoJEqZeroNF : W.c₆ = -216 * W.b₆ := by
rw [c₆, b₂_of_isCharTwoJEqZeroNF, b₄_of_isCharTwoJEqZeroNF]
ring1
@[simp]
theorem Δ_of_isCharTwoJEqZeroNF : W.Δ = -(64 * W.a₄ ^ 3 + 27 * W.b₆ ^ 2) := by
rw [Δ, b₂_of_isCharTwoJEqZeroNF, b₄_of_isCharTwoJEqZeroNF]
ring1
variable [CharP R 2]
theorem b₄_of_isCharTwoJEqZeroNF_of_char_two : W.b₄ = 0 := by
rw [b₄_of_isCharTwoJEqZeroNF]
linear_combination W.a₄ * CharP.cast_eq_zero R 2
theorem b₈_of_isCharTwoJEqZeroNF_of_char_two : W.b₈ = W.a₄ ^ 2 := by
rw [b₈_of_isCharTwoJEqZeroNF]
linear_combination -W.a₄ ^ 2 * CharP.cast_eq_zero R 2
theorem c₄_of_isCharTwoJEqZeroNF_of_char_two : W.c₄ = 0 := by
rw [c₄_of_isCharTwoJEqZeroNF]
linear_combination -24 * W.a₄ * CharP.cast_eq_zero R 2
theorem c₆_of_isCharTwoJEqZeroNF_of_char_two : W.c₆ = 0 := by
rw [c₆_of_isCharTwoJEqZeroNF]
linear_combination -108 * W.b₆ * CharP.cast_eq_zero R 2
theorem Δ_of_isCharTwoJEqZeroNF_of_char_two : W.Δ = W.a₃ ^ 4 := by
rw [Δ_of_isCharTwoJEqZeroNF, b₆_of_char_two]
linear_combination (-32 * W.a₄ ^ 3 - 14 * W.a₃ ^ 4) * CharP.cast_eq_zero R 2
variable (W : WeierstrassCurve F) [W.IsElliptic] [W.IsCharTwoJEqZeroNF]
theorem j_of_isCharTwoJEqZeroNF : W.j = 110592 * W.a₄ ^ 3 / (64 * W.a₄ ^ 3 + 27 * W.b₆ ^ 2) := by
have h := W.Δ'.ne_zero
rw [coe_Δ', Δ_of_isCharTwoJEqZeroNF] at h
rw [j, Units.val_inv_eq_inv_val, ← div_eq_inv_mul, coe_Δ',
c₄_of_isCharTwoJEqZeroNF, Δ_of_isCharTwoJEqZeroNF, div_eq_div_iff h (neg_ne_zero.1 h)]
ring1
@[simp]
theorem j_of_isCharTwoJEqZeroNF_of_char_two [CharP F 2] : W.j = 0 := by
rw [j, c₄_of_isCharTwoJEqZeroNF_of_char_two]; simp
end Quantity
/-! ## Normal forms of characteristic = 2 -/
/-- A `WeierstrassCurve` is in normal form of characteristic = 2, if it is
`Y² + XY = X³ + a₂X² + a₆` (`WeierstrassCurve.IsCharTwoJNeZeroNF`) or
`Y² + a₃Y = X³ + a₄X + a₆` (`WeierstrassCurve.IsCharTwoJEqZeroNF`). -/
class inductive IsCharTwoNF : Prop
| of_j_ne_zero [W.IsCharTwoJNeZeroNF] : IsCharTwoNF
| of_j_eq_zero [W.IsCharTwoJEqZeroNF] : IsCharTwoNF
instance isCharTwoNF_of_isCharTwoJNeZeroNF [W.IsCharTwoJNeZeroNF] : W.IsCharTwoNF :=
IsCharTwoNF.of_j_ne_zero
instance isCharTwoNF_of_isCharTwoJEqZeroNF [W.IsCharTwoJEqZeroNF] : W.IsCharTwoNF :=
IsCharTwoNF.of_j_eq_zero
section VariableChange
variable [CharP R 2] [CharP F 2]
/-- For a `WeierstrassCurve` defined over a ring of characteristic = 2,
there is an explicit change of variables of it to `Y² + a₃Y = X³ + a₄X + a₆`
(`WeierstrassCurve.IsCharTwoJEqZeroNF`) if its j = 0. -/
def toCharTwoJEqZeroNF : VariableChange R := ⟨1, W.a₂, 0, 0⟩
theorem toCharTwoJEqZeroNF_spec (ha₁ : W.a₁ = 0) :
(W.toCharTwoJEqZeroNF • W).IsCharTwoJEqZeroNF := by
constructor
· simp [toCharTwoJEqZeroNF, ha₁, variableChange_a₁]
· simp_rw [toCharTwoJEqZeroNF, variableChange_a₂, inv_one, Units.val_one]
linear_combination 2 * W.a₂ * CharP.cast_eq_zero R 2
variable (W : WeierstrassCurve F)
/-- For a `WeierstrassCurve` defined over a field of characteristic = 2,
there is an explicit change of variables of it to `Y² + XY = X³ + a₂X² + a₆`
(`WeierstrassCurve.IsCharTwoJNeZeroNF`) if its j ≠ 0. -/
def toCharTwoJNeZeroNF (W : WeierstrassCurve F) (ha₁ : W.a₁ ≠ 0) : VariableChange F :=
⟨Units.mk0 _ ha₁, W.a₃ / W.a₁, 0, (W.a₁ ^ 2 * W.a₄ + W.a₃ ^ 2) / W.a₁ ^ 3⟩
theorem toCharTwoJNeZeroNF_spec (ha₁ : W.a₁ ≠ 0) :
(W.toCharTwoJNeZeroNF ha₁ • W).IsCharTwoJNeZeroNF := by
constructor
· simp [toCharTwoJNeZeroNF, ha₁, variableChange_a₁]
· field_simp [toCharTwoJNeZeroNF, variableChange_a₃]
linear_combination (W.a₃ * W.a₁ ^ 3 + W.a₁ ^ 2 * W.a₄ + W.a₃ ^ 2) * CharP.cast_eq_zero F 2
· field_simp [toCharTwoJNeZeroNF, variableChange_a₄]
linear_combination (W.a₁ ^ 4 * W.a₃ ^ 2 + W.a₁ ^ 5 * W.a₃ * W.a₂) * CharP.cast_eq_zero F 2
/-- For a `WeierstrassCurve` defined over a field of characteristic = 2,
there is an explicit change of variables of it to `WeierstrassCurve.IsCharTwoNF`, that is,
`Y² + XY = X³ + a₂X² + a₆` (`WeierstrassCurve.IsCharTwoJNeZeroNF`) or
`Y² + a₃Y = X³ + a₄X + a₆` (`WeierstrassCurve.IsCharTwoJEqZeroNF`). -/
def toCharTwoNF [DecidableEq F] : VariableChange F :=
if ha₁ : W.a₁ = 0 then W.toCharTwoJEqZeroNF else W.toCharTwoJNeZeroNF ha₁
instance toCharTwoNF_spec [DecidableEq F] : (W.toCharTwoNF • W).IsCharTwoNF := by
by_cases ha₁ : W.a₁ = 0
· rw [toCharTwoNF, dif_pos ha₁]
haveI := W.toCharTwoJEqZeroNF_spec ha₁
infer_instance
· rw [toCharTwoNF, dif_neg ha₁]
haveI := W.toCharTwoJNeZeroNF_spec ha₁
infer_instance
theorem exists_variableChange_isCharTwoNF : ∃ C : VariableChange F, (C • W).IsCharTwoNF := by
classical
exact ⟨_, W.toCharTwoNF_spec⟩
end VariableChange
end WeierstrassCurve
|
Defs.lean
|
/-
Copyright (c) 2023 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash, Deepro Choudhury, Scott Carnahan
-/
import Mathlib.LinearAlgebra.PerfectPairing.Basic
import Mathlib.LinearAlgebra.Reflection
/-!
# Root data and root systems
This file contains basic definitions for root systems and root data.
## Main definitions:
* `RootPairing`: Given two perfectly-paired `R`-modules `M` and `N` (over some commutative ring
`R`) a root pairing with indexing set `ι` is the data of an `ι`-indexed subset of `M`
("the roots") an `ι`-indexed subset of `N` ("the coroots"), and an `ι`-indexed set of
permutations of `ι` such that each root-coroot pair evaluates to `2`, and the permutation
attached to each element of `ι` is compatible with the reflections on the corresponding roots and
coroots.
* `RootDatum`: A root datum is a root pairing for which the roots and coroots take values in
finitely-generated free Abelian groups.
* `RootSystem`: A root system is a root pairing for which the roots span their ambient module.
## Implementation details
A root datum is sometimes defined as two subsets: roots and coroots, together with a bijection
between them, subject to hypotheses. However the hypotheses ensure that the bijection is unique and
so the question arises of whether this bijection should be part of the data of a root datum or
whether one should merely assert its existence. For root systems, things are even more extreme: the
coroots are uniquely determined by the roots. Furthermore a root system induces a canonical
non-degenerate bilinear form on the ambient space and many informal accounts even include this form
as part of the data.
We have opted for a design in which some of the uniquely-determined data is included: the bijection
between roots and coroots is (implicitly) included and the coroots are included for root systems.
Empirically this seems to be by far the most convenient design and by providing extensionality
lemmas expressing the uniqueness we expect to get the best of both worlds.
Furthermore, we require roots and coroots to be injections from a base indexing type `ι` rather than
subsets of their codomains. This design was chosen to avoid the bijection between roots and coroots
being a dependently-typed object. A third option would be to have the roots and coroots be subsets
but to avoid having a dependently-typed bijection by defining it globally with junk value `0`
outside of the roots and coroots. This would work but lacks the convenient symmetry that the chosen
design enjoys: by introducing the indexing type `ι`, one does not have to pick a direction
(`roots → coroots` or `coroots → roots`) for the forward direction of the bijection. Besides,
providing the user with the additional definitional power to specify an indexing type `ι` is a
benefit and the junk-value pattern is a cost.
As a final point of divergence from the classical literature, we make the reflection permutation on
roots and coroots explicit, rather than specifying only that reflection preserves the sets of roots
and coroots. This is necessary when working with infinite root systems, where the coroots are not
uniquely determined by the roots, because without it, the reflection permutations on roots and
coroots may not correspond. For this purpose, we define a map from `ι` to permutations on `ι`, and
require that it is compatible with reflections and coreflections.
-/
open Set Function
open Module hiding reflection
open Submodule (span)
open AddSubgroup (zmultiples)
noncomputable section
variable (ι R M N : Type*)
[CommRing R] [AddCommGroup M] [Module R M] [AddCommGroup N] [Module R N]
/-- Given two perfectly-paired `R`-modules `M` and `N`, a root pairing with indexing set `ι`
is the data of an `ι`-indexed subset of `M` ("the roots"), an `ι`-indexed subset of `N`
("the coroots"), and an `ι`-indexed set of permutations of `ι`, such that each root-coroot pair
evaluates to `2`, and the permutation attached to each element of `ι` is compatible with the
reflections on the corresponding roots and coroots.
It exists to allow for a convenient unification of the theories of root systems and root data. -/
structure RootPairing extends PerfectPairing R M N where
/-- A parametrized family of vectors, called roots. -/
root : ι ↪ M
/-- A parametrized family of dual vectors, called coroots. -/
coroot : ι ↪ N
root_coroot_two : ∀ i, toLinearMap (root i) (coroot i) = 2
/-- A parametrized family of permutations, induced by reflections. This corresponds to the
classical requirement that the symmetry attached to each root (later defined in
`RootPairing.reflection`) leave the whole set of roots stable: as explained above, we
formalize this stability by fixing the image of the roots through each reflection (whence the
permutation); and similarly for coroots. -/
reflectionPerm : ι → (ι ≃ ι)
reflectionPerm_root : ∀ i j,
root j - toPerfectPairing (root j) (coroot i) • root i = root (reflectionPerm i j)
reflectionPerm_coroot : ∀ i j,
coroot j - toPerfectPairing (root i) (coroot j) • coroot i = coroot (reflectionPerm i j)
/-- A root datum is a root pairing with coefficients in the integers and for which the root and
coroot spaces are finitely-generated free Abelian groups.
Note that the latter assumptions `[Finite ℤ X₁] [Finite ℤ X₂]` should be supplied as mixins, and
that freeness follows automatically since two finitely-generated Abelian groups in perfect pairing
are necessarily free. Moreover Lean knows this, e.g., via `PerfectPairing.reflexive_left`,
`Module.instNoZeroSMulDivisorsOfIsDomain`, `Module.free_of_finite_type_torsion_free'`. -/
abbrev RootDatum (X₁ X₂ : Type*) [AddCommGroup X₁] [AddCommGroup X₂] := RootPairing ι ℤ X₁ X₂
/-- A root system is a root pairing for which the roots and coroots span their ambient modules.
Note that this is slightly more general than the usual definition in the sense that `N` is not
required to be the dual of `M`. -/
structure RootSystem extends RootPairing ι R M N where
span_root_eq_top : span R (range root) = ⊤
span_coroot_eq_top : span R (range coroot) = ⊤
attribute [simp] RootSystem.span_root_eq_top
attribute [simp] RootSystem.span_coroot_eq_top
namespace RootPairing
variable {ι R M N}
variable (P : RootPairing ι R M N) (i j : ι)
@[simp]
lemma toLinearMap_eq_toPerfectPairing (x : M) (y : N) :
P.toLinearMap x y = P.toPerfectPairing x y := rfl
@[deprecated (since := "2025-04-20")]
alias toLin_toPerfectPairing := toLinearMap_eq_toPerfectPairing
/-- If we interchange the roles of `M` and `N`, we still have a root pairing. -/
protected def flip : RootPairing ι R N M :=
{ P.toPerfectPairing.flip with
root := P.coroot
coroot := P.root
root_coroot_two := P.root_coroot_two
reflectionPerm := P.reflectionPerm
reflectionPerm_root := P.reflectionPerm_coroot
reflectionPerm_coroot := P.reflectionPerm_root }
@[simp]
lemma flip_flip : P.flip.flip = P :=
rfl
variable (ι R M N) in
/-- `RootPairing.flip` as an equivalence. -/
@[simps] def flipEquiv : RootPairing ι R N M ≃ RootPairing ι R M N where
toFun P := P.flip
invFun P := P.flip
/-- If we interchange the roles of `M` and `N`, we still have a root system. -/
protected def _root_.RootSystem.flip (P : RootSystem ι R M N) : RootSystem ι R N M :=
{ toRootPairing := P.toRootPairing.flip
span_root_eq_top := P.span_coroot_eq_top
span_coroot_eq_top := P.span_root_eq_top }
@[simp]
protected lemma _root_.RootSystem.flip_flip (P : RootSystem ι R M N) :
P.flip.flip = P :=
rfl
variable (ι R M N) in
/-- `RootSystem.flip` as an equivalence. -/
@[simps] def _root_.RootSystem.flipEquiv : RootSystem ι R N M ≃ RootSystem ι R M N where
toFun P := P.flip
invFun P := P.flip
lemma ne_zero [NeZero (2 : R)] : (P.root i : M) ≠ 0 :=
fun h ↦ NeZero.ne' (2 : R) <| by simpa [h] using P.root_coroot_two i
lemma ne_zero' [NeZero (2 : R)] : (P.coroot i : N) ≠ 0 :=
P.flip.ne_zero i
lemma zero_notMem_range_root [NeZero (2 : R)] : 0 ∉ range P.root := by
simpa only [mem_range, not_exists] using fun i ↦ P.ne_zero i
@[deprecated (since := "2025-05-24")] alias zero_nmem_range_root := zero_notMem_range_root
lemma zero_notMem_range_coroot [NeZero (2 : R)] : 0 ∉ range P.coroot :=
P.flip.zero_notMem_range_root
@[deprecated (since := "2025-05-24")] alias zero_nmem_range_coroot := zero_notMem_range_coroot
lemma exists_ne_zero [Nonempty ι] [NeZero (2 : R)] : ∃ i, P.root i ≠ 0 := by
obtain ⟨i⟩ := inferInstanceAs (Nonempty ι)
exact ⟨i, P.ne_zero i⟩
lemma exists_ne_zero' [Nonempty ι] [NeZero (2 : R)] : ∃ i, P.coroot i ≠ 0 :=
P.flip.exists_ne_zero
include P in
protected lemma nontrivial [Nonempty ι] [NeZero (2 : R)] : Nontrivial M := by
obtain ⟨i, hi⟩ := P.exists_ne_zero
exact ⟨P.root i, 0, hi⟩
include P in
protected lemma nontrivial' [Nonempty ι] [NeZero (2 : R)] : Nontrivial N :=
P.flip.nontrivial
/-- Roots written as functionals on the coweight space. -/
abbrev root' (i : ι) : Dual R N := P.toPerfectPairing (P.root i)
/-- Coroots written as functionals on the weight space. -/
abbrev coroot' (i : ι) : Dual R M := P.toPerfectPairing.flip (P.coroot i)
/-- This is the pairing between roots and coroots. -/
def pairing : R := P.root' i (P.coroot j)
@[simp]
lemma root_coroot_eq_pairing : P.toPerfectPairing (P.root i) (P.coroot j) = P.pairing i j :=
rfl
@[simp]
lemma root'_coroot_eq_pairing : P.root' i (P.coroot j) = P.pairing i j :=
rfl
@[simp]
lemma root_coroot'_eq_pairing : P.coroot' i (P.root j) = P.pairing j i :=
rfl
lemma coroot_root_eq_pairing : P.toLinearMap.flip (P.coroot i) (P.root j) = P.pairing j i := by
simp
@[simp]
lemma pairing_same : P.pairing i i = 2 := P.root_coroot_two i
variable {P} in
lemma pairing_eq_add_of_root_eq_add {i j k l : ι} (h : P.root k = P.root i + P.root j) :
P.pairing k l = P.pairing i l + P.pairing j l := by
simp only [← root_coroot_eq_pairing, h, map_add, LinearMap.add_apply]
variable {P} in
lemma pairing_eq_add_of_root_eq_smul_add_smul
{i j k l : ι} {x y : R} (h : P.root k = x • P.root i + y • P.root l) :
P.pairing k j = x • P.pairing i j + y • P.pairing l j := by
simp only [← root_coroot_eq_pairing, h, map_add, map_smul, LinearMap.add_apply,
LinearMap.smul_apply, smul_eq_mul]
lemma coroot_root_two :
P.toLinearMap.flip (P.coroot i) (P.root i) = 2 := by
simp
/-- The reflection associated to a root. -/
def reflection : M ≃ₗ[R] M :=
Module.reflection (P.flip.root_coroot_two i)
@[simp]
lemma root_reflectionPerm (j : ι) :
P.root (P.reflectionPerm i j) = (P.reflection i) (P.root j) :=
(P.reflectionPerm_root i j).symm
@[deprecated (since := "2025-05-28")] alias root_reflection_perm := root_reflectionPerm
theorem mapsTo_reflection_root :
MapsTo (P.reflection i) (range P.root) (range P.root) := by
rintro - ⟨j, rfl⟩
exact P.root_reflectionPerm i j ▸ mem_range_self (P.reflectionPerm i j)
lemma reflection_apply (x : M) :
P.reflection i x = x - (P.coroot' i x) • P.root i :=
rfl
lemma reflection_apply_root :
P.reflection i (P.root j) = P.root j - (P.pairing j i) • P.root i :=
rfl
@[simp]
lemma reflection_apply_self :
P.reflection i (P.root i) = - P.root i :=
Module.reflection_apply_self (P.coroot_root_two i)
@[simp]
lemma reflection_same (x : M) :
P.reflection i (P.reflection i x) = x :=
Module.involutive_reflection (P.coroot_root_two i) x
@[simp]
lemma reflection_inv :
(P.reflection i)⁻¹ = P.reflection i :=
rfl
@[simp]
lemma reflection_sq : P.reflection i ^ 2 = 1 :=
mul_eq_one_iff_eq_inv.mpr rfl
@[simp]
lemma reflectionPerm_sq : P.reflectionPerm i ^ 2 = 1 := by
ext j
apply P.root.injective
simp only [sq, Equiv.Perm.mul_apply, root_reflectionPerm, reflection_same, Equiv.Perm.one_apply]
@[deprecated (since := "2025-05-28")] alias reflection_perm_sq := reflectionPerm_sq
@[simp]
lemma reflectionPerm_inv : (P.reflectionPerm i)⁻¹ = P.reflectionPerm i :=
(mul_eq_one_iff_eq_inv.mp <| P.reflectionPerm_sq i).symm
@[deprecated (since := "2025-05-28")] alias reflection_perm_inv := reflectionPerm_inv
@[simp]
lemma reflectionPerm_self : P.reflectionPerm i (P.reflectionPerm i j) = j := by
apply P.root.injective
simp only [root_reflectionPerm, reflection_same]
@[deprecated (since := "2025-05-28")] alias reflection_perm_self := reflectionPerm_self
lemma reflectionPerm_involutive : Involutive (P.reflectionPerm i) :=
involutive_iff_iter_2_eq_id.mpr (by ext; simp)
@[deprecated (since := "2025-05-28")] alias reflection_perm_involutive := reflectionPerm_involutive
@[simp]
lemma reflectionPerm_symm : (P.reflectionPerm i).symm = P.reflectionPerm i :=
Involutive.symm_eq_self_of_involutive (P.reflectionPerm i) <| P.reflectionPerm_involutive i
@[deprecated (since := "2025-05-28")] alias reflection_perm_symm := reflectionPerm_symm
lemma bijOn_reflection_root :
BijOn (P.reflection i) (range P.root) (range P.root) :=
Module.bijOn_reflection_of_mapsTo _ <| P.mapsTo_reflection_root i
@[simp]
lemma reflection_image_eq :
P.reflection i '' (range P.root) = range P.root :=
(P.bijOn_reflection_root i).image_eq
/-- The reflection associated to a coroot. -/
def coreflection : N ≃ₗ[R] N :=
Module.reflection (P.root_coroot_two i)
@[simp]
lemma coroot_reflectionPerm (j : ι) :
P.coroot (P.reflectionPerm i j) = (P.coreflection i) (P.coroot j) :=
(P.reflectionPerm_coroot i j).symm
@[deprecated (since := "2025-05-28")] alias coroot_reflection_perm := coroot_reflectionPerm
theorem mapsTo_coreflection_coroot :
MapsTo (P.coreflection i) (range P.coroot) (range P.coroot) := by
rintro - ⟨j, rfl⟩
exact P.coroot_reflectionPerm i j ▸ mem_range_self (P.reflectionPerm i j)
lemma coreflection_apply (f : N) :
P.coreflection i f = f - (P.root' i) f • P.coroot i :=
rfl
lemma coreflection_apply_coroot :
P.coreflection i (P.coroot j) = P.coroot j - (P.pairing i j) • P.coroot i :=
rfl
@[simp]
lemma coreflection_apply_self :
P.coreflection i (P.coroot i) = - P.coroot i :=
Module.reflection_apply_self (P.flip.coroot_root_two i)
@[simp]
lemma coreflection_same (x : N) :
P.coreflection i (P.coreflection i x) = x :=
Module.involutive_reflection (P.flip.coroot_root_two i) x
@[simp]
lemma coreflection_inv :
(P.coreflection i)⁻¹ = P.coreflection i :=
rfl
@[simp]
lemma coreflection_sq :
P.coreflection i ^ 2 = 1 :=
mul_eq_one_iff_eq_inv.mpr rfl
lemma bijOn_coreflection_coroot : BijOn (P.coreflection i) (range P.coroot) (range P.coroot) :=
bijOn_reflection_root P.flip i
@[simp]
lemma coreflection_image_eq :
P.coreflection i '' (range P.coroot) = range P.coroot :=
(P.bijOn_coreflection_coroot i).image_eq
lemma coreflection_eq_flip_reflection :
P.coreflection i = P.flip.reflection i :=
rfl
lemma reflection_reflectionPerm {i j : ι} :
P.reflection (P.reflectionPerm j i) = P.reflection j * P.reflection i * P.reflection j := by
ext x
simp only [reflection_apply, coreflection_apply, PerfectPairing.flip_apply_apply,
coroot_reflectionPerm, root_coroot_eq_pairing, map_sub, map_smul, smul_eq_mul,
root_reflectionPerm, LinearEquiv.mul_apply, pairing_same]
module
lemma reflection_dualMap_eq_coreflection :
(P.reflection i).dualMap ∘ₗ P.toLinearMap.flip = P.toLinearMap.flip ∘ₗ P.coreflection i := by
ext n m
simp [map_sub, coreflection_apply, reflection_apply, mul_comm (P.toPerfectPairing m (P.coroot i))]
lemma coroot_eq_coreflection_of_root_eq
{i j k : ι} (hk : P.root k = P.reflection i (P.root j)) :
P.coroot k = P.coreflection i (P.coroot j) := by
rw [← P.root_reflectionPerm, EmbeddingLike.apply_eq_iff_eq] at hk
rw [← P.coroot_reflectionPerm, hk]
lemma coroot'_reflectionPerm {i j : ι} :
P.coroot' (P.reflectionPerm i j) = P.coroot' j ∘ₗ P.reflection i := by
ext y
simp [coreflection_apply_coroot, reflection_apply, map_sub, mul_comm]
@[deprecated (since := "2025-05-28")] alias coroot'_reflection_perm := coroot'_reflectionPerm
lemma coroot'_reflection {i j : ι} (y : M) :
P.coroot' j (P.reflection i y) = P.coroot' (P.reflectionPerm i j) y :=
(LinearMap.congr_fun P.coroot'_reflectionPerm y).symm
lemma pairing_reflectionPerm (i j k : ι) :
P.pairing j (P.reflectionPerm i k) = P.pairing (P.reflectionPerm i j) k := by
simp only [pairing, root', coroot_reflectionPerm, root_reflectionPerm]
simp only [coreflection_apply_coroot, map_sub, map_smul, smul_eq_mul,
reflection_apply_root]
simp [← toLinearMap_eq_toPerfectPairing, LinearMap.smul_apply,
LinearMap.sub_apply, smul_eq_mul]
simp [mul_comm]
@[deprecated (since := "2025-05-28")] alias pairing_reflection_perm := pairing_reflectionPerm
@[simp]
lemma toDualLeft_conj_reflection :
P.toDualLeft.conj (P.reflection i) = (P.coreflection i).toLinearMap.dualMap := by
ext f n
simp [LinearEquiv.conj_apply, reflection_apply, coreflection_apply, mul_comm (f <| P.coroot i)]
@[simp]
lemma toDualRight_conj_coreflection :
P.toDualRight.conj (P.coreflection i) = (P.reflection i).toLinearMap.dualMap :=
P.flip.toDualLeft_conj_reflection i
@[simp]
lemma pairing_reflectionPerm_self_left (P : RootPairing ι R M N) (i j : ι) :
P.pairing (P.reflectionPerm i i) j = - P.pairing i j := by
rw [pairing, root', ← reflectionPerm_root, root'_coroot_eq_pairing, pairing_same, two_smul,
sub_add_cancel_left, ← toLinearMap_eq_toPerfectPairing, LinearMap.map_neg₂,
toLinearMap_eq_toPerfectPairing, root'_coroot_eq_pairing]
@[deprecated (since := "2025-05-28")]
alias pairing_reflection_perm_self_left := pairing_reflectionPerm_self_left
@[simp]
lemma pairing_reflectionPerm_self_right (i j : ι) :
P.pairing i (P.reflectionPerm j j) = - P.pairing i j := by
rw [pairing, ← reflectionPerm_coroot, root_coroot_eq_pairing, pairing_same, two_smul,
sub_add_cancel_left, ← toLinearMap_eq_toPerfectPairing, map_neg,
toLinearMap_eq_toPerfectPairing, root_coroot_eq_pairing]
@[deprecated (since := "2025-05-28")]
alias pairing_reflection_perm_self_right := pairing_reflectionPerm_self_right
/-- The indexing set of a root pairing carries an involutive negation, corresponding to the negation
of a root / coroot. -/
@[simps] def indexNeg : InvolutiveNeg ι where
neg i := P.reflectionPerm i i
neg_neg i := by
apply P.root.injective
simp only [root_reflectionPerm, reflection_apply, PerfectPairing.flip_apply_apply,
root_coroot_eq_pairing, pairing_same, map_sub, map_smul, coroot_reflectionPerm,
coreflection_apply_self, map_neg]
module
lemma ne_neg [NeZero (2 : R)] [IsDomain R] :
letI := P.indexNeg
i ≠ -i := by
have := P.reflexive_left
intro contra
replace contra : P.root i = -P.root i := by simpa using congr_arg P.root contra
simp [eq_neg_iff_add_eq_zero, ← two_smul R, NeZero.out, P.ne_zero i] at contra
variable {i j} in
@[simp]
lemma root_eq_neg_iff :
P.root i = - P.root j ↔ i = P.reflectionPerm j j := by
refine ⟨fun h ↦ P.root.injective ?_, fun h ↦ by simp [h]⟩
rw [root_reflectionPerm, reflection_apply_self, h]
variable {i j} in
@[simp]
lemma coroot_eq_neg_iff :
P.coroot i = - P.coroot j ↔ i = P.reflectionPerm j j :=
P.flip.root_eq_neg_iff
lemma neg_mem_range_root_iff {x : M} :
-x ∈ range P.root ↔ x ∈ range P.root := by
suffices ∀ x : M, -x ∈ range P.root → x ∈ range P.root by
refine ⟨this x, fun h ↦ ?_⟩
rw [← neg_neg x] at h
exact this (-x) h
intro y ⟨i, hi⟩
exact ⟨P.reflectionPerm i i, by simp [neg_eq_iff_eq_neg.mpr hi]⟩
lemma neg_mem_range_coroot_iff {x : N} :
-x ∈ range P.coroot ↔ x ∈ range P.coroot :=
P.flip.neg_mem_range_root_iff
lemma neg_root_mem :
- P.root i ∈ range P.root :=
⟨P.reflectionPerm i i, by simp⟩
lemma neg_coroot_mem :
- P.coroot i ∈ range P.coroot :=
P.flip.neg_root_mem i
variable {P} in
lemma smul_coroot_eq_of_root_eq_smul [Finite ι] [NoZeroSMulDivisors ℤ N] (i j : ι) (t : R)
(h : P.root j = t • P.root i) :
t • P.coroot j = P.coroot i := by
have hij : t * P.pairing i j = 2 := by simpa using ((P.coroot' j).congr_arg h).symm
refine Module.eq_of_mapsTo_reflection_of_mem (f := P.root' i) (g := P.root' i)
(finite_range P.coroot) (by simp [hij]) (by simp) (by simp [hij]) (by simp) ?_
(P.mapsTo_coreflection_coroot i) (mem_range_self i)
convert P.mapsTo_coreflection_coroot j
ext x
replace h : P.root' j = t • P.root' i := by ext; simp [h, root']
simp [Module.preReflection_apply, coreflection_apply, h, smul_comm _ t, mul_smul]
variable {P} in
@[simp] lemma coroot_eq_smul_coroot_iff [Finite ι] [NoZeroSMulDivisors ℤ M] [NoZeroSMulDivisors ℤ N]
{i j : ι} {t : R} :
P.coroot i = t • P.coroot j ↔ P.root j = t • P.root i :=
⟨fun h ↦ (P.flip.smul_coroot_eq_of_root_eq_smul j i t h).symm,
fun h ↦ (P.smul_coroot_eq_of_root_eq_smul i j t h).symm⟩
lemma mem_range_root_of_mem_range_reflection_of_mem_range_root
{r : M ≃ₗ[R] M} {α : M} (hr : r ∈ range P.reflection) (hα : α ∈ range P.root) :
r • α ∈ range P.root := by
obtain ⟨i, rfl⟩ := hr
obtain ⟨j, rfl⟩ := hα
exact ⟨P.reflectionPerm i j, P.root_reflectionPerm i j⟩
lemma mem_range_coroot_of_mem_range_coreflection_of_mem_range_coroot
{r : N ≃ₗ[R] N} {α : N} (hr : r ∈ range P.coreflection) (hα : α ∈ range P.coroot) :
r • α ∈ range P.coroot := by
obtain ⟨i, rfl⟩ := hr
obtain ⟨j, rfl⟩ := hα
exact ⟨P.reflectionPerm i j, P.coroot_reflectionPerm i j⟩
lemma pairing_smul_root_eq (k : ι) (hij : P.reflectionPerm i = P.reflectionPerm j) :
P.pairing k i • P.root i = P.pairing k j • P.root j := by
have h : P.reflection i (P.root k) = P.reflection j (P.root k) := by
simp only [← root_reflectionPerm, hij]
simpa only [reflection_apply_root, sub_right_inj] using h
lemma pairing_smul_coroot_eq (k : ι) (hij : P.reflectionPerm i = P.reflectionPerm j) :
P.pairing i k • P.coroot i = P.pairing j k • P.coroot j := by
have h : P.coreflection i (P.coroot k) = P.coreflection j (P.coroot k) := by
simp only [← coroot_reflectionPerm, hij]
simpa only [coreflection_apply_coroot, sub_right_inj] using h
lemma two_nsmul_reflection_eq_of_perm_eq (hij : P.reflectionPerm i = P.reflectionPerm j) :
2 • ⇑(P.reflection i) = 2 • P.reflection j := by
ext x
suffices
2 • P.toLinearMap x (P.coroot i) • P.root i = 2 • P.toLinearMap x (P.coroot j) • P.root j by
simpa [reflection_apply, smul_sub]
calc 2 • P.toLinearMap x (P.coroot i) • P.root i
= P.toLinearMap x (P.coroot i) • ((2 : R) • P.root i) := ?_
_ = P.toLinearMap x (P.coroot i) • (P.pairing i j • P.root j) := ?_
_ = P.toLinearMap x (P.pairing i j • P.coroot i) • (P.root j) := ?_
_ = P.toLinearMap x ((2 : R) • P.coroot j) • (P.root j) := ?_
_ = 2 • P.toLinearMap x (P.coroot j) • P.root j := ?_
· rw [smul_comm, ← Nat.cast_smul_eq_nsmul R, Nat.cast_ofNat]
· rw [P.pairing_smul_root_eq j i i hij.symm, pairing_same]
· rw [← smul_comm, ← smul_assoc, map_smul]
· rw [← P.pairing_smul_coroot_eq j i j hij.symm, pairing_same]
· rw [map_smul, smul_assoc, ← Nat.cast_smul_eq_nsmul R, Nat.cast_ofNat]
lemma reflectionPerm_eq_reflectionPerm_iff_of_isSMulRegular (h2 : IsSMulRegular M 2) :
P.reflectionPerm i = P.reflectionPerm j ↔ P.reflection i = P.reflection j := by
refine ⟨fun h ↦ ?_, fun h ↦ Equiv.ext fun k ↦ P.root.injective <| by simp [h]⟩
suffices ⇑(P.reflection i) = ⇑(P.reflection j) from DFunLike.coe_injective this
replace h2 : IsSMulRegular (M → M) 2 := IsSMulRegular.pi fun _ ↦ h2
exact h2 <| P.two_nsmul_reflection_eq_of_perm_eq i j h
@[deprecated (since := "2025-05-28")]
alias reflection_perm_eq_reflection_perm_iff_of_isSMulRegular :=
reflectionPerm_eq_reflectionPerm_iff_of_isSMulRegular
lemma reflectionPerm_eq_reflectionPerm_iff_of_span :
P.reflectionPerm i = P.reflectionPerm j ↔
∀ x ∈ span R (range P.root), P.reflection i x = P.reflection j x := by
refine ⟨fun h x hx ↦ ?_, fun h ↦ ?_⟩
· induction hx using Submodule.span_induction with
| mem x hx =>
obtain ⟨k, rfl⟩ := hx
simp only [← root_reflectionPerm, h]
| zero => simp
| add x y _ _ hx hy => simp [hx, hy]
| smul t x _ hx => simp [hx]
· ext k
apply P.root.injective
simp [h (P.root k) (Submodule.subset_span <| mem_range_self k)]
@[deprecated (since := "2025-05-28")]
alias reflection_perm_eq_reflection_perm_iff_of_span := reflectionPerm_eq_reflectionPerm_iff_of_span
lemma _root_.RootSystem.reflectionPerm_eq_reflectionPerm_iff (P : RootSystem ι R M N) (i j : ι) :
P.reflectionPerm i = P.reflectionPerm j ↔ P.reflection i = P.reflection j := by
refine ⟨fun h ↦ ?_, fun h ↦ Equiv.ext fun k ↦ P.root.injective <| by simp [h]⟩
ext x
exact (P.reflectionPerm_eq_reflectionPerm_iff_of_span i j).mp h x <| by simp
@[deprecated (since := "2025-05-28")]
alias _root_.RootSystem.reflection_perm_eq_reflection_perm_iff :=
_root_.RootSystem.reflectionPerm_eq_reflectionPerm_iff
@[simp] lemma toDualLeft_comp_root : P.toDualLeft ∘ P.root = P.root' := rfl
@[simp] lemma toDualRight_comp_root : P.toDualRight ∘ P.coroot = P.coroot' := rfl
/-- The Coxeter Weight of a pair gives the weight of an edge in a Coxeter diagram, when it is
finite. It is `4 cos² θ`, where `θ` describes the dihedral angle between hyperplanes. -/
def coxeterWeight : R := pairing P i j * pairing P j i
lemma coxeterWeight_swap : coxeterWeight P i j = coxeterWeight P j i := by
simp only [coxeterWeight, mul_comm]
/-- Two roots are orthogonal when they are fixed by each others' reflections. -/
def IsOrthogonal : Prop := pairing P i j = 0 ∧ pairing P j i = 0
lemma isOrthogonal_symm : IsOrthogonal P i j ↔ IsOrthogonal P j i := by
simp only [IsOrthogonal, and_comm]
lemma isOrthogonal_comm (h : IsOrthogonal P i j) : Commute (P.reflection i) (P.reflection j) := by
rw [commute_iff_eq]
ext v
replace h : P.pairing i j = 0 ∧ P.pairing j i = 0 := by simpa [IsOrthogonal] using h
erw [Module.End.mul_apply, Module.End.mul_apply]
simp only [LinearEquiv.coe_coe, reflection_apply, PerfectPairing.flip_apply_apply, map_sub,
map_smul, root_coroot_eq_pairing, h, zero_smul, sub_zero]
abel
variable {P i j}
lemma IsOrthogonal.flip (h : IsOrthogonal P i j) : IsOrthogonal P.flip i j := ⟨h.2, h.1⟩
lemma IsOrthogonal.symm (h : IsOrthogonal P i j) : IsOrthogonal P j i := ⟨h.2, h.1⟩
lemma IsOrthogonal.reflection_apply_left (h : IsOrthogonal P i j) :
P.reflection j (P.root i) = P.root i := by
simp [reflection_apply, h.1]
lemma IsOrthogonal.reflection_apply_right (h : IsOrthogonal P j i) :
P.reflection j (P.root i) = P.root i :=
h.symm.reflection_apply_left
lemma IsOrthogonal.coreflection_apply_left (h : IsOrthogonal P i j) :
P.coreflection j (P.coroot i) = P.coroot i :=
h.flip.reflection_apply_left
lemma IsOrthogonal.coreflection_apply_right (h : IsOrthogonal P j i) :
P.coreflection j (P.coroot i) = P.coroot i :=
h.flip.reflection_apply_right
lemma isFixedPt_reflection_of_isOrthogonal {s : Set ι} (hj : ∀ i ∈ s, P.IsOrthogonal j i)
{x : M} (hx : x ∈ span R (P.root '' s)) :
IsFixedPt (P.reflection j) x := by
rw [IsFixedPt]
induction hx using Submodule.span_induction with
| zero => rw [map_zero]
| add u v hu hv hu' hv' => rw [map_add, hu', hv']
| smul t u hu hu' => rw [map_smul, hu']
| mem u hu =>
obtain ⟨i, his, rfl⟩ := hu
exact IsOrthogonal.reflection_apply_right <| hj i his
lemma reflectionPerm_eq_of_pairing_eq_zero (h : P.pairing j i = 0) :
P.reflectionPerm i j = j :=
P.root.injective <| by simp [reflection_apply, h]
@[deprecated (since := "2025-05-28")]
alias reflection_perm_eq_of_pairing_eq_zero := reflectionPerm_eq_of_pairing_eq_zero
lemma reflectionPerm_eq_of_pairing_eq_zero' (h : P.pairing i j = 0) :
P.reflectionPerm i j = j :=
P.flip.reflectionPerm_eq_of_pairing_eq_zero h
@[deprecated (since := "2025-05-28")]
alias reflection_perm_eq_of_pairing_eq_zero' := reflectionPerm_eq_of_pairing_eq_zero'
lemma reflectionPerm_eq_iff_smul_root :
P.reflectionPerm i j = j ↔ P.pairing j i • P.root i = 0 :=
⟨fun h ↦ by simpa [h] using P.reflectionPerm_root i j,
fun h ↦ P.root.injective <| by simp [reflection_apply, h]⟩
@[deprecated (since := "2025-05-28")]
alias reflection_perm_eq_iff_smul_root := reflectionPerm_eq_iff_smul_root
lemma reflectionPerm_eq_iff_smul_coroot :
P.reflectionPerm i j = j ↔ P.pairing i j • P.coroot i = 0 :=
P.flip.reflectionPerm_eq_iff_smul_root
@[deprecated (since := "2025-05-28")]
alias reflection_perm_eq_iff_smul_coroot := reflectionPerm_eq_iff_smul_coroot
lemma pairing_eq_zero_iff [NeZero (2 : R)] [NoZeroSMulDivisors R M] :
P.pairing i j = 0 ↔ P.pairing j i = 0 := by
suffices ∀ {i j : ι}, P.pairing i j = 0 → P.pairing j i = 0 from ⟨this, this⟩
intro i j h
simpa [P.ne_zero i, reflectionPerm_eq_iff_smul_root] using
P.reflectionPerm_eq_of_pairing_eq_zero' h
lemma pairing_eq_zero_iff' [NeZero (2 : R)] [IsDomain R] :
P.pairing i j = 0 ↔ P.pairing j i = 0 := by
have := P.reflexive_left
exact pairing_eq_zero_iff
lemma coxeterWeight_zero_iff_isOrthogonal [NeZero (2 : R)] [IsDomain R] :
P.coxeterWeight i j = 0 ↔ P.IsOrthogonal i j := by
have := P.reflexive_left
simp [coxeterWeight, IsOrthogonal, P.pairing_eq_zero_iff (i := i) (j := j)]
lemma isOrthogonal_iff_pairing_eq_zero [NeZero (2 : R)] [NoZeroSMulDivisors R M] :
P.IsOrthogonal i j ↔ P.pairing i j = 0 :=
⟨fun h ↦ h.1, fun h ↦ ⟨h, pairing_eq_zero_iff.mp h⟩⟩
lemma isFixedPt_reflectionPerm_iff [NeZero (2 : R)] [NoZeroSMulDivisors R M] :
IsFixedPt (P.reflectionPerm i) j ↔ P.pairing i j = 0 := by
refine ⟨fun h ↦ ?_, P.reflectionPerm_eq_of_pairing_eq_zero'⟩
simpa [P.ne_zero i, pairing_eq_zero_iff, IsFixedPt, reflectionPerm_eq_iff_smul_root] using h
@[deprecated (since := "2025-05-28")]
alias isFixedPt_reflection_perm_iff := isFixedPt_reflectionPerm_iff
end RootPairing
|
TensorProduct.lean
|
/-
Copyright (c) 2025 Junyan Xu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Junyan Xu
-/
import Mathlib.Algebra.Colimit.Finiteness
import Mathlib.LinearAlgebra.TensorProduct.DirectLimit
/-!
# Tensor product with direct limit of finitely generated submodules
We show that if `M` and `P` are arbitrary modules and `N` is a finitely generated submodule
of a module `P`, then two elements of `N ⊗ M` have the same image in `P ⊗ M` if and only if
they already have the same image in `N' ⊗ M` for some finitely generated submodule `N' ≥ N`.
This is the theorem `Submodule.FG.exists_rTensor_fg_inclusion_eq`. The key facts used are
that every module is the direct limit of its finitely generated submodules and that tensor
product preserves colimits.
-/
open TensorProduct
variable {R M P : Type*} [CommSemiring R]
variable [AddCommMonoid M] [Module R M] [AddCommMonoid P] [Module R P]
theorem Submodule.FG.exists_rTensor_fg_inclusion_eq {N : Submodule R P} (hN : N.FG)
{x y : N ⊗[R] M} (eq : N.subtype.rTensor M x = N.subtype.rTensor M y) :
∃ N', N'.FG ∧ ∃ h : N ≤ N', (N.inclusion h).rTensor M x = (N.inclusion h).rTensor M y := by
classical
lift N to {N : Submodule R P // N.FG} using hN
apply_fun (Module.fgSystem.equiv R P).symm.toLinearMap.rTensor M at eq
apply_fun directLimitLeft _ _ at eq
simp_rw [← LinearMap.rTensor_comp_apply, ← (LinearEquiv.eq_toLinearMap_symm_comp _ _).mpr
(Module.fgSystem.equiv_comp_of N), directLimitLeft_rTensor_of] at eq
have ⟨N', le, eq⟩ := Module.DirectLimit.exists_eq_of_of_eq eq
exact ⟨_, N'.2, le, eq⟩
|
Basic.lean
|
/-
Copyright (c) 2019 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann, Kyle Miller, Mario Carneiro
-/
import Mathlib.Data.Finset.NatAntidiagonal
import Mathlib.Data.Nat.GCD.Basic
import Mathlib.Data.Nat.BinaryRec
import Mathlib.Logic.Function.Iterate
import Mathlib.Tactic.Ring
import Mathlib.Tactic.Zify
import Mathlib.Data.Nat.Choose.Basic
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
/-!
# Fibonacci Numbers
This file defines the fibonacci series, proves results about it and introduces
methods to compute it quickly.
-/
/-!
# The Fibonacci Sequence
## Summary
Definition of the Fibonacci sequence `F₀ = 0, F₁ = 1, Fₙ₊₂ = Fₙ + Fₙ₊₁`.
## Main Definitions
- `Nat.fib` returns the stream of Fibonacci numbers.
## Main Statements
- `Nat.fib_add_two`: shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.`.
- `Nat.fib_gcd`: `fib n` is a strong divisibility sequence.
- `Nat.fib_succ_eq_sum_choose`: `fib` is given by the sum of `Nat.choose` along an antidiagonal.
- `Nat.fib_succ_eq_succ_sum`: shows that `F₀ + F₁ + ⋯ + Fₙ = Fₙ₊₂ - 1`.
- `Nat.fib_two_mul` and `Nat.fib_two_mul_add_one` are the basis for an efficient algorithm to
compute `fib` (see `Nat.fastFib`).
## Implementation Notes
For efficiency purposes, the sequence is defined using `Stream.iterate`.
## Tags
fib, fibonacci
-/
namespace Nat
/-- Implementation of the fibonacci sequence satisfying
`fib 0 = 0, fib 1 = 1, fib (n + 2) = fib n + fib (n + 1)`.
*Note:* We use a stream iterator for better performance when compared to the naive recursive
implementation.
-/
@[pp_nodot]
def fib (n : ℕ) : ℕ :=
((fun p : ℕ × ℕ => (p.snd, p.fst + p.snd))^[n] (0, 1)).fst
@[simp]
theorem fib_zero : fib 0 = 0 :=
rfl
@[simp]
theorem fib_one : fib 1 = 1 :=
rfl
@[simp]
theorem fib_two : fib 2 = 1 :=
rfl
/-- Shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.` -/
theorem fib_add_two {n : ℕ} : fib (n + 2) = fib n + fib (n + 1) := by
simp [fib, Function.iterate_succ_apply']
lemma fib_add_one : ∀ {n}, n ≠ 0 → fib (n + 1) = fib (n - 1) + fib n
| _n + 1, _ => fib_add_two
theorem fib_le_fib_succ {n : ℕ} : fib n ≤ fib (n + 1) := by cases n <;> simp [fib_add_two]
@[mono]
theorem fib_mono : Monotone fib :=
monotone_nat_of_le_succ fun _ => fib_le_fib_succ
@[simp] lemma fib_eq_zero : ∀ {n}, fib n = 0 ↔ n = 0
| 0 => Iff.rfl
| 1 => Iff.rfl
| n + 2 => by simp [fib_add_two, fib_eq_zero]
@[simp] lemma fib_pos {n : ℕ} : 0 < fib n ↔ 0 < n := by simp [pos_iff_ne_zero]
theorem fib_add_two_sub_fib_add_one {n : ℕ} : fib (n + 2) - fib (n + 1) = fib n := by
rw [fib_add_two, add_tsub_cancel_right]
theorem fib_lt_fib_succ {n : ℕ} (hn : 2 ≤ n) : fib n < fib (n + 1) := by
rcases exists_add_of_le hn with ⟨n, rfl⟩
rw [← tsub_pos_iff_lt, add_comm 2, add_right_comm, fib_add_two, add_tsub_cancel_right, fib_pos]
exact succ_pos n
/-- `fib (n + 2)` is strictly monotone. -/
theorem fib_add_two_strictMono : StrictMono fun n => fib (n + 2) := by
refine strictMono_nat_of_lt_succ fun n => ?_
rw [add_right_comm]
exact fib_lt_fib_succ (self_le_add_left _ _)
lemma fib_strictMonoOn : StrictMonoOn fib (Set.Ici 2)
| _m + 2, _, _n + 2, _, hmn => fib_add_two_strictMono <| lt_of_add_lt_add_right hmn
lemma fib_lt_fib {m : ℕ} (hm : 2 ≤ m) : ∀ {n}, fib m < fib n ↔ m < n
| 0 => by simp
| 1 => by simp
| n + 2 => fib_strictMonoOn.lt_iff_lt hm <| by simp
theorem le_fib_self {n : ℕ} (five_le_n : 5 ≤ n) : n ≤ fib n := by
induction' five_le_n with n five_le_n IH
· -- 5 ≤ fib 5
rfl
· -- n + 1 ≤ fib (n + 1) for 5 ≤ n
rw [succ_le_iff]
calc
n ≤ fib n := IH
_ < fib (n + 1) := fib_lt_fib_succ (le_trans (by decide) five_le_n)
lemma le_fib_add_one : ∀ n, n ≤ fib n + 1
| 0 => zero_le_one
| 1 => one_le_two
| 2 => le_rfl
| 3 => le_rfl
| 4 => le_rfl
| _n + 5 => (le_fib_self le_add_self).trans <| le_succ _
/-- Subsequent Fibonacci numbers are coprime,
see https://proofwiki.org/wiki/Consecutive_Fibonacci_Numbers_are_Coprime -/
theorem fib_coprime_fib_succ (n : ℕ) : Nat.Coprime (fib n) (fib (n + 1)) := by
induction' n with n ih
· simp
· simp only [fib_add_two, coprime_add_self_right, Coprime, ih.symm]
/-- See https://proofwiki.org/wiki/Fibonacci_Number_in_terms_of_Smaller_Fibonacci_Numbers -/
theorem fib_add (m n : ℕ) : fib (m + n + 1) = fib m * fib n + fib (m + 1) * fib (n + 1) := by
induction' n with n ih generalizing m
· simp
· specialize ih (m + 1)
rw [add_assoc m 1 n, add_comm 1 n] at ih
simp only [fib_add_two, ih]
ring
theorem fib_two_mul (n : ℕ) : fib (2 * n) = fib n * (2 * fib (n + 1) - fib n) := by
cases n
· simp
· rw [two_mul, ← add_assoc, fib_add, fib_add_two, two_mul]
simp only [← add_assoc, add_tsub_cancel_right]
ring
theorem fib_two_mul_add_one (n : ℕ) : fib (2 * n + 1) = fib (n + 1) ^ 2 + fib n ^ 2 := by
rw [two_mul, fib_add]
ring
theorem fib_two_mul_add_two (n : ℕ) :
fib (2 * n + 2) = fib (n + 1) * (2 * fib n + fib (n + 1)) := by
rw [fib_add_two, fib_two_mul, fib_two_mul_add_one]
have : fib n ≤ 2 * fib (n + 1) :=
le_trans fib_le_fib_succ (mul_comm 2 _ ▸ Nat.le_mul_of_pos_right _ two_pos)
zify [this]
ring
/-- Computes `(Nat.fib n, Nat.fib (n + 1))` using the binary representation of `n`.
Supports `Nat.fastFib`. -/
def fastFibAux : ℕ → ℕ × ℕ :=
Nat.binaryRec (fib 0, fib 1) fun b _ p =>
if b then (p.2 ^ 2 + p.1 ^ 2, p.2 * (2 * p.1 + p.2))
else (p.1 * (2 * p.2 - p.1), p.2 ^ 2 + p.1 ^ 2)
/-- Computes `Nat.fib n` using the binary representation of `n`.
Proved to be equal to `Nat.fib` in `Nat.fast_fib_eq`. -/
def fastFib (n : ℕ) : ℕ :=
(fastFibAux n).1
theorem fast_fib_aux_bit_ff (n : ℕ) :
fastFibAux (bit false n) =
let p := fastFibAux n
(p.1 * (2 * p.2 - p.1), p.2 ^ 2 + p.1 ^ 2) := by
rw [fastFibAux, binaryRec_eq]
· rfl
· simp
theorem fast_fib_aux_bit_tt (n : ℕ) :
fastFibAux (bit true n) =
let p := fastFibAux n
(p.2 ^ 2 + p.1 ^ 2, p.2 * (2 * p.1 + p.2)) := by
rw [fastFibAux, binaryRec_eq]
· rfl
· simp
theorem fast_fib_aux_eq (n : ℕ) : fastFibAux n = (fib n, fib (n + 1)) := by
refine Nat.binaryRec ?_ ?_ n
· simp [fastFibAux]
· rintro (_ | _) n' ih <;>
simp only [fast_fib_aux_bit_ff, fast_fib_aux_bit_tt, congr_arg Prod.fst ih,
congr_arg Prod.snd ih, Prod.mk_inj] <;>
simp [bit, fib_two_mul, fib_two_mul_add_one, fib_two_mul_add_two]
theorem fast_fib_eq (n : ℕ) : fastFib n = fib n := by rw [fastFib, fast_fib_aux_eq]
theorem gcd_fib_add_self (m n : ℕ) : gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n) := by
rcases Nat.eq_zero_or_pos n with rfl | h
· simp
replace h := Nat.succ_pred_eq_of_pos h; rw [← h, succ_eq_add_one]
calc
gcd (fib m) (fib (n.pred + 1 + m)) =
gcd (fib m) (fib n.pred * fib m + fib (n.pred + 1) * fib (m + 1)) := by
rw [← fib_add n.pred _]
ring_nf
_ = gcd (fib m) (fib (n.pred + 1) * fib (m + 1)) := by
rw [add_comm, gcd_add_mul_right_right (fib m) _ (fib n.pred)]
_ = gcd (fib m) (fib (n.pred + 1)) :=
Coprime.gcd_mul_right_cancel_right (fib (n.pred + 1)) (Coprime.symm (fib_coprime_fib_succ m))
theorem gcd_fib_add_mul_self (m n : ℕ) : ∀ k, gcd (fib m) (fib (n + k * m)) = gcd (fib m) (fib n)
| 0 => by simp
| k + 1 => by
rw [← gcd_fib_add_mul_self m n k, add_mul, ← add_assoc, one_mul, gcd_fib_add_self _ _]
/-- `fib n` is a strong divisibility sequence,
see https://proofwiki.org/wiki/GCD_of_Fibonacci_Numbers -/
theorem fib_gcd (m n : ℕ) : fib (gcd m n) = gcd (fib m) (fib n) := by
induction m, n using Nat.gcd.induction with
| H0 => simp
| H1 m n _ h' =>
rw [← gcd_rec m n] at h'
conv_rhs => rw [← mod_add_div' n m]
rwa [gcd_fib_add_mul_self m (n % m) (n / m), gcd_comm (fib m) _]
theorem fib_dvd (m n : ℕ) (h : m ∣ n) : fib m ∣ fib n := by
rwa [← gcd_eq_left_iff_dvd, ← fib_gcd, gcd_eq_left_iff_dvd.mpr]
theorem fib_succ_eq_sum_choose :
∀ n : ℕ, fib (n + 1) = ∑ p ∈ Finset.antidiagonal n, choose p.1 p.2 :=
twoStepInduction rfl rfl fun n h1 h2 => by
rw [fib_add_two, h1, h2, Finset.Nat.antidiagonal_succ_succ', Finset.Nat.antidiagonal_succ']
simp [choose_succ_succ, Finset.sum_add_distrib, add_left_comm]
theorem fib_succ_eq_succ_sum (n : ℕ) : fib (n + 1) = (∑ k ∈ Finset.range n, fib k) + 1 := by
induction' n with n ih
· simp
· calc
fib (n + 2) = fib n + fib (n + 1) := fib_add_two
_ = (fib n + ∑ k ∈ Finset.range n, fib k) + 1 := by rw [ih, add_assoc]
_ = (∑ k ∈ Finset.range (n + 1), fib k) + 1 := by simp [Finset.range_add_one]
end Nat
|
Max.lean
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Yury Kudryashov, Yaël Dillies
-/
import Mathlib.Order.Synonym
/-!
# Minimal/maximal and bottom/top elements
This file defines predicates for elements to be minimal/maximal or bottom/top and typeclasses
saying that there are no such elements.
## Predicates
* `IsBot`: An element is *bottom* if all elements are greater than it.
* `IsTop`: An element is *top* if all elements are less than it.
* `IsMin`: An element is *minimal* if no element is strictly less than it.
* `IsMax`: An element is *maximal* if no element is strictly greater than it.
See also `isBot_iff_isMin` and `isTop_iff_isMax` for the equivalences in a (co)directed order.
## Typeclasses
* `NoBotOrder`: An order without bottom elements.
* `NoTopOrder`: An order without top elements.
* `NoMinOrder`: An order without minimal elements.
* `NoMaxOrder`: An order without maximal elements.
-/
open OrderDual
universe u v
variable {α β : Type*}
/-- Order without bottom elements. -/
class NoBotOrder (α : Type*) [LE α] : Prop where
/-- For each term `a`, there is some `b` which is either incomparable or strictly smaller. -/
exists_not_ge (a : α) : ∃ b, ¬a ≤ b
/-- Order without top elements. -/
class NoTopOrder (α : Type*) [LE α] : Prop where
/-- For each term `a`, there is some `b` which is either incomparable or strictly larger. -/
exists_not_le (a : α) : ∃ b, ¬b ≤ a
/-- Order without minimal elements. Sometimes called coinitial or dense. -/
class NoMinOrder (α : Type*) [LT α] : Prop where
/-- For each term `a`, there is some strictly smaller `b`. -/
exists_lt (a : α) : ∃ b, b < a
/-- Order without maximal elements. Sometimes called cofinal. -/
class NoMaxOrder (α : Type*) [LT α] : Prop where
/-- For each term `a`, there is some strictly greater `b`. -/
exists_gt (a : α) : ∃ b, a < b
export NoBotOrder (exists_not_ge)
export NoTopOrder (exists_not_le)
export NoMinOrder (exists_lt)
export NoMaxOrder (exists_gt)
instance nonempty_lt [LT α] [NoMinOrder α] (a : α) : Nonempty { x // x < a } :=
nonempty_subtype.2 (exists_lt a)
instance nonempty_gt [LT α] [NoMaxOrder α] (a : α) : Nonempty { x // a < x } :=
nonempty_subtype.2 (exists_gt a)
instance IsEmpty.toNoMaxOrder [LT α] [IsEmpty α] : NoMaxOrder α := ⟨isEmptyElim⟩
instance IsEmpty.toNoMinOrder [LT α] [IsEmpty α] : NoMinOrder α := ⟨isEmptyElim⟩
instance OrderDual.noBotOrder [LE α] [NoTopOrder α] : NoBotOrder αᵒᵈ :=
⟨fun a => exists_not_le (α := α) a⟩
instance OrderDual.noTopOrder [LE α] [NoBotOrder α] : NoTopOrder αᵒᵈ :=
⟨fun a => exists_not_ge (α := α) a⟩
instance OrderDual.noMinOrder [LT α] [NoMaxOrder α] : NoMinOrder αᵒᵈ :=
⟨fun a => exists_gt (α := α) a⟩
instance OrderDual.noMaxOrder [LT α] [NoMinOrder α] : NoMaxOrder αᵒᵈ :=
⟨fun a => exists_lt (α := α) a⟩
-- See note [lower instance priority]
instance (priority := 100) [Preorder α] [NoMinOrder α] : NoBotOrder α :=
⟨fun a => (exists_lt a).imp fun _ => not_le_of_gt⟩
-- See note [lower instance priority]
instance (priority := 100) [Preorder α] [NoMaxOrder α] : NoTopOrder α :=
⟨fun a => (exists_gt a).imp fun _ => not_le_of_gt⟩
instance noMaxOrder_of_left [Preorder α] [Preorder β] [NoMaxOrder α] : NoMaxOrder (α × β) :=
⟨fun ⟨a, b⟩ => by
obtain ⟨c, h⟩ := exists_gt a
exact ⟨(c, b), Prod.mk_lt_mk_iff_left.2 h⟩⟩
instance noMaxOrder_of_right [Preorder α] [Preorder β] [NoMaxOrder β] : NoMaxOrder (α × β) :=
⟨fun ⟨a, b⟩ => by
obtain ⟨c, h⟩ := exists_gt b
exact ⟨(a, c), Prod.mk_lt_mk_iff_right.2 h⟩⟩
instance noMinOrder_of_left [Preorder α] [Preorder β] [NoMinOrder α] : NoMinOrder (α × β) :=
⟨fun ⟨a, b⟩ => by
obtain ⟨c, h⟩ := exists_lt a
exact ⟨(c, b), Prod.mk_lt_mk_iff_left.2 h⟩⟩
instance noMinOrder_of_right [Preorder α] [Preorder β] [NoMinOrder β] : NoMinOrder (α × β) :=
⟨fun ⟨a, b⟩ => by
obtain ⟨c, h⟩ := exists_lt b
exact ⟨(a, c), Prod.mk_lt_mk_iff_right.2 h⟩⟩
instance {ι : Type u} {π : ι → Type*} [Nonempty ι] [∀ i, Preorder (π i)] [∀ i, NoMaxOrder (π i)] :
NoMaxOrder (∀ i, π i) :=
⟨fun a => by
classical
obtain ⟨b, hb⟩ := exists_gt (a <| Classical.arbitrary _)
exact ⟨_, lt_update_self_iff.2 hb⟩⟩
instance {ι : Type u} {π : ι → Type*} [Nonempty ι] [∀ i, Preorder (π i)] [∀ i, NoMinOrder (π i)] :
NoMinOrder (∀ i, π i) :=
⟨fun a => by
classical
obtain ⟨b, hb⟩ := exists_lt (a <| Classical.arbitrary _)
exact ⟨_, update_lt_self_iff.2 hb⟩⟩
theorem NoBotOrder.to_noMinOrder (α : Type*) [LinearOrder α] [NoBotOrder α] : NoMinOrder α :=
{ exists_lt := fun a => by simpa [not_le] using exists_not_ge a }
theorem NoTopOrder.to_noMaxOrder (α : Type*) [LinearOrder α] [NoTopOrder α] : NoMaxOrder α :=
{ exists_gt := fun a => by simpa [not_le] using exists_not_le a }
theorem noBotOrder_iff_noMinOrder (α : Type*) [LinearOrder α] : NoBotOrder α ↔ NoMinOrder α :=
⟨fun _ => NoBotOrder.to_noMinOrder α, fun _ => inferInstance⟩
theorem noTopOrder_iff_noMaxOrder (α : Type*) [LinearOrder α] : NoTopOrder α ↔ NoMaxOrder α :=
⟨fun _ => NoTopOrder.to_noMaxOrder α, fun _ => inferInstance⟩
theorem NoMinOrder.not_acc [LT α] [NoMinOrder α] (a : α) : ¬Acc (· < ·) a := fun h =>
Acc.recOn h fun x _ => (exists_lt x).recOn
theorem NoMaxOrder.not_acc [LT α] [NoMaxOrder α] (a : α) : ¬Acc (· > ·) a := fun h =>
Acc.recOn h fun x _ => (exists_gt x).recOn
section LE
variable [LE α] {a : α}
/-- `a : α` is a bottom element of `α` if it is less than or equal to any other element of `α`.
This predicate is roughly an unbundled version of `OrderBot`, except that a preorder may have
several bottom elements. When `α` is linear, this is useful to make a case disjunction on
`NoMinOrder α` within a proof. -/
def IsBot (a : α) : Prop :=
∀ b, a ≤ b
/-- `a : α` is a top element of `α` if it is greater than or equal to any other element of `α`.
This predicate is roughly an unbundled version of `OrderBot`, except that a preorder may have
several top elements. When `α` is linear, this is useful to make a case disjunction on
`NoMaxOrder α` within a proof. -/
def IsTop (a : α) : Prop :=
∀ b, b ≤ a
/-- `a` is a minimal element of `α` if no element is strictly less than it. We spell it without `<`
to avoid having to convert between `≤` and `<`. Instead, `isMin_iff_forall_not_lt` does the
conversion. -/
def IsMin (a : α) : Prop :=
∀ ⦃b⦄, b ≤ a → a ≤ b
/-- `a` is a maximal element of `α` if no element is strictly greater than it. We spell it without
`<` to avoid having to convert between `≤` and `<`. Instead, `isMax_iff_forall_not_lt` does the
conversion. -/
def IsMax (a : α) : Prop :=
∀ ⦃b⦄, a ≤ b → b ≤ a
@[simp]
theorem not_isBot [NoBotOrder α] (a : α) : ¬IsBot a := fun h =>
let ⟨_, hb⟩ := exists_not_ge a
hb <| h _
@[simp]
theorem not_isTop [NoTopOrder α] (a : α) : ¬IsTop a := fun h =>
let ⟨_, hb⟩ := exists_not_le a
hb <| h _
protected theorem IsBot.isMin (h : IsBot a) : IsMin a := fun b _ => h b
protected theorem IsTop.isMax (h : IsTop a) : IsMax a := fun b _ => h b
theorem IsTop.isMax_iff {α} [PartialOrder α] {i j : α} (h : IsTop i) : IsMax j ↔ j = i := by
simp_rw [le_antisymm_iff, h j, true_and]
exact ⟨(· (h j)), Function.swap (fun _ ↦ h · |>.trans ·)⟩
theorem IsBot.isMin_iff {α} [PartialOrder α] {i j : α} (h : IsBot i) : IsMin j ↔ j = i := by
simp_rw [le_antisymm_iff, h j, and_true]
exact ⟨fun a ↦ a (h j), fun a h' ↦ fun _ ↦ Preorder.le_trans j i h' a (h h')⟩
@[simp]
theorem isBot_toDual_iff : IsBot (toDual a) ↔ IsTop a :=
Iff.rfl
@[simp]
theorem isTop_toDual_iff : IsTop (toDual a) ↔ IsBot a :=
Iff.rfl
@[simp]
theorem isMin_toDual_iff : IsMin (toDual a) ↔ IsMax a :=
Iff.rfl
@[simp]
theorem isMax_toDual_iff : IsMax (toDual a) ↔ IsMin a :=
Iff.rfl
@[simp]
theorem isBot_ofDual_iff {a : αᵒᵈ} : IsBot (ofDual a) ↔ IsTop a :=
Iff.rfl
@[simp]
theorem isTop_ofDual_iff {a : αᵒᵈ} : IsTop (ofDual a) ↔ IsBot a :=
Iff.rfl
@[simp]
theorem isMin_ofDual_iff {a : αᵒᵈ} : IsMin (ofDual a) ↔ IsMax a :=
Iff.rfl
@[simp]
theorem isMax_ofDual_iff {a : αᵒᵈ} : IsMax (ofDual a) ↔ IsMin a :=
Iff.rfl
alias ⟨_, IsTop.toDual⟩ := isBot_toDual_iff
alias ⟨_, IsBot.toDual⟩ := isTop_toDual_iff
alias ⟨_, IsMax.toDual⟩ := isMin_toDual_iff
alias ⟨_, IsMin.toDual⟩ := isMax_toDual_iff
alias ⟨_, IsTop.ofDual⟩ := isBot_ofDual_iff
alias ⟨_, IsBot.ofDual⟩ := isTop_ofDual_iff
alias ⟨_, IsMax.ofDual⟩ := isMin_ofDual_iff
alias ⟨_, IsMin.ofDual⟩ := isMax_ofDual_iff
end LE
section Preorder
variable [Preorder α] {a b : α}
theorem IsBot.mono (ha : IsBot a) (h : b ≤ a) : IsBot b := fun _ => h.trans <| ha _
theorem IsTop.mono (ha : IsTop a) (h : a ≤ b) : IsTop b := fun _ => (ha _).trans h
theorem IsMin.mono (ha : IsMin a) (h : b ≤ a) : IsMin b := fun _ hc => h.trans <| ha <| hc.trans h
theorem IsMax.mono (ha : IsMax a) (h : a ≤ b) : IsMax b := fun _ hc => (ha <| h.trans hc).trans h
theorem IsMin.not_lt (h : IsMin a) : ¬b < a := fun hb => hb.not_ge <| h hb.le
theorem IsMax.not_lt (h : IsMax a) : ¬a < b := fun hb => hb.not_ge <| h hb.le
theorem not_isMin_of_lt (h : b < a) : ¬IsMin a := fun ha => ha.not_lt h
theorem not_isMax_of_lt (h : a < b) : ¬IsMax a := fun ha => ha.not_lt h
alias LT.lt.not_isMin := not_isMin_of_lt
alias LT.lt.not_isMax := not_isMax_of_lt
theorem isMin_iff_forall_not_lt : IsMin a ↔ ∀ b, ¬b < a :=
⟨fun h _ => h.not_lt, fun h _ hba => of_not_not fun hab => h _ <| hba.lt_of_not_ge hab⟩
theorem isMax_iff_forall_not_lt : IsMax a ↔ ∀ b, ¬a < b :=
⟨fun h _ => h.not_lt, fun h _ hba => of_not_not fun hab => h _ <| hba.lt_of_not_ge hab⟩
@[simp]
theorem not_isMin_iff : ¬IsMin a ↔ ∃ b, b < a := by
simp [lt_iff_le_not_ge, IsMin, not_forall]
@[simp]
theorem not_isMax_iff : ¬IsMax a ↔ ∃ b, a < b := by
simp [lt_iff_le_not_ge, IsMax, not_forall]
@[simp]
theorem not_isMin [NoMinOrder α] (a : α) : ¬IsMin a :=
not_isMin_iff.2 <| exists_lt a
@[simp]
theorem not_isMax [NoMaxOrder α] (a : α) : ¬IsMax a :=
not_isMax_iff.2 <| exists_gt a
namespace Subsingleton
variable [Subsingleton α]
protected theorem isBot (a : α) : IsBot a := fun _ => (Subsingleton.elim _ _).le
protected theorem isTop (a : α) : IsTop a := fun _ => (Subsingleton.elim _ _).le
protected theorem isMin (a : α) : IsMin a :=
(Subsingleton.isBot _).isMin
protected theorem isMax (a : α) : IsMax a :=
(Subsingleton.isTop _).isMax
end Subsingleton
end Preorder
section PartialOrder
variable [PartialOrder α] {a b : α}
protected theorem IsMin.eq_of_le (ha : IsMin a) (h : b ≤ a) : b = a :=
h.antisymm <| ha h
protected theorem IsMin.eq_of_ge (ha : IsMin a) (h : b ≤ a) : a = b :=
h.antisymm' <| ha h
protected theorem IsMax.eq_of_le (ha : IsMax a) (h : a ≤ b) : a = b :=
h.antisymm <| ha h
protected theorem IsMax.eq_of_ge (ha : IsMax a) (h : a ≤ b) : b = a :=
h.antisymm' <| ha h
protected theorem IsBot.lt_of_ne (ha : IsBot a) (h : a ≠ b) : a < b :=
(ha b).lt_of_ne h
protected theorem IsTop.lt_of_ne (ha : IsTop a) (h : b ≠ a) : b < a :=
(ha b).lt_of_ne h
protected theorem IsBot.not_isMax [Nontrivial α] (ha : IsBot a) : ¬ IsMax a := by
intro ha'
obtain ⟨b, hb⟩ := exists_ne a
exact hb <| ha'.eq_of_ge (ha.lt_of_ne hb.symm).le
protected theorem IsTop.not_isMin [Nontrivial α] (ha : IsTop a) : ¬ IsMin a :=
ha.toDual.not_isMax
protected theorem IsBot.not_isTop [Nontrivial α] (ha : IsBot a) : ¬ IsTop a :=
mt IsTop.isMax ha.not_isMax
protected theorem IsTop.not_isBot [Nontrivial α] (ha : IsTop a) : ¬ IsBot a :=
ha.toDual.not_isTop
end PartialOrder
section Prod
variable [Preorder α] [Preorder β] {a : α} {b : β} {x : α × β}
theorem IsBot.prodMk (ha : IsBot a) (hb : IsBot b) : IsBot (a, b) := fun _ => ⟨ha _, hb _⟩
@[deprecated (since := "2025-02-22")]
alias IsBot.prod_mk := IsBot.prodMk
theorem IsTop.prodMk (ha : IsTop a) (hb : IsTop b) : IsTop (a, b) := fun _ => ⟨ha _, hb _⟩
@[deprecated (since := "2025-02-22")]
alias IsTop.prod_mk := IsTop.prodMk
theorem IsMin.prodMk (ha : IsMin a) (hb : IsMin b) : IsMin (a, b) := fun _ hc => ⟨ha hc.1, hb hc.2⟩
@[deprecated (since := "2025-02-22")]
alias IsMin.prod_mk := IsMin.prodMk
theorem IsMax.prodMk (ha : IsMax a) (hb : IsMax b) : IsMax (a, b) := fun _ hc => ⟨ha hc.1, hb hc.2⟩
@[deprecated (since := "2025-02-22")]
alias IsMax.prod_mk := IsMax.prodMk
theorem IsBot.fst (hx : IsBot x) : IsBot x.1 := fun c => (hx (c, x.2)).1
theorem IsBot.snd (hx : IsBot x) : IsBot x.2 := fun c => (hx (x.1, c)).2
theorem IsTop.fst (hx : IsTop x) : IsTop x.1 := fun c => (hx (c, x.2)).1
theorem IsTop.snd (hx : IsTop x) : IsTop x.2 := fun c => (hx (x.1, c)).2
theorem IsMin.fst (hx : IsMin x) : IsMin x.1 :=
fun c hc => (hx <| show (c, x.2) ≤ x from (and_iff_left le_rfl).2 hc).1
theorem IsMin.snd (hx : IsMin x) : IsMin x.2 :=
fun c hc => (hx <| show (x.1, c) ≤ x from (and_iff_right le_rfl).2 hc).2
theorem IsMax.fst (hx : IsMax x) : IsMax x.1 :=
fun c hc => (hx <| show x ≤ (c, x.2) from (and_iff_left le_rfl).2 hc).1
theorem IsMax.snd (hx : IsMax x) : IsMax x.2 :=
fun c hc => (hx <| show x ≤ (x.1, c) from (and_iff_right le_rfl).2 hc).2
theorem Prod.isBot_iff : IsBot x ↔ IsBot x.1 ∧ IsBot x.2 :=
⟨fun hx => ⟨hx.fst, hx.snd⟩, fun h => h.1.prodMk h.2⟩
theorem Prod.isTop_iff : IsTop x ↔ IsTop x.1 ∧ IsTop x.2 :=
⟨fun hx => ⟨hx.fst, hx.snd⟩, fun h => h.1.prodMk h.2⟩
theorem Prod.isMin_iff : IsMin x ↔ IsMin x.1 ∧ IsMin x.2 :=
⟨fun hx => ⟨hx.fst, hx.snd⟩, fun h => h.1.prodMk h.2⟩
theorem Prod.isMax_iff : IsMax x ↔ IsMax x.1 ∧ IsMax x.2 :=
⟨fun hx => ⟨hx.fst, hx.snd⟩, fun h => h.1.prodMk h.2⟩
end Prod
|
ParametrizedAdjunction.lean
|
/-
Copyright (c) 2025 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.CategoryTheory.LiftingProperties.Basic
import Mathlib.CategoryTheory.Limits.Shapes.Pullback.CommSq
import Mathlib.CategoryTheory.Adjunction.Parametrized
/-!
# Lifting properties and parametrized adjunctions
Let `F : C₁ ⥤ C₂ ⥤ C₃`. Given morphisms `f₁ : X₁ ⟶ Y₁` in `C₁`
and `f₂ : X₂ ⟶ Y₂` in `C₂`, we introduce a structure
`F.PushoutObjObj f₁ f₂` which contains the data of a
pushout of `(F.obj Y₁).obj X₂` and `(F.obj X₁).obj Y₂`
along `(F.obj X₁).obj X₂`. If `sq₁₂ : F.PushoutObjObj f₁ f₂`,
we have a canonical "inclusion" `sq₁₂.ι : sq₁₂.pt ⟶ (F.obj Y₁).obj Y₂`.
Similarly, if we have a bifunctor `G : C₁ᵒᵖ ⥤ C₃ ⥤ C₂`, and
morphisms `f₁ : X₁ ⟶ Y₁` in `C₁` and `f₃ : X₃ ⟶ Y₃` in `C₃`,
we introduce a structure `F.PullbackObjObj f₁ f₃` which
contains the data of a pullback of `(G.obj (op X₁)).obj X₃`
and `(G.obj (op Y₁)).obj Y₃` over `(G.obj (op X₁)).obj Y₃`.
If `sq₁₃ : F.PullbackObjObj f₁ f₃`, we have a canonical
projection `sq₁₃.π : (G.obj Y₁).obj X₃ ⟶ sq₁₃.pt`.
Now, if we have a parametrized adjunction `adj₂ : F ⊣₂ G`,
`sq₁₂ : F.PushoutObjObj f₁ f₂` and `sq₁₃ : G.PullbackObjObj f₁ f₃`,
we show that `sq₁₂.ι` has the left lifting property with respect to
`f₃` if and only if `f₂` has the left lifting property with respect
to `sq₁₃.π`: this is the lemma `ParametrizedAdjunction.hasLiftingProperty_iff`.
-/
universe v₁ v₂ v₃ u₁ u₂ u₃
namespace CategoryTheory
open Opposite Limits
variable {C₁ : Type u₁} {C₂ : Type u₂} {C₃ : Type u₃}
[Category.{v₁} C₁] [Category.{v₂} C₂] [Category.{v₃} C₃]
(F : C₁ ⥤ C₂ ⥤ C₃) (G : C₁ᵒᵖ ⥤ C₃ ⥤ C₂)
namespace Functor
section
variable {X₁ Y₁ : C₁} (f₁ : X₁ ⟶ Y₁) {X₂ Y₂ : C₂} (f₂ : X₂ ⟶ Y₂)
/-- Given a bifunctor `F : C₁ ⥤ C₂ ⥤ C₃`, and morphisms `f₁ : X₁ ⟶ Y₁` in `C₁`
and `f₂ : X₂ ⟶ Y₂` in `C₂`, this structure contains the data of
a pushout of `(F.obj Y₁).obj X₂` and `(F.obj X₁).obj Y₂`
along `(F.obj X₁).obj X₂`. -/
structure PushoutObjObj where
/-- the pushout -/
pt : C₃
/-- the first inclusion -/
inl : (F.obj Y₁).obj X₂ ⟶ pt
/-- the second inclusion -/
inr : (F.obj X₁).obj Y₂ ⟶ pt
isPushout : IsPushout ((F.map f₁).app X₂) ((F.obj X₁).map f₂) inl inr
namespace PushoutObjObj
/-- The `PushoutObjObj` structure given by the pushout of the colimits API. -/
@[simps]
noncomputable def ofHasPushout
[HasPushout ((F.map f₁).app X₂) ((F.obj X₁).map f₂)] :
F.PushoutObjObj f₁ f₂ :=
{ isPushout := IsPushout.of_hasPushout _ _, .. }
variable {F f₁ f₂} (sq : F.PushoutObjObj f₁ f₂)
/-- The "inclusion" `sq.pt ⟶ (F.obj Y₁).obj Y₂` when
`sq : F.PushoutObjObj f₁ f₂`. -/
noncomputable def ι : sq.pt ⟶ (F.obj Y₁).obj Y₂ :=
sq.isPushout.desc ((F.obj Y₁).map f₂) ((F.map f₁).app Y₂) (by simp)
@[reassoc (attr := simp)]
lemma inl_ι : sq.inl ≫ sq.ι = (F.obj Y₁).map f₂ := by simp [ι]
@[reassoc (attr := simp)]
lemma inr_ι : sq.inr ≫ sq.ι = (F.map f₁).app Y₂ := by simp [ι]
/-- Given `sq : F.PushoutObjObj f₁ f₂`, flipping the pushout square gives
`sq.flip : F.flip.PushoutObjObj f₂ f₁`. -/
@[simps]
def flip : F.flip.PushoutObjObj f₂ f₁ where
pt := sq.pt
inl := sq.inr
inr := sq.inl
isPushout := sq.isPushout.flip
@[simp]
lemma ι_flip : sq.flip.ι = sq.ι := by
apply sq.flip.isPushout.hom_ext
· rw [inl_ι, flip_inl, inr_ι, flip_obj_map]
· rw [inr_ι, flip_inr, inl_ι, flip_map_app]
end PushoutObjObj
end
section
variable {X₁ Y₁ : C₁} (f₁ : X₁ ⟶ Y₁) {X₃ Y₃ : C₃} (f₃ : X₃ ⟶ Y₃)
/-- Given a bifunctor `G : C₁ᵒᵖ ⥤ C₃ ⥤ C₂`, and morphisms `f₁ : X₁ ⟶ Y₁` in `C₁`
and `f₃ : X₃ ⟶ Y₃` in `C₃`, this structure contains the data of
a pullback of `(G.obj (op X₁)).obj X₃`
and `(G.obj (op Y₁)).obj Y₃` over `(G.obj (op X₁)).obj Y₃`. -/
structure PullbackObjObj where
/-- the pullback -/
pt : C₂
/-- the first projection -/
fst : pt ⟶ (G.obj (op X₁)).obj X₃
/-- the second projection -/
snd : pt ⟶ (G.obj (op Y₁)).obj Y₃
isPullback : IsPullback fst snd ((G.obj (op X₁)).map f₃)
((G.map f₁.op).app Y₃)
namespace PullbackObjObj
/-- The `PullbackObjObj` structure given by the pullback of the limits API. -/
@[simps]
noncomputable def ofHasPullback
[HasPullback ((G.obj (op X₁)).map f₃) ((G.map f₁.op).app Y₃)] :
G.PullbackObjObj f₁ f₃ :=
{ isPullback := IsPullback.of_hasPullback _ _, ..}
variable {G f₁ f₃} (sq : G.PullbackObjObj f₁ f₃)
/-- The projection `(G.obj (op Y₁)).obj X₃ ⟶ sq.pt` when
`sq : G.PullbackObjObj f₁ f₃`. -/
noncomputable def π : (G.obj (op Y₁)).obj X₃ ⟶ sq.pt :=
sq.isPullback.lift ((G.map f₁.op).app X₃) ((G.obj (op Y₁)).map f₃) (by simp)
@[reassoc (attr := simp)]
lemma π_fst : sq.π ≫ sq.fst = (G.map f₁.op).app X₃ := by simp [π]
@[reassoc (attr := simp)]
lemma π_snd : sq.π ≫ sq.snd = (G.obj (op Y₁)).map f₃ := by simp [π]
end PullbackObjObj
end
end Functor
namespace ParametrizedAdjunction
variable {F G} (adj₂ : F ⊣₂ G)
{X₁ Y₁ : C₁} {f₁ : X₁ ⟶ Y₁} {X₂ Y₂ : C₂} {f₂ : X₂ ⟶ Y₂}
{X₃ Y₃ : C₃} {f₃ : X₃ ⟶ Y₃}
(sq₁₂ : F.PushoutObjObj f₁ f₂) (sq₁₃ : G.PullbackObjObj f₁ f₃)
/-- Given a parametrized adjunction `F ⊣₂ G` between bifunctors, and structures
`sq₁₂ : F.PushoutObjObj f₁ f₂` and `sq₁₃ : G.PullbackObjObj f₁ f₃`, there are
as many commutative squares with left map `sq₁₂.ι` and right map `f₃`
as commutative squares with left map `f₂` and right map `sq₁₃.π`. -/
@[simps! apply_left symm_apply_right]
noncomputable def arrowHomEquiv :
(Arrow.mk sq₁₂.ι ⟶ Arrow.mk f₃) ≃
(Arrow.mk f₂ ⟶ Arrow.mk sq₁₃.π) where
toFun α :=
Arrow.homMk (adj₂.homEquiv (sq₁₂.inl ≫ α.left))
(sq₁₃.isPullback.lift
(adj₂.homEquiv (sq₁₂.inr ≫ α.left)) (adj₂.homEquiv α.right)
(by simp [← adj₂.homEquiv_naturality_one,
← adj₂.homEquiv_naturality_three])) (by
apply sq₁₃.isPullback.hom_ext
· simp [← adj₂.homEquiv_naturality_two,
← adj₂.homEquiv_naturality_one,
sq₁₂.isPushout.w_assoc]
· simp [← adj₂.homEquiv_naturality_two,
← adj₂.homEquiv_naturality_three])
invFun β :=
Arrow.homMk
(sq₁₂.isPushout.desc
(adj₂.homEquiv.symm β.left)
(adj₂.homEquiv.symm (β.right ≫ sq₁₃.fst)) (by
have := Arrow.w β =≫ sq₁₃.fst
dsimp at this
simp only [Category.assoc, sq₁₃.π_fst] at this
simp only [← adj₂.homEquiv_symm_naturality_one,
← adj₂.homEquiv_symm_naturality_two,
Arrow.mk_left, Arrow.mk_right, this]))
(adj₂.homEquiv.symm (β.right ≫ sq₁₃.snd)) (by
apply sq₁₂.isPushout.hom_ext
· have := Arrow.w β =≫ sq₁₃.snd
dsimp at this
simp only [Category.assoc, sq₁₃.π_snd] at this
simp [← adj₂.homEquiv_symm_naturality_two,
← adj₂.homEquiv_symm_naturality_three, this]
· simp [← adj₂.homEquiv_symm_naturality_one,
← adj₂.homEquiv_symm_naturality_three, sq₁₃.isPullback.w])
left_inv α := by
ext
· apply sq₁₂.isPushout.hom_ext <;> simp
· simp
right_inv β := by
ext
· simp
· apply sq₁₃.isPullback.hom_ext <;> simp
@[reassoc (attr := simp)]
lemma arrowHomEquiv_apply_right_fst (α : Arrow.mk sq₁₂.ι ⟶ Arrow.mk f₃) :
((adj₂.arrowHomEquiv sq₁₂ sq₁₃) α).right ≫ sq₁₃.fst = adj₂.homEquiv (sq₁₂.inr ≫ α.left) :=
IsPullback.lift_fst _ _ _ _
@[reassoc (attr := simp)]
lemma arrowHomEquiv_apply_right_snd (α : Arrow.mk sq₁₂.ι ⟶ Arrow.mk f₃) :
((adj₂.arrowHomEquiv sq₁₂ sq₁₃) α).right ≫ sq₁₃.snd = adj₂.homEquiv α.right :=
IsPullback.lift_snd _ _ _ _
@[reassoc (attr := simp)]
lemma inl_arrowHomEquiv_symm_apply_left (β : Arrow.mk f₂ ⟶ Arrow.mk sq₁₃.π) :
sq₁₂.inl ≫ ((adj₂.arrowHomEquiv sq₁₂ sq₁₃).symm β).left = adj₂.homEquiv.symm β.left :=
IsPushout.inl_desc _ _ _ _
@[reassoc (attr := simp)]
lemma inr_arrowHomEquiv_symm_apply_left (β : Arrow.mk f₂ ⟶ Arrow.mk sq₁₃.π) :
sq₁₂.inr ≫ ((adj₂.arrowHomEquiv sq₁₂ sq₁₃).symm β).left =
adj₂.homEquiv.symm (β.right ≫ sq₁₃.fst) :=
IsPushout.inr_desc _ _ _ _
/-- Given a parametrized adjunction `F ⊣₂ G` between bifunctors, structures
`sq₁₂ : F.PushoutObjObj f₁ f₂` and `sq₁₃ : G.PullbackObjObj f₁ f₃`,
there are as many liftings for the commutative square given by a
map `α : Arrow.mk sq₁₂.ι ⟶ Arrow.mk f₃` as there are liftings
for the square given by the corresponding map `Arrow.mk f₂ ⟶ Arrow.mk sq₁₃.π`. -/
noncomputable def liftStructEquiv (α : Arrow.mk sq₁₂.ι ⟶ Arrow.mk f₃) :
Arrow.LiftStruct α ≃ Arrow.LiftStruct (adj₂.arrowHomEquiv sq₁₂ sq₁₃ α) where
toFun l :=
{ l := adj₂.homEquiv l.l
fac_left := by
have := l.fac_left
dsimp at this ⊢
simp only [← adj₂.homEquiv_naturality_two, ← this,
sq₁₂.inl_ι_assoc]
fac_right := by
apply sq₁₃.isPullback.hom_ext
· have := l.fac_left
dsimp at this ⊢
simp only [Category.assoc, sq₁₃.π_fst, ← adj₂.homEquiv_naturality_one,
arrowHomEquiv_apply_right_fst, Arrow.mk_left, ← this, sq₁₂.inr_ι_assoc]
· have := l.fac_right
dsimp at this ⊢
simp only [Category.assoc, sq₁₃.π_snd, ← this, adj₂.homEquiv_naturality_three,
arrowHomEquiv_apply_right_snd, Arrow.mk_right] }
invFun l :=
{ l := adj₂.homEquiv.symm l.l
fac_left := by
apply sq₁₂.isPushout.hom_ext
· have := l.fac_left
dsimp at this ⊢
simp only [sq₁₂.inl_ι_assoc, ← adj₂.homEquiv_symm_naturality_two,
this, Equiv.symm_apply_apply]
· have := l.fac_right =≫ sq₁₃.fst
dsimp at this ⊢
simp only [Category.assoc, sq₁₃.π_fst] at this
simp only [sq₁₂.inr_ι_assoc, ← adj₂.homEquiv_symm_naturality_one,
this, Equiv.symm_apply_apply, arrowHomEquiv_apply_right_fst, Arrow.mk_left]
fac_right := by
have := l.fac_right =≫ sq₁₃.snd
dsimp at this ⊢
simp only [Category.assoc, sq₁₃.π_snd, arrowHomEquiv_apply_right_snd,
Arrow.mk_right] at this
rw [← adj₂.homEquiv_symm_naturality_three, this,
Equiv.symm_apply_apply] }
left_inv _ := by aesop
right_inv _ := by aesop
include adj₂ in
lemma hasLiftingProperty_iff :
HasLiftingProperty sq₁₂.ι f₃ ↔ HasLiftingProperty f₂ sq₁₃.π := by
simp only [Arrow.hasLiftingProperty_iff]
constructor
· intro h β
obtain ⟨α, rfl⟩ := (adj₂.arrowHomEquiv sq₁₂ sq₁₃).surjective β
exact ⟨adj₂.liftStructEquiv sq₁₂ sq₁₃ α (h α).some⟩
· intro h α
exact ⟨(adj₂.liftStructEquiv sq₁₂ sq₁₃ α).symm (h _).some⟩
end ParametrizedAdjunction
end CategoryTheory
|
Basic.lean
|
/-
Copyright (c) 2020 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison
-/
import Mathlib.LinearAlgebra.Matrix.Adjugate
import Mathlib.LinearAlgebra.Matrix.Block
import Mathlib.RingTheory.MatrixPolynomialAlgebra
/-!
# Characteristic polynomials and the Cayley-Hamilton theorem
We define characteristic polynomials of matrices and
prove the Cayley–Hamilton theorem over arbitrary commutative rings.
See the file `Mathlib/LinearAlgebra/Matrix/Charpoly/Coeff.lean` for corollaries of this theorem.
## Main definitions
* `Matrix.charpoly` is the characteristic polynomial of a matrix.
## Implementation details
We follow a nice proof from http://drorbn.net/AcademicPensieve/2015-12/CayleyHamilton.pdf
-/
noncomputable section
universe u v w
namespace Matrix
open Finset Matrix Polynomial
variable {R S : Type*} [CommRing R] [CommRing S]
variable {m n : Type*} [DecidableEq m] [DecidableEq n] [Fintype m] [Fintype n]
variable (M₁₁ : Matrix m m R) (M₁₂ : Matrix m n R) (M₂₁ : Matrix n m R) (M₂₂ M : Matrix n n R)
variable (i j : n)
/-- The "characteristic matrix" of `M : Matrix n n R` is the matrix of polynomials $t I - M$.
The determinant of this matrix is the characteristic polynomial.
-/
def charmatrix (M : Matrix n n R) : Matrix n n R[X] :=
Matrix.scalar n (X : R[X]) - (C : R →+* R[X]).mapMatrix M
theorem charmatrix_apply :
charmatrix M i j = (Matrix.diagonal fun _ : n => X) i j - C (M i j) :=
rfl
@[simp]
theorem charmatrix_apply_eq : charmatrix M i i = (X : R[X]) - C (M i i) := by
simp only [charmatrix, RingHom.mapMatrix_apply, sub_apply, scalar_apply, map_apply,
diagonal_apply_eq]
@[simp]
theorem charmatrix_apply_ne (h : i ≠ j) : charmatrix M i j = -C (M i j) := by
simp only [charmatrix, RingHom.mapMatrix_apply, sub_apply, scalar_apply, diagonal_apply_ne _ h,
map_apply, sub_eq_neg_self]
@[simp]
theorem charmatrix_zero : charmatrix (0 : Matrix n n R) = Matrix.scalar n (X : R[X]) := by
simp [charmatrix]
@[simp]
theorem charmatrix_diagonal (d : n → R) :
charmatrix (diagonal d) = diagonal fun i => X - C (d i) := by
rw [charmatrix, scalar_apply, RingHom.mapMatrix_apply, diagonal_map (map_zero _), diagonal_sub]
@[simp]
theorem charmatrix_one : charmatrix (1 : Matrix n n R) = diagonal fun _ => X - 1 :=
charmatrix_diagonal _
@[simp]
theorem charmatrix_natCast (k : ℕ) :
charmatrix (k : Matrix n n R) = diagonal fun _ => X - (k : R[X]) :=
charmatrix_diagonal _
@[simp]
theorem charmatrix_ofNat (k : ℕ) [k.AtLeastTwo] :
charmatrix (ofNat(k) : Matrix n n R) = diagonal fun _ => X - ofNat(k) :=
charmatrix_natCast _
@[simp]
theorem charmatrix_transpose (M : Matrix n n R) : (Mᵀ).charmatrix = M.charmatrixᵀ := by
simp [charmatrix, transpose_map]
theorem matPolyEquiv_charmatrix : matPolyEquiv (charmatrix M) = X - C M := by
ext k i j
simp only [matPolyEquiv_coeff_apply, coeff_sub]
by_cases h : i = j
· subst h
rw [charmatrix_apply_eq, coeff_sub]
simp only [coeff_X, coeff_C]
split_ifs <;> simp
· rw [charmatrix_apply_ne _ _ _ h, coeff_X, coeff_neg, coeff_C, coeff_C]
split_ifs <;> simp [h]
theorem charmatrix_reindex (e : n ≃ m) :
charmatrix (reindex e e M) = reindex e e (charmatrix M) := by
ext i j x
by_cases h : i = j
all_goals simp [h]
lemma charmatrix_map (M : Matrix n n R) (f : R →+* S) :
charmatrix (M.map f) = (charmatrix M).map (Polynomial.map f) := by
ext i j
by_cases h : i = j <;> simp [h, charmatrix, diagonal]
lemma charmatrix_fromBlocks :
charmatrix (fromBlocks M₁₁ M₁₂ M₂₁ M₂₂) =
fromBlocks (charmatrix M₁₁) (- M₁₂.map C) (- M₂₁.map C) (charmatrix M₂₂) := by
simp only [charmatrix]
ext (i|i) (j|j) : 2 <;> simp [diagonal]
-- TODO: importing block triangular here is somewhat expensive, if more lemmas about it are added
-- to this file, it may be worth extracting things out to Charpoly/Block.lean
@[simp]
lemma charmatrix_blockTriangular_iff {α : Type*} [Preorder α] {M : Matrix n n R} {b : n → α} :
M.charmatrix.BlockTriangular b ↔ M.BlockTriangular b := by
rw [charmatrix, scalar_apply, RingHom.mapMatrix_apply, (blockTriangular_diagonal _).sub_iff_right]
simp [BlockTriangular]
alias ⟨BlockTriangular.of_charmatrix, BlockTriangular.charmatrix⟩ := charmatrix_blockTriangular_iff
/-- The characteristic polynomial of a matrix `M` is given by $\det (t I - M)$. -/
def charpoly (M : Matrix n n R) : R[X] :=
(charmatrix M).det
theorem eval_charpoly (M : Matrix m m R) (t : R) :
M.charpoly.eval t = (Matrix.scalar _ t - M).det := by
rw [Matrix.charpoly, ← Polynomial.coe_evalRingHom, RingHom.map_det, Matrix.charmatrix]
congr
ext i j
obtain rfl | hij := eq_or_ne i j <;> simp [*]
@[simp]
theorem charpoly_zero : charpoly (0 : Matrix n n R) = X ^ Fintype.card n := by
simp [charpoly]
theorem charpoly_diagonal (d : n → R) : charpoly (diagonal d) = ∏ i, (X - C (d i)) := by
simp [charpoly]
theorem charpoly_one : charpoly (1 : Matrix n n R) = (X - 1) ^ Fintype.card n := by
simp [charpoly]
theorem charpoly_natCast (k : ℕ) :
charpoly (k : Matrix n n R) = (X - (k : R[X])) ^ Fintype.card n := by
simp [charpoly]
theorem charpoly_ofNat (k : ℕ) [k.AtLeastTwo] :
charpoly (ofNat(k) : Matrix n n R) = (X - ofNat(k)) ^ Fintype.card n:=
charpoly_natCast _
@[simp]
theorem charpoly_transpose (M : Matrix n n R) : (Mᵀ).charpoly = M.charpoly := by
simp [charpoly]
theorem charpoly_reindex (e : n ≃ m)
(M : Matrix n n R) : (reindex e e M).charpoly = M.charpoly := by
unfold Matrix.charpoly
rw [charmatrix_reindex, Matrix.det_reindex_self]
lemma charpoly_map (M : Matrix n n R) (f : R →+* S) :
(M.map f).charpoly = M.charpoly.map f := by
rw [charpoly, charmatrix_map, ← Polynomial.coe_mapRingHom, charpoly, RingHom.map_det,
RingHom.mapMatrix_apply]
@[simp]
lemma charpoly_fromBlocks_zero₁₂ :
(fromBlocks M₁₁ 0 M₂₁ M₂₂).charpoly = (M₁₁.charpoly * M₂₂.charpoly) := by
simp only [charpoly, charmatrix_fromBlocks, Matrix.map_zero _ (Polynomial.C_0), neg_zero,
det_fromBlocks_zero₁₂]
@[simp]
lemma charpoly_fromBlocks_zero₂₁ :
(fromBlocks M₁₁ M₁₂ 0 M₂₂).charpoly = (M₁₁.charpoly * M₂₂.charpoly) := by
simp only [charpoly, charmatrix_fromBlocks, Matrix.map_zero _ (Polynomial.C_0), neg_zero,
det_fromBlocks_zero₂₁]
lemma charmatrix_toSquareBlock {α : Type*} [DecidableEq α] {b : n → α} {a : α} :
(M.toSquareBlock b a).charmatrix = M.charmatrix.toSquareBlock b a := by
ext i j : 1
simp [charmatrix_apply, toSquareBlock_def, diagonal_apply, Subtype.ext_iff]
lemma BlockTriangular.charpoly {α : Type*} {b : n → α} [LinearOrder α] (h : M.BlockTriangular b) :
M.charpoly = ∏ a ∈ image b univ, (M.toSquareBlock b a).charpoly := by
simp only [Matrix.charpoly, h.charmatrix.det, charmatrix_toSquareBlock]
lemma charpoly_of_upperTriangular [LinearOrder n] (M : Matrix n n R) (h : M.BlockTriangular id) :
M.charpoly = ∏ i : n, (X - C (M i i)) := by
simp [charpoly, det_of_upperTriangular h.charmatrix]
-- This proof follows http://drorbn.net/AcademicPensieve/2015-12/CayleyHamilton.pdf
/-- The **Cayley-Hamilton Theorem**, that the characteristic polynomial of a matrix,
applied to the matrix itself, is zero.
This holds over any commutative ring.
See `LinearMap.aeval_self_charpoly` for the equivalent statement about endomorphisms.
-/
theorem aeval_self_charpoly (M : Matrix n n R) : aeval M M.charpoly = 0 := by
-- We begin with the fact $χ_M(t) I = adjugate (t I - M) * (t I - M)$,
-- as an identity in `Matrix n n R[X]`.
have h : M.charpoly • (1 : Matrix n n R[X]) = adjugate (charmatrix M) * charmatrix M :=
(adjugate_mul _).symm
-- Using the algebra isomorphism `Matrix n n R[X] ≃ₐ[R] Polynomial (Matrix n n R)`,
-- we have the same identity in `Polynomial (Matrix n n R)`.
apply_fun matPolyEquiv at h
simp only [map_mul, matPolyEquiv_charmatrix] at h
-- Because the coefficient ring `Matrix n n R` is non-commutative,
-- evaluation at `M` is not multiplicative.
-- However, any polynomial which is a product of the form $N * (t I - M)$
-- is sent to zero, because the evaluation function puts the polynomial variable
-- to the right of any coefficients, so everything telescopes.
apply_fun fun p => p.eval M at h
rw [eval_mul_X_sub_C] at h
-- Now $χ_M (t) I$, when thought of as a polynomial of matrices
-- and evaluated at some `N` is exactly $χ_M (N)$.
rw [matPolyEquiv_smul_one, eval_map] at h
-- Thus we have $χ_M(M) = 0$, which is the desired result.
exact h
end Matrix
|
Basic.lean
|
/-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import Mathlib.Algebra.ContinuedFractions.Basic
import Mathlib.Algebra.Order.Floor.Defs
/-!
# Computable Continued Fractions
## Summary
We formalise the standard computation of (regular) continued fractions for linear ordered floor
fields. The algorithm is rather simple. Here is an outline of the procedure adapted from Wikipedia:
Take a value `v`. We call `⌊v⌋` the *integer part* of `v` and `v - ⌊v⌋` the *fractional part* of
`v`. A continued fraction representation of `v` can then be given by `[⌊v⌋; b₀, b₁, b₂,...]`, where
`[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v - ⌊v⌋)`. This
process stops when the fractional part hits 0.
In other words: to calculate a continued fraction representation of a number `v`, write down the
integer part (i.e. the floor) of `v`. Subtract this integer part from `v`. If the difference is 0,
stop; otherwise find the reciprocal of the difference and repeat. The procedure will terminate if
and only if `v` is rational.
For an example, refer to `IntFractPair.stream`.
## Main definitions
- `GenContFract.IntFractPair.stream`: computes the stream of integer and fractional parts of a given
value as described in the summary.
- `GenContFract.of`: computes the generalised continued fraction of a value `v`.
In fact, it computes a regular continued fraction that terminates if and only if `v` is rational.
## Implementation Notes
There is an intermediate definition `GenContFract.IntFractPair.seq1` between
`GenContFract.IntFractPair.stream` and `GenContFract.of` to wire up things. Users should not
(need to) directly interact with it.
The computation of the integer and fractional pairs of a value can elegantly be
captured by a recursive computation of a stream of option pairs. This is done in
`IntFractPair.stream`. However, the type then does not guarantee the first pair to always be
`some` value, as expected by a continued fraction.
To separate concerns, we first compute a single head term that always exists in
`GenContFract.IntFractPair.seq1` followed by the remaining stream of option pairs. This sequence
with a head term (`seq1`) is then transformed to a generalized continued fraction in
`GenContFract.of` by extracting the wanted integer parts of the head term and the stream.
## References
- https://en.wikipedia.org/wiki/Continued_fraction
## Tags
numerics, number theory, approximations, fractions
-/
assert_not_exists Finset
namespace GenContFract
-- Fix a carrier `K`.
variable (K : Type*)
/-- We collect an integer part `b = ⌊v⌋` and fractional part `fr = v - ⌊v⌋` of a value `v` in a pair
`⟨b, fr⟩`.
-/
structure IntFractPair where
b : ℤ
fr : K
variable {K}
/-! Interlude: define some expected coercions and instances. -/
namespace IntFractPair
/-- Make an `IntFractPair` printable. -/
instance [Repr K] : Repr (IntFractPair K) :=
⟨fun p _ => "(b : " ++ repr p.b ++ ", fract : " ++ repr p.fr ++ ")"⟩
instance inhabited [Inhabited K] : Inhabited (IntFractPair K) :=
⟨⟨0, default⟩⟩
/-- Maps a function `f` on the fractional components of a given pair.
-/
def mapFr {β : Type*} (f : K → β) (gp : IntFractPair K) : IntFractPair β :=
⟨gp.b, f gp.fr⟩
section coe
/-! Interlude: define some expected coercions. -/
-- Fix another type `β` which we will convert to.
variable {β : Type*} [Coe K β]
/-- The coercion between integer-fraction pairs happens componentwise. -/
@[coe]
def coeFn : IntFractPair K → IntFractPair β := mapFr (↑)
/-- Coerce a pair by coercing the fractional component. -/
instance coe : Coe (IntFractPair K) (IntFractPair β) where
coe := coeFn
@[simp, norm_cast]
theorem coe_to_intFractPair {b : ℤ} {fr : K} :
(↑(IntFractPair.mk b fr) : IntFractPair β) = IntFractPair.mk b (↑fr : β) :=
rfl
end coe
-- Fix a discrete linear ordered division ring with `floor` function.
variable [DivisionRing K] [LinearOrder K] [FloorRing K]
/-- Creates the integer and fractional part of a value `v`, i.e. `⟨⌊v⌋, v - ⌊v⌋⟩`. -/
protected def of (v : K) : IntFractPair K :=
⟨⌊v⌋, Int.fract v⟩
/-- Creates the stream of integer and fractional parts of a value `v` needed to obtain the continued
fraction representation of `v` in `GenContFract.of`. More precisely, given a value `v : K`, it
recursively computes a stream of option `ℤ × K` pairs as follows:
- `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩`
- `stream v (n + 1) = some ⟨⌊frₙ⁻¹⌋, frₙ⁻¹ - ⌊frₙ⁻¹⌋⟩`,
if `stream v n = some ⟨_, frₙ⟩` and `frₙ ≠ 0`
- `stream v (n + 1) = none`, otherwise
For example, let `(v : ℚ) := 3.4`. The process goes as follows:
- `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩ = some ⟨3, 0.4⟩`
- `stream v 1 = some ⟨⌊0.4⁻¹⌋, 0.4⁻¹ - ⌊0.4⁻¹⌋⟩ = some ⟨⌊2.5⌋, 2.5 - ⌊2.5⌋⟩ = some ⟨2, 0.5⟩`
- `stream v 2 = some ⟨⌊0.5⁻¹⌋, 0.5⁻¹ - ⌊0.5⁻¹⌋⟩ = some ⟨⌊2⌋, 2 - ⌊2⌋⟩ = some ⟨2, 0⟩`
- `stream v n = none`, for `n ≥ 3`
-/
protected def stream (v : K) : Stream' <| Option (IntFractPair K)
| 0 => some (IntFractPair.of v)
| n + 1 =>
(IntFractPair.stream v n).bind fun ap_n =>
if ap_n.fr = 0 then none else some (IntFractPair.of ap_n.fr⁻¹)
/-- Shows that `IntFractPair.stream` has the sequence property, that is once we return `none` at
position `n`, we also return `none` at `n + 1`.
-/
theorem stream_isSeq (v : K) : (IntFractPair.stream v).IsSeq := by
intro _ hyp
simp [IntFractPair.stream, hyp]
/--
Uses `IntFractPair.stream` to create a sequence with head (i.e. `seq1`) of integer and fractional
parts of a value `v`. The first value of `IntFractPair.stream` is never `none`, so we can safely
extract it and put the tail of the stream in the sequence part.
This is just an intermediate representation and users should not (need to) directly interact with
it. The setup of rewriting/simplification lemmas that make the definitions easy to use is done in
`Mathlib/Algebra/ContinuedFractions/Computation/Translations.lean`.
-/
protected def seq1 (v : K) : Stream'.Seq1 <| IntFractPair K :=
⟨IntFractPair.of v, -- the head
-- take the tail of `IntFractPair.stream` since the first element is already in the head
Stream'.Seq.tail
-- create a sequence from `IntFractPair.stream`
⟨IntFractPair.stream v, -- the underlying stream
stream_isSeq v⟩⟩ -- the proof that the stream is a sequence
end IntFractPair
/-- Returns the `GenContFract` of a value. In fact, the returned gcf is also a `ContFract` that
terminates if and only if `v` is rational
(see `Mathlib/Algebra/ContinuedFractions/Computation/TerminatesIffRat.lean`).
The continued fraction representation of `v` is given by `[⌊v⌋; b₀, b₁, b₂,...]`, where
`[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v - ⌊v⌋)`. This
process stops when the fractional part `v - ⌊v⌋` hits 0 at some step.
The implementation uses `IntFractPair.stream` to obtain the partial denominators of the continued
fraction. Refer to said function for more details about the computation process.
-/
protected def of [DivisionRing K] [LinearOrder K] [FloorRing K] (v : K) : GenContFract K :=
let ⟨h, s⟩ := IntFractPair.seq1 v -- get the sequence of integer and fractional parts.
⟨h.b, -- the head is just the first integer part
s.map fun p => ⟨1, p.b⟩⟩ -- the sequence consists of the remaining integer parts as the partial
-- denominators; all partial numerators are simply 1
end GenContFract
|
Defs.lean
|
/-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import Mathlib.Algebra.Field.Basic
import Mathlib.Algebra.Field.Rat
import Mathlib.Algebra.Group.Commute.Basic
import Mathlib.Algebra.GroupWithZero.Units.Lemmas
import Mathlib.Data.Int.Cast.Lemmas
import Mathlib.Data.Rat.Lemmas
import Mathlib.Order.Nat
/-!
# Casts for Rational Numbers
## Summary
We define the canonical injection from ℚ into an arbitrary division ring and prove various
casting lemmas showing the well-behavedness of this injection.
## Tags
rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting
-/
assert_not_exists MulAction OrderedAddCommMonoid
variable {F ι α β : Type*}
namespace NNRat
variable [DivisionSemiring α] {q r : ℚ≥0}
@[simp, norm_cast] lemma cast_natCast (n : ℕ) : ((n : ℚ≥0) : α) = n := by simp [cast_def]
@[simp, norm_cast] lemma cast_ofNat (n : ℕ) [n.AtLeastTwo] :
(ofNat(n) : ℚ≥0) = (ofNat(n) : α) := cast_natCast _
@[simp, norm_cast] lemma cast_zero : ((0 : ℚ≥0) : α) = 0 := (cast_natCast _).trans Nat.cast_zero
@[simp, norm_cast] lemma cast_one : ((1 : ℚ≥0) : α) = 1 := (cast_natCast _).trans Nat.cast_one
lemma cast_commute (q : ℚ≥0) (a : α) : Commute (↑q) a := by
simpa only [cast_def] using (q.num.cast_commute a).div_left (q.den.cast_commute a)
lemma commute_cast (a : α) (q : ℚ≥0) : Commute a q := (cast_commute ..).symm
lemma cast_comm (q : ℚ≥0) (a : α) : q * a = a * q := cast_commute _ _
@[norm_cast] lemma cast_divNat_of_ne_zero (a : ℕ) {b : ℕ} (hb : (b : α) ≠ 0) :
divNat a b = (a / b : α) := by
rcases e : divNat a b with ⟨⟨n, d, h, c⟩, hn⟩
rw [← Rat.num_nonneg] at hn
lift n to ℕ using hn
have hd : (d : α) ≠ 0 := by
refine fun hd ↦ hb ?_
have : Rat.divInt a b = _ := congr_arg NNRat.cast e
obtain ⟨k, rfl⟩ : d ∣ b := by simpa [Int.natCast_dvd_natCast, this] using Rat.den_dvd a b
simp [*]
have hb' : b ≠ 0 := by rintro rfl; exact hb Nat.cast_zero
simp_rw [Rat.mk'_eq_divInt, mk_divInt, divNat_inj hb' h] at e
rw [cast_def]
dsimp
rw [Commute.div_eq_div_iff _ hd hb]
· norm_cast
rw [e]
exact b.commute_cast _
@[norm_cast]
lemma cast_add_of_ne_zero (hq : (q.den : α) ≠ 0) (hr : (r.den : α) ≠ 0) :
↑(q + r) = (q + r : α) := by
rw [add_def, cast_divNat_of_ne_zero, cast_def, cast_def, mul_comm _ q.den,
(Nat.commute_cast _ _).div_add_div (Nat.commute_cast _ _) hq hr]
· push_cast
rfl
· push_cast
exact mul_ne_zero hq hr
@[norm_cast]
lemma cast_mul_of_ne_zero (hq : (q.den : α) ≠ 0) (hr : (r.den : α) ≠ 0) :
↑(q * r) = (q * r : α) := by
rw [mul_def, cast_divNat_of_ne_zero, cast_def, cast_def,
(Nat.commute_cast _ _).div_mul_div_comm (Nat.commute_cast _ _)]
· push_cast
rfl
· push_cast
exact mul_ne_zero hq hr
@[norm_cast]
lemma cast_inv_of_ne_zero (hq : (q.num : α) ≠ 0) : (q⁻¹ : ℚ≥0) = (q⁻¹ : α) := by
rw [inv_def, cast_divNat_of_ne_zero _ hq, cast_def, inv_div]
@[norm_cast]
lemma cast_div_of_ne_zero (hq : (q.den : α) ≠ 0) (hr : (r.num : α) ≠ 0) :
↑(q / r) = (q / r : α) := by
rw [div_def, cast_divNat_of_ne_zero, cast_def, cast_def, div_eq_mul_inv (_ / _),
inv_div, (Nat.commute_cast _ _).div_mul_div_comm (Nat.commute_cast _ _)]
· push_cast
rfl
· push_cast
exact mul_ne_zero hq hr
end NNRat
namespace Rat
variable [DivisionRing α] {p q : ℚ}
@[simp, norm_cast]
theorem cast_intCast (n : ℤ) : ((n : ℚ) : α) = n :=
(cast_def _).trans <| show (n / (1 : ℕ) : α) = n by rw [Nat.cast_one, div_one]
@[simp, norm_cast]
theorem cast_natCast (n : ℕ) : ((n : ℚ) : α) = n := by
rw [← Int.cast_natCast, cast_intCast, Int.cast_natCast]
@[simp, norm_cast] lemma cast_ofNat (n : ℕ) [n.AtLeastTwo] :
((ofNat(n) : ℚ) : α) = (ofNat(n) : α) := by
simp [cast_def]
@[simp, norm_cast]
theorem cast_zero : ((0 : ℚ) : α) = 0 :=
(cast_intCast _).trans Int.cast_zero
@[simp, norm_cast]
theorem cast_one : ((1 : ℚ) : α) = 1 :=
(cast_intCast _).trans Int.cast_one
theorem cast_commute (r : ℚ) (a : α) : Commute (↑r) a := by
simpa only [cast_def] using (r.1.cast_commute a).div_left (r.2.cast_commute a)
theorem cast_comm (r : ℚ) (a : α) : (r : α) * a = a * r :=
(cast_commute r a).eq
theorem commute_cast (a : α) (r : ℚ) : Commute a r :=
(r.cast_commute a).symm
@[norm_cast]
lemma cast_divInt_of_ne_zero (a : ℤ) {b : ℤ} (b0 : (b : α) ≠ 0) : (a /. b : α) = a / b := by
have b0' : b ≠ 0 := by
refine mt ?_ b0
simp +contextual
rcases e : a /. b with ⟨n, d, h, c⟩
have d0 : (d : α) ≠ 0 := by
intro d0
have dd := den_dvd a b
rcases show (d : ℤ) ∣ b by rwa [e] at dd with ⟨k, ke⟩
have : (b : α) = (d : α) * (k : α) := by rw [ke, Int.cast_mul, Int.cast_natCast]
rw [d0, zero_mul] at this
contradiction
rw [mk'_eq_divInt] at e
have := congr_arg ((↑) : ℤ → α)
((divInt_eq_iff b0' <| ne_of_gt <| Int.natCast_pos.2 h.bot_lt).1 e)
rw [Int.cast_mul, Int.cast_mul, Int.cast_natCast] at this
rw [eq_comm, cast_def, div_eq_mul_inv, eq_div_iff_mul_eq d0, mul_assoc, (d.commute_cast _).eq,
← mul_assoc, this, mul_assoc, mul_inv_cancel₀ b0, mul_one]
@[norm_cast]
lemma cast_mkRat_of_ne_zero (a : ℤ) {b : ℕ} (hb : (b : α) ≠ 0) : (mkRat a b : α) = a / b := by
rw [Rat.mkRat_eq_divInt, cast_divInt_of_ne_zero, Int.cast_natCast]; rwa [Int.cast_natCast]
@[norm_cast]
lemma cast_add_of_ne_zero {q r : ℚ} (hq : (q.den : α) ≠ 0) (hr : (r.den : α) ≠ 0) :
(q + r : ℚ) = (q + r : α) := by
rw [add_def', cast_mkRat_of_ne_zero, cast_def, cast_def, mul_comm r.num,
(Nat.cast_commute _ _).div_add_div (Nat.commute_cast _ _) hq hr]
· push_cast
rfl
· push_cast
exact mul_ne_zero hq hr
@[simp, norm_cast] lemma cast_neg (q : ℚ) : ↑(-q) = (-q : α) := by simp [cast_def, neg_div]
@[norm_cast] lemma cast_sub_of_ne_zero (hp : (p.den : α) ≠ 0) (hq : (q.den : α) ≠ 0) :
↑(p - q) = (p - q : α) := by simp [sub_eq_add_neg, cast_add_of_ne_zero, hp, hq]
@[norm_cast] lemma cast_mul_of_ne_zero (hp : (p.den : α) ≠ 0) (hq : (q.den : α) ≠ 0) :
↑(p * q) = (p * q : α) := by
rw [mul_eq_mkRat, cast_mkRat_of_ne_zero, cast_def, cast_def,
(Nat.commute_cast _ _).div_mul_div_comm (Int.commute_cast _ _)]
· push_cast
rfl
· push_cast
exact mul_ne_zero hp hq
@[norm_cast]
lemma cast_inv_of_ne_zero (hq : (q.num : α) ≠ 0) : ↑(q⁻¹) = (q⁻¹ : α) := by
rw [inv_def', cast_divInt_of_ne_zero _ hq, cast_def, inv_div, Int.cast_natCast]
@[norm_cast] lemma cast_div_of_ne_zero (hp : (p.den : α) ≠ 0) (hq : (q.num : α) ≠ 0) :
↑(p / q) = (p / q : α) := by
rw [div_def', cast_divInt_of_ne_zero, cast_def, cast_def, div_eq_mul_inv (_ / _), inv_div,
(Int.commute_cast _ _).div_mul_div_comm (Nat.commute_cast _ _)]
· push_cast
rfl
· push_cast
exact mul_ne_zero hp hq
end Rat
open Rat
variable [FunLike F α β]
@[simp] lemma map_nnratCast [DivisionSemiring α] [DivisionSemiring β] [RingHomClass F α β] (f : F)
(q : ℚ≥0) : f q = q := by simp_rw [NNRat.cast_def, map_div₀, map_natCast]
@[simp]
lemma eq_nnratCast [DivisionSemiring α] [FunLike F ℚ≥0 α] [RingHomClass F ℚ≥0 α] (f : F) (q : ℚ≥0) :
f q = q := by rw [← map_nnratCast f, NNRat.cast_id]
@[simp]
theorem map_ratCast [DivisionRing α] [DivisionRing β] [RingHomClass F α β] (f : F) (q : ℚ) :
f q = q := by rw [cast_def, map_div₀, map_intCast, map_natCast, cast_def]
@[simp] lemma eq_ratCast [DivisionRing α] [FunLike F ℚ α] [RingHomClass F ℚ α] (f : F) (q : ℚ) :
f q = q := by rw [← map_ratCast f, Rat.cast_id]
namespace MonoidWithZeroHomClass
variable {M₀ : Type*} [MonoidWithZero M₀]
section NNRat
variable [FunLike F ℚ≥0 M₀] [MonoidWithZeroHomClass F ℚ≥0 M₀] {f g : F}
/-- If monoid with zero homs `f` and `g` from `ℚ≥0` agree on the naturals then they are equal. -/
lemma ext_nnrat' (h : ∀ n : ℕ, f n = g n) : f = g :=
(DFunLike.ext f g) fun r => by
rw [← r.num_div_den, div_eq_mul_inv, map_mul, map_mul, h, eq_on_inv₀ f g]
apply h
/-- If monoid with zero homs `f` and `g` from `ℚ≥0` agree on the naturals then they are equal.
See note [partially-applied ext lemmas] for why `comp` is used here. -/
@[ext]
lemma ext_nnrat {f g : ℚ≥0 →*₀ M₀}
(h : f.comp (Nat.castRingHom ℚ≥0 : ℕ →*₀ ℚ≥0) = g.comp (Nat.castRingHom ℚ≥0)) : f = g :=
ext_nnrat' <| DFunLike.congr_fun h
/-- If monoid with zero homs `f` and `g` from `ℚ≥0` agree on the positive naturals then they are
equal. -/
lemma ext_nnrat_on_pnat (same_on_pnat : ∀ n : ℕ, 0 < n → f n = g n) : f = g :=
ext_nnrat' <| DFunLike.congr_fun <| ext_nat''
((f : ℚ≥0 →*₀ M₀).comp (Nat.castRingHom ℚ≥0 : ℕ →*₀ ℚ≥0))
((g : ℚ≥0 →*₀ M₀).comp (Nat.castRingHom ℚ≥0 : ℕ →*₀ ℚ≥0)) (by simpa)
end NNRat
section Rat
variable [FunLike F ℚ M₀] [MonoidWithZeroHomClass F ℚ M₀] {f g : F}
/-- If monoid with zero homs `f` and `g` from `ℚ` agree on the integers then they are equal. -/
theorem ext_rat' (h : ∀ m : ℤ, f m = g m) : f = g :=
(DFunLike.ext f g) fun r => by
rw [← r.num_div_den, div_eq_mul_inv, map_mul, map_mul, h, ← Int.cast_natCast,
eq_on_inv₀ f g]
apply h
/-- If monoid with zero homs `f` and `g` from `ℚ` agree on the integers then they are equal.
See note [partially-applied ext lemmas] for why `comp` is used here. -/
@[ext]
theorem ext_rat {f g : ℚ →*₀ M₀}
(h : f.comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) = g.comp (Int.castRingHom ℚ)) : f = g :=
ext_rat' <| DFunLike.congr_fun h
/-- If monoid with zero homs `f` and `g` from `ℚ` agree on the positive naturals and `-1` then
they are equal. -/
theorem ext_rat_on_pnat (same_on_neg_one : f (-1) = g (-1))
(same_on_pnat : ∀ n : ℕ, 0 < n → f n = g n) : f = g :=
ext_rat' <|
DFunLike.congr_fun <|
show
(f : ℚ →*₀ M₀).comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) =
(g : ℚ →*₀ M₀).comp (Int.castRingHom ℚ : ℤ →*₀ ℚ)
from ext_int' (by simpa) (by simpa)
end Rat
end MonoidWithZeroHomClass
/-- Any two ring homomorphisms from `ℚ` to a semiring are equal. If the codomain is a division ring,
then this lemma follows from `eq_ratCast`. -/
theorem RingHom.ext_rat {R : Type*} [Semiring R] [FunLike F ℚ R] [RingHomClass F ℚ R] (f g : F) :
f = g :=
MonoidWithZeroHomClass.ext_rat' <|
RingHom.congr_fun <|
((f : ℚ →+* R).comp (Int.castRingHom ℚ)).ext_int ((g : ℚ →+* R).comp (Int.castRingHom ℚ))
instance NNRat.subsingleton_ringHom {R : Type*} [Semiring R] : Subsingleton (ℚ≥0 →+* R) where
allEq f g := MonoidWithZeroHomClass.ext_nnrat' <| by simp
instance Rat.subsingleton_ringHom {R : Type*} [Semiring R] : Subsingleton (ℚ →+* R) :=
⟨RingHom.ext_rat⟩
|
Tietze.lean
|
/-
Copyright (c) 2024 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import Mathlib.Analysis.Complex.Basic
import Mathlib.Analysis.RCLike.Lemmas
import Mathlib.Topology.TietzeExtension
import Mathlib.Analysis.NormedSpace.HomeomorphBall
import Mathlib.Analysis.NormedSpace.RCLike
/-!
# Finite dimensional topological vector spaces over `ℝ` satisfy the Tietze extension property
There are two main results here:
- `RCLike.instTietzeExtensionTVS`: finite dimensional topological vector spaces over `ℝ` (or `ℂ`)
have the Tietze extension property.
- `BoundedContinuousFunction.exists_norm_eq_restrict_eq`: when mapping into a finite dimensional
normed vector space over `ℝ` (or `ℂ`), the extension can be chosen to preserve the norm of the
bounded continuous function it extends.
-/
universe u u₁ v w
-- this is not an instance because Lean cannot determine `𝕜`.
theorem TietzeExtension.of_tvs (𝕜 : Type v) [NontriviallyNormedField 𝕜] {E : Type w}
[AddCommGroup E] [Module 𝕜 E] [TopologicalSpace E] [IsTopologicalAddGroup E]
[ContinuousSMul 𝕜 E] [T2Space E] [FiniteDimensional 𝕜 E] [CompleteSpace 𝕜]
[TietzeExtension.{u, v} 𝕜] : TietzeExtension.{u, w} E :=
Module.Basis.ofVectorSpace 𝕜 E |>.equivFun.toContinuousLinearEquiv.toHomeomorph |> .of_homeo
instance Complex.instTietzeExtension : TietzeExtension ℂ :=
TietzeExtension.of_tvs ℝ
instance (priority := 900) RCLike.instTietzeExtension {𝕜 : Type*} [RCLike 𝕜] :
TietzeExtension 𝕜 := TietzeExtension.of_tvs ℝ
instance RCLike.instTietzeExtensionTVS {𝕜 : Type v} [RCLike 𝕜] {E : Type w}
[AddCommGroup E] [Module 𝕜 E] [TopologicalSpace E] [IsTopologicalAddGroup E]
[ContinuousSMul 𝕜 E] [T2Space E] [FiniteDimensional 𝕜 E] :
TietzeExtension.{u, w} E :=
TietzeExtension.of_tvs 𝕜
instance Set.instTietzeExtensionUnitBall {𝕜 : Type v} [RCLike 𝕜] {E : Type w}
[NormedAddCommGroup E] [NormedSpace 𝕜 E] [FiniteDimensional 𝕜 E] :
TietzeExtension.{u, w} (Metric.ball (0 : E) 1) :=
have : NormedSpace ℝ E := NormedSpace.restrictScalars ℝ 𝕜 E
.of_homeo Homeomorph.unitBall.symm
instance Set.instTietzeExtensionUnitClosedBall {𝕜 : Type v} [RCLike 𝕜] {E : Type w}
[NormedAddCommGroup E] [NormedSpace 𝕜 E] [FiniteDimensional 𝕜 E] :
TietzeExtension.{u, w} (Metric.closedBall (0 : E) 1) := by
have : NormedSpace ℝ E := NormedSpace.restrictScalars ℝ 𝕜 E
have : IsScalarTower ℝ 𝕜 E := Real.isScalarTower
-- I didn't find this retract in Mathlib.
let g : E → E := fun x ↦ ‖x‖⁻¹ • x
classical
suffices this : Continuous (piecewise (Metric.closedBall 0 1) id g) by
refine .of_retract ⟨Subtype.val, by fun_prop⟩ ⟨_, this.codRestrict fun x ↦ ?_⟩ ?_
· by_cases hx : x ∈ Metric.closedBall 0 1
· simpa [piecewise_eq_of_mem (hi := hx)] using hx
· simp only [g, piecewise_eq_of_notMem (hi := hx), RCLike.real_smul_eq_coe_smul (K := 𝕜)]
by_cases hx' : x = 0 <;> simp [hx']
· ext x
simp
refine continuous_piecewise (fun x hx ↦ ?_) continuousOn_id ?_
· replace hx : ‖x‖ = 1 := by simpa [frontier_closedBall (0 : E) one_ne_zero] using hx
simp [g, hx]
· refine continuousOn_id.norm.inv₀ ?_ |>.smul continuousOn_id
simp only [closure_compl, interior_closedBall (0 : E) one_ne_zero, mem_compl_iff,
Metric.mem_ball, dist_zero_right, not_lt, id_eq, ne_eq, norm_eq_zero]
exact fun x hx ↦ norm_pos_iff.mp <| one_pos.trans_le hx
theorem Metric.instTietzeExtensionBall {𝕜 : Type v} [RCLike 𝕜] {E : Type w}
[NormedAddCommGroup E] [NormedSpace 𝕜 E] [FiniteDimensional 𝕜 E] {r : ℝ} (hr : 0 < r) :
TietzeExtension.{u, w} (Metric.ball (0 : E) r) :=
have : NormedSpace ℝ E := NormedSpace.restrictScalars ℝ 𝕜 E
.of_homeo <| show (Metric.ball (0 : E) r) ≃ₜ (Metric.ball (0 : E) 1) from
PartialHomeomorph.unitBallBall (0 : E) r hr |>.toHomeomorphSourceTarget.symm
theorem Metric.instTietzeExtensionClosedBall (𝕜 : Type v) [RCLike 𝕜] {E : Type w}
[NormedAddCommGroup E] [NormedSpace 𝕜 E] [FiniteDimensional 𝕜 E] (y : E) {r : ℝ} (hr : 0 < r) :
TietzeExtension.{u, w} (Metric.closedBall y r) :=
.of_homeo <| by
change (Metric.closedBall y r) ≃ₜ (Metric.closedBall (0 : E) 1)
symm
apply (DilationEquiv.smulTorsor y (k := (r : 𝕜)) <| by exact_mod_cast hr.ne').toHomeomorph.sets
ext x
simp only [mem_closedBall, dist_zero_right, DilationEquiv.coe_toHomeomorph, Set.mem_preimage,
DilationEquiv.smulTorsor_apply, vadd_eq_add, dist_add_self_left, norm_smul,
RCLike.norm_ofReal, abs_of_nonneg hr.le]
exact (mul_le_iff_le_one_right hr).symm
variable {X : Type u} [TopologicalSpace X] [NormalSpace X] {s : Set X} (hs : IsClosed s)
variable (𝕜 : Type v) [RCLike 𝕜]
variable {E : Type w} [NormedAddCommGroup E] [NormedSpace 𝕜 E] [FiniteDimensional 𝕜 E]
namespace BoundedContinuousFunction
include 𝕜 hs in
/-- **Tietze extension theorem** for real-valued bounded continuous maps, a version with a closed
embedding and bundled composition. If `e : C(X, Y)` is a closed embedding of a topological space
into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists
a bounded continuous function `g : Y →ᵇ ℝ` of the same norm such that `g ∘ e = f`. -/
theorem exists_norm_eq_restrict_eq (f : s →ᵇ E) :
∃ g : X →ᵇ E, ‖g‖ = ‖f‖ ∧ g.restrict s = f := by
by_cases hf : ‖f‖ = 0; · exact ⟨0, by aesop⟩
have := Metric.instTietzeExtensionClosedBall.{u, v} 𝕜 (0 : E) (by aesop : 0 < ‖f‖)
have hf' x : f x ∈ Metric.closedBall 0 ‖f‖ := by simpa using f.norm_coe_le_norm x
obtain ⟨g, hg_mem, hg⟩ := (f : C(s, E)).exists_forall_mem_restrict_eq hs hf'
simp only [Metric.mem_closedBall, dist_zero_right] at hg_mem
let g' : X →ᵇ E := .ofNormedAddCommGroup g (map_continuous g) ‖f‖ hg_mem
refine ⟨g', ?_, by ext x; congrm($(hg) x)⟩
apply le_antisymm ((g'.norm_le <| by positivity).mpr hg_mem)
refine (f.norm_le <| by positivity).mpr fun x ↦ ?_
have hx : f x = g' x := by simpa using congr($(hg) x).symm
rw [hx]
exact g'.norm_le (norm_nonneg g') |>.mp le_rfl x
end BoundedContinuousFunction
|
Testable.lean
|
/-
Copyright (c) 2022 Henrik Böving. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Henrik Böving, Simon Hudon
-/
import Plausible.Testable
import Mathlib.Logic.Basic
/-!
This module contains `Plausible.Testable` and `Plausible.PrintableProb` instances for mathlib types.
-/
namespace Plausible
namespace Testable
open TestResult
instance factTestable {p : Prop} [Testable p] : Testable (Fact p) where
run cfg min := do
let h ← runProp p cfg min
pure <| iff fact_iff h
end Testable
section PrintableProp
instance Fact.printableProp {p : Prop} [PrintableProp p] : PrintableProp (Fact p) where
printProp := printProp p
end PrintableProp
end Plausible
|
ssrmatching.v
|
From Corelib Require Export ssrmatching.
|
test_rat.v
|
From mathcomp Require Import all_boot all_order all_algebra.
Local Open Scope ring_scope.
Goal 2%:Q + 2%:Q = 4%:Q.
Proof. reflexivity. Qed.
Goal - 2%:Q = -1 * 2%:Q.
Proof. reflexivity. Qed.
Goal 2%:Q ^+ 2 = 4%:Q.
Proof. reflexivity. Qed.
Goal (-1)^-1 = -1 :> rat.
Proof. reflexivity. Qed.
Local Open Scope rat_scope.
Check 12.
Check 3.14.
Check -3.14.
Check 0.5.
Check 0.2.
|
ring_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 choice ssrnat.
From mathcomp Require Import seq ssralg generic_quotient.
(******************************************************************************)
(* Quotients of algebraic structures *)
(* *)
(* This file defines a join hierarchy mixing the structures defined in file *)
(* ssralg (up to unit ring type) and the quotType quotient structure defined *)
(* in generic_quotient.v. Every structure in that (join) hierarchy is *)
(* parametrized by a base type T and the constants and operations on the *)
(* base type that will be used to confer its algebraic structure to the *)
(* quotient. Note that T itself is in general not an instance of an *)
(* algebraic structure. The canonical surjection from T onto its quotient *)
(* should be compatible with the parameter operations. *)
(* *)
(* The second part of the file provides a definition of (non trivial) *)
(* decidable ideals (resp. prime ideals) of an arbitrary instance of ring *)
(* structure and a construction of the quotient of a ring by such an ideal. *)
(* These definitions extend the hierarchy of sub-structures defined in file *)
(* ssralg (see Module Pred in ssralg), following a similar methodology. *)
(* Although the definition of the (structure of) quotient of a ring by an *)
(* ideal is a general one, we do not provide infrastructure for the case of *)
(* non commutative ring and left or two-sided ideals. *)
(* *)
(* The file defines the following Structures: *)
(* zmodQuotType T e z n a == Z-module obtained by quotienting type T *)
(* with the relation e and whose neutral, *)
(* opposite and addition are the images in the *)
(* quotient of the parameters z, n and a, *)
(* respectively *)
(* The HB class is called ZmodQuotient. *)
(* nzRingQuotType T e z n a o m == non trivial ring obtained by quotienting *)
(* type T with the relation e and whose zero *)
(* opposite, addition, one, and multiplication *)
(* are the images in the quotient of the *)
(* parameters z, n, a, o, m, respectively *)
(* The HB class is called NzRingQuotient. *)
(* unitRingQuotType ... u i == As in the previous cases, instance of unit *)
(* ring whose unit predicate is obtained from *)
(* u and the inverse from i *)
(* The HB class is called UnitRingQuotient. *)
(* idealr R == {pred R} is a non-trivial, decidable, *)
(* right ideal of the ring R *)
(* (join of GRing.ZmodClosed and ProperIdeal) *)
(* The HB class is called Idealr. *)
(* prime_idealr R == {pred R} is a non-trivial, decidable, *)
(* right, prime ideal of the ring R *)
(* The HB class is called PrimeIdealr. *)
(* *)
(* The formalization of ideals features the following constructions: *)
(* proper_ideal R == the collective predicate (S : pred R) on the *)
(* ring R is stable by the ring product and does *)
(* contain R's one *)
(* The HB class is called ProperIdeal. *)
(* idealr R == join of GRing.ZmodClosed and ProperIdeal *)
(* prime_idealr_closed S := u * v \in S -> (u \in S) || (v \in S) *)
(* idealr_closed S == the collective predicate (S : pred R) on the *)
(* ring R represents a (right) ideal *)
(* This implies its being a proper_ideal. *)
(* {ideal_quot kI} == quotient by the keyed (right) ideal predicate *)
(* kI of a commutative ring R. Note that we only *)
(* provide canonical structures of ring quotients *)
(* for commutative rings, in which a right ideal *)
(* is obviously a two-sided ideal *)
(******************************************************************************)
Import GRing.Theory.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Local Open Scope ring_scope.
Local Open Scope quotient_scope.
Reserved Notation "{ 'ideal_quot' I }" (format "{ 'ideal_quot' I }").
#[warning="-postfix-notation-not-level-1"]
Reserved Notation "m = n %[ 'mod_ideal' I ]"
(format "'[hv ' m '/' = n '/' %[ 'mod_ideal' I ] ']'").
#[warning="-postfix-notation-not-level-1"]
Reserved Notation "m == n %[ 'mod_ideal' I ]"
(format "'[hv ' m '/' == n '/' %[ 'mod_ideal' I ] ']'").
#[warning="-postfix-notation-not-level-1"]
Reserved Notation "m <> n %[ 'mod_ideal' I ]"
(format "'[hv ' m '/' <> n '/' %[ 'mod_ideal' I ] ']'").
#[warning="-postfix-notation-not-level-1"]
Reserved Notation "m != n %[ 'mod_ideal' I ]"
(format "'[hv ' m '/' != n '/' %[ 'mod_ideal' I ] ']'").
(* Variable (T : Type).
Variable eqT : rel T.
Variables (zeroT : T) (oppT : T -> T) (addT : T -> T -> T). *)
HB.mixin Record isZmodQuotient T eqT (zeroT : T) (oppT : T -> T) (addT : T -> T -> T)
(Q : Type) of GRing.Zmodule Q & EqQuotient T eqT Q := {
pi_zeror : \pi_Q zeroT = 0;
pi_oppr : {morph \pi_Q : x / oppT x >-> - x};
pi_addr : {morph \pi_Q : x y / addT x y >-> x + y}
}.
#[short(type="zmodQuotType")]
HB.structure Definition ZmodQuotient T eqT zeroT oppT addT :=
{Q of isZmodQuotient T eqT zeroT oppT addT Q &
GRing.Zmodule Q & EqQuotient T eqT Q}.
Section ZModQuotient.
Variable (T : Type).
Variable eqT : rel T.
Variables (zeroT : T) (oppT : T -> T) (addT : T -> T -> T).
Implicit Type zqT : ZmodQuotient.type eqT zeroT oppT addT.
Canonical pi_zero_quot_morph zqT := PiMorph (@pi_zeror _ _ _ _ _ zqT).
Canonical pi_opp_quot_morph zqT := PiMorph1 (@pi_oppr _ _ _ _ _ zqT).
Canonical pi_add_quot_morph zqT := PiMorph2 (@pi_addr _ _ _ _ _ zqT).
End ZModQuotient.
Section PiAdditive.
Variables (V : zmodType) (equivV : rel V) (zeroV : V).
Variable Q : @zmodQuotType V equivV zeroV -%R +%R.
Lemma pi_is_zmod_morphism : zmod_morphism \pi_Q.
Proof. by move=> x y /=; rewrite !piE. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `pi_is_monoid_morphism` instead")]
Definition pi_is_additive := pi_is_zmod_morphism.
HB.instance Definition _ := GRing.isZmodMorphism.Build V Q \pi_Q pi_is_zmod_morphism.
End PiAdditive.
(* Variable (T : Type).
Variable eqT : rel T.
Variables (zeroT : T) (oppT : T -> T) (addT : T -> T -> T).
Variables (oneT : T) (mulT : T -> T -> T).
*)
HB.mixin Record isNzRingQuotient T eqT zeroT oppT
addT (oneT : T) (mulT : T -> T -> T) (Q : Type)
of ZmodQuotient T eqT zeroT oppT addT Q & GRing.NzRing Q:=
{
pi_oner : \pi_Q oneT = 1;
pi_mulr : {morph \pi_Q : x y / mulT x y >-> x * y}
}.
Module isRingQuotient.
#[deprecated(since="mathcomp 2.4.0",
note="Use isNzRingQuotient.Build instead.")]
Notation Build T eqT zeroT oppT addT oneT mulT Q :=
(isNzRingQuotient.Build T eqT zeroT oppT addT oneT mulT Q) (only parsing).
End isRingQuotient.
#[deprecated(since="mathcomp 2.4.0",
note="Use isNzRingQuotient instead.")]
Notation isRingQuotient T eqT zeroT oppT addT oneT mulT Q :=
(isNzRingQuotient T eqT zeroT oppT addT oneT mulT Q) (only parsing).
#[short(type="nzRingQuotType")]
HB.structure Definition NzRingQuotient T eqT zeroT oppT addT oneT mulT :=
{Q of isNzRingQuotient T eqT zeroT oppT addT oneT mulT Q &
ZmodQuotient T eqT zeroT oppT addT Q & GRing.NzRing Q }.
#[deprecated(since="mathcomp 2.4.0",
note="Use nzRingQuotType instead.")]
Notation ringQuotType := (nzRingQuotType) (only parsing).
Section nzRingQuotient.
(*Clash with the module name NzRingQuotient*)
Variable (T : Type).
Variable eqT : rel T.
Variables (zeroT : T) (oppT : T -> T) (addT : T -> T -> T) (oneT : T) (mulT : T -> T -> T).
Implicit Type rqT : NzRingQuotient.type eqT zeroT oppT addT oneT mulT.
Canonical pi_one_quot_morph rqT := PiMorph (@pi_oner _ _ _ _ _ _ _ rqT).
Canonical pi_mul_quot_morph rqT := PiMorph2 (@pi_mulr _ _ _ _ _ _ _ rqT).
End nzRingQuotient.
Section PiRMorphism.
Variables (R : nzRingType) (equivR : rel R) (zeroR : R).
Variable Q : @nzRingQuotType R equivR zeroR -%R +%R 1 *%R.
Lemma pi_is_monoid_morphism : monoid_morphism \pi_Q.
Proof. by split; do ?move=> x y /=; rewrite !piE. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `pi_is_monoid_morphism` instead")]
Definition pi_is_multiplicative :=
(fun g => (g.2,g.1)) pi_is_monoid_morphism.
HB.instance Definition _ := GRing.isMonoidMorphism.Build R Q \pi_Q
pi_is_monoid_morphism.
End PiRMorphism.
HB.mixin Record isUnitRingQuotient T eqT zeroT oppT addT oneT mulT (unitT : pred T) (invT : T -> T)
(Q : Type) of NzRingQuotient T eqT zeroT oppT addT oneT mulT Q & GRing.UnitRing Q :=
{
pi_unitr : {mono \pi_Q : x / unitT x >-> x \in GRing.unit};
pi_invr : {morph \pi_Q : x / invT x >-> x^-1}
}.
#[short(type="unitRingQuotType")]
HB.structure Definition UnitRingQuotient T eqT zeroT oppT addT oneT mulT unitT invT :=
{Q of isUnitRingQuotient T eqT zeroT oppT addT oneT mulT unitT invT Q & GRing.UnitRing Q & isQuotient T Q & isEqQuotient T eqT Q & isZmodQuotient T eqT zeroT oppT addT Q & isNzRingQuotient T eqT zeroT oppT addT oneT mulT Q}.
Section UnitRingQuot.
Variable (T : Type).
Variable eqT : rel T.
Variables (zeroT : T) (oppT : T -> T) (addT : T -> T -> T).
Variables (oneT : T) (mulT : T -> T -> T).
Variables (unitT : pred T) (invT : T -> T).
Implicit Type urqT : UnitRingQuotient.type eqT zeroT oppT addT oneT mulT unitT invT.
Canonical pi_unit_quot_morph urqT := PiMono1 (@pi_unitr _ _ _ _ _ _ _ _ _ urqT).
Canonical pi_inv_quot_morph urqT := PiMorph1 (@pi_invr _ _ _ _ _ _ _ _ _ urqT).
End UnitRingQuot.
Definition proper_ideal (R : nzRingType) (S : {pred R}) : Prop :=
1 \notin S /\ forall a, {in S, forall u, a * u \in S}.
Definition prime_idealr_closed (R : nzRingType) (S : {pred R}) : Prop :=
forall u v, u * v \in S -> (u \in S) || (v \in S).
Definition idealr_closed (R : nzRingType) (S : {pred R}) :=
[/\ 0 \in S, 1 \notin S & forall a, {in S &, forall u v, a * u + v \in S}].
Lemma idealr_closed_nontrivial R S : @idealr_closed R S -> proper_ideal S.
Proof. by case=> S0 S1 hS; split => // a x xS; rewrite -[_ * _]addr0 hS. Qed.
Lemma idealr_closedB R S : @idealr_closed R S -> zmod_closed S.
Proof. by case=> S0 _ hS; split=> // x y xS yS; rewrite -mulN1r addrC hS. Qed.
HB.mixin Record isProperIdeal (R : nzRingType) (S : R -> bool) := {
proper_ideal_subproof : proper_ideal S
}.
#[short(type="proper_ideal")]
HB.structure Definition ProperIdeal R := {S of isProperIdeal R S}.
#[short(type="idealr")]
HB.structure Definition Idealr (R : nzRingType) :=
{S of GRing.ZmodClosed R S & ProperIdeal R S}.
HB.mixin Record isPrimeIdealrClosed (R : nzRingType) (S : R -> bool) := {
prime_idealr_closed_subproof : prime_idealr_closed S
}.
#[short(type="prime_idealr")]
HB.structure Definition PrimeIdealr (R : nzRingType) :=
{S of Idealr R S & isPrimeIdealrClosed R S}.
HB.factory Record isIdealr (R : nzRingType) (S : R -> bool) := {
idealr_closed_subproof : idealr_closed S
}.
HB.builders Context R S of isIdealr R S.
HB.instance Definition _ := GRing.isZmodClosed.Build R S
(idealr_closedB idealr_closed_subproof).
HB.instance Definition _ := isProperIdeal.Build R S
(idealr_closed_nontrivial idealr_closed_subproof).
HB.end.
Section IdealTheory.
Variables (R : nzRingType) (idealrI : idealr R).
Local Notation I := (idealrI : pred R).
Lemma idealr1 : 1 \in I = false.
Proof. apply: negPf; exact: proper_ideal_subproof.1. Qed.
Lemma idealMr a u : u \in I -> a * u \in I.
Proof. exact: proper_ideal_subproof.2. Qed.
Lemma idealr0 : 0 \in I. Proof. exact: rpred0. Qed.
End IdealTheory.
Section PrimeIdealTheory.
Variables (R : comNzRingType) (pidealI : prime_idealr R).
Local Notation I := (pidealI : pred R).
Lemma prime_idealrM u v : (u * v \in I) = (u \in I) || (v \in I).
Proof.
apply/idP/idP; last by case/orP => /idealMr hI; rewrite // mulrC.
exact: prime_idealr_closed_subproof.
Qed.
End PrimeIdealTheory.
Module Quotient.
Section ZmodQuotient.
Variables (R : zmodType) (I : zmodClosed R).
Definition equiv (x y : R) := (x - y) \in I.
Lemma equivE x y : (equiv x y) = (x - y \in I). Proof. by []. Qed.
Lemma equiv_is_equiv : equiv_class_of equiv.
Proof.
split=> [x|x y|y x z]; rewrite !equivE ?subrr ?rpred0 //.
by rewrite -opprB rpredN.
by move=> *; rewrite -[x](addrNK y) -addrA rpredD.
Qed.
Canonical equiv_equiv := EquivRelPack equiv_is_equiv.
Canonical equiv_encModRel := defaultEncModRel equiv.
Definition quot := {eq_quot equiv}.
#[export]
HB.instance Definition _ : EqQuotient R equiv quot := EqQuotient.on quot.
#[export]
HB.instance Definition _ := Choice.on quot.
Lemma idealrBE x y : (x - y) \in I = (x == y %[mod quot]).
Proof. by rewrite piE equivE. Qed.
Lemma idealrDE x y : (x + y) \in I = (x == - y %[mod quot]).
Proof. by rewrite -idealrBE opprK. Qed.
Definition zero : quot := lift_cst quot 0.
Definition add := lift_op2 quot +%R.
Definition opp := lift_op1 quot -%R.
Canonical pi_zero_morph := PiConst zero.
Lemma pi_opp : {morph \pi : x / - x >-> opp x}.
Proof.
move=> x; unlock opp; apply/eqP; rewrite piE equivE.
by rewrite -opprD rpredN idealrDE opprK reprK.
Qed.
Canonical pi_opp_morph := PiMorph1 pi_opp.
Lemma pi_add : {morph \pi : x y / x + y >-> add x y}.
Proof.
move=> x y /=; unlock add; apply/eqP; rewrite piE equivE.
rewrite opprD addrAC addrA -addrA.
by rewrite rpredD // (idealrBE, idealrDE) ?pi_opp ?reprK.
Qed.
Canonical pi_add_morph := PiMorph2 pi_add.
Lemma addqA: associative add.
Proof. by move=> x y z; rewrite -[x]reprK -[y]reprK -[z]reprK !piE addrA. Qed.
Lemma addqC: commutative add.
Proof. by move=> x y; rewrite -[x]reprK -[y]reprK !piE addrC. Qed.
Lemma add0q: left_id zero add.
Proof. by move=> x; rewrite -[x]reprK !piE add0r. Qed.
Lemma addNq: left_inverse zero opp add.
Proof. by move=> x; rewrite -[x]reprK !piE addNr. Qed.
#[export]
HB.instance Definition _ := GRing.isZmodule.Build quot addqA addqC add0q addNq.
#[export]
HB.instance Definition _ := @isZmodQuotient.Build R equiv 0 -%R +%R quot
(lock _) pi_opp pi_add.
End ZmodQuotient.
Arguments quot R%_type I%_type.
Notation "{ 'quot' I }" := (quot I) : type_scope.
Section RingQuotient.
Variables (R : comNzRingType) (idealI : idealr R).
Local Notation I := (idealI : pred R).
Definition one : {quot idealI} := lift_cst {quot idealI} 1.
Definition mul := lift_op2 {quot idealI} *%R.
Canonical pi_one_morph := PiConst one.
Lemma pi_mul: {morph \pi : x y / x * y >-> mul x y}.
Proof.
move=> x y; unlock mul; apply/eqP; rewrite piE equivE.
rewrite -[_ * _](addrNK (x * repr (\pi_{quot idealI} y))) -mulrBr.
rewrite -addrA -mulrBl rpredD //.
by rewrite idealMr // idealrDE opprK reprK.
by rewrite mulrC idealMr // idealrDE opprK reprK.
Qed.
Canonical pi_mul_morph := PiMorph2 pi_mul.
Lemma mulqA: associative mul.
Proof. by move=> x y z; rewrite -[x]reprK -[y]reprK -[z]reprK !piE mulrA. Qed.
Lemma mulqC: commutative mul.
Proof. by move=> x y; rewrite -[x]reprK -[y]reprK !piE mulrC. Qed.
Lemma mul1q: left_id one mul.
Proof. by move=> x; rewrite -[x]reprK !piE mul1r. Qed.
Lemma mulq_addl: left_distributive mul +%R.
Proof.
move=> x y z; rewrite -[x]reprK -[y]reprK -[z]reprK.
by apply/eqP; rewrite piE /= mulrDl equiv_refl.
Qed.
Lemma nonzero1q: one != 0.
Proof. by rewrite piE equivE subr0 idealr1. Qed.
#[export]
HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build (quot idealI)
mulqA mulqC mul1q mulq_addl nonzero1q.
#[export]
HB.instance Definition _ := @isNzRingQuotient.Build
R (equiv idealI) 0 -%R +%R 1%R *%R (quot idealI) (lock _) pi_mul.
End RingQuotient.
Section IDomainQuotient.
Variables (R : comNzRingType) (I : prime_idealr R).
Lemma rquot_IdomainAxiom (x y : {quot I}): x * y = 0 -> (x == 0) || (y == 0).
Proof.
by move=> /eqP; rewrite -[x]reprK -[y]reprK !piE !equivE !subr0 prime_idealrM.
Qed.
End IDomainQuotient.
Module Exports. HB.reexport. End Exports.
End Quotient.
Export Quotient.Exports.
Notation "{ 'ideal_quot' I }" := (@Quotient.quot _ I) : type_scope.
Notation "x == y %[ 'mod_ideal' I ]" :=
(x == y %[mod {ideal_quot I}]) : quotient_scope.
Notation "x = y %[ 'mod_ideal' I ]" :=
(x = y %[mod {ideal_quot I}]) : quotient_scope.
Notation "x != y %[ 'mod_ideal' I ]" :=
(x != y %[mod {ideal_quot I}]) : quotient_scope.
Notation "x <> y %[ 'mod_ideal' I ]" :=
(x <> y %[mod {ideal_quot I}]) : quotient_scope.
|
ChevalleyComplexity.lean
|
/-
Copyright (c) 2025 Yaël Dillies, Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Andrew Yang
-/
import Mathlib.Algebra.Order.SuccPred.WithBot
import Mathlib.Algebra.Polynomial.CoeffMem
import Mathlib.Data.DFinsupp.WellFounded
import Mathlib.RingTheory.Spectrum.Prime.ConstructibleSet
import Mathlib.RingTheory.Spectrum.Prime.Polynomial
/-!
# Chevalley's theorem with complexity bound
⚠ For general usage, see `Mathlib/RingTheory/Spectrum/Prime/Chevalley.lean`.
Chevalley's theorem states that if `f : R → S` is a finitely presented ring hom between commutative
rings, then the image of a constructible set in `Spec S` is a constructible set in `Spec R`.
Constructible sets in the prime spectrum of `R[X]` are made of closed sets in the prime spectrum
(using unions, intersections, and complements), which are themselves made from a family of
polynomials.
We say a closed set *has complexity at most `M`* if it can be written as the zero locus of a family
of at most `M` polynomials each of degree at most `M`. We say a constructible set *has complexity
at most `M`* if it can be written as `(C₁ ∪ ... ∪ Cₖ) \ D` where `k ≤ M`, `C₁, ..., Cₖ` are closed
sets of complexity at most `M` and `D` is a closed set.
This file proves a complexity-aware version of Chevalley's theorem, namely that a constructible set
of complexity at most `M` in `Spec R[X₁, ..., Xₘ]` gets mapped under
`f : R[Y₁, ..., Yₙ] → R[X₁, ..., Xₘ]` to a constructible set of complexity `O_{M, m, n}(1)` in
`Spec R[Y₁, ..., Yₙ]`.
The bound `O_{M, m, n}(1)` we find is of tower type.
## Sketch proof
We first show the result in the case of `C : R → R[X]`. We prove this by induction on the number of
components of the form `(C₁ ∪ ... ∪ Cₖ) \ D`, then by induction again on the number of polynomials
used to describe `(C₁ ∪ ... ∪ Cₖ)`. See the (private) lemma `chevalley_polynomialC`.
Secondly, we prove the result in the case of `C : R → R[X₁, ..., Xₘ]` by composing the first result
with itself `m` times. See the (private) lemma `chevalley_mvPolynomialC`.
Note that, if composing the first result for `C : R → R[X₁]` and `C : R[X₁] → R[X₁, X₂]` naïvely,
the second map `C : R[X₁] → R[X₁, X₂]` won't *see* the `X₁`-degree of the polynomials used to
describe the constructible set in `Spec R[X₁]`. One therefore needs to track a subgroup of the ring
which all coefficients of all used polynomials lie in.
Finally, we deduce the result for any `f : R[Y₁, ..., Yₙ] → R[X₁, ..., Xₘ]` by decomposing it into
two maps `C : R[Y₁, ..., Yₙ] → R[X₁, ..., Xₘ, Y₁, ..., Yₙ]` and
`σ : R[X₁, ..., Xₘ, Y₁, ..., Yₙ] → R[X₁, ..., Xₘ]`. See `chevalley_mvPolynomial_mvPolynomial`.
## Main reference
The structure of the proof follows https://stacks.math.columbia.edu/tag/00FE, although they do
not give an explicit bound on the complexity.
-/
variable {R₀ R S M A : Type*} [CommRing R₀] [CommRing R] [Algebra R₀ R] [CommRing S] [Algebra R₀ S]
variable [AddCommGroup M] [Module R M] [CommRing A] [Algebra R A] {n : ℕ}
open Function Localization MvPolynomial Polynomial TensorProduct PrimeSpectrum
open scoped Pointwise
namespace ChevalleyThm
/-! ### The `C : R → R[X]` case -/
namespace PolynomialC
local notation3 "coeff("p")" => Set.range (Polynomial.coeff p)
variable (n) in
/-- The codomain of the measure that will decrease during the induction in the `C : R → R[X]` case
of Chevalley's theorem with complexity bound. -/
private abbrev DegreeType := (Fin n → WithBot ℕ) ×ₗ Prop
variable (R n) in
/-- A type synonym for families of polynomials. This is used in the induction for the case of
`C : R → R[X]` of Chevalley's theorem with complexity bound. -/
@[ext]
private structure InductionObj where
/-- The underlying family of polynomials of an induction object. -/
val : Fin n → R[X]
namespace InductionObj
private instance : CoeFun (InductionObj R n) (fun _ ↦ Fin n → R[X]) := ⟨InductionObj.val⟩
variable (R₀) in
/-- A subgroup containing all coefficients of all polynomials of a given induction object for
Chevalley's theorem with complexity.
Note that we force `1` to lie in that subgroup so that `fun n ↦ e.coeffSubmodule ^ n` is
increasing. -/
private def coeffSubmodule (e : InductionObj R n) : Submodule R₀ R :=
.span R₀ ({1} ∪ ⋃ i, coeff(e i))
private lemma coeffSubmodule_mapRingHom_comp (e : InductionObj R n) (f : R →ₐ[R₀] S) :
({ val := mapRingHom f ∘ e } : InductionObj S n).coeffSubmodule R₀
= (e.coeffSubmodule R₀).map f.toLinearMap := by
simp [coeffSubmodule, Submodule.map_span, Set.image_insert_eq, Set.image_iUnion, ← Set.range_comp,
coeff_map_eq_comp]
variable {e T : InductionObj R n}
private lemma coeff_mem_coeffSubmodule {i : Fin n} {d : ℕ} :
(e i).coeff d ∈ e.coeffSubmodule R₀ :=
Submodule.subset_span <| .inr <| Set.mem_iUnion.2 ⟨i, Set.mem_range_self _⟩
private lemma one_mem_coeffSubmodule : 1 ∈ e.coeffSubmodule R₀ := Submodule.subset_span (.inl rfl)
private lemma one_le_coeffSubmodule : 1 ≤ e.coeffSubmodule R₀ := by
rw [Submodule.one_eq_span, Submodule.span_le, Set.singleton_subset_iff]
exact one_mem_coeffSubmodule
variable (e) in
/-- The measure that will decrease during the induction in the `C : R → R[X]` case of
Chevalley's theorem with complexity bound. -/
private def degree : DegreeType n :=
toLex (Polynomial.degree ∘ e, ¬ ∃ i, (e i).Monic ∧ ∀ j, e j ≠ 0 → (e i).degree ≤ (e j).degree)
@[simp] private lemma ofLex_degree_fst (i) : (ofLex e.degree).fst i = (e i).degree := rfl
private lemma ofLex_degree_snd :
(ofLex e.degree).snd ↔
¬ ∃ i, (e i).Monic ∧ ∀ j, e j ≠ 0 → (e i).degree ≤ (e j).degree := .rfl
variable (e) in
/-- The bound on the degree of the polynomials used to describe the constructible set appearing in
the case of `C : R → R[X]` of Chevalley's theorem with complexity bound. -/
private def degBound : ℕ := ∑ i, (e i).degree.succ
variable (e) in
/-- The bound on the power of the subgroup generated by the coefficients of the polynomials used to
describe the constructible set appearing in the case of `C : R → R[X]` of Chevalley's theorem with
complexity bound. -/
private def powBound : ℕ := e.degBound ^ e.degBound
private lemma powBound_ne_zero : e.powBound ≠ 0 := Nat.pow_self_pos.ne'
variable (R₀ R n e) in
/-- The statement we induct on in the `C : R → R[X]` case of Chevalley's theorem with complexity
bound. -/
private def Statement [Algebra ℤ R] : Prop :=
∀ f : R[X], ∃ T : ConstructibleSetData R,
comap Polynomial.C '' (zeroLocus (Set.range e) \ zeroLocus {f}) = T.toSet ∧
∀ C ∈ T, C.n ≤ e.degBound ∧ ∀ i, C.g i ∈ e.coeffSubmodule R₀ ^ e.powBound
end InductionObj
open InductionObj
universe u
/--
The structure of the induction in the proof of Chevalley's theorem:
Consider a property on a vector `e` of polynomials. Suppose that it holds for the following cases:
1. The vector contains zeroes only.
2. The vector contains a single monic polynomial (and zero otherwise).
3. Suppose `eᵢ` has the lowest degree among all monic polynomials and `eⱼ` is some other polynomial.
If the property holds when `eⱼ` is replaced by `eⱼ % eᵢ`, then it holds for `e`.
4. Suppose the property holds for both the localization at some leading coefficient of `eᵢ` and
the localization at the leading coefficient of `eᵢ`, then the property holds for `e`.
Then it holds for all vectors `e` over all rings.
-/
private lemma induction_structure (n : ℕ)
(P : ∀ (R : Type u) [CommRing R], (InductionObj R n) → Prop)
(hP₁ : ∀ (R) [CommRing R], P R ⟨0⟩)
(hP₂ : ∀ (R) [CommRing R] (e : InductionObj R n) (i : Fin n),
(e.1 i).Monic → (∀ j ≠ i, e.1 j = 0) → P R e)
(hP₃ : ∀ (R) [CommRing R] (e : InductionObj R n) (i j : Fin n),
(e.1 i).Monic → (e.1 i).degree ≤ (e.1 j).degree → i ≠ j →
P R ⟨update e.1 j (e.1 j %ₘ e.1 i)⟩ → P R e)
(hP₄ : ∀ (R) [CommRing R] (c : R) (i : Fin n) (e : InductionObj R n), c = (e.1 i).leadingCoeff →
c ≠ 0 →
P (Away c) ⟨Polynomial.C (IsLocalization.Away.invSelf (S := Away c) c) •
mapRingHom (algebraMap _ _) ∘ e⟩ →
P (R ⧸ Ideal.span {c}) ⟨mapRingHom (algebraMap _ _) ∘ e⟩ → P R e)
{R} [CommRing R] (e : InductionObj R n) : P R e := by
classical
set v := e.degree with hv
clear_value v
induction v using WellFoundedLT.induction generalizing R with
| ind v H_IH =>
by_cases he0 : e = ⟨0⟩
· exact he0 ▸ hP₁ R
cases subsingleton_or_nontrivial R
· convert hP₁ R; ext; exact Subsingleton.elim _ _
simp only [InductionObj.ext_iff, funext_iff, Pi.zero_apply, not_forall] at he0
-- Case I : The `e i ≠ 0` with minimal degree has invertible leading coefficient
by_cases H : (∃ i, (e.1 i).Monic ∧ ∀ j, e.1 j ≠ 0 → (e.1 i).degree ≤ (e.1 j).degree)
· obtain ⟨i, hi, i_min⟩ := H
-- Case I.ii : `e j = 0` for all `j ≠ i`.
by_cases H' : ∀ j ≠ i, e.1 j = 0
-- then `I = Ideal.span {e i}`
· exact hP₂ R e i hi H'
-- Case I.i : There is another `e j ≠ 0`
· simp only [ne_eq, not_forall] at H'
obtain ⟨j, hj, hj'⟩ := H'
replace i_min := i_min j hj'
-- then we can replace `e j` with `e j %ₘ (C h.unit⁻¹ * e i) `
-- with `h : IsUnit (e i).leadingCoeff`.
apply hP₃ R e i j hi i_min (.symm hj) (H_IH _ ?_ _ rfl)
refine .left _ _ (lt_of_le_of_ne (b := (ofLex v).1) ?_ ?_)
· intro k
simp only [comp_apply, update_apply, hv]
split_ifs with hjk
· rw [hjk]
exact (degree_modByMonic_le _ hi).trans i_min
· exact le_rfl
· simp only [hv, ne_eq, not_forall, funext_iff,
comp_apply]
use j
simp only [update_self]
refine ((degree_modByMonic_lt _ hi).trans_le i_min).ne
-- Case II : The `e i ≠ 0` with minimal degree has non-invertible leading coefficient
obtain ⟨i, hi, i_min⟩ : ∃ i, e.1 i ≠ 0 ∧ ∀ j, e.1 j ≠ 0 → (e.1 i).degree ≤ (e.1 j).degree := by
have : ∃ n : ℕ, ∃ i, (e.1 i).degree = n ∧ (e.1 i) ≠ 0 := by
obtain ⟨i, hi⟩ := he0; exact ⟨(e.1 i).natDegree, i, degree_eq_natDegree hi, hi⟩
let m := Nat.find this
obtain ⟨i, hi, hi'⟩ : ∃ i, (e.1 i).degree = m ∧ (e.1 i) ≠ 0 := Nat.find_spec this
refine ⟨i, hi', fun j hj ↦ ?_⟩
refine hi.le.trans ?_
rw [degree_eq_natDegree hj, Nat.cast_le]
exact Nat.find_min' _ ⟨j, degree_eq_natDegree hj, hj⟩
-- We replace `R` by `R ⧸ Ideal.span {(e i).leadingCoeff}` where `(e i).degree` is lowered
-- and `Away (e i).leadingCoeff` where `(e i).leadingCoeff` becomes invertible.
apply hP₄ _ _ i e rfl (by simpa using hi) (H_IH _ ?_ _ rfl) (H_IH _ ?_ _ rfl)
· rw [hv, Prod.Lex.lt_iff']
constructor
· intro j
simp only [coe_mapRingHom, InductionObj.ofLex_degree_fst, Pi.smul_apply,
comp_apply, smul_eq_mul]
refine ((degree_mul_le _ _).trans (add_le_add degree_C_le degree_map_le)).trans ?_
simp
rw [lt_iff_le_not_ge]
simp only [coe_mapRingHom, funext_iff, InductionObj.ofLex_degree_fst, Pi.smul_apply,
comp_apply, smul_eq_mul, show (ofLex e.degree).2 from H,
le_Prop_eq, implies_true, true_implies, true_and]
simp only [InductionObj.ofLex_degree_snd, Pi.smul_apply, comp_apply, smul_eq_mul,
ne_eq, not_exists, not_and, not_forall, not_le, not_lt]
intro h_eq
refine ⟨i, ?_, ?_⟩
· rw [Monic.def, ← coeff_natDegree (p := _ * _), natDegree_eq_of_degree_eq (h_eq i),
Polynomial.coeff_C_mul, Polynomial.coeff_map, coeff_natDegree, mul_comm,
IsLocalization.Away.mul_invSelf]
· intro j hj; rw [h_eq, h_eq]; exact i_min j fun H ↦ (by simp [H] at hj)
· rw [hv]
refine .left _ _ (lt_of_le_of_ne ?_ ?_)
· intro j; simpa using degree_map_le
simp only [coe_mapRingHom, ne_eq]
intro h_eq
replace h_eq := congr_fun h_eq i
simp only [Ideal.Quotient.algebraMap_eq, comp_apply, degree_map_eq_iff,
Ideal.Quotient.mk_singleton_self, ne_eq, not_true_eq_false, false_or] at h_eq
exact hi h_eq
open IsLocalization in
open Submodule hiding comap in
/-- Part 4 of the induction structure applied to `Statement R₀ R n`. See the docstring of
`induction_structure`. -/
private lemma induction_aux (R : Type*) [CommRing R] [Algebra R₀ R]
(c : R) (i : Fin n) (e : InductionObj R n) (hi : c = (e.1 i).leadingCoeff) (hc : c ≠ 0) :
Statement R₀ (Away c) n
⟨Polynomial.C (IsLocalization.Away.invSelf (S := Away c) c) •
mapRingHom (algebraMap _ _) ∘ e⟩ →
Statement R₀ (R ⧸ Ideal.span {c}) n ⟨mapRingHom (algebraMap _ _) ∘ e⟩ →
Statement R₀ R n e := by
set q₁ := IsScalarTower.toAlgHom R₀ R (Away c)
set q₂ := Ideal.Quotient.mkₐ R₀ (.span {c})
have q₂_surjective : Surjective q₂ := Ideal.Quotient.mk_surjective
set e₁ : InductionObj (Away c) n :=
⟨Polynomial.C (IsLocalization.Away.invSelf (S := Away c) c) • mapRingHom q₁ ∘ e⟩
set e₂ : InductionObj (R ⧸ Ideal.span {c}) n := ⟨mapRingHom q₂ ∘ e⟩
have degBound_e₁_le : e₁.degBound ≤ e.degBound := by
unfold degBound
gcongr with j
exact (degree_mul_le _ _).trans <| (add_le_of_nonpos_left degree_C_le).trans degree_map_le
have degBound_e₂_lt : e₂.degBound < e.degBound := by
unfold degBound
refine Fintype.sum_strictMono <| Pi.lt_def.2 ⟨fun j ↦ ?_, i, ?_⟩
· dsimp
gcongr
exact degree_map_le
· gcongr
exact degree_map_lt (by simp [q₂, ← hi]) (by simpa [hi] using hc)
intro (H₁ : Statement R₀ _ _ e₁) (H₂ : Statement R₀ _ _ e₂) f
obtain ⟨T₁, hT₁⟩ := H₁ (mapRingHom q₁ f)
obtain ⟨T₂, hT₂⟩ := H₂ (mapRingHom q₂ f)
simp only [forall_and] at hT₁ hT₂
obtain ⟨hT₁, hT₁deg, hT₁span⟩ := hT₁
obtain ⟨hT₂, hT₂deg, hT₂span⟩ := hT₂
-- Lift the tuples of `T₁` from `Away c` to `R`
let _ : Invertible (q₁ c) :=
-- TODO(Andrew): add API for `IsLocalization.Away.invSelf`
⟨IsLocalization.Away.invSelf c, by simp [q₁, IsLocalization.Away.invSelf], by
simp [q₁, IsLocalization.Away.invSelf]⟩
have he₁span :
e₁.coeffSubmodule R₀ ^ e₁.powBound = ⅟(q₁ c ^ e₁.powBound) •
(span R₀ ({c} ∪ ⋃ i, coeff(e i)) ^ e₁.powBound).map q₁.toLinearMap := by
unfold coeffSubmodule
rw [Submodule.map_pow, map_span, invOf_pow, ← smul_pow, ← span_smul]
simp [Set.image_insert_eq, Set.smul_set_insert, Set.image_iUnion, Set.smul_set_iUnion, q₁, e₁]
congr! with i
change _ = IsLocalization.Away.invSelf c • _
simp [← Set.range_comp, Set.smul_set_range]
ext
simp
replace hT₁span x hx i :=
smul_mem_pointwise_smul _ (q₁ c ^ e₁.powBound) _ (hT₁span x hx i)
simp only [he₁span, smul_invOf_smul, smul_eq_mul] at hT₁span
choose! g₁ hg₁ hq₁g₁ using hT₁span
-- Lift the constants of `T₁` from `Away c` to `R`
choose! n₁ f₁ hf₁ using Away.surj (S := Away c) c
change (∀ _, _ * q₁ _ ^ _ = q₁ _) at hf₁
-- Lift the tuples of `T₂` from `R ⧸ Ideal.span {c}` to `R`
rw [coeffSubmodule_mapRingHom_comp, ← Submodule.map_pow] at hT₂span
choose! g₂ hg₂ hq₂g₂ using hT₂span
-- Lift the constants of `T₂` from `R ⧸ Ideal.span {c}` to `R`
choose! f₂ hf₂ using Ideal.Quotient.mkₐ_surjective R₀ (I := .span {c})
change (∀ _, q₂ _ = _) at hf₂
-- Lift everything together
classical
let S₁ : Finset (BasicConstructibleSetData R) := T₁.image fun x ↦ ⟨c * f₁ x.f, _, g₁ x⟩
let S₂ : Finset (BasicConstructibleSetData R) := T₂.image fun x ↦ ⟨f₂ x.f, _, Fin.cons c (g₂ x)⟩
refine ⟨S₁ ∪ S₂, ?_, ?_⟩
· calc
comap Polynomial.C '' (zeroLocus (.range e) \ zeroLocus {f})
= comap q₁ '' (comap Polynomial.C ''
(comap (mapRingHom q₁.toRingHom) ⁻¹' (zeroLocus (.range e) \ zeroLocus {f}))) ∪
comap q₂ '' (comap Polynomial.C ''
(comap (mapRingHom q₂.toRingHom) ⁻¹' (zeroLocus (.range e) \ zeroLocus {f}))) :=
Set.image_of_range_union_range_eq_univ (by ext; simp) (by ext; simp)
(by rw [Ideal.Quotient.mkₐ_toRingHom,
← range_comap_algebraMap_localization_compl_eq_range_comap_quotientMk,
RingHom.algebraMap_toAlgebra]; exact Set.union_compl_self _) _
_ = (⋃ C ∈ S₁, C.toSet) ∪ ⋃ C ∈ S₂, C.toSet := ?_
_ = ⋃ C ∈ S₁ ∪ S₂, C.toSet := by
simpa using (Set.biUnion_union S₁.toSet S₂.toSet _).symm
congr 1
· convert congr(comap q₁.toRingHom '' $hT₁)
· dsimp only [e₁]
rw [Set.preimage_diff, preimage_comap_zeroLocus, preimage_comap_zeroLocus,
Set.image_singleton, Pi.smul_def, ← Set.smul_set_range, Set.range_comp]
congr 1
refine (PrimeSpectrum.zeroLocus_smul_of_isUnit (.map _ ?_) _).symm
exact isUnit_iff_exists_inv'.mpr ⟨_, IsLocalization.Away.mul_invSelf c⟩
· rw [ConstructibleSetData.toSet, Set.image_iUnion₂]
simp_rw [← Finset.mem_coe, S₁, Finset.coe_image, Set.biUnion_image]
congr! with x hxT₁
apply Set.injOn_preimage subset_rfl (f := comap q₁.toRingHom)
· dsimp only [q₁, AlgHom.toRingHom_eq_coe]
rw [IsScalarTower.coe_toAlgHom,
localization_away_comap_range (S := Localization.Away c) (r := c),
BasicConstructibleSetData.toSet, sdiff_eq, ← basicOpen_eq_zeroLocus_compl,
basicOpen_mul]
exact Set.inter_subset_right.trans Set.inter_subset_left
· exact Set.image_subset_range ..
· rw [BasicConstructibleSetData.toSet, BasicConstructibleSetData.toSet, Set.preimage_diff,
preimage_comap_zeroLocus, preimage_comap_zeroLocus, Set.preimage_image_eq]
swap; · exact localization_specComap_injective _ (.powers c)
simp only [AlgHom.toLinearMap_apply] at hq₁g₁
simp only [← Set.range_comp, comp_def, AlgHom.toRingHom_eq_coe, RingHom.coe_coe,
hq₁g₁ _ hxT₁, Set.image_singleton, map_mul, ← hf₁, mul_comm x.1, ← mul_assoc,
← pow_succ']
simp only [← smul_eq_mul, ← Set.smul_set_range, ← Set.smul_set_singleton,
zeroLocus_smul_of_isUnit ((isUnit_of_invertible (q₁ c)).pow _)]
· convert congr(comap q₂.toRingHom '' $hT₂)
· rw [Set.preimage_diff, preimage_comap_zeroLocus, preimage_comap_zeroLocus,
Set.image_singleton, Set.range_comp, AlgHom.toRingHom_eq_coe]
· rw [ConstructibleSetData.toSet, Set.image_iUnion₂]
simp_rw [← Finset.mem_coe, S₂, Finset.coe_image, Set.biUnion_image]
congr! 3 with x hxT₂
apply Set.injOn_preimage subset_rfl (f := comap q₂.toRingHom)
· rw [range_comap_of_surjective _ _ q₂_surjective]
simp only [AlgHom.toRingHom_eq_coe, Ideal.Quotient.mkₐ_ker, zeroLocus_span, q₂]
exact Set.diff_subset.trans (zeroLocus_anti_mono (by simp))
· exact Set.image_subset_range _ _
· simp only [AlgHom.toLinearMap_apply] at hq₂g₂
have : q₂ c = 0 := by simp [q₂]
simp only [BasicConstructibleSetData.toSet, Set.preimage_diff, preimage_comap_zeroLocus,
preimage_comap_zeroLocus,
Set.preimage_image_eq _ (comap_injective_of_surjective _ q₂_surjective)]
simp only [Fin.range_cons, Set.image_singleton, Set.image_insert_eq,
← Set.range_comp, comp_def]
simp only [AlgHom.toRingHom_eq_coe, AlgHom.coe_toRingHom, hq₂g₂ _ hxT₂, hf₂]
rw [← Set.union_singleton, zeroLocus_union,
this, zeroLocus_singleton_zero, Set.inter_univ]
· simp only [Finset.mem_union, forall_and, or_imp, Finset.forall_mem_image, S₁, S₂]
refine ⟨⟨fun x hx ↦ (hT₁deg _ hx).trans degBound_e₁_le,
fun x hx ↦ (hT₂deg _ hx).trans_lt degBound_e₂_lt⟩,
fun x hx k ↦ SetLike.mem_of_subset ?_ (hg₁ _ hx _),
fun x hx ↦ Fin.cons ?_ fun k ↦ SetLike.mem_of_subset ?_ (hg₂ _ hx _)⟩
· norm_cast
calc
span R₀ ({c} ∪ ⋃ i, coeff(e i)) ^ e₁.powBound
_ ≤ span R₀ (⋃ i, coeff(e i)) ^ e₁.powBound := by
gcongr; simpa [Set.insert_subset_iff] using ⟨_, _, hi.symm⟩
_ ≤ e.coeffSubmodule R₀ ^ e.powBound := by
unfold coeffSubmodule powBound
gcongr
· exact one_le_coeffSubmodule
· exact Set.subset_union_right
· omega
· exact le_self_pow one_le_coeffSubmodule powBound_ne_zero <| subset_span <| .inr <| by
simpa using ⟨_, _, hi.symm⟩
· unfold powBound
gcongr
· exact one_le_coeffSubmodule
· omega
/-- The main induction in the proof of Chevalley's theorem for `R →+* R[X]`.
See the docstring of `induction_structure` for the overview. -/
private lemma statement : ∀ S : InductionObj R n, Statement R₀ R n S := by
intro S; revert R₀; revert S
classical
apply induction_structure
· intro R _ R₀ _ _ f
refine ⟨(Finset.range (f.natDegree + 2)).image fun j ↦ ⟨f.coeff j, 0, 0⟩, ?_, ?_⟩
· convert image_comap_C_basicOpen f
· simp only [basicOpen_eq_zeroLocus_compl, Set.compl_eq_univ_diff]
congr 1
rw [← Set.univ_subset_iff]
rintro x _ _ ⟨_, rfl⟩
exact zero_mem x.asIdeal
· suffices Set.range f.coeff = ⋃ i < f.natDegree + 2, {f.coeff i} by
simp [BasicConstructibleSetData.toSet, ConstructibleSetData.toSet,
← Set.compl_eq_univ_diff, eq_compl_comm (y := zeroLocus _), ← zeroLocus_iUnion₂, this]
trans f.coeff '' (Set.Iio (f.natDegree + 2))
· refine ((Set.image_subset_range _ _).antisymm ?_).symm
rintro _ ⟨i, rfl⟩
by_cases hi : i ≤ f.natDegree
· exact ⟨i, hi.trans_lt (by simp), rfl⟩
· exact ⟨f.natDegree + 1, by simp,
by simp [f.coeff_eq_zero_of_natDegree_lt (lt_of_not_ge hi)]⟩
· ext; simp [eq_comm]
· simp
· intros R _ g i hi hi_min _ R₀ _ f
let M := R[X] ⧸ Ideal.span {g.1 i}
have : Module.Free R M := .of_basis (AdjoinRoot.powerBasis' hi).basis
have : Module.Finite R M := .of_basis (AdjoinRoot.powerBasis' hi).basis
refine ⟨(Finset.range (Module.finrank R M)).image
fun j ↦ ⟨(Algebra.lmul R M (Ideal.Quotient.mk _ f)).charpoly.coeff j, 0, 0⟩, ?_, ?_⟩
· ext x
have : zeroLocus (Set.range g.val) = zeroLocus {g.1 i} := by
rw [Set.range_eq_iUnion, zeroLocus_iUnion]
refine (Set.iInter_subset _ _).antisymm (Set.subset_iInter fun j ↦ ?_)
by_cases hij : i = j
· subst hij; rfl
· rw [hi_min j (.symm hij), zeroLocus_singleton_zero]; exact Set.subset_univ _
rw [this, ← Polynomial.algebraMap_eq, mem_image_comap_zeroLocus_sdiff,
IsScalarTower.algebraMap_apply R[X] M, isNilpotent_tensor_residueField_iff]
simp [BasicConstructibleSetData.toSet, ConstructibleSetData.toSet, Set.subset_def, M]
· simp
· intro R _ c i j hi hle hne H R₀ _ _ f
cases subsingleton_or_nontrivial R
· use ∅
simp [ConstructibleSetData.toSet, Subsingleton.elim f 0]
obtain ⟨S, hS, hS'⟩ := H (R₀ := R₀) f
refine ⟨S, Eq.trans ?_ hS, ?_⟩
· rw [← zeroLocus_span (Set.range _), ← zeroLocus_span (Set.range _),
idealSpan_range_update_divByMonic hne _ hi]
· intro C hC
let c' : InductionObj _ _ := ⟨update c.val j (c.val j %ₘ c.val i)⟩
have deg_bound₁ : c'.degBound ≤ c.degBound := by
dsimp [InductionObj.degBound, c']
gcongr with k
· rw [update_apply]
split_ifs with hkj
· subst hkj; exact (degree_modByMonic_le _ hi).trans hle
· rfl
refine ⟨(hS' C hC).1.trans deg_bound₁, fun k ↦ SetLike.le_def.mp ?_ ((hS' C hC).2 k)⟩
change c'.coeffSubmodule R₀ ^ c'.powBound ≤ _
delta powBound
suffices hij : c'.coeffSubmodule R₀ ≤ c.coeffSubmodule R₀ ^ (c.val j).degree.succ by
by_cases hi' : c.val i = 1
· gcongr
· exact c.one_le_coeffSubmodule
· refine Submodule.span_le.mpr (Set.union_subset ?_ ?_)
· exact Set.subset_union_left.trans Submodule.subset_span
· refine Set.iUnion_subset fun k ↦ ?_
simp only [update_apply, hi', modByMonic_one, c']
split_ifs
· rintro _ ⟨_, rfl⟩
exact zero_mem _
· exact (Set.subset_iUnion (fun i ↦ coeff(c.val i)) k).trans
(Set.subset_union_right.trans Submodule.subset_span)
rw [Nat.one_le_iff_ne_zero, ← Nat.pos_iff_ne_zero, InductionObj.degBound]
refine Fintype.sum_pos (Pi.lt_def.mpr ⟨by positivity, i, by simp [hi']⟩)
refine (pow_le_pow_left' hij _).trans ?_
rw [← pow_mul]
apply pow_le_pow_right' c.one_le_coeffSubmodule
have deg_bound₂ : c'.degBound < c.degBound := by
dsimp [InductionObj.degBound, c']
apply Finset.sum_lt_sum ?_ ⟨j, Finset.mem_univ _, ?_⟩
· intro k _
rw [update_apply]
split_ifs with hkj
· subst hkj; gcongr; exact (degree_modByMonic_le _ hi).trans hle
· rfl
· gcongr; simpa using (degree_modByMonic_lt _ hi).trans_le hle
calc (c.val j).degree.succ * c'.degBound ^ c'.degBound
_ ≤ c.degBound * c.degBound ^ c'.degBound := by
gcongr
delta InductionObj.degBound
exact Finset.single_le_sum (f := fun i ↦ (c.val i).degree.succ)
(by intros; positivity) (Finset.mem_univ _)
_ = c.degBound ^ (c'.degBound + 1) := by rw [pow_succ']
_ ≤ c.degBound ^ c.degBound := by gcongr <;> omega
rw [coeffSubmodule]
simp only [Submodule.span_le, Set.union_subset_iff, Set.singleton_subset_iff, SetLike.mem_coe,
Set.iUnion_subset_iff, Set.range_subset_iff, c']
constructor
· apply one_le_pow_of_one_le' c.one_le_coeffSubmodule
rw [Submodule.one_eq_span]
exact Submodule.subset_span rfl
· intro l m
rw [update_apply]
split_ifs with hlj
· convert coeff_modByMonic_mem_pow_natDegree_mul _ _ _ (fun _ ↦ coeff_mem_coeffSubmodule)
one_mem_coeffSubmodule _ (fun _ ↦ coeff_mem_coeffSubmodule) one_mem_coeffSubmodule _
rw [← pow_succ, Polynomial.degree_eq_natDegree, WithBot.succ_natCast, Nat.cast_id]
intro e
simp [show c.val i = 0 by simpa [e] using hle] at hi
· have : (c.val j).degree.succ ≠ 0 := by
rw [← Nat.pos_iff_ne_zero]
apply WithBot.succ_lt_succ (x := ⊥)
refine lt_of_lt_of_le ?_ hle
rw [bot_lt_iff_ne_bot, ne_eq, degree_eq_bot]
intro e
simp [e] at hi
refine le_self_pow c.one_le_coeffSubmodule this ?_
exact Submodule.subset_span (.inr (Set.mem_iUnion_of_mem l ⟨m, rfl⟩))
· intro R _ c i e he hc H₁ H₂ R₀ _ _
exact induction_aux (R₀ := R₀) R c i e he hc H₁ H₂
end PolynomialC
open PolynomialC InductionObj in
/-- The `C : R → R[X]` case of **Chevalley's theorem** with complexity bound. -/
lemma chevalley_polynomialC {R : Type*} [CommRing R] (M : Submodule ℤ R) (hM : 1 ∈ M)
(S : ConstructibleSetData R[X]) (hS : ∀ C ∈ S, ∀ j k, (C.g j).coeff k ∈ M) :
∃ T : ConstructibleSetData R,
comap Polynomial.C '' S.toSet = T.toSet ∧ ∀ C ∈ T, C.n ≤ S.degBound ∧
∀ i, C.g i ∈ M ^ S.degBound ^ S.degBound := by
classical
choose f hf₁ hf₂ hf₃ using fun C : BasicConstructibleSetData R[X] ↦ statement (R₀ := ℤ) ⟨C.g⟩ C.f
refine ⟨S.biUnion f, ?_, ?_⟩
· simp only [BasicConstructibleSetData.toSet, ConstructibleSetData.toSet, Set.image_iUnion,
Finset.set_biUnion_biUnion, hf₁]
· simp only [Finset.mem_biUnion, forall_exists_index, and_imp]
intros x y hy hx
have H : degBound ⟨y.g⟩ ≤ S.degBound :=
Finset.le_sup (f := fun e ↦ ∑ i, (e.g i).degree.succ) hy
refine ⟨(hf₂ y x hx).trans H, fun i ↦ SetLike.le_def.mp ?_ (hf₃ y x hx i)⟩
gcongr
· simpa [Submodule.one_eq_span]
· refine Submodule.span_le.mpr ?_
simp [Set.subset_def, hM, forall_comm (α := R), hS y hy]
· delta powBound
by_cases h : S.degBound = 0
· have : degBound ⟨y.g⟩ = 0 := by nlinarith
rw [h, this]
gcongr
rwa [Nat.one_le_iff_ne_zero]
/-! ### The `C : R → R[X₁, ..., Xₘ]` case -/
namespace MvPolynomialC
mutual
/-- The bound on the number of polynomials used to describe the constructible set appearing in the
case of `C : R → R[X₁, ..., Xₘ]` of Chevalley's theorem with complexity bound. -/
def numBound (k : ℕ) (D : ℕ → ℕ) : ℕ → ℕ
| 0 => k
| n + 1 => numBound k D n * degBound k D n * D n
/-- The bound on the degree of the polynomials used to describe the constructible set appearing in
the case of `C : R → R[X₁, ..., Xₘ]` of Chevalley's theorem with complexity bound. -/
def degBound (k : ℕ) (D : ℕ → ℕ) : ℕ → ℕ
| 0 => 1
| n + 1 => numBound k D (n + 1) ^ numBound k D (n + 1) * degBound k D n
end
@[simp] lemma degBound_zero (k : ℕ) (D : ℕ → ℕ) : degBound k D 0 = 1 := by rw [degBound]
@[simp] lemma numBound_zero (k : ℕ) (D : ℕ → ℕ) : numBound k D 0 = k := by rw [numBound]
@[simp]
lemma degBound_succ (k : ℕ) (D : ℕ → ℕ) (n) :
degBound k D (n + 1) = numBound k D (n + 1) ^ numBound k D (n + 1) * degBound k D n := by
rw [degBound]
@[simp]
lemma numBound_succ (k : ℕ) (D : ℕ → ℕ) (n) :
numBound k D (n + 1) = numBound k D n * degBound k D n * D n := by
rw [numBound]
mutual
lemma degBound_casesOn_succ (k₀ k : ℕ) (D : ℕ → ℕ) :
∀ n, degBound k₀ (fun t ↦ Nat.casesOn t k D) (n + 1) =
(k₀ * k) ^ (k₀ * k) * degBound (k₀ * k) ((k₀ * k) ^ (k₀ * k) • D) n
| 0 => by simp
| n + 1 => by
rw [degBound_succ, numBound_casesOn_succ, degBound_casesOn_succ, numBound_succ, degBound_succ,
numBound_succ]
ring
lemma numBound_casesOn_succ (k₀ k : ℕ) (D : ℕ → ℕ) :
∀ n, numBound k₀ (Nat.casesOn · k D) (n + 1) = numBound (k₀ * k) ((k₀ * k) ^ (k₀ * k) • D) n
| 0 => by simp
| n + 1 => by
rw [numBound_succ (n := n + 1), numBound_casesOn_succ k₀ k D n, numBound_succ,
degBound_casesOn_succ]
dsimp
ring
end
variable {k₁ k₂ : ℕ} (hk : k₁ ≤ k₂) {D₁ D₂ : ℕ → ℕ}
mutual
lemma degBound_le_degBound (hk : k₁ ≤ k₂) :
∀ (n) (_ : ∀ i < n, D₁ i ≤ D₂ i), degBound k₁ D₁ n ≤ degBound k₂ D₂ n
| 0, hD => by simp
| n + 1, hD => by
rw [degBound_succ, degBound_succ]
refine Nat.mul_le_mul (Nat.pow_self_mono (numBound_mono hk _ hD)) (degBound_le_degBound hk _
fun i hi ↦ hD _ (hi.trans n.lt_succ_self))
lemma numBound_mono (hk : k₁ ≤ k₂) :
∀ n, (∀ i < n, D₁ i ≤ D₂ i) → numBound k₁ D₁ n ≤ numBound k₂ D₂ n
| 0, hD => by simpa using hk
| n + 1, hD => by
rw [numBound_succ, numBound_succ]
gcongr
· exact numBound_mono hk _ fun i hi ↦ hD _ (hi.trans n.lt_succ_self)
· exact degBound_le_degBound hk _ fun i hi ↦ hD _ (hi.trans n.lt_succ_self)
· exact hD _ n.lt_succ_self
end
lemma degBound_pos (k : ℕ) (D : ℕ → ℕ) : ∀ n, 0 < degBound k D n
| 0 => by simp
| n + 1 => by simp [degBound_succ, Nat.pow_self_pos, degBound_pos]
end MvPolynomialC
open MvPolynomialC in
/-- The `C : R → R[X₁, ..., Xₘ]` case of **Chevalley's theorem** with complexity bound. -/
lemma chevalley_mvPolynomialC
{M : Submodule ℤ R} (hM : 1 ∈ M) (k : ℕ) (d : Multiset (Fin n))
(S : ConstructibleSetData (MvPolynomial (Fin n) R))
(hSn : ∀ C ∈ S, C.n ≤ k)
(hS : ∀ C ∈ S, ∀ j, C.g j ∈ coeffsIn _ M ⊓ (degreesLE _ _ d).restrictScalars _) :
∃ T : ConstructibleSetData R,
comap MvPolynomial.C '' S.toSet = T.toSet ∧
∀ C ∈ T, C.n ≤ numBound k (fun i ↦ 1 + (d.map Fin.val).count i) n ∧
∀ i, C.g i ∈ M ^ (degBound k (fun i ↦ 1 + (d.map Fin.val).count i) n) := by
classical
induction' n with n IH generalizing k M
· refine ⟨(S.map (isEmptyRingEquiv _ _).toRingHom), ?_, ?_⟩
· rw [ConstructibleSetData.toSet_map]
change _ = (comapEquiv (isEmptyRingEquiv _ _)).symm ⁻¹' _
rw [← OrderIso.image_eq_preimage]
rfl
· simp only [ConstructibleSetData.map, RingEquiv.toRingHom_eq_coe, Finset.mem_image, comp_apply,
BasicConstructibleSetData.map, RingHom.coe_coe, isEmptyRingEquiv_eq_coeff_zero, pow_one,
numBound_zero, degBound_zero, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂]
exact fun a haS ↦ ⟨hSn a haS, fun i ↦ (hS a haS i).1 0⟩
let e : MvPolynomial (Fin (n + 1)) R ≃ₐ[R] (MvPolynomial (Fin n) R)[X] := finSuccEquiv R n
let S' := S.map e.toRingHom
have hS' : S'.degBound ≤ k * (1 + d.count 0) := by
apply Finset.sup_le fun x hxS ↦ ?_
simp only [ConstructibleSetData.map, AlgEquiv.toRingEquiv_eq_coe, RingEquiv.toRingHom_eq_coe,
AlgEquiv.toRingEquiv_toRingHom, Finset.mem_image, BasicConstructibleSetData.map,
RingHom.coe_coe, S'] at hxS
obtain ⟨C, hxS, rfl⟩ := hxS
trans ∑ i : Fin C.n, (1 + d.count 0)
· gcongr with j hj
simp only [e, comp_apply]
by_cases hgj : C.g j = 0
· rw [hgj, map_zero]
simp
rw [degree_finSuccEquiv hgj, WithBot.succ_natCast, add_comm]
simp only [Nat.cast_id, add_le_add_iff_left, degreeOf_def]
exact Multiset.count_le_of_le _ (hS _ hxS _).2
· simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul]
gcongr
exact hSn _ hxS
let B : Multiset (Fin n) :=
(d.toFinsupp.comapDomain Fin.succ (Fin.succ_injective _).injOn).toMultiset
obtain ⟨T, hT₁, hT₂⟩ := chevalley_polynomialC
(R := MvPolynomial (Fin n) R)
(coeffsIn _ M ⊓ (degreesLE _ _ B).restrictScalars ℤ)
(by simpa [MvPolynomial.coeff_one, apply_ite] using hM)
S' (fun x hxS j k ↦ by
simp only [ConstructibleSetData.map, AlgEquiv.toRingEquiv_eq_coe,
RingEquiv.toRingHom_eq_coe, AlgEquiv.toRingEquiv_toRingHom, Finset.mem_image,
BasicConstructibleSetData.map, RingHom.coe_coe, S', e] at hxS
obtain ⟨C, hxS, rfl⟩ := hxS
simp only [comp_apply, Submodule.mem_inf, mem_coeffsIn, Submodule.restrictScalars_mem,
mem_degreesLE]
constructor
· intro d
simp only [finSuccEquiv_coeff_coeff]
exact (hS _ hxS _).1 _
· simp only [B]
replace hS := (hS _ hxS j).2
simp only [Submodule.coe_restrictScalars, SetLike.mem_coe, mem_degreesLE,
Multiset.le_iff_count, Finsupp.count_toMultiset, Finsupp.comapDomain_apply,
Multiset.toFinsupp_apply, ← degreeOf_def] at hS ⊢
intro a
exact (degreeOf_coeff_finSuccEquiv (C.g j) a k).trans (hS _))
let N := (k * (1 + d.count 0)) ^ (k * (1 + d.count 0))
have (C) (hCT : C ∈ T) (a) : C.g a ∈ coeffsIn (Fin n) (M ^ N) ⊓
(degreesLE R (Fin n) (N • B)).restrictScalars ℤ := by
refine SetLike.le_def.mp ?_ ((hT₂ C hCT).2 a)
refine pow_inf_le.trans (inf_le_inf ?_ ?_)
· refine (pow_le_pow_right' ?_ (Nat.pow_self_mono hS')).trans le_coeffsIn_pow
simpa [MvPolynomial.coeff_one, apply_ite] using hM
· rw [degreesLE_nsmul, Submodule.restrictScalars_pow Nat.pow_self_pos.ne']
refine pow_le_pow_right' ?_ (Nat.pow_self_mono hS')
simp
have h1M : 1 ≤ M := Submodule.one_le.mpr hM
obtain ⟨U, hU₁, hU₂⟩ := IH (M := M ^ N)
(SetLike.le_def.mp (le_self_pow h1M Nat.pow_self_pos.ne') hM) _ _ T
(fun C hCT ↦ (hT₂ C hCT).1)
(fun C hCT k ↦ this C hCT k)
simp only [Multiset.map_nsmul, Multiset.count_nsmul, ← pow_mul, N] at hU₂
have : ∀ i < n + 1, i.casesOn (1 + d.count 0) (1 + (B.map Fin.val).count ·) ≤
1 + (d.map Fin.val).count i := by
intro t ht
change _ ≤ 1 + (d.map Fin.val).count (Fin.mk t ht).val
rw [Multiset.count_map_eq_count' _ _ Fin.val_injective]
obtain - | t := t
· exact le_rfl
· simp only [add_lt_add_iff_right] at ht
change 1 + (B.map Fin.val).count (Fin.mk t ht).val ≤ _
rw [Multiset.count_map_eq_count' _ _ Fin.val_injective]
simp [B]
refine ⟨U, ?_, fun C hCU ↦ ⟨(hU₂ C hCU).1.trans ?_,
fun i ↦ pow_le_pow_right' h1M ?_ <| (hU₂ C hCU).2 i⟩⟩
· unfold S' at hT₁
rw [← hU₁, ← hT₁, ← Set.image_comp, ← ContinuousMap.coe_comp, ← comap_comp,
ConstructibleSetData.toSet_map]
change _ = _ '' ((comapEquiv e.toRingEquiv).symm ⁻¹' _)
rw [← OrderIso.image_eq_preimage, Set.image_image]
simp only [comapEquiv_apply, ← comap_apply, ← comap_comp_apply]
congr!
exact e.symm.toAlgHom.comp_algebraMap.symm
· refine (numBound_mono hS' _ fun _ _ ↦ ?_).trans
((numBound_casesOn_succ k _ _ _).symm.trans_le (numBound_mono le_rfl _ this))
simp +contextual [mul_add, Nat.one_le_iff_ne_zero]
· refine (Nat.mul_le_mul le_rfl (degBound_le_degBound hS' _ fun _ _ ↦ ?_)).trans
((degBound_casesOn_succ k _ _ _).symm.trans_le (degBound_le_degBound le_rfl _ this))
simp +contextual [mul_add, Nat.one_le_iff_ne_zero]
/-! ### The general `f : R[Y₁, ..., Yₙ] → R[X₁, ..., Xₘ]` case -/
/-- The bound on the number of polynomials used to describe the constructible set appearing in
Chevalley's theorem with complexity bound. -/
def numBound (k m n : ℕ) (d : Multiset (Fin m)) : ℕ :=
MvPolynomialC.numBound (k + n) (1 + (d.map Fin.val).count ·) m
/-- The bound on the degree of the polynomials used to describe the constructible set appearing in
Chevalley's theorem with complexity bound. -/
def degBound (k m n : ℕ) (d : Multiset (Fin m)) : ℕ :=
MvPolynomialC.degBound (k + n) (1 + (d.map Fin.val).count ·) m
end ChevalleyThm
open ChevalleyThm
/-- **Chevalley's theorem** with complexity bound.
A constructible set of complexity at most `M` in `Spec R[X₁, ..., Xₘ]` gets mapped under
`f : R[Y₁, ..., Yₙ] → R[X₁, ..., Xₘ]` to a constructible set of complexity `O_{M, m, n}(1)` in
`Spec R[Y₁, ..., Yₙ]`.
See the module doc of `Mathlib/RingTheory/Spectrum/Prime/ChevalleyComplexity.lean` for an
explanation of this notion of complexity. -/
lemma chevalley_mvPolynomial_mvPolynomial
{m n : ℕ} (f : MvPolynomial (Fin n) R →ₐ[R] MvPolynomial (Fin m) R)
(k : ℕ) (d : Multiset (Fin m))
(S : ConstructibleSetData (MvPolynomial (Fin m) R))
(hSn : ∀ C ∈ S, C.n ≤ k)
(hS : ∀ C ∈ S, ∀ j, (C.g j).degrees ≤ d)
(hf : ∀ i, (f (.X i)).degrees ≤ d) :
∃ T : ConstructibleSetData (MvPolynomial (Fin n) R),
comap f '' S.toSet = T.toSet ∧
∀ C ∈ T, C.n ≤ numBound k m n d ∧ ∀ i j, (C.g i).degreeOf j ≤ degBound k m n d := by
classical
let g : MvPolynomial (Fin m) (MvPolynomial (Fin n) R) →+* MvPolynomial (Fin m) R :=
eval₂Hom f.toRingHom X
have hg : g.comp (algebraMap (MvPolynomial (Fin n) R) _) = f := by ext x : 2 <;> simp [g]
let σ : MvPolynomial (Fin m) R →+* MvPolynomial (Fin m) (MvPolynomial (Fin n) R) :=
map (algebraMap _ _)
have hσ : g.comp σ = .id _ := by ext : 2 <;> simp [g, σ]
have hσ' (x) : g (σ x) = x := DFunLike.congr_fun hσ x
have hg' : Surjective g := LeftInverse.surjective hσ'
let S' : ConstructibleSetData (MvPolynomial (Fin m) (MvPolynomial (Fin n) R)) := S.image
fun ⟨fk, k, gk⟩ ↦ ⟨σ fk, k + n, fun s ↦ (finSumFinEquiv.symm s).elim (σ ∘ gk)
fun i ↦ .C (.X i) - σ (f (.X i))⟩
let s₀ : Set (MvPolynomial (Fin m) (MvPolynomial (Fin n) R)) :=
.range fun i ↦ .C (.X i) - σ (f (.X i))
have hs : zeroLocus s₀ = Set.range (comap g) := by
rw [range_comap_of_surjective _ _ hg', ← zeroLocus_span]
congr! 2
have H : Ideal.span s₀ ≤ RingHom.ker g := by
simp only [Ideal.span_le, Set.range_subset_iff, SetLike.mem_coe, RingHom.mem_ker, map_sub,
hσ', s₀]
simp [g]
refine H.antisymm fun p hp ↦ ?_
obtain ⟨q₁, q₂, hq₁, rfl⟩ : ∃ q₁ q₂, q₁ ∈ Ideal.span s₀ ∧ p = q₁ + σ q₂ := by
clear hp
obtain ⟨p, rfl⟩ := (commAlgEquiv _ _ _).surjective p
simp_rw [← (commAlgEquiv R (Fin n) (Fin m)).symm.injective.eq_iff,
AlgEquiv.symm_apply_apply]
induction p using MvPolynomial.induction_on with
| C q =>
exact ⟨0, q, by simp, (commAlgEquiv _ _ _).injective <|
by simp [commAlgEquiv_C, σ]⟩
| add p q hp hq =>
obtain ⟨q₁, q₂, hq₁, rfl⟩ := hp
obtain ⟨q₃, q₄, hq₃, rfl⟩ := hq
refine ⟨q₁ + q₃, q₂ + q₄, add_mem hq₁ hq₃, by simp only [map_add, add_add_add_comm]⟩
| mul_X p i hp =>
obtain ⟨q₁, q₂, hq₁, rfl⟩ := hp
simp only [← (commAlgEquiv R (Fin n) (Fin m)).injective.eq_iff,
map_mul, AlgEquiv.apply_symm_apply, commAlgEquiv_X]
refine ⟨q₁ * .C (.X i) + σ q₂ * (.C (.X i) - σ (f (.X i))), q₂ * f (.X i), ?_, ?_⟩
· exact add_mem (Ideal.mul_mem_right _ _ hq₁)
(Ideal.mul_mem_left _ _ (Ideal.subset_span (Set.mem_range_self _)))
· simp; ring
obtain rfl : q₂ = 0 := by simpa [hσ', show g q₁ = 0 from H hq₁] using hp
simpa using hq₁
have hg'' (t) : comap g '' t = comap σ ⁻¹' t ∩ zeroLocus s₀ := by
refine Set.injOn_preimage (f := comap g) .rfl ?_ ?_ ?_
· simp
· simp [hs]
· rw [Set.preimage_image_eq _ (comap_injective_of_surjective g hg'),
Set.preimage_inter, hs, Set.preimage_range, Set.inter_univ,
← Set.preimage_comp, ← ContinuousMap.coe_comp, ← comap_comp, hσ]
simp only [comap_id, ContinuousMap.coe_id, Set.preimage_id_eq, id_eq]
have hS' : comap g '' S.toSet = S'.toSet := by
simp only [S', BasicConstructibleSetData.toSet, ConstructibleSetData.toSet, Set.image_iUnion₂,
Finset.set_biUnion_finset_image, ← comp_def (g := finSumFinEquiv.symm), Set.range_comp,
Equiv.range_eq_univ, Set.image_univ, Set.Sum.elim_range,
Set.image_diff (hf := comap_injective_of_surjective g hg'), zeroLocus_union]
simp [hg'', ← Set.inter_diff_distrib_right, Set.sdiff_inter_right_comm, s₀]
obtain ⟨T, hT, hT'⟩ :=
chevalley_mvPolynomialC
(M := (degreesLE R (Fin n) Finset.univ.1).restrictScalars ℤ) (by simp) (k + n) d S'
(Finset.forall_mem_image.mpr fun x hx ↦ (by simpa using hSn _ hx))
(Finset.forall_mem_image.mpr fun x hx ↦ by
intro j
obtain ⟨j, rfl⟩ := finSumFinEquiv.surjective j
simp only [Equiv.symm_apply_apply, Submodule.mem_inf, mem_coeffsIn,
Submodule.restrictScalars_mem, mem_degreesLE]
constructor
· intro i
obtain j | j := j
· simp [σ, MvPolynomial.coeff_map, degrees_C]
· simp only [MvPolynomial.algebraMap_eq, Sum.elim_inr, MvPolynomial.coeff_sub,
MvPolynomial.coeff_C, MvPolynomial.coeff_map, σ]
refine degrees_sub_le.trans ?_
simp only [degrees_C, apply_ite, degrees_zero,
Multiset.union_zero]
split_ifs with h
· refine (degrees_X' _).trans ?_
simp
· simp
· obtain j | j := j
· simp only [MvPolynomial.algebraMap_eq, Sum.elim_inl, comp_apply, σ]
exact degrees_map_le.trans (hS _ hx j)
· refine degrees_sub_le.trans ?_
simp only [degrees_C, Multiset.zero_union]
exact degrees_map_le.trans (hf _))
refine ⟨T, ?_, fun C hCT ↦ ⟨(hT' C hCT).1, fun i j ↦ ?_⟩⟩
· rwa [← hg, comap_comp, ContinuousMap.coe_comp, Set.image_comp, hS']
· have := (hT' C hCT).2 i
rw [← Submodule.restrictScalars_pow (MvPolynomialC.degBound_pos ..).ne', ← degreesLE_nsmul,
Submodule.restrictScalars_mem, mem_degreesLE,
Multiset.le_iff_count] at this
simpa only [Multiset.count_nsmul, Multiset.count_univ, mul_one, ← degreeOf_def]
using this j
|
DegLex.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.Algebra.Group.TransferInstance
import Mathlib.Data.Finsupp.MonomialOrder
import Mathlib.Data.Finsupp.Weight
/-! Homogeneous lexicographic monomial ordering
* `MonomialOrder.degLex`: a variant of the lexicographic ordering that first compares degrees.
For this, `σ` needs to be embedded with an ordering relation which satisfies `WellFoundedGT σ`.
(This last property is automatic when `σ` is finite).
The type synonym is `DegLex (σ →₀ ℕ)` and the two lemmas `MonomialOrder.degLex_le_iff`
and `MonomialOrder.degLex_lt_iff` rewrite the ordering as comparisons in the type `Lex (σ →₀ ℕ)`.
## References
* [Cox, Little and O'Shea, *Ideals, varieties, and algorithms*][coxlittleoshea1997]
* [Becker and Weispfenning, *Gröbner bases*][Becker-Weispfenning1993]
-/
/-- A type synonym to equip a type with its lexicographic order sorted by degrees. -/
def DegLex (α : Type*) := α
variable {α : Type*}
/-- `toDegLex` is the identity function to the `DegLex` of a type. -/
@[match_pattern] def toDegLex : α ≃ DegLex α := Equiv.refl _
theorem toDegLex_injective : Function.Injective (toDegLex (α := α)) := fun _ _ ↦ _root_.id
theorem toDegLex_inj {a b : α} : toDegLex a = toDegLex b ↔ a = b := Iff.rfl
/-- `ofDegLex` is the identity function from the `DegLex` of a type. -/
@[match_pattern] def ofDegLex : DegLex α ≃ α := Equiv.refl _
theorem ofDegLex_injective : Function.Injective (ofDegLex (α := α)) := fun _ _ ↦ _root_.id
theorem ofDegLex_inj {a b : DegLex α} : ofDegLex a = ofDegLex b ↔ a = b := Iff.rfl
@[simp] theorem ofDegLex_symm_eq : (@ofDegLex α).symm = toDegLex := rfl
@[simp] theorem toDegLex_symm_eq : (@toDegLex α).symm = ofDegLex := rfl
@[simp] theorem ofDegLex_toDegLex (a : α) : ofDegLex (toDegLex a) = a := rfl
@[simp] theorem toDegLex_ofDegLex (a : DegLex α) : toDegLex (ofDegLex a) = a := rfl
/-- A recursor for `DegLex`. Use as `induction x`. -/
@[elab_as_elim, induction_eliminator, cases_eliminator]
protected def DegLex.rec {β : DegLex α → Sort*} (h : ∀ a, β (toDegLex a)) :
∀ a, β a := fun a => h (ofDegLex a)
@[simp] lemma DegLex.forall_iff {p : DegLex α → Prop} : (∀ a, p a) ↔ ∀ a, p (toDegLex a) := Iff.rfl
@[simp] lemma DegLex.exists_iff {p : DegLex α → Prop} : (∃ a, p a) ↔ ∃ a, p (toDegLex a) := Iff.rfl
noncomputable instance [AddCommMonoid α] :
AddCommMonoid (DegLex α) := ofDegLex.addCommMonoid
theorem toDegLex_add [AddCommMonoid α] (a b : α) :
toDegLex (a + b) = toDegLex a + toDegLex b := rfl
theorem ofDegLex_add [AddCommMonoid α] (a b : DegLex α) :
ofDegLex (a + b) = ofDegLex a + ofDegLex b := rfl
namespace Finsupp
open scoped Function in -- required for scoped `on` notation
/-- `Finsupp.DegLex r s` is the homogeneous lexicographic order on `α →₀ M`,
where `α` is ordered by `r` and `M` is ordered by `s`.
The type synonym `DegLex (α →₀ M)` has an order given by `Finsupp.DegLex (· < ·) (· < ·)`. -/
protected def DegLex (r : α → α → Prop) (s : ℕ → ℕ → Prop) :
(α →₀ ℕ) → (α →₀ ℕ) → Prop :=
(Prod.Lex s (Finsupp.Lex r s)) on (fun x ↦ (x.degree, x))
theorem degLex_def {r : α → α → Prop} {s : ℕ → ℕ → Prop} {a b : α →₀ ℕ} :
Finsupp.DegLex r s a b ↔ Prod.Lex s (Finsupp.Lex r s) (a.degree, a) (b.degree, b) :=
Iff.rfl
namespace DegLex
theorem wellFounded
{r : α → α → Prop} [IsTrichotomous α r] (hr : WellFounded (Function.swap r))
{s : ℕ → ℕ → Prop} (hs : WellFounded s) (hs0 : ∀ ⦃n⦄, ¬ s n 0) :
WellFounded (Finsupp.DegLex r s) := by
have wft := WellFounded.prod_lex hs (Finsupp.Lex.wellFounded' hs0 hs hr)
rw [← Set.wellFoundedOn_univ] at wft
unfold Finsupp.DegLex
rw [← Set.wellFoundedOn_range]
exact Set.WellFoundedOn.mono wft (le_refl _) (fun _ _ ↦ trivial)
instance [LT α] : LT (DegLex (α →₀ ℕ)) :=
⟨fun f g ↦ Finsupp.DegLex (· < ·) (· < ·) (ofDegLex f) (ofDegLex g)⟩
theorem lt_def [LT α] {a b : DegLex (α →₀ ℕ)} :
a < b ↔ (toLex ((ofDegLex a).degree, toLex (ofDegLex a))) <
(toLex ((ofDegLex b).degree, toLex (ofDegLex b))) :=
Iff.rfl
theorem lt_iff [LT α] {a b : DegLex (α →₀ ℕ)} :
a < b ↔ (ofDegLex a).degree < (ofDegLex b).degree ∨
(((ofDegLex a).degree = (ofDegLex b).degree) ∧ toLex (ofDegLex a) < toLex (ofDegLex b)) := by
simp [lt_def, Prod.Lex.toLex_lt_toLex]
variable [LinearOrder α]
instance isStrictOrder : IsStrictOrder (DegLex (α →₀ ℕ)) (· < ·) where
irrefl := fun a ↦ by simp [lt_def]
trans := by
intro a b c hab hbc
simp only [lt_iff] at hab hbc ⊢
rcases hab with (hab | hab)
· rcases hbc with (hbc | hbc)
· left; exact lt_trans hab hbc
· left; exact lt_of_lt_of_eq hab hbc.1
· rcases hbc with (hbc | hbc)
· left; exact lt_of_eq_of_lt hab.1 hbc
· right; exact ⟨Eq.trans hab.1 hbc.1, lt_trans hab.2 hbc.2⟩
/-- The linear order on `Finsupp`s obtained by the homogeneous lexicographic ordering. -/
instance : LinearOrder (DegLex (α →₀ ℕ)) :=
LinearOrder.lift'
(fun (f : DegLex (α →₀ ℕ)) ↦ toLex ((ofDegLex f).degree, toLex (ofDegLex f)))
(fun f g ↦ by simp)
theorem le_iff {x y : DegLex (α →₀ ℕ)} :
x ≤ y ↔ (ofDegLex x).degree < (ofDegLex y).degree ∨
(ofDegLex x).degree = (ofDegLex y).degree ∧ toLex (ofDegLex x) ≤ toLex (ofDegLex y) := by
simp only [le_iff_eq_or_lt, lt_iff, EmbeddingLike.apply_eq_iff_eq]
by_cases h : x = y
· simp [h]
· by_cases k : (ofDegLex x).degree < (ofDegLex y).degree
· simp [k]
· simp only [h, k, false_or]
instance : IsOrderedCancelAddMonoid (DegLex (α →₀ ℕ)) where
le_of_add_le_add_left a b c h := by
rw [le_iff] at h ⊢
simpa only [ofDegLex_add, degree_add, add_lt_add_iff_left, add_right_inj, toLex_add,
add_le_add_iff_left] using h
add_le_add_left a b h c := by
rw [le_iff] at h ⊢
simpa [ofDegLex_add, degree_add] using h
theorem single_strictAnti : StrictAnti (fun (a : α) ↦ toDegLex (single a 1)) := by
intro _ _ h
simp only [lt_iff, ofDegLex_toDegLex, degree_single, lt_self_iff_false, Lex.single_lt_iff, h,
and_self, or_true]
theorem single_antitone : Antitone (fun (a : α) ↦ toDegLex (single a 1)) :=
single_strictAnti.antitone
theorem single_lt_iff {a b : α} :
toDegLex (Finsupp.single b 1) < toDegLex (Finsupp.single a 1) ↔ a < b :=
single_strictAnti.lt_iff_gt
theorem single_le_iff {a b : α} :
toDegLex (Finsupp.single b 1) ≤ toDegLex (Finsupp.single a 1) ↔ a ≤ b :=
single_strictAnti.le_iff_ge
theorem monotone_degree :
Monotone (fun (x : DegLex (α →₀ ℕ)) ↦ (ofDegLex x).degree) := by
intro x y
rw [le_iff]
rintro (h | h)
· apply le_of_lt h
· apply le_of_eq h.1
noncomputable instance orderBot : OrderBot (DegLex (α →₀ ℕ)) where
bot := toDegLex (0 : α →₀ ℕ)
bot_le x := by
simp only [le_iff, ofDegLex_toDegLex, toLex_zero, degree_zero]
rcases eq_zero_or_pos (ofDegLex x).degree with (h | h)
· simp only [h, lt_self_iff_false, true_and, false_or]
exact bot_le
· simp [h]
instance wellFoundedLT [WellFoundedGT α] :
WellFoundedLT (DegLex (α →₀ ℕ)) :=
⟨wellFounded wellFounded_gt wellFounded_lt fun n ↦ (zero_le n).not_gt⟩
end DegLex
end Finsupp
namespace MonomialOrder
open Finsupp
variable {σ : Type*} [LinearOrder σ] [WellFoundedGT σ]
/-- The deg-lexicographic order on `σ →₀ ℕ`, as a `MonomialOrder` -/
noncomputable def degLex :
MonomialOrder σ where
syn := DegLex (σ →₀ ℕ)
toSyn := { toEquiv := toDegLex, map_add' := toDegLex_add }
toSyn_monotone a b h := by
simp only [AddEquiv.coe_mk, DegLex.le_iff, ofDegLex_toDegLex]
by_cases ha : a.degree < b.degree
· exact Or.inl ha
· refine Or.inr ⟨le_antisymm ?_ (not_lt.mp ha), toLex_monotone h⟩
rw [← add_tsub_cancel_of_le h, degree_add]
exact Nat.le_add_right a.degree (b - a).degree
theorem degLex_le_iff {a b : σ →₀ ℕ} :
a ≼[degLex] b ↔ toDegLex a ≤ toDegLex b :=
Iff.rfl
theorem degLex_lt_iff {a b : σ →₀ ℕ} :
a ≺[degLex] b ↔ toDegLex a < toDegLex b :=
Iff.rfl
theorem degLex_single_le_iff {a b : σ} :
single a 1 ≼[degLex] single b 1 ↔ b ≤ a := by
rw [MonomialOrder.degLex_le_iff, DegLex.single_le_iff]
theorem degLex_single_lt_iff {a b : σ} :
single a 1 ≺[degLex] single b 1 ↔ b < a := by
rw [MonomialOrder.degLex_lt_iff, DegLex.single_lt_iff]
end MonomialOrder
section Examples
open Finsupp MonomialOrder DegLex
/-- for the deg-lexicographic ordering, X 1 < X 0 -/
example : single (1 : Fin 2) 1 ≺[degLex] single 0 1 := by
rw [degLex_lt_iff, single_lt_iff]
exact Nat.one_pos
/-- for the deg-lexicographic ordering, X 0 * X 1 < X 0 ^ 2 -/
example : (single 0 1 + single 1 1) ≺[degLex] single (0 : Fin 2) 2 := by
simp only [degLex_lt_iff, lt_iff, ofDegLex_toDegLex, degree_add,
degree_single, Nat.reduceAdd, lt_self_iff_false, true_and, false_or]
use 0
simp
/-- for the deg-lexicographic ordering, X 0 < X 1 ^ 2 -/
example : single (0 : Fin 2) 1 ≺[degLex] single 1 2 := by
simp [degLex_lt_iff, lt_iff]
end Examples
|
Opposite.lean
|
/-
Copyright (c) 2018 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison, Reid Barton, Simon Hudon, Kenny Lau
-/
import Mathlib.Logic.Equiv.Defs
import Mathlib.Logic.Small.Defs
/-!
# Opposites
In this file we define a structure `Opposite α` containing a single field of type `α` and
two bijections `op : α → αᵒᵖ` and `unop : αᵒᵖ → α`. If `α` is a category, then `αᵒᵖ` is the
opposite category, with all arrows reversed.
-/
universe v u
-- morphism levels before object levels. See note [CategoryTheory universes].
variable (α : Sort u)
/-- The type of objects of the opposite of `α`; used to define the opposite category.
Now that Lean 4 supports definitional eta equality for records,
both `unop (op X) = X` and `op (unop X) = X` are definitional equalities.
-/
structure Opposite where
/-- The canonical map `α → αᵒᵖ`. -/
op ::
/-- The canonical map `αᵒᵖ → α`. -/
unop : α
attribute [pp_nodot] Opposite.unop
/-- Make sure that `Opposite.op a` is pretty-printed as `op a` instead of `{ unop := a }` or
`⟨a⟩`. -/
@[app_unexpander Opposite.op]
protected def Opposite.unexpander_op : Lean.PrettyPrinter.Unexpander
| s => pure s
@[inherit_doc]
notation:max -- Use a high right binding power (like that of postfix ⁻¹) so that, for example,
-- `Presheaf Cᵒᵖ` parses as `Presheaf (Cᵒᵖ)` and not `(Presheaf C)ᵒᵖ`.
α "ᵒᵖ" => Opposite α
namespace Opposite
variable {α}
theorem op_injective : Function.Injective (op : α → αᵒᵖ) := fun _ _ => congr_arg Opposite.unop
theorem unop_injective : Function.Injective (unop : αᵒᵖ → α) := fun ⟨_⟩⟨_⟩ => by simp
@[simp]
theorem op_unop (x : αᵒᵖ) : op (unop x) = x :=
rfl
theorem unop_op (x : α) : unop (op x) = x :=
rfl
-- We could prove these by `Iff.rfl`, but that would make these eligible for `dsimp`. That would be
-- a bad idea because `Opposite` is irreducible.
theorem op_inj_iff (x y : α) : op x = op y ↔ x = y :=
op_injective.eq_iff
@[simp]
theorem unop_inj_iff (x y : αᵒᵖ) : unop x = unop y ↔ x = y :=
unop_injective.eq_iff
/-- The type-level equivalence between a type and its opposite. -/
def equivToOpposite : α ≃ αᵒᵖ where
toFun := op
invFun := unop
left_inv := unop_op
right_inv := op_unop
theorem op_surjective : Function.Surjective (op : α → αᵒᵖ) := equivToOpposite.surjective
theorem unop_surjective : Function.Surjective (unop : αᵒᵖ → α) := equivToOpposite.symm.surjective
@[simp]
theorem equivToOpposite_coe : (equivToOpposite : α → αᵒᵖ) = op :=
rfl
@[simp]
theorem equivToOpposite_symm_coe : (equivToOpposite.symm : αᵒᵖ → α) = unop :=
rfl
theorem op_eq_iff_eq_unop {x : α} {y} : op x = y ↔ x = unop y :=
equivToOpposite.apply_eq_iff_eq_symm_apply
theorem unop_eq_iff_eq_op {x} {y : α} : unop x = y ↔ x = op y :=
equivToOpposite.symm.apply_eq_iff_eq_symm_apply
instance [Inhabited α] : Inhabited αᵒᵖ :=
⟨op default⟩
instance [Nonempty α] : Nonempty αᵒᵖ := Nonempty.map op ‹_›
instance [Subsingleton α] : Subsingleton αᵒᵖ := unop_injective.subsingleton
/-- A deprecated alias for `Opposite.rec`. -/
@[deprecated Opposite.rec (since := "2025-04-04")]
protected def rec' {F : αᵒᵖ → Sort v} (h : ∀ X, F (op X)) : ∀ X, F X := fun X => h (unop X)
/-- If `X` is `u`-small, also `Xᵒᵖ` is `u`-small.
Note: This is not an instance, because it tends to mislead typeclass search. -/
lemma small {X : Type v} [Small.{u} X] : Small.{u} Xᵒᵖ := by
obtain ⟨S, ⟨e⟩⟩ := Small.equiv_small (α := X)
exact ⟨S, ⟨equivToOpposite.symm.trans e⟩⟩
end Opposite
|
PUnit.lean
|
/-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import Mathlib.Algebra.GCDMonoid.Basic
import Mathlib.Algebra.Ring.PUnit
/-!
# `PUnit` is a GCD monoid
This file collects facts about algebraic structures on the one-element type, e.g. that it is has a
GCD.
-/
namespace PUnit
-- This is too high-powered and should be split off also
instance normalizedGCDMonoid : NormalizedGCDMonoid PUnit where
gcd _ _ := unit
lcm _ _ := unit
normUnit _ := 1
normUnit_zero := rfl
normUnit_mul := by subsingleton
normUnit_coe_units := by subsingleton
gcd_dvd_left _ _ := ⟨unit, by subsingleton⟩
gcd_dvd_right _ _ := ⟨unit, by subsingleton⟩
dvd_gcd {_ _} _ _ _ := ⟨unit, by subsingleton⟩
gcd_mul_lcm _ _ := ⟨1, by subsingleton⟩
lcm_zero_left := by subsingleton
lcm_zero_right := by subsingleton
normalize_gcd := by subsingleton
normalize_lcm := by subsingleton
@[simp]
theorem gcd_eq {x y : PUnit} : gcd x y = unit :=
rfl
@[simp]
theorem lcm_eq {x y : PUnit} : lcm x y = unit :=
rfl
@[simp]
theorem norm_unit_eq {x : PUnit} : normUnit x = 1 :=
rfl
end PUnit
|
Plus.lean
|
/-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import Mathlib.CategoryTheory.Sites.Sheaf
/-!
# The plus construction for presheaves.
This file contains the construction of `P⁺`, for a presheaf `P : Cᵒᵖ ⥤ D`
where `C` is endowed with a grothendieck topology `J`.
See <https://stacks.math.columbia.edu/tag/00W1> for details.
-/
namespace CategoryTheory.GrothendieckTopology
open CategoryTheory
open CategoryTheory.Limits
open Opposite
universe w' w v u
variable {C : Type u} [Category.{v} C] (J : GrothendieckTopology C)
variable {D : Type w} [Category.{w'} D]
noncomputable section
variable [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.Cover X), HasMultiequalizer (S.index P)]
variable (P : Cᵒᵖ ⥤ D)
/-- The diagram whose colimit defines the values of `plus`. -/
@[simps]
def diagram (X : C) : (J.Cover X)ᵒᵖ ⥤ D where
obj S := multiequalizer (S.unop.index P)
map {S _} f :=
Multiequalizer.lift _ _ (fun I => Multiequalizer.ι (S.unop.index P) (I.map f.unop))
(fun I => Multiequalizer.condition (S.unop.index P) (Cover.Relation.mk' (I.r.map f.unop)))
/-- A helper definition used to define the morphisms for `plus`. -/
@[simps]
def diagramPullback {X Y : C} (f : X ⟶ Y) : J.diagram P Y ⟶ (J.pullback f).op ⋙ J.diagram P X where
app S :=
Multiequalizer.lift _ _ (fun I => Multiequalizer.ι (S.unop.index P) I.base) fun I =>
Multiequalizer.condition (S.unop.index P) (Cover.Relation.mk' I.r.base)
naturality S T f := Multiequalizer.hom_ext _ _ _ (fun I => by simp; rfl)
/-- A natural transformation `P ⟶ Q` induces a natural transformation
between diagrams whose colimits define the values of `plus`. -/
@[simps]
def diagramNatTrans {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (X : C) : J.diagram P X ⟶ J.diagram Q X where
app W :=
Multiequalizer.lift _ _ (fun _ => Multiequalizer.ι _ _ ≫ η.app _) (fun i => by
dsimp only
erw [Category.assoc, Category.assoc, ← η.naturality, ← η.naturality,
Multiequalizer.condition_assoc]
rfl)
@[simp]
theorem diagramNatTrans_id (X : C) (P : Cᵒᵖ ⥤ D) :
J.diagramNatTrans (𝟙 P) X = 𝟙 (J.diagram P X) := by
ext : 2
refine Multiequalizer.hom_ext _ _ _ (fun i => ?_)
simp
@[simp]
theorem diagramNatTrans_zero [Preadditive D] (X : C) (P Q : Cᵒᵖ ⥤ D) :
J.diagramNatTrans (0 : P ⟶ Q) X = 0 := by
ext : 2
refine Multiequalizer.hom_ext _ _ _ (fun i => ?_)
simp
@[simp]
theorem diagramNatTrans_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) (X : C) :
J.diagramNatTrans (η ≫ γ) X = J.diagramNatTrans η X ≫ J.diagramNatTrans γ X := by
ext : 2
refine Multiequalizer.hom_ext _ _ _ (fun i => ?_)
simp
variable (D) in
/-- `J.diagram P`, as a functor in `P`. -/
@[simps]
def diagramFunctor (X : C) : (Cᵒᵖ ⥤ D) ⥤ (J.Cover X)ᵒᵖ ⥤ D where
obj P := J.diagram P X
map η := J.diagramNatTrans η X
variable [∀ X : C, HasColimitsOfShape (J.Cover X)ᵒᵖ D]
/-- The plus construction, associating a presheaf to any presheaf.
See `plusFunctor` below for a functorial version. -/
def plusObj : Cᵒᵖ ⥤ D where
obj X := colimit (J.diagram P X.unop)
map f := colimMap (J.diagramPullback P f.unop) ≫ colimit.pre _ _
map_id := by
intro X
refine colimit.hom_ext (fun S => ?_)
dsimp
simp only [diagramPullback_app, colimit.ι_pre, ι_colimMap_assoc, Category.comp_id]
let e := S.unop.pullbackId
dsimp only [Functor.op, pullback_obj]
rw [← colimit.w _ e.inv.op, ← Category.assoc]
convert Category.id_comp (colimit.ι (diagram J P (unop X)) S)
refine Multiequalizer.hom_ext _ _ _ (fun I => ?_)
dsimp
simp only [Multiequalizer.lift_ι, Category.id_comp, Category.assoc]
dsimp [Cover.Arrow.map, Cover.Arrow.base]
cases I
congr
simp
map_comp := by
intro X Y Z f g
refine colimit.hom_ext (fun S => ?_)
dsimp
simp only [diagramPullback_app, colimit.ι_pre_assoc, colimit.ι_pre, ι_colimMap_assoc,
Category.assoc]
let e := S.unop.pullbackComp g.unop f.unop
dsimp only [Functor.op, pullback_obj]
rw [← colimit.w _ e.inv.op, ← Category.assoc, ← Category.assoc]
congr 1
refine Multiequalizer.hom_ext _ _ _ (fun I => ?_)
dsimp
simp only [Multiequalizer.lift_ι, Category.assoc]
cases I
dsimp only [Cover.Arrow.base, Cover.Arrow.map]
congr 2
simp
/-- An auxiliary definition used in `plus` below. -/
def plusMap {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : J.plusObj P ⟶ J.plusObj Q where
app X := colimMap (J.diagramNatTrans η X.unop)
naturality := by
intro X Y f
dsimp [plusObj]
ext
simp only [diagramPullback_app, ι_colimMap, colimit.ι_pre_assoc, colimit.ι_pre,
ι_colimMap_assoc, Category.assoc]
simp_rw [← Category.assoc]
congr 1
exact Multiequalizer.hom_ext _ _ _ (fun I => by simp)
@[simp]
theorem plusMap_id (P : Cᵒᵖ ⥤ D) : J.plusMap (𝟙 P) = 𝟙 _ := by
ext : 2
dsimp only [plusMap, plusObj]
rw [J.diagramNatTrans_id, NatTrans.id_app]
ext
simp
@[simp]
theorem plusMap_zero [Preadditive D] (P Q : Cᵒᵖ ⥤ D) : J.plusMap (0 : P ⟶ Q) = 0 := by
ext : 2
refine colimit.hom_ext (fun S => ?_)
erw [comp_zero, colimit.ι_map, J.diagramNatTrans_zero, zero_comp]
@[simp, reassoc]
theorem plusMap_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) :
J.plusMap (η ≫ γ) = J.plusMap η ≫ J.plusMap γ := by
ext : 2
refine colimit.hom_ext (fun S => ?_)
simp [plusMap, J.diagramNatTrans_comp]
variable (D) in
/-- The plus construction, a functor sending `P` to `J.plusObj P`. -/
@[simps]
def plusFunctor : (Cᵒᵖ ⥤ D) ⥤ Cᵒᵖ ⥤ D where
obj P := J.plusObj P
map η := J.plusMap η
/-- The canonical map from `P` to `J.plusObj P`.
See `toPlusNatTrans` for a functorial version. -/
def toPlus : P ⟶ J.plusObj P where
app X := Cover.toMultiequalizer (⊤ : J.Cover X.unop) P ≫ colimit.ι (J.diagram P X.unop) (op ⊤)
naturality := by
intro X Y f
dsimp [plusObj]
delta Cover.toMultiequalizer
simp only [diagramPullback_app, colimit.ι_pre, ι_colimMap_assoc, Category.assoc]
dsimp only [Functor.op, unop_op]
let e : (J.pullback f.unop).obj ⊤ ⟶ ⊤ := homOfLE (OrderTop.le_top _)
rw [← colimit.w _ e.op, ← Category.assoc, ← Category.assoc, ← Category.assoc]
congr 1
refine Multiequalizer.hom_ext _ _ _ (fun I => ?_)
simp only [Category.assoc]
dsimp [Cover.Arrow.base]
simp
@[reassoc (attr := simp)]
theorem toPlus_naturality {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) :
η ≫ J.toPlus Q = J.toPlus _ ≫ J.plusMap η := by
ext
dsimp [toPlus, plusMap]
delta Cover.toMultiequalizer
simp only [ι_colimMap, Category.assoc]
simp_rw [← Category.assoc]
congr 1
exact Multiequalizer.hom_ext _ _ _ (fun I => by simp)
variable (D) in
/-- The natural transformation from the identity functor to `plus`. -/
@[simps]
def toPlusNatTrans : 𝟭 (Cᵒᵖ ⥤ D) ⟶ J.plusFunctor D where
app P := J.toPlus P
/-- `(P ⟶ P⁺)⁺ = P⁺ ⟶ P⁺⁺` -/
@[simp]
theorem plusMap_toPlus : J.plusMap (J.toPlus P) = J.toPlus (J.plusObj P) := by
ext X : 2
refine colimit.hom_ext (fun S => ?_)
dsimp only [plusMap, toPlus]
let e : S.unop ⟶ ⊤ := homOfLE (OrderTop.le_top _)
rw [ι_colimMap, ← colimit.w _ e.op, ← Category.assoc, ← Category.assoc]
congr 1
refine Multiequalizer.hom_ext _ _ _ (fun I => ?_)
erw [Multiequalizer.lift_ι]
simp only [unop_op, op_unop, diagram_map, Category.assoc, limit.lift_π,
Multifork.ofι_π_app]
let ee : (J.pullback (I.map e).f).obj S.unop ⟶ ⊤ := homOfLE (OrderTop.le_top _)
erw [← colimit.w _ ee.op, ι_colimMap_assoc, colimit.ι_pre, diagramPullback_app,
← Category.assoc, ← Category.assoc]
congr 1
refine Multiequalizer.hom_ext _ _ _ (fun II => ?_)
convert Multiequalizer.condition (S.unop.index P)
{ fst := I, snd := II.base, r.Z := II.Y, r.g₁ := II.f, r.g₂ := 𝟙 II.Y } using 1
all_goals simp
theorem isIso_toPlus_of_isSheaf (hP : Presheaf.IsSheaf J P) : IsIso (J.toPlus P) := by
rw [Presheaf.isSheaf_iff_multiequalizer] at hP
suffices ∀ X, IsIso ((J.toPlus P).app X) from NatIso.isIso_of_isIso_app _
intro X
refine IsIso.comp_isIso' inferInstance ?_
suffices ∀ (S T : (J.Cover X.unop)ᵒᵖ) (f : S ⟶ T), IsIso ((J.diagram P X.unop).map f) from
isIso_ι_of_isInitial (initialOpOfTerminal isTerminalTop) _
intro S T e
have : S.unop.toMultiequalizer P ≫ (J.diagram P X.unop).map e = T.unop.toMultiequalizer P :=
Multiequalizer.hom_ext _ _ _ (fun II => by simp)
have :
(J.diagram P X.unop).map e = inv (S.unop.toMultiequalizer P) ≫ T.unop.toMultiequalizer P := by
simp [← this]
rw [this]
infer_instance
/-- The natural isomorphism between `P` and `P⁺` when `P` is a sheaf. -/
def isoToPlus (hP : Presheaf.IsSheaf J P) : P ≅ J.plusObj P :=
letI := isIso_toPlus_of_isSheaf J P hP
asIso (J.toPlus P)
@[simp]
theorem isoToPlus_hom (hP : Presheaf.IsSheaf J P) : (J.isoToPlus P hP).hom = J.toPlus P :=
rfl
/-- Lift a morphism `P ⟶ Q` to `P⁺ ⟶ Q` when `Q` is a sheaf. -/
def plusLift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : Presheaf.IsSheaf J Q) : J.plusObj P ⟶ Q :=
J.plusMap η ≫ (J.isoToPlus Q hQ).inv
@[reassoc (attr := simp)]
theorem toPlus_plusLift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : Presheaf.IsSheaf J Q) :
J.toPlus P ≫ J.plusLift η hQ = η := by
dsimp [plusLift]
rw [← Category.assoc]
rw [Iso.comp_inv_eq]
dsimp only [isoToPlus, asIso]
rw [toPlus_naturality]
theorem plusLift_unique {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : Presheaf.IsSheaf J Q)
(γ : J.plusObj P ⟶ Q) (hγ : J.toPlus P ≫ γ = η) : γ = J.plusLift η hQ := by
dsimp only [plusLift]
rw [Iso.eq_comp_inv, ← hγ, plusMap_comp]
simp
theorem plus_hom_ext {P Q : Cᵒᵖ ⥤ D} (η γ : J.plusObj P ⟶ Q) (hQ : Presheaf.IsSheaf J Q)
(h : J.toPlus P ≫ η = J.toPlus P ≫ γ) : η = γ := by
have : γ = J.plusLift (J.toPlus P ≫ γ) hQ := by
apply plusLift_unique
rfl
rw [this]
apply plusLift_unique
exact h
@[simp]
theorem isoToPlus_inv (hP : Presheaf.IsSheaf J P) :
(J.isoToPlus P hP).inv = J.plusLift (𝟙 _) hP := by
apply J.plusLift_unique
rw [Iso.comp_inv_eq, Category.id_comp]
rfl
@[simp]
theorem plusMap_plusLift {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) (hR : Presheaf.IsSheaf J R) :
J.plusMap η ≫ J.plusLift γ hR = J.plusLift (η ≫ γ) hR := by
apply J.plusLift_unique
rw [← Category.assoc, ← J.toPlus_naturality, Category.assoc, J.toPlus_plusLift]
instance plusFunctor_preservesZeroMorphisms [Preadditive D] :
(plusFunctor J D).PreservesZeroMorphisms where
map_zero F G := by
ext
dsimp
rw [J.plusMap_zero, NatTrans.app_zero]
end
end CategoryTheory.GrothendieckTopology
|
Born.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.CategoryTheory.ConcreteCategory.Basic
import Mathlib.Topology.Bornology.Hom
/-!
# The category of bornologies
This defines `Born`, the category of bornologies.
-/
universe u
open CategoryTheory
/-- The category of bornologies. -/
structure Born where
/-- The underlying bornology. -/
carrier : Type*
[str : Bornology carrier]
attribute [instance] Born.str
namespace Born
instance : CoeSort Born Type* :=
⟨carrier⟩
/-- Construct a bundled `Born` from a `Bornology`. -/
abbrev of (α : Type*) [Bornology α] : Born where
carrier := α
instance : Inhabited Born :=
⟨of PUnit⟩
instance : LargeCategory.{u} Born where
Hom X Y := LocallyBoundedMap X Y
id X := LocallyBoundedMap.id X
comp f g := g.comp f
instance : ConcreteCategory Born (LocallyBoundedMap · ·) where
hom f := f
ofHom f := f
end Born
|
choice.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.
(******************************************************************************)
(* Types with a choice operator *)
(* *)
(* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *)
(* *)
(* This file contains the definitions of: *)
(* choiceType == interface for types with a choice operator *)
(* The HB class is Choice. *)
(* The exact contents is documented below just before *)
(* hasChoice. *)
(* subChoiceType == interface for types that are both subType and choiceType *)
(* The HB class is SubChoice. *)
(* countType == interface for countable types (implies choiceType) *)
(* The HB class is Countable. *)
(* subCountType == interface for types that are both subType and countType *)
(* The HB class is SubCountable. *)
(* *)
(* xchoose exP == a standard x such that P x, given exP : exists x : T, P x *)
(* when T is a choiceType *)
(* The choice depends only on the extent of P (in particular,*)
(* it is independent of exP). *)
(* choose P x0 == if P x0, a standard x such that P x *)
(* pickle x == a nat encoding the value x : T, where T is a countType *)
(* unpickle n == a partial inverse to pickle: unpickle (pickle x) = Some x *)
(* pickle_inv n == a sharp partial inverse to pickle pickle_inv n = Some x *)
(* if and only if pickle x = n *)
(* *)
(* PCanIsCountable ff' == builds an instance of the isCountable interface *)
(* given ff' : pcancel f f' where the codomain of f is *)
(* a countType *)
(* CanIsCountable ff' == builds an instance of the isCountable interface *)
(* given ff' : cancel f f' where the codomain of f is *)
(* a countType *)
(* *)
(* [Choice of T by <:], [Countable of T by <:] == Choice/Countable interface *)
(* for T when T has a subType p structure with p : pred cT *)
(* and cT has a Choice/Countable interface *)
(* The corresponding structure is Canonical. This notation *)
(* is in form_scope. *)
(* *)
(* List of Choice/Countable factories with a dedicated alias: *)
(* pcan_type fK == Choice/Countable for T, given f : T -> cT where cT *)
(* has a Choice/Countable structure, a left inverse *)
(* partial function g and fK : pcancel f g *)
(* can_type fK == Choice/Countable for T, given f : T -> cT, g and *)
(* fK : cancel f g *)
(* *)
(* GenTree.tree T == generic n-ary tree type with nat-labeled nodes and *)
(* T-labeled leaves, for example GenTree.Leaf (x : T), *)
(* GenTree.Node 5 [:: t; t'] *)
(* GenTree.tree is equipped with eqType, choiceType, *)
(* and countType instances, and so simple datatypes *)
(* can be similarly equipped by encoding into *)
(* GenTree.tree and using the interfaces above. *)
(* CodeSeq.code == bijection from seq nat to nat *)
(* CodeSeq.decode == bijection inverse to CodeSeq.code *)
(* *)
(* In addition to the lemmas relevant to these definitions, this file also *)
(* contains definitions of choiceType and countType instances for all basic *)
(* basic datatypes (e.g., nat, bool, subTypes, pairs, sums, etc.). *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
(* Technical definitions about coding and decoding of nat sequences, which *)
(* are used below to define various Canonical instances of the choice and *)
(* countable interfaces. *)
Module CodeSeq.
(* Goedel-style one-to-one encoding of seq nat into nat. *)
(* The code for [:: n1; ...; nk] has binary representation *)
(* 1 0 ... 0 1 ... 1 0 ... 0 1 0 ... 0 *)
(* <-----> <-----> <-----> *)
(* nk 0s n2 0s n1 0s *)
Definition code := foldr (fun n m => 2 ^ n * m.*2.+1) 0.
Fixpoint decode_rec (v q r : nat) {struct q} :=
match q, r with
| 0, _ => [:: v]
| q'.+1, 0 => v :: [rec 0, q', q']
| q'.+1, 1 => [rec v.+1, q', q']
| q'.+1, r'.+2 => [rec v, q', r']
end where "[ 'rec' v , q , r ]" := (decode_rec v q r).
Arguments decode_rec : simpl nomatch.
Definition decode n := if n is 0 then [::] else [rec 0, n.-1, n.-1].
Lemma decodeK : cancel decode code.
Proof.
have m2s: forall n, n.*2 - n = n by move=> n; rewrite -addnn addnK.
case=> //= n; rewrite -[n.+1]mul1n -(expn0 2) -[n in RHS]m2s.
elim: n {2 4}n {1 3}0 => [|q IHq] [|[|r]] v //=; rewrite {}IHq ?mul1n ?m2s //.
by rewrite expnSr -mulnA mul2n.
Qed.
Lemma codeK : cancel code decode.
Proof.
elim=> //= v s IHs; rewrite -[_ * _]prednK ?muln_gt0 ?expn_gt0 //=.
set two := 2; rewrite -[v in RHS]addn0; elim: v 0 => [|v IHv {IHs}] q.
rewrite mul1n add0n /= -{}[in RHS]IHs; case: (code s) => // u; pose n := u.+1.
by transitivity [rec q, n + u.+1, n.*2]; [rewrite addnn | elim: n => //=].
rewrite expnS -mulnA mul2n -{1}addnn -[_ * _]prednK ?muln_gt0 ?expn_gt0 //.
set u := _.-1 in IHv *; set n := u; rewrite [in u1 in _ + u1]/n.
by rewrite [in RHS]addSnnS -{}IHv; elim: n.
Qed.
Lemma ltn_code s : all (fun j => j < code s) s.
Proof.
elim: s => //= i s IHs; rewrite -[_.+1]muln1 leq_mul 1?ltn_expl //=.
apply: sub_all IHs => j /leqW lejs; rewrite -[j.+1]mul1n leq_mul ?expn_gt0 //.
by rewrite ltnS -[j]mul1n -mul2n leq_mul.
Qed.
Lemma gtn_decode n : all (ltn^~ n) (decode n).
Proof. by rewrite -{1}[n]decodeK ltn_code. Qed.
End CodeSeq.
Section OtherEncodings.
(* Miscellaneous encodings: option T -c-> seq T, T1 * T2 -c-> {i : T1 & T2} *)
(* T1 + T2 -c-> option T1 * option T2, unit -c-> bool; bool -c-> nat is *)
(* already covered in ssrnat by the nat_of_bool coercion, the odd predicate, *)
(* and their "cancellation" lemma oddb. We use these encodings to propagate *)
(* canonical structures through these type constructors so that ultimately *)
(* all Choice and Countable instanced derive from nat and the seq and sigT *)
(* constructors. *)
Variables T T1 T2 : Type.
Definition seq_of_opt := @oapp T _ (nseq 1) [::].
Lemma seq_of_optK : cancel seq_of_opt ohead. Proof. by case. Qed.
Definition tag_of_pair (p : T1 * T2) := @Tagged T1 p.1 (fun _ => T2) p.2.
Definition pair_of_tag (u : {i : T1 & T2}) := (tag u, tagged u).
Lemma tag_of_pairK : cancel tag_of_pair pair_of_tag. Proof. by case. Qed.
Lemma pair_of_tagK : cancel pair_of_tag tag_of_pair. Proof. by case. Qed.
Definition opair_of_sum (s : T1 + T2) :=
match s with inl x => (Some x, None) | inr y => (None, Some y) end.
Definition sum_of_opair p :=
oapp (some \o @inr T1 T2) (omap (@inl _ T2) p.1) p.2.
Lemma opair_of_sumK : pcancel opair_of_sum sum_of_opair. Proof. by case. Qed.
Lemma bool_of_unitK : cancel (fun _ => true) (fun _ => tt).
Proof. by case. Qed.
End OtherEncodings.
Prenex Implicits seq_of_opt tag_of_pair pair_of_tag opair_of_sum sum_of_opair.
Prenex Implicits seq_of_optK tag_of_pairK pair_of_tagK opair_of_sumK.
(* Generic variable-arity tree type, providing an encoding target for *)
(* miscellaneous user datatypes. The GenTree.tree type can be combined with *)
(* a sigT type to model multi-sorted concrete datatypes. *)
Module GenTree.
Section Def.
Variable T : Type.
Unset Elimination Schemes.
Inductive tree := Leaf of T | Node of nat & seq tree.
Definition tree_rect K IH_leaf IH_node :=
fix loop t : K t := match t with
| Leaf x => IH_leaf x
| Node n f0 =>
let fix iter_pair f : foldr (fun t => prod (K t)) unit f :=
if f is t :: f' then (loop t, iter_pair f') else tt in
IH_node n f0 (iter_pair f0)
end.
Definition tree_rec (K : tree -> Set) := @tree_rect K.
Definition tree_ind K IH_leaf IH_node :=
fix loop t : K t : Prop := match t with
| Leaf x => IH_leaf x
| Node n f0 =>
let fix iter_conj f : foldr (fun t => and (K t)) True f :=
if f is t :: f' then conj (loop t) (iter_conj f') else Logic.I
in IH_node n f0 (iter_conj f0)
end.
Fixpoint encode t : seq (nat + T) :=
match t with
| Leaf x => [:: inr _ x]
| Node n f => inl _ n.+1 :: rcons (flatten (map encode f)) (inl _ 0)
end.
Definition decode_step c fs :=
match c with
| inr x => (Leaf x :: fs.1, fs.2)
| inl 0 => ([::], fs.1 :: fs.2)
| inl n.+1 => (Node n fs.1 :: head [::] fs.2, behead fs.2)
end.
Definition decode c := ohead (foldr decode_step ([::], [::]) c).1.
Lemma codeK : pcancel encode decode.
Proof.
move=> t; rewrite /decode; set fs := (_, _).
suffices ->: foldr decode_step fs (encode t) = (t :: fs.1, fs.2) by [].
elim: t => //= n f IHt in (fs) *; elim: f IHt => //= t f IHf [].
by rewrite rcons_cat foldr_cat => -> /= /IHf[-> -> ->].
Qed.
End Def.
End GenTree.
Arguments GenTree.codeK : clear implicits.
HB.instance Definition _ (T : eqType) := Equality.copy (GenTree.tree T)
(pcan_type (GenTree.codeK T)).
(* Structures for Types with a choice function, and for Types with countably *)
(* many elements. The two concepts are closely linked: we indeed make *)
(* Countable a subclass of Choice, as countable choice is valid in CiC. This *)
(* apparent redundancy is needed to ensure the consistency of the Canonical *)
(* inference, as the canonical Choice for a given type may differ from the *)
(* countable choice for its canonical Countable structure, e.g., for options. *)
(* The Choice interface exposes two choice functions; for T : choiceType *)
(* and P : pred T, we provide: *)
(* xchoose : (exists x, P x) -> T *)
(* choose : pred T -> T -> T *)
(* While P (xchoose exP) will always hold, P (choose P x0) will be true if *)
(* and only if P x0 holds. Both xchoose and choose are extensional in P and *)
(* do not depend on the witness exP or x0 (provided P x0 holds). Note that *)
(* xchoose is slightly more powerful, but less convenient to use. *)
(* However, neither choose nor xchoose are composable: it would not be *)
(* be possible to extend the Choice structure to arbitrary pairs using only *)
(* these functions, for instance. Internally, the interfaces provides a *)
(* subtly stronger operation, Choice.InternalTheory.find, which performs a *)
(* limited search using an integer parameter only rather than a full value as *)
(* [x]choose does. This is not a restriction in a constructive theory, where *)
(* all types are concrete and hence countable. In the case of an axiomatic *)
(* theory, such as that of the Coq reals library, postulating a suitable *)
(* axiom of choice suppresses the need for guidance. Nevertheless this *)
(* operation is just what is needed to make the Choice interface compose. *)
(* The Countable interface provides three functions; for T : countType we *)
(* get pickle : T -> nat, and unpickle, pickle_inv : nat -> option T. *)
(* The functions provide an effective embedding of T in nat: unpickle is a *)
(* left inverse to pickle, which satisfies pcancel pickle unpickle, i.e., *)
(* unpickle \o pickle =1 some; pickle_inv is a more precise inverse for which *)
(* we also have ocancel pickle_inv pickle. Both unpickle and pickle need to *)
(* be partial functions to allow for possibly empty types such as {x | P x}. *)
(* The names of these functions underline the correspondence with the *)
(* notion of "Serializable" types in programming languages. *)
(* Finally, we need to provide a join class to let type inference unify *)
(* subType and countType class constraints, e.g., for a countable subType of *)
(* an uncountable choiceType (the issue does not arise earlier with eqType or *)
(* choiceType because in practice the base type of an Equality/Choice subType *)
(* is always an Equality/Choice Type). *)
HB.mixin Record hasChoice T := Mixin {
find_subdef : pred T -> nat -> option T;
choice_correct_subdef {P n x} : find_subdef P n = Some x -> P x;
choice_complete_subdef {P : pred T} :
(exists x, P x) -> exists n, find_subdef P n;
choice_extensional_subdef {P Q : pred T} :
P =1 Q -> find_subdef P =1 find_subdef Q
}.
#[short(type="choiceType")]
HB.structure Definition Choice := { T of hasChoice T & hasDecEq T}.
Module Export ChoiceNamespace.
Module Choice.
Module InternalTheory.
Notation find := find_subdef.
Notation correct := choice_correct_subdef.
Arguments correct {_ _ _ _}.
Notation complete := choice_complete_subdef.
Arguments complete {_ _}.
Notation extensional := choice_extensional_subdef.
Arguments extensional {_ _ _}.
Section InternalTheory.
Variable T : Choice.type.
Implicit Types P Q : pred T.
Fact xchoose_subproof P exP :
{x | find P (ex_minn (@choice_complete_subdef _ P exP)) = Some x}.
Proof.
case: (ex_minnP (complete exP)) => n.
by case: (find P n) => // x; exists x.
Qed.
End InternalTheory.
End InternalTheory.
End Choice.
End ChoiceNamespace.
Section ChoiceTheory.
Implicit Type T : choiceType.
Import Choice.InternalTheory CodeSeq.
Local Notation dc := decode.
Section OneType.
Variable T : choiceType.
Implicit Types P Q : pred T.
Definition xchoose P exP := sval (@xchoose_subproof T P exP).
Lemma xchooseP P exP : P (@xchoose P exP).
Proof. by rewrite /xchoose; case: (xchoose_subproof exP) => x /= /correct. Qed.
Lemma eq_xchoose P Q exP exQ : P =1 Q -> @xchoose P exP = @xchoose Q exQ.
Proof.
rewrite /xchoose => eqPQ.
case: (xchoose_subproof exP) => x; case: (xchoose_subproof exQ) => y /=.
case: ex_minnP => n; rewrite -(extensional eqPQ) => Pn minQn.
case: ex_minnP => m; rewrite !(extensional eqPQ) => Qm minPm.
by case: (eqVneq m n) => [-> -> [] //|]; rewrite eqn_leq minQn ?minPm.
Qed.
Lemma sigW P : (exists x, P x) -> {x | P x}.
Proof. by move=> exP; exists (xchoose exP); apply: xchooseP. Qed.
Lemma sig2W P Q : (exists2 x, P x & Q x) -> {x | P x & Q x}.
Proof.
move=> exPQ; have [|x /andP[]] := @sigW (predI P Q); last by exists x.
by have [x Px Qx] := exPQ; exists x; apply/andP.
Qed.
Lemma sig_eqW (vT : eqType) (lhs rhs : T -> vT) :
(exists x, lhs x = rhs x) -> {x | lhs x = rhs x}.
Proof.
move=> exP; suffices [x /eqP Ex]: {x | lhs x == rhs x} by exists x.
by apply: sigW; have [x /eqP Ex] := exP; exists x.
Qed.
Lemma sig2_eqW (vT : eqType) (P : pred T) (lhs rhs : T -> vT) :
(exists2 x, P x & lhs x = rhs x) -> {x | P x & lhs x = rhs x}.
Proof.
move=> exP; suffices [x Px /eqP Ex]: {x | P x & lhs x == rhs x} by exists x.
by apply: sig2W; have [x Px /eqP Ex] := exP; exists x.
Qed.
Definition choose P x0 :=
if insub x0 : {? x | P x} is Some (exist x Px) then
xchoose (ex_intro [eta P] x Px)
else x0.
Lemma chooseP P x0 : P x0 -> P (choose P x0).
Proof. by move=> Px0; rewrite /choose insubT xchooseP. Qed.
Lemma choose_id P x0 y0 : P x0 -> P y0 -> choose P x0 = choose P y0.
Proof. by move=> Px0 Py0; rewrite /choose !insubT /=; apply: eq_xchoose. Qed.
Lemma eq_choose P Q : P =1 Q -> choose P =1 choose Q.
Proof.
rewrite /choose => eqPQ x0.
do [case: insubP; rewrite eqPQ] => [[x Px] Qx0 _| ?]; last by rewrite insubN.
by rewrite insubT; apply: eq_xchoose.
Qed.
Section CanChoice.
Variables (sT : Type) (f : sT -> T).
Lemma PCanHasChoice f' : pcancel f f' -> hasChoice sT.
Proof.
move=> fK; pose liftP sP := [pred x | oapp sP false (f' x)].
pose sf sP := [fun n => obind f' (find (liftP sP) n)].
exists sf => [sP n x | sP [y sPy] | sP sQ eqPQ n] /=.
- by case Df: (find _ n) => //= [?] Dx; have:= correct Df; rewrite /= Dx.
- have [|n Pn] := @complete T (liftP sP); first by exists (f y); rewrite /= fK.
exists n; case Df: (find _ n) Pn => //= [x] _.
by have:= correct Df => /=; case: (f' x).
by congr (obind _ _); apply: extensional => x /=; case: (f' x) => /=.
Qed.
Definition CanHasChoice f' (fK : cancel f f') :=
PCanHasChoice (can_pcan fK).
HB.instance Definition _ f' (fK : pcancel f f') : hasChoice (pcan_type fK) :=
PCanHasChoice fK.
HB.instance Definition _ f' (fK : cancel f f') : hasChoice (can_type fK) :=
PCanHasChoice (can_pcan fK).
End CanChoice.
Section SubChoice.
Variables (P : pred T) (sT : subType P).
#[hnf] HB.instance Definition _ := Choice.copy (sub_type sT) (pcan_type valK).
End SubChoice.
Fact seq_hasChoice : hasChoice (seq T).
Proof.
pose r f := [fun xs => fun x : T => f (x :: xs) : option (seq T)].
pose fix f sP ns xs {struct ns} :=
if ns is n :: ns1 then let fr := r (f sP ns1) xs in obind fr (find fr n)
else if sP xs then Some xs else None.
exists (fun sP nn => f sP (dc nn) nil) => [sP n ys | sP [ys] | sP sQ eqPQ n].
- elim: {n}(dc n) nil => [|n ns IHs] xs /=; first by case: ifP => // sPxs [<-].
by case: (find _ n) => //= [x]; apply: IHs.
- rewrite -(cats0 ys); elim/last_ind: ys nil => [|ys y IHs] xs /=.
by move=> sPxs; exists 0; rewrite /= sPxs.
rewrite cat_rcons => /IHs[n1 sPn1] {IHs}.
have /complete[n]: exists z, f sP (dc n1) (z :: xs) by exists y.
case Df: (find _ n)=> // [x] _; exists (code (n :: dc n1)).
by rewrite codeK /= Df /= (correct Df).
elim: {n}(dc n) nil => [|n ns IHs] xs /=; first by rewrite eqPQ.
rewrite (@extensional _ _ (r (f sQ ns) xs)) => [|x]; last by rewrite IHs.
by case: find => /=.
Qed.
HB.instance Definition _ := seq_hasChoice.
End OneType.
Section TagChoice.
Variables (I : choiceType) (T_ : I -> choiceType).
Fact tagged_hasChoice : hasChoice {i : I & T_ i}.
Proof.
pose mkT i (x : T_ i) := Tagged T_ x.
pose ft tP n i := omap (mkT i) (find (tP \o mkT i) n).
pose fi tP ni nt := obind (ft tP nt) (find (ft tP nt) ni).
pose f tP n := if dc n is [:: ni; nt] then fi tP ni nt else None.
exists f => [tP n u | tP [[i x] tPxi] | sP sQ eqPQ n].
- rewrite /f /fi; case: (dc n) => [|ni [|nt []]] //=.
case: (find _ _) => //= [i]; rewrite /ft.
by case Df: (find _ _) => //= [x] [<-]; have:= correct Df.
- have /complete[nt tPnt]: exists y, (tP \o mkT i) y by exists x.
have{tPnt}: exists j, ft tP nt j by exists i; rewrite /ft; case: find tPnt.
case/complete=> ni tPn; exists (code [:: ni; nt]); rewrite /f codeK /fi.
by case Df: find tPn => //= [j] _; have:= correct Df.
rewrite /f /fi; case: (dc n) => [|ni [|nt []]] //=.
rewrite (@extensional _ _ (ft sQ nt)) => [|i].
by case: find => //= i; congr (omap _ _); apply: extensional => x /=.
by congr (omap _ _); apply: extensional => x /=.
Qed.
HB.instance Definition _ := tagged_hasChoice.
End TagChoice.
Fact nat_hasChoice : hasChoice nat.
Proof.
pose f := [fun (P : pred nat) n => if P n then Some n else None].
exists f => [P n m | P [n Pn] | P Q eqPQ n] /=; last by rewrite eqPQ.
by case: ifP => // Pn [<-].
by exists n; rewrite Pn.
Qed.
HB.instance Definition _ := nat_hasChoice.
HB.instance Definition _ := Choice.copy bool (can_type oddb).
HB.instance Definition _ := Choice.on bitseq.
HB.instance Definition _ := Choice.copy unit (can_type bool_of_unitK).
HB.instance Definition _ := Choice.copy void (pcan_type (of_voidK unit)).
HB.instance Definition _ T :=
Choice.copy (option T) (can_type (@seq_of_optK (Choice.sort T))).
HB.instance Definition _ (T1 T2 : choiceType) :=
Choice.copy (T1 * T2)%type (can_type (@tag_of_pairK T1 T2)).
HB.instance Definition _ (T1 T2 : choiceType) :=
Choice.copy (T1 + T2)%type (pcan_type (@opair_of_sumK T1 T2)).
HB.instance Definition _ T :=
Choice.copy (GenTree.tree T) (pcan_type (GenTree.codeK T)).
End ChoiceTheory.
#[short(type="subChoiceType")]
HB.structure Definition SubChoice T (P : pred T) :=
{ sT of Choice sT & isSub T P sT }.
Prenex Implicits xchoose choose.
Notation "[ 'Choice' 'of' T 'by' <: ]" := (Choice.copy T%type (sub_type T%type))
(format "[ 'Choice' 'of' T 'by' <: ]") : form_scope.
HB.instance Definition _ (T : choiceType) (P : pred T) :=
[Choice of {x | P x} by <:].
HB.mixin Record Choice_isCountable (T : Type) : Type := {
pickle : T -> nat;
unpickle : nat -> option T;
pickleK : pcancel pickle unpickle
}.
Arguments Choice_isCountable.axioms_ T%_type_scope.
#[short(type="countType")]
HB.structure Definition Countable := { T of Choice T & Choice_isCountable T }.
HB.factory Record isCountable (T : Type) : Type := {
pickle : T -> nat;
unpickle : nat -> option T;
pickleK : pcancel pickle unpickle
}.
HB.builders Context T of isCountable T.
HB.instance Definition _ := Equality.copy T (pcan_type pickleK).
HB.instance Definition _ := PCanHasChoice pickleK.
HB.instance Definition _ := Choice_isCountable.Build T pickleK.
HB.end.
Arguments isCountable.axioms_ T%_type_scope.
Section CountableTheory.
Variable T : countType.
Definition pickle_inv n :=
obind (fun x : T => if pickle x == n then Some x else None) (unpickle n).
Lemma pickle_invK : ocancel pickle_inv pickle.
Proof.
by rewrite /pickle_inv => n; case def_x: (unpickle n) => //= [x]; case: eqP.
Qed.
Lemma pickleK_inv : pcancel pickle pickle_inv.
Proof. by rewrite /pickle_inv => x; rewrite pickleK /= eqxx. Qed.
Lemma pcan_pickleK sT f f' :
@pcancel T sT f f' -> pcancel (pickle \o f) (pcomp f' unpickle).
Proof. by move=> fK x; rewrite /pcomp pickleK /= fK. Qed.
Definition PCanIsCountable sT (f : sT -> T) f' (fK : pcancel f f') :=
isCountable.Build sT (pcan_pickleK fK).
Definition CanIsCountable sT f f' (fK : cancel f f') :=
@PCanIsCountable sT _ _ (can_pcan fK).
HB.instance Definition _ sT (f : sT -> T) f' (fK : pcancel f f') :
isCountable (pcan_type fK) := PCanIsCountable fK.
HB.instance Definition _ sT (f : sT -> T) f' (fK : cancel f f') :
isCountable (can_type fK) := CanIsCountable fK.
#[hnf] HB.instance Definition _ (P : pred T) (sT : subType P) :=
Countable.copy (sub_type sT) (pcan_type valK).
Definition pickle_seq s := CodeSeq.code (map (@pickle T) s).
Definition unpickle_seq n := Some (pmap (@unpickle T) (CodeSeq.decode n)).
Lemma pickle_seqK : pcancel pickle_seq unpickle_seq.
Proof. by move=> s; rewrite /unpickle_seq CodeSeq.codeK (map_pK pickleK). Qed.
HB.instance Definition _ := isCountable.Build (seq T) pickle_seqK.
End CountableTheory.
Notation "[ 'Countable' 'of' T 'by' <: ]" :=
(Countable.copy T%type (sub_type T%type))
(format "[ 'Countable' 'of' T 'by' <: ]") : form_scope.
Arguments pickle_inv {T} n.
Arguments pickleK {T} x : rename.
Arguments pickleK_inv {T} x.
Arguments pickle_invK {T} n : rename.
#[short(type="subCountType")]
HB.structure Definition SubCountable T (P : pred T) :=
{ sT of Countable sT & isSub T P sT}.
Section TagCountType.
Variables (I : countType) (T_ : I -> countType).
Definition pickle_tagged (u : {i : I & T_ i}) :=
CodeSeq.code [:: pickle (tag u); pickle (tagged u)].
Definition unpickle_tagged s :=
if CodeSeq.decode s is [:: ni; nx] then
obind (fun i => omap (@Tagged I i T_) (unpickle nx)) (unpickle ni)
else None.
Lemma pickle_taggedK : pcancel pickle_tagged unpickle_tagged.
Proof.
by case=> i x; rewrite /unpickle_tagged CodeSeq.codeK /= pickleK /= pickleK.
Qed.
HB.instance Definition _ :=
Choice_isCountable.Build {i : I & T_ i} pickle_taggedK.
End TagCountType.
(* The remaining instances for standard datatypes. *)
Section CountableDataTypes.
Implicit Type T : countType.
Lemma nat_pickleK : pcancel id (@Some nat). Proof. by []. Qed.
HB.instance Definition _ := Choice_isCountable.Build nat nat_pickleK.
HB.instance Definition _ := Countable.copy bool (can_type oddb).
HB.instance Definition _ := Countable.on bitseq.
HB.instance Definition _ := Countable.copy unit (can_type bool_of_unitK).
HB.instance Definition _ := Countable.copy void
(pcan_type (of_voidK unit)).
HB.instance Definition _ T := Countable.copy (option T)
(can_type (@seq_of_optK T)).
HB.instance Definition _ T (P : pred T) := [Countable of {x | P x} by <:].
HB.instance Definition _ T1 T2 :=
Countable.copy (T1 * T2)%type (can_type (@tag_of_pairK T1 T2)).
HB.instance Definition _ (T1 T2 : countType) :=
Countable.copy (T1 + T2)%type (pcan_type (@opair_of_sumK T1 T2)).
HB.instance Definition _ T := Countable.copy (GenTree.tree T)
(pcan_type (GenTree.codeK T)).
End CountableDataTypes.
|
interval.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 div fintype bigop order ssralg finset fingroup.
From mathcomp Require Import ssrnum.
(******************************************************************************)
(* Intervals in ordered types *)
(* *)
(* This file provides support for intervals in ordered types. The datatype *)
(* (interval T) gives a formal characterization of an interval, as the pair *)
(* of its right and left bounds. *)
(* interval T == the type of formal intervals on T. *)
(* x \in i == when i is a formal interval on an ordered type, *)
(* \in can be used to test membership. *)
(* itvP x_in_i == where x_in_i has type x \in i, if i is ground, *)
(* gives a set of rewrite rules that x_in_i implies *)
(* lteBSide, bnd_simp == multirules to simplify inequalities between interval *)
(* bounds *)
(* miditv i == middle point of interval i *)
(* *)
(* When using interval.v, the lemma `in_itv` is in practice very useful. For *)
(* example, the execution of the tactic `rewrite in_itv` w.r.t. an hypothesis *)
(* of the form x \in `]a, b[ into a < x < b. *)
(* *)
(* Intervals of T form an partially ordered type (porderType) whose ordering *)
(* is the subset relation. If T is a lattice, intervals also form a lattice *)
(* (latticeType) whose meet and join are intersection and convex hull *)
(* respectively. They are distributive if T is an orderType. *)
(* *)
(* We provide a set of notations to write intervals (see below) *)
(* `[a, b], `]a, b], ..., `]-oo, a], ..., `]-oo, +oo[ *)
(* The substrings "oo", "oc", "co", "cc" in the names of lemmas respectively *)
(* stand for the intervals of the shape `]a, b[, `]a, b], `[a, b[, `[a, b]. *)
(* The substrings "pinfty" and "ninfty" in the names of lemmas stand for *)
(* +oo and -oo. *)
(* We also provide the lemma subitvP which computes the inequalities one *)
(* needs to prove when trying to prove the inclusion of intervals. *)
(* *)
(* Remark that we cannot implement a boolean comparison test for intervals on *)
(* an arbitrary ordered types, for this problem might be undecidable. Note *)
(* also that type (interval R) may contain several inhabitants coding for the *)
(* same interval. However, these pathological issues do not arise when R is a *)
(* real domain: we could provide a specific theory for this important case. *)
(* *)
(* References: *)
(* - Cyril Cohen, Assia Mahboubi, Formal proofs in real algebraic geometry: *)
(* from ordered fields quantifier elimination, LMCS, 2012 *)
(* - Cyril Cohen, Formalized algebraic numbers: construction and first-order *)
(* theory, PhD thesis, 2012, section 4.3 *)
(* *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Reserved Notation "'-oo'".
Reserved Notation "'+oo'".
Reserved Notation "`[ a , b ]" (format "`[ a , b ]").
Reserved Notation "`] a , b ]" (format "`] a , b ]").
Reserved Notation "`[ a , b [" (format "`[ a , b [").
Reserved Notation "`] a , b [" (format "`] a , b [").
Reserved Notation "`] '-oo' , b ]" (format "`] '-oo' , b ]").
Reserved Notation "`] '-oo' , b [" (format "`] '-oo' , b [").
Reserved Notation "`[ a , '+oo' [" (format "`[ a , '+oo' [").
Reserved Notation "`] a , '+oo' [" (format "`] a , '+oo' [").
Reserved Notation "`] -oo , '+oo' [" (format "`] -oo , '+oo' [").
Local Open Scope order_scope.
Import Order.TTheory.
Variant itv_bound (T : Type) : Type := BSide of bool & T | BInfty of bool.
Notation BLeft := (BSide true).
Notation BRight := (BSide false).
Notation "'-oo'" := (BInfty _ true) : order_scope.
Notation "'+oo'" := (BInfty _ false) : order_scope.
Variant interval (T : Type) := Interval of itv_bound T & itv_bound T.
Coercion pair_of_interval T (I : interval T) : itv_bound T * itv_bound T :=
let: Interval b1 b2 := I in (b1, b2).
(* We provide the 9 following notations to help writing formal intervals *)
Notation "`[ a , b ]" := (Interval (BLeft a) (BRight b)) : order_scope.
Notation "`] a , b ]" := (Interval (BRight a) (BRight b)) : order_scope.
Notation "`[ a , b [" := (Interval (BLeft a) (BLeft b)) : order_scope.
Notation "`] a , b [" := (Interval (BRight a) (BLeft b)) : order_scope.
Notation "`] '-oo' , b ]" := (Interval -oo (BRight b)) : order_scope.
Notation "`] '-oo' , b [" := (Interval -oo (BLeft b)) : order_scope.
Notation "`[ a , '+oo' [" := (Interval (BLeft a) +oo) : order_scope.
Notation "`] a , '+oo' [" := (Interval (BRight a) +oo) : order_scope.
Notation "`] -oo , '+oo' [" := (Interval -oo +oo) : order_scope.
Notation "`[ a , b ]" := (Interval (BLeft a) (BRight b)) : ring_scope.
Notation "`] a , b ]" := (Interval (BRight a) (BRight b)) : ring_scope.
Notation "`[ a , b [" := (Interval (BLeft a) (BLeft b)) : ring_scope.
Notation "`] a , b [" := (Interval (BRight a) (BLeft b)) : ring_scope.
Notation "`] '-oo' , b ]" := (Interval -oo (BRight b)) : ring_scope.
Notation "`] '-oo' , b [" := (Interval -oo (BLeft b)) : ring_scope.
Notation "`[ a , '+oo' [" := (Interval (BLeft a) +oo) : ring_scope.
Notation "`] a , '+oo' [" := (Interval (BRight a) +oo) : ring_scope.
Notation "`] -oo , '+oo' [" := (Interval -oo +oo) : ring_scope.
Fact itv_bound_display (disp : Order.disp_t) : Order.disp_t. Proof. exact. Qed.
Fact interval_display (disp : Order.disp_t) : Order.disp_t. Proof. exact. Qed.
Module IntervalCan.
Section IntervalCan.
Variable T : Type.
Lemma itv_bound_can :
cancel (fun b : itv_bound T =>
match b with BSide b x => (b, Some x) | BInfty b => (b, None) end)
(fun b =>
match b with (b, Some x) => BSide b x | (b, None) => BInfty _ b end).
Proof. by case. Qed.
Lemma interval_can :
@cancel _ (interval T)
(fun '(Interval b1 b2) => (b1, b2)) (fun '(b1, b2) => Interval b1 b2).
Proof. by case. Qed.
End IntervalCan.
#[export, hnf]
HB.instance Definition _ (T : eqType) := Equality.copy (itv_bound T)
(can_type (@itv_bound_can T)).
#[export, hnf]
HB.instance Definition _ (T : eqType) := Equality.copy (interval T)
(can_type (@interval_can T)).
#[export, hnf]
HB.instance Definition _ (T : choiceType) := Choice.copy (itv_bound T)
(can_type (@itv_bound_can T)).
#[export, hnf]
HB.instance Definition _ (T : choiceType) := Choice.copy (interval T)
(can_type (@interval_can T)).
#[export, hnf]
HB.instance Definition _ (T : countType) := Countable.copy (itv_bound T)
(can_type (@itv_bound_can T)).
#[export, hnf]
HB.instance Definition _ (T : countType) := Countable.copy (interval T)
(can_type (@interval_can T)).
#[export, hnf]
HB.instance Definition _ (T : finType) := Finite.copy (itv_bound T)
(can_type (@itv_bound_can T)).
#[export, hnf]
HB.instance Definition _ (T : finType) := Finite.copy (interval T)
(can_type (@interval_can T)).
Module Exports. HB.reexport. End Exports.
End IntervalCan.
Export IntervalCan.Exports.
Section IntervalPOrder.
Variable (disp : Order.disp_t) (T : porderType disp).
Implicit Types (x y z : T) (b bl br : itv_bound T) (i : interval T).
Definition le_bound b1 b2 :=
match b1, b2 with
| -oo, _ | _, +oo => true
| BSide b1 x1, BSide b2 x2 => x1 < x2 ?<= if b2 ==> b1
| _, _ => false
end.
Definition lt_bound b1 b2 :=
match b1, b2 with
| -oo, +oo | -oo, BSide _ _ | BSide _ _, +oo => true
| BSide b1 x1, BSide b2 x2 => x1 < x2 ?<= if b1 && ~~ b2
| _, _ => false
end.
Lemma lt_bound_def b1 b2 : lt_bound b1 b2 = (b2 != b1) && le_bound b1 b2.
Proof. by case: b1 b2 => [[]?|[]][[]?|[]] //=; rewrite lt_def. Qed.
Lemma le_bound_refl : reflexive le_bound.
Proof. by move=> [[]?|[]] /=. Qed.
Lemma le_bound_anti : antisymmetric le_bound.
Proof. by case=> [[]?|[]] [[]?|[]] //=; case: comparableP => // ->. Qed.
Lemma le_bound_trans : transitive le_bound.
Proof.
by case=> [[]?|[]] [[]?|[]] [[]?|[]] lexy leyz //;
apply: (lteif_imply _ (lteif_trans lexy leyz)).
Qed.
HB.instance Definition _ :=
Order.isPOrder.Build (itv_bound_display disp) (itv_bound T)
lt_bound_def le_bound_refl le_bound_anti le_bound_trans.
Lemma bound_lexx c1 c2 x : (BSide c1 x <= BSide c2 x) = (c2 ==> c1).
Proof. by rewrite /<=%O /= lteifxx. Qed.
Lemma bound_ltxx c1 c2 x : (BSide c1 x < BSide c2 x) = (c1 && ~~ c2).
Proof. by rewrite /<%O /= lteifxx. Qed.
Lemma ge_pinfty b : (+oo <= b) = (b == +oo). Proof. by case: b => [|] []. Qed.
Lemma le_ninfty b : (b <= -oo) = (b == -oo). Proof. by case: b => // - []. Qed.
Lemma gt_pinfty b : (+oo < b) = false. Proof. by []. Qed.
Lemma lt_ninfty b : (b < -oo) = false. Proof. by case: b => // -[]. Qed.
Lemma ltBSide x y (b b' : bool) :
BSide b x < BSide b' y = (x < y ?<= if b && ~~ b').
Proof. by []. Qed.
Lemma leBSide x y (b b' : bool) :
BSide b x <= BSide b' y = (x < y ?<= if b' ==> b).
Proof. by []. Qed.
Definition lteBSide := (ltBSide, leBSide).
Lemma ltBRight_leBLeft b x : b < BRight x = (b <= BLeft x).
Proof. by move: b => [[] b|[]]. Qed.
Lemma leBRight_ltBLeft b x : BRight x <= b = (BLeft x < b).
Proof. by move: b => [[] b|[]]. Qed.
Let BLeft_ltE x y (b : bool) : BSide b x < BLeft y = (x < y).
Proof. by case: b. Qed.
Let BRight_leE x y (b : bool) : BSide b x <= BRight y = (x <= y).
Proof. by case: b. Qed.
Let BRight_BLeft_leE x y : BRight x <= BLeft y = (x < y).
Proof. by []. Qed.
Let BLeft_BRight_ltE x y : BLeft x < BRight y = (x <= y).
Proof. by []. Qed.
Let BRight_BSide_ltE x y (b : bool) : BRight x < BSide b y = (x < y).
Proof. by case: b. Qed.
Let BLeft_BSide_leE x y (b : bool) : BLeft x <= BSide b y = (x <= y).
Proof. by case: b. Qed.
Let BSide_ltE x y (b : bool) : BSide b x < BSide b y = (x < y).
Proof. by case: b. Qed.
Let BSide_leE x y (b : bool) : BSide b x <= BSide b y = (x <= y).
Proof. by case: b. Qed.
Let BInfty_leE a : a <= BInfty T false. Proof. by case: a => [[] a|[]]. Qed.
Let BInfty_geE a : BInfty T true <= a. Proof. by case: a => [[] a|[]]. Qed.
Let BInfty_le_eqE a : BInfty T false <= a = (a == BInfty T false).
Proof. by case: a => [[] a|[]]. Qed.
Let BInfty_ge_eqE a : a <= BInfty T true = (a == BInfty T true).
Proof. by case: a => [[] a|[]]. Qed.
Let BInfty_ltE a : a < BInfty T false = (a != BInfty T false).
Proof. by case: a => [[] a|[]]. Qed.
Let BInfty_gtE a : BInfty T true < a = (a != BInfty T true).
Proof. by case: a => [[] a|[]]. Qed.
Let BInfty_ltF a : BInfty T false < a = false.
Proof. by case: a => [[] a|[]]. Qed.
Let BInfty_gtF a : a < BInfty T true = false.
Proof. by case: a => [[] a|[]]. Qed.
Let BInfty_BInfty_ltE : BInfty T true < BInfty T false. Proof. by []. Qed.
Definition bnd_simp := (BLeft_ltE, BRight_leE,
BRight_BLeft_leE, BLeft_BRight_ltE,
BRight_BSide_ltE, BLeft_BSide_leE, BSide_ltE, BSide_leE,
BInfty_leE, BInfty_geE, BInfty_BInfty_ltE,
BInfty_le_eqE, BInfty_ge_eqE, BInfty_ltE, BInfty_gtE, BInfty_ltF, BInfty_gtF,
@lexx _ T, @ltxx _ T, @eqxx T).
Lemma comparable_BSide_min s (x y : T) : (x >=< y)%O ->
BSide s (Order.min x y) = Order.min (BSide s x) (BSide s y).
Proof. by rewrite !minEle bnd_simp => /comparable_leP[]. Qed.
Lemma comparable_BSide_max s (x y : T) : (x >=< y)%O ->
BSide s (Order.max x y) = Order.max (BSide s x) (BSide s y).
Proof. by rewrite !maxEle bnd_simp => /comparable_leP[]. Qed.
Definition subitv i1 i2 :=
let: Interval b1l b1r := i1 in
let: Interval b2l b2r := i2 in (b2l <= b1l) && (b1r <= b2r).
Lemma subitv_refl : reflexive subitv.
Proof. by case=> /= ? ?; rewrite !lexx. Qed.
Lemma subitv_anti : antisymmetric subitv.
Proof.
by case=> [? ?][? ?]; rewrite andbACA => /andP[] /le_anti -> /le_anti ->.
Qed.
Lemma subitv_trans : transitive subitv.
Proof.
case=> [yl yr][xl xr][zl zr] /andP [Hl Hr] /andP [Hl' Hr'] /=.
by rewrite (le_trans Hl' Hl) (le_trans Hr Hr').
Qed.
HB.instance Definition _ :=
Order.isPOrder.Build (interval_display disp) (interval T)
(fun _ _ => erefl) subitv_refl subitv_anti subitv_trans.
Definition pred_of_itv i : pred T := [pred x | `[x, x] <= i].
Canonical Structure itvPredType := PredType pred_of_itv.
Lemma subitvE b1l b1r b2l b2r :
(Interval b1l b1r <= Interval b2l b2r) = (b2l <= b1l) && (b1r <= b2r).
Proof. by []. Qed.
Lemma in_itv x i :
x \in i =
let: Interval l u := i in
match l with
| BSide b lb => lb < x ?<= if b
| BInfty b => b
end &&
match u with
| BSide b ub => x < ub ?<= if ~~ b
| BInfty b => ~~ b
end.
Proof. by case: i => [[? ?|[]][|[]]]. Qed.
Lemma itv_boundlr bl br x :
(x \in Interval bl br) = (bl <= BLeft x) && (BRight x <= br).
Proof. by []. Qed.
Lemma itv_splitI bl br x :
x \in Interval bl br = (x \in Interval bl +oo) && (x \in Interval -oo br).
Proof. by rewrite !itv_boundlr andbT. Qed.
Lemma subitvP i1 i2 : i1 <= i2 -> {subset i1 <= i2}.
Proof. by move=> ? ? /le_trans; exact. Qed.
(* Remove the line below when requiring Coq >= 8.20 *)
#[warning="-unsupported-attributes"]
#[warn(note="The lemma subset_itv was generalized in MathComp 2.4.0 and the original was renamed to subset_itv_bound.",
cats="mathcomp-subset-itv")]
Lemma subset_itv (x y z u : itv_bound T) : x <= y -> z <= u ->
{subset Interval y z <= Interval x u}.
Proof. by move=> xy zu; apply: subitvP; rewrite subitvE xy zu. Qed.
#[deprecated(since="mathcomp 2.4.0", note="Use subset_itv instead.")]
Lemma subset_itv_bound (r s u v : bool) x y : r <= u -> v <= s ->
{subset Interval (BSide r x) (BSide s y) <= Interval (BSide u x) (BSide v y)}.
Proof.
by move: r s u v=> [] [] [] []// *; apply: subset_itv; rewrite bnd_simp.
Qed.
Lemma subset_itv_oo_cc x y : {subset `]x, y[ <= `[x, y]}.
Proof. by apply: subset_itv; rewrite bnd_simp. Qed.
Lemma subset_itv_oo_oc x y : {subset `]x, y[ <= `]x, y]}.
Proof. by apply: subset_itv; rewrite bnd_simp. Qed.
Lemma subset_itv_oo_co x y : {subset `]x, y[ <= `[x, y[}.
Proof. by apply: subset_itv; rewrite bnd_simp. Qed.
Lemma subset_itv_oc_cc x y : {subset `]x, y] <= `[x, y]}.
Proof. by apply: subset_itv; rewrite bnd_simp. Qed.
Lemma subset_itv_co_cc x y : {subset `[x, y[ <= `[x, y]}.
Proof. by apply: subset_itv; rewrite bnd_simp. Qed.
Lemma itvxx x : `[x, x] =i pred1 x.
Proof. by move=> y; rewrite in_itv/= -eq_le eq_sym. Qed.
Lemma itvxxP y x : reflect (y = x) (y \in `[x, x]).
Proof. by rewrite itvxx; apply/eqP. Qed.
Lemma subitvPl b1l b2l br :
b2l <= b1l -> {subset Interval b1l br <= Interval b2l br}.
Proof. by move=> ?; apply: subitvP; rewrite subitvE lexx andbT. Qed.
Lemma subitvPr bl b1r b2r :
b1r <= b2r -> {subset Interval bl b1r <= Interval bl b2r}.
Proof. by move=> ?; apply: subitvP; rewrite subitvE lexx. Qed.
Lemma itv_xx x cl cr y :
y \in Interval (BSide cl x) (BSide cr x) = cl && ~~ cr && (y == x).
Proof. by case: cl cr => [] []; rewrite [LHS]lteif_anti // eq_sym. Qed.
Lemma boundl_in_itv c x b : x \in Interval (BSide c x) b = c && (BRight x <= b).
Proof. by rewrite itv_boundlr bound_lexx. Qed.
Lemma boundr_in_itv c x b :
x \in Interval b (BSide c x) = ~~ c && (b <= BLeft x).
Proof. by rewrite itv_boundlr bound_lexx implybF andbC. Qed.
Definition bound_in_itv := (boundl_in_itv, boundr_in_itv).
Lemma lt_in_itv bl br x : x \in Interval bl br -> bl < br.
Proof. by case/andP; apply/le_lt_trans. Qed.
Lemma lteif_in_itv cl cr yl yr x :
x \in Interval (BSide cl yl) (BSide cr yr) -> yl < yr ?<= if cl && ~~ cr.
Proof. exact: lt_in_itv. Qed.
Lemma itv_ge b1 b2 : ~~ (b1 < b2) -> Interval b1 b2 =i pred0.
Proof. by move=> ltb12 y; apply/contraNF: ltb12; apply/lt_in_itv. Qed.
Definition itv_decompose i x : Prop :=
let: Interval l u := i in
(match l return Prop with
| BSide b lb => lb < x ?<= if b
| BInfty b => b
end *
match u return Prop with
| BSide b ub => x < ub ?<= if ~~ b
| BInfty b => ~~ b
end)%type.
Lemma itv_dec : forall x i, reflect (itv_decompose i x) (x \in i).
Proof. by move=> ? [[? ?|[]][? ?|[]]]; apply: (iffP andP); case. Qed.
Arguments itv_dec {x i}.
(* we compute a set of rewrite rules associated to an interval *)
Definition itv_rewrite i x : Type :=
let: Interval l u := i in
(match l with
| BLeft a => (a <= x) * (x < a = false)
| BRight a => (a <= x) * (a < x) * (x <= a = false) * (x < a = false)
| -oo => forall x : T, x == x
| +oo => forall b : bool, unkeyed b = false
end *
match u with
| BRight b => (x <= b) * (b < x = false)
| BLeft b => (x <= b) * (x < b) * (b <= x = false) * (b < x = false)
| +oo => forall x : T, x == x
| -oo => forall b : bool, unkeyed b = false
end *
match l, u with
| BLeft a, BRight b =>
(a <= b) * (b < a = false) * (a \in `[a, b]) * (b \in `[a, b])
| BLeft a, BLeft b =>
(a <= b) * (a < b) * (b <= a = false) * (b < a = false)
* (a \in `[a, b]) * (a \in `[a, b[) * (b \in `[a, b]) * (b \in `]a, b])
| BRight a, BRight b =>
(a <= b) * (a < b) * (b <= a = false) * (b < a = false)
* (a \in `[a, b]) * (a \in `[a, b[) * (b \in `[a, b]) * (b \in `]a, b])
| BRight a, BLeft b =>
(a <= b) * (a < b) * (b <= a = false) * (b < a = false)
* (a \in `[a, b]) * (a \in `[a, b[) * (b \in `[a, b]) * (b \in `]a, b])
| _, _ => forall x : T, x == x
end)%type.
Lemma itvP x i : x \in i -> itv_rewrite i x.
Proof.
case: i => [[[]a|[]][[]b|[]]] /andP [] ha hb; rewrite /= ?bound_in_itv;
do ![split | apply/negbTE; rewrite (le_gtF, lt_geF)];
by [|apply: ltW | move: (lteif_trans ha hb) => //=; exact: ltW].
Qed.
Arguments itvP [x i].
Lemma itv_splitU1 b x : b <= BLeft x ->
Interval b (BRight x) =i [predU1 x & Interval b (BLeft x)].
Proof.
move=> bx z; rewrite !inE/= !subitvE ?bnd_simp//= lt_neqAle.
by case: (eqVneq z x) => [->|]//=; rewrite lexx bx.
Qed.
Lemma itv_split1U b x : BRight x <= b ->
Interval (BLeft x) b =i [predU1 x & Interval (BRight x) b].
Proof.
move=> bx z; rewrite !inE/= !subitvE ?bnd_simp//= lt_neqAle.
by case: (eqVneq z x) => [->|]//=; rewrite lexx bx.
Qed.
End IntervalPOrder.
Section IntervalLattice.
Variable (disp : Order.disp_t) (T : latticeType disp).
Implicit Types (x y z : T) (b bl br : itv_bound T) (i : interval T).
Definition bound_meet bl br : itv_bound T :=
match bl, br with
| -oo, _ | _, -oo => -oo
| +oo, b | b, +oo => b
| BSide xb x, BSide yb y =>
BSide (((x <= y) && xb) || ((y <= x) && yb)) (x `&` y)
end.
Definition bound_join bl br : itv_bound T :=
match bl, br with
| -oo, b | b, -oo => b
| +oo, _ | _, +oo => +oo
| BSide xb x, BSide yb y =>
BSide ((~~ (x <= y) || yb) && (~~ (y <= x) || xb)) (x `|` y)
end.
Lemma bound_meetC : commutative bound_meet.
Proof.
case=> [? ?|[]][? ?|[]] //=; rewrite meetC; congr BSide.
by case: lcomparableP; rewrite ?orbF // orbC.
Qed.
Lemma bound_joinC : commutative bound_join.
Proof.
case=> [? ?|[]][? ?|[]] //=; rewrite joinC; congr BSide.
by case: lcomparableP; rewrite ?andbT // andbC.
Qed.
Lemma bound_meetA : associative bound_meet.
Proof.
case=> [? x|[]][? y|[]][? z|[]] //=; rewrite !lexI meetA; congr BSide.
by case: (lcomparableP x y) => [|||->]; case: (lcomparableP y z) => [|||->];
case: (lcomparableP x z) => [|||//<-]; case: (lcomparableP x y);
rewrite //= ?andbF ?orbF ?lexx ?orbA //; case: (lcomparableP y z).
Qed.
Lemma bound_joinA : associative bound_join.
Proof.
case=> [? x|[]][? y|[]][? z|[]] //=; rewrite !leUx joinA; congr BSide.
by case: (lcomparableP x y) => [|||->]; case: (lcomparableP y z) => [|||->];
case: (lcomparableP x z) => [|||//<-]; case: (lcomparableP x y);
rewrite //= ?orbT ?andbT ?lexx ?andbA //; case: (lcomparableP y z).
Qed.
Lemma bound_meetKU b2 b1 : bound_join b1 (bound_meet b1 b2) = b1.
Proof.
case: b1 b2 => [? ?|[]][? ?|[]] //=;
rewrite ?meetKU ?joinxx ?leIl ?lexI ?lexx ?andbb //=; congr BSide.
by case: lcomparableP; rewrite ?orbF /= ?andbb ?orbK.
Qed.
Lemma bound_joinKI b2 b1 : bound_meet b1 (bound_join b1 b2) = b1.
Proof.
case: b1 b2 => [? ?|[]][? ?|[]] //=;
rewrite ?joinKI ?meetxx ?leUl ?leUx ?lexx ?orbb //=; congr BSide.
by case: lcomparableP; rewrite ?orbF ?orbb ?andKb.
Qed.
Lemma bound_leEmeet b1 b2 : (b1 <= b2) = (bound_meet b1 b2 == b1).
Proof.
case: b1 b2 => [[]t[][]|[][][]] //=; rewrite ?eqxx// => t';
rewrite [LHS]/<=%O /eq_op ?andbT ?andbF ?orbF/= /eq_op/= /eq_op/=;
case: lcomparableP => //=; rewrite ?eqxx//=; [| | |].
- by move/lt_eqF.
- move=> ic; apply: esym; apply: contraNF ic.
by move=> /eqP/meet_idPl; apply: le_comparable.
- by move/lt_eqF.
- move=> ic; apply: esym; apply: contraNF ic.
by move=> /eqP/meet_idPl; apply: le_comparable.
Qed.
HB.instance Definition _ :=
Order.POrder_isLattice.Build (itv_bound_display disp) (itv_bound T)
bound_meetC bound_joinC bound_meetA bound_joinA
bound_joinKI bound_meetKU bound_leEmeet.
Lemma bound_le0x b : -oo <= b. Proof. by []. Qed.
Lemma bound_lex1 b : b <= +oo. Proof. by case: b => [|[]]. Qed.
HB.instance Definition _ :=
Order.hasBottom.Build (itv_bound_display disp) (itv_bound T) bound_le0x.
HB.instance Definition _ :=
Order.hasTop.Build (itv_bound_display disp) (itv_bound T) bound_lex1.
Definition itv_meet i1 i2 : interval T :=
let: Interval b1l b1r := i1 in
let: Interval b2l b2r := i2 in Interval (b1l `|` b2l) (b1r `&` b2r).
Definition itv_join i1 i2 : interval T :=
let: Interval b1l b1r := i1 in
let: Interval b2l b2r := i2 in Interval (b1l `&` b2l) (b1r `|` b2r).
Lemma itv_meetC : commutative itv_meet.
Proof. by case=> [? ?][? ?] /=; rewrite meetC joinC. Qed.
Lemma itv_joinC : commutative itv_join.
Proof. by case=> [? ?][? ?] /=; rewrite meetC joinC. Qed.
Lemma itv_meetA : associative itv_meet.
Proof. by case=> [? ?][? ?][? ?] /=; rewrite meetA joinA. Qed.
Lemma itv_joinA : associative itv_join.
Proof. by case=> [? ?][? ?][? ?] /=; rewrite meetA joinA. Qed.
Lemma itv_meetKU i2 i1 : itv_join i1 (itv_meet i1 i2) = i1.
Proof. by case: i1 i2 => [? ?][? ?] /=; rewrite meetKU joinKI. Qed.
Lemma itv_joinKI i2 i1 : itv_meet i1 (itv_join i1 i2) = i1.
Proof. by case: i1 i2 => [? ?][? ?] /=; rewrite meetKU joinKI. Qed.
Lemma itv_leEmeet i1 i2 : (i1 <= i2) = (itv_meet i1 i2 == i1).
Proof.
by case: i1 i2 => [? ?] [? ?]; rewrite /eq_op/=/eq_op/= eq_meetl eq_joinl.
Qed.
HB.instance Definition _ :=
Order.POrder_isLattice.Build (interval_display disp) (interval T)
itv_meetC itv_joinC itv_meetA itv_joinA
itv_joinKI itv_meetKU itv_leEmeet.
Lemma itv_le0x i : Interval +oo -oo <= i. Proof. by case: i => [[|[]]]. Qed.
Lemma itv_lex1 i : i <= `]-oo, +oo[. Proof. by case: i => [?[|[]]]. Qed.
HB.instance Definition _ :=
Order.hasBottom.Build (interval_display disp) (interval T) itv_le0x.
HB.instance Definition _ :=
Order.hasTop.Build (interval_display disp) (interval T) itv_lex1.
Lemma in_itvI x i1 i2 : x \in i1 `&` i2 = (x \in i1) && (x \in i2).
Proof. exact: lexI. Qed.
End IntervalLattice.
Section IntervalTotal.
Variable (disp : Order.disp_t) (T : orderType disp).
Implicit Types (a b c : itv_bound T) (x y z : T) (i : interval T).
Lemma BSide_min s (x y : T) :
BSide s (Order.min x y) = Order.min (BSide s x) (BSide s y).
Proof. exact: comparable_BSide_min. Qed.
Lemma BSide_max s (x y : T) :
BSide s (Order.max x y) = Order.max (BSide s x) (BSide s y).
Proof. exact: comparable_BSide_max. Qed.
Lemma itv_bound_total : total (<=%O : rel (itv_bound T)).
Proof. by move=> [[]?|[]][[]?|[]]; rewrite /<=%O //=; case: ltgtP. Qed.
HB.instance Definition _ :=
Order.Lattice_isTotal.Build
(itv_bound_display disp) (itv_bound T) itv_bound_total.
Lemma itv_meetUl : @left_distributive (interval T) _ Order.meet Order.join.
Proof.
by move=> [? ?][? ?][? ?]; rewrite /Order.meet /Order.join /= -meetUl -joinIl.
Qed.
HB.instance Definition _ :=
Order.Lattice_Meet_isDistrLattice.Build
(interval_display disp) (interval T) itv_meetUl.
Lemma itv_splitU c a b : a <= c <= b ->
forall y, y \in Interval a b = (y \in Interval a c) || (y \in Interval c b).
Proof.
case/andP => leac lecb y.
rewrite !itv_boundlr !(ltNge (BLeft y) _ : (BRight y <= _) = _).
case: (leP a) (leP b) (leP c) => leay [] leby [] lecy //=.
- by case: leP lecy (le_trans lecb leby).
- by case: leP leay (le_trans leac lecy).
Qed.
Lemma itv_splitUeq x a b : x \in Interval a b ->
forall y, y \in Interval a b =
[|| y \in Interval a (BLeft x), y == x | y \in Interval (BRight x) b].
Proof.
case/andP => ax xb y; rewrite (@itv_splitU (BLeft x)) ?ax ?ltW //.
by congr orb; rewrite (@itv_splitU (BRight x)) ?bound_lexx // itv_xx.
Qed.
Lemma itv_total_meet3E i1 i2 i3 :
i1 `&` i2 `&` i3 \in [:: i1 `&` i2; i1 `&` i3; i2 `&` i3].
Proof.
case: i1 i2 i3 => [b1l b1r] [b2l b2r] [b3l b3r]; rewrite !inE /eq_op /=.
case: (leP b1l b2l); case: (leP b1l b3l); case: (leP b2l b3l);
case: (leP b1r b2r); case: (leP b1r b3r); case: (leP b2r b3r);
rewrite ?eqxx ?orbT //= => b23r b13r b12r b23l b13l b12l.
- by case: leP b13r (le_trans b12r b23r).
- by case: leP b13l (le_trans b12l b23l).
- by case: leP b13l (le_trans b12l b23l).
- by case: leP b13r (le_trans b12r b23r).
- by case: leP b13r (le_trans b12r b23r).
- by case: leP b13l (lt_trans b23l b12l).
- by case: leP b13r (lt_trans b23r b12r).
- by case: leP b13l (lt_trans b23l b12l).
- by case: leP b13r (lt_trans b23r b12r).
- by case: leP b13r (lt_trans b23r b12r).
Qed.
Lemma itv_total_join3E i1 i2 i3 :
i1 `|` i2 `|` i3 \in [:: i1 `|` i2; i1 `|` i3; i2 `|` i3].
Proof.
case: i1 i2 i3 => [b1l b1r] [b2l b2r] [b3l b3r]; rewrite !inE /eq_op /=.
case: (leP b1l b2l); case: (leP b1l b3l); case: (leP b2l b3l);
case: (leP b1r b2r); case: (leP b1r b3r); case: (leP b2r b3r);
rewrite ?eqxx ?orbT //= => b23r b13r b12r b23l b13l b12l.
- by case: leP b13r (le_trans b12r b23r).
- by case: leP b13r (le_trans b12r b23r).
- by case: leP b13l (le_trans b12l b23l).
- by case: leP b13l (le_trans b12l b23l).
- by case: leP b13l (le_trans b12l b23l).
- by case: leP b13r (lt_trans b23r b12r).
- by case: leP b13l (lt_trans b23l b12l).
- by case: leP b13l (lt_trans b23l b12l).
- by case: leP b13l (lt_trans b23l b12l).
- by case: leP b13r (lt_trans b23r b12r).
Qed.
Lemma predC_itvl a : [predC Interval -oo a] =i Interval a +oo.
Proof.
case: a => [b x|[]//] y.
by rewrite !inE !subitvE/= bnd_simp andbT !lteBSide/= lteifNE negbK.
Qed.
Lemma predC_itvr a : [predC Interval a +oo] =i Interval -oo a.
Proof. by move=> y; rewrite inE/= -predC_itvl negbK. Qed.
Lemma predC_itv i : [predC i] =i [predU Interval -oo i.1 & Interval i.2 +oo].
Proof.
case: i => [a a']; move=> x; rewrite inE/= itv_splitI negb_and.
by symmetry; rewrite inE/= -predC_itvl -predC_itvr.
Qed.
End IntervalTotal.
Local Open Scope ring_scope.
Import GRing.Theory Num.Theory.
Section IntervalNumDomain.
Variable R : numDomainType.
Implicit Types x : R.
Lemma real_BSide_min b x y : x \in Num.real -> y \in Num.real ->
BSide b (Order.min x y) = Order.min (BSide b x) (BSide b y).
Proof. by move=> xr yr; apply/comparable_BSide_min/real_comparable. Qed.
Lemma real_BSide_max b x y : x \in Num.real -> y \in Num.real ->
BSide b (Order.max x y) = Order.max (BSide b x) (BSide b y).
Proof. by move=> xr yr; apply/comparable_BSide_max/real_comparable. Qed.
Lemma mem0_itvcc_xNx x : (0 \in `[- x, x]) = (0 <= x).
Proof. by rewrite itv_boundlr [in LHS]/<=%O /= oppr_le0 andbb. Qed.
Lemma mem0_itvoo_xNx x : 0 \in `]- x, x[ = (0 < x).
Proof. by rewrite itv_boundlr [in LHS]/<=%O /= oppr_lt0 andbb. Qed.
Lemma oppr_itv ba bb (xa xb x : R) :
(- x \in Interval (BSide ba xa) (BSide bb xb)) =
(x \in Interval (BSide (~~ bb) (- xb)) (BSide (~~ ba) (- xa))).
Proof.
by rewrite !itv_boundlr /<=%O /= !implybF negbK andbC lteifNl lteifNr.
Qed.
Lemma oppr_itvoo (a b x : R) : (- x \in `]a, b[) = (x \in `]- b, - a[).
Proof. exact: oppr_itv. Qed.
Lemma oppr_itvco (a b x : R) : (- x \in `[a, b[) = (x \in `]- b, - a]).
Proof. exact: oppr_itv. Qed.
Lemma oppr_itvoc (a b x : R) : (- x \in `]a, b]) = (x \in `[- b, - a[).
Proof. exact: oppr_itv. Qed.
Lemma oppr_itvcc (a b x : R) : (- x \in `[a, b]) = (x \in `[- b, - a]).
Proof. exact: oppr_itv. Qed.
Definition miditv (R : numDomainType) (i : interval R) : R :=
match i with
| Interval (BSide _ a) (BSide _ b) => (a + b) / 2%:R
| Interval -oo%O (BSide _ b) => b - 1
| Interval (BSide _ a) +oo%O => a + 1
| Interval -oo%O +oo%O => 0
| _ => 0
end.
End IntervalNumDomain.
Section IntervalField.
Variable R : numFieldType.
Implicit Types (x y z : R) (i : interval R).
Local Notation mid x y := ((x + y) / 2).
Lemma mid_in_itv : forall ba bb (xa xb : R), xa < xb ?<= if ba && ~~ bb ->
mid xa xb \in Interval (BSide ba xa) (BSide bb xb).
Proof.
by move=> [] [] xa xb /= ?; apply/itv_dec; rewrite /= ?midf_lte // ?ltW.
Qed.
Lemma mid_in_itvoo : forall (xa xb : R), xa < xb -> mid xa xb \in `]xa, xb[.
Proof. by move=> xa xb ?; apply: mid_in_itv. Qed.
Lemma mid_in_itvcc : forall (xa xb : R), xa <= xb -> mid xa xb \in `[xa, xb].
Proof. by move=> xa xb ?; apply: mid_in_itv. Qed.
Lemma mem_miditv i : (i.1 < i.2)%O -> miditv i \in i.
Proof.
move: i => [[ba a|[]] [bb b|[]]] //= ab; first exact: mid_in_itv.
by rewrite !in_itv -lteifBlDl subrr lteif01.
by rewrite !in_itv lteifBlDr -lteifBlDl subrr lteif01.
Qed.
Lemma miditv_le_left i b : (i.1 < i.2)%O -> (BSide b (miditv i) <= i.2)%O.
Proof.
case: i => [x y] lti; have := mem_miditv lti; rewrite inE => /andP[_ ].
by apply: le_trans; rewrite !bnd_simp.
Qed.
Lemma miditv_ge_right i b : (i.1 < i.2)%O -> (i.1 <= BSide b (miditv i))%O.
Proof.
case: i => [x y] lti; have := mem_miditv lti; rewrite inE => /andP[+ _].
by move=> /le_trans; apply; rewrite !bnd_simp.
Qed.
Lemma in_segmentDgt0Pr x y z :
reflect (forall e, e > 0 -> y \in `[x - e, z + e]) (y \in `[x, z]).
Proof.
apply/(iffP idP)=> [xyz e /[dup] e_gt0 /ltW e_ge0 | xyz_e].
by rewrite in_itv /= lerBDr !ler_wpDr// (itvP xyz).
by rewrite in_itv /= ; apply/andP; split; apply/ler_addgt0Pr => ? /xyz_e;
rewrite in_itv /= lerBDr => /andP [].
Qed.
Lemma in_segmentDgt0Pl x y z :
reflect (forall e, e > 0 -> y \in `[- e + x, e + z]) (y \in `[x, z]).
Proof.
apply/(equivP (in_segmentDgt0Pr x y z)).
by split=> zxy e /zxy; rewrite [z + _]addrC [_ + x]addrC.
Qed.
End IntervalField.
|
RingInvo.lean
|
/-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andreas Swerdlow, Kenny Lau
-/
import Mathlib.Algebra.Ring.Equiv
import Mathlib.Algebra.Ring.Opposite
/-!
# Ring involutions
This file defines a ring involution as a structure extending `R ≃+* Rᵐᵒᵖ`,
with the additional fact `f.involution : (f (f x).unop).unop = x`.
## Notations
We provide a coercion to a function `R → Rᵐᵒᵖ`.
## References
* <https://en.wikipedia.org/wiki/Involution_(mathematics)#Ring_theory>
## Tags
Ring involution
-/
variable {F : Type*} (R : Type*)
/-- A ring involution -/
structure RingInvo [Semiring R] extends R ≃+* Rᵐᵒᵖ where
/-- The requirement that the ring homomorphism is its own inverse -/
involution' : ∀ x, (toFun (toFun x).unop).unop = x
/-- The equivalence of rings underlying a ring involution. -/
add_decl_doc RingInvo.toRingEquiv
/-- `RingInvoClass F R` states that `F` is a type of ring involutions.
You should extend this class when you extend `RingInvo`. -/
class RingInvoClass (F R : Type*) [Semiring R] [EquivLike F R Rᵐᵒᵖ] : Prop
extends RingEquivClass F R Rᵐᵒᵖ where
/-- Every ring involution must be its own inverse -/
involution : ∀ (f : F) (x), (f (f x).unop).unop = x
/-- Turn an element of a type `F` satisfying `RingInvoClass F R` into an actual
`RingInvo`. This is declared as the default coercion from `F` to `RingInvo R`. -/
@[coe]
def RingInvoClass.toRingInvo {R} [Semiring R] [EquivLike F R Rᵐᵒᵖ] [RingInvoClass F R] (f : F) :
RingInvo R :=
{ (f : R ≃+* Rᵐᵒᵖ) with involution' := RingInvoClass.involution f }
namespace RingInvo
variable {R} [Semiring R] [EquivLike F R Rᵐᵒᵖ]
/-- Any type satisfying `RingInvoClass` can be cast into `RingInvo` via
`RingInvoClass.toRingInvo`. -/
instance [RingInvoClass F R] : CoeTC F (RingInvo R) :=
⟨RingInvoClass.toRingInvo⟩
instance : EquivLike (RingInvo R) R Rᵐᵒᵖ where
coe f := f.toFun
inv f := f.invFun
coe_injective' e f h₁ h₂ := by
rcases e with ⟨⟨tE, _⟩, _⟩; rcases f with ⟨⟨tF, _⟩, _⟩
cases tE
cases tF
congr
left_inv f := f.left_inv
right_inv f := f.right_inv
instance : RingInvoClass (RingInvo R) R where
map_add f := f.map_add'
map_mul f := f.map_mul'
involution f := f.involution'
/-- Construct a ring involution from a ring homomorphism. -/
def mk' (f : R →+* Rᵐᵒᵖ) (involution : ∀ r, (f (f r).unop).unop = r) : RingInvo R :=
{ f with
invFun := fun r => (f r.unop).unop
left_inv := fun r => involution r
right_inv := fun _ => MulOpposite.unop_injective <| involution _
involution' := involution }
@[simp]
theorem involution (f : RingInvo R) (x : R) : (f (f x).unop).unop = x :=
f.involution' x
-- Porting note: remove Coe instance, not needed
-- instance hasCoeToRingEquiv : Coe (RingInvo R) (R ≃+* Rᵐᵒᵖ) :=
-- ⟨RingInvo.toRingEquiv⟩
@[norm_cast]
theorem coe_ringEquiv (f : RingInvo R) (a : R) : (f : R ≃+* Rᵐᵒᵖ) a = f a :=
rfl
theorem map_eq_zero_iff (f : RingInvo R) {x : R} : f x = 0 ↔ x = 0 :=
f.toRingEquiv.map_eq_zero_iff
end RingInvo
open RingInvo
section CommRing
variable [CommRing R]
/-- The identity function of a `CommRing` is a ring involution. -/
protected def RingInvo.id : RingInvo R :=
{ RingEquiv.toOpposite R with involution' := fun _ => rfl }
instance : Inhabited (RingInvo R) :=
⟨RingInvo.id _⟩
end CommRing
|
Basic.lean
|
/-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Frédéric Dupuis, Heather Macbeth
-/
import Mathlib.Analysis.InnerProductSpace.Projection.Minimal
import Mathlib.Analysis.InnerProductSpace.Symmetric
import Mathlib.Analysis.RCLike.Lemmas
/-!
# The orthogonal projection
Given a nonempty subspace `K` of an inner product space `E` such that `K`
admits an orthogonal projection, this file constructs
`K.orthogonalProjection : E →L[𝕜] K`, the orthogonal projection of `E` onto `K`. This map
satisfies: for any point `u` in `E`, the point `v = K.orthogonalProjection u` in `K` minimizes the
distance `‖u - v‖` to `u`.
This file also defines `K.starProjection : E →L[𝕜] E` which is the
orthogonal projection of `E` onto `K` but as a map from `E` to `E` instead of `E` to `K`.
Basic API for `orthogonalProjection` and `starProjection` is developed.
## References
The orthogonal projection construction is adapted from
* [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*]
* [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*]
The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html>
-/
variable {𝕜 E F : Type*} [RCLike 𝕜]
variable [NormedAddCommGroup E] [NormedAddCommGroup F]
variable [InnerProductSpace 𝕜 E] [InnerProductSpace ℝ F]
local notation "⟪" x ", " y "⟫" => inner 𝕜 x y
local notation "absR" => @abs ℝ _ _
namespace Submodule
/-- A subspace `K : Submodule 𝕜 E` has an orthogonal projection if every vector `v : E` admits an
orthogonal projection to `K`. -/
class HasOrthogonalProjection (K : Submodule 𝕜 E) : Prop where
exists_orthogonal (v : E) : ∃ w ∈ K, v - w ∈ Kᗮ
variable (K : Submodule 𝕜 E)
instance (priority := 100) HasOrthogonalProjection.ofCompleteSpace [CompleteSpace K] :
K.HasOrthogonalProjection where
exists_orthogonal v := by
rcases K.exists_norm_eq_iInf_of_complete_subspace (completeSpace_coe_iff_isComplete.mp ‹_›) v
with ⟨w, hwK, hw⟩
refine ⟨w, hwK, (K.mem_orthogonal' _).2 ?_⟩
rwa [← K.norm_eq_iInf_iff_inner_eq_zero hwK]
instance [K.HasOrthogonalProjection] : Kᗮ.HasOrthogonalProjection where
exists_orthogonal v := by
rcases HasOrthogonalProjection.exists_orthogonal (K := K) v with ⟨w, hwK, hw⟩
refine ⟨_, hw, ?_⟩
rw [sub_sub_cancel]
exact K.le_orthogonal_orthogonal hwK
instance HasOrthogonalProjection.map_linearIsometryEquiv [K.HasOrthogonalProjection]
{E' : Type*} [NormedAddCommGroup E'] [InnerProductSpace 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') :
(K.map (f.toLinearEquiv : E →ₗ[𝕜] E')).HasOrthogonalProjection where
exists_orthogonal v := by
rcases HasOrthogonalProjection.exists_orthogonal (K := K) (f.symm v) with ⟨w, hwK, hw⟩
refine ⟨f w, Submodule.mem_map_of_mem hwK, Set.forall_mem_image.2 fun u hu ↦ ?_⟩
erw [← f.symm.inner_map_map, f.symm_apply_apply, map_sub, f.symm_apply_apply, hw u hu]
instance HasOrthogonalProjection.map_linearIsometryEquiv' [K.HasOrthogonalProjection]
{E' : Type*} [NormedAddCommGroup E'] [InnerProductSpace 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') :
(K.map f.toLinearIsometry).HasOrthogonalProjection :=
HasOrthogonalProjection.map_linearIsometryEquiv K f
instance : (⊤ : Submodule 𝕜 E).HasOrthogonalProjection := ⟨fun v ↦ ⟨v, trivial, by simp⟩⟩
noncomputable section
section orthogonalProjection
variable [K.HasOrthogonalProjection]
/-- The orthogonal projection onto a complete subspace, as an
unbundled function. This definition is only intended for use in
setting up the bundled version `orthogonalProjection` and should not
be used once that is defined. -/
def orthogonalProjectionFn (v : E) :=
(HasOrthogonalProjection.exists_orthogonal (K := K) v).choose
variable {K}
/-- The unbundled orthogonal projection is in the given subspace.
This lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
theorem orthogonalProjectionFn_mem (v : E) : K.orthogonalProjectionFn v ∈ K :=
(HasOrthogonalProjection.exists_orthogonal (K := K) v).choose_spec.left
/-- The characterization of the unbundled orthogonal projection. This
lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
theorem orthogonalProjectionFn_inner_eq_zero (v : E) :
∀ w ∈ K, ⟪v - K.orthogonalProjectionFn v, w⟫ = 0 :=
(K.mem_orthogonal' _).1 (HasOrthogonalProjection.exists_orthogonal (K := K) v).choose_spec.right
/-- The unbundled orthogonal projection is the unique point in `K`
with the orthogonality property. This lemma is only intended for use
in setting up the bundled version and should not be used once that is
defined. -/
theorem eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K)
(hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : K.orthogonalProjectionFn u = v := by
rw [← sub_eq_zero, ← @inner_self_eq_zero 𝕜]
have hvs : K.orthogonalProjectionFn u - v ∈ K :=
Submodule.sub_mem K (orthogonalProjectionFn_mem u) hvm
have huo : ⟪u - K.orthogonalProjectionFn u, K.orthogonalProjectionFn u - v⟫ = 0 :=
orthogonalProjectionFn_inner_eq_zero u _ hvs
have huv : ⟪u - v, K.orthogonalProjectionFn u - v⟫ = 0 := hvo _ hvs
have houv : ⟪u - v - (u - K.orthogonalProjectionFn u), K.orthogonalProjectionFn u - v⟫ = 0 := by
rw [inner_sub_left, huo, huv, sub_zero]
rwa [sub_sub_sub_cancel_left] at houv
variable (K)
theorem orthogonalProjectionFn_norm_sq (v : E) :
‖v‖ * ‖v‖ =
‖v - K.orthogonalProjectionFn v‖ * ‖v - K.orthogonalProjectionFn v‖ +
‖K.orthogonalProjectionFn v‖ * ‖K.orthogonalProjectionFn v‖ := by
set p := K.orthogonalProjectionFn v
have h' : ⟪v - p, p⟫ = 0 :=
orthogonalProjectionFn_inner_eq_zero _ _ (orthogonalProjectionFn_mem v)
convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (v - p) p h' using 2 <;> simp
/-- The orthogonal projection onto a complete subspace. -/
def orthogonalProjection : E →L[𝕜] K :=
LinearMap.mkContinuous
{ toFun := fun v => ⟨K.orthogonalProjectionFn v, orthogonalProjectionFn_mem v⟩
map_add' := fun x y => by
have hm : K.orthogonalProjectionFn x + K.orthogonalProjectionFn y ∈ K :=
Submodule.add_mem K (orthogonalProjectionFn_mem x) (orthogonalProjectionFn_mem y)
have ho :
∀ w ∈ K, ⟪x + y - (K.orthogonalProjectionFn x + K.orthogonalProjectionFn y), w⟫ = 0 := by
intro w hw
rw [add_sub_add_comm, inner_add_left, orthogonalProjectionFn_inner_eq_zero _ w hw,
orthogonalProjectionFn_inner_eq_zero _ w hw, add_zero]
ext
simp [eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero hm ho]
map_smul' := fun c x => by
have hm : c • K.orthogonalProjectionFn x ∈ K :=
Submodule.smul_mem K _ (orthogonalProjectionFn_mem x)
have ho : ∀ w ∈ K, ⟪c • x - c • K.orthogonalProjectionFn x, w⟫ = 0 := by
intro w hw
rw [← smul_sub, inner_smul_left, orthogonalProjectionFn_inner_eq_zero _ w hw,
mul_zero]
ext
simp [eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero hm ho] }
1 fun x => by
simp only [one_mul, LinearMap.coe_mk]
refine le_of_pow_le_pow_left₀ two_ne_zero (norm_nonneg _) ?_
change ‖K.orthogonalProjectionFn x‖ ^ 2 ≤ ‖x‖ ^ 2
nlinarith [K.orthogonalProjectionFn_norm_sq x]
variable {K}
@[simp]
theorem orthogonalProjectionFn_eq (v : E) :
K.orthogonalProjectionFn v = (K.orthogonalProjection v : E) :=
rfl
/-- The orthogonal projection onto a subspace as a map from the full space to itself,
as opposed to `Submodule.orthogonalProjection`, which maps into the subtype. This
version is important as it satisfies `IsStarProjection`. -/
def starProjection (U : Submodule 𝕜 E) [U.HasOrthogonalProjection] :
E →L[𝕜] E := U.subtypeL ∘L U.orthogonalProjection
lemma starProjection_apply (U : Submodule 𝕜 E) [U.HasOrthogonalProjection] (v : E) :
U.starProjection v = U.orthogonalProjection v := rfl
@[simp]
lemma coe_orthogonalProjection_apply (U : Submodule 𝕜 E) [U.HasOrthogonalProjection] (v : E) :
U.orthogonalProjection v = U.starProjection v := rfl
@[simp]
lemma starProjection_apply_mem (U : Submodule 𝕜 E) [U.HasOrthogonalProjection] (x : E) :
U.starProjection x ∈ U := by
simp only [starProjection_apply, SetLike.coe_mem]
/-- The characterization of the orthogonal projection. -/
@[simp]
theorem starProjection_inner_eq_zero (v : E) :
∀ w ∈ K, ⟪v - K.starProjection v, w⟫ = 0 :=
orthogonalProjectionFn_inner_eq_zero v
@[deprecated (since := "2025-07-07")] alias orthogonalProjection_inner_eq_zero :=
starProjection_inner_eq_zero
/-- The difference of `v` from its orthogonal projection onto `K` is in `Kᗮ`. -/
@[simp]
theorem sub_starProjection_mem_orthogonal (v : E) : v - K.starProjection v ∈ Kᗮ := by
intro w hw
rw [inner_eq_zero_symm]
exact starProjection_inner_eq_zero _ _ hw
@[deprecated (since := "2025-07-07")] alias sub_orthogonalProjection_mem_orthogonal :=
sub_starProjection_mem_orthogonal
/-- The orthogonal projection is the unique point in `K` with the
orthogonality property. -/
theorem eq_starProjection_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K)
(hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : K.starProjection u = v :=
eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero hvm hvo
@[deprecated (since := "2025-07-07")] alias eq_orthogonalProjection_of_mem_of_inner_eq_zero :=
eq_starProjection_of_mem_of_inner_eq_zero
/-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the
orthogonal projection. -/
theorem eq_starProjection_of_mem_orthogonal {u v : E} (hv : v ∈ K)
(hvo : u - v ∈ Kᗮ) : K.starProjection u = v :=
eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero hv <| (Submodule.mem_orthogonal' _ _).1 hvo
@[deprecated (since := "2025-07-07")] alias eq_orthogonalProjection_of_mem_orthogonal :=
eq_starProjection_of_mem_orthogonal
/-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the
orthogonal projection. -/
theorem eq_starProjection_of_mem_orthogonal' {u v z : E}
(hv : v ∈ K) (hz : z ∈ Kᗮ) (hu : u = v + z) : K.starProjection u = v :=
eq_starProjection_of_mem_orthogonal hv (by simpa [hu] )
@[deprecated (since := "2025-07-07")] alias eq_orthogonalProjection_of_mem_orthogonal' :=
eq_starProjection_of_mem_orthogonal'
@[simp]
theorem starProjection_orthogonal_val (u : E) :
Kᗮ.starProjection u = u - K.starProjection u :=
eq_starProjection_of_mem_orthogonal' (sub_starProjection_mem_orthogonal _)
(K.le_orthogonal_orthogonal (K.orthogonalProjection u).2) <| (sub_add_cancel _ _).symm
@[deprecated (since := "2025-07-07")] alias orthogonalProjection_orthogonal_val :=
starProjection_orthogonal_val
theorem orthogonalProjection_orthogonal (u : E) :
Kᗮ.orthogonalProjection u =
⟨u - K.starProjection u, sub_starProjection_mem_orthogonal _⟩ :=
Subtype.eq <| starProjection_orthogonal_val _
lemma starProjection_orthogonal (U : Submodule 𝕜 E) [U.HasOrthogonalProjection] :
Uᗮ.starProjection = ContinuousLinearMap.id 𝕜 E - U.starProjection := by
ext
simp only [starProjection, ContinuousLinearMap.comp_apply,
orthogonalProjection_orthogonal]
simp
lemma starProjection_orthogonal' (U : Submodule 𝕜 E) [U.HasOrthogonalProjection] :
Uᗮ.starProjection = 1 - U.starProjection := starProjection_orthogonal U
/-- The orthogonal projection of `y` on `U` minimizes the distance `‖y - x‖` for `x ∈ U`. -/
theorem starProjection_minimal {U : Submodule 𝕜 E} [U.HasOrthogonalProjection] (y : E) :
‖y - U.starProjection y‖ = ⨅ x : U, ‖y - x‖ := by
rw [starProjection_apply, U.norm_eq_iInf_iff_inner_eq_zero (Submodule.coe_mem _)]
exact starProjection_inner_eq_zero _
@[deprecated (since := "2025-07-07")] alias orthogonalProjection_minimal := starProjection_minimal
/-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/
@[deprecated "As there are no subtypes causing dependent type issues, there is no need for this
result as `simp` will suffice" (since := "12-07-2025")]
theorem eq_starProjection_of_eq_submodule {K' : Submodule 𝕜 E} [K'.HasOrthogonalProjection]
(h : K = K') (u : E) : K.starProjection u = K'.starProjection u := by
simp [h]
@[deprecated (since := "2025-07-07")] alias eq_orthogonalProjection_of_eq_submodule :=
eq_starProjection_of_eq_submodule
/-- The orthogonal projection sends elements of `K` to themselves. -/
@[simp]
theorem orthogonalProjection_mem_subspace_eq_self (v : K) : K.orthogonalProjection v = v := by
ext
apply eq_starProjection_of_mem_of_inner_eq_zero <;> simp
@[simp]
theorem starProjection_mem_subspace_eq_self (v : K) :
K.starProjection v = v := by simp [starProjection_apply]
/-- A point equals its orthogonal projection if and only if it lies in the subspace. -/
theorem starProjection_eq_self_iff {v : E} : K.starProjection v = v ↔ v ∈ K := by
refine ⟨fun h => ?_, fun h => eq_starProjection_of_mem_of_inner_eq_zero h ?_⟩
· rw [← h]
simp
· simp
@[deprecated (since := "2025-07-07")] alias orthogonalProjection_eq_self_iff :=
starProjection_eq_self_iff
variable (K) in
@[simp]
lemma isIdempotentElem_starProjection : IsIdempotentElem K.starProjection :=
ContinuousLinearMap.ext fun x ↦ starProjection_eq_self_iff.mpr <| by simp
@[simp]
lemma range_starProjection (U : Submodule 𝕜 E) [U.HasOrthogonalProjection] :
LinearMap.range U.starProjection = U := by
ext x
exact ⟨fun ⟨y, hy⟩ ↦ hy ▸ coe_mem (U.orthogonalProjection y),
fun h ↦ ⟨x, starProjection_eq_self_iff.mpr h⟩⟩
lemma starProjection_top : (⊤ : Submodule 𝕜 E).starProjection = ContinuousLinearMap.id 𝕜 E := by
ext
exact starProjection_eq_self_iff.mpr trivial
lemma starProjection_top' : (⊤ : Submodule 𝕜 E).starProjection = 1 :=
starProjection_top
@[simp]
theorem orthogonalProjection_eq_zero_iff {v : E} : K.orthogonalProjection v = 0 ↔ v ∈ Kᗮ := by
refine ⟨fun h ↦ ?_, fun h ↦ Subtype.eq <| eq_starProjection_of_mem_orthogonal
(zero_mem _) ?_⟩
· rw [← sub_zero v, ← coe_zero (p := K), ← h]
exact sub_starProjection_mem_orthogonal (K := K) v
· simpa
@[simp]
theorem ker_orthogonalProjection : LinearMap.ker K.orthogonalProjection = Kᗮ := by
ext; exact orthogonalProjection_eq_zero_iff
open ContinuousLinearMap in
@[simp]
lemma ker_starProjection (U : Submodule 𝕜 E) [U.HasOrthogonalProjection] :
LinearMap.ker U.starProjection = Uᗮ := by
rw [(isIdempotentElem_starProjection U).ker_eq_range, ← starProjection_orthogonal',
range_starProjection]
theorem _root_.LinearIsometry.map_starProjection {E E' : Type*} [NormedAddCommGroup E]
[NormedAddCommGroup E'] [InnerProductSpace 𝕜 E] [InnerProductSpace 𝕜 E'] (f : E →ₗᵢ[𝕜] E')
(p : Submodule 𝕜 E) [p.HasOrthogonalProjection] [(p.map f.toLinearMap).HasOrthogonalProjection]
(x : E) : f (p.starProjection x) = (p.map f.toLinearMap).starProjection (f x) := by
refine (eq_starProjection_of_mem_of_inner_eq_zero ?_ fun y hy => ?_).symm
· refine Submodule.apply_coe_mem_map _ _
rcases hy with ⟨x', hx', rfl : f x' = y⟩
rw [← f.map_sub, f.inner_map_map, starProjection_inner_eq_zero x x' hx']
@[deprecated (since := "2025-07-07")] alias _root_.LinearIsometry.map_orthogonalProjection :=
LinearIsometry.map_starProjection
theorem _root_.LinearIsometry.map_starProjection' {E E' : Type*} [NormedAddCommGroup E]
[NormedAddCommGroup E'] [InnerProductSpace 𝕜 E] [InnerProductSpace 𝕜 E'] (f : E →ₗᵢ[𝕜] E')
(p : Submodule 𝕜 E) [p.HasOrthogonalProjection] [(p.map f).HasOrthogonalProjection] (x : E) :
f (p.starProjection x) = (p.map f).starProjection (f x) :=
have : (p.map f.toLinearMap).HasOrthogonalProjection := ‹_›
f.map_starProjection p x
@[deprecated (since := "2025-07-07")] alias _root_.LinearIsometry.map_orthogonalProjection' :=
LinearIsometry.map_starProjection'
/-- Orthogonal projection onto the `Submodule.map` of a subspace. -/
theorem starProjection_map_apply {E E' : Type*} [NormedAddCommGroup E]
[NormedAddCommGroup E'] [InnerProductSpace 𝕜 E] [InnerProductSpace 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E')
(p : Submodule 𝕜 E) [p.HasOrthogonalProjection] (x : E') :
(p.map (f.toLinearEquiv : E →ₗ[𝕜] E')).starProjection x =
f (p.starProjection (f.symm x)) := by
simpa only [f.coe_toLinearIsometry, f.apply_symm_apply] using
(f.toLinearIsometry.map_starProjection' p (f.symm x)).symm
@[deprecated (since := "2025-07-07")] alias orthogonalProjection_map_apply :=
starProjection_map_apply
/-- The orthogonal projection onto the trivial submodule is the zero map. -/
@[simp]
theorem orthogonalProjection_bot : (⊥ : Submodule 𝕜 E).orthogonalProjection = 0 := by ext
@[simp]
lemma starProjection_bot : (⊥ : Submodule 𝕜 E).starProjection = 0 := by
rw [starProjection, orthogonalProjection_bot, ContinuousLinearMap.comp_zero]
variable (K)
/-- The orthogonal projection has norm `≤ 1`. -/
theorem orthogonalProjection_norm_le : ‖K.orthogonalProjection‖ ≤ 1 :=
LinearMap.mkContinuous_norm_le _ (by simp) _
theorem starProjection_norm_le : ‖K.starProjection‖ ≤ 1 :=
K.orthogonalProjection_norm_le
theorem norm_orthogonalProjection_apply {v : E} (hv : v ∈ K) :
‖orthogonalProjection K v‖ = ‖v‖ :=
congr(‖$(K.starProjection_eq_self_iff.mpr hv)‖)
theorem norm_starProjection_apply {v : E} (hv : v ∈ K) :
‖K.starProjection v‖ = ‖v‖ :=
norm_orthogonalProjection_apply _ hv
/-- The orthogonal projection onto a closed subspace is norm non-increasing. -/
theorem norm_orthogonalProjection_apply_le (v : E) :
‖orthogonalProjection K v‖ ≤ ‖v‖ := by calc
‖orthogonalProjection K v‖ ≤ ‖orthogonalProjection K‖ * ‖v‖ := K.orthogonalProjection.le_opNorm _
_ ≤ 1 * ‖v‖ := by gcongr; exact orthogonalProjection_norm_le K
_ = _ := by simp
theorem norm_starProjection_apply_le (v : E) :
‖K.starProjection v‖ ≤ ‖v‖ := K.norm_orthogonalProjection_apply_le v
/-- The orthogonal projection onto a closed subspace is a `1`-Lipschitz map. -/
theorem lipschitzWith_orthogonalProjection :
LipschitzWith 1 (orthogonalProjection K) :=
ContinuousLinearMap.lipschitzWith_of_opNorm_le (orthogonalProjection_norm_le K)
theorem lipschitzWith_starProjection :
LipschitzWith 1 K.starProjection :=
ContinuousLinearMap.lipschitzWith_of_opNorm_le (starProjection_norm_le K)
/-- The operator norm of the orthogonal projection onto a nontrivial subspace is `1`. -/
theorem norm_orthogonalProjection (hK : K ≠ ⊥) :
‖K.orthogonalProjection‖ = 1 := by
refine le_antisymm K.orthogonalProjection_norm_le ?_
obtain ⟨x, hxK, hx_ne_zero⟩ := Submodule.exists_mem_ne_zero_of_ne_bot hK
simpa [K.norm_orthogonalProjection_apply hxK, norm_eq_zero, hx_ne_zero]
using K.orthogonalProjection.ratio_le_opNorm x
theorem norm_starProjection (hK : K ≠ ⊥) :
‖K.starProjection‖ = 1 :=
K.norm_orthogonalProjection hK
variable (𝕜)
theorem smul_starProjection_singleton {v : E} (w : E) :
((‖v‖ ^ 2 : ℝ) : 𝕜) • (𝕜 ∙ v).starProjection w = ⟪v, w⟫ • v := by
suffices ((𝕜 ∙ v).starProjection (((‖v‖ : 𝕜) ^ 2) • w)) = ⟪v, w⟫ • v by
simpa using this
apply eq_starProjection_of_mem_of_inner_eq_zero
· rw [Submodule.mem_span_singleton]
use ⟪v, w⟫
· rw [← Submodule.mem_orthogonal', Submodule.mem_orthogonal_singleton_iff_inner_left]
simp [inner_sub_left, inner_smul_left, inner_self_eq_norm_sq_to_K, mul_comm]
@[deprecated (since := "2025-07-07")] alias smul_orthogonalProjection_singleton :=
smul_starProjection_singleton
/-- Formula for orthogonal projection onto a single vector. -/
theorem starProjection_singleton {v : E} (w : E) :
(𝕜 ∙ v).starProjection w = (⟪v, w⟫ / ((‖v‖ ^ 2 : ℝ) : 𝕜)) • v := by
by_cases hv : v = 0
· rw [hv]
simp [Submodule.span_zero_singleton 𝕜]
have hv' : ‖v‖ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv)
have key :
(((‖v‖ ^ 2 : ℝ) : 𝕜)⁻¹ * ((‖v‖ ^ 2 : ℝ) : 𝕜)) • ((𝕜 ∙ v).starProjection w) =
(((‖v‖ ^ 2 : ℝ) : 𝕜)⁻¹ * ⟪v, w⟫) • v := by
simp [mul_smul, smul_starProjection_singleton 𝕜 w, -map_pow]
convert key using 1 <;> field_simp [hv']
@[deprecated (since := "2025-07-07")] alias orthogonalProjection_singleton :=
starProjection_singleton
/-- Formula for orthogonal projection onto a single unit vector. -/
theorem starProjection_unit_singleton {v : E} (hv : ‖v‖ = 1) (w : E) :
(𝕜 ∙ v).starProjection w = ⟪v, w⟫ • v := by
rw [← smul_starProjection_singleton 𝕜 w]
simp [hv]
@[deprecated (since := "2025-07-07")] alias orthogonalProjection_unit_singleton :=
starProjection_unit_singleton
end orthogonalProjection
variable {K}
/-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/
theorem exists_add_mem_mem_orthogonal [K.HasOrthogonalProjection] (v : E) :
∃ y ∈ K, ∃ z ∈ Kᗮ, v = y + z :=
⟨K.orthogonalProjection v, Subtype.coe_prop _, v - K.orthogonalProjection v,
sub_starProjection_mem_orthogonal _, by simp⟩
/-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/
theorem orthogonalProjection_mem_subspace_orthogonalComplement_eq_zero [K.HasOrthogonalProjection]
{v : E} (hv : v ∈ Kᗮ) : K.orthogonalProjection v = 0 := by
ext
convert eq_starProjection_of_mem_orthogonal (K := K) _ _ <;> simp [hv]
/-- The projection into `U` from an orthogonal submodule `V` is the zero map. -/
theorem IsOrtho.orthogonalProjection_comp_subtypeL {U V : Submodule 𝕜 E}
[U.HasOrthogonalProjection] (h : U ⟂ V) : U.orthogonalProjection ∘L V.subtypeL = 0 :=
ContinuousLinearMap.ext fun v =>
orthogonalProjection_mem_subspace_orthogonalComplement_eq_zero <| h.symm v.prop
theorem IsOrtho.starProjection_comp_starProjection {U V : Submodule 𝕜 E}
[U.HasOrthogonalProjection] [V.HasOrthogonalProjection] (h : U ⟂ V) :
U.starProjection ∘L V.starProjection = 0 :=
calc _ = U.subtypeL ∘L (U.orthogonalProjection ∘L V.subtypeL) ∘L V.orthogonalProjection := by
simp only [starProjection, ContinuousLinearMap.comp_assoc]
_ = 0 := by simp [h.orthogonalProjection_comp_subtypeL]
/-- The projection into `U` from `V` is the zero map if and only if `U` and `V` are orthogonal. -/
theorem orthogonalProjection_comp_subtypeL_eq_zero_iff {U V : Submodule 𝕜 E}
[U.HasOrthogonalProjection] : U.orthogonalProjection ∘L V.subtypeL = 0 ↔ U ⟂ V :=
⟨fun h u hu v hv => by
convert starProjection_inner_eq_zero v u hu using 2
have : U.orthogonalProjection v = 0 := DFunLike.congr_fun h (⟨_, hv⟩ : V)
rw [starProjection_apply, this, Submodule.coe_zero, sub_zero],
Submodule.IsOrtho.orthogonalProjection_comp_subtypeL⟩
/-- `U.starProjection ∘ V.starProjection = 0` iff `U` and `V` are pairwise orthogonal. -/
theorem starProjection_comp_starProjection_eq_zero_iff {U V : Submodule 𝕜 E}
[U.HasOrthogonalProjection] [V.HasOrthogonalProjection] :
U.starProjection ∘L V.starProjection = 0 ↔ U ⟂ V := by
refine ⟨fun h => ?_, fun h => h.starProjection_comp_starProjection⟩
rw [← orthogonalProjection_comp_subtypeL_eq_zero_iff]
simp only [ContinuousLinearMap.ext_iff, ContinuousLinearMap.comp_apply, subtypeL_apply,
starProjection_apply, ContinuousLinearMap.zero_apply, coe_eq_zero] at h ⊢
intro x
simpa using h (x : E)
/-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/
theorem orthogonalProjection_orthogonal_apply_eq_zero
[Kᗮ.HasOrthogonalProjection] {v : E} (hv : v ∈ K) : Kᗮ.orthogonalProjection v = 0 :=
orthogonalProjection_mem_subspace_orthogonalComplement_eq_zero (K.le_orthogonal_orthogonal hv)
@[deprecated (since := "22-07-2025")] alias
orthogonalProjection_mem_subspace_orthogonal_precomplement_eq_zero :=
orthogonalProjection_orthogonal_apply_eq_zero
theorem starProjection_orthogonal_apply_eq_zero
[Kᗮ.HasOrthogonalProjection] {v : E} (hv : v ∈ K) :
Kᗮ.starProjection v = 0 := by
rw [starProjection_apply, coe_eq_zero]
exact orthogonalProjection_orthogonal_apply_eq_zero hv
/-- If `U ≤ V`, then projecting on `V` and then on `U` is the same as projecting on `U`. -/
theorem orthogonalProjection_starProjection_of_le {U V : Submodule 𝕜 E}
[U.HasOrthogonalProjection] [V.HasOrthogonalProjection] (h : U ≤ V) (x : E) :
U.orthogonalProjection (V.starProjection x) = U.orthogonalProjection x :=
Eq.symm <| by
simpa only [sub_eq_zero, map_sub] using
orthogonalProjection_mem_subspace_orthogonalComplement_eq_zero
(Submodule.orthogonal_le h (sub_starProjection_mem_orthogonal x))
@[deprecated (since := "2025-07-07")] alias orthogonalProjection_orthogonalProjection_of_le :=
orthogonalProjection_starProjection_of_le
theorem starProjection_comp_starProjection_of_le {U V : Submodule 𝕜 E}
[U.HasOrthogonalProjection] [V.HasOrthogonalProjection] (h : U ≤ V) :
U.starProjection ∘L V.starProjection = U.starProjection := ContinuousLinearMap.ext fun _ => by
nth_rw 1 [starProjection]
simp [orthogonalProjection_starProjection_of_le h]
open ContinuousLinearMap in
theorem _root_.ContinuousLinearMap.IsIdempotentElem.hasOrthogonalProjection_range [CompleteSpace E]
{p : E →L[𝕜] E} (hp : IsIdempotentElem p) : (LinearMap.range p).HasOrthogonalProjection :=
have := hp.isClosed_range.completeSpace_coe
.ofCompleteSpace _
/-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/
theorem orthogonalProjection_orthogonalComplement_singleton_eq_zero (v : E) :
(𝕜 ∙ v)ᗮ.orthogonalProjection v = 0 :=
orthogonalProjection_orthogonal_apply_eq_zero
(Submodule.mem_span_singleton_self v)
theorem starProjection_orthogonalComplement_singleton_eq_zero (v : E) :
(𝕜 ∙ v)ᗮ.starProjection v = 0 := by
rw [starProjection_apply, coe_eq_zero]
exact orthogonalProjection_orthogonalComplement_singleton_eq_zero v
/-- If the orthogonal projection to `K` is well-defined, then a vector splits as the sum of its
orthogonal projections onto a complete submodule `K` and onto the orthogonal complement of `K`. -/
theorem starProjection_add_starProjection_orthogonal [K.HasOrthogonalProjection]
(w : E) : K.starProjection w + Kᗮ.starProjection w = w := by
simp
@[deprecated (since := "2025-07-07")] alias
orthogonalProjection_add_orthogonalProjection_orthogonal :=
starProjection_add_starProjection_orthogonal
/-- The Pythagorean theorem, for an orthogonal projection. -/
theorem norm_sq_eq_add_norm_sq_projection (x : E) (S : Submodule 𝕜 E) [S.HasOrthogonalProjection] :
‖x‖ ^ 2 = ‖S.orthogonalProjection x‖ ^ 2 + ‖Sᗮ.orthogonalProjection x‖ ^ 2 :=
calc
‖x‖ ^ 2 = ‖S.starProjection x + Sᗮ.starProjection x‖ ^ 2 := by
rw [starProjection_add_starProjection_orthogonal]
_ = ‖S.orthogonalProjection x‖ ^ 2 + ‖Sᗮ.orthogonalProjection x‖ ^ 2 := by
simp only [sq]
exact norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero _ _ <|
(S.mem_orthogonal _).1 (Sᗮ.orthogonalProjection x).2 _ (S.orthogonalProjection x).2
theorem norm_sq_eq_add_norm_sq_starProjection (x : E) (S : Submodule 𝕜 E)
[S.HasOrthogonalProjection] :
‖x‖ ^ 2 = ‖S.starProjection x‖ ^ 2 + ‖Sᗮ.starProjection x‖ ^ 2 :=
norm_sq_eq_add_norm_sq_projection x S
theorem mem_iff_norm_starProjection (U : Submodule 𝕜 E)
[U.HasOrthogonalProjection] (v : E) :
v ∈ U ↔ ‖U.starProjection v‖ = ‖v‖ := by
refine ⟨fun h => norm_starProjection_apply _ h, fun h => ?_⟩
simpa [h, sub_eq_zero, eq_comm (a := v), starProjection_eq_self_iff] using
U.norm_sq_eq_add_norm_sq_starProjection v
/-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal
complement sum to the identity. -/
theorem id_eq_sum_starProjection_self_orthogonalComplement [K.HasOrthogonalProjection] :
ContinuousLinearMap.id 𝕜 E =
K.starProjection + Kᗮ.starProjection := by
ext w
exact (K.starProjection_add_starProjection_orthogonal w).symm
@[deprecated (since := "2025-07-07")] alias
id_eq_sum_orthogonalProjection_self_orthogonalComplement :=
id_eq_sum_starProjection_self_orthogonalComplement
-- Porting note: The priority should be higher than `Submodule.coe_inner`.
@[simp high]
theorem inner_orthogonalProjection_eq_of_mem_right [K.HasOrthogonalProjection] (u : K) (v : E) :
⟪K.orthogonalProjection v, u⟫ = ⟪v, u⟫ :=
calc
⟪K.orthogonalProjection v, u⟫ = ⟪K.starProjection v, u⟫ := K.coe_inner _ _
_ = ⟪K.starProjection v, u⟫ + ⟪v - K.starProjection v, u⟫ := by
rw [starProjection_inner_eq_zero _ _ (Submodule.coe_mem _), add_zero]
_ = ⟪v, u⟫ := by rw [← inner_add_left, add_sub_cancel]
-- Porting note: The priority should be higher than `Submodule.coe_inner`.
@[simp high]
theorem inner_orthogonalProjection_eq_of_mem_left [K.HasOrthogonalProjection] (u : K) (v : E) :
⟪u, K.orthogonalProjection v⟫ = ⟪(u : E), v⟫ := by
rw [← inner_conj_symm, ← inner_conj_symm (u : E), inner_orthogonalProjection_eq_of_mem_right]
variable (K)
/-- The orthogonal projection is self-adjoint. -/
theorem inner_starProjection_left_eq_right [K.HasOrthogonalProjection] (u v : E) :
⟪K.starProjection u, v⟫ = ⟪u, K.starProjection v⟫ := by
simp_rw [starProjection_apply, ← inner_orthogonalProjection_eq_of_mem_left,
inner_orthogonalProjection_eq_of_mem_right]
@[deprecated (since := "2025-07-07")] alias
inner_orthogonalProjection_left_eq_right := inner_starProjection_left_eq_right
/-- The orthogonal projection is symmetric. -/
theorem starProjection_isSymmetric [K.HasOrthogonalProjection] :
(K.starProjection : E →ₗ[𝕜] E).IsSymmetric :=
inner_starProjection_left_eq_right K
@[deprecated (since := "2025-07-07")] alias
orthogonalProjection_isSymmetric := starProjection_isSymmetric
theorem starProjection_apply_eq_zero_iff [K.HasOrthogonalProjection] {v : E} :
K.starProjection v = 0 ↔ v ∈ Kᗮ := by
refine ⟨fun h w hw => ?_, fun hv => ?_⟩
· rw [← starProjection_eq_self_iff.mpr hw, inner_starProjection_left_eq_right, h,
inner_zero_right]
· simp [starProjection_apply, orthogonalProjection_mem_subspace_orthogonalComplement_eq_zero hv]
open RCLike
lemma re_inner_starProjection_eq_normSq [K.HasOrthogonalProjection] (v : E) :
re ⟪K.starProjection v, v⟫ = ‖K.orthogonalProjection v‖^2 := by
rw [starProjection_apply,
re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two,
div_eq_iff (NeZero.ne' 2).symm, pow_two, add_sub_assoc, ← eq_sub_iff_add_eq', coe_norm,
← mul_sub_one, show (2 : ℝ) - 1 = 1 by norm_num, mul_one, sub_eq_iff_eq_add', norm_sub_rev]
exact orthogonalProjectionFn_norm_sq K v
@[deprecated (since := "2025-07-07")] alias
re_inner_orthogonalProjection_eq_normSq := re_inner_starProjection_eq_normSq
lemma re_inner_starProjection_nonneg [K.HasOrthogonalProjection] (v : E) :
0 ≤ re ⟪K.starProjection v, v⟫ := by
rw [re_inner_starProjection_eq_normSq K v]
exact sq_nonneg ‖K.orthogonalProjection v‖
@[deprecated (since := "2025-07-07")] alias
re_inner_orthogonalProjection_nonneg := re_inner_starProjection_nonneg
end
end Submodule
|
ExtensiveTopology.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.CategoryTheory.Sites.Coherent.Basic
/-!
# Description of the covering sieves of the extensive topology
This file characterises the covering sieves of the extensive topology.
## Main result
* `extensiveTopology.mem_sieves_iff_contains_colimit_cofan`: a sieve is a covering sieve for the
extensive topology if and only if it contains a finite family of morphisms with fixed target
exhibiting the target as a coproduct of the sources.
-/
open CategoryTheory Limits
variable {C : Type*} [Category C] [FinitaryPreExtensive C]
namespace CategoryTheory
lemma extensiveTopology.mem_sieves_iff_contains_colimit_cofan {X : C} (S : Sieve X) :
S ∈ (extensiveTopology C) X ↔
(∃ (α : Type) (_ : Finite α) (Y : α → C) (π : (a : α) → (Y a ⟶ X)),
Nonempty (IsColimit (Cofan.mk X π)) ∧ (∀ a : α, (S.arrows) (π a))) := by
constructor
· intro h
induction h with
| of X S hS =>
obtain ⟨α, _, Y, π, h, h'⟩ := hS
refine ⟨α, inferInstance, Y, π, ?_, fun a ↦ ?_⟩
· have : IsIso (Sigma.desc (Cofan.mk X π).inj) := by simpa using h'
exact ⟨Cofan.isColimitOfIsIsoSigmaDesc (Cofan.mk X π)⟩
· obtain ⟨rfl, _⟩ := h
exact ⟨Y a, 𝟙 Y a, π a, Presieve.ofArrows.mk a, by simp⟩
| top X =>
refine ⟨Unit, inferInstance, fun _ => X, fun _ => (𝟙 X), ⟨?_⟩, by simp⟩
have : IsIso (Sigma.desc (Cofan.mk X fun (_ : Unit) ↦ 𝟙 X).inj) := by
have : IsIso (coproductUniqueIso (fun () => X)).hom := inferInstance
exact this
exact Cofan.isColimitOfIsIsoSigmaDesc (Cofan.mk X _)
| transitive X R S _ _ a b =>
obtain ⟨α, w, Y₁, π, h, h'⟩ := a
choose β _ Y_n π_n H using fun a => b (h' a)
exact ⟨(Σ a, β a), inferInstance, fun ⟨a,b⟩ => Y_n a b, fun ⟨a, b⟩ => (π_n a b) ≫ (π a),
⟨Limits.Cofan.isColimitTrans _ h.some _ (fun a ↦ (H a).1.some)⟩,
fun c => (H c.fst).2 c.snd⟩
· intro ⟨α, _, Y, π, h, h'⟩
apply (extensiveCoverage C).mem_toGrothendieck_sieves_of_superset (R := Presieve.ofArrows Y π)
· exact fun _ _ hh ↦ by cases hh; exact h' _
· refine ⟨α, inferInstance, Y, π, rfl, ?_⟩
rw [show IsIso (Sigma.desc π) ↔ _ from
Limits.Cofan.isColimit_iff_isIso_sigmaDesc (c := Cofan.mk X π)]
exact h
end CategoryTheory
|
TranslationNumber.lean
|
/-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import Mathlib.Analysis.SpecificLimits.Basic
import Mathlib.Order.Iterate
import Mathlib.Order.SemiconjSup
import Mathlib.Topology.Order.MonotoneContinuity
import Mathlib.Algebra.CharP.Defs
/-!
# Translation number of a monotone real map that commutes with `x ↦ x + 1`
Let `f : ℝ → ℝ` be a monotone map such that `f (x + 1) = f x + 1` for all `x`. Then the limit
$$
\tau(f)=\lim_{n\to\infty}{f^n(x)-x}{n}
$$
exists and does not depend on `x`. This number is called the *translation number* of `f`.
Different authors use different notation for this number: `τ`, `ρ`, `rot`, etc
In this file we define a structure `CircleDeg1Lift` for bundled maps with these properties, define
translation number of `f : CircleDeg1Lift`, prove some estimates relating `f^n(x)-x` to `τ(f)`. In
case of a continuous map `f` we also prove that `f` admits a point `x` such that `f^n(x)=x+m` if and
only if `τ(f)=m/n`.
Maps of this type naturally appear as lifts of orientation preserving circle homeomorphisms. More
precisely, let `f` be an orientation preserving homeomorphism of the circle $S^1=ℝ/ℤ$, and
consider a real number `a` such that
`⟦a⟧ = f 0`, where `⟦⟧` means the natural projection `ℝ → ℝ/ℤ`. Then there exists a unique
continuous function `F : ℝ → ℝ` such that `F 0 = a` and `⟦F x⟧ = f ⟦x⟧` for all `x` (this fact is
not formalized yet). This function is strictly monotone, continuous, and satisfies
`F (x + 1) = F x + 1`. The number `⟦τ F⟧ : ℝ / ℤ` is called the *rotation number* of `f`.
It does not depend on the choice of `a`.
## Main definitions
* `CircleDeg1Lift`: a monotone map `f : ℝ → ℝ` such that `f (x + 1) = f x + 1` for all `x`;
the type `CircleDeg1Lift` is equipped with `Lattice` and `Monoid` structures; the
multiplication is given by composition: `(f * g) x = f (g x)`.
* `CircleDeg1Lift.translationNumber`: translation number of `f : CircleDeg1Lift`.
## Main statements
We prove the following properties of `CircleDeg1Lift.translationNumber`.
* `CircleDeg1Lift.translationNumber_eq_of_dist_bounded`: if the distance between `(f^n) 0`
and `(g^n) 0` is bounded from above uniformly in `n : ℕ`, then `f` and `g` have equal
translation numbers.
* `CircleDeg1Lift.translationNumber_eq_of_semiconjBy`: if two `CircleDeg1Lift` maps `f`, `g`
are semiconjugate by a `CircleDeg1Lift` map, then `τ f = τ g`.
* `CircleDeg1Lift.translationNumber_units_inv`: if `f` is an invertible `CircleDeg1Lift` map
(equivalently, `f` is a lift of an orientation-preserving circle homeomorphism), then
the translation number of `f⁻¹` is the negative of the translation number of `f`.
* `CircleDeg1Lift.translationNumber_mul_of_commute`: if `f` and `g` commute, then
`τ (f * g) = τ f + τ g`.
* `CircleDeg1Lift.translationNumber_eq_rat_iff`: the translation number of `f` is equal to
a rational number `m / n` if and only if `(f^n) x = x + m` for some `x`.
* `CircleDeg1Lift.semiconj_of_bijective_of_translationNumber_eq`: if `f` and `g` are two
bijective `CircleDeg1Lift` maps and their translation numbers are equal, then these
maps are semiconjugate to each other.
* `CircleDeg1Lift.semiconj_of_group_action_of_forall_translationNumber_eq`: let `f₁` and `f₂` be
two actions of a group `G` on the circle by degree 1 maps (formally, `f₁` and `f₂` are two
homomorphisms from `G →* CircleDeg1Lift`). If the translation numbers of `f₁ g` and `f₂ g` are
equal to each other for all `g : G`, then these two actions are semiconjugate by some
`F : CircleDeg1Lift`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes
d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes].
## Notation
We use a local notation `τ` for the translation number of `f : CircleDeg1Lift`.
## Implementation notes
We define the translation number of `f : CircleDeg1Lift` to be the limit of the sequence
`(f ^ (2 ^ n)) 0 / (2 ^ n)`, then prove that `((f ^ n) x - x) / n` tends to this number for any `x`.
This way it is much easier to prove that the limit exists and basic properties of the limit.
We define translation number for a wider class of maps `f : ℝ → ℝ` instead of lifts of orientation
preserving circle homeomorphisms for two reasons:
* non-strictly monotone circle self-maps with discontinuities naturally appear as Poincaré maps
for some flows on the two-torus (e.g., one can take a constant flow and glue in a few Cherry
cells);
* definition and some basic properties still work for this class.
## References
* [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]
## TODO
Here are some short-term goals.
* Introduce a structure or a typeclass for lifts of circle homeomorphisms. We use
`Units CircleDeg1Lift` for now, but it's better to have a dedicated type (or a typeclass?).
* Prove that the `SemiconjBy` relation on circle homeomorphisms is an equivalence relation.
* Introduce `ConditionallyCompleteLattice` structure, use it in the proof of
`CircleDeg1Lift.semiconj_of_group_action_of_forall_translationNumber_eq`.
* Prove that the orbits of the irrational rotation are dense in the circle. Deduce that a
homeomorphism with an irrational rotation is semiconjugate to the corresponding irrational
translation by a continuous `CircleDeg1Lift`.
## Tags
circle homeomorphism, rotation number
-/
open Filter Set Int Topology
open Function hiding Commute
/-!
### Definition and monoid structure
-/
/-- A lift of a monotone degree one map `S¹ → S¹`. -/
structure CircleDeg1Lift : Type extends ℝ →o ℝ where
map_add_one' : ∀ x, toFun (x + 1) = toFun x + 1
namespace CircleDeg1Lift
instance : FunLike CircleDeg1Lift ℝ ℝ where
coe f := f.toFun
coe_injective' | ⟨⟨_, _⟩, _⟩, ⟨⟨_, _⟩, _⟩, rfl => rfl
instance : OrderHomClass CircleDeg1Lift ℝ ℝ where
map_rel f _ _ h := f.monotone' h
@[simp] theorem coe_mk (f h) : ⇑(mk f h) = f := rfl
variable (f g : CircleDeg1Lift)
@[simp] theorem coe_toOrderHom : ⇑f.toOrderHom = f := rfl
protected theorem monotone : Monotone f := f.monotone'
@[mono] theorem mono {x y} (h : x ≤ y) : f x ≤ f y := f.monotone h
theorem strictMono_iff_injective : StrictMono f ↔ Injective f :=
f.monotone.strictMono_iff_injective
@[simp]
theorem map_add_one : ∀ x, f (x + 1) = f x + 1 :=
f.map_add_one'
@[simp]
theorem map_one_add (x : ℝ) : f (1 + x) = 1 + f x := by rw [add_comm, map_add_one, add_comm 1]
@[ext]
theorem ext ⦃f g : CircleDeg1Lift⦄ (h : ∀ x, f x = g x) : f = g :=
DFunLike.ext f g h
instance : Monoid CircleDeg1Lift where
mul f g :=
{ toOrderHom := f.1.comp g.1
map_add_one' := fun x => by simp [map_add_one] }
one := ⟨.id, fun _ => rfl⟩
mul_one _ := rfl
one_mul _ := rfl
mul_assoc _ _ _ := DFunLike.coe_injective rfl
instance : Inhabited CircleDeg1Lift := ⟨1⟩
@[simp]
theorem coe_mul : ⇑(f * g) = f ∘ g :=
rfl
theorem mul_apply (x) : (f * g) x = f (g x) :=
rfl
@[simp]
theorem coe_one : ⇑(1 : CircleDeg1Lift) = id :=
rfl
instance unitsHasCoeToFun : CoeFun CircleDeg1Liftˣ fun _ => ℝ → ℝ :=
⟨fun f => ⇑(f : CircleDeg1Lift)⟩
@[simp]
theorem units_inv_apply_apply (f : CircleDeg1Liftˣ) (x : ℝ) :
(f⁻¹ : CircleDeg1Liftˣ) (f x) = x := by simp only [← mul_apply, f.inv_mul, coe_one, id]
@[simp]
theorem units_apply_inv_apply (f : CircleDeg1Liftˣ) (x : ℝ) :
f ((f⁻¹ : CircleDeg1Liftˣ) x) = x := by simp only [← mul_apply, f.mul_inv, coe_one, id]
/-- If a lift of a circle map is bijective, then it is an order automorphism of the line. -/
def toOrderIso : CircleDeg1Liftˣ →* ℝ ≃o ℝ where
toFun f :=
{ toFun := f
invFun := ⇑f⁻¹
left_inv := units_inv_apply_apply f
right_inv := units_apply_inv_apply f
map_rel_iff' := ⟨fun h => by simpa using mono (↑f⁻¹) h, mono f⟩ }
map_one' := rfl
map_mul' _ _ := rfl
@[simp]
theorem coe_toOrderIso (f : CircleDeg1Liftˣ) : ⇑(toOrderIso f) = f :=
rfl
@[simp]
theorem coe_toOrderIso_symm (f : CircleDeg1Liftˣ) :
⇑(toOrderIso f).symm = (f⁻¹ : CircleDeg1Liftˣ) :=
rfl
@[simp]
theorem coe_toOrderIso_inv (f : CircleDeg1Liftˣ) : ⇑(toOrderIso f)⁻¹ = (f⁻¹ : CircleDeg1Liftˣ) :=
rfl
theorem isUnit_iff_bijective {f : CircleDeg1Lift} : IsUnit f ↔ Bijective f :=
⟨fun ⟨u, h⟩ => h ▸ (toOrderIso u).bijective, fun h =>
Units.isUnit
{ val := f
inv :=
{ toFun := (Equiv.ofBijective f h).symm
monotone' := fun x y hxy =>
(f.strictMono_iff_injective.2 h.1).le_iff_le.1
(by simp only [Equiv.ofBijective_apply_symm_apply f h, hxy])
map_add_one' := fun x =>
h.1 <| by simp only [Equiv.ofBijective_apply_symm_apply f, f.map_add_one] }
val_inv := ext <| Equiv.ofBijective_apply_symm_apply f h
inv_val := ext <| Equiv.ofBijective_symm_apply_apply f h }⟩
theorem coe_pow : ∀ n : ℕ, ⇑(f ^ n) = f^[n]
| 0 => rfl
| n + 1 => by
ext x
simp [coe_pow n, pow_succ]
theorem semiconjBy_iff_semiconj {f g₁ g₂ : CircleDeg1Lift} :
SemiconjBy f g₁ g₂ ↔ Semiconj f g₁ g₂ :=
CircleDeg1Lift.ext_iff
theorem commute_iff_commute {f g : CircleDeg1Lift} : Commute f g ↔ Function.Commute f g :=
CircleDeg1Lift.ext_iff
/-!
### Translate by a constant
-/
/-- The map `y ↦ x + y` as a `CircleDeg1Lift`. More precisely, we define a homomorphism from
`Multiplicative ℝ` to `CircleDeg1Liftˣ`, so the translation by `x` is
`translation (Multiplicative.ofAdd x)`. -/
def translate : Multiplicative ℝ →* CircleDeg1Liftˣ := MonoidHom.toHomUnits <|
{ toFun := fun x =>
⟨⟨fun y => x.toAdd + y, fun _ _ h => add_le_add_left h _⟩, fun _ =>
(add_assoc _ _ _).symm⟩
map_one' := ext <| zero_add
map_mul' := fun _ _ => ext <| add_assoc _ _ }
@[simp]
theorem translate_apply (x y : ℝ) : translate (Multiplicative.ofAdd x) y = x + y :=
rfl
@[simp]
theorem translate_inv_apply (x y : ℝ) : (translate <| Multiplicative.ofAdd x)⁻¹ y = -x + y :=
rfl
@[simp]
theorem translate_zpow (x : ℝ) (n : ℤ) :
translate (Multiplicative.ofAdd x) ^ n = translate (Multiplicative.ofAdd <| ↑n * x) := by
simp only [← zsmul_eq_mul, ofAdd_zsmul, MonoidHom.map_zpow]
@[simp]
theorem translate_pow (x : ℝ) (n : ℕ) :
translate (Multiplicative.ofAdd x) ^ n = translate (Multiplicative.ofAdd <| ↑n * x) :=
translate_zpow x n
@[simp]
theorem translate_iterate (x : ℝ) (n : ℕ) :
(translate (Multiplicative.ofAdd x))^[n] = translate (Multiplicative.ofAdd <| ↑n * x) := by
rw [← coe_pow, ← Units.val_pow_eq_pow_val, translate_pow]
/-!
### Commutativity with integer translations
In this section we prove that `f` commutes with translations by an integer number.
First we formulate these statements (for a natural or an integer number,
addition on the left or on the right, addition or subtraction) using `Function.Commute`,
then reformulate as `simp` lemmas `map_int_add` etc.
-/
theorem commute_nat_add (n : ℕ) : Function.Commute f (n + ·) := by
simpa only [nsmul_one, add_left_iterate] using Function.Commute.iterate_right f.map_one_add n
theorem commute_add_nat (n : ℕ) : Function.Commute f (· + n) := by
simp only [add_comm _ (n : ℝ), f.commute_nat_add n]
theorem commute_sub_nat (n : ℕ) : Function.Commute f (· - n) := by
simpa only [sub_eq_add_neg] using
(f.commute_add_nat n).inverses_right (Equiv.addRight _).right_inv (Equiv.addRight _).left_inv
theorem commute_add_int : ∀ n : ℤ, Function.Commute f (· + n)
| (n : ℕ) => f.commute_add_nat n
| -[n+1] => by simpa [sub_eq_add_neg] using f.commute_sub_nat (n + 1)
theorem commute_int_add (n : ℤ) : Function.Commute f (n + ·) := by
simpa only [add_comm _ (n : ℝ)] using f.commute_add_int n
theorem commute_sub_int (n : ℤ) : Function.Commute f (· - n) := by
simpa only [sub_eq_add_neg] using
(f.commute_add_int n).inverses_right (Equiv.addRight _).right_inv (Equiv.addRight _).left_inv
@[simp]
theorem map_int_add (m : ℤ) (x : ℝ) : f (m + x) = m + f x :=
f.commute_int_add m x
@[simp]
theorem map_add_int (x : ℝ) (m : ℤ) : f (x + m) = f x + m :=
f.commute_add_int m x
@[simp]
theorem map_sub_int (x : ℝ) (n : ℤ) : f (x - n) = f x - n :=
f.commute_sub_int n x
@[simp]
theorem map_add_nat (x : ℝ) (n : ℕ) : f (x + n) = f x + n :=
f.map_add_int x n
@[simp]
theorem map_nat_add (n : ℕ) (x : ℝ) : f (n + x) = n + f x :=
f.map_int_add n x
@[simp]
theorem map_sub_nat (x : ℝ) (n : ℕ) : f (x - n) = f x - n :=
f.map_sub_int x n
theorem map_int_of_map_zero (n : ℤ) : f n = f 0 + n := by rw [← f.map_add_int, zero_add]
@[simp]
theorem map_fract_sub_fract_eq (x : ℝ) : f (fract x) - fract x = f x - x := by
rw [Int.fract, f.map_sub_int, sub_sub_sub_cancel_right]
/-!
### Pointwise order on circle maps
-/
/-- Monotone circle maps form a lattice with respect to the pointwise order -/
noncomputable instance : Lattice CircleDeg1Lift where
sup f g :=
{ toFun := fun x => max (f x) (g x)
monotone' := fun _ _ h => max_le_max (f.mono h) (g.mono h)
-- TODO: generalize to `Monotone.max`
map_add_one' := fun x => by simp [max_add_add_right] }
le f g := ∀ x, f x ≤ g x
le_refl f x := le_refl (f x)
le_trans _ _ _ h₁₂ h₂₃ x := le_trans (h₁₂ x) (h₂₃ x)
le_antisymm _ _ h₁₂ h₂₁ := ext fun x => le_antisymm (h₁₂ x) (h₂₁ x)
le_sup_left f g x := le_max_left (f x) (g x)
le_sup_right f g x := le_max_right (f x) (g x)
sup_le _ _ _ h₁ h₂ x := max_le (h₁ x) (h₂ x)
inf f g :=
{ toFun := fun x => min (f x) (g x)
monotone' := fun _ _ h => min_le_min (f.mono h) (g.mono h)
map_add_one' := fun x => by simp [min_add_add_right] }
inf_le_left f g x := min_le_left (f x) (g x)
inf_le_right f g x := min_le_right (f x) (g x)
le_inf _ _ _ h₂ h₃ x := le_min (h₂ x) (h₃ x)
@[simp]
theorem sup_apply (x : ℝ) : (f ⊔ g) x = max (f x) (g x) :=
rfl
@[simp]
theorem inf_apply (x : ℝ) : (f ⊓ g) x = min (f x) (g x) :=
rfl
theorem iterate_monotone (n : ℕ) : Monotone fun f : CircleDeg1Lift => f^[n] := fun f _ h =>
f.monotone.iterate_le_of_le h _
theorem iterate_mono {f g : CircleDeg1Lift} (h : f ≤ g) (n : ℕ) : f^[n] ≤ g^[n] :=
iterate_monotone n h
theorem pow_mono {f g : CircleDeg1Lift} (h : f ≤ g) (n : ℕ) : f ^ n ≤ g ^ n := fun x => by
simp only [coe_pow, iterate_mono h n x]
theorem pow_monotone (n : ℕ) : Monotone fun f : CircleDeg1Lift => f ^ n := fun _ _ h => pow_mono h n
/-!
### Estimates on `(f * g) 0`
We prove the estimates `f 0 + ⌊g 0⌋ ≤ f (g 0) ≤ f 0 + ⌈g 0⌉` and some corollaries with added/removed
floors and ceils.
We also prove that for two semiconjugate maps `g₁`, `g₂`, the distance between `g₁ 0` and `g₂ 0`
is less than two.
-/
theorem map_le_of_map_zero (x : ℝ) : f x ≤ f 0 + ⌈x⌉ :=
calc
f x ≤ f ⌈x⌉ := f.monotone <| le_ceil _
_ = f 0 + ⌈x⌉ := f.map_int_of_map_zero _
theorem map_map_zero_le : f (g 0) ≤ f 0 + ⌈g 0⌉ :=
f.map_le_of_map_zero (g 0)
theorem floor_map_map_zero_le : ⌊f (g 0)⌋ ≤ ⌊f 0⌋ + ⌈g 0⌉ :=
calc
⌊f (g 0)⌋ ≤ ⌊f 0 + ⌈g 0⌉⌋ := floor_mono <| f.map_map_zero_le g
_ = ⌊f 0⌋ + ⌈g 0⌉ := floor_add_intCast _ _
theorem ceil_map_map_zero_le : ⌈f (g 0)⌉ ≤ ⌈f 0⌉ + ⌈g 0⌉ :=
calc
⌈f (g 0)⌉ ≤ ⌈f 0 + ⌈g 0⌉⌉ := ceil_mono <| f.map_map_zero_le g
_ = ⌈f 0⌉ + ⌈g 0⌉ := ceil_add_intCast _ _
theorem map_map_zero_lt : f (g 0) < f 0 + g 0 + 1 :=
calc
f (g 0) ≤ f 0 + ⌈g 0⌉ := f.map_map_zero_le g
_ < f 0 + (g 0 + 1) := add_lt_add_left (ceil_lt_add_one _) _
_ = f 0 + g 0 + 1 := (add_assoc _ _ _).symm
theorem le_map_of_map_zero (x : ℝ) : f 0 + ⌊x⌋ ≤ f x :=
calc
f 0 + ⌊x⌋ = f ⌊x⌋ := (f.map_int_of_map_zero _).symm
_ ≤ f x := f.monotone <| floor_le _
theorem le_map_map_zero : f 0 + ⌊g 0⌋ ≤ f (g 0) :=
f.le_map_of_map_zero (g 0)
theorem le_floor_map_map_zero : ⌊f 0⌋ + ⌊g 0⌋ ≤ ⌊f (g 0)⌋ :=
calc
⌊f 0⌋ + ⌊g 0⌋ = ⌊f 0 + ⌊g 0⌋⌋ := (floor_add_intCast _ _).symm
_ ≤ ⌊f (g 0)⌋ := floor_mono <| f.le_map_map_zero g
theorem le_ceil_map_map_zero : ⌈f 0⌉ + ⌊g 0⌋ ≤ ⌈(f * g) 0⌉ :=
calc
⌈f 0⌉ + ⌊g 0⌋ = ⌈f 0 + ⌊g 0⌋⌉ := (ceil_add_intCast _ _).symm
_ ≤ ⌈f (g 0)⌉ := ceil_mono <| f.le_map_map_zero g
theorem lt_map_map_zero : f 0 + g 0 - 1 < f (g 0) :=
calc
f 0 + g 0 - 1 = f 0 + (g 0 - 1) := add_sub_assoc _ _ _
_ < f 0 + ⌊g 0⌋ := add_lt_add_left (sub_one_lt_floor _) _
_ ≤ f (g 0) := f.le_map_map_zero g
theorem dist_map_map_zero_lt : dist (f 0 + g 0) (f (g 0)) < 1 := by
rw [dist_comm, Real.dist_eq, abs_lt, lt_sub_iff_add_lt', sub_lt_iff_lt_add', ← sub_eq_add_neg]
exact ⟨f.lt_map_map_zero g, f.map_map_zero_lt g⟩
theorem dist_map_zero_lt_of_semiconj {f g₁ g₂ : CircleDeg1Lift} (h : Function.Semiconj f g₁ g₂) :
dist (g₁ 0) (g₂ 0) < 2 :=
calc
dist (g₁ 0) (g₂ 0) ≤ dist (g₁ 0) (f (g₁ 0) - f 0) + dist _ (g₂ 0) := dist_triangle _ _ _
_ = dist (f 0 + g₁ 0) (f (g₁ 0)) + dist (g₂ 0 + f 0) (g₂ (f 0)) := by
simp only [h.eq, Real.dist_eq, sub_sub, add_comm (f 0), sub_sub_eq_add_sub,
abs_sub_comm (g₂ (f 0))]
_ < 1 + 1 := add_lt_add (f.dist_map_map_zero_lt g₁) (g₂.dist_map_map_zero_lt f)
_ = 2 := one_add_one_eq_two
theorem dist_map_zero_lt_of_semiconjBy {f g₁ g₂ : CircleDeg1Lift} (h : SemiconjBy f g₁ g₂) :
dist (g₁ 0) (g₂ 0) < 2 :=
dist_map_zero_lt_of_semiconj <| semiconjBy_iff_semiconj.1 h
/-!
### Limits at infinities and continuity
-/
protected theorem tendsto_atBot : Tendsto f atBot atBot :=
tendsto_atBot_mono f.map_le_of_map_zero <| tendsto_atBot_add_const_left _ _ <|
(tendsto_atBot_mono fun x => (ceil_lt_add_one x).le) <|
tendsto_atBot_add_const_right _ _ tendsto_id
protected theorem tendsto_atTop : Tendsto f atTop atTop :=
tendsto_atTop_mono f.le_map_of_map_zero <| tendsto_atTop_add_const_left _ _ <|
(tendsto_atTop_mono fun x => (sub_one_lt_floor x).le) <| by
simpa [sub_eq_add_neg] using tendsto_atTop_add_const_right _ _ tendsto_id
theorem continuous_iff_surjective : Continuous f ↔ Function.Surjective f :=
⟨fun h => h.surjective f.tendsto_atTop f.tendsto_atBot, f.monotone.continuous_of_surjective⟩
/-!
### Estimates on `(f^n) x`
If we know that `f x` is `≤`/`<`/`≥`/`>`/`=` to `x + m`, then we have a similar estimate on
`f^[n] x` and `x + n * m`.
For `≤`, `≥`, and `=` we formulate both `of` (implication) and `iff` versions because implications
work for `n = 0`. For `<` and `>` we formulate only `iff` versions.
-/
theorem iterate_le_of_map_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) (n : ℕ) :
f^[n] x ≤ x + n * m := by
simpa only [nsmul_eq_mul, add_right_iterate] using
(f.commute_add_int m).iterate_le_of_map_le f.monotone (monotone_id.add_const (m : ℝ)) h n
theorem le_iterate_of_add_int_le_map {x : ℝ} {m : ℤ} (h : x + m ≤ f x) (n : ℕ) :
x + n * m ≤ f^[n] x := by
simpa only [nsmul_eq_mul, add_right_iterate] using
(f.commute_add_int m).symm.iterate_le_of_map_le (monotone_id.add_const (m : ℝ)) f.monotone h n
theorem iterate_eq_of_map_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) (n : ℕ) :
f^[n] x = x + n * m := by
simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_eq_of_map_eq n h
theorem iterate_pos_le_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) :
f^[n] x ≤ x + n * m ↔ f x ≤ x + m := by
simpa only [nsmul_eq_mul, add_right_iterate] using
(f.commute_add_int m).iterate_pos_le_iff_map_le f.monotone (strictMono_id.add_const (m : ℝ)) hn
theorem iterate_pos_lt_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) :
f^[n] x < x + n * m ↔ f x < x + m := by
simpa only [nsmul_eq_mul, add_right_iterate] using
(f.commute_add_int m).iterate_pos_lt_iff_map_lt f.monotone (strictMono_id.add_const (m : ℝ)) hn
theorem iterate_pos_eq_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) :
f^[n] x = x + n * m ↔ f x = x + m := by
simpa only [nsmul_eq_mul, add_right_iterate] using
(f.commute_add_int m).iterate_pos_eq_iff_map_eq f.monotone (strictMono_id.add_const (m : ℝ)) hn
theorem le_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) :
x + n * m ≤ f^[n] x ↔ x + m ≤ f x := by
simpa only [not_lt] using not_congr (f.iterate_pos_lt_iff hn)
theorem lt_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) :
x + n * m < f^[n] x ↔ x + m < f x := by
simpa only [not_le] using not_congr (f.iterate_pos_le_iff hn)
theorem mul_floor_map_zero_le_floor_iterate_zero (n : ℕ) : ↑n * ⌊f 0⌋ ≤ ⌊f^[n] 0⌋ := by
rw [le_floor, Int.cast_mul, Int.cast_natCast, ← zero_add ((n : ℝ) * _)]
apply le_iterate_of_add_int_le_map
simp [floor_le]
/-!
### Definition of translation number
-/
noncomputable section
/-- An auxiliary sequence used to define the translation number. -/
def transnumAuxSeq (n : ℕ) : ℝ :=
(f ^ (2 ^ n : ℕ)) 0 / 2 ^ n
/-- The translation number of a `CircleDeg1Lift`, $τ(f)=\lim_{n→∞}\frac{f^n(x)-x}{n}$. We use
an auxiliary sequence `\frac{f^{2^n}(0)}{2^n}` to define `τ(f)` because some proofs are simpler
this way. -/
def translationNumber : ℝ :=
limUnder atTop f.transnumAuxSeq
end
-- TODO: choose two different symbols for `CircleDeg1Lift.translationNumber` and the future
-- `circle_mono_homeo.rotation_number`, then make them `localized notation`s
local notation "τ" => translationNumber
theorem transnumAuxSeq_def : f.transnumAuxSeq = fun n : ℕ => (f ^ (2 ^ n : ℕ)) 0 / 2 ^ n :=
rfl
theorem translationNumber_eq_of_tendsto_aux {τ' : ℝ} (h : Tendsto f.transnumAuxSeq atTop (𝓝 τ')) :
τ f = τ' :=
h.limUnder_eq
theorem translationNumber_eq_of_tendsto₀ {τ' : ℝ}
(h : Tendsto (fun n : ℕ => f^[n] 0 / n) atTop (𝓝 τ')) : τ f = τ' :=
f.translationNumber_eq_of_tendsto_aux <| by
simpa [Function.comp_def, transnumAuxSeq_def, coe_pow] using
h.comp (Nat.tendsto_pow_atTop_atTop_of_one_lt one_lt_two)
theorem translationNumber_eq_of_tendsto₀' {τ' : ℝ}
(h : Tendsto (fun n : ℕ => f^[n + 1] 0 / (n + 1)) atTop (𝓝 τ')) : τ f = τ' :=
f.translationNumber_eq_of_tendsto₀ <| (tendsto_add_atTop_iff_nat 1).1 (mod_cast h)
theorem transnumAuxSeq_zero : f.transnumAuxSeq 0 = f 0 := by simp [transnumAuxSeq]
theorem transnumAuxSeq_dist_lt (n : ℕ) :
dist (f.transnumAuxSeq n) (f.transnumAuxSeq (n + 1)) < 1 / 2 / 2 ^ n := by
have : 0 < (2 ^ (n + 1) : ℝ) := pow_pos zero_lt_two _
rw [div_div, ← pow_succ', ← abs_of_pos this]
calc
_ = dist ((f ^ 2 ^ n) 0 + (f ^ 2 ^ n) 0) ((f ^ 2 ^ n) ((f ^ 2 ^ n) 0)) / |2 ^ (n + 1)| := by
simp_rw [transnumAuxSeq, Real.dist_eq]
rw [← abs_div, sub_div, pow_succ, pow_succ', ← two_mul, mul_div_mul_left _ _ (two_ne_zero' ℝ),
pow_mul, sq, mul_apply]
_ < _ := by gcongr; exact (f ^ 2 ^ n).dist_map_map_zero_lt (f ^ 2 ^ n)
theorem tendsto_translationNumber_aux : Tendsto f.transnumAuxSeq atTop (𝓝 <| τ f) :=
(cauchySeq_of_le_geometric_two fun n => le_of_lt <| f.transnumAuxSeq_dist_lt n).tendsto_limUnder
theorem dist_map_zero_translationNumber_le : dist (f 0) (τ f) ≤ 1 :=
f.transnumAuxSeq_zero ▸
dist_le_of_le_geometric_two_of_tendsto₀ (fun n => le_of_lt <| f.transnumAuxSeq_dist_lt n)
f.tendsto_translationNumber_aux
theorem tendsto_translationNumber_of_dist_bounded_aux (x : ℕ → ℝ) (C : ℝ)
(H : ∀ n : ℕ, dist ((f ^ n) 0) (x n) ≤ C) :
Tendsto (fun n : ℕ => x (2 ^ n) / 2 ^ n) atTop (𝓝 <| τ f) := by
apply f.tendsto_translationNumber_aux.congr_dist (squeeze_zero (fun _ => dist_nonneg) _ _)
· exact fun n => C / 2 ^ n
· intro n
have : 0 < (2 ^ n : ℝ) := pow_pos zero_lt_two _
convert (div_le_div_iff_of_pos_right this).2 (H (2 ^ n)) using 1
rw [transnumAuxSeq, Real.dist_eq, ← sub_div, abs_div, abs_of_pos this, Real.dist_eq]
· exact mul_zero C ▸ tendsto_const_nhds.mul <| tendsto_inv_atTop_zero.comp <|
tendsto_pow_atTop_atTop_of_one_lt one_lt_two
theorem translationNumber_eq_of_dist_bounded {f g : CircleDeg1Lift} (C : ℝ)
(H : ∀ n : ℕ, dist ((f ^ n) 0) ((g ^ n) 0) ≤ C) : τ f = τ g :=
Eq.symm <| g.translationNumber_eq_of_tendsto_aux <|
f.tendsto_translationNumber_of_dist_bounded_aux (fun n ↦ (g ^ n) 0) C H
@[simp]
theorem translationNumber_one : τ 1 = 0 :=
translationNumber_eq_of_tendsto₀ _ <| by simp
theorem translationNumber_eq_of_semiconjBy {f g₁ g₂ : CircleDeg1Lift} (H : SemiconjBy f g₁ g₂) :
τ g₁ = τ g₂ :=
translationNumber_eq_of_dist_bounded 2 fun n =>
le_of_lt <| dist_map_zero_lt_of_semiconjBy <| H.pow_right n
theorem translationNumber_eq_of_semiconj {f g₁ g₂ : CircleDeg1Lift}
(H : Function.Semiconj f g₁ g₂) : τ g₁ = τ g₂ :=
translationNumber_eq_of_semiconjBy <| semiconjBy_iff_semiconj.2 H
theorem translationNumber_mul_of_commute {f g : CircleDeg1Lift} (h : Commute f g) :
τ (f * g) = τ f + τ g := by
refine tendsto_nhds_unique ?_
(f.tendsto_translationNumber_aux.add g.tendsto_translationNumber_aux)
simp only [transnumAuxSeq, ← add_div]
refine (f * g).tendsto_translationNumber_of_dist_bounded_aux
(fun n ↦ (f ^ n) 0 + (g ^ n) 0) 1 fun n ↦ ?_
rw [h.mul_pow, dist_comm]
exact le_of_lt ((f ^ n).dist_map_map_zero_lt (g ^ n))
@[simp]
theorem translationNumber_units_inv (f : CircleDeg1Liftˣ) : τ ↑f⁻¹ = -τ f :=
eq_neg_iff_add_eq_zero.2 <| by
simp [← translationNumber_mul_of_commute (Commute.refl _).units_inv_left]
@[simp]
theorem translationNumber_pow : ∀ n : ℕ, τ (f ^ n) = n * τ f
| 0 => by simp
| n + 1 => by
rw [pow_succ, translationNumber_mul_of_commute (Commute.pow_self f n),
translationNumber_pow n, Nat.cast_add_one, add_mul, one_mul]
@[simp]
theorem translationNumber_zpow (f : CircleDeg1Liftˣ) : ∀ n : ℤ, τ (f ^ n : Units _) = n * τ f
| (n : ℕ) => by simp [translationNumber_pow f n]
| -[n+1] => by simp; ring
@[simp]
theorem translationNumber_conj_eq (f : CircleDeg1Liftˣ) (g : CircleDeg1Lift) :
τ (↑f * g * ↑f⁻¹) = τ g :=
(translationNumber_eq_of_semiconjBy (f.mk_semiconjBy g)).symm
@[simp]
theorem translationNumber_conj_eq' (f : CircleDeg1Liftˣ) (g : CircleDeg1Lift) :
τ (↑f⁻¹ * g * f) = τ g :=
translationNumber_conj_eq f⁻¹ g
theorem dist_pow_map_zero_mul_translationNumber_le (n : ℕ) :
dist ((f ^ n) 0) (n * f.translationNumber) ≤ 1 :=
f.translationNumber_pow n ▸ (f ^ n).dist_map_zero_translationNumber_le
theorem tendsto_translation_number₀' :
Tendsto (fun n : ℕ => (f ^ (n + 1) : CircleDeg1Lift) 0 / ((n : ℝ) + 1)) atTop (𝓝 <| τ f) := by
refine
tendsto_iff_dist_tendsto_zero.2 <|
squeeze_zero (fun _ => dist_nonneg) (fun n => ?_)
((tendsto_const_div_atTop_nhds_zero_nat 1).comp (tendsto_add_atTop_nat 1))
dsimp
have : (0 : ℝ) < n + 1 := n.cast_add_one_pos
rw [Real.dist_eq, div_sub' (ne_of_gt this), abs_div, ← Real.dist_eq, abs_of_pos this,
Nat.cast_add_one, div_le_div_iff_of_pos_right this, ← Nat.cast_add_one]
apply dist_pow_map_zero_mul_translationNumber_le
theorem tendsto_translation_number₀ : Tendsto (fun n : ℕ => (f ^ n) 0 / n) atTop (𝓝 <| τ f) :=
(tendsto_add_atTop_iff_nat 1).1 (mod_cast f.tendsto_translation_number₀')
/-- For any `x : ℝ` the sequence $\frac{f^n(x)-x}{n}$ tends to the translation number of `f`.
In particular, this limit does not depend on `x`. -/
theorem tendsto_translationNumber (x : ℝ) :
Tendsto (fun n : ℕ => ((f ^ n) x - x) / n) atTop (𝓝 <| τ f) := by
rw [← translationNumber_conj_eq' (translate <| Multiplicative.ofAdd x)]
refine (tendsto_translation_number₀ _).congr fun n ↦ ?_
simp [sub_eq_neg_add, Units.conj_pow']
theorem tendsto_translation_number' (x : ℝ) :
Tendsto (fun n : ℕ => ((f ^ (n + 1) : CircleDeg1Lift) x - x) / (n + 1)) atTop (𝓝 <| τ f) :=
mod_cast (tendsto_add_atTop_iff_nat 1).2 (f.tendsto_translationNumber x)
theorem translationNumber_mono : Monotone τ := fun f g h =>
le_of_tendsto_of_tendsto' f.tendsto_translation_number₀ g.tendsto_translation_number₀ fun n => by
gcongr; exact pow_mono h _ _
theorem translationNumber_translate (x : ℝ) : τ (translate <| Multiplicative.ofAdd x) = x :=
translationNumber_eq_of_tendsto₀' _ <| by
simp only [translate_iterate, translate_apply, add_zero, Nat.cast_succ,
mul_div_cancel_left₀ (M₀ := ℝ) _ (Nat.cast_add_one_ne_zero _), tendsto_const_nhds]
theorem translationNumber_le_of_le_add {z : ℝ} (hz : ∀ x, f x ≤ x + z) : τ f ≤ z :=
translationNumber_translate z ▸ translationNumber_mono fun x => (hz x).trans_eq (add_comm _ _)
theorem le_translationNumber_of_add_le {z : ℝ} (hz : ∀ x, x + z ≤ f x) : z ≤ τ f :=
translationNumber_translate z ▸ translationNumber_mono fun x => (add_comm _ _).trans_le (hz x)
theorem translationNumber_le_of_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) : τ f ≤ m :=
le_of_tendsto' (f.tendsto_translation_number' x) fun n =>
(div_le_iff₀' (n.cast_add_one_pos : (0 : ℝ) < _)).mpr <| sub_le_iff_le_add'.2 <|
(coe_pow f (n + 1)).symm ▸ @Nat.cast_add_one ℝ _ n ▸ f.iterate_le_of_map_le_add_int h (n + 1)
theorem translationNumber_le_of_le_add_nat {x : ℝ} {m : ℕ} (h : f x ≤ x + m) : τ f ≤ m :=
@translationNumber_le_of_le_add_int f x m h
theorem le_translationNumber_of_add_int_le {x : ℝ} {m : ℤ} (h : x + m ≤ f x) : ↑m ≤ τ f :=
ge_of_tendsto' (f.tendsto_translation_number' x) fun n =>
(le_div_iff₀ (n.cast_add_one_pos : (0 : ℝ) < _)).mpr <| le_sub_iff_add_le'.2 <| by
simp only [coe_pow, mul_comm (m : ℝ), ← Nat.cast_add_one, f.le_iterate_of_add_int_le_map h]
theorem le_translationNumber_of_add_nat_le {x : ℝ} {m : ℕ} (h : x + m ≤ f x) : ↑m ≤ τ f :=
@le_translationNumber_of_add_int_le f x m h
/-- If `f x - x` is an integer number `m` for some point `x`, then `τ f = m`.
On the circle this means that a map with a fixed point has rotation number zero. -/
theorem translationNumber_of_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) : τ f = m :=
le_antisymm (translationNumber_le_of_le_add_int f <| le_of_eq h)
(le_translationNumber_of_add_int_le f <| le_of_eq h.symm)
theorem floor_sub_le_translationNumber (x : ℝ) : ↑⌊f x - x⌋ ≤ τ f :=
le_translationNumber_of_add_int_le f <| le_sub_iff_add_le'.1 (floor_le <| f x - x)
theorem translationNumber_le_ceil_sub (x : ℝ) : τ f ≤ ⌈f x - x⌉ :=
translationNumber_le_of_le_add_int f <| sub_le_iff_le_add'.1 (le_ceil <| f x - x)
theorem map_lt_of_translationNumber_lt_int {n : ℤ} (h : τ f < n) (x : ℝ) : f x < x + n :=
not_le.1 <| mt f.le_translationNumber_of_add_int_le <| not_le.2 h
theorem map_lt_of_translationNumber_lt_nat {n : ℕ} (h : τ f < n) (x : ℝ) : f x < x + n :=
@map_lt_of_translationNumber_lt_int f n h x
theorem map_lt_add_floor_translationNumber_add_one (x : ℝ) : f x < x + ⌊τ f⌋ + 1 := by
rw [add_assoc]
norm_cast
refine map_lt_of_translationNumber_lt_int _ ?_ _
push_cast
exact lt_floor_add_one _
theorem map_lt_add_translationNumber_add_one (x : ℝ) : f x < x + τ f + 1 :=
calc
f x < x + ⌊τ f⌋ + 1 := f.map_lt_add_floor_translationNumber_add_one x
_ ≤ x + τ f + 1 := by gcongr; apply floor_le
theorem lt_map_of_int_lt_translationNumber {n : ℤ} (h : ↑n < τ f) (x : ℝ) : x + n < f x :=
not_le.1 <| mt f.translationNumber_le_of_le_add_int <| not_le.2 h
theorem lt_map_of_nat_lt_translationNumber {n : ℕ} (h : ↑n < τ f) (x : ℝ) : x + n < f x :=
@lt_map_of_int_lt_translationNumber f n h x
/-- If `f^n x - x`, `n > 0`, is an integer number `m` for some point `x`, then
`τ f = m / n`. On the circle this means that a map with a periodic orbit has
a rational rotation number. -/
theorem translationNumber_of_map_pow_eq_add_int {x : ℝ} {n : ℕ} {m : ℤ} (h : (f ^ n) x = x + m)
(hn : 0 < n) : τ f = m / n := by
have := (f ^ n).translationNumber_of_eq_add_int h
rwa [translationNumber_pow, mul_comm, ← eq_div_iff] at this
exact Nat.cast_ne_zero.2 (ne_of_gt hn)
/-- If a predicate depends only on `f x - x` and holds for all `0 ≤ x ≤ 1`,
then it holds for all `x`. -/
theorem forall_map_sub_of_Icc (P : ℝ → Prop) (h : ∀ x ∈ Icc (0 : ℝ) 1, P (f x - x)) (x : ℝ) :
P (f x - x) :=
f.map_fract_sub_fract_eq x ▸ h _ ⟨fract_nonneg _, le_of_lt (fract_lt_one _)⟩
theorem translationNumber_lt_of_forall_lt_add (hf : Continuous f) {z : ℝ} (hz : ∀ x, f x < x + z) :
τ f < z := by
obtain ⟨x, -, hx⟩ : ∃ x ∈ Icc (0 : ℝ) 1, ∀ y ∈ Icc (0 : ℝ) 1, f y - y ≤ f x - x :=
isCompact_Icc.exists_isMaxOn (nonempty_Icc.2 zero_le_one)
(hf.sub continuous_id).continuousOn
refine lt_of_le_of_lt ?_ (sub_lt_iff_lt_add'.2 <| hz x)
apply translationNumber_le_of_le_add
simp only [← sub_le_iff_le_add']
exact f.forall_map_sub_of_Icc (fun a => a ≤ f x - x) hx
theorem lt_translationNumber_of_forall_add_lt (hf : Continuous f) {z : ℝ} (hz : ∀ x, x + z < f x) :
z < τ f := by
obtain ⟨x, -, hx⟩ : ∃ x ∈ Icc (0 : ℝ) 1, ∀ y ∈ Icc (0 : ℝ) 1, f x - x ≤ f y - y :=
isCompact_Icc.exists_isMinOn (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuousOn
refine lt_of_lt_of_le (lt_sub_iff_add_lt'.2 <| hz x) ?_
apply le_translationNumber_of_add_le
simp only [← le_sub_iff_add_le']
exact f.forall_map_sub_of_Icc _ hx
/-- If `f` is a continuous monotone map `ℝ → ℝ`, `f (x + 1) = f x + 1`, then there exists `x`
such that `f x = x + τ f`. -/
theorem exists_eq_add_translationNumber (hf : Continuous f) : ∃ x, f x = x + τ f := by
obtain ⟨a, ha⟩ : ∃ x, f x ≤ x + τ f := by
by_contra! H
exact lt_irrefl _ (f.lt_translationNumber_of_forall_add_lt hf H)
obtain ⟨b, hb⟩ : ∃ x, x + τ f ≤ f x := by
by_contra! H
exact lt_irrefl _ (f.translationNumber_lt_of_forall_lt_add hf H)
exact intermediate_value_univ₂ hf (continuous_id.add continuous_const) ha hb
theorem translationNumber_eq_int_iff (hf : Continuous f) {m : ℤ} :
τ f = m ↔ ∃ x : ℝ, f x = x + m := by
constructor
· intro h
simp only [← h]
exact f.exists_eq_add_translationNumber hf
· rintro ⟨x, hx⟩
exact f.translationNumber_of_eq_add_int hx
theorem continuous_pow (hf : Continuous f) (n : ℕ) : Continuous (f ^ n : CircleDeg1Lift) := by
rw [coe_pow]
exact hf.iterate n
theorem translationNumber_eq_rat_iff (hf : Continuous f) {m : ℤ} {n : ℕ} (hn : 0 < n) :
τ f = m / n ↔ ∃ x, (f ^ n) x = x + m := by
rw [eq_div_iff, mul_comm, ← translationNumber_pow] <;> [skip; exact ne_of_gt (Nat.cast_pos.2 hn)]
exact (f ^ n).translationNumber_eq_int_iff (f.continuous_pow hf n)
/-- Consider two actions `f₁ f₂ : G →* CircleDeg1Lift` of a group on the real line by lifts of
orientation preserving circle homeomorphisms. Suppose that for each `g : G` the homeomorphisms
`f₁ g` and `f₂ g` have equal rotation numbers. Then there exists `F : CircleDeg1Lift` such that
`F * f₁ g = f₂ g * F` for all `g : G`.
This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et
cohomologie bornee][ghys87:groupes]. -/
theorem semiconj_of_group_action_of_forall_translationNumber_eq {G : Type*} [Group G]
(f₁ f₂ : G →* CircleDeg1Lift) (h : ∀ g, τ (f₁ g) = τ (f₂ g)) :
∃ F : CircleDeg1Lift, ∀ g, Semiconj F (f₁ g) (f₂ g) := by
-- Equality of translation number guarantees that for each `x`
-- the set `{f₂ g⁻¹ (f₁ g x) | g : G}` is bounded above.
have : ∀ x, BddAbove (range fun g => f₂ g⁻¹ (f₁ g x)) := by
refine fun x => ⟨x + 2, ?_⟩
rintro _ ⟨g, rfl⟩
have : τ (f₂ g⁻¹) = -τ (f₂ g) := by
rw [← MonoidHom.coe_toHomUnits, MonoidHom.map_inv, translationNumber_units_inv,
MonoidHom.coe_toHomUnits]
calc
f₂ g⁻¹ (f₁ g x) ≤ f₂ g⁻¹ (x + τ (f₁ g) + 1) :=
mono _ (map_lt_add_translationNumber_add_one _ _).le
_ = f₂ g⁻¹ (x + τ (f₂ g)) + 1 := by rw [h, map_add_one]
_ ≤ x + τ (f₂ g) + τ (f₂ g⁻¹) + 1 + 1 :=
add_le_add_right (map_lt_add_translationNumber_add_one _ _).le _
_ = x + 2 := by simp [this, add_assoc, one_add_one_eq_two]
-- We have a theorem about actions by `OrderIso`, so we introduce auxiliary maps
-- to `ℝ ≃o ℝ`.
set F₁ := toOrderIso.comp f₁.toHomUnits
set F₂ := toOrderIso.comp f₂.toHomUnits
have hF₁ : ∀ g, ⇑(F₁ g) = f₁ g := fun _ => rfl
have hF₂ : ∀ g, ⇑(F₂ g) = f₂ g := fun _ => rfl
-- Now we apply `csSup_div_semiconj` and go back to `f₁` and `f₂`.
refine ⟨⟨⟨fun x ↦ ⨆ g', (F₂ g')⁻¹ (F₁ g' x), fun x y hxy => ?_⟩, fun x => ?_⟩,
csSup_div_semiconj F₂ F₁ fun x => ?_⟩ <;> simp only [hF₁, hF₂, ← map_inv]
· exact ciSup_mono (this y) fun g => mono _ (mono _ hxy)
· simp only [map_add_one]
exact (Monotone.map_ciSup_of_continuousAt (continuousAt_id.add continuousAt_const)
(monotone_id.add_const (1 : ℝ)) (this x)).symm
· exact this x
/-- If two lifts of circle homeomorphisms have the same translation number, then they are
semiconjugate by a `CircleDeg1Lift`. This version uses arguments `f₁ f₂ : CircleDeg1Liftˣ`
to assume that `f₁` and `f₂` are homeomorphisms. -/
theorem units_semiconj_of_translationNumber_eq {f₁ f₂ : CircleDeg1Liftˣ} (h : τ f₁ = τ f₂) :
∃ F : CircleDeg1Lift, Semiconj F f₁ f₂ :=
have : ∀ n : Multiplicative ℤ,
τ ((Units.coeHom _).comp (zpowersHom _ f₁) n) =
τ ((Units.coeHom _).comp (zpowersHom _ f₂) n) := fun n ↦ by
simp [h]
(semiconj_of_group_action_of_forall_translationNumber_eq _ _ this).imp fun F hF => by
simpa using hF (Multiplicative.ofAdd 1)
/-- If two lifts of circle homeomorphisms have the same translation number, then they are
semiconjugate by a `CircleDeg1Lift`. This version uses assumptions `IsUnit f₁` and `IsUnit f₂`
to assume that `f₁` and `f₂` are homeomorphisms. -/
theorem semiconj_of_isUnit_of_translationNumber_eq {f₁ f₂ : CircleDeg1Lift} (h₁ : IsUnit f₁)
(h₂ : IsUnit f₂) (h : τ f₁ = τ f₂) : ∃ F : CircleDeg1Lift, Semiconj F f₁ f₂ := by
rcases h₁, h₂ with ⟨⟨f₁, rfl⟩, ⟨f₂, rfl⟩⟩
exact units_semiconj_of_translationNumber_eq h
/-- If two lifts of circle homeomorphisms have the same translation number, then they are
semiconjugate by a `CircleDeg1Lift`. This version uses assumptions `bijective f₁` and
`bijective f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/
theorem semiconj_of_bijective_of_translationNumber_eq {f₁ f₂ : CircleDeg1Lift} (h₁ : Bijective f₁)
(h₂ : Bijective f₂) (h : τ f₁ = τ f₂) : ∃ F : CircleDeg1Lift, Semiconj F f₁ f₂ :=
semiconj_of_isUnit_of_translationNumber_eq (isUnit_iff_bijective.2 h₁) (isUnit_iff_bijective.2 h₂)
h
end CircleDeg1Lift
|
Basic.lean
|
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
-/
import Mathlib.Algebra.Order.CauSeq.Completion
import Mathlib.Algebra.Order.Ring.Rat
import Mathlib.Data.Rat.Cast.Defs
/-!
# Real numbers from Cauchy sequences
This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers.
This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply
lifting everything to `ℚ`.
The facts that the real numbers are an Archimedean floor ring,
and a conditionally complete linear order,
have been deferred to the file `Mathlib/Data/Real/Archimedean.lean`,
in order to keep the imports here simple.
The fact that the real numbers are a (trivial) *-ring has similarly been deferred to
`Mathlib/Data/Real/Star.lean`.
-/
assert_not_exists Finset Module Submonoid FloorRing
/-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational
numbers. -/
structure Real where ofCauchy ::
/-- The underlying Cauchy completion -/
cauchy : CauSeq.Completion.Cauchy (abs : ℚ → ℚ)
@[inherit_doc]
notation "ℝ" => Real
namespace CauSeq.Completion
-- this can't go in `Data.Real.CauSeqCompletion` as the structure on `ℚ` isn't available
@[simp]
theorem ofRat_rat {abv : ℚ → ℚ} [IsAbsoluteValue abv] (q : ℚ) :
ofRat (q : ℚ) = (q : Cauchy abv) :=
rfl
end CauSeq.Completion
namespace Real
open CauSeq CauSeq.Completion
variable {x : ℝ}
theorem ext_cauchy_iff : ∀ {x y : Real}, x = y ↔ x.cauchy = y.cauchy
| ⟨a⟩, ⟨b⟩ => by rw [ofCauchy.injEq]
theorem ext_cauchy {x y : Real} : x.cauchy = y.cauchy → x = y :=
ext_cauchy_iff.2
/-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/
def equivCauchy : ℝ ≃ CauSeq.Completion.Cauchy (abs : ℚ → ℚ) :=
⟨Real.cauchy, Real.ofCauchy, fun ⟨_⟩ => rfl, fun _ => rfl⟩
-- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511
private irreducible_def zero : ℝ :=
⟨0⟩
private irreducible_def one : ℝ :=
⟨1⟩
private irreducible_def add : ℝ → ℝ → ℝ
| ⟨a⟩, ⟨b⟩ => ⟨a + b⟩
private irreducible_def neg : ℝ → ℝ
| ⟨a⟩ => ⟨-a⟩
private irreducible_def mul : ℝ → ℝ → ℝ
| ⟨a⟩, ⟨b⟩ => ⟨a * b⟩
private noncomputable irreducible_def inv' : ℝ → ℝ
| ⟨a⟩ => ⟨a⁻¹⟩
instance : Zero ℝ :=
⟨zero⟩
instance : One ℝ :=
⟨one⟩
instance : Add ℝ :=
⟨add⟩
instance : Neg ℝ :=
⟨neg⟩
instance : Mul ℝ :=
⟨mul⟩
instance : Sub ℝ :=
⟨fun a b => a + -b⟩
noncomputable instance : Inv ℝ :=
⟨inv'⟩
theorem ofCauchy_zero : (⟨0⟩ : ℝ) = 0 :=
zero_def.symm
theorem ofCauchy_one : (⟨1⟩ : ℝ) = 1 :=
one_def.symm
theorem ofCauchy_add (a b) : (⟨a + b⟩ : ℝ) = ⟨a⟩ + ⟨b⟩ :=
(add_def _ _).symm
theorem ofCauchy_neg (a) : (⟨-a⟩ : ℝ) = -⟨a⟩ :=
(neg_def _).symm
theorem ofCauchy_sub (a b) : (⟨a - b⟩ : ℝ) = ⟨a⟩ - ⟨b⟩ := by
rw [sub_eq_add_neg, ofCauchy_add, ofCauchy_neg]
rfl
theorem ofCauchy_mul (a b) : (⟨a * b⟩ : ℝ) = ⟨a⟩ * ⟨b⟩ :=
(mul_def _ _).symm
theorem ofCauchy_inv {f} : (⟨f⁻¹⟩ : ℝ) = ⟨f⟩⁻¹ :=
show _ = inv' _ by rw [inv']
theorem cauchy_zero : (0 : ℝ).cauchy = 0 :=
show zero.cauchy = 0 by rw [zero_def]
theorem cauchy_one : (1 : ℝ).cauchy = 1 :=
show one.cauchy = 1 by rw [one_def]
theorem cauchy_add : ∀ a b, (a + b : ℝ).cauchy = a.cauchy + b.cauchy
| ⟨a⟩, ⟨b⟩ => show (add _ _).cauchy = _ by rw [add_def]
theorem cauchy_neg : ∀ a, (-a : ℝ).cauchy = -a.cauchy
| ⟨a⟩ => show (neg _).cauchy = _ by rw [neg_def]
theorem cauchy_mul : ∀ a b, (a * b : ℝ).cauchy = a.cauchy * b.cauchy
| ⟨a⟩, ⟨b⟩ => show (mul _ _).cauchy = _ by rw [mul_def]
theorem cauchy_sub : ∀ a b, (a - b : ℝ).cauchy = a.cauchy - b.cauchy
| ⟨a⟩, ⟨b⟩ => by
rw [sub_eq_add_neg, ← cauchy_neg, ← cauchy_add]
rfl
theorem cauchy_inv : ∀ f, (f⁻¹ : ℝ).cauchy = f.cauchy⁻¹
| ⟨f⟩ => show (inv' _).cauchy = _ by rw [inv']
instance instNatCast : NatCast ℝ where natCast n := ⟨n⟩
instance instIntCast : IntCast ℝ where intCast z := ⟨z⟩
instance instNNRatCast : NNRatCast ℝ where nnratCast q := ⟨q⟩
instance instRatCast : RatCast ℝ where ratCast q := ⟨q⟩
lemma ofCauchy_natCast (n : ℕ) : (⟨n⟩ : ℝ) = n := rfl
lemma ofCauchy_intCast (z : ℤ) : (⟨z⟩ : ℝ) = z := rfl
lemma ofCauchy_nnratCast (q : ℚ≥0) : (⟨q⟩ : ℝ) = q := rfl
lemma ofCauchy_ratCast (q : ℚ) : (⟨q⟩ : ℝ) = q := rfl
lemma cauchy_natCast (n : ℕ) : (n : ℝ).cauchy = n := rfl
lemma cauchy_intCast (z : ℤ) : (z : ℝ).cauchy = z := rfl
lemma cauchy_nnratCast (q : ℚ≥0) : (q : ℝ).cauchy = q := rfl
lemma cauchy_ratCast (q : ℚ) : (q : ℝ).cauchy = q := rfl
instance commRing : CommRing ℝ where
natCast n := ⟨n⟩
intCast z := ⟨z⟩
zero := (0 : ℝ)
one := (1 : ℝ)
mul := (· * ·)
add := (· + ·)
neg := @Neg.neg ℝ _
sub := @Sub.sub ℝ _
npow := @npowRec ℝ ⟨1⟩ ⟨(· * ·)⟩
nsmul := @nsmulRec ℝ ⟨0⟩ ⟨(· + ·)⟩
zsmul := @zsmulRec ℝ ⟨0⟩ ⟨(· + ·)⟩ ⟨@Neg.neg ℝ _⟩ (@nsmulRec ℝ ⟨0⟩ ⟨(· + ·)⟩)
add_zero a := by apply ext_cauchy; simp [cauchy_add, cauchy_zero]
zero_add a := by apply ext_cauchy; simp [cauchy_add, cauchy_zero]
add_comm a b := by apply ext_cauchy; simp only [cauchy_add, add_comm]
add_assoc a b c := by apply ext_cauchy; simp only [cauchy_add, add_assoc]
mul_zero a := by apply ext_cauchy; simp [cauchy_mul, cauchy_zero]
zero_mul a := by apply ext_cauchy; simp [cauchy_mul, cauchy_zero]
mul_one a := by apply ext_cauchy; simp [cauchy_mul, cauchy_one]
one_mul a := by apply ext_cauchy; simp [cauchy_mul, cauchy_one]
mul_comm a b := by apply ext_cauchy; simp only [cauchy_mul, mul_comm]
mul_assoc a b c := by apply ext_cauchy; simp only [cauchy_mul, mul_assoc]
left_distrib a b c := by apply ext_cauchy; simp only [cauchy_add, cauchy_mul, mul_add]
right_distrib a b c := by apply ext_cauchy; simp only [cauchy_add, cauchy_mul, add_mul]
neg_add_cancel a := by apply ext_cauchy; simp [cauchy_add, cauchy_neg, cauchy_zero]
natCast_zero := by apply ext_cauchy; simp [cauchy_zero]
natCast_succ n := by apply ext_cauchy; simp [cauchy_one, cauchy_add]
intCast_negSucc z := by apply ext_cauchy; simp [cauchy_neg, cauchy_natCast]
/-- `Real.equivCauchy` as a ring equivalence. -/
@[simps]
def ringEquivCauchy : ℝ ≃+* CauSeq.Completion.Cauchy (abs : ℚ → ℚ) :=
{ equivCauchy with
toFun := cauchy
invFun := ofCauchy
map_add' := cauchy_add
map_mul' := cauchy_mul }
/-! Extra instances to short-circuit type class resolution.
These short-circuits have an additional property of ensuring that a computable path is found; if
`Field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable`
version of them. -/
instance instRing : Ring ℝ := by infer_instance
instance : CommSemiring ℝ := by infer_instance
instance semiring : Semiring ℝ := by infer_instance
instance : CommMonoidWithZero ℝ := by infer_instance
instance : MonoidWithZero ℝ := by infer_instance
instance : AddCommGroup ℝ := by infer_instance
instance : AddGroup ℝ := by infer_instance
instance : AddCommMonoid ℝ := by infer_instance
instance : AddMonoid ℝ := by infer_instance
instance : AddLeftCancelSemigroup ℝ := by infer_instance
instance : AddRightCancelSemigroup ℝ := by infer_instance
instance : AddCommSemigroup ℝ := by infer_instance
instance : AddSemigroup ℝ := by infer_instance
instance : CommMonoid ℝ := by infer_instance
instance : Monoid ℝ := by infer_instance
instance : CommSemigroup ℝ := by infer_instance
instance : Semigroup ℝ := by infer_instance
instance : Inhabited ℝ :=
⟨0⟩
/-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/
def mk (x : CauSeq ℚ abs) : ℝ :=
⟨CauSeq.Completion.mk x⟩
theorem mk_eq {f g : CauSeq ℚ abs} : mk f = mk g ↔ f ≈ g :=
ext_cauchy_iff.trans CauSeq.Completion.mk_eq
private irreducible_def lt : ℝ → ℝ → Prop
| ⟨x⟩, ⟨y⟩ =>
(Quotient.liftOn₂ x y (· < ·)) fun _ _ _ _ hf hg =>
propext <|
⟨fun h => lt_of_eq_of_lt (Setoid.symm hf) (lt_of_lt_of_eq h hg), fun h =>
lt_of_eq_of_lt hf (lt_of_lt_of_eq h (Setoid.symm hg))⟩
instance : LT ℝ :=
⟨lt⟩
theorem lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g :=
show lt _ _ ↔ _ by rw [lt_def]; rfl
@[simp]
theorem mk_lt {f g : CauSeq ℚ abs} : mk f < mk g ↔ f < g :=
lt_cauchy
theorem mk_zero : mk 0 = 0 := by rw [← ofCauchy_zero]; rfl
theorem mk_one : mk 1 = 1 := by rw [← ofCauchy_one]; rfl
theorem mk_add {f g : CauSeq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, ← ofCauchy_add]
theorem mk_mul {f g : CauSeq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, ← ofCauchy_mul]
theorem mk_neg {f : CauSeq ℚ abs} : mk (-f) = -mk f := by simp [mk, ← ofCauchy_neg]
@[simp]
theorem mk_pos {f : CauSeq ℚ abs} : 0 < mk f ↔ Pos f := by
rw [← mk_zero, mk_lt]
exact iff_of_eq (congr_arg Pos (sub_zero f))
lemma mk_const {x : ℚ} : mk (const abs x) = x := rfl
private irreducible_def le (x y : ℝ) : Prop :=
x < y ∨ x = y
instance : LE ℝ :=
⟨le⟩
private theorem le_def' {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y :=
iff_of_eq <| le_def _ _
@[simp]
theorem mk_le {f g : CauSeq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by
simp only [le_def', mk_lt, mk_eq]; rfl
@[elab_as_elim]
protected theorem ind_mk {C : Real → Prop} (x : Real) (h : ∀ y, C (mk y)) : C x := by
obtain ⟨x⟩ := x
induction x using Quot.induction_on
exact h _
theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := by
induction a using Real.ind_mk
induction b using Real.ind_mk
induction c using Real.ind_mk
simp only [mk_lt, ← mk_add]
change Pos _ ↔ Pos _; rw [add_sub_add_left_eq_sub]
instance partialOrder : PartialOrder ℝ where
le := (· ≤ ·)
lt := (· < ·)
lt_iff_le_not_ge a b := by
induction a using Real.ind_mk
induction b using Real.ind_mk
simpa using lt_iff_le_not_ge
le_refl a := by
induction a using Real.ind_mk
rw [mk_le]
le_trans a b c := by
induction a using Real.ind_mk
induction b using Real.ind_mk
induction c using Real.ind_mk
simpa using le_trans
le_antisymm a b := by
induction a using Real.ind_mk
induction b using Real.ind_mk
simpa [mk_eq] using CauSeq.le_antisymm
instance : Preorder ℝ := by infer_instance
theorem ratCast_lt {x y : ℚ} : (x : ℝ) < (y : ℝ) ↔ x < y := by
rw [← mk_const, ← mk_const, mk_lt]
exact const_lt
protected theorem zero_lt_one : (0 : ℝ) < 1 := by
convert ratCast_lt.2 zero_lt_one <;> simp [← ofCauchy_ratCast, ofCauchy_one, ofCauchy_zero]
@[deprecated ZeroLEOneClass.factZeroLtOne (since := "2025-05-12")]
protected theorem fact_zero_lt_one : Fact ((0 : ℝ) < 1) :=
⟨Real.zero_lt_one⟩
instance instNontrivial : Nontrivial ℝ where
exists_pair_ne := ⟨0, 1, Real.zero_lt_one.ne⟩
instance instZeroLEOneClass : ZeroLEOneClass ℝ where
zero_le_one := le_of_lt Real.zero_lt_one
instance instIsOrderedAddMonoid : IsOrderedAddMonoid ℝ where
add_le_add_left := by
simp only [le_iff_eq_or_lt]
rintro a b ⟨rfl, h⟩
· simp only [lt_self_iff_false, or_false, forall_const]
· exact fun c => Or.inr ((add_lt_add_iff_left c).2 ‹_›)
instance instIsStrictOrderedRing : IsStrictOrderedRing ℝ :=
.of_mul_pos fun a b ↦ by
induction' a using Real.ind_mk with a
induction' b using Real.ind_mk with b
simpa only [mk_lt, mk_pos, ← mk_mul] using CauSeq.mul_pos
instance instIsOrderedRing : IsOrderedRing ℝ :=
inferInstance
instance instIsOrderedCancelAddMonoid : IsOrderedCancelAddMonoid ℝ :=
inferInstance
private irreducible_def sup : ℝ → ℝ → ℝ
| ⟨x⟩, ⟨y⟩ => ⟨Quotient.map₂ (· ⊔ ·) (fun _ _ hx _ _ hy => sup_equiv_sup hx hy) x y⟩
instance : Max ℝ :=
⟨sup⟩
theorem ofCauchy_sup (a b) : (⟨⟦a ⊔ b⟧⟩ : ℝ) = ⟨⟦a⟧⟩ ⊔ ⟨⟦b⟧⟩ :=
show _ = sup _ _ by
rw [sup_def]
rfl
@[simp]
theorem mk_sup (a b) : (mk (a ⊔ b) : ℝ) = mk a ⊔ mk b :=
ofCauchy_sup _ _
private irreducible_def inf : ℝ → ℝ → ℝ
| ⟨x⟩, ⟨y⟩ => ⟨Quotient.map₂ (· ⊓ ·) (fun _ _ hx _ _ hy => inf_equiv_inf hx hy) x y⟩
instance : Min ℝ :=
⟨inf⟩
theorem ofCauchy_inf (a b) : (⟨⟦a ⊓ b⟧⟩ : ℝ) = ⟨⟦a⟧⟩ ⊓ ⟨⟦b⟧⟩ :=
show _ = inf _ _ by
rw [inf_def]
rfl
@[simp]
theorem mk_inf (a b) : (mk (a ⊓ b) : ℝ) = mk a ⊓ mk b :=
ofCauchy_inf _ _
instance : DistribLattice ℝ :=
{ Real.partialOrder with
sup := (· ⊔ ·)
le := (· ≤ ·)
le_sup_left := by
intros a b
induction a using Real.ind_mk
induction b using Real.ind_mk
dsimp only; rw [← mk_sup, mk_le]
exact CauSeq.le_sup_left
le_sup_right := by
intros a b
induction a using Real.ind_mk
induction b using Real.ind_mk
dsimp only; rw [← mk_sup, mk_le]
exact CauSeq.le_sup_right
sup_le := by
intros a b c
induction a using Real.ind_mk
induction b using Real.ind_mk
induction c using Real.ind_mk
simp_rw [← mk_sup, mk_le]
exact CauSeq.sup_le
inf := (· ⊓ ·)
inf_le_left := by
intros a b
induction a using Real.ind_mk
induction b using Real.ind_mk
dsimp only; rw [← mk_inf, mk_le]
exact CauSeq.inf_le_left
inf_le_right := by
intros a b
induction a using Real.ind_mk
induction b using Real.ind_mk
dsimp only; rw [← mk_inf, mk_le]
exact CauSeq.inf_le_right
le_inf := by
intros a b c
induction a using Real.ind_mk
induction b using Real.ind_mk
induction c using Real.ind_mk
simp_rw [← mk_inf, mk_le]
exact CauSeq.le_inf
le_sup_inf := by
intros a b c
induction a using Real.ind_mk
induction b using Real.ind_mk
induction c using Real.ind_mk
apply Eq.le
simp only [← mk_sup, ← mk_inf]
exact congr_arg mk (CauSeq.sup_inf_distrib_left ..).symm }
-- Extra instances to short-circuit type class resolution
instance lattice : Lattice ℝ :=
inferInstance
instance : SemilatticeInf ℝ :=
inferInstance
instance : SemilatticeSup ℝ :=
inferInstance
instance leTotal_R : IsTotal ℝ (· ≤ ·) :=
⟨by
intros a b
induction a using Real.ind_mk
induction b using Real.ind_mk
simpa using CauSeq.le_total ..⟩
open scoped Classical in
noncomputable instance linearOrder : LinearOrder ℝ :=
Lattice.toLinearOrder ℝ
instance : IsDomain ℝ := IsStrictOrderedRing.isDomain
noncomputable instance instDivInvMonoid : DivInvMonoid ℝ where
lemma ofCauchy_div (f g) : (⟨f / g⟩ : ℝ) = (⟨f⟩ : ℝ) / (⟨g⟩ : ℝ) := by
simp_rw [div_eq_mul_inv, ofCauchy_mul, ofCauchy_inv]
noncomputable instance field : Field ℝ where
mul_inv_cancel := by
rintro ⟨a⟩ h
rw [mul_comm]
simp only [← ofCauchy_inv, ← ofCauchy_mul, ← ofCauchy_one, ← ofCauchy_zero,
Ne, ofCauchy.injEq] at *
exact CauSeq.Completion.inv_mul_cancel h
inv_zero := by simp [← ofCauchy_zero, ← ofCauchy_inv]
nnqsmul := _
nnqsmul_def := fun _ _ => rfl
qsmul := _
qsmul_def := fun _ _ => rfl
nnratCast_def q := by
rw [← ofCauchy_nnratCast, NNRat.cast_def, ofCauchy_div, ofCauchy_natCast, ofCauchy_natCast]
ratCast_def q := by
rw [← ofCauchy_ratCast, Rat.cast_def, ofCauchy_div, ofCauchy_natCast, ofCauchy_intCast]
-- Extra instances to short-circuit type class resolution
noncomputable instance : DivisionRing ℝ := by infer_instance
noncomputable instance decidableLT (a b : ℝ) : Decidable (a < b) := by infer_instance
noncomputable instance decidableLE (a b : ℝ) : Decidable (a ≤ b) := by infer_instance
noncomputable instance decidableEq (a b : ℝ) : Decidable (a = b) := by infer_instance
/-- Show an underlying cauchy sequence for real numbers.
The representative chosen is the one passed in the VM to `Quot.mk`, so two cauchy sequences
converging to the same number may be printed differently.
-/
unsafe instance : Repr ℝ where
reprPrec r p := Repr.addAppParen ("Real.ofCauchy " ++ repr r.cauchy) p
theorem le_mk_of_forall_le {f : CauSeq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := by
intro h
induction x using Real.ind_mk
apply le_of_not_gt
rw [mk_lt]
rintro ⟨K, K0, hK⟩
obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ <| half_pos K0))
apply not_lt_of_ge (H _ le_rfl).1
rw [← mk_const, mk_lt]
refine ⟨_, half_pos K0, i, fun j ij => ?_⟩
have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 <| (H _ le_rfl).2.2 _ ij).1)
rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this
theorem mk_le_of_forall_le {f : CauSeq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) :
mk f ≤ x := by
obtain ⟨i, H⟩ := h
rw [← neg_le_neg_iff, ← mk_neg]
exact le_mk_of_forall_le ⟨i, fun j ij => by simp [H _ ij]⟩
theorem mk_near_of_forall_near {f : CauSeq ℚ abs} {x : ℝ} {ε : ℝ}
(H : ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| ≤ ε) : |mk f - x| ≤ ε :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add'.2 <|
mk_le_of_forall_le <|
H.imp fun _ h j ij => sub_le_iff_le_add'.1 (abs_sub_le_iff.1 <| h j ij).1,
sub_le_comm.1 <|
le_mk_of_forall_le <| H.imp fun _ h j ij => sub_le_comm.1 (abs_sub_le_iff.1 <| h j ij).2⟩
lemma mul_add_one_le_add_one_pow {a : ℝ} (ha : 0 ≤ a) (b : ℕ) : a * b + 1 ≤ (a + 1) ^ b := by
rcases ha.eq_or_lt with rfl | ha'
· simp
clear ha
induction b generalizing a with
| zero => simp
| succ b hb =>
calc
a * ↑(b + 1) + 1 = (0 + 1) ^ b * a + (a * b + 1) := by
simp [mul_add, add_assoc, add_left_comm]
_ ≤ (a + 1) ^ b * a + (a + 1) ^ b := by
gcongr
· norm_num
· exact hb ha'
_ = (a + 1) ^ (b + 1) := by simp [pow_succ, mul_add]
end Real
/-- A function `f : R → ℝ` is power-multiplicative if for all `r ∈ R` and all positive `n ∈ ℕ`,
`f (r ^ n) = (f r) ^ n`. -/
def IsPowMul {R : Type*} [Pow R ℕ] (f : R → ℝ) :=
∀ (a : R) {n : ℕ}, 1 ≤ n → f (a ^ n) = f a ^ n
lemma IsPowMul.map_one_le_one {R : Type*} [Monoid R] {f : R → ℝ} (hf : IsPowMul f) :
f 1 ≤ 1 := by
have hf1 : (f 1)^2 = f 1 := by conv_rhs => rw [← one_pow 2, hf _ one_le_two]
rcases eq_zero_or_one_of_sq_eq_self hf1 with h | h <;> rw [h]
exact zero_le_one
/-- A ring homomorphism `f : α →+* β` is bounded with respect to the functions `nα : α → ℝ` and
`nβ : β → ℝ` if there exists a positive constant `C` such that for all `x` in `α`,
`nβ (f x) ≤ C * nα x`. -/
def RingHom.IsBoundedWrt {α : Type*} [Ring α] {β : Type*} [Ring β] (nα : α → ℝ) (nβ : β → ℝ)
(f : α →+* β) : Prop :=
∃ C : ℝ, 0 < C ∧ ∀ x : α, nβ (f x) ≤ C * nα x
|
BoundedVariation.lean
|
/-
Copyright (c) 2022 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import Mathlib.Analysis.Calculus.FDeriv.Add
import Mathlib.Analysis.Calculus.FDeriv.Equiv
import Mathlib.Analysis.Calculus.FDeriv.Prod
import Mathlib.Analysis.Calculus.Monotone
import Mathlib.Topology.EMetricSpace.BoundedVariation
/-!
# Almost everywhere differentiability of functions with locally bounded variation
In this file we show that a bounded variation function is differentiable almost everywhere.
This implies that Lipschitz functions from the real line into finite-dimensional vector space
are also differentiable almost everywhere.
## Main definitions and results
* `LocallyBoundedVariationOn.ae_differentiableWithinAt` shows that a bounded variation
function into a finite dimensional real vector space is differentiable almost everywhere.
* `LipschitzOnWith.ae_differentiableWithinAt` is the same result for Lipschitz functions.
We also give several variations around these results.
-/
open scoped NNReal ENNReal Topology
open Set MeasureTheory Filter
variable {α : Type*} [LinearOrder α] {E : Type*} [PseudoEMetricSpace E]
/-! ## -/
variable {V : Type*} [NormedAddCommGroup V] [NormedSpace ℝ V] [FiniteDimensional ℝ V]
namespace LocallyBoundedVariationOn
/-- A bounded variation function into `ℝ` is differentiable almost everywhere. Superseded by
`ae_differentiableWithinAt_of_mem`. -/
theorem ae_differentiableWithinAt_of_mem_real {f : ℝ → ℝ} {s : Set ℝ}
(h : LocallyBoundedVariationOn f s) : ∀ᵐ x, x ∈ s → DifferentiableWithinAt ℝ f s x := by
obtain ⟨p, q, hp, hq, rfl⟩ : ∃ p q, MonotoneOn p s ∧ MonotoneOn q s ∧ f = p - q :=
h.exists_monotoneOn_sub_monotoneOn
filter_upwards [hp.ae_differentiableWithinAt_of_mem, hq.ae_differentiableWithinAt_of_mem] with
x hxp hxq xs
exact (hxp xs).sub (hxq xs)
/-- A bounded variation function into a finite dimensional product vector space is differentiable
almost everywhere. Superseded by `ae_differentiableWithinAt_of_mem`. -/
theorem ae_differentiableWithinAt_of_mem_pi {ι : Type*} [Fintype ι] {f : ℝ → ι → ℝ} {s : Set ℝ}
(h : LocallyBoundedVariationOn f s) : ∀ᵐ x, x ∈ s → DifferentiableWithinAt ℝ f s x := by
have A : ∀ i : ι, LipschitzWith 1 fun x : ι → ℝ => x i := fun i => LipschitzWith.eval i
have : ∀ i : ι, ∀ᵐ x, x ∈ s → DifferentiableWithinAt ℝ (fun x : ℝ => f x i) s x := fun i ↦ by
apply ae_differentiableWithinAt_of_mem_real
exact LipschitzWith.comp_locallyBoundedVariationOn (A i) h
filter_upwards [ae_all_iff.2 this] with x hx xs
exact differentiableWithinAt_pi.2 fun i => hx i xs
/-- A real function into a finite dimensional real vector space with bounded variation on a set
is differentiable almost everywhere in this set. -/
theorem ae_differentiableWithinAt_of_mem {f : ℝ → V} {s : Set ℝ}
(h : LocallyBoundedVariationOn f s) : ∀ᵐ x, x ∈ s → DifferentiableWithinAt ℝ f s x := by
let A := (Module.Basis.ofVectorSpace ℝ V).equivFun.toContinuousLinearEquiv
suffices H : ∀ᵐ x, x ∈ s → DifferentiableWithinAt ℝ (A ∘ f) s x by
filter_upwards [H] with x hx xs
have : f = (A.symm ∘ A) ∘ f := by
simp only [ContinuousLinearEquiv.symm_comp_self, Function.id_comp]
rw [this]
exact A.symm.differentiableAt.comp_differentiableWithinAt x (hx xs)
apply ae_differentiableWithinAt_of_mem_pi
exact A.lipschitz.comp_locallyBoundedVariationOn h
/-- A real function into a finite dimensional real vector space with bounded variation on a set
is differentiable almost everywhere in this set. -/
theorem ae_differentiableWithinAt {f : ℝ → V} {s : Set ℝ} (h : LocallyBoundedVariationOn f s)
(hs : MeasurableSet s) : ∀ᵐ x ∂volume.restrict s, DifferentiableWithinAt ℝ f s x := by
rw [ae_restrict_iff' hs]
exact h.ae_differentiableWithinAt_of_mem
/-- A real function into a finite dimensional real vector space with bounded variation
is differentiable almost everywhere. -/
theorem ae_differentiableAt {f : ℝ → V} (h : LocallyBoundedVariationOn f univ) :
∀ᵐ x, DifferentiableAt ℝ f x := by
filter_upwards [h.ae_differentiableWithinAt_of_mem] with x hx
rw [differentiableWithinAt_univ] at hx
exact hx (mem_univ _)
end LocallyBoundedVariationOn
/-- A real function into a finite dimensional real vector space which is Lipschitz on a set
is differentiable almost everywhere in this set. For the general Rademacher theorem assuming
that the source space is finite dimensional, see `LipschitzOnWith.ae_differentiableWithinAt_of_mem`.
-/
theorem LipschitzOnWith.ae_differentiableWithinAt_of_mem_real {C : ℝ≥0} {f : ℝ → V} {s : Set ℝ}
(h : LipschitzOnWith C f s) : ∀ᵐ x, x ∈ s → DifferentiableWithinAt ℝ f s x :=
h.locallyBoundedVariationOn.ae_differentiableWithinAt_of_mem
/-- A real function into a finite dimensional real vector space which is Lipschitz on a set
is differentiable almost everywhere in this set. For the general Rademacher theorem assuming
that the source space is finite dimensional, see `LipschitzOnWith.ae_differentiableWithinAt`. -/
theorem LipschitzOnWith.ae_differentiableWithinAt_real {C : ℝ≥0} {f : ℝ → V} {s : Set ℝ}
(h : LipschitzOnWith C f s) (hs : MeasurableSet s) :
∀ᵐ x ∂volume.restrict s, DifferentiableWithinAt ℝ f s x :=
h.locallyBoundedVariationOn.ae_differentiableWithinAt hs
/-- A real Lipschitz function into a finite dimensional real vector space is differentiable
almost everywhere. For the general Rademacher theorem assuming
that the source space is finite dimensional, see `LipschitzWith.ae_differentiableAt`. -/
theorem LipschitzWith.ae_differentiableAt_real {C : ℝ≥0} {f : ℝ → V} (h : LipschitzWith C f) :
∀ᵐ x, DifferentiableAt ℝ f x :=
(h.locallyBoundedVariationOn univ).ae_differentiableAt
|
qfpoly.v
|
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice.
From mathcomp Require Import fintype tuple div bigop binomial finset finfun.
From mathcomp Require Import ssralg countalg finalg poly polydiv qpoly perm.
From mathcomp Require Import fingroup falgebra fieldext finfield galois.
From mathcomp Require Import finalg zmodp matrix vector.
(******************************************************************************)
(* This file extends the algebras R[X]/<p> defined in qpoly with the field *)
(* when p is irreducible *)
(* It defines the new field on top of {qpoly p}. As irreducible is in general *)
(* decidable in general, this is done by giving a proof explicitly. *)
(* monic_irreducible_poly p == proof that p is monic and irreducible *)
(* {poly %/ p with mi} == defined as {poly %/ p} where mi is proof of *)
(* monic_irreducible_poly p *)
(* It also defines the discrete logarithm with a primitive polynomial on a *)
(* finite field *)
(* primitive_poly p == p is a primitive polynomial *)
(* qlogp q == is the discrete log of q where q is an element of *)
(* the quotient field with respect to a primitive *)
(* polynomial p *)
(* plogp p q == is the discrete log of q with respect to p in {poly F} *)
(* this makes only sense if p is a primitive polynomial of *)
(* size > 2 *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Import GRing.Theory.
Import Pdiv.CommonRing.
Import Pdiv.RingMonic.
Import Pdiv.Field.
Import FinRing.Theory.
Local Open Scope ring_scope.
Reserved Notation "{ 'poly' '%/' p 'with' mi }"
(p at level 2, mi at level 10, format "{ 'poly' '%/' p 'with' mi }").
Section DomainDef.
Variable R : idomainType.
Variable h : {poly R}.
Definition monic_irreducible_poly (p : {poly R}) :=
((irreducible_poly p) * (p \is monic))%type.
Hypothesis hI : monic_irreducible_poly h.
Definition qfpoly : monic_irreducible_poly h -> predArgType :=
fun=> {poly %/ h}.
End DomainDef.
Notation "{ 'poly' '%/' p 'with' hi }" := (@qfpoly _ p hi).
Section iDomain.
Variable R : idomainType.
Variable h : {poly R}.
Hypothesis hI : monic_irreducible_poly h.
HB.instance Definition _ := GRing.NzRing.on {poly %/ h with hI}.
End iDomain.
Section finIDomain.
Variable R : finIdomainType.
Variable h : {poly R}.
Hypothesis hI : monic_irreducible_poly h.
HB.instance Definition _ := Finite.on {poly %/ h with hI}.
End finIDomain.
Section Field.
Variable R : fieldType.
Variable h : {poly R}.
Local Notation hQ := (mk_monic h).
Hypothesis hI : monic_irreducible_poly h.
HB.instance Definition _ := GRing.ComUnitRing.on {poly %/ h with hI}.
Lemma mk_monicE : mk_monic h = h.
Proof. by rewrite /mk_monic !hI. Qed.
Lemma coprimep_unit (p : {poly %/ h}) : p != 0%R -> coprimep hQ p.
Proof.
move=> pNZ.
rewrite irreducible_poly_coprime //; last first.
by case: hI; rewrite mk_monicE.
apply: contra pNZ => H; case: eqP => // /eqP /dvdp_leq /(_ H).
by rewrite leqNgt size_mk_monic.
Qed.
Lemma qpoly_mulVp (p : {poly %/ h}) : p != 0%R -> (qpoly_inv p * p = 1)%R.
Proof. by move=> pNZ; apply/qpoly_mulVz/coprimep_unit. Qed.
Lemma qpoly_inv0 : qpoly_inv 0%R = 0%R :> {poly %/ h}.
Proof.
rewrite /qpoly_inv /= coprimep0 -size_poly_eq1.
rewrite [in X in X == _]mk_monicE.
by have [[]] := hI; case: size => [|[]].
Qed.
HB.instance Definition _ := GRing.ComUnitRing_isField.Build {poly %/ h with hI}
coprimep_unit.
HB.instance Definition _ := GRing.UnitAlgebra.on {poly %/ h with hI}.
HB.instance Definition _ := Vector.on {poly %/ h with hI}.
End Field.
Section FinField.
Variable R : finFieldType.
Variable h : {poly R}.
Local Notation hQ := (mk_monic h).
HB.instance Definition _ := Finite.on {poly %/ h}.
Hypothesis hI : monic_irreducible_poly h.
HB.instance Definition _ := Finite.on {poly %/ h with hI}.
Lemma card_qfpoly : #|{poly %/ h with hI}| = #|R| ^ (size h).-1.
Proof. by rewrite card_monic_qpoly ?hI. Qed.
Lemma card_qfpoly_gt1 : 1 < #|{poly %/ h with hI}|.
Proof. by have := card_finNzRing_gt1 {poly %/ h with hI}. Qed.
End FinField.
Section inPoly.
Variable R : comNzRingType.
Variable h : {poly R}.
Lemma in_qpoly_comp_horner (p q : {poly R}) :
in_qpoly h (p \Po q) =
(map_poly (qpolyC h) p).[in_qpoly h q].
Proof.
have hQM := monic_mk_monic h.
rewrite comp_polyE /map_poly poly_def horner_sum /=.
apply: val_inj.
rewrite /= rmodp_sum // poly_of_qpoly_sum.
apply: eq_bigr => i _.
rewrite !hornerE /in_qpoly /=.
rewrite mul_polyC // !rmodpZ //=.
by rewrite poly_of_qpolyX /= rmodp_id // rmodpX // rmodp_id.
Qed.
Lemma map_poly_div_inj : injective (map_poly (qpolyC h)).
Proof.
apply: map_inj_poly => [x y /val_eqP /eqP /polyC_inj //|].
by rewrite qpolyC0.
Qed.
End inPoly.
Section finPoly.
(* Unfortunately we need some duplications so inference
propagates qfpoly :-( )*)
Definition qfpoly_const (R : idomainType) (h : {poly R})
(hMI : monic_irreducible_poly h) : R -> {poly %/ h with hMI} :=
qpolyC h.
Lemma map_fpoly_div_inj (R : idomainType) (h : {poly R})
(hMI : monic_irreducible_poly h) :
injective (map_poly (qfpoly_const hMI)).
Proof. by apply: (@map_poly_div_inj R h). Qed.
End finPoly.
Section Splitting.
Variable F : finFieldType.
Variable h : {poly F}.
Hypothesis hI : monic_irreducible_poly h.
Definition qfpoly_splitting_field_type :=
FinSplittingFieldType F {poly %/ h with hI}.
End Splitting.
Section PrimitivePoly.
Variable F : finFieldType.
Variable h : {poly F}.
Hypothesis sh_gt2 : 2 < size h.
Let sh_gt1 : 1 < size h.
Proof. by apply: leq_ltn_trans sh_gt2. Qed.
Definition primitive_poly (p: {poly F}) :=
let v := #|{poly %/ p}|.-1 in
[&& p \is monic,
irreducibleb p,
p %| 'X^v - 1 &
[forall n : 'I_v, (p %| 'X^n - 1) ==> (n == 0%N :> nat)]].
Lemma primitive_polyP (p : {poly F}) :
reflect
(let v := #|{poly %/ p}|.-1 in
[/\ monic_irreducible_poly p,
p %| 'X^v - 1 &
forall n, 0 < n < v -> ~~ (p %| 'X^n - 1)])
(primitive_poly p).
Proof.
apply: (iffP and4P) => [[H1 H2 H3 /forallP H4] v|[[H1 H2] H3 H4]]; split => //.
- by split => //; apply/irreducibleP.
- move=> n /andP[n_gt0 nLv]; apply/negP => /(implyP (H4 (Ordinal nLv))) /=.
by rewrite eqn0Ngt n_gt0.
- by apply/irreducibleP.
apply/forallP=> [] [[|n] Hn] /=; apply/implyP => pDX //.
by case/negP: (H4 n.+1 Hn).
Qed.
Hypothesis Hh : primitive_poly h.
Lemma primitive_mi : monic_irreducible_poly h.
Proof. by case/primitive_polyP: Hh. Qed.
Lemma primitive_poly_in_qpoly_eq0 p : (in_qpoly h p == 0) = (h %| p).
Proof.
have hM : h \is monic by case/and4P:Hh.
have hMi : monic_irreducible_poly h by apply: primitive_mi.
apply/eqP/idP => [/val_eqP /= | hDp].
by rewrite -Pdiv.IdomainMonic.modpE mk_monicE.
by apply/val_eqP; rewrite /= -Pdiv.IdomainMonic.modpE mk_monicE.
Qed.
Local Notation qT := {poly %/ h with primitive_mi}.
Lemma card_primitive_qpoly : #|{poly %/ h}|= #|F| ^ (size h).-1.
Proof. by rewrite card_monic_qpoly ?primitive_mi. Qed.
Lemma qX_neq0 : 'qX != 0 :> qT.
Proof.
apply/eqP => /val_eqP/=.
by rewrite [rmodp _ _]qpolyXE ?polyX_eq0 //; case: primitive_mi.
Qed.
Lemma qX_in_unit : ('qX : qT) \in GRing.unit.
Proof. by rewrite unitfE /= qX_neq0. Qed.
Definition gX : {unit qT} := FinRing.unit _ qX_in_unit.
Lemma dvdp_order n : (h %| 'X^n - 1) = (gX ^+ n == 1)%g.
Proof.
have [hM hI] := primitive_mi.
have eqr_add2r (r : nzRingType) (a b c : r) : (a + c == b + c) = (a == b).
by apply/eqP/eqP => [H|->//]; rewrite -(addrK c a) H addrK.
rewrite -val_eqE /= val_unitX /= -val_eqE /=.
rewrite (poly_of_qpolyX) qpolyXE // mk_monicE //.
rewrite -[in RHS](subrK 1 'X^n) rmodpD //.
rewrite [rmodp 1 h]rmodp_small ?size_poly1 //.
rewrite -[1%:P]add0r polyC1 /= eqr_add2r.
by rewrite dvdpE /=; apply/rmodp_eq0P/eqP.
Qed.
Lemma gX_order : #[gX]%g = (#|qT|).-1.
Proof.
have /primitive_polyP[Hp1 Hp2 Hp3] := Hh.
set n := _.-1 in Hp2 Hp3 *.
have n_gt0 : 0 < n by rewrite ltn_predRL card_qfpoly_gt1.
have [hM hI] := primitive_mi.
have gX_neq1 : gX != 1%g.
apply/eqP/val_eqP/eqP/val_eqP=> /=.
rewrite [X in X != _]qpolyXE /= //.
by apply/eqP=> Hx1; have := @size_polyX F; rewrite Hx1 size_poly1.
have Hx : (gX ^+ n)%g = 1%g by apply/eqP; rewrite -dvdp_order.
have Hf i : 0 < i < n -> (gX ^+ i != 1)%g by rewrite -dvdp_order => /Hp3.
have o_gt0 : 0 < #[gX]%g by rewrite order_gt0.
have : n <= #[gX]%g.
rewrite leqNgt; apply/negP=> oLx.
have /Hf/eqP[] : 0 < #[gX]%g < n by rewrite o_gt0.
by rewrite expg_order.
case: ltngtP => nLo _ //.
have: uniq (path.traject (mulg gX) 1%g #[gX]%g).
by apply/card_uniqP; rewrite path.size_traject -(eq_card (cycle_traject gX)).
case: #[gX]%g o_gt0 nLo => //= n1 _ nLn1 /andP[/negP[]].
apply/path.trajectP; exists n.-1; first by rewrite prednK.
rewrite -iterSr prednK // -[LHS]Hx.
by elim: (n) => //= n2 <-; rewrite expgS.
Qed.
Lemma gX_all : <[gX]>%g = [set: {unit qT}]%G.
Proof.
apply/eqP; rewrite eqEcard; apply/andP; split.
by apply/subsetP=> i; rewrite inE.
rewrite leq_eqVlt; apply/orP; left; apply/eqP.
rewrite -orderE gX_order card_qfpoly -[in RHS](mk_monicE primitive_mi).
rewrite -card_qpoly -(cardC1 (0 : {poly %/ h with primitive_mi})).
rewrite cardsT card_sub.
by apply: eq_card => x; rewrite [LHS]unitfE.
Qed.
Let pred_card_qT_gt0 : 0 < #|qT|.-1.
Proof. by rewrite ltn_predRL card_qfpoly_gt1. Qed.
Definition qlogp (p : qT) : nat :=
odflt (Ordinal pred_card_qT_gt0) (pick [pred i in 'I_ _ | ('qX ^+ i == p)]).
Lemma qlogp_lt p : qlogp p < #|qT|.-1.
Proof. by rewrite /qlogp; case: pickP. Qed.
Lemma qlogp_qX (p : qT) : p != 0 -> 'qX ^+ (qlogp p) = p.
Proof.
move=> p_neq0.
have Up : p \in GRing.unit by rewrite unitfE.
pose gp : {unit qT}:= FinRing.unit _ Up.
have /cyclePmin[i iLc iX] : gp \in <[gX]>%g by rewrite gX_all inE.
rewrite gX_order in iLc.
rewrite /qlogp; case: pickP => [j /eqP//|/(_ (Ordinal iLc))] /eqP[].
by have /val_eqP/eqP/= := iX; rewrite FinRing.val_unitX.
Qed.
Lemma qX_order_card : 'qX ^+ (#|qT|).-1 = 1 :> qT.
Proof.
have /primitive_polyP [_ Hd _] := Hh.
rewrite dvdp_order in Hd.
have -> : 1 = val (1%g : {unit qT}) by [].
by rewrite -(eqP Hd) val_unitX.
Qed.
Lemma qX_order_dvd (i : nat) : 'qX ^+ i = 1 :> qT -> (#|qT|.-1 %| i)%N.
Proof.
rewrite -gX_order cyclic.order_dvdn => Hd.
by apply/eqP/val_inj; rewrite /= -Hd val_unitX.
Qed.
Lemma qlogp0 : qlogp 0 = 0%N.
Proof.
rewrite /qlogp; case: pickP => //= x.
by rewrite (expf_eq0 ('qX : qT)) (negPf qX_neq0) andbF.
Qed.
Lemma qlogp1 : qlogp 1 = 0%N.
Proof.
case: (qlogp 1 =P 0%N) => // /eqP log1_neq0.
have := qlogp_lt 1; rewrite ltnNge => /negP[].
apply: dvdn_leq; first by rewrite lt0n.
by rewrite qX_order_dvd // qlogp_qX ?oner_eq0.
Qed.
Lemma qlogp_eq0 (q : qT) : (qlogp q == 0%N) = (q == 0) || (q == 1).
Proof.
case: (q =P 0) => [->|/eqP q_neq0]/=; first by rewrite qlogp0.
case: (q =P 1) => [->|/eqP q_neq1]/=; first by rewrite qlogp1.
rewrite /qlogp; case: pickP => [x|/(_ (Ordinal (qlogp_lt q)))] /=.
by case: ((x : nat) =P 0%N) => // ->; rewrite expr0 eq_sym (negPf q_neq1).
by rewrite qlogp_qX // eqxx.
Qed.
Lemma qX_exp_neq0 i : 'qX ^+ i != 0 :> qT.
Proof. by rewrite expf_eq0 negb_and qX_neq0 orbT. Qed.
Lemma qX_exp_inj i j :
i < #|qT|.-1 -> j < #|qT|.-1 -> 'qX ^+ i = 'qX ^+ j :> qT -> i = j.
Proof.
wlog iLj : i j / (i <= j)%N => [Hw|] iL jL Hqx.
case: (ltngtP i j)=> // /ltnW iLj; first by apply: Hw.
by apply/sym_equal/Hw.
suff ji_eq0 : (j - i = 0)%N by rewrite -(subnK iLj) ji_eq0.
case: ((j - i)%N =P 0%N) => // /eqP ji_neq0.
have : j - i < #|qT|.-1 by apply: leq_ltn_trans (leq_subr _ _) jL.
rewrite ltnNge => /negP[].
apply: dvdn_leq; first by rewrite lt0n.
have HqXi : 'qX ^+ i != 0 :> qT by rewrite expf_eq0 (negPf qX_neq0) andbF.
by apply/qX_order_dvd/(mulIf HqXi); rewrite mul1r -exprD subnK.
Qed.
Lemma powX_eq_mod i j : i = j %[mod #|qT|.-1] -> 'qX ^+ i = 'qX ^+ j :> qT.
Proof.
set n := _.-1 => iEj.
rewrite [i](divn_eq i n) [j](divn_eq j n) !exprD ![(_ * n)%N]mulnC.
by rewrite !exprM !qX_order_card !expr1n !mul1r iEj.
Qed.
Lemma qX_expK i : i < #|qT|.-1 -> qlogp ('qX ^+ i) = i.
Proof.
move=> iLF; apply: qX_exp_inj => //; first by apply: qlogp_lt.
by rewrite qlogp_qX // expf_eq0 (negPf qX_neq0) andbF.
Qed.
Lemma qlogpD (q1 q2 : qT) :
q1 != 0 -> q2 != 0 ->qlogp (q1 * q2) = ((qlogp q1 + qlogp q2) %% #|qT|.-1)%N.
Proof.
move=> q1_neq0 q2_neq0.
apply: qX_exp_inj; [apply: qlogp_lt => // | rewrite ltn_mod // |].
rewrite -[RHS]mul1r -(expr1n _ ((qlogp q1 + qlogp q2) %/ #|qT|.-1)).
rewrite -qX_order_card -exprM mulnC -exprD -divn_eq exprD !qlogp_qX //.
by rewrite mulf_eq0 negb_or q1_neq0.
Qed.
End PrimitivePoly.
Section Plogp.
Variable F : finFieldType.
Definition plogp (p q : {poly F}) :=
if boolP (primitive_poly p) is AltTrue Hh then
qlogp ((in_qpoly p q) : {poly %/ p with primitive_mi Hh})
else 0%N.
Lemma plogp_lt (p q : {poly F}) : 2 < size p -> plogp p q < #|{poly %/ p}|.-1.
Proof.
move=> /ltnW size_gt1.
rewrite /plogp.
case (boolP (primitive_poly p)) => // Hh; first by apply: qlogp_lt.
by rewrite ltn_predRL (card_finNzRing_gt1 {poly %/ p}).
Qed.
Lemma plogp_X (p q : {poly F}) :
2 < size p -> primitive_poly p -> ~~ (p %| q) -> p %| q - 'X ^+ plogp p q.
Proof.
move=> sp_gt2 Hh pNDq.
rewrite /plogp.
case (boolP (primitive_poly p)) => // Hh'; last by case/negP: Hh'.
have pM : p \is monic by case/and4P: Hh'.
have pMi : monic_irreducible_poly p by apply: primitive_mi.
set q' : {poly %/ p with primitive_mi Hh'} := in_qpoly p q.
apply/modp_eq0P; rewrite modpD modpN; apply/eqP; rewrite subr_eq0; apply/eqP.
rewrite !Pdiv.IdomainMonic.modpE //=.
suff /val_eqP/eqP/= : 'qX ^+ qlogp q' = q'.
rewrite /= [X in rmodp _ X]mk_monicE // => <-.
by rewrite poly_of_qpolyX /= mk_monicE // [rmodp 'X p]rmodp_small ?size_polyX.
apply: qlogp_qX => //.
apply/eqP=> /val_eqP/eqP.
rewrite /= mk_monicE // => /rmodp_eq0P; rewrite -dvdpE => pDq.
by case/negP: pNDq.
Qed.
Lemma plogp0 (p : {poly F}) : 2 < size p -> plogp p 0 = 0%N.
Proof.
move=> sp_gt2; rewrite /plogp; case (boolP (primitive_poly p)) => // i.
by rewrite in_qpoly0 qlogp0.
Qed.
Lemma plogp1 (p : {poly F}) : 2 < size p -> plogp p 1 = 0%N.
Proof.
move=> sp_gt2; rewrite /plogp; case (boolP (primitive_poly p)) => // i.
suff->: in_qpoly p 1 = 1 by apply: qlogp1.
apply/val_eqP/eqP; apply: in_qpoly_small.
rewrite mk_monicE ?size_poly1 ?(leq_trans _ sp_gt2) //.
by apply: primitive_mi.
Qed.
Lemma plogp_div_eq0 (p q : {poly F}) :
2 < size p -> (p %| q) -> plogp p q = 0%N.
Proof.
move=> sp_gt2; rewrite /plogp; case (boolP (primitive_poly p)) => // i pDq.
suff-> : in_qpoly p q = 0 by apply: qlogp0.
by apply/eqP; rewrite primitive_poly_in_qpoly_eq0.
Qed.
Lemma plogpD (p q1 q2 : {poly F}) :
2 < size p -> primitive_poly p -> ~~ (p %| q1) -> ~~ (p %| q2) ->
plogp p (q1 * q2) = ((plogp p q1 + plogp p q2) %% #|{poly %/ p}|.-1)%N.
Proof.
move=> sp_gt2 Pp pNDq1 pNDq2.
rewrite /plogp; case (boolP (primitive_poly p)) => [|/negP//] i /=.
have pmi := primitive_mi i.
by rewrite rmorphM qlogpD //= primitive_poly_in_qpoly_eq0.
Qed.
End Plogp.
|
Basic.lean
|
/-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Floris van Doorn
-/
import Mathlib.Algebra.GroupWithZero.Basic
import Mathlib.Algebra.Group.Pointwise.Set.Basic
/-!
# Pointwise operations of sets in a group with zero
This file proves properties of pointwise operations of sets in a group with zero.
## Tags
set multiplication, set addition, pointwise addition, pointwise multiplication,
pointwise subtraction
-/
assert_not_exists MulAction OrderedAddCommMonoid Ring
open Function
open scoped Pointwise
variable {α : Type*}
namespace Set
section MulZeroClass
variable [MulZeroClass α] {s : Set α}
/-! Note that `Set` is not a `MulZeroClass` because `0 * ∅ ≠ 0`. -/
lemma mul_zero_subset (s : Set α) : s * 0 ⊆ 0 := by simp [subset_def, mem_mul]
lemma zero_mul_subset (s : Set α) : 0 * s ⊆ 0 := by simp [subset_def, mem_mul]
lemma Nonempty.mul_zero (hs : s.Nonempty) : s * 0 = 0 :=
s.mul_zero_subset.antisymm <| by simpa [mem_mul] using hs
lemma Nonempty.zero_mul (hs : s.Nonempty) : 0 * s = 0 :=
s.zero_mul_subset.antisymm <| by simpa [mem_mul] using hs
end MulZeroClass
section GroupWithZero
variable [GroupWithZero α] {s : Set α}
lemma div_zero_subset (s : Set α) : s / 0 ⊆ 0 := by simp [subset_def, mem_div]
lemma zero_div_subset (s : Set α) : 0 / s ⊆ 0 := by simp [subset_def, mem_div]
lemma Nonempty.div_zero (hs : s.Nonempty) : s / 0 = 0 :=
s.div_zero_subset.antisymm <| by simpa [mem_div] using hs
lemma Nonempty.zero_div (hs : s.Nonempty) : 0 / s = 0 :=
s.zero_div_subset.antisymm <| by simpa [mem_div] using hs
@[simp] protected lemma inv_zero : (0 : Set α)⁻¹ = 0 := by ext; simp
end GroupWithZero
end Set
|
Lemmas.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.Divisibility.Hom
import Mathlib.Algebra.Group.Irreducible.Lemmas
import Mathlib.Algebra.GroupWithZero.Equiv
import Mathlib.Algebra.Prime.Defs
import Mathlib.Order.Monotone.Defs
/-!
# Associated, prime, and irreducible 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`,
however this is not true in general.
We also define an equivalence relation `Associated`
saying that two elements of a monoid differ by a multiplication by a unit.
Then we show that the quotient type `Associates` is a monoid
and prove basic properties of this quotient.
-/
assert_not_exists OrderedCommMonoid Multiset
variable {M N : Type*}
section Prime
variable [CommMonoidWithZero M]
section Map
variable [CommMonoidWithZero N] {F : Type*} {G : Type*} [FunLike F M N]
variable [MonoidWithZeroHomClass F M N] [FunLike G N M] [MulHomClass G N M]
variable (f : F) (g : G) {p : M}
theorem comap_prime (hinv : ∀ a, g (f a : N) = a) (hp : Prime (f p)) : Prime p :=
⟨fun h => hp.1 <| by simp [h], fun h => hp.2.1 <| h.map f, fun a b h => by
refine
(hp.2.2 (f a) (f b) <| by
convert map_dvd f h
simp).imp
?_ ?_ <;>
· intro h
convert ← map_dvd g h <;> apply hinv⟩
theorem MulEquiv.prime_iff {E : Type*} [EquivLike E M N] [MulEquivClass E M N] (e : E) :
Prime (e p) ↔ Prime p := by
let e := MulEquivClass.toMulEquiv e
exact ⟨comap_prime e e.symm fun a => by simp,
fun h => (comap_prime e.symm e fun a => by simp) <| (e.symm_apply_apply p).substr h⟩
end Map
end Prime
theorem Prime.left_dvd_or_dvd_right_of_dvd_mul [CancelCommMonoidWithZero M] {p : M} (hp : Prime p)
{a b : M} : a ∣ p * b → p ∣ a ∨ a ∣ b := by
rintro ⟨c, hc⟩
rcases hp.2.2 a c (hc ▸ dvd_mul_right _ _) with (h | ⟨x, rfl⟩)
· exact Or.inl h
· rw [mul_left_comm, mul_right_inj' hp.ne_zero] at hc
exact Or.inr (hc.symm ▸ dvd_mul_right _ _)
theorem Prime.pow_dvd_of_dvd_mul_left [CancelCommMonoidWithZero M] {p a b : M} (hp : Prime p)
(n : ℕ) (h : ¬p ∣ a) (h' : p ^ n ∣ a * b) : p ^ n ∣ b := by
induction n with
| zero =>
rw [pow_zero]
exact one_dvd b
| succ n ih =>
obtain ⟨c, rfl⟩ := ih (dvd_trans (pow_dvd_pow p n.le_succ) h')
rw [pow_succ]
apply mul_dvd_mul_left _ ((hp.dvd_or_dvd _).resolve_left h)
rwa [← mul_dvd_mul_iff_left (pow_ne_zero n hp.ne_zero), ← pow_succ, mul_left_comm]
theorem Prime.pow_dvd_of_dvd_mul_right [CancelCommMonoidWithZero M] {p a b : M} (hp : Prime p)
(n : ℕ) (h : ¬p ∣ b) (h' : p ^ n ∣ a * b) : p ^ n ∣ a := by
rw [mul_comm] at h'
exact hp.pow_dvd_of_dvd_mul_left n h h'
theorem Prime.dvd_of_pow_dvd_pow_mul_pow_of_square_not_dvd [CancelCommMonoidWithZero M] {p a b : M}
{n : ℕ} (hp : Prime p) (hpow : p ^ n.succ ∣ a ^ n.succ * b ^ n) (hb : ¬p ^ 2 ∣ b) : p ∣ a := by
-- Suppose `p ∣ b`, write `b = p * x` and `hy : a ^ n.succ * b ^ n = p ^ n.succ * y`.
rcases hp.dvd_or_dvd ((dvd_pow_self p (Nat.succ_ne_zero n)).trans hpow) with H | hbdiv
· exact hp.dvd_of_dvd_pow H
obtain ⟨x, rfl⟩ := hp.dvd_of_dvd_pow hbdiv
obtain ⟨y, hy⟩ := hpow
-- Then we can divide out a common factor of `p ^ n` from the equation `hy`.
have : a ^ n.succ * x ^ n = p * y := by
refine mul_left_cancel₀ (pow_ne_zero n hp.ne_zero) ?_
rw [← mul_assoc _ p, ← pow_succ, ← hy, mul_pow, ← mul_assoc (a ^ n.succ), mul_comm _ (p ^ n),
mul_assoc]
-- So `p ∣ a` (and we're done) or `p ∣ x`, which can't be the case since it implies `p^2 ∣ b`.
refine hp.dvd_of_dvd_pow ((hp.dvd_or_dvd ⟨_, this⟩).resolve_right fun hdvdx => hb ?_)
obtain ⟨z, rfl⟩ := hp.dvd_of_dvd_pow hdvdx
rw [pow_two, ← mul_assoc]
exact dvd_mul_right _ _
theorem prime_pow_succ_dvd_mul {M : Type*} [CancelCommMonoidWithZero M] {p x y : M} (h : Prime p)
{i : ℕ} (hxy : p ^ (i + 1) ∣ x * y) : p ^ (i + 1) ∣ x ∨ p ∣ y := by
rw [or_iff_not_imp_right]
exact fun a ↦ Prime.pow_dvd_of_dvd_mul_right h (i + 1) a hxy
section CancelCommMonoidWithZero
variable [CancelCommMonoidWithZero M] {a p : M}
theorem succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul (hp : Prime p) {a b : M} {k l : ℕ} :
p ^ k ∣ a → p ^ l ∣ b → p ^ (k + l + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b :=
fun ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩ =>
have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z) := by
simpa [mul_comm, pow_add, hx, hy, mul_assoc, mul_left_comm] using hz
have hp0 : p ^ (k + l) ≠ 0 := pow_ne_zero _ hp.ne_zero
have hpd : p ∣ x * y := ⟨z, by rwa [mul_right_inj' hp0] at h⟩
(hp.dvd_or_dvd hpd).elim
(fun ⟨d, hd⟩ => Or.inl ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩)
fun ⟨d, hd⟩ => Or.inr ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩
theorem Prime.not_isSquare (hp : Prime p) : ¬IsSquare p :=
hp.irreducible.not_isSquare
@[deprecated (since := "2025-04-17")]
alias Prime.not_square := Prime.not_isSquare
theorem IsSquare.not_prime (ha : IsSquare a) : ¬Prime a := fun h => h.not_isSquare ha
theorem not_prime_pow {n : ℕ} (hn : n ≠ 1) : ¬Prime (a ^ n) := fun hp =>
not_irreducible_pow hn hp.irreducible
end CancelCommMonoidWithZero
section CommMonoidWithZero
theorem DvdNotUnit.isUnit_of_irreducible_right [CommMonoidWithZero M] {p q : M}
(h : DvdNotUnit p q) (hq : Irreducible q) : IsUnit p := by
obtain ⟨_, x, hx, hx'⟩ := h
exact ((irreducible_iff.1 hq).right hx').resolve_right hx
theorem not_irreducible_of_not_unit_dvdNotUnit [CommMonoidWithZero M] {p q : M} (hp : ¬IsUnit p)
(h : DvdNotUnit p q) : ¬Irreducible q :=
mt h.isUnit_of_irreducible_right hp
theorem DvdNotUnit.not_unit [CommMonoidWithZero M] {p q : M} (hp : DvdNotUnit p q) : ¬IsUnit q := by
obtain ⟨-, x, hx, rfl⟩ := hp
exact fun hc => hx (isUnit_iff_dvd_one.mpr (dvd_of_mul_left_dvd (isUnit_iff_dvd_one.mp hc)))
end CommMonoidWithZero
section CancelCommMonoidWithZero
theorem DvdNotUnit.ne [CancelCommMonoidWithZero M] {p q : M} (h : DvdNotUnit p q) : p ≠ q := by
by_contra hcontra
obtain ⟨hp, x, hx', hx''⟩ := h
simp_all
theorem pow_injective_of_not_isUnit [CancelCommMonoidWithZero M] {q : M} (hq : ¬IsUnit q)
(hq' : q ≠ 0) : Function.Injective fun n : ℕ => q ^ n := by
refine injective_of_lt_imp_ne fun n m h => DvdNotUnit.ne ⟨pow_ne_zero n hq', q ^ (m - n), ?_, ?_⟩
· exact not_isUnit_of_not_isUnit_dvd hq (dvd_pow (dvd_refl _) (Nat.sub_pos_of_lt h).ne')
· exact (pow_mul_pow_sub q h.le).symm
theorem pow_inj_of_not_isUnit [CancelCommMonoidWithZero M] {q : M} (hq : ¬IsUnit q)
(hq' : q ≠ 0) {m n : ℕ} : q ^ m = q ^ n ↔ m = n :=
(pow_injective_of_not_isUnit hq hq').eq_iff
end CancelCommMonoidWithZero
|
GluingOneHypercover.lean
|
/-
Copyright (c) 2024 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Calle Sönne, Joël Riou, Ravi Vakil
-/
import Mathlib.AlgebraicGeometry.Gluing
import Mathlib.AlgebraicGeometry.Sites.BigZariski
import Mathlib.CategoryTheory.Sites.OneHypercover
/-!
# The 1-hypercover of a glue data
In this file, given `D : Scheme.GlueData`, we construct a 1-hypercover
`D.openHypercover` of the scheme `D.glued` in the big Zariski site.
We use this 1-hypercover in order to define a constructor `D.sheafValGluedMk`
for sections over `D.glued` of a sheaf of types over the big Zariski site.
## Notes
This contribution was created as part of the AIM workshop
"Formalizing algebraic geometry" in June 2024.
-/
universe v u
open CategoryTheory Opposite Limits
namespace AlgebraicGeometry.Scheme.GlueData
variable (D : Scheme.GlueData.{u})
/-- The 1-hypercover of `D.glued` in the big Zariski site that is given by the
open cover `D.U` from the glue data `D`.
The "covering of the intersection of two such open subsets" is the trivial
covering given by `D.V`. -/
@[simps]
noncomputable def oneHypercover : Scheme.zariskiTopology.OneHypercover D.glued where
I₀ := D.J
X := D.U
f := D.ι
I₁ _ _ := PUnit
Y i₁ i₂ _ := D.V (i₁, i₂)
p₁ i₁ i₂ _ := D.f i₁ i₂
p₂ i₁ i₂ _ := D.t i₁ i₂ ≫ D.f i₂ i₁
w i₁ i₂ _ := by simp only [Category.assoc, Scheme.GlueData.glue_condition]
mem₀ := by
refine zariskiTopology.superset_covering ?_ (grothendieckTopology_cover D.openCover)
rw [Sieve.generate_le_iff]
rintro W _ ⟨i⟩
exact ⟨_, 𝟙 _, _, ⟨i⟩, by simp; rfl⟩
mem₁ i₁ i₂ W p₁ p₂ fac := by
refine zariskiTopology.superset_covering (fun T g _ ↦ ?_) (zariskiTopology.top_mem _)
have ⟨φ, h₁, h₂⟩ := PullbackCone.IsLimit.lift' (D.vPullbackConeIsLimit i₁ i₂)
(g ≫ p₁) (g ≫ p₂) (by simpa using g ≫= fac)
exact ⟨⟨⟩, φ, h₁.symm, h₂.symm⟩
section
variable {F : Sheaf Scheme.zariskiTopology (Type v)}
(s : ∀ (j : D.J), F.val.obj (op (D.U j)))
(h : ∀ (i j : D.J), F.val.map (D.f i j).op (s i) =
F.val.map ((D.f j i).op ≫ (D.t i j).op) (s j))
/-- Constructor for sections over `D.glued` of a sheaf of types on the big Zariski site. -/
noncomputable def sheafValGluedMk : F.val.obj (op D.glued) :=
Multifork.IsLimit.sectionsEquiv (D.oneHypercover.isLimitMultifork F)
{ val := s
property := fun _ ↦ h _ _ }
@[simp]
lemma sheafValGluedMk_val (j : D.J) : F.val.map (D.ι j).op (D.sheafValGluedMk s h) = s j :=
Multifork.IsLimit.sectionsEquiv_apply_val (D.oneHypercover.isLimitMultifork F) _ _
end
end AlgebraicGeometry.Scheme.GlueData
|
FunctorCategory.lean
|
/-
Copyright (c) 2024 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.CategoryTheory.Monoidal.FunctorCategory
import Mathlib.CategoryTheory.Enriched.Ordinary.Basic
import Mathlib.CategoryTheory.Functor.Category
import Mathlib.CategoryTheory.Limits.Shapes.End
/-!
# Functor categories are enriched
If `C` is a `V`-enriched ordinary category, then `J ⥤ C` is also
both a `V`-enriched ordinary category and a `J ⥤ V`-enriched
ordinary category, provided `C` has suitable limits.
We first define the `V`-enriched structure on `J ⥤ C` by saying
that if `F₁` and `F₂` are in `J ⥤ C`, then `enrichedHom V F₁ F₂ : V`
is a suitable limit involving `F₁.obj j ⟶[V] F₂.obj j` for all `j : C`.
The `J ⥤ V` object of morphisms `functorEnrichedHom V F₁ F₂ : J ⥤ V`
is defined by sending `j : J` to the previously defined `enrichedHom`
for the "restriction" of `F₁` and `F₂` to the category `Under j`.
The definition `isLimitConeFunctorEnrichedHom` shows that
`enriched V F₁ F₂` is the limit of the functor `functorEnrichedHom V F₁ F₂`.
-/
universe v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄
namespace CategoryTheory.Enriched.FunctorCategory
open Category MonoidalCategory Limits Functor
variable (V : Type u₁) [Category.{v₁} V] [MonoidalCategory V]
{C : Type u₂} [Category.{v₂} C] {J : Type u₃} [Category.{v₃} J]
{K : Type u₄} [Category.{v₄} K] [EnrichedOrdinaryCategory V C]
variable (F₁ F₂ F₃ F₄ : J ⥤ C)
/-- Given two functors `F₁` and `F₂` from a category `J` to a `V`-enriched
ordinary category `C`, this is the diagram `Jᵒᵖ ⥤ J ⥤ V` whose end shall be
the `V`-morphisms in `J ⥤ V` from `F₁` to `F₂`. -/
@[simps!]
def diagram : Jᵒᵖ ⥤ J ⥤ V := F₁.op ⋙ eHomFunctor V C ⋙ (whiskeringLeft J C V).obj F₂
/-- The condition that the end `diagram V F₁ F₂` exists, see `enrichedHom`. -/
abbrev HasEnrichedHom := HasEnd (diagram V F₁ F₂)
section
variable [HasEnrichedHom V F₁ F₂]
/-- The `V`-enriched hom from `F₁` to `F₂` when `F₁` and `F₂` are functors `J ⥤ C`
and `C` is a `V`-enriched category. -/
noncomputable abbrev enrichedHom : V := end_ (diagram V F₁ F₂)
/-- The projection `enrichedHom V F₁ F₂ ⟶ F₁.obj j ⟶[V] F₂.obj j` in the category `V`
for any `j : J` when `F₁` and `F₂` are functors `J ⥤ C` and `C` is a `V`-enriched category. -/
noncomputable abbrev enrichedHomπ (j : J) : enrichedHom V F₁ F₂ ⟶ F₁.obj j ⟶[V] F₂.obj j :=
end_.π _ j
@[reassoc]
lemma enrichedHom_condition {i j : J} (f : i ⟶ j) :
enrichedHomπ V F₁ F₂ i ≫ eHomWhiskerLeft V (F₁.obj i) (F₂.map f) =
enrichedHomπ V F₁ F₂ j ≫ eHomWhiskerRight V (F₁.map f) (F₂.obj j) :=
end_.condition (diagram V F₁ F₂) f
@[reassoc]
lemma enrichedHom_condition' {i j : J} (f : i ⟶ j) :
enrichedHomπ V F₁ F₂ i ≫ (ρ_ _).inv ≫
_ ◁ (eHomEquiv V) (F₂.map f) ≫ eComp V _ _ _ =
enrichedHomπ V F₁ F₂ j ≫ (λ_ _).inv ≫
(eHomEquiv V) (F₁.map f) ▷ _ ≫ eComp V _ _ _ :=
end_.condition (diagram V F₁ F₂) f
variable {F₁ F₂}
/-- Given functors `F₁` and `F₂` in `J ⥤ C`, where `C` is a `V`-enriched ordinary category,
this is the bijection `(F₁ ⟶ F₂) ≃ (𝟙_ V ⟶ enrichedHom V F₁ F₂)`. -/
noncomputable def homEquiv : (F₁ ⟶ F₂) ≃ (𝟙_ V ⟶ enrichedHom V F₁ F₂) where
toFun τ := end_.lift (fun j ↦ eHomEquiv V (τ.app j)) (fun i j f ↦ by
trans eHomEquiv V (τ.app i ≫ F₂.map f)
· dsimp
simp only [eHomEquiv_comp, tensorHom_def_assoc, MonoidalCategory.whiskerRight_id,
← unitors_equal, assoc, Iso.inv_hom_id_assoc, eHomWhiskerLeft]
· dsimp
simp only [← NatTrans.naturality, eHomEquiv_comp, tensorHom_def', id_whiskerLeft,
assoc, Iso.inv_hom_id_assoc, eHomWhiskerRight])
invFun g :=
{ app := fun j ↦ (eHomEquiv V).symm (g ≫ end_.π _ j)
naturality := fun i j f ↦ (eHomEquiv V).injective (by
simp only [eHomEquiv_comp, Equiv.apply_symm_apply, Iso.cancel_iso_inv_left]
conv_rhs =>
rw [tensorHom_def_assoc, MonoidalCategory.whiskerRight_id_assoc, assoc,
enrichedHom_condition' V F₁ F₂ f]
conv_lhs =>
rw [tensorHom_def'_assoc, MonoidalCategory.whiskerLeft_comp_assoc,
id_whiskerLeft_assoc, id_whiskerLeft_assoc, Iso.inv_hom_id_assoc, unitors_equal]) }
left_inv τ := by aesop
right_inv g := by aesop
@[reassoc (attr := simp)]
lemma homEquiv_apply_π (τ : F₁ ⟶ F₂) (j : J) :
homEquiv V τ ≫ enrichedHomπ V _ _ j = eHomEquiv V (τ.app j) := by
simp [homEquiv]
end
section
variable [HasEnrichedHom V F₁ F₁]
/-- The identity for the `V`-enrichment of the category `J ⥤ C`. -/
noncomputable def enrichedId : 𝟙_ V ⟶ enrichedHom V F₁ F₁ := homEquiv _ (𝟙 F₁)
@[reassoc (attr := simp)]
lemma enrichedId_π (j : J) : enrichedId V F₁ ≫ end_.π _ j = eId V (F₁.obj j) := by
simp [enrichedId]
@[simp]
lemma homEquiv_id : homEquiv V (𝟙 F₁) = enrichedId V F₁ := rfl
end
section
variable [HasEnrichedHom V F₁ F₂] [HasEnrichedHom V F₂ F₃] [HasEnrichedHom V F₁ F₃]
/-- The composition for the `V`-enrichment of the category `J ⥤ C`. -/
noncomputable def enrichedComp : enrichedHom V F₁ F₂ ⊗ enrichedHom V F₂ F₃ ⟶ enrichedHom V F₁ F₃ :=
end_.lift (fun j ↦ (end_.π _ j ⊗ₘ end_.π _ j) ≫ eComp V _ _ _) (fun i j f ↦ by
dsimp
trans (end_.π (diagram V F₁ F₂) i ⊗ₘ end_.π (diagram V F₂ F₃) j) ≫
(ρ_ _).inv ▷ _ ≫ (_ ◁ (eHomEquiv V (F₂.map f))) ▷ _ ≫ eComp V _ (F₂.obj i) _ ▷ _ ≫
eComp V _ (F₂.obj j) _
· have := end_.condition (diagram V F₂ F₃) f
dsimp [eHomWhiskerLeft, eHomWhiskerRight] at this ⊢
conv_lhs => rw [assoc, tensorHom_def_assoc]
conv_rhs =>
rw [tensorHom_def_assoc, whisker_assoc_assoc, e_assoc,
triangle_assoc_comp_right_inv_assoc, ← MonoidalCategory.whiskerLeft_comp_assoc,
← MonoidalCategory.whiskerLeft_comp_assoc, ← MonoidalCategory.whiskerLeft_comp_assoc,
assoc, assoc, ← this, MonoidalCategory.whiskerLeft_comp_assoc,
MonoidalCategory.whiskerLeft_comp_assoc, MonoidalCategory.whiskerLeft_comp_assoc,
← e_assoc, whiskerLeft_rightUnitor_inv_assoc, associator_inv_naturality_right_assoc,
Iso.hom_inv_id_assoc, whisker_exchange_assoc, MonoidalCategory.whiskerRight_id_assoc,
Iso.inv_hom_id_assoc]
· have := end_.condition (diagram V F₁ F₂) f
dsimp [eHomWhiskerLeft, eHomWhiskerRight] at this ⊢
conv_lhs =>
rw [tensorHom_def'_assoc, ← comp_whiskerRight_assoc,
← comp_whiskerRight_assoc, ← comp_whiskerRight_assoc,
assoc, assoc, this, comp_whiskerRight_assoc, comp_whiskerRight_assoc,
comp_whiskerRight_assoc, leftUnitor_inv_whiskerRight_assoc,
← associator_inv_naturality_left_assoc, ← e_assoc',
Iso.inv_hom_id_assoc, ← whisker_exchange_assoc, id_whiskerLeft_assoc,
Iso.inv_hom_id_assoc]
conv_rhs => rw [assoc, tensorHom_def'_assoc])
@[reassoc (attr := simp)]
lemma enrichedComp_π (j : J) :
enrichedComp V F₁ F₂ F₃ ≫ end_.π _ j =
(end_.π (diagram V F₁ F₂) j ⊗ₘ end_.π (diagram V F₂ F₃) j) ≫ eComp V _ _ _ := by
simp [enrichedComp]
variable {F₁ F₂ F₃}
@[reassoc]
lemma homEquiv_comp (f : F₁ ⟶ F₂) (g : F₂ ⟶ F₃) :
(homEquiv V) (f ≫ g) = (λ_ (𝟙_ V)).inv ≫ ((homEquiv V) f ⊗ₘ (homEquiv V) g) ≫
enrichedComp V F₁ F₂ F₃ := by
ext j
simp only [homEquiv_apply_π, NatTrans.comp_app, eHomEquiv_comp, assoc,
enrichedComp_π, Functor.op_obj, ← tensor_comp_assoc]
end
@[reassoc (attr := simp)]
lemma enriched_id_comp [HasEnrichedHom V F₁ F₁] [HasEnrichedHom V F₁ F₂] :
(λ_ (enrichedHom V F₁ F₂)).inv ≫ enrichedId V F₁ ▷ enrichedHom V F₁ F₂ ≫
enrichedComp V F₁ F₁ F₂ = 𝟙 _ := by
ext j
rw [assoc, assoc, enrichedComp_π, id_comp, tensorHom_def, assoc,
← comp_whiskerRight_assoc, enrichedId_π, ← whisker_exchange_assoc,
id_whiskerLeft, assoc, assoc, Iso.inv_hom_id_assoc]
dsimp
rw [e_id_comp, comp_id]
@[reassoc (attr := simp)]
lemma enriched_comp_id [HasEnrichedHom V F₁ F₂] [HasEnrichedHom V F₂ F₂] :
(ρ_ (enrichedHom V F₁ F₂)).inv ≫ enrichedHom V F₁ F₂ ◁ enrichedId V F₂ ≫
enrichedComp V F₁ F₂ F₂ = 𝟙 _ := by
ext j
rw [assoc, assoc, enrichedComp_π, id_comp, tensorHom_def', assoc,
← MonoidalCategory.whiskerLeft_comp_assoc, enrichedId_π,
whisker_exchange_assoc, MonoidalCategory.whiskerRight_id, assoc, assoc,
Iso.inv_hom_id_assoc]
dsimp
rw [e_comp_id, comp_id]
@[reassoc]
lemma enriched_assoc [HasEnrichedHom V F₁ F₂] [HasEnrichedHom V F₁ F₃] [HasEnrichedHom V F₁ F₄]
[HasEnrichedHom V F₂ F₃] [HasEnrichedHom V F₂ F₄] [HasEnrichedHom V F₃ F₄] :
(α_ (enrichedHom V F₁ F₂) (enrichedHom V F₂ F₃) (enrichedHom V F₃ F₄)).inv ≫
enrichedComp V F₁ F₂ F₃ ▷ enrichedHom V F₃ F₄ ≫ enrichedComp V F₁ F₃ F₄ =
enrichedHom V F₁ F₂ ◁ enrichedComp V F₂ F₃ F₄ ≫ enrichedComp V F₁ F₂ F₄ := by
ext j
conv_lhs =>
rw [assoc, assoc, enrichedComp_π,
tensorHom_def_assoc, ← comp_whiskerRight_assoc, enrichedComp_π,
comp_whiskerRight_assoc, ← whisker_exchange_assoc,
← whisker_exchange_assoc, ← tensorHom_def'_assoc, ← associator_inv_naturality_assoc]
conv_rhs =>
rw [assoc, enrichedComp_π, tensorHom_def'_assoc, ← MonoidalCategory.whiskerLeft_comp_assoc,
enrichedComp_π, MonoidalCategory.whiskerLeft_comp_assoc, whisker_exchange_assoc,
whisker_exchange_assoc, ← tensorHom_def_assoc]
dsimp
rw [e_assoc]
variable (J C)
/-- If `C` is a `V`-enriched ordinary category, and `C` has suitable limits,
then `J ⥤ C` is also a `V`-enriched ordinary category. -/
noncomputable def enrichedOrdinaryCategory [∀ (F₁ F₂ : J ⥤ C), HasEnrichedHom V F₁ F₂] :
EnrichedOrdinaryCategory V (J ⥤ C) where
Hom F₁ F₂ := enrichedHom V F₁ F₂
id F := enrichedId V F
comp F₁ F₂ F₃ := enrichedComp V F₁ F₂ F₃
assoc _ _ _ _ := enriched_assoc _ _ _ _ _
homEquiv := homEquiv V
homEquiv_id _ := homEquiv_id V _
homEquiv_comp f g := homEquiv_comp V f g
variable {J C}
section
variable (G : K ⥤ J) [HasEnrichedHom V F₁ F₂]
variable {F₁ F₂} in
/-- If `F₁` and `F₂` are functors `J ⥤ C`, `G : K ⥤ J`, and
`F₁'` and `F₂'` are functors `K ⥤ C` that are respectively
isomorphic to `G ⋙ F₁` and `G ⋙ F₂`, then this is the
induced morphism `enrichedHom V F₁ F₂ ⟶ enrichedHom V F₁' F₂'` in `V`
when `C` is a category enriched in `V`. -/
noncomputable abbrev precompEnrichedHom' {F₁' F₂' : K ⥤ C}
[HasEnrichedHom V F₁' F₂'] (e₁ : G ⋙ F₁ ≅ F₁') (e₂ : G ⋙ F₂ ≅ F₂') :
enrichedHom V F₁ F₂ ⟶ enrichedHom V F₁' F₂' :=
end_.lift (fun x ↦ enrichedHomπ V F₁ F₂ (G.obj x) ≫
(eHomWhiskerRight _ (e₁.inv.app x) _ ≫ eHomWhiskerLeft _ _ (e₂.hom.app x)))
(fun i j f ↦ by
dsimp
rw [assoc, assoc, assoc, assoc, ← eHomWhiskerLeft_comp,
← eHom_whisker_exchange, ← e₂.hom.naturality f,
eHomWhiskerLeft_comp_assoc]
dsimp
rw [enrichedHom_condition_assoc, eHom_whisker_exchange,
eHom_whisker_exchange, ← eHomWhiskerRight_comp_assoc,
← eHomWhiskerRight_comp_assoc, NatTrans.naturality]
dsimp )
/-- If `F₁` and `F₂` are functors `J ⥤ C`, and `G : K ⥤ J`,
then this is the induced morphism
`enrichedHom V F₁ F₂ ⟶ enrichedHom V (G ⋙ F₁) (G ⋙ F₂)` in `V`
when `C` is a category enriched in `V`. -/
noncomputable abbrev precompEnrichedHom
[HasEnrichedHom V (G ⋙ F₁) (G ⋙ F₂)] :
enrichedHom V F₁ F₂ ⟶ enrichedHom V (G ⋙ F₁) (G ⋙ F₂) :=
precompEnrichedHom' V G (Iso.refl _) (Iso.refl _)
end
section
/-- Given functors `F₁` and `F₂` in `J ⥤ C`, where `C` is a category enriched in `V`,
this condition allows the definition of `functorEnrichedHom V F₁ F₂ : J ⥤ V`. -/
abbrev HasFunctorEnrichedHom :=
∀ (j : J), HasEnrichedHom V (Under.forget j ⋙ F₁) (Under.forget j ⋙ F₂)
variable [HasFunctorEnrichedHom V F₁ F₂]
instance {j j' : J} (f : j ⟶ j') :
HasEnrichedHom V (Under.map f ⋙ Under.forget j ⋙ F₁)
(Under.map f ⋙ Under.forget j ⋙ F₂) :=
inferInstanceAs (HasEnrichedHom V (Under.forget j' ⋙ F₁) (Under.forget j' ⋙ F₂))
/-- Given functors `F₁` and `F₂` in `J ⥤ C`, where `C` is a category enriched in `V`,
this is the enriched hom functor from `F₁` to `F₂` in `J ⥤ V`. -/
@[simps!]
noncomputable def functorEnrichedHom : J ⥤ V where
obj j := enrichedHom V (Under.forget j ⋙ F₁) (Under.forget j ⋙ F₂)
map f := precompEnrichedHom' V (Under.map f) (Iso.refl _) (Iso.refl _)
map_id X := by
ext j
-- this was produced by `simp?`
simp only [diagram_obj_obj, Functor.comp_obj, Under.forget_obj, end_.lift_π,
Under.map_obj_right, Iso.refl_inv, NatTrans.id_app, eHomWhiskerRight_id, Iso.refl_hom,
eHomWhiskerLeft_id, comp_id, id_comp]
congr 1
simp [Under.map, Comma.mapLeft]
rfl
map_comp f g := by
ext j
-- this was produced by `simp?`
simp only [diagram_obj_obj, Functor.comp_obj, Under.forget_obj, end_.lift_π,
Under.map_obj_right, Iso.refl_inv, NatTrans.id_app, eHomWhiskerRight_id, Iso.refl_hom,
eHomWhiskerLeft_id, comp_id, assoc]
congr 1
simp [Under.map, Comma.mapLeft]
variable [HasEnrichedHom V F₁ F₂]
/-- The (limit) cone expressing that the limit of `functorEnrichedHom V F₁ F₂`
is `enrichedHom V F₁ F₂`. -/
@[simps]
noncomputable def coneFunctorEnrichedHom : Cone (functorEnrichedHom V F₁ F₂) where
pt := enrichedHom V F₁ F₂
π := { app := fun j ↦ precompEnrichedHom V F₁ F₂ (Under.forget j) }
namespace isLimitConeFunctorEnrichedHom
variable {V F₁ F₂} (s : Cone (functorEnrichedHom V F₁ F₂))
/-- Auxiliary definition for `Enriched.FunctorCategory.isLimitConeFunctorEnrichedHom`. -/
noncomputable def lift : s.pt ⟶ enrichedHom V F₁ F₂ :=
end_.lift (fun j ↦ s.π.app j ≫ enrichedHomπ V _ _ (Under.mk (𝟙 j))) (fun j j' f ↦ by
dsimp
rw [← s.w f, assoc, assoc, assoc]
-- this was produced by `simp?`
simp only [functorEnrichedHom_obj, functorEnrichedHom_map, end_.lift_π_assoc, diagram_obj_obj,
Functor.comp_obj, Under.forget_obj, Under.mk_right, Under.map_obj_right, Iso.refl_inv,
NatTrans.id_app, eHomWhiskerRight_id, Iso.refl_hom, eHomWhiskerLeft_id, comp_id]
have := enrichedHom_condition V (Under.forget j ⋙ F₁) (Under.forget j ⋙ F₂)
(Under.homMk f : Under.mk (𝟙 j) ⟶ Under.mk f)
dsimp at this
rw [this]
congr 3
simp [Under.map, Comma.mapLeft]
rfl)
lemma fac (j : J) : lift s ≫ (coneFunctorEnrichedHom V F₁ F₂).π.app j = s.π.app j := by
dsimp [coneFunctorEnrichedHom]
ext k
have := s.w k.hom
dsimp at this
-- this was produced by `simp? [lift, ← this]`
simp only [diagram_obj_obj, Functor.comp_obj, Under.forget_obj, lift, functorEnrichedHom_obj,
assoc, end_.lift_π, Iso.refl_inv, NatTrans.id_app, eHomWhiskerRight_id, Iso.refl_hom,
eHomWhiskerLeft_id, comp_id, ← this, Under.map_obj_right, Under.mk_right]
congr
simp [Under.map, Comma.mapLeft]
rfl
end isLimitConeFunctorEnrichedHom
open isLimitConeFunctorEnrichedHom in
/-- The limit of `functorEnrichedHom V F₁ F₂` is `enrichedHom V F₁ F₂`. -/
noncomputable def isLimitConeFunctorEnrichedHom :
IsLimit (coneFunctorEnrichedHom V F₁ F₂) where
lift := lift
fac := fac
uniq s m hm := by
dsimp
ext j
simpa using ((hm j).trans (fac s j).symm) =≫ enrichedHomπ V _ _ (Under.mk (𝟙 j))
end
/-- The identity for the `J ⥤ V`-enrichment of the category `J ⥤ C`. -/
@[simps]
noncomputable def functorEnrichedId [HasFunctorEnrichedHom V F₁ F₁] :
𝟙_ (J ⥤ V) ⟶ functorEnrichedHom V F₁ F₁ where
app j := enrichedId V _
/-- The composition for the `J ⥤ V`-enrichment of the category `J ⥤ C`. -/
@[simps]
noncomputable def functorEnrichedComp [HasFunctorEnrichedHom V F₁ F₂]
[HasFunctorEnrichedHom V F₂ F₃] [HasFunctorEnrichedHom V F₁ F₃] :
functorEnrichedHom V F₁ F₂ ⊗ functorEnrichedHom V F₂ F₃ ⟶ functorEnrichedHom V F₁ F₃ where
app j := enrichedComp V _ _ _
naturality j j' f := by
dsimp
ext k
dsimp
rw [assoc, assoc, enrichedComp_π]
dsimp
rw [← tensor_comp_assoc]
simp
@[reassoc (attr := simp)]
lemma functorEnriched_id_comp [HasFunctorEnrichedHom V F₁ F₂] [HasFunctorEnrichedHom V F₁ F₁] :
(λ_ (functorEnrichedHom V F₁ F₂)).inv ≫
functorEnrichedId V F₁ ▷ functorEnrichedHom V F₁ F₂ ≫
functorEnrichedComp V F₁ F₁ F₂ = 𝟙 (functorEnrichedHom V F₁ F₂) := by cat_disch
@[reassoc (attr := simp)]
lemma functorEnriched_comp_id [HasFunctorEnrichedHom V F₁ F₂] [HasFunctorEnrichedHom V F₂ F₂] :
(ρ_ (functorEnrichedHom V F₁ F₂)).inv ≫
functorEnrichedHom V F₁ F₂ ◁ functorEnrichedId V F₂ ≫
functorEnrichedComp V F₁ F₂ F₂ = 𝟙 (functorEnrichedHom V F₁ F₂) := by cat_disch
@[reassoc]
lemma functorEnriched_assoc [HasFunctorEnrichedHom V F₁ F₂] [HasFunctorEnrichedHom V F₂ F₃]
[HasFunctorEnrichedHom V F₃ F₄] [HasFunctorEnrichedHom V F₁ F₃]
[HasFunctorEnrichedHom V F₂ F₄] [HasFunctorEnrichedHom V F₁ F₄] :
(α_ _ _ _).inv ≫ functorEnrichedComp V F₁ F₂ F₃ ▷ functorEnrichedHom V F₃ F₄ ≫
functorEnrichedComp V F₁ F₃ F₄ =
functorEnrichedHom V F₁ F₂ ◁ functorEnrichedComp V F₂ F₃ F₄ ≫
functorEnrichedComp V F₁ F₂ F₄ := by
ext j
dsimp
rw [enriched_assoc]
variable (J C) in
/-- If `C` is a `V`-enriched ordinary category, and `C` has suitable limits,
then `J ⥤ C` is also a `J ⥤ V`-enriched ordinary category. -/
noncomputable def functorEnrichedCategory
[∀ (F₁ F₂ : J ⥤ C), HasFunctorEnrichedHom V F₁ F₂] :
EnrichedCategory (J ⥤ V) (J ⥤ C) where
Hom F₁ F₂ := functorEnrichedHom V F₁ F₂
id F := functorEnrichedId V F
comp F₁ F₂ F₃ := functorEnrichedComp V F₁ F₂ F₃
assoc F₁ F₂ F₃ F₄ := functorEnriched_assoc V F₁ F₂ F₃ F₄
variable {F₁ F₂} in
/-- Given functors `F₁` and `F₂` in `J ⥤ C`, where `C` is a `V`-enriched ordinary category,
this is the bijection `(F₁ ⟶ F₂) ≃ (𝟙_ (J ⥤ V) ⟶ functorEnrichedHom V F₁ F₂)`. -/
@[simps! apply_app]
noncomputable def functorHomEquiv [HasFunctorEnrichedHom V F₁ F₂] [HasEnrichedHom V F₁ F₂] :
(F₁ ⟶ F₂) ≃ (𝟙_ (J ⥤ V) ⟶ functorEnrichedHom V F₁ F₂) :=
(homEquiv V).trans (isLimitConeFunctorEnrichedHom V F₁ F₂).homEquiv
lemma functorHomEquiv_id [HasFunctorEnrichedHom V F₁ F₁] [HasEnrichedHom V F₁ F₁] :
(functorHomEquiv V) (𝟙 F₁) = functorEnrichedId V F₁ := by cat_disch
variable {F₁ F₂ F₃} in
lemma functorHomEquiv_comp [HasFunctorEnrichedHom V F₁ F₂] [HasEnrichedHom V F₁ F₂]
[HasFunctorEnrichedHom V F₂ F₃] [HasEnrichedHom V F₂ F₃]
[HasFunctorEnrichedHom V F₁ F₃] [HasEnrichedHom V F₁ F₃]
(f : F₁ ⟶ F₂) (g : F₂ ⟶ F₃) :
(functorHomEquiv V) (f ≫ g) = (λ_ (𝟙_ (J ⥤ V))).inv ≫
((functorHomEquiv V) f ⊗ₘ (functorHomEquiv V) g) ≫ functorEnrichedComp V F₁ F₂ F₃ := by
ext j
dsimp
ext k
rw [homEquiv_comp, assoc, assoc, assoc, assoc, assoc, end_.lift_π, enrichedComp_π]
simp [← tensor_comp_assoc]
attribute [local instance] functorEnrichedCategory
variable (J C) in
/-- If `C` is a `V`-enriched ordinary category, and `C` has suitable limits,
then `J ⥤ C` is also a `J ⥤ V`-enriched ordinary category. -/
noncomputable def functorEnrichedOrdinaryCategory
[∀ (F₁ F₂ : J ⥤ C), HasFunctorEnrichedHom V F₁ F₂]
[∀ (F₁ F₂ : J ⥤ C), HasEnrichedHom V F₁ F₂] :
EnrichedOrdinaryCategory (J ⥤ V) (J ⥤ C) where
homEquiv := functorHomEquiv V
homEquiv_id F := functorHomEquiv_id V F
homEquiv_comp f g := functorHomEquiv_comp V f g
end CategoryTheory.Enriched.FunctorCategory
|
Notation.lean
|
/-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura
-/
import Mathlib.Init
/-!
# Notation `ℕ` for the natural numbers.
-/
@[inherit_doc] notation "ℕ" => Nat
|
Integral.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.RingTheory.IntegralClosure.IntegrallyClosed
import Mathlib.RingTheory.Valuation.Integers
/-!
# Integral elements over the ring of integers of a valuation
The ring of integers is integrally closed inside the original ring.
-/
universe u v w
namespace Valuation
namespace Integers
section CommRing
variable {R : Type u} {Γ₀ : Type v} [CommRing R] [LinearOrderedCommGroupWithZero Γ₀]
variable {v : Valuation R Γ₀} {O : Type w} [CommRing O] [Algebra O R] (hv : Integers v O)
include hv
open Polynomial
theorem mem_of_integral {x : R} (hx : IsIntegral O x) : x ∈ v.integer :=
let ⟨p, hpm, hpx⟩ := hx
le_of_not_gt fun hvx : 1 < v x => by
rw [hpm.as_sum, eval₂_add, eval₂_pow, eval₂_X, eval₂_finset_sum, add_eq_zero_iff_eq_neg] at hpx
replace hpx := congr_arg v hpx; refine ne_of_gt ?_ hpx
rw [v.map_neg, v.map_pow]
refine v.map_sum_lt' (zero_lt_one.trans_le (one_le_pow_of_one_le' hvx.le _)) fun i hi => ?_
rw [eval₂_mul, eval₂_pow, eval₂_C, eval₂_X, v.map_mul, v.map_pow, ←
one_mul (v x ^ p.natDegree)]
rcases (hv.2 <| p.coeff i).lt_or_eq with hvpi | hvpi
· exact mul_lt_mul'' hvpi (pow_lt_pow_right₀ hvx <| Finset.mem_range.1 hi) zero_le' zero_le'
· rw [hvpi, one_mul, one_mul]; exact pow_lt_pow_right₀ hvx (Finset.mem_range.1 hi)
protected theorem integralClosure : integralClosure O R = ⊥ :=
bot_unique fun _ hr =>
let ⟨x, hx⟩ := hv.3 (hv.mem_of_integral hr)
Algebra.mem_bot.2 ⟨x, hx⟩
end CommRing
section FractionField
variable {K : Type u} {Γ₀ : Type v} [Field K] [LinearOrderedCommGroupWithZero Γ₀]
variable {v : Valuation K Γ₀} {O : Type w} [CommRing O]
variable [Algebra O K] [IsFractionRing O K]
variable (hv : Integers v O)
include hv in
theorem integrallyClosed : IsIntegrallyClosed O :=
(IsIntegrallyClosed.integralClosure_eq_bot_iff K).mp (Valuation.Integers.integralClosure hv)
end FractionField
end Integers
end Valuation
|
HasColimits.lean
|
/-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import Mathlib.Geometry.RingedSpace.LocallyRingedSpace
import Mathlib.Algebra.Category.Ring.Constructions
import Mathlib.Geometry.RingedSpace.OpenImmersion
import Mathlib.CategoryTheory.Limits.Constructions.LimitsOfProductsAndEqualizers
/-!
# Colimits of LocallyRingedSpace
We construct the explicit coproducts and coequalizers of `LocallyRingedSpace`.
It then follows that `LocallyRingedSpace` has all colimits, and
`forgetToSheafedSpace` preserves them.
-/
namespace AlgebraicGeometry
universe w' w v u
open CategoryTheory CategoryTheory.Limits Opposite TopologicalSpace
attribute [local instance] Opposite.small
namespace SheafedSpace
variable {C : Type u} [Category.{v} C]
variable {J : Type w} [Category.{w'} J] [Small.{v} J] (F : J ⥤ SheafedSpace.{_, _, v} C)
theorem isColimit_exists_rep [HasLimitsOfShape Jᵒᵖ C] {c : Cocone F} (hc : IsColimit c) (x : c.pt) :
∃ (i : J) (y : F.obj i), (c.ι.app i).base y = x :=
Concrete.isColimit_exists_rep (F ⋙ forget C) (isColimitOfPreserves (forget C) hc) x
-- Porting note: argument `C` of colimit need to be made explicit, odd
theorem colimit_exists_rep [HasLimitsOfShape Jᵒᵖ C] (x : colimit (C := SheafedSpace C) F) :
∃ (i : J) (y : F.obj i), (colimit.ι F i).base y = x :=
Concrete.isColimit_exists_rep (F ⋙ SheafedSpace.forget C)
(isColimitOfPreserves (SheafedSpace.forget _) (colimit.isColimit F)) x
instance [HasLimits C] {X Y : SheafedSpace C} (f g : X ⟶ Y) : Epi (coequalizer.π f g).base := by
rw [← show _ = (coequalizer.π f g).base from
ι_comp_coequalizerComparison f g (SheafedSpace.forget C),
← PreservesCoequalizer.iso_hom]
apply epi_comp
end SheafedSpace
namespace LocallyRingedSpace
section HasCoproducts
variable {ι : Type v} [Small.{u} ι] (F : Discrete ι ⥤ LocallyRingedSpace.{u})
/-- The explicit coproduct for `F : discrete ι ⥤ LocallyRingedSpace`. -/
noncomputable def coproduct : LocallyRingedSpace where
toSheafedSpace := colimit (C := SheafedSpace.{u+1, u, u} CommRingCat.{u})
(F ⋙ forgetToSheafedSpace)
isLocalRing x := by
obtain ⟨i, y, ⟨⟩⟩ := SheafedSpace.colimit_exists_rep (F ⋙ forgetToSheafedSpace) x
haveI : IsLocalRing (((F ⋙ forgetToSheafedSpace).obj i).presheaf.stalk y) :=
(F.obj i).isLocalRing _
exact
(asIso ((colimit.ι (C := SheafedSpace.{u+1, u, u} CommRingCat.{u})
(F ⋙ forgetToSheafedSpace) i :).stalkMap y)).symm.commRingCatIsoToRingEquiv.isLocalRing
/-- The explicit coproduct cofan for `F : discrete ι ⥤ LocallyRingedSpace`. -/
noncomputable def coproductCofan : Cocone F where
pt := coproduct F
ι :=
{ app := fun j => ⟨colimit.ι (C := SheafedSpace.{u+1, u, u} CommRingCat.{u})
(F ⋙ forgetToSheafedSpace) j, inferInstance⟩
naturality := fun ⟨j⟩ ⟨j'⟩ ⟨⟨(f : j = j')⟩⟩ => by subst f; simp }
/-- The explicit coproduct cofan constructed in `coproduct_cofan` is indeed a colimit. -/
noncomputable def coproductCofanIsColimit : IsColimit (coproductCofan F) where
desc s :=
⟨colimit.desc (C := SheafedSpace.{u+1, u, u} CommRingCat.{u})
(F ⋙ forgetToSheafedSpace) (forgetToSheafedSpace.mapCocone s), by
intro x
obtain ⟨i, y, ⟨⟩⟩ := SheafedSpace.colimit_exists_rep (F ⋙ forgetToSheafedSpace) x
have := PresheafedSpace.stalkMap.comp
(colimit.ι (C := SheafedSpace.{u+1, u, u} CommRingCat.{u})
(F ⋙ forgetToSheafedSpace) i)
(colimit.desc (C := SheafedSpace.{u+1, u, u} CommRingCat.{u})
(F ⋙ forgetToSheafedSpace) (forgetToSheafedSpace.mapCocone s)) y
rw [← IsIso.comp_inv_eq] at this
erw [← this,
PresheafedSpace.stalkMap.congr_hom _ _
(colimit.ι_desc (C := SheafedSpace.{u+1, u, u} CommRingCat.{u})
(forgetToSheafedSpace.mapCocone s) i :)]
haveI :
IsLocalHom
(((forgetToSheafedSpace.mapCocone s).ι.app i).stalkMap y).hom :=
(s.ι.app i).2 y
infer_instance⟩
fac _ _ := LocallyRingedSpace.Hom.ext'
(colimit.ι_desc (C := SheafedSpace.{u+1, u, u} CommRingCat.{u}) _ _)
uniq s f h :=
LocallyRingedSpace.Hom.ext'
(IsColimit.uniq _ (forgetToSheafedSpace.mapCocone s) f.toShHom fun j =>
congr_arg LocallyRingedSpace.Hom.toShHom (h j))
instance : HasColimitsOfShape (Discrete ι) LocallyRingedSpace.{u} :=
⟨fun F => ⟨⟨⟨_, coproductCofanIsColimit F⟩⟩⟩⟩
noncomputable instance : PreservesColimitsOfShape (Discrete.{v} ι) forgetToSheafedSpace.{u} :=
⟨fun {G} =>
preservesColimit_of_preserves_colimit_cocone (coproductCofanIsColimit G)
((colimit.isColimit (C := SheafedSpace.{u+1, u, u} CommRingCat.{u}) _).ofIsoColimit
(Cocones.ext (Iso.refl _) fun _ => Category.comp_id _))⟩
end HasCoproducts
section HasCoequalizer
variable {X Y : LocallyRingedSpace.{v}} (f g : X ⟶ Y)
namespace HasCoequalizer
@[instance]
theorem coequalizer_π_app_isLocalHom
(U : TopologicalSpace.Opens (coequalizer f.toShHom g.toShHom).carrier) :
IsLocalHom ((coequalizer.π f.toShHom g.toShHom :).c.app (op U)).hom := by
have := ι_comp_coequalizerComparison f.toShHom g.toShHom SheafedSpace.forgetToPresheafedSpace
rw [← PreservesCoequalizer.iso_hom] at this
erw [SheafedSpace.congr_app this.symm (op U)]
rw [PresheafedSpace.comp_c_app, ← PresheafedSpace.colimitPresheafObjIsoComponentwiseLimit_hom_π]
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/10754): this instance has to be manually added
haveI : IsIso (PreservesCoequalizer.iso
SheafedSpace.forgetToPresheafedSpace f.toShHom g.toShHom).hom.c :=
PresheafedSpace.c_isIso_of_iso _
-- Had to add this instance too.
have := CommRingCat.equalizer_ι_isLocalHom' (PresheafedSpace.componentwiseDiagram _
((Opens.map
(PreservesCoequalizer.iso SheafedSpace.forgetToPresheafedSpace (Hom.toShHom f)
(Hom.toShHom g)).hom.base).obj
(unop (op U))))
infer_instance
/-!
We roughly follow the construction given in [MR0302656]. Given a pair `f, g : X ⟶ Y` of morphisms
of locally ringed spaces, we want to show that the stalk map of
`π = coequalizer.π f g` (as sheafed space homs) is a local ring hom. It then follows that
`coequalizer f g` is indeed a locally ringed space, and `coequalizer.π f g` is a morphism of
locally ringed space.
Given a germ `⟨U, s⟩` of `x : coequalizer f g` such that `π꙳ x : Y` is invertible, we ought to show
that `⟨U, s⟩` is invertible. That is, there exists an open set `U' ⊆ U` containing `x` such that the
restriction of `s` onto `U'` is invertible. This `U'` is given by `π '' V`, where `V` is the
basic open set of `π⋆x`.
Since `f ⁻¹' V = Y.basic_open (f ≫ π)꙳ x = Y.basic_open (g ≫ π)꙳ x = g ⁻¹' V`, we have
`π ⁻¹' (π '' V) = V` (as the underlying set map is merely the set-theoretic coequalizer).
This shows that `π '' V` is indeed open, and `s` is invertible on `π '' V` as the components of `π꙳`
are local ring homs.
-/
variable (U : Opens (coequalizer f.toShHom g.toShHom).carrier)
variable (s : (coequalizer f.toShHom g.toShHom).presheaf.obj (op U))
/-- (Implementation). The basic open set of the section `π꙳ s`. -/
noncomputable def imageBasicOpen : Opens Y :=
Y.toRingedSpace.basicOpen
(show Y.presheaf.obj (op (unop _)) from ((coequalizer.π f.toShHom g.toShHom).c.app (op U)) s)
theorem imageBasicOpen_image_preimage :
(coequalizer.π f.toShHom g.toShHom).base ⁻¹' ((coequalizer.π f.toShHom g.toShHom).base ''
(imageBasicOpen f g U s).1) = (imageBasicOpen f g U s).1 := by
fapply Types.coequalizer_preimage_image_eq_of_preimage_eq f.base
-- Porting note: Type of `f.base` and `g.base` needs to be explicit
(g.base : X.carrier.1 ⟶ Y.carrier.1)
· ext
simp_rw [types_comp_apply, ← TopCat.comp_app, ← PresheafedSpace.comp_base]
congr 3
exact coequalizer.condition f.toShHom g.toShHom
· apply isColimitCoforkMapOfIsColimit (forget TopCat)
apply isColimitCoforkMapOfIsColimit (SheafedSpace.forget _)
exact coequalizerIsCoequalizer f.toShHom g.toShHom
· suffices
(TopologicalSpace.Opens.map f.base).obj (imageBasicOpen f g U s) =
(TopologicalSpace.Opens.map g.base).obj (imageBasicOpen f g U s)
by injection this
delta imageBasicOpen
rw [preimage_basicOpen f, preimage_basicOpen g]
dsimp only [Functor.op, unop_op]
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/11224): change `rw` to `erw`
erw [← CommRingCat.comp_apply, ← SheafedSpace.comp_c_app', ← CommRingCat.comp_apply,
← SheafedSpace.comp_c_app',
SheafedSpace.congr_app (coequalizer.condition f.toShHom g.toShHom),
CommRingCat.comp_apply, X.toRingedSpace.basicOpen_res]
apply inf_eq_right.mpr
refine (RingedSpace.basicOpen_le _ _).trans ?_
rw [coequalizer.condition f.toShHom g.toShHom]
theorem imageBasicOpen_image_open :
IsOpen ((coequalizer.π f.toShHom g.toShHom).base '' (imageBasicOpen f g U s).1) := by
rw [← (TopCat.homeoOfIso (PreservesCoequalizer.iso (SheafedSpace.forget _) f.toShHom
g.toShHom)).isOpen_preimage, TopCat.coequalizer_isOpen_iff, ← Set.preimage_comp]
erw [← TopCat.coe_comp]
rw [PreservesCoequalizer.iso_hom, ι_comp_coequalizerComparison]
dsimp only [SheafedSpace.forget]
rw [imageBasicOpen_image_preimage]
exact (imageBasicOpen f g U s).2
@[instance]
theorem coequalizer_π_stalk_isLocalHom (x : Y) :
IsLocalHom ((coequalizer.π f.toShHom g.toShHom :).stalkMap x).hom := by
constructor
rintro a ha
rcases TopCat.Presheaf.germ_exist _ _ a with ⟨U, hU, s, rfl⟩
rw [-- Manually apply `elementwise_of%` to generate a `ConcreteCategory` lemma
elementwise_of% PresheafedSpace.stalkMap_germ
(coequalizer.π (C := SheafedSpace _) f.toShHom g.toShHom) U _ hU] at ha
let V := imageBasicOpen f g U s
have hV : (coequalizer.π f.toShHom g.toShHom).base ⁻¹'
((coequalizer.π f.toShHom g.toShHom).base '' V.1) = V.1 :=
imageBasicOpen_image_preimage f g U s
have hV' : V = ⟨(coequalizer.π f.toShHom g.toShHom).base ⁻¹'
((coequalizer.π f.toShHom g.toShHom).base '' V.1), hV.symm ▸ V.2⟩ :=
SetLike.ext' hV.symm
have V_open : IsOpen ((coequalizer.π f.toShHom g.toShHom).base '' V.1) :=
imageBasicOpen_image_open f g U s
have VleU : ⟨(coequalizer.π f.toShHom g.toShHom).base '' V.1, V_open⟩ ≤ U :=
Set.image_subset_iff.mpr (Y.toRingedSpace.basicOpen_le _)
have hxV : x ∈ V := ⟨hU, ha⟩
rw [← (coequalizer f.toShHom g.toShHom).presheaf.germ_res_apply (homOfLE VleU) _
(@Set.mem_image_of_mem _ _ (coequalizer.π f.toShHom g.toShHom).base x V.1 hxV) s]
apply RingHom.isUnit_map
rw [← isUnit_map_iff ((coequalizer.π f.toShHom g.toShHom :).c.app _).hom,
← CommRingCat.comp_apply, NatTrans.naturality, CommRingCat.comp_apply,
← isUnit_map_iff (Y.presheaf.map (eqToHom hV').op).hom]
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/11224): change `rw` to `erw`
erw [← CommRingCat.comp_apply, ← CommRingCat.comp_apply, ← Y.presheaf.map_comp]
convert @RingedSpace.isUnit_res_basicOpen Y.toRingedSpace (unop _)
(((coequalizer.π f.toShHom g.toShHom).c.app (op U)) s)
end HasCoequalizer
/-- The coequalizer of two locally ringed space in the category of sheafed spaces is a locally
ringed space. -/
noncomputable def coequalizer : LocallyRingedSpace where
toSheafedSpace := Limits.coequalizer f.toShHom g.toShHom
isLocalRing x := by
obtain ⟨y, rfl⟩ :=
(TopCat.epi_iff_surjective (coequalizer.π f.toShHom g.toShHom).base).mp inferInstance x
exact ((coequalizer.π f.toShHom g.toShHom :).stalkMap y).hom.domain_isLocalRing
/-- The explicit coequalizer cofork of locally ringed spaces. -/
noncomputable def coequalizerCofork : Cofork f g :=
@Cofork.ofπ _ _ _ _ f g (coequalizer f g) ⟨coequalizer.π f.toShHom g.toShHom,
-- Porting note: this used to be automatic
HasCoequalizer.coequalizer_π_stalk_isLocalHom _ _⟩
(LocallyRingedSpace.Hom.ext' (coequalizer.condition f.toShHom g.toShHom))
theorem isLocalHom_stalkMap_congr {X Y : RingedSpace} (f g : X ⟶ Y) (H : f = g) (x)
(h : IsLocalHom (f.stalkMap x).hom) :
IsLocalHom (g.stalkMap x).hom := by
rw [PresheafedSpace.stalkMap.congr_hom _ _ H.symm x]; infer_instance
/-- The cofork constructed in `coequalizer_cofork` is indeed a colimit cocone. -/
noncomputable def coequalizerCoforkIsColimit : IsColimit (coequalizerCofork f g) := by
apply Cofork.IsColimit.mk'
intro s
have e : f.toShHom ≫ s.π.toShHom = g.toShHom ≫ s.π.toShHom := by injection s.condition
refine ⟨⟨coequalizer.desc s.π.toShHom e, ?_⟩, ?_⟩
· intro x
rcases (TopCat.epi_iff_surjective
(coequalizer.π f.toShHom g.toShHom).base).mp inferInstance x with ⟨y, rfl⟩
-- Porting note: was `apply isLocalHom_of_comp _ (PresheafedSpace.stalkMap ...)`, this
-- used to allow you to provide the proof that `... ≫ ...` is a local ring homomorphism later,
-- but this is no longer possible
set h := _
change IsLocalHom h
suffices _ : IsLocalHom (((coequalizerCofork f g).π.1.stalkMap _).hom.comp h) by
apply isLocalHom_of_comp _ ((coequalizerCofork f g).π.1.stalkMap _).hom
rw [← CommRingCat.hom_ofHom h, ← CommRingCat.hom_comp]
erw [← PresheafedSpace.stalkMap.comp]
apply isLocalHom_stalkMap_congr _ _ (coequalizer.π_desc s.π.toShHom e).symm y
infer_instance
constructor
· exact LocallyRingedSpace.Hom.ext' (coequalizer.π_desc _ _)
intro m h
replace h : (coequalizerCofork f g).π.toShHom ≫ m.1 = s.π.toShHom := by rw [← h]; rfl
apply LocallyRingedSpace.Hom.ext'
apply (colimit.isColimit (parallelPair f.toShHom g.toShHom)).uniq (Cofork.ofπ s.π.toShHom e) m.1
rintro ⟨⟩
· rw [← (colimit.cocone (parallelPair f.toShHom g.toShHom)).w WalkingParallelPairHom.left,
Category.assoc]
change _ ≫ _ ≫ _ = _ ≫ _
congr
· exact h
instance : HasCoequalizer f g :=
⟨⟨⟨_, coequalizerCoforkIsColimit f g⟩⟩⟩
instance : HasCoequalizers LocallyRingedSpace :=
hasCoequalizers_of_hasColimit_parallelPair _
noncomputable instance preservesCoequalizer :
PreservesColimitsOfShape WalkingParallelPair forgetToSheafedSpace.{v} :=
⟨fun {F} => by
-- Porting note: was `apply preservesColimitOfIsoDiagram ...` and the proof that preservation
-- of colimit is provided later
suffices PreservesColimit (parallelPair (F.map WalkingParallelPairHom.left)
(F.map WalkingParallelPairHom.right)) forgetToSheafedSpace from
preservesColimit_of_iso_diagram _ (diagramIsoParallelPair F).symm
apply preservesColimit_of_preserves_colimit_cocone (coequalizerCoforkIsColimit _ _)
apply (isColimitMapCoconeCoforkEquiv _ _).symm _
dsimp only [forgetToSheafedSpace]
exact coequalizerIsCoequalizer _ _⟩
end HasCoequalizer
instance : HasColimits LocallyRingedSpace :=
has_colimits_of_hasCoequalizers_and_coproducts
noncomputable instance preservesColimits_forgetToSheafedSpace :
PreservesColimits LocallyRingedSpace.forgetToSheafedSpace.{u} :=
preservesColimits_of_preservesCoequalizers_and_coproducts _
end LocallyRingedSpace
end AlgebraicGeometry
|
Basic.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
-/
import Mathlib.Algebra.Group.Action.End
import Mathlib.Algebra.GroupWithZero.Action.Defs
import Mathlib.Algebra.Group.Action.Prod
import Mathlib.Algebra.GroupWithZero.Prod
/-!
# Definitions of group actions
This file defines a hierarchy of group action type-classes on top of the previously defined
notation classes `SMul` and its additive version `VAdd`:
* `MulAction M α` and its additive version `AddAction G P` are typeclasses used for
actions of multiplicative and additive monoids and groups; they extend notation classes
`SMul` and `VAdd` that are defined in `Algebra.Group.Defs`;
* `DistribMulAction M A` is a typeclass for an action of a multiplicative monoid on
an additive monoid such that `a • (b + c) = a • b + a • c` and `a • 0 = 0`.
The hierarchy is extended further by `Module`, defined elsewhere.
Also provided are typeclasses for faithful and transitive actions, and typeclasses regarding the
interaction of different group actions,
* `SMulCommClass M N α` and its additive version `VAddCommClass M N α`;
* `IsScalarTower M N α` and its additive version `VAddAssocClass M N α`;
* `IsCentralScalar M α` and its additive version `IsCentralVAdd M N α`.
## Notation
- `a • b` is used as notation for `SMul.smul a b`.
- `a +ᵥ b` is used as notation for `VAdd.vadd a b`.
## Implementation details
This file should avoid depending on other parts of `GroupTheory`, to avoid import cycles.
More sophisticated lemmas belong in `GroupTheory.GroupAction`.
## Tags
group action
-/
assert_not_exists Ring
open Function
variable {G G₀ A M M₀ N₀ R α : Type*}
section GroupWithZero
variable [GroupWithZero G₀] [MulAction G₀ α] {a : G₀}
protected lemma MulAction.bijective₀ (ha : a ≠ 0) : Bijective (a • · : α → α) :=
MulAction.bijective <| Units.mk0 a ha
protected lemma MulAction.injective₀ (ha : a ≠ 0) : Injective (a • · : α → α) :=
(MulAction.bijective₀ ha).injective
protected lemma MulAction.surjective₀ (ha : a ≠ 0) : Surjective (a • · : α → α) :=
(MulAction.bijective₀ ha).surjective
end GroupWithZero
section DistribMulAction
variable [Group G] [Monoid M] [AddMonoid A]
variable (A)
/-- Each element of the group defines an additive monoid isomorphism.
This is a stronger version of `MulAction.toPerm`. -/
@[simps +simpRhs]
def DistribMulAction.toAddEquiv [DistribMulAction G A] (x : G) : A ≃+ A where
__ := toAddMonoidHom A x
__ := MulAction.toPermHom G A x
variable (G)
/-- Each element of the group defines an additive monoid isomorphism.
This is a stronger version of `MulAction.toPermHom`. -/
@[simps]
def DistribMulAction.toAddAut [DistribMulAction G A] : G →* AddAut A where
toFun := toAddEquiv _
map_one' := AddEquiv.ext (one_smul _)
map_mul' _ _ := AddEquiv.ext (mul_smul _ _)
end DistribMulAction
/-- Scalar multiplication as a monoid homomorphism with zero. -/
@[simps]
def smulMonoidWithZeroHom [MonoidWithZero M₀] [MulZeroOneClass N₀] [MulActionWithZero M₀ N₀]
[IsScalarTower M₀ N₀ N₀] [SMulCommClass M₀ N₀ N₀] : M₀ × N₀ →*₀ N₀ :=
{ smulMonoidHom with map_zero' := smul_zero _ }
namespace AddAut
/-- The tautological action by `AddAut A` on `A`.
This generalizes `Function.End.applyMulAction`. -/
instance applyDistribMulAction [AddMonoid A] : DistribMulAction (AddAut A) A where
smul := (· <| ·)
smul_zero := map_zero
smul_add := map_add
one_smul _ := rfl
mul_smul _ _ _ := rfl
end AddAut
lemma IsUnit.smul_sub_iff_sub_inv_smul [Group G] [Monoid R] [AddGroup R] [DistribMulAction G R]
[IsScalarTower G R R] [SMulCommClass G R R] (r : G) (a : R) :
IsUnit (r • (1 : R) - a) ↔ IsUnit (1 - r⁻¹ • a) := by
rw [← isUnit_smul_iff r (1 - r⁻¹ • a), smul_sub, smul_inv_smul]
|
Instances.lean
|
/-
Copyright (c) 2025 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.CategoryTheory.MorphismProperty.WeakFactorizationSystem
import Mathlib.AlgebraicTopology.ModelCategory.CategoryWithCofibrations
/-!
# Consequences of model category axioms
In this file, we deduce basic properties of fibrations, cofibrations,
and weak equivalences from the axioms of model categories.
-/
universe w v u
open CategoryTheory Limits MorphismProperty
namespace HomotopicalAlgebra
variable (C : Type u) [Category.{v} C]
instance [CategoryWithWeakEquivalences C] [CategoryWithCofibrations C]
[(cofibrations C).IsStableUnderRetracts]
[(weakEquivalences C).IsStableUnderRetracts] :
(trivialCofibrations C).IsStableUnderRetracts := by
dsimp [trivialCofibrations]
infer_instance
instance [CategoryWithWeakEquivalences C] [CategoryWithFibrations C]
[(fibrations C).IsStableUnderRetracts]
[(weakEquivalences C).IsStableUnderRetracts] :
(trivialFibrations C).IsStableUnderRetracts := by
dsimp [trivialFibrations]
infer_instance
section IsStableUnderComposition
variable {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
instance [CategoryWithCofibrations C] [(cofibrations C).IsStableUnderComposition]
[hf : Cofibration f] [hg : Cofibration g] : Cofibration (f ≫ g) :=
(cofibration_iff _).2 ((cofibrations C).comp_mem _ _ hf.mem hg.mem)
instance [CategoryWithFibrations C] [(fibrations C).IsStableUnderComposition]
[hf : Fibration f] [hg : Fibration g] : Fibration (f ≫ g) :=
(fibration_iff _).2 ((fibrations C).comp_mem _ _ hf.mem hg.mem)
instance [CategoryWithWeakEquivalences C] [(weakEquivalences C).IsStableUnderComposition]
[hf : WeakEquivalence f] [hg : WeakEquivalence g] : WeakEquivalence (f ≫ g) :=
(weakEquivalence_iff _).2 ((weakEquivalences C).comp_mem _ _ hf.mem hg.mem)
end IsStableUnderComposition
variable [CategoryWithWeakEquivalences C]
section HasTwoOutOfThreeProperty
variable [(weakEquivalences C).HasTwoOutOfThreeProperty]
{C} {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
lemma weakEquivalence_of_postcomp
[hg : WeakEquivalence g] [hfg : WeakEquivalence (f ≫ g)] :
WeakEquivalence f := by
rw [weakEquivalence_iff] at hg hfg ⊢
exact of_postcomp _ _ _ hg hfg
lemma weakEquivalence_of_precomp
[hf : WeakEquivalence f] [hfg : WeakEquivalence (f ≫ g)] :
WeakEquivalence g := by
rw [weakEquivalence_iff] at hf hfg ⊢
exact of_precomp _ _ _ hf hfg
lemma weakEquivalence_postcomp_iff [WeakEquivalence g] :
WeakEquivalence (f ≫ g) ↔ WeakEquivalence f :=
⟨fun _ ↦ weakEquivalence_of_postcomp f g, fun _ ↦ inferInstance⟩
lemma weakEquivalence_precomp_iff [WeakEquivalence f] :
WeakEquivalence (f ≫ g) ↔ WeakEquivalence g :=
⟨fun _ ↦ weakEquivalence_of_precomp f g, fun _ ↦ inferInstance⟩
variable {f g} {fg : X ⟶ Z}
lemma weakEquivalence_of_postcomp_of_fac (fac : f ≫ g = fg)
[WeakEquivalence g] [hfg : WeakEquivalence fg] :
WeakEquivalence f := by
subst fac
exact weakEquivalence_of_postcomp f g
lemma weakEquivalence_of_precomp_of_fac (fac : f ≫ g = fg)
[WeakEquivalence f] [WeakEquivalence fg] :
WeakEquivalence g := by
subst fac
exact weakEquivalence_of_precomp f g
end HasTwoOutOfThreeProperty
variable [CategoryWithCofibrations C] [CategoryWithFibrations C]
section
variable [IsWeakFactorizationSystem (trivialCofibrations C) (fibrations C)]
lemma fibrations_llp :
(fibrations C).llp = trivialCofibrations C :=
llp_eq_of_wfs _ _
lemma trivialCofibrations_rlp :
(trivialCofibrations C).rlp = fibrations C :=
rlp_eq_of_wfs _ _
instance : (trivialCofibrations C).IsStableUnderCobaseChange := by
rw [← fibrations_llp]
infer_instance
instance : (fibrations C).IsStableUnderBaseChange := by
rw [← trivialCofibrations_rlp]
infer_instance
instance : (trivialCofibrations C).IsMultiplicative := by
rw [← fibrations_llp]
infer_instance
instance : (fibrations C).IsMultiplicative := by
rw [← trivialCofibrations_rlp]
infer_instance
variable (J : Type w)
instance isStableUnderCoproductsOfShape_trivialCofibrations :
(trivialCofibrations C).IsStableUnderCoproductsOfShape J := by
rw [← fibrations_llp]
apply MorphismProperty.llp_isStableUnderCoproductsOfShape
instance isStableUnderProductsOfShape_fibrations :
(fibrations C).IsStableUnderProductsOfShape J := by
rw [← trivialCofibrations_rlp]
apply MorphismProperty.rlp_isStableUnderProductsOfShape
end
section
variable [IsWeakFactorizationSystem (cofibrations C) (trivialFibrations C)]
lemma trivialFibrations_llp :
(trivialFibrations C).llp = cofibrations C :=
llp_eq_of_wfs _ _
lemma cofibrations_rlp :
(cofibrations C).rlp = trivialFibrations C :=
rlp_eq_of_wfs _ _
instance : (cofibrations C).IsStableUnderCobaseChange := by
rw [← trivialFibrations_llp]
infer_instance
instance : (trivialFibrations C).IsStableUnderBaseChange := by
rw [← cofibrations_rlp]
infer_instance
instance : (cofibrations C).IsMultiplicative := by
rw [← trivialFibrations_llp]
infer_instance
instance : (trivialFibrations C).IsMultiplicative := by
rw [← cofibrations_rlp]
infer_instance
variable (J : Type w)
instance isStableUnderCoproductsOfShape_cofibrations :
(cofibrations C).IsStableUnderCoproductsOfShape J := by
rw [← trivialFibrations_llp]
apply MorphismProperty.llp_isStableUnderCoproductsOfShape
instance isStableUnderProductsOfShape_trivialFibrations :
(trivialFibrations C).IsStableUnderProductsOfShape J := by
rw [← cofibrations_rlp]
apply MorphismProperty.rlp_isStableUnderProductsOfShape
end
section Pullbacks
section
variable {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [HasPushout f g]
instance [(cofibrations C).IsStableUnderCobaseChange] [hg : Cofibration g] :
Cofibration (pushout.inl f g) := by
rw [cofibration_iff] at hg ⊢
exact MorphismProperty.of_isPushout (IsPushout.of_hasPushout f g) hg
instance [(cofibrations C).IsStableUnderCobaseChange] [hf : Cofibration f] :
Cofibration (pushout.inr f g) := by
rw [cofibration_iff] at hf ⊢
exact MorphismProperty.of_isPushout (IsPushout.of_hasPushout f g).flip hf
instance [(trivialCofibrations C).IsStableUnderCobaseChange]
[Cofibration g] [WeakEquivalence g] : WeakEquivalence (pushout.inl f g) := by
rw [weakEquivalence_iff]
exact (MorphismProperty.of_isPushout (IsPushout.of_hasPushout f g)
(mem_trivialCofibrations g)).2
instance [(trivialCofibrations C).IsStableUnderCobaseChange]
[Cofibration f] [WeakEquivalence f] : WeakEquivalence (pushout.inr f g) := by
rw [weakEquivalence_iff]
exact (MorphismProperty.of_isPushout (IsPushout.of_hasPushout f g).flip
(mem_trivialCofibrations f)).2
end
section
variable {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [HasPullback f g]
instance [(fibrations C).IsStableUnderBaseChange]
[hf : Fibration f] : Fibration (pullback.snd f g) := by
rw [fibration_iff] at hf ⊢
exact MorphismProperty.of_isPullback (IsPullback.of_hasPullback f g) hf
instance [(fibrations C).IsStableUnderBaseChange]
[hg : Fibration g] : Fibration (pullback.fst f g) := by
rw [fibration_iff] at hg ⊢
exact MorphismProperty.of_isPullback (IsPullback.of_hasPullback f g).flip hg
instance [(trivialFibrations C).IsStableUnderBaseChange]
[Fibration f] [WeakEquivalence f] : WeakEquivalence (pullback.snd f g) := by
rw [weakEquivalence_iff]
exact (MorphismProperty.of_isPullback (IsPullback.of_hasPullback f g)
(mem_trivialFibrations f)).2
instance [(trivialFibrations C).IsStableUnderBaseChange]
[Fibration g] [WeakEquivalence g] : WeakEquivalence (pullback.fst f g) := by
rw [weakEquivalence_iff]
exact (MorphismProperty.of_isPullback (IsPullback.of_hasPullback f g).flip
(mem_trivialFibrations g)).2
end
end Pullbacks
section Products
variable (J : Type w) {C J} {X Y : J → C} (f : ∀ i, X i ⟶ Y i)
section
variable [HasCoproduct X] [HasCoproduct Y] [h : ∀ i, Cofibration (f i)]
instance [IsWeakFactorizationSystem (cofibrations C) (trivialFibrations C)] :
Cofibration (Limits.Sigma.map f) := by
simp only [cofibration_iff] at h ⊢
exact MorphismProperty.colimMap _ (fun ⟨i⟩ ↦ h i)
instance [IsWeakFactorizationSystem (trivialCofibrations C) (fibrations C)]
[∀ i, WeakEquivalence (f i)] :
WeakEquivalence (Limits.Sigma.map f) := by
rw [weakEquivalence_iff]
exact (MorphismProperty.colimMap (W := (trivialCofibrations C)) _
(fun ⟨i⟩ ↦ mem_trivialCofibrations (f i))).2
end
section
variable [HasProduct X] [HasProduct Y] [h : ∀ i, Fibration (f i)]
instance [IsWeakFactorizationSystem (trivialCofibrations C) (fibrations C)] :
Fibration (Limits.Pi.map f) := by
simp only [fibration_iff] at h ⊢
exact MorphismProperty.limMap _ (fun ⟨i⟩ ↦ h i)
instance [IsWeakFactorizationSystem (cofibrations C) (trivialFibrations C)]
[∀ i, WeakEquivalence (f i)] :
WeakEquivalence (Limits.Pi.map f) := by
rw [weakEquivalence_iff]
exact (MorphismProperty.limMap (W := (trivialFibrations C)) _
(fun ⟨i⟩ ↦ mem_trivialFibrations (f i))).2
end
end Products
section BinaryProducts
variable {X₁ X₂ Y₁ Y₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂)
instance [IsWeakFactorizationSystem (cofibrations C) (trivialFibrations C)]
[h₁ : Cofibration f₁] [h₂ : Cofibration f₂] [HasBinaryCoproduct X₁ X₂]
[HasBinaryCoproduct Y₁ Y₂] : Cofibration (coprod.map f₁ f₂) := by
rw [cofibration_iff] at h₁ h₂ ⊢
apply MorphismProperty.colimMap
rintro (_ | _) <;> assumption
instance [IsWeakFactorizationSystem (trivialCofibrations C) (fibrations C)]
[h₁ : Fibration f₁] [h₂ : Fibration f₂] [HasBinaryProduct X₁ X₂]
[HasBinaryProduct Y₁ Y₂] : Fibration (prod.map f₁ f₂) := by
rw [fibration_iff] at h₁ h₂ ⊢
apply MorphismProperty.limMap
rintro (_ | _) <;> assumption
end BinaryProducts
section IsIso
variable {X Y : C} (f : X ⟶ Y)
instance [IsWeakFactorizationSystem (trivialCofibrations C) (fibrations C)] [IsIso f] :
Cofibration f := by
have := (fibrations C).llp_of_isIso f
rw [fibrations_llp] at this
simpa only [cofibration_iff] using this.1
instance [IsWeakFactorizationSystem (cofibrations C) (trivialFibrations C)] [IsIso f] :
Fibration f := by
have := (cofibrations C).rlp_of_isIso f
rw [cofibrations_rlp] at this
simpa only [fibration_iff] using this.1
instance [IsWeakFactorizationSystem (trivialCofibrations C) (fibrations C)]
[(weakEquivalences C).IsStableUnderRetracts] [IsIso f] :
WeakEquivalence f := by
have h := MorphismProperty.factorizationData (trivialCofibrations C) (fibrations C) f
rw [weakEquivalence_iff]
exact MorphismProperty.of_retract (RetractArrow.ofLeftLiftingProperty h.fac) h.hi.2
end IsIso
instance [IsWeakFactorizationSystem (trivialCofibrations C) (fibrations C)]
[(weakEquivalences C).IsStableUnderRetracts]
[(weakEquivalences C).IsStableUnderComposition] :
(weakEquivalences C).IsMultiplicative where
id_mem _ := by
rw [← weakEquivalence_iff]
infer_instance
instance [IsWeakFactorizationSystem (trivialCofibrations C) (fibrations C)]
[(weakEquivalences C).IsStableUnderRetracts]
[(weakEquivalences C).IsStableUnderComposition] :
(weakEquivalences C).RespectsIso :=
MorphismProperty.respectsIso_of_isStableUnderComposition (fun _ _ _ (_ : IsIso _) ↦ by
rw [← weakEquivalence_iff]
infer_instance)
instance [(weakEquivalences C).ContainsIdentities] (X : C) :
WeakEquivalence (𝟙 X) := by
rw [weakEquivalence_iff]
apply id_mem
section MapFactorizationData
variable {X Y : C} (f : X ⟶ Y)
section
variable (h : MapFactorizationData (cofibrations C) (trivialFibrations C) f)
instance : Cofibration h.i := by
simpa only [cofibration_iff] using h.hi
instance : Fibration h.p := by
simpa only [fibration_iff] using h.hp.1
instance : WeakEquivalence h.p := by
simpa only [weakEquivalence_iff] using h.hp.2
end
section
variable (h : MapFactorizationData (trivialCofibrations C) (fibrations C) f)
instance : Cofibration h.i := by
simpa only [cofibration_iff] using h.hi.1
instance : WeakEquivalence h.i := by
simpa only [weakEquivalence_iff] using h.hi.2
instance : Fibration h.p := by
simpa only [fibration_iff] using h.hp
end
end MapFactorizationData
end HomotopicalAlgebra
|
Interval.lean
|
/-
Copyright (c) 2021 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.Interval.Finset.Basic
import Mathlib.Data.Fintype.BigOperators
/-!
# Intervals in a pi type
This file shows that (dependent) functions to locally finite orders equipped with the pointwise
order are locally finite and calculates the cardinality of their intervals.
-/
open Finset Fintype
variable {ι : Type*} {α : ι → Type*} [Fintype ι] [DecidableEq ι] [∀ i, DecidableEq (α i)]
namespace Pi
section PartialOrder
variable [∀ i, PartialOrder (α i)]
section LocallyFiniteOrder
variable [∀ i, LocallyFiniteOrder (α i)]
instance instLocallyFiniteOrder : LocallyFiniteOrder (∀ i, α i) :=
LocallyFiniteOrder.ofIcc _ (fun a b => piFinset fun i => Icc (a i) (b i)) fun a b x => by
simp_rw [mem_piFinset, mem_Icc, le_def, forall_and]
variable (a b : ∀ i, α i)
theorem Icc_eq : Icc a b = piFinset fun i => Icc (a i) (b i) :=
rfl
theorem card_Icc : #(Icc a b) = ∏ i, #(Icc (a i) (b i)) :=
card_piFinset _
theorem card_Ico : #(Ico a b) = ∏ i, #(Icc (a i) (b i)) - 1 := by
rw [card_Ico_eq_card_Icc_sub_one, card_Icc]
theorem card_Ioc : #(Ioc a b) = ∏ i, #(Icc (a i) (b i)) - 1 := by
rw [card_Ioc_eq_card_Icc_sub_one, card_Icc]
theorem card_Ioo : #(Ioo a b) = ∏ i, #(Icc (a i) (b i)) - 2 := by
rw [card_Ioo_eq_card_Icc_sub_two, card_Icc]
end LocallyFiniteOrder
section LocallyFiniteOrderBot
variable [∀ i, LocallyFiniteOrderBot (α i)] (b : ∀ i, α i)
instance instLocallyFiniteOrderBot : LocallyFiniteOrderBot (∀ i, α i) :=
.ofIic _ (fun b => piFinset fun i => Iic (b i)) fun b x => by
simp_rw [mem_piFinset, mem_Iic, le_def]
lemma card_Iic : #(Iic b) = ∏ i, #(Iic (b i)) := card_piFinset _
lemma card_Iio : #(Iio b) = ∏ i, #(Iic (b i)) - 1 := by rw [card_Iio_eq_card_Iic_sub_one, card_Iic]
end LocallyFiniteOrderBot
section LocallyFiniteOrderTop
variable [∀ i, LocallyFiniteOrderTop (α i)] (a : ∀ i, α i)
instance instLocallyFiniteOrderTop : LocallyFiniteOrderTop (∀ i, α i) :=
LocallyFiniteOrderTop.ofIci _ (fun a => piFinset fun i => Ici (a i)) fun a x => by
simp_rw [mem_piFinset, mem_Ici, le_def]
lemma card_Ici : #(Ici a) = ∏ i, #(Ici (a i)) := card_piFinset _
lemma card_Ioi : #(Ioi a) = ∏ i, #(Ici (a i)) - 1 := by rw [card_Ioi_eq_card_Ici_sub_one, card_Ici]
end LocallyFiniteOrderTop
end PartialOrder
section Lattice
variable [∀ i, Lattice (α i)] [∀ i, LocallyFiniteOrder (α i)] (a b : ∀ i, α i)
theorem uIcc_eq : uIcc a b = piFinset fun i => uIcc (a i) (b i) := rfl
theorem card_uIcc : #(uIcc a b) = ∏ i, #(uIcc (a i) (b i)) := card_Icc _ _
end Lattice
end Pi
|
Criterion.lean
|
/-
Copyright (c) 2025 Antoine Chambert-Loir. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Antoine Chambert-Loir
-/
import Mathlib.RingTheory.Ideal.Maps
import Mathlib.RingTheory.Polynomial.Content
import Mathlib.RingTheory.Ideal.Quotient.Operations
/-! # The Eisenstein criterion
`Polynomial.generalizedEisenstein` :
Let `R` be an integral domain
and let `K` an `R`-algebra which is a field
Let `q : R[X]` be a monic polynomial which is prime in `K[X]`.
Let `f : R[X]` be a polynomial of strictly positive degree
satisfying the following properties:
* the image of `f` in `K[X]` is a power of `q`.
* the leading coefficient of `f` is not zero in `K`
* the polynomial `f` is primitive.
Assume moreover that `f.modByMonic q` is not zero in `(R ⧸ (P ^ 2))[X]`,
where `P` is the kernel of `algebraMap R K`.
Then `f` is irreducible.
We give in `Archive.Examples.Eisenstein` an explicit example
of application of this criterion.
* `Polynomial.irreducible_of_eisenstein_criterion` : the classic Eisenstein criterion.
It is the particular case where `q := X`.
# TODO
The case of a polynomial `q := X - a` is interesting,
then the mod `P ^ 2` hypothesis can rephrased as saying
that `f.derivative.eval a ∉ P ^ 2`. (TODO)
The case of cyclotomic polynomials of prime index `p`
could be proved directly using that result, taking `a = 1`.
The result can also be generalized to the case where
the leading coefficients of `f` and `q` do not belong to `P`.
(By localization at `P`, make these coefficients invertible.)
There are two obstructions, though :
* Usually, one will only obtain irreducibility in `F[X]`, where `F` is the field
of fractions of `R`. (If `R` is a UFD, this will be close to what is wanted,
but not in general.)
* The mod `P ^ 2` hypothesis will have to be rephrased to a condition
in the second symbolic power of `P`. When `P` is a maximal ideal,
that symbolic power coincides with `P ^ 2`, but not in general.
-/
namespace Polynomial
open Ideal.Quotient Ideal RingHom
variable {R : Type*} [CommRing R] [IsDomain R]
{K : Type*} [Field K] [Algebra R K]
private lemma generalizedEisenstein_aux {q f g : R[X]} {p : ℕ}
(hq_irr : Irreducible (q.map (algebraMap R K)))
(hq_monic : q.Monic)
(hf_lC : algebraMap R K f.leadingCoeff ≠ 0)
(hf_prim : f.IsPrimitive)
(hfmodP : f.map (algebraMap R K) =
C (algebraMap R K f.leadingCoeff) * q.map (algebraMap R K) ^ p)
(hg_div : g ∣ f) :
∃ m r, g = C g.leadingCoeff * q ^ m + r ∧
r.map (algebraMap R K) = 0 ∧ (m = 0 → IsUnit g) := by
set P := ker (algebraMap R K)
have hP : P.IsPrime := ker_isPrime (algebraMap R K)
have hgP : g.leadingCoeff ∉ P := by
simp only [mem_ker, P]
obtain ⟨h, rfl⟩ := hg_div
simp only [leadingCoeff_mul, map_mul, ne_eq, mul_eq_zero, not_or] at hf_lC
exact hf_lC.1
have map_dvd_pow_q :
g.map (algebraMap R K) ∣ q.map (algebraMap R K) ^ p := by
rw [← IsUnit.dvd_mul_left _, ← hfmodP]
· exact Polynomial.map_dvd _ hg_div
· simp_all
obtain ⟨m, hm, hf⟩ := (dvd_prime_pow hq_irr.prime _).mp map_dvd_pow_q
set r := g - C g.leadingCoeff * q ^ m
have hg : g = C g.leadingCoeff * q ^ m + r := by ring
have hr : r.map (algebraMap R K) = 0 := by
obtain ⟨u, hu⟩ := hf.symm
obtain ⟨a, ha, ha'⟩ := Polynomial.isUnit_iff.mp u.isUnit
suffices C (algebraMap R K g.leadingCoeff) = u by
simp [r, ← this, Polynomial.map_sub, ← hu, Polynomial.map_mul, map_C,
Polynomial.map_pow, mul_comm]
rw [← leadingCoeff_map_of_leadingCoeff_ne_zero _ hgP, ← hu, ← ha',
leadingCoeff_mul, leadingCoeff_C, (hq_monic.map _).pow m, one_mul]
use m, r, hg, hr
intro hm
rw [isPrimitive_iff_isUnit_of_C_dvd] at hf_prim
rw [hm, pow_zero, mul_one] at hg
suffices g.natDegree = 0 by
obtain ⟨a, rfl⟩ := Polynomial.natDegree_eq_zero.mp this
apply IsUnit.map
apply hf_prim
rwa [leadingCoeff_C] at hgP
by_contra hg'
apply hgP
rw [hg, leadingCoeff, coeff_add, ← hg, coeff_C, if_neg hg', zero_add,
mem_ker, ← coeff_map, hr, coeff_zero]
/-- A generalized Eisenstein criterion
Let `R` be an integral domain and `K` an `R`-algebra which is a domain.
Let `q : R[X]` be a monic polynomial which is prime in `K[X]`.
Let `f : R[X]` be a primitive polynomial of strictly positive degree
whose leading coefficient is not zero in `K`
and such that the image `f` in `K[X]` is a power of `q`.
Assume moreover that `f.modByMonic q` is not zero in `(R ⧸ (P ^ 2))[X]`,
where `P` is the kernel of `algebraMap R K`.
Then `f` is irreducible. -/
theorem generalizedEisenstein {q f : R[X]} {p : ℕ}
(hq_irr : Irreducible (q.map (algebraMap R K))) (hq_monic : q.Monic)
(hf_prim : f.IsPrimitive)
(hfd0 : 0 < natDegree f)
(hfP : algebraMap R K f.leadingCoeff ≠ 0)
(hfmodP : f.map (algebraMap R K) =
C (algebraMap R K f.leadingCoeff) * q.map (algebraMap R K) ^ p)
(hfmodP2 : (f.modByMonic q).map (mk ((ker (algebraMap R K)) ^ 2)) ≠ 0) :
Irreducible f where
not_isUnit := mt degree_eq_zero_of_isUnit fun h => by
simp_all [natDegree_pos_iff_degree_pos]
isUnit_or_isUnit g h h_eq := by
-- We have to show that factorizations `f = g * h` are trivial
set P : Ideal R := ker (algebraMap R K)
obtain ⟨m, r, hg, hr, hm0⟩ :=
generalizedEisenstein_aux hq_irr hq_monic hfP hf_prim hfmodP (h_eq ▸ dvd_mul_right g h)
obtain ⟨n, s, hh, hs, hn0⟩ :=
generalizedEisenstein_aux hq_irr hq_monic hfP hf_prim hfmodP (h_eq ▸ dvd_mul_left h g)
by_cases hm : m = 0
-- If `m = 0`, `generalizedEisenstein_aux` shows that `g` is a unit.
· left; exact hm0 hm
by_cases hn : n = 0
-- If `n = 0`, `generalizedEisenstein_aux` shows that `h` is a unit.
· right; exact hn0 hn
-- Otherwise, we will get a contradiction by showing that `f %ₘ q` is zero mod `P ^ 2`.
exfalso
apply hfmodP2
suffices f %ₘ q = (r * s) %ₘ q by
-- Since the coefficients of `r` and `s` are in `P`, those of `r * s` are in `P ^ 2`
suffices h : map (Ideal.Quotient.mk (P ^ 2)) (r * s) = 0 by
simp [this, h, map_modByMonic, hq_monic]
ext n
have h (x : ℕ × ℕ) : (Ideal.Quotient.mk (P ^ 2)) (r.coeff x.1 * s.coeff x.2) = 0 := by
rw [eq_zero_iff_mem, pow_two]
apply mul_mem_mul
· rw [mem_ker, ← coeff_map, hr, coeff_zero]
· rw [mem_ker, ← coeff_map, hs, coeff_zero]
simp [- Polynomial.map_mul, coeff_mul, h]
-- It remains to prove the equality `f %ₘ q = (r * s) %ₘ q`, which is straightforward
rw [h_eq, hg, hh]
simp only [add_mul, mul_add, map_add, ← modByMonicHom_apply]
simp only [← add_assoc, modByMonicHom_apply]
iterate 3 rw [(modByMonic_eq_zero_iff_dvd hq_monic).mpr]
· simp
· exact ((dvd_pow_self q hm).mul_left _).mul_right _
· simp only [← mul_assoc]
exact (dvd_pow_self q hn).mul_left _
· exact ((dvd_pow_self q hn).mul_left _).mul_left _
/-- If `f` is a non constant polynomial with coefficients in `R`, and `P` is a prime ideal in `R`,
then if every coefficient in `R` except the leading coefficient is in `P`, and
the trailing coefficient is not in `P^2` and no non units in `R` divide `f`, then `f` is
irreducible. -/
theorem irreducible_of_eisenstein_criterion {f : R[X]} {P : Ideal R} (hP : P.IsPrime)
(hfl : f.leadingCoeff ∉ P)
(hfP : ∀ n : ℕ, ↑n < degree f → f.coeff n ∈ P) (hfd0 : 0 < degree f)
(h0 : f.coeff 0 ∉ P ^ 2) (hu : f.IsPrimitive) : Irreducible f := by
apply generalizedEisenstein (K := FractionRing (R ⧸ P)) (q := X) (p := f.natDegree)
(by simp [map_X, irreducible_X]) monic_X hu
(natDegree_pos_iff_degree_pos.mpr hfd0)
· simp only [IsScalarTower.algebraMap_eq R (R ⧸ P) (FractionRing (R ⧸ P)),
Quotient.algebraMap_eq, coe_comp, Function.comp_apply, ne_eq,
FaithfulSMul.algebraMap_eq_zero_iff]
rw [Ideal.Quotient.eq_zero_iff_mem]
exact hfl
· rw [← map_C, ← Polynomial.map_pow, ← Polynomial.map_mul]
simp only [IsScalarTower.algebraMap_eq R (R ⧸ P) (FractionRing (R ⧸ P)),
Quotient.algebraMap_eq, ← map_map]
congr 1
ext n
simp only [coeff_map, Ideal.Quotient.mk_eq_mk_iff_sub_mem]
simp only [coeff_C_mul, coeff_X_pow, mul_ite, mul_one, mul_zero, sub_ite, sub_zero]
split_ifs with hn
· rw [hn, leadingCoeff, sub_self]
exact zero_mem _
· by_cases hn' : n < f.natDegree
· exact hfP _ (coe_lt_degree.mpr hn')
· rw [f.coeff_eq_zero_of_natDegree_lt]
· exact P.zero_mem
· simp [Nat.lt_iff_le_and_ne, ← Nat.not_lt, hn', Ne.symm hn]
· rw [modByMonic_X, map_C, ne_eq, C_eq_zero, Ideal.Quotient.eq_zero_iff_mem,
← coeff_zero_eq_eval_zero]
convert h0
· rw [IsScalarTower.algebraMap_eq R (R ⧸ P) (FractionRing (R ⧸ P))]
rw [ker_comp_of_injective]
· ext a; simp
· exact FaithfulSMul.algebraMap_injective (R ⧸ P) (FractionRing (R ⧸ P))
end Polynomial
|
Adjunctions.lean
|
/-
Copyright (c) 2023 Dagur Asgeirsson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Dagur Asgeirsson
-/
import Mathlib.Topology.Category.Stonean.Basic
import Mathlib.Topology.Category.TopCat.Adjunctions
import Mathlib.Topology.Compactification.StoneCech
/-!
# Adjunctions involving the category of Stonean spaces
This file constructs the left adjoint `typeToStonean` to the forgetful functor from Stonean spaces
to sets, using the Stone-Cech compactification. This allows to conclude that the monomorphisms in
`Stonean` are precisely the injective maps (see `Stonean.mono_iff_injective`).
-/
universe u
open CategoryTheory Adjunction
namespace Stonean
/-- The object part of the compactification functor from types to Stonean spaces. -/
def stoneCechObj (X : Type u) : Stonean :=
letI : TopologicalSpace X := ⊥
haveI : DiscreteTopology X := ⟨rfl⟩
haveI : ExtremallyDisconnected (StoneCech X) :=
CompactT2.Projective.extremallyDisconnected StoneCech.projective
of (StoneCech X)
/-- The equivalence of homsets to establish the adjunction between the Stone-Cech compactification
functor and the forgetful functor. -/
noncomputable def stoneCechEquivalence (X : Type u) (Y : Stonean.{u}) :
(stoneCechObj X ⟶ Y) ≃ (X ⟶ ToType Y) := by
letI : TopologicalSpace X := ⊥
haveI : DiscreteTopology X := ⟨rfl⟩
refine fullyFaithfulToCompHaus.homEquiv.trans ?_
exact (_root_.stoneCechEquivalence (TopCat.of X) (toCompHaus.obj Y)).trans
(TopCat.adj₁.homEquiv _ _)
end Stonean
/-- The Stone-Cech compactification functor from types to Stonean spaces. -/
noncomputable def typeToStonean : Type u ⥤ Stonean.{u} :=
leftAdjointOfEquiv (G := forget _) Stonean.stoneCechEquivalence fun _ _ _ _ _ => rfl
namespace Stonean
/-- The Stone-Cech compactification functor is left adjoint to the forgetful functor. -/
noncomputable def stoneCechAdjunction : typeToStonean ⊣ (forget Stonean) :=
adjunctionOfEquivLeft (G := forget _) stoneCechEquivalence fun _ _ _ _ _ => rfl
/-- The forgetful functor from Stonean spaces, being a right adjoint, preserves limits. -/
noncomputable instance forget.preservesLimits : Limits.PreservesLimits (forget Stonean) :=
rightAdjoint_preservesLimits stoneCechAdjunction
end Stonean
|
Monomorphisms.lean
|
/-
Copyright (c) 2025 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.CategoryTheory.MorphismProperty.Limits
import Mathlib.CategoryTheory.Abelian.Basic
/-!
# Monomorphisms are stable under cobase change
In an abelian category `C`, the class of morphism
`monomorphisms C` is stable under cobase change and
`epimorphisms C` is stable under base change.
-/
universe v u
namespace CategoryTheory.Abelian
variable {C : Type u} [Category.{v} C] [Abelian C]
open MorphismProperty
instance : (monomorphisms C).IsStableUnderCobaseChange :=
IsStableUnderCobaseChange.mk' (fun _ _ _ f g _ hf ↦ by
simp only [monomorphisms.iff] at hf ⊢
infer_instance)
instance : (epimorphisms C).IsStableUnderBaseChange :=
IsStableUnderBaseChange.mk' (fun _ _ _ f g _ hf ↦ by
simp only [epimorphisms.iff] at hf ⊢
infer_instance)
end CategoryTheory.Abelian
|
Centralizer.lean
|
/-
Copyright (c) 2024 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang
-/
import Mathlib.LinearAlgebra.TensorProduct.Basis
import Mathlib.RingTheory.TensorProduct.Basic
/-!
# Properties of centers and centralizers
This file contains theorems about the center and centralizer of a subalgebra.
## Main results
Let `R` be a commutative ring and `A` and `B` two `R`-algebras.
- `Subalgebra.centralizer_sup`: if `S` and `T` are subalgebras of `A`, then the centralizer of
`S ⊔ T` is the intersection of the centralizer of `S` and the centralizer of `T`.
- `Subalgebra.centralizer_range_includeLeft_eq_center_tensorProduct`: if `B` is free as a module,
then the centralizer of `A ⊗ 1` in `A ⊗ B` is `C(A) ⊗ B` where `C(A)` is the center of `A`.
- `Subalgebra.centralizer_range_includeRight_eq_center_tensorProduct`: if `A` is free as a module,
then the centralizer of `1 ⊗ B` in `A ⊗ B` is `A ⊗ C(B)` where `C(B)` is the center of `B`.
-/
namespace Subalgebra
open Algebra.TensorProduct
section CommSemiring
variable {R : Type*} [CommSemiring R]
variable {A : Type*} [Semiring A] [Algebra R A]
lemma le_centralizer_iff (S T : Subalgebra R A) : S ≤ centralizer R T ↔ T ≤ centralizer R S :=
⟨fun h t ht _ hs ↦ (h hs t ht).symm, fun h s hs _ ht ↦ (h ht s hs).symm⟩
lemma centralizer_coe_sup (S T : Subalgebra R A) :
centralizer R ((S ⊔ T : Subalgebra R A) : Set A) = centralizer R S ⊓ centralizer R T :=
eq_of_forall_le_iff fun K ↦ by
simp_rw [le_centralizer_iff, sup_le_iff, le_inf_iff, K.le_centralizer_iff]
lemma centralizer_coe_iSup {ι : Sort*} (S : ι → Subalgebra R A) :
centralizer R ((⨆ i, S i : Subalgebra R A) : Set A) = ⨅ i, centralizer R (S i) :=
eq_of_forall_le_iff fun K ↦ by
simp_rw [le_centralizer_iff, iSup_le_iff, le_iInf_iff, K.le_centralizer_iff]
end CommSemiring
section Free
variable (R : Type*) [CommSemiring R]
variable (A : Type*) [Semiring A] [Algebra R A]
variable (B : Type*) [Semiring B] [Algebra R B]
open Finsupp TensorProduct
/--
Let `R` be a commutative ring and `A, B` be `R`-algebras where `B` is free as `R`-module.
For any subset `S ⊆ A`, the centralizer of `S ⊗ 1 ⊆ A ⊗ B` is `C_A(S) ⊗ B` where `C_A(S)` is the
centralizer of `S` in `A`.
-/
lemma centralizer_coe_image_includeLeft_eq_center_tensorProduct
(S : Set A) [Module.Free R B] :
Subalgebra.centralizer R
(Algebra.TensorProduct.includeLeft (S := R) '' S) =
(Algebra.TensorProduct.map (Subalgebra.centralizer R (S : Set A)).val
(AlgHom.id R B)).range := by
classical
ext w
constructor
· intro hw
rw [mem_centralizer_iff] at hw
let ℬ := Module.Free.chooseBasis R B
obtain ⟨b, rfl⟩ := TensorProduct.eq_repr_basis_right ℬ w
refine Subalgebra.sum_mem _ fun j hj => ⟨⟨b j, ?_⟩ ⊗ₜ[R] ℬ j, by simp⟩
rw [Subalgebra.mem_centralizer_iff]
intro x hx
suffices x • b = b.mapRange (· * x) (by simp) from Finsupp.ext_iff.1 this j
specialize hw (x ⊗ₜ[R] 1) ⟨x, hx, rfl⟩
simp only [Finsupp.sum, Finset.mul_sum, Algebra.TensorProduct.tmul_mul_tmul, one_mul,
Finset.sum_mul, mul_one] at hw
refine TensorProduct.sum_tmul_basis_right_injective ℬ ?_
simp only [Finsupp.coe_lsum]
rw [sum_of_support_subset (s := b.support) (hs := Finsupp.support_smul) (h := by simp),
sum_of_support_subset (s := b.support) (hs := support_mapRange) (h := by simp)]
simpa only [Finsupp.coe_smul, Pi.smul_apply, smul_eq_mul, LinearMap.flip_apply,
TensorProduct.mk_apply, Finsupp.mapRange_apply] using hw
· rintro ⟨w, rfl⟩
rw [Subalgebra.mem_centralizer_iff]
rintro _ ⟨x, hx, rfl⟩
induction w using TensorProduct.induction_on with
| zero => simp
| tmul b c =>
simp [Subalgebra.mem_centralizer_iff _ |>.1 b.2 x hx]
| add y z hy hz => rw [map_add, mul_add, hy, hz, add_mul]
/--
Let `R` be a commutative ring and `A, B` be `R`-algebras where `B` is free as `R`-module.
For any subset `S ⊆ B`, the centralizer of `1 ⊗ S ⊆ A ⊗ B` is `A ⊗ C_B(S)` where `C_B(S)` is the
centralizer of `S` in `B`.
-/
lemma centralizer_coe_image_includeRight_eq_center_tensorProduct
(S : Set B) [Module.Free R A] :
Subalgebra.centralizer R
(Algebra.TensorProduct.includeRight '' S) =
(Algebra.TensorProduct.map (AlgHom.id R A)
(Subalgebra.centralizer R (S : Set B)).val).range := by
have eq1 := centralizer_coe_image_includeLeft_eq_center_tensorProduct R B A S
apply_fun Subalgebra.comap (Algebra.TensorProduct.comm R A B).toAlgHom at eq1
convert eq1
· ext x
simpa [mem_centralizer_iff] using
⟨fun h b hb ↦ (Algebra.TensorProduct.comm R A B).symm.injective <| by aesop, fun h b hb ↦
(Algebra.TensorProduct.comm R A B).injective <| by aesop⟩
· ext x
simp only [AlgHom.mem_range, AlgEquiv.toAlgHom_eq_coe, mem_comap, AlgHom.coe_coe]
constructor
· rintro ⟨x, rfl⟩
exact ⟨(Algebra.TensorProduct.comm R _ _) x,
by rw [Algebra.TensorProduct.comm_comp_map_apply]⟩
· rintro ⟨y, hy⟩
refine ⟨(Algebra.TensorProduct.comm R _ _) y, (Algebra.TensorProduct.comm R A B).injective ?_⟩
rw [← hy, comm_comp_map_apply, ← comm_symm, AlgEquiv.symm_apply_apply]
/--
Let `R` be a commutative ring and `A, B` be `R`-algebras where `B` is free as `R`-module.
For any subalgebra `S` of `A`, the centralizer of `S ⊗ 1 ⊆ A ⊗ B` is `C_A(S) ⊗ B` where `C_A(S)` is
the centralizer of `S` in `A`.
-/
lemma centralizer_coe_map_includeLeft_eq_center_tensorProduct
(S : Subalgebra R A) [Module.Free R B] :
Subalgebra.centralizer R
(S.map (Algebra.TensorProduct.includeLeft (R := R) (B := B))) =
(Algebra.TensorProduct.map (Subalgebra.centralizer R (S : Set A)).val
(AlgHom.id R B)).range :=
centralizer_coe_image_includeLeft_eq_center_tensorProduct R A B S
/--
Let `R` be a commutative ring and `A, B` be `R`-algebras where `A` is free as `R`-module.
For any subalgebra `S` of `B`, the centralizer of `1 ⊗ S ⊆ A ⊗ B` is `A ⊗ C_B(S)` where `C_B(S)` is
the centralizer of `S` in `B`.
-/
lemma centralizer_coe_map_includeRight_eq_center_tensorProduct
(S : Subalgebra R B) [Module.Free R A] :
Subalgebra.centralizer R
(S.map (Algebra.TensorProduct.includeRight (R := R) (A := A))) =
(Algebra.TensorProduct.map (AlgHom.id R A)
(Subalgebra.centralizer R (S : Set B)).val).range :=
centralizer_coe_image_includeRight_eq_center_tensorProduct R A B S
/--
Let `R` be a commutative ring and `A, B` be `R`-algebras where `B` is free as `R`-module.
Then the centralizer of `A ⊗ 1 ⊆ A ⊗ B` is `C(A) ⊗ B` where `C(A)` is the center of `A`.
-/
lemma centralizer_coe_range_includeLeft_eq_center_tensorProduct [Module.Free R B] :
Subalgebra.centralizer R
(Algebra.TensorProduct.includeLeft : A →ₐ[R] A ⊗[R] B).range =
(Algebra.TensorProduct.map (Subalgebra.center R A).val (AlgHom.id R B)).range := by
rw [← centralizer_univ, ← Algebra.coe_top (R := R) (A := A),
← centralizer_coe_map_includeLeft_eq_center_tensorProduct R A B ⊤]
ext
simp [includeLeft, includeLeftRingHom]
/--
Let `R` be a commutative ring and `A, B` be `R`-algebras where `A` is free as `R`-module.
Then the centralizer of `1 ⊗ B ⊆ A ⊗ B` is `A ⊗ C(B)` where `C(B)` is the center of `B`.
-/
lemma centralizer_range_includeRight_eq_center_tensorProduct [Module.Free R A] :
Subalgebra.centralizer R
(Algebra.TensorProduct.includeRight : B →ₐ[R] A ⊗[R] B).range =
(Algebra.TensorProduct.map (AlgHom.id R A) (center R B).val).range := by
rw [← centralizer_univ, ← Algebra.coe_top (R := R) (A := B),
← centralizer_coe_map_includeRight_eq_center_tensorProduct R A B ⊤]
ext
simp [includeRight]
lemma centralizer_tensorProduct_eq_center_tensorProduct_left [Module.Free R B] :
Subalgebra.centralizer R
(Algebra.TensorProduct.map (AlgHom.id R A) (Algebra.ofId R B)).range =
(Algebra.TensorProduct.map (Subalgebra.center R A).val (AlgHom.id R B)).range := by
rw [← centralizer_coe_range_includeLeft_eq_center_tensorProduct]
simp [Algebra.TensorProduct.map_range]
lemma centralizer_tensorProduct_eq_center_tensorProduct_right [Module.Free R A] :
Subalgebra.centralizer R
(Algebra.TensorProduct.map (Algebra.ofId R A) (AlgHom.id R B)).range =
(Algebra.TensorProduct.map (AlgHom.id R A) (center R B).val).range := by
rw [← centralizer_range_includeRight_eq_center_tensorProduct]
simp [Algebra.TensorProduct.map_range]
end Free
end Subalgebra
|
TsumUniformlyOn.lean
|
/-
Copyright (c) 2025 Chris Birkbeck. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Birkbeck
-/
import Mathlib.Analysis.Calculus.IteratedDeriv.Defs
import Mathlib.Analysis.Calculus.UniformLimitsDeriv
import Mathlib.Analysis.NormedSpace.FunctionSeries
import Mathlib.Topology.Algebra.InfiniteSum.UniformOn
/-!
# Differentiability of sum of functions
We prove some `HasSumUniformlyOn` versions of theorems from
`Mathlib.Analysis.NormedSpace.FunctionSeries`.
Alongside this we prove `derivWithin_tsum` which states that the derivative of a series of functions
is the sum of the derivatives, under suitable conditions we also prove an `iteratedDerivWithin`
version.
-/
open Set Metric TopologicalSpace Function Filter
open scoped Topology NNReal
section UniformlyOn
variable {α β F : Type*} [NormedAddCommGroup F] [CompleteSpace F] {u : α → ℝ}
theorem HasSumUniformlyOn.of_norm_le_summable {f : α → β → F} (hu : Summable u) {s : Set β}
(hfu : ∀ n x, x ∈ s → ‖f n x‖ ≤ u n) : HasSumUniformlyOn f (fun x ↦ ∑' n, f n x) {s} := by
simp [hasSumUniformlyOn_iff_tendstoUniformlyOn, tendstoUniformlyOn_tsum hu hfu]
theorem HasSumUniformlyOn.of_norm_le_summable_eventually {ι : Type*} {f : ι → β → F} {u : ι → ℝ}
(hu : Summable u) {s : Set β} (hfu : ∀ᶠ n in cofinite, ∀ x ∈ s, ‖f n x‖ ≤ u n) :
HasSumUniformlyOn f (fun x ↦ ∑' n, f n x) {s} := by
simp [hasSumUniformlyOn_iff_tendstoUniformlyOn,
tendstoUniformlyOn_tsum_of_cofinite_eventually hu hfu]
lemma SummableLocallyUniformlyOn.of_locally_bounded_eventually [TopologicalSpace β]
[LocallyCompactSpace β] {f : α → β → F} {s : Set β} (hs : IsOpen s)
(hu : ∀ K ⊆ s, IsCompact K → ∃ u : α → ℝ, Summable u ∧
∀ᶠ n in cofinite, ∀ k ∈ K, ‖f n k‖ ≤ u n) : SummableLocallyUniformlyOn f s := by
apply HasSumLocallyUniformlyOn.summableLocallyUniformlyOn (g := fun x ↦ ∑' n, f n x)
rw [hasSumLocallyUniformlyOn_iff_tendstoLocallyUniformlyOn,
tendstoLocallyUniformlyOn_iff_forall_isCompact hs]
intro K hK hKc
obtain ⟨u, hu1, hu2⟩ := hu K hK hKc
exact tendstoUniformlyOn_tsum_of_cofinite_eventually hu1 hu2
lemma SummableLocallyUniformlyOn_of_locally_bounded [TopologicalSpace β] [LocallyCompactSpace β]
{f : α → β → F} {s : Set β} (hs : IsOpen s)
(hu : ∀ K ⊆ s, IsCompact K → ∃ u : α → ℝ, Summable u ∧ ∀ n, ∀ k ∈ K, ‖f n k‖ ≤ u n) :
SummableLocallyUniformlyOn f s := by
apply SummableLocallyUniformlyOn.of_locally_bounded_eventually hs
intro K hK hKc
obtain ⟨u, hu1, hu2⟩ := hu K hK hKc
exact ⟨u, hu1, by filter_upwards using hu2⟩
end UniformlyOn
variable {ι F E : Type*} [NontriviallyNormedField E] [IsRCLikeNormedField E]
[NormedAddCommGroup F] [NormedSpace E F] {s : Set E}
/-- The `derivWithin` of a sum whose derivative is absolutely and uniformly convergent sum on an
open set `s` is the sum of the derivatives of sequence of functions on the open set `s` -/
theorem derivWithin_tsum {f : ι → E → F} (hs : IsOpen s) {x : E} (hx : x ∈ s)
(hf : ∀ y ∈ s, Summable fun n ↦ f n y)
(h : SummableLocallyUniformlyOn (fun n ↦ (derivWithin (fun z ↦ f n z) s)) s)
(hf2 : ∀ n r, r ∈ s → DifferentiableAt E (f n) r) :
derivWithin (fun z ↦ ∑' n , f n z) s x = ∑' n, derivWithin (f n) s x := by
apply HasDerivWithinAt.derivWithin ?_ (hs.uniqueDiffWithinAt hx)
apply HasDerivAt.hasDerivWithinAt
apply hasDerivAt_of_tendstoLocallyUniformlyOn hs _ _ (fun y hy ↦(hf y hy).hasSum ) hx
(f' := fun n : Finset ι ↦ fun a ↦ ∑ i ∈ n, derivWithin (fun z ↦ f i z) s a)
· obtain ⟨g, hg⟩ := h
apply (hasSumLocallyUniformlyOn_iff_tendstoLocallyUniformlyOn.mp hg).congr_right
exact fun _ hb ↦ Eq.symm (hg.tsum_eqOn hb)
· filter_upwards with t r hr using HasDerivAt.fun_sum
(fun q hq ↦ ((hf2 q r hr).differentiableWithinAt.hasDerivWithinAt.hasDerivAt)
(hs.mem_nhds hr))
/-- If a sequence of functions `fₙ` is such that `∑ fₙ (z)` is summable for each `z` in an
open set `s`, and for each `1 ≤ k ≤ m`, the series of `k`-th iterated derivatives
`∑ (iteratedDerivWithin k fₙ s) (z)`
is summable locally uniformly on `s`, and each `fₙ` is `m`-times differentiable, then the `m`-th
iterated derivative of the sum is the sum of the `m`-th iterated derivatives. -/
theorem iteratedDerivWithin_tsum {f : ι → E → F} (m : ℕ) (hs : IsOpen s)
{x : E} (hx : x ∈ s) (hsum : ∀ t ∈ s, Summable (fun n : ι ↦ f n t))
(h : ∀ k, 1 ≤ k → k ≤ m → SummableLocallyUniformlyOn
(fun n ↦ (iteratedDerivWithin k (fun z ↦ f n z) s)) s)
(hf2 : ∀ n k r, k ≤ m → r ∈ s →
DifferentiableAt E (iteratedDerivWithin k (fun z ↦ f n z) s) r) :
iteratedDerivWithin m (fun z ↦ ∑' n , f n z) s x = ∑' n, iteratedDerivWithin m (f n) s x := by
induction' m with m hm generalizing x
· simp
· simp_rw [iteratedDerivWithin_succ]
rw [← derivWithin_tsum hs hx _ _ (fun n r hr ↦ hf2 n m r (by omega) hr)]
· exact derivWithin_congr (fun t ht ↦ hm ht (fun k hk1 hkm ↦ h k hk1 (by omega))
(fun k r e hr he ↦ hf2 k r e (by omega) he)) (hm hx (fun k hk1 hkm ↦ h k hk1 (by omega))
(fun k r e hr he ↦ hf2 k r e (by omega) he))
· intro r hr
by_cases hm2 : m = 0
· simp [hm2, hsum r hr]
· exact ((h m (by omega) (by omega)).summable hr).congr (fun _ ↦ by simp)
· exact SummableLocallyUniformlyOn_congr
(fun _ _ ht ↦ iteratedDerivWithin_succ) (h (m + 1) (by omega) (by omega))
|
Basic.lean
|
/-
Copyright (c) 2021 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import Mathlib.MeasureTheory.Measure.Real
import Mathlib.MeasureTheory.Measure.Typeclasses.Finite
import Mathlib.Topology.Algebra.InfiniteSum.Module
/-!
# Vector valued measures
This file defines vector valued measures, which are σ-additive functions from a set to an add monoid
`M` such that it maps the empty set and non-measurable sets to zero. In the case
that `M = ℝ`, we called the vector measure a signed measure and write `SignedMeasure α`.
Similarly, when `M = ℂ`, we call the measure a complex measure and write `ComplexMeasure α`
(defined in `MeasureTheory/Measure/Complex`).
## Main definitions
* `MeasureTheory.VectorMeasure` is a vector valued, σ-additive function that maps the empty
and non-measurable set to zero.
* `MeasureTheory.VectorMeasure.map` is the pushforward of a vector measure along a function.
* `MeasureTheory.VectorMeasure.restrict` is the restriction of a vector measure on some set.
## Notation
* `v ≤[i] w` means that the vector measure `v` restricted on the set `i` is less than or equal
to the vector measure `w` restricted on `i`, i.e. `v.restrict i ≤ w.restrict i`.
## Implementation notes
We require all non-measurable sets to be mapped to zero in order for the extensionality lemma
to only compare the underlying functions for measurable sets.
We use `HasSum` instead of `tsum` in the definition of vector measures in comparison to `Measure`
since this provides summability.
## Tags
vector measure, signed measure, complex measure
-/
noncomputable section
open NNReal ENNReal
open scoped Function -- required for scoped `on` notation
namespace MeasureTheory
variable {α β : Type*} {m : MeasurableSpace α}
/-- A vector measure on a measurable space `α` is a σ-additive `M`-valued function (for some `M`
an add monoid) such that the empty set and non-measurable sets are mapped to zero. -/
structure VectorMeasure (α : Type*) [MeasurableSpace α] (M : Type*) [AddCommMonoid M]
[TopologicalSpace M] where
/-- The measure of sets -/
measureOf' : Set α → M
/-- The empty set has measure zero -/
empty' : measureOf' ∅ = 0
/-- Non-measurable sets have measure zero -/
not_measurable' ⦃i : Set α⦄ : ¬MeasurableSet i → measureOf' i = 0
/-- The measure is σ-additive -/
m_iUnion' ⦃f : ℕ → Set α⦄ : (∀ i, MeasurableSet (f i)) → Pairwise (Disjoint on f) →
HasSum (fun i => measureOf' (f i)) (measureOf' (⋃ i, f i))
/-- A `SignedMeasure` is an `ℝ`-vector measure. -/
abbrev SignedMeasure (α : Type*) [MeasurableSpace α] :=
VectorMeasure α ℝ
open Set
namespace VectorMeasure
section
variable {M : Type*} [AddCommMonoid M] [TopologicalSpace M]
attribute [coe] VectorMeasure.measureOf'
instance instCoeFun : CoeFun (VectorMeasure α M) fun _ => Set α → M :=
⟨VectorMeasure.measureOf'⟩
initialize_simps_projections VectorMeasure (measureOf' → apply)
@[simp]
theorem empty (v : VectorMeasure α M) : v ∅ = 0 :=
v.empty'
theorem not_measurable (v : VectorMeasure α M) {i : Set α} (hi : ¬MeasurableSet i) : v i = 0 :=
v.not_measurable' hi
theorem m_iUnion (v : VectorMeasure α M) {f : ℕ → Set α} (hf₁ : ∀ i, MeasurableSet (f i))
(hf₂ : Pairwise (Disjoint on f)) : HasSum (fun i => v (f i)) (v (⋃ i, f i)) :=
v.m_iUnion' hf₁ hf₂
theorem coe_injective : @Function.Injective (VectorMeasure α M) (Set α → M) (⇑) := fun v w h => by
cases v
cases w
congr
theorem ext_iff' (v w : VectorMeasure α M) : v = w ↔ ∀ i : Set α, v i = w i := by
rw [← coe_injective.eq_iff, funext_iff]
theorem ext_iff (v w : VectorMeasure α M) : v = w ↔ ∀ i : Set α, MeasurableSet i → v i = w i := by
constructor
· rintro rfl _ _
rfl
· rw [ext_iff']
intro h i
by_cases hi : MeasurableSet i
· exact h i hi
· simp_rw [not_measurable _ hi]
@[ext]
theorem ext {s t : VectorMeasure α M} (h : ∀ i : Set α, MeasurableSet i → s i = t i) : s = t :=
(ext_iff s t).2 h
variable [Countable β] {v : VectorMeasure α M} {f : β → Set α}
theorem hasSum_of_disjoint_iUnion (hm : ∀ i, MeasurableSet (f i)) (hd : Pairwise (Disjoint on f)) :
HasSum (fun i => v (f i)) (v (⋃ i, f i)) := by
rcases Countable.exists_injective_nat β with ⟨e, he⟩
rw [← hasSum_extend_zero he]
convert m_iUnion v (f := Function.extend e f fun _ ↦ ∅) _ _
· simp only [Pi.zero_def, Function.apply_extend v, Function.comp_def, empty]
· exact (iSup_extend_bot he _).symm
· simp [Function.apply_extend MeasurableSet, Function.comp_def, hm]
· exact hd.disjoint_extend_bot (he.factorsThrough _)
variable [T2Space M]
theorem of_disjoint_iUnion (hm : ∀ i, MeasurableSet (f i)) (hd : Pairwise (Disjoint on f)) :
v (⋃ i, f i) = ∑' i, v (f i) :=
(hasSum_of_disjoint_iUnion hm hd).tsum_eq.symm
theorem of_union {A B : Set α} (h : Disjoint A B) (hA : MeasurableSet A) (hB : MeasurableSet B) :
v (A ∪ B) = v A + v B := by
rw [Set.union_eq_iUnion, of_disjoint_iUnion, tsum_fintype, Fintype.sum_bool, cond, cond]
exacts [fun b => Bool.casesOn b hB hA, pairwise_disjoint_on_bool.2 h]
theorem of_add_of_diff {A B : Set α} (hA : MeasurableSet A) (hB : MeasurableSet B) (h : A ⊆ B) :
v A + v (B \ A) = v B := by
rw [← of_union (@Set.disjoint_sdiff_right _ A B) hA (hB.diff hA), Set.union_diff_cancel h]
theorem of_diff {M : Type*} [AddCommGroup M] [TopologicalSpace M] [T2Space M]
{v : VectorMeasure α M} {A B : Set α} (hA : MeasurableSet A) (hB : MeasurableSet B)
(h : A ⊆ B) : v (B \ A) = v B - v A := by
rw [← of_add_of_diff hA hB h, add_sub_cancel_left]
theorem of_diff_of_diff_eq_zero {A B : Set α} (hA : MeasurableSet A) (hB : MeasurableSet B)
(h' : v (B \ A) = 0) : v (A \ B) + v B = v A := by
symm
calc
v A = v (A \ B ∪ A ∩ B) := by simp only [Set.diff_union_inter]
_ = v (A \ B) + v (A ∩ B) := by
rw [of_union]
· rw [disjoint_comm]
exact Set.disjoint_of_subset_left A.inter_subset_right disjoint_sdiff_self_right
· exact hA.diff hB
· exact hA.inter hB
_ = v (A \ B) + v (A ∩ B ∪ B \ A) := by
rw [of_union, h', add_zero]
· exact Set.disjoint_of_subset_left A.inter_subset_left disjoint_sdiff_self_right
· exact hA.inter hB
· exact hB.diff hA
_ = v (A \ B) + v B := by rw [Set.union_comm, Set.inter_comm, Set.diff_union_inter]
theorem of_iUnion_nonneg {M : Type*} [TopologicalSpace M]
[AddCommMonoid M] [PartialOrder M] [IsOrderedAddMonoid M]
[OrderClosedTopology M] {v : VectorMeasure α M} (hf₁ : ∀ i, MeasurableSet (f i))
(hf₂ : Pairwise (Disjoint on f)) (hf₃ : ∀ i, 0 ≤ v (f i)) : 0 ≤ v (⋃ i, f i) :=
(v.of_disjoint_iUnion hf₁ hf₂).symm ▸ tsum_nonneg hf₃
theorem of_iUnion_nonpos {M : Type*} [TopologicalSpace M]
[AddCommMonoid M] [PartialOrder M] [IsOrderedAddMonoid M]
[OrderClosedTopology M] {v : VectorMeasure α M} (hf₁ : ∀ i, MeasurableSet (f i))
(hf₂ : Pairwise (Disjoint on f)) (hf₃ : ∀ i, v (f i) ≤ 0) : v (⋃ i, f i) ≤ 0 :=
(v.of_disjoint_iUnion hf₁ hf₂).symm ▸ tsum_nonpos hf₃
theorem of_nonneg_disjoint_union_eq_zero {s : SignedMeasure α} {A B : Set α} (h : Disjoint A B)
(hA₁ : MeasurableSet A) (hB₁ : MeasurableSet B) (hA₂ : 0 ≤ s A) (hB₂ : 0 ≤ s B)
(hAB : s (A ∪ B) = 0) : s A = 0 := by
rw [of_union h hA₁ hB₁] at hAB
linarith
theorem of_nonpos_disjoint_union_eq_zero {s : SignedMeasure α} {A B : Set α} (h : Disjoint A B)
(hA₁ : MeasurableSet A) (hB₁ : MeasurableSet B) (hA₂ : s A ≤ 0) (hB₂ : s B ≤ 0)
(hAB : s (A ∪ B) = 0) : s A = 0 := by
rw [of_union h hA₁ hB₁] at hAB
linarith
end
section SMul
variable {M : Type*} [AddCommMonoid M] [TopologicalSpace M]
variable {R : Type*} [Semiring R] [DistribMulAction R M] [ContinuousConstSMul R M]
/-- Given a scalar `r` and a vector measure `v`, `smul r v` is the vector measure corresponding to
the set function `s : Set α => r • (v s)`. -/
def smul (r : R) (v : VectorMeasure α M) : VectorMeasure α M where
measureOf' := r • ⇑v
empty' := by rw [Pi.smul_apply, empty, smul_zero]
not_measurable' _ hi := by rw [Pi.smul_apply, v.not_measurable hi, smul_zero]
m_iUnion' _ hf₁ hf₂ := by exact HasSum.const_smul _ (v.m_iUnion hf₁ hf₂)
instance instSMul : SMul R (VectorMeasure α M) :=
⟨smul⟩
@[simp]
theorem coe_smul (r : R) (v : VectorMeasure α M) : ⇑(r • v) = r • ⇑v := rfl
theorem smul_apply (r : R) (v : VectorMeasure α M) (i : Set α) : (r • v) i = r • v i := rfl
end SMul
section AddCommMonoid
variable {M : Type*} [AddCommMonoid M] [TopologicalSpace M]
instance instZero : Zero (VectorMeasure α M) :=
⟨⟨0, rfl, fun _ _ => rfl, fun _ _ _ => hasSum_zero⟩⟩
instance instInhabited : Inhabited (VectorMeasure α M) :=
⟨0⟩
@[simp]
theorem coe_zero : ⇑(0 : VectorMeasure α M) = 0 := rfl
theorem zero_apply (i : Set α) : (0 : VectorMeasure α M) i = 0 := rfl
variable [ContinuousAdd M]
/-- The sum of two vector measure is a vector measure. -/
def add (v w : VectorMeasure α M) : VectorMeasure α M where
measureOf' := v + w
empty' := by simp
not_measurable' _ hi := by rw [Pi.add_apply, v.not_measurable hi, w.not_measurable hi, add_zero]
m_iUnion' _ hf₁ hf₂ := HasSum.add (v.m_iUnion hf₁ hf₂) (w.m_iUnion hf₁ hf₂)
instance instAdd : Add (VectorMeasure α M) :=
⟨add⟩
@[simp]
theorem coe_add (v w : VectorMeasure α M) : ⇑(v + w) = v + w := rfl
theorem add_apply (v w : VectorMeasure α M) (i : Set α) : (v + w) i = v i + w i := rfl
instance instAddCommMonoid : AddCommMonoid (VectorMeasure α M) :=
Function.Injective.addCommMonoid _ coe_injective coe_zero coe_add fun _ _ => coe_smul _ _
/-- `(⇑)` is an `AddMonoidHom`. -/
@[simps]
def coeFnAddMonoidHom : VectorMeasure α M →+ Set α → M where
toFun := (⇑)
map_zero' := coe_zero
map_add' := coe_add
end AddCommMonoid
section AddCommGroup
variable {M : Type*} [AddCommGroup M] [TopologicalSpace M] [IsTopologicalAddGroup M]
/-- The negative of a vector measure is a vector measure. -/
def neg (v : VectorMeasure α M) : VectorMeasure α M where
measureOf' := -v
empty' := by simp
not_measurable' _ hi := by rw [Pi.neg_apply, neg_eq_zero, v.not_measurable hi]
m_iUnion' _ hf₁ hf₂ := HasSum.neg <| v.m_iUnion hf₁ hf₂
instance instNeg : Neg (VectorMeasure α M) :=
⟨neg⟩
@[simp]
theorem coe_neg (v : VectorMeasure α M) : ⇑(-v) = -v := rfl
theorem neg_apply (v : VectorMeasure α M) (i : Set α) : (-v) i = -v i := rfl
/-- The difference of two vector measure is a vector measure. -/
def sub (v w : VectorMeasure α M) : VectorMeasure α M where
measureOf' := v - w
empty' := by simp
not_measurable' _ hi := by rw [Pi.sub_apply, v.not_measurable hi, w.not_measurable hi, sub_zero]
m_iUnion' _ hf₁ hf₂ := HasSum.sub (v.m_iUnion hf₁ hf₂) (w.m_iUnion hf₁ hf₂)
instance instSub : Sub (VectorMeasure α M) :=
⟨sub⟩
@[simp]
theorem coe_sub (v w : VectorMeasure α M) : ⇑(v - w) = v - w := rfl
theorem sub_apply (v w : VectorMeasure α M) (i : Set α) : (v - w) i = v i - w i := rfl
instance instAddCommGroup : AddCommGroup (VectorMeasure α M) :=
Function.Injective.addCommGroup _ coe_injective coe_zero coe_add coe_neg coe_sub
(fun _ _ => coe_smul _ _) fun _ _ => coe_smul _ _
end AddCommGroup
section DistribMulAction
variable {M : Type*} [AddCommMonoid M] [TopologicalSpace M]
variable {R : Type*} [Semiring R] [DistribMulAction R M] [ContinuousConstSMul R M]
instance instDistribMulAction [ContinuousAdd M] : DistribMulAction R (VectorMeasure α M) :=
Function.Injective.distribMulAction coeFnAddMonoidHom coe_injective coe_smul
end DistribMulAction
section Module
variable {M : Type*} [AddCommMonoid M] [TopologicalSpace M]
variable {R : Type*} [Semiring R] [Module R M] [ContinuousConstSMul R M]
instance instModule [ContinuousAdd M] : Module R (VectorMeasure α M) :=
Function.Injective.module R coeFnAddMonoidHom coe_injective coe_smul
end Module
end VectorMeasure
namespace Measure
open Classical in
/-- A finite measure coerced into a real function is a signed measure. -/
@[simps]
def toSignedMeasure (μ : Measure α) [hμ : IsFiniteMeasure μ] : SignedMeasure α where
measureOf' := fun s : Set α => if MeasurableSet s then μ.real s else 0
empty' := by simp
not_measurable' _ hi := if_neg hi
m_iUnion' f hf₁ hf₂ := by
simp only [*, MeasurableSet.iUnion hf₁, if_true, measure_iUnion hf₂ hf₁, measureReal_def]
rw [ENNReal.tsum_toReal_eq]
exacts [(summable_measure_toReal hf₁ hf₂).hasSum, fun _ ↦ measure_ne_top _ _]
theorem toSignedMeasure_apply_measurable {μ : Measure α} [IsFiniteMeasure μ] {i : Set α}
(hi : MeasurableSet i) : μ.toSignedMeasure i = μ.real i :=
if_pos hi
-- Without this lemma, `singularPart_neg` in
-- `Mathlib/MeasureTheory/Measure/Decomposition/Lebesgue.lean` is extremely slow
theorem toSignedMeasure_congr {μ ν : Measure α} [IsFiniteMeasure μ] [IsFiniteMeasure ν]
(h : μ = ν) : μ.toSignedMeasure = ν.toSignedMeasure := by
congr
theorem toSignedMeasure_eq_toSignedMeasure_iff {μ ν : Measure α} [IsFiniteMeasure μ]
[IsFiniteMeasure ν] : μ.toSignedMeasure = ν.toSignedMeasure ↔ μ = ν := by
refine ⟨fun h => ?_, fun h => ?_⟩
· ext1 i hi
have : μ.toSignedMeasure i = ν.toSignedMeasure i := by rw [h]
rwa [toSignedMeasure_apply_measurable hi, toSignedMeasure_apply_measurable hi,
measureReal_eq_measureReal_iff] at this
· congr
@[simp]
theorem toSignedMeasure_zero : (0 : Measure α).toSignedMeasure = 0 := by
ext i
simp
@[simp]
theorem toSignedMeasure_add (μ ν : Measure α) [IsFiniteMeasure μ] [IsFiniteMeasure ν] :
(μ + ν).toSignedMeasure = μ.toSignedMeasure + ν.toSignedMeasure := by
ext i hi
rw [toSignedMeasure_apply_measurable hi, measureReal_add_apply,
VectorMeasure.add_apply, toSignedMeasure_apply_measurable hi,
toSignedMeasure_apply_measurable hi]
@[simp]
theorem toSignedMeasure_smul (μ : Measure α) [IsFiniteMeasure μ] (r : ℝ≥0) :
(r • μ).toSignedMeasure = r • μ.toSignedMeasure := by
ext i hi
rw [toSignedMeasure_apply_measurable hi, VectorMeasure.smul_apply,
toSignedMeasure_apply_measurable hi, measureReal_nnreal_smul_apply]
rfl
open Classical in
/-- A measure is a vector measure over `ℝ≥0∞`. -/
@[simps]
def toENNRealVectorMeasure (μ : Measure α) : VectorMeasure α ℝ≥0∞ where
measureOf' := fun i : Set α => if MeasurableSet i then μ i else 0
empty' := by simp
not_measurable' _ hi := if_neg hi
m_iUnion' _ hf₁ hf₂ := by
rw [Summable.hasSum_iff ENNReal.summable, if_pos (MeasurableSet.iUnion hf₁),
MeasureTheory.measure_iUnion hf₂ hf₁]
exact tsum_congr fun n => if_pos (hf₁ n)
theorem toENNRealVectorMeasure_apply_measurable {μ : Measure α} {i : Set α} (hi : MeasurableSet i) :
μ.toENNRealVectorMeasure i = μ i :=
if_pos hi
@[simp]
theorem toENNRealVectorMeasure_zero : (0 : Measure α).toENNRealVectorMeasure = 0 := by
ext i
simp
@[simp]
theorem toENNRealVectorMeasure_add (μ ν : Measure α) :
(μ + ν).toENNRealVectorMeasure = μ.toENNRealVectorMeasure + ν.toENNRealVectorMeasure := by
refine MeasureTheory.VectorMeasure.ext fun i hi => ?_
rw [toENNRealVectorMeasure_apply_measurable hi, add_apply, VectorMeasure.add_apply,
toENNRealVectorMeasure_apply_measurable hi, toENNRealVectorMeasure_apply_measurable hi]
theorem toSignedMeasure_sub_apply {μ ν : Measure α} [IsFiniteMeasure μ] [IsFiniteMeasure ν]
{i : Set α} (hi : MeasurableSet i) :
(μ.toSignedMeasure - ν.toSignedMeasure) i = μ.real i - ν.real i := by
rw [VectorMeasure.sub_apply, toSignedMeasure_apply_measurable hi,
Measure.toSignedMeasure_apply_measurable hi]
end Measure
namespace VectorMeasure
open Measure
section
/-- A vector measure over `ℝ≥0∞` is a measure. -/
def ennrealToMeasure {_ : MeasurableSpace α} (v : VectorMeasure α ℝ≥0∞) : Measure α :=
ofMeasurable (fun s _ => v s) v.empty fun _ hf₁ hf₂ => v.of_disjoint_iUnion hf₁ hf₂
theorem ennrealToMeasure_apply {m : MeasurableSpace α} {v : VectorMeasure α ℝ≥0∞} {s : Set α}
(hs : MeasurableSet s) : ennrealToMeasure v s = v s := by
rw [ennrealToMeasure, ofMeasurable_apply _ hs]
@[simp]
theorem _root_.MeasureTheory.Measure.toENNRealVectorMeasure_ennrealToMeasure
(μ : VectorMeasure α ℝ≥0∞) :
toENNRealVectorMeasure (ennrealToMeasure μ) = μ := ext fun s hs => by
rw [toENNRealVectorMeasure_apply_measurable hs, ennrealToMeasure_apply hs]
@[simp]
theorem ennrealToMeasure_toENNRealVectorMeasure (μ : Measure α) :
ennrealToMeasure (toENNRealVectorMeasure μ) = μ := Measure.ext fun s hs => by
rw [ennrealToMeasure_apply hs, toENNRealVectorMeasure_apply_measurable hs]
/-- The equiv between `VectorMeasure α ℝ≥0∞` and `Measure α` formed by
`MeasureTheory.VectorMeasure.ennrealToMeasure` and
`MeasureTheory.Measure.toENNRealVectorMeasure`. -/
@[simps]
def equivMeasure [MeasurableSpace α] : VectorMeasure α ℝ≥0∞ ≃ Measure α where
toFun := ennrealToMeasure
invFun := toENNRealVectorMeasure
left_inv := toENNRealVectorMeasure_ennrealToMeasure
right_inv := ennrealToMeasure_toENNRealVectorMeasure
end
section
variable [MeasurableSpace α] [MeasurableSpace β]
variable {M : Type*} [AddCommMonoid M] [TopologicalSpace M]
variable (v : VectorMeasure α M)
open Classical in
/-- The pushforward of a vector measure along a function. -/
def map (v : VectorMeasure α M) (f : α → β) : VectorMeasure β M :=
if hf : Measurable f then
{ measureOf' := fun s => if MeasurableSet s then v (f ⁻¹' s) else 0
empty' := by simp
not_measurable' := fun _ hi => if_neg hi
m_iUnion' := by
intro g hg₁ hg₂
convert v.m_iUnion (fun i => hf (hg₁ i)) fun i j hij => (hg₂ hij).preimage _
· rw [if_pos (hg₁ _)]
· rw [Set.preimage_iUnion, if_pos (MeasurableSet.iUnion hg₁)] }
else 0
theorem map_not_measurable {f : α → β} (hf : ¬Measurable f) : v.map f = 0 :=
dif_neg hf
theorem map_apply {f : α → β} (hf : Measurable f) {s : Set β} (hs : MeasurableSet s) :
v.map f s = v (f ⁻¹' s) := by
rw [map, dif_pos hf]
exact if_pos hs
@[simp]
theorem map_id : v.map id = v :=
ext fun i hi => by rw [map_apply v measurable_id hi, Set.preimage_id]
@[simp]
theorem map_zero (f : α → β) : (0 : VectorMeasure α M).map f = 0 := by
by_cases hf : Measurable f
· ext i hi
rw [map_apply _ hf hi, zero_apply, zero_apply]
· exact dif_neg hf
section
variable {N : Type*} [AddCommMonoid N] [TopologicalSpace N]
/-- Given a vector measure `v` on `M` and a continuous `AddMonoidHom` `f : M → N`, `f ∘ v` is a
vector measure on `N`. -/
def mapRange (v : VectorMeasure α M) (f : M →+ N) (hf : Continuous f) : VectorMeasure α N where
measureOf' s := f (v s)
empty' := by rw [empty, AddMonoidHom.map_zero]
not_measurable' i hi := by rw [not_measurable v hi, AddMonoidHom.map_zero]
m_iUnion' _ hg₁ hg₂ := HasSum.map (v.m_iUnion hg₁ hg₂) f hf
@[simp]
theorem mapRange_apply {f : M →+ N} (hf : Continuous f) {s : Set α} : v.mapRange f hf s = f (v s) :=
rfl
@[simp]
theorem mapRange_id : v.mapRange (AddMonoidHom.id M) continuous_id = v := by
ext
rfl
@[simp]
theorem mapRange_zero {f : M →+ N} (hf : Continuous f) :
mapRange (0 : VectorMeasure α M) f hf = 0 := by
ext
simp
section ContinuousAdd
variable [ContinuousAdd M] [ContinuousAdd N]
@[simp]
theorem mapRange_add {v w : VectorMeasure α M} {f : M →+ N} (hf : Continuous f) :
(v + w).mapRange f hf = v.mapRange f hf + w.mapRange f hf := by
ext
simp
/-- Given a continuous `AddMonoidHom` `f : M → N`, `mapRangeHom` is the `AddMonoidHom` mapping the
vector measure `v` on `M` to the vector measure `f ∘ v` on `N`. -/
def mapRangeHom (f : M →+ N) (hf : Continuous f) : VectorMeasure α M →+ VectorMeasure α N where
toFun v := v.mapRange f hf
map_zero' := mapRange_zero hf
map_add' _ _ := mapRange_add hf
end ContinuousAdd
section Module
variable {R : Type*} [Semiring R] [Module R M] [Module R N]
variable [ContinuousAdd M] [ContinuousAdd N] [ContinuousConstSMul R M] [ContinuousConstSMul R N]
/-- Given a continuous linear map `f : M → N`, `mapRangeₗ` is the linear map mapping the
vector measure `v` on `M` to the vector measure `f ∘ v` on `N`. -/
def mapRangeₗ (f : M →ₗ[R] N) (hf : Continuous f) : VectorMeasure α M →ₗ[R] VectorMeasure α N where
toFun v := v.mapRange f.toAddMonoidHom hf
map_add' _ _ := mapRange_add hf
map_smul' := by
intros
ext
simp
end Module
end
open Classical in
/-- The restriction of a vector measure on some set. -/
def restrict (v : VectorMeasure α M) (i : Set α) : VectorMeasure α M :=
if hi : MeasurableSet i then
{ measureOf' := fun s => if MeasurableSet s then v (s ∩ i) else 0
empty' := by simp
not_measurable' := fun _ hi => if_neg hi
m_iUnion' := by
intro f hf₁ hf₂
convert v.m_iUnion (fun n => (hf₁ n).inter hi)
(hf₂.mono fun i j => Disjoint.mono inf_le_left inf_le_left)
· rw [if_pos (hf₁ _)]
· rw [Set.iUnion_inter, if_pos (MeasurableSet.iUnion hf₁)] }
else 0
theorem restrict_not_measurable {i : Set α} (hi : ¬MeasurableSet i) : v.restrict i = 0 :=
dif_neg hi
theorem restrict_apply {i : Set α} (hi : MeasurableSet i) {j : Set α} (hj : MeasurableSet j) :
v.restrict i j = v (j ∩ i) := by
rw [restrict, dif_pos hi]
exact if_pos hj
theorem restrict_eq_self {i : Set α} (hi : MeasurableSet i) {j : Set α} (hj : MeasurableSet j)
(hij : j ⊆ i) : v.restrict i j = v j := by
rw [restrict_apply v hi hj, Set.inter_eq_left.2 hij]
@[simp]
theorem restrict_empty : v.restrict ∅ = 0 :=
ext fun i hi => by
rw [restrict_apply v MeasurableSet.empty hi, Set.inter_empty, v.empty, zero_apply]
@[simp]
theorem restrict_univ : v.restrict Set.univ = v :=
ext fun i hi => by rw [restrict_apply v MeasurableSet.univ hi, Set.inter_univ]
@[simp]
theorem restrict_zero {i : Set α} : (0 : VectorMeasure α M).restrict i = 0 := by
by_cases hi : MeasurableSet i
· ext j hj
rw [restrict_apply 0 hi hj, zero_apply, zero_apply]
· exact dif_neg hi
section ContinuousAdd
variable [ContinuousAdd M]
theorem map_add (v w : VectorMeasure α M) (f : α → β) : (v + w).map f = v.map f + w.map f := by
by_cases hf : Measurable f
· ext i hi
simp [map_apply _ hf hi]
· simp [map, dif_neg hf]
/-- `VectorMeasure.map` as an additive monoid homomorphism. -/
@[simps]
def mapGm (f : α → β) : VectorMeasure α M →+ VectorMeasure β M where
toFun v := v.map f
map_zero' := map_zero f
map_add' _ _ := map_add _ _ f
@[simp]
theorem restrict_add (v w : VectorMeasure α M) (i : Set α) :
(v + w).restrict i = v.restrict i + w.restrict i := by
by_cases hi : MeasurableSet i
· ext j hj
simp [restrict_apply _ hi hj]
· simp [restrict_not_measurable _ hi]
/-- `VectorMeasure.restrict` as an additive monoid homomorphism. -/
@[simps]
def restrictGm (i : Set α) : VectorMeasure α M →+ VectorMeasure α M where
toFun v := v.restrict i
map_zero' := restrict_zero
map_add' _ _ := restrict_add _ _ i
end ContinuousAdd
section Partition
variable {M : Type*} [TopologicalSpace M] [AddCommMonoid M] [T2Space M] [ContinuousAdd M]
variable (v : VectorMeasure α M) {i : Set α}
@[simp]
theorem restrict_add_restrict_compl (hi : MeasurableSet i) :
v.restrict i + v.restrict iᶜ = v := by
ext A hA
rw [add_apply, restrict_apply _ hi hA, restrict_apply _ hi.compl hA,
← of_union _ (hA.inter hi) (hA.inter hi.compl)]
· simp
· exact disjoint_compl_right.inter_right' A |>.inter_left' A
end Partition
section Sub
variable {M : Type*} [AddCommGroup M] [TopologicalSpace M] [IsTopologicalAddGroup M]
@[simp]
theorem restrict_neg (v : VectorMeasure α M) (i : Set α) :
(-v).restrict i = -(v.restrict i) := by
by_cases hi : MeasurableSet i
· ext j hj; simp [restrict_apply _ hi hj]
· simp [restrict_not_measurable _ hi]
@[simp]
theorem restrict_sub (v w : VectorMeasure α M) (i : Set α) :
(v - w).restrict i = v.restrict i - w.restrict i := by
simp [sub_eq_add_neg, restrict_add, restrict_neg]
end Sub
end
section
variable [MeasurableSpace β]
variable {M : Type*} [AddCommMonoid M] [TopologicalSpace M]
variable {R : Type*} [Semiring R] [DistribMulAction R M] [ContinuousConstSMul R M]
@[simp]
theorem map_smul {v : VectorMeasure α M} {f : α → β} (c : R) : (c • v).map f = c • v.map f := by
by_cases hf : Measurable f
· ext i hi
simp [map_apply _ hf hi]
· simp only [map, dif_neg hf]
-- `smul_zero` does not work since we do not require `ContinuousAdd`
ext i
simp
@[simp]
theorem restrict_smul {v : VectorMeasure α M} {i : Set α} (c : R) :
(c • v).restrict i = c • v.restrict i := by
by_cases hi : MeasurableSet i
· ext j hj
simp [restrict_apply _ hi hj]
· simp only [restrict_not_measurable _ hi]
-- `smul_zero` does not work since we do not require `ContinuousAdd`
ext j
simp
end
section
variable [MeasurableSpace β]
variable {M : Type*} [AddCommMonoid M] [TopologicalSpace M]
variable {R : Type*} [Semiring R] [Module R M] [ContinuousConstSMul R M] [ContinuousAdd M]
/-- `VectorMeasure.map` as a linear map. -/
@[simps]
def mapₗ (f : α → β) : VectorMeasure α M →ₗ[R] VectorMeasure β M where
toFun v := v.map f
map_add' _ _ := map_add _ _ f
map_smul' _ _ := map_smul _
/-- `VectorMeasure.restrict` as an additive monoid homomorphism. -/
@[simps]
def restrictₗ (i : Set α) : VectorMeasure α M →ₗ[R] VectorMeasure α M where
toFun v := v.restrict i
map_add' _ _ := restrict_add _ _ i
map_smul' _ _ := restrict_smul _
end
section
variable {M : Type*} [TopologicalSpace M] [AddCommMonoid M] [PartialOrder M]
/-- Vector measures over a partially ordered monoid is partially ordered.
This definition is consistent with `Measure.instPartialOrder`. -/
instance instPartialOrder : PartialOrder (VectorMeasure α M) where
le v w := ∀ i, MeasurableSet i → v i ≤ w i
le_refl _ _ _ := le_rfl
le_trans _ _ _ h₁ h₂ i hi := le_trans (h₁ i hi) (h₂ i hi)
le_antisymm _ _ h₁ h₂ := ext fun i hi => le_antisymm (h₁ i hi) (h₂ i hi)
variable {v w : VectorMeasure α M}
theorem le_iff : v ≤ w ↔ ∀ i, MeasurableSet i → v i ≤ w i := Iff.rfl
theorem le_iff' : v ≤ w ↔ ∀ i, v i ≤ w i := by
refine ⟨fun h i => ?_, fun h i _ => h i⟩
by_cases hi : MeasurableSet i
· exact h i hi
· rw [v.not_measurable hi, w.not_measurable hi]
end
/-- `v ≤[i] w` is notation for `v.restrict i ≤ w.restrict i`. -/
scoped[MeasureTheory]
notation3:50 v " ≤[" i:50 "] " w:50 =>
MeasureTheory.VectorMeasure.restrict v i ≤ MeasureTheory.VectorMeasure.restrict w i
section
variable {M : Type*} [TopologicalSpace M] [AddCommMonoid M] [PartialOrder M]
variable (v w : VectorMeasure α M)
theorem restrict_le_restrict_iff {i : Set α} (hi : MeasurableSet i) :
v ≤[i] w ↔ ∀ ⦃j⦄, MeasurableSet j → j ⊆ i → v j ≤ w j :=
⟨fun h j hj₁ hj₂ => restrict_eq_self v hi hj₁ hj₂ ▸ restrict_eq_self w hi hj₁ hj₂ ▸ h j hj₁,
fun h => le_iff.1 fun _ hj =>
(restrict_apply v hi hj).symm ▸ (restrict_apply w hi hj).symm ▸
h (hj.inter hi) Set.inter_subset_right⟩
theorem subset_le_of_restrict_le_restrict {i : Set α} (hi : MeasurableSet i) (hi₂ : v ≤[i] w)
{j : Set α} (hj : j ⊆ i) : v j ≤ w j := by
by_cases hj₁ : MeasurableSet j
· exact (restrict_le_restrict_iff _ _ hi).1 hi₂ hj₁ hj
· rw [v.not_measurable hj₁, w.not_measurable hj₁]
theorem restrict_le_restrict_of_subset_le {i : Set α}
(h : ∀ ⦃j⦄, MeasurableSet j → j ⊆ i → v j ≤ w j) : v ≤[i] w := by
by_cases hi : MeasurableSet i
· exact (restrict_le_restrict_iff _ _ hi).2 h
· rw [restrict_not_measurable v hi, restrict_not_measurable w hi]
theorem restrict_le_restrict_subset {i j : Set α} (hi₁ : MeasurableSet i) (hi₂ : v ≤[i] w)
(hij : j ⊆ i) : v ≤[j] w :=
restrict_le_restrict_of_subset_le v w fun _ _ hk₂ =>
subset_le_of_restrict_le_restrict v w hi₁ hi₂ (Set.Subset.trans hk₂ hij)
theorem le_restrict_empty : v ≤[∅] w := by
intro j _
rw [restrict_empty, restrict_empty]
theorem le_restrict_univ_iff_le : v ≤[Set.univ] w ↔ v ≤ w := by
simp
end
section
variable {M : Type*} [TopologicalSpace M]
[AddCommGroup M] [PartialOrder M] [IsOrderedAddMonoid M] [IsTopologicalAddGroup M]
variable (v w : VectorMeasure α M)
nonrec theorem neg_le_neg {i : Set α} (hi : MeasurableSet i) (h : v ≤[i] w) : -w ≤[i] -v := by
intro j hj₁
rw [restrict_apply _ hi hj₁, restrict_apply _ hi hj₁, neg_apply, neg_apply]
refine neg_le_neg ?_
rw [← restrict_apply _ hi hj₁, ← restrict_apply _ hi hj₁]
exact h j hj₁
theorem neg_le_neg_iff {i : Set α} (hi : MeasurableSet i) : -w ≤[i] -v ↔ v ≤[i] w :=
⟨fun h => neg_neg v ▸ neg_neg w ▸ neg_le_neg _ _ hi h, fun h => neg_le_neg _ _ hi h⟩
end
section
variable {M : Type*} [TopologicalSpace M]
[AddCommMonoid M] [PartialOrder M] [IsOrderedAddMonoid M] [OrderClosedTopology M]
variable (v w : VectorMeasure α M) {i j : Set α}
theorem restrict_le_restrict_iUnion {f : ℕ → Set α} (hf₁ : ∀ n, MeasurableSet (f n))
(hf₂ : ∀ n, v ≤[f n] w) : v ≤[⋃ n, f n] w := by
refine restrict_le_restrict_of_subset_le v w fun a ha₁ ha₂ => ?_
have ha₃ : ⋃ n, a ∩ disjointed f n = a := by
rwa [← Set.inter_iUnion, iUnion_disjointed, Set.inter_eq_left]
have ha₄ : Pairwise (Disjoint on fun n => a ∩ disjointed f n) :=
(disjoint_disjointed _).mono fun i j => Disjoint.mono inf_le_right inf_le_right
rw [← ha₃, v.of_disjoint_iUnion _ ha₄, w.of_disjoint_iUnion _ ha₄]
· refine Summable.tsum_le_tsum (fun n => (restrict_le_restrict_iff v w (hf₁ n)).1 (hf₂ n) ?_ ?_)
?_ ?_
· exact ha₁.inter (MeasurableSet.disjointed hf₁ n)
· exact Set.Subset.trans Set.inter_subset_right (disjointed_subset _ _)
· refine (v.m_iUnion (fun n => ?_) ?_).summable
· exact ha₁.inter (MeasurableSet.disjointed hf₁ n)
· exact (disjoint_disjointed _).mono fun i j => Disjoint.mono inf_le_right inf_le_right
· refine (w.m_iUnion (fun n => ?_) ?_).summable
· exact ha₁.inter (MeasurableSet.disjointed hf₁ n)
· exact (disjoint_disjointed _).mono fun i j => Disjoint.mono inf_le_right inf_le_right
· intro n
exact ha₁.inter (MeasurableSet.disjointed hf₁ n)
· exact fun n => ha₁.inter (MeasurableSet.disjointed hf₁ n)
theorem restrict_le_restrict_countable_iUnion [Countable β] {f : β → Set α}
(hf₁ : ∀ b, MeasurableSet (f b)) (hf₂ : ∀ b, v ≤[f b] w) : v ≤[⋃ b, f b] w := by
cases nonempty_encodable β
rw [← Encodable.iUnion_decode₂]
refine restrict_le_restrict_iUnion v w ?_ ?_
· intro n
measurability
· intro n
rcases Encodable.decode₂ β n with - | b
· simp
· simp [hf₂ b]
theorem restrict_le_restrict_union (hi₁ : MeasurableSet i) (hi₂ : v ≤[i] w) (hj₁ : MeasurableSet j)
(hj₂ : v ≤[j] w) : v ≤[i ∪ j] w := by
rw [Set.union_eq_iUnion]
refine restrict_le_restrict_countable_iUnion v w ?_ ?_
· measurability
· rintro (_ | _) <;> simpa
end
section
variable {M : Type*} [TopologicalSpace M] [AddCommMonoid M] [PartialOrder M]
variable (v w : VectorMeasure α M) {i j : Set α}
theorem nonneg_of_zero_le_restrict (hi₂ : 0 ≤[i] v) : 0 ≤ v i := by
by_cases hi₁ : MeasurableSet i
· exact (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hi₁ Set.Subset.rfl
· rw [v.not_measurable hi₁]
theorem nonpos_of_restrict_le_zero (hi₂ : v ≤[i] 0) : v i ≤ 0 := by
by_cases hi₁ : MeasurableSet i
· exact (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hi₁ Set.Subset.rfl
· rw [v.not_measurable hi₁]
theorem zero_le_restrict_not_measurable (hi : ¬MeasurableSet i) : 0 ≤[i] v := by
rw [restrict_zero, restrict_not_measurable _ hi]
theorem restrict_le_zero_of_not_measurable (hi : ¬MeasurableSet i) : v ≤[i] 0 := by
rw [restrict_zero, restrict_not_measurable _ hi]
theorem measurable_of_not_zero_le_restrict (hi : ¬0 ≤[i] v) : MeasurableSet i :=
Not.imp_symm (zero_le_restrict_not_measurable _) hi
theorem measurable_of_not_restrict_le_zero (hi : ¬v ≤[i] 0) : MeasurableSet i :=
Not.imp_symm (restrict_le_zero_of_not_measurable _) hi
theorem zero_le_restrict_subset (hi₁ : MeasurableSet i) (hij : j ⊆ i) (hi₂ : 0 ≤[i] v) : 0 ≤[j] v :=
restrict_le_restrict_of_subset_le _ _ fun _ hk₁ hk₂ =>
(restrict_le_restrict_iff _ _ hi₁).1 hi₂ hk₁ (Set.Subset.trans hk₂ hij)
theorem restrict_le_zero_subset (hi₁ : MeasurableSet i) (hij : j ⊆ i) (hi₂ : v ≤[i] 0) : v ≤[j] 0 :=
restrict_le_restrict_of_subset_le _ _ fun _ hk₁ hk₂ =>
(restrict_le_restrict_iff _ _ hi₁).1 hi₂ hk₁ (Set.Subset.trans hk₂ hij)
end
section
variable {M : Type*} [TopologicalSpace M] [AddCommMonoid M] [LinearOrder M]
variable (v w : VectorMeasure α M) {i j : Set α}
theorem exists_pos_measure_of_not_restrict_le_zero (hi : ¬v ≤[i] 0) :
∃ j : Set α, MeasurableSet j ∧ j ⊆ i ∧ 0 < v j := by
have hi₁ : MeasurableSet i := measurable_of_not_restrict_le_zero _ hi
rw [restrict_le_restrict_iff _ _ hi₁] at hi
push_neg at hi
exact hi
end
section
variable {M : Type*} [TopologicalSpace M] [AddCommMonoid M] [PartialOrder M]
[AddLeftMono M] [ContinuousAdd M]
instance instAddLeftMono : AddLeftMono (VectorMeasure α M) :=
⟨fun _ _ _ h i hi => add_le_add_left (h i hi) _⟩
end
section
variable {L M N : Type*}
variable [AddCommMonoid L] [TopologicalSpace L] [AddCommMonoid M] [TopologicalSpace M]
[AddCommMonoid N] [TopologicalSpace N]
/-- A vector measure `v` is absolutely continuous with respect to a measure `μ` if for all sets
`s`, `μ s = 0`, we have `v s = 0`. -/
def AbsolutelyContinuous (v : VectorMeasure α M) (w : VectorMeasure α N) :=
∀ ⦃s : Set α⦄, w s = 0 → v s = 0
@[inherit_doc VectorMeasure.AbsolutelyContinuous]
scoped[MeasureTheory] infixl:50 " ≪ᵥ " => MeasureTheory.VectorMeasure.AbsolutelyContinuous
open MeasureTheory
namespace AbsolutelyContinuous
variable {v : VectorMeasure α M} {w : VectorMeasure α N}
theorem mk (h : ∀ ⦃s : Set α⦄, MeasurableSet s → w s = 0 → v s = 0) : v ≪ᵥ w := by
intro s hs
by_cases hmeas : MeasurableSet s
· exact h hmeas hs
· exact not_measurable v hmeas
theorem eq {w : VectorMeasure α M} (h : v = w) : v ≪ᵥ w :=
fun _ hs => h.symm ▸ hs
@[refl]
theorem refl (v : VectorMeasure α M) : v ≪ᵥ v :=
eq rfl
@[trans]
theorem trans {u : VectorMeasure α L} {v : VectorMeasure α M} {w : VectorMeasure α N} (huv : u ≪ᵥ v)
(hvw : v ≪ᵥ w) : u ≪ᵥ w :=
fun _ hs => huv <| hvw hs
theorem zero (v : VectorMeasure α N) : (0 : VectorMeasure α M) ≪ᵥ v :=
fun s _ => VectorMeasure.zero_apply s
theorem neg_left {M : Type*} [AddCommGroup M] [TopologicalSpace M] [IsTopologicalAddGroup M]
{v : VectorMeasure α M} {w : VectorMeasure α N} (h : v ≪ᵥ w) : -v ≪ᵥ w := by
intro s hs
rw [neg_apply, h hs, neg_zero]
theorem neg_right {N : Type*} [AddCommGroup N] [TopologicalSpace N] [IsTopologicalAddGroup N]
{v : VectorMeasure α M} {w : VectorMeasure α N} (h : v ≪ᵥ w) : v ≪ᵥ -w := by
intro s hs
rw [neg_apply, neg_eq_zero] at hs
exact h hs
theorem add [ContinuousAdd M] {v₁ v₂ : VectorMeasure α M} {w : VectorMeasure α N} (hv₁ : v₁ ≪ᵥ w)
(hv₂ : v₂ ≪ᵥ w) : v₁ + v₂ ≪ᵥ w := by
intro s hs
rw [add_apply, hv₁ hs, hv₂ hs, zero_add]
theorem sub {M : Type*} [AddCommGroup M] [TopologicalSpace M] [IsTopologicalAddGroup M]
{v₁ v₂ : VectorMeasure α M} {w : VectorMeasure α N} (hv₁ : v₁ ≪ᵥ w) (hv₂ : v₂ ≪ᵥ w) :
v₁ - v₂ ≪ᵥ w := by
intro s hs
rw [sub_apply, hv₁ hs, hv₂ hs, zero_sub, neg_zero]
theorem smul {R : Type*} [Semiring R] [DistribMulAction R M] [ContinuousConstSMul R M] {r : R}
{v : VectorMeasure α M} {w : VectorMeasure α N} (h : v ≪ᵥ w) : r • v ≪ᵥ w := by
intro s hs
rw [smul_apply, h hs, smul_zero]
theorem map [MeasureSpace β] (h : v ≪ᵥ w) (f : α → β) : v.map f ≪ᵥ w.map f := by
by_cases hf : Measurable f
· refine mk fun s hs hws => ?_
rw [map_apply _ hf hs] at hws ⊢
exact h hws
· intro s _
rw [map_not_measurable v hf, zero_apply]
theorem ennrealToMeasure {μ : VectorMeasure α ℝ≥0∞} :
(∀ ⦃s : Set α⦄, μ.ennrealToMeasure s = 0 → v s = 0) ↔ v ≪ᵥ μ := by
constructor <;> intro h
· refine mk fun s hmeas hs => h ?_
rw [← hs, ennrealToMeasure_apply hmeas]
· intro s hs
by_cases hmeas : MeasurableSet s
· rw [ennrealToMeasure_apply hmeas] at hs
exact h hs
· exact not_measurable v hmeas
end AbsolutelyContinuous
/-- Two vector measures `v` and `w` are said to be mutually singular if there exists a measurable
set `s`, such that for all `t ⊆ s`, `v t = 0` and for all `t ⊆ sᶜ`, `w t = 0`.
We note that we do not require the measurability of `t` in the definition since this makes it easier
to use. This is equivalent to the definition which requires measurability. To prove
`MutuallySingular` with the measurability condition, use
`MeasureTheory.VectorMeasure.MutuallySingular.mk`. -/
def MutuallySingular (v : VectorMeasure α M) (w : VectorMeasure α N) : Prop :=
∃ s : Set α, MeasurableSet s ∧ (∀ t ⊆ s, v t = 0) ∧ ∀ t ⊆ sᶜ, w t = 0
@[inherit_doc VectorMeasure.MutuallySingular]
scoped[MeasureTheory] infixl:60 " ⟂ᵥ " => MeasureTheory.VectorMeasure.MutuallySingular
namespace MutuallySingular
variable {v v₁ v₂ : VectorMeasure α M} {w w₁ w₂ : VectorMeasure α N}
theorem mk (s : Set α) (hs : MeasurableSet s) (h₁ : ∀ t ⊆ s, MeasurableSet t → v t = 0)
(h₂ : ∀ t ⊆ sᶜ, MeasurableSet t → w t = 0) : v ⟂ᵥ w := by
refine ⟨s, hs, fun t hst => ?_, fun t hst => ?_⟩ <;> by_cases ht : MeasurableSet t
· exact h₁ t hst ht
· exact not_measurable v ht
· exact h₂ t hst ht
· exact not_measurable w ht
theorem symm (h : v ⟂ᵥ w) : w ⟂ᵥ v :=
let ⟨s, hmeas, hs₁, hs₂⟩ := h
⟨sᶜ, hmeas.compl, hs₂, fun t ht => hs₁ _ (compl_compl s ▸ ht : t ⊆ s)⟩
theorem zero_right : v ⟂ᵥ (0 : VectorMeasure α N) :=
⟨∅, MeasurableSet.empty, fun _ ht => (Set.subset_empty_iff.1 ht).symm ▸ v.empty,
fun _ _ => zero_apply _⟩
theorem zero_left : (0 : VectorMeasure α M) ⟂ᵥ w :=
zero_right.symm
theorem add_left [T2Space N] [ContinuousAdd M] (h₁ : v₁ ⟂ᵥ w) (h₂ : v₂ ⟂ᵥ w) : v₁ + v₂ ⟂ᵥ w := by
obtain ⟨u, hmu, hu₁, hu₂⟩ := h₁
obtain ⟨v, hmv, hv₁, hv₂⟩ := h₂
refine mk (u ∩ v) (hmu.inter hmv) (fun t ht _ => ?_) fun t ht hmt => ?_
· rw [add_apply, hu₁ _ (Set.subset_inter_iff.1 ht).1, hv₁ _ (Set.subset_inter_iff.1 ht).2,
zero_add]
· rw [Set.compl_inter] at ht
rw [(_ : t = uᶜ ∩ t ∪ vᶜ \ uᶜ ∩ t),
of_union _ (hmu.compl.inter hmt) ((hmv.compl.diff hmu.compl).inter hmt), hu₂, hv₂, add_zero]
· exact Set.Subset.trans Set.inter_subset_left diff_subset
· exact Set.inter_subset_left
· exact disjoint_sdiff_self_right.mono Set.inter_subset_left Set.inter_subset_left
· apply Set.Subset.antisymm <;> intro x hx
· by_cases hxu' : x ∈ uᶜ
· exact Or.inl ⟨hxu', hx⟩
rcases ht hx with (hxu | hxv)
exacts [False.elim (hxu' hxu), Or.inr ⟨⟨hxv, hxu'⟩, hx⟩]
· rcases hx with hx | hx <;> exact hx.2
theorem add_right [T2Space M] [ContinuousAdd N] (h₁ : v ⟂ᵥ w₁) (h₂ : v ⟂ᵥ w₂) : v ⟂ᵥ w₁ + w₂ :=
(add_left h₁.symm h₂.symm).symm
theorem smul_right {R : Type*} [Semiring R] [DistribMulAction R N] [ContinuousConstSMul R N]
(r : R) (h : v ⟂ᵥ w) : v ⟂ᵥ r • w :=
let ⟨s, hmeas, hs₁, hs₂⟩ := h
⟨s, hmeas, hs₁, fun t ht => by simp only [coe_smul, Pi.smul_apply, hs₂ t ht, smul_zero]⟩
theorem smul_left {R : Type*} [Semiring R] [DistribMulAction R M] [ContinuousConstSMul R M] (r : R)
(h : v ⟂ᵥ w) : r • v ⟂ᵥ w :=
(smul_right r h.symm).symm
theorem neg_left {M : Type*} [AddCommGroup M] [TopologicalSpace M] [IsTopologicalAddGroup M]
{v : VectorMeasure α M} {w : VectorMeasure α N} (h : v ⟂ᵥ w) : -v ⟂ᵥ w := by
obtain ⟨u, hmu, hu₁, hu₂⟩ := h
refine ⟨u, hmu, fun s hs => ?_, hu₂⟩
rw [neg_apply v s, neg_eq_zero]
exact hu₁ s hs
theorem neg_right {N : Type*} [AddCommGroup N] [TopologicalSpace N] [IsTopologicalAddGroup N]
{v : VectorMeasure α M} {w : VectorMeasure α N} (h : v ⟂ᵥ w) : v ⟂ᵥ -w :=
h.symm.neg_left.symm
@[simp]
theorem neg_left_iff {M : Type*} [AddCommGroup M] [TopologicalSpace M] [IsTopologicalAddGroup M]
{v : VectorMeasure α M} {w : VectorMeasure α N} : -v ⟂ᵥ w ↔ v ⟂ᵥ w :=
⟨fun h => neg_neg v ▸ h.neg_left, neg_left⟩
@[simp]
theorem neg_right_iff {N : Type*} [AddCommGroup N] [TopologicalSpace N] [IsTopologicalAddGroup N]
{v : VectorMeasure α M} {w : VectorMeasure α N} : v ⟂ᵥ -w ↔ v ⟂ᵥ w :=
⟨fun h => neg_neg w ▸ h.neg_right, neg_right⟩
end MutuallySingular
section Trim
open Classical in
/-- Restriction of a vector measure onto a sub-σ-algebra. -/
@[simps]
def trim {m n : MeasurableSpace α} (v : VectorMeasure α M) (hle : m ≤ n) :
@VectorMeasure α m M _ _ :=
@VectorMeasure.mk α m M _ _
(fun i => if MeasurableSet[m] i then v i else 0)
(by dsimp only; rw [if_pos (@MeasurableSet.empty _ m), v.empty])
(fun i hi => by dsimp only; rw [if_neg hi])
(fun f hf₁ hf₂ => by
dsimp only
have hf₁' : ∀ k, MeasurableSet[n] (f k) := fun k => hle _ (hf₁ k)
convert v.m_iUnion hf₁' hf₂ using 1
· ext n
rw [if_pos (hf₁ n)]
· rw [if_pos (@MeasurableSet.iUnion _ _ m _ _ hf₁)])
variable {n : MeasurableSpace α} {v : VectorMeasure α M}
theorem trim_eq_self : v.trim le_rfl = v := by
ext i hi
exact if_pos hi
@[simp]
theorem zero_trim (hle : m ≤ n) : (0 : VectorMeasure α M).trim hle = 0 := by
ext i hi
exact if_pos hi
theorem trim_measurableSet_eq (hle : m ≤ n) {i : Set α} (hi : MeasurableSet[m] i) :
v.trim hle i = v i :=
if_pos hi
theorem restrict_trim (hle : m ≤ n) {i : Set α} (hi : MeasurableSet[m] i) :
@VectorMeasure.restrict α m M _ _ (v.trim hle) i = (v.restrict i).trim hle := by
ext j hj
rw [@restrict_apply _ m, trim_measurableSet_eq hle hj, restrict_apply, trim_measurableSet_eq]
all_goals measurability
end Trim
end
end VectorMeasure
namespace SignedMeasure
open VectorMeasure
open MeasureTheory
/-- The underlying function for `SignedMeasure.toMeasureOfZeroLE`. -/
def toMeasureOfZeroLE' (s : SignedMeasure α) (i : Set α) (hi : 0 ≤[i] s) (j : Set α)
(hj : MeasurableSet j) : ℝ≥0∞ :=
((↑) : ℝ≥0 → ℝ≥0∞) ⟨s.restrict i j, le_trans (by simp) (hi j hj)⟩
/-- Given a signed measure `s` and a positive measurable set `i`, `toMeasureOfZeroLE`
provides the measure, mapping measurable sets `j` to `s (i ∩ j)`. -/
def toMeasureOfZeroLE (s : SignedMeasure α) (i : Set α) (hi₁ : MeasurableSet i) (hi₂ : 0 ≤[i] s) :
Measure α := by
refine Measure.ofMeasurable (s.toMeasureOfZeroLE' i hi₂) ?_ ?_
· simp_rw [toMeasureOfZeroLE', s.restrict_apply hi₁ MeasurableSet.empty, Set.empty_inter i,
s.empty]
rfl
· intro f hf₁ hf₂
have h₁ : ∀ n, MeasurableSet (i ∩ f n) := fun n => hi₁.inter (hf₁ n)
have h₂ : Pairwise (Disjoint on fun n : ℕ => i ∩ f n) := by
intro n m hnm
exact ((hf₂ hnm).inf_left' i).inf_right' i
simp only [toMeasureOfZeroLE', s.restrict_apply hi₁ (MeasurableSet.iUnion hf₁), Set.inter_comm,
Set.inter_iUnion, s.of_disjoint_iUnion h₁ h₂]
have h : ∀ n, 0 ≤ s (i ∩ f n) := fun n =>
s.nonneg_of_zero_le_restrict (s.zero_le_restrict_subset hi₁ Set.inter_subset_left hi₂)
rw [NNReal.coe_tsum_of_nonneg h, ENNReal.coe_tsum]
· refine tsum_congr fun n => ?_
simp_rw [s.restrict_apply hi₁ (hf₁ n), Set.inter_comm]
· exact (NNReal.summable_mk h).2 (s.m_iUnion h₁ h₂).summable
variable (s : SignedMeasure α) {i j : Set α}
theorem toMeasureOfZeroLE_apply (hi : 0 ≤[i] s) (hi₁ : MeasurableSet i) (hj₁ : MeasurableSet j) :
s.toMeasureOfZeroLE i hi₁ hi j = ((↑) : ℝ≥0 → ℝ≥0∞) ⟨s (i ∩ j), nonneg_of_zero_le_restrict
s (zero_le_restrict_subset s hi₁ Set.inter_subset_left hi)⟩ := by
simp_rw [toMeasureOfZeroLE, Measure.ofMeasurable_apply _ hj₁, toMeasureOfZeroLE',
s.restrict_apply hi₁ hj₁, Set.inter_comm]
theorem toMeasureOfZeroLE_real_apply (hi : 0 ≤[i] s) (hi₁ : MeasurableSet i)
(hj₁ : MeasurableSet j) :
(s.toMeasureOfZeroLE i hi₁ hi).real j = s (i ∩ j) := by
simp [measureReal_def, toMeasureOfZeroLE_apply, hj₁]
/-- Given a signed measure `s` and a negative measurable set `i`, `toMeasureOfLEZero`
provides the measure, mapping measurable sets `j` to `-s (i ∩ j)`. -/
def toMeasureOfLEZero (s : SignedMeasure α) (i : Set α) (hi₁ : MeasurableSet i) (hi₂ : s ≤[i] 0) :
Measure α :=
toMeasureOfZeroLE (-s) i hi₁ <| @neg_zero (VectorMeasure α ℝ) _ ▸ neg_le_neg _ _ hi₁ hi₂
theorem toMeasureOfLEZero_apply (hi : s ≤[i] 0) (hi₁ : MeasurableSet i) (hj₁ : MeasurableSet j) :
s.toMeasureOfLEZero i hi₁ hi j = ((↑) : ℝ≥0 → ℝ≥0∞) ⟨-s (i ∩ j), neg_apply s (i ∩ j) ▸
nonneg_of_zero_le_restrict _ (zero_le_restrict_subset _ hi₁ Set.inter_subset_left
(@neg_zero (VectorMeasure α ℝ) _ ▸ neg_le_neg _ _ hi₁ hi))⟩ := by
erw [toMeasureOfZeroLE_apply]
· simp
· assumption
theorem toMeasureOfLEZero_real_apply (hi : s ≤[i] 0) (hi₁ : MeasurableSet i)
(hj₁ : MeasurableSet j) :
(s.toMeasureOfLEZero i hi₁ hi).real j = -s (i ∩ j) := by
simp [measureReal_def, toMeasureOfLEZero_apply _ hi hi₁ hj₁]
/-- `SignedMeasure.toMeasureOfZeroLE` is a finite measure. -/
instance toMeasureOfZeroLE_finite (hi : 0 ≤[i] s) (hi₁ : MeasurableSet i) :
IsFiniteMeasure (s.toMeasureOfZeroLE i hi₁ hi) where
measure_univ_lt_top := by
rw [toMeasureOfZeroLE_apply s hi hi₁ MeasurableSet.univ]
exact ENNReal.coe_lt_top
/-- `SignedMeasure.toMeasureOfLEZero` is a finite measure. -/
instance toMeasureOfLEZero_finite (hi : s ≤[i] 0) (hi₁ : MeasurableSet i) :
IsFiniteMeasure (s.toMeasureOfLEZero i hi₁ hi) where
measure_univ_lt_top := by
rw [toMeasureOfLEZero_apply s hi hi₁ MeasurableSet.univ]
exact ENNReal.coe_lt_top
theorem toMeasureOfZeroLE_toSignedMeasure (hs : 0 ≤[Set.univ] s) :
(s.toMeasureOfZeroLE Set.univ MeasurableSet.univ hs).toSignedMeasure = s := by
ext i hi
simp [hi, toMeasureOfZeroLE_apply _ _ _ hi, measureReal_def]
theorem toMeasureOfLEZero_toSignedMeasure (hs : s ≤[Set.univ] 0) :
(s.toMeasureOfLEZero Set.univ MeasurableSet.univ hs).toSignedMeasure = -s := by
ext i hi
simp [hi, toMeasureOfLEZero_apply _ _ _ hi, measureReal_def]
end SignedMeasure
namespace Measure
open VectorMeasure
variable (μ ν : Measure α) [IsFiniteMeasure μ] [IsFiniteMeasure ν] (s : Set α)
theorem zero_le_toSignedMeasure : 0 ≤ μ.toSignedMeasure := by
rw [← le_restrict_univ_iff_le]
refine restrict_le_restrict_of_subset_le _ _ fun j hj₁ _ => ?_
simp only [VectorMeasure.coe_zero, Pi.zero_apply, Measure.toSignedMeasure_apply_measurable hj₁,
measureReal_nonneg]
theorem toSignedMeasure_toMeasureOfZeroLE :
μ.toSignedMeasure.toMeasureOfZeroLE Set.univ MeasurableSet.univ
((le_restrict_univ_iff_le _ _).2 (zero_le_toSignedMeasure μ)) = μ := by
refine Measure.ext fun i hi => ?_
lift μ i to ℝ≥0 using (measure_lt_top _ _).ne with m hm
rw [SignedMeasure.toMeasureOfZeroLE_apply _ _ _ hi, ENNReal.coe_inj]
congr
simp [hi, ← hm, measureReal_def]
theorem toSignedMeasure_restrict_eq_restrict_toSignedMeasure (hs : MeasurableSet s) :
μ.toSignedMeasure.restrict s = (μ.restrict s).toSignedMeasure := by
ext A hA
simp [VectorMeasure.restrict_apply, toSignedMeasure_apply, hA, hs]
theorem toSignedMeasure_le_toSignedMeasure_iff :
μ.toSignedMeasure ≤ ν.toSignedMeasure ↔ μ ≤ ν := by
rw [Measure.le_iff, VectorMeasure.le_iff]
congrm ∀ s, (hs : MeasurableSet s) → ?_
simp_rw [toSignedMeasure_apply_measurable hs, real_def]
apply ENNReal.toReal_le_toReal <;> finiteness
end Measure
end MeasureTheory
|
DepRewrite.lean
|
/-
Copyright (c) 2025 Aaron Liu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Liu, Wojciech Nawrocki
-/
import Lean.Elab.Tactic.Simp
import Lean.Elab.Tactic.Conv.Basic
import Lean.Elab.Tactic.Rewrite
import Mathlib.Init
/-! ## Dependent rewrite tactic -/
namespace Mathlib.Tactic.DepRewrite
open Lean Meta
theorem dcongrArg.{u, v} {α : Sort u} {a a' : α} {β : (a' : α) → a = a' → Sort v}
(h : a = a') (f : (a' : α) → (h : a = a') → β a' h) :
f a rfl = Eq.rec (motive := fun x h' ↦ β x (h.trans h')) (f a' h) h.symm := by
cases h; rfl
theorem nddcongrArg.{u, v} {α : Sort u} {a a' : α} {β : Sort v}
(h : a = a') (f : (a' : α) → (h : a = a') → β) :
f a rfl = f a' h := by
cases h; rfl
theorem heqL.{u} {α β : Sort u} {a : α} {b : β} (h : HEq a b) :
a = cast (type_eq_of_heq h).symm b := by
cases h; rfl
theorem heqR.{u} {α β : Sort u} {a : α} {b : β} (h : HEq a b) :
cast (type_eq_of_heq h) a = b := by
cases h; rfl
private def traceCls : Name := `Tactic.depRewrite
private def traceClsVisit : Name := `Tactic.depRewrite.visit
private def traceClsCast : Name := `Tactic.depRewrite.cast
initialize
registerTraceClass traceCls
registerTraceClass traceClsVisit
registerTraceClass traceClsCast
/-- See `Config.castMode`. -/
inductive CastMode where
/-- Only insert casts on proofs.
In this mode, it is *not* permitted to cast subterms of proofs that are not themselves proofs. -/
-- TODO: should we relax this restriction and switch `castMode` when visiting a proof?
| proofs
/- TODO: `proofs` plus "good" user-defined casts such as `Fin.cast`.
See https://leanprover.zulipchat.com/#narrow/channel/239415-metaprogramming-.2F-tactics/topic/dependent.20rewrite.20tactic/near/497185687 -/
-- | userDef
/-- Insert casts whenever necessary. -/
| all
deriving BEq
instance : ToString CastMode := ⟨fun
| .proofs => "proofs"
| .all => "all"⟩
/-- Embedding of `CastMode` into naturals. -/
def CastMode.toNat : CastMode → Nat
| .proofs => 0
| .all => 1
instance : LE CastMode where
le a b := a.toNat ≤ b.toNat
instance : DecidableLE CastMode :=
fun a b => inferInstanceAs (Decidable (a.toNat ≤ b.toNat))
/-- Configures the behavior of the `rewrite!` and `rw!` tactics. -/
structure Config where
/-- Which transparency level to use when unifying the rewrite rule's LHS
against subterms of the term being rewritten. -/
transparency : TransparencyMode := .reducible
/-- Which occurrences to rewrite. -/
occs : Occurrences := .all
/-- The cast mode specifies when `rw!` is permitted to insert casts
in order to correct subterms that become type-incorect
as a result of rewriting.
For example, given `P : Nat → Prop`, `f : (n : Nat) → P n → Nat` and `h : P n₀`,
rewriting `f n₀ h` by `eq : n₀ = n₁` produces `f n₁ h`,
where `h` does not typecheck at `P n₁`.
The tactic will cast `h` to `eq ▸ h : P n₁` iff `.proofs ≤ castMode`. -/
castMode : CastMode := .proofs
/-- `ReaderT` context for `M`. -/
structure Context where
/-- Configuration. -/
cfg : DepRewrite.Config
/-- The pattern to generalize over. -/
p : Expr
/-- The free variable to substitute for `p`. -/
x : Expr
/-- A proof of `p = x`. Must be an fvar. -/
h : Expr
/-- The list of *value-less* binders (`cdecl`s and nondependent `ldecl`s)
that we have introduced.
Together with each binder, we store its type abstracted over `x` and `h`,
and with all occurrences of previous entries in `Δ`
casted along the abstracting equation.
E.g., if the local context is `a : T, b : U`,
we store `(a, Ma)` where `Ma := fun (x' : α) (h' : x = x') => T[x'/x, h'/h]`
and `(b, fun (x' : α) (h' : x = x') => U[x'/x, h'/h, (Eq.rec (motive := Ma) a h)/a])`
See the docstring on `visitAndCast`. -/
Δ : Array (FVarId × Expr)
/-- The set of all *dependent* `ldecl`s that we have introduced. -/
δ : Std.HashSet FVarId
-- TODO: use `@[computed_field]`s below when `structure` supports that
/-- Cached `p.toHeadIndex`. -/
pHeadIdx : HeadIndex := p.toHeadIndex
/-- Cached `p.toNumArgs`. -/
pNumArgs : Nat := p.headNumArgs
/-- We use a cache entry iff the upcoming traversal would abstract exactly the same occurrences
as the cached traversal. -/
def canUseCache (cacheOcc dCacheOcc currOcc : Nat) : Occurrences → Bool
| .all => true
| .pos l | .neg l => Id.run do
let mut prevOccs := #[]
let mut currOccs := #[]
for p in l.toArray.qsort do
if cacheOcc ≤ p && p < cacheOcc + dCacheOcc then
prevOccs := prevOccs.push (p - cacheOcc)
if currOcc ≤ p && p < currOcc + dCacheOcc then
currOccs := currOccs.push (p - currOcc)
return prevOccs == currOccs
/-- Monad for computing `dabstract`.
The `Nat` state tracks which occurrence of the pattern we are about to see, 1-indexed
(so the initial value is `1`).
The cache stores results of `visit` together with
- the `Nat` state before the cached call; and
- the difference in the state resulting from the call.
We store these because even if the cache hits,
we must update the state as if the call had been made.
Storing the difference suffices because the state increases monotonically.
See also `canUseCache`. -/
abbrev M := ReaderT Context <| MonadCacheT ExprStructEq (Expr × Nat × Nat) <|
StateRefT Nat MetaM
/-- Check that casting `e : t` is allowed in the current mode.
(We don't need to know what type `e` is cast to:
we only check the sort of `t`, and it cannot change.) -/
def checkCastAllowed (e t : Expr) (castMode : CastMode) : MetaM Unit := do
let throwMismatch : Unit → MetaM Unit := fun _ => do
throwError m!"\
Will not cast{indentExpr e}\nin cast mode '{castMode}'. \
If inserting more casts is acceptable, use `rw! (castMode := .all)`."
if castMode == .proofs then
if !(← isProp t) then
throwMismatch ()
/-- In `e`, inline the values of those `ldecl`s that appear in `fvars`. -/
def zetaDelta (e : Expr) (fvars : Std.HashSet FVarId) : MetaM Expr :=
let unfold? (fvarId : FVarId) : MetaM (Option Expr) := do
if fvars.contains fvarId then
fvarId.getValue?
else
return none
let pre (e : Expr) : MetaM TransformStep := do
let .fvar fvarId := e | return .continue
let some val ← unfold? fvarId | return .continue
return .visit val
transform e (pre := pre)
/-- If `e : te` is a term whose type mentions `x`, `h` (the generalization variables)
or entries in `Δ`/`δ`,
return `h.symm ▸ e : te[p/x, rfl/h, …]`.
Otherwise return `none`. -/
def castBack? (e te x h : Expr) (Δ : Array (FVarId × Expr)) (δ : Std.HashSet FVarId) :
MetaM (Option Expr) := do
if !te.hasAnyFVar (fun f => f == x.fvarId! || f == h.fvarId! ||
Δ.any (·.1 == f) || δ.contains f) then
return none
let e' ← mkEqRec (← motive) e (← mkEqSymm h)
trace[Tactic.depRewrite.cast] "casting (x ↦ p):{indentExpr e'}"
return some e'
where
/-- Compute the motive that casts `e` back to `te[p/x, rfl/h, …]`. -/
motive : MetaM Expr := do
withLocalDeclD `x' (← inferType x) fun x' => do
withLocalDeclD `h' (← mkEq x x') fun h' => do
/- The motive computation below operates syntactically, i.e.,
it looks for the fvars `x` and `h`.
This breaks in the presence of `let`-binders:
if we traverse into `b` in `let a := n; b` with `n` as the pattern,
we will have `a := x` in the local context.
If the type-correctness of `b` depends on the defeq `a ≡ n`,
because `b` does not depend on `x` syntactically,
a `replaceFVars` substitution will not suffice to fix `b`.
Thus we unfold the necessary dependent `ldecl`s when computing motives.
If their values depend on `x`,
this will be visible in the syntactic form of `te`. -/
let te ← zetaDelta te δ
let mut fs := #[x, h]
let mut es := #[x', ← mkEqTrans h h']
for (f, M) in Δ do
fs := fs.push (.fvar f)
es := es.push (← mkEqRec M (.fvar f) h')
let te := te.replaceFVars fs es
mkLambdaFVars #[x', h'] te
/-- Cast `e : te[p/x, rfl/h, ...]` to `h ▸ e : te`. -/
def castFwd (e te p x h : Expr) (Δ : Array (FVarId × Expr)) (δ : Std.HashSet FVarId) :
MetaM Expr := do
if !te.hasAnyFVar (fun f => f == x.fvarId! || f == h.fvarId! ||
Δ.any (·.1 == f) || δ.contains f) then
return e
let motive ← do
withLocalDeclD `x' (← inferType x) fun x' => do
withLocalDeclD `h' (← mkEq p x') fun h' => do
let te ← zetaDelta te δ
let mut fs := #[x, h]
let mut es := #[x', h']
for (f, M) in Δ do
fs := fs.push (.fvar f)
es := es.push (← mkEqRec M (.fvar f) (← mkEqTrans (← mkEqSymm h) h'))
let te := te.replaceFVars fs es
mkLambdaFVars #[x', h'] te
let e' ← mkEqRec motive e h
trace[Tactic.depRewrite.cast] "casting (p ↦ x):{indentExpr e'}"
return e'
mutual
/-- Given `e`, return `e'` where `e'` has had
- the occurrences of `p` in `ctx.cfg.occs` replaced by `x`; and
- subterms cast as appropriate in order to make `e'` type-correct.
If `et?` is not `none`, the output is guaranteed to have type (defeq to) `et?`.
We do _not_ assume that `e` is well-typed.
We use this when processing binders:
to traverse `∀ (x : α), β`,
we obtain `α' ← visit α`,
add `x : α'` to the local context
and continue traversing `β`.
Although `x : α' ⊢ β` may not hold,
the output `β'` should have `x : α' ⊢ β'` (otherwise we have a bug).
To achieve this, we maintain the invariant
that all entries in the local context that we have introduced
can be translated back to their original (pre-`visit`) types
using the motive computed by `castBack?.motive`.
(But we have not attempted to prove this.) -/
partial def visitAndCast (e : Expr) (et? : Option Expr) : M Expr := do
let e' ← visit e et?
let some et := et? | return e'
let te' ← inferType e'
-- Increase transparency to avoid inserting unnecessary casts
-- between definientia and definienda (δ reductions).
if ← withAtLeastTransparency .default <| withNewMCtxDepth <| isDefEq te' et then
return e'
trace[Tactic.depRewrite.cast] "casting{indentExpr e'}\nto expected type{indentExpr et}"
let ctx ← read
checkCastAllowed e' te' ctx.cfg.castMode
/- Try casting from the inferred type (x ↦ p),
and to the expected type (p ↦ x).
In certain cases we need to cast in both directions (see `bool_dep_test`). -/
match ← castBack? e' te' ctx.x ctx.h ctx.Δ ctx.δ with
| some e'' =>
let te'' ← inferType e''
if ← withAtLeastTransparency .default <| withNewMCtxDepth <| isDefEq te'' et then
return e''
castFwd e'' et ctx.p ctx.x ctx.h ctx.Δ ctx.δ
| none =>
castFwd e' et ctx.p ctx.x ctx.h ctx.Δ ctx.δ
/-- Like `visitAndCast`, but does not insert casts at the top level.
The expected types of certain subterms are computed from `et?`. -/
partial def visit (e : Expr) (et? : Option Expr) : M Expr :=
withTraceNode traceClsVisit (fun
| .ok e' => pure m!"{e} => {e'} (et: {et?})"
| .error _ => pure m!"{e} => 💥️") <| Meta.withIncRecDepth do
let ctx ← read
if let some (eup, cacheOcc, dCacheOcc) ← MonadCache.findCached? { val := e : ExprStructEq } then
if canUseCache cacheOcc dCacheOcc (← get) ctx.cfg.occs then
modify (· + dCacheOcc)
return eup
let initOccs ← get
let eup ← visitInner e et?
MonadCache.cache { val := e : ExprStructEq } (eup, initOccs, (← get) - initOccs)
return eup
-- TODO(WN): further speedup might come from returning whether anything
-- was rewritten inside a `visit`,
-- and then skipping the type correctness check if it wasn't.
/-- See `visit`. -/
partial def visitInner (e : Expr) (et? : Option Expr) : M Expr := do
let ctx ← read
if e.hasLooseBVars then
throwError "internal error: forgot to instantiate"
if e.toHeadIndex == ctx.pHeadIdx && e.headNumArgs == ctx.pNumArgs then
-- We save the metavariable context here,
-- so that it can be rolled back unless `occs.contains i`.
let mctx ← getMCtx
-- Note that the pattern `ctx.p` is created in the outer lctx,
-- so bvars from the visited term will not be unified into the pattern.
if ← withTransparency ctx.cfg.transparency <| isDefEq e ctx.p then
let i ← modifyGet fun i => (i, i+1)
if ctx.cfg.occs.contains i then
return ctx.x
else
-- Revert the metavariable context,
-- so that other matches are still possible.
setMCtx mctx
match e with
| .mdata d b => return .mdata d (← visitAndCast b et?)
| .app f a =>
let (fup, tr) ← do
let fup ← visit f none
let tfup ← inferType fup
withAtLeastTransparency .default <| forallBoundedTelescope tfup (some 1) fun xs _ => do
match xs with
| #[r] => return (fup, ← inferType r)
| _ =>
-- The term in function position was rewritten to a non-function,
-- so cast it back to one.
let some fup' ← castBack? fup tfup ctx.x ctx.h ctx.Δ ctx.δ
| throwError "internal error: unexpected castBack failure on{indentExpr fup}"
let tfup' ← inferType fup'
withAtLeastTransparency .default <| forallBoundedTelescope tfup' (some 1) fun xs _ => do
let #[r] := xs | throwError "internal error: function expected, got{indentExpr fup'}"
return (fup', ← inferType r)
let aup ← visitAndCast a tr
return .app fup aup
| .proj n i b =>
let bup ← visit b none
let tbup ← inferType bup
if (← withAtLeastTransparency .default <| whnf tbup).isAppOf n then
return .proj n i bup
/- Otherwise the term in structure position was rewritten to have a different type,
so cast it back to the original type.
(While the other type may itself be a structure type,
we can't assume that its projections are the same as those of the original.) -/
let some bup' ← castBack? bup tbup ctx.x ctx.h ctx.Δ ctx.δ
| throwError "internal error: could not cast back in{indentExpr bup}"
return .proj n i bup'
| .letE n t v b nondep =>
let tup ← visit t none
let vup ← visitAndCast v tup
if nondep || !vup.hasAnyFVar (fun f => f == ctx.x.fvarId! || f == ctx.h.fvarId! ||
ctx.Δ.any (·.1 == f) || ctx.δ.contains f) then
return ← withLetDecl n tup vup (nondep := nondep) fun r => do
let motive ← castBack?.motive tup ctx.x ctx.h ctx.Δ ctx.δ
let bup ← withReader (fun ctx => { ctx with Δ := ctx.Δ.push (r.fvarId!, motive) })
(visitAndCast (b.instantiate1 r) et?)
return .letE n tup vup (bup.abstract #[r]) nondep
withLetDecl n tup vup (nondep := nondep) fun r => do
let bup ← withReader (fun ctx => { ctx with δ := ctx.δ.insert r.fvarId! })
(visitAndCast (b.instantiate1 r) et?)
return .letE n tup vup (bup.abstract #[r]) nondep
| .lam n t b bi =>
let tup ← visit t none
withLocalDecl n bi tup fun r => do
-- NOTE(WN): there should be some way to propagate the expected type here,
-- but it is not easy to do correctly (see `lam (as argument)` tests).
let motive ← castBack?.motive tup ctx.x ctx.h ctx.Δ ctx.δ
let bup ← withReader (fun ctx => { ctx with Δ := ctx.Δ.push (r.fvarId!, motive) })
(visit (b.instantiate1 r) none)
return .lam n tup (bup.abstract #[r]) bi
| .forallE n t b bi =>
let tup ← visit t none
withLocalDecl n bi tup fun r => do
let motive ← castBack?.motive tup ctx.x ctx.h ctx.Δ ctx.δ
let bup ← withReader (fun ctx => { ctx with Δ := ctx.Δ.push (r.fvarId!, motive) })
(visit (b.instantiate1 r) none)
return .forallE n tup (bup.abstract #[r]) bi
| _ => return e
end
/-- Analogue of `kabstract` with support for inserting casts. -/
def dabstract (e : Expr) (p : Expr) (cfg : DepRewrite.Config) : MetaM Expr := do
let e ← instantiateMVars e
let tp ← inferType p
withTraceNode traceCls (fun
-- Message shows unified pattern (without mvars) b/c it is constructed after the body runs
| .ok motive => pure m!"{e} =[x/{p}]=> {motive}"
| .error (err : Lean.Exception) => pure m!"{e} =[x/{p}]=> 💥️{indentD err.toMessageData}") do
withLocalDeclD `x tp fun x => do
withLocalDeclD `h (← mkEq p x) fun h => do
let e' ← visit e none |>.run { cfg, p, x, h, Δ := ∅, δ := ∅ } |>.run.run' 1
mkLambdaFVars #[x, h] e'
/-- Analogue of `Lean.MVarId.rewrite` with support for inserting casts. -/
def _root_.Lean.MVarId.depRewrite (mvarId : MVarId) (e : Expr) (heq : Expr)
(symm : Bool := false) (config := { : DepRewrite.Config }) : MetaM RewriteResult :=
mvarId.withContext do
mvarId.checkNotAssigned `depRewrite
let heqIn := heq
let heqType ← instantiateMVars (← inferType heq)
let (newMVars, binderInfos, heqType) ← forallMetaTelescopeReducing heqType
let heq := mkAppN heq newMVars
let cont (heq heqType : Expr) : MetaM RewriteResult := do
match (← matchEq? heqType) with
| none => throwTacticEx `depRewrite mvarId
m!"equality or iff proof expected{indentExpr heqType}"
| some (α, lhs, rhs) =>
let cont (heq lhs rhs : Expr) : MetaM RewriteResult := do
if lhs.getAppFn.isMVar then
throwTacticEx `depRewrite mvarId
m!"pattern is a metavariable{indentExpr lhs}\nfrom equation{indentExpr heqType}"
let e ← instantiateMVars e
let eAbst ← withConfig (fun oldConfig => { config, oldConfig with }) <|
dabstract e lhs config
let .lam _ _ (.lam _ _ eBody _) _ := eAbst |
throwTacticEx `depRewrite mvarId
m!"internal error: output{indentExpr eAbst}\nof dabstract is not a lambda"
if !eBody.hasLooseBVars then
throwTacticEx `depRewrite mvarId
m!"did not find instance of the pattern in the target expression{indentExpr lhs}"
try
check eAbst
catch e : Lean.Exception =>
throwTacticEx `depRewrite mvarId <| m!"\
motive{indentExpr eAbst}\nis not type correct:{indentD e.toMessageData}\n\
unlike with rw/rewrite, this error should NOT happen in rw!/rewrite!: \
please report it on the Lean Zulip"
-- construct rewrite proof
let eType ← inferType e
-- `eNew ≡ eAbst rhs heq`
let eNew := eBody.instantiateRev #[rhs, heq]
-- Has the type of the term that we rewrote changed?
-- (Checking whether the motive depends on `x` is overly conservative:
-- when rewriting by a definitional equality,
-- the motive may use `x` while the type remains the same.)
let isDep ← withNewMCtxDepth <| not <$> (inferType eNew >>= isDefEq eType)
let u1 ← getLevel α
let u2 ← getLevel eType
-- `eqPrf : eAbst lhs rfl = eNew`
-- `eAbst lhs rfl ≡ e`
let (eNew, eqPrf) ← do
if isDep then
lambdaBoundedTelescope eAbst 2 fun xs eBody => do
let #[x, h] := xs | throwError
"internal error: expected 2 arguments in{indentExpr eAbst}"
let eBodyTp ← inferType eBody
checkCastAllowed eBody eBodyTp config.castMode
let some eBody ← castBack? eBody eBodyTp x h ∅ ∅ | throwError
"internal error: body{indentExpr eBody}\nshould mention '{x}' or '{h}'"
let motive ← mkLambdaFVars xs eBodyTp
pure (
eBody.replaceFVars #[x, h] #[rhs, heq],
mkApp6 (.const ``dcongrArg [u1, u2]) α lhs rhs motive heq eAbst)
else
pure (eNew, mkApp6 (.const ``nddcongrArg [u1, u2]) α lhs rhs eType heq eAbst)
postprocessAppMVars `depRewrite mvarId newMVars binderInfos
(synthAssignedInstances := !tactic.skipAssignedInstances.get (← getOptions))
let newMVarIds ← newMVars.map Expr.mvarId! |>.filterM fun mvarId =>
not <$> mvarId.isAssigned
let otherMVarIds ← getMVarsNoDelayed heqIn
let otherMVarIds := otherMVarIds.filter (!newMVarIds.contains ·)
let newMVarIds := newMVarIds ++ otherMVarIds
pure { eNew := eNew, eqProof := eqPrf, mvarIds := newMVarIds.toList }
match symm with
| false => cont heq lhs rhs
| true => do
cont (← mkEqSymm heq) rhs lhs
match heqType.iff? with
| some (lhs, rhs) =>
let heqType ← mkEq lhs rhs
let heq := mkApp3 (mkConst ``propext) lhs rhs heq
cont heq heqType
| none => match heqType.heq? with
| some (α, lhs, β, rhs) =>
let heq ← mkAppOptM (if symm then ``heqR else ``heqL) #[α, β, lhs, rhs, heq]
cont heq (← inferType heq)
| none =>
cont heq heqType
/--
The configuration used by `rw!` to call `dsimp`.
This configuration uses only iota reduction (recursor application) to simplify terms.
-/
private def depRwContext : MetaM Simp.Context :=
Simp.mkContext
{Lean.Meta.Simp.neutralConfig with
etaStruct := .none
iota := true
failIfUnchanged := false}
open Parser Elab Tactic
/--
`rewrite!` is like `rewrite`,
but can also insert casts to adjust types that depend on the LHS of a rewrite.
It is available as an ordinary tactic and a `conv` tactic.
The sort of casts that are inserted is controlled by the `castMode` configuration option.
By default, only proof terms are casted;
by proof irrelevance, this adds no observable complexity.
With `rewrite! +letAbs (castMode := .all)`, casts are inserted whenever necessary.
This means that the 'motive is not type correct' error never occurs,
at the expense of creating potentially complicated terms.
-/
syntax (name := depRewriteSeq) "rewrite!" optConfig rwRuleSeq (location)? : tactic
/--
`rw!` is like `rewrite!`, but also calls `dsimp` to simplify the result after every substitution.
It is available as an ordinary tactic and a `conv` tactic.
-/
syntax (name := depRwSeq) "rw!" optConfig rwRuleSeq (location)? : tactic
/-- Apply `rewrite!` to the goal. -/
def depRewriteTarget (stx : Syntax) (symm : Bool) (config : DepRewrite.Config := {}) :
TacticM Unit := do
Term.withSynthesize <| withMainContext do
let e ← elabTerm stx none true
let r ← (← getMainGoal).depRewrite (← getMainTarget) e symm (config := config)
let mvarId' ← (← getMainGoal).replaceTargetEq r.eNew r.eqProof
replaceMainGoal (mvarId' :: r.mvarIds)
/-- Apply `rewrite!` to a local declaration. -/
def depRewriteLocalDecl (stx : Syntax) (symm : Bool) (fvarId : FVarId)
(config : DepRewrite.Config := {}) : TacticM Unit := withMainContext do
-- Note: we cannot execute `replaceLocalDecl` inside `Term.withSynthesize`.
-- See issues #2711 and #2727.
let rwResult ← Term.withSynthesize <| withMainContext do
let e ← elabTerm stx none true
let localDecl ← fvarId.getDecl
(← getMainGoal).depRewrite localDecl.type e symm (config := config)
let replaceResult ← (← getMainGoal).replaceLocalDecl fvarId rwResult.eNew rwResult.eqProof
replaceMainGoal (replaceResult.mvarId :: rwResult.mvarIds)
/-- Elaborate `DepRewrite.Config`. -/
declare_config_elab elabDepRewriteConfig Config
@[tactic depRewriteSeq, inherit_doc depRewriteSeq]
def evalDepRewriteSeq : Tactic := fun stx => do
let cfg ← elabDepRewriteConfig stx[1]
let loc := expandOptLocation stx[3]
withRWRulesSeq stx[0] stx[2] fun symm term => do
withLocation loc
(depRewriteLocalDecl term symm · cfg)
(depRewriteTarget term symm cfg)
(throwTacticEx `depRewrite · "did not find instance of the pattern in the current goal")
@[tactic depRwSeq, inherit_doc depRwSeq]
def evalDepRwSeq : Tactic := fun stx => do
let cfg ← elabDepRewriteConfig stx[1]
let loc := expandOptLocation stx[3]
withRWRulesSeq stx[0] stx[2] fun symm term => do
withLocation loc
(depRewriteLocalDecl term symm · cfg)
(depRewriteTarget term symm cfg)
(throwTacticEx `depRewrite · "did not find instance of the pattern in the current goal")
-- copied from Lean.Elab.Tactic.evalDSimp
dsimpLocation (← depRwContext) #[] loc
namespace Conv
open Conv
@[inherit_doc depRewriteSeq]
syntax (name := depRewrite) "rewrite!" optConfig rwRuleSeq (location)? : conv
@[inherit_doc depRwSeq]
syntax (name := depRw) "rw!" optConfig rwRuleSeq (location)? : conv
/-- Apply `rewrite!` to the goal. -/
def depRewriteTarget (stx : Syntax) (symm : Bool) (config : DepRewrite.Config := {}) :
TacticM Unit := do
Term.withSynthesize <| withMainContext do
let e ← elabTerm stx none true
let r ← (← getMainGoal).depRewrite (← getLhs) e symm (config := config)
updateLhs r.eNew r.eqProof
replaceMainGoal ((← getMainGoal) :: r.mvarIds)
/-- Apply `rw!` to the goal. -/
def depRwTarget (stx : Syntax) (symm : Bool) (config : DepRewrite.Config := {}) : TacticM Unit := do
Term.withSynthesize <| withMainContext do
let e ← elabTerm stx none true
let r ← (← getMainGoal).depRewrite (← getLhs) e symm (config := config)
updateLhs r.eNew r.eqProof
-- copied from Lean.Elab.Conv.Simp
changeLhs (← dsimp (← getLhs) (← depRwContext)).1
replaceMainGoal ((← getMainGoal) :: r.mvarIds)
/-- Apply `rw!` to a local declaration. -/
def depRwLocalDecl (stx : Syntax) (symm : Bool) (fvarId : FVarId)
(config : DepRewrite.Config := {}) : TacticM Unit := withMainContext do
-- Note: we cannot execute `replaceLocalDecl` inside `Term.withSynthesize`.
-- See issues #2711 and #2727.
let rwResult ← Term.withSynthesize <| withMainContext do
let e ← elabTerm stx none true
let localDecl ← fvarId.getDecl
(← getMainGoal).depRewrite localDecl.type e symm (config := config)
let replaceResult ← (← getMainGoal).replaceLocalDecl fvarId rwResult.eNew rwResult.eqProof
let dsimpResult := (← dsimp rwResult.eNew (← depRwContext)).1
let replaceResult ← replaceResult.mvarId.changeLocalDecl replaceResult.fvarId dsimpResult
replaceMainGoal (replaceResult :: rwResult.mvarIds)
@[tactic depRewrite, inherit_doc depRewriteSeq]
def evalDepRewriteSeq : Tactic := fun stx => do
let cfg ← elabDepRewriteConfig stx[1]
let loc := expandOptLocation stx[3]
withRWRulesSeq stx[0] stx[2] fun symm term => do
withLocation loc
(DepRewrite.depRewriteLocalDecl term symm · cfg)
(depRewriteTarget term symm cfg)
(throwTacticEx `depRewrite · "did not find instance of the pattern in the current goal")
@[tactic depRw, inherit_doc depRwSeq]
def evalDepRwSeq : Tactic := fun stx => do
let cfg ← elabDepRewriteConfig stx[1]
let loc := expandOptLocation stx[3]
withRWRulesSeq stx[0] stx[2] fun symm term => do
withLocation loc
(depRwLocalDecl term symm · cfg)
(depRwTarget term symm cfg)
(throwTacticEx `depRewrite · "did not find instance of the pattern in the current goal")
-- Note: in this version of the tactic, `dsimp` is done inside `withLocation`.
-- This is done so that `dsimp` will not close the goal automatically.
end Conv
end Mathlib.Tactic.DepRewrite
|
Fiber.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.AlgebraicGeometry.PullbackCarrier
import Mathlib.AlgebraicGeometry.Morphisms.Finite
import Mathlib.RingTheory.Spectrum.Prime.Jacobson
/-!
# Scheme-theoretic fiber
## Main result
- `AlgebraicGeometry.Scheme.Hom.fiber`: `f.fiber y` is the scheme theoretic fiber of `f` at `y`.
- `AlgebraicGeometry.Scheme.Hom.fiberHomeo`: `f.fiber y` is homeomorphic to `f ⁻¹' {y}`.
- `AlgebraicGeometry.Scheme.Hom.finite_preimage`: Finite morphisms have finite fibers.
- `AlgebraicGeometry.Scheme.Hom.discrete_fiber`: Finite morphisms have discrete fibers.
-/
universe u
noncomputable section
open CategoryTheory Limits
namespace AlgebraicGeometry
variable {X Y : Scheme.{u}}
/-- `f.fiber y` is the scheme theoretic fiber of `f` at `y`. -/
def Scheme.Hom.fiber (f : X.Hom Y) (y : Y) : Scheme := pullback f (Y.fromSpecResidueField y)
/-- `f.fiberι y : f.fiber y ⟶ X` is the embedding of the scheme theoretic fiber into `X`. -/
def Scheme.Hom.fiberι (f : X.Hom Y) (y : Y) : f.fiber y ⟶ X := pullback.fst _ _
instance (f : X.Hom Y) (y : Y) : (f.fiber y).CanonicallyOver X where hom := f.fiberι y
/-- The canonical map from the scheme theoretic fiber to the residue field. -/
def Scheme.Hom.fiberToSpecResidueField (f : X.Hom Y) (y : Y) :
f.fiber y ⟶ Spec (Y.residueField y) :=
pullback.snd _ _
/-- The fiber of `f` at `y` is naturally a `κ(y)`-scheme. -/
@[reducible] def Scheme.Hom.fiberOverSpecResidueField
(f : X.Hom Y) (y : Y) : (f.fiber y).Over (Spec (Y.residueField y)) where
hom := f.fiberToSpecResidueField y
lemma Scheme.Hom.fiberToSpecResidueField_apply (f : X.Hom Y) (y : Y) (x : f.fiber y) :
(f.fiberToSpecResidueField y).base x = IsLocalRing.closedPoint (Y.residueField y) :=
Subsingleton.elim (α := PrimeSpectrum _) _ _
lemma Scheme.Hom.range_fiberι (f : X.Hom Y) (y : Y) :
Set.range (f.fiberι y).base = f.base ⁻¹' {y} := by
simp [fiber, fiberι, Scheme.Pullback.range_fst, Scheme.range_fromSpecResidueField]
instance (f : X ⟶ Y) (y : Y) : IsPreimmersion (f.fiberι y) :=
MorphismProperty.pullback_fst _ _ inferInstance
/-- The scheme theoretic fiber of `f` at `y` is homeomorphic to `f ⁻¹' {y}`. -/
def Scheme.Hom.fiberHomeo (f : X.Hom Y) (y : Y) : f.fiber y ≃ₜ f.base ⁻¹' {y} :=
.trans (f.fiberι y).isEmbedding.toHomeomorph (.setCongr (f.range_fiberι y))
@[simp]
lemma Scheme.Hom.fiberHomeo_apply (f : X.Hom Y) (y : Y) (x : f.fiber y) :
(f.fiberHomeo y x).1 = (f.fiberι y).base x := rfl
@[simp]
lemma Scheme.Hom.fiberι_fiberHomeo_symm (f : X.Hom Y) (y : Y) (x : f.base ⁻¹' {y}) :
(f.fiberι y).base ((f.fiberHomeo y).symm x) = x :=
congr($((f.fiberHomeo y).apply_symm_apply x).1)
/-- A point `x` as a point in the fiber of `f` at `f x`. -/
def Scheme.Hom.asFiber (f : X.Hom Y) (x : X) : f.fiber (f.base x) :=
(f.fiberHomeo (f.base x)).symm ⟨x, rfl⟩
@[simp]
lemma Scheme.Hom.fiberι_asFiber (f : X.Hom Y) (x : X) : (f.fiberι _).base (f.asFiber x) = x :=
f.fiberι_fiberHomeo_symm _ _
instance (f : X ⟶ Y) [QuasiCompact f] (y : Y) : CompactSpace (f.fiber y) :=
haveI : QuasiCompact (f.fiberToSpecResidueField y) :=
MorphismProperty.pullback_snd _ _ inferInstance
HasAffineProperty.iff_of_isAffine (P := @QuasiCompact)
(f := f.fiberToSpecResidueField y).mp inferInstance
lemma QuasiCompact.isCompact_preimage_singleton (f : X ⟶ Y) [QuasiCompact f] (y : Y) :
IsCompact (f.base ⁻¹' {y}) :=
f.range_fiberι y ▸ isCompact_range (f.fiberι y).continuous
instance (f : X ⟶ Y) [IsAffineHom f] (y : Y) : IsAffine (f.fiber y) :=
haveI : IsAffineHom (f.fiberToSpecResidueField y) :=
MorphismProperty.pullback_snd _ _ inferInstance
isAffine_of_isAffineHom (f.fiberToSpecResidueField y)
instance (f : X ⟶ Y) (y : Y) [LocallyOfFiniteType f] : JacobsonSpace (f.fiber y) :=
have : LocallyOfFiniteType (f.fiberToSpecResidueField y) :=
MorphismProperty.pullback_snd _ _ inferInstance
LocallyOfFiniteType.jacobsonSpace (f.fiberToSpecResidueField y)
instance (f : X ⟶ Y) (y : Y) [IsFinite f] : Finite (f.fiber y) := by
have H : IsFinite (f.fiberToSpecResidueField y) := MorphismProperty.pullback_snd _ _ inferInstance
have : IsArtinianRing Γ(f.fiber y, ⊤) :=
@IsArtinianRing.of_finite (Y.residueField y) Γ(f.fiber y, ⊤) _ _ (show _ from _) _ _
((HasAffineProperty.iff_of_isAffine.mp H).2.comp (.of_surjective _ (Scheme.ΓSpecIso
(Y.residueField y)).commRingCatIsoToRingEquiv.symm.surjective))
exact .of_injective (β := PrimeSpectrum _) _ (f.fiber y).isoSpec.hom.homeomorph.injective
lemma IsFinite.finite_preimage_singleton (f : X ⟶ Y) [IsFinite f] (y : Y) :
(f.base ⁻¹' {y}).Finite :=
f.range_fiberι y ▸ Set.finite_range (f.fiberι y).base
lemma Scheme.Hom.finite_preimage (f : X.Hom Y) [IsFinite f] {s : Set Y} (hs : s.Finite) :
(f.base ⁻¹' s).Finite := by
rw [← Set.biUnion_of_singleton s, Set.preimage_iUnion₂]
exact hs.biUnion fun _ _ ↦ IsFinite.finite_preimage_singleton f _
instance Scheme.Hom.discrete_fiber (f : X ⟶ Y) (y : Y) [IsFinite f] :
DiscreteTopology (f.fiber y) := inferInstance
end AlgebraicGeometry
|
Basic.lean
|
/-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import Mathlib.Algebra.Polynomial.Module.AEval
/-!
# Polynomial module
In this file, we define the polynomial module for an `R`-module `M`, i.e. the `R[X]`-module `M[X]`.
This is defined as a type alias `PolynomialModule R M := ℕ →₀ M`, since there might be different
module structures on `ℕ →₀ M` of interest. See the docstring of `PolynomialModule` for details.
-/
universe u v
open Polynomial
/-- The `R[X]`-module `M[X]` for an `R`-module `M`.
This is isomorphic (as an `R`-module) to `M[X]` when `M` is a ring.
We require all the module instances `Module S (PolynomialModule R M)` to factor through `R` except
`Module R[X] (PolynomialModule R M)`.
In this constraint, we have the following instances for example :
- `R` acts on `PolynomialModule R R[X]`
- `R[X]` acts on `PolynomialModule R R[X]` as `R[Y]` acting on `R[X][Y]`
- `R` acts on `PolynomialModule R[X] R[X]`
- `R[X]` acts on `PolynomialModule R[X] R[X]` as `R[X]` acting on `R[X][Y]`
- `R[X][X]` acts on `PolynomialModule R[X] R[X]` as `R[X][Y]` acting on itself
This is also the reason why `R` is included in the alias, or else there will be two different
instances of `Module R[X] (PolynomialModule R[X])`.
See https://leanprover.zulipchat.com/#narrow/stream/144837-PR-reviews/topic/.2315065.20polynomial.20modules
for the full discussion.
-/
@[nolint unusedArguments]
def PolynomialModule (R M : Type*) [CommRing R] [AddCommGroup M] [Module R M] := ℕ →₀ M
deriving Inhabited, FunLike, CoeFun
noncomputable section
deriving instance AddCommGroup for PolynomialModule
end
variable (R : Type*) {M : Type*} [CommRing R] [AddCommGroup M] [Module R M] (I : Ideal R)
variable {S : Type*} [CommSemiring S] [Algebra S R] [Module S M] [IsScalarTower S R M]
namespace PolynomialModule
/-- This is required to have the `IsScalarTower S R M` instance to avoid diamonds. -/
@[nolint unusedArguments]
noncomputable instance : Module S (PolynomialModule R M) :=
Finsupp.module ℕ M
theorem zero_apply (i : ℕ) : (0 : PolynomialModule R M) i = 0 :=
Finsupp.zero_apply
theorem add_apply (g₁ g₂ : PolynomialModule R M) (a : ℕ) : (g₁ + g₂) a = g₁ a + g₂ a :=
Finsupp.add_apply g₁ g₂ a
/-- The monomial `m * x ^ i`. This is defeq to `Finsupp.singleAddHom`, and is redefined here
so that it has the desired type signature. -/
noncomputable def single (i : ℕ) : M →+ PolynomialModule R M :=
Finsupp.singleAddHom i
theorem single_apply (i : ℕ) (m : M) (n : ℕ) : single R i m n = ite (i = n) m 0 :=
Finsupp.single_apply
/-- `PolynomialModule.single` as a linear map. -/
noncomputable def lsingle (i : ℕ) : M →ₗ[R] PolynomialModule R M :=
Finsupp.lsingle i
theorem lsingle_apply (i : ℕ) (m : M) (n : ℕ) : lsingle R i m n = ite (i = n) m 0 :=
Finsupp.single_apply
theorem single_smul (i : ℕ) (r : R) (m : M) : single R i (r • m) = r • single R i m :=
(lsingle R i).map_smul r m
variable {R}
@[elab_as_elim]
theorem induction_linear {motive : PolynomialModule R M → Prop} (f : PolynomialModule R M)
(zero : motive 0) (add : ∀ f g, motive f → motive g → motive (f + g))
(single : ∀ a b, motive (single R a b)) : motive f :=
Finsupp.induction_linear f zero add single
noncomputable instance polynomialModule : Module R[X] (PolynomialModule R M) :=
inferInstanceAs (Module R[X] (Module.AEval' (Finsupp.lmapDomain M R Nat.succ)))
lemma smul_def (f : R[X]) (m : PolynomialModule R M) :
f • m = aeval (Finsupp.lmapDomain M R Nat.succ) f m := by
rfl
instance (M : Type u) [AddCommGroup M] [Module R M] [Module S M] [IsScalarTower S R M] :
IsScalarTower S R (PolynomialModule R M) :=
Finsupp.isScalarTower _ _
instance isScalarTower' (M : Type u) [AddCommGroup M] [Module R M] [Module S M]
[IsScalarTower S R M] : IsScalarTower S R[X] (PolynomialModule R M) := by
haveI : IsScalarTower R R[X] (PolynomialModule R M) :=
inferInstanceAs <| IsScalarTower R R[X] <| Module.AEval' <| Finsupp.lmapDomain M R Nat.succ
constructor
intro x y z
rw [← @IsScalarTower.algebraMap_smul S R, ← @IsScalarTower.algebraMap_smul S R, smul_assoc]
@[simp]
theorem monomial_smul_single (i : ℕ) (r : R) (j : ℕ) (m : M) :
monomial i r • single R j m = single R (i + j) (r • m) := by
simp only [Module.End.mul_apply, Polynomial.aeval_monomial, Module.End.pow_apply,
Module.algebraMap_end_apply, smul_def]
induction i generalizing r j m with
| zero =>
rw [Function.iterate_zero, zero_add]
exact Finsupp.smul_single r j m
| succ n hn =>
rw [Function.iterate_succ, Function.comp_apply, add_assoc, ← hn]
congr 2
rw [Nat.one_add]
exact Finsupp.mapDomain_single
@[simp]
theorem monomial_smul_apply (i : ℕ) (r : R) (g : PolynomialModule R M) (n : ℕ) :
(monomial i r • g) n = ite (i ≤ n) (r • g (n - i)) 0 := by
induction' g using PolynomialModule.induction_linear with p q hp hq
· simp only [smul_zero, zero_apply, ite_self]
· simp only [smul_add, add_apply, hp, hq]
split_ifs
exacts [rfl, zero_add 0]
· rw [monomial_smul_single, single_apply, single_apply, smul_ite, smul_zero, ← ite_and]
grind
@[simp]
theorem smul_single_apply (i : ℕ) (f : R[X]) (m : M) (n : ℕ) :
(f • single R i m) n = ite (i ≤ n) (f.coeff (n - i) • m) 0 := by
induction' f using Polynomial.induction_on' with p q hp hq
· rw [add_smul, Finsupp.add_apply, hp, hq, coeff_add, add_smul]
split_ifs
exacts [rfl, zero_add 0]
· grind [monomial_smul_single, single_apply, coeff_monomial, zero_smul]
theorem smul_apply (f : R[X]) (g : PolynomialModule R M) (n : ℕ) :
(f • g) n = ∑ x ∈ Finset.antidiagonal n, f.coeff x.1 • g x.2 := by
induction f using Polynomial.induction_on' with
| add p q hp hq =>
rw [add_smul, Finsupp.add_apply, hp, hq, ← Finset.sum_add_distrib]
congr
ext
rw [coeff_add, add_smul]
| monomial f_n f_a =>
rw [Finset.Nat.sum_antidiagonal_eq_sum_range_succ fun i j => (monomial f_n f_a).coeff i • g j,
monomial_smul_apply]
simp_rw [Polynomial.coeff_monomial, ← Finset.mem_range_succ_iff]
simp
/-- `PolynomialModule R R` is isomorphic to `R[X]` as an `R[X]` module. -/
noncomputable def equivPolynomialSelf : PolynomialModule R R ≃ₗ[R[X]] R[X] :=
{ (Polynomial.toFinsuppIso R).symm with
map_smul' := fun r x => by
dsimp
rw [← RingEquiv.coe_toEquiv_symm, RingEquiv.coe_toEquiv]
induction x using induction_linear with
| zero => rw [smul_zero, map_zero, mul_zero]
| add _ _ hp hq => rw [smul_add, map_add, map_add, mul_add, hp, hq]
| single n a =>
ext i
simp only [coeff_ofFinsupp, smul_single_apply, toFinsuppIso_symm_apply, coeff_ofFinsupp,
single_apply, smul_eq_mul, Polynomial.coeff_mul, mul_ite, mul_zero]
split_ifs with hn
· rw [Finset.sum_eq_single (i - n, n)]
· simp only [ite_true]
· rintro ⟨p, q⟩ hpq1 hpq2
rw [Finset.mem_antidiagonal] at hpq1
split_ifs with H
· dsimp at H
exfalso
apply hpq2
rw [← hpq1, H]
simp only [add_tsub_cancel_right]
· rfl
· intro H
exfalso
apply H
rw [Finset.mem_antidiagonal, tsub_add_cancel_of_le hn]
· symm
rw [Finset.sum_ite_of_false, Finset.sum_const_zero]
grind [Finset.mem_antidiagonal] }
/-- `PolynomialModule R S` is isomorphic to `S[X]` as an `R` module. -/
noncomputable def equivPolynomial {S : Type*} [CommRing S] [Algebra R S] :
PolynomialModule R S ≃ₗ[R] S[X] :=
{ (Polynomial.toFinsuppIso S).symm with map_smul' := fun _ _ => rfl }
@[simp]
lemma equivPolynomialSelf_apply_eq (p : PolynomialModule R R) :
equivPolynomialSelf p = equivPolynomial p := rfl
@[simp]
lemma equivPolynomial_single {S : Type*} [CommRing S] [Algebra R S] (n : ℕ) (x : S) :
equivPolynomial (single R n x) = monomial n x := rfl
variable (R' : Type*) {M' : Type*} [CommRing R'] [AddCommGroup M'] [Module R' M']
variable [Module R M']
/-- The image of a polynomial under a linear map. -/
noncomputable def map (f : M →ₗ[R] M') : PolynomialModule R M →ₗ[R] PolynomialModule R' M' :=
Finsupp.mapRange.linearMap f
@[simp]
theorem map_single (f : M →ₗ[R] M') (i : ℕ) (m : M) : map R' f (single R i m) = single R' i (f m) :=
Finsupp.mapRange_single (hf := f.map_zero)
variable [Algebra R R'] [IsScalarTower R R' M']
theorem map_smul (f : M →ₗ[R] M') (p : R[X]) (q : PolynomialModule R M) :
map R' f (p • q) = p.map (algebraMap R R') • map R' f q := by
induction q using induction_linear with
| zero => rw [smul_zero, map_zero, smul_zero]
| add f g e₁ e₂ => rw [smul_add, map_add, e₁, e₂, map_add, smul_add]
| single i m =>
induction p using Polynomial.induction_on' with
| add _ _ e₁ e₂ => rw [add_smul, map_add, e₁, e₂, Polynomial.map_add, add_smul]
| monomial => rw [monomial_smul_single, map_single, Polynomial.map_monomial, map_single,
monomial_smul_single, f.map_smul, algebraMap_smul]
/-- Evaluate a polynomial `p : PolynomialModule R M` at `r : R`. -/
@[simps! -isSimp]
noncomputable def eval (r : R) : PolynomialModule R M →ₗ[R] M where
toFun p := p.sum fun i m => r ^ i • m
map_add' _ _ := Finsupp.sum_add_index' (fun _ => smul_zero _) fun _ _ _ => smul_add _ _ _
map_smul' s m := by
refine (Finsupp.sum_smul_index' ?_).trans ?_
· exact fun i => smul_zero _
· simp_rw [RingHom.id_apply, Finsupp.smul_sum]
congr
ext i c
rw [smul_comm]
@[simp]
theorem eval_single (r : R) (i : ℕ) (m : M) : eval r (single R i m) = r ^ i • m :=
Finsupp.sum_single_index (smul_zero _)
@[simp]
theorem eval_lsingle (r : R) (i : ℕ) (m : M) : eval r (lsingle R i m) = r ^ i • m :=
eval_single r i m
theorem eval_smul (p : R[X]) (q : PolynomialModule R M) (r : R) :
eval r (p • q) = p.eval r • eval r q := by
induction q using induction_linear with
| zero => rw [smul_zero, map_zero, smul_zero]
| add f g e₁ e₂ => rw [smul_add, map_add, e₁, e₂, map_add, smul_add]
| single i m =>
induction p using Polynomial.induction_on' with
| add _ _ e₁ e₂ => rw [add_smul, map_add, Polynomial.eval_add, e₁, e₂, add_smul]
| monomial => simp only [monomial_smul_single, Polynomial.eval_monomial, eval_single]; module
@[simp]
theorem eval_map (f : M →ₗ[R] M') (q : PolynomialModule R M) (r : R) :
eval (algebraMap R R' r) (map R' f q) = f (eval r q) := by
induction q using induction_linear with
| zero => simp_rw [map_zero]
| add f g e₁ e₂ => simp_rw [map_add, e₁, e₂]
| single i m => simp only [map_single, eval_single, f.map_smul]; module
@[simp]
theorem eval_map' (f : M →ₗ[R] M) (q : PolynomialModule R M) (r : R) :
eval r (map R f q) = f (eval r q) :=
eval_map R f q r
@[simp]
lemma aeval_equivPolynomial {S : Type*} [CommRing S] [Algebra S R]
(f : PolynomialModule S S) (x : R) :
aeval x (equivPolynomial f) = eval x (map R (Algebra.linearMap S R) f) := by
induction f using induction_linear with
| zero => simp
| add f g e₁ e₂ => simp_rw [map_add, e₁, e₂]
| single i m => rw [equivPolynomial_single, aeval_monomial, mul_comm, map_single,
Algebra.linearMap_apply, eval_single, smul_eq_mul]
/-- `comp p q` is the composition of `p : R[X]` and `q : M[X]` as `q(p(x))`. -/
@[simps!]
noncomputable def comp (p : R[X]) : PolynomialModule R M →ₗ[R] PolynomialModule R M :=
LinearMap.comp ((eval p).restrictScalars R) (map R[X] (lsingle R 0))
theorem comp_single (p : R[X]) (i : ℕ) (m : M) : comp p (single R i m) = p ^ i • single R 0 m := by
rw [comp_apply, map_single, eval_single]
rfl
theorem comp_eval (p : R[X]) (q : PolynomialModule R M) (r : R) :
eval r (comp p q) = eval (p.eval r) q := by
rw [← LinearMap.comp_apply]
induction q using induction_linear with
| zero => simp_rw [map_zero]
| add _ _ e₁ e₂ => simp_rw [map_add, e₁, e₂]
| single i m =>
rw [LinearMap.comp_apply, comp_single, eval_single, eval_smul, eval_single, eval_pow]
module
theorem comp_smul (p p' : R[X]) (q : PolynomialModule R M) :
comp p (p' • q) = p'.comp p • comp p q := by
rw [comp_apply, map_smul, eval_smul, Polynomial.comp, Polynomial.eval_map, comp_apply]
rfl
end PolynomialModule
|
TuranDensity.lean
|
/-
Copyright (c) 2025 Mitchell Horner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mitchell Horner
-/
import Mathlib.Analysis.Asymptotics.AsymptoticEquivalent
import Mathlib.Combinatorics.Enumerative.DoubleCounting
import Mathlib.Combinatorics.SimpleGraph.DeleteEdges
import Mathlib.Combinatorics.SimpleGraph.Extremal.Basic
import Mathlib.Data.Nat.Choose.Cast
/-!
# Turán density
This files defines the **Turán density** of a simple graph.
## Main definitions
* `SimpleGraph.turanDensity H` is the **Turán density** of the simple graph `H`, defined as the
limit of `extremalNumber n H / n.choose 2` as `n` approaches `∞`.
* `SimpleGraph.tendsto_turanDensity` is the proof that `SimpleGraph.turanDensity` is well-defined.
* `SimpleGraph.isEquivalent_extremalNumber` is the proof that `extremalNumber n H` is
asymptotically equivalent to `turanDensity H * n.choose 2` as `n` approaches `∞`.
-/
open Asymptotics Filter Finset Fintype Topology
namespace SimpleGraph
variable {V W : Type*} {G : SimpleGraph V} {H : SimpleGraph W}
lemma antitoneOn_extremalNumber_div_choose_two (H : SimpleGraph W) :
AntitoneOn (fun n ↦ (extremalNumber n H / n.choose 2 : ℝ)) (Set.Ici 2) := by
apply antitoneOn_nat_Ici_of_succ_le
intro n hn
conv_lhs =>
enter [1, 1]
rw [← Fintype.card_fin (n+1)]
rw [div_le_iff₀ (mod_cast Nat.choose_pos (by linarith)),
extremalNumber_le_iff_of_nonneg H (by positivity)]
intro G _ h
rw [mul_comm, ← mul_div_assoc, le_div_iff₀' (mod_cast Nat.choose_pos hn), Nat.cast_choose_two,
Nat.cast_choose_two, Nat.cast_add_one, add_sub_cancel_right (n : ℝ) 1,
mul_comm _ (n-1 : ℝ), ← mul_div (n-1 : ℝ), mul_comm _ (n/2 : ℝ), mul_assoc, mul_comm (n-1 : ℝ),
← mul_div (n+1 : ℝ), mul_comm _ (n/2 : ℝ), mul_assoc, mul_le_mul_left (by positivity),
← Nat.cast_pred (by positivity), ←Nat.cast_mul, ←Nat.cast_add_one, ←Nat.cast_mul, Nat.cast_le]
conv_rhs =>
rw [← Fintype.card_fin (n+1), ← card_univ]
-- double counting `(v, e) ↦ v ∉ e`
apply card_nsmul_le_card_nsmul' (r := fun v e ↦ v ∉ e)
-- counting `e`
· intro e he
simp_rw [← Sym2.mem_toFinset, bipartiteBelow, filter_not, filter_mem_eq_inter, univ_inter,
← compl_eq_univ_sdiff, card_compl, Fintype.card_fin, card_toFinset_mem_edgeFinset ⟨e, he⟩,
Nat.cast_id, Nat.reduceSubDiff, le_refl]
-- counting `v`
· intro v hv
simpa [edgeFinset_deleteIncidenceSet_eq_filter]
using card_edgeFinset_deleteIncidenceSet_le_extremalNumber h v
/-- The **Turán density** of a simple graph `H` is the limit of `extremalNumber n H / n.choose 2`
as `n` approaches `∞`.
See `SimpleGraph.tendsto_turanDensity` for proof of existence. -/
noncomputable def turanDensity (H : SimpleGraph W) :=
limUnder atTop fun n ↦ (extremalNumber n H / n.choose 2 : ℝ)
/-- The **Turán density** of a simple graph `H` is well-defined. -/
theorem tendsto_turanDensity (H : SimpleGraph W) :
Tendsto (fun n ↦ (extremalNumber n H / n.choose 2 : ℝ)) atTop (𝓝 (turanDensity H)) := by
let f := fun n ↦ (extremalNumber n H / n.choose 2 : ℝ)
suffices h : ∃ x, Tendsto (fun n ↦ f (n + 2)) atTop (𝓝 x) by
obtain ⟨_, h⟩ := by simpa [tendsto_add_atTop_iff_nat 2] using h
simpa [← Tendsto.limUnder_eq h] using h
use ⨅ n, f (n + 2)
apply tendsto_atTop_ciInf
· rw [antitone_add_nat_iff_antitoneOn_nat_Ici]
exact antitoneOn_extremalNumber_div_choose_two H
· use 0
intro n ⟨_, hn⟩
rw [← hn]
positivity
/-- `extremalNumber n H` is asymptotically equivalent to `turanDensity H * n.choose 2` as `n`
approaches `∞`. -/
theorem isEquivalent_extremalNumber (h : turanDensity H ≠ 0) :
(fun n ↦ (extremalNumber n H : ℝ)) ~[atTop] (fun n ↦ (turanDensity H * n.choose 2 : ℝ)) := by
have hπ := tendsto_turanDensity H
apply Tendsto.const_mul (1/turanDensity H : ℝ) at hπ
simp_rw [one_div_mul_cancel h, div_mul_div_comm, one_mul] at hπ
have hz : ∀ᶠ (x : ℕ) in atTop, turanDensity H * x.choose 2 ≠ 0 := by
rw [eventually_atTop]
use 2
intro n hn
simp [h, Nat.choose_eq_zero_iff, hn]
simpa [isEquivalent_iff_tendsto_one hz] using hπ
end SimpleGraph
|
frobenius.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div.
From mathcomp Require Import fintype bigop prime finset fingroup morphism.
From mathcomp Require Import perm action quotient gproduct cyclic center.
From mathcomp Require Import pgroup nilpotent sylow hall abelian.
(******************************************************************************)
(* Definition of Frobenius groups, some basic results, and the Frobenius *)
(* theorem on the number of solutions of x ^+ n = 1. *)
(* semiregular K H <-> *)
(* the internal action of H on K is semiregular, i.e., no nontrivial *)
(* elements of H and K commute; note that this is actually a symmetric *)
(* condition. *)
(* semiprime K H <-> *)
(* the internal action of H on K is "prime", i.e., an element of K that *)
(* centralises a nontrivial element of H must centralise all of H. *)
(* normedTI A G L <=> *)
(* A is nonempty, strictly disjoint from its conjugates in G, and has *)
(* normaliser L in G. *)
(* [Frobenius G = K ><| H] <=> *)
(* G is (isomorphic to) a Frobenius group with kernel K and complement *)
(* H. This is an effective predicate (in bool), which tests the *)
(* equality with the semidirect product, and then the fact that H is a *)
(* proper self-normalizing TI-subgroup of G. *)
(* [Frobenius G with kernel H] <=> *)
(* G is (isomorphic to) a Frobenius group with kernel K; same as above, *)
(* but without the semi-direct product. *)
(* [Frobenius G with complement H] <=> *)
(* G is (isomorphic to) a Frobenius group with complement H; same as *)
(* above, but without the semi-direct product. The proof that this form *)
(* is equivalent to the above (i.e., the existence of Frobenius *)
(* kernels) requires character theory and will only be proved in the *)
(* vcharacter.v file. *)
(* [Frobenius G] <=> G is a Frobenius group. *)
(* Frobenius_action G H S to <-> *)
(* The action to of G on S defines an isomorphism of G with a *)
(* (permutation) Frobenius group, i.e., to is faithful and transitive *)
(* on S, no nontrivial element of G fixes more than one point in S, and *)
(* H is the stabilizer of some element of S, and non-trivial. Thus, *)
(* Frobenius_action G H S 'P *)
(* asserts that G is a Frobenius group in the classic sense. *)
(* has_Frobenius_action G H <-> *)
(* Frobenius_action G H S to holds for some sT : finType, S : {set st} *)
(* and to : {action gT &-> sT}. This is a predicate in Prop, but is *)
(* exactly reflected by [Frobenius G with complement H] : bool. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Import GroupScope.
Section Definitions.
Variable gT : finGroupType.
Implicit Types A G K H L : {set gT}.
(* Corresponds to "H acts on K in a regular manner" in B & G. *)
Definition semiregular K H := {in H^#, forall x, 'C_K[x] = 1}.
(* Corresponds to "H acts on K in a prime manner" in B & G. *)
Definition semiprime K H := {in H^#, forall x, 'C_K[x] = 'C_K(H)}.
Definition normedTI A G L := [&& A != set0, trivIset (A :^: G) & 'N_G(A) == L].
Definition Frobenius_group_with_complement G H := (H != G) && normedTI H^# G H.
Definition Frobenius_group G :=
[exists H : {group gT}, Frobenius_group_with_complement G H].
Definition Frobenius_group_with_kernel_and_complement G K H :=
(K ><| H == G) && Frobenius_group_with_complement G H.
Definition Frobenius_group_with_kernel G K :=
[exists H : {group gT}, Frobenius_group_with_kernel_and_complement G K H].
Section FrobeniusAction.
Variables G H : {set gT}.
Variables (sT : finType) (S : {set sT}) (to : {action gT &-> sT}).
Definition Frobenius_action :=
[/\ [faithful G, on S | to],
[transitive G, on S | to],
{in G^#, forall x, #|'Fix_(S | to)[x]| <= 1},
H != 1
& exists2 u, u \in S & H = 'C_G[u | to]].
End FrobeniusAction.
Variant has_Frobenius_action G H : Prop :=
hasFrobeniusAction sT S to of @Frobenius_action G H sT S to.
End Definitions.
Arguments semiregular {gT} K%_g H%_g.
Arguments semiprime {gT} K%_g H%_g.
Arguments normedTI {gT} A%_g G%_g L%_g.
Arguments Frobenius_group_with_complement {gT} G%_g H%_g.
Arguments Frobenius_group {gT} G%_g.
Arguments Frobenius_group_with_kernel {gT} G%_g K%_g.
Arguments Frobenius_group_with_kernel_and_complement {gT} G%_g K%_g H%_g.
Arguments Frobenius_action {gT} G%_g H%_g {sT} S%_g to%_act.
Arguments has_Frobenius_action {gT} G%_g H%_g.
Notation "[ 'Frobenius' G 'with' 'complement' H ]" :=
(Frobenius_group_with_complement G H)
(G at level 50,
format "[ 'Frobenius' G 'with' 'complement' H ]") : group_scope.
Notation "[ 'Frobenius' G 'with' 'kernel' K ]" :=
(Frobenius_group_with_kernel G K)
(format "[ 'Frobenius' G 'with' 'kernel' K ]") : group_scope.
Notation "[ 'Frobenius' G ]" := (Frobenius_group G)
(format "[ 'Frobenius' G ]") : group_scope.
Notation "[ 'Frobenius' G = K ><| H ]" :=
(Frobenius_group_with_kernel_and_complement G K H)
(K, H at level 35,
format "[ 'Frobenius' G = K ><| H ]") : group_scope.
Section FrobeniusBasics.
Variable gT : finGroupType.
Implicit Types (A B : {set gT}) (G H K L R X : {group gT}).
Lemma semiregular1l H : semiregular 1 H.
Proof. by move=> x _ /=; rewrite setI1g. Qed.
Lemma semiregular1r K : semiregular K 1.
Proof. by move=> x; rewrite setDv inE. Qed.
Lemma semiregular_sym H K : semiregular K H -> semiregular H K.
Proof.
move=> regH x /setD1P[ntx Kx]; apply: contraNeq ntx.
rewrite -subG1 -setD_eq0 -setIDAC => /set0Pn[y /setIP[Hy cxy]].
by rewrite (sameP eqP set1gP) -(regH y Hy) inE Kx cent1C.
Qed.
Lemma semiregularS K1 K2 A1 A2 :
K1 \subset K2 -> A1 \subset A2 -> semiregular K2 A2 -> semiregular K1 A1.
Proof.
move=> sK12 sA12 regKA2 x /setD1P[ntx /(subsetP sA12)A2x].
by apply/trivgP; rewrite -(regKA2 x) ?inE ?ntx ?setSI.
Qed.
Lemma semiregular_prime H K : semiregular K H -> semiprime K H.
Proof.
move=> regH x Hx; apply/eqP; rewrite eqEsubset {1}regH // sub1G.
by rewrite -cent_set1 setIS ?centS // sub1set; case/setD1P: Hx.
Qed.
Lemma semiprime_regular H K : semiprime K H -> 'C_K(H) = 1 -> semiregular K H.
Proof. by move=> prKH tiKcH x Hx; rewrite prKH. Qed.
Lemma semiprimeS K1 K2 A1 A2 :
K1 \subset K2 -> A1 \subset A2 -> semiprime K2 A2 -> semiprime K1 A1.
Proof.
move=> sK12 sA12 prKA2 x /setD1P[ntx A1x].
apply/eqP; rewrite eqEsubset andbC -{1}cent_set1 setIS ?centS ?sub1set //=.
rewrite -(setIidPl sK12) -!setIA prKA2 ?setIS ?centS //.
by rewrite !inE ntx (subsetP sA12).
Qed.
Lemma cent_semiprime H K X :
semiprime K H -> X \subset H -> X :!=: 1 -> 'C_K(X) = 'C_K(H).
Proof.
move=> prKH sXH /trivgPn[x Xx ntx]; apply/eqP.
rewrite eqEsubset -{1}(prKH x) ?inE ?(subsetP sXH) ?ntx //=.
by rewrite -cent_cycle !setIS ?centS ?cycle_subG.
Qed.
Lemma stab_semiprime H K X :
semiprime K H -> X \subset K -> 'C_H(X) != 1 -> 'C_H(X) = H.
Proof.
move=> prKH sXK ntCHX; apply/setIidPl; rewrite centsC -subsetIidl.
rewrite -{2}(setIidPl sXK) -setIA -(cent_semiprime prKH _ ntCHX) ?subsetIl //.
by rewrite !subsetI subxx sXK centsC subsetIr.
Qed.
Lemma cent_semiregular H K X :
semiregular K H -> X \subset H -> X :!=: 1 -> 'C_K(X) = 1.
Proof.
move=> regKH sXH /trivgPn[x Xx ntx]; apply/trivgP.
rewrite -(regKH x) ?inE ?(subsetP sXH) ?ntx ?setIS //=.
by rewrite -cent_cycle centS ?cycle_subG.
Qed.
Lemma regular_norm_dvd_pred K H :
H \subset 'N(K) -> semiregular K H -> #|H| %| #|K|.-1.
Proof.
move=> nKH regH; have actsH: [acts H, on K^# | 'J] by rewrite astabsJ normD1.
rewrite (cardsD1 1 K) group1 -(acts_sum_card_orbit actsH) /=.
rewrite (eq_bigr (fun _ => #|H|)) ?sum_nat_const ?dvdn_mull //.
move=> _ /imsetP[x /setIdP[ntx Kx] ->]; rewrite card_orbit astab1J.
rewrite ['C_H[x]](trivgP _) ?indexg1 //=.
apply/subsetP=> y /setIP[Hy cxy]; apply: contraR ntx => nty.
by rewrite -[[set 1]](regH y) inE ?nty // Kx cent1C.
Qed.
Lemma regular_norm_coprime K H :
H \subset 'N(K) -> semiregular K H -> coprime #|K| #|H|.
Proof.
move=> nKH regH.
by rewrite (coprime_dvdr (regular_norm_dvd_pred nKH regH)) ?coprimenP.
Qed.
Lemma semiregularJ K H x : semiregular K H -> semiregular (K :^ x) (H :^ x).
Proof.
move=> regH yx; rewrite -conjD1g => /imsetP[y Hy ->].
by rewrite cent1J -conjIg regH ?conjs1g.
Qed.
Lemma semiprimeJ K H x : semiprime K H -> semiprime (K :^ x) (H :^ x).
Proof.
move=> prH yx; rewrite -conjD1g => /imsetP[y Hy ->].
by rewrite cent1J centJ -!conjIg prH.
Qed.
Lemma normedTI_P A G L :
reflect [/\ A != set0, L \subset 'N_G(A)
& {in G, forall g, ~~ [disjoint A & A :^ g] -> g \in L}]
(normedTI A G L).
Proof.
apply: (iffP and3P) => [[nzA /trivIsetP tiAG /eqP <-] | [nzA sLN tiAG]].
split=> // g Gg; rewrite inE Gg (sameP normP eqP) /= eq_sym; apply: contraR.
by apply: tiAG; rewrite ?mem_orbit ?orbit_refl.
have [/set0Pn[a Aa] /subsetIP[_ nAL]] := (nzA, sLN); split=> //; last first.
rewrite eqEsubset sLN andbT; apply/subsetP=> x /setIP[Gx nAx].
by apply/tiAG/pred0Pn=> //; exists a; rewrite /= (normP nAx) Aa.
apply/trivIsetP=> _ _ /imsetP[x Gx ->] /imsetP[y Gy ->]; apply: contraR.
rewrite -setI_eq0 -(mulgKV x y) conjsgM; set g := (y * x^-1)%g.
have Gg: g \in G by rewrite groupMl ?groupV.
rewrite -conjIg (inj_eq (act_inj 'Js x)) (eq_sym A) (sameP eqP normP).
by rewrite -cards_eq0 cardJg cards_eq0 setI_eq0 => /tiAG/(subsetP nAL)->.
Qed.
Arguments normedTI_P {A G L}.
Lemma normedTI_memJ_P A G L :
reflect [/\ A != set0, L \subset G
& {in A & G, forall a g, (a ^ g \in A) = (g \in L)}]
(normedTI A G L).
Proof.
apply: (iffP normedTI_P) => [[-> /subsetIP[sLG nAL] tiAG] | [-> sLG tiAG]].
split=> // a g Aa Gg; apply/idP/idP=> [Aag | Lg]; last first.
by rewrite memJ_norm ?(subsetP nAL).
by apply/tiAG/pred0Pn=> //; exists (a ^ g)%g; rewrite /= Aag memJ_conjg.
split=> // [ | g Gg /pred0Pn[ag /=]]; last first.
by rewrite andbC => /andP[/imsetP[a Aa ->]]; rewrite tiAG.
apply/subsetP=> g Lg; have Gg := subsetP sLG g Lg.
by rewrite !inE Gg; apply/subsetP=> _ /imsetP[a Aa ->]; rewrite tiAG.
Qed.
Lemma partition_class_support A G :
A != set0 -> trivIset (A :^: G) -> partition (A :^: G) (class_support A G).
Proof.
rewrite /partition cover_imset -class_supportEr eqxx => nzA ->.
by apply: contra nzA => /imsetP[x _ /eqP]; rewrite eq_sym -!cards_eq0 cardJg.
Qed.
Lemma partition_normedTI A G L :
normedTI A G L -> partition (A :^: G) (class_support A G).
Proof. by case/and3P=> ntA tiAG _; apply: partition_class_support. Qed.
Lemma card_support_normedTI A G L :
normedTI A G L -> #|class_support A G| = (#|A| * #|G : L|)%N.
Proof.
case/and3P=> ntA tiAG /eqP <-; rewrite -card_conjugates mulnC.
apply: card_uniform_partition (partition_class_support ntA tiAG).
by move=> _ /imsetP[y _ ->]; rewrite cardJg.
Qed.
Lemma normedTI_S A B G L :
A != set0 -> L \subset 'N(A) -> A \subset B -> normedTI B G L ->
normedTI A G L.
Proof.
move=> nzA /subsetP nAL /subsetP sAB /normedTI_memJ_P[nzB sLG tiB].
apply/normedTI_memJ_P; split=> // a x Aa Gx.
by apply/idP/idP => [Aax | /nAL/memJ_norm-> //]; rewrite -(tiB a) ?sAB.
Qed.
Lemma cent1_normedTI A G L :
normedTI A G L -> {in A, forall x, 'C_G[x] \subset L}.
Proof.
case/normedTI_memJ_P=> [_ _ tiAG] x Ax; apply/subsetP=> y /setIP[Gy cxy].
by rewrite -(tiAG x) // /(x ^ y) -(cent1P cxy) mulKg.
Qed.
Lemma Frobenius_actionP G H :
reflect (has_Frobenius_action G H) [Frobenius G with complement H].
Proof.
apply: (iffP andP) => [[neqHG] | [sT S to [ffulG transG regG ntH [u Su defH]]]].
case/normedTI_P=> nzH /subsetIP[sHG _] tiHG.
suffices: Frobenius_action G H (rcosets H G) 'Rs by apply: hasFrobeniusAction.
pose Hfix x := 'Fix_(rcosets H G | 'Rs)[x].
have regG: {in G^#, forall x, #|Hfix x| <= 1}.
move=> x /setD1P[ntx Gx].
apply: wlog_neg; rewrite -ltnNge => /ltnW/card_gt0P/=[Hy].
rewrite -(cards1 Hy) => /setIP[/imsetP[y Gy ->{Hy}] cHyx].
apply/subset_leq_card/subsetP=> _ /setIP[/imsetP[z Gz ->] cHzx].
rewrite -!sub_astab1 !astab1_act !sub1set astab1Rs in cHyx cHzx *.
rewrite !rcosetE; apply/set1P/rcoset_eqP; rewrite mem_rcoset.
apply: tiHG; [by rewrite !in_group | apply/pred0Pn; exists (x ^ y^-1)].
by rewrite conjD1g !inE conjg_eq1 ntx -mem_conjg cHyx conjsgM memJ_conjg.
have ntH: H :!=: 1 by rewrite -subG1 -setD_eq0.
split=> //; first 1 last; first exact: transRs_rcosets.
by exists (val H); rewrite ?orbit_refl // astab1Rs (setIidPr sHG).
apply/subsetP=> y /setIP[Gy cHy]; apply: contraR neqHG => nt_y.
rewrite (index1g sHG) //; apply/eqP; rewrite eqn_leq indexg_gt0 andbT.
apply: leq_trans (regG y _); last by rewrite setDE 2!inE Gy nt_y /=.
by rewrite /Hfix (setIidPl _) -1?astabC ?sub1set.
have sHG: H \subset G by rewrite defH subsetIl.
split.
apply: contraNneq ntH => /= defG.
suffices defS: S = [set u] by rewrite -(trivgP ffulG) /= defS defH.
apply/eqP; rewrite eq_sym eqEcard sub1set Su.
by rewrite -(atransP transG u Su) card_orbit -defH defG indexgg cards1.
apply/normedTI_P; rewrite setD_eq0 subG1 normD1 subsetI sHG normG.
split=> // x Gx; rewrite -setI_eq0 conjD1g defH inE Gx conjIg conjGid //.
rewrite -setDIl -setIIr -astab1_act setDIl => /set0Pn[y /setIP[Gy /setD1P[_]]].
case/setIP; rewrite 2!(sameP astab1P afix1P) => cuy cuxy; apply/astab1P.
apply: contraTeq (regG y Gy) => cu'x.
rewrite (cardD1 u) (cardD1 (to u x)) inE Su cuy inE /= inE cu'x cuxy.
by rewrite (actsP (atrans_acts transG)) ?Su.
Qed.
Section FrobeniusProperties.
Variables G H K : {group gT}.
Hypothesis frobG : [Frobenius G = K ><| H].
Lemma FrobeniusWker : [Frobenius G with kernel K].
Proof. by apply/existsP; exists H. Qed.
Lemma FrobeniusWcompl : [Frobenius G with complement H].
Proof. by case/andP: frobG. Qed.
Lemma FrobeniusW : [Frobenius G].
Proof. by apply/existsP; exists H; apply: FrobeniusWcompl. Qed.
Lemma Frobenius_context :
[/\ K ><| H = G, K :!=: 1, H :!=: 1, K \proper G & H \proper G].
Proof.
have [/eqP defG neqHG ntH _] := and4P frobG; rewrite setD_eq0 subG1 in ntH.
have ntK: K :!=: 1 by apply: contraNneq neqHG => K1; rewrite -defG K1 sdprod1g.
rewrite properEcard properEneq neqHG; have /mulG_sub[-> ->] := sdprodW defG.
by rewrite -(sdprod_card defG) ltn_Pmulr ?cardG_gt1.
Qed.
Lemma Frobenius_partition : partition (gval K |: (H^# :^: K)) G.
Proof.
have [/eqP defG _ tiHG] := and3P frobG; have [_ tiH1G /eqP defN] := and3P tiHG.
have [[_ /mulG_sub[sKG sHG] nKH tiKH] mulHK] := (sdprodP defG, sdprodWC defG).
set HG := H^# :^: K; set KHG := _ |: _.
have defHG: HG = H^# :^: G.
have: 'C_G[H^# | 'Js] * K = G by rewrite astab1Js defN mulHK.
move/subgroup_transitiveP/atransP.
by apply; rewrite ?atrans_orbit ?orbit_refl.
have /and3P[defHK _ nzHG] := partition_normedTI tiHG.
rewrite -defHG in defHK nzHG tiH1G.
have [tiKHG HG'K]: trivIset KHG /\ gval K \notin HG.
apply: trivIsetU1 => // _ /imsetP[x Kx ->]; rewrite -setI_eq0.
by rewrite -(conjGid Kx) -conjIg setIDA tiKH setDv conj0g.
rewrite /partition andbC tiKHG !inE negb_or nzHG eq_sym -card_gt0 cardG_gt0 /=.
rewrite eqEcard; apply/andP; split.
rewrite /cover big_setU1 //= subUset sKG -/(cover HG) (eqP defHK).
by rewrite class_support_subG // (subset_trans _ sHG) ?subD1set.
rewrite -(eqnP tiKHG) big_setU1 //= (eqnP tiH1G) (eqP defHK).
rewrite (card_support_normedTI tiHG) -(Lagrange sHG) (cardsD1 1) group1 mulSn.
by rewrite leq_add2r -mulHK indexMg -indexgI tiKH indexg1.
Qed.
Lemma Frobenius_cent1_ker : {in K^#, forall x, 'C_G[x] \subset K}.
Proof.
have [/eqP defG _ /normedTI_memJ_P[_ _ tiHG]] := and3P frobG.
move=> x /setD1P[ntx Kx]; have [_ /mulG_sub[sKG _] _ tiKH] := sdprodP defG.
have [/eqP <- _ _] := and3P Frobenius_partition; rewrite big_distrl /=.
apply/bigcupsP=> _ /setU1P[|/imsetP[y Ky]] ->; first exact: subsetIl.
apply: contraR ntx => /subsetPn[z]; rewrite inE mem_conjg => /andP[Hzy cxz] _.
rewrite -(conjg_eq1 x y^-1) -in_set1 -set1gE -tiKH inE andbC.
rewrite -(tiHG _ _ Hzy) ?(subsetP sKG) ?in_group // Ky andbT -conjJg.
by rewrite /(z ^ x) (cent1P cxz) mulKg.
Qed.
Lemma Frobenius_reg_ker : semiregular K H.
Proof.
move=> x /setD1P[ntx Hx].
apply/trivgP/subsetP=> y /setIP[Ky cxy]; apply: contraR ntx => nty.
have K1y: y \in K^# by rewrite inE nty.
have [/eqP/sdprod_context[_ sHG _ _ tiKH] _] := andP frobG.
suffices: x \in K :&: H by rewrite tiKH inE.
by rewrite inE (subsetP (Frobenius_cent1_ker K1y)) // inE cent1C (subsetP sHG).
Qed.
Lemma Frobenius_reg_compl : semiregular H K.
Proof. by apply: semiregular_sym; apply: Frobenius_reg_ker. Qed.
Lemma Frobenius_dvd_ker1 : #|H| %| #|K|.-1.
Proof.
apply: regular_norm_dvd_pred Frobenius_reg_ker.
by have[/sdprodP[]] := Frobenius_context.
Qed.
Lemma ltn_odd_Frobenius_ker : odd #|G| -> #|H|.*2 < #|K|.
Proof.
move/oddSg=> oddG.
have [/sdprodW/mulG_sub[sKG sHG] ntK _ _ _] := Frobenius_context.
by rewrite dvdn_double_ltn ?oddG ?cardG_gt1 ?Frobenius_dvd_ker1.
Qed.
Lemma Frobenius_index_dvd_ker1 : #|G : K| %| #|K|.-1.
Proof.
have[defG _ _ /andP[sKG _] _] := Frobenius_context.
by rewrite -divgS // -(sdprod_card defG) mulKn ?Frobenius_dvd_ker1.
Qed.
Lemma Frobenius_coprime : coprime #|K| #|H|.
Proof. by rewrite (coprime_dvdr Frobenius_dvd_ker1) ?coprimenP. Qed.
Lemma Frobenius_trivg_cent : 'C_K(H) = 1.
Proof.
by apply: (cent_semiregular Frobenius_reg_ker); case: Frobenius_context.
Qed.
Lemma Frobenius_index_coprime : coprime #|K| #|G : K|.
Proof. by rewrite (coprime_dvdr Frobenius_index_dvd_ker1) ?coprimenP. Qed.
Lemma Frobenius_ker_Hall : Hall G K.
Proof.
have [_ _ _ /andP[sKG _] _] := Frobenius_context.
by rewrite /Hall sKG Frobenius_index_coprime.
Qed.
Lemma Frobenius_compl_Hall : Hall G H.
Proof.
have [defG _ _ _ _] := Frobenius_context.
by rewrite -(sdprod_Hall defG) Frobenius_ker_Hall.
Qed.
End FrobeniusProperties.
Lemma normedTI_J x A G L : normedTI (A :^ x) (G :^ x) (L :^ x) = normedTI A G L.
Proof.
rewrite {1}/normedTI normJ -conjIg -(conj0g x) !(can_eq (conjsgK x)).
congr [&& _, _ == _ & _]; rewrite /cover (reindex_inj (@conjsg_inj _ x)).
by apply: eq_big => Hy; rewrite ?orbit_conjsg ?cardJg.
by rewrite bigcupJ cardJg (eq_bigl _ _ (orbit_conjsg _ _ _ _)).
Qed.
Lemma FrobeniusJcompl x G H :
[Frobenius G :^ x with complement H :^ x] = [Frobenius G with complement H].
Proof.
by congr (_ && _); rewrite ?(can_eq (conjsgK x)) // -conjD1g normedTI_J.
Qed.
Lemma FrobeniusJ x G K H :
[Frobenius G :^ x = K :^ x ><| H :^ x] = [Frobenius G = K ><| H].
Proof.
by congr (_ && _); rewrite ?FrobeniusJcompl // -sdprodJ (can_eq (conjsgK x)).
Qed.
Lemma FrobeniusJker x G K :
[Frobenius G :^ x with kernel K :^ x] = [Frobenius G with kernel K].
Proof.
apply/existsP/existsP=> [] [H]; last by exists (H :^ x)%G; rewrite FrobeniusJ.
by rewrite -(conjsgKV x H) FrobeniusJ; exists (H :^ x^-1)%G.
Qed.
Lemma FrobeniusJgroup x G : [Frobenius G :^ x] = [Frobenius G].
Proof.
apply/existsP/existsP=> [] [H].
by rewrite -(conjsgKV x H) FrobeniusJcompl; exists (H :^ x^-1)%G.
by exists (H :^ x)%G; rewrite FrobeniusJcompl.
Qed.
Lemma Frobenius_ker_dvd_ker1 G K :
[Frobenius G with kernel K] -> #|G : K| %| #|K|.-1.
Proof. by case/existsP=> H; apply: Frobenius_index_dvd_ker1. Qed.
Lemma Frobenius_ker_coprime G K :
[Frobenius G with kernel K] -> coprime #|K| #|G : K|.
Proof. by case/existsP=> H; apply: Frobenius_index_coprime. Qed.
Lemma Frobenius_semiregularP G K H :
K ><| H = G -> K :!=: 1 -> H :!=: 1 ->
reflect (semiregular K H) [Frobenius G = K ><| H].
Proof.
move=> defG ntK ntH.
apply: (iffP idP) => [|regG]; first exact: Frobenius_reg_ker.
have [nsKG sHG defKH nKH tiKH]:= sdprod_context defG; have [sKG _]:= andP nsKG.
apply/and3P; split; first by rewrite defG.
by rewrite eqEcard sHG -(sdprod_card defG) -ltnNge ltn_Pmull ?cardG_gt1.
apply/normedTI_memJ_P; rewrite setD_eq0 subG1 sHG -defKH -(normC nKH).
split=> // z _ /setD1P[ntz Hz] /mulsgP[y x Hy Kx ->]; rewrite groupMl // !inE.
rewrite conjg_eq1 ntz; apply/idP/idP=> [Hzxy | Hx]; last by rewrite !in_group.
apply: (subsetP (sub1G H)); have Hzy: z ^ y \in H by apply: groupJ.
rewrite -(regG (z ^ y)); last by apply/setD1P; rewrite conjg_eq1.
rewrite inE Kx cent1C (sameP cent1P commgP) -in_set1 -[[set 1]]tiKH inE /=.
rewrite andbC groupM ?groupV -?conjgM //= commgEr groupMr //.
by rewrite memJ_norm ?(subsetP nKH) ?groupV.
Qed.
Lemma prime_FrobeniusP G K H :
K :!=: 1 -> prime #|H| ->
reflect (K ><| H = G /\ 'C_K(H) = 1) [Frobenius G = K ><| H].
Proof.
move=> ntK H_pr; have ntH: H :!=: 1 by rewrite -cardG_gt1 prime_gt1.
have [defG | not_sdG] := eqVneq (K ><| H) G; last first.
by apply: (iffP andP) => [] [defG]; rewrite defG ?eqxx in not_sdG.
apply: (iffP (Frobenius_semiregularP defG ntK ntH)) => [regH | [_ regH x]].
split=> //; have [x defH] := cyclicP (prime_cyclic H_pr).
by rewrite defH cent_cycle regH // !inE defH cycle_id andbT -cycle_eq1 -defH.
case/setD1P=> nt_x Hx; apply/trivgP; rewrite -regH setIS //= -cent_cycle.
by rewrite centS // prime_meetG // (setIidPr _) ?cycle_eq1 ?cycle_subG.
Qed.
Lemma Frobenius_subl G K K1 H :
K1 :!=: 1 -> K1 \subset K -> H \subset 'N(K1) -> [Frobenius G = K ><| H] ->
[Frobenius K1 <*> H = K1 ><| H].
Proof.
move=> ntK1 sK1K nK1H frobG; have [_ _ ntH _ _] := Frobenius_context frobG.
apply/Frobenius_semiregularP=> //.
by rewrite sdprodEY ?coprime_TIg ?(coprimeSg sK1K) ?(Frobenius_coprime frobG).
by move=> x /(Frobenius_reg_ker frobG) cKx1; apply/trivgP; rewrite -cKx1 setSI.
Qed.
Lemma Frobenius_subr G K H H1 :
H1 :!=: 1 -> H1 \subset H -> [Frobenius G = K ><| H] ->
[Frobenius K <*> H1 = K ><| H1].
Proof.
move=> ntH1 sH1H frobG; have [defG ntK _ _ _] := Frobenius_context frobG.
apply/Frobenius_semiregularP=> //.
have [_ _ /(subset_trans sH1H) nH1K tiHK] := sdprodP defG.
by rewrite sdprodEY //; apply/trivgP; rewrite -tiHK setIS.
by apply: sub_in1 (Frobenius_reg_ker frobG); apply/subsetP/setSD.
Qed.
Lemma Frobenius_kerP G K :
reflect [/\ K :!=: 1, K \proper G, K <| G
& {in K^#, forall x, 'C_G[x] \subset K}]
[Frobenius G with kernel K].
Proof.
apply: (iffP existsP) => [[H frobG] | [ntK ltKG nsKG regK]].
have [/sdprod_context[nsKG _ _ _ _] ntK _ ltKG _] := Frobenius_context frobG.
by split=> //; apply: Frobenius_cent1_ker frobG.
have /andP[sKG nKG] := nsKG.
have hallK: Hall G K.
rewrite /Hall sKG //= coprime_sym coprime_pi' //.
apply: sub_pgroup (pgroup_pi K) => p; have [P sylP] := Sylow_exists p G.
have [[sPG pP p'GiP] sylPK] := (and3P sylP, Hall_setI_normal nsKG sylP).
rewrite -p_rank_gt0 -(rank_Sylow sylPK) rank_gt0 => ntPK.
rewrite inE /= -p'natEpi // (pnat_dvd _ p'GiP) ?indexgS //.
have /trivgPn[z]: P :&: K :&: 'Z(P) != 1.
by rewrite meet_center_nil ?(pgroup_nil pP) ?(normalGI sPG nsKG).
rewrite !inE -andbA -sub_cent1=> /and4P[_ Kz _ cPz] ntz.
by apply: subset_trans (regK z _); [apply/subsetIP | apply/setD1P].
have /splitsP[H /complP[tiKH defG]] := SchurZassenhaus_split hallK nsKG.
have [_ sHG] := mulG_sub defG; have nKH := subset_trans sHG nKG.
exists H; apply/Frobenius_semiregularP; rewrite ?sdprodE //.
by apply: contraNneq (proper_subn ltKG) => H1; rewrite -defG H1 mulg1.
apply: semiregular_sym => x Kx; apply/trivgP; rewrite -tiKH.
by rewrite subsetI subsetIl (subset_trans _ (regK x _)) ?setSI.
Qed.
Lemma set_Frobenius_compl G K H :
K ><| H = G -> [Frobenius G with kernel K] -> [Frobenius G = K ><| H].
Proof.
move=> defG /Frobenius_kerP[ntK ltKG _ regKG].
apply/Frobenius_semiregularP=> //.
by apply: contraTneq ltKG => H_1; rewrite -defG H_1 sdprodg1 properxx.
apply: semiregular_sym => y /regKG sCyK.
have [_ sHG _ _ tiKH] := sdprod_context defG.
by apply/trivgP; rewrite /= -(setIidPr sHG) setIAC -tiKH setSI.
Qed.
Lemma Frobenius_kerS G K G1 :
G1 \subset G -> K \proper G1 ->
[Frobenius G with kernel K] -> [Frobenius G1 with kernel K].
Proof.
move=> sG1G ltKG1 /Frobenius_kerP[ntK _ /andP[_ nKG] regKG].
apply/Frobenius_kerP; rewrite /normal proper_sub // (subset_trans sG1G) //.
by split=> // x /regKG; apply: subset_trans; rewrite setSI.
Qed.
Lemma Frobenius_action_kernel_def G H K sT S to :
K ><| H = G -> @Frobenius_action _ G H sT S to ->
K :=: 1 :|: [set x in G | 'Fix_(S | to)[x] == set0].
Proof.
move=> defG FrobG.
have partG: partition (gval K |: (H^# :^: K)) G.
apply: Frobenius_partition; apply/andP; rewrite defG; split=> //.
by apply/Frobenius_actionP; apply: hasFrobeniusAction FrobG.
have{FrobG} [ffulG transG regG ntH [u Su defH]]:= FrobG.
apply/setP=> x /[!inE]; have [-> | ntx] := eqVneq; first exact: group1.
rewrite /= -(cover_partition partG) /cover.
have neKHy y: gval K <> H^# :^ y.
by move/setP/(_ 1); rewrite group1 conjD1g setD11.
rewrite big_setU1 /= ?inE; last by apply/imsetP=> [[y _ /neKHy]].
have [nsKG sHG _ _ tiKH] := sdprod_context defG; have [sKG nKG]:= andP nsKG.
symmetry; case Kx: (x \in K) => /=.
apply/set0Pn=> [[v /setIP[Sv]]]; have [y Gy ->] := atransP2 transG Su Sv.
rewrite -sub1set -astabC sub1set astab1_act mem_conjg => Hxy.
case/negP: ntx; rewrite -in_set1 -(conjgKV y x) -mem_conjgV conjs1g -tiKH.
by rewrite defH setIA inE -mem_conjg (setIidPl sKG) (normsP nKG) ?Kx.
apply/andP=> [[/bigcupP[_ /imsetP[y Ky ->] Hyx] /set0Pn[]]]; exists (to u y).
rewrite inE (actsP (atrans_acts transG)) ?(subsetP sKG) // Su.
rewrite -sub1set -astabC sub1set astab1_act.
by rewrite conjD1g defH conjIg !inE in Hyx; case/and3P: Hyx.
Qed.
End FrobeniusBasics.
Arguments normedTI_P {gT A G L}.
Arguments normedTI_memJ_P {gT A G L}.
Arguments Frobenius_kerP {gT G K}.
Lemma Frobenius_coprime_quotient (gT : finGroupType) (G K H N : {group gT}) :
K ><| H = G -> N <| G -> coprime #|K| #|H| /\ H :!=: 1%g ->
N \proper K /\ {in H^#, forall x, 'C_K[x] \subset N} ->
[Frobenius G / N = (K / N) ><| (H / N)]%g.
Proof.
move=> defG nsNG [coKH ntH] [ltNK regH].
have [[sNK _] [_ /mulG_sub[sKG sHG] _ _]] := (andP ltNK, sdprodP defG).
have [_ nNG] := andP nsNG; have nNH := subset_trans sHG nNG.
apply/Frobenius_semiregularP; first exact: quotient_coprime_sdprod.
- by rewrite quotient_neq1 ?(normalS _ sKG).
- by rewrite -(isog_eq1 (quotient_isog _ _)) ?coprime_TIg ?(coprimeSg sNK).
move=> _ /(subsetP (quotientD1 _ _))/morphimP[x nNx H1x ->].
rewrite -cent_cycle -quotient_cycle //=.
rewrite -strongest_coprime_quotient_cent ?cycle_subG //.
- by rewrite cent_cycle quotientS1 ?regH.
- by rewrite subIset ?sNK.
- rewrite (coprimeSg (subsetIl N _)) ?(coprimeSg sNK) ?(coprimegS _ coKH) //.
by rewrite cycle_subG; case/setD1P: H1x.
by rewrite orbC abelian_sol ?cycle_abelian.
Qed.
Section InjmFrobenius.
Variables (gT rT : finGroupType) (D G : {group gT}) (f : {morphism D >-> rT}).
Implicit Types (H K : {group gT}) (sGD : G \subset D) (injf : 'injm f).
Lemma injm_Frobenius_compl H sGD injf :
[Frobenius G with complement H] -> [Frobenius f @* G with complement f @* H].
Proof.
case/andP=> neqGH /normedTI_P[nzH /subsetIP[sHG _] tiHG].
have sHD := subset_trans sHG sGD; have sH1D := subset_trans (subD1set H 1) sHD.
apply/andP; rewrite (can_in_eq (injmK injf)) //; split=> //.
apply/normedTI_P; rewrite normD1 -injmD1 // -!cards_eq0 card_injm // in nzH *.
rewrite subsetI normG morphimS //; split=> // _ /morphimP[x Dx Gx ->] ti'fHx.
rewrite mem_morphim ?tiHG //; apply: contra ti'fHx; rewrite -!setI_eq0 => tiHx.
by rewrite -morphimJ // -injmI ?conj_subG // (eqP tiHx) morphim0.
Qed.
Lemma injm_Frobenius H K sGD injf :
[Frobenius G = K ><| H] -> [Frobenius f @* G = f @* K ><| f @* H].
Proof.
case/andP=> /eqP defG frobG.
by apply/andP; rewrite (injm_sdprod _ injf defG) // eqxx injm_Frobenius_compl.
Qed.
Lemma injm_Frobenius_ker K sGD injf :
[Frobenius G with kernel K] -> [Frobenius f @* G with kernel f @* K].
Proof.
case/existsP=> H frobG; apply/existsP.
by exists (f @* H)%G; apply: injm_Frobenius.
Qed.
Lemma injm_Frobenius_group sGD injf : [Frobenius G] -> [Frobenius f @* G].
Proof.
case/existsP=> H frobG; apply/existsP; exists (f @* H)%G.
exact: injm_Frobenius_compl.
Qed.
End InjmFrobenius.
Theorem Frobenius_Ldiv (gT : finGroupType) (G : {group gT}) n :
n %| #|G| -> n %| #|'Ldiv_n(G)|.
Proof.
move=> nG; move: {2}_.+1 (ltnSn (#|G| %/ n)) => mq.
elim: mq => // mq IHm in gT G n nG *; case/dvdnP: nG => q oG.
have [q_gt0 n_gt0] : 0 < q /\ 0 < n by apply/andP; rewrite -muln_gt0 -oG.
rewrite ltnS oG mulnK // => leqm.
have:= q_gt0; rewrite leq_eqVlt => /predU1P[q1 | lt1q].
rewrite -(mul1n n) q1 -oG (setIidPl _) //.
by apply/subsetP=> x Gx; rewrite inE -order_dvdn order_dvdG.
pose p := pdiv q; have pr_p: prime p by apply: pdiv_prime.
have lt1p: 1 < p := prime_gt1 pr_p; have p_gt0 := ltnW lt1p.
have{leqm} lt_qp_mq: q %/ p < mq by apply: leq_trans leqm; rewrite ltn_Pdiv.
have: n %| #|'Ldiv_(p * n)(G)|.
have: p * n %| #|G| by rewrite oG dvdn_pmul2r ?pdiv_dvd.
move/IHm=> IH; apply: dvdn_trans (IH _); first exact: dvdn_mull.
by rewrite oG divnMr.
rewrite -(cardsID 'Ldiv_n()) dvdn_addl.
rewrite -setIA ['Ldiv_n(_)](setIidPr _) //.
by apply/subsetP=> x; rewrite !inE -!order_dvdn; apply: dvdn_mull.
rewrite -setIDA; set A := _ :\: _.
have pA x: x \in A -> #[x]`_p = (n`_p * p)%N.
rewrite !inE -!order_dvdn => /andP[xn xnp].
rewrite !p_part // -expnSr; congr (p ^ _)%N; apply/eqP.
rewrite eqn_leq -{1}addn1 -(pfactorK 1 pr_p) -lognM ?expn1 // mulnC.
rewrite dvdn_leq_log ?muln_gt0 ?p_gt0 //= ltnNge; apply: contra xn => xn.
move: xnp; rewrite -[#[x]](partnC p) //.
rewrite !Gauss_dvd ?coprime_partC //; case/andP=> _.
rewrite p_part ?pfactor_dvdn // xn Gauss_dvdr // coprime_sym.
exact: pnat_coprime (pnat_id _) (part_pnat _ _).
rewrite -(partnC p n_gt0) Gauss_dvd ?coprime_partC //; apply/andP; split.
rewrite -sum1_card (partition_big_imset (@cycle _)) /=.
apply: dvdn_sum => _ /imsetP[x /setIP[Gx Ax] ->].
rewrite (eq_bigl (generator <[x]>)) => [|y].
rewrite sum1dep_card -totient_gen -[#[x]](partnC p) //.
rewrite totient_coprime ?coprime_partC // dvdn_mulr // .
by rewrite (pA x Ax) p_part // -expnSr totient_pfactor // dvdn_mull.
rewrite /generator eq_sym andbC; case xy: {+}(_ == _) => //.
rewrite !inE -!order_dvdn in Ax *.
by rewrite -cycle_subG /order -(eqP xy) cycle_subG Gx.
rewrite -sum1_card (partition_big_imset (fun x => x.`_p ^: G)) /=.
apply: dvdn_sum => _ /imsetP[x /setIP[Gx Ax] ->].
set y := x.`_p; have oy: #[y] = (n`_p * p)%N by rewrite order_constt pA.
rewrite (partition_big (fun x => x.`_p) [in y ^: G]) /= => [|z]; last first.
by case/andP=> _ /eqP <-; rewrite /= class_refl.
pose G' := ('C_G[y] / <[y]>)%G; pose n' := gcdn #|G'| n`_p^'.
have n'_gt0: 0 < n' by rewrite gcdn_gt0 cardG_gt0.
rewrite (eq_bigr (fun _ => #|'Ldiv_n'(G')|)) => [|_ /imsetP[a Ga ->]].
rewrite sum_nat_const -index_cent1 indexgI.
rewrite -(dvdn_pmul2l (cardG_gt0 'C_G[y])) mulnA LagrangeI.
have oCy: #|'C_G[y]| = (#[y] * #|G'|)%N.
rewrite card_quotient ?subcent1_cycle_norm // Lagrange //.
by rewrite subcent1_cycle_sub ?groupX.
rewrite oCy -mulnA -(muln_lcm_gcd #|G'|) -/n' mulnA dvdn_mul //.
rewrite muln_lcmr -oCy order_constt pA // mulnAC partnC // dvdn_lcm.
by rewrite cardSg ?subsetIl // mulnC oG dvdn_pmul2r ?pdiv_dvd.
apply: IHm; [exact: dvdn_gcdl | apply: leq_ltn_trans lt_qp_mq].
rewrite -(@divnMr n`_p^') // -muln_lcm_gcd mulnC divnMl //.
rewrite leq_divRL // divn_mulAC ?leq_divLR ?dvdn_mulr ?dvdn_lcmr //.
rewrite dvdn_leq ?muln_gt0 ?q_gt0 //= mulnC muln_lcmr dvdn_lcm.
rewrite -(@dvdn_pmul2l n`_p) // mulnA -oy -oCy mulnCA partnC // -oG.
by rewrite cardSg ?subsetIl // dvdn_mul ?pdiv_dvd.
pose h := [fun z => coset <[y]> (z ^ a^-1)].
pose h' := [fun Z : coset_of <[y]> => (y * (repr Z).`_p^') ^ a].
rewrite -sum1_card (reindex_onto h h') /= => [|Z]; last first.
rewrite conjgK coset_kerl ?cycle_id ?morph_constt ?repr_coset_norm //.
rewrite /= coset_reprK 2!inE -order_dvdn dvdn_gcd => /and3P[_ _ p'Z].
by apply: constt_p_elt (pnat_dvd p'Z _); apply: part_pnat.
apply: eq_bigl => z; apply/andP/andP=> [[]|[]].
rewrite inE -andbA => /and3P[Gz Az _] /eqP zp_ya.
have czy: z ^ a^-1 \in 'C[y].
rewrite -mem_conjg -normJ conjg_set1 -zp_ya.
by apply/cent1P; apply: commuteX.
have Nz: z ^ a^-1 \in 'N(<[y]>) by apply: subsetP czy; apply: norm_gen.
have G'z: h z \in G' by rewrite mem_morphim //= inE groupJ // groupV.
rewrite inE G'z inE -order_dvdn dvdn_gcd order_dvdG //=.
rewrite /order -morphim_cycle // -quotientE card_quotient ?cycle_subG //.
rewrite -(@dvdn_pmul2l #[y]) // Lagrange; last first.
by rewrite /= cycleJ cycle_subG mem_conjgV -zp_ya mem_cycle.
rewrite oy mulnAC partnC // [#|_|]orderJ; split.
by rewrite !inE -!order_dvdn mulnC in Az; case/andP: Az.
set Z := coset _ _; have NZ := repr_coset_norm Z; have:= coset_reprK Z.
case/kercoset_rcoset=> {NZ}// _ /cycleP[i ->] ->{Z}.
rewrite consttM; last exact/commute_sym/commuteX/cent1P.
rewrite (constt1P _) ?p_eltNK 1?p_eltX ?p_elt_constt // mul1g.
by rewrite conjMg consttJ conjgKV -zp_ya consttC.
rewrite 2!inE -order_dvdn; set Z := coset _ _ => /andP[Cz n'Z] /eqP def_z.
have Nz: z ^ a^-1 \in 'N(<[y]>).
rewrite -def_z conjgK groupMr; first by rewrite -(cycle_subG y) normG.
by rewrite groupX ?repr_coset_norm.
have{Cz} /setIP[Gz Cz]: z ^ a^-1 \in 'C_G[y].
case/morphimP: Cz => u Nu Cu /kercoset_rcoset[] // _ /cycleP[i ->] ->.
by rewrite groupMr // groupX // inE groupX //; apply/cent1P.
have{def_z} zp_ya: z.`_p = y ^ a.
rewrite -def_z consttJ consttM.
rewrite constt_p_elt ?p_elt_constt //.
by rewrite (constt1P _) ?p_eltNK ?p_elt_constt ?mulg1.
apply: commute_sym; apply/cent1P.
by rewrite -def_z conjgK groupMl // in Cz; apply/cent1P.
have ozp: #[z ^ a^-1]`_p = #[y] by rewrite -order_constt consttJ zp_ya conjgK.
split; rewrite zp_ya // -class_lcoset lcoset_id // eqxx andbT.
rewrite -(conjgKV a z) !inE groupJ //= -!order_dvdn orderJ; apply/andP; split.
apply: contra (partn_dvd p n_gt0) _.
by rewrite ozp -(muln1 n`_p) oy dvdn_pmul2l // dvdn1 neq_ltn lt1p orbT.
rewrite -(partnC p n_gt0) mulnCA mulnA -oy -(@partnC p #[_]) // ozp.
apply dvdn_mul => //; apply: dvdn_trans (dvdn_trans n'Z (dvdn_gcdr _ _)).
rewrite {2}/order -morphim_cycle // -quotientE card_quotient ?cycle_subG //.
rewrite -(@dvdn_pmul2l #|<[z ^ a^-1]> :&: <[y]>|) ?cardG_gt0 // LagrangeI.
rewrite -[#|<[_]>|](partnC p) ?order_gt0 // dvdn_pmul2r // ozp.
by rewrite cardSg ?subsetIr.
Qed.
|
finfun.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice.
From mathcomp Require Import fintype tuple.
(******************************************************************************)
(* This file implements a type for functions with a finite domain: *)
(* {ffun aT -> rT} where aT should have a finType structure, *)
(* {ffun forall x : aT, rT} for dependent functions over a finType aT, *)
(* and {ffun funT} where funT expands to a product over a finType. *)
(* Any eqType, choiceType, countType and finType structures on rT extend to *)
(* {ffun aT -> rT} as Leibnitz equality and extensional equalities coincide. *)
(* (T ^ n)%type is notation for {ffun 'I_n -> T}, which is isomorphic *)
(* to n.-tuple T, but is structurally positive and thus can be used to *)
(* define inductive types, e.g., Inductive tree := node n of tree ^ n (see *)
(* mid-file for an expanded example). *)
(* --> More generally, {ffun fT} is always structurally positive. *)
(* {ffun fT} inherits combinatorial structures of rT, i.e., eqType, *)
(* choiceType, countType, and finType. However, due to some limitations of *)
(* the Coq 8.9 unification code the structures are only inherited in the *)
(* NON dependent case, when rT does not depend on x. *)
(* For f : {ffun fT} with fT := forall x : aT, rT we define *)
(* f x == the image of x under f (f coerces to a CiC function) *)
(* --> The coercion is structurally decreasing, e.g., Coq will accept *)
(* Fixpoint size t := let: node n f := t in sumn (codom (size \o f)) + 1. *)
(* as structurally decreasing on t of the inductive tree type above. *)
(* {dffun fT} == alias for {ffun fT} that inherits combinatorial *)
(* structures on rT, when rT DOES depend on x. *)
(* total_fun g == the function induced by a dependent function g of type *)
(* forall x, rT on the total space {x : aT & rT}. *)
(* := fun x => Tagged (fun x => rT) (g x). *)
(* tfgraph f == the total function graph of f, i.e., the #|aT|.-tuple *)
(* of all the (dependent pair) values of total_fun f. *)
(* finfun g == the f extensionally equal to g, and the RECOMMENDED *)
(* interface for building elements of {ffun fT}. *)
(* [ffun x : aT => E] := finfun (fun x : aT => E). *)
(* There should be an explicit type constraint on E if *)
(* type does not depend on x, due to the Coq unification *)
(* limitations referred to above. *)
(* ffun0 aT0 == the trivial finfun, from a proof aT0 that #|aT| = 0. *)
(* f \in family F == f belongs to the family F (f x \in F x for all x) *)
(* There are additional operations for non-dependent finite functions, *)
(* i.e., f in {ffun aT -> rT}. *)
(* [ffun x => E] := finfun (fun x => E). *)
(* The type of E must not depend on x; this restriction *)
(* is a mitigation of the aforementioned Coq unification *)
(* limitations. *)
(* [ffun=> E] := [ffun _ => E] (E should not have a dependent type). *)
(* fgraph f == the function graph of f, i.e., the #|aT|.-tuple *)
(* listing the values of f x, for x ranging over enum aT. *)
(* Finfun G == the finfun f whose (simple) function graph is G. *)
(* f \in ffun_on R == the range of f is a subset of R. *)
(* y.-support f == the y-support of f, i.e., [pred x | f x != y]. *)
(* Thus, y.-support f \subset D means f has y-support D. *)
(* We will put Notation support := 0.-support in ssralg. *)
(* f \in pffun_on y D R == f is a y-partial function from D to R: *)
(* f has y-support D and f x \in R for all x \in D. *)
(* f \in pfamily y D F == f belongs to the y-partial family from D to F: *)
(* f has y-support D and f x \in F x for all x \in D. *)
(* fprod I T_ == alternative construct to {ffun forall i : I, T_ i} for *)
(* the finite product of finTypes, in a set-theoretic way *)
(* := Record fprod I T_ := FProd *)
(* { fprod_fun : {ffun I -> {i : I & T_ i}} ; *)
(* fprod_prop : [forall i : I, tag (fprod_fun i) == i] }. *)
(* fprod I T_ is endowed with a finType structure and allow these operations: *)
(* [fprod i : I => F] == the dependent fprod function built from fun i:I => F *)
(* := fprod_of_fun (fun i : I => F) *)
(* [fprod : I => F] == [fprod _ : I => F] *)
(* [fprod i => F] == [fprod i : _ => F] *)
(* [fprod => F] == [fprod _ : _ => F] *)
(* These fprod terms coerce into vanilla dependent functions via the coercion *)
(* fun_of_fprod I T_ : fprod I T_ -> (forall i : I, T_ i). *)
(* We also define the mutual bijections: *)
(* fprod_of_dffun : {dffun forall i : I, T_ i} -> fprod I T_ *)
(* dffun_of_fprod : fprod I T_ -> {dffun forall i : I, T_ i} *)
(* of_family_tagged_with : {x in family (tagged_with T_)} -> fprod I T_ *)
(* to_family_tagged_with : fprod I T_ -> {x in family (tagged_with T_)} *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Section Def.
Variables (aT : finType) (rT : aT -> Type).
Inductive finfun_on : seq aT -> Type :=
| finfun_nil : finfun_on [::]
| finfun_cons x s of rT x & finfun_on s : finfun_on (x :: s).
Local Fixpoint finfun_rec (g : forall x, rT x) s : finfun_on s :=
if s is x1 :: s1 then finfun_cons (g x1) (finfun_rec g s1) else finfun_nil.
Local Fixpoint fun_of_fin_rec x s (f_s : finfun_on s) : x \in s -> rT x :=
if f_s is finfun_cons x1 s1 y1 f_s1 then
if eqP is ReflectT Dx in reflect _ Dxb return Dxb || (x \in s1) -> rT x then
fun=> ecast x (rT x) (esym Dx) y1
else fun_of_fin_rec f_s1
else fun isF => False_rect (rT x) (notF isF).
Variant finfun_of (ph : phant (forall x, rT x)) : predArgType :=
FinfunOf of finfun_on (enum aT).
Definition dfinfun_of ph := finfun_of ph.
Definition fun_of_fin ph (f : finfun_of ph) x :=
let: FinfunOf f_aT := f in fun_of_fin_rec f_aT (mem_enum aT x).
End Def.
Coercion fun_of_fin : finfun_of >-> Funclass.
Identity Coercion unfold_dfinfun_of : dfinfun_of >-> finfun_of.
Arguments fun_of_fin {aT rT ph} f x.
Notation "{ 'ffun' fT }" := (finfun_of (Phant fT))
(format "{ 'ffun' '[hv' fT ']' }") : type_scope.
Notation "{ 'dffun' fT }" := (dfinfun_of (Phant fT))
(format "{ 'dffun' '[hv' fT ']' }") : type_scope.
Definition exp_finIndexType n : finType := 'I_n.
Notation "T ^ n" :=
(@finfun_of (exp_finIndexType n) (fun=> T) (Phant _)) : type_scope.
Local Notation finPi aT rT := (forall x : Finite.sort aT, rT x) (only parsing).
HB.lock Definition finfun aT rT g :=
FinfunOf (Phant (finPi aT rT)) (finfun_rec g (enum aT)).
Canonical finfun_unlock := Unlockable finfun.unlock.
Arguments finfun {aT rT} g.
Notation "[ 'ffun' x : aT => E ]" := (finfun (fun x : aT => E))
(x name) : function_scope.
Notation "[ 'ffun' x => E ]" := (@finfun _ (fun=> _) (fun x => E))
(x name, format "[ 'ffun' x => E ]") : function_scope.
Notation "[ 'ffun' => E ]" := [ffun _ => E]
(format "[ 'ffun' => E ]") : function_scope.
(* Example outcommented.
(* Examples of using finite functions as containers in recursive inductive *)
(* types, and making use of the fact that the type and accessor are *)
(* structurally positive and decreasing, respectively. *)
Unset Elimination Schemes.
Inductive tree := node n of tree ^ n.
Fixpoint size t := let: node n f := t in sumn (codom (size \o f)) + 1.
Example tree_step (K : tree -> Type) :=
forall n st (t := node st) & forall i : 'I_n, K (st i), K t.
Example tree_rect K (Kstep : tree_step K) : forall t, K t.
Proof. by fix IHt 1 => -[n st]; apply/Kstep=> i; apply: IHt. Defined.
(* An artificial example use of dependent functions. *)
Inductive tri_tree n := tri_row of {ffun forall i : 'I_n, tri_tree i}.
Fixpoint tri_size n (t : tri_tree n) :=
let: tri_row f := t in sumn [seq tri_size (f i) | i : 'I_n] + 1.
Example tri_tree_step (K : forall n, tri_tree n -> Type) :=
forall n st (t := tri_row st) & forall i : 'I_n, K i (st i), K n t.
Example tri_tree_rect K (Kstep : tri_tree_step K) : forall n t, K n t.
Proof. by fix IHt 2 => n [st]; apply/Kstep=> i; apply: IHt. Defined.
Set Elimination Schemes.
(* End example. *) *)
(* The correspondence between finfun_of and CiC dependent functions. *)
Section DepPlainTheory.
Variables (aT : finType) (rT : aT -> Type).
Notation fT := {ffun finPi aT rT}.
Implicit Type f : fT.
Fact ffun0 (aT0 : #|aT| = 0) : fT.
Proof. by apply/finfun=> x; have:= card0_eq aT0 x. Qed.
Lemma ffunE g x : (finfun g : fT) x = g x.
Proof.
rewrite unlock /=; set s := enum aT; set s_x : mem_seq s x := mem_enum _ _.
by elim: s s_x => //= x1 s IHs; case: eqP => [|_]; [case: x1 / | apply: IHs].
Qed.
Lemma ffunP (f1 f2 : fT) : (forall x, f1 x = f2 x) <-> f1 = f2.
Proof.
suffices ffunK f g: (forall x, f x = g x) -> f = finfun g.
by split=> [/ffunK|] -> //; apply/esym/ffunK.
case: f => f Dg; rewrite unlock; congr FinfunOf.
have{} Dg x (aTx : mem_seq (enum aT) x): g x = fun_of_fin_rec f aTx.
by rewrite -Dg /= (bool_irrelevance (mem_enum _ _) aTx).
elim: (enum aT) / f (enum_uniq aT) => //= x1 s y f IHf /andP[s'x1 Us] in Dg *.
rewrite Dg ?eqxx //=; case: eqP => // /eq_axiomK-> /= _.
rewrite {}IHf // => x s_x; rewrite Dg ?s_x ?orbT //.
by case: eqP (memPn s'x1 x s_x) => // _ _ /(bool_irrelevance s_x) <-.
Qed.
Lemma ffunK : @cancel (finPi aT rT) fT fun_of_fin finfun.
Proof. by move=> f; apply/ffunP=> x; rewrite ffunE. Qed.
Lemma eq_dffun (g1 g2 : forall x, rT x) :
(forall x, g1 x = g2 x) -> finfun g1 = finfun g2.
Proof. by move=> eq_g; apply/ffunP => x; rewrite !ffunE eq_g. Qed.
Definition total_fun g x := Tagged rT (g x : rT x).
Definition tfgraph f := codom_tuple (total_fun f).
Lemma codom_tffun f : codom (total_fun f) = tfgraph f. Proof. by []. Qed.
Local Definition tfgraph_inv (G : #|aT|.-tuple {x : aT & rT x}) : option fT :=
if eqfunP isn't ReflectT Dtg then None else
Some [ffun x => ecast x (rT x) (Dtg x) (tagged (tnth G (enum_rank x)))].
Local Lemma tfgraphK : pcancel tfgraph tfgraph_inv.
Proof.
move=> f; have Dg x: tnth (tfgraph f) (enum_rank x) = total_fun f x.
by rewrite tnth_map -[tnth _ _]enum_val_nth enum_rankK.
rewrite /tfgraph_inv; case: eqfunP => /= [Dtg | [] x]; last by rewrite Dg.
congr (Some _); apply/ffunP=> x; rewrite ffunE.
by rewrite Dg in (Dx := Dtg x) *; rewrite eq_axiomK.
Qed.
Lemma tfgraph_inj : injective tfgraph. Proof. exact: pcan_inj tfgraphK. Qed.
Definition family_mem mF := [pred f : fT | [forall x, in_mem (f x) (mF x)]].
Variables (pT : forall x, predType (rT x)) (F : forall x, pT x).
(* Helper for defining notation for function families. *)
Local Definition fmem F x := mem (F x : pT x).
Lemma familyP f : reflect (forall x, f x \in F x) (f \in family_mem (fmem F)).
Proof. exact: forallP. Qed.
End DepPlainTheory.
Arguments ffunK {aT rT} f : rename.
Arguments ffun0 {aT rT} aT0.
Arguments eq_dffun {aT rT} [g1] g2 eq_g12.
Arguments total_fun {aT rT} g x.
Arguments tfgraph {aT rT} f.
Arguments tfgraphK {aT rT} f : rename.
Arguments tfgraph_inj {aT rT} [f1 f2] : rename.
Arguments fmem {aT rT pT} F x /.
Arguments familyP {aT rT pT F f}.
Notation family F := (family_mem (fmem F)).
Section InheritedStructures.
Variable aT : finType.
Notation dffun_aT rT rS := {dffun forall x : aT, rT x : rS}.
#[hnf] HB.instance Definition _ rT := Equality.copy (dffun_aT rT eqType)
(pcan_type tfgraphK).
#[hnf] HB.instance Definition _ (rT : eqType) :=
Equality.copy {ffun aT -> rT} {dffun forall _, rT}.
#[hnf] HB.instance Definition _ rT := Choice.copy (dffun_aT rT choiceType)
(pcan_type tfgraphK).
#[hnf] HB.instance Definition _ (rT : choiceType) :=
Choice.copy {ffun aT -> rT} {dffun forall _, rT}.
#[hnf] HB.instance Definition _ rT := Countable.copy (dffun_aT rT countType)
(pcan_type tfgraphK).
#[hnf] HB.instance Definition _ (rT : countType) :=
Countable.copy {ffun aT -> rT} {dffun forall _, rT}.
#[hnf] HB.instance Definition _ rT := Finite.copy (dffun_aT rT finType)
(pcan_type tfgraphK).
#[hnf] HB.instance Definition _ (rT : finType) :=
Finite.copy {ffun aT -> rT} {dffun forall _, rT}.
End InheritedStructures.
Section FinFunTuple.
Context {T : Type} {n : nat}.
Definition tuple_of_finfun (f : T ^ n) : n.-tuple T := [tuple f i | i < n].
Definition finfun_of_tuple (t : n.-tuple T) : (T ^ n) := [ffun i => tnth t i].
Lemma finfun_of_tupleK : cancel finfun_of_tuple tuple_of_finfun.
Proof.
by move=> t; apply: eq_from_tnth => i; rewrite tnth_map ffunE tnth_ord_tuple.
Qed.
Lemma tuple_of_finfunK : cancel tuple_of_finfun finfun_of_tuple.
Proof.
by move=> f; apply/ffunP => i; rewrite ffunE tnth_map tnth_ord_tuple.
Qed.
End FinFunTuple.
Section FunPlainTheory.
Variables (aT : finType) (rT : Type).
Notation fT := {ffun aT -> rT}.
Implicit Types (f : fT) (R : pred rT).
Definition fgraph f := codom_tuple f.
Definition Finfun (G : #|aT|.-tuple rT) := [ffun x => tnth G (enum_rank x)].
Lemma tnth_fgraph f i : tnth (fgraph f) i = f (enum_val i).
Proof. by rewrite tnth_map /tnth -enum_val_nth. Qed.
Lemma FinfunK : cancel Finfun fgraph.
Proof.
by move=> G; apply/eq_from_tnth=> i; rewrite tnth_fgraph ffunE enum_valK.
Qed.
Lemma fgraphK : cancel fgraph Finfun.
Proof. by move=> f; apply/ffunP=> x; rewrite ffunE tnth_fgraph enum_rankK. Qed.
Lemma fgraph_ffun0 aT0 : fgraph (ffun0 aT0) = nil :> seq rT.
Proof. by apply/nilP/eqP; rewrite size_tuple. Qed.
Lemma codom_ffun f : codom f = fgraph f. Proof. by []. Qed.
Lemma tagged_tfgraph f : @map _ rT tagged (tfgraph f) = fgraph f.
Proof. by rewrite -map_comp. Qed.
Lemma eq_ffun (g1 g2 : aT -> rT) : g1 =1 g2 -> finfun g1 = finfun g2.
Proof. exact: eq_dffun. Qed.
Lemma fgraph_codom f : fgraph f = codom_tuple f.
Proof. exact/esym/val_inj/codom_ffun. Qed.
Definition ffun_on_mem (mR : mem_pred rT) := family_mem (fun _ : aT => mR).
Lemma ffun_onP R f : reflect (forall x, f x \in R) (f \in ffun_on_mem (mem R)).
Proof. exact: forallP. Qed.
End FunPlainTheory.
Arguments Finfun {aT rT} G.
Arguments fgraph {aT rT} f.
Arguments FinfunK {aT rT} G : rename.
Arguments fgraphK {aT rT} f : rename.
Arguments eq_ffun {aT rT} [g1] g2 eq_g12.
Arguments ffun_onP {aT rT R f}.
Notation ffun_on R := (ffun_on_mem _ (mem R)).
Notation "@ 'ffun_on' aT R" :=
(ffun_on R : simpl_pred (finfun_of (Phant (aT -> id _))))
(at level 10, aT, R at level 9).
Lemma nth_fgraph_ord T n (x0 : T) (i : 'I_n) f : nth x0 (fgraph f) i = f i.
Proof.
by rewrite -[i in RHS]enum_rankK -tnth_fgraph (tnth_nth x0) enum_rank_ord.
Qed.
(*****************************************************************************)
Section Support.
Variables (aT : Type) (rT : eqType).
Definition support_for y (f : aT -> rT) := [pred x | f x != y].
Lemma supportE x y f : (x \in support_for y f) = (f x != y). Proof. by []. Qed.
End Support.
Notation "y .-support" := (support_for y)
(at level 1, format "y .-support") : function_scope.
Section EqTheory.
Variables (aT : finType) (rT : eqType).
Notation fT := {ffun aT -> rT}.
Implicit Types (y : rT) (D : {pred aT}) (R : {pred rT}) (f : fT).
Lemma supportP y D g :
reflect (forall x, x \notin D -> g x = y) (y.-support g \subset D).
Proof.
by (apply: (iffP subsetP) => Dg x; [apply: contraNeq|apply: contraR]) => /Dg->.
Qed.
Definition pfamily_mem y mD (mF : aT -> mem_pred rT) :=
family (fun i : aT => if in_mem i mD then pred_of_simpl (mF i) else pred1 y).
Lemma pfamilyP (pT : predType rT) y D (F : aT -> pT) f :
reflect (y.-support f \subset D /\ {in D, forall x, f x \in F x})
(f \in pfamily_mem y (mem D) (fmem F)).
Proof.
apply: (iffP familyP) => [/= f_pfam | [/supportP f_supp f_fam] x].
split=> [|x Ax]; last by have:= f_pfam x; rewrite Ax.
by apply/subsetP=> x; case: ifP (f_pfam x) => //= _ fx0 /negP[].
by case: ifPn => Ax /=; rewrite inE /= (f_fam, f_supp).
Qed.
Definition pffun_on_mem y mD mR := pfamily_mem y mD (fun _ => mR).
Lemma pffun_onP y D R f :
reflect (y.-support f \subset D /\ {subset image f D <= R})
(f \in pffun_on_mem y (mem D) (mem R)).
Proof.
apply: (iffP (pfamilyP y D (fun _ => R) f)) => [] [-> f_fam]; split=> //.
by move=> _ /imageP[x Ax ->]; apply: f_fam.
by move=> x Ax; apply: f_fam; apply/imageP; exists x.
Qed.
End EqTheory.
Arguments supportP {aT rT y D g}.
Arguments pfamilyP {aT rT pT y D F f}.
Arguments pffun_onP {aT rT y D R f}.
Notation pfamily y D F := (pfamily_mem y (mem D) (fmem F)).
Notation pffun_on y D R := (pffun_on_mem y (mem D) (mem R)).
(*****************************************************************************)
Section FinDepTheory.
Variables (aT : finType) (rT : aT -> finType).
Notation fT := {dffun forall x : aT, rT x}.
Lemma card_family (F : forall x, pred (rT x)) :
#|(family F : simpl_pred fT)| = foldr muln 1 [seq #|F x| | x : aT].
Proof.
rewrite /image_mem; set E := enum aT in (uniqE := enum_uniq aT) *.
have trivF x: x \notin E -> #|F x| = 1 by rewrite mem_enum.
elim: E uniqE => /= [_ | x0 E IH_E /andP[E'x0 uniqE]] in F trivF *.
have /fin_all_exists[f0 Ff0] x: exists y0, F x =i pred1 y0.
have /pred0Pn[y Fy]: #|F x| != 0 by rewrite trivF.
by exists y; apply/fsym/subset_cardP; rewrite ?subset_pred1 // card1 trivF.
apply: eq_card1 (finfun f0 : fT) _ _ => f; apply/familyP/eqP=> [Ff | {f}-> x].
by apply/ffunP=> x; have /[!(Ff0, ffunE)]/eqP := Ff x.
by rewrite ffunE Ff0 inE /=.
have [y0 Fxy0 | Fx00] := pickP (F x0); last first.
by rewrite !eq_card0 // => f; apply: contraFF (Fx00 (f x0))=> /familyP; apply.
pose F1 x := if eqP is ReflectT Dx then xpred1 (ecast x (rT x) Dx y0) else F x.
transitivity (#|[predX F x0 & family F1 : pred fT]|); last first.
rewrite cardX {}IH_E {uniqE}// => [|x E'x]; last first.
rewrite /F1; case: eqP => [Dx | /nesym/eqP-x0'x]; first exact: card1.
by rewrite trivF // negb_or x0'x.
congr (_ * foldr _ _ _); apply/eq_in_map=> x Ex.
by rewrite /F1; case: eqP => // Dx0; rewrite Dx0 Ex in E'x0.
pose g yf : fT := let: (y, f) := yf : rT x0 * fT in
[ffun x => if eqP is ReflectT Dx then ecast x (rT x) Dx y else f x].
have gK: cancel (fun f : fT => (f x0, g (y0, f))) g.
by move=> f; apply/ffunP=> x; rewrite !ffunE; case: eqP => //; case: x /.
rewrite -(card_image (can_inj gK)); apply: eq_card => [] [y f] /=.
apply/imageP/andP=> [[f1 /familyP/=Ff1] [-> ->]| [/=Fx0y /familyP/=Ff]].
split=> //; apply/familyP=> x; rewrite ffunE /F1 /=.
by case: eqP => // Dx; apply: eqxx.
exists (g (y, f)).
by apply/familyP=> x; have:= Ff x; rewrite ffunE /F1; case: eqP; [case: x /|].
congr (_, _); first by rewrite /= ffunE; case: eqP => // Dx; rewrite eq_axiomK.
by apply/ffunP=> x; have:= Ff x; rewrite !ffunE /F1; case: eqP => // Dx /eqP.
Qed.
Lemma card_dep_ffun : #|fT| = foldr muln 1 [seq #|rT x| | x : aT].
Proof. by rewrite -card_family; apply/esym/eq_card=> f; apply/familyP. Qed.
End FinDepTheory.
Section FinFunTheory.
Variables aT rT : finType.
Notation fT := {ffun aT -> rT}.
Implicit Types (D : {pred aT}) (R : {pred rT}) (F : aT -> pred rT).
Lemma card_pfamily y0 D F :
#|pfamily y0 D F| = foldr muln 1 [seq #|F x| | x in D].
Proof.
rewrite card_family !/(image _ _) /(enum D) -enumT /=.
by elim: (enum aT) => //= x E ->; have [// | D'x] := ifP; rewrite card1 mul1n.
Qed.
Lemma card_pffun_on y0 D R : #|pffun_on y0 D R| = #|R| ^ #|D|.
Proof.
rewrite (cardE D) card_pfamily /image_mem.
by elim: (enum D) => //= _ e ->; rewrite expnS.
Qed.
Lemma card_ffun_on R : #|@ffun_on aT R| = #|R| ^ #|aT|.
Proof.
rewrite card_family /image_mem cardT.
by elim: (enum aT) => //= _ e ->; rewrite expnS.
Qed.
Lemma card_ffun : #|fT| = #|rT| ^ #|aT|.
Proof. by rewrite -card_ffun_on; apply/esym/eq_card=> f; apply/forallP. Qed.
End FinFunTheory.
Section DependentFiniteProduct.
Variables (I : finType) (T_ : I -> finType).
Notation fprod_type := (forall i : I, T_ i) (only parsing).
(* Definition of [fprod] := dependent product of finTypes *)
Record fprod : predArgType := FProd
{ fprod_fun : {ffun I -> {i : I & T_ i}} ;
fprod_prop : [forall i : I, tag (fprod_fun i) == i] }.
Lemma tag_fprod_fun (f : fprod) i : tag (fprod_fun f i) = i.
Proof. by have /'forall_eqP/(_ i) := fprod_prop f. Qed.
Definition fun_of_fprod (f : fprod) : fprod_type :=
fun i => etagged ('forall_eqP (fprod_prop f) i).
Coercion fun_of_fprod : fprod >-> Funclass.
#[hnf] HB.instance Definition _ := [isSub for fprod_fun].
#[hnf] HB.instance Definition _ := [Finite of fprod by <:].
Lemma fprod_of_prod_type_subproof (f : fprod_type) :
[forall i : I, tag ([ffun i => Tagged T_ (f i)] i) == i].
Proof. by apply/'forall_eqP => i /=; rewrite ffunE. Qed.
Definition fprod_of_fun (f : fprod_type) : fprod :=
FProd (fprod_of_prod_type_subproof f).
Lemma fprodK : cancel fun_of_fprod fprod_of_fun.
Proof.
rewrite /fun_of_fprod /fprod_of_fun; case=> f fP.
by apply/val_inj/ffunP => i /=; rewrite !ffunE etaggedK.
Qed.
Lemma fprodE g i : fprod_of_fun g i = g i.
Proof.
rewrite /fprod_of_fun /fun_of_fprod/=.
by move: ('forall_eqP _ _); rewrite ffunE/= => e; rewrite eq_axiomK.
Qed.
Lemma fprodP (f1 f2 : fprod) : (forall x, f1 x = f2 x) <-> f1 = f2.
Proof.
split=> [eq_f12|->//]; rewrite -[f1]fprodK -[f2]fprodK.
by apply/val_inj/ffunP => i; rewrite !ffunE eq_f12.
Qed.
Definition dffun_of_fprod (f : fprod) : {dffun forall i : I, T_ i} :=
[ffun x => f x].
Definition fprod_of_dffun (f : {dffun forall i : I, T_ i}) : fprod :=
fprod_of_fun f.
Lemma dffun_of_fprodK : cancel dffun_of_fprod fprod_of_dffun.
Proof. by move=> f; apply/fprodP=> i; rewrite fprodE ffunE. Qed.
#[local] Hint Resolve dffun_of_fprodK : core.
Lemma fprod_of_dffunK : cancel fprod_of_dffun dffun_of_fprod.
Proof. by move=> f; apply/ffunP => i; rewrite !ffunE fprodE. Qed.
#[local] Hint Resolve fprod_of_dffunK : core.
Lemma dffun_of_fprod_bij : bijective dffun_of_fprod.
Proof. by exists fprod_of_dffun. Qed.
Lemma fprod_of_dffun_bij : bijective fprod_of_dffun.
Proof. by exists dffun_of_fprod. Qed.
Definition to_family_tagged_with (f : fprod) : {x in family (tagged_with T_)} :=
exist _ (fprod_fun f) (fprod_prop f).
Definition of_family_tagged_with (f : {x in family (tagged_with T_)}) : fprod :=
FProd (valP f).
Lemma to_family_tagged_withK :
cancel to_family_tagged_with of_family_tagged_with.
Proof. by case=> f fP; apply/val_inj. Qed.
#[local] Hint Resolve to_family_tagged_withK : core.
Lemma of_family_tagged_withK :
cancel of_family_tagged_with to_family_tagged_with.
Proof. by case=> f fP; apply/val_inj. Qed.
#[local] Hint Resolve of_family_tagged_withK : core.
Lemma to_family_tagged_with_bij : bijective to_family_tagged_with.
Proof. by exists of_family_tagged_with. Qed.
Lemma of_family_tagged_with_bij : bijective of_family_tagged_with.
Proof. by exists to_family_tagged_with. Qed.
Lemma etaggedE (a : fprod) (i : I) (e : tag (fprod_fun a i) = i) :
etagged e = a i.
Proof. by case: a e => //= f fP e; congr etagged; apply: eq_irrelevance. Qed.
End DependentFiniteProduct.
Arguments to_family_tagged_with {I T_}.
Arguments of_family_tagged_with {I T_}.
Notation "[ 'fprod' i : I => F ]" := (fprod_of_fun (fun i : I => F))
(i name, only parsing) : function_scope.
Notation "[ 'fprod' : I => F ]" := (fprod_of_fun (fun _ : I => F))
(only parsing) : function_scope.
Notation "[ 'fprod' i => F ]" := [fprod i : _ => F]
(i name, format "[ 'fprod' i => F ]") : function_scope.
Notation "[ 'fprod' => F ]" := [fprod : _ => F]
(format "[ 'fprod' => F ]") : function_scope.
|
LaxMilgram.lean
|
/-
Copyright (c) 2022 Daniel Roca González. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Roca González
-/
import Mathlib.Analysis.InnerProductSpace.Dual
/-!
# The Lax-Milgram Theorem
We consider a Hilbert space `V` over `ℝ`
equipped with a bounded bilinear form `B : V →L[ℝ] V →L[ℝ] ℝ`.
Recall that a bilinear form `B : V →L[ℝ] V →L[ℝ] ℝ` is *coercive*
iff `∃ C, (0 < C) ∧ ∀ u, C * ‖u‖ * ‖u‖ ≤ B u u`.
Under the hypothesis that `B` is coercive we prove the Lax-Milgram theorem:
that is, the map `InnerProductSpace.continuousLinearMapOfBilin` from
`Analysis.InnerProductSpace.Dual` can be upgraded to a continuous equivalence
`IsCoercive.continuousLinearEquivOfBilin : V ≃L[ℝ] V`.
## References
* We follow the notes of Peter Howard's Spring 2020 *M612: Partial Differential Equations* lecture,
see[howard]
## Tags
dual, Lax-Milgram
-/
noncomputable section
open RCLike LinearMap ContinuousLinearMap InnerProductSpace
open LinearMap (ker range)
open RealInnerProductSpace NNReal
universe u
namespace IsCoercive
variable {V : Type u} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [CompleteSpace V]
variable {B : V →L[ℝ] V →L[ℝ] ℝ}
local postfix:1024 "♯" => continuousLinearMapOfBilin (𝕜 := ℝ)
theorem bounded_below (coercive : IsCoercive B) : ∃ C, 0 < C ∧ ∀ v, C * ‖v‖ ≤ ‖B♯ v‖ := by
rcases coercive with ⟨C, C_ge_0, coercivity⟩
refine ⟨C, C_ge_0, ?_⟩
intro v
by_cases h : 0 < ‖v‖
· refine (mul_le_mul_right h).mp ?_
calc
C * ‖v‖ * ‖v‖ ≤ B v v := coercivity v
_ = ⟪B♯ v, v⟫_ℝ := (continuousLinearMapOfBilin_apply B v v).symm
_ ≤ ‖B♯ v‖ * ‖v‖ := real_inner_le_norm (B♯ v) v
· have : v = 0 := by simpa using h
simp [this]
theorem antilipschitz (coercive : IsCoercive B) : ∃ C : ℝ≥0, 0 < C ∧ AntilipschitzWith C B♯ := by
rcases coercive.bounded_below with ⟨C, C_pos, below_bound⟩
refine ⟨C⁻¹.toNNReal, Real.toNNReal_pos.mpr (inv_pos.mpr C_pos), ?_⟩
refine ContinuousLinearMap.antilipschitz_of_bound B♯ ?_
simp_rw [Real.coe_toNNReal', max_eq_left_of_lt (inv_pos.mpr C_pos), ←
inv_mul_le_iff₀ (inv_pos.mpr C_pos)]
simpa using below_bound
theorem ker_eq_bot (coercive : IsCoercive B) : ker B♯ = ⊥ := by
rw [LinearMapClass.ker_eq_bot]
rcases coercive.antilipschitz with ⟨_, _, antilipschitz⟩
exact antilipschitz.injective
theorem isClosed_range (coercive : IsCoercive B) : IsClosed (range B♯ : Set V) := by
rcases coercive.antilipschitz with ⟨_, _, antilipschitz⟩
exact antilipschitz.isClosed_range B♯.uniformContinuous
theorem range_eq_top (coercive : IsCoercive B) : range B♯ = ⊤ := by
haveI := coercive.isClosed_range.completeSpace_coe
rw [← (range B♯).orthogonal_orthogonal]
rw [Submodule.eq_top_iff']
intro v w mem_w_orthogonal
rcases coercive with ⟨C, C_pos, coercivity⟩
obtain rfl : w = 0 := by
rw [← norm_eq_zero, ← mul_self_eq_zero, ← mul_right_inj' C_pos.ne', mul_zero, ←
mul_assoc]
apply le_antisymm
· calc
C * ‖w‖ * ‖w‖ ≤ B w w := coercivity w
_ = ⟪B♯ w, w⟫_ℝ := (continuousLinearMapOfBilin_apply B w w).symm
_ = 0 := mem_w_orthogonal _ ⟨w, rfl⟩
· positivity
exact inner_zero_left _
/-- The Lax-Milgram equivalence of a coercive bounded bilinear operator:
for all `v : V`, `continuousLinearEquivOfBilin B v` is the unique element `V`
such that `continuousLinearEquivOfBilin B v, w⟫ = B v w`.
The Lax-Milgram theorem states that this is a continuous equivalence.
-/
def continuousLinearEquivOfBilin (coercive : IsCoercive B) : V ≃L[ℝ] V :=
ContinuousLinearEquiv.ofBijective B♯ coercive.ker_eq_bot coercive.range_eq_top
@[simp]
theorem continuousLinearEquivOfBilin_apply (coercive : IsCoercive B) (v w : V) :
⟪coercive.continuousLinearEquivOfBilin v, w⟫_ℝ = B v w :=
continuousLinearMapOfBilin_apply B v w
theorem unique_continuousLinearEquivOfBilin (coercive : IsCoercive B) {v f : V}
(is_lax_milgram : ∀ w, ⟪f, w⟫_ℝ = B v w) : f = coercive.continuousLinearEquivOfBilin v :=
unique_continuousLinearMapOfBilin B is_lax_milgram
end IsCoercive
|
Matching.lean
|
/-
Copyright (c) 2020 Alena Gusakov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alena Gusakov, Arthur Paulino, Kyle Miller, Pim Otte
-/
import Mathlib.Combinatorics.SimpleGraph.Clique
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Subgraph
import Mathlib.Combinatorics.SimpleGraph.Connectivity.WalkCounting
import Mathlib.Combinatorics.SimpleGraph.DegreeSum
import Mathlib.Combinatorics.SimpleGraph.Operations
import Mathlib.Data.Set.Card.Arithmetic
import Mathlib.Data.Set.Functor
/-!
# Matchings
A *matching* for a simple graph is a set of disjoint pairs of adjacent vertices, and the set of all
the vertices in a matching is called its *support* (and sometimes the vertices in the support are
said to be *saturated* by the matching). A *perfect matching* is a matching whose support contains
every vertex of the graph.
In this module, we represent a matching as a subgraph whose vertices are each incident to at most
one edge, and the edges of the subgraph represent the paired vertices.
## Main definitions
* `SimpleGraph.Subgraph.IsMatching`: `M.IsMatching` means that `M` is a matching of its
underlying graph.
* `SimpleGraph.Subgraph.IsPerfectMatching` defines when a subgraph `M` of a simple graph is a
perfect matching, denoted `M.IsPerfectMatching`.
* `SimpleGraph.IsMatchingFree` means that a graph `G` has no perfect matchings.
* `SimpleGraph.IsCycles` means that a graph consists of cycles (including cycles of length 0,
also known as isolated vertices)
* `SimpleGraph.IsAlternating` means that edges in a graph `G` are alternatingly
included and not included in some other graph `G'`
## TODO
* Define an `other` function and prove useful results about it (https://leanprover.zulipchat.com/#narrow/stream/252551-graph-theory/topic/matchings/near/266205863)
* Provide a bicoloring for matchings (https://leanprover.zulipchat.com/#narrow/stream/252551-graph-theory/topic/matchings/near/265495120)
* Tutte's Theorem
* Hall's Marriage Theorem (see `Mathlib/Combinatorics/Hall/Basic.lean`)
-/
assert_not_exists Field TwoSidedIdeal
open Function
namespace SimpleGraph
variable {V W : Type*} {G G' : SimpleGraph V} {M M' : Subgraph G} {u v w : V}
namespace Subgraph
/--
The subgraph `M` of `G` is a matching if every vertex of `M` is incident to exactly one edge in `M`.
We say that the vertices in `M.support` are *matched* or *saturated*.
-/
def IsMatching (M : Subgraph G) : Prop := ∀ ⦃v⦄, v ∈ M.verts → ∃! w, M.Adj v w
/-- Given a vertex, returns the unique edge of the matching it is incident to. -/
noncomputable def IsMatching.toEdge (h : M.IsMatching) (v : M.verts) : M.edgeSet :=
⟨s(v, (h v.property).choose), (h v.property).choose_spec.1⟩
theorem IsMatching.toEdge_eq_of_adj (h : M.IsMatching) (hv : v ∈ M.verts) (hvw : M.Adj v w) :
h.toEdge ⟨v, hv⟩ = ⟨s(v, w), hvw⟩ := by
simp only [IsMatching.toEdge, Subtype.mk_eq_mk]
congr
exact ((h (M.edge_vert hvw)).choose_spec.2 w hvw).symm
theorem IsMatching.toEdge.surjective (h : M.IsMatching) : Surjective h.toEdge := by
rintro ⟨⟨x, y⟩, he⟩
exact ⟨⟨x, M.edge_vert he⟩, h.toEdge_eq_of_adj _ he⟩
theorem IsMatching.toEdge_eq_toEdge_of_adj (h : M.IsMatching)
(hv : v ∈ M.verts) (hw : w ∈ M.verts) (ha : M.Adj v w) :
h.toEdge ⟨v, hv⟩ = h.toEdge ⟨w, hw⟩ := by
rw [h.toEdge_eq_of_adj hv ha, h.toEdge_eq_of_adj hw (M.symm ha), Subtype.mk_eq_mk, Sym2.eq_swap]
lemma IsMatching.map_ofLE (h : M.IsMatching) (hGG' : G ≤ G') :
(M.map (Hom.ofLE hGG')).IsMatching := by
intro _ hv
obtain ⟨_, hv, hv'⟩ := Set.mem_image _ _ _ |>.mp hv
obtain ⟨w, hw⟩ := h hv
use w
simpa using hv' ▸ hw
lemma IsMatching.eq_of_adj_left (hM : M.IsMatching) (huv : M.Adj u v) (huw : M.Adj u w) : v = w :=
(hM <| M.edge_vert huv).unique huv huw
lemma IsMatching.eq_of_adj_right (hM : M.IsMatching) (huw : M.Adj u w) (hvw : M.Adj v w) : u = v :=
hM.eq_of_adj_left huw.symm hvw.symm
lemma IsMatching.not_adj_left_of_ne (hM : M.IsMatching) (hvw : v ≠ w) (huv : M.Adj u v) :
¬M.Adj u w := fun huw ↦ hvw <| hM.eq_of_adj_left huv huw
lemma IsMatching.not_adj_right_of_ne (hM : M.IsMatching) (huv : u ≠ v) (huw : M.Adj u w) :
¬M.Adj v w := fun hvw ↦ huv <| hM.eq_of_adj_right huw hvw
lemma IsMatching.sup (hM : M.IsMatching) (hM' : M'.IsMatching)
(hd : Disjoint M.support M'.support) : (M ⊔ M').IsMatching := by
intro v hv
have aux {N N' : Subgraph G} (hN : N.IsMatching) (hd : Disjoint N.support N'.support)
(hmN: v ∈ N.verts) : ∃! w, (N ⊔ N').Adj v w := by
obtain ⟨w, hw⟩ := hN hmN
use w
refine ⟨sup_adj.mpr (.inl hw.1), ?_⟩
intro y hy
cases hy with
| inl h => exact hw.2 y h
| inr h =>
rw [Set.disjoint_left] at hd
simpa [(mem_support _).mpr ⟨w, hw.1⟩, (mem_support _).mpr ⟨y, h⟩] using @hd v
cases Set.mem_or_mem_of_mem_union hv with
| inl hmM => exact aux hM hd hmM
| inr hmM' =>
rw [sup_comm]
exact aux hM' (Disjoint.symm hd) hmM'
lemma IsMatching.iSup {ι : Sort _} {f : ι → Subgraph G} (hM : (i : ι) → (f i).IsMatching)
(hd : Pairwise fun i j ↦ Disjoint (f i).support (f j).support) :
(⨆ i, f i).IsMatching := by
intro v hv
obtain ⟨i , hi⟩ := Set.mem_iUnion.mp (verts_iSup ▸ hv)
obtain ⟨w , hw⟩ := hM i hi
use w
refine ⟨iSup_adj.mpr ⟨i, hw.1⟩, ?_⟩
intro y hy
obtain ⟨i' , hi'⟩ := iSup_adj.mp hy
by_cases heq : i = i'
· exact hw.2 y (heq.symm ▸ hi')
· have := hd heq
simp only [Set.disjoint_left] at this
simpa [(mem_support _).mpr ⟨w, hw.1⟩, (mem_support _).mpr ⟨y, hi'⟩] using @this v
lemma IsMatching.subgraphOfAdj (h : G.Adj v w) : (G.subgraphOfAdj h).IsMatching := by
intro _ hv
rw [subgraphOfAdj_verts, Set.mem_insert_iff, Set.mem_singleton_iff] at hv
cases hv with
| inl => use w; aesop
| inr => use v; aesop
lemma IsMatching.coeSubgraph {G' : Subgraph G} {M : Subgraph G'.coe} (hM : M.IsMatching) :
(Subgraph.coeSubgraph M).IsMatching := by
intro _ hv
obtain ⟨w, hw⟩ := hM <| Set.mem_of_mem_image_val <| (Subgraph.verts_coeSubgraph M).symm ▸ hv
use w
refine ⟨?_, fun y hy => ?_⟩
· obtain ⟨v, hv⟩ := (Set.mem_image _ _ _).mp <| (Subgraph.verts_coeSubgraph M).symm ▸ hv
simp only [coeSubgraph_adj, Subtype.coe_eta, Subtype.coe_prop, exists_const]
exact ⟨hv.2 ▸ v.2, hw.1⟩
· obtain ⟨_, hw', hvw⟩ := (coeSubgraph_adj _ _ _).mp hy
rw [← hw.2 ⟨y, hw'⟩ hvw]
lemma IsMatching.exists_of_disjoint_sets_of_equiv {s t : Set V} (h : Disjoint s t)
(f : s ≃ t) (hadj : ∀ v : s, G.Adj v (f v)) :
∃ M : Subgraph G, M.verts = s ∪ t ∧ M.IsMatching := by
use {
verts := s ∪ t
Adj := fun v w ↦ (∃ h : v ∈ s, f ⟨v, h⟩ = w) ∨ (∃ h : w ∈ s, f ⟨w, h⟩ = v)
adj_sub := by
intro v w h
obtain (⟨hv, rfl⟩ | ⟨hw, rfl⟩) := h
· exact hadj ⟨v, _⟩
· exact (hadj ⟨w, _⟩).symm
edge_vert := by aesop }
simp only [Subgraph.IsMatching, Set.mem_union, true_and]
intro v hv
rcases hv with hl | hr
· use f ⟨v, hl⟩
simp only [hl, exists_const, true_or, exists_true_left, true_and]
rintro y (rfl | ⟨hys, rfl⟩)
· rfl
· exact (h.ne_of_mem hl (f ⟨y, hys⟩).coe_prop rfl).elim
· use f.symm ⟨v, hr⟩
simp only [Subtype.coe_eta, Equiv.apply_symm_apply, Subtype.coe_prop, exists_const, or_true,
true_and]
rintro y (⟨hy, rfl⟩ | ⟨hy, rfl⟩)
· exact (h.ne_of_mem hy hr rfl).elim
· simp
protected lemma IsMatching.map {G' : SimpleGraph W} {M : Subgraph G} (f : G →g G')
(hf : Injective f) (hM : M.IsMatching) : (M.map f).IsMatching := by
rintro _ ⟨v, hv, rfl⟩
obtain ⟨v', hv'⟩ := hM hv
use f v'
refine ⟨⟨v, v', hv'.1, rfl, rfl⟩, ?_⟩
rintro _ ⟨w, w', hw, hw', rfl⟩
cases hf hw'.symm
rw [hv'.2 w' hw]
@[simp]
lemma Iso.isMatching_map {G' : SimpleGraph W} {M : Subgraph G} (f : G ≃g G') :
(M.map f.toHom).IsMatching ↔ M.IsMatching where
mp h := by simpa [← map_comp] using h.map f.symm.toHom f.symm.injective
mpr := .map f.toHom f.injective
/--
The subgraph `M` of `G` is a perfect matching on `G` if it's a matching and every vertex `G` is
matched.
-/
def IsPerfectMatching (M : G.Subgraph) : Prop := M.IsMatching ∧ M.IsSpanning
theorem IsMatching.support_eq_verts (h : M.IsMatching) : M.support = M.verts := by
refine M.support_subset_verts.antisymm fun v hv => ?_
obtain ⟨w, hvw, -⟩ := h hv
exact ⟨_, hvw⟩
theorem isMatching_iff_forall_degree [∀ v, Fintype (M.neighborSet v)] :
M.IsMatching ↔ ∀ v : V, v ∈ M.verts → M.degree v = 1 := by
simp only [degree_eq_one_iff_unique_adj, IsMatching]
theorem IsMatching.even_card [Fintype M.verts] (h : M.IsMatching) : Even M.verts.toFinset.card := by
classical
rw [isMatching_iff_forall_degree] at h
use M.coe.edgeFinset.card
rw [← two_mul, ← M.coe.sum_degrees_eq_twice_card_edges]
-- Porting note: `SimpleGraph.Subgraph.coe_degree` does not trigger because it uses
-- instance arguments instead of implicit arguments for the first `Fintype` argument.
-- Using a `convert_to` to swap out the `Fintype` instance to the "right" one.
convert_to _ = Finset.sum Finset.univ fun v => SimpleGraph.degree (Subgraph.coe M) v using 3
simp [h, Finset.card_univ]
theorem isPerfectMatching_iff : M.IsPerfectMatching ↔ ∀ v, ∃! w, M.Adj v w := by
refine ⟨?_, fun hm => ⟨fun v _ => hm v, fun v => ?_⟩⟩
· rintro ⟨hm, hs⟩ v
exact hm (hs v)
· obtain ⟨w, hw, -⟩ := hm v
exact M.edge_vert hw
theorem isPerfectMatching_iff_forall_degree [∀ v, Fintype (M.neighborSet v)] :
M.IsPerfectMatching ↔ ∀ v, M.degree v = 1 := by
simp [degree_eq_one_iff_unique_adj, isPerfectMatching_iff]
theorem IsPerfectMatching.even_card [Fintype V] (h : M.IsPerfectMatching) :
Even (Fintype.card V) := by
classical
simpa only [h.2.card_verts] using IsMatching.even_card h.1
lemma IsMatching.induce_connectedComponent (h : M.IsMatching) (c : ConnectedComponent G) :
(M.induce (M.verts ∩ c.supp)).IsMatching := by
intro _ hv
obtain ⟨hv, rfl⟩ := hv
obtain ⟨w, hvw, hw⟩ := h hv
use w
simpa [hv, hvw, M.edge_vert hvw.symm, (M.adj_sub hvw).symm.reachable] using fun _ _ _ ↦ hw _
lemma IsPerfectMatching.induce_connectedComponent_isMatching (h : M.IsPerfectMatching)
(c : ConnectedComponent G) : (M.induce c.supp).IsMatching := by
simpa [h.2.verts_eq_univ] using h.1.induce_connectedComponent c
@[simp]
lemma IsPerfectMatching.toSubgraph_iff (h : M.spanningCoe ≤ G') :
(G'.toSubgraph M.spanningCoe h).IsPerfectMatching ↔ M.IsPerfectMatching := by
simp only [isPerfectMatching_iff, toSubgraph_adj, spanningCoe_adj]
end Subgraph
lemma IsClique.even_iff_exists_isMatching {u : Set V} (hc : G.IsClique u)
(hu : u.Finite) : Even u.ncard ↔ ∃ (M : Subgraph G), M.verts = u ∧ M.IsMatching := by
refine ⟨fun h ↦ ?_, by
rintro ⟨M, rfl, hMr⟩
simpa [Set.ncard_eq_toFinset_card _ hu, Set.toFinite_toFinset,
← Set.toFinset_card] using @hMr.even_card _ _ _ hu.fintype⟩
obtain ⟨t, u, rfl, hd, hcard⟩ := Set.exists_union_disjoint_ncard_eq_of_even h
obtain ⟨f⟩ : Nonempty (t ≃ u) := by
rw [← Cardinal.eq, ← t.cast_ncard (Set.finite_union.mp hu).1,
← u.cast_ncard (Set.finite_union.mp hu).2]
exact congrArg Nat.cast hcard
exact Subgraph.IsMatching.exists_of_disjoint_sets_of_equiv hd f
fun v ↦ hc (by simp) (by simp) <| hd.ne_of_mem (by simp) (by simp)
namespace ConnectedComponent
section Finite
lemma even_card_of_isPerfectMatching [Fintype V] [DecidableEq V] [DecidableRel G.Adj]
(c : ConnectedComponent G) (hM : M.IsPerfectMatching) :
Even (Fintype.card c.supp) := by
#adaptation_note /-- https://github.com/leanprover/lean4/pull/5020
some instances that use the chain of coercions
`[SetLike X], X → Set α → Sort _` are
blocked by the discrimination tree. This can be fixed by redeclaring the instance for `X`
using the double coercion but the proper fix seems to avoid the double coercion. -/
letI : DecidablePred fun x ↦ x ∈ (M.induce c.supp).verts := fun a ↦ G.instDecidableMemSupp c a
simpa using (hM.induce_connectedComponent_isMatching c).even_card
lemma odd_matches_node_outside [Finite V] {u : Set V}
(hM : M.IsPerfectMatching) (c : (Subgraph.deleteVerts ⊤ u).coe.oddComponents) :
∃ᵉ (w ∈ u) (v : ((⊤ : G.Subgraph).deleteVerts u).verts), M.Adj v w ∧ v ∈ c.val.supp := by
by_contra! h
have hMmatch : (M.induce c.val.supp).IsMatching := by
intro v hv
obtain ⟨w, hw⟩ := hM.1 (hM.2 v)
obtain ⟨⟨v', hv'⟩, ⟨hv , rfl⟩⟩ := hv
use w
have hwnu : w ∉ u := fun hw' ↦ h w hw' ⟨v', hv'⟩ (hw.1) hv
refine ⟨⟨⟨⟨v', hv'⟩, hv, rfl⟩, ?_, hw.1⟩, fun _ hy ↦ hw.2 _ hy.2.2⟩
apply ConnectedComponent.mem_coe_supp_of_adj ⟨⟨v', hv'⟩, ⟨hv, rfl⟩⟩ ⟨by trivial, hwnu⟩
simp only [Subgraph.induce_verts, Subgraph.verts_top, Set.mem_diff, Set.mem_univ, true_and,
Subgraph.induce_adj, hwnu, not_false_eq_true, and_self, Subgraph.top_adj, M.adj_sub hw.1,
and_true] at hv' ⊢
trivial
apply Nat.not_even_iff_odd.2 c.prop
haveI : Fintype ↑(Subgraph.induce M (Subtype.val '' supp c.val)).verts := Fintype.ofFinite _
classical
haveI : Fintype (c.val.supp) := Fintype.ofFinite _
simpa [Subgraph.induce_verts, Subgraph.verts_top, Nat.card_eq_fintype_card, Set.toFinset_card,
Finset.card_image_of_injective, ← Nat.card_coe_set_eq] using hMmatch.even_card
end Finite
end ConnectedComponent
/--
A graph is matching free if it has no perfect matching. It does not make much sense to
consider a graph being free of just matchings, because any non-trivial graph has those.
-/
def IsMatchingFree (G : SimpleGraph V) := ∀ M : Subgraph G, ¬ M.IsPerfectMatching
lemma IsMatchingFree.mono {G G' : SimpleGraph V} (h : G ≤ G') (hmf : G'.IsMatchingFree) :
G.IsMatchingFree := by
intro x
by_contra! hc
apply hmf (x.map (SimpleGraph.Hom.ofLE h))
refine ⟨hc.1.map_ofLE h, ?_⟩
intro v
simp only [Subgraph.map_verts, Hom.coe_ofLE, id_eq, Set.image_id']
exact hc.2 v
lemma exists_maximal_isMatchingFree [Finite V] (h : G.IsMatchingFree) :
∃ Gmax : SimpleGraph V, G ≤ Gmax ∧ Gmax.IsMatchingFree ∧
∀ G', G' > Gmax → ∃ M : Subgraph G', M.IsPerfectMatching := by
simp_rw [← @not_forall_not _ Subgraph.IsPerfectMatching]
obtain ⟨Gmax, hGmax⟩ := Finite.exists_le_maximal h
exact ⟨Gmax, ⟨hGmax.1, ⟨hGmax.2.prop, fun _ h' ↦ hGmax.2.not_prop_of_gt h'⟩⟩⟩
/-- A graph `G` consists of a set of cycles, if each vertex is either isolated or connected to
exactly two vertices. This is used to create new matchings by taking the `symmDiff` with cycles.
The definition of `symmDiff` that makes sense is the one for `SimpleGraph`. The `symmDiff`
for `SimpleGraph.Subgraph` deriving from the lattice structure also affects the vertices included,
which we do not want in this case. This is why this property is defined for `SimpleGraph`, rather
than `SimpleGraph.Subgraph`.
-/
def IsCycles (G : SimpleGraph V) := ∀ ⦃v⦄, (G.neighborSet v).Nonempty → (G.neighborSet v).ncard = 2
/--
Given a vertex with one edge in a graph of cycles this gives the other edge incident
to the same vertex.
-/
lemma IsCycles.other_adj_of_adj (h : G.IsCycles) (hadj : G.Adj v w) :
∃ w', w ≠ w' ∧ G.Adj v w' := by
simp_rw [← SimpleGraph.mem_neighborSet] at hadj ⊢
have := h ⟨w, hadj⟩
obtain ⟨w', hww'⟩ := (G.neighborSet v).exists_ne_of_one_lt_ncard (by omega) w
exact ⟨w', ⟨hww'.2.symm, hww'.1⟩⟩
lemma IsCycles.existsUnique_ne_adj (h : G.IsCycles) (hadj : G.Adj v w) :
∃! w', w ≠ w' ∧ G.Adj v w' := by
obtain ⟨w', ⟨hww, hww'⟩⟩ := h.other_adj_of_adj hadj
use w'
refine ⟨⟨hww, hww'⟩, ?_⟩
intro y ⟨hwy, hwy'⟩
obtain ⟨x, y', hxy'⟩ := Set.ncard_eq_two.mp (h ⟨w, hadj⟩)
simp_rw [← SimpleGraph.mem_neighborSet] at *
aesop
lemma IsCycles.toSimpleGraph (c : G.ConnectedComponent) (h : G.IsCycles) :
c.toSimpleGraph.spanningCoe.IsCycles := by
intro v ⟨w, hw⟩
rw [mem_neighborSet, c.adj_spanningCoe_toSimpleGraph] at hw
rw [← h ⟨w, hw.2⟩]
congr 1
ext w'
simp only [mem_neighborSet, c.adj_spanningCoe_toSimpleGraph, hw, true_and]
@[deprecated (since := "2025-06-08")] alias IsCycles.induce_supp := IsCycles.toSimpleGraph
lemma Walk.IsCycle.isCycles_spanningCoe_toSubgraph {u : V} {p : G.Walk u u} (hpc : p.IsCycle) :
p.toSubgraph.spanningCoe.IsCycles := by
intro v hv
apply hpc.ncard_neighborSet_toSubgraph_eq_two
obtain ⟨_, hw⟩ := hv
exact p.mem_verts_toSubgraph.mp <| p.toSubgraph.edge_vert hw
lemma Walk.IsPath.isCycles_spanningCoe_toSubgraph_sup_edge {u v} {p : G.Walk u v} (hp : p.IsPath)
(h : u ≠ v) (hs : s(v, u) ∉ p.edges) : (p.toSubgraph.spanningCoe ⊔ edge v u).IsCycles := by
let c := (p.mapLe (OrderTop.le_top G)).cons (by simp [h.symm] : (completeGraph V).Adj v u)
have : p.toSubgraph.spanningCoe ⊔ edge v u = c.toSubgraph.spanningCoe := by
ext w x
simp only [sup_adj, Subgraph.spanningCoe_adj, completeGraph_eq_top, edge_adj, c,
Walk.toSubgraph, Subgraph.sup_adj, subgraphOfAdj_adj, adj_toSubgraph_mapLe]
aesop
exact this ▸ IsCycle.isCycles_spanningCoe_toSubgraph (by simp [Walk.cons_isCycle_iff, c, hp, hs])
lemma Walk.IsCycle.adj_toSubgraph_iff_of_isCycles [LocallyFinite G] {u} {p : G.Walk u u}
(hp : p.IsCycle) (hcyc : G.IsCycles) (hv : v ∈ p.toSubgraph.verts) :
∀ w, p.toSubgraph.Adj v w ↔ G.Adj v w := by
refine fun w ↦ Subgraph.adj_iff_of_neighborSet_equiv (?_ : Inhabited _).default (Set.toFinite _)
apply Classical.inhabited_of_nonempty
rw [← Cardinal.eq, ← Set.cast_ncard (Set.toFinite _),
← Set.cast_ncard (finite_neighborSet_toSubgraph p), hcyc
(Set.Nonempty.mono (p.toSubgraph.neighborSet_subset v) <|
Set.nonempty_of_ncard_ne_zero <| by simp [
hp.ncard_neighborSet_toSubgraph_eq_two (by aesop)]),
hp.ncard_neighborSet_toSubgraph_eq_two (by aesop)]
open scoped symmDiff
lemma Subgraph.IsPerfectMatching.symmDiff_isCycles
{M : Subgraph G} {M' : Subgraph G'} (hM : M.IsPerfectMatching)
(hM' : M'.IsPerfectMatching) : (M.spanningCoe ∆ M'.spanningCoe).IsCycles := by
intro v
obtain ⟨w, hw⟩ := hM.1 (hM.2 v)
obtain ⟨w', hw'⟩ := hM'.1 (hM'.2 v)
simp only [symmDiff_def, Set.ncard_eq_two, ne_eq, imp_iff_not_or, Set.not_nonempty_iff_eq_empty,
Set.eq_empty_iff_forall_notMem, SimpleGraph.mem_neighborSet, SimpleGraph.sup_adj, sdiff_adj,
spanningCoe_adj, not_or, not_and, not_not]
by_cases hww' : w = w'
· simp_all [← imp_iff_not_or]
· right
use w, w'
aesop
lemma IsCycles.snd_of_mem_support_of_isPath_of_adj [Finite V] {v w w' : V}
(hcyc : G.IsCycles) (p : G.Walk v w) (hw : w ≠ w') (hw' : w' ∈ p.support) (hp : p.IsPath)
(hadj : G.Adj v w') : p.snd = w' := by
classical
apply hp.snd_of_toSubgraph_adj
rw [Walk.mem_support_iff_exists_getVert] at hw'
obtain ⟨n, ⟨rfl, hnl⟩⟩ := hw'
by_cases hn : n = 0 ∨ n = p.length
· aesop
have e : G.neighborSet (p.getVert n) ≃ p.toSubgraph.neighborSet (p.getVert n) := by
refine @Classical.ofNonempty _ ?_
rw [← Cardinal.eq, ← Set.cast_ncard (Set.toFinite _), ← Set.cast_ncard (Set.toFinite _),
hp.ncard_neighborSet_toSubgraph_internal_eq_two (by omega) (by omega),
hcyc (Set.nonempty_of_mem hadj.symm)]
rw [Subgraph.adj_comm, Subgraph.adj_iff_of_neighborSet_equiv e (Set.toFinite _)]
exact hadj.symm
private lemma IsCycles.reachable_sdiff_toSubgraph_spanningCoe_aux [Fintype V] {v w : V}
(hcyc : G.IsCycles) (p : G.Walk v w) (hp : p.IsPath) :
(G \ p.toSubgraph.spanningCoe).Reachable w v := by
classical
-- Consider the case when p is nil
by_cases hvw : v = w
· subst hvw
use .nil
have hpn : ¬p.Nil := Walk.not_nil_of_ne hvw
obtain ⟨w', ⟨hw'1, hw'2⟩, hwu⟩ := hcyc.existsUnique_ne_adj
(p.toSubgraph_adj_snd hpn).adj_sub
-- The edge (v, w) can't be in p, because then it would be the second node
have hnpvw' : ¬ p.toSubgraph.Adj v w' := by
intro h
exact hw'1 (hp.snd_of_toSubgraph_adj h)
-- If w = w', then then the reachability can be proved with just one edge
by_cases hww' : w = w'
· subst hww'
have : (G \ p.toSubgraph.spanningCoe).Adj w v := by
simp only [sdiff_adj, Subgraph.spanningCoe_adj]
exact ⟨hw'2.symm, fun h ↦ hnpvw' h.symm⟩
exact this.reachable
-- Construct the walk needed recursively by extending p
have hle : (G \ (p.cons hw'2.symm).toSubgraph.spanningCoe) ≤ (G \ p.toSubgraph.spanningCoe) := by
apply sdiff_le_sdiff (by rfl) ?hcd
simp
have hp'p : (p.cons hw'2.symm).IsPath := by
rw [Walk.cons_isPath_iff]
refine ⟨hp, fun hw' ↦ ?_⟩
exact hw'1 (hcyc.snd_of_mem_support_of_isPath_of_adj _ hww' hw' hp hw'2)
have : (G \ p.toSubgraph.spanningCoe).Adj w' v := by
simp only [sdiff_adj, Subgraph.spanningCoe_adj]
refine ⟨hw'2.symm, fun h ↦ ?_⟩
exact hnpvw' h.symm
use (((hcyc.reachable_sdiff_toSubgraph_spanningCoe_aux
(p.cons hw'2.symm) hp'p).some).mapLe hle).append this.toWalk
termination_by Fintype.card V + 1 - p.length
decreasing_by
simp_wf
have := Walk.IsPath.length_lt hp
omega
lemma IsCycles.reachable_sdiff_toSubgraph_spanningCoe [Finite V] {v w : V} (hcyc : G.IsCycles)
(p : G.Walk v w) (hp : p.IsPath) : (G \ p.toSubgraph.spanningCoe).Reachable w v := by
have : Fintype V := Fintype.ofFinite V
exact reachable_sdiff_toSubgraph_spanningCoe_aux hcyc p hp
lemma IsCycles.reachable_deleteEdges [Finite V] (hadj : G.Adj v w)
(hcyc : G.IsCycles) : (G.deleteEdges {s(v, w)}).Reachable v w := by
have : fromEdgeSet {s(v, w)} = hadj.toWalk.toSubgraph.spanningCoe := by
simp only [Walk.toSubgraph, singletonSubgraph_le_iff, subgraphOfAdj_verts, Set.mem_insert_iff,
Set.mem_singleton_iff, or_true, sup_of_le_left]
exact (Subgraph.spanningCoe_subgraphOfAdj hadj).symm
rw [show G.deleteEdges {s(v, w)} = G \ fromEdgeSet {s(v, w)} from by rfl]
exact this ▸ (hcyc.reachable_sdiff_toSubgraph_spanningCoe hadj.toWalk
(Walk.IsPath.of_adj hadj)).symm
lemma IsCycles.exists_cycle_toSubgraph_verts_eq_connectedComponentSupp [Finite V]
{c : G.ConnectedComponent} (h : G.IsCycles) (hv : v ∈ c.supp)
(hn : (G.neighborSet v).Nonempty) :
∃ (p : G.Walk v v), p.IsCycle ∧ p.toSubgraph.verts = c.supp := by
classical
obtain ⟨w, hw⟩ := hn
obtain ⟨u, p, hp⟩ := SimpleGraph.adj_and_reachable_delete_edges_iff_exists_cycle.mp
⟨hw, h.reachable_deleteEdges hw⟩
have hvp : v ∈ p.support := SimpleGraph.Walk.fst_mem_support_of_mem_edges _ hp.2
have : p.toSubgraph.verts = c.supp := by
obtain ⟨c', hc'⟩ := p.toSubgraph_connected.exists_verts_eq_connectedComponentSupp (by
intro v hv w hadj
refine (Subgraph.adj_iff_of_neighborSet_equiv ?_ (Set.toFinite _)).mpr hadj
have : (G.neighborSet v).Nonempty := by
rw [Walk.mem_verts_toSubgraph] at hv
refine (Set.nonempty_of_ncard_ne_zero ?_).mono (p.toSubgraph.neighborSet_subset v)
rw [hp.1.ncard_neighborSet_toSubgraph_eq_two hv]
omega
refine @Classical.ofNonempty _ ?_
rw [← Cardinal.eq, ← Set.cast_ncard (Set.toFinite _), ← Set.cast_ncard (Set.toFinite _),
h this, hp.1.ncard_neighborSet_toSubgraph_eq_two (p.mem_verts_toSubgraph.mp hv)])
rw [hc']
have : v ∈ c'.supp := by
rw [← hc', Walk.mem_verts_toSubgraph]
exact hvp
simp_all
use p.rotate hvp
rw [← this]
exact ⟨hp.1.rotate _, by simp⟩
/--
A graph `G` is alternating with respect to some other graph `G'`, if exactly every other edge in
`G` is in `G'`. Note that the degree of each vertex needs to be at most 2 for this to be
possible. This property is used to create new matchings using `symmDiff`.
The definition of `symmDiff` that makes sense is the one for `SimpleGraph`. The `symmDiff`
for `SimpleGraph.Subgraph` deriving from the lattice structure also affects the vertices included,
which we do not want in this case. This is why this property, just like `IsCycles`, is defined
for `SimpleGraph` rather than `SimpleGraph.Subgraph`.
-/
def IsAlternating (G G' : SimpleGraph V) :=
∀ ⦃v w w': V⦄, w ≠ w' → G.Adj v w → G.Adj v w' → (G'.Adj v w ↔ ¬ G'.Adj v w')
lemma IsAlternating.mono {G'' : SimpleGraph V} (halt : G.IsAlternating G') (h : G'' ≤ G) :
G''.IsAlternating G' := fun _ _ _ hww' hvw hvw' ↦ halt hww' (h hvw) (h hvw')
lemma IsAlternating.spanningCoe (halt : G.IsAlternating G') (H : Subgraph G) :
H.spanningCoe.IsAlternating G' := by
intro v w w' hww' hvw hvv'
simp only [Subgraph.spanningCoe_adj] at hvw hvv'
exact halt hww' hvw.adj_sub hvv'.adj_sub
lemma IsAlternating.sup_edge {u x : V} (halt : G.IsAlternating G') (hnadj : ¬G'.Adj u x)
(hu' : ∀ u', u' ≠ u → G.Adj x u' → G'.Adj x u')
(hx' : ∀ x', x' ≠ x → G.Adj x' u → G'.Adj x' u) : (G ⊔ edge u x).IsAlternating G' := by
by_cases hadj : G.Adj u x
· rwa [sup_edge_of_adj G hadj]
intro v w w' hww' hvw hvv'
simp only [sup_adj, edge_adj] at hvw hvv'
obtain hl | hr := hvw <;> obtain h1 | h2 := hvv'
· exact halt hww' hl h1
· rw [G'.adj_congr_of_sym2 (by aesop : s(v, w') = s(u, x))]
simp only [hnadj, not_false_eq_true, iff_true]
rcases h2.1 with ⟨h2l1, h2l2⟩ | ⟨h2r1,h2r2⟩
· subst h2l1 h2l2
exact (hx' _ hww' hl.symm).symm
· aesop
· rw [G'.adj_congr_of_sym2 (by aesop : s(v, w) = s(u, x))]
simp only [hnadj, false_iff, not_not]
rcases hr.1 with ⟨hrl1, hrl2⟩ | ⟨hrr1, hrr2⟩
· subst hrl1 hrl2
exact (hx' _ hww'.symm h1.symm).symm
· aesop
· aesop
lemma Subgraph.IsPerfectMatching.symmDiff_of_isAlternating (hM : M.IsPerfectMatching)
(hG' : G'.IsAlternating M.spanningCoe) (hG'cyc : G'.IsCycles) :
(⊤ : Subgraph (M.spanningCoe ∆ G')).IsPerfectMatching := by
rw [Subgraph.isPerfectMatching_iff]
intro v
simp only [symmDiff_def]
obtain ⟨w, hw⟩ := hM.1 (hM.2 v)
by_cases h : G'.Adj v w
· obtain ⟨w', hw'⟩ := hG'cyc.other_adj_of_adj h
have hmadj : M.Adj v w ↔ ¬M.Adj v w' := by simpa using hG' hw'.1 h hw'.2
use w'
simp only [Subgraph.top_adj, SimpleGraph.sup_adj, sdiff_adj, Subgraph.spanningCoe_adj,
hmadj.mp hw.1, hw'.2, not_true_eq_false, and_self, not_false_eq_true, or_true, true_and]
rintro y (hl | hr)
· aesop
· obtain ⟨w'', hw''⟩ := hG'cyc.other_adj_of_adj hr.1
by_contra! hc
simp_all [show M.Adj v y ↔ ¬M.Adj v w' from by simpa using hG' hc hr.1 hw'.2]
· use w
simp only [Subgraph.top_adj, SimpleGraph.sup_adj, sdiff_adj, Subgraph.spanningCoe_adj, hw.1, h,
not_false_eq_true, and_self, not_true_eq_false, or_false, true_and]
rintro y (hl | hr)
· exact hw.2 _ hl.1
· have ⟨w', hw'⟩ := hG'cyc.other_adj_of_adj hr.1
simp_all [show M.Adj v y ↔ ¬M.Adj v w' from by simpa using hG' hw'.1 hr.1 hw'.2]
lemma Subgraph.IsPerfectMatching.isAlternating_symmDiff_left {M' : Subgraph G'}
(hM : M.IsPerfectMatching) (hM' : M'.IsPerfectMatching) :
(M.spanningCoe ∆ M'.spanningCoe).IsAlternating M.spanningCoe := by
intro v w w' hww' hvw hvw'
obtain ⟨v1, hm1, hv1⟩ := hM.1 (hM.2 v)
obtain ⟨v2, hm2, hv2⟩ := hM'.1 (hM'.2 v)
simp only [symmDiff_def] at *
aesop
lemma Subgraph.IsPerfectMatching.isAlternating_symmDiff_right
{M' : Subgraph G'} (hM : M.IsPerfectMatching) (hM' : M'.IsPerfectMatching) :
(M.spanningCoe ∆ M'.spanningCoe).IsAlternating M'.spanningCoe := by
simpa [symmDiff_comm] using isAlternating_symmDiff_left hM' hM
end SimpleGraph
|
Basic.lean
|
/-
Copyright (c) 2022 Rémi Bottinelli. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémi Bottinelli
-/
import Mathlib.CategoryTheory.Groupoid
import Mathlib.Combinatorics.Quiver.Basic
/-!
This file defines a few basic properties of groupoids.
-/
namespace CategoryTheory
namespace Groupoid
variable (C : Type*) [Groupoid C]
section Thin
theorem isThin_iff : Quiver.IsThin C ↔ ∀ c : C, Subsingleton (c ⟶ c) := by
refine ⟨fun h c => h c c, fun h c d => Subsingleton.intro fun f g => ?_⟩
haveI := h d
calc
f = f ≫ inv g ≫ g := by simp only [inv_eq_inv, IsIso.inv_hom_id, Category.comp_id]
_ = f ≫ inv f ≫ g := by congr 1
simp only [inv_eq_inv, IsIso.inv_hom_id, eq_iff_true_of_subsingleton]
_ = g := by simp only [inv_eq_inv, IsIso.hom_inv_id_assoc]
end Thin
section Disconnected
/-- A subgroupoid is totally disconnected if it only has loops. -/
def IsTotallyDisconnected :=
∀ c d : C, (c ⟶ d) → c = d
end Disconnected
end Groupoid
end CategoryTheory
|
End.lean
|
/-
Copyright (c) 2020 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison, Andrew Yang
-/
import Mathlib.CategoryTheory.Monoidal.Functor
/-!
# Endofunctors as a monoidal category.
We give the monoidal category structure on `C ⥤ C`,
and show that when `C` itself is monoidal, it embeds via a monoidal functor into `C ⥤ C`.
## TODO
Can we use this to show coherence results, e.g. a cheap proof that `λ_ (𝟙_ C) = ρ_ (𝟙_ C)`?
I suspect this is harder than is usually made out.
-/
universe v u
namespace CategoryTheory
open Functor.LaxMonoidal Functor.OplaxMonoidal Functor.Monoidal
variable (C : Type u) [Category.{v} C]
/-- The category of endofunctors of any category is a monoidal category,
with tensor product given by composition of functors
(and horizontal composition of natural transformations).
Note: due to the fact that composition of functors in mathlib is reversed compared to the
one usually found in the literature, this monoidal structure is in fact the monoidal
opposite of the one usually considered in the literature.
-/
def endofunctorMonoidalCategory : MonoidalCategory (C ⥤ C) where
tensorObj F G := F ⋙ G
whiskerLeft X _ _ F := Functor.whiskerLeft X F
whiskerRight F X := Functor.whiskerRight F X
tensorHom α β := α ◫ β
tensorUnit := 𝟭 C
associator F G H := Functor.associator F G H
leftUnitor F := Functor.leftUnitor F
rightUnitor F := Functor.rightUnitor F
open CategoryTheory.MonoidalCategory
attribute [local instance] endofunctorMonoidalCategory
@[simp] theorem endofunctorMonoidalCategory_tensorUnit_obj (X : C) :
(𝟙_ (C ⥤ C)).obj X = X := rfl
@[simp] theorem endofunctorMonoidalCategory_tensorUnit_map {X Y : C} (f : X ⟶ Y) :
(𝟙_ (C ⥤ C)).map f = f := rfl
@[simp] theorem endofunctorMonoidalCategory_tensorObj_obj (F G : C ⥤ C) (X : C) :
(F ⊗ G).obj X = G.obj (F.obj X) := rfl
@[simp] theorem endofunctorMonoidalCategory_tensorObj_map (F G : C ⥤ C) {X Y : C} (f : X ⟶ Y) :
(F ⊗ G).map f = G.map (F.map f) := rfl
@[simp] theorem endofunctorMonoidalCategory_tensorMap_app
{F G H K : C ⥤ C} {α : F ⟶ G} {β : H ⟶ K} (X : C) :
(α ⊗ₘ β).app X = β.app (F.obj X) ≫ K.map (α.app X) := rfl
@[simp] theorem endofunctorMonoidalCategory_whiskerLeft_app
{F H K : C ⥤ C} {β : H ⟶ K} (X : C) :
(F ◁ β).app X = β.app (F.obj X) := rfl
@[simp] theorem endofunctorMonoidalCategory_whiskerRight_app
{F G H : C ⥤ C} {α : F ⟶ G} (X : C) :
(α ▷ H).app X = H.map (α.app X) := rfl
@[simp] theorem endofunctorMonoidalCategory_associator_hom_app (F G H : C ⥤ C) (X : C) :
(α_ F G H).hom.app X = 𝟙 _ := rfl
@[simp] theorem endofunctorMonoidalCategory_associator_inv_app (F G H : C ⥤ C) (X : C) :
(α_ F G H).inv.app X = 𝟙 _ := rfl
@[simp] theorem endofunctorMonoidalCategory_leftUnitor_hom_app (F : C ⥤ C) (X : C) :
(λ_ F).hom.app X = 𝟙 _ := rfl
@[simp] theorem endofunctorMonoidalCategory_leftUnitor_inv_app (F : C ⥤ C) (X : C) :
(λ_ F).inv.app X = 𝟙 _ := rfl
@[simp] theorem endofunctorMonoidalCategory_rightUnitor_hom_app (F : C ⥤ C) (X : C) :
(ρ_ F).hom.app X = 𝟙 _ := rfl
@[simp] theorem endofunctorMonoidalCategory_rightUnitor_inv_app (F : C ⥤ C) (X : C) :
(ρ_ F).inv.app X = 𝟙 _ := rfl
namespace MonoidalCategory
variable [MonoidalCategory C]
/-- Tensoring on the right gives a monoidal functor from `C` into endofunctors of `C`.
-/
instance : (tensoringRight C).Monoidal :=
Functor.CoreMonoidal.toMonoidal
{ εIso := (rightUnitorNatIso C).symm
μIso := fun X Y => (Functor.isoWhiskerRight (curriedAssociatorNatIso C)
((evaluation C (C ⥤ C)).obj X ⋙ (evaluation C C).obj Y)) }
@[simp] lemma tensoringRight_ε :
ε (tensoringRight C) = (rightUnitorNatIso C).inv := rfl
@[simp] lemma tensoringRight_η :
η (tensoringRight C) = (rightUnitorNatIso C).hom := rfl
@[simp] lemma tensoringRight_μ (X Y : C) (Z : C) :
(μ (tensoringRight C) X Y).app Z = (α_ Z X Y).hom := rfl
@[simp] lemma tensoringRight_δ (X Y : C) (Z : C) :
(δ (tensoringRight C) X Y).app Z = (α_ Z X Y).inv := rfl
end MonoidalCategory
variable {C}
variable {M : Type*} [Category M] [MonoidalCategory M] (F : M ⥤ (C ⥤ C))
@[reassoc (attr := simp)]
theorem μ_δ_app (i j : M) (X : C) [F.Monoidal] :
(μ F i j).app X ≫ (δ F i j).app X = 𝟙 _ :=
(μIso F i j).hom_inv_id_app X
@[reassoc (attr := simp)]
theorem δ_μ_app (i j : M) (X : C) [F.Monoidal] :
(δ F i j).app X ≫ (μ F i j).app X = 𝟙 _ :=
(μIso F i j).inv_hom_id_app X
@[reassoc (attr := simp)]
theorem ε_η_app (X : C) [F.Monoidal] : (ε F).app X ≫ (η F).app X = 𝟙 _ :=
(εIso F).hom_inv_id_app X
@[reassoc (attr := simp)]
theorem η_ε_app (X : C) [F.Monoidal] : (η F).app X ≫ (ε F).app X = 𝟙 _ :=
(εIso F).inv_hom_id_app X
@[reassoc (attr := simp)]
theorem ε_naturality {X Y : C} (f : X ⟶ Y) [F.LaxMonoidal] :
(ε F).app X ≫ (F.obj (𝟙_ M)).map f = f ≫ (ε F).app Y :=
((ε F).naturality f).symm
@[reassoc (attr := simp)]
theorem η_naturality {X Y : C} (f : X ⟶ Y) [F.OplaxMonoidal] :
(η F).app X ≫ (𝟙_ (C ⥤ C)).map f = (η F).app X ≫ f := by
simp
@[reassoc (attr := simp)]
theorem μ_naturality {m n : M} {X Y : C} (f : X ⟶ Y) [F.LaxMonoidal] :
(F.obj n).map ((F.obj m).map f) ≫ (μ F m n).app Y = (μ F m n).app X ≫ (F.obj _).map f :=
(μ F m n).naturality f
-- This is a simp lemma in the reverse direction via `NatTrans.naturality`.
@[reassoc]
theorem δ_naturality {m n : M} {X Y : C} (f : X ⟶ Y) [F.OplaxMonoidal] :
(δ F m n).app X ≫ (F.obj n).map ((F.obj m).map f) =
(F.obj _).map f ≫ (δ F m n).app Y := by simp
-- This is not a simp lemma since it could be proved by the lemmas later.
@[reassoc]
theorem μ_naturality₂ {m n m' n' : M} (f : m ⟶ m') (g : n ⟶ n') (X : C) [F.LaxMonoidal] :
(F.map g).app ((F.obj m).obj X) ≫ (F.obj n').map ((F.map f).app X) ≫ (μ F m' n').app X =
(μ F m n).app X ≫ (F.map (f ⊗ₘ g)).app X := by
have := congr_app (μ_natural F f g) X
dsimp at this
simpa using this
@[reassoc (attr := simp)]
theorem μ_naturalityₗ {m n m' : M} (f : m ⟶ m') (X : C) [F.LaxMonoidal] :
(F.obj n).map ((F.map f).app X) ≫ (μ F m' n).app X =
(μ F m n).app X ≫ (F.map (f ▷ n)).app X := by
rw [← tensorHom_id, ← μ_naturality₂ F f (𝟙 n) X]
simp
@[reassoc (attr := simp)]
theorem μ_naturalityᵣ {m n n' : M} (g : n ⟶ n') (X : C) [F.LaxMonoidal] :
(F.map g).app ((F.obj m).obj X) ≫ (μ F m n').app X =
(μ F m n).app X ≫ (F.map (m ◁ g)).app X := by
rw [← id_tensorHom, ← μ_naturality₂ F (𝟙 m) g X]
simp
@[reassoc (attr := simp)]
theorem δ_naturalityₗ {m n m' : M} (f : m ⟶ m') (X : C) [F.OplaxMonoidal] :
(δ F m n).app X ≫ (F.obj n).map ((F.map f).app X) =
(F.map (f ▷ n)).app X ≫ (δ F m' n).app X :=
congr_app (δ_natural_left F f n) X
@[reassoc (attr := simp)]
theorem δ_naturalityᵣ {m n n' : M} (g : n ⟶ n') (X : C) [F.OplaxMonoidal] :
(δ F m n).app X ≫ (F.map g).app ((F.obj m).obj X) =
(F.map (m ◁ g)).app X ≫ (δ F m n').app X :=
congr_app (δ_natural_right F m g) X
@[reassoc]
theorem left_unitality_app (n : M) (X : C) [F.LaxMonoidal] :
(F.obj n).map ((ε F).app X) ≫ (μ F (𝟙_ M) n).app X ≫ (F.map (λ_ n).hom).app X = 𝟙 _ :=
congr_app (left_unitality F n).symm X
@[simp, reassoc]
theorem obj_ε_app (n : M) (X : C) [F.Monoidal] :
(F.obj n).map ((ε F).app X) = (F.map (λ_ n).inv).app X ≫ (δ F (𝟙_ M) n).app X := by
rw [map_leftUnitor_inv]
dsimp
simp only [Category.id_comp, Category.assoc, μ_δ_app, endofunctorMonoidalCategory_tensorObj_obj,
Category.comp_id]
@[simp, reassoc]
theorem obj_η_app (n : M) (X : C) [F.Monoidal] :
(F.obj n).map ((η F).app X) = (μ F (𝟙_ M) n).app X ≫ (F.map (λ_ n).hom).app X := by
rw [← cancel_mono ((F.obj n).map ((ε F).app X)), ← Functor.map_comp]
simp
@[reassoc]
theorem right_unitality_app (n : M) (X : C) [F.Monoidal] :
(ε F).app ((F.obj n).obj X) ≫ (μ F n (𝟙_ M)).app X ≫ (F.map (ρ_ n).hom).app X = 𝟙 _ :=
congr_app (Functor.LaxMonoidal.right_unitality F n).symm X
@[simp]
theorem ε_app_obj (n : M) (X : C) [F.Monoidal] :
(ε F).app ((F.obj n).obj X) = (F.map (ρ_ n).inv).app X ≫ (δ F n (𝟙_ M)).app X := by
rw [map_rightUnitor_inv]
dsimp
simp only [Category.id_comp, Category.assoc, μ_δ_app,
endofunctorMonoidalCategory_tensorObj_obj, Category.comp_id]
@[simp]
theorem η_app_obj (n : M) (X : C) [F.Monoidal] :
(η F).app ((F.obj n).obj X) = (μ F n (𝟙_ M)).app X ≫ (F.map (ρ_ n).hom).app X := by
rw [map_rightUnitor]
dsimp
simp only [Category.comp_id, μ_δ_app_assoc]
@[reassoc]
theorem associativity_app (m₁ m₂ m₃ : M) (X : C) [F.LaxMonoidal] :
(F.obj m₃).map ((μ F m₁ m₂).app X) ≫
(μ F (m₁ ⊗ m₂) m₃).app X ≫ (F.map (α_ m₁ m₂ m₃).hom).app X =
(μ F m₂ m₃).app ((F.obj m₁).obj X) ≫ (μ F m₁ (m₂ ⊗ m₃)).app X := by
have := congr_app (associativity F m₁ m₂ m₃) X
dsimp at this
simpa using this
@[simp, reassoc]
theorem obj_μ_app (m₁ m₂ m₃ : M) (X : C) [F.Monoidal] :
(F.obj m₃).map ((μ F m₁ m₂).app X) =
(μ F m₂ m₃).app ((F.obj m₁).obj X) ≫
(μ F m₁ (m₂ ⊗ m₃)).app X ≫
(F.map (α_ m₁ m₂ m₃).inv).app X ≫ (δ F (m₁ ⊗ m₂) m₃).app X := by
rw [← associativity_app_assoc]
simp
@[simp, reassoc]
theorem obj_μ_inv_app (m₁ m₂ m₃ : M) (X : C) [F.Monoidal] :
(F.obj m₃).map ((δ F m₁ m₂).app X) =
(μ F (m₁ ⊗ m₂) m₃).app X ≫
(F.map (α_ m₁ m₂ m₃).hom).app X ≫
(δ F m₁ (m₂ ⊗ m₃)).app X ≫ (δ F m₂ m₃).app ((F.obj m₁).obj X) := by
rw [map_associator]
dsimp
simp only [Category.id_comp, Category.assoc, μ_δ_app_assoc, μ_δ_app,
endofunctorMonoidalCategory_tensorObj_obj, Category.comp_id]
@[reassoc (attr := simp)]
theorem obj_zero_map_μ_app {m : M} {X Y : C} (f : X ⟶ (F.obj m).obj Y) [F.Monoidal] :
(F.obj (𝟙_ M)).map f ≫ (μ F m (𝟙_ M)).app _ =
(η F).app _ ≫ f ≫ (F.map (ρ_ m).inv).app _ := by
rw [← cancel_epi ((ε F).app _), ← cancel_mono ((δ F _ _).app _)]
simp
@[simp]
theorem obj_μ_zero_app (m₁ m₂ : M) (X : C) [F.Monoidal] :
(μ F (𝟙_ M) m₂).app ((F.obj m₁).obj X) ≫ (μ F m₁ (𝟙_ M ⊗ m₂)).app X ≫
(F.map (α_ m₁ (𝟙_ M) m₂).inv).app X ≫ (δ F (m₁ ⊗ 𝟙_ M) m₂).app X =
(μ F (𝟙_ M) m₂).app ((F.obj m₁).obj X) ≫
(F.map (λ_ m₂).hom).app ((F.obj m₁).obj X) ≫ (F.obj m₂).map ((F.map (ρ_ m₁).inv).app X) := by
rw [← obj_η_app_assoc, ← Functor.map_comp]
simp
/-- If `m ⊗ n ≅ 𝟙_M`, then `F.obj m` is a left inverse of `F.obj n`. -/
@[simps!]
noncomputable def unitOfTensorIsoUnit (m n : M) (h : m ⊗ n ≅ 𝟙_ M) [F.Monoidal] :
F.obj m ⋙ F.obj n ≅ 𝟭 C :=
μIso F m n ≪≫ F.mapIso h ≪≫ (εIso F).symm
/-- If `m ⊗ n ≅ 𝟙_M` and `n ⊗ m ≅ 𝟙_M` (subject to some commuting constraints),
then `F.obj m` and `F.obj n` forms a self-equivalence of `C`. -/
@[simps]
noncomputable def equivOfTensorIsoUnit (m n : M) (h₁ : m ⊗ n ≅ 𝟙_ M) (h₂ : n ⊗ m ≅ 𝟙_ M)
(H : h₁.hom ▷ m ≫ (λ_ m).hom = (α_ m n m).hom ≫ m ◁ h₂.hom ≫ (ρ_ m).hom) [F.Monoidal] :
C ≌ C where
functor := F.obj m
inverse := F.obj n
unitIso := (unitOfTensorIsoUnit F m n h₁).symm
counitIso := unitOfTensorIsoUnit F n m h₂
functor_unitIso_comp X := by
dsimp
simp only [μ_naturalityᵣ_assoc, μ_naturalityₗ_assoc, η_app_obj, Category.assoc,
obj_μ_inv_app, Functor.map_comp, δ_μ_app_assoc, obj_ε_app,
unitOfTensorIsoUnit_inv_app]
simp only [← NatTrans.comp_app, ← F.map_comp, ← H, inv_hom_whiskerRight_assoc,
Iso.inv_hom_id, Functor.map_id, NatTrans.id_app]
end CategoryTheory
|
all_algebra.v
|
(* N.B. interval_inference is not exported here.
To enjoys the automation it provides,
you need to explictly "Import interval_inference". *)
From mathcomp Require Export ssralg.
From mathcomp Require Export ssrnum.
From mathcomp Require Export finalg.
From mathcomp Require Export countalg.
From mathcomp Require Export poly.
From mathcomp Require Export polydiv.
From mathcomp Require Export polyXY.
From mathcomp Require Export qpoly.
From mathcomp Require Export ssrint.
From mathcomp Require Export archimedean.
From mathcomp Require Export rat.
From mathcomp Require Export intdiv.
From mathcomp Require Export interval.
From mathcomp Require Import interval_inference.
From mathcomp Require Export matrix.
From mathcomp Require Export mxpoly.
From mathcomp Require Export mxalgebra.
From mathcomp Require Export mxred.
From mathcomp Require Export vector.
From mathcomp Require Export ring_quotient.
From mathcomp Require Export fraction.
From mathcomp Require Export zmodp.
From mathcomp Require Export sesquilinear.
From mathcomp Require Export spectral.
|
PrimeSeparator.lean
|
/-
Copyright (c) 2024 Sam van Gool. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sam van Gool
-/
import Mathlib.Order.PrimeIdeal
import Mathlib.Order.Zorn
/-!
# Separating prime filters and ideals
In a bounded distributive lattice, if $F$ is a filter, $I$ is an ideal, and $F$ and $I$ are
disjoint, then there exists a prime ideal $J$ containing $I$ with $J$ still disjoint from $F$.
This theorem is a crucial ingredient to [Stone's][Sto1938] duality for bounded distributive
lattices. The construction of the separator relies on Zorn's lemma.
## Tags
ideal, filter, prime, distributive lattice
## References
* [M. H. Stone, Topological representations of distributive lattices and Brouwerian logics
(1938)][Sto1938]
-/
universe u
variable {α : Type*}
open Order Ideal Set
variable [DistribLattice α] [BoundedOrder α]
variable {F : PFilter α} {I : Ideal α}
namespace DistribLattice
lemma mem_ideal_sup_principal (a b : α) (J : Ideal α) : b ∈ J ⊔ principal a ↔ ∃ j ∈ J, b ≤ j ⊔ a :=
⟨fun ⟨j, ⟨jJ, _, ha', bja'⟩⟩ => ⟨j, jJ, le_trans bja' (sup_le_sup_left ha' j)⟩,
fun ⟨j, hj, hbja⟩ => ⟨j, hj, a, le_refl a, hbja⟩⟩
theorem prime_ideal_of_disjoint_filter_ideal (hFI : Disjoint (F : Set α) (I : Set α)) :
∃ J : Ideal α, (IsPrime J) ∧ I ≤ J ∧ Disjoint (F : Set α) J := by
-- Let S be the set of ideals containing I and disjoint from F.
set S : Set (Set α) := { J : Set α | IsIdeal J ∧ I ≤ J ∧ Disjoint (F : Set α) J }
-- Then I is in S...
have IinS : ↑I ∈ S := by
refine ⟨Order.Ideal.isIdeal I, by trivial⟩
-- ...and S contains upper bounds for any non-empty chains.
have chainub : ∀ c ⊆ S, IsChain (· ⊆ ·) c → c.Nonempty → ∃ ub ∈ S, ∀ s ∈ c, s ⊆ ub := by
intros c hcS hcC hcNe
use sUnion c
refine ⟨?_, fun s hs ↦ le_sSup hs⟩
simp only [le_eq_subset, mem_setOf_eq, disjoint_sUnion_right, S]
let ⟨J, hJ⟩ := hcNe
refine ⟨Order.isIdeal_sUnion_of_isChain (fun _ hJ ↦ (hcS hJ).1) hcC hcNe,
⟨le_trans (hcS hJ).2.1 (le_sSup hJ), fun J hJ ↦ (hcS hJ).2.2⟩⟩
-- Thus, by Zorn's lemma, we can pick a maximal ideal J in S.
obtain ⟨Jset, _, hmax⟩ := zorn_subset_nonempty S chainub I IinS
obtain ⟨Jidl, IJ, JF⟩ := hmax.prop
set J := IsIdeal.toIdeal Jidl
use J
have IJ' : I ≤ J := IJ
clear chainub IinS
-- By construction, J contains I and is disjoint from F. It remains to prove that J is prime.
refine ⟨?_, ⟨IJ, JF⟩⟩
-- First note that J is proper: ⊤ ∈ F so ⊤ ∉ J because F and J are disjoint.
have Jpr : IsProper J := isProper_of_notMem (Set.disjoint_left.1 JF F.top_mem)
-- Suppose that a₁ ∉ J, a₂ ∉ J. We need to prove that a₁ ⊔ a₂ ∉ J.
rw [isPrime_iff_mem_or_mem]
intros a₁ a₂
contrapose!
intro ⟨ha₁, ha₂⟩
-- Consider the ideals J₁, J₂ generated by J ∪ {a₁} and J ∪ {a₂}, respectively.
let J₁ := J ⊔ principal a₁
let J₂ := J ⊔ principal a₂
-- For each i, Jᵢ is an ideal that contains aᵢ, and is not equal to J.
have a₁J₁ : a₁ ∈ J₁ := mem_of_subset_of_mem (le_sup_right : _ ≤ J ⊔ _) mem_principal_self
have a₂J₂ : a₂ ∈ J₂ := mem_of_subset_of_mem (le_sup_right : _ ≤ J ⊔ _) mem_principal_self
have J₁J : ↑J₁ ≠ Jset := ne_of_mem_of_not_mem' a₁J₁ ha₁
have J₂J : ↑J₂ ≠ Jset := ne_of_mem_of_not_mem' a₂J₂ ha₂
-- Therefore, since J is maximal, we must have Jᵢ ∉ S.
have J₁S : ↑J₁ ∉ S := fun h => J₁J (hmax.eq_of_le h (le_sup_left : J ≤ J₁)).symm
have J₂S : ↑J₂ ∉ S := fun h => J₂J (hmax.eq_of_le h (le_sup_left : J ≤ J₂)).symm
-- Since Jᵢ is an ideal that contains I, we have that Jᵢ is not disjoint from F.
have J₁F : ¬ (Disjoint (F : Set α) J₁) := by
intro hdis
apply J₁S
simp only [le_eq_subset, mem_setOf_eq, SetLike.coe_subset_coe, S]
exact ⟨J₁.isIdeal, le_trans IJ' le_sup_left, hdis⟩
have J₂F : ¬ (Disjoint (F : Set α) J₂) := by
intro hdis
apply J₂S
simp only [le_eq_subset, mem_setOf_eq, SetLike.coe_subset_coe, S]
exact ⟨J₂.isIdeal, le_trans IJ' le_sup_left, hdis⟩
-- Thus, pick cᵢ ∈ F ∩ Jᵢ.
let ⟨c₁, ⟨c₁F, c₁J₁⟩⟩ := Set.not_disjoint_iff.1 J₁F
let ⟨c₂, ⟨c₂F, c₂J₂⟩⟩ := Set.not_disjoint_iff.1 J₂F
-- Using the definition of Jᵢ, we can pick bᵢ ∈ J such that cᵢ ≤ bᵢ ⊔ aᵢ.
let ⟨b₁, ⟨b₁J, cba₁⟩⟩ := (mem_ideal_sup_principal a₁ c₁ J).1 c₁J₁
let ⟨b₂, ⟨b₂J, cba₂⟩⟩ := (mem_ideal_sup_principal a₂ c₂ J).1 c₂J₂
-- Since J is an ideal, we have b := b₁ ⊔ b₂ ∈ J.
let b := b₁ ⊔ b₂
have bJ : b ∈ J := sup_mem b₁J b₂J
-- We now prove a key inequality, using crucially that the lattice is distributive.
have ineq : c₁ ⊓ c₂ ≤ b ⊔ (a₁ ⊓ a₂) :=
calc
c₁ ⊓ c₂ ≤ (b₁ ⊔ a₁) ⊓ (b₂ ⊔ a₂) := inf_le_inf cba₁ cba₂
_ ≤ (b ⊔ a₁) ⊓ (b ⊔ a₂) := by
apply inf_le_inf <;> apply sup_le_sup_right; exact le_sup_left; exact le_sup_right
_ = b ⊔ (a₁ ⊓ a₂) := (sup_inf_left b a₁ a₂).symm
-- Note that c₁ ⊓ c₂ ∈ F, since c₁ and c₂ are both in F and F is a filter.
-- Since F is an upper set, it now follows that b ⊔ (a₁ ⊓ a₂) ∈ F.
have ba₁a₂F : b ⊔ (a₁ ⊓ a₂) ∈ F := PFilter.mem_of_le ineq (PFilter.inf_mem c₁F c₂F)
-- Now, if we would have a₁ ⊓ a₂ ∈ J, then, since J is an ideal and b ∈ J, we would also get
-- b ⊔ (a₁ ⊓ a₂) ∈ J. But this contradicts that J is disjoint from F.
contrapose! JF with ha₁a₂
rw [Set.not_disjoint_iff]
use b ⊔ (a₁ ⊓ a₂)
exact ⟨ba₁a₂F, sup_mem bJ ha₁a₂⟩
-- TODO: Define prime filters in Mathlib so that the following corollary can be stated and proved.
-- theorem prime_filter_of_disjoint_filter_ideal (hFI : Disjoint (F : Set α) (I : Set α)) :
-- ∃ G : PFilter α, (IsPrime G) ∧ F ≤ G ∧ Disjoint (G : Set α) I := by sorry
end DistribLattice
|
LogTrigonometric.lean
|
/-
Copyright (c) 2025 Stefan Kebekus. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Stefan Kebekus
-/
import Mathlib.Analysis.SpecialFunctions.Integrability.LogMeromorphic
/-!
# Integral of `log ∘ sin`
This file computes special values of the integral of `log ∘ sin`. Given that the indefinite integral
involves the dilogarithm, this can be seen as computing special values of `Li₂`.
-/
open Filter Interval Real
/-
Helper lemma for `integral_log_sin_zero_pi_div_two`: The integral of `log ∘ sin` on `0 … π` is
double the integral on `0 … π/2`.
-/
private lemma integral_log_sin_zero_pi_eq_two_mul_integral_log_sin_zero_pi_div_two :
∫ x in (0)..π, log (sin x) = 2 * ∫ x in (0)..(π / 2), log (sin x) := by
rw [← intervalIntegral.integral_add_adjacent_intervals (a := 0) (b := π / 2) (c := π)
(by apply intervalIntegrable_log_sin) (by apply intervalIntegrable_log_sin)]
conv =>
left; right; arg 1
intro x
rw [← sin_pi_sub]
rw [intervalIntegral.integral_comp_sub_left (fun x ↦ log (sin x)), sub_self,
(by linarith : π - π / 2 = π / 2)]
ring!
/--
The integral of `log ∘ sin` on `0 … π/2` equals `-log 2 * π / 2`.
-/
theorem integral_log_sin_zero_pi_div_two : ∫ x in (0)..(π / 2), log (sin x) = -log 2 * π / 2 := by
calc ∫ x in (0)..(π / 2), log (sin x)
_ = ∫ x in (0)..(π / 2), (log (sin (2 * x)) - log 2 - log (cos x)) := by
apply intervalIntegral.integral_congr_codiscreteWithin
apply Filter.codiscreteWithin.mono (by tauto : Ι 0 (π / 2) ⊆ Set.univ)
have t₀ : sin ⁻¹' {0}ᶜ ∈ Filter.codiscrete ℝ := by
apply analyticOnNhd_sin.preimage_zero_mem_codiscrete (x := π / 2)
simp
have t₁ : cos ⁻¹' {0}ᶜ ∈ Filter.codiscrete ℝ := by
apply analyticOnNhd_cos.preimage_zero_mem_codiscrete (x := 0)
simp
filter_upwards [t₀, t₁] with y h₁y h₂y
simp_all only [Set.preimage_compl, Set.mem_compl_iff, Set.mem_preimage, Set.mem_singleton_iff,
sin_two_mul, ne_eq, mul_eq_zero, OfNat.ofNat_ne_zero, or_self, not_false_eq_true, log_mul]
ring
_ = (∫ x in (0)..(π / 2), log (sin (2 * x))) - π / 2 * log 2
- ∫ x in (0)..(π / 2), log (cos x) := by
rw [intervalIntegral.integral_sub _ _,
intervalIntegral.integral_sub _ intervalIntegrable_const,
intervalIntegral.integral_const]
· simp
· simpa using (intervalIntegrable_log_sin (a := 0) (b := π)).comp_mul_left
· apply IntervalIntegrable.sub _ intervalIntegrable_const
simpa using (intervalIntegrable_log_sin (a := 0) (b := π)).comp_mul_left
· exact intervalIntegrable_log_cos
_ = (∫ x in (0)..(π / 2), log (sin (2 * x)))
- π / 2 * log 2 - ∫ x in (0)..(π / 2), log (sin x) := by
simp [← sin_pi_div_two_sub,
intervalIntegral.integral_comp_sub_left (fun x ↦ log (sin x)) (π / 2)]
_ = -log 2 * π / 2 := by
simp only [intervalIntegral.integral_comp_mul_left (f := fun x ↦ log (sin x)) two_ne_zero,
mul_zero, (by linarith : 2 * (π / 2) = π),
integral_log_sin_zero_pi_eq_two_mul_integral_log_sin_zero_pi_div_two, smul_eq_mul, ne_eq,
OfNat.ofNat_ne_zero, not_false_eq_true, inv_mul_cancel_left₀, sub_sub_cancel_left, neg_mul]
linarith
/--
The integral of `log ∘ sin` on `0 … π` equals `-log 2 * π`.
-/
theorem integral_log_sin_zero_pi : ∫ x in (0)..π, log (sin x) = -log 2 * π := by
rw [integral_log_sin_zero_pi_eq_two_mul_integral_log_sin_zero_pi_div_two,
integral_log_sin_zero_pi_div_two]
ring
|
ssralg.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 div seq.
From mathcomp Require Import choice fintype finfun bigop prime binomial.
From mathcomp Require Export nmodule.
(******************************************************************************)
(* Ring-like structures *)
(* *)
(* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *)
(* *)
(* Reference: Francois Garillot, Georges Gonthier, Assia Mahboubi, Laurence *)
(* Rideau, Packaging mathematical structures, TPHOLs 2009 *)
(* *)
(* This file defines the following algebraic structures: *)
(* *)
(* semiPzRingType == non-commutative semi rings *)
(* (NModule with a multiplication) *)
(* The HB class is called PzSemiRing. *)
(* nzSemiRingType == non-commutative non-trivial semi rings *)
(* (NModule with a multiplication) *)
(* The HB class is called NzSemiRing. *)
(* comPzSemiRingType == commutative semi rings *)
(* The HB class is called ComPzSemiRing. *)
(* comNzSemiRingType == commutative non-trivial semi rings *)
(* The HB class is called ComNzSemiRing. *)
(* pzRingType == non-commutative rings *)
(* (semi rings with an opposite) *)
(* The HB class is called PzRing. *)
(* nzRingType == non-commutative non-trivial rings *)
(* (semi rings with an opposite) *)
(* The HB class is called NzRing. *)
(* comPzRingType == commutative rings *)
(* The HB class is called ComPzRing. *)
(* comNzRingType == commutative non-trivial rings *)
(* The HB class is called ComNzRing. *)
(* lSemiModType R == semimodule with left multiplication by external scalars *)
(* in the semiring R *)
(* The HB class is called LSemiModule. *)
(* lmodType R == module with left multiplication by external scalars *)
(* in the pzRing R *)
(* The HB class is called Lmodule. *)
(* lSemiAlgType R == left semialgebra, semiring with scaling that associates *)
(* on the left *)
(* The HB class is called LSemiAlgebra. *)
(* lalgType R == left algebra, ring with scaling that associates on the *)
(* left *)
(* The HB class is called Lalgebra. *)
(* semiAlgType R == semialgebra, semiring with scaling that associates both *)
(* left and right *)
(* The HB class is called SemiAlgebra. *)
(* algType R == algebra, ring with scaling that associates both left *)
(* and right *)
(* The HB class is called Algebra. *)
(*comSemiAlgType R == commutative semiAlgType *)
(* The HB class is called ComSemiAlgebra. *)
(* comAlgType R == commutative algType *)
(* The HB class is called ComAlgebra. *)
(* unitRingType == Rings whose units have computable inverses *)
(* The HB class is called UnitRing. *)
(* comUnitRingType == commutative UnitRing *)
(* The HB class is called ComUnitRing. *)
(* unitAlgType R == algebra with computable inverses *)
(* The HB class is called UnitAlgebra. *)
(*comUnitAlgType R == commutative UnitAlgebra *)
(* The HB class is called ComUnitAlgebra. *)
(* idomainType == integral, commutative, ring with partial inverses *)
(* The HB class is called IntegralDomain. *)
(* fieldType == commutative fields *)
(* The HB class is called Field. *)
(* decFieldType == fields with a decidable first order theory *)
(* The HB class is called DecidableField. *)
(* closedFieldType == algebraically closed fields *)
(* The HB class is called ClosedField. *)
(* *)
(* and their joins with subType: *)
(* *)
(* subPzSemiRingType R P == join of pzSemiRingType and *)
(* subType (P : pred R) such that val is a *)
(* semiring morphism *)
(* The HB class is called SubPzSemiRing. *)
(* subNzSemiRingType R P == join of nzSemiRingType and *)
(* subType (P : pred R) such that val is a *)
(* semiring morphism *)
(* The HB class is called SubNzSemiRing. *)
(*subComPzSemiRingType R P == join of comPzSemiRingType and *)
(* subType (P : pred R) such that val is a morphism*)
(* The HB class is called SubComPzSemiRing. *)
(*subComNzSemiRingType R P == join of comNzSemiRingType and *)
(* subType (P : pred R) such that val is a morphism*)
(* The HB class is called SubComNzSemiRing. *)
(* subPzRingType R P == join of pzRingType and subType (P : pred R) *)
(* such that val is a morphism *)
(* The HB class is called SubPzRing. *)
(* subComPzRingType R P == join of comPzRingType and subType (P : pred R) *)
(* such that val is a morphism *)
(* The HB class is called SubComPzRing. *)
(* subNzRingType R P == join of nzRingType and subType (P : pred R) *)
(* such that val is a morphism *)
(* The HB class is called SubNzRing. *)
(* subComNzRingType R P == join of comNzRingType and subType (P : pred R) *)
(* such that val is a morphism *)
(* The HB class is called SubComNzRing. *)
(* subLSemiModType R V P == join of lSemiModType and subType (P : pred V) *)
(* such that val is scalable *)
(* The HB class is called SubLSemiModule. *)
(* subLmodType R V P == join of lmodType and subType (P : pred V) *)
(* such that val is scalable *)
(* The HB class is called SubLmodule. *)
(* subLSemiAlgType R V P == join of lSemiAlgType and subType (P : pred V) *)
(* such that val is linear *)
(* The HB class is called SubLSemiAlgebra. *)
(* subLalgType R V P == join of lalgType and subType (P : pred V) *)
(* such that val is linear *)
(* The HB class is called SubLalgebra. *)
(* subSemiAlgType R V P == join of semiAlgType and subType (P : pred V) *)
(* such that val is linear *)
(* The HB class is called SubSemiAlgebra. *)
(* subAlgType R V P == join of algType and subType (P : pred V) *)
(* such that val is linear *)
(* The HB class is called SubAlgebra. *)
(* subUnitRingType R P == join of unitRingType and subType (P : pred R) *)
(* such that val is a ring morphism *)
(* The HB class is called SubUnitRing. *)
(* subComUnitRingType R P == join of comUnitRingType and subType (P : pred R)*)
(* such that val is a ring morphism *)
(* The HB class is called SubComUnitRing. *)
(* subIdomainType R P == join of idomainType and subType (P : pred R) *)
(* such that val is a ring morphism *)
(* The HB class is called SubIntegralDomain. *)
(* subField R P == join of fieldType and subType (P : pred R) *)
(* such that val is a ring morphism *)
(* The HB class is called SubField. *)
(* *)
(* Morphisms between the above structures (see below for details): *)
(* *)
(* {rmorphism R -> S} == semi ring (resp. ring) morphism between *)
(* semiPzRingType (resp. pzRingType) instances *)
(* R and S. *)
(* The HB class is called RMorphism. *)
(* {linear U -> V | s} == semilinear (resp. linear) functions of type *)
(* U -> V, where U is a left semimodule (resp. *)
(* left module) over semiring (resp. ring) R, V is *)
(* an N-module (resp. Z-module), and s is a scaling*)
(* operator (detailed below) of type R -> V -> V. *)
(* The HB class is called Linear. *)
(* {lrmorphism A -> B | s} == semialgebra (resp. algebra) morphisms of type *)
(* A -> B, where A is a left semialgebra *)
(* (resp. left algebra) over semiring (resp. ring) *)
(* R, B is an semiring (resp. ring), and s is a *)
(* scaling operator (detailed below) of type *)
(* R -> B -> B. *)
(* The HB class is called LRMorphism. *)
(* *)
(* -> The scaling operator s above should be one of *:%R, *%R, or a *)
(* combination nu \; *:%R or nu \; *%R with a semiring morphism nu; *)
(* otherwise some of the theory (e.g., the linearZ rule) will not apply. *)
(* To enable the overloading of the scaling operator, we use the following *)
(* structures: *)
(* *)
(* GRing.Scale.preLaw R V == scaling morphisms of type R -> V -> V *)
(* The HB class is called Scale.PreLaw. *)
(* GRing.Scale.semiLaw R V == scaling morphisms of type R -> V -> V *)
(* The HB class is called Scale.SemiLaw. *)
(* GRing.Scale.law R V == scaling morphisms of type R -> V -> V *)
(* The HB class is called Scale.Law. *)
(* *)
(* Closedness predicates for the algebraic structures: *)
(* *)
(* addrClosed V == predicate closed under addition on V : nmodType *)
(* The HB class is called AddClosed. *)
(* opprClosed V == predicate closed under opposite on V : zmodType *)
(* The HB class is called OppClosed. *)
(* zmodClosed V == predicate closed under opposite and addition on V *)
(* The HB class is called ZmodClosed. *)
(* mulr2Closed R == predicate closed under multiplication on *)
(* R : semiPzRingType *)
(* The HB class is called Mul2Closed. *)
(* mulrClosed R == predicate closed under multiplication and for 1 *)
(* The HB class is called MulClosed. *)
(* semiring2Closed R == predicate closed under addition and multiplication *)
(* The HB class is called Semiring2Closed. *)
(* semiringClosed R == predicate closed under semiring operations *)
(* The HB class is called SemiringClosed. *)
(* smulClosed R == predicate closed under multiplication and for -1 *)
(* The HB class is called SmulClosed. *)
(* subringClosed R == predicate closed under ring operations *)
(* The HB class is called SubringClosed. *)
(* divClosed R == predicate closed under division *)
(* The HB class is called DivClosed. *)
(* sdivClosed R == predicate closed under division and opposite *)
(* The HB class is called SdivClosed. *)
(* submodClosed R == predicate closed under lSemiModType operations *)
(* The HB class is called SubmodClosed. *)
(* subalgClosed R == predicate closed under lSemiAlgType operations *)
(* The HB class is called SubalgClosed. *)
(* divringClosed R == predicate closed under unitRing operations *)
(* The HB class is called DivringClosed. *)
(* divalgClosed R S == predicate closed under (S : unitAlg R) operations *)
(* The HB class is called DivalgClosed. *)
(* *)
(* The rpred* lemmas ensure that the set S remains stable under the specified *)
(* operations, provided the corresponding closedness predicate is satisfied. *)
(* This stability is crucial for constructing and reasoning about *)
(* substructures within algebraic hierarchies. For example: *)
(* *)
(* - rpred0: Concludes 0 \in S if S is addrClosed. *)
(* - rpredD: Concludes x + y \in S if x \in S and y \in S and S is addrClosed.*)
(* - rpredN: Concludes -x \in S if x \in S and S is opprClosed. *)
(* - rpredZ: Concludes a *: v \in S if v \in S and S is scalerClosed. *)
(* *)
(* Canonical properties of the algebraic structures: *)
(* * Nmodule (additive abelian monoids): *)
(* 0 == the zero (additive identity) of a Nmodule *)
(* x + y == the sum of x and y (in a Nmodule) *)
(* x *+ n == n times x, with n in nat (non-negative), i.e., *)
(* x + (x + .. (x + x)..) (n terms); x *+ 1 is thus *)
(* convertible to x, and x *+ 2 to x + x *)
(* \sum_<range> e == iterated sum for a Nmodule (cf bigop.v) *)
(* e`_i == nth 0 e i, when e : seq M and M has a nmodType *)
(* structure *)
(* support f == 0.-support f, i.e., [pred x | f x != 0] *)
(* addr_closed S <-> collective predicate S is closed under finite *)
(* sums (0 and x + y in S, for x, y in S) *)
(* [SubChoice_isSubNmodule of U by <:] == nmodType mixin for a subType whose *)
(* base type is a nmodType and whose predicate's is *)
(* an addrClosed *)
(* *)
(* * Zmodule (additive abelian groups): *)
(* - x == the opposite (additive inverse) of x *)
(* x - y == the difference of x and y; this is only notation *)
(* for x + (- y) *)
(* x *- n == notation for - (x *+ n), the opposite of x *+ n *)
(* oppr_closed S <-> collective predicate S is closed under opposite *)
(* zmod_closed S <-> collective predicate S is closed under zmodType *)
(* operations (0 and x - y in S, for x, y in S) *)
(* This property coerces to oppr_pred and addr_pred. *)
(* [SubChoice_isSubZmodule of U by <:] == zmodType mixin for a subType whose *)
(* base type is a zmodType and whose predicate's *)
(* is a zmodClosed *)
(* *)
(* * PzSemiRing (non-commutative semirings): *)
(* R^c == the converse (semi)ring for R: R^c is convertible*)
(* to R but when R has a canonical (semi)ring *)
(* structure R^c has the converse one: *)
(* if x y : R^c, then x * y = (y : R) * (x : R) *)
(* 1 == the multiplicative identity element of a semiring*)
(* n%:R == the semiring image of an n in nat; this is just *)
(* notation for 1 *+ n, so 1%:R is convertible to 1 *)
(* and 2%:R to 1 + 1 *)
(* <number> == <number>%:R with <number> a sequence of digits *)
(* x * y == the semiring product of x and y *)
(* \prod_<range> e == iterated product for a semiring (cf bigop.v) *)
(* x ^+ n == x to the nth power with n in nat (non-negative), *)
(* i.e., x * (x * .. (x * x)..) (n factors); x ^+ 1 *)
(* is thus convertible to x, and x ^+ 2 to x * x *)
(* GRing.comm x y <-> x and y commute, i.e., x * y = y * x *)
(* GRing.lreg x <-> x if left-regular, i.e., *%R x is injective *)
(* GRing.rreg x <-> x if right-regular, i.e., *%R^~ x is injective *)
(* [pchar R] == the characteristic of R, defined as the set of *)
(* prime numbers p such that p%:R = 0 in R *)
(* The set [pchar R] has at most one element, and is*)
(* implemented as a pred_nat collective predicate *)
(* (see prime.v); thus the statement p \in [pchar R]*)
(* can be read as `R has characteristic p', while *)
(* [pchar R] =i pred0 means `R has characteristic 0'*)
(* when R is a field. *)
(* pFrobenius_aut chRp == the Frobenius automorphism mapping x in R to *)
(* x ^+ p, where chRp : p \in [pchar R] is a proof *)
(* that R has (non-zero) characteristic p *)
(* mulr_closed S <-> collective predicate S is closed under finite *)
(* products (1 and x * y in S for x, y in S) *)
(* semiring_closed S <-> collective predicate S is closed under semiring *)
(* operations (0, 1, x + y and x * y in S) *)
(* [SubNmodule_isSubPzSemiRing of R by <:] == *)
(* [SubChoice_isSubPzSemiRing of R by <:] == semiPzRingType mixin for a *)
(* subType whose base type is a pzSemiRingType and *)
(* whose predicate's is a semiringClosed *)
(* *)
(* * NzSemiRing (non-commutative non-trivial semirings): *)
(* [SubNmodule_isSubNzSemiRing of R by <:] == *)
(* [SubChoice_isSubNzSemiRing of R by <:] == semiNzRingType mixin for a *)
(* subType whose base type is a nzSemiRingType and *)
(* whose predicate's is a semiringClosed *)
(* *)
(* * PzRing (non-commutative rings): *)
(* GRing.sign R b := (-1) ^+ b in R : pzRingType, with b : bool *)
(* This is a parsing-only helper notation, to be *)
(* used for defining more specific instances. *)
(* smulr_closed S <-> collective predicate S is closed under products *)
(* and opposite (-1 and x * y in S for x, y in S) *)
(* subring_closed S <-> collective predicate S is closed under ring *)
(* operations (1, x - y and x * y in S) *)
(* [SubZmodule_isSubPzRing of R by <:] == *)
(* [SubChoice_isSubPzRing of R by <:] == pzRingType mixin for a subType whose *)
(* base *)
(* type is a pzRingType and whose predicate's is a *)
(* subringClosed *)
(* *)
(* * NzRing (non-commutative non-trivial rings): *)
(* [SubZmodule_isSubNzRing of R by <:] == *)
(* [SubChoice_isSubNzRing of R by <:] == nzRingType mixin for a subType whose *)
(* base *)
(* type is a nzRingType and whose predicate's is a *)
(* subringClosed *)
(* *)
(* * ComPzSemiRing (commutative PzSemiRings): *)
(* [SubNmodule_isSubComPzSemiRing of R by <:] == *)
(* [SubChoice_isSubComPzSemiRing of R by <:] == comPzSemiRingType mixin for a *)
(* subType whose base type is a comPzSemiRingType *)
(* and whose predicate's is a semiringClosed *)
(* *)
(* * ComNzSemiRing (commutative NzSemiRings): *)
(* [SubNmodule_isSubComNzSemiRing of R by <:] == *)
(* [SubChoice_isSubComNzSemiRing of R by <:] == comNzSemiRingType mixin for a *)
(* subType whose base type is a comNzSemiRingType *)
(* and whose predicate's is a semiringClosed *)
(* *)
(* * ComPzRing (commutative PzRings): *)
(* [SubZmodule_isSubComPzRing of R by <:] == *)
(* [SubChoice_isSubComPzRing of R by <:] == comPzRingType mixin for a *)
(* subType whose base type is a comPzRingType and *)
(* whose predicate's is a subringClosed *)
(* *)
(* * ComNzRing (commutative NzRings): *)
(* [SubZmodule_isSubComNzRing of R by <:] == *)
(* [SubChoice_isSubComNzRing of R by <:] == comNzRingType mixin for a *)
(* subType whose base type is a comNzRingType and *)
(* whose predicate's is a subringClosed *)
(* *)
(* * UnitRing (NzRings whose units have computable inverses): *)
(* x \is a GRing.unit <=> x is a unit (i.e., has an inverse) *)
(* x^-1 == the ring inverse of x, if x is a unit, else x *)
(* x / y == x divided by y (notation for x * y^-1) *)
(* x ^- n := notation for (x ^+ n)^-1, the inverse of x ^+ n *)
(* invr_closed S <-> collective predicate S is closed under inverse *)
(* divr_closed S <-> collective predicate S is closed under division *)
(* (1 and x / y in S) *)
(* sdivr_closed S <-> collective predicate S is closed under division *)
(* and opposite (-1 and x / y in S, for x, y in S) *)
(* divring_closed S <-> collective predicate S is closed under unitRing *)
(* operations (1, x - y and x / y in S) *)
(* [SubNzRing_isSubUnitRing of R by <:] == *)
(* [SubChoice_isSubUnitRing of R by <:] == unitRingType mixin for a subType *)
(* whose base type is a unitRingType and whose *)
(* predicate's is a divringClosed and whose ring *)
(* structure is compatible with the base type's *)
(* *)
(* * ComUnitRing (commutative rings with computable inverses): *)
(* [SubChoice_isSubComUnitRing of R by <:] == comUnitRingType mixin for a *)
(* subType whose base type is a comUnitRingType and *)
(* whose predicate's is a divringClosed and whose *)
(* ring structure is compatible with the base *)
(* type's *)
(* *)
(* * IntegralDomain (integral, commutative, ring with partial inverses): *)
(* [SubComUnitRing_isSubIntegralDomain R by <:] == *)
(* [SubChoice_isSubIntegralDomain R by <:] == mixin axiom for a idomain *)
(* subType *)
(* *)
(* * Field (commutative fields): *)
(* GRing.Field.axiom inv == field axiom: x != 0 -> inv x * x = 1 for all x *)
(* This is equivalent to the property above, but *)
(* does not require a unitRingType as inv is an *)
(* explicit argument. *)
(* [SubIntegralDomain_isSubField of R by <:] == mixin axiom for a field *)
(* subType *)
(* *)
(* * DecidableField (fields with a decidable first order theory): *)
(* GRing.term R == the type of formal expressions in a unit ring R *)
(* with formal variables 'X_k, k : nat, and *)
(* manifest constants x%:T, x : R *)
(* The notation of all the ring operations is *)
(* redefined for terms, in scope %T. *)
(* GRing.formula R == the type of first order formulas over R; the %T *)
(* scope binds the logical connectives /\, \/, ~, *)
(* ==>, ==, and != to formulae; GRing.True/False *)
(* and GRing.Bool b denote constant formulae, and *)
(* quantifiers are written 'forall/'exists 'X_k, f *)
(* GRing.Unit x tests for ring units *)
(* GRing.If p_f t_f e_f emulates if-then-else *)
(* GRing.Pick p_f t_f e_f emulates fintype.pick *)
(* foldr GRing.Exists/Forall q_f xs can be used *)
(* to write iterated quantifiers *)
(* GRing.eval e t == the value of term t with valuation e : seq R *)
(* (e maps 'X_i to e`_i) *)
(* GRing.same_env e1 e2 <-> environments e1 and e2 are extensionally equal *)
(* GRing.qf_form f == f is quantifier-free *)
(* GRing.holds e f == the intuitionistic CiC interpretation of the *)
(* formula f holds with valuation e *)
(* GRing.qf_eval e f == the value (in bool) of a quantifier-free f *)
(* GRing.sat e f == valuation e satisfies f (only in a decField) *)
(* GRing.sol n f == a sequence e of size n such that e satisfies f, *)
(* if one exists, or [::] if there is no such e *)
(* 'exists 'X_i, u1 == 0 /\ ... /\ u_m == 0 /\ v1 != 0 ... /\ v_n != 0 *)
(* *)
(* * LSemiModule (semimodule with left multiplication by external scalars). *)
(* a *: v == v scaled by a, when v is in an LSemiModule V and *)
(* a is in the scalar semiring of V *)
(* scaler_closed S <-> collective predicate S is closed under scaling *)
(* subsemimod_closed S <-> collective predicate S is closed under *)
(* lSemiModType operations (0, +%R, and *:%R) *)
(* [SubNmodule_isSubLSemiModule of V by <:] == *)
(* [SubChoice_isSubLSemiModule of V by <:] == mixin axiom for a subType of an *)
(* lSemiModType *)
(* *)
(* * Lmodule (module with left multiplication by external scalars). *)
(* linear_closed S <-> collective predicate S is closed under linear *)
(* combinations (a *: u + v in S when u, v in S) *)
(* submod_closed S <-> collective predicate S is closed under lmodType *)
(* operations (0 and a *: u + v in S) *)
(* [SubZmodule_isSubLmodule of V by <:] == *)
(* [SubChoice_isSubLmodule of V by <:] == mixin axiom for a subType of an *)
(* lmodType *)
(* *)
(* * LSemiAlgebra *)
(* (left semialgebra, semiring with scaling that associates on the left): *)
(* R^o == the regular (semi)algebra of R: R^o is *)
(* convertible to R, but when R has a *)
(* nz(Semi)RingType structure then R^o extends it *)
(* to an l(Semi)AlgType structure by letting R act *)
(* on itself: if x : R and y : R^o then *)
(* x *: y = x * (y : R) *)
(* k%:A == the image of the scalar k in a left semialgebra; *)
(* this is simply notation for k *: 1 *)
(* [SubSemiRing_SubLSemiModule_isSubLSemiAlgebra of V by <:] *)
(* == mixin axiom for a subType of an lSemiAlgType *)
(* *)
(* * Lalgebra (left algebra, ring with scaling that associates on the left): *)
(* subalg_closed S <-> collective predicate S is closed under lalgType *)
(* operations (1, a *: u + v and u * v in S) *)
(* [SubNzRing_SubLmodule_isSubLalgebra of V by <:] == *)
(* [SubChoice_isSubLalgebra of V by <:] == mixin axiom for a subType of an *)
(* lalgType *)
(* *)
(* * SemiAlgebra (semiring with scaling that associates both left and right):*)
(* [SubLSemiAlgebra_isSubSemiAlgebra of V by <:] == *)
(* == mixin axiom for a subType of an semiAlgType *)
(* *)
(* * Algebra (ring with scaling that associates both left and right): *)
(* [SubLalgebra_isSubAlgebra of V by <:] == *)
(* [SubChoice_isSubAlgebra of V by <:] == mixin axiom for a subType of an *)
(* algType *)
(* *)
(* * UnitAlgebra (algebra with computable inverses): *)
(* divalg_closed S <-> collective predicate S is closed under all *)
(* unitAlgType operations (1, a *: u + v and u / v *)
(* are in S fo u, v in S) *)
(* *)
(* In addition to this structure hierarchy, we also develop a separate, *)
(* parallel hierarchy for morphisms linking these structures: *)
(* *)
(* * RMorphism (semiring or ring morphisms): *)
(* monoid_morphism f <-> f of type R -> S is a multiplicative monoid *)
(* morphism, i.e., f maps 1 and * in R to 1 and * *)
(* in S, respectively. R and S must have canonical *)
(* pzSemiRingType instances. *)
(* {rmorphism R -> S} == the interface type for semiring morphisms; both *)
(* R and S must have pzSemiRingType instances *)
(* When both R and S have pzRingType instances, it *)
(* is a ring morphism. *)
(* := GRing.RMorphism.type R S *)
(* *)
(* -> If R and S are UnitRings the f also maps units to units and inverses *)
(* of units to inverses; if R is a field then f is a field isomorphism *)
(* between R and its image. *)
(* -> Additive properties (raddf_suffix, see below) are duplicated and *)
(* specialised for RMorphism (as rmorph_suffix). This allows more *)
(* precise rewriting and cleaner chaining: although raddf lemmas will *)
(* recognize RMorphism functions, the converse will not hold (we cannot *)
(* add reverse inheritance rules because of incomplete backtracking in *)
(* the Canonical Projection unification), so one would have to insert a *)
(* /= every time one switched from additive to multiplicative rules. *)
(* *)
(* * Linear (semilinear or linear functions): *)
(* scalable_for s f <-> f of type U -> V is scalable for the scaling *)
(* operator s of type R -> V -> V, i.e., *)
(* f morphs a *: _ to s a _; R, U, and V must be a *)
(* pzSemiRingType, an lSemiModType R, and an *)
(* nmodType, respectively. *)
(* := forall a, {morph f : u / a *: u >-> s a u} *)
(* scalable f <-> f of type U -> V is scalable, i.e., f morphs *)
(* scaling on U to scaling on V, a *: _ to a *: _; *)
(* U and V must be lSemiModType R for the same *)
(* pzSemiRingType R. *)
(* := scalable_for *:%R f *)
(* semilinear_for s f <-> f of type U -> V is semilinear for s of type *)
(* R -> V -> V , i.e., f morphs a *: _ and addition *)
(* on U to s a _ and addition on V, respectively; *)
(* R, U, and V must be a pzSemiRingType, an *)
(* lSemiModType R and an nmodType, respectively. *)
(* := scalable_for s f * {morph f : x y / x + y} *)
(* semilinear f <-> f of type U -> V is semilinear, i.e., f morphs *)
(* scaling and addition on U to scaling and *)
(* addition on V, respectively; U and V must be *)
(* lSemiModType R for the same pzSemiRingType R. *)
(* := semilinear_for *:% f *)
(* semiscalar f <-> f of type U -> R is a semiscalar function, *)
(* i.e., f morphs scaling and addition on U to *)
(* multiplication and addition on R; R and U must *)
(* be a pzSemiRingType and an lSemiModType R, *)
(* respectively. *)
(* := semilinear_for *%R f *)
(* linear_for s f <-> f of type U -> V is linear for s of type *)
(* R -> V -> V, i.e., *)
(* f (a *: u + v) = s a (f u) + f v; *)
(* R, U, and V must be a pzRingType, an lmodType R, *)
(* and a zmodType, respectively. *)
(* linear f <-> f of type U -> V is linear, i.e., *)
(* f (f *: u + v) = a *: f u + f v; *)
(* U and V must be lmodType R for the same *)
(* pzRingType R. *)
(* := linear_for *:%R f *)
(* scalar f <-> f of type U -> R is a scalar function, i.e., *)
(* f (a *: u + v) = a * f u + f v; *)
(* R and U must be a pzRingType and an lmodType R, *)
(* respectively. *)
(* := linear_for *%R f *)
(* {linear U -> V | s} == the interface type for functions (semi)linear *)
(* for the scaling operator s of type R -> V -> V, *)
(* i.e., a structure that encapsulates two *)
(* properties semi_additive f and scalable_for s f *)
(* for functions f : U -> V; R, U, and V must be a *)
(* pzSemiRingType, an lSemiModType R, and an *)
(* nmodType, respectively. *)
(* {linear U -> V} == the interface type for (semi)linear functions, *)
(* of type U -> V where both U and V must be *)
(* lSemiModType R for the same pzSemiRingType R *)
(* := {linear U -> V | *:%R} *)
(* {scalar U} == the interface type for (semi)scalar functions, *)
(* of type U -> R where U must be an lSemiModType R *)
(* := {linear U -> R | *%R} *)
(* (a *: u)%Rlin == transient forms that simplify to a *: u, a * u, *)
(* (a * u)%Rlin nu a *: u, and nu a * u, respectively, and are *)
(* (a *:^nu u)%Rlin created by rewriting with the linearZ lemma *)
(* (a *^nu u)%Rlin The forms allows the RHS of linearZ to be matched*)
(* reliably, using the GRing.Scale.law structure. *)
(* -> Similarly to semiring morphisms, semiadditive properties are *)
(* specialized for semilinear functions. *)
(* -> Although {scalar U} is convertible to {linear U -> R^o}, it does not *)
(* actually use R^o, so that rewriting preserves the canonical structure *)
(* of the range of scalar functions. *)
(* -> The generic linearZ lemma uses a set of bespoke interface structures to *)
(* ensure that both left-to-right and right-to-left rewriting work even in *)
(* the presence of scaling functions that simplify non-trivially (e.g., *)
(* idfun \; *%R). Because most of the canonical instances and projections *)
(* are coercions the machinery will be mostly invisible (with only the *)
(* {linear ...} structure and %Rlin notations showing), but users should *)
(* beware that in (a *: f u)%Rlin, a actually occurs in the f u subterm. *)
(* -> The simpler linear_LR, or more specialized linearZZ and scalarZ rules *)
(* should be used instead of linearZ if there are complexity issues, as *)
(* well as for explicit forward and backward application, as the main *)
(* parameter of linearZ is a proper sub-interface of {linear U -> V | s}. *)
(* *)
(* * LRMorphism (semialgebra or algebra morphisms): *)
(* {lrmorphism A -> B | s} == the interface type for semiring (resp. ring) *)
(* morphisms semilinear (resp. linear) for the *)
(* scaling operator s of type R -> B -> B, i.e., *)
(* the join of semiring (resp. ring) morphisms *)
(* {rmorphism A -> B} and semilinear (resp. linear) *)
(* functions {linear A -> B | s}; R, A, and B must *)
(* be a pzSemiRingType (resp. pzRingType), an *)
(* lSemiAlgType R (resp. lalgType R), and a *)
(* pzSemiRingType (resp. pzRingType), respectively *)
(* {lrmorphism A -> B} == the interface type for semialgebra (resp. *)
(* algebra) morphisms, where A and B must be *)
(* lSemiAlgType R (resp. lalgType R) for the same *)
(* pzSemiRingType (resp. pzRingType) R *)
(* := {lrmorphism A -> B | *:%R} *)
(* -> Linear and rmorphism properties do not need to be specialized for *)
(* as we supply inheritance join instances in both directions. *)
(* Finally we supply some helper notation for morphisms: *)
(* x^f == the image of x under some morphism *)
(* This notation is only reserved (not defined) *)
(* here; it is bound locally in sections where some *)
(* morphism is used heavily (e.g., the container *)
(* morphism in the parametricity sections of poly *)
(* and matrix, or the Frobenius section here) *)
(* \0 == the constant null function, which has a *)
(* canonical linear structure, and simplifies on *)
(* application (see ssrfun.v) *)
(* f \+ g == the additive composition of f and g, i.e., the *)
(* function x |-> f x + g x; f \+ g is canonically *)
(* linear when f and g are, and simplifies on *)
(* application (see ssrfun.v) *)
(* f \- g == the function x |-> f x - g x, canonically *)
(* linear when f and g are, and simplifies on *)
(* application *)
(* \- g == the function x |-> - f x, canonically linear *)
(* when f is, and simplifies on application *)
(* k \*: f == the function x |-> k *: f x, which is *)
(* canonically linear when f is and simplifies on *)
(* application (this is a shorter alternative to *)
(* *:%R k \o f) *)
(* GRing.in_alg A == the ring morphism that injects R into A, where A *)
(* has an lalgType R structure; GRing.in_alg A k *)
(* simplifies to k%:A *)
(* a \*o f == the function x |-> a * f x, canonically linear *)
(* when f is and its codomain is an algType *)
(* and which simplifies on application *)
(* a \o* f == the function x |-> f x * a, canonically linear *)
(* when f is and its codomain is an lalgType *)
(* and which simplifies on application *)
(* f \* g == the function x |-> f x * g x; f \* g *)
(* simplifies on application *)
(* The Lemmas about these structures are contained in both the GRing module *)
(* and in the submodule GRing.Theory, which can be imported when unqualified *)
(* access to the theory is needed (GRing.Theory also allows the unqualified *)
(* use of additive, linear, Linear, etc). The main GRing module should NOT be *)
(* imported. *)
(* Notations are defined in scope ring_scope (delimiter %R), except term *)
(* and formula notations, which are in term_scope (delimiter %T). *)
(* This library also extends the conventional suffixes described in library *)
(* ssrbool.v with the following: *)
(* 0 -- ring 0, as in addr0 : x + 0 = x *)
(* 1 -- ring 1, as in mulr1 : x * 1 = x *)
(* D -- ring addition, as in linearD : f (u + v) = f u + f v *)
(* B -- ring subtraction, as in opprB : - (x - y) = y - x *)
(* M -- ring multiplication, as in invfM : (x * y)^-1 = x^-1 * y^-1 *)
(* Mn -- ring by nat multiplication, as in raddfMn : f (x *+ n) = f x *+ n *)
(* N -- ring opposite, as in mulNr : (- x) * y = - (x * y) *)
(* V -- ring inverse, as in mulVr : x^-1 * x = 1 *)
(* X -- ring exponentiation, as in rmorphXn : f (x ^+ n) = f x ^+ n *)
(* Z -- (left) module scaling, as in linearZ : f (a *: v) = s *: f v *)
(* The operator suffixes D, B, M and X are also used for the corresponding *)
(* operations on nat, as in natrX : (m ^ n)%:R = m%:R ^+ n. For the binary *)
(* power operator, a trailing "n" suffix is used to indicate the operator *)
(* suffix applies to the left-hand ring argument, as in *)
(* expr1n : 1 ^+ n = 1 vs. expr1 : x ^+ 1 = x. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Declare Scope ring_scope.
Declare Scope term_scope.
Declare Scope linear_ring_scope.
Reserved Notation "+%R".
Reserved Notation "-%R".
Reserved Notation "*%R" (format " *%R").
Reserved Notation "*:%R" (format " *:%R").
Reserved Notation "n %:R" (left associativity, format "n %:R").
Reserved Notation "k %:A" (left associativity, format "k %:A").
Reserved Notation "[ 'pchar' F ]" (format "[ 'pchar' F ]").
Reserved Notation "[ 'char' F ]" (format "[ 'char' F ]").
Reserved Notation "x %:T" (left associativity, format "x %:T").
Reserved Notation "''X_' i" (at level 8, i at level 2, format "''X_' i").
(* Patch for recurring Coq parser bug: Coq seg faults when a level 200 *)
(* notation is used as a pattern. *)
Reserved Notation "''exists' ''X_' i , f"
(at level 199, i at level 2, right associativity,
format "'[hv' ''exists' ''X_' i , '/ ' f ']'").
Reserved Notation "''forall' ''X_' i , f"
(at level 199, i at level 2, right associativity,
format "'[hv' ''forall' ''X_' i , '/ ' f ']'").
Reserved Notation "x ^f" (left associativity, format "x ^f").
Reserved Notation "\0".
Reserved Notation "f \+ g" (at level 50, left associativity).
Reserved Notation "f \- g" (at level 50, left associativity).
Reserved Notation "\- f" (at level 35, f at level 35).
Reserved Notation "a \*o f" (at level 40).
Reserved Notation "a \o* f" (at level 40).
Reserved Notation "a \*: f" (at level 40).
Reserved Notation "f \* g" (at level 40, left associativity).
Reserved Notation "'{' 'additive' U '->' V '}'"
(U at level 98, V at level 99, format "{ 'additive' U -> V }").
Reserved Notation "'{' 'rmorphism' U '->' V '}'"
(U at level 98, V at level 99, format "{ 'rmorphism' U -> V }").
Reserved Notation "'{' 'lrmorphism' U '->' V '|' s '}'"
(U at level 98, V at level 99, format "{ 'lrmorphism' U -> V | s }").
Reserved Notation "'{' 'lrmorphism' U '->' V '}'"
(U at level 98, V at level 99, format "{ 'lrmorphism' U -> V }").
Reserved Notation "'{' 'linear' U '->' V '|' s '}'"
(U at level 98, V at level 99, format "{ 'linear' U -> V | s }").
Reserved Notation "'{' 'linear' U '->' V '}'"
(U at level 98, V at level 99,
format "{ 'linear' U -> V }").
Reserved Notation "'{' 'scalar' U '}'" (format "{ 'scalar' U }").
Reserved Notation "R ^c" (format "R ^c").
Reserved Notation "R ^o" (format "R ^o").
Declare Scope ring_scope.
Delimit Scope ring_scope with R.
Declare Scope term_scope.
Delimit Scope term_scope with T.
Local Open Scope ring_scope.
Module Export Dummy.
Module GRing := Algebra.
End Dummy.
Module Import GRing.
Export Algebra.
Import Monoid.Theory.
Local Notation "0" := (@zero _) : ring_scope.
Local Notation "+%R" := (@add _) : function_scope.
Local Notation "x + y" := (add x y) : ring_scope.
Local Notation "x *+ n" := (natmul x n) : ring_scope.
Local Notation "\sum_ ( i <- r | P ) F" := (\big[+%R/0]_(i <- r | P) F).
Local Notation "\sum_ ( m <= i < n ) F" := (\big[+%R/0]_(m <= i < n) F).
Local Notation "\sum_ ( i < n ) F" := (\big[+%R/0]_(i < n) F).
Local Notation "\sum_ ( i 'in' A ) F" := (\big[+%R/0]_(i in A) F).
Local Notation "s `_ i" := (nth 0 s i) : ring_scope.
Section NmoduleTheory.
Variable V : nmodType.
Implicit Types x y : V.
Lemma addrA : associative (@add V).
Proof. exact: addrA. Qed.
Lemma addrC : commutative (@add V).
Proof. exact: addrC. Qed.
Lemma add0r : left_id (@zero V) add.
Proof. exact: add0r. Qed.
Lemma addr0 : right_id (@zero V) add.
Proof. exact: addr0. Qed.
Lemma addrCA : @left_commutative V V +%R. Proof. exact: addrCA. Qed.
Lemma addrAC : @right_commutative V V +%R. Proof. exact: addrAC. Qed.
Lemma addrACA : @interchange V +%R +%R. Proof. exact: addrACA. Qed.
Lemma mulr0n x : x *+ 0 = 0. Proof. exact: mulr0n. Qed.
Lemma mulr1n x : x *+ 1 = x. Proof. exact: mulr1n. Qed.
Lemma mulr2n x : x *+ 2 = x + x. Proof. exact: mulr2n. Qed.
Lemma mulrS x n : x *+ n.+1 = x + (x *+ n). Proof. exact: mulrS. Qed.
Lemma mulrSr x n : x *+ n.+1 = x *+ n + x. Proof. exact: mulrSr. Qed.
Lemma mulrb x (b : bool) : x *+ b = (if b then x else 0).
Proof. exact: mulrb. Qed.
Lemma mul0rn n : 0 *+ n = 0 :> V. Proof. exact: mul0rn. Qed.
Lemma mulrnDl n : {morph (fun x => x *+ n) : x y / x + y}.
Proof. exact: mulrnDl. Qed.
Lemma mulrnDr x m n : x *+ (m + n) = x *+ m + x *+ n.
Proof. exact: mulrnDr. Qed.
Lemma mulrnA x m n : x *+ (m * n) = x *+ m *+ n. Proof. exact: mulrnA. Qed.
Lemma mulrnAC x m n : x *+ m *+ n = x *+ n *+ m. Proof. exact: mulrnAC. Qed.
Lemma iter_addr n x y : iter n (+%R x) y = x *+ n + y.
Proof. exact: iter_addr. Qed.
Lemma iter_addr_0 n x : iter n (+%R x) 0 = x *+ n.
Proof. exact: iter_addr_0. Qed.
Lemma sumrMnl I r P (F : I -> V) n :
\sum_(i <- r | P i) F i *+ n = (\sum_(i <- r | P i) F i) *+ n.
Proof. exact: sumrMnl. Qed.
Lemma sumrMnr x I r P (F : I -> nat) :
\sum_(i <- r | P i) x *+ F i = x *+ (\sum_(i <- r | P i) F i).
Proof. exact: sumrMnr. Qed.
Lemma sumr_const (I : finType) (A : pred I) x : \sum_(i in A) x = x *+ #|A|.
Proof. exact: sumr_const. Qed.
Lemma sumr_const_nat m n x : \sum_(n <= i < m) x = x *+ (m - n).
Proof. exact: sumr_const_nat. Qed.
#[deprecated(since="mathcomp 2.4.0",
note="Use Algebra.nmod_closed instead.")]
Definition addr_closed := nmod_closed.
End NmoduleTheory.
Local Notation "-%R" := (@opp _) : ring_scope.
Local Notation "- x" := (opp x) : ring_scope.
Local Notation "x - y" := (x + - y) : ring_scope.
Local Notation "x *- n" := (- (x *+ n)) : ring_scope.
Section ZmoduleTheory.
Variable V : zmodType.
Implicit Types x y : V.
Lemma addNr : @left_inverse V V V 0 -%R +%R. Proof. exact: addNr. Qed.
Lemma addrN : @right_inverse V V V 0 -%R +%R. Proof. exact: addrN. Qed.
Definition subrr := addrN.
Lemma addKr : @left_loop V V -%R +%R. Proof. exact: addKr. Qed.
Lemma addNKr : @rev_left_loop V V -%R +%R. Proof. exact: addNKr. Qed.
Lemma addrK : @right_loop V V -%R +%R. Proof. exact: addrK. Qed.
Lemma addrNK : @rev_right_loop V V -%R +%R. Proof. exact: addrNK. Qed.
Definition subrK := addrNK.
Lemma subrKC x y : x + (y - x) = y. Proof. by rewrite addrC subrK. Qed.
Lemma subKr x : involutive (fun y => x - y). Proof. exact: subKr. Qed.
Lemma addrI : @right_injective V V V +%R. Proof. exact: addrI. Qed.
Lemma addIr : @left_injective V V V +%R. Proof. exact: addIr. Qed.
Lemma subrI : right_injective (fun x y => x - y). Proof. exact: subrI. Qed.
Lemma subIr : left_injective (fun x y => x - y). Proof. exact: subIr. Qed.
Lemma opprK : @involutive V -%R. Proof. exact: opprK. Qed.
Lemma oppr_inj : @injective V V -%R. Proof. exact: oppr_inj. Qed.
Lemma oppr0 : -0 = 0 :> V. Proof. exact: oppr0. Qed.
Lemma oppr_eq0 x : (- x == 0) = (x == 0). Proof. exact: oppr_eq0. Qed.
Lemma subr0 x : x - 0 = x. Proof. exact: subr0. Qed.
Lemma sub0r x : 0 - x = - x. Proof. exact: sub0r. Qed.
Lemma opprB x y : - (x - y) = y - x. Proof. exact: opprB. Qed.
Lemma opprD : {morph -%R: x y / x + y : V}. Proof. exact: opprD. Qed.
Lemma addrKA z x y : (x + z) - (z + y) = x - y. Proof. exact: addrKA. Qed.
Lemma subrKA z x y : (x - z) + (z + y) = x + y. Proof. exact: subrKA. Qed.
Lemma addr0_eq x y : x + y = 0 -> - x = y. Proof. exact: addr0_eq. Qed.
Lemma subr0_eq x y : x - y = 0 -> x = y. Proof. exact: subr0_eq. Qed.
Lemma subr_eq x y z : (x - z == y) = (x == y + z). Proof. exact: subr_eq. Qed.
Lemma subr_eq0 x y : (x - y == 0) = (x == y). Proof. exact: subr_eq0. Qed.
Lemma addr_eq0 x y : (x + y == 0) = (x == - y). Proof. exact: addr_eq0. Qed.
Lemma eqr_opp x y : (- x == - y) = (x == y). Proof. exact: eqr_opp. Qed.
Lemma eqr_oppLR x y : (- x == y) = (x == - y). Proof. exact: eqr_oppLR. Qed.
Lemma mulNrn x n : (- x) *+ n = x *- n. Proof. exact: mulNrn. Qed.
Lemma mulrnBl n : {morph (fun x => x *+ n) : x y / x - y}.
Proof. exact: mulrnBl. Qed.
Lemma mulrnBr x m n : n <= m -> x *+ (m - n) = x *+ m - x *+ n.
Proof. exact: mulrnBr. Qed.
Lemma sumrN I r P (F : I -> V) :
(\sum_(i <- r | P i) - F i = - (\sum_(i <- r | P i) F i)).
Proof. exact: sumrN. Qed.
Lemma sumrB I r (P : pred I) (F1 F2 : I -> V) :
\sum_(i <- r | P i) (F1 i - F2 i)
= \sum_(i <- r | P i) F1 i - \sum_(i <- r | P i) F2 i.
Proof. exact: sumrB. Qed.
Lemma telescope_sumr n m (f : nat -> V) : n <= m ->
\sum_(n <= k < m) (f k.+1 - f k) = f m - f n.
Proof. exact: telescope_sumr. Qed.
Lemma telescope_sumr_eq n m (f u : nat -> V) : n <= m ->
(forall k, (n <= k < m)%N -> u k = f k.+1 - f k) ->
\sum_(n <= k < m) u k = f m - f n.
Proof. exact: telescope_sumr_eq. Qed.
Section ClosedPredicates.
Variable S : {pred V}.
Definition oppr_closed := oppr_closed S.
Definition subr_2closed := subr_closed S.
Definition zmod_closed := zmod_closed S.
Lemma zmod_closedN : zmod_closed -> oppr_closed.
Proof. exact: zmod_closedN. Qed.
Lemma zmod_closedD : zmod_closed -> nmod_closed S.
Proof. by move=> z; split; [case: z|apply/zmod_closedD]. Qed.
End ClosedPredicates.
End ZmoduleTheory.
Arguments addrI {V} y [x1 x2].
Arguments addIr {V} x [x1 x2].
Arguments opprK {V}.
Arguments oppr_inj {V} [x1 x2].
Arguments telescope_sumr_eq {V n m} f u.
HB.mixin Record Nmodule_isPzSemiRing R of Nmodule R := {
one : R;
mul : R -> R -> R;
mulrA : associative mul;
mul1r : left_id one mul;
mulr1 : right_id one mul;
mulrDl : left_distributive mul +%R;
mulrDr : right_distributive mul +%R;
mul0r : left_zero zero mul;
mulr0 : right_zero zero mul;
}.
#[short(type="pzSemiRingType")]
HB.structure Definition PzSemiRing :=
{ R of Nmodule_isPzSemiRing R & Nmodule R }.
HB.factory Record isPzSemiRing R of Choice R := {
zero : R;
add : R -> R -> R;
one : R;
mul : R -> R -> R;
addrA : associative add;
addrC : commutative add;
add0r : left_id zero add;
mulrA : associative mul;
mul1r : left_id one mul;
mulr1 : right_id one mul;
mulrDl : left_distributive mul add;
mulrDr : right_distributive mul add;
mul0r : left_zero zero mul;
mulr0 : right_zero zero mul;
}.
HB.builders Context R of isPzSemiRing R.
HB.instance Definition _ := @isNmodule.Build R
zero add addrA addrC add0r.
HB.instance Definition _ := @Nmodule_isPzSemiRing.Build R
one mul mulrA mul1r mulr1 mulrDl mulrDr mul0r mulr0.
HB.end.
Module PzSemiRingExports.
Bind Scope ring_scope with PzSemiRing.sort.
End PzSemiRingExports.
HB.export PzSemiRingExports.
HB.mixin Record PzSemiRing_isNonZero R of PzSemiRing R := {
oner_neq0 : @one R != 0
}.
#[short(type="nzSemiRingType")]
HB.structure Definition NzSemiRing :=
{ R of PzSemiRing_isNonZero R & PzSemiRing R }.
#[deprecated(since="mathcomp 2.4.0",
note="Use NzSemiRing instead.")]
Notation SemiRing R := (NzSemiRing R) (only parsing).
Module SemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use NzSemiRing.sort instead.")]
Notation sort := (NzSemiRing.sort) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use NzSemiRing.on instead.")]
Notation on R := (NzSemiRing.on R) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use NzSemiRing.copy instead.")]
Notation copy T U := (NzSemiRing.copy T U) (only parsing).
End SemiRing.
HB.factory Record Nmodule_isNzSemiRing R of Nmodule R := {
one : R;
mul : R -> R -> R;
mulrA : associative mul;
mul1r : left_id one mul;
mulr1 : right_id one mul;
mulrDl : left_distributive mul +%R;
mulrDr : right_distributive mul +%R;
mul0r : left_zero zero mul;
mulr0 : right_zero zero mul;
oner_neq0 : one != 0
}.
HB.builders Context R of Nmodule_isNzSemiRing R.
HB.instance Definition _ :=
Nmodule_isPzSemiRing.Build R mulrA mul1r mulr1 mulrDl mulrDr mul0r mulr0.
HB.instance Definition _ := PzSemiRing_isNonZero.Build R oner_neq0.
HB.end.
Module Nmodule_isSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use Nmodule_isNzSemiRing.Build instead.")]
Notation Build R := (Nmodule_isNzSemiRing.Build R) (only parsing).
End Nmodule_isSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use Nmodule_isNzSemiRing instead.")]
Notation Nmodule_isSemiRing R := (Nmodule_isNzSemiRing R) (only parsing).
HB.factory Record isNzSemiRing R of Choice R := {
zero : R;
add : R -> R -> R;
one : R;
mul : R -> R -> R;
addrA : associative add;
addrC : commutative add;
add0r : left_id zero add;
mulrA : associative mul;
mul1r : left_id one mul;
mulr1 : right_id one mul;
mulrDl : left_distributive mul add;
mulrDr : right_distributive mul add;
mul0r : left_zero zero mul;
mulr0 : right_zero zero mul;
oner_neq0 : one != zero
}.
Module isSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use isNzSemiRing.Build instead.")]
Notation Build R := (isNzSemiRing.Build R) (only parsing).
End isSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use isNzSemiRing instead.")]
Notation isSemiRing R := (isNzSemiRing R) (only parsing).
HB.builders Context R of isNzSemiRing R.
HB.instance Definition _ := @isNmodule.Build R
zero add addrA addrC add0r.
HB.instance Definition _ := @Nmodule_isNzSemiRing.Build R
one mul mulrA mul1r mulr1 mulrDl mulrDr mul0r mulr0 oner_neq0.
HB.end.
Module NzSemiRingExports.
Bind Scope ring_scope with NzSemiRing.sort.
End NzSemiRingExports.
HB.export NzSemiRingExports.
Definition exp R x n := iterop n (@mul R) x (@one R).
Arguments exp : simpl never.
Definition comm R x y := @mul R x y = mul y x.
Definition lreg R x := injective (@mul R x).
Definition rreg R x := injective ((@mul R)^~ x).
Local Notation "1" := (@one _) : ring_scope.
Local Notation "n %:R" := (1 *+ n) : ring_scope.
Local Notation "*%R" := (@mul _) : function_scope.
Local Notation "x * y" := (mul x y) : ring_scope.
Local Notation "x ^+ n" := (exp x n) : ring_scope.
Local Notation "\prod_ ( i <- r | P ) F" := (\big[*%R/1]_(i <- r | P) F).
Local Notation "\prod_ ( i | P ) F" := (\big[*%R/1]_(i | P) F).
Local Notation "\prod_ ( i 'in' A ) F" := (\big[*%R/1]_(i in A) F).
Local Notation "\prod_ ( m <= i < n ) F" := (\big[*%R/1%R]_(m <= i < n) F%R).
(* The ``field'' characteristic; the definition, and many of the theorems, *)
(* has to apply to rings as well; indeed, we need the Frobenius automorphism *)
(* results for a non commutative ring in the proof of Gorenstein 2.6.3. *)
Definition pchar (R : nzSemiRingType) : nat_pred :=
[pred p | prime p & p%:R == 0 :> R].
#[deprecated(since="mathcomp 2.4.0", note="Use pchar instead.")]
Notation char := pchar (only parsing).
Local Notation has_pchar0 L := (pchar L =i pred0).
#[deprecated(since="mathcomp 2.4.0", note="Use has_pchar0 instead.")]
Notation has_char0 L := (has_pchar0 L) (only parsing).
(* Converse ring tag. *)
Definition converse R : Type := R.
Local Notation "R ^c" := (converse R) : type_scope.
Section PzSemiRingTheory.
Variable R : pzSemiRingType.
Implicit Types x y : R.
#[export]
HB.instance Definition _ := Monoid.isLaw.Build R 1 *%R mulrA mul1r mulr1.
#[export]
HB.instance Definition _ := Monoid.isMulLaw.Build R 0 *%R mul0r mulr0.
#[export]
HB.instance Definition _ := Monoid.isAddLaw.Build R *%R +%R mulrDl mulrDr.
Lemma mulr_suml I r P (F : I -> R) x :
(\sum_(i <- r | P i) F i) * x = \sum_(i <- r | P i) F i * x.
Proof. exact: big_distrl. Qed.
Lemma mulr_sumr I r P (F : I -> R) x :
x * (\sum_(i <- r | P i) F i) = \sum_(i <- r | P i) x * F i.
Proof. exact: big_distrr. Qed.
Lemma mulrnAl x y n : (x *+ n) * y = (x * y) *+ n.
Proof. by elim: n => [|n IHn]; rewrite ?mul0r // !mulrS mulrDl IHn. Qed.
Lemma mulrnAr x y n : x * (y *+ n) = (x * y) *+ n.
Proof. by elim: n => [|n IHn]; rewrite ?mulr0 // !mulrS mulrDr IHn. Qed.
Lemma mulr_natl x n : n%:R * x = x *+ n.
Proof. by rewrite mulrnAl mul1r. Qed.
Lemma mulr_natr x n : x * n%:R = x *+ n.
Proof. by rewrite mulrnAr mulr1. Qed.
Lemma natrD m n : (m + n)%:R = m%:R + n%:R :> R. Proof. exact: mulrnDr. Qed.
Lemma natr1 n : n%:R + 1 = n.+1%:R :> R. Proof. by rewrite mulrSr. Qed.
Lemma nat1r n : 1 + n%:R = n.+1%:R :> R. Proof. by rewrite mulrS. Qed.
Definition natr_sum := big_morph (natmul 1) natrD (mulr0n 1).
Lemma natrM m n : (m * n)%:R = m%:R * n%:R :> R.
Proof. by rewrite mulrnA mulr_natr. Qed.
Lemma expr0 x : x ^+ 0 = 1. Proof. by []. Qed.
Lemma expr1 x : x ^+ 1 = x. Proof. by []. Qed.
Lemma expr2 x : x ^+ 2 = x * x. Proof. by []. Qed.
Lemma exprS x n : x ^+ n.+1 = x * x ^+ n.
Proof. by case: n => //; rewrite mulr1. Qed.
Lemma expr0n n : 0 ^+ n = (n == 0%N)%:R :> R.
Proof. by case: n => // n; rewrite exprS mul0r. Qed.
Lemma expr1n n : 1 ^+ n = 1 :> R.
Proof. by elim: n => // n IHn; rewrite exprS mul1r. Qed.
Lemma exprD x m n : x ^+ (m + n) = x ^+ m * x ^+ n.
Proof. by elim: m => [|m IHm]; rewrite ?mul1r // !exprS -mulrA -IHm. Qed.
Lemma exprSr x n : x ^+ n.+1 = x ^+ n * x.
Proof. by rewrite -addn1 exprD expr1. Qed.
Lemma expr_sum x (I : Type) (s : seq I) (P : pred I) F :
x ^+ (\sum_(i <- s | P i) F i) = \prod_(i <- s | P i) x ^+ F i :> R.
Proof. exact: (big_morph _ (exprD _)). Qed.
Lemma commr_sym x y : comm x y -> comm y x. Proof. by []. Qed.
Lemma commr_refl x : comm x x. Proof. by []. Qed.
Lemma commr0 x : comm x 0.
Proof. by rewrite /comm mulr0 mul0r. Qed.
Lemma commr1 x : comm x 1.
Proof. by rewrite /comm mulr1 mul1r. Qed.
Lemma commrD x y z : comm x y -> comm x z -> comm x (y + z).
Proof. by rewrite /comm mulrDl mulrDr => -> ->. Qed.
Lemma commr_sum (I : Type) (s : seq I) (P : pred I) (F : I -> R) x :
(forall i, P i -> comm x (F i)) -> comm x (\sum_(i <- s | P i) F i).
Proof.
move=> comm_x_F; rewrite /comm mulr_suml mulr_sumr.
by apply: eq_bigr => i /comm_x_F.
Qed.
Lemma commrMn x y n : comm x y -> comm x (y *+ n).
Proof.
rewrite /comm => com_xy.
by elim: n => [|n IHn]; rewrite ?commr0 // mulrS commrD.
Qed.
Lemma commrM x y z : comm x y -> comm x z -> comm x (y * z).
Proof. by move=> com_xy; rewrite /comm mulrA com_xy -!mulrA => ->. Qed.
Lemma commr_prod (I : Type) (s : seq I) (P : pred I) (F : I -> R) x :
(forall i, P i -> comm x (F i)) -> comm x (\prod_(i <- s | P i) F i).
Proof. exact: (big_ind _ (commr1 x) (@commrM x)). Qed.
Lemma commr_nat x n : comm x n%:R. Proof. exact/commrMn/commr1. Qed.
Lemma commrX x y n : comm x y -> comm x (y ^+ n).
Proof.
rewrite /comm => com_xy.
by elim: n => [|n IHn]; rewrite ?commr1 // exprS commrM.
Qed.
Lemma exprMn_comm x y n : comm x y -> (x * y) ^+ n = x ^+ n * y ^+ n.
Proof.
move=> com_xy; elim: n => /= [|n IHn]; first by rewrite mulr1.
by rewrite !exprS IHn !mulrA; congr (_ * _); rewrite -!mulrA -commrX.
Qed.
Lemma exprMn_n x m n : (x *+ m) ^+ n = x ^+ n *+ (m ^ n) :> R.
Proof.
elim: n => [|n IHn]; first by rewrite mulr1n.
by rewrite exprS IHn mulrnAl mulrnAr -mulrnA exprS -expnSr.
Qed.
Lemma exprM x m n : x ^+ (m * n) = x ^+ m ^+ n.
Proof.
elim: m => [|m IHm]; first by rewrite expr1n.
by rewrite mulSn exprD IHm exprS exprMn_comm //; apply: commrX.
Qed.
Lemma exprAC x m n : (x ^+ m) ^+ n = (x ^+ n) ^+ m.
Proof. by rewrite -!exprM mulnC. Qed.
Lemma expr_mod n x i : x ^+ n = 1 -> x ^+ (i %% n) = x ^+ i.
Proof.
move=> xn1; rewrite {2}(divn_eq i n) exprD mulnC exprM xn1.
by rewrite expr1n mul1r.
Qed.
Lemma expr_dvd n x i : x ^+ n = 1 -> n %| i -> x ^+ i = 1.
Proof.
by move=> xn1 dvd_n_i; rewrite -(expr_mod i xn1) (eqnP dvd_n_i).
Qed.
Lemma natrX n k : (n ^ k)%:R = n%:R ^+ k :> R.
Proof. by rewrite exprMn_n expr1n. Qed.
Lemma mulrI_eq0 x y : lreg x -> (x * y == 0) = (y == 0).
Proof. by move=> reg_x; rewrite -{1}(mulr0 x) (inj_eq reg_x). Qed.
Lemma lreg1 : lreg (1 : R).
Proof. by move=> x y; rewrite !mul1r. Qed.
Lemma lregM x y : lreg x -> lreg y -> lreg (x * y).
Proof. by move=> reg_x reg_y z t; rewrite -!mulrA => /reg_x/reg_y. Qed.
Lemma lregMl (a b: R) : lreg (a * b) -> lreg b.
Proof. by move=> rab c c' eq_bc; apply/rab; rewrite -!mulrA eq_bc. Qed.
Lemma rregMr (a b: R) : rreg (a * b) -> rreg a.
Proof. by move=> rab c c' eq_ca; apply/rab; rewrite !mulrA eq_ca. Qed.
Lemma lregX x n : lreg x -> lreg (x ^+ n).
Proof.
by move=> reg_x; elim: n => [|n]; [apply: lreg1 | rewrite exprS; apply: lregM].
Qed.
Lemma iter_mulr n x y : iter n ( *%R x) y = x ^+ n * y.
Proof. by elim: n => [|n ih]; rewrite ?expr0 ?mul1r //= ih exprS -mulrA. Qed.
Lemma iter_mulr_1 n x : iter n ( *%R x) 1 = x ^+ n.
Proof. by rewrite iter_mulr mulr1. Qed.
Lemma prodr_const (I : finType) (A : pred I) x : \prod_(i in A) x = x ^+ #|A|.
Proof. by rewrite big_const -iteropE. Qed.
Lemma prodr_const_nat n m x : \prod_(n <= i < m) x = x ^+ (m - n).
Proof. by rewrite big_const_nat -iteropE. Qed.
Lemma prodrXr x I r P (F : I -> nat) :
\prod_(i <- r | P i) x ^+ F i = x ^+ (\sum_(i <- r | P i) F i).
Proof. by rewrite (big_morph _ (exprD _) (erefl _)). Qed.
Lemma prodrM_comm {I : eqType} r (P : pred I) (F G : I -> R) :
(forall i j, P i -> P j -> comm (F i) (G j)) ->
\prod_(i <- r | P i) (F i * G i) =
\prod_(i <- r | P i) F i * \prod_(i <- r | P i) G i.
Proof.
move=> FG; elim: r => [|i r IHr]; rewrite !(big_nil, big_cons) ?mulr1//.
case: ifPn => // Pi; rewrite IHr !mulrA; congr (_ * _); rewrite -!mulrA.
by rewrite commr_prod // => j Pj; apply/commr_sym/FG.
Qed.
Lemma prodrMl_comm {I : finType} (A : pred I) (x : R) F :
(forall i, A i -> comm x (F i)) ->
\prod_(i in A) (x * F i) = x ^+ #|A| * \prod_(i in A) F i.
Proof. by move=> xF; rewrite prodrM_comm ?prodr_const// => i j _ /xF. Qed.
Lemma prodrMr_comm {I : finType} (A : pred I) (x : R) F :
(forall i, A i -> comm x (F i)) ->
\prod_(i in A) (F i * x) = \prod_(i in A) F i * x ^+ #|A|.
Proof. by move=> xF; rewrite prodrM_comm ?prodr_const// => i j /xF. Qed.
Lemma prodrMn (I : Type) (s : seq I) (P : pred I) (F : I -> R) (g : I -> nat) :
\prod_(i <- s | P i) (F i *+ g i) =
\prod_(i <- s | P i) (F i) *+ \prod_(i <- s | P i) g i.
Proof.
by elim/big_rec3: _ => // i y1 y2 y3 _ ->; rewrite mulrnAr mulrnAl -mulrnA.
Qed.
Lemma prodrMn_const n (I : finType) (A : pred I) (F : I -> R) :
\prod_(i in A) (F i *+ n) = \prod_(i in A) F i *+ n ^ #|A|.
Proof. by rewrite prodrMn prod_nat_const. Qed.
Lemma natr_prod I r P (F : I -> nat) :
(\prod_(i <- r | P i) F i)%:R = \prod_(i <- r | P i) (F i)%:R :> R.
Proof. exact: (big_morph _ natrM). Qed.
Lemma exprDn_comm x y n (cxy : comm x y) :
(x + y) ^+ n = \sum_(i < n.+1) (x ^+ (n - i) * y ^+ i) *+ 'C(n, i).
Proof.
elim: n => [|n IHn]; rewrite big_ord_recl mulr1 ?big_ord0 ?addr0 //=.
rewrite exprS {}IHn /= mulrDl !big_distrr /= big_ord_recl mulr1 subn0.
rewrite !big_ord_recr /= !binn !subnn !mul1r !subn0 bin0 !exprS -addrA.
congr (_ + _); rewrite addrA -big_split /=; congr (_ + _).
apply: eq_bigr => i _; rewrite !mulrnAr !mulrA -exprS -subSn ?(valP i) //.
by rewrite subSS (commrX _ (commr_sym cxy)) -mulrA -exprS -mulrnDr.
Qed.
Lemma exprD1n x n : (x + 1) ^+ n = \sum_(i < n.+1) x ^+ i *+ 'C(n, i).
Proof.
rewrite addrC (exprDn_comm n (commr_sym (commr1 x))).
by apply: eq_bigr => i _; rewrite expr1n mul1r.
Qed.
Lemma sqrrD1 x : (x + 1) ^+ 2 = x ^+ 2 + x *+ 2 + 1.
Proof.
rewrite exprD1n !big_ord_recr big_ord0 /= add0r.
by rewrite addrC addrA addrAC.
Qed.
Section ClosedPredicates.
Variable S : {pred R}.
Definition mulr_2closed := {in S &, forall u v, u * v \in S}.
Definition mulr_closed := 1 \in S /\ mulr_2closed.
Definition semiring_closed := nmod_closed S /\ mulr_closed.
Lemma semiring_closedD : semiring_closed -> nmod_closed S. Proof. by case. Qed.
Lemma semiring_closedM : semiring_closed -> mulr_closed. Proof. by case. Qed.
End ClosedPredicates.
End PzSemiRingTheory.
Section NzSemiRingTheory.
Variable R : nzSemiRingType.
Implicit Types x y : R.
Lemma oner_eq0 : (1 == 0 :> R) = false. Proof. exact: negbTE oner_neq0. Qed.
Lemma lastr_eq0 (s : seq R) x : x != 0 -> (last x s == 0) = (last 1 s == 0).
Proof. by case: s => [|y s] /negPf // ->; rewrite oner_eq0. Qed.
Lemma lreg_neq0 x : lreg x -> x != 0.
Proof. by move=> reg_x; rewrite -[x]mulr1 mulrI_eq0 ?oner_eq0. Qed.
Definition pFrobenius_aut p of p \in pchar R := fun x => x ^+ p.
(* FIXME: Generalize to `pzSemiRingType` once `char` has a sensible
definition. *)
Section FrobeniusAutomorphism.
Variable p : nat.
Hypothesis pcharFp : p \in pchar R.
Lemma pcharf0 : p%:R = 0 :> R. Proof. by apply/eqP; case/andP: pcharFp. Qed.
Lemma pcharf_prime : prime p. Proof. by case/andP: pcharFp. Qed.
Hint Resolve pcharf_prime : core.
Lemma mulrn_pchar x : x *+ p = 0. Proof. by rewrite -mulr_natl pcharf0 mul0r. Qed.
Lemma natr_mod_pchar n : (n %% p)%:R = n%:R :> R.
Proof. by rewrite {2}(divn_eq n p) natrD mulrnA mulrn_pchar add0r. Qed.
Lemma dvdn_pcharf n : (p %| n)%N = (n%:R == 0 :> R).
Proof.
apply/idP/eqP=> [/dvdnP[n' ->]|n0]; first by rewrite natrM pcharf0 mulr0.
apply/idPn; rewrite -prime_coprime // => /eqnP pn1.
have [a _ /dvdnP[b]] := Bezoutl n (prime_gt0 pcharf_prime).
move/(congr1 (fun m => m%:R : R))/eqP.
by rewrite natrD !natrM pcharf0 n0 !mulr0 pn1 addr0 oner_eq0.
Qed.
Lemma pcharf_eq : pchar R =i (p : nat_pred).
Proof.
move=> q; apply/andP/eqP=> [[q_pr q0] | ->]; last by rewrite pcharf0.
by apply/eqP; rewrite eq_sym -dvdn_prime2 // dvdn_pcharf.
Qed.
Lemma bin_lt_pcharf_0 k : 0 < k < p -> 'C(p, k)%:R = 0 :> R.
Proof. by move=> lt0kp; apply/eqP; rewrite -dvdn_pcharf prime_dvd_bin. Qed.
Local Notation "x ^f" := (pFrobenius_aut pcharFp x).
Lemma pFrobenius_autE x : x^f = x ^+ p. Proof. by []. Qed.
Local Notation f'E := pFrobenius_autE.
Lemma pFrobenius_aut0 : 0^f = 0.
Proof. by rewrite f'E -(prednK (prime_gt0 pcharf_prime)) exprS mul0r. Qed.
Lemma pFrobenius_aut1 : 1^f = 1.
Proof. by rewrite f'E expr1n. Qed.
Lemma pFrobenius_autD_comm x y (cxy : comm x y) : (x + y)^f = x^f + y^f.
Proof.
have defp := prednK (prime_gt0 pcharf_prime).
rewrite !f'E exprDn_comm // big_ord_recr subnn -defp big_ord_recl /= defp.
rewrite subn0 mulr1 mul1r bin0 binn big1 ?addr0 // => i _.
by rewrite -mulr_natl bin_lt_pcharf_0 ?mul0r //= -{2}defp ltnS (valP i).
Qed.
Lemma pFrobenius_autMn x n : (x *+ n)^f = x^f *+ n.
Proof.
elim: n => [|n IHn]; first exact: pFrobenius_aut0.
by rewrite !mulrS pFrobenius_autD_comm ?IHn //; apply: commrMn.
Qed.
Lemma pFrobenius_aut_nat n : (n%:R)^f = n%:R.
Proof. by rewrite pFrobenius_autMn pFrobenius_aut1. Qed.
Lemma pFrobenius_autM_comm x y : comm x y -> (x * y)^f = x^f * y^f.
Proof. exact: exprMn_comm. Qed.
Lemma pFrobenius_autX x n : (x ^+ n)^f = x^f ^+ n.
Proof. by rewrite !f'E -!exprM mulnC. Qed.
End FrobeniusAutomorphism.
Section Char2.
Hypothesis pcharR2 : 2 \in pchar R.
Lemma addrr_pchar2 x : x + x = 0. Proof. by rewrite -mulr2n mulrn_pchar. Qed.
End Char2.
End NzSemiRingTheory.
#[short(type="pzRingType")]
HB.structure Definition PzRing := { R of PzSemiRing R & Zmodule R }.
HB.factory Record Zmodule_isPzRing R of Zmodule R := {
one : R;
mul : R -> R -> R;
mulrA : associative mul;
mul1r : left_id one mul;
mulr1 : right_id one mul;
mulrDl : left_distributive mul +%R;
mulrDr : right_distributive mul +%R;
}.
HB.builders Context R of Zmodule_isPzRing R.
Local Notation "1" := one.
Local Notation "x * y" := (mul x y).
Lemma mul0r : @left_zero R R 0 mul.
Proof. by move=> x; apply: (addIr (1 * x)); rewrite -mulrDl !add0r mul1r. Qed.
Lemma mulr0 : @right_zero R R 0 mul.
Proof. by move=> x; apply: (addIr (x * 1)); rewrite -mulrDr !add0r mulr1. Qed.
HB.instance Definition _ := Nmodule_isPzSemiRing.Build R
mulrA mul1r mulr1 mulrDl mulrDr mul0r mulr0.
HB.end.
HB.factory Record isPzRing R of Choice R := {
zero : R;
opp : R -> R;
add : R -> R -> R;
one : R;
mul : R -> R -> R;
addrA : associative add;
addrC : commutative add;
add0r : left_id zero add;
addNr : left_inverse zero opp add;
mulrA : associative mul;
mul1r : left_id one mul;
mulr1 : right_id one mul;
mulrDl : left_distributive mul add;
mulrDr : right_distributive mul add;
}.
HB.builders Context R of isPzRing R.
HB.instance Definition _ := @isZmodule.Build R
zero opp add addrA addrC add0r addNr.
HB.instance Definition _ := @Zmodule_isPzRing.Build R
one mul mulrA mul1r mulr1 mulrDl mulrDr.
HB.end.
Module PzRingExports.
Bind Scope ring_scope with PzRing.sort.
End PzRingExports.
HB.export PzRingExports.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_aut instead.")]
Notation Frobenius_aut := pFrobenius_aut (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf0 instead.")]
Notation charf0 := pcharf0 (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf_prime instead.")]
Notation charf_prime := pcharf_prime (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use mulrn_pchar instead.")]
Notation mulrn_char := mulrn_pchar (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use natr_mod_pchar instead.")]
Notation natr_mod_char := natr_mod_pchar (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use dvdn_pcharf instead.")]
Notation dvdn_charf := dvdn_pcharf (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf_eq instead.")]
Notation charf_eq := pcharf_eq (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use bin_lt_pcharf_0 instead.")]
Notation bin_lt_charf_0 := bin_lt_pcharf_0 (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autE instead.")]
Notation Frobenius_autE := pFrobenius_autE (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_aut0 instead.")]
Notation Frobenius_aut0 := pFrobenius_aut0 (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_aut1 instead.")]
Notation Frobenius_aut1 := pFrobenius_aut1 (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autD_comm instead.")]
Notation Frobenius_autD_comm := pFrobenius_autD_comm (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autMn instead.")]
Notation Frobenius_autMn := pFrobenius_autMn (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_aut_nat instead.")]
Notation Frobenius_aut_nat := pFrobenius_aut_nat (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autM_comm instead.")]
Notation Frobenius_autM_comm := pFrobenius_autM_comm (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autX instead.")]
Notation Frobenius_autX := pFrobenius_autX (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use addrr_pchar2 instead.")]
Notation addrr_char2 := addrr_pchar2 (only parsing).
#[short(type="nzRingType")]
HB.structure Definition NzRing := { R of NzSemiRing R & Zmodule R }.
#[deprecated(since="mathcomp 2.4.0",
note="Use NzRing instead.")]
Notation Ring R := (NzRing R) (only parsing).
Module Ring.
#[deprecated(since="mathcomp 2.4.0",
note="Use NzRing.sort instead.")]
Notation sort := (NzRing.sort) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use NzRing.on instead.")]
Notation on R := (NzRing.on R) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use NzRing.copy instead.")]
Notation copy T U := (NzRing.copy T U) (only parsing).
End Ring.
HB.factory Record Zmodule_isNzRing R of Zmodule R := {
one : R;
mul : R -> R -> R;
mulrA : associative mul;
mul1r : left_id one mul;
mulr1 : right_id one mul;
mulrDl : left_distributive mul +%R;
mulrDr : right_distributive mul +%R;
oner_neq0 : one != 0
}.
Module Zmodule_isRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use Zmodule_isNzRing.Build instead.")]
Notation Build R := (Zmodule_isNzRing.Build R) (only parsing).
End Zmodule_isRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use Zmodule_isNzRing instead.")]
Notation Zmodule_isRing R := (Zmodule_isNzRing R) (only parsing).
HB.builders Context R of Zmodule_isNzRing R.
HB.instance Definition _ := Zmodule_isPzRing.Build R
mulrA mul1r mulr1 mulrDl mulrDr.
HB.instance Definition _ := PzSemiRing_isNonZero.Build R oner_neq0.
HB.end.
HB.factory Record isNzRing R of Choice R := {
zero : R;
opp : R -> R;
add : R -> R -> R;
one : R;
mul : R -> R -> R;
addrA : associative add;
addrC : commutative add;
add0r : left_id zero add;
addNr : left_inverse zero opp add;
mulrA : associative mul;
mul1r : left_id one mul;
mulr1 : right_id one mul;
mulrDl : left_distributive mul add;
mulrDr : right_distributive mul add;
oner_neq0 : one != zero
}.
Module isRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use isNzRing.Build instead.")]
Notation Build R := (isNzRing.Build R) (only parsing).
End isRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use isNzRing instead.")]
Notation isRing R := (isNzRing R) (only parsing).
HB.builders Context R of isNzRing R.
HB.instance Definition _ := @isZmodule.Build R
zero opp add addrA addrC add0r addNr.
HB.instance Definition _ := @Zmodule_isNzRing.Build R
one mul mulrA mul1r mulr1 mulrDl mulrDr oner_neq0.
HB.end.
Module NzRingExports.
Bind Scope ring_scope with NzRing.sort.
End NzRingExports.
HB.export NzRingExports.
Notation sign R b := (exp (- @one R) (nat_of_bool b)) (only parsing).
Local Notation "- 1" := (- (1)) : ring_scope.
Section PzRingTheory.
Variable R : pzRingType.
Implicit Types x y : R.
Lemma mulrN x y : x * (- y) = - (x * y).
Proof. by apply: (addrI (x * y)); rewrite -mulrDr !subrr mulr0. Qed.
Lemma mulNr x y : (- x) * y = - (x * y).
Proof. by apply: (addrI (x * y)); rewrite -mulrDl !subrr mul0r. Qed.
Lemma mulrNN x y : (- x) * (- y) = x * y.
Proof. by rewrite mulrN mulNr opprK. Qed.
Lemma mulN1r x : -1 * x = - x.
Proof. by rewrite mulNr mul1r. Qed.
Lemma mulrN1 x : x * -1 = - x.
Proof. by rewrite mulrN mulr1. Qed.
Lemma mulrBl x y z : (y - z) * x = y * x - z * x.
Proof. by rewrite mulrDl mulNr. Qed.
Lemma mulrBr x y z : x * (y - z) = x * y - x * z.
Proof. by rewrite mulrDr mulrN. Qed.
Lemma natrB m n : n <= m -> (m - n)%:R = m%:R - n%:R :> R.
Proof. exact: mulrnBr. Qed.
Lemma commrN x y : comm x y -> comm x (- y).
Proof. by move=> com_xy; rewrite /comm mulrN com_xy mulNr. Qed.
Lemma commrN1 x : comm x (-1). Proof. exact/commrN/commr1. Qed.
Lemma commrB x y z : comm x y -> comm x z -> comm x (y - z).
Proof. by move=> com_xy com_xz; apply: commrD => //; apply: commrN. Qed.
Lemma commr_sign x n : comm x ((-1) ^+ n).
Proof. exact: (commrX n (commrN1 x)). Qed.
Lemma signr_odd n : (-1) ^+ (odd n) = (-1) ^+ n :> R.
Proof.
elim: n => //= n IHn; rewrite exprS -{}IHn.
by case/odd: n; rewrite !mulN1r ?opprK.
Qed.
Lemma mulr_sign (b : bool) x : (-1) ^+ b * x = (if b then - x else x).
Proof. by case: b; rewrite ?mulNr mul1r. Qed.
Lemma signr_addb b1 b2 : (-1) ^+ (b1 (+) b2) = (-1) ^+ b1 * (-1) ^+ b2 :> R.
Proof. by rewrite mulr_sign; case: b1 b2 => [] []; rewrite ?opprK. Qed.
Lemma signrE (b : bool) : (-1) ^+ b = 1 - b.*2%:R :> R.
Proof. by case: b; rewrite ?subr0 // opprD addNKr. Qed.
Lemma signrN b : (-1) ^+ (~~ b) = - (-1) ^+ b :> R.
Proof. by case: b; rewrite ?opprK. Qed.
Lemma mulr_signM (b1 b2 : bool) x1 x2 :
((-1) ^+ b1 * x1) * ((-1) ^+ b2 * x2) = (-1) ^+ (b1 (+) b2) * (x1 * x2).
Proof.
by rewrite signr_addb -!mulrA; congr (_ * _); rewrite !mulrA commr_sign.
Qed.
Lemma exprNn x n : (- x) ^+ n = (-1) ^+ n * x ^+ n :> R.
Proof. by rewrite -mulN1r exprMn_comm // /comm mulN1r mulrN mulr1. Qed.
Lemma sqrrN x : (- x) ^+ 2 = x ^+ 2. Proof. exact: mulrNN. Qed.
Lemma sqrr_sign n : ((-1) ^+ n) ^+ 2 = 1 :> R.
Proof. by rewrite exprAC sqrrN !expr1n. Qed.
Lemma signrMK n : @involutive R ( *%R ((-1) ^+ n)).
Proof. by move=> x; rewrite mulrA -expr2 sqrr_sign mul1r. Qed.
Lemma mulrI0_lreg x : (forall y, x * y = 0 -> y = 0) -> lreg x.
Proof.
move=> reg_x y z eq_xy_xz; apply/eqP; rewrite -subr_eq0 [y - z]reg_x //.
by rewrite mulrBr eq_xy_xz subrr.
Qed.
Lemma lregN x : lreg x -> lreg (- x).
Proof. by move=> reg_x y z; rewrite !mulNr => /oppr_inj/reg_x. Qed.
Lemma lreg_sign n : lreg ((-1) ^+ n : R). Proof. exact/lregX/lregN/lreg1. Qed.
Lemma prodrN (I : finType) (A : pred I) (F : I -> R) :
\prod_(i in A) - F i = (- 1) ^+ #|A| * \prod_(i in A) F i.
Proof.
rewrite -sum1_card; elim/big_rec3: _ => [|i x n _ _ ->]; first by rewrite mulr1.
by rewrite exprS !mulrA mulN1r !mulNr commrX //; apply: commrN1.
Qed.
Lemma exprBn_comm x y n (cxy : comm x y) :
(x - y) ^+ n =
\sum_(i < n.+1) ((-1) ^+ i * x ^+ (n - i) * y ^+ i) *+ 'C(n, i).
Proof.
rewrite exprDn_comm; last exact: commrN.
by apply: eq_bigr => i _; congr (_ *+ _); rewrite -commr_sign -mulrA -exprNn.
Qed.
Lemma subrXX_comm x y n (cxy : comm x y) :
x ^+ n - y ^+ n = (x - y) * (\sum_(i < n) x ^+ (n.-1 - i) * y ^+ i).
Proof.
case: n => [|n]; first by rewrite big_ord0 mulr0 subrr.
rewrite mulrBl !big_distrr big_ord_recl big_ord_recr /= subnn mulr1 mul1r.
rewrite subn0 -!exprS opprD -!addrA; congr (_ + _); rewrite addrA -sumrB.
rewrite big1 ?add0r // => i _; rewrite !mulrA -exprS -subSn ?(valP i) //.
by rewrite subSS (commrX _ (commr_sym cxy)) -mulrA -exprS subrr.
Qed.
Lemma subrX1 x n : x ^+ n - 1 = (x - 1) * (\sum_(i < n) x ^+ i).
Proof.
rewrite -!(opprB 1) mulNr -{1}(expr1n _ n).
rewrite (subrXX_comm _ (commr_sym (commr1 x))); congr (- (_ * _)).
by apply: eq_bigr => i _; rewrite expr1n mul1r.
Qed.
Lemma sqrrB1 x : (x - 1) ^+ 2 = x ^+ 2 - x *+ 2 + 1.
Proof. by rewrite -sqrrN opprB addrC sqrrD1 sqrrN mulNrn. Qed.
Lemma subr_sqr_1 x : x ^+ 2 - 1 = (x - 1) * (x + 1).
Proof. by rewrite subrX1 !big_ord_recr big_ord0 /= addrAC add0r. Qed.
Section ClosedPredicates.
Variable S : {pred R}.
Definition smulr_closed := -1 \in S /\ mulr_2closed S.
Definition subring_closed := [/\ 1 \in S, subr_2closed S & mulr_2closed S].
Lemma smulr_closedM : smulr_closed -> mulr_closed S.
Proof. by case=> SN1 SM; split=> //; rewrite -[1]mulr1 -mulrNN SM. Qed.
Lemma smulr_closedN : smulr_closed -> oppr_closed S.
Proof. by case=> SN1 SM x Sx; rewrite -mulN1r SM. Qed.
Lemma subring_closedB : subring_closed -> zmod_closed S.
Proof. by case=> S1 SB _; split; rewrite // -(subrr 1) SB. Qed.
Lemma subring_closedM : subring_closed -> smulr_closed.
Proof.
by case=> S1 SB SM; split; rewrite ?(zmod_closedN (subring_closedB _)).
Qed.
Lemma subring_closed_semi : subring_closed -> semiring_closed S.
Proof.
by move=> ringS; split; [apply/zmod_closedD/subring_closedB | case: ringS].
Qed.
End ClosedPredicates.
End PzRingTheory.
Section NzRingTheory.
Variable R : nzRingType.
Implicit Types x y : R.
Lemma signr_eq0 n : ((-1) ^+ n == 0 :> R) = false.
Proof. by rewrite -signr_odd; case: odd; rewrite ?oppr_eq0 oner_eq0. Qed.
(* FIXME: Generalize to `pzSemiRingType` once `char` has a sensible
definition. *)
Section FrobeniusAutomorphism.
Variable p : nat.
Hypothesis pcharFp : p \in pchar R.
Hint Resolve pcharf_prime : core.
Local Notation "x ^f" := (pFrobenius_aut pcharFp x).
Lemma pFrobenius_autN x : (- x)^f = - x^f.
Proof.
apply/eqP; rewrite -subr_eq0 opprK addrC.
by rewrite -(pFrobenius_autD_comm _ (commrN _)) // subrr pFrobenius_aut0.
Qed.
Lemma pFrobenius_autB_comm x y : comm x y -> (x - y)^f = x^f - y^f.
Proof.
by move/commrN/pFrobenius_autD_comm->; rewrite pFrobenius_autN.
Qed.
End FrobeniusAutomorphism.
Lemma exprNn_pchar x n : (pchar R).-nat n -> (- x) ^+ n = - (x ^+ n).
Proof.
pose p := pdiv n; have [|n_gt1 pcharRn] := leqP n 1; first by case: (n) => [|[]].
have pcharRp: p \in pchar R by rewrite (pnatPpi pcharRn) // pi_pdiv.
have /p_natP[e ->]: p.-nat n by rewrite -(eq_pnat _ (pcharf_eq pcharRp)).
elim: e => // e IHe; rewrite expnSr !exprM {}IHe.
by rewrite -pFrobenius_autE pFrobenius_autN.
Qed.
Section Char2.
Hypothesis pcharR2 : 2 \in pchar R.
Lemma oppr_pchar2 x : - x = x.
Proof. by apply/esym/eqP; rewrite -addr_eq0 addrr_pchar2. Qed.
Lemma subr_pchar2 x y : x - y = x + y. Proof. by rewrite oppr_pchar2. Qed.
Lemma addrK_pchar2 x : involutive (+%R^~ x).
Proof. by move=> y; rewrite /= -subr_pchar2 addrK. Qed.
Lemma addKr_pchar2 x : involutive (+%R x).
Proof. by move=> y; rewrite -{1}[x]oppr_pchar2 addKr. Qed.
End Char2.
End NzRingTheory.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autN instead.")]
Notation Frobenius_autN := pFrobenius_autN (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autB_comm instead.")]
Notation Frobenius_autB_comm := pFrobenius_autB_comm (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use exprNn_pchar instead.")]
Notation exprNn_char := exprNn_pchar (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use oppr_pchar2 instead.")]
Notation oppr_char2 := oppr_pchar2 (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use subr_pchar2 instead.")]
Notation subr_char2 := subr_pchar2 (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use addrK_pchar2 instead.")]
Notation addrK_char2 := addrK_pchar2 (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use addKr_pchar2 instead.")]
Notation addKr_char2 := addKr_pchar2 (only parsing).
Section ConverseRing.
#[export]
HB.instance Definition _ (T : eqType) := Equality.on T^c.
#[export]
HB.instance Definition _ (T : choiceType) := Choice.on T^c.
#[export]
HB.instance Definition _ (U : nmodType) := Nmodule.on U^c.
#[export]
HB.instance Definition _ (U : zmodType) := Zmodule.on U^c.
#[export]
HB.instance Definition _ (R : pzSemiRingType) :=
let mul' (x y : R) := y * x in
let mulrA' x y z := esym (mulrA z y x) in
let mulrDl' x y z := mulrDr z x y in
let mulrDr' x y z := mulrDl y z x in
Nmodule_isPzSemiRing.Build R^c
mulrA' mulr1 mul1r mulrDl' mulrDr' mulr0 mul0r.
#[export]
HB.instance Definition _ (R : pzRingType) := PzSemiRing.on R^c.
#[export]
HB.instance Definition _ (R : nzSemiRingType) :=
PzSemiRing_isNonZero.Build R^c oner_neq0.
#[export]
HB.instance Definition _ (R : nzRingType) := NzSemiRing.on R^c.
End ConverseRing.
Lemma rev_prodr (R : pzSemiRingType)
(I : Type) (r : seq I) (P : pred I) (E : I -> R) :
\prod_(i <- r | P i) (E i : R^c) = \prod_(i <- rev r | P i) E i.
Proof. by rewrite rev_big_rev. Qed.
Section SemiRightRegular.
Variable R : pzSemiRingType.
Implicit Types x y : R.
Lemma mulIr_eq0 x y : rreg x -> (y * x == 0) = (y == 0).
Proof. exact: (@mulrI_eq0 R^c). Qed.
Lemma rreg1 : rreg (1 : R).
Proof. exact: (@lreg1 R^c). Qed.
Lemma rregM x y : rreg x -> rreg y -> rreg (x * y).
Proof. by move=> reg_x reg_y; apply: (@lregM R^c). Qed.
Lemma revrX x n : (x : R^c) ^+ n = (x : R) ^+ n.
Proof. by elim: n => // n IHn; rewrite exprS exprSr IHn. Qed.
Lemma rregX x n : rreg x -> rreg (x ^+ n).
Proof. by move/(@lregX R^c x n); rewrite revrX. Qed.
End SemiRightRegular.
Lemma rreg_neq0 (R : nzSemiRingType) (x : R) : rreg x -> x != 0.
Proof. exact: (@lreg_neq0 R^c). Qed.
Section RightRegular.
Variable R : pzRingType.
Implicit Types x y : R.
Lemma mulIr0_rreg x : (forall y, y * x = 0 -> y = 0) -> rreg x.
Proof. exact: (@mulrI0_lreg R^c). Qed.
Lemma rregN x : rreg x -> rreg (- x). Proof. exact: (@lregN R^c). Qed.
End RightRegular.
HB.mixin Record Nmodule_isLSemiModule (R : pzSemiRingType) V of Nmodule V := {
scale : R -> V -> V;
scalerA : forall a b v, scale a (scale b v) = scale (a * b) v;
scale0r : forall v, scale 0 v = 0;
scale1r : left_id 1 scale;
scalerDr : right_distributive scale +%R;
scalerDl : forall v, {morph scale^~ v: a b / a + b}
}.
#[short(type="lSemiModType")]
HB.structure Definition LSemiModule (R : pzSemiRingType) :=
{M of Nmodule M & Nmodule_isLSemiModule R M}.
Module LSemiModExports.
Bind Scope ring_scope with LSemiModule.sort.
End LSemiModExports.
HB.export LSemiModExports.
Local Notation "*:%R" := (@scale _ _) : function_scope.
Local Notation "a *: v" := (scale a v) : ring_scope.
#[short(type="lmodType")]
HB.structure Definition Lmodule (R : pzRingType) :=
{M of Zmodule M & Nmodule_isLSemiModule R M}.
(* FIXME: see #1126 and #1127 *)
Arguments scalerA [R s] (a b)%_ring_scope v.
Module LmodExports.
Bind Scope ring_scope with Lmodule.sort.
End LmodExports.
HB.export LmodExports.
HB.factory Record Zmodule_isLmodule (R : pzRingType) V of Zmodule V := {
scale : R -> V -> V;
scalerA : forall a b v, scale a (scale b v) = scale (a * b) v;
scale1r : left_id 1 scale;
scalerDr : right_distributive scale +%R;
scalerDl : forall v, {morph scale^~ v: a b / a + b}
}.
HB.builders Context R V of Zmodule_isLmodule R V.
Lemma scale0r v : scale 0 v = 0.
Proof. by apply: (addIr (scale 1 v)); rewrite -scalerDl !add0r. Qed.
HB.instance Definition _ :=
Nmodule_isLSemiModule.Build R V scalerA scale0r scale1r scalerDr scalerDl.
HB.end.
HB.factory Record LSemiModule_isLmodule (R : pzRingType) V
of LSemiModule R V := {}.
HB.builders Context R V of LSemiModule_isLmodule R V.
Definition opp : V -> V := scale (- 1).
Lemma addNr : left_inverse 0 opp +%R.
Proof.
move=> v; suff : scale (-1 + 1) v = 0 by rewrite scalerDl scale1r.
by rewrite addNr scale0r.
Qed.
HB.instance Definition _ := Nmodule_isZmodule.Build V addNr.
HB.end.
Section LSemiModuleTheory.
Variables (R : pzSemiRingType) (V : lSemiModType R).
Implicit Types (a b c : R) (u v : V).
Lemma scaler0 a : a *: 0 = 0 :> V.
Proof. by rewrite -[0 in LHS](scale0r 0) scalerA mulr0 scale0r. Qed.
Lemma scaler_nat n v : n%:R *: v = v *+ n.
Proof.
elim: n => /= [|n]; first by rewrite scale0r.
by rewrite !mulrS scalerDl ?scale1r => ->.
Qed.
Lemma scalerMnl a v n : a *: v *+ n = (a *+ n) *: v.
Proof.
elim: n => [|n IHn]; first by rewrite !mulr0n scale0r.
by rewrite !mulrSr IHn scalerDl.
Qed.
Lemma scalerMnr a v n : a *: v *+ n = a *: (v *+ n).
Proof.
elim: n => [|n IHn]; first by rewrite !mulr0n scaler0.
by rewrite !mulrSr IHn scalerDr.
Qed.
Lemma scaler_suml v I r (P : pred I) F :
(\sum_(i <- r | P i) F i) *: v = \sum_(i <- r | P i) F i *: v.
Proof. exact: (big_morph _ (scalerDl v) (scale0r v)). Qed.
Lemma scaler_sumr a I r (P : pred I) (F : I -> V) :
a *: (\sum_(i <- r | P i) F i) = \sum_(i <- r | P i) a *: F i.
Proof. exact: big_endo (scalerDr a) (scaler0 a) I r P F. Qed.
Section ClosedPredicates.
Variable S : {pred V}.
Definition scaler_closed := forall a, {in S, forall v, a *: v \in S}.
Definition subsemimod_closed := nmod_closed S /\ scaler_closed.
Lemma subsemimod_closedD : subsemimod_closed -> nmod_closed S.
Proof. by case. Qed.
Lemma subsemimod_closedZ : subsemimod_closed -> scaler_closed.
Proof. by case. Qed.
End ClosedPredicates.
End LSemiModuleTheory.
Section LmoduleTheory.
Variables (R : pzRingType) (V : lmodType R).
Implicit Types (a b c : R) (u v : V).
Lemma scaleNr a v : - a *: v = - (a *: v).
Proof. by apply: (addIr (a *: v)); rewrite -scalerDl !addNr scale0r. Qed.
Lemma scaleN1r v : - 1 *: v = - v.
Proof. by rewrite scaleNr scale1r. Qed.
Lemma scalerN a v : a *: - v = - (a *: v).
Proof. by apply: (addIr (a *: v)); rewrite -scalerDr !addNr scaler0. Qed.
Lemma scalerBl a b v : (a - b) *: v = a *: v - b *: v.
Proof. by rewrite scalerDl scaleNr. Qed.
Lemma scalerBr a u v : a *: (u - v) = a *: u - a *: v.
Proof. by rewrite scalerDr scalerN. Qed.
Lemma scaler_sign (b : bool) v : (-1) ^+ b *: v = (if b then - v else v).
Proof. by case: b; rewrite ?scaleNr scale1r. Qed.
Lemma signrZK n : @involutive V ( *:%R ((-1) ^+ n)).
Proof. by move=> u; rewrite scalerA -expr2 sqrr_sign scale1r. Qed.
Section ClosedPredicates.
Variable S : {pred V}.
Definition linear_closed := forall a, {in S &, forall u v, a *: u + v \in S}.
Definition submod_closed := 0 \in S /\ linear_closed.
Lemma linear_closedB : linear_closed -> subr_2closed S.
Proof. by move=> Slin u v Su Sv; rewrite addrC -scaleN1r Slin. Qed.
Lemma submod_closedB : submod_closed -> zmod_closed S.
Proof. by case=> S0 /linear_closedB. Qed.
Lemma submod_closed_semi : submod_closed -> subsemimod_closed S.
Proof.
move=> /[dup] /submod_closedB /zmod_closedD SD [S0 Slin]; split => // a v Sv.
by rewrite -[a *: v]addr0 Slin.
Qed.
End ClosedPredicates.
End LmoduleTheory.
(* TOTHINK: Can I change `NzSemiRing` to `PzSemiRing`? *)
HB.mixin Record LSemiModule_isLSemiAlgebra R V
of NzSemiRing V & LSemiModule R V := {
scalerAl : forall (a : R) (u v : V), a *: (u * v) = (a *: u) * v
}.
#[short(type="lSemiAlgType")]
HB.structure Definition LSemiAlgebra R :=
{A of LSemiModule R A & NzSemiRing A & LSemiModule_isLSemiAlgebra R A}.
Module LSemiAlgExports.
Bind Scope ring_scope with LSemiAlgebra.sort.
End LSemiAlgExports.
HB.export LSemiAlgExports.
(* Scalar injection (see the definition of in_alg A below). *)
Local Notation "k %:A" := (k *: 1) : ring_scope.
#[short(type="lalgType")]
HB.structure Definition Lalgebra R :=
{A of Lmodule R A & NzRing A & LSemiModule_isLSemiAlgebra R A}.
Module LalgExports.
Bind Scope ring_scope with Lalgebra.sort.
End LalgExports.
HB.export LalgExports.
HB.factory Record Lmodule_isLalgebra R V of NzRing V & Lmodule R V := {
scalerAl : forall (a : R) (u v : V), a *: (u * v) = (a *: u) * v
}.
HB.builders Context R V of Lmodule_isLalgebra R V.
HB.instance Definition _ := LSemiModule_isLSemiAlgebra.Build R V scalerAl.
HB.end.
(* Regular ring algebra tag. *)
Definition regular R : Type := R.
Local Notation "R ^o" := (regular R) : type_scope.
Section RegularAlgebra.
#[export]
HB.instance Definition _ (V : nmodType) := Nmodule.on V^o.
#[export]
HB.instance Definition _ (V : zmodType) := Zmodule.on V^o.
#[export]
HB.instance Definition _ (R : pzSemiRingType) := PzSemiRing.on R^o.
#[export]
HB.instance Definition _ (R : nzSemiRingType) := NzSemiRing.on R^o.
#[export]
HB.instance Definition _ (R : pzSemiRingType) :=
@Nmodule_isLSemiModule.Build R R^o
mul mulrA mul0r mul1r mulrDr (fun v a b => mulrDl a b v).
#[export]
HB.instance Definition _ (R : nzSemiRingType) :=
LSemiModule_isLSemiAlgebra.Build R R^o mulrA.
#[export]
HB.instance Definition _ (R : pzRingType) := PzRing.on R^o.
#[export]
HB.instance Definition _ (R : nzRingType) := NzRing.on R^o.
End RegularAlgebra.
Section LSemiAlgebraTheory.
Variables (R : pzSemiRingType) (A : lSemiAlgType R).
Lemma mulr_algl (a : R) (x : A) : (a *: 1) * x = a *: x.
Proof. by rewrite -scalerAl mul1r. Qed.
End LSemiAlgebraTheory.
Section LalgebraTheory.
Variables (R : pzRingType) (A : lalgType R).
Section ClosedPredicates.
Variable S : {pred A}.
Definition subalg_closed := [/\ 1 \in S, linear_closed S & mulr_2closed S].
Lemma subalg_closedZ : subalg_closed -> submod_closed S.
Proof. by case=> S1 Slin _; split; rewrite // -(subrr 1) linear_closedB. Qed.
Lemma subalg_closedBM : subalg_closed -> subring_closed S.
Proof. by case=> S1 Slin SM; split=> //; apply: linear_closedB. Qed.
End ClosedPredicates.
End LalgebraTheory.
(* Morphism hierarchy. *)
(* Lifted multiplication. *)
Section LiftedSemiRing.
Variables (R : pzSemiRingType) (T : Type).
Implicit Type f : T -> R.
Definition mull_fun a f x := a * f x.
Definition mulr_fun a f x := f x * a.
Definition mul_fun f g x := f x * g x.
End LiftedSemiRing.
(* Lifted linear operations. *)
Section LiftedScale.
Variables (R : pzSemiRingType) (U : Type).
Variables (V : lSemiModType R) (A : lSemiAlgType R).
Definition scale_fun a (f : U -> V) x := a *: f x.
Definition in_alg k : A := k%:A.
End LiftedScale.
Local Notation "\0" := (null_fun _) : function_scope.
Local Notation "f \+ g" := (add_fun f g) : function_scope.
Local Notation "f \- g" := (sub_fun f g) : function_scope.
Local Notation "\- f" := (opp_fun f) : function_scope.
Local Notation "a \*: f" := (scale_fun a f) : function_scope.
Local Notation "x \*o f" := (mull_fun x f) : function_scope.
Local Notation "x \o* f" := (mulr_fun x f) : function_scope.
Local Notation "f \* g" := (mul_fun f g) : function_scope.
Arguments in_alg {_} A _ /.
Arguments mull_fun {_ _} a f _ /.
Arguments mulr_fun {_ _} a f _ /.
Arguments scale_fun {_ _ _} a f _ /.
Arguments mul_fun {_ _} f g _ /.
Section AdditiveTheory.
Section SemiRingProperties.
Variables (R S : pzSemiRingType) (f : {additive R -> S}).
Lemma raddfMnat n x : f (n%:R * x) = n%:R * f x.
Proof. by rewrite !mulr_natl raddfMn. Qed.
Variables (U : lSemiModType R) (V : lSemiModType S) (h : {additive U -> V}).
Lemma raddfZnat n u : h (n%:R *: u) = n%:R *: h u.
Proof. by rewrite !scaler_nat raddfMn. Qed.
End SemiRingProperties.
Section MulFun.
Variables (R : pzSemiRingType) (U : nmodType) (a : R) (f : {additive U -> R}).
Fact mull_fun_is_nmod_morphism : nmod_morphism (a \*o f).
Proof. by split=> [|x y]; rewrite /= ?raddf0 ?mulr0// raddfD mulrDr. Qed.
#[export]
HB.instance Definition _ := isNmodMorphism.Build U R (a \*o f)
mull_fun_is_nmod_morphism.
Fact mulr_fun_is_nmod_morphism : nmod_morphism (a \o* f).
Proof. by split=> [|x y]; rewrite /= ?raddf0 ?mul0r// raddfD mulrDl. Qed.
#[export]
HB.instance Definition _ := isNmodMorphism.Build U R (a \o* f)
mulr_fun_is_nmod_morphism.
End MulFun.
Section Properties.
Variables (U V : zmodType) (f : {additive U -> V}).
Lemma raddfN : {morph f : x / - x}. Proof. exact: raddfN. Qed.
Lemma raddfB : {morph f : x y / x - y}. Proof. exact: raddfB. Qed.
Lemma raddf_inj : (forall x, f x = 0 -> x = 0) -> injective f.
Proof. exact: raddf_inj. Qed.
Lemma raddfMNn n : {morph f : x / x *- n}. Proof. exact: raddfMNn. Qed.
End Properties.
Section RingProperties.
Variables (R S : pzRingType) (f : {additive R -> S}).
Lemma raddfMsign n x : f ((-1) ^+ n * x) = (-1) ^+ n * f x.
Proof. by rewrite !(mulr_sign, =^~ signr_odd) (fun_if f) raddfN. Qed.
Variables (U : lmodType R) (V : lmodType S) (h : {additive U -> V}).
Lemma raddfZsign n u : h ((-1) ^+ n *: u) = (-1) ^+ n *: h u.
Proof. by rewrite !(scaler_sign, =^~ signr_odd) (fun_if h) raddfN. Qed.
End RingProperties.
Section ScaleFun.
Variables (R : pzSemiRingType) (U : nmodType) (V : lSemiModType R).
Variables (a : R) (f : {additive U -> V}).
#[export]
HB.instance Definition _ :=
isNmodMorphism.Build V V ( *:%R a) (conj (scaler0 _ a) (scalerDr a)).
#[export]
HB.instance Definition _ := Additive.copy (a \*: f) (f \; *:%R a).
End ScaleFun.
End AdditiveTheory.
#[deprecated(since="mathcomp 2.5.0", note="use `monoid_morphism` instead")]
Definition multiplicative (R S : pzSemiRingType) (f : R -> S) : Prop :=
{morph f : x y / x * y}%R * (f 1 = 1).
(* FIXME: remove once PzSemiRing extends Monoid. *)
Definition monoid_morphism (R S : pzSemiRingType) (f : R -> S) : Prop :=
(f 1 = 1) * {morph f : x y / x * y}%R.
HB.mixin Record isMonoidMorphism (R S : pzSemiRingType) (f : R -> S) := {
monoid_morphism_subproof : monoid_morphism f
}.
HB.structure Definition RMorphism (R S : pzSemiRingType) :=
{f of @isNmodMorphism R S f & isMonoidMorphism R S f}.
(* FIXME: remove the @ once
https://github.com/math-comp/hierarchy-builder/issues/319 is fixed *)
#[warning="-deprecated-since-mathcomp-2.5.0"]
HB.factory Record isMultiplicative (R S : pzSemiRingType) (f : R -> S) := {
rmorphism_subproof : multiplicative f
}.
HB.builders Context R S f of isMultiplicative R S f.
#[warning="-HB.no-new-instance"]
HB.instance Definition _ := isMonoidMorphism.Build R S f
(rmorphism_subproof.2, rmorphism_subproof.1).
HB.end.
Module RMorphismExports.
Notation "{ 'rmorphism' U -> V }" := (RMorphism.type U%type V%type)
: type_scope.
End RMorphismExports.
HB.export RMorphismExports.
Section RmorphismTheory.
Section Properties.
Variables (R S : pzSemiRingType) (f : {rmorphism R -> S}).
Lemma rmorph0 : f 0 = 0. Proof. exact: raddf0. Qed.
Lemma rmorphD : {morph f : x y / x + y}. Proof. exact: raddfD. Qed.
Lemma rmorphMn n : {morph f : x / x *+ n}. Proof. exact: raddfMn. Qed.
Lemma rmorph_sum I r (P : pred I) E :
f (\sum_(i <- r | P i) E i) = \sum_(i <- r | P i) f (E i).
Proof. exact: raddf_sum. Qed.
Lemma rmorphism_monoidP : monoid_morphism f.
Proof. exact: monoid_morphism_subproof. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `rmorphism_monoidP` instead")]
Definition rmorphismMP : multiplicative f :=
(fun p => (p.2, p.1)) rmorphism_monoidP.
Lemma rmorph1 : f 1 = 1. Proof. by case: rmorphism_monoidP. Qed.
Lemma rmorphM : {morph f: x y / x * y}. Proof. by case: rmorphism_monoidP. Qed.
Lemma rmorph_prod I r (P : pred I) E :
f (\prod_(i <- r | P i) E i) = \prod_(i <- r | P i) f (E i).
Proof. exact: (big_morph f rmorphM rmorph1). Qed.
Lemma rmorphXn n : {morph f : x / x ^+ n}.
Proof. by elim: n => [|n IHn] x; rewrite ?rmorph1 // !exprS rmorphM IHn. Qed.
Lemma rmorph_nat n : f n%:R = n%:R. Proof. by rewrite rmorphMn rmorph1. Qed.
Lemma rmorph_eq_nat x n : injective f -> (f x == n%:R) = (x == n%:R).
Proof. by move/inj_eq <-; rewrite rmorph_nat. Qed.
Lemma rmorph_eq1 x : injective f -> (f x == 1) = (x == 1).
Proof. exact: rmorph_eq_nat 1%N. Qed.
Lemma can2_monoid_morphism f' : cancel f f' -> cancel f' f -> monoid_morphism f'.
Proof.
move=> fK f'K.
by split=> [|x y]; apply: (canLR fK); rewrite /= (rmorph1, rmorphM) ?f'K.
Qed.
#[deprecated(since="mathcomp 2.5.0",
note="use `can2_monoid_morphism` instead")]
Definition can2_rmorphism f' (cff' : cancel f f') :=
(fun p => (p.2, p.1)) \o (can2_monoid_morphism cff').
End Properties.
Lemma rmorph_pchar (R S : nzSemiRingType) (f : {rmorphism R -> S}) p :
p \in pchar R -> p \in pchar S.
Proof.
by rewrite !inE -(rmorph_nat f) => /andP[-> /= /eqP->]; rewrite rmorph0.
Qed.
Section Projections.
Variables (R S T : pzSemiRingType).
Variables (f : {rmorphism S -> T}) (g : {rmorphism R -> S}).
Fact idfun_is_monoid_morphism : monoid_morphism (@idfun R).
Proof. by []. Qed.
#[export]
HB.instance Definition _ := isMonoidMorphism.Build R R idfun
idfun_is_monoid_morphism.
Fact comp_is_monoid_morphism : monoid_morphism (f \o g).
Proof. by split=> [|x y] /=; rewrite ?rmorph1 ?rmorphM. Qed.
#[export]
HB.instance Definition _ := isMonoidMorphism.Build R T (f \o g)
comp_is_monoid_morphism.
End Projections.
Section Properties.
Variables (R S : pzRingType) (f : {rmorphism R -> S}).
Lemma rmorphN : {morph f : x / - x}. Proof. exact: raddfN. Qed.
Lemma rmorphB : {morph f: x y / x - y}. Proof. exact: raddfB. Qed.
Lemma rmorphMNn n : {morph f : x / x *- n}. Proof. exact: raddfMNn. Qed.
Lemma rmorphMsign n : {morph f : x / (- 1) ^+ n * x}.
Proof. exact: raddfMsign. Qed.
Lemma rmorphN1 : f (- 1) = (- 1). Proof. by rewrite rmorphN rmorph1. Qed.
Lemma rmorph_sign n : f ((- 1) ^+ n) = (- 1) ^+ n.
Proof. by rewrite rmorphXn /= rmorphN1. Qed.
End Properties.
Section InSemiAlgebra.
Variables (R : pzSemiRingType) (A : lSemiAlgType R).
Fact in_alg_is_nmod_morphism : nmod_morphism (in_alg A).
Proof. by split; [exact: scale0r | exact: scalerDl]. Qed.
#[export]
HB.instance Definition _ :=
isNmodMorphism.Build R A (in_alg A) in_alg_is_nmod_morphism.
Fact in_alg_is_monoid_morphism : monoid_morphism (in_alg A).
Proof. by split=> [|x y]; rewrite /= ?scale1r // mulr_algl scalerA. Qed.
#[export]
HB.instance Definition _ := isMonoidMorphism.Build R A (in_alg A)
in_alg_is_monoid_morphism.
Lemma in_algE a : in_alg A a = a%:A. Proof. by []. Qed.
End InSemiAlgebra.
End RmorphismTheory.
#[deprecated(since="mathcomp 2.4.0", note="Use rmorph_pchar instead.")]
Notation rmorph_char := rmorph_pchar (only parsing).
Module Scale.
HB.mixin Record isPreLaw
(R : pzSemiRingType) (V : nmodType) (op : R -> V -> V) := {
op_nmod_morphism : forall a, nmod_morphism (op a);
}.
#[export]
HB.structure Definition PreLaw R V := {op of isPreLaw R V op}.
Definition preLaw := PreLaw.type.
HB.mixin Record isSemiLaw
(R : pzSemiRingType) (V : nmodType) (op : R -> V -> V) := {
op0v : forall v, op 0 v = 0;
op1v : op 1 =1 id;
opA : forall a b v, op a (op b v) = op (a * b) v;
}.
#[export]
HB.structure Definition SemiLaw R V :=
{op of isPreLaw R V op & isSemiLaw R V op}.
Definition semiLaw := SemiLaw.type.
HB.mixin Record isLaw (R : pzRingType) (V : zmodType) (op : R -> V -> V) :=
{ N1op : op (-1) =1 -%R }.
#[export]
HB.structure Definition Law (R : pzRingType) (V : zmodType) :=
{op of isPreLaw R V op & isLaw R V op}.
Definition law := Law.type.
Section CompSemiLaw.
Context (R : pzSemiRingType) (V : nmodType) (s : semiLaw R V).
Context (aR : pzSemiRingType) (nu : {rmorphism aR -> R}).
Fact comp_op0v v : (nu \; s) 0 v = 0.
Proof. by rewrite /= rmorph0 op0v. Qed.
Fact comp_op1v : (nu \; s) 1 =1 id.
Proof. by move=> v; rewrite /= rmorph1 op1v. Qed.
Fact comp_opA a b v : (nu \; s) a ((nu \; s) b v) = (nu \; s) (a * b) v.
Proof. by rewrite /= opA rmorphM. Qed.
End CompSemiLaw.
Fact compN1op
(R : pzRingType) (V : zmodType) (s : law R V)
(aR : pzRingType) (nu : {rmorphism aR -> R}) : (nu \; s) (-1) =1 -%R.
Proof. by move=> v; rewrite /= rmorphN1 N1op. Qed.
Module Exports. HB.reexport. End Exports.
End Scale.
Export Scale.Exports.
#[export]
HB.instance Definition _ (R : pzSemiRingType) :=
Scale.isPreLaw.Build R R *%R (fun => mull_fun_is_nmod_morphism _ idfun).
#[export]
HB.instance Definition _ (R : pzSemiRingType) :=
Scale.isSemiLaw.Build R R *%R mul0r mul1r mulrA.
#[export]
HB.instance Definition _ (R : pzRingType) :=
Scale.isLaw.Build R R *%R (@mulN1r R).
#[export]
HB.instance Definition _ (R : pzSemiRingType) (V : lSemiModType R) :=
Scale.isPreLaw.Build R V *:%R (fun => (scaler0 _ _, scalerDr _)).
#[export]
HB.instance Definition _ (R : pzSemiRingType) (V : lSemiModType R) :=
Scale.isSemiLaw.Build R V *:%R scale0r scale1r (@scalerA _ _).
#[export]
HB.instance Definition _ (R : pzRingType) (U : lmodType R) :=
Scale.isLaw.Build R U *:%R (@scaleN1r R U).
#[export]
HB.instance Definition _
(R : pzSemiRingType) (V : nmodType) (s : Scale.preLaw R V)
(aR : pzSemiRingType) (nu : {rmorphism aR -> R}) :=
Scale.isPreLaw.Build aR V (nu \; s) (fun => Scale.op_nmod_morphism _).
#[export]
HB.instance Definition _
(R : pzSemiRingType) (V : nmodType) (s : Scale.semiLaw R V)
(aR : pzSemiRingType) (nu : {rmorphism aR -> R}) :=
Scale.isSemiLaw.Build aR V (nu \; s)
(Scale.comp_op0v s nu) (Scale.comp_op1v s nu) (Scale.comp_opA s nu).
#[export]
HB.instance Definition _
(R : pzRingType) (V : zmodType) (s : Scale.law R V)
(aR : pzRingType) (nu : {rmorphism aR -> R}) :=
Scale.isLaw.Build aR V (nu \; s) (Scale.compN1op s nu).
#[export, non_forgetful_inheritance]
HB.instance Definition _
(R : pzSemiRingType) (V : nmodType) (s : Scale.preLaw R V) a :=
isNmodMorphism.Build V V (s a) (Scale.op_nmod_morphism a).
Definition scalable_for (R : pzSemiRingType) (U : lSemiModType R) (V : nmodType)
(s : R -> V -> V) (f : U -> V) :=
forall a, {morph f : u / a *: u >-> s a u}.
HB.mixin Record isScalable (R : pzSemiRingType) (U : lSemiModType R)
(V : nmodType) (s : R -> V -> V) (f : U -> V) := {
semi_linear_subproof : scalable_for s f;
}.
HB.structure Definition Linear (R : pzSemiRingType)
(U : lSemiModType R) (V : nmodType) (s : R -> V -> V) :=
{f of @isNmodMorphism U V f & isScalable R U V s f}.
Definition semilinear_for (R : pzSemiRingType)
(U : lSemiModType R) (V : nmodType) (s : R -> V -> V) (f : U -> V) : Type :=
scalable_for s f * {morph f : x y / x + y}.
Lemma nmod_morphism_semilinear (R : pzSemiRingType)
(U : lSemiModType R) (V : nmodType) (s : Scale.semiLaw R V) (f : U -> V) :
semilinear_for s f -> nmod_morphism f.
Proof.
by case=> sf Df; split => //; rewrite -[0 in LHS](scale0r 0) sf Scale.op0v.
Qed.
Definition additive_semilinear := nmod_morphism_semilinear.
Lemma scalable_semilinear (R : pzSemiRingType)
(U : lSemiModType R) (V : nmodType) (s : Scale.preLaw R V) (f : U -> V) :
semilinear_for s f -> scalable_for s f.
Proof. by case. Qed.
HB.factory Record isSemilinear (R : pzSemiRingType) (U : lSemiModType R)
(V : nmodType) (s : Scale.semiLaw R V) (f : U -> V) := {
linear_subproof : semilinear_for s f;
}.
HB.builders Context R U V s f of isSemilinear R U V s f.
HB.instance Definition _ := isNmodMorphism.Build U V f
(additive_semilinear linear_subproof).
HB.instance Definition _ :=
isScalable.Build R U V s f (scalable_semilinear linear_subproof).
HB.end.
Definition linear_for (R : pzSemiRingType) (U : lSemiModType R) (V : nmodType)
(s : R -> V -> V) (f : U -> V) :=
forall a, {morph f : u v / a *: u + v >-> s a u + v}.
Lemma zmod_morphism_linear (R : pzRingType) (U : lmodType R) V
(s : Scale.law R V) (f : U -> V) : linear_for s f -> zmod_morphism f.
Proof. by move=> Lsf x y; rewrite -scaleN1r addrC Lsf Scale.N1op addrC. Qed.
#[deprecated(since="mathcomp 2.5.0",
note="use `zmod_morphism_linear` instead")]
Definition additive_linear := zmod_morphism_linear.
Lemma scalable_linear (R : pzRingType) (U : lmodType R) V
(s : Scale.law R V) (f : U -> V) : linear_for s f -> scalable_for s f.
Proof.
by move=> Lsf a v; rewrite -[a *:v](addrK v) (zmod_morphism_linear Lsf) Lsf addrK.
Qed.
Lemma semilinear_linear (R : pzRingType) (U : lmodType R) V
(s : Scale.law R V) (f : U -> V) : linear_for s f -> semilinear_for s f.
Proof.
move=> Lsf; split=> [a x|x y]; first exact: (scalable_linear Lsf).
have f0: f 0 = 0 by rewrite -[0 in LHS]subr0 (zmod_morphism_linear Lsf) subrr.
by rewrite -[y in LHS]opprK -[- y]add0r !(zmod_morphism_linear Lsf) f0 sub0r opprK.
Qed.
HB.factory Record isLinear (R : pzRingType) (U : lmodType R) (V : zmodType)
(s : Scale.law R V) (f : U -> V) := {
linear_subproof : linear_for s f;
}.
HB.builders Context R U V s f of isLinear R U V s f.
HB.instance Definition _ := isZmodMorphism.Build U V f
(zmod_morphism_linear linear_subproof).
HB.instance Definition _ := isScalable.Build R U V s f
(scalable_linear linear_subproof).
HB.end.
Module LinearExports.
Notation scalable f := (scalable_for *:%R f).
Notation semilinear f := (semilinear_for *:%R f).
Notation semiscalar f := (semilinear_for *%R f).
Notation linear f := (linear_for *:%R f).
Notation scalar f := (linear_for *%R f).
Module Linear.
Section Linear.
Variables (R : pzSemiRingType) (U : lSemiModType R) (V : nmodType).
Variables (s : R -> V -> V).
(* Support for right-to-left rewriting with the generic linearZ rule. *)
Local Notation mapUV := (@Linear.type R U V s).
Definition map_class := mapUV.
Definition map_at (a : R) := mapUV.
Structure map_for a s_a := MapFor {map_for_map : mapUV; _ : s a = s_a}.
Definition unify_map_at a (g : map_at a) := MapFor g (erefl (s a)).
Structure wrapped := Wrap {unwrap : mapUV}.
Definition wrap (f : map_class) := Wrap f.
End Linear.
End Linear.
Notation "{ 'linear' U -> V | s }" := (@Linear.type _ U V s) : type_scope.
Notation "{ 'linear' U -> V }" := {linear U -> V | *:%R} : type_scope.
Notation "{ 'scalar' U }" := {linear U -> _ | *%R}
(format "{ 'scalar' U }") : type_scope.
(* Support for right-to-left rewriting with the generic linearZ rule. *)
Coercion Linear.map_for_map : Linear.map_for >-> Linear.type.
Coercion Linear.unify_map_at : Linear.map_at >-> Linear.map_for.
Canonical Linear.unify_map_at.
Coercion Linear.unwrap : Linear.wrapped >-> Linear.type.
Coercion Linear.wrap : Linear.map_class >-> Linear.wrapped.
Canonical Linear.wrap.
End LinearExports.
HB.export LinearExports.
Section LinearTheory.
Section GenericProperties.
Variables (R : pzSemiRingType) (U : lSemiModType R) (V : nmodType).
Variables (s : R -> V -> V) (f : {linear U -> V | s}).
Lemma linear0 : f 0 = 0. Proof. exact: raddf0. Qed.
Lemma linearD : {morph f : x y / x + y}. Proof. exact: raddfD. Qed.
Lemma linearMn n : {morph f : x / x *+ n}. Proof. exact: raddfMn. Qed.
Lemma linear_sum I r (P : pred I) E :
f (\sum_(i <- r | P i) E i) = \sum_(i <- r | P i) f (E i).
Proof. exact: raddf_sum. Qed.
Lemma linearZ_LR : scalable_for s f. Proof. exact: semi_linear_subproof. Qed.
Lemma semilinearP : semilinear_for s f.
Proof. split; [exact: linearZ_LR | exact: linearD]. Qed.
Lemma linearP : linear_for s f.
Proof. by move=> a u v /=; rewrite !semilinearP. Qed.
End GenericProperties.
Section GenericProperties.
Variables (R : pzRingType) (U : lmodType R) (V : zmodType) (s : R -> V -> V).
Variables (f : {linear U -> V | s}).
Lemma linearN : {morph f : x / - x}. Proof. exact: raddfN. Qed.
Lemma linearB : {morph f : x y / x - y}. Proof. exact: raddfB. Qed.
Lemma linearMNn n : {morph f : x / x *- n}. Proof. exact: raddfMNn. Qed.
End GenericProperties.
Section BidirectionalLinearZ.
(* The general form of the linearZ lemma uses some bespoke interfaces to *)
(* allow right-to-left rewriting when a composite scaling operation such as *)
(* conjC \; *%R has been expanded, say in a^* * f u. This redex is matched *)
(* by using the Scale.law interface to recognize a "head" scaling operation *)
(* h (here *%R), stow away its "scalar" c, then reconcile h c and s a, once *)
(* s is known, that is, once the Linear.map structure for f has been found. *)
(* In general, s and a need not be equal to h and c; indeed they need not *)
(* have the same type! The unification is performed by the unify_map_at *)
(* default instance for the Linear.map_for U s a h_c sub-interface of *)
(* Linear.map; the h_c pattern uses the Scale.law structure to insure it is *)
(* inferred when rewriting right-to-left. *)
(* The wrap on the rhs allows rewriting f (a *: b *: u) into a *: b *: f u *)
(* with rewrite !linearZ /= instead of rewrite linearZ /= linearZ /=. *)
(* Without it, the first rewrite linearZ would produce *)
(* (a *: apply (map_for_map (@check_map_at .. a f)) (b *: u)%R)%Rlin *)
(* and matching the second rewrite LHS would bypass the unify_map_at default *)
(* instance for b, reuse the one for a, and subsequently fail to match the *)
(* b *: u argument. The extra wrap / unwrap ensures that this can't happen. *)
(* In the RL direction, the wrap / unwrap will be inserted on the redex side *)
(* as needed, without causing unnecessary delta-expansion: using an explicit *)
(* identity function would have Coq normalize the redex to head normal, then *)
(* reduce the identity to expose the map_for_map projection, and the *)
(* expanded Linear.map structure would then be exposed in the result. *)
(* Most of this machinery will be invisible to a casual user, because all *)
(* the projections and default instances involved are declared as coercions. *)
Lemma linearZ (R : pzSemiRingType) (U : lSemiModType R) (V : nmodType)
(s : R -> V -> V) (S : pzSemiRingType) (h : Scale.preLaw S V)
(c : S) (a : R) (h_c := h c) (f : Linear.map_for U s a h_c) (u : U) :
f (a *: u) = h_c (Linear.wrap f u).
Proof. by rewrite linearZ_LR; case: f => f /= ->. Qed.
End BidirectionalLinearZ.
Section LmodProperties.
Variables (R : pzSemiRingType) (U V : lSemiModType R) (f : {linear U -> V}).
Lemma linearZZ : scalable f. Proof. exact: linearZ_LR. Qed.
Lemma semilinearPZ : semilinear f. Proof. exact: semilinearP. Qed.
Lemma linearPZ : linear f. Proof. exact: linearP. Qed.
Lemma can2_scalable f' : cancel f f' -> cancel f' f -> scalable f'.
Proof. by move=> fK f'K a x; apply: (canLR fK); rewrite linearZZ f'K. Qed.
Lemma can2_semilinear f' : cancel f f' -> cancel f' f -> semilinear f'.
Proof.
by move=> fK f'K; split=> ? ?; apply: (canLR fK); rewrite semilinearPZ !f'K.
Qed.
Lemma can2_linear f' : cancel f f' -> cancel f' f -> linear f'.
Proof. by move=> fK f'K a x y /=; apply: (canLR fK); rewrite linearP !f'K. Qed.
End LmodProperties.
Section ScalarProperties.
Variable (R : pzSemiRingType) (U : lSemiModType R) (f : {scalar U}).
Lemma scalarZ : scalable_for *%R f. Proof. exact: linearZ_LR. Qed.
Lemma semiscalarP : semiscalar f. Proof. exact: semilinearP. Qed.
Lemma scalarP : scalar f. Proof. exact: linearP. Qed.
End ScalarProperties.
Section LinearLSemiMod.
Section Idfun.
Variables (R : pzSemiRingType) (U : lSemiModType R).
Lemma idfun_is_scalable : scalable (@idfun U). Proof. by []. Qed.
#[export]
HB.instance Definition _ := isScalable.Build R U U *:%R idfun idfun_is_scalable.
End Idfun.
Section Plain.
Variables (R : pzSemiRingType) (W U : lSemiModType R) (V : nmodType).
Variables (s : R -> V -> V) (f : {linear U -> V | s}) (g : {linear W -> U}).
Lemma comp_is_scalable : scalable_for s (f \o g).
Proof. by move=> a v /=; rewrite !linearZ_LR. Qed.
#[export]
HB.instance Definition _ := isScalable.Build R W V s (f \o g) comp_is_scalable.
End Plain.
Section SemiScale.
Variables (R : pzSemiRingType) (U : lSemiModType R) (V : nmodType).
Variables (s : Scale.preLaw R V) (f g : {linear U -> V | s}).
Lemma null_fun_is_scalable : scalable_for s (\0 : U -> V).
Proof. by move=> a v /=; rewrite raddf0. Qed.
#[export]
HB.instance Definition _ :=
isScalable.Build R U V s \0 null_fun_is_scalable.
Lemma add_fun_is_scalable : scalable_for s (add_fun f g).
Proof. by move=> a u; rewrite /= !linearZ_LR raddfD. Qed.
#[export]
HB.instance Definition _ :=
isScalable.Build R U V s (f \+ g) add_fun_is_scalable.
End SemiScale.
End LinearLSemiMod.
Section LinearLmod.
Variables (R : pzRingType) (U : lmodType R).
Lemma opp_is_scalable : scalable (-%R : U -> U).
Proof. by move=> a v /=; rewrite scalerN. Qed.
#[export]
HB.instance Definition _ := isScalable.Build R U U *:%R -%R opp_is_scalable.
End LinearLmod.
Section Scale.
Variables (R : pzRingType) (U : lmodType R) (V : zmodType).
Variables (s : Scale.preLaw R V) (f g : {linear U -> V | s}).
Lemma sub_fun_is_scalable : scalable_for s (f \- g).
Proof. by move=> a u; rewrite /= !linearZ_LR raddfB. Qed.
#[export]
HB.instance Definition _ :=
isScalable.Build R U V s (f \- g) sub_fun_is_scalable.
Lemma opp_fun_is_scalable : scalable_for s (\- f).
Proof. by move=> a u; rewrite /= linearZ_LR raddfN. Qed.
#[export]
HB.instance Definition _ := isScalable.Build R U V s (\- f) opp_fun_is_scalable.
End Scale.
Section LinearLSemiAlg.
Variables (R : pzSemiRingType) (A : lSemiAlgType R) (U : lSemiModType R).
Variables (a : A) (f : {linear U -> A}).
Fact mulr_fun_is_scalable : scalable (a \o* f).
Proof. by move=> k x /=; rewrite linearZ scalerAl. Qed.
#[export]
HB.instance Definition _ :=
isScalable.Build R U A *:%R (a \o* f) mulr_fun_is_scalable.
End LinearLSemiAlg.
End LinearTheory.
HB.structure Definition LRMorphism (R : pzSemiRingType) (A : lSemiAlgType R)
(B : pzSemiRingType) (s : R -> B -> B) :=
{f of @RMorphism A B f & isScalable R A B s f}.
(* FIXME: remove the @ once
https://github.com/math-comp/hierarchy-builder/issues/319 is fixed *)
Module LRMorphismExports.
Notation "{ 'lrmorphism' A -> B | s }" := (@LRMorphism.type _ A%type B%type s)
: type_scope.
Notation "{ 'lrmorphism' A -> B }" := {lrmorphism A%type -> B%type | *:%R}
: type_scope.
End LRMorphismExports.
HB.export LRMorphismExports.
Section LRMorphismTheory.
Variables (R : pzSemiRingType) (A B : lSemiAlgType R) (C : pzSemiRingType).
Variables (s : R -> C -> C).
Variables (f : {lrmorphism A -> B}) (g : {lrmorphism B -> C | s}).
#[export] HB.instance Definition _ := RMorphism.on (@idfun A).
#[export] HB.instance Definition _ := RMorphism.on (g \o f).
Lemma rmorph_alg a : f a%:A = a%:A.
Proof. by rewrite linearZ /= rmorph1. Qed.
End LRMorphismTheory.
HB.mixin Record PzSemiRing_hasCommutativeMul R of PzSemiRing R := {
mulrC : commutative (@mul R)
}.
Module SemiRing_hasCommutativeMul.
#[deprecated(since="mathcomp 2.4.0",
note="Use PzSemiRing_hasCommutativeMul.Build instead.")]
Notation Build R := (PzSemiRing_hasCommutativeMul.Build R) (only parsing).
End SemiRing_hasCommutativeMul.
#[deprecated(since="mathcomp 2.4.0",
note="Use PzSemiRing_hasCommutativeMul instead.")]
Notation SemiRing_hasCommutativeMul R :=
(PzSemiRing_hasCommutativeMul R) (only parsing).
#[short(type="comPzSemiRingType")]
HB.structure Definition ComPzSemiRing :=
{R of PzSemiRing R & PzSemiRing_hasCommutativeMul R}.
Module ComPzSemiRingExports.
Bind Scope ring_scope with ComPzSemiRing.sort.
End ComPzSemiRingExports.
HB.export ComPzSemiRingExports.
HB.factory Record Nmodule_isComPzSemiRing R of Nmodule R := {
one : R;
mul : R -> R -> R;
mulrA : associative mul;
mulrC : commutative mul;
mul1r : left_id one mul;
mulrDl : left_distributive mul add;
mul0r : left_zero zero mul;
}.
HB.builders Context R of Nmodule_isComPzSemiRing R.
Definition mulr1 := Monoid.mulC_id mulrC mul1r.
Definition mulrDr := Monoid.mulC_dist mulrC mulrDl.
Lemma mulr0 : right_zero zero mul.
Proof. by move=> x; rewrite mulrC mul0r. Qed.
HB.instance Definition _ := Nmodule_isPzSemiRing.Build R
mulrA mul1r mulr1 mulrDl mulrDr mul0r mulr0.
HB.instance Definition _ := PzSemiRing_hasCommutativeMul.Build R mulrC.
HB.end.
#[short(type="comNzSemiRingType")]
HB.structure Definition ComNzSemiRing :=
{R of NzSemiRing R & PzSemiRing_hasCommutativeMul R}.
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzSemiRing instead.")]
Notation ComSemiRing R := (ComNzSemiRing R) (only parsing).
Module ComSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzSemiRing.sort instead.")]
Notation sort := (ComNzSemiRing.sort) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzSemiRing.on instead.")]
Notation on R := (ComNzSemiRing.on R) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzSemiRing.copy instead.")]
Notation copy T U := (ComNzSemiRing.copy T U) (only parsing).
End ComSemiRing.
Module ComNzSemiRingExports.
Bind Scope ring_scope with ComNzSemiRing.sort.
End ComNzSemiRingExports.
HB.export ComNzSemiRingExports.
HB.factory Record Nmodule_isComNzSemiRing R of Nmodule R := {
one : R;
mul : R -> R -> R;
mulrA : associative mul;
mulrC : commutative mul;
mul1r : left_id one mul;
mulrDl : left_distributive mul add;
mul0r : left_zero zero mul;
oner_neq0 : one != zero
}.
Module Nmodule_isComSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use Nmodule_isComNzSemiRing.Build instead.")]
Notation Build R := (Nmodule_isComNzSemiRing.Build R) (only parsing).
End Nmodule_isComSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use Nmodule_isComNzSemiRing instead.")]
Notation Nmodule_isComSemiRing R := (Nmodule_isComNzSemiRing R) (only parsing).
HB.builders Context R of Nmodule_isComNzSemiRing R.
Definition mulr1 := Monoid.mulC_id mulrC mul1r.
Definition mulrDr := Monoid.mulC_dist mulrC mulrDl.
Lemma mulr0 : right_zero zero mul.
Proof. by move=> x; rewrite mulrC mul0r. Qed.
HB.instance Definition _ := Nmodule_isNzSemiRing.Build R
mulrA mul1r mulr1 mulrDl mulrDr mul0r mulr0 oner_neq0.
HB.instance Definition _ := PzSemiRing_hasCommutativeMul.Build R mulrC.
HB.end.
Section ComSemiRingTheory.
Variable R : comPzSemiRingType.
Implicit Types x y : R.
#[export]
HB.instance Definition _ := SemiGroup.isCommutativeLaw.Build R *%R mulrC.
Lemma mulrCA : @left_commutative R R *%R. Proof. exact: mulmCA. Qed.
Lemma mulrAC : @right_commutative R R *%R. Proof. exact: mulmAC. Qed.
Lemma mulrACA : @interchange R *%R *%R. Proof. exact: mulmACA. Qed.
Lemma exprMn n : {morph (fun x => x ^+ n) : x y / x * y}.
Proof. by move=> x y; exact/exprMn_comm/mulrC. Qed.
Lemma prodrXl n I r (P : pred I) (F : I -> R) :
\prod_(i <- r | P i) F i ^+ n = (\prod_(i <- r | P i) F i) ^+ n.
Proof. by rewrite (big_morph _ (exprMn n) (expr1n _ n)). Qed.
Lemma prodr_undup_exp_count (I : eqType) r (P : pred I) (F : I -> R) :
\prod_(i <- undup r | P i) F i ^+ count_mem i r = \prod_(i <- r | P i) F i.
Proof. exact: big_undup_iterop_count. Qed.
Lemma prodrMl {I : finType} (A : pred I) (x : R) F :
\prod_(i in A) (x * F i) = x ^+ #|A| * \prod_(i in A) F i.
Proof. by rewrite big_split ?prodr_const. Qed.
Lemma prodrMr {I : finType} (A : pred I) (x : R) F :
\prod_(i in A) (F i * x) = \prod_(i in A) F i * x ^+ #|A|.
Proof. by rewrite big_split ?prodr_const. Qed.
Lemma exprDn x y n :
(x + y) ^+ n = \sum_(i < n.+1) (x ^+ (n - i) * y ^+ i) *+ 'C(n, i).
Proof. by rewrite exprDn_comm //; apply: mulrC. Qed.
Lemma sqrrD x y : (x + y) ^+ 2 = x ^+ 2 + x * y *+ 2 + y ^+ 2.
Proof. by rewrite exprDn !big_ord_recr big_ord0 /= add0r mulr1 mul1r. Qed.
End ComSemiRingTheory.
(* FIXME: Generalize to `comPzSemiRingType` ? *)
Section ComNzSemiRingTheory.
Variable R : comNzSemiRingType.
Implicit Types x y : R.
Section FrobeniusAutomorphism.
Variables (p : nat) (pcharRp : p \in pchar R).
Lemma pFrobenius_aut_is_nmod_morphism : nmod_morphism (pFrobenius_aut pcharRp).
Proof.
by split=> [|x y]; [exact: pFrobenius_aut0 | exact/pFrobenius_autD_comm/mulrC].
Qed.
Lemma pFrobenius_aut_is_monoid_morphism : monoid_morphism (pFrobenius_aut pcharRp).
Proof.
by split=> [|x y]; [exact: pFrobenius_aut1 | exact/pFrobenius_autM_comm/mulrC].
Qed.
#[export]
HB.instance Definition _ := isNmodMorphism.Build R R (pFrobenius_aut pcharRp)
pFrobenius_aut_is_nmod_morphism.
#[export]
HB.instance Definition _ := isMonoidMorphism.Build R R (pFrobenius_aut pcharRp)
pFrobenius_aut_is_monoid_morphism.
End FrobeniusAutomorphism.
Lemma exprDn_pchar x y n : (pchar R).-nat n -> (x + y) ^+ n = x ^+ n + y ^+ n.
Proof.
pose p := pdiv n; have [|n_gt1 pcharRn] := leqP n 1; first by case: (n) => [|[]].
have pcharRp: p \in pchar R by rewrite (pnatPpi pcharRn) ?pi_pdiv.
have{pcharRn} /p_natP[e ->]: p.-nat n by rewrite -(eq_pnat _ (pcharf_eq pcharRp)).
by elim: e => // e IHe; rewrite !expnSr !exprM IHe -pFrobenius_autE rmorphD.
Qed.
(* FIXME: Generalize to `comPzSemiRingType` ? *)
Lemma rmorph_comm (S : nzSemiRingType) (f : {rmorphism R -> S}) x y :
comm (f x) (f y).
Proof. by red; rewrite -!rmorphM mulrC. Qed.
Section ScaleLinear.
Variables (U V : lSemiModType R) (b : R) (f : {linear U -> V}).
Lemma scale_is_scalable : scalable ( *:%R b : V -> V).
Proof. by move=> a v /=; rewrite !scalerA mulrC. Qed.
#[export]
HB.instance Definition _ :=
isScalable.Build R V V *:%R ( *:%R b) scale_is_scalable.
Lemma scale_fun_is_scalable : scalable (b \*: f).
Proof. by move=> a v /=; rewrite !linearZ. Qed.
#[export]
HB.instance Definition _ :=
isScalable.Build R U V *:%R (b \*: f) scale_fun_is_scalable.
End ScaleLinear.
End ComNzSemiRingTheory.
#[short(type="comPzRingType")]
HB.structure Definition ComPzRing := {R of PzRing R & ComPzSemiRing R}.
HB.factory Record PzRing_hasCommutativeMul R of PzRing R := {
mulrC : commutative (@mul R)
}.
Module Ring_hasCommutativeMul.
#[deprecated(since="mathcomp 2.4.0",
note="Use PzRing_hasCommutativeMul.Build instead.")]
Notation Build R := (PzRing_hasCommutativeMul.Build R) (only parsing).
End Ring_hasCommutativeMul.
#[deprecated(since="mathcomp 2.4.0",
note="Use PzRing_hasCommutativeMul instead.")]
Notation Ring_hasCommutativeMul R :=
(PzRing_hasCommutativeMul R) (only parsing).
HB.builders Context R of PzRing_hasCommutativeMul R.
HB.instance Definition _ := PzSemiRing_hasCommutativeMul.Build R mulrC.
HB.end.
HB.factory Record Zmodule_isComPzRing R of Zmodule R := {
one : R;
mul : R -> R -> R;
mulrA : associative mul;
mulrC : commutative mul;
mul1r : left_id one mul;
mulrDl : left_distributive mul add;
}.
HB.builders Context R of Zmodule_isComPzRing R.
Definition mulr1 := Monoid.mulC_id mulrC mul1r.
Definition mulrDr := Monoid.mulC_dist mulrC mulrDl.
HB.instance Definition _ := Zmodule_isPzRing.Build R
mulrA mul1r mulr1 mulrDl mulrDr.
HB.instance Definition _ := PzRing_hasCommutativeMul.Build R mulrC.
HB.end.
Module ComPzRingExports.
Bind Scope ring_scope with ComPzRing.sort.
End ComPzRingExports.
HB.export ComPzRingExports.
#[deprecated(since="mathcomp 2.5.0",
note="Use pFrobenius_aut_is_monoid_morphism instead.")]
Notation pFrobenius_aut_is_multiplicative :=
(fun p => (p.2, p.1) \o pFrobenius_aut_is_monoid_morphism) (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use exprDn_pchar instead.")]
Notation exprDn_char := exprDn_pchar (only parsing).
#[short(type="comNzRingType")]
HB.structure Definition ComNzRing := {R of NzRing R & ComNzSemiRing R}.
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzRing instead.")]
Notation ComRing R := (ComNzRing R) (only parsing).
Module ComRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzRing.sort instead.")]
Notation sort := (ComNzRing.sort) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzRing.on instead.")]
Notation on R := (ComNzRing.on R) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzRing.copy instead.")]
Notation copy T U := (ComNzRing.copy T U) (only parsing).
End ComRing.
HB.factory Record Zmodule_isComNzRing R of Zmodule R := {
one : R;
mul : R -> R -> R;
mulrA : associative mul;
mulrC : commutative mul;
mul1r : left_id one mul;
mulrDl : left_distributive mul add;
oner_neq0 : one != zero
}.
Module Zmodule_isComRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use Zmodule_isComNzRing.Build instead.")]
Notation Build R := (Zmodule_isComNzRing.Build R) (only parsing).
End Zmodule_isComRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use Zmodule_isComNzRing instead.")]
Notation Zmodule_isComRing R := (Zmodule_isComNzRing R) (only parsing).
HB.builders Context R of Zmodule_isComNzRing R.
Definition mulr1 := Monoid.mulC_id mulrC mul1r.
Definition mulrDr := Monoid.mulC_dist mulrC mulrDl.
HB.instance Definition _ := Zmodule_isNzRing.Build R
mulrA mul1r mulr1 mulrDl mulrDr oner_neq0.
HB.instance Definition _ := PzRing_hasCommutativeMul.Build R mulrC.
HB.end.
Module ComNzRingExports.
Bind Scope ring_scope with ComNzRing.sort.
End ComNzRingExports.
HB.export ComNzRingExports.
Section ComPzRingTheory.
Variable R : comPzRingType.
Implicit Types x y : R.
Lemma exprBn x y n :
(x - y) ^+ n =
\sum_(i < n.+1) ((-1) ^+ i * x ^+ (n - i) * y ^+ i) *+ 'C(n, i).
Proof. by rewrite exprBn_comm //; apply: mulrC. Qed.
Lemma subrXX x y n :
x ^+ n - y ^+ n = (x - y) * (\sum_(i < n) x ^+ (n.-1 - i) * y ^+ i).
Proof. by rewrite -subrXX_comm //; apply: mulrC. Qed.
Lemma sqrrB x y : (x - y) ^+ 2 = x ^+ 2 - x * y *+ 2 + y ^+ 2.
Proof. by rewrite sqrrD mulrN mulNrn sqrrN. Qed.
Lemma subr_sqr x y : x ^+ 2 - y ^+ 2 = (x - y) * (x + y).
Proof. by rewrite subrXX !big_ord_recr big_ord0 /= add0r mulr1 mul1r. Qed.
Lemma subr_sqrDB x y : (x + y) ^+ 2 - (x - y) ^+ 2 = x * y *+ 4.
Proof.
rewrite sqrrD sqrrB -!(addrAC _ (y ^+ 2)) opprB.
by rewrite [LHS]addrC addrA subrK -mulrnDr.
Qed.
End ComPzRingTheory.
HB.mixin Record LSemiAlgebra_isSemiAlgebra R V of LSemiAlgebra R V := {
scalerAr : forall k (x y : V), k *: (x * y) = x * (k *: y);
}.
#[short(type="semiAlgType")]
HB.structure Definition SemiAlgebra (R : pzSemiRingType) :=
{A of LSemiAlgebra_isSemiAlgebra R A & LSemiAlgebra R A}.
Module SemiAlgExports.
Bind Scope ring_scope with SemiAlgebra.sort.
End SemiAlgExports.
HB.factory Record LSemiAlgebra_isComSemiAlgebra R V
of ComPzSemiRing V & LSemiAlgebra R V := {}.
HB.builders Context (R : pzSemiRingType) V of LSemiAlgebra_isComSemiAlgebra R V.
Lemma scalarAr k (x y : V) : k *: (x * y) = x * (k *: y).
Proof. by rewrite mulrC scalerAl mulrC. Qed.
HB.instance Definition _ := LSemiAlgebra_isSemiAlgebra.Build R V scalarAr.
HB.end.
#[short(type="algType")]
HB.structure Definition Algebra (R : pzRingType) :=
{A of LSemiAlgebra_isSemiAlgebra R A & Lalgebra R A}.
Module AlgExports.
Bind Scope ring_scope with Algebra.sort.
End AlgExports.
HB.export AlgExports.
HB.factory Record Lalgebra_isAlgebra (R : pzRingType) V of Lalgebra R V := {
scalerAr : forall k (x y : V), k *: (x * y) = x * (k *: y);
}.
HB.builders Context (R : pzRingType) V of Lalgebra_isAlgebra R V.
HB.instance Definition _ := LSemiAlgebra_isSemiAlgebra.Build R V scalerAr.
HB.end.
HB.factory Record Lalgebra_isComAlgebra R V of ComPzRing V & Lalgebra R V := {}.
HB.builders Context (R : pzRingType) V of Lalgebra_isComAlgebra R V.
Lemma scalarAr k (x y : V) : k *: (x * y) = x * (k *: y).
Proof. by rewrite mulrC scalerAl mulrC. Qed.
HB.instance Definition lalgebra_is_algebra : Lalgebra_isAlgebra R V :=
Lalgebra_isAlgebra.Build R V scalarAr.
HB.end.
#[short(type="comSemiAlgType")]
HB.structure Definition ComSemiAlgebra R :=
{V of ComNzSemiRing V & SemiAlgebra R V}.
Module ComSemiAlgExports.
Bind Scope ring_scope with ComSemiAlgebra.sort.
End ComSemiAlgExports.
HB.export ComSemiAlgExports.
Section SemiAlgebraTheory.
#[export]
HB.instance Definition _ (R : comPzSemiRingType) :=
PzSemiRing_hasCommutativeMul.Build R^c (fun _ _ => mulrC _ _).
#[export]
HB.instance Definition _ (R : comPzSemiRingType) := ComPzSemiRing.on R^o.
#[export]
HB.instance Definition _ (R : comNzSemiRingType) := ComNzSemiRing.on R^c.
#[export]
HB.instance Definition _ (R : comNzSemiRingType) := ComNzSemiRing.on R^o.
#[export]
HB.instance Definition _ (R : comNzSemiRingType) :=
LSemiAlgebra_isComSemiAlgebra.Build R R^o.
End SemiAlgebraTheory.
#[short(type="comAlgType")]
HB.structure Definition ComAlgebra R := {V of ComNzRing V & Algebra R V}.
Module ComAlgExports.
Bind Scope ring_scope with ComAlgebra.sort.
End ComAlgExports.
HB.export ComAlgExports.
Section AlgebraTheory.
#[export]
HB.instance Definition _ (R : comPzRingType) := ComPzRing.on R^c.
#[export]
HB.instance Definition _ (R : comPzRingType) := ComPzRing.on R^o.
#[export]
HB.instance Definition _ (R : comNzRingType) := ComNzRing.on R^c.
#[export]
HB.instance Definition _ (R : comNzRingType) := ComNzRing.on R^o.
End AlgebraTheory.
Section SemiAlgebraTheory.
Variables (R : pzSemiRingType) (A : semiAlgType R).
Implicit Types (k : R) (x y : A).
Lemma scalerCA k x y : k *: x * y = x * (k *: y).
Proof. by rewrite -scalerAl scalerAr. Qed.
Lemma mulr_algr a x : x * a%:A = a *: x.
Proof. by rewrite -scalerAr mulr1. Qed.
Lemma comm_alg a x : comm a%:A x.
Proof. by rewrite /comm mulr_algr mulr_algl. Qed.
Lemma exprZn k x n : (k *: x) ^+ n = k ^+ n *: x ^+ n.
Proof.
elim: n => [|n IHn]; first by rewrite !expr0 scale1r.
by rewrite !exprS IHn -scalerA scalerAr scalerAl.
Qed.
Lemma scaler_prod I r (P : pred I) (F : I -> R) (G : I -> A) :
\prod_(i <- r | P i) (F i *: G i) =
\prod_(i <- r | P i) F i *: \prod_(i <- r | P i) G i.
Proof.
elim/big_rec3: _ => [|i x a _ _ ->]; first by rewrite scale1r.
by rewrite -scalerAl -scalerAr scalerA.
Qed.
Lemma scaler_prodl (I : finType) (S : pred I) (F : I -> A) k :
\prod_(i in S) (k *: F i) = k ^+ #|S| *: \prod_(i in S) F i.
Proof. by rewrite scaler_prod prodr_const. Qed.
Lemma scaler_prodr (I : finType) (S : pred I) (F : I -> R) x :
\prod_(i in S) (F i *: x) = \prod_(i in S) F i *: x ^+ #|S|.
Proof. by rewrite scaler_prod prodr_const. Qed.
End SemiAlgebraTheory.
Section AlgebraTheory.
Variables (R : pzSemiRingType) (A : semiAlgType R).
Variables (U : lSemiModType R) (a : A) (f : {linear U -> A}).
Lemma mull_fun_is_scalable : scalable (a \*o f).
Proof. by move=> k x /=; rewrite linearZ scalerAr. Qed.
#[export]
HB.instance Definition _ := isScalable.Build R U A *:%R (a \*o f)
mull_fun_is_scalable.
End AlgebraTheory.
HB.mixin Record NzRing_hasMulInverse R of NzRing R := {
unit_subdef : pred R;
inv : R -> R;
mulVr_subproof : {in unit_subdef, left_inverse 1 inv *%R};
divrr_subproof : {in unit_subdef, right_inverse 1 inv *%R};
unitrP_subproof : forall x y, y * x = 1 /\ x * y = 1 -> unit_subdef x;
invr_out_subproof : {in [predC unit_subdef], inv =1 id}
}.
Module Ring_hasMulInverse.
#[deprecated(since="mathcomp 2.4.0",
note="Use NzRing_hasMulInverse.Build instead.")]
Notation Build R := (NzRing_hasMulInverse.Build R) (only parsing).
End Ring_hasMulInverse.
#[deprecated(since="mathcomp 2.4.0",
note="Use NzRing_hasMulInverse instead.")]
Notation Ring_hasMulInverse R := (NzRing_hasMulInverse R) (only parsing).
#[short(type="unitRingType")]
HB.structure Definition UnitRing := {R of NzRing_hasMulInverse R & NzRing R}.
Module UnitRingExports.
Bind Scope ring_scope with UnitRing.sort.
End UnitRingExports.
HB.export UnitRingExports.
Definition unit_pred {R : unitRingType} :=
Eval cbv [ unit_subdef NzRing_hasMulInverse.unit_subdef ] in
(fun u : R => unit_subdef u).
Arguments unit_pred _ _ /.
Definition unit {R : unitRingType} := [qualify a u : R | unit_pred u].
Local Notation "x ^-1" := (inv x).
Local Notation "x / y" := (x * y^-1).
Local Notation "x ^- n" := ((x ^+ n)^-1).
Section UnitRingTheory.
Variable R : unitRingType.
Implicit Types x y : R.
Lemma divrr : {in unit, right_inverse 1 (@inv R) *%R}.
Proof. exact: divrr_subproof. Qed.
Definition mulrV := divrr.
Lemma mulVr : {in unit, left_inverse 1 (@inv R) *%R}.
Proof. exact: mulVr_subproof. Qed.
Lemma invr_out x : x \isn't a unit -> x^-1 = x.
Proof. exact: invr_out_subproof. Qed.
Lemma unitrP x : reflect (exists y, y * x = 1 /\ x * y = 1) (x \is a unit).
Proof.
apply: (iffP idP) => [Ux | []]; last exact: unitrP_subproof.
by exists x^-1; rewrite divrr ?mulVr.
Qed.
Lemma mulKr : {in unit, left_loop (@inv R) *%R}.
Proof. by move=> x Ux y; rewrite mulrA mulVr ?mul1r. Qed.
Lemma mulVKr : {in unit, rev_left_loop (@inv R) *%R}.
Proof. by move=> x Ux y; rewrite mulrA mulrV ?mul1r. Qed.
Lemma mulrK : {in unit, right_loop (@inv R) *%R}.
Proof. by move=> x Ux y; rewrite -mulrA divrr ?mulr1. Qed.
Lemma mulrVK : {in unit, rev_right_loop (@inv R) *%R}.
Proof. by move=> x Ux y; rewrite -mulrA mulVr ?mulr1. Qed.
Definition divrK := mulrVK.
Lemma mulrI : {in @unit R, right_injective *%R}.
Proof. by move=> x Ux; apply: can_inj (mulKr Ux). Qed.
Lemma mulIr : {in @unit R, left_injective *%R}.
Proof. by move=> x Ux; apply: can_inj (mulrK Ux). Qed.
(* Due to noncommutativity, fractions are inverted. *)
Lemma telescope_prodr n m (f : nat -> R) :
(forall k, n < k < m -> f k \is a unit) -> n < m ->
\prod_(n <= k < m) (f k / f k.+1) = f n / f m.
Proof.
move=> Uf ltnm; rewrite (telescope_big (fun i j => f i / f j)) ?ltnm//.
by move=> k ltnkm /=; rewrite mulrA divrK// Uf.
Qed.
Lemma telescope_prodr_eq n m (f u : nat -> R) : n < m ->
(forall k, n < k < m -> f k \is a unit) ->
(forall k, (n <= k < m)%N -> u k = f k / f k.+1) ->
\prod_(n <= k < m) u k = f n / f m.
Proof.
by move=> ? ? uE; under eq_big_nat do rewrite uE //=; exact: telescope_prodr.
Qed.
Lemma commrV x y : comm x y -> comm x y^-1.
Proof.
have [Uy cxy | /invr_out-> //] := boolP (y \in unit).
by apply: (canLR (mulrK Uy)); rewrite -mulrA cxy mulKr.
Qed.
Lemma unitrE x : (x \is a unit) = (x / x == 1).
Proof.
apply/idP/eqP=> [Ux | xx1]; first exact: divrr.
by apply/unitrP; exists x^-1; rewrite -commrV.
Qed.
Lemma invrK : involutive (@inv R).
Proof.
move=> x; case Ux: (x \in unit); last by rewrite !invr_out ?Ux.
rewrite -(mulrK Ux _^-1) -mulrA commrV ?mulKr //.
by apply/unitrP; exists x; rewrite divrr ?mulVr.
Qed.
Lemma invr_inj : injective (@inv R). Proof. exact: inv_inj invrK. Qed.
Lemma unitrV x : (x^-1 \in unit) = (x \in unit).
Proof. by rewrite !unitrE invrK commrV. Qed.
Lemma unitr1 : 1 \in @unit R.
Proof. by apply/unitrP; exists 1; rewrite mulr1. Qed.
Lemma invr1 : 1^-1 = 1 :> R.
Proof. by rewrite -{2}(mulVr unitr1) mulr1. Qed.
Lemma div1r x : 1 / x = x^-1. Proof. by rewrite mul1r. Qed.
Lemma divr1 x : x / 1 = x. Proof. by rewrite invr1 mulr1. Qed.
Lemma natr_div m d :
d %| m -> d%:R \is a @unit R -> (m %/ d)%:R = m%:R / d%:R :> R.
Proof.
by rewrite dvdn_eq => /eqP def_m unit_d; rewrite -{2}def_m natrM mulrK.
Qed.
Lemma divrI : {in unit, right_injective (fun x y => x / y)}.
Proof. by move=> x /mulrI/inj_comp; apply; apply: invr_inj. Qed.
Lemma divIr : {in unit, left_injective (fun x y => x / y)}.
Proof. by move=> x; rewrite -unitrV => /mulIr. Qed.
Lemma unitr0 : (0 \is a @unit R) = false.
Proof. by apply/unitrP=> [[x [_ /esym/eqP]]]; rewrite mul0r oner_eq0. Qed.
Lemma invr0 : 0^-1 = 0 :> R.
Proof. by rewrite invr_out ?unitr0. Qed.
Lemma unitrN1 : -1 \is a @unit R.
Proof. by apply/unitrP; exists (-1); rewrite mulrNN mulr1. Qed.
Lemma invrN1 : (-1)^-1 = -1 :> R.
Proof. by rewrite -{2}(divrr unitrN1) mulN1r opprK. Qed.
Lemma invr_sign n : ((-1) ^- n) = (-1) ^+ n :> R.
Proof. by rewrite -signr_odd; case: (odd n); rewrite (invr1, invrN1). Qed.
Lemma unitrMl x y : y \is a unit -> (x * y \is a unit) = (x \is a unit).
Proof.
move=> Uy; wlog Ux: x y Uy / x \is a unit => [WHxy|].
by apply/idP/idP=> Ux; first rewrite -(mulrK Uy x); rewrite WHxy ?unitrV.
rewrite Ux; apply/unitrP; exists (y^-1 * x^-1).
by rewrite -!mulrA mulKr ?mulrA ?mulrK ?divrr ?mulVr.
Qed.
Lemma unitrMr x y : x \is a unit -> (x * y \is a unit) = (y \is a unit).
Proof.
move=> Ux; apply/idP/idP=> [Uxy | Uy]; last by rewrite unitrMl.
by rewrite -(mulKr Ux y) unitrMl ?unitrV.
Qed.
Lemma unitr_prod {I : Type} (P : pred I) (E : I -> R) (r : seq I) :
(forall i, P i -> E i \is a GRing.unit) ->
(\prod_(i <- r | P i) E i \is a GRing.unit).
Proof.
by move=> Eunit; elim/big_rec: _ => [/[!unitr1] |i x /Eunit/unitrMr->].
Qed.
Lemma unitr_prod_in {I : eqType} (P : pred I) (E : I -> R) (r : seq I) :
{in r, forall i, P i -> E i \is a GRing.unit} ->
(\prod_(i <- r | P i) E i \is a GRing.unit).
Proof.
by rewrite big_seq_cond => H; apply: unitr_prod => i /andP[]; exact: H.
Qed.
Lemma invrM : {in unit &, forall x y, (x * y)^-1 = y^-1 * x^-1}.
Proof.
move=> x y Ux Uy; have Uxy: (x * y \in unit) by rewrite unitrMl.
by apply: (mulrI Uxy); rewrite divrr ?mulrA ?mulrK ?divrr.
Qed.
Lemma unitrM_comm x y :
comm x y -> (x * y \is a unit) = (x \is a unit) && (y \is a unit).
Proof.
move=> cxy; apply/idP/andP=> [Uxy | [Ux Uy]]; last by rewrite unitrMl.
suffices Ux: x \in unit by rewrite unitrMr in Uxy.
apply/unitrP; case/unitrP: Uxy => z [zxy xyz]; exists (y * z).
rewrite mulrA xyz -{1}[y]mul1r -{1}zxy cxy -!mulrA (mulrA x) (mulrA _ z) xyz.
by rewrite mul1r -cxy.
Qed.
Lemma unitrX x n : x \is a unit -> x ^+ n \is a unit.
Proof.
by move=> Ux; elim: n => [|n IHn]; rewrite ?unitr1 // exprS unitrMl.
Qed.
Lemma unitrX_pos x n : n > 0 -> (x ^+ n \in unit) = (x \in unit).
Proof.
case: n => // n _; rewrite exprS unitrM_comm; last exact: commrX.
by case Ux: (x \is a unit); rewrite // unitrX.
Qed.
Lemma exprVn x n : x^-1 ^+ n = x ^- n.
Proof.
elim: n => [|n IHn]; first by rewrite !expr0 ?invr1.
case Ux: (x \is a unit); first by rewrite exprSr exprS IHn -invrM // unitrX.
by rewrite !invr_out ?unitrX_pos ?Ux.
Qed.
Lemma exprB m n x : n <= m -> x \is a unit -> x ^+ (m - n) = x ^+ m / x ^+ n.
Proof. by move/subnK=> {2}<- Ux; rewrite exprD mulrK ?unitrX. Qed.
Lemma invr_neq0 x : x != 0 -> x^-1 != 0.
Proof.
move=> nx0; case Ux: (x \is a unit); last by rewrite invr_out ?Ux.
by apply/eqP=> x'0; rewrite -unitrV x'0 unitr0 in Ux.
Qed.
Lemma invr_eq0 x : (x^-1 == 0) = (x == 0).
Proof. by apply: negb_inj; apply/idP/idP; move/invr_neq0; rewrite ?invrK. Qed.
Lemma invr_eq1 x : (x^-1 == 1) = (x == 1).
Proof. by rewrite (inv_eq invrK) invr1. Qed.
Lemma rev_unitrP (x y : R^c) : y * x = 1 /\ x * y = 1 -> x \is a unit.
Proof. by case=> [yx1 xy1]; apply/unitrP; exists y. Qed.
#[export]
HB.instance Definition _ :=
NzRing_hasMulInverse.Build R^c mulrV mulVr rev_unitrP invr_out.
#[export]
HB.instance Definition _ := UnitRing.on R^o.
End UnitRingTheory.
Arguments invrK {R}.
Arguments invr_inj {R} [x1 x2].
Arguments telescope_prodr_eq {R n m} f u.
Lemma rev_prodrV (R : unitRingType)
(I : Type) (r : seq I) (P : pred I) (E : I -> R) :
(forall i, P i -> E i \is a GRing.unit) ->
\prod_(i <- r | P i) (E i)^-1 = ((\prod_(i <- r | P i) (E i : R^c))^-1).
Proof.
move=> Eunit; symmetry.
apply: (big_morph_in GRing.unit _ _ (unitr1 R^c) (@invrM _) (invr1 _)) Eunit.
by move=> x y xunit; rewrite unitrMr.
Qed.
Section UnitRingClosedPredicates.
Variables (R : unitRingType) (S : {pred R}).
Definition invr_closed := {in S, forall x, x^-1 \in S}.
Definition divr_2closed := {in S &, forall x y, x / y \in S}.
Definition divr_closed := 1 \in S /\ divr_2closed.
Definition sdivr_closed := -1 \in S /\ divr_2closed.
Definition divring_closed := [/\ 1 \in S, subr_2closed S & divr_2closed].
Lemma divr_closedV : divr_closed -> invr_closed.
Proof. by case=> S1 Sdiv x Sx; rewrite -[x^-1]mul1r Sdiv. Qed.
Lemma divr_closedM : divr_closed -> mulr_closed S.
Proof.
by case=> S1 Sdiv; split=> // x y Sx Sy; rewrite -[y]invrK -[y^-1]mul1r !Sdiv.
Qed.
Lemma sdivr_closed_div : sdivr_closed -> divr_closed.
Proof. by case=> SN1 Sdiv; split; rewrite // -(divrr (@unitrN1 _)) Sdiv. Qed.
Lemma sdivr_closedM : sdivr_closed -> smulr_closed S.
Proof.
by move=> Sdiv; have [_ SM] := divr_closedM (sdivr_closed_div Sdiv); case: Sdiv.
Qed.
Lemma divring_closedBM : divring_closed -> subring_closed S.
Proof. by case=> S1 SB Sdiv; split=> //; case: divr_closedM. Qed.
Lemma divring_closed_div : divring_closed -> sdivr_closed.
Proof.
case=> S1 SB Sdiv; split; rewrite ?zmod_closedN //.
exact/subring_closedB/divring_closedBM.
Qed.
End UnitRingClosedPredicates.
Section UnitRingMorphism.
Variables (R S : unitRingType) (f : {rmorphism R -> S}).
Lemma rmorph_unit x : x \in unit -> f x \in unit.
Proof.
case/unitrP=> y [yx1 xy1]; apply/unitrP.
by exists (f y); rewrite -!rmorphM // yx1 xy1 rmorph1.
Qed.
Lemma rmorphV : {in unit, {morph f: x / x^-1}}.
Proof.
move=> x Ux; rewrite /= -[(f x)^-1]mul1r.
by apply: (canRL (mulrK (rmorph_unit Ux))); rewrite -rmorphM mulVr ?rmorph1.
Qed.
Lemma rmorph_div x y : y \in unit -> f (x / y) = f x / f y.
Proof. by move=> Uy; rewrite rmorphM /= rmorphV. Qed.
End UnitRingMorphism.
#[short(type="comUnitRingType")]
HB.structure Definition ComUnitRing := {R of ComNzRing R & UnitRing R}.
Module ComUnitRingExports.
Bind Scope ring_scope with ComUnitRing.sort.
End ComUnitRingExports.
HB.export ComUnitRingExports.
(* TODO_HB: fix the name (was ComUnitRingMixin) *)
HB.factory Record ComNzRing_hasMulInverse R of ComNzRing R := {
unit : {pred R};
inv : R -> R;
mulVx : {in unit, left_inverse 1 inv *%R};
unitPl : forall x y, y * x = 1 -> unit x;
invr_out : {in [predC unit], inv =1 id}
}.
Module ComRing_hasMulInverse.
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzRing_hasMulInverse.Build instead.")]
Notation Build R := (ComNzRing_hasMulInverse.Build R) (only parsing).
End ComRing_hasMulInverse.
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzRing_hasMulInverse instead.")]
Notation ComRing_hasMulInverse R := (ComNzRing_hasMulInverse R) (only parsing).
HB.builders Context R of ComNzRing_hasMulInverse R.
Fact mulC_mulrV : {in unit, right_inverse 1 inv *%R}.
Proof. by move=> x Ux /=; rewrite mulrC mulVx. Qed.
Fact mulC_unitP x y : y * x = 1 /\ x * y = 1 -> unit x.
Proof. by case=> yx _; apply: unitPl yx. Qed.
HB.instance Definition _ :=
NzRing_hasMulInverse.Build R mulVx mulC_mulrV mulC_unitP invr_out.
HB.end.
#[short(type="unitAlgType")]
HB.structure Definition UnitAlgebra R := {V of Algebra R V & UnitRing V}.
Module UnitAlgebraExports.
Bind Scope ring_scope with UnitAlgebra.sort.
End UnitAlgebraExports.
HB.export UnitAlgebraExports.
#[short(type="comUnitAlgType")]
HB.structure Definition ComUnitAlgebra R := {V of ComAlgebra R V & UnitRing V}.
Module ComUnitAlgebraExports.
Bind Scope ring_scope with UnitAlgebra.sort.
End ComUnitAlgebraExports.
HB.export ComUnitAlgebraExports.
Section ComUnitRingTheory.
Variable R : comUnitRingType.
Implicit Types x y : R.
Lemma unitrM x y : (x * y \in unit) = (x \in unit) && (y \in unit).
Proof. exact/unitrM_comm/mulrC. Qed.
Lemma unitrPr x : reflect (exists y, x * y = 1) (x \in unit).
Proof.
by apply: (iffP (unitrP x)) => [[y []] | [y]]; exists y; rewrite // mulrC.
Qed.
Lemma mulr1_eq x y : x * y = 1 -> x^-1 = y.
Proof.
by move=> xy_eq1; rewrite -[LHS]mulr1 -xy_eq1; apply/mulKr/unitrPr; exists y.
Qed.
Lemma divr1_eq x y : x / y = 1 -> x = y. Proof. by move/mulr1_eq/invr_inj. Qed.
Lemma divKr x : x \is a unit -> {in unit, involutive (fun y => x / y)}.
Proof. by move=> Ux y Uy; rewrite /= invrM ?unitrV // invrK mulrC divrK. Qed.
Lemma expr_div_n x y n : (x / y) ^+ n = x ^+ n / y ^+ n.
Proof. by rewrite exprMn exprVn. Qed.
Lemma unitr_prodP (I : eqType) (r : seq I) (P : pred I) (E : I -> R) :
reflect {in r, forall i, P i -> E i \is a GRing.unit}
(\prod_(i <- r | P i) E i \is a GRing.unit).
Proof.
rewrite (big_morph [in unit] unitrM (@unitr1 _) ) big_all_cond.
exact: 'all_implyP.
Qed.
Lemma prodrV (I : eqType) (r : seq I) (P : pred I) (E : I -> R) :
(forall i, P i -> E i \is a GRing.unit) ->
\prod_(i <- r | P i) (E i)^-1 = (\prod_(i <- r | P i) E i)^-1.
Proof.
by move=> /rev_prodrV->; rewrite rev_prodr (perm_big r)// perm_rev.
Qed.
(* TODO: HB.saturate *)
#[export] HB.instance Definition _ := ComUnitRing.on R^c.
#[export] HB.instance Definition _ := ComUnitRing.on R^o.
(* /TODO *)
End ComUnitRingTheory.
Section UnitAlgebraTheory.
Variable (R : comUnitRingType) (A : unitAlgType R).
Implicit Types (k : R) (x y : A).
Lemma scaler_injl : {in unit, @right_injective R A A *:%R}.
Proof.
move=> k Uk x1 x2 Hx1x2.
by rewrite -[x1]scale1r -(mulVr Uk) -scalerA Hx1x2 scalerA mulVr // scale1r.
Qed.
Lemma scaler_unit k x : k \in unit -> (k *: x \in unit) = (x \in unit).
Proof.
move=> Uk; apply/idP/idP=> [Ukx | Ux]; apply/unitrP; last first.
exists (k^-1 *: x^-1).
by rewrite -!scalerAl -!scalerAr !scalerA !mulVr // !mulrV // scale1r.
exists (k *: (k *: x)^-1); split.
apply: (mulrI Ukx).
by rewrite mulr1 mulrA -scalerAr mulrV // -scalerAl mul1r.
apply: (mulIr Ukx).
by rewrite mul1r -mulrA -scalerAl mulVr // -scalerAr mulr1.
Qed.
Lemma invrZ k x : k \in unit -> x \in unit -> (k *: x)^-1 = k^-1 *: x^-1.
Proof.
move=> Uk Ux; have Ukx: (k *: x \in unit) by rewrite scaler_unit.
apply: (mulIr Ukx).
by rewrite mulVr // -scalerAl -scalerAr scalerA !mulVr // scale1r.
Qed.
Section ClosedPredicates.
Variables S : {pred A}.
Definition divalg_closed := [/\ 1 \in S, linear_closed S & divr_2closed S].
Lemma divalg_closedBdiv : divalg_closed -> divring_closed S.
Proof. by case=> S1 /linear_closedB. Qed.
Lemma divalg_closedZ : divalg_closed -> subalg_closed S.
Proof. by case=> S1 Slin Sdiv; split=> //; have [] := @divr_closedM A S. Qed.
End ClosedPredicates.
End UnitAlgebraTheory.
Module ClosedExports.
Notation addr_closed := nmod_closed.
Notation oppr_closed := oppr_closed.
Notation zmod_closed := zmod_closed.
Notation mulr_closed := mulr_closed.
Notation semiring_closed := semiring_closed.
Notation smulr_closed := smulr_closed.
Notation subring_closed := subring_closed.
Notation scaler_closed := scaler_closed.
Notation subsemimod_closed := subsemimod_closed.
Notation linear_closed := linear_closed.
Notation submod_closed := submod_closed.
Notation subalg_closed := subalg_closed.
Notation invr_closed := invr_closed.
Notation divr_2closed := divr_2closed.
Notation divr_closed := divr_closed.
Notation sdivr_closed := sdivr_closed.
Notation divring_closed := divring_closed.
Notation divalg_closed := divalg_closed.
Coercion zmod_closedD : zmod_closed >-> nmod_closed.
Coercion zmod_closedN : zmod_closed >-> oppr_closed.
Coercion semiring_closedD : semiring_closed >-> addr_closed.
Coercion semiring_closedM : semiring_closed >-> mulr_closed.
Coercion smulr_closedM : smulr_closed >-> mulr_closed.
Coercion smulr_closedN : smulr_closed >-> oppr_closed.
Coercion subring_closedB : subring_closed >-> zmod_closed.
Coercion subring_closedM : subring_closed >-> smulr_closed.
Coercion subring_closed_semi : subring_closed >-> semiring_closed.
Coercion subsemimod_closedD : subsemimod_closed >-> addr_closed.
Coercion subsemimod_closedZ : subsemimod_closed >-> scaler_closed.
Coercion linear_closedB : linear_closed >-> subr_2closed.
Coercion submod_closedB : submod_closed >-> zmod_closed.
Coercion submod_closed_semi : submod_closed >-> subsemimod_closed.
Coercion subalg_closedZ : subalg_closed >-> submod_closed.
Coercion subalg_closedBM : subalg_closed >-> subring_closed.
Coercion divr_closedV : divr_closed >-> invr_closed.
Coercion divr_closedM : divr_closed >-> mulr_closed.
Coercion sdivr_closed_div : sdivr_closed >-> divr_closed.
Coercion sdivr_closedM : sdivr_closed >-> smulr_closed.
Coercion divring_closedBM : divring_closed >-> subring_closed.
Coercion divring_closed_div : divring_closed >-> sdivr_closed.
Coercion divalg_closedBdiv : divalg_closed >-> divring_closed.
Coercion divalg_closedZ : divalg_closed >-> subalg_closed.
End ClosedExports.
(* Reification of the theory of rings with units, in named style *)
Section TermDef.
Variable R : Type.
Inductive term : Type :=
| Var of nat
| Const of R
| NatConst of nat
| Add of term & term
| Opp of term
| NatMul of term & nat
| Mul of term & term
| Inv of term
| Exp of term & nat.
Inductive formula : Type :=
| Bool of bool
| Equal of term & term
| Unit of term
| And of formula & formula
| Or of formula & formula
| Implies of formula & formula
| Not of formula
| Exists of nat & formula
| Forall of nat & formula.
End TermDef.
Bind Scope term_scope with term.
Bind Scope term_scope with formula.
Arguments Add {R} t1%_T t2%_T.
Arguments Opp {R} t1%_T.
Arguments NatMul {R} t1%_T n%_N.
Arguments Mul {R} t1%_T t2%_T.
Arguments Inv {R} t1%_T.
Arguments Exp {R} t1%_T n%_N.
Arguments Equal {R} t1%_T t2%_T.
Arguments Unit {R} t1%_T.
Arguments And {R} f1%_T f2%_T.
Arguments Or {R} f1%_T f2%_T.
Arguments Implies {R} f1%_T f2%_T.
Arguments Not {R} f1%_T.
Arguments Exists {R} i%_N f1%_T.
Arguments Forall {R} i%_N f1%_T.
Arguments Bool {R} b.
Arguments Const {R} x.
Notation True := (Bool true).
Notation False := (Bool false).
Local Notation "''X_' i" := (Var _ i) : term_scope.
Local Notation "n %:R" := (NatConst _ n) : term_scope.
Local Notation "x %:T" := (Const x) : term_scope.
Local Notation "0" := 0%:R%T : term_scope.
Local Notation "1" := 1%:R%T : term_scope.
Local Infix "+" := Add : term_scope.
Local Notation "- t" := (Opp t) : term_scope.
Local Notation "t - u" := (Add t (- u)) : term_scope.
Local Infix "*" := Mul : term_scope.
Local Infix "*+" := NatMul : term_scope.
Local Notation "t ^-1" := (Inv t) : term_scope.
Local Notation "t / u" := (Mul t u^-1) : term_scope.
Local Infix "^+" := Exp : term_scope.
Local Infix "==" := Equal : term_scope.
Local Infix "/\" := And : term_scope.
Local Infix "\/" := Or : term_scope.
Local Infix "==>" := Implies : term_scope.
Local Notation "~ f" := (Not f) : term_scope.
Local Notation "x != y" := (Not (x == y)) : term_scope.
Local Notation "''exists' ''X_' i , f" := (Exists i f) : term_scope.
Local Notation "''forall' ''X_' i , f" := (Forall i f) : term_scope.
Section Substitution.
Variable R : Type.
Fixpoint tsubst (t : term R) (s : nat * term R) :=
match t with
| 'X_i => if i == s.1 then s.2 else t
| _%:T | _%:R => t
| t1 + t2 => tsubst t1 s + tsubst t2 s
| - t1 => - tsubst t1 s
| t1 *+ n => tsubst t1 s *+ n
| t1 * t2 => tsubst t1 s * tsubst t2 s
| t1^-1 => (tsubst t1 s)^-1
| t1 ^+ n => tsubst t1 s ^+ n
end%T.
Fixpoint fsubst (f : formula R) (s : nat * term R) :=
match f with
| Bool _ => f
| t1 == t2 => tsubst t1 s == tsubst t2 s
| Unit t1 => Unit (tsubst t1 s)
| f1 /\ f2 => fsubst f1 s /\ fsubst f2 s
| f1 \/ f2 => fsubst f1 s \/ fsubst f2 s
| f1 ==> f2 => fsubst f1 s ==> fsubst f2 s
| ~ f1 => ~ fsubst f1 s
| ('exists 'X_i, f1) => 'exists 'X_i, if i == s.1 then f1 else fsubst f1 s
| ('forall 'X_i, f1) => 'forall 'X_i, if i == s.1 then f1 else fsubst f1 s
end%T.
End Substitution.
Section EvalTerm.
Variable R : unitRingType.
(* Evaluation of a reified term into R a ring with units *)
Fixpoint eval (e : seq R) (t : term R) {struct t} : R :=
match t with
| ('X_i)%T => e`_i
| (x%:T)%T => x
| (n%:R)%T => n%:R
| (t1 + t2)%T => eval e t1 + eval e t2
| (- t1)%T => - eval e t1
| (t1 *+ n)%T => eval e t1 *+ n
| (t1 * t2)%T => eval e t1 * eval e t2
| t1^-1%T => (eval e t1)^-1
| (t1 ^+ n)%T => eval e t1 ^+ n
end.
Definition same_env (e e' : seq R) := nth 0 e =1 nth 0 e'.
Lemma eq_eval e e' t : same_env e e' -> eval e t = eval e' t.
Proof. by move=> eq_e; elim: t => //= t1 -> // t2 ->. Qed.
Lemma eval_tsubst e t s :
eval e (tsubst t s) = eval (set_nth 0 e s.1 (eval e s.2)) t.
Proof.
case: s => i u; elim: t => //=; do 2?[move=> ? -> //] => j.
by rewrite nth_set_nth /=; case: (_ == _).
Qed.
(* Evaluation of a reified formula *)
Fixpoint holds (e : seq R) (f : formula R) {struct f} : Prop :=
match f with
| Bool b => b
| (t1 == t2)%T => eval e t1 = eval e t2
| Unit t1 => eval e t1 \in unit
| (f1 /\ f2)%T => holds e f1 /\ holds e f2
| (f1 \/ f2)%T => holds e f1 \/ holds e f2
| (f1 ==> f2)%T => holds e f1 -> holds e f2
| (~ f1)%T => ~ holds e f1
| ('exists 'X_i, f1)%T => exists x, holds (set_nth 0 e i x) f1
| ('forall 'X_i, f1)%T => forall x, holds (set_nth 0 e i x) f1
end.
Lemma same_env_sym e e' : same_env e e' -> same_env e' e.
Proof. exact: fsym. Qed.
(* Extensionality of formula evaluation *)
Lemma eq_holds e e' f : same_env e e' -> holds e f -> holds e' f.
Proof.
pose sv := set_nth (0 : R).
have eq_i i v e1 e2: same_env e1 e2 -> same_env (sv e1 i v) (sv e2 i v).
by move=> eq_e j; rewrite !nth_set_nth /= eq_e.
elim: f e e' => //=.
- by move=> t1 t2 e e' eq_e; rewrite !(eq_eval _ eq_e).
- by move=> t e e' eq_e; rewrite (eq_eval _ eq_e).
- by move=> f1 IH1 f2 IH2 e e' eq_e; move/IH2: (eq_e); move/IH1: eq_e; tauto.
- by move=> f1 IH1 f2 IH2 e e' eq_e; move/IH2: (eq_e); move/IH1: eq_e; tauto.
- by move=> f1 IH1 f2 IH2 e e' eq_e f12; move/IH1: (same_env_sym eq_e); eauto.
- by move=> f1 IH1 e e'; move/same_env_sym; move/IH1; tauto.
- by move=> i f1 IH1 e e'; move/(eq_i i)=> eq_e [x f_ex]; exists x; eauto.
by move=> i f1 IH1 e e'; move/(eq_i i); eauto.
Qed.
(* Evaluation and substitution by a constant *)
Lemma holds_fsubst e f i v :
holds e (fsubst f (i, v%:T)%T) <-> holds (set_nth 0 e i v) f.
Proof.
elim: f e => //=; do [
by move=> *; rewrite !eval_tsubst
| move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto
| move=> f IHf e; move: (IHf e); tauto
| move=> j f IHf e].
- case eq_ji: (j == i); first rewrite (eqP eq_ji).
by split=> [] [x f_x]; exists x; rewrite set_set_nth eqxx in f_x *.
split=> [] [x f_x]; exists x; move: f_x; rewrite set_set_nth eq_sym eq_ji;
have:= IHf (set_nth 0 e j x); tauto.
case eq_ji: (j == i); first rewrite (eqP eq_ji).
by split=> [] f_ x; move: (f_ x); rewrite set_set_nth eqxx.
split=> [] f_ x; move: (IHf (set_nth 0 e j x)) (f_ x);
by rewrite set_set_nth 1?[i == j]eq_sym eq_ji; tauto.
Qed.
(* Boolean test selecting terms in the language of rings *)
Fixpoint rterm (t : term R) :=
match t with
| _^-1 => false
| t1 + t2 | t1 * t2 => rterm t1 && rterm t2
| - t1 | t1 *+ _ | t1 ^+ _ => rterm t1
| _ => true
end%T.
(* Boolean test selecting formulas in the theory of rings *)
Fixpoint rformula (f : formula R) :=
match f with
| Bool _ => true
| t1 == t2 => rterm t1 && rterm t2
| Unit t1 => false
| f1 /\ f2 | f1 \/ f2 | f1 ==> f2 => rformula f1 && rformula f2
| ~ f1 | ('exists 'X__, f1) | ('forall 'X__, f1) => rformula f1
end%T.
(* Upper bound of the names used in a term *)
Fixpoint ub_var (t : term R) :=
match t with
| 'X_i => i.+1
| t1 + t2 | t1 * t2 => maxn (ub_var t1) (ub_var t2)
| - t1 | t1 *+ _ | t1 ^+ _ | t1^-1 => ub_var t1
| _ => 0%N
end%T.
(* Replaces inverses in the term t by fresh variables, accumulating the *)
(* substitution. *)
Fixpoint to_rterm (t : term R) (r : seq (term R)) (n : nat) {struct t} :=
match t with
| t1^-1 =>
let: (t1', r1) := to_rterm t1 r n in
('X_(n + size r1), rcons r1 t1')
| t1 + t2 =>
let: (t1', r1) := to_rterm t1 r n in
let: (t2', r2) := to_rterm t2 r1 n in
(t1' + t2', r2)
| - t1 =>
let: (t1', r1) := to_rterm t1 r n in
(- t1', r1)
| t1 *+ m =>
let: (t1', r1) := to_rterm t1 r n in
(t1' *+ m, r1)
| t1 * t2 =>
let: (t1', r1) := to_rterm t1 r n in
let: (t2', r2) := to_rterm t2 r1 n in
(Mul t1' t2', r2)
| t1 ^+ m =>
let: (t1', r1) := to_rterm t1 r n in
(t1' ^+ m, r1)
| _ => (t, r)
end%T.
Lemma to_rterm_id t r n : rterm t -> to_rterm t r n = (t, r).
Proof.
elim: t r n => //.
- by move=> t1 IHt1 t2 IHt2 r n /= /andP[rt1 rt2]; rewrite {}IHt1 // IHt2.
- by move=> t IHt r n /= rt; rewrite {}IHt.
- by move=> t IHt r n m /= rt; rewrite {}IHt.
- by move=> t1 IHt1 t2 IHt2 r n /= /andP[rt1 rt2]; rewrite {}IHt1 // IHt2.
- by move=> t IHt r n m /= rt; rewrite {}IHt.
Qed.
(* A ring formula stating that t1 is equal to 0 in the ring theory. *)
(* Also applies to non commutative rings. *)
Definition eq0_rform t1 :=
let m := ub_var t1 in
let: (t1', r1) := to_rterm t1 [::] m in
let fix loop r i := match r with
| [::] => t1' == 0
| t :: r' =>
let f := 'X_i * t == 1 /\ t * 'X_i == 1 in
'forall 'X_i, (f \/ 'X_i == t /\ ~ ('exists 'X_i, f)) ==> loop r' i.+1
end%T
in loop r1 m.
(* Transformation of a formula in the theory of rings with units into an *)
(* equivalent formula in the sub-theory of rings. *)
Fixpoint to_rform f :=
match f with
| Bool b => f
| t1 == t2 => eq0_rform (t1 - t2)
| Unit t1 => eq0_rform (t1 * t1^-1 - 1)
| f1 /\ f2 => to_rform f1 /\ to_rform f2
| f1 \/ f2 => to_rform f1 \/ to_rform f2
| f1 ==> f2 => to_rform f1 ==> to_rform f2
| ~ f1 => ~ to_rform f1
| ('exists 'X_i, f1) => 'exists 'X_i, to_rform f1
| ('forall 'X_i, f1) => 'forall 'X_i, to_rform f1
end%T.
(* The transformation gives a ring formula. *)
Lemma to_rform_rformula f : rformula (to_rform f).
Proof.
suffices eq0_ring t1: rformula (eq0_rform t1) by elim: f => //= => f1 ->.
rewrite /eq0_rform; move: (ub_var t1) => m; set tr := _ m.
suffices: all rterm (tr.1 :: tr.2).
case: tr => {}t1 r /= /andP[t1_r].
by elim: r m => [|t r IHr] m; rewrite /= ?andbT // => /andP[->]; apply: IHr.
have: all rterm [::] by [].
rewrite {}/tr; elim: t1 [::] => //=.
- move=> t1 IHt1 t2 IHt2 r.
move/IHt1; case: to_rterm => {r IHt1}t1 r /= /andP[t1_r].
move/IHt2; case: to_rterm => {r IHt2}t2 r /= /andP[t2_r].
by rewrite t1_r t2_r.
- by move=> t1 IHt1 r /IHt1; case: to_rterm.
- by move=> t1 IHt1 n r /IHt1; case: to_rterm.
- move=> t1 IHt1 t2 IHt2 r.
move/IHt1; case: to_rterm => {r IHt1}t1 r /= /andP[t1_r].
move/IHt2; case: to_rterm => {r IHt2}t2 r /= /andP[t2_r].
by rewrite t1_r t2_r.
- move=> t1 IHt1 r.
by move/IHt1; case: to_rterm => {r IHt1}t1 r /=; rewrite all_rcons.
- by move=> t1 IHt1 n r /IHt1; case: to_rterm.
Qed.
(* Correctness of the transformation. *)
Lemma to_rformP e f : holds e (to_rform f) <-> holds e f.
Proof.
suffices{e f} equal0_equiv e t1 t2:
holds e (eq0_rform (t1 - t2)) <-> (eval e t1 == eval e t2).
- elim: f e => /=; try tauto.
+ move=> t1 t2 e.
by split; [move/equal0_equiv/eqP | move/eqP/equal0_equiv].
+ by move=> t1 e; rewrite unitrE; apply: equal0_equiv.
+ by move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.
+ by move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.
+ by move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.
+ by move=> f1 IHf1 e; move: (IHf1 e); tauto.
+ by move=> n f1 IHf1 e; split=> [] [x] /IHf1; exists x.
+ by move=> n f1 IHf1 e; split=> Hx x; apply/IHf1.
rewrite -(add0r (eval e t2)) -(can2_eq (subrK _) (addrK _)).
rewrite -/(eval e (t1 - t2)); move: (t1 - t2)%T => {t1 t2} t.
have sub_var_tsubst s t0: s.1 >= ub_var t0 -> tsubst t0 s = t0.
elim: t0 {t} => //=.
- by move=> n; case: ltngtP.
- by move=> t1 IHt1 t2 IHt2; rewrite geq_max => /andP[/IHt1-> /IHt2->].
- by move=> t1 IHt1 /IHt1->.
- by move=> t1 IHt1 n /IHt1->.
- by move=> t1 IHt1 t2 IHt2; rewrite geq_max => /andP[/IHt1-> /IHt2->].
- by move=> t1 IHt1 /IHt1->.
- by move=> t1 IHt1 n /IHt1->.
pose fix rsub t' m r : term R :=
if r is u :: r' then tsubst (rsub t' m.+1 r') (m, u^-1)%T else t'.
pose fix ub_sub m r : Prop :=
if r is u :: r' then ub_var u <= m /\ ub_sub m.+1 r' else true.
suffices{t} rsub_to_r t r0 m: m >= ub_var t -> ub_sub m r0 ->
let: (t', r) := to_rterm t r0 m in
[/\ take (size r0) r = r0,
ub_var t' <= m + size r, ub_sub m r & rsub t' m r = t].
- have:= rsub_to_r t [::] _ (leqnn _); rewrite /eq0_rform.
case: (to_rterm _ _ _) => [t1' r1] [//|_ _ ub_r1 def_t].
rewrite -{2}def_t {def_t}.
elim: r1 (ub_var t) e ub_r1 => [|u r1 IHr1] m e /= => [_|[ub_u ub_r1]].
by split=> /eqP.
rewrite eval_tsubst /=; set y := eval e u; split=> t_eq0.
apply/IHr1=> //; apply: t_eq0.
rewrite nth_set_nth /= eqxx -(eval_tsubst e u (m, Const _)).
rewrite sub_var_tsubst //= -/y.
case Uy: (y \in unit); [left | right]; first by rewrite mulVr ?divrr.
split=> [|[z]]; first by rewrite invr_out ?Uy.
rewrite nth_set_nth /= eqxx.
rewrite -!(eval_tsubst _ _ (m, Const _)) !sub_var_tsubst // -/y => yz1.
by case/unitrP: Uy; exists z.
move=> x def_x; apply/IHr1=> //; suff ->: x = y^-1 by []; move: def_x.
rewrite nth_set_nth /= eqxx -(eval_tsubst e u (m, Const _)).
rewrite sub_var_tsubst //= -/y; case=> [[xy1 yx1] | [xy nUy]].
by rewrite -[y^-1]mul1r -[1]xy1 mulrK //; apply/unitrP; exists x.
rewrite invr_out //; apply/unitrP=> [[z yz1]]; case: nUy; exists z.
rewrite nth_set_nth /= eqxx -!(eval_tsubst _ _ (m, _%:T)%T).
by rewrite !sub_var_tsubst.
have rsub_id r t0 n: ub_var t0 <= n -> rsub t0 n r = t0.
by elim: r n => //= t1 r IHr n let0n; rewrite IHr ?sub_var_tsubst ?leqW.
have rsub_acc r s t1 m1:
ub_var t1 <= m1 + size r -> rsub t1 m1 (r ++ s) = rsub t1 m1 r.
elim: r t1 m1 => [|t1 r IHr] t2 m1 /=; first by rewrite addn0; apply: rsub_id.
by move=> letmr; rewrite IHr ?addSnnS.
elim: t r0 m => /=; try do [
by move=> n r m hlt hub; rewrite take_size (ltn_addr _ hlt) rsub_id
| by move=> n r m hlt hub; rewrite leq0n take_size rsub_id
| move=> t1 IHt1 t2 IHt2 r m; rewrite geq_max; case/andP=> hub1 hub2 hmr;
case: to_rterm {hub1 hmr}(IHt1 r m hub1 hmr) => t1' r1;
case=> htake1 hub1' hsub1 <-;
case: to_rterm {IHt2 hub2 hsub1}(IHt2 r1 m hub2 hsub1) => t2' r2 /=;
rewrite geq_max; case=> htake2 -> hsub2 /= <-;
rewrite -{1 2}(cat_take_drop (size r1) r2) htake2; set r3 := drop _ _;
rewrite size_cat addnA (leq_trans _ (leq_addr _ _)) //;
split=> {hsub2}//;
first by [rewrite takel_cat // -htake1 size_take geq_min leqnn orbT];
rewrite -(rsub_acc r1 r3 t1') {hub1'}// -{htake1}htake2 {r3}cat_take_drop;
by elim: r2 m => //= u r2 IHr2 m; rewrite IHr2
| do [ move=> t1 IHt1 r m; do 2!move=> /IHt1{}IHt1
| move=> t1 IHt1 n r m; do 2!move=> /IHt1{}IHt1];
case: to_rterm IHt1 => t1' r1 [-> -> hsub1 <-]; split=> {hsub1}//;
by elim: r1 m => //= u r1 IHr1 m; rewrite IHr1].
move=> t1 IH r m letm /IH {IH} /(_ letm) {letm}.
case: to_rterm => t1' r1 /= [def_r ub_t1' ub_r1 <-].
rewrite size_rcons addnS leqnn -{1}cats1 takel_cat ?def_r; last first.
by rewrite -def_r size_take geq_min leqnn orbT.
elim: r1 m ub_r1 ub_t1' {def_r} => /= [|u r1 IHr1] m => [_|[->]].
by rewrite addn0 eqxx.
by rewrite -addSnnS => /IHr1 IH /IH[_ _ ub_r1 ->].
Qed.
(* Boolean test selecting formulas which describe a constructible set, *)
(* i.e. formulas without quantifiers. *)
(* The quantifier elimination check. *)
Fixpoint qf_form (f : formula R) :=
match f with
| Bool _ | _ == _ | Unit _ => true
| f1 /\ f2 | f1 \/ f2 | f1 ==> f2 => qf_form f1 && qf_form f2
| ~ f1 => qf_form f1
| _ => false
end%T.
(* Boolean holds predicate for quantifier free formulas *)
Definition qf_eval e := fix loop (f : formula R) : bool :=
match f with
| Bool b => b
| t1 == t2 => (eval e t1 == eval e t2)%bool
| Unit t1 => eval e t1 \in unit
| f1 /\ f2 => loop f1 && loop f2
| f1 \/ f2 => loop f1 || loop f2
| f1 ==> f2 => (loop f1 ==> loop f2)%bool
| ~ f1 => ~~ loop f1
|_ => false
end%T.
(* qf_eval is equivalent to holds *)
Lemma qf_evalP e f : qf_form f -> reflect (holds e f) (qf_eval e f).
Proof.
elim: f => //=; try by move=> *; apply: idP.
- by move=> t1 t2 _; apply: eqP.
- move=> f1 IHf1 f2 IHf2 /= /andP[/IHf1[] f1T]; last by right; case.
by case/IHf2; [left | right; case].
- move=> f1 IHf1 f2 IHf2 /= /andP[/IHf1[] f1F]; first by do 2 left.
by case/IHf2; [left; right | right; case].
- move=> f1 IHf1 f2 IHf2 /= /andP[/IHf1[] f1T]; last by left.
by case/IHf2; [left | right; move/(_ f1T)].
by move=> f1 IHf1 /IHf1[]; [right | left].
Qed.
Implicit Type bc : seq (term R) * seq (term R).
(* Quantifier-free formula are normalized into DNF. A DNF is *)
(* represented by the type seq (seq (term R) * seq (term R)), where we *)
(* separate positive and negative literals *)
(* DNF preserving conjunction *)
Definition and_dnf bcs1 bcs2 :=
\big[cat/nil]_(bc1 <- bcs1)
map (fun bc2 => (bc1.1 ++ bc2.1, bc1.2 ++ bc2.2)) bcs2.
(* Computes a DNF from a qf ring formula *)
Fixpoint qf_to_dnf (f : formula R) (neg : bool) {struct f} :=
match f with
| Bool b => if b (+) neg then [:: ([::], [::])] else [::]
| t1 == t2 => [:: if neg then ([::], [:: t1 - t2]) else ([:: t1 - t2], [::])]
| f1 /\ f2 => (if neg then cat else and_dnf) [rec f1, neg] [rec f2, neg]
| f1 \/ f2 => (if neg then and_dnf else cat) [rec f1, neg] [rec f2, neg]
| f1 ==> f2 => (if neg then and_dnf else cat) [rec f1, ~~ neg] [rec f2, neg]
| ~ f1 => [rec f1, ~~ neg]
| _ => if neg then [:: ([::], [::])] else [::]
end%T where "[ 'rec' f , neg ]" := (qf_to_dnf f neg).
(* Conversely, transforms a DNF into a formula *)
Definition dnf_to_form :=
let pos_lit t := And (t == 0) in let neg_lit t := And (t != 0) in
let cls bc := Or (foldr pos_lit True bc.1 /\ foldr neg_lit True bc.2) in
foldr cls False.
(* Catenation of dnf is the Or of formulas *)
Lemma cat_dnfP e bcs1 bcs2 :
qf_eval e (dnf_to_form (bcs1 ++ bcs2))
= qf_eval e (dnf_to_form bcs1 \/ dnf_to_form bcs2).
Proof.
by elim: bcs1 => //= bc1 bcs1 IH1; rewrite -orbA; congr orb; rewrite IH1.
Qed.
(* and_dnf is the And of formulas *)
Lemma and_dnfP e bcs1 bcs2 :
qf_eval e (dnf_to_form (and_dnf bcs1 bcs2))
= qf_eval e (dnf_to_form bcs1 /\ dnf_to_form bcs2).
Proof.
elim: bcs1 => [|bc1 bcs1 IH1] /=; first by rewrite /and_dnf big_nil.
rewrite /and_dnf big_cons -/(and_dnf bcs1 bcs2) cat_dnfP /=.
rewrite {}IH1 /= andb_orl; congr orb.
elim: bcs2 bc1 {bcs1} => [|bc2 bcs2 IH] bc1 /=; first by rewrite andbF.
rewrite {}IH /= andb_orr; congr orb => {bcs2}.
suffices aux (l1 l2 : seq (term R)) g : let redg := foldr (And \o g) True in
qf_eval e (redg (l1 ++ l2)) = qf_eval e (redg l1 /\ redg l2)%T.
+ by rewrite 2!aux /= 2!andbA -andbA -andbCA andbA andbCA andbA.
by elim: l1 => [| t1 l1 IHl1] //=; rewrite -andbA IHl1.
Qed.
Lemma qf_to_dnfP e :
let qev f b := qf_eval e (dnf_to_form (qf_to_dnf f b)) in
forall f, qf_form f && rformula f -> qev f false = qf_eval e f.
Proof.
move=> qev; have qevT f: qev f true = ~~ qev f false.
rewrite {}/qev; elim: f => //=; do [by case | move=> f1 IH1 f2 IH2 | ].
- by move=> t1 t2; rewrite !andbT !orbF.
- by rewrite and_dnfP cat_dnfP negb_and -IH1 -IH2.
- by rewrite and_dnfP cat_dnfP negb_or -IH1 -IH2.
- by rewrite and_dnfP cat_dnfP /= negb_or IH1 -IH2 negbK.
by move=> t1 ->; rewrite negbK.
rewrite /qev; elim=> //=; first by case.
- by move=> t1 t2 _; rewrite subr_eq0 !andbT orbF.
- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.
by rewrite and_dnfP /= => /IH1-> /IH2->.
- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.
by rewrite cat_dnfP /= => /IH1-> => /IH2->.
- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.
by rewrite cat_dnfP /= [qf_eval _ _]qevT -implybE => /IH1 <- /IH2->.
by move=> f1 IH1 /IH1 <-; rewrite -qevT.
Qed.
Lemma dnf_to_form_qf bcs : qf_form (dnf_to_form bcs).
Proof.
by elim: bcs => //= [[clT clF] _ ->] /=; elim: clT => //=; elim: clF.
Qed.
Definition dnf_rterm cl := all rterm cl.1 && all rterm cl.2.
Lemma qf_to_dnf_rterm f b : rformula f -> all dnf_rterm (qf_to_dnf f b).
Proof.
set ok := all dnf_rterm.
have cat_ok bcs1 bcs2: ok bcs1 -> ok bcs2 -> ok (bcs1 ++ bcs2).
by move=> ok1 ok2; rewrite [ok _]all_cat; apply/andP.
have and_ok bcs1 bcs2: ok bcs1 -> ok bcs2 -> ok (and_dnf bcs1 bcs2).
rewrite /and_dnf unlock; elim: bcs1 => //= cl1 bcs1 IH1; rewrite -andbA.
case/and3P=> ok11 ok12 ok1 ok2; rewrite cat_ok ?{}IH1 {bcs1 ok1}//.
elim: bcs2 ok2 => //= cl2 bcs2 IH2 /andP[ok2 /IH2->].
by rewrite /dnf_rterm !all_cat ok11 ok12 /= !andbT.
elim: f b => //=; [ by do 2!case | | | | | by auto | | ];
try by repeat case/andP || intro; case: ifP; auto.
by rewrite /dnf_rterm => ?? [] /= ->.
Qed.
Lemma dnf_to_rform bcs : rformula (dnf_to_form bcs) = all dnf_rterm bcs.
Proof.
elim: bcs => //= [[cl1 cl2] bcs ->]; rewrite {2}/dnf_rterm /=; congr (_ && _).
by (congr andb; [elim: cl1 | elim: cl2]) => //= t cl ->; rewrite andbT.
Qed.
Section If.
Variables (pred_f then_f else_f : formula R).
Definition If := (pred_f /\ then_f \/ ~ pred_f /\ else_f)%T.
Lemma If_form_qf :
qf_form pred_f -> qf_form then_f -> qf_form else_f -> qf_form If.
Proof. by move=> /= -> -> ->. Qed.
Lemma If_form_rf :
rformula pred_f -> rformula then_f -> rformula else_f -> rformula If.
Proof. by move=> /= -> -> ->. Qed.
Lemma eval_If e :
let ev := qf_eval e in ev If = (if ev pred_f then ev then_f else ev else_f).
Proof. by rewrite /=; case: ifP => _; rewrite ?orbF. Qed.
End If.
Section Pick.
Variables (I : finType) (pred_f then_f : I -> formula R) (else_f : formula R).
Definition Pick :=
\big[Or/False]_(p : {ffun pred I})
((\big[And/True]_i (if p i then pred_f i else ~ pred_f i))
/\ (if pick p is Some i then then_f i else else_f))%T.
Lemma Pick_form_qf :
(forall i, qf_form (pred_f i)) ->
(forall i, qf_form (then_f i)) ->
qf_form else_f ->
qf_form Pick.
Proof.
move=> qfp qft qfe; have mA := (big_morph qf_form) true andb.
rewrite mA // big1 //= => p _.
rewrite mA // big1 => [|i _]; first by case: pick.
by rewrite fun_if if_same /= qfp.
Qed.
Lemma eval_Pick e (qev := qf_eval e) :
let P i := qev (pred_f i) in
qev Pick = (if pick P is Some i then qev (then_f i) else qev else_f).
Proof.
move=> P; rewrite ((big_morph qev) false orb) //= big_orE /=.
apply/existsP/idP=> [[p] | true_at_P].
rewrite ((big_morph qev) true andb) //= big_andE /=.
case/andP=> /forallP-eq_p_P.
rewrite (@eq_pick _ _ P) => [|i]; first by case: pick.
by move/(_ i): eq_p_P => /=; case: (p i) => //= /negPf.
exists [ffun i => P i] => /=; apply/andP; split.
rewrite ((big_morph qev) true andb) //= big_andE /=.
by apply/forallP=> i; rewrite /= ffunE; case Pi: (P i) => //=; apply: negbT.
rewrite (@eq_pick _ _ P) => [|i]; first by case: pick true_at_P.
by rewrite ffunE.
Qed.
End Pick.
Section MultiQuant.
Variable f : formula R.
Implicit Types (I : seq nat) (e : seq R).
Lemma foldExistsP I e :
(exists2 e', {in [predC I], same_env e e'} & holds e' f)
<-> holds e (foldr Exists f I).
Proof.
elim: I e => /= [|i I IHi] e.
by split=> [[e' eq_e] |]; [apply: eq_holds => i; rewrite eq_e | exists e].
split=> [[e' eq_e f_e'] | [x]]; last set e_x := set_nth 0 e i x.
exists e'`_i; apply/IHi; exists e' => // j.
by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP => // ->.
case/IHi=> e' eq_e f_e'; exists e' => // j.
by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP.
Qed.
Lemma foldForallP I e :
(forall e', {in [predC I], same_env e e'} -> holds e' f)
<-> holds e (foldr Forall f I).
Proof.
elim: I e => /= [|i I IHi] e.
by split=> [|f_e e' eq_e]; [apply | apply: eq_holds f_e => i; rewrite eq_e].
split=> [f_e' x | f_e e' eq_e]; first set e_x := set_nth 0 e i x.
apply/IHi=> e' eq_e; apply: f_e' => j.
by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP.
move/IHi: (f_e e'`_i); apply=> j.
by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP => // ->.
Qed.
End MultiQuant.
End EvalTerm.
Prenex Implicits dnf_rterm.
Definition integral_domain_axiom (R : pzRingType) :=
forall x y : R, x * y = 0 -> (x == 0) || (y == 0).
HB.mixin Record ComUnitRing_isIntegral R of ComUnitRing R := {
mulf_eq0_subproof : integral_domain_axiom R;
}.
#[mathcomp(axiom="integral_domain_axiom"), short(type="idomainType")]
HB.structure Definition IntegralDomain :=
{R of ComUnitRing_isIntegral R & ComUnitRing R}.
Module IntegralDomainExports.
Bind Scope ring_scope with IntegralDomain.sort.
End IntegralDomainExports.
HB.export IntegralDomainExports.
Section IntegralDomainTheory.
Variable R : idomainType.
Implicit Types x y : R.
Lemma mulf_eq0 x y : (x * y == 0) = (x == 0) || (y == 0).
Proof.
apply/eqP/idP; first exact: mulf_eq0_subproof.
by case/pred2P=> ->; rewrite (mulr0, mul0r).
Qed.
Lemma prodf_eq0 (I : finType) (P : pred I) (F : I -> R) :
reflect (exists2 i, P i & (F i == 0)) (\prod_(i | P i) F i == 0).
Proof.
apply: (iffP idP) => [|[i Pi /eqP Fi0]]; last first.
by rewrite (bigD1 i) //= Fi0 mul0r.
elim: (index_enum _) => [|i r IHr]; first by rewrite big_nil oner_eq0.
rewrite big_cons /=; have [Pi | _] := ifP; last exact: IHr.
by rewrite mulf_eq0; case/orP=> // Fi0; exists i.
Qed.
Lemma prodf_seq_eq0 I r (P : pred I) (F : I -> R) :
(\prod_(i <- r | P i) F i == 0) = has (fun i => P i && (F i == 0)) r.
Proof. by rewrite (big_morph _ mulf_eq0 (oner_eq0 _)) big_has_cond. Qed.
Lemma mulf_neq0 x y : x != 0 -> y != 0 -> x * y != 0.
Proof. by move=> x0 y0; rewrite mulf_eq0; apply/norP. Qed.
Lemma prodf_neq0 (I : finType) (P : pred I) (F : I -> R) :
reflect (forall i, P i -> (F i != 0)) (\prod_(i | P i) F i != 0).
Proof. by rewrite (sameP (prodf_eq0 _ _) exists_inP); apply: exists_inPn. Qed.
Lemma prodf_seq_neq0 I r (P : pred I) (F : I -> R) :
(\prod_(i <- r | P i) F i != 0) = all (fun i => P i ==> (F i != 0)) r.
Proof.
rewrite prodf_seq_eq0 -all_predC; apply: eq_all => i /=.
by rewrite implybE negb_and.
Qed.
Lemma expf_eq0 x n : (x ^+ n == 0) = (n > 0) && (x == 0).
Proof.
elim: n => [|n IHn]; first by rewrite oner_eq0.
by rewrite exprS mulf_eq0 IHn andKb.
Qed.
Lemma sqrf_eq0 x : (x ^+ 2 == 0) = (x == 0). Proof. exact: expf_eq0. Qed.
Lemma expf_neq0 x m : x != 0 -> x ^+ m != 0.
Proof. by move=> x_nz; rewrite expf_eq0; apply/nandP; right. Qed.
Lemma natf_neq0_pchar n : (n%:R != 0 :> R) = (pchar R)^'.-nat n.
Proof.
have [-> | /prod_prime_decomp->] := posnP n; first by rewrite eqxx.
rewrite !big_seq; elim/big_rec: _ => [|[p e] s /=]; first by rewrite oner_eq0.
case/mem_prime_decomp=> p_pr _ _; rewrite pnatM pnatX eqn0Ngt orbC => <-.
by rewrite natrM natrX mulf_eq0 expf_eq0 negb_or negb_and pnatE ?inE p_pr.
Qed.
Lemma natf0_pchar n : n > 0 -> n%:R == 0 :> R -> exists p, p \in pchar R.
Proof.
move=> n_gt0 nR_0; exists (pdiv n`_(pchar R)).
apply: pnatP (pdiv_dvd _); rewrite ?part_pnat // ?pdiv_prime //.
by rewrite ltn_neqAle eq_sym partn_eq1 // -natf_neq0_pchar nR_0 /=.
Qed.
Lemma pcharf'_nat n : (pchar R)^'.-nat n = (n%:R != 0 :> R).
Proof.
have [-> | n_gt0] := posnP n; first by rewrite eqxx.
apply/idP/idP => [|nz_n]; last first.
by apply/pnatP=> // p p_pr p_dvd_n; apply: contra nz_n => /dvdn_pcharf <-.
apply: contraL => n0; have [// | p pcharRp] := natf0_pchar _ n0.
have [p_pr _] := andP pcharRp; rewrite (eq_pnat _ (eq_negn (pcharf_eq pcharRp))).
by rewrite p'natE // (dvdn_pcharf pcharRp) n0.
Qed.
Lemma pcharf0P : pchar R =i pred0 <-> (forall n, (n%:R == 0 :> R) = (n == 0)%N).
Proof.
split=> pcharF0 n; last by rewrite !inE pcharF0 andbC; case: eqP => // ->.
have [-> | n_gt0] := posnP; first exact: eqxx.
by apply/negP; case/natf0_pchar=> // p; rewrite pcharF0.
Qed.
Lemma eqf_sqr x y : (x ^+ 2 == y ^+ 2) = (x == y) || (x == - y).
Proof. by rewrite -subr_eq0 subr_sqr mulf_eq0 subr_eq0 addr_eq0. Qed.
Lemma mulfI x : x != 0 -> injective ( *%R x).
Proof.
move=> nz_x y z; apply: contra_eq => neq_yz.
by rewrite -subr_eq0 -mulrBr mulf_neq0 ?subr_eq0.
Qed.
Lemma mulIf x : x != 0 -> injective ( *%R^~ x).
Proof. by move=> nz_x y z; rewrite -!(mulrC x); apply: mulfI. Qed.
Lemma divfI x : x != 0 -> injective (fun y => x / y).
Proof. by move/mulfI/inj_comp; apply; apply: invr_inj. Qed.
Lemma divIf y : y != 0 -> injective (fun x => x / y).
Proof. by rewrite -invr_eq0; apply: mulIf. Qed.
Lemma sqrf_eq1 x : (x ^+ 2 == 1) = (x == 1) || (x == -1).
Proof. by rewrite -subr_eq0 subr_sqr_1 mulf_eq0 subr_eq0 addr_eq0. Qed.
Lemma expfS_eq1 x n :
(x ^+ n.+1 == 1) = (x == 1) || (\sum_(i < n.+1) x ^+ i == 0).
Proof. by rewrite -![_ == 1]subr_eq0 subrX1 mulf_eq0. Qed.
Lemma lregP x : reflect (lreg x) (x != 0).
Proof. by apply: (iffP idP) => [/mulfI | /lreg_neq0]. Qed.
Lemma rregP x : reflect (rreg x) (x != 0).
Proof. by apply: (iffP idP) => [/mulIf | /rreg_neq0]. Qed.
#[export]
HB.instance Definition _ := IntegralDomain.on R^o.
End IntegralDomainTheory.
#[deprecated(since="mathcomp 2.4.0", note="Use natf_neq0_pchar instead.")]
Notation natf_neq0 := natf_neq0_pchar (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use natf0_pchar instead.")]
Notation natf0_char := natf0_pchar (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf'_nat instead.")]
Notation charf'_nat := pcharf'_nat (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf0P instead.")]
Notation charf0P := pcharf0P (only parsing).
Arguments lregP {R x}.
Arguments rregP {R x}.
Definition field_axiom (R : unitRingType) := forall x : R, x != 0 -> x \in unit.
HB.mixin Record UnitRing_isField R of UnitRing R := {
fieldP : field_axiom R;
}.
#[mathcomp(axiom="field_axiom"), short(type="fieldType")]
HB.structure Definition Field := { R of IntegralDomain R & UnitRing_isField R }.
Module FieldExports.
Bind Scope ring_scope with Field.sort.
End FieldExports.
HB.export FieldExports.
#[export] HB.instance Definition regular_field (F : fieldType) := Field.on F^o.
Lemma IdomainMixin (R : unitRingType): Field.axiom R -> IntegralDomain.axiom R.
Proof.
move=> m x y xy0; apply/norP=> [[]] /m Ux /m.
by rewrite -(unitrMr _ Ux) xy0 unitr0.
Qed.
HB.factory Record ComUnitRing_isField R of ComUnitRing R := {
fieldP : field_axiom R;
}.
HB.builders Context R of ComUnitRing_isField R.
HB.instance Definition _ :=
ComUnitRing_isIntegral.Build R (IdomainMixin fieldP).
HB.instance Definition _ := UnitRing_isField.Build R fieldP.
HB.end.
HB.factory Record ComNzRing_isField R of ComNzRing R := {
inv : R -> R;
mulVf : forall x, x != 0 -> inv x * x = 1;
invr0 : inv 0 = 0;
}.
Module ComRing_isField.
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzRing_isField.Build instead.")]
Notation Build R := (ComNzRing_isField.Build R) (only parsing).
End ComRing_isField.
#[deprecated(since="mathcomp 2.4.0",
note="Use ComNzRing_isField instead.")]
Notation ComRing_isField R := (ComNzRing_isField R) (only parsing).
HB.builders Context R of ComNzRing_isField R.
Fact intro_unit (x y : R) : y * x = 1 -> x != 0.
Proof.
move=> yx1; apply: contraNneq (@oner_neq0 R) => x0.
by rewrite -yx1 x0 mulr0.
Qed.
Fact inv_out : {in predC (predC1 0), inv =1 id}.
Proof. by move=> x /negbNE/eqP->; exact: invr0. Qed.
HB.instance Definition _ : ComNzRing_hasMulInverse R :=
ComNzRing_hasMulInverse.Build R mulVf intro_unit inv_out.
HB.instance Definition _ : ComUnitRing_isField R :=
ComUnitRing_isField.Build R (fun x x_neq_0 => x_neq_0).
HB.end.
Section FieldTheory.
Variable F : fieldType.
Implicit Types x y : F.
Lemma unitfE x : (x \in unit) = (x != 0).
Proof. by apply/idP/idP=> [/(memPn _)-> | /fieldP]; rewrite ?unitr0. Qed.
Lemma mulVf x : x != 0 -> x^-1 * x = 1.
Proof. by rewrite -unitfE; apply: mulVr. Qed.
Lemma divff x : x != 0 -> x / x = 1.
Proof. by rewrite -unitfE; apply: divrr. Qed.
Definition mulfV := divff.
Lemma mulKf x : x != 0 -> cancel ( *%R x) ( *%R x^-1).
Proof. by rewrite -unitfE; apply: mulKr. Qed.
Lemma mulVKf x : x != 0 -> cancel ( *%R x^-1) ( *%R x).
Proof. by rewrite -unitfE; apply: mulVKr. Qed.
Lemma mulfK x : x != 0 -> cancel ( *%R^~ x) ( *%R^~ x^-1).
Proof. by rewrite -unitfE; apply: mulrK. Qed.
Lemma mulfVK x : x != 0 -> cancel ( *%R^~ x^-1) ( *%R^~ x).
Proof. by rewrite -unitfE; apply: divrK. Qed.
Definition divfK := mulfVK.
Lemma invfM : {morph @inv F : x y / x * y}.
Proof.
move=> x y; have [->|nzx] := eqVneq x 0; first by rewrite !(mul0r, invr0).
have [->|nzy] := eqVneq y 0; first by rewrite !(mulr0, invr0).
by rewrite mulrC invrM ?unitfE.
Qed.
Lemma invf_div x y : (x / y)^-1 = y / x.
Proof. by rewrite invfM invrK mulrC. Qed.
Lemma divKf x : x != 0 -> involutive (fun y => x / y).
Proof. by move=> nz_x y; rewrite invf_div mulrC divfK. Qed.
Lemma expfB_cond m n x : (x == 0) + n <= m -> x ^+ (m - n) = x ^+ m / x ^+ n.
Proof.
move/subnK=> <-; rewrite addnA addnK !exprD.
have [-> | nz_x] := eqVneq; first by rewrite !mulr0 !mul0r.
by rewrite mulfK ?expf_neq0.
Qed.
Lemma expfB m n x : n < m -> x ^+ (m - n) = x ^+ m / x ^+ n.
Proof. by move=> lt_n_m; apply: expfB_cond; case: eqP => // _; apply: ltnW. Qed.
Lemma prodfV I r (P : pred I) (E : I -> F) :
\prod_(i <- r | P i) (E i)^-1 = (\prod_(i <- r | P i) E i)^-1.
Proof. by rewrite (big_morph _ invfM (invr1 F)). Qed.
Lemma prodf_div I r (P : pred I) (E D : I -> F) :
\prod_(i <- r | P i) (E i / D i) =
\prod_(i <- r | P i) E i / \prod_(i <- r | P i) D i.
Proof. by rewrite big_split prodfV. Qed.
Lemma telescope_prodf n m (f : nat -> F) :
(forall k, n < k < m -> f k != 0) -> n < m ->
\prod_(n <= k < m) (f k.+1 / f k) = f m / f n.
Proof.
move=> nz_f ltnm; apply: invr_inj; rewrite prodf_div !invf_div -prodf_div.
by apply: telescope_prodr => // k /nz_f; rewrite unitfE.
Qed.
Lemma telescope_prodf_eq n m (f u : nat -> F) :
(forall k, n < k < m -> f k != 0) -> n < m ->
(forall k, n <= k < m -> u k = f k.+1 / f k) ->
\prod_(n <= k < m) u k = f m / f n.
Proof.
by move=> ? ? uE; under eq_big_nat do rewrite uE //=; exact: telescope_prodf.
Qed.
Lemma addf_div x1 y1 x2 y2 :
y1 != 0 -> y2 != 0 -> x1 / y1 + x2 / y2 = (x1 * y2 + x2 * y1) / (y1 * y2).
Proof. by move=> nzy1 nzy2; rewrite invfM mulrDl !mulrA mulrAC !mulfK. Qed.
Lemma mulf_div x1 y1 x2 y2 : (x1 / y1) * (x2 / y2) = (x1 * x2) / (y1 * y2).
Proof. by rewrite mulrACA -invfM. Qed.
Lemma eqr_div x y z t : y != 0 -> t != 0 -> (x / y == z / t) = (x * t == z * y).
Proof.
move=> yD0 tD0; rewrite -[x in RHS](divfK yD0) -[z in RHS](divfK tD0) mulrAC.
by apply/eqP/eqP => [->|/(mulIf yD0)/(mulIf tD0)].
Qed.
Lemma eqr_sum_div I r P (f : I -> F) c a : c != 0 ->
\big[+%R/0]_(x <- r | P x) (f x / c) == a
= (\big[+%R/0]_(x <- r | P x) f x == a * c).
Proof.
by move=> ?; rewrite -mulr_suml -(divr1 a) eqr_div ?oner_eq0// mulr1 divr1.
Qed.
Lemma pchar0_natf_div :
pchar F =i pred0 -> forall m d, d %| m -> (m %/ d)%:R = m%:R / d%:R :> F.
Proof.
move/pcharf0P=> pchar0F m [|d] d_dv_m; first by rewrite divn0 invr0 mulr0.
by rewrite natr_div // unitfE pchar0F.
Qed.
Section FieldMorphismInj.
Variables (R : nzRingType) (f : {rmorphism F -> R}).
Lemma fmorph_eq0 x : (f x == 0) = (x == 0).
Proof.
have [-> | nz_x] := eqVneq x; first by rewrite rmorph0 eqxx.
apply/eqP; move/(congr1 ( *%R (f x^-1)))/eqP.
by rewrite -rmorphM mulVf // mulr0 rmorph1 ?oner_eq0.
Qed.
Lemma fmorph_inj : injective f.
Proof. by apply/raddf_inj => x /eqP; rewrite fmorph_eq0 => /eqP. Qed.
Lemma fmorph_eq : {mono f : x y / x == y}.
Proof. exact: inj_eq fmorph_inj. Qed.
Lemma fmorph_eq1 x : (f x == 1) = (x == 1).
Proof. by rewrite -(inj_eq fmorph_inj) rmorph1. Qed.
Lemma fmorph_pchar : pchar R =i pchar F.
Proof. by move=> p; rewrite !inE -fmorph_eq0 rmorph_nat. Qed.
End FieldMorphismInj.
Section FieldMorphismInv.
Variables (R : unitRingType) (f : {rmorphism F -> R}).
Lemma fmorph_unit x : (f x \in unit) = (x != 0).
Proof.
have [-> |] := eqVneq x; first by rewrite rmorph0 unitr0.
by rewrite -unitfE; apply: rmorph_unit.
Qed.
Lemma fmorphV : {morph f: x / x^-1}.
Proof.
move=> x; have [-> | nz_x] := eqVneq x 0; first by rewrite !(invr0, rmorph0).
by rewrite rmorphV ?unitfE.
Qed.
Lemma fmorph_div : {morph f : x y / x / y}.
Proof. by move=> x y; rewrite rmorphM /= fmorphV. Qed.
End FieldMorphismInv.
Section ModuleTheory.
Variable V : lmodType F.
Implicit Types (a : F) (v : V).
Lemma scalerK a : a != 0 -> cancel ( *:%R a : V -> V) ( *:%R a^-1).
Proof. by move=> nz_a v; rewrite scalerA mulVf // scale1r. Qed.
Lemma scalerKV a : a != 0 -> cancel ( *:%R a^-1 : V -> V) ( *:%R a).
Proof. by rewrite -invr_eq0 -{3}[a]invrK; apply: scalerK. Qed.
Lemma scalerI a : a != 0 -> injective ( *:%R a : V -> V).
Proof. by move=> nz_a; apply: can_inj (scalerK nz_a). Qed.
Lemma scaler_eq0 a v : (a *: v == 0) = (a == 0) || (v == 0).
Proof.
have [-> | nz_a] := eqVneq a; first by rewrite scale0r eqxx.
by rewrite (can2_eq (scalerK nz_a) (scalerKV nz_a)) scaler0.
Qed.
End ModuleTheory.
Lemma pchar_lalg (A : lalgType F) : pchar A =i pchar F.
Proof. by move=> p; rewrite inE -scaler_nat scaler_eq0 oner_eq0 orbF. Qed.
End FieldTheory.
#[deprecated(since="mathcomp 2.4.0", note="Use pchar0_natf_div instead.")]
Notation char0_natf_div := pchar0_natf_div (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use fmorph_pchar instead.")]
Notation fmorph_char := fmorph_pchar (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pchar_lalg instead.")]
Notation char_lalg := pchar_lalg (only parsing).
Arguments fmorph_inj {F R} f [x1 x2].
Arguments telescope_prodf_eq {F n m} f u.
Definition decidable_field_axiom (R : unitRingType)
(s : seq R -> pred (formula R)) :=
forall e f, reflect (holds e f) (s e f).
HB.mixin Record Field_isDecField R of UnitRing R := {
sat : seq R -> pred (formula R);
satP : decidable_field_axiom sat;
}.
#[mathcomp(axiom="decidable_field_axiom"), short(type="decFieldType")]
HB.structure Definition DecidableField := { F of Field F & Field_isDecField F }.
Module DecFieldExports.
Bind Scope ring_scope with DecidableField.sort.
End DecFieldExports.
HB.export DecFieldExports.
#[export] HB.instance Definition _ (F : decFieldType) := DecidableField.on F^o.
Section DecidableFieldTheory.
Variable F : decFieldType.
Implicit Type f : formula F.
Fact sol_subproof n f :
reflect (exists s, (size s == n) && sat s f)
(sat [::] (foldr Exists f (iota 0 n))).
Proof.
apply: (iffP (satP _ _)) => [|[s]]; last first.
case/andP=> /eqP sz_s /satP f_s; apply/foldExistsP.
exists s => // i; rewrite !inE mem_iota -leqNgt add0n => le_n_i.
by rewrite !nth_default ?sz_s.
case/foldExistsP=> e e0 f_e; set s := take n (set_nth 0 e n 0).
have sz_s: size s = n by rewrite size_take size_set_nth leq_max leqnn.
exists s; rewrite sz_s eqxx; apply/satP; apply: eq_holds f_e => i.
case: (leqP n i) => [le_n_i | lt_i_n].
by rewrite -e0 ?nth_default ?sz_s // !inE mem_iota -leqNgt.
by rewrite nth_take // nth_set_nth /= eq_sym eqn_leq leqNgt lt_i_n.
Qed.
Definition sol n f :=
if sol_subproof n f is ReflectT sP then xchoose sP else nseq n 0.
Lemma size_sol n f : size (sol n f) = n.
Proof.
rewrite /sol; case: sol_subproof => [sP | _]; last exact: size_nseq.
by case/andP: (xchooseP sP) => /eqP.
Qed.
Lemma solP n f : reflect (exists2 s, size s = n & holds s f) (sat (sol n f) f).
Proof.
rewrite /sol; case: sol_subproof => [sP | sPn].
case/andP: (xchooseP sP) => _ ->; left.
by case: sP => s; case/andP; move/eqP=> <-; move/satP; exists s.
apply: (iffP (satP _ _)); first by exists (nseq n 0); rewrite ?size_nseq.
by case=> s sz_s; move/satP=> f_s; case: sPn; exists s; rewrite sz_s eqxx.
Qed.
Lemma eq_sat f1 f2 :
(forall e, holds e f1 <-> holds e f2) -> sat^~ f1 =1 sat^~ f2.
Proof. by move=> eqf12 e; apply/satP/satP; case: (eqf12 e). Qed.
Lemma eq_sol f1 f2 :
(forall e, holds e f1 <-> holds e f2) -> sol^~ f1 =1 sol^~ f2.
Proof.
rewrite /sol => /eq_sat eqf12 n.
do 2![case: sol_subproof] => //= [f1s f2s | ns1 [s f2s] | [s f1s] []].
- by apply: eq_xchoose => s; rewrite eqf12.
- by case: ns1; exists s; rewrite -eqf12.
by exists s; rewrite eqf12.
Qed.
End DecidableFieldTheory.
Arguments satP {F e f} : rename.
Arguments solP {F n f} : rename.
Section QE_Mixin.
Variable F : Field.type.
Implicit Type f : formula F.
Variable proj : nat -> seq (term F) * seq (term F) -> formula F.
(* proj is the elimination of a single existential quantifier *)
(* The elimination projector is well_formed. *)
Definition wf_QE_proj :=
forall i bc (bc_i := proj i bc),
dnf_rterm bc -> qf_form bc_i && rformula bc_i.
(* The elimination projector is valid *)
Definition valid_QE_proj :=
forall i bc (ex_i_bc := ('exists 'X_i, dnf_to_form [:: bc])%T) e,
dnf_rterm bc -> reflect (holds e ex_i_bc) (qf_eval e (proj i bc)).
Hypotheses (wf_proj : wf_QE_proj) (ok_proj : valid_QE_proj).
Let elim_aux f n := foldr Or False (map (proj n) (qf_to_dnf f false)).
Fixpoint quantifier_elim f :=
match f with
| f1 /\ f2 => (quantifier_elim f1) /\ (quantifier_elim f2)
| f1 \/ f2 => (quantifier_elim f1) \/ (quantifier_elim f2)
| f1 ==> f2 => (~ quantifier_elim f1) \/ (quantifier_elim f2)
| ~ f => ~ quantifier_elim f
| ('exists 'X_n, f) => elim_aux (quantifier_elim f) n
| ('forall 'X_n, f) => ~ elim_aux (~ quantifier_elim f) n
| _ => f
end%T.
Lemma quantifier_elim_wf f :
let qf := quantifier_elim f in rformula f -> qf_form qf && rformula qf.
Proof.
suffices aux_wf f0 n : let qf := elim_aux f0 n in
rformula f0 -> qf_form qf && rformula qf.
- by elim: f => //=; do ?[ move=> f1 IH1 f2 IH2;
case/andP=> rf1 rf2;
case/andP:(IH1 rf1)=> -> ->;
case/andP:(IH2 rf2)=> -> -> //
| move=> n f1 IH rf1;
case/andP: (IH rf1)=> qff rf;
rewrite aux_wf ].
rewrite /elim_aux => rf.
suffices or_wf fs : let ofs := foldr Or False fs in
all (@qf_form F) fs && all (@rformula F) fs -> qf_form ofs && rformula ofs.
- apply: or_wf.
suffices map_proj_wf bcs: let mbcs := map (proj n) bcs in
all dnf_rterm bcs -> all (@qf_form _) mbcs && all (@rformula _) mbcs.
by apply/map_proj_wf/qf_to_dnf_rterm.
elim: bcs => [|bc bcs ihb] bcsr //= /andP[rbc rbcs].
by rewrite andbAC andbA wf_proj //= andbC ihb.
elim: fs => //= g gs ihg; rewrite -andbA => /and4P[-> qgs -> rgs] /=.
by apply: ihg; rewrite qgs rgs.
Qed.
Lemma quantifier_elim_rformP e f :
rformula f -> reflect (holds e f) (qf_eval e (quantifier_elim f)).
Proof.
pose rc e n f := exists x, qf_eval (set_nth 0 e n x) f.
have auxP f0 e0 n0: qf_form f0 && rformula f0 ->
reflect (rc e0 n0 f0) (qf_eval e0 (elim_aux f0 n0)).
+ rewrite /elim_aux => cf; set bcs := qf_to_dnf f0 false.
apply: (@iffP (rc e0 n0 (dnf_to_form bcs))); last first.
- by case=> x; rewrite -qf_to_dnfP //; exists x.
- by case=> x; rewrite qf_to_dnfP //; exists x.
have: all dnf_rterm bcs by case/andP: cf => _; apply: qf_to_dnf_rterm.
elim: {f0 cf}bcs => [|bc bcs IHbcs] /=; first by right; case.
case/andP=> r_bc /IHbcs {IHbcs}bcsP.
have f_qf := dnf_to_form_qf [:: bc].
case: ok_proj => //= [ex_x|no_x].
left; case: ex_x => x /(qf_evalP _ f_qf); rewrite /= orbF => bc_x.
by exists x; rewrite /= bc_x.
apply: (iffP bcsP) => [[x bcs_x] | [x]] /=.
by exists x; rewrite /= bcs_x orbT.
case/orP => [bc_x|]; last by exists x.
by case: no_x; exists x; apply/(qf_evalP _ f_qf); rewrite /= bc_x.
elim: f e => //.
- by move=> b e _; apply: idP.
- by move=> t1 t2 e _; apply: eqP.
- move=> f1 IH1 f2 IH2 e /= /andP[/IH1[] f1e]; last by right; case.
by case/IH2; [left | right; case].
- move=> f1 IH1 f2 IH2 e /= /andP[/IH1[] f1e]; first by do 2!left.
by case/IH2; [left; right | right; case].
- move=> f1 IH1 f2 IH2 e /= /andP[/IH1[] f1e]; last by left.
by case/IH2; [left | right; move/(_ f1e)].
- by move=> f IHf e /= /IHf[]; [right | left].
- move=> n f IHf e /= rf; have rqf := quantifier_elim_wf rf.
by apply: (iffP (auxP _ _ _ rqf)) => [] [x]; exists x; apply/IHf.
move=> n f IHf e /= rf; have rqf := quantifier_elim_wf rf.
case: auxP => // [f_x|no_x]; first by right=> no_x; case: f_x => x /IHf[].
by left=> x; apply/IHf=> //; apply/idPn=> f_x; case: no_x; exists x.
Qed.
Definition proj_sat e f := qf_eval e (quantifier_elim (to_rform f)).
Lemma proj_satP : DecidableField.axiom proj_sat.
Proof.
move=> e f; have fP := quantifier_elim_rformP e (to_rform_rformula f).
by apply: (iffP fP); move/to_rformP.
Qed.
End QE_Mixin.
HB.factory Record Field_QE_isDecField F of Field F := {
proj : nat -> seq (term F) * seq (term F) -> formula F;
wf_proj : wf_QE_proj proj;
ok_proj : valid_QE_proj proj;
}.
HB.builders Context F of Field_QE_isDecField F.
HB.instance Definition qe_is_def_field : Field_isDecField F :=
Field_isDecField.Build F (proj_satP wf_proj ok_proj).
HB.end.
(* Axiom == all non-constant monic polynomials have a root *)
Definition closed_field_axiom (R : pzRingType) :=
forall n (P : nat -> R), n > 0 ->
exists x : R, x ^+ n = \sum_(i < n) P i * (x ^+ i).
HB.mixin Record DecField_isAlgClosed F of DecidableField F := {
solve_monicpoly : closed_field_axiom F;
}.
#[mathcomp(axiom="closed_field_axiom"), short(type="closedFieldType")]
HB.structure Definition ClosedField :=
{ F of DecidableField F & DecField_isAlgClosed F }.
Module ClosedFieldExports.
Bind Scope ring_scope with ClosedField.sort.
End ClosedFieldExports.
HB.export ClosedFieldExports.
#[export] HB.instance Definition _ (F : closedFieldType) := ClosedField.on F^o.
Section ClosedFieldTheory.
Variable F : closedFieldType.
Lemma imaginary_exists : {i : F | i ^+ 2 = -1}.
Proof.
have /sig_eqW[i Di2] := @solve_monicpoly F 2 (nth 0 [:: -1]) isT.
by exists i; rewrite Di2 !big_ord_recl big_ord0 mul0r mulr1 !addr0.
Qed.
End ClosedFieldTheory.
Lemma lalgMixin (R : pzRingType) (A : lalgType R) (B : lmodType R) (f : B -> A) :
phant B -> injective f -> scalable f ->
forall mulB, {morph f : x y / mulB x y >-> x * y} ->
forall a u v, a *: (mulB u v) = mulB (a *: u) v.
Proof.
by move=> _ injf fZ mulB fM a x y; apply: injf; rewrite !(fZ, fM) scalerAl.
Qed.
Lemma comRingMixin (R : comPzRingType) (T : pzRingType) (f : T -> R) :
phant T -> injective f -> {morph f : x y / x * y} -> commutative (@mul T).
Proof. by move=> _ inj_f fM x y; apply: inj_f; rewrite !fM mulrC. Qed.
Lemma algMixin (R : pzRingType) (A : algType R) (B : lalgType R) (f : B -> A) :
phant B -> injective f -> {morph f : x y / x * y} -> scalable f ->
forall k (x y : B), k *: (x * y) = x * (k *: y).
Proof.
by move=> _ inj_f fM fZ a x y; apply: inj_f; rewrite !(fM, fZ) scalerAr.
Qed.
(* Mixins for stability properties *)
HB.mixin Record isMul2Closed (R : pzSemiRingType) (S : {pred R}) := {
rpredM : mulr_2closed S
}.
HB.mixin Record isMul1Closed (R : pzSemiRingType) (S : {pred R}) := {
rpred1 : 1 \in S
}.
HB.mixin Record isInvClosed (R : unitRingType) (S : {pred R}) := {
rpredVr : invr_closed S
}.
HB.mixin Record isScaleClosed (R : pzSemiRingType) (V : lSemiModType R)
(S : {pred V}) := {
rpredZ : scaler_closed S
}.
(* Structures for stability properties *)
Local Notation addrClosed := addrClosed.
Local Notation opprClosed := opprClosed.
#[short(type="mulr2Closed")]
HB.structure Definition Mul2Closed (R : pzSemiRingType) :=
{S of isMul2Closed R S}.
#[short(type="mulrClosed")]
HB.structure Definition MulClosed (R : pzSemiRingType) :=
{S of Mul2Closed R S & isMul1Closed R S}.
#[short(type="semiring2Closed")]
HB.structure Definition Semiring2Closed (R : pzSemiRingType) :=
{S of AddClosed R S & Mul2Closed R S}.
#[short(type="semiringClosed")]
HB.structure Definition SemiringClosed (R : pzSemiRingType) :=
{S of AddClosed R S & MulClosed R S}.
#[short(type="smulClosed")]
HB.structure Definition SmulClosed (R : pzRingType) :=
{S of OppClosed R S & MulClosed R S}.
#[short(type="subringClosed")]
HB.structure Definition SubringClosed (R : pzRingType) :=
{S of ZmodClosed R S & MulClosed R S}.
#[short(type="divClosed")]
HB.structure Definition DivClosed (R : unitRingType) :=
{S of MulClosed R S & isInvClosed R S}.
#[short(type="sdivClosed")]
HB.structure Definition SdivClosed (R : unitRingType) :=
{S of SmulClosed R S & isInvClosed R S}.
#[short(type="submodClosed")]
HB.structure Definition SubmodClosed (R : pzSemiRingType) (V : lSemiModType R)
:= {S of AddClosed V S & isScaleClosed R V S}.
#[short(type="subalgClosed")]
HB.structure Definition SubalgClosed (R : pzSemiRingType) (A : lSemiAlgType R)
:= {S of SemiringClosed A S & isScaleClosed R A S}.
#[short(type="divringClosed")]
HB.structure Definition DivringClosed (R : unitRingType) :=
{S of SubringClosed R S & isInvClosed R S}.
#[short(type="divalgClosed")]
HB.structure Definition DivalgClosed (R : pzRingType) (A : unitAlgType R) :=
{S of DivringClosed A S & isScaleClosed R A S}.
(* Factories for stability properties *)
HB.factory Record isMulClosed (R : pzSemiRingType) (S : {pred R}) := {
rpred1M : mulr_closed S
}.
HB.builders Context R S of isMulClosed R S.
HB.instance Definition _ := isMul2Closed.Build R S (proj2 rpred1M).
HB.instance Definition _ := isMul1Closed.Build R S (proj1 rpred1M).
HB.end.
HB.factory Record isSmulClosed (R : pzRingType) (S : R -> bool) := {
smulr_closed_subproof : smulr_closed S
}.
HB.builders Context R S of isSmulClosed R S.
HB.instance Definition _ := isMulClosed.Build R S
(smulr_closedM smulr_closed_subproof).
HB.instance Definition _ := isOppClosed.Build R S
(smulr_closedN smulr_closed_subproof).
HB.end.
HB.factory Record isSemiringClosed (R : pzSemiRingType) (S : R -> bool) := {
semiring_closed_subproof : semiring_closed S
}.
HB.builders Context R S of isSemiringClosed R S.
HB.instance Definition _ := isAddClosed.Build R S
(semiring_closedD semiring_closed_subproof).
HB.instance Definition _ := isMulClosed.Build R S
(semiring_closedM semiring_closed_subproof).
HB.end.
HB.factory Record isSubringClosed (R : pzRingType) (S : R -> bool) := {
subring_closed_subproof : subring_closed S
}.
HB.builders Context R S of isSubringClosed R S.
HB.instance Definition _ := isZmodClosed.Build R S
(subring_closedB subring_closed_subproof).
HB.instance Definition _ := isSmulClosed.Build R S
(subring_closedM subring_closed_subproof).
HB.end.
HB.factory Record isDivClosed (R : unitRingType) (S : R -> bool) := {
divr_closed_subproof : divr_closed S
}.
HB.builders Context R S of isDivClosed R S.
HB.instance Definition _ := isMulClosed.Build R S
(divr_closedM divr_closed_subproof).
HB.instance Definition _ := isInvClosed.Build R S
(divr_closedV divr_closed_subproof).
HB.end.
HB.factory Record isSdivClosed (R : unitRingType) (S : R -> bool) := {
sdivr_closed_subproof : sdivr_closed S
}.
HB.builders Context R S of isSdivClosed R S.
HB.instance Definition _ := isDivClosed.Build R S
(sdivr_closed_div sdivr_closed_subproof).
HB.instance Definition _ := isSmulClosed.Build R S
(sdivr_closedM sdivr_closed_subproof).
HB.end.
HB.factory Record isSubSemiModClosed (R : pzSemiRingType) (V : lSemiModType R)
(S : V -> bool) := {
subsemimod_closed_subproof : subsemimod_closed S
}.
HB.builders Context R V S of isSubSemiModClosed R V S.
HB.instance Definition _ := isAddClosed.Build V S
(subsemimod_closedD subsemimod_closed_subproof).
HB.instance Definition _ := isScaleClosed.Build R V S
(subsemimod_closedZ subsemimod_closed_subproof).
HB.end.
HB.factory Record isSubmodClosed (R : pzRingType) (V : lmodType R)
(S : V -> bool) := {
submod_closed_subproof : submod_closed S
}.
HB.builders Context R V S of isSubmodClosed R V S.
HB.instance Definition _ := isZmodClosed.Build V S
(submod_closedB submod_closed_subproof).
HB.instance Definition _ := isScaleClosed.Build R V S
(subsemimod_closedZ (submod_closed_semi submod_closed_subproof)).
HB.end.
HB.factory Record isSubalgClosed (R : pzRingType) (A : lalgType R)
(S : A -> bool) := {
subalg_closed_subproof : subalg_closed S
}.
HB.builders Context R A S of isSubalgClosed R A S.
HB.instance Definition _ := isSubmodClosed.Build R A S
(subalg_closedZ subalg_closed_subproof).
HB.instance Definition _ := isSubringClosed.Build A S
(subalg_closedBM subalg_closed_subproof).
HB.end.
HB.factory Record isDivringClosed (R : unitRingType) (S : R -> bool) := {
divring_closed_subproof : divring_closed S
}.
HB.builders Context R S of isDivringClosed R S.
HB.instance Definition _ := isSubringClosed.Build R S
(divring_closedBM divring_closed_subproof).
HB.instance Definition _ := isSdivClosed.Build R S
(divring_closed_div divring_closed_subproof).
HB.end.
HB.factory Record isDivalgClosed (R : comUnitRingType) (A : unitAlgType R)
(S : A -> bool) := {
divalg_closed_subproof : divalg_closed S
}.
HB.builders Context R A S of isDivalgClosed R A S.
HB.instance Definition _ := isDivringClosed.Build A S
(divalg_closedBdiv divalg_closed_subproof).
HB.instance Definition _ := isSubalgClosed.Build R A S
(divalg_closedZ divalg_closed_subproof).
HB.end.
Section NmodulePred.
Variables (V : nmodType).
Section Add.
Variable S : addrClosed V.
Lemma rpred0D : nmod_closed S. Proof. exact: nmod_closed_subproof. Qed.
End Add.
End NmodulePred.
Section ZmodulePred.
Variables (V : zmodType).
Section Opp.
Variable S : opprClosed V.
End Opp.
Section Sub.
Variable S : zmodClosed V.
Lemma zmodClosedP : zmod_closed S.
Proof. split; [ exact: (@rpred0D V S).1 | exact: rpredB ]. Qed.
End Sub.
End ZmodulePred.
Section SemiRingPred.
Variables (R : pzSemiRingType).
Section Mul.
Variable S : mulrClosed R.
Lemma rpred1M : mulr_closed S.
Proof. exact: (conj rpred1 rpredM). Qed.
Lemma rpred_prod I r (P : pred I) F :
(forall i, P i -> F i \in S) -> \prod_(i <- r | P i) F i \in S.
Proof. by move=> IH; elim/big_ind: _; [apply: rpred1 | apply: rpredM |]. Qed.
Lemma rpredX n : {in S, forall u, u ^+ n \in S}.
Proof. by move=> u Su; rewrite -(card_ord n) -prodr_const rpred_prod. Qed.
End Mul.
Lemma rpred_nat (S : semiringClosed R) n : n%:R \in S.
Proof. by rewrite rpredMn ?rpred1. Qed.
Lemma semiringClosedP (rngS : semiringClosed R) : semiring_closed rngS.
Proof. split; [ exact: rpred0D | exact: rpred1M ]. Qed.
End SemiRingPred.
Section RingPred.
Variables (R : pzRingType).
Lemma rpredMsign (S : opprClosed R) n x : ((-1) ^+ n * x \in S) = (x \in S).
Proof. by rewrite -signr_odd mulr_sign; case: ifP => // _; rewrite rpredN. Qed.
Lemma rpredN1 (S : smulClosed R) : -1 \in S.
Proof. by rewrite rpredN rpred1. Qed.
Lemma rpred_sign (S : smulClosed R) n : (-1) ^+ n \in S.
Proof. by rewrite rpredX ?rpredN1. Qed.
Lemma subringClosedP (rngS : subringClosed R) : subring_closed rngS.
Proof.
split; [ exact: rpred1 | exact: (zmodClosedP rngS).2 | exact: rpredM ].
Qed.
End RingPred.
Section LmodPred.
Variables (R : pzSemiRingType) (V : lSemiModType R).
Lemma rpredZnat (S : addrClosed V) n : {in S, forall u, n%:R *: u \in S}.
Proof. by move=> u Su; rewrite /= scaler_nat rpredMn. Qed.
Lemma subsemimodClosedP (modS : submodClosed V) : subsemimod_closed modS.
Proof. by split; [exact: rpred0D | exact: rpredZ]. Qed.
End LmodPred.
Section LmodPred.
Variables (R : pzRingType) (V : lmodType R).
Lemma rpredZsign (S : opprClosed V) n u : ((-1) ^+ n *: u \in S) = (u \in S).
Proof. by rewrite -signr_odd scaler_sign fun_if if_arg rpredN if_same. Qed.
Lemma submodClosedP (modS : submodClosed V) : submod_closed modS.
Proof.
split; first exact (@rpred0D V modS).1.
by move=> a u v uS vS; apply: rpredD; first exact: rpredZ.
Qed.
End LmodPred.
Section LalgPred.
Variables (R : pzRingType) (A : lalgType R).
Lemma subalgClosedP (algS : subalgClosed A) : subalg_closed algS.
Proof.
split; [ exact: rpred1 | | exact: rpredM ].
by move=> a u v uS vS; apply: rpredD; first exact: rpredZ.
Qed.
End LalgPred.
Section UnitRingPred.
Variable R : unitRingType.
Section Div.
Variable S : divClosed R.
Lemma rpredV x : (x^-1 \in S) = (x \in S).
Proof. by apply/idP/idP=> /rpredVr; rewrite ?invrK. Qed.
Lemma rpred_div : {in S &, forall x y, x / y \in S}.
Proof. by move=> x y Sx Sy; rewrite /= rpredM ?rpredV. Qed.
Lemma rpredXN n : {in S, forall x, x ^- n \in S}.
Proof. by move=> x Sx; rewrite /= rpredV rpredX. Qed.
Lemma rpredMl x y : x \in S -> x \is a unit-> (x * y \in S) = (y \in S).
Proof.
move=> Sx Ux; apply/idP/idP=> [Sxy | /(rpredM _ _ Sx)-> //].
by rewrite -(mulKr Ux y); rewrite rpredM ?rpredV.
Qed.
Lemma rpredMr x y : x \in S -> x \is a unit -> (y * x \in S) = (y \in S).
Proof.
move=> Sx Ux; apply/idP/idP=> [Sxy | /rpredM-> //].
by rewrite -(mulrK Ux y); rewrite rpred_div.
Qed.
Lemma rpred_divr x y : x \in S -> x \is a unit -> (y / x \in S) = (y \in S).
Proof. by rewrite -rpredV -unitrV; apply: rpredMr. Qed.
Lemma rpred_divl x y : x \in S -> x \is a unit -> (x / y \in S) = (y \in S).
Proof. by rewrite -(rpredV y); apply: rpredMl. Qed.
End Div.
Lemma divringClosedP (divS : divringClosed R) : divring_closed divS.
Proof. split; [ exact: rpred1 | exact: rpredB | exact: rpred_div ]. Qed.
Fact unitr_sdivr_closed : @sdivr_closed R unit.
Proof. by split=> [|x y Ux Uy]; rewrite ?unitrN1 // unitrMl ?unitrV. Qed.
#[export]
HB.instance Definition _ := isSdivClosed.Build R unit_pred unitr_sdivr_closed.
Implicit Type x : R.
Lemma unitrN x : (- x \is a unit) = (x \is a unit). Proof. exact: rpredN. Qed.
Lemma invrN x : (- x)^-1 = - x^-1.
Proof.
have [Ux | U'x] := boolP (x \is a unit); last by rewrite !invr_out ?unitrN.
by rewrite -mulN1r invrM ?unitrN1 // invrN1 mulrN1.
Qed.
Lemma divrNN x y : (- x) / (- y) = x / y.
Proof. by rewrite invrN mulrNN. Qed.
Lemma divrN x y : x / (- y) = - (x / y).
Proof. by rewrite invrN mulrN. Qed.
Lemma invr_signM n x : ((-1) ^+ n * x)^-1 = (-1) ^+ n * x^-1.
Proof. by rewrite -signr_odd !mulr_sign; case: ifP => // _; rewrite invrN. Qed.
Lemma divr_signM (b1 b2 : bool) x1 x2:
((-1) ^+ b1 * x1) / ((-1) ^+ b2 * x2) = (-1) ^+ (b1 (+) b2) * (x1 / x2).
Proof. by rewrite invr_signM mulr_signM. Qed.
End UnitRingPred.
Section FieldPred.
Variable F : fieldType.
Implicit Types x y : F.
Section ModuleTheory.
Variable V : lmodType F.
Implicit Types (a : F) (v : V).
Lemma rpredZeq (S : submodClosed V) a v :
(a *: v \in S) = (a == 0) || (v \in S).
Proof.
have [-> | nz_a] := eqVneq; first by rewrite scale0r rpred0.
by apply/idP/idP; first rewrite -{2}(scalerK nz_a v); apply: rpredZ.
Qed.
End ModuleTheory.
Section Predicates.
Context (S : divClosed F).
Lemma fpredMl x y : x \in S -> x != 0 -> (x * y \in S) = (y \in S).
Proof. by rewrite -!unitfE; apply: rpredMl. Qed.
Lemma fpredMr x y : x \in S -> x != 0 -> (y * x \in S) = (y \in S).
Proof. by rewrite -!unitfE; apply: rpredMr. Qed.
Lemma fpred_divl x y : x \in S -> x != 0 -> (x / y \in S) = (y \in S).
Proof. by rewrite -!unitfE; apply: rpred_divl. Qed.
Lemma fpred_divr x y : x \in S -> x != 0 -> (y / x \in S) = (y \in S).
Proof. by rewrite -!unitfE; apply: rpred_divr. Qed.
End Predicates.
End FieldPred.
HB.mixin Record isSubPzSemiRing (R : pzSemiRingType) (S : pred R) U
of SubNmodule R S U & PzSemiRing U := {
valM_subproof : monoid_morphism (val : U -> R);
}.
Module isSubSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use isSubPzSemiRing.Build instead.")]
Notation Build R S U := (isSubPzSemiRing.Build R S U) (only parsing).
End isSubSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use isSubPzSemiRing instead.")]
Notation isSubSemiRing R S U := (isSubPzSemiRing R S U) (only parsing).
#[short(type="subPzSemiRingType")]
HB.structure Definition SubPzSemiRing (R : pzSemiRingType) (S : pred R) :=
{ U of SubNmodule R S U & PzSemiRing U & isSubPzSemiRing R S U }.
#[short(type="subNzSemiRingType")]
HB.structure Definition SubNzSemiRing (R : nzSemiRingType) (S : pred R) :=
{ U of SubNmodule R S U & NzSemiRing U & isSubPzSemiRing R S U }.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzSemiRing instead.")]
Notation SubSemiRing R := (SubNzSemiRing R) (only parsing).
Module SubSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzSemiRing.sort instead.")]
Notation sort := (SubNzSemiRing.sort) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzSemiRing.on instead.")]
Notation on R := (SubNzSemiRing.on R) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzSemiRing.copy instead.")]
Notation copy T U := (SubNzSemiRing.copy T U) (only parsing).
End SubSemiRing.
Section multiplicative.
Context (R : pzSemiRingType) (S : pred R) (U : SubPzSemiRing.type S).
Notation val := (val : U -> R).
#[export]
HB.instance Definition _ := isMonoidMorphism.Build U R val valM_subproof.
Lemma val1 : val 1 = 1. Proof. exact: rmorph1. Qed.
Lemma valM : {morph val : x y / x * y}. Proof. exact: rmorphM. Qed.
Lemma valM1 : monoid_morphism val. Proof. exact: valM_subproof. Qed.
End multiplicative.
HB.factory Record SubNmodule_isSubPzSemiRing (R : pzSemiRingType) S U
of SubNmodule R S U := {
mulr_closed_subproof : mulr_closed S
}.
HB.builders Context R S U of SubNmodule_isSubPzSemiRing R S U.
HB.instance Definition _ := isMulClosed.Build R S mulr_closed_subproof.
Let inU v Sv : U := Sub v Sv.
Let oneU : U := inU (@rpred1 _ (MulClosed.clone R S _)).
Let mulU (u1 u2 : U) := inU (rpredM _ _ (valP u1) (valP u2)).
Lemma mulrA : associative mulU.
Proof. by move=> x y z; apply: val_inj; rewrite !SubK mulrA. Qed.
Lemma mul1r : left_id oneU mulU.
Proof. by move=> x; apply: val_inj; rewrite !SubK mul1r. Qed.
Lemma mulr1 : right_id oneU mulU.
Proof. by move=> x; apply: val_inj; rewrite !SubK mulr1. Qed.
Lemma mulrDl : left_distributive mulU +%R.
Proof.
by move=> x y z; apply: val_inj; rewrite !(SubK, raddfD)/= !SubK mulrDl.
Qed.
Lemma mulrDr : right_distributive mulU +%R.
Proof.
by move=> x y z; apply: val_inj; rewrite !(SubK, raddfD)/= !SubK mulrDr.
Qed.
Lemma mul0r : left_zero 0%R mulU.
Proof. by move=> x; apply: val_inj; rewrite SubK val0 mul0r. Qed.
Lemma mulr0 : right_zero 0%R mulU.
Proof. by move=> x; apply: val_inj; rewrite SubK val0 mulr0. Qed.
HB.instance Definition _ := Nmodule_isPzSemiRing.Build U
mulrA mul1r mulr1 mulrDl mulrDr mul0r mulr0.
Lemma valM : monoid_morphism (val : U -> R).
Proof. by split=> [|x y] /=; rewrite !SubK. Qed.
HB.instance Definition _ := isSubPzSemiRing.Build R S U valM.
HB.end.
HB.factory Record SubNmodule_isSubNzSemiRing (R : nzSemiRingType) S U
of SubNmodule R S U := {
mulr_closed_subproof : mulr_closed S
}.
Module SubNmodule_isSubSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNmodule_isSubNzSemiRing.Build instead.")]
Notation Build R S U := (SubNmodule_isSubNzSemiRing.Build R S U) (only parsing).
End SubNmodule_isSubSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNmodule_isSubNzSemiRing instead.")]
Notation SubNmodule_isSubSemiRing R S U :=
(SubNmodule_isSubNzSemiRing R S U) (only parsing).
HB.builders Context R S U of SubNmodule_isSubNzSemiRing R S U.
HB.instance Definition _ := SubNmodule_isSubPzSemiRing.Build R S U
mulr_closed_subproof.
Lemma oner_neq0 : (1 : U) != 0.
Proof. by rewrite -(inj_eq val_inj) SubK raddf0 oner_neq0. Qed.
HB.instance Definition _ := PzSemiRing_isNonZero.Build U oner_neq0.
HB.end.
#[short(type="subComPzSemiRingType")]
HB.structure Definition SubComPzSemiRing (R : pzSemiRingType) S :=
{U of SubPzSemiRing R S U & ComPzSemiRing U}.
HB.factory Record SubPzSemiRing_isSubComPzSemiRing (R : comPzSemiRingType) S U
of SubPzSemiRing R S U := {}.
HB.builders Context R S U of SubPzSemiRing_isSubComPzSemiRing R S U.
Lemma mulrC : @commutative U U *%R.
Proof. by move=> x y; apply: val_inj; rewrite !rmorphM mulrC. Qed.
HB.instance Definition _ := PzSemiRing_hasCommutativeMul.Build U mulrC.
HB.end.
#[short(type="subComNzSemiRingType")]
HB.structure Definition SubComNzSemiRing (R : nzSemiRingType) S :=
{U of SubNzSemiRing R S U & ComNzSemiRing U}.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubComNzSemiRing instead.")]
Notation SubComSemiRing R := (SubComNzSemiRing R) (only parsing).
Module SubComSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubComNzSemiRing.sort instead.")]
Notation sort := (SubComNzSemiRing.sort) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use SubComNzSemiRing.on instead.")]
Notation on R := (SubComNzSemiRing.on R) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use SubComNzSemiRing.copy instead.")]
Notation copy T U := (SubComNzSemiRing.copy T U) (only parsing).
End SubComSemiRing.
HB.factory Record SubNzSemiRing_isSubComNzSemiRing (R : comNzSemiRingType) S U
of SubNzSemiRing R S U := {}.
Module SubSemiRing_isSubComSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzSemiRing_isSubComNzSemiRing.Build instead.")]
Notation Build R S U :=
(SubNzSemiRing_isSubComNzSemiRing.Build R S U) (only parsing).
End SubSemiRing_isSubComSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzSemiRing_isSubComNzSemiRing instead.")]
Notation SubSemiRing_isSubComSemiRing R S U :=
(SubNzSemiRing_isSubComNzSemiRing R S U) (only parsing).
HB.builders Context R S U of SubNzSemiRing_isSubComNzSemiRing R S U.
HB.instance Definition _ := SubPzSemiRing_isSubComPzSemiRing.Build R S U.
HB.end.
#[short(type="subPzRingType")]
HB.structure Definition SubPzRing (R : pzRingType) (S : pred R) :=
{ U of SubPzSemiRing R S U & PzRing U & isSubZmodule R S U }.
HB.factory Record SubZmodule_isSubPzRing (R : pzRingType) S U
of SubZmodule R S U := {
subring_closed_subproof : subring_closed S
}.
HB.builders Context R S U of SubZmodule_isSubPzRing R S U.
HB.instance Definition _ := isSubringClosed.Build R S subring_closed_subproof.
Let inU v Sv : U := Sub v Sv.
Let oneU : U := inU (@rpred1 _ (MulClosed.clone R S _)).
Let mulU (u1 u2 : U) := inU (rpredM _ _ (valP u1) (valP u2)).
HB.instance Definition _ := SubNmodule_isSubPzSemiRing.Build R S U
(smulr_closedM (subring_closedM subring_closed_subproof)).
HB.end.
#[short(type="subNzRingType")]
HB.structure Definition SubNzRing (R : nzRingType) (S : pred R) :=
{ U of SubNzSemiRing R S U & NzRing U & isSubBaseAddUMagma R S U }.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzRing instead.")]
Notation SubRing R := (SubNzRing R) (only parsing).
Module SubRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzRing.sort instead.")]
Notation sort := (SubNzRing.sort) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzRing.on instead.")]
Notation on R := (SubNzRing.on R) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzRing.copy instead.")]
Notation copy T U := (SubNzRing.copy T U) (only parsing).
End SubRing.
HB.factory Record SubZmodule_isSubNzRing (R : nzRingType) S U
of SubZmodule R S U := {
subring_closed_subproof : subring_closed S
}.
Module SubZmodule_isSubRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubZmodule_isSubNzRing.Build instead.")]
Notation Build R S U := (SubZmodule_isSubNzRing.Build R S U) (only parsing).
End SubZmodule_isSubRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubZmodule_isSubNzRing instead.")]
Notation SubZmodule_isSubRing R S U :=
(SubZmodule_isSubNzRing R S U) (only parsing).
HB.builders Context R S U of SubZmodule_isSubNzRing R S U.
HB.instance Definition _ := isSubringClosed.Build R S subring_closed_subproof.
Let inU v Sv : U := Sub v Sv.
Let oneU : U := inU (@rpred1 _ (MulClosed.clone R S _)).
Let mulU (u1 u2 : U) := inU (rpredM _ _ (valP u1) (valP u2)).
HB.instance Definition _ := SubNmodule_isSubNzSemiRing.Build R S U
(smulr_closedM (subring_closedM subring_closed_subproof)).
HB.end.
#[short(type="subComPzRingType")]
HB.structure Definition SubComPzRing (R : pzRingType) S :=
{U of SubPzRing R S U & ComPzRing U}.
HB.factory Record SubPzRing_isSubComPzRing (R : comPzRingType) S U
of SubPzRing R S U := {}.
HB.builders Context R S U of SubPzRing_isSubComPzRing R S U.
Lemma mulrC : @commutative U U *%R.
Proof. by move=> x y; apply: val_inj; rewrite !rmorphM mulrC. Qed.
HB.instance Definition _ := PzRing_hasCommutativeMul.Build U mulrC.
HB.end.
#[short(type="subComNzRingType")]
HB.structure Definition SubComNzRing (R : nzRingType) S :=
{U of SubNzRing R S U & ComNzRing U}.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubComNzRing instead.")]
Notation SubComRing R := (SubComNzRing R) (only parsing).
Module SubComRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubComNzRing.sort instead.")]
Notation sort := (SubComNzRing.sort) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use SubComNzRing.on instead.")]
Notation on R := (SubComNzRing.on R) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use SubComNzRing.copy instead.")]
Notation copy T U := (SubComNzRing.copy T U) (only parsing).
End SubComRing.
HB.factory Record SubNzRing_isSubComNzRing (R : comNzRingType) S U
of SubNzRing R S U := {}.
Module SubRing_isSubComRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzRing_isSubComNzRing.Build instead.")]
Notation Build R S U := (SubNzRing_isSubComNzRing.Build R S U) (only parsing).
End SubRing_isSubComRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzRing_isSubComNzRing instead.")]
Notation SubRing_isSubComRing R S U :=
(SubNzRing_isSubComNzRing R S U) (only parsing).
HB.builders Context R S U of SubNzRing_isSubComNzRing R S U.
HB.instance Definition _ := SubPzRing_isSubComPzRing.Build R S U.
HB.end.
HB.mixin Record isSubLSemiModule (R : pzSemiRingType) (V : lSemiModType R)
(S : pred V) W of SubNmodule V S W & LSemiModule R W := {
valZ : scalable (val : W -> V);
}.
#[short(type="subLSemiModType")]
HB.structure Definition SubLSemiModule (R : pzSemiRingType) (V : lSemiModType R)
(S : pred V) :=
{ W of SubNmodule V S W &
Nmodule_isLSemiModule R W & isSubLSemiModule R V S W}.
#[short(type="subLmodType")]
HB.structure Definition SubLmodule (R : pzRingType) (V : lmodType R)
(S : pred V) :=
{ W of SubZmodule V S W &
Nmodule_isLSemiModule R W & isSubLSemiModule R V S W}.
Section linear.
Context (R : pzSemiRingType) (V : lSemiModType R).
Context (S : pred V) (W : subLSemiModType S).
Notation val := (val : W -> V).
#[export]
HB.instance Definition _ := isScalable.Build R W V *:%R val valZ.
End linear.
HB.factory Record isSubLmodule (R : pzRingType) (V : lmodType R) (S : pred V)
W of SubZmodule V S W & Lmodule R W := {
valZ : scalable (val : W -> V);
}.
HB.builders Context (R : pzRingType) (V : lmodType R) S W of
isSubLmodule R V S W.
HB.instance Definition _ := isSubLSemiModule.Build R V S W valZ.
HB.end.
HB.factory Record SubNmodule_isSubLSemiModule
(R : pzSemiRingType) (V : lSemiModType R) S W of SubNmodule V S W := {
submod_closed_subproof : subsemimod_closed S
}.
HB.builders Context (R : pzSemiRingType) (V : lSemiModType R) S W
of SubNmodule_isSubLSemiModule R V S W.
HB.instance Definition _ :=
isSubSemiModClosed.Build R V S submod_closed_subproof.
Let inW v Sv : W := Sub v Sv.
Let scaleW a (w : W) := inW (rpredZ a _ (valP w)).
Lemma scalerA' a b v : scaleW a (scaleW b v) = scaleW (a * b) v.
Proof. by apply: val_inj; rewrite !SubK scalerA. Qed.
Lemma scale0r v : scaleW 0 v = 0.
Proof. by apply: val_inj; rewrite SubK scale0r raddf0. Qed.
Lemma scale1r : left_id 1 scaleW.
Proof. by move=> x; apply: val_inj; rewrite SubK scale1r. Qed.
Lemma scalerDr : right_distributive scaleW +%R.
Proof.
by move=> a u v; apply: val_inj; rewrite !(SubK, raddfD)/= !SubK.
Qed.
Lemma scalerDl v : {morph scaleW^~ v : a b / a + b}.
Proof.
by move=> a b; apply: val_inj; rewrite !(SubK, raddfD)/= !SubK scalerDl.
Qed.
HB.instance Definition _ := Nmodule_isLSemiModule.Build R W
scalerA' scale0r scale1r scalerDr scalerDl.
Fact valZ : scalable (val : W -> _). Proof. by move=> k w; rewrite SubK. Qed.
HB.instance Definition _ := isSubLSemiModule.Build R V S W valZ.
HB.end.
HB.factory Record SubZmodule_isSubLmodule (R : pzRingType) (V : lmodType R) S W
of SubZmodule V S W := {
submod_closed_subproof : submod_closed S
}.
HB.builders Context (R : pzRingType) (V : lmodType R) S W
of SubZmodule_isSubLmodule R V S W.
HB.instance Definition _ := SubNmodule_isSubLSemiModule.Build R V S W
(submod_closed_semi submod_closed_subproof).
HB.end.
#[short(type="subLSemiAlgType")]
HB.structure Definition SubLSemiAlgebra
(R : pzSemiRingType) (V : lSemiAlgType R) S :=
{W of SubNzSemiRing V S W & @SubLSemiModule R V S W & LSemiAlgebra R W}.
#[short(type="subLalgType")]
HB.structure Definition SubLalgebra (R : pzRingType) (V : lalgType R) S :=
{W of SubNzRing V S W & @SubLmodule R V S W & Lalgebra R W}.
HB.factory Record SubNzSemiRing_SubLSemiModule_isSubLSemiAlgebra
(R : pzSemiRingType) (V : lSemiAlgType R) S W
of SubNzSemiRing V S W & @SubLSemiModule R V S W := {}.
HB.builders Context (R : pzSemiRingType) (V : lSemiAlgType R) S W
of SubNzSemiRing_SubLSemiModule_isSubLSemiAlgebra R V S W.
Lemma scalerAl (a : R) (u v : W) : a *: (u * v) = a *: u * v.
Proof. by apply: val_inj; rewrite !(linearZ, rmorphM) /= linearZ scalerAl. Qed.
HB.instance Definition _ := LSemiModule_isLSemiAlgebra.Build R W scalerAl.
HB.end.
HB.factory Record SubNzRing_SubLmodule_isSubLalgebra (R : pzRingType)
(V : lalgType R) S W of SubNzRing V S W & @SubLmodule R V S W := {}.
Module SubRing_SubLmodule_isSubLalgebra.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzRing_SubLmodule_isSubLalgebra.Build instead.")]
Notation Build R V S U :=
(SubNzRing_SubLmodule_isSubLalgebra.Build R V S U) (only parsing).
End SubRing_SubLmodule_isSubLalgebra.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubNzRing_SubLmodule_isSubLalgebra instead.")]
Notation SubRing_SubLmodule_isSubLalgebra R V S U :=
(SubNzRing_SubLmodule_isSubLalgebra R V S U) (only parsing).
HB.builders Context (R : pzRingType) (V : lalgType R) S W
of SubNzRing_SubLmodule_isSubLalgebra R V S W.
HB.instance Definition _ :=
SubNzSemiRing_SubLSemiModule_isSubLSemiAlgebra.Build R V S W.
HB.end.
#[short(type="subSemiAlgType")]
HB.structure Definition SubSemiAlgebra (R : pzSemiRingType) (V : semiAlgType R)
S :=
{W of @SubLSemiAlgebra R V S W & SemiAlgebra R W}.
#[short(type="subAlgType")]
HB.structure Definition SubAlgebra (R : pzRingType) (V : algType R) S :=
{W of @SubLalgebra R V S W & Algebra R W}.
HB.factory Record SubLSemiAlgebra_isSubSemiAlgebra (R : pzSemiRingType)
(V : semiAlgType R) S W of @SubLSemiAlgebra R V S W := {}.
HB.builders Context (R : pzSemiRingType) (V : semiAlgType R) S W
of SubLSemiAlgebra_isSubSemiAlgebra R V S W.
Lemma scalerAr (k : R) (x y : W) : k *: (x * y) = x * (k *: y).
Proof. by apply: val_inj; rewrite !(linearZ, rmorphM)/= linearZ scalerAr. Qed.
HB.instance Definition _ := LSemiAlgebra_isSemiAlgebra.Build R W scalerAr.
HB.end.
HB.factory Record SubLalgebra_isSubAlgebra (R : pzRingType)
(V : algType R) S W of @SubLalgebra R V S W := {}.
HB.builders Context (R : pzRingType) (V : algType R) S W
of SubLalgebra_isSubAlgebra R V S W.
HB.instance Definition _ := SubLSemiAlgebra_isSubSemiAlgebra.Build R V S W.
HB.end.
#[short(type="subUnitRingType")]
HB.structure Definition SubUnitRing (R : nzRingType) (S : pred R) :=
{U of SubNzRing R S U & UnitRing U}.
HB.factory Record SubNzRing_isSubUnitRing (R : unitRingType) S U
of SubNzRing R S U := {
divring_closed_subproof : divring_closed S
}.
HB.builders Context (R : unitRingType) S U of SubNzRing_isSubUnitRing R S U.
HB.instance Definition _ := isDivringClosed.Build R S divring_closed_subproof.
Let inU v Sv : U := Sub v Sv.
Let invU (u : U) := inU (rpredVr _ (valP u)).
Lemma mulVr : {in [pred x | val x \is a unit], left_inverse 1 invU *%R}.
Proof.
by move=> x /[!inE] xu; apply: val_inj; rewrite rmorphM rmorph1 /= SubK mulVr.
Qed.
Lemma divrr : {in [pred x | val x \is a unit], right_inverse 1 invU *%R}.
by move=> x /[!inE] xu; apply: val_inj; rewrite rmorphM rmorph1 /= SubK mulrV.
Qed.
Lemma unitrP (x y : U) : y * x = 1 /\ x * y = 1 -> val x \is a unit.
Proof.
move=> -[/(congr1 val) yx1 /(congr1 val) xy1].
by apply: rev_unitrP (val y) _; rewrite !rmorphM rmorph1 /= in yx1 xy1.
Qed.
Lemma invr_out : {in [pred x | val x \isn't a unit], invU =1 id}.
Proof.
by move=> x /[!inE] xNU; apply: val_inj; rewrite SubK invr_out.
Qed.
HB.instance Definition _ := NzRing_hasMulInverse.Build U
mulVr divrr unitrP invr_out.
HB.end.
#[short(type="subComUnitRingType")]
HB.structure Definition SubComUnitRing (R : comUnitRingType) (S : pred R) :=
{U of SubComNzRing R S U & SubUnitRing R S U}.
#[short(type="subIdomainType")]
HB.structure Definition SubIntegralDomain (R : idomainType) (S : pred R) :=
{U of SubComNzRing R S U & IntegralDomain U}.
HB.factory Record SubComUnitRing_isSubIntegralDomain (R : idomainType) S U
of SubComUnitRing R S U := {}.
HB.builders Context (R : idomainType) S U
of SubComUnitRing_isSubIntegralDomain R S U.
Lemma id : IntegralDomain.axiom U.
Proof.
move=> x y /(congr1 val)/eqP; rewrite rmorphM /=.
by rewrite -!(inj_eq val_inj) rmorph0 -mulf_eq0.
Qed.
HB.instance Definition _ := ComUnitRing_isIntegral.Build U id.
HB.end.
#[short(type="subFieldType")]
HB.structure Definition SubField (F : fieldType) (S : pred F) :=
{U of SubIntegralDomain F S U & Field U}.
HB.factory Record SubIntegralDomain_isSubField (F : fieldType) S U
of SubIntegralDomain F S U := {
subfield_subproof : {mono (val : U -> F) : u / u \in unit}
}.
HB.builders Context (F : fieldType) S U of SubIntegralDomain_isSubField F S U.
Lemma fieldP : Field.axiom U.
Proof.
by move=> u; rewrite -(inj_eq val_inj) rmorph0 -unitfE subfield_subproof.
Qed.
HB.instance Definition _ := UnitRing_isField.Build U fieldP.
HB.end.
HB.factory Record SubChoice_isSubPzSemiRing (R : pzSemiRingType) S U
of SubChoice R S U := {
semiring_closed_subproof : semiring_closed S
}.
HB.builders Context (R : pzSemiRingType) S U of SubChoice_isSubPzSemiRing R S U.
HB.instance Definition _ := SubChoice_isSubNmodule.Build R S U
(semiring_closedD semiring_closed_subproof).
HB.instance Definition _ := SubNmodule_isSubPzSemiRing.Build R S U
(semiring_closedM semiring_closed_subproof).
HB.end.
HB.factory Record SubChoice_isSubNzSemiRing (R : nzSemiRingType) S U
of SubChoice R S U := {
semiring_closed_subproof : semiring_closed S
}.
Module SubChoice_isSubSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubChoice_isSubNzSemiRing.Build instead.")]
Notation Build R S U := (SubChoice_isSubNzSemiRing.Build R S U) (only parsing).
End SubChoice_isSubSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubChoice_isSubNzSemiRing instead.")]
Notation SubChoice_isSubSemiRing R S U :=
(SubChoice_isSubNzSemiRing R S U) (only parsing).
HB.builders Context (R : nzSemiRingType) S U of SubChoice_isSubNzSemiRing R S U.
HB.instance Definition _ := SubChoice_isSubNmodule.Build R S U
(semiring_closedD semiring_closed_subproof).
HB.instance Definition _ := SubNmodule_isSubNzSemiRing.Build R S U
(semiring_closedM semiring_closed_subproof).
HB.end.
HB.factory Record SubChoice_isSubComPzSemiRing (R : comPzSemiRingType) S U
of SubChoice R S U := {
semiring_closed_subproof : semiring_closed S
}.
HB.builders Context (R : comPzSemiRingType) S U
of SubChoice_isSubComPzSemiRing R S U.
HB.instance Definition _ := SubChoice_isSubPzSemiRing.Build R S U
semiring_closed_subproof.
HB.instance Definition _ := SubPzSemiRing_isSubComPzSemiRing.Build R S U.
HB.end.
HB.factory Record SubChoice_isSubComNzSemiRing (R : comNzSemiRingType) S U
of SubChoice R S U := {
semiring_closed_subproof : semiring_closed S
}.
Module SubChoice_isSubComSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubChoice_isSubComNzSemiRing.Build instead.")]
Notation Build R S U :=
(SubChoice_isSubComNzSemiRing.Build R S U) (only parsing).
End SubChoice_isSubComSemiRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubChoice_isSubComNzSemiRing instead.")]
Notation SubChoice_isSubComSemiRing R S U :=
(SubChoice_isSubComNzSemiRing R S U) (only parsing).
HB.builders Context (R : comNzSemiRingType) S U
of SubChoice_isSubComNzSemiRing R S U.
HB.instance Definition _ := SubChoice_isSubNzSemiRing.Build R S U
semiring_closed_subproof.
HB.instance Definition _ := SubNzSemiRing_isSubComNzSemiRing.Build R S U.
HB.end.
HB.factory Record SubChoice_isSubPzRing (R : pzRingType) S U of SubChoice R S U := {
subring_closed_subproof : subring_closed S
}.
HB.builders Context (R : pzRingType) S U of SubChoice_isSubPzRing R S U.
HB.instance Definition _ := SubChoice_isSubZmodule.Build R S U
(subring_closedB subring_closed_subproof).
HB.instance Definition _ := SubZmodule_isSubPzRing.Build R S U
subring_closed_subproof.
HB.end.
HB.factory Record SubChoice_isSubNzRing (R : nzRingType) S U of SubChoice R S U := {
subring_closed_subproof : subring_closed S
}.
Module SubChoice_isSubRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubChoice_isSubNzRing.Build instead.")]
Notation Build R S U := (SubChoice_isSubNzRing.Build R S U) (only parsing).
End SubChoice_isSubRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubChoice_isSubNzRing instead.")]
Notation SubChoice_isSubRing R S U :=
(SubChoice_isSubNzRing R S U) (only parsing).
HB.builders Context (R : nzRingType) S U of SubChoice_isSubNzRing R S U.
HB.instance Definition _ := SubChoice_isSubZmodule.Build R S U
(subring_closedB subring_closed_subproof).
HB.instance Definition _ := SubZmodule_isSubNzRing.Build R S U
subring_closed_subproof.
HB.end.
HB.factory Record SubChoice_isSubComPzRing (R : comPzRingType) S U
of SubChoice R S U := {
subring_closed_subproof : subring_closed S
}.
HB.builders Context (R : comPzRingType) S U of SubChoice_isSubComPzRing R S U.
HB.instance Definition _ := SubChoice_isSubPzRing.Build R S U
subring_closed_subproof.
HB.instance Definition _ := SubPzRing_isSubComPzRing.Build R S U.
HB.end.
HB.factory Record SubChoice_isSubComNzRing (R : comNzRingType) S U
of SubChoice R S U := {
subring_closed_subproof : subring_closed S
}.
Module SubChoice_isSubComRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubChoice_isSubComNzRing.Build instead.")]
Notation Build R S U := (SubChoice_isSubComNzRing.Build R S U) (only parsing).
End SubChoice_isSubComRing.
#[deprecated(since="mathcomp 2.4.0",
note="Use SubChoice_isSubComNzRing instead.")]
Notation SubChoice_isSubComRing R S U :=
(SubChoice_isSubComNzRing R S U) (only parsing).
HB.builders Context (R : comNzRingType) S U of SubChoice_isSubComNzRing R S U.
HB.instance Definition _ := SubChoice_isSubNzRing.Build R S U
subring_closed_subproof.
HB.instance Definition _ := SubNzRing_isSubComNzRing.Build R S U.
HB.end.
HB.factory Record SubChoice_isSubLSemiModule
(R : pzSemiRingType) (V : lSemiModType R) S W of SubChoice V S W := {
subsemimod_closed_subproof : subsemimod_closed S
}.
HB.builders Context (R : pzSemiRingType) (V : lSemiModType R) S W
of SubChoice_isSubLSemiModule R V S W.
HB.instance Definition _ := SubChoice_isSubNmodule.Build V S W
(subsemimod_closedD subsemimod_closed_subproof).
HB.instance Definition _ := SubNmodule_isSubLSemiModule.Build R V S W
subsemimod_closed_subproof.
HB.end.
HB.factory Record SubChoice_isSubLmodule (R : pzRingType) (V : lmodType R) S W
of SubChoice V S W := {
submod_closed_subproof : submod_closed S
}.
HB.builders Context (R : pzRingType) (V : lmodType R) S W
of SubChoice_isSubLmodule R V S W.
HB.instance Definition _ := SubChoice_isSubZmodule.Build V S W
(submod_closedB submod_closed_subproof).
HB.instance Definition _ := SubZmodule_isSubLmodule.Build R V S W
submod_closed_subproof.
HB.end.
(* TODO: SubChoice_isSubLSemiAlgebra? *)
HB.factory Record SubChoice_isSubLalgebra (R : pzRingType) (A : lalgType R) S W
of SubChoice A S W := {
subalg_closed_subproof : subalg_closed S
}.
HB.builders Context (R : pzRingType) (A : lalgType R) S W
of SubChoice_isSubLalgebra R A S W.
HB.instance Definition _ := SubChoice_isSubNzRing.Build A S W
(subalg_closedBM subalg_closed_subproof).
HB.instance Definition _ := SubZmodule_isSubLmodule.Build R A S W
(subalg_closedZ subalg_closed_subproof).
HB.instance Definition _ := SubNzRing_SubLmodule_isSubLalgebra.Build R A S W.
HB.end.
(* TODO: SubChoice_isSubSemiAlgebra? *)
HB.factory Record SubChoice_isSubAlgebra (R : pzRingType) (A : algType R) S W
of SubChoice A S W := {
subalg_closed_subproof : subalg_closed S
}.
HB.builders Context (R : pzRingType) (A : algType R) S W
of SubChoice_isSubAlgebra R A S W.
HB.instance Definition _ := SubChoice_isSubLalgebra.Build R A S W
subalg_closed_subproof.
HB.instance Definition _ := SubLalgebra_isSubAlgebra.Build R A S W.
HB.end.
HB.factory Record SubChoice_isSubUnitRing (R : unitRingType) S U
of SubChoice R S U := {
divring_closed_subproof : divring_closed S
}.
HB.builders Context (R : unitRingType) S U of SubChoice_isSubUnitRing R S U.
HB.instance Definition _ := SubChoice_isSubNzRing.Build R S U
(divring_closedBM divring_closed_subproof).
HB.instance Definition _ := SubNzRing_isSubUnitRing.Build R S U
divring_closed_subproof.
HB.end.
HB.factory Record SubChoice_isSubComUnitRing (R : comUnitRingType) S U
of SubChoice R S U := {
divring_closed_subproof : divring_closed S
}.
HB.builders Context (R : comUnitRingType) S U
of SubChoice_isSubComUnitRing R S U.
HB.instance Definition _ := SubChoice_isSubComNzRing.Build R S U
(divring_closedBM divring_closed_subproof).
HB.instance Definition _ := SubNzRing_isSubUnitRing.Build R S U
divring_closed_subproof.
HB.end.
HB.factory Record SubChoice_isSubIntegralDomain (R : idomainType) S U
of SubChoice R S U := {
divring_closed_subproof : divring_closed S
}.
HB.builders Context (R : idomainType) S U
of SubChoice_isSubIntegralDomain R S U.
HB.instance Definition _ := SubChoice_isSubComUnitRing.Build R S U
divring_closed_subproof.
HB.instance Definition _ := SubComUnitRing_isSubIntegralDomain.Build R S U.
HB.end.
Module SubExports.
Notation "[ 'SubChoice_isSubNmodule' 'of' U 'by' <: ]" :=
(SubChoice_isSubNmodule.Build _ _ U rpred0D)
(format "[ 'SubChoice_isSubNmodule' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubZmodule' 'of' U 'by' <: ]" :=
(SubChoice_isSubZmodule.Build _ _ U (zmodClosedP _))
(format "[ 'SubChoice_isSubZmodule' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubNmodule_isSubNzSemiRing' 'of' U 'by' <: ]" :=
(SubNmodule_isSubNzSemiRing.Build _ _ U (@rpred1M _ _))
(format "[ 'SubNmodule_isSubNzSemiRing' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ SubNmodule_isSubNzSemiRing of U by <: ] instead.")]
Notation "[ 'SubNmodule_isSubSemiRing' 'of' U 'by' <: ]" :=
(SubNmodule_isSubNzSemiRing.Build _ _ U (@rpred1M _ _))
(format "[ 'SubNmodule_isSubSemiRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubNzSemiRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubNzSemiRing.Build _ _ U (semiringClosedP _))
(format "[ 'SubChoice_isSubNzSemiRing' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ 'SubChoice_isSubNzSemiRing' of U by <: ] instead.")]
Notation "[ 'SubChoice_isSubSemiRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubNzSemiRing.Build _ _ U (semiringClosedP _))
(format "[ 'SubChoice_isSubSemiRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubNzSemiRing_isSubComNzSemiRing' 'of' U 'by' <: ]" :=
(SubNzSemiRing_isSubComNzSemiRing.Build _ _ U)
(format "[ 'SubNzSemiRing_isSubComNzSemiRing' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ 'SubNzSemiRing_isSubComNzSemiRing' of U by <: ] instead.")]
Notation "[ 'SubSemiRing_isSubComSemiRing' 'of' U 'by' <: ]" :=
(SubNzSemiRing_isSubComNzSemiRing.Build _ _ U)
(format "[ 'SubSemiRing_isSubComSemiRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubComNzSemiRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubComNzSemiRing.Build _ _ U (semiringClosedP _))
(format "[ 'SubChoice_isSubComNzSemiRing' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ 'SubChoice_isSubComNzSemiRing' of U by <: ] instead.")]
Notation "[ 'SubChoice_isSubComSemiRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubComNzSemiRing.Build _ _ U (semiringClosedP _))
(format "[ 'SubChoice_isSubComSemiRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubZmodule_isSubNzRing' 'of' U 'by' <: ]" :=
(SubZmodule_isSubNzRing.Build _ _ U (subringClosedP _))
(format "[ 'SubZmodule_isSubNzRing' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ 'SubZmodule_isSubNzRing' of U by <: ] instead.")]
Notation "[ 'SubZmodule_isSubRing' 'of' U 'by' <: ]" :=
(SubZmodule_isSubNzRing.Build _ _ U (subringClosedP _))
(format "[ 'SubZmodule_isSubRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubNzRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubNzRing.Build _ _ U (subringClosedP _))
(format "[ 'SubChoice_isSubNzRing' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ 'SubChoice_isSubNzRing' of U by <: ] instead.")]
Notation "[ 'SubChoice_isSubRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubNzRing.Build _ _ U (subringClosedP _))
(format "[ 'SubChoice_isSubRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubNzRing_isSubComNzRing' 'of' U 'by' <: ]" :=
(SubNzRing_isSubComNzRing.Build _ _ U)
(format "[ 'SubNzRing_isSubComNzRing' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ 'SubNzRing_isSubComNzRing' of U by <: ] instead.")]
Notation "[ 'SubRing_isSubComRing' 'of' U 'by' <: ]" :=
(SubNzRing_isSubComNzRing.Build _ _ U)
(format "[ 'SubRing_isSubComRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubComNzRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubComNzRing.Build _ _ U (subringClosedP _))
(format "[ 'SubChoice_isSubComNzRing' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ 'SubChoice_isSubComNzRing' of U by <: ] instead.")]
Notation "[ 'SubChoice_isSubComRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubComNzRing.Build _ _ U (subringClosedP _))
(format "[ 'SubChoice_isSubComRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubNmodule_isSubLSemiModule' 'of' U 'by' <: ]" :=
(SubNmodule_isSubLSemiModule.Build _ _ _ U (subsemimodClosedP _))
(format "[ 'SubNmodule_isSubLSemiModule' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubLSemiModule' 'of' U 'by' <: ]" :=
(SubChoice_isSubLSemiModule.Build _ _ _ U (subsemimodClosedP _))
(format "[ 'SubChoice_isSubLSemiModule' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubZmodule_isSubLmodule' 'of' U 'by' <: ]" :=
(SubZmodule_isSubLmodule.Build _ _ _ U (submodClosedP _))
(format "[ 'SubZmodule_isSubLmodule' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubLmodule' 'of' U 'by' <: ]" :=
(SubChoice_isSubLmodule.Build _ _ _ U (submodClosedP _))
(format "[ 'SubChoice_isSubLmodule' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubNzSemiRing_SubLSemiModule_isSubLSemiAlgebra' 'of' U 'by' <: ]" :=
(SubNzSemiRing_SubLSemiModule_isSubLSemiAlgebra.Build _ _ _ U)
(format "[ 'SubNzSemiRing_SubLSemiModule_isSubLSemiAlgebra' 'of' U 'by' <: ]")
: form_scope.
(* TODO: SubChoice_isSubLSemiAlgebra? *)
Notation "[ 'SubNzRing_SubLmodule_isSubLalgebra' 'of' U 'by' <: ]" :=
(SubNzRing_SubLmodule_isSubLalgebra.Build _ _ _ U)
(format "[ 'SubNzRing_SubLmodule_isSubLalgebra' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ 'SubNzRing_SubLmodule_isSubLalgebra' of U by <: ] instead.")]
Notation "[ 'SubRing_SubLmodule_isSubLalgebra' 'of' U 'by' <: ]" :=
(SubNzRing_SubLmodule_isSubLalgebra.Build _ _ _ U)
(format "[ 'SubRing_SubLmodule_isSubLalgebra' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubLalgebra' 'of' U 'by' <: ]" :=
(SubChoice_isSubLalgebra.Build _ _ _ U (subalgClosedP _))
(format "[ 'SubChoice_isSubLalgebra' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubLSemiAlgebra_isSubSemiAlgebra' 'of' U 'by' <: ]" :=
(SubLSemiAlgebra_isSubSemiAlgebra.Build _ _ _ U)
(format "[ 'SubLSemiAlgebra_isSubSemiAlgebra' 'of' U 'by' <: ]")
: form_scope.
(* TODO: SubChoice_isSubSemiAlgebra? *)
Notation "[ 'SubLalgebra_isSubAlgebra' 'of' U 'by' <: ]" :=
(SubLalgebra_isSubAlgebra.Build _ _ _ U)
(format "[ 'SubLalgebra_isSubAlgebra' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubAlgebra' 'of' U 'by' <: ]" :=
(SubChoice_isSubAlgebra.Build _ _ _ U (subalgClosedP _))
(format "[ 'SubChoice_isSubAlgebra' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubNzRing_isSubUnitRing' 'of' U 'by' <: ]" :=
(SubNzRing_isSubUnitRing.Build _ _ U (divringClosedP _))
(format "[ 'SubNzRing_isSubUnitRing' 'of' U 'by' <: ]")
: form_scope.
#[deprecated(since="mathcomp 2.4.0",
note="Use [ 'SubNzRing_isSubUnitRing' of U by <: ] instead.")]
Notation "[ 'SubRing_isSubUnitRing' 'of' U 'by' <: ]" :=
(SubNzRing_isSubUnitRing.Build _ _ U (divringClosedP _))
(format "[ 'SubRing_isSubUnitRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubUnitRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubUnitRing.Build _ _ U (divringClosedP _))
(format "[ 'SubChoice_isSubUnitRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubComUnitRing' 'of' U 'by' <: ]" :=
(SubChoice_isSubComUnitRing.Build _ _ U (divringClosedP _))
(format "[ 'SubChoice_isSubComUnitRing' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubComUnitRing_isSubIntegralDomain' 'of' U 'by' <: ]" :=
(SubComUnitRing_isSubIntegralDomain.Build _ _ U)
(format "[ 'SubComUnitRing_isSubIntegralDomain' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubChoice_isSubIntegralDomain' 'of' U 'by' <: ]" :=
(SubChoice_isSubIntegralDomain.Build _ _ U (divringClosedP _))
(format "[ 'SubChoice_isSubIntegralDomain' 'of' U 'by' <: ]")
: form_scope.
Notation "[ 'SubIntegralDomain_isSubField' 'of' U 'by' <: ]" :=
(SubIntegralDomain_isSubField.Build _ _ U (frefl _))
(format "[ 'SubIntegralDomain_isSubField' 'of' U 'by' <: ]")
: form_scope.
End SubExports.
HB.export SubExports.
Module Theory.
Definition addrA := @addrA.
Definition addrC := @addrC.
Definition add0r := @add0r.
Definition addNr := @addNr.
Definition addr0 := addr0.
Definition addrN := addrN.
Definition subrr := subrr.
Definition addrCA := addrCA.
Definition addrAC := addrAC.
Definition addrACA := addrACA.
Definition addKr := addKr.
Definition addNKr := addNKr.
Definition addrK := addrK.
Definition addrNK := addrNK.
Definition subrK := subrK.
Definition subKr := subKr.
Definition addrI := @addrI.
Definition addIr := @addIr.
Definition subrI := @subrI.
Definition subIr := @subIr.
Arguments addrI {V} y [x1 x2].
Arguments addIr {V} x [x1 x2].
Arguments subrI {V} y [x1 x2].
Arguments subIr {V} x [x1 x2].
Definition opprK := @opprK.
Arguments opprK {V}.
Definition oppr_inj := @oppr_inj.
Arguments oppr_inj {V} [x1 x2].
Definition oppr0 := oppr0.
Definition oppr_eq0 := oppr_eq0.
Definition opprD := opprD.
Definition opprB := opprB.
Definition addrKA := addrKA.
Definition subrKA := subrKA.
Definition subr0 := subr0.
Definition sub0r := sub0r.
Definition subr_eq := subr_eq.
Definition addr0_eq := addr0_eq.
Definition subr0_eq := subr0_eq.
Definition subr_eq0 := subr_eq0.
Definition addr_eq0 := addr_eq0.
Definition eqr_opp := eqr_opp.
Definition eqr_oppLR := eqr_oppLR.
Definition sumrN := sumrN.
Definition sumrB := sumrB.
Definition sumrMnl := sumrMnl.
Definition sumrMnr := sumrMnr.
Definition sumr_const := sumr_const.
Definition sumr_const_nat := sumr_const_nat.
Definition telescope_sumr := telescope_sumr.
Definition telescope_sumr_eq := @telescope_sumr_eq.
Arguments telescope_sumr_eq {V n m} f u.
Definition mulr0n := mulr0n.
Definition mulr1n := mulr1n.
Definition mulr2n := mulr2n.
Definition mulrS := mulrS.
Definition mulrSr := mulrSr.
Definition mulrb := mulrb.
Definition mul0rn := mul0rn.
Definition mulNrn := mulNrn.
Definition mulrnDl := mulrnDl.
Definition mulrnDr := mulrnDr.
Definition mulrnBl := mulrnBl.
Definition mulrnBr := mulrnBr.
Definition mulrnA := mulrnA.
Definition mulrnAC := mulrnAC.
Definition iter_addr := iter_addr.
Definition iter_addr_0 := iter_addr_0.
Definition mulrA := @mulrA.
Definition mul1r := @mul1r.
Definition mulr1 := @mulr1.
Definition mulrDl := @mulrDl.
Definition mulrDr := @mulrDr.
Definition oner_neq0 := @oner_neq0.
Definition oner_eq0 := oner_eq0.
Definition mul0r := @mul0r.
Definition mulr0 := @mulr0.
Definition mulrN := mulrN.
Definition mulNr := mulNr.
Definition mulrNN := mulrNN.
Definition mulN1r := mulN1r.
Definition mulrN1 := mulrN1.
Definition mulr_suml := mulr_suml.
Definition mulr_sumr := mulr_sumr.
Definition mulrBl := mulrBl.
Definition mulrBr := mulrBr.
Definition mulrnAl := mulrnAl.
Definition mulrnAr := mulrnAr.
Definition mulr_natl := mulr_natl.
Definition mulr_natr := mulr_natr.
Definition natrD := natrD.
Definition nat1r := nat1r.
Definition natr1 := natr1.
Arguments natr1 {R} n.
Arguments nat1r {R} n.
Definition natrB := natrB.
Definition natr_sum := natr_sum.
Definition natrM := natrM.
Definition natrX := natrX.
Definition expr0 := expr0.
Definition exprS := exprS.
Definition expr1 := expr1.
Definition expr2 := expr2.
Definition expr0n := expr0n.
Definition expr1n := expr1n.
Definition exprD := exprD.
Definition exprSr := exprSr.
Definition expr_sum := expr_sum.
Definition commr_sym := commr_sym.
Definition commr_refl := commr_refl.
Definition commr0 := commr0.
Definition commr1 := commr1.
Definition commrN := commrN.
Definition commrN1 := commrN1.
Definition commrD := commrD.
Definition commrB := commrB.
Definition commr_sum := commr_sum.
Definition commr_prod := commr_prod.
Definition commrMn := commrMn.
Definition commrM := commrM.
Definition commr_nat := commr_nat.
Definition commrX := commrX.
Definition exprMn_comm := exprMn_comm.
Definition commr_sign := commr_sign.
Definition exprMn_n := exprMn_n.
Definition exprM := exprM.
Definition exprAC := exprAC.
Definition expr_mod := expr_mod.
Definition expr_dvd := expr_dvd.
Definition signr_odd := signr_odd.
Definition signr_eq0 := signr_eq0.
Definition mulr_sign := mulr_sign.
Definition signr_addb := signr_addb.
Definition signrN := signrN.
Definition signrE := signrE.
Definition mulr_signM := mulr_signM.
Definition exprNn := exprNn.
Definition sqrrN := sqrrN.
Definition sqrr_sign := sqrr_sign.
Definition signrMK := signrMK.
Definition mulrI_eq0 := mulrI_eq0.
Definition lreg_neq0 := lreg_neq0.
Definition mulrI0_lreg := mulrI0_lreg.
Definition lregN := lregN.
Definition lreg1 := lreg1.
Definition lregM := lregM.
Definition lregX := lregX.
Definition lreg_sign := lreg_sign.
Definition lregP {R x} := @lregP R x.
Definition mulIr_eq0 := mulIr_eq0.
Definition mulIr0_rreg := mulIr0_rreg.
Definition rreg_neq0 := rreg_neq0.
Definition rregN := rregN.
Definition rreg1 := rreg1.
Definition rregM := rregM.
Definition revrX := revrX.
Definition rregX := rregX.
Definition rregP {R x} := @rregP R x.
Definition exprDn_comm := exprDn_comm.
Definition exprBn_comm := exprBn_comm.
Definition subrXX_comm := subrXX_comm.
Definition exprD1n := exprD1n.
Definition subrX1 := subrX1.
Definition sqrrD1 := sqrrD1.
Definition sqrrB1 := sqrrB1.
Definition subr_sqr_1 := subr_sqr_1.
Definition pcharf0 := pcharf0.
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf0 instead.")]
Definition charf0 := pcharf0.
Definition pcharf_prime := pcharf_prime.
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf_prime instead.")]
Definition charf_prime := pcharf_prime.
Definition mulrn_pchar := mulrn_pchar.
#[deprecated(since="mathcomp 2.4.0", note="Use mulrn_pchar instead.")]
Definition mulrn_char := mulrn_pchar.
Definition dvdn_pcharf := dvdn_pcharf.
#[deprecated(since="mathcomp 2.4.0", note="Use dvdn_pcharf instead.")]
Definition dvdn_charf := dvdn_pcharf.
Definition pcharf_eq := pcharf_eq.
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf_eq instead.")]
Definition charf_eq := pcharf_eq.
Definition bin_lt_pcharf_0 := bin_lt_pcharf_0.
#[deprecated(since="mathcomp 2.4.0", note="Use bin_lt_pcharf_0 instead.")]
Definition bin_lt_charf_0 := bin_lt_pcharf_0.
Definition pFrobenius_autE := pFrobenius_autE.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autE instead.")]
Definition Frobenius_autE := pFrobenius_autE.
Definition pFrobenius_aut0 := pFrobenius_aut0.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_aut0 instead.")]
Definition Frobenius_aut0 := pFrobenius_aut0.
Definition pFrobenius_aut1 := pFrobenius_aut1.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_aut1 instead.")]
Definition Frobenius_aut1 := pFrobenius_aut1.
Definition pFrobenius_autD_comm := pFrobenius_autD_comm.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autD_comm instead.")]
Definition Frobenius_autD_comm := pFrobenius_autD_comm.
Definition pFrobenius_autMn := pFrobenius_autMn.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autMn instead.")]
Definition Frobenius_autMn := pFrobenius_autMn.
Definition pFrobenius_aut_nat := pFrobenius_aut_nat.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_aut_nat instead.")]
Definition Frobenius_aut_nat := pFrobenius_aut_nat.
Definition pFrobenius_autM_comm := pFrobenius_autM_comm.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autM_comm instead.")]
Definition Frobenius_autM_comm := pFrobenius_autM_comm.
Definition pFrobenius_autX := pFrobenius_autX.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autX instead.")]
Definition Frobenius_autX := pFrobenius_autX.
Definition pFrobenius_autN := pFrobenius_autN.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autN instead.")]
Definition Frobenius_autN := pFrobenius_autN.
Definition pFrobenius_autB_comm := pFrobenius_autB_comm.
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_autB_comm instead.")]
Definition Frobenius_autB_comm := pFrobenius_autB_comm.
Definition exprNn_pchar := exprNn_pchar.
#[deprecated(since="mathcomp 2.4.0", note="Use exprNn_pchar instead.")]
Definition exprNn_char := exprNn_pchar.
Definition addrr_pchar2 := addrr_pchar2.
#[deprecated(since="mathcomp 2.4.0", note="Use addrr_pchar2 instead.")]
Definition addrr_char2 := addrr_pchar2.
Definition oppr_pchar2 := oppr_pchar2.
#[deprecated(since="mathcomp 2.4.0", note="Use oppr_pchar2 instead.")]
Definition oppr_char2 := oppr_pchar2.
Definition addrK_pchar2 := addrK_pchar2.
#[deprecated(since="mathcomp 2.4.0", note="Use addrK_pchar2 instead.")]
Definition addrK_char2 := addrK_pchar2.
Definition addKr_pchar2 := addKr_pchar2.
#[deprecated(since="mathcomp 2.4.0", note="Use addKr_pchar2 instead.")]
Definition addKr_char2 := addKr_pchar2.
Definition iter_mulr := iter_mulr.
Definition iter_mulr_1 := iter_mulr_1.
Definition prodr_const := prodr_const.
Definition prodr_const_nat := prodr_const_nat.
Definition mulrC := @mulrC.
Definition mulrCA := mulrCA.
Definition mulrAC := mulrAC.
Definition mulrACA := mulrACA.
Definition exprMn := exprMn.
Definition prodrXl := prodrXl.
Definition prodrXr := prodrXr.
Definition prodrN := prodrN.
Definition prodrMn_const := prodrMn_const.
Definition prodrM_comm := prodrM_comm.
Definition prodrMl_comm := prodrMl_comm.
Definition prodrMr_comm := prodrMr_comm.
Definition prodrMl := prodrMl.
Definition prodrMr := prodrMr.
Definition prodrMn := prodrMn.
Definition rev_prodr := rev_prodr.
Definition natr_prod := natr_prod.
Definition prodr_undup_exp_count := prodr_undup_exp_count.
Definition exprDn := exprDn.
Definition exprBn := exprBn.
Definition subrXX := subrXX.
Definition sqrrD := sqrrD.
Definition sqrrB := sqrrB.
Definition subr_sqr := subr_sqr.
Definition subr_sqrDB := subr_sqrDB.
Definition exprDn_pchar := exprDn_pchar.
#[deprecated(since="mathcomp 2.4.0", note="Use exprDn_pchar instead.")]
Definition exprDn_char := exprDn_pchar.
Definition mulrV := mulrV.
Definition divrr := divrr.
Definition mulVr := mulVr.
Definition invr_out := invr_out.
Definition unitrP {R x} := @unitrP R x.
Definition mulKr := mulKr.
Definition mulVKr := mulVKr.
Definition mulrK := mulrK.
Definition mulrVK := mulrVK.
Definition divrK := divrK.
Definition mulrI := mulrI.
Definition mulIr := mulIr.
Definition divrI := divrI.
Definition divIr := divIr.
Definition telescope_prodr := telescope_prodr.
Definition telescope_prodr_eq := @telescope_prodr_eq.
Arguments telescope_prodr_eq {R n m} f u.
Definition commrV := commrV.
Definition unitrE := unitrE.
Definition invrK := @invrK.
Arguments invrK {R}.
Definition invr_inj := @invr_inj.
Arguments invr_inj {R} [x1 x2].
Definition unitrV := unitrV.
Definition unitr1 := unitr1.
Definition invr1 := invr1.
Definition divr1 := divr1.
Definition div1r := div1r.
Definition natr_div := natr_div.
Definition unitr0 := unitr0.
Definition invr0 := invr0.
Definition unitrN1 := unitrN1.
Definition unitrN := unitrN.
Definition invrN1 := invrN1.
Definition invrN := invrN.
Definition divrNN := divrNN.
Definition divrN := divrN.
Definition invr_sign := invr_sign.
Definition unitrMl := unitrMl.
Definition unitrMr := unitrMr.
Definition invrM := invrM.
Definition unitr_prod := unitr_prod.
Definition unitr_prod_in := unitr_prod_in.
Definition invr_eq0 := invr_eq0.
Definition invr_eq1 := invr_eq1.
Definition invr_neq0 := invr_neq0.
Definition rev_unitrP := rev_unitrP.
Definition rev_prodrV := rev_prodrV.
Definition unitrM_comm := unitrM_comm.
Definition unitrX := unitrX.
Definition unitrX_pos := unitrX_pos.
Definition exprVn := exprVn.
Definition exprB := exprB.
Definition invr_signM := invr_signM.
Definition divr_signM := divr_signM.
Definition rpred0D := @rpred0D.
Definition rpred0 := rpred0.
Definition rpredD := rpredD.
Definition rpredNr := @rpredNr.
Definition rpred_sum := rpred_sum.
Definition rpredMn := rpredMn.
Definition rpredN := rpredN.
Definition rpredB := rpredB.
Definition rpredBC := rpredBC.
Definition rpredMNn := rpredMNn.
Definition rpredDr := rpredDr.
Definition rpredDl := rpredDl.
Definition rpredBr := rpredBr.
Definition rpredBl := rpredBl.
Definition zmodClosedP := zmodClosedP.
Definition rpredMsign := rpredMsign.
Definition rpred1M := @rpred1M.
Definition rpred1 := @rpred1.
Definition rpredM := @rpredM.
Definition rpred_prod := rpred_prod.
Definition rpredX := rpredX.
Definition rpred_nat := rpred_nat.
Definition rpredN1 := rpredN1.
Definition rpred_sign := rpred_sign.
Definition semiringClosedP := semiringClosedP.
Definition subringClosedP := subringClosedP.
Definition rpredZsign := rpredZsign.
Definition rpredZnat := rpredZnat.
Definition submodClosedP := submodClosedP.
Definition subalgClosedP := subalgClosedP.
Definition rpredZ := @rpredZ.
Definition rpredVr := @rpredVr.
Definition rpredV := rpredV.
Definition rpred_div := rpred_div.
Definition rpredXN := rpredXN.
Definition rpredZeq := rpredZeq.
Definition pchar_lalg := pchar_lalg.
#[deprecated(since="mathcomp 2.4.0", note="Use pchar_lalg instead.")]
Definition char_lalg := pchar_lalg.
Definition rpredMr := rpredMr.
Definition rpredMl := rpredMl.
Definition rpred_divr := rpred_divr.
Definition rpred_divl := rpred_divl.
Definition divringClosedP := divringClosedP.
Definition eq_eval := eq_eval.
Definition eval_tsubst := eval_tsubst.
Definition eq_holds := eq_holds.
Definition holds_fsubst := holds_fsubst.
Definition unitrM := unitrM.
Definition unitr_prodP := unitr_prodP.
Definition prodrV := prodrV.
Definition unitrPr {R x} := @unitrPr R x.
Definition expr_div_n := expr_div_n.
Definition mulr1_eq := mulr1_eq.
Definition divr1_eq := divr1_eq.
Definition divKr := divKr.
Definition mulf_eq0 := mulf_eq0.
Definition prodf_eq0 := prodf_eq0.
Definition prodf_seq_eq0 := prodf_seq_eq0.
Definition mulf_neq0 := mulf_neq0.
Definition prodf_neq0 := prodf_neq0.
Definition prodf_seq_neq0 := prodf_seq_neq0.
Definition expf_eq0 := expf_eq0.
Definition sqrf_eq0 := sqrf_eq0.
Definition expf_neq0 := expf_neq0.
Definition natf_neq0_pchar := natf_neq0_pchar.
#[deprecated(since="mathcomp 2.4.0", note="Use natf_neq0_pchar instead.")]
Definition natf_neq0 := natf_neq0_pchar.
Definition natf0_pchar := natf0_pchar.
#[deprecated(since="mathcomp 2.4.0", note="Use natf0_pchar instead.")]
Definition natf0_char := natf0_pchar.
Definition pcharf'_nat := pcharf'_nat.
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf'_nat instead.")]
Definition charf'_nat := pcharf'_nat.
Definition pcharf0P := pcharf0P.
#[deprecated(since="mathcomp 2.4.0", note="Use pcharf0P instead.")]
Definition charf0P := pcharf0P.
Definition eqf_sqr := eqf_sqr.
Definition mulfI := mulfI.
Definition mulIf := mulIf.
Definition divfI := divfI.
Definition divIf := divIf.
Definition sqrf_eq1 := sqrf_eq1.
Definition expfS_eq1 := expfS_eq1.
Definition fieldP := @fieldP.
Definition unitfE := unitfE.
Definition mulVf := mulVf.
Definition mulfV := mulfV.
Definition divff := divff.
Definition mulKf := mulKf.
Definition mulVKf := mulVKf.
Definition mulfK := mulfK.
Definition mulfVK := mulfVK.
Definition divfK := divfK.
Definition divKf := divKf.
Definition invfM := invfM.
Definition invf_div := invf_div.
Definition expfB_cond := expfB_cond.
Definition expfB := expfB.
Definition prodfV := prodfV.
Definition prodf_div := prodf_div.
Definition telescope_prodf := telescope_prodf.
Definition telescope_prodf_eq := @telescope_prodf_eq.
Arguments telescope_prodf_eq {F n m} f u.
Definition addf_div := addf_div.
Definition mulf_div := mulf_div.
Definition eqr_div := eqr_div.
Definition eqr_sum_div := eqr_sum_div.
Definition pchar0_natf_div := pchar0_natf_div.
#[deprecated(since="mathcomp 2.4.0", note="Use pchar0_natf_div instead.")]
Definition char0_natf_div := pchar0_natf_div.
Definition fpredMr := fpredMr.
Definition fpredMl := fpredMl.
Definition fpred_divr := fpred_divr.
Definition fpred_divl := fpred_divl.
Definition satP {F e f} := @satP F e f.
Definition eq_sat := eq_sat.
Definition solP {F n f} := @solP F n f.
Definition eq_sol := eq_sol.
Definition size_sol := size_sol.
Definition solve_monicpoly := @solve_monicpoly.
#[warning="-deprecated-since-mathcomp-2.5.0",
deprecated(since="mathcomp 2.5.0", note="use `nmod_morphism` instead")]
Definition semi_additive := semi_additive.
Definition nmod_morphism := nmod_morphism.
#[warning="-deprecated-since-mathcomp-2.5.0",
deprecated(since="mathcomp 2.5.0", note="use `zmod_morphism` instead")]
Definition additive := additive.
Definition zmod_morphism := zmod_morphism.
Definition raddf0 := raddf0.
Definition raddf_eq0 := raddf_eq0.
Definition raddf_inj := raddf_inj.
Definition raddfN := raddfN.
Definition raddfD := raddfD.
Definition raddfB := raddfB.
Definition raddf_sum := raddf_sum.
Definition raddfMn := raddfMn.
Definition raddfMNn := raddfMNn.
Definition raddfMnat := raddfMnat.
Definition raddfMsign := raddfMsign.
#[warning="-deprecated-since-mathcomp-2.5.0",
deprecated(since="mathcomp 2.5.0", note="use `can2_nmod_morphism` instead")]
Definition can2_semi_additive := can2_semi_additive.
Definition can2_nmod_morphism := can2_nmod_morphism.
#[warning="-deprecated-since-mathcomp-2.5.0",
deprecated(since="mathcomp 2.5.0", note="use `can2_zmod_morphism` instead")]
Definition can2_additive := can2_additive.
Definition can2_zmod_morphism := can2_zmod_morphism.
#[warning="-deprecated-since-mathcomp-2.5.0",
deprecated(since="mathcomp 2.5.0", note="use `monoid_morphism` instead")]
Definition multiplicative := multiplicative.
Definition monoid_morphism := monoid_morphism.
Definition rmorph0 := rmorph0.
Definition rmorphN := rmorphN.
Definition rmorphD := rmorphD.
Definition rmorphB := rmorphB.
Definition rmorph_sum := rmorph_sum.
Definition rmorphMn := rmorphMn.
Definition rmorphMNn := rmorphMNn.
#[warning="-deprecated-since-mathcomp-2.5.0",
deprecated(since="mathcomp 2.5.0", note="use `rmorphism_monoidP` instead")]
Definition rmorphismMP := rmorphismMP.
Definition rmorphism_monoidP := rmorphism_monoidP.
Definition rmorph1 := rmorph1.
Definition rmorph_eq1 := rmorph_eq1.
Definition rmorphM := rmorphM.
Definition rmorphMsign := rmorphMsign.
Definition rmorph_nat := rmorph_nat.
Definition rmorph_eq_nat := rmorph_eq_nat.
Definition rmorph_prod := rmorph_prod.
Definition rmorphXn := rmorphXn.
Definition rmorphN1 := rmorphN1.
Definition rmorph_sign := rmorph_sign.
Definition rmorph_pchar := rmorph_pchar.
#[deprecated(since="mathcomp 2.4.0", note="Use rmorph_pchar instead.")]
Definition rmorph_char := rmorph_pchar.
#[warning="-deprecated-since-mathcomp-2.5.0",
deprecated(since="mathcomp 2.5.0", note="use `can2_monoid_morphism` instead")]
Definition can2_rmorphism := can2_rmorphism.
Definition can2_monoid_morphism := can2_monoid_morphism.
Definition rmorph_comm := rmorph_comm.
Definition rmorph_unit := rmorph_unit.
Definition rmorphV := rmorphV.
Definition rmorph_div := rmorph_div.
Definition fmorph_eq0 := fmorph_eq0.
Definition fmorph_inj := @fmorph_inj.
Arguments fmorph_inj {F R} f [x1 x2].
Definition fmorph_eq := fmorph_eq.
Definition fmorph_eq1 := fmorph_eq1.
Definition fmorph_pchar := fmorph_pchar.
#[deprecated(since="mathcomp 2.4.0", note="Use fmorph_pchar instead.")]
Definition fmorph_char := fmorph_pchar.
Definition fmorph_unit := fmorph_unit.
Definition fmorphV := fmorphV.
Definition fmorph_div := fmorph_div.
Definition scalerA := scalerA.
Definition scale1r := @scale1r.
Definition scalerDr := @scalerDr.
Definition scalerDl := @scalerDl.
Definition scaler0 := scaler0.
Definition scale0r := @scale0r.
Definition scaleNr := scaleNr.
Definition scaleN1r := scaleN1r.
Definition scalerN := scalerN.
Definition scalerBl := scalerBl.
Definition scalerBr := scalerBr.
Definition scaler_nat := scaler_nat.
Definition scalerMnl := scalerMnl.
Definition scalerMnr := scalerMnr.
Definition scaler_suml := scaler_suml.
Definition scaler_sumr := scaler_sumr.
Definition scaler_eq0 := scaler_eq0.
Definition scalerK := scalerK.
Definition scalerKV := scalerKV.
Definition scalerI := scalerI.
Definition scalerAl := @scalerAl.
Definition mulr_algl := mulr_algl.
Definition scaler_sign := scaler_sign.
Definition signrZK := signrZK.
Definition scalerCA := scalerCA.
Definition scalerAr := @scalerAr.
Definition mulr_algr := mulr_algr.
Definition comm_alg := comm_alg.
Definition exprZn := exprZn.
Definition scaler_prodl := scaler_prodl.
Definition scaler_prodr := scaler_prodr.
Definition scaler_prod := scaler_prod.
Definition scaler_injl := scaler_injl.
Definition scaler_unit := scaler_unit.
Definition invrZ := invrZ.
Definition raddfZnat := raddfZnat.
Definition raddfZsign := raddfZsign.
Definition in_algE := in_algE.
Definition scalable_for := scalable_for.
Definition semilinear_for := semilinear_for.
Definition linear_for := linear_for.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `nmod_morphism_semilinear` instead")]
Definition additive_semilinear := additive_semilinear.
Definition nmod_morphism_semilinear := nmod_morphism_semilinear.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `zmod_morphism_linear` instead")]
Definition additive_linear := additive_linear.
Definition zmod_morphism_linear := zmod_morphism_linear.
Definition scalable_semilinear := scalable_semilinear.
Definition scalable_linear := scalable_linear.
Definition linear0 := linear0.
Definition linearN := linearN.
Definition linearD := linearD.
Definition linearB := linearB.
Definition linear_sum := linear_sum.
Definition linearMn := linearMn.
Definition linearMNn := linearMNn.
Definition semilinearP := semilinearP.
Definition linearP := linearP.
Definition linearZ_LR := linearZ_LR.
Definition linearZ := linearZ.
Definition semilinearPZ := semilinearPZ.
Definition linearPZ := linearPZ.
Definition linearZZ := linearZZ.
Definition semiscalarP := semiscalarP.
Definition scalarP := scalarP.
Definition scalarZ := scalarZ.
Definition can2_scalable := can2_scalable.
Definition can2_linear := can2_linear.
Definition can2_semilinear := can2_semilinear.
Definition rmorph_alg := rmorph_alg.
Definition imaginary_exists := imaginary_exists.
Definition raddf := (raddf0, raddfN, raddfD, raddfMn).
Definition rmorphE :=
(rmorphD, rmorph0, rmorphB, rmorphN, rmorphMNn, rmorphMn, rmorph1, rmorphXn).
Definition linearE :=
(linearD, linear0, linearB, linearMNn, linearMn, linearZ).
Notation null_fun V := (null_fun V) (only parsing).
Notation in_alg A := (in_alg A) (only parsing).
End Theory.
Module AllExports. HB.reexport. End AllExports.
End GRing.
Export AllExports.
Export Scale.Exports.
Export ClosedExports.
#[deprecated(since="mathcomp 2.4.0",
note="Try pzSemiRingType (the potentially-zero counterpart) first, or use nzSemiRingType instead.")]
Notation semiRingType := (nzSemiRingType) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Try pzRingType (the potentially-zero counterpart) first, or use nzRingType instead.")]
Notation ringType := (nzRingType) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Try comPzSemiRingType (the potentially-zero counterpart) first, or use comNzSemiRingType instead.")]
Notation comSemiRingType := (comNzSemiRingType) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Try comPzRingType (the potentially-zero counterpart) first, or use comNzRingType instead.")]
Notation comRingType := (comNzRingType) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Try subPzSemiRingType (the potentially-zero counterpart) first, or use subNzSemiRingType instead.")]
Notation subSemiRingType := (subNzSemiRingType) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Try subComPzSemiRingType (the potentially-zero counterpart) first, or use subComNzSemiRingType instead.")]
Notation subComSemiRingType := (subComNzSemiRingType) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Try subPzRingType (the potentially-zero counterpart) first, or use subNzRingType instead.")]
Notation subRingType := (subNzRingType) (only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Try subComPzRingType (the potentially-zero counterpart) first, or use subComNzRingType instead.")]
Notation subComNzRingType := (subComNzRingType) (only parsing).
Notation addrClosed := addrClosed.
Notation opprClosed := opprClosed.
Variant Ione := IOne : Ione.
Inductive Inatmul :=
| INatmul : Ione -> nat -> Inatmul
| IOpp : Inatmul -> Inatmul.
Variant Idummy_placeholder :=.
Definition parse (x : Number.int) : Inatmul :=
match x with
| Number.IntDecimal (Decimal.Pos u) => INatmul IOne (Nat.of_uint u)
| Number.IntDecimal (Decimal.Neg u) => IOpp (INatmul IOne (Nat.of_uint u))
| Number.IntHexadecimal (Hexadecimal.Pos u) =>
INatmul IOne (Nat.of_hex_uint u)
| Number.IntHexadecimal (Hexadecimal.Neg u) =>
IOpp (INatmul IOne (Nat.of_hex_uint u))
end.
Definition print (x : Inatmul) : option Number.int :=
match x with
| INatmul IOne n =>
Some (Number.IntDecimal (Decimal.Pos (Nat.to_uint n)))
| IOpp (INatmul IOne n) =>
Some (Number.IntDecimal (Decimal.Neg (Nat.to_uint n)))
| _ => None
end.
Arguments GRing.one {_}.
Set Warnings "-via-type-remapping,-via-type-mismatch".
Number Notation Idummy_placeholder parse print (via Inatmul
mapping [[natmul] => INatmul, [opp] => IOpp, [one] => IOne])
: ring_scope.
Set Warnings "via-type-remapping,via-type-mismatch".
Arguments GRing.one : clear implicits.
Notation "0" := (@zero _) : ring_scope.
Notation "-%R" := (@opp _) : ring_scope.
Notation "- x" := (opp x) : ring_scope.
Notation "+%R" := (@add _) : function_scope.
Notation "x + y" := (add x y) : ring_scope.
Notation "x - y" := (add x (- y)) : ring_scope.
Arguments natmul : simpl never.
Notation "x *+ n" := (natmul x n) : ring_scope.
Notation "x *- n" := (opp (x *+ n)) : ring_scope.
Notation "s `_ i" := (seq.nth 0%R s%R i) : ring_scope.
Notation support := 0.-support.
Notation "1" := (@one _) : ring_scope.
Notation "- 1" := (opp 1) : ring_scope.
Notation "n %:R" := (natmul 1 n) : ring_scope.
Arguments GRing.pchar R%_type.
Notation "[ 'pchar' R ]" := (GRing.pchar R) : ring_scope.
#[deprecated(since="mathcomp 2.4.0", note="Use [pchar R] instead.")]
Notation "[ 'char' R ]" := (GRing.pchar R) : ring_scope.
Notation has_pchar0 R := (GRing.pchar R =i pred0).
#[deprecated(since="mathcomp 2.4.0", note="Use has_pchar0 instead.")]
Notation has_char0 R := (GRing.pchar R =i pred0).
Notation pFrobenius_aut chRp := (pFrobenius_aut chRp).
#[deprecated(since="mathcomp 2.4.0", note="Use pFrobenius_aut instead.")]
Notation Frobenius_aut chRp := (pFrobenius_aut chRp).
Notation "*%R" := (@mul _) : function_scope.
Notation "x * y" := (mul x y) : ring_scope.
Arguments exp : simpl never.
Notation "x ^+ n" := (exp x n) : ring_scope.
Notation "x ^-1" := (inv x) : ring_scope.
Notation "x ^- n" := (inv (x ^+ n)) : ring_scope.
Notation "x / y" := (mul x y^-1) : ring_scope.
Notation "*:%R" := (@scale _ _) : function_scope.
Notation "a *: m" := (scale a m) : ring_scope.
Notation "k %:A" := (scale k 1) : ring_scope.
Notation "\0" := (null_fun _) : ring_scope.
Notation "f \+ g" := (add_fun f g) : ring_scope.
Notation "f \- g" := (sub_fun f g) : ring_scope.
Notation "\- f" := (opp_fun f) : ring_scope.
Notation "a \*: f" := (scale_fun a f) : ring_scope.
Notation "x \*o f" := (mull_fun x f) : ring_scope.
Notation "x \o* f" := (mulr_fun x f) : ring_scope.
Notation "f \* g" := (mul_fun f g) : ring_scope.
Arguments mull_fun {_ _} a f _ /.
Arguments mulr_fun {_ _} a f _ /.
Arguments scale_fun {_ _ _} a f _ /.
Arguments mul_fun {_ _} f g _ /.
Notation "\sum_ ( i <- r | P ) F" :=
(\big[+%R/0%R]_(i <- r | P%B) F%R) : ring_scope.
Notation "\sum_ ( i <- r ) F" :=
(\big[+%R/0%R]_(i <- r) F%R) : ring_scope.
Notation "\sum_ ( m <= i < n | P ) F" :=
(\big[+%R/0%R]_(m <= i < n | P%B) F%R) : ring_scope.
Notation "\sum_ ( m <= i < n ) F" :=
(\big[+%R/0%R]_(m <= i < n) F%R) : ring_scope.
Notation "\sum_ ( i | P ) F" :=
(\big[+%R/0%R]_(i | P%B) F%R) : ring_scope.
Notation "\sum_ i F" :=
(\big[+%R/0%R]_i F%R) : ring_scope.
Notation "\sum_ ( i : t | P ) F" :=
(\big[+%R/0%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.
Notation "\sum_ ( i : t ) F" :=
(\big[+%R/0%R]_(i : t) F%R) (only parsing) : ring_scope.
Notation "\sum_ ( i < n | P ) F" :=
(\big[+%R/0%R]_(i < n | P%B) F%R) : ring_scope.
Notation "\sum_ ( i < n ) F" :=
(\big[+%R/0%R]_(i < n) F%R) : ring_scope.
Notation "\sum_ ( i 'in' A | P ) F" :=
(\big[+%R/0%R]_(i in A | P%B) F%R) : ring_scope.
Notation "\sum_ ( i 'in' A ) F" :=
(\big[+%R/0%R]_(i in A) F%R) : ring_scope.
Notation "\prod_ ( i <- r | P ) F" :=
(\big[*%R/1%R]_(i <- r | P%B) F%R) : ring_scope.
Notation "\prod_ ( i <- r ) F" :=
(\big[*%R/1%R]_(i <- r) F%R) : ring_scope.
Notation "\prod_ ( m <= i < n | P ) F" :=
(\big[*%R/1%R]_(m <= i < n | P%B) F%R) : ring_scope.
Notation "\prod_ ( m <= i < n ) F" :=
(\big[*%R/1%R]_(m <= i < n) F%R) : ring_scope.
Notation "\prod_ ( i | P ) F" :=
(\big[*%R/1%R]_(i | P%B) F%R) : ring_scope.
Notation "\prod_ i F" :=
(\big[*%R/1%R]_i F%R) : ring_scope.
Notation "\prod_ ( i : t | P ) F" :=
(\big[*%R/1%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.
Notation "\prod_ ( i : t ) F" :=
(\big[*%R/1%R]_(i : t) F%R) (only parsing) : ring_scope.
Notation "\prod_ ( i < n | P ) F" :=
(\big[*%R/1%R]_(i < n | P%B) F%R) : ring_scope.
Notation "\prod_ ( i < n ) F" :=
(\big[*%R/1%R]_(i < n) F%R) : ring_scope.
Notation "\prod_ ( i 'in' A | P ) F" :=
(\big[*%R/1%R]_(i in A | P%B) F%R) : ring_scope.
Notation "\prod_ ( i 'in' A ) F" :=
(\big[*%R/1%R]_(i in A) F%R) : ring_scope.
Notation "R ^c" := (converse R) : type_scope.
Notation "R ^o" := (regular R) : type_scope.
Bind Scope term_scope with term.
Bind Scope term_scope with formula.
Notation "''X_' i" := (Var _ i) : term_scope.
Notation "n %:R" := (NatConst _ n) : term_scope.
Notation "0" := 0%:R%T : term_scope.
Notation "1" := 1%:R%T : term_scope.
Notation "x %:T" := (Const x) : term_scope.
Infix "+" := Add : term_scope.
Notation "- t" := (Opp t) : term_scope.
Notation "t - u" := (Add t (- u)) : term_scope.
Infix "*" := Mul : term_scope.
Infix "*+" := NatMul : term_scope.
Notation "t ^-1" := (Inv t) : term_scope.
Notation "t / u" := (Mul t u^-1) : term_scope.
Infix "^+" := Exp : term_scope.
Infix "==" := Equal : term_scope.
Notation "x != y" := (GRing.Not (x == y)) : term_scope.
Infix "/\" := And : term_scope.
Infix "\/" := Or : term_scope.
Infix "==>" := Implies : term_scope.
Notation "~ f" := (Not f) : term_scope.
Notation "''exists' ''X_' i , f" := (Exists i f) : term_scope.
Notation "''forall' ''X_' i , f" := (Forall i f) : term_scope.
(* Lifting Structure from the codomain of finfuns. *)
Section Sum.
Variables (aT : finType) (rT : nmodType).
Variables (I : Type) (r : seq I) (P : pred I) (F : I -> {ffun aT -> rT}).
Lemma sum_ffunE x : (\sum_(i <- r | P i) F i) x = \sum_(i <- r | P i) F i x.
Proof. by elim/big_rec2: _ => // [|i _ y _ <-]; rewrite !ffunE. Qed.
Lemma sum_ffun :
\sum_(i <- r | P i) F i = [ffun x => \sum_(i <- r | P i) F i x].
Proof. by apply/ffunP=> i; rewrite sum_ffunE ffunE. Qed.
End Sum.
Section FinFunSemiRing.
(* As rings require 1 != 0 in order to lift a ring structure over finfuns *)
(* we need evidence that the domain is non-empty. *)
Variable (aT : finType) (R : pzSemiRingType).
Definition ffun_one : {ffun aT -> R} := [ffun => 1].
Definition ffun_mul (f g : {ffun aT -> R}) := [ffun x => f x * g x].
Fact ffun_mulA : associative ffun_mul.
Proof. by move=> f1 f2 f3; apply/ffunP=> i; rewrite !ffunE mulrA. Qed.
Fact ffun_mul_1l : left_id ffun_one ffun_mul.
Proof. by move=> f; apply/ffunP=> i; rewrite !ffunE mul1r. Qed.
Fact ffun_mul_1r : right_id ffun_one ffun_mul.
Proof. by move=> f; apply/ffunP=> i; rewrite !ffunE mulr1. Qed.
Fact ffun_mul_addl : left_distributive ffun_mul (@ffun_add _ _).
Proof. by move=> f1 f2 f3; apply/ffunP=> i; rewrite !ffunE mulrDl. Qed.
Fact ffun_mul_addr : right_distributive ffun_mul (@ffun_add _ _).
Proof. by move=> f1 f2 f3; apply/ffunP=> i; rewrite !ffunE mulrDr. Qed.
Fact ffun_mul_0l : left_zero (@ffun_zero _ _) ffun_mul.
Proof. by move=> f; apply/ffunP=> i; rewrite !ffunE mul0r. Qed.
Fact ffun_mul_0r : right_zero (@ffun_zero _ _) ffun_mul.
Proof. by move=> f; apply/ffunP=> i; rewrite !ffunE mulr0. Qed.
#[export]
HB.instance Definition _ := Nmodule_isPzSemiRing.Build {ffun aT -> R}
ffun_mulA ffun_mul_1l ffun_mul_1r ffun_mul_addl ffun_mul_addr
ffun_mul_0l ffun_mul_0r.
Definition ffun_semiring : pzSemiRingType := {ffun aT -> R}.
End FinFunSemiRing.
Section FinFunSemiRing.
Variable (aT : finType) (R : nzSemiRingType) (a : aT).
Fact ffun1_nonzero : ffun_one aT R != 0.
Proof. by apply/eqP => /ffunP/(_ a)/eqP; rewrite !ffunE oner_eq0. Qed.
(* TODO_HB uncomment once ffun_ring below is fixed
#[export]
HB.instance Definition _ := PzSemiRing_isNonZero.Build {ffun aT -> R}
ffun1_nonzero.
*)
End FinFunSemiRing.
HB.instance Definition _ (aT : finType) (R : pzRingType) :=
Zmodule_isPzRing.Build {ffun aT -> R}
(@ffun_mulA _ _) (@ffun_mul_1l _ _) (@ffun_mul_1r _ _)
(@ffun_mul_addl _ _) (@ffun_mul_addr _ _).
(* As nzRings require 1 != 0 in order to lift a ring structure over finfuns *)
(* we need evidence that the domain is non-empty. *)
Section FinFunRing.
Variable (aT : finType) (R : nzRingType) (a : aT).
(* TODO_HB: doesn't work in combination with ffun_semiring above *)
HB.instance Definition _ :=
PzSemiRing_isNonZero.Build {ffun aT -> R} (@ffun1_nonzero _ _ a).
Definition ffun_ring : nzRingType := {ffun aT -> R}.
End FinFunRing.
(* TODO_HB do FinFunComSemiRing once above is fixed *)
Section FinFunComRing.
Variable (aT : finType) (R : comPzRingType) (a : aT).
Fact ffun_mulC : commutative (@ffun_mul aT R).
Proof. by move=> f1 f2; apply/ffunP=> i; rewrite !ffunE mulrC. Qed.
(* TODO_HB
#[export]
HB.instance Definition _ :=
Ring_hasCommutativeMul.Build (ffun_ring _ a) ffun_mulC.
*)
End FinFunComRing.
Section FinFunLSemiMod.
Variable (R : pzSemiRingType) (aT : finType) (rT : lSemiModType R).
Implicit Types f g : {ffun aT -> rT}.
Definition ffun_scale k f := [ffun a => k *: f a].
Fact ffun_scaleA k1 k2 f :
ffun_scale k1 (ffun_scale k2 f) = ffun_scale (k1 * k2) f.
Proof. by apply/ffunP=> a; rewrite !ffunE scalerA. Qed.
Fact ffun_scale0r f : ffun_scale 0 f = 0.
Proof. by apply/ffunP=> a; rewrite !ffunE scale0r. Qed.
Fact ffun_scale1 : left_id 1 ffun_scale.
Proof. by move=> f; apply/ffunP=> a; rewrite !ffunE scale1r. Qed.
Fact ffun_scale_addr k : {morph (ffun_scale k) : x y / x + y}.
Proof. by move=> f g; apply/ffunP=> a; rewrite !ffunE scalerDr. Qed.
Fact ffun_scale_addl u : {morph (ffun_scale)^~ u : k1 k2 / k1 + k2}.
Proof. by move=> k1 k2; apply/ffunP=> a; rewrite !ffunE scalerDl. Qed.
#[export]
HB.instance Definition _ := Nmodule_isLSemiModule.Build R {ffun aT -> rT}
ffun_scaleA ffun_scale0r ffun_scale1 ffun_scale_addr ffun_scale_addl.
End FinFunLSemiMod.
#[export]
HB.instance Definition _ (R : pzRingType) (aT : finType) (rT : lmodType R) :=
LSemiModule.on {ffun aT -> rT}.
(* External direct product. *)
Section PairSemiRing.
Variables R1 R2 : pzSemiRingType.
Definition mul_pair (x y : R1 * R2) := (x.1 * y.1, x.2 * y.2).
Fact pair_mulA : associative mul_pair.
Proof. by move=> x y z; congr (_, _); apply: mulrA. Qed.
Fact pair_mul1l : left_id (1, 1) mul_pair.
Proof. by case=> x1 x2; congr (_, _); apply: mul1r. Qed.
Fact pair_mul1r : right_id (1, 1) mul_pair.
Proof. by case=> x1 x2; congr (_, _); apply: mulr1. Qed.
Fact pair_mulDl : left_distributive mul_pair +%R.
Proof. by move=> x y z; congr (_, _); apply: mulrDl. Qed.
Fact pair_mulDr : right_distributive mul_pair +%R.
Proof. by move=> x y z; congr (_, _); apply: mulrDr. Qed.
Fact pair_mul0r : left_zero 0 mul_pair.
Proof. by move=> x; congr (_, _); apply: mul0r. Qed.
Fact pair_mulr0 : right_zero 0 mul_pair.
Proof. by move=> x; congr (_, _); apply: mulr0. Qed.
#[export]
HB.instance Definition _ := Nmodule_isPzSemiRing.Build (R1 * R2)%type
pair_mulA pair_mul1l pair_mul1r pair_mulDl pair_mulDr pair_mul0r pair_mulr0.
Fact fst_is_monoid_morphism : monoid_morphism fst. Proof. by []. Qed.
#[export]
HB.instance Definition _ := isMonoidMorphism.Build (R1 * R2)%type R1 fst
fst_is_monoid_morphism.
Fact snd_is_monoid_morphism : monoid_morphism snd. Proof. by []. Qed.
#[export]
HB.instance Definition _ := isMonoidMorphism.Build (R1 * R2)%type R2 snd
snd_is_monoid_morphism.
End PairSemiRing.
Section PairSemiRing.
Variables R1 R2 : nzSemiRingType.
Fact pair_one_neq0 : 1 != 0 :> R1 * R2.
Proof. by rewrite xpair_eqE oner_eq0. Qed.
#[export]
HB.instance Definition _ := PzSemiRing_isNonZero.Build (R1 * R2)%type
pair_one_neq0.
End PairSemiRing.
Section PairComSemiRing.
Variables R1 R2 : comPzSemiRingType.
Fact pair_mulC : commutative (@mul_pair R1 R2).
Proof. by move=> x y; congr (_, _); apply: mulrC. Qed.
#[export]
HB.instance Definition _ := PzSemiRing_hasCommutativeMul.Build (R1 * R2)%type
pair_mulC.
End PairComSemiRing.
(* TODO: HB.saturate *)
#[export]
HB.instance Definition _ (R1 R2 : comNzSemiRingType) :=
NzSemiRing.on (R1 * R2)%type.
#[export]
HB.instance Definition _ (R1 R2 : pzRingType) := PzSemiRing.on (R1 * R2)%type.
#[export]
HB.instance Definition _ (R1 R2 : nzRingType) := NzSemiRing.on (R1 * R2)%type.
#[export]
HB.instance Definition _ (R1 R2 : comPzRingType) := PzRing.on (R1 * R2)%type.
#[export]
HB.instance Definition _ (R1 R2 : comNzRingType) := NzRing.on (R1 * R2)%type.
(* /TODO *)
Section PairLSemiMod.
Variables (R : pzSemiRingType) (V1 V2 : lSemiModType R).
Definition scale_pair a (v : V1 * V2) : V1 * V2 := (a *: v.1, a *: v.2).
Fact pair_scaleA a b u : scale_pair a (scale_pair b u) = scale_pair (a * b) u.
Proof. by congr (_, _); apply: scalerA. Qed.
Fact pair_scale0 u : scale_pair 0 u = 0.
Proof. by case: u => u1 u2; congr (_, _); apply: scale0r. Qed.
Fact pair_scale1 u : scale_pair 1 u = u.
Proof. by case: u => u1 u2; congr (_, _); apply: scale1r. Qed.
Fact pair_scaleDr : right_distributive scale_pair +%R.
Proof. by move=> a u v; congr (_, _); apply: scalerDr. Qed.
Fact pair_scaleDl u : {morph scale_pair^~ u: a b / a + b}.
Proof. by move=> a b; congr (_, _); apply: scalerDl. Qed.
#[export]
HB.instance Definition _ := Nmodule_isLSemiModule.Build R (V1 * V2)%type
pair_scaleA pair_scale0 pair_scale1 pair_scaleDr pair_scaleDl.
Fact fst_is_scalable : scalable fst. Proof. by []. Qed.
#[export]
HB.instance Definition _ :=
isScalable.Build R (V1 * V2)%type V1 *:%R fst fst_is_scalable.
Fact snd_is_scalable : scalable snd. Proof. by []. Qed.
#[export]
HB.instance Definition _ :=
isScalable.Build R (V1 * V2)%type V2 *:%R snd snd_is_scalable.
End PairLSemiMod.
Section PairLSemiAlg.
Variables (R : pzSemiRingType) (A1 A2 : lSemiAlgType R).
Fact pair_scaleAl a (u v : A1 * A2) : a *: (u * v) = (a *: u) * v.
Proof. by congr (_, _); apply: scalerAl. Qed.
#[export]
HB.instance Definition _ := LSemiModule_isLSemiAlgebra.Build R (A1 * A2)%type
pair_scaleAl.
(* TODO: HB.saturate *)
#[export]
HB.instance Definition _ := RMorphism.on (@fst A1 A2).
#[export]
HB.instance Definition _ := RMorphism.on (@snd A1 A2).
(* /TODO *)
End PairLSemiAlg.
Section PairSemiAlg.
Variables (R : pzSemiRingType) (A1 A2 : semiAlgType R).
Fact pair_scaleAr a (u v : A1 * A2) : a *: (u * v) = u * (a *: v).
Proof. by congr (_, _); apply: scalerAr. Qed.
#[export]
HB.instance Definition _ := LSemiAlgebra_isSemiAlgebra.Build R (A1 * A2)%type
pair_scaleAr.
End PairSemiAlg.
Section PairUnitRing.
Variables R1 R2 : unitRingType.
Definition pair_unitr :=
[qualify a x : R1 * R2 | (x.1 \is a GRing.unit) && (x.2 \is a GRing.unit)].
Definition pair_invr x :=
if x \is a pair_unitr then (x.1^-1, x.2^-1) else x.
Lemma pair_mulVl : {in pair_unitr, left_inverse 1 pair_invr *%R}.
Proof.
rewrite /pair_invr=> x; case: ifP => // /andP[Ux1 Ux2] _.
by congr (_, _); apply: mulVr.
Qed.
Lemma pair_mulVr : {in pair_unitr, right_inverse 1 pair_invr *%R}.
Proof.
rewrite /pair_invr=> x; case: ifP => // /andP[Ux1 Ux2] _.
by congr (_, _); apply: mulrV.
Qed.
Lemma pair_unitP x y : y * x = 1 /\ x * y = 1 -> x \is a pair_unitr.
Proof.
case=> [[y1x y2x] [x1y x2y]]; apply/andP.
by split; apply/unitrP; [exists y.1 | exists y.2].
Qed.
Lemma pair_invr_out : {in [predC pair_unitr], pair_invr =1 id}.
Proof. by rewrite /pair_invr => x /negPf/= ->. Qed.
#[export]
HB.instance Definition _ := NzRing_hasMulInverse.Build (R1 * R2)%type
pair_mulVl pair_mulVr pair_unitP pair_invr_out.
End PairUnitRing.
(* TODO: HB.saturate *)
#[export]
HB.instance Definition _ (R1 R2 : comUnitRingType) :=
UnitRing.on (R1 * R2)%type.
#[export]
HB.instance Definition _ (R : pzSemiRingType) (A1 A2 : comSemiAlgType R) :=
SemiAlgebra.on (A1 * A2)%type.
#[export]
HB.instance Definition _ (R : pzRingType) (V1 V2 : lmodType R) :=
LSemiModule.on (V1 * V2)%type.
#[export]
HB.instance Definition _ (R : pzRingType) (A1 A2 : lalgType R) :=
LSemiAlgebra.on (A1 * A2)%type.
#[export]
HB.instance Definition _ (R : pzRingType) (A1 A2 : algType R) :=
SemiAlgebra.on (A1 * A2)%type.
#[export]
HB.instance Definition _ (R : pzRingType) (A1 A2 : comAlgType R) :=
Algebra.on (A1 * A2)%type.
#[export]
HB.instance Definition _ (R : pzRingType) (A1 A2 : unitAlgType R) :=
Algebra.on (A1 * A2)%type.
#[export]
HB.instance Definition _ (R : pzRingType) (A1 A2 : comUnitAlgType R) :=
Algebra.on (A1 * A2)%type.
(* /TODO *)
Lemma pairMnE (M1 M2 : zmodType) (x : M1 * M2) n :
x *+ n = (x.1 *+ n, x.2 *+ n).
Proof. by case: x => x y; elim: n => //= n; rewrite !mulrS => ->. Qed.
(* begin hide *)
(* Testing subtype hierarchy
Section Test0.
Variables (T : choiceType) (S : {pred T}).
Inductive B := mkB x & x \in S.
Definition vB u := let: mkB x _ := u in x.
HB.instance Definition _ := [isSub for vB].
HB.instance Definition _ := [Choice of B by <:].
End Test0.
Section Test1.
Variables (R : unitRingType) (S : divringClosed R).
HB.instance Definition _ := [SubChoice_isSubUnitRing of B S by <:].
End Test1.
Section Test2.
Variables (R : comUnitRingType) (A : unitAlgType R) (S : divalgClosed A).
HB.instance Definition _ := [SubZmodule_isSubLmodule of B S by <:].
HB.instance Definition _ := [SubNzRing_SubLmodule_isSubLalgebra of B S by <:].
HB.instance Definition _ := [SubLalgebra_isSubAlgebra of B S by <:].
End Test2.
Section Test3.
Variables (F : fieldType) (S : divringClosed F).
HB.instance Definition _ := [SubRing_isSubComNzRing of B S by <:].
HB.instance Definition _ := [SubComUnitRing_isSubIntegralDomain of B S by <:].
HB.instance Definition _ := [SubIntegralDomain_isSubField of B S by <:].
End Test3.
*)
(* end hide *)
(* Algebraic structure of bool *)
HB.instance Definition _ := Zmodule_isComNzRing.Build bool
andbA andbC andTb andb_addl isT.
Fact mulVb (b : bool) : b != 0 -> b * b = 1.
Proof. by case: b. Qed.
Fact invb_out (x y : bool) : y * x = 1 -> x != 0.
Proof. by case: x; case: y. Qed.
HB.instance Definition _ := ComNzRing_hasMulInverse.Build bool
mulVb invb_out (fun x => fun => erefl x).
Lemma bool_fieldP : Field.axiom bool. Proof. by []. Qed.
HB.instance Definition _ := ComUnitRing_isField.Build bool bool_fieldP.
(* Algebraic structure of nat *)
HB.instance Definition _ := Nmodule_isComNzSemiRing.Build nat
mulnA mulnC mul1n mulnDl mul0n erefl.
HB.instance Definition _ (R : pzSemiRingType) :=
isMonoidMorphism.Build nat R (natmul 1) (mulr1n 1, natrM R).
Lemma natr0E : 0 = 0%N. Proof. by []. Qed.
Lemma natr1E : 1 = 1%N. Proof. by []. Qed.
Lemma natn n : n%:R = n.
Proof. by elim: n => [//|n IHn]; rewrite -nat1r IHn. Qed.
Lemma natrDE n m : n + m = (n + m)%N. Proof. by []. Qed.
Lemma natrME n m : n * m = (n * m)%N. Proof. by []. Qed.
Lemma natrXE n m : n ^+ m = (n ^ m)%N. Proof. by []. Qed.
Definition natrE := (natr0E, natr1E, natn, natrDE, natrME, natrXE).
|
classfun.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path.
From mathcomp Require Import div choice fintype tuple finfun bigop prime order.
From mathcomp Require Import ssralg poly finset fingroup morphism perm.
From mathcomp Require Import automorphism quotient finalg action gproduct zmodp.
From mathcomp Require Import commutator cyclic center pgroup sylow matrix.
From mathcomp Require Import vector falgebra ssrnum algC algnum archimedean.
(******************************************************************************)
(* This file contains the basic theory of class functions: *)
(* 'CF(G) == the type of class functions on G : {group gT}, i.e., *)
(* which map gT to the type algC of complex algebraics, *)
(* have support in G, and are constant on each conjugacy *)
(* class of G. 'CF(G) implements the falgType interface of *)
(* finite-dimensional F-algebras. *)
(* The identity 1 : 'CF(G) is the indicator function of G, *)
(* and (later) the principal character. *)
(* --> The %CF scope (cfun_scope) is bound to the 'CF(_) types. *)
(* 'CF(G)%VS == the (total) vector space of 'CF(G). *)
(* 'CF(G, A) == the subspace of functions in 'CF(G) with support in A. *)
(* phi x == the image of x : gT under phi : 'CF(G). *)
(* #[phi]%CF == the multiplicative order of phi : 'CF(G). *)
(* cfker phi == the kernel of phi : 'CF(G); note that cfker phi <| G. *)
(* cfaithful phi <=> phi : 'CF(G) is faithful (has a trivial kernel). *)
(* '1_A == the indicator function of A as a function of 'CF(G). *)
(* (Provided A <| G; G is determined by the context.) *)
(* phi^*%CF == the function conjugate to phi : 'CF(G). *)
(* cfAut u phi == the function conjugate to phi by an algC-automorphism u *)
(* phi^u The notation "_ ^u" is only reserved; it is up to *)
(* clients to set Notation "phi ^u" := (cfAut u phi). *)
(* '[phi, psi] == the convolution of phi, psi : 'CF(G) over G, normalised *)
(* '[phi, psi]_G by #|G| so that '[1, 1]_G = 1 (G is usually inferred). *)
(* cfdotr psi phi == '[phi, psi] (self-expanding). *)
(* '[phi], '[phi]_G == the squared norm '[phi, phi] of phi : 'CF(G). *)
(* orthogonal R S <=> each phi in R : seq 'CF(G) is orthogonal to each psi in *)
(* S, i.e., '[phi, psi] = 0. As 'CF(G) coerces to seq, one *)
(* can write orthogonal phi S and orthogonal phi psi. *)
(* pairwise_orthogonal S <=> the class functions in S are pairwise orthogonal *)
(* AND non-zero. *)
(* orthonormal S <=> S is pairwise orthogonal and all class functions in S *)
(* have norm 1. *)
(* isometry tau <-> tau : 'CF(D) -> 'CF(R) is an isometry, mapping *)
(* '[_, _]_D to '[_, _]_R. *)
(* {in CD, isometry tau, to CR} <-> in the domain CD, tau is an isometry *)
(* whose range is contained in CR. *)
(* cfReal phi <=> phi is real, i.e., phi^* == phi. *)
(* cfAut_closed u S <-> S : seq 'CF(G) is closed under conjugation by u. *)
(* cfConjC_closed S <-> S : seq 'CF(G) is closed under complex conjugation. *)
(* conjC_subset S1 S2 <-> S1 : seq 'CF(G) represents a subset of S2 closed *)
(* under complex conjugation. *)
(* := [/\ uniq S1, {subset S1 <= S2} & cfConjC_closed S1]. *)
(* 'Res[H] phi == the restriction of phi : 'CF(G) to a function of 'CF(H) *)
(* 'Res[H, G] phi 'Res[H] phi x = phi x if x \in H (when H \subset G), *)
(* 'Res phi 'Res[H] phi x = 0 if x \notin H. The syntax variants *)
(* allow H and G to be inferred; the default is to specify *)
(* H explicitly, and infer G from the type of phi. *)
(* 'Ind[G] phi == the class function of 'CF(G) induced by phi : 'CF(H), *)
(* 'Ind[G, H] phi when H \subset G. As with 'Res phi, both G and H can *)
(* 'Ind phi be inferred, though usually G isn't. *)
(* cfMorph phi == the class function in 'CF(G) that maps x to phi (f x), *)
(* where phi : 'CF(f @* G), provided G \subset 'dom f. *)
(* cfIsom isoGR phi == the class function in 'CF(R) that maps f x to phi x, *)
(* given isoGR : isom G R f, f : {morphism G >-> rT} and *)
(* phi : 'CF(G). *)
(* (phi %% H)%CF == special case of cfMorph phi, when phi : 'CF(G / H). *)
(* (phi / H)%CF == the class function in 'CF(G / H) that coincides with *)
(* phi : 'CF(G) on cosets of H \subset cfker phi. *)
(* For a group G that is a semidirect product (defG : K ><| H = G), we have *)
(* cfSdprod KxH phi == for phi : 'CF(H), the class function of 'CF(G) that *)
(* maps k * h to psi h when k \in K and h \in H. *)
(* For a group G that is a direct product (with KxH : K \x H = G), we have *)
(* cfDprodl KxH phi == for phi : 'CF(K), the class function of 'CF(G) that *)
(* maps k * h to phi k when k \in K and h \in H. *)
(* cfDprodr KxH psi == for psi : 'CF(H), the class function of 'CF(G) that *)
(* maps k * h to psi h when k \in K and h \in H. *)
(* cfDprod KxH phi psi == for phi : 'CF(K), psi : 'CF(H), the class function *)
(* of 'CF(G) that maps k * h to phi k * psi h (this is *)
(* the product of the two functions above). *)
(* Finally, given defG : \big[dprod/1]_(i | P i) A i = G, with G and A i *)
(* groups and i ranges over a finType, we have *)
(* cfBigdprodi defG phi == for phi : 'CF(A i) s.t. P i, the class function *)
(* of 'CF(G) that maps x to phi x_i, where x_i is the *)
(* (A i)-component of x : G. *)
(* cfBigdprod defG phi == for phi : forall i, 'CF(A i), the class function *)
(* of 'CF(G) that maps x to \prod_(i | P i) phi i x_i, *)
(* where x_i is the (A i)-component of x : G. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Declare Scope cfun_scope.
Import Order.TTheory GroupScope GRing.Theory Num.Theory.
Local Open Scope ring_scope.
Delimit Scope cfun_scope with CF.
Reserved Notation "''CF' ( G , A )" (format "''CF' ( G , A )").
Reserved Notation "''CF' ( G )" (format "''CF' ( G )").
Reserved Notation "''1_' G" (at level 8, G at level 2, format "''1_' G").
Reserved Notation "''Res[' H , G ]". (* only parsing *)
Reserved Notation "''Res[' H ]" (format "''Res[' H ]").
Reserved Notation "''Res'". (* only parsing *)
Reserved Notation "''Ind[' G , H ]". (* only parsing *)
Reserved Notation "''Ind[' G ]". (* only "''Ind[' G ]" *)
Reserved Notation "''Ind'". (* only parsing *)
Reserved Notation "'[ phi , psi ]_ G"
(at level 0, G at level 2). (* only parsing *)
Reserved Notation "'[ phi ]_ G"
(at level 0, G at level 2). (* only parsing *)
Reserved Notation "phi ^u" (format "phi ^u").
Section AlgC.
(* Arithmetic properties of group orders in the characteristic 0 field algC. *)
Variable (gT : finGroupType).
Implicit Types (G : {group gT}) (B : {set gT}).
Lemma neq0CG G : (#|G|)%:R != 0 :> algC. Proof. exact: natrG_neq0. Qed.
Lemma neq0CiG G B : (#|G : B|)%:R != 0 :> algC.
Proof. exact: natr_indexg_neq0. Qed.
Lemma gt0CG G : 0 < #|G|%:R :> algC. Proof. exact: natrG_gt0. Qed.
Lemma gt0CiG G B : 0 < #|G : B|%:R :> algC. Proof. exact: natr_indexg_gt0. Qed.
Lemma algC'G_pchar G : [pchar algC]^'.-group G.
Proof. by apply/pgroupP=> p _; rewrite inE /= pchar_num. Qed.
End AlgC.
#[deprecated(since="mathcomp 2.4.0", note="Use algC'G_pchar instead.")]
Notation algC'G := (algC'G_pchar) (only parsing).
Section Defs.
Variable gT : finGroupType.
Definition is_class_fun (B : {set gT}) (f : {ffun gT -> algC}) :=
[forall x, forall y in B, f (x ^ y) == f x] && (support f \subset B).
Lemma intro_class_fun (G : {group gT}) f :
{in G &, forall x y, f (x ^ y) = f x} ->
(forall x, x \notin G -> f x = 0) ->
is_class_fun G (finfun f).
Proof.
move=> fJ Gf; apply/andP; split; last first.
by apply/supportP=> x notAf; rewrite ffunE Gf.
apply/'forall_eqfun_inP=> x y Gy; rewrite !ffunE.
by have [/fJ-> // | notGx] := boolP (x \in G); rewrite !Gf ?groupJr.
Qed.
Variable B : {set gT}.
Local Notation G := <<B>>.
Record classfun : predArgType :=
Classfun {cfun_val; _ : is_class_fun G cfun_val}.
Implicit Types phi psi xi : classfun.
(* The default expansion lemma cfunE requires key = 0. *)
Fact classfun_key : unit. Proof. by []. Qed.
Definition Cfun := locked_with classfun_key (fun flag : nat => Classfun).
HB.instance Definition _ := [isSub for cfun_val].
HB.instance Definition _ := [Choice of classfun by <:].
Definition cfun_eqType : eqType := classfun.
Definition fun_of_cfun phi := cfun_val phi : gT -> algC.
Coercion fun_of_cfun : classfun >-> Funclass.
Lemma cfunElock k f fP : @Cfun k (finfun f) fP =1 f.
Proof. by rewrite locked_withE; apply: ffunE. Qed.
Lemma cfunE f fP : @Cfun 0 (finfun f) fP =1 f.
Proof. exact: cfunElock. Qed.
Lemma cfunP phi psi : phi =1 psi <-> phi = psi.
Proof. by split=> [/ffunP/val_inj | ->]. Qed.
Lemma cfun0gen phi x : x \notin G -> phi x = 0.
Proof. by case: phi => f fP; case: (andP fP) => _ /supportP; apply. Qed.
Lemma cfun_in_genP phi psi : {in G, phi =1 psi} -> phi = psi.
Proof.
move=> eq_phi; apply/cfunP=> x.
by have [/eq_phi-> // | notAx] := boolP (x \in G); rewrite !cfun0gen.
Qed.
Lemma cfunJgen phi x y : y \in G -> phi (x ^ y) = phi x.
Proof.
case: phi => f fP Gy; apply/eqP.
by case: (andP fP) => /'forall_forall_inP->.
Qed.
Fact cfun_zero_subproof : is_class_fun G (0 : {ffun _}).
Proof. exact: intro_class_fun. Qed.
Definition cfun_zero := Cfun 0 cfun_zero_subproof.
Fact cfun_comp_subproof f phi :
f 0 = 0 -> is_class_fun G [ffun x => f (phi x)].
Proof.
by move=> f0; apply: intro_class_fun => [x y _ /cfunJgen | x /cfun0gen] ->.
Qed.
Definition cfun_comp f f0 phi := Cfun 0 (@cfun_comp_subproof f phi f0).
Definition cfun_opp := cfun_comp (oppr0 _).
Fact cfun_add_subproof phi psi : is_class_fun G [ffun x => phi x + psi x].
Proof.
apply: intro_class_fun => [x y Gx Gy | x notGx]; rewrite ?cfunJgen //.
by rewrite !cfun0gen ?add0r.
Qed.
Definition cfun_add phi psi := Cfun 0 (cfun_add_subproof phi psi).
Fact cfun_indicator_subproof (A : {set gT}) :
is_class_fun G [ffun x => ((x \in G) && (x ^: G \subset A))%:R].
Proof.
apply: intro_class_fun => [x y Gx Gy | x /negbTE/= -> //].
by rewrite groupJr ?classGidl.
Qed.
Definition cfun_indicator A := Cfun 1 (cfun_indicator_subproof A).
Local Notation "''1_' A" := (cfun_indicator A) : ring_scope.
Lemma cfun1Egen x : '1_G x = (x \in G)%:R.
Proof. by rewrite cfunElock andb_idr // => /class_subG->. Qed.
Fact cfun_mul_subproof phi psi : is_class_fun G [ffun x => phi x * psi x].
Proof.
apply: intro_class_fun => [x y Gx Gy | x notGx]; rewrite ?cfunJgen //.
by rewrite cfun0gen ?mul0r.
Qed.
Definition cfun_mul phi psi := Cfun 0 (cfun_mul_subproof phi psi).
Definition cfun_unit := [pred phi : classfun | [forall x in G, phi x != 0]].
Definition cfun_inv phi :=
if phi \in cfun_unit then cfun_comp (invr0 _) phi else phi.
Definition cfun_scale a := cfun_comp (mulr0 a).
Fact cfun_addA : associative cfun_add.
Proof. by move=> phi psi xi; apply/cfunP=> x; rewrite !cfunE addrA. Qed.
Fact cfun_addC : commutative cfun_add.
Proof. by move=> phi psi; apply/cfunP=> x; rewrite !cfunE addrC. Qed.
Fact cfun_add0 : left_id cfun_zero cfun_add.
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE add0r. Qed.
Fact cfun_addN : left_inverse cfun_zero cfun_opp cfun_add.
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE addNr. Qed.
HB.instance Definition _ := GRing.isZmodule.Build classfun
cfun_addA cfun_addC cfun_add0 cfun_addN.
Lemma muln_cfunE phi n x : (phi *+ n) x = phi x *+ n.
Proof. by elim: n => [|n IHn]; rewrite ?mulrS !cfunE ?IHn. Qed.
Lemma sum_cfunE I r (P : pred I) (phi : I -> classfun) x :
(\sum_(i <- r | P i) phi i) x = \sum_(i <- r | P i) (phi i) x.
Proof. by elim/big_rec2: _ => [|i _ psi _ <-]; rewrite cfunE. Qed.
Fact cfun_mulA : associative cfun_mul.
Proof. by move=> phi psi xi; apply/cfunP=> x; rewrite !cfunE mulrA. Qed.
Fact cfun_mulC : commutative cfun_mul.
Proof. by move=> phi psi; apply/cfunP=> x; rewrite !cfunE mulrC. Qed.
Fact cfun_mul1 : left_id '1_G cfun_mul.
Proof.
by move=> phi; apply: cfun_in_genP => x Gx; rewrite !cfunE cfun1Egen Gx mul1r.
Qed.
Fact cfun_mulD : left_distributive cfun_mul cfun_add.
Proof. by move=> phi psi xi; apply/cfunP=> x; rewrite !cfunE mulrDl. Qed.
Fact cfun_nz1 : '1_G != 0.
Proof.
by apply/eqP=> /cfunP/(_ 1%g)/eqP; rewrite cfun1Egen cfunE group1 oner_eq0.
Qed.
HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build classfun
cfun_mulA cfun_mulC cfun_mul1 cfun_mulD cfun_nz1.
Definition cfun_nzRingType : nzRingType := classfun.
#[deprecated(since="mathcomp 2.4.0",
note="Use cfun_nzRingType instead.")]
Notation cfun_ringType := (cfun_nzRingType) (only parsing).
Lemma expS_cfunE phi n x : (phi ^+ n.+1) x = phi x ^+ n.+1.
Proof. by elim: n => //= n IHn; rewrite !cfunE IHn. Qed.
Fact cfun_mulV : {in cfun_unit, left_inverse 1 cfun_inv *%R}.
Proof.
move=> phi Uphi; rewrite /cfun_inv Uphi; apply/cfun_in_genP=> x Gx.
by rewrite !cfunE cfun1Egen Gx mulVf ?(forall_inP Uphi).
Qed.
Fact cfun_unitP phi psi : psi * phi = 1 -> phi \in cfun_unit.
Proof.
move/cfunP=> phiK; apply/forall_inP=> x Gx; rewrite -unitfE; apply/unitrP.
by exists (psi x); have:= phiK x; rewrite !cfunE cfun1Egen Gx mulrC.
Qed.
Fact cfun_inv0id : {in [predC cfun_unit], cfun_inv =1 id}.
Proof. by rewrite /cfun_inv => phi /negbTE/= ->. Qed.
HB.instance Definition _ :=
GRing.ComNzRing_hasMulInverse.Build classfun cfun_mulV cfun_unitP cfun_inv0id.
Fact cfun_scaleA a b phi :
cfun_scale a (cfun_scale b phi) = cfun_scale (a * b) phi.
Proof. by apply/cfunP=> x; rewrite !cfunE mulrA. Qed.
Fact cfun_scale1 : left_id 1 cfun_scale.
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE mul1r. Qed.
Fact cfun_scaleDr : right_distributive cfun_scale +%R.
Proof. by move=> a phi psi; apply/cfunP=> x; rewrite !cfunE mulrDr. Qed.
Fact cfun_scaleDl phi : {morph cfun_scale^~ phi : a b / a + b}.
Proof. by move=> a b; apply/cfunP=> x; rewrite !cfunE mulrDl. Qed.
HB.instance Definition _ := GRing.Zmodule_isLmodule.Build algC classfun
cfun_scaleA cfun_scale1 cfun_scaleDr cfun_scaleDl.
Fact cfun_scaleAl a phi psi : a *: (phi * psi) = (a *: phi) * psi.
Proof. by apply/cfunP=> x; rewrite !cfunE mulrA. Qed.
Fact cfun_scaleAr a phi psi : a *: (phi * psi) = phi * (a *: psi).
Proof. by rewrite !(mulrC phi) cfun_scaleAl. Qed.
HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build algC classfun
cfun_scaleAl.
HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build algC classfun
cfun_scaleAr.
Section Automorphism.
Variable u : {rmorphism algC -> algC}.
Definition cfAut := cfun_comp (rmorph0 u).
Lemma cfAut_cfun1i A : cfAut '1_A = '1_A.
Proof. by apply/cfunP=> x; rewrite !cfunElock rmorph_nat. Qed.
Lemma cfAutZ a phi : cfAut (a *: phi) = u a *: cfAut phi.
Proof. by apply/cfunP=> x; rewrite !cfunE rmorphM. Qed.
Lemma cfAut_is_zmod_morphism : zmod_morphism cfAut.
Proof.
by move=> phi psi; apply/cfunP=> x; rewrite ?cfAut_cfun1i // !cfunE /= rmorphB.
Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfAut_is_zmod_morphism` instead")]
Definition cfAut_is_additive := cfAut_is_zmod_morphism.
Lemma cfAut_is_monoid_morphism : monoid_morphism cfAut.
Proof.
by split=> [|phi psi]; apply/cfunP=> x; rewrite ?cfAut_cfun1i // !cfunE rmorphM.
Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfAut_is_monoid_morphism` instead")]
Definition cfAut_is_multiplicative :=
(fun g => (g.2,g.1)) cfAut_is_monoid_morphism.
HB.instance Definition _ := GRing.isZmodMorphism.Build classfun classfun cfAut
cfAut_is_zmod_morphism.
HB.instance Definition _ := GRing.isMonoidMorphism.Build classfun classfun cfAut
cfAut_is_monoid_morphism.
Lemma cfAut_cfun1 : cfAut 1 = 1. Proof. exact: rmorph1. Qed.
Lemma cfAut_scalable : scalable_for (u \; *:%R) cfAut.
Proof. by move=> a phi; apply/cfunP=> x; rewrite !cfunE rmorphM. Qed.
HB.instance Definition _ :=
GRing.isScalable.Build algC classfun classfun (u \; *:%R) cfAut
cfAut_scalable.
Definition cfAut_closed (S : seq classfun) :=
{in S, forall phi, cfAut phi \in S}.
End Automorphism.
(* FIX ME this has changed *)
Notation conjC := Num.conj_op.
Definition cfReal phi := cfAut conjC phi == phi.
Definition cfConjC_subset (S1 S2 : seq classfun) :=
[/\ uniq S1, {subset S1 <= S2} & cfAut_closed conjC S1].
Fact cfun_vect_iso : Vector.axiom #|classes G| classfun.
Proof.
exists (fun phi => \row_i phi (repr (enum_val i))) => [a phi psi|].
by apply/rowP=> i; rewrite !(mxE, cfunE).
set n := #|_|; pose eK x : 'I_n := enum_rank_in (classes1 _) (x ^: G).
have rV2vP v : is_class_fun G [ffun x => v (eK x) *+ (x \in G)].
apply: intro_class_fun => [x y Gx Gy | x /negbTE/=-> //].
by rewrite groupJr // /eK classGidl.
exists (fun v : 'rV_n => Cfun 0 (rV2vP (v 0))) => [phi | v].
apply/cfun_in_genP=> x Gx; rewrite cfunE Gx mxE enum_rankK_in ?mem_classes //.
by have [y Gy ->] := repr_class <<B>> x; rewrite cfunJgen.
apply/rowP=> i; rewrite mxE cfunE; have /imsetP[x Gx def_i] := enum_valP i.
rewrite def_i; have [y Gy ->] := repr_class <<B>> x.
by rewrite groupJ // /eK classGidl // -def_i enum_valK_in.
Qed.
HB.instance Definition _ := Lmodule_hasFinDim.Build algC classfun cfun_vect_iso.
Definition cfun_vectType : vectType _ := classfun.
Definition cfun_base A : #|classes B ::&: A|.-tuple classfun :=
[tuple of [seq '1_xB | xB in classes B ::&: A]].
Definition classfun_on A := <<cfun_base A>>%VS.
Definition cfdot phi psi := #|B|%:R^-1 * \sum_(x in B) phi x * (psi x)^*.
Definition cfdotr psi phi := cfdot phi psi.
Definition cfnorm phi := cfdot phi phi.
Coercion seq_of_cfun phi := [:: phi].
Definition cforder phi := \big[lcmn/1]_(x in <<B>>) #[phi x]%C.
End Defs.
Bind Scope cfun_scope with classfun.
Arguments classfun {gT} B%_g.
Arguments classfun_on {gT} B%_g A%_g.
Arguments cfun_indicator {gT} B%_g.
Arguments cfAut {gT B%_g} u phi%_CF.
Arguments cfReal {gT B%_g} phi%_CF.
Arguments cfdot {gT B%_g} phi%_CF psi%_CF.
Arguments cfdotr {gT B%_g} psi%_CF phi%_CF /.
Arguments cfnorm {gT B%_g} phi%_CF /.
Notation "''CF' ( G )" := (classfun G) : type_scope.
Notation "''CF' ( G )" := (@fullv _ (cfun_vectType G)) : vspace_scope.
Notation "''1_' A" := (cfun_indicator _ A) : ring_scope.
Notation "''CF' ( G , A )" := (classfun_on G A) : ring_scope.
Notation "1" := (@GRing.one (cfun_nzRingType _)) (only parsing) : cfun_scope.
(* FIX ME this has changed *)
Notation conjC := Num.conj_op.
Notation "phi ^*" := (cfAut conjC phi) : cfun_scope.
Notation cfConjC_closed := (cfAut_closed conjC).
Prenex Implicits cfReal.
(* Workaround for overeager projection reduction. *)
Notation eqcfP := (@eqP (cfun_eqType _) _ _) (only parsing).
Notation "#[ phi ]" := (cforder phi) : cfun_scope.
Notation "''[' u , v ]_ G":= (@cfdot _ G u v) (only parsing) : ring_scope.
Notation "''[' u , v ]" := (cfdot u v) : ring_scope.
Notation "''[' u ]_ G" := '[u, u]_G (only parsing) : ring_scope.
Notation "''[' u ]" := '[u, u] : ring_scope.
Section Predicates.
Variables (gT rT : finGroupType) (D : {set gT}) (R : {set rT}).
Implicit Types (phi psi : 'CF(D)) (S : seq 'CF(D)) (tau : 'CF(D) -> 'CF(R)).
Definition cfker phi := [set x in D | [forall y, phi (x * y)%g == phi y]].
Definition cfaithful phi := cfker phi \subset [1].
Definition ortho_rec S1 S2 :=
all [pred phi | all [pred psi | '[phi, psi] == 0] S2] S1.
Definition orthogonal := ortho_rec.
Arguments orthogonal : simpl never.
Fixpoint pair_ortho_rec S :=
if S is psi :: S' then ortho_rec psi S' && pair_ortho_rec S' else true.
(* We exclude 0 from pairwise orthogonal sets. *)
Definition pairwise_orthogonal S := (0 \notin S) && pair_ortho_rec S.
Definition orthonormal S := all [pred psi | '[psi] == 1] S && pair_ortho_rec S.
Definition isometry tau := forall phi psi, '[tau phi, tau psi] = '[phi, psi].
Definition isometry_from_to mCFD tau mCFR :=
prop_in2 mCFD (inPhantom (isometry tau))
/\ prop_in1 mCFD (inPhantom (forall phi, in_mem (tau phi) mCFR)).
End Predicates.
Arguments orthogonal : simpl never.
Arguments cfker {gT D%_g} phi%_CF.
Arguments cfaithful {gT D%_g} phi%_CF.
Arguments orthogonal {gT D%_g} S1%_CF S2%_CF.
Arguments pairwise_orthogonal {gT D%_g} S%_CF.
Arguments orthonormal {gT D%_g} S%_CF.
Arguments isometry {gT rT D%_g R%_g} tau%_CF.
Notation "{ 'in' CFD , 'isometry' tau , 'to' CFR }" :=
(isometry_from_to (mem CFD) tau (mem CFR))
(format "{ 'in' CFD , 'isometry' tau , 'to' CFR }")
: type_scope.
Section ClassFun.
Variables (gT : finGroupType) (G : {group gT}).
Implicit Types (A B : {set gT}) (H K : {group gT}) (phi psi xi : 'CF(G)).
Local Notation "''1_' A" := (cfun_indicator G A).
Lemma cfun0 phi x : x \notin G -> phi x = 0.
Proof. by rewrite -{1}(genGid G) => /(cfun0gen phi). Qed.
Lemma support_cfun phi : support phi \subset G.
Proof. by apply/subsetP=> g; apply: contraR => /cfun0->. Qed.
Lemma cfunJ phi x y : y \in G -> phi (x ^ y) = phi x.
Proof. by rewrite -{1}(genGid G) => /(cfunJgen phi)->. Qed.
Lemma cfun_repr phi x : phi (repr (x ^: G)) = phi x.
Proof. by have [y Gy ->] := repr_class G x; apply: cfunJ. Qed.
Lemma cfun_inP phi psi : {in G, phi =1 psi} -> phi = psi.
Proof. by rewrite -{1}genGid => /cfun_in_genP. Qed.
Lemma cfuniE A x : A <| G -> '1_A x = (x \in A)%:R.
Proof.
case/andP=> sAG nAG; rewrite cfunElock genGid.
by rewrite class_sub_norm // andb_idl // => /(subsetP sAG).
Qed.
Lemma support_cfuni A : A <| G -> support '1_A =i A.
Proof. by move=> nsAG x; rewrite !inE cfuniE // pnatr_eq0 -lt0n lt0b. Qed.
Lemma eq_mul_cfuni A phi : A <| G -> {in A, phi * '1_A =1 phi}.
Proof. by move=> nsAG x Ax; rewrite cfunE cfuniE // Ax mulr1. Qed.
Lemma eq_cfuni A : A <| G -> {in A, '1_A =1 (1 : 'CF(G))}.
Proof. by rewrite -['1_A]mul1r; apply: eq_mul_cfuni. Qed.
Lemma cfuniG : '1_G = 1.
Proof. by rewrite -[G in '1_G]genGid. Qed.
Lemma cfun1E g : (1 : 'CF(G)) g = (g \in G)%:R.
Proof. by rewrite -cfuniG cfuniE. Qed.
Lemma cfun11 : (1 : 'CF(G)) 1%g = 1.
Proof. by rewrite cfun1E group1. Qed.
Lemma prod_cfunE I r (P : pred I) (phi : I -> 'CF(G)) x :
x \in G -> (\prod_(i <- r | P i) phi i) x = \prod_(i <- r | P i) (phi i) x.
Proof.
by move=> Gx; elim/big_rec2: _ => [|i _ psi _ <-]; rewrite ?cfunE ?cfun1E ?Gx.
Qed.
Lemma exp_cfunE phi n x : x \in G -> (phi ^+ n) x = phi x ^+ n.
Proof. by rewrite -[n]card_ord -!prodr_const; apply: prod_cfunE. Qed.
Lemma mul_cfuni A B : '1_A * '1_B = '1_(A :&: B) :> 'CF(G).
Proof.
apply/cfunP=> g; rewrite !cfunElock -natrM mulnb subsetI.
by rewrite andbCA !andbA andbb.
Qed.
Lemma cfun_classE x y : '1_(x ^: G) y = ((x \in G) && (y \in x ^: G))%:R.
Proof.
rewrite cfunElock genGid class_sub_norm ?class_norm //; congr (_ : bool)%:R.
by apply: andb_id2r => /imsetP[z Gz ->]; rewrite groupJr.
Qed.
Lemma cfun_on_sum A :
'CF(G, A) = (\sum_(xG in classes G | xG \subset A) <['1_xG]>)%VS.
Proof.
by rewrite ['CF(G, A)]span_def big_image; apply: eq_bigl => xG; rewrite !inE.
Qed.
Lemma cfun_onP A phi :
reflect (forall x, x \notin A -> phi x = 0) (phi \in 'CF(G, A)).
Proof.
apply: (iffP idP) => [/coord_span-> x notAx | Aphi].
set b := cfun_base G A; rewrite sum_cfunE big1 // => i _; rewrite cfunE.
have /mapP[xG]: b`_i \in b by rewrite -tnth_nth mem_tnth.
rewrite mem_enum => /setIdP[/imsetP[y Gy ->] Ay] ->.
by rewrite cfun_classE Gy (contraNF (subsetP Ay x)) ?mulr0.
suffices <-: \sum_(xG in classes G) phi (repr xG) *: '1_xG = phi.
apply: memv_suml => _ /imsetP[x Gx ->]; rewrite rpredZeq cfun_repr.
have [s_xG_A | /subsetPn[_ /imsetP[y Gy ->]]] := boolP (x ^: G \subset A).
by rewrite cfun_on_sum [_ \in _](sumv_sup (x ^: G)) ?mem_classes ?orbT.
by move/Aphi; rewrite cfunJ // => ->; rewrite eqxx.
apply/cfun_inP=> x Gx; rewrite sum_cfunE (bigD1 (x ^: G)) ?mem_classes //=.
rewrite cfunE cfun_repr cfun_classE Gx class_refl mulr1.
rewrite big1 ?addr0 // => _ /andP[/imsetP[y Gy ->]]; apply: contraNeq.
rewrite cfunE cfun_repr cfun_classE Gy mulf_eq0 => /norP[_].
by rewrite pnatr_eq0 -lt0n lt0b => /class_eqP->.
Qed.
Arguments cfun_onP {A phi}.
Lemma cfun_on0 A phi x : phi \in 'CF(G, A) -> x \notin A -> phi x = 0.
Proof. by move/cfun_onP; apply. Qed.
Lemma sum_by_classes (R : nzRingType) (F : gT -> R) :
{in G &, forall g h, F (g ^ h) = F g} ->
\sum_(g in G) F g = \sum_(xG in classes G) #|xG|%:R * F (repr xG).
Proof.
move=> FJ; rewrite {1}(partition_big _ _ ((@mem_classes gT)^~ G)) /=.
apply: eq_bigr => _ /imsetP[x Gx ->]; have [y Gy ->] := repr_class G x.
rewrite mulr_natl -sumr_const FJ {y Gy}//; apply/esym/eq_big=> y /=.
apply/idP/andP=> [xGy | [Gy /eqP<-]]; last exact: class_refl.
by rewrite (class_eqP xGy) (subsetP (class_subG Gx (subxx _))).
by case/imsetP=> z Gz ->; rewrite FJ.
Qed.
Lemma cfun_base_free A : free (cfun_base G A).
Proof.
have b_i (i : 'I_#|classes G ::&: A|) : (cfun_base G A)`_i = '1_(enum_val i).
by rewrite /enum_val -!tnth_nth tnth_map.
apply/freeP => s S0 i; move/cfunP/(_ (repr (enum_val i))): S0.
rewrite sum_cfunE (bigD1 i) //= big1 ?addr0 => [|j].
rewrite b_i !cfunE; have /setIdP[/imsetP[x Gx ->] _] := enum_valP i.
by rewrite cfun_repr cfun_classE Gx class_refl mulr1.
apply: contraNeq; rewrite b_i !cfunE mulf_eq0 => /norP[_].
rewrite -(inj_eq enum_val_inj).
have /setIdP[/imsetP[x _ ->] _] := enum_valP i; rewrite cfun_repr.
have /setIdP[/imsetP[y Gy ->] _] := enum_valP j; rewrite cfun_classE Gy.
by rewrite pnatr_eq0 -lt0n lt0b => /class_eqP->.
Qed.
Lemma dim_cfun : \dim 'CF(G) = #|classes G|.
Proof. by rewrite dimvf /dim /= genGid. Qed.
Lemma dim_cfun_on A : \dim 'CF(G, A) = #|classes G ::&: A|.
Proof. by rewrite (eqnP (cfun_base_free A)) size_tuple. Qed.
Lemma dim_cfun_on_abelian A : abelian G -> A \subset G -> \dim 'CF(G, A) = #|A|.
Proof.
move/abelian_classP=> cGG sAG; rewrite -(card_imset _ set1_inj) dim_cfun_on.
apply/eq_card=> xG; rewrite !inE.
apply/andP/imsetP=> [[/imsetP[x Gx ->] Ax] | [x Ax ->]] {xG}.
by rewrite cGG ?sub1set // in Ax *; exists x.
by rewrite -{1}(cGG x) ?mem_classes ?(subsetP sAG) ?sub1set.
Qed.
Lemma cfuni_on A : '1_A \in 'CF(G, A).
Proof.
apply/cfun_onP=> x notAx; rewrite cfunElock genGid.
by case: andP => // [[_ s_xG_A]]; rewrite (subsetP s_xG_A) ?class_refl in notAx.
Qed.
Lemma mul_cfuni_on A phi : phi * '1_A \in 'CF(G, A).
Proof.
by apply/cfun_onP=> x /(cfun_onP (cfuni_on A)) Ax0; rewrite cfunE Ax0 mulr0.
Qed.
Lemma cfun_onE phi A : (phi \in 'CF(G, A)) = (support phi \subset A).
Proof. exact: (sameP cfun_onP supportP). Qed.
Lemma cfun_onT phi : phi \in 'CF(G, [set: gT]).
Proof. by rewrite cfun_onE. Qed.
Lemma cfun_onD1 phi A :
(phi \in 'CF(G, A^#)) = (phi \in 'CF(G, A)) && (phi 1%g == 0).
Proof.
by rewrite !cfun_onE -!(eq_subset (in_set (support _))) subsetD1 !inE negbK.
Qed.
Lemma cfun_onG phi : phi \in 'CF(G, G).
Proof. by rewrite cfun_onE support_cfun. Qed.
Lemma cfunD1E phi : (phi \in 'CF(G, G^#)) = (phi 1%g == 0).
Proof. by rewrite cfun_onD1 cfun_onG. Qed.
Lemma cfunGid : 'CF(G, G) = 'CF(G)%VS.
Proof. by apply/vspaceP=> phi; rewrite cfun_onG memvf. Qed.
Lemma cfun_onS A B phi : B \subset A -> phi \in 'CF(G, B) -> phi \in 'CF(G, A).
Proof. by rewrite !cfun_onE => sBA /subset_trans->. Qed.
Lemma cfun_complement A :
A <| G -> ('CF(G, A) + 'CF(G, G :\: A)%SET = 'CF(G))%VS.
Proof.
case/andP=> sAG nAG; rewrite -cfunGid [rhs in _ = rhs]cfun_on_sum.
rewrite (bigID (fun B => B \subset A)) /=.
congr (_ + _)%VS; rewrite cfun_on_sum; apply: eq_bigl => /= xG.
rewrite andbAC; apply/esym/andb_idr=> /andP[/imsetP[x Gx ->] _].
by rewrite class_subG.
rewrite -andbA; apply: andb_id2l => /imsetP[x Gx ->].
by rewrite !class_sub_norm ?normsD ?normG // inE andbC.
Qed.
Lemma cfConjCE phi x : ( phi^* )%CF x = (phi x)^*.
Proof. by rewrite cfunE. Qed.
Lemma cfConjCK : involutive (fun phi => phi^* )%CF.
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE /= conjCK. Qed.
Lemma cfConjC_cfun1 : ( 1^* )%CF = 1 :> 'CF(G).
Proof. exact: rmorph1. Qed.
(* Class function kernel and faithful class functions *)
Fact cfker_is_group phi : group_set (cfker phi).
Proof.
apply/group_setP; split=> [|x y]; rewrite !inE ?group1.
by apply/forallP=> y; rewrite mul1g.
case/andP=> Gx /forallP-Kx /andP[Gy /forallP-Ky]; rewrite groupM //.
by apply/forallP=> z; rewrite -mulgA (eqP (Kx _)) Ky.
Qed.
Canonical cfker_group phi := Group (cfker_is_group phi).
Lemma cfker_sub phi : cfker phi \subset G.
Proof. by rewrite /cfker setIdE subsetIl. Qed.
Lemma cfker_norm phi : G \subset 'N(cfker phi).
Proof.
apply/subsetP=> z Gz; have phiJz := cfunJ phi _ (groupVr Gz).
rewrite inE; apply/subsetP=> _ /imsetP[x /setIdP[Gx /forallP-Kx] ->].
rewrite inE groupJ //; apply/forallP=> y.
by rewrite -(phiJz y) -phiJz conjMg conjgK Kx.
Qed.
Lemma cfker_normal phi : cfker phi <| G.
Proof. by rewrite /normal cfker_sub cfker_norm. Qed.
Lemma cfkerMl phi x y : x \in cfker phi -> phi (x * y)%g = phi y.
Proof. by case/setIdP=> _ /eqfunP->. Qed.
Lemma cfkerMr phi x y : x \in cfker phi -> phi (y * x)%g = phi y.
Proof.
by move=> Kx; rewrite conjgC cfkerMl ?cfunJ ?(subsetP (cfker_sub phi)).
Qed.
Lemma cfker1 phi x : x \in cfker phi -> phi x = phi 1%g.
Proof. by move=> Kx; rewrite -[x]mulg1 cfkerMl. Qed.
Lemma cfker_cfun0 : @cfker _ G 0 = G.
Proof.
apply/setP=> x; rewrite !inE andb_idr // => Gx; apply/forallP=> y.
by rewrite !cfunE.
Qed.
Lemma cfker_add phi psi : cfker phi :&: cfker psi \subset cfker (phi + psi).
Proof.
apply/subsetP=> x /setIP[Kphi_x Kpsi_x]; have [Gx _] := setIdP Kphi_x.
by rewrite inE Gx; apply/forallP=> y; rewrite !cfunE !cfkerMl.
Qed.
Lemma cfker_sum I r (P : pred I) (Phi : I -> 'CF(G)) :
G :&: \bigcap_(i <- r | P i) cfker (Phi i)
\subset cfker (\sum_(i <- r | P i) Phi i).
Proof.
elim/big_rec2: _ => [|i K psi Pi sK_psi]; first by rewrite setIT cfker_cfun0.
by rewrite setICA; apply: subset_trans (setIS _ sK_psi) (cfker_add _ _).
Qed.
Lemma cfker_scale a phi : cfker phi \subset cfker (a *: phi).
Proof.
apply/subsetP=> x Kphi_x; have [Gx _] := setIdP Kphi_x.
by rewrite inE Gx; apply/forallP=> y; rewrite !cfunE cfkerMl.
Qed.
Lemma cfker_scale_nz a phi : a != 0 -> cfker (a *: phi) = cfker phi.
Proof.
move=> nz_a; apply/eqP.
by rewrite eqEsubset -{2}(scalerK nz_a phi) !cfker_scale.
Qed.
Lemma cfker_opp phi : cfker (- phi) = cfker phi.
Proof. by rewrite -scaleN1r cfker_scale_nz // oppr_eq0 oner_eq0. Qed.
Lemma cfker_cfun1 : @cfker _ G 1 = G.
Proof.
apply/setP=> x; rewrite !inE andb_idr // => Gx; apply/forallP=> y.
by rewrite !cfun1E groupMl.
Qed.
Lemma cfker_mul phi psi : cfker phi :&: cfker psi \subset cfker (phi * psi).
Proof.
apply/subsetP=> x /setIP[Kphi_x Kpsi_x]; have [Gx _] := setIdP Kphi_x.
by rewrite inE Gx; apply/forallP=> y; rewrite !cfunE !cfkerMl.
Qed.
Lemma cfker_prod I r (P : pred I) (Phi : I -> 'CF(G)) :
G :&: \bigcap_(i <- r | P i) cfker (Phi i)
\subset cfker (\prod_(i <- r | P i) Phi i).
Proof.
elim/big_rec2: _ => [|i K psi Pi sK_psi]; first by rewrite setIT cfker_cfun1.
by rewrite setICA; apply: subset_trans (setIS _ sK_psi) (cfker_mul _ _).
Qed.
Lemma cfaithfulE phi : cfaithful phi = (cfker phi \subset [1]).
Proof. by []. Qed.
End ClassFun.
Arguments classfun_on {gT} B%_g A%_g.
Notation "''CF' ( G , A )" := (classfun_on G A) : ring_scope.
Arguments cfun_onP {gT G A phi}.
Arguments cfConjCK {gT G} phi : rename.
#[global] Hint Resolve cfun_onT : core.
Section DotProduct.
Variable (gT : finGroupType) (G : {group gT}).
Implicit Types (M : {group gT}) (phi psi xi : 'CF(G)) (R S : seq 'CF(G)).
Lemma cfdotE phi psi :
'[phi, psi] = #|G|%:R^-1 * \sum_(x in G) phi x * (psi x)^*.
Proof. by []. Qed.
Lemma cfdotElr A B phi psi :
phi \in 'CF(G, A) -> psi \in 'CF(G, B) ->
'[phi, psi] = #|G|%:R^-1 * \sum_(x in A :&: B) phi x * (psi x)^*.
Proof.
move=> Aphi Bpsi; rewrite (big_setID G)/= cfdotE (big_setID (A :&: B))/= setIC.
congr (_ * (_ + _)); rewrite !big1 // => x /setDP[_].
by move/cfun0->; rewrite mul0r.
rewrite inE; case/nandP=> notABx; first by rewrite (cfun_on0 Aphi) ?mul0r.
by rewrite (cfun_on0 Bpsi) // rmorph0 mulr0.
Qed.
Lemma cfdotEl A phi psi :
phi \in 'CF(G, A) ->
'[phi, psi] = #|G|%:R^-1 * \sum_(x in A) phi x * (psi x)^*.
Proof. by move=> Aphi; rewrite (cfdotElr Aphi (cfun_onT psi)) setIT. Qed.
Lemma cfdotEr A phi psi :
psi \in 'CF(G, A) ->
'[phi, psi] = #|G|%:R^-1 * \sum_(x in A) phi x * (psi x)^*.
Proof. by move=> Apsi; rewrite (cfdotElr (cfun_onT phi) Apsi) setTI. Qed.
Lemma cfdot_complement A phi psi :
phi \in 'CF(G, A) -> psi \in 'CF(G, G :\: A) -> '[phi, psi] = 0.
Proof.
move=> Aphi A'psi; rewrite (cfdotElr Aphi A'psi).
by rewrite setDE setICA setICr setI0 big_set0 mulr0.
Qed.
Lemma cfnormE A phi :
phi \in 'CF(G, A) -> '[phi] = #|G|%:R^-1 * (\sum_(x in A) `|phi x| ^+ 2).
Proof. by move/cfdotEl->; rewrite (eq_bigr _ (fun _ _ => normCK _)). Qed.
Lemma eq_cfdotl A phi1 phi2 psi :
psi \in 'CF(G, A) -> {in A, phi1 =1 phi2} -> '[phi1, psi] = '[phi2, psi].
Proof.
move/cfdotEr=> eq_dot eq_phi; rewrite !eq_dot; congr (_ * _).
by apply: eq_bigr => x Ax; rewrite eq_phi.
Qed.
Lemma cfdot_cfuni A B :
A <| G -> B <| G -> '['1_A, '1_B]_G = #|A :&: B|%:R / #|G|%:R.
Proof.
move=> nsAG nsBG; rewrite (cfdotElr (cfuni_on G A) (cfuni_on G B)) mulrC.
congr (_ / _); rewrite -sumr_const; apply: eq_bigr => x /setIP[Ax Bx].
by rewrite !cfuniE // Ax Bx mul1r rmorph1.
Qed.
Lemma cfnorm1 : '[1]_G = 1.
Proof. by rewrite cfdot_cfuni ?genGid // setIid divff ?neq0CG. Qed.
Lemma cfdotrE psi phi : cfdotr psi phi = '[phi, psi]. Proof. by []. Qed.
Lemma cfdotr_is_linear xi : linear (cfdotr xi : 'CF(G) -> algC^o).
Proof.
move=> a phi psi; rewrite scalerAr -mulrDr; congr (_ * _).
rewrite linear_sum -big_split; apply: eq_bigr => x _ /=.
by rewrite !cfunE mulrDl -mulrA.
Qed.
HB.instance Definition _ xi := GRing.isSemilinear.Build algC _ _ _ (cfdotr xi)
(GRing.semilinear_linear (cfdotr_is_linear xi)).
Lemma cfdot0l xi : '[0, xi] = 0.
Proof. by rewrite -cfdotrE linear0. Qed.
Lemma cfdotNl xi phi : '[- phi, xi] = - '[phi, xi].
Proof. by rewrite -!cfdotrE linearN. Qed.
Lemma cfdotDl xi phi psi : '[phi + psi, xi] = '[phi, xi] + '[psi, xi].
Proof. by rewrite -!cfdotrE linearD. Qed.
Lemma cfdotBl xi phi psi : '[phi - psi, xi] = '[phi, xi] - '[psi, xi].
Proof. by rewrite -!cfdotrE linearB. Qed.
Lemma cfdotMnl xi phi n : '[phi *+ n, xi] = '[phi, xi] *+ n.
Proof. by rewrite -!cfdotrE linearMn. Qed.
Lemma cfdot_suml xi I r (P : pred I) (phi : I -> 'CF(G)) :
'[\sum_(i <- r | P i) phi i, xi] = \sum_(i <- r | P i) '[phi i, xi].
Proof. by rewrite -!cfdotrE linear_sum. Qed.
Lemma cfdotZl xi a phi : '[a *: phi, xi] = a * '[phi, xi].
Proof. by rewrite -!cfdotrE linearZ. Qed.
Lemma cfdotC phi psi : '[phi, psi] = ('[psi, phi])^*.
Proof.
rewrite /cfdot rmorphM /= fmorphV rmorph_nat rmorph_sum; congr (_ * _).
by apply: eq_bigr=> x _; rewrite rmorphM /= conjCK mulrC.
Qed.
Lemma eq_cfdotr A phi psi1 psi2 :
phi \in 'CF(G, A) -> {in A, psi1 =1 psi2} -> '[phi, psi1] = '[phi, psi2].
Proof. by move=> Aphi /eq_cfdotl eq_dot; rewrite cfdotC eq_dot // -cfdotC. Qed.
Lemma cfdotBr xi phi psi : '[xi, phi - psi] = '[xi, phi] - '[xi, psi].
Proof. by rewrite !(cfdotC xi) -rmorphB cfdotBl. Qed.
HB.instance Definition _ xi :=
GRing.isZmodMorphism.Build _ _ (cfdot xi) (cfdotBr xi).
Lemma cfdot0r xi : '[xi, 0] = 0. Proof. exact: raddf0. Qed.
Lemma cfdotNr xi phi : '[xi, - phi] = - '[xi, phi].
Proof. exact: raddfN. Qed.
Lemma cfdotDr xi phi psi : '[xi, phi + psi] = '[xi, phi] + '[xi, psi].
Proof. exact: raddfD. Qed.
Lemma cfdotMnr xi phi n : '[xi, phi *+ n] = '[xi, phi] *+ n.
Proof. exact: raddfMn. Qed.
Lemma cfdot_sumr xi I r (P : pred I) (phi : I -> 'CF(G)) :
'[xi, \sum_(i <- r | P i) phi i] = \sum_(i <- r | P i) '[xi, phi i].
Proof. exact: raddf_sum. Qed.
Lemma cfdotZr a xi phi : '[xi, a *: phi] = a^* * '[xi, phi].
Proof. by rewrite !(cfdotC xi) cfdotZl rmorphM. Qed.
Lemma cfdot_cfAut (u : {rmorphism algC -> algC}) phi psi :
{in image psi G, {morph u : x / x^*}} ->
'[cfAut u phi, cfAut u psi] = u '[phi, psi].
Proof.
move=> uC; rewrite rmorphM /= fmorphV rmorph_nat rmorph_sum; congr (_ * _).
by apply: eq_bigr => x Gx; rewrite !cfunE rmorphM /= uC ?map_f ?mem_enum.
Qed.
Lemma cfdot_conjC phi psi : '[phi^*, psi^*] = '[phi, psi]^*.
Proof. by rewrite cfdot_cfAut. Qed.
Lemma cfdot_conjCl phi psi : '[phi^*, psi] = '[phi, psi^*]^*.
Proof. by rewrite -cfdot_conjC cfConjCK. Qed.
Lemma cfdot_conjCr phi psi : '[phi, psi^*] = '[phi^*, psi]^*.
Proof. by rewrite -cfdot_conjC cfConjCK. Qed.
Lemma cfnorm_ge0 phi : 0 <= '[phi].
Proof.
by rewrite mulr_ge0 ?invr_ge0 ?ler0n ?sumr_ge0 // => x _; apply: mul_conjC_ge0.
Qed.
Lemma cfnorm_eq0 phi : ('[phi] == 0) = (phi == 0).
Proof.
apply/idP/eqP=> [|->]; last by rewrite cfdot0r.
rewrite mulf_eq0 invr_eq0 (negbTE (neq0CG G)) /= => /eqP/psumr_eq0P phi0.
apply/cfun_inP=> x Gx; apply/eqP; rewrite cfunE -mul_conjC_eq0.
by rewrite phi0 // => y _; apply: mul_conjC_ge0.
Qed.
Lemma cfnorm_gt0 phi : ('[phi] > 0) = (phi != 0).
Proof. by rewrite lt_def cfnorm_ge0 cfnorm_eq0 andbT. Qed.
Lemma sqrt_cfnorm_ge0 phi : 0 <= sqrtC '[phi].
Proof. by rewrite sqrtC_ge0 cfnorm_ge0. Qed.
Lemma sqrt_cfnorm_eq0 phi : (sqrtC '[phi] == 0) = (phi == 0).
Proof. by rewrite sqrtC_eq0 cfnorm_eq0. Qed.
Lemma sqrt_cfnorm_gt0 phi : (sqrtC '[phi] > 0) = (phi != 0).
Proof. by rewrite sqrtC_gt0 cfnorm_gt0. Qed.
Lemma cfnormZ a phi : '[a *: phi]= `|a| ^+ 2 * '[phi]_G.
Proof. by rewrite cfdotZl cfdotZr mulrA normCK. Qed.
Lemma cfnormN phi : '[- phi] = '[phi].
Proof. by rewrite cfdotNl raddfN opprK. Qed.
Lemma cfnorm_sign n phi : '[(-1) ^+ n *: phi] = '[phi].
Proof. by rewrite -signr_odd scaler_sign; case: (odd n); rewrite ?cfnormN. Qed.
Lemma cfnormD phi psi :
let d := '[phi, psi] in '[phi + psi] = '[phi] + '[psi] + ( d + d^* ).
Proof. by rewrite /= addrAC -cfdotC cfdotDl !cfdotDr !addrA. Qed.
Lemma cfnormB phi psi :
let d := '[phi, psi] in '[phi - psi] = '[phi] + '[psi] - ( d + d^* ).
Proof. by rewrite /= cfnormD cfnormN cfdotNr rmorphN -opprD. Qed.
Lemma cfnormDd phi psi : '[phi, psi] = 0 -> '[phi + psi] = '[phi] + '[psi].
Proof. by move=> ophipsi; rewrite cfnormD ophipsi rmorph0 !addr0. Qed.
Lemma cfnormBd phi psi : '[phi, psi] = 0 -> '[phi - psi] = '[phi] + '[psi].
Proof.
by move=> ophipsi; rewrite cfnormDd ?cfnormN // cfdotNr ophipsi oppr0.
Qed.
Lemma cfnorm_conjC phi : '[phi^*] = '[phi].
Proof. by rewrite cfdot_conjC geC0_conj // cfnorm_ge0. Qed.
Lemma cfCauchySchwarz phi psi :
`|'[phi, psi]| ^+ 2 <= '[phi] * '[psi] ?= iff ~~ free (phi :: psi).
Proof.
rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC.
have [-> | nz_psi] /= := eqVneq psi 0.
by apply/leifP; rewrite !cfdot0r normCK mul0r mulr0.
without loss ophi: phi / '[phi, psi] = 0.
move=> IHo; pose a := '[phi, psi] / '[psi]; pose phi1 := phi - a *: psi.
have ophi: '[phi1, psi] = 0.
by rewrite cfdotBl cfdotZl divfK ?cfnorm_eq0 ?subrr.
rewrite (canRL (subrK _) (erefl phi1)) rpredDr ?rpredZ ?memv_line //.
rewrite cfdotDl ophi add0r cfdotZl normrM (ger0_norm (cfnorm_ge0 _)).
rewrite exprMn mulrA -cfnormZ cfnormDd; last by rewrite cfdotZr ophi mulr0.
by have:= IHo _ ophi; rewrite mulrDl -leifBLR subrr ophi normCK mul0r.
rewrite ophi normCK mul0r; split; first by rewrite mulr_ge0 ?cfnorm_ge0.
rewrite eq_sym mulf_eq0 orbC cfnorm_eq0 (negPf nz_psi) /=.
apply/idP/idP=> [|/vlineP[a {2}->]]; last by rewrite cfdotZr ophi mulr0.
by rewrite cfnorm_eq0 => /eqP->; apply: rpred0.
Qed.
Lemma cfCauchySchwarz_sqrt phi psi :
`|'[phi, psi]| <= sqrtC '[phi] * sqrtC '[psi] ?= iff ~~ free (phi :: psi).
Proof.
rewrite -(sqrCK (normr_ge0 _)) -sqrtCM ?qualifE/= ?cfnorm_ge0 //.
rewrite (mono_in_leif (@ler_sqrtC _)) 1?rpredM ?qualifE/= ?cfnorm_ge0 //;
[ exact: cfCauchySchwarz | exact: O.. ].
Qed.
Lemma cf_triangle_leif phi psi :
sqrtC '[phi + psi] <= sqrtC '[phi] + sqrtC '[psi]
?= iff ~~ free (phi :: psi) && (0 <= coord [tuple psi] 0 phi).
Proof.
rewrite -(mono_in_leif ler_sqr) ?rpredD ?qualifE/= ?sqrtC_ge0 ?cfnorm_ge0 //;
[| exact: O.. ].
rewrite andbC sqrrD !sqrtCK addrAC cfnormD (mono_leif (lerD2l _)).
rewrite -mulr_natr -[_ + _](divfK (negbT (eqC_nat 2 0))) -/('Re _).
rewrite (mono_leif (ler_pM2r _)) ?ltr0n //.
have:= leif_trans (leif_Re_Creal '[phi, psi]) (cfCauchySchwarz_sqrt phi psi).
congr (_ <= _ ?= iff _); first by rewrite ReE.
apply: andb_id2r; rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC /=.
have [-> | nz_psi] := eqVneq psi 0; first by rewrite cfdot0r coord0.
case/vlineP=> [x ->]; rewrite cfdotZl linearZ pmulr_lge0 ?cfnorm_gt0 //=.
by rewrite (coord_free 0) ?seq1_free // eqxx mulr1.
Qed.
Lemma orthogonal_cons phi R S :
orthogonal (phi :: R) S = orthogonal phi S && orthogonal R S.
Proof. by rewrite /orthogonal /= andbT. Qed.
Lemma orthoP phi psi : reflect ('[phi, psi] = 0) (orthogonal phi psi).
Proof. by rewrite /orthogonal /= !andbT; apply: eqP. Qed.
Lemma orthogonalP S R :
reflect {in S & R, forall phi psi, '[phi, psi] = 0} (orthogonal S R).
Proof.
apply: (iffP allP) => oSR phi => [psi /oSR/allP opS /opS/eqP // | /oSR opS].
by apply/allP=> psi /= /opS->.
Qed.
Lemma orthoPl phi S :
reflect {in S, forall psi, '[phi, psi] = 0} (orthogonal phi S).
Proof.
by rewrite [orthogonal _ S]andbT /=; apply: (iffP allP) => ophiS ? /ophiS/eqP.
Qed.
Arguments orthoPl {phi S}.
Lemma orthogonal_sym : symmetric (@orthogonal _ G).
Proof.
apply: symmetric_from_pre => R S /orthogonalP oRS.
by apply/orthogonalP=> phi psi Rpsi Sphi; rewrite cfdotC oRS ?rmorph0.
Qed.
Lemma orthoPr S psi :
reflect {in S, forall phi, '[phi, psi] = 0} (orthogonal S psi).
Proof.
rewrite orthogonal_sym.
by apply: (iffP orthoPl) => oSpsi phi Sphi; rewrite cfdotC oSpsi ?conjC0.
Qed.
Lemma eq_orthogonal R1 R2 S1 S2 :
R1 =i R2 -> S1 =i S2 -> orthogonal R1 S1 = orthogonal R2 S2.
Proof.
move=> eqR eqS; rewrite [orthogonal _ _](eq_all_r eqR).
by apply: eq_all => psi /=; apply: eq_all_r.
Qed.
Lemma orthogonal_catl R1 R2 S :
orthogonal (R1 ++ R2) S = orthogonal R1 S && orthogonal R2 S.
Proof. exact: all_cat. Qed.
Lemma orthogonal_catr R S1 S2 :
orthogonal R (S1 ++ S2) = orthogonal R S1 && orthogonal R S2.
Proof. by rewrite !(orthogonal_sym R) orthogonal_catl. Qed.
Lemma span_orthogonal S1 S2 phi1 phi2 :
orthogonal S1 S2 -> phi1 \in <<S1>>%VS -> phi2 \in <<S2>>%VS ->
'[phi1, phi2] = 0.
Proof.
move/orthogonalP=> oS12; do 2!move/(@coord_span _ _ _ (in_tuple _))->.
rewrite cfdot_suml big1 // => i _; rewrite cfdot_sumr big1 // => j _.
by rewrite cfdotZl cfdotZr oS12 ?mem_nth ?mulr0.
Qed.
Lemma orthogonal_split S beta :
{X : 'CF(G) & X \in <<S>>%VS &
{Y | [/\ beta = X + Y, '[X, Y] = 0 & orthogonal Y S]}}.
Proof.
suffices [X S_X [Y -> oYS]]:
{X : _ & X \in <<S>>%VS & {Y | beta = X + Y & orthogonal Y S}}.
- exists X => //; exists Y.
by rewrite cfdotC (span_orthogonal oYS) ?memv_span1 ?conjC0.
elim: S beta => [|phi S IHS] beta.
by exists 0; last exists beta; rewrite ?mem0v ?add0r.
have [[U S_U [V -> oVS]] [X S_X [Y -> oYS]]] := (IHS phi, IHS beta).
pose Z := '[Y, V] / '[V] *: V; exists (X + Z).
rewrite /Z -{4}(addKr U V) scalerDr scalerN addrA addrC span_cons.
by rewrite memv_add ?memvB ?memvZ ?memv_line.
exists (Y - Z); first by rewrite addrCA !addrA addrK addrC.
apply/orthoPl=> psi /[!inE] /predU1P[-> | Spsi]; last first.
by rewrite cfdotBl cfdotZl (orthoPl oVS _ Spsi) mulr0 subr0 (orthoPl oYS).
rewrite cfdotBl !cfdotDr (span_orthogonal oYS) // ?memv_span ?mem_head //.
rewrite !cfdotZl (span_orthogonal oVS _ S_U) ?mulr0 ?memv_span ?mem_head //.
have [-> | nzV] := eqVneq V 0; first by rewrite cfdot0r !mul0r subrr.
by rewrite divfK ?cfnorm_eq0 ?subrr.
Qed.
Lemma map_orthogonal M (nu : 'CF(G) -> 'CF(M)) S R (A : {pred 'CF(G)}) :
{in A &, isometry nu} -> {subset S <= A} -> {subset R <= A} ->
orthogonal (map nu S) (map nu R) = orthogonal S R.
Proof.
move=> Inu sSA sRA; rewrite [orthogonal _ _]all_map.
apply: eq_in_all => phi Sphi; rewrite /= all_map.
by apply: eq_in_all => psi Rpsi; rewrite /= Inu ?(sSA phi) ?(sRA psi).
Qed.
Lemma orthogonal_oppr S R : orthogonal S (map -%R R) = orthogonal S R.
Proof.
wlog suffices IH: S R / orthogonal S R -> orthogonal S (map -%R R).
by apply/idP/idP=> /IH; rewrite ?mapK //; apply: opprK.
move/orthogonalP=> oSR; apply/orthogonalP=> xi1 _ Sxi1 /mapP[xi2 Rxi2 ->].
by rewrite cfdotNr oSR ?oppr0.
Qed.
Lemma orthogonal_oppl S R : orthogonal (map -%R S) R = orthogonal S R.
Proof. by rewrite -!(orthogonal_sym R) orthogonal_oppr. Qed.
Lemma pairwise_orthogonalP S :
reflect (uniq (0 :: S)
/\ {in S &, forall phi psi, phi != psi -> '[phi, psi] = 0})
(pairwise_orthogonal S).
Proof.
rewrite /pairwise_orthogonal /=; case notS0: (~~ _); last by right; case.
elim: S notS0 => [|phi S IH] /=; first by left.
rewrite inE eq_sym andbT => /norP[nz_phi /IH{}IH].
have [opS | not_opS] := allP; last first.
right=> [[/andP[notSp _] opS]]; case: not_opS => psi Spsi /=.
by rewrite opS ?mem_head 1?mem_behead // (memPnC notSp).
rewrite (contra (opS _)) /= ?cfnorm_eq0 //.
apply: (iffP IH) => [] [uniqS oSS]; last first.
by split=> //; apply: sub_in2 oSS => psi Spsi; apply: mem_behead.
split=> // psi xi /[!inE] /predU1P[-> // | Spsi].
by case/predU1P=> [-> | /opS] /eqP.
case/predU1P=> [-> _ | Sxi /oSS-> //].
by apply/eqP; rewrite cfdotC conjC_eq0 [_ == 0]opS.
Qed.
Lemma pairwise_orthogonal_cat R S :
pairwise_orthogonal (R ++ S) =
[&& pairwise_orthogonal R, pairwise_orthogonal S & orthogonal R S].
Proof.
rewrite /pairwise_orthogonal mem_cat negb_or -!andbA; do !bool_congr.
elim: R => [|phi R /= ->]; rewrite ?andbT // orthogonal_cons all_cat -!andbA /=.
by do !bool_congr.
Qed.
Lemma eq_pairwise_orthogonal R S :
perm_eq R S -> pairwise_orthogonal R = pairwise_orthogonal S.
Proof.
apply: catCA_perm_subst R S => R S S'.
rewrite !pairwise_orthogonal_cat !orthogonal_catr (orthogonal_sym R S) -!andbA.
by do !bool_congr.
Qed.
Lemma sub_pairwise_orthogonal S1 S2 :
{subset S1 <= S2} -> uniq S1 ->
pairwise_orthogonal S2 -> pairwise_orthogonal S1.
Proof.
move=> sS12 uniqS1 /pairwise_orthogonalP[/andP[notS2_0 _] oS2].
apply/pairwise_orthogonalP; rewrite /= (contra (sS12 0)) //.
by split=> //; apply: sub_in2 oS2.
Qed.
Lemma orthogonal_free S : pairwise_orthogonal S -> free S.
Proof.
case/pairwise_orthogonalP=> [/=/andP[notS0 uniqS] oSS].
rewrite -(in_tupleE S); apply/freeP => a aS0 i.
have S_i: S`_i \in S by apply: mem_nth.
have /eqP: '[S`_i, 0]_G = 0 := cfdot0r _.
rewrite -{2}aS0 raddf_sum /= (bigD1 i) //= big1 => [|j neq_ji]; last 1 first.
by rewrite cfdotZr oSS ?mulr0 ?mem_nth // eq_sym nth_uniq.
rewrite addr0 cfdotZr mulf_eq0 conjC_eq0 cfnorm_eq0.
by case/pred2P=> // Si0; rewrite -Si0 S_i in notS0.
Qed.
Lemma filter_pairwise_orthogonal S p :
pairwise_orthogonal S -> pairwise_orthogonal (filter p S).
Proof.
move=> orthoS; apply: sub_pairwise_orthogonal (orthoS).
exact: mem_subseq (filter_subseq p S).
exact/filter_uniq/free_uniq/orthogonal_free.
Qed.
Lemma orthonormal_not0 S : orthonormal S -> 0 \notin S.
Proof.
by case/andP=> /allP S1 _; rewrite (contra (S1 _)) //= cfdot0r eq_sym oner_eq0.
Qed.
Lemma orthonormalE S :
orthonormal S = all [pred phi | '[phi] == 1] S && pairwise_orthogonal S.
Proof. by rewrite -(andb_idl (@orthonormal_not0 S)) andbCA. Qed.
Lemma orthonormal_orthogonal S : orthonormal S -> pairwise_orthogonal S.
Proof. by rewrite orthonormalE => /andP[_]. Qed.
Lemma orthonormal_cat R S :
orthonormal (R ++ S) = [&& orthonormal R, orthonormal S & orthogonal R S].
Proof.
rewrite !orthonormalE pairwise_orthogonal_cat all_cat -!andbA.
by do !bool_congr.
Qed.
Lemma eq_orthonormal R S : perm_eq R S -> orthonormal R = orthonormal S.
Proof.
move=> eqRS; rewrite !orthonormalE (eq_all_r (perm_mem eqRS)).
by rewrite (eq_pairwise_orthogonal eqRS).
Qed.
Lemma orthonormal_free S : orthonormal S -> free S.
Proof. by move/orthonormal_orthogonal/orthogonal_free. Qed.
Lemma orthonormalP S :
reflect (uniq S /\ {in S &, forall phi psi, '[phi, psi]_G = (phi == psi)%:R})
(orthonormal S).
Proof.
rewrite orthonormalE; have [/= normS | not_normS] := allP; last first.
by right=> [[_ o1S]]; case: not_normS => phi Sphi; rewrite /= o1S ?eqxx.
apply: (iffP (pairwise_orthogonalP S)) => [] [uniqS oSS].
split=> // [|phi psi]; first by case/andP: uniqS.
by have [-> _ /normS/eqP | /oSS] := eqVneq.
split=> // [|phi psi Sphi Spsi /negbTE]; last by rewrite oSS // => ->.
by rewrite /= (contra (normS _)) // cfdot0r eq_sym oner_eq0.
Qed.
Lemma sub_orthonormal S1 S2 :
{subset S1 <= S2} -> uniq S1 -> orthonormal S2 -> orthonormal S1.
Proof.
move=> sS12 uniqS1 /orthonormalP[_ oS1].
by apply/orthonormalP; split; last apply: sub_in2 sS12 _ _.
Qed.
Lemma orthonormal2P phi psi :
reflect [/\ '[phi, psi] = 0, '[phi] = 1 & '[psi] = 1]
(orthonormal [:: phi; psi]).
Proof.
rewrite /orthonormal /= !andbT andbC.
by apply: (iffP and3P) => [] []; do 3!move/eqP->.
Qed.
Lemma conjC_pair_orthogonal S chi :
cfConjC_closed S -> ~~ has cfReal S -> pairwise_orthogonal S -> chi \in S ->
pairwise_orthogonal (chi :: chi^*%CF).
Proof.
move=> ccS /hasPn nrS oSS Schi; apply: sub_pairwise_orthogonal oSS.
by apply/allP; rewrite /= Schi ccS.
by rewrite /= inE eq_sym nrS.
Qed.
Lemma cfdot_real_conjC phi psi : cfReal phi -> '[phi, psi^*]_G = '[phi, psi]^*.
Proof. by rewrite -cfdot_conjC => /eqcfP->. Qed.
Lemma extend_cfConjC_subset S X phi :
cfConjC_closed S -> ~~ has cfReal S -> phi \in S -> phi \notin X ->
cfConjC_subset X S -> cfConjC_subset [:: phi, phi^* & X]%CF S.
Proof.
move=> ccS nrS Sphi X'phi [uniqX /allP-sXS ccX].
split; last 1 [by apply/allP; rewrite /= Sphi ccS | apply/allP]; rewrite /= inE.
by rewrite negb_or X'phi eq_sym (hasPn nrS) // (contra (ccX _)) ?cfConjCK.
by rewrite cfConjCK !mem_head orbT; apply/allP=> xi Xxi; rewrite !inE ccX ?orbT.
Qed.
(* Note: other isometry lemmas, and the dot product lemmas for orthogonal *)
(* and orthonormal sequences are in vcharacter, because we need the 'Z[S] *)
(* notation for the isometry domains. Alternatively, this could be moved to *)
(* cfun. *)
End DotProduct.
Arguments orthoP {gT G phi psi}.
Arguments orthoPl {gT G phi S}.
Arguments orthoPr {gT G S psi}.
Arguments orthogonalP {gT G S R}.
Arguments pairwise_orthogonalP {gT G S}.
Arguments orthonormalP {gT G S}.
Section CfunOrder.
Variables (gT : finGroupType) (G : {group gT}) (phi : 'CF(G)).
Lemma dvdn_cforderP n :
reflect {in G, forall x, phi x ^+ n = 1} (#[phi]%CF %| n)%N.
Proof.
apply: (iffP (dvdn_biglcmP _ _ _)); rewrite genGid => phiG1 x Gx.
by apply/eqP; rewrite -dvdn_orderC phiG1.
by rewrite dvdn_orderC phiG1.
Qed.
Lemma dvdn_cforder n : (#[phi]%CF %| n) = (phi ^+ n == 1).
Proof.
apply/dvdn_cforderP/eqP=> phi_n_1 => [|x Gx].
by apply/cfun_inP=> x Gx; rewrite exp_cfunE // cfun1E Gx phi_n_1.
by rewrite -exp_cfunE // phi_n_1 // cfun1E Gx.
Qed.
Lemma exp_cforder : phi ^+ #[phi]%CF = 1.
Proof. by apply/eqP; rewrite -dvdn_cforder. Qed.
End CfunOrder.
Arguments dvdn_cforderP {gT G phi n}.
Section MorphOrder.
Variables (aT rT : finGroupType) (G : {group aT}) (R : {group rT}).
Variable f : {rmorphism 'CF(G) -> 'CF(R)}.
Lemma cforder_rmorph phi : #[f phi]%CF %| #[phi]%CF.
Proof. by rewrite dvdn_cforder -rmorphXn exp_cforder rmorph1. Qed.
Lemma cforder_inj_rmorph phi : injective f -> #[f phi]%CF = #[phi]%CF.
Proof.
move=> inj_f; apply/eqP; rewrite eqn_dvd cforder_rmorph dvdn_cforder /=.
by rewrite -(rmorph_eq1 _ inj_f) rmorphXn exp_cforder.
Qed.
End MorphOrder.
Section BuildIsometries.
Variable (gT : finGroupType) (L G : {group gT}).
Implicit Types (phi psi xi : 'CF(L)) (R S : seq 'CF(L)).
Implicit Types (U : {pred 'CF(L)}) (W : {pred 'CF(G)}).
Lemma sub_iso_to U1 U2 W1 W2 tau :
{subset U2 <= U1} -> {subset W1 <= W2} ->
{in U1, isometry tau, to W1} -> {in U2, isometry tau, to W2}.
Proof.
by move=> sU sW [Itau Wtau]; split=> [|u /sU/Wtau/sW //]; apply: sub_in2 Itau.
Qed.
Lemma isometry_of_free S f :
free S -> {in S &, isometry f} ->
{tau : {linear 'CF(L) -> 'CF(G)} |
{in S, tau =1 f} & {in <<S>>%VS &, isometry tau}}.
Proof.
move=> freeS If; have defS := free_span freeS.
have [tau /(_ freeS (size_map f S))Dtau] := linear_of_free S (map f S).
have{} Dtau: {in S, tau =1 f}.
by move=> _ /(nthP 0)[i ltiS <-]; rewrite -!(nth_map 0 0) ?Dtau.
exists tau => // _ _ /defS[a -> _] /defS[b -> _].
rewrite !{1}linear_sum !{1}cfdot_suml; apply/eq_big_seq=> xi1 Sxi1.
rewrite !{1}cfdot_sumr; apply/eq_big_seq=> xi2 Sxi2.
by rewrite !linearZ /= !Dtau // !cfdotZl !cfdotZr If.
Qed.
Lemma isometry_of_cfnorm S tauS :
pairwise_orthogonal S -> pairwise_orthogonal tauS ->
map cfnorm tauS = map cfnorm S ->
{tau : {linear 'CF(L) -> 'CF(G)} | map tau S = tauS
& {in <<S>>%VS &, isometry tau}}.
Proof.
move=> oS oT eq_nST; have freeS := orthogonal_free oS.
have eq_sz: size tauS = size S by have:= congr1 size eq_nST; rewrite !size_map.
have [tau defT] := linear_of_free S tauS; rewrite -[S]/(tval (in_tuple S)).
exists tau => [|u v /coord_span-> /coord_span->]; rewrite ?raddf_sum ?defT //=.
apply: eq_bigr => i _ /=; rewrite linearZ !cfdotZr !cfdot_suml; congr (_ * _).
apply: eq_bigr => j _ /=; rewrite linearZ !cfdotZl; congr (_ * _).
rewrite -!(nth_map 0 0 tau) ?{}defT //; have [-> | neq_ji] := eqVneq j i.
by rewrite -!['[_]](nth_map 0 0 cfnorm) ?eq_sz // eq_nST.
have{oS} [/=/andP[_ uS] oS] := pairwise_orthogonalP oS.
have{oT} [/=/andP[_ uT] oT] := pairwise_orthogonalP oT.
by rewrite oS ?oT ?mem_nth ?nth_uniq ?eq_sz.
Qed.
Lemma isometry_raddf_inj U (tau : {additive 'CF(L) -> 'CF(G)}) :
{in U &, isometry tau} -> {in U &, forall u v, u - v \in U} ->
{in U &, injective tau}.
Proof.
move=> Itau linU phi psi Uphi Upsi /eqP; rewrite -subr_eq0 -raddfB.
by rewrite -cfnorm_eq0 Itau ?linU // cfnorm_eq0 subr_eq0 => /eqP.
Qed.
Lemma opp_isometry : @isometry _ _ G G -%R.
Proof. by move=> x y; rewrite cfdotNl cfdotNr opprK. Qed.
End BuildIsometries.
Section Restrict.
Variables (gT : finGroupType) (A B : {set gT}).
Local Notation H := <<A>>.
Local Notation G := <<B>>.
Fact cfRes_subproof (phi : 'CF(B)) :
is_class_fun H [ffun x => phi (if H \subset G then x else 1%g) *+ (x \in H)].
Proof.
apply: intro_class_fun => /= [x y Hx Hy | x /negbTE/=-> //].
by rewrite Hx (groupJ Hx) //; case: subsetP => // sHG; rewrite cfunJgen ?sHG.
Qed.
Definition cfRes phi := Cfun 1 (cfRes_subproof phi).
Lemma cfResE phi : A \subset B -> {in A, cfRes phi =1 phi}.
Proof. by move=> sAB x Ax; rewrite cfunElock mem_gen ?genS. Qed.
Lemma cfRes1 phi : cfRes phi 1%g = phi 1%g.
Proof. by rewrite cfunElock if_same group1. Qed.
Lemma cfRes_is_linear : linear cfRes.
Proof.
by move=> a phi psi; apply/cfunP=> x; rewrite !cfunElock mulrnAr mulrnDl.
Qed.
HB.instance Definition _ := GRing.isSemilinear.Build algC _ _ _ cfRes
(GRing.semilinear_linear cfRes_is_linear).
Lemma cfRes_cfun1 : cfRes 1 = 1.
Proof.
apply: cfun_in_genP => x Hx; rewrite cfunElock Hx !cfun1Egen Hx.
by case: subsetP => [-> // | _]; rewrite group1.
Qed.
Lemma cfRes_is_monoid_morphism : monoid_morphism cfRes.
Proof.
split=> [|phi psi]; [exact: cfRes_cfun1 | apply/cfunP=> x].
by rewrite !cfunElock mulrnAr mulrnAl -mulrnA mulnb andbb.
Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfRes_is_monoid_morphism` instead")]
Definition cfRes_is_multiplicative :=
(fun g => (g.2,g.1)) cfRes_is_monoid_morphism.
HB.instance Definition _ := GRing.isMonoidMorphism.Build _ _ cfRes
cfRes_is_monoid_morphism.
End Restrict.
Arguments cfRes {gT} A%_g {B%_g} phi%_CF.
Notation "''Res[' H , G ]" := (@cfRes _ H G) (only parsing) : ring_scope.
Notation "''Res[' H ]" := 'Res[H, _] : ring_scope.
Notation "''Res'" := 'Res[_] (only parsing) : ring_scope.
Section MoreRestrict.
Variables (gT : finGroupType) (G H : {group gT}).
Implicit Types (A : {set gT}) (phi : 'CF(G)).
Lemma cfResEout phi : ~~ (H \subset G) -> 'Res[H] phi = (phi 1%g)%:A.
Proof.
move/negPf=> not_sHG; apply/cfunP=> x.
by rewrite cfunE cfun1E mulr_natr cfunElock !genGid not_sHG.
Qed.
Lemma cfResRes A phi :
A \subset H -> H \subset G -> 'Res[A] ('Res[H] phi) = 'Res[A] phi.
Proof.
move=> sAH sHG; apply/cfunP=> x; rewrite !cfunElock !genGid !gen_subG sAH sHG.
by rewrite (subset_trans sAH) // -mulrnA mulnb -in_setI (setIidPr _) ?gen_subG.
Qed.
Lemma cfRes_id A psi : 'Res[A] psi = psi.
Proof. by apply/cfun_in_genP=> x Ax; rewrite cfunElock Ax subxx. Qed.
Lemma sub_cfker_Res A phi :
A \subset H -> A \subset cfker phi -> A \subset cfker ('Res[H, G] phi).
Proof.
move=> sAH kerA; apply/subsetP=> x Ax; have Hx := subsetP sAH x Ax.
rewrite inE Hx; apply/forallP=> y; rewrite !cfunElock !genGid groupMl //.
by rewrite !(fun_if phi) cfkerMl // (subsetP kerA).
Qed.
Lemma eq_cfker_Res phi : H \subset cfker phi -> cfker ('Res[H, G] phi) = H.
Proof. by move=> kH; apply/eqP; rewrite eqEsubset cfker_sub sub_cfker_Res. Qed.
Lemma cfRes_sub_ker phi : H \subset cfker phi -> 'Res[H, G] phi = (phi 1%g)%:A.
Proof.
move=> kerHphi; have sHG := subset_trans kerHphi (cfker_sub phi).
apply/cfun_inP=> x Hx; have ker_x := subsetP kerHphi x Hx.
by rewrite cfResE // cfunE cfun1E Hx mulr1 cfker1.
Qed.
Lemma cforder_Res phi : #['Res[H] phi]%CF %| #[phi]%CF.
Proof. exact: cforder_rmorph. Qed.
End MoreRestrict.
Section Morphim.
Variables (aT rT : finGroupType) (D : {group aT}) (f : {morphism D >-> rT}).
Section Main.
Variable G : {group aT}.
Implicit Type phi : 'CF(f @* G).
Fact cfMorph_subproof phi :
is_class_fun <<G>>
[ffun x => phi (if G \subset D then f x else 1%g) *+ (x \in G)].
Proof.
rewrite genGid; apply: intro_class_fun => [x y Gx Gy | x /negPf-> //].
rewrite Gx groupJ //; case subsetP => // sGD.
by rewrite morphJ ?cfunJ ?mem_morphim ?sGD.
Qed.
Definition cfMorph phi := Cfun 1 (cfMorph_subproof phi).
Lemma cfMorphE phi x : G \subset D -> x \in G -> cfMorph phi x = phi (f x).
Proof. by rewrite cfunElock => -> ->. Qed.
Lemma cfMorph1 phi : cfMorph phi 1%g = phi 1%g.
Proof. by rewrite cfunElock morph1 if_same group1. Qed.
Lemma cfMorphEout phi : ~~ (G \subset D) -> cfMorph phi = (phi 1%g)%:A.
Proof.
move/negPf=> not_sGD; apply/cfunP=> x; rewrite cfunE cfun1E mulr_natr.
by rewrite cfunElock not_sGD.
Qed.
Lemma cfMorph_cfun1 : cfMorph 1 = 1.
Proof.
apply/cfun_inP=> x Gx; rewrite cfunElock !cfun1E Gx.
by case: subsetP => [sGD | _]; rewrite ?group1 // mem_morphim ?sGD.
Qed.
Fact cfMorph_is_linear : linear cfMorph.
Proof.
by move=> a phi psi; apply/cfunP=> x; rewrite !cfunElock mulrnAr -mulrnDl.
Qed.
HB.instance Definition _ := GRing.isSemilinear.Build algC _ _ _ cfMorph
(GRing.semilinear_linear cfMorph_is_linear).
Fact cfMorph_is_monoid_morphism : monoid_morphism cfMorph.
Proof.
split=> [|phi psi]; [exact: cfMorph_cfun1 | apply/cfunP=> x].
by rewrite !cfunElock mulrnAr mulrnAl -mulrnA mulnb andbb.
Qed.
HB.instance Definition _ := GRing.isMonoidMorphism.Build _ _ cfMorph
cfMorph_is_monoid_morphism.
Hypothesis sGD : G \subset D.
Lemma cfMorph_inj : injective cfMorph.
Proof.
move=> phi1 phi2 eq_phi; apply/cfun_inP=> _ /morphimP[x Dx Gx ->].
by rewrite -!cfMorphE // eq_phi.
Qed.
Lemma cfMorph_eq1 phi : (cfMorph phi == 1) = (phi == 1).
Proof. exact/rmorph_eq1/cfMorph_inj. Qed.
Lemma cfker_morph phi : cfker (cfMorph phi) = G :&: f @*^-1 (cfker phi).
Proof.
apply/setP=> x /[!inE]; apply: andb_id2l => Gx.
have Dx := subsetP sGD x Gx; rewrite Dx mem_morphim //=.
apply/forallP/forallP=> Kx y.
have [{y} /morphimP[y Dy Gy ->] | fG'y] := boolP (y \in f @* G).
by rewrite -morphM // -!(cfMorphE phi) ?groupM.
by rewrite !cfun0 ?groupMl // mem_morphim.
have [Gy | G'y] := boolP (y \in G); last by rewrite !cfun0 ?groupMl.
by rewrite !cfMorphE ?groupM ?morphM // (subsetP sGD).
Qed.
Lemma cfker_morph_im phi : f @* cfker (cfMorph phi) = cfker phi.
Proof. by rewrite cfker_morph // morphim_setIpre (setIidPr (cfker_sub _)). Qed.
Lemma sub_cfker_morph phi (A : {set aT}) :
(A \subset cfker (cfMorph phi)) = (A \subset G) && (f @* A \subset cfker phi).
Proof.
rewrite cfker_morph // subsetI; apply: andb_id2l => sAG.
by rewrite sub_morphim_pre // (subset_trans sAG).
Qed.
Lemma sub_morphim_cfker phi (A : {set aT}) :
A \subset G -> (f @* A \subset cfker phi) = (A \subset cfker (cfMorph phi)).
Proof. by move=> sAG; rewrite sub_cfker_morph ?sAG. Qed.
Lemma cforder_morph phi : #[cfMorph phi]%CF = #[phi]%CF.
Proof. exact/cforder_inj_rmorph/cfMorph_inj. Qed.
End Main.
Lemma cfResMorph (G H : {group aT}) (phi : 'CF(f @* G)) :
H \subset G -> G \subset D -> 'Res (cfMorph phi) = cfMorph ('Res[f @* H] phi).
Proof.
move=> sHG sGD; have sHD := subset_trans sHG sGD.
apply/cfun_inP=> x Hx; have [Gx Dx] := (subsetP sHG x Hx, subsetP sHD x Hx).
by rewrite !(cfMorphE, cfResE) ?morphimS ?mem_morphim //.
Qed.
End Morphim.
Prenex Implicits cfMorph.
Section Isomorphism.
Variables (aT rT : finGroupType) (G : {group aT}) (f : {morphism G >-> rT}).
Variable R : {group rT}.
Hypothesis isoGR : isom G R f.
Let defR := isom_im isoGR.
Local Notation G1 := (isom_inv isoGR @* R).
Let defG : G1 = G := isom_im (isom_sym isoGR).
Fact cfIsom_key : unit. Proof. by []. Qed.
Definition cfIsom :=
locked_with cfIsom_key (cfMorph \o 'Res[G1] : 'CF(G) -> 'CF(R)).
Canonical cfIsom_unlockable := [unlockable of cfIsom].
Lemma cfIsomE phi (x : aT : finType) : x \in G -> cfIsom phi (f x) = phi x.
Proof.
move=> Gx; rewrite unlock cfMorphE //= /restrm ?defG ?cfRes_id ?invmE //.
by rewrite -defR mem_morphim.
Qed.
Lemma cfIsom1 phi : cfIsom phi 1%g = phi 1%g.
Proof. by rewrite -(morph1 f) cfIsomE. Qed.
Lemma cfIsom_is_zmod_morphism : zmod_morphism cfIsom.
Proof. rewrite unlock; exact: raddfB. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfIsom_is_zmod_morphism` instead")]
Definition cfIsom_is_additive := cfIsom_is_zmod_morphism.
Lemma cfIsom_is_monoid_morphism : monoid_morphism cfIsom.
Proof. rewrite unlock; exact: (rmorph1 _, rmorphM _). Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfIsom_is_monoid_morphism` instead")]
Definition cfIsom_is_multiplicative :=
(fun g => (g.2,g.1)) cfIsom_is_monoid_morphism.
Lemma cfIsom_is_scalable : scalable cfIsom.
Proof. rewrite unlock; exact: linearZ_LR. Qed.
HB.instance Definition _ := GRing.isZmodMorphism.Build _ _ cfIsom cfIsom_is_zmod_morphism.
HB.instance Definition _ := GRing.isMonoidMorphism.Build _ _ cfIsom
cfIsom_is_monoid_morphism.
HB.instance Definition _ := GRing.isScalable.Build _ _ _ _ cfIsom
cfIsom_is_scalable.
Lemma cfIsom_cfun1 : cfIsom 1 = 1. Proof. exact: rmorph1. Qed.
Lemma cfker_isom phi : cfker (cfIsom phi) = f @* cfker phi.
Proof.
rewrite unlock cfker_morph // defG cfRes_id morphpre_restrm morphpre_invm.
by rewrite -defR !morphimIim.
Qed.
End Isomorphism.
Prenex Implicits cfIsom.
Section InvMorphism.
Variables (aT rT : finGroupType) (G : {group aT}) (f : {morphism G >-> rT}).
Variable R : {group rT}.
Hypothesis isoGR : isom G R f.
Lemma cfIsomK : cancel (cfIsom isoGR) (cfIsom (isom_sym isoGR)).
Proof.
move=> phi; apply/cfun_inP=> x Gx; rewrite -{1}(invmE (isom_inj isoGR) Gx).
by rewrite !cfIsomE // -(isom_im isoGR) mem_morphim.
Qed.
Lemma cfIsomKV : cancel (cfIsom (isom_sym isoGR)) (cfIsom isoGR).
Proof.
move=> phi; apply/cfun_inP=> y Ry; pose injGR := isom_inj isoGR.
rewrite -{1}[y](invmK injGR) ?(isom_im isoGR) //.
suffices /morphpreP[fGy Gf'y]: y \in invm injGR @*^-1 G by rewrite !cfIsomE.
by rewrite morphpre_invm (isom_im isoGR).
Qed.
Lemma cfIsom_inj : injective (cfIsom isoGR). Proof. exact: can_inj cfIsomK. Qed.
Lemma cfIsom_eq1 phi : (cfIsom isoGR phi == 1) = (phi == 1).
Proof. exact/rmorph_eq1/cfIsom_inj. Qed.
Lemma cforder_isom phi : #[cfIsom isoGR phi]%CF = #[phi]%CF.
Proof. exact: cforder_inj_rmorph cfIsom_inj. Qed.
End InvMorphism.
Arguments cfIsom_inj {aT rT G f R} isoGR [phi1 phi2] : rename.
Section Coset.
Variables (gT : finGroupType) (G : {group gT}) (B : {set gT}).
Implicit Type rT : finGroupType.
Local Notation H := <<B>>%g.
Definition cfMod : 'CF(G / B) -> 'CF(G) := cfMorph.
Definition ffun_Quo (phi : 'CF(G)) :=
[ffun Hx : coset_of B =>
phi (if B \subset cfker phi then repr Hx else 1%g) *+ (Hx \in G / B)%g].
Fact cfQuo_subproof phi : is_class_fun <<G / B>> (ffun_Quo phi).
Proof.
rewrite genGid; apply: intro_class_fun => [|Hx /negPf-> //].
move=> _ _ /morphimP[x Nx Gx ->] /morphimP[z Nz Gz ->].
rewrite -morphJ ?mem_morphim ?val_coset_prim ?groupJ //= -gen_subG.
case: subsetP => // KphiH; do 2!case: repr_rcosetP => _ /KphiH/cfkerMl->.
by rewrite cfunJ.
Qed.
Definition cfQuo phi := Cfun 1 (cfQuo_subproof phi).
Local Notation "phi / 'B'" := (cfQuo phi)
(at level 40, left associativity) : cfun_scope.
Local Notation "phi %% 'B'" := (cfMod phi) (at level 40) : cfun_scope.
(* We specialize the cfMorph lemmas to cfMod by strengthening the domain *)
(* condition G \subset 'N(H) to H <| G; the cfMorph lemmas can be used if the *)
(* stronger results are needed. *)
Lemma cfModE phi x : B <| G -> x \in G -> (phi %% B)%CF x = phi (coset B x).
Proof. by move/normal_norm=> nBG; apply: cfMorphE. Qed.
Lemma cfMod1 phi : (phi %% B)%CF 1%g = phi 1%g. Proof. exact: cfMorph1. Qed.
HB.instance Definition _ := GRing.LRMorphism.on cfMod.
Lemma cfMod_cfun1 : (1 %% B)%CF = 1. Proof. exact: rmorph1. Qed.
Lemma cfker_mod phi : B <| G -> B \subset cfker (phi %% B).
Proof.
case/andP=> sBG nBG; rewrite cfker_morph // subsetI sBG.
apply: subset_trans _ (ker_sub_pre _ _); rewrite ker_coset_prim subsetI.
by rewrite (subset_trans sBG nBG) sub_gen.
Qed.
(* Note that cfQuo is nondegenerate even when G does not normalize B. *)
Lemma cfQuoEnorm (phi : 'CF(G)) x :
B \subset cfker phi -> x \in 'N_G(B) -> (phi / B)%CF (coset B x) = phi x.
Proof.
rewrite cfunElock -gen_subG => sHK /setIP[Gx nHx]; rewrite sHK /=.
rewrite mem_morphim // val_coset_prim //.
by case: repr_rcosetP => _ /(subsetP sHK)/cfkerMl->.
Qed.
Lemma cfQuoE (phi : 'CF(G)) x :
B <| G -> B \subset cfker phi -> x \in G -> (phi / B)%CF (coset B x) = phi x.
Proof. by case/andP=> _ nBG sBK Gx; rewrite cfQuoEnorm // (setIidPl _). Qed.
Lemma cfQuo1 (phi : 'CF(G)) : (phi / B)%CF 1%g = phi 1%g.
Proof. by rewrite cfunElock repr_coset1 group1 if_same. Qed.
Lemma cfQuoEout (phi : 'CF(G)) :
~~ (B \subset cfker phi) -> (phi / B)%CF = (phi 1%g)%:A.
Proof.
move/negPf=> not_kerB; apply/cfunP=> x; rewrite cfunE cfun1E mulr_natr.
by rewrite cfunElock not_kerB.
Qed.
(* cfQuo is only linear on the class functions that have H in their kernel. *)
Lemma cfQuo_cfun1 : (1 / B)%CF = 1.
Proof.
apply/cfun_inP=> Hx G_Hx; rewrite cfunElock !cfun1E G_Hx cfker_cfun1 -gen_subG.
have [x nHx Gx ->] := morphimP G_Hx.
case: subsetP=> [sHG | _]; last by rewrite group1.
by rewrite val_coset_prim //; case: repr_rcosetP => y /sHG/groupM->.
Qed.
(* Cancellation properties *)
Lemma cfModK : B <| G -> cancel cfMod cfQuo.
Proof.
move=> nsBG phi; apply/cfun_inP=> _ /morphimP[x Nx Gx ->] //.
by rewrite cfQuoE ?cfker_mod ?cfModE.
Qed.
Lemma cfQuoK :
B <| G -> forall phi, B \subset cfker phi -> (phi / B %% B)%CF = phi.
Proof.
by move=> nsHG phi sHK; apply/cfun_inP=> x Gx; rewrite cfModE ?cfQuoE.
Qed.
Lemma cfMod_eq1 psi : B <| G -> (psi %% B == 1)%CF = (psi == 1).
Proof. by move/cfModK/can_eq <-; rewrite rmorph1. Qed.
Lemma cfQuo_eq1 phi :
B <| G -> B \subset cfker phi -> (phi / B == 1)%CF = (phi == 1).
Proof. by move=> nsBG kerH; rewrite -cfMod_eq1 // cfQuoK. Qed.
End Coset.
Arguments cfQuo {gT G%_G} B%_g phi%_CF.
Arguments cfMod {gT G%_G B%_g} phi%_CF.
Notation "phi / H" := (cfQuo H phi) : cfun_scope.
Notation "phi %% H" := (@cfMod _ _ H phi) : cfun_scope.
Section MoreCoset.
Variables (gT : finGroupType) (G : {group gT}).
Implicit Types (H K : {group gT}) (phi : 'CF(G)).
Lemma cfResMod H K (psi : 'CF(G / K)) :
H \subset G -> K <| G -> ('Res (psi %% K) = 'Res[H / K] psi %% K)%CF.
Proof. by move=> sHG /andP[_]; apply: cfResMorph. Qed.
Lemma quotient_cfker_mod (A : {set gT}) K (psi : 'CF(G / K)) :
K <| G -> (cfker (psi %% K) / K)%g = cfker psi.
Proof. by case/andP=> _ /cfker_morph_im <-. Qed.
Lemma sub_cfker_mod (A : {set gT}) K (psi : 'CF(G / K)) :
K <| G -> A \subset 'N(K) ->
(A \subset cfker (psi %% K)) = (A / K \subset cfker psi)%g.
Proof.
by move=> nsKG nKA; rewrite -(quotientSGK nKA) ?quotient_cfker_mod// cfker_mod.
Qed.
Lemma cfker_quo H phi :
H <| G -> H \subset cfker (phi) -> cfker (phi / H) = (cfker phi / H)%g.
Proof.
move=> nsHG /cfQuoK {2}<- //; have [sHG nHG] := andP nsHG.
by rewrite cfker_morph 1?quotientGI // cosetpreK (setIidPr _) ?cfker_sub.
Qed.
Lemma cfQuoEker phi x :
x \in G -> (phi / cfker phi)%CF (coset (cfker phi) x) = phi x.
Proof. by move/cfQuoE->; rewrite ?cfker_normal. Qed.
Lemma cfaithful_quo phi : cfaithful (phi / cfker phi).
Proof. by rewrite cfaithfulE cfker_quo ?cfker_normal ?trivg_quotient. Qed.
(* Note that there is no requirement that K be normal in H or G. *)
Lemma cfResQuo H K phi :
K \subset cfker phi -> K \subset H -> H \subset G ->
('Res[H / K] (phi / K) = 'Res[H] phi / K)%CF.
Proof.
move=> kerK sKH sHG; apply/cfun_inP=> xb Hxb; rewrite cfResE ?quotientS //.
have{xb Hxb} [x nKx Hx ->] := morphimP Hxb.
by rewrite !cfQuoEnorm ?cfResE// 1?inE ?Hx ?(subsetP sHG)// sub_cfker_Res.
Qed.
Lemma cfQuoInorm K phi :
K \subset cfker phi -> (phi / K)%CF = 'Res ('Res['N_G(K)] phi / K)%CF.
Proof.
move=> kerK; rewrite -cfResQuo ?subsetIl ?quotientInorm ?cfRes_id //.
by rewrite subsetI normG (subset_trans kerK) ?cfker_sub.
Qed.
Lemma cforder_mod H (psi : 'CF(G / H)) : H <| G -> #[psi %% H]%CF = #[psi]%CF.
Proof. by move/cfModK/can_inj/cforder_inj_rmorph->. Qed.
Lemma cforder_quo H phi :
H <| G -> H \subset cfker phi -> #[phi / H]%CF = #[phi]%CF.
Proof. by move=> nsHG kerHphi; rewrite -cforder_mod ?cfQuoK. Qed.
End MoreCoset.
Section Product.
Variable (gT : finGroupType) (G : {group gT}).
Lemma cfunM_onI A B phi psi :
phi \in 'CF(G, A) -> psi \in 'CF(G, B) -> phi * psi \in 'CF(G, A :&: B).
Proof.
rewrite !cfun_onE => Aphi Bpsi; apply/subsetP=> x; rewrite !inE cfunE mulf_eq0.
by case/norP=> /(subsetP Aphi)-> /(subsetP Bpsi).
Qed.
Lemma cfunM_on A phi psi :
phi \in 'CF(G, A) -> psi \in 'CF(G, A) -> phi * psi \in 'CF(G, A).
Proof. by move=> Aphi Bpsi; rewrite -[A]setIid cfunM_onI. Qed.
End Product.
Section SDproduct.
Variables (gT : finGroupType) (G K H : {group gT}).
Hypothesis defG : K ><| H = G.
Fact cfSdprodKey : unit. Proof. by []. Qed.
Definition cfSdprod :=
locked_with cfSdprodKey
(cfMorph \o cfIsom (tagged (sdprod_isom defG)) : 'CF(H) -> 'CF(G)).
Canonical cfSdprod_unlockable := [unlockable of cfSdprod].
Lemma cfSdprod_is_zmod_morphism : zmod_morphism cfSdprod.
Proof. rewrite unlock; exact: raddfB. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfSdprod_is_zmod_morphism` instead")]
Definition cfSdprod_is_additive := cfSdprod_is_zmod_morphism.
Lemma cfSdprod_is_monoid_morphism : monoid_morphism cfSdprod.
Proof. rewrite unlock; exact: (rmorph1 _, rmorphM _). Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfSdprod_is_monoid_morphism` instead")]
Definition cfSdprod_is_multiplicative :=
(fun g => (g.2,g.1)) cfSdprod_is_monoid_morphism.
Lemma cfSdprod_is_scalable : scalable cfSdprod.
Proof. rewrite unlock; exact: linearZ_LR. Qed.
HB.instance Definition _ := GRing.isZmodMorphism.Build _ _ cfSdprod cfSdprod_is_zmod_morphism.
HB.instance Definition _ := GRing.isMonoidMorphism.Build _ _ cfSdprod
cfSdprod_is_monoid_morphism.
HB.instance Definition _ := GRing.isScalable.Build _ _ _ _ cfSdprod
cfSdprod_is_scalable.
Lemma cfSdprod1 phi : cfSdprod phi 1%g = phi 1%g.
Proof. by rewrite unlock /= cfMorph1 cfIsom1. Qed.
Let nsKG : K <| G. Proof. by have [] := sdprod_context defG. Qed.
Let sHG : H \subset G. Proof. by have [] := sdprod_context defG. Qed.
Let sKG : K \subset G. Proof. by have [] := andP nsKG. Qed.
Lemma cfker_sdprod phi : K \subset cfker (cfSdprod phi).
Proof. by rewrite unlock_with cfker_mod. Qed.
Lemma cfSdprodEr phi : {in H, cfSdprod phi =1 phi}.
Proof. by move=> y Hy; rewrite unlock cfModE ?cfIsomE ?(subsetP sHG). Qed.
Lemma cfSdprodE phi : {in K & H, forall x y, cfSdprod phi (x * y)%g = phi y}.
Proof.
by move=> x y Kx Hy; rewrite /= cfkerMl ?(subsetP (cfker_sdprod _)) ?cfSdprodEr.
Qed.
Lemma cfSdprodK : cancel cfSdprod 'Res[H].
Proof. by move=> phi; apply/cfun_inP=> x Hx; rewrite cfResE ?cfSdprodEr. Qed.
Lemma cfSdprod_inj : injective cfSdprod. Proof. exact: can_inj cfSdprodK. Qed.
Lemma cfSdprod_eq1 phi : (cfSdprod phi == 1) = (phi == 1).
Proof. exact: rmorph_eq1 cfSdprod_inj. Qed.
Lemma cfRes_sdprodK phi : K \subset cfker phi -> cfSdprod ('Res[H] phi) = phi.
Proof.
move=> kerK; apply/cfun_inP=> _ /(mem_sdprod defG)[x [y [Kx Hy -> _]]].
by rewrite cfSdprodE // cfResE // cfkerMl ?(subsetP kerK).
Qed.
Lemma sdprod_cfker phi : K ><| cfker phi = cfker (cfSdprod phi).
Proof.
have [skerH [_ _ nKH tiKH]] := (cfker_sub phi, sdprodP defG).
rewrite unlock cfker_morph ?normal_norm // cfker_isom restrmEsub //=.
rewrite -(sdprod_modl defG) ?sub_cosetpre //=; congr (_ ><| _).
by rewrite quotientK ?(subset_trans skerH) // -group_modr //= setIC tiKH mul1g.
Qed.
Lemma cforder_sdprod phi : #[cfSdprod phi]%CF = #[phi]%CF.
Proof. exact: cforder_inj_rmorph cfSdprod_inj. Qed.
End SDproduct.
Section DProduct.
Variables (gT : finGroupType) (G K H : {group gT}).
Hypothesis KxH : K \x H = G.
Lemma reindex_dprod R idx (op : Monoid.com_law idx) (F : gT -> R) :
\big[op/idx]_(g in G) F g =
\big[op/idx]_(k in K) \big[op/idx]_(h in H) F (k * h)%g.
Proof.
have /mulgmP/misomP[fM /isomP[injf im_f]] := KxH.
rewrite pair_big_dep -im_f morphimEdom big_imset; last exact/injmP.
by apply: eq_big => [][x y]; rewrite ?inE.
Qed.
Definition cfDprodr := cfSdprod (dprodWsd KxH).
Definition cfDprodl := cfSdprod (dprodWsdC KxH).
Definition cfDprod phi psi := cfDprodl phi * cfDprodr psi.
HB.instance Definition _ := GRing.LRMorphism.on cfDprodl.
HB.instance Definition _ := GRing.LRMorphism.on cfDprodr.
Lemma cfDprodl1 phi : cfDprodl phi 1%g = phi 1%g. Proof. exact: cfSdprod1. Qed.
Lemma cfDprodr1 psi : cfDprodr psi 1%g = psi 1%g. Proof. exact: cfSdprod1. Qed.
Lemma cfDprod1 phi psi : cfDprod phi psi 1%g = phi 1%g * psi 1%g.
Proof. by rewrite cfunE /= !cfSdprod1. Qed.
Lemma cfDprodl_eq1 phi : (cfDprodl phi == 1) = (phi == 1).
Proof. exact: cfSdprod_eq1. Qed.
Lemma cfDprodr_eq1 psi : (cfDprodr psi == 1) = (psi == 1).
Proof. exact: cfSdprod_eq1. Qed.
Lemma cfDprod_cfun1r phi : cfDprod phi 1 = cfDprodl phi.
Proof. by rewrite /cfDprod rmorph1 mulr1. Qed.
Lemma cfDprod_cfun1l psi : cfDprod 1 psi = cfDprodr psi.
Proof. by rewrite /cfDprod rmorph1 mul1r. Qed.
Lemma cfDprod_cfun1 : cfDprod 1 1 = 1.
Proof. by rewrite cfDprod_cfun1l rmorph1. Qed.
Lemma cfDprod_split phi psi : cfDprod phi psi = cfDprod phi 1 * cfDprod 1 psi.
Proof. by rewrite cfDprod_cfun1l cfDprod_cfun1r. Qed.
Let nsKG : K <| G. Proof. by have [] := dprod_normal2 KxH. Qed.
Let nsHG : H <| G. Proof. by have [] := dprod_normal2 KxH. Qed.
Let cKH : H \subset 'C(K). Proof. by have [] := dprodP KxH. Qed.
Let sKG := normal_sub nsKG.
Let sHG := normal_sub nsHG.
Lemma cfDprodlK : cancel cfDprodl 'Res[K]. Proof. exact: cfSdprodK. Qed.
Lemma cfDprodrK : cancel cfDprodr 'Res[H]. Proof. exact: cfSdprodK. Qed.
Lemma cfker_dprodl phi : cfker phi \x H = cfker (cfDprodl phi).
Proof.
by rewrite dprodC -sdprod_cfker dprodEsd // centsC (centsS (cfker_sub _)).
Qed.
Lemma cfker_dprodr psi : K \x cfker psi = cfker (cfDprodr psi).
Proof. by rewrite -sdprod_cfker dprodEsd // (subset_trans (cfker_sub _)). Qed.
Lemma cfDprodEl phi : {in K & H, forall k h, cfDprodl phi (k * h)%g = phi k}.
Proof. by move=> k h Kk Hh /=; rewrite -(centsP cKH) // cfSdprodE. Qed.
Lemma cfDprodEr psi : {in K & H, forall k h, cfDprodr psi (k * h)%g = psi h}.
Proof. exact: cfSdprodE. Qed.
Lemma cfDprodE phi psi :
{in K & H, forall h k, cfDprod phi psi (h * k)%g = phi h * psi k}.
Proof. by move=> k h Kk Hh /=; rewrite cfunE cfDprodEl ?cfDprodEr. Qed.
Lemma cfDprod_Resl phi psi : 'Res[K] (cfDprod phi psi) = psi 1%g *: phi.
Proof.
by apply/cfun_inP=> x Kx; rewrite cfunE cfResE // -{1}[x]mulg1 mulrC cfDprodE.
Qed.
Lemma cfDprod_Resr phi psi : 'Res[H] (cfDprod phi psi) = phi 1%g *: psi.
Proof.
by apply/cfun_inP=> y Hy; rewrite cfunE cfResE // -{1}[y]mul1g cfDprodE.
Qed.
Lemma cfDprodKl (psi : 'CF(H)) : psi 1%g = 1 -> cancel (cfDprod^~ psi) 'Res.
Proof. by move=> psi1 phi; rewrite cfDprod_Resl psi1 scale1r. Qed.
Lemma cfDprodKr (phi : 'CF(K)) : phi 1%g = 1 -> cancel (cfDprod phi) 'Res.
Proof. by move=> phi1 psi; rewrite cfDprod_Resr phi1 scale1r. Qed.
(* Note that equality holds here iff either cfker phi = K and cfker psi = H, *)
(* or else phi != 0, psi != 0 and coprime #|K : cfker phi| #|H : cfker phi|. *)
Lemma cfker_dprod phi psi :
cfker phi <*> cfker psi \subset cfker (cfDprod phi psi).
Proof.
rewrite -genM_join gen_subG; apply/subsetP=> _ /mulsgP[x y kKx kHy ->] /=.
have [[Kx _] [Hy _]] := (setIdP kKx, setIdP kHy).
have Gxy: (x * y)%g \in G by rewrite -(dprodW KxH) mem_mulg.
rewrite inE Gxy; apply/forallP=> g.
have [Gg | G'g] := boolP (g \in G); last by rewrite !cfun0 1?groupMl.
have{g Gg} [k [h [Kk Hh -> _]]] := mem_dprod KxH Gg.
rewrite mulgA -(mulgA x) (centsP cKH y) // mulgA -mulgA !cfDprodE ?groupM //.
by rewrite !cfkerMl.
Qed.
Lemma cfdot_dprod phi1 phi2 psi1 psi2 :
'[cfDprod phi1 psi1, cfDprod phi2 psi2] = '[phi1, phi2] * '[psi1, psi2].
Proof.
rewrite !cfdotE mulrCA -mulrA mulrCA mulrA -invfM -natrM (dprod_card KxH).
congr (_ * _); rewrite big_distrl reindex_dprod /=; apply: eq_bigr => k Kk.
rewrite big_distrr; apply: eq_bigr => h Hh /=.
by rewrite mulrCA -mulrA -rmorphM mulrCA mulrA !cfDprodE.
Qed.
Lemma cfDprodl_iso : isometry cfDprodl.
Proof.
by move=> phi1 phi2; rewrite -!cfDprod_cfun1r cfdot_dprod cfnorm1 mulr1.
Qed.
Lemma cfDprodr_iso : isometry cfDprodr.
Proof.
by move=> psi1 psi2; rewrite -!cfDprod_cfun1l cfdot_dprod cfnorm1 mul1r.
Qed.
Lemma cforder_dprodl phi : #[cfDprodl phi]%CF = #[phi]%CF.
Proof. exact: cforder_sdprod. Qed.
Lemma cforder_dprodr psi : #[cfDprodr psi]%CF = #[psi]%CF.
Proof. exact: cforder_sdprod. Qed.
End DProduct.
Lemma cfDprodC (gT : finGroupType) (G K H : {group gT})
(KxH : K \x H = G) (HxK : H \x K = G) chi psi :
cfDprod KxH chi psi = cfDprod HxK psi chi.
Proof.
rewrite /cfDprod mulrC.
by congr (_ * _); congr (cfSdprod _ _); apply: eq_irrelevance.
Qed.
Section Bigdproduct.
Variables (gT : finGroupType) (I : finType) (P : pred I).
Variables (A : I -> {group gT}) (G : {group gT}).
Hypothesis defG : \big[dprod/1%g]_(i | P i) A i = G.
Let sAG i : P i -> A i \subset G.
Proof. by move=> Pi; rewrite -(bigdprodWY defG) (bigD1 i) ?joing_subl. Qed.
Fact cfBigdprodi_subproof i :
gval (if P i then A i else 1%G) \x <<\bigcup_(j | P j && (j != i)) A j>> = G.
Proof.
have:= defG; rewrite fun_if big_mkcond (bigD1 i) // -big_mkcondl /= => defGi.
by have [[_ Gi' _ defGi']] := dprodP defGi; rewrite (bigdprodWY defGi') -defGi'.
Qed.
Definition cfBigdprodi i := cfDprodl (cfBigdprodi_subproof i) \o 'Res[_, A i].
HB.instance Definition _ i := GRing.LRMorphism.on (@cfBigdprodi i).
Lemma cfBigdprodi1 i (phi : 'CF(A i)) : cfBigdprodi phi 1%g = phi 1%g.
Proof. by rewrite cfDprodl1 cfRes1. Qed.
Lemma cfBigdprodi_eq1 i (phi : 'CF(A i)) :
P i -> (cfBigdprodi phi == 1) = (phi == 1).
Proof. by move=> Pi; rewrite cfSdprod_eq1 Pi cfRes_id. Qed.
Lemma cfBigdprodiK i : P i -> cancel (@cfBigdprodi i) 'Res[A i].
Proof.
move=> Pi phi; have:= cfDprodlK (cfBigdprodi_subproof i) ('Res phi).
by rewrite -[cfDprodl _ _]/(cfBigdprodi phi) Pi cfRes_id.
Qed.
Lemma cfBigdprodi_inj i : P i -> injective (@cfBigdprodi i).
Proof. by move/cfBigdprodiK; apply: can_inj. Qed.
Lemma cfBigdprodEi i (phi : 'CF(A i)) x :
P i -> (forall j, P j -> x j \in A j) ->
cfBigdprodi phi (\prod_(j | P j) x j)%g = phi (x i).
Proof.
have [r big_r [Ur mem_r] _] := big_enumP P => Pi AxP.
have:= bigdprodWcp defG; rewrite -!big_r => defGr.
have{AxP} [r_i Axr]: i \in r /\ {in r, forall j, x j \in A j}.
by split=> [|j]; rewrite mem_r // => /AxP.
rewrite (perm_bigcprod defGr Axr (perm_to_rem r_i)) big_cons.
rewrite cfDprodEl ?Pi ?cfRes_id ?Axr // big_seq group_prod // => j.
rewrite mem_rem_uniq // => /andP[i'j /= r_j].
by apply/mem_gen/bigcupP; exists j; [rewrite -mem_r r_j | apply: Axr].
Qed.
Lemma cfBigdprodi_iso i : P i -> isometry (@cfBigdprodi i).
Proof. by move=> Pi phi psi; rewrite cfDprodl_iso Pi !cfRes_id. Qed.
Definition cfBigdprod (phi : forall i, 'CF(A i)) :=
\prod_(i | P i) cfBigdprodi (phi i).
Lemma cfBigdprodE phi x :
(forall i, P i -> x i \in A i) ->
cfBigdprod phi (\prod_(i | P i) x i)%g = \prod_(i | P i) phi i (x i).
Proof.
move=> Ax; rewrite prod_cfunE; last by rewrite -(bigdprodW defG) mem_prodg.
by apply: eq_bigr => i Pi; rewrite cfBigdprodEi.
Qed.
Lemma cfBigdprod1 phi : cfBigdprod phi 1%g = \prod_(i | P i) phi i 1%g.
Proof. by rewrite prod_cfunE //; apply/eq_bigr=> i _; apply: cfBigdprodi1. Qed.
Lemma cfBigdprodK phi (Phi := cfBigdprod phi) i (a := phi i 1%g / Phi 1%g) :
Phi 1%g != 0 -> P i -> a != 0 /\ a *: 'Res[A i] Phi = phi i.
Proof.
move=> nzPhi Pi; split.
rewrite mulf_neq0 ?invr_eq0 // (contraNneq _ nzPhi) // => phi_i0.
by rewrite cfBigdprod1 (bigD1 i) //= phi_i0 mul0r.
apply/cfun_inP=> x Aix; rewrite cfunE cfResE ?sAG // mulrAC.
have {1}->: x = (\prod_(j | P j) (if j == i then x else 1))%g.
rewrite -big_mkcondr (big_pred1 i) ?eqxx // => j /=.
by apply: andb_idl => /eqP->.
rewrite cfBigdprodE => [|j _]; last by case: eqP => // ->.
apply: canLR (mulfK nzPhi) _; rewrite cfBigdprod1 !(bigD1 i Pi) /= eqxx.
by rewrite mulrCA !mulrA; congr (_ * _); apply: eq_bigr => j /andP[_ /negPf->].
Qed.
Lemma cfdot_bigdprod phi psi :
'[cfBigdprod phi, cfBigdprod psi] = \prod_(i | P i) '[phi i, psi i].
Proof.
apply: canLR (mulKf (neq0CG G)) _; rewrite -(bigdprod_card defG).
rewrite (big_morph _ (@natrM _) (erefl _)) -big_split /=.
rewrite (eq_bigr _ (fun i _ => mulVKf (neq0CG _) _)) (big_distr_big_dep 1%g) /=.
set F := pfamily _ _ _; pose h (f : {ffun I -> gT}) := (\prod_(i | P i) f i)%g.
pose is_hK x f := forall f1, (f1 \in F) && (h f1 == x) = (f == f1).
have /fin_all_exists[h1 Dh1] x: exists f, x \in G -> is_hK x f.
case Gx: (x \in G); last by exists [ffun _ => x].
have [f [Af fK Uf]] := mem_bigdprod defG Gx.
exists [ffun i => if P i then f i else 1%g] => _ f1.
apply/andP/eqP=> [[/pfamilyP[Pf1 Af1] /eqP Dx] | <-].
by apply/ffunP=> i; rewrite ffunE; case: ifPn => [/Uf-> | /(supportP Pf1)].
split; last by rewrite fK; apply/eqP/eq_bigr=> i Pi; rewrite ffunE Pi.
by apply/familyP=> i; rewrite ffunE !unfold_in; case: ifP => //= /Af.
rewrite (reindex_onto h h1) /= => [|x /Dh1/(_ (h1 x))]; last first.
by rewrite eqxx => /andP[_ /eqP].
apply/eq_big => [f | f /andP[/Dh1<- /andP[/pfamilyP[_ Af] _]]]; last first.
by rewrite !cfBigdprodE // rmorph_prod -big_split /=.
apply/idP/idP=> [/andP[/Dh1<-] | Ff]; first by rewrite eqxx andbT.
have /pfamilyP[_ Af] := Ff; suffices Ghf: h f \in G by rewrite -Dh1 ?Ghf ?Ff /=.
by apply/group_prod=> i Pi; rewrite (subsetP (sAG Pi)) ?Af.
Qed.
End Bigdproduct.
Section MorphIsometry.
Variable gT : finGroupType.
Implicit Types (D G H K : {group gT}) (aT rT : finGroupType).
Lemma cfMorph_iso aT rT (G D : {group aT}) (f : {morphism D >-> rT}) :
G \subset D -> isometry (cfMorph : 'CF(f @* G) -> 'CF(G)).
Proof.
move=> sGD phi psi; rewrite !cfdotE card_morphim (setIidPr sGD).
rewrite -(LagrangeI G ('ker f)) /= mulnC natrM invfM -mulrA.
congr (_ * _); apply: (canLR (mulKf (neq0CG _))).
rewrite mulr_sumr (partition_big_imset f) /= -morphimEsub //.
apply: eq_bigr => _ /morphimP[x Dx Gx ->].
rewrite -(card_rcoset _ x) mulr_natl -sumr_const.
apply/eq_big => [y | y /andP[Gy /eqP <-]]; last by rewrite !cfMorphE.
rewrite mem_rcoset inE groupMr ?groupV // -mem_rcoset.
by apply: andb_id2l => /(subsetP sGD) Dy; apply: sameP eqP (rcoset_kerP f _ _).
Qed.
Lemma cfIsom_iso rT G (R : {group rT}) (f : {morphism G >-> rT}) :
forall isoG : isom G R f, isometry (cfIsom isoG).
Proof.
move=> isoG phi psi; rewrite unlock cfMorph_iso //; set G1 := _ @* R.
by rewrite -(isom_im (isom_sym isoG)) -/G1 in phi psi *; rewrite !cfRes_id.
Qed.
Lemma cfMod_iso H G : H <| G -> isometry (@cfMod _ G H).
Proof. by case/andP=> _; apply: cfMorph_iso. Qed.
Lemma cfQuo_iso H G :
H <| G -> {in [pred phi | H \subset cfker phi] &, isometry (@cfQuo _ G H)}.
Proof.
by move=> nsHG phi psi sHkphi sHkpsi; rewrite -(cfMod_iso nsHG) !cfQuoK.
Qed.
Lemma cfnorm_quo H G phi :
H <| G -> H \subset cfker phi -> '[phi / H] = '[phi]_G.
Proof. by move=> nsHG sHker; apply: cfQuo_iso. Qed.
Lemma cfSdprod_iso K H G (defG : K ><| H = G) : isometry (cfSdprod defG).
Proof.
move=> phi psi; have [/andP[_ nKG] _ _ _ _] := sdprod_context defG.
by rewrite [cfSdprod _]locked_withE cfMorph_iso ?cfIsom_iso.
Qed.
End MorphIsometry.
Section Induced.
Variable gT : finGroupType.
Section Def.
Variables B A : {set gT}.
Local Notation G := <<B>>.
Local Notation H := <<A>>.
(* The default value for the ~~ (H \subset G) case matches the one for cfRes *)
(* so that Frobenius reciprocity holds even in this degenerate case. *)
Definition ffun_cfInd (phi : 'CF(A)) :=
[ffun x => if H \subset G then #|A|%:R^-1 * (\sum_(y in G) phi (x ^ y))
else #|G|%:R * '[phi, 1] *+ (x == 1%g)].
Fact cfInd_subproof phi : is_class_fun G (ffun_cfInd phi).
Proof.
apply: intro_class_fun => [x y Gx Gy | x H'x]; last first.
case: subsetP => [sHG | _]; last by rewrite (negPf (group1_contra H'x)).
rewrite big1 ?mulr0 // => y Gy; rewrite cfun0gen ?(contra _ H'x) //= => /sHG.
by rewrite memJ_norm ?(subsetP (normG _)).
rewrite conjg_eq1 (reindex_inj (mulgI y^-1)%g); congr (if _ then _ * _ else _).
by apply: eq_big => [z | z Gz]; rewrite ?groupMl ?groupV // -conjgM mulKVg.
Qed.
Definition cfInd phi := Cfun 1 (cfInd_subproof phi).
Lemma cfInd_is_linear : linear cfInd.
Proof.
move=> c phi psi; apply/cfunP=> x; rewrite !cfunElock; case: ifP => _.
rewrite mulrCA -mulrDr [c * _]mulr_sumr -big_split /=.
by congr (_ * _); apply: eq_bigr => y _; rewrite !cfunE.
rewrite mulrnAr -mulrnDl !(mulrCA c) -!mulrDr [c * _]mulr_sumr -big_split /=.
by congr (_ * (_ * _) *+ _); apply: eq_bigr => y; rewrite !cfunE mulrA mulrDl.
Qed.
HB.instance Definition _ := GRing.isSemilinear.Build algC _ _ _ cfInd
(GRing.semilinear_linear cfInd_is_linear).
End Def.
Local Notation "''Ind[' B , A ]" := (@cfInd B A) : ring_scope.
Local Notation "''Ind[' B ]" := 'Ind[B, _] : ring_scope.
Lemma cfIndE (G H : {group gT}) phi x :
H \subset G -> 'Ind[G, H] phi x = #|H|%:R^-1 * (\sum_(y in G) phi (x ^ y)).
Proof. by rewrite cfunElock !genGid => ->. Qed.
Variables G K H : {group gT}.
Implicit Types (phi : 'CF(H)) (psi : 'CF(G)).
Lemma cfIndEout phi :
~~ (H \subset G) -> 'Ind[G] phi = (#|G|%:R * '[phi, 1]) *: '1_1%G.
Proof.
move/negPf=> not_sHG; apply/cfunP=> x; rewrite cfunE cfuniE ?normal1 // inE.
by rewrite mulr_natr cfunElock !genGid not_sHG.
Qed.
Lemma cfIndEsdprod (phi : 'CF(K)) x :
K ><| H = G -> 'Ind[G] phi x = \sum_(w in H) phi (x ^ w)%g.
Proof.
move=> defG; have [/andP[sKG _] _ mulKH nKH _] := sdprod_context defG.
rewrite cfIndE //; apply: canLR (mulKf (neq0CG _)) _; rewrite -mulKH mulr_sumr.
rewrite (set_partition_big _ (rcosets_partition_mul H K)) ?big_imset /=.
apply: eq_bigr => y Hy; rewrite rcosetE norm_rlcoset ?(subsetP nKH) //.
rewrite -lcosetE mulr_natl big_imset /=; last exact: in2W (mulgI _).
by rewrite -sumr_const; apply: eq_bigr => z Kz; rewrite conjgM cfunJ.
have [{}nKH /isomP[injf _]] := sdprod_isom defG.
apply: can_in_inj (fun Ky => invm injf (coset K (repr Ky))) _ => y Hy.
by rewrite rcosetE -val_coset ?(subsetP nKH) // coset_reprK invmE.
Qed.
Lemma cfInd_on A phi :
H \subset G -> phi \in 'CF(H, A) -> 'Ind[G] phi \in 'CF(G, class_support A G).
Proof.
move=> sHG Af; apply/cfun_onP=> g AG'g; rewrite cfIndE ?big1 ?mulr0 // => h Gh.
apply: (cfun_on0 Af); apply: contra AG'g => Agh.
by rewrite -[g](conjgK h) memJ_class_support // groupV.
Qed.
Lemma cfInd_id phi : 'Ind[H] phi = phi.
Proof.
apply/cfun_inP=> x Hx; rewrite cfIndE // (eq_bigr _ (cfunJ phi x)) sumr_const.
by rewrite -[phi x *+ _]mulr_natl mulKf ?neq0CG.
Qed.
Lemma cfInd_normal phi : H <| G -> 'Ind[G] phi \in 'CF(G, H).
Proof.
case/andP=> sHG nHG; apply: (cfun_onS (class_support_sub_norm (subxx _) nHG)).
by rewrite cfInd_on ?cfun_onG.
Qed.
Lemma cfInd1 phi : H \subset G -> 'Ind[G] phi 1%g = #|G : H|%:R * phi 1%g.
Proof.
move=> sHG; rewrite cfIndE // natf_indexg // -mulrA mulrCA; congr (_ * _).
by rewrite mulr_natl -sumr_const; apply: eq_bigr => x; rewrite conj1g.
Qed.
Lemma cfInd_cfun1 : H <| G -> 'Ind[G, H] 1 = #|G : H|%:R *: '1_H.
Proof.
move=> nsHG; have [sHG nHG] := andP nsHG; rewrite natf_indexg // mulrC.
apply/cfunP=> x; rewrite cfIndE ?cfunE ?cfuniE // -mulrA; congr (_ * _).
rewrite mulr_natl -sumr_const; apply: eq_bigr => y Gy.
by rewrite cfun1E -{1}(normsP nHG y Gy) memJ_conjg.
Qed.
Lemma cfnorm_Ind_cfun1 : H <| G -> '['Ind[G, H] 1] = #|G : H|%:R.
Proof.
move=> nsHG; rewrite cfInd_cfun1 // cfnormZ normr_nat cfdot_cfuni // setIid.
by rewrite expr2 {2}natf_indexg ?normal_sub // !mulrA divfK ?mulfK ?neq0CG.
Qed.
Lemma cfIndInd phi :
K \subset G -> H \subset K -> 'Ind[G] ('Ind[K] phi) = 'Ind[G] phi.
Proof.
move=> sKG sHK; apply/cfun_inP=> x Gx; rewrite !cfIndE ?(subset_trans sHK) //.
apply: canLR (mulKf (neq0CG K)) _; rewrite mulr_sumr mulr_natl.
transitivity (\sum_(y in G) \sum_(z in K) #|H|%:R^-1 * phi ((x ^ y) ^ z)).
by apply: eq_bigr => y Gy; rewrite cfIndE // -mulr_sumr.
symmetry; rewrite exchange_big /= -sumr_const; apply: eq_bigr => z Kz.
rewrite (reindex_inj (mulIg z)).
by apply: eq_big => [y | y _]; rewrite ?conjgM // groupMr // (subsetP sKG).
Qed.
(* This is Isaacs, Lemma (5.2). *)
Lemma Frobenius_reciprocity phi psi : '[phi, 'Res[H] psi] = '['Ind[G] phi, psi].
Proof.
have [sHG | not_sHG] := boolP (H \subset G); last first.
rewrite cfResEout // cfIndEout // cfdotZr cfdotZl mulrAC; congr (_ * _).
rewrite (cfdotEl _ (cfuni_on _ _)) mulVKf ?neq0CG // big_set1.
by rewrite cfuniE ?normal1 ?set11 ?mul1r.
transitivity (#|H|%:R^-1 * \sum_(x in G) phi x * (psi x)^* ).
rewrite (big_setID H) /= (setIidPr sHG) addrC big1 ?add0r; last first.
by move=> x /setDP[_ /cfun0->]; rewrite mul0r.
by congr (_ * _); apply: eq_bigr => x Hx; rewrite cfResE.
set h' := _^-1; apply: canRL (mulKf (neq0CG G)) _.
transitivity (h' * \sum_(y in G) \sum_(x in G) phi (x ^ y) * (psi (x ^ y))^* ).
rewrite mulrCA mulr_natl -sumr_const; congr (_ * _); apply: eq_bigr => y Gy.
by rewrite (reindex_acts 'J _ Gy) ?astabsJ ?normG.
rewrite exchange_big mulr_sumr; apply: eq_bigr => x _; rewrite cfIndE //=.
by rewrite -mulrA mulr_suml; congr (_ * _); apply: eq_bigr => y /(cfunJ psi)->.
Qed.
Definition cfdot_Res_r := Frobenius_reciprocity.
Lemma cfdot_Res_l psi phi : '['Res[H] psi, phi] = '[psi, 'Ind[G] phi].
Proof. by rewrite cfdotC cfdot_Res_r -cfdotC. Qed.
Lemma cfIndM phi psi: H \subset G ->
'Ind[G] (phi * ('Res[H] psi)) = 'Ind[G] phi * psi.
Proof.
move=> HsG; apply/cfun_inP=> x Gx; rewrite !cfIndE // !cfunE !cfIndE // -mulrA.
congr (_ * _); rewrite mulr_suml; apply: eq_bigr=> i iG; rewrite !cfunE.
case: (boolP (x ^ i \in H)) => xJi; last by rewrite cfun0gen ?mul0r ?genGid.
by rewrite !cfResE //; congr (_ * _); rewrite cfunJgen ?genGid.
Qed.
End Induced.
Arguments cfInd {gT} B%_g {A%_g} phi%_CF.
Notation "''Ind[' G , H ]" := (@cfInd _ G H) (only parsing) : ring_scope.
Notation "''Ind[' G ]" := 'Ind[G, _] : ring_scope.
Notation "''Ind'" := 'Ind[_] (only parsing) : ring_scope.
Section MorphInduced.
Variables (aT rT : finGroupType) (D G H : {group aT}) (R S : {group rT}).
Lemma cfIndMorph (f : {morphism D >-> rT}) (phi : 'CF(f @* H)) :
'ker f \subset H -> H \subset G -> G \subset D ->
'Ind[G] (cfMorph phi) = cfMorph ('Ind[f @* G] phi).
Proof.
move=> sKH sHG sGD; have [sHD inD] := (subset_trans sHG sGD, subsetP sGD).
apply/cfun_inP=> /= x Gx; have [Dx sKG] := (inD x Gx, subset_trans sKH sHG).
rewrite cfMorphE ?cfIndE ?morphimS // (partition_big_imset f) -morphimEsub //=.
rewrite card_morphim (setIidPr sHD) natf_indexg // invfM invrK -mulrA.
congr (_ * _); rewrite mulr_sumr; apply: eq_bigr => _ /morphimP[y Dy Gy ->].
rewrite -(card_rcoset _ y) mulr_natl -sumr_const.
apply: eq_big => [z | z /andP[Gz /eqP <-]].
have [Gz | G'z] := boolP (z \in G).
by rewrite (sameP eqP (rcoset_kerP _ _ _)) ?inD.
by case: rcosetP G'z => // [[t Kt ->]]; rewrite groupM // (subsetP sKG).
have [Dz Dxz] := (inD z Gz, inD (x ^ z) (groupJ Gx Gz)); rewrite -morphJ //.
have [Hxz | notHxz] := boolP (x ^ z \in H); first by rewrite cfMorphE.
by rewrite !cfun0 // -sub1set -morphim_set1 // morphimSGK ?sub1set.
Qed.
Variables (g : {morphism G >-> rT}) (h : {morphism H >-> rT}).
Hypotheses (isoG : isom G R g) (isoH : isom H S h) (eq_hg : {in H, h =1 g}).
Hypothesis sHG : H \subset G.
Lemma cfResIsom phi : 'Res[S] (cfIsom isoG phi) = cfIsom isoH ('Res[H] phi).
Proof.
have [[injg defR] [injh defS]] := (isomP isoG, isomP isoH).
rewrite !morphimEdom in defS defR; apply/cfun_inP=> s.
rewrite -{1}defS => /imsetP[x Hx ->] {s}; have Gx := subsetP sHG x Hx.
rewrite {1}eq_hg ?(cfResE, cfIsomE) // -defS -?eq_hg ?imset_f // -defR.
by rewrite (eq_in_imset eq_hg) imsetS.
Qed.
Lemma cfIndIsom phi : 'Ind[R] (cfIsom isoH phi) = cfIsom isoG ('Ind[G] phi).
Proof.
have [[injg defR] [_ defS]] := (isomP isoG, isomP isoH).
rewrite morphimEdom (eq_in_imset eq_hg) -morphimEsub // in defS.
apply/cfun_inP=> s; rewrite -{1}defR => /morphimP[x _ Gx ->]{s}.
rewrite cfIsomE ?cfIndE // -defR -{1}defS ?morphimS ?card_injm // morphimEdom.
congr (_ * _); rewrite big_imset //=; last exact/injmP.
apply: eq_bigr => y Gy; rewrite -morphJ //.
have [Hxy | H'xy] := boolP (x ^ y \in H); first by rewrite -eq_hg ?cfIsomE.
by rewrite !cfun0 -?defS // -sub1set -morphim_set1 ?injmSK ?sub1set // groupJ.
Qed.
End MorphInduced.
Section FieldAutomorphism.
Variables (u : {rmorphism algC -> algC}) (gT rT : finGroupType).
Variables (G K H : {group gT}) (f : {morphism G >-> rT}) (R : {group rT}).
Implicit Types (phi : 'CF(G)) (S : seq 'CF(G)).
Local Notation "phi ^u" := (cfAut u phi).
Lemma cfAutZ_nat n phi : (n%:R *: phi)^u = n%:R *: phi^u.
Proof. exact: raddfZnat. Qed.
Lemma cfAutZ_Cnat z phi : z \in Num.nat -> (z *: phi)^u = z *: phi^u.
Proof. exact: raddfZ_nat. Qed.
Lemma cfAutZ_Cint z phi : z \in Num.int -> (z *: phi)^u = z *: phi^u.
Proof. exact: raddfZ_int. Qed.
Lemma cfAutK : cancel (@cfAut gT G u) (cfAut (algC_invaut u)).
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE /= algC_autK. Qed.
Lemma cfAutVK : cancel (cfAut (algC_invaut u)) (@cfAut gT G u).
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE /= algC_invautK. Qed.
Lemma cfAut_inj : injective (@cfAut gT G u).
Proof. exact: can_inj cfAutK. Qed.
Lemma cfAut_eq1 phi : (cfAut u phi == 1) = (phi == 1).
Proof. by rewrite rmorph_eq1 //; apply: cfAut_inj. Qed.
Lemma support_cfAut phi : support phi^u =i support phi.
Proof. by move=> x; rewrite !inE cfunE fmorph_eq0. Qed.
Lemma map_cfAut_free S : cfAut_closed u S -> free S -> free (map (cfAut u) S).
Proof.
set Su := map _ S => sSuS freeS; have uniqS := free_uniq freeS.
have uniqSu: uniq Su by rewrite (map_inj_uniq cfAut_inj).
have{} sSuS: {subset Su <= S} by move=> _ /mapP[phi Sphi ->]; apply: sSuS.
have [|_ eqSuS] := uniq_min_size uniqSu sSuS; first by rewrite size_map.
by rewrite (perm_free (uniq_perm uniqSu uniqS eqSuS)).
Qed.
Lemma cfAut_on A phi : (phi^u \in 'CF(G, A)) = (phi \in 'CF(G, A)).
Proof. by rewrite !cfun_onE (eq_subset (support_cfAut phi)). Qed.
Lemma cfker_aut phi : cfker phi^u = cfker phi.
Proof.
apply/setP=> x /[!inE]; apply: andb_id2l => Gx.
by apply/forallP/forallP=> Kx y;
have:= Kx y; rewrite !cfunE (inj_eq (fmorph_inj u)).
Qed.
Lemma cfAut_cfuni A : ('1_A)^u = '1_A :> 'CF(G).
Proof. by apply/cfunP=> x; rewrite !cfunElock rmorph_nat. Qed.
Lemma cforder_aut phi : #[phi^u]%CF = #[phi]%CF.
Proof. exact: cforder_inj_rmorph cfAut_inj. Qed.
Lemma cfAutRes phi : ('Res[H] phi)^u = 'Res phi^u.
Proof. by apply/cfunP=> x; rewrite !cfunElock rmorphMn. Qed.
Lemma cfAutMorph (psi : 'CF(f @* H)) : (cfMorph psi)^u = cfMorph psi^u.
Proof. by apply/cfun_inP=> x Hx; rewrite !cfunElock Hx. Qed.
Lemma cfAutIsom (isoGR : isom G R f) phi :
(cfIsom isoGR phi)^u = cfIsom isoGR phi^u.
Proof.
apply/cfun_inP=> y; have [_ {1}<-] := isomP isoGR => /morphimP[x _ Gx ->{y}].
by rewrite !(cfunE, cfIsomE).
Qed.
Lemma cfAutQuo phi : (phi / H)^u = (phi^u / H)%CF.
Proof. by apply/cfunP=> Hx; rewrite !cfunElock cfker_aut rmorphMn. Qed.
Lemma cfAutMod (psi : 'CF(G / H)) : (psi %% H)^u = (psi^u %% H)%CF.
Proof. by apply/cfunP=> x; rewrite !cfunElock rmorphMn. Qed.
Lemma cfAutInd (psi : 'CF(H)) : ('Ind[G] psi)^u = 'Ind psi^u.
Proof.
have [sHG | not_sHG] := boolP (H \subset G).
apply/cfunP=> x; rewrite !(cfunE, cfIndE) // rmorphM /= fmorphV rmorph_nat.
by congr (_ * _); rewrite rmorph_sum; apply: eq_bigr => y; rewrite !cfunE.
rewrite !cfIndEout // linearZ /= cfAut_cfuni rmorphM rmorph_nat /=.
rewrite -cfdot_cfAut ?rmorph1 // => _ /imageP[x Hx ->].
by rewrite cfun1E Hx !rmorph1.
Qed.
Hypothesis KxH : K \x H = G.
Lemma cfAutDprodl (phi : 'CF(K)) : (cfDprodl KxH phi)^u = cfDprodl KxH phi^u.
Proof.
apply/cfun_inP=> _ /(mem_dprod KxH)[x [y [Kx Hy -> _]]].
by rewrite !(cfunE, cfDprodEl).
Qed.
Lemma cfAutDprodr (psi : 'CF(H)) : (cfDprodr KxH psi)^u = cfDprodr KxH psi^u.
Proof.
apply/cfun_inP=> _ /(mem_dprod KxH)[x [y [Kx Hy -> _]]].
by rewrite !(cfunE, cfDprodEr).
Qed.
Lemma cfAutDprod (phi : 'CF(K)) (psi : 'CF(H)) :
(cfDprod KxH phi psi)^u = cfDprod KxH phi^u psi^u.
Proof. by rewrite rmorphM /= cfAutDprodl cfAutDprodr. Qed.
End FieldAutomorphism.
Arguments cfAutK u {gT G}.
Arguments cfAutVK u {gT G}.
Arguments cfAut_inj u {gT G} [phi1 phi2] : rename.
Definition conj_cfRes := cfAutRes conjC.
Definition cfker_conjC := cfker_aut conjC.
Definition conj_cfQuo := cfAutQuo conjC.
Definition conj_cfMod := cfAutMod conjC.
Definition conj_cfInd := cfAutInd conjC.
Definition cfconjC_eq1 := cfAut_eq1 conjC.
|
wlog.lean
|
/-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Johan Commelin
-/
import Mathlib.Tactic.WLOG
import Mathlib.Algebra.Ring.Nat
example {x y : ℕ} : True := by
wlog h : x ≤ y
· guard_hyp h : ¬x ≤ y
guard_hyp this : ∀ {x y : ℕ}, x ≤ y → True -- `wlog` generalizes by default
guard_target =ₛ True
trivial
· guard_hyp h : x ≤ y
guard_target =ₛ True
trivial
example {x y : ℕ} : True := by
wlog h : x ≤ y generalizing x with H
· guard_hyp h : ¬x ≤ y
guard_hyp H : ∀ {x : ℕ}, x ≤ y → True -- only `x` was generalized
guard_target =ₛ True
trivial
· guard_hyp h : x ≤ y
guard_target =ₛ True
trivial
example {x y z : ℕ} : True := by
wlog h : x ≤ y + z with H
· guard_hyp h : ¬ x ≤ y + z
guard_hyp H : ∀ {x y z : ℕ}, x ≤ y + z → True -- wlog-claim is named `H` instead of `this`
guard_target =ₛ True
trivial
· guard_hyp h : x ≤ y + z
guard_target =ₛ True
trivial
example : ∀ _ _ : ℕ, True := by
intro x y
wlog h : x ≤ y -- `wlog` finds new variables
· trivial
· trivial
example {x y : ℕ} : True := by
wlog h : x ≤ y generalizing y x with H
· guard_hyp h : ¬ x ≤ y
guard_hyp H : ∀ {x y : ℕ}, x ≤ y → True -- order of ids in `generalizing` is ignored
trivial
· trivial
-- metadata doesn't cause a problem
example (α : Type := ℕ) (x : Option α := none) (y : Option α := by exact 0) : True := by
wlog h : x = y with H
· guard_hyp h : ¬ x = y
guard_hyp H : ∀ α, ∀ {x y : Option α}, x = y → True
trivial
· guard_hyp h : x = y
guard_target =ₛ True
trivial
-- inaccessible names work
example {x y : ℕ} : True := by
wlog _ : x ≤ y
case _ h => -- if these hypotheses weren't inaccessible, they wouldn't be renamed by `case`
guard_hyp h : ¬x ≤ y
guard_hyp this : ∀ {x y : ℕ}, x ≤ y → True
guard_target =ₛ True
trivial
case _ h =>
guard_hyp h : x ≤ y
guard_target =ₛ True
trivial
-- Handle ldecls properly:
example (x y : ℕ) : True := by
let z := 0
wlog hxy' : z ≤ y with H
· trivial
· trivial
|
Sequences.lean
|
/-
Copyright (c) 2018 Jan-David Salchow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow, Patrick Massot, Yury Kudryashov
-/
import Mathlib.Order.Filter.AtTopBot.Defs
import Mathlib.Topology.Defs.Filter
/-!
# Sequences in topological spaces
In this file we define sequential closure, continuity, compactness etc.
## Main definitions
### Set operation
* `seqClosure s`: sequential closure of a set, the set of limits of sequences of points of `s`;
### Predicates
* `IsSeqClosed s`: predicate saying that a set is sequentially closed, i.e., `seqClosure s ⊆ s`;
* `SeqContinuous f`: predicate saying that a function is sequentially continuous, i.e.,
for any sequence `u : ℕ → X` that converges to a point `x`, the sequence `f ∘ u` converges to
`f x`;
* `IsSeqCompact s`: predicate saying that a set is sequentially compact, i.e., every sequence
taking values in `s` has a converging subsequence.
### Type classes
* `FrechetUrysohnSpace X`: a typeclass saying that a topological space is a *Fréchet-Urysohn
space*, i.e., the sequential closure of any set is equal to its closure.
* `SequentialSpace X`: a typeclass saying that a topological space is a *sequential space*, i.e.,
any sequentially closed set in this space is closed. This condition is weaker than being a
Fréchet-Urysohn space.
* `SeqCompactSpace X`: a typeclass saying that a topological space is sequentially compact, i.e.,
every sequence in `X` has a converging subsequence.
## Tags
sequentially closed, sequentially compact, sequential space
-/
open Set Filter
open scoped Topology
variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y]
/-- The sequential closure of a set `s : Set X` in a topological space `X` is the set of all `a : X`
which arise as limit of sequences in `s`. Note that the sequential closure of a set is not
guaranteed to be sequentially closed. -/
def seqClosure (s : Set X) : Set X :=
{ a | ∃ x : ℕ → X, (∀ n : ℕ, x n ∈ s) ∧ Tendsto x atTop (𝓝 a) }
/-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`, the
limit belongs to `s` as well. Note that the sequential closure of a set is not guaranteed to be
sequentially closed. -/
def IsSeqClosed (s : Set X) : Prop :=
∀ ⦃x : ℕ → X⦄ ⦃p : X⦄, (∀ n, x n ∈ s) → Tendsto x atTop (𝓝 p) → p ∈ s
/-- A function between topological spaces is sequentially continuous if it commutes with limit of
convergent sequences. -/
def SeqContinuous (f : X → Y) : Prop :=
∀ ⦃x : ℕ → X⦄ ⦃p : X⦄, Tendsto x atTop (𝓝 p) → Tendsto (f ∘ x) atTop (𝓝 (f p))
/-- A set `s` is sequentially compact if every sequence taking values in `s` has a
converging subsequence. -/
def IsSeqCompact (s : Set X) :=
∀ ⦃x : ℕ → X⦄, (∀ n, x n ∈ s) → ∃ a ∈ s, ∃ φ : ℕ → ℕ, StrictMono φ ∧ Tendsto (x ∘ φ) atTop (𝓝 a)
variable (X)
/-- A space `X` is sequentially compact if every sequence in `X` has a
converging subsequence. -/
@[mk_iff]
class SeqCompactSpace : Prop where
isSeqCompact_univ : IsSeqCompact (univ : Set X)
export SeqCompactSpace (isSeqCompact_univ)
/-- A topological space is called a *Fréchet-Urysohn space*, if the sequential closure of any set
is equal to its closure. Since one of the inclusions is trivial, we require only the non-trivial one
in the definition. -/
class FrechetUrysohnSpace : Prop where
closure_subset_seqClosure : ∀ s : Set X, closure s ⊆ seqClosure s
/-- A topological space is said to be a *sequential space* if any sequentially closed set in this
space is closed. This condition is weaker than being a Fréchet-Urysohn space. -/
class SequentialSpace : Prop where
isClosed_of_seq : ∀ s : Set X, IsSeqClosed s → IsClosed s
variable {X}
/-- In a sequential space, a sequentially closed set is closed. -/
protected theorem IsSeqClosed.isClosed [SequentialSpace X] {s : Set X} (hs : IsSeqClosed s) :
IsClosed s :=
SequentialSpace.isClosed_of_seq s hs
|
Basic.lean
|
/-
Copyright (c) 2024 Dagur Asgeirsson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz, Dagur Asgeirsson, Filippo A. E. Nuccio, Riccardo Brasca
-/
import Mathlib.Topology.Category.TopCat.Basic
import Mathlib.CategoryTheory.Functor.EpiMono
import Mathlib.CategoryTheory.Functor.ReflectsIso.Basic
/-!
# Categories of Compact Hausdorff Spaces
We construct the category of compact Hausdorff spaces satisfying an additional property `P`.
## Implementation
We define a structure `CompHausLike` which takes as an argument a predicate `P` on topological
spaces. It consists of the data of a topological space, satisfying the additional properties of
being compact and Hausdorff, and satisfying `P`. We give a category structure to `CompHausLike P`
induced by the forgetful functor to topological spaces.
It used to be the case (before https://github.com/leanprover-community/mathlib4/pull/12930 was merged) that several different categories of compact
Hausdorff spaces, possibly satisfying some extra property, were defined from scratch in this way.
For example, one would define a structure `CompHaus` as follows:
```lean
structure CompHaus where
toTop : TopCat
[is_compact : CompactSpace toTop]
[is_hausdorff : T2Space toTop]
```
and give it the category structure induced from topological spaces. Then the category of profinite
spaces was defined as follows:
```lean
structure Profinite where
toCompHaus : CompHaus
[isTotallyDisconnected : TotallyDisconnectedSpace toCompHaus]
```
The categories `Stonean` consisting of extremally disconnected compact Hausdorff spaces and
`LightProfinite` consisting of totally disconnected, second countable compact Hausdorff spaces were
defined in a similar way. This resulted in code duplication, and reducing this duplication was part
of the motivation for introducing `CompHausLike`.
Using `CompHausLike`, we can now define
`CompHaus := CompHausLike (fun _ ↦ True)`
`Profinite := CompHausLike (fun X ↦ TotallyDisconnectedSpace X)`.
`Stonean := CompHausLike (fun X ↦ ExtremallyDisconnected X)`.
`LightProfinite := CompHausLike (fun X ↦ TotallyDisconnectedSpace X ∧ SecondCountableTopology X)`.
These four categories are important building blocks of condensed objects (see the files
`Condensed.Basic` and `Condensed.Light.Basic`). These categories share many properties and often,
one wants to argue about several of them simultaneously. This is the other part of the motivation
for introducing `CompHausLike`. On paper, one would say "let `C` be on of the categories `CompHaus`
or `Profinite`, then the following holds: ...". This was not possible in Lean using the old
definitions. Using the new definitions, this becomes a matter of identifying what common property
of `CompHaus` and `Profinite` is used in the proof in question, and then proving the theorem for
`CompHausLike P` satisfying that property, and it will automatically apply to both `CompHaus` and
`Profinite`.
-/
universe u
open CategoryTheory
variable (P : TopCat.{u} → Prop)
/-- The type of Compact Hausdorff topological spaces satisfying an additional property `P`. -/
structure CompHausLike where
/-- The underlying topological space of an object of `CompHausLike P`. -/
toTop : TopCat
/-- The underlying topological space is compact. -/
[is_compact : CompactSpace toTop]
/-- The underlying topological space is T2. -/
[is_hausdorff : T2Space toTop]
/-- The underlying topological space satisfies P. -/
prop : P toTop
namespace CompHausLike
attribute [instance] is_compact is_hausdorff
instance : CoeSort (CompHausLike P) (Type u) :=
⟨fun X => X.toTop⟩
instance category : Category (CompHausLike P) :=
InducedCategory.category toTop
instance concreteCategory : ConcreteCategory (CompHausLike P) (C(·, ·)) :=
InducedCategory.concreteCategory toTop
instance hasForget₂ : HasForget₂ (CompHausLike P) TopCat :=
InducedCategory.hasForget₂ _
variable (X : Type u) [TopologicalSpace X] [CompactSpace X] [T2Space X]
/-- This wraps the predicate `P : TopCat → Prop` in a typeclass. -/
class HasProp : Prop where
hasProp : P (TopCat.of X)
instance (X : CompHausLike P) : HasProp P X := ⟨X.4⟩
variable [HasProp P X]
/-- A constructor for objects of the category `CompHausLike P`,
taking a type, and bundling the compact Hausdorff topology
found by typeclass inference. -/
abbrev of : CompHausLike P where
toTop := TopCat.of X
is_compact := ‹_›
is_hausdorff := ‹_›
prop := HasProp.hasProp
theorem coe_of : (CompHausLike.of P X : Type _) = X := rfl
@[simp]
theorem coe_id (X : CompHausLike P) : (𝟙 X : X → X) = id :=
rfl
@[simp]
theorem coe_comp {X Y Z : CompHausLike P} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g : X → Z) = g ∘ f :=
rfl
section
variable {X} {Y : Type u} [TopologicalSpace Y] [CompactSpace Y] [T2Space Y] [HasProp P Y]
variable {Z : Type u} [TopologicalSpace Z] [CompactSpace Z] [T2Space Z] [HasProp P Z]
/-- Typecheck a continuous map as a morphism in the category `CompHausLike P`. -/
abbrev ofHom (f : C(X, Y)) : of P X ⟶ of P Y := ConcreteCategory.ofHom f
@[simp] lemma hom_ofHom (f : C(X, Y)) : ConcreteCategory.hom (ofHom P f) = f := rfl
@[simp] lemma ofHom_id : ofHom P (ContinuousMap.id X) = 𝟙 (of _ X) := rfl
@[simp] lemma ofHom_comp (f : C(X, Y)) (g : C(Y, Z)) :
ofHom P (g.comp f) = ofHom _ f ≫ ofHom _ g := rfl
end
variable {P}
/-- If `P` imples `P'`, then there is a functor from `CompHausLike P` to `CompHausLike P'`. -/
@[simps map]
def toCompHausLike {P P' : TopCat → Prop} (h : ∀ (X : CompHausLike P), P X.toTop → P' X.toTop) :
CompHausLike P ⥤ CompHausLike P' where
obj X :=
have : HasProp P' X := ⟨(h _ X.prop)⟩
CompHausLike.of _ X
map f := f
section
variable {P P' : TopCat → Prop} (h : ∀ (X : CompHausLike P), P X.toTop → P' X.toTop)
/-- If `P` imples `P'`, then the functor from `CompHausLike P` to `CompHausLike P'` is fully
faithful. -/
def fullyFaithfulToCompHausLike : (toCompHausLike h).FullyFaithful :=
fullyFaithfulInducedFunctor _
instance : (toCompHausLike h).Full := (fullyFaithfulToCompHausLike h).full
instance : (toCompHausLike h).Faithful := (fullyFaithfulToCompHausLike h).faithful
end
variable (P)
/-- The fully faithful embedding of `CompHausLike P` in `TopCat`. -/
@[simps! map]
def compHausLikeToTop : CompHausLike.{u} P ⥤ TopCat.{u} :=
inducedFunctor _
-- The `Full, Faithful` instances should be constructed by a deriving handler.
-- https://github.com/leanprover-community/mathlib4/issues/380
example {P P' : TopCat → Prop} (h : ∀ (X : CompHausLike P), P X.toTop → P' X.toTop) :
toCompHausLike h ⋙ compHausLikeToTop P' = compHausLikeToTop P := rfl
/-- The functor from `CompHausLike P` to `TopCat` is fully faithful. -/
def fullyFaithfulCompHausLikeToTop : (compHausLikeToTop P).FullyFaithful :=
fullyFaithfulInducedFunctor _
instance : (compHausLikeToTop P).Full :=
inferInstanceAs (inducedFunctor _).Full
instance : (compHausLikeToTop P).Faithful :=
inferInstanceAs (inducedFunctor _).Faithful
instance (X : CompHausLike P) : CompactSpace ((compHausLikeToTop P).obj X) :=
inferInstanceAs (CompactSpace X.toTop)
instance (X : CompHausLike P) : T2Space ((compHausLikeToTop P).obj X) :=
inferInstanceAs (T2Space X.toTop)
variable {P}
theorem epi_of_surjective {X Y : CompHausLike.{u} P} (f : X ⟶ Y) (hf : Function.Surjective f) :
Epi f := by
rw [← CategoryTheory.epi_iff_surjective] at hf
exact (forget (CompHausLike P)).epi_of_epi_map hf
theorem mono_iff_injective {X Y : CompHausLike.{u} P} (f : X ⟶ Y) :
Mono f ↔ Function.Injective f := by
constructor
· intro hf x₁ x₂ h
let g₁ : X ⟶ X := ofHom _ ⟨fun _ => x₁, continuous_const⟩
let g₂ : X ⟶ X := ofHom _ ⟨fun _ => x₂, continuous_const⟩
have : g₁ ≫ f = g₂ ≫ f := by ext; exact h
exact CategoryTheory.congr_fun ((cancel_mono _).mp this) x₁
· rw [← CategoryTheory.mono_iff_injective]
apply (forget (CompHausLike P)).mono_of_mono_map
/-- Any continuous function on compact Hausdorff spaces is a closed map. -/
theorem isClosedMap {X Y : CompHausLike.{u} P} (f : X ⟶ Y) : IsClosedMap f := fun _ hC =>
(hC.isCompact.image f.hom.continuous).isClosed
/-- Any continuous bijection of compact Hausdorff spaces is an isomorphism. -/
theorem isIso_of_bijective {X Y : CompHausLike.{u} P} (f : X ⟶ Y) (bij : Function.Bijective f) :
IsIso f := by
let E := Equiv.ofBijective _ bij
have hE : Continuous E.symm := by
rw [continuous_iff_isClosed]
intro S hS
rw [← E.image_eq_preimage]
exact isClosedMap f S hS
refine ⟨⟨ofHom _ ⟨E.symm, hE⟩, ?_, ?_⟩⟩
· ext x
apply E.symm_apply_apply
· ext x
apply E.apply_symm_apply
instance forget_reflectsIsomorphisms :
(forget (CompHausLike.{u} P)).ReflectsIsomorphisms :=
⟨by intro A B f hf; rw [isIso_iff_bijective] at hf; exact isIso_of_bijective _ hf⟩
/-- Any continuous bijection of compact Hausdorff spaces induces an isomorphism. -/
noncomputable def isoOfBijective {X Y : CompHausLike.{u} P} (f : X ⟶ Y)
(bij : Function.Bijective f) : X ≅ Y :=
letI := isIso_of_bijective _ bij
asIso f
/-- Construct an isomorphism from a homeomorphism. -/
@[simps!]
def isoOfHomeo {X Y : CompHausLike.{u} P} (f : X ≃ₜ Y) : X ≅ Y :=
(fullyFaithfulCompHausLikeToTop P).preimageIso (TopCat.isoOfHomeo f)
/-- Construct a homeomorphism from an isomorphism. -/
@[simps!]
def homeoOfIso {X Y : CompHausLike.{u} P} (f : X ≅ Y) : X ≃ₜ Y :=
TopCat.homeoOfIso <| (compHausLikeToTop P).mapIso f
/-- The equivalence between isomorphisms in `CompHaus` and homeomorphisms
of topological spaces. -/
@[simps]
def isoEquivHomeo {X Y : CompHausLike.{u} P} : (X ≅ Y) ≃ (X ≃ₜ Y) where
toFun := homeoOfIso
invFun := isoOfHomeo
/-- A constant map as a morphism in `CompHausLike` -/
def const {P : TopCat.{u} → Prop}
(T : CompHausLike.{u} P) {S : CompHausLike.{u} P} (s : S) : T ⟶ S :=
ofHom _ (ContinuousMap.const _ s)
lemma const_comp {P : TopCat.{u} → Prop} {S T U : CompHausLike.{u} P}
(s : S) (g : S ⟶ U) : T.const s ≫ g = T.const (g s) :=
rfl
end CompHausLike
|
Basic.lean
|
/-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import Mathlib.Algebra.Group.Submonoid.Operations
import Mathlib.Data.DFinsupp.Sigma
import Mathlib.Data.DFinsupp.Submonoid
/-!
# Direct sum
This file defines the direct sum of abelian groups, indexed by a discrete type.
## Notation
`⨁ i, β i` is the n-ary direct sum `DirectSum`.
This notation is in the `DirectSum` locale, accessible after `open DirectSum`.
## References
* https://en.wikipedia.org/wiki/Direct_sum
-/
open Function
universe u v w u₁
variable (ι : Type v) (β : ι → Type w)
/-- `DirectSum ι β` is the direct sum of a family of additive commutative monoids `β i`.
Note: `open DirectSum` will enable the notation `⨁ i, β i` for `DirectSum ι β`. -/
def DirectSum [∀ i, AddCommMonoid (β i)] : Type _ :=
Π₀ i, β i
deriving AddCommMonoid, Inhabited, DFunLike, CoeFun
/-- `⨁ i, f i` is notation for `DirectSum _ f` and equals the direct sum of `fun i ↦ f i`.
Taking the direct sum over multiple arguments is possible, e.g. `⨁ (i) (j), f i j`. -/
scoped[DirectSum] notation3 "⨁ "(...)", "r:(scoped f => DirectSum _ f) => r
-- Porting note: The below recreates some of the lean3 notation, not fully yet
-- section
-- open Batteries.ExtendedBinder
-- syntax (name := bigdirectsum) "⨁ " extBinders ", " term : term
-- macro_rules (kind := bigdirectsum)
-- | `(⨁ $_:ident, $y:ident → $z:ident) => `(DirectSum _ (fun $y ↦ $z))
-- | `(⨁ $x:ident, $p) => `(DirectSum _ (fun $x ↦ $p))
-- | `(⨁ $_:ident : $t:ident, $p) => `(DirectSum _ (fun $t ↦ $p))
-- | `(⨁ ($x:ident) ($y:ident), $p) => `(DirectSum _ (fun $x ↦ fun $y ↦ $p))
-- end
instance [DecidableEq ι] [∀ i, AddCommMonoid (β i)] [∀ i, DecidableEq (β i)] :
DecidableEq (DirectSum ι β) :=
inferInstanceAs <| DecidableEq (Π₀ i, β i)
namespace DirectSum
variable {ι}
/-- Coercion from a `DirectSum` to a pi type is an `AddMonoidHom`. -/
def coeFnAddMonoidHom [∀ i, AddCommMonoid (β i)] : (⨁ i, β i) →+ (Π i, β i) where
toFun x := x
__ := DFinsupp.coeFnAddMonoidHom
@[simp]
lemma coeFnAddMonoidHom_apply [∀ i, AddCommMonoid (β i)] (v : ⨁ i, β i) :
coeFnAddMonoidHom β v = v :=
rfl
section AddCommGroup
variable [∀ i, AddCommGroup (β i)]
instance : AddCommGroup (DirectSum ι β) :=
inferInstanceAs (AddCommGroup (Π₀ i, β i))
variable {β}
@[simp]
theorem sub_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i :=
rfl
end AddCommGroup
variable [∀ i, AddCommMonoid (β i)]
@[ext] theorem ext {x y : DirectSum ι β} (w : ∀ i, x i = y i) : x = y :=
DFunLike.ext _ _ w
@[simp]
theorem zero_apply (i : ι) : (0 : ⨁ i, β i) i = 0 :=
rfl
variable {β}
@[simp]
theorem add_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ + g₂) i = g₁ i + g₂ i :=
rfl
section DecidableEq
variable [DecidableEq ι]
variable (β)
/-- `mk β s x` is the element of `⨁ i, β i` that is zero outside `s`
and has coefficient `x i` for `i` in `s`. -/
def mk (s : Finset ι) : (∀ i : (↑s : Set ι), β i.1) →+ ⨁ i, β i where
toFun := DFinsupp.mk s
map_add' _ _ := DFinsupp.mk_add
map_zero' := DFinsupp.mk_zero
/-- `of i` is the natural inclusion map from `β i` to `⨁ i, β i`. -/
def of (i : ι) : β i →+ ⨁ i, β i :=
DFinsupp.singleAddHom β i
variable {β}
@[simp]
theorem of_eq_same (i : ι) (x : β i) : (of _ i x) i = x :=
DFinsupp.single_eq_same
theorem of_eq_of_ne (i j : ι) (x : β i) (h : i ≠ j) : (of _ i x) j = 0 :=
DFinsupp.single_eq_of_ne h
lemma of_apply {i : ι} (j : ι) (x : β i) : of β i x j = if h : i = j then Eq.recOn h x else 0 :=
DFinsupp.single_apply
theorem mk_apply_of_mem {s : Finset ι} {f : ∀ i : (↑s : Set ι), β i.val} {n : ι} (hn : n ∈ s) :
mk β s f n = f ⟨n, hn⟩ := by
dsimp only [Finset.coe_sort_coe, mk, AddMonoidHom.coe_mk, ZeroHom.coe_mk, DFinsupp.mk_apply]
rw [dif_pos hn]
theorem mk_apply_of_notMem {s : Finset ι} {f : ∀ i : (↑s : Set ι), β i.val} {n : ι} (hn : n ∉ s) :
mk β s f n = 0 := by
dsimp only [Finset.coe_sort_coe, mk, AddMonoidHom.coe_mk, ZeroHom.coe_mk, DFinsupp.mk_apply]
rw [dif_neg hn]
@[deprecated (since := "2025-05-23")] alias mk_apply_of_not_mem := mk_apply_of_notMem
@[simp]
theorem support_zero [∀ (i : ι) (x : β i), Decidable (x ≠ 0)] : (0 : ⨁ i, β i).support = ∅ :=
DFinsupp.support_zero
@[simp]
theorem support_of [∀ (i : ι) (x : β i), Decidable (x ≠ 0)] (i : ι) (x : β i) (h : x ≠ 0) :
(of _ i x).support = {i} :=
DFinsupp.support_single_ne_zero h
theorem support_of_subset [∀ (i : ι) (x : β i), Decidable (x ≠ 0)] {i : ι} {b : β i} :
(of _ i b).support ⊆ {i} :=
DFinsupp.support_single_subset
theorem sum_support_of [∀ (i : ι) (x : β i), Decidable (x ≠ 0)] (x : ⨁ i, β i) :
(∑ i ∈ x.support, of β i (x i)) = x :=
DFinsupp.sum_single
theorem sum_univ_of [Fintype ι] (x : ⨁ i, β i) :
∑ i ∈ Finset.univ, of β i (x i) = x := by
apply DFinsupp.ext (fun i ↦ ?_)
rw [DFinsupp.finset_sum_apply]
simp [of_apply]
theorem mk_injective (s : Finset ι) : Function.Injective (mk β s) :=
DFinsupp.mk_injective s
theorem of_injective (i : ι) : Function.Injective (of β i) :=
DFinsupp.single_injective
@[elab_as_elim]
protected theorem induction_on {motive : (⨁ i, β i) → Prop} (x : ⨁ i, β i) (zero : motive 0)
(of : ∀ (i : ι) (x : β i), motive (of β i x))
(add : ∀ x y, motive x → motive y → motive (x + y)) : motive x := by
apply DFinsupp.induction x zero
intro i b f h1 h2 ih
solve_by_elim
/-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`,
then they are equal. -/
theorem addHom_ext {γ : Type*} [AddZeroClass γ] ⦃f g : (⨁ i, β i) →+ γ⦄
(H : ∀ (i : ι) (y : β i), f (of _ i y) = g (of _ i y)) : f = g :=
DFinsupp.addHom_ext H
/-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`,
then they are equal.
See note [partially-applied ext lemmas]. -/
@[ext high]
theorem addHom_ext' {γ : Type*} [AddZeroClass γ] ⦃f g : (⨁ i, β i) →+ γ⦄
(H : ∀ i : ι, f.comp (of _ i) = g.comp (of _ i)) : f = g :=
addHom_ext fun i => DFunLike.congr_fun <| H i
variable {γ : Type u₁} [AddCommMonoid γ]
section ToAddMonoid
variable (φ : ∀ i, β i →+ γ) (ψ : (⨁ i, β i) →+ γ)
-- Porting note: The elaborator is struggling with `liftAddHom`. Passing it `β` explicitly helps.
-- This applies to roughly the remainder of the file.
/-- `toAddMonoid φ` is the natural homomorphism from `⨁ i, β i` to `γ`
induced by a family `φ` of homomorphisms `β i → γ`. -/
def toAddMonoid : (⨁ i, β i) →+ γ :=
DFinsupp.liftAddHom (β := β) φ
@[simp]
theorem toAddMonoid_of (i) (x : β i) : toAddMonoid φ (of β i x) = φ i x :=
DFinsupp.liftAddHom_apply_single φ i x
theorem toAddMonoid.unique (f : ⨁ i, β i) : ψ f = toAddMonoid (fun i => ψ.comp (of β i)) f := by
congr
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` applies addHom_ext' here, which isn't what we want.
apply DFinsupp.addHom_ext'
simp [toAddMonoid, of]
lemma toAddMonoid_injective : Injective (toAddMonoid : (∀ i, β i →+ γ) → (⨁ i, β i) →+ γ) :=
DFinsupp.liftAddHom.injective
@[simp] lemma toAddMonoid_inj {f g : ∀ i, β i →+ γ} : toAddMonoid f = toAddMonoid g ↔ f = g :=
toAddMonoid_injective.eq_iff
end ToAddMonoid
section FromAddMonoid
/-- `fromAddMonoid φ` is the natural homomorphism from `γ` to `⨁ i, β i`
induced by a family `φ` of homomorphisms `γ → β i`.
Note that this is not an isomorphism. Not every homomorphism `γ →+ ⨁ i, β i` arises in this way. -/
def fromAddMonoid : (⨁ i, γ →+ β i) →+ γ →+ ⨁ i, β i :=
toAddMonoid fun i => AddMonoidHom.compHom (of β i)
@[simp]
theorem fromAddMonoid_of (i : ι) (f : γ →+ β i) : fromAddMonoid (of _ i f) = (of _ i).comp f := by
rw [fromAddMonoid, toAddMonoid_of]
rfl
theorem fromAddMonoid_of_apply (i : ι) (f : γ →+ β i) (x : γ) :
fromAddMonoid (of _ i f) x = of _ i (f x) := by
rw [fromAddMonoid_of, AddMonoidHom.coe_comp, Function.comp]
end FromAddMonoid
variable (β)
-- TODO: generalize this to remove the assumption `S ⊆ T`.
/-- `setToSet β S T h` is the natural homomorphism `⨁ (i : S), β i → ⨁ (i : T), β i`,
where `h : S ⊆ T`. -/
def setToSet (S T : Set ι) (H : S ⊆ T) : (⨁ i : S, β i) →+ ⨁ i : T, β i :=
toAddMonoid fun i => of (fun i : Subtype T => β i) ⟨↑i, H i.2⟩
end DecidableEq
instance unique [∀ i, Subsingleton (β i)] : Unique (⨁ i, β i) :=
DFinsupp.unique
/-- A direct sum over an empty type is trivial. -/
instance uniqueOfIsEmpty [IsEmpty ι] : Unique (⨁ i, β i) :=
DFinsupp.uniqueOfIsEmpty
/-- The natural equivalence between `⨁ _ : ι, M` and `M` when `Unique ι`. -/
protected def id (M : Type v) (ι : Type* := PUnit) [AddCommMonoid M] [Unique ι] :
(⨁ _ : ι, M) ≃+ M :=
{
DirectSum.toAddMonoid fun _ =>
AddMonoidHom.id
M with
toFun := DirectSum.toAddMonoid fun _ => AddMonoidHom.id M
invFun := of (fun _ => M) default
left_inv := fun x =>
DirectSum.induction_on x (by rw [AddMonoidHom.map_zero, AddMonoidHom.map_zero])
(fun p x => by rw [Unique.default_eq p, toAddMonoid_of]; rfl) fun x y ihx ihy => by
rw [AddMonoidHom.map_add, AddMonoidHom.map_add, ihx, ihy]
right_inv := fun _ => toAddMonoid_of _ _ _ }
section CongrLeft
variable {κ : Type*}
/-- Reindexing terms of a direct sum. -/
def equivCongrLeft (h : ι ≃ κ) : (⨁ i, β i) ≃+ ⨁ k, β (h.symm k) :=
{ DFinsupp.equivCongrLeft h with map_add' := DFinsupp.comapDomain'_add _ h.right_inv}
@[simp]
theorem equivCongrLeft_apply (h : ι ≃ κ) (f : ⨁ i, β i) (k : κ) :
equivCongrLeft h f k = f (h.symm k) := by
exact DFinsupp.comapDomain'_apply _ h.right_inv _ _
end CongrLeft
section Option
variable {α : Option ι → Type w} [∀ i, AddCommMonoid (α i)]
/-- Isomorphism obtained by separating the term of index `none` of a direct sum over `Option ι`. -/
@[simps!]
noncomputable def addEquivProdDirectSum : (⨁ i, α i) ≃+ α none × ⨁ i, α (some i) :=
{ DFinsupp.equivProdDFinsupp with map_add' := DFinsupp.equivProdDFinsupp_add }
end Option
section Sigma
variable [DecidableEq ι] {α : ι → Type u} {δ : ∀ i, α i → Type w} [∀ i j, AddCommMonoid (δ i j)]
/-- The natural map between `⨁ (i : Σ i, α i), δ i.1 i.2` and `⨁ i (j : α i), δ i j`. -/
def sigmaCurry : (⨁ i : Σ _i, _, δ i.1 i.2) →+ ⨁ (i) (j), δ i j where
toFun := DFinsupp.sigmaCurry (δ := δ)
map_zero' := DFinsupp.sigmaCurry_zero
map_add' f g := DFinsupp.sigmaCurry_add f g
@[simp]
theorem sigmaCurry_apply (f : ⨁ i : Σ _i, _, δ i.1 i.2) (i : ι) (j : α i) :
sigmaCurry f i j = f ⟨i, j⟩ :=
DFinsupp.sigmaCurry_apply (δ := δ) _ i j
/-- The natural map between `⨁ i (j : α i), δ i j` and `Π₀ (i : Σ i, α i), δ i.1 i.2`, inverse of
`curry`. -/
def sigmaUncurry : (⨁ (i) (j), δ i j) →+ ⨁ i : Σ _i, _, δ i.1 i.2 where
toFun := DFinsupp.sigmaUncurry
map_zero' := DFinsupp.sigmaUncurry_zero
map_add' := DFinsupp.sigmaUncurry_add
@[simp]
theorem sigmaUncurry_apply (f : ⨁ (i) (j), δ i j) (i : ι) (j : α i) :
sigmaUncurry f ⟨i, j⟩ = f i j :=
DFinsupp.sigmaUncurry_apply f i j
/-- The natural map between `⨁ (i : Σ i, α i), δ i.1 i.2` and `⨁ i (j : α i), δ i j`. -/
def sigmaCurryEquiv : (⨁ i : Σ _i, _, δ i.1 i.2) ≃+ ⨁ (i) (j), δ i j :=
{ sigmaCurry, DFinsupp.sigmaCurryEquiv with }
end Sigma
/-- The canonical embedding from `⨁ i, A i` to `M` where `A` is a collection of `AddSubmonoid M`
indexed by `ι`.
When `S = Submodule _ M`, this is available as a `LinearMap`, `DirectSum.coe_linearMap`. -/
protected def coeAddMonoidHom {M S : Type*} [DecidableEq ι] [AddCommMonoid M] [SetLike S M]
[AddSubmonoidClass S M] (A : ι → S) : (⨁ i, A i) →+ M :=
toAddMonoid fun i => AddSubmonoidClass.subtype (A i)
theorem coeAddMonoidHom_eq_dfinsuppSum [DecidableEq ι]
{M S : Type*} [DecidableEq M] [AddCommMonoid M]
[SetLike S M] [AddSubmonoidClass S M] (A : ι → S) (x : DirectSum ι fun i => A i) :
DirectSum.coeAddMonoidHom A x = DFinsupp.sum x fun i => (fun x : A i => ↑x) := by
simp only [DirectSum.coeAddMonoidHom, toAddMonoid, DFinsupp.liftAddHom, AddEquiv.coe_mk,
Equiv.coe_fn_mk]
exact DFinsupp.sumAddHom_apply _ x
@[deprecated (since := "2025-04-06")]
alias coeAddMonoidHom_eq_dfinsupp_sum := coeAddMonoidHom_eq_dfinsuppSum
@[simp]
theorem coeAddMonoidHom_of {M S : Type*} [DecidableEq ι] [AddCommMonoid M] [SetLike S M]
[AddSubmonoidClass S M] (A : ι → S) (i : ι) (x : A i) :
DirectSum.coeAddMonoidHom A (of (fun i => A i) i x) = x :=
toAddMonoid_of _ _ _
theorem coe_of_apply {M S : Type*} [DecidableEq ι] [AddCommMonoid M] [SetLike S M]
[AddSubmonoidClass S M] {A : ι → S} (i j : ι) (x : A i) :
(of (fun i ↦ {x // x ∈ A i}) i x j : M) = if i = j then x else 0 := by
obtain rfl | h := Decidable.eq_or_ne i j
· rw [DirectSum.of_eq_same, if_pos rfl]
· rw [DirectSum.of_eq_of_ne _ _ _ h, if_neg h, ZeroMemClass.coe_zero, ZeroMemClass.coe_zero]
/-- The `DirectSum` formed by a collection of additive submonoids (or subgroups, or submodules) of
`M` is said to be internal if the canonical map `(⨁ i, A i) →+ M` is bijective.
For the alternate statement in terms of independence and spanning, see
`DirectSum.subgroup_isInternal_iff_iSupIndep_and_supr_eq_top` and
`DirectSum.isInternal_submodule_iff_iSupIndep_and_iSup_eq_top`. -/
def IsInternal {M S : Type*} [DecidableEq ι] [AddCommMonoid M] [SetLike S M]
[AddSubmonoidClass S M] (A : ι → S) : Prop :=
Function.Bijective (DirectSum.coeAddMonoidHom A)
theorem IsInternal.addSubmonoid_iSup_eq_top {M : Type*} [DecidableEq ι] [AddCommMonoid M]
(A : ι → AddSubmonoid M) (h : IsInternal A) : iSup A = ⊤ := by
rw [AddSubmonoid.iSup_eq_mrange_dfinsuppSumAddHom, AddMonoidHom.mrange_eq_top]
exact Function.Bijective.surjective h
variable {M S : Type*} [AddCommMonoid M] [SetLike S M] [AddSubmonoidClass S M]
theorem support_subset [DecidableEq ι] [DecidableEq M] (A : ι → S) (x : DirectSum ι fun i => A i) :
(Function.support fun i => (x i : M)) ⊆ ↑(DFinsupp.support x) := by
intro m
simp only [Function.mem_support, Finset.mem_coe, DFinsupp.mem_support_toFun, not_imp_not,
ZeroMemClass.coe_eq_zero, imp_self]
theorem finite_support (A : ι → S) (x : DirectSum ι fun i => A i) :
(Function.support fun i => (x i : M)).Finite := by
classical
exact (DFinsupp.support x).finite_toSet.subset (DirectSum.support_subset _ x)
section map
variable {ι : Type*} {α : ι → Type*} {β : ι → Type*} [∀ i, AddCommMonoid (α i)]
variable [∀ i, AddCommMonoid (β i)] (f : ∀ (i : ι), α i →+ β i)
/-- create a homomorphism from `⨁ i, α i` to `⨁ i, β i` by giving the component-wise map `f`. -/
def map : (⨁ i, α i) →+ ⨁ i, β i := DFinsupp.mapRange.addMonoidHom f
@[simp] lemma map_of [DecidableEq ι] (i : ι) (x : α i) : map f (of α i x) = of β i (f i x) :=
DFinsupp.mapRange_single (hf := fun _ => map_zero _)
@[simp] lemma map_apply (i : ι) (x : ⨁ i, α i) : map f x i = f i (x i) :=
DFinsupp.mapRange_apply (hf := fun _ => map_zero _) _ _ _
@[simp] lemma map_id :
(map (fun i ↦ AddMonoidHom.id (α i))) = AddMonoidHom.id (⨁ i, α i) :=
DFinsupp.mapRange.addMonoidHom_id
@[simp] lemma map_comp {γ : ι → Type*} [∀ i, AddCommMonoid (γ i)]
(g : ∀ (i : ι), β i →+ γ i) :
(map (fun i ↦ (g i).comp (f i))) = (map g).comp (map f) :=
DFinsupp.mapRange.addMonoidHom_comp _ _
lemma map_injective : Function.Injective (map f) ↔ ∀ i, Function.Injective (f i) := by
classical exact DFinsupp.mapRange_injective (hf := fun _ ↦ map_zero _)
lemma map_surjective : Function.Surjective (map f) ↔ (∀ i, Function.Surjective (f i)) := by
classical exact DFinsupp.mapRange_surjective (hf := fun _ ↦ map_zero _)
lemma map_eq_iff (x y : ⨁ i, α i) :
map f x = map f y ↔ ∀ i, f i (x i) = f i (y i) := by
simp_rw [DirectSum.ext_iff, map_apply]
end map
end DirectSum
/-- The canonical isomorphism of a finite direct sum of additive commutative monoids
and the corresponding finite product. -/
def DirectSum.addEquivProd {ι : Type*} [Fintype ι] (G : ι → Type*) [(i : ι) → AddCommMonoid (G i)] :
DirectSum ι G ≃+ ((i : ι) → G i) :=
⟨DFinsupp.equivFunOnFintype, fun g h ↦ funext fun _ ↦ by
simp only [DFinsupp.equivFunOnFintype, Equiv.toFun_as_coe, Equiv.coe_fn_mk, add_apply,
Pi.add_apply]⟩
|
ProdUnivMany.lean
|
import Mathlib.Data.Fin.Tuple.Reflection
@[to_additive]
lemma prod_test (R : Type) [CommMonoid R] (f : Fin 10 → R) :
∏ i, f i = f 0 * f 1 * f 2 * f 3 * f 4 * f 5 * f 6 * f 7 * f 8 * f 9 := by
simp only [Fin.prod_univ_ofNat]
/--
info: sum_test (R : Type) [AddCommMonoid R] (f : Fin 10 → R) :
∑ i, f i = f 0 + f 1 + f 2 + f 3 + f 4 + f 5 + f 6 + f 7 + f 8 + f 9
-/
#guard_msgs in
#check sum_test
example (R : Type) [AddCommMonoid R] (f : Fin 10 → R) :
∑ i, f i = f 0 + f 1 + f 2 + f 3 + f 4 + f 5 + f 6 + f 7 + f 8 + f 9 := by
simp only [Fin.sum_univ_ofNat]
|
Defs.lean
|
/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import Mathlib.Data.FunLike.Equiv
import Mathlib.Data.Quot
import Mathlib.Data.Subtype
import Mathlib.Logic.Unique
import Mathlib.Tactic.Conv
import Mathlib.Tactic.Simps.Basic
import Mathlib.Tactic.Substs
/-!
# Equivalence between types
In this file we define two types:
* `Equiv α β` a.k.a. `α ≃ β`: a bijective map `α → β` bundled with its inverse map; we use this (and
not equality!) to express that various `Type`s or `Sort`s are equivalent.
* `Equiv.Perm α`: the group of permutations `α ≃ α`. More lemmas about `Equiv.Perm` can be found in
`Mathlib/GroupTheory/Perm.lean`.
Then we define
* canonical isomorphisms between various types: e.g.,
- `Equiv.refl α` is the identity map interpreted as `α ≃ α`;
* operations on equivalences: e.g.,
- `Equiv.symm e : β ≃ α` is the inverse of `e : α ≃ β`;
- `Equiv.trans e₁ e₂ : α ≃ γ` is the composition of `e₁ : α ≃ β` and `e₂ : β ≃ γ` (note the order
of the arguments!);
* definitions that transfer some instances along an equivalence. By convention, we transfer
instances from right to left.
- `Equiv.inhabited` takes `e : α ≃ β` and `[Inhabited β]` and returns `Inhabited α`;
- `Equiv.unique` takes `e : α ≃ β` and `[Unique β]` and returns `Unique α`;
- `Equiv.decidableEq` takes `e : α ≃ β` and `[DecidableEq β]` and returns `DecidableEq α`.
More definitions of this kind can be found in other files.
E.g., `Mathlib/Algebra/Equiv/TransferInstance.lean` does it for many algebraic type classes like
`Group`, `Module`, etc.
Many more such isomorphisms and operations are defined in `Mathlib/Logic/Equiv/Basic.lean`.
## Tags
equivalence, congruence, bijective map
-/
open Function
universe u v w z
variable {α : Sort u} {β : Sort v} {γ : Sort w}
/-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/
structure Equiv (α : Sort*) (β : Sort _) where
/-- The forward map of an equivalence.
Do NOT use directly. Use the coercion instead. -/
protected toFun : α → β
/-- The backward map of an equivalence.
Do NOT use `e.invFun` directly. Use the coercion of `e.symm` instead. -/
protected invFun : β → α
protected left_inv : LeftInverse invFun toFun := by intro; first | rfl | ext <;> rfl
protected right_inv : RightInverse invFun toFun := by intro; first | rfl | ext <;> rfl
@[inherit_doc]
infixl:25 " ≃ " => Equiv
/-- Turn an element of a type `F` satisfying `EquivLike F α β` into an actual
`Equiv`. This is declared as the default coercion from `F` to `α ≃ β`. -/
@[coe]
def EquivLike.toEquiv {F} [EquivLike F α β] (f : F) : α ≃ β where
toFun := f
invFun := EquivLike.inv f
left_inv := EquivLike.left_inv f
right_inv := EquivLike.right_inv f
/-- Any type satisfying `EquivLike` can be cast into `Equiv` via `EquivLike.toEquiv`. -/
instance {F} [EquivLike F α β] : CoeTC F (α ≃ β) :=
⟨EquivLike.toEquiv⟩
/-- `Perm α` is the type of bijections from `α` to itself. -/
abbrev Equiv.Perm (α : Sort*) :=
Equiv α α
namespace Equiv
instance : EquivLike (α ≃ β) α β where
coe := Equiv.toFun
inv := Equiv.invFun
left_inv := Equiv.left_inv
right_inv := Equiv.right_inv
coe_injective' e₁ e₂ h₁ h₂ := by cases e₁; cases e₂; congr
/-- Deprecated helper instance for when inference gets stuck on following the normal chain
`EquivLike → FunLike`. -/
@[deprecated EquivLike.toFunLike (since := "2025-06-20")]
def instFunLike : FunLike (α ≃ β) α β where
coe := Equiv.toFun
coe_injective' := DFunLike.coe_injective
@[simp, norm_cast]
lemma _root_.EquivLike.coe_coe {F} [EquivLike F α β] (e : F) :
((e : α ≃ β) : α → β) = e := rfl
@[simp, grind =] theorem coe_fn_mk (f : α → β) (g l r) : (Equiv.mk f g l r : α → β) = f :=
rfl
/-- The map `(r ≃ s) → (r → s)` is injective. -/
theorem coe_fn_injective : @Function.Injective (α ≃ β) (α → β) (fun e => e) :=
DFunLike.coe_injective'
protected theorem coe_inj {e₁ e₂ : α ≃ β} : (e₁ : α → β) = e₂ ↔ e₁ = e₂ :=
@DFunLike.coe_fn_eq _ _ _ _ e₁ e₂
@[ext] theorem ext {f g : Equiv α β} (H : ∀ x, f x = g x) : f = g := DFunLike.ext f g H
protected theorem congr_arg {f : Equiv α β} {x x' : α} : x = x' → f x = f x' :=
DFunLike.congr_arg f
protected theorem congr_fun {f g : Equiv α β} (h : f = g) (x : α) : f x = g x :=
DFunLike.congr_fun h x
@[ext] theorem Perm.ext {σ τ : Equiv.Perm α} (H : ∀ x, σ x = τ x) : σ = τ := Equiv.ext H
protected theorem Perm.congr_arg {f : Equiv.Perm α} {x x' : α} : x = x' → f x = f x' :=
Equiv.congr_arg
protected theorem Perm.congr_fun {f g : Equiv.Perm α} (h : f = g) (x : α) : f x = g x :=
Equiv.congr_fun h x
/-- Any type is equivalent to itself. -/
@[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, fun _ => rfl, fun _ => rfl⟩
instance inhabited' : Inhabited (α ≃ α) := ⟨Equiv.refl α⟩
/-- Inverse of an equivalence `e : α ≃ β`. -/
@[symm]
protected def symm (e : α ≃ β) : β ≃ α := ⟨e.invFun, e.toFun, e.right_inv, e.left_inv⟩
/-- See Note [custom simps projection] -/
def Simps.symm_apply (e : α ≃ β) : β → α := e.symm
initialize_simps_projections Equiv (toFun → apply, invFun → symm_apply)
/-- Restatement of `Equiv.left_inv` in terms of `Function.LeftInverse`. -/
theorem left_inv' (e : α ≃ β) : Function.LeftInverse e.symm e := e.left_inv
/-- Restatement of `Equiv.right_inv` in terms of `Function.RightInverse`. -/
theorem right_inv' (e : α ≃ β) : Function.RightInverse e.symm e := e.right_inv
/-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/
@[trans]
protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩
@[simps]
instance : Trans Equiv Equiv Equiv where
trans := Equiv.trans
/-- `Equiv.symm` defines an equivalence between `α ≃ β` and `β ≃ α`. -/
@[simps!]
def symmEquiv (α β : Sort*) : (α ≃ β) ≃ (β ≃ α) where
toFun := .symm
invFun := .symm
@[simp, mfld_simps] theorem toFun_as_coe (e : α ≃ β) : e.toFun = e := rfl
@[simp, mfld_simps] theorem invFun_as_coe (e : α ≃ β) : e.invFun = e.symm := rfl
protected theorem injective (e : α ≃ β) : Injective e := EquivLike.injective e
protected theorem surjective (e : α ≃ β) : Surjective e := EquivLike.surjective e
protected theorem bijective (e : α ≃ β) : Bijective e := EquivLike.bijective e
protected theorem subsingleton (e : α ≃ β) [Subsingleton β] : Subsingleton α :=
e.injective.subsingleton
protected theorem subsingleton.symm (e : α ≃ β) [Subsingleton α] : Subsingleton β :=
e.symm.injective.subsingleton
theorem subsingleton_congr (e : α ≃ β) : Subsingleton α ↔ Subsingleton β :=
⟨fun _ => e.symm.subsingleton, fun _ => e.subsingleton⟩
instance equiv_subsingleton_cod [Subsingleton β] : Subsingleton (α ≃ β) :=
⟨fun _ _ => Equiv.ext fun _ => Subsingleton.elim _ _⟩
instance equiv_subsingleton_dom [Subsingleton α] : Subsingleton (α ≃ β) :=
⟨fun f _ => Equiv.ext fun _ => @Subsingleton.elim _ (Equiv.subsingleton.symm f) _ _⟩
instance permUnique [Subsingleton α] : Unique (Perm α) :=
uniqueOfSubsingleton (Equiv.refl α)
theorem Perm.subsingleton_eq_refl [Subsingleton α] (e : Perm α) : e = Equiv.refl α :=
Subsingleton.elim _ _
protected theorem nontrivial {α β} (e : α ≃ β) [Nontrivial β] : Nontrivial α :=
e.surjective.nontrivial
theorem nontrivial_congr {α β} (e : α ≃ β) : Nontrivial α ↔ Nontrivial β :=
⟨fun _ ↦ e.symm.nontrivial, fun _ ↦ e.nontrivial⟩
/-- Transfer `DecidableEq` across an equivalence. -/
protected def decidableEq (e : α ≃ β) [DecidableEq β] : DecidableEq α :=
e.injective.decidableEq
theorem nonempty_congr (e : α ≃ β) : Nonempty α ↔ Nonempty β := Nonempty.congr e e.symm
protected theorem nonempty (e : α ≃ β) [Nonempty β] : Nonempty α := e.nonempty_congr.mpr ‹_›
/-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/
protected def inhabited [Inhabited β] (e : α ≃ β) : Inhabited α := ⟨e.symm default⟩
/-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/
protected def unique [Unique β] (e : α ≃ β) : Unique α := e.symm.surjective.unique
/-- Equivalence between equal types. -/
protected def cast {α β : Sort _} (h : α = β) : α ≃ β :=
⟨cast h, cast h.symm, fun _ => by cases h; rfl, fun _ => by cases h; rfl⟩
@[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((Equiv.mk f g l r).symm : β → α) = g := rfl
@[simp] theorem coe_refl : (Equiv.refl α : α → α) = id := rfl
/-- This cannot be a `simp` lemmas as it incorrectly matches against `e : α ≃ synonym α`, when
`synonym α` is semireducible. This makes a mess of `Multiplicative.ofAdd` etc. -/
theorem Perm.coe_subsingleton {α : Type*} [Subsingleton α] (e : Perm α) : (e : α → α) = id := by
rw [Perm.subsingleton_eq_refl e, coe_refl]
@[simp] theorem refl_apply (x : α) : Equiv.refl α x = x := rfl
@[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : (f.trans g : α → γ) = g ∘ f := rfl
@[simp] theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl
@[simp, grind =] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x := e.right_inv x
@[simp, grind =] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x := e.left_inv x
@[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply
@[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply
@[simp] lemma _root_.EquivLike.apply_coe_symm_apply {F} [EquivLike F α β] (e : F) (x : β) :
e ((e : α ≃ β).symm x) = x :=
(e : α ≃ β).apply_symm_apply x
@[simp] lemma _root_.EquivLike.coe_symm_apply_apply {F} [EquivLike F α β] (e : F) (x : α) :
(e : α ≃ β).symm (e x) = x :=
(e : α ≃ β).symm_apply_apply x
@[simp] lemma _root_.EquivLike.coe_symm_comp_self {F} [EquivLike F α β] (e : F) :
(e : α ≃ β).symm ∘ e = id :=
(e : α ≃ β).symm_comp_self
@[simp] lemma _root_.EquivLike.self_comp_coe_symm {F} [EquivLike F α β] (e : F) :
e ∘ (e : α ≃ β).symm = id :=
(e : α ≃ β).self_comp_symm
@[simp] theorem symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) :
(f.trans g).symm a = f.symm (g.symm a) := rfl
theorem symm_symm_apply (f : α ≃ β) (b : α) : f.symm.symm b = f b := rfl
theorem apply_eq_iff_eq (f : α ≃ β) {x y : α} : f x = f y ↔ x = y := EquivLike.apply_eq_iff_eq f
theorem apply_eq_iff_eq_symm_apply {x : α} {y : β} (f : α ≃ β) : f x = y ↔ x = f.symm y := by
conv_lhs => rw [← apply_symm_apply f y]
rw [apply_eq_iff_eq]
@[simp] theorem cast_apply {α β} (h : α = β) (x : α) : Equiv.cast h x = cast h x := rfl
@[simp] theorem cast_symm {α β} (h : α = β) : (Equiv.cast h).symm = Equiv.cast h.symm := rfl
@[simp] theorem cast_refl {α} (h : α = α := rfl) : Equiv.cast h = Equiv.refl α := rfl
@[simp] theorem cast_trans {α β γ} (h : α = β) (h2 : β = γ) :
(Equiv.cast h).trans (Equiv.cast h2) = Equiv.cast (h.trans h2) :=
ext fun x => by substs h h2; rfl
theorem cast_eq_iff_heq {α β} (h : α = β) {a : α} {b : β} : Equiv.cast h a = b ↔ a ≍ b := by
subst h; simp
theorem symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y :=
⟨fun H => by simp [H.symm], fun H => by simp [H]⟩
theorem eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x :=
(eq_comm.trans e.symm_apply_eq).trans eq_comm
@[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := rfl
theorem symm_bijective : Function.Bijective (Equiv.symm : (α ≃ β) → β ≃ α) :=
Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩
@[simp] theorem trans_refl (e : α ≃ β) : e.trans (Equiv.refl β) = e := by cases e; rfl
@[simp] theorem refl_symm : (Equiv.refl α).symm = Equiv.refl α := rfl
@[simp] theorem refl_trans (e : α ≃ β) : (Equiv.refl α).trans e = e := by cases e; rfl
@[simp] theorem symm_trans_self (e : α ≃ β) : e.symm.trans e = Equiv.refl β := ext <| by simp
@[simp] theorem self_trans_symm (e : α ≃ β) : e.trans e.symm = Equiv.refl α := ext <| by simp
theorem trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) :
(ab.trans bc).trans cd = ab.trans (bc.trans cd) := Equiv.ext fun _ => rfl
theorem leftInverse_symm (f : Equiv α β) : LeftInverse f.symm f := f.left_inv
theorem rightInverse_symm (f : Equiv α β) : Function.RightInverse f.symm f := f.right_inv
theorem injective_comp (e : α ≃ β) (f : β → γ) : Injective (f ∘ e) ↔ Injective f :=
EquivLike.injective_comp e f
theorem comp_injective (f : α → β) (e : β ≃ γ) : Injective (e ∘ f) ↔ Injective f :=
EquivLike.comp_injective f e
theorem surjective_comp (e : α ≃ β) (f : β → γ) : Surjective (f ∘ e) ↔ Surjective f :=
EquivLike.surjective_comp e f
theorem comp_surjective (f : α → β) (e : β ≃ γ) : Surjective (e ∘ f) ↔ Surjective f :=
EquivLike.comp_surjective f e
theorem bijective_comp (e : α ≃ β) (f : β → γ) : Bijective (f ∘ e) ↔ Bijective f :=
EquivLike.bijective_comp e f
theorem comp_bijective (f : α → β) (e : β ≃ γ) : Bijective (e ∘ f) ↔ Bijective f :=
EquivLike.comp_bijective f e
@[simp]
theorem extend_apply {f : α ≃ β} (g : α → γ) (e' : β → γ) (b : β) :
extend f g e' b = g (f.symm b) := by
rw [← f.apply_symm_apply b, f.injective.extend_apply, apply_symm_apply]
/-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ`
is equivalent to the type of equivalences `β ≃ δ`. -/
def equivCongr {δ : Sort*} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) where
toFun ac := (ab.symm.trans ac).trans cd
invFun bd := ab.trans <| bd.trans <| cd.symm
left_inv ac := by ext x; simp only [trans_apply, symm_apply_apply]
right_inv ac := by ext x; simp only [trans_apply, apply_symm_apply]
@[simp] theorem equivCongr_refl {α β} :
(Equiv.refl α).equivCongr (Equiv.refl β) = Equiv.refl (α ≃ β) := by ext; rfl
@[simp] theorem equivCongr_symm {δ} (ab : α ≃ β) (cd : γ ≃ δ) :
(ab.equivCongr cd).symm = ab.symm.equivCongr cd.symm := by ext; rfl
@[simp] theorem equivCongr_trans {δ ε ζ} (ab : α ≃ β) (de : δ ≃ ε) (bc : β ≃ γ) (ef : ε ≃ ζ) :
(ab.equivCongr de).trans (bc.equivCongr ef) = (ab.trans bc).equivCongr (de.trans ef) := by
ext; rfl
@[simp] theorem equivCongr_refl_left {α β γ} (bg : β ≃ γ) (e : α ≃ β) :
(Equiv.refl α).equivCongr bg e = e.trans bg := rfl
@[simp] theorem equivCongr_refl_right {α β} (ab e : α ≃ β) :
ab.equivCongr (Equiv.refl β) e = ab.symm.trans e := rfl
@[simp] theorem equivCongr_apply_apply {δ} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x) :
ab.equivCongr cd e x = cd (e (ab.symm x)) := rfl
section permCongr
variable {α' β' : Type*} (e : α' ≃ β')
/-- If `α` is equivalent to `β`, then `Perm α` is equivalent to `Perm β`. -/
def permCongr : Perm α' ≃ Perm β' := equivCongr e e
theorem permCongr_def (p : Equiv.Perm α') : e.permCongr p = (e.symm.trans p).trans e := rfl
@[simp] theorem permCongr_refl : e.permCongr (Equiv.refl _) = Equiv.refl _ := by
simp [permCongr_def]
@[simp] theorem permCongr_symm : e.permCongr.symm = e.symm.permCongr := rfl
@[simp] theorem permCongr_apply (p : Equiv.Perm α') (x) : e.permCongr p x = e (p (e.symm x)) := rfl
theorem permCongr_symm_apply (p : Equiv.Perm β') (x) :
e.permCongr.symm p x = e.symm (p (e x)) := rfl
theorem permCongr_trans (p p' : Equiv.Perm α') :
(e.permCongr p).trans (e.permCongr p') = e.permCongr (p.trans p') := by
ext; simp only [trans_apply, permCongr_apply, symm_apply_apply]
end permCongr
/-- Two empty types are equivalent. -/
def equivOfIsEmpty (α β : Sort*) [IsEmpty α] [IsEmpty β] : α ≃ β :=
⟨isEmptyElim, isEmptyElim, isEmptyElim, isEmptyElim⟩
/-- If `α` is an empty type, then it is equivalent to the `Empty` type. -/
def equivEmpty (α : Sort u) [IsEmpty α] : α ≃ Empty := equivOfIsEmpty α _
/-- If `α` is an empty type, then it is equivalent to the `PEmpty` type in any universe. -/
def equivPEmpty (α : Sort v) [IsEmpty α] : α ≃ PEmpty.{u} := equivOfIsEmpty α _
/-- `α` is equivalent to an empty type iff `α` is empty. -/
def equivEmptyEquiv (α : Sort u) : α ≃ Empty ≃ IsEmpty α :=
⟨fun e => Function.isEmpty e, @equivEmpty α, fun e => ext fun x => (e x).elim, fun _ => rfl⟩
/-- The `Sort` of proofs of a false proposition is equivalent to `PEmpty`. -/
def propEquivPEmpty {p : Prop} (h : ¬p) : p ≃ PEmpty := @equivPEmpty p <| IsEmpty.prop_iff.2 h
/-- If both `α` and `β` have a unique element, then `α ≃ β`. -/
@[simps]
def ofUnique (α β : Sort _) [Unique.{u} α] [Unique.{v} β] : α ≃ β where
toFun := default
invFun := default
left_inv _ := Subsingleton.elim _ _
right_inv _ := Subsingleton.elim _ _
/-- If `α` has a unique element, then it is equivalent to any `PUnit`. -/
@[simps!]
def equivPUnit (α : Sort u) [Unique α] : α ≃ PUnit.{v} := ofUnique α _
/-- The `Sort` of proofs of a true proposition is equivalent to `PUnit`. -/
def propEquivPUnit {p : Prop} (h : p) : p ≃ PUnit.{0} := @equivPUnit p <| uniqueProp h
/-- `ULift α` is equivalent to `α`. -/
@[simps -fullyApplied apply]
protected def ulift {α : Type v} : ULift.{u} α ≃ α :=
⟨ULift.down, ULift.up, ULift.up_down, ULift.down_up.{v, u}⟩
/-- `PLift α` is equivalent to `α`. -/
@[simps -fullyApplied apply]
protected def plift : PLift α ≃ α := ⟨PLift.down, PLift.up, PLift.up_down, PLift.down_up⟩
/-- equivalence of propositions is the same as iff -/
def ofIff {P Q : Prop} (h : P ↔ Q) : P ≃ Q := ⟨h.mp, h.mpr, fun _ => rfl, fun _ => rfl⟩
/-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁`
is equivalent to the type of maps `α₂ → β₂`. -/
@[simps apply]
def arrowCongr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) where
toFun f := e₂ ∘ f ∘ e₁.symm
invFun f := e₂.symm ∘ f ∘ e₁
left_inv f := funext fun x => by simp only [comp_apply, symm_apply_apply]
right_inv f := funext fun x => by simp only [comp_apply, apply_symm_apply]
theorem arrowCongr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂)
(f : α₁ → β₁) (g : β₁ → γ₁) :
arrowCongr ea ec (g ∘ f) = arrowCongr eb ec g ∘ arrowCongr ea eb f := by
ext; simp only [comp, arrowCongr_apply, eb.symm_apply_apply]
@[simp] theorem arrowCongr_refl {α β : Sort*} :
arrowCongr (Equiv.refl α) (Equiv.refl β) = Equiv.refl (α → β) := rfl
@[simp] theorem arrowCongr_trans {α₁ α₂ α₃ β₁ β₂ β₃ : Sort*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
arrowCongr (e₁.trans e₂) (e₁'.trans e₂') = (arrowCongr e₁ e₁').trans (arrowCongr e₂ e₂') := rfl
@[simp] theorem arrowCongr_symm {α₁ α₂ β₁ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(arrowCongr e₁ e₂).symm = arrowCongr e₁.symm e₂.symm := rfl
/-- A version of `Equiv.arrowCongr` in `Type`, rather than `Sort`.
The `equiv_rw` tactic is not able to use the default `Sort` level `Equiv.arrowCongr`,
because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`.
-/
@[simps! apply]
def arrowCongr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) :=
Equiv.arrowCongr hα hβ
@[simp] theorem arrowCongr'_refl {α β : Type*} :
arrowCongr' (Equiv.refl α) (Equiv.refl β) = Equiv.refl (α → β) := rfl
@[simp] theorem arrowCongr'_trans {α₁ α₂ β₁ β₂ α₃ β₃ : Type*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
arrowCongr' (e₁.trans e₂) (e₁'.trans e₂') = (arrowCongr' e₁ e₁').trans (arrowCongr' e₂ e₂') :=
rfl
@[simp] theorem arrowCongr'_symm {α₁ α₂ β₁ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(arrowCongr' e₁ e₂).symm = arrowCongr' e₁.symm e₂.symm := rfl
/-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/
@[simps! apply] def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrowCongr e e
@[simp] theorem conj_refl : conj (Equiv.refl α) = Equiv.refl (α → α) := rfl
@[simp] theorem conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl
@[simp] theorem conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) :
(e₁.trans e₂).conj = e₁.conj.trans e₂.conj := rfl
-- This should not be a simp lemma as long as `(∘)` is reducible:
-- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using
-- `f₁ := g` and `f₂ := fun x ↦ x`. This causes nontermination.
theorem conj_comp (e : α ≃ β) (f₁ f₂ : α → α) : e.conj (f₁ ∘ f₂) = e.conj f₁ ∘ e.conj f₂ := by
apply arrowCongr_comp
theorem eq_comp_symm {α β γ} (e : α ≃ β) (f : β → γ) (g : α → γ) : f = g ∘ e.symm ↔ f ∘ e = g :=
(e.arrowCongr (Equiv.refl γ)).symm_apply_eq.symm
theorem comp_symm_eq {α β γ} (e : α ≃ β) (f : β → γ) (g : α → γ) : g ∘ e.symm = f ↔ g = f ∘ e :=
(e.arrowCongr (Equiv.refl γ)).eq_symm_apply.symm
theorem eq_symm_comp {α β γ} (e : α ≃ β) (f : γ → α) (g : γ → β) : f = e.symm ∘ g ↔ e ∘ f = g :=
((Equiv.refl γ).arrowCongr e).eq_symm_apply
theorem symm_comp_eq {α β γ} (e : α ≃ β) (f : γ → α) (g : γ → β) : e.symm ∘ g = f ↔ g = e ∘ f :=
((Equiv.refl γ).arrowCongr e).symm_apply_eq
theorem trans_eq_refl_iff_eq_symm {f : α ≃ β} {g : β ≃ α} :
f.trans g = Equiv.refl α ↔ f = g.symm := by
rw [← Equiv.coe_inj, coe_trans, coe_refl, ← eq_symm_comp, comp_id, Equiv.coe_inj]
theorem trans_eq_refl_iff_symm_eq {f : α ≃ β} {g : β ≃ α} :
f.trans g = Equiv.refl α ↔ f.symm = g := by
rw [trans_eq_refl_iff_eq_symm]
exact ⟨fun h ↦ h ▸ rfl, fun h ↦ h ▸ rfl⟩
theorem eq_symm_iff_trans_eq_refl {f : α ≃ β} {g : β ≃ α} :
f = g.symm ↔ f.trans g = Equiv.refl α :=
trans_eq_refl_iff_eq_symm.symm
theorem symm_eq_iff_trans_eq_refl {f : α ≃ β} {g : β ≃ α} :
f.symm = g ↔ f.trans g = Equiv.refl α :=
trans_eq_refl_iff_symm_eq.symm
/-- `PUnit` sorts in any two universes are equivalent. -/
def punitEquivPUnit : PUnit.{v} ≃ PUnit.{w} :=
⟨fun _ => .unit, fun _ => .unit, fun ⟨⟩ => rfl, fun ⟨⟩ => rfl⟩
/-- `Prop` is noncomputably equivalent to `Bool`. -/
noncomputable def propEquivBool : Prop ≃ Bool where
toFun p := @decide p (Classical.propDecidable _)
invFun b := b
left_inv p := by simp
right_inv b := by simp
section
/-- The sort of maps to `PUnit.{v}` is equivalent to `PUnit.{w}`. -/
def arrowPUnitEquivPUnit (α : Sort*) : (α → PUnit.{v}) ≃ PUnit.{w} :=
⟨fun _ => .unit, fun _ _ => .unit, fun _ => rfl, fun _ => rfl⟩
/-- The equivalence `(∀ i, β i) ≃ β ⋆` when the domain of `β` only contains `⋆` -/
@[simps -fullyApplied]
def piUnique [Unique α] (β : α → Sort*) : (∀ i, β i) ≃ β default where
toFun f := f default
invFun := uniqueElim
left_inv f := by ext i; cases Unique.eq_default i; rfl
/-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/
@[simps! -fullyApplied apply symm_apply]
def funUnique (α β) [Unique.{u} α] : (α → β) ≃ β := piUnique _
/-- The sort of maps from `PUnit` is equivalent to the codomain. -/
def punitArrowEquiv (α : Sort*) : (PUnit.{u} → α) ≃ α := funUnique PUnit.{u} α
/-- The sort of maps from `True` is equivalent to the codomain. -/
def trueArrowEquiv (α : Sort*) : (True → α) ≃ α := funUnique _ _
/-- The sort of maps from a type that `IsEmpty` is equivalent to `PUnit`. -/
def arrowPUnitOfIsEmpty (α β : Sort*) [IsEmpty α] : (α → β) ≃ PUnit.{u} where
toFun _ := PUnit.unit
invFun _ := isEmptyElim
left_inv _ := funext isEmptyElim
/-- The sort of maps from `Empty` is equivalent to `PUnit`. -/
def emptyArrowEquivPUnit (α : Sort*) : (Empty → α) ≃ PUnit.{u} := arrowPUnitOfIsEmpty _ _
/-- The sort of maps from `PEmpty` is equivalent to `PUnit`. -/
def pemptyArrowEquivPUnit (α : Sort*) : (PEmpty → α) ≃ PUnit.{u} := arrowPUnitOfIsEmpty _ _
/-- The sort of maps from `False` is equivalent to `PUnit`. -/
def falseArrowEquivPUnit (α : Sort*) : (False → α) ≃ PUnit.{u} := arrowPUnitOfIsEmpty _ _
end
section
/-- A `PSigma`-type is equivalent to the corresponding `Sigma`-type. -/
@[simps apply symm_apply]
def psigmaEquivSigma {α} (β : α → Type*) : (Σ' i, β i) ≃ Σ i, β i where
toFun a := ⟨a.1, a.2⟩
invFun a := ⟨a.1, a.2⟩
/-- A `PSigma`-type is equivalent to the corresponding `Sigma`-type. -/
@[simps apply symm_apply]
def psigmaEquivSigmaPLift {α} (β : α → Sort*) : (Σ' i, β i) ≃ Σ i : PLift α, PLift (β i.down) where
toFun a := ⟨PLift.up a.1, PLift.up a.2⟩
invFun a := ⟨a.1.down, a.2.down⟩
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ' a, β₁ a` and
`Σ' a, β₂ a`. -/
@[simps apply]
def psigmaCongrRight {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Σ' a, β₁ a) ≃ Σ' a, β₂ a where
toFun a := ⟨a.1, F a.1 a.2⟩
invFun a := ⟨a.1, (F a.1).symm a.2⟩
left_inv | ⟨a, b⟩ => congr_arg (PSigma.mk a) <| symm_apply_apply (F a) b
right_inv | ⟨a, b⟩ => congr_arg (PSigma.mk a) <| apply_symm_apply (F a) b
theorem psigmaCongrRight_trans {α} {β₁ β₂ β₃ : α → Sort*}
(F : ∀ a, β₁ a ≃ β₂ a) (G : ∀ a, β₂ a ≃ β₃ a) :
(psigmaCongrRight F).trans (psigmaCongrRight G) =
psigmaCongrRight fun a => (F a).trans (G a) := rfl
theorem psigmaCongrRight_symm {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) :
(psigmaCongrRight F).symm = psigmaCongrRight fun a => (F a).symm := rfl
@[simp]
theorem psigmaCongrRight_refl {α} {β : α → Sort*} :
(psigmaCongrRight fun a => Equiv.refl (β a)) = Equiv.refl (Σ' a, β a) := rfl
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and
`Σ a, β₂ a`. -/
@[simps apply]
def sigmaCongrRight {α} {β₁ β₂ : α → Type*} (F : ∀ a, β₁ a ≃ β₂ a) : (Σ a, β₁ a) ≃ Σ a, β₂ a where
toFun a := ⟨a.1, F a.1 a.2⟩
invFun a := ⟨a.1, (F a.1).symm a.2⟩
left_inv | ⟨a, b⟩ => congr_arg (Sigma.mk a) <| symm_apply_apply (F a) b
right_inv | ⟨a, b⟩ => congr_arg (Sigma.mk a) <| apply_symm_apply (F a) b
theorem sigmaCongrRight_trans {α} {β₁ β₂ β₃ : α → Type*}
(F : ∀ a, β₁ a ≃ β₂ a) (G : ∀ a, β₂ a ≃ β₃ a) :
(sigmaCongrRight F).trans (sigmaCongrRight G) =
sigmaCongrRight fun a => (F a).trans (G a) := rfl
theorem sigmaCongrRight_symm {α} {β₁ β₂ : α → Type*} (F : ∀ a, β₁ a ≃ β₂ a) :
(sigmaCongrRight F).symm = sigmaCongrRight fun a => (F a).symm := rfl
@[simp]
theorem sigmaCongrRight_refl {α} {β : α → Type*} :
(sigmaCongrRight fun a => Equiv.refl (β a)) = Equiv.refl (Σ a, β a) := rfl
/-- A `PSigma` with `Prop` fibers is equivalent to the subtype. -/
def psigmaEquivSubtype {α : Type v} (P : α → Prop) : (Σ' i, P i) ≃ Subtype P where
toFun x := ⟨x.1, x.2⟩
invFun x := ⟨x.1, x.2⟩
/-- A `Sigma` with `PLift` fibers is equivalent to the subtype. -/
def sigmaPLiftEquivSubtype {α : Type v} (P : α → Prop) : (Σ i, PLift (P i)) ≃ Subtype P :=
((psigmaEquivSigma _).symm.trans
(psigmaCongrRight fun _ => Equiv.plift)).trans (psigmaEquivSubtype P)
/-- A `Sigma` with `fun i ↦ ULift (PLift (P i))` fibers is equivalent to `{ x // P x }`.
Variant of `sigmaPLiftEquivSubtype`.
-/
def sigmaULiftPLiftEquivSubtype {α : Type v} (P : α → Prop) :
(Σ i, ULift (PLift (P i))) ≃ Subtype P :=
(sigmaCongrRight fun _ => Equiv.ulift).trans (sigmaPLiftEquivSubtype P)
namespace Perm
/-- A family of permutations `Π a, Perm (β a)` generates a permutation `Perm (Σ a, β₁ a)`. -/
abbrev sigmaCongrRight {α} {β : α → Sort _} (F : ∀ a, Perm (β a)) : Perm (Σ a, β a) :=
Equiv.sigmaCongrRight F
@[simp] theorem sigmaCongrRight_trans {α} {β : α → Sort _}
(F : ∀ a, Perm (β a)) (G : ∀ a, Perm (β a)) :
(sigmaCongrRight F).trans (sigmaCongrRight G) = sigmaCongrRight fun a => (F a).trans (G a) :=
rfl
@[simp] theorem sigmaCongrRight_symm {α} {β : α → Sort _} (F : ∀ a, Perm (β a)) :
(sigmaCongrRight F).symm = sigmaCongrRight fun a => (F a).symm :=
rfl
@[simp] theorem sigmaCongrRight_refl {α} {β : α → Sort _} :
(sigmaCongrRight fun a => Equiv.refl (β a)) = Equiv.refl (Σ a, β a) :=
rfl
end Perm
/-- `Function.swap` as an equivalence. -/
@[simps -fullyApplied]
def functionSwap (α β : Sort*) (γ : α → β → Sort*) :
((a : α) → (b : β) → γ a b) ≃ ((b : β) → (a : α) → γ a b) where
toFun := Function.swap
invFun := Function.swap
theorem _root_.Function.swap_bijective {α β : Sort*} {γ : α → β → Sort*} :
Function.Bijective (@Function.swap _ _ γ) :=
functionSwap _ _ _ |>.bijective
/-- An equivalence `f : α₁ ≃ α₂` generates an equivalence between `Σ a, β (f a)` and `Σ a, β a`. -/
@[simps apply] def sigmaCongrLeft {α₁ α₂ : Type*} {β : α₂ → Sort _} (e : α₁ ≃ α₂) :
(Σ a : α₁, β (e a)) ≃ Σ a : α₂, β a where
toFun a := ⟨e a.1, a.2⟩
invFun a := ⟨e.symm a.1, (e.right_inv' a.1).symm ▸ a.2⟩
left_inv := fun ⟨a, b⟩ => by simp
right_inv := fun ⟨a, b⟩ => by simp
/-- Transporting a sigma type through an equivalence of the base -/
def sigmaCongrLeft' {α₁ α₂} {β : α₁ → Sort _} (f : α₁ ≃ α₂) :
(Σ a : α₁, β a) ≃ Σ a : α₂, β (f.symm a) := (sigmaCongrLeft f.symm).symm
/-- Transporting a sigma type through an equivalence of the base and a family of equivalences
of matching fibers -/
def sigmaCongr {α₁ α₂} {β₁ : α₁ → Sort _} {β₂ : α₂ → Sort _} (f : α₁ ≃ α₂)
(F : ∀ a, β₁ a ≃ β₂ (f a)) : Sigma β₁ ≃ Sigma β₂ :=
(sigmaCongrRight F).trans (sigmaCongrLeft f)
/-- `Sigma` type with a constant fiber is equivalent to the product. -/
@[simps (attrs := [`mfld_simps]) apply symm_apply]
def sigmaEquivProd (α β : Type*) : (Σ _ : α, β) ≃ α × β :=
⟨fun a => ⟨a.1, a.2⟩, fun a => ⟨a.1, a.2⟩, fun ⟨_, _⟩ => rfl, fun ⟨_, _⟩ => rfl⟩
/-- If each fiber of a `Sigma` type is equivalent to a fixed type, then the sigma type
is equivalent to the product. -/
def sigmaEquivProdOfEquiv {α β} {β₁ : α → Sort _} (F : ∀ a, β₁ a ≃ β) : Sigma β₁ ≃ α × β :=
(sigmaCongrRight F).trans (sigmaEquivProd α β)
/-- The dependent product of types is associative up to an equivalence. -/
def sigmaAssoc {α : Type*} {β : α → Type*} (γ : ∀ a : α, β a → Type*) :
(Σ ab : Σ a : α, β a, γ ab.1 ab.2) ≃ Σ a : α, Σ b : β a, γ a b where
toFun x := ⟨x.1.1, ⟨x.1.2, x.2⟩⟩
invFun x := ⟨⟨x.1, x.2.1⟩, x.2.2⟩
/-- The dependent product of sorts is associative up to an equivalence. -/
def pSigmaAssoc {α : Sort*} {β : α → Sort*} (γ : ∀ a : α, β a → Sort*) :
(Σ' ab : Σ' a : α, β a, γ ab.1 ab.2) ≃ Σ' a : α, Σ' b : β a, γ a b where
toFun x := ⟨x.1.1, ⟨x.1.2, x.2⟩⟩
invFun x := ⟨⟨x.1, x.2.1⟩, x.2.2⟩
end
variable {p : α → Prop} {q : β → Prop} (e : α ≃ β)
protected lemma forall_congr_right : (∀ a, q (e a)) ↔ ∀ b, q b :=
⟨fun h a ↦ by simpa using h (e.symm a), fun h _ ↦ h _⟩
protected lemma forall_congr_left : (∀ a, p a) ↔ ∀ b, p (e.symm b) :=
e.symm.forall_congr_right.symm
protected lemma forall_congr (h : ∀ a, p a ↔ q (e a)) : (∀ a, p a) ↔ ∀ b, q b :=
e.forall_congr_left.trans (by simp [h])
protected lemma forall_congr' (h : ∀ b, p (e.symm b) ↔ q b) : (∀ a, p a) ↔ ∀ b, q b :=
e.forall_congr_left.trans (by simp [h])
protected lemma exists_congr_right : (∃ a, q (e a)) ↔ ∃ b, q b :=
⟨fun ⟨_, h⟩ ↦ ⟨_, h⟩, fun ⟨a, h⟩ ↦ ⟨e.symm a, by simpa using h⟩⟩
protected lemma exists_congr_left : (∃ a, p a) ↔ ∃ b, p (e.symm b) :=
e.symm.exists_congr_right.symm
protected lemma exists_congr (h : ∀ a, p a ↔ q (e a)) : (∃ a, p a) ↔ ∃ b, q b :=
e.exists_congr_left.trans <| by simp [h]
protected lemma exists_congr' (h : ∀ b, p (e.symm b) ↔ q b) : (∃ a, p a) ↔ ∃ b, q b :=
e.exists_congr_left.trans <| by simp [h]
protected lemma exists_subtype_congr (e : {a // p a} ≃ {b // q b}) : (∃ a, p a) ↔ ∃ b, q b := by
simp [← nonempty_subtype, nonempty_congr e]
protected lemma existsUnique_congr_right : (∃! a, q (e a)) ↔ ∃! b, q b :=
e.exists_congr <| by simpa using fun _ _ ↦ e.forall_congr (by simp)
protected lemma existsUnique_congr_left : (∃! a, p a) ↔ ∃! b, p (e.symm b) :=
e.symm.existsUnique_congr_right.symm
protected lemma existsUnique_congr (h : ∀ a, p a ↔ q (e a)) : (∃! a, p a) ↔ ∃! b, q b :=
e.existsUnique_congr_left.trans <| by simp [h]
protected lemma existsUnique_congr' (h : ∀ b, p (e.symm b) ↔ q b) : (∃! a, p a) ↔ ∃! b, q b :=
e.existsUnique_congr_left.trans <| by simp [h]
protected lemma existsUnique_subtype_congr (e : {a // p a} ≃ {b // q b}) :
(∃! a, p a) ↔ ∃! b, q b := by
simp [← unique_subtype_iff_existsUnique, unique_iff_subsingleton_and_nonempty,
nonempty_congr e, subsingleton_congr e]
-- We next build some higher arity versions of `Equiv.forall_congr`.
-- Although they appear to just be repeated applications of `Equiv.forall_congr`,
-- unification of metavariables works better with these versions.
-- In particular, they are necessary in `equiv_rw`.
-- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics,
-- it's rare to have axioms involving more than 3 elements at once.)
protected theorem forall₂_congr {α₁ α₂ β₁ β₂ : Sort*} {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀ {x y}, p x y ↔ q (eα x) (eβ y)) :
(∀ x y, p x y) ↔ ∀ x y, q x y :=
eα.forall_congr fun _ ↦ eβ.forall_congr <| @h _
protected theorem forall₂_congr' {α₁ α₂ β₁ β₂ : Sort*} {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀ {x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) :
(∀ x y, p x y) ↔ ∀ x y, q x y := (Equiv.forall₂_congr eα.symm eβ.symm h.symm).symm
protected theorem forall₃_congr
{α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*} {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀ {x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) :
(∀ x y z, p x y z) ↔ ∀ x y z, q x y z :=
Equiv.forall₂_congr _ _ <| Equiv.forall_congr _ <| @h _ _
protected theorem forall₃_congr'
{α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*} {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂)
(h : ∀ {x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) :
(∀ x y z, p x y z) ↔ ∀ x y z, q x y z :=
(Equiv.forall₃_congr eα.symm eβ.symm eγ.symm h.symm).symm
/-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/
@[simps apply]
noncomputable def ofBijective (f : α → β) (hf : Bijective f) : α ≃ β where
toFun := f
invFun := surjInv hf.surjective
left_inv := leftInverse_surjInv hf
right_inv := rightInverse_surjInv _
lemma ofBijective_apply_symm_apply (f : α → β) (hf : Bijective f) (x : β) :
f ((ofBijective f hf).symm x) = x :=
(ofBijective f hf).apply_symm_apply x
@[simp]
lemma ofBijective_symm_apply_apply (f : α → β) (hf : Bijective f) (x : α) :
(ofBijective f hf).symm (f x) = x :=
(ofBijective f hf).symm_apply_apply x
end Equiv
namespace Quot
/-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces,
if `ra a₁ a₂ ↔ rb (e a₁) (e a₂)`. -/
protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β)
(eq : ∀ a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) : Quot ra ≃ Quot rb where
toFun := Quot.map e fun a₁ a₂ => (eq a₁ a₂).1
invFun := Quot.map e.symm fun b₁ b₂ h =>
(eq (e.symm b₁) (e.symm b₂)).2
((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)
left_inv := by rintro ⟨a⟩; simp only [Quot.map, Equiv.symm_apply_apply]
right_inv := by rintro ⟨a⟩; simp only [Quot.map, Equiv.apply_symm_apply]
@[simp] theorem congr_mk {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β)
(eq : ∀ a₁ a₂ : α, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) (a : α) :
Quot.congr e eq (Quot.mk ra a) = Quot.mk rb (e a) := rfl
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congrRight {r r' : α → α → Prop} (eq : ∀ a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) :
Quot r ≃ Quot r' := Quot.congr (Equiv.refl α) eq
/-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α`
by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/
protected def congrLeft {r : α → α → Prop} (e : α ≃ β) :
Quot r ≃ Quot fun b b' => r (e.symm b) (e.symm b') :=
Quot.congr e fun _ _ => by simp only [e.symm_apply_apply]
end Quot
namespace Quotient
/-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces,
if `ra a₁ a₂ ↔ rb (e a₁) (e a₂)`. -/
protected def congr {ra : Setoid α} {rb : Setoid β} (e : α ≃ β)
(eq : ∀ a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) :
Quotient ra ≃ Quotient rb := Quot.congr e eq
@[simp] theorem congr_mk {ra : Setoid α} {rb : Setoid β} (e : α ≃ β)
(eq : ∀ a₁ a₂ : α, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) (a : α) :
Quotient.congr e eq (Quotient.mk ra a) = Quotient.mk rb (e a) := rfl
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congrRight {r r' : Setoid α}
(eq : ∀ a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) : Quotient r ≃ Quotient r' :=
Quot.congrRight eq
end Quotient
/-- Equivalence between `Fin 0` and `Empty`. -/
def finZeroEquiv : Fin 0 ≃ Empty := .equivEmpty _
/-- Equivalence between `Fin 0` and `PEmpty`. -/
def finZeroEquiv' : Fin 0 ≃ PEmpty.{u} := .equivPEmpty _
/-- Equivalence between `Fin 1` and `Unit`. -/
def finOneEquiv : Fin 1 ≃ Unit := .equivPUnit _
/-- Equivalence between `Fin 2` and `Bool`. -/
def finTwoEquiv : Fin 2 ≃ Bool where
toFun i := i == 1
invFun b := bif b then 1 else 0
left_inv i :=
match i with
| 0 => by simp
| 1 => by simp
right_inv b := by cases b <;> simp
namespace Equiv
variable {α β : Type*}
/-- The left summand of `α ⊕ β` is equivalent to `α`. -/
@[simps]
def sumIsLeft : {x : α ⊕ β // x.isLeft} ≃ α where
toFun x := x.1.getLeft x.2
invFun a := ⟨.inl a, Sum.isLeft_inl⟩
left_inv | ⟨.inl _a, _⟩ => rfl
/-- The right summand of `α ⊕ β` is equivalent to `β`. -/
@[simps]
def sumIsRight : {x : α ⊕ β // x.isRight} ≃ β where
toFun x := x.1.getRight x.2
invFun b := ⟨.inr b, Sum.isRight_inr⟩
left_inv | ⟨.inr _b, _⟩ => rfl
end Equiv
|
Embeddings.lean
|
/-
Copyright (c) 2022 Xavier Roblot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alex J. Best, Xavier Roblot
-/
import Mathlib.Algebra.Algebra.Hom.Rat
import Mathlib.Analysis.Complex.Polynomial.Basic
import Mathlib.NumberTheory.NumberField.Basic
/-!
# Embeddings of number fields
This file defines the embeddings of a number field and, in particular, the embeddings into
the field of complex numbers.
## Main Definitions and Results
* `NumberField.Embeddings.range_eval_eq_rootSet_minpoly`: let `x ∈ K` with `K` a number field and
let `A` be an algebraically closed field of char. 0. Then the images of `x` under the
embeddings of `K` in `A` are exactly the roots in `A` of the minimal polynomial of `x` over `ℚ`.
* `NumberField.Embeddings.pow_eq_one_of_norm_eq_one`: an algebraic integer whose conjugates are
all of norm one is a root of unity.
## Tags
number field, embeddings
-/
open scoped Finset
namespace NumberField.Embeddings
section Fintype
open Module
variable (K : Type*) [Field K] [NumberField K]
variable (A : Type*) [Field A] [CharZero A]
/-- There are finitely many embeddings of a number field. -/
noncomputable instance : Fintype (K →+* A) :=
Fintype.ofEquiv (K →ₐ[ℚ] A) RingHom.equivRatAlgHom.symm
variable [IsAlgClosed A]
/-- The number of embeddings of a number field is equal to its finrank. -/
theorem card : Fintype.card (K →+* A) = finrank ℚ K := by
rw [Fintype.ofEquiv_card RingHom.equivRatAlgHom.symm, AlgHom.card]
instance : Nonempty (K →+* A) := by
rw [← Fintype.card_pos_iff, NumberField.Embeddings.card K A]
exact Module.finrank_pos
end Fintype
section Roots
open Set Polynomial
variable (K A : Type*) [Field K] [NumberField K] [Field A] [Algebra ℚ A] [IsAlgClosed A] (x : K)
/-- Let `A` be an algebraically closed field and let `x ∈ K`, with `K` a number field.
The images of `x` by the embeddings of `K` in `A` are exactly the roots in `A` of
the minimal polynomial of `x` over `ℚ`. -/
theorem range_eval_eq_rootSet_minpoly :
(range fun φ : K →+* A => φ x) = (minpoly ℚ x).rootSet A := by
convert (NumberField.isAlgebraic K).range_eval_eq_rootSet_minpoly A x using 1
ext a
exact ⟨fun ⟨φ, hφ⟩ => ⟨φ.toRatAlgHom, hφ⟩, fun ⟨φ, hφ⟩ => ⟨φ.toRingHom, hφ⟩⟩
end Roots
section Bounded
open Module Polynomial Set
variable {K : Type*} [Field K] [NumberField K]
variable {A : Type*} [NormedField A] [IsAlgClosed A] [NormedAlgebra ℚ A]
theorem coeff_bdd_of_norm_le {B : ℝ} {x : K} (h : ∀ φ : K →+* A, ‖φ x‖ ≤ B) (i : ℕ) :
‖(minpoly ℚ x).coeff i‖ ≤ max B 1 ^ finrank ℚ K * (finrank ℚ K).choose (finrank ℚ K / 2) := by
have hx := Algebra.IsSeparable.isIntegral ℚ x
rw [← norm_algebraMap' A, ← coeff_map (algebraMap ℚ A)]
refine coeff_bdd_of_roots_le _ (minpoly.monic hx)
(IsAlgClosed.splits_codomain _) (minpoly.natDegree_le x) (fun z hz => ?_) i
classical
rw [← Multiset.mem_toFinset] at hz
obtain ⟨φ, rfl⟩ := (range_eval_eq_rootSet_minpoly K A x).symm.subset hz
exact h φ
variable (K A)
/-- Let `B` be a real number. The set of algebraic integers in `K` whose conjugates are all
smaller in norm than `B` is finite. -/
theorem finite_of_norm_le (B : ℝ) : {x : K | IsIntegral ℤ x ∧ ∀ φ : K →+* A, ‖φ x‖ ≤ B}.Finite := by
classical
let C := Nat.ceil (max B 1 ^ finrank ℚ K * (finrank ℚ K).choose (finrank ℚ K / 2))
have := bUnion_roots_finite (algebraMap ℤ K) (finrank ℚ K) (finite_Icc (-C : ℤ) C)
refine this.subset fun x hx => ?_; simp_rw [mem_iUnion]
have h_map_ℚ_minpoly := minpoly.isIntegrallyClosed_eq_field_fractions' ℚ hx.1
refine ⟨_, ⟨?_, fun i => ?_⟩, mem_rootSet.2 ⟨minpoly.ne_zero hx.1, minpoly.aeval ℤ x⟩⟩
· rw [← (minpoly.monic hx.1).natDegree_map (algebraMap ℤ ℚ), ← h_map_ℚ_minpoly]
exact minpoly.natDegree_le x
rw [mem_Icc, ← abs_le, ← @Int.cast_le ℝ]
refine (Eq.trans_le ?_ <| coeff_bdd_of_norm_le hx.2 i).trans (Nat.le_ceil _)
rw [h_map_ℚ_minpoly, coeff_map, eq_intCast, Int.norm_cast_rat, Int.norm_eq_abs, Int.cast_abs]
/-- An algebraic integer whose conjugates are all of norm one is a root of unity. -/
theorem pow_eq_one_of_norm_eq_one {x : K} (hxi : IsIntegral ℤ x) (hx : ∀ φ : K →+* A, ‖φ x‖ = 1) :
∃ (n : ℕ) (_ : 0 < n), x ^ n = 1 := by
obtain ⟨a, -, b, -, habne, h⟩ :=
@Set.Infinite.exists_ne_map_eq_of_mapsTo _ _ _ _ (x ^ · : ℕ → K) Set.infinite_univ
(by exact fun a _ => ⟨hxi.pow a, fun φ => by simp [hx φ]⟩) (finite_of_norm_le K A (1 : ℝ))
wlog hlt : b < a
· exact this K A hxi hx b a habne.symm h.symm (habne.lt_or_gt.resolve_right hlt)
refine ⟨a - b, tsub_pos_of_lt hlt, ?_⟩
rw [← Nat.sub_add_cancel hlt.le, pow_add, mul_left_eq_self₀] at h
refine h.resolve_right fun hp => ?_
specialize hx (IsAlgClosed.lift (R := ℚ)).toRingHom
rw [pow_eq_zero hp, map_zero, norm_zero] at hx; norm_num at hx
end Bounded
end NumberField.Embeddings
section Place
variable {K : Type*} [Field K] {A : Type*} [NormedDivisionRing A] [Nontrivial A] (φ : K →+* A)
/-- An embedding into a normed division ring defines a place of `K` -/
def NumberField.place : AbsoluteValue K ℝ :=
(IsAbsoluteValue.toAbsoluteValue (norm : A → ℝ)).comp φ.injective
@[simp]
theorem NumberField.place_apply (x : K) : (NumberField.place φ) x = norm (φ x) := rfl
end Place
namespace NumberField.ComplexEmbedding
open Complex NumberField
open scoped ComplexConjugate
variable (K : Type*) [Field K] {k : Type*} [Field k]
/--
A (random) lift of the complex embedding `φ : k →+* ℂ` to an extension `K` of `k`.
-/
noncomputable def lift [Algebra k K] [Algebra.IsAlgebraic k K] (φ : k →+* ℂ) : K →+* ℂ := by
letI := φ.toAlgebra
exact (IsAlgClosed.lift (R := k)).toRingHom
@[simp]
theorem lift_comp_algebraMap [Algebra k K] [Algebra.IsAlgebraic k K] (φ : k →+* ℂ) :
(lift K φ).comp (algebraMap k K) = φ := by
unfold lift
letI := φ.toAlgebra
rw [AlgHom.toRingHom_eq_coe, AlgHom.comp_algebraMap_of_tower, RingHom.algebraMap_toAlgebra']
@[simp]
theorem lift_algebraMap_apply [Algebra k K] [Algebra.IsAlgebraic k K] (φ : k →+* ℂ) (x : k) :
lift K φ (algebraMap k K x) = φ x :=
RingHom.congr_fun (lift_comp_algebraMap K φ) x
variable {K}
/-- The conjugate of a complex embedding as a complex embedding. -/
abbrev conjugate (φ : K →+* ℂ) : K →+* ℂ := star φ
@[simp]
theorem conjugate_coe_eq (φ : K →+* ℂ) (x : K) : (conjugate φ) x = conj (φ x) := rfl
theorem place_conjugate (φ : K →+* ℂ) : place (conjugate φ) = place φ := by
ext; simp only [place_apply, norm_conj, conjugate_coe_eq]
/-- An embedding into `ℂ` is real if it is fixed by complex conjugation. -/
abbrev IsReal (φ : K →+* ℂ) : Prop := IsSelfAdjoint φ
theorem isReal_iff {φ : K →+* ℂ} : IsReal φ ↔ conjugate φ = φ := isSelfAdjoint_iff
theorem isReal_conjugate_iff {φ : K →+* ℂ} : IsReal (conjugate φ) ↔ IsReal φ :=
IsSelfAdjoint.star_iff
/-- A real embedding as a ring homomorphism from `K` to `ℝ` . -/
def IsReal.embedding {φ : K →+* ℂ} (hφ : IsReal φ) : K →+* ℝ where
toFun x := (φ x).re
map_one' := by simp only [map_one, one_re]
map_mul' := by
simp only [Complex.conj_eq_iff_im.mp (RingHom.congr_fun hφ _), map_mul, mul_re,
mul_zero, tsub_zero, forall_const]
map_zero' := by simp only [map_zero, zero_re]
map_add' := by simp only [map_add, add_re, forall_const]
@[simp]
theorem IsReal.coe_embedding_apply {φ : K →+* ℂ} (hφ : IsReal φ) (x : K) :
(hφ.embedding x : ℂ) = φ x := by
apply Complex.ext
· rfl
· rw [ofReal_im, eq_comm, ← Complex.conj_eq_iff_im]
exact RingHom.congr_fun hφ x
lemma IsReal.comp (f : k →+* K) {φ : K →+* ℂ} (hφ : IsReal φ) :
IsReal (φ.comp f) := by ext1 x; simpa using RingHom.congr_fun hφ (f x)
lemma isReal_comp_iff {f : k ≃+* K} {φ : K →+* ℂ} :
IsReal (φ.comp (f : k →+* K)) ↔ IsReal φ :=
⟨fun H ↦ by convert H.comp f.symm.toRingHom; ext1; simp, IsReal.comp _⟩
lemma exists_comp_symm_eq_of_comp_eq [Algebra k K] [IsGalois k K] (φ ψ : K →+* ℂ)
(h : φ.comp (algebraMap k K) = ψ.comp (algebraMap k K)) :
∃ σ : K ≃ₐ[k] K, φ.comp σ.symm = ψ := by
letI := (φ.comp (algebraMap k K)).toAlgebra
letI := φ.toAlgebra
have : IsScalarTower k K ℂ := IsScalarTower.of_algebraMap_eq' rfl
let ψ' : K →ₐ[k] ℂ := { ψ with commutes' := fun r ↦ (RingHom.congr_fun h r).symm }
use (AlgHom.restrictNormal' ψ' K).symm
ext1 x
exact AlgHom.restrictNormal_commutes ψ' K x
variable [Algebra k K] (φ : K →+* ℂ) (σ : K ≃ₐ[k] K)
/--
`IsConj φ σ` states that `σ : K ≃ₐ[k] K` is the conjugation under the embedding `φ : K →+* ℂ`.
-/
def IsConj : Prop := conjugate φ = φ.comp σ
variable {φ σ}
lemma IsConj.eq (h : IsConj φ σ) (x) : φ (σ x) = star (φ x) := RingHom.congr_fun h.symm x
lemma IsConj.ext {σ₁ σ₂ : K ≃ₐ[k] K} (h₁ : IsConj φ σ₁) (h₂ : IsConj φ σ₂) : σ₁ = σ₂ :=
AlgEquiv.ext fun x ↦ φ.injective ((h₁.eq x).trans (h₂.eq x).symm)
lemma IsConj.ext_iff {σ₁ σ₂ : K ≃ₐ[k] K} (h₁ : IsConj φ σ₁) : σ₁ = σ₂ ↔ IsConj φ σ₂ :=
⟨fun e ↦ e ▸ h₁, h₁.ext⟩
lemma IsConj.isReal_comp (h : IsConj φ σ) : IsReal (φ.comp (algebraMap k K)) := by
ext1 x
simp only [conjugate_coe_eq, RingHom.coe_comp, Function.comp_apply, ← h.eq,
starRingEnd_apply, AlgEquiv.commutes]
lemma isConj_one_iff : IsConj φ (1 : K ≃ₐ[k] K) ↔ IsReal φ := Iff.rfl
alias ⟨_, IsReal.isConjGal_one⟩ := ComplexEmbedding.isConj_one_iff
lemma isConj_ne_one_iff (hσ : IsConj φ σ) :
σ ≠ 1 ↔ ¬ IsReal φ :=
not_iff_not.mpr ⟨fun h ↦ isConj_one_iff.mp (h ▸ hσ),
fun h ↦ (IsConj.ext_iff hσ).mpr h.isConjGal_one⟩
lemma IsConj.symm (hσ : IsConj φ σ) :
IsConj φ σ.symm := RingHom.ext fun x ↦ by simpa using congr_arg star (hσ.eq (σ.symm x))
lemma isConj_symm : IsConj φ σ.symm ↔ IsConj φ σ :=
⟨IsConj.symm, IsConj.symm⟩
lemma isConj_apply_apply (hσ : IsConj φ σ) (x : K) :
σ (σ x) = x := by
simp [← φ.injective.eq_iff, hσ.eq]
theorem IsConj.comp (hσ : IsConj φ σ) (ν : K ≃ₐ[k] K) :
IsConj (φ.comp ν) (ν⁻¹ * σ * ν) := by
ext
simpa [← AlgEquiv.mul_apply, ← mul_assoc] using RingHom.congr_fun hσ _
lemma orderOf_isConj_two_of_ne_one (hσ : IsConj φ σ) (hσ' : σ ≠ 1) :
orderOf σ = 2 :=
orderOf_eq_prime_iff.mpr ⟨by ext; simpa using isConj_apply_apply hσ _, hσ'⟩
end NumberField.ComplexEmbedding
|
Finite.lean
|
/-
Copyright (c) 2023 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.Pointwise.Set.Scalar
import Mathlib.Data.Finite.Prod
import Mathlib.Algebra.Group.Pointwise.Set.Basic
/-! # Finiteness lemmas for pointwise operations on sets -/
assert_not_exists MulAction MonoidWithZero
open Pointwise
variable {F α β γ : Type*}
namespace Set
section One
variable [One α]
@[to_additive (attr := simp)]
theorem finite_one : (1 : Set α).Finite :=
finite_singleton _
end One
section Mul
variable [Mul α] {s t : Set α}
@[to_additive]
theorem Finite.mul : s.Finite → t.Finite → (s * t).Finite :=
Finite.image2 _
/-- Multiplication preserves finiteness. -/
@[to_additive /-- Addition preserves finiteness. -/]
instance fintypeMul [DecidableEq α] (s t : Set α) [Fintype s] [Fintype t] : Fintype (s * t) :=
Set.fintypeImage2 _ _ _
end Mul
section Monoid
variable [Monoid α] {s t : Set α}
@[to_additive]
instance decidableMemMul [Fintype α] [DecidableEq α] [DecidablePred (· ∈ s)]
[DecidablePred (· ∈ t)] : DecidablePred (· ∈ s * t) := fun _ ↦ decidable_of_iff _ mem_mul.symm
@[to_additive]
instance decidableMemPow [Fintype α] [DecidableEq α] [DecidablePred (· ∈ s)] (n : ℕ) :
DecidablePred (· ∈ s ^ n) := by
induction' n with n ih
· simp only [pow_zero, mem_one]
infer_instance
· letI := ih
rw [pow_succ]
infer_instance
end Monoid
section SMul
variable [SMul α β] {s : Set α} {t : Set β}
@[to_additive]
theorem Finite.smul : s.Finite → t.Finite → (s • t).Finite :=
Finite.image2 _
end SMul
section HasSMulSet
variable [SMul α β] {s : Set β} {a : α}
@[to_additive]
theorem Finite.smul_set : s.Finite → (a • s).Finite :=
Finite.image _
@[to_additive]
theorem Infinite.of_smul_set : (a • s).Infinite → s.Infinite :=
Infinite.of_image _
end HasSMulSet
section Vsub
variable [VSub α β] {s t : Set β}
theorem Finite.vsub (hs : s.Finite) (ht : t.Finite) : Set.Finite (s -ᵥ t) :=
hs.image2 _ ht
end Vsub
section Cancel
variable [Mul α] [IsLeftCancelMul α] [IsRightCancelMul α] {s t : Set α}
@[to_additive]
lemma finite_mul : (s * t).Finite ↔ s.Finite ∧ t.Finite ∨ s = ∅ ∨ t = ∅ :=
finite_image2 (fun _ _ ↦ (mul_left_injective _).injOn) fun _ _ ↦ (mul_right_injective _).injOn
@[to_additive]
lemma infinite_mul : (s * t).Infinite ↔ s.Infinite ∧ t.Nonempty ∨ t.Infinite ∧ s.Nonempty :=
infinite_image2 (fun _ _ => (mul_left_injective _).injOn) fun _ _ => (mul_right_injective _).injOn
end Cancel
section InvolutiveInv
variable [InvolutiveInv α] {s : Set α}
@[to_additive (attr := simp)] lemma finite_inv : s⁻¹.Finite ↔ s.Finite := by
rw [← image_inv_eq_inv, finite_image_iff inv_injective.injOn]
@[to_additive (attr := simp)] lemma infinite_inv : s⁻¹.Infinite ↔ s.Infinite := finite_inv.not
@[to_additive] alias ⟨Finite.of_inv, Finite.inv⟩ := finite_inv
end InvolutiveInv
section Div
variable [Div α] {s t : Set α}
@[to_additive] lemma Finite.div : s.Finite → t.Finite → (s / t).Finite := .image2 _
/-- Division preserves finiteness. -/
@[to_additive /-- Subtraction preserves finiteness. -/]
instance fintypeDiv [DecidableEq α] (s t : Set α) [Fintype s] [Fintype t] : Fintype (s / t) :=
Set.fintypeImage2 _ _ _
end Div
section Group
variable [Group α] {s t : Set α}
@[to_additive]
lemma finite_div : (s / t).Finite ↔ s.Finite ∧ t.Finite ∨ s = ∅ ∨ t = ∅ :=
finite_image2 (fun _ _ ↦ div_left_injective.injOn) fun _ _ ↦ div_right_injective.injOn
@[to_additive]
lemma infinite_div : (s / t).Infinite ↔ s.Infinite ∧ t.Nonempty ∨ t.Infinite ∧ s.Nonempty :=
infinite_image2 (fun _ _ ↦ div_left_injective.injOn) fun _ _ ↦ div_right_injective.injOn
end Group
end Set
open Set
namespace Group
variable {G : Type*} [Group G] [Fintype G] (S : Set G)
@[to_additive]
theorem card_pow_eq_card_pow_card_univ [∀ k : ℕ, DecidablePred (· ∈ S ^ k)] :
∀ k, Fintype.card G ≤ k → Fintype.card (↥(S ^ k)) = Fintype.card (↥(S ^ Fintype.card G)) := by
have hG : 0 < Fintype.card G := Fintype.card_pos
rcases S.eq_empty_or_nonempty with (rfl | ⟨a, ha⟩)
· refine fun k hk ↦ Fintype.card_congr ?_
rw [empty_pow (hG.trans_le hk).ne', empty_pow (ne_of_gt hG)]
have key : ∀ (a) (s t : Set G) [Fintype s] [Fintype t],
(∀ b : G, b ∈ s → b * a ∈ t) → Fintype.card s ≤ Fintype.card t := by
refine fun a s t _ _ h ↦ Fintype.card_le_of_injective (fun ⟨b, hb⟩ ↦ ⟨b * a, h b hb⟩) ?_
rintro ⟨b, hb⟩ ⟨c, hc⟩ hbc
exact Subtype.ext (mul_right_cancel (Subtype.ext_iff.mp hbc))
have mono : Monotone (fun n ↦ Fintype.card (↥(S ^ n)) : ℕ → ℕ) :=
monotone_nat_of_le_succ fun n ↦ key a _ _ fun b hb ↦ Set.mul_mem_mul hb ha
refine fun _ ↦ Nat.stabilises_of_monotone mono (fun n ↦ set_fintype_card_le_univ (S ^ n))
fun n h ↦ le_antisymm (mono (n + 1).le_succ) (key a⁻¹ (S ^ (n + 2)) (S ^ (n + 1)) ?_)
replace h₂ : S ^ n * {a} = S ^ (n + 1) := by
have : Fintype (S ^ n * Set.singleton a) := by
classical
apply fintypeMul
refine Set.eq_of_subset_of_card_le ?_ (le_trans (ge_of_eq h) ?_)
· exact mul_subset_mul Set.Subset.rfl (Set.singleton_subset_iff.mpr ha)
· convert key a (S ^ n) (S ^ n * {a}) fun b hb ↦ Set.mul_mem_mul hb (Set.mem_singleton a)
rw [pow_succ', ← h₂, ← mul_assoc, ← pow_succ', h₂, mul_singleton, forall_mem_image]
intro x hx
rwa [mul_inv_cancel_right]
end Group
|
Nakayama.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.RingTheory.Finiteness.Defs
import Mathlib.RingTheory.Ideal.Operations
/-!
# Nakayama's lemma
## Main results
* `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form:
if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R
such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0.
-/
namespace Submodule
/-- **Nakayama's Lemma**. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2. -/
@[stacks 00DV]
theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [CommRing R] {M : Type*}
[AddCommGroup M] [Module R M] (I : Ideal R) (N : Submodule R M) (hn : N.FG) (hin : N ≤ I • N) :
∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := by
rw [fg_def] at hn
rcases hn with ⟨s, hfs, hs⟩
have H : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (LinearMap.lsmul R M r) ∧ s ⊆ N := by
refine ⟨1, ?_, ?_, ?_⟩
· rw [sub_self]
exact I.zero_mem
· rw [hs]
intro n hn
rw [mem_comap]
change (1 : R) • n ∈ I • N
rw [one_smul]
exact hin hn
· rw [← span_le, hs]
clear hin hs
induction s, hfs using Set.Finite.induction_on with
| empty =>
rcases H with ⟨r, hr1, hrn, _⟩
refine ⟨r, hr1, fun n hn => ?_⟩
specialize hrn hn
rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn
| @insert i s _ _ ih =>
apply ih
rcases H with ⟨r, hr1, hrn, hs⟩
rw [← Set.singleton_union, span_union, smul_sup] at hrn
rw [Set.insert_subset_iff] at hs
have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s := by
specialize hrn hs.1
rw [mem_comap, mem_sup] at hrn
rcases hrn with ⟨y, hy, z, hz, hyz⟩
dsimp at hyz
rw [mem_smul_span_singleton] at hy
rcases hy with ⟨c, hci, rfl⟩
use r - c
constructor
· rw [sub_right_comm]
exact I.sub_mem hr1 hci
· rw [sub_smul, ← hyz, add_sub_cancel_left]
exact hz
rcases this with ⟨c, hc1, hci⟩
refine ⟨c * r, ?_, ?_, hs.2⟩
· simpa only [mul_sub, mul_one, sub_add_sub_cancel] using I.add_mem (I.mul_mem_left c hr1) hc1
· intro n hn
specialize hrn hn
rw [mem_comap, mem_sup] at hrn
rcases hrn with ⟨y, hy, z, hz, hyz⟩
dsimp at hyz
rw [mem_smul_span_singleton] at hy
rcases hy with ⟨d, _, rfl⟩
simp only [mem_comap, LinearMap.lsmul_apply]
rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul]
exact add_mem (smul_mem _ _ hci) (smul_mem _ _ hz)
theorem exists_mem_and_smul_eq_self_of_fg_of_le_smul {R : Type*} [CommRing R] {M : Type*}
[AddCommGroup M] [Module R M] (I : Ideal R) (N : Submodule R M) (hn : N.FG) (hin : N ≤ I • N) :
∃ r ∈ I, ∀ n ∈ N, r • n = n := by
obtain ⟨r, hr, hr'⟩ := exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul I N hn hin
exact ⟨-(r - 1), I.neg_mem hr, fun n hn => by simpa [sub_smul] using hr' n hn⟩
end Submodule
|
PUnit.lean
|
/-
Copyright (c) 2022 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang
-/
import Mathlib.Topology.Sheaves.SheafCondition.Sites
/-!
# Presheaves on `PUnit`
Presheaves on `PUnit` satisfy sheaf condition iff its value at empty set is a terminal object.
-/
namespace TopCat.Presheaf
universe u v w
open CategoryTheory CategoryTheory.Limits TopCat Opposite
variable {C : Type u} [Category.{v} C]
theorem isSheaf_of_isTerminal_of_indiscrete {X : TopCat.{w}} (hind : X.str = ⊤) (F : Presheaf C X)
(it : IsTerminal <| F.obj <| op ⊥) : F.IsSheaf := fun c U s hs => by
obtain rfl | hne := eq_or_ne U ⊥
· intro _ _
rw [@existsUnique_iff_exists _ ⟨fun _ _ => _⟩]
· refine ⟨it.from _, fun U hU hs => IsTerminal.hom_ext ?_ _ _⟩
rwa [le_bot_iff.1 hU.le]
· apply it.hom_ext
· convert Presieve.isSheafFor_top_sieve (F ⋙ coyoneda.obj (@op C c))
rw [← Sieve.id_mem_iff_eq_top]
have := (U.eq_bot_or_top hind).resolve_left hne
subst this
obtain he | ⟨⟨x⟩⟩ := isEmpty_or_nonempty X
· exact (hne <| SetLike.ext'_iff.2 <| Set.univ_eq_empty_iff.2 he).elim
obtain ⟨U, f, hf, hm⟩ := hs x _root_.trivial
obtain rfl | rfl := U.eq_bot_or_top hind
· cases hm
· convert hf
theorem isSheaf_iff_isTerminal_of_indiscrete {X : TopCat.{w}} (hind : X.str = ⊤)
(F : Presheaf C X) : F.IsSheaf ↔ Nonempty (IsTerminal <| F.obj <| op ⊥) :=
⟨fun h => ⟨Sheaf.isTerminalOfEmpty ⟨F, h⟩⟩, fun ⟨it⟩ =>
isSheaf_of_isTerminal_of_indiscrete hind F it⟩
theorem isSheaf_on_punit_of_isTerminal (F : Presheaf C (TopCat.of PUnit))
(it : IsTerminal <| F.obj <| op ⊥) : F.IsSheaf :=
isSheaf_of_isTerminal_of_indiscrete (@Subsingleton.elim (TopologicalSpace PUnit) _ _ _) F it
theorem isSheaf_on_punit_iff_isTerminal (F : Presheaf C (TopCat.of PUnit)) :
F.IsSheaf ↔ Nonempty (IsTerminal <| F.obj <| op ⊥) :=
⟨fun h => ⟨Sheaf.isTerminalOfEmpty ⟨F, h⟩⟩, fun ⟨it⟩ => isSheaf_on_punit_of_isTerminal F it⟩
end TopCat.Presheaf
|
Filter.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.Filter
import Mathlib.Topology.Order.Basic
/-!
# Topology on filters of a space with order topology
In this file we prove that `𝓝 (f x)` tends to `𝓝 Filter.atTop` provided that `f` tends to
`Filter.atTop`, and similarly for `Filter.atBot`.
-/
open Topology
namespace Filter
variable {α X : Type*} [TopologicalSpace X] [PartialOrder X] [OrderTopology X]
protected theorem tendsto_nhds_atTop [NoMaxOrder X] : Tendsto 𝓝 (atTop : Filter X) (𝓝 atTop) :=
Filter.tendsto_nhds_atTop_iff.2 fun x => (eventually_gt_atTop x).mono fun _ => le_mem_nhds
protected theorem tendsto_nhds_atBot [NoMinOrder X] : Tendsto 𝓝 (atBot : Filter X) (𝓝 atBot) :=
@Filter.tendsto_nhds_atTop Xᵒᵈ _ _ _ _
theorem Tendsto.nhds_atTop [NoMaxOrder X] {f : α → X} {l : Filter α} (h : Tendsto f l atTop) :
Tendsto (𝓝 ∘ f) l (𝓝 atTop) :=
Filter.tendsto_nhds_atTop.comp h
theorem Tendsto.nhds_atBot [NoMinOrder X] {f : α → X} {l : Filter α} (h : Tendsto f l atBot) :
Tendsto (𝓝 ∘ f) l (𝓝 atBot) :=
@Tendsto.nhds_atTop α Xᵒᵈ _ _ _ _ _ _ h
end Filter
|
Basic.lean
|
/-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kim Morrison
-/
import Mathlib.Algebra.Order.Hom.Monoid
import Mathlib.SetTheory.Game.Ordinal
import Mathlib.Tactic.Linter.DeprecatedModule
deprecated_module
"This module is now at `CombinatorialGames.Surreal.Basic` in the CGT repo <https://github.com/vihdzp/combinatorial-games>"
(since := "2025-08-06")
/-!
# Surreal numbers
The basic theory of surreal numbers, built on top of the theory of combinatorial (pre-)games.
A pregame is `Numeric` if all the Left options are strictly smaller than all the Right options, and
all those options are themselves numeric. In terms of combinatorial games, the numeric games have
"frozen"; you can only make your position worse by playing, and Left is some definite "number" of
moves ahead (or behind) Right.
A surreal number is an equivalence class of numeric pregames.
In fact, the surreals form a complete ordered field, containing a copy of the reals (and much else
besides!) but we do not yet have a complete development.
## Order properties
Surreal numbers inherit the relations `≤` and `<` from games (`Surreal.instLE` and
`Surreal.instLT`), and these relations satisfy the axioms of a partial order.
## Algebraic operations
In this file, we show that the surreals form a linear ordered commutative group.
In `Mathlib/SetTheory/Surreal/Multiplication.lean`, we define multiplication and show that the
surreals form a linear ordered commutative ring.
One can also map all the ordinals into the surreals!
## TODO
- Define the field structure on the surreals.
## References
* [Conway, *On numbers and games*][Conway2001]
* [Schleicher, Stoll, *An introduction to Conway's games and numbers*][SchleicherStoll]
-/
universe u
namespace SetTheory
open scoped PGame
namespace PGame
/-- A pre-game is numeric if everything in the L set is less than everything in the R set,
and all the elements of L and R are also numeric. -/
def Numeric : PGame → Prop
| ⟨_, _, L, R⟩ => (∀ i j, L i < R j) ∧ (∀ i, Numeric (L i)) ∧ ∀ j, Numeric (R j)
theorem numeric_def {x : PGame} :
Numeric x ↔
(∀ i j, x.moveLeft i < x.moveRight j) ∧
(∀ i, Numeric (x.moveLeft i)) ∧ ∀ j, Numeric (x.moveRight j) := by
cases x; rfl
namespace Numeric
theorem mk {x : PGame} (h₁ : ∀ i j, x.moveLeft i < x.moveRight j) (h₂ : ∀ i, Numeric (x.moveLeft i))
(h₃ : ∀ j, Numeric (x.moveRight j)) : Numeric x :=
numeric_def.2 ⟨h₁, h₂, h₃⟩
theorem left_lt_right {x : PGame} (o : Numeric x) (i : x.LeftMoves) (j : x.RightMoves) :
x.moveLeft i < x.moveRight j := by cases x; exact o.1 i j
theorem moveLeft {x : PGame} (o : Numeric x) (i : x.LeftMoves) : Numeric (x.moveLeft i) := by
cases x; exact o.2.1 i
theorem moveRight {x : PGame} (o : Numeric x) (j : x.RightMoves) : Numeric (x.moveRight j) := by
cases x; exact o.2.2 j
lemma isOption {x' x} (h : IsOption x' x) (hx : Numeric x) : Numeric x' := by
cases h
· apply hx.moveLeft
· apply hx.moveRight
end Numeric
@[elab_as_elim]
theorem numeric_rec {C : PGame → Prop}
(H : ∀ (l r) (L : l → PGame) (R : r → PGame), (∀ i j, L i < R j) →
(∀ i, Numeric (L i)) → (∀ i, Numeric (R i)) → (∀ i, C (L i)) → (∀ i, C (R i)) →
C ⟨l, r, L, R⟩) :
∀ x, Numeric x → C x
| ⟨_, _, _, _⟩, ⟨h, hl, hr⟩ =>
H _ _ _ _ h hl hr (fun i => numeric_rec H _ (hl i)) fun i => numeric_rec H _ (hr i)
theorem Relabelling.numeric_imp {x y : PGame} (r : x ≡r y) (ox : Numeric x) : Numeric y := by
induction x using PGame.moveRecOn generalizing y with | _ x IHl IHr
apply Numeric.mk (fun i j => ?_) (fun i => ?_) fun j => ?_
· rw [← lt_congr (r.moveLeftSymm i).equiv (r.moveRightSymm j).equiv]
apply ox.left_lt_right
· exact IHl _ (r.moveLeftSymm i) (ox.moveLeft _)
· exact IHr _ (r.moveRightSymm j) (ox.moveRight _)
/-- Relabellings preserve being numeric. -/
theorem Relabelling.numeric_congr {x y : PGame} (r : x ≡r y) : Numeric x ↔ Numeric y :=
⟨r.numeric_imp, r.symm.numeric_imp⟩
theorem lf_asymm {x y : PGame} (ox : Numeric x) (oy : Numeric y) : x ⧏ y → ¬y ⧏ x := by
refine numeric_rec (C := fun x => ∀ z (_oz : Numeric z), x ⧏ z → ¬z ⧏ x)
(fun xl xr xL xR hx _oxl _oxr IHxl IHxr => ?_) x ox y oy
refine numeric_rec fun yl yr yL yR hy oyl oyr _IHyl _IHyr => ?_
rw [mk_lf_mk, mk_lf_mk]; rintro (⟨i, h₁⟩ | ⟨j, h₁⟩) (⟨i, h₂⟩ | ⟨j, h₂⟩)
· exact IHxl _ _ (oyl _) (h₁.moveLeft_lf _) (h₂.moveLeft_lf _)
· exact (le_trans h₂ h₁).not_gf (lf_of_lt (hy _ _))
· exact (le_trans h₁ h₂).not_gf (lf_of_lt (hx _ _))
· exact IHxr _ _ (oyr _) (h₁.lf_moveRight _) (h₂.lf_moveRight _)
theorem le_of_lf {x y : PGame} (h : x ⧏ y) (ox : Numeric x) (oy : Numeric y) : x ≤ y :=
not_lf.1 (lf_asymm ox oy h)
alias LF.le := le_of_lf
theorem lt_of_lf {x y : PGame} (h : x ⧏ y) (ox : Numeric x) (oy : Numeric y) : x < y :=
(lt_or_fuzzy_of_lf h).resolve_right (not_fuzzy_of_le (h.le ox oy))
alias LF.lt := lt_of_lf
theorem lf_iff_lt {x y : PGame} (ox : Numeric x) (oy : Numeric y) : x ⧏ y ↔ x < y :=
⟨fun h => h.lt ox oy, lf_of_lt⟩
/-- Definition of `x ≤ y` on numeric pre-games, in terms of `<` -/
theorem le_iff_forall_lt {x y : PGame} (ox : x.Numeric) (oy : y.Numeric) :
x ≤ y ↔ (∀ i, x.moveLeft i < y) ∧ ∀ j, x < y.moveRight j := by
refine le_iff_forall_lf.trans (and_congr ?_ ?_) <;>
refine forall_congr' fun i => lf_iff_lt ?_ ?_ <;>
apply_rules [Numeric.moveLeft, Numeric.moveRight]
/-- Definition of `x < y` on numeric pre-games, in terms of `≤` -/
theorem lt_iff_exists_le {x y : PGame} (ox : x.Numeric) (oy : y.Numeric) :
x < y ↔ (∃ i, x ≤ y.moveLeft i) ∨ ∃ j, x.moveRight j ≤ y := by
rw [← lf_iff_lt ox oy, lf_iff_exists_le]
theorem lt_of_exists_le {x y : PGame} (ox : x.Numeric) (oy : y.Numeric) :
((∃ i, x ≤ y.moveLeft i) ∨ ∃ j, x.moveRight j ≤ y) → x < y :=
(lt_iff_exists_le ox oy).2
/-- The definition of `x < y` on numeric pre-games, in terms of `<` two moves later. -/
theorem lt_def {x y : PGame} (ox : x.Numeric) (oy : y.Numeric) :
x < y ↔
(∃ i, (∀ i', x.moveLeft i' < y.moveLeft i) ∧ ∀ j, x < (y.moveLeft i).moveRight j) ∨
∃ j, (∀ i, (x.moveRight j).moveLeft i < y) ∧ ∀ j', x.moveRight j < y.moveRight j' := by
rw [← lf_iff_lt ox oy, lf_def]
refine or_congr ?_ ?_ <;> refine exists_congr fun x_1 => ?_ <;> refine and_congr ?_ ?_ <;>
refine forall_congr' fun i => lf_iff_lt ?_ ?_ <;>
apply_rules [Numeric.moveLeft, Numeric.moveRight]
theorem not_fuzzy {x y : PGame} (ox : Numeric x) (oy : Numeric y) : ¬Fuzzy x y :=
fun h => not_lf.2 ((lf_of_fuzzy h).le ox oy) h.2
theorem lt_or_equiv_or_gt {x y : PGame} (ox : Numeric x) (oy : Numeric y) :
x < y ∨ (x ≈ y) ∨ y < x :=
((lf_or_equiv_or_gf x y).imp fun h => h.lt ox oy) <| Or.imp_right fun h => h.lt oy ox
theorem numeric_of_isEmpty (x : PGame) [IsEmpty x.LeftMoves] [IsEmpty x.RightMoves] : Numeric x :=
Numeric.mk isEmptyElim isEmptyElim isEmptyElim
theorem numeric_of_isEmpty_leftMoves (x : PGame) [IsEmpty x.LeftMoves] :
(∀ j, Numeric (x.moveRight j)) → Numeric x :=
Numeric.mk isEmptyElim isEmptyElim
theorem numeric_of_isEmpty_rightMoves (x : PGame) [IsEmpty x.RightMoves]
(H : ∀ i, Numeric (x.moveLeft i)) : Numeric x :=
Numeric.mk (fun _ => isEmptyElim) H isEmptyElim
theorem numeric_zero : Numeric 0 :=
numeric_of_isEmpty 0
theorem numeric_one : Numeric 1 :=
numeric_of_isEmpty_rightMoves 1 fun _ => numeric_zero
theorem Numeric.neg : ∀ {x : PGame} (_ : Numeric x), Numeric (-x)
| ⟨_, _, _, _⟩, o =>
⟨fun j i => neg_lt_neg_iff.2 (o.1 i j), fun j => (o.2.2 j).neg, fun i => (o.2.1 i).neg⟩
/-- Inserting a smaller numeric left option into a numeric game results in a numeric game. -/
theorem insertLeft_numeric {x x' : PGame} (x_num : x.Numeric) (x'_num : x'.Numeric)
(h : x' ≤ x) : (insertLeft x x').Numeric := by
rw [le_iff_forall_lt x'_num x_num] at h
unfold Numeric at x_num ⊢
rcases x with ⟨xl, xr, xL, xR⟩
simp only [insertLeft, Sum.forall, forall_const, Sum.elim_inl, Sum.elim_inr] at x_num ⊢
constructor
· simp only [x_num.1, implies_true, true_and]
simp only [rightMoves_mk, moveRight_mk] at h
exact h.2
· simp only [x_num, implies_true, x'_num, and_self]
/-- Inserting a larger numeric right option into a numeric game results in a numeric game. -/
theorem insertRight_numeric {x x' : PGame} (x_num : x.Numeric) (x'_num : x'.Numeric)
(h : x ≤ x') : (insertRight x x').Numeric := by
rw [← neg_neg (x.insertRight x'), ← neg_insertLeft_neg]
apply Numeric.neg
exact insertLeft_numeric (Numeric.neg x_num) (Numeric.neg x'_num) (neg_le_neg_iff.mpr h)
namespace Numeric
theorem moveLeft_lt {x : PGame} (o : Numeric x) (i) : x.moveLeft i < x :=
(moveLeft_lf i).lt (o.moveLeft i) o
theorem moveLeft_le {x : PGame} (o : Numeric x) (i) : x.moveLeft i ≤ x :=
(o.moveLeft_lt i).le
theorem lt_moveRight {x : PGame} (o : Numeric x) (j) : x < x.moveRight j :=
(lf_moveRight j).lt o (o.moveRight j)
theorem le_moveRight {x : PGame} (o : Numeric x) (j) : x ≤ x.moveRight j :=
(o.lt_moveRight j).le
theorem add : ∀ {x y : PGame} (_ : Numeric x) (_ : Numeric y), Numeric (x + y)
| ⟨xl, xr, xL, xR⟩, ⟨yl, yr, yL, yR⟩, ox, oy =>
⟨by
rintro (ix | iy) (jx | jy)
· exact add_lt_add_right (ox.1 ix jx) _
· exact (add_lf_add_of_lf_of_le (lf_mk _ _ ix) (oy.le_moveRight jy)).lt
((ox.moveLeft ix).add oy) (ox.add (oy.moveRight jy))
· exact (add_lf_add_of_lf_of_le (mk_lf _ _ jx) (oy.moveLeft_le iy)).lt
(ox.add (oy.moveLeft iy)) ((ox.moveRight jx).add oy)
· exact add_lt_add_left (oy.1 iy jy) ⟨xl, xr, xL, xR⟩, by
constructor
· rintro (ix | iy)
· exact (ox.moveLeft ix).add oy
· exact ox.add (oy.moveLeft iy)
· rintro (jx | jy)
· apply (ox.moveRight jx).add oy
· apply ox.add (oy.moveRight jy)⟩
termination_by x y => (x, y) -- Porting note: Added `termination_by`
theorem sub {x y : PGame} (ox : Numeric x) (oy : Numeric y) : Numeric (x - y) :=
ox.add oy.neg
end Numeric
/-- Pre-games defined by natural numbers are numeric. -/
theorem numeric_nat : ∀ n : ℕ, Numeric n
| 0 => numeric_zero
| n + 1 => (numeric_nat n).add numeric_one
/-- Ordinal games are numeric. -/
theorem numeric_toPGame (o : Ordinal) : o.toPGame.Numeric := by
induction o using Ordinal.induction with | _ o IH
apply numeric_of_isEmpty_rightMoves
simpa using fun i => IH _ (Ordinal.toLeftMovesToPGame_symm_lt i)
end PGame
end SetTheory
open SetTheory PGame
/-- The type of surreal numbers. These are the numeric pre-games quotiented
by the equivalence relation `x ≈ y ↔ x ≤ y ∧ y ≤ x`. In the quotient,
the order becomes a total order. -/
def Surreal :=
Quotient (inferInstanceAs <| Setoid (Subtype Numeric))
namespace Surreal
/-- Construct a surreal number from a numeric pre-game. -/
def mk (x : PGame) (h : x.Numeric) : Surreal :=
⟦⟨x, h⟩⟧
instance : Zero Surreal :=
⟨mk 0 numeric_zero⟩
instance : One Surreal :=
⟨mk 1 numeric_one⟩
instance : Inhabited Surreal :=
⟨0⟩
lemma mk_eq_mk {x y : PGame.{u}} {hx hy} : mk x hx = mk y hy ↔ x ≈ y := Quotient.eq
lemma mk_eq_zero {x : PGame.{u}} {hx} : mk x hx = 0 ↔ x ≈ 0 := Quotient.eq
/-- Lift an equivalence-respecting function on pre-games to surreals. -/
def lift {α} (f : ∀ x, Numeric x → α)
(H : ∀ {x y} (hx : Numeric x) (hy : Numeric y), x.Equiv y → f x hx = f y hy) : Surreal → α :=
Quotient.lift (fun x : { x // Numeric x } => f x.1 x.2) fun x y => H x.2 y.2
/-- Lift a binary equivalence-respecting function on pre-games to surreals. -/
def lift₂ {α} (f : ∀ x y, Numeric x → Numeric y → α)
(H :
∀ {x₁ y₁ x₂ y₂} (ox₁ : Numeric x₁) (oy₁ : Numeric y₁) (ox₂ : Numeric x₂) (oy₂ : Numeric y₂),
x₁.Equiv x₂ → y₁.Equiv y₂ → f x₁ y₁ ox₁ oy₁ = f x₂ y₂ ox₂ oy₂) :
Surreal → Surreal → α :=
lift (fun x ox => lift (fun y oy => f x y ox oy) fun _ _ => H _ _ _ _ equiv_rfl)
fun _ _ h => funext <| Quotient.ind fun _ => H _ _ _ _ h equiv_rfl
instance instLE : LE Surreal :=
⟨lift₂ (fun x y _ _ => x ≤ y) fun _ _ _ _ hx hy => propext (le_congr hx hy)⟩
@[simp]
lemma mk_le_mk {x y : PGame.{u}} {hx hy} : mk x hx ≤ mk y hy ↔ x ≤ y := Iff.rfl
lemma zero_le_mk {x : PGame.{u}} {hx} : 0 ≤ mk x hx ↔ 0 ≤ x := Iff.rfl
instance instLT : LT Surreal :=
⟨lift₂ (fun x y _ _ => x < y) fun _ _ _ _ hx hy => propext (lt_congr hx hy)⟩
lemma mk_lt_mk {x y : PGame.{u}} {hx hy} : mk x hx < mk y hy ↔ x < y := Iff.rfl
lemma zero_lt_mk {x : PGame.{u}} {hx} : 0 < mk x hx ↔ 0 < x := Iff.rfl
/-- Same as `moveLeft_lt`, but for `Surreal` instead of `PGame` -/
theorem mk_moveLeft_lt_mk {x : PGame} (o : Numeric x) (i) :
Surreal.mk (x.moveLeft i) (Numeric.moveLeft o i) < Surreal.mk x o := Numeric.moveLeft_lt o i
/-- Same as `lt_moveRight`, but for `Surreal` instead of `PGame` -/
theorem mk_lt_mk_moveRight {x : PGame} (o : Numeric x) (j) :
Surreal.mk x o < Surreal.mk (x.moveRight j) (Numeric.moveRight o j) := Numeric.lt_moveRight o j
/-- Addition on surreals is inherited from pre-game addition:
the sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/
instance : Add Surreal :=
⟨Surreal.lift₂ (fun (x y : PGame) ox oy => ⟦⟨x + y, ox.add oy⟩⟧) fun _ _ _ _ hx hy =>
Quotient.sound (add_congr hx hy)⟩
/-- Negation for surreal numbers is inherited from pre-game negation:
the negation of `{L | R}` is `{-R | -L}`. -/
instance : Neg Surreal :=
⟨Surreal.lift (fun x ox => ⟦⟨-x, ox.neg⟩⟧) fun _ _ a => Quotient.sound (neg_equiv_neg_iff.2 a)⟩
instance addCommGroup : AddCommGroup Surreal where
add := (· + ·)
add_assoc := by rintro ⟨_⟩ ⟨_⟩ ⟨_⟩; exact Quotient.sound add_assoc_equiv
zero := 0
zero_add := by rintro ⟨a⟩; exact Quotient.sound (zero_add_equiv a)
add_zero := by rintro ⟨a⟩; exact Quotient.sound (add_zero_equiv a)
neg := Neg.neg
neg_add_cancel := by rintro ⟨a⟩; exact Quotient.sound (neg_add_cancel_equiv a)
add_comm := by rintro ⟨_⟩ ⟨_⟩; exact Quotient.sound add_comm_equiv
nsmul := nsmulRec
zsmul := zsmulRec
instance partialOrder : PartialOrder Surreal where
le := (· ≤ ·)
lt := (· < ·)
le_refl := by rintro ⟨_⟩; apply @le_rfl PGame
le_trans := by rintro ⟨_⟩ ⟨_⟩ ⟨_⟩; apply @le_trans PGame
lt_iff_le_not_ge := by rintro ⟨_, ox⟩ ⟨_, oy⟩; apply @lt_iff_le_not_ge PGame
le_antisymm := by rintro ⟨_⟩ ⟨_⟩ h₁ h₂; exact Quotient.sound ⟨h₁, h₂⟩
instance isOrderedAddMonoid : IsOrderedAddMonoid Surreal where
add_le_add_left := by rintro ⟨_⟩ ⟨_⟩ hx ⟨_⟩; exact @add_le_add_left PGame _ _ _ _ _ hx _
lemma mk_add {x y : PGame} (hx : x.Numeric) (hy : y.Numeric) :
Surreal.mk (x + y) (hx.add hy) = Surreal.mk x hx + Surreal.mk y hy := by rfl
lemma mk_sub {x y : PGame} (hx : x.Numeric) (hy : y.Numeric) :
Surreal.mk (x - y) (hx.sub hy) = Surreal.mk x hx - Surreal.mk y hy := by rfl
lemma zero_def : 0 = mk 0 numeric_zero := by rfl
noncomputable instance : LinearOrder Surreal :=
{ Surreal.partialOrder with
le_total := by
rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩
exact or_iff_not_imp_left.2 fun h => (PGame.not_le.1 h).le oy ox
toDecidableLE := Classical.decRel _ }
instance : AddMonoidWithOne Surreal :=
AddMonoidWithOne.unary
/-- Casts a `Surreal` number into a `Game`. -/
def toGame : Surreal →+o Game where
toFun := lift (fun x _ => ⟦x⟧) fun _ _ => Quot.sound
map_zero' := rfl
map_add' := by rintro ⟨_, _⟩ ⟨_, _⟩; rfl
monotone' := by rintro ⟨_, _⟩ ⟨_, _⟩; exact id
@[simp]
theorem zero_toGame : toGame 0 = 0 :=
rfl
@[simp]
theorem one_toGame : toGame 1 = 1 :=
rfl
@[simp]
theorem nat_toGame : ∀ n : ℕ, toGame n = n :=
map_natCast' _ one_toGame
/-- A small family of surreals is bounded above. -/
lemma bddAbove_range_of_small {ι : Type*} [Small.{u} ι] (f : ι → Surreal.{u}) :
BddAbove (Set.range f) := by
induction f using Quotient.induction_on_pi with | _ f
let g : ι → PGame.{u} := Subtype.val ∘ f
have hg (i) : (g i).Numeric := Subtype.prop _
conv in (⟦f _⟧) =>
change mk (g i) (hg i)
clear_value g
clear f
let x : PGame.{u} := ⟨Σ i, (g <| (equivShrink.{u} ι).symm i).LeftMoves, PEmpty,
fun x ↦ moveLeft _ x.2, PEmpty.elim⟩
refine ⟨mk x (.mk (by simp [x]) (fun _ ↦ (hg _).moveLeft _) (by simp [x])),
Set.forall_mem_range.2 fun i ↦ ?_⟩
rw [mk_le_mk, ← (equivShrink ι).symm_apply_apply i, le_iff_forall_lf]
simpa [x] using fun j ↦ @moveLeft_lf x ⟨equivShrink ι i, j⟩
/-- A small set of surreals is bounded above. -/
lemma bddAbove_of_small (s : Set Surreal.{u}) [Small.{u} s] : BddAbove s := by
simpa using bddAbove_range_of_small (Subtype.val : s → Surreal.{u})
/-- A small family of surreals is bounded below. -/
lemma bddBelow_range_of_small {ι : Type*} [Small.{u} ι] (f : ι → Surreal.{u}) :
BddBelow (Set.range f) := by
induction f using Quotient.induction_on_pi with | _ f
let g : ι → PGame.{u} := Subtype.val ∘ f
have hg (i) : (g i).Numeric := Subtype.prop _
conv in (⟦f _⟧) =>
change mk (g i) (hg i)
clear_value g
clear f
let x : PGame.{u} := ⟨PEmpty, Σ i, (g <| (equivShrink.{u} ι).symm i).RightMoves,
PEmpty.elim, fun x ↦ moveRight _ x.2⟩
refine ⟨mk x (.mk (by simp [x]) (by simp [x]) (fun _ ↦ (hg _).moveRight _) ),
Set.forall_mem_range.2 fun i ↦ ?_⟩
rw [mk_le_mk, ← (equivShrink ι).symm_apply_apply i, le_iff_forall_lf]
simpa [x] using fun j ↦ @lf_moveRight x ⟨equivShrink ι i, j⟩
/-- A small set of surreals is bounded below. -/
lemma bddBelow_of_small (s : Set Surreal.{u}) [Small.{u} s] : BddBelow s := by
simpa using bddBelow_range_of_small (Subtype.val : s → Surreal.{u})
end Surreal
open Surreal
namespace Ordinal
/-- Converts an ordinal into the corresponding surreal. -/
noncomputable def toSurreal : Ordinal ↪o Surreal where
toFun o := mk _ (numeric_toPGame o)
inj' a b h := toPGame_equiv_iff.1 (by apply Quotient.exact h) -- Porting note: Added `by apply`
map_rel_iff' := @toPGame_le_iff
end Ordinal
|
Matrix.lean
|
/-
Copyright (c) 2021 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth, Eric Wieser
-/
import Mathlib.Analysis.InnerProductSpace.PiL2
/-!
# Matrices as a normed space
In this file we provide the following non-instances for norms on matrices:
* The elementwise norm (with `open scoped Matrix.Norms.Elementwise`):
* `Matrix.seminormedAddCommGroup`
* `Matrix.normedAddCommGroup`
* `Matrix.normedSpace`
* `Matrix.isBoundedSMul`
* `Matrix.normSMulClass`
* The Frobenius norm (with `open scoped Matrix.Norms.Frobenius`):
* `Matrix.frobeniusSeminormedAddCommGroup`
* `Matrix.frobeniusNormedAddCommGroup`
* `Matrix.frobeniusNormedSpace`
* `Matrix.frobeniusNormedRing`
* `Matrix.frobeniusNormedAlgebra`
* `Matrix.frobeniusIsBoundedSMul`
* `Matrix.frobeniusNormSMulClass`
* The $L^\infty$ operator norm (with `open scoped Matrix.Norms.Operator`):
* `Matrix.linftyOpSeminormedAddCommGroup`
* `Matrix.linftyOpNormedAddCommGroup`
* `Matrix.linftyOpNormedSpace`
* `Matrix.linftyOpIsBoundedSMul`
* `Matrix.linftyOpNormSMulClass`
* `Matrix.linftyOpNonUnitalSemiNormedRing`
* `Matrix.linftyOpSemiNormedRing`
* `Matrix.linftyOpNonUnitalNormedRing`
* `Matrix.linftyOpNormedRing`
* `Matrix.linftyOpNormedAlgebra`
These are not declared as instances because there are several natural choices for defining the norm
of a matrix.
The norm induced by the identification of `Matrix m n 𝕜` with
`EuclideanSpace n 𝕜 →L[𝕜] EuclideanSpace m 𝕜` (i.e., the ℓ² operator norm) can be found in
`Mathlib/Analysis/CStarAlgebra/Matrix.lean` and `open scoped Matrix.Norms.L2Operator`.
It is separated to avoid extraneous imports in this file.
-/
noncomputable section
open WithLp
open scoped NNReal Matrix
namespace Matrix
variable {R l m n α β ι : Type*} [Fintype l] [Fintype m] [Fintype n] [Unique ι]
/-! ### The elementwise supremum norm -/
section LinfLinf
section SeminormedAddCommGroup
variable [SeminormedAddCommGroup α] [SeminormedAddCommGroup β]
/-- Seminormed group instance (using sup norm of sup norm) for matrices over a seminormed group. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
protected def seminormedAddCommGroup : SeminormedAddCommGroup (Matrix m n α) :=
Pi.seminormedAddCommGroup
attribute [local instance] Matrix.seminormedAddCommGroup
theorem norm_def (A : Matrix m n α) : ‖A‖ = ‖fun i j => A i j‖ := rfl
/-- The norm of a matrix is the sup of the sup of the nnnorm of the entries -/
lemma norm_eq_sup_sup_nnnorm (A : Matrix m n α) :
‖A‖ = Finset.sup Finset.univ fun i ↦ Finset.sup Finset.univ fun j ↦ ‖A i j‖₊ := by
simp_rw [Matrix.norm_def, Pi.norm_def, Pi.nnnorm_def]
theorem nnnorm_def (A : Matrix m n α) : ‖A‖₊ = ‖fun i j => A i j‖₊ := rfl
theorem norm_le_iff {r : ℝ} (hr : 0 ≤ r) {A : Matrix m n α} : ‖A‖ ≤ r ↔ ∀ i j, ‖A i j‖ ≤ r := by
simp_rw [norm_def, pi_norm_le_iff_of_nonneg hr]
theorem nnnorm_le_iff {r : ℝ≥0} {A : Matrix m n α} : ‖A‖₊ ≤ r ↔ ∀ i j, ‖A i j‖₊ ≤ r := by
simp_rw [nnnorm_def, pi_nnnorm_le_iff]
theorem norm_lt_iff {r : ℝ} (hr : 0 < r) {A : Matrix m n α} : ‖A‖ < r ↔ ∀ i j, ‖A i j‖ < r := by
simp_rw [norm_def, pi_norm_lt_iff hr]
theorem nnnorm_lt_iff {r : ℝ≥0} (hr : 0 < r) {A : Matrix m n α} :
‖A‖₊ < r ↔ ∀ i j, ‖A i j‖₊ < r := by
simp_rw [nnnorm_def, pi_nnnorm_lt_iff hr]
theorem norm_entry_le_entrywise_sup_norm (A : Matrix m n α) {i : m} {j : n} : ‖A i j‖ ≤ ‖A‖ :=
(norm_le_pi_norm (A i) j).trans (norm_le_pi_norm A i)
theorem nnnorm_entry_le_entrywise_sup_nnnorm (A : Matrix m n α) {i : m} {j : n} : ‖A i j‖₊ ≤ ‖A‖₊ :=
(nnnorm_le_pi_nnnorm (A i) j).trans (nnnorm_le_pi_nnnorm A i)
@[simp]
theorem nnnorm_map_eq (A : Matrix m n α) (f : α → β) (hf : ∀ a, ‖f a‖₊ = ‖a‖₊) :
‖A.map f‖₊ = ‖A‖₊ := by
simp only [nnnorm_def, Pi.nnnorm_def, Matrix.map_apply, hf]
@[simp]
theorem norm_map_eq (A : Matrix m n α) (f : α → β) (hf : ∀ a, ‖f a‖ = ‖a‖) : ‖A.map f‖ = ‖A‖ :=
(congr_arg ((↑) : ℝ≥0 → ℝ) <| nnnorm_map_eq A f fun a => Subtype.ext <| hf a :)
@[simp]
theorem nnnorm_transpose (A : Matrix m n α) : ‖Aᵀ‖₊ = ‖A‖₊ :=
Finset.sup_comm _ _ _
@[simp]
theorem norm_transpose (A : Matrix m n α) : ‖Aᵀ‖ = ‖A‖ :=
congr_arg ((↑) : ℝ≥0 → ℝ) <| nnnorm_transpose A
@[simp]
theorem nnnorm_conjTranspose [StarAddMonoid α] [NormedStarGroup α] (A : Matrix m n α) :
‖Aᴴ‖₊ = ‖A‖₊ :=
(nnnorm_map_eq _ _ nnnorm_star).trans A.nnnorm_transpose
@[simp]
theorem norm_conjTranspose [StarAddMonoid α] [NormedStarGroup α] (A : Matrix m n α) : ‖Aᴴ‖ = ‖A‖ :=
congr_arg ((↑) : ℝ≥0 → ℝ) <| nnnorm_conjTranspose A
instance [StarAddMonoid α] [NormedStarGroup α] : NormedStarGroup (Matrix m m α) :=
⟨(le_of_eq <| norm_conjTranspose ·)⟩
@[simp]
theorem nnnorm_replicateCol (v : m → α) : ‖replicateCol ι v‖₊ = ‖v‖₊ := by
simp [nnnorm_def, Pi.nnnorm_def]
@[deprecated (since := "2025-03-20")] alias nnnorm_col := nnnorm_replicateCol
@[simp]
theorem norm_replicateCol (v : m → α) : ‖replicateCol ι v‖ = ‖v‖ :=
congr_arg ((↑) : ℝ≥0 → ℝ) <| nnnorm_replicateCol v
@[deprecated (since := "2025-03-20")] alias norm_col := norm_replicateCol
@[simp]
theorem nnnorm_replicateRow (v : n → α) : ‖replicateRow ι v‖₊ = ‖v‖₊ := by
simp [nnnorm_def, Pi.nnnorm_def]
@[deprecated (since := "2025-03-20")] alias nnnorm_row := nnnorm_replicateRow
@[simp]
theorem norm_replicateRow (v : n → α) : ‖replicateRow ι v‖ = ‖v‖ :=
congr_arg ((↑) : ℝ≥0 → ℝ) <| nnnorm_replicateRow v
@[deprecated (since := "2025-03-20")] alias norm_row := norm_replicateRow
@[simp]
theorem nnnorm_diagonal [DecidableEq n] (v : n → α) : ‖diagonal v‖₊ = ‖v‖₊ := by
simp_rw [nnnorm_def, Pi.nnnorm_def]
congr 1 with i : 1
refine le_antisymm (Finset.sup_le fun j hj => ?_) ?_
· obtain rfl | hij := eq_or_ne i j
· rw [diagonal_apply_eq]
· rw [diagonal_apply_ne _ hij, nnnorm_zero]
exact zero_le _
· refine Eq.trans_le ?_ (Finset.le_sup (Finset.mem_univ i))
rw [diagonal_apply_eq]
@[simp]
theorem norm_diagonal [DecidableEq n] (v : n → α) : ‖diagonal v‖ = ‖v‖ :=
congr_arg ((↑) : ℝ≥0 → ℝ) <| nnnorm_diagonal v
/-- Note this is safe as an instance as it carries no data. -/
-- Porting note: not yet implemented: `@[nolint fails_quickly]`
instance [Nonempty n] [DecidableEq n] [One α] [NormOneClass α] : NormOneClass (Matrix n n α) :=
⟨(norm_diagonal _).trans <| norm_one⟩
end SeminormedAddCommGroup
/-- Normed group instance (using sup norm of sup norm) for matrices over a normed group. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
protected def normedAddCommGroup [NormedAddCommGroup α] : NormedAddCommGroup (Matrix m n α) :=
Pi.normedAddCommGroup
section NormedSpace
attribute [local instance] Matrix.seminormedAddCommGroup
/-- This applies to the sup norm of sup norm. -/
protected theorem isBoundedSMul [SeminormedRing R] [SeminormedAddCommGroup α] [Module R α]
[IsBoundedSMul R α] : IsBoundedSMul R (Matrix m n α) :=
Pi.instIsBoundedSMul
@[deprecated (since := "2025-03-10")] protected alias boundedSMul := Matrix.isBoundedSMul
/-- This applies to the sup norm of sup norm. -/
protected theorem normSMulClass [SeminormedRing R] [SeminormedAddCommGroup α] [Module R α]
[NormSMulClass R α] : NormSMulClass R (Matrix m n α) :=
Pi.instNormSMulClass
variable [NormedField R] [SeminormedAddCommGroup α] [NormedSpace R α]
/-- Normed space instance (using sup norm of sup norm) for matrices over a normed space. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
protected def normedSpace : NormedSpace R (Matrix m n α) :=
Pi.normedSpace
namespace Norms.Elementwise
attribute [scoped instance]
Matrix.seminormedAddCommGroup
Matrix.normedAddCommGroup
Matrix.normedSpace
Matrix.isBoundedSMul
Matrix.normSMulClass
end Norms.Elementwise
end NormedSpace
end LinfLinf
/-! ### The $L_\infty$ operator norm
This section defines the matrix norm $\|A\|_\infty = \operatorname{sup}_i (\sum_j \|A_{ij}\|)$.
Note that this is equivalent to the operator norm, considering $A$ as a linear map between two
$L^\infty$ spaces.
-/
section LinftyOp
/-- Seminormed group instance (using sup norm of L1 norm) for matrices over a seminormed group. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
protected def linftyOpSeminormedAddCommGroup [SeminormedAddCommGroup α] :
SeminormedAddCommGroup (Matrix m n α) :=
(by infer_instance : SeminormedAddCommGroup (m → PiLp 1 fun j : n => α))
/-- Normed group instance (using sup norm of L1 norm) for matrices over a normed ring. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
protected def linftyOpNormedAddCommGroup [NormedAddCommGroup α] :
NormedAddCommGroup (Matrix m n α) :=
(by infer_instance : NormedAddCommGroup (m → PiLp 1 fun j : n => α))
/-- This applies to the sup norm of L1 norm. -/
@[local instance]
protected theorem linftyOpIsBoundedSMul
[SeminormedRing R] [SeminormedAddCommGroup α] [Module R α] [IsBoundedSMul R α] :
IsBoundedSMul R (Matrix m n α) :=
(by infer_instance : IsBoundedSMul R (m → PiLp 1 fun j : n => α))
/-- This applies to the sup norm of L1 norm. -/
@[local instance]
protected theorem linftyOpNormSMulClass
[SeminormedRing R] [SeminormedAddCommGroup α] [Module R α] [NormSMulClass R α] :
NormSMulClass R (Matrix m n α) :=
(by infer_instance : NormSMulClass R (m → PiLp 1 fun j : n => α))
/-- Normed space instance (using sup norm of L1 norm) for matrices over a normed space. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
protected def linftyOpNormedSpace [NormedField R] [SeminormedAddCommGroup α] [NormedSpace R α] :
NormedSpace R (Matrix m n α) :=
(by infer_instance : NormedSpace R (m → PiLp 1 fun j : n => α))
section SeminormedAddCommGroup
variable [SeminormedAddCommGroup α]
theorem linfty_opNorm_def (A : Matrix m n α) :
‖A‖ = ((Finset.univ : Finset m).sup fun i : m => ∑ j : n, ‖A i j‖₊ : ℝ≥0) := by
-- Porting note: added
change ‖fun i => toLp 1 (A i)‖ = _
simp [Pi.norm_def, PiLp.nnnorm_eq_of_L1]
theorem linfty_opNNNorm_def (A : Matrix m n α) :
‖A‖₊ = (Finset.univ : Finset m).sup fun i : m => ∑ j : n, ‖A i j‖₊ :=
Subtype.ext <| linfty_opNorm_def A
@[simp]
theorem linfty_opNNNorm_replicateCol (v : m → α) : ‖replicateCol ι v‖₊ = ‖v‖₊ := by
rw [linfty_opNNNorm_def, Pi.nnnorm_def]
simp
@[deprecated (since := "2025-03-20")] alias linfty_opNNNorm_col := linfty_opNNNorm_replicateCol
@[simp]
theorem linfty_opNorm_replicateCol (v : m → α) : ‖replicateCol ι v‖ = ‖v‖ :=
congr_arg ((↑) : ℝ≥0 → ℝ) <| linfty_opNNNorm_replicateCol v
@[deprecated (since := "2025-03-20")] alias linfty_opNorm_col := linfty_opNorm_replicateCol
@[simp]
theorem linfty_opNNNorm_replicateRow (v : n → α) : ‖replicateRow ι v‖₊ = ∑ i, ‖v i‖₊ := by
simp [linfty_opNNNorm_def]
@[deprecated (since := "2025-03-20")] alias linfty_opNNNorm_row := linfty_opNNNorm_replicateRow
@[simp]
theorem linfty_opNorm_replicateRow (v : n → α) : ‖replicateRow ι v‖ = ∑ i, ‖v i‖ :=
(congr_arg ((↑) : ℝ≥0 → ℝ) <| linfty_opNNNorm_replicateRow v).trans <| by simp [NNReal.coe_sum]
@[deprecated (since := "2025-03-20")] alias linfty_opNorm_row := linfty_opNNNorm_replicateRow
@[simp]
theorem linfty_opNNNorm_diagonal [DecidableEq m] (v : m → α) : ‖diagonal v‖₊ = ‖v‖₊ := by
rw [linfty_opNNNorm_def, Pi.nnnorm_def]
congr 1 with i : 1
refine (Finset.sum_eq_single_of_mem _ (Finset.mem_univ i) fun j _hj hij => ?_).trans ?_
· rw [diagonal_apply_ne' _ hij, nnnorm_zero]
· rw [diagonal_apply_eq]
@[simp]
theorem linfty_opNorm_diagonal [DecidableEq m] (v : m → α) : ‖diagonal v‖ = ‖v‖ :=
congr_arg ((↑) : ℝ≥0 → ℝ) <| linfty_opNNNorm_diagonal v
end SeminormedAddCommGroup
section NonUnitalSeminormedRing
variable [NonUnitalSeminormedRing α]
theorem linfty_opNNNorm_mul (A : Matrix l m α) (B : Matrix m n α) : ‖A * B‖₊ ≤ ‖A‖₊ * ‖B‖₊ := by
simp_rw [linfty_opNNNorm_def, Matrix.mul_apply]
calc
(Finset.univ.sup fun i => ∑ k, ‖∑ j, A i j * B j k‖₊) ≤
Finset.univ.sup fun i => ∑ k, ∑ j, ‖A i j‖₊ * ‖B j k‖₊ :=
Finset.sup_mono_fun fun i _hi =>
Finset.sum_le_sum fun k _hk => nnnorm_sum_le_of_le _ fun j _hj => nnnorm_mul_le _ _
_ = Finset.univ.sup fun i => ∑ j, ‖A i j‖₊ * ∑ k, ‖B j k‖₊ := by
simp_rw [@Finset.sum_comm m, Finset.mul_sum]
_ ≤ Finset.univ.sup fun i => ∑ j, ‖A i j‖₊ * Finset.univ.sup fun i => ∑ j, ‖B i j‖₊ := by
refine Finset.sup_mono_fun fun i _hi => ?_
gcongr with j hj
exact Finset.le_sup (f := fun i ↦ ∑ k : n, ‖B i k‖₊) hj
_ ≤ (Finset.univ.sup fun i => ∑ j, ‖A i j‖₊) * Finset.univ.sup fun i => ∑ j, ‖B i j‖₊ := by
simp_rw [← Finset.sum_mul, ← NNReal.finset_sup_mul]
rfl
theorem linfty_opNorm_mul (A : Matrix l m α) (B : Matrix m n α) : ‖A * B‖ ≤ ‖A‖ * ‖B‖ :=
linfty_opNNNorm_mul _ _
theorem linfty_opNNNorm_mulVec (A : Matrix l m α) (v : m → α) : ‖A *ᵥ v‖₊ ≤ ‖A‖₊ * ‖v‖₊ := by
rw [← linfty_opNNNorm_replicateCol (ι := Fin 1) (A *ᵥ v),
← linfty_opNNNorm_replicateCol v (ι := Fin 1)]
exact linfty_opNNNorm_mul A (replicateCol (Fin 1) v)
theorem linfty_opNorm_mulVec (A : Matrix l m α) (v : m → α) : ‖A *ᵥ v‖ ≤ ‖A‖ * ‖v‖ :=
linfty_opNNNorm_mulVec _ _
end NonUnitalSeminormedRing
/-- Seminormed non-unital ring instance (using sup norm of L1 norm) for matrices over a semi normed
non-unital ring. Not declared as an instance because there are several natural choices for defining
the norm of a matrix. -/
@[local instance]
protected def linftyOpNonUnitalSemiNormedRing [NonUnitalSeminormedRing α] :
NonUnitalSeminormedRing (Matrix n n α) :=
{ Matrix.linftyOpSeminormedAddCommGroup, Matrix.instNonUnitalRing with
norm_mul_le := linfty_opNorm_mul }
/-- The `L₁-L∞` norm preserves one on non-empty matrices. Note this is safe as an instance, as it
carries no data. -/
instance linfty_opNormOneClass [SeminormedRing α] [NormOneClass α] [DecidableEq n] [Nonempty n] :
NormOneClass (Matrix n n α) where norm_one := (linfty_opNorm_diagonal _).trans norm_one
/-- Seminormed ring instance (using sup norm of L1 norm) for matrices over a semi normed ring. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
protected def linftyOpSemiNormedRing [SeminormedRing α] [DecidableEq n] :
SeminormedRing (Matrix n n α) :=
{ Matrix.linftyOpNonUnitalSemiNormedRing, Matrix.instRing with }
/-- Normed non-unital ring instance (using sup norm of L1 norm) for matrices over a normed
non-unital ring. Not declared as an instance because there are several natural choices for defining
the norm of a matrix. -/
@[local instance]
protected def linftyOpNonUnitalNormedRing [NonUnitalNormedRing α] :
NonUnitalNormedRing (Matrix n n α) :=
{ Matrix.linftyOpNonUnitalSemiNormedRing with
eq_of_dist_eq_zero := eq_of_dist_eq_zero }
/-- Normed ring instance (using sup norm of L1 norm) for matrices over a normed ring. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
protected def linftyOpNormedRing [NormedRing α] [DecidableEq n] : NormedRing (Matrix n n α) :=
{ Matrix.linftyOpSemiNormedRing with
eq_of_dist_eq_zero := eq_of_dist_eq_zero }
/-- Normed algebra instance (using sup norm of L1 norm) for matrices over a normed algebra. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
protected def linftyOpNormedAlgebra [NormedField R] [SeminormedRing α] [NormedAlgebra R α]
[DecidableEq n] : NormedAlgebra R (Matrix n n α) :=
{ Matrix.linftyOpNormedSpace, Matrix.instAlgebra with }
section
variable [NormedDivisionRing α] [NormedAlgebra ℝ α]
/-- Auxiliary construction; an element of norm 1 such that `a * unitOf a = ‖a‖`. -/
private def unitOf (a : α) : α := by classical exact if a = 0 then 1 else ‖a‖ • a⁻¹
private theorem norm_unitOf (a : α) : ‖unitOf a‖₊ = 1 := by
rw [unitOf]
split_ifs with h
· simp
· rw [← nnnorm_eq_zero] at h
rw [nnnorm_smul, nnnorm_inv, nnnorm_norm, mul_inv_cancel₀ h]
private theorem mul_unitOf (a : α) : a * unitOf a = algebraMap _ _ (‖a‖₊ : ℝ) := by
simp only [unitOf, coe_nnnorm]
split_ifs with h
· simp [h]
· rw [mul_smul_comm, mul_inv_cancel₀ h, Algebra.algebraMap_eq_smul_one]
end
/-!
For a matrix over a field, the norm defined in this section agrees with the operator norm on
`ContinuousLinearMap`s between function types (which have the infinity norm).
-/
section
variable [NontriviallyNormedField α] [NormedAlgebra ℝ α]
lemma linfty_opNNNorm_eq_opNNNorm (A : Matrix m n α) :
‖A‖₊ = ‖ContinuousLinearMap.mk (Matrix.mulVecLin A)‖₊ := by
rw [ContinuousLinearMap.opNNNorm_eq_of_bounds _ (linfty_opNNNorm_mulVec _) fun N hN => ?_]
rw [linfty_opNNNorm_def]
refine Finset.sup_le fun i _ => ?_
cases isEmpty_or_nonempty n
· simp
classical
let x : n → α := fun j => unitOf (A i j)
have hxn : ‖x‖₊ = 1 := by
simp_rw [x, Pi.nnnorm_def, norm_unitOf, Finset.sup_const Finset.univ_nonempty]
specialize hN x
rw [hxn, mul_one, Pi.nnnorm_def, Finset.sup_le_iff] at hN
replace hN := hN i (Finset.mem_univ _)
dsimp [mulVec, dotProduct] at hN
simp_rw [x, mul_unitOf, ← map_sum, nnnorm_algebraMap, ← NNReal.coe_sum, NNReal.nnnorm_eq,
nnnorm_one, mul_one] at hN
exact hN
lemma linfty_opNorm_eq_opNorm (A : Matrix m n α) :
‖A‖ = ‖ContinuousLinearMap.mk (Matrix.mulVecLin A)‖ :=
congr_arg NNReal.toReal (linfty_opNNNorm_eq_opNNNorm A)
variable [DecidableEq n]
@[simp] lemma linfty_opNNNorm_toMatrix (f : (n → α) →L[α] (m → α)) :
‖LinearMap.toMatrix' (↑f : (n → α) →ₗ[α] (m → α))‖₊ = ‖f‖₊ := by
rw [linfty_opNNNorm_eq_opNNNorm]
simp only [← toLin'_apply', toLin'_toMatrix']
@[simp] lemma linfty_opNorm_toMatrix (f : (n → α) →L[α] (m → α)) :
‖LinearMap.toMatrix' (↑f : (n → α) →ₗ[α] (m → α))‖ = ‖f‖ :=
congr_arg NNReal.toReal (linfty_opNNNorm_toMatrix f)
end
namespace Norms.Operator
attribute [scoped instance]
Matrix.linftyOpSeminormedAddCommGroup
Matrix.linftyOpNormedAddCommGroup
Matrix.linftyOpNormedSpace
Matrix.linftyOpIsBoundedSMul
Matrix.linftyOpNormSMulClass
Matrix.linftyOpNonUnitalSemiNormedRing
Matrix.linftyOpSemiNormedRing
Matrix.linftyOpNonUnitalNormedRing
Matrix.linftyOpNormedRing
Matrix.linftyOpNormedAlgebra
end Norms.Operator
end LinftyOp
/-! ### The Frobenius norm
This is defined as $\|A\| = \sqrt{\sum_{i,j} \|A_{ij}\|^2}$.
When the matrix is over the real or complex numbers, this norm is submultiplicative.
-/
section frobenius
open scoped Matrix
/-- Seminormed group instance (using the Frobenius norm) for matrices over a seminormed group. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
def frobeniusSeminormedAddCommGroup [SeminormedAddCommGroup α] :
SeminormedAddCommGroup (Matrix m n α) :=
inferInstanceAs (SeminormedAddCommGroup (PiLp 2 fun _i : m => PiLp 2 fun _j : n => α))
/-- Normed group instance (using the Frobenius norm) for matrices over a normed group. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
def frobeniusNormedAddCommGroup [NormedAddCommGroup α] : NormedAddCommGroup (Matrix m n α) :=
(by infer_instance : NormedAddCommGroup (PiLp 2 fun i : m => PiLp 2 fun j : n => α))
/-- This applies to the Frobenius norm. -/
@[local instance]
theorem frobeniusIsBoundedSMul [SeminormedRing R] [SeminormedAddCommGroup α] [Module R α]
[IsBoundedSMul R α] :
IsBoundedSMul R (Matrix m n α) :=
(by infer_instance : IsBoundedSMul R (PiLp 2 fun i : m => PiLp 2 fun j : n => α))
/-- This applies to the Frobenius norm. -/
@[local instance]
theorem frobeniusNormSMulClass [SeminormedRing R] [SeminormedAddCommGroup α] [Module R α]
[NormSMulClass R α] :
NormSMulClass R (Matrix m n α) :=
(by infer_instance : NormSMulClass R (PiLp 2 fun i : m => PiLp 2 fun j : n => α))
@[deprecated (since := "2025-03-10")] alias frobeniusBoundedSMul := frobeniusIsBoundedSMul
/-- Normed space instance (using the Frobenius norm) for matrices over a normed space. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
def frobeniusNormedSpace [NormedField R] [SeminormedAddCommGroup α] [NormedSpace R α] :
NormedSpace R (Matrix m n α) :=
(by infer_instance : NormedSpace R (PiLp 2 fun i : m => PiLp 2 fun j : n => α))
section SeminormedAddCommGroup
variable [SeminormedAddCommGroup α] [SeminormedAddCommGroup β]
theorem frobenius_nnnorm_def (A : Matrix m n α) :
‖A‖₊ = (∑ i, ∑ j, ‖A i j‖₊ ^ (2 : ℝ)) ^ (1 / 2 : ℝ) := by
-- Porting note: added, along with `WithLp.equiv_symm_pi_apply` below
change ‖toLp 2 fun i => toLp 2 fun j => A i j‖₊ = _
simp_rw [PiLp.nnnorm_eq_of_L2, NNReal.sq_sqrt, NNReal.sqrt_eq_rpow, NNReal.rpow_two,
PiLp.toLp_apply]
theorem frobenius_norm_def (A : Matrix m n α) :
‖A‖ = (∑ i, ∑ j, ‖A i j‖ ^ (2 : ℝ)) ^ (1 / 2 : ℝ) :=
(congr_arg ((↑) : ℝ≥0 → ℝ) (frobenius_nnnorm_def A)).trans <| by simp [NNReal.coe_sum]
@[simp]
theorem frobenius_nnnorm_map_eq (A : Matrix m n α) (f : α → β) (hf : ∀ a, ‖f a‖₊ = ‖a‖₊) :
‖A.map f‖₊ = ‖A‖₊ := by simp_rw [frobenius_nnnorm_def, Matrix.map_apply, hf]
@[simp]
theorem frobenius_norm_map_eq (A : Matrix m n α) (f : α → β) (hf : ∀ a, ‖f a‖ = ‖a‖) :
‖A.map f‖ = ‖A‖ :=
(congr_arg ((↑) : ℝ≥0 → ℝ) <| frobenius_nnnorm_map_eq A f fun a => Subtype.ext <| hf a :)
@[simp]
theorem frobenius_nnnorm_transpose (A : Matrix m n α) : ‖Aᵀ‖₊ = ‖A‖₊ := by
rw [frobenius_nnnorm_def, frobenius_nnnorm_def, Finset.sum_comm]
simp_rw [Matrix.transpose_apply]
@[simp]
theorem frobenius_norm_transpose (A : Matrix m n α) : ‖Aᵀ‖ = ‖A‖ :=
congr_arg ((↑) : ℝ≥0 → ℝ) <| frobenius_nnnorm_transpose A
@[simp]
theorem frobenius_nnnorm_conjTranspose [StarAddMonoid α] [NormedStarGroup α] (A : Matrix m n α) :
‖Aᴴ‖₊ = ‖A‖₊ :=
(frobenius_nnnorm_map_eq _ _ nnnorm_star).trans A.frobenius_nnnorm_transpose
@[simp]
theorem frobenius_norm_conjTranspose [StarAddMonoid α] [NormedStarGroup α] (A : Matrix m n α) :
‖Aᴴ‖ = ‖A‖ :=
congr_arg ((↑) : ℝ≥0 → ℝ) <| frobenius_nnnorm_conjTranspose A
instance frobenius_normedStarGroup [StarAddMonoid α] [NormedStarGroup α] :
NormedStarGroup (Matrix m m α) :=
⟨(le_of_eq <| frobenius_norm_conjTranspose ·)⟩
@[simp]
lemma frobenius_norm_replicateRow (v : m → α) : ‖replicateRow ι v‖ = ‖toLp 2 v‖ := by
rw [frobenius_norm_def, Fintype.sum_unique, PiLp.norm_eq_of_L2, Real.sqrt_eq_rpow]
simp only [replicateRow_apply, Real.rpow_two, PiLp.toLp_apply]
@[deprecated (since := "2025-03-20")] alias frobenius_norm_row := frobenius_norm_replicateRow
@[simp]
lemma frobenius_nnnorm_replicateRow (v : m → α) : ‖replicateRow ι v‖₊ = ‖toLp 2 v‖₊ :=
Subtype.ext <| frobenius_norm_replicateRow v
@[deprecated (since := "2025-03-20")] alias frobenius_nnnorm_row := frobenius_nnnorm_replicateRow
@[simp]
lemma frobenius_norm_replicateCol (v : n → α) : ‖replicateCol ι v‖ = ‖toLp 2 v‖ := by
simp [frobenius_norm_def, PiLp.norm_eq_of_L2, Real.sqrt_eq_rpow]
@[deprecated (since := "2025-03-20")] alias frobenius_norm_col := frobenius_norm_replicateCol
@[simp]
lemma frobenius_nnnorm_replicateCol (v : n → α) : ‖replicateCol ι v‖₊ = ‖toLp 2 v‖₊ :=
Subtype.ext <| frobenius_norm_replicateCol v
@[deprecated (since := "2025-03-20")] alias frobenius_nnnorm_col := frobenius_nnnorm_replicateCol
@[simp]
lemma frobenius_nnnorm_diagonal [DecidableEq n] (v : n → α) : ‖diagonal v‖₊ = ‖toLp 2 v‖₊ := by
simp_rw [frobenius_nnnorm_def, ← Finset.sum_product', Finset.univ_product_univ,
PiLp.nnnorm_eq_of_L2]
let s := (Finset.univ : Finset n).map ⟨fun i : n => (i, i), fun i j h => congr_arg Prod.fst h⟩
rw [← Finset.sum_subset (Finset.subset_univ s) fun i _hi his => ?_]
· rw [Finset.sum_map, NNReal.sqrt_eq_rpow]
dsimp
simp_rw [diagonal_apply_eq, NNReal.rpow_two]
· suffices i.1 ≠ i.2 by rw [diagonal_apply_ne _ this, nnnorm_zero, NNReal.zero_rpow two_ne_zero]
intro h
exact Finset.mem_map.not.mp his ⟨i.1, Finset.mem_univ _, Prod.ext rfl h⟩
@[simp]
lemma frobenius_norm_diagonal [DecidableEq n] (v : n → α) : ‖diagonal v‖ = ‖toLp 2 v‖ :=
(congr_arg ((↑) : ℝ≥0 → ℝ) <| frobenius_nnnorm_diagonal v :).trans rfl
end SeminormedAddCommGroup
theorem frobenius_nnnorm_one [DecidableEq n] [SeminormedAddCommGroup α] [One α] :
‖(1 : Matrix n n α)‖₊ = .sqrt (Fintype.card n) * ‖(1 : α)‖₊ := by
calc
‖(diagonal 1 : Matrix n n α)‖₊
_ = ‖toLp 2 (Function.const _ 1)‖₊ := frobenius_nnnorm_diagonal _
_ = .sqrt (Fintype.card n) * ‖(1 : α)‖₊ := by
rw [PiLp.nnnorm_toLp_const (ENNReal.ofNat_ne_top (n := 2))]
simp [NNReal.sqrt_eq_rpow]
section RCLike
variable [RCLike α]
theorem frobenius_nnnorm_mul (A : Matrix l m α) (B : Matrix m n α) : ‖A * B‖₊ ≤ ‖A‖₊ * ‖B‖₊ := by
simp_rw [frobenius_nnnorm_def, Matrix.mul_apply]
rw [← NNReal.mul_rpow, @Finset.sum_comm _ _ m, Finset.sum_mul_sum]
gcongr with i _ j
rw [← NNReal.rpow_le_rpow_iff one_half_pos, ← NNReal.rpow_mul,
mul_div_cancel₀ (1 : ℝ) two_ne_zero, NNReal.rpow_one, NNReal.mul_rpow]
simpa only [PiLp.toLp_apply, PiLp.inner_apply, RCLike.inner_apply', starRingEnd_apply,
Pi.nnnorm_def, PiLp.nnnorm_eq_of_L2, star_star, nnnorm_star, NNReal.sqrt_eq_rpow,
NNReal.rpow_two] using nnnorm_inner_le_nnnorm (𝕜 := α) (toLp 2 (star <| A i ·)) (toLp 2 (B · j))
theorem frobenius_norm_mul (A : Matrix l m α) (B : Matrix m n α) : ‖A * B‖ ≤ ‖A‖ * ‖B‖ :=
frobenius_nnnorm_mul A B
/-- Normed ring instance (using the Frobenius norm) for matrices over `ℝ` or `ℂ`. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
def frobeniusNormedRing [DecidableEq m] : NormedRing (Matrix m m α) :=
{ Matrix.frobeniusSeminormedAddCommGroup, Matrix.instRing with
norm := Norm.norm
norm_mul_le := frobenius_norm_mul
eq_of_dist_eq_zero := eq_of_dist_eq_zero }
/-- Normed algebra instance (using the Frobenius norm) for matrices over `ℝ` or `ℂ`. Not
declared as an instance because there are several natural choices for defining the norm of a
matrix. -/
@[local instance]
def frobeniusNormedAlgebra [DecidableEq m] [NormedField R] [NormedAlgebra R α] :
NormedAlgebra R (Matrix m m α) :=
{ Matrix.frobeniusNormedSpace, Matrix.instAlgebra with }
end RCLike
end frobenius
namespace Norms.Frobenius
attribute [scoped instance]
Matrix.frobeniusSeminormedAddCommGroup
Matrix.frobeniusNormedAddCommGroup
Matrix.frobeniusNormedSpace
Matrix.frobeniusNormedRing
Matrix.frobeniusNormedAlgebra
Matrix.frobeniusIsBoundedSMul
Matrix.frobeniusNormSMulClass
end Norms.Frobenius
end Matrix
|
Partial.lean
|
/-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import Mathlib.Order.Filter.Partial
import Mathlib.Topology.Neighborhoods
/-!
# Partial functions and topological spaces
In this file we prove properties of `Filter.PTendsto` etc in topological spaces. We also introduce
`PContinuous`, a version of `Continuous` for partially defined functions.
-/
open Filter
open Topology
variable {X Y : Type*} [TopologicalSpace X]
theorem rtendsto_nhds {r : SetRel Y X} {l : Filter Y} {x : X} :
RTendsto r l (𝓝 x) ↔ ∀ s, IsOpen s → x ∈ s → r.core s ∈ l :=
all_mem_nhds_filter _ _ (fun _s _t => id) _
theorem rtendsto'_nhds {r : SetRel Y X} {l : Filter Y} {x : X} :
RTendsto' r l (𝓝 x) ↔ ∀ s, IsOpen s → x ∈ s → r.preimage s ∈ l := by
rw [rtendsto'_def]
apply all_mem_nhds_filter
apply SetRel.preimage_mono
theorem ptendsto_nhds {f : Y →. X} {l : Filter Y} {x : X} :
PTendsto f l (𝓝 x) ↔ ∀ s, IsOpen s → x ∈ s → f.core s ∈ l :=
rtendsto_nhds
theorem ptendsto'_nhds {f : Y →. X} {l : Filter Y} {x : X} :
PTendsto' f l (𝓝 x) ↔ ∀ s, IsOpen s → x ∈ s → f.preimage s ∈ l :=
rtendsto'_nhds
/-! ### Continuity and partial functions -/
variable [TopologicalSpace Y]
/-- Continuity of a partial function -/
def PContinuous (f : X →. Y) :=
∀ s, IsOpen s → IsOpen (f.preimage s)
theorem open_dom_of_pcontinuous {f : X →. Y} (h : PContinuous f) : IsOpen f.Dom := by
rw [← PFun.preimage_univ]; exact h _ isOpen_univ
theorem pcontinuous_iff' {f : X →. Y} :
PContinuous f ↔ ∀ {x y} (_ : y ∈ f x), PTendsto' f (𝓝 x) (𝓝 y) := by
constructor
· intro h x y h'
simp only [ptendsto'_def, mem_nhds_iff]
rintro s ⟨t, tsubs, opent, yt⟩
exact ⟨f.preimage t, PFun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩
intro hf s os
rw [isOpen_iff_nhds]
rintro x ⟨y, ys, fxy⟩ t
rw [mem_principal]
intro (h : f.preimage s ⊆ t)
apply mem_of_superset _ h
have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x := by
intro s hs
have : PTendsto' f (𝓝 x) (𝓝 y) := hf fxy
rw [ptendsto'_def] at this
exact this s hs
change f.preimage s ∈ 𝓝 x
apply h'
rw [mem_nhds_iff]
exact ⟨s, Set.Subset.refl _, os, ys⟩
theorem continuousWithinAt_iff_ptendsto_res (f : X → Y) {x : X} {s : Set X} :
ContinuousWithinAt f s x ↔ PTendsto (PFun.res f s) (𝓝 x) (𝓝 (f x)) :=
tendsto_iff_ptendsto _ _ _ _
|
HVertexOperator.lean
|
/-
Copyright (c) 2024 Scott Carnahan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Carnahan
-/
import Mathlib.RingTheory.HahnSeries.Multiplication
/-!
# Vertex operators
In this file we introduce heterogeneous vertex operators using Hahn series. When `R = ℂ`, `V = W`,
and `Γ = ℤ`, then this is the usual notion of "meromorphic left-moving 2D field". The notion we use
here allows us to consider composites and scalar-multiply by multivariable Laurent series.
## Definitions
* `HVertexOperator` : An `R`-linear map from an `R`-module `V` to `HahnModule Γ W`.
* The coefficient function as an `R`-linear map.
* Composition of heterogeneous vertex operators - values are Hahn series on lex order product.
## Main results
* Ext
## TODO
* `HahnSeries Γ R`-module structure on `HVertexOperator Γ R V W`
(needs https://github.com/leanprover-community/mathlib4/pull/19062.
This means we can consider products of the form `(X-Y)^n A(X)B(Y)` for all integers `n`,
where `(X-Y)^n` is expanded as `X^n(1-Y/X)^n` in `R((X))((Y))`.
* curry for tensor product inputs
* more API to make ext comparisons easier.
* formal variable API, e.g., like the `T` function for Laurent polynomials.
## References
* [R. Borcherds, *Vertex Algebras, Kac-Moody Algebras, and the Monster*][borcherds1986vertex]
-/
assert_not_exists Cardinal
noncomputable section
variable {Γ : Type*} [PartialOrder Γ] {R : Type*} {V W : Type*} [CommRing R]
[AddCommGroup V] [Module R V] [AddCommGroup W] [Module R W]
/-- A heterogeneous `Γ`-vertex operator over a commutator ring `R` is an `R`-linear map from an
`R`-module `V` to `Γ`-Hahn series with coefficients in an `R`-module `W`. -/
abbrev HVertexOperator (Γ : Type*) [PartialOrder Γ] (R : Type*) [CommRing R]
(V : Type*) (W : Type*) [AddCommGroup V] [Module R V] [AddCommGroup W] [Module R W] :=
V →ₗ[R] (HahnModule Γ R W)
namespace HVertexOperator
section Coeff
open HahnModule
@[ext]
theorem ext (A B : HVertexOperator Γ R V W) (h : ∀ v : V, A v = B v) :
A = B := LinearMap.ext h
/-- The coefficient of a heterogeneous vertex operator, viewed as a formal power series with
coefficients in linear maps. -/
@[simps]
def coeff (A : HVertexOperator Γ R V W) (n : Γ) : V →ₗ[R] W where
toFun v := ((of R).symm (A v)).coeff n
map_add' _ _ := by simp
map_smul' _ _ := by
simp only [map_smul, RingHom.id_apply, of_symm_smul, HahnSeries.coeff_smul]
theorem coeff_isPWOsupport (A : HVertexOperator Γ R V W) (v : V) :
((of R).symm (A v)).coeff.support.IsPWO :=
((of R).symm (A v)).isPWO_support'
@[ext]
theorem coeff_inj : Function.Injective (coeff : HVertexOperator Γ R V W → Γ → (V →ₗ[R] W)) := by
intro _ _ h
ext v n
exact congrFun (congrArg DFunLike.coe (congrFun h n)) v
/-- Given a coefficient function valued in linear maps satisfying a partially well-ordered support
condition, we produce a heterogeneous vertex operator. -/
@[simps]
def of_coeff (f : Γ → V →ₗ[R] W)
(hf : ∀ (x : V), (Function.support (f · x)).IsPWO) : HVertexOperator Γ R V W where
toFun x := (of R) { coeff := fun g => f g x, isPWO_support' := hf x }
map_add' _ _ := by ext; simp
map_smul' _ _ := by ext; simp
@[simp]
theorem coeff_add (A B : HVertexOperator Γ R V W) : (A + B).coeff = A.coeff + B.coeff := by
ext
simp
@[simp]
theorem coeff_smul (A : HVertexOperator Γ R V W) (r : R) : (r • A).coeff = r • (A.coeff) := by
ext
simp
end Coeff
section Products
variable {Γ Γ' : Type*} [PartialOrder Γ] [PartialOrder Γ'] {R : Type*}
[CommRing R] {U V W : Type*} [AddCommGroup U] [Module R U] [AddCommGroup V] [Module R V]
[AddCommGroup W] [Module R W] (A : HVertexOperator Γ R V W) (B : HVertexOperator Γ' R U V)
open HahnModule
/-- The composite of two heterogeneous vertex operators acting on a vector, as an iterated Hahn
series. -/
@[simps]
def compHahnSeries (u : U) : HahnSeries Γ' (HahnSeries Γ W) where
coeff g' := A (coeff B g' u)
isPWO_support' := by
refine Set.IsPWO.mono (((of R).symm (B u)).isPWO_support') ?_
simp_all only [coeff_apply, Function.support_subset_iff, ne_eq, Function.mem_support]
intro g' hg' hAB
apply hg'
simp_rw [hAB]
simp_all only [map_zero, not_true_eq_false]
@[simp]
theorem compHahnSeries_add (u v : U) :
compHahnSeries A B (u + v) = compHahnSeries A B u + compHahnSeries A B v := by
ext
simp only [compHahnSeries_coeff, map_add, coeff_apply, HahnSeries.coeff_add', Pi.add_apply]
rw [← HahnSeries.coeff_add]
@[simp]
theorem compHahnSeries_smul (r : R) (u : U) :
compHahnSeries A B (r • u) = r • compHahnSeries A B u := by
ext
simp only [compHahnSeries_coeff, LinearMapClass.map_smul, coeff_apply, HahnSeries.coeff_smul]
rw [← HahnSeries.coeff_smul]
/-- The composite of two heterogeneous vertex operators, as a heterogeneous vertex operator. -/
@[simps]
def comp : HVertexOperator (Γ' ×ₗ Γ) R U W where
toFun u := HahnModule.of R (HahnSeries.ofIterate (compHahnSeries A B u))
map_add' := by
intro u v
ext g
simp only [HahnSeries.ofIterate, compHahnSeries_add, Equiv.symm_apply_apply,
HahnModule.of_symm_add, HahnSeries.coeff_add', Pi.add_apply]
map_smul' := by
intro r x
ext g
simp only [HahnSeries.ofIterate, compHahnSeries_smul, HahnSeries.coeff_smul,
compHahnSeries_coeff, coeff_apply, Equiv.symm_apply_apply, RingHom.id_apply, of_symm_smul]
@[simp]
theorem coeff_comp (g : Γ' ×ₗ Γ) :
(comp A B).coeff g = A.coeff (ofLex g).2 ∘ₗ B.coeff (ofLex g).1 := by
rfl
end Products
end HVertexOperator
|
Module.lean
|
/-
Copyright (c) 2021 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import Mathlib.Data.SetLike.Fintype
import Mathlib.Order.Filter.EventuallyConst
import Mathlib.RingTheory.Ideal.Prod
import Mathlib.RingTheory.Ideal.Quotient.Operations
import Mathlib.RingTheory.Jacobson.Semiprimary
import Mathlib.RingTheory.Nilpotent.Lemmas
import Mathlib.RingTheory.Noetherian.Defs
import Mathlib.RingTheory.Spectrum.Maximal.Basic
import Mathlib.RingTheory.Spectrum.Prime.Basic
/-!
# Artinian rings and modules
A module satisfying these equivalent conditions is said to be an *Artinian* R-module
if every decreasing chain of submodules is eventually constant, or equivalently,
if the relation `<` on submodules is well founded.
A ring is said to be left (or right) Artinian if it is Artinian as a left (or right) module over
itself, or simply Artinian if it is both left and right Artinian.
## Main definitions
Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`.
* `IsArtinian R M` is the proposition that `M` is an Artinian `R`-module. It is a class,
implemented as the predicate that the `<` relation on submodules is well founded.
* `IsArtinianRing R` is the proposition that `R` is a left Artinian ring.
## Main results
* `IsArtinianRing.primeSpectrum_finite`, `IsArtinianRing.isMaximal_of_isPrime`: there are only
finitely prime ideals in a commutative artinian ring, and each of them is maximal.
* `IsArtinianRing.equivPi`: a reduced commutative artinian ring `R` is isomorphic to a finite
product of fields (and therefore is a semisimple ring and a decomposition monoid; moreover
`R[X]` is also a decomposition monoid).
* `IsArtinian.isSemisimpleModule_iff_jacobson`: an Artinian module is semisimple
iff its Jacobson radical is zero.
* `instIsSemiprimaryRingOfIsArtinianRing`: an Artinian ring `R` is semiprimary, in particular
the Jacobson radical of `R` is a nilpotent ideal (`IsArtinianRing.isNilpotent_jacobson_bot`).
## References
* [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald]
* [P. Samuel, *Algebraic Theory of Numbers*][samuel1967]
## Tags
Artinian, artinian, Artinian ring, Artinian module, artinian ring, artinian module
-/
open Set Filter Pointwise
/-- `IsArtinian R M` is the proposition that `M` is an Artinian `R`-module,
implemented as the well-foundedness of submodule inclusion. -/
abbrev IsArtinian (R M) [Semiring R] [AddCommMonoid M] [Module R M] : Prop :=
WellFoundedLT (Submodule R M)
theorem isArtinian_iff (R M) [Semiring R] [AddCommMonoid M] [Module R M] : IsArtinian R M ↔
WellFounded (· < · : Submodule R M → Submodule R M → Prop) :=
isWellFounded_iff _ _
section Semiring
variable {R M P N : Type*}
variable [Semiring R] [AddCommMonoid M] [AddCommMonoid P] [AddCommMonoid N]
variable [Module R M] [Module R P] [Module R N]
theorem LinearMap.isArtinian_iff_of_bijective {S P} [Semiring S] [AddCommMonoid P] [Module S P]
{σ : R →+* S} [RingHomSurjective σ] (l : M →ₛₗ[σ] P) (hl : Function.Bijective l) :
IsArtinian R M ↔ IsArtinian S P :=
let e := Submodule.orderIsoMapComapOfBijective l hl
⟨fun _ ↦ e.symm.strictMono.wellFoundedLT, fun _ ↦ e.strictMono.wellFoundedLT⟩
theorem isArtinian_of_injective (f : M →ₗ[R] P) (h : Function.Injective f) [IsArtinian R P] :
IsArtinian R M :=
⟨Subrelation.wf
(fun {A B} hAB => show A.map f < B.map f from Submodule.map_strictMono_of_injective h hAB)
(InvImage.wf (Submodule.map f) IsWellFounded.wf)⟩
instance isArtinian_submodule' [IsArtinian R M] (N : Submodule R M) : IsArtinian R N :=
isArtinian_of_injective N.subtype Subtype.val_injective
theorem isArtinian_of_le {s t : Submodule R M} [IsArtinian R t] (h : s ≤ t) : IsArtinian R s :=
isArtinian_of_injective (Submodule.inclusion h) (Submodule.inclusion_injective h)
variable (M) in
theorem isArtinian_of_surjective (f : M →ₗ[R] P) (hf : Function.Surjective f) [IsArtinian R M] :
IsArtinian R P :=
⟨Subrelation.wf
(fun {A B} hAB =>
show A.comap f < B.comap f from Submodule.comap_strictMono_of_surjective hf hAB)
(InvImage.wf (Submodule.comap f) IsWellFounded.wf)⟩
/--
If `M` is an Artinian `R` module, and `S` is an `R`-algebra with a surjective
algebra map, then `M` is an Artinian `S` module.
-/
theorem isArtinian_of_surjective_algebraMap {S : Type*} [CommSemiring S] [Algebra S R]
[Module S M] [IsArtinian R M] [IsScalarTower S R M]
(H : Function.Surjective (algebraMap S R)) : IsArtinian S M := by
apply (OrderEmbedding.wellFoundedLT (β := Submodule R M))
refine ⟨⟨?_, ?_⟩, ?_⟩
· intro N
refine {toAddSubmonoid := N.toAddSubmonoid, smul_mem' := ?_}
intro c x hx
obtain ⟨r, rfl⟩ := H c
suffices r • x ∈ N by simpa [Algebra.algebraMap_eq_smul_one, smul_assoc]
apply N.smul_mem _ hx
· intro N1 N2 h
rwa [Submodule.ext_iff] at h ⊢
· intro N1 N2
rfl
instance isArtinian_range (f : M →ₗ[R] P) [IsArtinian R M] : IsArtinian R (LinearMap.range f) :=
isArtinian_of_surjective _ _ f.surjective_rangeRestrict
theorem isArtinian_of_linearEquiv (f : M ≃ₗ[R] P) [IsArtinian R M] : IsArtinian R P :=
isArtinian_of_surjective _ f.toLinearMap f.toEquiv.surjective
theorem LinearEquiv.isArtinian_iff (f : M ≃ₗ[R] P) : IsArtinian R M ↔ IsArtinian R P :=
⟨fun _ ↦ isArtinian_of_linearEquiv f, fun _ ↦ isArtinian_of_linearEquiv f.symm⟩
-- This was previously a global instance,
-- but it doesn't appear to be used and has been implicated in slow typeclass resolutions.
lemma isArtinian_of_finite [Finite M] : IsArtinian R M :=
⟨Finite.wellFounded_of_trans_of_irrefl _⟩
-- Porting note: elab_as_elim can only be global and cannot be changed on an imported decl
-- attribute [local elab_as_elim] Finite.induction_empty_option
open Submodule
theorem IsArtinian.finite_of_linearIndependent [Nontrivial R] [h : IsArtinian R M] {s : Set M}
(hs : LinearIndependent R ((↑) : s → M)) : s.Finite := by
refine by_contradiction fun hf ↦ (RelEmbedding.wellFounded_iff_isEmpty.1 h.wf).elim' ?_
have f : ℕ ↪ s := Set.Infinite.natEmbedding s hf
have : ∀ n, (↑) ∘ f '' { m | n ≤ m } ⊆ s := by
rintro n x ⟨y, _, rfl⟩
exact (f y).2
have : ∀ a b : ℕ, a ≤ b ↔
span R (Subtype.val ∘ f '' { m | b ≤ m }) ≤ span R (Subtype.val ∘ f '' { m | a ≤ m }) := by
intro a b
rw [span_le_span_iff hs (this b) (this a),
Set.image_subset_image_iff (Subtype.coe_injective.comp f.injective), Set.subset_def]
simp only [Set.mem_setOf_eq]
exact ⟨fun hab x ↦ hab.trans, (· _ le_rfl)⟩
exact ⟨⟨fun n ↦ span R (Subtype.val ∘ f '' { m | n ≤ m }), fun x y ↦ by
rw [le_antisymm_iff, ← this y x, ← this x y]
exact fun ⟨h₁, h₂⟩ ↦ le_antisymm_iff.2 ⟨h₂, h₁⟩⟩, by
intro a b
conv_rhs => rw [GT.gt, lt_iff_le_not_ge, this, this, ← lt_iff_le_not_ge]
rfl⟩
/-- A module is Artinian iff every nonempty set of submodules has a minimal submodule among them. -/
theorem set_has_minimal_iff_artinian :
(∀ a : Set <| Submodule R M, a.Nonempty → ∃ M' ∈ a, ∀ I ∈ a, ¬I < M') ↔ IsArtinian R M := by
rw [isArtinian_iff, WellFounded.wellFounded_iff_has_min]
theorem IsArtinian.set_has_minimal [IsArtinian R M] (a : Set <| Submodule R M) (ha : a.Nonempty) :
∃ M' ∈ a, ∀ I ∈ a, ¬I < M' :=
set_has_minimal_iff_artinian.mpr ‹_› a ha
/-- A module is Artinian iff every decreasing chain of submodules stabilizes. -/
theorem monotone_stabilizes_iff_artinian :
(∀ f : ℕ →o (Submodule R M)ᵒᵈ, ∃ n, ∀ m, n ≤ m → f n = f m) ↔ IsArtinian R M :=
wellFoundedGT_iff_monotone_chain_condition.symm
namespace IsArtinian
variable [IsArtinian R M]
theorem monotone_stabilizes (f : ℕ →o (Submodule R M)ᵒᵈ) : ∃ n, ∀ m, n ≤ m → f n = f m :=
monotone_stabilizes_iff_artinian.mpr ‹_› f
theorem eventuallyConst_of_isArtinian (f : ℕ →o (Submodule R M)ᵒᵈ) :
atTop.EventuallyConst f := by
simp_rw [eventuallyConst_atTop, eq_comm]
exact monotone_stabilizes f
/-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/
theorem induction {P : Submodule R M → Prop} (hgt : ∀ I, (∀ J < I, P J) → P I) (I : Submodule R M) :
P I :=
WellFoundedLT.induction I hgt
open Function
/-- Any injective endomorphism of an Artinian module is surjective. -/
theorem surjective_of_injective_endomorphism (f : M →ₗ[R] M) (s : Injective f) : Surjective f := by
have h := ‹IsArtinian R M›; contrapose! h
rw [IsArtinian, WellFoundedLT, isWellFounded_iff]
refine (RelEmbedding.natGT (LinearMap.range <| f ^ ·) ?_).not_wellFounded
intro n
simp_rw [pow_succ, Module.End.mul_eq_comp, LinearMap.range_comp, ← Submodule.map_top (f ^ n)]
refine Submodule.map_strictMono_of_injective (Module.End.iterate_injective s n) (Ne.lt_top ?_)
rwa [Ne, LinearMap.range_eq_top]
/-- Any injective endomorphism of an Artinian module is bijective. -/
theorem bijective_of_injective_endomorphism (f : M →ₗ[R] M) (s : Injective f) : Bijective f :=
⟨s, surjective_of_injective_endomorphism f s⟩
/-- A sequence `f` of submodules of an artinian module,
with the supremum `f (n+1)` and the infimum of `f 0`, ..., `f n` being ⊤,
is eventually ⊤. -/
theorem disjoint_partial_infs_eventually_top (f : ℕ → Submodule R M)
(h : ∀ n, Disjoint (partialSups (OrderDual.toDual ∘ f) n) (OrderDual.toDual (f (n + 1)))) :
∃ n : ℕ, ∀ m, n ≤ m → f m = ⊤ := by
-- A little off-by-one cleanup first:
rsuffices ⟨n, w⟩ : ∃ n : ℕ, ∀ m, n ≤ m → OrderDual.toDual f (m + 1) = ⊤
· use n + 1
rintro (_ | m) p
· cases p
· apply w
exact Nat.succ_le_succ_iff.mp p
obtain ⟨n, w⟩ := monotone_stabilizes (partialSups (OrderDual.toDual ∘ f))
refine ⟨n, fun m p ↦ (h m).eq_bot_of_ge <| sup_eq_left.mp ?_⟩
simpa only [partialSups_add_one] using (w (m + 1) <| le_add_right p).symm.trans <| w m p
end IsArtinian
namespace LinearMap
variable [IsArtinian R M]
lemma eventually_iInf_range_pow_eq (f : Module.End R M) :
∀ᶠ n in atTop, ⨅ m, LinearMap.range (f ^ m) = LinearMap.range (f ^ n) := by
obtain ⟨n, hn : ∀ m, n ≤ m → LinearMap.range (f ^ n) = LinearMap.range (f ^ m)⟩ :=
IsArtinian.monotone_stabilizes f.iterateRange
refine eventually_atTop.mpr ⟨n, fun l hl ↦ le_antisymm (iInf_le _ _) (le_iInf fun m ↦ ?_)⟩
rcases le_or_gt l m with h | h
· rw [← hn _ (hl.trans h), hn _ hl]
· exact f.iterateRange.monotone h.le
end LinearMap
end Semiring
section Ring
variable {R M P N : Type*}
variable [Ring R] [AddCommGroup M] [AddCommGroup P] [AddCommGroup N]
variable [Module R M] [Module R P] [Module R N]
instance isArtinian_of_quotient_of_artinian
(N : Submodule R M) [IsArtinian R M] : IsArtinian R (M ⧸ N) :=
isArtinian_of_surjective M (Submodule.mkQ N) (Submodule.Quotient.mk_surjective N)
theorem isArtinian_of_range_eq_ker [IsArtinian R M] [IsArtinian R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P)
(h : LinearMap.range f = LinearMap.ker g) : IsArtinian R N :=
wellFounded_lt_exact_sequence (LinearMap.range f)
(Submodule.map ((LinearMap.ker f).liftQ f le_rfl))
(Submodule.comap ((LinearMap.ker f).liftQ f le_rfl))
(Submodule.comap g.rangeRestrict) (Submodule.map g.rangeRestrict)
(Submodule.gciMapComap <| LinearMap.ker_eq_bot.mp <| Submodule.ker_liftQ_eq_bot _ _ _ le_rfl)
(Submodule.giMapComap g.surjective_rangeRestrict)
(by simp [Submodule.map_comap_eq, inf_comm, Submodule.range_liftQ])
(by simp [Submodule.comap_map_eq, h])
theorem isArtinian_iff_submodule_quotient (S : Submodule R P) :
IsArtinian R P ↔ IsArtinian R S ∧ IsArtinian R (P ⧸ S) := by
refine ⟨fun h ↦ ⟨inferInstance, inferInstance⟩, fun ⟨_, _⟩ ↦ ?_⟩
apply isArtinian_of_range_eq_ker S.subtype S.mkQ
rw [Submodule.ker_mkQ, Submodule.range_subtype]
instance isArtinian_prod [IsArtinian R M] [IsArtinian R P] : IsArtinian R (M × P) :=
isArtinian_of_range_eq_ker (LinearMap.inl R M P) (LinearMap.snd R M P) (LinearMap.range_inl R M P)
instance isArtinian_sup (M₁ M₂ : Submodule R P) [IsArtinian R M₁] [IsArtinian R M₂] :
IsArtinian R ↥(M₁ ⊔ M₂) := by
have := isArtinian_range (M₁.subtype.coprod M₂.subtype)
rwa [LinearMap.range_coprod, Submodule.range_subtype, Submodule.range_subtype] at this
variable {ι : Type*} [Finite ι]
instance isArtinian_pi :
∀ {M : ι → Type*} [Π i, AddCommGroup (M i)]
[Π i, Module R (M i)] [∀ i, IsArtinian R (M i)], IsArtinian R (Π i, M i) := by
apply Finite.induction_empty_option _ _ _ ι
· exact fun e h ↦ isArtinian_of_linearEquiv (LinearEquiv.piCongrLeft R _ e)
· infer_instance
· exact fun ih ↦ isArtinian_of_linearEquiv (LinearEquiv.piOptionEquivProd R).symm
/-- A version of `isArtinian_pi` for non-dependent functions. We need this instance because
sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to
prove that `ι → ℝ` is finite dimensional over `ℝ`). -/
instance isArtinian_pi' [IsArtinian R M] : IsArtinian R (ι → M) :=
isArtinian_pi
--Porting note (https://github.com/leanprover-community/mathlib4/issues/10754): new instance
instance isArtinian_finsupp [IsArtinian R M] : IsArtinian R (ι →₀ M) :=
isArtinian_of_linearEquiv (Finsupp.linearEquivFunOnFinite _ _ _).symm
instance isArtinian_iSup :
∀ {M : ι → Submodule R P} [∀ i, IsArtinian R (M i)], IsArtinian R ↥(⨆ i, M i) := by
apply Finite.induction_empty_option _ _ _ ι
· intro _ _ e h _ _; rw [← e.iSup_comp]; apply h
· intros; rw [iSup_of_empty]; infer_instance
· intro _ _ ih _ _; rw [iSup_option]; infer_instance
variable (R M) in
theorem IsArtinian.isSemisimpleModule_iff_jacobson [IsArtinian R M] :
IsSemisimpleModule R M ↔ Module.jacobson R M = ⊥ :=
⟨fun _ ↦ IsSemisimpleModule.jacobson_eq_bot R M, fun h ↦
have ⟨s, hs⟩ := Finset.exists_inf_le (Subtype.val (p := fun m : Submodule R M ↦ IsCoatom m))
have _ (m : s) : IsSimpleModule R (M ⧸ m.1.1) := isSimpleModule_iff_isCoatom.mpr m.1.2
let f : M →ₗ[R] ∀ m : s, M ⧸ m.1.1 := LinearMap.pi fun m ↦ m.1.1.mkQ
.of_injective f <| LinearMap.ker_eq_bot.mp <| le_bot_iff.mp fun x hx ↦ by
rw [← h, Module.jacobson, Submodule.mem_sInf]
exact fun m hm ↦ hs ⟨m, hm⟩ <| Submodule.mem_finset_inf.mpr fun i hi ↦
(Submodule.Quotient.mk_eq_zero i.1).mp <| congr_fun hx ⟨i, hi⟩⟩
open Submodule Function
namespace LinearMap
variable [IsArtinian R M]
/-- For any endomorphism of an Artinian module, any sufficiently high iterate has codisjoint kernel
and range. -/
theorem eventually_codisjoint_ker_pow_range_pow (f : Module.End R M) :
∀ᶠ n in atTop, Codisjoint (LinearMap.ker (f ^ n)) (LinearMap.range (f ^ n)) := by
obtain ⟨n, hn : ∀ m, n ≤ m → LinearMap.range (f ^ n) = LinearMap.range (f ^ m)⟩ :=
IsArtinian.monotone_stabilizes f.iterateRange
refine eventually_atTop.mpr ⟨n, fun m hm ↦ codisjoint_iff.mpr ?_⟩
simp_rw [← hn _ hm, Submodule.eq_top_iff', Submodule.mem_sup]
intro x
rsuffices ⟨y, hy⟩ : ∃ y, (f ^ m) ((f ^ n) y) = (f ^ m) x
· exact ⟨x - (f ^ n) y, by simp [hy], (f ^ n) y, by simp⟩
-- Note: https://github.com/leanprover-community/mathlib4/pull/8386 had to change `mem_range` into `mem_range (f := _)`
simp_rw [f.pow_apply n, f.pow_apply m, ← iterate_add_apply, ← f.pow_apply (m + n),
← f.pow_apply m, ← mem_range (f := _), ← hn _ (n.le_add_left m), hn _ hm]
exact LinearMap.mem_range_self (f ^ m) x
/-- This is the Fitting decomposition of the module `M` with respect to the endomorphism `f`.
See also `LinearMap.isCompl_iSup_ker_pow_iInf_range_pow` for an alternative spelling. -/
theorem eventually_isCompl_ker_pow_range_pow [IsNoetherian R M] (f : Module.End R M) :
∀ᶠ n in atTop, IsCompl (LinearMap.ker (f ^ n)) (LinearMap.range (f ^ n)) := by
filter_upwards [f.eventually_disjoint_ker_pow_range_pow.and
f.eventually_codisjoint_ker_pow_range_pow] with n hn
simpa only [isCompl_iff]
/-- This is the Fitting decomposition of the module `M` with respect to the endomorphism `f`.
See also `LinearMap.eventually_isCompl_ker_pow_range_pow` for an alternative spelling. -/
theorem isCompl_iSup_ker_pow_iInf_range_pow [IsNoetherian R M] (f : M →ₗ[R] M) :
IsCompl (⨆ n, LinearMap.ker (f ^ n)) (⨅ n, LinearMap.range (f ^ n)) := by
obtain ⟨k, hk⟩ := eventually_atTop.mp <| f.eventually_isCompl_ker_pow_range_pow.and <|
f.eventually_iInf_range_pow_eq.and f.eventually_iSup_ker_pow_eq
obtain ⟨h₁, h₂, h₃⟩ := hk k (le_refl k)
rwa [h₂, h₃]
end LinearMap
end Ring
section CommSemiring
variable {R : Type*} (M : Type*) [CommSemiring R] [AddCommMonoid M] [Module R M] [IsArtinian R M]
namespace IsArtinian
theorem range_smul_pow_stabilizes (r : R) :
∃ n : ℕ, ∀ m, n ≤ m →
LinearMap.range (r ^ n • LinearMap.id : M →ₗ[R] M) =
LinearMap.range (r ^ m • LinearMap.id : M →ₗ[R] M) :=
monotone_stabilizes
⟨fun n => LinearMap.range (r ^ n • LinearMap.id : M →ₗ[R] M), fun n m h x ⟨y, hy⟩ =>
⟨r ^ (m - n) • y, by
dsimp at hy ⊢
rw [← smul_assoc, smul_eq_mul, ← pow_add, ← hy, add_tsub_cancel_of_le h]⟩⟩
variable {M}
theorem exists_pow_succ_smul_dvd (r : R) (x : M) :
∃ (n : ℕ) (y : M), r ^ n.succ • y = r ^ n • x := by
obtain ⟨n, hn⟩ := IsArtinian.range_smul_pow_stabilizes M r
simp_rw [SetLike.ext_iff] at hn
exact ⟨n, by simpa using hn n.succ n.le_succ (r ^ n • x)⟩
end IsArtinian
end CommSemiring
theorem isArtinian_of_submodule_of_artinian (R M) [Semiring R] [AddCommMonoid M] [Module R M]
(N : Submodule R M) (_ : IsArtinian R M) : IsArtinian R N := inferInstance
/-- If `M / S / R` is a scalar tower, and `M / R` is Artinian, then `M / S` is also Artinian. -/
theorem isArtinian_of_tower (R) {S M} [Semiring R] [Semiring S] [AddCommMonoid M] [SMul R S]
[Module S M] [Module R M] [IsScalarTower R S M] (h : IsArtinian R M) : IsArtinian S M :=
⟨(Submodule.restrictScalarsEmbedding R S M).wellFounded h.wf⟩
-- See `Mathlib/RingTheory/Artinian/Ring.lean`
assert_not_exists IsLocalization IsLocalRing
/-- A ring is Artinian if it is Artinian as a module over itself.
Strictly speaking, this should be called `IsLeftArtinianRing` but we omit the `Left` for
convenience in the commutative case. For a right Artinian ring, use `IsArtinian Rᵐᵒᵖ R`.
For equivalent definitions, see `Mathlib/RingTheory/Artinian/Ring.lean`.
-/
@[stacks 00J5]
abbrev IsArtinianRing (R) [Semiring R] :=
IsArtinian R R
theorem isArtinianRing_iff {R} [Semiring R] : IsArtinianRing R ↔ IsArtinian R R := Iff.rfl
instance DivisionSemiring.instIsArtinianRing {K : Type*} [DivisionSemiring K] : IsArtinianRing K :=
⟨Finite.wellFounded_of_trans_of_irrefl _⟩
instance DivisionRing.instIsArtinianRing {K : Type*} [DivisionRing K] : IsArtinianRing K :=
inferInstance
theorem Ring.isArtinian_of_zero_eq_one {R} [Semiring R] (h01 : (0 : R) = 1) : IsArtinianRing R :=
have := subsingleton_of_zero_eq_one h01
inferInstance
instance (R) [Ring R] [IsArtinianRing R] (I : Ideal R) [I.IsTwoSided] : IsArtinianRing (R ⧸ I) :=
isArtinian_of_tower R inferInstance
open Submodule Function
instance isArtinian_of_fg_of_artinian' {R M} [Ring R] [AddCommGroup M] [Module R M]
[IsArtinianRing R] [Module.Finite R M] : IsArtinian R M :=
have ⟨_, _, h⟩ := Module.Finite.exists_fin' R M
isArtinian_of_surjective _ _ h
theorem isArtinian_of_fg_of_artinian {R M} [Ring R] [AddCommGroup M] [Module R M]
(N : Submodule R M) [IsArtinianRing R] (hN : N.FG) : IsArtinian R N := by
rw [← Module.Finite.iff_fg] at hN; infer_instance
theorem IsArtinianRing.of_finite (R S) [Ring R] [Ring S] [Module R S] [IsScalarTower R S S]
[IsArtinianRing R] [Module.Finite R S] : IsArtinianRing S :=
isArtinian_of_tower R isArtinian_of_fg_of_artinian'
/-- In a module over an artinian ring, the submodule generated by finitely many vectors is
artinian. -/
theorem isArtinian_span_of_finite (R) {M} [Ring R] [AddCommGroup M] [Module R M] [IsArtinianRing R]
{A : Set M} (hA : A.Finite) : IsArtinian R (Submodule.span R A) :=
isArtinian_of_fg_of_artinian _ (Submodule.fg_def.mpr ⟨A, hA, rfl⟩)
theorem Function.Surjective.isArtinianRing {R} [Semiring R] {S} [Semiring S] {F}
[FunLike F R S] [RingHomClass F R S]
{f : F} (hf : Function.Surjective f) [H : IsArtinianRing R] : IsArtinianRing S := by
rw [isArtinianRing_iff] at H ⊢
exact ⟨(Ideal.orderEmbeddingOfSurjective f hf).wellFounded H.wf⟩
instance isArtinianRing_rangeS {R} [Semiring R] {S} [Semiring S] (f : R →+* S) [IsArtinianRing R] :
IsArtinianRing f.rangeS :=
f.rangeSRestrict_surjective.isArtinianRing
instance isArtinianRing_range {R} [Ring R] {S} [Ring S] (f : R →+* S) [IsArtinianRing R] :
IsArtinianRing f.range :=
isArtinianRing_rangeS f
theorem RingEquiv.isArtinianRing {R S} [Semiring R] [Semiring S] (f : R ≃+* S)
[IsArtinianRing R] : IsArtinianRing S :=
f.surjective.isArtinianRing
instance {R S} [Semiring R] [Semiring S] [IsArtinianRing R] [IsArtinianRing S] :
IsArtinianRing (R × S) :=
Ideal.idealProdEquiv.toOrderEmbedding.wellFoundedLT
instance {ι} [Finite ι] : ∀ {R : ι → Type*} [Π i, Semiring (R i)] [∀ i, IsArtinianRing (R i)],
IsArtinianRing (Π i, R i) := by
apply Finite.induction_empty_option _ _ _ ι
· exact fun e h ↦ RingEquiv.isArtinianRing (.piCongrLeft _ e)
· infer_instance
· exact fun ih ↦ RingEquiv.isArtinianRing (.symm .piOptionEquivProd)
namespace IsArtinianRing
section CommSemiring
variable (R : Type*) [CommSemiring R] [IsArtinianRing R]
@[stacks 00J7]
lemma setOf_isMaximal_finite : {I : Ideal R | I.IsMaximal}.Finite := by
have ⟨s, H⟩ := Finset.exists_inf_le (Subtype.val (p := fun I : Ideal R ↦ I.IsMaximal))
refine Set.finite_def.2 ⟨s, fun p ↦ ?_⟩
have ⟨q, hq1, hq2⟩ := p.2.isPrime.inf_le'.mp (H p)
rwa [← Subtype.ext <| q.2.eq_of_le p.2.ne_top hq2]
instance : Finite (MaximalSpectrum R) :=
haveI : Finite {I : Ideal R // I.IsMaximal} := (setOf_isMaximal_finite R).to_subtype
.of_equiv _ (MaximalSpectrum.equivSubtype _).symm
end CommSemiring
section CommRing
variable {R : Type*} [CommRing R] [IsArtinianRing R]
variable (R) in
lemma isField_of_isDomain [IsDomain R] : IsField R := by
refine ⟨Nontrivial.exists_pair_ne, mul_comm, fun {x} hx ↦ ?_⟩
obtain ⟨n, y, hy⟩ := IsArtinian.exists_pow_succ_smul_dvd x (1 : R)
replace hy : x ^ n * (x * y - 1) = 0 := by
rw [mul_sub, sub_eq_zero]
convert hy using 1
simp [Nat.succ_eq_add_one, pow_add, mul_assoc]
rw [mul_eq_zero, sub_eq_zero] at hy
exact ⟨_, hy.resolve_left <| pow_ne_zero _ hx⟩
/- Does not hold in a commutative semiring:
consider {0, 0.5, 1} with ⊔ as + and ⊓ as *, then both {0} and {0, 0.5} are prime ideals. -/
-- Note: type class synthesis should try to synthesize `p.IsPrime` before `IsArtinianRing R`,
-- hence the argument order.
instance isMaximal_of_isPrime {R : Type*} [CommRing R] (p : Ideal R) [p.IsPrime]
[IsArtinianRing R] : p.IsMaximal :=
Ideal.Quotient.maximal_of_isField _ (isField_of_isDomain _)
lemma isPrime_iff_isMaximal (p : Ideal R) : p.IsPrime ↔ p.IsMaximal :=
⟨fun _ ↦ isMaximal_of_isPrime p, fun h ↦ h.isPrime⟩
/-- The prime spectrum is in bijection with the maximal spectrum. -/
@[simps]
def primeSpectrumEquivMaximalSpectrum : PrimeSpectrum R ≃ MaximalSpectrum R where
toFun I := ⟨I.asIdeal, isPrime_iff_isMaximal I.asIdeal |>.mp I.isPrime⟩
invFun I := ⟨I.asIdeal, isPrime_iff_isMaximal I.asIdeal |>.mpr I.isMaximal⟩
lemma primeSpectrumEquivMaximalSpectrum_comp_asIdeal :
MaximalSpectrum.asIdeal ∘ primeSpectrumEquivMaximalSpectrum =
PrimeSpectrum.asIdeal (R := R) := rfl
lemma primeSpectrumEquivMaximalSpectrum_symm_comp_asIdeal :
PrimeSpectrum.asIdeal ∘ primeSpectrumEquivMaximalSpectrum.symm =
MaximalSpectrum.asIdeal (R := R) := rfl
lemma primeSpectrum_asIdeal_range_eq :
range PrimeSpectrum.asIdeal = (range <| MaximalSpectrum.asIdeal (R := R)) := by
simp only [PrimeSpectrum.range_asIdeal, MaximalSpectrum.range_asIdeal,
isPrime_iff_isMaximal]
variable (R)
lemma setOf_isPrime_finite : {I : Ideal R | I.IsPrime}.Finite := by
simpa only [isPrime_iff_isMaximal] using setOf_isMaximal_finite R
instance : Finite (PrimeSpectrum R) :=
haveI : Finite {I : Ideal R // I.IsPrime} := (setOf_isPrime_finite R).to_subtype
.of_equiv _ (PrimeSpectrum.equivSubtype _).symm.toEquiv
/-- A temporary field instance on the quotients by maximal ideals. -/
@[local instance] noncomputable def fieldOfSubtypeIsMaximal
(I : MaximalSpectrum R) : Field (R ⧸ I.asIdeal) :=
Ideal.Quotient.field I.asIdeal
/-- The quotient of a commutative artinian ring by its nilradical is isomorphic to
a finite product of fields, namely the quotients by the maximal ideals. -/
noncomputable def quotNilradicalEquivPi :
R ⧸ nilradical R ≃+* ∀ I : MaximalSpectrum R, R ⧸ I.asIdeal :=
let f := MaximalSpectrum.asIdeal (R := R)
.trans
(Ideal.quotEquivOfEq <| ext fun x ↦ by
rw [PrimeSpectrum.nilradical_eq_iInf, iInf, primeSpectrum_asIdeal_range_eq]; rfl)
(Ideal.quotientInfRingEquivPiQuotient f <| fun I J h ↦
Ideal.isCoprime_iff_sup_eq.mpr <| I.2.coprime_of_ne J.2 <|
fun hIJ ↦ h <| MaximalSpectrum.ext hIJ)
/-- A reduced commutative artinian ring is isomorphic to a finite product of fields,
namely the quotients by the maximal ideals. -/
noncomputable def equivPi [IsReduced R] : R ≃+* ∀ I : MaximalSpectrum R, R ⧸ I.asIdeal :=
.trans (.symm <| .quotientBot R) <| .trans
(Ideal.quotEquivOfEq (nilradical_eq_zero R).symm) (quotNilradicalEquivPi R)
theorem isSemisimpleRing_of_isReduced [IsReduced R] : IsSemisimpleRing R :=
(equivPi R).symm.isSemisimpleRing
end CommRing
section Ring
variable {R : Type*} [Ring R] [IsArtinianRing R]
theorem isSemisimpleRing_iff_jacobson : IsSemisimpleRing R ↔ Ring.jacobson R = ⊥ :=
IsArtinian.isSemisimpleModule_iff_jacobson R R
instance : IsSemiprimaryRing R where
isSemisimpleRing :=
IsArtinianRing.isSemisimpleRing_iff_jacobson.mpr (Ring.jacobson_quotient_jacobson R)
isNilpotent := by
let Jac := Ring.jacobson R
have ⟨n, hn⟩ := IsArtinian.monotone_stabilizes ⟨(Jac ^ ·), @Ideal.pow_le_pow_right _ _ _⟩
have hn : Jac * Jac ^ n = Jac ^ n := by
rw [← Ideal.IsTwoSided.pow_succ]; exact (hn _ n.le_succ).symm
use n; by_contra ne
have ⟨N, ⟨eq, ne⟩, min⟩ := wellFounded_lt.has_min {N | Jac * N = N ∧ N ≠ ⊥} ⟨_, hn, ne⟩
have : Jac ^ n * N = N := n.rec (by rw [Jac.pow_zero, N.one_mul])
fun n hn ↦ by rwa [Jac.pow_succ, mul_assoc, eq]
let I x := Submodule.map (LinearMap.toSpanSingleton R R x) (Jac ^ n)
have hI x : I x ≤ Ideal.span {x} := by
rw [Ideal.span, LinearMap.span_singleton_eq_range]; exact LinearMap.map_le_range
have ⟨x, hx⟩ : ∃ x ∈ N, I x ≠ ⊥ := by
contrapose! ne
rw [← this, ← le_bot_iff, Ideal.mul_le]
refine fun ri hi rn hn ↦ ?_
rw [← ne rn hn]
exact ⟨ri, hi, rfl⟩
rw [← Ideal.span_singleton_le_iff_mem] at hx
have : I x = N := by
refine ((hI x).trans hx.1).eq_of_not_lt (min _ ⟨?_, hx.2⟩)
rw [← smul_eq_mul, ← Submodule.map_smul'', smul_eq_mul, hn]
have : Ideal.span {x} = N := le_antisymm hx.1 (this.symm.trans_le <| hI x)
refine (this ▸ ne) ((Submodule.fg_span <| Set.finite_singleton x).eq_bot_of_le_jacobson_smul ?_)
rw [← Ideal.span, this, smul_eq_mul, eq]
end Ring
end IsArtinianRing
|
Real.lean
|
/-
Copyright (c) 2023 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Lorenzo Luccioli, Rémy Degenne, Alexander Bentkamp
-/
import Mathlib.Analysis.SpecialFunctions.Gaussian.FourierTransform
import Mathlib.MeasureTheory.Group.Convolution
import Mathlib.Probability.Moments.MGFAnalytic
import Mathlib.Probability.Independence.Basic
/-!
# Gaussian distributions over ℝ
We define a Gaussian measure over the reals.
## Main definitions
* `gaussianPDFReal`: the function `μ v x ↦ (1 / (sqrt (2 * pi * v))) * exp (- (x - μ)^2 / (2 * v))`,
which is the probability density function of a Gaussian distribution with mean `μ` and
variance `v` (when `v ≠ 0`).
* `gaussianPDF`: `ℝ≥0∞`-valued pdf, `gaussianPDF μ v x = ENNReal.ofReal (gaussianPDFReal μ v x)`.
* `gaussianReal`: a Gaussian measure on `ℝ`, parametrized by its mean `μ` and variance `v`.
If `v = 0`, this is `dirac μ`, otherwise it is defined as the measure with density
`gaussianPDF μ v` with respect to the Lebesgue measure.
## Main results
* `gaussianReal_add_const`: if `X` is a random variable with Gaussian distribution with mean `μ` and
variance `v`, then `X + y` is Gaussian with mean `μ + y` and variance `v`.
* `gaussianReal_const_mul`: if `X` is a random variable with Gaussian distribution with mean `μ` and
variance `v`, then `c * X` is Gaussian with mean `c * μ` and variance `c^2 * v`.
-/
open scoped ENNReal NNReal Real Complex
open MeasureTheory
namespace ProbabilityTheory
section GaussianPDF
/-- Probability density function of the gaussian distribution with mean `μ` and variance `v`. -/
noncomputable
def gaussianPDFReal (μ : ℝ) (v : ℝ≥0) (x : ℝ) : ℝ :=
(√(2 * π * v))⁻¹ * rexp (- (x - μ)^2 / (2 * v))
lemma gaussianPDFReal_def (μ : ℝ) (v : ℝ≥0) :
gaussianPDFReal μ v =
fun x ↦ (√(2 * π * v))⁻¹ * rexp (- (x - μ)^2 / (2 * v)) := rfl
@[simp]
lemma gaussianPDFReal_zero_var (m : ℝ) : gaussianPDFReal m 0 = 0 := by
ext1 x
simp [gaussianPDFReal]
/-- The gaussian pdf is positive when the variance is not zero. -/
lemma gaussianPDFReal_pos (μ : ℝ) (v : ℝ≥0) (x : ℝ) (hv : v ≠ 0) : 0 < gaussianPDFReal μ v x := by
rw [gaussianPDFReal]
positivity
/-- The gaussian pdf is nonnegative. -/
lemma gaussianPDFReal_nonneg (μ : ℝ) (v : ℝ≥0) (x : ℝ) : 0 ≤ gaussianPDFReal μ v x := by
rw [gaussianPDFReal]
positivity
/-- The gaussian pdf is measurable. -/
@[fun_prop]
lemma measurable_gaussianPDFReal (μ : ℝ) (v : ℝ≥0) : Measurable (gaussianPDFReal μ v) :=
(((measurable_id.add_const _).pow_const _).neg.div_const _).exp.const_mul _
/-- The gaussian pdf is strongly measurable. -/
@[fun_prop]
lemma stronglyMeasurable_gaussianPDFReal (μ : ℝ) (v : ℝ≥0) :
StronglyMeasurable (gaussianPDFReal μ v) :=
(measurable_gaussianPDFReal μ v).stronglyMeasurable
@[fun_prop]
lemma integrable_gaussianPDFReal (μ : ℝ) (v : ℝ≥0) :
Integrable (gaussianPDFReal μ v) := by
rw [gaussianPDFReal_def]
by_cases hv : v = 0
· simp [hv]
let g : ℝ → ℝ := fun x ↦ (√(2 * π * v))⁻¹ * rexp (- x ^ 2 / (2 * v))
have hg : Integrable g := by
suffices g = fun x ↦ (√(2 * π * v))⁻¹ * rexp (- (2 * v)⁻¹ * x ^ 2) by
rw [this]
refine (integrable_exp_neg_mul_sq ?_).const_mul (√(2 * π * v))⁻¹
simp [lt_of_le_of_ne (zero_le _) (Ne.symm hv)]
ext x
simp only [g, NNReal.zero_le_coe, Real.sqrt_mul',
mul_inv_rev, NNReal.coe_mul, NNReal.coe_inv, NNReal.coe_ofNat, neg_mul, mul_eq_mul_left_iff,
Real.exp_eq_exp, mul_eq_zero, inv_eq_zero, Real.sqrt_eq_zero, NNReal.coe_eq_zero, hv,
false_or]
rw [mul_comm]
left
field_simp
exact Integrable.comp_sub_right hg μ
/-- The gaussian distribution pdf integrates to 1 when the variance is not zero. -/
lemma lintegral_gaussianPDFReal_eq_one (μ : ℝ) {v : ℝ≥0} (h : v ≠ 0) :
∫⁻ x, ENNReal.ofReal (gaussianPDFReal μ v x) = 1 := by
rw [← ENNReal.toReal_eq_one_iff]
have hfm : AEStronglyMeasurable (gaussianPDFReal μ v) volume := by fun_prop
have hf : 0 ≤ₐₛ gaussianPDFReal μ v := ae_of_all _ (gaussianPDFReal_nonneg μ v)
rw [← integral_eq_lintegral_of_nonneg_ae hf hfm]
simp only [gaussianPDFReal,
integral_const_mul]
rw [integral_sub_right_eq_self (μ := volume) (fun a ↦ rexp (-a ^ 2 / ((2 : ℝ) * v))) μ]
simp only [div_eq_inv_mul, mul_inv_rev,
mul_neg]
simp_rw [← neg_mul]
rw [neg_mul, integral_gaussian, ← Real.sqrt_inv, ← Real.sqrt_mul]
· field_simp
ring
· positivity
/-- The gaussian distribution pdf integrates to 1 when the variance is not zero. -/
lemma integral_gaussianPDFReal_eq_one (μ : ℝ) {v : ℝ≥0} (hv : v ≠ 0) :
∫ x, gaussianPDFReal μ v x = 1 := by
have h := lintegral_gaussianPDFReal_eq_one μ hv
rw [← ofReal_integral_eq_lintegral_ofReal (integrable_gaussianPDFReal _ _)
(ae_of_all _ (gaussianPDFReal_nonneg _ _)), ← ENNReal.ofReal_one] at h
rwa [← ENNReal.ofReal_eq_ofReal_iff (integral_nonneg (gaussianPDFReal_nonneg _ _)) zero_le_one]
lemma gaussianPDFReal_sub {μ : ℝ} {v : ℝ≥0} (x y : ℝ) :
gaussianPDFReal μ v (x - y) = gaussianPDFReal (μ + y) v x := by
simp only [gaussianPDFReal]
rw [sub_add_eq_sub_sub_swap]
lemma gaussianPDFReal_add {μ : ℝ} {v : ℝ≥0} (x y : ℝ) :
gaussianPDFReal μ v (x + y) = gaussianPDFReal (μ - y) v x := by
rw [sub_eq_add_neg, ← gaussianPDFReal_sub, sub_eq_add_neg, neg_neg]
lemma gaussianPDFReal_inv_mul {μ : ℝ} {v : ℝ≥0} {c : ℝ} (hc : c ≠ 0) (x : ℝ) :
gaussianPDFReal μ v (c⁻¹ * x) = |c| * gaussianPDFReal (c * μ) (⟨c^2, sq_nonneg _⟩ * v) x := by
simp only [gaussianPDFReal.eq_1, NNReal.zero_le_coe,
Real.sqrt_mul', mul_inv_rev, NNReal.coe_mul, NNReal.coe_mk]
rw [← mul_assoc]
refine congr_arg₂ _ ?_ ?_
· field_simp
rw [Real.sqrt_sq_eq_abs]
ring_nf
calc (√↑v)⁻¹ * (√2)⁻¹ * (√π)⁻¹
= (√↑v)⁻¹ * (√2)⁻¹ * (√π)⁻¹ * (|c| * |c|⁻¹) := by
rw [mul_inv_cancel₀, mul_one]
simp only [ne_eq, abs_eq_zero, hc, not_false_eq_true]
_ = (√↑v)⁻¹ * (√2)⁻¹ * (√π)⁻¹ * |c| * |c|⁻¹ := by ring
· congr 1
field_simp
congr 1
ring
lemma gaussianPDFReal_mul {μ : ℝ} {v : ℝ≥0} {c : ℝ} (hc : c ≠ 0) (x : ℝ) :
gaussianPDFReal μ v (c * x)
= |c⁻¹| * gaussianPDFReal (c⁻¹ * μ) (⟨(c^2)⁻¹, inv_nonneg.mpr (sq_nonneg _)⟩ * v) x := by
conv_lhs => rw [← inv_inv c, gaussianPDFReal_inv_mul (inv_ne_zero hc)]
simp
/-- The pdf of a Gaussian distribution on ℝ with mean `μ` and variance `v`. -/
noncomputable
def gaussianPDF (μ : ℝ) (v : ℝ≥0) (x : ℝ) : ℝ≥0∞ := ENNReal.ofReal (gaussianPDFReal μ v x)
lemma gaussianPDF_def (μ : ℝ) (v : ℝ≥0) :
gaussianPDF μ v = fun x ↦ ENNReal.ofReal (gaussianPDFReal μ v x) := rfl
@[simp]
lemma gaussianPDF_zero_var (μ : ℝ) : gaussianPDF μ 0 = 0 := by ext; simp [gaussianPDF]
@[simp]
lemma toReal_gaussianPDF {μ : ℝ} {v : ℝ≥0} (x : ℝ) :
(gaussianPDF μ v x).toReal = gaussianPDFReal μ v x := by
rw [gaussianPDF, ENNReal.toReal_ofReal (gaussianPDFReal_nonneg μ v x)]
lemma gaussianPDF_pos (μ : ℝ) {v : ℝ≥0} (hv : v ≠ 0) (x : ℝ) : 0 < gaussianPDF μ v x := by
rw [gaussianPDF, ENNReal.ofReal_pos]
exact gaussianPDFReal_pos _ _ _ hv
lemma gaussianPDF_lt_top {μ : ℝ} {v : ℝ≥0} {x : ℝ} : gaussianPDF μ v x < ∞ := by simp [gaussianPDF]
lemma gaussianPDF_ne_top {μ : ℝ} {v : ℝ≥0} {x : ℝ} : gaussianPDF μ v x ≠ ∞ := by simp [gaussianPDF]
@[simp]
lemma support_gaussianPDF {μ : ℝ} {v : ℝ≥0} (hv : v ≠ 0) :
Function.support (gaussianPDF μ v) = Set.univ := by
ext x
simp only [Set.mem_univ, iff_true]
exact (gaussianPDF_pos _ hv x).ne'
@[measurability, fun_prop]
lemma measurable_gaussianPDF (μ : ℝ) (v : ℝ≥0) : Measurable (gaussianPDF μ v) :=
(measurable_gaussianPDFReal _ _).ennreal_ofReal
@[simp]
lemma lintegral_gaussianPDF_eq_one (μ : ℝ) {v : ℝ≥0} (h : v ≠ 0) :
∫⁻ x, gaussianPDF μ v x = 1 :=
lintegral_gaussianPDFReal_eq_one μ h
end GaussianPDF
section GaussianReal
/-- A Gaussian distribution on `ℝ` with mean `μ` and variance `v`. -/
noncomputable
def gaussianReal (μ : ℝ) (v : ℝ≥0) : Measure ℝ :=
if v = 0 then Measure.dirac μ else volume.withDensity (gaussianPDF μ v)
lemma gaussianReal_of_var_ne_zero (μ : ℝ) {v : ℝ≥0} (hv : v ≠ 0) :
gaussianReal μ v = volume.withDensity (gaussianPDF μ v) := if_neg hv
@[simp]
lemma gaussianReal_zero_var (μ : ℝ) : gaussianReal μ 0 = Measure.dirac μ := if_pos rfl
instance instIsProbabilityMeasureGaussianReal (μ : ℝ) (v : ℝ≥0) :
IsProbabilityMeasure (gaussianReal μ v) where
measure_univ := by by_cases h : v = 0 <;> simp [gaussianReal_of_var_ne_zero, h]
lemma noAtoms_gaussianReal {μ : ℝ} {v : ℝ≥0} (h : v ≠ 0) : NoAtoms (gaussianReal μ v) := by
rw [gaussianReal_of_var_ne_zero _ h]
infer_instance
lemma gaussianReal_apply (μ : ℝ) {v : ℝ≥0} (hv : v ≠ 0) (s : Set ℝ) :
gaussianReal μ v s = ∫⁻ x in s, gaussianPDF μ v x := by
rw [gaussianReal_of_var_ne_zero _ hv, withDensity_apply' _ s]
lemma gaussianReal_apply_eq_integral (μ : ℝ) {v : ℝ≥0} (hv : v ≠ 0) (s : Set ℝ) :
gaussianReal μ v s = ENNReal.ofReal (∫ x in s, gaussianPDFReal μ v x) := by
rw [gaussianReal_apply _ hv s, ofReal_integral_eq_lintegral_ofReal]
· rfl
· exact (integrable_gaussianPDFReal _ _).restrict
· exact ae_of_all _ (gaussianPDFReal_nonneg _ _)
lemma gaussianReal_absolutelyContinuous (μ : ℝ) {v : ℝ≥0} (hv : v ≠ 0) :
gaussianReal μ v ≪ volume := by
rw [gaussianReal_of_var_ne_zero _ hv]
exact withDensity_absolutelyContinuous _ _
lemma gaussianReal_absolutelyContinuous' (μ : ℝ) {v : ℝ≥0} (hv : v ≠ 0) :
volume ≪ gaussianReal μ v := by
rw [gaussianReal_of_var_ne_zero _ hv]
refine withDensity_absolutelyContinuous' ?_ ?_
· exact (measurable_gaussianPDF _ _).aemeasurable
· exact ae_of_all _ (fun _ ↦ (gaussianPDF_pos _ hv _).ne')
lemma rnDeriv_gaussianReal (μ : ℝ) (v : ℝ≥0) :
∂(gaussianReal μ v)/∂volume =ₐₛ gaussianPDF μ v := by
by_cases hv : v = 0
· simp only [hv, gaussianReal_zero_var, gaussianPDF_zero_var]
refine (Measure.eq_rnDeriv measurable_zero (mutuallySingular_dirac μ volume) ?_).symm
rw [withDensity_zero, add_zero]
· rw [gaussianReal_of_var_ne_zero _ hv]
exact Measure.rnDeriv_withDensity _ (measurable_gaussianPDF μ v)
lemma integral_gaussianReal_eq_integral_smul {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E]
{μ : ℝ} {v : ℝ≥0} {f : ℝ → E} (hv : v ≠ 0) :
∫ x, f x ∂(gaussianReal μ v) = ∫ x, gaussianPDFReal μ v x • f x := by
simp [gaussianReal, hv,
integral_withDensity_eq_integral_toReal_smul (measurable_gaussianPDF _ _)
(ae_of_all _ fun _ ↦ gaussianPDF_lt_top)]
section Transformations
variable {μ : ℝ} {v : ℝ≥0}
lemma _root_.MeasurableEmbedding.gaussianReal_comap_apply (hv : v ≠ 0)
{f : ℝ → ℝ} (hf : MeasurableEmbedding f)
{f' : ℝ → ℝ} (h_deriv : ∀ x, HasDerivAt f (f' x) x) {s : Set ℝ} (hs : MeasurableSet s) :
(gaussianReal μ v).comap f s
= ENNReal.ofReal (∫ x in s, |f' x| * gaussianPDFReal μ v (f x)) := by
rw [gaussianReal_of_var_ne_zero _ hv, gaussianPDF_def]
exact hf.withDensity_ofReal_comap_apply_eq_integral_abs_deriv_mul' hs h_deriv
(ae_of_all _ (gaussianPDFReal_nonneg _ _)) (integrable_gaussianPDFReal _ _)
lemma _root_.MeasurableEquiv.gaussianReal_map_symm_apply (hv : v ≠ 0) (f : ℝ ≃ᵐ ℝ) {f' : ℝ → ℝ}
(h_deriv : ∀ x, HasDerivAt f (f' x) x) {s : Set ℝ} (hs : MeasurableSet s) :
(gaussianReal μ v).map f.symm s
= ENNReal.ofReal (∫ x in s, |f' x| * gaussianPDFReal μ v (f x)) := by
rw [gaussianReal_of_var_ne_zero _ hv, gaussianPDF_def]
exact f.withDensity_ofReal_map_symm_apply_eq_integral_abs_deriv_mul' hs h_deriv
(ae_of_all _ (gaussianPDFReal_nonneg _ _)) (integrable_gaussianPDFReal _ _)
/-- The map of a Gaussian distribution by addition of a constant is a Gaussian. -/
lemma gaussianReal_map_add_const (y : ℝ) :
(gaussianReal μ v).map (· + y) = gaussianReal (μ + y) v := by
by_cases hv : v = 0
· simp only [hv, gaussianReal_zero_var]
exact Measure.map_dirac (measurable_id'.add_const _) _
let e : ℝ ≃ᵐ ℝ := (Homeomorph.addRight y).symm.toMeasurableEquiv
have he' : ∀ x, HasDerivAt e ((fun _ ↦ 1) x) x := fun _ ↦ (hasDerivAt_id _).sub_const y
change (gaussianReal μ v).map e.symm = gaussianReal (μ + y) v
ext s' hs'
rw [MeasurableEquiv.gaussianReal_map_symm_apply hv e he' hs']
simp only [abs_one, one_mul]
rw [gaussianReal_apply_eq_integral _ hv s']
simp [e, gaussianPDFReal_sub _ y, Homeomorph.addRight, ← sub_eq_add_neg]
/-- The map of a Gaussian distribution by addition of a constant is a Gaussian. -/
lemma gaussianReal_map_const_add (y : ℝ) :
(gaussianReal μ v).map (y + ·) = gaussianReal (μ + y) v := by
simp_rw [add_comm y]
exact gaussianReal_map_add_const y
/-- The map of a Gaussian distribution by multiplication by a constant is a Gaussian. -/
lemma gaussianReal_map_const_mul (c : ℝ) :
(gaussianReal μ v).map (c * ·) = gaussianReal (c * μ) (⟨c^2, sq_nonneg _⟩ * v) := by
by_cases hv : v = 0
· simp only [hv, mul_zero, gaussianReal_zero_var]
exact Measure.map_dirac (measurable_id'.const_mul c) μ
by_cases hc : c = 0
· simp only [hc, zero_mul]
rw [Measure.map_const]
simp only [measure_univ, one_smul]
convert (gaussianReal_zero_var 0).symm
simp only [ne_eq, zero_pow, mul_eq_zero, hv, or_false, not_false_eq_true, reduceCtorEq,
NNReal.mk_zero]
let e : ℝ ≃ᵐ ℝ := (Homeomorph.mulLeft₀ c hc).symm.toMeasurableEquiv
have he' : ∀ x, HasDerivAt e ((fun _ ↦ c⁻¹) x) x := by
suffices ∀ x, HasDerivAt (fun x => c⁻¹ * x) (c⁻¹ * 1) x by rwa [mul_one] at this
exact fun _ ↦ HasDerivAt.const_mul _ (hasDerivAt_id _)
change (gaussianReal μ v).map e.symm = gaussianReal (c * μ) (⟨c^2, sq_nonneg _⟩ * v)
ext s' hs'
rw [MeasurableEquiv.gaussianReal_map_symm_apply hv e he' hs',
gaussianReal_apply_eq_integral _ _ s']
swap
· simp only [ne_eq, mul_eq_zero, hv, or_false]
rw [← NNReal.coe_inj]
simp [hc]
simp only [e, Homeomorph.mulLeft₀,
Equiv.mulLeft₀_symm_apply, Homeomorph.toMeasurableEquiv_coe, Homeomorph.homeomorph_mk_coe_symm,
gaussianPDFReal_inv_mul hc]
congr with x
suffices |c⁻¹| * |c| = 1 by rw [← mul_assoc, this, one_mul]
rw [abs_inv, inv_mul_cancel₀]
rwa [ne_eq, abs_eq_zero]
/-- The map of a Gaussian distribution by multiplication by a constant is a Gaussian. -/
lemma gaussianReal_map_mul_const (c : ℝ) :
(gaussianReal μ v).map (· * c) = gaussianReal (c * μ) (⟨c^2, sq_nonneg _⟩ * v) := by
simp_rw [mul_comm _ c]
exact gaussianReal_map_const_mul c
lemma gaussianReal_map_neg : (gaussianReal μ v).map (fun x ↦ -x) = gaussianReal (-μ) v := by
simpa using gaussianReal_map_const_mul (μ := μ) (v := v) (-1)
lemma gaussianReal_map_sub_const (y : ℝ) :
(gaussianReal μ v).map (· - y) = gaussianReal (μ - y) v := by
simp_rw [sub_eq_add_neg, gaussianReal_map_add_const]
lemma gaussianReal_map_const_sub (y : ℝ) :
(gaussianReal μ v).map (y - ·) = gaussianReal (y - μ) v := by
simp_rw [sub_eq_add_neg]
have : (fun x ↦ y + -x) = (fun x ↦ y + x) ∘ fun x ↦ -x := by ext; simp
rw [this, ← Measure.map_map (by fun_prop) (by fun_prop), gaussianReal_map_neg,
gaussianReal_map_const_add, add_comm]
variable {Ω : Type} [MeasureSpace Ω]
/-- If `X` is a real random variable with Gaussian law with mean `μ` and variance `v`, then `X + y`
has Gaussian law with mean `μ + y` and variance `v`. -/
lemma gaussianReal_add_const {X : Ω → ℝ} (hX : Measure.map X ℙ = gaussianReal μ v) (y : ℝ) :
Measure.map (fun ω ↦ X ω + y) ℙ = gaussianReal (μ + y) v := by
have hXm : AEMeasurable X := aemeasurable_of_map_neZero (by rw [hX]; infer_instance)
change Measure.map ((fun ω ↦ ω + y) ∘ X) ℙ = gaussianReal (μ + y) v
rw [← AEMeasurable.map_map_of_aemeasurable (measurable_id'.add_const _).aemeasurable hXm, hX,
gaussianReal_map_add_const y]
/-- If `X` is a real random variable with Gaussian law with mean `μ` and variance `v`, then `y + X`
has Gaussian law with mean `μ + y` and variance `v`. -/
lemma gaussianReal_const_add {X : Ω → ℝ} (hX : Measure.map X ℙ = gaussianReal μ v) (y : ℝ) :
Measure.map (fun ω ↦ y + X ω) ℙ = gaussianReal (μ + y) v := by
simp_rw [add_comm y]
exact gaussianReal_add_const hX y
/-- If `X` is a real random variable with Gaussian law with mean `μ` and variance `v`, then `c * X`
has Gaussian law with mean `c * μ` and variance `c^2 * v`. -/
lemma gaussianReal_const_mul {X : Ω → ℝ} (hX : Measure.map X ℙ = gaussianReal μ v) (c : ℝ) :
Measure.map (fun ω ↦ c * X ω) ℙ = gaussianReal (c * μ) (⟨c^2, sq_nonneg _⟩ * v) := by
have hXm : AEMeasurable X := aemeasurable_of_map_neZero (by rw [hX]; infer_instance)
change Measure.map ((fun ω ↦ c * ω) ∘ X) ℙ = gaussianReal (c * μ) (⟨c^2, sq_nonneg _⟩ * v)
rw [← AEMeasurable.map_map_of_aemeasurable (measurable_id'.const_mul c).aemeasurable hXm, hX]
exact gaussianReal_map_const_mul c
/-- If `X` is a real random variable with Gaussian law with mean `μ` and variance `v`, then `X * c`
has Gaussian law with mean `c * μ` and variance `c^2 * v`. -/
lemma gaussianReal_mul_const {X : Ω → ℝ} (hX : Measure.map X ℙ = gaussianReal μ v) (c : ℝ) :
Measure.map (fun ω ↦ X ω * c) ℙ = gaussianReal (c * μ) (⟨c^2, sq_nonneg _⟩ * v) := by
simp_rw [mul_comm _ c]
exact gaussianReal_const_mul hX c
end Transformations
section CharacteristicFunction
open Real Complex
variable {Ω : Type*} {mΩ : MeasurableSpace Ω} {p : Measure Ω} {μ : ℝ} {v : ℝ≥0} {X : Ω → ℝ}
/-- The complex moment generating function of a Gaussian distribution with mean `μ` and variance `v`
is given by `z ↦ exp (z * μ + v * z ^ 2 / 2)`. -/
theorem complexMGF_id_gaussianReal (z : ℂ) :
complexMGF id (gaussianReal μ v) z = cexp (z * μ + v * z ^ 2 / 2) := by
by_cases hv : v = 0
· simp [complexMGF, hv]
calc ∫ x, cexp (z * x) ∂gaussianReal μ v
_ = ∫ x, gaussianPDFReal μ v x * cexp (z * x) ∂ℙ := by
simp_rw [integral_gaussianReal_eq_integral_smul hv, Complex.real_smul]
_ = (√(2 * π * v))⁻¹
* ∫ x : ℝ, cexp (-(2 * v)⁻¹ * x ^ 2 + (z + μ / v) * x + -μ ^ 2 / (2 * v)) ∂ℙ := by
unfold gaussianPDFReal
push_cast
simp_rw [mul_assoc, integral_const_mul, ← Complex.exp_add]
congr with x
congr 1
ring
_ = (√(2 * π * v))⁻¹ * (π / - -(2 * v)⁻¹) ^ (1 / 2 : ℂ)
* cexp (-μ ^ 2 / (2 * v) - (z + μ / v) ^ 2 / (4 * -(2 * v)⁻¹)) := by
rw [integral_cexp_quadratic (by simpa using pos_iff_ne_zero.mpr hv), ← mul_assoc]
_ = 1 * cexp (-μ ^ 2 / (2 * v) - (z + μ / v) ^ 2 / (4 * -(2 * v)⁻¹)) := by
congr 1
field_simp [Real.sqrt_eq_rpow]
rw [Complex.ofReal_cpow (by positivity)]
push_cast
ring_nf
_ = cexp (z * μ + v * z ^ 2 / 2) := by
rw [one_mul]
congr 1
have : (v : ℂ) ≠ 0 := by simpa
field_simp
ring
/-- The complex moment generating function of a random variable with Gaussian distribution
with mean `μ` and variance `v` is given by `z ↦ exp (z * μ + v * z ^ 2 / 2)`. -/
theorem complexMGF_gaussianReal (hX : p.map X = gaussianReal μ v) (z : ℂ) :
complexMGF X p z = cexp (z * μ + v * z ^ 2 / 2) := by
have hX_meas : AEMeasurable X p := aemeasurable_of_map_neZero (by rw [hX]; infer_instance)
rw [← complexMGF_id_map hX_meas, hX, complexMGF_id_gaussianReal]
/-- The characteristic function of a Gaussian distribution with mean `μ` and variance `v`
is given by `t ↦ exp (t * μ - v * t ^ 2 / 2)`. -/
theorem charFun_gaussianReal (t : ℝ) :
charFun (gaussianReal μ v) t = cexp (t * μ * I - v * t ^ 2 / 2) := by
rw [← complexMGF_id_mul_I, complexMGF_id_gaussianReal]
congr
simp only [mul_pow, I_sq, mul_neg, mul_one, sub_eq_add_neg]
ring_nf
/-- The moment generating function of a random variable with Gaussian distribution
with mean `μ` and variance `v` is given by `t ↦ exp (μ * t + v * t ^ 2 / 2)`. -/
theorem mgf_gaussianReal (hX : p.map X = gaussianReal μ v) (t : ℝ) :
mgf X p t = rexp (μ * t + v * t ^ 2 / 2) := by
suffices (mgf X p t : ℂ) = rexp (μ * t + ↑v * t ^ 2 / 2) from mod_cast this
have hX_meas : AEMeasurable X p := aemeasurable_of_map_neZero (by rw [hX]; infer_instance)
rw [← mgf_id_map hX_meas, ← complexMGF_ofReal, hX, complexMGF_id_gaussianReal, mul_comm μ]
norm_cast
theorem mgf_fun_id_gaussianReal :
mgf (fun x ↦ x) (gaussianReal μ v) = fun t ↦ rexp (μ * t + v * t ^ 2 / 2) := by
ext t
rw [mgf_gaussianReal]
simp
theorem mgf_id_gaussianReal : mgf id (gaussianReal μ v) = fun t ↦ rexp (μ * t + v * t ^ 2 / 2) :=
mgf_fun_id_gaussianReal
/-- The cumulant generating function of a random variable with Gaussian distribution
with mean `μ` and variance `v` is given by `t ↦ μ * t + v * t ^ 2 / 2`. -/
theorem cgf_gaussianReal (hX : p.map X = gaussianReal μ v) (t : ℝ) :
cgf X p t = μ * t + v * t ^ 2 / 2 := by
rw [cgf, mgf_gaussianReal hX t, Real.log_exp]
lemma integrable_exp_mul_gaussianReal (t : ℝ) :
Integrable (fun x ↦ rexp (t * x)) (gaussianReal μ v) := by
rw [← mgf_pos_iff, mgf_gaussianReal (μ := μ) (v := v) (by simp)]
exact Real.exp_pos _
@[simp]
lemma integrableExpSet_id_gaussianReal : integrableExpSet id (gaussianReal μ v) = Set.univ := by
ext
simpa [integrableExpSet] using integrable_exp_mul_gaussianReal _
@[simp]
lemma integrableExpSet_fun_id_gaussianReal :
integrableExpSet (fun x ↦ x) (gaussianReal μ v) = Set.univ :=
integrableExpSet_id_gaussianReal
end CharacteristicFunction
section Moments
variable {μ : ℝ} {v : ℝ≥0}
/-- The mean of a real Gaussian distribution `gaussianReal μ v` is its mean parameter `μ`. -/
@[simp]
lemma integral_id_gaussianReal : ∫ x, x ∂gaussianReal μ v = μ := by
rw [← deriv_mgf_zero (by simp), mgf_fun_id_gaussianReal, _root_.deriv_exp (by fun_prop)]
simp only [mul_zero, ne_eq, OfNat.ofNat_ne_zero, not_false_eq_true, zero_pow, zero_div,
add_zero, Real.exp_zero, one_mul]
rw [deriv_fun_add (by fun_prop) (by fun_prop), deriv_fun_mul (by fun_prop) (by fun_prop)]
simp
/-- The variance of a real Gaussian distribution `gaussianReal μ v` is
its variance parameter `v`. -/
@[simp]
lemma variance_fun_id_gaussianReal : Var[fun x ↦ x; gaussianReal μ v] = v := by
rw [variance_eq_integral measurable_id'.aemeasurable]
simp only [integral_id_gaussianReal]
calc ∫ ω, (ω - μ) ^ 2 ∂gaussianReal μ v
_ = ∫ ω, ω ^ 2 ∂(gaussianReal μ v).map (fun x ↦ x - μ) := by
rw [integral_map (by fun_prop) (by fun_prop)]
_ = ∫ ω, ω ^ 2 ∂(gaussianReal 0 v) := by simp [gaussianReal_map_sub_const]
_ = iteratedDeriv 2 (mgf (fun x ↦ x) (gaussianReal 0 v)) 0 := by
rw [iteratedDeriv_mgf_zero] <;> simp
_ = v := by
rw [mgf_fun_id_gaussianReal, iteratedDeriv_succ, iteratedDeriv_one]
simp only [zero_mul, zero_add]
have : deriv (fun t ↦ rexp (v * t ^ 2 / 2)) = fun t ↦ v * t * rexp (v * t ^ 2 / 2) := by
ext t
rw [_root_.deriv_exp (by fun_prop)]
simp only [deriv_div_const, differentiableAt_const, differentiableAt_fun_id, Nat.cast_ofNat,
DifferentiableAt.fun_pow, deriv_fun_mul, deriv_const', zero_mul, deriv_fun_pow,
Nat.add_one_sub_one, pow_one, deriv_id'', mul_one, zero_add]
ring
rw [this, deriv_fun_mul (by fun_prop) (by fun_prop), deriv_fun_mul (by fun_prop) (by fun_prop)]
simp
/-- The variance of a real Gaussian distribution `gaussianReal μ v` is
its variance parameter `v`. -/
@[simp]
lemma variance_id_gaussianReal : Var[id; gaussianReal μ v] = v :=
variance_fun_id_gaussianReal
/-- All the moments of a real Gaussian distribution are finite. That is, the identity is in Lp for
all finite `p`. -/
lemma memLp_id_gaussianReal (p : ℝ≥0) : MemLp id p (gaussianReal μ v) :=
memLp_of_mem_interior_integrableExpSet (by simp) p
/-- All the moments of a real Gaussian distribution are finite. That is, the identity is in Lp for
all finite `p`. -/
lemma memLp_id_gaussianReal' (p : ℝ≥0∞) (hp : p ≠ ∞) : MemLp id p (gaussianReal μ v) := by
lift p to ℝ≥0 using hp
exact memLp_id_gaussianReal p
end Moments
section LinearMap
variable {μ : ℝ} {v : ℝ≥0}
lemma gaussianReal_map_linearMap (L : ℝ →ₗ[ℝ] ℝ) :
(gaussianReal μ v).map L = gaussianReal (L μ) ((L 1 ^ 2).toNNReal * v) := by
have : (L : ℝ → ℝ) = fun x ↦ L 1 * x := by
ext x
have : x = x • 1 := by simp
conv_lhs => rw [this, L.map_smul, smul_eq_mul, mul_comm]
rw [this, gaussianReal_map_const_mul]
congr
simp only [mul_one, left_eq_sup]
positivity
lemma gaussianReal_map_continuousLinearMap (L : ℝ →L[ℝ] ℝ) :
(gaussianReal μ v).map L = gaussianReal (L μ) ((L 1 ^ 2).toNNReal * v) :=
gaussianReal_map_linearMap L
@[simp]
lemma integral_linearMap_gaussianReal (L : ℝ →ₗ[ℝ] ℝ) :
∫ x, L x ∂(gaussianReal μ v) = L μ := by
have : ∫ x, L x ∂(gaussianReal μ v) = ∫ x, x ∂((gaussianReal μ v).map L) := by
rw [integral_map (φ := L) (by fun_prop) (by fun_prop)]
simp [this, gaussianReal_map_linearMap]
@[simp]
lemma integral_continuousLinearMap_gaussianReal (L : ℝ →L[ℝ] ℝ) :
∫ x, L x ∂(gaussianReal μ v) = L μ := integral_linearMap_gaussianReal L
@[simp]
lemma variance_linearMap_gaussianReal (L : ℝ →ₗ[ℝ] ℝ) :
Var[L; gaussianReal μ v] = (L 1 ^ 2).toNNReal * v := by
rw [← variance_id_map, gaussianReal_map_linearMap, variance_id_gaussianReal]
· simp only [NNReal.coe_mul, Real.coe_toNNReal']
· fun_prop
@[simp]
lemma variance_continuousLinearMap_gaussianReal (L : ℝ →L[ℝ] ℝ) :
Var[L; gaussianReal μ v] = (L 1 ^ 2).toNNReal * v :=
variance_linearMap_gaussianReal L
end LinearMap
/-- The convolution of two real Gaussian distributions with means `m₁, m₂` and variances `v₁, v₂`
is a real Gaussian distribution with mean `m₁ + m₂` and variance `v₁ + v₂`. -/
lemma gaussianReal_conv_gaussianReal {m₁ m₂ : ℝ} {v₁ v₂ : ℝ≥0} :
(gaussianReal m₁ v₁) ∗ (gaussianReal m₂ v₂) = gaussianReal (m₁ + m₂) (v₁ + v₂) := by
refine Measure.ext_of_charFun ?_
ext t
simp_rw [charFun_conv, charFun_gaussianReal]
rw [← Complex.exp_add]
simp only [Complex.ofReal_add, NNReal.coe_add]
ring_nf
/- The sum of two real Gaussian variables with means `m₁, m₂` and variances `v₁, v₂` is a real
Gaussian distribution with mean `m₁ + m₂` and variance `v_1 + v_2`. -/
lemma gaussianReal_add_gaussianReal_of_indepFun {Ω} {mΩ : MeasurableSpace Ω} {P : Measure Ω}
{m₁ m₂ : ℝ} {v₁ v₂ : ℝ≥0} {X Y : Ω → ℝ} (hXY : IndepFun X Y P)
(hX : P.map X = gaussianReal m₁ v₁) (hY : P.map Y = gaussianReal m₂ v₂) :
P.map (X + Y) = gaussianReal (m₁ + m₂) (v₁ + v₂) := by
rw [hXY.map_add_eq_map_conv_map₀', hX, hY, gaussianReal_conv_gaussianReal]
· apply AEMeasurable.of_map_ne_zero; simp [NeZero.ne, hX]
· apply AEMeasurable.of_map_ne_zero; simp [NeZero.ne, hY]
· rw [hX]; apply IsFiniteMeasure.toSigmaFinite
· rw [hY]; apply IsFiniteMeasure.toSigmaFinite
end GaussianReal
end ProbabilityTheory
|
Pi.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.LinearAlgebra.Finsupp.LSum
import Mathlib.LinearAlgebra.Pi
/-!
# Properties of the module `α →₀ M`
* `Finsupp.linearEquivFunOnFinite`: `α →₀ β` and `a → β` are equivalent if `α` is finite
## Tags
function with finite support, module, linear algebra
-/
noncomputable section
open Set LinearMap Submodule
namespace Finsupp
section LinearEquiv.finsuppUnique
variable (R : Type*) {S : Type*} (M : Type*)
variable [AddCommMonoid M] [Semiring R] [Module R M]
variable (α : Type*) [Unique α]
/-- If `α` has a unique term, then the type of finitely supported functions `α →₀ M` is
`R`-linearly equivalent to `M`. -/
noncomputable def LinearEquiv.finsuppUnique : (α →₀ M) ≃ₗ[R] M :=
{ Finsupp.equivFunOnFinite.trans (Equiv.funUnique α M) with
map_add' := fun _ _ => rfl
map_smul' := fun _ _ => rfl }
variable {R M}
@[simp]
theorem LinearEquiv.finsuppUnique_apply (f : α →₀ M) :
LinearEquiv.finsuppUnique R M α f = f default :=
rfl
variable {α}
@[simp]
theorem LinearEquiv.finsuppUnique_symm_apply (m : M) :
(LinearEquiv.finsuppUnique R M α).symm m = Finsupp.single default m := by
ext; simp [LinearEquiv.finsuppUnique, Equiv.funUnique, single, Pi.single,
equivFunOnFinite, Function.update]
end LinearEquiv.finsuppUnique
variable {α : Type*} {M : Type*} {N : Type*} {P : Type*} {R : Type*} {S : Type*}
variable [Semiring R] [Semiring S] [AddCommMonoid M] [Module R M]
variable [AddCommMonoid N] [Module R N]
variable [AddCommMonoid P] [Module R P]
/-- Forget that a function is finitely supported.
This is the linear version of `Finsupp.toFun`. -/
@[simps]
def lcoeFun : (α →₀ M) →ₗ[R] α → M where
toFun := (⇑)
map_add' x y := by
ext
simp
map_smul' x y := by
ext
simp
end Finsupp
variable {R : Type*} {M : Type*} {N : Type*}
variable [Semiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N]
open Finsupp
namespace LinearMap
variable {α : Type*}
open Finsupp Function
-- See also `LinearMap.splittingOfFinsuppSurjective`
/-- A surjective linear map to functions on a finite type has a splitting. -/
def splittingOfFunOnFintypeSurjective [Finite α] (f : M →ₗ[R] α → R) (s : Surjective f) :
(α → R) →ₗ[R] M :=
(Finsupp.lift _ _ _ fun x : α => (s (Finsupp.single x 1)).choose).comp
(linearEquivFunOnFinite R R α).symm.toLinearMap
theorem splittingOfFunOnFintypeSurjective_splits [Finite α] (f : M →ₗ[R] α → R)
(s : Surjective f) : f.comp (splittingOfFunOnFintypeSurjective f s) = LinearMap.id := by
classical
ext x y
dsimp [splittingOfFunOnFintypeSurjective]
rw [linearEquivFunOnFinite_symm_single, Finsupp.sum_single_index, one_smul,
(s (Finsupp.single x 1)).choose_spec, Finsupp.single_eq_pi_single]
rw [zero_smul]
theorem leftInverse_splittingOfFunOnFintypeSurjective [Finite α] (f : M →ₗ[R] α → R)
(s : Surjective f) : LeftInverse f (splittingOfFunOnFintypeSurjective f s) := fun g =>
LinearMap.congr_fun (splittingOfFunOnFintypeSurjective_splits f s) g
theorem splittingOfFunOnFintypeSurjective_injective [Finite α] (f : M →ₗ[R] α → R)
(s : Surjective f) : Injective (splittingOfFunOnFintypeSurjective f s) :=
(leftInverse_splittingOfFunOnFintypeSurjective f s).injective
end LinearMap
namespace Finsupp
variable {α : Type*}
/-- Given a family `Sᵢ` of `R`-submodules of `M` indexed by a type `α`, this is the `R`-submodule
of `α →₀ M` of functions `f` such that `f i ∈ Sᵢ` for all `i : α`. -/
def submodule (S : α → Submodule R M) : Submodule R (α →₀ M) where
carrier := { x | ∀ i, x i ∈ S i }
add_mem' hx hy i := (S i).add_mem (hx i) (hy i)
zero_mem' i := (S i).zero_mem
smul_mem' r _ hx i := (S i).smul_mem r (hx i)
@[simp]
lemma mem_submodule_iff (S : α → Submodule R M) (x : α →₀ M) :
x ∈ submodule S ↔ ∀ i, x i ∈ S i := by
rfl
theorem ker_mapRange (f : M →ₗ[R] N) (I : Type*) :
LinearMap.ker (mapRange.linearMap (α := I) f) = submodule (fun _ => LinearMap.ker f) := by
ext x
simp [Finsupp.ext_iff]
theorem range_mapRange_linearMap (f : M →ₗ[R] N) (hf : LinearMap.ker f = ⊥) (I : Type*) :
LinearMap.range (mapRange.linearMap (α := I) f) = submodule (fun _ => LinearMap.range f) := by
ext x
constructor
· rintro ⟨y, hy⟩
simp [← hy]
· intro hx
choose y hy using hx
refine ⟨⟨x.support, y, fun i => ?_⟩, by ext; simp_all⟩
constructor
<;> contrapose!
<;> simp_all (config := {contextual := true}) [← hy, map_zero, LinearMap.ker_eq_bot'.1 hf]
end Finsupp
|
RightExactness.lean
|
/-
Copyright (c) 2023 Antoine Chambert-Loir. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Antoine Chambert-Loir
-/
import Mathlib.Algebra.Exact
import Mathlib.RingTheory.Ideal.Maps
import Mathlib.RingTheory.Ideal.Quotient.Defs
import Mathlib.RingTheory.TensorProduct.Basic
/-! # Right-exactness properties of tensor product
## Modules
* `LinearMap.rTensor_surjective` asserts that when one tensors
a surjective map on the right, one still gets a surjective linear map.
More generally, `LinearMap.rTensor_range` computes the range of
`LinearMap.rTensor`
* `LinearMap.lTensor_surjective` asserts that when one tensors
a surjective map on the left, one still gets a surjective linear map.
More generally, `LinearMap.lTensor_range` computes the range of
`LinearMap.lTensor`
* `TensorProduct.rTensor_exact` says that when one tensors a short exact
sequence on the right, one still gets a short exact sequence
(right-exactness of `TensorProduct.rTensor`),
and `rTensor.equiv` gives the LinearEquiv that follows from this
combined with `LinearMap.rTensor_surjective`.
* `TensorProduct.lTensor_exact` says that when one tensors a short exact
sequence on the left, one still gets a short exact sequence
(right-exactness of `TensorProduct.rTensor`)
and `lTensor.equiv` gives the LinearEquiv that follows from this
combined with `LinearMap.lTensor_surjective`.
* For `N : Submodule R M`, `LinearMap.exact_subtype_mkQ N` says that
the inclusion of the submodule and the quotient map form an exact pair,
and `lTensor_mkQ` compute `ker (lTensor Q (N.mkQ))` and similarly for `rTensor_mkQ`
* `TensorProduct.map_ker` computes the kernel of `TensorProduct.map f g'`
in the presence of two short exact sequences.
The proofs are those of [bourbaki1989] (chap. 2, §3, n°6)
## Algebras
In the case of a tensor product of algebras, these results can be particularized
to compute some kernels.
* `Algebra.TensorProduct.ker_map` computes the kernel of `Algebra.TensorProduct.map f g`
* `Algebra.TensorProduct.lTensor_ker` and `Algebra.TensorProduct.rTensor_ker`
compute the kernels of `Algebra.TensorProduct.map f id` and `Algebra.TensorProduct.map id g`
## Note on implementation
* All kernels are computed by applying the first isomorphism theorem and
establishing some isomorphisms.
* The proofs are essentially done twice,
once for `lTensor` and then for `rTensor`.
It is possible to apply `TensorProduct.flip` to deduce one of them
from the other.
However, this approach will lead to different isomorphisms,
and it is not quicker.
* The proofs of `Ideal.map_includeLeft_eq` and `Ideal.map_includeRight_eq`
could be easier if `I ⊗[R] B` was naturally an `A ⊗[R] B` module,
and the map to `A ⊗[R] B` was known to be linear.
This depends on the B-module structure on a tensor product
whose use rapidly conflicts with everything…
## TODO
* Treat the noncommutative case
* Treat the case of modules over semirings
(For a possible definition of an exact sequence of commutative semigroups, see
[Grillet-1969b], Pierre-Antoine Grillet,
*The tensor product of commutative semigroups*,
Trans. Amer. Math. Soc. 138 (1969), 281-293, doi:10.1090/S0002-9947-1969-0237688-1 .)
-/
assert_not_exists Cardinal
section Modules
open TensorProduct LinearMap
section Semiring
variable {R : Type*} [CommSemiring R] {M N P Q : Type*}
[AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] [AddCommMonoid Q]
[Module R M] [Module R N] [Module R P] [Module R Q]
{f : M →ₗ[R] N} (g : N →ₗ[R] P)
lemma le_comap_range_lTensor (q : Q) :
LinearMap.range g ≤ (LinearMap.range (lTensor Q g)).comap (TensorProduct.mk R Q P q) := by
rintro x ⟨n, rfl⟩
exact ⟨q ⊗ₜ[R] n, rfl⟩
lemma le_comap_range_rTensor (q : Q) :
LinearMap.range g ≤ (LinearMap.range (rTensor Q g)).comap
((TensorProduct.mk R P Q).flip q) := by
rintro x ⟨n, rfl⟩
exact ⟨n ⊗ₜ[R] q, rfl⟩
variable (Q) {g}
/-- If `g` is surjective, then `lTensor Q g` is surjective -/
theorem LinearMap.lTensor_surjective (hg : Function.Surjective g) :
Function.Surjective (lTensor Q g) := by
intro z
induction z with
| zero => exact ⟨0, map_zero _⟩
| tmul q p =>
obtain ⟨n, rfl⟩ := hg p
exact ⟨q ⊗ₜ[R] n, rfl⟩
| add x y hx hy =>
obtain ⟨x, rfl⟩ := hx
obtain ⟨y, rfl⟩ := hy
exact ⟨x + y, map_add _ _ _⟩
theorem LinearMap.lTensor_range :
range (lTensor Q g) =
range (lTensor Q (Submodule.subtype (range g))) := by
have : g = (Submodule.subtype _).comp g.rangeRestrict := rfl
nth_rewrite 1 [this]
rw [lTensor_comp]
apply range_comp_of_range_eq_top
rw [range_eq_top]
apply lTensor_surjective
rw [← range_eq_top, range_rangeRestrict]
/-- If `g` is surjective, then `rTensor Q g` is surjective -/
theorem LinearMap.rTensor_surjective (hg : Function.Surjective g) :
Function.Surjective (rTensor Q g) := by
intro z
induction z with
| zero => exact ⟨0, map_zero _⟩
| tmul p q =>
obtain ⟨n, rfl⟩ := hg p
exact ⟨n ⊗ₜ[R] q, rfl⟩
| add x y hx hy =>
obtain ⟨x, rfl⟩ := hx
obtain ⟨y, rfl⟩ := hy
exact ⟨x + y, map_add _ _ _⟩
theorem LinearMap.rTensor_range :
range (rTensor Q g) =
range (rTensor Q (Submodule.subtype (range g))) := by
have : g = (Submodule.subtype _).comp g.rangeRestrict := rfl
nth_rewrite 1 [this]
rw [rTensor_comp]
apply range_comp_of_range_eq_top
rw [range_eq_top]
apply rTensor_surjective
rw [← range_eq_top, range_rangeRestrict]
lemma LinearMap.rTensor_exact_iff_lTensor_exact :
Function.Exact (f.rTensor Q) (g.rTensor Q) ↔
Function.Exact (f.lTensor Q) (g.lTensor Q) :=
Function.Exact.iff_of_ladder_linearEquiv (e₁ := TensorProduct.comm _ _ _)
(e₂ := TensorProduct.comm _ _ _) (e₃ := TensorProduct.comm _ _ _)
(by ext; simp) (by ext; simp)
variable (hg : Function.Surjective g)
{N' P' : Type*} [AddCommMonoid N'] [AddCommMonoid P'] [Module R N'] [Module R P']
{g' : N' →ₗ[R] P'} (hg' : Function.Surjective g')
include hg hg' in
theorem TensorProduct.map_surjective : Function.Surjective (TensorProduct.map g g') := by
rw [← lTensor_comp_rTensor, coe_comp]
exact Function.Surjective.comp (lTensor_surjective _ hg') (rTensor_surjective _ hg)
end Semiring
variable {R M N P : Type*} [CommRing R]
[AddCommGroup M] [AddCommGroup N] [AddCommGroup P]
[Module R M] [Module R N] [Module R P]
open Function
variable {f : M →ₗ[R] N} {g : N →ₗ[R] P}
(Q : Type*) [AddCommGroup Q] [Module R Q]
(hfg : Exact f g) (hg : Function.Surjective g)
/-- The direct map in `lTensor.equiv` -/
noncomputable def lTensor.toFun (hfg : Exact f g) :
Q ⊗[R] N ⧸ LinearMap.range (lTensor Q f) →ₗ[R] Q ⊗[R] P :=
Submodule.liftQ _ (lTensor Q g) <| by
rw [LinearMap.range_le_iff_comap, ← LinearMap.ker_comp,
← lTensor_comp, hfg.linearMap_comp_eq_zero, lTensor_zero, ker_zero]
/-- The inverse map in `lTensor.equiv_of_rightInverse` (computably, given a right inverse) -/
noncomputable def lTensor.inverse_of_rightInverse {h : P → N} (hfg : Exact f g)
(hgh : Function.RightInverse h g) :
Q ⊗[R] P →ₗ[R] Q ⊗[R] N ⧸ LinearMap.range (lTensor Q f) :=
TensorProduct.lift <| LinearMap.flip <| {
toFun := fun p ↦ Submodule.mkQ _ ∘ₗ ((TensorProduct.mk R _ _).flip (h p))
map_add' := fun p p' => LinearMap.ext fun q => (Submodule.Quotient.eq _).mpr <| by
change q ⊗ₜ[R] (h (p + p')) - (q ⊗ₜ[R] (h p) + q ⊗ₜ[R] (h p')) ∈ range (lTensor Q f)
rw [← TensorProduct.tmul_add, ← TensorProduct.tmul_sub]
apply le_comap_range_lTensor f
rw [exact_iff] at hfg
simp only [← hfg, mem_ker, map_sub, map_add, hgh _, sub_self]
map_smul' := fun r p => LinearMap.ext fun q => (Submodule.Quotient.eq _).mpr <| by
change q ⊗ₜ[R] (h (r • p)) - r • q ⊗ₜ[R] (h p) ∈ range (lTensor Q f)
rw [← TensorProduct.tmul_smul, ← TensorProduct.tmul_sub]
apply le_comap_range_lTensor f
rw [exact_iff] at hfg
simp only [← hfg, mem_ker, map_sub, map_smul, hgh _, sub_self] }
lemma lTensor.inverse_of_rightInverse_apply
{h : P → N} (hgh : Function.RightInverse h g) (y : Q ⊗[R] N) :
(lTensor.inverse_of_rightInverse Q hfg hgh) ((lTensor Q g) y) =
Submodule.Quotient.mk (p := (LinearMap.range (lTensor Q f))) y := by
simp only [← LinearMap.comp_apply, ← Submodule.mkQ_apply]
rw [exact_iff] at hfg
apply LinearMap.congr_fun
apply TensorProduct.ext'
intro n q
simp? [lTensor.inverse_of_rightInverse] says
simp only [inverse_of_rightInverse, coe_comp, Function.comp_apply, lTensor_tmul,
lift.tmul, flip_apply, coe_mk, AddHom.coe_mk, mk_apply, Submodule.mkQ_apply]
rw [Submodule.Quotient.eq, ← TensorProduct.tmul_sub]
apply le_comap_range_lTensor f n
rw [← hfg, mem_ker, map_sub, sub_eq_zero, hgh]
lemma lTensor.inverse_of_rightInverse_comp_lTensor
{h : P → N} (hgh : Function.RightInverse h g) :
(lTensor.inverse_of_rightInverse Q hfg hgh).comp (lTensor Q g) =
Submodule.mkQ (p := LinearMap.range (lTensor Q f)) := by
rw [LinearMap.ext_iff]
intro y
simp only [coe_comp, Function.comp_apply, Submodule.mkQ_apply,
lTensor.inverse_of_rightInverse_apply]
/-- The inverse map in `lTensor.equiv` -/
noncomputable
def lTensor.inverse :
Q ⊗[R] P →ₗ[R] Q ⊗[R] N ⧸ LinearMap.range (lTensor Q f) :=
lTensor.inverse_of_rightInverse Q hfg (Function.rightInverse_surjInv hg)
lemma lTensor.inverse_apply (y : Q ⊗[R] N) :
(lTensor.inverse Q hfg hg) ((lTensor Q g) y) =
Submodule.Quotient.mk (p := (LinearMap.range (lTensor Q f))) y := by
rw [lTensor.inverse, lTensor.inverse_of_rightInverse_apply]
lemma lTensor.inverse_comp_lTensor :
(lTensor.inverse Q hfg hg).comp (lTensor Q g) =
Submodule.mkQ (p := LinearMap.range (lTensor Q f)) := by
rw [lTensor.inverse, lTensor.inverse_of_rightInverse_comp_lTensor]
/-- For a surjective `f : N →ₗ[R] P`,
the natural equivalence between `Q ⊗ N ⧸ (image of ker f)` to `Q ⊗ P`
(computably, given a right inverse) -/
noncomputable
def lTensor.linearEquiv_of_rightInverse {h : P → N} (hgh : Function.RightInverse h g) :
((Q ⊗[R] N) ⧸ (LinearMap.range (lTensor Q f))) ≃ₗ[R] (Q ⊗[R] P) := {
toLinearMap := lTensor.toFun Q hfg
invFun := lTensor.inverse_of_rightInverse Q hfg hgh
left_inv := fun y ↦ by
simp only [lTensor.toFun, AddHom.toFun_eq_coe, coe_toAddHom]
obtain ⟨y, rfl⟩ := Submodule.mkQ_surjective _ y
simp only [Submodule.mkQ_apply, Submodule.liftQ_apply, lTensor.inverse_of_rightInverse_apply]
right_inv := fun z ↦ by
simp only [AddHom.toFun_eq_coe, coe_toAddHom]
obtain ⟨y, rfl⟩ := lTensor_surjective Q (hgh.surjective) z
rw [lTensor.inverse_of_rightInverse_apply]
simp only [lTensor.toFun, Submodule.liftQ_apply] }
/-- For a surjective `f : N →ₗ[R] P`,
the natural equivalence between `Q ⊗ N ⧸ (image of ker f)` to `Q ⊗ P` -/
noncomputable def lTensor.equiv :
((Q ⊗[R] N) ⧸ (LinearMap.range (lTensor Q f))) ≃ₗ[R] (Q ⊗[R] P) :=
lTensor.linearEquiv_of_rightInverse Q hfg (Function.rightInverse_surjInv hg)
include hfg hg in
/-- Tensoring an exact pair on the left gives an exact pair -/
theorem lTensor_exact : Exact (lTensor Q f) (lTensor Q g) := by
rw [exact_iff, ← Submodule.ker_mkQ (p := range (lTensor Q f)),
← lTensor.inverse_comp_lTensor Q hfg hg]
apply symm
apply LinearMap.ker_comp_of_ker_eq_bot
rw [LinearMap.ker_eq_bot]
exact (lTensor.equiv Q hfg hg).symm.injective
/-- Right-exactness of tensor product -/
lemma lTensor_mkQ (N : Submodule R M) :
ker (lTensor Q (N.mkQ)) = range (lTensor Q N.subtype) := by
rw [← exact_iff]
exact lTensor_exact Q (LinearMap.exact_subtype_mkQ N) (Submodule.mkQ_surjective N)
/-- The direct map in `rTensor.equiv` -/
noncomputable def rTensor.toFun (hfg : Exact f g) :
N ⊗[R] Q ⧸ range (rTensor Q f) →ₗ[R] P ⊗[R] Q :=
Submodule.liftQ _ (rTensor Q g) <| by
rw [range_le_iff_comap, ← ker_comp, ← rTensor_comp,
hfg.linearMap_comp_eq_zero, rTensor_zero, ker_zero]
/-- The inverse map in `rTensor.equiv_of_rightInverse` (computably, given a right inverse) -/
noncomputable def rTensor.inverse_of_rightInverse {h : P → N} (hfg : Exact f g)
(hgh : Function.RightInverse h g) :
P ⊗[R] Q →ₗ[R] N ⊗[R] Q ⧸ LinearMap.range (rTensor Q f) :=
TensorProduct.lift {
toFun := fun p ↦ Submodule.mkQ _ ∘ₗ TensorProduct.mk R _ _ (h p)
map_add' := fun p p' => LinearMap.ext fun q => (Submodule.Quotient.eq _).mpr <| by
change h (p + p') ⊗ₜ[R] q - (h p ⊗ₜ[R] q + h p' ⊗ₜ[R] q) ∈ range (rTensor Q f)
rw [← TensorProduct.add_tmul, ← TensorProduct.sub_tmul]
apply le_comap_range_rTensor f
rw [exact_iff] at hfg
simp only [← hfg, mem_ker, map_sub, map_add, hgh _, sub_self]
map_smul' := fun r p => LinearMap.ext fun q => (Submodule.Quotient.eq _).mpr <| by
change h (r • p) ⊗ₜ[R] q - r • h p ⊗ₜ[R] q ∈ range (rTensor Q f)
rw [TensorProduct.smul_tmul', ← TensorProduct.sub_tmul]
apply le_comap_range_rTensor f
rw [exact_iff] at hfg
simp only [← hfg, mem_ker, map_sub, map_smul, hgh _, sub_self] }
lemma rTensor.inverse_of_rightInverse_apply
{h : P → N} (hgh : Function.RightInverse h g) (y : N ⊗[R] Q) :
(rTensor.inverse_of_rightInverse Q hfg hgh) ((rTensor Q g) y) =
Submodule.Quotient.mk (p := LinearMap.range (rTensor Q f)) y := by
simp only [← LinearMap.comp_apply, ← Submodule.mkQ_apply]
rw [exact_iff] at hfg
apply LinearMap.congr_fun
apply TensorProduct.ext'
intro n q
simp? [rTensor.inverse_of_rightInverse] says
simp only [inverse_of_rightInverse, coe_comp, Function.comp_apply, rTensor_tmul,
lift.tmul, coe_mk, AddHom.coe_mk, mk_apply, Submodule.mkQ_apply]
rw [Submodule.Quotient.eq, ← TensorProduct.sub_tmul]
apply le_comap_range_rTensor f
rw [← hfg, mem_ker, map_sub, sub_eq_zero, hgh]
lemma rTensor.inverse_of_rightInverse_comp_rTensor
{h : P → N} (hgh : Function.RightInverse h g) :
(rTensor.inverse_of_rightInverse Q hfg hgh).comp (rTensor Q g) =
Submodule.mkQ (p := LinearMap.range (rTensor Q f)) := by
rw [LinearMap.ext_iff]
intro y
simp only [coe_comp, Function.comp_apply, Submodule.mkQ_apply,
rTensor.inverse_of_rightInverse_apply]
/-- The inverse map in `rTensor.equiv` -/
noncomputable
def rTensor.inverse :
P ⊗[R] Q →ₗ[R] N ⊗[R] Q ⧸ LinearMap.range (rTensor Q f) :=
rTensor.inverse_of_rightInverse Q hfg (Function.rightInverse_surjInv hg)
lemma rTensor.inverse_apply (y : N ⊗[R] Q) :
(rTensor.inverse Q hfg hg) ((rTensor Q g) y) =
Submodule.Quotient.mk (p := LinearMap.range (rTensor Q f)) y := by
rw [rTensor.inverse, rTensor.inverse_of_rightInverse_apply]
lemma rTensor.inverse_comp_rTensor :
(rTensor.inverse Q hfg hg).comp (rTensor Q g) =
Submodule.mkQ (p := LinearMap.range (rTensor Q f)) := by
rw [rTensor.inverse, rTensor.inverse_of_rightInverse_comp_rTensor]
/-- For a surjective `f : N →ₗ[R] P`,
the natural equivalence between `N ⊗[R] Q ⧸ (range (rTensor Q f))` and `P ⊗[R] Q`
(computably, given a right inverse) -/
noncomputable
def rTensor.linearEquiv_of_rightInverse {h : P → N} (hgh : Function.RightInverse h g) :
((N ⊗[R] Q) ⧸ (range (rTensor Q f))) ≃ₗ[R] (P ⊗[R] Q) := {
toLinearMap := rTensor.toFun Q hfg
invFun := rTensor.inverse_of_rightInverse Q hfg hgh
left_inv := fun y ↦ by
simp only [rTensor.toFun, AddHom.toFun_eq_coe, coe_toAddHom]
obtain ⟨y, rfl⟩ := Submodule.mkQ_surjective _ y
simp only [Submodule.mkQ_apply, Submodule.liftQ_apply, rTensor.inverse_of_rightInverse_apply]
right_inv := fun z ↦ by
simp only [AddHom.toFun_eq_coe, coe_toAddHom]
obtain ⟨y, rfl⟩ := rTensor_surjective Q hgh.surjective z
rw [rTensor.inverse_of_rightInverse_apply]
simp only [rTensor.toFun, Submodule.liftQ_apply] }
/-- For a surjective `f : N →ₗ[R] P`,
the natural equivalence between `N ⊗[R] Q ⧸ (range (rTensor Q f))` and `P ⊗[R] Q` -/
noncomputable def rTensor.equiv :
((N ⊗[R] Q) ⧸ (LinearMap.range (rTensor Q f))) ≃ₗ[R] (P ⊗[R] Q) :=
rTensor.linearEquiv_of_rightInverse Q hfg (Function.rightInverse_surjInv hg)
include hfg hg in
/-- Tensoring an exact pair on the right gives an exact pair -/
theorem rTensor_exact : Exact (rTensor Q f) (rTensor Q g) := by
rw [rTensor_exact_iff_lTensor_exact]
exact lTensor_exact Q hfg hg
/-- Right-exactness of tensor product (`rTensor`) -/
lemma rTensor_mkQ (N : Submodule R M) :
ker (rTensor Q N.mkQ) = range (rTensor Q N.subtype) := by
rw [← exact_iff]
exact rTensor_exact Q (LinearMap.exact_subtype_mkQ N) (Submodule.mkQ_surjective N)
open Submodule LinearEquiv in
lemma LinearMap.ker_tensorProductMk {I : Ideal R} :
ker (TensorProduct.mk R (R ⧸ I) Q 1) = I • ⊤ := by
apply comap_injective_of_surjective (TensorProduct.lid R Q).surjective
rw [← comap_coe_toLinearMap, ← ker_comp]
convert rTensor_mkQ Q I
· ext; simp
rw [← comap_coe_toLinearMap, ← toLinearMap_eq_coe, comap_equiv_eq_map_symm, toLinearMap_eq_coe,
map_coe_toLinearMap, map_symm_eq_iff, map_range_rTensor_subtype_lid]
variable {M' N' P' : Type*}
[AddCommGroup M'] [AddCommGroup N'] [AddCommGroup P']
[Module R M'] [Module R N'] [Module R P']
{f' : M' →ₗ[R] N'} {g' : N' →ₗ[R] P'}
(hfg' : Exact f' g') (hg' : Function.Surjective g')
include hg hg' hfg hfg' in
/-- Kernel of a product map (right-exactness of tensor product) -/
theorem TensorProduct.map_ker :
ker (TensorProduct.map g g') = range (lTensor N f') ⊔ range (rTensor N' f) := by
rw [← lTensor_comp_rTensor]
rw [ker_comp]
rw [← Exact.linearMap_ker_eq (rTensor_exact N' hfg hg)]
rw [← Submodule.comap_map_eq]
apply congr_arg₂ _ rfl
rw [range_eq_map, ← Submodule.map_comp, rTensor_comp_lTensor,
Submodule.map_top]
rw [← lTensor_comp_rTensor, range_eq_map, Submodule.map_comp,
Submodule.map_top]
rw [range_eq_top.mpr (rTensor_surjective M' hg), Submodule.map_top]
rw [Exact.linearMap_ker_eq (lTensor_exact P hfg' hg')]
end Modules
section Algebras
open Algebra.TensorProduct
open scoped TensorProduct
variable
{R : Type*} [CommSemiring R]
{A B : Type*} [Semiring A] [Semiring B] [Algebra R A] [Algebra R B]
/-- The ideal of `A ⊗[R] B` generated by `I` is the image of `I ⊗[R] B` -/
lemma Ideal.map_includeLeft_eq (I : Ideal A) :
(I.map (Algebra.TensorProduct.includeLeft : A →ₐ[R] A ⊗[R] B)).restrictScalars R
= LinearMap.range (LinearMap.rTensor B (Submodule.subtype (I.restrictScalars R))) := by
rw [← SetLike.coe_set_eq]
apply le_antisymm
· intro x hx
simp only [SetLike.mem_coe, LinearMap.mem_range]
rw [Ideal.map, ← submodule_span_eq] at hx
refine Submodule.span_induction ?_ ?_ ?_ ?_ hx
· intro x
simp only [includeLeft_apply, Set.mem_image, SetLike.mem_coe]
rintro ⟨y, hy, rfl⟩
use ⟨y, hy⟩ ⊗ₜ[R] 1
rfl
· use 0
simp only [map_zero]
· rintro x y - - ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩
use x + y
simp only [map_add]
· rintro a x - ⟨x, hx, rfl⟩
induction a with
| zero =>
use 0
simp only [map_zero, smul_eq_mul, zero_mul]
| tmul a b =>
induction x with
| zero =>
use 0
simp only [map_zero, smul_eq_mul, mul_zero]
| tmul x y =>
use (a • x) ⊗ₜ[R] (b * y)
simp only [smul_eq_mul]
with_unfolding_all rfl
| add x y hx hy =>
obtain ⟨x', hx'⟩ := hx
obtain ⟨y', hy'⟩ := hy
use x' + y'
simp only [map_add, hx', smul_add, hy']
| add a b ha hb =>
obtain ⟨x', ha'⟩ := ha
obtain ⟨y', hb'⟩ := hb
use x' + y'
simp only [map_add, ha', add_smul, hb']
· rintro x ⟨y, rfl⟩
induction y with
| zero =>
rw [map_zero]
apply zero_mem
| tmul a b =>
simp only [LinearMap.rTensor_tmul, Submodule.coe_subtype]
suffices (a : A) ⊗ₜ[R] b = ((1 : A) ⊗ₜ[R] b) * ((a : A) ⊗ₜ[R] (1 : B)) by
simp only [Submodule.coe_restrictScalars, SetLike.mem_coe]
rw [this]
apply Ideal.mul_mem_left
-- Note: adding `includeLeft` as a hint fixes a timeout https://github.com/leanprover-community/mathlib4/pull/8386
apply Ideal.mem_map_of_mem includeLeft
exact Submodule.coe_mem a
simp only [Algebra.TensorProduct.tmul_mul_tmul,
mul_one, one_mul]
| add x y hx hy =>
rw [map_add]
apply Submodule.add_mem _ hx hy
/-- The ideal of `A ⊗[R] B` generated by `I` is the image of `A ⊗[R] I` -/
lemma Ideal.map_includeRight_eq (I : Ideal B) :
(I.map (Algebra.TensorProduct.includeRight : B →ₐ[R] A ⊗[R] B)).restrictScalars R
= LinearMap.range (LinearMap.lTensor A (Submodule.subtype (I.restrictScalars R))) := by
rw [← SetLike.coe_set_eq]
apply le_antisymm
· intro x hx
simp only [SetLike.mem_coe, LinearMap.mem_range]
rw [Ideal.map, ← submodule_span_eq] at hx
refine Submodule.span_induction ?_ ?_ ?_ ?_ hx
· intro x
simp only [includeRight_apply, Set.mem_image, SetLike.mem_coe]
rintro ⟨y, hy, rfl⟩
use 1 ⊗ₜ[R] ⟨y, hy⟩
rfl
· use 0
simp only [map_zero]
· rintro x y - - ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩
use x + y
simp only [map_add]
· rintro a x - ⟨x, hx, rfl⟩
induction a with
| zero =>
use 0
simp only [map_zero, smul_eq_mul, zero_mul]
| tmul a b =>
induction x with
| zero =>
use 0
simp only [map_zero, smul_eq_mul, mul_zero]
| tmul x y =>
use (a * x) ⊗ₜ[R] (b •y)
simp only [LinearMap.lTensor_tmul, Submodule.coe_subtype, smul_eq_mul, tmul_mul_tmul]
rfl
| add x y hx hy =>
obtain ⟨x', hx'⟩ := hx
obtain ⟨y', hy'⟩ := hy
use x' + y'
simp only [map_add, hx', smul_add, hy']
| add a b ha hb =>
obtain ⟨x', ha'⟩ := ha
obtain ⟨y', hb'⟩ := hb
use x' + y'
simp only [map_add, ha', add_smul, hb']
· rintro x ⟨y, rfl⟩
induction y with
| zero =>
rw [map_zero]
apply zero_mem
| tmul a b =>
simp only [LinearMap.lTensor_tmul, Submodule.coe_subtype]
suffices a ⊗ₜ[R] (b : B) = (a ⊗ₜ[R] (1 : B)) * ((1 : A) ⊗ₜ[R] (b : B)) by
rw [this]
simp only [Submodule.coe_restrictScalars, SetLike.mem_coe]
apply Ideal.mul_mem_left
-- Note: adding `includeRight` as a hint fixes a timeout https://github.com/leanprover-community/mathlib4/pull/8386
apply Ideal.mem_map_of_mem includeRight
exact Submodule.coe_mem b
simp only [Algebra.TensorProduct.tmul_mul_tmul,
mul_one, one_mul]
| add x y hx hy =>
rw [map_add]
apply Submodule.add_mem _ hx hy
-- Now, we can prove the right exactness properties of the tensor product,
-- in its versions for algebras
variable {R : Type*} [CommRing R]
{A B C D : Type*} [Ring A] [Ring B] [Ring C] [Ring D]
[Algebra R A] [Algebra R B] [Algebra R C] [Algebra R D]
(f : A →ₐ[R] B) (g : C →ₐ[R] D)
/-- If `g` is surjective, then the kernel of `(id A) ⊗ g` is generated by the kernel of `g` -/
lemma Algebra.TensorProduct.lTensor_ker (hg : Function.Surjective g) :
RingHom.ker (map (AlgHom.id R A) g) =
(RingHom.ker g).map (Algebra.TensorProduct.includeRight : C →ₐ[R] A ⊗[R] C) := by
rw [← Submodule.restrictScalars_inj R]
have : (RingHom.ker (map (AlgHom.id R A) g)).restrictScalars R =
LinearMap.ker (LinearMap.lTensor A (AlgHom.toLinearMap g)) := rfl
rw [this, Ideal.map_includeRight_eq]
rw [(lTensor_exact A g.toLinearMap.exact_subtype_ker_map hg).linearMap_ker_eq]
rfl
/-- If `f` is surjective, then the kernel of `f ⊗ (id B)` is generated by the kernel of `f` -/
lemma Algebra.TensorProduct.rTensor_ker (hf : Function.Surjective f) :
RingHom.ker (map f (AlgHom.id R C)) =
(RingHom.ker f).map (Algebra.TensorProduct.includeLeft : A →ₐ[R] A ⊗[R] C) := by
rw [← Submodule.restrictScalars_inj R]
have : (RingHom.ker (map f (AlgHom.id R C))).restrictScalars R =
LinearMap.ker (LinearMap.rTensor C (AlgHom.toLinearMap f)) := rfl
rw [this, Ideal.map_includeLeft_eq]
rw [(rTensor_exact C f.toLinearMap.exact_subtype_ker_map hf).linearMap_ker_eq]
rfl
/-- If `f` and `g` are surjective morphisms of algebras, then
the kernel of `Algebra.TensorProduct.map f g` is generated by the kernels of `f` and `g` -/
theorem Algebra.TensorProduct.map_ker (hf : Function.Surjective f) (hg : Function.Surjective g) :
RingHom.ker (map f g) =
(RingHom.ker f).map (Algebra.TensorProduct.includeLeft : A →ₐ[R] A ⊗[R] C) ⊔
(RingHom.ker g).map (Algebra.TensorProduct.includeRight : C →ₐ[R] A ⊗[R] C) := by
-- rewrite map f g as the composition of two maps
have : map f g = (map f (AlgHom.id R D)).comp (map (AlgHom.id R A) g) := ext rfl rfl
rw [this]
-- this needs some rewriting to RingHom
-- TODO: can `RingHom.comap_ker` take an arbitrary `RingHomClass`, rather than just `RingHom`?
simp only [AlgHom.ker_coe, AlgHom.comp_toRingHom]
rw [← RingHom.comap_ker]
simp only [← AlgHom.ker_coe]
-- apply one step of exactness
rw [← Algebra.TensorProduct.lTensor_ker _ hg, RingHom.ker_eq_comap_bot (map (AlgHom.id R A) g)]
rw [← Ideal.comap_map_of_surjective (map (AlgHom.id R A) g) (LinearMap.lTensor_surjective A hg)]
-- apply the other step of exactness
rw [Algebra.TensorProduct.rTensor_ker _ hf]
apply congr_arg₂ _ rfl
simp only [AlgHom.coe_ideal_map, Ideal.map_map]
rw [← AlgHom.comp_toRingHom, Algebra.TensorProduct.map_comp_includeLeft]
rfl
end Algebras
|
Basic.lean
|
/-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Filippo A. E. Nuccio, Andrew Yang
-/
import Mathlib.RingTheory.Ideal.MinimalPrime.Basic
import Mathlib.RingTheory.Nilpotent.Lemmas
import Mathlib.RingTheory.Noetherian.Basic
import Mathlib.RingTheory.Spectrum.Prime.Defs
/-!
# Prime spectrum of a commutative (semi)ring
For the Zariski topology, see `Mathlib/RingTheory/Spectrum/Prime/Topology.lean`.
(It is also naturally endowed with a sheaf of rings,
which is constructed in `AlgebraicGeometry.StructureSheaf`.)
## Main definitions
* `zeroLocus s`: The zero locus of a subset `s` of `R`
is the subset of `PrimeSpectrum R` consisting of all prime ideals that contain `s`.
* `vanishingIdeal t`: The vanishing ideal of a subset `t` of `PrimeSpectrum R`
is the intersection of points in `t` (viewed as prime ideals).
## Conventions
We denote subsets of (semi)rings with `s`, `s'`, etc...
whereas we denote subsets of prime spectra with `t`, `t'`, etc...
## Inspiration/contributors
The contents of this file draw inspiration from <https://github.com/ramonfmir/lean-scheme>
which has contributions from Ramon Fernandez Mir, Kevin Buzzard, Kenny Lau,
and Chris Hughes (on an earlier repository).
## References
* [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald]
* [P. Samuel, *Algebraic Theory of Numbers*][samuel1967]
-/
-- A dividing line between this file and `Mathlib/RingTheory/Spectrum/Prime/Topology.lean` is
-- that we should not depend on the Zariski topology here
assert_not_exists TopologicalSpace
noncomputable section
open scoped Pointwise
universe u v
variable (R : Type u) (S : Type v)
namespace PrimeSpectrum
section CommSemiRing
variable [CommSemiring R] [CommSemiring S]
variable {R S}
lemma nonempty_iff_nontrivial : Nonempty (PrimeSpectrum R) ↔ Nontrivial R := by
refine ⟨fun ⟨p⟩ ↦ ⟨0, 1, fun h ↦ p.2.ne_top ?_⟩, fun h ↦ ?_⟩
· simp [Ideal.eq_top_iff_one p.asIdeal, ← h]
· obtain ⟨I, hI⟩ := Ideal.exists_maximal R
exact ⟨⟨I, hI.isPrime⟩⟩
lemma isEmpty_iff_subsingleton : IsEmpty (PrimeSpectrum R) ↔ Subsingleton R := by
rw [← not_iff_not, not_isEmpty_iff, not_subsingleton_iff_nontrivial, nonempty_iff_nontrivial]
instance [Nontrivial R] : Nonempty <| PrimeSpectrum R :=
nonempty_iff_nontrivial.mpr inferInstance
/-- The prime spectrum of the zero ring is empty. -/
instance [Subsingleton R] : IsEmpty (PrimeSpectrum R) :=
isEmpty_iff_subsingleton.mpr inferInstance
lemma nontrivial (p : PrimeSpectrum R) : Nontrivial R :=
nonempty_iff_nontrivial.mp ⟨p⟩
variable (R S)
theorem range_asIdeal : Set.range PrimeSpectrum.asIdeal = {J : Ideal R | J.IsPrime} :=
Set.ext fun J ↦
⟨fun hJ ↦ let ⟨j, hj⟩ := Set.mem_range.mp hJ; Set.mem_setOf.mpr <| hj ▸ j.isPrime,
fun hJ ↦ Set.mem_range.mpr ⟨⟨J, Set.mem_setOf.mp hJ⟩, rfl⟩⟩
/-- The map from the direct sum of prime spectra to the prime spectrum of a direct product. -/
@[simp]
def primeSpectrumProdOfSum : PrimeSpectrum R ⊕ PrimeSpectrum S → PrimeSpectrum (R × S)
| Sum.inl ⟨I, _⟩ => ⟨Ideal.prod I ⊤, Ideal.isPrime_ideal_prod_top⟩
| Sum.inr ⟨J, _⟩ => ⟨Ideal.prod ⊤ J, Ideal.isPrime_ideal_prod_top'⟩
/-- The prime spectrum of `R × S` is in bijection with the disjoint unions of the prime spectrum of
`R` and the prime spectrum of `S`. -/
noncomputable def primeSpectrumProd :
PrimeSpectrum (R × S) ≃ PrimeSpectrum R ⊕ PrimeSpectrum S :=
Equiv.symm <|
Equiv.ofBijective (primeSpectrumProdOfSum R S) (by
constructor
· rintro (⟨I, hI⟩ | ⟨J, hJ⟩) (⟨I', hI'⟩ | ⟨J', hJ'⟩) h <;>
simp only [mk.injEq, Ideal.prod_inj, primeSpectrumProdOfSum] at h
· simp only [h]
· exact False.elim (hI.ne_top h.left)
· exact False.elim (hJ.ne_top h.right)
· simp only [h]
· rintro ⟨I, hI⟩
rcases (Ideal.ideal_prod_prime I).mp hI with (⟨p, ⟨hp, rfl⟩⟩ | ⟨p, ⟨hp, rfl⟩⟩)
· exact ⟨Sum.inl ⟨p, hp⟩, rfl⟩
· exact ⟨Sum.inr ⟨p, hp⟩, rfl⟩)
variable {R S}
@[simp]
theorem primeSpectrumProd_symm_inl_asIdeal (x : PrimeSpectrum R) :
((primeSpectrumProd R S).symm <| Sum.inl x).asIdeal = Ideal.prod x.asIdeal ⊤ := by
cases x
rfl
@[simp]
theorem primeSpectrumProd_symm_inr_asIdeal (x : PrimeSpectrum S) :
((primeSpectrumProd R S).symm <| Sum.inr x).asIdeal = Ideal.prod ⊤ x.asIdeal := by
cases x
rfl
/-- The zero locus of a set `s` of elements of a commutative (semi)ring `R` is the set of all
prime ideals of the ring that contain the set `s`.
An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`.
At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring
`R` modulo the prime ideal `x`. In this manner, `zeroLocus s` is exactly the subset of
`PrimeSpectrum R` where all "functions" in `s` vanish simultaneously.
-/
def zeroLocus (s : Set R) : Set (PrimeSpectrum R) :=
{ x | s ⊆ x.asIdeal }
@[simp]
theorem mem_zeroLocus (x : PrimeSpectrum R) (s : Set R) : x ∈ zeroLocus s ↔ s ⊆ x.asIdeal :=
Iff.rfl
@[simp]
theorem zeroLocus_span (s : Set R) : zeroLocus (Ideal.span s : Set R) = zeroLocus s := by
ext x
exact (Submodule.gi R R).gc s x.asIdeal
/-- The vanishing ideal of a set `t` of points of the prime spectrum of a commutative ring `R` is
the intersection of all the prime ideals in the set `t`.
An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`.
At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring
`R` modulo the prime ideal `x`. In this manner, `vanishingIdeal t` is exactly the ideal of `R`
consisting of all "functions" that vanish on all of `t`.
-/
def vanishingIdeal (t : Set (PrimeSpectrum R)) : Ideal R :=
⨅ x ∈ t, x.asIdeal
theorem coe_vanishingIdeal (t : Set (PrimeSpectrum R)) :
(vanishingIdeal t : Set R) = { f : R | ∀ x ∈ t, f ∈ x.asIdeal } := by
ext f
rw [vanishingIdeal, SetLike.mem_coe, Submodule.mem_iInf]
apply forall_congr'; intro x
rw [Submodule.mem_iInf]
theorem mem_vanishingIdeal (t : Set (PrimeSpectrum R)) (f : R) :
f ∈ vanishingIdeal t ↔ ∀ x ∈ t, f ∈ x.asIdeal := by
rw [← SetLike.mem_coe, coe_vanishingIdeal, Set.mem_setOf_eq]
@[simp]
theorem vanishingIdeal_singleton (x : PrimeSpectrum R) :
vanishingIdeal ({x} : Set (PrimeSpectrum R)) = x.asIdeal := by simp [vanishingIdeal]
theorem subset_zeroLocus_iff_le_vanishingIdeal (t : Set (PrimeSpectrum R)) (I : Ideal R) :
t ⊆ zeroLocus I ↔ I ≤ vanishingIdeal t :=
⟨fun h _ k => (mem_vanishingIdeal _ _).mpr fun _ j => (mem_zeroLocus _ _).mpr (h j) k, fun h =>
fun x j => (mem_zeroLocus _ _).mpr (le_trans h fun _ h => ((mem_vanishingIdeal _ _).mp h) x j)⟩
section Gc
variable (R)
/-- `zeroLocus` and `vanishingIdeal` form a galois connection. -/
theorem gc :
@GaloisConnection (Ideal R) (Set (PrimeSpectrum R))ᵒᵈ _ _ (fun I => zeroLocus I) fun t =>
vanishingIdeal t :=
fun I t => subset_zeroLocus_iff_le_vanishingIdeal t I
/-- `zeroLocus` and `vanishingIdeal` form a galois connection. -/
theorem gc_set :
@GaloisConnection (Set R) (Set (PrimeSpectrum R))ᵒᵈ _ _ (fun s => zeroLocus s) fun t =>
vanishingIdeal t := by
have ideal_gc : GaloisConnection Ideal.span _ := (Submodule.gi R R).gc
simpa [zeroLocus_span, Function.comp_def] using ideal_gc.compose (gc R)
theorem subset_zeroLocus_iff_subset_vanishingIdeal (t : Set (PrimeSpectrum R)) (s : Set R) :
t ⊆ zeroLocus s ↔ s ⊆ vanishingIdeal t :=
(gc_set R) s t
end Gc
theorem subset_vanishingIdeal_zeroLocus (s : Set R) : s ⊆ vanishingIdeal (zeroLocus s) :=
(gc_set R).le_u_l s
theorem le_vanishingIdeal_zeroLocus (I : Ideal R) : I ≤ vanishingIdeal (zeroLocus I) :=
(gc R).le_u_l I
@[simp]
theorem vanishingIdeal_zeroLocus_eq_radical (I : Ideal R) :
vanishingIdeal (zeroLocus (I : Set R)) = I.radical :=
Ideal.ext fun f => by
rw [mem_vanishingIdeal, Ideal.radical_eq_sInf, Submodule.mem_sInf]
exact ⟨fun h x hx => h ⟨x, hx.2⟩ hx.1, fun h x hx => h x.1 ⟨hx, x.2⟩⟩
theorem nilradical_eq_iInf : nilradical R = iInf asIdeal := by
apply range_asIdeal R ▸ nilradical_eq_sInf R
@[simp] theorem vanishingIdeal_univ : vanishingIdeal Set.univ = nilradical R := by
rw [vanishingIdeal, iInf_univ, nilradical_eq_iInf]
@[simp]
theorem zeroLocus_radical (I : Ideal R) : zeroLocus (I.radical : Set R) = zeroLocus I :=
vanishingIdeal_zeroLocus_eq_radical I ▸ (gc R).l_u_l_eq_l I
theorem subset_zeroLocus_vanishingIdeal (t : Set (PrimeSpectrum R)) :
t ⊆ zeroLocus (vanishingIdeal t) :=
(gc R).l_u_le t
theorem zeroLocus_anti_mono {s t : Set R} (h : s ⊆ t) : zeroLocus t ⊆ zeroLocus s :=
(gc_set R).monotone_l h
theorem zeroLocus_anti_mono_ideal {s t : Ideal R} (h : s ≤ t) :
zeroLocus (t : Set R) ⊆ zeroLocus (s : Set R) :=
(gc R).monotone_l h
theorem vanishingIdeal_anti_mono {s t : Set (PrimeSpectrum R)} (h : s ⊆ t) :
vanishingIdeal t ≤ vanishingIdeal s :=
(gc R).monotone_u h
theorem zeroLocus_subset_zeroLocus_iff (I J : Ideal R) :
zeroLocus (I : Set R) ⊆ zeroLocus (J : Set R) ↔ J ≤ I.radical := by
rw [subset_zeroLocus_iff_le_vanishingIdeal, vanishingIdeal_zeroLocus_eq_radical]
theorem zeroLocus_subset_zeroLocus_singleton_iff (f g : R) :
zeroLocus ({f} : Set R) ⊆ zeroLocus {g} ↔ g ∈ (Ideal.span ({f} : Set R)).radical := by
rw [← zeroLocus_span {f}, ← zeroLocus_span {g}, zeroLocus_subset_zeroLocus_iff, Ideal.span_le,
Set.singleton_subset_iff, SetLike.mem_coe]
theorem zeroLocus_bot : zeroLocus ((⊥ : Ideal R) : Set R) = Set.univ :=
(gc R).l_bot
@[simp]
lemma zeroLocus_nilradical : zeroLocus (nilradical R : Set R) = Set.univ := by
rw [nilradical, zeroLocus_radical, Ideal.zero_eq_bot, zeroLocus_bot]
@[simp]
theorem zeroLocus_singleton_zero : zeroLocus ({0} : Set R) = Set.univ :=
zeroLocus_bot
@[simp]
theorem zeroLocus_empty : zeroLocus (∅ : Set R) = Set.univ :=
(gc_set R).l_bot
@[simp]
theorem vanishingIdeal_empty : vanishingIdeal (∅ : Set (PrimeSpectrum R)) = ⊤ := by
simpa using (gc R).u_top
theorem zeroLocus_empty_of_one_mem {s : Set R} (h : (1 : R) ∈ s) : zeroLocus s = ∅ := by
rw [Set.eq_empty_iff_forall_notMem]
intro x hx
rw [mem_zeroLocus] at hx
have x_prime : x.asIdeal.IsPrime := by infer_instance
have eq_top : x.asIdeal = ⊤ := by
rw [Ideal.eq_top_iff_one]
exact hx h
apply x_prime.ne_top eq_top
@[simp]
theorem zeroLocus_singleton_one : zeroLocus ({1} : Set R) = ∅ :=
zeroLocus_empty_of_one_mem (Set.mem_singleton (1 : R))
theorem zeroLocus_empty_iff_eq_top {I : Ideal R} : zeroLocus (I : Set R) = ∅ ↔ I = ⊤ := by
constructor
· contrapose!
intro h
rcases Ideal.exists_le_maximal I h with ⟨M, hM, hIM⟩
exact ⟨⟨M, hM.isPrime⟩, hIM⟩
· rintro rfl
apply zeroLocus_empty_of_one_mem
trivial
@[simp]
theorem zeroLocus_univ : zeroLocus (Set.univ : Set R) = ∅ :=
zeroLocus_empty_of_one_mem (Set.mem_univ 1)
theorem vanishingIdeal_eq_top_iff {s : Set (PrimeSpectrum R)} : vanishingIdeal s = ⊤ ↔ s = ∅ := by
rw [← top_le_iff, ← subset_zeroLocus_iff_le_vanishingIdeal, Submodule.top_coe, zeroLocus_univ,
Set.subset_empty_iff]
theorem zeroLocus_eq_univ_iff (s : Set R) :
zeroLocus s = Set.univ ↔ s ⊆ nilradical R := by
rw [← Set.univ_subset_iff, subset_zeroLocus_iff_subset_vanishingIdeal, vanishingIdeal_univ]
@[deprecated (since := "2025-04-05")] alias zeroLocus_eq_top_iff := zeroLocus_eq_univ_iff
theorem zeroLocus_sup (I J : Ideal R) :
zeroLocus ((I ⊔ J : Ideal R) : Set R) = zeroLocus I ∩ zeroLocus J :=
(gc R).l_sup
theorem zeroLocus_union (s s' : Set R) : zeroLocus (s ∪ s') = zeroLocus s ∩ zeroLocus s' :=
(gc_set R).l_sup
theorem vanishingIdeal_union (t t' : Set (PrimeSpectrum R)) :
vanishingIdeal (t ∪ t') = vanishingIdeal t ⊓ vanishingIdeal t' :=
(gc R).u_inf
theorem zeroLocus_iSup {ι : Sort*} (I : ι → Ideal R) :
zeroLocus ((⨆ i, I i : Ideal R) : Set R) = ⋂ i, zeroLocus (I i) :=
(gc R).l_iSup
theorem zeroLocus_iUnion {ι : Sort*} (s : ι → Set R) :
zeroLocus (⋃ i, s i) = ⋂ i, zeroLocus (s i) :=
(gc_set R).l_iSup
theorem zeroLocus_iUnion₂ {ι : Sort*} {κ : (i : ι) → Sort*} (s : ∀ i, κ i → Set R) :
zeroLocus (⋃ (i) (j), s i j) = ⋂ (i) (j), zeroLocus (s i j) :=
(gc_set R).l_iSup₂
theorem zeroLocus_bUnion (s : Set (Set R)) :
zeroLocus (⋃ s' ∈ s, s' : Set R) = ⋂ s' ∈ s, zeroLocus s' := by simp only [zeroLocus_iUnion]
theorem vanishingIdeal_iUnion {ι : Sort*} (t : ι → Set (PrimeSpectrum R)) :
vanishingIdeal (⋃ i, t i) = ⨅ i, vanishingIdeal (t i) :=
(gc R).u_iInf
theorem zeroLocus_inf (I J : Ideal R) :
zeroLocus ((I ⊓ J : Ideal R) : Set R) = zeroLocus I ∪ zeroLocus J :=
Set.ext fun x => x.2.inf_le
theorem union_zeroLocus (s s' : Set R) :
zeroLocus s ∪ zeroLocus s' = zeroLocus (Ideal.span s ⊓ Ideal.span s' : Ideal R) := by
rw [zeroLocus_inf]
simp
theorem zeroLocus_mul (I J : Ideal R) :
zeroLocus ((I * J : Ideal R) : Set R) = zeroLocus I ∪ zeroLocus J :=
Set.ext fun x => x.2.mul_le
theorem zeroLocus_singleton_mul (f g : R) :
zeroLocus ({f * g} : Set R) = zeroLocus {f} ∪ zeroLocus {g} :=
Set.ext fun x => by simpa using x.2.mul_mem_iff_mem_or_mem
@[simp]
theorem zeroLocus_pow (I : Ideal R) {n : ℕ} (hn : n ≠ 0) :
zeroLocus ((I ^ n : Ideal R) : Set R) = zeroLocus I :=
zeroLocus_radical (I ^ n) ▸ (I.radical_pow hn).symm ▸ zeroLocus_radical I
@[simp]
theorem zeroLocus_singleton_pow (f : R) (n : ℕ) (hn : 0 < n) :
zeroLocus ({f ^ n} : Set R) = zeroLocus {f} :=
Set.ext fun x => by simpa using x.2.pow_mem_iff_mem n hn
theorem sup_vanishingIdeal_le (t t' : Set (PrimeSpectrum R)) :
vanishingIdeal t ⊔ vanishingIdeal t' ≤ vanishingIdeal (t ∩ t') := by
intro r
rw [Submodule.mem_sup, mem_vanishingIdeal]
rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩
rw [mem_vanishingIdeal] at hf hg
apply Submodule.add_mem <;> solve_by_elim
theorem mem_compl_zeroLocus_iff_notMem {f : R} {I : PrimeSpectrum R} :
I ∈ (zeroLocus {f} : Set (PrimeSpectrum R))ᶜ ↔ f ∉ I.asIdeal := by
rw [Set.mem_compl_iff, mem_zeroLocus, Set.singleton_subset_iff]; rfl
@[deprecated (since := "2025-05-23")]
alias mem_compl_zeroLocus_iff_not_mem := mem_compl_zeroLocus_iff_notMem
@[simp]
lemma zeroLocus_insert_zero (s : Set R) : zeroLocus (insert 0 s) = zeroLocus s := by
rw [← Set.union_singleton, zeroLocus_union, zeroLocus_singleton_zero, Set.inter_univ]
@[simp]
lemma zeroLocus_diff_singleton_zero (s : Set R) : zeroLocus (s \ {0}) = zeroLocus s := by
rw [← zeroLocus_insert_zero, ← zeroLocus_insert_zero (s := s)]; simp
lemma zeroLocus_smul_of_isUnit {r : R} (hr : IsUnit r) (s : Set R) :
zeroLocus (r • s) = zeroLocus s := by
ext; simp [Set.subset_def, ← Set.image_smul, Ideal.unit_mul_mem_iff_mem _ hr]
section Order
instance [IsDomain R] : OrderBot (PrimeSpectrum R) where
bot := ⟨⊥, Ideal.bot_prime⟩
bot_le I := @bot_le _ _ _ I.asIdeal
instance {R : Type*} [Field R] : Unique (PrimeSpectrum R) where
default := ⊥
uniq x := PrimeSpectrum.ext ((IsSimpleOrder.eq_bot_or_eq_top _).resolve_right x.2.ne_top)
/-- Also see `PrimeSpectrum.isClosed_singleton_iff_isMaximal` -/
lemma isMax_iff {x : PrimeSpectrum R} :
IsMax x ↔ x.asIdeal.IsMaximal := by
refine ⟨fun hx ↦ ⟨⟨x.2.ne_top, fun I hI ↦ ?_⟩⟩, fun hx y e ↦ (hx.eq_of_le y.2.ne_top e).ge⟩
by_contra e
obtain ⟨m, hm, hm'⟩ := Ideal.exists_le_maximal I e
exact hx.not_lt (show x < ⟨m, hm.isPrime⟩ from hI.trans_le hm')
lemma zeroLocus_eq_singleton (m : Ideal R) [m.IsMaximal] :
zeroLocus m = {⟨m, inferInstance⟩} := by
ext I
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· simp only [mem_zeroLocus, SetLike.coe_subset_coe] at h
simpa using PrimeSpectrum.ext_iff.mpr (Ideal.IsMaximal.eq_of_le ‹_› I.2.ne_top h).symm
· simp [Set.mem_singleton_iff.mp h]
lemma isMin_iff {x : PrimeSpectrum R} :
IsMin x ↔ x.asIdeal ∈ minimalPrimes R := by
change IsMin _ ↔ Minimal (fun q : Ideal R ↦ q.IsPrime ∧ ⊥ ≤ q) _
simp only [IsMin, Minimal, x.2, bot_le, and_self, and_true, true_and]
exact ⟨fun H y hy e ↦ @H ⟨y, hy⟩ e, fun H y e ↦ H y.2 e⟩
end Order
section Noetherian
open Submodule
variable (R : Type u) [CommRing R] [IsNoetherianRing R]
variable {A : Type u} [CommRing A] [IsDomain A] [IsNoetherianRing A]
/-- In a noetherian ring, every ideal contains a product of prime ideals
([samuel1967, § 3.3, Lemma 3]). -/
theorem exists_primeSpectrum_prod_le (I : Ideal R) :
∃ Z : Multiset (PrimeSpectrum R), Multiset.prod (Z.map asIdeal) ≤ I := by
-- Porting note: Need to specify `P` explicitly
refine IsNoetherian.induction
(P := fun I => ∃ Z : Multiset (PrimeSpectrum R), Multiset.prod (Z.map asIdeal) ≤ I)
(fun (M : Ideal R) hgt => ?_) I
by_cases h_prM : M.IsPrime
· use {⟨M, h_prM⟩}
rw [Multiset.map_singleton, Multiset.prod_singleton]
by_cases htop : M = ⊤
· rw [htop]
exact ⟨0, le_top⟩
have lt_add : ∀ z ∉ M, M < M + span R {z} := by
intro z hz
refine lt_of_le_of_ne le_sup_left fun m_eq => hz ?_
rw [m_eq]
exact Ideal.mem_sup_right (mem_span_singleton_self z)
obtain ⟨x, hx, y, hy, hxy⟩ := (Ideal.not_isPrime_iff.mp h_prM).resolve_left htop
obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx)
obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy)
use Wx + Wy
rw [Multiset.map_add, Multiset.prod_add]
apply le_trans (Submodule.mul_le_mul h_Wx h_Wy)
rw [add_mul]
apply sup_le (show M * (M + span R {y}) ≤ M from Ideal.mul_le_right)
rw [mul_add]
apply sup_le (show span R {x} * M ≤ M from Ideal.mul_le_left)
rwa [span_mul_span, Set.singleton_mul_singleton, span_singleton_le_iff_mem]
/-- In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero
product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as
product or prime ideals ([samuel1967, § 3.3, Lemma 3]) -/
theorem exists_primeSpectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬IsField A) {I : Ideal A}
(h_nzI : I ≠ ⊥) :
∃ Z : Multiset (PrimeSpectrum A),
Multiset.prod (Z.map asIdeal) ≤ I ∧ Multiset.prod (Z.map asIdeal) ≠ ⊥ := by
revert h_nzI
-- Porting note: Need to specify `P` explicitly
refine IsNoetherian.induction (P := fun I => I ≠ ⊥ → ∃ Z : Multiset (PrimeSpectrum A),
Multiset.prod (Z.map asIdeal) ≤ I ∧ Multiset.prod (Z.map asIdeal) ≠ ⊥)
(fun (M : Ideal A) hgt => ?_) I
intro h_nzM
have hA_nont : Nontrivial A := IsDomain.toNontrivial
by_cases h_topM : M = ⊤
· rcases h_topM with rfl
obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ p : Ideal A, p ≠ ⊥ ∧ p.IsPrime := by
apply Ring.not_isField_iff_exists_prime.mp h_fA
use ({⟨p_id, h_pp⟩} : Multiset (PrimeSpectrum A)), le_top
rwa [Multiset.map_singleton, Multiset.prod_singleton]
by_cases h_prM : M.IsPrime
· use ({⟨M, h_prM⟩} : Multiset (PrimeSpectrum A))
rw [Multiset.map_singleton, Multiset.prod_singleton]
exact ⟨le_rfl, h_nzM⟩
obtain ⟨x, hx, y, hy, h_xy⟩ := (Ideal.not_isPrime_iff.mp h_prM).resolve_left h_topM
have lt_add : ∀ z ∉ M, M < M + span A {z} := by
intro z hz
refine lt_of_le_of_ne le_sup_left fun m_eq => hz ?_
rw [m_eq]
exact mem_sup_right (mem_span_singleton_self z)
obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx))
obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy))
use Wx + Wy
rw [Multiset.map_add, Multiset.prod_add]
refine ⟨le_trans (Submodule.mul_le_mul h_Wx_le h_Wy_le) ?_, mt Ideal.mul_eq_bot.mp ?_⟩
· rw [add_mul]
apply sup_le (show M * (M + span A {y}) ≤ M from Ideal.mul_le_right)
rw [mul_add]
apply sup_le (show span A {x} * M ≤ M from Ideal.mul_le_left)
rwa [span_mul_span, Set.singleton_mul_singleton, span_singleton_le_iff_mem]
· rintro (hx | hy) <;> contradiction
end Noetherian
end CommSemiRing
end PrimeSpectrum
|
WithBotTop.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.Data.Set.Image
import Mathlib.Order.Interval.Set.Basic
import Mathlib.Order.WithBot
/-!
# Intervals in `WithTop α` and `WithBot α`
In this file we prove various lemmas about `Set.image`s and `Set.preimage`s of intervals under
`some : α → WithTop α` and `some : α → WithBot α`.
-/
open Set
variable {α : Type*}
/-! ### `WithTop` -/
namespace WithTop
@[simp]
theorem preimage_coe_top : (some : α → WithTop α) ⁻¹' {⊤} = (∅ : Set α) :=
eq_empty_of_subset_empty fun _ => coe_ne_top
variable [Preorder α] {a b : α}
theorem range_coe : range (some : α → WithTop α) = Iio ⊤ := by
ext x
rw [mem_Iio, WithTop.lt_top_iff_ne_top, mem_range, ne_top_iff_exists]
@[simp]
theorem preimage_coe_Ioi : (some : α → WithTop α) ⁻¹' Ioi a = Ioi a :=
ext fun _ => coe_lt_coe
@[simp]
theorem preimage_coe_Ici : (some : α → WithTop α) ⁻¹' Ici a = Ici a :=
ext fun _ => coe_le_coe
@[simp]
theorem preimage_coe_Iio : (some : α → WithTop α) ⁻¹' Iio a = Iio a :=
ext fun _ => coe_lt_coe
@[simp]
theorem preimage_coe_Iic : (some : α → WithTop α) ⁻¹' Iic a = Iic a :=
ext fun _ => coe_le_coe
@[simp]
theorem preimage_coe_Icc : (some : α → WithTop α) ⁻¹' Icc a b = Icc a b := by simp [← Ici_inter_Iic]
@[simp]
theorem preimage_coe_Ico : (some : α → WithTop α) ⁻¹' Ico a b = Ico a b := by simp [← Ici_inter_Iio]
@[simp]
theorem preimage_coe_Ioc : (some : α → WithTop α) ⁻¹' Ioc a b = Ioc a b := by simp [← Ioi_inter_Iic]
@[simp]
theorem preimage_coe_Ioo : (some : α → WithTop α) ⁻¹' Ioo a b = Ioo a b := by simp [← Ioi_inter_Iio]
@[simp]
theorem preimage_coe_Iio_top : (some : α → WithTop α) ⁻¹' Iio ⊤ = univ := by
rw [← range_coe, preimage_range]
@[simp]
theorem preimage_coe_Ico_top : (some : α → WithTop α) ⁻¹' Ico a ⊤ = Ici a := by
simp [← Ici_inter_Iio]
@[simp]
theorem preimage_coe_Ioo_top : (some : α → WithTop α) ⁻¹' Ioo a ⊤ = Ioi a := by
simp [← Ioi_inter_Iio]
theorem image_coe_Ioi : (some : α → WithTop α) '' Ioi a = Ioo (a : WithTop α) ⊤ := by
rw [← preimage_coe_Ioi, image_preimage_eq_inter_range, range_coe, Ioi_inter_Iio]
theorem image_coe_Ici : (some : α → WithTop α) '' Ici a = Ico (a : WithTop α) ⊤ := by
rw [← preimage_coe_Ici, image_preimage_eq_inter_range, range_coe, Ici_inter_Iio]
theorem image_coe_Iio : (some : α → WithTop α) '' Iio a = Iio (a : WithTop α) := by
rw [← preimage_coe_Iio, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left (Iio_subset_Iio le_top)]
theorem image_coe_Iic : (some : α → WithTop α) '' Iic a = Iic (a : WithTop α) := by
rw [← preimage_coe_Iic, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left (Iic_subset_Iio.2 <| coe_lt_top a)]
theorem image_coe_Icc : (some : α → WithTop α) '' Icc a b = Icc (a : WithTop α) b := by
rw [← preimage_coe_Icc, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left
(Subset.trans Icc_subset_Iic_self <| Iic_subset_Iio.2 <| coe_lt_top b)]
theorem image_coe_Ico : (some : α → WithTop α) '' Ico a b = Ico (a : WithTop α) b := by
rw [← preimage_coe_Ico, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left (Subset.trans Ico_subset_Iio_self <| Iio_subset_Iio le_top)]
theorem image_coe_Ioc : (some : α → WithTop α) '' Ioc a b = Ioc (a : WithTop α) b := by
rw [← preimage_coe_Ioc, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left
(Subset.trans Ioc_subset_Iic_self <| Iic_subset_Iio.2 <| coe_lt_top b)]
theorem image_coe_Ioo : (some : α → WithTop α) '' Ioo a b = Ioo (a : WithTop α) b := by
rw [← preimage_coe_Ioo, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left (Subset.trans Ioo_subset_Iio_self <| Iio_subset_Iio le_top)]
end WithTop
/-! ### `WithBot` -/
namespace WithBot
@[simp]
theorem preimage_coe_bot : (some : α → WithBot α) ⁻¹' {⊥} = (∅ : Set α) :=
@WithTop.preimage_coe_top αᵒᵈ
variable [Preorder α] {a b : α}
theorem range_coe : range (some : α → WithBot α) = Ioi ⊥ :=
@WithTop.range_coe αᵒᵈ _
@[simp]
theorem preimage_coe_Ioi : (some : α → WithBot α) ⁻¹' Ioi a = Ioi a :=
ext fun _ => coe_lt_coe
@[simp]
theorem preimage_coe_Ici : (some : α → WithBot α) ⁻¹' Ici a = Ici a :=
ext fun _ => coe_le_coe
@[simp]
theorem preimage_coe_Iio : (some : α → WithBot α) ⁻¹' Iio a = Iio a :=
ext fun _ => coe_lt_coe
@[simp]
theorem preimage_coe_Iic : (some : α → WithBot α) ⁻¹' Iic a = Iic a :=
ext fun _ => coe_le_coe
@[simp]
theorem preimage_coe_Icc : (some : α → WithBot α) ⁻¹' Icc a b = Icc a b := by simp [← Ici_inter_Iic]
@[simp]
theorem preimage_coe_Ico : (some : α → WithBot α) ⁻¹' Ico a b = Ico a b := by simp [← Ici_inter_Iio]
@[simp]
theorem preimage_coe_Ioc : (some : α → WithBot α) ⁻¹' Ioc a b = Ioc a b := by simp [← Ioi_inter_Iic]
@[simp]
theorem preimage_coe_Ioo : (some : α → WithBot α) ⁻¹' Ioo a b = Ioo a b := by simp [← Ioi_inter_Iio]
@[simp]
theorem preimage_coe_Ioi_bot : (some : α → WithBot α) ⁻¹' Ioi ⊥ = univ := by
rw [← range_coe, preimage_range]
@[simp]
theorem preimage_coe_Ioc_bot : (some : α → WithBot α) ⁻¹' Ioc ⊥ a = Iic a := by
simp [← Ioi_inter_Iic]
@[simp]
theorem preimage_coe_Ioo_bot : (some : α → WithBot α) ⁻¹' Ioo ⊥ a = Iio a := by
simp [← Ioi_inter_Iio]
theorem image_coe_Iio : (some : α → WithBot α) '' Iio a = Ioo (⊥ : WithBot α) a := by
rw [← preimage_coe_Iio, image_preimage_eq_inter_range, range_coe, inter_comm, Ioi_inter_Iio]
theorem image_coe_Iic : (some : α → WithBot α) '' Iic a = Ioc (⊥ : WithBot α) a := by
rw [← preimage_coe_Iic, image_preimage_eq_inter_range, range_coe, inter_comm, Ioi_inter_Iic]
theorem image_coe_Ioi : (some : α → WithBot α) '' Ioi a = Ioi (a : WithBot α) := by
rw [← preimage_coe_Ioi, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left (Ioi_subset_Ioi bot_le)]
theorem image_coe_Ici : (some : α → WithBot α) '' Ici a = Ici (a : WithBot α) := by
rw [← preimage_coe_Ici, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left (Ici_subset_Ioi.2 <| bot_lt_coe a)]
theorem image_coe_Icc : (some : α → WithBot α) '' Icc a b = Icc (a : WithBot α) b := by
rw [← preimage_coe_Icc, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left
(Subset.trans Icc_subset_Ici_self <| Ici_subset_Ioi.2 <| bot_lt_coe a)]
theorem image_coe_Ioc : (some : α → WithBot α) '' Ioc a b = Ioc (a : WithBot α) b := by
rw [← preimage_coe_Ioc, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left (Subset.trans Ioc_subset_Ioi_self <| Ioi_subset_Ioi bot_le)]
theorem image_coe_Ico : (some : α → WithBot α) '' Ico a b = Ico (a : WithBot α) b := by
rw [← preimage_coe_Ico, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left
(Subset.trans Ico_subset_Ici_self <| Ici_subset_Ioi.2 <| bot_lt_coe a)]
theorem image_coe_Ioo : (some : α → WithBot α) '' Ioo a b = Ioo (a : WithBot α) b := by
rw [← preimage_coe_Ioo, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left (Subset.trans Ioo_subset_Ioi_self <| Ioi_subset_Ioi bot_le)]
end WithBot
|
Basic.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.Analysis.Complex.Circle
import Mathlib.Analysis.NormedSpace.BallAction
/-!
# Poincaré disc
In this file we define `Complex.UnitDisc` to be the unit disc in the complex plane. We also
introduce some basic operations on this disc.
-/
open Set Function Metric
noncomputable section
local notation "conj'" => starRingEnd ℂ
namespace Complex
/-- The complex unit disc, denoted as `𝔻` withinin the Complex namespace -/
def UnitDisc : Type :=
ball (0 : ℂ) 1 deriving TopologicalSpace
@[inherit_doc] scoped[UnitDisc] notation "𝔻" => Complex.UnitDisc
open UnitDisc
namespace UnitDisc
/-- Coercion to `ℂ`. -/
@[coe] protected def coe : 𝔻 → ℂ := Subtype.val
instance instCommSemigroup : CommSemigroup UnitDisc := by unfold UnitDisc; infer_instance
instance instSemigroupWithZero : SemigroupWithZero UnitDisc := by unfold UnitDisc; infer_instance
instance instIsCancelMulZero : IsCancelMulZero UnitDisc := by unfold UnitDisc; infer_instance
instance instHasDistribNeg : HasDistribNeg UnitDisc := by unfold UnitDisc; infer_instance
instance instCoe : Coe UnitDisc ℂ := ⟨UnitDisc.coe⟩
theorem coe_injective : Injective ((↑) : 𝔻 → ℂ) :=
Subtype.coe_injective
@[simp, norm_cast]
theorem coe_inj {z w : 𝔻} : (z : ℂ) = w ↔ z = w := Subtype.val_inj
theorem norm_lt_one (z : 𝔻) : ‖(z : ℂ)‖ < 1 :=
mem_ball_zero_iff.1 z.2
theorem norm_ne_one (z : 𝔻) : ‖(z : ℂ)‖ ≠ 1 :=
z.norm_lt_one.ne
@[deprecated (since := "2025-02-16")] alias abs_lt_one := norm_lt_one
@[deprecated (since := "2025-02-16")] alias abs_ne_one := norm_ne_one
theorem normSq_lt_one (z : 𝔻) : normSq z < 1 := by
convert (Real.sqrt_lt' one_pos).1 z.norm_lt_one
exact (one_pow 2).symm
theorem coe_ne_one (z : 𝔻) : (z : ℂ) ≠ 1 :=
ne_of_apply_ne (‖·‖) <| by simp [z.norm_ne_one]
theorem coe_ne_neg_one (z : 𝔻) : (z : ℂ) ≠ -1 :=
ne_of_apply_ne (‖·‖) <| by simpa [norm_neg] using z.norm_ne_one
theorem one_add_coe_ne_zero (z : 𝔻) : (1 + z : ℂ) ≠ 0 :=
mt neg_eq_iff_add_eq_zero.2 z.coe_ne_neg_one.symm
@[simp, norm_cast]
theorem coe_mul (z w : 𝔻) : ↑(z * w) = (z * w : ℂ) :=
rfl
/-- A constructor that assumes `‖z‖ < 1` instead of `dist z 0 < 1` and returns an element
of `𝔻` instead of `↥Metric.ball (0 : ℂ) 1`. -/
def mk (z : ℂ) (hz : ‖z‖ < 1) : 𝔻 :=
⟨z, mem_ball_zero_iff.2 hz⟩
@[simp]
theorem coe_mk (z : ℂ) (hz : ‖z‖ < 1) : (mk z hz : ℂ) = z :=
rfl
@[simp]
theorem mk_coe (z : 𝔻) (hz : ‖(z : ℂ)‖ < 1 := z.norm_lt_one) : mk z hz = z :=
Subtype.eta _ _
@[simp]
theorem mk_neg (z : ℂ) (hz : ‖-z‖ < 1) : mk (-z) hz = -mk z (norm_neg z ▸ hz) :=
rfl
@[simp]
theorem coe_zero : ((0 : 𝔻) : ℂ) = 0 :=
rfl
@[simp]
theorem coe_eq_zero {z : 𝔻} : (z : ℂ) = 0 ↔ z = 0 :=
coe_injective.eq_iff' coe_zero
@[simp] theorem mk_zero : mk 0 (by simp) = 0 := rfl
@[simp] theorem mk_eq_zero {z : ℂ} (hz : ‖z‖ < 1) : mk z hz = 0 ↔ z = 0 := by simp [← coe_inj]
instance : Inhabited 𝔻 :=
⟨0⟩
instance circleAction : MulAction Circle 𝔻 :=
mulActionSphereBall
instance isScalarTower_circle_circle : IsScalarTower Circle Circle 𝔻 :=
isScalarTower_sphere_sphere_ball
instance isScalarTower_circle : IsScalarTower Circle 𝔻 𝔻 :=
isScalarTower_sphere_ball_ball
instance instSMulCommClass_circle : SMulCommClass Circle 𝔻 𝔻 :=
instSMulCommClass_sphere_ball_ball
instance instSMulCommClass_circle' : SMulCommClass 𝔻 Circle 𝔻 :=
SMulCommClass.symm _ _ _
@[simp, norm_cast]
theorem coe_smul_circle (z : Circle) (w : 𝔻) : ↑(z • w) = (z * w : ℂ) :=
rfl
instance closedBallAction : MulAction (closedBall (0 : ℂ) 1) 𝔻 :=
mulActionClosedBallBall
instance isScalarTower_closedBall_closedBall :
IsScalarTower (closedBall (0 : ℂ) 1) (closedBall (0 : ℂ) 1) 𝔻 :=
isScalarTower_closedBall_closedBall_ball
instance isScalarTower_closedBall : IsScalarTower (closedBall (0 : ℂ) 1) 𝔻 𝔻 :=
isScalarTower_closedBall_ball_ball
instance instSMulCommClass_closedBall : SMulCommClass (closedBall (0 : ℂ) 1) 𝔻 𝔻 :=
⟨fun _ _ _ => Subtype.ext <| mul_left_comm _ _ _⟩
instance instSMulCommClass_closedBall' : SMulCommClass 𝔻 (closedBall (0 : ℂ) 1) 𝔻 :=
SMulCommClass.symm _ _ _
instance instSMulCommClass_circle_closedBall : SMulCommClass Circle (closedBall (0 : ℂ) 1) 𝔻 :=
instSMulCommClass_sphere_closedBall_ball
instance instSMulCommClass_closedBall_circle : SMulCommClass (closedBall (0 : ℂ) 1) Circle 𝔻 :=
SMulCommClass.symm _ _ _
@[simp, norm_cast]
theorem coe_smul_closedBall (z : closedBall (0 : ℂ) 1) (w : 𝔻) : ↑(z • w) = (z * w : ℂ) :=
rfl
/-- Real part of a point of the unit disc. -/
def re (z : 𝔻) : ℝ :=
Complex.re z
/-- Imaginary part of a point of the unit disc. -/
def im (z : 𝔻) : ℝ :=
Complex.im z
@[simp, norm_cast]
theorem re_coe (z : 𝔻) : (z : ℂ).re = z.re :=
rfl
@[simp, norm_cast]
theorem im_coe (z : 𝔻) : (z : ℂ).im = z.im :=
rfl
@[simp]
theorem re_neg (z : 𝔻) : (-z).re = -z.re :=
rfl
@[simp]
theorem im_neg (z : 𝔻) : (-z).im = -z.im :=
rfl
/-- Conjugate point of the unit disc. -/
def conj (z : 𝔻) : 𝔻 :=
mk (conj' ↑z) <| (norm_conj z).symm ▸ z.norm_lt_one
@[simp]
theorem coe_conj (z : 𝔻) : (z.conj : ℂ) = conj' ↑z :=
rfl
@[simp]
theorem conj_zero : conj 0 = 0 :=
coe_injective (map_zero conj')
@[simp]
theorem conj_conj (z : 𝔻) : conj (conj z) = z :=
coe_injective <| Complex.conj_conj (z : ℂ)
@[simp]
theorem conj_neg (z : 𝔻) : (-z).conj = -z.conj :=
rfl
@[simp]
theorem re_conj (z : 𝔻) : z.conj.re = z.re :=
rfl
@[simp]
theorem im_conj (z : 𝔻) : z.conj.im = -z.im :=
rfl
@[simp]
theorem conj_mul (z w : 𝔻) : (z * w).conj = z.conj * w.conj :=
Subtype.ext <| map_mul _ _ _
end UnitDisc
end Complex
|
Basic.lean
|
/-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser, Kevin Buzzard, Jujian Zhang, Fangming Li
-/
import Mathlib.Algebra.DirectSum.Algebra
import Mathlib.Algebra.DirectSum.Decomposition
import Mathlib.Algebra.DirectSum.Internal
import Mathlib.Algebra.DirectSum.Ring
/-!
# Internally-graded rings and algebras
This file defines the typeclass `GradedAlgebra 𝒜`, for working with an algebra `A` that is
internally graded by a collection of submodules `𝒜 : ι → Submodule R A`.
See the docstring of that typeclass for more information.
## Main definitions
* `GradedRing 𝒜`: the typeclass, which is a combination of `SetLike.GradedMonoid`, and
`DirectSum.Decomposition 𝒜`.
* `GradedAlgebra 𝒜`: A convenience alias for `GradedRing` when `𝒜` is a family of submodules.
* `DirectSum.decomposeRingEquiv 𝒜 : A ≃ₐ[R] ⨁ i, 𝒜 i`, a more bundled version of
`DirectSum.decompose 𝒜`.
* `DirectSum.decomposeAlgEquiv 𝒜 : A ≃ₐ[R] ⨁ i, 𝒜 i`, a more bundled version of
`DirectSum.decompose 𝒜`.
* `GradedAlgebra.proj 𝒜 i` is the linear map from `A` to its degree `i : ι` component, such that
`proj 𝒜 i x = decompose 𝒜 x i`.
## Implementation notes
For now, we do not have internally-graded semirings and internally-graded rings; these can be
represented with `𝒜 : ι → Submodule ℕ A` and `𝒜 : ι → Submodule ℤ A` respectively, since all
`Semiring`s are ℕ-algebras via `Semiring.toNatAlgebra`, and all `Ring`s are `ℤ`-algebras via
`Ring.toIntAlgebra`.
## Tags
graded algebra, graded ring, graded semiring, decomposition
-/
open DirectSum
variable {ι R A σ : Type*}
section GradedRing
variable [DecidableEq ι] [AddMonoid ι] [CommSemiring R] [Semiring A] [Algebra R A]
variable [SetLike σ A] [AddSubmonoidClass σ A] (𝒜 : ι → σ)
open DirectSum
/-- An internally-graded `R`-algebra `A` is one that can be decomposed into a collection
of `Submodule R A`s indexed by `ι` such that the canonical map `A → ⨁ i, 𝒜 i` is bijective and
respects multiplication, i.e. the product of an element of degree `i` and an element of degree `j`
is an element of degree `i + j`.
Note that the fact that `A` is internally-graded, `GradedAlgebra 𝒜`, implies an externally-graded
algebra structure `DirectSum.GAlgebra R (fun i ↦ ↥(𝒜 i))`, which in turn makes available an
`Algebra R (⨁ i, 𝒜 i)` instance.
-/
class GradedRing (𝒜 : ι → σ) extends SetLike.GradedMonoid 𝒜, DirectSum.Decomposition 𝒜
variable [GradedRing 𝒜]
namespace DirectSum
/-- If `A` is graded by `ι` with degree `i` component `𝒜 i`, then it is isomorphic as
a ring to a direct sum of components. -/
def decomposeRingEquiv : A ≃+* ⨁ i, 𝒜 i :=
RingEquiv.symm
{ (decomposeAddEquiv 𝒜).symm with
map_mul' := (coeRingHom 𝒜).map_mul }
@[simp]
theorem decompose_one : decompose 𝒜 (1 : A) = 1 :=
map_one (decomposeRingEquiv 𝒜)
@[simp]
theorem decompose_symm_one : (decompose 𝒜).symm 1 = (1 : A) :=
map_one (decomposeRingEquiv 𝒜).symm
@[simp]
theorem decompose_mul (x y : A) : decompose 𝒜 (x * y) = decompose 𝒜 x * decompose 𝒜 y :=
map_mul (decomposeRingEquiv 𝒜) x y
@[simp]
theorem decompose_symm_mul (x y : ⨁ i, 𝒜 i) :
(decompose 𝒜).symm (x * y) = (decompose 𝒜).symm x * (decompose 𝒜).symm y :=
map_mul (decomposeRingEquiv 𝒜).symm x y
end DirectSum
/-- The projection maps of a graded ring -/
def GradedRing.proj (i : ι) : A →+ A :=
(AddSubmonoidClass.subtype (𝒜 i)).comp <|
(DFinsupp.evalAddMonoidHom i).comp <|
RingHom.toAddMonoidHom <| RingEquiv.toRingHom <| DirectSum.decomposeRingEquiv 𝒜
@[simp]
theorem GradedRing.proj_apply (i : ι) (r : A) :
GradedRing.proj 𝒜 i r = (decompose 𝒜 r : ⨁ i, 𝒜 i) i :=
rfl
theorem GradedRing.proj_recompose (a : ⨁ i, 𝒜 i) (i : ι) :
GradedRing.proj 𝒜 i ((decompose 𝒜).symm a) = (decompose 𝒜).symm (DirectSum.of _ i (a i)) := by
rw [GradedRing.proj_apply, decompose_symm_of, Equiv.apply_symm_apply]
theorem GradedRing.mem_support_iff [∀ (i) (x : 𝒜 i), Decidable (x ≠ 0)] (r : A) (i : ι) :
i ∈ (decompose 𝒜 r).support ↔ GradedRing.proj 𝒜 i r ≠ 0 :=
DFinsupp.mem_support_iff.trans ZeroMemClass.coe_eq_zero.not.symm
end GradedRing
section AddCancelMonoid
open DirectSum
variable [DecidableEq ι] [Semiring A] [SetLike σ A] [AddSubmonoidClass σ A] (𝒜 : ι → σ)
variable {i j : ι}
namespace DirectSum
theorem coe_decompose_mul_add_of_left_mem [AddLeftCancelMonoid ι] [GradedRing 𝒜] {a b : A}
(a_mem : a ∈ 𝒜 i) : (decompose 𝒜 (a * b) (i + j) : A) = a * decompose 𝒜 b j := by
lift a to 𝒜 i using a_mem
rw [decompose_mul, decompose_coe, coe_of_mul_apply_add]
theorem coe_decompose_mul_add_of_right_mem [AddRightCancelMonoid ι] [GradedRing 𝒜] {a b : A}
(b_mem : b ∈ 𝒜 j) : (decompose 𝒜 (a * b) (i + j) : A) = decompose 𝒜 a i * b := by
lift b to 𝒜 j using b_mem
rw [decompose_mul, decompose_coe, coe_mul_of_apply_add]
theorem decompose_mul_add_left [AddLeftCancelMonoid ι] [GradedRing 𝒜] (a : 𝒜 i) {b : A} :
decompose 𝒜 (↑a * b) (i + j) =
@GradedMonoid.GMul.mul ι (fun i => 𝒜 i) _ _ _ _ a (decompose 𝒜 b j) :=
Subtype.ext <| coe_decompose_mul_add_of_left_mem 𝒜 a.2
theorem decompose_mul_add_right [AddRightCancelMonoid ι] [GradedRing 𝒜] {a : A} (b : 𝒜 j) :
decompose 𝒜 (a * ↑b) (i + j) =
@GradedMonoid.GMul.mul ι (fun i => 𝒜 i) _ _ _ _ (decompose 𝒜 a i) b :=
Subtype.ext <| coe_decompose_mul_add_of_right_mem 𝒜 b.2
theorem coe_decompose_mul_of_left_mem_zero [AddMonoid ι] [GradedRing 𝒜] {a b : A}
(a_mem : a ∈ 𝒜 0) : (decompose 𝒜 (a * b) j : A) = a * decompose 𝒜 b j := by
lift a to 𝒜 0 using a_mem
rw [decompose_mul, decompose_coe, coe_of_mul_apply_of_mem_zero]
theorem coe_decompose_mul_of_right_mem_zero [AddMonoid ι] [GradedRing 𝒜] {a b : A}
(b_mem : b ∈ 𝒜 0) : (decompose 𝒜 (a * b) i : A) = decompose 𝒜 a i * b := by
lift b to 𝒜 0 using b_mem
rw [decompose_mul, decompose_coe, coe_mul_of_apply_of_mem_zero]
end DirectSum
end AddCancelMonoid
section GradedAlgebra
variable [DecidableEq ι] [AddMonoid ι] [CommSemiring R] [Semiring A] [Algebra R A]
variable (𝒜 : ι → Submodule R A)
/-- A special case of `GradedRing` with `σ = Submodule R A`. This is useful both because it
can avoid typeclass search, and because it provides a more concise name. -/
abbrev GradedAlgebra :=
GradedRing 𝒜
/-- A helper to construct a `GradedAlgebra` when the `SetLike.GradedMonoid` structure is already
available. This makes the `left_inv` condition easier to prove, and phrases the `right_inv`
condition in a way that allows custom `@[ext]` lemmas to apply.
See note [reducible non-instances]. -/
abbrev GradedAlgebra.ofAlgHom [SetLike.GradedMonoid 𝒜] (decompose : A →ₐ[R] ⨁ i, 𝒜 i)
(right_inv : (DirectSum.coeAlgHom 𝒜).comp decompose = AlgHom.id R A)
(left_inv : ∀ i (x : 𝒜 i), decompose (x : A) = DirectSum.of (fun i => ↥(𝒜 i)) i x) :
GradedAlgebra 𝒜 where
decompose' := decompose
left_inv := AlgHom.congr_fun right_inv
right_inv := by
suffices decompose.comp (DirectSum.coeAlgHom 𝒜) = AlgHom.id _ _ from AlgHom.congr_fun this
ext i x : 2
exact (decompose.congr_arg <| DirectSum.coeAlgHom_of _ _ _).trans (left_inv i x)
variable [GradedAlgebra 𝒜]
namespace DirectSum
/-- If `A` is graded by `ι` with degree `i` component `𝒜 i`, then it is isomorphic as
an algebra to a direct sum of components. -/
-- Porting note: deleted [simps] and added the corresponding lemmas by hand
def decomposeAlgEquiv : A ≃ₐ[R] ⨁ i, 𝒜 i :=
AlgEquiv.symm
{ (decomposeAddEquiv 𝒜).symm with
map_mul' := map_mul (coeAlgHom 𝒜)
commutes' := (coeAlgHom 𝒜).commutes }
@[simp]
lemma decomposeAlgEquiv_apply (a : A) :
decomposeAlgEquiv 𝒜 a = decompose 𝒜 a := rfl
@[simp]
lemma decomposeAlgEquiv_symm_apply (a : ⨁ i, 𝒜 i) :
(decomposeAlgEquiv 𝒜).symm a = (decompose 𝒜).symm a := rfl
@[simp]
lemma decompose_algebraMap (r : R) :
decompose 𝒜 (algebraMap R A r) = algebraMap R (⨁ i, 𝒜 i) r :=
(decomposeAlgEquiv 𝒜).commutes r
@[simp]
lemma decompose_symm_algebraMap (r : R) :
(decompose 𝒜).symm (algebraMap R (⨁ i, 𝒜 i) r) = algebraMap R A r :=
(decomposeAlgEquiv 𝒜).symm.commutes r
end DirectSum
open DirectSum
/-- The projection maps of graded algebra -/
def GradedAlgebra.proj (𝒜 : ι → Submodule R A) [GradedAlgebra 𝒜] (i : ι) : A →ₗ[R] A :=
(𝒜 i).subtype.comp <| (DFinsupp.lapply i).comp <| (decomposeAlgEquiv 𝒜).toAlgHom.toLinearMap
@[simp]
theorem GradedAlgebra.proj_apply (i : ι) (r : A) :
GradedAlgebra.proj 𝒜 i r = (decompose 𝒜 r : ⨁ i, 𝒜 i) i :=
rfl
theorem GradedAlgebra.proj_recompose (a : ⨁ i, 𝒜 i) (i : ι) :
GradedAlgebra.proj 𝒜 i ((decompose 𝒜).symm a) = (decompose 𝒜).symm (of _ i (a i)) := by
rw [GradedAlgebra.proj_apply, decompose_symm_of, Equiv.apply_symm_apply]
theorem GradedAlgebra.mem_support_iff [DecidableEq A] (r : A) (i : ι) :
i ∈ (decompose 𝒜 r).support ↔ GradedAlgebra.proj 𝒜 i r ≠ 0 :=
DFinsupp.mem_support_iff.trans Submodule.coe_eq_zero.not.symm
end GradedAlgebra
section CanonicalOrder
open SetLike.GradedMonoid DirectSum
variable [Semiring A] [DecidableEq ι]
variable [AddCommMonoid ι] [PartialOrder ι] [CanonicallyOrderedAdd ι]
variable [SetLike σ A] [AddSubmonoidClass σ A] (𝒜 : ι → σ) [GradedRing 𝒜]
/-- If `A` is graded by a canonically ordered add monoid, then the projection map `x ↦ x₀` is a ring
homomorphism.
-/
@[simps]
def GradedRing.projZeroRingHom : A →+* A where
toFun a := decompose 𝒜 a 0
map_one' :=
-- Porting note: qualified `one_mem`
decompose_of_mem_same 𝒜 SetLike.GradedOne.one_mem
map_zero' := by
simp only -- Porting note: added
rw [decompose_zero]
rfl
map_add' _ _ := by
simp only -- Porting note: added
rw [decompose_add]
rfl
map_mul' := by
refine DirectSum.Decomposition.inductionOn 𝒜 (fun x => ?_) ?_ ?_
· simp only [zero_mul, decompose_zero, zero_apply, ZeroMemClass.coe_zero]
· rintro i ⟨c, hc⟩
refine DirectSum.Decomposition.inductionOn 𝒜 ?_ ?_ ?_
· simp only [mul_zero, decompose_zero, zero_apply, ZeroMemClass.coe_zero]
· rintro j ⟨c', hc'⟩
simp only
by_cases h : i + j = 0
· rw [decompose_of_mem_same 𝒜
(show c * c' ∈ 𝒜 0 from h ▸ SetLike.GradedMul.mul_mem hc hc'),
decompose_of_mem_same 𝒜 (show c ∈ 𝒜 0 from (add_eq_zero.mp h).1 ▸ hc),
decompose_of_mem_same 𝒜 (show c' ∈ 𝒜 0 from (add_eq_zero.mp h).2 ▸ hc')]
· rw [decompose_of_mem_ne 𝒜 (SetLike.GradedMul.mul_mem hc hc') h]
rcases show i ≠ 0 ∨ j ≠ 0 by rwa [add_eq_zero, not_and_or] at h with h' | h'
· simp only [decompose_of_mem_ne 𝒜 hc h', zero_mul]
· simp only [decompose_of_mem_ne 𝒜 hc' h', mul_zero]
· intro _ _ hd he
simp only at hd he -- Porting note: added
simp only [mul_add, decompose_add, add_apply, AddMemClass.coe_add, hd, he]
· rintro _ _ ha hb _
simp only at ha hb -- Porting note: added
simp only [add_mul, decompose_add, add_apply, AddMemClass.coe_add, ha, hb]
section GradeZero
/-- The ring homomorphism from `A` to `𝒜 0` sending every `a : A` to `a₀`. -/
def GradedRing.projZeroRingHom' : A →+* 𝒜 0 :=
((GradedRing.projZeroRingHom 𝒜).codRestrict _ fun _x => SetLike.coe_mem _ :
A →+* SetLike.GradeZero.subsemiring 𝒜)
@[simp] lemma GradedRing.coe_projZeroRingHom'_apply (a : A) :
(GradedRing.projZeroRingHom' 𝒜 a : A) = GradedRing.projZeroRingHom 𝒜 a := rfl
@[simp] lemma GradedRing.projZeroRingHom'_apply_coe (a : 𝒜 0) :
GradedRing.projZeroRingHom' 𝒜 a = a := by
ext; simp only [coe_projZeroRingHom'_apply, projZeroRingHom_apply, decompose_coe, of_eq_same]
/-- The ring homomorphism `GradedRing.projZeroRingHom' 𝒜` is surjective. -/
lemma GradedRing.projZeroRingHom'_surjective :
Function.Surjective (GradedRing.projZeroRingHom' 𝒜) :=
Function.RightInverse.surjective (GradedRing.projZeroRingHom'_apply_coe 𝒜)
end GradeZero
variable {a b : A} {n i : ι}
namespace DirectSum
theorem coe_decompose_mul_of_left_mem_of_not_le (a_mem : a ∈ 𝒜 i) (h : ¬i ≤ n) :
(decompose 𝒜 (a * b) n : A) = 0 := by
lift a to 𝒜 i using a_mem
rwa [decompose_mul, decompose_coe, coe_of_mul_apply_of_not_le]
theorem coe_decompose_mul_of_right_mem_of_not_le (b_mem : b ∈ 𝒜 i) (h : ¬i ≤ n) :
(decompose 𝒜 (a * b) n : A) = 0 := by
lift b to 𝒜 i using b_mem
rwa [decompose_mul, decompose_coe, coe_mul_of_apply_of_not_le]
variable [Sub ι] [OrderedSub ι] [AddLeftReflectLE ι]
theorem coe_decompose_mul_of_left_mem_of_le (a_mem : a ∈ 𝒜 i) (h : i ≤ n) :
(decompose 𝒜 (a * b) n : A) = a * decompose 𝒜 b (n - i) := by
lift a to 𝒜 i using a_mem
rwa [decompose_mul, decompose_coe, coe_of_mul_apply_of_le]
theorem coe_decompose_mul_of_right_mem_of_le (b_mem : b ∈ 𝒜 i) (h : i ≤ n) :
(decompose 𝒜 (a * b) n : A) = decompose 𝒜 a (n - i) * b := by
lift b to 𝒜 i using b_mem
rwa [decompose_mul, decompose_coe, coe_mul_of_apply_of_le]
theorem coe_decompose_mul_of_left_mem (n) [Decidable (i ≤ n)] (a_mem : a ∈ 𝒜 i) :
(decompose 𝒜 (a * b) n : A) = if i ≤ n then a * decompose 𝒜 b (n - i) else 0 := by
lift a to 𝒜 i using a_mem
rw [decompose_mul, decompose_coe, coe_of_mul_apply]
theorem coe_decompose_mul_of_right_mem (n) [Decidable (i ≤ n)] (b_mem : b ∈ 𝒜 i) :
(decompose 𝒜 (a * b) n : A) = if i ≤ n then decompose 𝒜 a (n - i) * b else 0 := by
lift b to 𝒜 i using b_mem
rw [decompose_mul, decompose_coe, coe_mul_of_apply]
end DirectSum
end CanonicalOrder
namespace DirectSum.IsInternal
variable {R : Type*} [CommSemiring R] {A : Type*} [Semiring A] [Algebra R A]
variable {ι : Type*} [DecidableEq ι] [AddMonoid ι]
variable {M : ι → Submodule R A} [SetLike.GradedMonoid M]
-- The following lines were given on Zulip by Adam Topaz
/-- The canonical isomorphism of an internal direct sum with the ambient algebra -/
noncomputable def coeAlgEquiv (hM : DirectSum.IsInternal M) :
(DirectSum ι fun i => ↥(M i)) ≃ₐ[R] A :=
{ RingEquiv.ofBijective (DirectSum.coeAlgHom M) hM with commutes' := fun r => by simp }
/-- Given an `R`-algebra `A` and a family `ι → Submodule R A` of submodules
parameterized by an additive monoid `ι`
and satisfying `SetLike.GradedMonoid M` (essentially, is multiplicative)
such that `DirectSum.IsInternal M` (`A` is the direct sum of the `M i`),
we endow `A` with the structure of a graded algebra.
The submodules are the *homogeneous* parts. -/
noncomputable def gradedAlgebra (hM : DirectSum.IsInternal M) : GradedAlgebra M :=
{ (inferInstance : SetLike.GradedMonoid M) with
decompose' := hM.coeAlgEquiv.symm
left_inv := hM.coeAlgEquiv.symm.left_inv
right_inv := hM.coeAlgEquiv.left_inv }
end DirectSum.IsInternal
|
DivMod.lean
|
/-
Copyright (c) 2024 Lean FRO. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison
-/
import Mathlib.Init
/-!
# Basic lemmas about division and modulo for integers
-/
namespace Int
/-! ### `ediv` and `fdiv` -/
theorem mul_ediv_le_mul_ediv_assoc {a : Int} (ha : 0 ≤ a) (b : Int) {c : Int} (hc : 0 ≤ c) :
a * (b / c) ≤ a * b / c := by
obtain rfl | hlt : c = 0 ∨ 0 < c := by omega
· simp
· rw [Int.le_ediv_iff_mul_le hlt, Int.mul_assoc]
exact Int.mul_le_mul_of_nonneg_left (Int.ediv_mul_le b (Int.ne_of_gt hlt)) ha
theorem ediv_ediv_eq_ediv_mul (m : Int) {n k : Int} (hn : 0 ≤ n) :
m / n / k = m / (n * k) := by
have {k : Int} (hk : 0 < k) : m / n / k = m / (n * k) := by
obtain rfl | hn' : n = 0 ∨ 0 < n := by omega
· simp
· apply Int.le_antisymm
· apply Int.le_ediv_of_mul_le (Int.mul_pos hn' hk)
calc
m / n / k * (n * k) = m / n / k * k * n := by ac_rfl
_ ≤ m / n * n :=
Int.mul_le_mul_of_nonneg_right (Int.ediv_mul_le (m / n) (Int.ne_of_gt hk)) hn
_ ≤ m :=
Int.ediv_mul_le m (Int.ne_of_gt hn')
· apply Int.le_ediv_of_mul_le hk
rw [← Int.mul_ediv_mul_of_pos_left m n hk, Int.mul_comm m k, Int.mul_comm (_ / _) k]
apply Int.mul_ediv_le_mul_ediv_assoc
· exact Int.le_of_lt hk
· exact Int.le_of_lt <| Int.mul_pos hn' hk
· rcases Int.lt_trichotomy 0 k with hk | rfl | hk
· exact this hk
· simp
· rw [← Int.neg_neg (m / n / k), ← Int.ediv_neg, this (Int.neg_pos_of_neg hk), ← Int.ediv_neg,
Int.mul_neg, Int.neg_neg]
theorem fdiv_fdiv_eq_fdiv_mul (m : Int) {n k : Int} (hn : 0 ≤ n) (hk : 0 ≤ k) :
(m.fdiv n).fdiv k = m.fdiv (n * k) := by
rw [Int.fdiv_eq_ediv_of_nonneg _ hn,
Int.fdiv_eq_ediv_of_nonneg _ hk,
Int.fdiv_eq_ediv_of_nonneg _ (Int.mul_nonneg hn hk),
ediv_ediv_eq_ediv_mul _ hn]
/-! ### `emod` -/
theorem emod_eq_sub_self_emod {a b : Int} : a % b = (a - b) % b :=
(sub_emod_right a b).symm
end Int
|
sesquilinear.v
|
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div.
From mathcomp Require Import choice fintype tuple bigop ssralg finset fingroup.
From mathcomp Require Import zmodp poly order ssrnum matrix mxalgebra vector.
(******************************************************************************)
(* Sesquilinear forms *)
(* *)
(* e_ j := the row matrix with a 1 in column j *)
(* M ^ phi := map_mx phi M *)
(* Notation in scope sesquilinear_scope. *)
(* M ^t phi := (M ^T) ^ phi *)
(* Notation in scope sesquilinear_scope. *)
(* involutive_rmorphism R == the type of involutive functions *)
(* R has type nzRingType. *)
(* The HB class is InvolutiveRMorphism. *)
(* *)
(* {bilinear U -> U' -> V | s & s'} == the type of bilinear forms which are *)
(* essentially functions of type U -> U' -> V *)
(* U and U' are lmodType's, V is a zmodType, s and *)
(* s' are scaling operations of type R -> V -> V. *)
(* The HB class is Bilinear. *)
(* The factory bilinear_isBilinear provides a way *)
(* to instantiate a bilinear form from two *)
(* GRing.linear_for proofs. *)
(* {bilinear U -> V -> W | s } := {bilinear U -> V -> W | s.1 & s.2} *)
(* {bilinear U -> V -> W} := {bilinear U -> V -> W | *:%R & *:%R } *)
(* {biscalar U} := {bilinear U -> U -> _ | *%R & *%R } *)
(* *)
(* applyr f x := f ^~ x with f : U -> U' -> V *)
(* form theta M u v == form defined from a matrix M *)
(* := (u *m M *m (v ^t theta)) 0 0 *)
(* u and v are row vectors, M is a square matrix, *)
(* coefficients have type R : fieldType, *)
(* theta is a morphism *)
(* *)
(* {hermitian U for eps & theta} == hermitian/skew-hermitian form *)
(* eps is a boolean flag, *)
(* (false -> hermitian, true -> skew-hermitian), *)
(* theta is a function R -> R (R : nzRingType). *)
(* The HB class is Hermitian. *)
(* *%R is used as a the first scaling operator. *)
(* theta \; *R is used as the second scaling *)
(* operation of the bilinear form. *)
(* The archetypal case is theta being the complex *)
(* conjugate. *)
(* *)
(* M \is (eps, theta).-sesqui == M is a sesquilinear form *)
(* *)
(* orthomx theta M B == M-orthogonal complement of B *)
(* := kermx (M *m B ^t theta) *)
(* M is a square matrix representing a sesquilinear *)
(* form, B is a rectangle matrix representing a *)
(* subspace *)
(* (local notation: B ^_|_) *)
(* ortho theta M B == orthomx theta M B with theta a morphism *)
(* A '_|_ B := (A%MS <= B^_|_)%MS *)
(* This is a local notation. *)
(* rad theta M := ortho theta M 1%:M *)
(* (local notation: 1%:M^_|_) *)
(* *)
(* {symmetric U} == symmetric form *)
(* := {hermitian U for false & idfun} *)
(* {skew_symmetric U} == skew-symmetric form *)
(* := {hermitian U for true & idfun} *)
(* {hermitian_sym U for theta} := hermitian form using theta (eps = false) *)
(* {dot U for theta} == type of positive definite forms *)
(* The HB class is Dot. *)
(* *)
(* is_skew eps theta form := eps = true /\ theta = idfun *)
(* is_sym eps theta form := eps = false /\ theta = idfun *)
(* is_hermsym eps theta form := eps = false *)
(* *)
(* ortho_rec s1 s2 := elements of s1 and s2 are pairwise orthogonal *)
(* pairwise_orthogonal s == elements of s are pairwise orthogonal and *)
(* s does not contain 0 *)
(* orthogonal s1 s2 == the inner product of an element of S1 and *)
(* an element of S2 is 0 *)
(* := ortho_rec s1 s2 *)
(* orthonormal s == s is an orthonormal set of unit vectors *)
(* *)
(* isometry form1 form2 tau == tau is an isometry from form1 to form2 *)
(* form1 and form2 are hermitian forms. *)
(* {in D, isometry tau, to R} == local notation for now *)
(* *)
(* orthov (V : {vspace vT}) == the space orthogonal to V *)
(* *)
(* In the following definitions, we have f : {hermitian vT for eps & theta} *)
(* with vT : vectType F (F : fieldType): *)
(* nondegenerate f == f is non-degenerated *)
(* is_symplectic f == f is a symplectic bilinear form *)
(* is_orthogonal f == f is an orthogonal form *)
(* is_unitary f == f is a unitary form *)
(* *)
(* form_of_matrix theta M U V := \tr (U *m M *m (V ^t theta)) *)
(* matrix_of_form f := \matrix_(i, j) form 'e_i 'e_j *)
(* M \is hermitianmx eps theta == same as M \is (eps, theta).-sesqui *)
(* without the constraint that theta is a morphism *)
(* *)
(* symmetricmx := hermitianmx _ false idfun *)
(* skewmx := hermitianmx _ true idfun *)
(* hermsymmx := hermitianmx _ false conjC *)
(* *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Reserved Notation "M ^t phi"
(at level 39, left associativity, format "M ^t phi").
Reserved Notation "A ^!" (format "A ^!").
Reserved Notation "A ^_|_" (format "A ^_|_").
Reserved Notation "A ''_|_' B" (at level 69, format "A ''_|_' B").
Reserved Notation "eps_theta .-sesqui" (format "eps_theta .-sesqui").
Local Open Scope ring_scope.
Import GRing.Theory Order.Theory Num.Theory.
Notation "''e_' j" := (delta_mx 0 j)
(format "''e_' j", at level 8, j at level 2) : ring_scope.
Declare Scope sesquilinear_scope.
Delimit Scope sesquilinear_scope with sesqui.
Local Open Scope sesquilinear_scope.
Notation "M ^ phi" := (map_mx phi M) : sesquilinear_scope.
Notation "M ^t phi" := ((M ^T) ^ phi) : sesquilinear_scope.
(* TODO: move? *)
Lemma eq_map_mx_id (R : nzRingType) m n (M : 'M[R]_(m, n)) (f : R -> R) :
f =1 id -> M ^ f = M.
Proof. by move=> /eq_map_mx->; rewrite map_mx_id. Qed.
HB.mixin Record isInvolutive (R : nzRingType) (f : R -> R) :=
{ involutive_subproof : involutive f }.
(* TODO: move? *)
#[short(type="involutive_rmorphism")]
HB.structure Definition InvolutiveRMorphism (R : nzRingType) :=
{ f of @GRing.RMorphism R R f & @isInvolutive R f }.
Section InvolutiveTheory.
Variable R : nzRingType.
Let idfunK : involutive (@idfun R). Proof. by []. Qed.
HB.instance Definition _ := isInvolutive.Build _ _ idfunK.
Lemma rmorphK (f : involutive_rmorphism R) : involutive f.
Proof. by move: f => [? [? ? []]]. Qed.
End InvolutiveTheory.
Definition conjC {C : numClosedFieldType} (c : C) : C := c^*.
HB.instance Definition _ (C : numClosedFieldType) :=
GRing.RMorphism.on (@conjC C).
Section conjC_involutive.
Variable C : numClosedFieldType.
Let conjCfun_involutive : involutive (@conjC C). Proof. exact: conjCK. Qed.
HB.instance Definition _ :=
isInvolutive.Build _ (@conjC C) conjCfun_involutive.
End conjC_involutive.
Lemma map_mxCK {C : numClosedFieldType} m n (A : 'M[C]_(m, n)) :
(A ^ conjC) ^ conjC = A.
Proof. by apply/matrixP=> i j; rewrite !mxE conjCK. Qed.
(*Structure revop X Y Z (f : Y -> X -> Z) := RevOp {
fun_of_revop :> X -> Y -> Z;
_ : forall x, f x =1 fun_of_revop^~ x
}.
Notation "[ 'revop' revop 'of' op ]" :=
(@RevOp _ _ _ revop op (fun _ _ => erefl))
(format "[ 'revop' revop 'of' op ]") : form_scope.*)
HB.mixin Record isBilinear (R : nzRingType) (U U' : lmodType R) (V : zmodType)
(s : R -> V -> V) (s' : R -> V -> V) (f : U -> U' -> V) := {
zmod_morphisml_subproof : forall u', zmod_morphism (f ^~ u') ;
zmod_morphismr_subproof : forall u, zmod_morphism (f u) ;
linearl_subproof : forall u', scalable_for s (f ^~ u') ;
linearr_subproof : forall u, scalable_for s' (f u)
}.
#[short(type="bilinear")]
HB.structure Definition Bilinear (R : nzRingType) (U U' : lmodType R)
(V : zmodType) (s : R -> V -> V) (s' : R -> V -> V) :=
{f of isBilinear R U U' V s s' f}.
Definition bilinear_for (R : nzRingType) (U U' : lmodType R) (V : zmodType)
(s : GRing.Scale.law R V) (s' : GRing.Scale.law R V) (f : U -> U' -> V) :=
((forall u', GRing.linear_for (s : R -> V -> V) (f ^~ u'))
* (forall u, GRing.linear_for s' (f u)))%type.
HB.factory Record bilinear_isBilinear (R : nzRingType) (U U' : lmodType R)
(V : zmodType) (s : GRing.Scale.law R V) (s' : GRing.Scale.law R V)
(f : U -> U' -> V) := {
bilinear_subproof : bilinear_for s s' f
}.
HB.builders Context R U U' V s s' f of bilinear_isBilinear R U U' V s s' f.
HB.instance Definition _ := isBilinear.Build R U U' V s s' f
(fun u' => zmod_morphism_linear (bilinear_subproof.1 u'))
(fun u => zmod_morphism_linear (bilinear_subproof.2 u))
(fun u' => scalable_linear (bilinear_subproof.1 u'))
(fun u => scalable_linear (bilinear_subproof.2 u)).
HB.end.
Module BilinearExports.
Module Bilinear.
Section bilinear.
Variables (R : nzRingType) (U U' : lmodType R) (V : zmodType) (s s' : R -> V -> V).
Local Notation bilinear f := (bilinear_for *:%R *:%R f).
Local Notation biscalar f := (bilinear_for *%R *%R f).
(* Support for right-to-left rewriting with the generic linearZ rule. *)
Notation mapUUV := (@Bilinear.type R U U' V s s').
Definition map_class := mapUUV.
Definition map_at_left (a : R) := mapUUV.
Definition map_at_right (b : R) := mapUUV.
Definition map_at_both (a b : R) := mapUUV.
Structure map_for_left a s_a :=
MapForLeft {map_for_left_map : mapUUV; _ : s a = s_a }.
Structure map_for_right b s'_b :=
MapForRight {map_for_right_map : mapUUV; _ : s' b = s'_b }.
Structure map_for_both a b s_a s'_b :=
MapForBoth {map_for_both_map : mapUUV; _ : s a = s_a ; _ : s' b = s'_b }.
Definition unify_map_at_left a (f : map_at_left a) :=
MapForLeft f (erefl (s a)).
Definition unify_map_at_right b (f : map_at_right b) :=
MapForRight f (erefl (s' b)).
Definition unify_map_at_both a b (f : map_at_both a b) :=
MapForBoth f (erefl (s a)) (erefl (s' b)).
Structure wrapped := Wrap {unwrap : mapUUV}.
Definition wrap (f : map_class) := Wrap f.
End bilinear.
End Bilinear.
Notation "{ 'bilinear' U -> V -> W | s & t }" :=
(@Bilinear.type _ U%type V%type W%type s t)
(U at level 98, V at level 98, W at level 99,
format "{ 'bilinear' U -> V -> W | s & t }") : ring_scope.
Notation "{ 'bilinear' U -> V -> W | s }" :=
({bilinear U -> V -> W | s.1 & s.2})
(U at level 98, V at level 98, W at level 99,
format "{ 'bilinear' U -> V -> W | s }") : ring_scope.
Notation "{ 'bilinear' U -> V -> W }" := {bilinear U -> V -> W | *:%R & *:%R}
(U at level 98, V at level 98, W at level 99,
format "{ 'bilinear' U -> V -> W }") : ring_scope.
Notation "{ 'biscalar' U }" := {bilinear U%type -> U%type -> _ | *%R & *%R}
(format "{ 'biscalar' U }") : ring_scope.
End BilinearExports.
Export BilinearExports.
#[non_forgetful_inheritance]
HB.instance Definition _ (R : nzRingType) (U U' : lmodType R) (V : zmodType)
(s : R -> V -> V) (s' : R -> V -> V)
(f : {bilinear U -> U' -> V | s & s'}) (u : U)
:= @GRing.isZmodMorphism.Build U' V (f u) (@zmod_morphismr_subproof _ _ _ _ _ _ f u).
#[non_forgetful_inheritance]
HB.instance Definition _ (R : nzRingType) (U U' : lmodType R) (V : zmodType)
(s : R -> V -> V) (s' : R -> V -> V) (f : @bilinear R U U' V s s') (u : U)
:= @GRing.isScalable.Build _ _ _ _ (f u) (@linearr_subproof _ _ _ _ _ _ f u).
Section applyr.
Variables (R : nzRingType) (U U' : lmodType R) (V : zmodType)
(s s' : R -> V -> V).
Definition applyr_head t (f : U -> U' -> V) u v := let: tt := t in f v u.
End applyr.
Notation applyr := (applyr_head tt).
Coercion Bilinear.map_for_left_map : Bilinear.map_for_left >-> Bilinear.type.
Coercion Bilinear.map_for_right_map : Bilinear.map_for_right >-> Bilinear.type.
Coercion Bilinear.map_for_both_map : Bilinear.map_for_both >-> Bilinear.type.
Coercion Bilinear.unify_map_at_left : Bilinear.map_at_left >-> Bilinear.map_for_left.
Coercion Bilinear.unify_map_at_right : Bilinear.map_at_right >-> Bilinear.map_for_right.
Coercion Bilinear.unify_map_at_both : Bilinear.map_at_both >-> Bilinear.map_for_both.
Canonical Bilinear.unify_map_at_left.
Canonical Bilinear.unify_map_at_right.
Canonical Bilinear.unify_map_at_both.
Coercion Bilinear.unwrap : Bilinear.wrapped >-> Bilinear.type.
Coercion Bilinear.wrap : Bilinear.map_class >-> Bilinear.wrapped.
Canonical Bilinear.wrap.
Section BilinearTheory.
Variable R : nzRingType.
Section GenericProperties.
Variables (U U' : lmodType R) (V : zmodType) (s : R -> V -> V) (s' : R -> V -> V).
Variable f : {bilinear U -> U' -> V | s & s'}.
Section GenericPropertiesr.
Variable z : U.
Lemma linear0r : f z 0 = 0. Proof. by rewrite raddf0. Qed.
Lemma linearNr : {morph f z : x / - x}. Proof. exact: raddfN. Qed.
Lemma linearDr : {morph f z : x y / x + y}. Proof. exact: raddfD. Qed.
Lemma linearBr : {morph f z : x y / x - y}. Proof. exact: raddfB. Qed.
Lemma linearMnr n : {morph f z : x / x *+ n}. Proof. exact: raddfMn. Qed.
Lemma linearMNnr n : {morph f z : x / x *- n}. Proof. exact: raddfMNn. Qed.
Lemma linear_sumr I r (P : pred I) E :
f z (\sum_(i <- r | P i) E i) = \sum_(i <- r | P i) f z (E i).
Proof. exact: raddf_sum. Qed.
Lemma linearZr_LR : scalable_for s' (f z). Proof. exact: linearZ_LR. Qed.
Lemma linearPr a : {morph f z : u v / a *: u + v >-> s' a u + v}.
Proof. exact: linearP. Qed.
End GenericPropertiesr.
Lemma applyrE x : applyr f x =1 f^~ x. Proof. by []. Qed.
Section GenericPropertiesl.
Variable z : U'.
HB.instance Definition _ :=
GRing.isZmodMorphism.Build _ _ (applyr f z) (@zmod_morphisml_subproof _ _ _ _ _ _ f z).
HB.instance Definition _ :=
GRing.isScalable.Build _ _ _ _ (applyr f z) (@linearl_subproof _ _ _ _ _ _ f z).
Lemma linear0l : f 0 z = 0. Proof. by rewrite -applyrE raddf0. Qed.
Lemma linearNl : {morph f^~ z : x / - x}.
Proof. by move=> ?; rewrite -applyrE raddfN. Qed.
Lemma linearDl : {morph f^~ z : x y / x + y}.
Proof. by move=> ? ?; rewrite -applyrE raddfD. Qed.
Lemma linearBl : {morph f^~ z : x y / x - y}.
Proof. by move=> ? ?; rewrite -applyrE raddfB. Qed.
Lemma linearMnl n : {morph f^~ z : x / x *+ n}.
Proof. by move=> ?; rewrite -applyrE raddfMn. Qed.
Lemma linearMNnl n : {morph f^~ z : x / x *- n}.
Proof. by move=> ?; rewrite -applyrE raddfMNn. Qed.
Lemma linear_sumlz I r (P : pred I) E :
f (\sum_(i <- r | P i) E i) z = \sum_(i <- r | P i) f (E i) z.
Proof. by rewrite -applyrE raddf_sum. Qed.
Lemma linearZl_LR : scalable_for s (f ^~ z).
Proof. by move=> ? ?; rewrite -applyrE linearZ_LR. Qed.
Lemma linearPl a : {morph f^~ z : u v / a *: u + v >-> s a u + v}.
Proof. by move=> ? ?; rewrite -applyrE linearP. Qed.
End GenericPropertiesl.
End GenericProperties.
Section BidirectionalLinearZ.
Variables (U U' : lmodType R) (V : zmodType) (s s' : R -> V -> V).
Variables (S : nzRingType) (h : GRing.Scale.law S V) (h' : GRing.Scale.law S V).
Lemma linearZl z (c : S) (a : R) (h_c := h c)
(f : Bilinear.map_for_left U U' s s' a h_c) u :
f (a *: u) z = h_c (Bilinear.wrap f u z).
Proof. by rewrite linearZl_LR; case: f => f /= ->. Qed.
Lemma linearZr z c' b (h'_c' := h' c')
(f : Bilinear.map_for_right U U' s s' b h'_c') u :
f z (b *: u) = h'_c' (Bilinear.wrap f z u).
Proof. by rewrite linearZr_LR; case: f => f /= ->. Qed.
Lemma linearZlr c c' a b (h_c := h c) (h'_c' := h' c')
(f : Bilinear.map_for_both U U' s s' a b h_c h'_c') u v :
f (a *: u) (b *: v) = h_c (h'_c' (Bilinear.wrap f u v)).
Proof. by rewrite linearZl_LR linearZ_LR; case: f => f /= -> ->. Qed.
Lemma linearZrl c c' a b (h_c := h c) (h'_c' := h' c')
(f : Bilinear.map_for_both U U' s s' a b h_c h'_c') u v :
f (a *: u) (b *: v) = h'_c' (h_c (Bilinear.wrap f u v)).
Proof. by rewrite linearZ_LR/= linearZl_LR; case: f => f /= -> ->. Qed.
End BidirectionalLinearZ.
End BilinearTheory.
(* TODO
Canonical rev_mulmx (R : nzRingType) m n p := [revop mulmxr of @mulmx R m n p].
*)
(*Canonical mulmx_bilinear (R : comNzRingType) m n p := [bilinear of @mulmx R m n p].*)
Lemma mulmx_is_bilinear (R : comNzRingType) m n p : bilinear_for
(GRing.Scale.Law.clone _ _ *:%R _) (GRing.Scale.Law.clone _ _ *:%R _)
(@mulmx R m n p).
Proof.
split=> [u'|u] a x y /=.
- by rewrite mulmxDl scalemxAl.
- by rewrite mulmxDr scalemxAr.
Qed.
HB.instance Definition _ (R : comNzRingType) m n p := bilinear_isBilinear.Build R
[the lmodType R of 'M[R]_(m, n)] [the lmodType R of 'M[R]_(n, p)]
[the zmodType of 'M[R]_(m, p)] _ _ (@mulmx R m n p)
(mulmx_is_bilinear R m n p).
Section BilinearForms.
Variables (R : fieldType) (theta : {rmorphism R -> R}).
Variables (n : nat) (M : 'M[R]_n).
Implicit Types (a b : R) (u v : 'rV[R]_n) (N P Q : 'M[R]_n).
Definition form u v := (u *m M *m (v ^t theta)) 0 0.
Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u] : ring_scope.
Lemma form0l u : '[0, u] = 0. Proof. by rewrite /form !mul0mx mxE. Qed.
Lemma form0r u : '[u, 0] = 0.
Proof. by rewrite /form trmx0 map_mx0 mulmx0 mxE. Qed.
Lemma formDl u v w : '[u + v, w] = '[u, w] + '[v, w].
Proof. by rewrite /form !mulmxDl mxE. Qed.
Lemma formDr u v w : '[u, v + w] = '[u, v] + '[u, w].
Proof. by rewrite /form linearD !map_mxD !mulmxDr mxE. Qed.
Lemma formZr a u v : '[u, a *: v] = theta a * '[u, v].
Proof. by rewrite /form !(linearZ, map_mxZ) /= mxE. Qed.
Lemma formZl a u v : '[a *: u, v] = a * '[u, v].
Proof.
by do !rewrite /form -[_ *: _ *m _]/(mulmxr _ _) linearZ /=; rewrite mxE.
Qed.
Lemma formNl u v : '[- u, v] = - '[u, v].
Proof. by rewrite -scaleN1r formZl mulN1r. Qed.
Lemma formNr u v : '[u, - v] = - '[u, v].
Proof. by rewrite -scaleN1r formZr rmorphN1 mulN1r. Qed.
Lemma formee i j : '['e_i, 'e_j] = M i j.
Proof.
rewrite /form -rowE -map_trmx map_delta_mx -[M in LHS]trmxK.
by rewrite -tr_col -trmx_mul -rowE !mxE.
Qed.
Lemma form0_eq0 : M = 0 -> forall u v, '[u, v] = 0.
Proof. by rewrite/form=> -> u v; rewrite mulmx0 mul0mx mxE. Qed.
End BilinearForms.
HB.mixin Record isHermitianSesquilinear (R : nzRingType) (U : lmodType R)
(eps : bool) (theta : R -> R) (f : U -> U -> R) := {
hermitian_subproof : forall x y : U, f x y = (-1) ^+ eps * theta (f y x)
}.
HB.structure Definition Hermitian (R : nzRingType) (U : lmodType R)
(eps : bool) (theta : R -> R) :=
{f of @Bilinear R U U _ ( *%R ) (theta \; *%R) f &
@isHermitianSesquilinear R U eps theta f}.
Notation "{ 'hermitian' U 'for' eps & theta }" := (@Hermitian.type _ U eps theta)
(format "{ 'hermitian' U 'for' eps & theta }") : ring_scope.
(* duplicate to trick HB *)
#[non_forgetful_inheritance]
HB.instance Definition _ (R : nzRingType) (U : lmodType R)
(eps : bool) (theta : R -> R) (f : {hermitian U for eps & theta}) (u : U) :=
@GRing.isZmodMorphism.Build _ _ (f u) (@zmod_morphismr_subproof _ _ _ _ _ _ f u).
#[non_forgetful_inheritance]
HB.instance Definition _ (R : nzRingType) (U : lmodType R)
(eps : bool) (theta : R -> R) (f : {hermitian U for eps & theta}) (u : U) :=
@GRing.isScalable.Build _ _ _ _ (f u) (@linearr_subproof _ _ _ _ _ _ f u).
(*Variables (R : nzRingType) (U : lmodType R) (eps : bool) (theta : R -> R).
Implicit Types phU : phant U.
Local Coercion GRing.Scale.op : GRing.Scale.law >-> Funclass.
Definition axiom (f : U -> U -> R) :=
forall x y : U, f x y = (-1) ^+ eps * theta (f y x).
Record class_of (f : U -> U -> R) : Prop := Class {
base : Bilinear.class_of ( *%R) (theta \; *%R) f;
mixin : axiom f
}.*)
(*Canonical additiver (u : U) := Additive (base class u).
Canonical linearr (u : U) := Linear (base class u).
Canonical additivel (u' : U) := @GRing.Additive.Pack _ _ (Phant (U -> R))
(applyr cF u') (Bilinear.basel (base class) u').
Canonical linearl (u' : U) := @GRing.Linear.Pack _ _ _ _ (Phant (U -> R))
(applyr cF u') (Bilinear.basel (base class) u').
Canonical bilinear := @Bilinear.Pack _ _ _ _ _ _ (Phant (U -> U -> R)) cF (base class).*)
(*Module Exports.
Notation "{ 'hermitian' U 'for' eps & theta }" := (map eps theta (Phant U))
(format "{ 'hermitian' U 'for' eps & theta }") : ring_scope.
Coercion base : class_of >-> bilmorphism_for.
Coercion apply : map >-> Funclass.
Notation "[ 'hermitian' 'of' f 'as' g ]" := (@clone _ _ _ _ _ _ f g _ idfun idfun)
(format "[ 'hermitian' 'of' f 'as' g ]") : form_scope.
Notation "[ 'hermitian' 'of' f ]" := (@clone _ _ _ _ _ _ f f _ idfun idfun)
(format "[ 'hermitian' 'of' f ]") : form_scope.
Notation hermitian_for := Hermitian.axiom.
Notation Hermitian fM := (pack (Phant _) fM idfun).
Canonical additiver.
Canonical linearr.
Canonical additivel.
Canonical linearl.
Canonical bilinear.
Notation hermapplyr := (@applyr_head _ _ _ _ tt).
End Exports.
End Hermitian.
Include Hermitian.Exports.*)
Definition orthomx {R : fieldType} (theta : R -> R) n m M (B : 'M_(m, n)) : 'M_n :=
kermx (M *m (B ^t theta)).
Section Sesquilinear.
Variables (R : fieldType) (n : nat).
Implicit Types (a b : R) (u v : 'rV[R]_n) (N P Q : 'M[R]_n).
Section Def.
Variable eps_theta : bool * {rmorphism R -> R}.
Definition sesqui :=
[qualify M : 'M_n | M == ((-1) ^+ eps_theta.1) *: M ^t eps_theta.2].
Fact sesqui_key : pred_key sesqui. Proof. by []. Qed.
Canonical sesqui_keyed := KeyedQualifier sesqui_key.
End Def.
Local Notation "eps_theta .-sesqui" := (sesqui eps_theta).
Variables (eps : bool) (theta : {rmorphism R -> R}) (M : 'M[R]_n).
Local Notation "''[' u , v ]" := (form theta M u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u] : ring_scope.
Lemma sesquiE : (M \is (eps, theta).-sesqui) = (M == (-1) ^+ eps *: M ^t theta).
Proof. by rewrite qualifE. Qed.
Lemma sesquiP : reflect (M = (-1) ^+ eps *: M ^t theta)
(M \is (eps, theta).-sesqui).
Proof. by rewrite sesquiE; exact/eqP. Qed.
Hypotheses (thetaK : involutive theta) (M_sesqui : M \is (eps, theta).-sesqui).
Lemma trmx_sesqui : M^T = (-1) ^+ eps *: M ^ theta.
Proof.
rewrite [in LHS](sesquiP _) // -mul_scalar_mx trmx_mul.
by rewrite tr_scalar_mx mul_mx_scalar map_trmx trmxK.
Qed.
Lemma maptrmx_sesqui : M^t theta = (-1) ^+ eps *: M.
Proof.
by rewrite trmx_sesqui map_mxZ rmorph_sign -map_mx_comp eq_map_mx_id.
Qed.
Lemma formC u v : '[u, v] = (-1) ^+ eps * theta '[v, u].
Proof.
rewrite /form [M in LHS](sesquiP _) // -mulmxA !mxE rmorph_sum mulr_sumr.
apply: eq_bigr => /= i _; rewrite !(mxE, mulr_sumr, mulr_suml, rmorph_sum).
apply: eq_bigr => /= j _; rewrite !mxE !rmorphM mulrCA -!mulrA.
by congr (_ * _); rewrite mulrA mulrC /= thetaK.
Qed.
Lemma form_eq0C u v : ('[u, v] == 0) = ('[v, u] == 0).
Proof. by rewrite formC mulf_eq0 signr_eq0 /= fmorph_eq0. Qed.
Definition ortho m (B : 'M_(m, n)) := orthomx theta M B.
Local Notation "B ^_|_" := (ortho B) : ring_scope.
Local Notation "A '_|_ B" := (A%MS <= B^_|_)%MS : ring_scope.
Lemma normalE u v : (u '_|_ v) = ('[u, v] == 0).
Proof.
by rewrite (sameP sub_kermxP eqP) mulmxA [_ *m _^t _]mx11_scalar fmorph_eq0.
Qed.
Lemma form_eq0P {u v} : reflect ('[u, v] = 0) (u '_|_ v).
Proof. by rewrite normalE; apply/eqP. Qed.
Lemma normalP p q (A : 'M_(p, n)) (B :'M_(q, n)) :
reflect (forall (u v : 'rV_n), (u <= A)%MS -> (v <= B)%MS -> u '_|_ v)
(A '_|_ B).
Proof.
apply: (iffP idP) => AnB.
move=> u v uA vB; rewrite (submx_trans uA) // (submx_trans AnB) //.
apply/sub_kermxP; have /submxP [w ->] := vB.
rewrite trmx_mul map_mxM !mulmxA -[kermx _ *m _ *m _]mulmxA.
by rewrite [kermx _ *m _](sub_kermxP _) // mul0mx.
apply/rV_subP => u /AnB /(_ _) /sub_kermxP uMv; apply/sub_kermxP.
suff: forall m (v : 'rV[R]_m),
(forall i, v *m 'e_i ^t theta = 0 :> 'M_1) -> v = 0.
apply => i; rewrite !mulmxA -!mulmxA -map_mxM -trmx_mul uMv //.
by apply/submxP; exists 'e_i.
move=> /= m v Hv; apply: (can_inj (@trmxK _ _ _)).
rewrite trmx0; apply/row_matrixP=> i; rewrite row0 rowE.
apply: (can_inj (@trmxK _ _ _)); rewrite trmx0 trmx_mul trmxK.
by rewrite -(map_delta_mx theta) map_trmx Hv.
Qed.
Lemma normalC p q (A : 'M_(p, n)) (B : 'M_(q, n)) : (A '_|_ B) = (B '_|_ A).
Proof.
gen have nC : p q A B / A '_|_ B -> B '_|_ A; last by apply/idP/idP; apply/nC.
move=> AnB; apply/normalP => u v ? ?; rewrite normalE.
rewrite formC mulf_eq0 ?fmorph_eq0 ?signr_eq0 /=.
by rewrite -normalE (normalP _ _ AnB).
Qed.
Lemma normal_ortho_mx p (A : 'M_(p, n)) : ((A^_|_) '_|_ A).
Proof. by []. Qed.
Lemma normal_mx_ortho p (A : 'M_(p, n)) : (A '_|_ (A^_|_)).
Proof. by rewrite normalC. Qed.
Lemma rank_normal u : (\rank (u ^_|_) >= n.-1)%N.
Proof.
rewrite mxrank_ker -subn1 leq_sub2l //.
by rewrite (leq_trans (mxrankM_maxr _ _)) // rank_leq_col.
Qed.
Definition rad := 1%:M^_|_.
Lemma rad_ker : rad = kermx M.
Proof. by rewrite /rad /ortho /orthomx trmx1 map_mx1 mulmx1. Qed.
(* Pythagoras *)
Theorem formDd u v : u '_|_ v -> '[u + v] = '[u] + '[v].
Proof.
move=> uNv; rewrite formDl !formDr ['[v, u]]formC.
by rewrite ['[u, v]](form_eq0P _) // rmorph0 mulr0 addr0 add0r.
Qed.
Lemma formZ a u : '[a *: u]= (a * theta a) * '[u].
Proof. by rewrite formZl formZr mulrA. Qed.
Lemma formN u : '[- u] = '[u].
Proof. by rewrite formNr formNl opprK. Qed.
Lemma form_sign m u : '[(-1) ^+ m *: u] = '[u].
Proof. by rewrite -signr_odd scaler_sign; case: odd; rewrite ?formN. Qed.
Lemma formD u v : let d := '[u, v] in
'[u + v] = '[u] + '[v] + (d + (-1) ^+ eps * theta d).
Proof. by rewrite formDl !formDr ['[v, _]]formC [_ + '[v]]addrC addrACA. Qed.
Lemma formB u v : let d := '[u, v] in
'[u - v] = '[u] + '[v] - (d + (-1) ^+ eps * theta d).
Proof. by rewrite formD formN !formNr rmorphN mulrN -opprD. Qed.
Lemma formBd u v : u '_|_ v -> '[u - v] = '[u] + '[v].
Proof.
by move=> uTv; rewrite formDd ?formN // normalE formNr oppr_eq0 -normalE.
Qed.
(* Lemma formJ u v : '[u ^ theta, v ^ theta] = (-1) ^+ eps * theta '[u, v]. *)
(* Proof. *)
(* rewrite {1}/form -map_trmx -map_mx_comp (@eq_map_mx _ _ _ _ _ id) ?map_mx_id //. *)
(* set x := (_ *m _); have -> : x 0 0 = theta ((x^t theta) 0 0) by rewrite !mxE. *)
(* rewrite !trmx_mul trmxK map_trmx mulmxA !map_mxM. *)
(* rewrite maptrmx_sesqui -!scalemxAr -scalemxAl mxE rmorphM rmorph_sign. *)
(* Lemma formJ u : '[u ^ theta] = (-1) ^+ eps * '[u]. *)
(* Proof. *)
(* rewrite {1}/form -map_trmx -map_mx_comp (@eq_map_mx _ _ _ _ _ id) ?map_mx_id //. *)
(* set x := (_ *m _); have -> : x 0 0 = theta ((x^t theta) 0 0) by rewrite !mxE. *)
(* rewrite !trmx_mul trmxK map_trmx mulmxA !map_mxM. *)
(* rewrite maptrmx_sesqui -!scalemxAr -scalemxAl mxE rmorphM rmorph_sign. *)
(* rewrite !map_mxM. *)
(* rewrite -map_mx_comp eq_map_mx_id //. *)
(* !linearZr_LR /=. linearZ. *)
(* linearZl. *)
(* rewrite trmx_sesqui. *)
(* rewrite mapmx. *)
(* rewrite map *)
(* apply/matrixP. *)
(* rewrite formC. *)
(* Proof. by rewrite cfdot_conjC geC0_conj // cfnorm_ge0. Qed. *)
(* Lemma cfCauchySchwarz u v : *)
(* `|'[u, v]| ^+ 2 <= '[u] * '[v] ?= iff ~~ free (u :: v). *)
(* Proof. *)
(* rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC. *)
(* have [-> | nz_v] /= := altP (v =P 0). *)
(* by apply/lerifP; rewrite !cfdot0r normCK mul0r mulr0. *)
(* without loss ou: u / '[u, v] = 0. *)
(* move=> IHo; pose a := '[u, v] / '[v]; pose u1 := u - a *: v. *)
(* have ou: '[u1, v] = 0. *)
(* by rewrite cfdotBl cfdotZl divfK ?cfnorm_eq0 ?subrr. *)
(* rewrite (canRL (subrK _) (erefl u1)) rpredDr ?rpredZ ?memv_line //. *)
(* rewrite cfdotDl ou add0r cfdotZl normrM (ger0_norm (cfnorm_ge0 _)). *)
(* rewrite exprMn mulrA -cfnormZ cfnormDd; last by rewrite cfdotZr ou mulr0. *)
(* by have:= IHo _ ou; rewrite mulrDl -lerif_subLR subrr ou normCK mul0r. *)
(* rewrite ou normCK mul0r; split; first by rewrite mulr_ge0 ?cfnorm_ge0. *)
(* rewrite eq_sym mulf_eq0 orbC cfnorm_eq0 (negPf nz_v) /=. *)
(* apply/idP/idP=> [|/vlineP[a {2}->]]; last by rewrite cfdotZr ou mulr0. *)
(* by rewrite cfnorm_eq0 => /eqP->; apply: rpred0. *)
(* Qed. *)
End Sesquilinear.
Notation "eps_theta .-sesqui" := (sesqui _ eps_theta) : ring_scope.
Notation symmetric_form := (false, idfun).-sesqui.
Notation skew := (true, idfun).-sesqui.
Notation hermitian := (false, @Num.conj_op _).-sesqui.
HB.mixin Record isDotProduct (R : numDomainType) (U : lmodType R)
(op : U -> U -> R) := { neq0_dnorm_gt0 : forall u, u != 0 -> 0 < op u u }.
HB.structure Definition Dot (R : numDomainType) (U : lmodType R)
(theta : R -> R) :=
{op of isDotProduct R U op & @Hermitian R U false theta op}.
Notation "{ 'dot' U 'for' theta }" := (@Dot.type _ U theta)
(format "{ 'dot' U 'for' theta }") : ring_scope.
(* duplicate to trick HB *)
#[non_forgetful_inheritance]
HB.instance Definition _ (R : numDomainType) (U : lmodType R)
(theta : R -> R) (f : {dot U for theta}) (u : U) :=
@GRing.isZmodMorphism.Build _ _ (f u) (@zmod_morphismr_subproof _ _ _ _ _ _ f u).
#[non_forgetful_inheritance]
HB.instance Definition _ (R : numDomainType) (U : lmodType R)
(theta : R -> R) (f : {dot U for theta}) (u : U) :=
@GRing.isScalable.Build _ _ _ _ (f u) (@linearr_subproof _ _ _ _ _ _ f u).
(*Notation "{ 'dot' U 'for' theta }" := (map theta (Phant U))
(format "{ 'dot' U 'for' theta }") : ring_scope.
Coercion base : class_of >-> Hermitian.class_of.
Coercion apply : map >-> Funclass.
Notation "[ 'dot' 'of' f 'as' g ]" := (@clone _ _ _ _ _ f g _ idfun idfun)
(format "[ 'dot' 'of' f 'as' g ]") : form_scope.
Notation "[ 'dot' 'of' f ]" := (@clone _ _ _ _ _ f f _ idfun idfun)
(format "[ 'dot' 'of' f ]") : form_scope.
Notation Dot fM := (pack fM idfun).
Notation is_dot := Dot.axiom.*)
Notation "{ 'symmetric' U }" := ({hermitian U for false & idfun})
(format "{ 'symmetric' U }") : ring_scope.
Notation "{ 'skew_symmetric' U }" := ({hermitian U for true & idfun})
(format "{ 'skew_symmetric' U }") : ring_scope.
Notation "{ 'hermitian_sym' U 'for' theta }" := ({hermitian U for false & theta})
(format "{ 'hermitian_sym' U 'for' theta }") : ring_scope.
Definition is_skew (R : nzRingType) (eps : bool) (theta : R -> R)
(U : lmodType R) (form : {hermitian U for eps & theta}) :=
(eps = true) /\ (theta =1 id).
Definition is_sym (R : nzRingType) (eps : bool) (theta : R -> R)
(U : lmodType R) (form : {hermitian U for eps & theta}) :=
(eps = false) /\ (theta =1 id).
Definition is_hermsym (R : nzRingType) (eps : bool) (theta : R -> R)
(U : lmodType R) (form : {hermitian U for eps & theta}) :=
(eps = false).
Section HermitianModuleTheory.
Variables (R : nzRingType) (eps : bool) (theta : {rmorphism R -> R}).
Variables (U : lmodType R) (form : {hermitian U for eps & theta}).
Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u]%R : ring_scope.
Lemma hermC u v : '[u, v] = (-1) ^+ eps * theta '[v, u].
Proof. by move: form => [? [[? ? ? ?] []]] /=. Qed.
Lemma hnormN u : '[- u] = '[u].
Proof. by rewrite linearNl linearNr opprK. Qed.
Lemma hnorm_sign n u : '[(-1) ^+ n *: u] = '[u].
Proof. by rewrite -signr_odd scaler_sign; case: (odd n); rewrite ?hnormN. Qed.
Lemma hnormD u v :
let d := '[u, v] in '[u + v] = '[u] + '[v] + (d + (-1) ^+ eps * theta d).
Proof. by rewrite /= addrAC -hermC linearDl 2!linearDr !addrA. Qed.
Lemma hnormB u v :
let d := '[u, v] in '[u - v] = '[u] + '[v] - (d + (-1) ^+ eps * theta d).
Proof.
by rewrite /= hnormD hnormN linearNr addrA rmorphN mulrN opprD addrA.
Qed.
Lemma hnormDd u v : '[u, v] = 0 -> '[u + v] = '[u] + '[v].
Proof. by move=> ouv; rewrite hnormD ouv rmorph0 mulr0 !addr0. Qed.
Lemma hnormBd u v : '[u, v] = 0 -> '[u - v] = '[u] + '[v].
Proof.
by move=> ouv; rewrite hnormDd ?hnormN// linearNr [X in - X]ouv oppr0.
Qed.
Local Notation "u '_|_ v" := ('[u, v] == 0) : ring_scope.
Definition ortho_rec (s1 s2 : seq U) :=
all [pred u | all [pred v | u '_|_ v] s2] s1.
Fixpoint pair_ortho_rec (s : seq U) :=
if s is v :: s' then ortho_rec [:: v] s' && pair_ortho_rec s' else true.
(* We exclude 0 from pairwise orthogonal sets. *)
Definition pairwise_orthogonal s := (0 \notin s) && pair_ortho_rec s.
Definition orthogonal s1 s2 := (@ortho_rec s1 s2).
Arguments orthogonal : simpl never.
Lemma orthogonal_cons u us vs :
orthogonal (u :: us) vs = orthogonal [:: u] vs && orthogonal us vs.
Proof. by rewrite /orthogonal /= andbT. Qed.
Definition orthonormal s := all [pred v | '[v] == 1] s && pair_ortho_rec s.
Lemma orthonormal_not0 S : orthonormal S -> 0 \notin S.
Proof.
by case/andP=> /allP S1 _; rewrite (contra (S1 _)) //= linear0r eq_sym oner_eq0.
Qed.
Lemma orthonormalE S :
orthonormal S = all [pred phi | '[phi] == 1] S && pairwise_orthogonal S.
Proof. by rewrite -(andb_idl (@orthonormal_not0 S)) andbCA. Qed.
Lemma orthonormal_orthogonal S : orthonormal S -> pairwise_orthogonal S.
Proof. by rewrite orthonormalE => /andP[_]. Qed.
End HermitianModuleTheory.
Arguments orthogonal {R eps theta U} form s1 s2.
Arguments pairwise_orthogonal {R eps theta U} form s.
Arguments orthonormal {R eps theta U} form s.
Section HermitianIsometry.
Variables (R : nzRingType) (eps : bool) (theta : {rmorphism R -> R}).
Variables (U1 U2 : lmodType R) (form1 : {hermitian U1 for eps & theta})
(form2 : {hermitian U2 for eps & theta}).
Local Notation "''[' u , v ]_1" := (form1 u%R v%R) : ring_scope.
Local Notation "''[' u , v ]_2" := (form2 u%R v%R) : ring_scope.
Local Notation "''[' u ]_1" := (form1 u%R u%R) : ring_scope.
Local Notation "''[' u ]_2" := (form2 u%R u%R): ring_scope.
Definition isometry tau := forall u v, form1 (tau u) (tau v) = form2 u%R v%R.
Definition isometry_from_to mD tau mR :=
prop_in2 mD (inPhantom (isometry tau)) /\
prop_in1 mD (inPhantom (forall u, in_mem (tau u) mR)).
Local Notation "{ 'in' D , 'isometry' tau , 'to' R }" :=
(isometry_from_to (mem D) tau (mem R))
(format "{ 'in' D , 'isometry' tau , 'to' R }")
: type_scope.
End HermitianIsometry.
Section HermitianVectTheory.
Variables (R : fieldType) (eps : bool) (theta : {rmorphism R -> R}).
Variable (U : lmodType R) (form : {hermitian U for eps & theta}).
Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u]%R : ring_scope.
Lemma herm_eq0C u v : ('[u, v] == 0) = ('[v, u] == 0).
Proof. by rewrite hermC mulf_eq0 signr_eq0 /= fmorph_eq0. Qed.
End HermitianVectTheory.
Section HermitianFinVectTheory.
Variables (F : fieldType) (eps : bool) (theta : {rmorphism F -> F}).
Variables (vT : vectType F) (form : {hermitian vT for eps & theta}).
Let n := \dim {:vT}.
Implicit Types (u v : vT) (U V : {vspace vT}).
Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u]%R : ring_scope.
Let alpha v := (linfun (applyr form v : vT -> F^o)).
Definition orthov V := (\bigcap_(i < \dim V) lker (alpha (vbasis V)`_i))%VS.
Local Notation "U '_|_ V" := (U <= orthov V)%VS : vspace_scope.
Lemma mem_orthovPn V u : reflect (exists2 v, v \in V & '[u, v] != 0) (u \notin orthov V).
Proof.
apply: (iffP idP) => [u_orthovV|[v /coord_vbasis-> uvNorthov]]; last first.
apply/subv_bigcapP => uP.
rewrite linear_sumr big1 ?eqxx//= in uvNorthov.
move=> i _; have := uP i isT.
by rewrite -memvE memv_ker lfunE/= linearZr/= => /eqP/= ->; rewrite mulr0.
suff /existsP [i ui_neq0] : [exists i : 'I_(\dim V), '[u, (vbasis V)`_i] != 0].
by exists (vbasis V)`_i => //; rewrite vbasis_mem ?mem_nth ?size_tuple.
apply: contraNT u_orthovV; rewrite negb_exists => /forallP ui_eq0.
apply/subv_bigcapP => i _.
by rewrite -memvE memv_ker lfunE /= -[_ == _]negbK.
Qed.
Lemma mem_orthovP V u : reflect {in V, forall v, '[u, v] = 0} (u \in orthov V).
Proof.
apply: (iffP idP) => [/mem_orthovPn orthovNu v vV|/(_ _ _)/eqP orthov_u].
by apply/eqP/negP=> /negP Northov_uv; apply: orthovNu; exists v.
by apply/mem_orthovPn => -[v /orthov_u->].
Qed.
Lemma orthov1E u : orthov <[u]> = lker (alpha u).
Proof.
apply/eqP; rewrite eqEsubv; apply/andP.
split; apply/subvP=> v; rewrite memv_ker lfunE /=.
by move=> /mem_orthovP-> //; rewrite ?memv_line.
move=> vu_eq0; apply/mem_orthovP => w /vlineP[k->].
by apply/eqP; rewrite linearZ mulf_eq0 vu_eq0 orbT.
Qed.
Lemma orthovP U V : reflect {in U & V, forall u v, '[u, v] = 0} (U '_|_ V)%VS.
Proof.
apply: (iffP subvP); last by move=> H ??; apply/mem_orthovP=> ??; apply: H.
by move=> /(_ _ _)/mem_orthovP; move=> H ????; apply: H.
Qed.
Lemma orthov_sym U V : (U '_|_ V)%VS = (V '_|_ U)%VS.
Proof. by apply/orthovP/orthovP => eq0 ????; apply/eqP; rewrite herm_eq0C eq0. Qed.
Lemma mem_orthov1 v u : (u \in orthov <[v]>) = ('[u, v] == 0).
Proof. by rewrite orthov1E memv_ker lfunE. Qed.
Lemma orthov11 u v : (<[u]> '_|_ <[v]>)%VS = ('[u, v] == 0).
Proof. exact: mem_orthov1. Qed.
Lemma mem_orthov1_sym v u : (u \in orthov <[v]>) = (v \in orthov <[u]>).
Proof. exact: orthov_sym. Qed.
Lemma orthov0 : orthov 0 = fullv.
Proof.
apply/eqP; rewrite eqEsubv subvf.
apply/subvP => x _; rewrite mem_orthov1.
by rewrite linear0r.
Qed.
Lemma mem_orthov_sym V u : (u \in orthov V) = (V <= orthov <[u]>)%VS.
Proof. exact: orthov_sym. Qed.
Lemma leq_dim_orthov1 u V : ((\dim V).-1 <= \dim (V :&: orthov <[u]>))%N.
Proof.
rewrite -(limg_ker_dim (alpha u) V) -orthov1E.
have := dimvS (subvf (alpha u @: V)); rewrite dimvf addnC.
by case: (\dim _) => [|[]] // _; rewrite leq_pred.
Qed.
Lemma dim_img_form_eq1 u V : u \notin orthov V -> \dim (alpha u @: V)%VS = 1%N.
Proof.
move=> /mem_orthovPn [v vV Northov_uv]; apply/eqP; rewrite eqn_leq /=.
rewrite -[1%N as X in (_ <= X)%N](dimvf [the vectType F of F^o]) dimvS ?subvf//=.
have := @dimvS _ _ <['[v, u] : F^o]> (alpha u @: V).
rewrite -memvE dim_vline herm_eq0C Northov_uv; apply.
by apply/memv_imgP; exists v; rewrite ?memvf// !lfunE /=.
Qed.
Lemma eq_dim_orthov1 u V : u \notin orthov V -> (\dim V).-1 = \dim (V :&: orthov <[u]>).
Proof.
rewrite -(limg_ker_dim (alpha u) V) => /dim_img_form_eq1->.
by rewrite -orthov1E addn1.
Qed.
Lemma dim_img_form_eq0 u V : u \in orthov V -> \dim (alpha u @: V)%VS = 0%N.
Proof. by move=> uV; apply/eqP; rewrite dimv_eq0 -lkerE -orthov1E orthov_sym. Qed.
Lemma neq_dim_orthov1 u V : (\dim V > 0)%N ->
u \in orthov V -> ((\dim V).-1 < \dim (V :&: orthov <[u]>))%N.
Proof.
move=> V_gt0; rewrite -(limg_ker_dim (alpha u) V) -orthov1E => u_in.
rewrite dim_img_form_eq0 // addn0 (capv_idPl _) 1?orthov_sym //.
by case: (\dim _) V_gt0.
Qed.
Lemma leqif_dim_orthov1 u V : (\dim V > 0)%N ->
((\dim V).-1 <= \dim (V :&: orthov <[u]>) ?= iff (u \notin orthov V))%N.
Proof.
move=> Vr_gt0; apply/leqifP.
by case: (boolP (u \in _)) => /= [/neq_dim_orthov1->|/eq_dim_orthov1->].
Qed.
Lemma leqif_dim_orthov1_full u : (n > 0)%N ->
((\dim {:vT}).-1 <= \dim (orthov <[u]>) ?= iff (u \notin orthov fullv))%N.
Proof.
by move=> n_gt0; have := @leqif_dim_orthov1 u fullv; rewrite capfv; apply.
Qed.
(* Link between orthov and orthovgonality of sequences *)
Lemma orthogonal1P u v : reflect ('[u, v] = 0) (orthogonal form [:: u] [:: v]).
Proof. by rewrite /orthogonal /= !andbT; apply: eqP. Qed.
Lemma orthogonalP us vs :
reflect {in us & vs, forall u v, '[u, v] = 0} (orthogonal form us vs).
Proof.
apply: (iffP allP) => ousvs u => [v /ousvs/allP opus /opus/eqP // | /ousvs opus].
by apply/allP=> v /= /opus->.
Qed.
Lemma orthogonal_oppr S R : orthogonal form S (map -%R R) = orthogonal form S R.
Proof.
wlog suffices IH: S R / orthogonal form S R -> orthogonal form S (map -%R R).
by apply/idP/idP=> /IH; rewrite ?mapK //; apply: opprK.
move/orthogonalP=> oSR; apply/orthogonalP=> xi1 _ Sxi1 /mapP[xi2 Rxi2 ->].
by rewrite linearNr /= oSR ?oppr0.
Qed.
Lemma orthogonalE us vs : (orthogonal form us vs) = (<<us>> '_|_ <<vs>>)%VS.
Proof.
apply/orthogonalP/orthovP => uvsP u v; last first.
by move=> uus vvs; rewrite uvsP // memv_span.
rewrite -[us]in_tupleE -[vs]in_tupleE => /coord_span-> /coord_span->.
rewrite linear_sumr big1 //= => i _.
rewrite linear_sumlz big1 //= => j _.
by rewrite linearZlr/= uvsP ?mulr0// mem_nth.
Qed.
Lemma orthovE U V : (U '_|_ V)%VS = orthogonal form (vbasis U) (vbasis V).
Proof. by rewrite orthogonalE !(span_basis (vbasisP _)). Qed.
Notation radv := (orthov fullv).
Lemma orthoDv U V W : (U + V '_|_ W)%VS = (U '_|_ W)%VS && (V '_|_ W)%VS.
Proof. by rewrite subv_add. Qed.
Lemma orthovD U V W : (U '_|_ V + W)%VS = (U '_|_ V)%VS && (U '_|_ W)%VS.
Proof. by rewrite ![(U '_|_ _)%VS]orthov_sym orthoDv. Qed.
Definition nondegenerate := radv == 0%VS.
Definition is_psymplectic := [/\ nondegenerate, is_skew form &
2 \in [pchar F] -> forall u, '[u, u] = 0].
Definition is_porthogonal := [/\ nondegenerate, is_sym form &
2 \in [pchar F] -> forall u, '[u, u] = 0].
Definition is_unitary := nondegenerate /\ (is_hermsym form).
End HermitianFinVectTheory.
#[deprecated(since="mathcomp 2.4.0", note="Use is_psymplectic instead.")]
Notation is_symplectic := is_psymplectic (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use is_porthogonal instead.")]
Notation is_orthogonal := is_porthogonal (only parsing).
Arguments orthogonalP {F eps theta vT form us vs}.
Arguments orthovP {F eps theta vT form U V}.
Arguments mem_orthovPn {F eps theta vT form V u}.
Arguments mem_orthovP {F eps theta vT form V u}.
Section DotVectTheory.
Variables (C : numClosedFieldType).
Variable (U : lmodType C) (form : {dot U for conjC}).
Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u]%R : ring_scope.
Lemma dnorm_geiff0 u : 0 <= '[u] ?= iff (u == 0).
Proof.
by apply/leifP; have [->|uN0] := altP eqP; rewrite ?linear0r ?neq0_dnorm_gt0.
Qed.
Lemma dnorm_ge0 u : 0 <= '[u]. Proof. by rewrite dnorm_geiff0. Qed.
Lemma dnorm_eq0 u : ('[u] == 0) = (u == 0).
Proof. by rewrite -dnorm_geiff0 eq_sym. Qed.
Lemma dnorm_gt0 u : (0 < '[u]) = (u != 0).
Proof. by rewrite lt_def dnorm_eq0 dnorm_ge0 andbT. Qed.
Lemma sqrt_dnorm_ge0 u : 0 <= sqrtC '[u].
Proof. by rewrite sqrtC_ge0 dnorm_ge0. Qed.
Lemma sqrt_dnorm_eq0 u : (sqrtC '[u] == 0) = (u == 0).
Proof. by rewrite sqrtC_eq0 dnorm_eq0. Qed.
Lemma sqrt_dnorm_gt0 u : (sqrtC '[u] > 0) = (u != 0).
Proof. by rewrite sqrtC_gt0 dnorm_gt0. Qed.
Lemma dnormZ a u : '[a *: u]= `|a| ^+ 2 * '[u].
Proof. by rewrite linearZl_LR linearZr_LR/= mulrA normCK. Qed.
Lemma dnormD u v : let d := '[u, v] in '[u + v] = '[u] + '[v] + (d + d^*).
Proof. by rewrite hnormD mul1r. Qed.
Lemma dnormB u v : let d := '[u, v] in '[u - v] = '[u] + '[v] - (d + d^*).
Proof. by rewrite hnormB mul1r. Qed.
End DotVectTheory.
#[global]
Hint Extern 0 (is_true (0 <= Dot.sort _ _ _
(* NB: This Hint is assuming ^*, a more precise pattern would be welcome *)))
=> apply: dnorm_ge0 : core.
Section HermitianTheory.
Variables (C : numClosedFieldType) (eps : bool) (theta : {rmorphism C -> C}).
Variable (U : lmodType C) (form : {dot U for conjC}).
Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u]%R : ring_scope.
Lemma pairwise_orthogonalP S :
reflect (uniq (0 :: S)
/\ {in S &, forall phi psi, phi != psi -> '[phi, psi] = 0})
(pairwise_orthogonal form S).
Proof.
rewrite /pairwise_orthogonal /=; case notS0: (~~ _); last by right; case.
elim: S notS0 => [|phi S IH] /=; first by left.
rewrite inE eq_sym andbT => /norP[nz_phi {}/IH IH].
have [opS | not_opS] := allP; last first.
right=> [[/andP[notSp _] opS]]; case: not_opS => psi Spsi /=.
by rewrite opS ?mem_head 1?mem_behead // (memPnC notSp).
rewrite (contra (opS _)) /= ?dnorm_eq0 //.
apply: (iffP IH) => [] [uniqS oSS]; last first.
by split=> //; apply: sub_in2 oSS => psi Spsi; apply: mem_behead.
split=> // psi xi; rewrite !inE => /predU1P[-> // | Spsi].
by case/predU1P=> [-> | /opS] /eqP.
case/predU1P=> [-> _ | Sxi /oSS-> //].
apply/eqP; rewrite hermC.
by move: (opS psi Spsi) => /= /eqP ->; rewrite rmorph0 mulr0.
Qed.
Lemma pairwise_orthogonal_cat R S :
pairwise_orthogonal form (R ++ S) =
[&& pairwise_orthogonal form R, pairwise_orthogonal form S & orthogonal form R S].
Proof.
rewrite /pairwise_orthogonal mem_cat negb_or -!andbA; do !bool_congr.
elim: R => [|phi R /= ->]; rewrite ?andbT// all_cat -!andbA /=.
by do !bool_congr.
Qed.
Lemma orthonormal_cat R S :
orthonormal form (R ++ S) =
[&& orthonormal form R, orthonormal form S & orthogonal form R S].
Proof.
rewrite !orthonormalE pairwise_orthogonal_cat all_cat -!andbA.
by do !bool_congr.
Qed.
Lemma orthonormalP S :
reflect (uniq S /\ {in S &, forall phi psi, '[phi, psi] = (phi == psi)%:R})
(orthonormal form S).
Proof.
rewrite orthonormalE; have [/= normS | not_normS] := allP; last first.
by right=> [[_ o1S]]; case: not_normS => phi Sphi; rewrite /= o1S ?eqxx.
apply: (iffP (pairwise_orthogonalP S)) => [] [uniqS oSS].
split=> // [|phi psi]; first by case/andP: uniqS.
by have [-> _ /normS/eqP | /oSS] := altP eqP.
split=> // [|phi psi Sphi Spsi /negbTE]; last by rewrite oSS // => ->.
by rewrite /= (contra (normS _)) // linear0r eq_sym oner_eq0.
Qed.
Lemma sub_orthonormal S1 S2 :
{subset S1 <= S2} -> uniq S1 -> orthonormal form S2 -> orthonormal form S1.
Proof.
move=> sS12 uniqS1 /orthonormalP[_ oS1].
by apply/orthonormalP; split; last apply: sub_in2 sS12 _ _.
Qed.
Lemma orthonormal2P phi psi :
reflect [/\ '[phi, psi] = 0, '[phi] = 1 & '[psi] = 1]
(orthonormal form [:: phi; psi]).
Proof.
rewrite /orthonormal /= !andbT andbC.
by apply: (iffP and3P) => [] []; do 3!move/eqP->.
Qed.
End HermitianTheory.
Section DotFinVectTheory.
Variable C : numClosedFieldType.
Variables (U : vectType C) (form : {dot U for conjC}).
Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u]%R : ring_scope.
Lemma sub_pairwise_orthogonal S1 S2 :
{subset S1 <= S2} -> uniq S1 ->
pairwise_orthogonal form S2 -> pairwise_orthogonal form S1.
Proof.
move=> sS12 uniqS1 /pairwise_orthogonalP[/andP[notS2_0 _] oS2].
apply/pairwise_orthogonalP; rewrite /= (contra (sS12 0)) //.
by split=> //; apply: sub_in2 oS2.
Qed.
Lemma orthogonal_free S : pairwise_orthogonal form S -> free S.
Proof.
case/pairwise_orthogonalP=> [/=/andP[notS0 uniqS] oSS].
rewrite -(in_tupleE S); apply/freeP => a aS0 i.
have S_i: S`_i \in S by apply: mem_nth.
have /eqP: '[S`_i, 0] = 0 := linear0r _ _.
rewrite -{2}aS0 raddf_sum /= (bigD1 i) //= big1 => [|j neq_ji]; last 1 first.
by rewrite linearZ /= oSS ?mulr0 ?mem_nth // eq_sym nth_uniq.
rewrite addr0 linearZ mulf_eq0 conjC_eq0 dnorm_eq0.
by case/pred2P=> // Si0; rewrite -Si0 S_i in notS0.
Qed.
Lemma filter_pairwise_orthogonal S p :
pairwise_orthogonal form S -> pairwise_orthogonal form (filter p S).
Proof.
move=> orthoS; apply: sub_pairwise_orthogonal (orthoS).
exact: mem_subseq (filter_subseq p S).
exact/filter_uniq/free_uniq/orthogonal_free.
Qed.
Lemma orthonormal_free S : orthonormal form S -> free S.
Proof. by move/orthonormal_orthogonal/orthogonal_free. Qed.
Theorem CauchySchwarz (u v : U) :
`|'[u, v]| ^+ 2 <= '[u] * '[v] ?= iff ~~ free [:: u; v].
Proof.
rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC.
have [-> | nz_v] /= := altP (v =P 0).
by apply/leifP; rewrite /= !linear0r normCK mul0r mulr0.
without loss ou: u / '[u, v] = 0.
move=> IHo; pose a := '[u, v] / '[v]; pose u1 := u - a *: v.
have ou: '[u1, v] = 0.
rewrite linearBl/=.
rewrite linearZl_LR.
by rewrite divfK ?dnorm_eq0 ?subrr.
rewrite (canRL (subrK _) (erefl u1)) rpredDr ?rpredZ ?memv_line //.
rewrite linearDl /= ou add0r.
rewrite linearZl_LR/= normrM (ger0_norm (dnorm_ge0 _ _)).
rewrite exprMn mulrA -dnormZ hnormDd/=; last by rewrite linearZr_LR/= ou mulr0.
have:= IHo _ ou.
by rewrite mulrDl -leifBLR subrr ou normCK mul0r.
rewrite ou normCK mul0r; split; first by rewrite mulr_ge0.
rewrite eq_sym mulf_eq0 orbC dnorm_eq0 (negPf nz_v) /=.
apply/idP/idP=> [|/vlineP[a {2}->]]; last by rewrite linearZr_LR/= ou mulr0.
by rewrite dnorm_eq0 => /eqP->; apply: rpred0.
Qed.
Lemma CauchySchwarz_sqrt u v :
`|'[u, v]| <= sqrtC '[u] * sqrtC '[v] ?= iff ~~ free [:: u; v].
Proof.
rewrite -(sqrCK (normr_ge0 _)) -sqrtCM ?nnegrE//.
rewrite (mono_in_leif (@ler_sqrtC _)) 1?rpredM//= ?nnegrE//=.
exact: CauchySchwarz.
Qed.
Lemma orthoP phi psi : reflect ('[phi, psi] = 0) (orthogonal form [:: phi] [:: psi]).
Proof. by rewrite /orthogonal /= !andbT; apply: eqP. Qed.
Lemma orthoPl phi S :
reflect {in S, forall psi, '[phi, psi] = 0} (orthogonal form [:: phi] S).
Proof.
by rewrite [orthogonal form _ S]andbT /=; apply: (iffP allP) => ophiS ? /ophiS/eqP.
Qed.
Arguments orthoPl {phi S}.
Lemma orthogonal_sym : symmetric (orthogonal form).
Proof.
apply: symmetric_from_pre => R S /orthogonalP oRS.
by apply/orthogonalP=> phi psi Rpsi Sphi; rewrite hermC /= oRS ?rmorph0 ?mulr0.
Qed.
Lemma orthoPr S psi :
reflect {in S, forall phi, '[phi, psi] = 0} (orthogonal form S [:: psi]).
Proof.
rewrite orthogonal_sym.
by apply: (iffP orthoPl) => oSpsi phi Sphi; rewrite hermC /= oSpsi //= conjC0 mulr0.
Qed.
Lemma orthogonal_catl R1 R2 S :
orthogonal form (R1 ++ R2) S = orthogonal form R1 S && orthogonal form R2 S.
Proof. exact: all_cat. Qed.
Lemma orthogonal_catr R S1 S2 :
orthogonal form R (S1 ++ S2) = orthogonal form R S1 && orthogonal form R S2.
Proof. by rewrite !(orthogonal_sym R) orthogonal_catl. Qed.
Lemma eq_pairwise_orthogonal R S :
perm_eq R S -> pairwise_orthogonal form R = pairwise_orthogonal form S.
Proof.
apply: catCA_perm_subst R S => R S S'.
rewrite !pairwise_orthogonal_cat !orthogonal_catr (orthogonal_sym R S) -!andbA.
by do !bool_congr.
Qed.
Lemma eq_orthonormal S0 S : perm_eq S0 S -> orthonormal form S0 = orthonormal form S.
Proof.
move=> eqRS; rewrite !orthonormalE (eq_all_r (perm_mem eqRS)).
by rewrite (eq_pairwise_orthogonal eqRS).
Qed.
Lemma orthogonal_oppl S R : orthogonal form (map -%R S) R = orthogonal form S R.
Proof. by rewrite -!(orthogonal_sym R) orthogonal_oppr. Qed.
Lemma triangle_lerif u v :
sqrtC '[u + v] <= sqrtC '[u] + sqrtC '[v]
?= iff ~~ free [:: u; v] && (0 <= coord [tuple v] 0 u).
Proof.
rewrite -(mono_in_leif ler_sqr) ?rpredD ?nnegrE ?sqrtC_ge0//.
rewrite andbC sqrrD !sqrtCK addrAC dnormD (mono_leif (lerD2l _))/=.
rewrite -mulr_natr -[_ + _](divfK (negbT (pnatr_eq0 C 2))) -/('Re _).
rewrite (mono_leif (ler_pM2r _)) ?ltr0n//.
have := leif_trans (leif_Re_Creal '[u, v]) (CauchySchwarz_sqrt u v).
rewrite ReE; congr (_ <= _ ?= iff _); apply: andb_id2r.
rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC.
have [-> | nz_v] := altP (v =P 0); first by rewrite linear0 coord0.
case/vlineP=> [x ->]; rewrite linearZl linearZ/= pmulr_lge0 ?dnorm_gt0 //=.
by rewrite (coord_free 0) ?seq1_free // eqxx mulr1.
Qed.
Lemma span_orthogonal S1 S2 phi1 phi2 :
orthogonal form S1 S2 -> phi1 \in <<S1>>%VS -> phi2 \in <<S2>>%VS ->
'[phi1, phi2] = 0.
Proof.
move/orthogonalP=> oS12; do 2!move/(@coord_span _ _ _ (in_tuple _))->.
rewrite linear_sumlz big1 // => i _; rewrite linear_sumr big1 // => j _.
by rewrite linearZlr/= oS12 ?mem_nth ?mulr0.
Qed.
Lemma orthogonal_split S beta :
{X : U & X \in <<S>>%VS &
{Y :U | [/\ beta = X + Y, '[X, Y] = 0 & orthogonal form [:: Y] S]}}.
Proof.
suffices [X S_X [Y -> oYS]]:
{X : _ & X \in <<S>>%VS & {Y | beta = X + Y & orthogonal form [:: Y] S}}.
- exists X => //; exists Y.
by rewrite hermC /= (span_orthogonal oYS) ?memv_span1 ?conjC0 // mulr0.
elim: S beta => [|phi S IHS] beta.
by exists 0; last exists beta; rewrite ?mem0v ?add0r.
have [[UU S_U [V -> oVS]] [X S_X [Y -> oYS]]] := (IHS phi, IHS beta).
pose Z := '[Y, V] / '[V] *: V; exists (X + Z).
rewrite /Z -{4}(addKr UU V) scalerDr scalerN addrA addrC span_cons.
by rewrite memv_add ?memvB ?memvZ ?memv_line.
exists (Y - Z); first by rewrite addrCA !addrA addrK addrC.
apply/orthoPl=> psi; rewrite !inE => /predU1P[-> | Spsi]; last first.
by rewrite linearBl linearZl_LR /= (orthoPl oVS _ Spsi) mulr0 subr0 (orthoPl oYS).
rewrite linearBl !linearDr /= (span_orthogonal oYS) // ?memv_span ?mem_head //.
rewrite !linearZl_LR /= (span_orthogonal oVS _ S_U) ?mulr0 ?memv_span ?mem_head //.
have [-> | nzV] := eqVneq V 0; first by rewrite linear0r !mul0r subrr.
by rewrite divfK ?dnorm_eq0 ?subrr.
Qed.
End DotFinVectTheory.
Arguments orthoP {C U form phi psi}.
Arguments pairwise_orthogonalP {C U form S}.
Arguments orthonormalP {C U form S}.
Arguments orthoPl {C U form phi S}.
Arguments orthoPr {C U form S psi}.
Section BuildIsometries.
Variables (C : numClosedFieldType) (U U1 U2 : vectType C).
Variables (form : {dot U for conjC}) (form1 : {dot U1 for conjC})
(form2 : {dot U2 for conjC}).
Definition normf1 := fun u => form1 u u.
Definition normf2 := fun u => form2 u u.
Lemma isometry_of_dnorm S tauS :
pairwise_orthogonal form1 S -> pairwise_orthogonal form2 tauS ->
map normf2 tauS = map normf1 S ->
{tau : {linear U1 -> U2} | map tau S = tauS
& {in <<S>>%VS &, isometry form2 form1 tau}}.
Proof.
move=> oS oT eq_nST; have freeS := orthogonal_free oS.
have eq_sz: size tauS = size S by have:= congr1 size eq_nST; rewrite !size_map.
have [tau defT] := linear_of_free S tauS; rewrite -[S]/(tval (in_tuple S)).
exists tau => [|u v /coord_span-> /coord_span->]; rewrite ?raddf_sum ?defT //=.
apply: eq_bigr => i _ /=; rewrite !linearZ/= !linear_sumlz; congr (_ * _).
apply: eq_bigr => j _ /=; rewrite linearZ !linearZl; congr (_ * _).
rewrite -!(nth_map 0 0 tau) ?{}defT //; have [-> | neq_ji] := eqVneq j i.
by rewrite /= -[RHS](nth_map 0 0 normf1) -?[LHS](nth_map 0 0 normf2) ?eq_sz // eq_nST.
have{oS} [/=/andP[_ uS] oS] := pairwise_orthogonalP oS.
have{oT} [/=/andP[_ uT] oT] := pairwise_orthogonalP oT.
by rewrite oS ?oT ?mem_nth ?nth_uniq ?eq_sz.
Qed.
Lemma isometry_of_free S f :
free S -> {in S &, isometry form2 form1 f} ->
{tau : {linear U1 -> U2} |
{in S, tau =1 f} & {in <<S>>%VS &, isometry form2 form1 tau}}.
Proof.
move=> freeS If; have defS := free_span freeS.
have [tau /(_ freeS (size_map f S))Dtau] := linear_of_free S (map f S).
have {}Dtau: {in S, tau =1 f}.
by move=> _ /(nthP 0)[i ltiS <-]; rewrite -!(nth_map 0 0) ?Dtau.
exists tau => // _ _ /defS[a -> _] /defS[b -> _] /=.
rewrite 2!{1}linear_sum /= !{1}linear_sumlz /=; apply/eq_big_seq=> xi1 Sxi1.
rewrite !{1}linear_sumr; apply/eq_big_seq=> xi2 Sxi2 /=.
by rewrite !linearZ /= !linearZl !Dtau //= If.
Qed.
Lemma isometry_raddf_inj (tau : {additive U1 -> U2}) :
{in U1 &, isometry form2 form1 tau} ->
{in U1 &, forall u v, u - v \in U1} ->
{in U1 &, injective tau}.
Proof.
move=> Itau linU phi psi Uphi Upsi /eqP; rewrite -subr_eq0 -raddfB.
by rewrite -(dnorm_eq0 form2) Itau ?linU // dnorm_eq0 subr_eq0 => /eqP.
Qed.
End BuildIsometries.
Section MatrixForms.
Variables (R : fieldType) (n : nat).
Implicit Types (a b : R) (u v : 'rV[R]_n) (M N P Q : 'M[R]_n).
Section Def.
Variable theta : R -> R.
Definition form_of_matrix m M (U V : 'M_(m, n)) := \tr (U *m M *m (V ^t theta)).
Definition matrix_of_form (form : 'rV[R]_n -> 'rV[R]_n -> R) : 'M[R]_n :=
\matrix_(i, j) form 'e_i 'e_j.
Implicit Type form : {bilinear 'rV[R]_n -> 'rV[R]_n -> R | *%R & theta \; *%R}.
Lemma matrix_of_formE form i j : matrix_of_form form i j = form 'e_i 'e_j.
Proof. by rewrite mxE. Qed.
End Def.
Section FormOfMatrix.
Variables (m : nat) (M : 'M[R]_n).
Implicit Types (U V : 'M[R]_(m, n)).
Variables (theta : {rmorphism R -> R}).
Local Notation "''[' U , V ]" := (form_of_matrix theta M U%R V%R) : ring_scope.
Local Notation "''[' U ]" := '[U, U]%R : ring_scope.
Let form_of_matrix_is_linear U :
linear_for (theta \; *%R) (form_of_matrix theta M U).
Proof.
rewrite /form_of_matrix => k v w; rewrite -linearP/=.
by rewrite linearP map_mxD map_mxZ !mulmxDr !scalemxAr.
Qed.
HB.instance Definition _ U := @GRing.isLinear.Build _ _ _ _
(form_of_matrix theta M U) (form_of_matrix_is_linear U).
Definition form_of_matrixr U := (form_of_matrix theta M)^~U.
Let form_of_matrixr_is_linear U : linear_for *%R (form_of_matrixr U).
Proof.
rewrite /form_of_matrixr /form_of_matrix => k v w.
by rewrite -linearP /= !mulmxDl -!scalemxAl.
Qed.
HB.instance Definition _ U := @GRing.isLinear.Build _ _ _ _
(form_of_matrixr U) (form_of_matrixr_is_linear U).
(* TODO
Canonical form_of_matrixr_rev :=
[revop form_of_matrixr of form_of_matrix theta M].
*)
Lemma form_of_matrix_is_bilinear :
bilinear_for
(GRing.Scale.Law.clone _ _ ( *%R ) _) (GRing.Scale.Law.clone _ _ (theta \; *%R ) _)
(@form_of_matrix theta m M).
Proof.
split=> [u'|u] a x y /=.
- by rewrite /form_of_matrix !mulmxDl linearD/= -!scalemxAl linearZ.
- rewrite /form_of_matrix -linearZ/= -linearD/= [in LHS]linearD/= map_mxD.
rewrite mulmxDr; congr (\tr (_ + _)).
rewrite scalemxAr; congr (_ *m _).
by rewrite linearZ/= map_mxZ.
Qed.
HB.instance Definition _ :=
bilinear_isBilinear.Build R _ _ _
(GRing.Scale.Law.clone _ _ ( *%R ) _)
(GRing.Scale.Law.clone _ _ (theta \; *%R ) _)
(@form_of_matrix theta m M)
form_of_matrix_is_bilinear.
(*Canonical form_of_matrix_is_bilinear := [the @bilinear _ _ _ _ of form_of_matrix theta M].*)
End FormOfMatrix.
Section FormOfMatrix1.
Variables (M : 'M[R]_n).
Variables (theta : {rmorphism R -> R}).
Local Notation "''[' u , v ]" := (form_of_matrix theta M u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u]%R : ring_scope.
Lemma rV_formee i j : '['e_i :'rV__, 'e_j] = M i j.
Proof.
rewrite /form_of_matrix -rowE -map_trmx map_delta_mx -[M in LHS]trmxK.
by rewrite -tr_col -trmx_mul -rowE trace_mx11 !mxE.
Qed.
Lemma form_of_matrixK : matrix_of_form (form_of_matrix theta M) = M.
Proof. by apply/matrixP => i j; rewrite !mxE rV_formee. Qed.
Lemma rV_form0_eq0 : M = 0 -> forall u v, '[u, v] = 0.
Proof.
by rewrite /form_of_matrix => -> u v; rewrite mulmx0 mul0mx trace_mx11 mxE.
Qed.
End FormOfMatrix1.
Section MatrixOfForm.
Variable (theta : {rmorphism R -> R}).
Variable form : {bilinear 'rV[R]_n -> 'rV[R]_n -> R | *%R & theta \; *%R}.
Lemma matrix_of_formK : form_of_matrix theta (matrix_of_form form) =2 form.
Proof.
set f := (X in X =2 _); have f_eq i j : f 'e_i 'e_j = form 'e_i 'e_j.
by rewrite /f rV_formee mxE.
move=> u v; rewrite [u]row_sum_delta [v]row_sum_delta /f.
rewrite !linear_sum/=; apply: eq_bigr => j _.
rewrite !linear_sumlz/=; apply: eq_bigr => i _.
by rewrite !linearZlr/= -f_eq.
Qed.
End MatrixOfForm.
Section HermitianMx.
Variable eps : bool.
Section HermitianMxDef.
Variable theta : R -> R.
Definition hermitianmx :=
[qualify M : 'M_n | M == ((-1) ^+ eps) *: M ^t theta].
Fact hermitianmx_key : pred_key hermitianmx. Proof. by []. Qed.
Canonical hermitianmx_keyed := KeyedQualifier hermitianmx_key.
Structure hermitian_matrix := HermitianMx {
mx_of_hermitian :> 'M[R]_n;
_ : mx_of_hermitian \is hermitianmx }.
Lemma is_hermitianmxE M :
(M \is hermitianmx) = (M == (-1) ^+ eps *: M ^t theta).
Proof. by rewrite qualifE. Qed.
Lemma is_hermitianmxP M :
reflect (M = (-1) ^+ eps *: M ^t theta) (M \is hermitianmx).
Proof. by rewrite is_hermitianmxE; apply/eqP. Qed.
Lemma hermitianmxE (M : hermitian_matrix) :
M = ((-1) ^+ eps) *: M ^t theta :> 'M__.
Proof. by apply/eqP; case: M. Qed.
Lemma trmx_hermitian (M : hermitian_matrix) :
M^T = ((-1) ^+ eps) *: M ^ theta :> 'M__.
Proof. by rewrite {1}hermitianmxE linearZ /= map_trmx trmxK. Qed.
End HermitianMxDef.
Section HermitianMxTheory.
Variables (theta : involutive_rmorphism R) (M : hermitian_matrix theta).
Lemma maptrmx_hermitian : M^t theta = (-1) ^+ eps *: (M : 'M__).
Proof.
rewrite trmx_hermitian map_mxZ rmorph_sign -map_mx_comp.
by rewrite (map_mx_id (rmorphK _)).
Qed.
Lemma form_of_matrix_is_hermitian m x y :
(@form_of_matrix theta m M) x y =
(-1) ^+ eps * theta ((@form_of_matrix theta m M) y x).
Proof.
rewrite {1}hermitianmxE /form_of_matrix.
rewrite -!(scalemxAr, scalemxAl) linearZ/=; congr (_ * _).
rewrite -mxtrace_tr -trace_map_mx !(trmx_mul, map_mxM, map_trmx, trmxK).
by rewrite -mulmxA -!map_mx_comp !(map_mx_id (rmorphK _)).
Qed.
HB.instance Definition _ m := @isHermitianSesquilinear.Build _ _ _ _ _
(@form_of_matrix_is_hermitian m).
Local Notation "''[' u , v ]" := (form_of_matrix theta M u%R v%R) : ring_scope.
Local Notation "''[' u ]" := '[u, u]%R : ring_scope.
Local Notation "B ^!" := (orthomx theta M B) : matrix_set_scope.
Local Notation "A '_|_ B" := (A%MS <= B%MS^!)%MS : matrix_set_scope.
Lemma orthomxE u v : (u '_|_ v)%MS = ('[u, v] == 0).
Proof.
rewrite (sameP sub_kermxP eqP) mulmxA.
by rewrite [_ *m _^t _]mx11_scalar -trace_mx11 fmorph_eq0.
Qed.
Lemma hermmx_eq0P {u v} : reflect ('[u, v] = 0) (u '_|_ v)%MS.
Proof. by rewrite orthomxE; apply/eqP. Qed.
Lemma orthomxP p q (A : 'M_(p, n)) (B :'M_(q, n)) :
reflect (forall (u v : 'rV_n), u <= A -> v <= B -> u '_|_ v)%MS
(A '_|_ B)%MS.
Proof.
apply: (iffP idP) => AnB.
move=> u v uA vB; rewrite (submx_trans uA) // (submx_trans AnB) //.
apply/sub_kermxP; have /submxP [w ->] := vB.
rewrite trmx_mul map_mxM !mulmxA -[kermx _ *m _ *m _]mulmxA.
by rewrite [kermx _ *m _](sub_kermxP _) // mul0mx.
apply/rV_subP => u /AnB /(_ _) /sub_kermxP uMv; apply/sub_kermxP.
suff: forall m (v : 'rV[R]_m),
(forall i, v *m 'e_i ^t theta = 0 :> 'M_1) -> v = 0.
apply => i; rewrite !mulmxA -!mulmxA -map_mxM -trmx_mul uMv //.
by apply/submxP; exists 'e_i.
move=> /= m v Hv; apply: (can_inj (@trmxK _ _ _)).
rewrite trmx0; apply/row_matrixP=> i; rewrite row0 rowE.
apply: (can_inj (@trmxK _ _ _)); rewrite trmx0 trmx_mul trmxK.
by rewrite -(map_delta_mx theta) map_trmx Hv.
Qed.
Lemma orthomx_sym p q (A : 'M_(p, n)) (B :'M_(q, n)) :
(A '_|_ B)%MS = (B '_|_ A)%MS.
Proof.
gen have nC : p q A B / (A '_|_ B -> B '_|_ A)%MS; last by apply/idP/idP; apply/nC.
move=> AnB; apply/orthomxP => u v ? ?; rewrite orthomxE.
rewrite hermC mulf_eq0 ?fmorph_eq0 ?signr_eq0 /=.
by rewrite -orthomxE (orthomxP _ _ AnB).
Qed.
Lemma ortho_ortho_mx p (A : 'M_(p, n)) : (A^! '_|_ A)%MS. Proof. by []. Qed.
Lemma ortho_mx_ortho p (A : 'M_(p, n)) : (A '_|_ A^!)%MS.
Proof. by rewrite orthomx_sym. Qed.
Lemma rank_orthomx u : (\rank (u ^!) >= n.-1)%N.
Proof.
rewrite mxrank_ker -subn1 leq_sub2l //.
by rewrite (leq_trans (mxrankM_maxr _ _)) // rank_leq_col.
Qed.
Local Notation radmx := (1%:M^!)%MS.
Lemma radmxE : radmx = kermx M.
Proof. by rewrite /orthomx /orthomx trmx1 map_mx1 mulmx1. Qed.
Lemma orthoNmx k m (A : 'M[R]_(k, n)) (B : 'M[R]_(m, n)) :
((- A) '_|_ B)%MS = (A '_|_ B)%MS.
Proof. by rewrite eqmx_opp. Qed.
Lemma orthomxN k m (A : 'M[R]_(k, n)) (B : 'M[R]_(m, n)) :
(A '_|_ (- B))%MS = (A '_|_ B)%MS.
Proof. by rewrite ![(A '_|_ _)%MS]orthomx_sym orthoNmx. Qed.
Lemma orthoDmx k m p (A : 'M[R]_(k, n)) (B : 'M[R]_(m, n)) (C : 'M[R]_(p, n)) :
(A + B '_|_ C)%MS = (A '_|_ C)%MS && (B '_|_ C)%MS.
Proof. by rewrite addsmxE !(sameP sub_kermxP eqP) mul_col_mx col_mx_eq0. Qed.
Lemma orthomxD k m p (A : 'M[R]_(k, n)) (B : 'M[R]_(m, n)) (C : 'M[R]_(p, n)) :
(A '_|_ B + C)%MS = (A '_|_ B)%MS && (A '_|_ C)%MS.
Proof. by rewrite ![(A '_|_ _)%MS]orthomx_sym orthoDmx. Qed.
Lemma orthoZmx p m a (A : 'M[R]_(p, n)) (B : 'M[R]_(m, n)) : a != 0 ->
(a *: A '_|_ B)%MS = (A '_|_ B)%MS.
Proof. by move=> a_neq0; rewrite eqmx_scale. Qed.
Lemma orthomxZ p m a (A : 'M[R]_(p, n)) (B : 'M[R]_(m, n)) : a != 0 ->
(A '_|_ (a *: B))%MS = (A '_|_ B)%MS.
Proof. by move=> a_neq0; rewrite ![(A '_|_ _)%MS]orthomx_sym orthoZmx. Qed.
Lemma eqmx_ortho p m (A : 'M[R]_(p, n)) (B : 'M[R]_(m, n)) :
(A :=: B)%MS -> (A^! :=: B^!)%MS.
Proof.
move=> eqAB; apply/eqmxP.
by rewrite orthomx_sym -eqAB ortho_mx_ortho orthomx_sym eqAB ortho_mx_ortho.
Qed.
Lemma genmx_ortho p (A : 'M[R]_(p, n)) : (<<A>>^! :=: A^!)%MS.
Proof. exact: (eqmx_ortho (genmxE _)). Qed.
End HermitianMxTheory.
End HermitianMx.
End MatrixForms.
Notation symmetricmx := (hermitianmx _ false idfun).
Notation skewmx := (hermitianmx _ true idfun).
Notation hermsymmx := (hermitianmx _ false conjC).
Lemma hermitian1mx_subproof {C : numClosedFieldType} n : (1%:M : 'M[C]_n) \is hermsymmx.
Proof.
by rewrite qualifE /= expr0 scale1r tr_scalar_mx map_scalar_mx conjC1.
Qed.
Canonical hermitian1mx {C : numClosedFieldType} n :=
HermitianMx (@hermitian1mx_subproof C n).
|
Basic.lean
|
/-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
-/
import Mathlib.Data.ENNReal.Real
import Mathlib.Tactic.Bound.Attribute
import Mathlib.Topology.EMetricSpace.Basic
import Mathlib.Topology.MetricSpace.Pseudo.Defs
/-!
## Pseudo-metric spaces
Further results about pseudo-metric spaces.
-/
open Set Filter TopologicalSpace Bornology
open scoped ENNReal NNReal Uniformity Topology
universe u v
variable {α : Type u} {β : Type v} {ι : Type*}
variable [PseudoMetricSpace α]
/-- The triangle (polygon) inequality for sequences of points; `Finset.Ico` version. -/
theorem dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) :
dist (f m) (f n) ≤ ∑ i ∈ Finset.Ico m n, dist (f i) (f (i + 1)) := by
induction n, h using Nat.le_induction with
| base => rw [Finset.Ico_self, Finset.sum_empty, dist_self]
| succ n hle ihn =>
calc
dist (f m) (f (n + 1)) ≤ dist (f m) (f n) + dist (f n) (f (n + 1)) := dist_triangle _ _ _
_ ≤ (∑ i ∈ Finset.Ico m n, _) + _ := add_le_add ihn le_rfl
_ = ∑ i ∈ Finset.Ico m (n + 1), _ := by
rw [← Finset.insert_Ico_right_eq_Ico_add_one hle, Finset.sum_insert, add_comm]; simp
/-- The triangle (polygon) inequality for sequences of points; `Finset.range` version. -/
theorem dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) :
dist (f 0) (f n) ≤ ∑ i ∈ Finset.range n, dist (f i) (f (i + 1)) :=
Nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_dist f (Nat.zero_le n)
/-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
theorem dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ}
(hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f m) (f n) ≤ ∑ i ∈ Finset.Ico m n, d i :=
le_trans (dist_le_Ico_sum_dist f hmn) <|
Finset.sum_le_sum fun _k hk => hd (Finset.mem_Ico.1 hk).1 (Finset.mem_Ico.1 hk).2
/-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
theorem dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ}
(hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f 0) (f n) ≤ ∑ i ∈ Finset.range n, d i :=
Nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_of_dist_le (zero_le n) fun _ => hd
namespace Metric
-- instantiate pseudometric space as a topology
nonrec theorem isUniformInducing_iff [PseudoMetricSpace β] {f : α → β} :
IsUniformInducing f ↔ UniformContinuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
isUniformInducing_iff'.trans <| Iff.rfl.and <|
((uniformity_basis_dist.comap _).le_basis_iff uniformity_basis_dist).trans <| by
simp only [subset_def, Prod.forall, gt_iff_lt, preimage_setOf_eq, Prod.map_apply, mem_setOf]
nonrec theorem isUniformEmbedding_iff [PseudoMetricSpace β] {f : α → β} :
IsUniformEmbedding f ↔ Function.Injective f ∧ UniformContinuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := by
rw [isUniformEmbedding_iff, and_comm, isUniformInducing_iff]
/-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y`. -/
theorem controlled_of_isUniformEmbedding [PseudoMetricSpace β] {f : α → β}
(h : IsUniformEmbedding f) :
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
⟨uniformContinuous_iff.1 h.uniformContinuous, (isUniformEmbedding_iff.1 h).2.2⟩
theorem totallyBounded_iff {s : Set α} :
TotallyBounded s ↔ ∀ ε > 0, ∃ t : Set α, t.Finite ∧ s ⊆ ⋃ y ∈ t, ball y ε :=
uniformity_basis_dist.totallyBounded_iff
/-- A pseudometric space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
theorem totallyBounded_of_finite_discretization {s : Set α}
(H : ∀ ε > (0 : ℝ),
∃ (β : Type u) (_ : Fintype β) (F : s → β), ∀ x y, F x = F y → dist (x : α) y < ε) :
TotallyBounded s := by
rcases s.eq_empty_or_nonempty with hs | hs
· rw [hs]
exact totallyBounded_empty
rcases hs with ⟨x0, hx0⟩
haveI : Inhabited s := ⟨⟨x0, hx0⟩⟩
refine totallyBounded_iff.2 fun ε ε0 => ?_
rcases H ε ε0 with ⟨β, fβ, F, hF⟩
let Finv := Function.invFun F
refine ⟨range (Subtype.val ∘ Finv), finite_range _, fun x xs => ?_⟩
let x' := Finv (F ⟨x, xs⟩)
have : F x' = F ⟨x, xs⟩ := Function.invFun_eq ⟨⟨x, xs⟩, rfl⟩
simp only [Set.mem_iUnion, Set.mem_range]
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
theorem finite_approx_of_totallyBounded {s : Set α} (hs : TotallyBounded s) :
∀ ε > 0, ∃ t, t ⊆ s ∧ Set.Finite t ∧ s ⊆ ⋃ y ∈ t, ball y ε := by
intro ε ε_pos
rw [totallyBounded_iff_subset] at hs
exact hs _ (dist_mem_uniformity ε_pos)
/-- Expressing uniform convergence using `dist` -/
theorem tendstoUniformlyOnFilter_iff {F : ι → β → α} {f : β → α} {p : Filter ι} {p' : Filter β} :
TendstoUniformlyOnFilter F f p p' ↔
∀ ε > 0, ∀ᶠ n : ι × β in p ×ˢ p', dist (f n.snd) (F n.fst n.snd) < ε := by
refine ⟨fun H ε hε => H _ (dist_mem_uniformity hε), fun H u hu => ?_⟩
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩
exact (H ε εpos).mono fun n hn => hε hn
/-- Expressing locally uniform convergence on a set using `dist`. -/
theorem tendstoLocallyUniformlyOn_iff [TopologicalSpace β] {F : ι → β → α} {f : β → α}
{p : Filter ι} {s : Set β} :
TendstoLocallyUniformlyOn F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := by
refine ⟨fun H ε hε => H _ (dist_mem_uniformity hε), fun H u hu x hx => ?_⟩
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩
rcases H ε εpos x hx with ⟨t, ht, Ht⟩
exact ⟨t, ht, Ht.mono fun n hs x hx => hε (hs x hx)⟩
/-- Expressing uniform convergence on a set using `dist`. -/
theorem tendstoUniformlyOn_iff {F : ι → β → α} {f : β → α} {p : Filter ι} {s : Set β} :
TendstoUniformlyOn F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε := by
refine ⟨fun H ε hε => H _ (dist_mem_uniformity hε), fun H u hu => ?_⟩
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩
exact (H ε εpos).mono fun n hs x hx => hε (hs x hx)
/-- Expressing locally uniform convergence using `dist`. -/
theorem tendstoLocallyUniformly_iff [TopologicalSpace β] {F : ι → β → α} {f : β → α}
{p : Filter ι} :
TendstoLocallyUniformly F f p ↔
∀ ε > 0, ∀ x : β, ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := by
simp only [← tendstoLocallyUniformlyOn_univ, tendstoLocallyUniformlyOn_iff, nhdsWithin_univ,
mem_univ, forall_const]
/-- Expressing uniform convergence using `dist`. -/
theorem tendstoUniformly_iff {F : ι → β → α} {f : β → α} {p : Filter ι} :
TendstoUniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε := by
rw [← tendstoUniformlyOn_univ, tendstoUniformlyOn_iff]
simp
protected theorem cauchy_iff {f : Filter α} :
Cauchy f ↔ NeBot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x ∈ t, ∀ y ∈ t, dist x y < ε :=
uniformity_basis_dist.cauchy_iff
variable {s : Set α}
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball
centered at `x` and intersecting `s` only at `x`. -/
theorem exists_ball_inter_eq_singleton_of_mem_discrete [DiscreteTopology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, Metric.ball x ε ∩ s = {x} :=
nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball
of positive radius centered at `x` and intersecting `s` only at `x`. -/
theorem exists_closedBall_inter_eq_singleton_of_discrete [DiscreteTopology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, Metric.closedBall x ε ∩ s = {x} :=
nhds_basis_closedBall.exists_inter_eq_singleton_of_mem_discrete hx
end Metric
open Metric
theorem Metric.inseparable_iff_nndist {x y : α} : Inseparable x y ↔ nndist x y = 0 := by
rw [EMetric.inseparable_iff, edist_nndist, ENNReal.coe_eq_zero]
alias ⟨Inseparable.nndist_eq_zero, _⟩ := Metric.inseparable_iff_nndist
theorem Metric.inseparable_iff {x y : α} : Inseparable x y ↔ dist x y = 0 := by
rw [Metric.inseparable_iff_nndist, dist_nndist, NNReal.coe_eq_zero]
alias ⟨Inseparable.dist_eq_zero, _⟩ := Metric.inseparable_iff
/-- A weaker version of `tendsto_nhds_unique` for `PseudoMetricSpace`. -/
theorem tendsto_nhds_unique_dist {f : β → α} {l : Filter β} {x y : α} [NeBot l]
(ha : Tendsto f l (𝓝 x)) (hb : Tendsto f l (𝓝 y)) : dist x y = 0 :=
(tendsto_nhds_unique_inseparable ha hb).dist_eq_zero
section Real
theorem cauchySeq_iff_tendsto_dist_atTop_0 [Nonempty β] [SemilatticeSup β] {u : β → α} :
CauchySeq u ↔ Tendsto (fun n : β × β => dist (u n.1) (u n.2)) atTop (𝓝 0) := by
rw [cauchySeq_iff_tendsto, Metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff,
Function.comp_def]
simp_rw [Prod.map_fst, Prod.map_snd]
end Real
namespace Topology
/-- The preimage of a separable set by an inducing map is separable. -/
protected lemma IsInducing.isSeparable_preimage {f : β → α} [TopologicalSpace β]
(hf : IsInducing f) {s : Set α} (hs : IsSeparable s) : IsSeparable (f ⁻¹' s) := by
have : SeparableSpace s := hs.separableSpace
have : SecondCountableTopology s := UniformSpace.secondCountable_of_separable _
have : IsInducing ((mapsTo_preimage f s).restrict _ _ _) :=
(hf.comp IsInducing.subtypeVal).codRestrict _
have := this.secondCountableTopology
exact .of_subtype _
protected theorem IsEmbedding.isSeparable_preimage {f : β → α} [TopologicalSpace β]
(hf : IsEmbedding f) {s : Set α} (hs : IsSeparable s) : IsSeparable (f ⁻¹' s) :=
hf.isInducing.isSeparable_preimage hs
end Topology
/-- A compact set is separable. -/
theorem IsCompact.isSeparable {s : Set α} (hs : IsCompact s) : IsSeparable s :=
haveI : CompactSpace s := isCompact_iff_compactSpace.mp hs
.of_subtype s
namespace Metric
section SecondCountable
open TopologicalSpace
/-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which
is `ε`-dense. -/
theorem secondCountable_of_almost_dense_set
(H : ∀ ε > (0 : ℝ), ∃ s : Set α, s.Countable ∧ ∀ x, ∃ y ∈ s, dist x y ≤ ε) :
SecondCountableTopology α := by
refine EMetric.secondCountable_of_almost_dense_set fun ε ε0 => ?_
rcases ENNReal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩
choose s hsc y hys hyx using H ε' (mod_cast ε'0)
refine ⟨s, hsc, iUnion₂_eq_univ_iff.2 fun x => ⟨y x, hys _, le_trans ?_ ε'ε.le⟩⟩
exact mod_cast hyx x
end SecondCountable
end Metric
section Compact
variable {X : Type*} [PseudoMetricSpace X] {s : Set X} {ε : ℝ}
/-- Any compact set in a pseudometric space can be covered by finitely many balls of a given
positive radius -/
theorem finite_cover_balls_of_compact (hs : IsCompact s) {e : ℝ} (he : 0 < e) :
∃ t ⊆ s, t.Finite ∧ s ⊆ ⋃ x ∈ t, ball x e :=
let ⟨t, hts, ht⟩ := hs.elim_nhds_subcover _ (fun x _ => ball_mem_nhds x he)
⟨t, hts, t.finite_toSet, ht⟩
alias IsCompact.finite_cover_balls := finite_cover_balls_of_compact
/-- Any relatively compact set in a pseudometric space can be covered by finitely many balls of a
given positive radius. -/
lemma exists_finite_cover_balls_of_isCompact_closure (hs : IsCompact (closure s)) (hε : 0 < ε) :
∃ t ⊆ s, t.Finite ∧ s ⊆ ⋃ x ∈ t, ball x ε := by
obtain ⟨t, hst⟩ := hs.elim_finite_subcover (fun x : s ↦ ball x ε) (fun _ ↦ isOpen_ball) fun x hx ↦
let ⟨y, hy, hxy⟩ := Metric.mem_closure_iff.1 hx _ hε; mem_iUnion.2 ⟨⟨y, hy⟩, hxy⟩
refine ⟨t.map ⟨Subtype.val, Subtype.val_injective⟩, by simp, Finset.finite_toSet _, ?_⟩
simpa using subset_closure.trans hst
end Compact
/-- If a map is continuous on a separable set `s`, then the image of `s` is also separable. -/
theorem ContinuousOn.isSeparable_image [TopologicalSpace β] {f : α → β} {s : Set α}
(hf : ContinuousOn f s) (hs : IsSeparable s) : IsSeparable (f '' s) := by
rw [image_eq_range, ← image_univ]
exact (isSeparable_univ_iff.2 hs.separableSpace).image hf.restrict
|
SpecificDegree.lean
|
/-
Copyright (c) 2024 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Alex J. Best
-/
import Mathlib.Algebra.Polynomial.Roots
import Mathlib.Tactic.IntervalCases
import Mathlib.Algebra.Polynomial.FieldDivision
/-!
# Polynomials of specific degree
Facts about polynomials that have a specific integer degree.
-/
namespace Polynomial
section IsDomain
variable {R : Type*} [CommRing R] [IsDomain R]
/-- A polynomial of degree 2 or 3 is irreducible iff it doesn't have roots. -/
theorem Monic.irreducible_iff_roots_eq_zero_of_degree_le_three {p : R[X]} (hp : p.Monic)
(hp2 : 2 ≤ p.natDegree) (hp3 : p.natDegree ≤ 3) : Irreducible p ↔ p.roots = 0 := by
have hp0 : p ≠ 0 := hp.ne_zero
have hp1 : p ≠ 1 := by rintro rfl; rw [natDegree_one] at hp2; cases hp2
rw [hp.irreducible_iff_lt_natDegree_lt hp1]
simp_rw [show p.natDegree / 2 = 1 from
(Nat.div_le_div_right hp3).antisymm
(by apply Nat.div_le_div_right (c := 2) hp2),
show Finset.Ioc 0 1 = {1} from rfl,
Finset.mem_singleton, Multiset.eq_zero_iff_forall_notMem, mem_roots hp0, ← dvd_iff_isRoot]
refine ⟨fun h r ↦ h _ (monic_X_sub_C r) (natDegree_X_sub_C r), fun h q hq hq1 ↦ ?_⟩
rw [hq.eq_X_add_C hq1, ← sub_neg_eq_add, ← C_neg]
apply h
end IsDomain
section Field
variable {K : Type*} [Field K] {p : K[X]}
/-- A polynomial of degree 2 or 3 is irreducible iff it doesn't have roots. -/
theorem irreducible_iff_roots_eq_zero_of_degree_le_three
(hp2 : 2 ≤ p.natDegree) (hp3 : p.natDegree ≤ 3) :
Irreducible p ↔ p.roots = 0 := by
have hp0 : p ≠ 0 := by rintro rfl; rw [natDegree_zero] at hp2; cases hp2
rw [← irreducible_mul_leadingCoeff_inv,
(monic_mul_leadingCoeff_inv hp0).irreducible_iff_roots_eq_zero_of_degree_le_three,
mul_comm, roots_C_mul]
· exact inv_ne_zero (leadingCoeff_ne_zero.mpr hp0)
· rwa [natDegree_mul_leadingCoeff_inv _ hp0]
· rwa [natDegree_mul_leadingCoeff_inv _ hp0]
lemma irreducible_of_degree_le_three_of_not_isRoot
(hdeg : p.natDegree ∈ Finset.Icc 1 3) (hnot : ∀ x, ¬ IsRoot p x) :
Irreducible p := by
rw [Finset.mem_Icc] at hdeg
by_cases hdeg2 : 2 ≤ p.natDegree
· rw [Polynomial.irreducible_iff_roots_eq_zero_of_degree_le_three hdeg2 hdeg.2]
apply Multiset.eq_zero_of_forall_notMem
simp_all
· apply Polynomial.irreducible_of_degree_eq_one
rw [← Nat.cast_one, Polynomial.degree_eq_iff_natDegree_eq_of_pos (by simp)]
exact le_antisymm (by rwa [not_le, Nat.lt_succ_iff] at hdeg2) hdeg.1
end Field
end Polynomial
|
Hausdorff.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.Topology.Compactness.SigmaCompact
import Mathlib.Topology.Irreducible
import Mathlib.Topology.Separation.Basic
/-!
# T₂ and T₂.₅ spaces.
This file defines the T₂ (Hausdorff) condition, which is the most commonly-used among the various
separation axioms, and the related T₂.₅ condition.
## Main definitions
* `T2Space`: A T₂/Hausdorff space is a space where, for every two points `x ≠ y`,
there is two disjoint open sets, one containing `x`, and the other `y`. T₂ implies T₁ and R₁.
* `T25Space`: A T₂.₅/Urysohn space is a space where, for every two points `x ≠ y`,
there is two open sets, one containing `x`, and the other `y`, whose closures are disjoint.
T₂.₅ implies T₂.
See `Mathlib/Topology/Separation/Regular.lean` for regular, T₃, etc spaces; and
`Mathlib/Topology/Separation/GDelta.lean` for the definitions of `PerfectlyNormalSpace` and
`T6Space`.
Note that `mathlib` adopts the modern convention that `m ≤ n` if and only if `T_m → T_n`, but
occasionally the literature swaps definitions for e.g. T₃ and regular.
## Main results
### T₂ spaces
* `t2_iff_nhds`: A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter.
* `t2_iff_isClosed_diagonal`: A space is T₂ iff the `diagonal` of `X` (that is, the set of all
points of the form `(a, a) : X × X`) is closed under the product topology.
* `separatedNhds_of_finset_finset`: Any two disjoint finsets are `SeparatedNhds`.
* Most topological constructions preserve Hausdorffness;
these results are part of the typeclass inference system (e.g. `Topology.IsEmbedding.t2Space`)
* `Set.EqOn.closure`: If two functions are equal on some set `s`, they are equal on its closure.
* `IsCompact.isClosed`: All compact sets are closed.
* `WeaklyLocallyCompactSpace.locallyCompactSpace`: If a topological space is both
weakly locally compact (i.e., each point has a compact neighbourhood)
and is T₂, then it is locally compact.
* `totallySeparatedSpace_of_t1_of_basis_clopen`: If `X` has a clopen basis, then
it is a `TotallySeparatedSpace`.
* `loc_compact_t2_tot_disc_iff_tot_sep`: A locally compact T₂ space is totally disconnected iff
it is totally separated.
* `T2Quotient`: the largest T2 quotient of a given topological space.
If the space is also compact:
* `normalOfCompactT2`: A compact T₂ space is a `NormalSpace`.
* `connectedComponent_eq_iInter_isClopen`: The connected component of a point
is the intersection of all its clopen neighbourhoods.
* `compact_t2_tot_disc_iff_tot_sep`: Being a `TotallyDisconnectedSpace`
is equivalent to being a `TotallySeparatedSpace`.
* `ConnectedComponents.t2`: `ConnectedComponents X` is T₂ for `X` T₂ and compact.
## References
* <https://en.wikipedia.org/wiki/Separation_axiom>
* [Willard's *General Topology*][zbMATH02107988]
-/
open Function Set Filter Topology TopologicalSpace
universe u v
variable {X : Type*} {Y : Type*} [TopologicalSpace X]
section Separation
/-- A T₂ space, also known as a Hausdorff space, is one in which for every
`x ≠ y` there exists disjoint open sets around `x` and `y`. This is
the most widely used of the separation axioms. -/
@[mk_iff]
class T2Space (X : Type u) [TopologicalSpace X] : Prop where
/-- Every two points in a Hausdorff space admit disjoint open neighbourhoods. -/
t2 : Pairwise fun x y => ∃ u v : Set X, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v
/-- Two different points can be separated by open sets. -/
theorem t2_separation [T2Space X] {x y : X} (h : x ≠ y) :
∃ u v : Set X, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v :=
T2Space.t2 h
-- todo: use this as a definition?
theorem t2Space_iff_disjoint_nhds : T2Space X ↔ Pairwise fun x y : X => Disjoint (𝓝 x) (𝓝 y) := by
refine (t2Space_iff X).trans (forall₃_congr fun x y _ => ?_)
simp only [(nhds_basis_opens x).disjoint_iff (nhds_basis_opens y), ← exists_and_left,
and_assoc, and_comm, and_left_comm]
@[simp]
theorem disjoint_nhds_nhds [T2Space X] {x y : X} : Disjoint (𝓝 x) (𝓝 y) ↔ x ≠ y :=
⟨fun hd he => by simp [he, nhds_neBot.ne] at hd, (t2Space_iff_disjoint_nhds.mp ‹_› ·)⟩
theorem pairwise_disjoint_nhds [T2Space X] : Pairwise (Disjoint on (𝓝 : X → Filter X)) := fun _ _ =>
disjoint_nhds_nhds.2
protected theorem Set.pairwiseDisjoint_nhds [T2Space X] (s : Set X) : s.PairwiseDisjoint 𝓝 :=
pairwise_disjoint_nhds.set_pairwise s
/-- Points of a finite set can be separated by open sets from each other. -/
theorem Set.Finite.t2_separation [T2Space X] {s : Set X} (hs : s.Finite) :
∃ U : X → Set X, (∀ x, x ∈ U x ∧ IsOpen (U x)) ∧ s.PairwiseDisjoint U :=
s.pairwiseDisjoint_nhds.exists_mem_filter_basis hs nhds_basis_opens
-- see Note [lower instance priority]
instance (priority := 100) T2Space.t1Space [T2Space X] : T1Space X :=
t1Space_iff_disjoint_pure_nhds.mpr fun _ _ hne =>
(disjoint_nhds_nhds.2 hne).mono_left <| pure_le_nhds _
-- see Note [lower instance priority]
instance (priority := 100) T2Space.r1Space [T2Space X] : R1Space X :=
⟨fun x y ↦ (eq_or_ne x y).imp specializes_of_eq disjoint_nhds_nhds.2⟩
theorem SeparationQuotient.t2Space_iff : T2Space (SeparationQuotient X) ↔ R1Space X := by
simp only [t2Space_iff_disjoint_nhds, Pairwise, surjective_mk.forall₂, ne_eq, mk_eq_mk,
r1Space_iff_inseparable_or_disjoint_nhds, ← disjoint_comap_iff surjective_mk, comap_mk_nhds_mk,
← or_iff_not_imp_left]
instance SeparationQuotient.t2Space [R1Space X] : T2Space (SeparationQuotient X) :=
t2Space_iff.2 ‹_›
instance (priority := 80) [R1Space X] [T0Space X] : T2Space X :=
t2Space_iff_disjoint_nhds.2 fun _x _y hne ↦ disjoint_nhds_nhds_iff_not_inseparable.2 fun hxy ↦
hne hxy.eq
theorem R1Space.t2Space_iff_t0Space [R1Space X] : T2Space X ↔ T0Space X := by
constructor <;> intro <;> infer_instance
/-- A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. -/
theorem t2_iff_nhds : T2Space X ↔ ∀ {x y : X}, NeBot (𝓝 x ⊓ 𝓝 y) → x = y := by
simp only [t2Space_iff_disjoint_nhds, disjoint_iff, neBot_iff, Ne, not_imp_comm, Pairwise]
theorem eq_of_nhds_neBot [T2Space X] {x y : X} (h : NeBot (𝓝 x ⊓ 𝓝 y)) : x = y :=
t2_iff_nhds.mp ‹_› h
theorem t2Space_iff_nhds :
T2Space X ↔ Pairwise fun x y : X => ∃ U ∈ 𝓝 x, ∃ V ∈ 𝓝 y, Disjoint U V := by
simp only [t2Space_iff_disjoint_nhds, Filter.disjoint_iff, Pairwise]
theorem t2_separation_nhds [T2Space X] {x y : X} (h : x ≠ y) :
∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ Disjoint u v :=
let ⟨u, v, open_u, open_v, x_in, y_in, huv⟩ := t2_separation h
⟨u, v, open_u.mem_nhds x_in, open_v.mem_nhds y_in, huv⟩
theorem t2_separation_compact_nhds [LocallyCompactSpace X] [T2Space X] {x y : X} (h : x ≠ y) :
∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ IsCompact u ∧ IsCompact v ∧ Disjoint u v := by
simpa only [exists_prop, ← exists_and_left, and_comm, and_assoc, and_left_comm] using
((compact_basis_nhds x).disjoint_iff (compact_basis_nhds y)).1 (disjoint_nhds_nhds.2 h)
theorem t2_iff_ultrafilter :
T2Space X ↔ ∀ {x y : X} (f : Ultrafilter X), ↑f ≤ 𝓝 x → ↑f ≤ 𝓝 y → x = y :=
t2_iff_nhds.trans <| by simp only [← exists_ultrafilter_iff, and_imp, le_inf_iff, exists_imp]
theorem t2_iff_isClosed_diagonal : T2Space X ↔ IsClosed (diagonal X) := by
simp only [t2Space_iff_disjoint_nhds, ← isOpen_compl_iff, isOpen_iff_mem_nhds, Prod.forall,
nhds_prod_eq, compl_diagonal_mem_prod, mem_compl_iff, mem_diagonal_iff, Pairwise]
theorem isClosed_diagonal [T2Space X] : IsClosed (diagonal X) :=
t2_iff_isClosed_diagonal.mp ‹_›
theorem tendsto_nhds_unique [T2Space X] {f : Y → X} {l : Filter Y} {a b : X} [NeBot l]
(ha : Tendsto f l (𝓝 a)) (hb : Tendsto f l (𝓝 b)) : a = b :=
(tendsto_nhds_unique_inseparable ha hb).eq
theorem tendsto_nhds_unique' [T2Space X] {f : Y → X} {l : Filter Y} {a b : X} (_ : NeBot l)
(ha : Tendsto f l (𝓝 a)) (hb : Tendsto f l (𝓝 b)) : a = b :=
tendsto_nhds_unique ha hb
theorem tendsto_nhds_unique_of_eventuallyEq [T2Space X] {f g : Y → X} {l : Filter Y} {a b : X}
[NeBot l] (ha : Tendsto f l (𝓝 a)) (hb : Tendsto g l (𝓝 b)) (hfg : f =ᶠ[l] g) : a = b :=
tendsto_nhds_unique (ha.congr' hfg) hb
theorem tendsto_nhds_unique_of_frequently_eq [T2Space X] {f g : Y → X} {l : Filter Y} {a b : X}
(ha : Tendsto f l (𝓝 a)) (hb : Tendsto g l (𝓝 b)) (hfg : ∃ᶠ x in l, f x = g x) : a = b :=
have : ∃ᶠ z : X × X in 𝓝 (a, b), z.1 = z.2 := (ha.prodMk_nhds hb).frequently hfg
not_not.1 fun hne => this (isClosed_diagonal.isOpen_compl.mem_nhds hne)
/-- If `s` and `t` are compact sets in a T₂ space, then the set neighborhoods filter of `s ∩ t`
is the infimum of set neighborhoods filters for `s` and `t`.
For general sets, only the `≤` inequality holds, see `nhdsSet_inter_le`. -/
theorem IsCompact.nhdsSet_inter_eq [T2Space X] {s t : Set X} (hs : IsCompact s) (ht : IsCompact t) :
𝓝ˢ (s ∩ t) = 𝓝ˢ s ⊓ 𝓝ˢ t := by
refine le_antisymm (nhdsSet_inter_le _ _) ?_
simp_rw [hs.nhdsSet_inf_eq_biSup, ht.inf_nhdsSet_eq_biSup, nhdsSet, sSup_image]
refine iSup₂_le fun x hxs ↦ iSup₂_le fun y hyt ↦ ?_
rcases eq_or_ne x y with (rfl | hne)
· exact le_iSup₂_of_le x ⟨hxs, hyt⟩ (inf_idem _).le
· exact (disjoint_nhds_nhds.mpr hne).eq_bot ▸ bot_le
/-- In a `T2Space X`, for a compact set `t` and a point `x` outside `t`, there are open sets `U`,
`V` that separate `t` and `x`. -/
lemma IsCompact.separation_of_notMem {X : Type u_1} [TopologicalSpace X] [T2Space X] {x : X}
{t : Set X} (H1 : IsCompact t) (H2 : x ∉ t) :
∃ (U : Set X), ∃ (V : Set X), IsOpen U ∧ IsOpen V ∧ t ⊆ U ∧ x ∈ V ∧ Disjoint U V := by
simpa [SeparatedNhds] using SeparatedNhds.of_isCompact_isCompact_isClosed H1 isCompact_singleton
isClosed_singleton <| disjoint_singleton_right.mpr H2
@[deprecated (since := "2025-05-23")]
alias IsCompact.separation_of_not_mem := IsCompact.separation_of_notMem
/-- In a `T2Space X`, for a compact set `t` and a point `x` outside `t`, `𝓝ˢ t` and `𝓝 x` are
disjoint. -/
lemma IsCompact.disjoint_nhdsSet_nhds {X : Type u_1} [TopologicalSpace X] [T2Space X] {x : X}
{t : Set X} (H1 : IsCompact t) (H2 : x ∉ t) :
Disjoint (𝓝ˢ t) (𝓝 x) := by
simpa using SeparatedNhds.disjoint_nhdsSet <| .of_isCompact_isCompact_isClosed H1
isCompact_singleton isClosed_singleton <| disjoint_singleton_right.mpr H2
/-- If a function `f` is
- injective on a compact set `s`;
- continuous at every point of this set;
- injective on a neighborhood of each point of this set,
then it is injective on a neighborhood of this set. -/
theorem Set.InjOn.exists_mem_nhdsSet {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y]
[T2Space Y] {f : X → Y} {s : Set X} (inj : InjOn f s) (sc : IsCompact s)
(fc : ∀ x ∈ s, ContinuousAt f x) (loc : ∀ x ∈ s, ∃ u ∈ 𝓝 x, InjOn f u) :
∃ t ∈ 𝓝ˢ s, InjOn f t := by
have : ∀ x ∈ s ×ˢ s, ∀ᶠ y in 𝓝 x, f y.1 = f y.2 → y.1 = y.2 := fun (x, y) ⟨hx, hy⟩ ↦ by
rcases eq_or_ne x y with rfl | hne
· rcases loc x hx with ⟨u, hu, hf⟩
exact Filter.mem_of_superset (prod_mem_nhds hu hu) <| forall_prod_set.2 hf
· suffices ∀ᶠ z in 𝓝 (x, y), f z.1 ≠ f z.2 from this.mono fun _ hne h ↦ absurd h hne
refine (fc x hx).prodMap' (fc y hy) <| isClosed_diagonal.isOpen_compl.mem_nhds ?_
exact inj.ne hx hy hne
rw [← eventually_nhdsSet_iff_forall, sc.nhdsSet_prod_eq sc] at this
exact eventually_prod_self_iff.1 this
/-- If a function `f` is
- injective on a compact set `s`;
- continuous at every point of this set;
- injective on a neighborhood of each point of this set,
then it is injective on an open neighborhood of this set. -/
theorem Set.InjOn.exists_isOpen_superset {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y]
[T2Space Y] {f : X → Y} {s : Set X} (inj : InjOn f s) (sc : IsCompact s)
(fc : ∀ x ∈ s, ContinuousAt f x) (loc : ∀ x ∈ s, ∃ u ∈ 𝓝 x, InjOn f u) :
∃ t, IsOpen t ∧ s ⊆ t ∧ InjOn f t :=
let ⟨_t, hst, ht⟩ := inj.exists_mem_nhdsSet sc fc loc
let ⟨u, huo, hsu, hut⟩ := mem_nhdsSet_iff_exists.1 hst
⟨u, huo, hsu, ht.mono hut⟩
section limUnder
variable [T2Space X] {f : Filter X}
/-!
### Properties of `lim` and `limUnder`
In this section we use explicit `Nonempty X` instances for `lim` and `limUnder`. This way the lemmas
are useful without a `Nonempty X` instance.
-/
theorem lim_eq {x : X} [NeBot f] (h : f ≤ 𝓝 x) : @lim _ _ ⟨x⟩ f = x :=
tendsto_nhds_unique (le_nhds_lim ⟨x, h⟩) h
theorem lim_eq_iff [NeBot f] (h : ∃ x : X, f ≤ 𝓝 x) {x} : @lim _ _ ⟨x⟩ f = x ↔ f ≤ 𝓝 x :=
⟨fun c => c ▸ le_nhds_lim h, lim_eq⟩
theorem Ultrafilter.lim_eq_iff_le_nhds [CompactSpace X] {x : X} {F : Ultrafilter X} :
F.lim = x ↔ ↑F ≤ 𝓝 x :=
⟨fun h => h ▸ F.le_nhds_lim, lim_eq⟩
theorem isOpen_iff_ultrafilter' [CompactSpace X] (U : Set X) :
IsOpen U ↔ ∀ F : Ultrafilter X, F.lim ∈ U → U ∈ F.1 := by
rw [isOpen_iff_ultrafilter]
refine ⟨fun h F hF => h F.lim hF F F.le_nhds_lim, ?_⟩
intro cond x hx f h
rw [← Ultrafilter.lim_eq_iff_le_nhds.2 h] at hx
exact cond _ hx
theorem Filter.Tendsto.limUnder_eq {x : X} {f : Filter Y} [NeBot f] {g : Y → X}
(h : Tendsto g f (𝓝 x)) : @limUnder _ _ _ ⟨x⟩ f g = x :=
lim_eq h
theorem Filter.limUnder_eq_iff {f : Filter Y} [NeBot f] {g : Y → X} (h : ∃ x, Tendsto g f (𝓝 x))
{x} : @limUnder _ _ _ ⟨x⟩ f g = x ↔ Tendsto g f (𝓝 x) :=
⟨fun c => c ▸ tendsto_nhds_limUnder h, Filter.Tendsto.limUnder_eq⟩
theorem Continuous.limUnder_eq [TopologicalSpace Y] {f : Y → X} (h : Continuous f) (y : Y) :
@limUnder _ _ _ ⟨f y⟩ (𝓝 y) f = f y :=
(h.tendsto y).limUnder_eq
@[simp]
theorem lim_nhds (x : X) : @lim _ _ ⟨x⟩ (𝓝 x) = x :=
lim_eq le_rfl
@[simp]
theorem limUnder_nhds_id (x : X) : @limUnder _ _ _ ⟨x⟩ (𝓝 x) id = x :=
lim_nhds x
@[simp]
theorem lim_nhdsWithin {x : X} {s : Set X} (h : x ∈ closure s) : @lim _ _ ⟨x⟩ (𝓝[s] x) = x :=
haveI : NeBot (𝓝[s] x) := mem_closure_iff_clusterPt.1 h
lim_eq inf_le_left
@[simp]
theorem limUnder_nhdsWithin_id {x : X} {s : Set X} (h : x ∈ closure s) :
@limUnder _ _ _ ⟨x⟩ (𝓝[s] x) id = x :=
lim_nhdsWithin h
end limUnder
/-!
### `T2Space` constructions
We use two lemmas to prove that various standard constructions generate Hausdorff spaces from
Hausdorff spaces:
* `separated_by_continuous` says that two points `x y : X` can be separated by open neighborhoods
provided that there exists a continuous map `f : X → Y` with a Hausdorff codomain such that
`f x ≠ f y`. We use this lemma to prove that topological spaces defined using `induced` are
Hausdorff spaces.
* `separated_by_isOpenEmbedding` says that for an open embedding `f : X → Y` of a Hausdorff space
`X`, the images of two distinct points `x y : X`, `x ≠ y` can be separated by open neighborhoods.
We use this lemma to prove that topological spaces defined using `coinduced` are Hausdorff spaces.
-/
-- see Note [lower instance priority]
instance (priority := 100) DiscreteTopology.toT2Space
[DiscreteTopology X] : T2Space X :=
⟨fun x y h => ⟨{x}, {y}, isOpen_discrete _, isOpen_discrete _, rfl, rfl, disjoint_singleton.2 h⟩⟩
theorem separated_by_continuous [TopologicalSpace Y] [T2Space Y]
{f : X → Y} (hf : Continuous f) {x y : X} (h : f x ≠ f y) :
∃ u v : Set X, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v :=
let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h
⟨f ⁻¹' u, f ⁻¹' v, uo.preimage hf, vo.preimage hf, xu, yv, uv.preimage _⟩
theorem separated_by_isOpenEmbedding [TopologicalSpace Y] [T2Space X]
{f : X → Y} (hf : IsOpenEmbedding f) {x y : X} (h : x ≠ y) :
∃ u v : Set Y, IsOpen u ∧ IsOpen v ∧ f x ∈ u ∧ f y ∈ v ∧ Disjoint u v :=
let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h
⟨f '' u, f '' v, hf.isOpenMap _ uo, hf.isOpenMap _ vo, mem_image_of_mem _ xu,
mem_image_of_mem _ yv, disjoint_image_of_injective hf.injective uv⟩
instance {p : X → Prop} [T2Space X] : T2Space (Subtype p) := inferInstance
instance Prod.t2Space [T2Space X] [TopologicalSpace Y] [T2Space Y] : T2Space (X × Y) :=
inferInstance
/-- If the codomain of an injective continuous function is a Hausdorff space, then so is its
domain. -/
theorem T2Space.of_injective_continuous [TopologicalSpace Y] [T2Space Y] {f : X → Y}
(hinj : Injective f) (hc : Continuous f) : T2Space X :=
⟨fun _ _ h => separated_by_continuous hc (hinj.ne h)⟩
/-- If the codomain of a topological embedding is a Hausdorff space, then so is its domain.
See also `T2Space.of_continuous_injective`. -/
theorem Topology.IsEmbedding.t2Space [TopologicalSpace Y] [T2Space Y] {f : X → Y}
(hf : IsEmbedding f) : T2Space X :=
.of_injective_continuous hf.injective hf.continuous
protected theorem Homeomorph.t2Space [TopologicalSpace Y] [T2Space X] (h : X ≃ₜ Y) : T2Space Y :=
h.symm.isEmbedding.t2Space
instance ULift.instT2Space [T2Space X] : T2Space (ULift X) :=
IsEmbedding.uliftDown.t2Space
instance [T2Space X] [TopologicalSpace Y] [T2Space Y] :
T2Space (X ⊕ Y) := by
constructor
rintro (x | x) (y | y) h
· exact separated_by_isOpenEmbedding .inl <| ne_of_apply_ne _ h
· exact separated_by_continuous continuous_isLeft <| by simp
· exact separated_by_continuous continuous_isLeft <| by simp
· exact separated_by_isOpenEmbedding .inr <| ne_of_apply_ne _ h
instance Pi.t2Space {Y : X → Type v} [∀ a, TopologicalSpace (Y a)]
[∀ a, T2Space (Y a)] : T2Space (∀ a, Y a) :=
inferInstance
instance Sigma.t2Space {ι} {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ a, T2Space (X a)] :
T2Space (Σ i, X i) := by
constructor
rintro ⟨i, x⟩ ⟨j, y⟩ neq
rcases eq_or_ne i j with (rfl | h)
· replace neq : x ≠ y := ne_of_apply_ne _ neq
exact separated_by_isOpenEmbedding .sigmaMk neq
· let _ := (⊥ : TopologicalSpace ι); have : DiscreteTopology ι := ⟨rfl⟩
exact separated_by_continuous (continuous_def.2 fun u _ => isOpen_sigma_fst_preimage u) h
section
variable (X)
/-- The smallest equivalence relation on a topological space giving a T2 quotient. -/
def t2Setoid : Setoid X := sInf {s | T2Space (Quotient s)}
/-- The largest T2 quotient of a topological space. This construction is left-adjoint to the
inclusion of T2 spaces into all topological spaces. -/
def T2Quotient := Quotient (t2Setoid X)
@[deprecated (since := "2025-05-15")] alias t2Quotient := T2Quotient
namespace T2Quotient
variable {X}
instance : TopologicalSpace (T2Quotient X) :=
inferInstanceAs <| TopologicalSpace (Quotient _)
/-- The map from a topological space to its largest T2 quotient. -/
def mk : X → T2Quotient X := Quotient.mk (t2Setoid X)
lemma mk_eq {x y : X} : mk x = mk y ↔ ∀ s : Setoid X, T2Space (Quotient s) → s x y :=
Setoid.quotient_mk_sInf_eq
variable (X)
lemma surjective_mk : Surjective (mk : X → T2Quotient X) := Quotient.mk_surjective
lemma continuous_mk : Continuous (mk : X → T2Quotient X) :=
continuous_quotient_mk'
variable {X}
@[elab_as_elim]
protected lemma inductionOn {motive : T2Quotient X → Prop} (q : T2Quotient X)
(h : ∀ x, motive (T2Quotient.mk x)) : motive q := Quotient.inductionOn q h
@[elab_as_elim]
protected lemma inductionOn₂ [TopologicalSpace Y] {motive : T2Quotient X → T2Quotient Y → Prop}
(q : T2Quotient X) (q' : T2Quotient Y) (h : ∀ x y, motive (mk x) (mk y)) : motive q q' :=
Quotient.inductionOn₂ q q' h
/-- The largest T2 quotient of a topological space is indeed T2. -/
instance : T2Space (T2Quotient X) := by
rw [t2Space_iff]
rintro ⟨x⟩ ⟨y⟩ (h : ¬ T2Quotient.mk x = T2Quotient.mk y)
obtain ⟨s, hs, hsxy⟩ : ∃ s, T2Space (Quotient s) ∧ Quotient.mk s x ≠ Quotient.mk s y := by
simpa [T2Quotient.mk_eq] using h
exact separated_by_continuous (continuous_map_sInf (by exact hs)) hsxy
lemma compatible {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y]
{f : X → Y} (hf : Continuous f) : letI _ := t2Setoid X
∀ (a b : X), a ≈ b → f a = f b := by
change t2Setoid X ≤ Setoid.ker f
exact sInf_le <| .of_injective_continuous
(Setoid.ker_lift_injective _) (hf.quotient_lift fun _ _ ↦ id)
/-- The universal property of the largest T2 quotient of a topological space `X`: any continuous
map from `X` to a T2 space `Y` uniquely factors through `T2Quotient X`. This declaration builds the
factored map. Its continuity is `T2Quotient.continuous_lift`, the fact that it indeed factors the
original map is `T2Quotient.lift_mk` and uniqueness is `T2Quotient.unique_lift`. -/
def lift {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y]
{f : X → Y} (hf : Continuous f) : T2Quotient X → Y :=
Quotient.lift f (T2Quotient.compatible hf)
lemma continuous_lift {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y]
{f : X → Y} (hf : Continuous f) : Continuous (T2Quotient.lift hf) :=
continuous_coinduced_dom.mpr hf
@[simp]
lemma lift_mk {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y]
{f : X → Y} (hf : Continuous f) (x : X) : lift hf (mk x) = f x :=
Quotient.lift_mk (s := t2Setoid X) f (T2Quotient.compatible hf) x
lemma unique_lift {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [T2Space Y]
{f : X → Y} (hf : Continuous f) {g : T2Quotient X → Y} (hfg : g ∘ mk = f) :
g = lift hf := by
apply surjective_mk X |>.right_cancellable |>.mp <| funext _
simp [← hfg]
end T2Quotient
end
variable {Z : Type*} [TopologicalSpace Y] [TopologicalSpace Z]
theorem isClosed_eq [T2Space X] {f g : Y → X} (hf : Continuous f) (hg : Continuous g) :
IsClosed { y : Y | f y = g y } :=
continuous_iff_isClosed.mp (hf.prodMk hg) _ isClosed_diagonal
/-- If functions `f` and `g` are continuous on a closed set `s`,
then the set of points `x ∈ s` such that `f x = g x` is a closed set. -/
protected theorem IsClosed.isClosed_eq [T2Space Y] {f g : X → Y} {s : Set X} (hs : IsClosed s)
(hf : ContinuousOn f s) (hg : ContinuousOn g s) : IsClosed {x ∈ s | f x = g x} :=
(hf.prodMk hg).preimage_isClosed_of_isClosed hs isClosed_diagonal
theorem isOpen_ne_fun [T2Space X] {f g : Y → X} (hf : Continuous f) (hg : Continuous g) :
IsOpen { y : Y | f y ≠ g y } :=
isOpen_compl_iff.mpr <| isClosed_eq hf hg
/-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. See also
`Set.EqOn.of_subset_closure` for a more general version. -/
protected theorem Set.EqOn.closure [T2Space X] {s : Set Y} {f g : Y → X} (h : EqOn f g s)
(hf : Continuous f) (hg : Continuous g) : EqOn f g (closure s) :=
closure_minimal h (isClosed_eq hf hg)
/-- If two continuous functions are equal on a dense set, then they are equal. -/
theorem Continuous.ext_on [T2Space X] {s : Set Y} (hs : Dense s) {f g : Y → X} (hf : Continuous f)
(hg : Continuous g) (h : EqOn f g s) : f = g :=
funext fun x => h.closure hf hg (hs x)
theorem eqOn_closure₂' [T2Space Z] {s : Set X} {t : Set Y} {f g : X → Y → Z}
(h : ∀ x ∈ s, ∀ y ∈ t, f x y = g x y) (hf₁ : ∀ x, Continuous (f x))
(hf₂ : ∀ y, Continuous fun x => f x y) (hg₁ : ∀ x, Continuous (g x))
(hg₂ : ∀ y, Continuous fun x => g x y) : ∀ x ∈ closure s, ∀ y ∈ closure t, f x y = g x y :=
suffices closure s ⊆ ⋂ y ∈ closure t, { x | f x y = g x y } by simpa only [subset_def, mem_iInter]
(closure_minimal fun x hx => mem_iInter₂.2 <| Set.EqOn.closure (h x hx) (hf₁ _) (hg₁ _)) <|
isClosed_biInter fun _ _ => isClosed_eq (hf₂ _) (hg₂ _)
theorem eqOn_closure₂ [T2Space Z] {s : Set X} {t : Set Y} {f g : X → Y → Z}
(h : ∀ x ∈ s, ∀ y ∈ t, f x y = g x y) (hf : Continuous (uncurry f))
(hg : Continuous (uncurry g)) : ∀ x ∈ closure s, ∀ y ∈ closure t, f x y = g x y :=
eqOn_closure₂' h hf.uncurry_left hf.uncurry_right hg.uncurry_left hg.uncurry_right
/-- If `f x = g x` for all `x ∈ s` and `f`, `g` are continuous on `t`, `s ⊆ t ⊆ closure s`, then
`f x = g x` for all `x ∈ t`. See also `Set.EqOn.closure`. -/
theorem Set.EqOn.of_subset_closure [T2Space Y] {s t : Set X} {f g : X → Y} (h : EqOn f g s)
(hf : ContinuousOn f t) (hg : ContinuousOn g t) (hst : s ⊆ t) (hts : t ⊆ closure s) :
EqOn f g t := by
intro x hx
have : (𝓝[s] x).NeBot := mem_closure_iff_clusterPt.mp (hts hx)
exact
tendsto_nhds_unique_of_eventuallyEq ((hf x hx).mono_left <| nhdsWithin_mono _ hst)
((hg x hx).mono_left <| nhdsWithin_mono _ hst) (h.eventuallyEq_of_mem self_mem_nhdsWithin)
theorem Function.LeftInverse.isClosed_range [T2Space X] {f : X → Y} {g : Y → X}
(h : Function.LeftInverse f g) (hf : Continuous f) (hg : Continuous g) : IsClosed (range g) :=
have : EqOn (g ∘ f) id (closure <| range g) :=
h.rightInvOn_range.eqOn.closure (hg.comp hf) continuous_id
isClosed_of_closure_subset fun x hx => ⟨f x, this hx⟩
theorem Function.LeftInverse.isClosedEmbedding [T2Space X] {f : X → Y} {g : Y → X}
(h : Function.LeftInverse f g) (hf : Continuous f) (hg : Continuous g) : IsClosedEmbedding g :=
⟨.of_leftInverse h hf hg, h.isClosed_range hf hg⟩
theorem SeparatedNhds.of_isCompact_isCompact [T2Space X] {s t : Set X} (hs : IsCompact s)
(ht : IsCompact t) (hst : Disjoint s t) : SeparatedNhds s t := by
simp only [SeparatedNhds, prod_subset_compl_diagonal_iff_disjoint.symm] at hst ⊢
exact generalized_tube_lemma hs ht isClosed_diagonal.isOpen_compl hst
/-- In a `T2Space X`, for disjoint closed sets `s t` such that `closure sᶜ` is compact,
there are neighbourhoods that separate `s` and `t`. -/
lemma SeparatedNhds.of_isClosed_isCompact_closure_compl_isClosed [T2Space X] {s : Set X}
{t : Set X} (H1 : IsClosed s) (H2 : IsCompact (closure sᶜ)) (H3 : IsClosed t)
(H4 : Disjoint s t) : SeparatedNhds s t := by
-- Since `t` is a closed subset of the compact set `closure sᶜ`, it is compact.
have ht : IsCompact t := .of_isClosed_subset H2 H3 <| H4.subset_compl_left.trans subset_closure
-- we split `s` into its frontier and its interior.
rw [← diff_union_of_subset (interior_subset (s := s))]
-- since `t ⊆ sᶜ`, which is open, and `interior s` is open, we have
-- `SeparatedNhds (interior s) t`, which leaves us only with the frontier.
refine .union_left ?_ ⟨interior s, sᶜ, isOpen_interior, H1.isOpen_compl, le_rfl,
H4.subset_compl_left, disjoint_compl_right.mono_left interior_subset⟩
-- Since the frontier of `s` is compact (as it is a subset of `closure sᶜ`), we simply apply
-- `SeparatedNhds_of_isCompact_isCompact`.
rw [← H1.frontier_eq, frontier_eq_closure_inter_closure, H1.closure_eq]
refine .of_isCompact_isCompact ?_ ht (disjoint_of_subset_left inter_subset_left H4)
exact H2.of_isClosed_subset (H1.inter isClosed_closure) inter_subset_right
section SeparatedFinset
theorem SeparatedNhds.of_finset_finset [T2Space X] (s t : Finset X) (h : Disjoint s t) :
SeparatedNhds (s : Set X) t :=
.of_isCompact_isCompact s.finite_toSet.isCompact t.finite_toSet.isCompact <| mod_cast h
theorem SeparatedNhds.of_singleton_finset [T2Space X] {x : X} {s : Finset X} (h : x ∉ s) :
SeparatedNhds ({x} : Set X) s :=
mod_cast .of_finset_finset {x} s (Finset.disjoint_singleton_left.mpr h)
end SeparatedFinset
/-- In a `T2Space`, every compact set is closed. -/
theorem IsCompact.isClosed [T2Space X] {s : Set X} (hs : IsCompact s) : IsClosed s :=
isClosed_iff_forall_filter.2 fun _x _f _ hfs hfx =>
let ⟨_y, hy, hfy⟩ := hs.exists_clusterPt hfs
mem_of_eq_of_mem (eq_of_nhds_neBot (hfy.mono hfx).neBot).symm hy
theorem IsCompact.preimage_continuous [CompactSpace X] [T2Space Y] {f : X → Y} {s : Set Y}
(hs : IsCompact s) (hf : Continuous f) : IsCompact (f ⁻¹' s) :=
(hs.isClosed.preimage hf).isCompact
lemma Pi.isCompact_iff {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)]
[∀ i, T2Space (X i)] {s : Set (Π i, X i)} :
IsCompact s ↔ IsClosed s ∧ ∀ i, IsCompact (eval i '' s) := by
constructor <;> intro H
· exact ⟨H.isClosed, fun i ↦ H.image <| continuous_apply i⟩
· exact IsCompact.of_isClosed_subset (isCompact_univ_pi H.2) H.1 (subset_pi_eval_image univ s)
lemma Pi.isCompact_closure_iff {ι : Type*} {X : ι → Type*} [∀ i, TopologicalSpace (X i)]
[∀ i, T2Space (X i)] {s : Set (Π i, X i)} :
IsCompact (closure s) ↔ ∀ i, IsCompact (closure <| eval i '' s) := by
simp_rw [← exists_isCompact_superset_iff, Pi.exists_compact_superset_iff, image_subset_iff]
/-- If `V : ι → Set X` is a decreasing family of compact sets then any neighborhood of
`⋂ i, V i` contains some `V i`. This is a version of `exists_subset_nhds_of_isCompact'` where we
don't need to assume each `V i` closed because it follows from compactness since `X` is
assumed to be Hausdorff. -/
theorem exists_subset_nhds_of_isCompact [T2Space X] {ι : Type*} [Nonempty ι] {V : ι → Set X}
(hV : Directed (· ⊇ ·) V) (hV_cpct : ∀ i, IsCompact (V i)) {U : Set X}
(hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U :=
exists_subset_nhds_of_isCompact' hV hV_cpct (fun i => (hV_cpct i).isClosed) hU
theorem CompactExhaustion.isClosed [T2Space X] (K : CompactExhaustion X) (n : ℕ) : IsClosed (K n) :=
(K.isCompact n).isClosed
theorem IsCompact.inter [T2Space X] {s t : Set X} (hs : IsCompact s) (ht : IsCompact t) :
IsCompact (s ∩ t) :=
hs.inter_right <| ht.isClosed
theorem image_closure_of_isCompact [T2Space Y] {s : Set X} (hs : IsCompact (closure s)) {f : X → Y}
(hf : ContinuousOn f (closure s)) : f '' closure s = closure (f '' s) :=
Subset.antisymm hf.image_closure <|
closure_minimal (image_mono subset_closure) (hs.image_of_continuousOn hf).isClosed
/-- Two continuous maps into a Hausdorff space agree at a point iff they agree in a
neighborhood. -/
theorem ContinuousAt.ne_iff_eventually_ne [T2Space Y] {x : X} {f g : X → Y}
(hf : ContinuousAt f x) (hg : ContinuousAt g x) :
f x ≠ g x ↔ ∀ᶠ x in 𝓝 x, f x ≠ g x := by
constructor <;> intro hfg
· obtain ⟨Uf, Ug, h₁U, h₂U, h₃U, h₄U, h₅U⟩ := t2_separation hfg
rw [Set.disjoint_iff_inter_eq_empty] at h₅U
filter_upwards [inter_mem
(hf.preimage_mem_nhds (IsOpen.mem_nhds h₁U h₃U))
(hg.preimage_mem_nhds (IsOpen.mem_nhds h₂U h₄U))]
intro x hx
simp only [Set.mem_inter_iff, Set.mem_preimage] at hx
by_contra H
rw [H] at hx
have : g x ∈ Uf ∩ Ug := hx
simp [h₅U] at this
· obtain ⟨t, h₁t, h₂t, h₃t⟩ := eventually_nhds_iff.1 hfg
exact h₁t x h₃t
/-- **Local identity principle** for continuous maps: Two continuous maps into a Hausdorff space
agree in a punctured neighborhood of a non-isolated point iff they agree in a neighborhood. -/
theorem ContinuousAt.eventuallyEq_nhds_iff_eventuallyEq_nhdsNE [T2Space Y] {x : X} {f g : X → Y}
(hf : ContinuousAt f x) (hg : ContinuousAt g x) [(𝓝[≠] x).NeBot] :
f =ᶠ[𝓝[≠] x] g ↔ f =ᶠ[𝓝 x] g := by
constructor <;> intro hfg
· apply eventuallyEq_nhds_of_eventuallyEq_nhdsNE hfg
by_contra hCon
obtain ⟨a, ha⟩ : {x | f x ≠ g x ∧ f x = g x}.Nonempty := by
have h₁ := (eventually_nhdsWithin_of_eventually_nhds
((hf.ne_iff_eventually_ne hg).1 hCon)).and hfg
have h₂ : ∅ ∉ 𝓝[≠] x := by exact empty_notMem (𝓝[≠] x)
simp_all
simp at ha
· exact hfg.filter_mono nhdsWithin_le_nhds
@[deprecated (since := "2025-05-22")]
alias ContinuousAt.eventuallyEq_nhd_iff_eventuallyEq_nhdNE :=
ContinuousAt.eventuallyEq_nhds_iff_eventuallyEq_nhdsNE
/-- A continuous map from a compact space to a Hausdorff space is a closed map. -/
protected theorem Continuous.isClosedMap [CompactSpace X] [T2Space Y] {f : X → Y}
(h : Continuous f) : IsClosedMap f := fun _s hs => (hs.isCompact.image h).isClosed
/-- A continuous injective map from a compact space to a Hausdorff space is a closed embedding. -/
theorem Continuous.isClosedEmbedding [CompactSpace X] [T2Space Y] {f : X → Y} (h : Continuous f)
(hf : Function.Injective f) : IsClosedEmbedding f :=
.of_continuous_injective_isClosedMap h hf h.isClosedMap
/-- A continuous surjective map from a compact space to a Hausdorff space is a quotient map. -/
theorem IsQuotientMap.of_surjective_continuous [CompactSpace X] [T2Space Y] {f : X → Y}
(hsurj : Surjective f) (hcont : Continuous f) : IsQuotientMap f :=
hcont.isClosedMap.isQuotientMap hcont hsurj
theorem isPreirreducible_iff_subsingleton [T2Space X] {S : Set X} :
IsPreirreducible S ↔ S.Subsingleton := by
refine ⟨fun h x hx y hy => ?_, Set.Subsingleton.isPreirreducible⟩
by_contra e
obtain ⟨U, V, hU, hV, hxU, hyV, h'⟩ := t2_separation e
exact ((h U V hU hV ⟨x, hx, hxU⟩ ⟨y, hy, hyV⟩).mono inter_subset_right).not_disjoint h'
-- todo: use `alias` + `attribute [protected]` once we get `attribute [protected]`
protected lemma IsPreirreducible.subsingleton [T2Space X] {S : Set X} (h : IsPreirreducible S) :
S.Subsingleton :=
isPreirreducible_iff_subsingleton.1 h
theorem isIrreducible_iff_singleton [T2Space X] {S : Set X} : IsIrreducible S ↔ ∃ x, S = {x} := by
rw [IsIrreducible, isPreirreducible_iff_subsingleton,
exists_eq_singleton_iff_nonempty_subsingleton]
/-- There does not exist a nontrivial preirreducible T₂ space. -/
theorem not_preirreducible_nontrivial_t2 (X) [TopologicalSpace X] [PreirreducibleSpace X]
[Nontrivial X] [T2Space X] : False :=
(PreirreducibleSpace.isPreirreducible_univ (X := X)).subsingleton.not_nontrivial nontrivial_univ
theorem t2Space_antitone {X : Type*} : Antitone (@T2Space X) :=
fun inst₁ inst₂ h_top h_t2 ↦ @T2Space.of_injective_continuous _ _ inst₁ inst₂
h_t2 _ Function.injective_id <| continuous_id_of_le h_top
end Separation
|
Integral.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.AlgebraicGeometry.Morphisms.AffineAnd
import Mathlib.AlgebraicGeometry.Morphisms.ClosedImmersion
import Mathlib.AlgebraicGeometry.Morphisms.UniversallyClosed
import Mathlib.RingTheory.RingHom.Integral
import Mathlib.RingTheory.PolynomialAlgebra
/-!
# Integral morphisms of schemes
A morphism of schemes `f : X ⟶ Y` is integral if the preimage
of an arbitrary affine open subset of `Y` is affine and the induced ring map is integral.
It is equivalent to ask only that `Y` is covered by affine opens whose preimage is affine
and the induced ring map is integral.
-/
universe v u
open CategoryTheory TopologicalSpace Opposite MorphismProperty
namespace AlgebraicGeometry
/-- A morphism of schemes `X ⟶ Y` is finite if
the preimage of any affine open subset of `Y` is affine and the induced ring
hom is finite. -/
@[mk_iff]
class IsIntegralHom {X Y : Scheme} (f : X ⟶ Y) : Prop extends IsAffineHom f where
integral_app (U : Y.Opens) (hU : IsAffineOpen U) : (f.app U).hom.IsIntegral
namespace IsIntegralHom
instance hasAffineProperty : HasAffineProperty @IsIntegralHom
fun X _ f _ ↦ IsAffine X ∧ RingHom.IsIntegral (f.app ⊤).hom := by
change HasAffineProperty @IsIntegralHom (affineAnd RingHom.IsIntegral)
rw [HasAffineProperty.affineAnd_iff _ RingHom.isIntegral_respectsIso
RingHom.isIntegral_isStableUnderBaseChange.localizationPreserves.away
RingHom.isIntegral_ofLocalizationSpan]
simp [isIntegralHom_iff]
instance : IsStableUnderComposition @IsIntegralHom :=
HasAffineProperty.affineAnd_isStableUnderComposition (Q := RingHom.IsIntegral) hasAffineProperty
RingHom.isIntegral_stableUnderComposition
instance : IsStableUnderBaseChange @IsIntegralHom :=
HasAffineProperty.affineAnd_isStableUnderBaseChange (Q := RingHom.IsIntegral) hasAffineProperty
RingHom.isIntegral_respectsIso RingHom.isIntegral_isStableUnderBaseChange
instance : ContainsIdentities @IsIntegralHom :=
⟨fun X ↦ ⟨fun _ _ ↦ by simpa using RingHom.isIntegral_of_surjective _ (Equiv.refl _).surjective⟩⟩
lemma SpecMap_iff {R S : CommRingCat} {φ : R ⟶ S} :
IsIntegralHom (Spec.map φ) ↔ φ.hom.IsIntegral := by
have := RingHom.toMorphismProperty_respectsIso_iff.mp RingHom.isIntegral_respectsIso
rw [HasAffineProperty.iff_of_isAffine (P := @IsIntegralHom), and_iff_right]
exacts [MorphismProperty.arrow_mk_iso_iff (RingHom.toMorphismProperty RingHom.IsIntegral)
(arrowIsoΓSpecOfIsAffine φ).symm, inferInstance]
instance : IsMultiplicative @IsIntegralHom where
instance (priority := 100) {X Y : Scheme.{u}} (f : X ⟶ Y) [IsIntegralHom f] :
UniversallyClosed f := by
revert X Y f ‹IsIntegralHom f›
rw [universallyClosed_eq, ← IsStableUnderBaseChange.universally_eq (P := @IsIntegralHom)]
apply universally_mono
intro X Y f
wlog hY : ∃ R, Y = Spec R
· rw [IsLocalAtTarget.iff_of_openCover (P := @IsIntegralHom) Y.affineCover,
IsLocalAtTarget.iff_of_openCover (P := topologically _) Y.affineCover]
exact fun a i ↦ this _ ⟨_, rfl⟩ (a i)
obtain ⟨R, rfl⟩ := hY
wlog hX : ∃ S, X = Spec S
· intro H
have inst : IsAffine X := isAffine_of_isAffineHom f
rw [← cancel_left_of_respectsIso (P := topologically _) X.isoSpec.inv]
rw [← cancel_left_of_respectsIso (P := @IsIntegralHom) X.isoSpec.inv] at H
exact this _ _ ⟨_, rfl⟩ H
obtain ⟨S, rfl⟩ := hX
obtain ⟨φ, rfl⟩ := Spec.map_surjective f
rw [SpecMap_iff]
exact PrimeSpectrum.isClosedMap_comap_of_isIntegral _
lemma iff_universallyClosed_and_isAffineHom {X Y : Scheme.{u}} {f : X ⟶ Y} :
IsIntegralHom f ↔ UniversallyClosed f ∧ IsAffineHom f := by
refine ⟨fun _ ↦ ⟨inferInstance, inferInstance⟩, fun ⟨H₁, H₂⟩ ↦ ?_⟩
clear * -
wlog hY : ∃ R, Y = Spec R
· rw [IsLocalAtTarget.iff_of_openCover (P := @IsIntegralHom) Y.affineCover]
rw [IsLocalAtTarget.iff_of_openCover (P := @UniversallyClosed) Y.affineCover] at H₁
rw [IsLocalAtTarget.iff_of_openCover (P := @IsAffineHom) Y.affineCover] at H₂
exact fun _ ↦ this inferInstance inferInstance ⟨_, rfl⟩
obtain ⟨R, rfl⟩ := hY
wlog hX : ∃ S, X = Spec S
· have inst : IsAffine X := isAffine_of_isAffineHom f
rw [← cancel_left_of_respectsIso (P := @IsIntegralHom) X.isoSpec.inv]
exact this _ inferInstance inferInstance ⟨_, rfl⟩
obtain ⟨S, rfl⟩ := hX
obtain ⟨φ, rfl⟩ : ∃ φ, Spec.map φ = f := ⟨_, Spec.map_preimage _⟩
rw [SpecMap_iff]
apply PrimeSpectrum.isIntegral_of_isClosedMap_comap_mapRingHom
algebraize [φ.1, Polynomial.mapRingHom φ.1]
haveI : IsScalarTower R (Polynomial R) (Polynomial S) :=
.of_algebraMap_eq' (Polynomial.mapRingHom_comp_C _).symm
refine H₁.out (Spec.map (CommRingCat.ofHom Polynomial.C))
(Spec.map (CommRingCat.ofHom Polynomial.C)) (Spec.map _)
(isPullback_Spec_map_isPushout _ _ _ _
(CommRingCat.isPushout_of_isPushout R S (Polynomial R) (Polynomial S))).flip
lemma eq_universallyClosed_inf_isAffineHom :
@IsIntegralHom = (@UniversallyClosed ⊓ @IsAffineHom : MorphismProperty Scheme) := by
ext
exact iff_universallyClosed_and_isAffineHom
end IsIntegralHom
end AlgebraicGeometry
|
Descent.lean
|
/-
Copyright (c) 2025 Christian Merten. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Christian Merten
-/
import Mathlib.AlgebraicGeometry.Morphisms.Affine
import Mathlib.AlgebraicGeometry.Morphisms.AffineAnd
import Mathlib.AlgebraicGeometry.Morphisms.LocalIso
import Mathlib.AlgebraicGeometry.Morphisms.RingHomProperties
import Mathlib.CategoryTheory.MorphismProperty.Descent
/-!
# Descent of morphism properties
Let `P` and `P'` be morphism properties. In this file we show some results to deduce
that `P` descends along `P'` from a codescent property of ring homomorphisms.
## Main results
- `HasRingHomProperty.descendsAlong`: if `P` is a local property induced by `Q`, `P'` implies
`Q'` on global sections of affines and `Q` codescends along `Q'`, then `P` descends along `P'`.
- `HasAffineProperty.descendsAlong_of_affineAnd`: if `P` is given by `affineAnd Q`, `P'` implies
`Q'` on global sections of affines and `Q` codescends along `Q'`, then `P` descends along `P'`
(see TODOs).
## TODO
- Show that affine morphisms descend along faithfully-flat morphisms. This will make
`HasAffineProperty.descendsAlong_of_affineAnd` useful.
-/
universe u v
open TensorProduct CategoryTheory Limits
namespace AlgebraicGeometry
variable (P P' : MorphismProperty Scheme.{u})
/--
If `P` is local at the source, every quasi compact scheme is dominated by an
affine scheme via `p : Y ⟶ X` such that `p` satisfies `P`.
-/
lemma Scheme.exists_hom_isAffine_of_isLocalAtSource (X : Scheme.{u}) [CompactSpace X]
[IsLocalAtSource P] [P.ContainsIdentities] :
∃ (Y : Scheme.{u}) (p : Y ⟶ X), Surjective p ∧ P p ∧ IsAffine Y := by
let 𝒰 := X.affineCover.finiteSubcover
let p : ∐ (fun i : 𝒰.J ↦ 𝒰.obj i) ⟶ X := Sigma.desc (fun i ↦ 𝒰.map i)
have (i : 𝒰.J) : IsAffine (𝒰.obj i) := inferInstanceAs <| IsAffine (X.affineCover.obj _)
refine ⟨_, p, ⟨fun x ↦ ?_⟩, ?_, inferInstance⟩
· obtain ⟨i, x, rfl⟩ := X.affineCover.finiteSubcover.exists_eq x
use (Sigma.ι (fun i ↦ X.affineCover.finiteSubcover.obj i) i).base x
rw [← Scheme.comp_base_apply, Sigma.ι_desc]
· rw [IsLocalAtSource.iff_of_openCover (P := P) (sigmaOpenCover _)]
exact fun i ↦ by simpa [p] using IsLocalAtSource.of_isOpenImmersion _
/-- If `P` is local at the target, to show `P` descends along `P'` we may assume
the base to be affine. -/
lemma IsLocalAtTarget.descendsAlong [IsLocalAtTarget P] [P'.IsStableUnderBaseChange]
(H : ∀ {R : CommRingCat.{u}} {X Y : Scheme.{u}} (f : X ⟶ Spec R) (g : Y ⟶ Spec R),
P' f → P (pullback.fst f g) → P g) :
P.DescendsAlong P' := by
apply MorphismProperty.DescendsAlong.mk'
introv h hf
wlog hZ : ∃ R, Z = Spec R generalizing X Y Z
· rw [IsLocalAtTarget.iff_of_openCover (P := P) Z.affineCover]
intro i
let ι := Z.affineCover.map i
let e : pullback (pullback.snd f ι) (pullback.snd g ι) ≅
pullback (pullback.fst f g) (pullback.fst f ι) :=
pullbackLeftPullbackSndIso f ι (pullback.snd g ι) ≪≫
pullback.congrHom rfl pullback.condition.symm ≪≫
(pullbackAssoc f g g ι).symm ≪≫ pullback.congrHom pullback.condition.symm rfl ≪≫
(pullbackRightPullbackFstIso f ι (pullback.fst f g)).symm
have heq : e.hom ≫ pullback.snd (pullback.fst f g) (pullback.fst f ι) =
pullback.fst (pullback.snd f ι) (pullback.snd g ι) := by
apply pullback.hom_ext <;> simp [e, pullback.condition]
refine this (f := pullback.snd f ι) ?_ ?_ ⟨_, rfl⟩
· exact P'.pullback_snd _ _ h
· change P (pullback.fst (pullback.snd f ι) (pullback.snd g ι))
rw [← heq, P.cancel_left_of_respectsIso]
exact AlgebraicGeometry.IsLocalAtTarget.of_isPullback (iY := pullback.fst f ι)
(CategoryTheory.IsPullback.of_hasPullback _ _) hf
obtain ⟨R, rfl⟩ := hZ
exact H f g h hf
variable (Q Q' : ∀ {R S : Type u} [CommRing R] [CommRing S], (R →+* S) → Prop)
variable {Q Q'} in
lemma of_pullback_fst_Spec_of_codescendsAlong [P.RespectsIso]
(hQQ' : RingHom.CodescendsAlong Q Q')
(H₁ : ∀ {R S : CommRingCat.{u}} {f : R ⟶ S}, P' (Spec.map f) → Q' f.hom)
(H₂ : ∀ {R S : CommRingCat.{u}} {f : R ⟶ S}, P (Spec.map f) ↔ Q f.hom)
{R S T : CommRingCat.{u}}
{f : Spec T ⟶ Spec R} {g : Spec S ⟶ Spec R} (h : P' f) (hf : P (pullback.fst f g)) :
P g := by
obtain ⟨φ, rfl⟩ := Spec.map_surjective g
obtain ⟨ψ, rfl⟩ := Spec.map_surjective f
algebraize [φ.hom, ψ.hom]
replace hf : P (pullback.fst (Spec.map <| CommRingCat.ofHom <| algebraMap R T)
(Spec.map <| CommRingCat.ofHom <| algebraMap R S)) := hf
rw [H₂]
refine hQQ'.algebraMap_tensorProduct (R := R) (S := T) (T := S) _ (H₁ h) ?_
rwa [← pullbackSpecIso_hom_fst R T S, P.cancel_left_of_respectsIso, H₂] at hf
/-- If `X` admits a morphism `p : T ⟶ X` from an affine scheme satisfying `P', to
show a property descends along a morphism `f : X ⟶ Z` satisfying `P'`, `X` may assumed to
be affine. -/
lemma IsStableUnderBaseChange.of_pullback_fst_of_isAffine [P'.RespectsIso]
[P'.IsStableUnderComposition] [P.IsStableUnderBaseChange]
(H : ∀ {R : CommRingCat.{u}} {S X : Scheme.{u}} (f : Spec R ⟶ S) (g : X ⟶ S),
P' f → P (pullback.fst f g) → P g) {X Y Z T : Scheme.{u}} [IsAffine T] (p : T ⟶ X)
(hp : P' p) (f : X ⟶ Z) (g : Y ⟶ Z) (h : P' f) (hf : P (pullback.fst f g)) : P g := by
apply H ((T.isoSpec.inv ≫ p) ≫ f)
· rw [Category.assoc, P'.cancel_left_of_respectsIso]
exact P'.comp_mem _ _ hp h
· rw [← pullbackRightPullbackFstIso_inv_fst f g (T.isoSpec.inv ≫ p),
P.cancel_left_of_respectsIso]
exact P.pullback_fst _ _ hf
open Opposite
variable [P'.IsStableUnderBaseChange] [P'.IsStableUnderComposition] [P.IsStableUnderBaseChange]
variable
(H₁ : (@IsLocalIso ⊓ @Surjective : MorphismProperty Scheme) ≤ P')
(H₂ : ∀ {R S : CommRingCat.{u}} {f : R ⟶ S}, P' (Spec.map f) → Q' f.hom)
include H₁ in
lemma IsLocalAtTarget.descendsAlong_inf_quasiCompact [IsLocalAtTarget P]
(H : ∀ {R S : CommRingCat.{u}} {Y : Scheme.{u}} (φ : R ⟶ S) (g : Y ⟶ Spec R),
P' (Spec.map φ) → P (pullback.fst (Spec.map φ) g) → P g) :
P.DescendsAlong (P' ⊓ @QuasiCompact) := by
apply IsLocalAtTarget.descendsAlong
intro R X Y f g hf h
wlog hX : ∃ T, X = Spec T generalizing X
· have _ : CompactSpace X := by simpa [← quasiCompact_over_affine_iff f] using hf.2
obtain ⟨Y, p, hsurj, hP', hY⟩ := X.exists_hom_isAffine_of_isLocalAtSource @IsLocalIso
refine this (f := (Y.isoSpec.inv ≫ p) ≫ f) ?_ ?_ ⟨_, rfl⟩
· rw [Category.assoc, (P' ⊓ @QuasiCompact).cancel_left_of_respectsIso]
exact ⟨P'.comp_mem _ _ (H₁ _ ⟨hP', hsurj⟩) hf.1, inferInstance⟩
· rw [← pullbackRightPullbackFstIso_inv_fst f g _, P.cancel_left_of_respectsIso]
exact P.pullback_fst _ _ h
obtain ⟨T, rfl⟩ := hX
obtain ⟨φ, rfl⟩ := Spec.map_surjective f
exact H φ g hf.1 h
include H₁ H₂ in
/--
Let `P` be the morphism property associated to the ring hom property `Q`. Suppose
- `P'` implies `Q'` on global sections for affine schemes,
- `P'` is satisfied for all surjective, local isomorphisms, and
- `Q` codescend along `Q'`.
Then `P` descends along quasi-compact morphisms satisfying `P'`.
Note: The second condition is in particular satisfied for faithfully flat morphisms.
-/
nonrec lemma HasRingHomProperty.descendsAlong [HasRingHomProperty P Q]
(hQQ' : RingHom.CodescendsAlong Q Q') :
P.DescendsAlong (P' ⊓ @QuasiCompact) := by
apply IsLocalAtTarget.descendsAlong_inf_quasiCompact _ _ H₁
introv h hf
wlog hY : ∃ S, Y = Spec S generalizing Y
· rw [IsLocalAtSource.iff_of_openCover (P := P) Y.affineCover]
intro i
have heq : pullback.fst (Spec.map φ) (Y.affineCover.map i ≫ g) =
pullback.map _ _ _ _ (𝟙 _) (Y.affineCover.map i) (𝟙 _) (by simp) (by simp) ≫
pullback.fst (Spec.map φ) g := (pullback.lift_fst _ _ _).symm
exact this _ (heq ▸ AlgebraicGeometry.IsLocalAtSource.comp hf _) ⟨_, rfl⟩
obtain ⟨S, rfl⟩ := hY
apply of_pullback_fst_Spec_of_codescendsAlong _ _ hQQ' H₂ _ h hf
simp [HasRingHomProperty.Spec_iff (P := P)]
include H₁ H₂ in
/--
Let `P` be a morphism property associated with `affineAnd Q`. Suppose
- `P'` implies `Q'` on global sections on affine schemes,
- `P'` is satisfied for surjective, local isomorphisms,
- affine morphisms descend along `P''`, and
- `Q` codescends along `Q'`,
Then `P` descends along quasi-compact morphisms satisfying `P'`.
Note: The second condition is in particular satisfied for faithfully flat morphisms.
-/
nonrec lemma HasAffineProperty.descendsAlong_of_affineAnd
(hP : HasAffineProperty P (affineAnd Q)) [MorphismProperty.DescendsAlong @IsAffineHom P']
(hQ : RingHom.RespectsIso Q) (hQQ' : RingHom.CodescendsAlong Q Q') :
P.DescendsAlong (P' ⊓ @QuasiCompact) := by
apply IsLocalAtTarget.descendsAlong_inf_quasiCompact _ _ H₁
introv h hf
have : IsAffine Y := by
convert isAffine_of_isAffineHom g
exact MorphismProperty.of_pullback_fst_of_descendsAlong h <|
AlgebraicGeometry.HasAffineProperty.affineAnd_le_isAffineHom P inferInstance _ hf
wlog hY : ∃ S, Y = Spec S generalizing Y
· rw [← P.cancel_left_of_respectsIso Y.isoSpec.inv]
have heq : pullback.fst (Spec.map φ) (Y.isoSpec.inv ≫ g) =
pullback.map _ _ _ _ (𝟙 _) (Y.isoSpec.inv) (𝟙 _) (by simp) (by simp) ≫
pullback.fst (Spec.map φ) g := (pullback.lift_fst _ _ _).symm
refine this _ ?_ inferInstance ⟨_, rfl⟩
rwa [heq, P.cancel_left_of_respectsIso]
obtain ⟨Y, rfl⟩ := hY
apply of_pullback_fst_Spec_of_codescendsAlong _ _ hQQ' H₂ _ h hf
simp [SpecMap_iff_of_affineAnd _ hQ]
end AlgebraicGeometry
|
algnum.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path.
From mathcomp Require Import div choice fintype tuple finfun bigop prime.
From mathcomp Require Import ssralg poly polydiv ssrnum ssrint archimedean rat.
From mathcomp Require Import finalg zmodp matrix mxalgebra mxpoly vector intdiv.
From mathcomp Require Import falgebra fieldext separable galois algC cyclotomic.
(******************************************************************************)
(* This file provides a few basic results and constructions in algebraic *)
(* number theory, that are used in the character theory library. Most of *)
(* these could be generalized to a more abstract setting. Note that the type *)
(* of abstract number fields is simply extFieldType rat. We define here: *)
(* x \in Crat_span X <=> x is a Q-linear combination of elements of *)
(* X : seq algC. *)
(* x \in Cint_span X <=> x is a Z-linear combination of elements of *)
(* X : seq algC. *)
(* x \in Aint <=> x : algC is an algebraic integer, i.e., the (monic) *)
(* polynomial of x over Q has integer coefficients. *)
(* (e %| a)%A <=> e divides a with respect to algebraic integers, *)
(* (e %| a)%Ax i.e., a is in the algebraic integer ideal generated *)
(* by e. This is is notation for a \in dvdA e, where *)
(* dvdv is the (collective) predicate for the Aint *)
(* ideal generated by e. As in the (e %| a)%C notation *)
(* e and a can be coerced to algC from nat or int. *)
(* The (e %| a)%Ax display form is a workaround for *)
(* design limitations of the Coq Notation facilities. *)
(* (a == b %[mod e])%A, (a != b %[mod e])%A <=> *)
(* a is equal (resp. not equal) to b mod e, i.e., a and *)
(* b belong to the same e * Aint class. We do not *)
(* force a, b and e to be algebraic integers. *)
(* #[x]%C == the multiplicative order of x, i.e., the n such that *)
(* x is an nth primitive root of unity, or 0 if x is not *)
(* a root of unity. *)
(* In addition several lemmas prove the (constructive) existence of number *)
(* fields and of automorphisms of algC. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Declare Scope algC_scope.
Declare Scope algC_expanded_scope.
Import GRing.Theory Num.Theory.
Local Open Scope ring_scope.
Local Notation ZtoQ := (intr : int -> rat).
Local Notation ZtoC := (intr : int -> algC).
Local Notation QtoC := (ratr : rat -> algC).
Local Notation intrp := (map_poly intr).
Local Notation pZtoQ := (map_poly ZtoQ).
Local Notation pZtoC := (map_poly ZtoC).
Local Notation pQtoC := (map_poly ratr).
Local Definition intr_inj_ZtoC := (intr_inj : injective ZtoC).
#[local] Hint Resolve intr_inj_ZtoC : core.
Section MoreAlgCaut.
Implicit Type rR : unitRingType.
Lemma alg_num_field (Qz : fieldExtType rat) a : a%:A = ratr a :> Qz.
Proof. by rewrite -in_algE fmorph_eq_rat. Qed.
Lemma rmorphZ_num (Qz : fieldExtType rat) rR (f : {rmorphism Qz -> rR}) a x :
f (a *: x) = ratr a * f x.
Proof. by rewrite -mulr_algl rmorphM alg_num_field fmorph_rat. Qed.
Lemma fmorph_numZ (Qz1 Qz2 : fieldExtType rat) (f : {rmorphism Qz1 -> Qz2}) :
scalable f.
Proof. by move=> a x; rewrite rmorphZ_num -alg_num_field mulr_algl. Qed.
End MoreAlgCaut.
(* Number fields and rational spans. *)
Lemma algC_PET (s : seq algC) :
{z | exists a : nat ^ size s, z = \sum_(i < size s) s`_i *+ a i
& exists ps, s = [seq (pQtoC p).[z] | p <- ps]}.
Proof.
elim: s => [|x s [z /sig_eqW[a Dz] /sig_eqW[ps Ds]]].
by exists 0; [exists [ffun _ => 2%N]; rewrite big_ord0 | exists nil].
have r_exists (y : algC): {r | r != 0 & root (pQtoC r) y}.
have [r [_ mon_r] dv_r] := minCpolyP y.
by exists r; rewrite ?monic_neq0 ?dv_r.
suffices /sig_eqW[[n [|px [|pz []]]]// [Dpx Dpz]]:
exists np, let zn := x *+ np.1 + z in
[:: x; z] = [seq (pQtoC p).[zn] | p <- np.2].
- exists (x *+ n + z).
exists [ffun i => oapp a n (unlift ord0 i)].
rewrite /= big_ord_recl ffunE unlift_none Dz; congr (_ + _).
by apply: eq_bigr => i _; rewrite ffunE liftK.
exists (px :: [seq p \Po pz | p <- ps]); rewrite /= -Dpx; congr (_ :: _).
rewrite -map_comp Ds; apply: eq_map => p /=.
by rewrite map_comp_poly horner_comp -Dpz.
have [rx nz_rx rx0] := r_exists x.
have [rz nz_rz rz0] := r_exists (- z).
have pchar0_Q: [pchar rat] =i pred0 by apply: pchar_num.
have [n [[pz Dpz] [px Dpx]]] := pchar0_PET nz_rz rz0 nz_rx rx0 pchar0_Q.
by exists (n, [:: px; - pz]); rewrite /= !raddfN hornerN -[z]opprK Dpz Dpx.
Qed.
Lemma num_field_exists (s : seq algC) :
{Qs : fieldExtType rat & {QsC : {rmorphism Qs -> algC}
& {s1 : seq Qs | map QsC s1 = s & <<1 & s1>>%VS = fullv}}}.
Proof.
have [z /sig_eqW[a Dz] /sig_eqW[ps Ds]] := algC_PET s.
suffices [Qs [QsC [z1 z1C z1gen]]]:
{Qs : fieldExtType rat & {QsC : {rmorphism Qs -> algC} &
{z1 : Qs | QsC z1 = z & forall xx, exists p, fieldExt_horner z1 p = xx}}}.
- set inQs := fieldExt_horner z1 in z1gen *; pose s1 := map inQs ps.
have inQsK p: QsC (inQs p) = (pQtoC p).[z].
rewrite /= -horner_map z1C -map_poly_comp; congr _.[z].
by apply: eq_map_poly => b /=; rewrite alg_num_field fmorph_rat.
exists Qs, QsC, s1; first by rewrite -map_comp Ds (eq_map inQsK).
have sz_ps: size ps = size s by rewrite Ds size_map.
apply/vspaceP=> x; rewrite memvf; have [p {x}<-] := z1gen x.
elim/poly_ind: p => [|p b ApQs]; first by rewrite /inQs rmorph0 mem0v.
rewrite /inQs rmorphD rmorphM /= fieldExt_hornerX fieldExt_hornerC -/inQs /=.
suffices ->: z1 = \sum_(i < size s) s1`_i *+ a i.
rewrite memvD ?memvZ ?mem1v ?memvM ?memv_suml // => i _.
by rewrite rpredMn ?seqv_sub_adjoin ?mem_nth // size_map sz_ps.
apply: (fmorph_inj QsC); rewrite z1C Dz rmorph_sum; apply: eq_bigr => i _.
by rewrite rmorphMn {1}Ds !(nth_map 0) ?sz_ps //= inQsK.
have [r [Dr /monic_neq0 nz_r] dv_r] := minCpolyP z.
have rz0: root (pQtoC r) z by rewrite dv_r.
have irr_r: irreducible_poly r.
by apply/(subfx_irreducibleP rz0 nz_r)=> q qz0 nzq; rewrite dvdp_leq // -dv_r.
exists (SubFieldExtType rz0 irr_r), (@subfx_inj _ _ QtoC z r).
exists (subfx_root _ z r) => [|x]; first exact: subfx_inj_root.
by have{x} [p ->] := subfxEroot rz0 nz_r x; exists p.
Qed.
Definition in_Crat_span s x :=
exists a : rat ^ size s, x = \sum_i QtoC (a i) * s`_i.
Fact Crat_span_subproof s x : decidable (in_Crat_span s x).
Proof.
have [Qxs [QxsC [[|x1 s1] // [<- <-] {x s} _]]] := num_field_exists (x :: s).
apply: decP (x1 \in <<in_tuple s1>>%VS) _; rewrite /in_Crat_span size_map.
apply: (iffP idP) => [/coord_span-> | [a Dx]].
move: (coord _) => a; exists [ffun i => a i x1]; rewrite rmorph_sum /=.
by apply: eq_bigr => i _; rewrite ffunE rmorphZ_num (nth_map 0).
have{Dx} ->: x1 = \sum_i a i *: s1`_i.
apply: (fmorph_inj QxsC); rewrite Dx rmorph_sum /=.
by apply: eq_bigr => i _; rewrite rmorphZ_num (nth_map 0).
by apply: memv_suml => i _; rewrite memvZ ?memv_span ?mem_nth.
Qed.
Definition Crat_span s : pred algC := Crat_span_subproof s.
Lemma Crat_spanP s x : reflect (in_Crat_span s x) (x \in Crat_span s).
Proof. exact: sumboolP. Qed.
Lemma mem_Crat_span s : {subset s <= Crat_span s}.
Proof.
move=> _ /(nthP 0)[ix ltxs <-]; pose i0 := Ordinal ltxs.
apply/Crat_spanP; exists [ffun i => (i == i0)%:R].
rewrite (bigD1_ord i0) //= ffunE eqxx // rmorph1 mul1r.
by rewrite big1 ?addr0 // => i; rewrite ffunE rmorph_nat mulr_natl lift_eqF.
Qed.
Fact Crat_span_zmod_closed s : zmod_closed (Crat_span s).
Proof.
split=> [|_ _ /Crat_spanP[x ->] /Crat_spanP[y ->]].
apply/Crat_spanP; exists 0.
by apply/esym/big1=> i _; rewrite ffunE rmorph0 mul0r.
apply/Crat_spanP; exists (x - y); rewrite -sumrB; apply: eq_bigr => i _.
by rewrite -mulrBl -rmorphB !ffunE.
Qed.
HB.instance Definition _ s := GRing.isZmodClosed.Build _ (Crat_span s)
(Crat_span_zmod_closed s).
Section NumFieldProj.
Variables (Qn : fieldExtType rat) (QnC : {rmorphism Qn -> algC}).
Lemma Crat_spanZ b a : {in Crat_span b, forall x, ratr a * x \in Crat_span b}.
Proof.
move=> _ /Crat_spanP[a1 ->]; apply/Crat_spanP; exists [ffun i => a * a1 i].
by rewrite mulr_sumr; apply: eq_bigr => i _; rewrite ffunE mulrA -rmorphM.
Qed.
Lemma Crat_spanM b : {in Crat & Crat_span b, forall a x, a * x \in Crat_span b}.
Proof. by move=> _ x /CratP[a ->]; apply: Crat_spanZ. Qed.
(* In principle CtoQn could be taken to be additive and Q-linear, but this *)
(* would require a limit construction. *)
Lemma num_field_proj : {CtoQn | CtoQn 0 = 0 & cancel QnC CtoQn}.
Proof.
pose b := vbasis {:Qn}.
have Qn_bC (u : {x | x \in Crat_span (map QnC b)}): {y | QnC y = sval u}.
case: u => _ /= /Crat_spanP/sig_eqW[a ->].
exists (\sum_i a i *: b`_i); rewrite rmorph_sum /=; apply: eq_bigr => i _.
by rewrite rmorphZ_num (nth_map 0) // -(size_map QnC).
pose CtoQn x := oapp (fun u => sval (Qn_bC u)) 0 (insub x).
suffices QnCK: cancel QnC CtoQn by exists CtoQn; rewrite // -(rmorph0 QnC) /=.
move=> x; rewrite /CtoQn insubT => /= [|Qn_x]; last first.
by case: (Qn_bC _) => x1 /= /fmorph_inj.
rewrite (coord_vbasis (memvf x)) rmorph_sum rpred_sum //= => i _.
rewrite rmorphZ_num Crat_spanZ ?mem_Crat_span // -/b.
by rewrite -tnth_nth -tnth_map mem_tnth.
Qed.
Lemma restrict_aut_to_num_field (nu : {rmorphism algC -> algC}) :
(forall x, exists y, nu (QnC x) = QnC y) ->
{nu0 : {lrmorphism Qn -> Qn} | {morph QnC : x / nu0 x >-> nu x}}.
Proof.
move=> Qn_nu; pose nu0 x := sval (sig_eqW (Qn_nu x)).
have QnC_nu0: {morph QnC : x / nu0 x >-> nu x}.
by rewrite /nu0 => x; case: (sig_eqW _).
have nu0a : zmod_morphism nu0.
by move=> x y; apply: (fmorph_inj QnC); rewrite !(QnC_nu0, rmorphB).
have nu0m : monoid_morphism nu0.
split=> [|x y]; apply: (fmorph_inj QnC); rewrite ?QnC_nu0 ?rmorph1 //.
by rewrite !rmorphM /= !QnC_nu0.
pose nu0aM := GRing.isZmodMorphism.Build Qn Qn nu0 nu0a.
pose nu0mM := GRing.isMonoidMorphism.Build Qn Qn nu0 nu0m.
pose nu0RM : {rmorphism _ -> _} := HB.pack nu0 nu0aM nu0mM.
pose nu0lM := GRing.isScalable.Build rat Qn Qn *:%R nu0 (fmorph_numZ nu0RM).
pose nu0LRM : {lrmorphism _ -> _} := HB.pack nu0 nu0aM nu0mM nu0lM.
by exists nu0LRM.
Qed.
Lemma map_Qnum_poly (nu : {rmorphism algC -> algC}) p :
p \in polyOver 1%VS -> map_poly (nu \o QnC) p = (map_poly QnC p).
Proof.
move=> Qp; apply/polyP=> i; rewrite /= !coef_map /=.
have /vlineP[a ->]: p`_i \in 1%VS by apply: polyOverP.
by rewrite alg_num_field !fmorph_rat.
Qed.
End NumFieldProj.
Lemma restrict_aut_to_normal_num_field (Qn : splittingFieldType rat)
(QnC : {rmorphism Qn -> algC})(nu : {rmorphism algC -> algC}) :
{nu0 : {lrmorphism Qn -> Qn} | {morph QnC : x / nu0 x >-> nu x}}.
Proof.
apply: restrict_aut_to_num_field => x.
case: (splitting_field_normal 1%AS x) => rs /eqP Hrs.
have: root (map_poly (nu \o QnC) (minPoly 1%AS x)) (nu (QnC x)).
by rewrite fmorph_root root_minPoly.
rewrite map_Qnum_poly ?minPolyOver // Hrs.
rewrite [map_poly _ _](_:_ = \prod_(y <- map QnC rs) ('X - y%:P)).
by rewrite root_prod_XsubC; case/mapP => y _ ?; exists y.
by rewrite big_map rmorph_prod /=; apply: eq_bigr => i _; rewrite map_polyXsubC.
Qed.
(* Integral spans. *)
Lemma dec_Cint_span (V : vectType algC) m (s : m.-tuple V) v :
decidable (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 rewrite memv_suml // => i _; rewrite -scaler_int memvZ.
case s_v: (v \in <<s>>%VS); last by right=> [[a Dv]]; rewrite Dv s_Zs in s_v.
pose IzT := {: 'I_m * 'I_(\dim <<s>>)}; pose Iz := 'I_#|IzT|.
pose b := vbasis <<s>>.
pose z_s := [seq coord b ij.2 (tnth s ij.1) | ij : IzT].
pose rank2 j i: Iz := enum_rank (i, j); pose val21 (p : Iz) := (enum_val p).1.
pose inQzs w := [forall j, Crat_span z_s (coord b j w)].
have enum_pairK j: {in predT, cancel (rank2 j) val21}.
by move=> i; rewrite /val21 enum_rankK.
have Qz_Zs a: inQzs (\sum_(i < m) s`_i *~ a i).
apply/forallP=> j; apply/Crat_spanP; rewrite /in_Crat_span size_map -cardE.
exists [ffun ij => (a (val21 ij))%:Q *+ ((enum_val ij).2 == j)].
rewrite linear_sum {1}(reindex_onto _ _ (enum_pairK j)) big_mkcond /=.
apply: eq_bigr => ij _ /=; rewrite nth_image (tnth_nth 0) ffunE /val21.
rewrite raddfMz rmorphMn rmorph_int mulrnAl mulrzl /=.
rewrite (can2_eq (@enum_rankK _) (@enum_valK _)).
by case: (enum_val ij) => i j1; rewrite xpair_eqE eqxx; have [->|] := eqVneq.
case Qz_v: (inQzs v); last by right=> [[a Dv]]; rewrite Dv Qz_Zs in Qz_v.
have [Qz [QzC [z1s Dz_s _]]] := num_field_exists z_s.
have sz_z1s: size z1s = #|IzT| by rewrite -(size_map QzC) Dz_s size_map cardE.
have xv j: {x | coord b j v = QzC x}.
apply: sig_eqW; have /Crat_spanP[x ->] := forallP Qz_v j.
exists (\sum_ij x ij *: z1s`_ij); rewrite rmorph_sum; apply: eq_bigr => ij _.
by rewrite rmorphZ_num -[in RHS](nth_map _ 0) ?Dz_s // -(size_map QzC) Dz_s.
pose sz := [tuple [ffun j => z1s`_(rank2 j i)] | i < m].
have [Zsv | Zs'v] := dec_Qint_span sz [ffun j => sval (xv j)].
left; have{Zsv} [a Dv] := Zsv; exists a.
transitivity (\sum_j \sum_(i < m) QzC ((sz`_i *~ a i) j) *: b`_j).
rewrite {1}(coord_vbasis s_v) -/b; apply: eq_bigr => j _.
rewrite -scaler_suml; congr (_ *: _).
have{Dv} /ffunP/(_ j) := Dv; rewrite sum_ffunE !ffunE -rmorph_sum => <-.
by case: (xv j).
rewrite exchange_big; apply: eq_bigr => i _.
rewrite (coord_vbasis (s_s i)) -/b mulrz_suml; apply: eq_bigr => j _.
rewrite scalerMzl ffunMzE rmorphMz; congr ((_ *~ _) *: _).
rewrite nth_mktuple ffunE -(nth_map _ 0) ?sz_z1s // Dz_s.
by rewrite nth_image enum_rankK /= (tnth_nth 0).
right=> [[a Dv]]; case: Zs'v; exists a.
apply/ffunP=> j; rewrite sum_ffunE !ffunE; apply: (fmorph_inj QzC).
case: (xv j) => /= _ <-; rewrite Dv linear_sum rmorph_sum /=.
apply: eq_bigr => i _; rewrite nth_mktuple raddfMz !ffunMzE rmorphMz ffunE.
by rewrite -(nth_map _ 0 QzC) ?sz_z1s // Dz_s nth_image enum_rankK -tnth_nth.
Qed.
Definition Cint_span (s : seq algC) : pred algC :=
fun x => dec_Cint_span (in_tuple [seq \row_(i < 1) y | y <- s]) (\row_i x).
Lemma Cint_spanP n (s : n.-tuple algC) x :
reflect (inIntSpan s x) (x \in Cint_span s).
Proof.
rewrite unfold_in; case: (dec_Cint_span _ _) => [Zs_x | Zs'x] /=.
left; have{Zs_x} [] := Zs_x; rewrite /= size_map size_tuple => a /rowP/(_ 0).
rewrite !mxE => ->; exists a; rewrite summxE; apply: eq_bigr => i _.
by rewrite -scaler_int (nth_map 0) ?size_tuple // !mxE mulrzl.
right=> [[a Dx]]; have{Zs'x} [] := Zs'x.
rewrite /inIntSpan /= size_map size_tuple; exists a.
apply/rowP=> i0; rewrite !mxE summxE Dx; apply: eq_bigr => i _.
by rewrite -scaler_int mxE mulrzl (nth_map 0) ?size_tuple // !mxE.
Qed.
Lemma mem_Cint_span s : {subset s <= Cint_span s}.
Proof.
move=> _ /(nthP 0)[ix ltxs <-]; apply/(Cint_spanP (in_tuple s)).
exists [ffun i => i == Ordinal ltxs : int].
rewrite (bigD1 (Ordinal ltxs)) //= ffunE eqxx.
by rewrite big1 ?addr0 // => i; rewrite ffunE => /negbTE->.
Qed.
Lemma Cint_span_zmod_closed s : zmod_closed (Cint_span s).
Proof.
have sP := Cint_spanP (in_tuple s); split=> [|_ _ /sP[x ->] /sP[y ->]].
by apply/sP; exists 0; rewrite big1 // => i; rewrite ffunE.
apply/sP; exists (x - y); rewrite -sumrB; apply: eq_bigr => i _.
by rewrite !ffunE raddfB.
Qed.
HB.instance Definition _ s := GRing.isZmodClosed.Build _ (Cint_span s)
(Cint_span_zmod_closed s).
(* Automorphism extensions. *)
Lemma extend_algC_subfield_aut (Qs : fieldExtType rat)
(QsC : {rmorphism Qs -> algC}) (phi : {rmorphism Qs -> Qs}) :
{nu : {rmorphism algC -> algC} | {morph QsC : x / phi x >-> nu x}}.
Proof.
pose numF_inj (Qr : fieldExtType rat) := {rmorphism Qr -> algC}.
pose subAut := {Qr : _ & numF_inj Qr * {lrmorphism Qr -> Qr}}%type.
pose SubAut := existT _ _ (_, _) : subAut.
pose Sdom (mu : subAut) := projT1 mu.
pose Sinj (mu : subAut) : {rmorphism Sdom mu -> algC} := (projT2 mu).1.
pose Saut (mu : subAut) : {rmorphism Sdom mu -> Sdom mu} := (projT2 mu).2.
have Sinj_poly Qr (QrC : numF_inj Qr) p:
map_poly QrC (map_poly (in_alg Qr) p) = pQtoC p.
- rewrite -map_poly_comp; apply: eq_map_poly => a.
by rewrite /= rmorphZ_num rmorph1 mulr1.
have ext1 mu0 x : {mu1 | exists y, x = Sinj mu1 y
& exists2 in01 : {lrmorphism _ -> _}, Sinj mu0 =1 Sinj mu1 \o in01
& {morph in01: y / Saut mu0 y >-> Saut mu1 y}}.
- pose b0 := vbasis {:Sdom mu0}.
have [z _ /sig_eqW[[|px ps] // [Dx Ds]]] := algC_PET (x :: map (Sinj mu0) b0).
have [p [_ mon_p] /(_ p) pz0] := minCpolyP z; rewrite dvdpp in pz0.
have [r Dr] := closed_field_poly_normal (pQtoC p : {poly algC}).
rewrite lead_coef_map {mon_p}(monicP mon_p) rmorph1 scale1r in Dr.
have{pz0} rz: z \in r by rewrite -root_prod_XsubC -Dr.
have [Qr [QrC [rr Drr genQr]]] := num_field_exists r.
have{rz} [zz Dz]: {zz | QrC zz = z}.
by move: rz; rewrite -Drr => /mapP/sig2_eqW[zz]; exists zz.
have{ps Ds} [in01 Din01]:
{in01 : {lrmorphism _ -> _} | Sinj mu0 =1 QrC \o in01}.
have in01P y: {yy | Sinj mu0 y = QrC yy}.
exists (\sum_i coord b0 i y *: (map_poly (in_alg Qr) ps`_i).[zz]).
rewrite {1}(coord_vbasis (memvf y)) !rmorph_sum /=; apply: eq_bigr => i _.
rewrite 2!rmorphZ_num -(nth_map _ 0) ?size_tuple // Ds.
rewrite -horner_map Dz Sinj_poly (nth_map 0) //.
by have:= congr1 size Ds; rewrite !size_map size_tuple => <-.
pose in01 y := sval (in01P y).
have Din01 y: Sinj mu0 y = QrC (in01 y) by rewrite /in01; case: (in01P y).
pose rwM := (=^~ Din01, rmorphZ_num, rmorph1, rmorphB, rmorphM).
have in01a : zmod_morphism in01.
by move=> ? ?; apply: (fmorph_inj QrC); rewrite !rwM.
have in01m : monoid_morphism in01.
by split; try move=> ? ?; apply: (fmorph_inj QrC); rewrite !rwM /= ?rwM.
have in01l : scalable in01.
by try move=> ? ?; apply: (fmorph_inj QrC); rewrite !rwM.
pose in01aM := GRing.isZmodMorphism.Build _ _ in01 in01a.
pose in01mM := GRing.isMonoidMorphism.Build _ _ in01 in01m.
pose in01lM := GRing.isScalable.Build _ _ _ _ in01 in01l.
pose in01LRM : {lrmorphism _ -> _} := HB.pack in01
in01aM in01mM in01lM.
by exists in01LRM.
have {z zz Dz px} Dx: exists xx, x = QrC xx.
exists (map_poly (in_alg Qr) px).[zz].
by rewrite -horner_map Dz Sinj_poly Dx.
pose lin01 := linfun in01; pose K := (lin01 @: fullv)%VS.
have memK y: reflect (exists yy, y = in01 yy) (y \in K).
apply: (iffP memv_imgP) => [[yy _ ->] | [yy ->]];
by exists yy; rewrite ?lfunE ?memvf.
have algK: is_aspace K.
rewrite /is_aspace has_algid1; last first.
by apply/memK; exists 1; rewrite rmorph1.
apply/prodvP=> _ _ /memK[y1 ->] /memK[y2 ->].
by apply/memK; exists (y1 * y2); rewrite rmorphM.
have ker_in01: lker lin01 == 0%VS.
by apply/lker0P=> y1 y2; rewrite !lfunE; apply: fmorph_inj.
pose f := (lin01 \o linfun (Saut mu0) \o lin01^-1)%VF.
have Df y: f (in01 y) = in01 (Saut mu0 y).
transitivity (f (lin01 y)); first by rewrite !lfunE.
by do 4!rewrite lfunE /=; rewrite lker0_lfunK.
have hom_f: kHom 1 (ASpace algK) f.
apply/kHomP_tmp; split=> [_ /vlineP[a ->] | _ _ /memK[y1 ->] /memK[y2 ->]].
by rewrite -(rmorph_alg in01) Df /= !rmorph_alg.
by rewrite -rmorphM !Df !rmorphM.
pose pr := map_poly (in_alg Qr) p.
have Qpr: pr \is a polyOver 1%VS.
by apply/polyOverP=> i; rewrite coef_map memvZ ?memv_line.
have splitQr: splittingFieldFor K pr fullv.
apply: splittingFieldForS (sub1v (Sub K algK)) (subvf _) _; exists rr => //.
congr (_ %= _): (eqpxx pr); apply/(map_poly_inj QrC).
rewrite Sinj_poly Dr -Drr big_map rmorph_prod /=; apply: eq_bigr => zz _.
by rewrite map_polyXsubC.
have [f1 aut_f1 Df1]:= kHom_extends (sub1v (ASpace algK)) hom_f Qpr splitQr.
pose f1mM := GRing.isMonoidMorphism.Build _ _ f1 (kHom_monoid_morphism aut_f1).
pose nu : {lrmorphism _ -> _} := HB.pack (fun_of_lfun f1) f1mM.
exists (SubAut Qr QrC nu) => //; exists in01 => //= y.
by rewrite -Df -Df1 //; apply/memK; exists y.
have phiZ: scalable phi.
by move=> a y; rewrite rmorphZ_num -alg_num_field mulr_algl.
pose philM := GRing.isScalable.Build _ _ _ _ phi phiZ.
pose phiLRM : {lrmorphism _ -> _} := HB.pack (GRing.RMorphism.sort phi) philM.
pose fix ext n :=
if n is i.+1 then oapp (fun x => s2val (ext1 (ext i) x)) (ext i) (unpickle i)
else SubAut Qs QsC phiLRM.
have mem_ext x n: (pickle x < n)%N -> {xx | Sinj (ext n) xx = x}.
move=> ltxn; apply: sig_eqW; elim: n ltxn => // n IHn.
rewrite ltnS leq_eqVlt => /predU1P[<- | /IHn[xx <-]] /=.
by rewrite pickleK /=; case: (ext1 _ x) => mu [xx]; exists xx.
case: (unpickle n) => /= [y|]; last by exists xx.
case: (ext1 _ y) => mu /= _ [in_mu inj_in_mu _].
by exists (in_mu xx); rewrite inj_in_mu.
pose nu x := Sinj _ (Saut _ (sval (mem_ext x _ (ltnSn _)))).
have nu_inj n y: nu (Sinj (ext n) y) = Sinj (ext n) (Saut (ext n) y).
rewrite /nu; case: (mem_ext _ _ _); move: _.+1 => n1 y1 Dy /=.
without loss /subnK Dn1: n n1 y y1 Dy / (n <= n1)%N.
by move=> IH; case/orP: (leq_total n n1) => /IH => [/(_ y) | /(_ y1)]->.
move: (n1 - n)%N => k in Dn1; elim: k => [|k IHk] in n Dn1 y Dy *.
by move: y1 Dy; rewrite -Dn1 => y1 /fmorph_inj ->.
rewrite addSnnS in Dn1; move/IHk: Dn1 => /=.
case: (unpickle _) => [z|] /=; last exact.
case: (ext1 _ _) => mu /= _ [in_mu Dinj Daut].
by rewrite Dy => /(_ _ (Dinj _))->; rewrite -Daut Dinj.
pose le_nu (x : algC) n := (pickle x < n)%N.
have max3 x1 x2 x3: exists n, [/\ le_nu x1 n, le_nu x2 n & le_nu x3 n].
exists (maxn (pickle x1) (maxn (pickle x2) (pickle x3))).+1.
by apply/and3P; rewrite /le_nu !ltnS -!geq_max.
have nua : zmod_morphism nu.
move=> x1 x2; have [n] := max3 (x1 - x2) x1 x2.
case=> /mem_ext[y Dx] /mem_ext[y1 Dx1] /mem_ext[y2 Dx2].
rewrite -Dx nu_inj; rewrite -Dx1 -Dx2 -rmorphB in Dx.
by rewrite (fmorph_inj _ Dx) !rmorphB -!nu_inj Dx1 Dx2.
have num : monoid_morphism nu.
split=> [|x1 x2]; first by rewrite -(rmorph1 QsC) (nu_inj 0) !rmorph1.
have [n] := max3 (x1 * x2) x1 x2.
case=> /mem_ext[y Dx] /mem_ext[y1 Dx1] /mem_ext[y2 Dx2].
rewrite -Dx nu_inj; rewrite -Dx1 -Dx2 -rmorphM in Dx.
by rewrite (fmorph_inj _ Dx) !rmorphM /= -!nu_inj Dx1 Dx2.
pose nuaM := GRing.isZmodMorphism.Build _ _ nu nua.
pose numM := GRing.isMonoidMorphism.Build _ _ nu num.
pose nuRM : {rmorphism _ -> _} := HB.pack nu nuaM numM.
by exists nuRM => x; rewrite /= (nu_inj 0).
Qed.
(* Extended automorphisms of Q_n. *)
Lemma Qn_aut_exists k n :
coprime k n ->
{u : {rmorphism algC -> algC} | forall z, z ^+ n = 1 -> u z = z ^+ k}.
Proof.
have [-> /eqnP | n_gt0 co_k_n] := posnP n.
by rewrite gcdn0 => ->; exists idfun.
have [z prim_z] := C_prim_root_exists n_gt0.
have [Qn [QnC [[|zn []] // [Dz]]] genQn] := num_field_exists [:: z].
pose phi := kHomExtend 1 \1 zn (zn ^+ k).
have homQn1: kHom 1 1 (\1%VF : 'End(Qn)) by rewrite kHom1.
have pzn_zk0: root (map_poly \1%VF (minPoly 1 zn)) (zn ^+ k).
rewrite -(fmorph_root QnC) rmorphXn /= Dz -map_poly_comp.
rewrite (@eq_map_poly _ _ _ QnC) => [|a]; last by rewrite /= id_lfunE.
set p1 := map_poly _ _.
have [q1 Dp1]: exists q1, p1 = pQtoC q1.
have aP i: (minPoly 1 zn)`_i \in 1%VS.
by apply/polyOverP; apply: minPolyOver.
have{aP} a_ i := sig_eqW (vlineP _ _ (aP i)).
exists (\poly_(i < size (minPoly 1 zn)) sval (a_ i)).
apply/polyP=> i; rewrite coef_poly coef_map coef_poly /=.
case: ifP => _; rewrite ?rmorph0 //; case: (a_ i) => a /= ->.
by rewrite alg_num_field fmorph_rat.
have: root p1 z by rewrite -Dz fmorph_root root_minPoly.
rewrite Dp1; have [q2 [Dq2 _] ->] := minCpolyP z.
case/dvdpP=> r1 ->; rewrite rmorphM rootM /= -Dq2; apply/orP; right.
rewrite (minCpoly_cyclotomic prim_z) /cyclotomic.
rewrite (bigD1 (Ordinal (ltn_pmod k n_gt0))) ?coprime_modl //=.
by rewrite rootM root_XsubC prim_expr_mod ?eqxx.
have phim : monoid_morphism phi.
by apply/kHom_monoid_morphism; rewrite -genQn span_seq1 /= kHomExtendP.
pose phimM := GRing.isMonoidMorphism.Build _ _ phi phim.
pose phiRM : {rmorphism _ -> _} := HB.pack (fun_of_lfun phi) phimM.
have [nu Dnu] := extend_algC_subfield_aut QnC phiRM.
exists nu => _ /(prim_rootP prim_z)[i ->].
rewrite rmorphXn /= exprAC -Dz -Dnu /= -{1}[zn]hornerX /phi.
rewrite (kHomExtend_poly homQn1) ?polyOverX //.
rewrite map_polyE map_id_in => [|?]; last by rewrite id_lfunE.
by rewrite polyseqK hornerX rmorphXn.
Qed.
(* Algebraic integers. *)
Definition Aint : {pred algC} := fun x => minCpoly x \is a polyOver Num.int.
Lemma root_monic_Aint p x :
root p x -> p \is monic -> p \is a polyOver Num.int -> x \in Aint.
Proof.
have pZtoQtoC pz: pQtoC (pZtoQ pz) = pZtoC pz.
by rewrite -map_poly_comp; apply: eq_map_poly => b; rewrite /= rmorph_int.
move=> px0 mon_p /floorpP[pz Dp]; rewrite unfold_in.
move: px0; rewrite Dp -pZtoQtoC; have [q [-> mon_q] ->] := minCpolyP x.
case/dvdpP_rat_int=> qz [a nz_a Dq] [r].
move/(congr1 (fun q1 => lead_coef (a *: pZtoQ q1))).
rewrite rmorphM scalerAl -Dq lead_coefZ lead_coefM /=.
have /monicP->: pZtoQ pz \is monic by rewrite -(map_monic QtoC) pZtoQtoC -Dp.
rewrite (monicP mon_q) mul1r mulr1 lead_coef_map_inj //; last exact: intr_inj.
rewrite Dq => ->; apply/polyOverP=> i; rewrite !(coefZ, coef_map).
by rewrite -rmorphM /= rmorph_int.
Qed.
Lemma Cint_rat_Aint z : z \in Crat -> z \in Aint -> z \in Num.int.
Proof.
case/CratP=> a ->{z} /polyOverP/(_ 0).
have [p [Dp mon_p] dv_p] := minCpolyP (ratr a); rewrite Dp coef_map.
suffices /eqP->: p == 'X - a%:P by rewrite polyseqXsubC /= rmorphN rpredN.
rewrite -eqp_monic ?monicXsubC // irredp_XsubC //.
by rewrite -(size_map_poly QtoC) -Dp neq_ltn size_minCpoly orbT.
by rewrite -dv_p fmorph_root root_XsubC.
Qed.
Lemma Aint_Cint : {subset Num.int <= Aint}.
Proof.
move=> x; rewrite -polyOverXsubC.
by apply: root_monic_Aint; rewrite ?monicXsubC ?root_XsubC.
Qed.
Lemma Aint_int x : x%:~R \in Aint. Proof. by rewrite Aint_Cint. Qed.
Lemma Aint0 : 0 \in Aint. Proof. exact: Aint_int 0. Qed.
Lemma Aint1 : 1 \in Aint. Proof. exact: Aint_int 1. Qed.
#[global] Hint Resolve Aint0 Aint1 : core.
Lemma Aint_unity_root n x : (n > 0)%N -> n.-unity_root x -> x \in Aint.
Proof.
move=> n_gt0 xn1; apply: root_monic_Aint xn1 (monicXnsubC _ n_gt0) _.
by apply/polyOverP=> i; rewrite coefB coefC -mulrb coefXn /= rpredB ?rpred_nat.
Qed.
Lemma Aint_prim_root n z : n.-primitive_root z -> z \in Aint.
Proof.
move=> pr_z; apply/(Aint_unity_root (prim_order_gt0 pr_z))/unity_rootP.
exact: prim_expr_order.
Qed.
Lemma Aint_Cnat : {subset Num.nat <= Aint}.
Proof. by move=> z /intr_nat/Aint_Cint. Qed.
(* This is Isaacs, Lemma (3.3) *)
Lemma Aint_subring_exists (X : seq algC) :
{subset X <= Aint} ->
{S : pred algC &
(*a*) subring_closed S
/\ (*b*) {subset X <= S}
& (*c*) {Y : {n : nat & n.-tuple algC} &
{subset tagged Y <= S}
& forall x, reflect (inIntSpan (tagged Y) x) (x \in S)}}.
Proof.
move=> AZ_X; pose m := (size X).+1.
pose n (i : 'I_m) := (size (minCpoly X`_i)).-2; pose N := (\max_i n i).+1.
pose IY := family (fun i => [pred e : 'I_N | e <= n i]%N).
have IY_0: 0 \in IY by apply/familyP=> // i; rewrite ffunE.
pose inIY := enum_rank_in IY_0.
pose Y := [seq \prod_(i < m) X`_i ^+ (f : 'I_N ^ m) i | f in IY].
have S_P := Cint_spanP [tuple of Y]; set S := Cint_span _ in S_P.
have sYS: {subset Y <= S} by apply: mem_Cint_span.
have S_1: 1 \in S.
by apply/sYS/imageP; exists 0 => //; rewrite big1 // => i; rewrite ffunE.
have SmulX (i : 'I_m): {in S, forall x, x * X`_i \in S}.
move=> _ /S_P[x ->]; rewrite mulr_suml rpred_sum // => j _.
rewrite mulrzAl rpredMz {x}// nth_image mulrC (bigD1 i) //= mulrA -exprS.
move: {j}(enum_val j) (familyP (enum_valP j)) => f fP.
have:= fP i; rewrite inE /= leq_eqVlt => /predU1P[-> | fi_ltn]; last first.
apply/sYS/imageP; have fiK: (inord (f i).+1 : 'I_N) = (f i).+1 :> nat.
by rewrite inordK // ltnS (bigmax_sup i).
exists (finfun [eta f with i |-> inord (f i).+1]).
apply/familyP=> i1; rewrite inE ffunE /= fun_if fiK.
by case: eqP => [-> // | _]; apply: fP.
rewrite (bigD1 i isT) ffunE /= eqxx fiK; congr (_ * _).
by apply: eq_bigr => i1 /[!ffunE]/= /negPf->.
have [/monicP ] := (minCpoly_monic X`_i, root_minCpoly X`_i).
rewrite /root horner_coef lead_coefE -(subnKC (size_minCpoly _)) subn2.
rewrite big_ord_recr /= addrC addr_eq0 => ->; rewrite mul1r => /eqP->.
have /floorpP[p Dp]: X`_i \in Aint.
by have [/(nth_default 0)-> | /(mem_nth 0)/AZ_X] := leqP (size X) i.
rewrite -/(n i) Dp mulNr rpredN // mulr_suml rpred_sum // => [[e le_e]] /= _.
rewrite coef_map -mulrA mulrzl rpredMz ?sYS //; apply/imageP.
have eK: (inord e : 'I_N) = e :> nat by rewrite inordK // ltnS (bigmax_sup i).
exists (finfun [eta f with i |-> inord e]).
apply/familyP=> i1; rewrite inE ffunE /= fun_if eK.
by case: eqP => [-> // | _]; apply: fP.
rewrite (bigD1 i isT) ffunE /= eqxx eK; congr (_ * _).
by apply: eq_bigr => i1 /[!ffunE] /= /negPf->.
exists S; last by exists (Tagged (fun n => n.-tuple _) [tuple of Y]).
split=> [|x Xx]; last first.
by rewrite -[x]mul1r -(nth_index 0 Xx) (SmulX (Ordinal _)) // ltnS index_size.
split=> // x y Sx Sy; first by rewrite rpredB.
case/S_P: Sy => {y}[y ->]; rewrite mulr_sumr rpred_sum //= => j.
rewrite mulrzAr rpredMz {y}// nth_image; move: {j}(enum_val j) => f.
elim/big_rec: _ => [|i y _ IHy] in x Sx *; first by rewrite mulr1.
rewrite mulrA {y}IHy //.
elim: {f}(f i : nat) => [|e IHe] in x Sx *; first by rewrite mulr1.
by rewrite exprS mulrA IHe // SmulX.
Qed.
Section AlgIntSubring.
(* This is Isaacs, Theorem (3.4). *)
Theorem fin_Csubring_Aint S n (Y : n.-tuple algC) :
mulr_closed S -> (forall x, reflect (inIntSpan Y x) (x \in S)) ->
{subset S <= Aint}.
Proof.
move=> mulS.
pose Sm := GRing.isMulClosed.Build _ _ mulS.
pose SC : mulrClosed _ := HB.pack S Sm.
have ZP_C c: (ZtoC c)%:P \is a polyOver Num.int_num_subdef.
by rewrite raddfMz rpred_int.
move=> S_P x Sx; pose v := \row_(i < n) Y`_i.
have [v0 | nz_v] := eqVneq v 0.
case/S_P: Sx => {}x ->; rewrite big1 ?isAlgInt0 // => i _.
by have /rowP/(_ i)/[!mxE] -> := v0; rewrite mul0rz.
have sYS (i : 'I_n): x * Y`_i \in SC.
by rewrite rpredM //; apply/S_P/Cint_spanP/mem_Cint_span/memt_nth.
pose A := \matrix_(i, j < n) sval (sig_eqW (S_P _ (sYS j))) i.
pose p := char_poly (map_mx ZtoC A).
have: p \is a polyOver Num.int_num_subdef.
rewrite rpred_sum // => s _; rewrite rpredMsign rpred_prod // => j _.
by rewrite !mxE /= rpredB ?rpredMn ?polyOverX.
apply: root_monic_Aint (char_poly_monic _).
rewrite -eigenvalue_root_char; apply/eigenvalueP; exists v => //.
apply/rowP=> j; case dAj: (sig_eqW (S_P _ (sYS j))) => [a DxY].
by rewrite !mxE DxY; apply: eq_bigr => i _; rewrite !mxE dAj /= mulrzr.
Qed.
(* This is Isaacs, Corollary (3.5). *)
Corollary Aint_subring : subring_closed Aint.
Proof.
suff rAZ: {in Aint &, forall x y, (x - y \in Aint) * (x * y \in Aint)}.
by split=> // x y AZx AZy; rewrite rAZ.
move=> x y AZx AZy.
have [|S [ringS] ] := @Aint_subring_exists [:: x; y]; first exact/allP/and3P.
move=> /allP/and3P[Sx Sy _] [Y _ genYS].
have AZ_S := fin_Csubring_Aint ringS genYS.
by have [_ S_B S_M] := ringS; rewrite !AZ_S ?S_B ?S_M.
Qed.
HB.instance Definition _ := GRing.isSubringClosed.Build _ Aint Aint_subring.
End AlgIntSubring.
Lemma Aint_aut (nu : {rmorphism algC -> algC}) x :
(nu x \in Aint) = (x \in Aint).
Proof. by rewrite !unfold_in minCpoly_aut. Qed.
Definition dvdA (e : Algebraics.divisor) : {pred algC} :=
fun z => if e == 0 then z == 0 else z / e \in Aint.
Delimit Scope algC_scope with A.
Delimit Scope algC_expanded_scope with Ax.
Notation "e %| x" := (x \in dvdA e) : algC_expanded_scope.
Notation "e %| x" := (@in_mem Algebraics.divisor x (mem (dvdA e))) : algC_scope.
Fact dvdA_zmod_closed e : zmod_closed (dvdA e).
Proof.
split=> [|x y]; first by rewrite unfold_in mul0r eqxx rpred0 ?if_same.
rewrite ![(e %| _)%A]unfold_in.
case: ifP => [_ x0 /eqP-> | _]; first by rewrite subr0.
by rewrite mulrBl; apply: rpredB.
Qed.
HB.instance Definition _ e := GRing.isZmodClosed.Build _ (dvdA e)
(dvdA_zmod_closed e).
Definition eqAmod (e x y : Algebraics.divisor) := (e %| x - y)%A.
Notation "x == y %[mod e ]" := (eqAmod e x y) : algC_scope.
Notation "x != y %[mod e ]" := (~~ (eqAmod e x y)) : algC_scope.
Lemma eqAmod_refl e x : (x == x %[mod e])%A.
Proof. by rewrite /eqAmod subrr rpred0. Qed.
#[global] Hint Resolve eqAmod_refl : core.
Lemma eqAmod_sym e x y : ((x == y %[mod e]) = (y == x %[mod e]))%A.
Proof. by rewrite /eqAmod -opprB rpredN. Qed.
Lemma eqAmod_trans e y x z :
(x == y %[mod e] -> y == z %[mod e] -> x == z %[mod e])%A.
Proof.
by move=> Exy Eyz; rewrite /eqAmod -[x](subrK y) -[_ - z]addrA rpredD.
Qed.
Lemma eqAmod_transl e x y z :
(x == y %[mod e])%A -> (x == z %[mod e])%A = (y == z %[mod e])%A.
Proof. by move/(sym_left_transitive (eqAmod_sym e) (@eqAmod_trans e)). Qed.
Lemma eqAmod_transr e x y z :
(x == y %[mod e])%A -> (z == x %[mod e])%A = (z == y %[mod e])%A.
Proof. by move/(sym_right_transitive (eqAmod_sym e) (@eqAmod_trans e)). Qed.
Lemma eqAmod0 e x : (x == 0 %[mod e])%A = (e %| x)%A.
Proof. by rewrite /eqAmod subr0. Qed.
Lemma eqAmodN e x y : (- x == y %[mod e])%A = (x == - y %[mod e])%A.
Proof. by rewrite eqAmod_sym /eqAmod !opprK addrC. Qed.
Lemma eqAmodDr e x y z : (y + x == z + x %[mod e])%A = (y == z %[mod e])%A.
Proof. by rewrite /eqAmod addrAC opprD !addrA subrK. Qed.
Lemma eqAmodDl e x y z : (x + y == x + z %[mod e])%A = (y == z %[mod e])%A.
Proof. by rewrite !(addrC x) eqAmodDr. Qed.
Lemma eqAmodD e x1 x2 y1 y2 :
(x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 + y1 == x2 + y2 %[mod e])%A.
Proof.
by rewrite -(eqAmodDl e x2 y1) -(eqAmodDr e y1); apply: eqAmod_trans.
Qed.
Lemma eqAmodm0 e : (e == 0 %[mod e])%A.
Proof. by rewrite /eqAmod subr0 unfold_in; case: ifPn => // /divff->. Qed.
#[global] Hint Resolve eqAmodm0 : core.
Lemma eqAmodMr e :
{in Aint, forall z x y, x == y %[mod e] -> x * z == y * z %[mod e]}%A.
Proof.
move=> z Zz x y.
rewrite /eqAmod -mulrBl ![(e %| _)%A]unfold_in mulf_eq0 mulrAC.
by case: ifP => [_ -> // | _ Exy]; apply: rpredM.
Qed.
Lemma eqAmodMl e :
{in Aint, forall z x y, x == y %[mod e] -> z * x == z * y %[mod e]}%A.
Proof. by move=> z Zz x y Exy; rewrite !(mulrC z) eqAmodMr. Qed.
Lemma eqAmodMl0 e : {in Aint, forall x, x * e == 0 %[mod e]}%A.
Proof. by move=> x Zx; rewrite -(mulr0 x) eqAmodMl. Qed.
Lemma eqAmodMr0 e : {in Aint, forall x, e * x == 0 %[mod e]}%A.
Proof. by move=> x Zx; rewrite /= mulrC eqAmodMl0. Qed.
Lemma eqAmod_addl_mul e : {in Aint, forall x y, x * e + y == y %[mod e]}%A.
Proof. by move=> x Zx y; rewrite -{2}[y]add0r eqAmodDr eqAmodMl0. Qed.
Lemma eqAmodM e : {in Aint &, forall x1 y2 x2 y1,
x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 * y1 == x2 * y2 %[mod e]}%A.
Proof.
move=> x1 y2 Zx1 Zy2 x2 y1 eq_x /(eqAmodMl Zx1)/eqAmod_trans-> //.
exact: eqAmodMr.
Qed.
Lemma eqAmod_rat :
{in Crat & &, forall e m n, (m == n %[mod e])%A = (m == n %[mod e])%C}.
Proof.
move=> e m n Qe Qm Qn; rewrite /eqCmod unfold_in /eqAmod unfold_in.
case: ifPn => // nz_e; apply/idP/idP=> [/Cint_rat_Aint | /Aint_Cint] -> //.
by rewrite rpred_div ?rpredB.
Qed.
Lemma eqAmod0_rat : {in Crat &, forall e n, (n == 0 %[mod e])%A = (e %| n)%C}.
Proof. by move=> e n Qe Qn; rewrite /= eqAmod_rat /eqCmod ?subr0 ?Crat0. Qed.
Lemma eqAmod_nat (e m n : nat) : (m == n %[mod e])%A = (m == n %[mod e])%N.
Proof. by rewrite eqAmod_rat ?rpred_nat // eqCmod_nat. Qed.
Lemma eqAmod0_nat (e m : nat) : (m == 0 %[mod e])%A = (e %| m)%N.
Proof. by rewrite eqAmod0_rat ?rpred_nat // dvdC_nat. Qed.
(* Multiplicative order. *)
Definition orderC x :=
let p := minCpoly x in
oapp val 0 [pick n : 'I_(2 * size p ^ 2) | p == intrp 'Phi_n].
Notation "#[ x ]" := (orderC x) : C_scope.
Lemma exp_orderC x : x ^+ #[x]%C = 1.
Proof.
rewrite /orderC; case: pickP => //= [] [n _] /= /eqP Dp.
have n_gt0: (0 < n)%N.
rewrite lt0n; apply: contraTneq (size_minCpoly x) => n0.
by rewrite Dp n0 Cyclotomic0 rmorph1 size_poly1.
have [z prim_z] := C_prim_root_exists n_gt0.
rewrite prim_expr_order // -(root_cyclotomic prim_z).
by rewrite -Cintr_Cyclotomic // -Dp root_minCpoly.
Qed.
Lemma dvdn_orderC x n : (#[x]%C %| n)%N = (x ^+ n == 1).
Proof.
apply/idP/eqP=> [|x_n_1]; first by apply: expr_dvd; apply: exp_orderC.
have [-> | n_gt0] := posnP n; first by rewrite dvdn0.
have [m prim_x m_dv_n] := prim_order_exists n_gt0 x_n_1.
have{n_gt0} m_gt0 := dvdn_gt0 n_gt0 m_dv_n; congr (_ %| n)%N: m_dv_n.
pose p := minCpoly x; have Dp: p = cyclotomic x m := minCpoly_cyclotomic prim_x.
rewrite /orderC; case: pickP => /= [k /eqP Dp_k | no_k]; last first.
suffices lt_m_2p: (m < 2 * size p ^ 2)%N.
have /eqP[] := no_k (Ordinal lt_m_2p).
by rewrite /= -/p Dp -Cintr_Cyclotomic.
rewrite Dp size_cyclotomic (sqrnD 1) addnAC mulnDr -add1n leq_add //.
suffices: (m <= \prod_(q <- primes m | q == 2) q * totient m ^ 2)%N.
have [m_even | m_odd] := boolP (2%N \in primes m).
by rewrite -big_filter filter_pred1_uniq ?primes_uniq // big_seq1.
by rewrite big_hasC ?has_pred1 // => /leq_trans-> //; apply: leq_addl.
rewrite big_mkcond totientE // -mulnn -!big_split /=.
rewrite {1}[m]prod_prime_decomp // prime_decompE big_map /= !big_seq.
elim/big_ind2: _ => // [n1 m1 n2 m2 | q]; first exact: leq_mul.
rewrite mem_primes => /and3P[q_pr _ q_dv_m].
rewrite lognE q_pr m_gt0 q_dv_m /=; move: (logn q _) => k.
rewrite !mulnA expnS leq_mul //.
case: (ltngtP q 2) (prime_gt1 q_pr) => // [q_gt2|->] _.
rewrite mul1n mulnAC mulnn -{1}[q]muln1 leq_mul ?expn_gt0 ?prime_gt0 //.
by rewrite -(subnKC q_gt2) (ltn_exp2l 1).
by rewrite !muln1 -expnS (ltn_exp2l 0).
have k_prim_x: k.-primitive_root x.
have k_gt0: (0 < k)%N.
rewrite lt0n; apply: contraTneq (size_minCpoly x) => k0.
by rewrite Dp_k k0 Cyclotomic0 rmorph1 size_poly1.
have [z prim_z] := C_prim_root_exists k_gt0.
rewrite -(root_cyclotomic prim_z) -Cintr_Cyclotomic //.
by rewrite -Dp_k root_minCpoly.
apply/eqP; rewrite eqn_dvd !(@prim_order_dvd _ _ x) //.
by rewrite !prim_expr_order ?eqxx.
Qed.
|
archimedean.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice.
From mathcomp Require Import fintype bigop order ssralg poly ssrnum ssrint.
(******************************************************************************)
(* Archimedean structures *)
(* *)
(* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *)
(* *)
(* This file defines some numeric structures extended with the Archimedean *)
(* axiom. To use this file, insert "Import Num.Theory." and optionally *)
(* "Import Num.Def." before your scripts as in the ssrnum library. *)
(* The modules provided by this library subsume those from ssrnum. *)
(* *)
(* This file defines the following structures: *)
(* *)
(* archiNumDomainType == numDomainType with the Archimedean axiom *)
(* The HB class is called ArchiNumDomain. *)
(* archiNumFieldType == numFieldType with the Archimedean axiom *)
(* The HB class is called ArchiNumField. *)
(* archiClosedFieldType == closedFieldType with the Archimedean axiom *)
(* The HB class is called ArchiClosedField. *)
(* archiRealDomainType == realDomainType with the Archimedean axiom *)
(* The HB class is called ArchiRealDomain. *)
(* archiRealFieldType == realFieldType with the Archimedean axiom *)
(* The HB class is called ArchiRealField. *)
(* archiRcfType == rcfType with the Archimedean axiom *)
(* The HB class is called ArchiRealClosedField. *)
(* *)
(* Over these structures, we have the following operations: *)
(* x \is a Num.int <=> x is an integer, i.e., x = m%:~R for some m : int *)
(* x \is a Num.nat <=> x is a natural number, i.e., x = m%:R for some m : nat*)
(* Num.floor x == the m : int such that m%:~R <= x < (m + 1)%:~R *)
(* when x \is a Num.real, otherwise 0%Z *)
(* Num.ceil x == the m : int such that (m - 1)%:~R < x <= m%:~R *)
(* when x \is a Num.real, otherwise 0%Z *)
(* Num.truncn x == the n : nat such that n%:R <= x < n.+1%:R *)
(* when 0 <= n, otherwise 0%N *)
(* Num.bound x == an upper bound for x, i.e., an n such that `|x| < n%:R *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Local Open Scope ring_scope.
Import Order.TTheory GRing.Theory Num.Theory.
Module Num.
Import Num.Def.
HB.mixin Record NumDomain_hasFloorCeilTruncn R of Num.NumDomain R := {
floor : R -> int;
ceil : R -> int;
truncn : R -> nat;
int_num_subdef : pred R;
nat_num_subdef : pred R;
floor_subproof :
forall x,
if x \is Rreal then (floor x)%:~R <= x < (floor x + 1)%:~R
else floor x == 0;
ceil_subproof : forall x, ceil x = - floor (- x);
truncn_subproof : forall x, truncn x = if floor x is Posz n then n else 0;
int_num_subproof : forall x, reflect (exists n, x = n%:~R) (int_num_subdef x);
nat_num_subproof : forall x, reflect (exists n, x = n%:R) (nat_num_subdef x);
}.
#[short(type="archiNumDomainType")]
HB.structure Definition ArchiNumDomain :=
{ R of NumDomain_hasFloorCeilTruncn R & Num.NumDomain R }.
Module ArchiNumDomainExports.
Bind Scope ring_scope with ArchiNumDomain.sort.
End ArchiNumDomainExports.
HB.export ArchiNumDomainExports.
#[short(type="archiNumFieldType")]
HB.structure Definition ArchiNumField :=
{ R of NumDomain_hasFloorCeilTruncn R & Num.NumField R }.
Module ArchiNumFieldExports.
Bind Scope ring_scope with ArchiNumField.sort.
End ArchiNumFieldExports.
HB.export ArchiNumFieldExports.
#[short(type="archiClosedFieldType")]
HB.structure Definition ArchiClosedField :=
{ R of NumDomain_hasFloorCeilTruncn R & Num.ClosedField R }.
Module ArchiClosedFieldExports.
Bind Scope ring_scope with ArchiClosedField.sort.
End ArchiClosedFieldExports.
HB.export ArchiClosedFieldExports.
#[short(type="archiRealDomainType")]
HB.structure Definition ArchiRealDomain :=
{ R of NumDomain_hasFloorCeilTruncn R & Num.RealDomain R }.
Module ArchiRealDomainExports.
Bind Scope ring_scope with ArchiRealDomain.sort.
End ArchiRealDomainExports.
HB.export ArchiRealDomainExports.
#[short(type="archiRealFieldType")]
HB.structure Definition ArchiRealField :=
{ R of NumDomain_hasFloorCeilTruncn R & Num.RealField R }.
Module ArchiRealFieldExports.
Bind Scope ring_scope with ArchiRealField.sort.
End ArchiRealFieldExports.
HB.export ArchiRealFieldExports.
#[short(type="archiRcfType")]
HB.structure Definition ArchiRealClosedField :=
{ R of NumDomain_hasFloorCeilTruncn R & Num.RealClosedField R }.
Module ArchiRealClosedFieldExports.
Bind Scope ring_scope with ArchiRealClosedField.sort.
End ArchiRealClosedFieldExports.
HB.export ArchiRealClosedFieldExports.
Section Def.
Context {R : archiNumDomainType}.
Definition nat_num : qualifier 1 R := [qualify a x : R | nat_num_subdef x].
Definition int_num : qualifier 1 R := [qualify a x : R | int_num_subdef x].
Definition bound (x : R) := (truncn `|x|).+1.
End Def.
Arguments floor {R} : rename, simpl never.
Arguments ceil {R} : rename, simpl never.
Arguments truncn {R} : rename, simpl never.
Arguments nat_num {R} : simpl never.
Arguments int_num {R} : simpl never.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncn.")]
Notation trunc := truncn.
Module Def.
Export ssrnum.Num.Def.
Notation truncn := truncn.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncn.")]
Notation trunc := truncn.
Notation floor := floor.
Notation ceil := ceil.
Notation nat_num := nat_num.
Notation int_num := int_num.
Notation archi_bound := bound.
End Def.
Module intArchimedean.
Section intArchimedean.
Implicit Types n : int.
Lemma floorP n : if n \is Rreal then n%:~R <= n < (n + 1)%:~R else n == 0.
Proof. by rewrite num_real !intz ltzD1 lexx. Qed.
Lemma intrP n : reflect (exists m, n = m%:~R) true.
Proof. by apply: ReflectT; exists n; rewrite intz. Qed.
Lemma natrP n : reflect (exists m, n = m%:R) (0 <= n).
Proof.
apply: (iffP idP); last by case=> m ->; rewrite ler0n.
by case: n => // n _; exists n; rewrite natz.
Qed.
End intArchimedean.
End intArchimedean.
#[export]
HB.instance Definition _ :=
@NumDomain_hasFloorCeilTruncn.Build int id id _ xpredT Rnneg_pred
intArchimedean.floorP (fun=> esym (opprK _)) (fun=> erefl)
intArchimedean.intrP intArchimedean.natrP.
Module Import Theory.
Export ssrnum.Num.Theory.
Section ArchiNumDomainTheory.
Variable R : archiNumDomainType.
Implicit Types x y z : R.
Local Notation truncn := (@truncn R).
Local Notation floor := (@floor R).
Local Notation ceil := (@ceil R).
Local Notation nat_num := (@Def.nat_num R).
Local Notation int_num := (@Def.int_num R).
Local Lemma floorP x :
if x \is Rreal then (floor x)%:~R <= x < (floor x + 1)%:~R else floor x == 0.
Proof. exact: floor_subproof. Qed.
Lemma floorNceil x : floor x = - ceil (- x).
Proof. by rewrite ceil_subproof !opprK. Qed.
Lemma ceilNfloor x : ceil x = - floor (- x).
Proof. exact: ceil_subproof. Qed.
Lemma truncEfloor x : truncn x = if floor x is Posz n then n else 0.
Proof. exact: truncn_subproof. Qed.
Lemma natrP x : reflect (exists n, x = n%:R) (x \is a nat_num).
Proof. exact: nat_num_subproof. Qed.
Lemma intrP x : reflect (exists m, x = m%:~R) (x \is a int_num).
Proof. exact: int_num_subproof. Qed.
(* int_num and nat_num *)
Lemma intr_int m : m%:~R \is a int_num. Proof. by apply/intrP; exists m. Qed.
Lemma natr_nat n : n%:R \is a nat_num. Proof. by apply/natrP; exists n. Qed.
#[local] Hint Resolve intr_int natr_nat : core.
Lemma rpred_int_num (S : subringClosed R) x : x \is a int_num -> x \in S.
Proof. by move=> /intrP[n ->]; rewrite rpred_int. Qed.
Lemma rpred_nat_num (S : semiringClosed R) x : x \is a nat_num -> x \in S.
Proof. by move=> /natrP[n ->]; apply: rpred_nat. Qed.
Lemma int_num0 : 0 \is a int_num. Proof. exact: (intr_int 0). Qed.
Lemma int_num1 : 1 \is a int_num. Proof. exact: (intr_int 1). Qed.
Lemma nat_num0 : 0 \is a nat_num. Proof. exact: (natr_nat 0). Qed.
Lemma nat_num1 : 1 \is a nat_num. Proof. exact: (natr_nat 1). Qed.
#[local] Hint Resolve int_num0 int_num1 nat_num0 nat_num1 : core.
Fact int_num_subring : subring_closed int_num.
Proof.
by split=> // _ _ /intrP[n ->] /intrP[m ->]; rewrite -(intrB, intrM).
Qed.
#[export]
HB.instance Definition _ := GRing.isSubringClosed.Build R int_num_subdef
int_num_subring.
Fact nat_num_semiring : semiring_closed nat_num.
Proof.
by do 2![split] => //= _ _ /natrP[n ->] /natrP[m ->]; rewrite -(natrD, natrM).
Qed.
#[export]
HB.instance Definition _ := GRing.isSemiringClosed.Build R nat_num_subdef
nat_num_semiring.
Lemma Rreal_nat : {subset nat_num <= Rreal}. Proof. exact: rpred_nat_num. Qed.
Lemma intr_nat : {subset nat_num <= int_num}.
Proof. by move=> _ /natrP[n ->]; rewrite pmulrn intr_int. Qed.
Lemma Rreal_int : {subset int_num <= Rreal}. Proof. exact: rpred_int_num. Qed.
Lemma intrE x : (x \is a int_num) = (x \is a nat_num) || (- x \is a nat_num).
Proof.
apply/idP/orP => [/intrP[[n|n] ->]|[]/intr_nat]; rewrite ?rpredN //.
by left; apply/natrP; exists n.
by rewrite NegzE intrN opprK; right; apply/natrP; exists n.+1.
Qed.
Lemma intr_normK x : x \is a int_num -> `|x| ^+ 2 = x ^+ 2.
Proof. by move/Rreal_int/real_normK. Qed.
Lemma natr_normK x : x \is a nat_num -> `|x| ^+ 2 = x ^+ 2.
Proof. by move/Rreal_nat/real_normK. Qed.
Lemma natr_norm_int x : x \is a int_num -> `|x| \is a nat_num.
Proof. by move=> /intrP[m ->]; rewrite -intr_norm rpred_nat_num ?natr_nat. Qed.
Lemma natr_ge0 x : x \is a nat_num -> 0 <= x.
Proof. by move=> /natrP[n ->]; apply: ler0n. Qed.
Lemma natr_gt0 x : x \is a nat_num -> (0 < x) = (x != 0).
Proof. by move/natr_ge0; case: comparableP. Qed.
Lemma natrEint x : (x \is a nat_num) = (x \is a int_num) && (0 <= x).
Proof.
apply/idP/andP=> [Nx | [Zx x_ge0]]; first by rewrite intr_nat ?natr_ge0.
by rewrite -(ger0_norm x_ge0) natr_norm_int.
Qed.
Lemma intrEge0 x : 0 <= x -> (x \is a int_num) = (x \is a nat_num).
Proof. by rewrite natrEint andbC => ->. Qed.
Lemma intrEsign x : x \is a int_num -> x = (-1) ^+ (x < 0)%R * `|x|.
Proof. by move/Rreal_int/realEsign. Qed.
Lemma norm_natr x : x \is a nat_num -> `|x| = x.
Proof. by move/natr_ge0/ger0_norm. Qed.
Lemma natr_exp_even x n : ~~ odd n -> x \is a int_num -> x ^+ n \is a nat_num.
Proof.
move=> n_oddF x_intr.
by rewrite natrEint rpredX //= real_exprn_even_ge0 // Rreal_int.
Qed.
Lemma norm_intr_ge1 x : x \is a int_num -> x != 0 -> 1 <= `|x|.
Proof.
rewrite -normr_eq0 => /natr_norm_int/natrP[n ->].
by rewrite pnatr_eq0 ler1n lt0n.
Qed.
Lemma sqr_intr_ge1 x : x \is a int_num -> x != 0 -> 1 <= x ^+ 2.
Proof.
by move=> Zx nz_x; rewrite -intr_normK // expr_ge1 ?normr_ge0 ?norm_intr_ge1.
Qed.
Lemma intr_ler_sqr x : x \is a int_num -> x <= x ^+ 2.
Proof.
move=> Zx; have [-> | nz_x] := eqVneq x 0; first by rewrite expr0n.
apply: le_trans (_ : `|x| <= _); first by rewrite real_ler_norm ?Rreal_int.
by rewrite -intr_normK // ler_eXnr // norm_intr_ge1.
Qed.
(* floor and int_num *)
Lemma real_floor_itv x : x \is Rreal -> (floor x)%:~R <= x < (floor x + 1)%:~R.
Proof. by case: ifP (floorP x). Qed.
Lemma real_floor_le x : x \is Rreal -> (floor x)%:~R <= x.
Proof. by case/real_floor_itv/andP. Qed.
Lemma real_floorD1_gt x : x \is Rreal -> x < (floor x + 1)%:~R.
Proof. by case/real_floor_itv/andP. Qed.
Lemma floor_def x m : m%:~R <= x < (m + 1)%:~R -> floor x = m.
Proof.
case/andP=> lemx ltxm1; apply/eqP; rewrite eq_le -!ltzD1.
move: (ger_real lemx); rewrite realz => /real_floor_itv/andP[lefx ltxf1].
by rewrite -!(ltr_int R) 2?(@le_lt_trans _ _ x).
Qed.
(* TODO: rename to real_floor_ge_int,
once the currently deprecated one has been removed *)
Lemma real_floor_ge_int_tmp x n : x \is Rreal -> (n <= floor x) = (n%:~R <= x).
Proof.
move=> /real_floor_itv /andP[lefx ltxf1]; apply/idP/idP => lenx.
by apply: le_trans lefx; rewrite ler_int.
by rewrite -ltzD1 -(ltr_int R); apply: le_lt_trans ltxf1.
Qed.
#[deprecated(since="mathcomp 2.4.0", note="Use real_floor_ge_int_tmp instead.")]
Lemma real_floor_ge_int x n : x \is Rreal -> (n%:~R <= x) = (n <= floor x).
Proof. by move=> ?; rewrite real_floor_ge_int_tmp. Qed.
Lemma real_floor_lt_int x n : x \is Rreal -> (floor x < n) = (x < n%:~R).
Proof.
by move=> ?; rewrite [RHS]real_ltNge ?realz -?real_floor_ge_int_tmp -?ltNge.
Qed.
Lemma real_floor_eq x n : x \is Rreal ->
(floor x == n) = (n%:~R <= x < (n + 1)%:~R).
Proof.
by move=> xr; apply/eqP/idP => [<-|]; [exact: real_floor_itv|exact: floor_def].
Qed.
Lemma le_floor : {homo floor : x y / x <= y}.
Proof.
move=> x y lexy; move: (floorP x) (floorP y); rewrite (ger_real lexy).
case: ifP => [_ /andP[lefx _] /andP[_] | _ /eqP-> /eqP-> //].
by move=> /(le_lt_trans lexy) /(le_lt_trans lefx); rewrite ltr_int ltzD1.
Qed.
Lemma intrKfloor : cancel intr floor.
Proof. by move=> m; apply: floor_def; rewrite lexx rmorphD ltrDl ltr01. Qed.
Lemma natr_int n : n%:R \is a int_num.
Proof. by rewrite intrE natr_nat. Qed.
#[local] Hint Resolve natr_int : core.
Lemma intrEfloor x : x \is a int_num = ((floor x)%:~R == x).
Proof.
by apply/intrP/eqP => [[n ->] | <-]; [rewrite intrKfloor | exists (floor x)].
Qed.
Lemma floorK : {in int_num, cancel floor intr}.
Proof. by move=> z; rewrite intrEfloor => /eqP. Qed.
Lemma floor0 : floor 0 = 0. Proof. exact: intrKfloor 0. Qed.
Lemma floor1 : floor 1 = 1. Proof. exact: intrKfloor 1. Qed.
#[local] Hint Resolve floor0 floor1 : core.
Lemma real_floorDzr : {in int_num & Rreal, {morph floor : x y / x + y}}.
Proof.
move=> _ y /intrP[m ->] Ry; apply: floor_def.
by rewrite -addrA 2!rmorphD /= intrKfloor lerD2l ltrD2l real_floor_itv.
Qed.
Lemma real_floorDrz : {in Rreal & int_num, {morph floor : x y / x + y}}.
Proof. by move=> x y xr yz; rewrite addrC real_floorDzr // addrC. Qed.
Lemma floorN : {in int_num, {morph floor : x / - x}}.
Proof. by move=> _ /intrP[m ->]; rewrite -rmorphN !intrKfloor. Qed.
Lemma floorM : {in int_num &, {morph floor : x y / x * y}}.
Proof.
by move=> _ _ /intrP[m1 ->] /intrP[m2 ->]; rewrite -rmorphM !intrKfloor.
Qed.
Lemma floorX n : {in int_num, {morph floor : x / x ^+ n}}.
Proof. by move=> _ /intrP[m ->]; rewrite -rmorphXn !intrKfloor. Qed.
Lemma real_floor_ge0 x : x \is Rreal -> (0 <= floor x) = (0 <= x).
Proof. by move=> ?; rewrite real_floor_ge_int_tmp. Qed.
Lemma floor_lt0 x : (floor x < 0) = (x < 0).
Proof.
case: ifP (floorP x) => [xr _ | xr /eqP <-]; first by rewrite real_floor_lt_int.
by rewrite ltxx; apply/esym/(contraFF _ xr)/ltr0_real.
Qed.
Lemma real_floor_le0 x : x \is Rreal -> (floor x <= 0) = (x < 1).
Proof. by move=> ?; rewrite -ltzD1 add0r real_floor_lt_int. Qed.
Lemma floor_gt0 x : (floor x > 0) = (x >= 1).
Proof.
case: ifP (floorP x) => [xr _ | xr /eqP->].
by rewrite gtz0_ge1 real_floor_ge_int_tmp.
by rewrite ltxx; apply/esym/(contraFF _ xr)/ger1_real.
Qed.
Lemma floor_neq0 x : (floor x != 0) = (x < 0) || (x >= 1).
Proof.
case: ifP (floorP x) => [xr _ | xr /eqP->]; rewrite ?eqxx/=.
by rewrite neq_lt floor_lt0 floor_gt0.
by apply/esym/(contraFF _ xr) => /orP[/ltr0_real|/ger1_real].
Qed.
Lemma floorpK : {in polyOver int_num, cancel (map_poly floor) (map_poly intr)}.
Proof.
move=> p /(all_nthP 0) Zp; apply/polyP=> i.
rewrite coef_map coef_map_id0 //= -[p]coefK coef_poly.
by case: ifP => [/Zp/floorK // | _]; rewrite floor0.
Qed.
Lemma floorpP (p : {poly R}) :
p \is a polyOver int_num -> {q | p = map_poly intr q}.
Proof. by exists (map_poly floor p); rewrite floorpK. Qed.
(* ceil and int_num *)
Lemma real_ceil_itv x : x \is Rreal -> (ceil x - 1)%:~R < x <= (ceil x)%:~R.
Proof.
rewrite ceilNfloor -opprD !intrN ltrNl lerNr andbC -realN.
exact: real_floor_itv.
Qed.
Lemma real_ceilB1_lt x : x \is Rreal -> (ceil x - 1)%:~R < x.
Proof. by case/real_ceil_itv/andP. Qed.
Lemma real_ceil_ge x : x \is Rreal -> x <= (ceil x)%:~R.
Proof. by case/real_ceil_itv/andP. Qed.
Lemma ceil_def x m : (m - 1)%:~R < x <= m%:~R -> ceil x = m.
Proof.
rewrite -ltrN2 -lerN2 andbC -!intrN opprD opprK ceilNfloor.
by move=> /floor_def ->; rewrite opprK.
Qed.
(* TODO: rename to real_ceil_le_int,
once the currently deprecated one has been removed *)
Lemma real_ceil_le_int_tmp x n : x \is Rreal -> (ceil x <= n) = (x <= n%:~R).
Proof.
rewrite ceilNfloor lerNl -realN => /real_floor_ge_int_tmp ->.
by rewrite intrN lerN2.
Qed.
#[deprecated(since="mathcomp 2.4.0", note="Use real_ceil_le_int_tmp instead.")]
Lemma real_ceil_le_int x n : x \is Rreal -> x <= n%:~R = (ceil x <= n).
Proof. by move=> ?; rewrite real_ceil_le_int_tmp. Qed.
Lemma real_ceil_gt_int x n : x \is Rreal -> (n < ceil x) = (n%:~R < x).
Proof.
by move=> ?; rewrite [RHS]real_ltNge ?realz -?real_ceil_le_int_tmp ?ltNge.
Qed.
Lemma real_ceil_eq x n : x \is Rreal ->
(ceil x == n) = ((n - 1)%:~R < x <= n%:~R).
Proof.
by move=> xr; apply/eqP/idP => [<-|]; [exact: real_ceil_itv|exact: ceil_def].
Qed.
(* TODO: rename to le_ceil,
once the currently deprecated one has been removed *)
Lemma le_ceil_tmp : {homo ceil : x y / x <= y}.
Proof. by move=> x y lexy; rewrite !ceilNfloor lerN2 le_floor ?lerN2. Qed.
Lemma intrKceil : cancel intr ceil.
Proof. by move=> m; rewrite ceilNfloor -intrN intrKfloor opprK. Qed.
Lemma intrEceil x : x \is a int_num = ((ceil x)%:~R == x).
Proof. by rewrite -rpredN intrEfloor -eqr_oppLR -intrN -ceilNfloor. Qed.
Lemma ceilK : {in int_num, cancel ceil intr}.
Proof. by move=> z; rewrite intrEceil => /eqP. Qed.
Lemma ceil0 : ceil 0 = 0. Proof. exact: intrKceil 0. Qed.
Lemma ceil1 : ceil 1 = 1. Proof. exact: intrKceil 1. Qed.
#[local] Hint Resolve ceil0 ceil1 : core.
Lemma real_ceilDzr : {in int_num & Rreal, {morph ceil : x y / x + y}}.
Proof.
move=> x y x_int y_real.
by rewrite ceilNfloor opprD real_floorDzr ?rpredN // opprD -!ceilNfloor.
Qed.
Lemma real_ceilDrz : {in Rreal & int_num, {morph ceil : x y / x + y}}.
Proof. by move=> x y xr yz; rewrite addrC real_ceilDzr // addrC. Qed.
Lemma ceilN : {in int_num, {morph ceil : x / - x}}.
Proof. by move=> ? ?; rewrite !ceilNfloor !opprK floorN. Qed.
Lemma ceilM : {in int_num &, {morph ceil : x y / x * y}}.
Proof.
by move=> _ _ /intrP[m1 ->] /intrP[m2 ->]; rewrite -rmorphM !intrKceil.
Qed.
Lemma ceilX n : {in int_num, {morph ceil : x / x ^+ n}}.
Proof. by move=> _ /intrP[m ->]; rewrite -rmorphXn !intrKceil. Qed.
Lemma real_ceil_ge0 x : x \is Rreal -> (0 <= ceil x) = (-1 < x).
Proof.
by move=> ?; rewrite ceilNfloor oppr_ge0 real_floor_le0 ?realN 1?ltrNl.
Qed.
Lemma ceil_lt0 x : (ceil x < 0) = (x <= -1).
Proof. by rewrite ceilNfloor oppr_lt0 floor_gt0 lerNr. Qed.
Lemma real_ceil_le0 x : x \is Rreal -> (ceil x <= 0) = (x <= 0).
Proof. by move=> ?; rewrite real_ceil_le_int_tmp. Qed.
Lemma ceil_gt0 x : (ceil x > 0) = (x > 0).
Proof. by rewrite ceilNfloor oppr_gt0 floor_lt0 oppr_lt0. Qed.
Lemma ceil_neq0 x : (ceil x != 0) = (x <= -1) || (x > 0).
Proof. by rewrite ceilNfloor oppr_eq0 floor_neq0 oppr_lt0 lerNr orbC. Qed.
Lemma real_ceil_floor x : x \is Rreal ->
ceil x = floor x + (x \isn't a int_num).
Proof.
case Ix: (x \is a int_num) => Rx /=.
by apply/eqP; rewrite addr0 ceilNfloor eqr_oppLR floorN.
apply/ceil_def; rewrite addrK; move: (real_floor_itv Rx).
by rewrite le_eqVlt -intrEfloor Ix /= => /andP[-> /ltW].
Qed.
(* Relating Cnat and oldCnat. *)
Lemma truncn_floor x : truncn x = if 0 <= x then `|floor x|%N else 0%N.
Proof.
move: (floorP x); rewrite truncEfloor realE.
have [/le_floor|_]/= := boolP (0 <= x); first by rewrite floor0; case: floor.
by case: ifP => [/le_floor|_ /eqP->//]; rewrite floor0; case: floor => [[]|].
Qed.
(* trunc and nat_num *)
Local Lemma truncnP x :
if 0 <= x then (truncn x)%:R <= x < (truncn x).+1%:R else truncn x == 0%N.
Proof.
rewrite truncn_floor.
case: (boolP (0 <= x)) => //= /[dup] /le_floor + /ger0_real/real_floor_itv.
by rewrite floor0; case: (floor x) => // n _; rewrite absz_nat addrC -intS.
Qed.
Lemma truncn_itv x : 0 <= x -> (truncn x)%:R <= x < (truncn x).+1%:R.
Proof. by move=> x_ge0; move: (truncnP x); rewrite x_ge0. Qed.
Lemma truncn_le x : (truncn x)%:R <= x = (0 <= x).
Proof. by case: ifP (truncnP x) => [+ /andP[] | + /eqP->//]. Qed.
Lemma real_truncnS_gt x : x \is Rreal -> x < (truncn x).+1%:R.
Proof. by move/real_ge0P => [/truncn_itv/andP[]|/lt_le_trans->]. Qed.
Lemma truncn_def x n : n%:R <= x < n.+1%:R -> truncn x = n.
Proof.
case/andP=> lemx ltxm1; apply/eqP; rewrite eqn_leq -ltnS -[(n <= _)%N]ltnS.
have/truncn_itv/andP[lefx ltxf1]: 0 <= x by apply: le_trans lemx; apply: ler0n.
by rewrite -!(ltr_nat R) 2?(@le_lt_trans _ _ x).
Qed.
Lemma truncn_ge_nat x n : 0 <= x -> (n <= truncn x)%N = (n%:R <= x).
Proof.
move=> /truncn_itv /andP[letx ltxt1]; apply/idP/idP => lenx.
by apply: le_trans letx; rewrite ler_nat.
by rewrite -ltnS -(ltr_nat R); apply: le_lt_trans ltxt1.
Qed.
Lemma truncn_gt_nat x n : (n < truncn x)%N = (n.+1%:R <= x).
Proof.
case: ifP (truncnP x) => [x0 _ | x0 /eqP->]; first by rewrite truncn_ge_nat.
by rewrite ltn0; apply/esym/(contraFF _ x0)/le_trans.
Qed.
Lemma truncn_lt_nat x n : 0 <= x -> (truncn x < n)%N = (x < n%:R).
Proof. by move=> ?; rewrite real_ltNge ?ger0_real// ltnNge truncn_ge_nat. Qed.
Lemma real_truncn_le_nat x n : x \is Rreal -> (truncn x <= n)%N = (x < n.+1%:R).
Proof. by move=> ?; rewrite real_ltNge// leqNgt truncn_gt_nat. Qed.
Lemma truncn_eq x n : 0 <= x -> (truncn x == n) = (n%:R <= x < n.+1%:R).
Proof.
by move=> xr; apply/eqP/idP => [<-|]; [exact: truncn_itv|exact: truncn_def].
Qed.
Lemma le_truncn : {homo truncn : x y / x <= y >-> (x <= y)%N}.
Proof.
move=> x y lexy; move: (truncnP x) (truncnP y).
case: ifP => [x0 /andP[letx _] | x0 /eqP->//].
case: ifP => [y0 /andP[_] | y0 /eqP->]; [|by rewrite (le_trans x0 lexy) in y0].
by move=> /(le_lt_trans lexy) /(le_lt_trans letx); rewrite ltr_nat ltnS.
Qed.
Lemma natrK : cancel (GRing.natmul 1) truncn.
Proof. by move=> m; apply: truncn_def; rewrite ler_nat ltr_nat ltnS leqnn. Qed.
Lemma natrEtruncn x : (x \is a nat_num) = ((truncn x)%:R == x).
Proof.
by apply/natrP/eqP => [[n ->]|<-]; [rewrite natrK | exists (truncn x)].
Qed.
Lemma archi_boundP x : 0 <= x -> x < (bound x)%:R.
Proof.
move=> x_ge0; case/truncn_itv/andP: (normr_ge0 x) => _.
exact/le_lt_trans/real_ler_norm/ger0_real.
Qed.
Lemma truncnK : {in nat_num, cancel truncn (GRing.natmul 1)}.
Proof. by move=> x; rewrite natrEtruncn => /eqP. Qed.
Lemma truncn0 : truncn 0 = 0%N. Proof. exact: natrK 0%N. Qed.
Lemma truncn1 : truncn 1 = 1%N. Proof. exact: natrK 1%N. Qed.
#[local] Hint Resolve truncn0 truncn1 : core.
Lemma truncnD :
{in nat_num & Rnneg, {morph truncn : x y / x + y >-> (x + y)%N}}.
Proof.
move=> _ y /natrP[n ->] y_ge0; apply: truncn_def.
by rewrite -addnS !natrD !natrK lerD2l ltrD2l truncn_itv.
Qed.
Lemma truncnM : {in nat_num &, {morph truncn : x y / x * y >-> (x * y)%N}}.
Proof. by move=> _ _ /natrP[n1 ->] /natrP[n2 ->]; rewrite -natrM !natrK. Qed.
Lemma truncnX n : {in nat_num, {morph truncn : x / x ^+ n >-> (x ^ n)%N}}.
Proof. by move=> _ /natrP[n1 ->]; rewrite -natrX !natrK. Qed.
Lemma truncn_gt0 x : (0 < truncn x)%N = (1 <= x).
Proof.
case: ifP (truncnP x) => [x0 | x0 /eqP<-]; first by rewrite truncn_ge_nat.
by rewrite ltnn; apply/esym/(contraFF _ x0)/le_trans.
Qed.
Lemma truncn0Pn x : reflect (truncn x = 0%N) (~~ (1 <= x)).
Proof. by rewrite -truncn_gt0 -eqn0Ngt; apply: eqP. Qed.
Lemma sum_truncnK I r (P : pred I) F : (forall i, P i -> F i \is a nat_num) ->
(\sum_(i <- r | P i) truncn (F i))%:R = \sum_(i <- r | P i) F i.
Proof. by rewrite natr_sum => natr; apply: eq_bigr => i /natr /truncnK. Qed.
Lemma prod_truncnK I r (P : pred I) F : (forall i, P i -> F i \is a nat_num) ->
(\prod_(i <- r | P i) truncn (F i))%:R = \prod_(i <- r | P i) F i.
Proof. by rewrite natr_prod => natr; apply: eq_bigr => i /natr /truncnK. Qed.
Lemma natr_sum_eq1 (I : finType) (P : pred I) (F : I -> R) :
(forall i, P i -> F i \is a nat_num) -> \sum_(i | P i) F i = 1 ->
{i : I | [/\ P i, F i = 1 & forall j, j != i -> P j -> F j = 0]}.
Proof.
move=> natF /eqP; rewrite -sum_truncnK// -[1]/1%:R eqr_nat => /sum_nat_eq1 exi.
have [i /and3P[Pi /eqP f1 /forallP a]] : {i : I | [&& P i, truncn (F i) == 1
& [forall j : I, ((j != i) ==> P j ==> (truncn (F j) == 0))]]}.
apply/sigW; have [i [Pi /eqP f1 a]] := exi; exists i; apply/and3P; split=> //.
by apply/forallP => j; apply/implyP => ji; apply/implyP => Pj; apply/eqP/a.
exists i; split=> [//||j ji Pj]; rewrite -[LHS]truncnK ?natF ?f1//; apply/eqP.
by rewrite -[0]/0%:R eqr_nat; apply: implyP Pj; apply: implyP ji; apply: a.
Qed.
Lemma natr_mul_eq1 x y :
x \is a nat_num -> y \is a nat_num -> (x * y == 1) = (x == 1) && (y == 1).
Proof. by do 2!move/truncnK <-; rewrite -natrM !pnatr_eq1 muln_eq1. Qed.
Lemma natr_prod_eq1 (I : finType) (P : pred I) (F : I -> R) :
(forall i, P i -> F i \is a nat_num) -> \prod_(i | P i) F i = 1 ->
forall i, P i -> F i = 1.
Proof.
move=> natF /eqP; rewrite -prod_truncnK// -[1]/1%:R eqr_nat prod_nat_seq_eq1.
move/allP => a i Pi; apply/eqP; rewrite -[F i]truncnK ?natF// eqr_nat.
by apply: implyP Pi; apply: a; apply: mem_index_enum.
Qed.
(* predCmod *)
Variables (U V : lmodType R) (f : {additive U -> V}).
Lemma raddfZ_nat a u : a \is a nat_num -> f (a *: u) = a *: f u.
Proof. by move=> /natrP[n ->]; apply: raddfZnat. Qed.
Lemma rpredZ_nat (S : addrClosed V) :
{in nat_num & S, forall z u, z *: u \in S}.
Proof. by move=> _ u /natrP[n ->]; apply: rpredZnat. Qed.
Lemma raddfZ_int a u : a \is a int_num -> f (a *: u) = a *: f u.
Proof. by move=> /intrP[m ->]; rewrite !scaler_int raddfMz. Qed.
Lemma rpredZ_int (S : zmodClosed V) :
{in int_num & S, forall z u, z *: u \in S}.
Proof. by move=> _ u /intrP[m ->] ?; rewrite scaler_int rpredMz. Qed.
(* autC *)
Implicit Type nu : {rmorphism R -> R}.
Lemma aut_natr nu : {in nat_num, nu =1 id}.
Proof. by move=> _ /natrP[n ->]; apply: rmorph_nat. Qed.
Lemma aut_intr nu : {in int_num, nu =1 id}.
Proof. by move=> _ /intrP[m ->]; apply: rmorph_int. Qed.
End ArchiNumDomainTheory.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncn_itv.")]
Notation trunc_itv := truncn_itv.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncn_def.")]
Notation trunc_def := truncn_def.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncnK.")]
Notation truncK := truncnK.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncn0.")]
Notation trunc0 := truncn0.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncn1.")]
Notation trunc1 := truncn1.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncnD.")]
Notation truncD := truncnD.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncnM.")]
Notation truncM := truncnM.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncnX.")]
Notation truncX := truncnX.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncn_gt0.")]
Notation trunc_gt0 := truncn_gt0.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncn0Pn.")]
Notation trunc0Pn := truncn0Pn.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to sum_truncnK.")]
Notation sum_truncK := sum_truncnK.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to prod_truncnK.")]
Notation prod_truncK := prod_truncnK.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to truncn_floor.")]
Notation trunc_floor := truncn_floor.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to real_floor_le.")]
Notation real_ge_floor := real_floor_le.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to real_floorD1_gt.")]
Notation real_lt_succ_floor := real_floorD1_gt.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to real_ceilB1_lt.")]
Notation real_gt_pred_ceil := real_floorD1_gt.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to real_ceil_ge.")]
Notation real_le_ceil := real_ceil_ge.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to le_floor.")]
Notation floor_le := le_floor.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to le_ceil.")]
Notation ceil_le := le_ceil_tmp.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to natrEtruncn.")]
Notation natrE := natrEtruncn.
Arguments natrK {R} _%_N.
Arguments intrKfloor {R}.
Arguments intrKceil {R}.
Arguments natrP {R x}.
Arguments intrP {R x}.
#[global] Hint Resolve truncn0 truncn1 : core.
#[global] Hint Resolve floor0 floor1 : core.
#[global] Hint Resolve ceil0 ceil1 : core.
#[global] Hint Extern 0 (is_true (_%:R \is a nat_num)) => apply: natr_nat : core.
#[global] Hint Extern 0 (is_true (_%:R \in nat_num_subdef)) => apply: natr_nat : core.
#[global] Hint Extern 0 (is_true (_%:~R \is a int_num)) => apply: intr_int : core.
#[global] Hint Extern 0 (is_true (_%:~R \in int_num_subdef)) => apply: intr_int : core.
#[global] Hint Extern 0 (is_true (_%:R \is a int_num)) => apply: natr_int : core.
#[global] Hint Extern 0 (is_true (_%:R \in int_num_subdef)) => apply: natr_int : core.
#[global] Hint Extern 0 (is_true (0 \is a nat_num)) => apply: nat_num0 : core.
#[global] Hint Extern 0 (is_true (0 \in nat_num_subdef)) => apply: nat_num0 : core.
#[global] Hint Extern 0 (is_true (1 \is a nat_num)) => apply: nat_num1 : core.
#[global] Hint Extern 0 (is_true (1 \in int_num_subdef)) => apply: nat_num1 : core.
#[global] Hint Extern 0 (is_true (0 \is a int_num)) => apply: int_num0 : core.
#[global] Hint Extern 0 (is_true (0 \in int_num_subdef)) => apply: int_num0 : core.
#[global] Hint Extern 0 (is_true (1 \is a int_num)) => apply: int_num1 : core.
#[global] Hint Extern 0 (is_true (1 \in int_num_subdef)) => apply: int_num1 : core.
Section ArchiRealDomainTheory.
Variables (R : archiRealDomainType).
Implicit Type x : R.
Lemma upper_nthrootP x i : (bound x <= i)%N -> x < 2%:R ^+ i.
Proof.
case/truncn_itv/andP: (normr_ge0 x) => _ /ltr_normlW xlt le_b_i.
by rewrite (lt_le_trans xlt) // -natrX ler_nat (ltn_trans le_b_i) // ltn_expl.
Qed.
Lemma truncnS_gt x : x < (truncn x).+1%:R.
Proof. exact: real_truncnS_gt. Qed.
Lemma truncn_le_nat x n : (truncn x <= n)%N = (x < n.+1%:R).
Proof. exact: real_truncn_le_nat. Qed.
Lemma floor_itv x : (floor x)%:~R <= x < (floor x + 1)%:~R.
Proof. exact: real_floor_itv. Qed.
(* TODO: rename to floor_le, once the deprecated one has been removed *)
Lemma floor_le_tmp x : (floor x)%:~R <= x. Proof. exact: real_floor_le. Qed.
Lemma floorD1_gt x : x < (floor x + 1)%:~R.
Proof. exact: real_floorD1_gt. Qed.
#[deprecated(since="mathcomp 2.4.0", note="Use floor_ge_int_tmp instead.")]
Lemma floor_ge_int x n : n%:~R <= x = (n <= floor x).
Proof. by rewrite real_floor_ge_int_tmp. Qed.
(* TODO: rename to floor_ge_int,
once the currently deprecated one has been removed *)
Lemma floor_ge_int_tmp x n : (n <= floor x) = (n%:~R <= x).
Proof. exact: real_floor_ge_int_tmp. Qed.
Lemma floor_lt_int x n : (floor x < n) = (x < n%:~R).
Proof. exact: real_floor_lt_int. Qed.
Lemma floor_eq x n : (floor x == n) = (n%:~R <= x < (n + 1)%:~R).
Proof. exact: real_floor_eq. Qed.
Lemma floorDzr : {in @int_num R, {morph floor : x y / x + y}}.
Proof. by move=> x xz y; apply/real_floorDzr/num_real. Qed.
Lemma floorDrz x y : y \is a int_num -> floor (x + y) = floor x + floor y.
Proof. by move=> yz; apply/real_floorDrz/yz/num_real. Qed.
Lemma floor_ge0 x : (0 <= floor x) = (0 <= x).
Proof. exact: real_floor_ge0. Qed.
Lemma floor_le0 x : (floor x <= 0) = (x < 1).
Proof. exact: real_floor_le0. Qed.
Lemma ceil_itv x : (ceil x - 1)%:~R < x <= (ceil x)%:~R.
Proof. exact: real_ceil_itv. Qed.
Lemma ceilB1_lt x : (ceil x - 1)%:~R < x.
Proof. exact: real_ceilB1_lt. Qed.
Lemma ceil_ge x : x <= (ceil x)%:~R. Proof. exact: real_ceil_ge. Qed.
#[deprecated(since="mathcomp 2.4.0", note="Use ceil_le_int_tmp instead.")]
Lemma ceil_le_int x n : x <= n%:~R = (ceil x <= n).
Proof. by rewrite real_ceil_le_int_tmp. Qed.
(* TODO: rename to ceil_le_int,
once the currently deprecated one has been removed *)
Lemma ceil_le_int_tmp x n : (ceil x <= n) = (x <= n%:~R).
Proof. exact: real_ceil_le_int_tmp. Qed.
Lemma ceil_gt_int x n : (n < ceil x) = (n%:~R < x).
Proof. exact: real_ceil_gt_int. Qed.
Lemma ceil_eq x n : (ceil x == n) = ((n - 1)%:~R < x <= n%:~R).
Proof. exact: real_ceil_eq. Qed.
Lemma ceilDzr : {in @int_num R, {morph ceil : x y / x + y}}.
Proof. by move=> x xz y; apply/real_ceilDzr/num_real. Qed.
Lemma ceilDrz x y : y \is a int_num -> ceil (x + y) = ceil x + ceil y.
Proof. by move=> yz; apply/real_ceilDrz/yz/num_real. Qed.
Lemma ceil_ge0 x : (0 <= ceil x) = (-1 < x).
Proof. exact: real_ceil_ge0. Qed.
Lemma ceil_le0 x : (ceil x <= 0) = (x <= 0).
Proof. exact: real_ceil_le0. Qed.
Lemma ceil_floor x : ceil x = floor x + (x \isn't a int_num).
Proof. exact: real_ceil_floor. Qed.
End ArchiRealDomainTheory.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to floor_le_tmp.")]
Notation ge_floor := floor_le_tmp.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to floorD1_gt.")]
Notation lt_succ_floor := floorD1_gt.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to ceilB1_lt.")]
Notation gt_pred_ceil := ceilB1_lt.
#[deprecated(since="mathcomp 2.4.0", note="Renamed to ceil_ge.")]
Notation le_ceil := ceil_ge.
Section ArchiNumFieldTheory.
(* autLmodC *)
Variables (R : archiNumFieldType) (nu : {rmorphism R -> R}).
Lemma natr_aut x : (nu x \is a nat_num) = (x \is a nat_num).
Proof. by apply/idP/idP=> /[dup] ? /(aut_natr nu) => [/fmorph_inj <-| ->]. Qed.
Lemma intr_aut x : (nu x \is a int_num) = (x \is a int_num).
Proof. by rewrite !intrE -rmorphN !natr_aut. Qed.
End ArchiNumFieldTheory.
Section ArchiClosedFieldTheory.
Variable R : archiClosedFieldType.
Implicit Type x : R.
Lemma conj_natr x : x \is a nat_num -> x^* = x.
Proof. by move/Rreal_nat/CrealP. Qed.
Lemma conj_intr x : x \is a int_num -> x^* = x.
Proof. by move/Rreal_int/CrealP. Qed.
End ArchiClosedFieldTheory.
Section ZnatPred.
Lemma Znat_def (n : int) : (n \is a nat_num) = (0 <= n).
Proof. by []. Qed.
Lemma ZnatP (m : int) : reflect (exists n : nat, m = n) (m \is a nat_num).
Proof. by case: m => m; constructor; [exists m | case]. Qed.
End ZnatPred.
End Theory.
(* Factories *)
HB.factory Record NumDomain_hasTruncn R of Num.NumDomain R := {
trunc : R -> nat;
nat_num : pred R;
int_num : pred R;
truncP : forall x,
if 0 <= x then (trunc x)%:R <= x < (trunc x).+1%:R else trunc x == 0;
natrE : forall x, nat_num x = ((trunc x)%:R == x);
intrE : forall x, int_num x = nat_num x || nat_num (- x);
}.
#[deprecated(since="mathcomp 2.4.0",
note="Use NumDomain_hasTruncn instead.")]
Notation NumDomain_isArchimedean R := (NumDomain_hasTruncn R) (only parsing).
Module NumDomain_isArchimedean.
#[deprecated(since="mathcomp 2.4.0",
note="Use NumDomain_hasTruncn.Build instead.")]
Notation Build T U := (NumDomain_hasTruncn.Build T U) (only parsing).
End NumDomain_isArchimedean.
HB.builders Context R of NumDomain_hasTruncn R.
Fact trunc_itv x : 0 <= x -> (trunc x)%:R <= x < (trunc x).+1%:R.
Proof. by move=> x_ge0; move: (truncP x); rewrite x_ge0. Qed.
Definition floor (x : R) : int :=
if 0 <= x then Posz (trunc x)
else if x < 0 then - Posz (trunc (- x) + ~~ int_num x) else 0.
Fact floorP x :
if x \is Rreal then (floor x)%:~R <= x < (floor x + 1)%:~R else floor x == 0.
Proof.
rewrite /floor intrE !natrE negb_or realE.
case: (comparableP x 0) (@trunc_itv x) => //=;
try by rewrite -PoszD addn1 -pmulrn => _ ->.
move=> x_lt0 _; move: (truncP x); rewrite lt_geF // => /eqP ->.
rewrite gt_eqF //=; move: x_lt0.
rewrite [_ + 1]addrC -opprB !intrN lerNl ltrNr andbC -oppr_gt0.
move: {x}(- x) => x x_gt0; rewrite PoszD -addrA -PoszD.
have ->: Posz ((trunc x)%:R != x) - 1 = - Posz ((trunc x)%:R == x) by case: eqP.
have := trunc_itv (ltW x_gt0); rewrite le_eqVlt.
case: eqVneq => /=; last first.
by rewrite subr0 addn1 -!pmulrn => _ /andP[-> /ltW ->].
by rewrite intrB mulr1z addn0 -!pmulrn => -> _; rewrite gtrBl lexx andbT.
Qed.
Fact truncE x : trunc x = if floor x is Posz n then n else 0.
Proof.
rewrite /floor.
case: (comparableP x 0) (truncP x) => [+ /eqP ->| |_ /eqP ->|] //=.
by case: (_ + _)%N.
Qed.
Fact trunc_def x n : n%:R <= x < n.+1%:R -> trunc x = n.
Proof.
case/andP=> lemx ltxm1; apply/eqP; rewrite eqn_leq -ltnS -[(n <= _)%N]ltnS.
have/trunc_itv/andP[lefx ltxf1]: 0 <= x by apply: le_trans lemx; apply: ler0n.
by rewrite -!(ltr_nat R) 2?(@le_lt_trans _ _ x).
Qed.
Fact natrK : cancel (GRing.natmul 1) trunc.
Proof. by move=> m; apply: trunc_def; rewrite ler_nat ltr_nat ltnS leqnn. Qed.
Fact intrP x : reflect (exists n, x = n%:~R) (int_num x).
Proof.
rewrite intrE !natrE; apply: (iffP idP) => [|[n ->]]; last first.
by case: n => n; rewrite ?NegzE ?opprK natrK eqxx // orbT.
rewrite -eqr_oppLR !pmulrn -intrN.
by move=> /orP[] /eqP<-; [exists (trunc x) | exists (- Posz (trunc (- x)))].
Qed.
Fact natrP x : reflect (exists n, x = n%:R) (nat_num x).
Proof.
rewrite natrE.
by apply: (iffP eqP) => [<-|[n ->]]; [exists (trunc x) | rewrite natrK].
Qed.
HB.instance Definition _ :=
@NumDomain_hasFloorCeilTruncn.Build R floor _ trunc int_num nat_num
floorP (fun=> erefl) truncE intrP natrP.
HB.end.
HB.factory Record NumDomain_bounded_isArchimedean R of Num.NumDomain R := {
archi_bound_subproof : Num.archimedean_axiom R
}.
HB.builders Context R of NumDomain_bounded_isArchimedean R.
Implicit Type x : R.
Definition bound x := sval (sigW (archi_bound_subproof x)).
Lemma boundP x : 0 <= x -> x < (bound x)%:R.
Proof. by move/ger0_norm=> {1}<-; rewrite /bound; case: (sigW _). Qed.
Fact truncn_subproof x : {m | 0 <= x -> m%:R <= x < m.+1%:R }.
Proof.
have [Rx | _] := boolP (0 <= x); last by exists 0%N.
have/ex_minnP[n lt_x_n1 min_n]: exists n, x < n.+1%:R.
by exists (bound x); rewrite (lt_trans (boundP Rx)) ?ltr_nat.
exists n => _; rewrite {}lt_x_n1 andbT; case: n min_n => //= n min_n.
rewrite real_leNgt ?rpred_nat ?ger0_real //; apply/negP => /min_n.
by rewrite ltnn.
Qed.
Definition truncn x := if 0 <= x then sval (truncn_subproof x) else 0%N.
Lemma truncnP x :
if 0 <= x then (truncn x)%:R <= x < (truncn x).+1%:R else truncn x == 0%N.
Proof.
rewrite /truncn; case: truncn_subproof => // n hn.
by case: ifP => x_ge0; rewrite ?(ifT _ _ x_ge0) ?(ifF _ _ x_ge0) // hn.
Qed.
HB.instance Definition _ := NumDomain_hasTruncn.Build R
truncnP (fun => erefl) (fun => erefl).
HB.end.
Module Exports. HB.reexport. End Exports.
(* Not to pollute the local namespace, we define Num.nat and Num.int here. *)
Notation nat := nat_num.
Notation int := int_num.
#[deprecated(since="mathcomp 2.3.0", note="Use Num.ArchiRealDomain instead.")]
Notation ArchiDomain T := (ArchiRealDomain T).
Module ArchiDomain.
#[deprecated(since="mathcomp 2.3.0",
note="Use Num.ArchiRealDomain.type instead.")]
Notation type := ArchiRealDomain.type.
#[deprecated(since="mathcomp 2.3.0",
note="Use Num.ArchiRealDomain.copy instead.")]
Notation copy T C := (ArchiRealDomain.copy T C).
#[deprecated(since="mathcomp 2.3.0",
note="Use Num.ArchiRealDomain.on instead.")]
Notation on T := (ArchiRealDomain.on T).
End ArchiDomain.
#[deprecated(since="mathcomp 2.3.0", note="Use Num.ArchiRealField instead.")]
Notation ArchiField T := (ArchiRealField T).
Module ArchiField.
#[deprecated(since="mathcomp 2.3.0",
note="Use Num.ArchiRealField.type instead.")]
Notation type := ArchiRealField.type.
#[deprecated(since="mathcomp 2.3.0",
note="Use Num.ArchiRealField.copy instead.")]
Notation copy T C := (ArchiRealField.copy T C).
#[deprecated(since="mathcomp 2.3.0", note="Use Num.ArchiRealField.on instead.")]
Notation on T := (ArchiRealField.on T).
End ArchiField.
#[deprecated(since="mathcomp 2.3.0", note="Use real_floorDzr instead.")]
Notation floorD := real_floorDzr.
#[deprecated(since="mathcomp 2.3.0", note="Use real_ceilDzr instead.")]
Notation ceilD := real_ceilDzr.
#[deprecated(since="mathcomp 2.3.0", note="Use real_ceilDzr instead.")]
Notation real_ceilD := real_ceilDzr.
End Num.
Export Num.Exports.
#[deprecated(since="mathcomp 2.3.0", note="Use archiRealDomainType instead.")]
Notation archiDomainType := archiRealDomainType (only parsing).
#[deprecated(since="mathcomp 2.3.0", note="Use archiRealFieldType instead.")]
Notation archiFieldType := archiRealFieldType (only parsing).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.