filename
stringlengths
5
42
content
stringlengths
15
319k
fieldext.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div. From mathcomp Require Import choice fintype tuple finfun bigop ssralg countalg. From mathcomp Require Import finalg zmodp matrix vector falgebra poly polydiv. From mathcomp Require Import mxpoly generic_quotient. (******************************************************************************) (* Finite dimensional field extensions *) (* *) (* fieldExtType F == the interface type for finite field extensions of F *) (* it simply combines the fieldType and falgType F *) (* interfaces *) (* The HB class is called FieldExt. *) (* {subfield L} == the type of subfields of L that are also extensions *) (* of F; since we are in a finite dimensional setting *) (* these are exactly the F-subalgebras of L, and *) (* indeed {subfield L} is just display notation for *) (* {aspace L} when L is an extFieldType *) (* --> All aspace operations apply to {subfield L}, but there are several *) (* additional lemmas and canonical instances specific to {subfield L} *) (* spaces, e.g., subvs_of E is an extFieldType F when E : {subfield L}. *) (* --> Also note that not all constructive subfields have type {subfield E} *) (* in the same way that not all constructive subspaces have type *) (* {vspace E}. These types only include the so called "detachable" *) (* subspaces (and subalgebras). *) (* *) (* (E :&: F)%AS, (E * F)%AS == the intersection and product (meet and join) *) (* of E and F as subfields *) (* subFExtend iota z p == given a field morphism iota : F -> L, this is a *) (* type for the field F^iota(z) obtained by *) (* adjoining z to the image of F in L under iota *) (* The construction requires a non-zero polynomial *) (* p in F such that z is a root of p^iota; it *) (* returns the field F^iota if this is not so. *) (* However, p need not be irredicible. *) (* subfx_inj x == the injection of F^iota(z) into L *) (* inj_subfx iota z p x == the injection of F into F^iota(z) *) (* subfx_eval iota z p q == given q : {poly F} returns q.[z] as a value of *) (* type F^iota(z) *) (* subfx_root iota z p == the generator of F^iota(z) over F *) (* SubFieldExtType pz0 irr_p == a fieldExtType F structure for F^iota(z) *) (* (more precisely, subFExtend iota z p), given *) (* proofs pz0: root (map_poly iota p) z and *) (* irr_p : irreducible_poly p. *) (* The corresponding vectType substructure *) (* (SubfxVectType pz0 irr_p) has dimension *) (* (size p).-1 over F. *) (* minPoly K x == the monic minimal polynomial of x over the *) (* subfield K *) (* adjoin_degree K x == the degree of the minimal polynomial or the *) (* dimension of K(x)/K *) (* Fadjoin_poly K x y == a polynomial p over K such that y = p.[x] *) (* *) (* fieldOver F == L, but with an extFieldType (subvs_of F) *) (* structure, for F : {subfield L} *) (* vspaceOver F V == the smallest subspace of fieldOver F containing *) (* V; this coincides with V if V is an F-module *) (* baseFieldType L == L, but with an extFieldType F0 structure, when L *) (* has a canonical extFieldType F structure and F *) (* in turn has an extFieldType F0 structure *) (* baseVspace V == the subspace of baseFieldType L that coincides *) (* with V : {vspace L} *) (* --> Some caution must be exercised when using fieldOver and baseFieldType, *) (* because these are convertible to L while carrying different Lmodule *) (* structures. This means that the safeguards engineered in the ssralg *) (* library that normally curb the Coq kernel's inclination to diverge are *) (* no longer effectcive, so additional precautions should be taken when *) (* matching or rewriting terms of the form a *: u, because Coq may take *) (* forever to realize it's dealing with a *: in the wrong structure. The *) (* baseField_scaleE and fieldOver_scaleE lemmas should be used to expand *) (* or fold such "trans-structure" operations explicitly beforehand. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Local Open Scope ring_scope. Import GRing.Theory. #[short(type="fieldExtType")] HB.structure Definition FieldExt (R : nzRingType) := {T of Falgebra R T & GRing.PzRing_hasCommutativeMul T & GRing.Field T}. Module FieldExtExports. Bind Scope ring_scope with FieldExt.sort. Notation "{ 'subfield' L }" := (aspace L) (* NB: was (@aspace_of _ (FalgType _) (Phant L)) *) (format "{ 'subfield' L }") : type_scope. End FieldExtExports. HB.export FieldExtExports. (* FIXME: strange way to build a FieldExt *) HB.instance Definition _ (F : fieldType) := GRing.Field.on F^o. Section FieldExtTheory. Variables (F0 : fieldType) (L : fieldExtType F0). Implicit Types (U V M : {vspace L}) (E F K : {subfield L}). Lemma dim_cosetv U x : x != 0 -> \dim (U * <[x]>) = \dim U. Proof. move=> nz_x; rewrite -limg_amulr limg_dim_eq //. apply/eqP; rewrite -subv0; apply/subvP=> y. by rewrite memv_cap memv0 memv_ker lfunE mulf_eq0 (negPf nz_x) orbF => /andP[]. Qed. Lemma prodvC : commutative (@prodv F0 L). Proof. move=> U V; without loss suffices subC: U V / (U * V <= V * U)%VS. by apply/eqP; rewrite eqEsubv !{1}subC. by apply/prodvP=> x y Ux Vy; rewrite mulrC memv_mul. Qed. HB.instance Definition _ := SemiGroup.isCommutativeLaw.Build {vspace L} (@prodv _ L) prodvC. Lemma prodvCA : left_commutative (@prodv F0 L). Proof. exact: Monoid.mulmCA. Qed. Lemma prodvAC : right_commutative (@prodv F0 L). Proof. exact: Monoid.mulmAC. Qed. Lemma algid1 K : algid K = 1. Proof. exact/skew_field_algid1/fieldP. Qed. Lemma mem1v K : 1 \in K. Proof. by rewrite -algid_eq1 algid1. Qed. Lemma sub1v K : (1 <= K)%VS. Proof. exact: mem1v. Qed. Lemma subfield_closed K : agenv K = K. Proof. by apply/eqP; rewrite eqEsubv sub_agenv agenv_sub_modr ?sub1v ?asubv. Qed. Lemma AHom_lker0 (rT : falgType F0) (f : 'AHom(L, rT)) : lker f == 0%VS. Proof. by apply/lker0P; apply: fmorph_inj. Qed. Lemma AEnd_lker0 (f : 'AEnd(L)) : lker f == 0%VS. Proof. exact: AHom_lker0. Qed. Fact aimg_is_aspace (rT : falgType F0) (f : 'AHom(L, rT)) (E : {subfield L}) : is_aspace (f @: E). Proof. rewrite /is_aspace -aimgM limgS ?prodv_id // has_algid1 //. by apply/memv_imgP; exists 1; rewrite ?mem1v ?rmorph1. Qed. Canonical aimg_aspace rT f E := ASpace (@aimg_is_aspace rT f E). Lemma Fadjoin_idP {K x} : reflect (<<K; x>>%VS = K) (x \in K). Proof. apply: (iffP idP) => [/addv_idPl-> | <-]; first exact: subfield_closed. exact: memv_adjoin. Qed. Lemma Fadjoin0 K : <<K; 0>>%VS = K. Proof. by rewrite addv0 subfield_closed. Qed. Lemma Fadjoin_nil K : <<K & [::]>>%VS = K. Proof. by rewrite adjoin_nil subfield_closed. Qed. Lemma FadjoinP {K x E} : reflect (K <= E /\ x \in E)%VS (<<K; x>>%AS <= E)%VS. Proof. apply: (iffP idP) => [sKxE | /andP]. by rewrite (subvP sKxE) ?memv_adjoin // (subv_trans _ sKxE) ?subv_adjoin. by rewrite -subv_add => /agenvS; rewrite subfield_closed. Qed. Lemma Fadjoin_seqP {K} {rs : seq L} {E} : reflect (K <= E /\ {subset rs <= E})%VS (<<K & rs>> <= E)%VS. Proof. apply: (iffP idP) => [sKrsE | [sKE /span_subvP/(conj sKE)/andP]]. split=> [|x rs_x]; first exact: subv_trans (subv_adjoin_seq _ _) sKrsE. by rewrite (subvP sKrsE) ?seqv_sub_adjoin. by rewrite -subv_add => /agenvS; rewrite subfield_closed. Qed. Lemma alg_polyOver E p : map_poly (in_alg L) p \is a polyOver E. Proof. by apply/(polyOverS (subvP (sub1v _)))/polyOver1P; exists p. Qed. Lemma sub_adjoin1v x E : (<<1; x>> <= E)%VS = (x \in E)%VS. Proof. by rewrite (sameP FadjoinP andP) sub1v. Qed. Fact vsval_monoid_morphism K : monoid_morphism (vsval : subvs_of K -> L). Proof. by split => //=; apply: algid1. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `subfx_eval_is_monoid_morphism` instead")] Definition vsval_is_multiplicative K := (fun g => (g.2,g.1)) (vsval_monoid_morphism K). HB.instance Definition _ (K : {subfield L}) := GRing.isMonoidMorphism.Build (subvs_of K) L vsval (vsval_monoid_morphism K). Lemma vsval_invf K (w : subvs_of K) : val w^-1 = (vsval w)^-1. Proof. have [-> | Uv] := eqVneq w 0; first by rewrite !invr0. by apply: vsval_invr; rewrite unitfE. Qed. Fact aspace_divr_closed K : divr_closed K. Proof. by split=> [|u v Ku Kv]; rewrite ?mem1v ?memvM ?memvV. Qed. HB.instance Definition _ K := GRing.isDivClosed.Build L (pred_of_vspace K) (aspace_divr_closed K). HB.instance Definition _ (K : {subfield L}) := GRing.isSubPzSemiRing.Build L (pred_of_vspace K) (subvs_of K) (rmorph1 _, rmorphM _). (* Note that the nzRingType structure was built in the SubFalgType section of falgebra.v but the SubRing structure did not stand there, it is thus built only here *) HB.instance Definition _ (K : {subfield L}) := [SubNzRing_isSubComNzRing of subvs_of K by <:]. HB.instance Definition _ (K : {subfield L}) := [SubComUnitRing_isSubIntegralDomain of subvs_of K by <:]. Lemma subvs_fieldMixin K : GRing.field_axiom (subvs_of K). Proof. by move=> w nz_w; rewrite unitrE -val_eqE /= vsval_invf algid1 divff. Qed. HB.instance Definition _ K := GRing.UnitRing_isField.Build (subvs_of K) (@subvs_fieldMixin K). Lemma polyOver_subvs {K} {p : {poly L}} : reflect (exists q : {poly subvs_of K}, p = map_poly vsval q) (p \is a polyOver K). Proof. apply: (iffP polyOverP) => [Hp | [q ->] i]; last by rewrite coef_map // subvsP. exists (\poly_(i < size p) (Subvs (Hp i))); rewrite -{1}[p]coefK. by apply/polyP=> i; rewrite coef_map !coef_poly; case: ifP. Qed. Lemma divp_polyOver K : {in polyOver K &, forall p q, p %/ q \is a polyOver K}. Proof. move=> _ _ /polyOver_subvs[p ->] /polyOver_subvs[q ->]. by apply/polyOver_subvs; exists (p %/ q); rewrite map_divp. Qed. Lemma modp_polyOver K : {in polyOver K &, forall p q, p %% q \is a polyOver K}. Proof. move=> _ _ /polyOver_subvs[p ->] /polyOver_subvs[q ->]. by apply/polyOver_subvs; exists (p %% q); rewrite map_modp. Qed. Lemma gcdp_polyOver K : {in polyOver K &, forall p q, gcdp p q \is a polyOver K}. Proof. move=> _ _ /polyOver_subvs[p ->] /polyOver_subvs[q ->]. by apply/polyOver_subvs; exists (gcdp p q); rewrite gcdp_map. Qed. Fact prodv_is_aspace E F : is_aspace (E * F). Proof. rewrite /is_aspace prodvCA -!prodvA prodvA !prodv_id has_algid1 //=. by rewrite -[1]mulr1 memv_mul ?mem1v. Qed. Canonical prodv_aspace E F : {subfield L} := ASpace (prodv_is_aspace E F). Fact field_mem_algid E F : algid E \in F. Proof. by rewrite algid1 mem1v. Qed. Canonical capv_aspace E F : {subfield L} := aspace_cap (field_mem_algid E F). Lemma polyOverSv U V : (U <= V)%VS -> {subset polyOver U <= polyOver V}. Proof. by move/subvP=> sUV; apply: polyOverS. Qed. Lemma field_subvMl F U : (U <= F * U)%VS. Proof. by rewrite -{1}[U]prod1v prodvSl ?sub1v. Qed. Lemma field_subvMr U F : (U <= U * F)%VS. Proof. by rewrite prodvC field_subvMl. Qed. Lemma field_module_eq F M : (F * M <= M)%VS -> (F * M)%VS = M. Proof. by move=> modM; apply/eqP; rewrite eqEsubv modM field_subvMl. Qed. Lemma sup_field_module F E : (F * E <= E)%VS = (F <= E)%VS. Proof. apply/idP/idP; first exact: subv_trans (field_subvMr F E). by move/(prodvSl E)/subv_trans->; rewrite ?asubv. Qed. Lemma field_module_dimS F M : (F * M <= M)%VS -> (\dim F %| \dim M)%N. Proof. exact/skew_field_module_dimS/fieldP. Qed. Lemma field_dimS F E : (F <= E)%VS -> (\dim F %| \dim E)%N. Proof. exact/skew_field_dimS/fieldP. Qed. Lemma dim_field_module F M : (F * M <= M)%VS -> \dim M = (\dim_F M * \dim F)%N. Proof. by move/field_module_dimS/divnK. Qed. Lemma dim_sup_field F E : (F <= E)%VS -> \dim E = (\dim_F E * \dim F)%N. Proof. by move/field_dimS/divnK. Qed. Lemma field_module_semisimple F M (m := \dim_F M) : (F * M <= M)%VS -> {X : m.-tuple L | {subset X <= M} /\ 0 \notin X & let FX := (\sum_(i < m) F * <[X`_i]>)%VS in FX = M /\ directv FX}. Proof. move=> modM; have dimM: (m * \dim F)%N = \dim M by rewrite -dim_field_module. have [X [defM dxFX nzX]] := skew_field_module_semisimple (@fieldP L) modM. have szX: size X == m. rewrite -(eqn_pmul2r (adim_gt0 F)) dimM -defM (directvP dxFX) /=. rewrite -sum1_size big_distrl; apply/eqP/eq_big_seq => x Xx /=. by rewrite mul1n dim_cosetv ?(memPn nzX). rewrite directvE /= (big_nth 0) [eqbRHS](big_nth 0) in defM dxFX. rewrite (eqP szX) !big_mkord -directvE in defM dxFX. exists (Tuple szX) => //; split=> // _ /tnthP[i ->]; rewrite (tnth_nth 0) /=. by rewrite -defM memvE (sumv_sup i) ?field_subvMl. Qed. Section FadjoinPolyDefinitions. Variables (U : {vspace L}) (x : L). Definition adjoin_degree := (\dim_U <<U; x>>).-1.+1. Local Notation n := adjoin_degree. Definition Fadjoin_sum := (\sum_(i < n) U * <[x ^+ i]>)%VS. Definition Fadjoin_poly v : {poly L} := \poly_(i < n) (sumv_pi Fadjoin_sum (inord i) v / x ^+ i). Definition minPoly : {poly L} := 'X^n - Fadjoin_poly (x ^+ n). Lemma size_Fadjoin_poly v : size (Fadjoin_poly v) <= n. Proof. exact: size_poly. Qed. Lemma Fadjoin_polyOver v : Fadjoin_poly v \is a polyOver U. Proof. apply/(all_nthP 0) => i _; rewrite coef_poly /=. case: ifP => lti; last exact: mem0v. have /memv_cosetP[y Uy ->] := memv_sum_pi (erefl Fadjoin_sum) (inord i) v. rewrite inordK //; have [-> | /mulfK-> //] := eqVneq (x ^+ i) 0. by rewrite mulr0 mul0r mem0v. Qed. Fact Fadjoin_poly_is_linear : linear_for (in_alg L \; *:%R) Fadjoin_poly. Proof. move=> a u v; apply/polyP=> i; rewrite coefD coefZ !coef_poly. case: ifP => lti; last by rewrite mulr0 addr0. by rewrite linearP mulrA -mulrDl mulr_algl. Qed. HB.instance Definition _ := GRing.isSemilinear.Build F0 L {poly L} _ Fadjoin_poly (GRing.semilinear_linear Fadjoin_poly_is_linear). Lemma size_minPoly : size minPoly = n.+1. Proof. by rewrite size_polyDl ?size_polyXn // size_polyN ltnS size_poly. Qed. Lemma monic_minPoly : minPoly \is monic. Proof. rewrite monicE /lead_coef size_minPoly coefB coefXn eqxx. by rewrite nth_default ?subr0 ?size_poly. Qed. End FadjoinPolyDefinitions. Section FadjoinPoly. Variables (K : {subfield L}) (x : L). Local Notation n := (adjoin_degree (asval K) x). Local Notation sumKx := (Fadjoin_sum (asval K) x). Lemma adjoin_degreeE : n = \dim_K <<K; x>>. Proof. by rewrite [n]prednK // divn_gt0 ?adim_gt0 // dimvS ?subv_adjoin. Qed. Lemma dim_Fadjoin : \dim <<K; x>> = (n * \dim K)%N. Proof. by rewrite adjoin_degreeE -dim_sup_field ?subv_adjoin. Qed. Lemma adjoin0_deg : adjoin_degree K 0 = 1. Proof. by rewrite /adjoin_degree addv0 subfield_closed divnn adim_gt0. Qed. Lemma adjoin_deg_eq1 : (n == 1) = (x \in K). Proof. rewrite (sameP Fadjoin_idP eqP) adjoin_degreeE; have sK_Kx := subv_adjoin K x. apply/eqP/idP=> [dimKx1 | /eqP->]; last by rewrite divnn adim_gt0. by rewrite eq_sym eqEdim sK_Kx /= (dim_sup_field sK_Kx) dimKx1 mul1n. Qed. Lemma Fadjoin_sum_direct : directv sumKx. Proof. rewrite directvE /=; case: (ubnPgeq n) (isT : n > 0) => -[//|m] ltmn _. elim: m ltmn => [|m IHm] ltm1n; rewrite ?big_ord1 // !(big_ord_recr m.+1) /=. do [move/(_ (ltnW ltm1n))/eqP; set S := (\sum_i _)%VS] in IHm *. rewrite -IHm dimv_add_leqif; apply/subvP=> z; rewrite memv_cap => /andP[Sz]. case/memv_cosetP=> y Ky Dz; rewrite memv0 Dz mulf_eq0 expf_eq0 /=. apply: contraLR ltm1n => /norP[nz_y nz_x]. rewrite -leqNgt -(leq_pmul2r (adim_gt0 K)) -dim_Fadjoin. have{IHm} ->: (m.+1 * \dim K)%N = \dim S. rewrite -[m.+1]card_ord -sum_nat_const IHm. by apply: eq_bigr => i; rewrite dim_cosetv ?expf_neq0. apply/dimvS/agenv_sub_modl; first by rewrite (sumv_sup 0) //= prodv1 sub1v. rewrite prodvDl subv_add -[S]big_distrr prodvA prodv_id subvv !big_distrr /=. apply/subv_sumP=> i _; rewrite -expv_line prodvCA -expvSl expv_line. have [ltim | lemi] := ltnP i m; first by rewrite (sumv_sup (Sub i.+1 _)). have{lemi} /eqP->: i == m :> nat by rewrite eqn_leq leq_ord. rewrite -big_distrr -2!{2}(prodv_id K) /= -!prodvA big_distrr -/S prodvSr //=. by rewrite -(canLR (mulKf nz_y) Dz) -memvE memv_mul ?rpredV. Qed. Let nz_x_i (i : 'I_n) : x ^+ i != 0. Proof. by rewrite expf_eq0; case: eqP i => [->|_] [[]] //; rewrite adjoin0_deg. Qed. Lemma Fadjoin_eq_sum : <<K; x>>%VS = sumKx. Proof. apply/esym/eqP; rewrite eqEdim eq_leq ?andbT. apply/subv_sumP=> i _; rewrite -agenvM prodvS ?subv_adjoin //. by rewrite -expv_line (subv_trans (subX_agenv _ _)) ?agenvS ?addvSr. rewrite dim_Fadjoin -[n]card_ord -sum_nat_const (directvP Fadjoin_sum_direct). by apply: eq_bigr => i _; rewrite /= dim_cosetv. Qed. Lemma Fadjoin_poly_eq v : v \in <<K; x>>%VS -> (Fadjoin_poly K x v).[x] = v. Proof. move/(sumv_pi_sum Fadjoin_eq_sum)=> {2}<-; rewrite horner_poly. by apply: eq_bigr => i _; rewrite inord_val mulfVK. Qed. Lemma mempx_Fadjoin p : p \is a polyOver K -> p.[x] \in <<K; x>>%VS. Proof. move=> Kp; rewrite rpred_horner ?memv_adjoin ?(polyOverS _ Kp) //. exact: subvP_adjoin. Qed. Lemma Fadjoin_polyP {v} : reflect (exists2 p, p \in polyOver K & v = p.[x]) (v \in <<K; x>>%VS). Proof. apply: (iffP idP) => [Kx_v | [p Kp ->]]; last exact: mempx_Fadjoin. by exists (Fadjoin_poly K x v); rewrite ?Fadjoin_polyOver ?Fadjoin_poly_eq. Qed. Lemma Fadjoin_poly_unique p v : p \is a polyOver K -> size p <= n -> p.[x] = v -> Fadjoin_poly K x v = p. Proof. have polyKx q i: q \is a polyOver K -> q`_i * x ^+ i \in (K * <[x ^+ i]>)%VS. by move/polyOverP=> Kq; rewrite memv_mul ?Kq ?memv_line. move=> Kp szp Dv; have /Fadjoin_poly_eq/eqP := mempx_Fadjoin Kp. rewrite {1}Dv {Dv} !(@horner_coef_wide _ n) ?size_poly //. move/polyKx in Kp; have /polyKx K_pv := Fadjoin_polyOver K x v. rewrite (directv_sum_unique Fadjoin_sum_direct) // => /eqfunP eq_pq. apply/polyP=> i; have [leni|?] := leqP n i; last exact: mulIf (eq_pq (Sub i _)). by rewrite !nth_default ?(leq_trans _ leni) ?size_poly. Qed. Lemma Fadjoin_polyC v : v \in K -> Fadjoin_poly K x v = v%:P. Proof. move=> Kv; apply: Fadjoin_poly_unique; rewrite ?polyOverC ?hornerC //. by rewrite size_polyC (leq_trans (leq_b1 _)). Qed. Lemma Fadjoin_polyX : x \notin K -> Fadjoin_poly K x x = 'X. Proof. move=> K'x; apply: Fadjoin_poly_unique; rewrite ?polyOverX ?hornerX //. by rewrite size_polyX ltn_neqAle andbT eq_sym adjoin_deg_eq1. Qed. Lemma minPolyOver : minPoly K x \is a polyOver K. Proof. by rewrite /minPoly rpredB ?rpredX ?polyOverX ?Fadjoin_polyOver. Qed. Lemma minPolyxx : (minPoly K x).[x] = 0. Proof. by rewrite !hornerE Fadjoin_poly_eq ?subrr ?rpredX ?memv_adjoin. Qed. Lemma root_minPoly : root (minPoly K x) x. Proof. exact/rootP/minPolyxx. Qed. Lemma Fadjoin_poly_mod p : p \is a polyOver K -> Fadjoin_poly K x p.[x] = p %% minPoly K x. Proof. move=> Kp; rewrite {1}(divp_eq p (minPoly K x)) 2!hornerE minPolyxx mulr0 add0r. apply: Fadjoin_poly_unique => //; first by rewrite modp_polyOver // minPolyOver. by rewrite -ltnS -size_minPoly ltn_modp // monic_neq0 ?monic_minPoly. Qed. Lemma minPoly_XsubC : reflect (minPoly K x = 'X - x%:P) (x \in K). Proof. set p := minPoly K x; apply: (iffP idP) => [Kx | Dp]; last first. suffices ->: x = - p`_0 by rewrite rpredN (polyOverP minPolyOver). by rewrite Dp coefB coefX coefC add0r opprK. rewrite (@all_roots_prod_XsubC _ p [:: x]) /= ?root_minPoly //. by rewrite big_seq1 (monicP (monic_minPoly K x)) scale1r. by apply/eqP; rewrite size_minPoly eqSS adjoin_deg_eq1. Qed. Lemma root_small_adjoin_poly p : p \is a polyOver K -> size p <= n -> root p x = (p == 0). Proof. move=> Kp szp; apply/rootP/eqP=> [px0 | ->]; last by rewrite horner0. rewrite -(Fadjoin_poly_unique Kp szp px0). by apply: Fadjoin_poly_unique; rewrite ?polyOver0 ?size_poly0 ?horner0. Qed. Lemma minPoly_irr p : p \is a polyOver K -> p %| minPoly K x -> (p %= minPoly K x) || (p %= 1). Proof. rewrite dvdp_eq; set q := _ %/ _ => Kp def_pq. have Kq: q \is a polyOver K by rewrite divp_polyOver // minPolyOver. move: q Kq def_pq root_minPoly (size_minPoly K x) => q Kq /eqP->. rewrite rootM => pqx0 szpq. have [nzq nzp]: q != 0 /\ p != 0. by apply/norP; rewrite -mulf_eq0 -size_poly_eq0 szpq. without loss{pqx0} qx0: q p Kp Kq nzp nzq szpq / root q x. move=> IH; case/orP: pqx0 => /IH{}IH; first exact: IH. have{IH} /orP[]: (q %= p * q) || (q %= 1) by apply: IH => //; rewrite mulrC. by rewrite orbC -{1}[q]mul1r eqp_mul2r // eqp_sym => ->. by rewrite -{1}[p]mul1r eqp_sym eqp_mul2r // => ->. apply/orP; right; rewrite -size_poly_eq1 eqn_leq lt0n size_poly_eq0 nzp andbT. rewrite -(leq_add2r (size q)) -leq_subLR subn1 -size_mul // mulrC szpq. by rewrite ltnNge; apply: contra nzq => /(root_small_adjoin_poly Kq) <-. Qed. Lemma minPoly_dvdp p : p \is a polyOver K -> root p x -> (minPoly K x) %| p. Proof. move=> Kp rootp. have gcdK : gcdp (minPoly K x) p \is a polyOver K. by rewrite gcdp_polyOver ?minPolyOver. have /orP[gcd_eqK|gcd_eq1] := minPoly_irr gcdK (dvdp_gcdl (minPoly K x) p). by rewrite -(eqp_dvdl _ gcd_eqK) dvdp_gcdr. case/negP: (root1 x). by rewrite -(eqp_root gcd_eq1) root_gcd rootp root_minPoly. Qed. End FadjoinPoly. Lemma minPolyS K E a : (K <= E)%VS -> minPoly E a %| minPoly K a. Proof. move=> sKE; apply: minPoly_dvdp; last exact: root_minPoly. by apply: (polyOverSv sKE); rewrite minPolyOver. Qed. Arguments Fadjoin_polyP {K x v}. Lemma Fadjoin1_polyP x v : reflect (exists p, v = (map_poly (in_alg L) p).[x]) (v \in <<1; x>>%VS). Proof. apply: (iffP Fadjoin_polyP) => [[_ /polyOver1P]|] [p ->]; first by exists p. by exists (map_poly (in_alg L) p) => //; apply: alg_polyOver. Qed. Section Horner. Variables z : L. Definition fieldExt_horner := horner_morph (fun x => mulrC z (in_alg L x)). HB.instance Definition _ := GRing.RMorphism.on fieldExt_horner. Lemma fieldExt_hornerC b : fieldExt_horner b%:P = b%:A. Proof. exact: horner_morphC. Qed. Lemma fieldExt_hornerX : fieldExt_horner 'X = z. Proof. exact: horner_morphX. Qed. Fact fieldExt_hornerZ : scalable fieldExt_horner. Proof. move=> a p; rewrite -mul_polyC rmorphM /= fieldExt_hornerC. by rewrite -scalerAl mul1r. Qed. HB.instance Definition _ := GRing.isScalable.Build F0 {poly F0} L *:%R fieldExt_horner fieldExt_hornerZ. End Horner. End FieldExtTheory. Notation "E :&: F" := (capv_aspace E F) : aspace_scope. Notation "'C_ E [ x ]" := (capv_aspace E 'C[x]) : aspace_scope. Notation "'C_ ( E ) [ x ]" := (capv_aspace E 'C[x]) (only parsing) : aspace_scope. Notation "'C_ E ( V )" := (capv_aspace E 'C(V)) : aspace_scope. Notation "'C_ ( E ) ( V )" := (capv_aspace E 'C(V)) (only parsing) : aspace_scope. Notation "E * F" := (prodv_aspace E F) : aspace_scope. Notation "f @: E" := (aimg_aspace f E) : aspace_scope. Arguments Fadjoin_idP {F0 L K x}. Arguments FadjoinP {F0 L K x E}. Arguments Fadjoin_seqP {F0 L K rs E}. Arguments polyOver_subvs {F0 L K p}. Arguments Fadjoin_polyP {F0 L K x v}. Arguments Fadjoin1_polyP {F0 L x v}. Arguments minPoly_XsubC {F0 L K x}. Section MapMinPoly. Variables (F0 : fieldType) (L rL : fieldExtType F0) (f : 'AHom(L, rL)). Variables (K : {subfield L}) (x : L). Lemma adjoin_degree_aimg : adjoin_degree (f @: K) (f x) = adjoin_degree K x. Proof. rewrite !adjoin_degreeE -aimg_adjoin. by rewrite !limg_dim_eq ?(eqP (AHom_lker0 f)) ?capv0. Qed. Lemma map_minPoly : map_poly f (minPoly K x) = minPoly (f @: K) (f x). Proof. set fp := minPoly (f @: K) (f x). have [p Kp Dp]: exists2 p, p \is a polyOver K & map_poly f p = fp. have Kfp: fp \is a polyOver (f @: K)%VS by apply: minPolyOver. exists (map_poly f^-1%VF fp). apply/polyOver_poly=> j _; have /memv_imgP[y Ky ->] := polyOverP Kfp j. by rewrite lker0_lfunK ?AHom_lker0. rewrite -map_poly_comp map_poly_id // => _ /(allP Kfp)/memv_imgP[y _ ->]. by rewrite /= limg_lfunVK ?memv_img ?memvf. apply/eqP; rewrite -eqp_monic ?monic_map ?monic_minPoly // -Dp eqp_map. have: ~~ (p %= 1) by rewrite -size_poly_eq1 -(size_map_poly f) Dp size_minPoly. apply: implyP; rewrite implyNb orbC eqp_sym minPoly_irr //. rewrite -(dvdp_map f) Dp minPoly_dvdp ?fmorph_root ?root_minPoly //. by apply/polyOver_poly=> j _; apply/memv_img/polyOverP/minPolyOver. Qed. End MapMinPoly. (* Changing up the reference field of a fieldExtType. *) Section FieldOver. Variables (F0 : fieldType) (L : fieldExtType F0) (F : {subfield L}). Definition fieldOver of {vspace L} : Type := L. Local Notation K_F := (subvs_of F). Local Notation L_F := (fieldOver F). HB.instance Definition _ := GRing.Field.on L_F. Definition fieldOver_scale (a : K_F) (u : L_F) : L_F := vsval a * u. Local Infix "*F:" := fieldOver_scale (at level 40). Fact fieldOver_scaleA a b u : a *F: (b *F: u) = (a * b) *F: u. Proof. exact: mulrA. Qed. Fact fieldOver_scale1 u : 1 *F: u = u. Proof. by rewrite /(1 *F: u) /= algid1 mul1r. Qed. Fact fieldOver_scaleDr a u v : a *F: (u + v) = a *F: u + a *F: v. Proof. exact: mulrDr. Qed. Fact fieldOver_scaleDl v a b : (a + b) *F: v = a *F: v + b *F: v. Proof. exact: mulrDl. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build _ L_F fieldOver_scaleA fieldOver_scale1 fieldOver_scaleDr fieldOver_scaleDl. Lemma fieldOver_scaleE a (u : L) : a *: (u : L_F) = vsval a * u. Proof. by []. Qed. Fact fieldOver_scaleAl a u v : a *F: (u * v) = (a *F: u) * v. Proof. exact: mulrA. Qed. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build _ L_F fieldOver_scaleAl. Fact fieldOver_scaleAr a u v : a *F: (u * v) = u * (a *F: v). Proof. exact: mulrCA. Qed. HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build _ L_F fieldOver_scaleAr. Fact fieldOver_vectMixin : Lmodule_hasFinDim K_F L_F. Proof. have [bL [_ nz_bL] [defL dxSbL]] := field_module_semisimple (subvf (F * _)). do [set n := \dim_F {:L} in bL nz_bL *; set SbL := (\sum_i _)%VS] in defL dxSbL. have in_bL i (a : K_F) : val a * (bL`_i : L_F) \in (F * <[bL`_i]>)%VS. by rewrite memv_mul ?(valP a) ?memv_line. have nz_bLi (i : 'I_n): bL`_i != 0 by rewrite (memPn nz_bL) ?memt_nth. pose r2v (v : 'rV[K_F]_n) : L_F := \sum_i v 0 i *: (bL`_i : L_F). have r2v_lin: linear r2v. move=> a u v; rewrite /r2v scaler_sumr -big_split /=; apply: eq_bigr => i _. by rewrite scalerA -scalerDl !mxE. pose r2vlM := GRing.isLinear.Build _ _ _ _ r2v r2v_lin. pose r2vL : {linear _ -> _} := HB.pack r2v r2vlM. have v2rP x: {r : 'rV[K_F]_n | x = r2v r}. apply: sig_eqW; have /memv_sumP[y Fy ->]: x \in SbL by rewrite defL memvf. have /fin_all_exists[r Dr] i: exists r, y i = r *: (bL`_i : L_F). by have /memv_cosetP[a Fa ->] := Fy i isT; exists (Subvs Fa). by exists (\row_i r i); apply: eq_bigr => i _; rewrite mxE. pose v2r x := sval (v2rP x). have v2rK: cancel v2r r2vL by rewrite /v2r => x; case: (v2rP x). suffices r2vK: cancel r2v v2r. by exists n, v2r; [apply: can2_linear v2rK | exists r2v]. move=> r; apply/rowP=> i; apply/val_inj/(mulIf (nz_bLi i))/eqP; move: i isT. by apply/forall_inP; move/directv_sum_unique: dxSbL => <- //; apply/eqP/v2rK. Qed. HB.instance Definition _ := fieldOver_vectMixin. Implicit Types (V : {vspace L}) (E : {subfield L}). Lemma trivial_fieldOver : (1%VS : {vspace L_F}) =i F. Proof. move=> x; apply/vlineP/idP=> [[{}x ->] | Fx]. by rewrite fieldOver_scaleE mulr1 (valP x). by exists (vsproj F x); rewrite fieldOver_scaleE mulr1 vsprojK. Qed. Definition vspaceOver V := <<vbasis V : seq L_F>>%VS. Lemma mem_vspaceOver V : vspaceOver V =i (F * V)%VS. Proof. move=> y; apply/idP/idP; last rewrite unlock; move/coord_span->. rewrite (@memv_suml F0 L) // => i _. by rewrite memv_mul ?subvsP // vbasis_mem ?memt_nth. rewrite memv_suml // => ij _; rewrite -tnth_nth; set x := tnth _ ij. have/allpairsP[[u z] /= [Fu Vz {x}->]]: x \in _ := mem_tnth ij _. by rewrite scalerAl (memvZ (Subvs _)) ?memvZ ?memv_span //= vbasis_mem. Qed. Lemma mem_aspaceOver E : (F <= E)%VS -> vspaceOver E =i E. Proof. by move=> sFE y; rewrite mem_vspaceOver field_module_eq ?sup_field_module. Qed. Fact aspaceOver_suproof E : is_aspace (vspaceOver E). Proof. rewrite /is_aspace has_algid1; last by rewrite mem_vspaceOver (@mem1v _ L). by apply/prodvP=> u v; rewrite !mem_vspaceOver; apply: memvM. Qed. Canonical aspaceOver E := ASpace (aspaceOver_suproof E). Lemma dim_vspaceOver M : (F * M <= M)%VS -> \dim (vspaceOver M) = \dim_F M. Proof. move=> modM; have [] := field_module_semisimple modM. set n := \dim_F M => b [Mb nz_b] [defM dx_b]. suff: basis_of (vspaceOver M) b by apply: size_basis. apply/andP; split. rewrite eqEsubv; apply/andP; split; apply/span_subvP=> u. by rewrite mem_vspaceOver field_module_eq // => /Mb. move/(@vbasis_mem _ _ _ M); rewrite -defM => /memv_sumP[{}u Fu ->]. apply: memv_suml => i _; have /memv_cosetP[a Fa ->] := Fu i isT. by apply: (memvZ (Subvs Fa)); rewrite memv_span ?memt_nth. apply/freeP=> a /(directv_sum_independent dx_b) a_0 i. have{a_0}: a i *: (b`_i : L_F) == 0. by rewrite a_0 {i}// => i _; rewrite memv_mul ?memv_line ?subvsP. by rewrite scaler_eq0=> /predU1P[] // /idPn[]; rewrite (memPn nz_b) ?memt_nth. Qed. Lemma dim_aspaceOver E : (F <= E)%VS -> \dim (vspaceOver E) = \dim_F E. Proof. by rewrite -sup_field_module; apply: dim_vspaceOver. Qed. Lemma vspaceOverP V_F : {V | [/\ V_F = vspaceOver V, (F * V <= V)%VS & V_F =i V]}. Proof. pose V := (F * <<vbasis V_F : seq L>>)%VS. have idV: (F * V)%VS = V by rewrite prodvA prodv_id. suffices defVF: V_F = vspaceOver V. by exists V; split=> [||u]; rewrite ?defVF ?mem_vspaceOver ?idV. apply/vspaceP=> v; rewrite mem_vspaceOver idV. do [apply/idP/idP; last rewrite /V unlock] => [/coord_vbasis|/coord_span] ->. by apply: memv_suml => i _; rewrite memv_mul ?subvsP ?memv_span ?memt_nth. apply: memv_suml => i _; rewrite -tnth_nth; set xu := tnth _ i. have /allpairsP[[x u] /=]: xu \in _ := mem_tnth i _. case=> /vbasis_mem Fx /vbasis_mem Vu ->. rewrite scalerAl (coord_span Vu) mulr_sumr memv_suml // => j_. by rewrite -scalerCA (memvZ (Subvs _)) ?memvZ // vbasis_mem ?memt_nth. Qed. Lemma aspaceOverP (E_F : {subfield L_F}) : {E | [/\ E_F = aspaceOver E, (F <= E)%VS & E_F =i E]}. Proof. have [V [defEF modV memV]] := vspaceOverP E_F. have algE: has_algid V && (V * V <= V)%VS. rewrite has_algid1; last by rewrite -memV mem1v. by apply/prodvP=> u v; rewrite -!memV; apply: memvM. by exists (ASpace algE); rewrite -sup_field_module; split; first apply: val_inj. Qed. End FieldOver. (* Changing the reference field to a smaller field. *) Section BaseField. Variables (F0 : fieldType) (F : fieldExtType F0) (L : fieldExtType F). Definition baseFieldType : Type := L. Notation L0 := baseFieldType. HB.instance Definition _ := GRing.Field.on L0. Definition baseField_scale (a : F0) (u : L0) : L0 := in_alg F a *: u. Local Infix "*F0:" := baseField_scale (at level 40). Fact baseField_scaleA a b u : a *F0: (b *F0: u) = (a * b) *F0: u. Proof. by rewrite [_ *F0: _]scalerA -rmorphM. Qed. Fact baseField_scale1 u : 1 *F0: u = u. Proof. by rewrite /(1 *F0: u) rmorph1 scale1r. Qed. Fact baseField_scaleDr a u v : a *F0: (u + v) = a *F0: u + a *F0: v. Proof. exact: scalerDr. Qed. Fact baseField_scaleDl v a b : (a + b) *F0: v = a *F0: v + b *F0: v. Proof. by rewrite -scalerDl -rmorphD. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build _ L0 baseField_scaleA baseField_scale1 baseField_scaleDr baseField_scaleDl. Lemma baseField_scaleE a (u : L) : a *: (u : L0) = a%:A *: u. Proof. by []. Qed. Fact baseField_scaleAl a (u v : L0) : a *F0: (u * v) = (a *F0: u) * v. Proof. exact: scalerAl. Qed. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build _ L0 baseField_scaleAl. Fact baseField_scaleAr a u v : a *F0: (u * v) = u * (a *F0: v). Proof. exact: scalerAr. Qed. HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build _ L0 baseField_scaleAr. Let n := \dim {:F}. Let bF : n.-tuple F := vbasis {:F}. Let coordF (x : F) := (coord_vbasis (memvf x)). Fact baseField_vectMixin : Lmodule_hasFinDim F0 L0. Proof. pose bL := vbasis {:L}; set m := \dim {:L} in bL. pose v2r (x : L0) := mxvec (\matrix_(i, j) coord bF j (coord bL i x)). have v2r_lin: linear v2r. move=> a x y; rewrite -linearP; congr mxvec; apply/matrixP=> i j. by rewrite !mxE linearP /= mulr_algl linearP. pose r2v r := \sum_(i < m) (\sum_(j < n) vec_mx r i j *: bF`_j) *: bL`_i. have v2rK: cancel v2r r2v. move=> x; transitivity (\sum_(i < m) coord bL i x *: bL`_i); last first. by rewrite -coord_vbasis ?memvf. (* GG: rewrite {2}(coord_vbasis (memvf x)) -/m would take 8s; *) (* The -/m takes 8s, and without it then apply: eq_bigr takes 12s. *) (* The time drops to 2s with a -[GRing.Field.ringType F]/(F : fieldType) *) apply: eq_bigr => i _; rewrite mxvecK; congr (_ *: _ : L). by rewrite (coordF (coord bL i x)); apply: eq_bigr => j _; rewrite mxE. exists (m * n)%N, v2r => //; exists r2v => // r. apply: (canLR vec_mxK); apply/matrixP=> i j; rewrite mxE. by rewrite !coord_sum_free ?(basis_free (vbasisP _)). Qed. HB.instance Definition _ := baseField_vectMixin. Let F0ZEZ a x v : a *: ((x *: v : L) : L0) = (a *: x) *: v. Proof. by rewrite [a *: _]scalerA -scalerAl mul1r. Qed. Let baseVspace_basis V : seq L0 := [seq tnth bF ij.2 *: tnth (vbasis V) ij.1 | ij : 'I_(\dim V) * 'I_n]. Definition baseVspace V := <<baseVspace_basis V>>%VS. Lemma mem_baseVspace V : baseVspace V =i V. Proof. move=> y; apply/idP/idP=> [/coord_span->|/coord_vbasis->]; last first. apply: memv_suml => i _; rewrite (coordF (coord _ i (y : L))) scaler_suml -/n. apply: memv_suml => j _; rewrite -/bF -F0ZEZ memvZ ?memv_span // -!tnth_nth. by apply/imageP; exists (i, j). (* GG: the F0ZEZ lemma avoids serious performance issues here. *) apply: memv_suml => k _; rewrite nth_image; case: (enum_val k) => i j /=. by rewrite F0ZEZ memvZ ?vbasis_mem ?mem_tnth. Qed. Lemma dim_baseVspace V : \dim (baseVspace V) = (\dim V * n)%N. Proof. pose bV0 := baseVspace_basis V; set m := \dim V in bV0 *. suffices /size_basis->: basis_of (baseVspace V) bV0. by rewrite card_prod !card_ord. rewrite /basis_of eqxx. apply/freeP=> s sb0 k; rewrite -(enum_valK k); case/enum_val: k => i j. have free_baseP := freeP (basis_free (vbasisP _)). move: j; apply: (free_baseP _ _ fullv); move: i; apply: (free_baseP _ _ V). transitivity (\sum_i \sum_j s (enum_rank (i, j)) *: bV0`_(enum_rank (i, j))). apply: eq_bigr => i _; rewrite scaler_suml; apply: eq_bigr => j _. by rewrite -F0ZEZ nth_image enum_rankK -!tnth_nth. rewrite pair_bigA (reindex _ (onW_bij _ (enum_val_bij _))); apply: etrans sb0. by apply: eq_bigr => k _; rewrite -{5 6}[k](enum_valK k); case/enum_val: k. Qed. Fact baseAspace_suproof (E : {subfield L}) : is_aspace (baseVspace E). Proof. rewrite /is_aspace has_algid1; last by rewrite mem_baseVspace (mem1v E). by apply/prodvP=> u v; rewrite !mem_baseVspace; apply: memvM. Qed. Canonical baseAspace E := ASpace (baseAspace_suproof E). End BaseField. Arguments baseFieldType [F0 F]%_type L%_type. HB.lock Definition refBaseField (F0 : fieldType) (F : fieldExtType F0) (L : fieldExtType F) := baseAspace (1%AS : {aspace L}). Canonical refBaseField_unlockable := Unlockable refBaseField.unlock. Section RefBaseField. Variables (F0 : fieldType) (F : fieldExtType F0) (L : fieldExtType F). Notation F1 := (refBaseField L). Notation F1unlock := refBaseField.unlock. Notation L0 := (baseFieldType L). Let n := \dim {:F}. Let bF : n.-tuple F := vbasis {:F}. Let coordF (x : F) := (coord_vbasis (memvf x)). Lemma dim_refBaseField : \dim F1 = n. Proof. by rewrite F1unlock dim_baseVspace dimv1 mul1n. Qed. Lemma baseVspace_module V (V0 := baseVspace V) : (F1 * V0 <= V0)%VS. Proof. apply/prodvP=> u v; rewrite F1unlock !mem_baseVspace => /vlineP[x ->] Vv. by rewrite -(@scalerAl F L) mul1r; apply: memvZ. Qed. Lemma sub_baseField (E : {subfield L}) : (F1 <= baseVspace E)%VS. Proof. by rewrite -sup_field_module baseVspace_module. Qed. Lemma vspaceOver_refBase V : vspaceOver F1 (baseVspace V) =i V. Proof. move=> v; rewrite mem_vspaceOver field_module_eq ?baseVspace_module //. by rewrite mem_baseVspace. Qed. Lemma module_baseVspace M0 : (F1 * M0 <= M0)%VS -> {V | M0 = baseVspace V & M0 =i V}. Proof. move=> modM0; pose V := <<vbasis (vspaceOver F1 M0) : seq L>>%VS. suffices memM0: M0 =i V. by exists V => //; apply/vspaceP=> v; rewrite mem_baseVspace memM0. move=> v; rewrite -{1}(field_module_eq modM0) -(mem_vspaceOver M0) {}/V. move: (vspaceOver F1 M0) => M. apply/idP/idP=> [/coord_vbasis|/coord_span]->; apply/memv_suml=> i _. rewrite /(_ *: _) /= /fieldOver_scale; case: (coord _ i _) => /= x. rewrite {1}F1unlock mem_baseVspace => /vlineP[{}x ->]. by rewrite -(@scalerAl F L) mul1r memvZ ?memv_span ?memt_nth. move: (coord _ i _) => x; rewrite -[_`_i]mul1r scalerAl -tnth_nth. have F1x: x%:A \in F1. by rewrite F1unlock mem_baseVspace (@memvZ F L) // mem1v. by congr (_ \in M): (memvZ (Subvs F1x) (vbasis_mem (mem_tnth i _))). Qed. Lemma module_baseAspace (E0 : {subfield L0}) : (F1 <= E0)%VS -> {E | E0 = baseAspace E & E0 =i E}. Proof. rewrite -sup_field_module => /module_baseVspace[E defE0 memE0]. suffices algE: is_aspace E by exists (ASpace algE); first apply: val_inj. rewrite /is_aspace has_algid1 -?memE0 ?mem1v //. by apply/prodvP=> u v; rewrite -!memE0; apply: memvM. Qed. End RefBaseField. (* Base of fieldOver, finally. *) Section MoreFieldOver. Variables (F0 : fieldType) (L : fieldExtType F0) (F : {subfield L}). Lemma base_vspaceOver V : baseVspace (vspaceOver F V) =i (F * V)%VS. Proof. by move=> v; rewrite mem_baseVspace mem_vspaceOver. Qed. Lemma base_moduleOver V : (F * V <= V)%VS -> baseVspace (vspaceOver F V) =i V. Proof. by move=> /field_module_eq defV v; rewrite base_vspaceOver defV. Qed. Lemma base_aspaceOver (E : {subfield L}) : (F <= E)%VS -> baseVspace (vspaceOver F E) =i E. Proof. by rewrite -sup_field_module; apply: base_moduleOver. Qed. End MoreFieldOver. Section SubFieldExtension. Local Open Scope quotient_scope. Variables (F L : fieldType) (iota : {rmorphism F -> L}). Variables (z : L) (p : {poly F}). Local Notation "p ^iota" := (map_poly (GRing.RMorphism.sort iota) p) (format "p ^iota") : ring_scope. Let wf_p := (p != 0) && root p^iota z. Let p0 : {poly F} := if wf_p then (lead_coef p)^-1 *: p else 'X. Let z0 := if wf_p then z else 0. Let n := (size p0).-1. Let p0_mon : p0 \is monic. Proof. rewrite /p0; case: ifP => [/andP[nz_p _] | _]; last exact: monicX. by rewrite monicE lead_coefZ mulVf ?lead_coef_eq0. Qed. Let nz_p0 : p0 != 0. Proof. by rewrite monic_neq0 // p0_mon. Qed. Let p0z0 : root p0^iota z0. Proof. rewrite /p0 /z0; case: ifP => [/andP[_ pz0]|]; last by rewrite map_polyX rootX. by rewrite map_polyZ rootE hornerZ (rootP pz0) mulr0. Qed. Let n_gt0: 0 < n. Proof. rewrite /n -subn1 subn_gt0 -(size_map_poly iota). by rewrite (root_size_gt1 _ p0z0) ?map_poly_eq0. Qed. Let z0Ciota : commr_rmorph iota z0. Proof. by move=> x; apply: mulrC. Qed. Local Notation iotaPz := (horner_morph z0Ciota). Let iotaFz (x : 'rV[F]_n) := iotaPz (rVpoly x). Definition equiv_subfext x y := (iotaFz x == iotaFz y). Fact equiv_subfext_is_equiv : equiv_class_of equiv_subfext. Proof. by rewrite /equiv_subfext; split=> x // y w /eqP->. Qed. Canonical equiv_subfext_equiv := EquivRelPack equiv_subfext_is_equiv. Canonical equiv_subfext_encModRel := defaultEncModRel equiv_subfext. Definition subFExtend := {eq_quot equiv_subfext}. HB.instance Definition _ := Choice.on subFExtend. HB.instance Definition _ := Quotient.on subFExtend. HB.instance Definition _ : EqQuotient 'M[F]_(1, n) equiv_subfext subFExtend := EqQuotient.on subFExtend. Definition subfx_inj := lift_fun1 subFExtend iotaFz. Fact pi_subfx_inj : {mono \pi : x / iotaFz x >-> subfx_inj x}. Proof. unlock subfx_inj => x; apply/eqP; rewrite -/(equiv_subfext _ x). by rewrite -eqmodE reprK. Qed. Canonical pi_subfx_inj_morph := PiMono1 pi_subfx_inj. Let iotaPz_repr x : iotaPz (rVpoly (repr (\pi_(subFExtend) x))) = iotaFz x. Proof. by rewrite -/(iotaFz _) -!pi_subfx_inj reprK. Qed. Definition subfext0 := lift_cst subFExtend 0. Canonical subfext0_morph := PiConst subfext0. Definition subfext_add := lift_op2 subFExtend +%R. Fact pi_subfext_add : {morph \pi : x y / x + y >-> subfext_add x y}. Proof. unlock subfext_add => x y /=; apply/eqmodP/eqP. by rewrite /iotaFz !linearD /= !iotaPz_repr. Qed. Canonical pi_subfx_add_morph := PiMorph2 pi_subfext_add. Definition subfext_opp := lift_op1 subFExtend -%R. Fact pi_subfext_opp : {morph \pi : x / - x >-> subfext_opp x}. Proof. unlock subfext_opp => y /=; apply/eqmodP/eqP. by rewrite /iotaFz !linearN /= !iotaPz_repr. Qed. Canonical pi_subfext_opp_morph := PiMorph1 pi_subfext_opp. Fact addfxA : associative subfext_add. Proof. by move=> x y t; rewrite -[x]reprK -[y]reprK -[t]reprK !piE addrA. Qed. Fact addfxC : commutative subfext_add. Proof. by move=> x y; rewrite -[x]reprK -[y]reprK !piE addrC. Qed. Fact add0fx : left_id subfext0 subfext_add. Proof. by move=> x; rewrite -[x]reprK !piE add0r. Qed. Fact addfxN : left_inverse subfext0 subfext_opp subfext_add. Proof. by move=> x; rewrite -[x]reprK !piE addNr. Qed. HB.instance Definition _ := GRing.isZmodule.Build subFExtend addfxA addfxC add0fx addfxN. Let poly_rV_modp_K q : rVpoly (poly_rV (q %% p0) : 'rV[F]_n) = q %% p0. Proof. by apply: poly_rV_K; rewrite -ltnS -polySpred // ltn_modp. Qed. Let iotaPz_modp q : iotaPz (q %% p0) = iotaPz q. Proof. rewrite {2}(divp_eq q p0) rmorphD rmorphM /=. by rewrite [iotaPz p0](rootP p0z0) mulr0 add0r. Qed. Definition subfx_mul_rep (x y : 'rV[F]_n) : 'rV[F]_n := poly_rV ((rVpoly x) * (rVpoly y) %% p0). Definition subfext_mul := lift_op2 subFExtend subfx_mul_rep. Fact pi_subfext_mul : {morph \pi : x y / subfx_mul_rep x y >-> subfext_mul x y}. Proof. unlock subfext_mul => x y /=; apply/eqmodP/eqP. by rewrite /iotaFz !poly_rV_modp_K !iotaPz_modp !rmorphM /= !iotaPz_repr. Qed. Canonical pi_subfext_mul_morph := PiMorph2 pi_subfext_mul. Definition subfext1 := lift_cst subFExtend (poly_rV 1). Canonical subfext1_morph := PiConst subfext1. Fact mulfxA : associative (subfext_mul). Proof. elim/quotW=> x; elim/quotW=> y; elim/quotW=> w; rewrite !piE /subfx_mul_rep. by rewrite !poly_rV_modp_K [_ %% p0 * _]mulrC !modp_mul // mulrA mulrC. Qed. Fact mulfxC : commutative subfext_mul. Proof. by elim/quotW=> x; elim/quotW=> y; rewrite !piE /subfx_mul_rep /= mulrC. Qed. Fact mul1fx : left_id subfext1 subfext_mul. Proof. elim/quotW=> x; rewrite !piE /subfx_mul_rep poly_rV_K ?size_poly1 // mul1r. by rewrite modp_small ?rVpolyK // (polySpred nz_p0) ltnS size_poly. Qed. Fact mulfx_addl : left_distributive subfext_mul subfext_add. Proof. elim/quotW=> x; elim/quotW=> y; elim/quotW=> w. by rewrite !piE /subfx_mul_rep linearD /= mulrDl modpD linearD. Qed. Fact nonzero1fx : subfext1 != subfext0. Proof. rewrite !piE /equiv_subfext /iotaFz !linear0. by rewrite poly_rV_K ?rmorph1 ?oner_eq0 // size_poly1. Qed. HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build subFExtend mulfxA mulfxC mul1fx mulfx_addl nonzero1fx. Definition subfx_poly_inv (q : {poly F}) : {poly F} := if iotaPz q == 0 then 0 else let r := gdcop q p0 in let: (u, v) := egcdp q r in ((u * q + v * r)`_0)^-1 *: u. Let subfx_poly_invE q : iotaPz (subfx_poly_inv q) = (iotaPz q)^-1. Proof. rewrite /subfx_poly_inv. have [-> | nzq] := eqVneq; first by rewrite rmorph0 invr0. rewrite [nth]lock -[_^-1]mul1r; apply: canRL (mulfK nzq) _; rewrite -rmorphM /=. have rz0: iotaPz (gdcop q p0) = 0. by apply/rootP; rewrite gdcop_map root_gdco ?map_poly_eq0 // p0z0 nzq. do [case: gdcopP => r _; rewrite (negPf nz_p0) orbF => co_r_q _] in rz0 *. case: (egcdp q r) (egcdpE q r) => u v /=/eqp_size/esym/eqP. rewrite coprimep_size_gcd 1?coprimep_sym // => /size_poly1P[a nz_a Da]. rewrite Da -scalerAl (canRL (addrK _) Da) -lock coefC linearZ linearB /=. by rewrite rmorphM /= rz0 mulr0 subr0 horner_morphC -rmorphM mulVf ?rmorph1. Qed. Definition subfx_inv_rep (x : 'rV[F]_n) : 'rV[F]_n := poly_rV (subfx_poly_inv (rVpoly x) %% p0). Definition subfext_inv := lift_op1 subFExtend subfx_inv_rep. Fact pi_subfext_inv : {morph \pi : x / subfx_inv_rep x >-> subfext_inv x}. Proof. unlock subfext_inv => x /=; apply/eqmodP/eqP; rewrite /iotaFz. by rewrite 2!{1}poly_rV_modp_K 2!{1}iotaPz_modp !subfx_poly_invE iotaPz_repr. Qed. Canonical pi_subfext_inv_morph := PiMorph1 pi_subfext_inv. Fact subfx_fieldAxiom : forall x, x != 0 -> subfext_inv x * x = 1. Proof. elim/quotW=> x; apply: contraNeq; rewrite !piE /equiv_subfext /iotaFz !linear0. apply: contraR => nz_x; rewrite poly_rV_K ?size_poly1 // !poly_rV_modp_K. by rewrite iotaPz_modp rmorph1 rmorphM /= iotaPz_modp subfx_poly_invE mulVf. Qed. Fact subfx_inv0 : subfext_inv (0 : subFExtend) = (0 : subFExtend). Proof. apply/eqP; rewrite !piE /equiv_subfext /iotaFz /subfx_inv_rep !linear0. by rewrite /subfx_poly_inv rmorph0 eqxx mod0p !linear0. Qed. HB.instance Definition _ := GRing.ComNzRing_isField.Build subFExtend subfx_fieldAxiom subfx_inv0. Fact subfx_inj_is_zmod_morphism : zmod_morphism subfx_inj. Proof. by elim/quotW => x; elim/quotW => y; rewrite !piE /iotaFz linearB rmorphB. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `subfx_inj_is_zmod_morphism` instead")] Definition subfx_inj_is_additive := subfx_inj_is_zmod_morphism. Fact subfx_inj_is_monoid_morphism : monoid_morphism subfx_inj. Proof. split; first by rewrite piE /iotaFz poly_rV_K ?rmorph1 ?size_poly1. elim/quotW=> x; elim/quotW=> y; rewrite !piE /subfx_mul_rep /iotaFz. by rewrite poly_rV_modp_K iotaPz_modp rmorphM. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `subfx_inj_is_monoid_morphism` instead")] Definition subfx_inj_is_multiplicative := (fun g => (g.2,g.1)) subfx_inj_is_monoid_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build subFExtend L subfx_inj subfx_inj_is_zmod_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build subFExtend L subfx_inj subfx_inj_is_monoid_morphism. Definition subfx_eval := lift_embed subFExtend (fun q => poly_rV (q %% p0)). Canonical subfx_eval_morph := PiEmbed subfx_eval. Definition subfx_root := subfx_eval 'X. Lemma subfx_eval_is_zmod_morphism : zmod_morphism subfx_eval. Proof. by move=> x y; apply/eqP; rewrite piE -linearB modpD modNp. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `subfx_eval_is_zmod_morphism` instead")] Definition subfx_eval_is_additive := subfx_eval_is_zmod_morphism. Lemma subfx_eval_is_monoid_morphism : monoid_morphism subfx_eval. Proof. split=> [|x y]; apply/eqP; rewrite piE. by rewrite modp_small // size_poly1 -subn_gt0 subn1. by rewrite /subfx_mul_rep !poly_rV_modp_K !(modp_mul, mulrC _ y). Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `subfx_eval_is_monoid_morphism` instead")] Definition subfx_eval_is_multiplicative := (fun g => (g.2,g.1)) subfx_eval_is_monoid_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build {poly F} subFExtend subfx_eval subfx_eval_is_zmod_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly F} subFExtend subfx_eval subfx_eval_is_monoid_morphism. Definition inj_subfx := (subfx_eval \o polyC). HB.instance Definition _ := GRing.RMorphism.on inj_subfx. Lemma subfxE x: exists p, x = subfx_eval p. Proof. elim/quotW: x => x; exists (rVpoly x); apply/eqP; rewrite piE /equiv_subfext. by rewrite /iotaFz poly_rV_modp_K iotaPz_modp. Qed. Definition subfx_scale a x := inj_subfx a * x. Fact subfx_scalerA a b x : subfx_scale a (subfx_scale b x) = subfx_scale (a * b) x. Proof. by rewrite /subfx_scale rmorphM mulrA. Qed. Fact subfx_scaler1r : left_id 1 subfx_scale. Proof. by move=> x; rewrite /subfx_scale rmorph1 mul1r. Qed. Fact subfx_scalerDr : right_distributive subfx_scale +%R. Proof. by move=> a; apply: mulrDr. Qed. Fact subfx_scalerDl x : {morph subfx_scale^~ x : a b / a + b}. Proof. by move=> a b; rewrite /subfx_scale rmorphD mulrDl. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build _ subFExtend subfx_scalerA subfx_scaler1r subfx_scalerDr subfx_scalerDl. Fact subfx_scaleAl a u v : subfx_scale a (u * v) = (subfx_scale a u) * v. Proof. exact: mulrA. Qed. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build _ subFExtend subfx_scaleAl. Fact subfx_scaleAr a u v : subfx_scale a (u * v) = u * (subfx_scale a v). Proof. exact: mulrCA. Qed. HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build _ subFExtend subfx_scaleAr. Fact subfx_evalZ : scalable subfx_eval. Proof. by move=> a q; rewrite -mul_polyC rmorphM. Qed. HB.instance Definition _ := GRing.isScalable.Build F {poly F} subFExtend *:%R subfx_eval subfx_evalZ. Hypothesis (pz0 : root p^iota z). Section NonZero. Hypothesis nz_p : p != 0. Lemma subfx_inj_eval q : subfx_inj (subfx_eval q) = (q^iota).[z]. Proof. by rewrite piE /iotaFz poly_rV_modp_K iotaPz_modp /iotaPz /z0 /wf_p nz_p pz0. Qed. Lemma subfx_inj_root : subfx_inj subfx_root = z. Proof. by rewrite subfx_inj_eval // map_polyX hornerX. Qed. Lemma subfx_injZ b x : subfx_inj (b *: x) = iota b * subfx_inj x. Proof. by rewrite rmorphM /= subfx_inj_eval // map_polyC hornerC. Qed. Lemma subfx_inj_base b : subfx_inj b%:A = iota b. Proof. by rewrite subfx_injZ rmorph1 mulr1. Qed. Lemma subfxEroot x : {q | x = (map_poly (in_alg subFExtend) q).[subfx_root]}. Proof. have /sig_eqW[q ->] := subfxE x; exists q. apply: (fmorph_inj subfx_inj). rewrite -horner_map /= subfx_inj_root subfx_inj_eval //. by rewrite -map_poly_comp (eq_map_poly subfx_inj_base). Qed. Lemma subfx_irreducibleP : (forall q, root q^iota z -> q != 0 -> size p <= size q) <-> irreducible_poly p. Proof. split=> [min_p | irr_p q qz0 nz_q]. split=> [|q nonC_q q_dv_p]. by rewrite -(size_map_poly iota) (root_size_gt1 _ pz0) ?map_poly_eq0. have /dvdpP[r Dp] := q_dv_p; rewrite -dvdp_size_eqp // eqn_leq dvdp_leq //=. have [nz_r nz_q]: r != 0 /\ q != 0 by apply/norP; rewrite -mulf_eq0 -Dp. have: root r^iota z || root q^iota z by rewrite -rootM -rmorphM -Dp. case/orP=> /min_p; [case/(_ _)/idPn=> // | exact]. rewrite polySpred // -leqNgt Dp size_mul //= polySpred // -subn2 ltn_subRL. by rewrite addSnnS addnC ltn_add2l ltn_neqAle eq_sym nonC_q size_poly_gt0. pose r := gcdp p q; have nz_r: r != 0 by rewrite gcdp_eq0 (negPf nz_p). suffices /eqp_size <-: r %= p by rewrite dvdp_leq ?dvdp_gcdr. rewrite (irr_p _) ?dvdp_gcdl // -(size_map_poly iota) gtn_eqF //. by rewrite (@root_size_gt1 _ z) ?map_poly_eq0 // gcdp_map root_gcd pz0. Qed. End NonZero. Section Irreducible. Hypothesis irr_p : irreducible_poly p. Let nz_p : p != 0. Proof. exact: irredp_neq0. Qed. (* The Vector axiom requires irreducibility. *) Lemma min_subfx_vect : Vector.axiom (size p).-1 subFExtend. Proof. move/subfx_irreducibleP: irr_p => /=/(_ nz_p) min_p; set d := (size p).-1. have Dd: d.+1 = size p by rewrite polySpred. pose Fz2v x : 'rV_d := poly_rV (sval (sig_eqW (subfxE x)) %% p). pose vFz : 'rV_d -> subFExtend := subfx_eval \o rVpoly. have FLinj: injective subfx_inj by apply: fmorph_inj. have Fz2vK: cancel Fz2v vFz. move=> x; rewrite /vFz /Fz2v; case: (sig_eqW _) => /= q ->. apply: FLinj; rewrite !subfx_inj_eval // {2}(divp_eq q p) rmorphD rmorphM /=. by rewrite !hornerE (eqP pz0) mulr0 add0r poly_rV_K // -ltnS Dd ltn_modpN0. suffices vFzK: cancel vFz Fz2v. by exists Fz2v; [apply: can2_linear Fz2vK | exists vFz]. apply: inj_can_sym Fz2vK _ => v1 v2 /(congr1 subfx_inj)/eqP. rewrite -subr_eq0 -!raddfB /= subfx_inj_eval // => /min_p/implyP. rewrite leqNgt implybNN -Dd ltnS size_poly linearB subr_eq0 /=. by move/eqP/(can_inj rVpolyK). Qed. Definition SubfxVect := Lmodule_hasFinDim.Build _ subFExtend min_subfx_vect. Definition SubFieldExtType : fieldExtType F := HB.pack subFExtend SubfxVect. End Irreducible. End SubFieldExtension. Prenex Implicits subfx_inj. Lemma irredp_FAdjoin (F : fieldType) (p : {poly F}) : irreducible_poly p -> {L : fieldExtType F & \dim {:L} = (size p).-1 & {z | root (map_poly (in_alg L) p) z & <<1; z>>%VS = fullv}}. Proof. case=> p_gt1 irr_p; set n := (size p).-1; pose vL : vectType F := 'rV_n. have Dn: n.+1 = size p := ltn_predK p_gt1. have nz_p: p != 0 by rewrite -size_poly_eq0 -Dn. suffices [L dimL [toPF [toL toPF_K toL_K]]]: {L : fieldExtType F & \dim {:L} = (size p).-1 & {toPF : {linear L -> {poly F}} & {toL : {lrmorphism {poly F} -> L} | cancel toPF toL & forall q, toPF (toL q) = q %% p}}}. - exists L => //; pose z := toL 'X; set iota := in_alg _. suffices q_z q: toPF (map_poly iota q).[z] = q %% p. exists z; first by rewrite /root -(can_eq toPF_K) q_z modpp linear0. apply/vspaceP=> x; rewrite memvf; apply/Fadjoin_polyP. exists (map_poly iota (toPF x)). by apply/polyOverP=> i; rewrite coef_map memvZ ?mem1v. by apply: (can_inj toPF_K); rewrite q_z -toL_K toPF_K. elim/poly_ind: q => [|a q IHq]. by rewrite map_poly0 horner0 linear0 mod0p. rewrite rmorphD rmorphM /= map_polyX map_polyC hornerMXaddC linearD /=. rewrite linearZ /= -(rmorph1 toL) toL_K -modpZl alg_polyC modpD. congr (_ + _); rewrite -toL_K rmorphM -/z; congr (toPF (_ * z)). by apply: (can_inj toPF_K); rewrite toL_K. pose toL q : vL := poly_rV (q %% p); pose toPF (x : vL) := rVpoly x. have toL_K q : toPF (toL q) = q %% p. by rewrite /toPF poly_rV_K // -ltnS Dn ?ltn_modp -?Dn. have toPF_K: cancel toPF toL. by move=> x; rewrite /toL modp_small ?rVpolyK // -Dn ltnS size_poly. have toPinj := can_inj toPF_K. pose mul x y := toL (toPF x * toPF y); pose L1 := toL 1. have L1K: toPF L1 = 1 by rewrite toL_K modp_small ?size_poly1. have mulC: commutative mul by rewrite /mul => x y; rewrite mulrC. have mulA: associative mul. by move=> x y z; apply: toPinj; rewrite -!(mulC z) !toL_K !modp_mul mulrCA. have mul1: left_id L1 mul. by move=> x; apply: toPinj; rewrite mulC !toL_K modp_mul mulr1 -toL_K toPF_K. have mulD: left_distributive mul +%R. move=> x y z; apply: toPinj; rewrite /toPF raddfD /= -!/(toPF _). by rewrite !toL_K /toPF raddfD mulrDl modpD. have nzL1: L1 != 0 by rewrite -(inj_eq toPinj) L1K /toPF raddf0 oner_eq0. pose mulM := GRing.Zmodule_isComNzRing.Build _ mulA mulC mul1 mulD nzL1. pose rL : comNzRingType := HB.pack vL mulM. have mulZlM : GRing.Lmodule_isLalgebra F rL. constructor => a x y; apply: toPinj. by rewrite toL_K /toPF !linearZ /= -!/(toPF _) toL_K -scalerAl modpZl. pose laL : lalgType F := HB.pack rL mulZlM. have mulZrM : GRing.Lalgebra_isAlgebra F laL. by constructor => a x y; rewrite !(mulrC x) scalerAl. pose aL : algType F := HB.pack laL mulZrM. pose uLM := Algebra_isFalgebra.Build F aL. pose cuL : comUnitRingType := HB.pack aL uLM. have unitM : GRing.ComUnitRing_isField cuL. constructor => x nz_x; apply/unitrP; set q := toPF x. have nz_q: q != 0 by rewrite -(inj_eq toPinj) /toPF raddf0 in nz_x. have /Bezout_eq1_coprimepP[u upq1]: coprimep p q. apply: contraLR (leq_gcdpr p nz_q) => /irr_p/implyP. rewrite dvdp_gcdl -ltnNge /= => /eqp_size->. by rewrite (polySpred nz_p) ltnS size_poly. suffices: x * toL u.2 = 1 by exists (toL u.2); rewrite mulrC. apply: toPinj; rewrite !toL_K -upq1 modp_mul modpD mulrC. by rewrite modp_mull add0r. pose feL : fieldExtType F := HB.pack vL aL cuL unitM. exists feL; first by rewrite dimvf; apply: mul1n. exists toPF. have tol_lin: linear toL by move=> a q1 q2; rewrite -linearP -modpZl -modpD. have tol_mul : monoid_morphism (toL : {poly F} -> aL). by split=> [|q r]; apply: toPinj; rewrite !toL_K // modp_mul -!(mulrC r) modp_mul. pose toLlM := GRing.isLinear.Build _ _ _ _ toL tol_lin. pose toLmM := GRing.isMonoidMorphism.Build _ _ _ tol_mul. pose toLLRM : {lrmorphism _ -> feL} := HB.pack toL toLlM toLmM. by exists toLLRM. Qed. (*Coq 8.3 processes this shorter proof correctly, but then crashes on Qed. In Coq 8.4 Qed takes about 18s. In Coq 8.7, everything seems to be all right *) (* Lemma Xirredp_FAdjoin' (F : fieldType) (p : {poly F}) : *) (* irreducible_poly p -> *) (* {L : fieldExtType F & \dim {: L} = (size p).-1 & *) (* {z | root (map_poly (in_alg L) p) z & <<1; z>>%VS = fullv}}. *) (* Proof. *) (* case=> p_gt1 irr_p; set n := (size p).-1; pose vL := [vectType F of 'rV_n]. *) (* have Dn: n.+1 = size p := ltn_predK p_gt1. *) (* have nz_p: p != 0 by rewrite -size_poly_eq0 -Dn. *) (* pose toL q : vL := poly_rV (q %% p). *) (* have toL_K q : rVpoly (toL q) = q %% p. *) (* by rewrite poly_rV_K // -ltnS Dn ?ltn_modp -?Dn. *) (* pose mul (x y : vL) : vL := toL (rVpoly x * rVpoly y). *) (* pose L1 : vL := poly_rV 1. *) (* have L1K: rVpoly L1 = 1 by rewrite poly_rV_K // size_poly1 -ltnS Dn. *) (* have mulC: commutative mul by rewrite /mul => x y; rewrite mulrC. *) (* have mulA: associative mul. *) (* by move=> x y z; rewrite -!(mulC z) /mul !toL_K /toL !modp_mul mulrCA. *) (* have mul1: left_id L1 mul. *) (* move=> x; rewrite /mul L1K mul1r /toL modp_small ?rVpolyK // -Dn ltnS. *) (* by rewrite size_poly. *) (* have mulD: left_distributive mul +%R. *) (* move=> x y z; apply: canLR rVpolyK _. *) (* by rewrite !raddfD mulrDl /= !toL_K /toL modpD. *) (* have nzL1: L1 != 0 by rewrite -(can_eq rVpolyK) L1K raddf0 oner_eq0. *) (* pose mulM := GRing.Zmodule_isComNzRing.Build vL mulA mulC mul1 mulD nzL1. *) (* pose rL := ComNzRingType vL mulM. *) (* have mulZlM : GRing.Lmodule_isLalgebra F rL. *) (* constructor => a x y; apply: canRL rVpolyK _. *) (* by rewrite !linearZ /= toL_K -scalerAl modpZl. *) (* pose laL := LalgType F rL mulZlM. *) (* have mulZrM : GRing.Lalgebra_isAlgebra F laL. *) (* by constructor => a x y; rewrite !(mulrC x) scalerAl. *) (* pose aL := AlgType F laL mulZrM. *) (* pose uLM := Algebra_isFalgebra.Build F aL. *) (* pose cuL := ComUnitRingType uLM _. *) (* have unitM : GRing.ComUnitRing_isField cuL. *) (* constructor => x nz_x; apply/unitrP; set q := rVpoly x. *) (* have nz_q: q != 0 by rewrite -(can_eq rVpolyK) raddf0 in nz_x. *) (* have /Bezout_eq1_coprimepP[u upq1]: coprimep p q. *) (* have /contraR := irr_p _ _ (dvdp_gcdl p q); apply. *) (* have: size (gcdp p q) <= size q by apply: leq_gcdpr. *) (* rewrite leqNgt; apply: contra; move/eqp_size ->. *) (* by rewrite (polySpred nz_p) ltnS size_poly. *) (* suffices: x * toL u.2 = 1 by exists (toL u.2); rewrite mulrC. *) (* congr (poly_rV _); rewrite toL_K modp_mul mulrC (canRL (addKr _) upq1). *) (* by rewrite -mulNr modp_addl_mul_small ?size_poly1. *) (* pose feL := FieldExtType _ unitM _. *) (* exists feL; first by rewrite dimvf; apply: mul1n. *) (* pose z : vL := toL 'X; set iota := in_alg _. *) (* have q_z q: rVpoly (map_poly iota q).[z] = q %% p. *) (* elim/poly_ind: q => [|a q IHq]. *) (* by rewrite map_poly0 horner0 linear0 mod0p. *) (* rewrite rmorphD rmorphM /= map_polyX map_polyC hornerMXaddC linearD /=. *) (* rewrite linearZ /= L1K alg_polyC modpD; congr (_ + _); last first. *) (* by rewrite modp_small // size_polyC; case: (~~ _) => //; apply: ltnW. *) (* by rewrite !toL_K IHq mulrC modp_mul mulrC modp_mul. *) (* exists z; first by rewrite /root -(can_eq rVpolyK) q_z modpp linear0. *) (* apply/vspaceP=> x; rewrite memvf; apply/Fadjoin_polyP. *) (* exists (map_poly iota (rVpoly x)). *) (* by apply/polyOverP=> i; rewrite coef_map memvZ ?mem1v. *) (* by apply/(can_inj rVpolyK); rewrite q_z modp_small // -Dn ltnS size_poly. *) (* Qed. *)
ApproximateUnit.lean
/- Copyright (c) 2024 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.CStarAlgebra.ContinuousFunctionalCalculus.Order import Mathlib.Analysis.CStarAlgebra.SpecialFunctions.PosPart import Mathlib.Analysis.SpecialFunctions.ContinuousFunctionalCalculus.Rpow.Basic import Mathlib.Topology.ApproximateUnit /-! # Nonnegative contractions in a C⋆-algebra form an approximate unit This file shows that the collection of positive contractions (of norm strictly less than one) in a possibly non-unital C⋆-algebra form a directed set. The key step uses the continuous functional calculus applied with the functions `fun x : ℝ≥0, 1 - (1 + x)⁻¹` and `fun x : ℝ≥0, x * (1 - x)⁻¹`, which are inverses on the interval `{x : ℝ≥0 | x < 1}`. In addition, this file defines `IsIncreasingApproximateUnit` to be a filter `l` that is an approximate unit contained in the closed unit ball of nonnegative elements. Every C⋆-algebra has a filter generated by the sections `{x | a ≤ x} ∩ closedBall 0 1` for `0 ≤ a` and `‖a‖ < 1`, and moreover, this filter is an increasing approximate unit. ## Main declarations + `CFC.monotoneOn_one_sub_one_add_inv`: the function `f := fun x : ℝ≥0, 1 - (1 + x)⁻¹` is *operator monotone* on `Set.Ici (0 : A)` (i.e., `cfcₙ f` is monotone on `{x : A | 0 ≤ x}`). + `Set.InvOn.one_sub_one_add_inv`: the functions `f := fun x : ℝ≥0, 1 - (1 + x)⁻¹` and `g := fun x : ℝ≥0, x * (1 - x)⁻¹` are inverses on `{x : ℝ≥0 | x < 1}`. + `CStarAlgebra.directedOn_nonneg_ball`: the set `{x : A | 0 ≤ x} ∩ Metric.ball 0 1` is directed. + `Filter.IsIncreasingApproximateUnit`: a filter `l` is an *increasing approximate unit* if it is an approximate unit contained in the closed unit ball of nonnegative elements. + `CStarAlgebra.approximateUnit`: the filter generated by the sections `{x | a ≤ x} ∩ closedBall 0 1` for `0 ≤ a` with `‖a‖ < 1`. + `CStarAlgebra.increasingApproximateUnit`: the filter `CStarAlgebra.approximateUnit` is an increasing approximate unit. -/ variable {A : Type*} [NonUnitalCStarAlgebra A] local notation "σₙ" => quasispectrum local notation "σ" => spectrum open Unitization NNReal CStarAlgebra variable [PartialOrder A] [StarOrderedRing A] lemma CFC.monotoneOn_one_sub_one_add_inv : MonotoneOn (cfcₙ (fun x : ℝ≥0 ↦ 1 - (1 + x)⁻¹)) (Set.Ici (0 : A)) := by intro a ha b hb hab simp only [Set.mem_Ici] at ha hb rw [← inr_le_iff .., nnreal_cfcₙ_eq_cfc_inr a _, nnreal_cfcₙ_eq_cfc_inr b _] rw [← inr_le_iff a b (.of_nonneg ha) (.of_nonneg hb)] at hab rw [← inr_nonneg_iff] at ha hb have h_cfc_one_sub (c : A⁺¹) (hc : 0 ≤ c := by cfc_tac) : cfc (fun x : ℝ≥0 ↦ 1 - (1 + x)⁻¹) c = 1 - cfc (·⁻¹ : ℝ≥0 → ℝ≥0) (1 + c) := by rw [cfc_tsub _ _ _ (fun x _ ↦ by simp) (hg := by fun_prop (disch := intro _ _; positivity)), cfc_const_one ℝ≥0 c, cfc_comp' (·⁻¹) (1 + ·) c ?_, cfc_add .., cfc_const_one ℝ≥0 c, cfc_id' ℝ≥0 c] exact continuousOn_id.inv₀ (Set.forall_mem_image.mpr fun x _ ↦ by dsimp only [id]; positivity) rw [h_cfc_one_sub (a : A⁺¹), h_cfc_one_sub (b : A⁺¹)] gcongr rw [← CFC.rpow_neg_one_eq_cfc_inv, ← CFC.rpow_neg_one_eq_cfc_inv] exact rpow_neg_one_le_rpow_neg_one (add_nonneg zero_le_one ha) (by gcongr) <| isUnit_of_le isUnit_one zero_le_one <| le_add_of_nonneg_right ha lemma Set.InvOn.one_sub_one_add_inv : Set.InvOn (fun x ↦ 1 - (1 + x)⁻¹) (fun x ↦ x * (1 - x)⁻¹) {x : ℝ≥0 | x < 1} {x : ℝ≥0 | x < 1} := by have : (fun x : ℝ≥0 ↦ x * (1 + x)⁻¹) = fun x ↦ 1 - (1 + x)⁻¹ := by ext x : 1 field_simp simp [tsub_mul, inv_mul_cancel₀] rw [← this] constructor <;> intro x (hx : x < 1) · have : 0 < 1 - x := tsub_pos_of_lt hx field_simp [tsub_add_cancel_of_le hx.le, tsub_tsub_cancel_of_le hx.le] · field_simp [mul_tsub] lemma norm_cfcₙ_one_sub_one_add_inv_lt_one (a : A) : ‖cfcₙ (fun x : ℝ≥0 ↦ 1 - (1 + x)⁻¹) a‖ < 1 := nnnorm_cfcₙ_nnreal_lt fun x _ ↦ tsub_lt_self zero_lt_one (by positivity) -- the calls to `fun_prop` with a discharger set off the linter set_option linter.style.multiGoal false in lemma CStarAlgebra.directedOn_nonneg_ball : DirectedOn (· ≤ ·) ({x : A | 0 ≤ x} ∩ Metric.ball 0 1) := by let f : ℝ≥0 → ℝ≥0 := fun x => 1 - (1 + x)⁻¹ let g : ℝ≥0 → ℝ≥0 := fun x => x * (1 - x)⁻¹ suffices ∀ a b : A, 0 ≤ a → 0 ≤ b → ‖a‖ < 1 → ‖b‖ < 1 → a ≤ cfcₙ f (cfcₙ g a + cfcₙ g b) by rintro a ⟨(ha₁ : 0 ≤ a), ha₂⟩ b ⟨(hb₁ : 0 ≤ b), hb₂⟩ simp only [Metric.mem_ball, dist_zero_right] at ha₂ hb₂ refine ⟨cfcₙ f (cfcₙ g a + cfcₙ g b), ⟨by simp, ?_⟩, ?_, ?_⟩ · simpa only [Metric.mem_ball, dist_zero_right] using norm_cfcₙ_one_sub_one_add_inv_lt_one _ · exact this a b ha₁ hb₁ ha₂ hb₂ · exact add_comm (cfcₙ g a) (cfcₙ g b) ▸ this b a hb₁ ha₁ hb₂ ha₂ rintro a b ha₁ - ha₂ - calc a = cfcₙ (f ∘ g) a := by conv_lhs => rw [← cfcₙ_id ℝ≥0 a] refine cfcₙ_congr (Set.InvOn.one_sub_one_add_inv.1.eqOn.symm.mono fun x hx ↦ ?_) exact lt_of_le_of_lt (le_nnnorm_of_mem_quasispectrum hx) ha₂ _ = cfcₙ f (cfcₙ g a) := by rw [cfcₙ_comp f g a ?_ (by simp [f, tsub_self]) ?_ (by simp [g]) ha₁] · fun_prop (disch := intro _ _; positivity) · have (x) (hx : x ∈ σₙ ℝ≥0 a) : 1 - x ≠ 0 := by refine tsub_pos_of_lt ?_ |>.ne' exact lt_of_le_of_lt (le_nnnorm_of_mem_quasispectrum hx) ha₂ fun_prop (disch := assumption) _ ≤ cfcₙ f (cfcₙ g a + cfcₙ g b) := by have hab' : cfcₙ g a ≤ cfcₙ g a + cfcₙ g b := le_add_of_nonneg_right cfcₙ_nonneg_of_predicate exact CFC.monotoneOn_one_sub_one_add_inv cfcₙ_nonneg_of_predicate (cfcₙ_nonneg_of_predicate.trans hab') hab' section ApproximateUnit open Metric Filter Topology /-- An *increasing approximate unit* in a C⋆-algebra is an approximate unit contained in the closed unit ball of nonnegative elements. -/ structure Filter.IsIncreasingApproximateUnit (l : Filter A) : Prop extends l.IsApproximateUnit where eventually_nonneg : ∀ᶠ x in l, 0 ≤ x eventually_norm : ∀ᶠ x in l, ‖x‖ ≤ 1 namespace Filter.IsIncreasingApproximateUnit omit [StarOrderedRing A] in lemma eventually_nnnorm {l : Filter A} (hl : l.IsIncreasingApproximateUnit) : ∀ᶠ x in l, ‖x‖₊ ≤ 1 := hl.eventually_norm lemma eventually_isSelfAdjoint {l : Filter A} (hl : l.IsIncreasingApproximateUnit) : ∀ᶠ x in l, IsSelfAdjoint x := hl.eventually_nonneg.mp <| .of_forall fun _ ↦ IsSelfAdjoint.of_nonneg lemma eventually_star_eq {l : Filter A} (hl : l.IsIncreasingApproximateUnit) : ∀ᶠ x in l, star x = x := hl.eventually_isSelfAdjoint.mp <| .of_forall fun _ ↦ IsSelfAdjoint.star_eq end Filter.IsIncreasingApproximateUnit namespace CStarAlgebra open Submodule in /-- To show that `l` is a one-sided approximate unit for `A`, it suffices to verify it only for `m : A` with `0 ≤ m` and `‖m‖ < 1`. -/ lemma tendsto_mul_right_of_forall_nonneg_tendsto {l : Filter A} (h : ∀ m, 0 ≤ m → ‖m‖ < 1 → Tendsto (· * m) l (𝓝 m)) (m : A) : Tendsto (· * m) l (𝓝 m) := by obtain ⟨n, c, x, rfl⟩ := mem_span_set'.mp <| by change m ∈ span ℂ ({x | 0 ≤ x} ∩ ball 0 1) simp [span_nonneg_inter_unitBall] simp_rw [Finset.mul_sum] refine tendsto_finset_sum _ fun i _ ↦ ?_ simp_rw [mul_smul_comm] exact tendsto_const_nhds.smul <| h (x i) (x i).2.1 <| by simpa using (x i).2.2 omit [PartialOrder A] in /-- Multiplication on the left by `m` tends to `𝓝 m` if and only if multiplication on the right does, provided the elements are eventually selfadjoint along the filter `l`. -/ lemma tendsto_mul_left_iff_tendsto_mul_right {l : Filter A} (hl : ∀ᶠ x in l, IsSelfAdjoint x) : (∀ m, Tendsto (m * ·) l (𝓝 m)) ↔ (∀ m, Tendsto (· * m) l (𝓝 m)) := by refine ⟨fun h m ↦ ?_, fun h m ↦ ?_⟩ all_goals apply (star_star m ▸ (continuous_star.tendsto _ |>.comp <| h (star m))).congr' filter_upwards [hl] with x hx simp [hx.star_eq] variable (A) /-- The sections of positive strict contractions form a filter basis. -/ lemma isBasis_nonneg_sections : IsBasis (fun x : A ↦ 0 ≤ x ∧ ‖x‖ < 1) ({x | · ≤ x}) where nonempty := ⟨0, by simp⟩ inter {x y} hx hy := by peel directedOn_nonneg_ball x (by simpa) y (by simpa) with z hz exact ⟨by simpa using hz.1, fun a ha ↦ ⟨hz.2.1.trans ha, hz.2.2.trans ha⟩⟩ /-- The canonical approximate unit in a C⋆-algebra generated by the basis of sets `{x | a ≤ x} ∩ closedBall 0 1` for `0 ≤ a`. See also `CStarAlgebra.hasBasis_approximateUnit`. -/ def approximateUnit : Filter A := (isBasis_nonneg_sections A).filter ⊓ 𝓟 (closedBall 0 1) /-- The canonical approximate unit in a C⋆-algebra has a basis of sets `{x | a ≤ x} ∩ closedBall 0 1` for `0 ≤ a`. -/ lemma hasBasis_approximateUnit : (approximateUnit A).HasBasis (fun x : A ↦ 0 ≤ x ∧ ‖x‖ < 1) ({x | · ≤ x} ∩ closedBall 0 1) := isBasis_nonneg_sections A |>.hasBasis.inf_principal (closedBall 0 1) /-- This is a common reasoning sequence in C⋆-algebra theory. If `0 ≤ x ≤ y ≤ 1`, then the norm of `z - y * z` is controlled by the norm of `star z * (1 - x) * z`, which is advantageous because the latter is nonnegative. This is a key step in establishing the existence of an increasing approximate unit in general C⋆-algebras. -/ lemma nnnorm_sub_mul_self_le {A : Type*} [CStarAlgebra A] [PartialOrder A] [StarOrderedRing A] {x y : A} (z : A) (hx₀ : 0 ≤ x) (hy : y ∈ Set.Icc x 1) {c : ℝ≥0} (h : ‖star z * (1 - x) * z‖₊ ≤ c ^ 2) : ‖z - y * z‖₊ ≤ c := by nth_rw 1 [← one_mul z] rw [← sqrt_sq c, le_sqrt_iff_sq_le, ← sub_mul, sq, ← CStarRing.nnnorm_star_mul_self] simp only [star_mul, star_sub, star_one] have hy₀ : y ∈ Set.Icc 0 1 := ⟨hx₀.trans hy.1, hy.2⟩ have hy' : 1 - y ∈ Set.Icc 0 1 := Set.sub_mem_Icc_zero_iff_right.mpr hy₀ rw [hy₀.1.star_eq, ← mul_assoc, mul_assoc (star _), ← sq] refine nnnorm_le_nnnorm_of_nonneg_of_le (conjugate_nonneg (pow_nonneg hy'.1 2) _) ?_ |>.trans h refine conjugate_le_conjugate ?_ _ trans (1 - y) · simpa using pow_antitone hy'.1 hy'.2 one_le_two · gcongr exact hy.1 /-- A variant of `nnnorm_sub_mul_self_le` which uses `‖·‖` instead of `‖·‖₊`. -/ lemma norm_sub_mul_self_le {A : Type*} [CStarAlgebra A] [PartialOrder A] [StarOrderedRing A] {x y : A} (z : A) (hx₀ : 0 ≤ x) (hy : y ∈ Set.Icc x 1) {c : ℝ} (hc : 0 ≤ c) (h : ‖star z * (1 - x) * z‖ ≤ c ^ 2) : ‖z - y * z‖ ≤ c := nnnorm_sub_mul_self_le z hx₀ hy h (c := ⟨c, hc⟩) variable {A} in /-- A variant of `norm_sub_mul_self_le` for non-unital algebras that passes to the unitization. -/ lemma norm_sub_mul_self_le_of_inr {x y : A} (z : A) (hx₀ : 0 ≤ x) (hxy : x ≤ y) (hy₁ : ‖y‖ ≤ 1) {c : ℝ} (hc : 0 ≤ c) (h : ‖star (z : A⁺¹) * (1 - x) * z‖ ≤ c ^ 2) : ‖z - y * z‖ ≤ c := by rw [← norm_inr (𝕜 := ℂ), inr_sub, inr_mul] refine norm_sub_mul_self_le _ ?_ ?_ hc h · rwa [inr_nonneg_iff] · have hy := hx₀.trans hxy rw [Set.mem_Icc, inr_le_iff _ _ hx₀.isSelfAdjoint hy.isSelfAdjoint, ← norm_le_one_iff_of_nonneg _, norm_inr] exact ⟨hxy, hy₁⟩ variable {A} in /-- This shows `CStarAlgebra.approximateUnit` is a one-sided approximate unit, but this is marked `private` because it is only used to prove `CStarAlgebra.increasingApproximateUnit`. -/ private lemma tendsto_mul_right_approximateUnit (m : A) : Tendsto (· * m) (approximateUnit A) (𝓝 m) := by refine tendsto_mul_right_of_forall_nonneg_tendsto (fun m hm₁ hm₂ ↦ ?_) m rw [(hasBasis_approximateUnit A).tendsto_iff nhds_basis_closedBall] intro ε hε lift ε to ℝ≥0 using hε.le rw [coe_pos] at hε refine ⟨cfcₙ (fun y : ℝ≥0 ↦ 1 - (1 + y)⁻¹) (ε⁻¹ ^ 2 • m), ⟨cfcₙ_nonneg_of_predicate, norm_cfcₙ_one_sub_one_add_inv_lt_one (ε⁻¹ ^ 2 • m)⟩, ?_⟩ rintro x ⟨(hx₁ : _ ≤ x), hx₂⟩ simp only [mem_closedBall, dist_eq_norm', zero_sub, norm_neg] at hx₂ ⊢ rw [← coe_nnnorm, coe_le_coe] have hx₀ : 0 ≤ x := cfcₙ_nonneg_of_predicate.trans hx₁ rw [← inr_le_iff _ _ (.of_nonneg cfcₙ_nonneg_of_predicate) (.of_nonneg hx₀), nnreal_cfcₙ_eq_cfc_inr _ _ (by simp [tsub_self]), inr_smul] at hx₁ rw [← norm_inr (𝕜 := ℂ)] at hm₂ hx₂ rw [← inr_nonneg_iff] at hx₀ hm₁ rw [← nnnorm_inr (𝕜 := ℂ), inr_sub, inr_mul] generalize (x : A⁺¹) = x, (m : A⁺¹) = m at * set g : ℝ≥0 → ℝ≥0 := fun y ↦ 1 - (1 + y)⁻¹ have hg : Continuous g := by rw [← continuousOn_univ] fun_prop (disch := intro _ _; positivity) have hg' : ContinuousOn (fun y ↦ (1 + ε⁻¹ ^ 2 • y)⁻¹) (spectrum ℝ≥0 m) := ContinuousOn.inv₀ (by fun_prop) fun _ _ ↦ by positivity have hx : x ∈ Set.Icc 0 1 := mem_Icc_iff_norm_le_one.mpr ⟨hx₀, hx₂⟩ have hx' : x ∈ Set.Icc _ 1 := ⟨hx₁, hx.2⟩ refine nnnorm_sub_mul_self_le m cfc_nonneg_of_predicate hx' ?_ suffices star m * (1 - cfc g (ε⁻¹ ^ 2 • m)) * m = cfc (fun y : ℝ≥0 ↦ y * (1 + ε⁻¹ ^ 2 • y)⁻¹ * y) m by rw [this] refine nnnorm_cfc_nnreal_le fun y hy ↦ ?_ field_simp calc y * ε ^ 2 * y / (ε ^ 2 + y) ≤ ε ^ 2 * 1 := by rw [mul_div_assoc] gcongr · refine mul_le_of_le_one_left (zero_le _) ?_ have hm' := hm₂.le rw [norm_le_one_iff_of_nonneg m hm₁, ← cfc_id' ℝ≥0 m, ← cfc_one (R := ℝ≥0) m, cfc_nnreal_le_iff _ _ _ (QuasispectrumRestricts.nnreal_of_nonneg hm₁)] at hm' exact hm' y hy · exact div_le_one (by positivity) |>.mpr le_add_self _ = ε ^ 2 := mul_one _ rw [cfc_mul _ _ m (continuousOn_id' _ |>.mul hg') (continuousOn_id' _), cfc_mul _ _ m (continuousOn_id' _) hg', cfc_id' .., hm₁.star_eq] congr rw [← cfc_one (R := ℝ≥0) m, ← cfc_comp_smul _ _ _ hg.continuousOn hm₁, ← cfc_tsub _ _ m (by simp [g]) hm₁ (by fun_prop) (Continuous.continuousOn <| by fun_prop)] refine cfc_congr (fun y _ ↦ ?_) simp [g, tsub_tsub_cancel_of_le] /-- The filter `CStarAlgebra.approximateUnit` generated by the sections `{x | a ≤ x} ∩ closedBall 0 1` for `0 ≤ a` forms an increasing approximate unit. -/ lemma increasingApproximateUnit : IsIncreasingApproximateUnit (approximateUnit A) where tendsto_mul_left := by rw [tendsto_mul_left_iff_tendsto_mul_right] · exact tendsto_mul_right_approximateUnit · rw [(hasBasis_approximateUnit A).eventually_iff] peel (hasBasis_approximateUnit A).ex_mem with x hx exact ⟨hx, fun y hy ↦ (hx.1.trans hy.1).isSelfAdjoint⟩ tendsto_mul_right := tendsto_mul_right_approximateUnit eventually_nonneg := .filter_mono inf_le_left <| (isBasis_nonneg_sections A).hasBasis.eventually_iff.mpr ⟨0, by simp⟩ eventually_norm := .filter_mono inf_le_right <| by simp neBot := hasBasis_approximateUnit A |>.neBot_iff.mpr fun hx ↦ ⟨_, ⟨le_rfl, by simpa using hx.2.le⟩⟩ end CStarAlgebra end ApproximateUnit
CartesianClosed.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.Closed.Ideal import Mathlib.CategoryTheory.Monoidal.Cartesian.FunctorCategory import Mathlib.CategoryTheory.Sites.CartesianMonoidal import Mathlib.CategoryTheory.Sites.Sheafification /-! # Sheaf categories are cartesian closed ...if the underlying presheaf category is cartesian closed, the target category has (chosen) finite products, and there exists a sheafification functor. -/ noncomputable section open CategoryTheory Limits variable {C : Type*} [Category C] (J : GrothendieckTopology C) (A : Type*) [Category A] instance [HasSheafify J A] [CartesianMonoidalCategory A] [CartesianClosed (Cᵒᵖ ⥤ A)] : CartesianClosed (Sheaf J A) := cartesianClosedOfReflective (sheafToPresheaf _ _)
Bitwise.lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Alex Keizer -/ import Mathlib.Algebra.Group.Nat.Even import Mathlib.Algebra.NeZero import Mathlib.Algebra.Ring.Nat import Mathlib.Data.Bool.Basic import Mathlib.Data.List.GetD import Mathlib.Data.Nat.Bits import Mathlib.Order.Basic import Mathlib.Tactic.AdaptationNote import Mathlib.Tactic.Common /-! # Bitwise operations on natural numbers In the first half of this file, we provide theorems for reasoning about natural numbers from their bitwise properties. In the second half of this file, we show properties of the bitwise operations `lor`, `land` and `xor`, which are defined in core. ## Main results * `eq_of_testBit_eq`: two natural numbers are equal if they have equal bits at every position. * `exists_most_significant_bit`: if `n ≠ 0`, then there is some position `i` that contains the most significant `1`-bit of `n`. * `lt_of_testBit`: if `n` and `m` are numbers and `i` is a position such that the `i`-th bit of of `n` is zero, the `i`-th bit of `m` is one, and all more significant bits are equal, then `n < m`. ## Future work There is another way to express bitwise properties of natural number: `digits 2`. The two ways should be connected. ## Keywords bitwise, and, or, xor -/ open Function namespace Nat section variable {f : Bool → Bool → Bool} @[simp] lemma bitwise_zero_left (m : Nat) : bitwise f 0 m = if f false true then m else 0 := by simp [bitwise] @[simp] lemma bitwise_zero_right (n : Nat) : bitwise f n 0 = if f true false then n else 0 := by unfold bitwise simp only [ite_self, Nat.zero_div, ite_true, ite_eq_right_iff] rintro ⟨⟩ split_ifs <;> rfl lemma bitwise_zero : bitwise f 0 0 = 0 := by simp only [bitwise_zero_right, ite_self] lemma bitwise_of_ne_zero {n m : Nat} (hn : n ≠ 0) (hm : m ≠ 0) : bitwise f n m = bit (f (bodd n) (bodd m)) (bitwise f (n / 2) (m / 2)) := by conv_lhs => unfold bitwise have mod_two_iff_bod x : (x % 2 = 1 : Bool) = bodd x := by simp only [mod_two_of_bodd]; cases bodd x <;> rfl simp only [hn, hm, mod_two_iff_bod, ite_false, bit, two_mul, Bool.cond_eq_ite] theorem binaryRec_of_ne_zero {C : Nat → Sort*} (z : C 0) (f : ∀ b n, C n → C (bit b n)) {n} (h : n ≠ 0) : binaryRec z f n = bit_decomp n ▸ f (bodd n) (div2 n) (binaryRec z f (div2 n)) := by cases n using bitCasesOn with | h b n => rw [binaryRec_eq _ _ (by right; simpa [bit_eq_zero_iff] using h)] generalize_proofs h; revert h rw [bodd_bit, div2_bit] simp @[simp] lemma bitwise_bit {f : Bool → Bool → Bool} (h : f false false = false := by rfl) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := by conv_lhs => unfold bitwise simp only [bit, Bool.cond_eq_ite] have h4 x : (x + x + 1) / 2 = x := by rw [← two_mul, add_comm]; simp [add_mul_div_left] cases a <;> cases b <;> simp <;> split_ifs <;> simp_all +decide [two_mul] lemma bit_mod_two_eq_zero_iff (a x) : bit a x % 2 = 0 ↔ !a := by simp lemma bit_mod_two_eq_one_iff (a x) : bit a x % 2 = 1 ↔ a := by simp @[simp] theorem lor_bit : ∀ a m b n, bit a m ||| bit b n = bit (a || b) (m ||| n) := bitwise_bit @[simp] theorem land_bit : ∀ a m b n, bit a m &&& bit b n = bit (a && b) (m &&& n) := bitwise_bit @[simp] theorem ldiff_bit : ∀ a m b n, ldiff (bit a m) (bit b n) = bit (a && not b) (ldiff m n) := bitwise_bit @[simp] theorem xor_bit : ∀ a m b n, bit a m ^^^ bit b n = bit (bne a b) (m ^^^ n) := bitwise_bit attribute [simp] Nat.testBit_bitwise theorem testBit_lor : ∀ m n k, testBit (m ||| n) k = (testBit m k || testBit n k) := testBit_bitwise rfl theorem testBit_land : ∀ m n k, testBit (m &&& n) k = (testBit m k && testBit n k) := testBit_bitwise rfl @[simp] theorem testBit_ldiff : ∀ m n k, testBit (ldiff m n) k = (testBit m k && not (testBit n k)) := testBit_bitwise rfl attribute [simp] testBit_xor end @[simp] theorem bit_false : bit false = (2 * ·) := rfl @[simp] theorem bit_true : bit true = (2 * · + 1) := rfl @[simp] theorem bit_false_apply (n) : bit false n = (2 * n) := rfl @[simp] theorem bit_true_apply (n) : bit true n = (2 * n + 1) := rfl theorem bit_ne_zero_iff {n : ℕ} {b : Bool} : n.bit b ≠ 0 ↔ n = 0 → b = true := by simp /-- An alternative for `bitwise_bit` which replaces the `f false false = false` assumption with assumptions that neither `bit a m` nor `bit b n` are `0` (albeit, phrased as the implications `m = 0 → a = true` and `n = 0 → b = true`) -/ lemma bitwise_bit' {f : Bool → Bool → Bool} (a : Bool) (m : Nat) (b : Bool) (n : Nat) (ham : m = 0 → a = true) (hbn : n = 0 → b = true) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := by conv_lhs => unfold bitwise rw [← bit_ne_zero_iff] at ham hbn simp only [ham, hbn, bit_mod_two_eq_one_iff, Bool.decide_coe, ← div2_val, div2_bit, ite_false] conv_rhs => simp only [bit, two_mul, Bool.cond_eq_ite] lemma bitwise_eq_binaryRec (f : Bool → Bool → Bool) : bitwise f = binaryRec (fun n => cond (f false true) n 0) fun a m Ia => binaryRec (cond (f true false) (bit a m) 0) fun b n _ => bit (f a b) (Ia n) := by funext x y induction x using binaryRec' generalizing y with | z => simp only [bitwise_zero_left, binaryRec_zero, Bool.cond_eq_ite] | f xb x hxb ih => rw [← bit_ne_zero_iff] at hxb simp_rw [binaryRec_of_ne_zero _ _ hxb, bodd_bit, div2_bit, eq_rec_constant] induction y using binaryRec' with | z => simp only [bitwise_zero_right, binaryRec_zero, Bool.cond_eq_ite] | f yb y hyb => rw [← bit_ne_zero_iff] at hyb simp_rw [binaryRec_of_ne_zero _ _ hyb, bitwise_of_ne_zero hxb hyb, bodd_bit, ← div2_val, div2_bit, eq_rec_constant, ih] theorem zero_of_testBit_eq_false {n : ℕ} (h : ∀ i, testBit n i = false) : n = 0 := by induction n using Nat.binaryRec with | z => rfl | f b n hn => ?_ have : b = false := by simpa using h 0 rw [this, bit_false, hn fun i => by rw [← h (i + 1), testBit_bit_succ]] theorem testBit_eq_false_of_lt {n i} (h : n < 2 ^ i) : n.testBit i = false := by simp [testBit, shiftRight_eq_div_pow, Nat.div_eq_of_lt h] /-- The ith bit is the ith element of `n.bits`. -/ theorem testBit_eq_inth (n i : ℕ) : n.testBit i = n.bits.getI i := by induction i generalizing n with | zero => simp only [testBit, shiftRight_zero, one_and_eq_mod_two, mod_two_of_bodd, bodd_eq_bits_head, List.getI_zero_eq_headI] cases List.headI (bits n) <;> rfl | succ i ih => conv_lhs => rw [← bit_decomp n] rw [testBit_bit_succ, ih n.div2, div2_bits_eq_tail] cases n.bits <;> simp theorem exists_most_significant_bit {n : ℕ} (h : n ≠ 0) : ∃ i, testBit n i = true ∧ ∀ j, i < j → testBit n j = false := by induction n using Nat.binaryRec with | z => exact False.elim (h rfl) | f b n hn => ?_ by_cases h' : n = 0 · subst h' rw [show b = true by revert h cases b <;> simp] refine ⟨0, ⟨by rw [testBit_bit_zero], fun j hj => ?_⟩⟩ obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (ne_of_gt hj) rw [testBit_bit_succ, zero_testBit] · obtain ⟨k, ⟨hk, hk'⟩⟩ := hn h' refine ⟨k + 1, ⟨by rw [testBit_bit_succ, hk], fun j hj => ?_⟩⟩ obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (show j ≠ 0 by intro x; subst x; simp at hj) exact (testBit_bit_succ _ _ _).trans (hk' _ (lt_of_succ_lt_succ hj)) theorem lt_of_testBit {n m : ℕ} (i : ℕ) (hn : testBit n i = false) (hm : testBit m i = true) (hnm : ∀ j, i < j → testBit n j = testBit m j) : n < m := by induction n using Nat.binaryRec generalizing i m with | z => rw [Nat.pos_iff_ne_zero] rintro rfl simp at hm | f b n hn' => induction m using Nat.binaryRec generalizing i with | z => exact False.elim (Bool.false_ne_true ((zero_testBit i).symm.trans hm)) | f b' m hm' => by_cases hi : i = 0 · subst hi simp only [testBit_bit_zero] at hn hm have : n = m := eq_of_testBit_eq fun i => by convert hnm (i + 1) (Nat.zero_lt_succ _) using 1 <;> rw [testBit_bit_succ] rw [hn, hm, this, bit_false, bit_true] exact Nat.lt_succ_self _ · obtain ⟨i', rfl⟩ := exists_eq_succ_of_ne_zero hi simp only [testBit_bit_succ] at hn hm have := hn' _ hn hm fun j hj => by convert hnm j.succ (succ_lt_succ hj) using 1 <;> rw [testBit_bit_succ] exact bit_lt_bit b b' this theorem bitwise_swap {f : Bool → Bool → Bool} : bitwise (Function.swap f) = Function.swap (bitwise f) := by funext m n simp only [Function.swap] induction m using Nat.strongRecOn generalizing n with | ind m ih => ?_ rcases m with - | m <;> rcases n with - | n <;> try rw [bitwise_zero_left, bitwise_zero_right] · specialize ih ((m+1) / 2) (div_lt_self' ..) simp [bitwise_of_ne_zero, ih] /-- If `f` is a commutative operation on bools such that `f false false = false`, then `bitwise f` is also commutative. -/ theorem bitwise_comm {f : Bool → Bool → Bool} (hf : ∀ b b', f b b' = f b' b) (n m : ℕ) : bitwise f n m = bitwise f m n := suffices bitwise f = swap (bitwise f) by conv_lhs => rw [this] calc bitwise f = bitwise (swap f) := congr_arg _ <| funext fun _ => funext <| hf _ _ = swap (bitwise f) := bitwise_swap theorem lor_comm (n m : ℕ) : n ||| m = m ||| n := bitwise_comm Bool.or_comm n m theorem land_comm (n m : ℕ) : n &&& m = m &&& n := bitwise_comm Bool.and_comm n m lemma and_two_pow (n i : ℕ) : n &&& 2 ^ i = (n.testBit i).toNat * 2 ^ i := by refine eq_of_testBit_eq fun j => ?_ obtain rfl | hij := Decidable.eq_or_ne i j <;> cases h : n.testBit i · simp [h] · simp [h] · simp [testBit_two_pow_of_ne hij] · simp [testBit_two_pow_of_ne hij] lemma two_pow_and (n i : ℕ) : 2 ^ i &&& n = 2 ^ i * (n.testBit i).toNat := by rw [mul_comm, land_comm, and_two_pow] /-- Proving associativity of bitwise operations in general essentially boils down to a huge case distinction, so it is shorter to use this tactic instead of proving it in the general case. -/ macro "bitwise_assoc_tac" : tactic => set_option hygiene false in `(tactic| ( induction n using Nat.binaryRec generalizing m k with | z => simp | f b n hn => ?_ induction m using Nat.binaryRec with | z => simp | f b' m hm => ?_ induction k using Nat.binaryRec <;> simp [hn, Bool.or_assoc, Bool.and_assoc, Bool.bne_eq_xor])) theorem land_assoc (n m k : ℕ) : (n &&& m) &&& k = n &&& (m &&& k) := by bitwise_assoc_tac theorem lor_assoc (n m k : ℕ) : (n ||| m) ||| k = n ||| (m ||| k) := by bitwise_assoc_tac -- These lemmas match `mul_inv_cancel_right` and `mul_inv_cancel_left`. theorem xor_cancel_right (n m : ℕ) : (m ^^^ n) ^^^ n = m := by rw [Nat.xor_assoc, Nat.xor_self, xor_zero] theorem xor_cancel_left (n m : ℕ) : n ^^^ (n ^^^ m) = m := by rw [← Nat.xor_assoc, Nat.xor_self, zero_xor] theorem xor_right_injective {n : ℕ} : Function.Injective (HXor.hXor n : ℕ → ℕ) := fun m m' h => by rw [← xor_cancel_left n m, ← xor_cancel_left n m', h] theorem xor_left_injective {n : ℕ} : Function.Injective fun m => m ^^^ n := fun m m' (h : m ^^^ n = m' ^^^ n) => by rw [← xor_cancel_right n m, ← xor_cancel_right n m', h] @[simp] theorem xor_right_inj {n m m' : ℕ} : n ^^^ m = n ^^^ m' ↔ m = m' := xor_right_injective.eq_iff @[simp] theorem xor_left_inj {n m m' : ℕ} : m ^^^ n = m' ^^^ n ↔ m = m' := xor_left_injective.eq_iff @[simp] theorem xor_eq_zero {n m : ℕ} : n ^^^ m = 0 ↔ n = m := by rw [← Nat.xor_self n, xor_right_inj, eq_comm] theorem xor_ne_zero {n m : ℕ} : n ^^^ m ≠ 0 ↔ n ≠ m := xor_eq_zero.not theorem xor_trichotomy {a b c : ℕ} (h : a ^^^ b ^^^ c ≠ 0) : b ^^^ c < a ∨ c ^^^ a < b ∨ a ^^^ b < c := by set v := a ^^^ b ^^^ c with hv -- The xor of any two of `a`, `b`, `c` is the xor of `v` and the third. have hab : a ^^^ b = c ^^^ v := by rw [Nat.xor_comm c, xor_cancel_right] have hbc : b ^^^ c = a ^^^ v := by rw [← Nat.xor_assoc, xor_cancel_left] have hca : c ^^^ a = b ^^^ v := by rw [hv, Nat.xor_assoc, Nat.xor_comm a, ← Nat.xor_assoc, xor_cancel_left] -- If `i` is the position of the most significant bit of `v`, then at least one of `a`, `b`, `c` -- has a one bit at position `i`. obtain ⟨i, ⟨hi, hi'⟩⟩ := exists_most_significant_bit h have : testBit a i ∨ testBit b i ∨ testBit c i := by contrapose! hi simp_rw [Bool.eq_false_eq_not_eq_true] at hi ⊢ rw [testBit_xor, testBit_xor, hi.1, hi.2.1, hi.2.2] rfl -- If, say, `a` has a one bit at position `i`, then `a xor v` has a zero bit at position `i`, but -- the same bits as `a` in positions greater than `j`, so `a xor v < a`. obtain h | h | h := this on_goal 1 => left; rw [hbc] on_goal 2 => right; left; rw [hca] on_goal 3 => right; right; rw [hab] all_goals refine lt_of_testBit i ?_ h fun j hj => ?_ · rw [testBit_xor, h, hi] rfl · simp only [testBit_xor, hi' _ hj, Bool.bne_false] theorem lt_xor_cases {a b c : ℕ} (h : a < b ^^^ c) : a ^^^ c < b ∨ a ^^^ b < c := by obtain ha | hb | hc := xor_trichotomy <| Nat.xor_assoc _ _ _ ▸ xor_ne_zero.2 h.ne exacts [(h.asymm ha).elim, Or.inl <| Nat.xor_comm _ _ ▸ hb, Or.inr hc] @[simp] theorem xor_mod_two_eq {m n : ℕ} : (m ^^^ n) % 2 = (m + n) % 2 := by by_cases h : (m + n) % 2 = 0 · simp only [h, mod_two_eq_zero_iff_testBit_zero, testBit_zero, xor_mod_two_eq_one, decide_not, Bool.decide_iff_dist, Bool.not_eq_false', beq_iff_eq, decide_eq_decide] omega · simp only [mod_two_ne_zero] at h simp only [h, xor_mod_two_eq_one] omega @[simp] theorem even_xor {m n : ℕ} : Even (m ^^^ n) ↔ (Even m ↔ Even n) := by simp only [even_iff, xor_mod_two_eq] omega @[simp] theorem bit_lt_two_pow_succ_iff {b x n} : bit b x < 2 ^ (n + 1) ↔ x < 2 ^ n := by cases b <;> simp <;> omega lemma shiftLeft_lt {x n m : ℕ} (h : x < 2 ^ n) : x <<< m < 2 ^ (n + m) := by simp only [Nat.pow_add, shiftLeft_eq, Nat.mul_lt_mul_right (Nat.two_pow_pos _), h] /-- Note that the LHS is the expression used within `Std.BitVec.append`, hence the name. -/ lemma append_lt {x y n m} (hx : x < 2 ^ n) (hy : y < 2 ^ m) : y <<< n ||| x < 2 ^ (n + m) := by apply bitwise_lt_two_pow · rw [add_comm]; apply shiftLeft_lt hy · apply lt_of_lt_of_le hx <| Nat.pow_le_pow_right (le_succ _) (le_add_right _ _) end Nat
Refinements.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.Abelian.Refinements import Mathlib.Algebra.Homology.ShortComplex.HomologicalComplex /-! # Refinements This file contains lemmas about "refinements" that are specific to the study of the homology of `HomologicalComplex`. General lemmas about refinements and the case of `ShortComplex` appear in the file `CategoryTheory.Abelian.Refinements`. -/ open CategoryTheory variable {C ι : Type*} [Category C] [Abelian C] {c : ComplexShape ι} (K : HomologicalComplex C c) namespace HomologicalComplex lemma eq_liftCycles_homologyπ_up_to_refinements {A : C} {i : ι} (γ : A ⟶ K.homology i) (j : ι) (hj : c.next i = j) : ∃ (A' : C) (π : A' ⟶ A) (_ : Epi π) (z : A' ⟶ K.X i) (hz : z ≫ K.d i j = 0), π ≫ γ = K.liftCycles z j hj hz ≫ K.homologyπ i := by subst hj exact (K.sc i).eq_liftCycles_homologyπ_up_to_refinements γ end HomologicalComplex
UniqueSums.lean
/- Copyright (c) 2025 Yaël Dillies, Paul Lezeau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Paul Lezeau -/ import Mathlib.Algebra.FreeAbelianGroup.Finsupp import Mathlib.Algebra.Group.UniqueProds.Basic /-! # Free abelian groups have unique sums -/ assert_not_exists Cardinal StarModule instance {σ : Type*} : TwoUniqueSums (FreeAbelianGroup σ) := (FreeAbelianGroup.equivFinsupp σ).twoUniqueSums_iff.mpr inferInstance
LocPathConnected.lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Ben Eltschig -/ import Mathlib.Topology.Connected.PathConnected import Mathlib.Topology.AlexandrovDiscrete /-! # Locally path-connected spaces This file defines `LocPathConnectedSpace X`, a predicate class asserting that `X` is locally path-connected, in that each point has a basis of path-connected neighborhoods. ## Main results * `IsOpen.pathComponent` / `IsClosed.pathComponent`: in locally path-connected spaces, path-components are both open and closed. * `pathComponent_eq_connectedComponent`: in locally path-connected spaces, path-components and connected components agree. * `pathConnectedSpace_iff_connectedSpace`: locally path-connected spaces are path-connected iff they are connected. * `instLocallyConnectedSpace`: locally path-connected spaces are also locally connected. * `IsOpen.locPathConnectedSpace`: open subsets of locally path-connected spaces are locally path-connected. * `LocPathConnectedSpace.coinduced` / `Quotient.locPathConnectedSpace`: quotients of locally path-connected spaces are locally path-connected. * `Sum.locPathConnectedSpace` / `Sigma.locPathConnectedSpace`: disjoint unions of locally path-connected spaces are locally path-connected. Abstractly, this also shows that locally path-connected spaces form a coreflective subcategory of the category of topological spaces, although we do not prove that in this form here. ## Implementation notes In the definition of `LocPathConnectedSpace X` we require neighbourhoods in the basis to be path-connected, but not necessarily open; that they can also be required to be open is shown as a theorem in `isOpen_isPathConnected_basis`. -/ noncomputable section open Topology Filter unitInterval Set Function variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {x y z : X} {ι : Type*} {F : Set X} section LocPathConnectedSpace /-- A topological space is locally path connected, at every point, path connected neighborhoods form a neighborhood basis. -/ class LocPathConnectedSpace (X : Type*) [TopologicalSpace X] : Prop where /-- Each neighborhood filter has a basis of path-connected neighborhoods. -/ path_connected_basis : ∀ x : X, (𝓝 x).HasBasis (fun s : Set X => s ∈ 𝓝 x ∧ IsPathConnected s) id export LocPathConnectedSpace (path_connected_basis) theorem LocPathConnectedSpace.of_bases {p : X → ι → Prop} {s : X → ι → Set X} (h : ∀ x, (𝓝 x).HasBasis (p x) (s x)) (h' : ∀ x i, p x i → IsPathConnected (s x i)) : LocPathConnectedSpace X where path_connected_basis x := by rw [hasBasis_self] intro t ht rcases (h x).mem_iff.mp ht with ⟨i, hpi, hi⟩ exact ⟨s x i, (h x).mem_of_mem hpi, h' x i hpi, hi⟩ variable [LocPathConnectedSpace X] protected theorem IsOpen.pathComponentIn (hF : IsOpen F) (x : X) : IsOpen (pathComponentIn F x) := by rw [isOpen_iff_mem_nhds] intro y hy let ⟨s, hs⟩ := (path_connected_basis y).mem_iff.mp (hF.mem_nhds (pathComponentIn_subset hy)) exact mem_of_superset hs.1.1 <| pathComponentIn_congr hy ▸ hs.1.2.subset_pathComponentIn (mem_of_mem_nhds hs.1.1) hs.2 /-- In a locally path connected space, each path component is an open set. -/ protected theorem IsOpen.pathComponent (x : X) : IsOpen (pathComponent x) := by rw [← pathComponentIn_univ] exact isOpen_univ.pathComponentIn _ /-- In a locally path connected space, each path component is a closed set. -/ protected theorem IsClosed.pathComponent (x : X) : IsClosed (pathComponent x) := by rw [← isOpen_compl_iff, isOpen_iff_mem_nhds] intro y hxy rcases (path_connected_basis y).ex_mem with ⟨V, hVy, hVc⟩ filter_upwards [hVy] with z hz hxz exact hxy <| hxz.trans (hVc.joinedIn _ hz _ (mem_of_mem_nhds hVy)).joined /-- In a locally path connected space, each path component is a clopen set. -/ protected theorem IsClopen.pathComponent (x : X) : IsClopen (pathComponent x) := ⟨.pathComponent x, .pathComponent x⟩ lemma pathComponentIn_mem_nhds (hF : F ∈ 𝓝 x) : pathComponentIn F x ∈ 𝓝 x := by let ⟨u, huF, hu, hxu⟩ := mem_nhds_iff.mp hF exact mem_nhds_iff.mpr ⟨pathComponentIn u x, pathComponentIn_mono huF, hu.pathComponentIn x, mem_pathComponentIn_self hxu⟩ theorem pathConnectedSpace_iff_connectedSpace : PathConnectedSpace X ↔ ConnectedSpace X := by refine ⟨fun _ ↦ inferInstance, fun h ↦ ⟨inferInstance, fun x y ↦ ?_⟩⟩ rw [← mem_pathComponent_iff, (IsClopen.pathComponent _).eq_univ] <;> simp theorem pathComponent_eq_connectedComponent (x : X) : pathComponent x = connectedComponent x := (pathComponent_subset_component x).antisymm <| (IsClopen.pathComponent x).connectedComponent_subset (mem_pathComponent_self _) theorem pathConnected_subset_basis {U : Set X} (h : IsOpen U) (hx : x ∈ U) : (𝓝 x).HasBasis (fun s : Set X => s ∈ 𝓝 x ∧ IsPathConnected s ∧ s ⊆ U) id := (path_connected_basis x).hasBasis_self_subset (IsOpen.mem_nhds h hx) theorem isOpen_isPathConnected_basis (x : X) : (𝓝 x).HasBasis (fun s : Set X ↦ IsOpen s ∧ x ∈ s ∧ IsPathConnected s) id := by refine ⟨fun s ↦ ⟨fun hs ↦ ?_, fun ⟨u, hu⟩ ↦ mem_nhds_iff.mpr ⟨u, hu.2, hu.1.1, hu.1.2.1⟩⟩⟩ have ⟨u, hus, hu, hxu⟩ := mem_nhds_iff.mp hs exact ⟨pathComponentIn u x, ⟨hu.pathComponentIn _, ⟨mem_pathComponentIn_self hxu, isPathConnected_pathComponentIn hxu⟩⟩, pathComponentIn_subset.trans hus⟩ theorem Topology.IsOpenEmbedding.locPathConnectedSpace {e : Y → X} (he : IsOpenEmbedding e) : LocPathConnectedSpace Y := have (y : Y) : (𝓝 y).HasBasis (fun s ↦ s ∈ 𝓝 (e y) ∧ IsPathConnected s ∧ s ⊆ range e) (e ⁻¹' ·) := he.basis_nhds <| pathConnected_subset_basis he.isOpen_range (mem_range_self _) .of_bases this fun x s ⟨_, hs, hse⟩ ↦ by rwa [he.isPathConnected_iff, image_preimage_eq_of_subset hse] theorem IsOpen.locPathConnectedSpace {U : Set X} (h : IsOpen U) : LocPathConnectedSpace U := h.isOpenEmbedding_subtypeVal.locPathConnectedSpace theorem IsOpen.isConnected_iff_isPathConnected {U : Set X} (U_op : IsOpen U) : IsConnected U ↔ IsPathConnected U := by rw [isConnected_iff_connectedSpace, isPathConnected_iff_pathConnectedSpace] haveI := U_op.locPathConnectedSpace exact pathConnectedSpace_iff_connectedSpace.symm /-- Locally path-connected spaces are locally connected. -/ instance : LocallyConnectedSpace X := by refine ⟨forall_imp (fun x h ↦ ⟨fun s ↦ ?_⟩) isOpen_isPathConnected_basis⟩ refine ⟨fun hs ↦ ?_, fun ⟨u, ⟨hu, hxu, _⟩, hus⟩ ↦ mem_nhds_iff.mpr ⟨u, hus, hu, hxu⟩⟩ let ⟨u, ⟨hu, hxu, hu'⟩, hus⟩ := (h.mem_iff' s).mp hs exact ⟨u, ⟨hu, hxu, hu'.isConnected⟩, hus⟩ /-- A space is locally path-connected iff all path components of open subsets are open. -/ lemma locPathConnectedSpace_iff_isOpen_pathComponentIn {X : Type*} [TopologicalSpace X] : LocPathConnectedSpace X ↔ ∀ (x : X) (u : Set X), IsOpen u → IsOpen (pathComponentIn u x) := ⟨fun _ _ _ hu ↦ hu.pathComponentIn _, fun h ↦ ⟨fun x ↦ ⟨fun s ↦ by refine ⟨fun hs ↦ ?_, fun ⟨_, ht⟩ ↦ Filter.mem_of_superset ht.1.1 ht.2⟩ let ⟨u, hu⟩ := mem_nhds_iff.mp hs exact ⟨pathComponentIn u x, ⟨(h x u hu.2.1).mem_nhds (mem_pathComponentIn_self hu.2.2), isPathConnected_pathComponentIn hu.2.2⟩, pathComponentIn_subset.trans hu.1⟩⟩⟩⟩ /-- A space is locally path-connected iff all path components of open subsets are neighbourhoods. -/ lemma locPathConnectedSpace_iff_pathComponentIn_mem_nhds {X : Type*} [TopologicalSpace X] : LocPathConnectedSpace X ↔ ∀ x : X, ∀ u : Set X, IsOpen u → x ∈ u → pathComponentIn u x ∈ nhds x := by rw [locPathConnectedSpace_iff_isOpen_pathComponentIn] simp_rw [forall_comm (β := Set X), ← imp_forall_iff] refine forall_congr' fun u ↦ imp_congr_right fun _ ↦ ?_ exact ⟨fun h x hxu ↦ (h x).mem_nhds (mem_pathComponentIn_self hxu), fun h x ↦ isOpen_iff_mem_nhds.mpr fun y hy ↦ pathComponentIn_congr hy ▸ h y <| pathComponentIn_subset hy⟩ /-- Any topology coinduced by a locally path-connected topology is locally path-connected. -/ lemma LocPathConnectedSpace.coinduced {Y : Type*} (f : X → Y) : @LocPathConnectedSpace Y (.coinduced f ‹_›) := by let _ := TopologicalSpace.coinduced f ‹_›; have hf : Continuous f := continuous_coinduced_rng refine locPathConnectedSpace_iff_isOpen_pathComponentIn.mpr fun y u hu ↦ isOpen_coinduced.mpr <| isOpen_iff_mem_nhds.mpr fun x hx ↦ ?_ have hx' := preimage_mono pathComponentIn_subset hx refine mem_nhds_iff.mpr ⟨pathComponentIn (f ⁻¹' u) x, ?_, (hu.preimage hf).pathComponentIn _, mem_pathComponentIn_self hx'⟩ rw [← image_subset_iff, ← pathComponentIn_congr hx] exact ((isPathConnected_pathComponentIn hx').image hf).subset_pathComponentIn ⟨x, mem_pathComponentIn_self hx', rfl⟩ <| (image_mono pathComponentIn_subset).trans <| u.image_preimage_subset f /-- Quotients of locally path-connected spaces are locally path-connected. -/ lemma Topology.IsQuotientMap.locPathConnectedSpace {f : X → Y} (h : IsQuotientMap f) : LocPathConnectedSpace Y := h.2 ▸ LocPathConnectedSpace.coinduced f /-- Quotients of locally path-connected spaces are locally path-connected. -/ instance Quot.locPathConnectedSpace {r : X → X → Prop} : LocPathConnectedSpace (Quot r) := isQuotientMap_quot_mk.locPathConnectedSpace /-- Quotients of locally path-connected spaces are locally path-connected. -/ instance Quotient.locPathConnectedSpace {s : Setoid X} : LocPathConnectedSpace (Quotient s) := isQuotientMap_quotient_mk'.locPathConnectedSpace /-- Disjoint unions of locally path-connected spaces are locally path-connected. -/ instance Sum.locPathConnectedSpace.{u} {X Y : Type u} [TopologicalSpace X] [TopologicalSpace Y] [LocPathConnectedSpace X] [LocPathConnectedSpace Y] : LocPathConnectedSpace (X ⊕ Y) := by rw [locPathConnectedSpace_iff_pathComponentIn_mem_nhds]; intro x u hu hxu; rw [mem_nhds_iff] obtain x | y := x · refine ⟨Sum.inl '' (pathComponentIn (Sum.inl ⁻¹' u) x), ?_, ?_, ?_⟩ · apply IsPathConnected.subset_pathComponentIn · exact (isPathConnected_pathComponentIn (by exact hxu)).image continuous_inl · exact ⟨x, mem_pathComponentIn_self hxu, rfl⟩ · exact (image_mono pathComponentIn_subset).trans (u.image_preimage_subset _) · exact isOpenMap_inl _ <| (hu.preimage continuous_inl).pathComponentIn _ · exact ⟨x, mem_pathComponentIn_self hxu, rfl⟩ · refine ⟨Sum.inr '' (pathComponentIn (Sum.inr ⁻¹' u) y), ?_, ?_, ?_⟩ · apply IsPathConnected.subset_pathComponentIn · exact (isPathConnected_pathComponentIn (by exact hxu)).image continuous_inr · exact ⟨y, mem_pathComponentIn_self hxu, rfl⟩ · exact (image_mono pathComponentIn_subset).trans (u.image_preimage_subset _) · exact isOpenMap_inr _ <| (hu.preimage continuous_inr).pathComponentIn _ · exact ⟨y, mem_pathComponentIn_self hxu, rfl⟩ /-- Disjoint unions of locally path-connected spaces are locally path-connected. -/ instance Sigma.locPathConnectedSpace {X : ι → Type*} [(i : ι) → TopologicalSpace (X i)] [(i : ι) → LocPathConnectedSpace (X i)] : LocPathConnectedSpace ((i : ι) × X i) := by rw [locPathConnectedSpace_iff_pathComponentIn_mem_nhds]; intro x u hu hxu; rw [mem_nhds_iff] refine ⟨(Sigma.mk x.1) '' (pathComponentIn ((Sigma.mk x.1) ⁻¹' u) x.2), ?_, ?_, ?_⟩ · apply IsPathConnected.subset_pathComponentIn · exact (isPathConnected_pathComponentIn (by exact hxu)).image continuous_sigmaMk · exact ⟨x.2, mem_pathComponentIn_self hxu, rfl⟩ · exact (image_mono pathComponentIn_subset).trans (u.image_preimage_subset _) · exact isOpenMap_sigmaMk _ <| (hu.preimage continuous_sigmaMk).pathComponentIn _ · exact ⟨x.2, mem_pathComponentIn_self hxu, rfl⟩ instance AlexandrovDiscrete.locPathConnectedSpace [AlexandrovDiscrete X] : LocPathConnectedSpace X := by apply LocPathConnectedSpace.of_bases nhds_basis_nhdsKer_singleton simp only [forall_const, IsPathConnected, mem_nhdsKer_singleton] intro x exists x, specializes_rfl intro y hy symm apply hy.joinedIn <;> rewrite [mem_nhdsKer_singleton] <;> [assumption; rfl] end LocPathConnectedSpace
Zify.lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll, Mario Carneiro, Robert Y. Lewis -/ import Mathlib.Tactic.Basic import Mathlib.Tactic.Attr.Register import Mathlib.Data.Int.Cast.Basic import Mathlib.Order.Basic /-! # `zify` tactic The `zify` tactic is used to shift propositions from `Nat` to `Int`. This is often useful since `Int` has well-behaved subtraction. ``` example (a b c x y z : Nat) (h : ¬ x*y*z < 0) : c < a + 3*b := by zify zify at h /- h : ¬↑x * ↑y * ↑z < 0 ⊢ ↑c < ↑a + 3 * ↑b -/ ``` -/ namespace Mathlib.Tactic.Zify open Lean open Lean.Meta open Lean.Parser.Tactic open Lean.Elab.Tactic /-- The `zify` tactic is used to shift propositions from `Nat` to `Int`. This is often useful since `Int` has well-behaved subtraction. ``` example (a b c x y z : Nat) (h : ¬ x*y*z < 0) : c < a + 3*b := by zify zify at h /- h : ¬↑x * ↑y * ↑z < 0 ⊢ ↑c < ↑a + 3 * ↑b -/ ``` `zify` can be given extra lemmas to use in simplification. This is especially useful in the presence of nat subtraction: passing `≤` arguments will allow `push_cast` to do more work. ``` example (a b c : Nat) (h : a - b < c) (hab : b ≤ a) : false := by zify [hab] at h /- h : ↑a - ↑b < ↑c -/ ``` `zify` makes use of the `@[zify_simps]` attribute to move propositions, and the `push_cast` tactic to simplify the `Int`-valued expressions. `zify` is in some sense dual to the `lift` tactic. `lift (z : Int) to Nat` will change the type of an integer `z` (in the supertype) to `Nat` (the subtype), given a proof that `z ≥ 0`; propositions concerning `z` will still be over `Int`. `zify` changes propositions about `Nat` (the subtype) to propositions about `Int` (the supertype), without changing the type of any variable. -/ syntax (name := zify) "zify" (simpArgs)? (location)? : tactic macro_rules | `(tactic| zify $[[$simpArgs,*]]? $[at $location]?) => let args := simpArgs.map (·.getElems) |>.getD #[] `(tactic| simp -decide only [zify_simps, push_cast, $args,*] $[at $location]?) /-- The `Simp.Context` generated by `zify`. -/ def mkZifyContext (simpArgs : Option (Syntax.TSepArray `Lean.Parser.Tactic.simpStar ",")) : TacticM MkSimpContextResult := do let args := simpArgs.map (·.getElems) |>.getD #[] mkSimpContext (← `(tactic| simp -decide only [zify_simps, push_cast, $args,*])) false /-- A variant of `applySimpResultToProp` that cannot close the goal, but does not need a meta variable and returns a tuple of a proof and the corresponding simplified proposition. -/ def applySimpResultToProp' (proof : Expr) (prop : Expr) (r : Simp.Result) : MetaM (Expr × Expr) := do match r.proof? with | some eqProof => return (← mkExpectedTypeHint (← mkEqMP eqProof proof) r.expr, r.expr) | none => if r.expr != prop then return (← mkExpectedTypeHint proof r.expr, r.expr) else return (proof, r.expr) /-- Translate a proof and the proposition into a zified form. -/ def zifyProof (simpArgs : Option (Syntax.TSepArray `Lean.Parser.Tactic.simpStar ",")) (proof : Expr) (prop : Expr) : TacticM (Expr × Expr) := do let ctx_result ← mkZifyContext simpArgs let (r, _) ← simp prop ctx_result.ctx applySimpResultToProp' proof prop r @[zify_simps] lemma natCast_eq (a b : Nat) : a = b ↔ (a : Int) = (b : Int) := Int.ofNat_inj.symm @[zify_simps] lemma natCast_le (a b : Nat) : a ≤ b ↔ (a : Int) ≤ (b : Int) := Int.ofNat_le.symm @[zify_simps] lemma natCast_lt (a b : Nat) : a < b ↔ (a : Int) < (b : Int) := Int.ofNat_lt.symm @[zify_simps] lemma natCast_ne (a b : Nat) : a ≠ b ↔ (a : Int) ≠ (b : Int) := not_congr Int.ofNat_inj.symm @[zify_simps] lemma natCast_dvd (a b : Nat) : a ∣ b ↔ (a : Int) ∣ (b : Int) := Int.ofNat_dvd.symm -- TODO: is it worth adding lemmas for Prime and Coprime as well? -- Doing so in this file would require adding imports. -- `Nat.cast_sub` is already tagged as `norm_cast` but it does allow to use assumptions like -- `m < n` or more generally `m + k ≤ n`. We add two lemmas to increase the probability that -- `zify` will push through `ℕ` subtraction. variable {R : Type*} [AddGroupWithOne R] @[norm_cast] theorem Nat.cast_sub_of_add_le {m n k} (h : m + k ≤ n) : ((n - m : ℕ) : R) = n - m := Nat.cast_sub (m.le_add_right k |>.trans h) @[norm_cast] theorem Nat.cast_sub_of_lt {m n} (h : m < n) : ((n - m : ℕ) : R) = n - m := Nat.cast_sub h.le end Zify end Mathlib.Tactic
Lemmas.lean
/- Copyright (c) 2025 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Lorenzo Luccioli -/ import Mathlib.Probability.Kernel.Composition.MeasureComp import Mathlib.Probability.Kernel.Composition.ParallelComp /-! # Lemmas relating different ways to compose measures and kernels This file contains lemmas about the composition of measures and kernels that do not fit in any of the other files in this directory, because they involve several types of compositions/products. ## Main statements * `parallelComp_comp_parallelComp`: `(η ∥ₖ η') ∘ₖ (κ ∥ₖ κ') = (η ∘ₖ κ) ∥ₖ (η' ∘ₖ κ')` * `parallelComp_comp_copy`: `(κ ∥ₖ η) ∘ₖ (copy α) = κ ×ₖ η` * `deterministic_comp_copy`: for a deterministic kernel, copying then applying the kernel to the two copies is the same as first applying the kernel then copying. That is, if `κ` is a deterministic kernel, `(κ ∥ₖ κ) ∘ₖ copy α = copy β ∘ₖ κ`. -/ open MeasureTheory ProbabilityTheory open scoped ENNReal variable {α β γ δ : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} {mγ : MeasurableSpace γ} {mδ : MeasurableSpace δ} {μ : Measure α} {ν : Measure β} {κ : Kernel α β} namespace ProbabilityTheory.Kernel variable {η : Kernel γ δ} lemma parallelComp_comp_copy (κ : Kernel α β) (η : Kernel α γ) : (κ ∥ₖ η) ∘ₖ (copy α) = κ ×ₖ η := by by_cases hκ : IsSFiniteKernel κ swap; · simp [hκ] by_cases hη : IsSFiniteKernel η swap; · simp [hη] ext a s hs simp_rw [prod_apply, comp_apply, copy_apply, Measure.bind_apply hs (Kernel.aemeasurable _)] rw [lintegral_dirac'] swap; · exact Kernel.measurable_coe _ hs rw [parallelComp_apply] lemma swap_parallelComp : swap β δ ∘ₖ (κ ∥ₖ η) = η ∥ₖ κ ∘ₖ swap α γ := by by_cases hκ : IsSFiniteKernel κ swap; · simp [hκ] by_cases hη : IsSFiniteKernel η swap; · simp [hη] ext ac s hs simp_rw [comp_apply, parallelComp_apply, Measure.bind_apply hs (Kernel.aemeasurable _), swap_apply, lintegral_dirac' _ (Kernel.measurable_coe _ hs), parallelComp_apply' hs, Prod.fst_swap, Prod.snd_swap] rw [MeasureTheory.lintegral_prod_symm] swap; · exact ((Kernel.id.measurable_coe hs).comp measurable_swap).aemeasurable congr with d simp_rw [Prod.swap_prod_mk, Measure.dirac_apply' _ hs, ← Set.indicator_comp_right, lintegral_indicator (measurable_prodMk_left hs)] simp /-- For a deterministic kernel, copying then applying the kernel to the two copies is the same as first applying the kernel then copying. -/ lemma deterministic_comp_copy {f : α → β} (hf : Measurable f) : (deterministic f hf ∥ₖ deterministic f hf) ∘ₖ copy α = copy β ∘ₖ deterministic f hf := by simp_rw [parallelComp_comp_copy, deterministic_prod_deterministic, copy, deterministic_comp_deterministic, Function.comp_def] end ProbabilityTheory.Kernel namespace MeasureTheory.Measure lemma compProd_eq_parallelComp_comp_copy_comp [SFinite μ] : μ ⊗ₘ κ = (Kernel.id ∥ₖ κ) ∘ₘ Kernel.copy α ∘ₘ μ := by by_cases hκ : IsSFiniteKernel κ swap; · simp [hκ] rw [compProd_eq_comp_prod, ← Kernel.parallelComp_comp_copy, Measure.comp_assoc] lemma prod_comp_right [SFinite ν] {κ : Kernel β γ} [IsSFiniteKernel κ] : μ.prod (κ ∘ₘ ν) = (Kernel.id ∥ₖ κ) ∘ₘ (μ.prod ν) := by ext s hs rw [Measure.prod_apply hs, Measure.bind_apply hs (Kernel.aemeasurable _)] simp_rw [Measure.bind_apply (measurable_prodMk_left hs) (Kernel.aemeasurable _)] rw [MeasureTheory.lintegral_prod] swap; · exact (Kernel.measurable_coe _ hs).aemeasurable congr with a congr with b rw [Kernel.parallelComp_apply, Kernel.id_apply, Measure.prod_apply hs, lintegral_dirac'] exact measurable_measure_prodMk_left hs lemma prod_comp_left [SFinite μ] [SFinite ν] {κ : Kernel α γ} [IsSFiniteKernel κ] : (κ ∘ₘ μ).prod ν = (κ ∥ₖ Kernel.id) ∘ₘ (μ.prod ν) := by have h1 : (κ ∘ₘ μ).prod ν = (ν.prod (κ ∘ₘ μ)).map Prod.swap := by rw [Measure.prod_swap] have h2 : (κ ∥ₖ Kernel.id) ∘ₘ (μ.prod ν) = ((Kernel.id ∥ₖ κ) ∘ₘ (ν.prod μ)).map Prod.swap := by calc (κ ∥ₖ Kernel.id) ∘ₘ (μ.prod ν) _ = (κ ∥ₖ Kernel.id) ∘ₘ ((ν.prod μ).map Prod.swap) := by rw [Measure.prod_swap] _ = (κ ∥ₖ Kernel.id) ∘ₘ ((Kernel.swap _ _) ∘ₘ (ν.prod μ)) := by rw [Kernel.swap, Measure.deterministic_comp_eq_map] _ = (Kernel.swap _ _) ∘ₘ ((Kernel.id ∥ₖ κ) ∘ₘ (ν.prod μ)) := by rw [Measure.comp_assoc, Measure.comp_assoc, Kernel.swap_parallelComp] _ = ((Kernel.id ∥ₖ κ) ∘ₘ (ν.prod μ)).map Prod.swap := by rw [Kernel.swap, Measure.deterministic_comp_eq_map] rw [← Measure.prod_comp_right, ← h1] at h2 exact h2.symm end MeasureTheory.Measure namespace ProbabilityTheory.Kernel variable {α' β' γ' : Type*} {mα' : MeasurableSpace α'} {mβ' : MeasurableSpace β'} {mγ' : MeasurableSpace γ'} lemma parallelComp_id_left_comp_parallelComp {η : Kernel α' γ} [IsSFiniteKernel η] {ξ : Kernel γ δ} [IsSFiniteKernel ξ] : (Kernel.id ∥ₖ ξ) ∘ₖ (κ ∥ₖ η) = κ ∥ₖ (ξ ∘ₖ η) := by by_cases hκ : IsSFiniteKernel κ swap; · simp [hκ] ext a rw [parallelComp_apply, comp_apply, comp_apply, parallelComp_apply, Measure.prod_comp_right] lemma parallelComp_id_right_comp_parallelComp {η : Kernel α' γ} [IsSFiniteKernel η] {ξ : Kernel γ δ} [IsSFiniteKernel ξ] : (ξ ∥ₖ Kernel.id) ∘ₖ (η ∥ₖ κ) = (ξ ∘ₖ η) ∥ₖ κ := by by_cases hκ : IsSFiniteKernel κ swap; · simp [hκ] ext a rw [parallelComp_apply, comp_apply, comp_apply, parallelComp_apply, Measure.prod_comp_left] lemma parallelComp_comp_parallelComp [IsSFiniteKernel κ] {η : Kernel β γ} [IsSFiniteKernel η] {κ' : Kernel α' β'} [IsSFiniteKernel κ'] {η' : Kernel β' γ'} [IsSFiniteKernel η'] : (η ∥ₖ η') ∘ₖ (κ ∥ₖ κ') = (η ∘ₖ κ) ∥ₖ (η' ∘ₖ κ') := by rw [← parallelComp_id_left_comp_parallelComp, ← parallelComp_id_right_comp_parallelComp, ← comp_assoc, parallelComp_id_left_comp_parallelComp, comp_id] lemma parallelComp_comp_prod [IsSFiniteKernel κ] {η : Kernel β γ} [IsSFiniteKernel η] {κ' : Kernel α β'} [IsSFiniteKernel κ'] {η' : Kernel β' γ'} [IsSFiniteKernel η'] : (η ∥ₖ η') ∘ₖ (κ ×ₖ κ') = (η ∘ₖ κ) ×ₖ (η' ∘ₖ κ') := by rw [← parallelComp_comp_copy, ← comp_assoc, parallelComp_comp_parallelComp, ← parallelComp_comp_copy] lemma parallelComp_comm {η : Kernel γ δ} : (Kernel.id ∥ₖ κ) ∘ₖ (η ∥ₖ Kernel.id) = (η ∥ₖ Kernel.id) ∘ₖ (Kernel.id ∥ₖ κ) := by by_cases hκ : IsSFiniteKernel κ swap; · simp [hκ] by_cases hη : IsSFiniteKernel η swap; · simp [hη] rw [parallelComp_id_left_comp_parallelComp, parallelComp_id_right_comp_parallelComp, comp_id, comp_id] end ProbabilityTheory.Kernel lemma MeasureTheory.Measure.parallelComp_comp_compProd [IsSFiniteKernel κ] {η : Kernel β γ} [IsSFiniteKernel η] : (Kernel.id ∥ₖ η) ∘ₘ (μ ⊗ₘ κ) = μ ⊗ₘ (η ∘ₖ κ) := by by_cases hμ : SFinite μ swap; · simp [hμ] rw [Measure.compProd_eq_comp_prod, Measure.compProd_eq_comp_prod, Measure.comp_assoc, Kernel.parallelComp_comp_prod, Kernel.id_comp]
Isometric.lean
/- Copyright (c) 2024 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.CStarAlgebra.ContinuousFunctionalCalculus.Instances /-! # Isometric continuous functional calculus This file adds a class for an *isometric* continuous functional calculus. This is separate from the usual `ContinuousFunctionalCalculus` class because we prefer not to require a metric (or a norm) on the algebra for reasons discussed in the module documentation for that file. Of course, with a metric on the algebra and an isometric continuous functional calculus, the algebra must *be* a C⋆-algebra already. As such, it may seem like this class is not useful. However, the main purpose is to allow for the continuous functional calculus to be a isometric for the other scalar rings `ℝ` and `ℝ≥0` too. -/ local notation "σ" => spectrum local notation "σₙ" => quasispectrum /-! ### Isometric continuous functional calculus for unital algebras -/ section Unital /-- An extension of the `ContinuousFunctionalCalculus` requiring that `cfcHom` is an isometry. -/ class IsometricContinuousFunctionalCalculus (R A : Type*) (p : outParam (A → Prop)) [CommSemiring R] [StarRing R] [MetricSpace R] [IsTopologicalSemiring R] [ContinuousStar R] [Ring A] [StarRing A] [MetricSpace A] [Algebra R A] : Prop extends ContinuousFunctionalCalculus R A p where isometric (a : A) (ha : p a) : Isometry (cfcHom ha (R := R)) section MetricSpace open scoped ContinuousFunctionalCalculus lemma isometry_cfcHom {R A : Type*} {p : outParam (A → Prop)} [CommSemiring R] [StarRing R] [MetricSpace R] [IsTopologicalSemiring R] [ContinuousStar R] [Ring A] [StarRing A] [MetricSpace A] [Algebra R A] [IsometricContinuousFunctionalCalculus R A p] (a : A) (ha : p a := by cfc_tac) : Isometry (cfcHom (show p a from ha) (R := R)) := IsometricContinuousFunctionalCalculus.isometric a ha end MetricSpace section NormedRing open scoped ContinuousFunctionalCalculus variable {𝕜 A : Type*} {p : outParam (A → Prop)} variable [RCLike 𝕜] [NormedRing A] [StarRing A] [NormedAlgebra 𝕜 A] variable [IsometricContinuousFunctionalCalculus 𝕜 A p] lemma norm_cfcHom (a : A) (f : C(σ 𝕜 a, 𝕜)) (ha : p a := by cfc_tac) : ‖cfcHom (show p a from ha) f‖ = ‖f‖ := by refine isometry_cfcHom a |>.norm_map_of_map_zero (map_zero _) f lemma nnnorm_cfcHom (a : A) (f : C(σ 𝕜 a, 𝕜)) (ha : p a := by cfc_tac) : ‖cfcHom (show p a from ha) f‖₊ = ‖f‖₊ := Subtype.ext <| norm_cfcHom a f ha lemma IsGreatest.norm_cfc [Nontrivial A] (f : 𝕜 → 𝕜) (a : A) (hf : ContinuousOn f (σ 𝕜 a) := by cfc_cont_tac) (ha : p a := by cfc_tac) : IsGreatest ((fun x ↦ ‖f x‖) '' spectrum 𝕜 a) ‖cfc f a‖ := by obtain ⟨x, hx⟩ := ContinuousFunctionalCalculus.isCompact_spectrum a |>.image_of_continuousOn hf.norm |>.exists_isGreatest <| (ContinuousFunctionalCalculus.spectrum_nonempty a ha).image _ obtain ⟨x, hx', rfl⟩ := hx.1 convert hx rw [cfc_apply f a, norm_cfcHom a _] apply le_antisymm · apply ContinuousMap.norm_le _ (norm_nonneg _) |>.mpr rintro ⟨y, hy⟩ exact hx.2 ⟨y, hy, rfl⟩ · exact le_trans (by simp) <| ContinuousMap.norm_coe_le_norm _ (⟨x, hx'⟩ : σ 𝕜 a) lemma IsGreatest.nnnorm_cfc [Nontrivial A] (f : 𝕜 → 𝕜) (a : A) (hf : ContinuousOn f (σ 𝕜 a) := by cfc_cont_tac) (ha : p a := by cfc_tac) : IsGreatest ((fun x ↦ ‖f x‖₊) '' σ 𝕜 a) ‖cfc f a‖₊ := by convert Real.toNNReal_mono.map_isGreatest (.norm_cfc f a) all_goals simp [Set.image_image, norm_toNNReal] lemma norm_apply_le_norm_cfc (f : 𝕜 → 𝕜) (a : A) ⦃x : 𝕜⦄ (hx : x ∈ σ 𝕜 a) (hf : ContinuousOn f (σ 𝕜 a) := by cfc_cont_tac) (ha : p a := by cfc_tac) : ‖f x‖ ≤ ‖cfc f a‖ := by revert hx nontriviality A exact (IsGreatest.norm_cfc f a hf ha |>.2 ⟨x, ·, rfl⟩) lemma nnnorm_apply_le_nnnorm_cfc (f : 𝕜 → 𝕜) (a : A) ⦃x : 𝕜⦄ (hx : x ∈ σ 𝕜 a) (hf : ContinuousOn f (σ 𝕜 a) := by cfc_cont_tac) (ha : p a := by cfc_tac) : ‖f x‖₊ ≤ ‖cfc f a‖₊ := norm_apply_le_norm_cfc f a hx lemma norm_cfc_le {f : 𝕜 → 𝕜} {a : A} {c : ℝ} (hc : 0 ≤ c) (h : ∀ x ∈ σ 𝕜 a, ‖f x‖ ≤ c) : ‖cfc f a‖ ≤ c := by obtain (_ | _) := subsingleton_or_nontrivial A · simpa [Subsingleton.elim (cfc f a) 0] · refine cfc_cases (‖·‖ ≤ c) a f (by simpa) fun hf ha ↦ ?_ simp only [← cfc_apply f a, isLUB_le_iff (IsGreatest.norm_cfc f a hf ha |>.isLUB)] rintro - ⟨x, hx, rfl⟩ exact h x hx lemma norm_cfc_le_iff (f : 𝕜 → 𝕜) (a : A) {c : ℝ} (hc : 0 ≤ c) (hf : ContinuousOn f (σ 𝕜 a) := by cfc_cont_tac) (ha : p a := by cfc_tac) : ‖cfc f a‖ ≤ c ↔ ∀ x ∈ σ 𝕜 a, ‖f x‖ ≤ c := ⟨fun h _ hx ↦ norm_apply_le_norm_cfc f a hx hf ha |>.trans h, norm_cfc_le hc⟩ lemma norm_cfc_lt {f : 𝕜 → 𝕜} {a : A} {c : ℝ} (hc : 0 < c) (h : ∀ x ∈ σ 𝕜 a, ‖f x‖ < c) : ‖cfc f a‖ < c := by obtain (_ | _) := subsingleton_or_nontrivial A · simpa [Subsingleton.elim (cfc f a) 0] · refine cfc_cases (‖·‖ < c) a f (by simpa) fun hf ha ↦ ?_ simp only [← cfc_apply f a, (IsGreatest.norm_cfc f a hf ha |>.lt_iff)] rintro - ⟨x, hx, rfl⟩ exact h x hx lemma norm_cfc_lt_iff (f : 𝕜 → 𝕜) (a : A) {c : ℝ} (hc : 0 < c) (hf : ContinuousOn f (σ 𝕜 a) := by cfc_cont_tac) (ha : p a := by cfc_tac) : ‖cfc f a‖ < c ↔ ∀ x ∈ σ 𝕜 a, ‖f x‖ < c := ⟨fun h _ hx ↦ norm_apply_le_norm_cfc f a hx hf ha |>.trans_lt h, norm_cfc_lt hc⟩ open NNReal lemma nnnorm_cfc_le {f : 𝕜 → 𝕜} {a : A} (c : ℝ≥0) (h : ∀ x ∈ σ 𝕜 a, ‖f x‖₊ ≤ c) : ‖cfc f a‖₊ ≤ c := norm_cfc_le c.2 h lemma nnnorm_cfc_le_iff (f : 𝕜 → 𝕜) (a : A) (c : ℝ≥0) (hf : ContinuousOn f (σ 𝕜 a) := by cfc_cont_tac) (ha : p a := by cfc_tac) : ‖cfc f a‖₊ ≤ c ↔ ∀ x ∈ σ 𝕜 a, ‖f x‖₊ ≤ c := norm_cfc_le_iff f a c.2 lemma nnnorm_cfc_lt {f : 𝕜 → 𝕜} {a : A} {c : ℝ≥0} (hc : 0 < c) (h : ∀ x ∈ σ 𝕜 a, ‖f x‖₊ < c) : ‖cfc f a‖₊ < c := norm_cfc_lt hc h lemma nnnorm_cfc_lt_iff (f : 𝕜 → 𝕜) (a : A) {c : ℝ≥0} (hc : 0 < c) (hf : ContinuousOn f (σ 𝕜 a) := by cfc_cont_tac) (ha : p a := by cfc_tac) : ‖cfc f a‖₊ < c ↔ ∀ x ∈ σ 𝕜 a, ‖f x‖₊ < c := norm_cfc_lt_iff f a hc namespace IsometricContinuousFunctionalCalculus lemma isGreatest_norm_spectrum [Nontrivial A] (a : A) (ha : p a := by cfc_tac) : IsGreatest ((‖·‖) '' spectrum 𝕜 a) ‖a‖ := by simpa only [cfc_id 𝕜 a] using IsGreatest.norm_cfc (id : 𝕜 → 𝕜) a lemma norm_spectrum_le (a : A) ⦃x : 𝕜⦄ (hx : x ∈ σ 𝕜 a) (ha : p a := by cfc_tac) : ‖x‖ ≤ ‖a‖ := by simpa only [cfc_id 𝕜 a] using norm_apply_le_norm_cfc (id : 𝕜 → 𝕜) a hx lemma isGreatest_nnnorm_spectrum [Nontrivial A] (a : A) (ha : p a := by cfc_tac) : IsGreatest ((‖·‖₊) '' spectrum 𝕜 a) ‖a‖₊ := by simpa only [cfc_id 𝕜 a] using IsGreatest.nnnorm_cfc (id : 𝕜 → 𝕜) a lemma nnnorm_spectrum_le (a : A) ⦃x : 𝕜⦄ (hx : x ∈ σ 𝕜 a) (ha : p a := by cfc_tac) : ‖x‖₊ ≤ ‖a‖₊ := by simpa only [cfc_id 𝕜 a] using nnnorm_apply_le_nnnorm_cfc (id : 𝕜 → 𝕜) a hx end IsometricContinuousFunctionalCalculus end NormedRing namespace SpectrumRestricts variable {R S A : Type*} {p q : A → Prop} variable [Semifield R] [StarRing R] [MetricSpace R] [IsTopologicalSemiring R] [ContinuousStar R] variable [Semifield S] [StarRing S] [MetricSpace S] [IsTopologicalSemiring S] [ContinuousStar S] variable [Ring A] [StarRing A] [Algebra S A] variable [Algebra R S] [Algebra R A] [IsScalarTower R S A] [StarModule R S] [ContinuousSMul R S] variable [MetricSpace A] [IsometricContinuousFunctionalCalculus S A q] variable [CompleteSpace R] [ContinuousMap.UniqueHom R A] open scoped ContinuousFunctionalCalculus in protected theorem isometric_cfc (f : C(S, R)) (halg : Isometry (algebraMap R S)) (h0 : p 0) (h : ∀ a, p a ↔ q a ∧ SpectrumRestricts a f) : IsometricContinuousFunctionalCalculus R A p where toContinuousFunctionalCalculus := SpectrumRestricts.cfc f halg.isUniformEmbedding h0 h isometric a ha := by obtain ⟨ha', haf⟩ := h a |>.mp ha have _inst (a : A) : CompactSpace (σ R a) := by rw [← isCompact_iff_compactSpace, ← spectrum.preimage_algebraMap S] exact halg.isClosedEmbedding.isCompact_preimage <| ContinuousFunctionalCalculus.isCompact_spectrum a have := SpectrumRestricts.cfc f halg.isUniformEmbedding h0 h rw [cfcHom_eq_restrict f halg.isUniformEmbedding ha ha' haf] refine .of_dist_eq fun g₁ g₂ ↦ ?_ simp only [starAlgHom_apply, isometry_cfcHom a ha' |>.dist_eq] refine le_antisymm ?_ ?_ all_goals refine ContinuousMap.dist_le dist_nonneg |>.mpr fun x ↦ ?_ · simpa [halg.dist_eq] using ContinuousMap.dist_apply_le_dist _ · let x' : σ S a := Subtype.map (algebraMap R S) (fun _ ↦ spectrum.algebraMap_mem S) x apply le_of_eq_of_le ?_ <| ContinuousMap.dist_apply_le_dist x' simp only [ContinuousMap.comp_apply, ContinuousMap.coe_mk, StarAlgHom.ofId_apply, halg.dist_eq, x'] congr! all_goals ext; exact haf.left_inv _ |>.symm end SpectrumRestricts end Unital /-! ### Isometric continuous functional calculus for non-unital algebras -/ section NonUnital /-- An extension of the `NonUnitalContinuousFunctionalCalculus` requiring that `cfcₙHom` is an isometry. -/ class NonUnitalIsometricContinuousFunctionalCalculus (R A : Type*) (p : outParam (A → Prop)) [CommSemiring R] [Nontrivial R] [StarRing R] [MetricSpace R] [IsTopologicalSemiring R] [ContinuousStar R] [NonUnitalRing A] [StarRing A] [MetricSpace A] [Module R A] [IsScalarTower R A A] [SMulCommClass R A A] : Prop extends NonUnitalContinuousFunctionalCalculus R A p where isometric (a : A) (ha : p a) : Isometry (cfcₙHom ha (R := R)) section MetricSpace variable {R A : Type*} {p : outParam (A → Prop)} variable [CommSemiring R] [Nontrivial R] [StarRing R] [MetricSpace R] [IsTopologicalSemiring R] variable [ContinuousStar R] variable [NonUnitalRing A] [StarRing A] [MetricSpace A] [Module R A] variable [IsScalarTower R A A] [SMulCommClass R A A] open scoped NonUnitalContinuousFunctionalCalculus variable [NonUnitalIsometricContinuousFunctionalCalculus R A p] lemma isometry_cfcₙHom (a : A) (ha : p a := by cfc_tac) : Isometry (cfcₙHom (show p a from ha) (R := R)) := NonUnitalIsometricContinuousFunctionalCalculus.isometric a ha end MetricSpace section NormedRing variable {𝕜 A : Type*} {p : outParam (A → Prop)} variable [RCLike 𝕜] [NonUnitalNormedRing A] [StarRing A] [NormedSpace 𝕜 A] [IsScalarTower 𝕜 A A] variable [SMulCommClass 𝕜 A A] variable [NonUnitalIsometricContinuousFunctionalCalculus 𝕜 A p] open NonUnitalIsometricContinuousFunctionalCalculus open scoped ContinuousMapZero NonUnitalContinuousFunctionalCalculus lemma norm_cfcₙHom (a : A) (f : C(σₙ 𝕜 a, 𝕜)₀) (ha : p a := by cfc_tac) : ‖cfcₙHom (show p a from ha) f‖ = ‖f‖ := by refine isometry_cfcₙHom a |>.norm_map_of_map_zero (map_zero _) f lemma nnnorm_cfcₙHom (a : A) (f : C(σₙ 𝕜 a, 𝕜)₀) (ha : p a := by cfc_tac) : ‖cfcₙHom (show p a from ha) f‖₊ = ‖f‖₊ := Subtype.ext <| norm_cfcₙHom a f ha lemma IsGreatest.norm_cfcₙ (f : 𝕜 → 𝕜) (a : A) (hf : ContinuousOn f (σₙ 𝕜 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : p a := by cfc_tac) : IsGreatest ((fun x ↦ ‖f x‖) '' σₙ 𝕜 a) ‖cfcₙ f a‖ := by obtain ⟨x, hx⟩ := NonUnitalContinuousFunctionalCalculus.isCompact_quasispectrum a |>.image_of_continuousOn hf.norm |>.exists_isGreatest <| (quasispectrum.nonempty 𝕜 a).image _ obtain ⟨x, hx', rfl⟩ := hx.1 convert hx rw [cfcₙ_apply f a, norm_cfcₙHom a _] apply le_antisymm · apply ContinuousMap.norm_le _ (norm_nonneg _) |>.mpr rintro ⟨y, hy⟩ exact hx.2 ⟨y, hy, rfl⟩ · exact le_trans (by simp) <| ContinuousMap.norm_coe_le_norm _ (⟨x, hx'⟩ : σₙ 𝕜 a) lemma IsGreatest.nnnorm_cfcₙ (f : 𝕜 → 𝕜) (a : A) (hf : ContinuousOn f (σₙ 𝕜 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : p a := by cfc_tac) : IsGreatest ((fun x ↦ ‖f x‖₊) '' σₙ 𝕜 a) ‖cfcₙ f a‖₊ := by convert Real.toNNReal_mono.map_isGreatest (.norm_cfcₙ f a) all_goals simp [Set.image_image, norm_toNNReal] lemma norm_apply_le_norm_cfcₙ (f : 𝕜 → 𝕜) (a : A) ⦃x : 𝕜⦄ (hx : x ∈ σₙ 𝕜 a) (hf : ContinuousOn f (σₙ 𝕜 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : p a := by cfc_tac) : ‖f x‖ ≤ ‖cfcₙ f a‖ := IsGreatest.norm_cfcₙ f a hf hf₀ ha |>.2 ⟨x, hx, rfl⟩ lemma nnnorm_apply_le_nnnorm_cfcₙ (f : 𝕜 → 𝕜) (a : A) ⦃x : 𝕜⦄ (hx : x ∈ σₙ 𝕜 a) (hf : ContinuousOn f (σₙ 𝕜 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : p a := by cfc_tac) : ‖f x‖₊ ≤ ‖cfcₙ f a‖₊ := IsGreatest.nnnorm_cfcₙ f a hf hf₀ ha |>.2 ⟨x, hx, rfl⟩ lemma norm_cfcₙ_le {f : 𝕜 → 𝕜} {a : A} {c : ℝ} (h : ∀ x ∈ σₙ 𝕜 a, ‖f x‖ ≤ c) : ‖cfcₙ f a‖ ≤ c := by refine cfcₙ_cases (‖·‖ ≤ c) a f ?_ fun hf hf0 ha ↦ ?_ · simpa using (norm_nonneg _).trans <| h 0 (quasispectrum.zero_mem 𝕜 a) · simp only [← cfcₙ_apply f a, isLUB_le_iff (IsGreatest.norm_cfcₙ f a hf hf0 ha |>.isLUB)] rintro - ⟨x, hx, rfl⟩ exact h x hx lemma norm_cfcₙ_le_iff (f : 𝕜 → 𝕜) (a : A) (c : ℝ) (hf : ContinuousOn f (σₙ 𝕜 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : p a := by cfc_tac) : ‖cfcₙ f a‖ ≤ c ↔ ∀ x ∈ σₙ 𝕜 a, ‖f x‖ ≤ c := ⟨fun h _ hx ↦ norm_apply_le_norm_cfcₙ f a hx hf hf₀ ha |>.trans h, norm_cfcₙ_le⟩ lemma norm_cfcₙ_lt {f : 𝕜 → 𝕜} {a : A} {c : ℝ} (h : ∀ x ∈ σₙ 𝕜 a, ‖f x‖ < c) : ‖cfcₙ f a‖ < c := by refine cfcₙ_cases (‖·‖ < c) a f ?_ fun hf hf0 ha ↦ ?_ · simpa using (norm_nonneg _).trans_lt <| h 0 (quasispectrum.zero_mem 𝕜 a) · simp only [← cfcₙ_apply f a, (IsGreatest.norm_cfcₙ f a hf hf0 ha |>.lt_iff)] rintro - ⟨x, hx, rfl⟩ exact h x hx lemma norm_cfcₙ_lt_iff (f : 𝕜 → 𝕜) (a : A) (c : ℝ) (hf : ContinuousOn f (σₙ 𝕜 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : p a := by cfc_tac) : ‖cfcₙ f a‖ < c ↔ ∀ x ∈ σₙ 𝕜 a, ‖f x‖ < c := ⟨fun h _ hx ↦ norm_apply_le_norm_cfcₙ f a hx hf hf₀ ha |>.trans_lt h, norm_cfcₙ_lt⟩ open NNReal lemma nnnorm_cfcₙ_le {f : 𝕜 → 𝕜} {a : A} {c : ℝ≥0} (h : ∀ x ∈ σₙ 𝕜 a, ‖f x‖₊ ≤ c) : ‖cfcₙ f a‖₊ ≤ c := norm_cfcₙ_le h lemma nnnorm_cfcₙ_le_iff (f : 𝕜 → 𝕜) (a : A) (c : ℝ≥0) (hf : ContinuousOn f (σₙ 𝕜 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : p a := by cfc_tac) : ‖cfcₙ f a‖₊ ≤ c ↔ ∀ x ∈ σₙ 𝕜 a, ‖f x‖₊ ≤ c := norm_cfcₙ_le_iff f a c.1 hf hf₀ ha lemma nnnorm_cfcₙ_lt {f : 𝕜 → 𝕜} {a : A} {c : ℝ≥0} (h : ∀ x ∈ σₙ 𝕜 a, ‖f x‖₊ < c) : ‖cfcₙ f a‖₊ < c := norm_cfcₙ_lt h lemma nnnorm_cfcₙ_lt_iff (f : 𝕜 → 𝕜) (a : A) (c : ℝ≥0) (hf : ContinuousOn f (σₙ 𝕜 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : p a := by cfc_tac) : ‖cfcₙ f a‖₊ < c ↔ ∀ x ∈ σₙ 𝕜 a, ‖f x‖₊ < c := norm_cfcₙ_lt_iff f a c.1 hf hf₀ ha namespace NonUnitalIsometricContinuousFunctionalCalculus lemma isGreatest_norm_quasispectrum (a : A) (ha : p a := by cfc_tac) : IsGreatest ((‖·‖) '' σₙ 𝕜 a) ‖a‖ := by simpa only [cfcₙ_id 𝕜 a] using IsGreatest.norm_cfcₙ (id : 𝕜 → 𝕜) a lemma norm_quasispectrum_le (a : A) ⦃x : 𝕜⦄ (hx : x ∈ σₙ 𝕜 a) (ha : p a := by cfc_tac) : ‖x‖ ≤ ‖a‖ := by simpa only [cfcₙ_id 𝕜 a] using norm_apply_le_norm_cfcₙ (id : 𝕜 → 𝕜) a hx lemma isGreatest_nnnorm_quasispectrum (a : A) (ha : p a := by cfc_tac) : IsGreatest ((‖·‖₊) '' σₙ 𝕜 a) ‖a‖₊ := by simpa only [cfcₙ_id 𝕜 a] using IsGreatest.nnnorm_cfcₙ (id : 𝕜 → 𝕜) a lemma nnnorm_quasispectrum_le (a : A) ⦃x : 𝕜⦄ (hx : x ∈ σₙ 𝕜 a) (ha : p a := by cfc_tac) : ‖x‖₊ ≤ ‖a‖₊ := by simpa only [cfcₙ_id 𝕜 a] using nnnorm_apply_le_nnnorm_cfcₙ (id : 𝕜 → 𝕜) a hx end NonUnitalIsometricContinuousFunctionalCalculus end NormedRing namespace QuasispectrumRestricts open NonUnitalIsometricContinuousFunctionalCalculus variable {R S A : Type*} {p q : A → Prop} variable [Semifield R] [StarRing R] [MetricSpace R] [IsTopologicalSemiring R] [ContinuousStar R] variable [Field S] [StarRing S] [MetricSpace S] [IsTopologicalRing S] [ContinuousStar S] variable [NonUnitalRing A] [StarRing A] [Module S A] [IsScalarTower S A A] variable [SMulCommClass S A A] variable [Algebra R S] [Module R A] [IsScalarTower R S A] [StarModule R S] [ContinuousSMul R S] variable [IsScalarTower R A A] [SMulCommClass R A A] variable [MetricSpace A] [NonUnitalIsometricContinuousFunctionalCalculus S A q] variable [CompleteSpace R] [ContinuousMapZero.UniqueHom R A] open scoped NonUnitalContinuousFunctionalCalculus in protected theorem isometric_cfc (f : C(S, R)) (halg : Isometry (algebraMap R S)) (h0 : p 0) (h : ∀ a, p a ↔ q a ∧ QuasispectrumRestricts a f) : NonUnitalIsometricContinuousFunctionalCalculus R A p where toNonUnitalContinuousFunctionalCalculus := QuasispectrumRestricts.cfc f halg.isUniformEmbedding h0 h isometric a ha := by obtain ⟨ha', haf⟩ := h a |>.mp ha have _inst (a : A) : CompactSpace (σₙ R a) := by rw [← isCompact_iff_compactSpace, ← quasispectrum.preimage_algebraMap S] exact halg.isClosedEmbedding.isCompact_preimage <| NonUnitalContinuousFunctionalCalculus.isCompact_quasispectrum a have := QuasispectrumRestricts.cfc f halg.isUniformEmbedding h0 h rw [cfcₙHom_eq_restrict f halg.isUniformEmbedding ha ha' haf] refine .of_dist_eq fun g₁ g₂ ↦ ?_ simp only [nonUnitalStarAlgHom_apply, isometry_cfcₙHom a ha' |>.dist_eq] refine le_antisymm ?_ ?_ all_goals refine ContinuousMap.dist_le dist_nonneg |>.mpr fun x ↦ ?_ · simpa [halg.dist_eq] using ContinuousMap.dist_apply_le_dist _ · let x' : σₙ S a := Subtype.map (algebraMap R S) (fun _ ↦ quasispectrum.algebraMap_mem S) x apply le_of_eq_of_le ?_ <| ContinuousMap.dist_apply_le_dist x' simp only [ContinuousMap.coe_coe, ContinuousMapZero.comp_apply, ContinuousMapZero.coe_mk, ContinuousMap.coe_mk, StarAlgHom.ofId_apply, halg.dist_eq, x'] congr! 2 all_goals ext; exact haf.left_inv _ |>.symm end QuasispectrumRestricts end NonUnital /-! ### Instances of isometric continuous functional calculi The instances for `ℝ` and `ℂ` can be found in `Mathlib/Analysis/CStarAlgebra/ContinuousFunctionalCalculus/Basic.lean`, as those require an actual `CStarAlgebra` instance on `A`, whereas the one for `ℝ≥0` is simply inherited from an existing instance for `ℝ`. -/ section Instances section Unital variable {A : Type*} [NormedRing A] [PartialOrder A] [StarRing A] [StarOrderedRing A] variable [NormedAlgebra ℝ A] [IsometricContinuousFunctionalCalculus ℝ A IsSelfAdjoint] variable [NonnegSpectrumClass ℝ A] open NNReal in instance Nonneg.instIsometricContinuousFunctionalCalculus : IsometricContinuousFunctionalCalculus ℝ≥0 A (0 ≤ ·) := SpectrumRestricts.isometric_cfc (q := IsSelfAdjoint) ContinuousMap.realToNNReal isometry_subtype_coe le_rfl (fun _ ↦ nonneg_iff_isSelfAdjoint_and_spectrumRestricts) end Unital section NonUnital variable {A : Type*} [NonUnitalNormedRing A] [PartialOrder A] [StarRing A] [StarOrderedRing A] variable [NormedSpace ℝ A] [IsScalarTower ℝ A A] [SMulCommClass ℝ A A] variable [NonUnitalIsometricContinuousFunctionalCalculus ℝ A IsSelfAdjoint] variable [NonnegSpectrumClass ℝ A] open NNReal in instance Nonneg.instNonUnitalIsometricContinuousFunctionalCalculus : NonUnitalIsometricContinuousFunctionalCalculus ℝ≥0 A (0 ≤ ·) := QuasispectrumRestricts.isometric_cfc (q := IsSelfAdjoint) ContinuousMap.realToNNReal isometry_subtype_coe le_rfl (fun _ ↦ nonneg_iff_isSelfAdjoint_and_quasispectrumRestricts) end NonUnital end Instances /-! ### Properties specific to `ℝ≥0` -/ section NNReal open NNReal section Unital variable {A : Type*} [NormedRing A] [StarRing A] [NormedAlgebra ℝ A] [PartialOrder A] variable [StarOrderedRing A] [IsometricContinuousFunctionalCalculus ℝ A IsSelfAdjoint] variable [NonnegSpectrumClass ℝ A] lemma IsGreatest.nnnorm_cfc_nnreal [Nontrivial A] (f : ℝ≥0 → ℝ≥0) (a : A) (hf : ContinuousOn f (σ ℝ≥0 a) := by cfc_cont_tac) (ha : 0 ≤ a := by cfc_tac) : IsGreatest (f '' σ ℝ≥0 a) ‖cfc f a‖₊ := by rw [cfc_nnreal_eq_real] obtain ⟨-, ha'⟩ := nonneg_iff_isSelfAdjoint_and_spectrumRestricts.mp ha convert IsGreatest.nnnorm_cfc (fun x : ℝ ↦ (f x.toNNReal : ℝ)) a ?hf_cont case hf_cont => exact continuous_subtype_val.comp_continuousOn <| ContinuousOn.comp ‹_› continuous_real_toNNReal.continuousOn <| ha'.image ▸ Set.mapsTo_image .. ext x constructor all_goals rintro ⟨x, hx, rfl⟩ · exact ⟨x, spectrum.algebraMap_mem ℝ hx, by simp⟩ · exact ⟨x.toNNReal, ha'.apply_mem hx, by simp⟩ lemma apply_le_nnnorm_cfc_nnreal (f : ℝ≥0 → ℝ≥0) (a : A) ⦃x : ℝ≥0⦄ (hx : x ∈ σ ℝ≥0 a) (hf : ContinuousOn f (σ ℝ≥0 a) := by cfc_cont_tac) (ha : 0 ≤ a := by cfc_tac) : f x ≤ ‖cfc f a‖₊ := by revert hx nontriviality A exact (IsGreatest.nnnorm_cfc_nnreal f a hf ha |>.2 ⟨x, ·, rfl⟩) lemma nnnorm_cfc_nnreal_le {f : ℝ≥0 → ℝ≥0} {a : A} {c : ℝ≥0} (h : ∀ x ∈ σ ℝ≥0 a, f x ≤ c) : ‖cfc f a‖₊ ≤ c := by obtain (_ | _) := subsingleton_or_nontrivial A · rw [Subsingleton.elim (cfc f a) 0] simp · refine cfc_cases (‖·‖₊ ≤ c) a f (by simp) fun hf ha ↦ ?_ simp only [← cfc_apply f a, isLUB_le_iff (IsGreatest.nnnorm_cfc_nnreal f a hf ha |>.isLUB)] rintro - ⟨x, hx, rfl⟩ exact h x hx lemma nnnorm_cfc_nnreal_le_iff (f : ℝ≥0 → ℝ≥0) (a : A) (c : ℝ≥0) (hf : ContinuousOn f (σ ℝ≥0 a) := by cfc_cont_tac) (ha : 0 ≤ a := by cfc_tac) : ‖cfc f a‖₊ ≤ c ↔ ∀ x ∈ σ ℝ≥0 a, f x ≤ c := ⟨fun h _ hx ↦ apply_le_nnnorm_cfc_nnreal f a hx hf ha |>.trans h, nnnorm_cfc_nnreal_le⟩ lemma nnnorm_cfc_nnreal_lt {f : ℝ≥0 → ℝ≥0} {a : A} {c : ℝ≥0} (hc : 0 < c) (h : ∀ x ∈ σ ℝ≥0 a, f x < c) : ‖cfc f a‖₊ < c := by obtain (_ | _) := subsingleton_or_nontrivial A · rw [Subsingleton.elim (cfc f a) 0] simpa · refine cfc_cases (‖·‖₊ < c) a f (by simpa) fun hf ha ↦ ?_ simp only [← cfc_apply f a, (IsGreatest.nnnorm_cfc_nnreal f a hf ha |>.lt_iff)] rintro - ⟨x, hx, rfl⟩ exact h x hx lemma nnnorm_cfc_nnreal_lt_iff (f : ℝ≥0 → ℝ≥0) (a : A) {c : ℝ≥0} (hc : 0 < c) (hf : ContinuousOn f (σ ℝ≥0 a) := by cfc_cont_tac) (ha : 0 ≤ a := by cfc_tac) : ‖cfc f a‖₊ < c ↔ ∀ x ∈ σ ℝ≥0 a, f x < c := ⟨fun h _ hx ↦ apply_le_nnnorm_cfc_nnreal f a hx hf ha |>.trans_lt h, nnnorm_cfc_nnreal_lt hc⟩ namespace IsometricContinuousFunctionalCalculus lemma isGreatest_spectrum [Nontrivial A] (a : A) (ha : 0 ≤ a := by cfc_tac) : IsGreatest (σ ℝ≥0 a) ‖a‖₊ := by simpa [cfc_id ℝ≥0 a] using IsGreatest.nnnorm_cfc_nnreal id a lemma spectrum_le (a : A) ⦃x : ℝ≥0⦄ (hx : x ∈ σ ℝ≥0 a) (ha : 0 ≤ a := by cfc_tac) : x ≤ ‖a‖₊ := by simpa [cfc_id ℝ≥0 a] using apply_le_nnnorm_cfc_nnreal id a hx end IsometricContinuousFunctionalCalculus open IsometricContinuousFunctionalCalculus in lemma MonotoneOn.nnnorm_cfc [Nontrivial A] (f : ℝ≥0 → ℝ≥0) (a : A) (hf : MonotoneOn f (σ ℝ≥0 a)) (hf₂ : ContinuousOn f (σ ℝ≥0 a) := by cfc_cont_tac) (ha : 0 ≤ a := by cfc_tac) : ‖cfc f a‖₊ = f ‖a‖₊ := IsGreatest.nnnorm_cfc_nnreal f a |>.unique <| hf.map_isGreatest (isGreatest_spectrum a) end Unital section NonUnital variable {A : Type*} [NonUnitalNormedRing A] [StarRing A] [NormedSpace ℝ A] variable [IsScalarTower ℝ A A] [SMulCommClass ℝ A A] [PartialOrder A] variable [StarOrderedRing A] [NonUnitalIsometricContinuousFunctionalCalculus ℝ A IsSelfAdjoint] variable [NonnegSpectrumClass ℝ A] lemma IsGreatest.nnnorm_cfcₙ_nnreal (f : ℝ≥0 → ℝ≥0) (a : A) (hf : ContinuousOn f (σₙ ℝ≥0 a) := by cfc_cont_tac) (hf0 : f 0 = 0 := by cfc_zero_tac) (ha : 0 ≤ a := by cfc_tac) : IsGreatest (f '' σₙ ℝ≥0 a) ‖cfcₙ f a‖₊ := by rw [cfcₙ_nnreal_eq_real] obtain ⟨-, ha'⟩ := nonneg_iff_isSelfAdjoint_and_quasispectrumRestricts.mp ha convert IsGreatest.nnnorm_cfcₙ (fun x : ℝ ↦ (f x.toNNReal : ℝ)) a ?hf_cont (by simpa) case hf_cont => exact continuous_subtype_val.comp_continuousOn <| ContinuousOn.comp ‹_› continuous_real_toNNReal.continuousOn <| ha'.image ▸ Set.mapsTo_image .. ext x constructor all_goals rintro ⟨x, hx, rfl⟩ · exact ⟨x, quasispectrum.algebraMap_mem ℝ hx, by simp⟩ · exact ⟨x.toNNReal, ha'.apply_mem hx, by simp⟩ lemma apply_le_nnnorm_cfcₙ_nnreal (f : ℝ≥0 → ℝ≥0) (a : A) ⦃x : ℝ≥0⦄ (hx : x ∈ σₙ ℝ≥0 a) (hf : ContinuousOn f (σₙ ℝ≥0 a) := by cfc_cont_tac) (hf0 : f 0 = 0 := by cfc_zero_tac) (ha : 0 ≤ a := by cfc_tac) : f x ≤ ‖cfcₙ f a‖₊ := by revert hx exact (IsGreatest.nnnorm_cfcₙ_nnreal f a hf hf0 ha |>.2 ⟨x, ·, rfl⟩) lemma nnnorm_cfcₙ_nnreal_le {f : ℝ≥0 → ℝ≥0} {a : A} {c : ℝ≥0} (h : ∀ x ∈ σₙ ℝ≥0 a, f x ≤ c) : ‖cfcₙ f a‖₊ ≤ c := by refine cfcₙ_cases (‖·‖₊ ≤ c) a f (by simp) fun hf hf0 ha ↦ ?_ simp only [← cfcₙ_apply f a, isLUB_le_iff (IsGreatest.nnnorm_cfcₙ_nnreal f a hf hf0 ha |>.isLUB)] rintro - ⟨x, hx, rfl⟩ exact h x hx lemma nnnorm_cfcₙ_nnreal_le_iff (f : ℝ≥0 → ℝ≥0) (a : A) (c : ℝ≥0) (hf : ContinuousOn f (σₙ ℝ≥0 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : 0 ≤ a := by cfc_tac) : ‖cfcₙ f a‖₊ ≤ c ↔ ∀ x ∈ σₙ ℝ≥0 a, f x ≤ c := ⟨fun h _ hx ↦ apply_le_nnnorm_cfcₙ_nnreal f a hx hf hf₀ ha |>.trans h, nnnorm_cfcₙ_nnreal_le⟩ lemma nnnorm_cfcₙ_nnreal_lt {f : ℝ≥0 → ℝ≥0} {a : A} {c : ℝ≥0} (h : ∀ x ∈ σₙ ℝ≥0 a, f x < c) : ‖cfcₙ f a‖₊ < c := by refine cfcₙ_cases (‖·‖₊ < c) a f ?_ fun hf hf0 ha ↦ ?_ · simpa using zero_le (f 0) |>.trans_lt <| h 0 (quasispectrum.zero_mem ℝ≥0 _) · simp only [← cfcₙ_apply f a, (IsGreatest.nnnorm_cfcₙ_nnreal f a hf hf0 ha |>.lt_iff)] rintro - ⟨x, hx, rfl⟩ exact h x hx lemma nnnorm_cfcₙ_nnreal_lt_iff (f : ℝ≥0 → ℝ≥0) (a : A) (c : ℝ≥0) (hf : ContinuousOn f (σₙ ℝ≥0 a) := by cfc_cont_tac) (hf₀ : f 0 = 0 := by cfc_zero_tac) (ha : 0 ≤ a := by cfc_tac) : ‖cfcₙ f a‖₊ < c ↔ ∀ x ∈ σₙ ℝ≥0 a, f x < c := ⟨fun h _ hx ↦ apply_le_nnnorm_cfcₙ_nnreal f a hx hf hf₀ ha |>.trans_lt h, nnnorm_cfcₙ_nnreal_lt⟩ namespace NonUnitalIsometricContinuousFunctionalCalculus lemma isGreatest_quasispectrum (a : A) (ha : 0 ≤ a := by cfc_tac) : IsGreatest (σₙ ℝ≥0 a) ‖a‖₊ := by simpa [cfcₙ_id ℝ≥0 a] using IsGreatest.nnnorm_cfcₙ_nnreal id a lemma quasispectrum_le (a : A) ⦃x : ℝ≥0⦄ (hx : x ∈ σₙ ℝ≥0 a) (ha : 0 ≤ a := by cfc_tac) : x ≤ ‖a‖₊ := by simpa [cfcₙ_id ℝ≥0 a] using apply_le_nnnorm_cfcₙ_nnreal id a hx end NonUnitalIsometricContinuousFunctionalCalculus open NonUnitalIsometricContinuousFunctionalCalculus in lemma MonotoneOn.nnnorm_cfcₙ (f : ℝ≥0 → ℝ≥0) (a : A) (hf : MonotoneOn f (σₙ ℝ≥0 a)) (hf₂ : ContinuousOn f (σₙ ℝ≥0 a) := by cfc_cont_tac) (hf0 : f 0 = 0 := by cfc_zero_tac) (ha : 0 ≤ a := by cfc_tac) : ‖cfcₙ f a‖₊ = f ‖a‖₊ := IsGreatest.nnnorm_cfcₙ_nnreal f a |>.unique <| hf.map_isGreatest (isGreatest_quasispectrum a) end NonUnital end NNReal /-! ### Non-unital instance for unital algebras -/ namespace IsometricContinuousFunctionalCalculus variable {𝕜 A : Type*} {p : outParam (A → Prop)} variable [RCLike 𝕜] [NormedRing A] [StarRing A] [NormedAlgebra 𝕜 A] variable [IsometricContinuousFunctionalCalculus 𝕜 A p] open scoped ContinuousFunctionalCalculus in /-- An isometric continuous functional calculus on a unital algebra yields to a non-unital one. -/ instance toNonUnital : NonUnitalIsometricContinuousFunctionalCalculus 𝕜 A p where isometric a ha := by have : CompactSpace (σₙ 𝕜 a) := by have h_cpct : CompactSpace (spectrum 𝕜 a) := inferInstance simp only [← isCompact_iff_compactSpace, quasispectrum_eq_spectrum_union_zero] at h_cpct ⊢ exact h_cpct |>.union isCompact_singleton rw [cfcₙHom_eq_cfcₙHom_of_cfcHom, cfcₙHom_of_cfcHom] refine isometry_cfcHom a |>.comp ?_ simp only [MulHom.coe_coe, NonUnitalStarAlgHom.coe_toNonUnitalAlgHom] refine AddMonoidHomClass.isometry_of_norm _ fun f ↦ ?_ let ι : C(σ 𝕜 a, σₙ 𝕜 a) := ⟨_, continuous_inclusion <| spectrum_subset_quasispectrum 𝕜 a⟩ change ‖(f : C(σₙ 𝕜 a, 𝕜)).comp ι‖ = ‖(f : C(σₙ 𝕜 a, 𝕜))‖ apply le_antisymm (ContinuousMap.norm_le _ (by positivity) |>.mpr ?_) (ContinuousMap.norm_le _ (by positivity) |>.mpr ?_) · rintro ⟨x, hx⟩ exact (f : C(σₙ 𝕜 a, 𝕜)).norm_coe_le_norm ⟨x, spectrum_subset_quasispectrum 𝕜 a hx⟩ · rintro ⟨x, hx⟩ obtain (rfl | hx') : x = 0 ∨ x ∈ σ 𝕜 a := by simpa [quasispectrum_eq_spectrum_union_zero] using hx · change ‖f 0‖ ≤ _ simp · exact (f : C(σₙ 𝕜 a, 𝕜)).comp ι |>.norm_coe_le_norm ⟨x, hx'⟩ end IsometricContinuousFunctionalCalculus
Nonempty.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Logic.Function.Defs /-! # Nonempty types This file proves a few extra facts about `Nonempty`, which is defined in core Lean. ## Main declarations * `Nonempty.some`: Extracts a witness of nonemptiness using choice. Takes `Nonempty α` explicitly. * `Classical.arbitrary`: Extracts a witness of nonemptiness using choice. Takes `Nonempty α` as an instance. -/ section variable {α β : Sort*} @[simp] theorem Nonempty.forall {α} {p : Nonempty α → Prop} : (∀ h : Nonempty α, p h) ↔ ∀ a, p ⟨a⟩ := Iff.intro (fun h _ ↦ h _) fun h ⟨a⟩ ↦ h a @[simp] theorem Nonempty.exists {α} {p : Nonempty α → Prop} : (∃ h : Nonempty α, p h) ↔ ∃ a, p ⟨a⟩ := Iff.intro (fun ⟨⟨a⟩, h⟩ ↦ ⟨a, h⟩) fun ⟨a, h⟩ ↦ ⟨⟨a⟩, h⟩ -- Note: we set low priority here, to ensure it is not applied before `exists_prop` -- and `exists_const`. @[simp low] theorem exists_const_iff {α : Sort*} {P : Prop} : (∃ _ : α, P) ↔ Nonempty α ∧ P := Iff.intro (fun ⟨a, h⟩ ↦ ⟨⟨a⟩, h⟩) fun ⟨⟨a⟩, h⟩ ↦ ⟨a, h⟩ theorem exists_true_iff_nonempty {α : Sort*} : (∃ _ : α, True) ↔ Nonempty α := Iff.intro (fun ⟨a, _⟩ ↦ ⟨a⟩) fun ⟨a⟩ ↦ ⟨a, trivial⟩ theorem Nonempty.imp {α} {p : Prop} : (Nonempty α → p) ↔ (α → p) := Nonempty.forall theorem not_nonempty_iff_imp_false {α : Sort*} : ¬Nonempty α ↔ α → False := Nonempty.imp @[simp] theorem nonempty_psigma {α} {β : α → Sort*} : Nonempty (PSigma β) ↔ ∃ a : α, Nonempty (β a) := Iff.intro (fun ⟨⟨a, c⟩⟩ ↦ ⟨a, ⟨c⟩⟩) fun ⟨a, ⟨c⟩⟩ ↦ ⟨⟨a, c⟩⟩ @[simp] theorem nonempty_subtype {α} {p : α → Prop} : Nonempty (Subtype p) ↔ ∃ a : α, p a := Iff.intro (fun ⟨⟨a, h⟩⟩ ↦ ⟨a, h⟩) fun ⟨a, h⟩ ↦ ⟨⟨a, h⟩⟩ @[simp] theorem nonempty_pprod {α β} : Nonempty (PProd α β) ↔ Nonempty α ∧ Nonempty β := Iff.intro (fun ⟨⟨a, b⟩⟩ ↦ ⟨⟨a⟩, ⟨b⟩⟩) fun ⟨⟨a⟩, ⟨b⟩⟩ ↦ ⟨⟨a, b⟩⟩ @[simp] theorem nonempty_psum {α β} : Nonempty (α ⊕' β) ↔ Nonempty α ∨ Nonempty β := Iff.intro (fun ⟨h⟩ ↦ match h with | PSum.inl a => Or.inl ⟨a⟩ | PSum.inr b => Or.inr ⟨b⟩) fun h ↦ match h with | Or.inl ⟨a⟩ => ⟨PSum.inl a⟩ | Or.inr ⟨b⟩ => ⟨PSum.inr b⟩ @[simp] theorem nonempty_plift {α} : Nonempty (PLift α) ↔ Nonempty α := Iff.intro (fun ⟨⟨a⟩⟩ ↦ ⟨a⟩) fun ⟨a⟩ ↦ ⟨⟨a⟩⟩ /-- Using `Classical.choice`, lifts a (`Prop`-valued) `Nonempty` instance to a (`Type`-valued) `Inhabited` instance. `Classical.inhabited_of_nonempty` already exists, in `Init/Classical.lean`, but the assumption is not a type class argument, which makes it unsuitable for some applications. -/ noncomputable def Classical.inhabited_of_nonempty' {α} [h : Nonempty α] : Inhabited α := ⟨Classical.choice h⟩ /-- Using `Classical.choice`, extracts a term from a `Nonempty` type. -/ protected noncomputable abbrev Nonempty.some {α} (h : Nonempty α) : α := Classical.choice h /-- Using `Classical.choice`, extracts a term from a `Nonempty` type. -/ protected noncomputable abbrev Classical.arbitrary (α) [h : Nonempty α] : α := Classical.choice h /-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty. `Nonempty` cannot be a `functor`, because `Functor` is restricted to `Type`. -/ theorem Nonempty.map {α β} (f : α → β) : Nonempty α → Nonempty β | ⟨h⟩ => ⟨f h⟩ protected theorem Nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : Nonempty α → Nonempty β → Nonempty γ | ⟨x⟩, ⟨y⟩ => ⟨f x y⟩ protected theorem Nonempty.congr {α β} (f : α → β) (g : β → α) : Nonempty α ↔ Nonempty β := ⟨Nonempty.map f, Nonempty.map g⟩ theorem Nonempty.elim_to_inhabited {α : Sort*} [h : Nonempty α] {p : Prop} (f : Inhabited α → p) : p := h.elim <| f ∘ Inhabited.mk theorem Classical.nonempty_pi {ι} {α : ι → Sort*} : Nonempty (∀ i, α i) ↔ ∀ i, Nonempty (α i) := ⟨fun ⟨f⟩ a ↦ ⟨f a⟩, @Pi.instNonempty _ _⟩ theorem subsingleton_of_not_nonempty {α : Sort*} (h : ¬Nonempty α) : Subsingleton α := ⟨fun x ↦ False.elim <| not_nonempty_iff_imp_false.mp h x⟩ theorem Function.Surjective.nonempty [h : Nonempty β] {f : α → β} (hf : Function.Surjective f) : Nonempty α := let ⟨y⟩ := h let ⟨x, _⟩ := hf y ⟨x⟩ end section variable {α β : Type*} {γ : α → Type*} @[simp] theorem nonempty_sigma : Nonempty (Σ a : α, γ a) ↔ ∃ a : α, Nonempty (γ a) := Iff.intro (fun ⟨⟨a, c⟩⟩ ↦ ⟨a, ⟨c⟩⟩) fun ⟨a, ⟨c⟩⟩ ↦ ⟨⟨a, c⟩⟩ @[simp] theorem nonempty_sum : Nonempty (α ⊕ β) ↔ Nonempty α ∨ Nonempty β := Iff.intro (fun ⟨h⟩ ↦ match h with | Sum.inl a => Or.inl ⟨a⟩ | Sum.inr b => Or.inr ⟨b⟩) fun h ↦ match h with | Or.inl ⟨a⟩ => ⟨Sum.inl a⟩ | Or.inr ⟨b⟩ => ⟨Sum.inr b⟩ @[simp] theorem nonempty_prod : Nonempty (α × β) ↔ Nonempty α ∧ Nonempty β := Iff.intro (fun ⟨⟨a, b⟩⟩ ↦ ⟨⟨a⟩, ⟨b⟩⟩) fun ⟨⟨a⟩, ⟨b⟩⟩ ↦ ⟨⟨a, b⟩⟩ @[simp] theorem nonempty_ulift : Nonempty (ULift α) ↔ Nonempty α := Iff.intro (fun ⟨⟨a⟩⟩ ↦ ⟨a⟩) fun ⟨a⟩ ↦ ⟨⟨a⟩⟩ end
Connected.lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import Mathlib.CategoryTheory.Limits.Creates import Mathlib.CategoryTheory.Comma.Over.Basic import Mathlib.CategoryTheory.IsConnected /-! # Connected limits in the over category Shows that the forgetful functor `Over B ⥤ C` creates connected limits, in particular `Over B` has any connected limit which `C` has. -/ universe v' u' v u -- morphism levels before object levels. See note [CategoryTheory universes]. noncomputable section open CategoryTheory CategoryTheory.Limits variable {J : Type u'} [Category.{v'} J] variable {C : Type u} [Category.{v} C] variable {X : C} namespace CategoryTheory.Over namespace CreatesConnected /-- (Impl) Given a diagram in the over category, produce a natural transformation from the diagram legs to the specific object. -/ def natTransInOver {B : C} (F : J ⥤ Over B) : F ⋙ forget B ⟶ (CategoryTheory.Functor.const J).obj B where app j := (F.obj j).hom /-- (Impl) Given a cone in the base category, raise it to a cone in the over category. Note this is where the connected assumption is used. -/ @[simps] def raiseCone [IsConnected J] {B : C} {F : J ⥤ Over B} (c : Cone (F ⋙ forget B)) : Cone F where pt := Over.mk (c.π.app (Classical.arbitrary J) ≫ (F.obj (Classical.arbitrary J)).hom) π := { app := fun j => Over.homMk (c.π.app j) (nat_trans_from_is_connected (c.π ≫ natTransInOver F) j _) naturality := by intro X Y f apply CommaMorphism.ext · simpa using (c.w f).symm · simp } theorem raised_cone_lowers_to_original [IsConnected J] {B : C} {F : J ⥤ Over B} (c : Cone (F ⋙ forget B)) : (forget B).mapCone (raiseCone c) = c := by cat_disch /-- (Impl) Show that the raised cone is a limit. -/ def raisedConeIsLimit [IsConnected J] {B : C} {F : J ⥤ Over B} {c : Cone (F ⋙ forget B)} (t : IsLimit c) : IsLimit (raiseCone c) where lift s := Over.homMk (t.lift ((forget B).mapCone s)) uniq s m K := by ext1 apply t.hom_ext intro j simp [← K j] end CreatesConnected /-- The forgetful functor from the over category creates any connected limit. -/ instance forgetCreatesConnectedLimits [IsConnected J] {B : C} : CreatesLimitsOfShape J (forget B) where CreatesLimit := createsLimitOfReflectsIso fun c t => { liftedCone := CreatesConnected.raiseCone c validLift := eqToIso (CreatesConnected.raised_cone_lowers_to_original c) makesLimit := CreatesConnected.raisedConeIsLimit t } /-- The over category has any connected limit which the original category has. -/ instance has_connected_limits {B : C} [IsConnected J] [HasLimitsOfShape J C] : HasLimitsOfShape J (Over B) where has_limit F := hasLimit_of_created F (forget B) end CategoryTheory.Over
all_fingroup.v
From mathcomp Require Export action. From mathcomp Require Export automorphism. From mathcomp Require Export fingroup. From mathcomp Require Export gproduct. From mathcomp Require Export morphism. From mathcomp Require Export perm. From mathcomp Require Export presentation. From mathcomp Require Export quotient.
falgebra.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path. From mathcomp Require Import choice fintype div tuple finfun bigop ssralg. From mathcomp Require Import finalg zmodp matrix vector poly. (******************************************************************************) (* Finite dimensional free algebras, usually known as F-algebras *) (* *) (* falgType K == the interface type for F-algebras over K; it simply *) (* joins the unitAlgType K and vectType K interfaces *) (* The HB class is called Falgebra. *) (* Any aT with an falgType structure inherits all the Vector, NzRing and *) (* Algebra operations, and supports the following additional operations: *) (* \dim_A M == (\dim M %/ dim A)%N -- free module dimension *) (* amull u == the linear function v |-> u * v, for u, v : aT *) (* amulr u == the linear function v |-> v * u, for u, v : aT *) (* 1, f * g, f ^+ n == the identity function, the composite g \o f, the nth *) (* iterate of f, for 1, f, g in 'End(aT) *) (* This is just the usual F-algebra structure on *) (* 'End(aT). It is NOT canonical by default, but can be *) (* activated by the line Import FalgLfun. Beware also *) (* that (f^-1)%VF is the linear function inverse, not *) (* the ring inverse of f (though they do coincide when *) (* f is injective). *) (* 1%VS == the line generated by 1 : aT *) (* (U * V)%VS == the smallest subspace of aT that contains all *) (* products u * v for u in U, v in V *) (* (U ^+ n)%VS == (U * U * ... * U), n-times. U ^+ 0 = 1%VS *) (* 'C[u]%VS == the centraliser subspace of the vector u *) (* 'C_U[v]%VS := (U :&: 'C[v])%VS *) (* 'C(V)%VS == the centraliser subspace of the subspace V *) (* 'C_U(V)%VS := (U :&: 'C(V))%VS *) (* 'Z(V)%VS == the center subspace of the subspace V *) (* agenv U == the smallest subalgebra containing U ^+ n for all n *) (* <<U; v>>%VS == agenv (U + <[v]>) (adjoin v to U) *) (* <<U & vs>>%VS == agenv (U + <<vs>>) (adjoin vs to U) *) (* {aspace aT} == a subType of {vspace aT} consisting of sub-algebras *) (* of aT (see below); for A : {aspace aT}, subvs_of A *) (* has a canonical falgType K structure *) (* is_aspace U <=> the characteristic predicate of {aspace aT} stating *) (* that U is closed under product and contains an *) (* identity element, := has_algid U && (U * U <= U)%VS *) (* algid A == the identity element of A : {aspace aT}, which need *) (* not be equal to 1 (indeed, in a Wedderburn *) (* decomposition it is not even a unit in aT) *) (* is_algid U e <-> e : aT is an identity element for the subspace U: *) (* e in U, e != 0 & e * u = u * e = u for all u in U *) (* has_algid U <=> there is an e such that is_algid U e *) (* [aspace of U] == a clone of an existing {aspace aT} structure on *) (* U : {vspace aT} (more instances of {aspace aT} will *) (* be defined in extFieldType) *) (* [aspace of U for A] == a clone of A : {aspace aT} for U : {vspace aT} *) (* 1%AS == the canonical sub-algebra 1%VS *) (* {:aT}%AS == the canonical full algebra *) (* <<U>>%AS == the canonical algebra for agenv U; note that this is *) (* unrelated to <<vs>>%VS, the subspace spanned by vs *) (* <<U; v>>%AS == the canonical algebra for <<U; v>>%VS *) (* <<U & vs>>%AS == the canonical algebra for <<U & vs>>%VS *) (* ahom_in U f <=> f : 'Hom(aT, rT) is a multiplicative homomorphism *) (* inside U, and in addition f 1 = 1 (even if U doesn't *) (* contain 1) *) (* Note that f @: U need not be a subalgebra when U is, *) (* as f could annilate U. *) (* 'AHom(aT, rT) == the type of algebra homomorphisms from aT to rT, *) (* where aT and rT ARE falgType structures. Elements of *) (* 'AHom(aT, rT) coerce to 'End(aT, rT) and aT -> rT *) (* 'AEnd(aT) == algebra endomorphisms of aT (:= 'AHom(aT, aT)) *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope aspace_scope. Declare Scope lrfun_scope. Local Open Scope ring_scope. Reserved Notation "{ 'aspace' T }" (format "{ 'aspace' T }"). Reserved Notation "<< U & vs >>" (format "<< U & vs >>"). Reserved Notation "<< U ; x >>" (format "<< U ; x >>"). Reserved Notation "''AHom' ( T , rT )" (format "''AHom' ( T , rT )"). Reserved Notation "''AEnd' ( T )" (format "''AEnd' ( T )"). Notation "\dim_ E V" := (divn (\dim V) (\dim E)) (at level 10, E at level 2, V at level 8, format "\dim_ E V") : nat_scope. Import GRing.Theory. (* Finite dimensional algebra *) #[short(type="falgType")] HB.structure Definition Falgebra (R : nzRingType) := { A of Vector R A & GRing.UnitAlgebra R A }. #[deprecated(since="mathcomp 2.0.0", note="Use falgType instead.")] Notation FalgType := falgType. (* Supply a default unitRing mixin for the default unitAlgType base type. *) HB.factory Record Algebra_isFalgebra (K : fieldType) A of Vector K A & GRing.Algebra K A := {}. HB.builders Context K A of Algebra_isFalgebra K A. Let vA : Vector.type K := A. Let am u := linfun (u \o* idfun : vA -> vA). Let uam := [pred u | lker (am u) == 0%VS]. Let vam := [fun u => if u \in uam then (am u)^-1%VF 1 else u]. Lemma amE u v : am u v = v * u. Proof. by rewrite lfunE. Qed. Lemma mulVr : {in uam, left_inverse 1 vam *%R}. Proof. by move=> u Uu; rewrite /= Uu -amE lker0_lfunVK. Qed. Lemma divrr : {in uam, right_inverse 1 vam *%R}. Proof. by move=> u Uu; apply/(lker0P Uu); rewrite !amE -mulrA mulVr // mul1r mulr1. Qed. Lemma unitrP : forall x y, y * x = 1 /\ x * y = 1 -> uam x. Proof. move=> u v [_ uv1]. by apply/lker0P=> w1 w2 /(congr1 (am v)); rewrite !amE -!mulrA uv1 !mulr1. Qed. Lemma invr_out : {in [predC uam], vam =1 id}. Proof. by move=> u /negbTE/= ->. Qed. HB.instance Definition _ := GRing.NzRing_hasMulInverse.Build A mulVr divrr unitrP invr_out. HB.end. Module FalgebraExports. Bind Scope ring_scope with sort. End FalgebraExports. HB.export FalgebraExports. Notation "1" := (vline 1) : vspace_scope. HB.instance Definition _ (K : fieldType) n := Algebra_isFalgebra.Build K 'M[K]_n.+1. HB.instance Definition _ (R : comUnitRingType) := GRing.UnitAlgebra.on R^o. (* FIXME: remove once https://github.com/math-comp/hierarchy-builder/issues/197 is fixed *) Lemma regular_fullv (K : fieldType) : (fullv = 1 :> {vspace K^o})%VS. Proof. by apply/esym/eqP; rewrite eqEdim subvf dim_vline oner_eq0 dimvf. Qed. Section Proper. Variables (R : nzRingType) (aT : falgType R). Import VectorInternalTheory. Lemma FalgType_proper : dim aT > 0. Proof. rewrite lt0n; apply: contraNneq (oner_neq0 aT) => aT0. by apply/eqP/v2r_inj; do 2!move: (v2r _); rewrite aT0 => u v; rewrite !thinmx0. Qed. End Proper. Module FalgLfun. Section FalgLfun. Variable (R : comNzRingType) (aT : falgType R). Implicit Types f g : 'End(aT). HB.instance Definition _ := GRing.Algebra.copy 'End(aT) (lfun_algType (FalgType_proper aT)). Lemma lfun_mulE f g u : (f * g) u = g (f u). Proof. exact: lfunE. Qed. Lemma lfun_compE f g : (g \o f)%VF = f * g. Proof. by []. Qed. End FalgLfun. Section InvLfun. Variable (K : fieldType) (aT : falgType K). Implicit Types f g : 'End(aT). Definition lfun_invr f := if lker f == 0%VS then f^-1%VF else f. Lemma lfun_mulVr f : lker f == 0%VS -> f^-1%VF * f = 1. Proof. exact: lker0_compfV. Qed. Lemma lfun_mulrV f : lker f == 0%VS -> f * f^-1%VF = 1. Proof. exact: lker0_compVf. Qed. Fact lfun_mulRVr f : lker f == 0%VS -> lfun_invr f * f = 1. Proof. by move=> Uf; rewrite /lfun_invr Uf lfun_mulVr. Qed. Fact lfun_mulrRV f : lker f == 0%VS -> f * lfun_invr f = 1. Proof. by move=> Uf; rewrite /lfun_invr Uf lfun_mulrV. Qed. Fact lfun_unitrP f g : g * f = 1 /\ f * g = 1 -> lker f == 0%VS. Proof. case=> _ fK; apply/lker0P; apply: can_inj (g) _ => u. by rewrite -lfun_mulE fK lfunE. Qed. Lemma lfun_invr_out f : lker f != 0%VS -> lfun_invr f = f. Proof. by rewrite /lfun_invr => /negPf->. Qed. HB.instance Definition _ := GRing.NzRing_hasMulInverse.Build 'End(aT) lfun_mulRVr lfun_mulrRV lfun_unitrP lfun_invr_out. Lemma lfun_invE f : lker f == 0%VS -> f^-1%VF = f^-1. Proof. by rewrite /f^-1 /= /lfun_invr => ->. Qed. End InvLfun. End FalgLfun. Section FalgebraTheory. Variables (K : fieldType) (aT : falgType K). Implicit Types (u v : aT) (U V W : {vspace aT}). Import FalgLfun. Definition amull u : 'End(aT) := linfun (u \*o @idfun aT). Definition amulr u : 'End(aT) := linfun (u \o* @idfun aT). Lemma amull_inj : injective amull. Proof. by move=> u v /lfunP/(_ 1); rewrite !lfunE /= !mulr1. Qed. Lemma amulr_inj : injective amulr. Proof. by move=> u v /lfunP/(_ 1); rewrite !lfunE /= !mul1r. Qed. Fact amull_is_linear : linear amull. Proof. move=> a u v; apply/lfunP => w. by rewrite !lfunE /= scale_lfunE !lfunE /= mulrDl scalerAl. Qed. #[hnf] HB.instance Definition _ := GRing.isSemilinear.Build K aT (hom aT aT) _ amull (GRing.semilinear_linear amull_is_linear). (* amull is a converse ring morphism *) Lemma amull1 : amull 1 = \1%VF. Proof. by apply/lfunP => z; rewrite id_lfunE lfunE /= mul1r. Qed. Lemma amullM u v : (amull (u * v) = amull v * amull u)%VF. Proof. by apply/lfunP => w; rewrite comp_lfunE !lfunE /= mulrA. Qed. Lemma amulr_is_linear : linear amulr. Proof. move=> a u v; apply/lfunP => w. by rewrite !lfunE /= !lfunE /= lfunE mulrDr /= scalerAr. Qed. Lemma amulr_is_monoid_morphism : monoid_morphism amulr. Proof. split=> [|x y]; first by apply/lfunP => w; rewrite id_lfunE !lfunE /= mulr1. by apply/lfunP=> w; rewrite comp_lfunE !lfunE /= mulrA. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `amulr_is_monoid_morphism` instead")] Definition amulr_is_multiplicative := (fun p => (p.2, p.1)) amulr_is_monoid_morphism. #[hnf] HB.instance Definition _ := GRing.isSemilinear.Build K aT (hom aT aT) _ amulr (GRing.semilinear_linear amulr_is_linear). #[hnf] HB.instance Definition _ := GRing.isMonoidMorphism.Build aT (hom aT aT) amulr amulr_is_monoid_morphism. Lemma lker0_amull u : u \is a GRing.unit -> lker (amull u) == 0%VS. Proof. by move=> Uu; apply/lker0P=> v w; rewrite !lfunE; apply: mulrI. Qed. Lemma lker0_amulr u : u \is a GRing.unit -> lker (amulr u) == 0%VS. Proof. by move=> Uu; apply/lker0P=> v w; rewrite !lfunE; apply: mulIr. Qed. Lemma lfun1_poly (p : {poly aT}) : map_poly \1%VF p = p. Proof. by apply: map_poly_id => u _; apply: id_lfunE. Qed. Fact prodv_key : unit. Proof. by []. Qed. Definition prodv := locked_with prodv_key (fun U V => <<allpairs *%R (vbasis U) (vbasis V)>>%VS). Canonical prodv_unlockable := [unlockable fun prodv]. Local Notation "A * B" := (prodv A B) : vspace_scope. Lemma memv_mul U V : {in U & V, forall u v, u * v \in (U * V)%VS}. Proof. move=> u v /coord_vbasis-> /coord_vbasis->. rewrite mulr_suml; apply: memv_suml => i _. rewrite mulr_sumr; apply: memv_suml => j _. rewrite -scalerAl -scalerAr !memvZ // [prodv]unlock memv_span //. by apply/allpairsP; exists ((vbasis U)`_i, (vbasis V)`_j); rewrite !memt_nth. Qed. Lemma prodvP {U V W} : reflect {in U & V, forall u v, u * v \in W} (U * V <= W)%VS. Proof. apply: (iffP idP) => [sUVW u v Uu Vv | sUVW]. by rewrite (subvP sUVW) ?memv_mul. rewrite [prodv]unlock; apply/span_subvP=> _ /allpairsP[[u v] /= [Uu Vv ->]]. by rewrite sUVW ?vbasis_mem. Qed. Lemma prodv_line u v : (<[u]> * <[v]> = <[u * v]>)%VS. Proof. apply: subv_anti; rewrite -memvE memv_mul ?memv_line // andbT. apply/prodvP=> _ _ /vlineP[a ->] /vlineP[b ->]. by rewrite -scalerAr -scalerAl !memvZ ?memv_line. Qed. Lemma dimv1: \dim (1%VS : {vspace aT}) = 1. Proof. by rewrite dim_vline oner_neq0. Qed. Lemma dim_prodv U V : \dim (U * V) <= \dim U * \dim V. Proof. by rewrite unlock (leq_trans (dim_span _)) ?size_tuple. Qed. Lemma vspace1_neq0 : (1 != 0 :> {vspace aT})%VS. Proof. by rewrite -dimv_eq0 dimv1. Qed. Lemma vbasis1 : exists2 k, k != 0 & vbasis 1 = [:: k%:A] :> seq aT. Proof. move: (vbasis 1) (@vbasisP K aT 1); rewrite dim_vline oner_neq0. case/tupleP=> x X0; rewrite {X0}tuple0 => defX; have Xx := mem_head x nil. have /vlineP[k def_x] := basis_mem defX Xx; exists k; last by rewrite def_x. by have:= basis_not0 defX Xx; rewrite def_x scaler_eq0 oner_eq0 orbF. Qed. Lemma prod0v : left_zero 0%VS prodv. Proof. move=> U; apply/eqP; rewrite -dimv_eq0 -leqn0 (leq_trans (dim_prodv 0 U)) //. by rewrite dimv0. Qed. Lemma prodv0 : right_zero 0%VS prodv. Proof. move=> U; apply/eqP; rewrite -dimv_eq0 -leqn0 (leq_trans (dim_prodv U 0)) //. by rewrite dimv0 muln0. Qed. HB.instance Definition _ := Monoid.isMulLaw.Build {vspace aT} 0%VS prodv prod0v prodv0. Lemma prod1v : left_id 1%VS prodv. Proof. move=> U; apply/subv_anti/andP; split. by apply/prodvP=> _ u /vlineP[a ->] Uu; rewrite mulr_algl memvZ. by apply/subvP=> u Uu; rewrite -[u]mul1r memv_mul ?memv_line. Qed. Lemma prodv1 : right_id 1%VS prodv. Proof. move=> U; apply/subv_anti/andP; split. by apply/prodvP=> u _ Uu /vlineP[a ->]; rewrite mulr_algr memvZ. by apply/subvP=> u Uu; rewrite -[u]mulr1 memv_mul ?memv_line. Qed. Lemma prodvS U1 U2 V1 V2 : (U1 <= U2 -> V1 <= V2 -> U1 * V1 <= U2 * V2)%VS. Proof. move/subvP=> sU12 /subvP sV12; apply/prodvP=> u v Uu Vv. by rewrite memv_mul ?sU12 ?sV12. Qed. Lemma prodvSl U1 U2 V : (U1 <= U2 -> U1 * V <= U2 * V)%VS. Proof. by move/prodvS->. Qed. Lemma prodvSr U V1 V2 : (V1 <= V2 -> U * V1 <= U * V2)%VS. Proof. exact: prodvS. Qed. Lemma prodvDl : left_distributive prodv addv. Proof. move=> U1 U2 V; apply/esym/subv_anti/andP; split. by rewrite subv_add 2?prodvS ?addvSl ?addvSr. apply/prodvP=> _ v /memv_addP[u1 Uu1 [u2 Uu2 ->]] Vv. by rewrite mulrDl memv_add ?memv_mul. Qed. Lemma prodvDr : right_distributive prodv addv. Proof. move=> U V1 V2; apply/esym/subv_anti/andP; split. by rewrite subv_add 2?prodvS ?addvSl ?addvSr. apply/prodvP=> u _ Uu /memv_addP[v1 Vv1 [v2 Vv2 ->]]. by rewrite mulrDr memv_add ?memv_mul. Qed. HB.instance Definition _ := Monoid.isAddLaw.Build {vspace aT} prodv addv prodvDl prodvDr. Lemma prodvA : associative prodv. Proof. move=> U V W; rewrite -(span_basis (vbasisP U)) span_def !big_distrl /=. apply: eq_bigr => u _; rewrite -(span_basis (vbasisP W)) span_def !big_distrr. apply: eq_bigr => w _; rewrite -(span_basis (vbasisP V)) span_def /=. rewrite !(big_distrl, big_distrr) /=; apply: eq_bigr => v _. by rewrite !prodv_line mulrA. Qed. HB.instance Definition _ := Monoid.isLaw.Build {vspace aT} 1%VS prodv prodvA prod1v prodv1. Definition expv U n := iterop n.+1.-1 prodv U 1%VS. Local Notation "A ^+ n" := (expv A n) : vspace_scope. Lemma expv0 U : (U ^+ 0 = 1)%VS. Proof. by []. Qed. Lemma expv1 U : (U ^+ 1 = U)%VS. Proof. by []. Qed. Lemma expv2 U : (U ^+ 2 = U * U)%VS. Proof. by []. Qed. Lemma expvSl U n : (U ^+ n.+1 = U * U ^+ n)%VS. Proof. by case: n => //; rewrite prodv1. Qed. Lemma expv0n n : (0 ^+ n = if n is _.+1 then 0 else 1)%VS. Proof. by case: n => // n; rewrite expvSl prod0v. Qed. Lemma expv1n n : (1 ^+ n = 1)%VS. Proof. by elim: n => // n IHn; rewrite expvSl IHn prodv1. Qed. Lemma expvD U m n : (U ^+ (m + n) = U ^+ m * U ^+ n)%VS. Proof. by elim: m => [|m IHm]; rewrite ?prod1v // !expvSl IHm prodvA. Qed. Lemma expvSr U n : (U ^+ n.+1 = U ^+ n * U)%VS. Proof. by rewrite -addn1 expvD. Qed. Lemma expvM U m n : (U ^+ (m * n) = U ^+ m ^+ n)%VS. Proof. by elim: n => [|n IHn]; rewrite ?muln0 // mulnS expvD IHn expvSl. Qed. Lemma expvS U V n : (U <= V -> U ^+ n <= V ^+ n)%VS. Proof. move=> sUV; elim: n => [|n IHn]; first by rewrite !expv0 subvv. by rewrite !expvSl prodvS. Qed. Lemma expv_line u n : (<[u]> ^+ n = <[u ^+ n]>)%VS. Proof. elim: n => [|n IH]; first by rewrite expr0 expv0. by rewrite exprS expvSl IH prodv_line. Qed. (* Centralisers and centers. *) Definition centraliser1_vspace u := lker (amulr u - amull u). Local Notation "'C [ u ]" := (centraliser1_vspace u) : vspace_scope. Definition centraliser_vspace V := (\bigcap_i 'C[tnth (vbasis V) i])%VS. Local Notation "'C ( V )" := (centraliser_vspace V) : vspace_scope. Definition center_vspace V := (V :&: 'C(V))%VS. Local Notation "'Z ( V )" := (center_vspace V) : vspace_scope. Lemma cent1vP u v : reflect (u * v = v * u) (u \in 'C[v]%VS). Proof. by rewrite (sameP eqlfunP eqP) !lfunE /=; apply: eqP. Qed. Lemma cent1v1 u : 1 \in 'C[u]%VS. Proof. by apply/cent1vP; rewrite commr1. Qed. Lemma cent1v_id u : u \in 'C[u]%VS. Proof. exact/cent1vP. Qed. Lemma cent1vX u n : u ^+ n \in 'C[u]%VS. Proof. exact/cent1vP/esym/commrX. Qed. Lemma cent1vC u v : (u \in 'C[v])%VS = (v \in 'C[u])%VS. Proof. exact/cent1vP/cent1vP. Qed. Lemma centvP u V : reflect {in V, forall v, u * v = v * u} (u \in 'C(V))%VS. Proof. apply: (iffP subv_bigcapP) => [cVu y /coord_vbasis-> | cVu i _]. apply/esym/cent1vP/rpred_sum=> i _; apply: rpredZ. by rewrite -tnth_nth cent1vC memvE cVu. exact/cent1vP/cVu/vbasis_mem/mem_tnth. Qed. Lemma centvsP U V : reflect {in U & V, commutative *%R} (U <= 'C(V))%VS. Proof. by apply: (iffP subvP) => [cUV u v | cUV u] /cUV-/centvP; apply. Qed. Lemma subv_cent1 U v : (U <= 'C[v])%VS = (v \in 'C(U)%VS). Proof. by apply/subvP/centvP=> cUv u Uu; apply/cent1vP; rewrite 1?cent1vC cUv. Qed. Lemma centv1 V : 1 \in 'C(V)%VS. Proof. by apply/centvP=> v _; rewrite commr1. Qed. Lemma centvX V u n : u \in 'C(V)%VS -> u ^+ n \in 'C(V)%VS. Proof. by move/centvP=> cVu; apply/centvP=> v /cVu/esym/commrX->. Qed. Lemma centvC U V : (U <= 'C(V))%VS = (V <= 'C(U))%VS. Proof. by apply/centvsP/centvsP=> cUV u v UVu /cUV->. Qed. Lemma centerv_sub V : ('Z(V) <= V)%VS. Proof. exact: capvSl. Qed. Lemma cent_centerv V : (V <= 'C('Z(V)))%VS. Proof. by rewrite centvC capvSr. Qed. (* Building the predicate that checks is a vspace has a unit *) Definition is_algid e U := [/\ e \in U, e != 0 & {in U, forall u, e * u = u /\ u * e = u}]. Fact algid_decidable U : decidable (exists e, is_algid e U). Proof. have [-> | nzU] := eqVneq U 0%VS. by right=> [[e []]]; rewrite memv0 => ->. pose X := vbasis U; pose feq f1 f2 := [tuple of map f1 X ++ map f2 X]. have feqL f i: tnth (feq _ f _) (lshift _ i) = f X`_i. set v := f _; rewrite (tnth_nth v) /= nth_cat size_map size_tuple. by rewrite ltn_ord (nth_map 0) ?size_tuple. have feqR f i: tnth (feq _ _ f) (rshift _ i) = f X`_i. set v := f _; rewrite (tnth_nth v) /= nth_cat size_map size_tuple. by rewrite ltnNge leq_addr addKn /= (nth_map 0) ?size_tuple. apply: decP (vsolve_eq (feq _ amulr amull) (feq _ id id) U) _. apply: (iffP (vsolve_eqP _ _ _)) => [[e Ue id_e] | [e [Ue _ id_e]]]. suffices idUe: {in U, forall u, e * u = u /\ u * e = u}. exists e; split=> //; apply: contraNneq nzU => e0; rewrite -subv0. by apply/subvP=> u /idUe[<- _]; rewrite e0 mul0r mem0v. move=> u /coord_vbasis->; rewrite mulr_sumr mulr_suml. split; apply/eq_bigr=> i _; rewrite -(scalerAr, scalerAl); congr (_ *: _). by have:= id_e (lshift _ i); rewrite !feqL lfunE. by have:= id_e (rshift _ i); rewrite !feqR lfunE. have{id_e} /all_and2[ideX idXe]:= id_e _ (vbasis_mem (mem_tnth _ X)). exists e => // k; rewrite -[k]splitK. by case: (split k) => i; rewrite !(feqL, feqR) lfunE /= -tnth_nth. Qed. Definition has_algid : pred {vspace aT} := algid_decidable. Lemma has_algidP {U} : reflect (exists e, is_algid e U) (has_algid U). Proof. exact: sumboolP. Qed. Lemma has_algid1 U : 1 \in U -> has_algid U. Proof. move=> U1; apply/has_algidP; exists 1; split; rewrite ?oner_eq0 // => u _. by rewrite mulr1 mul1r. Qed. Definition is_aspace U := has_algid U && (U * U <= U)%VS. Structure aspace := ASpace {asval :> {vspace aT}; _ : is_aspace asval}. HB.instance Definition _ := [isSub for asval]. HB.instance Definition _ := [Choice of aspace by <:]. Definition clone_aspace U (A : aspace) := fun algU & phant_id algU (valP A) => @ASpace U algU : aspace. Fact aspace1_subproof : is_aspace 1. Proof. by rewrite /is_aspace prod1v -memvE has_algid1 memv_line. Qed. Canonical aspace1 : aspace := ASpace aspace1_subproof. Lemma aspacef_subproof : is_aspace fullv. Proof. by rewrite /is_aspace subvf has_algid1 ?memvf. Qed. Canonical aspacef : aspace := ASpace aspacef_subproof. Lemma polyOver1P p : reflect (exists q, p = map_poly (in_alg aT) q) (p \is a polyOver 1%VS). Proof. apply: (iffP idP) => [/allP/=Qp | [q ->]]; last first. by apply/polyOverP=> j; rewrite coef_map rpredZ ?memv_line. exists (map_poly (coord [tuple 1] 0) p). rewrite -map_poly_comp map_poly_id // => _ /Qp/vlineP[a ->] /=. by rewrite linearZ /= (coord_free 0) ?mulr1 // seq1_free ?oner_eq0. Qed. End FalgebraTheory. Delimit Scope aspace_scope with AS. Bind Scope aspace_scope with aspace. Arguments asval {K aT} a%_AS. Arguments aspace [K]%_type aT%_type. Arguments clone_aspace [K aT U%_VS A%_AS algU] _. Notation "{ 'aspace' T }" := (aspace T) : type_scope. Notation "A * B" := (prodv A B) : vspace_scope. Notation "A ^+ n" := (expv A n) : vspace_scope. Notation "'C [ u ]" := (centraliser1_vspace u) : vspace_scope. Notation "'C_ U [ v ]" := (capv U 'C[v]) : vspace_scope. Notation "'C_ ( U ) [ v ]" := (capv U 'C[v]) (only parsing) : vspace_scope. Notation "'C ( V )" := (centraliser_vspace V) : vspace_scope. Notation "'C_ U ( V )" := (capv U 'C(V)) : vspace_scope. Notation "'C_ ( U ) ( V )" := (capv U 'C(V)) (only parsing) : vspace_scope. Notation "'Z ( V )" := (center_vspace V) : vspace_scope. Notation "1" := (aspace1 _) : aspace_scope. Notation "{ : aT }" := (aspacef aT) : aspace_scope. Notation "[ 'aspace' 'of' U ]" := (@clone_aspace _ _ U _ _ id) (format "[ 'aspace' 'of' U ]") : form_scope. Notation "[ 'aspace' 'of' U 'for' A ]" := (@clone_aspace _ _ U A _ idfun) (format "[ 'aspace' 'of' U 'for' A ]") : form_scope. Arguments prodvP {K aT U V W}. Arguments cent1vP {K aT u v}. Arguments centvP {K aT u V}. Arguments centvsP {K aT U V}. Arguments has_algidP {K aT U}. Arguments polyOver1P {K aT p}. Section AspaceTheory. Variables (K : fieldType) (aT : falgType K). Implicit Types (u v e : aT) (U V : {vspace aT}) (A B : {aspace aT}). Import FalgLfun. Lemma algid_subproof U : {e | e \in U & has_algid U ==> (U <= lker (amull e - 1) :&: lker (amulr e - 1))%VS}. Proof. apply: sig2W; case: has_algidP => [[e]|]; last by exists 0; rewrite ?mem0v. case=> Ae _ idAe; exists e => //; apply/subvP=> u /idAe[eu_u ue_u]. by rewrite memv_cap !memv_ker !lfun_simp /= eu_u ue_u subrr eqxx. Qed. Definition algid U := s2val (algid_subproof U). Lemma memv_algid U : algid U \in U. Proof. by rewrite /algid; case: algid_subproof. Qed. Lemma algidl A : {in A, left_id (algid A) *%R}. Proof. rewrite /algid; case: algid_subproof => e _ /=; have /andP[-> _] := valP A. move/subvP=> idAe u /idAe/memv_capP[]. by rewrite memv_ker !lfun_simp /= subr_eq0 => /eqP. Qed. Lemma algidr A : {in A, right_id (algid A) *%R}. Proof. rewrite /algid; case: algid_subproof => e _ /=; have /andP[-> _] := valP A. move/subvP=> idAe u /idAe/memv_capP[_]. by rewrite memv_ker !lfun_simp /= subr_eq0 => /eqP. Qed. Lemma unitr_algid1 A u : u \in A -> u \is a GRing.unit -> algid A = 1. Proof. by move=> Eu /mulrI; apply; rewrite mulr1 algidr. Qed. Lemma algid_eq1 A : (algid A == 1) = (1 \in A). Proof. by apply/eqP/idP=> [<- | /algidr <-]; rewrite ?memv_algid ?mul1r. Qed. Lemma algid_neq0 A : algid A != 0. Proof. have /andP[/has_algidP[u [Au nz_u _]] _] := valP A. by apply: contraNneq nz_u => e0; rewrite -(algidr Au) e0 mulr0. Qed. Lemma dim_algid A : \dim <[algid A]> = 1%N. Proof. by rewrite dim_vline algid_neq0. Qed. Lemma adim_gt0 A : (0 < \dim A)%N. Proof. by rewrite -(dim_algid A) dimvS // -memvE ?memv_algid. Qed. Lemma not_asubv0 A : ~~ (A <= 0)%VS. Proof. by rewrite subv0 -dimv_eq0 -lt0n adim_gt0. Qed. Lemma adim1P {A} : reflect (A = <[algid A]>%VS :> {vspace aT}) (\dim A == 1%N). Proof. rewrite eqn_leq adim_gt0 -(memv_algid A) andbC -(dim_algid A) -eqEdim eq_sym. exact: eqP. Qed. Lemma asubv A : (A * A <= A)%VS. Proof. by have /andP[] := valP A. Qed. Lemma memvM A : {in A &, forall u v, u * v \in A}. Proof. exact/prodvP/asubv. Qed. Lemma prodv_id A : (A * A)%VS = A. Proof. apply/eqP; rewrite eqEsubv asubv; apply/subvP=> u Au. by rewrite -(algidl Au) memv_mul // memv_algid. Qed. Lemma prodv_sub U V A : (U <= A -> V <= A -> U * V <= A)%VS. Proof. by move=> sUA sVA; rewrite -prodv_id prodvS. Qed. Lemma expv_id A n : (A ^+ n.+1)%VS = A. Proof. by elim: n => // n IHn; rewrite !expvSl prodvA prodv_id -expvSl. Qed. Lemma limg_amulr U v : (amulr v @: U = U * <[v]>)%VS. Proof. rewrite -(span_basis (vbasisP U)) limg_span !span_def big_distrl /= big_map. by apply: eq_bigr => u; rewrite prodv_line lfunE. Qed. Lemma memv_cosetP {U v w} : reflect (exists2 u, u\in U & w = u * v) (w \in U * <[v]>)%VS. Proof. rewrite -limg_amulr. by apply: (iffP memv_imgP) => [] [u] Uu ->; exists u; rewrite ?lfunE. Qed. Lemma dim_cosetv_unit V u : u \is a GRing.unit -> \dim (V * <[u]>) = \dim V. Proof. by move/lker0_amulr/eqP=> Uu; rewrite -limg_amulr limg_dim_eq // Uu capv0. Qed. Lemma memvV A u : (u^-1 \in A) = (u \in A). Proof. suffices{u} invA: invr_closed A by apply/idP/idP=> /invA; rewrite ?invrK. move=> u Au; have [Uu | /invr_out-> //] := boolP (u \is a GRing.unit). rewrite memvE -(limg_ker0 _ _ (lker0_amulr Uu)) limg_line lfunE /= mulVr //. suff ->: (amulr u @: A)%VS = A by rewrite -memvE -algid_eq1 (unitr_algid1 Au). by apply/eqP; rewrite limg_amulr -dimv_leqif_eq ?prodv_sub ?dim_cosetv_unit. Qed. Fact aspace_cap_subproof A B : algid A \in B -> is_aspace (A :&: B). Proof. move=> BeA; apply/andP. split; [apply/has_algidP | by rewrite subv_cap !prodv_sub ?capvSl ?capvSr]. exists (algid A); rewrite /is_algid algid_neq0 memv_cap memv_algid. by split=> // u /memv_capP[Au _]; rewrite ?algidl ?algidr. Qed. Definition aspace_cap A B BeA := ASpace (@aspace_cap_subproof A B BeA). Fact centraliser1_is_aspace u : is_aspace 'C[u]. Proof. rewrite /is_aspace has_algid1 ?cent1v1 //=. apply/prodvP=> v w /cent1vP-cuv /cent1vP-cuw. by apply/cent1vP; rewrite -mulrA cuw !mulrA cuv. Qed. Canonical centraliser1_aspace u := ASpace (centraliser1_is_aspace u). Fact centraliser_is_aspace V : is_aspace 'C(V). Proof. rewrite /is_aspace has_algid1 ?centv1 //=. apply/prodvP=> u w /centvP-cVu /centvP-cVw. by apply/centvP=> v Vv; rewrite /= -mulrA cVw // !mulrA cVu. Qed. Canonical centraliser_aspace V := ASpace (centraliser_is_aspace V). Lemma centv_algid A : algid A \in 'C(A)%VS. Proof. by apply/centvP=> u Au; rewrite algidl ?algidr. Qed. Canonical center_aspace A := [aspace of 'Z(A) for aspace_cap (centv_algid A)]. Lemma algid_center A : algid 'Z(A) = algid A. Proof. rewrite -(algidl (subvP (centerv_sub A) _ (memv_algid _))) algidr //=. by rewrite memv_cap memv_algid centv_algid. Qed. Lemma Falgebra_FieldMixin : GRing.integral_domain_axiom aT -> GRing.field_axiom aT. Proof. move=> domT u nz_u; apply/unitrP. have kerMu: lker (amulr u) == 0%VS. rewrite eqEsubv sub0v andbT; apply/subvP=> v; rewrite memv_ker lfunE /=. by move/eqP/domT; rewrite (negPf nz_u) orbF memv0. have /memv_imgP[v _ vu1]: 1 \in limg (amulr u); last rewrite lfunE /= in vu1. suffices /eqP->: limg (amulr u) == fullv by rewrite memvf. by rewrite -dimv_leqif_eq ?subvf ?limg_dim_eq // (eqP kerMu) capv0. exists v; split=> //; apply: (lker0P kerMu). by rewrite !lfunE /= -mulrA -vu1 mulr1 mul1r. Qed. Section SkewField. Hypothesis fieldT : GRing.field_axiom aT. Lemma skew_field_algid1 A : algid A = 1. Proof. by rewrite (unitr_algid1 (memv_algid A)) ?fieldT ?algid_neq0. Qed. Lemma skew_field_module_semisimple A M : let sumA X := (\sum_(x <- X) A * <[x]>)%VS in (A * M <= M)%VS -> {X | [/\ sumA X = M, directv (sumA X) & 0 \notin X]}. Proof. move=> sumA sAM_M; pose X := Nil aT; pose k := (\dim (A * M) - \dim (sumA X))%N. have: (\dim (A * M) - \dim (sumA X) < k.+1)%N by []. have: [/\ (sumA X <= A * M)%VS, directv (sumA X) & 0 \notin X]. by rewrite /sumA directvE /= !big_nil sub0v dimv0. elim: {X k}k.+1 (X) => // k IHk X [sAX_AM dxAX nzX]; rewrite ltnS => leAXk. have [sM_AX | /subvPn/sig2W[y My notAXy]] := boolP (M <= sumA X)%VS. by exists X; split=> //; apply/eqP; rewrite eqEsubv (subv_trans sAX_AM). have nz_y: y != 0 by rewrite (memPnC notAXy) ?mem0v. pose AY := sumA (y :: X). have sAY_AM: (AY <= A * M)%VS by rewrite [AY]big_cons subv_add ?prodvSr. have dxAY: directv AY. rewrite directvE /= !big_cons [_ == _]directv_addE dxAX directvE eqxx /=. rewrite -/(sumA X) eqEsubv sub0v andbT -limg_amulr. apply/subvP=> _ /memv_capP[/memv_imgP[a Aa ->]]/[!lfunE]/= AXay. rewrite memv0 (mulIr_eq0 a (mulIr _)) ?fieldT //. apply: contraR notAXy => /fieldT-Ua; rewrite -[y](mulKr Ua) /sumA. by rewrite -big_distrr -(prodv_id A) /= -prodvA big_distrr memv_mul ?memvV. apply: (IHk (y :: X)); first by rewrite !inE eq_sym negb_or nz_y. rewrite -subSn ?dimvS // (directvP dxAY) /= big_cons -(directvP dxAX) /=. rewrite subnDA (leq_trans _ leAXk) ?leq_sub2r // leq_subLR -add1n leq_add2r. by rewrite dim_cosetv_unit ?fieldT ?adim_gt0. Qed. Lemma skew_field_module_dimS A M : (A * M <= M)%VS -> \dim A %| \dim M. Proof. case/skew_field_module_semisimple=> X [<- /directvP-> nzX] /=. rewrite big_seq prime.dvdn_sum // => x /(memPn nzX)nz_x. by rewrite dim_cosetv_unit ?fieldT. Qed. Lemma skew_field_dimS A B : (A <= B)%VS -> \dim A %| \dim B. Proof. by move=> sAB; rewrite skew_field_module_dimS ?prodv_sub. Qed. End SkewField. End AspaceTheory. (* Note that local centraliser might not be proper sub-algebras. *) Notation "'C [ u ]" := (centraliser1_aspace u) : aspace_scope. Notation "'C ( V )" := (centraliser_aspace V) : aspace_scope. Notation "'Z ( A )" := (center_aspace A) : aspace_scope. Arguments adim1P {K aT A}. Arguments memv_cosetP {K aT U v w}. Section Closure. Variables (K : fieldType) (aT : falgType K). Implicit Types (u v : aT) (U V W : {vspace aT}). (* Subspaces of an F-algebra form a Kleene algebra *) Definition agenv U := (\sum_(i < \dim {:aT}) U ^+ i)%VS. Local Notation "<< U & vs >>" := (agenv (U + <<vs>>)) : vspace_scope. Local Notation "<< U ; x >>" := (agenv (U + <[x]>)) : vspace_scope. Lemma agenvEl U : agenv U = (1 + U * agenv U)%VS. Proof. pose f V := (1 + U * V)%VS; rewrite -/(f _); pose n := \dim {:aT}. have ->: agenv U = iter n f 0%VS. rewrite /agenv -/n; elim: n => [|n IHn]; first by rewrite big_ord0. rewrite big_ord_recl /= -{}IHn; congr (1 + _)%VS; rewrite big_distrr /=. by apply: eq_bigr => i; rewrite expvSl. have fS i j: i <= j -> (iter i f 0 <= iter j f 0)%VS. by elim: i j => [|i IHi] [|j] leij; rewrite ?sub0v //= addvS ?prodvSr ?IHi. suffices /(@trajectP _ f _ n.+1)[i le_i_n Dfi]: looping f 0%VS n.+1. by apply/eqP; rewrite eqEsubv -iterS fS // Dfi fS. apply: contraLR (dimvS (subvf (iter n.+1 f 0%VS))); rewrite -/n -ltnNge. rewrite -looping_uniq; elim: n.+1 => // i IHi; rewrite trajectSr rcons_uniq. rewrite {1}trajectSr mem_rcons inE negb_or eq_sym eqEdim fS ?leqW // -ltnNge. by rewrite -andbA => /and3P[lt_fi _ /IHi/leq_ltn_trans->]. Qed. Lemma agenvEr U : agenv U = (1 + agenv U * U)%VS. Proof. rewrite [lhs in lhs = _]agenvEl big_distrr big_distrl /=; congr (_ + _)%VS. by apply: eq_bigr => i _ /=; rewrite -expvSr -expvSl. Qed. Lemma agenv_modl U V : (U * V <= V -> agenv U * V <= V)%VS. Proof. rewrite big_distrl /= => idlU_V; apply/subv_sumP=> [[i _] /= _]. elim: i => [|i]; first by rewrite expv0 prod1v. by apply: subv_trans; rewrite expvSr -prodvA prodvSr. Qed. Lemma agenv_modr U V : (V * U <= V -> V * agenv U <= V)%VS. Proof. rewrite big_distrr /= => idrU_V; apply/subv_sumP=> [[i _] /= _]. elim: i => [|i]; first by rewrite expv0 prodv1. by apply: subv_trans; rewrite expvSl prodvA prodvSl. Qed. Fact agenv_is_aspace U : is_aspace (agenv U). Proof. rewrite /is_aspace has_algid1; last by rewrite memvE agenvEl addvSl. by rewrite agenv_modl // [V in (_ <= V)%VS]agenvEl addvSr. Qed. Canonical agenv_aspace U : {aspace aT} := ASpace (agenv_is_aspace U). Lemma agenvE U : agenv U = agenv_aspace U. Proof. by []. Qed. (* Kleene algebra properties *) Lemma agenvM U : (agenv U * agenv U)%VS = agenv U. Proof. exact: prodv_id. Qed. Lemma agenvX n U : (agenv U ^+ n.+1)%VS = agenv U. Proof. exact: expv_id. Qed. Lemma sub1_agenv U : (1 <= agenv U)%VS. Proof. by rewrite agenvEl addvSl. Qed. Lemma sub_agenv U : (U <= agenv U)%VS. Proof. by rewrite 2!agenvEl addvC prodvDr prodv1 -addvA addvSl. Qed. Lemma subX_agenv U n : (U ^+ n <= agenv U)%VS. Proof. by case: n => [|n]; rewrite ?sub1_agenv // -(agenvX n) expvS // sub_agenv. Qed. Lemma agenv_sub_modl U V : (1 <= V -> U * V <= V -> agenv U <= V)%VS. Proof. move=> s1V /agenv_modl; apply: subv_trans. by rewrite -[Us in (Us <= _)%VS]prodv1 prodvSr. Qed. Lemma agenv_sub_modr U V : (1 <= V -> V * U <= V -> agenv U <= V)%VS. Proof. move=> s1V /agenv_modr; apply: subv_trans. by rewrite -[Us in (Us <= _)%VS]prod1v prodvSl. Qed. Lemma agenv_id U : agenv (agenv U) = agenv U. Proof. apply/eqP; rewrite eqEsubv sub_agenv andbT. by rewrite agenv_sub_modl ?sub1_agenv ?agenvM. Qed. Lemma agenvS U V : (U <= V -> agenv U <= agenv V)%VS. Proof. move=> sUV; rewrite agenv_sub_modl ?sub1_agenv //. by rewrite -[Vs in (_ <= Vs)%VS]agenvM prodvSl ?(subv_trans sUV) ?sub_agenv. Qed. Lemma agenv_add_id U V : agenv (agenv U + V) = agenv (U + V). Proof. apply/eqP; rewrite eqEsubv andbC agenvS ?addvS ?sub_agenv //=. rewrite agenv_sub_modl ?sub1_agenv //. rewrite -[rhs in (_ <= rhs)%VS]agenvM prodvSl // subv_add agenvS ?addvSl //=. exact: subv_trans (addvSr U V) (sub_agenv _). Qed. Lemma subv_adjoin U x : (U <= <<U; x>>)%VS. Proof. by rewrite (subv_trans (sub_agenv _)) ?agenvS ?addvSl. Qed. Lemma subv_adjoin_seq U xs : (U <= <<U & xs>>)%VS. Proof. by rewrite (subv_trans (sub_agenv _)) // ?agenvS ?addvSl. Qed. Lemma memv_adjoin U x : x \in <<U; x>>%VS. Proof. by rewrite memvE (subv_trans (sub_agenv _)) ?agenvS ?addvSr. Qed. Lemma seqv_sub_adjoin U xs : {subset xs <= <<U & xs>>%VS}. Proof. by apply/span_subvP; rewrite (subv_trans (sub_agenv _)) ?agenvS ?addvSr. Qed. Lemma subvP_adjoin U x y : y \in U -> y \in <<U; x>>%VS. Proof. exact/subvP/subv_adjoin. Qed. Lemma adjoin_nil V : <<V & [::]>>%VS = agenv V. Proof. by rewrite span_nil addv0. Qed. Lemma adjoin_cons V x rs : <<V & x :: rs>>%VS = << <<V; x>> & rs>>%VS. Proof. by rewrite span_cons addvA agenv_add_id. Qed. Lemma adjoin_rcons V rs x : <<V & rcons rs x>>%VS = << <<V & rs>>%VS; x>>%VS. Proof. by rewrite -cats1 span_cat addvA span_seq1 agenv_add_id. Qed. Lemma adjoin_seq1 V x : <<V & [:: x]>>%VS = <<V; x>>%VS. Proof. by rewrite adjoin_cons adjoin_nil agenv_id. Qed. Lemma adjoinC V x y : << <<V; x>>; y>>%VS = << <<V; y>>; x>>%VS. Proof. by rewrite !agenv_add_id -!addvA (addvC <[x]>%VS). Qed. Lemma adjoinSl U V x : (U <= V -> <<U; x>> <= <<V; x>>)%VS. Proof. by move=> sUV; rewrite agenvS ?addvS. Qed. Lemma adjoin_seqSl U V rs : (U <= V -> <<U & rs>> <= <<V & rs>>)%VS. Proof. by move=> sUV; rewrite agenvS ?addvS. Qed. Lemma adjoin_seqSr U rs1 rs2 : {subset rs1 <= rs2} -> (<<U & rs1>> <= <<U & rs2>>)%VS. Proof. by move/sub_span=> s_rs12; rewrite agenvS ?addvS. Qed. End Closure. Notation "<< U >>" := (agenv_aspace U) : aspace_scope. Notation "<< U & vs >>" := (agenv (U + <<vs>>)) : vspace_scope. Notation "<< U ; x >>" := (agenv (U + <[x]>)) : vspace_scope. Notation "<< U & vs >>" := << U + <<vs>> >>%AS : aspace_scope. Notation "<< U ; x >>" := << U + <[x]> >>%AS : aspace_scope. Section SubFalgType. (* The falgType structure of subvs_of A for A : {aspace aT}. *) (* We can't use the rpred-based mixin, because A need not contain 1. *) Variable (K : fieldType) (aT : falgType K) (A : {aspace aT}). Definition subvs_one := Subvs (memv_algid A). Definition subvs_mul (u v : subvs_of A) := Subvs (subv_trans (memv_mul (subvsP u) (subvsP v)) (asubv _)). Fact subvs_mulA : associative subvs_mul. Proof. by move=> x y z; apply/val_inj/mulrA. Qed. Fact subvs_mu1l : left_id subvs_one subvs_mul. Proof. by move=> x; apply/val_inj/algidl/(valP x). Qed. Fact subvs_mul1 : right_id subvs_one subvs_mul. Proof. by move=> x; apply/val_inj/algidr/(valP x). Qed. Fact subvs_mulDl : left_distributive subvs_mul +%R. Proof. move=> x y z; apply/val_inj/mulrDl. Qed. Fact subvs_mulDr : right_distributive subvs_mul +%R. Proof. move=> x y z; apply/val_inj/mulrDr. Qed. HB.instance Definition _ := GRing.Zmodule_isNzRing.Build (subvs_of A) subvs_mulA subvs_mu1l subvs_mul1 subvs_mulDl subvs_mulDr (algid_neq0 _). Lemma subvs_scaleAl k (x y : subvs_of A) : k *: (x * y) = (k *: x) * y. Proof. exact/val_inj/scalerAl. Qed. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build K (subvs_of A) subvs_scaleAl. Lemma subvs_scaleAr k (x y : subvs_of A) : k *: (x * y) = x * (k *: y). Proof. exact/val_inj/scalerAr. Qed. HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build K (subvs_of A) subvs_scaleAr. HB.instance Definition _ := Algebra_isFalgebra.Build K (subvs_of A). Implicit Type w : subvs_of A. Lemma vsval_unitr w : vsval w \is a GRing.unit -> w \is a GRing.unit. Proof. case: w => /= u Au Uu; have Au1: u^-1 \in A by rewrite memvV. apply/unitrP; exists (Subvs Au1). by split; apply: val_inj; rewrite /= ?mulrV ?mulVr ?(unitr_algid1 Au). Qed. Lemma vsval_invr w : vsval w \is a GRing.unit -> val w^-1 = (val w)^-1. Proof. move=> Uu; have def_w: w / w * w = w by rewrite divrK ?vsval_unitr. by apply: (mulrI Uu); rewrite -[in u in u / _]def_w ?mulrK. Qed. End SubFalgType. Section AHom. Variable K : fieldType. Section Class_Def. Variables aT rT : falgType K. Definition ahom_in (U : {vspace aT}) (f : 'Hom(aT, rT)) := all2rel (fun x y : aT => f (x * y) == f x * f y) (vbasis U) && (f 1 == 1). Lemma ahom_inP {f : 'Hom(aT, rT)} {U : {vspace aT}} : reflect ({in U &, {morph f : x y / x * y >-> x * y}} * (f 1 = 1)) (ahom_in U f). Proof. apply: (iffP andP) => [[/allrelP fM /eqP f1] | [fM f1]]; last first. rewrite f1; split=> //; apply/allrelP => x y Ax Ay. by rewrite fM // vbasis_mem. split=> // x y /coord_vbasis -> /coord_vbasis ->. rewrite !mulr_suml ![f _]linear_sum mulr_suml; apply: eq_bigr => i _ /=. rewrite !mulr_sumr linear_sum; apply: eq_bigr => j _ /=. rewrite !linearZ -!scalerAr -!scalerAl 2!linearZ /=; congr (_ *: (_ *: _)). by apply/eqP/fM; apply: memt_nth. Qed. Lemma ahomP_tmp {f : 'Hom(aT, rT)} : reflect (monoid_morphism f) (ahom_in {:aT} f). Proof. apply: (iffP ahom_inP) => [[fM f1] | fRM_P]; last first. by split=> [x y|]; [rewrite fRM_P.2|rewrite fRM_P.1]. by split=> // x y; rewrite fM ?memvf. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `ahomP_tmp` instead")] Lemma ahomP {f : 'Hom(aT, rT)} : reflect (multiplicative f) (ahom_in {:aT} f). Proof. by apply: (iffP ahomP_tmp) => [][]. Qed. Structure ahom := AHom {ahval :> 'Hom(aT, rT); _ : ahom_in {:aT} ahval}. HB.instance Definition _ := [isSub for ahval]. HB.instance Definition _ := [Equality of ahom by <:]. HB.instance Definition _ := [Choice of ahom by <:]. Fact linfun_is_ahom (f : {lrmorphism aT -> rT}) : ahom_in {:aT} (linfun f). Proof. by apply/ahom_inP; split=> [x y|]; rewrite !lfunE ?rmorphM ?rmorph1. Qed. Canonical linfun_ahom f := AHom (linfun_is_ahom f). End Class_Def. Arguments ahom_in [aT rT]. Arguments ahom_inP {aT rT f U}. #[warning="-deprecated-since-mathcomp-2.5.0"] Arguments ahomP {aT rT f}. Arguments ahomP_tmp {aT rT f}. Section LRMorphism. Variables aT rT sT : falgType K. Fact ahom_is_monoid_morphism (f : ahom aT rT) : monoid_morphism f. Proof. by apply/ahomP_tmp; case: f. Qed. #[hnf] HB.instance Definition _ (f : ahom aT rT) := GRing.isMonoidMorphism.Build aT rT f (ahom_is_monoid_morphism f). #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `ahom_is_monoid_morphism` instead")] Definition ahom_is_multiplicative (f : ahom aT rT) : multiplicative f := (fun p => (p.2, p.1)) (ahom_is_monoid_morphism f). Lemma ahomWin (f : ahom aT rT) U : ahom_in U f. Proof. by apply/ahom_inP; split; [apply: in2W (rmorphM _) | apply: rmorph1]. Qed. Lemma id_is_ahom (V : {vspace aT}) : ahom_in V \1. Proof. by apply/ahom_inP; split=> [x y|] /=; rewrite !id_lfunE. Qed. Canonical id_ahom := AHom (id_is_ahom (aspacef aT)). Lemma comp_is_ahom (V : {vspace aT}) (f : 'Hom(rT, sT)) (g : 'Hom(aT, rT)) : ahom_in {:rT} f -> ahom_in V g -> ahom_in V (f \o g). Proof. move=> /ahom_inP fM /ahom_inP gM; apply/ahom_inP. by split=> [x y Vx Vy|] /=; rewrite !comp_lfunE gM // fM ?memvf. Qed. Canonical comp_ahom (f : ahom rT sT) (g : ahom aT rT) := AHom (comp_is_ahom (valP f) (valP g)). Lemma aimgM (f : ahom aT rT) U V : (f @: (U * V) = f @: U * f @: V)%VS. Proof. apply/eqP; rewrite eqEsubv; apply/andP; split; last first. apply/prodvP=> _ _ /memv_imgP[u Hu ->] /memv_imgP[v Hv ->]. by rewrite -rmorphM memv_img // memv_mul. apply/subvP=> _ /memv_imgP[w UVw ->]; rewrite memv_preim (subvP _ w UVw) //. by apply/prodvP=> u v Uu Vv; rewrite -memv_preim rmorphM memv_mul // memv_img. Qed. Lemma aimg1 (f : ahom aT rT) : (f @: 1 = 1)%VS. Proof. by rewrite limg_line rmorph1. Qed. Lemma aimgX (f : ahom aT rT) U n : (f @: (U ^+ n) = f @: U ^+ n)%VS. Proof. elim: n => [|n IH]; first by rewrite !expv0 aimg1. by rewrite !expvSl aimgM IH. Qed. Lemma aimg_agen (f : ahom aT rT) U : (f @: agenv U)%VS = agenv (f @: U). Proof. apply/eqP; rewrite eqEsubv; apply/andP; split. by rewrite limg_sum; apply/subv_sumP => i _; rewrite aimgX subX_agenv. apply: agenv_sub_modl; first by rewrite -(aimg1 f) limgS // sub1_agenv. by rewrite -aimgM limgS // [rhs in (_ <= rhs)%VS]agenvEl addvSr. Qed. Lemma aimg_adjoin (f : ahom aT rT) U x : (f @: <<U; x>> = <<f @: U; f x>>)%VS. Proof. by rewrite aimg_agen limgD limg_line. Qed. Lemma aimg_adjoin_seq (f : ahom aT rT) U xs : (f @: <<U & xs>> = <<f @: U & map f xs>>)%VS. Proof. by rewrite aimg_agen limgD limg_span. Qed. Fact ker_sub_ahom_is_aspace (f g : ahom aT rT) : is_aspace (lker (ahval f - ahval g)). Proof. rewrite /is_aspace has_algid1; last by apply/eqlfunP; rewrite !rmorph1. apply/prodvP=> a b /eqlfunP Dfa /eqlfunP Dfb. by apply/eqlfunP; rewrite !rmorphM /= Dfa Dfb. Qed. Canonical ker_sub_ahom_aspace f g := ASpace (ker_sub_ahom_is_aspace f g). End LRMorphism. Canonical fixedSpace_aspace aT (f : ahom aT aT) := [aspace of fixedSpace f]. End AHom. Arguments ahom_in [K aT rT]. Notation "''AHom' ( aT , rT )" := (ahom aT rT) : type_scope. Notation "''AEnd' ( aT )" := (ahom aT aT) : type_scope. Delimit Scope lrfun_scope with AF. Bind Scope lrfun_scope with ahom. Notation "\1" := (@id_ahom _ _) : lrfun_scope. Notation "f \o g" := (comp_ahom f g) : lrfun_scope.
Span.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.Data.Finset.Sort import Mathlib.Topology.Category.Profinite.CofilteredLimit import Mathlib.Topology.Category.Profinite.Nobeling.Basic /-! # The good products span Most of the argument is developing an API for `π C (· ∈ s)` when `s : Finset I`; then the image of `C` is finite with the discrete topology. In this case, there is a direct argument that the good products span. The general result is deduced from this. For the overall proof outline see `Mathlib/Topology/Category/Profinite/Nobeling/Basic.lean`. ## Main theorems * `GoodProducts.spanFin` : The good products span the locally constant functions on `π C (· ∈ s)` if `s` is finite. * `GoodProducts.span` : The good products span `LocallyConstant C ℤ` for every closed subset `C`. ## References - [scholze2019condensed], Theorem 5.4. -/ universe u namespace Profinite.NobelingProof variable {I : Type u} (C : Set (I → Bool)) [LinearOrder I] section Fin variable (s : Finset I) /-- The `ℤ`-linear map induced by precomposition of the projection `C → π C (· ∈ s)`. -/ noncomputable def πJ : LocallyConstant (π C (· ∈ s)) ℤ →ₗ[ℤ] LocallyConstant C ℤ := LocallyConstant.comapₗ ℤ ⟨_, (continuous_projRestrict C (· ∈ s))⟩ theorem eval_eq_πJ (l : Products I) (hl : l.isGood (π C (· ∈ s))) : l.eval C = πJ C s (l.eval (π C (· ∈ s))) := by ext f simp only [πJ, LocallyConstant.comapₗ, LinearMap.coe_mk, AddHom.coe_mk, LocallyConstant.coe_comap, Function.comp_apply] exact (congr_fun (Products.evalFacProp C (· ∈ s) (Products.prop_of_isGood C (· ∈ s) hl)) _).symm /-- `π C (· ∈ s)` is finite for a finite set `s`. -/ noncomputable instance : Fintype (π C (· ∈ s)) := by let f : π C (· ∈ s) → (s → Bool) := fun x j ↦ x.val j.val refine Fintype.ofInjective f ?_ intro ⟨_, x, hx, rfl⟩ ⟨_, y, hy, rfl⟩ h ext i by_cases hi : i ∈ s · exact congrFun h ⟨i, hi⟩ · simp only [Proj, if_neg hi] open scoped Classical in /-- The Kronecker delta as a locally constant map from `π C (· ∈ s)` to `ℤ`. -/ noncomputable def spanFinBasis (x : π C (· ∈ s)) : LocallyConstant (π C (· ∈ s)) ℤ where toFun := fun y ↦ if y = x then 1 else 0 isLocallyConstant := haveI : DiscreteTopology (π C (· ∈ s)) := Finite.instDiscreteTopology IsLocallyConstant.of_discrete _ open scoped Classical in theorem spanFinBasis.span : ⊤ ≤ Submodule.span ℤ (Set.range (spanFinBasis C s)) := by intro f _ rw [Finsupp.mem_span_range_iff_exists_finsupp] use Finsupp.onFinset (Finset.univ) f.toFun (fun _ _ ↦ Finset.mem_univ _) ext x change LocallyConstant.evalₗ ℤ x _ = _ simp only [zsmul_eq_mul, map_finsuppSum, LocallyConstant.evalₗ_apply, LocallyConstant.coe_mul, Pi.mul_apply, spanFinBasis, LocallyConstant.coe_mk, mul_ite, mul_one, mul_zero, Finsupp.sum_ite_eq, Finsupp.mem_support_iff, ne_eq, ite_not] split_ifs with h <;> [exact h.symm; rfl] /-- A certain explicit list of locally constant maps. The theorem `factors_prod_eq_basis` shows that the product of the elements in this list is the delta function `spanFinBasis C s x`. -/ def factors (x : π C (· ∈ s)) : List (LocallyConstant (π C (· ∈ s)) ℤ) := List.map (fun i ↦ if x.val i = true then e (π C (· ∈ s)) i else (1 - (e (π C (· ∈ s)) i))) (s.sort (· ≥ ·)) theorem list_prod_apply {I} (C : Set (I → Bool)) (x : C) (l : List (LocallyConstant C ℤ)) : l.prod x = (l.map (LocallyConstant.evalMonoidHom x)).prod := by rw [← map_list_prod (LocallyConstant.evalMonoidHom x) l, LocallyConstant.evalMonoidHom_apply] theorem factors_prod_eq_basis_of_eq {x y : (π C fun x ↦ x ∈ s)} (h : y = x) : (factors C s x).prod y = 1 := by rw [list_prod_apply (π C (· ∈ s)) y _] apply List.prod_eq_one simp only [h, List.mem_map, LocallyConstant.evalMonoidHom, factors] rintro _ ⟨a, ⟨b, _, rfl⟩, rfl⟩ dsimp split_ifs with hh · rw [e, LocallyConstant.coe_mk, if_pos hh] · rw [LocallyConstant.sub_apply, e, LocallyConstant.coe_mk, LocallyConstant.coe_mk, if_neg hh] simp only [LocallyConstant.toFun_eq_coe, LocallyConstant.coe_one, Pi.one_apply, sub_zero] theorem e_mem_of_eq_true {x : (π C (· ∈ s))} {a : I} (hx : x.val a = true) : e (π C (· ∈ s)) a ∈ factors C s x := by rcases x with ⟨_, z, hz, rfl⟩ simp only [factors, List.mem_map, Finset.mem_sort] refine ⟨a, ?_, if_pos hx⟩ aesop (add simp Proj) theorem one_sub_e_mem_of_false {x y : (π C (· ∈ s))} {a : I} (ha : y.val a = true) (hx : x.val a = false) : 1 - e (π C (· ∈ s)) a ∈ factors C s x := by simp only [factors, List.mem_map, Finset.mem_sort] use a simp only [hx] rcases y with ⟨_, z, hz, rfl⟩ aesop (add simp Proj) theorem factors_prod_eq_basis_of_ne {x y : (π C (· ∈ s))} (h : y ≠ x) : (factors C s x).prod y = 0 := by rw [list_prod_apply (π C (· ∈ s)) y _] apply List.prod_eq_zero simp only [List.mem_map] obtain ⟨a, ha⟩ : ∃ a, y.val a ≠ x.val a := by contrapose! h; ext; apply h cases hx : x.val a · rw [hx, ne_eq, Bool.not_eq_false] at ha refine ⟨1 - (e (π C (· ∈ s)) a), ⟨one_sub_e_mem_of_false _ _ ha hx, ?_⟩⟩ rw [e, LocallyConstant.evalMonoidHom_apply, LocallyConstant.sub_apply, LocallyConstant.coe_one, Pi.one_apply, LocallyConstant.coe_mk, if_pos ha, sub_self] · refine ⟨e (π C (· ∈ s)) a, ⟨e_mem_of_eq_true _ _ hx, ?_⟩⟩ rw [hx] at ha rw [LocallyConstant.evalMonoidHom_apply, e, LocallyConstant.coe_mk, if_neg ha] /-- If `s` is finite, the product of the elements of the list `factors C s x` is the delta function at `x`. -/ theorem factors_prod_eq_basis (x : π C (· ∈ s)) : (factors C s x).prod = spanFinBasis C s x := by ext y dsimp [spanFinBasis] split_ifs with h <;> [exact factors_prod_eq_basis_of_eq _ _ h; exact factors_prod_eq_basis_of_ne _ _ h] theorem GoodProducts.finsuppSum_mem_span_eval {a : I} {as : List I} (ha : List.Chain' (· > ·) (a :: as)) {c : Products I →₀ ℤ} (hc : (c.support : Set (Products I)) ⊆ {m | m.val ≤ as}) : (Finsupp.sum c fun a_1 b ↦ e (π C (· ∈ s)) a * b • Products.eval (π C (· ∈ s)) a_1) ∈ Submodule.span ℤ (Products.eval (π C (· ∈ s)) '' {m | m.val ≤ a :: as}) := by apply Submodule.finsuppSum_mem intro m hm have hsm := (LinearMap.mulLeft ℤ (e (π C (· ∈ s)) a)).map_smul dsimp at hsm rw [hsm] apply Submodule.smul_mem apply Submodule.subset_span have hmas : m.val ≤ as := by apply hc simpa only [Finset.mem_coe, Finsupp.mem_support_iff] using hm refine ⟨⟨a :: m.val, ha.cons_of_le m.prop hmas⟩, ⟨List.cons_le_cons a hmas, ?_⟩⟩ simp only [Products.eval, List.map, List.prod_cons] @[deprecated (since := "2025-04-06")] alias GoodProducts.finsupp_sum_mem_span_eval := GoodProducts.finsuppSum_mem_span_eval /-- If `s` is a finite subset of `I`, then the good products span. -/ theorem GoodProducts.spanFin [WellFoundedLT I] : ⊤ ≤ Submodule.span ℤ (Set.range (eval (π C (· ∈ s)))) := by rw [span_iff_products] refine le_trans (spanFinBasis.span C s) ?_ rw [Submodule.span_le] rintro _ ⟨x, rfl⟩ rw [← factors_prod_eq_basis] let l := s.sort (· ≥ ·) dsimp [factors] suffices l.Chain' (· > ·) → (l.map (fun i ↦ if x.val i = true then e (π C (· ∈ s)) i else (1 - (e (π C (· ∈ s)) i)))).prod ∈ Submodule.span ℤ ((Products.eval (π C (· ∈ s))) '' {m | m.val ≤ l}) from Submodule.span_mono (Set.image_subset_range _ _) (this (Finset.sort_sorted_gt _).chain') induction l with | nil => intro _ apply Submodule.subset_span exact ⟨⟨[], List.chain'_nil⟩,⟨Or.inl rfl, rfl⟩⟩ | cons a as ih => rw [List.map_cons, List.prod_cons] intro ha specialize ih (by rw [List.chain'_cons'] at ha; exact ha.2) rw [Finsupp.mem_span_image_iff_linearCombination] at ih simp only [Finsupp.mem_supported, Finsupp.linearCombination_apply] at ih obtain ⟨c, hc, hc'⟩ := ih rw [← hc']; clear hc' have hmap := fun g ↦ map_finsuppSum (LinearMap.mulLeft ℤ (e (π C (· ∈ s)) a)) c g dsimp at hmap ⊢ split_ifs · rw [hmap] exact finsuppSum_mem_span_eval _ _ ha hc · ring_nf rw [hmap] apply Submodule.add_mem · apply Submodule.neg_mem exact finsuppSum_mem_span_eval _ _ ha hc · apply Submodule.finsuppSum_mem intro m hm apply Submodule.smul_mem apply Submodule.subset_span refine ⟨m, ⟨?_, rfl⟩⟩ simp only [Set.mem_setOf_eq] have hmas : m.val ≤ as := hc (by simpa only [Finset.mem_coe, Finsupp.mem_support_iff] using hm) refine le_trans hmas ?_ cases as with | nil => exact (List.nil_lt_cons a []).le | cons b bs => apply le_of_lt rw [List.chain'_cons_cons] at ha exact (List.lt_iff_lex_lt _ _).mp (List.Lex.rel ha.1) end Fin theorem fin_comap_jointlySurjective (hC : IsClosed C) (f : LocallyConstant C ℤ) : ∃ (s : Finset I) (g : LocallyConstant (π C (· ∈ s)) ℤ), f = g.comap ⟨(ProjRestrict C (· ∈ s)), continuous_projRestrict _ _⟩ := by obtain ⟨J, g, h⟩ := @Profinite.exists_locallyConstant (Finset I)ᵒᵖ _ _ _ (spanCone hC.isCompact) ℤ (spanCone_isLimit hC.isCompact) f exact ⟨(Opposite.unop J), g, h⟩ /-- The good products span all of `LocallyConstant C ℤ` if `C` is closed. -/ theorem GoodProducts.span [WellFoundedLT I] (hC : IsClosed C) : ⊤ ≤ Submodule.span ℤ (Set.range (eval C)) := by rw [span_iff_products] intro f _ obtain ⟨K, f', rfl⟩ : ∃ K f', f = πJ C K f' := fin_comap_jointlySurjective C hC f refine Submodule.span_mono ?_ <| Submodule.apply_mem_span_image_of_mem_span (πJ C K) <| spanFin C K (Submodule.mem_top : f' ∈ ⊤) rintro l ⟨y, ⟨m, rfl⟩, rfl⟩ exact ⟨m.val, eval_eq_πJ C K m.val m.prop⟩ end Profinite.NobelingProof
ComplexShape.lean
/- Copyright (c) 2021 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kim Morrison -/ import Mathlib.Algebra.Group.Defs import Mathlib.Logic.Relation import Mathlib.Logic.Function.Basic /-! # Shapes of homological complexes We define a structure `ComplexShape ι` for describing the shapes of homological complexes indexed by a type `ι`. This is intended to capture chain complexes and cochain complexes, indexed by either `ℕ` or `ℤ`, as well as more exotic examples. Rather than insisting that the indexing type has a `succ` function specifying where differentials should go, inside `c : ComplexShape` we have `c.Rel : ι → ι → Prop`, and when we define `HomologicalComplex` we only allow nonzero differentials `d i j` from `i` to `j` if `c.Rel i j`. Further, we require that `{ j // c.Rel i j }` and `{ i // c.Rel i j }` are subsingletons. This means that the shape consists of some union of lines, rays, intervals, and circles. Convenience functions `c.next` and `c.prev` provide these related elements when they exist, and return their input otherwise. This design aims to avoid certain problems arising from dependent type theory. In particular we never have to ensure morphisms `d i : X i ⟶ X (succ i)` compose as expected (which would often require rewriting by equations in the indexing type). Instead such identities become separate proof obligations when verifying that a complex we've constructed is of the desired shape. If `α` is an `AddRightCancelSemigroup`, then we define `up α : ComplexShape α`, the shape appropriate for cohomology, so `d : X i ⟶ X j` is nonzero only when `j = i + 1`, as well as `down α : ComplexShape α`, appropriate for homology, so `d : X i ⟶ X j` is nonzero only when `i = j + 1`. (Later we'll introduce `CochainComplex` and `ChainComplex` as abbreviations for `HomologicalComplex` with one of these shapes baked in.) -/ noncomputable section /-- A `c : ComplexShape ι` describes the shape of a chain complex, with chain groups indexed by `ι`. Typically `ι` will be `ℕ`, `ℤ`, or `Fin n`. There is a relation `Rel : ι → ι → Prop`, and we will only allow a non-zero differential from `i` to `j` when `Rel i j`. There are axioms which imply `{ j // c.Rel i j }` and `{ i // c.Rel i j }` are subsingletons. This means that the shape consists of some union of lines, rays, intervals, and circles. Below we define `c.next` and `c.prev` which provide these related elements. -/ @[ext] structure ComplexShape (ι : Type*) where /-- Nonzero differentials `X i ⟶ X j` shall be allowed on homological complexes when `Rel i j` holds. -/ Rel : ι → ι → Prop /-- There is at most one nonzero differential from `X i`. -/ next_eq : ∀ {i j j'}, Rel i j → Rel i j' → j = j' /-- There is at most one nonzero differential to `X j`. -/ prev_eq : ∀ {i i' j}, Rel i j → Rel i' j → i = i' namespace ComplexShape variable {ι : Type*} /-- The complex shape where only differentials from each `X.i` to itself are allowed. This is mostly only useful so we can describe the relation of "related in `k` steps" below. -/ @[simps] def refl (ι : Type*) : ComplexShape ι where Rel i j := i = j next_eq w w' := w.symm.trans w' prev_eq w w' := w.trans w'.symm /-- The reverse of a `ComplexShape`. -/ @[simps] def symm (c : ComplexShape ι) : ComplexShape ι where Rel i j := c.Rel j i next_eq w w' := c.prev_eq w w' prev_eq w w' := c.next_eq w w' @[simp] theorem symm_symm (c : ComplexShape ι) : c.symm.symm = c := rfl theorem symm_bijective : Function.Bijective (ComplexShape.symm : ComplexShape ι → ComplexShape ι) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ /-- The "composition" of two `ComplexShape`s. We need this to define "related in k steps" later. -/ @[simp] def trans (c₁ c₂ : ComplexShape ι) : ComplexShape ι where Rel := Relation.Comp c₁.Rel c₂.Rel next_eq w w' := by obtain ⟨k, w₁, w₂⟩ := w obtain ⟨k', w₁', w₂'⟩ := w' rw [c₁.next_eq w₁ w₁'] at w₂ exact c₂.next_eq w₂ w₂' prev_eq w w' := by obtain ⟨k, w₁, w₂⟩ := w obtain ⟨k', w₁', w₂'⟩ := w' rw [c₂.prev_eq w₂ w₂'] at w₁ exact c₁.prev_eq w₁ w₁' instance subsingleton_next (c : ComplexShape ι) (i : ι) : Subsingleton { j // c.Rel i j } := by constructor rintro ⟨j, rij⟩ ⟨k, rik⟩ congr exact c.next_eq rij rik instance subsingleton_prev (c : ComplexShape ι) (j : ι) : Subsingleton { i // c.Rel i j } := by constructor rintro ⟨i, rik⟩ ⟨j, rjk⟩ congr exact c.prev_eq rik rjk open Classical in /-- An arbitrary choice of index `j` such that `Rel i j`, if such exists. Returns `i` otherwise. -/ def next (c : ComplexShape ι) (i : ι) : ι := if h : ∃ j, c.Rel i j then h.choose else i open Classical in /-- An arbitrary choice of index `i` such that `Rel i j`, if such exists. Returns `j` otherwise. -/ def prev (c : ComplexShape ι) (j : ι) : ι := if h : ∃ i, c.Rel i j then h.choose else j theorem next_eq' (c : ComplexShape ι) {i j : ι} (h : c.Rel i j) : c.next i = j := by apply c.next_eq _ h rw [next] rw [dif_pos] exact Exists.choose_spec ⟨j, h⟩ theorem prev_eq' (c : ComplexShape ι) {i j : ι} (h : c.Rel i j) : c.prev j = i := by apply c.prev_eq _ h rw [prev, dif_pos] exact Exists.choose_spec (⟨i, h⟩ : ∃ k, c.Rel k j) lemma next_eq_self' (c : ComplexShape ι) (j : ι) (hj : ∀ k, ¬c.Rel j k) : c.next j = j := dif_neg (by simpa using hj) lemma prev_eq_self' (c : ComplexShape ι) (j : ι) (hj : ∀ i, ¬c.Rel i j) : c.prev j = j := dif_neg (by simpa using hj) lemma next_eq_self (c : ComplexShape ι) (j : ι) (hj : ¬c.Rel j (c.next j)) : c.next j = j := c.next_eq_self' j (fun k hk' => hj (by simpa only [c.next_eq' hk'] using hk')) lemma prev_eq_self (c : ComplexShape ι) (j : ι) (hj : ¬c.Rel (c.prev j) j) : c.prev j = j := c.prev_eq_self' j (fun k hk' => hj (by simpa only [c.prev_eq' hk'] using hk')) /-- The `ComplexShape` allowing differentials from `X i` to `X (i+a)`. (For example when `a = 1`, a cohomology theory indexed by `ℕ` or `ℤ`) -/ @[simps] def up' {α : Type*} [Add α] [IsRightCancelAdd α] (a : α) : ComplexShape α where Rel i j := i + a = j next_eq hi hj := hi.symm.trans hj prev_eq hi hj := add_right_cancel (hi.trans hj.symm) /-- The `ComplexShape` allowing differentials from `X (j+a)` to `X j`. (For example when `a = 1`, a homology theory indexed by `ℕ` or `ℤ`) -/ @[simps] def down' {α : Type*} [Add α] [IsRightCancelAdd α] (a : α) : ComplexShape α where Rel i j := j + a = i next_eq hi hj := add_right_cancel (hi.trans hj.symm) prev_eq hi hj := hi.symm.trans hj theorem down'_mk {α : Type*} [Add α] [IsRightCancelAdd α] (a : α) (i j : α) (h : j + a = i) : (down' a).Rel i j := h /-- The `ComplexShape` appropriate for cohomology, so `d : X i ⟶ X j` only when `j = i + 1`. -/ @[simps!] def up (α : Type*) [Add α] [IsRightCancelAdd α] [One α] : ComplexShape α := up' 1 /-- The `ComplexShape` appropriate for homology, so `d : X i ⟶ X j` only when `i = j + 1`. -/ @[simps!] def down (α : Type*) [Add α] [IsRightCancelAdd α] [One α] : ComplexShape α := down' 1 theorem down_mk {α : Type*} [Add α] [IsRightCancelAdd α] [One α] (i j : α) (h : j + 1 = i) : (down α).Rel i j := down'_mk (1 : α) i j h end ComplexShape end namespace ComplexShape variable (α : Type*) [AddRightCancelSemigroup α] [DecidableEq α] instance (a : α) : DecidableRel (ComplexShape.up' a).Rel := fun _ _ => by dsimp; infer_instance instance (a : α) : DecidableRel (ComplexShape.down' a).Rel := fun _ _ => by dsimp; infer_instance variable [One α] instance : DecidableRel (ComplexShape.up α).Rel := by dsimp [ComplexShape.up]; infer_instance instance : DecidableRel (ComplexShape.down α).Rel := by dsimp [ComplexShape.down]; infer_instance end ComplexShape
Pi.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.RingTheory.Unramified.Basic /-! # Formal-unramification of finite products of rings ## Main result - `Algebra.FormallyUnramified.pi_iff`: If `I` is finite, `Π i : I, A i` is `R`-formally-smooth if and only if each `A i` is `R`-formally-smooth. -/ namespace Algebra.FormallyUnramified universe u v variable {R : Type max u v} {I : Type v} [Finite I] (f : I → Type max u v) variable [CommRing R] [∀ i, CommRing (f i)] [∀ i, Algebra R (f i)] theorem pi_iff : FormallyUnramified R (∀ i, f i) ↔ ∀ i, FormallyUnramified R (f i) := by classical cases nonempty_fintype I constructor · intro _ i exact FormallyUnramified.of_surjective (Pi.evalAlgHom R f i) (Function.surjective_eval i) · intro H rw [iff_comp_injective] intros B _ _ J hJ f₁ f₂ e ext g rw [← Finset.univ_sum_single g, map_sum, map_sum] refine Finset.sum_congr rfl ?_ rintro x - have hf : ∀ x, f₁ x - f₂ x ∈ J := by intro g rw [← Ideal.Quotient.eq_zero_iff_mem, map_sub, sub_eq_zero] exact AlgHom.congr_fun e g let e : ∀ i, f i := Pi.single x 1 have he : IsIdempotentElem e := by simp [IsIdempotentElem, e, ← Pi.single_mul] have h₁ : (f₁ e) * (1 - f₂ e) = 0 := by rw [← Ideal.mem_bot, ← hJ, ← ((he.map f₁).mul (he.map f₂).one_sub).eq, ← pow_two] apply Ideal.pow_mem_pow convert Ideal.mul_mem_left _ (f₁ e) (hf e) using 1 rw [mul_sub, mul_sub, mul_one, (he.map f₁).eq] have h₂ : (f₂ e) * (1 - f₁ e) = 0 := by rw [← Ideal.mem_bot, ← hJ, ← ((he.map f₂).mul (he.map f₁).one_sub).eq, ← pow_two] apply Ideal.pow_mem_pow convert Ideal.mul_mem_left _ (-f₂ e) (hf e) using 1 rw [neg_mul, mul_sub, mul_sub, mul_one, neg_sub, (he.map f₂).eq] have H : f₁ e = f₂ e := by trans f₁ e * f₂ e · rw [← sub_eq_zero, ← h₁, mul_sub, mul_one] · rw [eq_comm, ← sub_eq_zero, ← h₂, mul_sub, mul_one, mul_comm] let J' := Ideal.span {1 - f₁ e} let f₁' : f x →ₐ[R] B ⧸ J' := by apply AlgHom.ofLinearMap (((Ideal.Quotient.mkₐ R J').comp f₁).toLinearMap.comp (LinearMap.single _ _ x)) · simp only [AlgHom.comp_toLinearMap, LinearMap.coe_comp, LinearMap.coe_single, Function.comp_apply, AlgHom.toLinearMap_apply, Ideal.Quotient.mkₐ_eq_mk] rw [eq_comm, ← sub_eq_zero, ← (Ideal.Quotient.mk J').map_one, ← map_sub, Ideal.Quotient.eq_zero_iff_mem, Ideal.mem_span_singleton] · intros r s; simp [Pi.single_mul] let f₂' : f x →ₐ[R] B ⧸ J' := by apply AlgHom.ofLinearMap (((Ideal.Quotient.mkₐ R J').comp f₂).toLinearMap.comp (LinearMap.single _ _ x)) · simp only [AlgHom.comp_toLinearMap, LinearMap.coe_comp, LinearMap.coe_single, Function.comp_apply, AlgHom.toLinearMap_apply, Ideal.Quotient.mkₐ_eq_mk] rw [eq_comm, ← sub_eq_zero, ← (Ideal.Quotient.mk J').map_one, ← map_sub, Ideal.Quotient.eq_zero_iff_mem, Ideal.mem_span_singleton, H] · intros r s; simp [Pi.single_mul] suffices f₁' = f₂' by have := AlgHom.congr_fun this (g x) simp only [AlgHom.comp_toLinearMap, AlgHom.ofLinearMap_apply, LinearMap.coe_comp, LinearMap.coe_single, Function.comp_apply, AlgHom.toLinearMap_apply, ← map_sub, Ideal.Quotient.mkₐ_eq_mk, ← sub_eq_zero (b := Ideal.Quotient.mk J' _), f₁', f₂', Ideal.Quotient.eq_zero_iff_mem, Ideal.mem_span_singleton, J'] at this obtain ⟨c, hc⟩ := this apply_fun (f₁ e * ·) at hc rwa [← mul_assoc, mul_sub, mul_sub, mul_one, (he.map f₁).eq, sub_self, zero_mul, ← map_mul, H, ← map_mul, ← Pi.single_mul, one_mul, sub_eq_zero] at hc apply FormallyUnramified.comp_injective (I := J.map (algebraMap _ _)) · rw [← Ideal.map_pow, hJ, Ideal.map_bot] · ext r rw [← sub_eq_zero] simp only [Ideal.Quotient.algebraMap_eq, AlgHom.coe_comp, Ideal.Quotient.mkₐ_eq_mk, Function.comp_apply, ← map_sub, Ideal.Quotient.eq_zero_iff_mem, f₁', f₂', AlgHom.comp_toLinearMap, AlgHom.ofLinearMap_apply, LinearMap.coe_comp, LinearMap.coe_single, Function.comp_apply, AlgHom.toLinearMap_apply, Ideal.Quotient.mkₐ_eq_mk] exact Ideal.mem_map_of_mem (Ideal.Quotient.mk J') (hf (Pi.single x r)) instance [∀ i, FormallyUnramified R (f i)] : FormallyUnramified R (Π i, f i) := (pi_iff _).mpr ‹_› end Algebra.FormallyUnramified
Defs.lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov, Yakov Pechersky -/ import Mathlib.Algebra.Group.Hom.Defs import Mathlib.Algebra.Group.InjSurj import Mathlib.Data.SetLike.Basic import Mathlib.Tactic.FastInstance /-! # Subsemigroups: definition This file defines bundled multiplicative and additive subsemigroups. ## Main definitions * `Subsemigroup M`: the type of bundled subsemigroup of a magma `M`; the underlying set is given in the `carrier` field of the structure, and should be accessed through coercion as in `(S : Set M)`. * `AddSubsemigroup M` : the type of bundled subsemigroups of an additive magma `M`. For each of the following definitions in the `Subsemigroup` namespace, there is a corresponding definition in the `AddSubsemigroup` namespace. * `Subsemigroup.copy` : copy of a subsemigroup with `carrier` replaced by a set that is equal but possibly not definitionally equal to the carrier of the original `Subsemigroup`. Similarly, for each of these definitions in the `MulHom` namespace, there is a corresponding definition in the `AddHom` namespace. * `MulHom.eqLocus f g`: the subsemigroup of those `x` such that `f x = g x` ## Implementation notes Subsemigroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subsemigroup's underlying set. Note that `Subsemigroup M` does not actually require `Semigroup M`, instead requiring only the weaker `Mul M`. This file is designed to have very few dependencies. In particular, it should not use natural numbers. ## Tags subsemigroup, subsemigroups -/ assert_not_exists RelIso CompleteLattice MonoidWithZero variable {M : Type*} {N : Type*} section NonAssoc variable [Mul M] {s : Set M} /-- `MulMemClass S M` says `S` is a type of sets `s : Set M` that are closed under `(*)` -/ class MulMemClass (S : Type*) (M : outParam Type*) [Mul M] [SetLike S M] : Prop where /-- A substructure satisfying `MulMemClass` is closed under multiplication. -/ mul_mem : ∀ {s : S} {a b : M}, a ∈ s → b ∈ s → a * b ∈ s export MulMemClass (mul_mem) /-- `AddMemClass S M` says `S` is a type of sets `s : Set M` that are closed under `(+)` -/ class AddMemClass (S : Type*) (M : outParam Type*) [Add M] [SetLike S M] : Prop where /-- A substructure satisfying `AddMemClass` is closed under addition. -/ add_mem : ∀ {s : S} {a b : M}, a ∈ s → b ∈ s → a + b ∈ s export AddMemClass (add_mem) attribute [to_additive] MulMemClass attribute [aesop 90% (rule_sets := [SetLike])] mul_mem add_mem /-- A subsemigroup of a magma `M` is a subset closed under multiplication. -/ structure Subsemigroup (M : Type*) [Mul M] where /-- The carrier of a subsemigroup. -/ carrier : Set M /-- The product of two elements of a subsemigroup belongs to the subsemigroup. -/ mul_mem' {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier /-- An additive subsemigroup of an additive magma `M` is a subset closed under addition. -/ structure AddSubsemigroup (M : Type*) [Add M] where /-- The carrier of an additive subsemigroup. -/ carrier : Set M /-- The sum of two elements of an additive subsemigroup belongs to the subsemigroup. -/ add_mem' {a b} : a ∈ carrier → b ∈ carrier → a + b ∈ carrier attribute [to_additive AddSubsemigroup] Subsemigroup namespace Subsemigroup @[to_additive] instance : SetLike (Subsemigroup M) M := ⟨Subsemigroup.carrier, fun p q h => by cases p; cases q; congr⟩ initialize_simps_projections Subsemigroup (carrier → coe, as_prefix coe) initialize_simps_projections AddSubsemigroup (carrier → coe, as_prefix coe) /-- The actual `Subsemigroup` obtained from an element of a `MulMemClass`. -/ @[to_additive (attr := simps) /-- The actual `AddSubsemigroup` obtained from an element of a `AddMemClass` -/] def ofClass {S M : Type*} [Mul M] [SetLike S M] [MulMemClass S M] (s : S) : Subsemigroup M := ⟨s, MulMemClass.mul_mem⟩ @[to_additive] instance (priority := 100) : CanLift (Set M) (Subsemigroup M) (↑) (fun s ↦ ∀ {x y}, x ∈ s → y ∈ s → x * y ∈ s) where prf s h := ⟨{ carrier := s, mul_mem' := h }, rfl⟩ @[to_additive] instance : MulMemClass (Subsemigroup M) M where mul_mem := fun {_ _ _} => Subsemigroup.mul_mem' _ @[to_additive (attr := simp)] theorem mem_carrier {s : Subsemigroup M} {x : M} : x ∈ s.carrier ↔ x ∈ s := Iff.rfl @[to_additive (attr := simp)] theorem mem_mk {s : Set M} {x : M} (h_mul) : x ∈ mk s h_mul ↔ x ∈ s := Iff.rfl @[to_additive (attr := simp, norm_cast)] theorem coe_set_mk (s : Set M) (h_mul) : (mk s h_mul : Set M) = s := rfl @[to_additive (attr := simp)] theorem mk_le_mk {s t : Set M} (h_mul) (h_mul') : mk s h_mul ≤ mk t h_mul' ↔ s ⊆ t := Iff.rfl /-- Two subsemigroups are equal if they have the same elements. -/ @[to_additive (attr := ext) /-- Two `AddSubsemigroup`s are equal if they have the same elements. -/] theorem ext {S T : Subsemigroup M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := SetLike.ext h /-- Copy a subsemigroup replacing `carrier` with a set that is equal to it. -/ @[to_additive /-- Copy an additive subsemigroup replacing `carrier` with a set that is equal to it. -/] protected def copy (S : Subsemigroup M) (s : Set M) (hs : s = S) : Subsemigroup M where carrier := s mul_mem' := hs.symm ▸ S.mul_mem' variable {S : Subsemigroup M} @[to_additive (attr := simp)] theorem coe_copy {s : Set M} (hs : s = S) : (S.copy s hs : Set M) = s := rfl @[to_additive] theorem copy_eq {s : Set M} (hs : s = S) : S.copy s hs = S := SetLike.coe_injective hs variable (S) /-- A subsemigroup is closed under multiplication. -/ @[to_additive /-- An `AddSubsemigroup` is closed under addition. -/] protected theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := Subsemigroup.mul_mem' S /-- The subsemigroup `M` of the magma `M`. -/ @[to_additive /-- The additive subsemigroup `M` of the magma `M`. -/] instance : Top (Subsemigroup M) := ⟨{ carrier := Set.univ mul_mem' := fun _ _ => Set.mem_univ _ }⟩ /-- The trivial subsemigroup `∅` of a magma `M`. -/ @[to_additive /-- The trivial `AddSubsemigroup` `∅` of an additive magma `M`. -/] instance : Bot (Subsemigroup M) := ⟨{ carrier := ∅ mul_mem' := False.elim }⟩ @[to_additive] instance : Inhabited (Subsemigroup M) := ⟨⊥⟩ @[to_additive] theorem notMem_bot {x : M} : x ∉ (⊥ : Subsemigroup M) := Set.notMem_empty x @[deprecated (since := "2025-05-23")] alias _root_.AddSubsemigroup.not_mem_bot := AddSubsemigroup.notMem_bot @[to_additive existing, deprecated (since := "2025-05-23")] alias not_mem_bot := notMem_bot @[to_additive (attr := simp)] theorem mem_top (x : M) : x ∈ (⊤ : Subsemigroup M) := Set.mem_univ x @[to_additive (attr := simp)] theorem coe_top : ((⊤ : Subsemigroup M) : Set M) = Set.univ := rfl @[to_additive (attr := simp)] theorem coe_bot : ((⊥ : Subsemigroup M) : Set M) = ∅ := rfl /-- The inf of two subsemigroups is their intersection. -/ @[to_additive /-- The inf of two `AddSubsemigroup`s is their intersection. -/] instance : Min (Subsemigroup M) := ⟨fun S₁ S₂ => { carrier := S₁ ∩ S₂ mul_mem' := fun ⟨hx, hx'⟩ ⟨hy, hy'⟩ => ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩ @[to_additive (attr := simp)] theorem coe_inf (p p' : Subsemigroup M) : ((p ⊓ p' : Subsemigroup M) : Set M) = (p : Set M) ∩ p' := rfl @[to_additive (attr := simp)] theorem mem_inf {p p' : Subsemigroup M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := Iff.rfl @[to_additive] theorem subsingleton_of_subsingleton [Subsingleton (Subsemigroup M)] : Subsingleton M := by constructor; intro x y have : ∀ a : M, a ∈ (⊥ : Subsemigroup M) := by simp [Subsingleton.elim (⊥ : Subsemigroup M) ⊤] exact absurd (this x) notMem_bot @[to_additive] instance [hn : Nonempty M] : Nontrivial (Subsemigroup M) := ⟨⟨⊥, ⊤, fun h => by obtain ⟨x⟩ := id hn refine absurd (?_ : x ∈ ⊥) notMem_bot simp [h]⟩⟩ end Subsemigroup namespace MulHom variable [Mul N] open Subsemigroup /-- The subsemigroup of elements `x : M` such that `f x = g x` -/ @[to_additive /-- The additive subsemigroup of elements `x : M` such that `f x = g x` -/] def eqLocus (f g : M →ₙ* N) : Subsemigroup M where carrier := { x | f x = g x } mul_mem' (hx : _ = _) (hy : _ = _) := by simp [*] @[to_additive] theorem eq_of_eqOn_top {f g : M →ₙ* N} (h : Set.EqOn f g (⊤ : Subsemigroup M)) : f = g := ext fun _ => h trivial end MulHom end NonAssoc namespace MulMemClass variable {A : Type*} [Mul M] [SetLike A M] [hA : MulMemClass A M] (S' : A) -- lower priority so other instances are found first /-- A submagma of a magma inherits a multiplication. -/ @[to_additive /-- An additive submagma of an additive magma inherits an addition. -/] instance (priority := 900) mul : Mul S' := ⟨fun a b => ⟨a.1 * b.1, mul_mem a.2 b.2⟩⟩ -- lower priority so later simp lemmas are used first; to appease simp_nf @[to_additive (attr := simp low, norm_cast)] theorem coe_mul (x y : S') : (↑(x * y) : M) = ↑x * ↑y := rfl -- lower priority so later simp lemmas are used first; to appease simp_nf @[to_additive (attr := simp low)] theorem mk_mul_mk (x y : M) (hx : x ∈ S') (hy : y ∈ S') : (⟨x, hx⟩ : S') * ⟨y, hy⟩ = ⟨x * y, mul_mem hx hy⟩ := rfl @[to_additive] theorem mul_def (x y : S') : x * y = ⟨x * y, mul_mem x.2 y.2⟩ := rfl /-- A subsemigroup of a semigroup inherits a semigroup structure. -/ @[to_additive /-- An `AddSubsemigroup` of an `AddSemigroup` inherits an `AddSemigroup` structure. -/] instance toSemigroup {M : Type*} [Semigroup M] {A : Type*} [SetLike A M] [MulMemClass A M] (S : A) : Semigroup S := fast_instance% Subtype.coe_injective.semigroup Subtype.val fun _ _ => rfl /-- A subsemigroup of a `CommSemigroup` is a `CommSemigroup`. -/ @[to_additive /-- An `AddSubsemigroup` of an `AddCommSemigroup` is an `AddCommSemigroup`. -/] instance toCommSemigroup {M} [CommSemigroup M] {A : Type*} [SetLike A M] [MulMemClass A M] (S : A) : CommSemigroup S := fast_instance% Subtype.coe_injective.commSemigroup Subtype.val fun _ _ => rfl /-- The natural semigroup hom from a subsemigroup of semigroup `M` to `M`. -/ @[to_additive /-- The natural semigroup hom from an `AddSubsemigroup` of `AddSubsemigroup` `M` to `M`. -/] def subtype : S' →ₙ* M where toFun := Subtype.val; map_mul' := fun _ _ => rfl variable {S'} in @[to_additive (attr := simp)] lemma subtype_apply (x : S') : MulMemClass.subtype S' x = x := rfl @[to_additive] lemma subtype_injective : Function.Injective (MulMemClass.subtype S') := Subtype.coe_injective @[to_additive (attr := simp)] theorem coe_subtype : (MulMemClass.subtype S' : S' → M) = Subtype.val := rfl end MulMemClass
PImage.lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.Finset.Option import Mathlib.Data.PFun import Mathlib.Data.Part /-! # Image of a `Finset α` under a partially defined function In this file we define `Part.toFinset` and `Finset.pimage`. We also prove some trivial lemmas about these definitions. ## Tags finite set, image, partial function -/ variable {α β : Type*} namespace Part /-- Convert an `o : Part α` with decidable `Part.Dom o` to `Finset α`. -/ def toFinset (o : Part α) [Decidable o.Dom] : Finset α := o.toOption.toFinset @[simp] theorem mem_toFinset {o : Part α} [Decidable o.Dom] {x : α} : x ∈ o.toFinset ↔ x ∈ o := by simp [toFinset] @[simp] theorem toFinset_none [Decidable (none : Part α).Dom] : none.toFinset = (∅ : Finset α) := by simp [toFinset] @[simp] theorem toFinset_some {a : α} [Decidable (some a).Dom] : (some a).toFinset = {a} := by simp [toFinset] @[simp] theorem coe_toFinset (o : Part α) [Decidable o.Dom] : (o.toFinset : Set α) = { x | x ∈ o } := Set.ext fun _ => mem_toFinset end Part namespace Finset variable [DecidableEq β] {f g : α →. β} [∀ x, Decidable (f x).Dom] [∀ x, Decidable (g x).Dom] {s t : Finset α} {b : β} /-- Image of `s : Finset α` under a partially defined function `f : α →. β`. -/ def pimage (f : α →. β) [∀ x, Decidable (f x).Dom] (s : Finset α) : Finset β := s.biUnion fun x => (f x).toFinset @[simp] theorem mem_pimage : b ∈ s.pimage f ↔ ∃ a ∈ s, b ∈ f a := by simp [pimage] @[simp, norm_cast] theorem coe_pimage : (s.pimage f : Set β) = f.image s := Set.ext fun _ => mem_pimage @[simp] theorem pimage_some (s : Finset α) (f : α → β) [∀ x, Decidable (Part.some <| f x).Dom] : (s.pimage fun x => Part.some (f x)) = s.image f := by ext simp [eq_comm] theorem pimage_congr (h₁ : s = t) (h₂ : ∀ x ∈ t, f x = g x) : s.pimage f = t.pimage g := by aesop /-- Rewrite `s.pimage f` in terms of `Finset.filter`, `Finset.attach`, and `Finset.image`. -/ theorem pimage_eq_image_filter : s.pimage f = {x ∈ s | (f x).Dom}.attach.image fun x : { x // x ∈ filter (fun x => (f x).Dom) s } => (f x).get (mem_filter.mp x.coe_prop).2 := by aesop (add simp Part.mem_eq) theorem pimage_union [DecidableEq α] : (s ∪ t).pimage f = s.pimage f ∪ t.pimage f := coe_inj.1 <| by simp only [coe_pimage, coe_union, ← PFun.image_union] @[simp] theorem pimage_empty : pimage f ∅ = ∅ := by ext simp theorem pimage_subset {t : Finset β} : s.pimage f ⊆ t ↔ ∀ x ∈ s, ∀ y ∈ f x, y ∈ t := by simp [subset_iff, @forall_swap _ β] @[mono] theorem pimage_mono (h : s ⊆ t) : s.pimage f ⊆ t.pimage f := pimage_subset.2 fun x hx _ hy => mem_pimage.2 ⟨x, h hx, hy⟩ theorem pimage_inter [DecidableEq α] : (s ∩ t).pimage f ⊆ s.pimage f ∩ t.pimage f := by simp only [← coe_subset, coe_pimage, coe_inter, PFun.image_inter] end Finset
Zip.lean
/- Copyright (c) 2021 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.Data.Vector.Basic /-! # The `zipWith` operation on vectors. -/ namespace List namespace Vector section ZipWith variable {α β γ : Type*} {n : ℕ} (f : α → β → γ) /-- Apply the function `f : α → β → γ` to each corresponding pair of elements from two vectors. -/ def zipWith : Vector α n → Vector β n → Vector γ n := fun x y => ⟨List.zipWith f x.1 y.1, by simp⟩ @[simp] theorem zipWith_toList (x : Vector α n) (y : Vector β n) : (Vector.zipWith f x y).toList = List.zipWith f x.toList y.toList := rfl @[simp] theorem zipWith_get (x : Vector α n) (y : Vector β n) (i) : (Vector.zipWith f x y).get i = f (x.get i) (y.get i) := by dsimp only [Vector.zipWith, Vector.get] simp @[simp] theorem zipWith_tail (x : Vector α n) (y : Vector β n) : (Vector.zipWith f x y).tail = Vector.zipWith f x.tail y.tail := by ext simp [get_tail] @[to_additive] theorem prod_mul_prod_eq_prod_zipWith [CommMonoid α] (x y : Vector α n) : x.toList.prod * y.toList.prod = (Vector.zipWith (· * ·) x y).toList.prod := List.prod_mul_prod_eq_prod_zipWith_of_length_eq x.toList y.toList ((toList_length x).trans (toList_length y).symm) end ZipWith end Vector end List
imset2_gproduct.v
From mathcomp Require Import all_boot all_fingroup. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Open Scope group_scope. Check @ker_sdprodm.
Slope.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.LinearAlgebra.AffineSpace.AffineMap import Mathlib.Tactic.FieldSimp /-! # Slope of a function In this file we define the slope of a function `f : k → PE` taking values in an affine space over `k` and prove some basic theorems about `slope`. The `slope` function naturally appears in the Mean Value Theorem, and in the proof of the fact that a function with nonnegative second derivative on an interval is convex on this interval. ## Tags affine space, slope -/ open AffineMap variable {k E PE : Type*} [Field k] [AddCommGroup E] [Module k E] [AddTorsor E PE] /-- `slope f a b = (b - a)⁻¹ • (f b -ᵥ f a)` is the slope of a function `f` on the interval `[a, b]`. Note that `slope f a a = 0`, not the derivative of `f` at `a`. -/ def slope (f : k → PE) (a b : k) : E := (b - a)⁻¹ • (f b -ᵥ f a) theorem slope_fun_def (f : k → PE) : slope f = fun a b => (b - a)⁻¹ • (f b -ᵥ f a) := rfl theorem slope_def_field (f : k → k) (a b : k) : slope f a b = (f b - f a) / (b - a) := (div_eq_inv_mul _ _).symm theorem slope_fun_def_field (f : k → k) (a : k) : slope f a = fun b => (f b - f a) / (b - a) := (div_eq_inv_mul _ _).symm @[simp] theorem slope_same (f : k → PE) (a : k) : (slope f a a : E) = 0 := by rw [slope, sub_self, inv_zero, zero_smul] theorem slope_def_module (f : k → E) (a b : k) : slope f a b = (b - a)⁻¹ • (f b - f a) := rfl @[simp] theorem sub_smul_slope (f : k → PE) (a b : k) : (b - a) • slope f a b = f b -ᵥ f a := by rcases eq_or_ne a b with (rfl | hne) · rw [sub_self, zero_smul, vsub_self] · rw [slope, smul_inv_smul₀ (sub_ne_zero.2 hne.symm)] theorem sub_smul_slope_vadd (f : k → PE) (a b : k) : (b - a) • slope f a b +ᵥ f a = f b := by rw [sub_smul_slope, vsub_vadd] @[simp] theorem slope_vadd_const (f : k → E) (c : PE) : (slope fun x => f x +ᵥ c) = slope f := by ext a b simp only [slope, vadd_vsub_vadd_cancel_right, vsub_eq_sub] @[simp] theorem slope_sub_smul (f : k → E) {a b : k} (h : a ≠ b) : slope (fun x => (x - a) • f x) a b = f b := by simp [slope, inv_smul_smul₀ (sub_ne_zero.2 h.symm)] theorem eq_of_slope_eq_zero {f : k → PE} {a b : k} (h : slope f a b = (0 : E)) : f a = f b := by rw [← sub_smul_slope_vadd f a b, h, smul_zero, zero_vadd] theorem AffineMap.slope_comp {F PF : Type*} [AddCommGroup F] [Module k F] [AddTorsor F PF] (f : PE →ᵃ[k] PF) (g : k → PE) (a b : k) : slope (f ∘ g) a b = f.linear (slope g a b) := by simp only [slope, (· ∘ ·), f.linear.map_smul, f.linearMap_vsub] theorem LinearMap.slope_comp {F : Type*} [AddCommGroup F] [Module k F] (f : E →ₗ[k] F) (g : k → E) (a b : k) : slope (f ∘ g) a b = f (slope g a b) := f.toAffineMap.slope_comp g a b theorem slope_comm (f : k → PE) (a b : k) : slope f a b = slope f b a := by rw [slope, slope, ← neg_vsub_eq_vsub_rev, smul_neg, ← neg_smul, neg_inv, neg_sub] @[simp] lemma slope_neg (f : k → E) (x y : k) : slope (fun t ↦ -f t) x y = -slope f x y := by simp only [slope_def_module, neg_sub_neg, ← smul_neg, neg_sub] @[simp] lemma slope_neg_fun (f : k → E) : slope (-f) = -slope f := by ext x y; exact slope_neg f x y lemma slope_eq_zero_iff {f : k → E} {a b : k} : slope f a b = 0 ↔ f a = f b := by simp [slope, sub_eq_zero, eq_comm, or_iff_right_of_imp (congr_arg _)] /-- `slope f a c` is a linear combination of `slope f a b` and `slope f b c`. This version explicitly provides coefficients. If `a ≠ c`, then the sum of the coefficients is `1`, so it is actually an affine combination, see `lineMap_slope_slope_sub_div_sub`. -/ theorem sub_div_sub_smul_slope_add_sub_div_sub_smul_slope (f : k → PE) (a b c : k) : ((b - a) / (c - a)) • slope f a b + ((c - b) / (c - a)) • slope f b c = slope f a c := by by_cases hab : a = b · subst hab rw [sub_self, zero_div, zero_smul, zero_add] by_cases hac : a = c · simp [hac] · rw [div_self (sub_ne_zero.2 <| Ne.symm hac), one_smul] by_cases hbc : b = c · subst hbc simp [sub_ne_zero.2 (Ne.symm hab)] rw [add_comm] simp_rw [slope, div_eq_inv_mul, mul_smul, ← smul_add, smul_inv_smul₀ (sub_ne_zero.2 <| Ne.symm hab), smul_inv_smul₀ (sub_ne_zero.2 <| Ne.symm hbc), vsub_add_vsub_cancel] /-- `slope f a c` is an affine combination of `slope f a b` and `slope f b c`. This version uses `lineMap` to express this property. -/ theorem lineMap_slope_slope_sub_div_sub (f : k → PE) (a b c : k) (h : a ≠ c) : lineMap (slope f a b) (slope f b c) ((c - b) / (c - a)) = slope f a c := by field_simp [sub_ne_zero.2 h.symm, ← sub_div_sub_smul_slope_add_sub_div_sub_smul_slope f a b c, lineMap_apply_module] /-- `slope f a b` is an affine combination of `slope f a (lineMap a b r)` and `slope f (lineMap a b r) b`. We use `lineMap` to express this property. -/ theorem lineMap_slope_lineMap_slope_lineMap (f : k → PE) (a b r : k) : lineMap (slope f (lineMap a b r) b) (slope f a (lineMap a b r)) r = slope f a b := by obtain rfl | hab : a = b ∨ a ≠ b := Classical.em _; · simp rw [slope_comm _ a, slope_comm _ a, slope_comm _ _ b] convert lineMap_slope_slope_sub_div_sub f b (lineMap a b r) a hab.symm using 2 rw [lineMap_apply_ring, eq_div_iff (sub_ne_zero.2 hab), sub_mul, one_mul, mul_sub, ← sub_sub, sub_sub_cancel] section Order variable [LinearOrder k] [IsStrictOrderedRing k] [PartialOrder E] [IsOrderedAddMonoid E] [PosSMulMono k E] {f : k → E} {x y : k} lemma slope_nonneg_iff_of_le (hxy : x ≤ y) : 0 ≤ slope f x y ↔ f x ≤ f y := by by_cases hxeqy : x = y · simp [hxeqy] refine ⟨fun h ↦ ?_, fun h ↦ smul_nonneg (inv_nonneg.2 (sub_nonneg.2 hxy)) ?_⟩ · have := smul_nonneg (sub_nonneg.2 hxy) h rwa [slope, ← mul_smul, mul_inv_cancel₀ (mt sub_eq_zero.1 (Ne.symm hxeqy)), one_smul, vsub_eq_sub, sub_nonneg] at this · rwa [vsub_eq_sub, sub_nonneg] lemma slope_nonpos_iff_of_le (hxy : x ≤ y) : slope f x y ≤ 0 ↔ f y ≤ f x := by simpa using slope_nonneg_iff_of_le (f := -f) hxy lemma slope_pos_iff_of_le (hxy : x ≤ y) : 0 < slope f x y ↔ f x < f y := by simp_rw [lt_iff_le_and_ne, slope_nonneg_iff_of_le hxy, Ne, eq_comm, slope_eq_zero_iff] lemma slope_neg_iff_of_le (hxy : x ≤ y) : slope f x y < 0 ↔ f y < f x := by simpa using slope_pos_iff_of_le (f := -f) hxy end Order
NFA.lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Maja Kądziołka -/ import Mathlib.Computability.DFA import Mathlib.Data.Fintype.Powerset /-! # Nondeterministic Finite Automata A Nondeterministic Finite Automaton (NFA) is a state machine which decides membership in a particular `Language`, by following every possible path that describes an input string. We show that DFAs and NFAs can decide the same languages, by constructing an equivalent DFA for every NFA, and vice versa. As constructing a DFA from an NFA uses an exponential number of states, we re-prove the pumping lemma instead of lifting `DFA.pumping_lemma`, in order to obtain the optimal bound on the minimal length of the string. Like `DFA`, this definition allows for automata with infinite states; a `Fintype` instance must be supplied for true NFAs. ## Main definitions * `NFA α σ`: automaton over alphabet `α` and set of states `σ` * `NFA.evalFrom M S x`: set of possible ending states for an input word `x` and set of initial states `S` * `NFA.accepts M`: the language accepted by the NFA `M` * `NFA.Path M s t x`: a specific path from `s` to `t` for an input word `x` * `NFA.Path.supp p`: set of states visited by the path `p` ## Main theorems * `NFA.pumping_lemma`: every sufficiently long string accepted by the NFA has a substring that can be repeated arbitrarily many times (and have the overall string still be accepted) -/ open Set open Computability universe u v /-- An NFA is a set of states (`σ`), a transition function from state to state labelled by the alphabet (`step`), a set of starting states (`start`) and a set of acceptance states (`accept`). Note the transition function sends a state to a `Set` of states. These are the states that it may be sent to. -/ structure NFA (α : Type u) (σ : Type v) where /-- The NFA's transition function -/ step : σ → α → Set σ /-- Set of starting states -/ start : Set σ /-- Set of accepting states -/ accept : Set σ variable {α : Type u} {σ : Type v} {M : NFA α σ} namespace NFA instance : Inhabited (NFA α σ) := ⟨NFA.mk (fun _ _ => ∅) ∅ ∅⟩ variable (M) in /-- `M.stepSet S a` is the union of `M.step s a` for all `s ∈ S`. -/ def stepSet (S : Set σ) (a : α) : Set σ := ⋃ s ∈ S, M.step s a theorem mem_stepSet {s : σ} {S : Set σ} {a : α} : s ∈ M.stepSet S a ↔ ∃ t ∈ S, s ∈ M.step t a := by simp [stepSet] variable (M) in @[simp] theorem stepSet_empty (a : α) : M.stepSet ∅ a = ∅ := by simp [stepSet] variable (M) in @[simp] theorem stepSet_singleton (s : σ) (a : α) : M.stepSet {s} a = M.step s a := by simp [stepSet] variable (M) in /-- `M.evalFrom S x` computes all possible paths through `M` with input `x` starting at an element of `S`. -/ def evalFrom (S : Set σ) : List α → Set σ := List.foldl M.stepSet S variable (M) in @[simp] theorem evalFrom_nil (S : Set σ) : M.evalFrom S [] = S := rfl variable (M) in @[simp] theorem evalFrom_singleton (S : Set σ) (a : α) : M.evalFrom S [a] = M.stepSet S a := rfl variable (M) in @[simp] theorem evalFrom_cons (S : Set σ) (a : α) (x : List α) : M.evalFrom S (a :: x) = M.evalFrom (M.stepSet S a) x := rfl @[simp] theorem evalFrom_append_singleton (S : Set σ) (x : List α) (a : α) : M.evalFrom S (x ++ [a]) = M.stepSet (M.evalFrom S x) a := by simp only [evalFrom, List.foldl_append, List.foldl_cons, List.foldl_nil] variable (M) in @[simp] theorem evalFrom_biUnion {ι : Type*} (t : Set ι) (f : ι → Set σ) : ∀ (x : List α), M.evalFrom (⋃ i ∈ t, f i) x = ⋃ i ∈ t, M.evalFrom (f i) x | [] => by simp | a :: x => by simp [stepSet, evalFrom_biUnion _ _ x] variable (M) in theorem evalFrom_eq_biUnion_singleton (S : Set σ) (x : List α) : M.evalFrom S x = ⋃ s ∈ S, M.evalFrom {s} x := by simp [← evalFrom_biUnion] theorem mem_evalFrom_iff_exists {s : σ} {S : Set σ} {x : List α} : s ∈ M.evalFrom S x ↔ ∃ t ∈ S, s ∈ M.evalFrom {t} x := by rw [evalFrom_eq_biUnion_singleton] simp variable (M) in /-- `M.eval x` computes all possible paths though `M` with input `x` starting at an element of `M.start`. -/ def eval : List α → Set σ := M.evalFrom M.start variable (M) in @[simp] theorem eval_nil : M.eval [] = M.start := rfl variable (M) in @[simp] theorem eval_singleton (a : α) : M.eval [a] = M.stepSet M.start a := rfl variable (M) in @[simp] theorem eval_append_singleton (x : List α) (a : α) : M.eval (x ++ [a]) = M.stepSet (M.eval x) a := evalFrom_append_singleton .. variable (M) in /-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/ def accepts : Language α := {x | ∃ S ∈ M.accept, S ∈ M.eval x} theorem mem_accepts {x : List α} : x ∈ M.accepts ↔ ∃ S ∈ M.accept, S ∈ M.evalFrom M.start x := by rfl variable (M) in /-- `M.Path` represents a concrete path through the NFA from a start state to an end state for a particular word. Note that due to the non-deterministic nature of the automata, there can be more than one `Path` for a given word. Also note that this is `Type` and not a `Prop`, so that we can speak about the properties of a particular `Path`, such as the set of states visited along the way (defined as `Path.supp`). -/ inductive Path : σ → σ → List α → Type (max u v) | nil (s : σ) : Path s s [] | cons (t s u : σ) (a : α) (x : List α) : t ∈ M.step s a → Path t u x → Path s u (a :: x) /-- Set of states visited by a path. -/ @[simp] def Path.supp [DecidableEq σ] {s t : σ} {x : List α} : M.Path s t x → Finset σ | nil s => {s} | cons _ _ _ _ _ _ p => {s} ∪ p.supp theorem mem_evalFrom_iff_nonempty_path {s t : σ} {x : List α} : t ∈ M.evalFrom {s} x ↔ Nonempty (M.Path s t x) where mp h := match x with | [] => have h : s = t := by simp at h; tauto ⟨h ▸ Path.nil s⟩ | a :: x => have h : ∃ s' ∈ M.step s a, t ∈ M.evalFrom {s'} x := by rw [evalFrom_cons, mem_evalFrom_iff_exists, stepSet_singleton] at h; exact h let ⟨s', h₁, h₂⟩ := h let ⟨p'⟩ := mem_evalFrom_iff_nonempty_path.1 h₂ ⟨Path.cons s' _ _ _ _ h₁ p'⟩ mpr p := match p with | ⟨Path.nil s⟩ => by simp | ⟨Path.cons s' s t a x h₁ h₂⟩ => by rw [evalFrom_cons, stepSet_singleton, mem_evalFrom_iff_exists] exact ⟨s', h₁, mem_evalFrom_iff_nonempty_path.2 ⟨h₂⟩⟩ theorem accepts_iff_exists_path {x : List α} : x ∈ M.accepts ↔ ∃ s ∈ M.start, ∃ t ∈ M.accept, Nonempty (M.Path s t x) := by simp only [← mem_evalFrom_iff_nonempty_path, mem_accepts, mem_evalFrom_iff_exists (S := M.start)] tauto variable (M) in /-- `M.toDFA` is a `DFA` constructed from an `NFA` `M` using the subset construction. The states is the type of `Set`s of `M.state` and the step function is `M.stepSet`. -/ def toDFA : DFA α (Set σ) where step := M.stepSet start := M.start accept := { S | ∃ s ∈ S, s ∈ M.accept } @[simp] theorem toDFA_correct : M.toDFA.accepts = M.accepts := by ext x rw [mem_accepts, DFA.mem_accepts] constructor <;> · exact fun ⟨w, h2, h3⟩ => ⟨w, h3, h2⟩ theorem pumping_lemma [Fintype σ] {x : List α} (hx : x ∈ M.accepts) (hlen : Fintype.card (Set σ) ≤ List.length x) : ∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ Fintype.card (Set σ) ∧ b ≠ [] ∧ {a} * {b}∗ * {c} ≤ M.accepts := by rw [← toDFA_correct] at hx ⊢ exact M.toDFA.pumping_lemma hx hlen end NFA namespace DFA /-- `M.toNFA` is an `NFA` constructed from a `DFA` `M` by using the same start and accept states and a transition function which sends `s` with input `a` to the singleton `M.step s a`. -/ @[simps] def toNFA (M : DFA α σ) : NFA α σ where step s a := {M.step s a} start := {M.start} accept := M.accept @[simp] theorem toNFA_evalFrom_match (M : DFA α σ) (start : σ) (s : List α) : M.toNFA.evalFrom {start} s = {M.evalFrom start s} := by change List.foldl M.toNFA.stepSet {start} s = {List.foldl M.step start s} induction s generalizing start with | nil => tauto | cons a s ih => rw [List.foldl, List.foldl, show M.toNFA.stepSet {start} a = {M.step start a} by simp [NFA.stepSet] ] tauto @[simp] theorem toNFA_correct (M : DFA α σ) : M.toNFA.accepts = M.accepts := by ext x rw [NFA.mem_accepts, toNFA_start, toNFA_evalFrom_match] constructor · rintro ⟨S, hS₁, hS₂⟩ rwa [Set.mem_singleton_iff.mp hS₂] at hS₁ · exact fun h => ⟨M.eval x, h, rfl⟩ end DFA namespace NFA variable (M) in /-- `M.reverse` constructs an NFA with the same states as `M`, but all the transitions reversed. The resulting automaton accepts a word `x` if and only if `M` accepts `List.reverse x`. -/ @[simps] def reverse : NFA α σ where step s a := { s' | s ∈ M.step s' a } start := M.accept accept := M.start variable (M) in @[simp] theorem reverse_reverse : M.reverse.reverse = M := by simp [reverse] theorem disjoint_stepSet_reverse {a : α} {S S' : Set σ} : Disjoint S (M.reverse.stepSet S' a) ↔ Disjoint S' (M.stepSet S a) := by rw [← not_iff_not] simp only [Set.not_disjoint_iff, mem_stepSet, reverse_step, Set.mem_setOf_eq] tauto theorem disjoint_evalFrom_reverse {x : List α} {S S' : Set σ} (h : Disjoint S (M.reverse.evalFrom S' x)) : Disjoint S' (M.evalFrom S x.reverse) := by simp only [evalFrom, List.foldl_reverse] at h ⊢ induction x generalizing S S' with | nil => rw [disjoint_comm] exact h | cons x xs ih => rw [List.foldl_cons] at h rw [List.foldr_cons, ← NFA.disjoint_stepSet_reverse, disjoint_comm] exact ih h theorem disjoint_evalFrom_reverse_iff {x : List α} {S S' : Set σ} : Disjoint S (M.reverse.evalFrom S' x) ↔ Disjoint S' (M.evalFrom S x.reverse) := ⟨disjoint_evalFrom_reverse, fun h ↦ List.reverse_reverse x ▸ disjoint_evalFrom_reverse h⟩ @[simp] theorem mem_accepts_reverse {x : List α} : x ∈ M.reverse.accepts ↔ x.reverse ∈ M.accepts := by simp [mem_accepts, ← Set.not_disjoint_iff, disjoint_evalFrom_reverse_iff] end NFA namespace Language protected theorem IsRegular.reverse {L : Language α} (h : L.IsRegular) : L.reverse.IsRegular := have ⟨σ, _, M, hM⟩ := h ⟨_, inferInstance, M.toNFA.reverse.toDFA, by ext; simp [hM]⟩ protected theorem IsRegular.of_reverse {L : Language α} (h : L.reverse.IsRegular) : L.IsRegular := L.reverse_reverse ▸ h.reverse /-- Regular languages are closed under reversal. -/ @[simp] theorem isRegular_reverse_iff {L : Language α} : L.reverse.IsRegular ↔ L.IsRegular := ⟨.of_reverse, .reverse⟩ end Language
Rat.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.Algebra.Rat /-! # Homomorphisms of `ℚ`-algebras -/ namespace RingHom variable {R S : Type*} /-- Reinterpret a `RingHom` as a `ℚ`-algebra homomorphism. This actually yields an equivalence, see `RingHom.equivRatAlgHom`. -/ def toRatAlgHom [Ring R] [Ring S] [Algebra ℚ R] [Algebra ℚ S] (f : R →+* S) : R →ₐ[ℚ] S := { f with commutes' := f.map_rat_algebraMap } @[simp] theorem toRatAlgHom_toRingHom [Ring R] [Ring S] [Algebra ℚ R] [Algebra ℚ S] (f : R →+* S) : ↑f.toRatAlgHom = f := RingHom.ext fun _x => rfl @[simp] theorem toRatAlgHom_apply [Ring R] [Ring S] [Algebra ℚ R] [Algebra ℚ S] (f : R →+* S) (x : R) : f.toRatAlgHom x = f x := rfl end RingHom section variable {R S : Type*} @[simp] theorem AlgHom.toRingHom_toRatAlgHom [Ring R] [Ring S] [Algebra ℚ R] [Algebra ℚ S] (f : R →ₐ[ℚ] S) : (f : R →+* S).toRatAlgHom = f := AlgHom.ext fun _x => rfl /-- The equivalence between `RingHom` and `ℚ`-algebra homomorphisms. -/ @[simps] def RingHom.equivRatAlgHom [Ring R] [Ring S] [Algebra ℚ R] [Algebra ℚ S] : (R →+* S) ≃ (R →ₐ[ℚ] S) where toFun := RingHom.toRatAlgHom invFun := AlgHom.toRingHom left_inv f := RingHom.toRatAlgHom_toRingHom f right_inv f := AlgHom.toRingHom_toRatAlgHom f end
Basic.lean
/- Copyright (c) 2021 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import Mathlib.CategoryTheory.Category.Grpd import Mathlib.CategoryTheory.Groupoid import Mathlib.Topology.Category.TopCat.Basic import Mathlib.Topology.Homotopy.Path import Mathlib.Data.Set.Subsingleton /-! # Fundamental groupoid of a space Given a topological space `X`, we can define the fundamental groupoid of `X` to be the category with objects being points of `X`, and morphisms `x ⟶ y` being paths from `x` to `y`, quotiented by homotopy equivalence. With this, the fundamental group of `X` based at `x` is just the automorphism group of `x`. -/ open CategoryTheory universe u variable {X : Type u} [TopologicalSpace X] variable {x₀ x₁ : X} noncomputable section open unitInterval namespace Path namespace Homotopy section /-- Auxiliary function for `reflTransSymm`. -/ def reflTransSymmAux (x : I × I) : ℝ := if (x.2 : ℝ) ≤ 1 / 2 then x.1 * 2 * x.2 else x.1 * (2 - 2 * x.2) @[continuity, fun_prop] theorem continuous_reflTransSymmAux : Continuous reflTransSymmAux := by refine continuous_if_le ?_ ?_ (Continuous.continuousOn ?_) (Continuous.continuousOn ?_) ?_ · fun_prop · fun_prop · fun_prop · fun_prop intro x hx norm_num [hx, mul_assoc] theorem reflTransSymmAux_mem_I (x : I × I) : reflTransSymmAux x ∈ I := by dsimp only [reflTransSymmAux] split_ifs · constructor · apply mul_nonneg · apply mul_nonneg · unit_interval · norm_num · unit_interval · rw [mul_assoc] apply mul_le_one₀ · unit_interval · apply mul_nonneg · norm_num · unit_interval · linarith · constructor · apply mul_nonneg · unit_interval linarith [unitInterval.nonneg x.2, unitInterval.le_one x.2] · apply mul_le_one₀ · unit_interval · linarith [unitInterval.nonneg x.2, unitInterval.le_one x.2] · linarith [unitInterval.nonneg x.2, unitInterval.le_one x.2] /-- For any path `p` from `x₀` to `x₁`, we have a homotopy from the constant path based at `x₀` to `p.trans p.symm`. -/ def reflTransSymm (p : Path x₀ x₁) : Homotopy (Path.refl x₀) (p.trans p.symm) where toFun x := p ⟨reflTransSymmAux x, reflTransSymmAux_mem_I x⟩ continuous_toFun := by fun_prop map_zero_left := by simp [reflTransSymmAux] map_one_left x := by simp only [reflTransSymmAux, Path.trans] cases le_or_gt (x : ℝ) 2⁻¹ with | inl hx => simp [hx, ← extend_extends] | inr hx => simp? [hx.not_le, ← extend_extends] says simp only [one_div, hx.not_ge, ↓reduceIte, Set.Icc.coe_one, one_mul, ← extend_extends, extend_symm, ContinuousMap.coe_mk, Function.comp_apply] ring_nf prop' t := by norm_num [reflTransSymmAux] /-- For any path `p` from `x₀` to `x₁`, we have a homotopy from the constant path based at `x₁` to `p.symm.trans p`. -/ def reflSymmTrans (p : Path x₀ x₁) : Homotopy (Path.refl x₁) (p.symm.trans p) := (reflTransSymm p.symm).cast rfl <| congr_arg _ (Path.symm_symm _) end section TransRefl /-- Auxiliary function for `trans_refl_reparam`. -/ def transReflReparamAux (t : I) : ℝ := if (t : ℝ) ≤ 1 / 2 then 2 * t else 1 @[continuity, fun_prop] theorem continuous_transReflReparamAux : Continuous transReflReparamAux := by refine continuous_if_le ?_ ?_ (Continuous.continuousOn ?_) (Continuous.continuousOn ?_) ?_ <;> [fun_prop; fun_prop; fun_prop; fun_prop; skip] intro x hx simp [hx] theorem transReflReparamAux_mem_I (t : I) : transReflReparamAux t ∈ I := by unfold transReflReparamAux split_ifs <;> constructor <;> linarith [unitInterval.le_one t, unitInterval.nonneg t] theorem transReflReparamAux_zero : transReflReparamAux 0 = 0 := by norm_num [transReflReparamAux] theorem transReflReparamAux_one : transReflReparamAux 1 = 1 := by norm_num [transReflReparamAux] theorem trans_refl_reparam (p : Path x₀ x₁) : p.trans (Path.refl x₁) = p.reparam (fun t => ⟨transReflReparamAux t, transReflReparamAux_mem_I t⟩) (by fun_prop) (Subtype.ext transReflReparamAux_zero) (Subtype.ext transReflReparamAux_one) := by ext unfold transReflReparamAux simp only [Path.trans_apply, coe_reparam, Function.comp_apply, one_div, Path.refl_apply] split_ifs · rfl · rfl · simp · simp /-- For any path `p` from `x₀` to `x₁`, we have a homotopy from `p.trans (Path.refl x₁)` to `p`. -/ def transRefl (p : Path x₀ x₁) : Homotopy (p.trans (Path.refl x₁)) p := ((Homotopy.reparam p (fun t => ⟨transReflReparamAux t, transReflReparamAux_mem_I t⟩) (by fun_prop) (Subtype.ext transReflReparamAux_zero) (Subtype.ext transReflReparamAux_one)).cast rfl (trans_refl_reparam p).symm).symm /-- For any path `p` from `x₀` to `x₁`, we have a homotopy from `(Path.refl x₀).trans p` to `p`. -/ def reflTrans (p : Path x₀ x₁) : Homotopy ((Path.refl x₀).trans p) p := (transRefl p.symm).symm₂.cast (by simp) (by simp) end TransRefl section Assoc /-- Auxiliary function for `trans_assoc_reparam`. -/ def transAssocReparamAux (t : I) : ℝ := if (t : ℝ) ≤ 1 / 4 then 2 * t else if (t : ℝ) ≤ 1 / 2 then t + 1 / 4 else 1 / 2 * (t + 1) @[continuity, fun_prop] theorem continuous_transAssocReparamAux : Continuous transAssocReparamAux := by refine continuous_if_le ?_ ?_ (Continuous.continuousOn ?_) (continuous_if_le ?_ ?_ (Continuous.continuousOn ?_) (Continuous.continuousOn ?_) ?_).continuousOn ?_ <;> [fun_prop; fun_prop; fun_prop; fun_prop; fun_prop; fun_prop; fun_prop; skip; skip] <;> · intro x hx norm_num [hx] theorem transAssocReparamAux_mem_I (t : I) : transAssocReparamAux t ∈ I := by unfold transAssocReparamAux split_ifs <;> constructor <;> linarith [unitInterval.le_one t, unitInterval.nonneg t] theorem transAssocReparamAux_zero : transAssocReparamAux 0 = 0 := by norm_num [transAssocReparamAux] theorem transAssocReparamAux_one : transAssocReparamAux 1 = 1 := by norm_num [transAssocReparamAux] theorem trans_assoc_reparam {x₀ x₁ x₂ x₃ : X} (p : Path x₀ x₁) (q : Path x₁ x₂) (r : Path x₂ x₃) : (p.trans q).trans r = (p.trans (q.trans r)).reparam (fun t => ⟨transAssocReparamAux t, transAssocReparamAux_mem_I t⟩) (by fun_prop) (Subtype.ext transAssocReparamAux_zero) (Subtype.ext transAssocReparamAux_one) := by ext x simp only [transAssocReparamAux, Path.trans_apply, Function.comp_apply, mul_ite, Path.coe_reparam] -- TODO: why does split_ifs not reduce the ifs?????? split_ifs with h₁ h₂ h₃ h₄ h₅ · rfl iterate 6 exfalso; linarith · have h : 2 * (2 * (x : ℝ)) - 1 = 2 * (2 * (↑x + 1 / 4) - 1) := by linarith simp [h] iterate 6 exfalso; linarith · congr ring /-- For paths `p q r`, we have a homotopy from `(p.trans q).trans r` to `p.trans (q.trans r)`. -/ def transAssoc {x₀ x₁ x₂ x₃ : X} (p : Path x₀ x₁) (q : Path x₁ x₂) (r : Path x₂ x₃) : Homotopy ((p.trans q).trans r) (p.trans (q.trans r)) := ((Homotopy.reparam (p.trans (q.trans r)) (fun t => ⟨transAssocReparamAux t, transAssocReparamAux_mem_I t⟩) (by fun_prop) (Subtype.ext transAssocReparamAux_zero) (Subtype.ext transAssocReparamAux_one)).cast rfl (trans_assoc_reparam p q r).symm).symm end Assoc end Homotopy end Path /-- The fundamental groupoid of a space `X` is defined to be a wrapper around `X`, and we subsequently put a `CategoryTheory.Groupoid` structure on it. -/ @[ext] structure FundamentalGroupoid (X : Type u) where /-- View a term of `FundamentalGroupoid X` as a term of `X`. -/ as : X namespace FundamentalGroupoid /-- The equivalence between `X` and the underlying type of its fundamental groupoid. This is useful for transferring constructions (instances, etc.) from `X` to `πₓ X`. -/ @[simps] def equiv (X : Type*) : FundamentalGroupoid X ≃ X where toFun x := x.as invFun x := .mk x @[simp] lemma isEmpty_iff (X : Type*) : IsEmpty (FundamentalGroupoid X) ↔ IsEmpty X := equiv _ |>.isEmpty_congr instance (X : Type*) [IsEmpty X] : IsEmpty (FundamentalGroupoid X) := equiv _ |>.isEmpty @[simp] lemma nonempty_iff (X : Type*) : Nonempty (FundamentalGroupoid X) ↔ Nonempty X := equiv _ |>.nonempty_congr instance (X : Type*) [Nonempty X] : Nonempty (FundamentalGroupoid X) := equiv _ |>.nonempty @[simp] lemma subsingleton_iff (X : Type*) : Subsingleton (FundamentalGroupoid X) ↔ Subsingleton X := equiv _ |>.subsingleton_congr instance (X : Type*) [Subsingleton X] : Subsingleton (FundamentalGroupoid X) := equiv _ |>.subsingleton -- TODO: It seems that `Equiv.nontrivial_congr` doesn't exist. -- Once it is added, please add the corresponding lemma and instance. instance {X : Type u} [Inhabited X] : Inhabited (FundamentalGroupoid X) := ⟨⟨default⟩⟩ attribute [local instance] Path.Homotopic.setoid instance : CategoryTheory.Groupoid (FundamentalGroupoid X) where Hom x y := Path.Homotopic.Quotient x.as y.as id x := ⟦Path.refl x.as⟧ comp {_ _ _} := Path.Homotopic.Quotient.comp id_comp {x _} f := Quotient.inductionOn f fun a => show ⟦(Path.refl x.as).trans a⟧ = ⟦a⟧ from Quotient.sound ⟨Path.Homotopy.reflTrans a⟩ comp_id {_ y} f := Quotient.inductionOn f fun a => show ⟦a.trans (Path.refl y.as)⟧ = ⟦a⟧ from Quotient.sound ⟨Path.Homotopy.transRefl a⟩ assoc {_ _ _ _} f g h := Quotient.inductionOn₃ f g h fun p q r => show ⟦(p.trans q).trans r⟧ = ⟦p.trans (q.trans r)⟧ from Quotient.sound ⟨Path.Homotopy.transAssoc p q r⟩ inv {x y} p := Quotient.lift (fun l : Path x.as y.as => ⟦l.symm⟧) (by rintro a b ⟨h⟩ simp only rw [Quotient.eq] exact ⟨h.symm₂⟩) p inv_comp {_ y} f := Quotient.inductionOn f fun a => show ⟦a.symm.trans a⟧ = ⟦Path.refl y.as⟧ from Quotient.sound ⟨(Path.Homotopy.reflSymmTrans a).symm⟩ comp_inv {x _} f := Quotient.inductionOn f fun a => show ⟦a.trans a.symm⟧ = ⟦Path.refl x.as⟧ from Quotient.sound ⟨(Path.Homotopy.reflTransSymm a).symm⟩ theorem comp_eq (x y z : FundamentalGroupoid X) (p : x ⟶ y) (q : y ⟶ z) : p ≫ q = p.comp q := rfl theorem id_eq_path_refl (x : FundamentalGroupoid X) : 𝟙 x = ⟦Path.refl x.as⟧ := rfl /-- The functor sending a topological space `X` to its fundamental groupoid. -/ def fundamentalGroupoidFunctor : TopCat ⥤ CategoryTheory.Grpd where obj X := { α := FundamentalGroupoid X } map f := { obj := fun x => ⟨f x.as⟩ map := fun {X Y} p => by exact Path.Homotopic.Quotient.mapFn p f.hom map_id := fun _ => rfl map_comp := fun {x y z} p q => by refine Quotient.inductionOn₂ p q fun a b => ?_ simp only [comp_eq, ← Path.Homotopic.map_lift, ← Path.Homotopic.comp_lift, Path.map_trans] } map_id X := by simp only congr ext x y p refine Quotient.inductionOn p fun q => ?_ rw [← Path.Homotopic.map_lift] conv_rhs => rw [← q.map_id] rfl map_comp f g := by simp only congr ext x y p refine Quotient.inductionOn p fun q => ?_ simp only rfl @[inherit_doc] scoped notation "π" => FundamentalGroupoid.fundamentalGroupoidFunctor /-- The fundamental groupoid of a topological space. -/ scoped notation "πₓ" => FundamentalGroupoid.fundamentalGroupoidFunctor.obj /-- The functor between fundamental groupoids induced by a continuous map. -/ scoped notation "πₘ" => FundamentalGroupoid.fundamentalGroupoidFunctor.map theorem map_eq {X Y : TopCat} {x₀ x₁ : X} (f : C(X, Y)) (p : Path.Homotopic.Quotient x₀ x₁) : (πₘ (TopCat.ofHom f)).map p = p.mapFn f := rfl /-- Help the typechecker by converting a point in a groupoid back to a point in the underlying topological space. -/ abbrev toTop {X : TopCat} (x : πₓ X) : X := x.as /-- Help the typechecker by converting a point in a topological space to a point in the fundamental groupoid of that space. -/ abbrev fromTop {X : TopCat} (x : X) : πₓ X := ⟨x⟩ /-- Help the typechecker by converting an arrow in the fundamental groupoid of a topological space back to a path in that space (i.e., `Path.Homotopic.Quotient`). -/ abbrev toPath {X : TopCat} {x₀ x₁ : πₓ X} (p : x₀ ⟶ x₁) : Path.Homotopic.Quotient x₀.as x₁.as := p /-- Help the typechecker by converting a path in a topological space to an arrow in the fundamental groupoid of that space. -/ abbrev fromPath {X : TopCat} {x₀ x₁ : X} (p : Path.Homotopic.Quotient x₀ x₁) : FundamentalGroupoid.mk x₀ ⟶ FundamentalGroupoid.mk x₁ := p end FundamentalGroupoid
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.NumberTheory.NumberField.InfinitePlace.Ramification import Mathlib.NumberTheory.NumberField.InfinitePlace.TotallyRealComplex deprecated_module (since := "2025-04-30")
Kernel.lean
/- Copyright (c) 2023 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import Mathlib.Probability.ConditionalProbability import Mathlib.Probability.Kernel.Basic import Mathlib.Probability.Kernel.Composition.MeasureComp import Mathlib.Tactic.Peel import Mathlib.MeasureTheory.MeasurableSpace.Pi /-! # Independence with respect to a kernel and a measure A family of sets of sets `π : ι → Set (Set Ω)` is independent with respect to a kernel `κ : Kernel α Ω` and a measure `μ` on `α` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, then for `μ`-almost every `a : α`, `κ a (⋂ i in s, f i) = ∏ i ∈ s, κ a (f i)`. This notion of independence is a generalization of both independence and conditional independence. For conditional independence, `κ` is the conditional kernel `ProbabilityTheory.condExpKernel` and `μ` is the ambient measure. For (non-conditional) independence, `κ = Kernel.const Unit μ` and the measure is the Dirac measure on `Unit`. The main purpose of this file is to prove only once the properties that hold for both conditional and non-conditional independence. ## Main definitions * `ProbabilityTheory.Kernel.iIndepSets`: independence of a family of sets of sets. Variant for two sets of sets: `ProbabilityTheory.Kernel.IndepSets`. * `ProbabilityTheory.Kernel.iIndep`: independence of a family of σ-algebras. Variant for two σ-algebras: `Indep`. * `ProbabilityTheory.Kernel.iIndepSet`: independence of a family of sets. Variant for two sets: `ProbabilityTheory.Kernel.IndepSet`. * `ProbabilityTheory.Kernel.iIndepFun`: independence of a family of functions (random variables). Variant for two functions: `ProbabilityTheory.Kernel.IndepFun`. See the file `Mathlib/Probability/Kernel/Basic.lean` for a more detailed discussion of these definitions in the particular case of the usual independence notion. ## Main statements * `ProbabilityTheory.Kernel.iIndepSets.iIndep`: if π-systems are independent as sets of sets, then the measurable space structures they generate are independent. * `ProbabilityTheory.Kernel.IndepSets.Indep`: variant with two π-systems. -/ open Set MeasureTheory MeasurableSpace open scoped MeasureTheory ENNReal namespace ProbabilityTheory.Kernel variable {α Ω ι : Type*} section Definitions variable {_mα : MeasurableSpace α} /-- A family of sets of sets `π : ι → Set (Set Ω)` is independent with respect to a kernel `κ` and a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, then `∀ᵐ a ∂μ, κ a (⋂ i in s, f i) = ∏ i ∈ s, κ a (f i)`. It will be used for families of pi_systems. -/ def iIndepSets {_mΩ : MeasurableSpace Ω} (π : ι → Set (Set Ω)) (κ : Kernel α Ω) (μ : Measure α := by volume_tac) : Prop := ∀ (s : Finset ι) {f : ι → Set Ω} (_H : ∀ i, i ∈ s → f i ∈ π i), ∀ᵐ a ∂μ, κ a (⋂ i ∈ s, f i) = ∏ i ∈ s, κ a (f i) /-- Two sets of sets `s₁, s₂` are independent with respect to a kernel `κ` and a measure `μ` if for any sets `t₁ ∈ s₁, t₂ ∈ s₂`, then `∀ᵐ a ∂μ, κ a (t₁ ∩ t₂) = κ a (t₁) * κ a (t₂)` -/ def IndepSets {_mΩ : MeasurableSpace Ω} (s1 s2 : Set (Set Ω)) (κ : Kernel α Ω) (μ : Measure α := by volume_tac) : Prop := ∀ t1 t2 : Set Ω, t1 ∈ s1 → t2 ∈ s2 → (∀ᵐ a ∂μ, κ a (t1 ∩ t2) = κ a t1 * κ a t2) /-- A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a kernel `κ` and a measure `μ` if the family of sets of measurable sets they define is independent. -/ def iIndep (m : ι → MeasurableSpace Ω) {_mΩ : MeasurableSpace Ω} (κ : Kernel α Ω) (μ : Measure α := by volume_tac) : Prop := iIndepSets (fun x ↦ {s | MeasurableSet[m x] s}) κ μ /-- Two measurable space structures (or σ-algebras) `m₁, m₂` are independent with respect to a kernel `κ` and a measure `μ` if for any sets `t₁ ∈ m₁, t₂ ∈ m₂`, `∀ᵐ a ∂μ, κ a (t₁ ∩ t₂) = κ a (t₁) * κ a (t₂)` -/ def Indep (m₁ m₂ : MeasurableSpace Ω) {_mΩ : MeasurableSpace Ω} (κ : Kernel α Ω) (μ : Measure α := by volume_tac) : Prop := IndepSets {s | MeasurableSet[m₁] s} {s | MeasurableSet[m₂] s} κ μ /-- A family of sets is independent if the family of measurable space structures they generate is independent. For a set `s`, the generated measurable space has measurable sets `∅, s, sᶜ, univ`. -/ def iIndepSet {_mΩ : MeasurableSpace Ω} (s : ι → Set Ω) (κ : Kernel α Ω) (μ : Measure α := by volume_tac) : Prop := iIndep (m := fun i ↦ generateFrom {s i}) κ μ /-- Two sets are independent if the two measurable space structures they generate are independent. For a set `s`, the generated measurable space structure has measurable sets `∅, s, sᶜ, univ`. -/ def IndepSet {_mΩ : MeasurableSpace Ω} (s t : Set Ω) (κ : Kernel α Ω) (μ : Measure α := by volume_tac) : Prop := Indep (generateFrom {s}) (generateFrom {t}) κ μ /-- A family of functions defined on the same space `Ω` and taking values in possibly different spaces, each with a measurable space structure, is independent if the family of measurable space structures they generate on `Ω` is independent. For a function `g` with codomain having measurable space structure `m`, the generated measurable space structure is `MeasurableSpace.comap g m`. -/ def iIndepFun {_mΩ : MeasurableSpace Ω} {β : ι → Type*} [m : ∀ x : ι, MeasurableSpace (β x)] (f : ∀ x : ι, Ω → β x) (κ : Kernel α Ω) (μ : Measure α := by volume_tac) : Prop := iIndep (m := fun x ↦ MeasurableSpace.comap (f x) (m x)) κ μ /-- Two functions are independent if the two measurable space structures they generate are independent. For a function `f` with codomain having measurable space structure `m`, the generated measurable space structure is `MeasurableSpace.comap f m`. -/ def IndepFun {β γ} {_mΩ : MeasurableSpace Ω} [mβ : MeasurableSpace β] [mγ : MeasurableSpace γ] (f : Ω → β) (g : Ω → γ) (κ : Kernel α Ω) (μ : Measure α := by volume_tac) : Prop := Indep (MeasurableSpace.comap f mβ) (MeasurableSpace.comap g mγ) κ μ end Definitions section ByDefinition variable {β : ι → Type*} {mβ : ∀ i, MeasurableSpace (β i)} {_mα : MeasurableSpace α} {m : ι → MeasurableSpace Ω} {_mΩ : MeasurableSpace Ω} {κ η : Kernel α Ω} {μ : Measure α} {π : ι → Set (Set Ω)} {s : ι → Set Ω} {S : Finset ι} {f : ∀ x : ι, Ω → β x} {s1 s2 : Set (Set Ω)} @[simp] lemma iIndepSets_zero_right : iIndepSets π κ 0 := by simp [iIndepSets] @[simp] lemma indepSets_zero_right : IndepSets s1 s2 κ 0 := by simp [IndepSets] @[simp] lemma indepSets_zero_left : IndepSets s1 s2 (0 : Kernel α Ω) μ := by simp [IndepSets] @[simp] lemma iIndep_zero_right : iIndep m κ 0 := by simp [iIndep] @[simp] lemma indep_zero_right {m₁ m₂ : MeasurableSpace Ω} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} : Indep m₁ m₂ κ 0 := by simp [Indep] @[simp] lemma indep_zero_left {m₁ m₂ : MeasurableSpace Ω} {_mΩ : MeasurableSpace Ω} : Indep m₁ m₂ (0 : Kernel α Ω) μ := by simp [Indep] @[simp] lemma iIndepSet_zero_right : iIndepSet s κ 0 := by simp [iIndepSet] @[simp] lemma indepSet_zero_right {s t : Set Ω} : IndepSet s t κ 0 := by simp [IndepSet] @[simp] lemma indepSet_zero_left {s t : Set Ω} : IndepSet s t (0 : Kernel α Ω) μ := by simp [IndepSet] @[simp] lemma iIndepFun_zero_right {β : ι → Type*} {m : ∀ x : ι, MeasurableSpace (β x)} {f : ∀ x : ι, Ω → β x} : iIndepFun f κ 0 := by simp [iIndepFun] @[simp] lemma indepFun_zero_right {β γ} [MeasurableSpace β] [MeasurableSpace γ] {f : Ω → β} {g : Ω → γ} : IndepFun f g κ 0 := by simp [IndepFun] @[simp] lemma indepFun_zero_left {β γ} [MeasurableSpace β] [MeasurableSpace γ] {f : Ω → β} {g : Ω → γ} : IndepFun f g (0 : Kernel α Ω) μ := by simp [IndepFun] lemma iIndepSets_congr (h : κ =ᵐ[μ] η) : iIndepSets π κ μ ↔ iIndepSets π η μ := by peel 3 refine ⟨fun h' ↦ ?_, fun h' ↦ ?_⟩ <;> · filter_upwards [h, h'] with a ha h'a simpa [ha] using h'a alias ⟨iIndepSets.congr, _⟩ := iIndepSets_congr lemma indepSets_congr (h : κ =ᵐ[μ] η) : IndepSets s1 s2 κ μ ↔ IndepSets s1 s2 η μ := by peel 4 refine ⟨fun h' ↦ ?_, fun h' ↦ ?_⟩ <;> · filter_upwards [h, h'] with a ha h'a simpa [ha] using h'a alias ⟨IndepSets.congr, _⟩ := indepSets_congr lemma iIndep_congr (h : κ =ᵐ[μ] η) : iIndep m κ μ ↔ iIndep m η μ := iIndepSets_congr h alias ⟨iIndep.congr, _⟩ := iIndep_congr lemma indep_congr {m₁ m₂ : MeasurableSpace Ω} {_mΩ : MeasurableSpace Ω} {κ η : Kernel α Ω} (h : κ =ᵐ[μ] η) : Indep m₁ m₂ κ μ ↔ Indep m₁ m₂ η μ := indepSets_congr h alias ⟨Indep.congr, _⟩ := indep_congr lemma iIndepSet_congr (h : κ =ᵐ[μ] η) : iIndepSet s κ μ ↔ iIndepSet s η μ := iIndep_congr h alias ⟨iIndepSet.congr, _⟩ := iIndepSet_congr lemma indepSet_congr {s t : Set Ω} (h : κ =ᵐ[μ] η) : IndepSet s t κ μ ↔ IndepSet s t η μ := indep_congr h alias ⟨indepSet.congr, _⟩ := indepSet_congr lemma iIndepFun_congr {β : ι → Type*} {m : ∀ x : ι, MeasurableSpace (β x)} {f : ∀ x : ι, Ω → β x} (h : κ =ᵐ[μ] η) : iIndepFun f κ μ ↔ iIndepFun f η μ := iIndep_congr h alias ⟨iIndepFun.congr, _⟩ := iIndepFun_congr lemma indepFun_congr {β γ} [MeasurableSpace β] [MeasurableSpace γ] {f : Ω → β} {g : Ω → γ} (h : κ =ᵐ[μ] η) : IndepFun f g κ μ ↔ IndepFun f g η μ := indep_congr h alias ⟨IndepFun.congr, _⟩ := indepFun_congr lemma iIndepSets.meas_biInter (h : iIndepSets π κ μ) (s : Finset ι) {f : ι → Set Ω} (hf : ∀ i, i ∈ s → f i ∈ π i) : ∀ᵐ a ∂μ, κ a (⋂ i ∈ s, f i) = ∏ i ∈ s, κ a (f i) := h s hf lemma iIndepSets.ae_isProbabilityMeasure (h : iIndepSets π κ μ) : ∀ᵐ a ∂μ, IsProbabilityMeasure (κ a) := by filter_upwards [h.meas_biInter ∅ (f := fun _ ↦ Set.univ) (by simp)] with a ha exact ⟨by simpa using ha⟩ lemma iIndepSets.meas_iInter [Fintype ι] (h : iIndepSets π κ μ) (hs : ∀ i, s i ∈ π i) : ∀ᵐ a ∂μ, κ a (⋂ i, s i) = ∏ i, κ a (s i) := by filter_upwards [h.meas_biInter Finset.univ (fun _i _ ↦ hs _)] with a ha using by simp [← ha] lemma iIndep.iIndepSets' (hμ : iIndep m κ μ) : iIndepSets (fun x ↦ {s | MeasurableSet[m x] s}) κ μ := hμ lemma iIndep.ae_isProbabilityMeasure (h : iIndep m κ μ) : ∀ᵐ a ∂μ, IsProbabilityMeasure (κ a) := h.iIndepSets'.ae_isProbabilityMeasure lemma iIndep.meas_biInter (hμ : iIndep m κ μ) (hs : ∀ i, i ∈ S → MeasurableSet[m i] (s i)) : ∀ᵐ a ∂μ, κ a (⋂ i ∈ S, s i) = ∏ i ∈ S, κ a (s i) := hμ _ hs lemma iIndep.meas_iInter [Fintype ι] (h : iIndep m κ μ) (hs : ∀ i, MeasurableSet[m i] (s i)) : ∀ᵐ a ∂μ, κ a (⋂ i, s i) = ∏ i, κ a (s i) := by filter_upwards [h.meas_biInter (fun i (_ : i ∈ Finset.univ) ↦ hs _)] with a ha simp [← ha] @[nontriviality, simp] lemma iIndepSets.of_subsingleton [Subsingleton ι] {m : ι → Set (Set Ω)} {κ : Kernel α Ω} [IsMarkovKernel κ] : iIndepSets m κ μ := by rintro s f hf obtain rfl | ⟨i, rfl⟩ : s = ∅ ∨ ∃ i, s = {i} := by simpa using (subsingleton_of_subsingleton (s := s.toSet)).eq_empty_or_singleton all_goals simp @[nontriviality, simp] lemma iIndep.of_subsingleton [Subsingleton ι] {m : ι → MeasurableSpace Ω} {κ : Kernel α Ω} [IsMarkovKernel κ] : iIndep m κ μ := by simp [iIndep] @[nontriviality, simp] lemma iIndepFun.of_subsingleton [Subsingleton ι] {β : ι → Type*} {m : ∀ i, MeasurableSpace (β i)} {f : ∀ i, Ω → β i} [IsMarkovKernel κ] : iIndepFun f κ μ := by simp [iIndepFun] protected lemma iIndepFun.iIndep (hf : iIndepFun f κ μ) : iIndep (fun x ↦ (mβ x).comap (f x)) κ μ := hf lemma iIndepFun.ae_isProbabilityMeasure (h : iIndepFun f κ μ) : ∀ᵐ a ∂μ, IsProbabilityMeasure (κ a) := h.iIndep.ae_isProbabilityMeasure lemma iIndepFun.meas_biInter (hf : iIndepFun f κ μ) (hs : ∀ i, i ∈ S → MeasurableSet[(mβ i).comap (f i)] (s i)) : ∀ᵐ a ∂μ, κ a (⋂ i ∈ S, s i) = ∏ i ∈ S, κ a (s i) := hf.iIndep.meas_biInter hs lemma iIndepFun.meas_iInter [Fintype ι] (hf : iIndepFun f κ μ) (hs : ∀ i, MeasurableSet[(mβ i).comap (f i)] (s i)) : ∀ᵐ a ∂μ, κ a (⋂ i, s i) = ∏ i, κ a (s i) := hf.iIndep.meas_iInter hs lemma IndepFun.meas_inter {β γ : Type*} [mβ : MeasurableSpace β] [mγ : MeasurableSpace γ] {f : Ω → β} {g : Ω → γ} (hfg : IndepFun f g κ μ) {s t : Set Ω} (hs : MeasurableSet[mβ.comap f] s) (ht : MeasurableSet[mγ.comap g] t) : ∀ᵐ a ∂μ, κ a (s ∩ t) = κ a s * κ a t := hfg _ _ hs ht end ByDefinition section Indep variable {_mα : MeasurableSpace α} @[symm] theorem IndepSets.symm {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {s₁ s₂ : Set (Set Ω)} (h : IndepSets s₁ s₂ κ μ) : IndepSets s₂ s₁ κ μ := by intros t1 t2 ht1 ht2 filter_upwards [h t2 t1 ht2 ht1] with a ha rwa [Set.inter_comm, mul_comm] @[symm] theorem Indep.symm {m₁ m₂ : MeasurableSpace Ω} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h : Indep m₁ m₂ κ μ) : Indep m₂ m₁ κ μ := IndepSets.symm h theorem indep_bot_right (m' : MeasurableSpace Ω) {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] : Indep m' ⊥ κ μ := by intros s t _ ht rw [Set.mem_setOf_eq, MeasurableSpace.measurableSet_bot_iff] at ht rcases eq_zero_or_isMarkovKernel κ with rfl | h · simp refine Filter.Eventually.of_forall (fun a ↦ ?_) rcases ht with ht | ht · rw [ht, Set.inter_empty, measure_empty, mul_zero] · rw [ht, Set.inter_univ, measure_univ, mul_one] theorem indep_bot_left (m' : MeasurableSpace Ω) {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] : Indep ⊥ m' κ μ := (indep_bot_right m').symm theorem indepSet_empty_right {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] (s : Set Ω) : IndepSet s ∅ κ μ := by simp only [IndepSet, generateFrom_singleton_empty] exact indep_bot_right _ theorem indepSet_empty_left {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] (s : Set Ω) : IndepSet ∅ s κ μ := (indepSet_empty_right s).symm theorem indepSets_of_indepSets_of_le_left {s₁ s₂ s₃ : Set (Set Ω)} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h_indep : IndepSets s₁ s₂ κ μ) (h31 : s₃ ⊆ s₁) : IndepSets s₃ s₂ κ μ := fun t1 t2 ht1 ht2 => h_indep t1 t2 (Set.mem_of_subset_of_mem h31 ht1) ht2 theorem indepSets_of_indepSets_of_le_right {s₁ s₂ s₃ : Set (Set Ω)} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h_indep : IndepSets s₁ s₂ κ μ) (h32 : s₃ ⊆ s₂) : IndepSets s₁ s₃ κ μ := fun t1 t2 ht1 ht2 => h_indep t1 t2 ht1 (Set.mem_of_subset_of_mem h32 ht2) theorem indep_of_indep_of_le_left {m₁ m₂ m₃ : MeasurableSpace Ω} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h_indep : Indep m₁ m₂ κ μ) (h31 : m₃ ≤ m₁) : Indep m₃ m₂ κ μ := fun t1 t2 ht1 ht2 => h_indep t1 t2 (h31 _ ht1) ht2 theorem indep_of_indep_of_le_right {m₁ m₂ m₃ : MeasurableSpace Ω} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h_indep : Indep m₁ m₂ κ μ) (h32 : m₃ ≤ m₂) : Indep m₁ m₃ κ μ := fun t1 t2 ht1 ht2 => h_indep t1 t2 ht1 (h32 _ ht2) theorem IndepSets.union {s₁ s₂ s' : Set (Set Ω)} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h₁ : IndepSets s₁ s' κ μ) (h₂ : IndepSets s₂ s' κ μ) : IndepSets (s₁ ∪ s₂) s' κ μ := by intro t1 t2 ht1 ht2 rcases (Set.mem_union _ _ _).mp ht1 with ht1₁ | ht1₂ · exact h₁ t1 t2 ht1₁ ht2 · exact h₂ t1 t2 ht1₂ ht2 @[simp] theorem IndepSets.union_iff {s₁ s₂ s' : Set (Set Ω)} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} : IndepSets (s₁ ∪ s₂) s' κ μ ↔ IndepSets s₁ s' κ μ ∧ IndepSets s₂ s' κ μ := ⟨fun h => ⟨indepSets_of_indepSets_of_le_left h Set.subset_union_left, indepSets_of_indepSets_of_le_left h Set.subset_union_right⟩, fun h => IndepSets.union h.left h.right⟩ theorem IndepSets.iUnion {s : ι → Set (Set Ω)} {s' : Set (Set Ω)} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (hyp : ∀ n, IndepSets (s n) s' κ μ) : IndepSets (⋃ n, s n) s' κ μ := by intro t1 t2 ht1 ht2 rw [Set.mem_iUnion] at ht1 obtain ⟨n, ht1⟩ := ht1 exact hyp n t1 t2 ht1 ht2 theorem IndepSets.bUnion {s : ι → Set (Set Ω)} {s' : Set (Set Ω)} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {u : Set ι} (hyp : ∀ n ∈ u, IndepSets (s n) s' κ μ) : IndepSets (⋃ n ∈ u, s n) s' κ μ := by intro t1 t2 ht1 ht2 simp_rw [Set.mem_iUnion] at ht1 rcases ht1 with ⟨n, hpn, ht1⟩ exact hyp n hpn t1 t2 ht1 ht2 theorem IndepSets.inter {s₁ s' : Set (Set Ω)} (s₂ : Set (Set Ω)) {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h₁ : IndepSets s₁ s' κ μ) : IndepSets (s₁ ∩ s₂) s' κ μ := fun t1 t2 ht1 ht2 => h₁ t1 t2 ((Set.mem_inter_iff _ _ _).mp ht1).left ht2 theorem IndepSets.iInter {s : ι → Set (Set Ω)} {s' : Set (Set Ω)} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h : ∃ n, IndepSets (s n) s' κ μ) : IndepSets (⋂ n, s n) s' κ μ := by intro t1 t2 ht1 ht2; obtain ⟨n, h⟩ := h; exact h t1 t2 (Set.mem_iInter.mp ht1 n) ht2 theorem IndepSets.bInter {s : ι → Set (Set Ω)} {s' : Set (Set Ω)} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {u : Set ι} (h : ∃ n ∈ u, IndepSets (s n) s' κ μ) : IndepSets (⋂ n ∈ u, s n) s' κ μ := by intro t1 t2 ht1 ht2 rcases h with ⟨n, hn, h⟩ exact h t1 t2 (Set.biInter_subset_of_mem hn ht1) ht2 theorem iIndep_comap_mem_iff {f : ι → Set Ω} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} : iIndep (fun i => MeasurableSpace.comap (· ∈ f i) ⊤) κ μ ↔ iIndepSet f κ μ := by simp_rw [← generateFrom_singleton, iIndepSet] theorem iIndepSets_singleton_iff {s : ι → Set Ω} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} : iIndepSets (fun i ↦ {s i}) κ μ ↔ ∀ S : Finset ι, ∀ᵐ a ∂μ, κ a (⋂ i ∈ S, s i) = ∏ i ∈ S, κ a (s i) := by refine ⟨fun h S ↦ h S (fun i _ ↦ rfl), fun h S f hf ↦ ?_⟩ filter_upwards [h S] with a ha have : ∀ i ∈ S, κ a (f i) = κ a (s i) := fun i hi ↦ by rw [hf i hi] rwa [Finset.prod_congr rfl this, Set.iInter₂_congr hf] theorem indepSets_singleton_iff {s t : Set Ω} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} : IndepSets {s} {t} κ μ ↔ ∀ᵐ a ∂μ, κ a (s ∩ t) = κ a s * κ a t := ⟨fun h ↦ h s t rfl rfl, fun h s1 t1 hs1 ht1 ↦ by rwa [Set.mem_singleton_iff.mp hs1, Set.mem_singleton_iff.mp ht1]⟩ end Indep /-! ### Deducing `Indep` from `iIndep` -/ section FromiIndepToIndep variable {_mα : MeasurableSpace α} theorem iIndepSets.indepSets {s : ι → Set (Set Ω)} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h_indep : iIndepSets s κ μ) {i j : ι} (hij : i ≠ j) : IndepSets (s i) (s j) κ μ := by classical intro t₁ t₂ ht₁ ht₂ have hf_m : ∀ x : ι, x ∈ ({i, j} : Finset ι) → ite (x = i) t₁ t₂ ∈ s x := by intro x hx rcases Finset.mem_insert.mp hx with hx | hx · simp [hx, ht₁] · simp [Finset.mem_singleton.mp hx, hij.symm, ht₂] have h1 : t₁ = ite (i = i) t₁ t₂ := by simp only [if_true] have h2 : t₂ = ite (j = i) t₁ t₂ := by simp only [hij.symm, if_false] have h_inter : ⋂ (t : ι) (_ : t ∈ ({i, j} : Finset ι)), ite (t = i) t₁ t₂ = ite (i = i) t₁ t₂ ∩ ite (j = i) t₁ t₂ := by simp only [Finset.set_biInter_singleton, Finset.set_biInter_insert] filter_upwards [h_indep {i, j} hf_m] with a h_indep' have h_prod : (∏ t ∈ ({i, j} : Finset ι), κ a (ite (t = i) t₁ t₂)) = κ a (ite (i = i) t₁ t₂) * κ a (ite (j = i) t₁ t₂) := by simp only [hij, Finset.prod_singleton, Finset.prod_insert, not_false_iff, Finset.mem_singleton] grind theorem iIndep.indep {m : ι → MeasurableSpace Ω} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h_indep : iIndep m κ μ) {i j : ι} (hij : i ≠ j) : Indep (m i) (m j) κ μ := iIndepSets.indepSets h_indep hij theorem iIndepFun.indepFun {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {β : ι → Type*} {m : ∀ x, MeasurableSpace (β x)} {f : ∀ i, Ω → β i} (hf_Indep : iIndepFun f κ μ) {i j : ι} (hij : i ≠ j) : IndepFun (f i) (f j) κ μ := hf_Indep.indep hij end FromiIndepToIndep /-! ## π-system lemma Independence of measurable spaces is equivalent to independence of generating π-systems. -/ section FromMeasurableSpacesToSetsOfSets /-! ### Independence of measurable space structures implies independence of generating π-systems -/ variable {_mα : MeasurableSpace α} theorem iIndep.iIndepSets {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {m : ι → MeasurableSpace Ω} {s : ι → Set (Set Ω)} (hms : ∀ n, m n = generateFrom (s n)) (h_indep : iIndep m κ μ) : iIndepSets s κ μ := fun S f hfs => h_indep S fun x hxS => ((hms x).symm ▸ measurableSet_generateFrom (hfs x hxS) : MeasurableSet[m x] (f x)) theorem Indep.indepSets {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {s1 s2 : Set (Set Ω)} (h_indep : Indep (generateFrom s1) (generateFrom s2) κ μ) : IndepSets s1 s2 κ μ := fun t1 t2 ht1 ht2 => h_indep t1 t2 (measurableSet_generateFrom ht1) (measurableSet_generateFrom ht2) end FromMeasurableSpacesToSetsOfSets section FromPiSystemsToMeasurableSpaces /-! ### Independence of generating π-systems implies independence of measurable space structures -/ variable {_mα : MeasurableSpace α} theorem IndepSets.indep_aux {m₂ m : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] {p1 p2 : Set (Set Ω)} (h2 : m₂ ≤ m) (hp2 : IsPiSystem p2) (hpm2 : m₂ = generateFrom p2) (hyp : IndepSets p1 p2 κ μ) {t1 t2 : Set Ω} (ht1 : t1 ∈ p1) (ht1m : MeasurableSet[m] t1) (ht2m : MeasurableSet[m₂] t2) : ∀ᵐ a ∂μ, κ a (t1 ∩ t2) = κ a t1 * κ a t2 := by rcases eq_zero_or_isMarkovKernel κ with rfl | h · simp induction t2, ht2m using induction_on_inter hpm2 hp2 with | empty => simp | basic u hu => exact hyp t1 u ht1 hu | compl u hu ihu => filter_upwards [ihu] with a ha rw [← Set.diff_eq, ← Set.diff_self_inter, measure_diff inter_subset_left (ht1m.inter (h2 _ hu)).nullMeasurableSet (measure_ne_top _ _), ha, measure_compl (h2 _ hu) (measure_ne_top _ _), measure_univ, ENNReal.mul_sub, mul_one] exact fun _ _ ↦ measure_ne_top _ _ | iUnion f hfd hfm ihf => rw [← ae_all_iff] at ihf filter_upwards [ihf] with a ha rw [inter_iUnion, measure_iUnion, measure_iUnion hfd fun i ↦ h2 _ (hfm i)] · simp only [ENNReal.tsum_mul_left, ha] · exact hfd.mono fun i j h ↦ (h.inter_left' _).inter_right' _ · exact fun i ↦ .inter ht1m (h2 _ <| hfm i) /-- The measurable space structures generated by independent pi-systems are independent. -/ theorem IndepSets.indep {m1 m2 m : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] {p1 p2 : Set (Set Ω)} (h1 : m1 ≤ m) (h2 : m2 ≤ m) (hp1 : IsPiSystem p1) (hp2 : IsPiSystem p2) (hpm1 : m1 = generateFrom p1) (hpm2 : m2 = generateFrom p2) (hyp : IndepSets p1 p2 κ μ) : Indep m1 m2 κ μ := by rcases eq_zero_or_isMarkovKernel κ with rfl | h · simp intros t1 t2 ht1 ht2 induction t1, ht1 using induction_on_inter hpm1 hp1 with | empty => simp only [Set.empty_inter, measure_empty, zero_mul, Filter.eventually_true] | basic t ht => refine IndepSets.indep_aux h2 hp2 hpm2 hyp ht (h1 _ ?_) ht2 rw [hpm1] exact measurableSet_generateFrom ht | compl t ht iht => filter_upwards [iht] with a ha have : tᶜ ∩ t2 = t2 \ (t ∩ t2) := by rw [Set.inter_comm t, Set.diff_self_inter, Set.diff_eq_compl_inter] rw [this, Set.inter_comm t t2, measure_diff Set.inter_subset_left ((h2 _ ht2).inter (h1 _ ht)).nullMeasurableSet (measure_ne_top (κ a) _), Set.inter_comm, ha, measure_compl (h1 _ ht) (measure_ne_top (κ a) t), measure_univ, mul_comm (1 - κ a t), ENNReal.mul_sub (fun _ _ ↦ measure_ne_top (κ a) _), mul_one, mul_comm] | iUnion f hf_disj hf_meas h => rw [← ae_all_iff] at h filter_upwards [h] with a ha rw [Set.inter_comm, Set.inter_iUnion, measure_iUnion] · rw [measure_iUnion hf_disj (fun i ↦ h1 _ (hf_meas i))] rw [← ENNReal.tsum_mul_right] congr 1 with i rw [Set.inter_comm t2, ha i] · intros i j hij rw [Function.onFun, Set.inter_comm t2, Set.inter_comm t2] exact Disjoint.inter_left _ (Disjoint.inter_right _ (hf_disj hij)) · exact fun i ↦ (h2 _ ht2).inter (h1 _ (hf_meas i)) theorem IndepSets.indep' {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] {p1 p2 : Set (Set Ω)} (hp1m : ∀ s ∈ p1, MeasurableSet s) (hp2m : ∀ s ∈ p2, MeasurableSet s) (hp1 : IsPiSystem p1) (hp2 : IsPiSystem p2) (hyp : IndepSets p1 p2 κ μ) : Indep (generateFrom p1) (generateFrom p2) κ μ := hyp.indep (generateFrom_le hp1m) (generateFrom_le hp2m) hp1 hp2 rfl rfl variable {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} theorem indepSets_piiUnionInter_of_disjoint {s : ι → Set (Set Ω)} {S T : Set ι} (h_indep : iIndepSets s κ μ) (hST : Disjoint S T) : IndepSets (piiUnionInter s S) (piiUnionInter s T) κ μ := by rintro t1 t2 ⟨p1, hp1, f1, ht1_m, ht1_eq⟩ ⟨p2, hp2, f2, ht2_m, ht2_eq⟩ classical let g i := ite (i ∈ p1) (f1 i) Set.univ ∩ ite (i ∈ p2) (f2 i) Set.univ have h_P_inter : ∀ᵐ a ∂μ, κ a (t1 ∩ t2) = ∏ n ∈ p1 ∪ p2, κ a (g n) := by have hgm : ∀ i ∈ p1 ∪ p2, g i ∈ s i := by intro i hi_mem_union rw [Finset.mem_union] at hi_mem_union rcases hi_mem_union with hi1 | hi2 · have hi2 : i ∉ p2 := fun hip2 => Set.disjoint_left.mp hST (hp1 hi1) (hp2 hip2) simp_rw [g, if_pos hi1, if_neg hi2, Set.inter_univ] exact ht1_m i hi1 · have hi1 : i ∉ p1 := fun hip1 => Set.disjoint_right.mp hST (hp2 hi2) (hp1 hip1) simp_rw [g, if_neg hi1, if_pos hi2, Set.univ_inter] exact ht2_m i hi2 have h_p1_inter_p2 : ((⋂ x ∈ p1, f1 x) ∩ ⋂ x ∈ p2, f2 x) = ⋂ i ∈ p1 ∪ p2, ite (i ∈ p1) (f1 i) Set.univ ∩ ite (i ∈ p2) (f2 i) Set.univ := by ext1 x simp only [Set.mem_ite_univ_right, Set.mem_inter_iff, Set.mem_iInter, Finset.mem_union] exact ⟨fun h i _ => ⟨h.1 i, h.2 i⟩, fun h => ⟨fun i hi => (h i (Or.inl hi)).1 hi, fun i hi => (h i (Or.inr hi)).2 hi⟩⟩ filter_upwards [h_indep _ hgm] with a ha rw [ht1_eq, ht2_eq, h_p1_inter_p2, ← ha] filter_upwards [h_P_inter, h_indep p1 ht1_m, h_indep p2 ht2_m, h_indep.ae_isProbabilityMeasure] with a h_P_inter ha1 ha2 h' have h_μg : ∀ n, κ a (g n) = (ite (n ∈ p1) (κ a (f1 n)) 1) * (ite (n ∈ p2) (κ a (f2 n)) 1) := by intro n dsimp only [g] split_ifs with h1 h2 · exact absurd rfl (Set.disjoint_iff_forall_ne.mp hST (hp1 h1) (hp2 h2)) all_goals simp only [measure_univ, one_mul, mul_one, Set.inter_univ, Set.univ_inter] simp_rw [h_P_inter, h_μg, Finset.prod_mul_distrib, Finset.prod_ite_mem (p1 ∪ p2) p1 (fun x ↦ κ a (f1 x)), Finset.union_inter_cancel_left, Finset.prod_ite_mem (p1 ∪ p2) p2 (fun x => κ a (f2 x)), Finset.union_inter_cancel_right, ht1_eq, ← ha1, ht2_eq, ← ha2] theorem iIndepSet.indep_generateFrom_of_disjoint {s : ι → Set Ω} (hsm : ∀ n, MeasurableSet (s n)) (hs : iIndepSet s κ μ) (S T : Set ι) (hST : Disjoint S T) : Indep (generateFrom { t | ∃ n ∈ S, s n = t }) (generateFrom { t | ∃ k ∈ T, s k = t }) κ μ := by classical rcases eq_or_ne μ 0 with rfl | hμ · simp obtain ⟨η, η_eq, hη⟩ : ∃ (η : Kernel α Ω), κ =ᵐ[μ] η ∧ IsMarkovKernel η := exists_ae_eq_isMarkovKernel hs.ae_isProbabilityMeasure hμ apply Indep.congr (Filter.EventuallyEq.symm η_eq) rw [← generateFrom_piiUnionInter_singleton_left, ← generateFrom_piiUnionInter_singleton_left] refine IndepSets.indep' (fun t ht => generateFrom_piiUnionInter_le _ ?_ _ _ (measurableSet_generateFrom ht)) (fun t ht => generateFrom_piiUnionInter_le _ ?_ _ _ (measurableSet_generateFrom ht)) ?_ ?_ ?_ · exact fun k => generateFrom_le fun t ht => (Set.mem_singleton_iff.1 ht).symm ▸ hsm k · exact fun k => generateFrom_le fun t ht => (Set.mem_singleton_iff.1 ht).symm ▸ hsm k · exact isPiSystem_piiUnionInter _ (fun k => IsPiSystem.singleton _) _ · exact isPiSystem_piiUnionInter _ (fun k => IsPiSystem.singleton _) _ · exact indepSets_piiUnionInter_of_disjoint (iIndep.iIndepSets (fun n => rfl) (hs.congr η_eq)) hST theorem indep_iSup_of_disjoint {m : ι → MeasurableSpace Ω} (h_le : ∀ i, m i ≤ _mΩ) (h_indep : iIndep m κ μ) {S T : Set ι} (hST : Disjoint S T) : Indep (⨆ i ∈ S, m i) (⨆ i ∈ T, m i) κ μ := by classical rcases eq_or_ne μ 0 with rfl | hμ · simp obtain ⟨η, η_eq, hη⟩ : ∃ (η : Kernel α Ω), κ =ᵐ[μ] η ∧ IsMarkovKernel η := exists_ae_eq_isMarkovKernel h_indep.ae_isProbabilityMeasure hμ apply Indep.congr (Filter.EventuallyEq.symm η_eq) refine IndepSets.indep (iSup₂_le fun i _ => h_le i) (iSup₂_le fun i _ => h_le i) ?_ ?_ (generateFrom_piiUnionInter_measurableSet m S).symm (generateFrom_piiUnionInter_measurableSet m T).symm ?_ · exact isPiSystem_piiUnionInter _ (fun n => @isPiSystem_measurableSet Ω (m n)) _ · exact isPiSystem_piiUnionInter _ (fun n => @isPiSystem_measurableSet Ω (m n)) _ · exact indepSets_piiUnionInter_of_disjoint (h_indep.congr η_eq) hST theorem indep_iSup_of_directed_le {Ω} {m : ι → MeasurableSpace Ω} {m' m0 : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] (h_indep : ∀ i, Indep (m i) m' κ μ) (h_le : ∀ i, m i ≤ m0) (h_le' : m' ≤ m0) (hm : Directed (· ≤ ·) m) : Indep (⨆ i, m i) m' κ μ := by let p : ι → Set (Set Ω) := fun n => { t | MeasurableSet[m n] t } have hp : ∀ n, IsPiSystem (p n) := fun n => @isPiSystem_measurableSet Ω (m n) have h_gen_n : ∀ n, m n = generateFrom (p n) := fun n => (@generateFrom_measurableSet Ω (m n)).symm have hp_supr_pi : IsPiSystem (⋃ n, p n) := isPiSystem_iUnion_of_directed_le p hp hm let p' := { t : Set Ω | MeasurableSet[m'] t } have hp'_pi : IsPiSystem p' := @isPiSystem_measurableSet Ω m' have h_gen' : m' = generateFrom p' := (@generateFrom_measurableSet Ω m').symm -- the π-systems defined are independent have h_pi_system_indep : IndepSets (⋃ n, p n) p' κ μ := by refine IndepSets.iUnion ?_ conv at h_indep => intro i rw [h_gen_n i, h_gen'] exact fun n => (h_indep n).indepSets -- now go from π-systems to σ-algebras refine IndepSets.indep (iSup_le h_le) h_le' hp_supr_pi hp'_pi ?_ h_gen' h_pi_system_indep exact (generateFrom_iUnion_measurableSet _).symm theorem iIndepSet.indep_generateFrom_lt [Preorder ι] {s : ι → Set Ω} (hsm : ∀ n, MeasurableSet (s n)) (hs : iIndepSet s κ μ) (i : ι) : Indep (generateFrom {s i}) (generateFrom { t | ∃ j < i, s j = t }) κ μ := by convert iIndepSet.indep_generateFrom_of_disjoint hsm hs {i} { j | j < i } (Set.disjoint_singleton_left.mpr (lt_irrefl _)) using 1 simp only [Set.mem_singleton_iff, exists_eq_left, Set.setOf_eq_eq_singleton'] theorem iIndepSet.indep_generateFrom_le [Preorder ι] {s : ι → Set Ω} (hsm : ∀ n, MeasurableSet (s n)) (hs : iIndepSet s κ μ) (i : ι) {k : ι} (hk : i < k) : Indep (generateFrom {s k}) (generateFrom { t | ∃ j ≤ i, s j = t }) κ μ := by convert iIndepSet.indep_generateFrom_of_disjoint hsm hs {k} { j | j ≤ i } (Set.disjoint_singleton_left.mpr hk.not_ge) using 1 simp only [Set.mem_singleton_iff, exists_eq_left, Set.setOf_eq_eq_singleton'] theorem iIndepSet.indep_generateFrom_le_nat {s : ℕ → Set Ω} (hsm : ∀ n, MeasurableSet (s n)) (hs : iIndepSet s κ μ) (n : ℕ) : Indep (generateFrom {s (n + 1)}) (generateFrom { t | ∃ k ≤ n, s k = t }) κ μ := iIndepSet.indep_generateFrom_le hsm hs _ n.lt_succ_self theorem indep_iSup_of_monotone [SemilatticeSup ι] {Ω} {m : ι → MeasurableSpace Ω} {m' m0 : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] (h_indep : ∀ i, Indep (m i) m' κ μ) (h_le : ∀ i, m i ≤ m0) (h_le' : m' ≤ m0) (hm : Monotone m) : Indep (⨆ i, m i) m' κ μ := indep_iSup_of_directed_le h_indep h_le h_le' (Monotone.directed_le hm) theorem indep_iSup_of_antitone [SemilatticeInf ι] {Ω} {m : ι → MeasurableSpace Ω} {m' m0 : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} [IsZeroOrMarkovKernel κ] (h_indep : ∀ i, Indep (m i) m' κ μ) (h_le : ∀ i, m i ≤ m0) (h_le' : m' ≤ m0) (hm : Antitone m) : Indep (⨆ i, m i) m' κ μ := indep_iSup_of_directed_le h_indep h_le h_le' hm.directed_le theorem iIndepSets.piiUnionInter_of_notMem {π : ι → Set (Set Ω)} {a : ι} {S : Finset ι} (hp_ind : iIndepSets π κ μ) (haS : a ∉ S) : IndepSets (piiUnionInter π S) (π a) κ μ := by rintro t1 t2 ⟨s, hs_mem, ft1, hft1_mem, ht1_eq⟩ ht2_mem_pia rw [Finset.coe_subset] at hs_mem classical let f := fun n => ite (n = a) t2 (ite (n ∈ s) (ft1 n) Set.univ) have h_f_mem : ∀ n ∈ insert a s, f n ∈ π n := by intro n hn_mem_insert dsimp only [f] rcases Finset.mem_insert.mp hn_mem_insert with hn_mem | hn_mem · simp [hn_mem, ht2_mem_pia] · grind have h_f_mem_pi : ∀ n ∈ s, f n ∈ π n := fun x hxS => h_f_mem x (by simp [hxS]) have h_t1 : t1 = ⋂ n ∈ s, f n := by suffices h_forall : ∀ n ∈ s, f n = ft1 n by grind intro n hnS have hn_ne_a : n ≠ a := by rintro rfl; exact haS (hs_mem hnS) simp_rw [f, if_pos hnS, if_neg hn_ne_a] have h_μ_t1 : ∀ᵐ a' ∂μ, κ a' t1 = ∏ n ∈ s, κ a' (f n) := by filter_upwards [hp_ind s h_f_mem_pi] with a' ha' rw [h_t1, ← ha'] have h_t2 : t2 = f a := by simp [f] have h_μ_inter : ∀ᵐ a' ∂μ, κ a' (t1 ∩ t2) = ∏ n ∈ insert a s, κ a' (f n) := by have h_t1_inter_t2 : t1 ∩ t2 = ⋂ n ∈ insert a s, f n := by rw [h_t1, h_t2, Finset.set_biInter_insert, Set.inter_comm] filter_upwards [hp_ind (insert a s) h_f_mem] with a' ha' rw [h_t1_inter_t2, ← ha'] have has : a ∉ s := fun has_mem => haS (hs_mem has_mem) filter_upwards [h_μ_t1, h_μ_inter] with a' ha1 ha2 rw [ha2, Finset.prod_insert has, h_t2, mul_comm, ha1] @[deprecated (since := "2025-05-23")] alias iIndepSets.piiUnionInter_of_not_mem := iIndepSets.piiUnionInter_of_notMem /-- The measurable space structures generated by independent pi-systems are independent. -/ theorem iIndepSets.iIndep (m : ι → MeasurableSpace Ω) (h_le : ∀ i, m i ≤ _mΩ) (π : ι → Set (Set Ω)) (h_pi : ∀ n, IsPiSystem (π n)) (h_generate : ∀ i, m i = generateFrom (π i)) (h_ind : iIndepSets π κ μ) : iIndep m κ μ := by classical rcases eq_or_ne μ 0 with rfl | hμ · simp obtain ⟨η, η_eq, hη⟩ : ∃ (η : Kernel α Ω), κ =ᵐ[μ] η ∧ IsMarkovKernel η := exists_ae_eq_isMarkovKernel h_ind.ae_isProbabilityMeasure hμ apply iIndep.congr (Filter.EventuallyEq.symm η_eq) intro s f refine Finset.induction ?_ ?_ s · simp only [Finset.notMem_empty, Set.mem_setOf_eq, IsEmpty.forall_iff, implies_true, Set.iInter_of_empty, Set.iInter_univ, measure_univ, Finset.prod_empty, Filter.eventually_true] · intro a S ha_notin_S h_rec hf_m have hf_m_S : ∀ x ∈ S, MeasurableSet[m x] (f x) := fun x hx => hf_m x (by simp [hx]) let p := piiUnionInter π S set m_p := generateFrom p with hS_eq_generate have h_indep : Indep m_p (m a) η μ := by have hp : IsPiSystem p := isPiSystem_piiUnionInter π h_pi S have h_le' : ∀ i, generateFrom (π i) ≤ _mΩ := fun i ↦ (h_generate i).symm.trans_le (h_le i) have hm_p : m_p ≤ _mΩ := generateFrom_piiUnionInter_le π h_le' S exact IndepSets.indep hm_p (h_le a) hp (h_pi a) hS_eq_generate (h_generate a) (iIndepSets.piiUnionInter_of_notMem (h_ind.congr η_eq) ha_notin_S) have h := h_indep.symm (f a) (⋂ n ∈ S, f n) (hf_m a (Finset.mem_insert_self a S)) ?_ · filter_upwards [h_rec hf_m_S, h] with a' ha' h' rwa [Finset.set_biInter_insert, Finset.prod_insert ha_notin_S, ← ha'] · have h_le_p : ∀ i ∈ S, m i ≤ m_p := by intros n hn rw [hS_eq_generate, h_generate n] exact le_generateFrom_piiUnionInter (S : Set ι) hn have h_S_f : ∀ i ∈ S, MeasurableSet[m_p] (f i) := fun i hi ↦ (h_le_p i hi) (f i) (hf_m_S i hi) exact S.measurableSet_biInter h_S_f end FromPiSystemsToMeasurableSpaces section IndepSet /-! ### Independence of measurable sets We prove the following equivalences on `IndepSet`, for measurable sets `s, t`. * `IndepSet s t κ μ ↔ ∀ᵐ a ∂μ, κ a (s ∩ t) = κ a s * κ a t`, * `IndepSet s t κ μ ↔ IndepSets {s} {t} κ μ`. -/ variable {_mα : MeasurableSpace α} theorem iIndepSet_iff_iIndepSets_singleton {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {f : ι → Set Ω} (hf : ∀ i, MeasurableSet (f i)) : iIndepSet f κ μ ↔ iIndepSets (fun i ↦ {f i}) κ μ := ⟨iIndep.iIndepSets fun _ ↦ rfl, iIndepSets.iIndep _ (fun i ↦ generateFrom_le <| by rintro t (rfl : t = _); exact hf _) _ (fun _ ↦ IsPiSystem.singleton _) fun _ ↦ rfl⟩ theorem iIndepSet.meas_biInter {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {f : ι → Set Ω} (h : iIndepSet f κ μ) (s : Finset ι) : ∀ᵐ a ∂μ, κ a (⋂ i ∈ s, f i) = ∏ i ∈ s, κ a (f i) := iIndep.iIndepSets (fun _ ↦ rfl) h _ (by simp) theorem iIndepSet_iff_meas_biInter {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {f : ι → Set Ω} (hf : ∀ i, MeasurableSet (f i)) : iIndepSet f κ μ ↔ ∀ s, ∀ᵐ a ∂μ, κ a (⋂ i ∈ s, f i) = ∏ i ∈ s, κ a (f i) := (iIndepSet_iff_iIndepSets_singleton hf).trans iIndepSets_singleton_iff theorem iIndepSets.iIndepSet_of_mem {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {π : ι → Set (Set Ω)} {f : ι → Set Ω} (hfπ : ∀ i, f i ∈ π i) (hf : ∀ i, MeasurableSet (f i)) (hπ : iIndepSets π κ μ) : iIndepSet f κ μ := (iIndepSet_iff_meas_biInter hf).2 fun _t ↦ hπ.meas_biInter _ fun _i _ ↦ hfπ _ variable {s t : Set Ω} (S T : Set (Set Ω)) theorem indepSet_iff_indepSets_singleton {m0 : MeasurableSpace Ω} (hs_meas : MeasurableSet s) (ht_meas : MeasurableSet t) (κ : Kernel α Ω) (μ : Measure α) [IsZeroOrMarkovKernel κ] : IndepSet s t κ μ ↔ IndepSets {s} {t} κ μ := ⟨Indep.indepSets, fun h => IndepSets.indep (generateFrom_le fun u hu => by rwa [Set.mem_singleton_iff.mp hu]) (generateFrom_le fun u hu => by rwa [Set.mem_singleton_iff.mp hu]) (IsPiSystem.singleton s) (IsPiSystem.singleton t) rfl rfl h⟩ theorem indepSet_iff_measure_inter_eq_mul {_m0 : MeasurableSpace Ω} (hs_meas : MeasurableSet s) (ht_meas : MeasurableSet t) (κ : Kernel α Ω) (μ : Measure α) [IsZeroOrMarkovKernel κ] : IndepSet s t κ μ ↔ ∀ᵐ a ∂μ, κ a (s ∩ t) = κ a s * κ a t := (indepSet_iff_indepSets_singleton hs_meas ht_meas κ μ).trans indepSets_singleton_iff theorem IndepSet.measure_inter_eq_mul {_m0 : MeasurableSpace Ω} (κ : Kernel α Ω) (μ : Measure α) (h : IndepSet s t κ μ) : ∀ᵐ a ∂μ, κ a (s ∩ t) = κ a s * κ a t := Indep.indepSets h _ _ (by simp) (by simp) theorem IndepSets.indepSet_of_mem {_m0 : MeasurableSpace Ω} (hs : s ∈ S) (ht : t ∈ T) (hs_meas : MeasurableSet s) (ht_meas : MeasurableSet t) (κ : Kernel α Ω) (μ : Measure α) [IsZeroOrMarkovKernel κ] (h_indep : IndepSets S T κ μ) : IndepSet s t κ μ := (indepSet_iff_measure_inter_eq_mul hs_meas ht_meas κ μ).mpr (h_indep s t hs ht) theorem Indep.indepSet_of_measurableSet {m₁ m₂ _ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} (h_indep : Indep m₁ m₂ κ μ) {s t : Set Ω} (hs : MeasurableSet[m₁] s) (ht : MeasurableSet[m₂] t) : IndepSet s t κ μ := by refine fun s' t' hs' ht' => h_indep s' t' ?_ ?_ · induction s', hs' using generateFrom_induction with | hC t ht => exact ht ▸ hs | empty => exact @MeasurableSet.empty _ m₁ | compl u _ hu => exact hu.compl | iUnion f _ hf => exact .iUnion hf · induction t', ht' using generateFrom_induction with | hC s hs => exact hs ▸ ht | empty => exact @MeasurableSet.empty _ m₂ | compl u _ hu => exact hu.compl | iUnion f _ hf => exact .iUnion hf theorem indep_iff_forall_indepSet (m₁ m₂ : MeasurableSpace Ω) {_m0 : MeasurableSpace Ω} (κ : Kernel α Ω) (μ : Measure α) : Indep m₁ m₂ κ μ ↔ ∀ s t, MeasurableSet[m₁] s → MeasurableSet[m₂] t → IndepSet s t κ μ := ⟨fun h => fun _s _t hs ht => h.indepSet_of_measurableSet hs ht, fun h s t hs ht => h s t hs ht s t (measurableSet_generateFrom (Set.mem_singleton s)) (measurableSet_generateFrom (Set.mem_singleton t))⟩ end IndepSet section IndepFun /-! ### Independence of random variables -/ variable {β β' γ γ' : Type*} {_mα : MeasurableSpace α} {_mΩ : MeasurableSpace Ω} {κ : Kernel α Ω} {μ : Measure α} {f : Ω → β} {g : Ω → β'} theorem indepFun_iff_measure_inter_preimage_eq_mul {mβ : MeasurableSpace β} {mβ' : MeasurableSpace β'} : IndepFun f g κ μ ↔ ∀ s t, MeasurableSet s → MeasurableSet t → ∀ᵐ a ∂μ, κ a (f ⁻¹' s ∩ g ⁻¹' t) = κ a (f ⁻¹' s) * κ a (g ⁻¹' t) := by constructor <;> intro h · refine fun s t hs ht => h (f ⁻¹' s) (g ⁻¹' t) ⟨s, hs, rfl⟩ ⟨t, ht, rfl⟩ · rintro _ _ ⟨s, hs, rfl⟩ ⟨t, ht, rfl⟩; exact h s t hs ht alias ⟨IndepFun.measure_inter_preimage_eq_mul, _⟩ := indepFun_iff_measure_inter_preimage_eq_mul theorem iIndepFun_iff_measure_inter_preimage_eq_mul {ι : Type*} {β : ι → Type*} (m : ∀ x, MeasurableSpace (β x)) (f : ∀ i, Ω → β i) : iIndepFun f κ μ ↔ ∀ (S : Finset ι) {sets : ∀ i : ι, Set (β i)} (_H : ∀ i, i ∈ S → MeasurableSet[m i] (sets i)), ∀ᵐ a ∂μ, κ a (⋂ i ∈ S, (f i) ⁻¹' (sets i)) = ∏ i ∈ S, κ a ((f i) ⁻¹' (sets i)) := by refine ⟨fun h S sets h_meas => h _ fun i hi_mem => ⟨sets i, h_meas i hi_mem, rfl⟩, ?_⟩ intro h S setsΩ h_meas classical let setsβ : ∀ i : ι, Set (β i) := fun i => dite (i ∈ S) (fun hi_mem => (h_meas i hi_mem).choose) fun _ => Set.univ have h_measβ : ∀ i ∈ S, MeasurableSet[m i] (setsβ i) := by intro i hi_mem simp_rw [setsβ, dif_pos hi_mem] exact (h_meas i hi_mem).choose_spec.1 have h_preim : ∀ i ∈ S, setsΩ i = f i ⁻¹' setsβ i := by intro i hi_mem simp_rw [setsβ, dif_pos hi_mem] exact (h_meas i hi_mem).choose_spec.2.symm simp_all alias ⟨iIndepFun.measure_inter_preimage_eq_mul, _⟩ := iIndepFun_iff_measure_inter_preimage_eq_mul theorem iIndepFun.congr' {β : ι → Type*} {mβ : ∀ i, MeasurableSpace (β i)} {f g : Π i, Ω → β i} (hf : iIndepFun f κ μ) (h : ∀ i, ∀ᵐ a ∂μ, f i =ᵐ[κ a] g i) : iIndepFun g κ μ := by rw [iIndepFun_iff_measure_inter_preimage_eq_mul] at hf ⊢ intro S sets hmeas have : ∀ᵐ a ∂μ, ∀ i ∈ S, f i =ᵐ[κ a] g i := (ae_ball_iff (Finset.countable_toSet S)).2 (fun i hi ↦ h i) filter_upwards [this, hf S hmeas] with a ha h'a have A i (hi : i ∈ S) : (κ a) (g i ⁻¹' sets i) = (κ a) (f i ⁻¹' sets i) := by apply measure_congr filter_upwards [ha i hi] with ω hω change (g i ω ∈ sets i) = (f i ω ∈ sets i) simp [hω] have B : (κ a) (⋂ i ∈ S, g i ⁻¹' sets i) = (κ a) (⋂ i ∈ S, f i ⁻¹' sets i) := by apply measure_congr filter_upwards [(ae_ball_iff (Finset.countable_toSet S)).2 ha] with ω hω change (ω ∈ ⋂ i ∈ S, g i ⁻¹' sets i) = (ω ∈ ⋂ i ∈ S, f i ⁻¹' sets i) simp +contextual [hω] convert h'a using 2 with i hi exact A i hi theorem iIndepFun_congr' {β : ι → Type*} {mβ : ∀ i, MeasurableSpace (β i)} {f g : Π i, Ω → β i} (h : ∀ i, ∀ᵐ a ∂μ, f i =ᵐ[κ a] g i) : iIndepFun f κ μ ↔ iIndepFun g κ μ where mp h' := h'.congr' h mpr h' := by refine h'.congr' fun i ↦ ?_ filter_upwards [h i] with a ha using ha.symm lemma iIndepFun.comp {β γ : ι → Type*} {mβ : ∀ i, MeasurableSpace (β i)} {mγ : ∀ i, MeasurableSpace (γ i)} {f : ∀ i, Ω → β i} (h : iIndepFun f κ μ) (g : ∀ i, β i → γ i) (hg : ∀ i, Measurable (g i)) : iIndepFun (fun i ↦ g i ∘ f i) κ μ := by rw [iIndepFun_iff_measure_inter_preimage_eq_mul] at h ⊢ refine fun t s hs ↦ ?_ have := h t (sets := fun i ↦ g i ⁻¹' (s i)) (fun i a ↦ hg i (hs i a)) filter_upwards [this] with a ha simp_rw [Set.preimage_comp] exact ha lemma iIndepFun.comp₀ {β γ : ι → Type*} {mβ : ∀ i, MeasurableSpace (β i)} {mγ : ∀ i, MeasurableSpace (γ i)} {f : ∀ i, Ω → β i} (h : iIndepFun f κ μ) (g : ∀ i, β i → γ i) (hf : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (hg : ∀ i, AEMeasurable (g i) ((κ ∘ₘ μ).map (f i))) : iIndepFun (fun i ↦ g i ∘ f i) κ μ := by have h : iIndepFun (fun i ↦ ((hg i).mk (g i)) ∘ f i) κ μ := iIndepFun.comp h (fun i ↦ (hg i).mk (g i)) fun i ↦ (hg i).measurable_mk have h_ae i := ae_of_ae_map (hf i) (hg i).ae_eq_mk.symm exact iIndepFun.congr' h fun i ↦ Measure.ae_ae_of_ae_comp (h_ae i) theorem indepFun_iff_indepSet_preimage {mβ : MeasurableSpace β} {mβ' : MeasurableSpace β'} [IsZeroOrMarkovKernel κ] (hf : Measurable f) (hg : Measurable g) : IndepFun f g κ μ ↔ ∀ s t, MeasurableSet s → MeasurableSet t → IndepSet (f ⁻¹' s) (g ⁻¹' t) κ μ := by refine indepFun_iff_measure_inter_preimage_eq_mul.trans ?_ constructor <;> intro h s t hs ht <;> specialize h s t hs ht · rwa [indepSet_iff_measure_inter_eq_mul (hf hs) (hg ht) κ μ] · rwa [← indepSet_iff_measure_inter_eq_mul (hf hs) (hg ht) κ μ] @[symm] nonrec theorem IndepFun.symm {_ : MeasurableSpace β} {_ : MeasurableSpace β'} (hfg : IndepFun f g κ μ) : IndepFun g f κ μ := hfg.symm theorem IndepFun.congr' {mβ : MeasurableSpace β} {mβ' : MeasurableSpace β'} {f' : Ω → β} {g' : Ω → β'} (hfg : IndepFun f g κ μ) (hf : ∀ᵐ a ∂μ, f =ᵐ[κ a] f') (hg : ∀ᵐ a ∂μ, g =ᵐ[κ a] g') : IndepFun f' g' κ μ := by rintro _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩ filter_upwards [hf, hg, hfg _ _ ⟨_, hA, rfl⟩ ⟨_, hB, rfl⟩] with a hf' hg' hfg' have h1 : f ⁻¹' A =ᵐ[κ a] f' ⁻¹' A := hf'.fun_comp A have h2 : g ⁻¹' B =ᵐ[κ a] g' ⁻¹' B := hg'.fun_comp B rwa [← measure_congr h1, ← measure_congr h2, ← measure_congr (h1.inter h2)] @[deprecated (since := "2025-03-18")] alias IndepFun.ae_eq := IndepFun.congr' theorem IndepFun.comp {mβ : MeasurableSpace β} {mβ' : MeasurableSpace β'} {mγ : MeasurableSpace γ} {mγ' : MeasurableSpace γ'} {φ : β → γ} {ψ : β' → γ'} (hfg : IndepFun f g κ μ) (hφ : Measurable φ) (hψ : Measurable ψ) : IndepFun (φ ∘ f) (ψ ∘ g) κ μ := by rintro _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩ apply hfg · exact ⟨φ ⁻¹' A, hφ hA, Set.preimage_comp.symm⟩ · exact ⟨ψ ⁻¹' B, hψ hB, Set.preimage_comp.symm⟩ theorem IndepFun.comp₀ {mβ : MeasurableSpace β} {mβ' : MeasurableSpace β'} {mγ : MeasurableSpace γ} {mγ' : MeasurableSpace γ'} {φ : β → γ} {ψ : β' → γ'} (hfg : IndepFun f g κ μ) (hf : AEMeasurable f (κ ∘ₘ μ)) (hg : AEMeasurable g (κ ∘ₘ μ)) (hφ : AEMeasurable φ ((κ ∘ₘ μ).map f)) (hψ : AEMeasurable ψ ((κ ∘ₘ μ).map g)) : IndepFun (φ ∘ f) (ψ ∘ g) κ μ := by have h : IndepFun ((hφ.mk φ) ∘ f) ((hψ.mk ψ) ∘ g) κ μ := by refine IndepFun.comp hfg hφ.measurable_mk hψ.measurable_mk have hφ_ae := ae_of_ae_map hf hφ.ae_eq_mk have hψ_ae := ae_of_ae_map hg hψ.ae_eq_mk refine IndepFun.congr' h ?_ ?_ · filter_upwards [Measure.ae_ae_of_ae_comp (hφ_ae)] with a haφ filter_upwards [haφ] with ω hωφ simp [hωφ] · filter_upwards [Measure.ae_ae_of_ae_comp (hψ_ae)] with a haψ filter_upwards [haψ] with ω hωψ simp [hωψ] theorem IndepFun.neg_right {_mβ : MeasurableSpace β} {_mβ' : MeasurableSpace β'} [Neg β'] [MeasurableNeg β'] (hfg : IndepFun f g κ μ) : IndepFun f (-g) κ μ := hfg.comp measurable_id measurable_neg theorem IndepFun.neg_left {_mβ : MeasurableSpace β} {_mβ' : MeasurableSpace β'} [Neg β] [MeasurableNeg β] (hfg : IndepFun f g κ μ) : IndepFun (-f) g κ μ := hfg.comp measurable_neg measurable_id section iIndepFun variable {β : ι → Type*} {m : ∀ i, MeasurableSpace (β i)} {f : ∀ i, Ω → β i} /-- If `f` is a family of mutually independent random variables (`iIndepFun m f μ`) and `S, T` are two disjoint finite index sets, then the tuple formed by `f i` for `i ∈ S` is independent of the tuple `(f i)_i` for `i ∈ T`. -/ theorem iIndepFun.indepFun_finset (S T : Finset ι) (hST : Disjoint S T) (hf_Indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) : IndepFun (fun a (i : S) => f i a) (fun a (i : T) => f i a) κ μ := by rcases eq_or_ne μ 0 with rfl | hμ · simp obtain ⟨η, η_eq, hη⟩ : ∃ (η : Kernel α Ω), κ =ᵐ[μ] η ∧ IsMarkovKernel η := exists_ae_eq_isMarkovKernel hf_Indep.ae_isProbabilityMeasure hμ apply IndepFun.congr (Filter.EventuallyEq.symm η_eq) -- We introduce π-systems, built from the π-system of boxes which generates `MeasurableSpace.pi`. let πSβ := Set.pi (Set.univ : Set S) '' Set.pi (Set.univ : Set S) fun i => { s : Set (β i) | MeasurableSet[m i] s } let πS := { s : Set Ω | ∃ t ∈ πSβ, (fun a (i : S) => f i a) ⁻¹' t = s } have hπS_pi : IsPiSystem πS := by exact IsPiSystem.comap (@isPiSystem_pi _ _ ?_) _ have hπS_gen : (MeasurableSpace.pi.comap fun a (i : S) => f i a) = generateFrom πS := by rw [generateFrom_pi.symm, comap_generateFrom] congr let πTβ := Set.pi (Set.univ : Set T) '' Set.pi (Set.univ : Set T) fun i => { s : Set (β i) | MeasurableSet[m i] s } let πT := { s : Set Ω | ∃ t ∈ πTβ, (fun a (i : T) => f i a) ⁻¹' t = s } have hπT_pi : IsPiSystem πT := by exact IsPiSystem.comap (@isPiSystem_pi _ _ ?_) _ have hπT_gen : (MeasurableSpace.pi.comap fun a (i : T) => f i a) = generateFrom πT := by rw [generateFrom_pi.symm, comap_generateFrom] congr -- To prove independence, we prove independence of the generating π-systems. refine IndepSets.indep (Measurable.comap_le (measurable_pi_iff.mpr fun i => hf_meas i)) (Measurable.comap_le (measurable_pi_iff.mpr fun i => hf_meas i)) hπS_pi hπT_pi hπS_gen hπT_gen ?_ rintro _ _ ⟨s, ⟨sets_s, hs1, hs2⟩, rfl⟩ ⟨t, ⟨sets_t, ht1, ht2⟩, rfl⟩ simp only [Set.mem_univ_pi, Set.mem_setOf_eq] at hs1 ht1 rw [← hs2, ← ht2] classical let sets_s' : ∀ i : ι, Set (β i) := fun i => dite (i ∈ S) (fun hi => sets_s ⟨i, hi⟩) fun _ => Set.univ have h_sets_s'_eq : ∀ {i} (hi : i ∈ S), sets_s' i = sets_s ⟨i, hi⟩ := by intro i hi; simp_rw [sets_s', dif_pos hi] have h_sets_s'_univ : ∀ {i} (_hi : i ∈ T), sets_s' i = Set.univ := by intro i hi; simp_rw [sets_s', dif_neg (Finset.disjoint_right.mp hST hi)] let sets_t' : ∀ i : ι, Set (β i) := fun i => dite (i ∈ T) (fun hi => sets_t ⟨i, hi⟩) fun _ => Set.univ have h_sets_t'_univ : ∀ {i} (_hi : i ∈ S), sets_t' i = Set.univ := by intro i hi; simp_rw [sets_t', dif_neg (Finset.disjoint_left.mp hST hi)] have h_meas_s' : ∀ i ∈ S, MeasurableSet (sets_s' i) := by intro i hi; rw [h_sets_s'_eq hi]; exact hs1 _ have h_meas_t' : ∀ i ∈ T, MeasurableSet (sets_t' i) := by intro i hi; simp_rw [sets_t', dif_pos hi]; exact ht1 _ have h_eq_inter_S : (fun (ω : Ω) (i : ↥S) => f (↑i) ω) ⁻¹' Set.pi Set.univ sets_s = ⋂ i ∈ S, f i ⁻¹' sets_s' i := by ext1 x simp_rw [Set.mem_preimage, Set.mem_univ_pi, Set.mem_iInter] grind have h_eq_inter_T : (fun (ω : Ω) (i : ↥T) => f (↑i) ω) ⁻¹' Set.pi Set.univ sets_t = ⋂ i ∈ T, f i ⁻¹' sets_t' i := by ext1 x simp only [Set.mem_preimage, Set.mem_univ_pi, Set.mem_iInter] constructor <;> intro h · intro i hi; simp_rw [sets_t', dif_pos hi]; exact h ⟨i, hi⟩ · grind replace hf_Indep := hf_Indep.congr η_eq rw [iIndepFun_iff_measure_inter_preimage_eq_mul] at hf_Indep have h_Inter_inter : ((⋂ i ∈ S, f i ⁻¹' sets_s' i) ∩ ⋂ i ∈ T, f i ⁻¹' sets_t' i) = ⋂ i ∈ S ∪ T, f i ⁻¹' (sets_s' i ∩ sets_t' i) := by ext1 x simp_rw [Set.mem_inter_iff, Set.mem_iInter, Set.mem_preimage, Finset.mem_union] constructor <;> intro h · grind · exact ⟨fun i hi => (h i (Or.inl hi)).1, fun i hi => (h i (Or.inr hi)).2⟩ have h_meas_inter : ∀ i ∈ S ∪ T, MeasurableSet (sets_s' i ∩ sets_t' i) := by intros i hi_mem rw [Finset.mem_union] at hi_mem rcases hi_mem with hi_mem | hi_mem · rw [h_sets_t'_univ hi_mem, Set.inter_univ] exact h_meas_s' i hi_mem · rw [h_sets_s'_univ hi_mem, Set.univ_inter] exact h_meas_t' i hi_mem filter_upwards [hf_Indep S h_meas_s', hf_Indep T h_meas_t', hf_Indep (S ∪ T) h_meas_inter] with a h_indepS h_indepT h_indepST rw [h_eq_inter_S, h_eq_inter_T, h_indepS, h_indepT, h_Inter_inter, h_indepST, Finset.prod_union hST] congr 1 · refine Finset.prod_congr rfl fun i hi => ?_ rw [h_sets_t'_univ hi, Set.inter_univ] · refine Finset.prod_congr rfl fun i hi => ?_ rw [h_sets_s'_univ hi, Set.univ_inter] theorem iIndepFun.indepFun_finset₀ (S T : Finset ι) (hST : Disjoint S T) (hf_Indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) : IndepFun (fun a (i : S) ↦ f i a) (fun a (i : T) ↦ f i a) κ μ := by have h : IndepFun (fun a (i : S) ↦ (hf_meas i).mk (f i) a) (fun a (i : T) ↦ (hf_meas i).mk (f i) a) κ μ := by refine iIndepFun.indepFun_finset S T hST ?_ fun i ↦ (hf_meas i).measurable_mk exact iIndepFun.congr' hf_Indep fun i ↦ Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk refine IndepFun.congr' h ?_ ?_ · have : ∀ᵐ (a : α) ∂μ, ∀ (i : S), f i =ᵐ[κ a] (hf_meas i).mk := by rw [ae_all_iff] exact fun i ↦ Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk filter_upwards [this] with a ha filter_upwards [ae_all_iff.2 ha] with b hb ext i exact (hb i).symm · have : ∀ᵐ (a : α) ∂μ, ∀ (i : T), f i =ᵐ[κ a] (hf_meas i).mk := by rw [ae_all_iff] exact fun i ↦ Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk filter_upwards [this] with a ha filter_upwards [ae_all_iff.2 ha] with b hb ext i exact (hb i).symm theorem iIndepFun.indepFun_prodMk (hf_Indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) (i j k : ι) (hik : i ≠ k) (hjk : j ≠ k) : IndepFun (fun a => (f i a, f j a)) (f k) κ μ := by classical have h_right : f k = (fun p : ∀ j : ({k} : Finset ι), β j => p ⟨k, Finset.mem_singleton_self k⟩) ∘ fun a (j : ({k} : Finset ι)) => f j a := rfl have h_meas_right : Measurable fun p : ∀ j : ({k} : Finset ι), β j => p ⟨k, Finset.mem_singleton_self k⟩ := measurable_pi_apply _ let s : Finset ι := {i, j} have h_left : (fun ω => (f i ω, f j ω)) = (fun p : ∀ l : s, β l => (p ⟨i, Finset.mem_insert_self i _⟩, p ⟨j, Finset.mem_insert_of_mem (Finset.mem_singleton_self _)⟩)) ∘ fun a (j : s) => f j a := by ext1 a simp only constructor have h_meas_left : Measurable fun p : ∀ l : s, β l => (p ⟨i, Finset.mem_insert_self i _⟩, p ⟨j, Finset.mem_insert_of_mem (Finset.mem_singleton_self _)⟩) := Measurable.prod (measurable_pi_apply _) (measurable_pi_apply _) rw [h_left, h_right] refine (hf_Indep.indepFun_finset s {k} ?_ hf_meas).comp h_meas_left h_meas_right rw [Finset.disjoint_singleton_right] simp only [s, Finset.mem_insert, Finset.mem_singleton, not_or] exact ⟨hik.symm, hjk.symm⟩ @[deprecated (since := "2025-03-05")] alias ProbabilityTheory.Kernel.iIndepFun.indepFun_prod_mk := iIndepFun.indepFun_prodMk theorem iIndepFun.indepFun_prodMk₀ (hf_Indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (i j k : ι) (hik : i ≠ k) (hjk : j ≠ k) : IndepFun (fun a ↦ (f i a, f j a)) (f k) κ μ := by have h : IndepFun (fun a ↦ ((hf_meas i).mk (f i) a, (hf_meas j).mk (f j) a)) ((hf_meas k).mk (f k)) κ μ := by refine iIndepFun.indepFun_prodMk ?_ (fun i ↦ (hf_meas i).measurable_mk) _ _ _ hik hjk exact iIndepFun.congr' hf_Indep fun i ↦ Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk refine IndepFun.congr' h ?_ ?_ · filter_upwards [Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk, Measure.ae_ae_of_ae_comp (hf_meas j).ae_eq_mk] with a hi hj filter_upwards [hi, hj] with ω hωi hωj rw [← hωi, ← hωj] · exact Measure.ae_ae_of_ae_comp (hf_meas k).ae_eq_mk.symm open Finset in lemma iIndepFun.indepFun_prodMk_prodMk (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) (i j k l : ι) (hik : i ≠ k) (hil : i ≠ l) (hjk : j ≠ k) (hjl : j ≠ l) : IndepFun (fun a ↦ (f i a, f j a)) (fun a ↦ (f k a, f l a)) κ μ := by classical let g (i j : ι) (v : Π x : ({i, j} : Finset ι), β x) : β i × β j := ⟨v ⟨i, mem_insert_self _ _⟩, v ⟨j, mem_insert_of_mem <| mem_singleton_self _⟩⟩ have hg (i j : ι) : Measurable (g i j) := by fun_prop exact (hf_indep.indepFun_finset {i, j} {k, l} (by aesop) hf_meas).comp (hg i j) (hg k l) @[deprecated (since := "2025-03-05")] alias ProbabilityTheory.Kernel.iIndepFun.indepFun_prod_mk_prod_mk := iIndepFun.indepFun_prodMk_prodMk theorem iIndepFun.indepFun_prodMk_prodMk₀ (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (i j k l : ι) (hik : i ≠ k) (hil : i ≠ l) (hjk : j ≠ k) (hjl : j ≠ l) : IndepFun (fun a ↦ (f i a, f j a)) (fun a ↦ (f k a, f l a)) κ μ := by have h : IndepFun (fun a ↦ ((hf_meas i).mk (f i) a, (hf_meas j).mk (f j) a)) (fun a ↦ ((hf_meas k).mk (f k) a, (hf_meas l).mk (f l) a)) κ μ := by refine iIndepFun.indepFun_prodMk_prodMk ?_ (fun i ↦ (hf_meas i).measurable_mk) _ _ _ _ hik hil hjk hjl exact iIndepFun.congr' hf_indep fun i ↦ Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk refine IndepFun.congr' h ?_ ?_ · filter_upwards [Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk, Measure.ae_ae_of_ae_comp (hf_meas j).ae_eq_mk] with a hi hj filter_upwards [hi, hj] with ω hωi hωj rw [← hωi, ← hωj] · filter_upwards [Measure.ae_ae_of_ae_comp (hf_meas k).ae_eq_mk, Measure.ae_ae_of_ae_comp (hf_meas l).ae_eq_mk] with a hk hl filter_upwards [hk, hl] with ω hωk hωl rw [← hωk, ← hωl] end iIndepFun section Mul variable {β : Type*} {m : MeasurableSpace β} [Mul β] [MeasurableMul₂ β] {f : ι → Ω → β} @[to_additive] lemma iIndepFun.indepFun_mul_left (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) (i j k : ι) (hik : i ≠ k) (hjk : j ≠ k) : IndepFun (f i * f j) (f k) κ μ := by have : IndepFun (fun ω => (f i ω, f j ω)) (f k) κ μ := hf_indep.indepFun_prodMk hf_meas i j k hik hjk simpa using this.comp (measurable_fst.mul measurable_snd) measurable_id @[to_additive] lemma iIndepFun.indepFun_mul_left₀ (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (i j k : ι) (hik : i ≠ k) (hjk : j ≠ k) : IndepFun (f i * f j) (f k) κ μ := by have : IndepFun (fun ω => (f i ω, f j ω)) (f k) κ μ := hf_indep.indepFun_prodMk₀ hf_meas i j k hik hjk simpa using this.comp (measurable_fst.mul measurable_snd) measurable_id @[to_additive] lemma iIndepFun.indepFun_mul_right (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) (i j k : ι) (hij : i ≠ j) (hik : i ≠ k) : IndepFun (f i) (f j * f k) κ μ := (hf_indep.indepFun_mul_left hf_meas _ _ _ hij.symm hik.symm).symm @[to_additive] lemma iIndepFun.indepFun_mul_right₀ (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (i j k : ι) (hij : i ≠ j) (hik : i ≠ k) : IndepFun (f i) (f j * f k) κ μ := (hf_indep.indepFun_mul_left₀ hf_meas _ _ _ hij.symm hik.symm).symm @[to_additive] lemma iIndepFun.indepFun_mul_mul (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) (i j k l : ι) (hik : i ≠ k) (hil : i ≠ l) (hjk : j ≠ k) (hjl : j ≠ l) : IndepFun (f i * f j) (f k * f l) κ μ := (hf_indep.indepFun_prodMk_prodMk hf_meas i j k l hik hil hjk hjl).comp measurable_mul measurable_mul @[to_additive] lemma iIndepFun.indepFun_mul_mul₀ (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (i j k l : ι) (hik : i ≠ k) (hil : i ≠ l) (hjk : j ≠ k) (hjl : j ≠ l) : IndepFun (f i * f j) (f k * f l) κ μ := (hf_indep.indepFun_prodMk_prodMk₀ hf_meas i j k l hik hil hjk hjl).comp measurable_mul measurable_mul end Mul section Div variable {β : Type*} {m : MeasurableSpace β} [Div β] [MeasurableDiv₂ β] {f : ι → Ω → β} @[to_additive] lemma iIndepFun.indepFun_div_left (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) (i j k : ι) (hik : i ≠ k) (hjk : j ≠ k) : IndepFun (f i / f j) (f k) κ μ := by have : IndepFun (fun ω => (f i ω, f j ω)) (f k) κ μ := hf_indep.indepFun_prodMk hf_meas i j k hik hjk simpa using this.comp (measurable_fst.div measurable_snd) measurable_id @[to_additive] lemma iIndepFun.indepFun_div_left₀ (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (i j k : ι) (hik : i ≠ k) (hjk : j ≠ k) : IndepFun (f i / f j) (f k) κ μ := by have : IndepFun (fun ω => (f i ω, f j ω)) (f k) κ μ := hf_indep.indepFun_prodMk₀ hf_meas i j k hik hjk simpa using this.comp (measurable_fst.div measurable_snd) measurable_id @[to_additive] lemma iIndepFun.indepFun_div_right (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) (i j k : ι) (hij : i ≠ j) (hik : i ≠ k) : IndepFun (f i) (f j / f k) κ μ := (hf_indep.indepFun_div_left hf_meas _ _ _ hij.symm hik.symm).symm @[to_additive] lemma iIndepFun.indepFun_div_right₀ (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (i j k : ι) (hij : i ≠ j) (hik : i ≠ k) : IndepFun (f i) (f j / f k) κ μ := (hf_indep.indepFun_div_left₀ hf_meas _ _ _ hij.symm hik.symm).symm @[to_additive] lemma iIndepFun.indepFun_div_div (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) (i j k l : ι) (hik : i ≠ k) (hil : i ≠ l) (hjk : j ≠ k) (hjl : j ≠ l) : IndepFun (f i / f j) (f k / f l) κ μ := (hf_indep.indepFun_prodMk_prodMk hf_meas i j k l hik hil hjk hjl).comp measurable_div measurable_div @[to_additive] lemma iIndepFun.indepFun_div_div₀ (hf_indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (i j k l : ι) (hik : i ≠ k) (hil : i ≠ l) (hjk : j ≠ k) (hjl : j ≠ l) : IndepFun (f i / f j) (f k / f l) κ μ := (hf_indep.indepFun_prodMk_prodMk₀ hf_meas i j k l hik hil hjk hjl).comp measurable_div measurable_div end Div section CommMonoid variable {β : Type*} {m : MeasurableSpace β} [CommMonoid β] [MeasurableMul₂ β] {f : ι → Ω → β} @[to_additive] theorem iIndepFun.indepFun_finset_prod_of_notMem (hf_Indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) {s : Finset ι} {i : ι} (hi : i ∉ s) : IndepFun (∏ j ∈ s, f j) (f i) κ μ := by classical have h_right : f i = (fun p : ({i} : Finset ι) → β => p ⟨i, Finset.mem_singleton_self i⟩) ∘ fun a (j : ({i} : Finset ι)) => f j a := rfl have h_meas_right : Measurable fun p : ({i} : Finset ι) → β => p ⟨i, Finset.mem_singleton_self i⟩ := measurable_pi_apply _ have h_left : ∏ j ∈ s, f j = (fun p : s → β => ∏ j, p j) ∘ fun a (j : s) => f j a := by ext1 a simp only [Function.comp_apply] have : (∏ j : ↥s, f (↑j) a) = (∏ j : ↥s, f ↑j) a := by rw [Finset.prod_apply] rw [this, Finset.prod_coe_sort] have h_meas_left : Measurable fun p : s → β => ∏ j, p j := Finset.univ.measurable_fun_prod fun (j : ↥s) (_H : j ∈ Finset.univ) => measurable_pi_apply j rw [h_left, h_right] exact (hf_Indep.indepFun_finset s {i} (Finset.disjoint_singleton_left.mpr hi).symm hf_meas).comp h_meas_left h_meas_right @[deprecated (since := "2025-05-23")] alias iIndepFun.indepFun_finset_sum_of_not_mem := iIndepFun.indepFun_finset_sum_of_notMem @[to_additive existing, deprecated (since := "2025-05-23")] alias iIndepFun.indepFun_finset_prod_of_not_mem := iIndepFun.indepFun_finset_prod_of_notMem @[to_additive] theorem iIndepFun.indepFun_finset_prod_of_notMem₀ (hf_Indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) {s : Finset ι} {i : ι} (hi : i ∉ s) : IndepFun (∏ j ∈ s, f j) (f i) κ μ := by have h : IndepFun (∏ j ∈ s, (hf_meas j).mk (f j)) ((hf_meas i).mk (f i)) κ μ := by refine iIndepFun.indepFun_finset_prod_of_notMem ?_ (fun i ↦ (hf_meas i).measurable_mk) hi exact iIndepFun.congr' hf_Indep fun i ↦ Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk refine IndepFun.congr' h ?_ ?_ · have : ∀ᵐ a ∂μ, ∀ (i : s), f i =ᵐ[κ a] (hf_meas i).mk := by rw [ae_all_iff] exact fun i ↦ Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk filter_upwards [this] with a ha filter_upwards [ae_all_iff.2 ha] with ω hω simp only [Finset.prod_apply] exact Finset.prod_congr rfl fun i hi ↦ (hω ⟨i, hi⟩).symm · exact Measure.ae_ae_of_ae_comp (hf_meas i).ae_eq_mk.symm @[deprecated (since := "2025-05-23")] alias iIndepFun.indepFun_finset_sum_of_not_mem₀ := iIndepFun.indepFun_finset_sum_of_notMem₀ @[to_additive existing, deprecated (since := "2025-05-23")] alias iIndepFun.indepFun_finset_prod_of_not_mem₀ := iIndepFun.indepFun_finset_prod_of_notMem₀ @[to_additive] theorem iIndepFun.indepFun_prod_range_succ {f : ℕ → Ω → β} (hf_Indep : iIndepFun f κ μ) (hf_meas : ∀ i, Measurable (f i)) (n : ℕ) : IndepFun (∏ j ∈ Finset.range n, f j) (f n) κ μ := hf_Indep.indepFun_finset_prod_of_notMem hf_meas Finset.notMem_range_self @[to_additive] theorem iIndepFun.indepFun_prod_range_succ₀ {f : ℕ → Ω → β} (hf_Indep : iIndepFun f κ μ) (hf_meas : ∀ i, AEMeasurable (f i) (κ ∘ₘ μ)) (n : ℕ) : IndepFun (∏ j ∈ Finset.range n, f j) (f n) κ μ := hf_Indep.indepFun_finset_prod_of_notMem₀ hf_meas Finset.notMem_range_self end CommMonoid theorem iIndepSet.iIndepFun_indicator [Zero β] [One β] {m : MeasurableSpace β} {s : ι → Set Ω} (hs : iIndepSet s κ μ) : iIndepFun (fun n => (s n).indicator fun _ω => (1 : β)) κ μ := by classical rw [iIndepFun_iff_measure_inter_preimage_eq_mul] rintro S π _hπ simp_rw [Set.indicator_const_preimage_eq_union] apply hs _ fun i _hi ↦ ?_ have hsi : MeasurableSet[generateFrom {s i}] (s i) := measurableSet_generateFrom (Set.mem_singleton _) refine MeasurableSet.union (MeasurableSet.ite' (fun _ => hsi) fun _ => ?_) (MeasurableSet.ite' (fun _ => hsi.compl) fun _ => ?_) · exact @MeasurableSet.empty _ (generateFrom {s i}) · exact @MeasurableSet.empty _ (generateFrom {s i}) end IndepFun variable {ι Ω α β : Type*} {mΩ : MeasurableSpace Ω} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} {κ : Kernel α Ω} {μ : Measure α} {X : ι → Ω → α} {Y : ι → Ω → β} {f : _ → Set Ω} {t : ι → Set β} {s : Finset ι} /-- The probability of an intersection of preimages conditioning on another intersection factors into a product. -/ lemma iIndepFun.cond_iInter [Finite ι] (hY : ∀ i, Measurable (Y i)) (hindep : iIndepFun (fun i ω ↦ (X i ω, Y i ω)) κ μ) (hf : ∀ i ∈ s, MeasurableSet[mα.comap (X i)] (f i)) (hy : ∀ᵐ a ∂μ, ∀ i ∉ s, κ a (Y i ⁻¹' t i) ≠ 0) (ht : ∀ i, MeasurableSet (t i)) : ∀ᵐ a ∂μ, (κ a)[⋂ i ∈ s, f i | ⋂ i, Y i ⁻¹' t i] = ∏ i ∈ s, (κ a)[f i | Y i in t i] := by classical cases nonempty_fintype ι let g (i' : ι) := if i' ∈ s then Y i' ⁻¹' t i' ∩ f i' else Y i' ⁻¹' t i' have hYt i : MeasurableSet[(mα.prod mβ).comap fun ω ↦ (X i ω, Y i ω)] (Y i ⁻¹' t i) := ⟨.univ ×ˢ t i, .prod .univ (ht _), by ext; simp⟩ have hg i : MeasurableSet[(mα.prod mβ).comap fun ω ↦ (X i ω, Y i ω)] (g i) := by by_cases hi : i ∈ s <;> simp only [hi, ↓reduceIte, g] · obtain ⟨A, hA, hA'⟩ := hf i hi exact (hYt _).inter ⟨A ×ˢ .univ, hA.prod .univ, by ext; simp [← hA']⟩ · exact hYt _ filter_upwards [hy, hindep.ae_isProbabilityMeasure, hindep.meas_iInter hYt, hindep.meas_iInter hg] with a hy _ hYt hg calc _ = (κ a (⋂ i, Y i ⁻¹' t i))⁻¹ * κ a ((⋂ i, Y i ⁻¹' t i) ∩ ⋂ i ∈ s, f i) := by rw [cond_apply]; exact .iInter fun i ↦ hY i (ht i) _ = (κ a (⋂ i, Y i ⁻¹' t i))⁻¹ * κ a (⋂ i, g i) := by congr 2 calc _ = (⋂ i, Y i ⁻¹' t i) ∩ ⋂ i, if i ∈ s then f i else .univ := by congr 1 simp only [Set.iInter_ite, Set.iInter_univ, Set.inter_univ] _ = ⋂ i, Y i ⁻¹' t i ∩ (if i ∈ s then f i else .univ) := by rw [Set.iInter_inter_distrib] _ = _ := Set.iInter_congr fun i ↦ by by_cases hi : i ∈ s <;> simp [hi, g] _ = (∏ i, κ a (Y i ⁻¹' t i))⁻¹ * κ a (⋂ i, g i) := by rw [hYt] _ = (∏ i, κ a (Y i ⁻¹' t i))⁻¹ * ∏ i, κ a (g i) := by rw [hg] _ = ∏ i, (κ a (Y i ⁻¹' t i))⁻¹ * κ a (g i) := by rw [Finset.prod_mul_distrib, ENNReal.prod_inv_distrib] exact fun _ _ i _ _ ↦ .inr <| measure_ne_top _ _ _ = ∏ i, if i ∈ s then (κ a)[f i | Y i ⁻¹' t i] else 1 := by refine Finset.prod_congr rfl fun i _ ↦ ?_ by_cases hi : i ∈ s · simp only [hi, ↓reduceIte, g, cond_apply (hY i (ht i))] · simp only [hi, ↓reduceIte, g, ENNReal.inv_mul_cancel (hy i hi) (measure_ne_top _ _)] _ = _ := by simp -- TODO: We can't state `Kernel.iIndepFun.cond` (the `Kernel` analogue of -- `ProbabilityTheory.iIndepFun.cond`) because we don't have a version of `ProbabilityTheory.cond` -- for kernels end ProbabilityTheory.Kernel
Submonoid.lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import Mathlib.Algebra.Group.Submonoid.Defs import Mathlib.Algebra.Order.Monoid.Basic import Mathlib.Order.Interval.Set.Defs /-! # Ordered instances on submonoids -/ assert_not_exists MonoidWithZero namespace SubmonoidClass variable {M S : Type*} [SetLike S M] -- Prefer subclasses of `Monoid` over subclasses of `SubmonoidClass`. /-- A submonoid of an ordered monoid is an ordered monoid. -/ @[to_additive /-- An `AddSubmonoid` of an ordered additive monoid is an ordered additive monoid. -/] instance (priority := 75) toIsOrderedMonoid [CommMonoid M] [PartialOrder M] [IsOrderedMonoid M] [SubmonoidClass S M] (s : S) : IsOrderedMonoid s := Subtype.coe_injective.isOrderedMonoid Subtype.val rfl (fun _ _ => rfl) fun _ _ => rfl -- Prefer subclasses of `Monoid` over subclasses of `SubmonoidClass`. /-- A submonoid of an ordered cancellative monoid is an ordered cancellative monoid. -/ @[to_additive AddSubmonoidClass.toIsOrderedCancelAddMonoid /-- An `AddSubmonoid` of an ordered cancellative additive monoid is an ordered cancellative additive monoid. -/] instance (priority := 75) toIsOrderedCancelMonoid [CommMonoid M] [PartialOrder M] [IsOrderedCancelMonoid M] [SubmonoidClass S M] (s : S) : IsOrderedCancelMonoid s := Subtype.coe_injective.isOrderedCancelMonoid Subtype.val rfl (fun _ _ => rfl) fun _ _ => rfl end SubmonoidClass namespace Submonoid variable {M : Type*} /-- A submonoid of an ordered monoid is an ordered monoid. -/ @[to_additive /-- An `AddSubmonoid` of an ordered additive monoid is an ordered additive monoid. -/] instance toIsOrderedMonoid [CommMonoid M] [PartialOrder M] [IsOrderedMonoid M] (S : Submonoid M) : IsOrderedMonoid S := Subtype.coe_injective.isOrderedMonoid Subtype.val rfl (fun _ _ => rfl) fun _ _ => rfl /-- A submonoid of an ordered cancellative monoid is an ordered cancellative monoid. -/ @[to_additive AddSubmonoid.toIsOrderedCancelAddMonoid /-- An `AddSubmonoid` of an ordered cancellative additive monoid is an ordered cancellative additive monoid. -/] instance toIsOrderedCancelMonoid [CommMonoid M] [PartialOrder M] [IsOrderedCancelMonoid M] (S : Submonoid M) : IsOrderedCancelMonoid S := Subtype.coe_injective.isOrderedCancelMonoid Subtype.val rfl (fun _ _ => rfl) fun _ _ => rfl section Preorder variable (M) variable [Monoid M] [Preorder M] [MulLeftMono M] {a : M} /-- The submonoid of elements that are at least `1`. -/ @[to_additive (attr := simps) /-- The submonoid of nonnegative elements. -/] def oneLE : Submonoid M where carrier := Set.Ici 1 mul_mem' := one_le_mul one_mem' := le_rfl variable {M} @[to_additive (attr := simp)] lemma mem_oneLE : a ∈ oneLE M ↔ 1 ≤ a := Iff.rfl end Preorder end Submonoid
Module.lean
/- Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser -/ import Mathlib.Algebra.Algebra.RestrictScalars import Mathlib.Algebra.CharP.Invertible import Mathlib.Data.Complex.Basic import Mathlib.LinearAlgebra.Matrix.ToLin import Mathlib.Data.Real.Star /-! # Complex number as a vector space over `ℝ` This file contains the following instances: * Any `•`-structure (`SMul`, `MulAction`, `DistribMulAction`, `Module`, `Algebra`) on `ℝ` imbues a corresponding structure on `ℂ`. This includes the statement that `ℂ` is an `ℝ` algebra. * any complex vector space is a real vector space; * any finite dimensional complex vector space is a finite dimensional real vector space; * the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex vector space. It also defines bundled versions of four standard maps (respectively, the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate): * `Complex.reLm` (`ℝ`-linear map); * `Complex.imLm` (`ℝ`-linear map); * `Complex.ofRealAm` (`ℝ`-algebra (homo)morphism); * `Complex.conjAe` (`ℝ`-algebra equivalence). It also provides a universal property of the complex numbers `Complex.lift`, which constructs a `ℂ →ₐ[ℝ] A` into any `ℝ`-algebra `A` given a square root of `-1`. In addition, this file provides a decomposition into `realPart` and `imaginaryPart` for any element of a `StarModule` over `ℂ`. ## Notation * `ℜ` and `ℑ` for the `realPart` and `imaginaryPart`, respectively, in the locale `ComplexStarModule`. -/ assert_not_exists NNReal namespace Complex open ComplexConjugate open scoped SMul variable {R : Type*} {S : Type*} attribute [local ext] Complex.ext /- The priority of the following instances has been manually lowered, as when they don't apply they lead Lean to a very costly path, and most often they don't apply (most actions on `ℂ` don't come from actions on `ℝ`). See https://github.com/leanprover-community/mathlib4/pull/11980 -/ -- priority manually adjusted in https://github.com/leanprover-community/mathlib4/pull/11980 instance (priority := 90) [SMul R ℝ] [SMul S ℝ] [SMulCommClass R S ℝ] : SMulCommClass R S ℂ where smul_comm r s x := by ext <;> simp [smul_re, smul_im, smul_comm] -- priority manually adjusted in https://github.com/leanprover-community/mathlib4/pull/11980 instance (priority := 90) [SMul R S] [SMul R ℝ] [SMul S ℝ] [IsScalarTower R S ℝ] : IsScalarTower R S ℂ where smul_assoc r s x := by ext <;> simp [smul_re, smul_im, smul_assoc] -- priority manually adjusted in https://github.com/leanprover-community/mathlib4/pull/11980 instance (priority := 90) [SMul R ℝ] [SMul Rᵐᵒᵖ ℝ] [IsCentralScalar R ℝ] : IsCentralScalar R ℂ where op_smul_eq_smul r x := by ext <;> simp [smul_re, smul_im, op_smul_eq_smul] -- priority manually adjusted in https://github.com/leanprover-community/mathlib4/pull/11980 instance (priority := 90) mulAction [Monoid R] [MulAction R ℝ] : MulAction R ℂ where one_smul x := by ext <;> simp [smul_re, smul_im, one_smul] mul_smul r s x := by ext <;> simp [smul_re, smul_im, mul_smul] -- priority manually adjusted in https://github.com/leanprover-community/mathlib4/pull/11980 instance (priority := 90) distribSMul [DistribSMul R ℝ] : DistribSMul R ℂ where smul_add r x y := by ext <;> simp [smul_re, smul_im, smul_add] smul_zero r := by ext <;> simp [smul_re, smul_im, smul_zero] -- priority manually adjusted in https://github.com/leanprover-community/mathlib4/pull/11980 instance (priority := 90) [Semiring R] [DistribMulAction R ℝ] : DistribMulAction R ℂ := { Complex.distribSMul, Complex.mulAction with } -- priority manually adjusted in https://github.com/leanprover-community/mathlib4/pull/11980 instance (priority := 100) instModule [Semiring R] [Module R ℝ] : Module R ℂ where add_smul r s x := by ext <;> simp [smul_re, smul_im, add_smul] zero_smul r := by ext <;> simp [smul_re, smul_im, zero_smul] -- priority manually adjusted in https://github.com/leanprover-community/mathlib4/pull/11980 instance (priority := 95) instAlgebraOfReal [CommSemiring R] [Algebra R ℝ] : Algebra R ℂ where algebraMap := Complex.ofRealHom.comp (algebraMap R ℝ) smul := (· • ·) smul_def' := fun r x => by ext <;> simp [smul_re, smul_im, Algebra.smul_def] commutes' := fun r ⟨xr, xi⟩ => by ext <;> simp [Algebra.commutes] instance : StarModule ℝ ℂ := ⟨fun r x => by simp only [star_def, star_trivial, real_smul, map_mul, conj_ofReal]⟩ @[simp] theorem coe_algebraMap : (algebraMap ℝ ℂ : ℝ → ℂ) = ((↑) : ℝ → ℂ) := rfl section variable {A : Type*} [Semiring A] [Algebra ℝ A] /-- We need this lemma since `Complex.coe_algebraMap` diverts the simp-normal form away from `AlgHom.commutes`. -/ @[simp] theorem _root_.AlgHom.map_coe_real_complex (f : ℂ →ₐ[ℝ] A) (x : ℝ) : f x = algebraMap ℝ A x := f.commutes x /-- Two `ℝ`-algebra homomorphisms from `ℂ` are equal if they agree on `Complex.I`. -/ @[ext] theorem algHom_ext ⦃f g : ℂ →ₐ[ℝ] A⦄ (h : f I = g I) : f = g := by ext ⟨x, y⟩ simp only [mk_eq_add_mul_I, map_add, AlgHom.map_coe_real_complex, map_mul, h] end open Module Submodule /-- `ℂ` has a basis over `ℝ` given by `1` and `I`. -/ noncomputable def basisOneI : Basis (Fin 2) ℝ ℂ := .ofEquivFun { toFun := fun z => ![z.re, z.im] invFun := fun c => c 0 + c 1 • I left_inv := fun z => by simp right_inv := fun c => by ext i fin_cases i <;> simp map_add' := fun z z' => by simp map_smul' := fun c z => by simp } @[simp] theorem coe_basisOneI_repr (z : ℂ) : ⇑(basisOneI.repr z) = ![z.re, z.im] := rfl @[simp] theorem coe_basisOneI : ⇑basisOneI = ![1, I] := funext fun i => Basis.apply_eq_iff.mpr <| Finsupp.ext fun j => by fin_cases i <;> fin_cases j <;> simp end Complex /- Register as an instance (with low priority) the fact that a complex vector space is also a real vector space. -/ instance (priority := 900) Module.complexToReal (E : Type*) [AddCommGroup E] [Module ℂ E] : Module ℝ E := RestrictScalars.module ℝ ℂ E /- Register as an instance (with low priority) the fact that a complex algebra is also a real algebra. -/ instance (priority := 900) Algebra.complexToReal {A : Type*} [Semiring A] [Algebra ℂ A] : Algebra ℝ A := RestrictScalars.algebra ℝ ℂ A -- try to make sure we're not introducing diamonds but we will need -- `reducible_and_instances` which currently fails https://github.com/leanprover-community/mathlib4/issues/10906 example : Prod.algebra ℝ ℂ ℂ = (Prod.algebra ℂ ℂ ℂ).complexToReal := rfl -- try to make sure we're not introducing diamonds but we will need -- `reducible_and_instances` which currently fails https://github.com/leanprover-community/mathlib4/issues/10906 example {ι : Type*} [Fintype ι] : Pi.algebra (R := ℝ) ι (fun _ ↦ ℂ) = (Pi.algebra (R := ℂ) ι (fun _ ↦ ℂ)).complexToReal := rfl example {A : Type*} [Ring A] [inst : Algebra ℂ A] : (inst.complexToReal).toModule = (inst.toModule).complexToReal := by with_reducible_and_instances rfl @[simp, norm_cast] theorem Complex.coe_smul {E : Type*} [AddCommGroup E] [Module ℂ E] (x : ℝ) (y : E) : (x : ℂ) • y = x • y := rfl /-- The scalar action of `ℝ` on a `ℂ`-module `E` induced by `Module.complexToReal` commutes with another scalar action of `M` on `E` whenever the action of `ℂ` commutes with the action of `M`. -/ instance (priority := 900) SMulCommClass.complexToReal {M E : Type*} [AddCommGroup E] [Module ℂ E] [SMul M E] [SMulCommClass ℂ M E] : SMulCommClass ℝ M E where smul_comm r _ _ := smul_comm (r : ℂ) _ _ /-- The scalar action of `ℝ` on a `ℂ`-module `E` induced by `Module.complexToReal` associates with another scalar action of `M` on `E` whenever the action of `ℂ` associates with the action of `M`. -/ instance IsScalarTower.complexToReal {M E : Type*} [AddCommGroup M] [Module ℂ M] [AddCommGroup E] [Module ℂ E] [SMul M E] [IsScalarTower ℂ M E] : IsScalarTower ℝ M E where smul_assoc r _ _ := smul_assoc (r : ℂ) _ _ -- check that the following instance is implied by the one above. example (E : Type*) [AddCommGroup E] [Module ℂ E] : IsScalarTower ℝ ℂ E := inferInstance instance (priority := 900) StarModule.complexToReal {E : Type*} [AddCommGroup E] [Star E] [Module ℂ E] [StarModule ℂ E] : StarModule ℝ E := ⟨fun r a => by rw [← smul_one_smul ℂ r a, star_smul, star_smul, star_one, smul_one_smul]⟩ namespace Complex open ComplexConjugate /-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/ def reLm : ℂ →ₗ[ℝ] ℝ where toFun x := x.re map_add' := add_re map_smul' := by simp @[simp] theorem reLm_coe : ⇑reLm = re := rfl /-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/ def imLm : ℂ →ₗ[ℝ] ℝ where toFun x := x.im map_add' := add_im map_smul' := by simp @[simp] theorem imLm_coe : ⇑imLm = im := rfl /-- `ℝ`-algebra morphism version of the canonical embedding of `ℝ` in `ℂ`. -/ def ofRealAm : ℝ →ₐ[ℝ] ℂ := Algebra.ofId ℝ ℂ @[simp] theorem ofRealAm_coe : ⇑ofRealAm = ((↑) : ℝ → ℂ) := rfl /-- `ℝ`-algebra isomorphism version of the complex conjugation function from `ℂ` to `ℂ` -/ def conjAe : ℂ ≃ₐ[ℝ] ℂ := { conj with invFun := conj left_inv := star_star right_inv := star_star commutes' := conj_ofReal } @[simp] theorem conjAe_coe : ⇑conjAe = conj := rfl /-- The matrix representation of `conjAe`. -/ @[simp] theorem toMatrix_conjAe : LinearMap.toMatrix basisOneI basisOneI conjAe.toLinearMap = !![1, 0; 0, -1] := by ext i j fin_cases i <;> fin_cases j <;> simp [LinearMap.toMatrix_apply] /-- The identity and the complex conjugation are the only two `ℝ`-algebra homomorphisms of `ℂ`. -/ theorem real_algHom_eq_id_or_conj (f : ℂ →ₐ[ℝ] ℂ) : f = AlgHom.id ℝ ℂ ∨ f = conjAe := by refine (eq_or_eq_neg_of_sq_eq_sq (f I) I <| by rw [← map_pow, I_sq, map_neg, map_one]).imp ?_ ?_ <;> refine fun h => algHom_ext ?_ exacts [h, conj_I.symm ▸ h] /-- The natural `LinearEquiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps! +simpRhs apply symm_apply_re symm_apply_im] def equivRealProdLm : ℂ ≃ₗ[ℝ] ℝ × ℝ := { equivRealProdAddHom with map_smul' := fun r c => by simp } theorem equivRealProdLm_symm_apply (p : ℝ × ℝ) : Complex.equivRealProdLm.symm p = p.1 + p.2 * Complex.I := Complex.equivRealProd_symm_apply p section lift variable {A : Type*} [Ring A] [Algebra ℝ A] /-- There is an alg_hom from `ℂ` to any `ℝ`-algebra with an element that squares to `-1`. See `Complex.lift` for this as an equiv. -/ def liftAux (I' : A) (hf : I' * I' = -1) : ℂ →ₐ[ℝ] A := AlgHom.ofLinearMap ((Algebra.linearMap ℝ A).comp reLm + (LinearMap.toSpanSingleton _ _ I').comp imLm) (show algebraMap ℝ A 1 + (0 : ℝ) • I' = 1 by rw [RingHom.map_one, zero_smul, add_zero]) fun ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ => show algebraMap ℝ A (x₁ * x₂ - y₁ * y₂) + (x₁ * y₂ + y₁ * x₂) • I' = (algebraMap ℝ A x₁ + y₁ • I') * (algebraMap ℝ A x₂ + y₂ • I') by rw [add_mul, mul_add, mul_add, add_comm _ (y₁ • I' * y₂ • I'), add_add_add_comm] congr 1 -- equate "real" and "imaginary" parts · rw [smul_mul_smul_comm, hf, smul_neg, ← Algebra.algebraMap_eq_smul_one, ← sub_eq_add_neg, ← RingHom.map_mul, ← RingHom.map_sub] · rw [Algebra.smul_def, Algebra.smul_def, Algebra.smul_def, ← Algebra.right_comm _ x₂, ← mul_assoc, ← add_mul, ← RingHom.map_mul, ← RingHom.map_mul, ← RingHom.map_add] @[simp] theorem liftAux_apply (I' : A) (hI') (z : ℂ) : liftAux I' hI' z = algebraMap ℝ A z.re + z.im • I' := rfl theorem liftAux_apply_I (I' : A) (hI') : liftAux I' hI' I = I' := by simp @[simp] theorem adjoin_I : Algebra.adjoin ℝ {I} = ⊤ := by refine top_unique fun x hx => ?_; clear hx rw [← x.re_add_im, ← smul_eq_mul, ← Complex.coe_algebraMap] exact add_mem (algebraMap_mem _ _) (Subalgebra.smul_mem _ (Algebra.subset_adjoin <| by simp) _) @[simp] theorem range_liftAux (I' : A) (hI') : (liftAux I' hI').range = Algebra.adjoin ℝ {I'} := by simp_rw [← Algebra.map_top, ← adjoin_I, AlgHom.map_adjoin, Set.image_singleton, liftAux_apply_I] /-- A universal property of the complex numbers, providing a unique `ℂ →ₐ[ℝ] A` for every element of `A` which squares to `-1`. This can be used to embed the complex numbers in the `Quaternion`s. This isomorphism is named to match the very similar `Zsqrtd.lift`. -/ @[simps +simpRhs] def lift : { I' : A // I' * I' = -1 } ≃ (ℂ →ₐ[ℝ] A) where toFun I' := liftAux I' I'.prop invFun F := ⟨F I, by rw [← map_mul, I_mul_I, map_neg, map_one]⟩ left_inv I' := Subtype.ext <| liftAux_apply_I (I' : A) I'.prop right_inv _ := algHom_ext <| liftAux_apply_I _ _ -- When applied to `Complex.I` itself, `lift` is the identity. @[simp] theorem liftAux_I : liftAux I I_mul_I = AlgHom.id ℝ ℂ := algHom_ext <| liftAux_apply_I _ _ -- When applied to `-Complex.I`, `lift` is conjugation, `conj`. @[simp] theorem liftAux_neg_I : liftAux (-I) ((neg_mul_neg _ _).trans I_mul_I) = conjAe := algHom_ext <| (liftAux_apply_I _ _).trans conj_I.symm end lift end Complex section RealImaginaryPart open Complex variable {A : Type*} [AddCommGroup A] [Module ℂ A] [StarAddMonoid A] [StarModule ℂ A] /-- Create a `selfAdjoint` element from a `skewAdjoint` element by multiplying by the scalar `-Complex.I`. -/ @[simps] def skewAdjoint.negISMul : skewAdjoint A →ₗ[ℝ] selfAdjoint A where toFun a := ⟨-I • ↑a, by simp only [neg_smul, neg_mem_iff, selfAdjoint.mem_iff, star_smul, star_def, conj_I, star_val_eq, smul_neg, neg_neg]⟩ map_add' a b := by ext simp only [AddSubgroup.coe_add, smul_add, AddMemClass.mk_add_mk] map_smul' a b := by ext simp only [neg_smul, skewAdjoint.val_smul, RingHom.id_apply, selfAdjoint.val_smul, smul_neg, neg_inj] rw [smul_comm] theorem skewAdjoint.I_smul_neg_I (a : skewAdjoint A) : I • (skewAdjoint.negISMul a : A) = a := by simp only [smul_smul, skewAdjoint.negISMul_apply_coe, neg_smul, smul_neg, I_mul_I, one_smul, neg_neg] /-- The real part `ℜ a` of an element `a` of a star module over `ℂ`, as a linear map. This is just `selfAdjointPart ℝ`, but we provide it as a separate definition in order to link it with lemmas concerning the `imaginaryPart`, which doesn't exist in star modules over other rings. -/ noncomputable def realPart : A →ₗ[ℝ] selfAdjoint A := selfAdjointPart ℝ /-- The imaginary part `ℑ a` of an element `a` of a star module over `ℂ`, as a linear map into the self adjoint elements. In a general star module, we have a decomposition into the `selfAdjoint` and `skewAdjoint` parts, but in a star module over `ℂ` we have `realPart_add_I_smul_imaginaryPart`, which allows us to decompose into a linear combination of `selfAdjoint`s. -/ noncomputable def imaginaryPart : A →ₗ[ℝ] selfAdjoint A := skewAdjoint.negISMul.comp (skewAdjointPart ℝ) @[inherit_doc] scoped[ComplexStarModule] notation "ℜ" => realPart @[inherit_doc] scoped[ComplexStarModule] notation "ℑ" => imaginaryPart open ComplexStarModule theorem realPart_apply_coe (a : A) : (ℜ a : A) = (2 : ℝ)⁻¹ • (a + star a) := by unfold realPart simp only [selfAdjointPart_apply_coe, invOf_eq_inv] theorem imaginaryPart_apply_coe (a : A) : (ℑ a : A) = -I • (2 : ℝ)⁻¹ • (a - star a) := by unfold imaginaryPart simp only [LinearMap.coe_comp, Function.comp_apply, skewAdjoint.negISMul_apply_coe, skewAdjointPart_apply_coe, invOf_eq_inv, neg_smul] /-- The standard decomposition of `ℜ a + Complex.I • ℑ a = a` of an element of a star module over `ℂ` into a linear combination of self adjoint elements. -/ theorem realPart_add_I_smul_imaginaryPart (a : A) : (ℜ a : A) + I • (ℑ a : A) = a := by simpa only [smul_smul, realPart_apply_coe, imaginaryPart_apply_coe, neg_smul, I_mul_I, one_smul, neg_sub, add_add_sub_cancel, smul_sub, smul_add, neg_sub_neg, invOf_eq_inv] using invOf_two_smul_add_invOf_two_smul ℝ a @[simp] theorem realPart_I_smul (a : A) : ℜ (I • a) = -ℑ a := by ext simp [realPart_apply_coe, imaginaryPart_apply_coe, smul_comm I, sub_eq_add_neg, add_comm] @[simp] theorem imaginaryPart_I_smul (a : A) : ℑ (I • a) = ℜ a := by ext simp [realPart_apply_coe, imaginaryPart_apply_coe, smul_comm I (2⁻¹ : ℝ), smul_smul I] theorem realPart_smul (z : ℂ) (a : A) : ℜ (z • a) = z.re • ℜ a - z.im • ℑ a := by have := by congrm (ℜ ($((re_add_im z).symm) • a)) simpa [-re_add_im, add_smul, ← smul_smul, sub_eq_add_neg] theorem imaginaryPart_smul (z : ℂ) (a : A) : ℑ (z • a) = z.re • ℑ a + z.im • ℜ a := by have := by congrm (ℑ ($((re_add_im z).symm) • a)) simpa [-re_add_im, add_smul, ← smul_smul] lemma skewAdjointPart_eq_I_smul_imaginaryPart (x : A) : (skewAdjointPart ℝ x : A) = I • (imaginaryPart x : A) := by simp [imaginaryPart_apply_coe, smul_smul] lemma imaginaryPart_eq_neg_I_smul_skewAdjointPart (x : A) : (imaginaryPart x : A) = -I • (skewAdjointPart ℝ x : A) := rfl lemma IsSelfAdjoint.coe_realPart {x : A} (hx : IsSelfAdjoint x) : (ℜ x : A) = x := hx.coe_selfAdjointPart_apply ℝ nonrec lemma IsSelfAdjoint.imaginaryPart {x : A} (hx : IsSelfAdjoint x) : ℑ x = 0 := by rw [imaginaryPart, LinearMap.comp_apply, hx.skewAdjointPart_apply _, map_zero] lemma realPart_comp_subtype_selfAdjoint : realPart.comp (selfAdjoint.submodule ℝ A).subtype = LinearMap.id := selfAdjointPart_comp_subtype_selfAdjoint ℝ lemma imaginaryPart_comp_subtype_selfAdjoint : imaginaryPart.comp (selfAdjoint.submodule ℝ A).subtype = 0 := by rw [imaginaryPart, LinearMap.comp_assoc, skewAdjointPart_comp_subtype_selfAdjoint, LinearMap.comp_zero] @[simp] lemma imaginaryPart_realPart {x : A} : ℑ (ℜ x : A) = 0 := (ℜ x).property.imaginaryPart @[simp] lemma imaginaryPart_imaginaryPart {x : A} : ℑ (ℑ x : A) = 0 := (ℑ x).property.imaginaryPart @[simp] lemma realPart_idem {x : A} : ℜ (ℜ x : A) = ℜ x := Subtype.ext <| (ℜ x).property.coe_realPart @[simp] lemma realPart_imaginaryPart {x : A} : ℜ (ℑ x : A) = ℑ x := Subtype.ext <| (ℑ x).property.coe_realPart lemma realPart_surjective : Function.Surjective (realPart (A := A)) := fun x ↦ ⟨(x : A), Subtype.ext x.property.coe_realPart⟩ lemma imaginaryPart_surjective : Function.Surjective (imaginaryPart (A := A)) := fun x ↦ ⟨I • (x : A), Subtype.ext <| by simp only [imaginaryPart_I_smul, x.property.coe_realPart]⟩ open Submodule lemma span_selfAdjoint : span ℂ (selfAdjoint A : Set A) = ⊤ := by refine eq_top_iff'.mpr fun x ↦ ?_ rw [← realPart_add_I_smul_imaginaryPart x] exact add_mem (subset_span (ℜ x).property) <| SMulMemClass.smul_mem _ <| subset_span (ℑ x).property /-- The natural `ℝ`-linear equivalence between `selfAdjoint ℂ` and `ℝ`. -/ @[simps apply symm_apply] def Complex.selfAdjointEquiv : selfAdjoint ℂ ≃ₗ[ℝ] ℝ where toFun := fun z ↦ (z : ℂ).re invFun := fun x ↦ ⟨x, conj_ofReal x⟩ left_inv := fun z ↦ Subtype.ext <| conj_eq_iff_re.mp z.property.star_eq map_add' := by simp map_smul' := by simp lemma Complex.coe_selfAdjointEquiv (z : selfAdjoint ℂ) : (selfAdjointEquiv z : ℂ) = z := by simpa [selfAdjointEquiv_symm_apply] using (congr_arg Subtype.val <| Complex.selfAdjointEquiv.left_inv z) @[simp] lemma realPart_ofReal (r : ℝ) : (ℜ (r : ℂ) : ℂ) = r := by rw [realPart_apply_coe, star_def, conj_ofReal, ← two_smul ℝ (r : ℂ)] simp @[simp] lemma imaginaryPart_ofReal (r : ℝ) : ℑ (r : ℂ) = 0 := by ext1; simp [imaginaryPart_apply_coe, conj_ofReal] lemma Complex.coe_realPart (z : ℂ) : (ℜ z : ℂ) = z.re := calc (ℜ z : ℂ) = (↑(ℜ (↑z.re + ↑z.im * I))) := by congrm (ℜ $((re_add_im z).symm)) _ = z.re := by rw [map_add, AddSubmonoid.coe_add, mul_comm, ← smul_eq_mul, realPart_I_smul] simp lemma star_mul_self_add_self_mul_star {A : Type*} [NonUnitalNonAssocRing A] [StarRing A] [Module ℂ A] [IsScalarTower ℂ A A] [SMulCommClass ℂ A A] [StarModule ℂ A] (a : A) : star a * a + a * star a = 2 • (ℜ a * ℜ a + ℑ a * ℑ a) := have a_eq := (realPart_add_I_smul_imaginaryPart a).symm calc star a * a + a * star a = _ := congr((star $(a_eq)) * $(a_eq) + $(a_eq) * (star $(a_eq))) _ = 2 • (ℜ a * ℜ a + ℑ a * ℑ a) := by simp [mul_add, add_mul, smul_smul, two_smul, mul_smul_comm, smul_mul_assoc] abel end RealImaginaryPart
UInt.lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Init import Mathlib.Algebra.Ring.InjSurj import Mathlib.Data.ZMod.Defs import Mathlib.Data.BitVec /-! # Adds Mathlib specific instances to the `UIntX` data types. The `CommRing` instances (and the `NatCast` and `IntCast` instances from which they is built) are scoped in the `UIntX.CommRing` namespace, rather than available globally. As a result, the `ring` tactic will not work on `UIntX` types without `open scoped UIntX.Ring`. This is because the presence of these casting operations contradicts assumptions made by the expression tree elaborator, namely that coercions do not form a cycle. The UInt version also interferes more with software-verification use-cases, which is reason to be more cautious here. -/ -- these theorems are fragile, so do them first set_option hygiene false in run_cmd for typeName' in [`UInt8, `UInt16, `UInt32, `UInt64, `USize] do let typeName := Lean.mkIdent typeName' Lean.Elab.Command.elabCommand (← `( namespace $typeName open $typeName (toBitVec_mul) in protected theorem toBitVec_nsmul (n : ℕ) (a : $typeName) : (n • a).toBitVec = n • a.toBitVec := by change (n * a).toBitVec = n • a.toBitVec rw [Lean.Grind.Semiring.nsmul_eq_natCast_mul, toBitVec_mul, nsmul_eq_mul, BitVec.natCast_eq_ofNat] rfl attribute [local instance] natCast intCast @[simp, int_toBitVec] protected theorem toBitVec_natCast (n : ℕ) : (n : $typeName).toBitVec = n := rfl open $typeName (toBitVec_neg) in @[simp, int_toBitVec] protected theorem toBitVec_intCast (z : ℤ) : (z : $typeName).toBitVec = z := by obtain ⟨z, rfl | rfl⟩ := z.eq_nat_or_neg · erw [intCast_ofNat]; rfl · rw [intCast_neg, toBitVec_neg] erw [intCast_ofNat] simp open $typeName (toBitVec_mul toBitVec_intCast) in @[simp, int_toBitVec] protected theorem toBitVec_zsmul (z : ℤ) (a : $typeName) : (z • a).toBitVec = z • a.toBitVec := by change (z * a).toBitVec = BitVec.ofInt _ z * a.toBitVec rw [toBitVec_mul] congr 1 rw [toBitVec_intCast] rfl end $typeName )) -- Note that these construct no new data, so cannot form diamonds with core. set_option hygiene false in run_cmd for typeName' in [`UInt8, `UInt16, `UInt32, `UInt64, `USize] do let typeName := Lean.mkIdent typeName' Lean.Elab.Command.elabCommand (← `( namespace $typeName open $typeName (eq_of_toFin_eq) in lemma toFin_injective : Function.Injective toFin := @eq_of_toFin_eq open $typeName (eq_of_toBitVec_eq) in lemma toBitVec_injective : Function.Injective toBitVec := @eq_of_toBitVec_eq open $typeName (toBitVec_one toBitVec_mul toBitVec_pow) in instance instCommMonoid : CommMonoid $typeName := Function.Injective.commMonoid toBitVec toBitVec_injective toBitVec_one (fun _ _ => toBitVec_mul) (fun _ _ => toBitVec_pow _ _) open $typeName ( toBitVec_zero toBitVec_add toBitVec_mul toBitVec_neg toBitVec_sub toBitVec_nsmul toBitVec_zsmul) in instance instNonUnitalCommRing : NonUnitalCommRing $typeName := Function.Injective.nonUnitalCommRing toBitVec toBitVec_injective toBitVec_zero (fun _ _ => toBitVec_add) (fun _ _ => toBitVec_mul) (fun _ => toBitVec_neg) (fun _ _ => toBitVec_sub) (fun _ _ => toBitVec_nsmul _ _) (fun _ _ => toBitVec_zsmul _ _) attribute [local instance] intCast natCast open $typeName ( toBitVec_zero toBitVec_one toBitVec_add toBitVec_mul toBitVec_neg toBitVec_sub toBitVec_nsmul toBitVec_zsmul toBitVec_pow toBitVec_natCast toBitVec_intCast) in local instance instCommRing : CommRing $typeName := Function.Injective.commRing toBitVec toBitVec_injective toBitVec_zero toBitVec_one (fun _ _ => toBitVec_add) (fun _ _ => toBitVec_mul) (fun _ => toBitVec_neg) (fun _ _ => toBitVec_sub) (fun _ _ => toBitVec_nsmul _ _) (fun _ _ => toBitVec_zsmul _ _) (fun _ _ => toBitVec_pow _ _) toBitVec_natCast toBitVec_intCast namespace CommRing attribute [scoped instance] instCommRing natCast intCast end CommRing end $typeName )) -- interpolating docstrings above is more trouble than it's worth let docString := s!"To use this instance, use `open scoped {typeName'}.CommRing`.\n\n" ++ "See the module docstring for an explanation" Lean.addDocStringCore (typeName'.mkStr "instCommRing") docString -- TODO: add these docstrings in core? -- Lean.addDocStringCore (typeName'.mkStr "instNatCast") docString -- Lean.addDocStringCore (typeName'.mkStr "instIntCast") docString namespace UInt8 /-- Is this an uppercase ASCII letter? -/ def isASCIIUpper (c : UInt8) : Bool := c ≥ 65 && c ≤ 90 /-- Is this a lowercase ASCII letter? -/ def isASCIILower (c : UInt8) : Bool := c ≥ 97 && c ≤ 122 /-- Is this an alphabetic ASCII character? -/ def isASCIIAlpha (c : UInt8) : Bool := c.isASCIIUpper || c.isASCIILower /-- Is this an ASCII digit character? -/ def isASCIIDigit (c : UInt8) : Bool := c ≥ 48 && c ≤ 57 /-- Is this an alphanumeric ASCII character? -/ def isASCIIAlphanum (c : UInt8) : Bool := c.isASCIIAlpha || c.isASCIIDigit /-- The numbers from 0 to 256 are all valid UTF-8 characters, so we can embed one in the other. -/ def toChar (n : UInt8) : Char := ⟨n.toUInt32, .inl (Nat.lt_trans n.toBitVec.isLt (by decide))⟩ end UInt8
polyXY.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype choice ssrnat seq. From mathcomp Require Import fintype tuple finfun bigop fingroup perm div. From mathcomp Require Import ssralg zmodp matrix mxalgebra. From mathcomp Require Import poly polydiv mxpoly binomial. (******************************************************************************) (* This file provides additional primitives and theory for bivariate *) (* polynomials (polynomials of two variables), represented as polynomials *) (* with (univariate) polynomial coefficients : *) (* 'Y == the (generic) second variable (:= 'X%:P). *) (* p^:P == the bivariate polynomial p['X], for p univariate. *) (* := map_poly polyC p (this notation is defined in poly.v). *) (* u.[x, y] == the bivariate polynomial u evaluated at 'X = x, 'Y = y. *) (* := u.[x%:P].[y]. *) (* sizeY u == the size of u in 'Y (1 + the 'Y-degree of u, if u != 0). *) (* := \max_(i < size u) size u`_i. *) (* swapXY u == the bivariate polynomial u['Y, 'X], for u bivariate. *) (* poly_XaY p == the bivariate polynomial p['X + 'Y], for p univariate. *) (* := p^:P \Po ('X + 'Y). *) (* poly_XmY p == the bivariate polynomial p['X * 'Y], for p univariate. *) (* := P^:P \Po ('X * 'Y). *) (* sub_annihilant p q == for univariate p, q != 0, a nonzero polynomial whose *) (* roots include all the differences of roots of p and q, in *) (* all field extensions (:= resultant (poly_XaY p) q^:P). *) (* div_annihilant p q == for polynomials p != 0, q with q.[0] != 0, a nonzero *) (* polynomial whose roots include all the quotients of roots *) (* of p by roots of q, in all field extensions *) (* (:= resultant (poly_XmY p) q^:P). *) (* The latter two "annhilants" provide uniform witnesses for an alternative *) (* proof of the closure of the algebraicOver predicate (see mxpoly.v). The *) (* fact that the annhilant does not depend on the particular choice of roots *) (* of p and q is crucial for the proof of the Primitive Element Theorem (file *) (* separable.v). *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Local Open Scope ring_scope. Import GRing.Theory. Local Notation "p ^ f" := (map_poly f p) : ring_scope. Local Notation eval := horner_eval. Notation "'Y" := 'X%:P : ring_scope. Notation "p ^:P" := (p ^ polyC) (format "p ^:P") : ring_scope. Notation "p .[ x , y ]" := (p.[x%:P].[y]) (left associativity, format "p .[ x , y ]") : ring_scope. Section PolyXY_NzRing. Variable R : nzRingType. Implicit Types (u : {poly {poly R}}) (p q : {poly R}) (x : R). Fact swapXY_key : unit. Proof. by []. Qed. Definition swapXY_def u : {poly {poly R}} := (u ^ map_poly polyC).['Y]. Definition swapXY := locked_with swapXY_key swapXY_def. Canonical swapXY_unlockable := [unlockable fun swapXY]. Definition sizeY u : nat := \max_(i < size u) (size u`_i). Definition poly_XaY p : {poly {poly R}} := p^:P \Po ('X + 'Y). Definition poly_XmY p : {poly {poly R}} := p^:P \Po ('X * 'Y). Definition sub_annihilant p q := resultant (poly_XaY p) q^:P. Definition div_annihilant p q := resultant (poly_XmY p) q^:P. Lemma swapXY_polyC p : swapXY p%:P = p^:P. Proof. by rewrite unlock map_polyC hornerC. Qed. Lemma swapXY_X : swapXY 'X = 'Y. Proof. by rewrite unlock map_polyX hornerX. Qed. Lemma swapXY_Y : swapXY 'Y = 'X. Proof. by rewrite swapXY_polyC map_polyX. Qed. Lemma swapXY_is_zmod_morphism : zmod_morphism swapXY. Proof. by move=> u v; rewrite unlock rmorphB !hornerE. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `swapXY_is_zmod_morphism` instead")] Definition swapXY_is_additive := swapXY_is_zmod_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build {poly {poly R}} {poly {poly R}} swapXY swapXY_is_zmod_morphism. Lemma coef_swapXY u i j : (swapXY u)`_i`_j = u`_j`_i. Proof. elim/poly_ind: u => [|u p IHu] in i j *; first by rewrite raddf0 !coef0. rewrite raddfD !coefD /= swapXY_polyC coef_map /= !coefC coefMX. rewrite !(fun_if (fun q : {poly R} => q`_i)) coef0 -IHu; congr (_ + _). by rewrite unlock rmorphM /= map_polyX hornerMX coefMC coefMX. Qed. Lemma swapXYK : involutive swapXY. Proof. by move=> u; apply/polyP=> i; apply/polyP=> j; rewrite !coef_swapXY. Qed. Lemma swapXY_map_polyC p : swapXY p^:P = p%:P. Proof. by rewrite -swapXY_polyC swapXYK. Qed. Lemma swapXY_eq0 u : (swapXY u == 0) = (u == 0). Proof. by rewrite (inv_eq swapXYK) raddf0. Qed. Lemma swapXY_is_monoid_morphism : monoid_morphism swapXY. Proof. split=> [|u v]; first by rewrite swapXY_polyC map_polyC. apply/polyP=> i; apply/polyP=> j; rewrite coef_swapXY !coefM !coef_sum. rewrite (eq_bigr _ (fun _ _ => coefM _ _ _)) exchange_big /=. apply: eq_bigr => j1 _; rewrite coefM; apply: eq_bigr=> i1 _. by rewrite !coef_swapXY. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `swapXY_is_monoid_morphism` instead")] Definition swapXY_is_multiplicative := (fun g => (g.2,g.1)) swapXY_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly {poly R}} {poly {poly R}} swapXY swapXY_is_monoid_morphism. Lemma swapXY_is_scalable : scalable_for (map_poly polyC \; *%R) swapXY. Proof. by move=> p u /=; rewrite -mul_polyC rmorphM /= swapXY_polyC. Qed. HB.instance Definition _ := GRing.isScalable.Build {poly R} {poly {poly R}} {poly {poly R}} (map_poly polyC \; *%R) swapXY swapXY_is_scalable. Lemma swapXY_comp_poly p u : swapXY (p^:P \Po u) = p^:P \Po swapXY u. Proof. rewrite -horner_map; congr _.[_]; rewrite -!map_poly_comp /=. by apply: eq_map_poly => x; rewrite /= swapXY_polyC map_polyC. Qed. Lemma max_size_coefXY u i : size u`_i <= sizeY u. Proof. have [ltiu | /(nth_default 0)->] := ltnP i (size u); last by rewrite size_poly0. exact: (bigmax_sup (Ordinal ltiu)). Qed. Lemma max_size_lead_coefXY u : size (lead_coef u) <= sizeY u. Proof. by rewrite lead_coefE max_size_coefXY. Qed. Lemma max_size_evalX u : size u.['X] <= sizeY u + (size u).-1. Proof. rewrite horner_coef (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP=> i _. rewrite (leq_trans (size_polyMleq _ _)) // size_polyXn addnS. by rewrite leq_add ?max_size_coefXY //= -ltnS (leq_trans _ (leqSpred _)). Qed. Lemma max_size_evalC u x : size u.[x%:P] <= sizeY u. Proof. rewrite horner_coef (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP=> i _. rewrite (leq_trans (size_polyMleq _ _)) // -polyC_exp size_polyC addnC -subn1. by rewrite (leq_trans _ (max_size_coefXY _ i)) // leq_subLR leq_add2r leq_b1. Qed. Lemma sizeYE u : sizeY u = size (swapXY u). Proof. apply/eqP; rewrite eqn_leq; apply/andP; split. apply/bigmax_leqP=> /= i _; apply/leq_sizeP => j /(nth_default 0) u_j_0. by rewrite -coef_swapXY u_j_0 coef0. apply/leq_sizeP=> j le_uY_j; apply/polyP=> i; rewrite coef_swapXY coef0. by rewrite nth_default // (leq_trans _ le_uY_j) ?max_size_coefXY. Qed. Lemma sizeY_eq0 u : (sizeY u == 0) = (u == 0). Proof. by rewrite sizeYE size_poly_eq0 swapXY_eq0. Qed. Lemma sizeY_mulX u : sizeY (u * 'X) = sizeY u. Proof. rewrite !sizeYE rmorphM /= swapXY_X rreg_size //. by have /monic_comreg[_ /rreg_lead] := monicX R. Qed. Lemma swapXY_poly_XaY p : swapXY (poly_XaY p) = poly_XaY p. Proof. by rewrite swapXY_comp_poly rmorphD /= swapXY_X swapXY_Y addrC. Qed. Lemma swapXY_poly_XmY p : swapXY (poly_XmY p) = poly_XmY p. Proof. by rewrite swapXY_comp_poly rmorphM /= swapXY_X swapXY_Y commr_polyX. Qed. Lemma poly_XaY0 : poly_XaY 0 = 0. Proof. by rewrite /poly_XaY rmorph0 comp_poly0. Qed. Lemma poly_XmY0 : poly_XmY 0 = 0. Proof. by rewrite /poly_XmY rmorph0 comp_poly0. Qed. End PolyXY_NzRing. Prenex Implicits swapXY sizeY poly_XaY poly_XmY sub_annihilant div_annihilant. Prenex Implicits swapXYK. Lemma swapXY_map (R S : nzRingType) (f : {additive R -> S}) u : swapXY (u ^ map_poly f) = swapXY u ^ map_poly f. Proof. by apply/polyP=> i; apply/polyP=> j; rewrite !(coef_map, coef_swapXY). Qed. Section PolyXY_ComNzRing. Variable R : comNzRingType. Implicit Types (u : {poly {poly R}}) (p : {poly R}) (x y : R). Lemma horner_swapXY u x : (swapXY u).[x%:P] = u ^ eval x. Proof. apply/polyP=> i /=; rewrite coef_map /= /eval horner_coef coef_sum -sizeYE. rewrite (horner_coef_wide _ (max_size_coefXY u i)); apply: eq_bigr=> j _. by rewrite -polyC_exp coefMC coef_swapXY. Qed. Lemma horner_polyC u x : u.[x%:P] = swapXY u ^ eval x. Proof. by rewrite -horner_swapXY swapXYK. Qed. Lemma horner2_swapXY u x y : (swapXY u).[x, y] = u.[y, x]. Proof. by rewrite horner_swapXY -{1}(hornerC y x) horner_map. Qed. Lemma horner_poly_XaY p v : (poly_XaY p).[v] = p \Po (v + 'X). Proof. by rewrite horner_comp !hornerE. Qed. Lemma horner_poly_XmY p v : (poly_XmY p).[v] = p \Po (v * 'X). Proof. by rewrite horner_comp !hornerE. Qed. End PolyXY_ComNzRing. Section PolyXY_Idomain. Variable R : idomainType. Implicit Types (p q : {poly R}) (x y : R). Lemma size_poly_XaY p : size (poly_XaY p) = size p. Proof. by rewrite size_comp_poly2 ?size_XaddC // size_map_polyC. Qed. Lemma poly_XaY_eq0 p : (poly_XaY p == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 size_poly_XaY. Qed. Lemma size_poly_XmY p : size (poly_XmY p) = size p. Proof. by rewrite size_comp_poly2 ?size_XmulC ?polyX_eq0 ?size_map_polyC. Qed. Lemma poly_XmY_eq0 p : (poly_XmY p == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 size_poly_XmY. Qed. Lemma lead_coef_poly_XaY p : lead_coef (poly_XaY p) = (lead_coef p)%:P. Proof. rewrite lead_coef_comp ?size_XaddC // -['Y]opprK -polyCN lead_coefXsubC. by rewrite expr1n mulr1 lead_coef_map_inj //; apply: polyC_inj. Qed. Lemma sub_annihilant_in_ideal p q : 1 < size p -> 1 < size q -> {uv : {poly {poly R}} * {poly {poly R}} | size uv.1 < size q /\ size uv.2 < size p & forall x y, (sub_annihilant p q).[y] = uv.1.[x, y] * p.[x + y] + uv.2.[x, y] * q.[x]}. Proof. rewrite -size_poly_XaY -(size_map_polyC q) => p1_gt1 q1_gt1. have [uv /= [ub_u ub_v Dr]] := resultant_in_ideal p1_gt1 q1_gt1. exists uv => // x y; rewrite -[r in r.[y]](hornerC _ x%:P) Dr. by rewrite !(hornerE, horner_comp). Qed. Lemma sub_annihilantP p q x y : p != 0 -> q != 0 -> p.[x] = 0 -> q.[y] = 0 -> (sub_annihilant p q).[x - y] = 0. Proof. move=> nz_p nz_q px0 qy0. have p_gt1: size p > 1 by have /rootP/root_size_gt1-> := px0. have q_gt1: size q > 1 by have /rootP/root_size_gt1-> := qy0. have [uv /= _ /(_ y)->] := sub_annihilant_in_ideal p_gt1 q_gt1. by rewrite (addrC y) subrK px0 qy0 !mulr0 addr0. Qed. Lemma sub_annihilant_neq0 p q : p != 0 -> q != 0 -> sub_annihilant p q != 0. Proof. rewrite resultant_eq0; set p1 := poly_XaY p => nz_p nz_q. have [nz_p1 nz_q1]: p1 != 0 /\ q^:P != 0 by rewrite poly_XaY_eq0 map_polyC_eq0. rewrite -leqNgt eq_leq //; apply/eqP/Bezout_coprimepPn=> // [[[u v]]] /=. rewrite !size_poly_gt0 -andbA => /and4P[nz_u ltuq nz_v _] Duv. have /eqP/= := congr1 (size \o (lead_coef \o swapXY)) Duv. rewrite ltn_eqF // !rmorphM !lead_coefM (leq_trans (leq_ltn_trans _ ltuq)) //=. rewrite -{2}[u]swapXYK -sizeYE swapXY_poly_XaY lead_coef_poly_XaY. by rewrite mulrC mul_polyC size_scale ?max_size_lead_coefXY ?lead_coef_eq0. rewrite swapXY_map_polyC lead_coefC size_map_polyC. set v1 := lead_coef _; have nz_v1: v1 != 0 by rewrite lead_coef_eq0 swapXY_eq0. rewrite [leqRHS]polySpred ?mulf_neq0 // size_mul //. by rewrite (polySpred nz_v1) addnC addnS polySpred // ltnS leq_addr. Qed. Lemma div_annihilant_in_ideal p q : 1 < size p -> 1 < size q -> {uv : {poly {poly R}} * {poly {poly R}} | size uv.1 < size q /\ size uv.2 < size p & forall x y, (div_annihilant p q).[y] = uv.1.[x, y] * p.[x * y] + uv.2.[x, y] * q.[x]}. Proof. rewrite -size_poly_XmY -(size_map_polyC q) => p1_gt1 q1_gt1. have [uv /= [ub_u ub_v Dr]] := resultant_in_ideal p1_gt1 q1_gt1. exists uv => // x y; rewrite -[r in r.[y]](hornerC _ x%:P) Dr. by rewrite !(hornerE, horner_comp). Qed. Lemma div_annihilant_neq0 p q : p != 0 -> q.[0] != 0 -> div_annihilant p q != 0. Proof. have factorX u: u != 0 -> root u 0 -> exists2 v, v != 0 & u = v * 'X. move=> nz_u /factor_theorem[v]; rewrite subr0 => Du; exists v => //. by apply: contraNneq nz_u => v0; rewrite Du v0 mul0r. have nzX: 'X != 0 := monic_neq0 (monicX _); have rootC0 := root_polyC _ 0. rewrite resultant_eq0 -leqNgt -rootE // => nz_p nz_q0; apply/eq_leq/eqP. have nz_q: q != 0 by apply: contraNneq nz_q0 => ->; rewrite root0. apply/Bezout_coprimepPn; rewrite ?map_polyC_eq0 ?poly_XmY_eq0 // => [[uv]]. rewrite !size_poly_gt0 -andbA ltnNge => /and4P[nz_u /negP ltuq nz_v _] Duv. pose u := swapXY uv.1; pose v := swapXY uv.2. suffices{ltuq}: size q <= sizeY u by rewrite sizeYE swapXYK -size_map_polyC. have{nz_u nz_v} [nz_u nz_v Dvu]: [/\ u != 0, v != 0 & q *: v = u * poly_XmY p]. rewrite !swapXY_eq0; split=> //; apply: (can_inj swapXYK). by rewrite linearZ rmorphM /= !swapXYK swapXY_poly_XmY Duv mulrC. have{Duv} [n ltvn]: {n | size v < n} by exists (size v).+1. elim: n {uv} => // n IHn in p (v) (u) nz_u nz_v Dvu nz_p ltvn *. have Dp0: root (poly_XmY p) 0 = root p 0 by rewrite root_comp !hornerE rootC0. have Dv0: root u 0 || root p 0 = root v 0 by rewrite -Dp0 -rootM -Dvu rootZ. have [v0_0 | nz_v0] := boolP (root v 0); last first. have nz_p0: ~~ root p 0 by apply: contra nz_v0; rewrite -Dv0 orbC => ->. apply: (@leq_trans (size (q * v.[0]))). by rewrite size_mul // (polySpred nz_v0) addnS leq_addr. rewrite -hornerZ Dvu !(horner_comp, hornerE) horner_map mulrC size_Cmul //. by rewrite horner_coef0 max_size_coefXY. have [v1 nz_v1 Dv] := factorX _ _ nz_v v0_0; rewrite Dv size_mulX // in ltvn. have /orP[/factorX[//|u1 nz_u1 Du] | p0_0]: root u 0 || root p 0 by rewrite Dv0. rewrite Du sizeY_mulX; apply: IHn nz_u1 nz_v1 _ nz_p ltvn. by apply: (mulIf (nzX _)); rewrite mulrAC -scalerAl -Du -Dv. have /factorX[|v2 nz_v2 Dv1]: root (swapXY v1) 0; rewrite ?swapXY_eq0 //. suffices: root (swapXY v1 * 'Y) 0 by rewrite mulrC mul_polyC rootZ ?polyX_eq0. have: root (swapXY (q *: v)) 0. by rewrite Dvu rmorphM rootM /= swapXY_poly_XmY Dp0 p0_0 orbT. by rewrite linearZ /= rootM rootC0 (negPf nz_q0) /= Dv rmorphM /= swapXY_X. rewrite ltnS (canRL swapXYK Dv1) -sizeYE sizeY_mulX sizeYE in ltvn. have [p1 nz_p1 Dp] := factorX _ _ nz_p p0_0. apply: IHn nz_u _ _ nz_p1 ltvn; first by rewrite swapXY_eq0. have: 'X * 'Y != 0 :> {poly {poly R}} by rewrite mulf_neq0 ?polyC_eq0 ?nzX. move/mulIf; apply. rewrite -scalerAl mulrA mulrAC -{1}swapXY_X -rmorphM /= -Dv1 swapXYK -Dv Dvu. by rewrite /poly_XmY Dp rmorphM /= map_polyX comp_polyM comp_polyX mulrA. Qed. End PolyXY_Idomain. Section PolyXY_Field. Variables (F E : fieldType) (FtoE : {rmorphism F -> E}). Local Notation pFtoE := (map_poly (GRing.RMorphism.sort FtoE)). Lemma div_annihilantP (p q : {poly E}) (x y : E) : p != 0 -> q != 0 -> y != 0 -> p.[x] = 0 -> q.[y] = 0 -> (div_annihilant p q).[x / y] = 0. Proof. move=> nz_p nz_q nz_y px0 qy0. have p_gt1: size p > 1 by have /rootP/root_size_gt1-> := px0. have q_gt1: size q > 1 by have /rootP/root_size_gt1-> := qy0. have [uv /= _ /(_ y)->] := div_annihilant_in_ideal p_gt1 q_gt1. by rewrite (mulrC y) divfK // px0 qy0 !mulr0 addr0. Qed. Lemma map_sub_annihilantP (p q : {poly F}) (x y : E) : p != 0 -> q != 0 ->(p ^ FtoE).[x] = 0 -> (q ^ FtoE).[y] = 0 -> (sub_annihilant p q ^ FtoE).[x - y] = 0. Proof. move=> nz_p nz_q px0 qy0; have pFto0 := map_poly_eq0 FtoE. rewrite map_resultant ?pFto0 ?lead_coef_eq0 ?map_poly_eq0 ?poly_XaY_eq0 //. rewrite map_comp_poly rmorphD /= map_polyC /= !map_polyX -!map_poly_comp /=. by rewrite !(eq_map_poly (map_polyC _)) !map_poly_comp sub_annihilantP ?pFto0. Qed. Lemma map_div_annihilantP (p q : {poly F}) (x y : E) : p != 0 -> q != 0 -> y != 0 -> (p ^ FtoE).[x] = 0 -> (q ^ FtoE).[y] = 0 -> (div_annihilant p q ^ FtoE).[x / y] = 0. Proof. move=> nz_p nz_q nz_y px0 qy0; have pFto0 := map_poly_eq0 FtoE. rewrite map_resultant ?pFto0 ?lead_coef_eq0 ?map_poly_eq0 ?poly_XmY_eq0 //. rewrite map_comp_poly rmorphM /= map_polyC /= !map_polyX -!map_poly_comp /=. by rewrite !(eq_map_poly (map_polyC _)) !map_poly_comp div_annihilantP ?pFto0. Qed. Lemma root_annihilant x p (pEx := (p ^ pFtoE).[x%:P]) : pEx != 0 -> algebraicOver FtoE x -> exists2 r : {poly F}, r != 0 & forall y, root pEx y -> root (r ^ FtoE) y. Proof. move=> nz_px [q nz_q qx0]. have [/size1_polyC Dp | p_gt1] := leqP (size p) 1. by rewrite {}/pEx Dp map_polyC hornerC map_poly_eq0 in nz_px *; exists p`_0. have nz_p: p != 0 by rewrite -size_poly_gt0 ltnW. have [m le_qm] := ubnP (size q); elim: m => // m IHm in q le_qm nz_q qx0 *. have nz_q1: q^:P != 0 by rewrite map_poly_eq0. have sz_q1: size q^:P = size q by rewrite size_map_polyC. have q1_gt1: size q^:P > 1. by rewrite sz_q1 -(size_map_poly FtoE) (root_size_gt1 _ qx0) ?map_poly_eq0. have [uv _ Dr] := resultant_in_ideal p_gt1 q1_gt1; set r := resultant p _ in Dr. have /eqP q1x0: (q^:P ^ pFtoE).[x%:P] == 0. by rewrite -swapXY_polyC -swapXY_map horner_swapXY !map_polyC polyC_eq0. have [|r_nz] := boolP (r == 0); last first. exists r => // y pxy0; rewrite -[r ^ _](hornerC _ x%:P) -map_polyC Dr. by rewrite rmorphD !rmorphM !hornerE q1x0 mulr0 addr0 rootM pxy0 orbT. rewrite resultant_eq0 => /gtn_eqF/Bezout_coprimepPn[]// [q2 p1] /=. rewrite size_poly_gt0 sz_q1 => /andP[/andP[nz_q2 ltq2] _] Dq. pose n := (size (lead_coef q2)).-1; pose q3 := map_poly (coefp n) q2. have nz_q3: q3 != 0 by rewrite map_poly_eq0_id0 ?lead_coef_eq0. apply: (IHm q3); rewrite ?(leq_ltn_trans (size_poly _ _)) ?(leq_trans ltq2) //. have /polyP/(_ n)/eqP: (q2 ^ pFtoE).[x%:P] = 0. apply: (mulIf nz_px); rewrite -hornerM -rmorphM Dq rmorphM hornerM /= q1x0. by rewrite mul0r mulr0. rewrite coef0; congr (_ == 0); rewrite !horner_coef coef_sum. rewrite size_map_poly !size_map_poly_id0 ?map_poly_eq0 ?lead_coef_eq0 //. by apply: eq_bigr => i _; rewrite -rmorphXn coefMC !coef_map. Qed. Lemma algebraic_root_polyXY x y : (let pEx p := (p ^ map_poly FtoE).[x%:P] in exists2 p, pEx p != 0 & root (pEx p) y) -> algebraicOver FtoE x -> algebraicOver FtoE y. Proof. by case=> p nz_px pxy0 /(root_annihilant nz_px)[r]; exists r; auto. Qed. End PolyXY_Field.
Dimension.lean
/- Copyright (c) 2024 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.Algebra.Homology.DerivedCategory.Ext.EnoughProjectives /-! # Projective dimension In an abelian category `C`, we shall say that `X : C` has projective dimension `< n` if all `Ext X Y i` vanish when `n ≤ i`. This defines a type class `HasProjectiveDimensionLT X n`. We also define a type class `HasProjectiveDimensionLE X n` as an abbreviation for `HasProjectiveDimensionLT X (n + 1)`. (Note that the fact that `X` is a zero object is equivalent to the condition `HasProjectiveDimensionLT X 0`, but this cannot be expressed in terms of `HasProjectiveDimensionLE`.) -/ universe w v u namespace CategoryTheory open Abelian Limits ZeroObject variable {C : Type u} [Category.{v} C] [Abelian C] /-- An object `X` in an abelian category has projective dimension `< n` if all `Ext X Y i` vanish when `n ≤ i`. See also `HasProjectiveDimensionLE`. (Do not use the `subsingleton'` field directly. Use the constructor `HasProjectiveDimensionLT.mk`, and the lemmas `hasProjectiveDimensionLT_iff` and `Ext.eq_zero_of_hasProjectiveDimensionLT`.) -/ class HasProjectiveDimensionLT (X : C) (n : ℕ) : Prop where mk' :: subsingleton' (i : ℕ) (hi : n ≤ i) ⦃Y : C⦄ : letI := HasExt.standard C Subsingleton (Ext.{max u v} X Y i) /-- An object `X` in an abelian category has projective dimension `≤ n` if all `Ext X Y i` vanish when `n + 1 ≤ i` -/ abbrev HasProjectiveDimensionLE (X : C) (n : ℕ) : Prop := HasProjectiveDimensionLT X (n + 1) namespace HasProjectiveDimensionLT variable [HasExt.{w} C] (X : C) (n : ℕ) lemma subsingleton [hX : HasProjectiveDimensionLT X n] (i : ℕ) (hi : n ≤ i) (Y : C) : Subsingleton (Ext.{w} X Y i) := by letI := HasExt.standard C have := hX.subsingleton' i hi exact Ext.chgUniv.{w, max u v}.symm.subsingleton variable {X n} in lemma mk (hX : ∀ (i : ℕ) (_ : n ≤ i) ⦃Y : C⦄, ∀ (e : Ext X Y i), e = 0) : HasProjectiveDimensionLT X n where subsingleton' i hi Y := by have : Subsingleton (Ext X Y i) := ⟨fun e₁ e₂ ↦ by simp only [hX i hi]⟩ letI := HasExt.standard C exact Ext.chgUniv.{max u v, w}.symm.subsingleton end HasProjectiveDimensionLT lemma Abelian.Ext.eq_zero_of_hasProjectiveDimensionLT [HasExt.{w} C] {X Y : C} {i : ℕ} (e : Ext X Y i) (n : ℕ) [HasProjectiveDimensionLT X n] (hi : n ≤ i) : e = 0 := (HasProjectiveDimensionLT.subsingleton X n i hi Y).elim _ _ section variable (X : C) (n : ℕ) lemma hasProjectiveDimensionLT_iff [HasExt.{w} C] : HasProjectiveDimensionLT X n ↔ ∀ (i : ℕ) (_ : n ≤ i) ⦃Y : C⦄, ∀ (e : Ext X Y i), e = 0 := ⟨fun _ _ hi _ e ↦ e.eq_zero_of_hasProjectiveDimensionLT n hi, HasProjectiveDimensionLT.mk⟩ variable {X} in lemma Limits.IsZero.hasProjectiveDimensionLT_zero (hX : IsZero X) : HasProjectiveDimensionLT X 0 := by letI := HasExt.standard C rw [hasProjectiveDimensionLT_iff] intro i hi Y e rw [← e.mk₀_id_comp, hX.eq_of_src (𝟙 X) 0, Ext.mk₀_zero, Ext.zero_comp] instance : HasProjectiveDimensionLT (0 : C) 0 := (isZero_zero C).hasProjectiveDimensionLT_zero lemma isZero_of_hasProjectiveDimensionLT_zero [HasProjectiveDimensionLT X 0] : IsZero X := by letI := HasExt.standard C rw [IsZero.iff_id_eq_zero] apply Ext.homEquiv₀.symm.injective simpa only [Ext.homEquiv₀_symm_apply, Ext.mk₀_zero] using Abelian.Ext.eq_zero_of_hasProjectiveDimensionLT _ 0 (by rfl) lemma hasProjectiveDimensionLT_of_ge (m : ℕ) (h : n ≤ m) [HasProjectiveDimensionLT X n] : HasProjectiveDimensionLT X m := by letI := HasExt.standard C rw [hasProjectiveDimensionLT_iff] intro i hi Y e exact e.eq_zero_of_hasProjectiveDimensionLT n (by omega) instance [HasProjectiveDimensionLT X n] (k : ℕ) : HasProjectiveDimensionLT X (n + k) := hasProjectiveDimensionLT_of_ge X n (n + k) (by omega) instance [HasProjectiveDimensionLT X n] (k : ℕ) : HasProjectiveDimensionLT X (k + n) := hasProjectiveDimensionLT_of_ge X n (k + n) (by omega) instance [HasProjectiveDimensionLT X n] : HasProjectiveDimensionLT X n.succ := inferInstanceAs (HasProjectiveDimensionLT X (n + 1)) instance [Projective X] : HasProjectiveDimensionLT X 1 := by letI := HasExt.standard C rw [hasProjectiveDimensionLT_iff] intro i hi Y e obtain _ | i := i · simp at hi · exact e.eq_zero_of_projective end lemma Retract.hasProjectiveDimensionLT {X Y : C} (h : Retract X Y) (n : ℕ) [HasProjectiveDimensionLT Y n] : HasProjectiveDimensionLT X n := by letI := HasExt.standard C rw [hasProjectiveDimensionLT_iff] intro i hi T x rw [← x.mk₀_id_comp, ← h.retract, ← Ext.mk₀_comp_mk₀, Ext.comp_assoc_of_second_deg_zero, ((Ext.mk₀ h.r).comp x (zero_add i)).eq_zero_of_hasProjectiveDimensionLT n hi, Ext.comp_zero] lemma hasProjectiveDimensionLT_of_iso {X X' : C} (e : X ≅ X') (n : ℕ) [HasProjectiveDimensionLT X n] : HasProjectiveDimensionLT X' n := e.symm.retract.hasProjectiveDimensionLT n namespace ShortComplex namespace ShortExact variable {S : ShortComplex C} (hS : S.ShortExact) (n : ℕ) include hS -- In the following lemmas, the parameters `HasProjectiveDimensionLT` are -- explicit as it is unlikely we may infer them, unless the short complex `S` -- was declared reducible lemma hasProjectiveDimensionLT_X₂ (h₁ : HasProjectiveDimensionLT S.X₁ n) (h₃ : HasProjectiveDimensionLT S.X₃ n) : HasProjectiveDimensionLT S.X₂ n := by letI := HasExt.standard C rw [hasProjectiveDimensionLT_iff] intro i hi Y x₂ obtain ⟨x₃, rfl⟩ := Ext.contravariant_sequence_exact₂ hS _ x₂ (Ext.eq_zero_of_hasProjectiveDimensionLT _ n hi) rw [x₃.eq_zero_of_hasProjectiveDimensionLT n hi, Ext.comp_zero] lemma hasProjectiveDimensionLT_X₃ (h₁ : HasProjectiveDimensionLT S.X₁ n) (h₂ : HasProjectiveDimensionLT S.X₂ (n + 1)) : HasProjectiveDimensionLT S.X₃ (n + 1) := by letI := HasExt.standard C rw [hasProjectiveDimensionLT_iff] rintro (_ | i) hi Y x₃ · simp at hi · obtain ⟨x₁, rfl⟩ := Ext.contravariant_sequence_exact₃ hS _ x₃ (Ext.eq_zero_of_hasProjectiveDimensionLT _ (n + 1) hi) (add_comm _ _) rw [x₁.eq_zero_of_hasProjectiveDimensionLT n (by omega), Ext.comp_zero] lemma hasProjectiveDimensionLT_X₁ (h₂ : HasProjectiveDimensionLT S.X₂ n) (h₃ : HasProjectiveDimensionLT S.X₃ (n + 1)) : HasProjectiveDimensionLT S.X₁ n := by letI := HasExt.standard C rw [hasProjectiveDimensionLT_iff] intro i hi Y x₁ obtain ⟨x₂, rfl⟩ := Ext.contravariant_sequence_exact₁ hS _ x₁ (add_comm _ _) (Ext.eq_zero_of_hasProjectiveDimensionLT _ (n + 1) (by omega)) rw [x₂.eq_zero_of_hasProjectiveDimensionLT n (by omega), Ext.comp_zero] lemma hasProjectiveDimensionLT_X₃_iff (n : ℕ) (h₂ : Projective S.X₂) : HasProjectiveDimensionLT S.X₃ (n + 2) ↔ HasProjectiveDimensionLT S.X₁ (n + 1) := ⟨fun _ ↦ hS.hasProjectiveDimensionLT_X₁ (n + 1) inferInstance inferInstance, fun _ ↦ hS.hasProjectiveDimensionLT_X₃ (n + 1) inferInstance inferInstance⟩ end ShortExact end ShortComplex instance (X Y : C) (n : ℕ) [HasProjectiveDimensionLT X n] [HasProjectiveDimensionLT Y n] : HasProjectiveDimensionLT (X ⊞ Y) n := (ShortComplex.Splitting.ofHasBinaryBiproduct X Y).shortExact.hasProjectiveDimensionLT_X₂ n (by assumption) (by assumption) end CategoryTheory
LinearCombination.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Algebra.Module.Submodule.Equiv import Mathlib.Data.Finsupp.Option import Mathlib.LinearAlgebra.Finsupp.Supported /-! # `Finsupp.linearCombination` ## Main definitions * `Finsupp.linearCombination R (v : ι → M)`: sends `l : ι →₀ R` to the linear combination of `v i` with coefficients `l i`; * `Finsupp.linearCombinationOn`: a restricted version of `Finsupp.linearCombination` with domain * `Fintype.linearCombination R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with coefficients `l i` (for a finite type `ι`) * `Finsupp.bilinearCombination R S`, `Fintype.bilinearCombination R S`: a bilinear version of `Finsupp.linearCombination` and `Fintype.linearCombination`. It requires that `M` is both an `R`-module and an `S`-module, with `SMulCommClass R S M`; the case `S = R` typically requires that `R` is commutative. ## Tags function with finite support, module, linear algebra -/ noncomputable section open Set LinearMap Submodule namespace Finsupp 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] section LinearCombination variable (R) variable {α' : Type*} {M' : Type*} [AddCommMonoid M'] [Module R M'] (v : α → M) {v' : α' → M'} /-- Interprets (l : α →₀ R) as a linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ def linearCombination : (α →₀ R) →ₗ[R] M := Finsupp.lsum ℕ fun i => LinearMap.id.smulRight (v i) variable {v} theorem linearCombination_apply (l : α →₀ R) : linearCombination R v l = l.sum fun i a => a • v i := rfl theorem linearCombination_apply_of_mem_supported {l : α →₀ R} {s : Finset α} (hs : l ∈ supported R R (↑s : Set α)) : linearCombination R v l = s.sum fun i => l i • v i := Finset.sum_subset hs fun x _ hxg => show l x • v x = 0 by rw [notMem_support_iff.1 hxg, zero_smul] @[simp] theorem linearCombination_single (c : R) (a : α) : linearCombination R v (single a c) = c • v a := by simp [linearCombination_apply, sum_single_index] theorem linearCombination_zero_apply (x : α →₀ R) : (linearCombination R (0 : α → M)) x = 0 := by simp [linearCombination_apply] variable (α M) @[simp] theorem linearCombination_zero : linearCombination R (0 : α → M) = 0 := LinearMap.ext (linearCombination_zero_apply R) @[simp] theorem linearCombination_single_index (c : M) (a : α) (f : α →₀ R) [DecidableEq α] : linearCombination R (Pi.single a c) f = f a • c := by rw [linearCombination_apply, sum_eq_single a, Pi.single_eq_same] · exact fun i _ hi ↦ by rw [Pi.single_eq_of_ne hi, smul_zero] · exact fun _ ↦ by simp only [zero_smul] variable {α M} theorem linearCombination_linear_comp (f : M →ₗ[R] M') : linearCombination R (f ∘ v) = f ∘ₗ linearCombination R v := by ext simp [linearCombination_apply] theorem apply_linearCombination (f : M →ₗ[R] M') (v) (l : α →₀ R) : f (linearCombination R v l) = linearCombination R (f ∘ v) l := congr($(linearCombination_linear_comp R f) l).symm theorem apply_linearCombination_id (f : M →ₗ[R] M') (l : M →₀ R) : f (linearCombination R _root_.id l) = linearCombination R f l := apply_linearCombination .. theorem linearCombination_unique [Unique α] (l : α →₀ R) (v : α → M) : linearCombination R v l = l default • v default := by rw [← linearCombination_single, ← unique_single l] theorem linearCombination_surjective (h : Function.Surjective v) : Function.Surjective (linearCombination R v) := by intro x obtain ⟨y, hy⟩ := h x exact ⟨single y 1, by simp [hy]⟩ theorem linearCombination_range (h : Function.Surjective v) : LinearMap.range (linearCombination R v) = ⊤ := range_eq_top.2 <| linearCombination_surjective R h /-- Any module is a quotient of a free module. This is stated as surjectivity of `Finsupp.linearCombination R id : (M →₀ R) →ₗ[R] M`. -/ theorem linearCombination_id_surjective (M) [AddCommMonoid M] [Module R M] : Function.Surjective (linearCombination R (id : M → M)) := linearCombination_surjective R Function.surjective_id theorem range_linearCombination : LinearMap.range (linearCombination R v) = span R (range v) := by ext x constructor · intro hx rw [LinearMap.mem_range] at hx rcases hx with ⟨l, hl⟩ rw [← hl] rw [linearCombination_apply] exact sum_mem fun i _ => Submodule.smul_mem _ _ (subset_span (mem_range_self i)) · apply span_le.2 intro x hx rcases hx with ⟨i, hi⟩ rw [SetLike.mem_coe, LinearMap.mem_range] use single i 1 simp [hi] theorem lmapDomain_linearCombination (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) : (linearCombination R v').comp (lmapDomain R R f) = g.comp (linearCombination R v) := by ext l simp [linearCombination_apply, h] theorem linearCombination_comp_lmapDomain (f : α → α') : (linearCombination R v').comp (Finsupp.lmapDomain R R f) = linearCombination R (v' ∘ f) := by ext simp @[simp] theorem linearCombination_embDomain (f : α ↪ α') (l : α →₀ R) : (linearCombination R v') (embDomain f l) = (linearCombination R (v' ∘ f)) l := by simp [linearCombination_apply, Finsupp.sum, support_embDomain, embDomain_apply] @[simp] theorem linearCombination_mapDomain (f : α → α') (l : α →₀ R) : (linearCombination R v') (mapDomain f l) = (linearCombination R (v' ∘ f)) l := LinearMap.congr_fun (linearCombination_comp_lmapDomain _ _) l @[simp] theorem linearCombination_equivMapDomain (f : α ≃ α') (l : α →₀ R) : (linearCombination R v') (equivMapDomain f l) = (linearCombination R (v' ∘ f)) l := by rw [equivMapDomain_eq_mapDomain, linearCombination_mapDomain] /-- A version of `Finsupp.range_linearCombination` which is useful for going in the other direction -/ theorem span_eq_range_linearCombination (s : Set M) : span R s = LinearMap.range (linearCombination R ((↑) : s → M)) := by rw [range_linearCombination, Subtype.range_coe_subtype, Set.setOf_mem_eq] theorem mem_span_iff_linearCombination (s : Set M) (x : M) : x ∈ span R s ↔ ∃ l : s →₀ R, linearCombination R (↑) l = x := (SetLike.ext_iff.1 <| span_eq_range_linearCombination _ _) x variable {R} in theorem mem_span_range_iff_exists_finsupp {v : α → M} {x : M} : x ∈ span R (range v) ↔ ∃ c : α →₀ R, (c.sum fun i a => a • v i) = x := by simp only [← Finsupp.range_linearCombination, LinearMap.mem_range, linearCombination_apply] theorem span_image_eq_map_linearCombination (s : Set α) : span R (v '' s) = Submodule.map (linearCombination R v) (supported R R s) := by apply span_eq_of_le · intro x hx rw [Set.mem_image] at hx apply Exists.elim hx intro i hi exact ⟨_, Finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ · refine map_le_iff_le_comap.2 fun z hz => ?_ have : ∀ i, z i • v i ∈ span R (v '' s) := by intro c haveI := Classical.decPred fun x => x ∈ s by_cases h : c ∈ s · exact smul_mem _ _ (subset_span (Set.mem_image_of_mem _ h)) · simp [(Finsupp.mem_supported' R _).1 hz _ h] rw [mem_comap, linearCombination_apply] refine sum_mem ?_ simp [this] theorem mem_span_image_iff_linearCombination {s : Set α} {x : M} : x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, linearCombination R v l = x := by rw [span_image_eq_map_linearCombination] simp theorem linearCombination_option (v : Option α → M) (f : Option α →₀ R) : linearCombination R v f = f none • v none + linearCombination R (v ∘ Option.some) f.some := by rw [linearCombination_apply, sum_option_index_smul, linearCombination_apply]; simp theorem linearCombination_linearCombination {α β : Type*} (A : α → M) (B : β → α →₀ R) (f : β →₀ R) : linearCombination R A (linearCombination R B f) = linearCombination R (fun b => linearCombination R A (B b)) f := by classical simp only [linearCombination_apply] induction f using induction_linear with | zero => simp only [sum_zero_index] | add f₁ f₂ h₁ h₂ => simp [sum_add_index, h₁, h₂, add_smul] | single => simp [sum_single_index, sum_smul_index, smul_sum, mul_smul] theorem linearCombination_smul [DecidableEq α] [Module R S] [Module S M] [IsScalarTower R S M] {w : α' → S} : linearCombination R (fun i : α × α' ↦ w i.2 • v i.1) = (linearCombination S v).restrictScalars R ∘ₗ mapRange.linearMap (linearCombination R w) ∘ₗ (finsuppProdLEquiv R).toLinearMap := by ext; simp @[simp] theorem linearCombination_fin_zero (f : Fin 0 → M) : linearCombination R f = 0 := by ext i apply finZeroElim i variable (α) (M) (v) /-- `Finsupp.linearCombinationOn M v s` interprets `p : α →₀ R` as a linear combination of a subset of the vectors in `v`, mapping it to the span of those vectors. The subset is indicated by a set `s : Set α` of indices. -/ def linearCombinationOn (s : Set α) : supported R R s →ₗ[R] span R (v '' s) := LinearMap.codRestrict _ ((linearCombination _ v).comp (Submodule.subtype (supported R R s))) fun ⟨l, hl⟩ => (mem_span_image_iff_linearCombination _).2 ⟨l, hl, rfl⟩ variable {α} {M} {v} theorem linearCombinationOn_range (s : Set α) : LinearMap.range (linearCombinationOn α M R v s) = ⊤ := by rw [linearCombinationOn, LinearMap.range_eq_map, LinearMap.map_codRestrict, ← LinearMap.range_le_iff_comap, range_subtype, Submodule.map_top, LinearMap.range_comp, range_subtype] exact (span_image_eq_map_linearCombination _ _).le theorem linearCombination_restrict (s : Set α) : linearCombination R (s.restrict v) = Submodule.subtype _ ∘ₗ linearCombinationOn α M R v s ∘ₗ (supportedEquivFinsupp s).symm.toLinearMap := by classical ext; simp [linearCombinationOn] theorem linearCombination_comp (f : α' → α) : linearCombination R (v ∘ f) = (linearCombination R v).comp (lmapDomain R R f) := by ext simp [linearCombination_apply] theorem linearCombination_comapDomain (f : α → α') (l : α' →₀ R) (hf : Set.InjOn f (f ⁻¹' ↑l.support)) : linearCombination R v (Finsupp.comapDomain f l hf) = (l.support.preimage f hf).sum fun i => l (f i) • v i := by rw [linearCombination_apply]; rfl theorem linearCombination_onFinset {s : Finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s) : linearCombination R g (Finsupp.onFinset s f hf) = Finset.sum s fun x : α => f x • g x := by classical simp only [linearCombination_apply, Finsupp.sum, Finsupp.onFinset_apply, Finsupp.support_onFinset] rw [Finset.sum_filter_of_ne] intro x _ h contrapose! h simp [h] variable [Module S M] [SMulCommClass R S M] variable (S) in /-- `Finsupp.bilinearCombination R S v f` is the linear combination of vectors in `v` with weights in `f`, as a bilinear map of `v` and `f`. In the absence of `SMulCommClass R S M`, use `Finsupp.linearCombination`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ def bilinearCombination : (α → M) →ₗ[S] (α →₀ R) →ₗ[R] M where toFun v := linearCombination R v map_add' u v := by ext; simp [Pi.add_apply, smul_add] map_smul' r v := by ext; simp [smul_comm] @[simp] theorem bilinearCombination_apply : bilinearCombination R S v = linearCombination R v := rfl end LinearCombination end Finsupp section Fintype variable {α M : Type*} (R : Type*) [Fintype α] [Semiring R] [AddCommMonoid M] [Module R M] variable (S : Type*) [Semiring S] [Module S M] [SMulCommClass R S M] variable (v : α → M) /-- `Fintype.linearCombination R v f` is the linear combination of vectors in `v` with weights in `f`. This variant of `Finsupp.linearCombination` is defined on fintype indexed vectors. This map is linear in `v` if `R` is commutative, and always linear in `f`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ protected def Fintype.linearCombination : (α → R) →ₗ[R] M where toFun f := ∑ i, f i • v i map_add' f g := by simp_rw [← Finset.sum_add_distrib, ← add_smul]; rfl map_smul' r f := by simp_rw [Finset.smul_sum, smul_smul]; rfl theorem Fintype.linearCombination_apply (f) : Fintype.linearCombination R v f = ∑ i, f i • v i := rfl @[simp] theorem Fintype.linearCombination_apply_single [DecidableEq α] (i : α) (r : R) : Fintype.linearCombination R v (Pi.single i r) = r • v i := by simp_rw [Fintype.linearCombination_apply, Pi.single_apply, ite_smul, zero_smul] rw [Finset.sum_ite_eq', if_pos (Finset.mem_univ _)] theorem Finsupp.linearCombination_eq_fintype_linearCombination_apply (x : α → R) : linearCombination R v ((Finsupp.linearEquivFunOnFinite R R α).symm x) = Fintype.linearCombination R v x := by apply Finset.sum_subset · exact Finset.subset_univ _ · intro x _ hx rw [Finsupp.notMem_support_iff.mp hx] exact zero_smul _ _ theorem Finsupp.linearCombination_eq_fintype_linearCombination : (linearCombination R v).comp (Finsupp.linearEquivFunOnFinite R R α).symm.toLinearMap = Fintype.linearCombination R v := LinearMap.ext <| linearCombination_eq_fintype_linearCombination_apply R v @[simp] theorem Fintype.range_linearCombination : LinearMap.range (Fintype.linearCombination R v) = Submodule.span R (Set.range v) := by rw [← Finsupp.linearCombination_eq_fintype_linearCombination, LinearMap.range_comp, LinearEquiv.range, Submodule.map_top, Finsupp.range_linearCombination] /-- `Fintype.bilinearCombination R S v f` is the linear combination of vectors in `v` with weights in `f`. This variant of `Finsupp.linearCombination` is defined on fintype indexed vectors. This map is linear in `v` if `R` is commutative, and always linear in `f`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ protected def Fintype.bilinearCombination : (α → M) →ₗ[S] (α → R) →ₗ[R] M where toFun v := Fintype.linearCombination R v map_add' u v := by ext; simp [Fintype.linearCombination, Finset.sum_add_distrib, Pi.add_apply, smul_add] map_smul' r v := by ext; simp [Fintype.linearCombination, Finset.smul_sum, smul_comm] variable {S} @[simp] theorem Fintype.bilinearCombination_apply : Fintype.bilinearCombination R S v = Fintype.linearCombination R v := rfl theorem Fintype.bilinearCombination_apply_single [DecidableEq α] (i : α) (r : R) : Fintype.bilinearCombination R S v (Pi.single i r) = r • v i := by simp [Fintype.bilinearCombination] section SpanRange variable {v} {x : M} /-- An element `x` lies in the span of `v` iff it can be written as sum `∑ cᵢ • vᵢ = x`. -/ theorem Submodule.mem_span_range_iff_exists_fun : x ∈ span R (range v) ↔ ∃ c : α → R, ∑ i, c i • v i = x := by rw [Finsupp.equivFunOnFinite.surjective.exists] simp only [Finsupp.mem_span_range_iff_exists_finsupp, Finsupp.equivFunOnFinite_apply] exact exists_congr fun c => Eq.congr_left <| Finsupp.sum_fintype _ _ fun i => zero_smul _ _ /-- A family `v : α → V` is generating `V` iff every element `(x : V)` can be written as sum `∑ cᵢ • vᵢ = x`. -/ theorem Submodule.top_le_span_range_iff_forall_exists_fun : ⊤ ≤ span R (range v) ↔ ∀ x, ∃ c : α → R, ∑ i, c i • v i = x := by simp_rw [← mem_span_range_iff_exists_fun] exact ⟨fun h x => h trivial, fun h x _ => h x⟩ omit [Fintype α] theorem Submodule.mem_span_image_iff_exists_fun {s : Set α} : x ∈ span R (v '' s) ↔ ∃ t : Finset α, ↑t ⊆ s ∧ ∃ c : t → R, ∑ i, c i • v i = x := by refine ⟨fun h ↦ ?_, fun ⟨t, ht, c, hx⟩ ↦ ?_⟩ · obtain ⟨l, hl, hx⟩ := (Finsupp.mem_span_image_iff_linearCombination R).mp h refine ⟨l.support, hl, l ∘ (↑), ?_⟩ rw [← hx] exact l.support.sum_coe_sort fun a ↦ l a • v a · rw [← hx] exact sum_smul_mem (span R (v '' s)) c fun a _ ↦ subset_span <| by aesop theorem Fintype.mem_span_image_iff_exists_fun {s : Set α} [Fintype s] : x ∈ span R (v '' s) ↔ ∃ c : s → R, ∑ i, c i • v i = x := by rw [← mem_span_range_iff_exists_fun, image_eq_range] end SpanRange end Fintype variable {R : Type*} {M : Type*} {N : Type*} variable [Semiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] open Finsupp section variable (R) /-- Pick some representation of `x : span R w` as a linear combination in `w`, ((Finsupp.mem_span_iff_linearCombination _ _ _).mp x.2).choose -/ irreducible_def Span.repr (w : Set M) (x : span R w) : w →₀ R := ((Finsupp.mem_span_iff_linearCombination _ _ _).mp x.2).choose @[simp] theorem Span.finsupp_linearCombination_repr {w : Set M} (x : span R w) : Finsupp.linearCombination R ((↑) : w → M) (Span.repr R w x) = x := by rw [Span.repr_def] exact ((Finsupp.mem_span_iff_linearCombination _ _ _).mp x.2).choose_spec end theorem LinearMap.map_finsupp_linearCombination (f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) : f (linearCombination R g l) = linearCombination R (f ∘ g) l := apply_linearCombination _ _ _ _ lemma Submodule.mem_span_iff_exists_finset_subset {s : Set M} {x : M} : x ∈ span R s ↔ ∃ (f : M → R) (t : Finset M), ↑t ⊆ s ∧ f.support ⊆ t ∧ ∑ a ∈ t, f a • a = x where mp := by rw [← s.image_id, mem_span_image_iff_linearCombination] rintro ⟨l, hl, rfl⟩ exact ⟨l, l.support, by simpa [linearCombination, Finsupp.sum] using hl⟩ mpr := by rintro ⟨n, t, hts, -, rfl⟩; exact sum_mem fun x hx ↦ smul_mem _ _ <| subset_span <| hts hx lemma Submodule.mem_span_finset {s : Finset M} {x : M} : x ∈ span R s ↔ ∃ f : M → R, f.support ⊆ s ∧ ∑ a ∈ s, f a • a = x where mp := by rw [mem_span_iff_exists_finset_subset] rintro ⟨f, t, hts, hf, rfl⟩ refine ⟨f, hf.trans hts, .symm <| Finset.sum_subset hts ?_⟩ simp +contextual [Function.support_subset_iff'.1 hf] mpr := by rintro ⟨f, -, rfl⟩; exact sum_mem fun x hx ↦ smul_mem _ _ <| subset_span <| hx /-- A variant of `Submodule.mem_span_finset` using `s` as the index type. -/ lemma Submodule.mem_span_finset' {s : Finset M} {x : M} : x ∈ span R s ↔ ∃ f : s → R, ∑ a : s, f a • a.1 = x := by rw [← Subtype.range_val (s := s.toSet), ← Fintype.range_linearCombination] simp [Fintype.linearCombination] /-- An element `m ∈ M` is contained in the `R`-submodule spanned by a set `s ⊆ M`, if and only if `m` can be written as a finite `R`-linear combination of elements of `s`. The implementation uses `Finsupp.sum`. -/ theorem Submodule.mem_span_set {m : M} {s : Set M} : m ∈ Submodule.span R s ↔ ∃ c : M →₀ R, (c.support : Set M) ⊆ s ∧ (c.sum fun mi r => r • mi) = m := by conv_lhs => rw [← Set.image_id s] exact Finsupp.mem_span_image_iff_linearCombination R (v := _root_.id (α := M)) /-- An element `m ∈ M` is contained in the `R`-submodule spanned by a set `s ⊆ M`, if and only if `m` can be written as a finite `R`-linear combination of elements of `s`. The implementation uses a sum indexed by `Fin n` for some `n`. -/ lemma Submodule.mem_span_set' {m : M} {s : Set M} : m ∈ Submodule.span R s ↔ ∃ (n : ℕ) (f : Fin n → R) (g : Fin n → s), ∑ i, f i • (g i : M) = m := by refine ⟨fun h ↦ ?_, ?_⟩ · rcases mem_span_set.1 h with ⟨c, cs, rfl⟩ have A : c.support ≃ Fin c.support.card := Finset.equivFin _ refine ⟨_, fun i ↦ c (A.symm i), fun i ↦ ⟨A.symm i, cs (A.symm i).2⟩, ?_⟩ rw [Finsupp.sum, ← Finset.sum_coe_sort c.support] exact Fintype.sum_equiv A.symm _ (fun j ↦ c j • (j : M)) (fun i ↦ rfl) · rintro ⟨n, f, g, rfl⟩ exact Submodule.sum_mem _ (fun i _ ↦ Submodule.smul_mem _ _ (Submodule.subset_span (g i).2)) /-- The span of a subset `s` is the union over all `n` of the set of linear combinations of at most `n` terms belonging to `s`. -/ lemma Submodule.span_eq_iUnion_nat (s : Set M) : (Submodule.span R s : Set M) = ⋃ (n : ℕ), (fun (f : Fin n → (R × M)) ↦ ∑ i, (f i).1 • (f i).2) '' ({f | ∀ i, (f i).2 ∈ s}) := by ext m simp only [SetLike.mem_coe, mem_iUnion, mem_image, mem_setOf_eq, mem_span_set'] refine exists_congr (fun n ↦ ⟨?_, ?_⟩) · rintro ⟨f, g, rfl⟩ exact ⟨fun i ↦ (f i, g i), fun i ↦ (g i).2, rfl⟩ · rintro ⟨f, hf, rfl⟩ exact ⟨fun i ↦ (f i).1, fun i ↦ ⟨(f i).2, (hf i)⟩, rfl⟩ section Ring variable {R M ι : Type*} [Ring R] [AddCommGroup M] [Module R M] (i : ι) (c : ι → R) (h₀ : c i = 0) /-- Given `c : ι → R` and an index `i` such that `c i = 0`, this is the linear isomorphism sending the `j`-th standard basis vector to itself plus `c j` multiplied with the `i`-th standard basis vector (in particular, the `i`-th standard basis vector is kept invariant). -/ def Finsupp.addSingleEquiv : (ι →₀ R) ≃ₗ[R] (ι →₀ R) := by refine .ofLinear (linearCombination _ fun j ↦ single j 1 + single i (c j)) (linearCombination _ fun j ↦ single j 1 - single i (c j)) ?_ ?_ <;> ext j k <;> obtain rfl | hk := eq_or_ne i k · simp [h₀] · simp [single_eq_of_ne hk] · simp [h₀] · simp [single_eq_of_ne hk] theorem Finsupp.linearCombination_comp_addSingleEquiv (v : ι → M) : linearCombination R v ∘ₗ addSingleEquiv i c h₀ = linearCombination R (v + (c · • v i)) := by ext; simp [addSingleEquiv] end Ring
Nat.lean
/- Copyright (c) 2024 Pim Otte. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pim Otte -/ import Mathlib.Algebra.BigOperators.Group.Finset.Lemmas import Mathlib.Data.Set.Finite.Lattice import Mathlib.SetTheory.Cardinal.Finite /-! # Big operators on a finset in the natural numbers This file contains the results concerning the interaction of finset big operators with natural numbers. -/ variable {ι : Type*} namespace Finset lemma even_sum_iff_even_card_odd {s : Finset ι} (f : ι → ℕ) : Even (∑ i ∈ s, f i) ↔ Even #{x ∈ s | Odd (f x)} := by rw [← Finset.sum_filter_add_sum_filter_not _ (fun x ↦ Even (f x)), Nat.even_add] simp only [Finset.mem_filter, and_imp, imp_self, implies_true, Finset.even_sum, true_iff] rw [Nat.even_iff, Finset.sum_nat_mod, Finset.sum_filter] simp +contextual only [Nat.not_even_iff_odd, Nat.odd_iff.mp] simp_rw [← Finset.sum_filter, ← Nat.even_iff, Finset.card_eq_sum_ones] lemma odd_sum_iff_odd_card_odd {s : Finset ι} (f : ι → ℕ) : Odd (∑ i ∈ s, f i) ↔ Odd #{x ∈ s | Odd (f x)} := by simp only [← Nat.not_even_iff_odd, even_sum_iff_even_card_odd] theorem card_preimage_eq_sum_card_image_eq {M : Type*} {f : ι → M} {s : Finset M} (hb : ∀ b ∈ s, Set.Finite {a | f a = b}) : Nat.card (f⁻¹' s) = ∑ b ∈ s, Nat.card {a // f a = b} := by classical -- `t = s ∩ Set.range f` as a `Finset` let t := (Set.finite_coe_iff.mp (Finite.Set.finite_inter_of_left ↑s (Set.range f))).toFinset rw [show Nat.card (f⁻¹' s) = Nat.card (f⁻¹' t) by simp [t]] rw [show ∑ b ∈ s, Nat.card {a //f a = b} = ∑ b ∈ t, Nat.card {a | f a = b} by exact (Finset.sum_subset (by simp [t]) (by aesop)).symm] have ht : Set.Finite (f⁻¹' t) := Set.Finite.preimage' (finite_toSet t) (by aesop) rw [Nat.card_eq_card_finite_toFinset ht, Finset.card_eq_sum_card_image (f := f)] refine Finset.sum_congr ?_ fun m hm ↦ ?_ · simpa [← Finset.coe_inj, t] using Set.image_preimage_eq_inter_range · rw [Nat.card_eq_card_finite_toFinset (hb _ (by aesop))] suffices {a | f a = m} ⊆ ht.toFinset from congr_arg (Finset.card ·) (Finset.ext_iff.mpr fun a ↦ by simpa using fun h ↦ this h) intro _ h simpa using by rwa [h] end Finset
CartanMatrix.lean
/- Copyright (c) 2025 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import Mathlib.LinearAlgebra.Matrix.BilinearForm import Mathlib.LinearAlgebra.RootSystem.Base import Mathlib.LinearAlgebra.RootSystem.Finite.Lemmas import Mathlib.LinearAlgebra.RootSystem.Finite.Nondegenerate /-! # Cartan matrices for root systems This file contains definitions and basic results about Cartan matrices of root pairings / systems. ## Main definitions: * `RootPairing.Base.cartanMatrix`: the Cartan matrix of a crystallographic root pairing, with respect to a base `b`. * `RootPairing.Base.cartanMatrix_nondegenerate`: the Cartan matrix is non-degenerate. * `RootPairing.Base.induction_on_cartanMatrix`: an induction principle expressing the connectedness of the Dynkin diagram of an irreducible root pairing. -/ noncomputable section open FaithfulSMul (algebraMap_injective) open Function Set open Module.End (invtSubmodule mem_invtSubmodule) open Submodule (span subset_span) variable {ι R M N : Type*} [CommRing R] [AddCommGroup M] [Module R M] [AddCommGroup N] [Module R N] namespace RootPairing.Base variable (S : Type*) [CommRing S] [Algebra S R] {P : RootPairing ι R M N} [P.IsValuedIn S] (b : P.Base) /-- The Cartan matrix of a root pairing, taking values in `S`, with respect to a base `b`. See also `RootPairing.Base.cartanMatrix`. -/ def cartanMatrixIn : Matrix b.support b.support S := .of fun i j ↦ P.pairingIn S i j lemma cartanMatrixIn_def (i j : b.support) : b.cartanMatrixIn S i j = P.pairingIn S i j := rfl @[simp] lemma algebraMap_cartanMatrixIn_apply (i j : b.support) : algebraMap S R (b.cartanMatrixIn S i j) = P.pairing i j := by simp [cartanMatrixIn_def] @[simp] lemma cartanMatrixIn_apply_same [FaithfulSMul S R] (i : b.support) : b.cartanMatrixIn S i i = 2 := FaithfulSMul.algebraMap_injective S R <| by simp [cartanMatrixIn_def, map_ofNat] /- If we generalised the notion of `RootPairing.Base` to work relative to an assumption `[P.IsValuedIn S]` then such a base would provide basis of `P.rootSpan S` and we could avoid using `Matrix.map` below. -/ lemma cartanMatrixIn_mul_diagonal_eq {P : RootSystem ι R M N} [P.IsValuedIn S] (B : P.InvariantForm) (b : P.Base) [DecidableEq ι] : (b.cartanMatrixIn S).map (algebraMap S R) * (Matrix.diagonal fun i : b.support ↦ B.form (P.root i) (P.root i)) = (2 : R) • BilinForm.toMatrix b.toWeightBasis B.form := by ext simp [B.two_mul_apply_root_root] lemma cartanMatrixIn_nondegenerate [IsDomain R] [NeZero (2 : R)] [FaithfulSMul S R] [IsDomain S] {P : RootSystem ι R M N} [P.IsValuedIn S] [Fintype ι] [P.IsAnisotropic] (b : P.Base) : (b.cartanMatrixIn S).Nondegenerate := by classical obtain ⟨B, hB⟩ : ∃ B : P.InvariantForm, B.form.Nondegenerate := ⟨P.toInvariantForm, P.rootForm_nondegenerate⟩ replace hB : ((2 : R) • BilinForm.toMatrix b.toWeightBasis B.form).Nondegenerate := by rwa [Matrix.Nondegenerate.smul_iff two_ne_zero, LinearMap.BilinForm.nondegenerate_toMatrix_iff] have aux : (Matrix.diagonal fun i : b.support ↦ B.form (P.root i) (P.root i)).Nondegenerate := by rw [Matrix.nondegenerate_iff_det_ne_zero, Matrix.det_diagonal, Finset.prod_ne_zero_iff] aesop rw [← cartanMatrixIn_mul_diagonal_eq (S := S), Matrix.Nondegenerate.mul_iff_right aux, Matrix.nondegenerate_iff_det_ne_zero, ← (algebraMap S R).mapMatrix_apply, ← RingHom.map_det, ne_eq, FaithfulSMul.algebraMap_eq_zero_iff] at hB rwa [Matrix.nondegenerate_iff_det_ne_zero] section IsCrystallographic variable [P.IsCrystallographic] /-- The Cartan matrix of a crystallographic root pairing, with respect to a base `b`. -/ abbrev cartanMatrix : Matrix b.support b.support ℤ := b.cartanMatrixIn ℤ variable [CharZero R] lemma cartanMatrix_apply_same (i : b.support) : b.cartanMatrix i i = 2 := b.cartanMatrixIn_apply_same ℤ i lemma cartanMatrix_apply_eq_zero_iff_pairing {i j : b.support} : b.cartanMatrix i j = 0 ↔ P.pairing i j = 0 := by rw [cartanMatrix, cartanMatrixIn_def, ← (algebraMap_injective ℤ R).eq_iff, algebraMap_pairingIn, map_zero] variable [IsDomain R] lemma cartanMatrix_apply_eq_zero_iff_symm {i j : b.support} : b.cartanMatrix i j = 0 ↔ b.cartanMatrix j i = 0 := by have _i := P.reflexive_left simp only [cartanMatrix_apply_eq_zero_iff_pairing, P.pairing_eq_zero_iff] variable [Finite ι] lemma cartanMatrix_le_zero_of_ne (i j : b.support) (h : i ≠ j) : b.cartanMatrix i j ≤ 0 := b.pairingIn_le_zero_of_ne (by rwa [ne_eq, ← Subtype.ext_iff]) i.property j.property lemma cartanMatrix_mem_of_ne {i j : b.support} (hij : i ≠ j) : b.cartanMatrix i j ∈ ({-3, -2, -1, 0} : Set ℤ) := by have := P.reflexive_left have := P.reflexive_right simp only [cartanMatrix, cartanMatrixIn_def] have h₁ := P.pairingIn_pairingIn_mem_set_of_isCrystallographic i j have h₂ : P.pairingIn ℤ i j ≤ 0 := b.cartanMatrix_le_zero_of_ne i j hij suffices P.pairingIn ℤ i j ≠ -4 by aesop by_contra contra replace contra : P.pairingIn ℤ j i = -1 ∧ P.pairingIn ℤ i j = -4 := ⟨by aesop, contra⟩ rw [pairingIn_neg_one_neg_four_iff] at contra refine (not_linearIndependent_iff.mpr ?_) b.linearIndepOn_root refine ⟨⟨{i, j}, by simpa⟩, Finsupp.single i (1 : R) + Finsupp.single j (2 : R), ?_⟩ simp [contra, hij, hij.symm] lemma cartanMatrix_eq_neg_chainTopCoeff {i j : b.support} (hij : i ≠ j) : b.cartanMatrix i j = - P.chainTopCoeff j i := by rw [cartanMatrix, cartanMatrixIn_def, ← neg_eq_iff_eq_neg, ← b.chainTopCoeff_eq_of_ne hij.symm] lemma cartanMatrix_apply_eq_zero_iff {i j : b.support} (hij : i ≠ j) : b.cartanMatrix i j = 0 ↔ P.root i + P.root j ∉ range P.root := by rw [b.cartanMatrix_eq_neg_chainTopCoeff hij, neg_eq_zero, Int.natCast_eq_zero, P.chainTopCoeff_eq_zero_iff] replace hij := b.linearIndependent_pair_of_ne hij.symm tauto lemma abs_cartanMatrix_apply [DecidableEq ι] {i j : b.support} : |b.cartanMatrix i j| = (if i = j then 4 else 0) - b.cartanMatrix i j := by rcases eq_or_ne i j with rfl | h · simp · simpa [h] using b.cartanMatrix_le_zero_of_ne i j h @[simp] lemma cartanMatrix_map_abs [DecidableEq ι] : b.cartanMatrix.map abs = 4 - b.cartanMatrix := by ext; simp [abs_cartanMatrix_apply, Matrix.ofNat_apply] lemma cartanMatrix_nondegenerate {P : RootSystem ι R M N} [P.IsCrystallographic] (b : P.Base) : b.cartanMatrix.Nondegenerate := let _i : Fintype ι := Fintype.ofFinite ι cartanMatrixIn_nondegenerate ℤ b /-- A characterisation of the connectedness of the Dynkin diagram for irreducible root pairings. -/ lemma induction_on_cartanMatrix [P.IsReduced] [P.IsIrreducible] (p : b.support → Prop) {i j : b.support} (hi : p i) (hp : ∀ i j, p i → b.cartanMatrix j i ≠ 0 → p j) : p j := by have _i : Nontrivial M := ⟨P.root i, 0, P.ne_zero i⟩ let q : Submodule R M := span R (P.root ∘ (↑) '' {i | p i}) have hq₀ : q ≠ ⊥ := q.ne_bot_iff.mpr ⟨P.root i, subset_span <| by simpa, P.ne_zero i⟩ have hq_mem (k : b.support) : P.root k ∈ q ↔ p k := by refine ⟨fun hk ↦ ?_, fun hk ↦ subset_span <| by simpa⟩ contrapose! hk exact b.linearIndepOn_root.linearIndependent.notMem_span_image hk have hq_notMem (k : b.support) (hk : P.root k ∉ q) : q ≤ LinearMap.ker (P.coroot' k) := by refine fun x hx ↦ LinearMap.mem_ker.mpr ?_ contrapose! hk rw [hq_mem] induction hx using Submodule.span_induction with | mem x hx => obtain ⟨l, hl, rfl⟩ : ∃ l : b.support, p l ∧ P.root l = x := by aesop replace hk : b.cartanMatrix k l ≠ 0 := by rwa [ne_eq, cartanMatrix_apply_eq_zero_iff_symm, cartanMatrix_apply_eq_zero_iff_pairing] tauto | zero => aesop | add x y hx hy hx' hy' => replace hk : P.coroot' k x ≠ 0 ∨ P.coroot' k y ≠ 0 := by by_contra! contra; aesop tauto | smul a x hx hx' => aesop have hq : ∀ k, q ∈ invtSubmodule (P.reflection k) := by rw [← b.forall_mem_support_invtSubmodule_iff] refine fun k hkb ↦ (mem_invtSubmodule _).mpr fun x hx ↦ ?_ rw [Submodule.mem_comap, LinearEquiv.coe_coe, reflection_apply] apply q.sub_mem hx by_cases hk : P.root k ∈ q · exact q.smul_mem _ hk · replace hk : P.coroot' k x = 0 := hq_notMem ⟨k, hkb⟩ hk hx simp [hk] simp [← hq_mem, IsIrreducible.eq_top_of_invtSubmodule_reflection q hq hq₀] open scoped Matrix in lemma injective_pairingIn {P : RootSystem ι R M N} [P.IsCrystallographic] (b : P.Base) : Injective (fun i (k : b.support) ↦ P.pairingIn ℤ i k) := by classical intro i j hij obtain ⟨f, -, -, hf⟩ := b.exists_root_eq_sum_int i obtain ⟨g, -, -, hg⟩ := b.exists_root_eq_sum_int j let f' : b.support → ℤ := f ∘ (↑) let g' : b.support → ℤ := g ∘ (↑) suffices f' = g' by rw [← P.root.apply_eq_iff_eq, hf, hg] refine Finset.sum_congr rfl fun k hk ↦ ?_ replace this : f k = g k := congr_fun this ⟨k, hk⟩ rw [this] replace hf : (fun k : b.support ↦ P.pairingIn ℤ i k) = f' ᵥ* b.cartanMatrix := by suffices ∀ k, P.pairingIn ℤ i k = ∑ l ∈ b.support, f l * P.pairingIn ℤ l k by ext; simp [f', this, cartanMatrixIn, Matrix.vecMul_eq_sum, b.support.sum_subtype (by tauto)] refine fun k ↦ algebraMap_injective ℤ R ?_ simp_rw [algebraMap_pairingIn, map_sum, map_mul, algebraMap_pairingIn, ← P.root_coroot'_eq_pairing] simp [hf] replace hg : (fun k : b.support ↦ P.pairingIn ℤ j k) = g' ᵥ* b.cartanMatrix := by suffices ∀ k, P.pairingIn ℤ j k = ∑ l ∈ b.support, g l * P.pairingIn ℤ l k by ext; simp [g', this, cartanMatrixIn, Matrix.vecMul_eq_sum, b.support.sum_subtype (by tauto)] refine fun k ↦ algebraMap_injective ℤ R ?_ simp_rw [algebraMap_pairingIn, map_sum, map_mul, algebraMap_pairingIn, ← P.root_coroot'_eq_pairing] simp [hg] suffices Injective fun v ↦ v ᵥ* b.cartanMatrix from this <| by simpa [← hf, ← hg] rw [Matrix.vecMul_injective_iff] apply Matrix.linearIndependent_rows_of_det_ne_zero rw [← Matrix.nondegenerate_iff_det_ne_zero] exact b.cartanMatrix_nondegenerate end IsCrystallographic end RootPairing.Base
Count.lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.MeasureTheory.Measure.Dirac import Mathlib.Topology.Algebra.InfiniteSum.ENNReal /-! # Counting measure In this file we define the counting measure `MeasurTheory.Measure.count` as `MeasureTheory.Measure.sum MeasureTheory.Measure.dirac` and prove basic properties of this measure. -/ open Set open scoped ENNReal Finset variable {α β : Type*} [MeasurableSpace α] [MeasurableSpace β] {s : Set α} noncomputable section namespace MeasureTheory.Measure /-- Counting measure on any measurable space. -/ def count : Measure α := sum dirac @[simp] lemma count_ne_zero'' [Nonempty α] : (count : Measure α) ≠ 0 := by simp [count] theorem le_count_apply : ∑' _ : s, (1 : ℝ≥0∞) ≤ count s := calc (∑' _ : s, 1 : ℝ≥0∞) = ∑' i, indicator s 1 i := tsum_subtype s 1 _ ≤ ∑' i, dirac i s := ENNReal.tsum_le_tsum fun _ => le_dirac_apply _ ≤ count s := le_sum_apply _ _ theorem count_apply (hs : MeasurableSet s) : count s = s.encard := by simp [count, hs, ← tsum_subtype, Set.encard] @[deprecated measure_empty (since := "2025-02-06")] theorem count_empty : count (∅ : Set α) = 0 := measure_empty @[simp] theorem count_apply_finset' {s : Finset α} (hs : MeasurableSet (s : Set α)) : count (↑s : Set α) = #s := by simp [count_apply hs] @[simp] theorem count_apply_finset [MeasurableSingletonClass α] (s : Finset α) : count (↑s : Set α) = #s := count_apply_finset' s.measurableSet theorem count_apply_finite' {s : Set α} (s_fin : s.Finite) (s_mble : MeasurableSet s) : count s = #s_fin.toFinset := by simp [← @count_apply_finset' _ _ s_fin.toFinset (by simpa only [Finite.coe_toFinset] using s_mble)] theorem count_apply_finite [MeasurableSingletonClass α] (s : Set α) (hs : s.Finite) : count s = #hs.toFinset := by rw [← count_apply_finset, Finite.coe_toFinset] /-- `count` measure evaluates to infinity at infinite sets. -/ theorem count_apply_infinite (hs : s.Infinite) : count s = ∞ := by refine top_unique (le_of_tendsto' ENNReal.tendsto_nat_nhds_top fun n => ?_) rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩ calc (#t : ℝ≥0∞) = ∑ i ∈ t, 1 := by simp _ = ∑' i : (t : Set α), 1 := (t.tsum_subtype 1).symm _ ≤ count (t : Set α) := le_count_apply _ ≤ count s := measure_mono ht @[simp] theorem count_apply_eq_top' (s_mble : MeasurableSet s) : count s = ∞ ↔ s.Infinite := by by_cases hs : s.Finite · simp [Set.Infinite, hs, count_apply_finite' hs s_mble] · change s.Infinite at hs simp [hs, count_apply_infinite] @[simp] theorem count_apply_eq_top [MeasurableSingletonClass α] : count s = ∞ ↔ s.Infinite := by by_cases hs : s.Finite · exact count_apply_eq_top' hs.measurableSet · change s.Infinite at hs simp [hs, count_apply_infinite] @[simp] theorem count_apply_lt_top' (s_mble : MeasurableSet s) : count s < ∞ ↔ s.Finite := calc count s < ∞ ↔ count s ≠ ∞ := lt_top_iff_ne_top _ ↔ ¬s.Infinite := not_congr (count_apply_eq_top' s_mble) _ ↔ s.Finite := Classical.not_not @[simp] theorem count_apply_lt_top [MeasurableSingletonClass α] : count s < ∞ ↔ s.Finite := calc count s < ∞ ↔ count s ≠ ∞ := lt_top_iff_ne_top _ ↔ ¬s.Infinite := not_congr count_apply_eq_top _ ↔ s.Finite := Classical.not_not @[simp] theorem count_eq_zero_iff : count s = 0 ↔ s = ∅ where mp h := eq_empty_of_forall_notMem fun x hx ↦ by simpa [hx] using ((ENNReal.le_tsum x).trans <| le_sum_apply _ _).trans_eq h mpr := by rintro rfl; exact measure_empty lemma count_ne_zero_iff : count s ≠ 0 ↔ s.Nonempty := count_eq_zero_iff.not.trans nonempty_iff_ne_empty.symm alias ⟨_, count_ne_zero⟩ := count_ne_zero_iff @[simp] lemma ae_count_iff {p : α → Prop} : (∀ᵐ x ∂count, p x) ↔ ∀ x, p x := by refine ⟨fun h x ↦ ?_, ae_of_all _⟩ rw [ae_iff, count_eq_zero_iff] at h by_contra hx rwa [← mem_empty_iff_false x, ← h] @[simp] theorem count_singleton' {a : α} (ha : MeasurableSet ({a} : Set α)) : count ({a} : Set α) = 1 := by rw [count_apply_finite' (Set.finite_singleton a) ha, Set.Finite.toFinset] simp [ ] theorem count_singleton [MeasurableSingletonClass α] (a : α) : count ({a} : Set α) = 1 := count_singleton' (measurableSet_singleton a) @[simp] theorem _root_.MeasureTheory.count_real_singleton' {a : α} (ha : MeasurableSet ({a} : Set α)) : count.real ({a} : Set α) = 1 := by rw [measureReal_def, count_singleton' ha, ENNReal.toReal_one] theorem _root_.MeasureTheory.count_real_singleton [MeasurableSingletonClass α] (a : α) : count.real ({a} : Set α) = 1 := count_real_singleton' (measurableSet_singleton a) theorem count_injective_image' {f : β → α} (hf : Function.Injective f) {s : Set β} (s_mble : MeasurableSet s) (fs_mble : MeasurableSet (f '' s)) : count (f '' s) = count s := by classical by_cases hs : s.Finite · lift s to Finset β using hs rw [← Finset.coe_image, count_apply_finset' _, count_apply_finset' s_mble, s.card_image_of_injective hf] simpa only [Finset.coe_image] using fs_mble · rw [count_apply_infinite hs] rw [← finite_image_iff hf.injOn] at hs rw [count_apply_infinite hs] theorem count_injective_image [MeasurableSingletonClass α] [MeasurableSingletonClass β] {f : β → α} (hf : Function.Injective f) (s : Set β) : count (f '' s) = count s := by by_cases hs : s.Finite · exact count_injective_image' hf hs.measurableSet (Finite.image f hs).measurableSet rw [count_apply_infinite hs] rw [← finite_image_iff hf.injOn] at hs rw [count_apply_infinite hs] instance count.instSigmaFinite [MeasurableSingletonClass α] [Countable α] : SigmaFinite (count : Measure α) := by simp [sigmaFinite_iff_measure_singleton_lt_top] instance count.isFiniteMeasure [Finite α] : IsFiniteMeasure (Measure.count : Measure α) := ⟨by cases nonempty_fintype α; simp [Measure.count_apply, finite_univ]⟩ @[simp] lemma count_univ : count (univ : Set α) = ENat.card α := by simp [count_apply .univ, encard_univ] end Measure end MeasureTheory
Basic.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Algebra.GroupWithZero.Associated import Mathlib.Algebra.Ring.Parity import Mathlib.Data.Nat.Prime.Defs /-! # Prime numbers This file develops the theory of prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. -/ namespace Nat variable {n : ℕ} theorem prime_mul_iff {a b : ℕ} : Nat.Prime (a * b) ↔ a.Prime ∧ b = 1 ∨ b.Prime ∧ a = 1 := by simp only [irreducible_mul_iff, ← irreducible_iff_nat_prime, Nat.isUnit_iff] theorem not_prime_mul {a b : ℕ} (a1 : a ≠ 1) (b1 : b ≠ 1) : ¬Prime (a * b) := by simp [prime_mul_iff, *] theorem not_prime_of_mul_eq {a b n : ℕ} (h : a * b = n) (h₁ : a ≠ 1) (h₂ : b ≠ 1) : ¬Prime n := h ▸ not_prime_mul h₁ h₂ @[deprecated (since := "2025-05-24")] alias not_prime_mul' := not_prime_of_mul_eq theorem Prime.dvd_iff_eq {p a : ℕ} (hp : p.Prime) (a1 : a ≠ 1) : a ∣ p ↔ p = a := by refine ⟨?_, by rintro rfl; rfl⟩ rintro ⟨j, rfl⟩ rcases prime_mul_iff.mp hp with (⟨_, rfl⟩ | ⟨_, rfl⟩) · exact mul_one _ · exact (a1 rfl).elim theorem Prime.eq_two_or_odd {p : ℕ} (hp : Prime p) : p = 2 ∨ p % 2 = 1 := p.mod_two_eq_zero_or_one.imp_left fun h => ((hp.eq_one_or_self_of_dvd 2 (dvd_of_mod_eq_zero h)).resolve_left (by decide)).symm theorem Prime.eq_two_or_odd' {p : ℕ} (hp : Prime p) : p = 2 ∨ Odd p := Or.imp_right (fun h => ⟨p / 2, (div_add_mod p 2).symm.trans (congr_arg _ h)⟩) hp.eq_two_or_odd section theorem Prime.five_le_of_ne_two_of_ne_three {p : ℕ} (hp : p.Prime) (h_two : p ≠ 2) (h_three : p ≠ 3) : 5 ≤ p := by by_contra! h revert h_two h_three hp decide +revert end theorem Prime.pred_pos {p : ℕ} (pp : Prime p) : 0 < pred p := lt_pred_iff.2 pp.one_lt theorem succ_pred_prime {p : ℕ} (pp : Prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem exists_dvd_of_not_prime {n : ℕ} (n2 : 2 ≤ n) (np : ¬Prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨minFac n, minFac_dvd _, ne_of_gt (minFac_prime (ne_of_gt n2)).one_lt, ne_of_lt <| (not_prime_iff_minFac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : 2 ≤ n) (np : ¬Prime n) : ∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n := ⟨minFac n, minFac_dvd _, (minFac_prime (ne_of_gt n2)).two_le, (not_prime_iff_minFac_lt n2).1 np⟩ theorem not_prime_of_dvd_of_ne {m n : ℕ} (h1 : m ∣ n) (h2 : m ≠ 1) (h3 : m ≠ n) : ¬Prime n := fun h => Or.elim (h.eq_one_or_self_of_dvd m h1) h2 h3 theorem not_prime_of_dvd_of_lt {m n : ℕ} (h1 : m ∣ n) (h2 : 2 ≤ m) (h3 : m < n) : ¬Prime n := not_prime_of_dvd_of_ne h1 (ne_of_gt h2) (ne_of_lt h3) theorem not_prime_iff_exists_dvd_ne {n : ℕ} (h : 2 ≤ n) : (¬Prime n) ↔ ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨exists_dvd_of_not_prime h, fun ⟨_, h1, h2, h3⟩ => not_prime_of_dvd_of_ne h1 h2 h3⟩ theorem not_prime_iff_exists_dvd_lt {n : ℕ} (h : 2 ≤ n) : (¬Prime n) ↔ ∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n := ⟨exists_dvd_of_not_prime2 h, fun ⟨_, h1, h2, h3⟩ => not_prime_of_dvd_of_lt h1 h2 h3⟩ theorem not_prime_iff_exists_mul_eq {n : ℕ} (h : 2 ≤ n) : (¬Prime n) ↔ ∃ a b, a < n ∧ b < n ∧ a * b = n := by rw [prime_iff_not_exists_mul_eq, and_iff_right h, Classical.not_not] theorem dvd_of_forall_prime_mul_dvd {a b : ℕ} (hdvd : ∀ p : ℕ, p.Prime → p ∣ a → p * a ∣ b) : a ∣ b := by obtain rfl | ha := eq_or_ne a 1 · apply one_dvd obtain ⟨p, hp⟩ := exists_prime_and_dvd ha exact _root_.trans (dvd_mul_left a p) (hdvd p hp.1 hp.2) theorem Prime.even_iff {p : ℕ} (hp : Prime p) : Even p ↔ p = 2 := by rw [even_iff_two_dvd, prime_dvd_prime_iff_eq prime_two hp, eq_comm] theorem Prime.odd_of_ne_two {p : ℕ} (hp : p.Prime) (h_two : p ≠ 2) : Odd p := hp.eq_two_or_odd'.resolve_left h_two theorem Prime.even_sub_one {p : ℕ} (hp : p.Prime) (h2 : p ≠ 2) : Even (p - 1) := let ⟨n, hn⟩ := hp.odd_of_ne_two h2; ⟨n, by rw [hn, Nat.add_sub_cancel, two_mul]⟩ /-- A prime `p` satisfies `p % 2 = 1` if and only if `p ≠ 2`. -/ theorem Prime.mod_two_eq_one_iff_ne_two {p : ℕ} [Fact p.Prime] : p % 2 = 1 ↔ p ≠ 2 := by refine ⟨fun h hf => ?_, (Nat.Prime.eq_two_or_odd <| @Fact.out p.Prime _).resolve_left⟩ rw [hf] at h simp at h theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, Prime k → k ∣ m → k ∣ n → k ∣ 1) : Coprime m n := coprime_of_dvd fun k kp km kn => not_le_of_gt kp.one_lt <| le_of_dvd Nat.one_pos <| H k kp km kn theorem Prime.dvd_iff_not_coprime {p n : ℕ} (pp : Prime p) : p ∣ n ↔ ¬Coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem Prime.not_coprime_iff_dvd {m n : ℕ} : ¬Coprime m n ↔ ∃ p, Prime p ∧ p ∣ m ∧ p ∣ n := by apply Iff.intro · intro h exact ⟨minFac (gcd m n), minFac_prime h, (minFac_dvd (gcd m n)).trans (gcd_dvd_left m n), (minFac_dvd (gcd m n)).trans (gcd_dvd_right m n)⟩ · intro h obtain ⟨p, hp⟩ := h apply Nat.not_coprime_of_dvd_of_dvd (Prime.one_lt hp.1) hp.2.1 hp.2.2 /-- If `0 < m < minFac n`, then `n` and `m` are coprime. -/ lemma coprime_of_lt_minFac {n m : ℕ} (h₀ : m ≠ 0) (h : m < minFac n) : Coprime n m := by rw [← not_not (a := n.Coprime m), Prime.not_coprime_iff_dvd] push_neg exact fun p hp hn hm ↦ ((le_of_dvd (by omega) hm).trans_lt <| h.trans_le <| minFac_le_of_dvd hp.two_le hn).false /-- If `0 < m < minFac n`, then `n` and `m` have gcd equal to `1`. -/ lemma gcd_eq_one_of_lt_minFac {n m : ℕ} (h₀ : m ≠ 0) (h : m < minFac n) : n.gcd m = 1 := coprime_iff_gcd_eq_one.mp <| coprime_of_lt_minFac h₀ h theorem Prime.not_dvd_mul {p m n : ℕ} (pp : Prime p) (Hm : ¬p ∣ m) (Hn : ¬p ∣ n) : ¬p ∣ m * n := mt pp.dvd_mul.1 <| by simp [Hm, Hn] @[simp] lemma coprime_two_left : Coprime 2 n ↔ Odd n := by rw [prime_two.coprime_iff_not_dvd, ← not_even_iff_odd, even_iff_two_dvd] @[simp] lemma coprime_two_right : n.Coprime 2 ↔ Odd n := coprime_comm.trans coprime_two_left protected alias ⟨Coprime.odd_of_left, _root_.Odd.coprime_two_left⟩ := coprime_two_left protected alias ⟨Coprime.odd_of_right, _root_.Odd.coprime_two_right⟩ := coprime_two_right theorem Prime.dvd_of_dvd_pow {p m n : ℕ} (pp : Prime p) (h : p ∣ m ^ n) : p ∣ m := pp.prime.dvd_of_dvd_pow h theorem Prime.not_prime_pow' {x n : ℕ} (hn : n ≠ 1) : ¬(x ^ n).Prime := not_irreducible_pow hn theorem Prime.not_prime_pow {x n : ℕ} (hn : 2 ≤ n) : ¬(x ^ n).Prime := not_prime_pow' ((two_le_iff _).mp hn).2 theorem Prime.eq_one_of_pow {x n : ℕ} (h : (x ^ n).Prime) : n = 1 := not_imp_not.mp Prime.not_prime_pow' h theorem Prime.pow_eq_iff {p a k : ℕ} (hp : p.Prime) : a ^ k = p ↔ a = p ∧ k = 1 := by refine ⟨fun h => ?_, fun h => by rw [h.1, h.2, pow_one]⟩ rw [← h] at hp rw [← h, hp.eq_one_of_pow, eq_self_iff_true, _root_.and_true, pow_one] theorem Prime.mul_eq_prime_sq_iff {x y p : ℕ} (hp : p.Prime) (hx : x ≠ 1) (hy : y ≠ 1) : x * y = p ^ 2 ↔ x = p ∧ y = p := by refine ⟨fun h => ?_, fun ⟨h₁, h₂⟩ => h₁.symm ▸ h₂.symm ▸ (sq _).symm⟩ have pdvdxy : p ∣ x * y := by rw [h]; simp [sq] -- Could be `wlog := hp.dvd_mul.1 pdvdxy using x y`, but that imports more than we want. suffices ∀ x' y' : ℕ, x' ≠ 1 → y' ≠ 1 → x' * y' = p ^ 2 → p ∣ x' → x' = p ∧ y' = p by obtain hx | hy := hp.dvd_mul.1 pdvdxy <;> [skip; rw [And.comm]] <;> [skip; rw [mul_comm] at h pdvdxy] <;> apply this <;> assumption rintro x y hx hy h ⟨a, ha⟩ have : a ∣ p := ⟨y, by rwa [ha, sq, mul_assoc, mul_right_inj' hp.ne_zero, eq_comm] at h⟩ obtain ha1 | hap := (Nat.dvd_prime hp).mp ‹a ∣ p› · subst ha1 rw [mul_one] at ha subst ha simp only [sq, mul_right_inj' hp.ne_zero] at h subst h exact ⟨rfl, rfl⟩ · refine (hy ?_).elim subst hap subst ha rw [sq, Nat.mul_eq_left (Nat.mul_ne_zero hp.ne_zero hp.ne_zero)] at h exact h theorem Prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : Prime p) (h : ¬p ∣ a) : Coprime a (p ^ m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : Prime p) (pq : Prime q) : Coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans <| not_congr <| dvd_prime_two_le pq pp.two_le theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : Prime p) (pq : Prime q) (h : p ≠ q) : Coprime (p ^ n) (q ^ m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : Prime p) (i : ℕ) : Coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem coprime_of_lt_prime {n p} (n_pos : 0 < n) (hlt : n < p) (pp : Prime p) : Coprime p n := (coprime_or_dvd_of_prime pp n).resolve_right fun h => Nat.lt_le_asymm hlt (le_of_dvd n_pos h) theorem eq_or_coprime_of_le_prime {n p} (n_pos : 0 < n) (hle : n ≤ p) (pp : Prime p) : p = n ∨ Coprime p n := hle.eq_or_lt.imp Eq.symm fun h => coprime_of_lt_prime n_pos h pp theorem prime_eq_prime_of_dvd_pow {m p q} (pp : Prime p) (pq : Prime q) (h : p ∣ q ^ m) : p = q := (prime_dvd_prime_iff_eq pp pq).mp (pp.dvd_of_dvd_pow h) theorem dvd_prime_pow {p : ℕ} (pp : Prime p) {m i : ℕ} : i ∣ p ^ m ↔ ∃ k ≤ m, i = p ^ k := by simp_rw [_root_.dvd_prime_pow (prime_iff.mp pp) m, associated_eq_eq] theorem Prime.dvd_mul_of_dvd_ne {p1 p2 n : ℕ} (h_neq : p1 ≠ p2) (pp1 : Prime p1) (pp2 : Prime p2) (h1 : p1 ∣ n) (h2 : p2 ∣ n) : p1 * p2 ∣ n := Coprime.mul_dvd_of_dvd_of_dvd ((coprime_primes pp1 pp2).mpr h_neq) h1 h2 /-- If `p` is prime, and `a` doesn't divide `p^k`, but `a` does divide `p^(k+1)` then `a = p^(k+1)`. -/ theorem eq_prime_pow_of_dvd_least_prime_pow {a p k : ℕ} (pp : Prime p) (h₁ : ¬a ∣ p ^ k) (h₂ : a ∣ p ^ (k + 1)) : a = p ^ (k + 1) := by obtain ⟨l, ⟨h, rfl⟩⟩ := (dvd_prime_pow pp).1 h₂ congr exact le_antisymm h (not_le.1 ((not_congr (pow_dvd_pow_iff_le_right (Prime.one_lt pp))).1 h₁)) theorem ne_one_iff_exists_prime_dvd : ∀ {n}, n ≠ 1 ↔ ∃ p : ℕ, p.Prime ∧ p ∣ n | 0 => by simpa using Exists.intro 2 Nat.prime_two | 1 => by simp [Nat.not_prime_one] | n + 2 => by let a := n + 2 have ha : a ≠ 1 := Nat.succ_succ_ne_one n simp only [a, true_iff, Ne, not_false_iff, ha] exact ⟨a.minFac, Nat.minFac_prime ha, a.minFac_dvd⟩ theorem eq_one_iff_not_exists_prime_dvd {n : ℕ} : n = 1 ↔ ∀ p : ℕ, p.Prime → ¬p ∣ n := by simpa using not_iff_not.mpr ne_one_iff_exists_prime_dvd theorem succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : Prime p) {m n k l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k + l + 1) ∣ m * n) : p ^ (k + 1) ∣ m ∨ p ^ (l + 1) ∣ n := by have hpd : p ^ (k + l) * p ∣ m * n := by let hpmn' : p ^ (succ (k + l)) ∣ m * n := hpmn rwa [pow_succ'] at hpmn' have hpd2 : p ∣ m * n / p ^ (k + l) := dvd_div_of_mul_dvd hpd have hpd3 : p ∣ m * n / (p ^ k * p ^ l) := by simpa [pow_add] using hpd2 have hpd4 : p ∣ m / p ^ k * (n / p ^ l) := by simpa [Nat.div_mul_div_comm hpm hpn] using hpd3 have hpd5 : p ∣ m / p ^ k ∨ p ∣ n / p ^ l := (Prime.dvd_mul p_prime).1 hpd4 suffices p ^ k * p ∣ m ∨ p ^ l * p ∣ n by rwa [_root_.pow_succ, _root_.pow_succ] exact hpd5.elim (fun h : p ∣ m / p ^ k => Or.inl <| mul_dvd_of_dvd_div hpm h) fun h : p ∣ n / p ^ l => Or.inr <| mul_dvd_of_dvd_div hpn h end Nat
finfield.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import fintype div tuple bigop prime finset fingroup. From mathcomp Require Import ssralg poly polydiv morphism action countalg. From mathcomp Require Import finalg zmodp cyclic center pgroup abelian matrix. From mathcomp Require Import mxpoly vector falgebra fieldext separable galois. From mathcomp Require ssrnum ssrint archimedean algC cyclotomic. (******************************************************************************) (* Additional constructions and results on finite fields *) (* *) (* FinFieldExtType L == a FinFieldType structure on the carrier of L, *) (* where L IS a fieldExtType F structure for an *) (* F that has a finFieldType structure. This *) (* does not take any existing finType structure *) (* on L; this should not be made canonical *) (* FinSplittingFieldType F L == a SplittingFieldType F structure on the *) (* carrier of L, where L IS a fieldExtType F for *) (* an F with a finFieldType structure; this *) (* should not be made canonical *) (* finvect_type vT == alias of vT : vecType R equipped with *) (* canonical instances for finType, finNzRing, *) (* etc structures (including FinFieldExtType *) (* above) for abstract vectType, falgType and *) (* fieldExtType over a finFieldType *) (* pPrimeCharType pcharRp == the carrier of a nzRingType R such that *) (* pcharRp : p \in [pchar R] holds. This type has*) (* canonical nzRingType, ..., fieldType *) (* structures compatible with those of R, as well*) (* as canonical lmodType 'F_p, ..., algType 'F_p *) (* structures, plus an falgType structure if R *) (* is a finUnitRingType and a splittingFieldType *) (* structure if R is a finFieldType *) (* FinSplittingFieldFor nz_p == sigma-pair whose sval is a splittingFieldType *) (* that is the splitting field for p : {poly F} *) (* over F : finFieldType, given nz_p : p != 0 *) (* PrimePowerField pr_p k_gt0 == sigma2-triple whose s2val is a finFieldType *) (* of characteristic p and order m = p ^ k, *) (* given pr_p : prime p and k_gt0 : k > 0 *) (* FinDomainFieldType domR == a finFieldType structure on a finUnitRingType *) (* R, given domR : GRing.IntegralDomain.axiom R. *) (* This is intended to be used inside proofs, *) (* where one cannot declare Canonical instances *) (* Otherwise one should construct explicitly the *) (* intermediate structures using the ssralg and *) (* finalg constructors, and finDomain_mulrC domR *) (* finDomain_fieldP domR to prove commutativity *) (* and field axioms (the former is Wedderburn's *) (* little theorem). *) (* FinDomainSplittingFieldType domR pcharRp == a splittingFieldType structure *) (* that repackages the two constructions above *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope GRing.Theory FinRing.Theory. Local Open Scope ring_scope. Section FinNzRing. Variable R : finNzRingType. Lemma finNzRing_nontrivial : [set: R] != 1%g. Proof. by apply/trivgPn; exists 1; rewrite ?inE ?oner_neq0. Qed. Lemma finNzRing_gt1 : 1 < #|R|. Proof. by rewrite -cardsT cardG_gt1 finNzRing_nontrivial. Qed. End FinNzRing. #[deprecated(since="mathcomp 2.4.0", note="Use finNzRing_nontrivial instead.")] Notation finRing_nontrivial := (finNzRing_nontrivial) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use finNzRing_gt1 instead.")] Notation finRing_gt1 := (finNzRing_gt1) (only parsing). Section FinField. Variable F : finFieldType. Lemma card_finField_unit : #|[set: {unit F}]| = #|F|.-1. Proof. by rewrite -(cardC1 0) cardsT card_sub; apply: eq_card => x; rewrite unitfE. Qed. Definition finField_unit x (nz_x : x != 0) := FinRing.unit F (etrans (unitfE x) nz_x). Lemma expf_card x : x ^+ #|F| = x :> F. Proof. rewrite -[RHS]mulr1 -(ltn_predK (finNzRing_gt1 F)) exprS. apply/eqP; rewrite -subr_eq0 -mulrBr mulf_eq0 subr_eq0 -implyNb -unitfE. apply/implyP=> Ux; rewrite -(val_unitX _ (Sub x _)) -val_unit1 val_eqE. by rewrite -order_dvdn -card_finField_unit order_dvdG ?inE. Qed. Lemma finField_genPoly : 'X^#|F| - 'X = \prod_x ('X - x%:P) :> {poly F}. Proof. set n := #|F|; set oppX := - 'X; set pF := LHS. have le_oppX_n: size oppX <= n by rewrite size_polyN size_polyX finNzRing_gt1. have: size pF = (size (enum F)).+1 by rewrite -cardE size_polyDl size_polyXn. move/all_roots_prod_XsubC->; last by rewrite uniq_rootsE enum_uniq. by rewrite big_enum lead_coefDl ?size_polyXn // lead_coefXn scale1r. by apply/allP=> x _; rewrite rootE !hornerE expf_card subrr. Qed. Lemma finPcharP : {p | prime p & p \in [pchar F]}. Proof. pose e := exponent [set: F]; have e_gt0: e > 0 by apply: exponent_gt0. have: e%:R == 0 :> F by rewrite -zmodXgE expg_exponent // inE. by case/natf0_pchar/sigW=> // p pcharFp; exists p; rewrite ?(pcharf_prime pcharFp). Qed. Lemma finField_is_abelem : is_abelem [set: F]. Proof. have [p pr_p pcharFp] := finPcharP. by apply/is_abelemP; exists p; last apply: fin_ring_pchar_abelem. Qed. Lemma card_finPcharP p n : #|F| = (p ^ n)%N -> prime p -> p \in [pchar F]. Proof. move=> oF pr_p; rewrite inE pr_p -order_dvdn. rewrite (abelem_order_p finField_is_abelem) ?inE ?oner_neq0 //=. have n_gt0: n > 0 by rewrite -(ltn_exp2l _ _ (prime_gt1 pr_p)) -oF finNzRing_gt1. by rewrite cardsT oF -(prednK n_gt0) pdiv_pfactor. Qed. End FinField. #[deprecated(since="mathcomp 2.4.0", note="Use finPcharP instead.")] Notation finCharP := (finPcharP) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use card_finPcharP instead.")] Notation card_finCharP := (card_finPcharP) (only parsing). Section CardVspace. Variables (F : finFieldType) (T : finType). Section Vector. Variable cvT : Vector F T. Let vT := Vector.Pack cvT. Lemma card_vspace (V : {vspace vT}) : #|V| = (#|F| ^ \dim V)%N. Proof. set n := \dim V; pose V2rV v := \row_i coord (vbasis V) i v. pose rV2V (rv : 'rV_n) := \sum_i rv 0 i *: (vbasis V)`_i. have rV2V_K: cancel rV2V V2rV. have freeV: free (vbasis V) := basis_free (vbasisP V). by move=> rv; apply/rowP=> i; rewrite mxE coord_sum_free. rewrite -[n]mul1n -card_mx -(card_imset _ (can_inj rV2V_K)). apply: eq_card => v; apply/idP/imsetP=> [/coord_vbasis-> | [rv _ ->]]. by exists (V2rV v) => //; apply: eq_bigr => i _; rewrite mxE. by apply: (@rpred_sum vT) => i _; rewrite rpredZ ?vbasis_mem ?memt_nth. Qed. Lemma card_vspacef : #|{: vT}%VS| = #|T|. Proof. by apply: eq_card => v; rewrite (@memvf _ vT). Qed. End Vector. Variable caT : Falgebra F T. Let aT := Falgebra.Pack caT. Lemma card_vspace1 : #|(1%VS : {vspace aT})| = #|F|. Proof. by rewrite card_vspace (dimv1 aT). Qed. End CardVspace. Definition finvect_type (vT : Type) : predArgType := vT. Section FinVector. Variables (R : finNzRingType) (vT : vectType R). Local Notation fvT := (finvect_type vT). HB.instance Definition _ := Vector.on fvT. HB.instance Definition _ := isCountable.Build fvT (pcan_pickleK (can_pcan VectorInternalTheory.v2rK)). HB.instance Definition _ := isFinite.Build fvT (pcan_enumP (can_pcan (VectorInternalTheory.v2rK : @cancel _ fvT _ _))). End FinVector. HB.instance Definition _ (F : finFieldType) (aT : falgType F) := Falgebra.on (finvect_type aT). Section FinFieldExt. Variables (F : finFieldType) (fT : fieldExtType F). Local Notation ffT := (finvect_type fT). HB.instance Definition _ := FieldExt.on ffT. Lemma ffT_splitting_subproof : SplittingField.axiom ffT. Proof. exists ('X^#|ffT| - 'X). by rewrite (@rpredB {poly fT}) 1?rpredX ?polyOverX. exists (enum ffT); first by rewrite big_enum finField_genPoly eqpxx. by apply/vspaceP=> x; rewrite memvf seqv_sub_adjoin ?mem_enum. Qed. HB.instance Definition _ := FieldExt_isSplittingField.Build F ffT ffT_splitting_subproof. End FinFieldExt. Definition FinSplittingFieldType (F : finFieldType) (fT : fieldExtType F) := HB.pack_for (splittingFieldType F) fT (SplittingField.on (finvect_type fT)). Definition FinFieldExtType (F : finFieldType) (fT : fieldExtType F) := HB.pack_for finFieldType (FinSplittingFieldType fT) (FinRing.Field.on (finvect_type fT)). Arguments FinSplittingFieldType : clear implicits. Section PrimeChar. Variable p : nat. Section PrimeCharRing. Variable R0 : nzRingType. Definition pPrimeCharType of p \in [pchar R0] : predArgType := R0. Hypothesis pcharRp : p \in [pchar R0]. Local Notation R := (pPrimeCharType pcharRp). Implicit Types (a b : 'F_p) (x y : R). HB.instance Definition _ := GRing.NzRing.on R. Definition pprimeChar_scale a x := a%:R * x. Local Infix "*p':" := pprimeChar_scale (at level 40). Let natrFp n : (inZp n : 'F_p)%:R = n%:R :> R. Proof. rewrite [in RHS](divn_eq n p) natrD mulrnA (mulrn_pchar pcharRp) add0r. by rewrite /= (Fp_cast (pcharf_prime pcharRp)). Qed. Lemma pprimeChar_scaleA a b x : a *p': (b *p': x) = (a * b) *p': x. Proof. by rewrite /pprimeChar_scale mulrA -natrM natrFp. Qed. Lemma pprimeChar_scale1 : left_id 1 pprimeChar_scale. Proof. by move=> x; rewrite /pprimeChar_scale mul1r. Qed. Lemma pprimeChar_scaleDr : right_distributive pprimeChar_scale +%R. Proof. by move=> a x y /=; rewrite /pprimeChar_scale mulrDr. Qed. Lemma pprimeChar_scaleDl x : {morph pprimeChar_scale^~ x: a b / a + b}. Proof. by move=> a b; rewrite /pprimeChar_scale natrFp natrD mulrDl. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build 'F_p R pprimeChar_scaleA pprimeChar_scale1 pprimeChar_scaleDr pprimeChar_scaleDl. Lemma pprimeChar_scaleAl (a : 'F_p) (u v : R) : a *: (u * v) = (a *: u) * v. Proof. by apply: mulrA. Qed. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build 'F_p R pprimeChar_scaleAl. Lemma pprimeChar_scaleAr (a : 'F_p) (x y : R) : a *: (x * y) = x * (a *: y). Proof. by rewrite ![a *: _]mulr_natl mulrnAr. Qed. HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build 'F_p R pprimeChar_scaleAr. End PrimeCharRing. Local Notation type := @pPrimeCharType. (* TODO: automatize parameter inference to do all of these *) HB.instance Definition _ (R : unitRingType) pcharRp := GRing.UnitRing.on (type R pcharRp). HB.instance Definition _ (R : comNzRingType) pcharRp := GRing.ComNzRing.on (type R pcharRp). HB.instance Definition _ (R : comUnitRingType) pcharRp := GRing.ComUnitRing.on (type R pcharRp). HB.instance Definition _ (R : idomainType) pcharRp := GRing.IntegralDomain.on (type R pcharRp). HB.instance Definition _ (R : fieldType) pcharRp := GRing.Field.on (type R pcharRp). Section FinNzRing. Variables (R0 : finNzRingType) (pcharRp : p \in [pchar R0]). Local Notation R := (type _ pcharRp). HB.instance Definition _ := FinGroup.on R. Let pr_p : prime p. Proof. exact: pcharf_prime pcharRp. Qed. Lemma pprimeChar_abelem : p.-abelem [set: R]. Proof. exact: fin_Fp_lmod_abelem. Qed. Lemma pprimeChar_pgroup : p.-group [set: R]. Proof. by case/and3P: pprimeChar_abelem. Qed. Lemma order_pprimeChar x : x != 0 :> R -> #[x]%g = p. Proof. by apply: (abelem_order_p pprimeChar_abelem); rewrite inE. Qed. Let n := logn p #|R|. Lemma card_pprimeChar : #|R| = (p ^ n)%N. Proof. by rewrite /n -cardsT {1}(card_pgroup pprimeChar_pgroup). Qed. Lemma pprimeChar_vectAxiom : Vector.axiom n R. Proof. have /isog_isom/=[f /isomP[injf im_f]]: [set: R] \isog [set: 'rV['F_p]_n]. rewrite (@isog_abelem_card _ _ p) fin_Fp_lmod_abelem //=. by rewrite !cardsT card_pprimeChar card_mx mul1n card_Fp. exists f; last by exists (invm injf) => x; rewrite ?invmE ?invmK ?im_f ?inE. move=> a x y; rewrite [a *: _]mulr_natl morphM ?morphX ?inE // zmodXgE. by congr (_ + _); rewrite -scaler_nat natr_Zp. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build 'F_p R pprimeChar_vectAxiom. Lemma pprimeChar_dimf : \dim {: R : vectType 'F_p } = n. Proof. by rewrite dimvf. Qed. End FinNzRing. HB.instance Definition _ (R : finUnitRingType) pcharRp := FinRing.UnitRing.on (type R pcharRp). HB.instance Definition _ (R : finComNzRingType) pcharRp := FinRing.ComNzRing.on (type R pcharRp). HB.instance Definition _ (R : finComUnitRingType) pcharRp := FinRing.ComUnitRing.on (type R pcharRp). HB.instance Definition _ (R : finIdomainType) pcharRp := FinRing.IntegralDomain.on (type R pcharRp). Section FinField. Variables (F0 : finFieldType) (pcharFp : p \in [pchar F0]). Local Notation F := (type _ pcharFp). HB.instance Definition _ := Finite.on F. HB.instance Definition _ := SplittingField.copy F (finvect_type F). End FinField. End PrimeChar. #[deprecated(since="mathcomp 2.4.0", note="Use pPrimeCharType instead.")] Notation PrimeCharType := (pPrimeCharType) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scale instead.")] Notation primeChar_scale := (pprimeChar_scale) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleA instead.")] Notation primeChar_scaleA := (pprimeChar_scaleA) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scale1 instead.")] Notation primeChar_scale1 := (pprimeChar_scale1) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleDr instead.")] Notation primeChar_scaleDr := (pprimeChar_scaleDr) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleDl instead.")] Notation primeChar_scaleDl := (pprimeChar_scaleDl) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleAl instead.")] Notation primeChar_scaleAl := (pprimeChar_scaleAl) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleAr instead.")] Notation primeChar_scaleAr := (pprimeChar_scaleAr) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_abelem instead.")] Notation primeChar_abelem := (pprimeChar_abelem) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_pgroup instead.")] Notation primeChar_pgroup := (pprimeChar_pgroup) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use order_pprimeChar instead.")] Notation order_primeChar := (order_pprimeChar) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use card_pprimeChar instead.")] Notation card_primeChar := (card_pprimeChar) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_vectAxiom instead.")] Notation primeChar_vectAxiom := (pprimeChar_vectAxiom) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_dimf instead.")] Notation primeChar_dimf := (pprimeChar_dimf) (only parsing). Section FinSplittingField. Variable F : finFieldType. (* By card_vspace order K = #|K| for any finType structure on L; however we *) (* do not want to impose the FinVector instance here. *) Let order (L : vectType F) (K : {vspace L}) := (#|F| ^ \dim K)%N. Section FinGalois. Variable L : splittingFieldType F. Implicit Types (a b : F) (x y : L) (K E : {subfield L}). Let galL K : galois K {:L}. Proof. without loss {K} ->: K / K = 1%AS. by move=> IH_K; apply: galoisS (IH_K _ (erefl _)); rewrite sub1v subvf. apply/splitting_galoisField; pose finL := FinFieldExtType L. exists ('X^#|finL| - 'X); split; first by rewrite rpredB 1?rpredX ?polyOverX. rewrite (finField_genPoly finL) -big_enum /=. by rewrite separable_prod_XsubC ?(enum_uniq finL). exists (enum finL). by rewrite (@big_enum _ _ _ _ finL) (finField_genPoly finL) eqpxx. by apply/vspaceP=> x; rewrite memvf seqv_sub_adjoin ?(mem_enum finL). Qed. Fact galLgen K : {alpha | generator 'Gal({:L} / K) alpha & forall x, alpha x = x ^+ order K}. Proof. without loss{K} ->: K / K = 1%AS; last rewrite /order dimv1 expn1. case/(_ 1%AS)=> // alpha /eqP-defGalL; rewrite /order dimv1 expn1 => Dalpha. exists (alpha ^+ \dim K)%g => [|x]; last first. elim: (\dim K) => [|n IHn]; first by rewrite gal_id. by rewrite expgSr galM ?memvf // IHn Dalpha expnSr exprM. have sGalLK: 'Gal({:L} / K) \subset <[alpha]> by rewrite -defGalL galS ?sub1v. rewrite /generator {sGalLK}(eq_subG_cyclic _ sGalLK) ?cycle_cyclic ?cycleX //. rewrite -orderE orderXdiv orderE -defGalL -?{1}galois_dim ?dimv1 ?divn1 //. by rewrite field_dimS ?subvf. pose f x := x ^+ #|F|. have idfP x: reflect (f x = x) (x \in 1%VS). apply: (iffP (vlineP _ _)) => [[a ->] | xFx]. by rewrite -in_algE -[LHS]rmorphXn expf_card. pose q := map_poly (in_alg L) ('X^#|F| - 'X). have: root q x. rewrite /q rmorphB /= map_polyXn map_polyX. by rewrite rootE !(hornerE, hornerXn) [x ^+ _]xFx subrr. have{q} ->: q = \prod_(z <- [seq b%:A | b : F]) ('X - z%:P). rewrite /q finField_genPoly rmorph_prod big_image /=. by apply: eq_bigr => b _; rewrite rmorphB /= map_polyX map_polyC. by rewrite root_prod_XsubC => /mapP[a]; exists a. have fA : zmod_morphism f. rewrite /f => x y; rewrite ?exprMn ?expr1n //. have [p _ pcharFp] := finPcharP F; rewrite (card_pprimeChar pcharFp). elim: (logn _ _) => // n IHn; rewrite expnSr !exprM {}IHn. by rewrite -(pchar_lalg L) in pcharFp; rewrite -pFrobenius_autE rmorphB. have fM : monoid_morphism f. by rewrite /f; split=> [|x y]; rewrite ?exprMn ?expr1n //. have fZ: scalable f. move=> a x; rewrite -[in LHS]mulr_algl fM. by rewrite (idfP _ _) ?mulr_algl ?memvZ // memv_line. pose faM := GRing.isZmodMorphism.Build _ _ f fA. pose fmM := GRing.isMonoidMorphism.Build _ _ f fM. pose flM := GRing.isScalable.Build _ _ _ _ f fZ. pose fLRM : {lrmorphism _ -> _} := HB.pack f faM fmM flM. have /kAut_to_gal[alpha galLalpha Dalpha]: kAut 1 {:L} (linfun fLRM). rewrite kAutfE; apply/kHomP_tmp; split=> [x /idfP | x y _ _]; rewrite !lfunE //=. exact: (rmorphM fLRM). have{} Dalpha: alpha =1 f by move=> a; rewrite -Dalpha ?memvf ?lfunE. suffices <-: fixedField [set alpha] = 1%AS. by rewrite gal_generated /generator; exists alpha. apply/vspaceP=> x; apply/fixedFieldP/idfP; rewrite ?memvf // => id_x. by rewrite -Dalpha id_x ?set11. by move=> _ /set1P->; rewrite Dalpha. Qed. Lemma finField_galois K E : (K <= E)%VS -> galois K E. Proof. move=> sKE; have /galois_fixedField <- := galL E. rewrite normal_fixedField_galois // -sub_abelian_normal ?galS //. apply: abelianS (galS _ (sub1v _)) _. by have [alpha /('Gal(_ / _) =P _)-> _] := galLgen 1; apply: cycle_abelian. Qed. Lemma finField_galois_generator K E : (K <= E)%VS -> {alpha | generator 'Gal(E / K) alpha & {in E, forall x, alpha x = x ^+ order K}}. Proof. move=> sKE; have [alpha defGalLK Dalpha] := galLgen K. have inKL_E: (K <= E <= {:L})%VS by rewrite sKE subvf. have nKE: normalField K E by have/and3P[] := finField_galois sKE. have galLKalpha: alpha \in 'Gal({:L} / K). by rewrite (('Gal(_ / _) =P _) defGalLK) cycle_id. exists (normalField_cast _ alpha) => [|x Ex]; last first. by rewrite (normalField_cast_eq inKL_E). rewrite /generator -(morphim_cycle (normalField_cast_morphism inKL_E nKE)) //. by rewrite -((_ =P <[alpha]>) defGalLK) normalField_img. Qed. End FinGalois. Lemma Fermat's_little_theorem (L : fieldExtType F) (K : {subfield L}) a : (a \in K) = (a ^+ order K == a). Proof. move: K a; wlog [{}L -> K a]: L / exists galL : splittingFieldType F, L = galL. by pose galL := FinSplittingFieldType F L => /(_ galL); apply; exists galL. have /galois_fixedField fixLK := finField_galois (subvf K). have [alpha defGalLK Dalpha] := finField_galois_generator (subvf K). rewrite -Dalpha ?memvf // -{1}fixLK (('Gal(_ / _) =P _) defGalLK). rewrite /cycle -gal_generated (galois_fixedField _) ?fixedField_galois //. by apply/fixedFieldP/eqP=> [|-> | alpha_x _ /set1P->]; rewrite ?memvf ?set11. Qed. End FinSplittingField. Section FinFieldExists. (* While the existence of finite splitting fields and of finite fields of *) (* arbitrary prime power order is mathematically straightforward, it is *) (* technically challenging to formalize in Coq. The Coq typechecker performs *) (* poorly for some of the deeply nested dependent types used in the *) (* construction, such as polynomials over extensions of extensions of finite *) (* fields. Any conversion in a nested structure parameter incurs a huge *) (* overhead as it is shared across term comparison by call-by-need evalution. *) (* The proof of FinSplittingFieldFor is contrived to mitigate this effect: *) (* the abbreviation map_poly_extField alone divides by 3 the proof checking *) (* time, by reducing the number of occurrences of field(Ext)Type structures *) (* in the subgoals; the successive, apparently redundant 'suffices' localize *) (* some of the conversions to smaller subgoals, yielding a further 8-fold *) (* time gain. In particular, we construct the splitting field as a subtype *) (* of a recursive construction rather than prove that the latter yields *) (* precisely a splitting field. *) (* The apparently redundant type annotation reduces checking time by 30%. *) Let map_poly_extField (F : fieldType) (L : fieldExtType F) := map_poly (in_alg L) : {poly F} -> {poly L}. Local Notation "p ^%:A" := (map_poly_extField _ p) (format "p ^%:A") : ring_scope. Lemma FinSplittingFieldFor (F : finFieldType) (p : {poly F}) : p != 0 -> {L : splittingFieldType F | splittingFieldFor 1 p^%:A {:L}}. Proof. have mapXsubC (f : {rmorphism _ -> _}) x: map_poly f ('X - x%:P) = 'X - (f x)%:P. by rewrite rmorphB /= map_polyX map_polyC. move=> nz_p; pose splits q := {zs | q %= \prod_(z <- zs) ('X - z%:P)}. suffices [L splitLp]: {L : fieldExtType F | splittingFieldFor 1 p^%:A {:L}}. by exists (FinSplittingFieldType F L). suffices [L [ys Dp]]: {L : fieldExtType F & splits L p^%:A}. pose Lp := subvs_of <<1 & ys>>; pose toL := linfun (vsval : Lp -> L). have [zs Dys]: {zs | map toL zs = ys}. exists (map (vsproj _) ys); rewrite -map_comp map_id_in // => y ys_y. by rewrite /= lfunE /= vsprojK ?seqv_sub_adjoin. exists Lp, zs. set lhs := (lhs in lhs %= _); set rhs := (rhs in _ %= rhs). suffices: map_poly toL lhs %= map_poly toL rhs by rewrite eqp_map. rewrite -Dys big_map in Dp; apply: etrans Dp; apply: congr2. by rewrite -map_poly_comp; apply/eq_map_poly=> x; apply: rmorph_alg. by rewrite rmorph_prod; apply/eq_bigr=> z _; apply mapXsubC. set Lzs := LHS; pose Lys := (toL @: Lzs)%VS; apply/vspaceP=> u. have: val u \in Lys by rewrite /Lys aimg_adjoin_seq aimg1 Dys (valP u). by case/memv_imgP=> v Lzs_v; rewrite memvf lfunE => /val_inj->. move: {2}_.+1 (ltnSn (size p)) => n; elim: n => // n IHn in F p nz_p * => lbn. have [Cp|C'p] := leqP (size p) 1. exists F^o, [::]. by rewrite big_nil -size_poly_eq1 size_map_poly eqn_leq Cp size_poly_gt0. have [r r_dv_p irr_r]: {r | r %| p & irreducible_poly r}. pose rVp (v : 'rV_n) (r := rVpoly v) := (1 < size r) && (r %| p). have [v0 Dp]: {v0 | rVpoly v0 = p & rVp v0}. by exists (poly_rV p); rewrite /rVp poly_rV_K ?C'p /=. case/(arg_minnP (size \o rVpoly))=> /= v; set r := rVpoly v. case/andP=> C'r r_dv_p min_r; exists r => //; split=> // q C'q q_dv_r. have nz_r: r != 0 by rewrite -size_poly_gt0 ltnW. have le_q_r: size q <= size r by rewrite dvdp_leq. have [u Dq]: {u : 'rV_n | rVpoly u = q}. by exists (poly_rV q); rewrite poly_rV_K ?(leq_trans le_q_r) ?size_poly. rewrite -dvdp_size_eqp // eqn_leq le_q_r -Dq min_r // /rVp Dq. rewrite ltn_neqAle eq_sym C'q size_poly_gt0 (dvdpN0 q_dv_r) //=. exact: dvdp_trans q_dv_r r_dv_p. have{irr_r} [K _ [x rx0 defK]] := irredp_FAdjoin irr_r. have{r rx0 r_dv_p} /factor_theorem/sig_eqW[q Dp]: root p^%:A x. by rewrite -(divpK r_dv_p) [_^%:A]rmorphM rootM rx0 orbT. have Dszp: size p = size (q * ('X - x%:P)) by rewrite -Dp size_map_poly. have nz_q: q != 0. by move: nz_p; rewrite -size_poly_eq0 Dszp size_poly_eq0 mulf_eq0 => /norP[]. have [L [zs Dq]]: {L : fieldExtType K & splits L q^%:A}. apply: (IHn (FinFieldExtType K) q nz_q). by rewrite ltnS Dszp size_mul ?polyXsubC_eq0 ?size_XsubC ?addn2 in lbn. suffices: splits L p^%:A^%:A. rewrite -[_^%:A]map_poly_comp. (* TODO_HB : had to give the F explicitly *) rewrite -(eq_map_poly (fun a : F => baseField_scaleE a 1)). by exists (baseFieldType L). exists (x%:A :: zs); rewrite big_cons; set rhs := _ * _. by rewrite Dp mulrC [_^%:A]rmorphM /= mapXsubC /= eqp_mull. Qed. Lemma pPrimePowerField p k (m := (p ^ k)%N) : prime p -> 0 < k -> {Fm : finFieldType | p \in [pchar Fm] & #|Fm| = m}. Proof. move=> pr_p k_gt0; have m_gt1: m > 1 by rewrite (ltn_exp2l 0) ?prime_gt1. have m_gt0 := ltnW m_gt1; have m1_gt0: m.-1 > 0 by rewrite -ltnS prednK. pose q := 'X^m - 'X; have Dq R: q R = ('X^(m.-1) - 1) * ('X - 0). by rewrite subr0 mulrBl mul1r -exprSr prednK. have /FinSplittingFieldFor[/= L splitLq]: q 'F_p != 0. by rewrite Dq monic_neq0 ?rpredM ?monicXsubC ?monicXnsubC. rewrite [_^%:A]rmorphB rmorphXn /= map_polyX -/(q L) in splitLq. have pcharL: p \in [pchar L] by rewrite pchar_lalg pchar_Fp. pose Fm := FinFieldExtType L; exists Fm => //. have /finField_galois_generator[/= a _ Da]: (1 <= {:L})%VS by apply: sub1v. pose Em := fixedSpace (a ^+ k)%g; rewrite card_Fp //= dimv1 expn1 in Da. have{splitLq} [zs DqL defL] := splitLq. have Uzs: uniq zs. rewrite -separable_prod_XsubC -(eqp_separable DqL) Dq separable_root andbC. rewrite /root !hornerE subr_eq0 eq_sym expr0n gtn_eqF ?oner_eq0 //=. rewrite cyclotomic.separable_Xn_sub_1 // -subn1 natrB // subr_eq0. by rewrite natrX pcharf0 // expr0n gtn_eqF // eq_sym oner_eq0. suffices /eq_card->: Fm =i zs. apply: succn_inj; rewrite (card_uniqP _) //= -(size_prod_XsubC _ id). by rewrite -(eqp_size DqL) size_polyDl size_polyXn // size_polyN size_polyX. have in_zs: zs =i Em. move=> z; rewrite -root_prod_XsubC -(eqp_root DqL) (sameP fixedSpaceP eqP). rewrite /root !hornerE subr_eq0 /= /m; congr (_ == z). elim: (k) => [|i IHi]; first by rewrite gal_id. by rewrite expgSr expnSr exprM IHi galM ?Da ?memvf. suffices defEm: Em = {:L}%VS by move=> z; rewrite in_zs defEm memvf. apply/eqP; rewrite eqEsubv subvf -defL -[Em]subfield_closed agenvS //. by rewrite subv_add sub1v; apply/span_subvP=> z; rewrite in_zs. Qed. End FinFieldExists. #[deprecated(since="mathcomp 2.4.0", note="Use pPrimePowerField instead.")] Notation PrimePowerField := (pPrimePowerField) (only parsing). Section FinDomain. Import order ssrnum ssrint archimedean algC cyclotomic Order.TTheory Num.Theory. Local Infix "%|" := dvdn. (* Hide polynomial divisibility. *) Variable R : finUnitRingType. Hypothesis domR : GRing.integral_domain_axiom R. Implicit Types x y : R. Let lregR x : x != 0 -> GRing.lreg x. Proof. by move=> xnz; apply: mulrI0_lreg => y /domR/orP[/idPn | /eqP]. Qed. Lemma finDomain_field : GRing.field_axiom R. Proof. move=> x /lregR-regx; apply/unitrP; exists (invF regx 1). by split; first apply: (regx); rewrite ?mulrA f_invF // mulr1 mul1r. Qed. (* This is Witt's proof of Wedderburn's little theorem. *) Theorem finDomain_mulrC : @commutative R R *%R. Proof. have fieldR := finDomain_field. have [p p_pr pcharRp]: exists2 p, prime p & p \in [pchar R]. have [e /prod_prime_decomp->]: {e | (e > 0)%N & e%:R == 0 :> R}. by exists #|[set: R]%G|; rewrite // -order_dvdn order_dvdG ?inE. rewrite big_seq; elim/big_rec: _ => [|[p m] /= n]; first by rewrite oner_eq0. case/mem_prime_decomp=> p_pr _ _ IHn. elim: m => [|m IHm]; rewrite ?mul1n {IHn}// expnS -mulnA natrM. by case/eqP/domR/orP=> //; exists p; last apply/andP. pose Rp := pPrimeCharType pcharRp; pose L : {vspace Rp} := fullv. pose G := [set: {unit R}]; pose ofG : {unit R} -> Rp := val. pose projG (E : {vspace Rp}) := [preim ofG of E]. have inG t nzt: Sub t (finDomain_field nzt) \in G by rewrite inE. have card_projG E: #|projG E| = (p ^ \dim E - 1)%N. transitivity #|E|.-1; last by rewrite subn1 card_vspace card_Fp. rewrite (cardD1 0) mem0v (card_preim val_inj) /=. apply: eq_card => x; congr (_ && _); rewrite [LHS]codom_val. by apply/idP/idP=> [/(memPn _ _)-> | /fieldR]; rewrite ?unitr0. pose C u := 'C[ofG u]%AS; pose Q := 'C(L)%AS; pose q := (p ^ \dim Q)%N. have defC u: 'C[u] =i projG (C u). by move=> v; rewrite cent1E !inE (sameP cent1vP eqP). have defQ: 'Z(G) =i projG Q. move=> u /[!inE]. apply/centP/centvP=> cGu v _; last exact/val_inj/cGu/memvf. by have [-> | /inG/cGu[]] := eqVneq v 0; first by rewrite commr0. have q_gt1: (1 < q)%N by rewrite (ltn_exp2l 0) ?prime_gt1 ?adim_gt0. pose n := \dim_Q L; have oG: #|G| = (q ^ n - 1)%N. rewrite -expnM mulnC divnK ?skew_field_dimS ?subvf // -card_projG. by apply: eq_card => u; rewrite !inE memvf. have oZ: #|'Z(G)| = (q - 1)%N by rewrite -card_projG; apply: eq_card. suffices n_le1: (n <= 1)%N. move=> u v; apply/centvsP: (memvf (u : Rp)) (memvf (v : Rp)) => {u v}. rewrite -(geq_leqif (dimv_leqif_sup (subvf Q))) -/L. by rewrite leq_divLR ?mul1n ?skew_field_dimS ?subvf in n_le1. without loss n_gt1: / (1 < n)%N by rewrite ltnNge; apply: wlog_neg. have [q_gt0 n_gt0] := (ltnW q_gt1, ltnW n_gt1). have [z z_prim] := C_prim_root_exists n_gt0. have zn1: z ^+ n = 1 by apply: prim_expr_order. have /eqP-n1z: `|z| == 1 by rewrite -(pexpr_eq1 n_gt0) // -normrX zn1 normr1. suffices /eqP/normCBeq[t n1t [Dq Dz]]: `|q%:R - z : algC| == `|q%:R : algC| - `|z|. suffices z1: z == 1 by rewrite leq_eqVlt -dvdn1 (prim_order_dvd z_prim) z1. by rewrite Dz n1z mul1r -(eqr_pMn2r q_gt0) Dq normr_nat mulr_natl. pose aq d : algC := (cyclotomic (z ^+ (n %/ d)) d).[q%:R]. suffices: `|aq n| <= (q - 1)%:R. rewrite eq_le lerB_dist andbT n1z normr_nat natrB //; apply: le_trans. rewrite {}/aq horner_prod divnn n_gt0 expr1 normr_prod. rewrite (bigD1 (Ordinal n_gt1)) ?coprime1n //= !hornerE ler_peMr //. elim/big_ind: _ => // [|d _]; first exact: mulr_ege1. rewrite !hornerE; apply: le_trans (lerB_dist _ _). by rewrite normr_nat normrX n1z expr1n lerBDl (leC_nat 2). have Zaq d: d %| n -> aq d \in Num.int. move/(dvdn_prim_root z_prim)=> zd_prim. rewrite rpred_horner ?rpred_nat //= -Cintr_Cyclotomic //. by apply/polyOverP=> i; rewrite coef_map ?rpred_int. suffices: (aq n %| (q - 1)%:R)%C. rewrite {1}[aq n]intrEsign ?Zaq // -(rpredMsign _ (aq n < 0)%R). rewrite dvdC_mul2l ?signr_eq0 //. have /natrP[m ->]: `|aq n| \in Num.nat by rewrite natr_norm_int ?Zaq. by rewrite leC_nat dvdC_nat; apply: dvdn_leq; rewrite subn_gt0. have prod_aq m: m %| n -> \prod_(d < n.+1 | d %| m) aq d = (q ^ m - 1)%:R. move=> m_dv_n; transitivity ('X^m - 1).[q%:R : algC]; last first. by rewrite !hornerE -natrX natrB ?expn_gt0 ?prime_gt0. rewrite (prod_cyclotomic (dvdn_prim_root z_prim m_dv_n)). have def_divm: perm_eq (divisors m) [seq d <- index_iota 0 n.+1 | d %| m]. rewrite uniq_perm ?divisors_uniq ?filter_uniq ?iota_uniq // => d. rewrite -dvdn_divisors ?(dvdn_gt0 n_gt0) // mem_filter mem_iota ltnS /=. by apply/esym/andb_idr=> d_dv_m; rewrite dvdn_leq ?(dvdn_trans d_dv_m). rewrite (perm_big _ def_divm) big_filter big_mkord horner_prod. by apply: eq_bigr => d d_dv_m; rewrite -exprM muln_divA ?divnK. have /rpredBl<-: (aq n %| #|G|%:R)%C. rewrite oG -prod_aq // (bigD1 ord_max) //= dvdC_mulr //. by apply: rpred_prod => d /andP[/Zaq]. rewrite center_class_formula addrC oZ natrD addKr natr_sum /=. apply: rpred_sum => _ /imsetP[u /setDP[_ Z'u] ->]; rewrite -/G /=. have sQC: (Q <= C u)%VS by apply/subvP=> v /centvP-cLv; apply/cent1vP/cLv/memvf. have{sQC} /dvdnP[m Dm]: \dim Q %| \dim (C u) by apply: skew_field_dimS. have m_dv_n: m %| n by rewrite dvdn_divRL // -?Dm ?skew_field_dimS ?subvf. have m_gt0: (0 < m)%N := dvdn_gt0 n_gt0 m_dv_n. have{Dm} oCu: #|'C[u]| = (q ^ m - 1)%N. by rewrite -expnM mulnC -Dm (eq_card (defC u)) card_projG. have ->: #|u ^: G|%:R = \prod_(d < n.+1 | d %| n) (aq d / aq d ^+ (d %| m)). rewrite -index_cent1 natf_indexg ?subsetT //= setTI prodf_div prod_aq // -oG. congr (_ / _); rewrite big_mkcond oCu -prod_aq //= big_mkcond /=. by apply: eq_bigr => d _; case: ifP => [/dvdn_trans->| _]; rewrite ?if_same. rewrite (bigD1 ord_max) //= [n %| m](contraNF _ Z'u) => [|n_dv_m]; last first. rewrite -sub_cent1 subEproper eq_sym eqEcard subsetT oG oCu leq_sub2r //. by rewrite leq_exp2l // dvdn_leq. rewrite divr1 dvdC_mulr //; apply/rpred_prod => d /andP[/Zaq-Zaqd _]. have [-> | nz_aqd] := eqVneq (aq d) 0; first by rewrite mul0r /=. by rewrite -[aq d]expr1 -exprB ?leq_b1 ?unitfE ?rpredX. Qed. Definition FinDomainFieldType : finFieldType := let cC := GRing.PzRing_hasCommutativeMul.Build R finDomain_mulrC in let cR : comUnitRingType := HB.pack R cC in let iC := GRing.ComUnitRing_isIntegral.Build cR domR in let iR : finIdomainType := HB.pack cR iC in let fC := GRing.UnitRing_isField.Build iR finDomain_field in HB.pack iR fC. Definition FinDomainSplittingFieldType_pchar p (pcharRp : p \in [pchar R]) := SplittingField.clone 'F_p R (@pPrimeCharType p FinDomainFieldType pcharRp). End FinDomain. #[deprecated(since="mathcomp 2.4.0", note="Use FinDomainSplittingFieldType_pchar instead.")] Notation FinDomainSplittingFieldType := (FinDomainSplittingFieldType_pchar) (only parsing).
action.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrbool ssrfun ssrnotations eqtype. From mathcomp Require Import ssrnat div seq prime fintype bigop finset. From mathcomp Require Import fingroup morphism perm automorphism quotient. (******************************************************************************) (* Group action: orbits, stabilisers, transitivity. *) (* is_action D to == the function to : T -> aT -> T defines an action *) (* of D : {set aT} on T. *) (* action D T == structure for a function defining an action of D. *) (* act_dom to == the domain D of to : action D rT. *) (* {action: aT &-> T} == structure for a total action. *) (* := action [set: aT] T *) (* TotalAction to1 toM == the constructor for total actions; to1 and toM *) (* are the proofs of the action identities for 1 and *) (* a * b, respectively. *) (* is_groupAction R to == to is a group action on range R: for all a in D, *) (* the permutation induced by to a is in Aut R. Thus *) (* the action of D must be trivial outside R. *) (* groupAction D R == the structure for group actions of D on R. This *) (* is a telescope on action D rT. *) (* gact_range to == the range R of to : groupAction D R. *) (* GroupAction toAut == constructs a groupAction for action to from *) (* toAut : actm to @* D \subset Aut R (actm to is *) (* the morphism to {perm rT} associated to 'to'). *) (* orbit to A x == the orbit of x under the action of A via to. *) (* orbit_transversal to A S == a transversal of the partition orbit to A @: S *) (* of S, provided A acts on S via to. *) (* amove to A x y == the set of a in A whose action sends x to y. *) (* 'C_A[x | to] == the stabiliser of x : rT in A :&: D. *) (* 'C_A(S | to) == the pointwise stabiliser of S : {set rT} in D :&: A. *) (* 'N_A(S | to) == the global stabiliser of S : {set rT} in D :&: A. *) (* 'Fix_(S | to)[a] == the set of fixpoints of a in S. *) (* 'Fix_(S | to)(A) == the set of fixpoints of A in S. *) (* In the first three _A can be omitted and defaults to the domain D of to; *) (* in the last two S can be omitted and defaults to [set: T], so 'Fix_to[a] *) (* is the set of all fixpoints of a. *) (* The domain restriction ensures that stabilisers have a canonical group *) (* structure, but note that 'Fix sets are generally not groups. Indeed, we *) (* provide alternative definitions when to is a group action on R: *) (* 'C_(G | to)(A) == the centraliser in R :&: G of the group action of *) (* D :&: A via to *) (* 'C_(G | to)[a] == the centraliser in R :&: G of a \in D, via to. *) (* These sets are groups when G is; G can be omitted: 'C(|to)(A) is the *) (* centraliser in R of the action of D :&: A via to. *) (* [acts A, on S | to] == A \subset D acts on the set S via to. *) (* {acts A, on S | to} == A acts on the set S (Prop statement). *) (* {acts A, on group G | to} == [acts A, on S | to] /\ G \subset R, i.e., *) (* A \subset D acts on G \subset R, via *) (* to : groupAction D R. *) (* [transitive A, on S | to] == A acts transitively on S. *) (* [faithful A, on S | to] == A acts faithfully on S. *) (* acts_irreducibly to A G == A acts irreducibly via the groupAction to *) (* on the nontrivial group G, i.e., A does *) (* not act on any nontrivial subgroup of G. *) (* Important caveat: the definitions of orbit, amove, 'Fix_(S | to)(A), *) (* transitive and faithful assume that A is a subset of the domain D. As most *) (* of the permutation actions we consider are total this is usually harmless. *) (* (Note that the theory of partial actions is only partially developed.) *) (* In all of the above, to is expected to be the actual action structure, *) (* not merely the function. There is a special scope %act for actions, and *) (* constructions and notations for many classical actions: *) (* 'P == natural action of a permutation group via aperm. *) (* 'J == internal group action (conjugation) via conjg (_ ^ _). *) (* 'R == regular group action (right translation) via mulg (_ * _). *) (* (However, to limit ambiguity, _ * _ is NOT a canonical action.) *) (* to^* == the action induced by to on {set rT} via to^* (== setact to). *) (* 'Js == the internal action on subsets via _ :^ _, equivalent to 'J^*. *) (* 'Rs == the regular action on subsets via rcoset, equivalent to 'R^*. *) (* 'JG == the conjugation action on {group rT} via (_ :^ _)%G. *) (* to / H == the action induced by to on coset_of H via qact to H, and *) (* restricted to (qact_dom to H) == 'N(rcosets H 'N(H) | to^* ). *) (* 'Q == the action induced to cosets by conjugation; the domain is *) (* qact_dom 'J H, which is provably equal to 'N(H). *) (* to %% A == the action of coset_of A via modact to A, with domain D / A *) (* and support restricted to 'C(D :&: A | to). *) (* to \ sAD == the action of A via ract to sAD == to, if sAD : A \subset D. *) (* [Aut G] == the permutation action restricted to Aut G, via autact G. *) (* <[nRA]> == the action of A on R via actby nRA == to in A and on R, and *) (* the trivial action elsewhere; here nRA : [acts A, on R | to] *) (* or nRA : {acts A, on group R | to}. *) (* to^? == the action induced by to on sT : @subType rT P, via subact to *) (* with domain subact_dom P to == 'N([set x | P x] | to). *) (* <<phi>> == the action of phi : D >-> {perm rT}, via mact phi. *) (* to \o f == the composite action (with domain f @*^-1 D) of the action to *) (* with f : {morphism G >-> aT}, via comp_act to f. Here f must *) (* be the actual morphism object (e.g., coset_morphism H), not *) (* the underlying function (e.g., coset H). *) (* The explicit application of an action to is usually written (to%act x a), *) (* but %act can be omitted if to is an abstract action or a set action to^*. *) (* Note that this form will simplify and expose the acting function. *) (* There is a %gact scope for group actions; the notations above are *) (* recognised in %gact when they denote canonical group actions. *) (* Actions can be used to define morphisms: *) (* actperm to == the morphism D >-> {perm rT} induced by to. *) (* actm to a == if a \in D the function on D induced by the action to, else *) (* the identity function. If to is a group action with range R *) (* then actm to a is canonically a morphism on R. *) (* We also define here the restriction operation on permutations (the domain *) (* of this operations is a stabiliser), and local automorphism groups: *) (* restr_perm S p == if p acts on S, the permutation with support in S that *) (* coincides with p on S; else the identity. Note that *) (* restr_perm is a permutation group morphism that maps *) (* Aut G to Aut S when S is a subgroup of G. *) (* Aut_in A G == the local permutation group 'N_A(G | 'P) / 'C_A(G | 'P) *) (* Usually A is an automorphism group, and then Aut_in A G *) (* is isomorphic to a subgroup of Aut G, specifically *) (* restr_perm @* A. *) (* Finally, gproduct.v will provide a semi-direct group construction that *) (* maps an external group action to an internal one; the theory of morphisms *) (* between such products makes use of the following definition: *) (* morph_act to to' f fA <=> the action of to' on the images of f and fA is *) (* the image of the action of to, i.e., for all x and a we *) (* have f (to x a) = to' (f x) (fA a). Note that there is *) (* no mention of the domains of to and to'; if needed, this *) (* predicate should be restricted via the {in ...} notation *) (* and domain conditions should be added. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope action_scope. Declare Scope groupAction_scope. Import GroupScope. Section ActionDef. Variables (aT : finGroupType) (D : {set aT}) (rT : Type). Implicit Types a b : aT. Implicit Type x : rT. Definition act_morph to x := forall a b, to x (a * b) = to (to x a) b. Definition is_action to := left_injective to /\ forall x, {in D &, act_morph to x}. Record action := Action {act :> rT -> aT -> rT; _ : is_action act}. Definition clone_action to := let: Action _ toP := to return {type of Action for to} -> action in fun k => k toP. End ActionDef. (* Need to close the Section here to avoid re-declaring all Argument Scopes *) Delimit Scope action_scope with act. Bind Scope action_scope with action. Arguments act_morph {aT rT%_type} to x%_g. Arguments is_action {aT} D%_g {rT} to. Arguments act {aT D%_g rT%_type} to%_act x%_g a%_g : rename. Arguments clone_action [aT D%_g rT%_type to%_act] _. Notation "{ 'action' aT &-> T }" := (action [set: aT] T) (format "{ 'action' aT &-> T }") : type_scope. Notation "[ 'action' 'of' to ]" := (clone_action (@Action _ _ _ to)) (format "[ 'action' 'of' to ]") : form_scope. Definition act_dom aT D rT of @action aT D rT := D. Section TotalAction. Variables (aT : finGroupType) (rT : Type) (to : rT -> aT -> rT). Hypotheses (to1 : to^~ 1 =1 id) (toM : forall x, act_morph to x). Lemma is_total_action : is_action setT to. Proof. split=> [a | x a b _ _] /=; last by rewrite toM. by apply: can_inj (to^~ a^-1) _ => x; rewrite -toM ?mulgV. Qed. Definition TotalAction := Action is_total_action. End TotalAction. Section ActionDefs. Variables (aT aT' : finGroupType) (D : {set aT}) (D' : {set aT'}). Definition morph_act rT rT' (to : action D rT) (to' : action D' rT') f fA := forall x a, f (to x a) = to' (f x) (fA a). Variable rT : finType. (* Most definitions require a finType structure on rT *) Implicit Type to : action D rT. Implicit Type A : {set aT}. Implicit Type S : {set rT}. Definition actm to a := if a \in D then to^~ a else id. Definition setact to S a := [set to x a | x in S]. Definition orbit to A x := to x @: A. Definition amove to A x y := [set a in A | to x a == y]. Definition afix to A := [set x | A \subset [set a | to x a == x]]. Definition astab S to := D :&: [set a | S \subset [set x | to x a == x]]. Definition astabs S to := D :&: [set a | S \subset to^~ a @^-1: S]. Definition acts_on A S to := {in A, forall a x, (to x a \in S) = (x \in S)}. Definition atrans A S to := S \in orbit to A @: S. Definition faithful A S to := A :&: astab S to \subset [1]. End ActionDefs. Arguments setact {aT D%_g rT} to%_act S%_g a%_g. Arguments orbit {aT D%_g rT} to%_act A%_g x%_g. Arguments amove {aT D%_g rT} to%_act A%_g x%_g y%_g. Arguments afix {aT D%_g rT} to%_act A%_g. Arguments astab {aT D%_g rT} S%_g to%_act. Arguments astabs {aT D%_g rT} S%_g to%_act. Arguments acts_on {aT D%_g rT} A%_g S%_g to%_act. Arguments atrans {aT D%_g rT} A%_g S%_g to%_act. Arguments faithful {aT D%_g rT} A%_g S%_g to%_act. Notation "to ^*" := (setact to) : function_scope. Prenex Implicits orbit amove. Notation "''Fix_' to ( A )" := (afix to A) (to at level 2, format "''Fix_' to ( A )") : group_scope. (* camlp4 grammar factoring *) Notation "''Fix_' ( to ) ( A )" := 'Fix_to(A) (only parsing) : group_scope. Notation "''Fix_' ( S | to ) ( A )" := (S :&: 'Fix_to(A)) (format "''Fix_' ( S | to ) ( A )") : group_scope. Notation "''Fix_' to [ a ]" := ('Fix_to([set a])) (to at level 2, format "''Fix_' to [ a ]") : group_scope. Notation "''Fix_' ( S | to ) [ a ]" := (S :&: 'Fix_to[a]) (format "''Fix_' ( S | to ) [ a ]") : group_scope. Notation "''C' ( S | to )" := (astab S to) : group_scope. Notation "''C_' A ( S | to )" := (A :&: 'C(S | to)) : group_scope. Notation "''C_' ( A ) ( S | to )" := 'C_A(S | to) (only parsing) : group_scope. Notation "''C' [ x | to ]" := ('C([set x] | to)) : group_scope. Notation "''C_' A [ x | to ]" := (A :&: 'C[x | to]) : group_scope. Notation "''C_' ( A ) [ x | to ]" := 'C_A[x | to] (only parsing) : group_scope. Notation "''N' ( S | to )" := (astabs S to) (format "''N' ( S | to )") : group_scope. Notation "''N_' A ( S | to )" := (A :&: 'N(S | to)) (A at level 2, format "''N_' A ( S | to )") : group_scope. Notation "[ 'acts' A , 'on' S | to ]" := (A \subset pred_of_set 'N(S | to)) (format "[ 'acts' A , 'on' S | to ]") : form_scope. Notation "{ 'acts' A , 'on' S | to }" := (acts_on A S to) (format "{ 'acts' A , 'on' S | to }") : type_scope. Notation "[ 'transitive' A , 'on' S | to ]" := (atrans A S to) (format "[ 'transitive' A , 'on' S | to ]") : form_scope. Notation "[ 'faithful' A , 'on' S | to ]" := (faithful A S to) (format "[ 'faithful' A , 'on' S | to ]") : form_scope. Section RawAction. (* Lemmas that do not require the group structure on the action domain. *) (* Some lemmas like actMin would be actually be valid for arbitrary rT, *) (* e.g., for actions on a function type, but would be difficult to use *) (* as a view due to the confusion between parameters and assumptions. *) Variables (aT : finGroupType) (D : {set aT}) (rT : finType) (to : action D rT). Implicit Types (a : aT) (x y : rT) (A B : {set aT}) (S T : {set rT}). Lemma act_inj : left_injective to. Proof. by case: to => ? []. Qed. Arguments act_inj : clear implicits. Lemma actMin x : {in D &, act_morph to x}. Proof. by case: to => ? []. Qed. Lemma actmEfun a : a \in D -> actm to a = to^~ a. Proof. by rewrite /actm => ->. Qed. Lemma actmE a : a \in D -> actm to a =1 to^~ a. Proof. by move=> Da; rewrite actmEfun. Qed. Lemma setactE S a : to^* S a = [set to x a | x in S]. Proof. by []. Qed. Lemma mem_setact S a x : x \in S -> to x a \in to^* S a. Proof. exact: imset_f. Qed. Lemma card_setact S a : #|to^* S a| = #|S|. Proof. by apply: card_imset; apply: act_inj. Qed. Lemma setact_is_action : is_action D to^*. Proof. split=> [a R S eqRS | a b Da Db S]; last first. by rewrite /setact /= -imset_comp; apply: eq_imset => x; apply: actMin. apply/setP=> x; apply/idP/idP=> /(mem_setact a). by rewrite eqRS => /imsetP[y Sy /act_inj->]. by rewrite -eqRS => /imsetP[y Sy /act_inj->]. Qed. Canonical set_action := Action setact_is_action. Lemma orbitE A x : orbit to A x = to x @: A. Proof. by []. Qed. Lemma orbitP A x y : reflect (exists2 a, a \in A & to x a = y) (y \in orbit to A x). Proof. by apply: (iffP imsetP) => [] [a]; exists a. Qed. Lemma mem_orbit A x a : a \in A -> to x a \in orbit to A x. Proof. exact: imset_f. Qed. Lemma afixP A x : reflect (forall a, a \in A -> to x a = x) (x \in 'Fix_to(A)). Proof. rewrite inE; apply: (iffP subsetP) => [xfix a /xfix | xfix a Aa]. by rewrite inE => /eqP. by rewrite inE xfix. Qed. Lemma afixS A B : A \subset B -> 'Fix_to(B) \subset 'Fix_to(A). Proof. by move=> sAB; apply/subsetP=> u /[!inE]; apply: subset_trans. Qed. Lemma afixU A B : 'Fix_to(A :|: B) = 'Fix_to(A) :&: 'Fix_to(B). Proof. by apply/setP=> x; rewrite !inE subUset. Qed. Lemma afix1P a x : reflect (to x a = x) (x \in 'Fix_to[a]). Proof. by rewrite inE sub1set inE; apply: eqP. Qed. Lemma astabIdom S : 'C_D(S | to) = 'C(S | to). Proof. by rewrite setIA setIid. Qed. Lemma astab_dom S : {subset 'C(S | to) <= D}. Proof. by move=> a /setIP[]. Qed. Lemma astab_act S a x : a \in 'C(S | to) -> x \in S -> to x a = x. Proof. rewrite 2!inE => /andP[_ cSa] Sx; apply/eqP. by have /[1!inE] := subsetP cSa x Sx. Qed. Lemma astabS S1 S2 : S1 \subset S2 -> 'C(S2 | to) \subset 'C(S1 | to). Proof. by move=> sS12; apply/subsetP=> x /[!inE] /andP[->]; apply: subset_trans. Qed. Lemma astabsIdom S : 'N_D(S | to) = 'N(S | to). Proof. by rewrite setIA setIid. Qed. Lemma astabs_dom S : {subset 'N(S | to) <= D}. Proof. by move=> a /setIdP[]. Qed. Lemma astabs_act S a x : a \in 'N(S | to) -> (to x a \in S) = (x \in S). Proof. rewrite 2!inE subEproper properEcard => /andP[_]. rewrite (card_preimset _ (act_inj _)) ltnn andbF orbF => /eqP{2}->. by rewrite inE. Qed. Lemma astab_sub S : 'C(S | to) \subset 'N(S | to). Proof. apply/subsetP=> a cSa; rewrite !inE (astab_dom cSa). by apply/subsetP=> x Sx; rewrite inE (astab_act cSa). Qed. Lemma astabsC S : 'N(~: S | to) = 'N(S | to). Proof. apply/setP=> a; apply/idP/idP=> nSa; rewrite !inE (astabs_dom nSa). by rewrite -setCS -preimsetC; apply/subsetP=> x; rewrite inE astabs_act. by rewrite preimsetC setCS; apply/subsetP=> x; rewrite inE astabs_act. Qed. Lemma astabsI S T : 'N(S | to) :&: 'N(T | to) \subset 'N(S :&: T | to). Proof. apply/subsetP=> a; rewrite !inE -!andbA preimsetI => /and4P[-> nSa _ nTa] /=. by rewrite setISS. Qed. Lemma astabs_setact S a : a \in 'N(S | to) -> to^* S a = S. Proof. move=> nSa; apply/eqP; rewrite eqEcard card_setact leqnn andbT. by apply/subsetP=> _ /imsetP[x Sx ->]; rewrite astabs_act. Qed. Lemma astab1_set S : 'C[S | set_action] = 'N(S | to). Proof. apply/setP=> a; apply/idP/idP=> nSa. case/setIdP: nSa => Da; rewrite !inE Da sub1set inE => /eqP defS. by apply/subsetP=> x Sx; rewrite inE -defS mem_setact. by rewrite !inE (astabs_dom nSa) sub1set inE /= astabs_setact. Qed. Lemma astabs_set1 x : 'N([set x] | to) = 'C[x | to]. Proof. apply/eqP; rewrite eqEsubset astab_sub andbC setIS //. by apply/subsetP=> a; rewrite ?(inE,sub1set). Qed. Lemma acts_dom A S : [acts A, on S | to] -> A \subset D. Proof. by move=> nSA; rewrite (subset_trans nSA) ?subsetIl. Qed. Lemma acts_act A S : [acts A, on S | to] -> {acts A, on S | to}. Proof. by move=> nAS a Aa x; rewrite astabs_act ?(subsetP nAS). Qed. Lemma astabCin A S : A \subset D -> (A \subset 'C(S | to)) = (S \subset 'Fix_to(A)). Proof. move=> sAD; apply/subsetP/subsetP=> [sAC x xS | sSF a aA]. by apply/afixP=> a aA; apply: astab_act (sAC _ aA) xS. rewrite !inE (subsetP sAD _ aA); apply/subsetP=> x xS. by move/afixP/(_ _ aA): (sSF _ xS) => /[1!inE] ->. Qed. Section ActsSetop. Variables (A : {set aT}) (S T : {set rT}). Hypotheses (AactS : [acts A, on S | to]) (AactT : [acts A, on T | to]). Lemma astabU : 'C(S :|: T | to) = 'C(S | to) :&: 'C(T | to). Proof. by apply/setP=> a; rewrite !inE subUset; case: (a \in D). Qed. Lemma astabsU : 'N(S | to) :&: 'N(T | to) \subset 'N(S :|: T | to). Proof. by rewrite -(astabsC S) -(astabsC T) -(astabsC (S :|: T)) setCU astabsI. Qed. Lemma astabsD : 'N(S | to) :&: 'N(T | to) \subset 'N(S :\: T| to). Proof. by rewrite setDE -(astabsC T) astabsI. Qed. Lemma actsI : [acts A, on S :&: T | to]. Proof. by apply: subset_trans (astabsI S T); rewrite subsetI AactS. Qed. Lemma actsU : [acts A, on S :|: T | to]. Proof. by apply: subset_trans astabsU; rewrite subsetI AactS. Qed. Lemma actsD : [acts A, on S :\: T | to]. Proof. by apply: subset_trans astabsD; rewrite subsetI AactS. Qed. End ActsSetop. Lemma acts_in_orbit A S x y : [acts A, on S | to] -> y \in orbit to A x -> x \in S -> y \in S. Proof. by move=> nSA/imsetP[a Aa ->{y}] Sx; rewrite (astabs_act _ (subsetP nSA a Aa)). Qed. Lemma subset_faithful A B S : B \subset A -> [faithful A, on S | to] -> [faithful B, on S | to]. Proof. by move=> sAB; apply: subset_trans; apply: setSI. Qed. Section Reindex. Variables (vT : Type) (idx : vT) (op : Monoid.com_law idx) (S : {set rT}). Lemma reindex_astabs a F : a \in 'N(S | to) -> \big[op/idx]_(i in S) F i = \big[op/idx]_(i in S) F (to i a). Proof. move=> nSa; rewrite (reindex_inj (act_inj a)); apply: eq_bigl => x. exact: astabs_act. Qed. Lemma reindex_acts A a F : [acts A, on S | to] -> a \in A -> \big[op/idx]_(i in S) F i = \big[op/idx]_(i in S) F (to i a). Proof. by move=> nSA /(subsetP nSA); apply: reindex_astabs. Qed. End Reindex. End RawAction. Arguments act_inj {aT D rT} to a [x1 x2] : rename. Notation "to ^*" := (set_action to) : action_scope. Arguments orbitP {aT D rT to A x y}. Arguments afixP {aT D rT to A x}. Arguments afix1P {aT D rT to a x}. Arguments reindex_astabs [aT D rT] to [vT idx op S] a [F]. Arguments reindex_acts [aT D rT] to [vT idx op S A a F]. Section PartialAction. (* Lemmas that require a (partial) group domain. *) Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable to : action D rT. Implicit Types a : aT. Implicit Types x y : rT. Implicit Types A B : {set aT}. Implicit Types G H : {group aT}. Implicit Types S : {set rT}. Lemma act1 x : to x 1 = x. Proof. by apply: (act_inj to 1); rewrite -actMin ?mulg1. Qed. Lemma actKin : {in D, right_loop invg to}. Proof. by move=> a Da /= x; rewrite -actMin ?groupV // mulgV act1. Qed. Lemma actKVin : {in D, rev_right_loop invg to}. Proof. by move=> a Da /= x; rewrite -{2}(invgK a) actKin ?groupV. Qed. Lemma setactVin S a : a \in D -> to^* S a^-1 = to^~ a @^-1: S. Proof. by move=> Da; apply: can2_imset_pre; [apply: actKVin | apply: actKin]. Qed. Lemma actXin x a i : a \in D -> to x (a ^+ i) = iter i (to^~ a) x. Proof. move=> Da; elim: i => /= [|i <-]; first by rewrite act1. by rewrite expgSr actMin ?groupX. Qed. Lemma afix1 : 'Fix_to(1) = setT. Proof. by apply/setP=> x; rewrite !inE sub1set inE act1 eqxx. Qed. Lemma afixD1 G : 'Fix_to(G^#) = 'Fix_to(G). Proof. by rewrite -{2}(setD1K (group1 G)) afixU afix1 setTI. Qed. Lemma orbit_refl G x : x \in orbit to G x. Proof. by rewrite -{1}[x]act1 mem_orbit. Qed. Local Notation orbit_rel A := (fun x y => x \in orbit to A y). Lemma contra_orbit G x y : x \notin orbit to G y -> x != y. Proof. by apply: contraNneq => ->; apply: orbit_refl. Qed. Lemma orbit_in_sym G : G \subset D -> symmetric (orbit_rel G). Proof. move=> sGD; apply: symmetric_from_pre => x y /imsetP[a Ga]. by move/(canLR (actKin (subsetP sGD a Ga))) <-; rewrite mem_orbit ?groupV. Qed. Lemma orbit_in_trans G : G \subset D -> transitive (orbit_rel G). Proof. move=> sGD _ _ z /imsetP[a Ga ->] /imsetP[b Gb ->]. by rewrite -actMin ?mem_orbit ?groupM // (subsetP sGD). Qed. Lemma orbit_in_eqP G x y : G \subset D -> reflect (orbit to G x = orbit to G y) (x \in orbit to G y). Proof. move=> sGD; apply: (iffP idP) => [yGx|<-]; last exact: orbit_refl. by apply/setP=> z; apply/idP/idP=> /orbit_in_trans-> //; rewrite orbit_in_sym. Qed. Lemma orbit_in_transl G x y z : G \subset D -> y \in orbit to G x -> (y \in orbit to G z) = (x \in orbit to G z). Proof. by move=> sGD Gxy; rewrite !(orbit_in_sym sGD _ z) (orbit_in_eqP y x sGD Gxy). Qed. Lemma orbit_act_in x a G : G \subset D -> a \in G -> orbit to G (to x a) = orbit to G x. Proof. by move=> sGD /mem_orbit/orbit_in_eqP->. Qed. Lemma orbit_actr_in x a G y : G \subset D -> a \in G -> (to y a \in orbit to G x) = (y \in orbit to G x). Proof. by move=> sGD /mem_orbit/orbit_in_transl->. Qed. Lemma orbit_inv_in A x y : A \subset D -> (y \in orbit to A^-1 x) = (x \in orbit to A y). Proof. move/subsetP=> sAD; apply/imsetP/imsetP=> [] [a Aa ->]. by exists a^-1; rewrite -?mem_invg ?actKin // -groupV sAD -?mem_invg. by exists a^-1; rewrite ?memV_invg ?actKin // sAD. Qed. Lemma orbit_lcoset_in A a x : A \subset D -> a \in D -> orbit to (a *: A) x = orbit to A (to x a). Proof. move/subsetP=> sAD Da; apply/setP=> y; apply/imsetP/imsetP=> [] [b Ab ->{y}]. by exists (a^-1 * b); rewrite -?actMin ?mulKVg // ?sAD -?mem_lcoset. by exists (a * b); rewrite ?mem_mulg ?set11 ?actMin // sAD. Qed. Lemma orbit_rcoset_in A a x y : A \subset D -> a \in D -> (to y a \in orbit to (A :* a) x) = (y \in orbit to A x). Proof. move=> sAD Da; rewrite -orbit_inv_in ?mul_subG ?sub1set // invMg. by rewrite invg_set1 orbit_lcoset_in ?inv_subG ?groupV ?actKin ?orbit_inv_in. Qed. Lemma orbit_conjsg_in A a x y : A \subset D -> a \in D -> (to y a \in orbit to (A :^ a) (to x a)) = (y \in orbit to A x). Proof. move=> sAD Da; rewrite conjsgE. by rewrite orbit_lcoset_in ?groupV ?mul_subG ?sub1set ?actKin ?orbit_rcoset_in. Qed. Lemma orbit1P G x : reflect (orbit to G x = [set x]) (x \in 'Fix_to(G)). Proof. apply: (iffP afixP) => [xfix | xfix a Ga]. apply/eqP; rewrite eq_sym eqEsubset sub1set -{1}[x]act1 imset_f //=. by apply/subsetP=> y; case/imsetP=> a Ga ->; rewrite inE xfix. by apply/set1P; rewrite -xfix imset_f. Qed. Lemma card_orbit1 G x : #|orbit to G x| = 1%N -> orbit to G x = [set x]. Proof. move=> orb1; apply/eqP; rewrite eq_sym eqEcard {}orb1 cards1. by rewrite sub1set orbit_refl. Qed. Lemma orbit_partition G S : [acts G, on S | to] -> partition (orbit to G @: S) S. Proof. move=> actsGS; have sGD := acts_dom actsGS. have eqiG: {in S & &, equivalence_rel [rel x y | y \in orbit to G x]}. by move=> x y z * /=; rewrite orbit_refl; split=> // /orbit_in_eqP->. congr (partition _ _): (equivalence_partitionP eqiG). apply: eq_in_imset => x Sx; apply/setP=> y. by rewrite inE /= andb_idl // => /acts_in_orbit->. Qed. Definition orbit_transversal A S := transversal (orbit to A @: S) S. Lemma orbit_transversalP G S (P := orbit to G @: S) (X := orbit_transversal G S) : [acts G, on S | to] -> [/\ is_transversal X P S, X \subset S, {in X &, forall x y, (y \in orbit to G x) = (x == y)} & forall x, x \in S -> exists2 a, a \in G & to x a \in X]. Proof. move/orbit_partition; rewrite -/P => partP. have [/eqP defS tiP _] := and3P partP. have trXP: is_transversal X P S := transversalP partP. have sXS: X \subset S := transversal_sub trXP. split=> // [x y Xx Xy /= | x Sx]. have Sx := subsetP sXS x Xx. rewrite -(inj_in_eq (pblock_inj trXP)) // eq_pblock ?defS //. by rewrite (def_pblock tiP (imset_f _ Sx)) ?orbit_refl. have /imsetP[y Xy defxG]: orbit to G x \in pblock P @: X. by rewrite (pblock_transversal trXP) ?imset_f. suffices /orbitP[a Ga def_y]: y \in orbit to G x by exists a; rewrite ?def_y. by rewrite defxG mem_pblock defS (subsetP sXS). Qed. Lemma group_set_astab S : group_set 'C(S | to). Proof. apply/group_setP; split=> [|a b cSa cSb]. by rewrite !inE group1; apply/subsetP=> x _; rewrite inE act1. rewrite !inE groupM ?(@astab_dom _ _ _ to S) //; apply/subsetP=> x Sx. by rewrite inE actMin ?(@astab_dom _ _ _ to S) ?(astab_act _ Sx). Qed. Canonical astab_group S := group (group_set_astab S). Lemma afix_gen_in A : A \subset D -> 'Fix_to(<<A>>) = 'Fix_to(A). Proof. move=> sAD; apply/eqP; rewrite eqEsubset afixS ?sub_gen //=. by rewrite -astabCin gen_subG ?astabCin. Qed. Lemma afix_cycle_in a : a \in D -> 'Fix_to(<[a]>) = 'Fix_to[a]. Proof. by move=> Da; rewrite afix_gen_in ?sub1set. Qed. Lemma afixYin A B : A \subset D -> B \subset D -> 'Fix_to(A <*> B) = 'Fix_to(A) :&: 'Fix_to(B). Proof. by move=> sAD sBD; rewrite afix_gen_in ?afixU // subUset sAD. Qed. Lemma afixMin G H : G \subset D -> H \subset D -> 'Fix_to(G * H) = 'Fix_to(G) :&: 'Fix_to(H). Proof. by move=> sGD sHD; rewrite -afix_gen_in ?mul_subG // genM_join afixYin. Qed. Lemma sub_astab1_in A x : A \subset D -> (A \subset 'C[x | to]) = (x \in 'Fix_to(A)). Proof. by move=> sAD; rewrite astabCin ?sub1set. Qed. Lemma group_set_astabs S : group_set 'N(S | to). Proof. apply/group_setP; split=> [|a b cSa cSb]. by rewrite !inE group1; apply/subsetP=> x Sx; rewrite inE act1. rewrite !inE groupM ?(@astabs_dom _ _ _ to S) //; apply/subsetP=> x Sx. by rewrite inE actMin ?(@astabs_dom _ _ _ to S) ?astabs_act. Qed. Canonical astabs_group S := group (group_set_astabs S). Lemma astab_norm S : 'N(S | to) \subset 'N('C(S | to)). Proof. apply/subsetP=> a nSa; rewrite inE sub_conjg; apply/subsetP=> b cSb. have [Da Db] := (astabs_dom nSa, astab_dom cSb). rewrite mem_conjgV !inE groupJ //; apply/subsetP=> x Sx. rewrite inE !actMin ?groupM ?groupV //. by rewrite (astab_act cSb) ?actKVin ?astabs_act ?groupV. Qed. Lemma astab_normal S : 'C(S | to) <| 'N(S | to). Proof. by rewrite /normal astab_sub astab_norm. Qed. Lemma acts_sub_orbit G S x : [acts G, on S | to] -> (orbit to G x \subset S) = (x \in S). Proof. move/acts_act=> GactS. apply/subsetP/idP=> [| Sx y]; first by apply; apply: orbit_refl. by case/orbitP=> a Ga <-{y}; rewrite GactS. Qed. Lemma acts_orbit G x : G \subset D -> [acts G, on orbit to G x | to]. Proof. move/subsetP=> sGD; apply/subsetP=> a Ga; rewrite !inE sGD //. apply/subsetP=> _ /imsetP[b Gb ->]. by rewrite inE -actMin ?sGD // imset_f ?groupM. Qed. Lemma acts_subnorm_fix A : [acts 'N_D(A), on 'Fix_to(D :&: A) | to]. Proof. apply/subsetP=> a nAa; have [Da _] := setIP nAa; rewrite !inE Da. apply/subsetP=> x Cx /[1!inE]; apply/afixP=> b DAb. have [Db _]:= setIP DAb; rewrite -actMin // conjgCV actMin ?groupJ ?groupV //. by rewrite /= (afixP Cx) // memJ_norm // groupV (subsetP (normsGI _ _) _ nAa). Qed. Lemma atrans_orbit G x : [transitive G, on orbit to G x | to]. Proof. by apply: imset_f; apply: orbit_refl. Qed. Section OrbitStabilizer. Variables (G : {group aT}) (x : rT). Hypothesis sGD : G \subset D. Let ssGD := subsetP sGD. Lemma amove_act a : a \in G -> amove to G x (to x a) = 'C_G[x | to] :* a. Proof. move=> Ga; apply/setP=> b; have Da := ssGD Ga. rewrite mem_rcoset !(inE, sub1set) !groupMr ?groupV //. by case Gb: (b \in G); rewrite //= actMin ?groupV ?ssGD ?(canF_eq (actKVin Da)). Qed. Lemma amove_orbit : amove to G x @: orbit to G x = rcosets 'C_G[x | to] G. Proof. apply/setP => Ha; apply/imsetP/rcosetsP=> [[y] | [a Ga ->]]. by case/imsetP=> b Gb -> ->{Ha y}; exists b => //; rewrite amove_act. by rewrite -amove_act //; exists (to x a); first apply: mem_orbit. Qed. Lemma amoveK : {in orbit to G x, cancel (amove to G x) (fun Ca => to x (repr Ca))}. Proof. move=> _ /orbitP[a Ga <-]; rewrite amove_act //= -[G :&: _]/(gval _). case: repr_rcosetP => b; rewrite !(inE, sub1set)=> /and3P[Gb _ xbx]. by rewrite actMin ?ssGD ?(eqP xbx). Qed. Lemma orbit_stabilizer : orbit to G x = [set to x (repr Ca) | Ca in rcosets 'C_G[x | to] G]. Proof. rewrite -amove_orbit -imset_comp /=; apply/setP=> z. by apply/idP/imsetP=> [xGz | [y xGy ->]]; first exists z; rewrite /= ?amoveK. Qed. Lemma act_reprK : {in rcosets 'C_G[x | to] G, cancel (to x \o repr) (amove to G x)}. Proof. move=> _ /rcosetsP[a Ga ->] /=; rewrite amove_act ?rcoset_repr //. rewrite -[G :&: _]/(gval _); case: repr_rcosetP => b /setIP[Gb _]. exact: groupM. Qed. End OrbitStabilizer. Lemma card_orbit_in G x : G \subset D -> #|orbit to G x| = #|G : 'C_G[x | to]|. Proof. move=> sGD; rewrite orbit_stabilizer 1?card_in_imset //. exact: can_in_inj (act_reprK _). Qed. Lemma card_orbit_in_stab G x : G \subset D -> (#|orbit to G x| * #|'C_G[x | to]|)%N = #|G|. Proof. by move=> sGD; rewrite mulnC card_orbit_in ?Lagrange ?subsetIl. Qed. Lemma acts_sum_card_orbit G S : [acts G, on S | to] -> \sum_(T in orbit to G @: S) #|T| = #|S|. Proof. by move/orbit_partition/card_partition. Qed. Lemma astab_setact_in S a : a \in D -> 'C(to^* S a | to) = 'C(S | to) :^ a. Proof. move=> Da; apply/setP=> b; rewrite mem_conjg !inE -mem_conjg conjGid //. apply: andb_id2l => Db; rewrite sub_imset_pre; apply: eq_subset_r => x. by rewrite !inE !actMin ?groupM ?groupV // invgK (canF_eq (actKVin Da)). Qed. Lemma astab1_act_in x a : a \in D -> 'C[to x a | to] = 'C[x | to] :^ a. Proof. by move=> Da; rewrite -astab_setact_in // /setact imset_set1. Qed. Theorem Frobenius_Cauchy G S : [acts G, on S | to] -> \sum_(a in G) #|'Fix_(S | to)[a]| = (#|orbit to G @: S| * #|G|)%N. Proof. move=> GactS; have sGD := acts_dom GactS. transitivity (\sum_(a in G) \sum_(x in 'Fix_(S | to)[a]) 1%N). by apply: eq_bigr => a _; rewrite -sum1_card. rewrite (exchange_big_dep [in S]) /= => [|a x _]; last by case/setIP. rewrite (set_partition_big _ (orbit_partition GactS)) -sum_nat_const /=. apply: eq_bigr => _ /imsetP[x Sx ->]. rewrite -(card_orbit_in_stab x sGD) -sum_nat_const. apply: eq_bigr => y; rewrite orbit_in_sym // => /imsetP[a Ga defx]. rewrite defx astab1_act_in ?(subsetP sGD) //. rewrite -{2}(conjGid Ga) -conjIg cardJg -sum1_card setIA (setIidPl sGD). by apply: eq_bigl => b; rewrite !(sub1set, inE) -(acts_act GactS Ga) -defx Sx. Qed. Lemma atrans_dvd_index_in G S : G \subset D -> [transitive G, on S | to] -> #|S| %| #|G : 'C_G(S | to)|. Proof. move=> sGD /imsetP[x Sx {1}->]; rewrite card_orbit_in //. by rewrite indexgS // setIS // astabS // sub1set. Qed. Lemma atrans_dvd_in G S : G \subset D -> [transitive G, on S | to] -> #|S| %| #|G|. Proof. move=> sGD transG; apply: dvdn_trans (atrans_dvd_index_in sGD transG) _. exact: dvdn_indexg. Qed. Lemma atransPin G S : G \subset D -> [transitive G, on S | to] -> forall x, x \in S -> orbit to G x = S. Proof. by move=> sGD /imsetP[y _ ->] x; apply/orbit_in_eqP. Qed. Lemma atransP2in G S : G \subset D -> [transitive G, on S | to] -> {in S &, forall x y, exists2 a, a \in G & y = to x a}. Proof. by move=> sGD transG x y /(atransPin sGD transG) <- /imsetP. Qed. Lemma atrans_acts_in G S : G \subset D -> [transitive G, on S | to] -> [acts G, on S | to]. Proof. move=> sGD transG; apply/subsetP=> a Ga; rewrite !inE (subsetP sGD) //. by apply/subsetP=> x /(atransPin sGD transG) <-; rewrite inE imset_f. Qed. Lemma subgroup_transitivePin G H S x : x \in S -> H \subset G -> G \subset D -> [transitive G, on S | to] -> reflect ('C_G[x | to] * H = G) [transitive H, on S | to]. Proof. move=> Sx sHG sGD trG; have sHD := subset_trans sHG sGD. apply: (iffP idP) => [trH | defG]. rewrite group_modr //; apply/setIidPl/subsetP=> a Ga. have Sxa: to x a \in S by rewrite (acts_act (atrans_acts_in sGD trG)). have [b Hb xab]:= atransP2in sHD trH Sxa Sx. have Da := subsetP sGD a Ga; have Db := subsetP sHD b Hb. rewrite -(mulgK b a) mem_mulg ?groupV // !inE groupM //= sub1set inE. by rewrite actMin -?xab. apply/imsetP; exists x => //; apply/setP=> y; rewrite -(atransPin sGD trG Sx). apply/imsetP/imsetP=> [] [a]; last by exists a; first apply: (subsetP sHG). rewrite -defG => /imset2P[c b /setIP[_ cxc] Hb ->] ->. exists b; rewrite ?actMin ?(astab_dom cxc) ?(subsetP sHD) //. by rewrite (astab_act cxc) ?inE. Qed. End PartialAction. Arguments orbit_transversal {aT D%_g rT} to%_act A%_g S%_g. Arguments orbit_in_eqP {aT D rT to G x y}. Arguments orbit1P {aT D rT to G x}. Arguments contra_orbit [aT D rT] to G [x y]. Notation "''C' ( S | to )" := (astab_group to S) : Group_scope. Notation "''C_' A ( S | to )" := (setI_group A 'C(S | to)) : Group_scope. Notation "''C_' ( A ) ( S | to )" := (setI_group A 'C(S | to)) (only parsing) : Group_scope. Notation "''C' [ x | to ]" := (astab_group to [set x%g]) : Group_scope. Notation "''C_' A [ x | to ]" := (setI_group A 'C[x | to]) : Group_scope. Notation "''C_' ( A ) [ x | to ]" := (setI_group A 'C[x | to]) (only parsing) : Group_scope. Notation "''N' ( S | to )" := (astabs_group to S) : Group_scope. Notation "''N_' A ( S | to )" := (setI_group A 'N(S | to)) : Group_scope. Section TotalActions. (* These lemmas are only established for total actions (domain = [set: rT]) *) Variable (aT : finGroupType) (rT : finType). Variable to : {action aT &-> rT}. Implicit Types (a b : aT) (x y z : rT) (A B : {set aT}) (G H : {group aT}). Implicit Type S : {set rT}. Lemma actM x a b : to x (a * b) = to (to x a) b. Proof. by rewrite actMin ?inE. Qed. Lemma actK : right_loop invg to. Proof. by move=> a; apply: actKin; rewrite inE. Qed. Lemma actKV : rev_right_loop invg to. Proof. by move=> a; apply: actKVin; rewrite inE. Qed. Lemma actX x a n : to x (a ^+ n) = iter n (to^~ a) x. Proof. by elim: n => [|n /= <-]; rewrite ?act1 // -actM expgSr. Qed. Lemma actCJ a b x : to (to x a) b = to (to x b) (a ^ b). Proof. by rewrite !actM actK. Qed. Lemma actCJV a b x : to (to x a) b = to (to x (b ^ a^-1)) a. Proof. by rewrite (actCJ _ a) conjgKV. Qed. Lemma orbit_sym G x y : (x \in orbit to G y) = (y \in orbit to G x). Proof. exact/orbit_in_sym/subsetT. Qed. Lemma orbit_trans G x y z : x \in orbit to G y -> y \in orbit to G z -> x \in orbit to G z. Proof. exact/orbit_in_trans/subsetT. Qed. Lemma orbit_eqP G x y : reflect (orbit to G x = orbit to G y) (x \in orbit to G y). Proof. exact/orbit_in_eqP/subsetT. Qed. Lemma orbit_transl G x y z : y \in orbit to G x -> (y \in orbit to G z) = (x \in orbit to G z). Proof. exact/orbit_in_transl/subsetT. Qed. Lemma orbit_act G a x: a \in G -> orbit to G (to x a) = orbit to G x. Proof. exact/orbit_act_in/subsetT. Qed. Lemma orbit_actr G a x y : a \in G -> (to y a \in orbit to G x) = (y \in orbit to G x). Proof. by move/mem_orbit/orbit_transl; apply. Qed. Lemma orbit_eq_mem G x y : (orbit to G x == orbit to G y) = (x \in orbit to G y). Proof. exact: sameP eqP (orbit_eqP G x y). Qed. Lemma orbit_inv A x y : (y \in orbit to A^-1 x) = (x \in orbit to A y). Proof. by rewrite orbit_inv_in ?subsetT. Qed. Lemma orbit_lcoset A a x : orbit to (a *: A) x = orbit to A (to x a). Proof. by rewrite orbit_lcoset_in ?subsetT ?inE. Qed. Lemma orbit_rcoset A a x y : (to y a \in orbit to (A :* a) x) = (y \in orbit to A x). Proof. by rewrite orbit_rcoset_in ?subsetT ?inE. Qed. Lemma orbit_conjsg A a x y : (to y a \in orbit to (A :^ a) (to x a)) = (y \in orbit to A x). Proof. by rewrite orbit_conjsg_in ?subsetT ?inE. Qed. Lemma astabP S a : reflect (forall x, x \in S -> to x a = x) (a \in 'C(S | to)). Proof. apply: (iffP idP) => [cSa x|cSa]; first exact: astab_act. by rewrite !inE; apply/subsetP=> x Sx; rewrite inE cSa. Qed. Lemma astab1P x a : reflect (to x a = x) (a \in 'C[x | to]). Proof. by rewrite !inE sub1set inE; apply: eqP. Qed. Lemma sub_astab1 A x : (A \subset 'C[x | to]) = (x \in 'Fix_to(A)). Proof. by rewrite sub_astab1_in ?subsetT. Qed. Lemma astabC A S : (A \subset 'C(S | to)) = (S \subset 'Fix_to(A)). Proof. by rewrite astabCin ?subsetT. Qed. Lemma afix_cycle a : 'Fix_to(<[a]>) = 'Fix_to[a]. Proof. by rewrite afix_cycle_in ?inE. Qed. Lemma afix_gen A : 'Fix_to(<<A>>) = 'Fix_to(A). Proof. by rewrite afix_gen_in ?subsetT. Qed. Lemma afixM G H : 'Fix_to(G * H) = 'Fix_to(G) :&: 'Fix_to(H). Proof. by rewrite afixMin ?subsetT. Qed. Lemma astabsP S a : reflect (forall x, (to x a \in S) = (x \in S)) (a \in 'N(S | to)). Proof. apply: (iffP idP) => [nSa x|nSa]; first exact: astabs_act. by rewrite !inE; apply/subsetP=> x; rewrite inE nSa. Qed. Lemma card_orbit G x : #|orbit to G x| = #|G : 'C_G[x | to]|. Proof. by rewrite card_orbit_in ?subsetT. Qed. Lemma dvdn_orbit G x : #|orbit to G x| %| #|G|. Proof. by rewrite card_orbit dvdn_indexg. Qed. Lemma card_orbit_stab G x : (#|orbit to G x| * #|'C_G[x | to]|)%N = #|G|. Proof. by rewrite mulnC card_orbit Lagrange ?subsetIl. Qed. Lemma actsP A S : reflect {acts A, on S | to} [acts A, on S | to]. Proof. apply: (iffP idP) => [nSA x|nSA]; first exact: acts_act. by apply/subsetP=> a Aa /[!inE]; apply/subsetP=> x; rewrite inE nSA. Qed. Arguments actsP {A S}. Lemma setact_orbit A x b : to^* (orbit to A x) b = orbit to (A :^ b) (to x b). Proof. apply/setP=> y; apply/idP/idP=> /imsetP[_ /imsetP[a Aa ->] ->{y}]. by rewrite actCJ mem_orbit ?memJ_conjg. by rewrite -actCJ mem_setact ?mem_orbit. Qed. Lemma astab_setact S a : 'C(to^* S a | to) = 'C(S | to) :^ a. Proof. apply/setP=> b; rewrite mem_conjg. apply/astabP/astabP=> stab x => [Sx|]. by rewrite conjgE invgK !actM stab ?actK //; apply/imsetP; exists x. by case/imsetP=> y Sy ->{x}; rewrite -actM conjgCV actM stab. Qed. Lemma astab1_act x a : 'C[to x a | to] = 'C[x | to] :^ a. Proof. by rewrite -astab_setact /setact imset_set1. Qed. Lemma atransP G S : [transitive G, on S | to] -> forall x, x \in S -> orbit to G x = S. Proof. by case/imsetP=> x _ -> y; apply/orbit_eqP. Qed. Lemma atransP2 G S : [transitive G, on S | to] -> {in S &, forall x y, exists2 a, a \in G & y = to x a}. Proof. by move=> GtrS x y /(atransP GtrS) <- /imsetP. Qed. Lemma atrans_acts G S : [transitive G, on S | to] -> [acts G, on S | to]. Proof. move=> GtrS; apply/subsetP=> a Ga; rewrite !inE. by apply/subsetP=> x /(atransP GtrS) <-; rewrite inE imset_f. Qed. Lemma atrans_supgroup G H S : G \subset H -> [transitive G, on S | to] -> [transitive H, on S | to] = [acts H, on S | to]. Proof. move=> sGH trG; apply/idP/idP=> [|actH]; first exact: atrans_acts. case/imsetP: trG => x Sx defS; apply/imsetP; exists x => //. by apply/eqP; rewrite eqEsubset acts_sub_orbit ?Sx // defS imsetS. Qed. Lemma atrans_acts_card G S : [transitive G, on S | to] = [acts G, on S | to] && (#|orbit to G @: S| == 1%N). Proof. apply/idP/andP=> [GtrS | [nSG]]. split; first exact: atrans_acts. rewrite ((_ @: S =P [set S]) _) ?cards1 // eqEsubset sub1set. apply/andP; split=> //; apply/subsetP=> _ /imsetP[x Sx ->]. by rewrite inE (atransP GtrS). rewrite eqn_leq andbC lt0n => /andP[/existsP[X /imsetP[x Sx X_Gx]]]. rewrite (cardD1 X) {X}X_Gx imset_f // ltnS leqn0 => /eqP GtrS. apply/imsetP; exists x => //; apply/eqP. rewrite eqEsubset acts_sub_orbit // Sx andbT. apply/subsetP=> y Sy; have:= card0_eq GtrS (orbit to G y). by rewrite !inE /= imset_f // andbT => /eqP <-; apply: orbit_refl. Qed. Lemma atrans_dvd G S : [transitive G, on S | to] -> #|S| %| #|G|. Proof. by case/imsetP=> x _ ->; apply: dvdn_orbit. Qed. (* This is Aschbacher (5.2) *) Lemma acts_fix_norm A B : A \subset 'N(B) -> [acts A, on 'Fix_to(B) | to]. Proof. move=> nAB; have:= acts_subnorm_fix to B; rewrite !setTI. exact: subset_trans. Qed. Lemma faithfulP A S : reflect (forall a, a \in A -> {in S, to^~ a =1 id} -> a = 1) [faithful A, on S | to]. Proof. apply: (iffP subsetP) => [Cto1 a Aa Ca | Cto1 a]. by apply/set1P; rewrite Cto1 // inE Aa; apply/astabP. by case/setIP=> Aa /astabP Ca; apply/set1P; apply: Cto1. Qed. (* This is the first part of Aschbacher (5.7) *) Lemma astab_trans_gcore G S u : [transitive G, on S | to] -> u \in S -> 'C(S | to) = gcore 'C[u | to] G. Proof. move=> transG Su; apply/eqP; rewrite eqEsubset. rewrite gcore_max ?astabS ?sub1set //=; last first. exact: subset_trans (atrans_acts transG) (astab_norm _ _). apply/subsetP=> x cSx; apply/astabP=> uy. case/(atransP2 transG Su) => y Gy ->{uy}. by apply/astab1P; rewrite astab1_act (bigcapP cSx). Qed. (* This is Aschbacher (5.20) *) Theorem subgroup_transitiveP G H S x : x \in S -> H \subset G -> [transitive G, on S | to] -> reflect ('C_G[x | to] * H = G) [transitive H, on S | to]. Proof. by move=> Sx sHG; apply: subgroup_transitivePin (subsetT G). Qed. (* This is Aschbacher (5.21) *) Lemma trans_subnorm_fixP x G H S : let C := 'C_G[x | to] in let T := 'Fix_(S | to)(H) in [transitive G, on S | to] -> x \in S -> H \subset C -> reflect ((H :^: G) ::&: C = H :^: C) [transitive 'N_G(H), on T | to]. Proof. move=> C T trGS Sx sHC; have actGS := acts_act (atrans_acts trGS). have:= sHC; rewrite subsetI sub_astab1 => /andP[sHG cHx]. have Tx: x \in T by rewrite inE Sx. apply: (iffP idP) => [trN | trC]. apply/setP=> Ha; apply/setIdP/imsetP=> [[]|[a Ca ->{Ha}]]; last first. by rewrite conj_subG //; case/setIP: Ca => Ga _; rewrite imset_f. case/imsetP=> a Ga ->{Ha}; rewrite subsetI !sub_conjg => /andP[_ sHCa]. have Txa: to x a^-1 \in T. by rewrite inE -sub_astab1 astab1_act actGS ?Sx ?groupV. have [b] := atransP2 trN Tx Txa; case/setIP=> Gb nHb cxba. exists (b * a); last by rewrite conjsgM (normP nHb). by rewrite inE groupM //; apply/astab1P; rewrite actM -cxba actKV. apply/imsetP; exists x => //; apply/setP=> y; apply/idP/idP=> [Ty|]. have [Sy cHy]:= setIP Ty; have [a Ga defy] := atransP2 trGS Sx Sy. have: H :^ a^-1 \in H :^: C. rewrite -trC inE subsetI imset_f 1?conj_subG ?groupV // sub_conjgV. by rewrite -astab1_act -defy sub_astab1. case/imsetP=> b /setIP[Gb /astab1P cxb] defHb. rewrite defy -{1}cxb -actM mem_orbit // inE groupM //. by apply/normP; rewrite conjsgM -defHb conjsgKV. case/imsetP=> a /setIP[Ga nHa] ->{y}. by rewrite inE actGS // Sx (acts_act (acts_fix_norm _) nHa). Qed. End TotalActions. Arguments astabP {aT rT to S a}. Arguments orbit_eqP {aT rT to G x y}. Arguments astab1P {aT rT to x a}. Arguments astabsP {aT rT to S a}. Arguments atransP {aT rT to G S}. Arguments actsP {aT rT to A S}. Arguments faithfulP {aT rT to A S}. Section Restrict. Variables (aT : finGroupType) (D : {set aT}) (rT : Type). Variables (to : action D rT) (A : {set aT}). Definition ract of A \subset D := act to. Variable sAD : A \subset D. Lemma ract_is_action : is_action A (ract sAD). Proof. rewrite /ract; case: to => f [injf fM]. by split=> // x; apply: (sub_in2 (subsetP sAD)). Qed. Canonical raction := Action ract_is_action. Lemma ractE : raction =1 to. Proof. by []. Qed. (* Other properties of raction need rT : finType; we defer them *) (* until after the definition of actperm. *) End Restrict. Notation "to \ sAD" := (raction to sAD) (at level 50) : action_scope. Section ActBy. Variables (aT : finGroupType) (D : {set aT}) (rT : finType). Definition actby_cond (A : {set aT}) R (to : action D rT) : Prop := [acts A, on R | to]. Definition actby A R to of actby_cond A R to := fun x a => if (x \in R) && (a \in A) then to x a else x. Variables (A : {group aT}) (R : {set rT}) (to : action D rT). Hypothesis nRA : actby_cond A R to. Lemma actby_is_action : is_action A (actby nRA). Proof. rewrite /actby; split=> [a x y | x a b Aa Ab /=]; last first. rewrite Aa Ab groupM // !andbT actMin ?(subsetP (acts_dom nRA)) //. by case Rx: (x \in R); rewrite ?(acts_act nRA) ?Rx. case Aa: (a \in A); rewrite ?andbF ?andbT //. case Rx: (x \in R); case Ry: (y \in R) => // eqxy; first exact: act_inj eqxy. by rewrite -eqxy (acts_act nRA Aa) Rx in Ry. by rewrite eqxy (acts_act nRA Aa) Ry in Rx. Qed. Canonical action_by := Action actby_is_action. Local Notation "<[nRA]>" := action_by : action_scope. Lemma actbyE x a : x \in R -> a \in A -> <[nRA]>%act x a = to x a. Proof. by rewrite /= /actby => -> ->. Qed. Lemma afix_actby B : 'Fix_<[nRA]>(B) = ~: R :|: 'Fix_to(A :&: B). Proof. apply/setP=> x; rewrite !inE /= /actby. case: (x \in R); last by apply/subsetP=> a _ /[!inE]. apply/subsetP/subsetP=> [cBx a | cABx a Ba] /[!inE]. by case/andP=> Aa /cBx; rewrite inE Aa. by case: ifP => //= Aa; have:= cABx a; rewrite !inE Aa => ->. Qed. Lemma astab_actby S : 'C(S | <[nRA]>) = 'C_A(R :&: S | to). Proof. apply/setP=> a; rewrite setIA (setIidPl (acts_dom nRA)) !inE. case Aa: (a \in A) => //=; apply/subsetP/subsetP=> cRSa x => [|Sx]. by case/setIP=> Rx /cRSa; rewrite !inE actbyE. by have:= cRSa x; rewrite !inE /= /actby Aa Sx; case: (x \in R) => //; apply. Qed. Lemma astabs_actby S : 'N(S | <[nRA]>) = 'N_A(R :&: S | to). Proof. apply/setP=> a; rewrite setIA (setIidPl (acts_dom nRA)) !inE. case Aa: (a \in A) => //=; apply/subsetP/subsetP=> nRSa x => [|Sx]. by case/setIP=> Rx /nRSa; rewrite !inE actbyE ?(acts_act nRA) ?Rx. have:= nRSa x; rewrite !inE /= /actby Aa Sx ?(acts_act nRA) //. by case: (x \in R) => //; apply. Qed. Lemma acts_actby (B : {set aT}) S : [acts B, on S | <[nRA]>] = (B \subset A) && [acts B, on R :&: S | to]. Proof. by rewrite astabs_actby subsetI. Qed. End ActBy. Notation "<[ nRA ] >" := (action_by nRA) : action_scope. Section SubAction. Variables (aT : finGroupType) (D : {group aT}). Variables (rT : finType) (sP : pred rT) (sT : subFinType sP) (to : action D rT). Implicit Type A : {set aT}. Implicit Type u : sT. Implicit Type S : {set sT}. Definition subact_dom := 'N([set x | sP x] | to). Canonical subact_dom_group := [group of subact_dom]. Implicit Type Na : {a | a \in subact_dom}. Lemma sub_act_proof u Na : sP (to (val u) (val Na)). Proof. by case: Na => a /= /(astabs_act (val u)); rewrite !inE valP. Qed. Definition subact u a := if insub a is Some Na then Sub _ (sub_act_proof u Na) else u. Lemma val_subact u a : val (subact u a) = if a \in subact_dom then to (val u) a else val u. Proof. by rewrite /subact -if_neg; case: insubP => [Na|] -> //=; rewrite SubK => ->. Qed. Lemma subact_is_action : is_action subact_dom subact. Proof. split=> [a u v eq_uv | u a b Na Nb]; apply: val_inj. move/(congr1 val): eq_uv; rewrite !val_subact. by case: (a \in _); first move/act_inj. have Da := astabs_dom Na; have Db := astabs_dom Nb. by rewrite !val_subact Na Nb groupM ?actMin. Qed. Canonical subaction := Action subact_is_action. Lemma astab_subact S : 'C(S | subaction) = subact_dom :&: 'C(val @: S | to). Proof. apply/setP=> a; rewrite inE in_setI; apply: andb_id2l => sDa. have [Da _] := setIP sDa; rewrite !inE Da. apply/subsetP/subsetP=> [cSa _ /imsetP[x Sx ->] | cSa x Sx] /[!inE]. by have:= cSa x Sx; rewrite inE -val_eqE val_subact sDa. by have:= cSa _ (imset_f val Sx); rewrite inE -val_eqE val_subact sDa. Qed. Lemma astabs_subact S : 'N(S | subaction) = subact_dom :&: 'N(val @: S | to). Proof. apply/setP=> a; rewrite inE in_setI; apply: andb_id2l => sDa. have [Da _] := setIP sDa; rewrite !inE Da. apply/subsetP/subsetP=> [nSa _ /imsetP[x Sx ->] | nSa x Sx] /[!inE]. by have /[1!inE]/(imset_f val) := nSa x Sx; rewrite val_subact sDa. have /[1!inE]/imsetP[y Sy def_y] := nSa _ (imset_f val Sx). by rewrite ((_ a =P y) _) // -val_eqE val_subact sDa def_y. Qed. Lemma afix_subact A : A \subset subact_dom -> 'Fix_subaction(A) = val @^-1: 'Fix_to(A). Proof. move/subsetP=> sAD; apply/setP=> u. rewrite !inE !(sameP setIidPl eqP); congr (_ == A). apply/setP=> a /[!inE]; apply: andb_id2l => Aa. by rewrite -val_eqE val_subact sAD. Qed. End SubAction. Notation "to ^?" := (subaction _ to) (format "to ^?") : action_scope. Section QuotientAction. Variables (aT : finGroupType) (D : {group aT}) (rT : finGroupType). Variables (to : action D rT) (H : {group rT}). Definition qact_dom := 'N(rcosets H 'N(H) | to^*). Canonical qact_dom_group := [group of qact_dom]. Local Notation subdom := (subact_dom (coset_range H) to^*). Fact qact_subdomE : subdom = qact_dom. Proof. by congr 'N(_|_); apply/setP=> Hx; rewrite !inE genGid. Qed. Lemma qact_proof : qact_dom \subset subdom. Proof. by rewrite qact_subdomE. Qed. Definition qact : coset_of H -> aT -> coset_of H := act (to^*^? \ qact_proof). Canonical quotient_action := [action of qact]. Lemma acts_qact_dom : [acts qact_dom, on 'N(H) | to]. Proof. apply/subsetP=> a nNa; rewrite !inE (astabs_dom nNa); apply/subsetP=> x Nx. have: H :* x \in rcosets H 'N(H) by rewrite -rcosetE imset_f. rewrite inE -(astabs_act _ nNa) => /rcosetsP[y Ny defHy]. have: to x a \in H :* y by rewrite -defHy (imset_f (to^~a)) ?rcoset_refl. by apply: subsetP; rewrite mul_subG ?sub1set ?normG. Qed. Lemma qactEcond x a : x \in 'N(H) -> quotient_action (coset H x) a = coset H (if a \in qact_dom then to x a else x). Proof. move=> Nx; apply: val_inj; rewrite val_subact //= qact_subdomE. have: H :* x \in rcosets H 'N(H) by rewrite -rcosetE imset_f. case nNa: (a \in _); rewrite // -(astabs_act _ nNa). rewrite !val_coset ?(acts_act acts_qact_dom nNa) //=. case/rcosetsP=> y Ny defHy; rewrite defHy; apply: rcoset_eqP. by rewrite rcoset_sym -defHy (imset_f (_^~_)) ?rcoset_refl. Qed. Lemma qactE x a : x \in 'N(H) -> a \in qact_dom -> quotient_action (coset H x) a = coset H (to x a). Proof. by move=> Nx nNa; rewrite qactEcond ?nNa. Qed. Lemma acts_quotient (A : {set aT}) (B : {set rT}) : A \subset 'N_qact_dom(B | to) -> [acts A, on B / H | quotient_action]. Proof. move=> nBA; apply: subset_trans {A}nBA _; apply/subsetP=> a /setIP[dHa nBa]. rewrite inE dHa inE; apply/subsetP=> _ /morphimP[x nHx Bx ->]. rewrite inE /= qactE //. by rewrite mem_morphim ?(acts_act acts_qact_dom) ?(astabs_act _ nBa). Qed. Lemma astabs_quotient (G : {group rT}) : H <| G -> 'N(G / H | quotient_action) = 'N_qact_dom(G | to). Proof. move=> nsHG; have [_ nHG] := andP nsHG. apply/eqP; rewrite eqEsubset acts_quotient // andbT. apply/subsetP=> a nGa; have dHa := astabs_dom nGa; have [Da _]:= setIdP dHa. rewrite inE dHa 2!inE Da; apply/subsetP=> x Gx; have nHx := subsetP nHG x Gx. rewrite -(quotientGK nsHG) 2!inE (acts_act acts_qact_dom) ?nHx //= inE. by rewrite -qactE // (astabs_act _ nGa) mem_morphim. Qed. End QuotientAction. Notation "to / H" := (quotient_action to H) : action_scope. Section ModAction. Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable to : action D rT. Implicit Types (G : {group aT}) (S : {set rT}). Section GenericMod. Variable H : {group aT}. Local Notation dom := 'N_D(H). Local Notation range := 'Fix_to(D :&: H). Let acts_dom : {acts dom, on range | to} := acts_act (acts_subnorm_fix to H). Definition modact x (Ha : coset_of H) := if x \in range then to x (repr (D :&: Ha)) else x. Lemma modactEcond x a : a \in dom -> modact x (coset H a) = (if x \in range then to x a else x). Proof. case/setIP=> Da Na; case: ifP => Cx; rewrite /modact Cx //. rewrite val_coset // -group_modr ?sub1set //. case: (repr _) / (repr_rcosetP (D :&: H) a) => a' Ha'. by rewrite actMin ?(afixP Cx _ Ha') //; case/setIP: Ha'. Qed. Lemma modactE x a : a \in D -> a \in 'N(H) -> x \in range -> modact x (coset H a) = to x a. Proof. by move=> Da Na Rx; rewrite modactEcond ?Rx // inE Da. Qed. Lemma modact_is_action : is_action (D / H) modact. Proof. split=> [Ha x y | x Ha Hb]; last first. case/morphimP=> a Na Da ->{Ha}; case/morphimP=> b Nb Db ->{Hb}. rewrite -morphM //= !modactEcond // ?groupM ?(introT setIP _) //. by case: ifP => Cx; rewrite ?(acts_dom, Cx, actMin, introT setIP _). case: (set_0Vmem (D :&: Ha)) => [Da0 | [a /setIP[Da NHa]]]. by rewrite /modact Da0 repr_set0 !act1 !if_same. have Na := subsetP (coset_norm _) _ NHa. have NDa: a \in 'N_D(H) by rewrite inE Da. rewrite -(coset_mem NHa) !modactEcond //. do 2![case: ifP]=> Cy Cx // eqxy; first exact: act_inj eqxy. by rewrite -eqxy acts_dom ?Cx in Cy. by rewrite eqxy acts_dom ?Cy in Cx. Qed. Canonical mod_action := Action modact_is_action. Section Stabilizers. Variable S : {set rT}. Hypothesis cSH : H \subset 'C(S | to). Let fixSH : S \subset 'Fix_to(D :&: H). Proof. by rewrite -astabCin ?subsetIl // subIset ?cSH ?orbT. Qed. Lemma astabs_mod : 'N(S | mod_action) = 'N(S | to) / H. Proof. apply/setP=> Ha; apply/idP/morphimP=> [nSa | [a nHa nSa ->]]. case/morphimP: (astabs_dom nSa) => a nHa Da defHa. exists a => //; rewrite !inE Da; apply/subsetP=> x Sx; rewrite !inE. by have:= Sx; rewrite -(astabs_act x nSa) defHa /= modactE ?(subsetP fixSH). have Da := astabs_dom nSa; rewrite !inE mem_quotient //; apply/subsetP=> x Sx. by rewrite !inE /= modactE ?(astabs_act x nSa) ?(subsetP fixSH). Qed. Lemma astab_mod : 'C(S | mod_action) = 'C(S | to) / H. Proof. apply/setP=> Ha; apply/idP/morphimP=> [cSa | [a nHa cSa ->]]. case/morphimP: (astab_dom cSa) => a nHa Da defHa. exists a => //; rewrite !inE Da; apply/subsetP=> x Sx; rewrite !inE. by rewrite -{2}[x](astab_act cSa) // defHa /= modactE ?(subsetP fixSH). have Da := astab_dom cSa; rewrite !inE mem_quotient //; apply/subsetP=> x Sx. by rewrite !inE /= modactE ?(astab_act cSa) ?(subsetP fixSH). Qed. End Stabilizers. Lemma afix_mod G S : H \subset 'C(S | to) -> G \subset 'N_D(H) -> 'Fix_(S | mod_action)(G / H) = 'Fix_(S | to)(G). Proof. move=> cSH /subsetIP[sGD nHG]. apply/eqP; rewrite eqEsubset !subsetI !subsetIl /= -!astabCin ?quotientS //. have cfixH F: H \subset 'C(S :&: F | to). by rewrite (subset_trans cSH) // astabS ?subsetIl. rewrite andbC astab_mod ?quotientS //=; last by rewrite astabCin ?subsetIr. by rewrite -(quotientSGK nHG) //= -astab_mod // astabCin ?quotientS ?subsetIr. Qed. End GenericMod. Lemma modact_faithful G S : [faithful G / 'C_G(S | to), on S | mod_action 'C_G(S | to)]. Proof. rewrite /faithful astab_mod ?subsetIr //=. by rewrite -quotientIG ?subsetIr ?trivg_quotient. Qed. End ModAction. Notation "to %% H" := (mod_action to H) : action_scope. Section ActPerm. (* Morphism to permutations induced by an action. *) Variables (aT : finGroupType) (D : {set aT}) (rT : finType). Variable to : action D rT. Definition actperm a := perm (act_inj to a). Lemma actpermM : {in D &, {morph actperm : a b / a * b}}. Proof. by move=> a b Da Db; apply/permP=> x; rewrite permM !permE actMin. Qed. Canonical actperm_morphism := Morphism actpermM. Lemma actpermE a x : actperm a x = to x a. Proof. by rewrite permE. Qed. Lemma actpermK x a : aperm x (actperm a) = to x a. Proof. exact: actpermE. Qed. Lemma ker_actperm : 'ker actperm = 'C(setT | to). Proof. congr (_ :&: _); apply/setP=> a /[!inE]/=. apply/eqP/subsetP=> [a1 x _ | a1]; first by rewrite inE -actpermE a1 perm1. by apply/permP=> x; apply/eqP; have:= a1 x; rewrite !inE actpermE perm1 => ->. Qed. End ActPerm. Section RestrictActionTheory. Variables (aT : finGroupType) (D : {set aT}) (rT : finType). Variables (to : action D rT). Lemma faithful_isom (A : {group aT}) S (nSA : actby_cond A S to) : [faithful A, on S | to] -> isom A (actperm <[nSA]> @* A) (actperm <[nSA]>). Proof. by move=> ffulAS; apply/isomP; rewrite ker_actperm astab_actby setIT. Qed. Variables (A : {set aT}) (sAD : A \subset D). Lemma ractpermE : actperm (to \ sAD) =1 actperm to. Proof. by move=> a; apply/permP=> x; rewrite !permE. Qed. Lemma afix_ract B : 'Fix_(to \ sAD)(B) = 'Fix_to(B). Proof. by []. Qed. Lemma astab_ract S : 'C(S | to \ sAD) = 'C_A(S | to). Proof. by rewrite setIA (setIidPl sAD). Qed. Lemma astabs_ract S : 'N(S | to \ sAD) = 'N_A(S | to). Proof. by rewrite setIA (setIidPl sAD). Qed. Lemma acts_ract (B : {set aT}) S : [acts B, on S | to \ sAD] = (B \subset A) && [acts B, on S | to]. Proof. by rewrite astabs_ract subsetI. Qed. End RestrictActionTheory. Section MorphAct. (* Action induced by a morphism to permutations. *) Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable phi : {morphism D >-> {perm rT}}. Definition mact x a := phi a x. Lemma mact_is_action : is_action D mact. Proof. split=> [a x y | x a b Da Db]; first exact: perm_inj. by rewrite /mact morphM //= permM. Qed. Canonical morph_action := Action mact_is_action. Lemma mactE x a : morph_action x a = phi a x. Proof. by []. Qed. Lemma injm_faithful : 'injm phi -> [faithful D, on setT | morph_action]. Proof. move/injmP=> phi_inj; apply/subsetP=> a /setIP[Da /astab_act a1]. apply/set1P/phi_inj => //; apply/permP=> x. by rewrite morph1 perm1 -mactE a1 ?inE. Qed. Lemma perm_mact a : actperm morph_action a = phi a. Proof. by apply/permP=> x; rewrite permE. Qed. End MorphAct. Notation "<< phi >>" := (morph_action phi) : action_scope. Section CompAct. Variables (gT aT : finGroupType) (rT : finType). Variables (D : {set aT}) (to : action D rT). Variables (B : {set gT}) (f : {morphism B >-> aT}). Definition comp_act x e := to x (f e). Lemma comp_is_action : is_action (f @*^-1 D) comp_act. Proof. split=> [e | x e1 e2]; first exact: act_inj. move=> /morphpreP[Be1 Dfe1] /morphpreP[Be2 Dfe2]. by rewrite /comp_act morphM ?actMin. Qed. Canonical comp_action := Action comp_is_action. Lemma comp_actE x e : comp_action x e = to x (f e). Proof. by []. Qed. Lemma afix_comp (A : {set gT}) : A \subset B -> 'Fix_comp_action(A) = 'Fix_to(f @* A). Proof. move=> sAB; apply/setP=> x; rewrite !inE /morphim (setIidPr sAB). apply/subsetP/subsetP; first by move=> + _ /imsetP[a + ->] => /[apply]/[!inE]. by move=> + a Aa => /(_ (f a)); rewrite !inE imset_f// => ->. Qed. Lemma astab_comp S : 'C(S | comp_action) = f @*^-1 'C(S | to). Proof. by apply/setP=> x; rewrite !inE -andbA. Qed. Lemma astabs_comp S : 'N(S | comp_action) = f @*^-1 'N(S | to). Proof. by apply/setP=> x; rewrite !inE -andbA. Qed. End CompAct. Notation "to \o f" := (comp_action to f) : action_scope. Section PermAction. (* Natural action of permutation groups. *) Variable rT : finType. Local Notation gT := {perm rT}. Implicit Types a b c : gT. Lemma aperm_is_action : is_action setT (@aperm rT). Proof. by apply: is_total_action => [x|x a b]; rewrite apermE (perm1, permM). Qed. Canonical perm_action := Action aperm_is_action. Lemma porbitE a : porbit a = orbit perm_action <[a]>%g. Proof. by rewrite unlock. Qed. Lemma perm_act1P a : reflect (forall x, aperm x a = x) (a == 1). Proof. apply: (iffP eqP) => [-> x | a1]; first exact: act1. by apply/permP=> x; rewrite -apermE a1 perm1. Qed. Lemma perm_faithful A : [faithful A, on setT | perm_action]. Proof. apply/subsetP=> a /setIP[Da crTa]. by apply/set1P; apply/permP=> x; rewrite -apermE perm1 (astabP crTa) ?inE. Qed. Lemma actperm_id p : actperm perm_action p = p. Proof. by apply/permP=> x; rewrite permE. Qed. End PermAction. Arguments perm_act1P {rT a}. Notation "'P" := (perm_action _) : action_scope. Section ActpermOrbits. Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable to : action D rT. Lemma orbit_morphim_actperm (A : {set aT}) : A \subset D -> orbit 'P (actperm to @* A) =1 orbit to A. Proof. move=> sAD x; rewrite morphimEsub // /orbit -imset_comp. by apply: eq_imset => a //=; rewrite actpermK. Qed. Lemma porbit_actperm (a : aT) : a \in D -> porbit (actperm to a) =1 orbit to <[a]>. Proof. move=> Da x. by rewrite porbitE -orbit_morphim_actperm ?cycle_subG ?morphim_cycle. Qed. End ActpermOrbits. Section RestrictPerm. Variables (T : finType) (S : {set T}). Definition restr_perm := actperm (<[subxx 'N(S | 'P)]>). Canonical restr_perm_morphism := [morphism of restr_perm]. Lemma restr_perm_on p : perm_on S (restr_perm p). Proof. apply/subsetP=> x; apply: contraR => notSx. by rewrite permE /= /actby (negPf notSx). Qed. Lemma triv_restr_perm p : p \notin 'N(S | 'P) -> restr_perm p = 1. Proof. move=> not_nSp; apply/permP=> x. by rewrite !permE /= /actby (negPf not_nSp) andbF. Qed. Lemma restr_permE : {in 'N(S | 'P) & S, forall p, restr_perm p =1 p}. Proof. by move=> y x nSp Sx; rewrite /= actpermE actbyE. Qed. Lemma ker_restr_perm : 'ker restr_perm = 'C(S | 'P). Proof. by rewrite ker_actperm astab_actby setIT (setIidPr (astab_sub _ _)). Qed. Lemma im_restr_perm p : restr_perm p @: S = S. Proof. exact: im_perm_on (restr_perm_on p). Qed. Lemma restr_perm_commute s : commute (restr_perm s) s. Proof. have [sC|/triv_restr_perm->] := boolP (s \in 'N(S | 'P)); last first. exact: (commute_sym (commute1 _)). apply/permP => x; have /= xsS := astabsP sC x; rewrite !permM. have [xS|xNS] := boolP (x \in S); first by rewrite ?(restr_permE) ?xsS. by rewrite !(out_perm (restr_perm_on _)) ?xsS. Qed. End RestrictPerm. Section Symmetry. Variables (T : finType) (S : {set T}). Lemma SymE : Sym S = 'C(~: S | 'P). Proof. apply/setP => s; rewrite inE; apply/idP/astabP => [sS x|/= S_id]. by rewrite inE /= apermE => /out_perm->. by apply/subsetP => x; move=> /(contra_neqN (S_id _)); rewrite inE negbK. Qed. End Symmetry. Section AutIn. Variable gT : finGroupType. Definition Aut_in A (B : {set gT}) := 'N_A(B | 'P) / 'C_A(B | 'P). Variables G H : {group gT}. Hypothesis sHG: H \subset G. Lemma Aut_restr_perm a : a \in Aut G -> restr_perm H a \in Aut H. Proof. move=> AutGa. case nHa: (a \in 'N(H | 'P)); last by rewrite triv_restr_perm ?nHa ?group1. rewrite inE restr_perm_on; apply/morphicP=> x y Hx Hy /=. by rewrite !restr_permE ?groupM // -(autmE AutGa) morphM ?(subsetP sHG). Qed. Lemma restr_perm_Aut : restr_perm H @* Aut G \subset Aut H. Proof. by apply/subsetP=> a'; case/morphimP=> a _ AutGa ->{a'}; apply: Aut_restr_perm. Qed. Lemma Aut_in_isog : Aut_in (Aut G) H \isog restr_perm H @* Aut G. Proof. rewrite /Aut_in -ker_restr_perm kerE -morphpreIdom -morphimIdom -kerE /=. by rewrite setIA (setIC _ (Aut G)) first_isog_loc ?subsetIr. Qed. Lemma Aut_sub_fullP : reflect (forall h : {morphism H >-> gT}, 'injm h -> h @* H = H -> exists g : {morphism G >-> gT}, [/\ 'injm g, g @* G = G & {in H, g =1 h}]) (Aut_in (Aut G) H \isog Aut H). Proof. rewrite (isog_transl _ Aut_in_isog) /=; set rG := _ @* _. apply: (iffP idP) => [iso_rG h injh hH| AutHinG]. have: aut injh hH \in rG; last case/morphimP=> g nHg AutGg def_g. suffices ->: rG = Aut H by apply: Aut_aut. by apply/eqP; rewrite eqEcard restr_perm_Aut /= (card_isog iso_rG). exists (autm_morphism AutGg); rewrite injm_autm im_autm; split=> // x Hx. by rewrite -(autE injh hH Hx) def_g actpermE actbyE. suffices ->: rG = Aut H by apply: isog_refl. apply/eqP; rewrite eqEsubset restr_perm_Aut /=. apply/subsetP=> h AutHh; have hH := im_autm AutHh. have [g [injg gG eq_gh]] := AutHinG _ (injm_autm AutHh) hH. have [Ng AutGg]: aut injg gG \in 'N(H | 'P) /\ aut injg gG \in Aut G. rewrite Aut_aut !inE; split=> //; apply/subsetP=> x Hx. by rewrite inE /= /aperm autE ?(subsetP sHG) // -hH eq_gh ?mem_morphim. apply/morphimP; exists (aut injg gG) => //; apply: (eq_Aut AutHh) => [|x Hx]. by rewrite (subsetP restr_perm_Aut) // mem_morphim. by rewrite restr_permE //= /aperm autE ?eq_gh ?(subsetP sHG). Qed. End AutIn. Arguments Aut_in {gT} A%_g B%_g. Section InjmAutIn. Variables (gT rT : finGroupType) (D G H : {group gT}) (f : {morphism D >-> rT}). Hypotheses (injf : 'injm f) (sGD : G \subset D) (sHG : H \subset G). Let sHD := subset_trans sHG sGD. Local Notation fGisom := (Aut_isom injf sGD). Local Notation fHisom := (Aut_isom injf sHD). Local Notation inH := (restr_perm H). Local Notation infH := (restr_perm (f @* H)). Lemma astabs_Aut_isom a : a \in Aut G -> (fGisom a \in 'N(f @* H | 'P)) = (a \in 'N(H | 'P)). Proof. move=> AutGa; rewrite !inE sub_morphim_pre // subsetI sHD /= /aperm. rewrite !(sameP setIidPl eqP) !eqEsubset !subsetIl; apply: eq_subset_r => x. rewrite !inE; apply: andb_id2l => Hx; have Gx: x \in G := subsetP sHG x Hx. have Dax: a x \in D by rewrite (subsetP sGD) // Aut_closed. by rewrite Aut_isomE // -!sub1set -morphim_set1 // injmSK ?sub1set. Qed. Lemma isom_restr_perm a : a \in Aut G -> fHisom (inH a) = infH (fGisom a). Proof. move=> AutGa; case nHa: (a \in 'N(H | 'P)); last first. by rewrite !triv_restr_perm ?astabs_Aut_isom ?nHa ?morph1. apply: (eq_Aut (Aut_Aut_isom injf sHD _)) => [|fx Hfx /=]. by rewrite (Aut_restr_perm (morphimS f sHG)) ?Aut_Aut_isom. have [x Dx Hx def_fx] := morphimP Hfx; have Gx := subsetP sHG x Hx. rewrite {1}def_fx Aut_isomE ?(Aut_restr_perm sHG) //. by rewrite !restr_permE ?astabs_Aut_isom // def_fx Aut_isomE. Qed. Lemma restr_perm_isom : isom (inH @* Aut G) (infH @* Aut (f @* G)) fHisom. Proof. apply: sub_isom; rewrite ?restr_perm_Aut ?injm_Aut_isom //=. rewrite -(im_Aut_isom injf sGD) -!morphim_comp. apply: eq_in_morphim; last exact: isom_restr_perm. (* TODO: investigate why rewrite does not match in the same order *) apply/setP=> a; rewrite in_setI [in RHS]in_setI; apply: andb_id2r => AutGa. (* the middle rewrite was rewrite 2!in_setI *) rewrite /= inE andbC inE (Aut_restr_perm sHG) //=. by symmetry; rewrite inE AutGa inE astabs_Aut_isom. Qed. Lemma injm_Aut_sub : Aut_in (Aut (f @* G)) (f @* H) \isog Aut_in (Aut G) H. Proof. do 2!rewrite isog_sym (isog_transl _ (Aut_in_isog _ _)). by rewrite isog_sym (isom_isog _ _ restr_perm_isom) // restr_perm_Aut. Qed. Lemma injm_Aut_full : (Aut_in (Aut (f @* G)) (f @* H) \isog Aut (f @* H)) = (Aut_in (Aut G) H \isog Aut H). Proof. by rewrite (isog_transl _ injm_Aut_sub) (isog_transr _ (injm_Aut injf sHD)). Qed. End InjmAutIn. Section GroupAction. Variables (aT rT : finGroupType) (D : {set aT}) (R : {set rT}). Local Notation actT := (action D rT). Definition is_groupAction (to : actT) := {in D, forall a, actperm to a \in Aut R}. Structure groupAction := GroupAction {gact :> actT; _ : is_groupAction gact}. Definition clone_groupAction to := let: GroupAction _ toA := to return {type of GroupAction for to} -> _ in fun k => k toA : groupAction. End GroupAction. Delimit Scope groupAction_scope with gact. Bind Scope groupAction_scope with groupAction. Arguments is_groupAction {aT rT D%_g} R%_g to%_act. Arguments groupAction {aT rT} D%_g R%_g. Arguments gact {aT rT D%_g R%_g} to%_gact : rename. Notation "[ 'groupAction' 'of' to ]" := (clone_groupAction (@GroupAction _ _ _ _ to)) (format "[ 'groupAction' 'of' to ]") : form_scope. Section GroupActionDefs. Variables (aT rT : finGroupType) (D : {set aT}) (R : {set rT}). Implicit Type A : {set aT}. Implicit Type S : {set rT}. Implicit Type to : groupAction D R. Definition gact_range of groupAction D R := R. Definition gacent to A := 'Fix_(R | to)(D :&: A). Definition acts_on_group A S to := [acts A, on S | to] /\ S \subset R. Coercion actby_cond_group A S to : acts_on_group A S to -> actby_cond A S to := @proj1 _ _. Definition acts_irreducibly A S to := [min S of G | G :!=: 1 & [acts A, on G | to]]. End GroupActionDefs. Arguments gacent {aT rT D%_g R%_g} to%_gact A%_g. Arguments acts_on_group {aT rT D%_g R%_g} A%_g S%_g to%_gact. Arguments acts_irreducibly {aT rT D%_g R%_g} A%_g S%_g to%_gact. Notation "''C_' ( | to ) ( A )" := (gacent to A) : group_scope. Notation "''C_' ( G | to ) ( A )" := (G :&: 'C_(|to)(A)) : group_scope. Notation "''C_' ( | to ) [ a ]" := 'C_(|to)([set a]) : group_scope. Notation "''C_' ( G | to ) [ a ]" := 'C_(G | to)([set a]) : group_scope. Notation "{ 'acts' A , 'on' 'group' G | to }" := (acts_on_group A G to) (format "{ 'acts' A , 'on' 'group' G | to }") : type_scope. Section RawGroupAction. Variables (aT rT : finGroupType) (D : {set aT}) (R : {set rT}). Variable to : groupAction D R. Lemma actperm_Aut : is_groupAction R to. Proof. by case: to. Qed. Lemma im_actperm_Aut : actperm to @* D \subset Aut R. Proof. by apply/subsetP=> _ /morphimP[a _ Da ->]; apply: actperm_Aut. Qed. Lemma gact_out x a : a \in D -> x \notin R -> to x a = x. Proof. by move=> Da Rx; rewrite -actpermE (out_Aut _ Rx) ?actperm_Aut. Qed. Lemma gactM : {in D, forall a, {in R &, {morph to^~ a : x y / x * y}}}. Proof. move=> a Da /= x y; rewrite -!(actpermE to); apply: morphicP x y. by rewrite Aut_morphic ?actperm_Aut. Qed. Lemma actmM a : {in R &, {morph actm to a : x y / x * y}}. Proof. by rewrite /actm; case: ifP => //; apply: gactM. Qed. Canonical act_morphism a := Morphism (actmM a). Lemma morphim_actm : {in D, forall a (S : {set rT}), S \subset R -> actm to a @* S = to^* S a}. Proof. by move=> a Da /= S sSR; rewrite /morphim /= actmEfun ?(setIidPr _). Qed. Variables (a : aT) (A B : {set aT}) (S : {set rT}). Lemma gacentIdom : 'C_(|to)(D :&: A) = 'C_(|to)(A). Proof. by rewrite /gacent setIA setIid. Qed. Lemma gacentIim : 'C_(R | to)(A) = 'C_(|to)(A). Proof. by rewrite setIA setIid. Qed. Lemma gacentS : A \subset B -> 'C_(|to)(B) \subset 'C_(|to)(A). Proof. by move=> sAB; rewrite !(setIS, afixS). Qed. Lemma gacentU : 'C_(|to)(A :|: B) = 'C_(|to)(A) :&: 'C_(|to)(B). Proof. by rewrite -setIIr -afixU -setIUr. Qed. Hypotheses (Da : a \in D) (sAD : A \subset D) (sSR : S \subset R). Lemma gacentE : 'C_(|to)(A) = 'Fix_(R | to)(A). Proof. by rewrite -{2}(setIidPr sAD). Qed. Lemma gacent1E : 'C_(|to)[a] = 'Fix_(R | to)[a]. Proof. by rewrite /gacent [D :&: _](setIidPr _) ?sub1set. Qed. Lemma subgacentE : 'C_(S | to)(A) = 'Fix_(S | to)(A). Proof. by rewrite gacentE setIA (setIidPl sSR). Qed. Lemma subgacent1E : 'C_(S | to)[a] = 'Fix_(S | to)[a]. Proof. by rewrite gacent1E setIA (setIidPl sSR). Qed. End RawGroupAction. Section GroupActionTheory. Variables aT rT : finGroupType. Variables (D : {group aT}) (R : {group rT}) (to : groupAction D R). Implicit Type A B : {set aT}. Implicit Types G H : {group aT}. Implicit Type S : {set rT}. Implicit Types M N : {group rT}. Lemma gact1 : {in D, forall a, to 1 a = 1}. Proof. by move=> a Da; rewrite /= -actmE ?morph1. Qed. Lemma gactV : {in D, forall a, {in R, {morph to^~ a : x / x^-1}}}. Proof. by move=> a Da /= x Rx; move; rewrite -!actmE ?morphV. Qed. Lemma gactX : {in D, forall a n, {in R, {morph to^~ a : x / x ^+ n}}}. Proof. by move=> a Da /= n x Rx; rewrite -!actmE // morphX. Qed. Lemma gactJ : {in D, forall a, {in R &, {morph to^~ a : x y / x ^ y}}}. Proof. by move=> a Da /= x Rx y Ry; rewrite -!actmE // morphJ. Qed. Lemma gactR : {in D, forall a, {in R &, {morph to^~ a : x y / [~ x, y]}}}. Proof. by move=> a Da /= x Rx y Ry; rewrite -!actmE // morphR. Qed. Lemma gact_stable : {acts D, on R | to}. Proof. apply: acts_act; apply/subsetP=> a Da; rewrite !inE Da. apply/subsetP=> x; rewrite inE; apply: contraLR => R'xa. by rewrite -(actKin to Da x) gact_out ?groupV. Qed. Lemma group_set_gacent A : group_set 'C_(|to)(A). Proof. apply/group_setP; split=> [|x y]. by rewrite !inE group1; apply/subsetP=> a /setIP[Da _]; rewrite inE gact1. case/setIP=> Rx /afixP cAx /setIP[Ry /afixP cAy]. rewrite inE groupM //; apply/afixP=> a Aa. by rewrite gactM ?cAx ?cAy //; case/setIP: Aa. Qed. Canonical gacent_group A := Group (group_set_gacent A). Lemma gacent1 : 'C_(|to)(1) = R. Proof. by rewrite /gacent (setIidPr (sub1G _)) afix1 setIT. Qed. Lemma gacent_gen A : A \subset D -> 'C_(|to)(<<A>>) = 'C_(|to)(A). Proof. by move=> sAD; rewrite /gacent ![D :&: _](setIidPr _) ?gen_subG ?afix_gen_in. Qed. Lemma gacentD1 A : 'C_(|to)(A^#) = 'C_(|to)(A). Proof. rewrite -gacentIdom -gacent_gen ?subsetIl // setIDA genD1 ?group1 //. by rewrite gacent_gen ?subsetIl // gacentIdom. Qed. Lemma gacent_cycle a : a \in D -> 'C_(|to)(<[a]>) = 'C_(|to)[a]. Proof. by move=> Da; rewrite gacent_gen ?sub1set. Qed. Lemma gacentY A B : A \subset D -> B \subset D -> 'C_(|to)(A <*> B) = 'C_(|to)(A) :&: 'C_(|to)(B). Proof. by move=> sAD sBD; rewrite gacent_gen ?gacentU // subUset sAD. Qed. Lemma gacentM G H : G \subset D -> H \subset D -> 'C_(|to)(G * H) = 'C_(|to)(G) :&: 'C_(|to)(H). Proof. by move=> sGD sHB; rewrite -gacent_gen ?mul_subG // genM_join gacentY. Qed. Lemma astab1 : 'C(1 | to) = D. Proof. by apply/setP=> x; rewrite ?(inE, sub1set) andb_idr //; move/gact1=> ->. Qed. Lemma astab_range : 'C(R | to) = 'C(setT | to). Proof. apply/eqP; rewrite eqEsubset andbC astabS ?subsetT //=. apply/subsetP=> a cRa; have Da := astab_dom cRa; rewrite !inE Da. apply/subsetP=> x; rewrite -(setUCr R) !inE. by case/orP=> ?; [rewrite (astab_act cRa) | rewrite gact_out]. Qed. Lemma gacentC A S : A \subset D -> S \subset R -> (S \subset 'C_(|to)(A)) = (A \subset 'C(S | to)). Proof. by move=> sAD sSR; rewrite subsetI sSR astabCin // (setIidPr sAD). Qed. Lemma astab_gen S : S \subset R -> 'C(<<S>> | to) = 'C(S | to). Proof. move=> sSR; apply/setP=> a; case Da: (a \in D); last by rewrite !inE Da. by rewrite -!sub1set -!gacentC ?sub1set ?gen_subG. Qed. Lemma astabM M N : M \subset R -> N \subset R -> 'C(M * N | to) = 'C(M | to) :&: 'C(N | to). Proof. move=> sMR sNR; rewrite -astabU -astab_gen ?mul_subG // genM_join. by rewrite astab_gen // subUset sMR. Qed. Lemma astabs1 : 'N(1 | to) = D. Proof. by rewrite astabs_set1 astab1. Qed. Lemma astabs_range : 'N(R | to) = D. Proof. apply/setIidPl; apply/subsetP=> a Da; rewrite inE. by apply/subsetP=> x Rx; rewrite inE gact_stable. Qed. Lemma astabsD1 S : 'N(S^# | to) = 'N(S | to). Proof. case S1: (1 \in S); last first. by rewrite (setDidPl _) // disjoint_sym disjoints_subset sub1set inE S1. apply/eqP; rewrite eqEsubset andbC -{1}astabsIdom -{1}astabs1 setIC astabsD /=. by rewrite -{2}(setD1K S1) -astabsIdom -{1}astabs1 astabsU. Qed. Lemma gacts_range A : A \subset D -> {acts A, on group R | to}. Proof. by move=> sAD; split; rewrite ?astabs_range. Qed. Lemma acts_subnorm_gacent A : A \subset D -> [acts 'N_D(A), on 'C_(| to)(A) | to]. Proof. move=> sAD; rewrite gacentE // actsI ?astabs_range ?subsetIl //. by rewrite -{2}(setIidPr sAD) acts_subnorm_fix. Qed. Lemma acts_subnorm_subgacent A B S : A \subset D -> [acts B, on S | to] -> [acts 'N_B(A), on 'C_(S | to)(A) | to]. Proof. move=> sAD actsB; rewrite actsI //; first by rewrite subIset ?actsB. by rewrite (subset_trans _ (acts_subnorm_gacent sAD)) ?setSI ?(acts_dom actsB). Qed. Lemma acts_gen A S : S \subset R -> [acts A, on S | to] -> [acts A, on <<S>> | to]. Proof. move=> sSR actsA; apply: {A}subset_trans actsA _. apply/subsetP=> a nSa; have Da := astabs_dom nSa; rewrite !inE Da. apply: subset_trans (_ : <<S>> \subset actm to a @*^-1 <<S>>) _. rewrite gen_subG subsetI sSR; apply/subsetP=> x Sx. by rewrite inE /= actmE ?mem_gen // astabs_act. by apply/subsetP=> x /[!inE]; case/andP=> Rx; rewrite /= actmE. Qed. Lemma acts_joing A M N : M \subset R -> N \subset R -> [acts A, on M | to] -> [acts A, on N | to] -> [acts A, on M <*> N | to]. Proof. by move=> sMR sNR nMA nNA; rewrite acts_gen ?actsU // subUset sMR. Qed. Lemma injm_actm a : 'injm (actm to a). Proof. apply/injmP=> x y Rx Ry; rewrite /= /actm; case: ifP => Da //. exact: act_inj. Qed. Lemma im_actm a : actm to a @* R = R. Proof. apply/eqP; rewrite eqEcard (card_injm (injm_actm a)) // leqnn andbT. apply/subsetP=> _ /morphimP[x Rx _ ->] /=. by rewrite /actm; case: ifP => // Da; rewrite gact_stable. Qed. Lemma acts_char G M : G \subset D -> M \char R -> [acts G, on M | to]. Proof. move=> sGD /charP[sMR charM]. apply/subsetP=> a Ga; have Da := subsetP sGD a Ga; rewrite !inE Da. apply/subsetP=> x Mx; have Rx := subsetP sMR x Mx. by rewrite inE -(charM _ (injm_actm a) (im_actm a)) -actmE // mem_morphim. Qed. Lemma gacts_char G M : G \subset D -> M \char R -> {acts G, on group M | to}. (* TODO: investigate why rewrite does not match in the same order *) Proof. by move=> sGD charM; split; rewrite ?acts_char// char_sub. Qed. (* was ending with rewrite (acts_char, char_sub)// *) Section Restrict. Variables (A : {group aT}) (sAD : A \subset D). Lemma ract_is_groupAction : is_groupAction R (to \ sAD). Proof. by move=> a Aa /=; rewrite ractpermE actperm_Aut ?(subsetP sAD). Qed. Canonical ract_groupAction := GroupAction ract_is_groupAction. Lemma gacent_ract B : 'C_(|ract_groupAction)(B) = 'C_(|to)(A :&: B). Proof. by rewrite /gacent afix_ract setIA (setIidPr sAD). Qed. End Restrict. Section ActBy. Variables (A : {group aT}) (G : {group rT}) (nGAg : {acts A, on group G | to}). Lemma actby_is_groupAction : is_groupAction G <[nGAg]>. Proof. move=> a Aa; rewrite /= inE; apply/andP; split. apply/subsetP=> x; apply: contraR => Gx. by rewrite actpermE /= /actby (negbTE Gx). apply/morphicP=> x y Gx Gy; rewrite !actpermE /= /actby Aa groupM ?Gx ?Gy //=. by case nGAg; move/acts_dom; do 2!move/subsetP=> ?; rewrite gactM; auto. Qed. Canonical actby_groupAction := GroupAction actby_is_groupAction. Lemma gacent_actby B : 'C_(|actby_groupAction)(B) = 'C_(G | to)(A :&: B). Proof. rewrite /gacent afix_actby !setIA setIid setIUr setICr set0U. by have [nAG sGR] := nGAg; rewrite (setIidPr (acts_dom nAG)) (setIidPl sGR). Qed. End ActBy. Section Quotient. Variable H : {group rT}. Lemma acts_qact_dom_norm : {acts qact_dom to H, on 'N(H) | to}. Proof. move=> a HDa /= x; rewrite {2}(('N(H) =P to^~ a @^-1: 'N(H)) _) ?inE {x}//. rewrite eqEcard (card_preimset _ (act_inj _ _)) leqnn andbT. apply/subsetP=> x Nx; rewrite inE; move/(astabs_act (H :* x)): HDa. rewrite mem_rcosets mulSGid ?normG // Nx => /rcosetsP[y Ny defHy]. suffices: to x a \in H :* y by apply: subsetP; rewrite mul_subG ?sub1set ?normG. by rewrite -defHy; apply: imset_f; apply: rcoset_refl. Qed. Lemma qact_is_groupAction : is_groupAction (R / H) (to / H). Proof. move=> a HDa /=; have Da := astabs_dom HDa. rewrite inE; apply/andP; split. apply/subsetP=> Hx /=; case: (cosetP Hx) => x Nx ->{Hx}. apply: contraR => R'Hx; rewrite actpermE qactE // gact_out //. by apply: contra R'Hx; apply: mem_morphim. apply/morphicP=> Hx Hy; rewrite !actpermE. case/morphimP=> x Nx Gx ->{Hx}; case/morphimP=> y Ny Gy ->{Hy}. by rewrite -morphM ?qactE ?groupM ?gactM // morphM ?acts_qact_dom_norm. Qed. Canonical quotient_groupAction := GroupAction qact_is_groupAction. Lemma qact_domE : H \subset R -> qact_dom to H = 'N(H | to). Proof. move=> sHR; apply/setP=> a; apply/idP/idP=> nHa; have Da := astabs_dom nHa. rewrite !inE Da; apply/subsetP=> x Hx; rewrite inE -(rcoset1 H). have /rcosetsP[y Ny defHy]: to^~ a @: H \in rcosets H 'N(H). by rewrite (astabs_act _ nHa); apply/rcosetsP; exists 1; rewrite ?mulg1. by rewrite (rcoset_eqP (_ : 1 \in H :* y)) -defHy -1?(gact1 Da) mem_setact. rewrite !inE Da; apply/subsetP=> Hx /[1!inE] /rcosetsP[x Nx ->{Hx}]. apply/imsetP; exists (to x a). case Rx: (x \in R); last by rewrite gact_out ?Rx. rewrite inE; apply/subsetP=> _ /imsetP[y Hy ->]. rewrite -(actKVin to Da y) -gactJ // ?(subsetP sHR, astabs_act, groupV) //. by rewrite memJ_norm // astabs_act ?groupV. apply/eqP; rewrite rcosetE eqEcard. rewrite (card_imset _ (act_inj _ _)) !card_rcoset leqnn andbT. apply/subsetP=> _ /imsetP[y Hxy ->]; rewrite !mem_rcoset in Hxy *. have Rxy := subsetP sHR _ Hxy; rewrite -(mulgKV x y). case Rx: (x \in R); last by rewrite !gact_out ?mulgK // 1?groupMl ?Rx. by rewrite -gactV // -gactM 1?groupMr ?groupV // mulgK astabs_act. Qed. End Quotient. Section Mod. Variable H : {group aT}. Lemma modact_is_groupAction : is_groupAction 'C_(|to)(H) (to %% H). Proof. move=> Ha /morphimP[a Na Da ->]; have NDa: a \in 'N_D(H) by apply/setIP. rewrite inE; apply/andP; split. apply/subsetP=> x; rewrite 2!inE andbC actpermE /= modactEcond //. by apply: contraR; case: ifP => // E Rx; rewrite gact_out. apply/morphicP=> x y /setIP[Rx cHx] /setIP[Ry cHy]. rewrite /= !actpermE /= !modactE ?gactM //. suffices: x * y \in 'C_(|to)(H) by case/setIP. by rewrite groupM //; apply/setIP. Qed. Canonical mod_groupAction := GroupAction modact_is_groupAction. Lemma modgactE x a : H \subset 'C(R | to) -> a \in 'N_D(H) -> (to %% H)%act x (coset H a) = to x a. Proof. move=> cRH NDa /=; have [Da Na] := setIP NDa. have [Rx | notRx] := boolP (x \in R). by rewrite modactE //; apply/afixP=> b /setIP[_ /(subsetP cRH)/astab_act->]. rewrite gact_out //= /modact; case: ifP => // _; rewrite gact_out //. suffices: a \in D :&: coset H a by case/mem_repr/setIP. by rewrite inE Da val_coset // rcoset_refl. Qed. Lemma gacent_mod G M : H \subset 'C(M | to) -> G \subset 'N(H) -> 'C_(M | mod_groupAction)(G / H) = 'C_(M | to)(G). Proof. move=> cMH nHG; rewrite -gacentIdom gacentE ?subsetIl // setICA. have sHD: H \subset D by rewrite (subset_trans cMH) ?subsetIl. rewrite -quotientGI // afix_mod ?setIS // setICA -gacentIim (setIC R) -setIA. rewrite -gacentE ?subsetIl // gacentIdom setICA (setIidPr _) //. by rewrite gacentC // ?(subset_trans cMH) ?astabS ?subsetIl // setICA subsetIl. Qed. Lemma acts_irr_mod G M : H \subset 'C(M | to) -> G \subset 'N(H) -> acts_irreducibly G M to -> acts_irreducibly (G / H) M mod_groupAction. Proof. move=> cMH nHG /mingroupP[/andP[ntM nMG] minM]. apply/mingroupP; rewrite ntM astabs_mod ?quotientS //; split=> // L modL ntL. have cLH: H \subset 'C(L | to) by rewrite (subset_trans cMH) ?astabS //. apply: minM => //; case/andP: modL => ->; rewrite astabs_mod ?quotientSGK //. by rewrite (subset_trans cLH) ?astab_sub. Qed. End Mod. Lemma modact_coset_astab x a : a \in D -> (to %% 'C(R | to))%act x (coset _ a) = to x a. Proof. move=> Da; apply: modgactE => {x}//. rewrite !inE Da; apply/subsetP=> _ /imsetP[c Cc ->]. have Dc := astab_dom Cc; rewrite !inE groupJ //. apply/subsetP=> x Rx; rewrite inE conjgE !actMin ?groupM ?groupV //. by rewrite (astab_act Cc) ?actKVin // gact_stable ?groupV. Qed. Lemma acts_irr_mod_astab G M : acts_irreducibly G M to -> acts_irreducibly (G / 'C_G(M | to)) M (mod_groupAction _). Proof. move=> irrG; have /andP[_ nMG] := mingroupp irrG. apply: acts_irr_mod irrG; first exact: subsetIr. by rewrite normsI ?normG // (subset_trans nMG) // astab_norm. Qed. Section CompAct. Variables (gT : finGroupType) (G : {group gT}) (f : {morphism G >-> aT}). Lemma comp_is_groupAction : is_groupAction R (comp_action to f). Proof. move=> a /morphpreP[Ba Dfa]; apply: etrans (actperm_Aut to Dfa). by congr (_ \in Aut R); apply/permP=> x; rewrite !actpermE. Qed. Canonical comp_groupAction := GroupAction comp_is_groupAction. Lemma gacent_comp U : 'C_(|comp_groupAction)(U) = 'C_(|to)(f @* U). Proof. rewrite /gacent afix_comp ?subIset ?subxx //. by rewrite -(setIC U) (setIC D) morphim_setIpre. Qed. End CompAct. End GroupActionTheory. Notation "''C_' ( | to ) ( A )" := (gacent_group to A) : Group_scope. Notation "''C_' ( G | to ) ( A )" := (setI_group G 'C_(|to)(A)) : Group_scope. Notation "''C_' ( | to ) [ a ]" := (gacent_group to [set a%g]) : Group_scope. Notation "''C_' ( G | to ) [ a ]" := (setI_group G 'C_(|to)[a]) : Group_scope. Notation "to \ sAD" := (ract_groupAction to sAD) : groupAction_scope. Notation "<[ nGA ] >" := (actby_groupAction nGA) : groupAction_scope. Notation "to / H" := (quotient_groupAction to H) : groupAction_scope. Notation "to %% H" := (mod_groupAction to H) : groupAction_scope. Notation "to \o f" := (comp_groupAction to f) : groupAction_scope. (* Operator group isomorphism. *) Section MorphAction. Variables (aT1 aT2 : finGroupType) (rT1 rT2 : finType). Variables (D1 : {group aT1}) (D2 : {group aT2}). Variables (to1 : action D1 rT1) (to2 : action D2 rT2). Variables (A : {set aT1}) (R S : {set rT1}). Variables (h : rT1 -> rT2) (f : {morphism D1 >-> aT2}). Hypotheses (actsDR : {acts D1, on R | to1}) (injh : {in R &, injective h}). Hypothesis defD2 : f @* D1 = D2. Hypotheses (sSR : S \subset R) (sAD1 : A \subset D1). Hypothesis hfJ : {in S & D1, morph_act to1 to2 h f}. Lemma morph_astabs : f @* 'N(S | to1) = 'N(h @: S | to2). Proof. apply/setP=> fx; apply/morphimP/idP=> [[x D1x nSx ->] | nSx]. rewrite 2!inE -{1}defD2 mem_morphim //=; apply/subsetP=> _ /imsetP[u Su ->]. by rewrite inE -hfJ ?imset_f // (astabs_act _ nSx). have [|x D1x _ def_fx] := morphimP (_ : fx \in f @* D1). by rewrite defD2 (astabs_dom nSx). exists x => //; rewrite !inE D1x; apply/subsetP=> u Su. have /imsetP[u' Su' /injh def_u']: h (to1 u x) \in h @: S. by rewrite hfJ // -def_fx (astabs_act _ nSx) imset_f. by rewrite inE def_u' ?actsDR ?(subsetP sSR). Qed. Lemma morph_astab : f @* 'C(S | to1) = 'C(h @: S | to2). Proof. apply/setP=> fx; apply/morphimP/idP=> [[x D1x cSx ->] | cSx]. rewrite 2!inE -{1}defD2 mem_morphim //=; apply/subsetP=> _ /imsetP[u Su ->]. by rewrite inE -hfJ // (astab_act cSx). have [|x D1x _ def_fx] := morphimP (_ : fx \in f @* D1). by rewrite defD2 (astab_dom cSx). exists x => //; rewrite !inE D1x; apply/subsetP=> u Su. rewrite inE -(inj_in_eq injh) ?actsDR ?(subsetP sSR) ?hfJ //. by rewrite -def_fx (astab_act cSx) ?imset_f. Qed. Lemma morph_afix : h @: 'Fix_(S | to1)(A) = 'Fix_(h @: S | to2)(f @* A). Proof. apply/setP=> hu; apply/imsetP/setIP=> [[u /setIP[Su cAu] ->]|]. split; first by rewrite imset_f. by apply/afixP=> _ /morphimP[x D1x Ax ->]; rewrite -hfJ ?(afixP cAu). case=> /imsetP[u Su ->] /afixP c_hu_fA; exists u; rewrite // inE Su. apply/afixP=> x Ax; have Dx := subsetP sAD1 x Ax. by apply: injh; rewrite ?actsDR ?(subsetP sSR) ?hfJ // c_hu_fA ?mem_morphim. Qed. End MorphAction. Section MorphGroupAction. Variables (aT1 aT2 rT1 rT2 : finGroupType). Variables (D1 : {group aT1}) (D2 : {group aT2}). Variables (R1 : {group rT1}) (R2 : {group rT2}). Variables (to1 : groupAction D1 R1) (to2 : groupAction D2 R2). Variables (h : {morphism R1 >-> rT2}) (f : {morphism D1 >-> aT2}). Hypotheses (iso_h : isom R1 R2 h) (iso_f : isom D1 D2 f). Hypothesis hfJ : {in R1 & D1, morph_act to1 to2 h f}. Implicit Types (A : {set aT1}) (S : {set rT1}) (M : {group rT1}). Lemma morph_gastabs S : S \subset R1 -> f @* 'N(S | to1) = 'N(h @* S | to2). Proof. have [[_ defD2] [injh _]] := (isomP iso_f, isomP iso_h). move=> sSR1; rewrite (morphimEsub _ sSR1). apply: (morph_astabs (gact_stable to1) (injmP injh)) => // u x. by move/(subsetP sSR1); apply: hfJ. Qed. Lemma morph_gastab S : S \subset R1 -> f @* 'C(S | to1) = 'C(h @* S | to2). Proof. have [[_ defD2] [injh _]] := (isomP iso_f, isomP iso_h). move=> sSR1; rewrite (morphimEsub _ sSR1). apply: (morph_astab (gact_stable to1) (injmP injh)) => // u x. by move/(subsetP sSR1); apply: hfJ. Qed. Lemma morph_gacent A : A \subset D1 -> h @* 'C_(|to1)(A) = 'C_(|to2)(f @* A). Proof. have [[_ defD2] [injh defR2]] := (isomP iso_f, isomP iso_h). move=> sAD1; rewrite !gacentE //; last by rewrite -defD2 morphimS. rewrite morphimEsub ?subsetIl // -{1}defR2 morphimEdom. exact: (morph_afix (gact_stable to1) (injmP injh)). Qed. Lemma morph_gact_irr A M : A \subset D1 -> M \subset R1 -> acts_irreducibly (f @* A) (h @* M) to2 = acts_irreducibly A M to1. Proof. move=> sAD1 sMR1. have [[injf defD2] [injh defR2]] := (isomP iso_f, isomP iso_h). have h_eq1 := morphim_injm_eq1 injh. apply/mingroupP/mingroupP=> [] [/andP[ntM actAM] minM]. split=> [|U]; first by rewrite -h_eq1 // ntM -(injmSK injf) ?morph_gastabs. case/andP=> ntU acts_fAU sUM; have sUR1 := subset_trans sUM sMR1. apply: (injm_morphim_inj injh) => //; apply: minM; last exact: morphimS. by rewrite h_eq1 // ntU -morph_gastabs ?morphimS. split=> [|U]; first by rewrite h_eq1 // ntM -morph_gastabs ?morphimS. case/andP=> ntU acts_fAU sUhM. have sUhR1 := subset_trans sUhM (morphimS h sMR1). have sU'M: h @*^-1 U \subset M by rewrite sub_morphpre_injm. rewrite /= -(minM _ _ sU'M) ?morphpreK // -h_eq1 ?subsetIl // -(injmSK injf) //. by rewrite morph_gastabs ?(subset_trans sU'M) // morphpreK ?ntU. Qed. End MorphGroupAction. (* Conjugation and right translation actions. *) Section InternalActionDefs. Variable gT : finGroupType. Implicit Type A : {set gT}. Implicit Type G : {group gT}. (* This is not a Canonical action because it is seldom used, and it would *) (* cause too many spurious matches (any group product would be viewed as an *) (* action!). *) Definition mulgr_action := TotalAction (@mulg1 gT) (@mulgA gT). Canonical conjg_action := TotalAction (@conjg1 gT) (@conjgM gT). Lemma conjg_is_groupAction : is_groupAction setT conjg_action. Proof. move=> a _; rewrite inE; apply/andP; split; first by apply/subsetP=> x /[1!inE]. by apply/morphicP=> x y _ _; rewrite !actpermE /= conjMg. Qed. Canonical conjg_groupAction := GroupAction conjg_is_groupAction. Lemma rcoset_is_action : is_action setT (@rcoset gT). Proof. by apply: is_total_action => [A|A x y]; rewrite !rcosetE (mulg1, rcosetM). Qed. Canonical rcoset_action := Action rcoset_is_action. Canonical conjsg_action := TotalAction (@conjsg1 gT) (@conjsgM gT). Lemma conjG_is_action : is_action setT (@conjG_group gT). Proof. apply: is_total_action => [G | G x y]; apply: val_inj; rewrite /= ?act1 //. exact: actM. Qed. Definition conjG_action := Action conjG_is_action. End InternalActionDefs. Notation "'R" := (@mulgr_action _) : action_scope. Notation "'Rs" := (@rcoset_action _) : action_scope. Notation "'J" := (@conjg_action _) : action_scope. Notation "'J" := (@conjg_groupAction _) : groupAction_scope. Notation "'Js" := (@conjsg_action _) : action_scope. Notation "'JG" := (@conjG_action _) : action_scope. Notation "'Q" := ('J / _)%act : action_scope. Notation "'Q" := ('J / _)%gact : groupAction_scope. Section InternalGroupAction. Variable gT : finGroupType. Implicit Types A B : {set gT}. Implicit Types G H : {group gT}. Implicit Type x : gT. (* Various identities for actions on groups. *) Lemma orbitR G x : orbit 'R G x = x *: G. Proof. by rewrite -lcosetE. Qed. Lemma astab1R x : 'C[x | 'R] = 1. Proof. apply/trivgP/subsetP=> y cxy. by rewrite -(mulKg x y) [x * y](astab1P cxy) mulVg set11. Qed. Lemma astabR G : 'C(G | 'R) = 1. Proof. apply/trivgP/subsetP=> x cGx. by rewrite -(mul1g x) [1 * x](astabP cGx) group1. Qed. Lemma astabsR G : 'N(G | 'R) = G. Proof. apply/setP=> x; rewrite !inE -setactVin ?inE //=. by rewrite -groupV -{1 3}(mulg1 G) rcoset_sym -sub1set -mulGS -!rcosetE. Qed. Lemma atransR G : [transitive G, on G | 'R]. Proof. by rewrite /atrans -{1}(mul1g G) -orbitR imset_f. Qed. Lemma faithfulR G : [faithful G, on G | 'R]. Proof. by rewrite /faithful astabR subsetIr. Qed. Definition Cayley_repr G := actperm <[atrans_acts (atransR G)]>. Theorem Cayley_isom G : isom G (Cayley_repr G @* G) (Cayley_repr G). Proof. exact: faithful_isom (faithfulR G). Qed. Theorem Cayley_isog G : G \isog Cayley_repr G @* G. Proof. exact: isom_isog (Cayley_isom G). Qed. Lemma orbitJ G x : orbit 'J G x = x ^: G. Proof. by []. Qed. Lemma afixJ A : 'Fix_('J)(A) = 'C(A). Proof. apply/setP=> x; apply/afixP/centP=> cAx y Ay /=. by rewrite /commute conjgC cAx. by rewrite conjgE cAx ?mulKg. Qed. Lemma astabJ A : 'C(A |'J) = 'C(A). Proof. apply/setP=> x; apply/astabP/centP=> cAx y Ay /=. by apply: esym; rewrite conjgC cAx. by rewrite conjgE -cAx ?mulKg. Qed. Lemma astab1J x : 'C[x |'J] = 'C[x]. Proof. by rewrite astabJ cent_set1. Qed. Lemma astabsJ A : 'N(A | 'J) = 'N(A). Proof. by apply/setP=> x; rewrite -2!groupV !inE -conjg_preim -sub_conjg. Qed. Lemma setactJ A x : 'J^*%act A x = A :^ x. Proof. by []. Qed. Lemma gacentJ A : 'C_(|'J)(A) = 'C(A). Proof. by rewrite gacentE ?setTI ?subsetT ?afixJ. Qed. Lemma orbitRs G A : orbit 'Rs G A = rcosets A G. Proof. by []. Qed. Lemma sub_afixRs_norms G x A : (G :* x \in 'Fix_('Rs)(A)) = (A \subset G :^ x). Proof. rewrite inE /=; apply: eq_subset_r => a. rewrite inE rcosetE -(can2_eq (rcosetKV x) (rcosetK x)) -!rcosetM. rewrite eqEcard card_rcoset leqnn andbT mulgA (conjgCV x) mulgK. by rewrite -{2 3}(mulGid G) mulGS sub1set -mem_conjg. Qed. Lemma sub_afixRs_norm G x : (G :* x \in 'Fix_('Rs)(G)) = (x \in 'N(G)). Proof. by rewrite sub_afixRs_norms -groupV inE sub_conjgV. Qed. Lemma afixRs_rcosets A G : 'Fix_(rcosets G A | 'Rs)(G) = rcosets G 'N_A(G). Proof. apply/setP=> Gx; apply/setIP/rcosetsP=> [[/rcosetsP[x Ax ->]]|[x]]. by rewrite sub_afixRs_norm => Nx; exists x; rewrite // inE Ax. by case/setIP=> Ax Nx ->; rewrite -{1}rcosetE imset_f // sub_afixRs_norm. Qed. Lemma astab1Rs G : 'C[G : {set gT} | 'Rs] = G. Proof. apply/setP=> x. by apply/astab1P/idP=> /= [<- | Gx]; rewrite rcosetE ?rcoset_refl ?rcoset_id. Qed. Lemma actsRs_rcosets H G : [acts G, on rcosets H G | 'Rs]. Proof. by rewrite -orbitRs acts_orbit ?subsetT. Qed. Lemma transRs_rcosets H G : [transitive G, on rcosets H G | 'Rs]. Proof. by rewrite -orbitRs atrans_orbit. Qed. (* This is the second part of Aschbacher (5.7) *) Lemma astabRs_rcosets H G : 'C(rcosets H G | 'Rs) = gcore H G. Proof. have transGH := transRs_rcosets H G. by rewrite (astab_trans_gcore transGH (orbit_refl _ G _)) astab1Rs. Qed. Lemma orbitJs G A : orbit 'Js G A = A :^: G. Proof. by []. Qed. Lemma astab1Js A : 'C[A | 'Js] = 'N(A). Proof. by apply/setP=> x; apply/astab1P/normP. Qed. Lemma card_conjugates A G : #|A :^: G| = #|G : 'N_G(A)|. Proof. by rewrite card_orbit astab1Js. Qed. Lemma afixJG G A : (G \in 'Fix_('JG)(A)) = (A \subset 'N(G)). Proof. by apply/afixP/normsP=> nG x Ax; apply/eqP; move/eqP: (nG x Ax). Qed. Lemma astab1JG G : 'C[G | 'JG] = 'N(G). Proof. by apply/setP=> x; apply/astab1P/normP=> [/congr_group | /group_inj]. Qed. Lemma dom_qactJ H : qact_dom 'J H = 'N(H). Proof. by rewrite qact_domE ?subsetT ?astabsJ. Qed. Lemma qactJ H (Hy : coset_of H) x : 'Q%act Hy x = if x \in 'N(H) then Hy ^ coset H x else Hy. Proof. case: (cosetP Hy) => y Ny ->{Hy}. by rewrite qactEcond // dom_qactJ; case Nx: (x \in 'N(H)); rewrite ?morphJ. Qed. Lemma actsQ A B H : A \subset 'N(H) -> A \subset 'N(B) -> [acts A, on B / H | 'Q]. Proof. by move=> nHA nBA; rewrite acts_quotient // subsetI dom_qactJ nHA astabsJ. Qed. Lemma astabsQ G H : H <| G -> 'N(G / H | 'Q) = 'N(H) :&: 'N(G). Proof. by move=> nsHG; rewrite astabs_quotient // dom_qactJ astabsJ. Qed. Lemma astabQ H Abar : 'C(Abar |'Q) = coset H @*^-1 'C(Abar). Proof. apply/setP=> x; rewrite inE /= dom_qactJ morphpreE in_setI /=. apply: andb_id2l => Nx; rewrite !inE -sub1set centsC cent_set1. apply: eq_subset_r => {Abar} Hy; rewrite inE qactJ Nx (sameP eqP conjg_fixP). by rewrite (sameP cent1P eqP) (sameP commgP eqP). Qed. Lemma sub_astabQ A H Bbar : (A \subset 'C(Bbar | 'Q)) = (A \subset 'N(H)) && (A / H \subset 'C(Bbar)). Proof. rewrite astabQ -morphpreIdom subsetI; apply: andb_id2l => nHA. by rewrite -sub_quotient_pre. Qed. Lemma sub_astabQR A B H : A \subset 'N(H) -> B \subset 'N(H) -> (A \subset 'C(B / H | 'Q)) = ([~: A, B] \subset H). Proof. move=> nHA nHB; rewrite sub_astabQ nHA /= (sameP commG1P eqP). by rewrite eqEsubset sub1G andbT -quotientR // quotient_sub1 // comm_subG. Qed. Lemma astabQR A H : A \subset 'N(H) -> 'C(A / H | 'Q) = [set x in 'N(H) | [~: [set x], A] \subset H]. Proof. move=> nHA; apply/setP=> x; rewrite astabQ -morphpreIdom 2!inE -astabQ. by case nHx: (x \in _); rewrite //= -sub1set sub_astabQR ?sub1set. Qed. Lemma quotient_astabQ H Abar : 'C(Abar | 'Q) / H = 'C(Abar). Proof. by rewrite astabQ cosetpreK. Qed. Lemma conj_astabQ A H x : x \in 'N(H) -> 'C(A / H | 'Q) :^ x = 'C(A :^ x / H | 'Q). Proof. move=> nHx; apply/setP=> y; rewrite !astabQ mem_conjg !in_setI -mem_conjg. rewrite -normJ (normP nHx) quotientJ //; apply/andb_id2l => nHy. by rewrite !inE centJ morphJ ?groupV ?morphV // -mem_conjg. Qed. Section CardClass. Variable G : {group gT}. Lemma index_cent1 x : #|G : 'C_G[x]| = #|x ^: G|. Proof. by rewrite -astab1J -card_orbit. Qed. Lemma classes_partition : partition (classes G) G. Proof. by apply: orbit_partition; apply/actsP=> x Gx y; apply: groupJr. Qed. Lemma sum_card_class : \sum_(C in classes G) #|C| = #|G|. Proof. by apply: acts_sum_card_orbit; apply/actsP=> x Gx y; apply: groupJr. Qed. Lemma class_formula : \sum_(C in classes G) #|G : 'C_G[repr C]| = #|G|. Proof. rewrite -sum_card_class; apply: eq_bigr => _ /imsetP[x Gx ->]. have: x \in x ^: G by rewrite -{1}(conjg1 x) imset_f. by case/mem_repr/imsetP=> y Gy ->; rewrite index_cent1 classGidl. Qed. Lemma abelian_classP : reflect {in G, forall x, x ^: G = [set x]} (abelian G). Proof. rewrite /abelian -astabJ astabC. by apply: (iffP subsetP) => cGG x Gx; apply/orbit1P; apply: cGG. Qed. Lemma card_classes_abelian : abelian G = (#|classes G| == #|G|). Proof. have cGgt0 C: C \in classes G -> 1 <= #|C| ?= iff (#|C| == 1)%N. by case/imsetP=> x _ ->; rewrite eq_sym -index_cent1. rewrite -sum_card_class -sum1_card (leqif_sum cGgt0). apply/abelian_classP/forall_inP=> [cGG _ /imsetP[x Gx ->]| cGG x Gx]. by rewrite cGG ?cards1. apply/esym/eqP; rewrite eqEcard sub1set cards1 class_refl leq_eqVlt cGG //. exact: imset_f. Qed. End CardClass. End InternalGroupAction. Lemma gacentQ (gT : finGroupType) (H : {group gT}) (A : {set gT}) : 'C_(|'Q)(A) = 'C(A / H). Proof. apply/setP=> Hx; case: (cosetP Hx) => x Nx ->{Hx}. rewrite -sub_cent1 -astab1J astabC sub1set -(quotientInorm H A). have defD: qact_dom 'J H = 'N(H) by rewrite qact_domE ?subsetT ?astabsJ. rewrite !(inE, mem_quotient) //= defD setIC. apply/subsetP/subsetP=> [cAx _ /morphimP[a Na Aa ->] | cAx a Aa]. by move/cAx: Aa; rewrite !inE qactE ?defD ?morphJ. have [_ Na] := setIP Aa; move/implyP: (cAx (coset H a)); rewrite mem_morphim //. by rewrite !inE qactE ?defD ?morphJ. Qed. Section AutAct. Variable (gT : finGroupType) (G : {set gT}). Definition autact := act ('P \ subsetT (Aut G)). Canonical aut_action := [action of autact]. Lemma autactK a : actperm aut_action a = a. Proof. by apply/permP=> x; rewrite permE. Qed. Lemma autact_is_groupAction : is_groupAction G aut_action. Proof. by move=> a Aa /=; rewrite autactK. Qed. Canonical aut_groupAction := GroupAction autact_is_groupAction. Section perm_prime_orbit. Variable (T : finType) (c : {perm T}). Hypothesis Tp : prime #|T|. Hypothesis cc : #[c]%g = #|T|. Let cp : prime #[c]%g. Proof. by rewrite cc. Qed. Lemma perm_prime_atrans : [transitive <[c]>, on setT | 'P]. Proof. apply/imsetP; suff /existsP[x] : [exists x, ~~ (#|orbit 'P <[c]> x| < #[c])]. move=> oxT; suff /eqP orbit_x : orbit 'P <[c]> x == setT by exists x. by rewrite eqEcard subsetT cardsT -cc leqNgt. apply/forallP => olT; have o1 x : #|orbit 'P <[c]> x| == 1%N. by case/primeP: cp => _ /(_ _ (dvdn_orbit 'P _ x))/orP[]//; rewrite ltn_eqF. suff c1 : c = 1%g by rewrite c1 ?order1 in (cp). apply/permP => x; rewrite perm1; apply/set1P. by rewrite -(card_orbit1 (eqP (o1 _))) (mem_orbit 'P) ?cycle_id. Qed. Lemma perm_prime_orbit x : orbit 'P <[c]> x = [set: T]. Proof. by apply: atransP => //; apply: perm_prime_atrans. Qed. Lemma perm_prime_astab x : 'C_<[c]>[x | 'P]%g = 1%g. Proof. by apply/card1_trivg/eqP; rewrite -(@eqn_pmul2l #|orbit 'P <[c]> x|) ?card_orbit_stab ?perm_prime_orbit ?cardsT ?muln1 ?prime_gt0// -cc. Qed. End perm_prime_orbit. End AutAct. Arguments autact {gT} G%_g. Arguments aut_action {gT} G%_g. Arguments aut_groupAction {gT} G%_g. Notation "[ 'Aut' G ]" := (aut_action G) : action_scope. Notation "[ 'Aut' G ]" := (aut_groupAction G) : groupAction_scope.
Completion.lean
/- Copyright (c) 2025 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Analysis.Asymptotics.Theta import Mathlib.Analysis.Normed.Group.Completion /-! # Asymptotics in the completion of a normed space In this file we prove lemmas relating `f = O(g)` etc for composition of functions with coercion of a seminormed group to its completion. -/ variable {α E F : Type*} [Norm E] [SeminormedAddCommGroup F] {f : α → E} {g : α → F} {l : Filter α} local postfix:100 "̂" => UniformSpace.Completion open UniformSpace.Completion namespace Asymptotics @[simp, norm_cast] lemma isBigO_completion_left : (fun x ↦ g x : α → F̂) =O[l] f ↔ g =O[l] f := by simp only [isBigO_iff, norm_coe] @[simp, norm_cast] lemma isBigO_completion_right : f =O[l] (fun x ↦ g x : α → F̂) ↔ f =O[l] g := by simp only [isBigO_iff, norm_coe] @[simp, norm_cast] lemma isTheta_completion_left : (fun x ↦ g x : α → F̂) =Θ[l] f ↔ g =Θ[l] f := and_congr isBigO_completion_left isBigO_completion_right @[simp, norm_cast] lemma isTheta_completion_right : f =Θ[l] (fun x ↦ g x : α → F̂) ↔ f =Θ[l] g := and_congr isBigO_completion_right isBigO_completion_left @[simp, norm_cast] lemma isLittleO_completion_left : (fun x ↦ g x : α → F̂) =o[l] f ↔ g =o[l] f := by simp only [isLittleO_iff, norm_coe] @[simp, norm_cast] lemma isLittleO_completion_right : f =o[l] (fun x ↦ g x : α → F̂) ↔ f =o[l] g := by simp only [isLittleO_iff, norm_coe] end Asymptotics
all.v
From mathcomp Require Export all_boot. From mathcomp Require Export all_order. From mathcomp Require Export all_fingroup. From mathcomp Require Export all_algebra. From mathcomp Require Export all_solvable. From mathcomp Require Export all_field. From mathcomp Require Export all_character.
FinMeasAdditive.lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov, Sébastien Gouëzel, Rémy Degenne -/ import Mathlib.MeasureTheory.Function.SimpleFuncDenseLp /-! # Additivity on measurable sets with finite measure Let `T : Set α → E →L[ℝ] F` be additive for measurable sets with finite measure, in the sense that for `s, t` two such sets, `Disjoint s t → T (s ∪ t) = T s + T t`. `T` is akin to a bilinear map on `Set α × E`, or a linear map on indicator functions. This property is named `FinMeasAdditive` in this file. We also define `DominatedFinMeasAdditive`, which requires in addition that the norm on every set is less than the measure of the set (up to a multiplicative constant); in `Mathlib/MeasureTheory/Integral/SetToL1.lean` we extend set functions with this stronger property to integrable (L1) functions. ## Main definitions - `FinMeasAdditive μ T`: the property that `T` is additive on measurable sets with finite measure. For two such sets, `Disjoint s t → T (s ∪ t) = T s + T t`. - `DominatedFinMeasAdditive μ T C`: `FinMeasAdditive μ T ∧ ∀ s, ‖T s‖ ≤ C * μ.real s`. This is the property needed to perform the extension from indicators to L1. ## Implementation notes The starting object `T : Set α → E →L[ℝ] F` matters only through its restriction on measurable sets with finite measure. Its value on other sets is ignored. -/ noncomputable section open Set Filter ENNReal Finset namespace MeasureTheory variable {α E F F' G 𝕜 : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [NormedAddCommGroup F] [NormedSpace ℝ F] [NormedAddCommGroup F'] [NormedSpace ℝ F'] [NormedAddCommGroup G] {m : MeasurableSpace α} {μ : Measure α} local infixr:25 " →ₛ " => SimpleFunc section FinMeasAdditive /-- A set function is `FinMeasAdditive` if its value on the union of two disjoint measurable sets with finite measure is the sum of its values on each set. -/ def FinMeasAdditive {β} [AddMonoid β] {_ : MeasurableSpace α} (μ : Measure α) (T : Set α → β) : Prop := ∀ s t, MeasurableSet s → MeasurableSet t → μ s ≠ ∞ → μ t ≠ ∞ → Disjoint s t → T (s ∪ t) = T s + T t namespace FinMeasAdditive variable {β : Type*} [AddCommMonoid β] {T T' : Set α → β} theorem zero : FinMeasAdditive μ (0 : Set α → β) := fun _ _ _ _ _ _ _ => by simp theorem add (hT : FinMeasAdditive μ T) (hT' : FinMeasAdditive μ T') : FinMeasAdditive μ (T + T') := by intro s t hs ht hμs hμt hst simp only [hT s t hs ht hμs hμt hst, hT' s t hs ht hμs hμt hst, Pi.add_apply] abel theorem smul [DistribSMul 𝕜 β] (hT : FinMeasAdditive μ T) (c : 𝕜) : FinMeasAdditive μ fun s => c • T s := fun s t hs ht hμs hμt hst => by simp [hT s t hs ht hμs hμt hst] theorem of_eq_top_imp_eq_top {μ' : Measure α} (h : ∀ s, MeasurableSet s → μ s = ∞ → μ' s = ∞) (hT : FinMeasAdditive μ T) : FinMeasAdditive μ' T := fun s t hs ht hμ's hμ't hst => hT s t hs ht (mt (h s hs) hμ's) (mt (h t ht) hμ't) hst theorem of_smul_measure {c : ℝ≥0∞} (hc_ne_top : c ≠ ∞) (hT : FinMeasAdditive (c • μ) T) : FinMeasAdditive μ T := by refine of_eq_top_imp_eq_top (fun s _ hμs => ?_) hT rw [Measure.smul_apply, smul_eq_mul, ENNReal.mul_eq_top] at hμs simp only [hc_ne_top, or_false, Ne, false_and] at hμs exact hμs.2 theorem smul_measure (c : ℝ≥0∞) (hc_ne_zero : c ≠ 0) (hT : FinMeasAdditive μ T) : FinMeasAdditive (c • μ) T := by refine of_eq_top_imp_eq_top (fun s _ hμs => ?_) hT rw [Measure.smul_apply, smul_eq_mul, ENNReal.mul_eq_top] simp only [hc_ne_zero, true_and, Ne, not_false_iff] exact Or.inl hμs theorem smul_measure_iff (c : ℝ≥0∞) (hc_ne_zero : c ≠ 0) (hc_ne_top : c ≠ ∞) : FinMeasAdditive (c • μ) T ↔ FinMeasAdditive μ T := ⟨fun hT => of_smul_measure hc_ne_top hT, fun hT => smul_measure c hc_ne_zero hT⟩ theorem map_empty_eq_zero {β} [AddCancelMonoid β] {T : Set α → β} (hT : FinMeasAdditive μ T) : T ∅ = 0 := by have h_empty : μ ∅ ≠ ∞ := (measure_empty.le.trans_lt ENNReal.coe_lt_top).ne specialize hT ∅ ∅ MeasurableSet.empty MeasurableSet.empty h_empty h_empty (disjoint_empty _) rw [Set.union_empty] at hT nth_rw 1 [← add_zero (T ∅)] at hT exact (add_left_cancel hT).symm theorem map_iUnion_fin_meas_set_eq_sum (T : Set α → β) (T_empty : T ∅ = 0) (h_add : FinMeasAdditive μ T) {ι} (S : ι → Set α) (sι : Finset ι) (hS_meas : ∀ i, MeasurableSet (S i)) (hSp : ∀ i ∈ sι, μ (S i) ≠ ∞) (h_disj : ∀ᵉ (i ∈ sι) (j ∈ sι), i ≠ j → Disjoint (S i) (S j)) : T (⋃ i ∈ sι, S i) = ∑ i ∈ sι, T (S i) := by classical revert hSp h_disj refine Finset.induction_on sι ?_ ?_ · simp only [Finset.notMem_empty, IsEmpty.forall_iff, iUnion_false, iUnion_empty, sum_empty, imp_true_iff, T_empty] intro a s has h hps h_disj rw [Finset.sum_insert has, ← h] swap; · exact fun i hi => hps i (Finset.mem_insert_of_mem hi) swap · exact fun i hi j hj hij => h_disj i (Finset.mem_insert_of_mem hi) j (Finset.mem_insert_of_mem hj) hij rw [← h_add (S a) (⋃ i ∈ s, S i) (hS_meas a) (measurableSet_biUnion _ fun i _ => hS_meas i) (hps a (Finset.mem_insert_self a s))] · congr; convert Finset.iSup_insert a s S · exact (measure_biUnion_lt_top s.finite_toSet fun i hi ↦ (hps i <| Finset.mem_insert_of_mem hi).lt_top).ne · simp_rw [Set.disjoint_iUnion_right] intro i hi refine h_disj a (Finset.mem_insert_self a s) i (Finset.mem_insert_of_mem hi) fun hai ↦ ?_ rw [← hai] at hi exact has hi end FinMeasAdditive /-- A `FinMeasAdditive` set function whose norm on every set is less than the measure of the set (up to a multiplicative constant). -/ def DominatedFinMeasAdditive {β} [SeminormedAddCommGroup β] {_ : MeasurableSpace α} (μ : Measure α) (T : Set α → β) (C : ℝ) : Prop := FinMeasAdditive μ T ∧ ∀ s, MeasurableSet s → μ s < ∞ → ‖T s‖ ≤ C * μ.real s namespace DominatedFinMeasAdditive variable {β : Type*} [SeminormedAddCommGroup β] {T T' : Set α → β} {C C' : ℝ} theorem zero {m : MeasurableSpace α} (μ : Measure α) (hC : 0 ≤ C) : DominatedFinMeasAdditive μ (0 : Set α → β) C := by refine ⟨FinMeasAdditive.zero, fun s _ _ => ?_⟩ rw [Pi.zero_apply, norm_zero] exact mul_nonneg hC toReal_nonneg theorem eq_zero_of_measure_zero {β : Type*} [NormedAddCommGroup β] {T : Set α → β} {C : ℝ} (hT : DominatedFinMeasAdditive μ T C) {s : Set α} (hs : MeasurableSet s) (hs_zero : μ s = 0) : T s = 0 := by refine norm_eq_zero.mp ?_ refine ((hT.2 s hs (by simp [hs_zero])).trans (le_of_eq ?_)).antisymm (norm_nonneg _) rw [measureReal_def, hs_zero, ENNReal.toReal_zero, mul_zero] theorem eq_zero {β : Type*} [NormedAddCommGroup β] {T : Set α → β} {C : ℝ} {_ : MeasurableSpace α} (hT : DominatedFinMeasAdditive (0 : Measure α) T C) {s : Set α} (hs : MeasurableSet s) : T s = 0 := eq_zero_of_measure_zero hT hs (by simp only [Measure.coe_zero, Pi.zero_apply]) theorem add (hT : DominatedFinMeasAdditive μ T C) (hT' : DominatedFinMeasAdditive μ T' C') : DominatedFinMeasAdditive μ (T + T') (C + C') := by refine ⟨hT.1.add hT'.1, fun s hs hμs => ?_⟩ rw [Pi.add_apply, add_mul] exact (norm_add_le _ _).trans (add_le_add (hT.2 s hs hμs) (hT'.2 s hs hμs)) theorem smul [SeminormedAddGroup 𝕜] [DistribSMul 𝕜 β] [IsBoundedSMul 𝕜 β] (hT : DominatedFinMeasAdditive μ T C) (c : 𝕜) : DominatedFinMeasAdditive μ (fun s => c • T s) (‖c‖ * C) := by refine ⟨hT.1.smul c, fun s hs hμs => (norm_smul_le _ _).trans ?_⟩ rw [mul_assoc] exact mul_le_mul le_rfl (hT.2 s hs hμs) (norm_nonneg _) (norm_nonneg _) theorem of_measure_le {μ' : Measure α} (h : μ ≤ μ') (hT : DominatedFinMeasAdditive μ T C) (hC : 0 ≤ C) : DominatedFinMeasAdditive μ' T C := by have h' : ∀ s, μ s = ∞ → μ' s = ∞ := fun s hs ↦ top_unique <| hs.symm.trans_le (h _) refine ⟨hT.1.of_eq_top_imp_eq_top fun s _ ↦ h' s, fun s hs hμ's ↦ ?_⟩ have hμs : μ s < ∞ := (h s).trans_lt hμ's calc ‖T s‖ ≤ C * μ.real s := hT.2 s hs hμs _ ≤ C * μ'.real s := by simp only [measureReal_def] gcongr exacts [hμ's.ne, h s] theorem add_measure_right {_ : MeasurableSpace α} (μ ν : Measure α) (hT : DominatedFinMeasAdditive μ T C) (hC : 0 ≤ C) : DominatedFinMeasAdditive (μ + ν) T C := of_measure_le (Measure.le_add_right le_rfl) hT hC theorem add_measure_left {_ : MeasurableSpace α} (μ ν : Measure α) (hT : DominatedFinMeasAdditive ν T C) (hC : 0 ≤ C) : DominatedFinMeasAdditive (μ + ν) T C := of_measure_le (Measure.le_add_left le_rfl) hT hC theorem of_smul_measure {c : ℝ≥0∞} (hc_ne_top : c ≠ ∞) (hT : DominatedFinMeasAdditive (c • μ) T C) : DominatedFinMeasAdditive μ T (c.toReal * C) := by have h : ∀ s, MeasurableSet s → c • μ s = ∞ → μ s = ∞ := by intro s _ hcμs simp only [hc_ne_top, Algebra.id.smul_eq_mul, ENNReal.mul_eq_top, or_false, Ne, false_and] at hcμs exact hcμs.2 refine ⟨hT.1.of_eq_top_imp_eq_top (μ := c • μ) h, fun s hs hμs => ?_⟩ have hcμs : c • μ s ≠ ∞ := mt (h s hs) hμs.ne rw [smul_eq_mul] at hcμs refine (hT.2 s hs hcμs.lt_top).trans (le_of_eq ?_) simp only [measureReal_ennreal_smul_apply] ring theorem of_measure_le_smul {μ' : Measure α} {c : ℝ≥0∞} (hc : c ≠ ∞) (h : μ ≤ c • μ') (hT : DominatedFinMeasAdditive μ T C) (hC : 0 ≤ C) : DominatedFinMeasAdditive μ' T (c.toReal * C) := (hT.of_measure_le h hC).of_smul_measure hc end DominatedFinMeasAdditive end FinMeasAdditive namespace SimpleFunc /-- Extend `Set α → (F →L[ℝ] F')` to `(α →ₛ F) → F'`. -/ def setToSimpleFunc {_ : MeasurableSpace α} (T : Set α → F →L[ℝ] F') (f : α →ₛ F) : F' := ∑ x ∈ f.range, T (f ⁻¹' {x}) x @[simp] theorem setToSimpleFunc_zero {m : MeasurableSpace α} (f : α →ₛ F) : setToSimpleFunc (0 : Set α → F →L[ℝ] F') f = 0 := by simp [setToSimpleFunc] theorem setToSimpleFunc_zero' {T : Set α → E →L[ℝ] F'} (h_zero : ∀ s, MeasurableSet s → μ s < ∞ → T s = 0) (f : α →ₛ E) (hf : Integrable f μ) : setToSimpleFunc T f = 0 := by simp_rw [setToSimpleFunc] refine sum_eq_zero fun x _ => ?_ by_cases hx0 : x = 0 · simp [hx0] rw [h_zero (f ⁻¹' ({x} : Set E)) (measurableSet_fiber _ _) (measure_preimage_lt_top_of_integrable f hf hx0), ContinuousLinearMap.zero_apply] @[simp] theorem setToSimpleFunc_zero_apply {m : MeasurableSpace α} (T : Set α → F →L[ℝ] F') : setToSimpleFunc T (0 : α →ₛ F) = 0 := by cases isEmpty_or_nonempty α <;> simp [setToSimpleFunc] theorem setToSimpleFunc_eq_sum_filter [DecidablePred fun x ↦ x ≠ (0 : F)] {m : MeasurableSpace α} (T : Set α → F →L[ℝ] F') (f : α →ₛ F) : setToSimpleFunc T f = ∑ x ∈ f.range with x ≠ 0, T (f ⁻¹' {x}) x := by symm refine sum_filter_of_ne fun x _ => mt fun hx0 => ?_ rw [hx0] exact ContinuousLinearMap.map_zero _ theorem map_setToSimpleFunc (T : Set α → F →L[ℝ] F') (h_add : FinMeasAdditive μ T) {f : α →ₛ G} (hf : Integrable f μ) {g : G → F} (hg : g 0 = 0) : (f.map g).setToSimpleFunc T = ∑ x ∈ f.range, T (f ⁻¹' {x}) (g x) := by classical have T_empty : T ∅ = 0 := h_add.map_empty_eq_zero have hfp : ∀ x ∈ f.range, x ≠ 0 → μ (f ⁻¹' {x}) ≠ ∞ := fun x _ hx0 => (measure_preimage_lt_top_of_integrable f hf hx0).ne simp only [setToSimpleFunc, range_map] refine Finset.sum_image' _ fun b hb => ?_ rcases mem_range.1 hb with ⟨a, rfl⟩ by_cases h0 : g (f a) = 0 · simp_rw [h0] rw [ContinuousLinearMap.map_zero, Finset.sum_eq_zero fun x hx => ?_] rw [mem_filter] at hx rw [hx.2, ContinuousLinearMap.map_zero] have h_left_eq : T (map g f ⁻¹' {g (f a)}) (g (f a)) = T (f ⁻¹' ({b ∈ f.range | g b = g (f a)} : Finset _)) (g (f a)) := by rw [map_preimage_singleton] rw [h_left_eq] have h_left_eq' : T (f ⁻¹' ({b ∈ f.range | g b = g (f a)} : Finset _)) (g (f a)) = T (⋃ y ∈ {b ∈ f.range | g b = g (f a)}, f ⁻¹' {y}) (g (f a)) := by rw [← Finset.set_biUnion_preimage_singleton] rw [h_left_eq'] rw [h_add.map_iUnion_fin_meas_set_eq_sum T T_empty] · simp only [sum_apply, ContinuousLinearMap.coe_sum'] refine Finset.sum_congr rfl fun x hx => ?_ rw [mem_filter] at hx rw [hx.2] · exact fun i => measurableSet_fiber _ _ · grind · grind [Set.disjoint_iff] theorem setToSimpleFunc_congr' (T : Set α → E →L[ℝ] F) (h_add : FinMeasAdditive μ T) {f g : α →ₛ E} (hf : Integrable f μ) (hg : Integrable g μ) (h : Pairwise fun x y => T (f ⁻¹' {x} ∩ g ⁻¹' {y}) = 0) : f.setToSimpleFunc T = g.setToSimpleFunc T := show ((pair f g).map Prod.fst).setToSimpleFunc T = ((pair f g).map Prod.snd).setToSimpleFunc T by have h_pair : Integrable (f.pair g) μ := integrable_pair hf hg rw [map_setToSimpleFunc T h_add h_pair Prod.fst_zero] rw [map_setToSimpleFunc T h_add h_pair Prod.snd_zero] refine Finset.sum_congr rfl fun p hp => ?_ rcases mem_range.1 hp with ⟨a, rfl⟩ by_cases eq : f a = g a · dsimp only [pair_apply]; rw [eq] · have : T (pair f g ⁻¹' {(f a, g a)}) = 0 := by have h_eq : T ((⇑(f.pair g)) ⁻¹' {(f a, g a)}) = T (f ⁻¹' {f a} ∩ g ⁻¹' {g a}) := by congr; rw [pair_preimage_singleton f g] rw [h_eq] exact h eq simp only [this, ContinuousLinearMap.zero_apply, pair_apply] theorem setToSimpleFunc_congr (T : Set α → E →L[ℝ] F) (h_zero : ∀ s, MeasurableSet s → μ s = 0 → T s = 0) (h_add : FinMeasAdditive μ T) {f g : α →ₛ E} (hf : Integrable f μ) (h : f =ᵐ[μ] g) : f.setToSimpleFunc T = g.setToSimpleFunc T := by refine setToSimpleFunc_congr' T h_add hf ((integrable_congr h).mp hf) ?_ refine fun x y hxy => h_zero _ ((measurableSet_fiber f x).inter (measurableSet_fiber g y)) ?_ rw [EventuallyEq, ae_iff] at h refine measure_mono_null (fun z => ?_) h simp_rw [Set.mem_inter_iff, Set.mem_setOf_eq, Set.mem_preimage, Set.mem_singleton_iff] intro h rwa [h.1, h.2] theorem setToSimpleFunc_congr_left (T T' : Set α → E →L[ℝ] F) (h : ∀ s, MeasurableSet s → μ s < ∞ → T s = T' s) (f : α →ₛ E) (hf : Integrable f μ) : setToSimpleFunc T f = setToSimpleFunc T' f := by simp_rw [setToSimpleFunc] refine sum_congr rfl fun x _ => ?_ by_cases hx0 : x = 0 · simp [hx0] · rw [h (f ⁻¹' {x}) (SimpleFunc.measurableSet_fiber _ _) (SimpleFunc.measure_preimage_lt_top_of_integrable _ hf hx0)] theorem setToSimpleFunc_add_left {m : MeasurableSpace α} (T T' : Set α → F →L[ℝ] F') {f : α →ₛ F} : setToSimpleFunc (T + T') f = setToSimpleFunc T f + setToSimpleFunc T' f := by simp_rw [setToSimpleFunc, Pi.add_apply] push_cast simp_rw [Pi.add_apply, sum_add_distrib] theorem setToSimpleFunc_add_left' (T T' T'' : Set α → E →L[ℝ] F) (h_add : ∀ s, MeasurableSet s → μ s < ∞ → T'' s = T s + T' s) {f : α →ₛ E} (hf : Integrable f μ) : setToSimpleFunc T'' f = setToSimpleFunc T f + setToSimpleFunc T' f := by classical simp_rw [setToSimpleFunc_eq_sum_filter] suffices ∀ x ∈ {x ∈ f.range | x ≠ 0}, T'' (f ⁻¹' {x}) = T (f ⁻¹' {x}) + T' (f ⁻¹' {x}) by rw [← sum_add_distrib] refine Finset.sum_congr rfl fun x hx => ?_ rw [this x hx] push_cast rw [Pi.add_apply] intro x hx refine h_add (f ⁻¹' {x}) (measurableSet_preimage _ _) (measure_preimage_lt_top_of_integrable _ hf ?_) rw [mem_filter] at hx exact hx.2 theorem setToSimpleFunc_smul_left {m : MeasurableSpace α} (T : Set α → F →L[ℝ] F') (c : ℝ) (f : α →ₛ F) : setToSimpleFunc (fun s => c • T s) f = c • setToSimpleFunc T f := by simp_rw [setToSimpleFunc, ContinuousLinearMap.smul_apply, smul_sum] theorem setToSimpleFunc_smul_left' (T T' : Set α → E →L[ℝ] F') (c : ℝ) (h_smul : ∀ s, MeasurableSet s → μ s < ∞ → T' s = c • T s) {f : α →ₛ E} (hf : Integrable f μ) : setToSimpleFunc T' f = c • setToSimpleFunc T f := by classical simp_rw [setToSimpleFunc_eq_sum_filter] suffices ∀ x ∈ {x ∈ f.range | x ≠ 0}, T' (f ⁻¹' {x}) = c • T (f ⁻¹' {x}) by rw [smul_sum] refine Finset.sum_congr rfl fun x hx => ?_ rw [this x hx, ContinuousLinearMap.smul_apply] intro x hx refine h_smul (f ⁻¹' {x}) (measurableSet_preimage _ _) (measure_preimage_lt_top_of_integrable _ hf ?_) rw [mem_filter] at hx exact hx.2 theorem setToSimpleFunc_add (T : Set α → E →L[ℝ] F) (h_add : FinMeasAdditive μ T) {f g : α →ₛ E} (hf : Integrable f μ) (hg : Integrable g μ) : setToSimpleFunc T (f + g) = setToSimpleFunc T f + setToSimpleFunc T g := have hp_pair : Integrable (f.pair g) μ := integrable_pair hf hg calc setToSimpleFunc T (f + g) = ∑ x ∈ (pair f g).range, T (pair f g ⁻¹' {x}) (x.fst + x.snd) := by rw [add_eq_map₂, map_setToSimpleFunc T h_add hp_pair]; simp _ = ∑ x ∈ (pair f g).range, (T (pair f g ⁻¹' {x}) x.fst + T (pair f g ⁻¹' {x}) x.snd) := (Finset.sum_congr rfl fun _ _ => ContinuousLinearMap.map_add _ _ _) _ = (∑ x ∈ (pair f g).range, T (pair f g ⁻¹' {x}) x.fst) + ∑ x ∈ (pair f g).range, T (pair f g ⁻¹' {x}) x.snd := by rw [Finset.sum_add_distrib] _ = ((pair f g).map Prod.fst).setToSimpleFunc T + ((pair f g).map Prod.snd).setToSimpleFunc T := by rw [map_setToSimpleFunc T h_add hp_pair Prod.snd_zero, map_setToSimpleFunc T h_add hp_pair Prod.fst_zero] theorem setToSimpleFunc_neg (T : Set α → E →L[ℝ] F) (h_add : FinMeasAdditive μ T) {f : α →ₛ E} (hf : Integrable f μ) : setToSimpleFunc T (-f) = -setToSimpleFunc T f := calc setToSimpleFunc T (-f) = setToSimpleFunc T (f.map Neg.neg) := rfl _ = -setToSimpleFunc T f := by rw [map_setToSimpleFunc T h_add hf neg_zero, setToSimpleFunc, ← sum_neg_distrib] exact Finset.sum_congr rfl fun x _ => ContinuousLinearMap.map_neg _ _ theorem setToSimpleFunc_sub (T : Set α → E →L[ℝ] F) (h_add : FinMeasAdditive μ T) {f g : α →ₛ E} (hf : Integrable f μ) (hg : Integrable g μ) : setToSimpleFunc T (f - g) = setToSimpleFunc T f - setToSimpleFunc T g := by rw [sub_eq_add_neg, setToSimpleFunc_add T h_add hf, setToSimpleFunc_neg T h_add hg, sub_eq_add_neg] rw [integrable_iff] at hg ⊢ intro x hx_ne rw [SimpleFunc.coe_neg, Pi.neg_def, ← Function.comp_def, preimage_comp, neg_preimage, Set.neg_singleton] refine hg (-x) ?_ simp [hx_ne] theorem setToSimpleFunc_smul_real (T : Set α → E →L[ℝ] F) (h_add : FinMeasAdditive μ T) (c : ℝ) {f : α →ₛ E} (hf : Integrable f μ) : setToSimpleFunc T (c • f) = c • setToSimpleFunc T f := calc setToSimpleFunc T (c • f) = ∑ x ∈ f.range, T (f ⁻¹' {x}) (c • x) := by rw [smul_eq_map c f, map_setToSimpleFunc T h_add hf]; dsimp only; rw [smul_zero] _ = ∑ x ∈ f.range, c • T (f ⁻¹' {x}) x := (Finset.sum_congr rfl fun b _ => by rw [ContinuousLinearMap.map_smul (T (f ⁻¹' {b})) c b]) _ = c • setToSimpleFunc T f := by simp only [setToSimpleFunc, smul_sum] theorem setToSimpleFunc_smul {E} [NormedAddCommGroup E] [SMulZeroClass 𝕜 E] [NormedSpace ℝ E] [DistribSMul 𝕜 F] (T : Set α → E →L[ℝ] F) (h_add : FinMeasAdditive μ T) (h_smul : ∀ c : 𝕜, ∀ s x, T s (c • x) = c • T s x) (c : 𝕜) {f : α →ₛ E} (hf : Integrable f μ) : setToSimpleFunc T (c • f) = c • setToSimpleFunc T f := calc setToSimpleFunc T (c • f) = ∑ x ∈ f.range, T (f ⁻¹' {x}) (c • x) := by rw [smul_eq_map c f, map_setToSimpleFunc T h_add hf]; dsimp only; rw [smul_zero] _ = ∑ x ∈ f.range, c • T (f ⁻¹' {x}) x := Finset.sum_congr rfl fun b _ => by rw [h_smul] _ = c • setToSimpleFunc T f := by simp only [setToSimpleFunc, smul_sum] section Order variable {G' G'' : Type*} [NormedAddCommGroup G''] [PartialOrder G''] [IsOrderedAddMonoid G''] [NormedSpace ℝ G''] [NormedAddCommGroup G'] [PartialOrder G'] [NormedSpace ℝ G'] theorem setToSimpleFunc_mono_left {m : MeasurableSpace α} (T T' : Set α → F →L[ℝ] G'') (hTT' : ∀ s x, T s x ≤ T' s x) (f : α →ₛ F) : setToSimpleFunc T f ≤ setToSimpleFunc T' f := by simp_rw [setToSimpleFunc]; exact sum_le_sum fun i _ => hTT' _ i theorem setToSimpleFunc_mono_left' (T T' : Set α → E →L[ℝ] G'') (hTT' : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, T s x ≤ T' s x) (f : α →ₛ E) (hf : Integrable f μ) : setToSimpleFunc T f ≤ setToSimpleFunc T' f := by refine sum_le_sum fun i _ => ?_ by_cases h0 : i = 0 · simp [h0] · exact hTT' _ (measurableSet_fiber _ _) (measure_preimage_lt_top_of_integrable _ hf h0) i theorem setToSimpleFunc_nonneg {m : MeasurableSpace α} (T : Set α → G' →L[ℝ] G'') (hT_nonneg : ∀ s x, 0 ≤ x → 0 ≤ T s x) (f : α →ₛ G') (hf : 0 ≤ f) : 0 ≤ setToSimpleFunc T f := by refine sum_nonneg fun i hi => hT_nonneg _ i ?_ rw [mem_range] at hi obtain ⟨y, hy⟩ := Set.mem_range.mp hi rw [← hy] refine le_trans ?_ (hf y) simp theorem setToSimpleFunc_nonneg' (T : Set α → G' →L[ℝ] G'') (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) (f : α →ₛ G') (hf : 0 ≤ f) (hfi : Integrable f μ) : 0 ≤ setToSimpleFunc T f := by refine sum_nonneg fun i hi => ?_ by_cases h0 : i = 0 · simp [h0] refine hT_nonneg _ (measurableSet_fiber _ _) (measure_preimage_lt_top_of_integrable _ hfi h0) i ?_ rw [mem_range] at hi obtain ⟨y, hy⟩ := Set.mem_range.mp hi rw [← hy] convert hf y theorem setToSimpleFunc_mono [IsOrderedAddMonoid G'] {T : Set α → G' →L[ℝ] G''} (h_add : FinMeasAdditive μ T) (hT_nonneg : ∀ s, MeasurableSet s → μ s < ∞ → ∀ x, 0 ≤ x → 0 ≤ T s x) {f g : α →ₛ G'} (hfi : Integrable f μ) (hgi : Integrable g μ) (hfg : f ≤ g) : setToSimpleFunc T f ≤ setToSimpleFunc T g := by rw [← sub_nonneg, ← setToSimpleFunc_sub T h_add hgi hfi] refine setToSimpleFunc_nonneg' T hT_nonneg _ ?_ (hgi.sub hfi) intro x simp only [coe_sub, sub_nonneg, coe_zero, Pi.zero_apply, Pi.sub_apply] exact hfg x end Order theorem norm_setToSimpleFunc_le_sum_opNorm {m : MeasurableSpace α} (T : Set α → F' →L[ℝ] F) (f : α →ₛ F') : ‖f.setToSimpleFunc T‖ ≤ ∑ x ∈ f.range, ‖T (f ⁻¹' {x})‖ * ‖x‖ := calc ‖∑ x ∈ f.range, T (f ⁻¹' {x}) x‖ ≤ ∑ x ∈ f.range, ‖T (f ⁻¹' {x}) x‖ := norm_sum_le _ _ _ ≤ ∑ x ∈ f.range, ‖T (f ⁻¹' {x})‖ * ‖x‖ := by refine Finset.sum_le_sum fun b _ => ?_; simp_rw [ContinuousLinearMap.le_opNorm] theorem norm_setToSimpleFunc_le_sum_mul_norm (T : Set α → F →L[ℝ] F') {C : ℝ} (hT_norm : ∀ s, MeasurableSet s → ‖T s‖ ≤ C * μ.real s) (f : α →ₛ F) : ‖f.setToSimpleFunc T‖ ≤ C * ∑ x ∈ f.range, μ.real (f ⁻¹' {x}) * ‖x‖ := calc ‖f.setToSimpleFunc T‖ ≤ ∑ x ∈ f.range, ‖T (f ⁻¹' {x})‖ * ‖x‖ := norm_setToSimpleFunc_le_sum_opNorm T f _ ≤ ∑ x ∈ f.range, C * μ.real (f ⁻¹' {x}) * ‖x‖ := by gcongr exact hT_norm _ <| SimpleFunc.measurableSet_fiber _ _ _ ≤ C * ∑ x ∈ f.range, μ.real (f ⁻¹' {x}) * ‖x‖ := by simp_rw [mul_sum, ← mul_assoc]; rfl theorem norm_setToSimpleFunc_le_sum_mul_norm_of_integrable (T : Set α → E →L[ℝ] F') {C : ℝ} (hT_norm : ∀ s, MeasurableSet s → μ s < ∞ → ‖T s‖ ≤ C * μ.real s) (f : α →ₛ E) (hf : Integrable f μ) : ‖f.setToSimpleFunc T‖ ≤ C * ∑ x ∈ f.range, μ.real (f ⁻¹' {x}) * ‖x‖ := calc ‖f.setToSimpleFunc T‖ ≤ ∑ x ∈ f.range, ‖T (f ⁻¹' {x})‖ * ‖x‖ := norm_setToSimpleFunc_le_sum_opNorm T f _ ≤ ∑ x ∈ f.range, C * μ.real (f ⁻¹' {x}) * ‖x‖ := by refine Finset.sum_le_sum fun b hb => ?_ obtain rfl | hb := eq_or_ne b 0 · simp gcongr exact hT_norm _ (SimpleFunc.measurableSet_fiber _ _) <| SimpleFunc.measure_preimage_lt_top_of_integrable _ hf hb _ ≤ C * ∑ x ∈ f.range, μ.real (f ⁻¹' {x}) * ‖x‖ := by simp_rw [mul_sum, ← mul_assoc]; rfl theorem setToSimpleFunc_indicator (T : Set α → F →L[ℝ] F') (hT_empty : T ∅ = 0) {m : MeasurableSpace α} {s : Set α} (hs : MeasurableSet s) (x : F) : SimpleFunc.setToSimpleFunc T (SimpleFunc.piecewise s hs (SimpleFunc.const α x) (SimpleFunc.const α 0)) = T s x := by classical obtain rfl | hs_empty := s.eq_empty_or_nonempty · simp only [hT_empty, ContinuousLinearMap.zero_apply, piecewise_empty, const_zero, setToSimpleFunc_zero_apply] simp_rw [setToSimpleFunc] obtain rfl | hs_univ := eq_or_ne s univ · haveI hα := hs_empty.to_type simp [← Function.const_def] rw [range_indicator hs hs_empty hs_univ] by_cases hx0 : x = 0 · simp_rw [hx0]; simp rw [sum_insert] swap; · rw [Finset.mem_singleton]; exact hx0 rw [sum_singleton, (T _).map_zero, add_zero] congr simp only [coe_piecewise, piecewise_eq_indicator, coe_const, Function.const_zero, piecewise_eq_indicator] rw [indicator_preimage, ← Function.const_def, preimage_const_of_mem] swap; · exact Set.mem_singleton x rw [← Function.const_zero, ← Function.const_def, preimage_const_of_notMem] swap; · rw [Set.mem_singleton_iff]; exact Ne.symm hx0 simp theorem setToSimpleFunc_const' [Nonempty α] (T : Set α → F →L[ℝ] F') (x : F) {m : MeasurableSpace α} : SimpleFunc.setToSimpleFunc T (SimpleFunc.const α x) = T univ x := by simp only [setToSimpleFunc, range_const, Set.mem_singleton, preimage_const_of_mem, sum_singleton, ← Function.const_def, coe_const] theorem setToSimpleFunc_const (T : Set α → F →L[ℝ] F') (hT_empty : T ∅ = 0) (x : F) {m : MeasurableSpace α} : SimpleFunc.setToSimpleFunc T (SimpleFunc.const α x) = T univ x := by cases isEmpty_or_nonempty α · have h_univ_empty : (univ : Set α) = ∅ := Subsingleton.elim _ _ rw [h_univ_empty, hT_empty] simp only [setToSimpleFunc, ContinuousLinearMap.zero_apply, sum_empty, range_eq_empty_of_isEmpty] · exact setToSimpleFunc_const' T x end SimpleFunc end MeasureTheory
Lax.lean
/- Copyright (c) 2024 Calle Sönne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne -/ import Mathlib.CategoryTheory.Bicategory.Functor.Prelax import Mathlib.Tactic.CategoryTheory.Slice import Mathlib.Tactic.CategoryTheory.ToApp /-! # Lax functors A lax functor `F` between bicategories `B` and `C` consists of * a function between objects `F.obj : B ⟶ C`, * a family of functions between 1-morphisms `F.map : (a ⟶ b) → (F.obj a ⟶ F.obj b)`, * a family of functions between 2-morphisms `F.map₂ : (f ⟶ g) → (F.map f ⟶ F.map g)`, * a family of 2-morphisms `F.mapId a : 𝟙 (F.obj a) ⟶ F.map (𝟙 a)`, * a family of 2-morphisms `F.mapComp f g : F.map f ≫ F.map g ⟶ F.map (f ≫ g)`, and * certain consistency conditions on them. ## Main definitions * `CategoryTheory.LaxFunctor B C` : an lax functor between bicategories `B` and `C` * `CategoryTheory.LaxFunctor.comp F G` : the composition of lax functors * `CategoryTheory.LaxFunctor.Pseudocore` : a structure on an Lax functor that promotes a Lax functor to a pseudofunctor ## Future work Some constructions in the bicategory library have only been done in terms of oplax functors, since lax functors had not yet been added (e.g `FunctorBicategory.lean`). A possible project would be to mirror these constructions for lax functors. -/ namespace CategoryTheory open Category Bicategory open Bicategory universe w₁ w₂ w₃ v₁ v₂ v₃ u₁ u₂ u₃ /-- A lax functor `F` between bicategories `B` and `C` consists of a function between objects `F.obj`, a function between 1-morphisms `F.map`, and a function between 2-morphisms `F.map₂`. Unlike functors between categories, `F.map` do not need to strictly commute with the composition, and do not need to strictly preserve the identity. Instead, there are specified 2-morphisms `𝟙 (F.obj a) ⟶ F.map (𝟙 a)` and `F.map f ≫ F.map g ⟶ F.map (f ≫ g)`. `F.map₂` strictly commute with compositions and preserve the identity. They also preserve the associator, the left unitor, and the right unitor modulo some adjustments of domains and codomains of 2-morphisms. -/ structure LaxFunctor (B : Type u₁) [Bicategory.{w₁, v₁} B] (C : Type u₂) [Bicategory.{w₂, v₂} C] extends PrelaxFunctor B C where /-- The 2-morphism underlying the lax unity constraint. -/ mapId (a : B) : 𝟙 (obj a) ⟶ map (𝟙 a) /-- The 2-morphism underlying the lax functoriality constraint. -/ mapComp {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : map f ≫ map g ⟶ map (f ≫ g) /-- Naturality of the lax functoriality constraint, on the left. -/ mapComp_naturality_left : ∀ {a b c : B} {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c), mapComp f g ≫ map₂ (η ▷ g) = map₂ η ▷ map g ≫ mapComp f' g:= by cat_disch /-- Naturality of the lax functoriality constraint, on the right. -/ mapComp_naturality_right : ∀ {a b c : B} (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g'), mapComp f g ≫ map₂ (f ◁ η) = map f ◁ map₂ η ≫ mapComp f g' := by cat_disch /-- Lax associativity. -/ map₂_associator : ∀ {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d), mapComp f g ▷ map h ≫ mapComp (f ≫ g) h ≫ map₂ (α_ f g h).hom = (α_ (map f) (map g) (map h)).hom ≫ map f ◁ mapComp g h ≫ mapComp f (g ≫ h) := by cat_disch /-- Lax left unity. -/ map₂_leftUnitor : ∀ {a b : B} (f : a ⟶ b), map₂ (λ_ f).inv = (λ_ (map f)).inv ≫ mapId a ▷ map f ≫ mapComp (𝟙 a) f := by cat_disch /-- Lax right unity. -/ map₂_rightUnitor : ∀ {a b : B} (f : a ⟶ b), map₂ (ρ_ f).inv = (ρ_ (map f)).inv ≫ map f ◁ mapId b ≫ mapComp f (𝟙 b) := by cat_disch initialize_simps_projections LaxFunctor (+toPrelaxFunctor, -obj, -map, -map₂) namespace LaxFunctor variable {B : Type u₁} [Bicategory.{w₁, v₁} B] {C : Type u₂} [Bicategory.{w₂, v₂} C] attribute [reassoc (attr := simp), to_app (attr := simp)] mapComp_naturality_left mapComp_naturality_right map₂_associator attribute [simp, reassoc, to_app] map₂_leftUnitor map₂_rightUnitor /-- The underlying prelax functor. -/ add_decl_doc LaxFunctor.toPrelaxFunctor variable (F : LaxFunctor B C) @[reassoc, to_app] lemma mapComp_assoc_left {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) : F.mapComp f g ▷ F.map h ≫ F.mapComp (f ≫ g) h = (α_ (F.map f) (F.map g) (F.map h)).hom ≫ F.map f ◁ F.mapComp g h ≫ F.mapComp f (g ≫ h) ≫ F.map₂ (α_ f g h).inv := by rw [← F.map₂_associator_assoc, ← F.map₂_comp] simp only [Iso.hom_inv_id, PrelaxFunctor.map₂_id, comp_id] @[reassoc, to_app] lemma mapComp_assoc_right {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) : F.map f ◁ F.mapComp g h ≫ F.mapComp f (g ≫ h) = (α_ (F.map f) (F.map g) (F.map h)).inv ≫ F.mapComp f g ▷ F.map h ≫ F.mapComp (f ≫ g) h ≫ F.map₂ (α_ f g h).hom := by simp only [map₂_associator, Iso.inv_hom_id_assoc] @[reassoc, to_app] lemma map₂_leftUnitor_hom {a b : B} (f : a ⟶ b) : (λ_ (F.map f)).hom = F.mapId a ▷ F.map f ≫ F.mapComp (𝟙 a) f ≫ F.map₂ (λ_ f).hom := by rw [← PrelaxFunctor.map₂Iso_hom, ← assoc, ← Iso.comp_inv_eq, ← Iso.eq_inv_comp] simp only [Functor.mapIso_inv, PrelaxFunctor.mapFunctor_map, map₂_leftUnitor] @[reassoc, to_app] lemma map₂_rightUnitor_hom {a b : B} (f : a ⟶ b) : (ρ_ (F.map f)).hom = F.map f ◁ F.mapId b ≫ F.mapComp f (𝟙 b) ≫ F.map₂ (ρ_ f).hom := by rw [← PrelaxFunctor.map₂Iso_hom, ← assoc, ← Iso.comp_inv_eq, ← Iso.eq_inv_comp] simp only [Functor.mapIso_inv, PrelaxFunctor.mapFunctor_map, map₂_rightUnitor] /-- The identity lax functor. -/ @[simps] def id (B : Type u₁) [Bicategory.{w₁, v₁} B] : LaxFunctor B B where toPrelaxFunctor := PrelaxFunctor.id B mapId := fun a => 𝟙 (𝟙 a) mapComp := fun f g => 𝟙 (f ≫ g) instance : Inhabited (LaxFunctor B B) := ⟨id B⟩ /-- Composition of lax functors. -/ @[simps] def comp {D : Type u₃} [Bicategory.{w₃, v₃} D] (F : LaxFunctor B C) (G : LaxFunctor C D) : LaxFunctor B D where toPrelaxFunctor := PrelaxFunctor.comp F.toPrelaxFunctor G.toPrelaxFunctor mapId := fun a => G.mapId (F.obj a) ≫ G.map₂ (F.mapId a) mapComp := fun f g => G.mapComp (F.map f) (F.map g) ≫ G.map₂ (F.mapComp f g) mapComp_naturality_left := fun η g => by dsimp rw [assoc, ← G.map₂_comp, mapComp_naturality_left, G.map₂_comp, mapComp_naturality_left_assoc] mapComp_naturality_right := fun f _ _ η => by dsimp rw [assoc, ← G.map₂_comp, mapComp_naturality_right, G.map₂_comp, mapComp_naturality_right_assoc] map₂_associator := fun f g h => by dsimp slice_rhs 1 3 => rw [Bicategory.whiskerLeft_comp, assoc, ← mapComp_naturality_right, ← map₂_associator_assoc] slice_rhs 3 5 => rw [← G.map₂_comp, ← G.map₂_comp, ← F.map₂_associator, G.map₂_comp, G.map₂_comp] slice_lhs 1 3 => rw [comp_whiskerRight, assoc, ← G.mapComp_naturality_left_assoc] simp only [assoc] map₂_leftUnitor := fun f => by dsimp simp only [map₂_leftUnitor, PrelaxFunctor.map₂_comp, assoc, mapComp_naturality_left_assoc, comp_whiskerRight] map₂_rightUnitor := fun f => by dsimp simp only [map₂_rightUnitor, PrelaxFunctor.map₂_comp, assoc, mapComp_naturality_right_assoc, Bicategory.whiskerLeft_comp] /-- A structure on an Lax functor that promotes an Lax functor to a pseudofunctor. See `Pseudofunctor.mkOfLax`. -/ structure PseudoCore (F : LaxFunctor B C) where /-- The isomorphism giving rise to the lax unity constraint -/ mapIdIso (a : B) : F.map (𝟙 a) ≅ 𝟙 (F.obj a) /-- The isomorphism giving rise to the lax functoriality constraint -/ mapCompIso {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : F.map (f ≫ g) ≅ F.map f ≫ F.map g /-- `mapIdIso` gives rise to the lax unity constraint -/ mapIdIso_inv {a : B} : (mapIdIso a).inv = F.mapId a := by cat_disch /-- `mapCompIso` gives rise to the lax functoriality constraint -/ mapCompIso_inv {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : (mapCompIso f g).inv = F.mapComp f g := by cat_disch attribute [simp] PseudoCore.mapIdIso_inv PseudoCore.mapCompIso_inv end LaxFunctor end CategoryTheory
Multiplicative.lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker, Aaron Anderson -/ import Mathlib.RingTheory.UniqueFactorizationDomain.NormalizedFactors /-! # Multiplicative maps on unique factorization domains ## Main results * `UniqueFactorizationMonoid.induction_on_coprime`: if `P` holds for `0`, units and powers of primes, and `P x ∧ P y` for coprime `x, y` implies `P (x * y)`, then `P` holds on all `a : α`. * `UniqueFactorizationMonoid.multiplicative_of_coprime`: if `f` maps `p ^ i` to `(f p) ^ i` for primes `p`, and `f` is multiplicative on coprime elements, then `f` is multiplicative everywhere. -/ assert_not_exists Field variable {α : Type*} namespace UniqueFactorizationMonoid variable {R : Type*} [CancelCommMonoidWithZero R] [UniqueFactorizationMonoid R] section Multiplicative variable [CancelCommMonoidWithZero α] [UniqueFactorizationMonoid α] variable {β : Type*} [CancelCommMonoidWithZero β] theorem prime_pow_coprime_prod_of_coprime_insert [DecidableEq α] {s : Finset α} (i : α → ℕ) (p : α) (hps : p ∉ s) (is_prime : ∀ q ∈ insert p s, Prime q) (is_coprime : ∀ᵉ (q ∈ insert p s) (q' ∈ insert p s), q ∣ q' → q = q') : IsRelPrime (p ^ i p) (∏ p' ∈ s, p' ^ i p') := by have hp := is_prime _ (Finset.mem_insert_self _ _) refine (isRelPrime_iff_no_prime_factors <| pow_ne_zero _ hp.ne_zero).mpr ?_ intro d hdp hdprod hd apply hps replace hdp := hd.dvd_of_dvd_pow hdp obtain ⟨q, q_mem', hdq⟩ := hd.exists_mem_multiset_dvd hdprod obtain ⟨q, q_mem, rfl⟩ := Multiset.mem_map.mp q_mem' replace hdq := hd.dvd_of_dvd_pow hdq have : p ∣ q := dvd_trans (hd.irreducible.dvd_symm hp.irreducible hdp) hdq convert q_mem using 0 rw [Finset.mem_val, is_coprime _ (Finset.mem_insert_self p s) _ (Finset.mem_insert_of_mem q_mem) this] /-- If `P` holds for units and powers of primes, and `P x ∧ P y` for coprime `x, y` implies `P (x * y)`, then `P` holds on a product of powers of distinct primes. -/ @[elab_as_elim] theorem induction_on_prime_power {P : α → Prop} (s : Finset α) (i : α → ℕ) (is_prime : ∀ p ∈ s, Prime p) (is_coprime : ∀ᵉ (p ∈ s) (q ∈ s), p ∣ q → p = q) (h1 : ∀ {x}, IsUnit x → P x) (hpr : ∀ {p} (i : ℕ), Prime p → P (p ^ i)) (hcp : ∀ {x y}, IsRelPrime x y → P x → P y → P (x * y)) : P (∏ p ∈ s, p ^ i p) := by letI := Classical.decEq α induction' s using Finset.induction_on with p f' hpf' ih · simpa using h1 isUnit_one rw [Finset.prod_insert hpf'] exact hcp (prime_pow_coprime_prod_of_coprime_insert i p hpf' is_prime is_coprime) (hpr (i p) (is_prime _ (Finset.mem_insert_self _ _))) (ih (fun q hq => is_prime _ (Finset.mem_insert_of_mem hq)) fun q hq q' hq' => is_coprime _ (Finset.mem_insert_of_mem hq) _ (Finset.mem_insert_of_mem hq')) /-- If `P` holds for `0`, units and powers of primes, and `P x ∧ P y` for coprime `x, y` implies `P (x * y)`, then `P` holds on all `a : α`. -/ @[elab_as_elim] theorem induction_on_coprime {P : α → Prop} (a : α) (h0 : P 0) (h1 : ∀ {x}, IsUnit x → P x) (hpr : ∀ {p} (i : ℕ), Prime p → P (p ^ i)) (hcp : ∀ {x y}, IsRelPrime x y → P x → P y → P (x * y)) : P a := by letI := Classical.decEq α have P_of_associated : ∀ {x y}, Associated x y → P x → P y := by rintro x y ⟨u, rfl⟩ hx exact hcp (fun p _ hpx => isUnit_of_dvd_unit hpx u.isUnit) hx (h1 u.isUnit) by_cases ha0 : a = 0 · rwa [ha0] haveI : Nontrivial α := ⟨⟨_, _, ha0⟩⟩ letI : NormalizationMonoid α := UniqueFactorizationMonoid.normalizationMonoid refine P_of_associated (prod_normalizedFactors ha0) ?_ rw [← (normalizedFactors a).map_id, Finset.prod_multiset_map_count] refine induction_on_prime_power _ _ ?_ ?_ @h1 @hpr @hcp <;> simp only [Multiset.mem_toFinset] · apply prime_of_normalized_factor · apply normalizedFactors_eq_of_dvd /-- If `f` maps `p ^ i` to `(f p) ^ i` for primes `p`, and `f` is multiplicative on coprime elements, then `f` is multiplicative on all products of primes. -/ theorem multiplicative_prime_power {f : α → β} (s : Finset α) (i j : α → ℕ) (is_prime : ∀ p ∈ s, Prime p) (is_coprime : ∀ᵉ (p ∈ s) (q ∈ s), p ∣ q → p = q) (h1 : ∀ {x y}, IsUnit y → f (x * y) = f x * f y) (hpr : ∀ {p} (i : ℕ), Prime p → f (p ^ i) = f p ^ i) (hcp : ∀ {x y}, IsRelPrime x y → f (x * y) = f x * f y) : f (∏ p ∈ s, p ^ (i p + j p)) = f (∏ p ∈ s, p ^ i p) * f (∏ p ∈ s, p ^ j p) := by letI := Classical.decEq α induction' s using Finset.induction_on with p s hps ih · simpa using h1 isUnit_one have hpr_p := is_prime _ (Finset.mem_insert_self _ _) have hpr_s : ∀ p ∈ s, Prime p := fun p hp => is_prime _ (Finset.mem_insert_of_mem hp) have hcp_p := fun i => prime_pow_coprime_prod_of_coprime_insert i p hps is_prime is_coprime have hcp_s : ∀ᵉ (p ∈ s) (q ∈ s), p ∣ q → p = q := fun p hp q hq => is_coprime p (Finset.mem_insert_of_mem hp) q (Finset.mem_insert_of_mem hq) rw [Finset.prod_insert hps, Finset.prod_insert hps, Finset.prod_insert hps, hcp (hcp_p _), hpr _ hpr_p, hcp (hcp_p _), hpr _ hpr_p, hcp (hcp_p (fun p => i p + j p)), hpr _ hpr_p, ih hpr_s hcp_s, pow_add, mul_assoc, mul_left_comm (f p ^ j p), mul_assoc] /-- If `f` maps `p ^ i` to `(f p) ^ i` for primes `p`, and `f` is multiplicative on coprime elements, then `f` is multiplicative everywhere. -/ theorem multiplicative_of_coprime (f : α → β) (a b : α) (h0 : f 0 = 0) (h1 : ∀ {x y}, IsUnit y → f (x * y) = f x * f y) (hpr : ∀ {p} (i : ℕ), Prime p → f (p ^ i) = f p ^ i) (hcp : ∀ {x y}, IsRelPrime x y → f (x * y) = f x * f y) : f (a * b) = f a * f b := by letI := Classical.decEq α by_cases ha0 : a = 0 · rw [ha0, zero_mul, h0, zero_mul] by_cases hb0 : b = 0 · rw [hb0, mul_zero, h0, mul_zero] by_cases hf1 : f 1 = 0 · calc f (a * b) = f (a * b * 1) := by rw [mul_one] _ = 0 := by simp only [h1 isUnit_one, hf1, mul_zero] _ = f a * f (b * 1) := by simp only [h1 isUnit_one, hf1, mul_zero] _ = f a * f b := by rw [mul_one] haveI : Nontrivial α := ⟨⟨_, _, ha0⟩⟩ letI : NormalizationMonoid α := UniqueFactorizationMonoid.normalizationMonoid suffices f (∏ p ∈ (normalizedFactors a).toFinset ∪ (normalizedFactors b).toFinset, p ^ ((normalizedFactors a).count p + (normalizedFactors b).count p)) = f (∏ p ∈ (normalizedFactors a).toFinset ∪ (normalizedFactors b).toFinset, p ^ (normalizedFactors a).count p) * f (∏ p ∈ (normalizedFactors a).toFinset ∪ (normalizedFactors b).toFinset, p ^ (normalizedFactors b).count p) by obtain ⟨ua, a_eq⟩ := prod_normalizedFactors ha0 obtain ⟨ub, b_eq⟩ := prod_normalizedFactors hb0 rw [← a_eq, ← b_eq, mul_right_comm (Multiset.prod (normalizedFactors a)) ua (Multiset.prod (normalizedFactors b) * ub), h1 ua.isUnit, h1 ub.isUnit, h1 ua.isUnit, ← mul_assoc, h1 ub.isUnit, mul_right_comm _ (f ua), ← mul_assoc] congr rw [← (normalizedFactors a).map_id, ← (normalizedFactors b).map_id, Finset.prod_multiset_map_count, Finset.prod_multiset_map_count, Finset.prod_subset (Finset.subset_union_left (s₂ := (normalizedFactors b).toFinset)), Finset.prod_subset (Finset.subset_union_right (s₂ := (normalizedFactors b).toFinset)), ← Finset.prod_mul_distrib] · simp_rw [id, ← pow_add, this] all_goals simp only [Multiset.mem_toFinset] · intro p _ hpb simp [hpb] · intro p _ hpa simp [hpa] refine multiplicative_prime_power _ _ _ ?_ ?_ @h1 @hpr @hcp all_goals simp only [Multiset.mem_toFinset, Finset.mem_union] · rintro p (hpa | hpb) <;> apply prime_of_normalized_factor <;> assumption · rintro p (hp | hp) q (hq | hq) hdvd <;> rw [← normalize_normalized_factor _ hp, ← normalize_normalized_factor _ hq] <;> exact normalize_eq_normalize hdvd ((prime_of_normalized_factor _ hp).irreducible.dvd_symm (prime_of_normalized_factor _ hq).irreducible hdvd) end Multiplicative end UniqueFactorizationMonoid
BigOperators.lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import Mathlib.Algebra.BigOperators.Balance import Mathlib.Data.Complex.Basic /-! # Finite sums and products of complex numbers -/ open Fintype open scoped BigOperators namespace Complex variable {α : Type*} (s : Finset α) @[simp, norm_cast] theorem ofReal_prod (f : α → ℝ) : ((∏ i ∈ s, f i : ℝ) : ℂ) = ∏ i ∈ s, (f i : ℂ) := map_prod ofRealHom _ _ @[simp, norm_cast] theorem ofReal_sum (f : α → ℝ) : ((∑ i ∈ s, f i : ℝ) : ℂ) = ∑ i ∈ s, (f i : ℂ) := map_sum ofRealHom _ _ @[simp, norm_cast] lemma ofReal_expect (f : α → ℝ) : (𝔼 i ∈ s, f i : ℝ) = 𝔼 i ∈ s, (f i : ℂ) := map_expect ofRealHom .. @[simp, norm_cast] lemma ofReal_balance [Fintype α] (f : α → ℝ) (a : α) : ((balance f a : ℝ) : ℂ) = balance ((↑) ∘ f) a := by simp [balance] @[simp] lemma ofReal_comp_balance {ι : Type*} [Fintype ι] (f : ι → ℝ) : ofReal ∘ balance f = balance (ofReal ∘ f : ι → ℂ) := funext <| ofReal_balance _ @[simp] theorem re_sum (f : α → ℂ) : (∑ i ∈ s, f i).re = ∑ i ∈ s, (f i).re := map_sum reAddGroupHom f s @[simp] lemma re_expect (f : α → ℂ) : (𝔼 i ∈ s, f i).re = 𝔼 i ∈ s, (f i).re := map_expect (LinearMap.mk reAddGroupHom.toAddHom (by simp)) f s @[simp] lemma re_balance [Fintype α] (f : α → ℂ) (a : α) : re (balance f a) = balance (re ∘ f) a := by simp [balance] @[simp] lemma re_comp_balance {ι : Type*} [Fintype ι] (f : ι → ℂ) : re ∘ balance f = balance (re ∘ f) := funext <| re_balance _ @[simp] theorem im_sum (f : α → ℂ) : (∑ i ∈ s, f i).im = ∑ i ∈ s, (f i).im := map_sum imAddGroupHom f s @[simp] lemma im_expect (f : α → ℂ) : (𝔼 i ∈ s, f i).im = 𝔼 i ∈ s, (f i).im := map_expect (LinearMap.mk imAddGroupHom.toAddHom (by simp)) f s @[simp] lemma im_balance [Fintype α] (f : α → ℂ) (a : α) : im (balance f a) = balance (im ∘ f) a := by simp [balance] @[simp] lemma im_comp_balance {ι : Type*} [Fintype ι] (f : ι → ℂ) : im ∘ balance f = balance (im ∘ f) := funext <| im_balance _ end Complex
StandardSmooth.lean
/- Copyright (c) 2024 Christian Merten. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jung Tao Cheng, Christian Merten, Andrew Yang -/ import Mathlib.Algebra.MvPolynomial.PDeriv import Mathlib.LinearAlgebra.Determinant import Mathlib.RingTheory.Extension.Presentation.Basic /-! # Standard smooth algebras In this file we define standard smooth algebras. For this we introduce the notion of a `PreSubmersivePresentation`. This is a presentation `P` that has fewer relations than generators. More precisely there exists an injective map from `σ` to `ι`. To such a presentation we may associate a jacobian. `P` is then a submersive presentation, if its jacobian is invertible. Finally, a standard smooth algebra is an algebra that admits a submersive presentation. While every standard smooth algebra is smooth, the converse does not hold. But if `S` is `R`-smooth, then `S` is `R`-standard smooth locally on `S`, i.e. there exists a set `{ t }` of `S` that generates the unit ideal, such that `Sₜ` is `R`-standard smooth for every `t` (TODO, see below). ## Main definitions All of these are in the `Algebra` namespace. Let `S` be an `R`-algebra. - `PreSubmersivePresentation`: A `Presentation` of `S` as `R`-algebra, equipped with an injective map `P.map` from `σ` to `ι`. This map is used to define the differential of a presubmersive presentation. For a presubmersive presentation `P` of `S` over `R` we make the following definitions: - `PreSubmersivePresentation.differential`: A linear endomorphism of `σ → P.Ring` sending the `j`-th standard basis vector, corresponding to the `j`-th relation, to the vector of partial derivatives of `P.relation j` with respect to the coordinates `P.map i` for `i : σ`. - `PreSubmersivePresentation.jacobian`: The determinant of `P.differential`. - `PreSubmersivePresentation.jacobiMatrix`: If `σ` has a `Fintype` instance, we may form the matrix corresponding to `P.differential`. Its determinant is `P.jacobian`. - `SubmersivePresentation`: A submersive presentation is a finite, presubmersive presentation `P` with in `S` invertible jacobian. Furthermore, for algebras we define: - `Algebra.IsStandardSmooth`: `S` is `R`-standard smooth if `S` admits a submersive `R`-presentation. - `Algebra.IsStandardSmooth.relativeDimension`: If `S` is `R`-standard smooth this is the dimension of an arbitrary submersive `R`-presentation of `S`. This is independent of the choice of the presentation (TODO, see below). - `Algebra.IsStandardSmoothOfRelativeDimension n`: `S` is `R`-standard smooth of relative dimension `n` if it admits a submersive `R`-presentation of dimension `n`. Finally, for ring homomorphisms we define: - `RingHom.IsStandardSmooth`: A ring homomorphism `R →+* S` is standard smooth if `S` is standard smooth as `R`-algebra. - `RingHom.IsStandardSmoothOfRelativeDimension n`: A ring homomorphism `R →+* S` is standard smooth of relative dimension `n` if `S` is standard smooth of relative dimension `n` as `R`-algebra. ## TODO - Show that the module of Kaehler differentials of a standard smooth `R`-algebra `S` of relative dimension `n` is `S`-free of rank `n`. In particular this shows that the relative dimension is independent of the choice of the standard smooth presentation. - Show that standard smooth algebras are smooth. This relies on the computation of the module of Kaehler differentials. - Show that locally on the target, smooth algebras are standard smooth. ## Implementation details Standard smooth algebras and ring homomorphisms feature 4 universe levels: The universe levels of the rings involved and the universe levels of the types of the variables and relations. ## Notes This contribution was created as part of the AIM workshop "Formalizing algebraic geometry" in June 2024. -/ universe t t' w w' u v open TensorProduct Module MvPolynomial variable (n m : ℕ) namespace Algebra variable (R : Type u) (S : Type v) (ι : Type w) (σ : Type t) [CommRing R] [CommRing S] [Algebra R S] /-- A `PreSubmersivePresentation` of an `R`-algebra `S` is a `Presentation` with relations equipped with an injective `map : relations → vars`. This map determines how the differential of `P` is constructed. See `PreSubmersivePresentation.differential` for details. -/ @[nolint checkUnivs] structure PreSubmersivePresentation extends Algebra.Presentation R S ι σ where /-- A map from the relations type to the variables type. Used to compute the differential. -/ map : σ → ι map_inj : Function.Injective map namespace PreSubmersivePresentation variable {R S ι σ} variable (P : PreSubmersivePresentation R S ι σ) include P in lemma card_relations_le_card_vars_of_isFinite [Finite ι] : Nat.card σ ≤ Nat.card ι := Nat.card_le_card_of_injective P.map P.map_inj section variable [Finite σ] /-- The standard basis of `σ → P.ring`. -/ noncomputable abbrev basis : Basis σ P.Ring (σ → P.Ring) := Pi.basisFun P.Ring σ /-- The differential of a `P : PreSubmersivePresentation` is a `P.Ring`-linear map on `σ → P.Ring`: The `j`-th standard basis vector, corresponding to the `j`-th relation of `P`, is mapped to the vector of partial derivatives of `P.relation j` with respect to the coordinates `P.map i` for all `i : σ`. The determinant of this map is the jacobian of `P` used to define when a `PreSubmersivePresentation` is submersive. See `PreSubmersivePresentation.jacobian`. -/ noncomputable def differential : (σ → P.Ring) →ₗ[P.Ring] (σ → P.Ring) := Basis.constr P.basis P.Ring (fun j i : σ ↦ MvPolynomial.pderiv (P.map i) (P.relation j)) /-- `PreSubmersivePresentation.differential` pushed forward to `S` via `aeval P.val`. -/ noncomputable def aevalDifferential : (σ → S) →ₗ[S] (σ → S) := (Pi.basisFun S σ).constr S (fun j i : σ ↦ aeval P.val <| pderiv (P.map i) (P.relation j)) @[simp] lemma aevalDifferential_single [DecidableEq σ] (i j : σ) : P.aevalDifferential (Pi.single i 1) j = aeval P.val (pderiv (P.map j) (P.relation i)) := by dsimp only [aevalDifferential] rw [← Pi.basisFun_apply, Basis.constr_basis] /-- The jacobian of a `P : PreSubmersivePresentation` is the determinant of `P.differential` viewed as element of `S`. -/ noncomputable def jacobian : S := algebraMap P.Ring S <| LinearMap.det P.differential end section Matrix variable [Fintype σ] [DecidableEq σ] /-- If `σ` has a `Fintype` and `DecidableEq` instance, the differential of `P` can be expressed in matrix form. -/ noncomputable def jacobiMatrix : Matrix σ σ P.Ring := LinearMap.toMatrix P.basis P.basis P.differential lemma jacobian_eq_jacobiMatrix_det : P.jacobian = algebraMap P.Ring S P.jacobiMatrix.det := by simp [jacobiMatrix, jacobian] lemma jacobiMatrix_apply (i j : σ) : P.jacobiMatrix i j = MvPolynomial.pderiv (P.map i) (P.relation j) := by simp [jacobiMatrix, LinearMap.toMatrix, differential, basis] lemma aevalDifferential_toMatrix'_eq_mapMatrix_jacobiMatrix : P.aevalDifferential.toMatrix' = (aeval P.val).mapMatrix P.jacobiMatrix := by ext i j : 1 rw [← LinearMap.toMatrix_eq_toMatrix'] rw [LinearMap.toMatrix_apply] simp [jacobiMatrix_apply] end Matrix section Constructions /-- If `algebraMap R S` is bijective, the empty generators are a pre-submersive presentation with no relations. -/ noncomputable def ofBijectiveAlgebraMap (h : Function.Bijective (algebraMap R S)) : PreSubmersivePresentation R S PEmpty.{w + 1} PEmpty.{t + 1} where toPresentation := Presentation.ofBijectiveAlgebraMap.{t, w} h map := PEmpty.elim map_inj (a b : PEmpty) h := by contradiction @[simp] lemma ofBijectiveAlgebraMap_jacobian (h : Function.Bijective (algebraMap R S)) : (ofBijectiveAlgebraMap h).jacobian = 1 := by classical have : (algebraMap (ofBijectiveAlgebraMap h).Ring S).mapMatrix (ofBijectiveAlgebraMap h).jacobiMatrix = 1 := by ext (i j : PEmpty) contradiction rw [jacobian_eq_jacobiMatrix_det, RingHom.map_det, this, Matrix.det_one] section Localization variable (r : R) [IsLocalization.Away r S] variable (S) in /-- If `S` is the localization of `R` at `r`, this is the canonical submersive presentation of `S` as `R`-algebra. -/ @[simps map] noncomputable def localizationAway : PreSubmersivePresentation R S Unit Unit where __ := Presentation.localizationAway S r map _ := () map_inj _ _ h := h @[simp] lemma localizationAway_jacobiMatrix : (localizationAway S r).jacobiMatrix = Matrix.diagonal (fun () ↦ MvPolynomial.C r) := by have h : (pderiv ()) (C r * X () - 1) = C r := by simp ext (i : Unit) (j : Unit) : 1 rwa [jacobiMatrix_apply] @[simp] lemma localizationAway_jacobian : (localizationAway S r).jacobian = algebraMap R S r := by rw [jacobian_eq_jacobiMatrix_det, localizationAway_jacobiMatrix] simp [show Fintype.card (localizationAway r (S := S)).rels = 1 from rfl] end Localization section Composition variable {ι' σ' T : Type*} [CommRing T] [Algebra R T] [Algebra S T] [IsScalarTower R S T] variable (Q : PreSubmersivePresentation S T ι' σ') (P : PreSubmersivePresentation R S ι σ) /-- Given an `R`-algebra `S` and an `S`-algebra `T` with pre-submersive presentations, this is the canonical pre-submersive presentation of `T` as an `R`-algebra. -/ @[simps map] noncomputable def comp : PreSubmersivePresentation R T (ι' ⊕ ι) (σ' ⊕ σ) where __ := Q.toPresentation.comp P.toPresentation map := Sum.elim (fun rq ↦ Sum.inl <| Q.map rq) (fun rp ↦ Sum.inr <| P.map rp) map_inj := Function.Injective.sumElim ((Sum.inl_injective).comp (Q.map_inj)) ((Sum.inr_injective).comp (P.map_inj)) <| by simp lemma toPresentation_comp : (Q.comp P).toPresentation = Q.toPresentation.comp P.toPresentation := rfl lemma toGenerators_comp : (Q.comp P).toGenerators = Q.toGenerators.comp P.toGenerators := rfl /-- The dimension of the composition of two finite submersive presentations is the sum of the dimensions. -/ lemma dimension_comp_eq_dimension_add_dimension [Finite ι] [Finite ι'] [Finite σ] [Finite σ'] : (Q.comp P).dimension = Q.dimension + P.dimension := by simp only [Presentation.dimension] have : Nat.card σ ≤ Nat.card ι := card_relations_le_card_vars_of_isFinite P have : Nat.card σ' ≤ Nat.card ι' := card_relations_le_card_vars_of_isFinite Q simp only [Nat.card_sum] omega section /-! ### Jacobian of composition Let `S` be an `R`-algebra and `T` be an `S`-algebra with presentations `P` and `Q` respectively. In this section we compute the jacobian of the composition of `Q` and `P` to be the product of the jacobians. For this we use a block decomposition of the jacobi matrix and show that the upper-right block vanishes, the upper-left block has determinant jacobian of `Q` and the lower-right block has determinant jacobian of `P`. -/ variable [Fintype σ] [Fintype σ'] open scoped Classical in private lemma jacobiMatrix_comp_inl_inr (i : σ') (j : σ) : (Q.comp P).jacobiMatrix (Sum.inl i) (Sum.inr j) = 0 := by classical rw [jacobiMatrix_apply] refine MvPolynomial.pderiv_eq_zero_of_notMem_vars (fun hmem ↦ ?_) apply MvPolynomial.vars_rename at hmem simp at hmem open scoped Classical in private lemma jacobiMatrix_comp_₁₂ : (Q.comp P).jacobiMatrix.toBlocks₁₂ = 0 := by ext i j : 1 simp [Matrix.toBlocks₁₂, jacobiMatrix_comp_inl_inr] section Q open scoped Classical in private lemma jacobiMatrix_comp_inl_inl (i j : σ') : aeval (Sum.elim X (MvPolynomial.C ∘ P.val)) ((Q.comp P).jacobiMatrix (Sum.inl j) (Sum.inl i)) = Q.jacobiMatrix j i := by rw [jacobiMatrix_apply, jacobiMatrix_apply, comp_map, Sum.elim_inl, ← Q.comp_aeval_relation_inl P.toPresentation] apply aeval_sumElim_pderiv_inl open scoped Classical in private lemma jacobiMatrix_comp_₁₁_det : (aeval (Q.comp P).val) (Q.comp P).jacobiMatrix.toBlocks₁₁.det = Q.jacobian := by rw [jacobian_eq_jacobiMatrix_det, AlgHom.map_det (aeval (Q.comp P).val), RingHom.map_det] congr ext i j : 1 simp only [Matrix.map_apply, RingHom.mapMatrix_apply, ← Q.jacobiMatrix_comp_inl_inl P, Q.algebraMap_apply] apply aeval_sumElim end Q section P open scoped Classical in private lemma jacobiMatrix_comp_inr_inr (i j : σ) : (Q.comp P).jacobiMatrix (Sum.inr i) (Sum.inr j) = MvPolynomial.rename Sum.inr (P.jacobiMatrix i j) := by rw [jacobiMatrix_apply, jacobiMatrix_apply] simp only [comp_map, Sum.elim_inr] apply pderiv_rename Sum.inr_injective open scoped Classical in private lemma jacobiMatrix_comp_₂₂_det : (aeval (Q.comp P).val) (Q.comp P).jacobiMatrix.toBlocks₂₂.det = algebraMap S T P.jacobian := by rw [jacobian_eq_jacobiMatrix_det] rw [AlgHom.map_det (aeval (Q.comp P).val), RingHom.map_det, RingHom.map_det] congr ext i j : 1 simp only [Matrix.toBlocks₂₂, AlgHom.mapMatrix_apply, Matrix.map_apply, Matrix.of_apply, RingHom.mapMatrix_apply, Generators.algebraMap_apply, map_aeval, coe_eval₂Hom] rw [jacobiMatrix_comp_inr_inr, ← IsScalarTower.algebraMap_eq] simp only [aeval, AlgHom.coe_mk, coe_eval₂Hom] generalize P.jacobiMatrix i j = p induction p using MvPolynomial.induction_on with | C a => simp only [algHom_C, algebraMap_eq, eval₂_C] | add p q hp hq => simp [hp, hq] | mul_X p i hp => simp only [map_mul, eval₂_mul, hp] simp [Presentation.toGenerators_comp, toPresentation_comp] end P end /-- The jacobian of the composition of presentations is the product of the jacobians. -/ @[simp] lemma comp_jacobian_eq_jacobian_smul_jacobian [Finite σ] [Finite σ'] : (Q.comp P).jacobian = P.jacobian • Q.jacobian := by classical cases nonempty_fintype σ' cases nonempty_fintype σ rw [jacobian_eq_jacobiMatrix_det, ← Matrix.fromBlocks_toBlocks ((Q.comp P).jacobiMatrix), jacobiMatrix_comp_₁₂] convert_to (aeval (Q.comp P).val) (Q.comp P).jacobiMatrix.toBlocks₁₁.det * (aeval (Q.comp P).val) (Q.comp P).jacobiMatrix.toBlocks₂₂.det = P.jacobian • Q.jacobian · simp only [Generators.algebraMap_apply, ← map_mul] congr convert Matrix.det_fromBlocks_zero₁₂ (Q.comp P).jacobiMatrix.toBlocks₁₁ (Q.comp P).jacobiMatrix.toBlocks₂₁ (Q.comp P).jacobiMatrix.toBlocks₂₂ · rw [jacobiMatrix_comp_₁₁_det, jacobiMatrix_comp_₂₂_det, mul_comm, Algebra.smul_def] end Composition section BaseChange variable (T : Type*) [CommRing T] [Algebra R T] (P : PreSubmersivePresentation R S ι σ) /-- If `P` is a pre-submersive presentation of `S` over `R` and `T` is an `R`-algebra, we obtain a natural pre-submersive presentation of `T ⊗[R] S` over `T`. -/ noncomputable def baseChange : PreSubmersivePresentation T (T ⊗[R] S) ι σ where __ := P.toPresentation.baseChange T map := P.map map_inj := P.map_inj lemma baseChange_toPresentation : (P.baseChange R).toPresentation = P.toPresentation.baseChange R := rfl lemma baseChange_ring : (P.baseChange R).Ring = P.Ring := rfl @[simp] lemma baseChange_jacobian [Finite σ] : (P.baseChange T).jacobian = 1 ⊗ₜ P.jacobian := by classical cases nonempty_fintype σ simp_rw [jacobian_eq_jacobiMatrix_det] have h : (baseChange T P).jacobiMatrix = (MvPolynomial.map (algebraMap R T)).mapMatrix P.jacobiMatrix := by ext i j : 1 simp only [baseChange, jacobiMatrix_apply, Presentation.baseChange_relation, RingHom.mapMatrix_apply, Matrix.map_apply, Presentation.baseChange_toGenerators, MvPolynomial.pderiv_map] rw [h] erw [← RingHom.map_det, aeval_map_algebraMap] rw [P.algebraMap_apply] apply aeval_one_tmul end BaseChange /-- Given a pre-submersive presentation `P` and equivalences `ι' ≃ ι` and `σ' ≃ σ`, this is the induced pre-sumbersive presentation with variables indexed by `ι` and relations indexed by `κ -/ @[simps toPresentation, simps -isSimp map] noncomputable def reindex (P : PreSubmersivePresentation R S ι σ) {ι' σ' : Type*} (e : ι' ≃ ι) (f : σ' ≃ σ) : PreSubmersivePresentation R S ι' σ' where __ := P.toPresentation.reindex e f map := e.symm ∘ P.map ∘ f map_inj := by rw [Function.Injective.of_comp_iff e.symm.injective, Function.Injective.of_comp_iff P.map_inj] exact f.injective lemma jacobiMatrix_reindex {ι' σ' : Type*} (e : ι' ≃ ι) (f : σ' ≃ σ) [Fintype σ'] [DecidableEq σ'] [Fintype σ] [DecidableEq σ] : (P.reindex e f).jacobiMatrix = (P.jacobiMatrix.reindex f.symm f.symm).map (MvPolynomial.rename e.symm) := by ext i j : 1 simp [jacobiMatrix_apply, MvPolynomial.pderiv_rename e.symm.injective, reindex, Presentation.reindex] @[simp] lemma jacobian_reindex (P : PreSubmersivePresentation R S ι σ) {ι' σ' : Type*} (e : ι' ≃ ι) (f : σ' ≃ σ) [Finite σ] [Finite σ'] : (P.reindex e f).jacobian = P.jacobian := by classical cases nonempty_fintype σ cases nonempty_fintype σ' simp_rw [PreSubmersivePresentation.jacobian_eq_jacobiMatrix_det] simp only [reindex_toPresentation, Presentation.reindex_toGenerators, jacobiMatrix_reindex, Matrix.reindex_apply, Equiv.symm_symm, Generators.algebraMap_apply, Generators.reindex_val] simp_rw [← MvPolynomial.aeval_rename, ← AlgHom.mapMatrix_apply, ← Matrix.det_submatrix_equiv_self f, AlgHom.map_det, AlgHom.mapMatrix_apply, Matrix.map_map] simp [← AlgHom.coe_comp, rename_comp_rename, rename_id] section variable {v : ι → MvPolynomial σ R} (a : ι → σ) (ha : Function.Injective a) (s : MvPolynomial σ R ⧸ (Ideal.span <| Set.range v) → MvPolynomial σ R := Function.surjInv Ideal.Quotient.mk_surjective) (hs : ∀ x, Ideal.Quotient.mk _ (s x) = x := by apply Function.surjInv_eq) /-- The naive pre-submersive presentation of a quotient `R[Xᵢ] ⧸ (vⱼ)`. If the definitional equality of the section matters, it can be explicitly provided. To construct the associated submersive presentation, use `PreSubmersivePresentation.jacobiMatrix_naive`. -/ @[simps! toPresentation] noncomputable def naive {v : ι → MvPolynomial σ R} (a : ι → σ) (ha : Function.Injective a) (s : MvPolynomial σ R ⧸ (Ideal.span <| Set.range v) → MvPolynomial σ R := Function.surjInv Ideal.Quotient.mk_surjective) (hs : ∀ x, Ideal.Quotient.mk _ (s x) = x := by apply Function.surjInv_eq) : PreSubmersivePresentation R (MvPolynomial σ R ⧸ (Ideal.span <| Set.range v)) σ ι where __ := Presentation.naive s hs map := a map_inj := ha @[simp] lemma jacobiMatrix_naive [Fintype ι] [DecidableEq ι] (i j : ι) : (naive a ha s hs).jacobiMatrix i j = (v j).pderiv (a i) := jacobiMatrix_apply _ _ _ end end Constructions end PreSubmersivePresentation variable [Finite σ] /-- A `PreSubmersivePresentation` is submersive if its jacobian is a unit in `S` and the presentation is finite. -/ @[nolint checkUnivs] structure SubmersivePresentation extends PreSubmersivePresentation.{t, w} R S ι σ where jacobian_isUnit : IsUnit toPreSubmersivePresentation.jacobian namespace SubmersivePresentation open PreSubmersivePresentation section Constructions variable {R S} in /-- If `algebraMap R S` is bijective, the empty generators are a submersive presentation with no relations. -/ noncomputable def ofBijectiveAlgebraMap (h : Function.Bijective (algebraMap R S)) : SubmersivePresentation R S PEmpty.{w + 1} PEmpty.{t + 1} where __ := PreSubmersivePresentation.ofBijectiveAlgebraMap.{t, w} h jacobian_isUnit := by rw [ofBijectiveAlgebraMap_jacobian] exact isUnit_one /-- The canonical submersive `R`-presentation of `R` with no generators and no relations. -/ noncomputable def id : SubmersivePresentation R R PEmpty.{w + 1} PEmpty.{t + 1} := ofBijectiveAlgebraMap Function.bijective_id section Composition variable {R S ι σ} variable {T ι' σ' : Type*} [CommRing T] [Algebra R T] [Algebra S T] [IsScalarTower R S T] variable [Finite σ'] (Q : SubmersivePresentation S T ι' σ') (P : SubmersivePresentation R S ι σ) /-- Given an `R`-algebra `S` and an `S`-algebra `T` with submersive presentations, this is the canonical submersive presentation of `T` as an `R`-algebra. -/ noncomputable def comp : SubmersivePresentation R T (ι' ⊕ ι) (σ' ⊕ σ) where __ := Q.toPreSubmersivePresentation.comp P.toPreSubmersivePresentation jacobian_isUnit := by rw [comp_jacobian_eq_jacobian_smul_jacobian, Algebra.smul_def, IsUnit.mul_iff] exact ⟨RingHom.isUnit_map _ <| P.jacobian_isUnit, Q.jacobian_isUnit⟩ end Composition section Localization variable {R} (r : R) [IsLocalization.Away r S] /-- If `S` is the localization of `R` at `r`, this is the canonical submersive presentation of `S` as `R`-algebra. -/ noncomputable def localizationAway : SubmersivePresentation R S Unit Unit where __ := PreSubmersivePresentation.localizationAway S r jacobian_isUnit := by rw [localizationAway_jacobian] apply IsLocalization.map_units' (⟨r, 1, by simp⟩ : Submonoid.powers r) end Localization section BaseChange variable (T) [CommRing T] [Algebra R T] (P : SubmersivePresentation R S ι σ) variable {R S ι σ} in /-- If `P` is a submersive presentation of `S` over `R` and `T` is an `R`-algebra, we obtain a natural submersive presentation of `T ⊗[R] S` over `T`. -/ noncomputable def baseChange : SubmersivePresentation T (T ⊗[R] S) ι σ where toPreSubmersivePresentation := P.toPreSubmersivePresentation.baseChange T jacobian_isUnit := P.baseChange_jacobian T ▸ P.jacobian_isUnit.map TensorProduct.includeRight end BaseChange variable {R S ι σ} in /-- Given a submersive presentation `P` and equivalences `ι' ≃ ι` and `σ' ≃ σ`, this is the induced sumbersive presentation with variables indexed by `ι'` and relations indexed by `σ'` -/ @[simps toPreSubmersivePresentation] noncomputable def reindex (P : SubmersivePresentation R S ι σ) {ι' σ' : Type*} [Finite σ'] (e : ι' ≃ ι) (f : σ' ≃ σ) : SubmersivePresentation R S ι' σ' where __ := P.toPreSubmersivePresentation.reindex e f jacobian_isUnit := by simp [P.jacobian_isUnit] end Constructions variable {R S ι σ} open Classical in /-- If `P` is submersive, `PreSubmersivePresentation.aevalDifferential` is an isomorphism. -/ noncomputable def aevalDifferentialEquiv (P : SubmersivePresentation R S ι σ) : (σ → S) ≃ₗ[S] (σ → S) := haveI : Fintype σ := Fintype.ofFinite σ have : IsUnit (LinearMap.toMatrix (Pi.basisFun S σ) (Pi.basisFun S σ) P.aevalDifferential).det := by convert P.jacobian_isUnit rw [LinearMap.toMatrix_eq_toMatrix', jacobian_eq_jacobiMatrix_det, aevalDifferential_toMatrix'_eq_mapMatrix_jacobiMatrix, P.algebraMap_eq] simp [RingHom.map_det] LinearEquiv.ofIsUnitDet this variable (P : SubmersivePresentation R S ι σ) @[simp] lemma aevalDifferentialEquiv_apply [Finite σ] (x : σ → S) : P.aevalDifferentialEquiv x = P.aevalDifferential x := rfl /-- If `P` is a submersive presentation, the partial derivatives of `P.relation i` by `P.map j` form a basis of `σ → S`. -/ noncomputable def basisDeriv (P : SubmersivePresentation R S ι σ) : Basis σ S (σ → S) := Basis.map (Pi.basisFun S σ) P.aevalDifferentialEquiv @[simp] lemma basisDeriv_apply (i j : σ) : P.basisDeriv i j = (aeval P.val) (pderiv (P.map j) (P.relation i)) := by classical simp [basisDeriv] lemma linearIndependent_aeval_val_pderiv_relation : LinearIndependent S (fun i j ↦ (aeval P.val) (pderiv (P.map j) (P.relation i))) := by simp_rw [← SubmersivePresentation.basisDeriv_apply] exact P.basisDeriv.linearIndependent end SubmersivePresentation attribute [local instance] Fintype.ofFinite /-- An `R`-algebra `S` is called standard smooth, if there exists a submersive presentation. -/ class IsStandardSmooth : Prop where out : ∃ (ι σ : Type) (_ : Finite σ), Finite ι ∧ Nonempty (SubmersivePresentation R S ι σ) lemma SubmersivePresentation.isStandardSmooth [Finite ι] (P : SubmersivePresentation R S ι σ) : IsStandardSmooth R S := by exact ⟨_, _, _, inferInstance, ⟨P.reindex (Fintype.equivFin _).symm (Fintype.equivFin _).symm⟩⟩ /-- The relative dimension of a standard smooth `R`-algebra `S` is the dimension of an arbitrarily chosen submersive `R`-presentation of `S`. Note: If `S` is non-trivial, this number is independent of the choice of the presentation as it is equal to the `S`-rank of `Ω[S/R]` (see `IsStandardSmoothOfRelativeDimension.rank_kaehlerDifferential`). -/ noncomputable def IsStandardSmooth.relativeDimension [IsStandardSmooth R S] : ℕ := letI := ‹IsStandardSmooth R S›.out.choose_spec.choose_spec.choose ‹IsStandardSmooth R S›.out.choose_spec.choose_spec.choose_spec.2.some.dimension /-- An `R`-algebra `S` is called standard smooth of relative dimension `n`, if there exists a submersive presentation of dimension `n`. -/ class IsStandardSmoothOfRelativeDimension : Prop where out : ∃ (ι σ : Type) (_ : Finite σ) (_ : Finite ι) (P : SubmersivePresentation R S ι σ), P.dimension = n lemma SubmersivePresentation.isStandardSmoothOfRelativeDimension [Finite ι] (P : SubmersivePresentation R S ι σ) (hP : P.dimension = n) : IsStandardSmoothOfRelativeDimension n R S := by refine ⟨⟨_, _, _, inferInstance, P.reindex (Fintype.equivFin _).symm (Fintype.equivFin σ).symm, ?_⟩⟩ simp [hP] variable {R} {S} lemma IsStandardSmoothOfRelativeDimension.isStandardSmooth [H : IsStandardSmoothOfRelativeDimension n R S] : IsStandardSmooth R S := ⟨_, _, _, H.out.choose_spec.choose_spec.choose_spec.choose, H.out.choose_spec.choose_spec.choose_spec.choose_spec.nonempty⟩ lemma IsStandardSmoothOfRelativeDimension.of_algebraMap_bijective (h : Function.Bijective (algebraMap R S)) : IsStandardSmoothOfRelativeDimension 0 R S := ⟨_, _, _, inferInstance, SubmersivePresentation.ofBijectiveAlgebraMap h, Presentation.ofBijectiveAlgebraMap_dimension h⟩ variable (R) in instance IsStandardSmoothOfRelativeDimension.id : IsStandardSmoothOfRelativeDimension 0 R R := IsStandardSmoothOfRelativeDimension.of_algebraMap_bijective Function.bijective_id instance (priority := 100) IsStandardSmooth.finitePresentation [IsStandardSmooth R S] : FinitePresentation R S := by obtain ⟨_, _, _, _, ⟨P⟩⟩ := ‹IsStandardSmooth R S› exact P.finitePresentation_of_isFinite section Composition variable (R S T) [CommRing T] [Algebra R T] [Algebra S T] [IsScalarTower R S T] lemma IsStandardSmooth.trans [IsStandardSmooth R S] [IsStandardSmooth S T] : IsStandardSmooth R T where out := by obtain ⟨_, _, _, _, ⟨P⟩⟩ := ‹IsStandardSmooth R S› obtain ⟨_, _, _, _, ⟨Q⟩⟩ := ‹IsStandardSmooth S T› exact ⟨_, _, _, inferInstance, ⟨Q.comp P⟩⟩ lemma IsStandardSmoothOfRelativeDimension.trans [IsStandardSmoothOfRelativeDimension n R S] [IsStandardSmoothOfRelativeDimension m S T] : IsStandardSmoothOfRelativeDimension (m + n) R T where out := by obtain ⟨_, _, _, _, P, hP⟩ := ‹IsStandardSmoothOfRelativeDimension n R S› obtain ⟨_, _, _, _, Q, hQ⟩ := ‹IsStandardSmoothOfRelativeDimension m S T› refine ⟨_, _, _, inferInstance, Q.comp P, hP ▸ hQ ▸ ?_⟩ apply PreSubmersivePresentation.dimension_comp_eq_dimension_add_dimension end Composition lemma IsStandardSmooth.localization_away (r : R) [IsLocalization.Away r S] : IsStandardSmooth R S where out := ⟨_, _, _, inferInstance, ⟨SubmersivePresentation.localizationAway S r⟩⟩ lemma IsStandardSmoothOfRelativeDimension.localization_away (r : R) [IsLocalization.Away r S] : IsStandardSmoothOfRelativeDimension 0 R S where out := ⟨_, _, _, inferInstance, SubmersivePresentation.localizationAway S r, Presentation.localizationAway_dimension_zero r⟩ section BaseChange variable (T) [CommRing T] [Algebra R T] instance IsStandardSmooth.baseChange [IsStandardSmooth R S] : IsStandardSmooth T (T ⊗[R] S) where out := by obtain ⟨ι, σ, _, _, ⟨P⟩⟩ := ‹IsStandardSmooth R S› exact ⟨ι, σ, _, inferInstance, ⟨P.baseChange T⟩⟩ instance IsStandardSmoothOfRelativeDimension.baseChange [IsStandardSmoothOfRelativeDimension n R S] : IsStandardSmoothOfRelativeDimension n T (T ⊗[R] S) where out := by obtain ⟨_, _, _, _, P, hP⟩ := ‹IsStandardSmoothOfRelativeDimension n R S› exact ⟨_, _, _, inferInstance, P.baseChange T, hP⟩ end BaseChange end Algebra
random.lean
import Mathlib.Control.Random import Mathlib.Tactic.NormNum import Batteries.Lean.LawfulMonad open Random -- TODO(kmill): remove once the mathlib ToExpr Int instance is removed set_option eval.pp false section Rand /-- info: 33 -/ #guard_msgs in #eval do IO.runRandWith 257 (show Rand _ from do let i ← randBound Int 3 30 (by norm_num) let j ← randBound Int 4 40 (by norm_num) return i.1 + j.1) -- using higher universes /-- info: ULift.up 19 -/ #guard_msgs in #eval do IO.runRandWith 257 (show Rand _ from do let i ← rand (ULift.{3} (Fin 20)) return i) end Rand -- using the monad transformer section RandT /-- info: Got 6 Got 27 --- info: 33 -/ #guard_msgs in #eval show IO _ from do IO.runRandWith 257 (do let i ← randBound Int 3 30 (by norm_num) IO.println s!"Got {i}" let j ← randBound Int 4 40 (by norm_num) IO.println s!"Got {j}" return i.1 + j.1) /-- info: Got 6 Got 27 --- info: 33 -/ #guard_msgs in #eval show Lean.Meta.MetaM _ from do IO.runRandWith 257 (do let i ← randBound Int 3 30 (by norm_num) IO.println s!"Got {i}" let j ← randBound Int 4 40 (by norm_num) IO.println s!"Got {j}" return i.1 + j.1) -- test that `MetaM` can access the global random number generator /-- info: Got 4 Got 4 --- info: 8 -/ #guard_msgs in #eval show Lean.Meta.MetaM _ from do IO.runRand (do -- since we don't know the seed, we use a trivial range here for determinism let i ← randBound Int 4 4 (by norm_num) IO.println s!"Got {i}" let j ← randBound Int 4 4 (by norm_num) IO.println s!"Got {i}" return i.1 + j.1) /-- info: GOOD -/ #guard_msgs in #eval show IO _ from do IO.runRandWith 257 <| do let mut count := 0 for _ in [:10000] do if (← randFin : Fin 3) == 1 then count := count + 1 if Float.abs (0.333 - (count / Nat.toFloat 10000)) < 0.01 then IO.println "GOOD" else IO.println "BAD" /-- info: GOOD -/ #guard_msgs in #eval show IO _ from do IO.runRandWith 257 <| do let mut count := 0 for _ in [:10000] do if (← randFin : Fin 2) == 0 then count := count + 1 if Float.abs (0.5 - (count / Nat.toFloat 10000)) < 0.01 then IO.println "GOOD" else IO.println "BAD" /-- info: GOOD -/ #guard_msgs in #eval show IO _ from do IO.runRandWith 257 <| do let mut count := 0 for _ in [:10000] do if (← randFin : Fin 10) == 5 then count := count + 1 if Float.abs (0.1 - (count / Nat.toFloat 10000)) < 0.01 then IO.println "GOOD" else IO.println "BAD" end RandT
Well.lean
/- Copyright (c) 2022 Yaël Dillies, Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Junyan Xu -/ import Mathlib.Data.Prod.Lex import Mathlib.SetTheory.Ordinal.Rank /-! # Extend a well-founded order to a well-order This file constructs a well-order (linear well-founded order) which is an extension of a given well-founded order. ## Proof idea We can map our order into two well-orders: * the first map respects the order but isn't necessarily injective. Namely, this is the *rank* function `IsWellFounded.rank : α → Ordinal`. * the second map is injective but doesn't necessarily respect the order. This is an arbitrary embedding into `Cardinal` given by `embeddingToCardinal`. Then their lexicographic product is a well-founded linear order which our original order injects in. ## Implementation note The definition in `mathlib` 3 used an auxiliary well-founded order on `α` lifted from `Cardinal`, instead of using `Cardinal` directly. The new definition is definitionally equal to the `mathlib` 3 version but avoids non-standard instances. ## Tags well founded relation, well order, extension -/ universe u variable {α : Type u} {r : α → α → Prop} namespace IsWellFounded variable {α : Type u} (r : α → α → Prop) [IsWellFounded α r] /-- An arbitrary well order on `α` that extends `r`. The construction maps `r` into two well-orders: the first map is `IsWellFounded.rank`, which is not necessarily injective but respects the order `r`; the other map is the identity (with an arbitrarily chosen well-order on `α`), which is injective but doesn't respect `r`. By taking the lexicographic product of the two, we get both properties, so we can pull it back and get a well-order that extend our original order `r`. Another way to view this is that we choose an arbitrary well-order to serve as a tiebreak between two elements of same rank. -/ noncomputable def wellOrderExtension : LinearOrder α := @LinearOrder.lift' α (Ordinal ×ₗ Cardinal) _ (fun a : α => (rank r a, embeddingToCardinal a)) fun _ _ h => embeddingToCardinal.injective <| congr_arg Prod.snd h instance wellOrderExtension.isWellFounded_lt : IsWellFounded α (wellOrderExtension r).lt := ⟨InvImage.wf (fun a : α => (rank r a, embeddingToCardinal a)) <| Ordinal.lt_wf.prod_lex Cardinal.lt_wf⟩ instance wellOrderExtension.isWellOrder_lt : IsWellOrder α (wellOrderExtension r).lt where /-- Any well-founded relation can be extended to a well-ordering on that type. -/ theorem exists_well_order_ge : ∃ s, r ≤ s ∧ IsWellOrder α s := ⟨(wellOrderExtension r).lt, fun _ _ h => Prod.Lex.left _ _ (rank_lt_of_rel h), ⟨⟩⟩ end IsWellFounded /-- A type alias for `α`, intended to extend a well-founded order on `α` to a well-order. -/ def WellOrderExtension (α : Type*) : Type _ := α instance [Inhabited α] : Inhabited (WellOrderExtension α) := ‹_› /-- "Identity" equivalence between a well-founded order and its well-order extension. -/ def toWellOrderExtension : α ≃ WellOrderExtension α := Equiv.refl _ noncomputable instance [LT α] [h : WellFoundedLT α] : LinearOrder (WellOrderExtension α) := h.wellOrderExtension instance WellOrderExtension.wellFoundedLT [LT α] [WellFoundedLT α] : WellFoundedLT (WellOrderExtension α) := IsWellFounded.wellOrderExtension.isWellFounded_lt (α := α) (· < ·) theorem toWellOrderExtension_strictMono [Preorder α] [WellFoundedLT α] : StrictMono (toWellOrderExtension : α → WellOrderExtension α) := fun _ _ h => Prod.Lex.left _ _ <| IsWellFounded.rank_lt_of_rel h
ModEq.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Data.Nat.ModEq /-! # Congruences modulo an integer This file defines the equivalence relation `a ≡ b [ZMOD n]` on the integers, similarly to how `Data.Nat.ModEq` defines them for the natural numbers. The notation is short for `n.ModEq a b`, which is defined to be `a % n = b % n` for integers `a b n`. ## Tags modeq, congruence, mod, MOD, modulo, integers -/ namespace Int /-- `a ≡ b [ZMOD n]` when `a % n = b % n`. -/ def ModEq (n a b : ℤ) := a % n = b % n @[inherit_doc] notation:50 a " ≡ " b " [ZMOD " n "]" => ModEq n a b variable {m n a b c d : ℤ} instance : Decidable (ModEq n a b) := decEq (a % n) (b % n) namespace ModEq @[refl, simp] protected theorem refl (a : ℤ) : a ≡ a [ZMOD n] := @rfl _ _ protected theorem rfl : a ≡ a [ZMOD n] := ModEq.refl _ instance : IsRefl _ (ModEq n) := ⟨ModEq.refl⟩ @[symm] protected theorem symm : a ≡ b [ZMOD n] → b ≡ a [ZMOD n] := Eq.symm @[trans] protected theorem trans : a ≡ b [ZMOD n] → b ≡ c [ZMOD n] → a ≡ c [ZMOD n] := Eq.trans instance : IsTrans ℤ (ModEq n) where trans := @Int.ModEq.trans n protected theorem eq : a ≡ b [ZMOD n] → a % n = b % n := id end ModEq theorem modEq_comm : a ≡ b [ZMOD n] ↔ b ≡ a [ZMOD n] := ⟨ModEq.symm, ModEq.symm⟩ @[simp] theorem natCast_modEq_iff {a b n : ℕ} : a ≡ b [ZMOD n] ↔ a ≡ b [MOD n] := by unfold ModEq Nat.ModEq; rw [← Int.ofNat_inj]; simp theorem modEq_zero_iff_dvd : a ≡ 0 [ZMOD n] ↔ n ∣ a := by rw [ModEq, zero_emod, dvd_iff_emod_eq_zero] theorem _root_.Dvd.dvd.modEq_zero_int (h : n ∣ a) : a ≡ 0 [ZMOD n] := modEq_zero_iff_dvd.2 h theorem _root_.Dvd.dvd.zero_modEq_int (h : n ∣ a) : 0 ≡ a [ZMOD n] := h.modEq_zero_int.symm theorem modEq_iff_dvd : a ≡ b [ZMOD n] ↔ n ∣ b - a := by rw [ModEq, eq_comm] simp [emod_eq_emod_iff_emod_sub_eq_zero, dvd_iff_emod_eq_zero] theorem modEq_iff_add_fac {a b n : ℤ} : a ≡ b [ZMOD n] ↔ ∃ t, b = a + n * t := by rw [modEq_iff_dvd] exact exists_congr fun t => sub_eq_iff_eq_add' alias ⟨ModEq.dvd, modEq_of_dvd⟩ := modEq_iff_dvd theorem mod_modEq (a n) : a % n ≡ a [ZMOD n] := emod_emod _ _ @[simp] theorem neg_modEq_neg : -a ≡ -b [ZMOD n] ↔ a ≡ b [ZMOD n] := by simp only [modEq_iff_dvd, (by omega : -b - -a = -(b - a)), Int.dvd_neg] @[simp] theorem modEq_neg : a ≡ b [ZMOD -n] ↔ a ≡ b [ZMOD n] := by simp [modEq_iff_dvd] namespace ModEq protected theorem of_dvd (d : m ∣ n) (h : a ≡ b [ZMOD n]) : a ≡ b [ZMOD m] := modEq_iff_dvd.2 <| d.trans h.dvd protected theorem mul_left' (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD c * n] := by obtain hc | rfl | hc := lt_trichotomy c 0 · rw [← neg_modEq_neg, ← modEq_neg, ← Int.neg_mul, ← Int.neg_mul, ← Int.neg_mul] simp only [ModEq, mul_emod_mul_of_pos _ _ (neg_pos.2 hc), h.eq] · simp only [Int.zero_mul, ModEq.rfl] · simp only [ModEq, mul_emod_mul_of_pos _ _ hc, h.eq] protected theorem mul_right' (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n * c] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact h.mul_left' @[gcongr] protected theorem add (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a + c ≡ b + d [ZMOD n] := modEq_iff_dvd.2 <| by convert Int.dvd_add h₁.dvd h₂.dvd using 1; omega protected theorem add_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c + a ≡ c + b [ZMOD n] := ModEq.rfl.add h protected theorem add_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a + c ≡ b + c [ZMOD n] := h.add ModEq.rfl protected theorem add_left_cancel (h₁ : a ≡ b [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : c ≡ d [ZMOD n] := have : d - c = b + d - (a + c) - (b - a) := by omega modEq_iff_dvd.2 <| by rw [this] exact Int.dvd_sub h₂.dvd h₁.dvd protected theorem add_left_cancel' (c : ℤ) (h : c + a ≡ c + b [ZMOD n]) : a ≡ b [ZMOD n] := ModEq.rfl.add_left_cancel h protected theorem add_right_cancel (h₁ : c ≡ d [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : a ≡ b [ZMOD n] := by rw [add_comm a, add_comm b] at h₂ exact h₁.add_left_cancel h₂ protected theorem add_right_cancel' (c : ℤ) (h : a + c ≡ b + c [ZMOD n]) : a ≡ b [ZMOD n] := ModEq.rfl.add_right_cancel h @[gcongr] protected theorem neg (h : a ≡ b [ZMOD n]) : -a ≡ -b [ZMOD n] := h.add_left_cancel (by simp_rw [← sub_eq_add_neg, sub_self]; rfl) @[gcongr] protected theorem sub (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a - c ≡ b - d [ZMOD n] := by rw [sub_eq_add_neg, sub_eq_add_neg] exact h₁.add h₂.neg protected theorem sub_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c - a ≡ c - b [ZMOD n] := ModEq.rfl.sub h protected theorem sub_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a - c ≡ b - c [ZMOD n] := h.sub ModEq.rfl protected theorem mul_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD n] := h.mul_left'.of_dvd <| dvd_mul_left _ _ protected theorem mul_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n] := h.mul_right'.of_dvd <| dvd_mul_right _ _ @[gcongr] protected theorem mul (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a * c ≡ b * d [ZMOD n] := (h₂.mul_left _).trans (h₁.mul_right _) @[gcongr] protected theorem pow (m : ℕ) (h : a ≡ b [ZMOD n]) : a ^ m ≡ b ^ m [ZMOD n] := by induction' m with d hd; · rfl rw [pow_succ, pow_succ] exact hd.mul h lemma of_mul_left (m : ℤ) (h : a ≡ b [ZMOD m * n]) : a ≡ b [ZMOD n] := by rw [modEq_iff_dvd] at *; exact (dvd_mul_left n m).trans h lemma of_mul_right (m : ℤ) : a ≡ b [ZMOD n * m] → a ≡ b [ZMOD n] := mul_comm m n ▸ of_mul_left _ /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c`. -/ theorem cancel_right_div_gcd (hm : 0 < m) (h : a * c ≡ b * c [ZMOD m]) : a ≡ b [ZMOD m / gcd m c] := by letI d := gcd m c rw [modEq_iff_dvd] at h ⊢ refine Int.dvd_of_dvd_mul_right_of_gcd_one (?_ : m / d ∣ c / d * (b - a)) ?_ · rw [mul_comm, ← Int.mul_ediv_assoc (b - a) (gcd_dvd_right ..), Int.sub_mul] exact Int.ediv_dvd_ediv (gcd_dvd_left ..) h · rw [gcd_div (gcd_dvd_left ..) (gcd_dvd_right ..), natAbs_natCast, Nat.div_self (gcd_pos_of_ne_zero_left c hm.ne')] /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c`. -/ theorem cancel_left_div_gcd (hm : 0 < m) (h : c * a ≡ c * b [ZMOD m]) : a ≡ b [ZMOD m / gcd m c] := cancel_right_div_gcd hm <| by simpa [mul_comm] using h theorem of_div (h : a / c ≡ b / c [ZMOD m / c]) (ha : c ∣ a) (ha : c ∣ b) (ha : c ∣ m) : a ≡ b [ZMOD m] := by convert h.mul_left' <;> rwa [Int.mul_ediv_cancel'] /-- Cancel left multiplication on both sides of the `≡` and in the modulus. For cancelling left multiplication in the modulus, see `Int.ModEq.of_mul_left`. -/ protected theorem mul_left_cancel' (hc : c ≠ 0) : c * a ≡ c * b [ZMOD c * m] → a ≡ b [ZMOD m] := by simp only [modEq_iff_dvd, ← Int.mul_sub] exact Int.dvd_of_mul_dvd_mul_left hc protected theorem mul_left_cancel_iff' (hc : c ≠ 0) : c * a ≡ c * b [ZMOD c * m] ↔ a ≡ b [ZMOD m] := ⟨ModEq.mul_left_cancel' hc, Int.ModEq.mul_left'⟩ /-- Cancel right multiplication on both sides of the `≡` and in the modulus. For cancelling right multiplication in the modulus, see `Int.ModEq.of_mul_right`. -/ protected theorem mul_right_cancel' (hc : c ≠ 0) : a * c ≡ b * c [ZMOD m * c] → a ≡ b [ZMOD m] := by simp only [modEq_iff_dvd, ← Int.sub_mul] exact Int.dvd_of_mul_dvd_mul_right hc protected theorem mul_right_cancel_iff' (hc : c ≠ 0) : a * c ≡ b * c [ZMOD m * c] ↔ a ≡ b [ZMOD m] := ⟨ModEq.mul_right_cancel' hc, ModEq.mul_right'⟩ end ModEq theorem modEq_one : a ≡ b [ZMOD 1] := modEq_of_dvd (one_dvd _) theorem modEq_sub (a b : ℤ) : a ≡ b [ZMOD a - b] := (modEq_of_dvd dvd_rfl).symm @[simp] theorem modEq_zero_iff : a ≡ b [ZMOD 0] ↔ a = b := by rw [ModEq, emod_zero, emod_zero] @[simp] theorem add_modEq_left : n + a ≡ a [ZMOD n] := ModEq.symm <| modEq_iff_dvd.2 <| by simp @[simp] theorem add_modEq_right : a + n ≡ a [ZMOD n] := ModEq.symm <| modEq_iff_dvd.2 <| by simp theorem modEq_and_modEq_iff_modEq_mul {a b m n : ℤ} (hmn : m.natAbs.Coprime n.natAbs) : a ≡ b [ZMOD m] ∧ a ≡ b [ZMOD n] ↔ a ≡ b [ZMOD m * n] := ⟨fun h => by rw [modEq_iff_dvd, modEq_iff_dvd] at h rw [modEq_iff_dvd, ← natAbs_dvd, ← dvd_natAbs, natCast_dvd_natCast, natAbs_mul] refine hmn.mul_dvd_of_dvd_of_dvd ?_ ?_ <;> rw [← natCast_dvd_natCast, natAbs_dvd, dvd_natAbs] <;> tauto, fun h => ⟨h.of_mul_right _, h.of_mul_left _⟩⟩ theorem gcd_a_modEq (a b : ℕ) : (a : ℤ) * Nat.gcdA a b ≡ Nat.gcd a b [ZMOD b] := by rw [← add_zero ((a : ℤ) * _), Nat.gcd_eq_gcd_ab] exact (dvd_mul_right _ _).zero_modEq_int.add_left _ theorem modEq_add_fac {a b n : ℤ} (c : ℤ) (ha : a ≡ b [ZMOD n]) : a + n * c ≡ b [ZMOD n] := calc a + n * c ≡ b + n * c [ZMOD n] := ha.add_right _ _ ≡ b + 0 [ZMOD n] := (dvd_mul_right _ _).modEq_zero_int.add_left _ _ ≡ b [ZMOD n] := by rw [add_zero] theorem modEq_sub_fac {a b n : ℤ} (c : ℤ) (ha : a ≡ b [ZMOD n]) : a - n * c ≡ b [ZMOD n] := by convert Int.modEq_add_fac (-c) ha using 1; rw [Int.mul_neg, sub_eq_add_neg] theorem modEq_add_fac_self {a t n : ℤ} : a + n * t ≡ a [ZMOD n] := modEq_add_fac _ ModEq.rfl theorem mod_coprime {a b : ℕ} (hab : Nat.Coprime a b) : ∃ y : ℤ, a * y ≡ 1 [ZMOD b] := ⟨Nat.gcdA a b, have hgcd : Nat.gcd a b = 1 := Nat.Coprime.gcd_eq_one hab calc ↑a * Nat.gcdA a b ≡ ↑a * Nat.gcdA a b + ↑b * Nat.gcdB a b [ZMOD ↑b] := ModEq.symm <| modEq_add_fac _ <| ModEq.refl _ _ ≡ 1 [ZMOD ↑b] := by rw [← Nat.gcd_eq_gcd_ab, hgcd]; rfl ⟩ theorem existsUnique_equiv (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℤ, 0 ≤ z ∧ z < b ∧ z ≡ a [ZMOD b] := ⟨a % b, emod_nonneg _ (ne_of_gt hb), by have : a % b < |b| := emod_lt_abs _ (ne_of_gt hb) rwa [abs_of_pos hb] at this, by simp [ModEq]⟩ theorem existsUnique_equiv_nat (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℕ, ↑z < b ∧ ↑z ≡ a [ZMOD b] := let ⟨z, hz1, hz2, hz3⟩ := existsUnique_equiv a hb ⟨z.natAbs, by constructor <;> rw [natAbs_of_nonneg hz1] <;> assumption⟩ theorem mod_mul_right_mod (a b c : ℤ) : a % (b * c) % b = a % b := (mod_modEq _ _).of_mul_right _ theorem mod_mul_left_mod (a b c : ℤ) : a % (b * c) % c = a % c := (mod_modEq _ _).of_mul_left _ end Int
Basic.lean
/- Copyright (c) 2022 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import Mathlib.Analysis.SpecialFunctions.ImproperIntegrals import Mathlib.MeasureTheory.Integral.ExpDecay /-! # The Gamma function This file defines the `Γ` function (of a real or complex variable `s`). We define this by Euler's integral `Γ(s) = ∫ x in Ioi 0, exp (-x) * x ^ (s - 1)` in the range where this integral converges (i.e., for `0 < s` in the real case, and `0 < re s` in the complex case). We show that this integral satisfies `Γ(1) = 1` and `Γ(s + 1) = s * Γ(s)`; hence we can define `Γ(s)` for all `s` as the unique function satisfying this recurrence and agreeing with Euler's integral in the convergence range. (If `s = -n` for `n ∈ ℕ`, then the function is undefined, and we set it to be `0` by convention.) ## Gamma function: main statements (complex case) * `Complex.Gamma`: the `Γ` function (of a complex variable). * `Complex.Gamma_eq_integral`: for `0 < re s`, `Γ(s)` agrees with Euler's integral. * `Complex.Gamma_add_one`: for all `s : ℂ` with `s ≠ 0`, we have `Γ (s + 1) = s Γ(s)`. * `Complex.Gamma_nat_eq_factorial`: for all `n : ℕ` we have `Γ (n + 1) = n!`. ## Gamma function: main statements (real case) * `Real.Gamma`: the `Γ` function (of a real variable). * Real counterparts of all the properties of the complex Gamma function listed above: `Real.Gamma_eq_integral`, `Real.Gamma_add_one`, `Real.Gamma_nat_eq_factorial`. ## Tags Gamma -/ noncomputable section open Filter intervalIntegral Set Real MeasureTheory Asymptotics open scoped Nat Topology ComplexConjugate namespace Real /-- Asymptotic bound for the `Γ` function integrand. -/ theorem Gamma_integrand_isLittleO (s : ℝ) : (fun x : ℝ => exp (-x) * x ^ s) =o[atTop] fun x : ℝ => exp (-(1 / 2) * x) := by refine isLittleO_of_tendsto (fun x hx => ?_) ?_ · exfalso; exact (exp_pos (-(1 / 2) * x)).ne' hx have : (fun x : ℝ => exp (-x) * x ^ s / exp (-(1 / 2) * x)) = (fun x : ℝ => exp (1 / 2 * x) / x ^ s)⁻¹ := by ext1 x field_simp [exp_ne_zero, exp_neg, ← Real.exp_add] left ring rw [this] exact (tendsto_exp_mul_div_rpow_atTop s (1 / 2) one_half_pos).inv_tendsto_atTop /-- The Euler integral for the `Γ` function converges for positive real `s`. -/ theorem GammaIntegral_convergent {s : ℝ} (h : 0 < s) : IntegrableOn (fun x : ℝ => exp (-x) * x ^ (s - 1)) (Ioi 0) := by rw [← Ioc_union_Ioi_eq_Ioi (@zero_le_one ℝ _ _ _ _), integrableOn_union] constructor · rw [← integrableOn_Icc_iff_integrableOn_Ioc] refine IntegrableOn.continuousOn_mul continuousOn_id.neg.rexp ?_ isCompact_Icc refine (intervalIntegrable_iff_integrableOn_Icc_of_le zero_le_one).mp ?_ exact intervalIntegrable_rpow' (by linarith) · refine integrable_of_isBigO_exp_neg one_half_pos ?_ (Gamma_integrand_isLittleO _).isBigO refine continuousOn_id.neg.rexp.mul (continuousOn_id.rpow_const ?_) intro x hx exact Or.inl ((zero_lt_one : (0 : ℝ) < 1).trans_le hx).ne' end Real namespace Complex /- Technical note: In defining the Gamma integrand exp (-x) * x ^ (s - 1) for s complex, we have to make a choice between ↑(Real.exp (-x)), Complex.exp (↑(-x)), and Complex.exp (-↑x), all of which are equal but not definitionally so. We use the first of these throughout. -/ /-- The integral defining the `Γ` function converges for complex `s` with `0 < re s`. This is proved by reduction to the real case. -/ theorem GammaIntegral_convergent {s : ℂ} (hs : 0 < s.re) : IntegrableOn (fun x => (-x).exp * x ^ (s - 1) : ℝ → ℂ) (Ioi 0) := by constructor · refine ContinuousOn.aestronglyMeasurable ?_ measurableSet_Ioi apply (continuous_ofReal.comp continuous_neg.rexp).continuousOn.mul apply continuousOn_of_forall_continuousAt intro x hx have : ContinuousAt (fun x : ℂ => x ^ (s - 1)) ↑x := continuousAt_cpow_const <| ofReal_mem_slitPlane.2 hx exact ContinuousAt.comp this continuous_ofReal.continuousAt · rw [← hasFiniteIntegral_norm_iff] refine HasFiniteIntegral.congr (Real.GammaIntegral_convergent hs).2 ?_ apply (ae_restrict_iff' measurableSet_Ioi).mpr filter_upwards with x hx rw [norm_mul, Complex.norm_of_nonneg <| le_of_lt <| exp_pos <| -x, norm_cpow_eq_rpow_re_of_pos hx _] simp /-- Euler's integral for the `Γ` function (of a complex variable `s`), defined as `∫ x in Ioi 0, exp (-x) * x ^ (s - 1)`. See `Complex.GammaIntegral_convergent` for a proof of the convergence of the integral for `0 < re s`. -/ def GammaIntegral (s : ℂ) : ℂ := ∫ x in Ioi (0 : ℝ), ↑(-x).exp * ↑x ^ (s - 1) theorem GammaIntegral_conj (s : ℂ) : GammaIntegral (conj s) = conj (GammaIntegral s) := by rw [GammaIntegral, GammaIntegral, ← integral_conj] refine setIntegral_congr_fun measurableSet_Ioi fun x hx => ?_ dsimp only rw [RingHom.map_mul, conj_ofReal, cpow_def_of_ne_zero (ofReal_ne_zero.mpr (ne_of_gt hx)), cpow_def_of_ne_zero (ofReal_ne_zero.mpr (ne_of_gt hx)), ← exp_conj, RingHom.map_mul, ← ofReal_log (le_of_lt hx), conj_ofReal, RingHom.map_sub, RingHom.map_one] theorem GammaIntegral_ofReal (s : ℝ) : GammaIntegral ↑s = ↑(∫ x : ℝ in Ioi 0, Real.exp (-x) * x ^ (s - 1)) := by have : ∀ r : ℝ, Complex.ofReal r = @RCLike.ofReal ℂ _ r := fun r => rfl rw [GammaIntegral] conv_rhs => rw [this, ← _root_.integral_ofReal] refine setIntegral_congr_fun measurableSet_Ioi ?_ intro x hx; dsimp only conv_rhs => rw [← this] rw [ofReal_mul, ofReal_cpow (mem_Ioi.mp hx).le] simp @[simp] theorem GammaIntegral_one : GammaIntegral 1 = 1 := by simpa only [← ofReal_one, GammaIntegral_ofReal, ofReal_inj, sub_self, rpow_zero, mul_one] using integral_exp_neg_Ioi_zero end Complex /-! Now we establish the recurrence relation `Γ(s + 1) = s * Γ(s)` using integration by parts. -/ namespace Complex section GammaRecurrence /-- The indefinite version of the `Γ` function, `Γ(s, X) = ∫ x ∈ 0..X, exp(-x) x ^ (s - 1)`. -/ def partialGamma (s : ℂ) (X : ℝ) : ℂ := ∫ x in (0)..X, (-x).exp * x ^ (s - 1) theorem tendsto_partialGamma {s : ℂ} (hs : 0 < s.re) : Tendsto (fun X : ℝ => partialGamma s X) atTop (𝓝 <| GammaIntegral s) := intervalIntegral_tendsto_integral_Ioi 0 (GammaIntegral_convergent hs) tendsto_id private theorem Gamma_integrand_intervalIntegrable (s : ℂ) {X : ℝ} (hs : 0 < s.re) (hX : 0 ≤ X) : IntervalIntegrable (fun x => (-x).exp * x ^ (s - 1) : ℝ → ℂ) volume 0 X := by rw [intervalIntegrable_iff_integrableOn_Ioc_of_le hX] exact IntegrableOn.mono_set (GammaIntegral_convergent hs) Ioc_subset_Ioi_self private theorem Gamma_integrand_deriv_integrable_A {s : ℂ} (hs : 0 < s.re) {X : ℝ} (hX : 0 ≤ X) : IntervalIntegrable (fun x => -((-x).exp * x ^ s) : ℝ → ℂ) volume 0 X := by convert (Gamma_integrand_intervalIntegrable (s + 1) _ hX).neg · simp only [ofReal_exp, ofReal_neg, add_sub_cancel_right]; rfl · simp only [add_re, one_re]; linarith private theorem Gamma_integrand_deriv_integrable_B {s : ℂ} (hs : 0 < s.re) {Y : ℝ} (hY : 0 ≤ Y) : IntervalIntegrable (fun x : ℝ => (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) volume 0 Y := by have : (fun x => (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) = (fun x => s * ((-x).exp * x ^ (s - 1)) : ℝ → ℂ) := by ext1; ring rw [this, intervalIntegrable_iff_integrableOn_Ioc_of_le hY] constructor · refine (continuousOn_const.mul ?_).aestronglyMeasurable measurableSet_Ioc apply (continuous_ofReal.comp continuous_neg.rexp).continuousOn.mul apply continuousOn_of_forall_continuousAt intro x hx refine (?_ : ContinuousAt (fun x : ℂ => x ^ (s - 1)) _).comp continuous_ofReal.continuousAt exact continuousAt_cpow_const <| ofReal_mem_slitPlane.2 hx.1 rw [← hasFiniteIntegral_norm_iff] simp_rw [norm_mul] refine (((Real.GammaIntegral_convergent hs).mono_set Ioc_subset_Ioi_self).hasFiniteIntegral.congr ?_).const_mul _ rw [EventuallyEq, ae_restrict_iff'] · filter_upwards with x hx rw [Complex.norm_of_nonneg (exp_pos _).le, norm_cpow_eq_rpow_re_of_pos hx.1] simp · exact measurableSet_Ioc /-- The recurrence relation for the indefinite version of the `Γ` function. -/ theorem partialGamma_add_one {s : ℂ} (hs : 0 < s.re) {X : ℝ} (hX : 0 ≤ X) : partialGamma (s + 1) X = s * partialGamma s X - (-X).exp * X ^ s := by rw [partialGamma, partialGamma, add_sub_cancel_right] have F_der_I : ∀ x : ℝ, x ∈ Ioo 0 X → HasDerivAt (fun x => (-x).exp * x ^ s : ℝ → ℂ) (-((-x).exp * x ^ s) + (-x).exp * (s * x ^ (s - 1))) x := by intro x hx have d1 : HasDerivAt (fun y : ℝ => (-y).exp) (-(-x).exp) x := by simpa using (hasDerivAt_neg x).exp have d2 : HasDerivAt (fun y : ℝ => (y : ℂ) ^ s) (s * x ^ (s - 1)) x := by have t := @HasDerivAt.cpow_const _ _ _ s (hasDerivAt_id ↑x) ?_ · simpa only [mul_one] using t.comp_ofReal · exact ofReal_mem_slitPlane.2 hx.1 simpa only [ofReal_neg, neg_mul] using d1.ofReal_comp.mul d2 have cont := (continuous_ofReal.comp continuous_neg.rexp).mul (continuous_ofReal_cpow_const hs) have der_ible := (Gamma_integrand_deriv_integrable_A hs hX).add (Gamma_integrand_deriv_integrable_B hs hX) have int_eval := integral_eq_sub_of_hasDerivAt_of_le hX cont.continuousOn F_der_I der_ible -- We are basically done here but manipulating the output into the right form is fiddly. apply_fun fun x : ℂ => -x at int_eval rw [intervalIntegral.integral_add (Gamma_integrand_deriv_integrable_A hs hX) (Gamma_integrand_deriv_integrable_B hs hX), intervalIntegral.integral_neg, neg_add, neg_neg] at int_eval rw [eq_sub_of_add_eq int_eval, sub_neg_eq_add, neg_sub, add_comm, add_sub] have : (fun x => (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) = (fun x => s * (-x).exp * x ^ (s - 1) : ℝ → ℂ) := by ext1; ring rw [this] rw [← intervalIntegral.integral_const_mul, ofReal_zero, zero_cpow] · rw [mul_zero, add_zero]; congr 2; ext1; ring · contrapose! hs; rw [hs, zero_re] /-- The recurrence relation for the `Γ` integral. -/ theorem GammaIntegral_add_one {s : ℂ} (hs : 0 < s.re) : GammaIntegral (s + 1) = s * GammaIntegral s := by suffices Tendsto (s + 1).partialGamma atTop (𝓝 <| s * GammaIntegral s) by refine tendsto_nhds_unique ?_ this apply tendsto_partialGamma; rw [add_re, one_re]; linarith have : (fun X : ℝ => s * partialGamma s X - X ^ s * (-X).exp) =ᶠ[atTop] (s + 1).partialGamma := by apply eventuallyEq_of_mem (Ici_mem_atTop (0 : ℝ)) intro X hX rw [partialGamma_add_one hs (mem_Ici.mp hX)] ring_nf refine Tendsto.congr' this ?_ suffices Tendsto (fun X => -X ^ s * (-X).exp : ℝ → ℂ) atTop (𝓝 0) by simpa using Tendsto.add (Tendsto.const_mul s (tendsto_partialGamma hs)) this rw [tendsto_zero_iff_norm_tendsto_zero] have : (fun e : ℝ => ‖-(e : ℂ) ^ s * (-e).exp‖) =ᶠ[atTop] fun e : ℝ => e ^ s.re * (-1 * e).exp := by refine eventuallyEq_of_mem (Ioi_mem_atTop 0) ?_ intro x hx; dsimp only rw [norm_mul, norm_neg, norm_cpow_eq_rpow_re_of_pos hx, Complex.norm_of_nonneg (exp_pos (-x)).le, neg_mul, one_mul] exact (tendsto_congr' this).mpr (tendsto_rpow_mul_exp_neg_mul_atTop_nhds_zero _ _ zero_lt_one) end GammaRecurrence /-! Now we define `Γ(s)` on the whole complex plane, by recursion. -/ section GammaDef /-- The `n`th function in this family is `Γ(s)` if `-n < s.re`, and junk otherwise. -/ noncomputable def GammaAux : ℕ → ℂ → ℂ | 0 => GammaIntegral | n + 1 => fun s : ℂ => GammaAux n (s + 1) / s theorem GammaAux_recurrence1 (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) : GammaAux n s = GammaAux n (s + 1) / s := by induction' n with n hn generalizing s · simp only [CharP.cast_eq_zero, Left.neg_neg_iff] at h1 dsimp only [GammaAux]; rw [GammaIntegral_add_one h1] rw [mul_comm, mul_div_cancel_right₀]; contrapose! h1; rw [h1] simp · dsimp only [GammaAux] have hh1 : -(s + 1).re < n := by rw [Nat.cast_add, Nat.cast_one] at h1 rw [add_re, one_re]; linarith rw [← hn (s + 1) hh1] theorem GammaAux_recurrence2 (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) : GammaAux n s = GammaAux (n + 1) s := by rcases n with - | n · simp only [CharP.cast_eq_zero, Left.neg_neg_iff] at h1 dsimp only [GammaAux] rw [GammaIntegral_add_one h1, mul_div_cancel_left₀] rintro rfl rw [zero_re] at h1 exact h1.false · dsimp only [GammaAux] have : GammaAux n (s + 1 + 1) / (s + 1) = GammaAux n (s + 1) := by have hh1 : -(s + 1).re < n := by rw [Nat.cast_add, Nat.cast_one] at h1 rw [add_re, one_re]; linarith rw [GammaAux_recurrence1 (s + 1) n hh1] rw [this] /-- The `Γ` function (of a complex variable `s`). -/ @[pp_nodot] irreducible_def Gamma (s : ℂ) : ℂ := GammaAux ⌊1 - s.re⌋₊ s theorem Gamma_eq_GammaAux (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) : Gamma s = GammaAux n s := by have u : ∀ k : ℕ, GammaAux (⌊1 - s.re⌋₊ + k) s = Gamma s := by intro k; induction' k with k hk · simp [Gamma] · rw [← hk, ← add_assoc] refine (GammaAux_recurrence2 s (⌊1 - s.re⌋₊ + k) ?_).symm rw [Nat.cast_add] have i0 := Nat.sub_one_lt_floor (1 - s.re) simp only [sub_sub_cancel_left] at i0 refine lt_add_of_lt_of_nonneg i0 ?_ rw [← Nat.cast_zero, Nat.cast_le]; exact Nat.zero_le k convert (u <| n - ⌊1 - s.re⌋₊).symm; rw [Nat.add_sub_of_le] by_cases h : 0 ≤ 1 - s.re · apply Nat.le_of_lt_succ exact_mod_cast lt_of_le_of_lt (Nat.floor_le h) (by linarith : 1 - s.re < n + 1) · rw [Nat.floor_of_nonpos] · omega · linarith /-- The recurrence relation for the `Γ` function. -/ theorem Gamma_add_one (s : ℂ) (h2 : s ≠ 0) : Gamma (s + 1) = s * Gamma s := by let n := ⌊1 - s.re⌋₊ have t1 : -s.re < n := by simpa only [sub_sub_cancel_left] using Nat.sub_one_lt_floor (1 - s.re) have t2 : -(s + 1).re < n := by rw [add_re, one_re]; linarith rw [Gamma_eq_GammaAux s n t1, Gamma_eq_GammaAux (s + 1) n t2, GammaAux_recurrence1 s n t1] field_simp theorem Gamma_eq_integral {s : ℂ} (hs : 0 < s.re) : Gamma s = GammaIntegral s := Gamma_eq_GammaAux s 0 (by norm_cast; linarith) @[simp] theorem Gamma_one : Gamma 1 = 1 := by rw [Gamma_eq_integral] <;> simp theorem Gamma_nat_eq_factorial (n : ℕ) : Gamma (n + 1) = n ! := by induction n with | zero => simp | succ n hn => rw [Gamma_add_one n.succ <| Nat.cast_ne_zero.mpr <| Nat.succ_ne_zero n] simp only [Nat.cast_succ, Nat.factorial_succ, Nat.cast_mul] congr @[simp] theorem Gamma_ofNat_eq_factorial (n : ℕ) [(n + 1).AtLeastTwo] : Gamma (ofNat(n + 1) : ℂ) = n ! := mod_cast Gamma_nat_eq_factorial (n : ℕ) /-- At `0` the Gamma function is undefined; by convention we assign it the value `0`. -/ @[simp] theorem Gamma_zero : Gamma 0 = 0 := by simp_rw [Gamma, zero_re, sub_zero, Nat.floor_one, GammaAux, div_zero] /-- At `-n` for `n ∈ ℕ`, the Gamma function is undefined; by convention we assign it the value 0. -/ theorem Gamma_neg_nat_eq_zero (n : ℕ) : Gamma (-n) = 0 := by induction n with | zero => rw [Nat.cast_zero, neg_zero, Gamma_zero] | succ n IH => have A : -(n.succ : ℂ) ≠ 0 := by rw [neg_ne_zero, Nat.cast_ne_zero] apply Nat.succ_ne_zero have : -(n : ℂ) = -↑n.succ + 1 := by simp rw [this, Gamma_add_one _ A] at IH contrapose! IH exact mul_ne_zero A IH theorem Gamma_conj (s : ℂ) : Gamma (conj s) = conj (Gamma s) := by suffices ∀ (n : ℕ) (s : ℂ), GammaAux n (conj s) = conj (GammaAux n s) by simp [Gamma, this] intro n induction n with | zero => rw [GammaAux]; exact GammaIntegral_conj | succ n IH => intro s rw [GammaAux] dsimp only rw [div_eq_mul_inv _ s, RingHom.map_mul, conj_inv, ← div_eq_mul_inv] suffices conj s + 1 = conj (s + 1) by rw [this, IH] rw [RingHom.map_add, RingHom.map_one] /-- Expresses the integral over `Ioi 0` of `t ^ (a - 1) * exp (-(r * t))` in terms of the Gamma function, for complex `a`. -/ lemma integral_cpow_mul_exp_neg_mul_Ioi {a : ℂ} {r : ℝ} (ha : 0 < a.re) (hr : 0 < r) : ∫ (t : ℝ) in Ioi 0, t ^ (a - 1) * exp (-(r * t)) = (1 / r) ^ a * Gamma a := by have aux : (1 / r : ℂ) ^ a = 1 / r * (1 / r) ^ (a - 1) := by nth_rewrite 2 [← cpow_one (1 / r : ℂ)] rw [← cpow_add _ _ (one_div_ne_zero <| ofReal_ne_zero.mpr hr.ne'), add_sub_cancel] calc _ = ∫ (t : ℝ) in Ioi 0, (1 / r) ^ (a - 1) * (r * t) ^ (a - 1) * exp (-(r * t)) := by refine MeasureTheory.setIntegral_congr_fun measurableSet_Ioi (fun x hx ↦ ?_) rw [mem_Ioi] at hx rw [mul_cpow_ofReal_nonneg hr.le hx.le, ← mul_assoc, one_div, ← ofReal_inv, ← mul_cpow_ofReal_nonneg (inv_pos.mpr hr).le hr.le, ← ofReal_mul r⁻¹, inv_mul_cancel₀ hr.ne', ofReal_one, one_cpow, one_mul] _ = 1 / r * ∫ (t : ℝ) in Ioi 0, (1 / r) ^ (a - 1) * t ^ (a - 1) * exp (-t) := by simp_rw [← ofReal_mul] rw [integral_comp_mul_left_Ioi (fun x ↦ _ * x ^ (a - 1) * exp (-x)) _ hr, mul_zero, real_smul, ← one_div, ofReal_div, ofReal_one] _ = 1 / r * (1 / r : ℂ) ^ (a - 1) * (∫ (t : ℝ) in Ioi 0, t ^ (a - 1) * exp (-t)) := by simp_rw [← MeasureTheory.integral_const_mul, mul_assoc] _ = (1 / r) ^ a * Gamma a := by rw [aux, Gamma_eq_integral ha] congr 2 with x rw [ofReal_exp, ofReal_neg, mul_comm] end GammaDef end Complex namespace Real /-- The `Γ` function (of a real variable `s`). -/ @[pp_nodot] def Gamma (s : ℝ) : ℝ := (Complex.Gamma s).re theorem Gamma_eq_integral {s : ℝ} (hs : 0 < s) : Gamma s = ∫ x in Ioi 0, exp (-x) * x ^ (s - 1) := by rw [Gamma, Complex.Gamma_eq_integral (by rwa [Complex.ofReal_re] : 0 < Complex.re s)] dsimp only [Complex.GammaIntegral] simp_rw [← Complex.ofReal_one, ← Complex.ofReal_sub] suffices ∫ x : ℝ in Ioi 0, ↑(exp (-x)) * (x : ℂ) ^ ((s - 1 : ℝ) : ℂ) = ∫ x : ℝ in Ioi 0, ((exp (-x) * x ^ (s - 1) : ℝ) : ℂ) by have cc : ∀ r : ℝ, Complex.ofReal r = @RCLike.ofReal ℂ _ r := fun r => rfl conv_lhs => rw [this]; enter [1, 2, x]; rw [cc] rw [_root_.integral_ofReal, ← cc, Complex.ofReal_re] refine setIntegral_congr_fun measurableSet_Ioi fun x hx => ?_ push_cast rw [Complex.ofReal_cpow (le_of_lt hx)] push_cast; rfl theorem Gamma_add_one {s : ℝ} (hs : s ≠ 0) : Gamma (s + 1) = s * Gamma s := by simp_rw [Gamma] rw [Complex.ofReal_add, Complex.ofReal_one, Complex.Gamma_add_one, Complex.re_ofReal_mul] rwa [Complex.ofReal_ne_zero] @[simp] theorem Gamma_one : Gamma 1 = 1 := by rw [Gamma, Complex.ofReal_one, Complex.Gamma_one, Complex.one_re] theorem _root_.Complex.Gamma_ofReal (s : ℝ) : Complex.Gamma (s : ℂ) = Gamma s := by rw [Gamma, eq_comm, ← Complex.conj_eq_iff_re, ← Complex.Gamma_conj, Complex.conj_ofReal] theorem Gamma_nat_eq_factorial (n : ℕ) : Gamma (n + 1) = n ! := by rw [Gamma, Complex.ofReal_add, Complex.ofReal_natCast, Complex.ofReal_one, Complex.Gamma_nat_eq_factorial, ← Complex.ofReal_natCast, Complex.ofReal_re] @[simp] theorem Gamma_ofNat_eq_factorial (n : ℕ) [(n + 1).AtLeastTwo] : Gamma (ofNat(n + 1) : ℝ) = n ! := mod_cast Gamma_nat_eq_factorial (n : ℕ) /-- At `0` the Gamma function is undefined; by convention we assign it the value `0`. -/ @[simp] theorem Gamma_zero : Gamma 0 = 0 := by simpa only [← Complex.ofReal_zero, Complex.Gamma_ofReal, Complex.ofReal_inj] using Complex.Gamma_zero /-- At `-n` for `n ∈ ℕ`, the Gamma function is undefined; by convention we assign it the value `0`. -/ theorem Gamma_neg_nat_eq_zero (n : ℕ) : Gamma (-n) = 0 := by simpa only [← Complex.ofReal_natCast, ← Complex.ofReal_neg, Complex.Gamma_ofReal, Complex.ofReal_eq_zero] using Complex.Gamma_neg_nat_eq_zero n theorem Gamma_pos_of_pos {s : ℝ} (hs : 0 < s) : 0 < Gamma s := by rw [Gamma_eq_integral hs] have : (Function.support fun x : ℝ => exp (-x) * x ^ (s - 1)) ∩ Ioi 0 = Ioi 0 := by rw [inter_eq_right] intro x hx rw [Function.mem_support] exact mul_ne_zero (exp_pos _).ne' (rpow_pos_of_pos hx _).ne' rw [setIntegral_pos_iff_support_of_nonneg_ae] · rw [this, volume_Ioi, ← ENNReal.ofReal_zero] exact ENNReal.ofReal_lt_top · refine eventually_of_mem (self_mem_ae_restrict measurableSet_Ioi) ?_ exact fun x hx => (mul_pos (exp_pos _) (rpow_pos_of_pos hx _)).le · exact GammaIntegral_convergent hs theorem Gamma_nonneg_of_nonneg {s : ℝ} (hs : 0 ≤ s) : 0 ≤ Gamma s := by obtain rfl | h := eq_or_lt_of_le hs · rw [Gamma_zero] · exact (Gamma_pos_of_pos h).le open Complex in /-- Expresses the integral over `Ioi 0` of `t ^ (a - 1) * exp (-(r * t))`, for positive real `r`, in terms of the Gamma function. -/ lemma integral_rpow_mul_exp_neg_mul_Ioi {a r : ℝ} (ha : 0 < a) (hr : 0 < r) : ∫ t : ℝ in Ioi 0, t ^ (a - 1) * exp (-(r * t)) = (1 / r) ^ a * Gamma a := by rw [← ofReal_inj, ofReal_mul, ← Gamma_ofReal, ofReal_cpow (by positivity), ofReal_div] convert integral_cpow_mul_exp_neg_mul_Ioi (by rwa [ofReal_re] : 0 < (a : ℂ).re) hr refine integral_ofReal.symm.trans <| setIntegral_congr_fun measurableSet_Ioi (fun t ht ↦ ?_) norm_cast simp_rw [← ofReal_cpow ht.le, RCLike.ofReal_mul, coe_algebraMap] open Lean.Meta Qq Mathlib.Meta.Positivity in /-- The `positivity` extension which identifies expressions of the form `Gamma a`. -/ @[positivity Gamma (_ : ℝ)] def _root_.Mathlib.Meta.Positivity.evalGamma : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ), ~q(Gamma $a) => match ← core q(inferInstance) q(inferInstance) a with | .positive pa => assertInstancesCommute pure (.positive q(Gamma_pos_of_pos $pa)) | .nonnegative pa => assertInstancesCommute pure (.nonnegative q(Gamma_nonneg_of_nonneg $pa)) | _ => pure .none | _, _, _ => throwError "failed to match on Gamma application" /-- The Gamma function does not vanish on `ℝ` (except at non-positive integers, where the function is mathematically undefined and we set it to `0` by convention). -/ theorem Gamma_ne_zero {s : ℝ} (hs : ∀ m : ℕ, s ≠ -m) : Gamma s ≠ 0 := by suffices ∀ {n : ℕ}, -(n : ℝ) < s → Gamma s ≠ 0 by apply this swap · exact ⌊-s⌋₊ + 1 rw [neg_lt, Nat.cast_add, Nat.cast_one] exact Nat.lt_floor_add_one _ intro n induction n generalizing s with | zero => intro hs refine (Gamma_pos_of_pos ?_).ne' rwa [Nat.cast_zero, neg_zero] at hs | succ _ n_ih => intro hs' have : Gamma (s + 1) ≠ 0 := by apply n_ih · intro m specialize hs (1 + m) contrapose! hs rw [← eq_sub_iff_add_eq] at hs rw [hs] push_cast ring · rw [Nat.cast_add, Nat.cast_one, neg_add] at hs' linarith rw [Gamma_add_one, mul_ne_zero_iff] at this · exact this.2 · simpa using hs 0 theorem Gamma_eq_zero_iff (s : ℝ) : Gamma s = 0 ↔ ∃ m : ℕ, s = -m := ⟨by contrapose!; exact Gamma_ne_zero, by rintro ⟨m, rfl⟩; exact Gamma_neg_nat_eq_zero m⟩ end Real
TypeTags.lean
/- Copyright (c) 2024 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import Mathlib.Order.SuccPred.Archimedean import Mathlib.Algebra.Order.Monoid.Unbundled.TypeTags /-! # Successor and predecessor on type tags This file declates successor and predecessor orders on type tags. -/ variable {X : Type*} instance [Preorder X] [h : SuccOrder X] : SuccOrder (Multiplicative X) := h instance [Preorder X] [h : SuccOrder X] : SuccOrder (Additive X) := h instance [Preorder X] [h : PredOrder X] : PredOrder (Multiplicative X) := h instance [Preorder X] [h : PredOrder X] : PredOrder (Additive X) := h instance [Preorder X] [SuccOrder X] [h : IsSuccArchimedean X] : IsSuccArchimedean (Multiplicative X) := h instance [Preorder X] [SuccOrder X] [h : IsSuccArchimedean X] : IsSuccArchimedean (Additive X) := h instance [Preorder X] [PredOrder X] [h : IsPredArchimedean X] : IsPredArchimedean (Multiplicative X) := h instance [Preorder X] [PredOrder X] [h : IsPredArchimedean X] : IsPredArchimedean (Additive X) := h namespace Order open Additive Multiplicative @[simp] lemma succ_ofMul [Preorder X] [SuccOrder X] (x : X) : succ (ofMul x) = ofMul (succ x) := rfl @[simp] lemma succ_toMul [Preorder X] [SuccOrder X] (x : Additive X) : succ x.toMul = (succ x).toMul := rfl @[simp] lemma succ_ofAdd [Preorder X] [SuccOrder X] (x : X) : succ (ofAdd x) = ofAdd (succ x) := rfl @[simp] lemma succ_toAdd [Preorder X] [SuccOrder X] (x : Multiplicative X) : succ x.toAdd = (succ x).toAdd := rfl @[simp] lemma pred_ofMul [Preorder X] [PredOrder X] (x : X) : pred (ofMul x) = ofMul (pred x) := rfl @[simp] lemma pred_toMul [Preorder X] [PredOrder X] (x : Additive X) : pred x.toMul = (pred x).toMul := rfl @[simp] lemma pred_ofAdd [Preorder X] [PredOrder X] (x : X) : pred (ofAdd x) = ofAdd (pred x) := rfl @[simp] lemma pred_toAdd [Preorder X] [PredOrder X] (x : Multiplicative X) : pred x.toAdd = (pred x).toAdd := rfl end Order
ModN.lean
/- Copyright (c) 2024 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Algebra.EuclideanDomain.Int import Mathlib.Algebra.Module.ZMod import Mathlib.LinearAlgebra.Dimension.Free /-! # Quotienting out a free `ℤ`-module If `G` is a rank `d` free `ℤ`-module, then `G/nG` is a finite group of cardinality `n ^ d`. -/ open Finsupp Function Module variable {G H M : Type*} [AddCommGroup G] {n : ℕ} variable (G n) in /-- `ModN G n` denotes the quotient of `G` by multiples of `n` -/ abbrev ModN : Type _ := G ⧸ LinearMap.range (LinearMap.lsmul ℤ G n) namespace ModN instance : Module (ZMod n) (ModN G n) := QuotientAddGroup.zmodModule (by simp) /-- The universal property of `ModN G n` in terms of monoids: Monoid homomorphisms from `ModN G n` are the same as monoid homormorphisms from `G` whose values are `n`-torsion. -/ protected def liftEquiv [AddMonoid M] : (ModN G n →+ M) ≃ {φ : G →+ M // ∀ g, n • φ g = 0} where toFun f := ⟨f.comp (QuotientAddGroup.mk' _), fun g ↦ by let Gn : AddSubgroup G := (LinearMap.range (LinearMap.lsmul ℤ G n)).toAddSubgroup suffices n • g ∈ (QuotientAddGroup.mk' Gn).ker by simp only [AddMonoidHom.coe_comp, comp_apply, ← map_nsmul] change f (QuotientAddGroup.mk' Gn (n • g)) = 0 -- Can we avoid `change`? rw [this, map_zero] simp [QuotientAddGroup.ker_mk', Gn]⟩ invFun φ := QuotientAddGroup.lift _ φ <| by rintro - ⟨g, rfl⟩; simpa using φ.property g left_inv f := by ext x induction x using QuotientAddGroup.induction_on rfl -- Should `simp` suffice here? right_inv φ := by aesop /-- The universal property of `ModN G n` in terms of `ZMod n`-modules: `ZMod n`-linear maps from `ModN G n` are the same as monoid homormorphisms from `G` whose values are `n`-torsion. -/ protected def liftEquiv' [AddCommGroup H] [Module (ZMod n) H] : (ModN G n →ₗ[ZMod n] H) ≃ {φ : G →+ H // ∀ g, n • φ g = 0} := (AddMonoidHom.toZModLinearMapEquiv n).symm.toEquiv.trans ModN.liftEquiv variable (n) in /-- The quotient map `G → G / nG`. -/ def mkQ : G →+ ModN G n := (LinearMap.range (LinearMap.lsmul ℤ G n)).mkQ variable [NeZero n] /-- Given a free module `G` over `ℤ`, construct the corresponding basis of `G / ⟨n⟩` over `ℤ / nℤ`. -/ noncomputable def basis {ι : Type*} (b : Basis ι ℤ G) : Basis ι (ZMod n) (ModN G n) := by set ψ : G →+ G := zsmulAddGroupHom n set nG := LinearMap.range (LinearMap.lsmul ℤ G n) set H := G ⧸ nG set φ : G →ₗ[ℤ] H := nG.mkQ let mod : (ι →₀ ℤ) →ₗ[ℤ] (ι →₀ ZMod n) := mapRange.linearMap (Int.castAddHom _).toIntLinearMap let f : G →ₗ[ℤ] (ι →₀ ℤ) := b.repr have hker : nG ≤ LinearMap.ker (mod.comp f) := by rintro _ ⟨x, rfl⟩ ext b simp [mod, f] let g : H →ₗ[ℤ] (ι →₀ ZMod n) := nG.liftQ (mod.comp f) hker refine ⟨.ofBijective (g.toAddMonoidHom.toZModLinearMap n) ⟨?_, ?_⟩⟩ · rw [AddMonoidHom.coe_toZModLinearMap, LinearMap.toAddMonoidHom_coe, injective_iff_map_eq_zero, nG.mkQ_surjective.forall] intro x hx simp only [Submodule.mkQ_apply, g] at hx rw [Submodule.liftQ_apply] at hx replace hx : ∀ b, ↑n ∣ f x b := by simpa [mod, DFunLike.ext_iff, ZMod.intCast_zmod_eq_zero_iff_dvd] using hx simp only [Submodule.mkQ_apply] rw [Submodule.Quotient.mk_eq_zero] choose c hc using hx refine ⟨b.repr.symm ⟨(f x).support, c, by simp [hc, NeZero.ne]⟩, b.repr.injective ?_⟩ simpa [DFunLike.ext_iff, eq_comm] using hc · suffices mod ∘ b.repr = g ∘ nG.mkQ by exact (this ▸ (mapRange_surjective _ (map_zero _) ZMod.intCast_surjective).comp b.repr.surjective).of_comp ext x b simp [mod, g, f, H] lemma basis_apply_eq_mkQ {ι : Type*} (b : Basis ι ℤ G) (i : ι) : basis b i = mkQ n (b i) := by rw [Basis.apply_eq_iff]; simp [basis, mkQ] variable [Module.Free ℤ G] [Module.Finite ℤ G] instance instModuleFinite : Module.Finite (ZMod n) (ModN G n) := .of_basis <| basis <| Module.Free.chooseBasis ℤ G instance instFinite : Finite (ModN G n) := Module.finite_of_finite (ZMod n) variable (G n) @[simp] lemma natCard_eq : Nat.card (ModN G n) = n ^ Module.finrank ℤ G := by simp [Nat.card_congr (basis <| Module.Free.chooseBasis ℤ G).repr.toEquiv, Nat.card_eq_fintype_card, Module.finrank_eq_card_chooseBasisIndex] end ModN
Basic.lean
/- Copyright (c) 2025 Dexin Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dexin Zhang -/ import Mathlib.Algebra.Group.Basic import Mathlib.ModelTheory.Semantics /-! # Presburger arithmetic This file defines the first-order language of Presburger arithmetic as (0,1,+). ## Main Definitions - `FirstOrder.Language.presburger`: the language of Presburger arithmetic. ## TODO - Generalize `presburger.sum` (maybe also `NatCast` and `SMul`) for classes like `FirstOrder.Language.IsOrdered`. - Define the theory of Presburger arithmetic and prove its properties (quantifier elimination, completeness, etc). -/ variable {α : Type*} namespace FirstOrder /-- The type of Presburger arithmetic functions, defined as (0, 1, +). -/ inductive presburgerFunc : ℕ → Type | zero : presburgerFunc 0 | one : presburgerFunc 0 | add : presburgerFunc 2 deriving DecidableEq /-- The language of Presburger arithmetic, defined as (0, 1, +). -/ def Language.presburger : Language := { Functions := presburgerFunc Relations := fun _ => Empty } deriving IsAlgebraic namespace Language.presburger variable {t t₁ t₂ : presburger.Term α} instance : Zero (presburger.Term α) where zero := Constants.term .zero instance : One (presburger.Term α) where one := Constants.term .one instance : Add (presburger.Term α) where add := Functions.apply₂ .add instance : NatCast (presburger.Term α) where natCast := Nat.unaryCast @[simp, norm_cast] theorem natCast_zero : (0 : ℕ) = (0 : presburger.Term α) := rfl @[simp, norm_cast] theorem natCast_succ (n : ℕ) : (n + 1 : ℕ) = (n : presburger.Term α) + 1 := rfl instance : SMul ℕ (presburger.Term α) where smul := nsmulRec @[simp] theorem zero_nsmul : 0 • t = 0 := rfl @[simp] theorem succ_nsmul {n : ℕ} : (n + 1) • t = n • t + t := rfl /-- Summation over a finite set of terms in Presburger arithmetic. It is defined via choice, so the result only makes sense when the structure satisfies commutativity (see `realize_sum`). -/ noncomputable def sum {β : Type*} (s : Finset β) (f : β → presburger.Term α) : presburger.Term α := (s.toList.map f).sum variable {M : Type*} {v : α → M} section variable [Zero M] [One M] [Add M] instance : presburger.Structure M where funMap | .zero, _ => 0 | .one, v => 1 | .add, v => v 0 + v 1 @[simp] theorem funMap_zero {v} : Structure.funMap (L := presburger) (M := M) presburgerFunc.zero v = 0 := rfl @[simp] theorem funMap_one {v} : Structure.funMap (L := presburger) (M := M) presburgerFunc.one v = 1 := rfl @[simp] theorem funMap_add {v} : Structure.funMap (L := presburger) (M := M) presburgerFunc.add v = v 0 + v 1 := rfl @[simp] theorem realize_zero : Term.realize v (0 : presburger.Term α) = 0 := rfl @[simp] theorem realize_one : Term.realize v (1 : presburger.Term α) = 1 := rfl @[simp] theorem realize_add : Term.realize v (t₁ + t₂) = Term.realize v t₁ + Term.realize v t₂ := rfl end @[simp] theorem realize_natCast [AddMonoidWithOne M] {n : ℕ} : Term.realize v (n : presburger.Term α) = n := by induction n with simp [*] @[simp] theorem realize_nsmul [AddMonoidWithOne M] {n : ℕ} : Term.realize v (n • t) = n • Term.realize v t := by induction n with simp [*, add_nsmul] @[simp] theorem realize_sum [AddCommMonoidWithOne M] {β : Type*} {s : Finset β} {f : β → presburger.Term α} : Term.realize v (sum s f) = ∑ i ∈ s, Term.realize v (f i) := by classical simp only [sum] conv => rhs; rw [← s.toList_toFinset, List.sum_toFinset _ s.nodup_toList] generalize s.toList = l induction l with simp [*] end FirstOrder.Language.presburger
CondVar.lean
/- Copyright (c) 2025 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.MeasureTheory.Function.ConditionalExpectation.Real import Mathlib.MeasureTheory.Integral.Average import Mathlib.Probability.Moments.Variance /-! # Conditional variance This file defines the variance of a real-valued random variable conditional to a sigma-algebra. ## TODO Define the Lebesgue conditional variance. See [GibbsMeasure](https://github.com/james18lpc/GibbsMeasure) for a definition of the Lebesgue conditional expectation). -/ open MeasureTheory Filter open scoped ENNReal namespace ProbabilityTheory variable {Ω : Type*} {m₀ m m' : MeasurableSpace Ω} {hm : m ≤ m₀} {X Y : Ω → ℝ} {μ : Measure[m₀] Ω} {s : Set Ω} variable (m X μ) in /-- Conditional variance of a real-valued random variable. It is defined as `0` if any one of the following conditions is true: - `m` is not a sub-σ-algebra of `m₀`, - `μ` is not σ-finite with respect to `m`, - `X - μ[X | m]` is not square-integrable. -/ noncomputable def condVar : Ω → ℝ := μ[(X - μ[X | m]) ^ 2 | m] @[inherit_doc] scoped notation "Var[" X "; " μ " | " m "]" => condVar m X μ /-- Conditional variance of a real-valued random variable. It is defined as `0` if any one of the following conditions is true: - `m` is not a sub-σ-algebra of `m₀`, - `volume` is not σ-finite with respect to `m`, - `X - 𝔼[X | m]` is not square-integrable. -/ scoped notation "Var[" f "|" m "]" => Var[f; MeasureTheory.volume | m] lemma condVar_of_not_le (hm : ¬m ≤ m₀) : Var[X; μ | m] = 0 := by rw [condVar, condExp_of_not_le hm] lemma condVar_of_not_sigmaFinite (hμm : ¬SigmaFinite (μ.trim hm)) : Var[X; μ | m] = 0 := by rw [condVar, condExp_of_not_sigmaFinite hm hμm] open scoped Classical in lemma condVar_of_sigmaFinite [SigmaFinite (μ.trim hm)] : Var[X; μ | m] = if Integrable (fun ω ↦ (X ω - (μ[X | m]) ω) ^ 2) μ then if StronglyMeasurable[m] (fun ω ↦ (X ω - (μ[X | m]) ω) ^ 2) then fun ω ↦ (X ω - (μ[X | m]) ω) ^ 2 else aestronglyMeasurable_condExpL1.mk (condExpL1 hm μ fun ω ↦ (X ω - (μ[X | m]) ω) ^ 2) else 0 := condExp_of_sigmaFinite _ lemma condVar_of_stronglyMeasurable [SigmaFinite (μ.trim hm)] (hX : StronglyMeasurable[m] X) (hXint : Integrable ((X - μ[X|m]) ^ 2) μ) : Var[X; μ | m] = fun ω ↦ (X ω - (μ[X | m]) ω) ^ 2 := condExp_of_stronglyMeasurable _ ((hX.sub stronglyMeasurable_condExp).pow _) hXint lemma condVar_of_not_integrable (hXint : ¬ Integrable (fun ω ↦ (X ω - (μ[X | m]) ω) ^ 2) μ) : Var[X; μ | m] = 0 := condExp_of_not_integrable hXint @[simp] lemma condVar_zero : Var[0; μ | m] = 0 := by simp [condVar] @[simp] lemma condVar_const (hm : m ≤ m₀) (c : ℝ) : Var[fun _ ↦ c; μ | m] = 0 := by obtain rfl | hc := eq_or_ne c 0 · simp [← Pi.zero_def] by_cases hμm : IsFiniteMeasure μ · simp [condVar, hm] · simp [condVar, condExp_of_not_integrable, integrable_const_iff_isFiniteMeasure hc, integrable_const_iff_isFiniteMeasure <| pow_ne_zero _ hc, hμm, Pi.pow_def] lemma stronglyMeasurable_condVar : StronglyMeasurable[m] (Var[X; μ | m]) := stronglyMeasurable_condExp lemma condVar_congr_ae (h : X =ᵐ[μ] Y) : Var[X; μ | m] =ᵐ[μ] Var[Y; μ | m] := condExp_congr_ae <| by filter_upwards [h, condExp_congr_ae h] with ω hω hω'; dsimp; rw [hω, hω'] lemma condVar_of_aestronglyMeasurable [hμm : SigmaFinite (μ.trim hm)] (hX : AEStronglyMeasurable[m] X μ) (hXint : Integrable ((X - μ[X|m]) ^ 2) μ) : Var[X; μ | m] =ᵐ[μ] (X - μ[X | m]) ^ 2 := condExp_of_aestronglyMeasurable' _ ((continuous_pow _).comp_aestronglyMeasurable (hX.sub stronglyMeasurable_condExp.aestronglyMeasurable)) hXint lemma integrable_condVar : Integrable Var[X; μ | m] μ := integrable_condExp /-- The integral of the conditional variance `Var[X | m]` over an `m`-measurable set is equal to the integral of `(X - μ[X | m]) ^ 2` on that set. -/ lemma setIntegral_condVar [SigmaFinite (μ.trim hm)] (hX : Integrable ((X - μ[X|m]) ^ 2) μ) (hs : MeasurableSet[m] s) : ∫ ω in s, (Var[X; μ | m]) ω ∂μ = ∫ ω in s, (X ω - (μ[X | m]) ω) ^ 2 ∂μ := setIntegral_condExp _ hX hs -- `(· ^ 2)` is a postfix operator called `_sq` in lemma names, but -- `condVar_ae_eq_condExp_sq_sub_condExp_sq` is a bit ridiculous, so we exceptionally denote it by -- `sq_` as it were a prefix. lemma condVar_ae_eq_condExp_sq_sub_sq_condExp (hm : m ≤ m₀) [IsFiniteMeasure μ] (hX : MemLp X 2 μ) : Var[X; μ | m] =ᵐ[μ] μ[X ^ 2 | m] - μ[X | m] ^ 2 := by calc Var[X; μ | m] _ = μ[X ^ 2 - 2 * X * μ[X | m] + μ[X | m] ^ 2 | m] := by rw [condVar, sub_sq] _ =ᵐ[μ] μ[X ^ 2 | m] - 2 * μ[X | m] ^ 2 + μ[X | m] ^ 2 := by have aux₀ : Integrable (X ^ 2) μ := hX.integrable_sq have aux₁ : Integrable (2 * X * μ[X | m]) μ := by rw [mul_assoc] exact (memLp_one_iff_integrable.1 <| hX.condExp.mul hX).const_mul _ have aux₂ : Integrable (μ[X | m] ^ 2) μ := hX.condExp.integrable_sq filter_upwards [condExp_add (m := m) (aux₀.sub aux₁) aux₂, condExp_sub (m := m) aux₀ aux₁, condExp_mul_of_stronglyMeasurable_right stronglyMeasurable_condExp aux₁ ((hX.integrable one_le_two).const_mul _), condExp_ofNat (m := m) 2 X] with ω hω₀ hω₁ hω₂ hω₃ simp [hω₀, hω₁, hω₂, hω₃, condExp_of_stronglyMeasurable hm (stronglyMeasurable_condExp.pow _) aux₂] simp [mul_assoc, sq] _ = μ[X ^ 2 | m] - μ[X | m] ^ 2 := by ring lemma condVar_ae_le_condExp_sq (hm : m ≤ m₀) [IsFiniteMeasure μ] (hX : MemLp X 2 μ) : Var[X; μ | m] ≤ᵐ[μ] μ[X ^ 2 | m] := by filter_upwards [condVar_ae_eq_condExp_sq_sub_sq_condExp hm hX] with ω hω dsimp at hω nlinarith /-- **Law of total variance** -/ lemma integral_condVar_add_variance_condExp (hm : m ≤ m₀) [IsProbabilityMeasure μ] (hX : MemLp X 2 μ) : μ[Var[X; μ | m]] + Var[μ[X | m]; μ] = Var[X; μ] := by calc μ[Var[X; μ | m]] + Var[μ[X | m]; μ] _ = μ[(μ[X ^ 2 | m] - μ[X | m] ^ 2 : Ω → ℝ)] + (μ[μ[X | m] ^ 2] - μ[μ[X | m]] ^ 2) := by congr 1 · exact integral_congr_ae <| condVar_ae_eq_condExp_sq_sub_sq_condExp hm hX · exact variance_eq_sub hX.condExp _ = μ[X ^ 2] - μ[μ[X | m] ^ 2] + (μ[μ[X | m] ^ 2] - μ[X] ^ 2) := by rw [integral_sub' integrable_condExp, integral_condExp hm, integral_condExp hm] exact hX.condExp.integrable_sq _ = Var[X; μ] := by rw [variance_eq_sub hX]; ring lemma condVar_bot' [NeZero μ] (X : Ω → ℝ) : Var[X; μ | ⊥] = fun _ => ⨍ ω, (X ω - ⨍ ω', X ω' ∂μ) ^ 2 ∂μ := by ext ω; simp [condVar, condExp_bot', average, measureReal_def] lemma condVar_bot_ae_eq (X : Ω → ℝ) : Var[X; μ | ⊥] =ᵐ[μ] fun _ ↦ ⨍ ω, (X ω - ⨍ ω', X ω' ∂μ) ^ 2 ∂μ := by obtain rfl | hμ := eq_zero_or_neZero μ · rw [ae_zero] exact eventually_bot · exact .of_forall <| congr_fun (condVar_bot' X) lemma condVar_bot [IsProbabilityMeasure μ] (hX : AEMeasurable X μ) : Var[X; μ | ⊥] = fun _ω ↦ Var[X; μ] := by simp [condVar_bot', average_eq_integral, variance_eq_integral hX] lemma condVar_smul (c : ℝ) (X : Ω → ℝ) : Var[c • X; μ | m] =ᵐ[μ] c ^ 2 • Var[X; μ | m] := by calc Var[c • X; μ | m] _ =ᵐ[μ] μ[c ^ 2 • (X - μ[X | m]) ^ 2 | m] := by rw [condVar] refine condExp_congr_ae ?_ filter_upwards [condExp_smul (m := m) c X] with ω hω simp [hω, ← mul_sub, mul_pow] _ =ᵐ[μ] c ^ 2 • Var[X; μ | m] := condExp_smul .. @[simp] lemma condVar_neg (X : Ω → ℝ) : Var[-X; μ | m] =ᵐ[μ] Var[X; μ | m] := by refine condExp_congr_ae ?_ filter_upwards [condExp_neg (m := m) X] with ω hω simp [hω] ring end ProbabilityTheory
DeltaGenerated.lean
/- Copyright (c) 2024 Ben Eltschig. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ben Eltschig -/ import Mathlib.CategoryTheory.Monad.Limits import Mathlib.Topology.Category.TopCat.Limits.Basic import Mathlib.Topology.Compactness.DeltaGeneratedSpace /-! # Delta-generated topological spaces The category of delta-generated spaces. See https://ncatlab.org/nlab/show/Delta-generated+topological+space. Adapted from `Mathlib/Topology/Category/CompactlyGenerated.lean`. ## TODO * `DeltaGenerated` is cartesian-closed. -/ universe u open CategoryTheory /-- The type of delta-generated topological spaces. -/ structure DeltaGenerated where /-- the underlying topological space -/ toTop : TopCat.{u} /-- The underlying topological space is delta-generated. -/ deltaGenerated : DeltaGeneratedSpace toTop := by infer_instance namespace DeltaGenerated instance : CoeSort DeltaGenerated Type* := ⟨fun X ↦ X.toTop⟩ attribute [instance] deltaGenerated instance : LargeCategory.{u} DeltaGenerated.{u} := InducedCategory.category toTop instance : ConcreteCategory.{u} DeltaGenerated.{u} (C(·, ·)) := InducedCategory.concreteCategory toTop /-- Constructor for objects of the category `DeltaGenerated` -/ abbrev of (X : Type u) [TopologicalSpace X] [DeltaGeneratedSpace X] : DeltaGenerated.{u} where toTop := TopCat.of X deltaGenerated := ‹_› /-- The forgetful functor `DeltaGenerated ⥤ TopCat` -/ @[simps!] def deltaGeneratedToTop : DeltaGenerated.{u} ⥤ TopCat.{u} := inducedFunctor _ /-- `deltaGeneratedToTop` is fully faithful. -/ def fullyFaithfulDeltaGeneratedToTop : deltaGeneratedToTop.{u}.FullyFaithful := fullyFaithfulInducedFunctor _ instance : deltaGeneratedToTop.{u}.Full := fullyFaithfulDeltaGeneratedToTop.full instance : deltaGeneratedToTop.{u}.Faithful := fullyFaithfulDeltaGeneratedToTop.faithful /-- The faithful (but not full) functor taking each topological space to its delta-generated coreflection. -/ @[simps!] def topToDeltaGenerated : TopCat.{u} ⥤ DeltaGenerated.{u} where obj X := of (DeltaGeneratedSpace.of X) map {_ Y} f := TopCat.ofHom ⟨f, (continuous_to_deltaGenerated (Y := Y)).mpr <| continuous_le_dom deltaGenerated_le f.hom.continuous⟩ instance : topToDeltaGenerated.{u}.Faithful := ⟨fun h ↦ by ext x; exact CategoryTheory.congr_fun h x⟩ /-- The adjunction between the forgetful functor `DeltaGenerated ⥤ TopCat` and its coreflector. -/ def coreflectorAdjunction : deltaGeneratedToTop ⊣ topToDeltaGenerated := Adjunction.mkOfUnitCounit { unit := { app X := TopCat.ofHom ⟨id, continuous_iff_coinduced_le.mpr (eq_deltaGenerated (X := X)).le⟩ } counit := { app X := TopCat.ofHom ⟨DeltaGeneratedSpace.counit, DeltaGeneratedSpace.continuous_counit⟩ }} /-- The category of delta-generated spaces is coreflective in the category of topological spaces. -/ instance deltaGeneratedToTop.coreflective : Coreflective deltaGeneratedToTop where R := topToDeltaGenerated adj := coreflectorAdjunction noncomputable instance deltaGeneratedToTop.createsColimits : CreatesColimits deltaGeneratedToTop := comonadicCreatesColimits deltaGeneratedToTop instance hasLimits : Limits.HasLimits DeltaGenerated := hasLimits_of_coreflective deltaGeneratedToTop instance hasColimits : Limits.HasColimits DeltaGenerated := hasColimits_of_hasColimits_createsColimits deltaGeneratedToTop end DeltaGenerated
Units.lean
/- Copyright (c) 2024 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Algebra.Group.Equiv.Defs import Mathlib.Algebra.Group.Pi.Basic import Mathlib.Algebra.Group.Units.Defs import Mathlib.Util.Delaborators /-! # Units in pi types -/ variable {ι : Type*} {M : ι → Type*} [∀ i, Monoid (M i)] {x : Π i, M i} open Units in /-- The monoid equivalence between units of a product, and the product of the units of each monoid. -/ @[to_additive (attr := simps) /-- The additive-monoid equivalence between (additive) units of a product, and the product of the (additive) units of each monoid. -/] def MulEquiv.piUnits : (Π i, M i)ˣ ≃* Π i, (M i)ˣ where toFun f i := ⟨f.val i, f.inv i, congr_fun f.val_inv i, congr_fun f.inv_val i⟩ invFun f := ⟨(val <| f ·), (inv <| f ·), funext (val_inv <| f ·), funext (inv_val <| f ·)⟩ map_mul' _ _ := rfl @[to_additive] lemma Pi.isUnit_iff : IsUnit x ↔ ∀ i, IsUnit (x i) := by simp_rw [isUnit_iff_exists, funext_iff, ← forall_and] exact Classical.skolem (p := fun i y ↦ x i * y = 1 ∧ y * x i = 1).symm @[to_additive] alias ⟨IsUnit.apply, _⟩ := Pi.isUnit_iff @[to_additive] lemma IsUnit.val_inv_apply (hx : IsUnit x) (i : ι) : (hx.unit⁻¹).1 i = (hx.apply i).unit⁻¹ := by rw [← Units.inv_eq_val_inv, ← MulEquiv.val_inv_piUnits_apply]; congr; ext; rfl
Preserves.lean
/- Copyright (c) 2025 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.CategoryTheory.Preadditive.Injective.Basic /-! # Preservation of injective objects We define a typeclass `Functor.PreservesInjectiveObjects`. We restate the existing result that if `F ⊣ G` is an adjunction and `F` preserves monomorphisms, then `G` preserves injective objects. We show that the converse is true if the codomain of `F` has enough injectives. -/ universe v₁ v₂ v₃ u₁ u₂ u₃ namespace CategoryTheory variable {C : Type u₁} [Category.{v₁} C] {D : Type u₂} [Category.{v₂} D] {E : Type u₃} [Category.{v₃} E] /-- A functor preserves injective objects if it maps injective objects to injective objects. -/ class Functor.PreservesInjectiveObjects (F : C ⥤ D) : Prop where injective_obj {X : C} : Injective X → Injective (F.obj X) /-- See `Functor.injective_obj_of_injective` for a variant taking `Injective X` as an explicit argument. -/ instance Functor.injective_obj (F : C ⥤ D) [F.PreservesInjectiveObjects] (X : C) [Injective X] : Injective (F.obj X) := Functor.PreservesInjectiveObjects.injective_obj inferInstance /-- See `Functor.injective_obj` for a variant taking `Injective X` as a typeclass argument. -/ theorem Functor.injective_obj_of_injective (F : C ⥤ D) [F.PreservesInjectiveObjects] {X : C} (h : Injective X) : Injective (F.obj X) := Functor.PreservesInjectiveObjects.injective_obj h instance Functor.preservesInjectiveObjects_comp (F : C ⥤ D) (G : D ⥤ E) [F.PreservesInjectiveObjects] [G.PreservesInjectiveObjects] : (F ⋙ G).PreservesInjectiveObjects where injective_obj := G.injective_obj_of_injective ∘ F.injective_obj_of_injective theorem Functor.preservesInjectiveObjects_of_adjunction_of_preservesMonomorphisms {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) [F.PreservesMonomorphisms] : G.PreservesInjectiveObjects where injective_obj h := adj.map_injective _ h instance (priority := low) Functor.preservesInjectiveObjects_of_isEquivalence {F : C ⥤ D} [IsEquivalence F] : F.PreservesInjectiveObjects := preservesInjectiveObjects_of_adjunction_of_preservesMonomorphisms F.asEquivalence.symm.toAdjunction theorem Functor.preservesMonomorphisms_of_adjunction_of_preservesInjectiveObjects [EnoughInjectives D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) [G.PreservesInjectiveObjects] : F.PreservesMonomorphisms where preserves {X Y} f _ := by suffices ∃ h, F.map f ≫ h = Injective.ι (F.obj X) from mono_of_mono_fac this.choose_spec have : Injective (G.obj (Injective.under (F.obj X))) := G.injective_obj _ exact ⟨F.map (Injective.factorThru (adj.unit.app X ≫ G.map (Injective.ι _)) f) ≫ adj.counit.app (Injective.under (F.obj X)), by simp [← Functor.map_comp_assoc]⟩ end CategoryTheory
Monoidal.lean
/- Copyright (c) 2024 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import Mathlib.Algebra.Category.CoalgCat.Basic import Mathlib.Algebra.Category.ModuleCat.Monoidal.Basic import Mathlib.CategoryTheory.Monoidal.Transport import Mathlib.RingTheory.Coalgebra.TensorProduct /-! # The monoidal category structure on `R`-coalgebras In `Mathlib/RingTheory/Coalgebra/TensorProduct.lean`, given two `R`-coalgebras `M, N`, we define a coalgebra instance on `M ⊗[R] N`, as well as the tensor product of two `CoalgHom`s as a `CoalgHom`, and the associator and left/right unitors for coalgebras as `CoalgEquiv`s. In this file, we declare a `MonoidalCategory` instance on the category of coalgebras, with data fields given by the definitions in `Mathlib/RingTheory/Coalgebra/TensorProduct.lean`, and Prop fields proved by pulling back the `MonoidalCategory` instance on the category of modules, using `Monoidal.induced`. -/ universe v u namespace CoalgCat variable (R : Type u) [CommRing R] open CategoryTheory Coalgebra open scoped TensorProduct MonoidalCategory @[simps] noncomputable instance instMonoidalCategoryStruct : MonoidalCategoryStruct.{u} (CoalgCat R) where tensorObj X Y := of R (X ⊗[R] Y) whiskerLeft X _ _ f := ofHom (f.1.lTensor X) whiskerRight f X := ofHom (f.1.rTensor X) tensorHom f g := ofHom (Coalgebra.TensorProduct.map f.1 g.1) tensorUnit := CoalgCat.of R R associator X Y Z := (Coalgebra.TensorProduct.assoc R R X Y Z).toCoalgIso leftUnitor X := (Coalgebra.TensorProduct.lid R X).toCoalgIso rightUnitor X := (Coalgebra.TensorProduct.rid R R X).toCoalgIso /-- The data needed to induce a `MonoidalCategory` structure via `CoalgCat.instMonoidalCategoryStruct` and the forgetful functor to modules. -/ @[simps] noncomputable def MonoidalCategory.inducingFunctorData : Monoidal.InducingFunctorData (forget₂ (CoalgCat R) (ModuleCat R)) where μIso _ _ := Iso.refl _ whiskerLeft_eq X Y Z f := by ext; rfl whiskerRight_eq X f := by ext; rfl tensorHom_eq f g := by ext; rfl εIso := Iso.refl _ associator_eq X Y Z := ModuleCat.hom_ext <| TensorProduct.ext <| TensorProduct.ext <| by ext; rfl leftUnitor_eq X := ModuleCat.hom_ext <| TensorProduct.ext <| by ext; rfl rightUnitor_eq X := ModuleCat.hom_ext <| TensorProduct.ext <| by ext; rfl noncomputable instance instMonoidalCategory : MonoidalCategory (CoalgCat R) := Monoidal.induced (forget₂ _ (ModuleCat R)) (MonoidalCategory.inducingFunctorData R) end CoalgCat
Skeletal.lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.CategoryTheory.Adjunction.Basic import Mathlib.CategoryTheory.Category.Preorder import Mathlib.CategoryTheory.IsomorphismClasses import Mathlib.CategoryTheory.Thin /-! # Skeleton of a category Define skeletal categories as categories in which any two isomorphic objects are equal. Construct the skeleton of an arbitrary category by taking isomorphism classes, and show it is a skeleton of the original category. In addition, construct the skeleton of a thin category as a partial ordering, and (noncomputably) show it is a skeleton of the original category. The advantage of this special case being handled separately is that lemmas and definitions about orderings can be used directly, for example for the subobject lattice. In addition, some of the commutative diagrams about the functors commute definitionally on the nose which is convenient in practice. -/ universe v₁ v₂ v₃ u₁ u₂ u₃ namespace CategoryTheory open Category variable (C : Type u₁) [Category.{v₁} C] variable (D : Type u₂) [Category.{v₂} D] variable {E : Type u₃} [Category.{v₃} E] /-- A category is skeletal if isomorphic objects are equal. -/ def Skeletal : Prop := ∀ ⦃X Y : C⦄, IsIsomorphic X Y → X = Y /-- `IsSkeletonOf C D F` says that `F : D ⥤ C` exhibits `D` as a skeletal full subcategory of `C`, in particular `F` is a (strong) equivalence and `D` is skeletal. -/ structure IsSkeletonOf (F : D ⥤ C) : Prop where /-- The category `D` has isomorphic objects equal -/ skel : Skeletal D /-- The functor `F` is an equivalence -/ eqv : F.IsEquivalence := by infer_instance attribute [local instance] isIsomorphicSetoid variable {C D} /-- If `C` is thin and skeletal, then any naturally isomorphic functors to `C` are equal. -/ theorem Functor.eq_of_iso {F₁ F₂ : D ⥤ C} [Quiver.IsThin C] (hC : Skeletal C) (hF : F₁ ≅ F₂) : F₁ = F₂ := Functor.ext (fun X => hC ⟨hF.app X⟩) fun _ _ _ => Subsingleton.elim _ _ /-- If `C` is thin and skeletal, `D ⥤ C` is skeletal. `CategoryTheory.functor_thin` shows it is thin also. -/ theorem functor_skeletal [Quiver.IsThin C] (hC : Skeletal C) : Skeletal (D ⥤ C) := fun _ _ h => h.elim (Functor.eq_of_iso hC) variable (C D) noncomputable section /-- Construct the skeleton category as the induced category on the isomorphism classes, and derive its category structure. -/ def Skeleton : Type u₁ := InducedCategory (C := Quotient (isIsomorphicSetoid C)) C Quotient.out deriving Category, [Inhabited C] → Inhabited _, (α : Sort _) → [CoeSort C α] → CoeSort _ α end /-- The functor from the skeleton of `C` to `C`. -/ @[simps!] noncomputable def fromSkeleton : Skeleton C ⥤ C := inducedFunctor _ -- The `Full, Faithful` instances should be constructed by a deriving handler. -- https://github.com/leanprover-community/mathlib4/issues/380 -- Note(kmill): `derive Functor.Full, Functor.Faithful` does not create instances -- that are in terms of `Skeleton`, but rather `InducedCategory`, which can't be applied. -- With `deriving @Functor.Full (Skeleton C)`, the instance can't be derived, for a similar reason. noncomputable instance : (fromSkeleton C).Full := by apply InducedCategory.full noncomputable instance : (fromSkeleton C).Faithful := by apply InducedCategory.faithful instance : (fromSkeleton C).EssSurj where mem_essImage X := ⟨Quotient.mk' X, Quotient.mk_out X⟩ noncomputable instance fromSkeleton.isEquivalence : (fromSkeleton C).IsEquivalence where variable {C} /-- The class of an object in the skeleton. -/ abbrev toSkeleton (X : C) : Skeleton C := ⟦X⟧ /-- The isomorphism between `⟦X⟧.out` and `X`. -/ noncomputable def preCounitIso (X : C) : (fromSkeleton C).obj (toSkeleton X) ≅ X := Nonempty.some (Quotient.mk_out X) alias fromSkeletonToSkeletonIso := preCounitIso variable (C) /-- An inverse to `fromSkeleton C` that forms an equivalence with it. -/ @[simps] noncomputable def toSkeletonFunctor : C ⥤ Skeleton C where obj := toSkeleton map {X Y} f := by apply (preCounitIso X).hom ≫ f ≫ (preCounitIso Y).inv map_id _ := by aesop map_comp _ _ := by change _ = CategoryStruct.comp (obj := C) _ _; simp /-- The equivalence between the skeleton and the category itself. -/ @[simps] noncomputable def skeletonEquivalence : Skeleton C ≌ C where functor := fromSkeleton C inverse := toSkeletonFunctor C unitIso := NatIso.ofComponents (fun X ↦ InducedCategory.isoMk (Nonempty.some <| Quotient.mk_out X.out).symm) fun _ ↦ .symm <| Iso.inv_hom_id_assoc _ _ counitIso := NatIso.ofComponents preCounitIso functor_unitIso_comp _ := Iso.inv_hom_id _ theorem skeleton_skeletal : Skeletal (Skeleton C) := by rintro X Y ⟨h⟩ have : X.out ≈ Y.out := ⟨(fromSkeleton C).mapIso h⟩ simpa using Quotient.sound this /-- The `skeleton` of `C` given by choice is a skeleton of `C`. -/ lemma skeleton_isSkeleton : IsSkeletonOf C (Skeleton C) (fromSkeleton C) where skel := skeleton_skeletal C eqv := fromSkeleton.isEquivalence C variable {C D} lemma toSkeleton_fromSkeleton_obj (X : Skeleton C) : toSkeleton ((fromSkeleton C).obj X) = X := Quotient.out_eq _ lemma toSkeleton_eq_toSkeleton_iff {X Y : C} : toSkeleton X = toSkeleton Y ↔ Nonempty (X ≅ Y) := Quotient.eq lemma congr_toSkeleton_of_iso {X Y : C} (e : X ≅ Y) : toSkeleton X = toSkeleton Y := Quotient.sound ⟨e⟩ /-- Provides a (noncomputable) isomorphism `X ≅ Y` given that `toSkeleton X = toSkeleton Y`. -/ noncomputable def Skeleton.isoOfEq {X Y : C} (h : toSkeleton X = toSkeleton Y) : X ≅ Y := Quotient.exact h |>.some lemma toSkeleton_eq_iff {X : C} {Y : Skeleton C} : toSkeleton X = Y ↔ Nonempty (X ≅ (fromSkeleton C).obj Y) := Quotient.mk_eq_iff_out namespace Functor /-- From a functor `C ⥤ D`, construct a map of skeletons `Skeleton C → Skeleton D`. -/ noncomputable def mapSkeleton (F : C ⥤ D) : Skeleton C ⥤ Skeleton D := (skeletonEquivalence C).functor ⋙ F ⋙ (skeletonEquivalence D).inverse variable (F : C ⥤ D) lemma mapSkeleton_obj_toSkeleton (X : C) : F.mapSkeleton.obj (toSkeleton X) = toSkeleton (F.obj X) := congr_toSkeleton_of_iso <| F.mapIso <| preCounitIso X instance [F.Full] : F.mapSkeleton.Full := by unfold mapSkeleton; infer_instance instance [F.Faithful] : F.mapSkeleton.Faithful := by unfold mapSkeleton; infer_instance instance [F.EssSurj] : F.mapSkeleton.EssSurj := by unfold mapSkeleton; infer_instance /-- A natural isomorphism between `X ↦ ⟦X⟧ ↦ ⟦FX⟧` and `X ↦ FX ↦ ⟦FX⟧`. On the level of categories, these are `C ⥤ Skeleton C ⥤ Skeleton D` and `C ⥤ D ⥤ Skeleton D`. So this says that the square formed by these 4 objects and 4 functors commutes. -/ noncomputable def toSkeletonFunctorCompMapSkeletonIso : toSkeletonFunctor C ⋙ F.mapSkeleton ≅ F ⋙ toSkeletonFunctor D := NatIso.ofComponents (fun X ↦ (toSkeletonFunctor D).mapIso <| F.mapIso <| preCounitIso X) (fun {X Y} f ↦ show (_ ≫ _) ≫ _ = _ ≫ _ by simp [assoc]) lemma mapSkeleton_injective [F.Full] [F.Faithful] : Function.Injective F.mapSkeleton.obj := fun _ _ h ↦ skeleton_skeletal C ⟨F.mapSkeleton.preimageIso <| eqToIso h⟩ lemma mapSkeleton_surjective [F.EssSurj] : Function.Surjective F.mapSkeleton.obj := fun Y ↦ let ⟨X, h⟩ := EssSurj.mem_essImage Y; ⟨X, skeleton_skeletal D h⟩ end Functor /-- Two categories which are categorically equivalent have skeletons with equivalent objects. -/ noncomputable def Equivalence.skeletonEquiv (e : C ≌ D) : Skeleton C ≃ Skeleton D := let f := ((skeletonEquivalence C).trans e).trans (skeletonEquivalence D).symm { toFun := f.functor.obj invFun := f.inverse.obj left_inv := fun X => skeleton_skeletal C ⟨(f.unitIso.app X).symm⟩ right_inv := fun Y => skeleton_skeletal D ⟨f.counitIso.app Y⟩ } variable (C D) /-- Construct the skeleton category by taking the quotient of objects. This construction gives a preorder with nice definitional properties, but is only really appropriate for thin categories. If your original category is not thin, you probably want to be using `skeleton` instead of this. -/ def ThinSkeleton : Type u₁ := Quotient (isIsomorphicSetoid C) instance inhabitedThinSkeleton [Inhabited C] : Inhabited (ThinSkeleton C) := ⟨@Quotient.mk' C (isIsomorphicSetoid C) default⟩ instance ThinSkeleton.preorder : Preorder (ThinSkeleton C) where le := @Quotient.lift₂ C C _ (isIsomorphicSetoid C) (isIsomorphicSetoid C) (fun X Y => Nonempty (X ⟶ Y)) (by rintro _ _ _ _ ⟨i₁⟩ ⟨i₂⟩ exact propext ⟨Nonempty.map fun f => i₁.inv ≫ f ≫ i₂.hom, Nonempty.map fun f => i₁.hom ≫ f ≫ i₂.inv⟩) le_refl := by refine Quotient.ind fun a => ?_ exact ⟨𝟙 _⟩ le_trans a b c := Quotient.inductionOn₃ a b c fun _ _ _ => Nonempty.map2 (· ≫ ·) /-- The functor from a category to its thin skeleton. -/ @[simps] def toThinSkeleton : C ⥤ ThinSkeleton C where obj := @Quotient.mk' C _ map f := homOfLE (Nonempty.intro f) /-! The constructions here are intended to be used when the category `C` is thin, even though some of the statements can be shown without this assumption. -/ namespace ThinSkeleton /-- The thin skeleton is thin. -/ instance thin : Quiver.IsThin (ThinSkeleton C) := fun _ _ => ⟨by rintro ⟨⟨f₁⟩⟩ ⟨⟨_⟩⟩ rfl⟩ variable {C} {D} /-- A functor `C ⥤ D` computably lowers to a functor `ThinSkeleton C ⥤ ThinSkeleton D`. -/ @[simps] def map (F : C ⥤ D) : ThinSkeleton C ⥤ ThinSkeleton D where obj := Quotient.map F.obj fun _ _ ⟨hX⟩ => ⟨F.mapIso hX⟩ map {X} {Y} := Quotient.recOnSubsingleton₂ X Y fun _ _ k => homOfLE (k.le.elim fun t => ⟨F.map t⟩) theorem comp_toThinSkeleton (F : C ⥤ D) : F ⋙ toThinSkeleton D = toThinSkeleton C ⋙ map F := rfl /-- Given a natural transformation `F₁ ⟶ F₂`, induce a natural transformation `map F₁ ⟶ map F₂`. -/ def mapNatTrans {F₁ F₂ : C ⥤ D} (k : F₁ ⟶ F₂) : map F₁ ⟶ map F₂ where app X := Quotient.recOnSubsingleton X fun x => ⟨⟨⟨k.app x⟩⟩⟩ /- Porting note: `map₂ObjMap`, `map₂Functor`, and `map₂NatTrans` were all extracted from the original `map₂` proof. Lean needed an extensive amount explicit type annotations to figure things out. This also translated into repeated deterministic timeouts. The extracted defs allow for explicit motives for the multiple descents to the quotients. It would be better to prove that `ThinSkeleton (C × D) ≌ ThinSkeleton C × ThinSkeleton D` which is more immediate from comparing the preorders. Then one could get `map₂` by currying. -/ /-- Given a bifunctor, we descend to a function on objects of `ThinSkeleton` -/ def map₂ObjMap (F : C ⥤ D ⥤ E) : ThinSkeleton C → ThinSkeleton D → ThinSkeleton E := fun x y => @Quotient.map₂ C D (isIsomorphicSetoid C) (isIsomorphicSetoid D) E (isIsomorphicSetoid E) (fun X Y => (F.obj X).obj Y) (fun X₁ _ ⟨hX⟩ _ Y₂ ⟨hY⟩ => ⟨(F.obj X₁).mapIso hY ≪≫ (F.mapIso hX).app Y₂⟩) x y /-- For each `x : ThinSkeleton C`, we promote `map₂ObjMap F x` to a functor -/ def map₂Functor (F : C ⥤ D ⥤ E) : ThinSkeleton C → ThinSkeleton D ⥤ ThinSkeleton E := fun x => { obj := fun y => map₂ObjMap F x y map := fun {y₁} {y₂} => @Quotient.recOnSubsingleton C (isIsomorphicSetoid C) (fun x => (y₁ ⟶ y₂) → (map₂ObjMap F x y₁ ⟶ map₂ObjMap F x y₂)) _ x fun X => Quotient.recOnSubsingleton₂ y₁ y₂ fun _ _ hY => homOfLE (hY.le.elim fun g => ⟨(F.obj X).map g⟩) } /-- This provides natural transformations `map₂Functor F x₁ ⟶ map₂Functor F x₂` given `x₁ ⟶ x₂` -/ def map₂NatTrans (F : C ⥤ D ⥤ E) : {x₁ x₂ : ThinSkeleton C} → (x₁ ⟶ x₂) → (map₂Functor F x₁ ⟶ map₂Functor F x₂) := fun {x₁} {x₂} => @Quotient.recOnSubsingleton₂ C C (isIsomorphicSetoid C) (isIsomorphicSetoid C) (fun x x' : ThinSkeleton C => (x ⟶ x') → (map₂Functor F x ⟶ map₂Functor F x')) _ x₁ x₂ (fun X₁ X₂ f => { app := fun y => Quotient.recOnSubsingleton y fun Y => homOfLE (f.le.elim fun f' => ⟨(F.map f').app Y⟩) }) -- TODO: state the lemmas about what happens when you compose with `toThinSkeleton` /-- A functor `C ⥤ D ⥤ E` computably lowers to a functor `ThinSkeleton C ⥤ ThinSkeleton D ⥤ ThinSkeleton E` -/ @[simps] def map₂ (F : C ⥤ D ⥤ E) : ThinSkeleton C ⥤ ThinSkeleton D ⥤ ThinSkeleton E where obj := map₂Functor F map := map₂NatTrans F variable (C) section variable [Quiver.IsThin C] instance toThinSkeleton_faithful : (toThinSkeleton C).Faithful where /-- Use `Quotient.out` to create a functor out of the thin skeleton. -/ @[simps] noncomputable def fromThinSkeleton : ThinSkeleton C ⥤ C where obj := Quotient.out map {x} {y} := Quotient.recOnSubsingleton₂ x y fun X Y f => (Nonempty.some (Quotient.mk_out X)).hom ≫ f.le.some ≫ (Nonempty.some (Quotient.mk_out Y)).inv /-- The equivalence between the thin skeleton and the category itself. -/ noncomputable def equivalence : ThinSkeleton C ≌ C where functor := fromThinSkeleton C inverse := toThinSkeleton C counitIso := NatIso.ofComponents fun X => Nonempty.some (Quotient.mk_out X) unitIso := NatIso.ofComponents fun x => Quotient.recOnSubsingleton x fun X => eqToIso (Quotient.sound ⟨(Nonempty.some (Quotient.mk_out X)).symm⟩) noncomputable instance fromThinSkeleton_isEquivalence : (fromThinSkeleton C).IsEquivalence := (equivalence C).isEquivalence_functor variable {C} theorem equiv_of_both_ways {X Y : C} (f : X ⟶ Y) (g : Y ⟶ X) : X ≈ Y := ⟨iso_of_both_ways f g⟩ instance thinSkeletonPartialOrder : PartialOrder (ThinSkeleton C) := { CategoryTheory.ThinSkeleton.preorder C with le_antisymm := Quotient.ind₂ (by rintro _ _ ⟨f⟩ ⟨g⟩ apply Quotient.sound (equiv_of_both_ways f g)) } theorem skeletal : Skeletal (ThinSkeleton C) := fun X Y => Quotient.inductionOn₂ X Y fun _ _ h => h.elim fun i => i.1.le.antisymm i.2.le theorem map_comp_eq (F : E ⥤ D) (G : D ⥤ C) : map (F ⋙ G) = map F ⋙ map G := Functor.eq_of_iso skeletal <| NatIso.ofComponents fun X => Quotient.recOnSubsingleton X fun _ => Iso.refl _ theorem map_id_eq : map (𝟭 C) = 𝟭 (ThinSkeleton C) := Functor.eq_of_iso skeletal <| NatIso.ofComponents fun X => Quotient.recOnSubsingleton X fun _ => Iso.refl _ theorem map_iso_eq {F₁ F₂ : D ⥤ C} (h : F₁ ≅ F₂) : map F₁ = map F₂ := Functor.eq_of_iso skeletal { hom := mapNatTrans h.hom inv := mapNatTrans h.inv } /-- `fromThinSkeleton C` exhibits the thin skeleton as a skeleton. -/ lemma thinSkeleton_isSkeleton : IsSkeletonOf C (ThinSkeleton C) (fromThinSkeleton C) where skel := skeletal instance isSkeletonOfInhabited : Inhabited (IsSkeletonOf C (ThinSkeleton C) (fromThinSkeleton C)) := ⟨thinSkeleton_isSkeleton⟩ end variable {C} /-- An adjunction between thin categories gives an adjunction between their thin skeletons. -/ def lowerAdjunction (R : D ⥤ C) (L : C ⥤ D) (h : L ⊣ R) : ThinSkeleton.map L ⊣ ThinSkeleton.map R where unit := { app := fun X => by letI := isIsomorphicSetoid C exact Quotient.recOnSubsingleton X fun x => homOfLE ⟨h.unit.app x⟩ } -- TODO: make quotient.rec_on_subsingleton' so the letI isn't needed counit := { app := fun X => by letI := isIsomorphicSetoid D exact Quotient.recOnSubsingleton X fun x => homOfLE ⟨h.counit.app x⟩ } end ThinSkeleton open ThinSkeleton section variable {C} {α : Type*} [PartialOrder α] /-- When `e : C ≌ α` is a categorical equivalence from a thin category `C` to some partial order `α`, the `ThinSkeleton C` is order isomorphic to `α`. -/ noncomputable def Equivalence.thinSkeletonOrderIso [Quiver.IsThin C] (e : C ≌ α) : ThinSkeleton C ≃o α := ((ThinSkeleton.equivalence C).trans e).toOrderIso end end CategoryTheory
SmoothSection.lean
/- Copyright (c) 2023 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Floris van Doorn, Michael Rothgang -/ import Mathlib.Geometry.Manifold.Algebra.LieGroup import Mathlib.Geometry.Manifold.MFDeriv.Basic import Mathlib.Topology.ContinuousMap.Basic import Mathlib.Geometry.Manifold.VectorBundle.Basic /-! # `C^n` sections In this file we define the type `ContMDiffSection` of `n` times continuously differentiable sections of a vector bundle over a manifold `M` and prove that it's a module over the base field. In passing, we prove that binary and finite sums, differences and scalar products of `C^n` sections are `C^n`. -/ open Bundle Filter Function open scoped Bundle Manifold ContDiff variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) {M : Type*} [TopologicalSpace M] [ChartedSpace H M] variable (F : Type*) [NormedAddCommGroup F] [NormedSpace 𝕜 F] -- `F` model fiber (n : WithTop ℕ∞) (V : M → Type*) [TopologicalSpace (TotalSpace F V)] -- `V` vector bundle [∀ x : M, TopologicalSpace (V x)] [FiberBundle F V] -- Binary and finite sums, negative, differences and scalar products of smooth sections are smooth section operations -- Let V be a vector bundle variable [∀ x, AddCommGroup (V x)] [∀ x, Module 𝕜 (V x)] [VectorBundle 𝕜 F V] variable {I F n V} variable {f : M → 𝕜} {a : 𝕜} {s t : Π x : M, V x} {u : Set M} {x₀ : M} lemma ContMDiffWithinAt.add_section (hs : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u x₀) (ht : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t x)) u x₀) : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x ((s + t) x)) u x₀ := by rw [contMDiffWithinAt_section] at hs ht ⊢ set e := trivializationAt F V x₀ refine (hs.add ht).congr_of_eventuallyEq ?_ ?_ · apply eventually_of_mem (U := e.baseSet) · exact mem_nhdsWithin_of_mem_nhds <| (e.open_baseSet.mem_nhds <| mem_baseSet_trivializationAt F V x₀) · intro x hx apply (e.linear 𝕜 hx).1 · apply (e.linear 𝕜 (FiberBundle.mem_baseSet_trivializationAt' x₀)).1 lemma ContMDiffAt.add_section (hs : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) x₀) (ht : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t x)) x₀) : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x ((s + t) x)) x₀ := by rw [← contMDiffWithinAt_univ] at hs ⊢ exact hs.add_section ht lemma ContMDiffOn.add_section (hs : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u) (ht : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t x)) u) : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x ((s + t) x)) u := fun x₀ hx₀ ↦ (hs x₀ hx₀).add_section (ht x₀ hx₀) lemma ContMDiff.add_section (hs : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x))) (ht : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t x))) : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x ((s + t) x)) := fun x₀ ↦ (hs x₀).add_section (ht x₀) lemma ContMDiffWithinAt.neg_section (hs : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u x₀) : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (- s x)) u x₀ := by rw [contMDiffWithinAt_section] at hs ⊢ set e := trivializationAt F V x₀ refine hs.neg.congr_of_eventuallyEq ?_ ?_ · apply eventually_of_mem (U := e.baseSet) · exact mem_nhdsWithin_of_mem_nhds <| (e.open_baseSet.mem_nhds <| mem_baseSet_trivializationAt F V x₀) · intro x hx apply (e.linear 𝕜 hx).map_neg · apply (e.linear 𝕜 (FiberBundle.mem_baseSet_trivializationAt' x₀)).map_neg lemma ContMDiffAt.neg_section (hs : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) x₀) : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (- s x)) x₀ := by rw [← contMDiffWithinAt_univ] at hs ⊢ exact hs.neg_section lemma ContMDiffOn.neg_section (hs : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u) : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (-s x)) u := fun x₀ hx₀ ↦ (hs x₀ hx₀).neg_section lemma ContMDiff.neg_section (hs : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x))) : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (-s x)) := fun x₀ ↦ (hs x₀).neg_section lemma ContMDiffWithinAt.sub_section (hs : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u x₀) (ht : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t x)) u x₀) : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x ((s - t) x)) u x₀ := by rw [sub_eq_add_neg] exact hs.add_section ht.neg_section lemma ContMDiffAt.sub_section (hs : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) x₀) (ht : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t x)) x₀) : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x ((s - t) x)) x₀ := by rw [sub_eq_add_neg] apply hs.add_section ht.neg_section lemma ContMDiffOn.sub_section (hs : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u) (ht : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t x)) u) : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x ((s - t) x)) u := fun x₀ hx₀ ↦ (hs x₀ hx₀).sub_section (ht x₀ hx₀) lemma ContMDiff.sub_section (hs : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x))) (ht : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t x))) : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x ((s - t) x)) := fun x₀ ↦ (hs x₀).sub_section (ht x₀) lemma ContMDiffWithinAt.smul_section (hf : ContMDiffWithinAt I 𝓘(𝕜) n f u x₀) (hs : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u x₀) : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (f x • s x)) u x₀ := by rw [contMDiffWithinAt_section] at hs ⊢ set e := trivializationAt F V x₀ refine (hf.smul hs).congr_of_eventuallyEq ?_ ?_ · apply eventually_of_mem (U := e.baseSet) · exact mem_nhdsWithin_of_mem_nhds <| (e.open_baseSet.mem_nhds <| mem_baseSet_trivializationAt F V x₀) · intro x hx apply (e.linear 𝕜 hx).2 · apply (e.linear 𝕜 (FiberBundle.mem_baseSet_trivializationAt' x₀)).2 lemma ContMDiffAt.smul_section (hf : ContMDiffAt I 𝓘(𝕜) n f x₀) (hs : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) x₀) : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (f x • s x)) x₀ := by rw [← contMDiffWithinAt_univ] at hs ⊢ exact .smul_section hf hs lemma ContMDiffOn.smul_section (hf : ContMDiffOn I 𝓘(𝕜) n f u) (hs : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u) : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (f x • s x)) u := fun x₀ hx₀ ↦ (hf x₀ hx₀).smul_section (hs x₀ hx₀) lemma ContMDiff.smul_section (hf : ContMDiff I 𝓘(𝕜) n f) (hs : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x))) : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (f x • s x)) := fun x₀ ↦ (hf x₀).smul_section (hs x₀) lemma ContMDiffWithinAt.const_smul_section (hs : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u x₀) : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (a • s x)) u x₀ := contMDiffWithinAt_const.smul_section hs lemma ContMDiffAt.const_smul_section (hs : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) x₀) : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (a • s x)) x₀ := contMDiffAt_const.smul_section hs lemma ContMDiffOn.const_smul_section (hs : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u) : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (a • s x)) u := contMDiffOn_const.smul_section hs lemma ContMDiff.const_smul_section (hs : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x))) : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (a • s x)) := fun x₀ ↦ (hs x₀).const_smul_section variable {ι : Type*} {t : ι → (x : M) → V x} lemma ContMDiffWithinAt.sum_section {s : Finset ι} (hs : ∀ i ∈ s, ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x)) u x₀) : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑ i ∈ s, (t i x))) u x₀ := by classical induction s using Finset.induction_on with | empty => simpa only [Finset.sum_empty] using contMDiffWithinAt_zeroSection .. | insert i s hi h => simp only [Finset.sum_insert hi] apply (hs _ (s.mem_insert_self i)).add_section exact h fun i a ↦ hs _ (s.mem_insert_of_mem a) lemma ContMDiffAt.sum_section {s : Finset ι} {x₀ : M} (hs : ∀ i ∈ s, ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x)) x₀) : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑ i ∈ s, (t i x))) x₀ := by simp_rw [← contMDiffWithinAt_univ] at hs ⊢ exact .sum_section hs lemma ContMDiffOn.sum_section {s : Finset ι} (hs : ∀ i ∈ s, ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x)) u) : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑ i ∈ s, (t i x))) u := fun x₀ hx₀ ↦ .sum_section fun i hi ↦ hs i hi x₀ hx₀ lemma ContMDiff.sum_section {s : Finset ι} (hs : ∀ i ∈ s, ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x))) : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑ i ∈ s, (t i x))) := fun x₀ ↦ .sum_section fun i hi ↦ (hs i hi) x₀ /-- The scalar product `ψ • s` of a `C^k` function `ψ : M → 𝕜` and a section `s` of a vector bundle `V → M` is `C^k` once `s` is `C^k` on an open set containing `tsupport ψ` . This is a vector bundle analogue of `contMDiff_of_tsupport`. -/ lemma ContMDiffOn.smul_section_of_tsupport {s : Π (x : M), V x} {ψ : M → 𝕜} (hψ : ContMDiffOn I 𝓘(𝕜) n ψ u) (ht : IsOpen u) (ht' : tsupport ψ ⊆ u) (hs : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (s x)) u) : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (ψ x • s x)) := by apply contMDiff_of_contMDiffOn_union_of_isOpen (hψ.smul_section hs) ?_ ?_ ht (isOpen_compl_iff.mpr <| isClosed_tsupport ψ) · apply ((contMDiff_zeroSection _ _).contMDiffOn (s := (tsupport ψ)ᶜ)).congr intro y hy simp [image_eq_zero_of_notMem_tsupport hy, zeroSection] · exact Set.compl_subset_iff_union.mp <| Set.compl_subset_compl.mpr ht' /-- The sum of a locally finite collection of sections is `C^k` iff each section is. Version at a point within a set. -/ lemma ContMDiffWithinAt.sum_section_of_locallyFinite (ht : LocallyFinite fun i ↦ {x : M | t i x ≠ 0}) (ht' : ∀ i, ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x)) u x₀) : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑' i, (t i x))) u x₀ := by obtain ⟨u', hu', hfin⟩ := ht x₀ -- All sections `t i` but a finite set `s` vanish near `x₀`: choose a neighbourhood `u` of `x₀` -- and a finite set `s` of sections which don't vanish. let s := {i | ((fun i ↦ {x | t i x ≠ 0}) i ∩ u').Nonempty} have := hfin.fintype have : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑ i ∈ s, (t i x))) (u ∩ u') x₀ := ContMDiffWithinAt.sum_section fun i hi ↦ ((ht' i).mono Set.inter_subset_left) apply (contMDiffWithinAt_inter hu').mp apply this.congr fun y hy ↦ ?_ · rw [TotalSpace.mk_inj, tsum_eq_sum'] refine support_subset_iff'.mpr fun i hi ↦ ?_ by_contra! h have : i ∈ s.toFinset := by refine Set.mem_toFinset.mpr ?_ simp only [s, ne_eq, Set.mem_setOf_eq] use x₀ simpa using ⟨h, mem_of_mem_nhds hu'⟩ exact hi this rw [TotalSpace.mk_inj, tsum_eq_sum'] refine support_subset_iff'.mpr fun i hi ↦ ?_ by_contra! h have : i ∈ s.toFinset := by refine Set.mem_toFinset.mpr ?_ simp only [s, ne_eq, Set.mem_setOf_eq] use y simpa using ⟨h, Set.mem_of_mem_inter_right hy⟩ exact hi this /-- The sum of a locally finite collection of sections is `C^k` at `x` iff each section is. -/ lemma ContMDiffAt.sum_section_of_locallyFinite (ht : LocallyFinite fun i ↦ {x : M | t i x ≠ 0}) (ht' : ∀ i, ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x)) x₀) : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑' i, (t i x))) x₀ := by simp_rw [← contMDiffWithinAt_univ] at ht' ⊢ exact .sum_section_of_locallyFinite ht ht' /-- The sum of a locally finite collection of sections is `C^k` on a set `u` iff each section is. -/ lemma ContMDiffOn.sum_section_of_locallyFinite (ht : LocallyFinite fun i ↦ {x : M | t i x ≠ 0}) (ht' : ∀ i, ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x)) u) : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑' i, (t i x))) u := fun x hx ↦ .sum_section_of_locallyFinite ht (ht' · x hx) /-- The sum of a locally finite collection of sections is `C^k` iff each section is. -/ lemma ContMDiff.sum_section_of_locallyFinite (ht : LocallyFinite fun i ↦ {x : M | t i x ≠ 0}) (ht' : ∀ i, ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x))) : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑' i, (t i x))) := fun x ↦ .sum_section_of_locallyFinite ht fun i ↦ ht' i x -- Future: the next four lemmas can presumably be generalised, but some hypotheses on the supports -- of the sections `t i` are necessary. lemma ContMDiffWithinAt.finsum_section_of_locallyFinite (ht : LocallyFinite fun i ↦ {x : M | t i x ≠ 0}) (ht' : ∀ i, ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x)) u x₀) : ContMDiffWithinAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑ᶠ i, t i x)) u x₀ := by apply (ContMDiffWithinAt.sum_section_of_locallyFinite ht ht').congr' (t := Set.univ) (fun y hy ↦ ?_) (by grind) trivial rw [← tsum_eq_finsum] choose U hu hfin using ht y have : {x | t x y ≠ 0} ⊆ {i | ((fun i ↦ {x | t i x ≠ 0}) i ∩ U).Nonempty} := by intro x hx rw [Set.mem_setOf] at hx ⊢ use y simpa using ⟨hx, mem_of_mem_nhds hu⟩ exact Set.Finite.subset hfin this lemma ContMDiffAt.finsum_section_of_locallyFinite (ht : LocallyFinite fun i ↦ {x : M | t i x ≠ 0}) (ht' : ∀ i, ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x)) x₀) : ContMDiffAt I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑ᶠ i, t i x)) x₀ := by simp_rw [← contMDiffWithinAt_univ] at ht' ⊢ exact ContMDiffWithinAt.finsum_section_of_locallyFinite ht ht' lemma ContMDiffOn.finsum_section_of_locallyFinite (ht : LocallyFinite fun i ↦ {x : M | t i x ≠ 0}) (ht' : ∀ i, ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x)) u) : ContMDiffOn I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑ᶠ i, t i x)) u := fun x hx ↦ ContMDiffWithinAt.finsum_section_of_locallyFinite ht fun i ↦ ht' i x hx lemma ContMDiff.finsum_section_of_locallyFinite (ht : LocallyFinite fun i ↦ {x : M | t i x ≠ 0}) (ht' : ∀ i, ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (t i x))) : ContMDiff I (I.prod 𝓘(𝕜, F)) n (fun x ↦ TotalSpace.mk' F x (∑ᶠ i, t i x)) := fun x ↦ ContMDiffAt.finsum_section_of_locallyFinite ht fun i ↦ ht' i x end operations /-- Bundled `n` times continuously differentiable sections of a vector bundle. Denoted as `Cₛ^n⟮I; F, V⟯` within the `Manifold` namespace. -/ structure ContMDiffSection where /-- the underlying function of this section -/ protected toFun : ∀ x, V x /-- proof that this section is `C^n` -/ protected contMDiff_toFun : ContMDiff I (I.prod 𝓘(𝕜, F)) n fun x ↦ TotalSpace.mk' F x (toFun x) @[inherit_doc] scoped[Manifold] notation "Cₛ^" n "⟮" I "; " F ", " V "⟯" => ContMDiffSection I F n V namespace ContMDiffSection variable {I} {n} {F} {V} instance : DFunLike Cₛ^n⟮I; F, V⟯ M V where coe := ContMDiffSection.toFun coe_injective' := by rintro ⟨⟩ ⟨⟩ h; congr variable {s t : Cₛ^n⟮I; F, V⟯} @[simp] theorem coeFn_mk (s : ∀ x, V x) (hs : ContMDiff I (I.prod 𝓘(𝕜, F)) n fun x => TotalSpace.mk x (s x)) : (mk s hs : ∀ x, V x) = s := rfl protected theorem contMDiff (s : Cₛ^n⟮I; F, V⟯) : ContMDiff I (I.prod 𝓘(𝕜, F)) n fun x => TotalSpace.mk' F x (s x : V x) := s.contMDiff_toFun theorem coe_inj ⦃s t : Cₛ^n⟮I; F, V⟯⦄ (h : (s : ∀ x, V x) = t) : s = t := DFunLike.ext' h theorem coe_injective : Injective ((↑) : Cₛ^n⟮I; F, V⟯ → ∀ x, V x) := coe_inj @[ext] theorem ext (h : ∀ x, s x = t x) : s = t := DFunLike.ext _ _ h section variable [∀ x, AddCommGroup (V x)] [∀ x, Module 𝕜 (V x)] [VectorBundle 𝕜 F V] instance instAdd : Add Cₛ^n⟮I; F, V⟯ := ⟨fun s t ↦ ⟨s + t, s.contMDiff.add_section t.contMDiff⟩⟩ @[simp] theorem coe_add (s t : Cₛ^n⟮I; F, V⟯) : ⇑(s + t) = ⇑s + t := rfl instance instSub : Sub Cₛ^n⟮I; F, V⟯ := ⟨fun s t ↦ ⟨s - t, s.contMDiff.sub_section t.contMDiff⟩⟩ @[simp] theorem coe_sub (s t : Cₛ^n⟮I; F, V⟯) : ⇑(s - t) = s - t := rfl instance instZero : Zero Cₛ^n⟮I; F, V⟯ := ⟨⟨fun _ => 0, (contMDiff_zeroSection 𝕜 V).of_le le_top⟩⟩ instance inhabited : Inhabited Cₛ^n⟮I; F, V⟯ := ⟨0⟩ @[simp] theorem coe_zero : ⇑(0 : Cₛ^n⟮I; F, V⟯) = 0 := rfl instance instNeg : Neg Cₛ^n⟮I; F, V⟯ := ⟨fun s ↦ ⟨-s, s.contMDiff.neg_section⟩⟩ @[simp] theorem coe_neg (s : Cₛ^n⟮I; F, V⟯) : ⇑(-s : Cₛ^n⟮I; F, V⟯) = -s := rfl instance instNSMul : SMul ℕ Cₛ^n⟮I; F, V⟯ := ⟨nsmulRec⟩ @[simp] theorem coe_nsmul (s : Cₛ^n⟮I; F, V⟯) (k : ℕ) : ⇑(k • s : Cₛ^n⟮I; F, V⟯) = k • ⇑s := by induction k with | zero => simp_rw [zero_smul]; rfl | succ k ih => simp_rw [succ_nsmul, ← ih]; rfl instance instZSMul : SMul ℤ Cₛ^n⟮I; F, V⟯ := ⟨zsmulRec⟩ @[simp] theorem coe_zsmul (s : Cₛ^n⟮I; F, V⟯) (z : ℤ) : ⇑(z • s : Cₛ^n⟮I; F, V⟯) = z • ⇑s := by rcases z with n | n · refine (coe_nsmul s n).trans ?_ simp only [Int.ofNat_eq_coe, natCast_zsmul] · refine (congr_arg Neg.neg (coe_nsmul s (n + 1))).trans ?_ simp only [negSucc_zsmul] instance instAddCommGroup : AddCommGroup Cₛ^n⟮I; F, V⟯ := coe_injective.addCommGroup _ coe_zero coe_add coe_neg coe_sub coe_nsmul coe_zsmul instance instSMul : SMul 𝕜 Cₛ^n⟮I; F, V⟯ := ⟨fun c s ↦ ⟨c • ⇑s, s.contMDiff.const_smul_section⟩⟩ @[simp] theorem coe_smul (r : 𝕜) (s : Cₛ^n⟮I; F, V⟯) : ⇑(r • s : Cₛ^n⟮I; F, V⟯) = r • ⇑s := rfl variable (I F V n) in /-- The additive morphism from `C^n` sections to dependent maps. -/ def coeAddHom : Cₛ^n⟮I; F, V⟯ →+ ∀ x, V x where toFun := (↑) map_zero' := coe_zero map_add' := coe_add @[simp] theorem coeAddHom_apply (s : Cₛ^n⟮I; F, V⟯) : coeAddHom I F n V s = s := rfl instance instModule : Module 𝕜 Cₛ^n⟮I; F, V⟯ := coe_injective.module 𝕜 (coeAddHom I F n V) coe_smul end protected theorem mdifferentiable' (s : Cₛ^n⟮I; F, V⟯) (hn : 1 ≤ n) : MDifferentiable I (I.prod 𝓘(𝕜, F)) fun x => TotalSpace.mk' F x (s x : V x) := s.contMDiff.mdifferentiable hn protected theorem mdifferentiable (s : Cₛ^∞⟮I; F, V⟯) : MDifferentiable I (I.prod 𝓘(𝕜, F)) fun x => TotalSpace.mk' F x (s x : V x) := s.contMDiff.mdifferentiable (mod_cast le_top) protected theorem mdifferentiableAt (s : Cₛ^∞⟮I; F, V⟯) {x} : MDifferentiableAt I (I.prod 𝓘(𝕜, F)) (fun x => TotalSpace.mk' F x (s x : V x)) x := s.mdifferentiable x end ContMDiffSection
Norm.lean
/- Copyright (c) 2024 Etienne Marion. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Etienne Marion -/ import Mathlib.Analysis.Calculus.Deriv.Abs import Mathlib.Analysis.Calculus.LineDeriv.Basic /-! # Differentiability of the norm in a real normed vector space This file provides basic results about the differentiability of the norm in a real vector space. Most are of the following kind: if the norm has some differentiability property (`DifferentiableAt`, `ContDiffAt`, `HasStrictFDerivAt`, `HasFDerivAt`) at `x`, then so it has at `t • x` when `t ≠ 0`. ## Main statements * `ContDiffAt.contDiffAt_norm_smul`: If the norm is continuously differentiable up to order `n` at `x`, then so it is at `t • x` when `t ≠ 0`. * `differentiableAt_norm_smul`: If `t ≠ 0`, the norm is differentiable at `x` if and only if it is at `t • x`. * `HasFDerivAt.hasFDerivAt_norm_smul`: If the norm has a Fréchet derivative `f` at `x` and `t ≠ 0`, then it has `(SignType t) • f` as a Fréchet derivative at `t · x`. * `fderiv_norm_smul` : `fderiv ℝ (‖·‖) (t • x) = (SignType.sign t : ℝ) • (fderiv ℝ (‖·‖) x)`, this holds without any differentiability assumptions. * `DifferentiableAt.fderiv_norm_self`: if the norm is differentiable at `x`, then `fderiv ℝ (‖·‖) x x = ‖x‖`. * `norm_fderiv_norm`: if the norm is differentiable at `x` then the operator norm of its derivative is `1` (on a non trivial space). ## Tags differentiability, norm -/ open ContinuousLinearMap Filter NNReal Real Set variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] variable {n : WithTop ℕ∞} {f : E →L[ℝ] ℝ} {x : E} {t : ℝ} variable (E) in theorem not_differentiableAt_norm_zero [Nontrivial E] : ¬DifferentiableAt ℝ (‖·‖) (0 : E) := by obtain ⟨x, hx⟩ := NormedSpace.exists_lt_norm ℝ E 0 intro h have : DifferentiableAt ℝ (fun t : ℝ ↦ ‖t • x‖) 0 := DifferentiableAt.comp _ (by simpa) (by simp) have : DifferentiableAt ℝ (|·|) (0 : ℝ) := by simp_rw [norm_smul, norm_eq_abs] at this have aux : abs = fun t ↦ (1 / ‖x‖) * (|t| * ‖x‖) := by field_simp rw [aux] exact this.const_mul _ exact not_differentiableAt_abs_zero this theorem ContDiffAt.contDiffAt_norm_smul (ht : t ≠ 0) (h : ContDiffAt ℝ n (‖·‖) x) : ContDiffAt ℝ n (‖·‖) (t • x) := by have h1 : ContDiffAt ℝ n (fun y ↦ t⁻¹ • y) (t • x) := (contDiff_const_smul t⁻¹).contDiffAt have h2 : ContDiffAt ℝ n (fun y ↦ |t| * ‖y‖) x := h.const_smul |t| conv at h2 => enter [4]; rw [← one_smul ℝ x, ← inv_mul_cancel₀ ht, mul_smul] convert h2.comp (t • x) h1 using 1 ext y simp only [Function.comp_apply] rw [norm_smul, ← mul_assoc, norm_eq_abs, ← abs_mul, mul_inv_cancel₀ ht, abs_one, one_mul] theorem contDiffAt_norm_smul_iff (ht : t ≠ 0) : ContDiffAt ℝ n (‖·‖) x ↔ ContDiffAt ℝ n (‖·‖) (t • x) where mp h := h.contDiffAt_norm_smul ht mpr hd := by convert hd.contDiffAt_norm_smul (inv_ne_zero ht) rw [smul_smul, inv_mul_cancel₀ ht, one_smul] theorem ContDiffAt.contDiffAt_norm_of_smul (h : ContDiffAt ℝ n (‖·‖) (t • x)) : ContDiffAt ℝ n (‖·‖) x := by rcases eq_bot_or_bot_lt n with rfl | hn · apply contDiffAt_zero.2 exact ⟨univ, univ_mem, continuous_norm.continuousOn⟩ replace hn : 1 ≤ n := ENat.add_one_natCast_le_withTop_of_lt hn obtain rfl | ht := eq_or_ne t 0 · by_cases hE : Nontrivial E · rw [zero_smul] at h exact (mt (ContDiffAt.differentiableAt · (mod_cast hn))) (not_differentiableAt_norm_zero E) h |>.elim · rw [not_nontrivial_iff_subsingleton] at hE rw [eq_const_of_subsingleton (‖·‖) 0] exact contDiffAt_const · exact contDiffAt_norm_smul_iff ht |>.2 h theorem HasStrictFDerivAt.hasStrictFDerivAt_norm_smul (ht : t ≠ 0) (h : HasStrictFDerivAt (‖·‖) f x) : HasStrictFDerivAt (‖·‖) ((SignType.sign t : ℝ) • f) (t • x) := by have h1 : HasStrictFDerivAt (fun y ↦ t⁻¹ • y) (t⁻¹ • ContinuousLinearMap.id ℝ E) (t • x) := hasStrictFDerivAt_id (t • x) |>.const_smul t⁻¹ have h2 : HasStrictFDerivAt (fun y ↦ |t| * ‖y‖) (|t| • f) x := h.const_smul |t| conv at h2 => enter [3]; rw [← one_smul ℝ x, ← inv_mul_cancel₀ ht, mul_smul] convert h2.comp (t • x) h1 with y · rw [norm_smul, ← mul_assoc, norm_eq_abs, ← abs_mul, mul_inv_cancel₀ ht, abs_one, one_mul] ext y simp only [coe_smul', Pi.smul_apply, smul_eq_mul, comp_smulₛₗ, map_inv₀, RingHom.id_apply, comp_id] rw [eq_inv_mul_iff_mul_eq₀ ht, ← mul_assoc, self_mul_sign] theorem HasStrictFDerivAt.hasStrictDerivAt_norm_smul_neg (ht : t < 0) (h : HasStrictFDerivAt (‖·‖) f x) : HasStrictFDerivAt (‖·‖) (-f) (t • x) := by simpa [ht] using h.hasStrictFDerivAt_norm_smul ht.ne theorem HasStrictFDerivAt.hasStrictDerivAt_norm_smul_pos (ht : 0 < t) (h : HasStrictFDerivAt (‖·‖) f x) : HasStrictFDerivAt (‖·‖) f (t • x) := by simpa [ht] using h.hasStrictFDerivAt_norm_smul ht.ne' theorem HasFDerivAt.hasFDerivAt_norm_smul (ht : t ≠ 0) (h : HasFDerivAt (‖·‖) f x) : HasFDerivAt (‖·‖) ((SignType.sign t : ℝ) • f) (t • x) := by have h1 : HasFDerivAt (fun y ↦ t⁻¹ • y) (t⁻¹ • ContinuousLinearMap.id ℝ E) (t • x) := hasFDerivAt_id (t • x) |>.const_smul t⁻¹ have h2 : HasFDerivAt (fun y ↦ |t| * ‖y‖) (|t| • f) x := h.const_smul |t| conv at h2 => enter [3]; rw [← one_smul ℝ x, ← inv_mul_cancel₀ ht, mul_smul] convert h2.comp (t • x) h1 using 2 with y · simp only [Function.comp_apply] rw [norm_smul, ← mul_assoc, norm_eq_abs, ← abs_mul, mul_inv_cancel₀ ht, abs_one, one_mul] · ext y simp only [coe_smul', Pi.smul_apply, smul_eq_mul, comp_smulₛₗ, map_inv₀, RingHom.id_apply, comp_id] rw [eq_inv_mul_iff_mul_eq₀ ht, ← mul_assoc, self_mul_sign] theorem HasFDerivAt.hasFDerivAt_norm_smul_neg (ht : t < 0) (h : HasFDerivAt (‖·‖) f x) : HasFDerivAt (‖·‖) (-f) (t • x) := by simpa [ht] using h.hasFDerivAt_norm_smul ht.ne theorem HasFDerivAt.hasFDerivAt_norm_smul_pos (ht : 0 < t) (h : HasFDerivAt (‖·‖) f x) : HasFDerivAt (‖·‖) f (t • x) := by simpa [ht] using h.hasFDerivAt_norm_smul ht.ne' theorem differentiableAt_norm_smul (ht : t ≠ 0) : DifferentiableAt ℝ (‖·‖) x ↔ DifferentiableAt ℝ (‖·‖) (t • x) where mp hd := (hd.hasFDerivAt.hasFDerivAt_norm_smul ht).differentiableAt mpr hd := by convert (hd.hasFDerivAt.hasFDerivAt_norm_smul (inv_ne_zero ht)).differentiableAt rw [smul_smul, inv_mul_cancel₀ ht, one_smul] theorem DifferentiableAt.differentiableAt_norm_of_smul (h : DifferentiableAt ℝ (‖·‖) (t • x)) : DifferentiableAt ℝ (‖·‖) x := by obtain rfl | ht := eq_or_ne t 0 · by_cases hE : Nontrivial E · rw [zero_smul] at h exact not_differentiableAt_norm_zero E h |>.elim · rw [not_nontrivial_iff_subsingleton] at hE exact (hasFDerivAt_of_subsingleton _ _).differentiableAt · exact differentiableAt_norm_smul ht |>.2 h theorem DifferentiableAt.fderiv_norm_self {x : E} (h : DifferentiableAt ℝ (‖·‖) x) : fderiv ℝ (‖·‖) x x = ‖x‖ := by rw [← h.lineDeriv_eq_fderiv, lineDeriv] have this (t : ℝ) : ‖x + t • x‖ = |1 + t| * ‖x‖ := by rw [← norm_eq_abs, ← norm_smul, add_smul, one_smul] simp_rw [this] rw [deriv_mul_const] · conv_lhs => enter [1, 1]; change _root_.abs ∘ (fun t ↦ 1 + t) rw [deriv_comp, deriv_abs, deriv_const_add] · simp · exact differentiableAt_abs (by simp) · exact differentiableAt_id.const_add _ · exact (differentiableAt_abs (by simp)).comp _ (differentiableAt_id.const_add _) variable (x t) in theorem fderiv_norm_smul : fderiv ℝ (‖·‖) (t • x) = (SignType.sign t : ℝ) • (fderiv ℝ (‖·‖) x) := by by_cases hE : Nontrivial E · by_cases hd : DifferentiableAt ℝ (‖·‖) x · obtain rfl | ht := eq_or_ne t 0 · simp only [zero_smul, _root_.sign_zero, SignType.coe_zero] exact fderiv_zero_of_not_differentiableAt <| not_differentiableAt_norm_zero E · rw [(hd.hasFDerivAt.hasFDerivAt_norm_smul ht).fderiv] · rw [fderiv_zero_of_not_differentiableAt hd, fderiv_zero_of_not_differentiableAt] · simp · exact mt DifferentiableAt.differentiableAt_norm_of_smul hd · rw [not_nontrivial_iff_subsingleton] at hE simp_rw [(hasFDerivAt_of_subsingleton _ _).fderiv, smul_zero] theorem fderiv_norm_smul_pos (ht : 0 < t) : fderiv ℝ (‖·‖) (t • x) = fderiv ℝ (‖·‖) x := by simp [fderiv_norm_smul, ht] theorem fderiv_norm_smul_neg (ht : t < 0) : fderiv ℝ (‖·‖) (t • x) = -fderiv ℝ (‖·‖) x := by simp [fderiv_norm_smul, ht] theorem norm_fderiv_norm [Nontrivial E] (h : DifferentiableAt ℝ (‖·‖) x) : ‖fderiv ℝ (‖·‖) x‖ = 1 := by have : x ≠ 0 := fun hx ↦ not_differentiableAt_norm_zero E (hx ▸ h) refine le_antisymm (NNReal.coe_one ▸ norm_fderiv_le_of_lipschitz ℝ lipschitzWith_one_norm) ?_ apply le_of_mul_le_mul_right _ (norm_pos_iff.2 this) calc 1 * ‖x‖ = fderiv ℝ (‖·‖) x x := by rw [one_mul, h.fderiv_norm_self] _ ≤ ‖fderiv ℝ (‖·‖) x x‖ := le_norm_self _ _ ≤ ‖fderiv ℝ (‖·‖) x‖ * ‖x‖ := le_opNorm _ _
LiftingProperties.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.Preadditive.Injective.Basic import Mathlib.CategoryTheory.MorphismProperty.LiftingProperty /-! # Characterization of injective objects in terms of lifting properties An object `I` is injective iff the morphism `I ⟶ 0` has the right lifting property with respect to monomorphisms, `injective_iff_rlp_monomorphisms_zero`. -/ universe v u namespace CategoryTheory open Limits ZeroObject variable {C : Type u} [Category.{v} C] namespace Injective lemma hasLiftingProperty_of_isZero {A B I Z : C} (i : A ⟶ B) [Mono i] [Injective I] (p : I ⟶ Z) (hZ : IsZero Z) : HasLiftingProperty i p where sq_hasLift {f g} sq := ⟨⟨{ l := Injective.factorThru f i fac_right := hZ.eq_of_tgt _ _ }⟩⟩ instance {A B I : C} (i : A ⟶ B) [Mono i] [Injective I] [HasZeroObject C] (p : I ⟶ 0) : HasLiftingProperty i (p : I ⟶ 0) := Injective.hasLiftingProperty_of_isZero i p (isZero_zero C) end Injective lemma injective_iff_rlp_monomorphisms_of_isZero [HasZeroMorphisms C] {I Z : C} (p : I ⟶ Z) (hZ : IsZero Z) : Injective I ↔ (MorphismProperty.monomorphisms C).rlp p := by obtain rfl := hZ.eq_of_tgt p 0 constructor · intro _ A B i (_ : Mono i) exact Injective.hasLiftingProperty_of_isZero i 0 hZ · intro h constructor intro A B f i hi have := h _ hi have sq : CommSq f i (0 : I ⟶ Z) 0 := ⟨by simp⟩ exact ⟨sq.lift, by simp⟩ lemma injective_iff_rlp_monomorphisms_zero [HasZeroMorphisms C] [HasZeroObject C] (I : C) : Injective I ↔ (MorphismProperty.monomorphisms C).rlp (0 : I ⟶ 0) := injective_iff_rlp_monomorphisms_of_isZero _ (isZero_zero C) end CategoryTheory
test_ssrAC.v
From mathcomp Require Import all_boot ssralg. Section Tests. Lemma test_orb (a b c d : bool) : (a || b) || (c || d) = (a || c) || (b || d). Proof. time by rewrite orbACA. Abort. Lemma test_orb (a b c d : bool) : (a || b) || (c || d) = (a || c) || (b || d). Proof. time by rewrite (AC (2*2) ((1*3)*(2*4))). Abort. Lemma test_orb (a b c d : bool) : (a || b) || (c || d) = (a || c) || (b || d). Proof. time by rewrite orb.[AC (2*2) ((1*3)*(2*4))]. Qed. Lemma test_addn (a b c d : nat) : a + b + c + d = a + c + b + d. Proof. time by rewrite -addnA addnAC addnA addnAC. Abort. Lemma test_addn (a b c d : nat) : a + b + c + d = a + c + b + d. Proof. time by rewrite (ACl (1*3*2*4)). Abort. Lemma test_addn (a b c d : nat) : a + b + c + d = a + c + b + d. Proof. time by rewrite addn.[ACl 1*3*2*4]. Qed. Lemma test_addr (R : comRingType) (a b c d : R) : (a + b + c + d = a + c + b + d)%R. Proof. time by rewrite -GRing.addrA GRing.addrAC GRing.addrA GRing.addrAC. Abort. Lemma test_addr (R : comRingType) (a b c d : R) : (a + b + c + d = a + c + b + d)%R. Proof. time by rewrite (ACl (1*3*2*4)). Abort. Lemma test_addr (R : comRingType) (a b c d : R) : (a + b + c + d = a + c + b + d)%R. Proof. time by rewrite (@GRing.add R).[ACl 1*3*2*4]. Qed. Local Open Scope ring_scope. Import GRing.Theory. Lemma test_mulr (R : comRingType) (x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 : R) (x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 : R) : (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) = (x0 * x2 * x4 * x9) * (x1 * x3 * x5 * x7) * x6 * x8 * (x10 * x12 * x14 * x19) * (x11 * x13 * x15 * x17) * x16 * x18 * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9)* (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) *(x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) * (x10 * x11) * (x12 * x13) * (x14 * x15) * (x16 * x17 * x18 * x19) * (x0 * x1) * (x2 * x3) * (x4 * x5) * (x6 * x7 * x8 * x9) . Proof. pose s := ((2 * 4 * 9 * 1 * 3 * 5 * 7 * 6 * 8 * 20 * 21 * 22 * 23) * 25 * 26 * 27 * 28 * (29 * 30 * 31) * 32 * 33 * 34 * 35 * 36 * 37 * 38 * 39 * 40 * 41 * (10 * 12 * 14 * 19 * 11 * 13 * 15 * 17 * 16 * 18 * 24) * (42 * 43 * 44 * 45 * 46 * 47 * 48 * 49) * 50 * 52 * 53 * 54 * 55 * 56 * 57 * 58 * 59 * 51* 60 * 62 * 63 * 64 * 65 * 66 * 67 * 68 * 69 * 61* 70 * 72 * 73 * 74 * 75 * 76 * 77 * 78 * 79 * 71 * 80 * 82 * 83 * 84 * 85 * 86 * 87 * 88 * 89 * 81* 90 * 92 * 93 * 94 * 95 * 96 * 97 * 98 * 99 * 91 * 100 * ((102 * 104 * 109 * 101 * 103 * 105 * 107 * 106 * 108 * 120 * 121 * 122 * 123) * 125 * 126 * 127 * 128 * (129 * 130 * 131) * 132 * 133 * 134 * 135 * 136 * 137 * 138 * 139 * 140 * 141 * (110 * 112 * 114 * 119 * 111 * 113 * 115 * 117 * 116 * 118 * 124) * (142 * 143 * 144 * 145 * 146 * 147 * 148 * 149) * 150 * 152 * 153 * 154 * 155 * 156 * 157 * 158 * 159 * 151* 160 * 162 * 163 * 164 * 165 * 166 * 167 * 168 * 169 * 161* 170 * 172 * 173 * 174 * 175 * 176 * 177 * 178 * 179 * 171 * 180 * 182 * 183 * 184 * 185 * 186 * 187 * 188 * 189 * 181* 190 * 192 * 193 * 194 * 195 * 196 * 197 * 198 * 199 * 191) )%AC. time have := (@GRing.mul R).[ACl s]. time rewrite (@GRing.mul R).[ACl s]. Abort. End Tests.
Powerset.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.List.Sublists import Mathlib.Data.List.Zip import Mathlib.Data.Multiset.Bind import Mathlib.Data.Multiset.Range /-! # The powerset of a multiset -/ namespace Multiset open List variable {α : Type*} /-! ### powerset -/ -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11215): TODO: Write a more efficient version /-- A helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` as multisets. -/ def powersetAux (l : List α) : List (Multiset α) := (sublists l).map (↑) theorem powersetAux_eq_map_coe {l : List α} : powersetAux l = (sublists l).map (↑) := rfl @[simp] theorem mem_powersetAux {l : List α} {s} : s ∈ powersetAux l ↔ s ≤ ↑l := Quotient.inductionOn s <| by simp [powersetAux_eq_map_coe, Subperm, and_comm] /-- Helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists'`), as multisets. -/ def powersetAux' (l : List α) : List (Multiset α) := (sublists' l).map (↑) theorem powersetAux_perm_powersetAux' {l : List α} : powersetAux l ~ powersetAux' l := by rw [powersetAux_eq_map_coe]; exact (sublists_perm_sublists' _).map _ @[simp] theorem powersetAux'_nil : powersetAux' (@nil α) = [0] := rfl @[simp] theorem powersetAux'_cons (a : α) (l : List α) : powersetAux' (a :: l) = powersetAux' l ++ List.map (cons a) (powersetAux' l) := by simp [powersetAux'] theorem powerset_aux'_perm {l₁ l₂ : List α} (p : l₁ ~ l₂) : powersetAux' l₁ ~ powersetAux' l₂ := by induction p with | nil => simp | cons _ _ IH => simp only [powersetAux'_cons] exact IH.append (IH.map _) | swap a b => simp only [powersetAux'_cons, map_append, List.map_map, append_assoc] apply Perm.append_left rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)] exact perm_append_comm.append_right _ | trans _ _ IH₁ IH₂ => exact IH₁.trans IH₂ theorem powersetAux_perm {l₁ l₂ : List α} (p : l₁ ~ l₂) : powersetAux l₁ ~ powersetAux l₂ := powersetAux_perm_powersetAux'.trans <| (powerset_aux'_perm p).trans powersetAux_perm_powersetAux'.symm --Porting note (https://github.com/leanprover-community/mathlib4/issues/11083): slightly slower implementation due to `map ofList` /-- The power set of a multiset. -/ def powerset (s : Multiset α) : Multiset (Multiset α) := Quot.liftOn s (fun l => (powersetAux l : Multiset (Multiset α))) (fun _ _ h => Quot.sound (powersetAux_perm h)) theorem powerset_coe (l : List α) : @powerset α l = ((sublists l).map (↑) : List (Multiset α)) := congr_arg ((↑) : List (Multiset α) → Multiset (Multiset α)) powersetAux_eq_map_coe @[simp] theorem powerset_coe' (l : List α) : @powerset α l = ((sublists' l).map (↑) : List (Multiset α)) := Quot.sound powersetAux_perm_powersetAux' @[simp] theorem powerset_zero : @powerset α 0 = {0} := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a ::ₘ s) = powerset s + map (cons a) (powerset s) := Quotient.inductionOn s fun l => by simp [Function.comp_def] @[simp] theorem mem_powerset {s t : Multiset α} : s ∈ powerset t ↔ s ≤ t := Quotient.inductionOn₂ s t <| by simp [Subperm, and_comm] theorem map_single_le_powerset (s : Multiset α) : s.map singleton ≤ powerset s := Quotient.inductionOn s fun l => by simp only [powerset_coe, quot_mk_to_coe, coe_le, map_coe] change l.map (((↑) : List α → Multiset α) ∘ pure) <+~ (sublists l).map (↑) rw [← List.map_map] exact ((map_pure_sublist_sublists _).map _).subperm @[simp] theorem card_powerset (s : Multiset α) : card (powerset s) = 2 ^ card s := Quotient.inductionOn s <| by simp theorem revzip_powersetAux {l : List α} ⦃x⦄ (h : x ∈ revzip (powersetAux l)) : x.1 + x.2 = ↑l := by rw [revzip, powersetAux_eq_map_coe, ← map_reverse, zip_map, ← revzip, List.mem_map] at h simp only [Prod.map_apply, Prod.exists] at h rcases h with ⟨l₁, l₂, h, rfl, rfl⟩ exact Quot.sound (revzip_sublists _ _ _ h) theorem revzip_powersetAux' {l : List α} ⦃x⦄ (h : x ∈ revzip (powersetAux' l)) : x.1 + x.2 = ↑l := by rw [revzip, powersetAux', ← map_reverse, zip_map, ← revzip, List.mem_map] at h simp only [Prod.map_apply, Prod.exists] at h rcases h with ⟨l₁, l₂, h, rfl, rfl⟩ exact Quot.sound (revzip_sublists' _ _ _ h) theorem revzip_powersetAux_lemma {α : Type*} [DecidableEq α] (l : List α) {l' : List (Multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) : revzip l' = l'.map fun x => (x, (l : Multiset α) - x) := by have : Forall₂ (fun (p : Multiset α × Multiset α) (s : Multiset α) => p = (s, ↑l - s)) (revzip l') ((revzip l').map Prod.fst) := by rw [forall₂_map_right_iff, forall₂_same] rintro ⟨s, t⟩ h dsimp rw [← H h, add_tsub_cancel_left] rw [← forall₂_eq_eq_eq, forall₂_map_right_iff] simpa using this theorem revzip_powersetAux_perm_aux' {l : List α} : revzip (powersetAux l) ~ revzip (powersetAux' l) := by haveI := Classical.decEq α rw [revzip_powersetAux_lemma l revzip_powersetAux, revzip_powersetAux_lemma l revzip_powersetAux'] exact powersetAux_perm_powersetAux'.map _ theorem revzip_powersetAux_perm {l₁ l₂ : List α} (p : l₁ ~ l₂) : revzip (powersetAux l₁) ~ revzip (powersetAux l₂) := by haveI := Classical.decEq α simp only [fun l : List α => revzip_powersetAux_lemma l revzip_powersetAux, coe_eq_coe.2 p] exact (powersetAux_perm p).map _ /-! ### powersetCard -/ /-- Helper function for `powersetCard`. Given a list `l`, `powersetCardAux n l` is the list of sublists of length `n`, as multisets. -/ def powersetCardAux (n : ℕ) (l : List α) : List (Multiset α) := sublistsLenAux n l (↑) [] theorem powersetCardAux_eq_map_coe {n} {l : List α} : powersetCardAux n l = (sublistsLen n l).map (↑) := by rw [powersetCardAux, sublistsLenAux_eq, append_nil] @[simp] theorem mem_powersetCardAux {n} {l : List α} {s} : s ∈ powersetCardAux n l ↔ s ≤ ↑l ∧ card s = n := Quotient.inductionOn s <| by simp only [quot_mk_to_coe, powersetCardAux_eq_map_coe, List.mem_map, mem_sublistsLen, coe_eq_coe, coe_le, Subperm, coe_card] exact fun l₁ => ⟨fun ⟨l₂, ⟨s, e⟩, p⟩ => ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩, fun ⟨⟨l₂, p, s⟩, e⟩ => ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩ @[simp] theorem powersetCardAux_zero (l : List α) : powersetCardAux 0 l = [0] := by simp [powersetCardAux_eq_map_coe] @[simp] theorem powersetCardAux_nil (n : ℕ) : powersetCardAux (n + 1) (@nil α) = [] := rfl @[simp] theorem powersetCardAux_cons (n : ℕ) (a : α) (l : List α) : powersetCardAux (n + 1) (a :: l) = powersetCardAux (n + 1) l ++ List.map (cons a) (powersetCardAux n l) := by simp [powersetCardAux_eq_map_coe] theorem powersetCardAux_perm {n} {l₁ l₂ : List α} (p : l₁ ~ l₂) : powersetCardAux n l₁ ~ powersetCardAux n l₂ := by induction' n with n IHn generalizing l₁ l₂ · simp induction p with | nil => rfl | cons _ p IH => simp only [powersetCardAux_cons] exact IH.append ((IHn p).map _) | swap a b => simp only [powersetCardAux_cons, append_assoc] apply Perm.append_left cases n · simp [Perm.swap] simp only [powersetCardAux_cons, map_append, List.map_map] rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)] exact perm_append_comm.append_right _ | trans _ _ IH₁ IH₂ => exact IH₁.trans IH₂ /-- `powersetCard n s` is the multiset of all submultisets of `s` of length `n`. -/ def powersetCard (n : ℕ) (s : Multiset α) : Multiset (Multiset α) := Quot.liftOn s (fun l => (powersetCardAux n l : Multiset (Multiset α))) fun _ _ h => Quot.sound (powersetCardAux_perm h) theorem powersetCard_coe' (n) (l : List α) : @powersetCard α n l = powersetCardAux n l := rfl theorem powersetCard_coe (n) (l : List α) : @powersetCard α n l = ((sublistsLen n l).map (↑) : List (Multiset α)) := congr_arg ((↑) : List (Multiset α) → Multiset (Multiset α)) powersetCardAux_eq_map_coe @[simp] theorem powersetCard_zero_left (s : Multiset α) : powersetCard 0 s = {0} := Quotient.inductionOn s fun l => by simp [powersetCard_coe'] theorem powersetCard_zero_right (n : ℕ) : @powersetCard α (n + 1) 0 = 0 := rfl @[simp] theorem powersetCard_cons (n : ℕ) (a : α) (s) : powersetCard (n + 1) (a ::ₘ s) = powersetCard (n + 1) s + map (cons a) (powersetCard n s) := Quotient.inductionOn s fun l => by simp [powersetCard_coe'] theorem powersetCard_one (s : Multiset α) : powersetCard 1 s = s.map singleton := Quotient.inductionOn s fun l ↦ by simp [powersetCard_coe, sublistsLen_one, map_reverse, Function.comp_def] @[simp] theorem mem_powersetCard {n : ℕ} {s t : Multiset α} : s ∈ powersetCard n t ↔ s ≤ t ∧ card s = n := Quotient.inductionOn t fun l => by simp [powersetCard_coe'] @[simp] theorem card_powersetCard (n : ℕ) (s : Multiset α) : card (powersetCard n s) = Nat.choose (card s) n := Quotient.inductionOn s <| by simp [powersetCard_coe] theorem powersetCard_le_powerset (n : ℕ) (s : Multiset α) : powersetCard n s ≤ powerset s := Quotient.inductionOn s fun l => by simp only [quot_mk_to_coe, powersetCard_coe, powerset_coe', coe_le] exact ((sublistsLen_sublist_sublists' _ _).map _).subperm theorem powersetCard_mono (n : ℕ) {s t : Multiset α} (h : s ≤ t) : powersetCard n s ≤ powersetCard n t := leInductionOn h fun {l₁ l₂} h => by simp only [powersetCard_coe, coe_le] exact ((sublistsLen_sublist_of_sublist _ h).map _).subperm @[simp] theorem powersetCard_eq_empty {α : Type*} (n : ℕ) {s : Multiset α} (h : card s < n) : powersetCard n s = 0 := card_eq_zero.mp (Nat.choose_eq_zero_of_lt h ▸ card_powersetCard _ _) theorem powersetCard_card_add (s : Multiset α) {i : ℕ} (hi : 0 < i) : s.powersetCard (card s + i) = 0 := by simp [hi] theorem powersetCard_map {β : Type*} (f : α → β) (n : ℕ) (s : Multiset α) : powersetCard n (s.map f) = (powersetCard n s).map (map f) := by induction' s using Multiset.induction with t s ih generalizing n · cases n <;> simp [powersetCard_zero_left] · cases n <;> simp [ih] theorem pairwise_disjoint_powersetCard (s : Multiset α) : _root_.Pairwise fun i j => Disjoint (s.powersetCard i) (s.powersetCard j) := fun _ _ h ↦ disjoint_left.mpr fun hi hj ↦ h ((Multiset.mem_powersetCard.mp hi).2.symm.trans (Multiset.mem_powersetCard.mp hj).2) theorem bind_powerset_len {α : Type*} (S : Multiset α) : (bind (Multiset.range (card S + 1)) fun k => S.powersetCard k) = S.powerset := by induction S using Quotient.inductionOn simp_rw [quot_mk_to_coe, powerset_coe', powersetCard_coe, ← coe_range, coe_bind, ← List.map_flatMap, coe_card] exact coe_eq_coe.mpr ((List.range_bind_sublistsLen_perm _).map _) @[simp] theorem nodup_powerset {s : Multiset α} : Nodup (powerset s) ↔ Nodup s := ⟨fun h => (nodup_of_le (map_single_le_powerset _) h).of_map _, Quotient.inductionOn s fun l h => by simp only [quot_mk_to_coe, powerset_coe', coe_nodup] refine (nodup_sublists'.2 h).map_on ?_ exact fun x sx y sy e => (h.perm_iff_eq_of_sublist (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (Quotient.exact e)⟩ alias ⟨Nodup.ofPowerset, Nodup.powerset⟩ := nodup_powerset protected theorem Nodup.powersetCard {n : ℕ} {s : Multiset α} (h : Nodup s) : Nodup (powersetCard n s) := nodup_of_le (powersetCard_le_powerset _ _) (nodup_powerset.2 h) end Multiset
IsNonarchimedean.lean
/- Copyright (c) 2025 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández, Fabrizio Barroero -/ import Mathlib.Algebra.Order.Hom.Basic import Mathlib.Data.Nat.Choose.Sum /-! # Nonarchimedean functions A function `f : α → R` is nonarchimedean if it satisfies the strong triangle inequality `f (a + b) ≤ max (f a) (f b)` for all `a b : α`. This file proves basic properties of nonarchimedean functions. -/ namespace IsNonarchimedean variable {R : Type*} [Semiring R] [LinearOrder R] {a b : R} {m n : ℕ} /-- A nonnegative nonarchimedean function satisfies the triangle inequality. -/ theorem add_le [IsStrictOrderedRing R] {α : Type*} [Add α] {f : α → R} (hf : ∀ x : α, 0 ≤ f x) (hna : IsNonarchimedean f) {a b : α} : f (a + b) ≤ f a + f b := by apply le_trans (hna _ _) rw [max_le_iff, le_add_iff_nonneg_right, le_add_iff_nonneg_left] exact ⟨hf _, hf _⟩ /-- If `f` is a nonegative nonarchimedean function `α → R` such that `f 0 = 0`, then for every `n : ℕ` and `a : α`, we have `f (n • a) ≤ (f a)`. -/ theorem nsmul_le {F α : Type*} [AddMonoid α] [FunLike F α R] [ZeroHomClass F α R] [NonnegHomClass F α R] {f : F} (hna : IsNonarchimedean f) {n : ℕ} {a : α} : f (n • a) ≤ f a := by induction n with | zero => simp | succ n _ => rw [add_nsmul] apply le_trans <| hna (n • a) (1 • a) simpa /-- If `f` is a nonegative nonarchimedean function `α → R` such that `f 0 = 0`, then for every `n : ℕ` and `a : α`, we have `f (n * a) ≤ (f a)`. -/ theorem nmul_le {F α : Type*} [NonAssocSemiring α] [FunLike F α R] [ZeroHomClass F α R] [NonnegHomClass F α R] {f : F} (hna : IsNonarchimedean f) {n : ℕ} {a : α} : f (n * a) ≤ f a := by rw [← nsmul_eq_mul] exact nsmul_le hna lemma apply_natCast_le_one_of_isNonarchimedean {F α : Type*} [AddMonoidWithOne α] [FunLike F α R] [ZeroHomClass F α R] [NonnegHomClass F α R] [OneHomClass F α R] {f : F} (hna : IsNonarchimedean f) {n : ℕ} : f n ≤ 1 := by rw [← nsmul_one n, ← map_one f] exact nsmul_le hna /-- If `f` is a nonarchimedean additive group seminorm on `α` with `f 1 = 1`, then for every `n : ℤ` we have `f n ≤ 1`. -/ theorem apply_intCast_le_one_of_isNonarchimedean [IsStrictOrderedRing R] {F α : Type*} [AddGroupWithOne α] [FunLike F α R] [AddGroupSeminormClass F α R] [OneHomClass F α R] {f : F} (hna : IsNonarchimedean f) {n : ℤ} : f n ≤ 1 := by obtain ⟨a, rfl | rfl⟩ := Int.eq_nat_or_neg n <;> simp [apply_natCast_le_one_of_isNonarchimedean hna] lemma add_eq_right_of_lt {F α : Type*} [AddGroup α] [FunLike F α R] [AddGroupSeminormClass F α R] {f : F} (hna : IsNonarchimedean f) {x y : α} (h_lt : f x < f y) : f (x + y) = f y := by by_contra! h have h1 : f (x + y) ≤ f y := (hna x y).trans_eq (max_eq_right_of_lt h_lt) apply lt_irrefl (f y) calc f y = f (-x + (x + y)) := by simp _ ≤ max (f (-x)) (f (x + y)) := hna (-x) (x + y) _ < max (f y) (f y) := by rw [max_self, map_neg_eq_map] exact max_lt h_lt <| lt_of_le_of_ne h1 h _ = f y := max_self (f y) lemma add_eq_left_of_lt {F α : Type*} [AddGroup α] [FunLike F α R] [AddGroupSeminormClass F α R] {f : F} (hna : IsNonarchimedean f) {x y : α} (h_lt : f y < f x) : f (x + y) = f x := by by_contra! h have h1 : f (x + y) ≤ f x := (hna x y).trans_eq (max_eq_left_of_lt h_lt) apply lt_irrefl (f x) calc f x = f (x + y + -y) := by simp _ ≤ max (f (x + y)) (f (-y)) := hna (x + y) (-y) _ < max (f x) (f x) := by rw [max_self, map_neg_eq_map] apply max_lt (lt_of_le_of_ne h1 h) h_lt _ = f x := max_self (f x) /-- If `f` is a nonarchimedean additive group seminorm on `α` and `x y : α` are such that `f x ≠ f y`, then `f (x + y) = max (f x) (f y)`. -/ theorem add_eq_max_of_ne {F α : Type*} [AddGroup α] [FunLike F α R] [AddGroupSeminormClass F α R] {f : F} (hna : IsNonarchimedean f) {x y : α} (hne : f x ≠ f y) : f (x + y) = max (f x) (f y) := by rcases hne.lt_or_gt with h_lt | h_lt · rw [add_eq_right_of_lt hna h_lt] exact (max_eq_right_of_lt h_lt).symm · rw [add_eq_left_of_lt hna h_lt] exact (max_eq_left_of_lt h_lt).symm omit [Semiring R] in /-- Given a nonarchimedean function `α → R`, a function `g : β → α` and a nonempty multiset `s : Multiset β`, we can always find `b : β` belonging to `s` such that `f (t.sum g) ≤ f (g b)` . -/ theorem multiset_image_add_of_nonempty {α β : Type*} [AddCommMonoid α] [Nonempty β] {f : α → R} (hna : IsNonarchimedean f) (g : β → α) {s : Multiset β} (hs : s ≠ 0) : ∃ b : β, (b ∈ s) ∧ f (Multiset.map g s).sum ≤ f (g b) := by induction s using Multiset.induction_on with | empty => contradiction | cons a s h => simp only [Multiset.mem_cons, Multiset.map_cons, Multiset.sum_cons, exists_eq_or_imp] by_cases h1 : s = 0 · simp [h1] · obtain ⟨w, h2, h3⟩ := h h1 rcases le_max_iff.mp <| hna (g a) (Multiset.map g s).sum with h4 | h4 · exact .inl h4 · exact .inr ⟨w, h2, le_trans h4 h3⟩ omit [Semiring R] in /-- Given a nonarchimedean function `α → R`, a function `g : β → α` and a nonempty finset `t : Finset β`, we can always find `b : β` belonging to `t` such that `f (t.sum g) ≤ f (g b)` . -/ theorem finset_image_add_of_nonempty {α β : Type*} [AddCommMonoid α] [Nonempty β] {f : α → R} (hna : IsNonarchimedean f) (g : β → α) {t : Finset β} (ht : t.Nonempty) : ∃ b ∈ t, f (t.sum g) ≤ f (g b) := by apply multiset_image_add_of_nonempty hna simp_all [Finset.nonempty_iff_ne_empty] /-- Given a nonegative nonarchimedean function `α → R` such that `f 0 = 0`, a function `g : β → α` and a multiset `s : Multiset β`, we can always find `b : β`, belonging to `s` if `s` is nonempty, such that `f (s.sum g) ≤ f (g b)` . -/ theorem multiset_image_add {F α β : Type*} [AddCommMonoid α] [FunLike F α R] [ZeroHomClass F α R] [NonnegHomClass F α R] [Nonempty β] {f : F} (hna : IsNonarchimedean f) (g : β → α) (s : Multiset β) : ∃ b : β, (s ≠ 0 → b ∈ s) ∧ f (Multiset.map g s).sum ≤ f (g b) := by induction s using Multiset.induction_on with | empty => simp | cons a s h => obtain ⟨b, hb1, hb2⟩ := multiset_image_add_of_nonempty (s := a ::ₘ s) hna g Multiset.cons_ne_zero exact ⟨b, fun _ ↦ hb1, hb2⟩ /-- Given a nonegative nonarchimedean function `α → R` such that `f 0 = 0`, a function `g : β → α` and a finset `t : Finset β`, we can always find `b : β`, belonging to `t` if `t` is nonempty, such that `f (t.sum g) ≤ f (g b)` . -/ theorem finset_image_add {F α β : Type*} [AddCommMonoid α] [FunLike F α R] [ZeroHomClass F α R] [NonnegHomClass F α R] [Nonempty β] {f : F} (hna : IsNonarchimedean f) (g : β → α) (t : Finset β) : ∃ b : β, (t.Nonempty → b ∈ t) ∧ f (t.sum g) ≤ f (g b) := by have h1 : t.Nonempty ↔ t.val ≠ 0 := by simp [Finset.nonempty_iff_ne_empty] rw [h1] exact multiset_image_add hna g t.val open Multiset in theorem multiset_powerset_image_add [IsStrictOrderedRing R] {F α : Type*} [CommRing α] [FunLike F α R] [AddGroupSeminormClass F α R] {f : F} (hf_na : IsNonarchimedean f) (s : Multiset α) (m : ℕ) : ∃ t : Multiset α, card t = card s - m ∧ (∀ x : α, x ∈ t → x ∈ s) ∧ f (map prod (powersetCard (card s - m) s)).sum ≤ f t.prod := by set g := fun t : Multiset α ↦ t.prod obtain ⟨b, hb_in, hb_le⟩ := hf_na.multiset_image_add g (powersetCard (card s - m) s) have hb : b ≤ s ∧ card b = card s - m := by rw [← mem_powersetCard] exact hb_in (card_pos.mp (card_powersetCard (s.card - m) s ▸ Nat.choose_pos ((card s).sub_le m))) exact ⟨b, hb.2, fun x hx ↦ mem_of_le hb.left hx, hb_le⟩ open Finset in theorem finset_powerset_image_add [IsStrictOrderedRing R] {F α β : Type*} [CommRing α] [FunLike F α R] [AddGroupSeminormClass F α R] {f : F} (hf_na : IsNonarchimedean f) (s : Finset β) (b : β → α) (m : ℕ) : ∃ u : powersetCard (s.card - m) s, f ((powersetCard (s.card - m) s).sum fun t : Finset β ↦ t.prod fun i : β ↦ -b i) ≤ f (u.val.prod fun i : β ↦ -b i) := by set g := fun t : Finset β ↦ t.prod fun i : β ↦ - b i obtain ⟨b, hb_in, hb⟩ := hf_na.finset_image_add g (powersetCard (s.card - m) s) exact ⟨⟨b, hb_in (powersetCard_nonempty.mpr (Nat.sub_le s.card m))⟩, hb⟩ omit [Semiring R] in open Finset in /-- Ultrametric inequality with `Finset.sum`. -/ lemma apply_sum_le_sup_of_isNonarchimedean {α β : Type*} [AddCommMonoid α] {f : α → R} (nonarch : IsNonarchimedean f) {s : Finset β} (hnonempty : s.Nonempty) {l : β → α} : f (∑ i ∈ s, l i) ≤ s.sup' hnonempty fun i => f (l i) := by induction hnonempty using Nonempty.cons_induction with | singleton i => simp | cons i s _ hs hind => simp only [sum_cons, le_sup'_iff, mem_cons, exists_eq_or_imp] rw [← le_sup'_iff hs] rcases le_max_iff.mp <| nonarch (l i) (∑ i ∈ s, l i) with h₁ | h₂ · exact .inl h₁ · exact .inr <| le_trans h₂ hind /-- If `f` is a nonarchimedean additive group seminorm on a commutative ring `α`, `n : ℕ`, and `a b : α`, then we can find `m : ℕ` such that `m ≤ n` and `f ((a + b) ^ n) ≤ (f (a ^ m)) * (f (b ^ (n - m)))`. -/ theorem add_pow_le {F α : Type*} [CommRing α] [FunLike F α R] [ZeroHomClass F α R] [NonnegHomClass F α R] [SubmultiplicativeHomClass F α R] {f : F} (hna : IsNonarchimedean f) (n : ℕ) (a b : α) : ∃ m < n + 1, f ((a + b) ^ n) ≤ f (a ^ m) * f (b ^ (n - m)) := by obtain ⟨m, hm_lt, hM⟩ := finset_image_add hna (fun m => a ^ m * b ^ (n - m) * ↑(n.choose m)) (Finset.range (n + 1)) simp only [Finset.nonempty_range_iff, ne_eq, Nat.succ_ne_zero, not_false_iff, Finset.mem_range, forall_true_left] at hm_lt refine ⟨m, hm_lt, ?_⟩ simp only [← add_pow] at hM rw [mul_comm] at hM exact le_trans hM (le_trans (nmul_le hna) (map_mul_le_mul _ _ _)) end IsNonarchimedean
CatCommSq.lean
/- Copyright (c) 2023 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.CategoryTheory.Equivalence /-! # 2-commutative squares of functors Similarly as `CommSq.lean` defines the notion of commutative squares, this file introduces the notion of 2-commutative squares of functors. If `T : C₁ ⥤ C₂`, `L : C₁ ⥤ C₃`, `R : C₂ ⥤ C₄`, `B : C₃ ⥤ C₄` are functors, then `[CatCommSq T L R B]` contains the datum of an isomorphism `T ⋙ R ≅ L ⋙ B`. Future work: using this notion in the development of the localization of categories (e.g. localization of adjunctions). -/ namespace CategoryTheory open Category Functor variable {C₁ C₂ C₃ C₄ C₅ C₆ : Type*} [Category C₁] [Category C₂] [Category C₃] [Category C₄] [Category C₅] [Category C₆] /-- `CatCommSq T L R B` expresses that there is a 2-commutative square of functors, where the functors `T`, `L`, `R` and `B` are respectively the left, top, right and bottom functors of the square. -/ @[ext] class CatCommSq (T : C₁ ⥤ C₂) (L : C₁ ⥤ C₃) (R : C₂ ⥤ C₄) (B : C₃ ⥤ C₄) where /-- Assuming `[CatCommSq T L R B]`, `iso T L R B` is the isomorphism `T ⋙ R ≅ L ⋙ B` given by the 2-commutative square. -/ iso (T) (L) (R) (B) : T ⋙ R ≅ L ⋙ B variable (T : C₁ ⥤ C₂) (L : C₁ ⥤ C₃) (R : C₂ ⥤ C₄) (B : C₃ ⥤ C₄) namespace CatCommSq /-- The vertical identity `CatCommSq` -/ @[simps!] def vId : CatCommSq T (𝟭 C₁) (𝟭 C₂) T where iso := (Functor.leftUnitor _) ≪≫ (Functor.rightUnitor _).symm /-- The horizontal identity `CatCommSq` -/ @[simps!] def hId : CatCommSq (𝟭 C₁) L L (𝟭 C₃) where iso := (Functor.rightUnitor _) ≪≫ (Functor.leftUnitor _).symm @[reassoc (attr := simp)] lemma iso_hom_naturality [h : CatCommSq T L R B] {x y : C₁} (f : x ⟶ y) : R.map (T.map f) ≫ (iso T L R B).hom.app y = (iso T L R B).hom.app x ≫ B.map (L.map f) := (iso T L R B).hom.naturality f @[reassoc (attr := simp)] lemma iso_inv_naturality [h : CatCommSq T L R B] {x y : C₁} (f : x ⟶ y) : B.map (L.map f) ≫ (iso T L R B).inv.app y = (iso T L R B).inv.app x ≫ R.map (T.map f) := (iso T L R B).inv.naturality f /-- Horizontal composition of 2-commutative squares -/ @[simps!] def hComp (T₁ : C₁ ⥤ C₂) (T₂ : C₂ ⥤ C₃) (V₁ : C₁ ⥤ C₄) (V₂ : C₂ ⥤ C₅) (V₃ : C₃ ⥤ C₆) (B₁ : C₄ ⥤ C₅) (B₂ : C₅ ⥤ C₆) [CatCommSq T₁ V₁ V₂ B₁] [CatCommSq T₂ V₂ V₃ B₂] : CatCommSq (T₁ ⋙ T₂) V₁ V₃ (B₁ ⋙ B₂) where iso := associator _ _ _ ≪≫ isoWhiskerLeft T₁ (iso T₂ V₂ V₃ B₂) ≪≫ (associator _ _ _).symm ≪≫ isoWhiskerRight (iso T₁ V₁ V₂ B₁) B₂ ≪≫ associator _ _ _ /-- A variant of `hComp` where both squares can be explicitly provided. -/ abbrev hComp' {T₁ : C₁ ⥤ C₂} {T₂ : C₂ ⥤ C₃} {V₁ : C₁ ⥤ C₄} {V₂ : C₂ ⥤ C₅} {V₃ : C₃ ⥤ C₆} {B₁ : C₄ ⥤ C₅} {B₂ : C₅ ⥤ C₆} (S₁ : CatCommSq T₁ V₁ V₂ B₁) (S₂ : CatCommSq T₂ V₂ V₃ B₂) : CatCommSq (T₁ ⋙ T₂) V₁ V₃ (B₁ ⋙ B₂) := letI := S₁ letI := S₂ hComp _ _ _ V₂ _ _ _ /-- Vertical composition of 2-commutative squares -/ @[simps!] def vComp (L₁ : C₁ ⥤ C₂) (L₂ : C₂ ⥤ C₃) (H₁ : C₁ ⥤ C₄) (H₂ : C₂ ⥤ C₅) (H₃ : C₃ ⥤ C₆) (R₁ : C₄ ⥤ C₅) (R₂ : C₅ ⥤ C₆) [CatCommSq H₁ L₁ R₁ H₂] [CatCommSq H₂ L₂ R₂ H₃] : CatCommSq H₁ (L₁ ⋙ L₂) (R₁ ⋙ R₂) H₃ where iso := (associator _ _ _).symm ≪≫ isoWhiskerRight (iso H₁ L₁ R₁ H₂) R₂ ≪≫ associator _ _ _ ≪≫ isoWhiskerLeft L₁ (iso H₂ L₂ R₂ H₃) ≪≫ (associator _ _ _).symm /-- A variant of `vComp` where both squares can be explicitly provided. -/ abbrev vComp' {L₁ : C₁ ⥤ C₂} {L₂ : C₂ ⥤ C₃} {H₁ : C₁ ⥤ C₄} {H₂ : C₂ ⥤ C₅} {H₃ : C₃ ⥤ C₆} {R₁ : C₄ ⥤ C₅} {R₂ : C₅ ⥤ C₆} (S₁ : CatCommSq H₁ L₁ R₁ H₂) (S₂ : CatCommSq H₂ L₂ R₂ H₃) : CatCommSq H₁ (L₁ ⋙ L₂) (R₁ ⋙ R₂) H₃ := letI := S₁ letI := S₂ vComp _ _ _ H₂ _ _ _ section variable (T : C₁ ≌ C₂) (L : C₁ ⥤ C₃) (R : C₂ ⥤ C₄) (B : C₃ ≌ C₄) /-- Horizontal inverse of a 2-commutative square -/ @[simps!] def hInv (_ : CatCommSq T.functor L R B.functor) : CatCommSq T.inverse R L B.inverse where iso := isoWhiskerLeft _ (L.rightUnitor.symm ≪≫ isoWhiskerLeft L B.unitIso ≪≫ (associator _ _ _).symm ≪≫ isoWhiskerRight (iso T.functor L R B.functor).symm B.inverse ≪≫ associator _ _ _ ) ≪≫ (associator _ _ _).symm ≪≫ isoWhiskerRight T.counitIso _ ≪≫ leftUnitor _ lemma hInv_hInv (h : CatCommSq T.functor L R B.functor) : hInv T.symm R L B.symm (hInv T L R B h) = h := by ext X rw [← cancel_mono (B.functor.map (L.map (T.unitIso.hom.app X)))] rw [← Functor.comp_map] erw [← h.iso.hom.naturality (T.unitIso.hom.app X)] rw [hInv_iso_hom_app] simp only [Equivalence.symm_functor] rw [hInv_iso_inv_app] dsimp simp only [Functor.comp_obj, assoc, ← Functor.map_comp, Iso.inv_hom_id_app, Equivalence.counitInv_app_functor, Functor.map_id] simp only [Functor.map_comp, Equivalence.fun_inv_map, assoc, Equivalence.counitInv_functor_comp, comp_id, Iso.inv_hom_id_app_assoc] /-- In a square of categories, when the top and bottom functors are part of equivalence of categories, it is equivalent to show 2-commutativity for the functors of these equivalences or for their inverses. -/ def hInvEquiv : CatCommSq T.functor L R B.functor ≃ CatCommSq T.inverse R L B.inverse where toFun := hInv T L R B invFun := hInv T.symm R L B.symm left_inv := hInv_hInv T L R B right_inv := hInv_hInv T.symm R L B.symm end section variable (T : C₁ ⥤ C₂) (L : C₁ ≌ C₃) (R : C₂ ≌ C₄) (B : C₃ ⥤ C₄) /-- Vertical inverse of a 2-commutative square -/ @[simps!] def vInv (_ : CatCommSq T L.functor R.functor B) : CatCommSq B L.inverse R.inverse T where iso := isoWhiskerRight (B.leftUnitor.symm ≪≫ isoWhiskerRight L.counitIso.symm B ≪≫ associator _ _ _ ≪≫ isoWhiskerLeft L.inverse (iso T L.functor R.functor B).symm) R.inverse ≪≫ associator _ _ _ ≪≫ isoWhiskerLeft _ (associator _ _ _) ≪≫ (associator _ _ _ ).symm ≪≫ isoWhiskerLeft _ R.unitIso.symm ≪≫ rightUnitor _ lemma vInv_vInv (h : CatCommSq T L.functor R.functor B) : vInv B L.symm R.symm T (vInv T L R B h) = h := by ext X rw [vInv_iso_hom_app] dsimp rw [vInv_iso_inv_app] rw [← cancel_mono (B.map (L.functor.map (NatTrans.app L.unitIso.hom X)))] rw [← Functor.comp_map] erw [← (iso T L.functor R.functor B).hom.naturality (L.unitIso.hom.app X)] dsimp simp only [Functor.map_comp, Equivalence.fun_inv_map, Functor.comp_obj, Functor.id_obj, assoc, Iso.inv_hom_id_app_assoc, Iso.inv_hom_id_app, comp_id] rw [← B.map_comp, L.counit_app_functor, ← L.functor.map_comp, ← NatTrans.comp_app, Iso.inv_hom_id, NatTrans.id_app, L.functor.map_id] simp only [Functor.comp_obj] rw [B.map_id] rw [comp_id, R.counit_app_functor, ← R.functor.map_comp_assoc, ← R.functor.map_comp_assoc, assoc, ← NatTrans.comp_app, Iso.hom_inv_id, NatTrans.id_app] simp /-- In a square of categories, when the left and right functors are part of equivalence of categories, it is equivalent to show 2-commutativity for the functors of these equivalences or for their inverses. -/ def vInvEquiv : CatCommSq T L.functor R.functor B ≃ CatCommSq B L.inverse R.inverse T where toFun := vInv T L R B invFun := vInv B L.symm R.symm T left_inv := vInv_vInv T L R B right_inv := vInv_vInv B L.symm R.symm T end end CatCommSq end CategoryTheory
IndicatorConstPointwise.lean
/- Copyright (c) 2023 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import Mathlib.Algebra.Notation.Indicator import Mathlib.Topology.Separation.Basic /-! # Pointwise convergence of indicator functions In this file, we prove the equivalence of three different ways to phrase that the indicator functions of sets converge pointwise. ## Main results For `A` a set, `(Asᵢ)` an indexed collection of sets, under mild conditions, the following are equivalent: (a) the indicator functions of `Asᵢ` tend to the indicator function of `A` pointwise; (b) for every `x`, we eventually have that `x ∈ Asᵢ` holds iff `x ∈ A` holds; (c) `Tendsto As _ <| Filter.pi (pure <| · ∈ A)`. The results stating these in the case when the indicators take values in a Fréchet space are: * `tendsto_indicator_const_iff_forall_eventually` is the equivalence (a) ↔ (b); * `tendsto_indicator_const_iff_tendsto_pi_pure` is the equivalence (a) ↔ (c). -/ open Filter Topology variable {α : Type*} {A : Set α} variable {β : Type*} [Zero β] [TopologicalSpace β] variable {ι : Type*} (L : Filter ι) {As : ι → Set α} lemma tendsto_ite {β : Type*} {p : ι → Prop} [DecidablePred p] {q : Prop} [Decidable q] {a b : β} {F G : Filter β} (haG : {a}ᶜ ∈ G) (hbF : {b}ᶜ ∈ F) (haF : principal {a} ≤ F) (hbG : principal {b} ≤ G) : Tendsto (fun i ↦ if p i then a else b) L (if q then F else G) ↔ ∀ᶠ i in L, p i ↔ q := by constructor <;> intro h · by_cases hq : q · simp only [hq, ite_true] at h filter_upwards [mem_map.mp (h hbF)] with i hi simp only [Set.preimage_compl, Set.mem_compl_iff, Set.mem_preimage, Set.mem_singleton_iff, ite_eq_right_iff, not_forall, exists_prop] at hi tauto · simp only [hq, ite_false] at h filter_upwards [mem_map.mp (h haG)] with i hi simp only [Set.preimage_compl, Set.mem_compl_iff, Set.mem_preimage, Set.mem_singleton_iff, ite_eq_left_iff, not_forall, exists_prop] at hi tauto · have obs : (fun _ ↦ if q then a else b) =ᶠ[L] (fun i ↦ if p i then a else b) := by filter_upwards [h] with i hi simp only [hi] apply Tendsto.congr' obs by_cases hq : q · simp only [hq, ite_true] apply le_trans _ haF simp only [principal_singleton, le_pure_iff, mem_map, Set.mem_singleton_iff, Set.preimage_const_of_mem, univ_mem] · simp only [hq, ite_false] apply le_trans _ hbG simp only [principal_singleton, le_pure_iff, mem_map, Set.mem_singleton_iff, Set.preimage_const_of_mem, univ_mem] lemma tendsto_indicator_const_apply_iff_eventually' (b : β) (nhds_b : {0}ᶜ ∈ 𝓝 b) (nhds_o : {b}ᶜ ∈ 𝓝 0) (x : α) : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b) x) L (𝓝 (A.indicator (fun (_ : α) ↦ b) x)) ↔ ∀ᶠ i in L, (x ∈ As i ↔ x ∈ A) := by classical have heart := @tendsto_ite ι L β (fun i ↦ x ∈ As i) _ (x ∈ A) _ b 0 (𝓝 b) (𝓝 (0 : β)) nhds_o nhds_b ?_ ?_ · convert heart by_cases hxA : x ∈ A <;> simp [hxA] · simp only [principal_singleton, le_def, mem_pure] exact fun s s_nhds ↦ mem_of_mem_nhds s_nhds · simp only [principal_singleton, le_def, mem_pure] exact fun s s_nhds ↦ mem_of_mem_nhds s_nhds lemma tendsto_indicator_const_iff_forall_eventually' (b : β) (nhds_b : {0}ᶜ ∈ 𝓝 b) (nhds_o : {b}ᶜ ∈ 𝓝 0) : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b)) L (𝓝 (A.indicator (fun (_ : α) ↦ b))) ↔ ∀ x, ∀ᶠ i in L, (x ∈ As i ↔ x ∈ A) := by simp_rw [tendsto_pi_nhds] apply forall_congr' exact tendsto_indicator_const_apply_iff_eventually' L b nhds_b nhds_o /-- The indicator functions of `Asᵢ` evaluated at `x` tend to the indicator function of `A` evaluated at `x` if and only if we eventually have the equivalence `x ∈ Asᵢ ↔ x ∈ A`. -/ @[simp] lemma tendsto_indicator_const_apply_iff_eventually [T1Space β] (b : β) [NeZero b] (x : α) : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b) x) L (𝓝 (A.indicator (fun (_ : α) ↦ b) x)) ↔ ∀ᶠ i in L, (x ∈ As i ↔ x ∈ A) := by apply tendsto_indicator_const_apply_iff_eventually' _ b · simp only [compl_singleton_mem_nhds_iff, ne_eq, NeZero.ne, not_false_eq_true] · simp only [compl_singleton_mem_nhds_iff, ne_eq, (NeZero.ne b).symm, not_false_eq_true] /-- The indicator functions of `Asᵢ` tend to the indicator function of `A` pointwise if and only if for every `x`, we eventually have the equivalence `x ∈ Asᵢ ↔ x ∈ A`. -/ @[simp] lemma tendsto_indicator_const_iff_forall_eventually [T1Space β] (b : β) [NeZero b] : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b)) L (𝓝 (A.indicator (fun (_ : α) ↦ b))) ↔ ∀ x, ∀ᶠ i in L, (x ∈ As i ↔ x ∈ A) := by apply tendsto_indicator_const_iff_forall_eventually' _ b · simp only [compl_singleton_mem_nhds_iff, ne_eq, NeZero.ne, not_false_eq_true] · simp only [compl_singleton_mem_nhds_iff, ne_eq, (NeZero.ne b).symm, not_false_eq_true] lemma tendsto_indicator_const_iff_tendsto_pi_pure' (b : β) (nhds_b : {0}ᶜ ∈ 𝓝 b) (nhds_o : {b}ᶜ ∈ 𝓝 0) : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b)) L (𝓝 (A.indicator (fun (_ : α) ↦ b))) ↔ (Tendsto As L <| Filter.pi (pure <| · ∈ A)) := by rw [tendsto_indicator_const_iff_forall_eventually' _ b nhds_b nhds_o, tendsto_pi] simp_rw [tendsto_pure] aesop lemma tendsto_indicator_const_iff_tendsto_pi_pure [T1Space β] (b : β) [NeZero b] : Tendsto (fun i ↦ (As i).indicator (fun (_ : α) ↦ b)) L (𝓝 (A.indicator (fun (_ : α) ↦ b))) ↔ (Tendsto As L <| Filter.pi (pure <| · ∈ A)) := by rw [tendsto_indicator_const_iff_forall_eventually _ b, tendsto_pi] simp_rw [tendsto_pure] aesop
AsType.lean
/- Copyright (c) 2019 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.CategoryTheory.FinCategory.Basic import Mathlib.Data.Fintype.EquivFin /-! # Finite categories are equivalent to category in `Type 0`. -/ universe w v u noncomputable section namespace CategoryTheory namespace FinCategory variable (α : Type*) [Fintype α] [SmallCategory α] [FinCategory α] /-- A FinCategory `α` is equivalent to a category with objects in `Type`. -/ --@[nolint unused_arguments] abbrev ObjAsType : Type := InducedCategory α (Fintype.equivFin α).symm instance {i j : ObjAsType α} : Fintype (i ⟶ j) := FinCategory.fintypeHom ((Fintype.equivFin α).symm i) _ /-- The constructed category is indeed equivalent to `α`. -/ noncomputable def objAsTypeEquiv : ObjAsType α ≌ α := (inducedFunctor (Fintype.equivFin α).symm).asEquivalence /-- A FinCategory `α` is equivalent to a fin_category with in `Type`. -/ --@[nolint unused_arguments] abbrev AsType : Type := Fin (Fintype.card α) @[simps -isSimp id comp] noncomputable instance categoryAsType : SmallCategory (AsType α) where Hom i j := Fin (Fintype.card (@Quiver.Hom (ObjAsType α) _ i j)) id _ := Fintype.equivFin _ (𝟙 _) comp f g := Fintype.equivFin _ ((Fintype.equivFin _).symm f ≫ (Fintype.equivFin _).symm g) attribute [local simp] categoryAsType_id categoryAsType_comp /-- The "identity" functor from `AsType α` to `ObjAsType α`. -/ @[simps] noncomputable def asTypeToObjAsType : AsType α ⥤ ObjAsType α where obj := id map {_ _} := (Fintype.equivFin _).symm /-- The "identity" functor from `ObjAsType α` to `AsType α`. -/ @[simps] noncomputable def objAsTypeToAsType : ObjAsType α ⥤ AsType α where obj := id map {_ _} := Fintype.equivFin _ /-- The constructed category (`AsType α`) is equivalent to `ObjAsType α`. -/ noncomputable def asTypeEquivObjAsType : AsType α ≌ ObjAsType α where functor := asTypeToObjAsType α inverse := objAsTypeToAsType α unitIso := NatIso.ofComponents Iso.refl counitIso := NatIso.ofComponents Iso.refl noncomputable instance asTypeFinCategory : FinCategory (AsType α) where fintypeHom := fun _ _ => show Fintype (Fin _) from inferInstance /-- The constructed category (`ObjAsType α`) is indeed equivalent to `α`. -/ noncomputable def equivAsType : AsType α ≌ α := (asTypeEquivObjAsType α).trans (objAsTypeEquiv α) end FinCategory end CategoryTheory
Basic.lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz, Yongle Hu, Jingting Wang -/ import Mathlib.FieldTheory.Fixed import Mathlib.FieldTheory.Normal.Closure import Mathlib.FieldTheory.PrimitiveElement import Mathlib.GroupTheory.GroupAction.FixingSubgroup /-! # Galois Extensions In this file we define Galois extensions as extensions which are both separable and normal. ## Main definitions - `IsGalois F E` where `E` is an extension of `F` - `fixedField H` where `H : Subgroup (E ≃ₐ[F] E)` - `fixingSubgroup K` where `K : IntermediateField F E` - `intermediateFieldEquivSubgroup` where `E/F` is finite dimensional and Galois ## Main results - `IntermediateField.fixingSubgroup_fixedField` : If `E/F` is finite dimensional (but not necessarily Galois) then `fixingSubgroup (fixedField H) = H` - `IsGalois.fixedField_fixingSubgroup`: If `E/F` is finite dimensional and Galois then `fixedField (fixingSubgroup K) = K` Together, these two results prove the Galois correspondence. - `IsGalois.tfae` : Equivalent characterizations of a Galois extension of finite degree ## Additional results - Instances for `Algebra.IsQuadraticExtension`: a quadratic extension is Galois (if separable) with cyclic and thus abelian Galois group. -/ open scoped Polynomial IntermediateField open Module AlgEquiv IntermediateField section variable (F : Type*) [Field F] (E : Type*) [Field E] [Algebra F E] /-- A field extension E/F is Galois if it is both separable and normal. Note that in mathlib a separable extension of fields is by definition algebraic. -/ @[stacks 09I0] class IsGalois : Prop where [to_isSeparable : Algebra.IsSeparable F E] [to_normal : Normal F E] variable {F E} theorem isGalois_iff : IsGalois F E ↔ Algebra.IsSeparable F E ∧ Normal F E := ⟨fun h => ⟨h.1, h.2⟩, fun h => { to_isSeparable := h.1 to_normal := h.2 }⟩ attribute [instance 100] IsGalois.to_isSeparable IsGalois.to_normal -- see Note [lower instance priority] variable (F E) namespace IsGalois instance self : IsGalois F F := ⟨⟩ variable {E} theorem integral [IsGalois F E] (x : E) : IsIntegral F x := to_normal.isIntegral x theorem separable [IsGalois F E] (x : E) : IsSeparable F x := Algebra.IsSeparable.isSeparable F x theorem splits [IsGalois F E] (x : E) : (minpoly F x).Splits (algebraMap F E) := Normal.splits' x variable (E) /-- Let $E$ be a field. Let $G$ be a finite group acting on $E$. Then the extension $E / E^G$ is Galois. -/ @[stacks 09I3 "first part"] instance of_fixed_field (G : Type*) [Group G] [Finite G] [MulSemiringAction G E] : IsGalois (FixedPoints.subfield G E) E := ⟨⟩ theorem IntermediateField.AdjoinSimple.card_aut_eq_finrank [FiniteDimensional F E] {α : E} (hα : IsIntegral F α) (h_sep : IsSeparable F α) (h_splits : (minpoly F α).Splits (algebraMap F F⟮α⟯)) : Nat.card (F⟮α⟯ ≃ₐ[F] F⟮α⟯) = finrank F F⟮α⟯ := by rw [IntermediateField.adjoin.finrank hα] rw [← IntermediateField.card_algHom_adjoin_integral F hα h_sep h_splits] exact Nat.card_congr (algEquivEquivAlgHom F F⟮α⟯) /-- Let $E / F$ be a finite extension of fields. If $E$ is Galois over $F$, then $|\text{Aut}(E/F)| = [E : F]$. -/ @[stacks 09I1 "'only if' part"] theorem card_aut_eq_finrank [FiniteDimensional F E] [IsGalois F E] : Nat.card (E ≃ₐ[F] E) = finrank F E := by obtain ⟨α, hα⟩ := Field.exists_primitive_element F E let iso : F⟮α⟯ ≃ₐ[F] E := { toFun := fun e => e.val invFun := fun e => ⟨e, by rw [hα]; exact IntermediateField.mem_top⟩ map_mul' := fun _ _ => rfl map_add' := fun _ _ => rfl commutes' := fun _ => rfl } have H : IsIntegral F α := IsGalois.integral F α have h_sep : IsSeparable F α := IsGalois.separable F α have h_splits : (minpoly F α).Splits (algebraMap F E) := IsGalois.splits F α replace h_splits : Polynomial.Splits (algebraMap F F⟮α⟯) (minpoly F α) := by simpa using Polynomial.splits_comp_of_splits (algebraMap F E) iso.symm.toAlgHom.toRingHom h_splits rw [← LinearEquiv.finrank_eq iso.toLinearEquiv] rw [← IntermediateField.AdjoinSimple.card_aut_eq_finrank F E H h_sep h_splits] apply Nat.card_congr exact Equiv.mk (fun ϕ => iso.trans (ϕ.trans iso.symm)) fun ϕ => iso.symm.trans (ϕ.trans iso) end IsGalois end section IsGaloisTower variable (F K E : Type*) [Field F] [Field K] [Field E] {E' : Type*} [Field E'] [Algebra F E'] variable [Algebra F K] [Algebra F E] [Algebra K E] [IsScalarTower F K E] /-- Let $E / K / F$ be a tower of field extensions. If $E$ is Galois over $F$, then $E$ is Galois over $K$. -/ @[stacks 09I2] theorem IsGalois.tower_top_of_isGalois [IsGalois F E] : IsGalois K E := { to_isSeparable := Algebra.isSeparable_tower_top_of_isSeparable F K E to_normal := Normal.tower_top_of_normal F K E } variable {F E} -- see Note [lower instance priority] instance (priority := 100) IsGalois.tower_top_intermediateField (K : IntermediateField F E) [IsGalois F E] : IsGalois K E := IsGalois.tower_top_of_isGalois F K E theorem isGalois_iff_isGalois_bot : IsGalois (⊥ : IntermediateField F E) E ↔ IsGalois F E := by constructor · intro h exact IsGalois.tower_top_of_isGalois (⊥ : IntermediateField F E) F E · intro h; infer_instance theorem IsGalois.of_algEquiv [IsGalois F E] (f : E ≃ₐ[F] E') : IsGalois F E' := { to_isSeparable := Algebra.IsSeparable.of_algHom F E f.symm to_normal := Normal.of_algEquiv f } theorem AlgEquiv.transfer_galois (f : E ≃ₐ[F] E') : IsGalois F E ↔ IsGalois F E' := ⟨fun _ => IsGalois.of_algEquiv f, fun _ => IsGalois.of_algEquiv f.symm⟩ theorem isGalois_iff_isGalois_top : IsGalois F (⊤ : IntermediateField F E) ↔ IsGalois F E := (IntermediateField.topEquiv : (⊤ : IntermediateField F E) ≃ₐ[F] E).transfer_galois instance isGalois_bot : IsGalois F (⊥ : IntermediateField F E) := (IntermediateField.botEquiv F E).transfer_galois.mpr (IsGalois.self F) theorem IsGalois.of_equiv_equiv {M N : Type*} [Field N] [Field M] [Algebra M N] [Algebra.IsAlgebraic F E] [h : IsGalois F E] {f : F ≃+* M} {g : E ≃+* N} (hcomp : (algebraMap M N).comp f = (g : E →+* N).comp (algebraMap F E)) : IsGalois M N := isGalois_iff.mpr ⟨Algebra.IsSeparable.of_equiv_equiv f g hcomp, Normal.of_equiv_equiv hcomp⟩ end IsGaloisTower section GaloisCorrespondence variable {F : Type*} [Field F] {E : Type*} [Field E] [Algebra F E] variable (H : Subgroup (E ≃ₐ[F] E)) (K : IntermediateField F E) /-- The intermediate field of fixed points fixed by a monoid action that commutes with the `F`-action on `E`. -/ def FixedPoints.intermediateField (M : Type*) [Monoid M] [MulSemiringAction M E] [SMulCommClass M F E] : IntermediateField F E := { FixedPoints.subfield M E with carrier := MulAction.fixedPoints M E algebraMap_mem' := fun a g => smul_algebraMap g a } namespace IntermediateField /-- The intermediate field fixed by a subgroup. -/ def fixedField : IntermediateField F E := FixedPoints.intermediateField H @[simp] lemma mem_fixedField_iff (x) : x ∈ fixedField H ↔ ∀ f ∈ H, f x = x := by change x ∈ MulAction.fixedPoints H E ↔ _ simp only [MulAction.mem_fixedPoints, Subtype.forall, Subgroup.mk_smul, AlgEquiv.smul_def] @[simp] lemma fixedField_bot : fixedField (⊥ : Subgroup (E ≃ₐ[F] E)) = ⊤ := by ext simp theorem finrank_fixedField_eq_card [FiniteDimensional F E] : finrank (fixedField H) E = Nat.card H := by have := Fintype.ofFinite H rw [Nat.card_eq_fintype_card] exact FixedPoints.finrank_eq_card H E /-- The subgroup fixing an intermediate field. -/ nonrec def fixingSubgroup : Subgroup (E ≃ₐ[F] E) := fixingSubgroup (E ≃ₐ[F] E) (K : Set E) theorem le_iff_le : K ≤ fixedField H ↔ H ≤ fixingSubgroup K := ⟨fun h g hg x => h (Subtype.mem x) ⟨g, hg⟩, fun h x hx g => h (Subtype.mem g) ⟨x, hx⟩⟩ /-- The map `K ↦ Gal(E/K)` is inclusion-reversing. -/ theorem fixingSubgroup_le {K1 K2 : IntermediateField F E} (h12 : K1 ≤ K2) : K2.fixingSubgroup ≤ K1.fixingSubgroup := fun _ hσ ⟨x, hx⟩ ↦ hσ ⟨x, h12 hx⟩ @[deprecated (since := "2025-05-02")] alias fixingSubgroup.antimono := fixingSubgroup_le theorem fixedField_le {H1 H2 : Subgroup (E ≃ₐ[F] E)} (h12 : H1 ≤ H2) : fixedField H2 ≤ fixedField H1 := fun _ hσ ⟨x, hx⟩ ↦ hσ ⟨x, h12 hx⟩ lemma fixingSubgroup_antitone : Antitone (@fixingSubgroup F _ E _ _) := fun _ _ ↦ fixingSubgroup_le @[deprecated (since := "2025-05-02")] alias fixingSubgroup_anti := fixingSubgroup_antitone lemma fixedField_antitone : Antitone (@fixedField F _ E _ _) := fun _ _ ↦ fixedField_le @[simp] lemma mem_fixingSubgroup_iff (σ) : σ ∈ fixingSubgroup K ↔ ∀ x ∈ K, σ x = x := _root_.mem_fixingSubgroup_iff _ @[simp] lemma fixingSubgroup_top : fixingSubgroup (⊤ : IntermediateField F E) = ⊥ := by ext simp [DFunLike.ext_iff] @[simp] lemma fixingSubgroup_bot : fixingSubgroup (⊥ : IntermediateField F E) = ⊤ := by ext simp [mem_bot] /-- The fixing subgroup of `K : IntermediateField F E` is isomorphic to `E ≃ₐ[K] E`. -/ def fixingSubgroupEquiv : fixingSubgroup K ≃* E ≃ₐ[K] E where toFun ϕ := { AlgEquiv.toRingEquiv (ϕ : E ≃ₐ[F] E) with commutes' := ϕ.mem } invFun ϕ := ⟨ϕ.restrictScalars _, ϕ.commutes⟩ map_mul' _ _ := by ext; rfl theorem fixingSubgroup_fixedField [FiniteDimensional F E] : fixingSubgroup (fixedField H) = H := by have H_le : H ≤ fixingSubgroup (fixedField H) := (le_iff_le _ _).mp le_rfl classical suffices Nat.card H = Nat.card (fixingSubgroup (fixedField H)) by exact SetLike.coe_injective (Set.eq_of_inclusion_surjective ((Nat.bijective_iff_injective_and_card (Set.inclusion H_le)).mpr ⟨Set.inclusion_injective H_le, this⟩).2).symm apply Nat.card_congr refine (FixedPoints.toAlgHomEquiv H E).trans ?_ refine (algEquivEquivAlgHom (fixedField H) E).toEquiv.symm.trans ?_ exact (fixingSubgroupEquiv (fixedField H)).toEquiv.symm /-- A subgroup is isomorphic to the Galois group of its fixed field. -/ def subgroupEquivAlgEquiv [FiniteDimensional F E] (H : Subgroup (E ≃ₐ[F] E)) : H ≃* E ≃ₐ[IntermediateField.fixedField H] E := (MulEquiv.subgroupCongr (fixingSubgroup_fixedField H).symm).trans (fixingSubgroupEquiv _) instance fixedField.smul : SMul K (fixedField (fixingSubgroup K)) where smul x y := ⟨x * y, fun ϕ => by rw [smul_mul', show ϕ • (x : E) = ↑x from ϕ.2 x, show ϕ • (y : E) = ↑y from y.2 ϕ]⟩ instance fixedField.algebra : Algebra K (fixedField (fixingSubgroup K)) where algebraMap := { toFun x := ⟨x, fun ϕ => Subtype.mem ϕ x⟩ map_zero' := rfl map_add' _ _ := rfl map_one' := rfl map_mul' _ _ := rfl } commutes' _ _ := mul_comm _ _ smul_def' _ _ := rfl instance fixedField.isScalarTower : IsScalarTower K (fixedField (fixingSubgroup K)) E := ⟨fun _ _ _ => mul_assoc _ _ _⟩ end IntermediateField namespace IsGalois theorem fixedField_fixingSubgroup [FiniteDimensional F E] [h : IsGalois F E] : IntermediateField.fixedField (IntermediateField.fixingSubgroup K) = K := by have K_le : K ≤ IntermediateField.fixedField (IntermediateField.fixingSubgroup K) := (IntermediateField.le_iff_le _ _).mpr le_rfl suffices finrank K E = finrank (IntermediateField.fixedField (IntermediateField.fixingSubgroup K)) E by exact (IntermediateField.eq_of_le_of_finrank_eq' K_le this).symm classical rw [IntermediateField.finrank_fixedField_eq_card, Nat.card_congr (IntermediateField.fixingSubgroupEquiv K).toEquiv] exact (card_aut_eq_finrank K E).symm @[simp] lemma fixedField_top [IsGalois F E] [FiniteDimensional F E] : fixedField (⊤ : Subgroup (E ≃ₐ[F] E)) = ⊥ := by rw [← fixingSubgroup_bot, fixedField_fixingSubgroup] theorem mem_bot_iff_fixed [IsGalois F E] [FiniteDimensional F E] (x : E) : x ∈ (⊥ : IntermediateField F E) ↔ ∀ f : E ≃ₐ[F] E, f x = x := by rw [← fixedField_top, mem_fixedField_iff] simp only [Subgroup.mem_top, forall_const] theorem mem_range_algebraMap_iff_fixed [IsGalois F E] [FiniteDimensional F E] (x : E) : x ∈ Set.range (algebraMap F E) ↔ ∀ f : E ≃ₐ[F] E, f x = x := mem_bot_iff_fixed x theorem card_fixingSubgroup_eq_finrank [FiniteDimensional F E] [IsGalois F E] : Nat.card (IntermediateField.fixingSubgroup K) = finrank K E := by conv_rhs => rw [← fixedField_fixingSubgroup K, IntermediateField.finrank_fixedField_eq_card] /-- The Galois correspondence from intermediate fields to subgroups. -/ @[stacks 09DW] def intermediateFieldEquivSubgroup [FiniteDimensional F E] [IsGalois F E] : IntermediateField F E ≃o (Subgroup (E ≃ₐ[F] E))ᵒᵈ where toFun := IntermediateField.fixingSubgroup invFun := IntermediateField.fixedField left_inv K := fixedField_fixingSubgroup K right_inv H := IntermediateField.fixingSubgroup_fixedField H map_rel_iff' {K L} := by rw [← fixedField_fixingSubgroup L, IntermediateField.le_iff_le, fixedField_fixingSubgroup L] rfl /-- The Galois correspondence as a `GaloisInsertion`. -/ def galoisInsertionIntermediateFieldSubgroup [FiniteDimensional F E] : GaloisInsertion (OrderDual.toDual ∘ (IntermediateField.fixingSubgroup : IntermediateField F E → Subgroup (E ≃ₐ[F] E))) ((IntermediateField.fixedField : Subgroup (E ≃ₐ[F] E) → IntermediateField F E) ∘ OrderDual.toDual) where choice K _ := IntermediateField.fixingSubgroup K gc K H := (IntermediateField.le_iff_le H K).symm le_l_u H := le_of_eq (IntermediateField.fixingSubgroup_fixedField H).symm choice_eq _ _ := rfl /-- The Galois correspondence as a `GaloisCoinsertion`. -/ def galoisCoinsertionIntermediateFieldSubgroup [FiniteDimensional F E] [IsGalois F E] : GaloisCoinsertion (OrderDual.toDual ∘ (IntermediateField.fixingSubgroup : IntermediateField F E → Subgroup (E ≃ₐ[F] E))) ((IntermediateField.fixedField : Subgroup (E ≃ₐ[F] E) → IntermediateField F E) ∘ OrderDual.toDual) := OrderIso.toGaloisCoinsertion intermediateFieldEquivSubgroup end IsGalois section /-In this section we prove that the normal subgroups correspond to the Galois subextensions in the Galois correspondence and its related results. -/ variable {K L : Type*} [Field K] [Field L] [Algebra K L] open IntermediateField open scoped Pointwise lemma IntermediateField.restrictNormalHom_ker (E : IntermediateField K L) [Normal K E] : (restrictNormalHom E).ker = E.fixingSubgroup := by simp only [Subgroup.ext_iff, MonoidHom.mem_ker, AlgEquiv.ext_iff, one_apply, Subtype.ext_iff, restrictNormalHom_apply, Subtype.forall, mem_fixingSubgroup_iff, implies_true] namespace IsGalois variable (E : IntermediateField K L) /-- If `H` is a normal Subgroup of `Gal(L / K)`, then `fixedField H` is Galois over `K`. -/ instance of_fixedField_normal_subgroup [IsGalois K L] (H : Subgroup (L ≃ₐ[K] L)) [hn : Subgroup.Normal H] : IsGalois K (fixedField H) where to_isSeparable := Algebra.isSeparable_tower_bot_of_isSeparable K (fixedField H) L to_normal := by apply normal_iff_forall_map_le'.mpr rintro σ x ⟨a, ha, rfl⟩ τ exact (symm_apply_eq σ).mp (ha ⟨σ⁻¹ * τ * σ, Subgroup.Normal.conj_mem' hn τ.1 τ.2 σ⟩) /-- If `H` is a normal Subgroup of `Gal(L / K)`, then `Gal(fixedField H / K)` is isomorphic to `Gal(L / K) ⧸ H`. -/ noncomputable def normalAutEquivQuotient [FiniteDimensional K L] [IsGalois K L] (H : Subgroup (L ≃ₐ[K] L)) [Subgroup.Normal H] : (L ≃ₐ[K] L) ⧸ H ≃* ((fixedField H) ≃ₐ[K] (fixedField H)) := (QuotientGroup.quotientMulEquivOfEq ((fixingSubgroup_fixedField H).symm.trans (fixedField H).restrictNormalHom_ker.symm)).trans <| QuotientGroup.quotientKerEquivOfSurjective (restrictNormalHom (fixedField H)) <| restrictNormalHom_surjective L lemma normalAutEquivQuotient_apply [FiniteDimensional K L] [IsGalois K L] (H : Subgroup (L ≃ₐ[K] L)) [Subgroup.Normal H] (σ : (L ≃ₐ[K] L)) : normalAutEquivQuotient H σ = (restrictNormalHom (fixedField H)) σ := rfl open scoped Pointwise @[simp] theorem map_fixingSubgroup (σ : L ≃ₐ[K] L) : (E.map σ).fixingSubgroup = (MulAut.conj σ) • E.fixingSubgroup := by ext τ simp only [coe_map, AlgHom.coe_coe, Set.mem_image, SetLike.mem_coe, AlgEquiv.smul_def, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, Subgroup.mem_pointwise_smul_iff_inv_smul_mem, ← symm_apply_eq, IntermediateField.fixingSubgroup, mem_fixingSubgroup_iff] rfl /-- Let `E` be an intermediateField of a Galois extension `L / K`. If `E / K` is Galois extension, then `E.fixingSubgroup` is a normal subgroup of `Gal(L / K)`. -/ instance fixingSubgroup_normal_of_isGalois [IsGalois K L] [IsGalois K E] : E.fixingSubgroup.Normal := by apply Subgroup.Normal.of_conjugate_fixed (fun σ ↦ ?_) rw [← map_fixingSubgroup, normal_iff_forall_map_eq'.mp inferInstance σ] end IsGalois end end GaloisCorrespondence section GaloisEquivalentDefinitions variable (F : Type*) [Field F] (E : Type*) [Field E] [Algebra F E] namespace IsGalois theorem is_separable_splitting_field [FiniteDimensional F E] [IsGalois F E] : ∃ p : F[X], p.Separable ∧ p.IsSplittingField F E := by obtain ⟨α, h1⟩ := Field.exists_primitive_element F E use minpoly F α, separable F α, IsGalois.splits F α rw [eq_top_iff, ← IntermediateField.top_toSubalgebra, ← h1] rw [IntermediateField.adjoin_simple_toSubalgebra_of_integral (integral F α)] apply Algebra.adjoin_mono rw [Set.singleton_subset_iff, Polynomial.mem_rootSet] exact ⟨minpoly.ne_zero (integral F α), minpoly.aeval _ _⟩ theorem of_fixedField_eq_bot [FiniteDimensional F E] (h : IntermediateField.fixedField (⊤ : Subgroup (E ≃ₐ[F] E)) = ⊥) : IsGalois F E := by rw [← isGalois_iff_isGalois_bot, ← h] classical exact IsGalois.of_fixed_field E (⊤ : Subgroup (E ≃ₐ[F] E)) /-- Let $E / F$ be a finite extension of fields. If $|\text{Aut}(E/F)| = [E : F]$, then $E$ is Galois over $F$. -/ @[stacks 09I1 "'if' part"] theorem of_card_aut_eq_finrank [FiniteDimensional F E] (h : Nat.card (E ≃ₐ[F] E) = finrank F E) : IsGalois F E := by apply of_fixedField_eq_bot have p : 0 < finrank (IntermediateField.fixedField (⊤ : Subgroup (E ≃ₐ[F] E))) E := finrank_pos classical rw [← IntermediateField.finrank_eq_one_iff, ← mul_left_inj' (ne_of_lt p).symm, finrank_mul_finrank, ← h, one_mul, IntermediateField.finrank_fixedField_eq_card] apply Nat.card_congr exact { toFun := fun g => ⟨g, Subgroup.mem_top g⟩, invFun := (↑) } variable {F} {E} variable {p : F[X]} theorem of_separable_splitting_field_aux [hFE : FiniteDimensional F E] [sp : p.IsSplittingField F E] (hp : p.Separable) (K : Type*) [Field K] [Algebra F K] [Algebra K E] [IsScalarTower F K E] {x : E} (hx : x ∈ p.aroots E) : Nat.card (K⟮x⟯.restrictScalars F →ₐ[F] E) = Nat.card (K →ₐ[F] E) * finrank K K⟮x⟯ := by have h : IsIntegral K x := (isIntegral_of_noetherian (IsNoetherian.iff_fg.2 hFE) x).tower_top have h1 : p ≠ 0 := fun hp => by rw [hp, Polynomial.aroots_zero] at hx exact Multiset.notMem_zero x hx have h2 : minpoly K x ∣ p.map (algebraMap F K) := by apply minpoly.dvd rw [Polynomial.aeval_def, Polynomial.eval₂_map, ← Polynomial.eval_map, ← IsScalarTower.algebraMap_eq] exact (Polynomial.mem_roots (Polynomial.map_ne_zero h1)).mp hx let key_equiv : (K⟮x⟯.restrictScalars F →ₐ[F] E) ≃ Σ f : K →ₐ[F] E, @AlgHom K K⟮x⟯ E _ _ _ _ (RingHom.toAlgebra f) := by change (K⟮x⟯ →ₐ[F] E) ≃ Σ f : K →ₐ[F] E, _ exact algHomEquivSigma haveI : ∀ f : K →ₐ[F] E, Finite (@AlgHom K K⟮x⟯ E _ _ _ _ (RingHom.toAlgebra f)) := fun f => by have := Finite.of_equiv _ key_equiv apply Finite.of_injective (Sigma.mk f) fun _ _ H => eq_of_heq (Sigma.ext_iff.mp H).2 have : FiniteDimensional F K := FiniteDimensional.left F K E rw [Nat.card_congr key_equiv, Nat.card_sigma, IntermediateField.adjoin.finrank h, Nat.card_eq_fintype_card] apply Finset.sum_const_nat intro f _ rw [← @IntermediateField.card_algHom_adjoin_integral K _ E _ _ x E _ (RingHom.toAlgebra f) h] · exact Polynomial.Separable.of_dvd ((Polynomial.separable_map (algebraMap F K)).mpr hp) h2 · refine Polynomial.splits_of_splits_of_dvd _ (Polynomial.map_ne_zero h1) ?_ h2 -- Porting note: use unification instead of synthesis for one argument of `algebraMap_eq` rw [Polynomial.splits_map_iff, ← @IsScalarTower.algebraMap_eq _ _ _ _ _ _ _ (_) _ _] exact sp.splits theorem of_separable_splitting_field [sp : p.IsSplittingField F E] (hp : p.Separable) : IsGalois F E := by haveI hFE : FiniteDimensional F E := Polynomial.IsSplittingField.finiteDimensional E p letI := Classical.decEq E let s := p.rootSet E have adjoin_root : IntermediateField.adjoin F s = ⊤ := by apply IntermediateField.toSubalgebra_injective rw [IntermediateField.top_toSubalgebra, ← top_le_iff, ← sp.adjoin_rootSet] apply IntermediateField.algebra_adjoin_le_adjoin let P : IntermediateField F E → Prop := fun K => Nat.card (K →ₐ[F] E) = finrank F K suffices P (IntermediateField.adjoin F s) by rw [adjoin_root] at this apply of_card_aut_eq_finrank rw [← Eq.trans this (LinearEquiv.finrank_eq IntermediateField.topEquiv.toLinearEquiv)] exact Nat.card_congr ((algEquivEquivAlgHom F E).toEquiv.trans (IntermediateField.topEquiv.symm.arrowCongr AlgEquiv.refl)) apply IntermediateField.induction_on_adjoin_finset _ P · have key := IntermediateField.card_algHom_adjoin_integral F (K := E) (show IsIntegral F (0 : E) from isIntegral_zero) rw [IsSeparable, minpoly.zero, Polynomial.natDegree_X] at key specialize key Polynomial.separable_X (Polynomial.splits_X (algebraMap F E)) rw [← @Subalgebra.finrank_bot F E _ _ _, ← IntermediateField.bot_toSubalgebra] at key refine Eq.trans ?_ key apply Nat.card_congr rw [IntermediateField.adjoin_zero] intro K x hx hK simp only [P] at * rw [of_separable_splitting_field_aux hp K (Multiset.mem_toFinset.mp hx), hK, finrank_mul_finrank] symm refine LinearEquiv.finrank_eq ?_ rfl /-- Equivalent characterizations of a Galois extension of finite degree. -/ theorem tfae [FiniteDimensional F E] : List.TFAE [ IsGalois F E, IntermediateField.fixedField (⊤ : Subgroup (E ≃ₐ[F] E)) = ⊥, Nat.card (E ≃ₐ[F] E) = finrank F E, ∃ p : F[X], p.Separable ∧ p.IsSplittingField F E] := by tfae_have 1 → 2 := fun h ↦ OrderIso.map_bot (@intermediateFieldEquivSubgroup F _ E _ _ _ h).symm tfae_have 1 → 3 := fun _ ↦ card_aut_eq_finrank F E tfae_have 1 → 4 := fun _ ↦ is_separable_splitting_field F E tfae_have 2 → 1 := of_fixedField_eq_bot F E tfae_have 3 → 1 := of_card_aut_eq_finrank F E tfae_have 4 → 1 := fun ⟨h, hp1, _⟩ ↦ of_separable_splitting_field hp1 tfae_finish end IsGalois end GaloisEquivalentDefinitions section normalClosure variable (k K F : Type*) [Field k] [Field K] [Field F] [Algebra k K] [Algebra k F] [Algebra K F] [IsScalarTower k K F] [IsGalois k F] /-- Let $F / K / k$ be a tower of field extensions. If $F$ is Galois over $k$, then the normal closure of $K$ over $k$ in $F$ is Galois over $k$. -/ @[stacks 0EXM] instance IsGalois.normalClosure : IsGalois k (normalClosure k K F) where to_isSeparable := Algebra.isSeparable_tower_bot_of_isSeparable k _ F end normalClosure section IsAlgClosure instance (priority := 100) IsAlgClosure.isGalois (k K : Type*) [Field k] [Field K] [Algebra k K] [IsAlgClosure k K] [CharZero k] : IsGalois k K where end IsAlgClosure namespace Algebra variable (F K : Type*) [Field F] [Field K] [Algebra F K] [IsQuadraticExtension F K] /-- A quadratic separable extension is Galois. -/ instance IsQuadraticExtension.isGalois [Algebra.IsSeparable F K] : IsGalois F K where /-- A quadratic extension has cyclic Galois group. -/ instance IsQuadraticExtension.isCyclic : IsCyclic (K ≃ₐ[F] K) := by have := finrank_eq_two F K ▸ AlgEquiv.card_le rw [← Nat.card_eq_fintype_card] at this interval_cases h : Nat.card (K ≃ₐ[F] K) · simp_all · exact @isCyclic_of_subsingleton _ _ (Finite.card_le_one_iff_subsingleton.mp h.le) · exact isCyclic_of_prime_card h /-- A quadratic extension has abelian Galois group. -/ instance IsQuadraticExtension.isMulCommutative_galoisGroup : IsMulCommutative (K ≃ₐ[F] K) := ⟨IsCyclic.commutative⟩ end Algebra
AllAny.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Batteries.Tactic.Alias import Mathlib.Tactic.TypeStar /-! # Boolean quantifiers This proves a few properties about `List.all` and `List.any`, which are the `Bool` universal and existential quantifiers. Their definitions are in core Lean. -/ variable {α : Type*} {p : α → Prop} [DecidablePred p] {l : List α} {a : α} namespace List theorem all_iff_forall_prop : (all l fun a => p a) ↔ ∀ a ∈ l, p a := by simp theorem any_iff_exists_prop : (any l fun a => p a) ↔ ∃ a ∈ l, p a := by simp theorem any_of_mem {p : α → Bool} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_eq_true.2 ⟨_, h₁, h₂⟩ end List
Path.lean
/- Copyright (c) 2021 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import Mathlib.Topology.Homotopy.Basic import Mathlib.Topology.Connected.PathConnected import Mathlib.Analysis.Convex.Basic /-! # Homotopy between paths In this file, we define a `Homotopy` between two `Path`s. In addition, we define a relation `Homotopic` on `Path`s, and prove that it is an equivalence relation. ## Definitions * `Path.Homotopy p₀ p₁` is the type of homotopies between paths `p₀` and `p₁` * `Path.Homotopy.refl p` is the constant homotopy between `p` and itself * `Path.Homotopy.symm F` is the `Path.Homotopy p₁ p₀` defined by reversing the homotopy * `Path.Homotopy.trans F G`, where `F : Path.Homotopy p₀ p₁`, `G : Path.Homotopy p₁ p₂` is the `Path.Homotopy p₀ p₂` defined by putting the first homotopy on `[0, 1/2]` and the second on `[1/2, 1]` * `Path.Homotopy.hcomp F G`, where `F : Path.Homotopy p₀ q₀` and `G : Path.Homotopy p₁ q₁` is a `Path.Homotopy (p₀.trans p₁) (q₀.trans q₁)` * `Path.Homotopic p₀ p₁` is the relation saying that there is a homotopy between `p₀` and `p₁` * `Path.Homotopic.setoid x₀ x₁` is the setoid on `Path`s from `Path.Homotopic` * `Path.Homotopic.Quotient x₀ x₁` is the quotient type from `Path x₀ x₀` by `Path.Homotopic.setoid` -/ universe u v variable {X : Type u} {Y : Type v} [TopologicalSpace X] [TopologicalSpace Y] variable {x₀ x₁ x₂ x₃ : X} noncomputable section open unitInterval namespace Path /-- The type of homotopies between two paths. -/ abbrev Homotopy (p₀ p₁ : Path x₀ x₁) := ContinuousMap.HomotopyRel p₀.toContinuousMap p₁.toContinuousMap {0, 1} namespace Homotopy section variable {p₀ p₁ : Path x₀ x₁} theorem coeFn_injective : @Function.Injective (Homotopy p₀ p₁) (I × I → X) (⇑) := DFunLike.coe_injective @[simp] theorem source (F : Homotopy p₀ p₁) (t : I) : F (t, 0) = x₀ := calc F (t, 0) = p₀ 0 := ContinuousMap.HomotopyRel.eq_fst _ _ (.inl rfl) _ = x₀ := p₀.source @[simp] theorem target (F : Homotopy p₀ p₁) (t : I) : F (t, 1) = x₁ := calc F (t, 1) = p₀ 1 := ContinuousMap.HomotopyRel.eq_fst _ _ (.inr rfl) _ = x₁ := p₀.target /-- Evaluating a path homotopy at an intermediate point, giving us a `Path`. -/ def eval (F : Homotopy p₀ p₁) (t : I) : Path x₀ x₁ where toFun := F.toHomotopy.curry t source' := by simp target' := by simp @[simp] theorem eval_zero (F : Homotopy p₀ p₁) : F.eval 0 = p₀ := by ext t simp [eval] @[simp] theorem eval_one (F : Homotopy p₀ p₁) : F.eval 1 = p₁ := by ext t simp [eval] end section variable {p₀ p₁ p₂ : Path x₀ x₁} /-- Given a path `p`, we can define a `Homotopy p p` by `F (t, x) = p x`. -/ @[simps!] def refl (p : Path x₀ x₁) : Homotopy p p := ContinuousMap.HomotopyRel.refl p.toContinuousMap {0, 1} /-- Given a `Homotopy p₀ p₁`, we can define a `Homotopy p₁ p₀` by reversing the homotopy. -/ @[simps!] def symm (F : Homotopy p₀ p₁) : Homotopy p₁ p₀ := ContinuousMap.HomotopyRel.symm F @[simp] theorem symm_symm (F : Homotopy p₀ p₁) : F.symm.symm = F := ContinuousMap.HomotopyRel.symm_symm F theorem symm_bijective : Function.Bijective (Homotopy.symm : Homotopy p₀ p₁ → Homotopy p₁ p₀) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ /-- Given `Homotopy p₀ p₁` and `Homotopy p₁ p₂`, we can define a `Homotopy p₀ p₂` by putting the first homotopy on `[0, 1/2]` and the second on `[1/2, 1]`. -/ def trans (F : Homotopy p₀ p₁) (G : Homotopy p₁ p₂) : Homotopy p₀ p₂ := ContinuousMap.HomotopyRel.trans F G theorem trans_apply (F : Homotopy p₀ p₁) (G : Homotopy p₁ p₂) (x : I × I) : (F.trans G) x = if h : (x.1 : ℝ) ≤ 1 / 2 then F (⟨2 * x.1, (unitInterval.mul_pos_mem_iff zero_lt_two).2 ⟨x.1.2.1, h⟩⟩, x.2) else G (⟨2 * x.1 - 1, unitInterval.two_mul_sub_one_mem_iff.2 ⟨(not_le.1 h).le, x.1.2.2⟩⟩, x.2) := ContinuousMap.HomotopyRel.trans_apply _ _ _ theorem symm_trans (F : Homotopy p₀ p₁) (G : Homotopy p₁ p₂) : (F.trans G).symm = G.symm.trans F.symm := ContinuousMap.HomotopyRel.symm_trans _ _ /-- Casting a `Homotopy p₀ p₁` to a `Homotopy q₀ q₁` where `p₀ = q₀` and `p₁ = q₁`. -/ @[simps!] def cast {p₀ p₁ q₀ q₁ : Path x₀ x₁} (F : Homotopy p₀ p₁) (h₀ : p₀ = q₀) (h₁ : p₁ = q₁) : Homotopy q₀ q₁ := ContinuousMap.HomotopyRel.cast F (congr_arg _ h₀) (congr_arg _ h₁) end section variable {p₀ q₀ : Path x₀ x₁} {p₁ q₁ : Path x₁ x₂} /-- Suppose `p₀` and `q₀` are paths from `x₀` to `x₁`, `p₁` and `q₁` are paths from `x₁` to `x₂`. Furthermore, suppose `F : Homotopy p₀ q₀` and `G : Homotopy p₁ q₁`. Then we can define a homotopy from `p₀.trans p₁` to `q₀.trans q₁`. -/ def hcomp (F : Homotopy p₀ q₀) (G : Homotopy p₁ q₁) : Homotopy (p₀.trans p₁) (q₀.trans q₁) where toFun x := if (x.2 : ℝ) ≤ 1 / 2 then (F.eval x.1).extend (2 * x.2) else (G.eval x.1).extend (2 * x.2 - 1) continuous_toFun := continuous_if_le (continuous_induced_dom.comp continuous_snd) continuous_const (F.toHomotopy.continuous.comp (by continuity)).continuousOn (G.toHomotopy.continuous.comp (by continuity)).continuousOn fun x hx => by norm_num [hx] map_zero_left x := by simp [Path.trans] map_one_left x := by simp [Path.trans] prop' x t ht := by rcases ht with ht | ht · norm_num [ht] · rw [Set.mem_singleton_iff] at ht norm_num [ht] theorem hcomp_apply (F : Homotopy p₀ q₀) (G : Homotopy p₁ q₁) (x : I × I) : F.hcomp G x = if h : (x.2 : ℝ) ≤ 1 / 2 then F.eval x.1 ⟨2 * x.2, (unitInterval.mul_pos_mem_iff zero_lt_two).2 ⟨x.2.2.1, h⟩⟩ else G.eval x.1 ⟨2 * x.2 - 1, unitInterval.two_mul_sub_one_mem_iff.2 ⟨(not_le.1 h).le, x.2.2.2⟩⟩ := show ite _ _ _ = _ by split_ifs <;> exact Path.extend_extends _ _ theorem hcomp_half (F : Homotopy p₀ q₀) (G : Homotopy p₁ q₁) (t : I) : F.hcomp G (t, ⟨1 / 2, by norm_num, by norm_num⟩) = x₁ := show ite _ _ _ = _ by norm_num end /-- Suppose `p` is a path, then we have a homotopy from `p` to `p.reparam f` by the convexity of `I`. -/ def reparam (p : Path x₀ x₁) (f : I → I) (hf : Continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) : Homotopy p (p.reparam f hf hf₀ hf₁) where toFun x := p ⟨σ x.1 * x.2 + x.1 * f x.2, show (σ x.1 : ℝ) • (x.2 : ℝ) + (x.1 : ℝ) • (f x.2 : ℝ) ∈ I from convex_Icc _ _ x.2.2 (f x.2).2 (by unit_interval) (by unit_interval) (by simp)⟩ map_zero_left x := by norm_num map_one_left x := by norm_num prop' t x hx := by rcases hx with hx | hx · rw [hx] simp [hf₀] · rw [Set.mem_singleton_iff] at hx rw [hx] simp [hf₁] continuous_toFun := by fun_prop /-- Suppose `F : Homotopy p q`. Then we have a `Homotopy p.symm q.symm` by reversing the second argument. -/ @[simps] def symm₂ {p q : Path x₀ x₁} (F : p.Homotopy q) : p.symm.Homotopy q.symm where toFun x := F ⟨x.1, σ x.2⟩ map_zero_left := by simp [Path.symm] map_one_left := by simp [Path.symm] prop' t x hx := by rcases hx with hx | hx · rw [hx] simp · rw [Set.mem_singleton_iff] at hx rw [hx] simp /-- Given `F : Homotopy p q`, and `f : C(X, Y)`, we can define a homotopy from `p.map f.continuous` to `q.map f.continuous`. -/ @[simps] def map {p q : Path x₀ x₁} (F : p.Homotopy q) (f : C(X, Y)) : Homotopy (p.map f.continuous) (q.map f.continuous) where toFun := f ∘ F map_zero_left := by simp map_one_left := by simp prop' t x hx := by rcases hx with hx | hx · simp [hx] · rw [Set.mem_singleton_iff] at hx simp [hx] end Homotopy /-- Two paths `p₀` and `p₁` are `Path.Homotopic` if there exists a `Homotopy` between them. -/ def Homotopic (p₀ p₁ : Path x₀ x₁) : Prop := Nonempty (p₀.Homotopy p₁) namespace Homotopic @[refl] theorem refl (p : Path x₀ x₁) : p.Homotopic p := ⟨Homotopy.refl p⟩ @[symm] theorem symm ⦃p₀ p₁ : Path x₀ x₁⦄ (h : p₀.Homotopic p₁) : p₁.Homotopic p₀ := h.map Homotopy.symm @[trans] theorem trans ⦃p₀ p₁ p₂ : Path x₀ x₁⦄ (h₀ : p₀.Homotopic p₁) (h₁ : p₁.Homotopic p₂) : p₀.Homotopic p₂ := h₀.map2 Homotopy.trans h₁ theorem equivalence : Equivalence (@Homotopic X _ x₀ x₁) := ⟨refl, (symm ·), (trans · ·)⟩ nonrec theorem map {p q : Path x₀ x₁} (h : p.Homotopic q) (f : C(X, Y)) : Homotopic (p.map f.continuous) (q.map f.continuous) := h.map fun F => F.map f theorem hcomp {p₀ p₁ : Path x₀ x₁} {q₀ q₁ : Path x₁ x₂} (hp : p₀.Homotopic p₁) (hq : q₀.Homotopic q₁) : (p₀.trans q₀).Homotopic (p₁.trans q₁) := hp.map2 Homotopy.hcomp hq /-- The setoid on `Path`s defined by the equivalence relation `Path.Homotopic`. That is, two paths are equivalent if there is a `Homotopy` between them. -/ protected def setoid (x₀ x₁ : X) : Setoid (Path x₀ x₁) := ⟨Homotopic, equivalence⟩ /-- The quotient on `Path x₀ x₁` by the equivalence relation `Path.Homotopic`. -/ protected def Quotient (x₀ x₁ : X) := Quotient (Homotopic.setoid x₀ x₁) attribute [local instance] Homotopic.setoid instance : Inhabited (Homotopic.Quotient () ()) := ⟨Quotient.mk' <| Path.refl ()⟩ /-- The composition of path homotopy classes. This is `Path.trans` descended to the quotient. -/ def Quotient.comp (P₀ : Path.Homotopic.Quotient x₀ x₁) (P₁ : Path.Homotopic.Quotient x₁ x₂) : Path.Homotopic.Quotient x₀ x₂ := Quotient.map₂ Path.trans (fun (_ : Path x₀ x₁) _ hp (_ : Path x₁ x₂) _ hq => hcomp hp hq) P₀ P₁ theorem comp_lift (P₀ : Path x₀ x₁) (P₁ : Path x₁ x₂) : ⟦P₀.trans P₁⟧ = Quotient.comp ⟦P₀⟧ ⟦P₁⟧ := rfl /-- The image of a path homotopy class `P₀` under a map `f`. This is `Path.map` descended to the quotient. -/ def Quotient.mapFn (P₀ : Path.Homotopic.Quotient x₀ x₁) (f : C(X, Y)) : Path.Homotopic.Quotient (f x₀) (f x₁) := Quotient.map (fun q : Path x₀ x₁ => q.map f.continuous) (fun _ _ h => Path.Homotopic.map h f) P₀ theorem map_lift (P₀ : Path x₀ x₁) (f : C(X, Y)) : ⟦P₀.map f.continuous⟧ = Quotient.mapFn ⟦P₀⟧ f := rfl -- Porting note: we didn't previously need the `α := ...` and `β := ...` hints. theorem hpath_hext {p₁ : Path x₀ x₁} {p₂ : Path x₂ x₃} (hp : ∀ t, p₁ t = p₂ t) : HEq (α := Path.Homotopic.Quotient _ _) ⟦p₁⟧ (β := Path.Homotopic.Quotient _ _) ⟦p₂⟧ := by obtain rfl : x₀ = x₂ := by convert hp 0 <;> simp obtain rfl : x₁ = x₃ := by convert hp 1 <;> simp rw [heq_iff_eq]; congr; ext t; exact hp t end Homotopic /-- A path `Path x₀ x₁` generates a homotopy between constant functions `fun _ ↦ x₀` and `fun _ ↦ x₁`. -/ @[simps!] def toHomotopyConst (p : Path x₀ x₁) : (ContinuousMap.const Y x₀).Homotopy (ContinuousMap.const Y x₁) where toContinuousMap := p.toContinuousMap.comp ContinuousMap.fst map_zero_left _ := p.source map_one_left _ := p.target end Path /-- Two constant continuous maps with nonempty domain are homotopic if and only if their values are joined by a path in the codomain. -/ @[simp] theorem ContinuousMap.homotopic_const_iff [Nonempty Y] : (ContinuousMap.const Y x₀).Homotopic (ContinuousMap.const Y x₁) ↔ Joined x₀ x₁ := by inhabit Y refine ⟨fun ⟨H⟩ ↦ ⟨⟨(H.toContinuousMap.comp .prodSwap).curry default, ?_, ?_⟩⟩, fun ⟨p⟩ ↦ ⟨p.toHomotopyConst⟩⟩ <;> simp namespace ContinuousMap.Homotopy /-- Given a homotopy `H : f ∼ g`, get the path traced by the point `x` as it moves from `f x` to `g x`. -/ def evalAt {X : Type*} {Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {f g : C(X, Y)} (H : ContinuousMap.Homotopy f g) (x : X) : Path (f x) (g x) where toFun t := H (t, x) source' := H.apply_zero x target' := H.apply_one x end ContinuousMap.Homotopy
Sum.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import Mathlib.Algebra.BigOperators.Intervals import Mathlib.Algebra.BigOperators.NatAntidiagonal import Mathlib.Algebra.BigOperators.Ring.Finset import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Tactic.Linarith import Mathlib.Tactic.Ring /-! # Sums of binomial coefficients This file includes variants of the binomial theorem and other results on sums of binomial coefficients. Theorems whose proofs depend on such sums may also go in this file for import reasons. -/ open Nat Finset variable {R : Type*} namespace Commute variable [Semiring R] {x y : R} /-- A version of the **binomial theorem** for commuting elements in noncommutative semirings. -/ theorem add_pow (h : Commute x y) (n : ℕ) : (x + y) ^ n = ∑ m ∈ range (n + 1), x ^ m * y ^ (n - m) * n.choose m := by let t : ℕ → ℕ → R := fun n m ↦ x ^ m * y ^ (n - m) * n.choose m change (x + y) ^ n = ∑ m ∈ range (n + 1), t n m have h_first : ∀ n, t n 0 = y ^ n := fun n ↦ by simp only [t, choose_zero_right, pow_zero, cast_one, mul_one, one_mul, tsub_zero] have h_last : ∀ n, t n n.succ = 0 := fun n ↦ by simp only [t, choose_succ_self, cast_zero, mul_zero] have h_middle : ∀ n i : ℕ, i ∈ range n.succ → (t n.succ i.succ) = x * t n i + y * t n i.succ := by intro n i h_mem have h_le : i ≤ n := le_of_lt_succ (mem_range.mp h_mem) dsimp only [t] rw [choose_succ_succ, cast_add, mul_add] congr 1 · rw [pow_succ' x, succ_sub_succ, mul_assoc, mul_assoc, mul_assoc] · rw [← mul_assoc y, ← mul_assoc y, (h.symm.pow_right i.succ).eq] by_cases h_eq : i = n · rw [h_eq, choose_succ_self, cast_zero, mul_zero, mul_zero] · rw [succ_sub (lt_of_le_of_ne h_le h_eq)] rw [pow_succ' y, mul_assoc, mul_assoc, mul_assoc, mul_assoc] induction n with | zero => rw [pow_zero, sum_range_succ, range_zero, sum_empty, zero_add] dsimp only [t] rw [pow_zero, pow_zero, choose_self, cast_one, mul_one, mul_one] | succ n ih => rw [sum_range_succ', h_first, sum_congr rfl (h_middle n), sum_add_distrib, add_assoc, pow_succ' (x + y), ih, add_mul, mul_sum, mul_sum] congr 1 rw [sum_range_succ', sum_range_succ, h_first, h_last, mul_zero, add_zero, _root_.pow_succ'] /-- A version of `Commute.add_pow` that avoids ℕ-subtraction by summing over the antidiagonal and also with the binomial coefficient applied via scalar action of ℕ. -/ theorem add_pow' (h : Commute x y) (n : ℕ) : (x + y) ^ n = ∑ m ∈ antidiagonal n, n.choose m.1 • (x ^ m.1 * y ^ m.2) := by simp_rw [Nat.sum_antidiagonal_eq_sum_range_succ fun m p ↦ n.choose m • (x ^ m * y ^ p), nsmul_eq_mul, cast_comm, h.add_pow] end Commute /-- The **binomial theorem** -/ theorem add_pow [CommSemiring R] (x y : R) (n : ℕ) : (x + y) ^ n = ∑ m ∈ range (n + 1), x ^ m * y ^ (n - m) * n.choose m := (Commute.all x y).add_pow n /-- A special case of the **binomial theorem** -/ theorem sub_pow [CommRing R] (x y : R) (n : ℕ) : (x - y) ^ n = ∑ m ∈ range (n + 1), (-1) ^ (m + n) * x ^ m * y ^ (n - m) * n.choose m := by rw [sub_eq_add_neg, add_pow] congr! 1 with m hm have : (-1 : R) ^ (n - m) = (-1) ^ (n + m) := by rw [mem_range] at hm simp [show n + m = n - m + 2 * m by omega, pow_add] rw [neg_pow, this] ring namespace Nat /-- The sum of entries in a row of Pascal's triangle -/ theorem sum_range_choose (n : ℕ) : (∑ m ∈ range (n + 1), n.choose m) = 2 ^ n := by have := (add_pow 1 1 n).symm simpa [one_add_one_eq_two] using this theorem sum_range_choose_halfway (m : ℕ) : (∑ i ∈ range (m + 1), (2 * m + 1).choose i) = 4 ^ m := have : (∑ i ∈ range (m + 1), (2 * m + 1).choose (2 * m + 1 - i)) = ∑ i ∈ range (m + 1), (2 * m + 1).choose i := sum_congr rfl fun i hi ↦ choose_symm <| by linarith [mem_range.1 hi] mul_right_injective₀ two_ne_zero <| calc (2 * ∑ i ∈ range (m + 1), (2 * m + 1).choose i) = (∑ i ∈ range (m + 1), (2 * m + 1).choose i) + ∑ i ∈ range (m + 1), (2 * m + 1).choose (2 * m + 1 - i) := by rw [two_mul, this] _ = (∑ i ∈ range (m + 1), (2 * m + 1).choose i) + ∑ i ∈ Ico (m + 1) (2 * m + 2), (2 * m + 1).choose i := by rw [range_eq_Ico, sum_Ico_reflect _ _ (by omega)] congr omega _ = ∑ i ∈ range (2 * m + 2), (2 * m + 1).choose i := sum_range_add_sum_Ico _ (by omega) _ = 2 ^ (2 * m + 1) := sum_range_choose (2 * m + 1) _ = 2 * 4 ^ m := by rw [pow_succ, pow_mul, mul_comm]; rfl theorem choose_middle_le_pow (n : ℕ) : (2 * n + 1).choose n ≤ 4 ^ n := by have t : (2 * n + 1).choose n ≤ ∑ i ∈ range (n + 1), (2 * n + 1).choose i := single_le_sum (fun x _ ↦ by omega) (self_mem_range_succ n) simpa [sum_range_choose_halfway n] using t theorem four_pow_le_two_mul_add_one_mul_central_binom (n : ℕ) : 4 ^ n ≤ (2 * n + 1) * (2 * n).choose n := calc 4 ^ n = (1 + 1) ^ (2 * n) := by simp [pow_mul] _ = ∑ m ∈ range (2 * n + 1), (2 * n).choose m := by simp [-Nat.reduceAdd, add_pow] _ ≤ ∑ _ ∈ range (2 * n + 1), (2 * n).choose (2 * n / 2) := by gcongr; apply choose_le_middle _ = (2 * n + 1) * choose (2 * n) n := by simp /-- **Zhu Shijie's identity** aka hockey-stick identity, version with `Icc`. -/ theorem sum_Icc_choose (n k : ℕ) : ∑ m ∈ Icc k n, m.choose k = (n + 1).choose (k + 1) := by rcases lt_or_ge n k with h | h · rw [choose_eq_zero_of_lt (by omega), Icc_eq_empty_of_lt h, sum_empty] · induction n, h using le_induction with | base => simp | succ n _ ih => rw [← Ico_insert_right (by omega), sum_insert (by simp), Ico_add_one_right_eq_Icc, ih, choose_succ_succ' (n + 1)] /-- **Zhu Shijie's identity** aka hockey-stick identity, version with `range`. Summing `(i + k).choose k` for `i ∈ [0, n]` gives `(n + k + 1).choose (k + 1)`. Combinatorial interpretation: `(i + k).choose k` is the number of decompositions of `[0, i)` in `k + 1` (possibly empty) intervals (this follows from a stars and bars description). In particular, `(n + k + 1).choose (k + 1)` corresponds to decomposing `[0, n)` into `k + 2` intervals. By putting away the last interval (of some length `n - i`), we have to decompose the remaining interval `[0, i)` into `k + 1` intervals, hence the sum. -/ lemma sum_range_add_choose (n k : ℕ) : ∑ i ∈ Finset.range (n + 1), (i + k).choose k = (n + k + 1).choose (k + 1) := by rw [← sum_Icc_choose, range_eq_Ico] convert (sum_map _ (addRightEmbedding k) (·.choose k)).symm using 2 rw [map_add_right_Ico, zero_add, add_right_comm, Ico_add_one_right_eq_Icc] end Nat theorem Int.alternating_sum_range_choose {n : ℕ} : (∑ m ∈ range (n + 1), ((-1) ^ m * n.choose m : ℤ)) = if n = 0 then 1 else 0 := by cases n with | zero => simp | succ n => have h := add_pow (-1 : ℤ) 1 n.succ simp only [one_pow, mul_one, neg_add_cancel] at h rw [← h, zero_pow n.succ_ne_zero, if_neg n.succ_ne_zero] theorem Int.alternating_sum_range_choose_of_ne {n : ℕ} (h0 : n ≠ 0) : (∑ m ∈ range (n + 1), ((-1) ^ m * n.choose m : ℤ)) = 0 := by rw [Int.alternating_sum_range_choose, if_neg h0] namespace Finset theorem sum_powerset_apply_card {α β : Type*} [AddCommMonoid α] (f : ℕ → α) {x : Finset β} : ∑ m ∈ x.powerset, f #m = ∑ m ∈ range (#x + 1), (#x).choose m • f m := by trans ∑ m ∈ range (#x + 1), ∑ j ∈ x.powerset with #j = m, f #j · refine (sum_fiberwise_of_maps_to ?_ _).symm intro y hy rw [mem_range, Nat.lt_succ_iff] rw [mem_powerset] at hy exact card_le_card hy · refine sum_congr rfl fun y _ ↦ ?_ rw [← card_powersetCard, ← sum_const] refine sum_congr powersetCard_eq_filter.symm fun z hz ↦ ?_ rw [(mem_powersetCard.1 hz).2] theorem sum_powerset_neg_one_pow_card {α : Type*} [DecidableEq α] {x : Finset α} : (∑ m ∈ x.powerset, (-1 : ℤ) ^ #m) = if x = ∅ then 1 else 0 := by rw [sum_powerset_apply_card] simp only [nsmul_eq_mul', ← card_eq_zero, Int.alternating_sum_range_choose] theorem sum_powerset_neg_one_pow_card_of_nonempty {α : Type*} {x : Finset α} (h0 : x.Nonempty) : (∑ m ∈ x.powerset, (-1 : ℤ) ^ #m) = 0 := by classical rw [sum_powerset_neg_one_pow_card] exact if_neg (nonempty_iff_ne_empty.mp h0) variable [NonAssocSemiring R] @[to_additive sum_choose_succ_nsmul] theorem prod_pow_choose_succ {M : Type*} [CommMonoid M] (f : ℕ → ℕ → M) (n : ℕ) : (∏ i ∈ range (n + 2), f i (n + 1 - i) ^ (n + 1).choose i) = (∏ i ∈ range (n + 1), f i (n + 1 - i) ^ n.choose i) * ∏ i ∈ range (n + 1), f (i + 1) (n - i) ^ n.choose i := by have A : (∏ i ∈ range (n + 1), f (i + 1) (n - i) ^ (n.choose (i + 1))) * f 0 (n + 1) = ∏ i ∈ range (n + 1), f i (n + 1 - i) ^ (n.choose i) := by rw [prod_range_succ, prod_range_succ']; simp rw [prod_range_succ'] simpa [choose_succ_succ, pow_add, prod_mul_distrib, A, mul_assoc] using mul_comm _ _ @[to_additive sum_antidiagonal_choose_succ_nsmul] theorem prod_antidiagonal_pow_choose_succ {M : Type*} [CommMonoid M] (f : ℕ → ℕ → M) (n : ℕ) : (∏ ij ∈ antidiagonal (n + 1), f ij.1 ij.2 ^ (n + 1).choose ij.1) = (∏ ij ∈ antidiagonal n, f ij.1 (ij.2 + 1) ^ n.choose ij.1) * ∏ ij ∈ antidiagonal n, f (ij.1 + 1) ij.2 ^ n.choose ij.2 := by simp only [Nat.prod_antidiagonal_eq_prod_range_succ_mk, prod_pow_choose_succ] have : ∀ i ∈ range (n + 1), i ≤ n := fun i hi ↦ by simpa [Nat.lt_succ_iff] using hi congr 1 · refine prod_congr rfl fun i hi ↦ ?_ rw [tsub_add_eq_add_tsub (this _ hi)] · refine prod_congr rfl fun i hi ↦ ?_ rw [choose_symm (this _ hi)] /-- The sum of `(n+1).choose i * f i (n+1-i)` can be split into two sums at rank `n`, respectively of `n.choose i * f i (n+1-i)` and `n.choose i * f (i+1) (n-i)`. -/ theorem sum_choose_succ_mul (f : ℕ → ℕ → R) (n : ℕ) : (∑ i ∈ range (n + 2), ((n + 1).choose i : R) * f i (n + 1 - i)) = (∑ i ∈ range (n + 1), (n.choose i : R) * f i (n + 1 - i)) + ∑ i ∈ range (n + 1), (n.choose i : R) * f (i + 1) (n - i) := by simpa only [nsmul_eq_mul] using sum_choose_succ_nsmul f n /-- The sum along the antidiagonal of `(n+1).choose i * f i j` can be split into two sums along the antidiagonal at rank `n`, respectively of `n.choose i * f i (j+1)` and `n.choose j * f (i+1) j`. -/ theorem sum_antidiagonal_choose_succ_mul (f : ℕ → ℕ → R) (n : ℕ) : (∑ ij ∈ antidiagonal (n + 1), ((n + 1).choose ij.1 : R) * f ij.1 ij.2) = (∑ ij ∈ antidiagonal n, (n.choose ij.1 : R) * f ij.1 (ij.2 + 1)) + ∑ ij ∈ antidiagonal n, (n.choose ij.2 : R) * f (ij.1 + 1) ij.2 := by simpa only [nsmul_eq_mul] using sum_antidiagonal_choose_succ_nsmul f n theorem sum_antidiagonal_choose_add (d n : ℕ) : (∑ ij ∈ antidiagonal n, (d + ij.2).choose d) = (d + n + 1).choose (d + 1) := by induction n with | zero => simp | succ n hn => rw [Nat.sum_antidiagonal_succ, hn, Nat.choose_succ_succ (d + (n + 1)), ← add_assoc] end Finset
Conv.lean
/- Copyright (c) 2024 Lean FRO LLC. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.CategoryTheory.Monoidal.Comon_ /-! # The convolution monoid. When `M : Comon_ C` and `N : Mon_ C`, the morphisms `M.X ⟶ N.X` form a monoid (in Type). -/ universe v₁ u₁ namespace CategoryTheory open MonoidalCategory open Mon_Class Comon_Class variable {C : Type u₁} [Category.{v₁} C] [MonoidalCategory C] /-- The morphisms in `C` between the underlying objects of a pair of bimonoids in `C` naturally has a (set-theoretic) monoid structure. -/ def Conv (M N : C) : Type v₁ := M ⟶ N namespace Conv variable {M : C} {N : C} [Comon_Class M] [Mon_Class N] instance : One (Conv M N) where one := ε[M] ≫ η[N] theorem one_eq : (1 : Conv M N) = ε[M] ≫ η[N] := rfl instance : Mul (Conv M N) where mul := fun f g => Δ[M] ≫ f ▷ M ≫ N ◁ g ≫ μ[N] theorem mul_eq (f g : Conv M N) : f * g = Δ[M] ≫ f ▷ M ≫ N ◁ g ≫ μ[N] := rfl instance : Monoid (Conv M N) where one_mul f := by simp [one_eq, mul_eq, ← whisker_exchange_assoc] mul_one f := by simp [one_eq, mul_eq, ← whisker_exchange_assoc] mul_assoc f g h := by simp only [mul_eq] simp only [comp_whiskerRight, whisker_assoc, Category.assoc, MonoidalCategory.whiskerLeft_comp] slice_lhs 7 8 => rw [← whisker_exchange] slice_rhs 2 3 => rw [← whisker_exchange] simp end Conv end CategoryTheory
Finiteness.lean
/- Copyright (c) 2024 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import Mathlib.Algebra.Colimit.Module import Mathlib.RingTheory.Finiteness.Basic /-! # Modules as direct limits of finitely generated submodules We show that every module is the direct limit of its finitely generated submodules. ## Main definitions * `Module.fgSystem`: the directed system of finitely generated submodules of a module. * `Module.fgSystem.equiv`: the isomorphism between a module and the direct limit of its finitely generated submodules. -/ namespace Module variable (R M : Type*) [Semiring R] [AddCommMonoid M] [Module R M] /-- The directed system of finitely generated submodules of a module. -/ def fgSystem (N₁ N₂ : {N : Submodule R M // N.FG}) (le : N₁ ≤ N₂) : N₁ →ₗ[R] N₂ := Submodule.inclusion le open DirectLimit namespace fgSystem instance : IsDirected {N : Submodule R M // N.FG} (· ≤ ·) where directed N₁ N₂ := ⟨⟨_, N₁.2.sup N₂.2⟩, Subtype.coe_le_coe.mp le_sup_left, Subtype.coe_le_coe.mp le_sup_right⟩ instance : DirectedSystem _ (fgSystem R M · · · ·) where map_self _ _ := rfl map_map _ _ _ _ _ _ := rfl variable [DecidableEq (Submodule R M)] open Submodule in /-- Every module is the direct limit of its finitely generated submodules. -/ noncomputable def equiv : DirectLimit _ (fgSystem R M) ≃ₗ[R] M := .ofBijective (lift _ _ _ _ (fun _ ↦ Submodule.subtype _) fun _ _ _ _ ↦ rfl) ⟨lift_injective _ _ fun _ ↦ Subtype.val_injective, fun x ↦ ⟨of _ _ _ _ ⟨_, fg_span_singleton x⟩ ⟨x, subset_span <| by rfl⟩, lift_of ..⟩⟩ variable {R M} lemma equiv_comp_of (N : {N : Submodule R M // N.FG}) : (equiv R M).toLinearMap ∘ₗ of _ _ _ _ N = N.1.subtype := by ext; simp [equiv] end fgSystem end Module
ssrnum.v
From mathcomp Require Export orderedzmod. From mathcomp Require Export numdomain. From mathcomp Require Export numfield. Module Num. Export orderedzmod.Num. Export numdomain.Num. Export numfield.Num. Module Theory. Export orderedzmod.Num.Theory. Export numdomain.Num.Theory. Export numfield.Num.Theory. End Theory. Module Def. Export orderedzmod.Num.Def. Export numdomain.Num.Def. Export numfield.Num.Def. End Def. Module ExtraDef. #[deprecated(since="mathcomp 2.5.0", note="Use Num.Def.sqrtr instead.")] Notation sqrtr := numfield.Num.Def.sqrtr. End ExtraDef. End Num.
Kleisli.lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Bhavik Mehta -/ import Mathlib.CategoryTheory.Adjunction.Basic import Mathlib.CategoryTheory.Monad.Basic /-! # Kleisli category on a (co)monad This file defines the Kleisli category on a monad `(T, η_ T, μ_ T)` as well as the co-Kleisli category on a comonad `(U, ε_ U, δ_ U)`. It also defines the Kleisli adjunction which gives rise to the monad `(T, η_ T, μ_ T)` as well as the co-Kleisli adjunction which gives rise to the comonad `(U, ε_ U, δ_ U)`. ## References * [Riehl, *Category theory in context*, Definition 5.2.9][riehl2017] -/ namespace CategoryTheory universe v u -- morphism levels before object levels. See note [CategoryTheory universes]. variable {C : Type u} [Category.{v} C] /-- The objects for the Kleisli category of the monad `T : Monad C`, which are the same thing as objects of the base category `C`. -/ @[nolint unusedArguments] def Kleisli (_T : Monad C) := C namespace Kleisli variable (T : Monad C) instance [Inhabited C] (T : Monad C) : Inhabited (Kleisli T) := ⟨(default : C)⟩ /-- The Kleisli category on a monad `T`. cf Definition 5.2.9 in [Riehl][riehl2017]. -/ instance category : Category (Kleisli T) where Hom := fun X Y : C => X ⟶ (T : C ⥤ C).obj Y id X := T.η.app X comp {_} {_} {Z} f g := f ≫ (T : C ⥤ C).map g ≫ T.μ.app Z id_comp {X} {Y} f := by rw [← T.η.naturality_assoc f, T.left_unit] apply Category.comp_id assoc f g h := by simp [Monad.assoc, T.mu_naturality_assoc] namespace Adjunction /-- The left adjoint of the adjunction which induces the monad `(T, η_ T, μ_ T)`. -/ @[simps] def toKleisli : C ⥤ Kleisli T where obj X := (X : Kleisli T) map {X} {Y} f := (f ≫ T.η.app Y : X ⟶ T.obj Y) map_comp {X} {Y} {Z} f g := by -- Porting note: hack for missing unfold_projs tactic change _ = (f ≫ (Monad.η T).app Y) ≫ T.map (g ≫ (Monad.η T).app Z) ≫ T.μ.app Z simp [← T.η.naturality g] /-- The right adjoint of the adjunction which induces the monad `(T, η_ T, μ_ T)`. -/ @[simps] def fromKleisli : Kleisli T ⥤ C where obj X := T.obj X map {_} {Y} f := T.map f ≫ T.μ.app Y map_id _ := T.right_unit _ map_comp {X} {Y} {Z} f g := by -- Porting note: hack for missing unfold_projs tactic change T.map (f ≫ T.map g ≫ T.μ.app Z) ≫ T.μ.app Z = _ simp only [Functor.map_comp, Category.assoc] rw [← T.μ.naturality_assoc g, T.assoc] rfl /-- The Kleisli adjunction which gives rise to the monad `(T, η_ T, μ_ T)`. cf Lemma 5.2.11 of [Riehl][riehl2017]. -/ def adj : toKleisli T ⊣ fromKleisli T := Adjunction.mkOfHomEquiv { homEquiv := fun X Y => Equiv.refl (X ⟶ T.obj Y) homEquiv_naturality_left_symm := fun {X} {Y} {Z} f g => by -- Porting note: used to be unfold_projs; dsimp change f ≫ g = (f ≫ T.η.app Y) ≫ T.map g ≫ T.μ.app Z rw [Category.assoc, ← T.η.naturality_assoc g, Functor.id_map] simp [Monad.left_unit] } /-- The composition of the adjunction gives the original functor. -/ def toKleisliCompFromKleisliIsoSelf : toKleisli T ⋙ fromKleisli T ≅ T := NatIso.ofComponents fun _ => Iso.refl _ end Adjunction end Kleisli /-- The objects for the co-Kleisli category of the comonad `U : Comonad C`, which are the same thing as objects of the base category `C`. -/ @[nolint unusedArguments] def Cokleisli (_U : Comonad C) := C namespace Cokleisli variable (U : Comonad C) instance [Inhabited C] (U : Comonad C) : Inhabited (Cokleisli U) := ⟨(default : C)⟩ /-- The co-Kleisli category on a comonad `U`. -/ instance category : Category (Cokleisli U) where Hom := fun X Y : C => (U : C ⥤ C).obj X ⟶ Y id X := U.ε.app X comp f g := U.δ.app _ ≫ (U : C ⥤ C).map f ≫ g namespace Adjunction /-- The right adjoint of the adjunction which induces the comonad `(U, ε_ U, δ_ U)`. -/ @[simps] def toCokleisli : C ⥤ Cokleisli U where obj X := (X : Cokleisli U) map {X} {_} f := (U.ε.app X ≫ f :) map_comp {X} {Y} {_} f g := by -- Porting note: working around lack of unfold_projs change U.ε.app X ≫ f ≫ g = U.δ.app X ≫ U.map (U.ε.app X ≫ f) ≫ U.ε.app Y ≫ g simp /-- The left adjoint of the adjunction which induces the comonad `(U, ε_ U, δ_ U)`. -/ @[simps] def fromCokleisli : Cokleisli U ⥤ C where obj X := U.obj X map {X} {_} f := U.δ.app X ≫ U.map f map_id _ := U.right_counit _ map_comp {X} {Y} {_} f g := by -- Porting note: working around lack of unfold_projs change U.δ.app X ≫ U.map (U.δ.app X ≫ U.map f ≫ g) = (U.δ.app X ≫ U.map f) ≫ (U.δ.app Y ≫ U.map g) simp only [Functor.map_comp, ← Category.assoc] rw [Comonad.coassoc] simp only [Category.assoc, NatTrans.naturality, Functor.comp_map] /-- The co-Kleisli adjunction which gives rise to the monad `(U, ε_ U, δ_ U)`. -/ def adj : fromCokleisli U ⊣ toCokleisli U := Adjunction.mkOfHomEquiv { homEquiv := fun X Y => Equiv.refl (U.obj X ⟶ Y) homEquiv_naturality_right := fun {X} {Y} {_} f g => by -- Porting note: working around lack of unfold_projs change f ≫ g = U.δ.app X ≫ U.map f ≫ U.ε.app Y ≫ g rw [← Category.assoc (U.map f), U.ε.naturality]; dsimp simp only [← Category.assoc, Comonad.left_counit, Category.id_comp] } /-- The composition of the adjunction gives the original functor. -/ def toCokleisliCompFromCokleisliIsoSelf : toCokleisli U ⋙ fromCokleisli U ≅ U := NatIso.ofComponents fun _ => Iso.refl _ end Adjunction end Cokleisli end CategoryTheory
polydiv.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import fintype bigop ssralg poly. (******************************************************************************) (* This file provides a library for the basic theory of Euclidean and pseudo- *) (* Euclidean division for polynomials over non trivial ring structures. *) (* The library defines two versions of the pseudo-euclidean division: one for *) (* coefficients in a (not necessarily commutative) non-trivial ring structure *) (* and one for coefficients equipped with a structure of integral domain. *) (* From the latter we derive the definition of the usual Euclidean division *) (* for coefficients in a field. Only the definition of the pseudo-division *) (* for coefficients in an integral domain is exported by default and benefits *) (* from notations. *) (* Also, the only theory exported by default is the one of division for *) (* polynomials with coefficients in a field. *) (* Other definitions and facts are qualified using name spaces indicating the *) (* hypotheses made on the structure of coefficients and the properties of the *) (* polynomial one divides with. *) (* *) (* Pdiv.Field (exported by the present library): *) (* edivp p q == pseudo-division of p by q with p q : {poly R} where *) (* R is an idomainType. *) (* Computes (k, quo, rem) : nat * {poly r} * {poly R}, *) (* such that size rem < size q and: *) (* + if lead_coef q is not a unit, then: *) (* (lead_coef q ^+ k) *: p = q * quo + rem *) (* + else if lead_coef q is a unit, then: *) (* p = q * quo + rem and k = 0 *) (* p %/ q == quotient (second component) computed by (edivp p q). *) (* p %% q == remainder (third component) computed by (edivp p q). *) (* scalp p q == exponent (first component) computed by (edivp p q). *) (* p %| q == tests the nullity of the remainder of the *) (* pseudo-division of p by q. *) (* rgcdp p q == Pseudo-greater common divisor obtained by performing *) (* the Euclidean algorithm on p and q using redivp as *) (* Euclidean division. *) (* p %= q == p and q are associate polynomials, i.e., p %| q and *) (* q %| p, or equivalently, p = c *: q for some nonzero *) (* constant c. *) (* gcdp p q == Pseudo-greater common divisor obtained by performing *) (* the Euclidean algorithm on p and q using edivp as *) (* Euclidean division. *) (* egcdp p q == The pair of Bezout coefficients: if e := egcdp p q, *) (* then size e.1 <= size q, size e.2 <= size p, and *) (* gcdp p q %= e.1 * p + e.2 * q *) (* coprimep p q == p and q are coprime, i.e., (gcdp p q) is a nonzero *) (* constant. *) (* gdcop q p == greatest divisor of p which is coprime to q. *) (* irreducible_poly p <-> p has only trivial (constant) divisors. *) (* mup x q == multplicity of x as a root of q *) (* *) (* Pdiv.Idomain: theory available for edivp and the related operation under *) (* the sole assumption that the ring of coefficients is canonically an *) (* integral domain (R : idomainType). *) (* *) (* Pdiv.IdomainMonic: theory available for edivp and the related operations *) (* under the assumption that the ring of coefficients is canonically *) (* and integral domain (R : idomainType) an the divisor is monic. *) (* *) (* Pdiv.IdomainUnit: theory available for edivp and the related operations *) (* under the assumption that the ring of coefficients is canonically an *) (* integral domain (R : idomainType) and the leading coefficient of the *) (* divisor is a unit. *) (* *) (* Pdiv.ClosedField: theory available for edivp and the related operation *) (* under the sole assumption that the ring of coefficients is canonically *) (* an algebraically closed field (R : closedField). *) (* *) (* Pdiv.Ring : *) (* redivp p q == pseudo-division of p by q with p q : {poly R} where R is *) (* a nzRingType. *) (* Computes (k, quo, rem) : nat * {poly r} * {poly R}, *) (* such that if rem = 0 then quo * q = p * (lead_coef q ^+ k) *) (* *) (* rdivp p q == quotient (second component) computed by (redivp p q). *) (* rmodp p q == remainder (third component) computed by (redivp p q). *) (* rscalp p q == exponent (first component) computed by (redivp p q). *) (* rdvdp p q == tests the nullity of the remainder of the pseudo-division *) (* of p by q. *) (* rgcdp p q == analogue of gcdp for coefficients in a nzRingType. *) (* rgdcop p q == analogue of gdcop for coefficients in a nzRingType. *) (*rcoprimep p q == analogue of coprimep p q for coefficients in a nzRingType. *) (* *) (* Pdiv.RingComRreg : theory of the operations defined in Pdiv.Ring, when the *) (* ring of coefficients is canonically commutative (R : comNzRingType) and *) (* the leading coefficient of the divisor is both right regular and *) (* commutes as a constant polynomial with the divisor itself *) (* *) (* Pdiv.RingMonic : theory of the operations defined in Pdiv.Ring, under the *) (* assumption that the divisor is monic. *) (* *) (* Pdiv.UnitRing: theory of the operations defined in Pdiv.Ring, when the *) (* ring R of coefficients is canonically with units (R : unitRingType). *) (* *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory. Local Open Scope ring_scope. Reserved Notation "p %= q" (at level 70, no associativity). Local Notation simp := Monoid.simpm. Module Pdiv. Module CommonRing. Section RingPseudoDivision. Variable R : nzRingType. Implicit Types d p q r : {poly R}. (* Pseudo division, defined on an arbitrary ring *) Definition redivp_rec (q : {poly R}) := let sq := size q in let cq := lead_coef q in fix loop (k : nat) (qq r : {poly R})(n : nat) {struct n} := if size r < sq then (k, qq, r) else let m := (lead_coef r) *: 'X^(size r - sq) in let qq1 := qq * cq%:P + m in let r1 := r * cq%:P - m * q in if n is n1.+1 then loop k.+1 qq1 r1 n1 else (k.+1, qq1, r1). Definition redivp_expanded_def p q := if q == 0 then (0, 0, p) else redivp_rec q 0 0 p (size p). Fact redivp_key : unit. Proof. by []. Qed. Definition redivp : {poly R} -> {poly R} -> nat * {poly R} * {poly R} := locked_with redivp_key redivp_expanded_def. Canonical redivp_unlockable := [unlockable fun redivp]. Definition rdivp p q := ((redivp p q).1).2. Definition rmodp p q := (redivp p q).2. Definition rscalp p q := ((redivp p q).1).1. Definition rdvdp p q := rmodp q p == 0. (*Definition rmultp := [rel m d | rdvdp d m].*) Lemma redivp_def p q : redivp p q = (rscalp p q, rdivp p q, rmodp p q). Proof. by rewrite /rscalp /rdivp /rmodp; case: (redivp p q) => [[]] /=. Qed. Lemma rdiv0p p : rdivp 0 p = 0. Proof. rewrite /rdivp unlock; case: ifP => // Hp; rewrite /redivp_rec !size_poly0. by rewrite polySpred ?Hp. Qed. Lemma rdivp0 p : rdivp p 0 = 0. Proof. by rewrite /rdivp unlock eqxx. Qed. Lemma rdivp_small p q : size p < size q -> rdivp p q = 0. Proof. rewrite /rdivp unlock; have [-> | _ ltpq] := eqP; first by rewrite size_poly0. by case: (size p) => [|s]; rewrite /= ltpq. Qed. Lemma leq_rdivp p q : size (rdivp p q) <= size p. Proof. have [/rdivp_small->|] := ltnP (size p) (size q); first by rewrite size_poly0. rewrite /rdivp /rmodp /rscalp unlock. have [->|q0] //= := eqVneq q 0. have: size (0 : {poly R}) <= size p by rewrite size_poly0. move: {2 3 4 6}(size p) (leqnn (size p)) => A. elim: (size p) 0%N (0 : {poly R}) {1 3 4}p (leqnn (size p)) => [|n ihn] k q1 r. by move/size_poly_leq0P->; rewrite /= size_poly0 size_poly_gt0 q0. move=> /= hrn hr hq1 hq; case: ltnP => //= hqr. have sq: 0 < size q by rewrite size_poly_gt0. have sr: 0 < size r by apply: leq_trans sq hqr. apply: ihn => //. - apply/leq_sizeP => j hnj. rewrite coefB -scalerAl coefZ coefXnM ltn_subRL ltnNge. have hj : (size r).-1 <= j by apply: leq_trans hnj; rewrite -ltnS prednK. rewrite [leqLHS]polySpred -?size_poly_gt0 // coefMC. rewrite (leq_ltn_trans hj) /=; last by rewrite -add1n leq_add2r. move: hj; rewrite leq_eqVlt prednK // => /predU1P [<- | hj]. by rewrite -subn1 subnAC subKn // !subn1 !lead_coefE subrr. have/leq_sizeP-> //: size q <= j - (size r - size q). by rewrite subnBA // leq_psubRL // leq_add2r. by move/leq_sizeP: (hj) => -> //; rewrite mul0r mulr0 subr0. - apply: leq_trans (size_polyD _ _) _; rewrite geq_max; apply/andP; split. apply: leq_trans (size_polyMleq _ _) _. by rewrite size_polyC lead_coef_eq0 q0 /= addn1. rewrite size_polyN; apply: leq_trans (size_polyMleq _ _) _. apply: leq_trans hr; rewrite -subn1 leq_subLR -[in (1 + _)%N](subnK hqr). by rewrite addnA leq_add2r add1n -(@size_polyXn R) size_scale_leq. apply: leq_trans (size_polyD _ _) _; rewrite geq_max; apply/andP; split. apply: leq_trans (size_polyMleq _ _) _. by rewrite size_polyC lead_coef_eq0 q0 /= addnS addn0. apply: leq_trans (size_scale_leq _ _) _. by rewrite size_polyXn -subSn // leq_subLR -add1n leq_add. Qed. Lemma rmod0p p : rmodp 0 p = 0. Proof. rewrite /rmodp unlock; case: ifP => // Hp; rewrite /redivp_rec !size_poly0. by rewrite polySpred ?Hp. Qed. Lemma rmodp0 p : rmodp p 0 = p. Proof. by rewrite /rmodp unlock eqxx. Qed. Lemma rscalp_small p q : size p < size q -> rscalp p q = 0. Proof. rewrite /rscalp unlock; case: eqP => _ // spq. by case sp: (size p) => [| s] /=; rewrite spq. Qed. Lemma ltn_rmodp p q : (size (rmodp p q) < size q) = (q != 0). Proof. rewrite /rdivp /rmodp /rscalp unlock; have [->|q0] := eqVneq q 0. by rewrite /= size_poly0 ltn0. elim: (size p) 0%N 0 {1 3}p (leqnn (size p)) => [|n ihn] k q1 r. move/size_poly_leq0P->. by rewrite /= size_poly0 size_poly_gt0 q0 size_poly0 size_poly_gt0. move=> hr /=; case: (ltnP (size r)) => // hsrq; apply/ihn/leq_sizeP => j hnj. rewrite coefB -scalerAl !coefZ coefXnM coefMC ltn_subRL ltnNge. have sq: 0 < size q by rewrite size_poly_gt0. have sr: 0 < size r by apply: leq_trans hsrq. have hj: (size r).-1 <= j by apply: leq_trans hnj; rewrite -ltnS prednK. move: (leq_add sq hj); rewrite add1n prednK // => -> /=. move: hj; rewrite leq_eqVlt prednK // => /predU1P [<- | hj]. by rewrite -predn_sub subKn // !lead_coefE subrr. have/leq_sizeP -> //: size q <= j - (size r - size q). by rewrite subnBA // leq_subRL ?leq_add2r // (leq_trans hj) // leq_addr. by move/leq_sizeP: hj => -> //; rewrite mul0r mulr0 subr0. Qed. Lemma ltn_rmodpN0 p q : q != 0 -> size (rmodp p q) < size q. Proof. by rewrite ltn_rmodp. Qed. Lemma rmodp1 p : rmodp p 1 = 0. Proof. apply/eqP; have := ltn_rmodp p 1. by rewrite !oner_neq0 -size_poly_eq0 size_poly1 ltnS leqn0. Qed. Lemma rmodp_small p q : size p < size q -> rmodp p q = p. Proof. rewrite /rmodp unlock; have [->|_] := eqP; first by rewrite size_poly0. by case sp: (size p) => [| s] Hs /=; rewrite sp Hs /=. Qed. Lemma leq_rmodp m d : size (rmodp m d) <= size m. Proof. have [/rmodp_small -> //|h] := ltnP (size m) (size d). have [->|d0] := eqVneq d 0; first by rewrite rmodp0. by apply: leq_trans h; apply: ltnW; rewrite ltn_rmodp. Qed. Lemma rmodpC p c : c != 0 -> rmodp p c%:P = 0. Proof. move=> Hc; apply/eqP; rewrite -size_poly_leq0 -ltnS. have -> : 1%N = nat_of_bool (c != 0) by rewrite Hc. by rewrite -size_polyC ltn_rmodp polyC_eq0. Qed. Lemma rdvdp0 d : rdvdp d 0. Proof. by rewrite /rdvdp rmod0p. Qed. Lemma rdvd0p n : rdvdp 0 n = (n == 0). Proof. by rewrite /rdvdp rmodp0. Qed. Lemma rdvd0pP n : reflect (n = 0) (rdvdp 0 n). Proof. by apply: (iffP idP); rewrite rdvd0p; move/eqP. Qed. Lemma rdvdpN0 p q : rdvdp p q -> q != 0 -> p != 0. Proof. by move=> pq hq; apply: contraTneq pq => ->; rewrite rdvd0p. Qed. Lemma rdvdp1 d : rdvdp d 1 = (size d == 1). Proof. rewrite /rdvdp; have [->|] := eqVneq d 0. by rewrite rmodp0 size_poly0 (negPf (oner_neq0 _)). rewrite -size_poly_leq0 -ltnS; case: ltngtP => // [|/eqP] hd _. by rewrite rmodp_small ?size_poly1 // oner_eq0. have [c cn0 ->] := size_poly1P _ hd. rewrite /rmodp unlock -size_poly_eq0 size_poly1 /= size_poly1 size_polyC cn0 /=. by rewrite polyC_eq0 (negPf cn0) !lead_coefC !scale1r subrr !size_poly0. Qed. Lemma rdvd1p m : rdvdp 1 m. Proof. by rewrite /rdvdp rmodp1. Qed. Lemma Nrdvdp_small (n d : {poly R}) : n != 0 -> size n < size d -> rdvdp d n = false. Proof. by move=> nn0 hs; rewrite /rdvdp (rmodp_small hs); apply: negPf. Qed. Lemma rmodp_eq0P p q : reflect (rmodp p q = 0) (rdvdp q p). Proof. exact: (iffP eqP). Qed. Lemma rmodp_eq0 p q : rdvdp q p -> rmodp p q = 0. Proof. exact: rmodp_eq0P. Qed. Lemma rdvdp_leq p q : rdvdp p q -> q != 0 -> size p <= size q. Proof. by move=> dvd_pq; rewrite leqNgt; apply: contra => /rmodp_small <-. Qed. Definition rgcdp p q := let: (p1, q1) := if size p < size q then (q, p) else (p, q) in if p1 == 0 then q1 else let fix loop (n : nat) (pp qq : {poly R}) {struct n} := let rr := rmodp pp qq in if rr == 0 then qq else if n is n1.+1 then loop n1 qq rr else rr in loop (size p1) p1 q1. Lemma rgcd0p : left_id 0 rgcdp. Proof. move=> p; rewrite /rgcdp size_poly0 size_poly_gt0 if_neg. case: ifP => /= [_ | nzp]; first by rewrite eqxx. by rewrite polySpred !(rmodp0, nzp) //; case: _.-1 => [|m]; rewrite rmod0p eqxx. Qed. Lemma rgcdp0 : right_id 0 rgcdp. Proof. move=> p; have:= rgcd0p p; rewrite /rgcdp size_poly0 size_poly_gt0. by case: eqVneq => p0; rewrite ?(eqxx, p0) //= eqxx. Qed. Lemma rgcdpE p q : rgcdp p q = if size p < size q then rgcdp (rmodp q p) p else rgcdp (rmodp p q) q. Proof. pose rgcdp_rec := fix rgcdp_rec (n : nat) (pp qq : {poly R}) {struct n} := let rr := rmodp pp qq in if rr == 0 then qq else if n is n1.+1 then rgcdp_rec n1 qq rr else rr. have Irec: forall m n p q, size q <= m -> size q <= n -> size q < size p -> rgcdp_rec m p q = rgcdp_rec n p q. + elim=> [|m Hrec] [|n] //= p1 q1. - move/size_poly_leq0P=> -> _; rewrite size_poly0 size_poly_gt0 rmodp0. by move/negPf->; case: n => [|n] /=; rewrite rmod0p eqxx. - move=> _ /size_poly_leq0P ->; rewrite size_poly0 size_poly_gt0 rmodp0. by move/negPf->; case: m {Hrec} => [|m] /=; rewrite rmod0p eqxx. case: eqVneq => Epq Sm Sn Sq //; have [->|nzq] := eqVneq q1 0. by case: n m {Sm Sn Hrec} => [|m] [|n] //=; rewrite rmod0p eqxx. apply: Hrec; last by rewrite ltn_rmodp. by rewrite -ltnS (leq_trans _ Sm) // ltn_rmodp. by rewrite -ltnS (leq_trans _ Sn) // ltn_rmodp. have [->|nzp] := eqVneq p 0. by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same. have [->|nzq] := eqVneq q 0. by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same. rewrite /rgcdp -/rgcdp_rec !ltn_rmodp (negPf nzp) (negPf nzq) /=. have [ltpq|leqp] := ltnP; rewrite !(negPf nzp, negPf nzq) //= polySpred //=. have [->|nzqp] := eqVneq. by case: (size p) => [|[|s]]; rewrite /= rmodp0 (negPf nzp) // rmod0p eqxx. apply: Irec => //; last by rewrite ltn_rmodp. by rewrite -ltnS -polySpred // (leq_trans _ ltpq) ?leqW // ltn_rmodp. by rewrite ltnW // ltn_rmodp. have [->|nzpq] := eqVneq. by case: (size q) => [|[|s]]; rewrite /= rmodp0 (negPf nzq) // rmod0p eqxx. apply: Irec => //; last by rewrite ltn_rmodp. by rewrite -ltnS -polySpred // (leq_trans _ leqp) // ltn_rmodp. by rewrite ltnW // ltn_rmodp. Qed. Variant comm_redivp_spec m d : nat * {poly R} * {poly R} -> Type := ComEdivnSpec k (q r : {poly R}) of (GRing.comm d (lead_coef d)%:P -> m * (lead_coef d ^+ k)%:P = q * d + r) & (d != 0 -> size r < size d) : comm_redivp_spec m d (k, q, r). Lemma comm_redivpP m d : comm_redivp_spec m d (redivp m d). Proof. rewrite unlock; have [->|Hd] := eqVneq d 0. by constructor; rewrite !(simp, eqxx). have: GRing.comm d (lead_coef d)%:P -> m * (lead_coef d ^+ 0)%:P = 0 * d + m. by rewrite !simp. elim: (size m) 0%N 0 {1 4 6}m (leqnn (size m)) => [|n IHn] k q r Hr /=. move/size_poly_leq0P: Hr ->. suff hsd: size (0: {poly R}) < size d by rewrite hsd => /= ?; constructor. by rewrite size_poly0 size_poly_gt0. case: ltnP => Hlt Heq; first by constructor. apply/IHn=> [|Cda]; last first. rewrite mulrDl addrAC -addrA subrK exprSr polyCM mulrA Heq //. by rewrite mulrDl -mulrA Cda mulrA. apply/leq_sizeP => j Hj; rewrite coefB coefMC -scalerAl coefZ coefXnM. rewrite ltn_subRL ltnNge (leq_trans Hr) /=; last first. by apply: leq_ltn_trans Hj _; rewrite -add1n leq_add2r size_poly_gt0. move: Hj; rewrite leq_eqVlt; case/predU1P => [<-{j} | Hj]; last first. rewrite !nth_default ?simp ?oppr0 ?(leq_trans Hr) //. by rewrite -{1}(subKn Hlt) leq_sub2r // (leq_trans Hr). move: Hr; rewrite leq_eqVlt ltnS; case/predU1P=> Hqq; last first. by rewrite !nth_default ?simp ?oppr0 // -{1}(subKn Hlt) leq_sub2r. rewrite /lead_coef Hqq polySpred // subSS subKn ?addrN //. by rewrite -subn1 leq_subLR add1n -Hqq. Qed. Lemma rmodpp p : GRing.comm p (lead_coef p)%:P -> rmodp p p = 0. Proof. move=> hC; rewrite /rmodp unlock; have [-> //|] := eqVneq. rewrite -size_poly_eq0 /redivp_rec; case sp: (size p)=> [|n] // _. rewrite sp ltnn subnn expr0 hC alg_polyC !simp subrr. by case: n sp => [|n] sp; rewrite size_polyC /= eqxx. Qed. Definition rcoprimep (p q : {poly R}) := size (rgcdp p q) == 1. Fixpoint rgdcop_rec q p n := if n is m.+1 then if rcoprimep p q then p else rgdcop_rec q (rdivp p (rgcdp p q)) m else (q == 0)%:R. Definition rgdcop q p := rgdcop_rec q p (size p). Lemma rgdcop0 q : rgdcop q 0 = (q == 0)%:R. Proof. by rewrite /rgdcop size_poly0. Qed. End RingPseudoDivision. End CommonRing. Module RingComRreg. Import CommonRing. Section ComRegDivisor. Variable R : nzRingType. Variable d : {poly R}. Hypothesis Cdl : GRing.comm d (lead_coef d)%:P. Hypothesis Rreg : GRing.rreg (lead_coef d). Implicit Types p q r : {poly R}. Lemma redivp_eq q r : size r < size d -> let k := (redivp (q * d + r) d).1.1 in let c := (lead_coef d ^+ k)%:P in redivp (q * d + r) d = (k, q * c, r * c). Proof. move=> lt_rd; case: comm_redivpP=> k q1 r1 /(_ Cdl) Heq. have dn0: d != 0 by case: (size d) lt_rd (size_poly_eq0 d) => // n _ <-. move=> /(_ dn0) Hs. have eC : q * d * (lead_coef d ^+ k)%:P = q * (lead_coef d ^+ k)%:P * d. by rewrite -mulrA polyC_exp (commrX k Cdl) mulrA. suff e1 : q1 = q * (lead_coef d ^+ k)%:P. congr (_, _, _) => //=; move/eqP: Heq. by rewrite [_ + r1]addrC -subr_eq e1 mulrDl addrAC eC subrr add0r; move/eqP. have : (q1 - q * (lead_coef d ^+ k)%:P) * d = r * (lead_coef d ^+ k)%:P - r1. apply: (@addIr _ r1); rewrite subrK. apply: (@addrI _ ((q * (lead_coef d ^+ k)%:P) * d)). by rewrite mulrDl mulNr !addrA [_ + (q1 * d)]addrC addrK -eC -mulrDl. move/eqP; rewrite -[_ == _ - _]subr_eq0 rreg_div0 //. by case/andP; rewrite subr_eq0; move/eqP. rewrite size_polyN; apply: (leq_ltn_trans (size_polyD _ _)); rewrite size_polyN. rewrite gtn_max Hs (leq_ltn_trans (size_polyMleq _ _)) //. rewrite size_polyC; case: (_ == _); last by rewrite addnS addn0. by rewrite addn0; apply: leq_ltn_trans lt_rd; case: size. Qed. (* this is a bad name *) Lemma rdivp_eq p : p * (lead_coef d ^+ (rscalp p d))%:P = (rdivp p d) * d + (rmodp p d). Proof. by rewrite /rdivp /rmodp /rscalp; case: comm_redivpP=> k q1 r1 Hc _; apply: Hc. Qed. (* section variables impose an inconvenient order on parameters *) Lemma eq_rdvdp k q1 p: p * ((lead_coef d)^+ k)%:P = q1 * d -> rdvdp d p. Proof. move=> he. have Hnq0 := rreg_lead0 Rreg; set lq := lead_coef d. pose v := rscalp p d; pose m := maxn v k. rewrite /rdvdp -(rreg_polyMC_eq0 _ (@rregX _ _ (m - v) Rreg)). suff: ((rdivp p d) * (lq ^+ (m - v))%:P - q1 * (lq ^+ (m - k))%:P) * d + (rmodp p d) * (lq ^+ (m - v))%:P == 0. rewrite rreg_div0 //; first by case/andP. by rewrite rreg_size ?ltn_rmodp //; exact: rregX. rewrite mulrDl addrAC mulNr -!mulrA polyC_exp -(commrX (m-v) Cdl). rewrite -polyC_exp mulrA -mulrDl -rdivp_eq // [(_ ^+ (m - k))%:P]polyC_exp. rewrite -(commrX (m-k) Cdl) -polyC_exp mulrA -he -!mulrA -!polyCM -/v. by rewrite -!exprD addnC subnK ?leq_maxl // addnC subnK ?subrr ?leq_maxr. Qed. Variant rdvdp_spec p q : {poly R} -> bool -> Type := | Rdvdp k q1 & p * ((lead_coef q)^+ k)%:P = q1 * q : rdvdp_spec p q 0 true | RdvdpN & rmodp p q != 0 : rdvdp_spec p q (rmodp p q) false. (* Is that version useable ? *) Lemma rdvdp_eqP p : rdvdp_spec p d (rmodp p d) (rdvdp d p). Proof. case hdvd: (rdvdp d p); last by apply: RdvdpN; move/rmodp_eq0P/eqP: hdvd. move/rmodp_eq0P: (hdvd)->; apply: (@Rdvdp _ _ (rscalp p d) (rdivp p d)). by rewrite rdivp_eq //; move/rmodp_eq0P: (hdvd)->; rewrite addr0. Qed. Lemma rdvdp_mull p : rdvdp d (p * d). Proof. by apply: (@eq_rdvdp 0 p); rewrite expr0 mulr1. Qed. Lemma rmodp_mull p : rmodp (p * d) d = 0. Proof. exact/eqP/rdvdp_mull. Qed. Lemma rmodpp : rmodp d d = 0. Proof. by rewrite -[d in rmodp d _]mul1r rmodp_mull. Qed. Lemma rdivpp : rdivp d d = (lead_coef d ^+ rscalp d d)%:P. Proof. have dn0 : d != 0 by rewrite -lead_coef_eq0 rreg_neq0. move: (rdivp_eq d); rewrite rmodpp addr0. suff ->: GRing.comm d (lead_coef d ^+ rscalp d d)%:P by move/(rreg_lead Rreg)->. by rewrite polyC_exp; apply: commrX. Qed. Lemma rdvdpp : rdvdp d d. Proof. exact/eqP/rmodpp. Qed. Lemma rdivpK p : rdvdp d p -> rdivp p d * d = p * (lead_coef d ^+ rscalp p d)%:P. Proof. by rewrite rdivp_eq /rdvdp; move/eqP->; rewrite addr0. Qed. End ComRegDivisor. End RingComRreg. Module RingMonic. Import CommonRing. Import RingComRreg. Section RingMonic. Variable R : nzRingType. Implicit Types p q r : {poly R}. Section MonicDivisor. Variable d : {poly R}. Hypothesis mond : d \is monic. Lemma redivp_eq q r : size r < size d -> let k := (redivp (q * d + r) d).1.1 in redivp (q * d + r) d = (k, q, r). Proof. case: (monic_comreg mond)=> Hc Hr /(redivp_eq Hc Hr q). by rewrite (eqP mond) => -> /=; rewrite expr1n !mulr1. Qed. Lemma rdivp_eq p : p = rdivp p d * d + rmodp p d. Proof. rewrite -rdivp_eq (eqP mond); last exact: commr1. by rewrite expr1n mulr1. Qed. Lemma rdivpp : rdivp d d = 1. Proof. by case: (monic_comreg mond) => hc hr; rewrite rdivpp // (eqP mond) expr1n. Qed. Lemma rdivp_addl_mul_small q r : size r < size d -> rdivp (q * d + r) d = q. Proof. by move=> Hd; case: (monic_comreg mond)=> Hc Hr; rewrite /rdivp redivp_eq. Qed. Lemma rdivp_addl_mul q r : rdivp (q * d + r) d = q + rdivp r d. Proof. case: (monic_comreg mond)=> Hc Hr; rewrite [r in _ * _ + r]rdivp_eq addrA. by rewrite -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0. Qed. Lemma rdivpDl q r : rdvdp d q -> rdivp (q + r) d = rdivp q d + rdivp r d. Proof. case: (monic_comreg mond)=> Hc Hr; rewrite [r in q + r]rdivp_eq addrA. rewrite [q in q + _ + _]rdivp_eq; move/rmodp_eq0P->. by rewrite addr0 -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0. Qed. Lemma rdivpDr q r : rdvdp d r -> rdivp (q + r) d = rdivp q d + rdivp r d. Proof. by rewrite addrC; move/rdivpDl->; rewrite addrC. Qed. Lemma rdivp_mull p : rdivp (p * d) d = p. Proof. by rewrite -[p * d]addr0 rdivp_addl_mul rdiv0p addr0. Qed. Lemma rmodp_mull p : rmodp (p * d) d = 0. Proof. by apply: rmodp_mull; rewrite (eqP mond); [apply: commr1 | apply: rreg1]. Qed. Lemma rmodpp : rmodp d d = 0. Proof. by apply: rmodpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1]. Qed. Lemma rmodp_addl_mul_small q r : size r < size d -> rmodp (q * d + r) d = r. Proof. by move=> Hd; case: (monic_comreg mond)=> Hc Hr; rewrite /rmodp redivp_eq. Qed. Lemma rmodp_id (p : {poly R}) : rmodp (rmodp p d) d = rmodp p d. Proof. by rewrite rmodp_small // ltn_rmodpN0 // monic_neq0. Qed. Lemma rmodpD p q : rmodp (p + q) d = rmodp p d + rmodp q d. Proof. rewrite [p in LHS]rdivp_eq [q in LHS]rdivp_eq addrACA -mulrDl. rewrite rmodp_addl_mul_small //; apply: (leq_ltn_trans (size_polyD _ _)). by rewrite gtn_max !ltn_rmodp // monic_neq0. Qed. Lemma rmodpN p : rmodp (- p) d = - (rmodp p d). Proof. rewrite {1}(rdivp_eq p) opprD // -mulNr rmodp_addl_mul_small //. by rewrite size_polyN ltn_rmodp // monic_neq0. Qed. Lemma rmodpB p q : rmodp (p - q) d = rmodp p d - rmodp q d. Proof. by rewrite rmodpD rmodpN. Qed. Lemma rmodpZ a p : rmodp (a *: p) d = a *: (rmodp p d). Proof. case: (altP (a =P 0%R)) => [-> | cn0]; first by rewrite !scale0r rmod0p. have -> : ((a *: p) = (a *: (rdivp p d)) * d + a *: (rmodp p d))%R. by rewrite -scalerAl -scalerDr -rdivp_eq. rewrite rmodp_addl_mul_small //. rewrite -mul_polyC; apply: leq_ltn_trans (size_polyMleq _ _) _. rewrite size_polyC cn0 addSn add0n /= ltn_rmodp. exact: monic_neq0. Qed. Lemma rmodp_sum (I : Type) (r : seq I) (P : pred I) (F : I -> {poly R}) : rmodp (\sum_(i <- r | P i) F i) d = (\sum_(i <- r | P i) (rmodp (F i) d)). Proof. by elim/big_rec2: _ => [|i p q _ <-]; rewrite ?(rmod0p, rmodpD). Qed. Lemma rmodp_mulmr p q : rmodp (p * (rmodp q d)) d = rmodp (p * q) d. Proof. by rewrite [q in RHS]rdivp_eq mulrDr rmodpD mulrA rmodp_mull add0r. Qed. Lemma rdvdpp : rdvdp d d. Proof. by apply: rdvdpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1]. Qed. (* section variables impose an inconvenient order on parameters *) Lemma eq_rdvdp q1 p : p = q1 * d -> rdvdp d p. Proof. (* this probably means I need to specify impl args for comm_rref_rdvdp *) move=> h; apply: (@eq_rdvdp _ _ _ _ 1 q1); rewrite (eqP mond). - exact: commr1. - exact: rreg1. by rewrite expr1n mulr1. Qed. Lemma rdvdp_mull p : rdvdp d (p * d). Proof. by apply: rdvdp_mull; rewrite (eqP mond) //; [apply: commr1 | apply: rreg1]. Qed. Lemma rdvdpP p : reflect (exists qq, p = qq * d) (rdvdp d p). Proof. case: (monic_comreg mond)=> Hc Hr; apply: (iffP idP) => [|[qq] /eq_rdvdp //]. by case: rdvdp_eqP=> // k qq; rewrite (eqP mond) expr1n mulr1 => ->; exists qq. Qed. Lemma rdivpK p : rdvdp d p -> (rdivp p d) * d = p. Proof. by move=> dvddp; rewrite [RHS]rdivp_eq rmodp_eq0 ?addr0. Qed. End MonicDivisor. Lemma drop_poly_rdivp n p : drop_poly n p = rdivp p 'X^n. Proof. rewrite -[p in RHS](poly_take_drop n) addrC rdivp_addl_mul ?monicXn//. by rewrite rdivp_small ?addr0// size_polyXn ltnS size_take_poly. Qed. Lemma take_poly_rmodp n p : take_poly n p = rmodp p 'X^n. Proof. have mX := monicXn R n; rewrite -[p in RHS](poly_take_drop n) rmodpD//. by rewrite rmodp_small ?rmodp_mull ?addr0// size_polyXn ltnS size_take_poly. Qed. End RingMonic. Section ComRingMonic. Variable R : comNzRingType. Implicit Types p q r : {poly R}. Variable d : {poly R}. Hypothesis mond : d \is monic. Lemma rmodp_mulml p q : rmodp (rmodp p d * q) d = rmodp (p * q) d. Proof. by rewrite [in LHS]mulrC [in RHS]mulrC rmodp_mulmr. Qed. Lemma rmodpX p n : rmodp ((rmodp p d) ^+ n) d = rmodp (p ^+ n) d. Proof. elim: n => [|n IH]; first by rewrite !expr0. rewrite !exprS -rmodp_mulmr // IH rmodp_mulmr //. by rewrite mulrC rmodp_mulmr // mulrC. Qed. Lemma rmodp_compr p q : rmodp (p \Po (rmodp q d)) d = (rmodp (p \Po q) d). Proof. elim/poly_ind: p => [|p c IH]; first by rewrite !comp_polyC !rmod0p. rewrite !comp_polyD !comp_polyM addrC rmodpD //. rewrite mulrC -rmodp_mulmr // IH rmodp_mulmr //. rewrite !comp_polyX !comp_polyC. by rewrite mulrC rmodp_mulmr // -rmodpD // addrC. Qed. End ComRingMonic. End RingMonic. Module Ring. Include CommonRing. Import RingMonic. Section ExtraMonicDivisor. Variable R : nzRingType. Implicit Types d p q r : {poly R}. Lemma rdivp1 p : rdivp p 1 = p. Proof. by rewrite -[p in LHS]mulr1 rdivp_mull // monic1. Qed. Lemma rdvdp_XsubCl p x : rdvdp ('X - x%:P) p = root p x. Proof. have [HcX Hr] := monic_comreg (monicXsubC x). apply/rmodp_eq0P/factor_theorem => [|[p1 ->]]; last exact/rmodp_mull/monicXsubC. move=> e0; exists (rdivp p ('X - x%:P)). by rewrite [LHS](rdivp_eq (monicXsubC x)) e0 addr0. Qed. Lemma polyXsubCP p x : reflect (p.[x] = 0) (rdvdp ('X - x%:P) p). Proof. by apply: (iffP idP); rewrite rdvdp_XsubCl; move/rootP. Qed. Lemma root_factor_theorem p x : root p x = (rdvdp ('X - x%:P) p). Proof. by rewrite rdvdp_XsubCl. Qed. End ExtraMonicDivisor. End Ring. Module ComRing. Import Ring. Import RingComRreg. Section CommutativeRingPseudoDivision. Variable R : comNzRingType. Implicit Types d p q m n r : {poly R}. Variant redivp_spec (m d : {poly R}) : nat * {poly R} * {poly R} -> Type := EdivnSpec k (q r: {poly R}) of (lead_coef d ^+ k) *: m = q * d + r & (d != 0 -> size r < size d) : redivp_spec m d (k, q, r). Lemma redivpP m d : redivp_spec m d (redivp m d). Proof. rewrite redivp_def; constructor; last by move=> dn0; rewrite ltn_rmodp. by rewrite -mul_polyC mulrC rdivp_eq //= /GRing.comm mulrC. Qed. Lemma rdivp_eq d p : (lead_coef d ^+ rscalp p d) *: p = rdivp p d * d + rmodp p d. Proof. by rewrite /rdivp /rmodp /rscalp; case: redivpP=> k q1 r1 Hc _; apply: Hc. Qed. Lemma rdvdp_eqP d p : rdvdp_spec p d (rmodp p d) (rdvdp d p). Proof. case hdvd: (rdvdp d p); last by move/rmodp_eq0P/eqP/RdvdpN: hdvd. move/rmodp_eq0P: (hdvd)->; apply: (@Rdvdp _ _ _ (rscalp p d) (rdivp p d)). by rewrite mulrC mul_polyC rdivp_eq; move/rmodp_eq0P: (hdvd)->; rewrite addr0. Qed. Lemma rdvdp_eq q p : rdvdp q p = (lead_coef q ^+ rscalp p q *: p == rdivp p q * q). Proof. rewrite rdivp_eq; apply/rmodp_eq0P/eqP => [->|/eqP]; first by rewrite addr0. by rewrite eq_sym addrC -subr_eq subrr; move/eqP<-. Qed. End CommutativeRingPseudoDivision. End ComRing. Module UnitRing. Import Ring. Section UnitRingPseudoDivision. Variable R : unitRingType. Implicit Type p q r d : {poly R}. Lemma uniq_roots_rdvdp p rs : all (root p) rs -> uniq_roots rs -> rdvdp (\prod_(z <- rs) ('X - z%:P)) p. Proof. move=> rrs /(uniq_roots_prod_XsubC rrs) [q ->]. exact/RingMonic.rdvdp_mull/monic_prod_XsubC. Qed. End UnitRingPseudoDivision. End UnitRing. Module IdomainDefs. Import Ring. Section IDomainPseudoDivisionDefs. Variable R : idomainType. Implicit Type p q r d : {poly R}. Definition edivp_expanded_def p q := let: (k, d, r) as edvpq := redivp p q in if lead_coef q \in GRing.unit then (0, (lead_coef q)^-k *: d, (lead_coef q)^-k *: r) else edvpq. Fact edivp_key : unit. Proof. by []. Qed. Definition edivp := locked_with edivp_key edivp_expanded_def. Canonical edivp_unlockable := [unlockable fun edivp]. Definition divp p q := ((edivp p q).1).2. Definition modp p q := (edivp p q).2. Definition scalp p q := ((edivp p q).1).1. Definition dvdp p q := modp q p == 0. Definition eqp p q := (dvdp p q) && (dvdp q p). End IDomainPseudoDivisionDefs. Notation "m %/ d" := (divp m d) : ring_scope. Notation "m %% d" := (modp m d) : ring_scope. Notation "p %| q" := (dvdp p q) : ring_scope. Notation "p %= q" := (eqp p q) : ring_scope. End IdomainDefs. Module WeakIdomain. Import Ring ComRing UnitRing IdomainDefs. Section WeakTheoryForIDomainPseudoDivision. Variable R : idomainType. Implicit Type p q r d : {poly R}. Lemma edivp_def p q : edivp p q = (scalp p q, divp p q, modp p q). Proof. by rewrite /scalp /divp /modp; case: (edivp p q) => [[]] /=. Qed. Lemma edivp_redivp p q : lead_coef q \in GRing.unit = false -> edivp p q = redivp p q. Proof. by move=> hu; rewrite unlock hu; case: (redivp p q) => [[? ?] ?]. Qed. Lemma divpE p q : p %/ q = if lead_coef q \in GRing.unit then lead_coef q ^- rscalp p q *: rdivp p q else rdivp p q. Proof. by case: ifP; rewrite /divp unlock redivp_def => ->. Qed. Lemma modpE p q : p %% q = if lead_coef q \in GRing.unit then lead_coef q ^- rscalp p q *: (rmodp p q) else rmodp p q. Proof. by case: ifP; rewrite /modp unlock redivp_def => ->. Qed. Lemma scalpE p q : scalp p q = if lead_coef q \in GRing.unit then 0 else rscalp p q. Proof. by case: ifP; rewrite /scalp unlock redivp_def => ->. Qed. Lemma dvdpE p q : p %| q = rdvdp p q. Proof. rewrite /dvdp modpE /rdvdp; case ulcq: (lead_coef p \in GRing.unit)=> //. rewrite -[in LHS]size_poly_eq0 size_scale ?size_poly_eq0 //. by rewrite invr_eq0 expf_neq0 //; apply: contraTneq ulcq => ->; rewrite unitr0. Qed. Lemma lc_expn_scalp_neq0 p q : lead_coef q ^+ scalp p q != 0. Proof. have [->|nzq] := eqVneq q 0; last by rewrite expf_neq0 ?lead_coef_eq0. by rewrite /scalp 2!unlock /= eqxx lead_coef0 unitr0 /= oner_neq0. Qed. Hint Resolve lc_expn_scalp_neq0 : core. Variant edivp_spec (m d : {poly R}) : nat * {poly R} * {poly R} -> bool -> Type := |Redivp_spec k (q r: {poly R}) of (lead_coef d ^+ k) *: m = q * d + r & lead_coef d \notin GRing.unit & (d != 0 -> size r < size d) : edivp_spec m d (k, q, r) false |Fedivp_spec (q r: {poly R}) of m = q * d + r & (lead_coef d \in GRing.unit) & (d != 0 -> size r < size d) : edivp_spec m d (0, q, r) true. (* There are several ways to state this fact. The most appropriate statement*) (* might be polished in light of usage. *) Lemma edivpP m d : edivp_spec m d (edivp m d) (lead_coef d \in GRing.unit). Proof. have hC : GRing.comm d (lead_coef d)%:P by rewrite /GRing.comm mulrC. case ud: (lead_coef d \in GRing.unit); last first. rewrite edivp_redivp // redivp_def; constructor; rewrite ?ltn_rmodp // ?ud //. by rewrite rdivp_eq. have cdn0: lead_coef d != 0 by apply: contraTneq ud => ->; rewrite unitr0. rewrite unlock ud redivp_def; constructor => //. rewrite -scalerAl -scalerDr -mul_polyC. have hn0 : (lead_coef d ^+ rscalp m d)%:P != 0. by rewrite polyC_eq0; apply: expf_neq0. apply: (mulfI hn0); rewrite !mulrA -exprVn !polyC_exp -exprMn -polyCM. by rewrite divrr // expr1n mul1r -polyC_exp mul_polyC rdivp_eq. move=> dn0; rewrite size_scale ?ltn_rmodp // -exprVn expf_eq0 negb_and. by rewrite invr_eq0 cdn0 orbT. Qed. Lemma edivp_eq d q r : size r < size d -> lead_coef d \in GRing.unit -> edivp (q * d + r) d = (0, q, r). Proof. have hC : GRing.comm d (lead_coef d)%:P by apply: mulrC. move=> hsrd hu; rewrite unlock hu; case et: (redivp _ _) => [[s qq] rr]. have cdn0 : lead_coef d != 0 by case: eqP hu => //= ->; rewrite unitr0. move: (et); rewrite RingComRreg.redivp_eq //; last exact/rregP. rewrite et /= mulrC (mulrC r) !mul_polyC; case=> <- <-. by rewrite !scalerA mulVr ?scale1r // unitrX. Qed. Lemma divp_eq p q : (lead_coef q ^+ scalp p q) *: p = (p %/ q) * q + (p %% q). Proof. rewrite divpE modpE scalpE. case uq: (lead_coef q \in GRing.unit); last by rewrite rdivp_eq. rewrite expr0 scale1r; have [->|qn0] := eqVneq q 0. by rewrite lead_coef0 expr0n /rscalp unlock eqxx invr1 !scale1r rmodp0 !simp. by rewrite -scalerAl -scalerDr -rdivp_eq scalerA mulVr (scale1r, unitrX). Qed. Lemma dvdp_eq q p : (q %| p) = (lead_coef q ^+ scalp p q *: p == (p %/ q) * q). Proof. rewrite dvdpE rdvdp_eq scalpE divpE; case: ifP => ulcq //. rewrite expr0 scale1r -scalerAl; apply/eqP/eqP => [<- | {2}->]. by rewrite scalerA mulVr ?scale1r // unitrX. by rewrite scalerA mulrV ?scale1r // unitrX. Qed. Lemma divpK d p : d %| p -> p %/ d * d = (lead_coef d ^+ scalp p d) *: p. Proof. by rewrite dvdp_eq; move/eqP->. Qed. Lemma divpKC d p : d %| p -> d * (p %/ d) = (lead_coef d ^+ scalp p d) *: p. Proof. by move=> ?; rewrite mulrC divpK. Qed. Lemma dvdpP q p : reflect (exists2 cqq, cqq.1 != 0 & cqq.1 *: p = cqq.2 * q) (q %| p). Proof. rewrite dvdp_eq; apply: (iffP eqP) => [e | [[c qq] cn0 e]]. by exists (lead_coef q ^+ scalp p q, p %/ q) => //=. apply/eqP; rewrite -dvdp_eq dvdpE. have Ecc: c%:P != 0 by rewrite polyC_eq0. have [->|nz_p] := eqVneq p 0; first by rewrite rdvdp0. pose p1 : {poly R} := lead_coef q ^+ rscalp p q *: qq - c *: (rdivp p q). have E1: c *: rmodp p q = p1 * q. rewrite mulrDl mulNr -scalerAl -e scalerA mulrC -scalerA -scalerAl. by rewrite -scalerBr rdivp_eq addrC addKr. suff: p1 * q == 0 by rewrite -E1 -mul_polyC mulf_eq0 (negPf Ecc). rewrite mulf_eq0; apply/norP; case=> p1_nz q_nz; have:= ltn_rmodp p q. by rewrite q_nz -(size_scale _ cn0) E1 size_mul // polySpred // ltnNge leq_addl. Qed. Lemma mulpK p q : q != 0 -> p * q %/ q = lead_coef q ^+ scalp (p * q) q *: p. Proof. move=> qn0; apply: (rregP qn0); rewrite -scalerAl divp_eq. suff -> : (p * q) %% q = 0 by rewrite addr0. rewrite modpE RingComRreg.rmodp_mull ?scaler0 ?if_same //. by red; rewrite mulrC. by apply/rregP; rewrite lead_coef_eq0. Qed. Lemma mulKp p q : q != 0 -> q * p %/ q = lead_coef q ^+ scalp (p * q) q *: p. Proof. by move=> nzq; rewrite mulrC; apply: mulpK. Qed. Lemma divpp p : p != 0 -> p %/ p = (lead_coef p ^+ scalp p p)%:P. Proof. move=> np0; have := divp_eq p p. suff -> : p %% p = 0 by rewrite addr0 -mul_polyC; move/(mulIf np0). rewrite modpE Ring.rmodpp; last by red; rewrite mulrC. by rewrite scaler0 if_same. Qed. End WeakTheoryForIDomainPseudoDivision. #[global] Hint Resolve lc_expn_scalp_neq0 : core. End WeakIdomain. Module CommonIdomain. Import Ring ComRing UnitRing IdomainDefs WeakIdomain. Section IDomainPseudoDivision. Variable R : idomainType. Implicit Type p q r d m n : {poly R}. Lemma scalp0 p : scalp p 0 = 0. Proof. by rewrite /scalp unlock lead_coef0 unitr0 unlock eqxx. Qed. Lemma divp_small p q : size p < size q -> p %/ q = 0. Proof. move=> spq; rewrite /divp unlock redivp_def /=. by case: ifP; rewrite rdivp_small // scaler0. Qed. Lemma leq_divp p q : (size (p %/ q) <= size p). Proof. rewrite /divp unlock redivp_def /=; case: ifP => ulcq; rewrite ?leq_rdivp //=. rewrite size_scale ?leq_rdivp // -exprVn expf_neq0 // invr_eq0. by case: eqP ulcq => // ->; rewrite unitr0. Qed. Lemma div0p p : 0 %/ p = 0. Proof. by rewrite /divp unlock redivp_def /=; case: ifP; rewrite rdiv0p // scaler0. Qed. Lemma divp0 p : p %/ 0 = 0. Proof. by rewrite /divp unlock redivp_def /=; case: ifP; rewrite rdivp0 // scaler0. Qed. Lemma divp1 m : m %/ 1 = m. Proof. by rewrite divpE lead_coefC unitr1 Ring.rdivp1 expr1n invr1 scale1r. Qed. Lemma modp0 p : p %% 0 = p. Proof. rewrite /modp unlock redivp_def; case: ifP; rewrite rmodp0 //= lead_coef0. by rewrite unitr0. Qed. Lemma mod0p p : 0 %% p = 0. Proof. by rewrite /modp unlock redivp_def /=; case: ifP; rewrite rmod0p // scaler0. Qed. Lemma modp1 p : p %% 1 = 0. Proof. by rewrite /modp unlock redivp_def /=; case: ifP; rewrite rmodp1 // scaler0. Qed. Hint Resolve divp0 divp1 mod0p modp0 modp1 : core. Lemma modp_small p q : size p < size q -> p %% q = p. Proof. move=> spq; rewrite /modp unlock redivp_def; case: ifP; rewrite rmodp_small //. by rewrite /= rscalp_small // expr0 /= invr1 scale1r. Qed. Lemma modpC p c : c != 0 -> p %% c%:P = 0. Proof. move=> cn0; rewrite /modp unlock redivp_def /=; case: ifP; rewrite ?rmodpC //. by rewrite scaler0. Qed. Lemma modp_mull p q : (p * q) %% q = 0. Proof. have [-> | nq0] := eqVneq q 0; first by rewrite modp0 mulr0. have rlcq : GRing.rreg (lead_coef q) by apply/rregP; rewrite lead_coef_eq0. have hC : GRing.comm q (lead_coef q)%:P by red; rewrite mulrC. rewrite modpE; case: ifP => ulcq; rewrite RingComRreg.rmodp_mull //. exact: scaler0. Qed. Lemma modp_mulr d p : (d * p) %% d = 0. Proof. by rewrite mulrC modp_mull. Qed. Lemma modpp d : d %% d = 0. Proof. by rewrite -[d in d %% _]mul1r modp_mull. Qed. Lemma ltn_modp p q : (size (p %% q) < size q) = (q != 0). Proof. rewrite /modp unlock redivp_def /=; case: ifP=> ulcq; rewrite ?ltn_rmodp //=. rewrite size_scale ?ltn_rmodp // -exprVn expf_neq0 // invr_eq0. by case: eqP ulcq => // ->; rewrite unitr0. Qed. Lemma ltn_divpl d q p : d != 0 -> (size (q %/ d) < size p) = (size q < size (p * d)). Proof. move=> dn0. have: (lead_coef d) ^+ (scalp q d) != 0 by apply: lc_expn_scalp_neq0. move/(size_scale q)<-; rewrite divp_eq; have [->|quo0] := eqVneq (q %/ d) 0. rewrite mul0r add0r size_poly0 size_poly_gt0. have [->|pn0] := eqVneq p 0; first by rewrite mul0r size_poly0 ltn0. by rewrite size_mul // (polySpred pn0) addSn ltn_addl // ltn_modp. rewrite size_polyDl; last first. by rewrite size_mul // (polySpred quo0) addSn /= ltn_addl // ltn_modp. have [->|pn0] := eqVneq p 0; first by rewrite mul0r size_poly0 !ltn0. by rewrite !size_mul ?quo0 // (polySpred dn0) !addnS ltn_add2r. Qed. Lemma leq_divpr d p q : d != 0 -> (size p <= size (q %/ d)) = (size (p * d) <= size q). Proof. by move=> dn0; rewrite leqNgt ltn_divpl // -leqNgt. Qed. Lemma divpN0 d p : d != 0 -> (p %/ d != 0) = (size d <= size p). Proof. move=> dn0. by rewrite -[d in RHS]mul1r -leq_divpr // size_polyC oner_eq0 size_poly_gt0. Qed. Lemma size_divp p q : q != 0 -> size (p %/ q) = (size p - (size q).-1)%N. Proof. move=> nq0; case: (leqP (size q) (size p)) => sqp; last first. move: (sqp); rewrite -{1}(ltn_predK sqp) ltnS -subn_eq0 divp_small //. by move/eqP->; rewrite size_poly0. have np0 : p != 0. by rewrite -size_poly_gt0; apply: leq_trans sqp; rewrite size_poly_gt0. have /= := congr1 (size \o @polyseq R) (divp_eq p q). rewrite size_scale; last by rewrite expf_eq0 lead_coef_eq0 (negPf nq0) andbF. have [->|qq0] := eqVneq (p %/ q) 0. by rewrite mul0r add0r=> es; move: nq0; rewrite -(ltn_modp p) -es ltnNge sqp. rewrite size_polyDl. by move->; apply/eqP; rewrite size_mul // (polySpred nq0) addnS /= addnK. rewrite size_mul ?qq0 //. move: nq0; rewrite -(ltn_modp p); move/leq_trans; apply. by rewrite (polySpred qq0) addSn /= leq_addl. Qed. Lemma ltn_modpN0 p q : q != 0 -> size (p %% q) < size q. Proof. by rewrite ltn_modp. Qed. Lemma modp_id p q : (p %% q) %% q = p %% q. Proof. by have [->|qn0] := eqVneq q 0; rewrite ?modp0 // modp_small ?ltn_modp. Qed. Lemma leq_modp m d : size (m %% d) <= size m. Proof. rewrite /modp unlock redivp_def /=; case: ifP; rewrite ?leq_rmodp //. move=> ud; rewrite size_scale ?leq_rmodp // invr_eq0 expf_neq0 //. by apply: contraTneq ud => ->; rewrite unitr0. Qed. Lemma dvdp0 d : d %| 0. Proof. by rewrite /dvdp mod0p. Qed. Hint Resolve dvdp0 : core. Lemma dvd0p p : (0 %| p) = (p == 0). Proof. by rewrite /dvdp modp0. Qed. Lemma dvd0pP p : reflect (p = 0) (0 %| p). Proof. by apply: (iffP idP); rewrite dvd0p; move/eqP. Qed. Lemma dvdpN0 p q : p %| q -> q != 0 -> p != 0. Proof. by move=> pq hq; apply: contraTneq pq => ->; rewrite dvd0p. Qed. Lemma dvdp1 d : (d %| 1) = (size d == 1). Proof. rewrite /dvdp modpE; case ud: (lead_coef d \in GRing.unit); last exact: rdvdp1. rewrite -size_poly_eq0 size_scale; first by rewrite size_poly_eq0 -rdvdp1. by rewrite invr_eq0 expf_neq0 //; apply: contraTneq ud => ->; rewrite unitr0. Qed. Lemma dvd1p m : 1 %| m. Proof. by rewrite /dvdp modp1. Qed. Lemma gtNdvdp p q : p != 0 -> size p < size q -> (q %| p) = false. Proof. by move=> nn0 hs; rewrite /dvdp; rewrite (modp_small hs); apply: negPf. Qed. Lemma modp_eq0P p q : reflect (p %% q = 0) (q %| p). Proof. exact: (iffP eqP). Qed. Lemma modp_eq0 p q : (q %| p) -> p %% q = 0. Proof. exact: modp_eq0P. Qed. Lemma leq_divpl d p q : d %| p -> (size (p %/ d) <= size q) = (size p <= size (q * d)). Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | nd0 hd]. by rewrite divp0 size_poly0 !leq0n. rewrite leq_eqVlt ltn_divpl // (leq_eqVlt (size p)). case lhs: (size p < size (q * d)); rewrite ?orbT ?orbF //. have: (lead_coef d) ^+ (scalp p d) != 0 by rewrite expf_neq0 // lead_coef_eq0. move/(size_scale p)<-; rewrite divp_eq; move/modp_eq0P: hd->; rewrite addr0. have [-> | quon0] := eqVneq (p %/ d) 0. rewrite mul0r size_poly0 2!(eq_sym 0) !size_poly_eq0. by rewrite mulf_eq0 (negPf nd0) orbF. have [-> | nq0] := eqVneq q 0. by rewrite mul0r size_poly0 !size_poly_eq0 mulf_eq0 (negPf nd0) orbF. by rewrite !size_mul // (polySpred nd0) !addnS /= eqn_add2r. Qed. Lemma dvdp_leq p q : q != 0 -> p %| q -> size p <= size q. Proof. move=> nq0 /modp_eq0P. by case: leqP => // /modp_small -> /eqP; rewrite (negPf nq0). Qed. Lemma eq_dvdp c quo q p : c != 0 -> c *: p = quo * q -> q %| p. Proof. move=> cn0; case: (eqVneq p 0) => [->|nz_quo def_quo] //. pose p1 : {poly R} := lead_coef q ^+ scalp p q *: quo - c *: (p %/ q). have E1: c *: (p %% q) = p1 * q. rewrite mulrDl mulNr -scalerAl -def_quo scalerA mulrC -scalerA. by rewrite -scalerAl -scalerBr divp_eq addrAC subrr add0r. rewrite /dvdp; apply/idPn=> m_nz. have: p1 * q != 0 by rewrite -E1 -mul_polyC mulf_neq0 // polyC_eq0. rewrite mulf_eq0; case/norP=> p1_nz q_nz. have := ltn_modp p q; rewrite q_nz -(size_scale (p %% q) cn0) E1. by rewrite size_mul // polySpred // ltnNge leq_addl. Qed. Lemma dvdpp d : d %| d. Proof. by rewrite /dvdp modpp. Qed. Hint Resolve dvdpp : core. Lemma divp_dvd p q : p %| q -> (q %/ p) %| q. Proof. have [-> | np0] := eqVneq p 0; first by rewrite divp0. rewrite dvdp_eq => /eqP h. apply: (@eq_dvdp ((lead_coef p)^+ (scalp q p)) p); last by rewrite mulrC. by rewrite expf_neq0 // lead_coef_eq0. Qed. Lemma dvdp_mull m d n : d %| n -> d %| m * n. Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite mulr0 dvdpp. rewrite dvdp_eq => /eqP e. apply: (@eq_dvdp (lead_coef d ^+ scalp n d) (m * (n %/ d))). by rewrite expf_neq0 // lead_coef_eq0. by rewrite scalerAr e mulrA. Qed. Lemma dvdp_mulr n d m : d %| m -> d %| m * n. Proof. by move=> hdm; rewrite mulrC dvdp_mull. Qed. Hint Resolve dvdp_mull dvdp_mulr : core. Lemma dvdp_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2. Proof. case: (eqVneq d1 0) => [-> /dvd0pP -> | d1n0]; first by rewrite !mul0r dvdpp. case: (eqVneq d2 0) => [-> _ /dvd0pP -> | d2n0]; first by rewrite !mulr0. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Hq1. rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Hq2. apply: (@eq_dvdp (c1 * c2) (q1 * q2)). by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0. rewrite -scalerA scalerAr scalerAl Hq1 Hq2 -!mulrA. by rewrite [d1 * (q2 * _)]mulrCA. Qed. Lemma dvdp_addr m d n : d %| m -> (d %| m + n) = (d %| n). Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite add0r. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1. apply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _. have sn0 : c1 * c2 != 0. by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF. move/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 - c2 *: q1) _ _ sn0). rewrite mulrDl -scaleNr -!scalerAl -Eq1 -Eq2 !scalerA. by rewrite mulNr mulrC scaleNr -scalerBr addrC addKr. have sn0 : c1 * c2 != 0. by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF. move/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 + c2 *: q1) _ _ sn0). by rewrite mulrDl -!scalerAl -Eq1 -Eq2 !scalerA mulrC addrC scalerDr. Qed. Lemma dvdp_addl n d m : d %| n -> (d %| m + n) = (d %| m). Proof. by rewrite addrC; apply: dvdp_addr. Qed. Lemma dvdp_add d m n : d %| m -> d %| n -> d %| m + n. Proof. by move/dvdp_addr->. Qed. Lemma dvdp_add_eq d m n : d %| m + n -> (d %| m) = (d %| n). Proof. by move=> ?; apply/idP/idP; [move/dvdp_addr <-| move/dvdp_addl <-]. Qed. Lemma dvdp_subr d m n : d %| m -> (d %| m - n) = (d %| n). Proof. by move=> ?; apply: dvdp_add_eq; rewrite -addrA addNr simp. Qed. Lemma dvdp_subl d m n : d %| n -> (d %| m - n) = (d %| m). Proof. by move/dvdp_addl<-; rewrite subrK. Qed. Lemma dvdp_sub d m n : d %| m -> d %| n -> d %| m - n. Proof. by move=> *; rewrite dvdp_subl. Qed. Lemma dvdp_mod d n m : d %| n -> (d %| m) = (d %| m %% n). Proof. have [-> | nn0] := eqVneq n 0; first by rewrite modp0. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite modp0. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1. apply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _. have sn0 : c1 * c2 != 0. by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF. pose quo := (c1 * lead_coef n ^+ scalp m n) *: q2 - c2 *: (m %/ n) * q1. move/eqP=> Eq2; apply: (@eq_dvdp _ quo _ _ sn0). rewrite mulrDl mulNr -!scalerAl -!mulrA -Eq1 -Eq2 -scalerAr !scalerA. rewrite mulrC [_ * c2]mulrC mulrA -[((_ * _) * _) *: _]scalerA -scalerBr. by rewrite divp_eq addrC addKr. have sn0 : c1 * c2 * lead_coef n ^+ scalp m n != 0. rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 ?(negPf dn0) ?andbF //. by rewrite (negPf nn0) andbF. move/eqP=> Eq2; apply: (@eq_dvdp _ (c2 *: (m %/ n) * q1 + c1 *: q2) _ _ sn0). rewrite -scalerA divp_eq scalerDr -!scalerA Eq2 scalerAl scalerAr Eq1. by rewrite scalerAl mulrDl mulrA. Qed. Lemma dvdp_trans : transitive (@dvdp R). Proof. move=> n d m. case: (eqVneq d 0) => [-> /dvd0pP -> // | dn0]. case: (eqVneq n 0) => [-> _ /dvd0pP -> // | nn0]. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Hq1. rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Hq2. have sn0 : c1 * c2 != 0 by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0. apply: (@eq_dvdp _ (q2 * q1) _ _ sn0). by rewrite -scalerA Hq2 scalerAr Hq1 mulrA. Qed. Lemma dvdp_mulIl p q : p %| p * q. Proof. exact/dvdp_mulr/dvdpp. Qed. Lemma dvdp_mulIr p q : q %| p * q. Proof. exact/dvdp_mull/dvdpp. Qed. Lemma dvdp_mul2r r p q : r != 0 -> (p * r %| q * r) = (p %| q). Proof. move=> nzr. have [-> | pn0] := eqVneq p 0. by rewrite mul0r !dvd0p mulf_eq0 (negPf nzr) orbF. have [-> | qn0] := eqVneq q 0; first by rewrite mul0r !dvdp0. apply/idP/idP; last by move=> ?; rewrite dvdp_mul ?dvdpp. rewrite dvdp_eq; set c := _ ^+ _; set x := _ %/ _; move/eqP=> Hx. apply: (@eq_dvdp c x); first by rewrite expf_neq0 // lead_coef_eq0 mulf_neq0. by apply: (mulIf nzr); rewrite -mulrA -scalerAl. Qed. Lemma dvdp_mul2l r p q: r != 0 -> (r * p %| r * q) = (p %| q). Proof. by rewrite ![r * _]mulrC; apply: dvdp_mul2r. Qed. Lemma ltn_divpr d p q : d %| q -> (size p < size (q %/ d)) = (size (p * d) < size q). Proof. by move=> dv_d_q; rewrite !ltnNge leq_divpl. Qed. Lemma dvdp_exp d k p : 0 < k -> d %| p -> d %| (p ^+ k). Proof. by case: k => // k _ d_dv_m; rewrite exprS dvdp_mulr. Qed. Lemma dvdp_exp2l d k l : k <= l -> d ^+ k %| d ^+ l. Proof. by move/subnK <-; rewrite exprD dvdp_mull // ?lead_coef_exp ?unitrX. Qed. Lemma dvdp_Pexp2l d k l : 1 < size d -> (d ^+ k %| d ^+ l) = (k <= l). Proof. move=> sd; case: leqP => [|gt_n_m]; first exact: dvdp_exp2l. have dn0 : d != 0 by rewrite -size_poly_gt0; apply: ltn_trans sd. rewrite gtNdvdp ?expf_neq0 // polySpred ?expf_neq0 // size_exp /=. rewrite [size (d ^+ k)]polySpred ?expf_neq0 // size_exp ltnS ltn_mul2l. by move: sd; rewrite -subn_gt0 subn1; move->. Qed. Lemma dvdp_exp2r p q k : p %| q -> p ^+ k %| q ^+ k. Proof. case: (eqVneq p 0) => [-> /dvd0pP -> // | pn0]. rewrite dvdp_eq; set c := _ ^+ _; set t := _ %/ _; move/eqP=> e. apply: (@eq_dvdp (c ^+ k) (t ^+ k)); first by rewrite !expf_neq0 ?lead_coef_eq0. by rewrite -exprMn -exprZn; congr (_ ^+ k). Qed. Lemma dvdp_exp_sub p q k l: p != 0 -> (p ^+ k %| q * p ^+ l) = (p ^+ (k - l) %| q). Proof. move=> pn0; case: (leqP k l)=> [|/ltnW] hkl. move: (hkl); rewrite -subn_eq0; move/eqP->; rewrite expr0 dvd1p. exact/dvdp_mull/dvdp_exp2l. by rewrite -[in LHS](subnK hkl) exprD dvdp_mul2r // expf_eq0 (negPf pn0) andbF. Qed. Lemma dvdp_XsubCl p x : ('X - x%:P) %| p = root p x. Proof. by rewrite dvdpE; apply: Ring.rdvdp_XsubCl. Qed. Lemma root_dvdp p q x : p %| q -> root p x -> root q x. Proof. by rewrite -!dvdp_XsubCl => /[swap]; exact: dvdp_trans. Qed. Lemma polyXsubCP p x : reflect (p.[x] = 0) (('X - x%:P) %| p). Proof. by rewrite dvdpE; apply: Ring.polyXsubCP. Qed. Lemma eqp_div_XsubC p c : (p == (p %/ ('X - c%:P)) * ('X - c%:P)) = ('X - c%:P %| p). Proof. by rewrite dvdp_eq lead_coefXsubC expr1n scale1r. Qed. Lemma root_factor_theorem p x : root p x = (('X - x%:P) %| p). Proof. by rewrite dvdp_XsubCl. Qed. Lemma uniq_roots_dvdp p rs : all (root p) rs -> uniq_roots rs -> (\prod_(z <- rs) ('X - z%:P)) %| p. Proof. move=> rrs; case/(uniq_roots_prod_XsubC rrs)=> q ->. by apply: dvdp_mull; rewrite // (eqP (monic_prod_XsubC _)) unitr1. Qed. Lemma root_bigmul x (ps : seq {poly R}) : ~~root (\big[*%R/1]_(p <- ps) p) x = all (fun p => ~~ root p x) ps. Proof. elim: ps => [|p ps ihp]; first by rewrite big_nil root1. by rewrite big_cons /= rootM negb_or ihp. Qed. Lemma eqpP m n : reflect (exists2 c12, (c12.1 != 0) && (c12.2 != 0) & c12.1 *: m = c12.2 *: n) (m %= n). Proof. apply: (iffP idP) => [| [[c1 c2]/andP[nz_c1 nz_c2 eq_cmn]]]; last first. rewrite /eqp (@eq_dvdp c2 c1%:P) -?eq_cmn ?mul_polyC // (@eq_dvdp c1 c2%:P)//. by rewrite eq_cmn mul_polyC. case: (eqVneq m 0) => [-> /andP [/dvd0pP -> _] | m_nz]. by exists (1, 1); rewrite ?scaler0 // oner_eq0. case: (eqVneq n 0) => [-> /andP [_ /dvd0pP ->] | n_nz /andP []]. by exists (1, 1); rewrite ?scaler0 // oner_eq0. rewrite !dvdp_eq; set c1 := _ ^+ _; set c2 := _ ^+ _. set q1 := _ %/ _; set q2 := _ %/ _; move/eqP => Hq1 /eqP Hq2; have Hc1 : c1 != 0 by rewrite expf_eq0 lead_coef_eq0 negb_and m_nz orbT. have Hc2 : c2 != 0 by rewrite expf_eq0 lead_coef_eq0 negb_and n_nz orbT. have def_q12: q1 * q2 = (c1 * c2)%:P. apply: (mulIf m_nz); rewrite mulrAC mulrC -Hq1 -scalerAr -Hq2 scalerA. by rewrite -mul_polyC. have: q1 * q2 != 0 by rewrite def_q12 -size_poly_eq0 size_polyC mulf_neq0. rewrite mulf_eq0; case/norP=> nz_q1 nz_q2. have: size q2 <= 1. have:= size_mul nz_q1 nz_q2; rewrite def_q12 size_polyC mulf_neq0 //=. by rewrite polySpred // => ->; rewrite leq_addl. rewrite leq_eqVlt ltnS size_poly_leq0 (negPf nz_q2) orbF. case/size_poly1P=> c cn0 cqe; exists (c2, c); first by rewrite Hc2. by rewrite Hq2 -mul_polyC -cqe. Qed. Lemma eqp_eq p q: p %= q -> (lead_coef q) *: p = (lead_coef p) *: q. Proof. move=> /eqpP [[c1 c2] /= /andP [nz_c1 nz_c2]] eq. have/(congr1 lead_coef) := eq; rewrite !lead_coefZ. move=> eqC; apply/(@mulfI _ c2%:P); rewrite ?polyC_eq0 //. by rewrite !mul_polyC scalerA -eqC mulrC -scalerA eq !scalerA mulrC. Qed. Lemma eqpxx : reflexive (@eqp R). Proof. by move=> p; rewrite /eqp dvdpp. Qed. Hint Resolve eqpxx : core. Lemma eqpW p q : p = q -> p %= q. Proof. by move->; rewrite eqpxx. Qed. Lemma eqp_sym : symmetric (@eqp R). Proof. by move=> p q; rewrite /eqp andbC. Qed. Lemma eqp_trans : transitive (@eqp R). Proof. move=> p q r; case/andP=> Dp pD; case/andP=> Dq qD. by rewrite /eqp (dvdp_trans Dp) // (dvdp_trans qD). Qed. Lemma eqp_ltrans : left_transitive (@eqp R). Proof. exact: sym_left_transitive eqp_sym eqp_trans. Qed. Lemma eqp_rtrans : right_transitive (@eqp R). Proof. exact: sym_right_transitive eqp_sym eqp_trans. Qed. Lemma eqp0 p : (p %= 0) = (p == 0). Proof. by apply/idP/eqP => [/andP [_ /dvd0pP] | -> //]. Qed. Lemma eqp01 : 0 %= (1 : {poly R}) = false. Proof. by rewrite eqp_sym eqp0 oner_eq0. Qed. Lemma eqp_scale p c : c != 0 -> c *: p %= p. Proof. move=> c0; apply/eqpP; exists (1, c); first by rewrite c0 oner_eq0. by rewrite scale1r. Qed. Lemma eqp_size p q : p %= q -> size p = size q. Proof. have [->|Eq] := eqVneq q 0; first by rewrite eqp0; move/eqP->. rewrite eqp_sym; have [->|Ep] := eqVneq p 0; first by rewrite eqp0; move/eqP->. by case/andP => Dp Dq; apply: anti_leq; rewrite !dvdp_leq. Qed. Lemma size_poly_eq1 p : (size p == 1) = (p %= 1). Proof. apply/size_poly1P/idP=> [[c cn0 ep] |]. by apply/eqpP; exists (1, c); rewrite ?oner_eq0 // alg_polyC scale1r. by move/eqp_size; rewrite size_poly1; move/eqP/size_poly1P. Qed. Lemma polyXsubC_eqp1 (x : R) : ('X - x%:P %= 1) = false. Proof. by rewrite -size_poly_eq1 size_XsubC. Qed. Lemma dvdp_eqp1 p q : p %| q -> q %= 1 -> p %= 1. Proof. move=> dpq hq. have sizeq : size q == 1 by rewrite size_poly_eq1. have n0q : q != 0 by case: eqP hq => // ->; rewrite eqp01. rewrite -size_poly_eq1 eqn_leq -{1}(eqP sizeq) dvdp_leq //= size_poly_gt0. by apply/eqP => p0; move: dpq n0q; rewrite p0 dvd0p => ->. Qed. Lemma eqp_dvdr q p d: p %= q -> d %| p = (d %| q). Proof. suff Hmn m n: m %= n -> (d %| m) -> (d %| n). by move=> mn; apply/idP/idP; apply: Hmn=> //; rewrite eqp_sym. by rewrite /eqp; case/andP=> pq qp dp; apply: (dvdp_trans dp). Qed. Lemma eqp_dvdl d2 d1 p : d1 %= d2 -> d1 %| p = (d2 %| p). suff Hmn m n: m %= n -> (m %| p) -> (n %| p). by move=> ?; apply/idP/idP; apply: Hmn; rewrite // eqp_sym. by rewrite /eqp; case/andP=> dd' d'd dp; apply: (dvdp_trans d'd). Qed. Lemma dvdpZr c m n : c != 0 -> m %| c *: n = (m %| n). Proof. by move=> cn0; exact/eqp_dvdr/eqp_scale. Qed. Lemma dvdpZl c m n : c != 0 -> (c *: m %| n) = (m %| n). Proof. by move=> cn0; exact/eqp_dvdl/eqp_scale. Qed. Lemma dvdpNl d p : (- d) %| p = (d %| p). Proof. by rewrite -scaleN1r; apply/eqp_dvdl/eqp_scale; rewrite oppr_eq0 oner_neq0. Qed. Lemma dvdpNr d p : d %| (- p) = (d %| p). Proof. by apply: eqp_dvdr; rewrite -scaleN1r eqp_scale ?oppr_eq0 ?oner_eq0. Qed. Lemma eqp_mul2r r p q : r != 0 -> (p * r %= q * r) = (p %= q). Proof. by move=> nz_r; rewrite /eqp !dvdp_mul2r. Qed. Lemma eqp_mul2l r p q: r != 0 -> (r * p %= r * q) = (p %= q). Proof. by move=> nz_r; rewrite /eqp !dvdp_mul2l. Qed. Lemma eqp_mull r p q: q %= r -> p * q %= p * r. Proof. case/eqpP=> [[c d]] /andP [c0 d0 e]; apply/eqpP; exists (c, d); rewrite ?c0 //. by rewrite scalerAr e -scalerAr. Qed. Lemma eqp_mulr q p r : p %= q -> p * r %= q * r. Proof. by move=> epq; rewrite ![_ * r]mulrC eqp_mull. Qed. Lemma eqp_exp p q k : p %= q -> p ^+ k %= q ^+ k. Proof. move=> pq; elim: k=> [|k ihk]; first by rewrite !expr0 eqpxx. by rewrite !exprS (@eqp_trans (q * p ^+ k)) // (eqp_mulr, eqp_mull). Qed. Lemma polyC_eqp1 (c : R) : (c%:P %= 1) = (c != 0). Proof. apply/eqpP/idP => [[[x y]] |nc0] /=. case: (eqVneq c) => [->|] //= /andP [_] /negPf <- /eqP. by rewrite alg_polyC scaler0 eq_sym polyC_eq0. exists (1, c); first by rewrite nc0 /= oner_neq0. by rewrite alg_polyC scale1r. Qed. Lemma dvdUp d p: d %= 1 -> d %| p. Proof. by move/eqp_dvdl->; rewrite dvd1p. Qed. Lemma dvdp_size_eqp p q : p %| q -> size p == size q = (p %= q). Proof. move=> pq; apply/idP/idP; last by move/eqp_size->. have [->|Hq] := eqVneq q 0; first by rewrite size_poly0 size_poly_eq0 eqp0. have [->|Hp] := eqVneq p 0. by rewrite size_poly0 eq_sym size_poly_eq0 eqp_sym eqp0. move: pq; rewrite dvdp_eq; set c := _ ^+ _; set x := _ %/ _; move/eqP=> eqpq. have /= := congr1 (size \o @polyseq R) eqpq. have cn0 : c != 0 by rewrite expf_neq0 // lead_coef_eq0. rewrite (@eqp_size _ q); last exact: eqp_scale. rewrite size_mul ?p0 // => [-> HH|]; last first. apply/eqP=> HH; move: eqpq; rewrite HH mul0r. by move/eqP; rewrite scale_poly_eq0 (negPf Hq) (negPf cn0). suff: size x == 1%N. case/size_poly1P=> y H1y H2y. by apply/eqpP; exists (y, c); rewrite ?H1y // eqpq H2y mul_polyC. case: (size p) HH (size_poly_eq0 p)=> [|n]; first by case: eqP Hp. by rewrite addnS -add1n eqn_add2r; move/eqP->. Qed. Lemma eqp_root p q : p %= q -> root p =1 root q. Proof. move/eqpP=> [[c d]] /andP [c0 d0 e] x; move/negPf:c0=>c0; move/negPf:d0=>d0. by rewrite rootE -[_==_]orFb -c0 -mulf_eq0 -hornerZ e hornerZ mulf_eq0 d0. Qed. Lemma eqp_rmod_mod p q : rmodp p q %= modp p q. Proof. rewrite modpE eqp_sym; case: ifP => ulcq //. apply: eqp_scale; rewrite invr_eq0 //. by apply: expf_neq0; apply: contraTneq ulcq => ->; rewrite unitr0. Qed. Lemma eqp_rdiv_div p q : rdivp p q %= divp p q. Proof. rewrite divpE eqp_sym; case: ifP=> ulcq//; apply: eqp_scale; rewrite invr_eq0//. by apply: expf_neq0; apply: contraTneq ulcq => ->; rewrite unitr0. Qed. Lemma dvd_eqp_divl d p q (dvd_dp : d %| q) (eq_pq : p %= q) : p %/ d %= q %/ d. Proof. case: (eqVneq q 0) eq_pq=> [->|q_neq0]; first by rewrite eqp0=> /eqP->. have d_neq0: d != 0 by apply: contraTneq dvd_dp=> ->; rewrite dvd0p. move=> eq_pq; rewrite -(@eqp_mul2r d) // !divpK // ?(eqp_dvdr _ eq_pq) //. rewrite (eqp_ltrans (eqp_scale _ _)) ?lc_expn_scalp_neq0 //. by rewrite (eqp_rtrans (eqp_scale _ _)) ?lc_expn_scalp_neq0. Qed. Definition gcdp p q := let: (p1, q1) := if size p < size q then (q, p) else (p, q) in if p1 == 0 then q1 else let fix loop (n : nat) (pp qq : {poly R}) {struct n} := let rr := modp pp qq in if rr == 0 then qq else if n is n1.+1 then loop n1 qq rr else rr in loop (size p1) p1 q1. Arguments gcdp : simpl never. Lemma gcd0p : left_id 0 gcdp. Proof. move=> p; rewrite /gcdp size_poly0 size_poly_gt0 if_neg. case: ifP => /= [_ | nzp]; first by rewrite eqxx. by rewrite polySpred !(modp0, nzp) //; case: _.-1 => [|m]; rewrite mod0p eqxx. Qed. Lemma gcdp0 : right_id 0 gcdp. Proof. move=> p; have:= gcd0p p; rewrite /gcdp size_poly0 size_poly_gt0. by case: eqVneq => //= ->; rewrite eqxx. Qed. Lemma gcdpE p q : gcdp p q = if size p < size q then gcdp (modp q p) p else gcdp (modp p q) q. Proof. pose gcdpE_rec := fix gcdpE_rec (n : nat) (pp qq : {poly R}) {struct n} := let rr := modp pp qq in if rr == 0 then qq else if n is n1.+1 then gcdpE_rec n1 qq rr else rr. have Irec: forall k l p q, size q <= k -> size q <= l -> size q < size p -> gcdpE_rec k p q = gcdpE_rec l p q. + elim=> [|m Hrec] [|n] //= p1 q1. - move/size_poly_leq0P=> -> _; rewrite size_poly0 size_poly_gt0 modp0. by move/negPf ->; case: n => [|n] /=; rewrite mod0p eqxx. - move=> _ /size_poly_leq0P ->; rewrite size_poly0 size_poly_gt0 modp0. by move/negPf ->; case: m {Hrec} => [|m] /=; rewrite mod0p eqxx. case: eqP => Epq Sm Sn Sq //; have [->|nzq] := eqVneq q1 0. by case: n m {Sm Sn Hrec} => [|m] [|n] //=; rewrite mod0p eqxx. apply: Hrec; last by rewrite ltn_modp. by rewrite -ltnS (leq_trans _ Sm) // ltn_modp. by rewrite -ltnS (leq_trans _ Sn) // ltn_modp. have [->|nzp] := eqVneq p 0; first by rewrite mod0p modp0 gcd0p gcdp0 if_same. have [->|nzq] := eqVneq q 0; first by rewrite mod0p modp0 gcd0p gcdp0 if_same. rewrite /gcdp !ltn_modp !(negPf nzp, negPf nzq) /=. have [ltpq|leqp] := ltnP; rewrite !(negPf nzp, negPf nzq) /= polySpred //. have [->|nzqp] := eqVneq. by case: (size p) => [|[|s]]; rewrite /= modp0 (negPf nzp) // mod0p eqxx. apply: Irec => //; last by rewrite ltn_modp. by rewrite -ltnS -polySpred // (leq_trans _ ltpq) ?leqW // ltn_modp. by rewrite ltnW // ltn_modp. case: eqVneq => [->|nzpq]. by case: (size q) => [|[|s]]; rewrite /= modp0 (negPf nzq) // mod0p eqxx. apply: Irec => //; rewrite ?ltn_modp //. by rewrite -ltnS -polySpred // (leq_trans _ leqp) // ltn_modp. by rewrite ltnW // ltn_modp. Qed. Lemma size_gcd1p p : size (gcdp 1 p) = 1. Proof. rewrite gcdpE size_polyC oner_eq0 /= modp1; have [|/size1_polyC ->] := ltnP. by rewrite gcd0p size_polyC oner_eq0. have [->|p00] := eqVneq p`_0 0; first by rewrite modp0 gcdp0 size_poly1. by rewrite modpC // gcd0p size_polyC p00. Qed. Lemma size_gcdp1 p : size (gcdp p 1) = 1. Proof. rewrite gcdpE size_polyC oner_eq0 /= modp1 ltnS; case: leqP. by move/size_poly_leq0P->; rewrite gcdp0 modp0 size_polyC oner_eq0. by rewrite gcd0p size_polyC oner_eq0. Qed. Lemma gcdpp : idempotent_op gcdp. Proof. by move=> p; rewrite gcdpE ltnn modpp gcd0p. Qed. Lemma dvdp_gcdlr p q : (gcdp p q %| p) && (gcdp p q %| q). Proof. have [r] := ubnP (minn (size q) (size p)); elim: r => // r IHr in p q *. have [-> | nz_p] := eqVneq p 0; first by rewrite gcd0p dvdpp andbT. have [-> | nz_q] := eqVneq q 0; first by rewrite gcdp0 dvdpp /=. rewrite ltnS gcdpE; case: leqP => [le_pq | lt_pq] le_qr. suffices /IHr/andP[E1 E2]: minn (size q) (size (p %% q)) < r. by rewrite E2 andbT (dvdp_mod _ E2). by rewrite gtn_min orbC (leq_trans _ le_qr) ?ltn_modp. suffices /IHr/andP[E1 E2]: minn (size p) (size (q %% p)) < r. by rewrite E2 (dvdp_mod _ E2). by rewrite gtn_min orbC (leq_trans _ le_qr) ?ltn_modp. Qed. Lemma dvdp_gcdl p q : gcdp p q %| p. Proof. by case/andP: (dvdp_gcdlr p q). Qed. Lemma dvdp_gcdr p q :gcdp p q %| q. Proof. by case/andP: (dvdp_gcdlr p q). Qed. Lemma leq_gcdpl p q : p != 0 -> size (gcdp p q) <= size p. Proof. by move=> pn0; move: (dvdp_gcdl p q); apply: dvdp_leq. Qed. Lemma leq_gcdpr p q : q != 0 -> size (gcdp p q) <= size q. Proof. by move=> qn0; move: (dvdp_gcdr p q); apply: dvdp_leq. Qed. Lemma dvdp_gcd p m n : p %| gcdp m n = (p %| m) && (p %| n). Proof. apply/idP/andP=> [dv_pmn | []]. by rewrite ?(dvdp_trans dv_pmn) ?dvdp_gcdl ?dvdp_gcdr. have [r] := ubnP (minn (size n) (size m)); elim: r => // r IHr in m n *. have [-> | nz_m] := eqVneq m 0; first by rewrite gcd0p. have [-> | nz_n] := eqVneq n 0; first by rewrite gcdp0. rewrite gcdpE ltnS; case: leqP => [le_nm | lt_mn] le_r dv_m dv_n. apply: IHr => //; last by rewrite -(dvdp_mod _ dv_n). by rewrite gtn_min orbC (leq_trans _ le_r) ?ltn_modp. apply: IHr => //; last by rewrite -(dvdp_mod _ dv_m). by rewrite gtn_min orbC (leq_trans _ le_r) ?ltn_modp. Qed. Lemma gcdpC p q : gcdp p q %= gcdp q p. Proof. by rewrite /eqp !dvdp_gcd !dvdp_gcdl !dvdp_gcdr. Qed. Lemma gcd1p p : gcdp 1 p %= 1. Proof. rewrite -size_poly_eq1 gcdpE size_poly1; case: ltnP. by rewrite modp1 gcd0p size_poly1 eqxx. move/size1_polyC=> e; rewrite e. have [->|p00] := eqVneq p`_0 0; first by rewrite modp0 gcdp0 size_poly1. by rewrite modpC // gcd0p size_polyC p00. Qed. Lemma gcdp1 p : gcdp p 1 %= 1. Proof. by rewrite (eqp_ltrans (gcdpC _ _)) gcd1p. Qed. Lemma gcdp_addl_mul p q r: gcdp r (p * r + q) %= gcdp r q. Proof. suff h m n d : gcdp d n %| gcdp d (m * d + n). apply/andP; split => //. by rewrite {2}(_: q = (-p) * r + (p * r + q)) ?H // mulNr addKr. by rewrite dvdp_gcd dvdp_gcdl /= dvdp_addr ?dvdp_gcdr ?dvdp_mull ?dvdp_gcdl. Qed. Lemma gcdp_addl m n : gcdp m (m + n) %= gcdp m n. Proof. by rewrite -[m in m + _]mul1r gcdp_addl_mul. Qed. Lemma gcdp_addr m n : gcdp m (n + m) %= gcdp m n. Proof. by rewrite addrC gcdp_addl. Qed. Lemma gcdp_mull m n : gcdp n (m * n) %= n. Proof. have [-> | nn0] := eqVneq n 0; first by rewrite gcd0p mulr0 eqpxx. have [-> | mn0] := eqVneq m 0; first by rewrite mul0r gcdp0 eqpxx. rewrite gcdpE modp_mull gcd0p size_mul //; case: leqP; last by rewrite eqpxx. rewrite (polySpred mn0) addSn /= -[leqRHS]add0n leq_add2r -ltnS. rewrite -polySpred //= leq_eqVlt ltnS size_poly_leq0 (negPf mn0) orbF. case/size_poly1P=> c cn0 -> {mn0 m}; rewrite mul_polyC. suff -> : n %% (c *: n) = 0 by rewrite gcd0p; apply: eqp_scale. by apply/modp_eq0P; rewrite dvdpZl. Qed. Lemma gcdp_mulr m n : gcdp n (n * m) %= n. Proof. by rewrite mulrC gcdp_mull. Qed. Lemma gcdp_scalel c m n : c != 0 -> gcdp (c *: m) n %= gcdp m n. Proof. move=> cn0; rewrite /eqp dvdp_gcd [gcdp m n %| _]dvdp_gcd !dvdp_gcdr !andbT. apply/andP; split; last first. by apply: dvdp_trans (dvdp_gcdl _ _) _; rewrite dvdpZr. by apply: dvdp_trans (dvdp_gcdl _ _) _; rewrite dvdpZl. Qed. Lemma gcdp_scaler c m n : c != 0 -> gcdp m (c *: n) %= gcdp m n. Proof. move=> cn0; apply: eqp_trans (gcdpC _ _) _. by apply: eqp_trans (gcdp_scalel _ _ _) _ => //; apply: gcdpC. Qed. Lemma dvdp_gcd_idl m n : m %| n -> gcdp m n %= m. Proof. have [-> | mn0] := eqVneq m 0. by rewrite dvd0p => /eqP ->; rewrite gcdp0 eqpxx. rewrite dvdp_eq; move/eqP/(f_equal (gcdp m)) => h. apply: eqp_trans (gcdp_mull (n %/ m) _). by rewrite -h eqp_sym gcdp_scaler // expf_neq0 // lead_coef_eq0. Qed. Lemma dvdp_gcd_idr m n : n %| m -> gcdp m n %= n. Proof. by move/dvdp_gcd_idl; exact/eqp_trans/gcdpC. Qed. Lemma gcdp_exp p k l : gcdp (p ^+ k) (p ^+ l) %= p ^+ minn k l. Proof. case: leqP => [|/ltnW] /subnK <-; rewrite exprD; first exact: gcdp_mull. exact/(eqp_trans (gcdpC _ _))/gcdp_mull. Qed. Lemma gcdp_eq0 p q : gcdp p q == 0 = (p == 0) && (q == 0). Proof. apply/idP/idP; last by case/andP => /eqP -> /eqP ->; rewrite gcdp0. have h m n: gcdp m n == 0 -> (m == 0). by rewrite -(dvd0p m); move/eqP<-; rewrite dvdp_gcdl. by move=> ?; rewrite (h _ q) // (h _ p) // -eqp0 (eqp_ltrans (gcdpC _ _)) eqp0. Qed. Lemma eqp_gcdr p q r : q %= r -> gcdp p q %= gcdp p r. Proof. move=> eqr; rewrite /eqp !(dvdp_gcd, dvdp_gcdl, andbT) /=. by rewrite -(eqp_dvdr _ eqr) dvdp_gcdr (eqp_dvdr _ eqr) dvdp_gcdr. Qed. Lemma eqp_gcdl r p q : p %= q -> gcdp p r %= gcdp q r. Proof. move=> eqr; rewrite /eqp !(dvdp_gcd, dvdp_gcdr, andbT) /=. by rewrite -(eqp_dvdr _ eqr) dvdp_gcdl (eqp_dvdr _ eqr) dvdp_gcdl. Qed. Lemma eqp_gcd p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> gcdp p1 q1 %= gcdp p2 q2. Proof. move=> e1 e2; exact: eqp_trans (eqp_gcdr _ e2) (eqp_gcdl _ e1). Qed. Lemma eqp_rgcd_gcd p q : rgcdp p q %= gcdp p q. Proof. move: {2}(minn (size p) (size q)) (leqnn (minn (size p) (size q))) => n. elim: n p q => [p q|n ihn p q hs]. rewrite leqn0; case: ltnP => _; rewrite size_poly_eq0; move/eqP->. by rewrite gcd0p rgcd0p eqpxx. by rewrite gcdp0 rgcdp0 eqpxx. have [-> | pn0] := eqVneq p 0; first by rewrite gcd0p rgcd0p eqpxx. have [-> | qn0] := eqVneq q 0; first by rewrite gcdp0 rgcdp0 eqpxx. rewrite gcdpE rgcdpE; case: ltnP hs => sp hs. have e := eqp_rmod_mod q p; apply/eqp_trans/ihn: (eqp_gcdl p e). by rewrite (eqp_size e) geq_min -ltnS (leq_trans _ hs) ?ltn_modp. have e := eqp_rmod_mod p q; apply/eqp_trans/ihn: (eqp_gcdl q e). by rewrite (eqp_size e) geq_min -ltnS (leq_trans _ hs) ?ltn_modp. Qed. Lemma gcdp_modl m n : gcdp (m %% n) n %= gcdp m n. Proof. have [/modp_small -> // | lenm] := ltnP (size m) (size n). by rewrite (gcdpE m n) ltnNge lenm. Qed. Lemma gcdp_modr m n : gcdp m (n %% m) %= gcdp m n. Proof. apply: eqp_trans (gcdpC _ _); apply: eqp_trans (gcdp_modl _ _); exact: gcdpC. Qed. Lemma gcdp_def d m n : d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) -> gcdp m n %= d. Proof. move=> dm dn h; rewrite /eqp dvdp_gcd dm dn !andbT. by apply: h; rewrite (dvdp_gcdl, dvdp_gcdr). Qed. Definition coprimep p q := size (gcdp p q) == 1%N. Lemma coprimep_size_gcd p q : coprimep p q -> size (gcdp p q) = 1. Proof. by rewrite /coprimep=> /eqP. Qed. Lemma coprimep_def p q : coprimep p q = (size (gcdp p q) == 1). Proof. done. Qed. Lemma coprimepZl c m n : c != 0 -> coprimep (c *: m) n = coprimep m n. Proof. by move=> ?; rewrite !coprimep_def (eqp_size (gcdp_scalel _ _ _)). Qed. Lemma coprimepZr c m n: c != 0 -> coprimep m (c *: n) = coprimep m n. Proof. by move=> ?; rewrite !coprimep_def (eqp_size (gcdp_scaler _ _ _)). Qed. Lemma coprimepp p : coprimep p p = (size p == 1). Proof. by rewrite coprimep_def gcdpp. Qed. Lemma gcdp_eqp1 p q : gcdp p q %= 1 = coprimep p q. Proof. by rewrite coprimep_def size_poly_eq1. Qed. Lemma coprimep_sym p q : coprimep p q = coprimep q p. Proof. by rewrite -!gcdp_eqp1; apply: eqp_ltrans; rewrite gcdpC. Qed. Lemma coprime1p p : coprimep 1 p. Proof. by rewrite /coprimep -[1%N](size_poly1 R); exact/eqP/eqp_size/gcd1p. Qed. Lemma coprimep1 p : coprimep p 1. Proof. by rewrite coprimep_sym; apply: coprime1p. Qed. Lemma coprimep0 p : coprimep p 0 = (p %= 1). Proof. by rewrite /coprimep gcdp0 size_poly_eq1. Qed. Lemma coprime0p p : coprimep 0 p = (p %= 1). Proof. by rewrite coprimep_sym coprimep0. Qed. (* This is different from coprimeP in div. shall we keep this? *) Lemma coprimepP p q : reflect (forall d, d %| p -> d %| q -> d %= 1) (coprimep p q). Proof. rewrite /coprimep; apply: (iffP idP) => [/eqP hs d dvddp dvddq | h]. have/dvdp_eqp1: d %| gcdp p q by rewrite dvdp_gcd dvddp dvddq. by rewrite -size_poly_eq1 hs; exact. by rewrite size_poly_eq1; case/andP: (dvdp_gcdlr p q); apply: h. Qed. Lemma coprimepPn p q : p != 0 -> reflect (exists d, (d %| gcdp p q) && ~~ (d %= 1)) (~~ coprimep p q). Proof. move=> p0; apply: (iffP idP). by rewrite -gcdp_eqp1=> ng1; exists (gcdp p q); rewrite dvdpp /=. case=> d /andP [dg]; apply: contra; rewrite -gcdp_eqp1=> g1. by move: dg; rewrite (eqp_dvdr _ g1) dvdp1 size_poly_eq1. Qed. Lemma coprimep_dvdl q p r : r %| q -> coprimep p q -> coprimep p r. Proof. move=> rp /coprimepP cpq'; apply/coprimepP => d dp dr. exact/cpq'/(dvdp_trans dr). Qed. Lemma coprimep_dvdr p q r : r %| p -> coprimep p q -> coprimep r q. Proof. by move=> rp; rewrite ![coprimep _ q]coprimep_sym; apply/coprimep_dvdl. Qed. Lemma coprimep_modl p q : coprimep (p %% q) q = coprimep p q. Proof. rewrite !coprimep_def [in RHS]gcdpE. by case: ltnP => // hpq; rewrite modp_small // gcdpE hpq. Qed. Lemma coprimep_modr q p : coprimep q (p %% q) = coprimep q p. Proof. by rewrite ![coprimep q _]coprimep_sym coprimep_modl. Qed. Lemma rcoprimep_coprimep q p : rcoprimep q p = coprimep q p. Proof. by rewrite /coprimep /rcoprimep (eqp_size (eqp_rgcd_gcd _ _)). Qed. Lemma eqp_coprimepr p q r : q %= r -> coprimep p q = coprimep p r. Proof. by rewrite -!gcdp_eqp1; move/(eqp_gcdr p)/eqp_ltrans. Qed. Lemma eqp_coprimepl p q r : q %= r -> coprimep q p = coprimep r p. Proof. by rewrite !(coprimep_sym _ p); apply: eqp_coprimepr. Qed. (* This should be implemented with an extended remainder sequence *) Fixpoint egcdp_rec p q k {struct k} : {poly R} * {poly R} := if k is k'.+1 then if q == 0 then (1, 0) else let: (u, v) := egcdp_rec q (p %% q) k' in (lead_coef q ^+ scalp p q *: v, (u - v * (p %/ q))) else (1, 0). Definition egcdp p q := if size q <= size p then egcdp_rec p q (size q) else let e := egcdp_rec q p (size p) in (e.2, e.1). (* No provable egcd0p *) Lemma egcdp0 p : egcdp p 0 = (1, 0). Proof. by rewrite /egcdp size_poly0. Qed. Lemma egcdp_recP : forall k p q, q != 0 -> size q <= k -> size q <= size p -> let e := (egcdp_rec p q k) in [/\ size e.1 <= size q, size e.2 <= size p & gcdp p q %= e.1 * p + e.2 * q]. Proof. elim=> [|k ihk] p q /= qn0; first by rewrite size_poly_leq0 (negPf qn0). move=> sqSn qsp; rewrite (negPf qn0). have sp : size p > 0 by apply: leq_trans qsp; rewrite size_poly_gt0. have [r0 | rn0] /= := eqVneq (p %%q) 0. rewrite r0 /egcdp_rec; case: k ihk sqSn => [|n] ihn sqSn /=. rewrite !scaler0 !mul0r subr0 add0r mul1r size_poly0 size_poly1. by rewrite dvdp_gcd_idr /dvdp ?r0. rewrite !eqxx mul0r scaler0 /= mul0r add0r subr0 mul1r size_poly0 size_poly1. by rewrite dvdp_gcd_idr /dvdp ?r0 //. have h1 : size (p %% q) <= k. by rewrite -ltnS; apply: leq_trans sqSn; rewrite ltn_modp. have h2 : size (p %% q) <= size q by rewrite ltnW // ltn_modp. have := ihk q (p %% q) rn0 h1 h2. case: (egcdp_rec _ _)=> u v /= => [[ihn'1 ihn'2 ihn'3]]. rewrite gcdpE ltnNge qsp //= (eqp_ltrans (gcdpC _ _)); split; last first. - apply: (eqp_trans ihn'3). rewrite mulrBl addrCA -scalerAl scalerAr -mulrA -mulrBr. by rewrite divp_eq addrAC subrr add0r eqpxx. - apply: (leq_trans (size_polyD _ _)). have [-> | vn0] := eqVneq v 0. rewrite mul0r size_polyN size_poly0 maxn0; apply: leq_trans ihn'1 _. exact: leq_modp. have [-> | qqn0] := eqVneq (p %/ q) 0. rewrite mulr0 size_polyN size_poly0 maxn0; apply: leq_trans ihn'1 _. exact: leq_modp. rewrite geq_max (leq_trans ihn'1) ?leq_modp //= size_polyN size_mul //. move: (ihn'2); rewrite (polySpred vn0) (polySpred qn0). rewrite -(ltn_add2r (size (p %/ q))) !addSn /= ltnS; move/leq_trans; apply. rewrite size_divp // addnBA ?addKn //. by apply: leq_trans qsp; apply: leq_pred. - by rewrite size_scale // lc_expn_scalp_neq0. Qed. Lemma egcdpP p q : p != 0 -> q != 0 -> forall (e := egcdp p q), [/\ size e.1 <= size q, size e.2 <= size p & gcdp p q %= e.1 * p + e.2 * q]. Proof. rewrite /egcdp => pn0 qn0; case: (leqP (size q) (size p)) => /= [|/ltnW] hp. exact: egcdp_recP. case: (egcdp_recP pn0 (leqnn (size p)) hp) => h1 h2 h3; split => //. by rewrite (eqp_ltrans (gcdpC _ _)) addrC. Qed. Lemma egcdpE p q (e := egcdp p q) : gcdp p q %= e.1 * p + e.2 * q. Proof. rewrite {}/e; have [-> /= | qn0] := eqVneq q 0. by rewrite gcdp0 egcdp0 mul1r mulr0 addr0. have [-> | pn0] := eqVneq p 0; last by case: (egcdpP pn0 qn0). by rewrite gcd0p /egcdp size_poly0 size_poly_leq0 (negPf qn0) /= !simp. Qed. Lemma Bezoutp p q : exists u, u.1 * p + u.2 * q %= (gcdp p q). Proof. have [-> | pn0] := eqVneq p 0. by rewrite gcd0p; exists (0, 1); rewrite mul0r mul1r add0r. have [-> | qn0] := eqVneq q 0. by rewrite gcdp0; exists (1, 0); rewrite mul0r mul1r addr0. pose e := egcdp p q; exists e; rewrite eqp_sym. by case: (egcdpP pn0 qn0). Qed. Lemma Bezout_coprimepP p q : reflect (exists u, u.1 * p + u.2 * q %= 1) (coprimep p q). Proof. rewrite -gcdp_eqp1; apply: (iffP idP)=> [g1|]. by case: (Bezoutp p q) => [[u v] Puv]; exists (u, v); apply: eqp_trans g1. case=> [[u v]]; rewrite eqp_sym=> Puv; rewrite /eqp (eqp_dvdr _ Puv). by rewrite dvdp_addr dvdp_mull ?dvdp_gcdl ?dvdp_gcdr //= dvd1p. Qed. Lemma coprimep_root p q x : coprimep p q -> root p x -> q.[x] != 0. Proof. case/Bezout_coprimepP=> [[u v] euv] px0. move/eqpP: euv => [[c1 c2]] /andP /= [c1n0 c2n0 e]. suffices: c1 * (v.[x] * q.[x]) != 0. by rewrite !mulf_eq0 !negb_or c1n0 /=; case/andP. have := f_equal (horner^~ x) e; rewrite /= !hornerZ hornerD. by rewrite !hornerM (eqP px0) mulr0 add0r hornerC mulr1; move->. Qed. Lemma Gauss_dvdpl p q d: coprimep d q -> (d %| p * q) = (d %| p). Proof. move/Bezout_coprimepP=>[[u v] Puv]; apply/idP/idP; last exact: dvdp_mulr. move/(eqp_mull p): Puv; rewrite mulr1 mulrDr eqp_sym=> peq dpq. rewrite (eqp_dvdr _ peq) dvdp_addr; first by rewrite mulrA mulrAC dvdp_mulr. by rewrite mulrA dvdp_mull ?dvdpp. Qed. Lemma Gauss_dvdpr p q d: coprimep d q -> (d %| q * p) = (d %| p). Proof. by rewrite mulrC; apply: Gauss_dvdpl. Qed. (* This could be simplified with the introduction of lcmp *) Lemma Gauss_dvdp m n p : coprimep m n -> (m * n %| p) = (m %| p) && (n %| p). Proof. have [-> | mn0] := eqVneq m 0. by rewrite coprime0p => /eqp_dvdl->; rewrite !mul0r dvd0p dvd1p andbT. have [-> | nn0] := eqVneq n 0. by rewrite coprimep0 => /eqp_dvdl->; rewrite !mulr0 dvd1p. move=> hc; apply/idP/idP => [mnmp | /andP [dmp dnp]]. move/Gauss_dvdpl: hc => <-; move: (dvdp_mull m mnmp); rewrite dvdp_mul2l //. move->; move: (dvdp_mulr n mnmp); rewrite dvdp_mul2r // andbT. exact: dvdp_mulr. move: (dnp); rewrite dvdp_eq. set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> e2. have/esym := Gauss_dvdpl q2 hc; rewrite -e2. have -> : m %| c2 *: p by rewrite -mul_polyC dvdp_mull. rewrite dvdp_eq; set c3 := _ ^+ _; set q3 := _ %/ _; move/eqP=> e3. apply: (@eq_dvdp (c3 * c2) q3). by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0. by rewrite mulrA -e3 -scalerAl -e2 scalerA. Qed. Lemma Gauss_gcdpr p m n : coprimep p m -> gcdp p (m * n) %= gcdp p n. Proof. move=> co_pm; apply/eqP; rewrite /eqp !dvdp_gcd !dvdp_gcdl /= andbC. rewrite dvdp_mull ?dvdp_gcdr // -(@Gauss_dvdpl _ m). by rewrite mulrC dvdp_gcdr. apply/coprimepP=> d; rewrite dvdp_gcd; case/andP=> hdp _ hdm. by move/coprimepP: co_pm; apply. Qed. Lemma Gauss_gcdpl p m n : coprimep p n -> gcdp p (m * n) %= gcdp p m. Proof. by move=> co_pn; rewrite mulrC Gauss_gcdpr. Qed. Lemma coprimepMr p q r : coprimep p (q * r) = (coprimep p q && coprimep p r). Proof. apply/coprimepP/andP=> [hp | [/coprimepP-hq hr]]. by split; apply/coprimepP=> d dp dq; rewrite hp //; [apply/dvdp_mulr | apply/dvdp_mull]. move=> d dp dqr; move/(_ _ dp) in hq. rewrite Gauss_dvdpl in dqr; first exact: hq. by move/coprimep_dvdr: hr; apply. Qed. Lemma coprimepMl p q r: coprimep (q * r) p = (coprimep q p && coprimep r p). Proof. by rewrite ![coprimep _ p]coprimep_sym coprimepMr. Qed. Lemma modp_coprime k u n : k != 0 -> (k * u) %% n %= 1 -> coprimep k n. Proof. move=> kn0 hmod; apply/Bezout_coprimepP. exists (((lead_coef n)^+(scalp (k * u) n) *: u), (- (k * u %/ n))). rewrite -scalerAl mulrC (divp_eq (u * k) n) mulNr -addrAC subrr add0r. by rewrite mulrC. Qed. Lemma coprimep_pexpl k m n : 0 < k -> coprimep (m ^+ k) n = coprimep m n. Proof. case: k => // k _; elim: k => [|k IHk]; first by rewrite expr1. by rewrite exprS coprimepMl -IHk andbb. Qed. Lemma coprimep_pexpr k m n : 0 < k -> coprimep m (n ^+ k) = coprimep m n. Proof. by move=> k_gt0; rewrite !(coprimep_sym m) coprimep_pexpl. Qed. Lemma coprimep_expl k m n : coprimep m n -> coprimep (m ^+ k) n. Proof. by case: k => [|k] co_pm; rewrite ?coprime1p // coprimep_pexpl. Qed. Lemma coprimep_expr k m n : coprimep m n -> coprimep m (n ^+ k). Proof. by rewrite !(coprimep_sym m); apply: coprimep_expl. Qed. Lemma gcdp_mul2l p q r : gcdp (p * q) (p * r) %= (p * gcdp q r). Proof. have [->|hp] := eqVneq p 0; first by rewrite !mul0r gcdp0 eqpxx. rewrite /eqp !dvdp_gcd !dvdp_mul2l // dvdp_gcdr dvdp_gcdl !andbT. move: (Bezoutp q r) => [[u v]] huv. rewrite eqp_sym in huv; rewrite (eqp_dvdr _ (eqp_mull _ huv)). rewrite mulrDr ![p * (_ * _)]mulrCA. by apply: dvdp_add; rewrite dvdp_mull// (dvdp_gcdr, dvdp_gcdl). Qed. Lemma gcdp_mul2r q r p : gcdp (q * p) (r * p) %= gcdp q r * p. Proof. by rewrite ![_ * p]mulrC gcdp_mul2l. Qed. Lemma mulp_gcdr p q r : r * (gcdp p q) %= gcdp (r * p) (r * q). Proof. by rewrite eqp_sym gcdp_mul2l. Qed. Lemma mulp_gcdl p q r : (gcdp p q) * r %= gcdp (p * r) (q * r). Proof. by rewrite eqp_sym gcdp_mul2r. Qed. Lemma coprimep_div_gcd p q : (p != 0) || (q != 0) -> coprimep (p %/ (gcdp p q)) (q %/ gcdp p q). Proof. rewrite -negb_and -gcdp_eq0 -gcdp_eqp1 => gpq0. rewrite -(@eqp_mul2r (gcdp p q)) // mul1r (eqp_ltrans (mulp_gcdl _ _ _)). have: gcdp p q %| p by rewrite dvdp_gcdl. have: gcdp p q %| q by rewrite dvdp_gcdr. rewrite !dvdp_eq => /eqP <- /eqP <-. have lcn0 k : (lead_coef (gcdp p q)) ^+ k != 0. by rewrite expf_neq0 ?lead_coef_eq0. by apply: eqp_gcd; rewrite ?eqp_scale. Qed. Lemma divp_eq0 p q : (p %/ q == 0) = [|| p == 0, q ==0 | size p < size q]. Proof. apply/eqP/idP=> [d0|]; last first. case/or3P; [by move/eqP->; rewrite div0p| by move/eqP->; rewrite divp0|]. by move/divp_small. case: eqVneq => // _; case: eqVneq => // qn0. move: (divp_eq p q); rewrite d0 mul0r add0r. move/(f_equal (fun x : {poly R} => size x)). by rewrite size_scale ?lc_expn_scalp_neq0 // => ->; rewrite ltn_modp qn0 !orbT. Qed. Lemma dvdp_div_eq0 p q : q %| p -> (p %/ q == 0) = (p == 0). Proof. move=> dvdp_qp; have [->|p_neq0] := eqVneq p 0; first by rewrite div0p eqxx. rewrite divp_eq0 ltnNge dvdp_leq // (negPf p_neq0) orbF /=. by apply: contraTF dvdp_qp=> /eqP ->; rewrite dvd0p. Qed. Lemma Bezout_coprimepPn p q : p != 0 -> q != 0 -> reflect (exists2 uv : {poly R} * {poly R}, (0 < size uv.1 < size q) && (0 < size uv.2 < size p) & uv.1 * p = uv.2 * q) (~~ (coprimep p q)). Proof. move=> pn0 qn0; apply: (iffP idP); last first. case=> [[u v] /= /andP [/andP [ps1 s1] /andP [ps2 s2]] e]. have: ~~(size (q * p) <= size (u * p)). rewrite -ltnNge !size_mul // -?size_poly_gt0 // (polySpred pn0) !addnS. by rewrite ltn_add2r. apply: contra => ?; apply: dvdp_leq; rewrite ?mulf_neq0 // -?size_poly_gt0 //. by rewrite mulrC Gauss_dvdp // dvdp_mull // e dvdp_mull. rewrite coprimep_def neq_ltn ltnS size_poly_leq0 gcdp_eq0. rewrite (negPf pn0) (negPf qn0) /=. case sg: (size (gcdp p q)) => [|n] //; case: n sg=> [|n] // sg _. move: (dvdp_gcdl p q); rewrite dvdp_eq; set c1 := _ ^+ _; move/eqP=> hu1. move: (dvdp_gcdr p q); rewrite dvdp_eq; set c2 := _ ^+ _; move/eqP=> hv1. exists (c1 *: (q %/ gcdp p q), c2 *: (p %/ gcdp p q)); last first. by rewrite -!scalerAl !scalerAr hu1 hv1 mulrCA. rewrite !size_scale ?lc_expn_scalp_neq0 //= !size_poly_gt0 !divp_eq0. rewrite gcdp_eq0 !(negPf pn0) !(negPf qn0) /= -!leqNgt leq_gcdpl //. rewrite leq_gcdpr //= !ltn_divpl -?size_poly_eq0 ?sg //. rewrite !size_mul // -?size_poly_eq0 ?sg // ![(_ + n.+2)%N]addnS /=. by rewrite -!(addn1 (size _)) !leq_add2l. Qed. Lemma dvdp_pexp2r m n k : k > 0 -> (m ^+ k %| n ^+ k) = (m %| n). Proof. move=> k_gt0; apply/idP/idP; last exact: dvdp_exp2r. have [-> // | nn0] := eqVneq n 0; have [-> | mn0] := eqVneq m 0. move/prednK: k_gt0=> {1}<-; rewrite exprS mul0r //= !dvd0p expf_eq0. by case/andP=> _ ->. set d := gcdp m n; have := dvdp_gcdr m n; rewrite -/d dvdp_eq. set c1 := _ ^+ _; set n' := _ %/ _; move/eqP=> def_n. have := dvdp_gcdl m n; rewrite -/d dvdp_eq. set c2 := _ ^+ _; set m' := _ %/ _; move/eqP=> def_m. have dn0 : d != 0 by rewrite gcdp_eq0 negb_and nn0 orbT. have c1n0 : c1 != 0 by rewrite !expf_neq0 // lead_coef_eq0. have c2n0 : c2 != 0 by rewrite !expf_neq0 // lead_coef_eq0. have c2k_n0 : c2 ^+ k != 0 by rewrite !expf_neq0 // lead_coef_eq0. rewrite -(@dvdpZr (c1 ^+ k)) ?expf_neq0 ?lead_coef_eq0 //. rewrite -(@dvdpZl (c2 ^+ k)) // -!exprZn def_m def_n !exprMn. rewrite dvdp_mul2r ?expf_neq0 //. have: coprimep (m' ^+ k) (n' ^+ k). by rewrite coprimep_pexpl // coprimep_pexpr // coprimep_div_gcd ?mn0. move/coprimepP=> hc hd. have /size_poly1P [c cn0 em'] : size m' == 1. case: (eqVneq m' 0) def_m => [-> /eqP | m'_n0 def_m]. by rewrite mul0r scale_poly_eq0 (negPf mn0) (negPf c2n0). have := hc _ (dvdpp _) hd; rewrite -size_poly_eq1. rewrite polySpred; last by rewrite expf_eq0 negb_and m'_n0 orbT. by rewrite size_exp eqSS muln_eq0 orbC eqn0Ngt k_gt0 /= -eqSS -polySpred. rewrite -(@dvdpZl c2) // def_m em' mul_polyC dvdpZl //. by rewrite -(@dvdpZr c1) // def_n dvdp_mull. Qed. Lemma root_gcd p q x : root (gcdp p q) x = root p x && root q x. Proof. rewrite /= !root_factor_theorem; apply/idP/andP=> [dg| [dp dq]]. by split; apply: dvdp_trans dg _; rewrite ?(dvdp_gcdl, dvdp_gcdr). have:= Bezoutp p q => [[[u v]]]; rewrite eqp_sym=> e. by rewrite (eqp_dvdr _ e) dvdp_addl dvdp_mull. Qed. Lemma root_biggcd x (ps : seq {poly R}) : root (\big[gcdp/0]_(p <- ps) p) x = all (fun p => root p x) ps. Proof. elim: ps => [|p ps ihp]; first by rewrite big_nil root0. by rewrite big_cons /= root_gcd ihp. Qed. (* "gdcop Q P" is the Greatest Divisor of P which is coprime to Q *) (* if P null, we pose that gdcop returns 1 if Q null, 0 otherwise*) Fixpoint gdcop_rec q p k := if k is m.+1 then if coprimep p q then p else gdcop_rec q (divp p (gcdp p q)) m else (q == 0)%:R. Definition gdcop q p := gdcop_rec q p (size p). Variant gdcop_spec q p : {poly R} -> Type := GdcopSpec r of (dvdp r p) & ((coprimep r q) || (p == 0)) & (forall d, dvdp d p -> coprimep d q -> dvdp d r) : gdcop_spec q p r. Lemma gdcop0 q : gdcop q 0 = (q == 0)%:R. Proof. by rewrite /gdcop size_poly0. Qed. Lemma gdcop_recP q p k : size p <= k -> gdcop_spec q p (gdcop_rec q p k). Proof. elim: k p => [p | k ihk p] /=. move/size_poly_leq0P->. have [->|q0] := eqVneq; split; rewrite ?coprime1p // ?eqxx ?orbT //. by move=> d _; rewrite coprimep0 dvdp1 size_poly_eq1. move=> hs; case cop : (coprimep _ _); first by split; rewrite ?dvdpp ?cop. have [-> | p0] := eqVneq p 0. by rewrite div0p; apply: ihk; rewrite size_poly0 leq0n. have [-> | q0] := eqVneq q 0. rewrite gcdp0 divpp ?p0 //= => {hs ihk}; case: k=> /=. rewrite eqxx; split; rewrite ?dvd1p ?coprimep0 ?eqpxx //=. by move=> d _; rewrite coprimep0 dvdp1 size_poly_eq1. move=> n; rewrite coprimep0 polyC_eqp1 //; rewrite lc_expn_scalp_neq0. split; first by rewrite (@eqp_dvdl 1) ?dvd1p // polyC_eqp1 lc_expn_scalp_neq0. by rewrite coprimep0 polyC_eqp1 // ?lc_expn_scalp_neq0. by move=> d _; rewrite coprimep0; move/eqp_dvdl->; rewrite dvd1p. move: (dvdp_gcdl p q); rewrite dvdp_eq; move/eqP=> e. have sgp : size (gcdp p q) <= size p. by apply: dvdp_leq; rewrite ?gcdp_eq0 ?p0 ?q0 // dvdp_gcdl. have : p %/ gcdp p q != 0; last move/negPf=>p'n0. apply: dvdpN0 (dvdp_mulIl (p %/ gcdp p q) (gcdp p q)) _. by rewrite -e scale_poly_eq0 negb_or lc_expn_scalp_neq0. have gn0 : gcdp p q != 0. apply: dvdpN0 (dvdp_mulIr (p %/ gcdp p q) (gcdp p q)) _. by rewrite -e scale_poly_eq0 negb_or lc_expn_scalp_neq0. have sp' : size (p %/ (gcdp p q)) <= k. rewrite size_divp ?sgp // leq_subLR (leq_trans hs) // -add1n leq_add2r -subn1. by rewrite ltn_subRL add1n ltn_neqAle eq_sym [_ == _]cop size_poly_gt0 gn0. case (ihk _ sp')=> r' dr'p'; first rewrite p'n0 orbF=> cr'q maxr'. constructor=> //=; rewrite ?(negPf p0) ?orbF //. exact/(dvdp_trans dr'p')/divp_dvd/dvdp_gcdl. move=> d dp cdq; apply: maxr'; last by rewrite cdq. case dpq: (d %| gcdp p q). move: (dpq); rewrite dvdp_gcd dp /= => dq; apply: dvdUp. apply: contraLR cdq => nd1; apply/coprimepPn; last first. by exists d; rewrite dvdp_gcd dvdpp dq nd1. by apply: contraNneq p0 => d0; move: dp; rewrite d0 dvd0p. apply: contraLR dp => ndp'. rewrite (@eqp_dvdr ((lead_coef (gcdp p q) ^+ scalp p (gcdp p q))*:p)). by rewrite e; rewrite Gauss_dvdpl //; apply: (coprimep_dvdl (dvdp_gcdr _ _)). by rewrite eqp_sym eqp_scale // lc_expn_scalp_neq0. Qed. Lemma gdcopP q p : gdcop_spec q p (gdcop q p). Proof. by rewrite /gdcop; apply: gdcop_recP. Qed. Lemma coprimep_gdco p q : (q != 0)%B -> coprimep (gdcop p q) p. Proof. by move=> q_neq0; case: gdcopP=> d; rewrite (negPf q_neq0) orbF. Qed. Lemma size2_dvdp_gdco p q d : p != 0 -> size d = 2 -> (d %| (gdcop q p)) = (d %| p) && ~~(d %| q). Proof. have [-> | dn0] := eqVneq d 0; first by rewrite size_poly0. move=> p0 sd; apply/idP/idP. case: gdcopP=> r rp crq maxr dr; move/negPf: (p0)=> p0f. rewrite (dvdp_trans dr) //=. apply: contraL crq => dq; rewrite p0f orbF; apply/coprimepPn. by apply: contraNneq p0 => r0; move: rp; rewrite r0 dvd0p. by exists d; rewrite dvdp_gcd dr dq -size_poly_eq1 sd. case/andP=> dp dq; case: gdcopP=> r rp crq maxr; apply: maxr=> //. apply/coprimepP=> x xd xq. move: (dvdp_leq dn0 xd); rewrite leq_eqVlt sd; case/orP; last first. rewrite ltnS leq_eqVlt ltnS size_poly_leq0 orbC. case/predU1P => [x0|]; last by rewrite -size_poly_eq1. by move: xd; rewrite x0 dvd0p (negPf dn0). by rewrite -sd dvdp_size_eqp //; move/(eqp_dvdl q); rewrite xq (negPf dq). Qed. Lemma dvdp_gdco p q : (gdcop p q) %| q. Proof. by case: gdcopP. Qed. Lemma root_gdco p q x : p != 0 -> root (gdcop q p) x = root p x && ~~(root q x). Proof. move=> p0 /=; rewrite !root_factor_theorem. apply: size2_dvdp_gdco; rewrite ?p0 //. by rewrite size_polyDl size_polyX // size_polyN size_polyC ltnS; case: (x != 0). Qed. Lemma dvdp_comp_poly r p q : (p %| q) -> (p \Po r) %| (q \Po r). Proof. have [-> | pn0] := eqVneq p 0. by rewrite comp_poly0 !dvd0p; move/eqP->; rewrite comp_poly0. rewrite dvdp_eq; set c := _ ^+ _; set s := _ %/ _; move/eqP=> Hq. apply: (@eq_dvdp c (s \Po r)); first by rewrite expf_neq0 // lead_coef_eq0. by rewrite -comp_polyZ Hq comp_polyM. Qed. Lemma gcdp_comp_poly r p q : gcdp p q \Po r %= gcdp (p \Po r) (q \Po r). Proof. apply/andP; split. by rewrite dvdp_gcd !dvdp_comp_poly ?dvdp_gcdl ?dvdp_gcdr. case: (Bezoutp p q) => [[u v]] /andP []. move/(dvdp_comp_poly r) => Huv _. rewrite (dvdp_trans _ Huv) // comp_polyD !comp_polyM. by rewrite dvdp_add // dvdp_mull //; [ exact: dvdp_gcdl | exact: dvdp_gcdr]. Qed. Lemma coprimep_comp_poly r p q : coprimep p q -> coprimep (p \Po r) (q \Po r). Proof. rewrite -!gcdp_eqp1 -!size_poly_eq1 -!dvdp1; move/(dvdp_comp_poly r). rewrite comp_polyC => Hgcd. by apply: dvdp_trans Hgcd; case/andP: (gcdp_comp_poly r p q). Qed. Lemma coprimep_addl_mul p q r : coprimep r (p * r + q) = coprimep r q. Proof. by rewrite !coprimep_def (eqp_size (gcdp_addl_mul _ _ _)). Qed. Definition irreducible_poly p := (size p > 1) * (forall q, size q != 1 -> q %| p -> q %= p) : Prop. Lemma irredp_neq0 p : irreducible_poly p -> p != 0. Proof. by rewrite -size_poly_gt0 => [[/ltnW]]. Qed. Definition apply_irredp p (irr_p : irreducible_poly p) := irr_p.2. Coercion apply_irredp : irreducible_poly >-> Funclass. Lemma modp_XsubC p c : p %% ('X - c%:P) = p.[c]%:P. Proof. have/factor_theorem [q /(canRL (subrK _)) Dp]: root (p - p.[c]%:P) c. by rewrite /root !hornerE subrr. rewrite modpE /= lead_coefXsubC unitr1 expr1n invr1 scale1r [in LHS]Dp. rewrite RingMonic.rmodp_addl_mul_small // ?monicXsubC// size_XsubC size_polyC. by case: (p.[c] == 0). Qed. Lemma coprimep_XsubC p c : coprimep p ('X - c%:P) = ~~ root p c. Proof. rewrite -coprimep_modl modp_XsubC /root -alg_polyC. have [-> | /coprimepZl->] := eqVneq; last exact: coprime1p. by rewrite scale0r /coprimep gcd0p size_XsubC. Qed. Lemma coprimep_XsubC2 (a b : R) : b - a != 0 -> coprimep ('X - a%:P) ('X - b%:P). Proof. by move=> bBa_neq0; rewrite coprimep_XsubC rootE hornerXsubC. Qed. Lemma coprimepX p : coprimep p 'X = ~~ root p 0. Proof. by rewrite -['X]subr0 coprimep_XsubC. Qed. Lemma eqp_monic : {in monic &, forall p q, (p %= q) = (p == q)}. Proof. move=> p q monic_p monic_q; apply/idP/eqP=> [|-> //]. case/eqpP=> [[a b] /= /andP[a_neq0 _] eq_pq]. apply: (@mulfI _ a%:P); first by rewrite polyC_eq0. rewrite !mul_polyC eq_pq; congr (_ *: q); apply: (mulIf (oner_neq0 _)). by rewrite -[in LHS](monicP monic_q) -(monicP monic_p) -!lead_coefZ eq_pq. Qed. Lemma dvdp_mul_XsubC p q c : (p %| ('X - c%:P) * q) = ((if root p c then p %/ ('X - c%:P) else p) %| q). Proof. case: ifPn => [| not_pc0]; last by rewrite Gauss_dvdpr ?coprimep_XsubC. rewrite root_factor_theorem -eqp_div_XsubC mulrC => /eqP{1}->. by rewrite dvdp_mul2l ?polyXsubC_eq0. Qed. Lemma dvdp_prod_XsubC (I : Type) (r : seq I) (F : I -> R) p : p %| \prod_(i <- r) ('X - (F i)%:P) -> {m | p %= \prod_(i <- mask m r) ('X - (F i)%:P)}. Proof. elim: r => [|i r IHr] in p *. by rewrite big_nil dvdp1; exists nil; rewrite // big_nil -size_poly_eq1. rewrite big_cons dvdp_mul_XsubC root_factor_theorem -eqp_div_XsubC. case: eqP => [{2}-> | _] /IHr[m Dp]; last by exists (false :: m). by exists (true :: m); rewrite /= mulrC big_cons eqp_mul2l ?polyXsubC_eq0. Qed. Lemma irredp_XsubC (x : R) : irreducible_poly ('X - x%:P). Proof. split=> [|d size_d d_dv_Xx]; first by rewrite size_XsubC. have: ~ d %= 1 by apply/negP; rewrite -size_poly_eq1. have [|m /=] := @dvdp_prod_XsubC _ [:: x] id d; first by rewrite big_seq1. by case: m => [|[] [|_ _] /=]; rewrite (big_nil, big_seq1). Qed. Lemma irredp_XaddC (x : R) : irreducible_poly ('X + x%:P). Proof. by rewrite -[x]opprK rmorphN; apply: irredp_XsubC. Qed. Lemma irredp_XsubCP d p : irreducible_poly p -> d %| p -> {d %= 1} + {d %= p}. Proof. move=> irred_p dvd_dp; have [] := boolP (_ %= 1); first by left. by rewrite -size_poly_eq1=> /irred_p /(_ dvd_dp); right. Qed. Lemma dvdp_exp_XsubCP (p : {poly R}) (c : R) (n : nat) : reflect (exists2 k, (k <= n)%N & p %= ('X - c%:P) ^+ k) (p %| ('X - c%:P) ^+ n). Proof. apply: (iffP idP) => [|[k lkn /eqp_dvdl->]]; last by rewrite dvdp_exp2l. move=> /Pdiv.WeakIdomain.dvdpP[[/= a q] a_neq0]. have [m [r]] := multiplicity_XsubC p c; have [->|pN0]/= := eqVneq p 0. rewrite mulr0 => _ _ /eqP; rewrite scale_poly_eq0 (negPf a_neq0)/=. by rewrite expf_eq0/= andbC polyXsubC_eq0. move=> rNc ->; rewrite mulrA => eq_qrm; exists m. have: ('X - c%:P) ^+ m %| a *: ('X - c%:P) ^+ n by rewrite eq_qrm dvdp_mull. by rewrite (eqp_dvdr _ (eqp_scale _ _))// dvdp_Pexp2l// size_XsubC. suff /eqP : size r = 1%N. by rewrite size_poly_eq1 => /eqp_mulr/eqp_trans->//; rewrite mul1r eqpxx. have : r %| a *: ('X - c%:P) ^+ n by rewrite eq_qrm mulrAC dvdp_mull. rewrite (eqp_dvdr _ (eqp_scale _ _))//. move: rNc; rewrite -coprimep_XsubC => /(coprimep_expr n) /coprimepP. by move=> /(_ _ (dvdpp _)); rewrite -size_poly_eq1 => /(_ _)/eqP. Qed. End IDomainPseudoDivision. Arguments gcdp : simpl never. #[global] Hint Resolve eqpxx divp0 divp1 mod0p modp0 modp1 : core. #[global] Hint Resolve dvdp_mull dvdp_mulr dvdpp dvdp0 : core. Arguments dvdp_exp_XsubCP {R p c n}. End CommonIdomain. Module Idomain. Include IdomainDefs. Export IdomainDefs. Include WeakIdomain. Include CommonIdomain. End Idomain. Module IdomainMonic. Import Ring ComRing UnitRing IdomainDefs Idomain. Section IdomainMonic. Variable R : idomainType. Implicit Type p d r : {poly R}. Section MonicDivisor. Variable q : {poly R}. Hypothesis monq : q \is monic. Lemma divpE p : p %/ q = rdivp p q. Proof. by rewrite divpE (eqP monq) unitr1 expr1n invr1 scale1r. Qed. Lemma modpE p : p %% q = rmodp p q. Proof. by rewrite modpE (eqP monq) unitr1 expr1n invr1 scale1r. Qed. Lemma scalpE p : scalp p q = 0. Proof. by rewrite scalpE (eqP monq) unitr1. Qed. Lemma divp_eq p : p = (p %/ q) * q + (p %% q). Proof. by rewrite -divp_eq (eqP monq) expr1n scale1r. Qed. Lemma divpp p : q %/ q = 1. Proof. by rewrite divpp ?monic_neq0 // (eqP monq) expr1n. Qed. Lemma dvdp_eq p : (q %| p) = (p == (p %/ q) * q). Proof. by rewrite dvdp_eq (eqP monq) expr1n scale1r. Qed. Lemma dvdpP p : reflect (exists qq, p = qq * q) (q %| p). Proof. apply: (iffP idP); first by rewrite dvdp_eq; move/eqP=> e; exists (p %/ q). by case=> qq ->; rewrite dvdp_mull // dvdpp. Qed. Lemma mulpK p : p * q %/ q = p. Proof. by rewrite mulpK ?monic_neq0 // (eqP monq) expr1n scale1r. Qed. Lemma mulKp p : q * p %/ q = p. Proof. by rewrite mulrC mulpK. Qed. End MonicDivisor. Lemma drop_poly_divp n p : drop_poly n p = p %/ 'X^n. Proof. by rewrite RingMonic.drop_poly_rdivp divpE // monicXn. Qed. Lemma take_poly_modp n p : take_poly n p = p %% 'X^n. Proof. by rewrite RingMonic.take_poly_rmodp modpE // monicXn. Qed. End IdomainMonic. End IdomainMonic. Module IdomainUnit. Import Ring ComRing UnitRing IdomainDefs Idomain. Section UnitDivisor. Variable R : idomainType. Variable d : {poly R}. Hypothesis ulcd : lead_coef d \in GRing.unit. Implicit Type p q r : {poly R}. Lemma divp_eq p : p = (p %/ d) * d + (p %% d). Proof. by have := divp_eq p d; rewrite scalpE ulcd expr0 scale1r. Qed. Lemma edivpP p q r : p = q * d + r -> size r < size d -> q = (p %/ d) /\ r = p %% d. Proof. move=> ep srd; have := divp_eq p; rewrite [LHS]ep. move/eqP; rewrite -subr_eq -addrA addrC eq_sym -subr_eq -mulrBl; move/eqP. have lcdn0 : lead_coef d != 0 by apply: contraTneq ulcd => ->; rewrite unitr0. have [-> /esym /eqP|abs] := eqVneq (p %/ d) q. by rewrite subrr mul0r subr_eq0 => /eqP<-. have hleq : size d <= size ((p %/ d - q) * d). rewrite size_proper_mul; last first. by rewrite mulf_eq0 (negPf lcdn0) orbF lead_coef_eq0 subr_eq0. by move: abs; rewrite -subr_eq0; move/polySpred->; rewrite addSn /= leq_addl. have hlt : size (r - p %% d) < size d. apply: leq_ltn_trans (size_polyD _ _) _. by rewrite gtn_max srd size_polyN ltn_modp -lead_coef_eq0. by move=> e; have:= leq_trans hlt hleq; rewrite e ltnn. Qed. Lemma divpP p q r : p = q * d + r -> size r < size d -> q = (p %/ d). Proof. by move/edivpP=> h; case/h. Qed. Lemma modpP p q r : p = q * d + r -> size r < size d -> r = (p %% d). Proof. by move/edivpP=> h; case/h. Qed. Lemma ulc_eqpP p q : lead_coef q \is a GRing.unit -> reflect (exists2 c : R, c != 0 & p = c *: q) (p %= q). Proof. have [->|] := eqVneq (lead_coef q) 0; first by rewrite unitr0. rewrite lead_coef_eq0 => nz_q ulcq; apply: (iffP idP). have [->|nz_p] := eqVneq p 0; first by rewrite eqp_sym eqp0 (negPf nz_q). move/eqp_eq=> eq; exists (lead_coef p / lead_coef q). by rewrite mulf_neq0 // ?invr_eq0 lead_coef_eq0. by apply/(scaler_injl ulcq); rewrite scalerA mulrCA divrr // mulr1. by case=> c nz_c ->; apply/eqpP; exists (1, c); rewrite ?scale1r ?oner_eq0. Qed. Lemma dvdp_eq p : (d %| p) = (p == p %/ d * d). Proof. apply/eqP/eqP=> [modp0 | ->]; last exact: modp_mull. by rewrite [p in LHS]divp_eq modp0 addr0. Qed. Lemma ucl_eqp_eq p q : lead_coef q \is a GRing.unit -> p %= q -> p = (lead_coef p / lead_coef q) *: q. Proof. move=> ulcq /eqp_eq; move/(congr1 ( *:%R (lead_coef q)^-1 )). by rewrite !scalerA mulrC divrr // scale1r mulrC. Qed. Lemma modpZl c p : (c *: p) %% d = c *: (p %% d). Proof. have [-> | cn0] := eqVneq c 0; first by rewrite !scale0r mod0p. have e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d). by rewrite -scalerAl -scalerDr -divp_eq. suff s: size (c *: (p %% d)) < size d by case: (edivpP e s) => _ ->. rewrite -mul_polyC; apply: leq_ltn_trans (size_polyMleq _ _) _. rewrite size_polyC cn0 addSn add0n /= ltn_modp -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma divpZl c p : (c *: p) %/ d = c *: (p %/ d). Proof. have [-> | cn0] := eqVneq c 0; first by rewrite !scale0r div0p. have e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d). by rewrite -scalerAl -scalerDr -divp_eq. suff s: size (c *: (p %% d)) < size d by case: (edivpP e s) => ->. rewrite -mul_polyC; apply: leq_ltn_trans (size_polyMleq _ _) _. rewrite size_polyC cn0 addSn add0n /= ltn_modp -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma eqp_modpl p q : p %= q -> (p %% d) %= (q %% d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 //= -!modpZl e. Qed. Lemma eqp_divl p q : p %= q -> (p %/ d) %= (q %/ d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!divpZl e. Qed. Lemma modpN p : (- p) %% d = - (p %% d). Proof. by rewrite -mulN1r -[RHS]mulN1r -polyCN !mul_polyC modpZl. Qed. Lemma divpN p : (- p) %/ d = - (p %/ d). Proof. by rewrite -mulN1r -[RHS]mulN1r -polyCN !mul_polyC divpZl. Qed. Lemma modpD p q : (p + q) %% d = p %% d + q %% d. Proof. have/edivpP [] // : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d). by rewrite mulrDl addrACA -!divp_eq. apply: leq_ltn_trans (size_polyD _ _) _. rewrite gtn_max !ltn_modp andbb -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma divpD p q : (p + q) %/ d = p %/ d + q %/ d. Proof. have/edivpP [] // : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d). by rewrite mulrDl addrACA -!divp_eq. apply: leq_ltn_trans (size_polyD _ _) _. rewrite gtn_max !ltn_modp andbb -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma mulpK q : (q * d) %/ d = q. Proof. case/esym/edivpP: (addr0 (q * d)); rewrite // size_poly0 size_poly_gt0. by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma mulKp q : (d * q) %/ d = q. Proof. by rewrite mulrC; apply: mulpK. Qed. Lemma divp_addl_mul_small q r : size r < size d -> (q * d + r) %/ d = q. Proof. by move=> srd; rewrite divpD (divp_small srd) addr0 mulpK. Qed. Lemma modp_addl_mul_small q r : size r < size d -> (q * d + r) %% d = r. Proof. by move=> srd; rewrite modpD modp_mull add0r modp_small. Qed. Lemma divp_addl_mul q r : (q * d + r) %/ d = q + r %/ d. Proof. by rewrite divpD mulpK. Qed. Lemma divpp : d %/ d = 1. Proof. by rewrite -[d in d %/ _]mul1r mulpK. Qed. Lemma leq_divMp m : size (m %/ d * d) <= size m. Proof. case: (eqVneq d 0) ulcd => [->|dn0 _]; first by rewrite lead_coef0 unitr0. have [->|q0] := eqVneq (m %/ d) 0; first by rewrite mul0r size_poly0 leq0n. rewrite {2}(divp_eq m) size_polyDl // size_mul // (polySpred q0) addSn /=. by rewrite ltn_addl // ltn_modp. Qed. Lemma dvdpP p : reflect (exists q, p = q * d) (d %| p). Proof. apply: (iffP idP) => [| [k ->]]; last by apply/eqP; rewrite modp_mull. by rewrite dvdp_eq; move/eqP->; exists (p %/ d). Qed. Lemma divpK p : d %| p -> p %/ d * d = p. Proof. by rewrite dvdp_eq; move/eqP. Qed. Lemma divpKC p : d %| p -> d * (p %/ d) = p. Proof. by move=> ?; rewrite mulrC divpK. Qed. Lemma dvdp_eq_div p q : d %| p -> (q == p %/ d) = (q * d == p). Proof. move/divpK=> {2}<-; apply/eqP/eqP; first by move->. apply/mulIf; rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->. by rewrite unitr0. Qed. Lemma dvdp_eq_mul p q : d %| p -> (p == q * d) = (p %/ d == q). Proof. by move=> dv_d_p; rewrite eq_sym -dvdp_eq_div // eq_sym. Qed. Lemma divp_mulA p q : d %| q -> p * (q %/ d) = p * q %/ d. Proof. move=> hdm; apply/eqP; rewrite eq_sym -dvdp_eq_mul. by rewrite -mulrA divpK. by move/divpK: hdm<-; rewrite mulrA dvdp_mull // dvdpp. Qed. Lemma divp_mulAC m n : d %| m -> m %/ d * n = m * n %/ d. Proof. by move=> hdm; rewrite mulrC (mulrC m); apply: divp_mulA. Qed. Lemma divp_mulCA p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d). Proof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed. Lemma modp_mul p q : (p * (q %% d)) %% d = (p * q) %% d. Proof. by rewrite [q in RHS]divp_eq mulrDr modpD mulrA modp_mull add0r. Qed. End UnitDivisor. #[deprecated(since="mathcomp 2.4.0", note="Renamed to leq_divMp.")] Notation leq_trunc_divp := leq_divMp. Section MoreUnitDivisor. Variable R : idomainType. Variable d : {poly R}. Hypothesis ulcd : lead_coef d \in GRing.unit. Implicit Types p q : {poly R}. Lemma expp_sub m n : n <= m -> (d ^+ (m - n))%N = d ^+ m %/ d ^+ n. Proof. by move/subnK=> {2}<-; rewrite exprD mulpK // lead_coef_exp unitrX. Qed. Lemma divp_pmul2l p q : lead_coef q \in GRing.unit -> d * p %/ (d * q) = p %/ q. Proof. move=> uq; rewrite {1}(divp_eq uq p) mulrDr mulrCA divp_addl_mul //; last first. by rewrite lead_coefM unitrM_comm ?ulcd //; red; rewrite mulrC. have dn0 : d != 0. by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0. have qn0 : q != 0. by rewrite -lead_coef_eq0; apply: contraTneq uq => ->; rewrite unitr0. have dqn0 : d * q != 0 by rewrite mulf_eq0 negb_or dn0. suff : size (d * (p %% q)) < size (d * q). by rewrite ltnNge -divpN0 // negbK => /eqP ->; rewrite addr0. have [-> | rn0] := eqVneq (p %% q) 0. by rewrite mulr0 size_poly0 size_poly_gt0. by rewrite !size_mul // (polySpred dn0) !addSn /= ltn_add2l ltn_modp. Qed. Lemma divp_pmul2r p q : lead_coef p \in GRing.unit -> q * d %/ (p * d) = q %/ p. Proof. by move=> uq; rewrite -!(mulrC d) divp_pmul2l. Qed. Lemma divp_divl r p q : lead_coef r \in GRing.unit -> lead_coef p \in GRing.unit -> q %/ p %/ r = q %/ (p * r). Proof. move=> ulcr ulcp. have e : q = (q %/ p %/ r) * (p * r) + ((q %/ p) %% r * p + q %% p). by rewrite addrA (mulrC p) mulrA -mulrDl; rewrite -divp_eq //; apply: divp_eq. have pn0 : p != 0. by rewrite -lead_coef_eq0; apply: contraTneq ulcp => ->; rewrite unitr0. have rn0 : r != 0. by rewrite -lead_coef_eq0; apply: contraTneq ulcr => ->; rewrite unitr0. have s : size ((q %/ p) %% r * p + q %% p) < size (p * r). have [-> | qn0] := eqVneq ((q %/ p) %% r) 0. rewrite mul0r add0r size_mul // (polySpred rn0) addnS /=. by apply: leq_trans (leq_addr _ _); rewrite ltn_modp. rewrite size_polyDl mulrC. by rewrite !size_mul // (polySpred pn0) !addSn /= ltn_add2l ltn_modp. rewrite size_mul // (polySpred qn0) addnS /=. by apply: leq_trans (leq_addr _ _); rewrite ltn_modp. case: (edivpP _ e s) => //; rewrite lead_coefM unitrM_comm ?ulcp //. by red; rewrite mulrC. Qed. Lemma divpAC p q : lead_coef p \in GRing.unit -> q %/ d %/ p = q %/ p %/ d. Proof. by move=> ulcp; rewrite !divp_divl // mulrC. Qed. Lemma modpZr c p : c \in GRing.unit -> p %% (c *: d) = (p %% d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !modp0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVr // scale1r -(divp_eq ulcd). suff s : size (p %% d) < size (c *: d). by rewrite (modpP _ e s) // -mul_polyC lead_coefM lead_coefC unitrM cn0. by rewrite size_scale ?ltn_modp //; apply: contraTneq cn0 => ->; rewrite unitr0. Qed. Lemma divpZr c p : c \in GRing.unit -> p %/ (c *: d) = c^-1 *: (p %/ d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !divp0 scaler0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVr // scale1r -(divp_eq ulcd). suff s : size (p %% d) < size (c *: d). by rewrite (divpP _ e s) // -mul_polyC lead_coefM lead_coefC unitrM cn0. by rewrite size_scale ?ltn_modp //; apply: contraTneq cn0 => ->; rewrite unitr0. Qed. End MoreUnitDivisor. End IdomainUnit. Module Field. Import Ring ComRing UnitRing. Include IdomainDefs. Export IdomainDefs. Include CommonIdomain. Section FieldDivision. Variable F : fieldType. Implicit Type p q r d : {poly F}. Lemma divp_eq p q : p = (p %/ q) * q + (p %% q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite modp0 mulr0 add0r. by apply: IdomainUnit.divp_eq; rewrite unitfE lead_coef_eq0. Qed. Lemma divp_modpP p q d r : p = q * d + r -> size r < size d -> q = (p %/ d) /\ r = p %% d. Proof. move=> he hs; apply: IdomainUnit.edivpP => //; rewrite unitfE lead_coef_eq0. by rewrite -size_poly_gt0; apply: leq_trans hs. Qed. Lemma divpP p q d r : p = q * d + r -> size r < size d -> q = (p %/ d). Proof. by move/divp_modpP=> h; case/h. Qed. Lemma modpP p q d r : p = q * d + r -> size r < size d -> r = (p %% d). Proof. by move/divp_modpP=> h; case/h. Qed. Lemma eqpfP p q : p %= q -> p = (lead_coef p / lead_coef q) *: q. Proof. have [->|nz_q] := eqVneq q 0; first by rewrite eqp0 scaler0 => /eqP ->. by apply/IdomainUnit.ucl_eqp_eq; rewrite unitfE lead_coef_eq0. Qed. Lemma dvdp_eq q p : (q %| p) = (p == p %/ q * q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite dvd0p mulr0 eq_sym. by apply: IdomainUnit.dvdp_eq; rewrite unitfE lead_coef_eq0. Qed. Lemma eqpf_eq p q : reflect (exists2 c, c != 0 & p = c *: q) (p %= q). Proof. apply: (iffP idP); last first. case=> c nz_c ->; apply/eqpP. by exists (1, c); rewrite ?scale1r ?oner_eq0. have [->|nz_q] := eqVneq q 0. by rewrite eqp0=> /eqP ->; exists 1; rewrite ?scale1r ?oner_eq0. case/IdomainUnit.ulc_eqpP; first by rewrite unitfE lead_coef_eq0. by move=> c nz_c ->; exists c. Qed. Lemma modpZl c p q : (c *: p) %% q = c *: (p %% q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite !modp0. by apply: IdomainUnit.modpZl; rewrite unitfE lead_coef_eq0. Qed. Lemma mulpK p q : q != 0 -> p * q %/ q = p. Proof. by move=> qn0; rewrite IdomainUnit.mulpK // unitfE lead_coef_eq0. Qed. Lemma mulKp p q : q != 0 -> q * p %/ q = p. Proof. by rewrite mulrC; apply: mulpK. Qed. Lemma divpZl c p q : (c *: p) %/ q = c *: (p %/ q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite !divp0 scaler0. by apply: IdomainUnit.divpZl; rewrite unitfE lead_coef_eq0. Qed. Lemma modpZr c p d : c != 0 -> p %% (c *: d) = (p %% d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !modp0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVf // scale1r -divp_eq. suff s : size (p %% d) < size (c *: d) by rewrite (modpP e s). by rewrite size_scale ?ltn_modp. Qed. Lemma divpZr c p d : c != 0 -> p %/ (c *: d) = c^-1 *: (p %/ d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !divp0 scaler0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVf // scale1r -divp_eq. suff s : size (p %% d) < size (c *: d) by rewrite (divpP e s). by rewrite size_scale ?ltn_modp. Qed. Lemma eqp_modpl d p q : p %= q -> (p %% d) %= (q %% d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!modpZl e. Qed. Lemma eqp_divl d p q : p %= q -> (p %/ d) %= (q %/ d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!divpZl e. Qed. Lemma eqp_modpr d p q : p %= q -> (d %% p) %= (d %% q). Proof. case/eqpP=> [[c1 c2]] /andP [c1n0 c2n0 e]. have -> : p = (c1^-1 * c2) *: q by rewrite -scalerA -e scalerA mulVf // scale1r. by rewrite modpZr ?eqpxx // mulf_eq0 negb_or invr_eq0 c1n0. Qed. Lemma eqp_mod p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> p1 %% q1 %= p2 %% q2. Proof. move=> e1 e2; exact: eqp_trans (eqp_modpl _ e1) (eqp_modpr _ e2). Qed. Lemma eqp_divr (d m n : {poly F}) : m %= n -> (d %/ m) %= (d %/ n). Proof. case/eqpP=> [[c1 c2]] /andP [c1n0 c2n0 e]. have -> : m = (c1^-1 * c2) *: n by rewrite -scalerA -e scalerA mulVf // scale1r. by rewrite divpZr ?eqp_scale // ?invr_eq0 mulf_eq0 negb_or invr_eq0 c1n0. Qed. Lemma eqp_div p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> p1 %/ q1 %= p2 %/ q2. Proof. move=> e1 e2; exact: eqp_trans (eqp_divl _ e1) (eqp_divr _ e2). Qed. Lemma eqp_gdcor p q r : q %= r -> gdcop p q %= gdcop p r. Proof. move=> eqr; rewrite /gdcop (eqp_size eqr). move: (size r)=> n; elim: n p q r eqr => [|n ihn] p q r; first by rewrite eqpxx. move=> eqr /=; rewrite (eqp_coprimepl p eqr); case: ifP => _ //. exact/ihn/eqp_div/eqp_gcdl. Qed. Lemma eqp_gdcol p q r : q %= r -> gdcop q p %= gdcop r p. Proof. move=> eqr; rewrite /gdcop; move: (size p)=> n. elim: n p q r eqr {1 3}p (eqpxx p) => [|n ihn] p q r eqr s esp /=. case: (eqVneq q 0) eqr => [-> | nq0 eqr] /=. by rewrite eqp_sym eqp0 => ->; rewrite eqpxx. by case: (eqVneq r 0) eqr nq0 => [->|]; rewrite ?eqpxx // eqp0 => ->. rewrite (eqp_coprimepr _ eqr) (eqp_coprimepl _ esp); case: ifP=> _ //. exact/ihn/eqp_div/eqp_gcd. Qed. Lemma eqp_rgdco_gdco q p : rgdcop q p %= gdcop q p. Proof. rewrite /rgdcop /gdcop; move: (size p)=> n. elim: n p q {1 3}p {1 3}q (eqpxx p) (eqpxx q) => [|n ihn] p q s t /= sp tq. case: (eqVneq t 0) tq => [-> | nt0 etq]. by rewrite eqp_sym eqp0 => ->; rewrite eqpxx. by case: (eqVneq q 0) etq nt0 => [->|]; rewrite ?eqpxx // eqp0 => ->. rewrite rcoprimep_coprimep (eqp_coprimepl t sp) (eqp_coprimepr p tq). case: ifP=> // _; apply: ihn => //; apply: eqp_trans (eqp_rdiv_div _ _) _. by apply: eqp_div => //; apply: eqp_trans (eqp_rgcd_gcd _ _) _; apply: eqp_gcd. Qed. Lemma modpD d p q : (p + q) %% d = p %% d + q %% d. Proof. have [-> | dn0] := eqVneq d 0; first by rewrite !modp0. by apply: IdomainUnit.modpD; rewrite unitfE lead_coef_eq0. Qed. Lemma modpN p q : (- p) %% q = - (p %% q). Proof. by apply/eqP; rewrite -addr_eq0 -modpD addNr mod0p. Qed. Lemma modNp p q : (- p) %% q = - (p %% q). Proof. exact: modpN. Qed. Lemma divpD d p q : (p + q) %/ d = p %/ d + q %/ d. Proof. have [-> | dn0] := eqVneq d 0; first by rewrite !divp0 addr0. by apply: IdomainUnit.divpD; rewrite unitfE lead_coef_eq0. Qed. Lemma divpN p q : (- p) %/ q = - (p %/ q). Proof. by apply/eqP; rewrite -addr_eq0 -divpD addNr div0p. Qed. Lemma divp_addl_mul_small d q r : size r < size d -> (q * d + r) %/ d = q. Proof. move=> srd; rewrite divpD (divp_small srd) addr0 mulpK // -size_poly_gt0. exact: leq_trans srd. Qed. Lemma modp_addl_mul_small d q r : size r < size d -> (q * d + r) %% d = r. Proof. by move=> srd; rewrite modpD modp_mull add0r modp_small. Qed. Lemma divp_addl_mul d q r : d != 0 -> (q * d + r) %/ d = q + r %/ d. Proof. by move=> dn0; rewrite divpD mulpK. Qed. Lemma divpp d : d != 0 -> d %/ d = 1. Proof. by move=> dn0; apply: IdomainUnit.divpp; rewrite unitfE lead_coef_eq0. Qed. Lemma leq_divMp d m : size (m %/ d * d) <= size m. Proof. have [-> | dn0] := eqVneq d 0; first by rewrite mulr0 size_poly0. by apply: IdomainUnit.leq_divMp; rewrite unitfE lead_coef_eq0. Qed. Lemma divpK d p : d %| p -> p %/ d * d = p. Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite mulr0. by apply: IdomainUnit.divpK; rewrite unitfE lead_coef_eq0. Qed. Lemma divpKC d p : d %| p -> d * (p %/ d) = p. Proof. by move=> ?; rewrite mulrC divpK. Qed. Lemma dvdp_eq_div d p q : d != 0 -> d %| p -> (q == p %/ d) = (q * d == p). Proof. by move=> dn0; apply: IdomainUnit.dvdp_eq_div; rewrite unitfE lead_coef_eq0. Qed. Lemma dvdp_eq_mul d p q : d != 0 -> d %| p -> (p == q * d) = (p %/ d == q). Proof. by move=> dn0 dv_d_p; rewrite eq_sym -dvdp_eq_div // eq_sym. Qed. Lemma divp_mulA d p q : d %| q -> p * (q %/ d) = p * q %/ d. Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite !divp0 mulr0. by apply: IdomainUnit.divp_mulA; rewrite unitfE lead_coef_eq0. Qed. Lemma divp_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d. Proof. by move=> hdm; rewrite mulrC (mulrC m); apply: divp_mulA. Qed. Lemma divp_mulCA d p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d). Proof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed. Lemma expp_sub d m n : d != 0 -> m >= n -> (d ^+ (m - n))%N = d ^+ m %/ d ^+ n. Proof. by move=> dn0 /subnK=> {2}<-; rewrite exprD mulpK // expf_neq0. Qed. Lemma divp_pmul2l d q p : d != 0 -> q != 0 -> d * p %/ (d * q) = p %/ q. Proof. by move=> dn0 qn0; apply: IdomainUnit.divp_pmul2l; rewrite unitfE lead_coef_eq0. Qed. Lemma divp_pmul2r d p q : d != 0 -> p != 0 -> q * d %/ (p * d) = q %/ p. Proof. by move=> dn0 qn0; rewrite -!(mulrC d) divp_pmul2l. Qed. Lemma divp_divl r p q : q %/ p %/ r = q %/ (p * r). Proof. have [-> | rn0] := eqVneq r 0; first by rewrite mulr0 !divp0. have [-> | pn0] := eqVneq p 0; first by rewrite mul0r !divp0 div0p. by apply: IdomainUnit.divp_divl; rewrite unitfE lead_coef_eq0. Qed. Lemma divpAC d p q : q %/ d %/ p = q %/ p %/ d. Proof. by rewrite !divp_divl // mulrC. Qed. Lemma edivp_def p q : edivp p q = (0, p %/ q, p %% q). Proof. rewrite Idomain.edivp_def; congr (_, _, _); rewrite /scalp 2!unlock /=. have [-> | qn0] := eqVneq; first by rewrite lead_coef0 unitr0. by rewrite unitfE lead_coef_eq0 qn0 /=; case: (redivp_rec _ _ _ _) => [[]]. Qed. Lemma divpE p q : p %/ q = (lead_coef q)^-(rscalp p q) *: (rdivp p q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite rdivp0 divp0 scaler0. by rewrite Idomain.divpE unitfE lead_coef_eq0 qn0. Qed. Lemma modpE p q : p %% q = (lead_coef q)^-(rscalp p q) *: (rmodp p q). Proof. have [-> | qn0] := eqVneq q 0. by rewrite rmodp0 modp0 /rscalp unlock eqxx lead_coef0 expr0 invr1 scale1r. by rewrite Idomain.modpE unitfE lead_coef_eq0 qn0. Qed. Lemma scalpE p q : scalp p q = 0. Proof. have [-> | qn0] := eqVneq q 0; first by rewrite scalp0. by rewrite Idomain.scalpE unitfE lead_coef_eq0 qn0. Qed. (* Just to have it without importing the weak theory *) Lemma dvdpE p q : p %| q = rdvdp p q. Proof. exact: Idomain.dvdpE. Qed. Variant edivp_spec m d : nat * {poly F} * {poly F} -> Type := EdivpSpec n q r of m = q * d + r & (d != 0) ==> (size r < size d) : edivp_spec m d (n, q, r). Lemma edivpP m d : edivp_spec m d (edivp m d). Proof. rewrite edivp_def; constructor; first exact: divp_eq. by apply/implyP=> dn0; rewrite ltn_modp. Qed. Lemma edivp_eq d q r : size r < size d -> edivp (q * d + r) d = (0, q, r). Proof. move=> srd; apply: Idomain.edivp_eq; rewrite // unitfE lead_coef_eq0. by rewrite -size_poly_gt0; apply: leq_trans srd. Qed. Lemma modp_mul p q m : (p * (q %% m)) %% m = (p * q) %% m. Proof. by rewrite [in RHS](divp_eq q m) mulrDr modpD mulrA modp_mull add0r. Qed. Lemma horner_mod p q x : root q x -> (p %% q).[x] = p.[x]. Proof. by rewrite [in RHS](divp_eq p q) !hornerE => /eqP->; rewrite mulr0 add0r. Qed. Lemma dvdpP p q : reflect (exists qq, p = qq * q) (q %| p). Proof. have [-> | qn0] := eqVneq q 0; last first. by apply: IdomainUnit.dvdpP; rewrite unitfE lead_coef_eq0. by rewrite dvd0p; apply: (iffP eqP) => [->| [? ->]]; [exists 1|]; rewrite mulr0. Qed. Lemma Bezout_eq1_coprimepP p q : reflect (exists u, u.1 * p + u.2 * q = 1) (coprimep p q). Proof. apply: (iffP idP)=> [hpq|]; last first. by case=> -[u v] /= e; apply/Bezout_coprimepP; exists (u, v); rewrite e eqpxx. case/Bezout_coprimepP: hpq => [[u v]] /=. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0] e. exists (c2^-1 *: (c1 *: u), c2^-1 *: (c1 *: v)); rewrite /= -!scalerAl. by rewrite -!scalerDr e scalerA mulVf // scale1r. Qed. Lemma dvdp_gdcor p q : q != 0 -> p %| (gdcop q p) * (q ^+ size p). Proof. rewrite /gdcop => nz_q; have [n hsp] := ubnPleq (size p). elim: n => [|n IHn] /= in p hsp *; first by rewrite (negPf nz_q) mul0r dvdp0. have [_ | ncop_pq] := ifPn; first by rewrite dvdp_mulr. have g_gt1: 1 < size (gcdp p q). rewrite ltn_neqAle eq_sym ncop_pq size_poly_gt0 gcdp_eq0. by rewrite negb_and nz_q orbT. have [-> | nz_p] := eqVneq p 0. by rewrite div0p exprSr mulrA dvdp_mulr // IHn // size_poly0. have le_d_p: size (p %/ gcdp p q) < size p. rewrite size_divp -?size_poly_eq0 -(subnKC g_gt1) // add2n /=. by rewrite polySpred // ltnS subSS leq_subr. rewrite -[p in p %| _](divpK (dvdp_gcdl p q)) exprSr mulrA. by rewrite dvdp_mul ?IHn ?dvdp_gcdr // -ltnS (leq_trans le_d_p). Qed. Lemma reducible_cubic_root p q : size p <= 4 -> 1 < size q < size p -> q %| p -> {r | root p r}. Proof. move=> p_le4 /andP[]; rewrite leq_eqVlt eq_sym. have [/poly2_root[x qx0] _ _ | _ /= q_gt2 p_gt_q] := size q =P 2. by exists x; rewrite -!dvdp_XsubCl in qx0 *; apply: (dvdp_trans qx0). case/dvdpP/sig_eqW=> r def_p; rewrite def_p. suffices /poly2_root[x rx0]: size r = 2 by exists x; rewrite rootM rx0. have /norP[nz_r nz_q]: ~~ [|| r == 0 | q == 0]. by rewrite -mulf_eq0 -def_p -size_poly_gt0 (leq_ltn_trans _ p_gt_q). rewrite def_p size_mul // -subn1 leq_subLR ltn_subRL in p_gt_q p_le4. by apply/eqP; rewrite -(eqn_add2r (size q)) eqn_leq (leq_trans p_le4). Qed. Lemma cubic_irreducible p : 1 < size p <= 4 -> (forall x, ~~ root p x) -> irreducible_poly p. Proof. move=> /andP[p_gt1 p_le4] root'p; split=> // q sz_q_neq1 q_dv_p. have nz_p: p != 0 by rewrite -size_poly_gt0 ltnW. have nz_q: q != 0 by apply: contraTneq q_dv_p => ->; rewrite dvd0p. have q_gt1: size q > 1 by rewrite ltn_neqAle eq_sym sz_q_neq1 size_poly_gt0. rewrite -dvdp_size_eqp // eqn_leq dvdp_leq //= leqNgt; apply/negP=> p_gt_q. by have [|x /idPn//] := reducible_cubic_root p_le4 _ q_dv_p; rewrite q_gt1. Qed. Section Multiplicity. Definition mup x q := [arg max_(n > (ord0 : 'I_(size q).+1) | ('X - x%:P) ^+ n %| q) n] : nat. Lemma mup_geq x q n : q != 0 -> (n <= mup x q)%N = (('X - x%:P) ^+ n %| q). Proof. move=> q_neq0; rewrite /mup; symmetry. case: arg_maxnP; rewrite ?expr0 ?dvd1p//= => i i_dvd gti. case: ltnP => [|/dvdp_exp2l/dvdp_trans]; last exact. apply: contraTF => dvdq; rewrite -leqNgt. suff n_small : (n < (size q).+1)%N by exact: (gti (Ordinal n_small)). by rewrite ltnS ltnW// -(size_exp_XsubC _ x) dvdp_leq. Qed. Lemma mup_leq x q n : q != 0 -> (mup x q <= n)%N = ~~ (('X - x%:P) ^+ n.+1 %| q). Proof. by move=> qN0; rewrite leqNgt mup_geq. Qed. Lemma mup_ltn x q n : q != 0 -> (mup x q < n)%N = ~~ (('X - x%:P) ^+ n %| q). Proof. by move=> qN0; rewrite ltnNge mup_geq. Qed. Lemma XsubC_dvd x q : q != 0 -> ('X - x%:P %| q) = (0 < mup x q)%N. Proof. by move=> /mup_geq-/(_ _ 1%N)/esym; apply. Qed. Lemma mup_XsubCX n x y : mup x (('X - y%:P) ^+ n) = (if (y == x) then n else 0)%N. Proof. have Xxn0 : ('X - y%:P) ^+ n != 0 by rewrite ?expf_neq0 ?polyXsubC_eq0. apply/eqP; rewrite eqn_leq mup_leq ?mup_geq//. have [->|Nxy] := eqVneq x y. by rewrite /= dvdpp ?dvdp_Pexp2l ?size_XsubC ?ltnn. by rewrite dvd1p dvdp_XsubCl /root horner_exp !hornerE expf_neq0// subr_eq0. Qed. Lemma mupNroot x q : ~~ root q x -> mup x q = 0%N. Proof. move=> qNx; have qN0 : q != 0 by apply: contraNneq qNx => ->; rewrite root0. by move: qNx; rewrite -dvdp_XsubCl XsubC_dvd// lt0n negbK => /eqP. Qed. Lemma mupMr x q1 q2 : ~~ root q1 x -> mup x (q1 * q2) = mup x q2. Proof. move=> q1Nx; have q1N0 : q1 != 0 by apply: contraNneq q1Nx => ->; rewrite root0. have [->|q2N0] := eqVneq q2 0; first by rewrite mulr0. apply/esym/eqP; rewrite eqn_leq mup_geq ?mulf_neq0// dvdp_mull -?mup_geq//=. rewrite mup_leq ?mulf_neq0// Gauss_dvdpr -?mup_ltn//. by rewrite coprimep_expl// coprimep_sym coprimep_XsubC. Qed. Lemma mupMl x q1 q2 : ~~ root q2 x -> mup x (q1 * q2) = mup x q1. Proof. by rewrite mulrC; apply/mupMr. Qed. Lemma mupM x q1 q2 : q1 != 0 -> q2 != 0 -> mup x (q1 * q2) = (mup x q1 + mup x q2)%N. Proof. move=> q1N0 q2N0; apply/eqP; rewrite eqn_leq mup_leq ?mulf_neq0//. rewrite mup_geq ?mulf_neq0// exprD ?dvdp_mul; do ?by rewrite -mup_geq. have [m1 [r1]] := multiplicity_XsubC q1 x; rewrite q1N0 /= => r1Nx ->. have [m2 [r2]] := multiplicity_XsubC q2 x; rewrite q2N0 /= => r2Nx ->. rewrite !mupMr// ?mup_XsubCX eqxx/= mulrACA exprS exprD. rewrite dvdp_mul2r ?mulf_neq0 ?expf_neq0 ?polyXsubC_eq0//. by rewrite dvdp_XsubCl rootM negb_or r1Nx r2Nx. Qed. Lemma mu_prod_XsubC x (s : seq F) : mup x (\prod_(y <- s) ('X - y%:P)) = count_mem x s. Proof. elim: s => [|y s IHs]; rewrite (big_cons, big_nil)/=. by rewrite mupNroot// root1. rewrite mupM ?polyXsubC_eq0// ?monic_neq0 ?monic_prod_XsubC//. by rewrite IHs (@mup_XsubCX 1). Qed. Lemma prod_XsubC_eq (s t : seq F) : \prod_(x <- s) ('X - x%:P) = \prod_(x <- t) ('X - x%:P) -> perm_eq s t. Proof. move=> eq_prod; apply/allP => x _ /=; apply/eqP. by have /(congr1 (mup x)) := eq_prod; rewrite !mu_prod_XsubC. Qed. End Multiplicity. Section FieldRingMap. Variable rR : nzRingType. Variable f : {rmorphism F -> rR}. Local Notation "p ^f" := (map_poly f p) : ring_scope. Implicit Type a b : {poly F}. Lemma redivp_map a b : redivp a^f b^f = (rscalp a b, (rdivp a b)^f, (rmodp a b)^f). Proof. rewrite /rdivp /rscalp /rmodp !unlock map_poly_eq0 size_map_poly. have [// | q_nz] := ifPn; rewrite -(rmorph0 (map_poly f)) //. have [m _] := ubnPeq (size a); elim: m 0%N 0 a => [|m IHm] qq r a /=. rewrite -!mul_polyC !size_map_poly !lead_coef_map // -(map_polyXn f). by rewrite -!(map_polyC f) -!rmorphM -rmorphB -rmorphD; case: (_ < _). rewrite -!mul_polyC !size_map_poly !lead_coef_map // -(map_polyXn f). by rewrite -!(map_polyC f) -!rmorphM -rmorphB -rmorphD /= IHm; case: (_ < _). Qed. End FieldRingMap. Section FieldMap. Variable rR : idomainType. Variable f : {rmorphism F -> rR}. Local Notation "p ^f" := (map_poly f p) : ring_scope. Implicit Type a b : {poly F}. Lemma edivp_map a b : edivp a^f b^f = (0, (a %/ b)^f, (a %% b)^f). Proof. have [-> | bn0] := eqVneq b 0. rewrite (rmorph0 (map_poly f)) WeakIdomain.edivp_def !modp0 !divp0. by rewrite (rmorph0 (map_poly f)) scalp0. rewrite unlock redivp_map lead_coef_map rmorph_unit; last first. by rewrite unitfE lead_coef_eq0. rewrite modpE divpE !map_polyZ [in RHS]rmorphV ?rmorphXn // unitfE. by rewrite expf_neq0 // lead_coef_eq0. Qed. Lemma scalp_map p q : scalp p^f q^f = scalp p q. Proof. by rewrite /scalp edivp_map edivp_def. Qed. Lemma map_divp p q : (p %/ q)^f = p^f %/ q^f. Proof. by rewrite /divp edivp_map edivp_def. Qed. Lemma map_modp p q : (p %% q)^f = p^f %% q^f. Proof. by rewrite /modp edivp_map edivp_def. Qed. Lemma egcdp_map p q : egcdp (map_poly f p) (map_poly f q) = (map_poly f (egcdp p q).1, map_poly f (egcdp p q).2). Proof. wlog le_qp: p q / size q <= size p. move=> IH; have [/IH// | lt_qp] := leqP (size q) (size p). have /IH := ltnW lt_qp; rewrite /egcdp !size_map_poly ltnW // leqNgt lt_qp /=. by case: (egcdp_rec _ _ _) => u v [-> ->]. rewrite /egcdp !size_map_poly {}le_qp; move: (size q) => n. elim: n => /= [|n IHn] in p q *; first by rewrite rmorph1 rmorph0. rewrite map_poly_eq0; have [_ | nz_q] := ifPn; first by rewrite rmorph1 rmorph0. rewrite -map_modp (IHn q (p %% q)); case: (egcdp_rec _ _ n) => u v /=. rewrite map_polyZ lead_coef_map -rmorphXn scalp_map rmorphB rmorphM. by rewrite -map_divp. Qed. Lemma dvdp_map p q : (p^f %| q^f) = (p %| q). Proof. by rewrite /dvdp -map_modp map_poly_eq0. Qed. Lemma eqp_map p q : (p^f %= q^f) = (p %= q). Proof. by rewrite /eqp !dvdp_map. Qed. Lemma gcdp_map p q : (gcdp p q)^f = gcdp p^f q^f. Proof. wlog lt_p_q: p q / size p < size q. move=> IHpq; case: (ltnP (size p) (size q)) => [|le_q_p]; first exact: IHpq. rewrite gcdpE (gcdpE p^f) !size_map_poly ltnNge le_q_p /= -map_modp. have [-> | q_nz] := eqVneq q 0; first by rewrite rmorph0 !gcdp0. by rewrite IHpq ?ltn_modp. have [m le_q_m] := ubnP (size q); elim: m => // m IHm in p q lt_p_q le_q_m *. rewrite gcdpE (gcdpE p^f) !size_map_poly lt_p_q -map_modp. have [-> | q_nz] := eqVneq p 0; first by rewrite rmorph0 !gcdp0. by rewrite IHm ?(leq_trans lt_p_q) ?ltn_modp. Qed. Lemma coprimep_map p q : coprimep p^f q^f = coprimep p q. Proof. by rewrite -!gcdp_eqp1 -eqp_map rmorph1 gcdp_map. Qed. Lemma gdcop_rec_map p q n : (gdcop_rec p q n)^f = gdcop_rec p^f q^f n. Proof. elim: n p q => [|n IH] => /= p q. by rewrite map_poly_eq0; case: eqP; rewrite ?rmorph1 ?rmorph0. rewrite /coprimep -gcdp_map size_map_poly. by case: eqP => Hq0 //; rewrite -map_divp -IH. Qed. Lemma gdcop_map p q : (gdcop p q)^f = gdcop p^f q^f. Proof. by rewrite /gdcop gdcop_rec_map !size_map_poly. Qed. End FieldMap. End FieldDivision. #[deprecated(since="mathcomp 2.4.0", note="Renamed to leq_divMp.")] Notation leq_trunc_divp := leq_divMp. End Field. Module ClosedField. Import Field. Section closed. Variable F : closedFieldType. Lemma root_coprimep (p q : {poly F}) : (forall x, root p x -> q.[x] != 0) -> coprimep p q. Proof. move=> Ncmn; rewrite -gcdp_eqp1 -size_poly_eq1; apply/closed_rootP. by case=> r; rewrite root_gcd !rootE=> /andP [/Ncmn/negPf->]. Qed. Lemma coprimepP (p q : {poly F}) : reflect (forall x, root p x -> q.[x] != 0) (coprimep p q). Proof. by apply: (iffP idP)=> [/coprimep_root|/root_coprimep]. Qed. End closed. End ClosedField. End Pdiv. Export Pdiv.Field.
Conv.lean
/- Copyright (c) 2023 Robin Böhne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robin Böhne, Wojciech Nawrocki, Patrick Massot -/ import Mathlib.Tactic.Widget.SelectPanelUtils import Mathlib.Data.String.Defs import Batteries.Tactic.Lint import Batteries.Lean.Position /-! # Conv widget This is a slightly improved version of one of the examples in the ProofWidget library. It defines a `conv?` tactic that displays a widget panel allowing to generate a `conv` call zooming to the subexpression selected in the goal. -/ open Lean Meta Server ProofWidgets private structure SolveReturn where expr : Expr val? : Option String listRest : List Nat private def solveLevel (expr : Expr) (path : List Nat) : MetaM SolveReturn := match expr with | Expr.app _ _ => do let mut descExp := expr let mut count := 0 let mut explicitList := [] -- we go through the application until we reach the end, counting how many explicit arguments -- it has and noting whether they are explicit or implicit while descExp.isApp do if (← Lean.Meta.inferType descExp.appFn!).bindingInfo!.isExplicit then explicitList := true::explicitList count := count + 1 else explicitList := false::explicitList descExp := descExp.appFn! -- we get the correct `enter` command by subtracting the number of `true`s in our list let mut mutablePath := path let mut length := count explicitList := List.reverse explicitList while !mutablePath.isEmpty && mutablePath.head! == 0 do if explicitList.head! == true then count := count - 1 explicitList := explicitList.tail! mutablePath := mutablePath.tail! let mut nextExp := expr while length > count do nextExp := nextExp.appFn! length := length - 1 nextExp := nextExp.appArg! let pathRest := if mutablePath.isEmpty then [] else mutablePath.tail! return { expr := nextExp, val? := toString count , listRest := pathRest } | Expr.lam n _ b _ => do let name := match n with | Name.str _ s => s | _ => panic! "no name found" return { expr := b, val? := name, listRest := path.tail! } | Expr.forallE n _ b _ => do let name := match n with | Name.str _ s => s | _ => panic! "no name found" return { expr := b, val? := name, listRest := path.tail! } | Expr.mdata _ b => do match b with | Expr.mdata _ _ => return { expr := b, val? := none, listRest := path } | _ => return { expr := b.appFn!.appArg!, val? := none, listRest := path.tail!.tail! } | _ => do return { expr := ← (Lean.Core.viewSubexpr path.head! expr) val? := toString (path.head! + 1) listRest := path.tail! } open Lean Syntax in /-- Return the link text and inserted text above and below of the conv widget. -/ @[nolint unusedArguments] def insertEnter (locations : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) (params : SelectInsertParams) : MetaM (String × String × Option (String.Pos × String.Pos)) := do let some pos := locations[0]? | throwError "You must select something." let (fvar, subexprPos) ← match pos with | ⟨_, .target subexprPos⟩ => pure (none, subexprPos) | ⟨_, .hypType fvar subexprPos⟩ => pure (some fvar, subexprPos) | ⟨_, .hypValue fvar subexprPos⟩ => pure (some fvar, subexprPos) | _ => throwError "You must select something in the goal or in a local value." let mut list := (SubExpr.Pos.toArray subexprPos).toList let mut expr := goalType let mut retList := [] -- generate list of commands for `enter` while !list.isEmpty do let res ← solveLevel expr list expr := res.expr retList := match res.val? with | none => retList | some val => val::retList list := res.listRest -- build `enter [...]` string retList := List.reverse retList -- prepare `enter` indentation let spc := String.replicate (SelectInsertParamsClass.replaceRange params).start.character ' ' let loc ← match fvar with | some fvarId => pure s!"at {← fvarId.getUserName} " | none => pure "" let mut enterval := s!"conv {loc}=>\n{spc} enter {retList}" if enterval.contains '0' then enterval := "Error: Not a valid conv target" if retList.isEmpty then enterval := "" return ("Generate conv", enterval, none) /-- Rpc function for the conv widget. -/ @[server_rpc_method] def ConvSelectionPanel.rpc := mkSelectionPanelRPC insertEnter "Use shift-click to select one sub-expression in the goal that you want to zoom on." "Conv 🔍" (onlyGoal := false) (onlyOne := true) /-- The conv widget. -/ @[widget_module] def ConvSelectionPanel : Component SelectInsertParams := mk_rpc_widget% ConvSelectionPanel.rpc open scoped Json in /-- Display a widget panel allowing to generate a `conv` call zooming to the subexpression selected in the goal. -/ elab stx:"conv?" : tactic => do let some replaceRange := (← getFileMap).rangeOfStx? stx | return Widget.savePanelWidgetInfo ConvSelectionPanel.javascriptHash (pure <| json% { replaceRange: $(replaceRange) }) stx
ContinuousMap.lean
/- Copyright (c) 2024 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.CStarAlgebra.Classes import Mathlib.Topology.ContinuousMap.Compact import Mathlib.Topology.ContinuousMap.ZeroAtInfty /-! # C⋆-algebras of continuous functions We place these here because, for reasons related to the import hierarchy, they cannot be placed in earlier files. -/ variable {α A : Type*} noncomputable section namespace BoundedContinuousFunction variable [TopologicalSpace α] instance [NonUnitalCStarAlgebra A] : NonUnitalCStarAlgebra (α →ᵇ A) where instance [NonUnitalCommCStarAlgebra A] : NonUnitalCommCStarAlgebra (α →ᵇ A) where instance [CStarAlgebra A] : CStarAlgebra (α →ᵇ A) where instance [CommCStarAlgebra A] : CommCStarAlgebra (α →ᵇ A) where end BoundedContinuousFunction namespace ContinuousMap variable [TopologicalSpace α] [CompactSpace α] instance [NonUnitalCStarAlgebra A] : NonUnitalCStarAlgebra C(α, A) where instance [NonUnitalCommCStarAlgebra A] : NonUnitalCommCStarAlgebra C(α, A) where instance [CStarAlgebra A] : CStarAlgebra C(α, A) where instance [CommCStarAlgebra A] : CommCStarAlgebra C(α, A) where end ContinuousMap namespace ZeroAtInftyContinuousMap open ZeroAtInfty instance [TopologicalSpace α] [NonUnitalCStarAlgebra A] : NonUnitalCStarAlgebra C₀(α, A) where instance [TopologicalSpace α] [NonUnitalCommCStarAlgebra A] : NonUnitalCommCStarAlgebra C₀(α, A) where end ZeroAtInftyContinuousMap
nilpotent.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path. From mathcomp Require Import fintype div bigop prime finset fingroup morphism. From mathcomp Require Import automorphism quotient commutator gproduct. From mathcomp Require Import perm gfunctor center gseries cyclic. From mathcomp Require finfun. (******************************************************************************) (* This file defines nilpotent and solvable groups, and give some of their *) (* elementary properties; more will be added later (e.g., the nilpotence of *) (* p-groups in sylow.v, or the fact that minimal normal subgroups of solvable *) (* groups are elementary abelian in maximal.v). This file defines: *) (* nilpotent G == G is nilpotent, i.e., [~: H, G] is a proper subgroup of H *) (* for all nontrivial H <| G. *) (* solvable G == G is solvable, i.e., H^`(1) is a proper subgroup of H for *) (* all nontrivial subgroups H of G. *) (* 'L_n(G) == the nth term of the lower central series, namely *) (* [~: G, ..., G] (n Gs) if n > 0, with 'L_0(G) = G. *) (* G is nilpotent iff 'L_n(G) = 1 for some n. *) (* 'Z_n(G) == the nth term of the upper central series, i.e., *) (* with 'Z_0(G) = 1, 'Z_n.+1(G) / 'Z_n(G) = 'Z(G / 'Z_n(G)). *) (* nil_class G == the nilpotence class of G, i.e., the least n such that *) (* 'L_n.+1(G) = 1 (or, equivalently, 'Z_n(G) = G), if G is *) (* nilpotent; we take nil_class G = #|G| when G is not *) (* nilpotent, so nil_class G < #|G| iff G is nilpotent. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Section SeriesDefs. Variables (n : nat) (gT : finGroupType) (A : {set gT}). (* By convention, the lower central series starts at 1 while the upper series *) (* starts at 0 (sic). *) Definition lower_central_at := iter n.-1 (fun B => [~: B, A]) A. Definition upper_central_at := iter n (fun B => coset B @*^-1 'Z(A / B)) 1. End SeriesDefs. Arguments lower_central_at n%_N {gT} A%_g. Arguments upper_central_at n%_N {gT} A%_g : simpl never. Notation "''L_' n ( G )" := (lower_central_at n G) (n at level 2, format "''L_' n ( G )") : group_scope. Notation "''Z_' n ( G )" := (upper_central_at n G) (n at level 2, format "''Z_' n ( G )") : group_scope. Section PropertiesDefs. Variables (gT : finGroupType) (A : {set gT}). Definition nilpotent := [forall (G : {group gT} | G \subset A :&: [~: G, A]), G :==: 1]. Definition nil_class := index 1 (mkseq (fun n => 'L_n.+1(A)) #|A|). Definition solvable := [forall (G : {group gT} | G \subset A :&: [~: G, G]), G :==: 1]. End PropertiesDefs. Arguments nilpotent {gT} A%_g. Arguments nil_class {gT} A%_g. Arguments solvable {gT} A%_g. Section NilpotentProps. Variable gT: finGroupType. Implicit Types (A B : {set gT}) (G H : {group gT}). Lemma nilpotent1 : nilpotent [1 gT]. Proof. by apply/forall_inP=> H; rewrite commG1 setIid -subG1. Qed. Lemma nilpotentS A B : B \subset A -> nilpotent A -> nilpotent B. Proof. move=> sBA nilA; apply/forall_inP=> H sHR. have:= forallP nilA H; rewrite (subset_trans sHR) //. by apply: subset_trans (setIS _ _) (setSI _ _); rewrite ?commgS. Qed. Lemma nil_comm_properl G H A : nilpotent G -> H \subset G -> H :!=: 1 -> A \subset 'N_G(H) -> [~: H, A] \proper H. Proof. move=> nilG sHG ntH; rewrite subsetI properE; case/andP=> sAG nHA. rewrite (subset_trans (commgS H (subset_gen A))) ?commg_subl ?gen_subG //. apply: contra ntH => sHR; have:= forallP nilG H; rewrite subsetI sHG. by rewrite (subset_trans sHR) ?commgS. Qed. Lemma nil_comm_properr G A H : nilpotent G -> H \subset G -> H :!=: 1 -> A \subset 'N_G(H) -> [~: A, H] \proper H. Proof. by rewrite commGC; apply: nil_comm_properl. Qed. Lemma centrals_nil (s : seq {group gT}) G : G.-central.-series 1%G s -> last 1%G s = G -> nilpotent G. Proof. move=> cGs defG; apply/forall_inP=> H /subsetIP[sHG sHR]. move: sHG; rewrite -{}defG -subG1 -[1]/(gval 1%G). elim: s 1%G cGs => //= L s IHs K /andP[/and3P[sRK sKL sLG] /IHs sHL] sHs. exact: subset_trans sHR (subset_trans (commSg _ (sHL sHs)) sRK). Qed. End NilpotentProps. Section LowerCentral. Variable gT : finGroupType. Implicit Types (A B : {set gT}) (G H : {group gT}). Lemma lcn0 A : 'L_0(A) = A. Proof. by []. Qed. Lemma lcn1 A : 'L_1(A) = A. Proof. by []. Qed. Lemma lcnSn n A : 'L_n.+2(A) = [~: 'L_n.+1(A), A]. Proof. by []. Qed. Lemma lcnSnS n G : [~: 'L_n(G), G] \subset 'L_n.+1(G). Proof. by case: n => //; apply: der1_subG. Qed. Lemma lcnE n A : 'L_n.+1(A) = iter n (fun B => [~: B, A]) A. Proof. by []. Qed. Lemma lcn2 A : 'L_2(A) = A^`(1). Proof. by []. Qed. Lemma lcn_group_set n G : group_set 'L_n(G). Proof. by case: n => [|[|n]]; apply: groupP. Qed. Canonical lower_central_at_group n G := Group (lcn_group_set n G). Lemma lcn_char n G : 'L_n(G) \char G. Proof. by case: n; last elim=> [|n IHn]; rewrite ?char_refl ?lcnSn ?charR. Qed. Lemma lcn_normal n G : 'L_n(G) <| G. Proof. exact/char_normal/lcn_char. Qed. Lemma lcn_sub n G : 'L_n(G) \subset G. Proof. exact/char_sub/lcn_char. Qed. Lemma lcn_norm n G : G \subset 'N('L_n(G)). Proof. exact/char_norm/lcn_char. Qed. Lemma lcn_subS n G : 'L_n.+1(G) \subset 'L_n(G). Proof. case: n => // n; rewrite lcnSn commGC commg_subr. by case/andP: (lcn_normal n.+1 G). Qed. Lemma lcn_normalS n G : 'L_n.+1(G) <| 'L_n(G). Proof. by apply: normalS (lcn_normal _ _); rewrite (lcn_subS, lcn_sub). Qed. Lemma lcn_central n G : 'L_n(G) / 'L_n.+1(G) \subset 'Z(G / 'L_n.+1(G)). Proof. case: n => [|n]; first by rewrite trivg_quotient sub1G. by rewrite subsetI quotientS ?lcn_sub ?quotient_cents2r. Qed. Lemma lcn_sub_leq m n G : n <= m -> 'L_m(G) \subset 'L_n(G). Proof. by move/subnK <-; elim: {m}(m - n) => // m; apply: subset_trans (lcn_subS _ _). Qed. Lemma lcnS n A B : A \subset B -> 'L_n(A) \subset 'L_n(B). Proof. by case: n => // n sAB; elim: n => // n IHn; rewrite !lcnSn genS ?imset2S. Qed. Lemma lcn_cprod n A B G : A \* B = G -> 'L_n(A) \* 'L_n(B) = 'L_n(G). Proof. case: n => // n /cprodP[[H K -> ->{A B}] defG cHK]. have sL := subset_trans (lcn_sub _ _); rewrite cprodE ?(centSS _ _ cHK) ?sL //. symmetry; elim: n => // n; rewrite lcnSn => ->; rewrite commMG /=; last first. by apply: subset_trans (commg_normr _ _); rewrite sL // -defG mulG_subr. rewrite -!(commGC G) -defG -{1}(centC cHK). rewrite !commMG ?normsR ?lcn_norm ?cents_norm // 1?centsC //. by rewrite -!(commGC 'L__(_)) -!lcnSn !(commG1P _) ?mul1g ?sL // centsC. Qed. Lemma lcn_dprod n A B G : A \x B = G -> 'L_n(A) \x 'L_n(B) = 'L_n(G). Proof. move=> defG; have [[K H defA defB] _ _ tiAB] := dprodP defG. rewrite !dprodEcp // in defG *; first exact: lcn_cprod. by rewrite defA defB; apply/trivgP; rewrite -tiAB defA defB setISS ?lcn_sub. Qed. Lemma der_cprod n A B G : A \* B = G -> A^`(n) \* B^`(n) = G^`(n). Proof. by move=> defG; elim: n => {defG}// n; apply: (lcn_cprod 2). Qed. Lemma der_dprod n A B G : A \x B = G -> A^`(n) \x B^`(n) = G^`(n). Proof. by move=> defG; elim: n => {defG}// n; apply: (lcn_dprod 2). Qed. Lemma lcn_bigcprod n I r P (F : I -> {set gT}) G : \big[cprod/1]_(i <- r | P i) F i = G -> \big[cprod/1]_(i <- r | P i) 'L_n(F i) = 'L_n(G). Proof. elim/big_rec2: _ G => [_ <- | i A Z _ IH G dG]; first exact/esym/trivgP/lcn_sub. by rewrite -(lcn_cprod n dG); have [[_ H _ dH]] := cprodP dG; rewrite dH (IH H). Qed. Lemma lcn_bigdprod n I r P (F : I -> {set gT}) G : \big[dprod/1]_(i <- r | P i) F i = G -> \big[dprod/1]_(i <- r | P i) 'L_n(F i) = 'L_n(G). Proof. elim/big_rec2: _ G => [_ <- | i A Z _ IH G dG]; first exact/esym/trivgP/lcn_sub. by rewrite -(lcn_dprod n dG); have [[_ H _ dH]] := dprodP dG; rewrite dH (IH H). Qed. Lemma der_bigcprod n I r P (F : I -> {set gT}) G : \big[cprod/1]_(i <- r | P i) F i = G -> \big[cprod/1]_(i <- r | P i) (F i)^`(n) = G^`(n). Proof. elim/big_rec2: _ G => [_ <- | i A Z _ IH G dG]; first by rewrite gF1. by rewrite -(der_cprod n dG); have [[_ H _ dH]] := cprodP dG; rewrite dH (IH H). Qed. Lemma der_bigdprod n I r P (F : I -> {set gT}) G : \big[dprod/1]_(i <- r | P i) F i = G -> \big[dprod/1]_(i <- r | P i) (F i)^`(n) = G^`(n). Proof. elim/big_rec2: _ G => [_ <- | i A Z _ IH G dG]; first by rewrite gF1. by rewrite -(der_dprod n dG); have [[_ H _ dH]] := dprodP dG; rewrite dH (IH H). Qed. Lemma nilpotent_class G : nilpotent G = (nil_class G < #|G|). Proof. rewrite /nil_class; set s := mkseq _ _. transitivity (1 \in s); last by rewrite -index_mem size_mkseq. apply/idP/mapP=> {s}/= [nilG | [n _ Ln1]]; last first. apply/forall_inP=> H /subsetIP[sHG sHR]. rewrite -subG1 {}Ln1; elim: n => // n IHn. by rewrite (subset_trans sHR) ?commSg. pose m := #|G|.-1; exists m; first by rewrite mem_iota /= prednK. set n := m; rewrite ['L__(G)]card_le1_trivg //= -(subnn m) -[m in _ - m]/n. elim: n => [|n]; [by rewrite subn0 prednK | rewrite lcnSn subnS]. case: (eqsVneq 'L_n.+1(G) 1) => [-> | ntLn]; first by rewrite comm1G cards1. case: (m - n) => [|m' /= IHn]; first by rewrite leqNgt cardG_gt1 ntLn. rewrite -ltnS (leq_trans (proper_card _) IHn) //. by rewrite (nil_comm_properl nilG) ?lcn_sub // subsetI subxx lcn_norm. Qed. Lemma lcn_nil_classP n G : nilpotent G -> reflect ('L_n.+1(G) = 1) (nil_class G <= n). Proof. rewrite nilpotent_class /nil_class; set s := mkseq _ _. set c := index 1 s => lt_c_G; case: leqP => [le_c_n | lt_n_c]. have Lc1: nth 1 s c = 1 by rewrite nth_index // -index_mem size_mkseq. by left; apply/trivgP; rewrite -Lc1 nth_mkseq ?lcn_sub_leq. right; apply/eqP/negPf; rewrite -(before_find 1 lt_n_c) nth_mkseq //. exact: ltn_trans lt_n_c lt_c_G. Qed. Lemma lcnP G : reflect (exists n, 'L_n.+1(G) = 1) (nilpotent G). Proof. apply: (iffP idP) => [nilG | [n Ln1]]. by exists (nil_class G); apply/lcn_nil_classP. apply/forall_inP=> H /subsetIP[sHG sHR]; rewrite -subG1 -{}Ln1. by elim: n => // n IHn; rewrite (subset_trans sHR) ?commSg. Qed. Lemma abelian_nil G : abelian G -> nilpotent G. Proof. by move=> abG; apply/lcnP; exists 1%N; apply/commG1P. Qed. Lemma nil_class0 G : (nil_class G == 0) = (G :==: 1). Proof. apply/idP/eqP=> [nilG | ->]. by apply/(lcn_nil_classP 0); rewrite ?nilpotent_class (eqP nilG) ?cardG_gt0. by rewrite -leqn0; apply/(lcn_nil_classP 0); rewrite ?nilpotent1. Qed. Lemma nil_class1 G : (nil_class G <= 1) = abelian G. Proof. have [-> | ntG] := eqsVneq G 1. by rewrite abelian1 leq_eqVlt ltnS leqn0 nil_class0 eqxx orbT. apply/idP/idP=> cGG. apply/commG1P; apply/(lcn_nil_classP 1); rewrite // nilpotent_class. by rewrite (leq_ltn_trans cGG) // cardG_gt1. by apply/(lcn_nil_classP 1); rewrite ?abelian_nil //; apply/commG1P. Qed. Lemma cprod_nil A B G : A \* B = G -> nilpotent G = nilpotent A && nilpotent B. Proof. move=> defG; case/cprodP: defG (defG) => [[H K -> ->{A B}] defG _] defGc. apply/idP/andP=> [nilG | [/lcnP[m LmH1] /lcnP[n LnK1]]]. by rewrite !(nilpotentS _ nilG) // -defG (mulG_subr, mulG_subl). apply/lcnP; exists (m + n.+1); apply/trivgP. case/cprodP: (lcn_cprod (m.+1 + n.+1) defGc) => _ <- _. by rewrite mulG_subG /= -{1}LmH1 -LnK1 !lcn_sub_leq ?leq_addl ?leq_addr. Qed. Lemma mulg_nil G H : H \subset 'C(G) -> nilpotent (G * H) = nilpotent G && nilpotent H. Proof. by move=> cGH; rewrite -(cprod_nil (cprodEY cGH)) /= cent_joinEr. Qed. Lemma dprod_nil A B G : A \x B = G -> nilpotent G = nilpotent A && nilpotent B. Proof. by case/dprodP=> [[H K -> ->] <- cHK _]; rewrite mulg_nil. Qed. Lemma bigdprod_nil I r (P : pred I) (A_ : I -> {set gT}) G : \big[dprod/1]_(i <- r | P i) A_ i = G -> (forall i, P i -> nilpotent (A_ i)) -> nilpotent G. Proof. move=> defG nilA; elim/big_rec: _ => [|i B Pi nilB] in G defG *. by rewrite -defG nilpotent1. have [[_ H _ defB] _ _ _] := dprodP defG. by rewrite (dprod_nil defG) nilA //= defB nilB. Qed. End LowerCentral. Notation "''L_' n ( G )" := (lower_central_at_group n G) : Group_scope. Lemma lcn_cont n : GFunctor.continuous (@lower_central_at n). Proof. case: n => //; elim=> // n IHn g0T h0T H phi. by rewrite !lcnSn morphimR ?lcn_sub // commSg ?IHn. Qed. Canonical lcn_igFun n := [igFun by lcn_sub^~ n & lcn_cont n]. Canonical lcn_gFun n := [gFun by lcn_cont n]. Canonical lcn_mgFun n := [mgFun by fun _ G H => @lcnS _ n G H]. Section UpperCentralFunctor. Variable n : nat. Implicit Type gT : finGroupType. Lemma ucn_pmap : exists hZ : GFunctor.pmap, @upper_central_at n = hZ. Proof. elim: n => [|n' [hZ defZ]]; first by exists trivGfun_pgFun. by exists [pgFun of @center %% hZ]; rewrite /= -defZ. Qed. (* Now extract all the intermediate facts of the last proof. *) Lemma ucn_group_set gT (G : {group gT}) : group_set 'Z_n(G). Proof. by have [hZ ->] := ucn_pmap; apply: groupP. Qed. Canonical upper_central_at_group gT G := Group (@ucn_group_set gT G). Lemma ucn_sub gT (G : {group gT}) : 'Z_n(G) \subset G. Proof. by have [hZ ->] := ucn_pmap; apply: gFsub. Qed. Lemma morphim_ucn : GFunctor.pcontinuous (@upper_central_at n). Proof. by have [hZ ->] := ucn_pmap; apply: pmorphimF. Qed. Canonical ucn_igFun := [igFun by ucn_sub & morphim_ucn]. Canonical ucn_gFun := [gFun by morphim_ucn]. Canonical ucn_pgFun := [pgFun by morphim_ucn]. Variable (gT : finGroupType) (G : {group gT}). Lemma ucn_char : 'Z_n(G) \char G. Proof. exact: gFchar. Qed. Lemma ucn_norm : G \subset 'N('Z_n(G)). Proof. exact: gFnorm. Qed. Lemma ucn_normal : 'Z_n(G) <| G. Proof. exact: gFnormal. Qed. End UpperCentralFunctor. Notation "''Z_' n ( G )" := (upper_central_at_group n G) : Group_scope. Section UpperCentral. Variable gT : finGroupType. Implicit Types (A B : {set gT}) (G H : {group gT}). Lemma ucn0 A : 'Z_0(A) = 1. Proof. by []. Qed. Lemma ucnSn n A : 'Z_n.+1(A) = coset 'Z_n(A) @*^-1 'Z(A / 'Z_n(A)). Proof. by []. Qed. Lemma ucnE n A : 'Z_n(A) = iter n (fun B => coset B @*^-1 'Z(A / B)) 1. Proof. by []. Qed. Lemma ucn_subS n G : 'Z_n(G) \subset 'Z_n.+1(G). Proof. by rewrite -{1}['Z_n(G)]ker_coset morphpreS ?sub1G. Qed. Lemma ucn_sub_geq m n G : n >= m -> 'Z_m(G) \subset 'Z_n(G). Proof. move/subnK <-; elim: {n}(n - m) => // n IHn. exact: subset_trans (ucn_subS _ _). Qed. Lemma ucn_central n G : 'Z_n.+1(G) / 'Z_n(G) = 'Z(G / 'Z_n(G)). Proof. by rewrite ucnSn cosetpreK. Qed. Lemma ucn_normalS n G : 'Z_n(G) <| 'Z_n.+1(G). Proof. by rewrite (normalS _ _ (ucn_normal n G)) ?ucn_subS ?ucn_sub. Qed. Lemma ucn_comm n G : [~: 'Z_n.+1(G), G] \subset 'Z_n(G). Proof. rewrite -quotient_cents2 ?normal_norm ?ucn_normal ?ucn_normalS //. by rewrite ucn_central subsetIr. Qed. Lemma ucn1 G : 'Z_1(G) = 'Z(G). Proof. apply: (quotient_inj (normal1 _) (normal1 _)). by rewrite /= (ucn_central 0) -injmF ?norms1 ?coset1_injm. Qed. Lemma ucnSnR n G : 'Z_n.+1(G) = [set x in G | [~: [set x], G] \subset 'Z_n(G)]. Proof. (* apply/setP=> x; rewrite inE -(setIidPr (ucn_sub n.+1 G)) inE ucnSn. *) (* FIXME: before, we got a `rewrite inE` right after the apply/setP=> x. * * However, this rewrite unfolds termes to strange internal HB names. * * We fixed the issue by applying the inE more carefully, but the problem * * needs to be investigated. *) apply/setP=> x; rewrite -(setIidPr (ucn_sub n.+1 G)) [LHS]inE [RHS]inE ucnSn. case Gx: (x \in G) => //=; have nZG := ucn_norm n G. rewrite -sub1set -sub_quotient_pre -?quotient_cents2 ?sub1set ?(subsetP nZG) //. by rewrite subsetI quotientS ?sub1set. Qed. Lemma ucn_cprod n A B G : A \* B = G -> 'Z_n(A) \* 'Z_n(B) = 'Z_n(G). Proof. case/cprodP=> [[H K -> ->{A B}] mulHK cHK]. elim: n => [|n /cprodP[_ /= defZ cZn]]; first exact: cprod1g. set Z := 'Z_n(G) in defZ cZn; rewrite (ucnSn n G) /= -/Z. have /mulGsubP[nZH nZK]: H * K \subset 'N(Z) by rewrite mulHK gFnorm. have <-: 'Z(H / Z) * 'Z(K / Z) = 'Z(G / Z). by rewrite -mulHK quotientMl // center_prod ?quotient_cents. have ZquoZ (B A : {group gT}): B \subset 'C(A) -> 'Z_n(A) * 'Z_n(B) = Z -> 'Z(A / Z) = 'Z_n.+1(A) / Z. - move=> cAB {}defZ; have cAZnB: 'Z_n(B) \subset 'C(A) := gFsub_trans _ cAB. have /second_isom[/=]: A \subset 'N(Z). by rewrite -defZ normsM ?gFnorm ?cents_norm // centsC. suffices ->: Z :&: A = 'Z_n(A). by move=> f inj_f im_f; rewrite -!im_f ?gFsub // ucn_central injm_center. rewrite -defZ -group_modl ?gFsub //; apply/mulGidPl. have [-> | n_gt0] := posnP n; first exact: subsetIl. by apply: subset_trans (ucn_sub_geq A n_gt0); rewrite /= setIC ucn1 setIS. rewrite (ZquoZ H K) 1?centsC 1?(centC cZn) // {ZquoZ}(ZquoZ K H) //. have cZn1: 'Z_n.+1(K) \subset 'C('Z_n.+1(H)) by apply: centSS cHK; apply: gFsub. rewrite -quotientMl ?quotientK ?mul_subG ?gFsub_trans //=. rewrite cprodE // -cent_joinEr ?mulSGid //= cent_joinEr //= -/Z. by rewrite -defZ mulgSS ?ucn_subS. Qed. Lemma ucn_dprod n A B G : A \x B = G -> 'Z_n(A) \x 'Z_n(B) = 'Z_n(G). Proof. move=> defG; have [[K H defA defB] _ _ tiAB] := dprodP defG. rewrite !dprodEcp // in defG *; first exact: ucn_cprod. by rewrite defA defB; apply/trivgP; rewrite -tiAB defA defB setISS ?ucn_sub. Qed. Lemma ucn_bigcprod n I r P (F : I -> {set gT}) G : \big[cprod/1]_(i <- r | P i) F i = G -> \big[cprod/1]_(i <- r | P i) 'Z_n(F i) = 'Z_n(G). Proof. elim/big_rec2: _ G => [_ <- | i A Z _ IH G dG]; first by rewrite gF1. by rewrite -(ucn_cprod n dG); have [[_ H _ dH]] := cprodP dG; rewrite dH (IH H). Qed. Lemma ucn_bigdprod n I r P (F : I -> {set gT}) G : \big[dprod/1]_(i <- r | P i) F i = G -> \big[dprod/1]_(i <- r | P i) 'Z_n(F i) = 'Z_n(G). Proof. elim/big_rec2: _ G => [_ <- | i A Z _ IH G dG]; first by rewrite gF1. by rewrite -(ucn_dprod n dG); have [[_ H _ dH]] := dprodP dG; rewrite dH (IH H). Qed. Lemma ucn_lcnP n G : ('L_n.+1(G) == 1) = ('Z_n(G) == G). Proof. rewrite !eqEsubset sub1G ucn_sub /= andbT -(ucn0 G); set i := (n in LHS). have: i + 0 = n by [rewrite addn0]; elim: i 0 => [j <- //|i IHi j]. rewrite addSnnS => /IHi <- {IHi}; rewrite ucnSn lcnSn. rewrite -sub_morphim_pre ?gFsub_trans ?gFnorm_trans // subsetI. by rewrite morphimS ?gFsub // quotient_cents2 ?gFsub_trans ?gFnorm_trans. Qed. Lemma ucnP G : reflect (exists n, 'Z_n(G) = G) (nilpotent G). Proof. apply: (iffP (lcnP G)) => -[n /eqP-clGn]; by exists n; apply/eqP; rewrite ucn_lcnP in clGn *. Qed. Lemma ucn_nil_classP n G : nilpotent G -> reflect ('Z_n(G) = G) (nil_class G <= n). Proof. move=> nilG; rewrite (sameP (lcn_nil_classP n nilG) eqP) ucn_lcnP; apply: eqP. Qed. Lemma ucn_id n G : 'Z_n('Z_n(G)) = 'Z_n(G). Proof. exact: gFid. Qed. Lemma ucn_nilpotent n G : nilpotent 'Z_n(G). Proof. by apply/ucnP; exists n; rewrite ucn_id. Qed. Lemma nil_class_ucn n G : nil_class 'Z_n(G) <= n. Proof. by apply/ucn_nil_classP; rewrite ?ucn_nilpotent // ucn_id. Qed. End UpperCentral. Section MorphNil. Variables (aT rT : finGroupType) (D : {group aT}) (f : {morphism D >-> rT}). Implicit Type G : {group aT}. Lemma morphim_lcn n G : G \subset D -> f @* 'L_n(G) = 'L_n(f @* G). Proof. move=> sHG; case: n => //; elim=> // n IHn. by rewrite !lcnSn -IHn morphimR // (subset_trans _ sHG) // lcn_sub. Qed. Lemma injm_ucn n G : 'injm f -> G \subset D -> f @* 'Z_n(G) = 'Z_n(f @* G). Proof. exact: injmF. Qed. Lemma morphim_nil G : nilpotent G -> nilpotent (f @* G). Proof. case/ucnP=> n ZnG; apply/ucnP; exists n; apply/eqP. by rewrite eqEsubset ucn_sub /= -{1}ZnG morphim_ucn. Qed. Lemma injm_nil G : 'injm f -> G \subset D -> nilpotent (f @* G) = nilpotent G. Proof. move=> injf sGD; apply/idP/idP; last exact: morphim_nil. case/ucnP=> n; rewrite -injm_ucn // => /injm_morphim_inj defZ. by apply/ucnP; exists n; rewrite defZ ?gFsub_trans. Qed. Lemma nil_class_morphim G : nilpotent G -> nil_class (f @* G) <= nil_class G. Proof. move=> nilG; rewrite (sameP (ucn_nil_classP _ (morphim_nil nilG)) eqP) /=. by rewrite eqEsubset ucn_sub -{1}(ucn_nil_classP _ nilG (leqnn _)) morphim_ucn. Qed. Lemma nil_class_injm G : 'injm f -> G \subset D -> nil_class (f @* G) = nil_class G. Proof. move=> injf sGD; case nilG: (nilpotent G). apply/eqP; rewrite eqn_leq nil_class_morphim //. rewrite (sameP (lcn_nil_classP _ nilG) eqP) -subG1. rewrite -(injmSK injf) ?gFsub_trans // morphim1. by rewrite morphim_lcn // (lcn_nil_classP _ _ (leqnn _)) //= injm_nil. transitivity #|G|; apply/eqP; rewrite eqn_leq. rewrite -(card_injm injf sGD) (leq_trans (index_size _ _)) ?size_mkseq //. by rewrite leqNgt -nilpotent_class injm_nil ?nilG. rewrite (leq_trans (index_size _ _)) ?size_mkseq // leqNgt -nilpotent_class. by rewrite nilG. Qed. End MorphNil. Section QuotientNil. Variables gT : finGroupType. Implicit Types (rT : finGroupType) (G H : {group gT}). Lemma quotient_ucn_add m n G : 'Z_(m + n)(G) / 'Z_n(G) = 'Z_m(G / 'Z_n(G)). Proof. elim: m => [|m IHm]; first exact: trivg_quotient. apply/setP=> Zx; have [x Nx ->{Zx}] := cosetP Zx. have [sZG nZG] := andP (ucn_normal n G). rewrite (ucnSnR m) inE -!sub1set -morphim_set1 //= -quotientR ?sub1set // -IHm. rewrite !quotientSGK ?(ucn_sub_geq, leq_addl, comm_subG _ nZG, sub1set) //=. by rewrite addSn /= ucnSnR inE. Qed. Lemma isog_nil rT G (L : {group rT}) : G \isog L -> nilpotent G = nilpotent L. Proof. by case/isogP=> f injf <-; rewrite injm_nil. Qed. Lemma isog_nil_class rT G (L : {group rT}) : G \isog L -> nil_class G = nil_class L. Proof. by case/isogP=> f injf <-; rewrite nil_class_injm. Qed. Lemma quotient_nil G H : nilpotent G -> nilpotent (G / H). Proof. exact: morphim_nil. Qed. Lemma quotient_center_nil G : nilpotent (G / 'Z(G)) = nilpotent G. Proof. rewrite -ucn1; apply/idP/idP; last exact: quotient_nil. case/ucnP=> c nilGq; apply/ucnP; exists c.+1; have nsZ1G := ucn_normal 1 G. apply: (quotient_inj _ nsZ1G); last by rewrite /= -(addn1 c) quotient_ucn_add. by rewrite (normalS _ _ nsZ1G) ?ucn_sub ?ucn_sub_geq. Qed. Lemma nil_class_quotient_center G : nilpotent (G) -> nil_class (G / 'Z(G)) = (nil_class G).-1. Proof. move=> nilG; have nsZ1G := ucn_normal 1 G. apply/eqP; rewrite -ucn1 eqn_leq; apply/andP; split. apply/ucn_nil_classP; rewrite ?quotient_nil //= -quotient_ucn_add ucn1. by rewrite (ucn_nil_classP _ _ _) ?addn1 ?leqSpred. rewrite -subn1 leq_subLR addnC; apply/ucn_nil_classP => //=. apply: (quotient_inj _ nsZ1G) => /=. by apply: normalS (ucn_sub _ _) nsZ1G; rewrite /= addnS ucn_sub_geq. by rewrite quotient_ucn_add; apply/ucn_nil_classP; rewrite //= quotient_nil. Qed. Lemma nilpotent_sub_norm G H : nilpotent G -> H \subset G -> 'N_G(H) \subset H -> G :=: H. Proof. move=> nilG sHG sNH; apply/eqP; rewrite eqEsubset sHG andbT; apply/negP=> nsGH. have{nsGH} [i sZH []]: exists2 i, 'Z_i(G) \subset H & ~ 'Z_i.+1(G) \subset H. case/ucnP: nilG => n ZnG; rewrite -{}ZnG in nsGH. elim: n => [|i IHi] in nsGH *; first by rewrite sub1G in nsGH. by case sZH: ('Z_i(G) \subset H); [exists i | apply: IHi; rewrite sZH]. apply: subset_trans sNH; rewrite subsetI ucn_sub -commg_subr. by apply: subset_trans sZH; apply: subset_trans (ucn_comm i G); apply: commgS. Qed. Lemma nilpotent_proper_norm G H : nilpotent G -> H \proper G -> H \proper 'N_G(H). Proof. move=> nilG; rewrite properEneq properE subsetI normG => /andP[neHG sHG]. by rewrite sHG; apply: contra neHG => /(nilpotent_sub_norm nilG)->. Qed. Lemma nilpotent_subnormal G H : nilpotent G -> H \subset G -> H <|<| G. Proof. move=> nilG; have [m] := ubnP (#|G| - #|H|). elim: m H => // m IHm H /ltnSE-leGHm sHG. have [->|] := eqVproper sHG; first exact: subnormal_refl. move/(nilpotent_proper_norm nilG); set K := 'N_G(H) => prHK. have snHK: H <|<| K by rewrite normal_subnormal ?normalSG. have sKG: K \subset G by rewrite subsetIl. apply: subnormal_trans snHK (IHm _ (leq_trans _ leGHm) sKG). by rewrite ltn_sub2l ?proper_card ?(proper_sub_trans prHK). Qed. Lemma TI_center_nil G H : nilpotent G -> H <| G -> H :&: 'Z(G) = 1 -> H :=: 1. Proof. move=> nilG /andP[sHG nHG] tiHZ. rewrite -{1}(setIidPl sHG); have{nilG} /ucnP[n <-] := nilG. elim: n => [|n IHn]; apply/trivgP; rewrite ?subsetIr // -tiHZ. rewrite [H :&: 'Z(G)]setIA subsetI setIS ?ucn_sub //= (sameP commG1P trivgP). rewrite -commg_subr commGC in nHG. rewrite -IHn subsetI (subset_trans _ nHG) ?commSg ?subsetIl //=. by rewrite (subset_trans _ (ucn_comm n G)) ?commSg ?subsetIr. Qed. Lemma meet_center_nil G H : nilpotent G -> H <| G -> H :!=: 1 -> H :&: 'Z(G) != 1. Proof. by move=> nilG nsHG; apply: contraNneq => /TI_center_nil->. Qed. Lemma center_nil_eq1 G : nilpotent G -> ('Z(G) == 1) = (G :==: 1). Proof. move=> nilG; apply/eqP/eqP=> [Z1 | ->]; last exact: center1. by rewrite (TI_center_nil nilG) // (setIidPr (center_sub G)). Qed. Lemma cyclic_nilpotent_quo_der1_cyclic G : nilpotent G -> cyclic (G / G^`(1)) -> cyclic G. Proof. move=> nG; rewrite (isog_cyclic (quotient1_isog G)). have [-> // | ntG' cGG'] := (eqVneq G^`(1) 1)%g. suffices: 'L_2(G) \subset G :&: 'L_3(G) by move/(eqfun_inP nG)=> <-. rewrite subsetI lcn_sub /= -quotient_cents2 ?lcn_norm //. apply: cyclic_factor_abelian (lcn_central 2 G) _. by rewrite (isog_cyclic (third_isog _ _ _)) ?lcn_normal // lcn_subS. Qed. End QuotientNil. Section Solvable. Variable gT : finGroupType. Implicit Types G H : {group gT}. Lemma nilpotent_sol G : nilpotent G -> solvable G. Proof. move=> nilG; apply/forall_inP=> H /subsetIP[sHG sHH']. by rewrite (forall_inP nilG) // subsetI sHG (subset_trans sHH') ?commgS. Qed. Lemma abelian_sol G : abelian G -> solvable G. Proof. by move/abelian_nil/nilpotent_sol. Qed. Lemma solvable1 : solvable [1 gT]. Proof. exact: abelian_sol (abelian1 gT). Qed. Lemma solvableS G H : H \subset G -> solvable G -> solvable H. Proof. move=> sHG solG; apply/forall_inP=> K /subsetIP[sKH sKK']. by rewrite (forall_inP solG) // subsetI (subset_trans sKH). Qed. Lemma sol_der1_proper G H : solvable G -> H \subset G -> H :!=: 1 -> H^`(1) \proper H. Proof. move=> solG sHG ntH; rewrite properE comm_subG //; apply: implyP ntH. by have:= forallP solG H; rewrite subsetI sHG implybNN. Qed. Lemma derivedP G : reflect (exists n, G^`(n) = 1) (solvable G). Proof. apply: (iffP idP) => [solG | [n solGn]]; last first. apply/forall_inP=> H /subsetIP[sHG sHH']. rewrite -subG1 -{}solGn; elim: n => // n IHn. exact: subset_trans sHH' (commgSS _ _). suffices IHn n: #|G^`(n)| <= (#|G|.-1 - n).+1. by exists #|G|.-1; rewrite [G^`(_)]card_le1_trivg ?(leq_trans (IHn _)) ?subnn. elim: n => [|n IHn]; first by rewrite subn0 prednK. rewrite dergSn subnS -ltnS. have [-> | ntGn] := eqVneq G^`(n) 1; first by rewrite commG1 cards1. case: (_ - _) IHn => [|n']; first by rewrite leqNgt cardG_gt1 ntGn. by apply: leq_trans (proper_card _); apply: sol_der1_proper (der_sub _ _) _. Qed. End Solvable. Section MorphSol. Variables (gT rT : finGroupType) (D : {group gT}) (f : {morphism D >-> rT}). Variable G : {group gT}. Lemma morphim_sol : solvable G -> solvable (f @* G). Proof. move/(solvableS (subsetIr D G)); case/derivedP=> n Gn1; apply/derivedP. by exists n; rewrite /= -morphimIdom -morphim_der ?subsetIl // Gn1 morphim1. Qed. Lemma injm_sol : 'injm f -> G \subset D -> solvable (f @* G) = solvable G. Proof. move=> injf sGD; apply/idP/idP; last exact: morphim_sol. case/derivedP=> n Gn1; apply/derivedP; exists n; apply/trivgP. by rewrite -(injmSK injf) ?gFsub_trans ?morphim_der // Gn1 morphim1. Qed. End MorphSol. Section QuotientSol. Variables gT rT : finGroupType. Implicit Types G H K : {group gT}. Lemma isog_sol G (L : {group rT}) : G \isog L -> solvable G = solvable L. Proof. by case/isogP=> f injf <-; rewrite injm_sol. Qed. Lemma quotient_sol G H : solvable G -> solvable (G / H). Proof. exact: morphim_sol. Qed. Lemma series_sol G H : H <| G -> solvable G = solvable H && solvable (G / H). Proof. case/andP=> sHG nHG; apply/idP/andP=> [solG | [solH solGH]]. by rewrite quotient_sol // (solvableS sHG). apply/forall_inP=> K /subsetIP[sKG sK'K]. suffices sKH: K \subset H by rewrite (forall_inP solH) // subsetI sKH. have nHK := subset_trans sKG nHG. rewrite -quotient_sub1 // subG1 (forall_inP solGH) //. by rewrite subsetI -morphimR ?morphimS. Qed. Lemma metacyclic_sol G : metacyclic G -> solvable G. Proof. case/metacyclicP=> K [cycK nsKG cycGq]. by rewrite (series_sol nsKG) !abelian_sol ?cyclic_abelian. Qed. End QuotientSol. Section setXn. Import finfun. Lemma setXn_sol n (gT : 'I_n -> finGroupType) (G : forall i, {group gT i}) : (forall i, solvable (G i)) -> solvable (setXn G). Proof. elim: n => [|n IHn] in gT G * => solG; first by rewrite groupX0 solvable1. pose gT' (i : 'I_n) := gT (lift ord0 i). pose prod_group_gT := [the finGroupType of {dffun forall i, gT i}]. pose prod_group_gT' := [the finGroupType of {dffun forall i, gT' i}]. pose f (x : prod_group_gT) : prod_group_gT' := [ffun i => x (lift ord0 i)]. have fm : morphic (setXn G) f. apply/'forall_implyP => -[a b]; rewrite !inE/=. by move=> /andP[/forallP aG /forallP bG]; apply/eqP/ffunP => i; rewrite !ffunE. rewrite (@series_sol _ [group of setXn G] ('ker (morphm fm))) ?ker_normal//=. rewrite (isog_sol (first_isog _))/=. have -> : (morphm fm @* setXn G)%g = setXn (fun i => G (lift ord0 i)). apply/setP => v; rewrite !inE morphimEdom; apply/idP/forallP => /=. move=> /imsetP[/=x]; rewrite inE => /forallP/= xG ->. by move=> i; rewrite morphmE ffunE xG. move=> vG; apply/imsetP. pose w := [ffun i : 'I_n.+1 => match unliftP ord0 i return (gT i) : Type with | UnliftSome j i_eq => ecast i (gT i) (esym i_eq) (v j) | UnliftNone i0 => 1%g end]. have wl i : w (lift ord0 i) = v i. rewrite ffunE; case: unliftP => //= j elij. have eij : i = j by case: elij; apply/val_inj. by rewrite [elij](eq_irrelevance _ (congr1 _ eij)); case: _ / eij. have w0 : w ord0 = 1%g by rewrite ffunE; case: unliftP. exists w; last by apply/ffunP => i; rewrite morphmE ffunE/= wl. apply/setXnP => i. case: (unliftP ord0 i) => [j|]->; rewrite ?wl ?w0 ?vG//. rewrite IHn ?andbT//; last by move=> i; apply: solG. pose k (x : gT ord0) : prod_group_gT := [ffun i : 'I_n.+1 => match (ord0 =P i) return (gT i) : Type with | ReflectT P => ecast i (gT i) P x | _ => 1%g end]. have km : morphic (G ord0) k. apply/'forall_implyP => -[a b]; rewrite !inE/= => /andP[aG bG]. apply/eqP/ffunP => i; rewrite !ffunE; case: eqP => //; rewrite ?mulg1//. by case: _ /. suff -> : ('ker (morphm fm) = morphm km @* G ord0)%g by rewrite morphim_sol. apply/setP => x; rewrite morphimEdom; apply/idP/imsetP => [xker|]. exists (x ord0). by have := dom_ker xker; rewrite inE => /forallP/(_ ord0). rewrite /= morphmE; apply/ffunP => i; rewrite ffunE; case: eqP => //=. by case: _ /. move/eqP; rewrite eq_sym; have /mker/= := xker; rewrite morphmE => /ffunP. by case: (@unliftP _ ord0 i) => [j|] ->//= /(_ j); rewrite !ffunE. move=> [x0 xG0 -> /=]; rewrite morphmE; apply/kerP; rewrite ?inE. by apply/forallP => i; rewrite ffunE; case: eqP => //=; case: _ /. by rewrite /= morphmE; apply/ffunP => i; rewrite !ffunE; case: eqP. Qed. End setXn.
WidePullbacks.lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Jakob von Raumer -/ import Mathlib.CategoryTheory.Limits.HasLimits import Mathlib.CategoryTheory.Thin /-! # Wide pullbacks We define the category `WidePullbackShape`, (resp. `WidePushoutShape`) which is the category obtained from a discrete category of type `J` by adjoining a terminal (resp. initial) element. Limits of this shape are wide pullbacks (pushouts). The convenience method `wideCospan` (`wideSpan`) constructs a functor from this category, hitting the given morphisms. We use `WidePullbackShape` to define ordinary pullbacks (pushouts) by using `J := WalkingPair`, which allows easy proofs of some related lemmas. Furthermore, wide pullbacks are used to show the existence of limits in the slice category. Namely, if `C` has wide pullbacks then `C/B` has limits for any object `B` in `C`. Typeclasses `HasWidePullbacks` and `HasFiniteWidePullbacks` assert the existence of wide pullbacks and finite wide pullbacks. -/ universe w w' v u open CategoryTheory CategoryTheory.Limits Opposite namespace CategoryTheory.Limits variable (J : Type w) /-- A wide pullback shape for any type `J` can be written simply as `Option J`. -/ def WidePullbackShape := Option J instance : Inhabited (WidePullbackShape J) where default := none /-- A wide pushout shape for any type `J` can be written simply as `Option J`. -/ def WidePushoutShape := Option J instance : Inhabited (WidePushoutShape J) where default := none namespace WidePullbackShape variable {J} -- Don't generate unnecessary `sizeOf_spec` lemma which the `simpNF` linter will complain about. set_option genSizeOfSpec false in /-- The type of arrows for the shape indexing a wide pullback. -/ inductive Hom : WidePullbackShape J → WidePullbackShape J → Type w | id : ∀ X, Hom X X | term : ∀ j : J, Hom (some j) none deriving DecidableEq -- This is relying on an automatically generated instance name, generated in a `deriving` handler. -- See https://github.com/leanprover/lean4/issues/2343 attribute [nolint unusedArguments] instDecidableEqHom instance struct : CategoryStruct (WidePullbackShape J) where Hom := Hom id j := Hom.id j comp f g := by cases f · exact g cases g apply Hom.term _ instance Hom.inhabited : Inhabited (Hom (none : WidePullbackShape J) none) := ⟨Hom.id (none : WidePullbackShape J)⟩ open Lean Elab Tactic /- Pointing note: experimenting with manual scoping of aesop tactics. Attempted to define aesop rule directing on `WidePushoutOut` and it didn't take for some reason -/ /-- An aesop tactic for bulk cases on morphisms in `WidePushoutShape` -/ def evalCasesBash : TacticM Unit := do evalTactic (← `(tactic| casesm* WidePullbackShape _, (_ : WidePullbackShape _) ⟶ (_ : WidePullbackShape _) )) attribute [local aesop safe tactic (rule_sets := [CategoryTheory])] evalCasesBash instance subsingleton_hom : Quiver.IsThin (WidePullbackShape J) := fun _ _ => by constructor intro a b casesm* WidePullbackShape _, (_ : WidePullbackShape _) ⟶ (_ : WidePullbackShape _) · rfl · rfl · rfl instance category : SmallCategory (WidePullbackShape J) := thin_category @[simp] theorem hom_id (X : WidePullbackShape J) : Hom.id X = 𝟙 X := rfl variable {C : Type u} [Category.{v} C] /-- Construct a functor out of the wide pullback shape given a J-indexed collection of arrows to a fixed object. -/ @[simps] def wideCospan (B : C) (objs : J → C) (arrows : ∀ j : J, objs j ⟶ B) : WidePullbackShape J ⥤ C where obj j := Option.casesOn j B objs map f := by obtain - | j := f · apply 𝟙 _ · exact arrows j /-- Every diagram is naturally isomorphic (actually, equal) to a `wideCospan` -/ def diagramIsoWideCospan (F : WidePullbackShape J ⥤ C) : F ≅ wideCospan (F.obj none) (fun j => F.obj (some j)) fun j => F.map (Hom.term j) := NatIso.ofComponents fun j => eqToIso <| by cat_disch /-- Construct a cone over a wide cospan. -/ @[simps] def mkCone {F : WidePullbackShape J ⥤ C} {X : C} (f : X ⟶ F.obj none) (π : ∀ j, X ⟶ F.obj (some j)) (w : ∀ j, π j ≫ F.map (Hom.term j) = f) : Cone F := { pt := X π := { app := fun j => match j with | none => f | some j => π j naturality := fun j j' f => by cases j <;> cases j' <;> cases f <;> simp [w] } } /-- Wide pullback diagrams of equivalent index types are equivalent. -/ def equivalenceOfEquiv (J' : Type w') (h : J ≃ J') : WidePullbackShape J ≌ WidePullbackShape J' where functor := wideCospan none (fun j => some (h j)) fun j => Hom.term (h j) inverse := wideCospan none (fun j => some (h.invFun j)) fun j => Hom.term (h.invFun j) unitIso := NatIso.ofComponents (fun j => by cases j <;> exact eqToIso (by simp)) counitIso := NatIso.ofComponents (fun j => by cases j <;> exact eqToIso (by simp)) attribute [local instance] uliftCategory in /-- Lifting universe and morphism levels preserves wide pullback diagrams. -/ def uliftEquivalence : ULiftHom.{w'} (ULift.{w'} (WidePullbackShape J)) ≌ WidePullbackShape (ULift J) := (ULiftHomULiftCategory.equiv.{w', w', w, w} (WidePullbackShape J)).symm.trans (equivalenceOfEquiv _ (Equiv.ulift.{w', w}.symm : J ≃ ULift.{w'} J)) end WidePullbackShape namespace WidePushoutShape variable {J} -- Don't generate unnecessary `sizeOf_spec` lemma which the `simpNF` linter will complain about. set_option genSizeOfSpec false in /-- The type of arrows for the shape indexing a wide pushout. -/ inductive Hom : WidePushoutShape J → WidePushoutShape J → Type w | id : ∀ X, Hom X X | init : ∀ j : J, Hom none (some j) deriving DecidableEq -- This is relying on an automatically generated instance name, generated in a `deriving` handler. -- See https://github.com/leanprover/lean4/issues/2343 attribute [nolint unusedArguments] instDecidableEqHom instance struct : CategoryStruct (WidePushoutShape J) where Hom := Hom id j := Hom.id j comp f g := by cases f · exact g cases g apply Hom.init _ instance Hom.inhabited : Inhabited (Hom (none : WidePushoutShape J) none) := ⟨Hom.id (none : WidePushoutShape J)⟩ open Lean Elab Tactic -- Pointing note: experimenting with manual scoping of aesop tactics; only this worked /-- An aesop tactic for bulk cases on morphisms in `WidePushoutShape` -/ def evalCasesBash' : TacticM Unit := do evalTactic (← `(tactic| casesm* WidePushoutShape _, (_ : WidePushoutShape _) ⟶ (_ : WidePushoutShape _) )) attribute [local aesop safe tactic (rule_sets := [CategoryTheory])] evalCasesBash' instance subsingleton_hom : Quiver.IsThin (WidePushoutShape J) := fun _ _ => by constructor intro a b casesm* WidePushoutShape _, (_ : WidePushoutShape _) ⟶ (_ : WidePushoutShape _) repeat rfl instance category : SmallCategory (WidePushoutShape J) := thin_category @[simp] theorem hom_id (X : WidePushoutShape J) : Hom.id X = 𝟙 X := rfl variable {C : Type u} [Category.{v} C] /-- Construct a functor out of the wide pushout shape given a J-indexed collection of arrows from a fixed object. -/ @[simps] def wideSpan (B : C) (objs : J → C) (arrows : ∀ j : J, B ⟶ objs j) : WidePushoutShape J ⥤ C where obj j := Option.casesOn j B objs map f := by obtain - | j := f · apply 𝟙 _ · exact arrows j map_comp := fun f g => by cases f · simp only [hom_id, Category.id_comp]; congr · cases g simp only [hom_id, Category.comp_id]; congr /-- Every diagram is naturally isomorphic (actually, equal) to a `wideSpan` -/ def diagramIsoWideSpan (F : WidePushoutShape J ⥤ C) : F ≅ wideSpan (F.obj none) (fun j => F.obj (some j)) fun j => F.map (Hom.init j) := NatIso.ofComponents fun j => eqToIso <| by cases j; repeat rfl /-- Construct a cocone over a wide span. -/ @[simps] def mkCocone {F : WidePushoutShape J ⥤ C} {X : C} (f : F.obj none ⟶ X) (ι : ∀ j, F.obj (some j) ⟶ X) (w : ∀ j, F.map (Hom.init j) ≫ ι j = f) : Cocone F := { pt := X ι := { app := fun j => match j with | none => f | some j => ι j naturality := fun j j' f => by cases j <;> cases j' <;> cases f <;> simp [w] } } /-- Wide pushout diagrams of equivalent index types are equivalent. -/ def equivalenceOfEquiv (J' : Type w') (h : J ≃ J') : WidePushoutShape J ≌ WidePushoutShape J' where functor := wideSpan none (fun j => some (h j)) fun j => Hom.init (h j) inverse := wideSpan none (fun j => some (h.invFun j)) fun j => Hom.init (h.invFun j) unitIso := NatIso.ofComponents (fun j => by cases j <;> exact eqToIso (by simp)) counitIso := NatIso.ofComponents (fun j => by cases j <;> exact eqToIso (by simp)) attribute [local instance] uliftCategory in /-- Lifting universe and morphism levels preserves wide pushout diagrams. -/ def uliftEquivalence : ULiftHom.{w'} (ULift.{w'} (WidePushoutShape J)) ≌ WidePushoutShape (ULift J) := (ULiftHomULiftCategory.equiv.{w', w', w, w} (WidePushoutShape J)).symm.trans (equivalenceOfEquiv _ (Equiv.ulift.{w', w}.symm : J ≃ ULift.{w'} J)) end WidePushoutShape variable (C : Type u) [Category.{v} C] /-- `HasWidePullbacks` represents a choice of wide pullback for every collection of morphisms -/ abbrev HasWidePullbacks : Prop := ∀ J : Type w, HasLimitsOfShape (WidePullbackShape J) C /-- `HasWidePushouts` represents a choice of wide pushout for every collection of morphisms -/ abbrev HasWidePushouts : Prop := ∀ J : Type w, HasColimitsOfShape (WidePushoutShape J) C variable {C J} /-- `HasWidePullback B objs arrows` means that `wideCospan B objs arrows` has a limit. -/ abbrev HasWidePullback (B : C) (objs : J → C) (arrows : ∀ j : J, objs j ⟶ B) : Prop := HasLimit (WidePullbackShape.wideCospan B objs arrows) /-- `HasWidePushout B objs arrows` means that `wideSpan B objs arrows` has a colimit. -/ abbrev HasWidePushout (B : C) (objs : J → C) (arrows : ∀ j : J, B ⟶ objs j) : Prop := HasColimit (WidePushoutShape.wideSpan B objs arrows) /-- A choice of wide pullback. -/ noncomputable abbrev widePullback (B : C) (objs : J → C) (arrows : ∀ j : J, objs j ⟶ B) [HasWidePullback B objs arrows] : C := limit (WidePullbackShape.wideCospan B objs arrows) /-- A choice of wide pushout. -/ noncomputable abbrev widePushout (B : C) (objs : J → C) (arrows : ∀ j : J, B ⟶ objs j) [HasWidePushout B objs arrows] : C := colimit (WidePushoutShape.wideSpan B objs arrows) namespace WidePullback variable {C : Type u} [Category.{v} C] {B : C} {objs : J → C} (arrows : ∀ j : J, objs j ⟶ B) variable [HasWidePullback B objs arrows] /-- The `j`-th projection from the pullback. -/ noncomputable abbrev π (j : J) : widePullback _ _ arrows ⟶ objs j := limit.π (WidePullbackShape.wideCospan _ _ _) (Option.some j) /-- The unique map to the base from the pullback. -/ noncomputable abbrev base : widePullback _ _ arrows ⟶ B := limit.π (WidePullbackShape.wideCospan _ _ _) Option.none @[reassoc (attr := simp)] theorem π_arrow (j : J) : π arrows j ≫ arrows _ = base arrows := by apply limit.w (WidePullbackShape.wideCospan _ _ _) (WidePullbackShape.Hom.term j) variable {arrows} in /-- Lift a collection of morphisms to a morphism to the pullback. -/ noncomputable abbrev lift {X : C} (f : X ⟶ B) (fs : ∀ j : J, X ⟶ objs j) (w : ∀ j, fs j ≫ arrows j = f) : X ⟶ widePullback _ _ arrows := limit.lift (WidePullbackShape.wideCospan _ _ _) (WidePullbackShape.mkCone f fs <| w) variable {X : C} (f : X ⟶ B) (fs : ∀ j : J, X ⟶ objs j) (w : ∀ j, fs j ≫ arrows j = f) @[reassoc] theorem lift_π (j : J) : lift f fs w ≫ π arrows j = fs _ := by simp only [limit.lift_π, WidePullbackShape.mkCone_pt, WidePullbackShape.mkCone_π_app] @[reassoc] theorem lift_base : lift f fs w ≫ base arrows = f := by simp only [limit.lift_π, WidePullbackShape.mkCone_pt, WidePullbackShape.mkCone_π_app] theorem eq_lift_of_comp_eq (g : X ⟶ widePullback _ _ arrows) : (∀ j : J, g ≫ π arrows j = fs j) → g ≫ base arrows = f → g = lift f fs w := by intro h1 h2 apply (limit.isLimit (WidePullbackShape.wideCospan B objs arrows)).uniq (WidePullbackShape.mkCone f fs <| w) rintro (_ | _) · apply h2 · apply h1 theorem hom_eq_lift (g : X ⟶ widePullback _ _ arrows) : g = lift (g ≫ base arrows) (fun j => g ≫ π arrows j) (by simp) := by aesop @[ext 1100] theorem hom_ext (g1 g2 : X ⟶ widePullback _ _ arrows) : (∀ j : J, g1 ≫ π arrows j = g2 ≫ π arrows j) → g1 ≫ base arrows = g2 ≫ base arrows → g1 = g2 := by intro h1 h2 apply limit.hom_ext rintro (_ | _) · apply h2 · apply h1 end WidePullback namespace WidePushout variable {C : Type u} [Category.{v} C] {B : C} {objs : J → C} (arrows : ∀ j : J, B ⟶ objs j) variable [HasWidePushout B objs arrows] /-- The `j`-th inclusion to the pushout. -/ noncomputable abbrev ι (j : J) : objs j ⟶ widePushout _ _ arrows := colimit.ι (WidePushoutShape.wideSpan _ _ _) (Option.some j) /-- The unique map from the head to the pushout. -/ noncomputable abbrev head : B ⟶ widePushout B objs arrows := colimit.ι (WidePushoutShape.wideSpan _ _ _) Option.none @[reassoc, simp] theorem arrow_ι (j : J) : arrows j ≫ ι arrows j = head arrows := by apply colimit.w (WidePushoutShape.wideSpan _ _ _) (WidePushoutShape.Hom.init j) variable {arrows} in /-- Descend a collection of morphisms to a morphism from the pushout. -/ noncomputable abbrev desc {X : C} (f : B ⟶ X) (fs : ∀ j : J, objs j ⟶ X) (w : ∀ j, arrows j ≫ fs j = f) : widePushout _ _ arrows ⟶ X := colimit.desc (WidePushoutShape.wideSpan B objs arrows) (WidePushoutShape.mkCocone f fs <| w) variable {X : C} (f : B ⟶ X) (fs : ∀ j : J, objs j ⟶ X) (w : ∀ j, arrows j ≫ fs j = f) @[reassoc] theorem ι_desc (j : J) : ι arrows j ≫ desc f fs w = fs _ := by simp only [colimit.ι_desc, WidePushoutShape.mkCocone_pt, WidePushoutShape.mkCocone_ι_app] @[reassoc] theorem head_desc : head arrows ≫ desc f fs w = f := by simp only [colimit.ι_desc, WidePushoutShape.mkCocone_pt, WidePushoutShape.mkCocone_ι_app] theorem eq_desc_of_comp_eq (g : widePushout _ _ arrows ⟶ X) : (∀ j : J, ι arrows j ≫ g = fs j) → head arrows ≫ g = f → g = desc f fs w := by intro h1 h2 apply (colimit.isColimit (WidePushoutShape.wideSpan B objs arrows)).uniq (WidePushoutShape.mkCocone f fs <| w) rintro (_ | _) · apply h2 · apply h1 theorem hom_eq_desc (g : widePushout _ _ arrows ⟶ X) : g = desc (head arrows ≫ g) (fun j => ι arrows j ≫ g) fun j => by rw [← Category.assoc] simp := by apply eq_desc_of_comp_eq · simp · rfl -- Porting note: another missing rfl @[ext 1100] theorem hom_ext (g1 g2 : widePushout _ _ arrows ⟶ X) : (∀ j : J, ι arrows j ≫ g1 = ι arrows j ≫ g2) → head arrows ≫ g1 = head arrows ≫ g2 → g1 = g2 := by intro h1 h2 apply colimit.hom_ext rintro (_ | _) · apply h2 · apply h1 end WidePushout variable (J) /-- The action on morphisms of the obvious functor `WidePullbackShape_op : WidePullbackShape J ⥤ (WidePushoutShape J)ᵒᵖ` -/ def widePullbackShapeOpMap : ∀ X Y : WidePullbackShape J, (X ⟶ Y) → ((op X : (WidePushoutShape J)ᵒᵖ) ⟶ (op Y : (WidePushoutShape J)ᵒᵖ)) | _, _, WidePullbackShape.Hom.id X => Quiver.Hom.op (WidePushoutShape.Hom.id _) | _, _, WidePullbackShape.Hom.term _ => Quiver.Hom.op (WidePushoutShape.Hom.init _) /-- The obvious functor `WidePullbackShape J ⥤ (WidePushoutShape J)ᵒᵖ` -/ @[simps] def widePullbackShapeOp : WidePullbackShape J ⥤ (WidePushoutShape J)ᵒᵖ where obj X := op X map {X₁} {X₂} := widePullbackShapeOpMap J X₁ X₂ /-- The action on morphisms of the obvious functor `widePushoutShapeOp : WidePushoutShape J ⥤ (WidePullbackShape J)ᵒᵖ` -/ def widePushoutShapeOpMap : ∀ X Y : WidePushoutShape J, (X ⟶ Y) → ((op X : (WidePullbackShape J)ᵒᵖ) ⟶ (op Y : (WidePullbackShape J)ᵒᵖ)) | _, _, WidePushoutShape.Hom.id X => Quiver.Hom.op (WidePullbackShape.Hom.id _) | _, _, WidePushoutShape.Hom.init _ => Quiver.Hom.op (WidePullbackShape.Hom.term _) /-- The obvious functor `WidePushoutShape J ⥤ (WidePullbackShape J)ᵒᵖ` -/ @[simps] def widePushoutShapeOp : WidePushoutShape J ⥤ (WidePullbackShape J)ᵒᵖ where obj X := op X map := fun {X} {Y} => widePushoutShapeOpMap J X Y /-- The obvious functor `(WidePullbackShape J)ᵒᵖ ⥤ WidePushoutShape J` -/ @[simps!] def widePullbackShapeUnop : (WidePullbackShape J)ᵒᵖ ⥤ WidePushoutShape J := (widePullbackShapeOp J).leftOp /-- The obvious functor `(WidePushoutShape J)ᵒᵖ ⥤ WidePullbackShape J` -/ @[simps!] def widePushoutShapeUnop : (WidePushoutShape J)ᵒᵖ ⥤ WidePullbackShape J := (widePushoutShapeOp J).leftOp /-- The inverse of the unit isomorphism of the equivalence `widePushoutShapeOpEquiv : (WidePushoutShape J)ᵒᵖ ≌ WidePullbackShape J` -/ def widePushoutShapeOpUnop : widePushoutShapeUnop J ⋙ widePullbackShapeOp J ≅ 𝟭 _ := NatIso.ofComponents fun _ => Iso.refl _ /-- The counit isomorphism of the equivalence `widePullbackShapeOpEquiv : (WidePullbackShape J)ᵒᵖ ≌ WidePushoutShape J` -/ def widePushoutShapeUnopOp : widePushoutShapeOp J ⋙ widePullbackShapeUnop J ≅ 𝟭 _ := NatIso.ofComponents fun _ => Iso.refl _ /-- The inverse of the unit isomorphism of the equivalence `widePullbackShapeOpEquiv : (WidePullbackShape J)ᵒᵖ ≌ WidePushoutShape J` -/ def widePullbackShapeOpUnop : widePullbackShapeUnop J ⋙ widePushoutShapeOp J ≅ 𝟭 _ := NatIso.ofComponents fun _ => Iso.refl _ /-- The counit isomorphism of the equivalence `widePushoutShapeOpEquiv : (WidePushoutShape J)ᵒᵖ ≌ WidePullbackShape J` -/ def widePullbackShapeUnopOp : widePullbackShapeOp J ⋙ widePushoutShapeUnop J ≅ 𝟭 _ := NatIso.ofComponents fun _ => Iso.refl _ /-- The duality equivalence `(WidePushoutShape J)ᵒᵖ ≌ WidePullbackShape J` -/ @[simps] def widePushoutShapeOpEquiv : (WidePushoutShape J)ᵒᵖ ≌ WidePullbackShape J where functor := widePushoutShapeUnop J inverse := widePullbackShapeOp J unitIso := (widePushoutShapeOpUnop J).symm counitIso := widePullbackShapeUnopOp J /-- The duality equivalence `(WidePullbackShape J)ᵒᵖ ≌ WidePushoutShape J` -/ @[simps] def widePullbackShapeOpEquiv : (WidePullbackShape J)ᵒᵖ ≌ WidePushoutShape J where functor := widePullbackShapeUnop J inverse := widePushoutShapeOp J unitIso := (widePullbackShapeOpUnop J).symm counitIso := widePushoutShapeUnopOp J /-- If a category has wide pushouts on a higher universe level it also has wide pushouts on a lower universe level. -/ theorem hasWidePushouts_shrink [HasWidePushouts.{max w w'} C] : HasWidePushouts.{w} C := fun _ => hasColimitsOfShape_of_equivalence (WidePushoutShape.equivalenceOfEquiv _ Equiv.ulift.{w'}) /-- If a category has wide pullbacks on a higher universe level it also has wide pullbacks on a lower universe level. -/ theorem hasWidePullbacks_shrink [HasWidePullbacks.{max w w'} C] : HasWidePullbacks.{w} C := fun _ => hasLimitsOfShape_of_equivalence (WidePullbackShape.equivalenceOfEquiv _ Equiv.ulift.{w'}) end CategoryTheory.Limits
Conformal.lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import Mathlib.Analysis.Calculus.Conformal.NormedSpace import Mathlib.Geometry.Euclidean.Angle.Unoriented.Basic /-! # Angles and conformal maps This file proves that conformal maps preserve angles. -/ namespace InnerProductGeometry variable {E F : Type*} variable [NormedAddCommGroup E] [NormedAddCommGroup F] variable [InnerProductSpace ℝ E] [InnerProductSpace ℝ F] theorem IsConformalMap.preserves_angle {f' : E →L[ℝ] F} (h : IsConformalMap f') (u v : E) : angle (f' u) (f' v) = angle u v := by obtain ⟨c, hc, li, rfl⟩ := h exact (angle_smul_smul hc _ _).trans (li.angle_map _ _) /-- If a real differentiable map `f` is conformal at a point `x`, then it preserves the angles at that point. -/ theorem ConformalAt.preserves_angle {f : E → F} {x : E} {f' : E →L[ℝ] F} (h : HasFDerivAt f f' x) (H : ConformalAt f x) (u v : E) : angle (f' u) (f' v) = angle u v := let ⟨_, h₁, c⟩ := H h₁.unique h ▸ IsConformalMap.preserves_angle c u v end InnerProductGeometry
Differentiable.lean
/- Copyright (c) 2024 Tomáš Skřivan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tomáš Skřivan -/ import Mathlib.Analysis.Calculus.FDeriv.Basic import Mathlib.Analysis.Calculus.FDeriv.Comp import Mathlib.Analysis.Calculus.FDeriv.Prod import Mathlib.Analysis.Calculus.FDeriv.Pi import Mathlib.Analysis.Calculus.FDeriv.Add import Mathlib.Analysis.Calculus.FDeriv.Mul import Mathlib.Analysis.Calculus.Deriv.Inv import Mathlib.Analysis.SpecialFunctions.ExpDeriv import Mathlib.Analysis.SpecialFunctions.Log.Deriv import Mathlib.Tactic.FunProp deprecated_module "fun_prop knows about Differentiable(At/On) directly; no need to import this file any more" (since := "2025-06-25")
Applicative.lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Algebra.Group.Defs import Mathlib.Control.Functor import Mathlib.Control.Basic /-! # `applicative` instances This file provides `Applicative` instances for concrete functors: * `id` * `Functor.comp` * `Functor.const` * `Functor.add_const` -/ universe u v w section Lemmas open Function variable {F : Type u → Type v} variable [Applicative F] [LawfulApplicative F] variable {α β γ σ : Type u} theorem Applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) : f <$> x <*> g <$> y = ((· ∘ g) ∘ f) <$> x <*> y := by simp [functor_norm, Function.comp_def] theorem Applicative.pure_seq_eq_map' (f : α → β) : ((pure f : F (α → β)) <*> ·) = (f <$> ·) := by ext; simp [functor_norm] theorem Applicative.ext {F} : ∀ {A1 : Applicative F} {A2 : Applicative F} [@LawfulApplicative F A1] [@LawfulApplicative F A2], (∀ {α : Type u} (x : α), @Pure.pure _ A1.toPure _ x = @Pure.pure _ A2.toPure _ x) → (∀ {α β : Type u} (f : F (α → β)) (x : F α), @Seq.seq _ A1.toSeq _ _ f (fun _ => x) = @Seq.seq _ A2.toSeq _ _ f (fun _ => x)) → A1 = A2 | { toFunctor := F1, seq := s1, pure := p1, seqLeft := sl1, seqRight := sr1 }, { toFunctor := F2, seq := s2, pure := p2, seqLeft := sl2, seqRight := sr2 }, L1, L2, H1, H2 => by obtain rfl : @p1 = @p2 := by funext α x apply H1 obtain rfl : @s1 = @s2 := by funext α β f x exact H2 f (x Unit.unit) obtain ⟨seqLeft_eq1, seqRight_eq1, pure_seq1, -⟩ := L1 obtain ⟨seqLeft_eq2, seqRight_eq2, pure_seq2, -⟩ := L2 obtain rfl : F1 = F2 := by apply Functor.ext intros exact (pure_seq1 _ _).symm.trans (pure_seq2 _ _) congr <;> funext α β x y · exact (seqLeft_eq1 _ (y Unit.unit)).trans (seqLeft_eq2 _ _).symm · exact (seqRight_eq1 _ (y Unit.unit)).trans (seqRight_eq2 _ (y Unit.unit)).symm end Lemmas -- Porting note: we have a monad instance for `Id` but not `id`, mathport can't tell -- which one is intended instance : CommApplicative Id where commutative_prod _ _ := rfl namespace Functor namespace Comp open Function hiding comp open Functor variable {F : Type u → Type w} {G : Type v → Type u} variable [Applicative F] [Applicative G] variable [LawfulApplicative F] [LawfulApplicative G] variable {α β γ : Type v} theorem map_pure (f : α → β) (x : α) : (f <$> pure x : Comp F G β) = pure (f x) := Comp.ext <| by simp theorem seq_pure (f : Comp F G (α → β)) (x : α) : f <*> pure x = (fun g : α → β => g x) <$> f := Comp.ext <| by simp [functor_norm] theorem seq_assoc (x : Comp F G α) (f : Comp F G (α → β)) (g : Comp F G (β → γ)) : g <*> (f <*> x) = @Function.comp α β γ <$> g <*> f <*> x := Comp.ext <| by simp [comp_def, functor_norm] theorem pure_seq_eq_map (f : α → β) (x : Comp F G α) : pure f <*> x = f <$> x := Comp.ext <| by simp [functor_norm] -- TODO: the first two results were handled by `control_laws_tac` in mathlib3 instance instLawfulApplicativeComp : LawfulApplicative (Comp F G) where seqLeft_eq := by intros; rfl seqRight_eq := by intros; rfl pure_seq := Comp.pure_seq_eq_map map_pure := Comp.map_pure seq_pure := Comp.seq_pure seq_assoc := Comp.seq_assoc theorem applicative_id_comp {F} [AF : Applicative F] [LawfulApplicative F] : @instApplicativeComp Id F _ _ = AF := @Applicative.ext F _ _ (instLawfulApplicativeComp (F := Id)) _ (fun _ => rfl) (fun _ _ => rfl) theorem applicative_comp_id {F} [AF : Applicative F] [LawfulApplicative F] : @Comp.instApplicativeComp F Id _ _ = AF := @Applicative.ext F _ _ (instLawfulApplicativeComp (G := Id)) _ (fun _ => rfl) (fun f x => show id <$> f <*> x = f <*> x by rw [id_map]) open CommApplicative instance {f : Type u → Type w} {g : Type v → Type u} [Applicative f] [Applicative g] [CommApplicative f] [CommApplicative g] : CommApplicative (Comp f g) where commutative_prod _ _ := by simp! [map, Seq.seq] rw [commutative_map] simp only [mk, flip, seq_map_assoc, Function.comp_def, map_map] congr funext x y rw [commutative_map] congr end Comp end Functor open Functor @[functor_norm] theorem Comp.seq_mk {α β : Type w} {f : Type u → Type v} {g : Type w → Type u} [Applicative f] [Applicative g] (h : f (g (α → β))) (x : f (g α)) : Comp.mk h <*> Comp.mk x = Comp.mk ((· <*> ·) <$> h <*> x) := rfl -- Porting note: There is some awkwardness in the following definition now that we have `HMul`. instance {α} [One α] [Mul α] : Applicative (Const α) where pure _ := (1 : α) seq f x := (show α from f) * (show α from x Unit.unit) -- Porting note: `(· <*> ·)` needed to change to `Seq.seq` in the `simp`. -- Also, `simp` didn't close `refl` goals. instance {α} [Monoid α] : LawfulApplicative (Const α) where map_pure _ _ := rfl seq_pure _ _ := by simp only [Seq.seq, pure, mul_one]; rfl pure_seq _ _ := by simp only [Seq.seq, pure, one_mul]; rfl seqLeft_eq _ _ := by simp only [Seq.seq]; rfl seqRight_eq _ _ := by simp only [Seq.seq]; rfl seq_assoc _ _ _ := by simp only [Seq.seq, mul_assoc]; rfl instance {α} [Zero α] [Add α] : Applicative (AddConst α) where pure _ := (0 : α) seq f x := (show α from f) + (show α from x Unit.unit) instance {α} [AddMonoid α] : LawfulApplicative (AddConst α) where map_pure _ _ := rfl seq_pure _ _ := by simp only [Seq.seq, pure, add_zero]; rfl pure_seq _ _ := by simp only [Seq.seq, pure, zero_add]; rfl seqLeft_eq _ _ := by simp only [Seq.seq]; rfl seqRight_eq _ _ := by simp only [Seq.seq]; rfl seq_assoc _ _ _ := by simp only [Seq.seq, add_assoc]; rfl
path.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq. (******************************************************************************) (* The basic theory of paths over an eqType; this file is essentially a *) (* complement to seq.v. Paths are non-empty sequences that obey a progression *) (* relation. They are passed around in three parts: the head and tail of the *) (* sequence, and a proof of a (boolean) predicate asserting the progression. *) (* This "exploded" view is rarely embarrassing, as the first two parameters *) (* are usually inferred from the type of the third; on the contrary, it saves *) (* the hassle of constantly constructing and destructing a dependent record. *) (* We define similarly cycles, for which we allow the empty sequence, *) (* which represents a non-rooted empty cycle; by contrast, the "empty" path *) (* from a point x is the one-item sequence containing only x. *) (* We allow duplicates; uniqueness, if desired (as is the case for several *) (* geometric constructions), must be asserted separately. We do provide *) (* shorthand, but only for cycles, because the equational properties of *) (* "path" and "uniq" are unfortunately incompatible (esp. wrt "cat"). *) (* We define notations for the common cases of function paths, where the *) (* progress relation is actually a function. In detail: *) (* path e x p == x :: p is an e-path [:: x_0; x_1; ... ; x_n], i.e., we *) (* have e x_i x_{i+1} for all i < n. The path x :: p starts *) (* at x and ends at last x p. *) (* fpath f x p == x :: p is an f-path, where f is a function, i.e., p is of *) (* the form [:: f x; f (f x); ...]. This is just a notation *) (* for path (frel f) x p. *) (* sorted e s == s is an e-sorted sequence: either s = [::], or s = x :: p *) (* is an e-path (this is often used with e = leq or ltn). *) (* cycle e c == c is an e-cycle: either c = [::], or c = x :: p with *) (* x :: (rcons p x) an e-path. *) (* fcycle f c == c is an f-cycle, for a function f. *) (* traject f x n == the f-path of size n starting at x *) (* := [:: x; f x; ...; iter n.-1 f x] *) (* looping f x n == the f-paths of size greater than n starting at x loop *) (* back, or, equivalently, traject f x n contains all *) (* iterates of f at x. *) (* merge e s1 s2 == the e-sorted merge of sequences s1 and s2: this is always *) (* a permutation of s1 ++ s2, and is e-sorted when s1 and s2 *) (* are and e is total. *) (* sort e s == a permutation of the sequence s, that is e-sorted when e *) (* is total (computed by a merge sort with the merge function *) (* above). This sort function is also designed to be stable. *) (* mem2 s x y == x, then y occur in the sequence (path) s; this is *) (* non-strict: mem2 s x x = (x \in s). *) (* next c x == the successor of the first occurrence of x in the sequence *) (* c (viewed as a cycle), or x if x \notin c. *) (* prev c x == the predecessor of the first occurrence of x in the *) (* sequence c (viewed as a cycle), or x if x \notin c. *) (* arc c x y == the sub-arc of the sequence c (viewed as a cycle) starting *) (* at the first occurrence of x in c, and ending just before *) (* the next occurrence of y (in cycle order); arc c x y *) (* returns an unspecified sub-arc of c if x and y do not both *) (* occur in c. *) (* ucycle e c <-> ucycleb e c (ucycle e c is a Coercion target of type Prop) *) (* ufcycle f c <-> c is a simple f-cycle, for a function f. *) (* shorten x p == the tail a duplicate-free subpath of x :: p with the same *) (* endpoints (x and last x p), obtained by removing all loops *) (* from x :: p. *) (* rel_base e e' h b <-> the function h is a functor from relation e to *) (* relation e', EXCEPT at points whose image under h satisfy *) (* the "base" predicate b: *) (* e' (h x) (h y) = e x y UNLESS b (h x) holds *) (* This is the statement of the side condition of the path *) (* functorial mapping lemma map_path. *) (* fun_base f f' h b <-> the function h is a functor from function f to f', *) (* except at the preimage of predicate b under h. *) (* We also provide three segmenting dependently-typed lemmas (splitP, splitPl *) (* and splitPr) whose elimination split a path x0 :: p at an internal point x *) (* as follows: *) (* - splitP applies when x \in p; it replaces p with (rcons p1 x ++ p2), so *) (* that x appears explicitly at the end of the left part. The elimination *) (* of splitP will also simultaneously replace take (index x p) with p1 and *) (* drop (index x p).+1 p with p2. *) (* - splitPl applies when x \in x0 :: p; it replaces p with p1 ++ p2 and *) (* simultaneously generates an equation x = last x0 p1. *) (* - splitPr applies when x \in p; it replaces p with (p1 ++ x :: p2), so x *) (* appears explicitly at the start of the right part. *) (* The parts p1 and p2 are computed using index/take/drop in all cases, but *) (* only splitP attempts to substitute the explicit values. The substitution *) (* of p can be deferred using the dependent equation generation feature of *) (* ssreflect, e.g.: case/splitPr def_p: {1}p / x_in_p => [p1 p2] generates *) (* the equation p = p1 ++ p2 instead of performing the substitution outright. *) (* Similarly, eliminating the loop removal lemma shortenP simultaneously *) (* replaces shorten e x p with a fresh constant p', and last x p with *) (* last x p'. *) (* Note that although all "path" functions actually operate on the *) (* underlying sequence, we provide a series of lemmas that define their *) (* interaction with the path and cycle predicates, e.g., the cat_path equation*) (* can be used to split the path predicate after splitting the underlying *) (* sequence. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Section Paths. Variables (n0 : nat) (T : Type). Section Path. Variables (x0_cycle : T) (e : rel T). Fixpoint path x (p : seq T) := if p is y :: p' then e x y && path y p' else true. Lemma cat_path x p1 p2 : path x (p1 ++ p2) = path x p1 && path (last x p1) p2. Proof. by elim: p1 x => [|y p1 Hrec] x //=; rewrite Hrec -!andbA. Qed. Lemma rcons_path x p y : path x (rcons p y) = path x p && e (last x p) y. Proof. by rewrite -cats1 cat_path /= andbT. Qed. Lemma take_path x p i : path x p -> path x (take i p). Proof. elim: p x i => [//| x p] IHp x' [//| i] /= /andP[-> ?]; exact: IHp. Qed. Lemma pathP x p x0 : reflect (forall i, i < size p -> e (nth x0 (x :: p) i) (nth x0 p i)) (path x p). Proof. elim: p x => [|y p IHp] x /=; first by left. apply: (iffP andP) => [[e_xy /IHp e_p [] //] | e_p]. by split; [apply: (e_p 0) | apply/(IHp y) => i; apply: e_p i.+1]. Qed. Definition cycle p := if p is x :: p' then path x (rcons p' x) else true. Lemma cycle_path p : cycle p = path (last x0_cycle p) p. Proof. by case: p => //= x p; rewrite rcons_path andbC. Qed. Lemma cycle_catC p q : cycle (p ++ q) = cycle (q ++ p). Proof. case: p q => [|x p] [|y q]; rewrite /= ?cats0 //=. by rewrite !rcons_path !cat_path !last_cat /= -!andbA; do !bool_congr. Qed. Lemma rot_cycle p : cycle (rot n0 p) = cycle p. Proof. by rewrite cycle_catC cat_take_drop. Qed. Lemma rotr_cycle p : cycle (rotr n0 p) = cycle p. Proof. by rewrite -rot_cycle rotrK. Qed. Definition sorted s := if s is x :: s' then path x s' else true. Lemma sortedP s x : reflect (forall i, i.+1 < size s -> e (nth x s i) (nth x s i.+1)) (sorted s). Proof. by case: s => *; [constructor|apply: (iffP (pathP _ _ _)); apply]. Qed. Lemma path_sorted x s : path x s -> sorted s. Proof. by case: s => //= y s /andP[]. Qed. Lemma path_min_sorted x s : all (e x) s -> path x s = sorted s. Proof. by case: s => //= y s /andP [->]. Qed. Lemma pairwise_sorted s : pairwise e s -> sorted s. Proof. by elim: s => //= x s IHs /andP[/path_min_sorted -> /IHs]. Qed. Lemma sorted_cat_cons s1 x s2 : sorted (s1 ++ x :: s2) = sorted (rcons s1 x) && path x s2. Proof. by case: s1 => [ | e1 s1] //=; rewrite -cat_rcons cat_path last_rcons. Qed. End Path. Section PathEq. Variables (e e' : rel T). Lemma rev_path x p : path e (last x p) (rev (belast x p)) = path (fun z => e^~ z) x p. Proof. elim: p x => //= y p IHp x; rewrite rev_cons rcons_path -{}IHp andbC. by rewrite -(last_cons x) -rev_rcons -lastI rev_cons last_rcons. Qed. Lemma rev_cycle p : cycle e (rev p) = cycle (fun z => e^~ z) p. Proof. case: p => //= x p; rewrite -rev_path last_rcons belast_rcons rev_cons. by rewrite -[in LHS]cats1 cycle_catC. Qed. Lemma rev_sorted p : sorted e (rev p) = sorted (fun z => e^~ z) p. Proof. by case: p => //= x p; rewrite -rev_path lastI rev_rcons. Qed. Lemma path_relI x s : path [rel x y | e x y && e' x y] x s = path e x s && path e' x s. Proof. by elim: s x => //= y s IHs x; rewrite andbACA IHs. Qed. Lemma cycle_relI s : cycle [rel x y | e x y && e' x y] s = cycle e s && cycle e' s. Proof. by case: s => [|? ?]; last apply: path_relI. Qed. Lemma sorted_relI s : sorted [rel x y | e x y && e' x y] s = sorted e s && sorted e' s. Proof. by case: s; last apply: path_relI. Qed. End PathEq. Section SubPath_in. Variable (P : {pred T}) (e e' : rel T). Hypothesis (ee' : {in P &, subrel e e'}). Lemma sub_in_path x s : all P (x :: s) -> path e x s -> path e' x s. Proof. by elim: s x => //= y s ihs x /and3P [? ? ?] /andP [/ee' -> //]; apply/ihs/andP. Qed. Lemma sub_in_cycle s : all P s -> cycle e s -> cycle e' s. Proof. case: s => //= x s /andP [Px Ps]. by apply: sub_in_path; rewrite /= all_rcons Px. Qed. Lemma sub_in_sorted s : all P s -> sorted e s -> sorted e' s. Proof. by case: s => //; apply: sub_in_path. Qed. End SubPath_in. Section EqPath_in. Variable (P : {pred T}) (e e' : rel T). Hypothesis (ee' : {in P &, e =2 e'}). Let e_e' : {in P &, subrel e e'}. Proof. by move=> ? ? ? ?; rewrite ee'. Qed. Let e'_e : {in P &, subrel e' e}. Proof. by move=> ? ? ? ?; rewrite ee'. Qed. Lemma eq_in_path x s : all P (x :: s) -> path e x s = path e' x s. Proof. by move=> Pxs; apply/idP/idP; apply: sub_in_path Pxs. Qed. Lemma eq_in_cycle s : all P s -> cycle e s = cycle e' s. Proof. by move=> Ps; apply/idP/idP; apply: sub_in_cycle Ps. Qed. Lemma eq_in_sorted s : all P s -> sorted e s = sorted e' s. Proof. by move=> Ps; apply/idP/idP; apply: sub_in_sorted Ps. Qed. End EqPath_in. Section SubPath. Variables e e' : rel T. Lemma sub_path : subrel e e' -> forall x p, path e x p -> path e' x p. Proof. by move=> ? ? ?; apply/sub_in_path/all_predT; apply: in2W. Qed. Lemma sub_cycle : subrel e e' -> subpred (cycle e) (cycle e'). Proof. by move=> ee' [] // ? ?; apply: sub_path. Qed. Lemma sub_sorted : subrel e e' -> subpred (sorted e) (sorted e'). Proof. by move=> ee' [] //=; apply: sub_path. Qed. Lemma eq_path : e =2 e' -> path e =2 path e'. Proof. by move=> ? ? ?; apply/eq_in_path/all_predT; apply: in2W. Qed. Lemma eq_cycle : e =2 e' -> cycle e =1 cycle e'. Proof. by move=> ee' [] // ? ?; apply: eq_path. Qed. Lemma eq_sorted : e =2 e' -> sorted e =1 sorted e'. Proof. by move=> ee' [] // ? ?; apply: eq_path. Qed. End SubPath. Section Transitive_in. Variables (P : {pred T}) (leT : rel T). Lemma order_path_min_in x s : {in P & &, transitive leT} -> all P (x :: s) -> path leT x s -> all (leT x) s. Proof. move=> leT_tr; elim: s => //= y s ihs /and3P [Px Py Ps] /andP [xy ys]. rewrite xy {}ihs ?Px //=; case: s Ps ys => //= z s /andP [Pz Ps] /andP [yz ->]. by rewrite (leT_tr _ _ _ Py Px Pz). Qed. Hypothesis leT_tr : {in P & &, transitive leT}. Lemma path_sorted_inE x s : all P (x :: s) -> path leT x s = all (leT x) s && sorted leT s. Proof. move=> Pxs; apply/idP/idP => [xs|/andP[/path_min_sorted<-//]]. by rewrite (order_path_min_in leT_tr) //; apply: path_sorted xs. Qed. Lemma sorted_pairwise_in s : all P s -> sorted leT s = pairwise leT s. Proof. by elim: s => //= x s IHs /andP [Px Ps]; rewrite path_sorted_inE ?IHs //= Px. Qed. Lemma path_pairwise_in x s : all P (x :: s) -> path leT x s = pairwise leT (x :: s). Proof. by move=> Pxs; rewrite -sorted_pairwise_in. Qed. Lemma cat_sorted2 s s' : sorted leT (s ++ s') -> sorted leT s * sorted leT s'. Proof. by case: s => //= x s; rewrite cat_path => /andP[-> /path_sorted]. Qed. Lemma sorted_mask_in m s : all P s -> sorted leT s -> sorted leT (mask m s). Proof. by move=> Ps; rewrite !sorted_pairwise_in ?all_mask //; exact: pairwise_mask. Qed. Lemma sorted_filter_in a s : all P s -> sorted leT s -> sorted leT (filter a s). Proof. rewrite filter_mask; exact: sorted_mask_in. Qed. Lemma path_mask_in x m s : all P (x :: s) -> path leT x s -> path leT x (mask m s). Proof. exact/(sorted_mask_in (true :: m)). Qed. Lemma path_filter_in x a s : all P (x :: s) -> path leT x s -> path leT x (filter a s). Proof. by move=> Pxs; rewrite filter_mask; exact: path_mask_in. Qed. Lemma sorted_ltn_nth_in x0 s : all P s -> sorted leT s -> {in [pred n | n < size s] &, {homo nth x0 s : i j / i < j >-> leT i j}}. Proof. by move=> Ps; rewrite sorted_pairwise_in //; apply/pairwiseP. Qed. Hypothesis leT_refl : {in P, reflexive leT}. Lemma sorted_leq_nth_in x0 s : all P s -> sorted leT s -> {in [pred n | n < size s] &, {homo nth x0 s : i j / i <= j >-> leT i j}}. Proof. move=> Ps s_sorted x y xs ys; rewrite leq_eqVlt=> /predU1P[->|]. exact/leT_refl/all_nthP. exact: sorted_ltn_nth_in. Qed. End Transitive_in. Section Transitive. Variable (leT : rel T). Lemma order_path_min x s : transitive leT -> path leT x s -> all (leT x) s. Proof. by move=> leT_tr; apply/order_path_min_in/all_predT => //; apply: in3W. Qed. Hypothesis leT_tr : transitive leT. Lemma path_le x x' s : leT x x' -> path leT x' s -> path leT x s. Proof. by case: s => [//| x'' s xlex' /= /andP[x'lex'' ->]]; rewrite (leT_tr xlex'). Qed. Let leT_tr' : {in predT & &, transitive leT}. Proof. exact: in3W. Qed. Lemma path_sortedE x s : path leT x s = all (leT x) s && sorted leT s. Proof. exact/path_sorted_inE/all_predT. Qed. Lemma sorted_pairwise s : sorted leT s = pairwise leT s. Proof. exact/sorted_pairwise_in/all_predT. Qed. Lemma path_pairwise x s : path leT x s = pairwise leT (x :: s). Proof. exact/path_pairwise_in/all_predT. Qed. Lemma sorted_mask m s : sorted leT s -> sorted leT (mask m s). Proof. exact/sorted_mask_in/all_predT. Qed. Lemma sorted_filter a s : sorted leT s -> sorted leT (filter a s). Proof. exact/sorted_filter_in/all_predT. Qed. Lemma path_mask x m s : path leT x s -> path leT x (mask m s). Proof. exact/path_mask_in/all_predT. Qed. Lemma path_filter x a s : path leT x s -> path leT x (filter a s). Proof. exact/path_filter_in/all_predT. Qed. Lemma sorted_ltn_nth x0 s : sorted leT s -> {in [pred n | n < size s] &, {homo nth x0 s : i j / i < j >-> leT i j}}. Proof. exact/sorted_ltn_nth_in/all_predT. Qed. Hypothesis leT_refl : reflexive leT. Lemma sorted_leq_nth x0 s : sorted leT s -> {in [pred n | n < size s] &, {homo nth x0 s : i j / i <= j >-> leT i j}}. Proof. exact/sorted_leq_nth_in/all_predT. Qed. Lemma take_sorted n s : sorted leT s -> sorted leT (take n s). Proof. by rewrite -[s in sorted _ s](cat_take_drop n) => /cat_sorted2[]. Qed. Lemma drop_sorted n s : sorted leT s -> sorted leT (drop n s). Proof. by rewrite -[s in sorted _ s](cat_take_drop n) => /cat_sorted2[]. Qed. End Transitive. End Paths. Arguments pathP {T e x p}. Arguments sortedP {T e s}. Arguments path_sorted {T e x s}. Arguments path_min_sorted {T e x s}. Arguments order_path_min_in {T P leT x s}. Arguments path_sorted_inE {T P leT} leT_tr {x s}. Arguments sorted_pairwise_in {T P leT} leT_tr {s}. Arguments path_pairwise_in {T P leT} leT_tr {x s}. Arguments sorted_mask_in {T P leT} leT_tr {m s}. Arguments sorted_filter_in {T P leT} leT_tr {a s}. Arguments path_mask_in {T P leT} leT_tr {x m s}. Arguments path_filter_in {T P leT} leT_tr {x a s}. Arguments sorted_ltn_nth_in {T P leT} leT_tr x0 {s}. Arguments sorted_leq_nth_in {T P leT} leT_tr leT_refl x0 {s}. Arguments order_path_min {T leT x s}. Arguments path_sortedE {T leT} leT_tr x s. Arguments sorted_pairwise {T leT} leT_tr s. Arguments path_pairwise {T leT} leT_tr x s. Arguments sorted_mask {T leT} leT_tr m {s}. Arguments sorted_filter {T leT} leT_tr a {s}. Arguments path_mask {T leT} leT_tr {x} m {s}. Arguments path_filter {T leT} leT_tr {x} a {s}. Arguments sorted_ltn_nth {T leT} leT_tr x0 {s}. Arguments sorted_leq_nth {T leT} leT_tr leT_refl x0 {s}. Section HomoPath. Variables (T T' : Type) (P : {pred T}) (f : T -> T') (e : rel T) (e' : rel T'). Lemma path_map x s : path e' (f x) (map f s) = path (relpre f e') x s. Proof. by elim: s x => //= y s <-. Qed. Lemma cycle_map s : cycle e' (map f s) = cycle (relpre f e') s. Proof. by case: s => //= ? ?; rewrite -map_rcons path_map. Qed. Lemma sorted_map s : sorted e' (map f s) = sorted (relpre f e') s. Proof. by case: s; last apply: path_map. Qed. Lemma homo_path_in x s : {in P &, {homo f : x y / e x y >-> e' x y}} -> all P (x :: s) -> path e x s -> path e' (f x) (map f s). Proof. by move=> f_mono; rewrite path_map; apply: sub_in_path. Qed. Lemma homo_cycle_in s : {in P &, {homo f : x y / e x y >-> e' x y}} -> all P s -> cycle e s -> cycle e' (map f s). Proof. by move=> f_mono; rewrite cycle_map; apply: sub_in_cycle. Qed. Lemma homo_sorted_in s : {in P &, {homo f : x y / e x y >-> e' x y}} -> all P s -> sorted e s -> sorted e' (map f s). Proof. by move=> f_mono; rewrite sorted_map; apply: sub_in_sorted. Qed. Lemma mono_path_in x s : {in P &, {mono f : x y / e x y >-> e' x y}} -> all P (x :: s) -> path e' (f x) (map f s) = path e x s. Proof. by move=> f_mono; rewrite path_map; apply: eq_in_path. Qed. Lemma mono_cycle_in s : {in P &, {mono f : x y / e x y >-> e' x y}} -> all P s -> cycle e' (map f s) = cycle e s. Proof. by move=> f_mono; rewrite cycle_map; apply: eq_in_cycle. Qed. Lemma mono_sorted_in s : {in P &, {mono f : x y / e x y >-> e' x y}} -> all P s -> sorted e' (map f s) = sorted e s. Proof. by case: s => // x s; apply: mono_path_in. Qed. Lemma homo_path x s : {homo f : x y / e x y >-> e' x y} -> path e x s -> path e' (f x) (map f s). Proof. by move=> f_homo; rewrite path_map; apply: sub_path. Qed. Lemma homo_cycle : {homo f : x y / e x y >-> e' x y} -> {homo map f : s / cycle e s >-> cycle e' s}. Proof. by move=> f_homo s hs; rewrite cycle_map (sub_cycle _ hs). Qed. Lemma homo_sorted : {homo f : x y / e x y >-> e' x y} -> {homo map f : s / sorted e s >-> sorted e' s}. Proof. by move/homo_path => ? []. Qed. Lemma mono_path x s : {mono f : x y / e x y >-> e' x y} -> path e' (f x) (map f s) = path e x s. Proof. by move=> f_mon; rewrite path_map; apply: eq_path. Qed. Lemma mono_cycle : {mono f : x y / e x y >-> e' x y} -> {mono map f : s / cycle e s >-> cycle e' s}. Proof. by move=> ? ?; rewrite cycle_map; apply: eq_cycle. Qed. Lemma mono_sorted : {mono f : x y / e x y >-> e' x y} -> {mono map f : s / sorted e s >-> sorted e' s}. Proof. by move=> f_mon [] //= x s; apply: mono_path. Qed. End HomoPath. Arguments path_map {T T' f e'}. Arguments cycle_map {T T' f e'}. Arguments sorted_map {T T' f e'}. Arguments homo_path_in {T T' P f e e' x s}. Arguments homo_cycle_in {T T' P f e e' s}. Arguments homo_sorted_in {T T' P f e e' s}. Arguments mono_path_in {T T' P f e e' x s}. Arguments mono_cycle_in {T T' P f e e' s}. Arguments mono_sorted_in {T T' P f e e' s}. Arguments homo_path {T T' f e e' x s}. Arguments homo_cycle {T T' f e e'}. Arguments homo_sorted {T T' f e e'}. Arguments mono_path {T T' f e e' x s}. Arguments mono_cycle {T T' f e e'}. Arguments mono_sorted {T T' f e e'}. Section CycleAll2Rel. Lemma cycle_all2rel (T : Type) (leT : rel T) : transitive leT -> forall s, cycle leT s = all2rel leT s. Proof. move=> leT_tr; elim=> //= x s IHs. rewrite allrel_cons2 -{}IHs // (path_sortedE leT_tr) /= all_rcons -rev_sorted. rewrite rev_rcons /= (path_sortedE (rev_trans leT_tr)) all_rev !andbA. case: (boolP (leT x x && _ && _)) => //=. case: s => //= y s /and3P[/and3P[_ xy _] yx sx]. rewrite rev_sorted rcons_path /= (leT_tr _ _ _ _ xy) ?andbT //. by case: (lastP s) sx => //= {}s z; rewrite all_rcons last_rcons => /andP [->]. Qed. Lemma cycle_all2rel_in (T : Type) (P : {pred T}) (leT : rel T) : {in P & &, transitive leT} -> forall s, all P s -> cycle leT s = all2rel leT s. Proof. move=> /in3_sig leT_tr _ /all_sigP [s ->]. by rewrite cycle_map allrel_mapl allrel_mapr; apply: cycle_all2rel. Qed. End CycleAll2Rel. Section PreInSuffix. Variables (T : eqType) (e : rel T). Implicit Type s : seq T. Local Notation path := (path e). Local Notation sorted := (sorted e). Lemma prefix_path x s1 s2 : prefix s1 s2 -> path x s2 -> path x s1. Proof. by rewrite prefixE => /eqP <-; exact: take_path. Qed. Lemma prefix_sorted s1 s2 : prefix s1 s2 -> sorted s2 -> sorted s1. Proof. by rewrite prefixE => /eqP <-; exact: take_sorted. Qed. Lemma infix_sorted s1 s2 : infix s1 s2 -> sorted s2 -> sorted s1. Proof. by rewrite infixE => /eqP <- ?; apply/take_sorted/drop_sorted. Qed. Lemma suffix_sorted s1 s2 : suffix s1 s2 -> sorted s2 -> sorted s1. Proof. by rewrite suffixE => /eqP <-; exact: drop_sorted. Qed. End PreInSuffix. Section EqSorted. Variables (T : eqType) (leT : rel T). Implicit Type s : seq T. Local Notation path := (path leT). Local Notation sorted := (sorted leT). Lemma subseq_path_in x s1 s2 : {in x :: s2 & &, transitive leT} -> subseq s1 s2 -> path x s2 -> path x s1. Proof. by move=> tr /subseqP [m _ ->]; apply/(path_mask_in tr). Qed. Lemma subseq_sorted_in s1 s2 : {in s2 & &, transitive leT} -> subseq s1 s2 -> sorted s2 -> sorted s1. Proof. by move=> tr /subseqP [m _ ->]; apply/(sorted_mask_in tr). Qed. Lemma sorted_ltn_index_in s : {in s & &, transitive leT} -> sorted s -> {in s &, forall x y, index x s < index y s -> leT x y}. Proof. case: s => // x0 s' leT_tr s_sorted x y xs ys. move/(sorted_ltn_nth_in leT_tr x0 (allss (_ :: _)) s_sorted). by rewrite ?nth_index ?[_ \in gtn _]index_mem //; apply. Qed. Lemma sorted_leq_index_in s : {in s & &, transitive leT} -> {in s, reflexive leT} -> sorted s -> {in s &, forall x y, index x s <= index y s -> leT x y}. Proof. case: s => // x0 s' leT_tr leT_refl s_sorted x y xs ys. move/(sorted_leq_nth_in leT_tr leT_refl x0 (allss (_ :: _)) s_sorted). by rewrite ?nth_index ?[_ \in gtn _]index_mem //; apply. Qed. Hypothesis leT_tr : transitive leT. Lemma subseq_path x s1 s2 : subseq s1 s2 -> path x s2 -> path x s1. Proof. by apply: subseq_path_in; apply: in3W. Qed. Lemma subseq_sorted s1 s2 : subseq s1 s2 -> sorted s2 -> sorted s1. Proof. by apply: subseq_sorted_in; apply: in3W. Qed. Lemma sorted_uniq : irreflexive leT -> forall s, sorted s -> uniq s. Proof. by move=> irr s; rewrite sorted_pairwise //; apply/pairwise_uniq. Qed. Lemma sorted_eq : antisymmetric leT -> forall s1 s2, sorted s1 -> sorted s2 -> perm_eq s1 s2 -> s1 = s2. Proof. by move=> leT_asym s1 s2; rewrite !sorted_pairwise //; apply: pairwise_eq. Qed. Lemma irr_sorted_eq : irreflexive leT -> forall s1 s2, sorted s1 -> sorted s2 -> s1 =i s2 -> s1 = s2. Proof. move=> leT_irr s1 s2 s1_sort s2_sort eq_s12. have: antisymmetric leT. by move=> m n /andP[? ltnm]; case/idP: (leT_irr m); apply: leT_tr ltnm. by move/sorted_eq; apply=> //; apply: uniq_perm => //; apply: sorted_uniq. Qed. Lemma sorted_ltn_index s : sorted s -> {in s &, forall x y, index x s < index y s -> leT x y}. Proof. case: s => // x0 s' s_sorted x y xs ys /(sorted_ltn_nth leT_tr x0 s_sorted). by rewrite ?nth_index ?[_ \in gtn _]index_mem //; apply. Qed. Lemma undup_path x s : path x s -> path x (undup s). Proof. exact/subseq_path/undup_subseq. Qed. Lemma undup_sorted s : sorted s -> sorted (undup s). Proof. exact/subseq_sorted/undup_subseq. Qed. Hypothesis leT_refl : reflexive leT. Lemma sorted_leq_index s : sorted s -> {in s &, forall x y, index x s <= index y s -> leT x y}. Proof. case: s => // x0 s' s_sorted x y xs ys. move/(sorted_leq_nth leT_tr leT_refl x0 s_sorted). by rewrite ?nth_index ?[_ \in gtn _]index_mem //; apply. Qed. End EqSorted. Arguments sorted_ltn_index_in {T leT s} leT_tr s_sorted. Arguments sorted_leq_index_in {T leT s} leT_tr leT_refl s_sorted. Arguments sorted_ltn_index {T leT} leT_tr {s}. Arguments sorted_leq_index {T leT} leT_tr leT_refl {s}. Section EqSorted_in. Variables (T : eqType) (leT : rel T). Implicit Type s : seq T. Lemma sorted_uniq_in s : {in s & &, transitive leT} -> {in s, irreflexive leT} -> sorted leT s -> uniq s. Proof. move=> /in3_sig leT_tr /in1_sig leT_irr; case/all_sigP: (allss s) => s' ->. by rewrite sorted_map (map_inj_uniq val_inj); exact: sorted_uniq. Qed. Lemma sorted_eq_in s1 s2 : {in s1 & &, transitive leT} -> {in s1 &, antisymmetric leT} -> sorted leT s1 -> sorted leT s2 -> perm_eq s1 s2 -> s1 = s2. Proof. move=> /in3_sig leT_tr /in2_sig/(_ _ _ _)/val_inj leT_anti + + /[dup] s1s2. have /all_sigP[s1' ->] := allss s1. have /all_sigP[{s1s2}s2 ->] : all [in s1] s2 by rewrite -(perm_all _ s1s2). by rewrite !sorted_map => ss1' ss2 /(perm_map_inj val_inj)/(sorted_eq leT_tr)->. Qed. Lemma irr_sorted_eq_in s1 s2 : {in s1 & &, transitive leT} -> {in s1, irreflexive leT} -> sorted leT s1 -> sorted leT s2 -> s1 =i s2 -> s1 = s2. Proof. move=> /in3_sig leT_tr /in1_sig leT_irr + + /[dup] s1s2. have /all_sigP[s1' ->] := allss s1. have /all_sigP[s2' ->] : all [in s1] s2 by rewrite -(eq_all_r s1s2). rewrite !sorted_map => ss1' ss2' {}s1s2; congr map. by apply: (irr_sorted_eq leT_tr) => // x; rewrite -!(mem_map val_inj). Qed. End EqSorted_in. Section EqPath. Variables (n0 : nat) (T : eqType) (e : rel T). Implicit Type p : seq T. Variant split x : seq T -> seq T -> seq T -> Type := Split p1 p2 : split x (rcons p1 x ++ p2) p1 p2. Lemma splitP p x (i := index x p) : x \in p -> split x p (take i p) (drop i.+1 p). Proof. by rewrite -has_pred1 => /split_find[? ? ? /eqP->]; constructor. Qed. Variant splitl x1 x : seq T -> Type := Splitl p1 p2 of last x1 p1 = x : splitl x1 x (p1 ++ p2). Lemma splitPl x1 p x : x \in x1 :: p -> splitl x1 x p. Proof. rewrite inE; case: eqP => [->| _ /splitP[]]; first by rewrite -(cat0s p). by split; apply: last_rcons. Qed. Variant splitr x : seq T -> Type := Splitr p1 p2 : splitr x (p1 ++ x :: p2). Lemma splitPr p x : x \in p -> splitr x p. Proof. by case/splitP=> p1 p2; rewrite cat_rcons. Qed. Fixpoint next_at x y0 y p := match p with | [::] => if x == y then y0 else x | y' :: p' => if x == y then y' else next_at x y0 y' p' end. Definition next p x := if p is y :: p' then next_at x y y p' else x. Fixpoint prev_at x y0 y p := match p with | [::] => if x == y0 then y else x | y' :: p' => if x == y' then y else prev_at x y0 y' p' end. Definition prev p x := if p is y :: p' then prev_at x y y p' else x. Lemma next_nth p x : next p x = if x \in p then if p is y :: p' then nth y p' (index x p) else x else x. Proof. case: p => //= y0 p. elim: p {2 3 5}y0 => [|y' p IHp] y /=; rewrite (eq_sym y) inE; by case: ifP => // _; apply: IHp. Qed. Lemma prev_nth p x : prev p x = if x \in p then if p is y :: p' then nth y p (index x p') else x else x. Proof. case: p => //= y0 p; rewrite inE orbC. elim: p {2 5}y0 => [|y' p IHp] y; rewrite /= ?inE // (eq_sym y'). by case: ifP => // _; apply: IHp. Qed. Lemma mem_next p x : (next p x \in p) = (x \in p). Proof. rewrite next_nth; case p_x: (x \in p) => //. case: p (index x p) p_x => [|y0 p'] //= i _; rewrite inE. have [lt_ip | ge_ip] := ltnP i (size p'); first by rewrite orbC mem_nth. by rewrite nth_default ?eqxx. Qed. Lemma mem_prev p x : (prev p x \in p) = (x \in p). Proof. rewrite prev_nth; case p_x: (x \in p) => //; case: p => [|y0 p] // in p_x *. by apply mem_nth; rewrite /= ltnS index_size. Qed. (* ucycleb is the boolean predicate, but ucycle is defined as a Prop *) (* so that it can be used as a coercion target. *) Definition ucycleb p := cycle e p && uniq p. Definition ucycle p : Prop := cycle e p && uniq p. (* Projections, used for creating local lemmas. *) Lemma ucycle_cycle p : ucycle p -> cycle e p. Proof. by case/andP. Qed. Lemma ucycle_uniq p : ucycle p -> uniq p. Proof. by case/andP. Qed. Lemma next_cycle p x : cycle e p -> x \in p -> e x (next p x). Proof. case: p => //= y0 p; elim: p {1 3 5}y0 => [|z p IHp] y /=; rewrite inE. by rewrite andbT; case: (x =P y) => // ->. by case/andP=> eyz /IHp; case: (x =P y) => // ->. Qed. Lemma prev_cycle p x : cycle e p -> x \in p -> e (prev p x) x. Proof. case: p => //= y0 p; rewrite inE orbC. elim: p {1 5}y0 => [|z p IHp] y /=; rewrite ?inE. by rewrite andbT; case: (x =P y0) => // ->. by case/andP=> eyz /IHp; case: (x =P z) => // ->. Qed. Lemma rot_ucycle p : ucycle (rot n0 p) = ucycle p. Proof. by rewrite /ucycle rot_uniq rot_cycle. Qed. Lemma rotr_ucycle p : ucycle (rotr n0 p) = ucycle p. Proof. by rewrite /ucycle rotr_uniq rotr_cycle. Qed. (* The "appears no later" partial preorder defined by a path. *) Definition mem2 p x y := y \in drop (index x p) p. Lemma mem2l p x y : mem2 p x y -> x \in p. Proof. by rewrite /mem2 -!index_mem size_drop ltn_subRL; apply/leq_ltn_trans/leq_addr. Qed. Lemma mem2lf {p x y} : x \notin p -> mem2 p x y = false. Proof. exact/contraNF/mem2l. Qed. Lemma mem2r p x y : mem2 p x y -> y \in p. Proof. by rewrite -[in y \in p](cat_take_drop (index x p) p) mem_cat orbC /mem2 => ->. Qed. Lemma mem2rf {p x y} : y \notin p -> mem2 p x y = false. Proof. exact/contraNF/mem2r. Qed. Lemma mem2_cat p1 p2 x y : mem2 (p1 ++ p2) x y = mem2 p1 x y || mem2 p2 x y || (x \in p1) && (y \in p2). Proof. rewrite [LHS]/mem2 index_cat fun_if if_arg !drop_cat addKn. case: ifPn => [p1x | /mem2lf->]; last by rewrite ltnNge leq_addr orbF. by rewrite index_mem p1x mem_cat -orbA (orb_idl (@mem2r _ _ _)). Qed. Lemma mem2_splice p1 p3 x y p2 : mem2 (p1 ++ p3) x y -> mem2 (p1 ++ p2 ++ p3) x y. Proof. by rewrite !mem2_cat mem_cat andb_orr orbC => /or3P[]->; rewrite ?orbT. Qed. Lemma mem2_splice1 p1 p3 x y z : mem2 (p1 ++ p3) x y -> mem2 (p1 ++ z :: p3) x y. Proof. exact: mem2_splice [::z]. Qed. Lemma mem2_cons x p y z : mem2 (x :: p) y z = (if x == y then z \in x :: p else mem2 p y z). Proof. by rewrite [LHS]/mem2 /=; case: ifP. Qed. Lemma mem2_seq1 x y z : mem2 [:: x] y z = (y == x) && (z == x). Proof. by rewrite mem2_cons eq_sym inE. Qed. Lemma mem2_last y0 p x : mem2 p x (last y0 p) = (x \in p). Proof. apply/idP/idP; first exact: mem2l; rewrite -index_mem /mem2 => p_x. by rewrite -nth_last -(subnKC p_x) -nth_drop mem_nth // size_drop subnSK. Qed. Lemma mem2l_cat {p1 p2 x} : x \notin p1 -> mem2 (p1 ++ p2) x =1 mem2 p2 x. Proof. by move=> p1'x y; rewrite mem2_cat (negPf p1'x) mem2lf ?orbF. Qed. Lemma mem2r_cat {p1 p2 x y} : y \notin p2 -> mem2 (p1 ++ p2) x y = mem2 p1 x y. Proof. by move=> p2'y; rewrite mem2_cat (negPf p2'y) -orbA orbC andbF mem2rf. Qed. Lemma mem2lr_splice {p1 p2 p3 x y} : x \notin p2 -> y \notin p2 -> mem2 (p1 ++ p2 ++ p3) x y = mem2 (p1 ++ p3) x y. Proof. move=> p2'x p2'y; rewrite catA !mem2_cat !mem_cat. by rewrite (negPf p2'x) (negPf p2'y) (mem2lf p2'x) andbF !orbF. Qed. Lemma mem2E s x y : mem2 s x y = subseq (if x == y then [:: x] else [:: x; y]) s. Proof. elim: s => [| h s]; first by case: ifP. rewrite mem2_cons => ->. do 2 rewrite inE (fun_if subseq) !if_arg !sub1seq /=. by have [->|] := eqVneq; case: eqVneq. Qed. Variant split2r x y : seq T -> Type := Split2r p1 p2 of y \in x :: p2 : split2r x y (p1 ++ x :: p2). Lemma splitP2r p x y : mem2 p x y -> split2r x y p. Proof. move=> pxy; have px := mem2l pxy. have:= pxy; rewrite /mem2 (drop_nth x) ?index_mem ?nth_index //. by case/splitP: px => p1 p2; rewrite cat_rcons. Qed. Fixpoint shorten x p := if p is y :: p' then if x \in p then shorten x p' else y :: shorten y p' else [::]. Variant shorten_spec x p : T -> seq T -> Type := ShortenSpec p' of path e x p' & uniq (x :: p') & {subset p' <= p} : shorten_spec x p (last x p') p'. Lemma shortenP x p : path e x p -> shorten_spec x p (last x p) (shorten x p). Proof. move=> e_p; have: x \in x :: p by apply: mem_head. elim: p x {1 3 5}x e_p => [|y2 p IHp] x y1. by rewrite mem_seq1 => _ /eqP->. rewrite inE orbC /= => /andP[ey12 {}/IHp IHp]. case: ifPn => [y2p_x _ | not_y2p_x /eqP def_x]. have [p' e_p' Up' p'p] := IHp _ y2p_x. by split=> // y /p'p; apply: predU1r. have [p' e_p' Up' p'p] := IHp y2 (mem_head y2 p). have{} p'p z: z \in y2 :: p' -> z \in y2 :: p. by rewrite !inE; case: (z == y2) => // /p'p. rewrite -(last_cons y1) def_x; split=> //=; first by rewrite ey12. by rewrite (contra (p'p y1)) -?def_x. Qed. End EqPath. (* Ordered paths and sorting. *) Section SortSeq. Variables (T : Type) (leT : rel T). Fixpoint merge s1 := if s1 is x1 :: s1' then let fix merge_s1 s2 := if s2 is x2 :: s2' then if leT x1 x2 then x1 :: merge s1' s2 else x2 :: merge_s1 s2' else s1 in merge_s1 else id. Arguments merge !s1 !s2 : rename. Fixpoint merge_sort_push s1 ss := match ss with | [::] :: ss' | [::] as ss' => s1 :: ss' | s2 :: ss' => [::] :: merge_sort_push (merge s2 s1) ss' end. Fixpoint merge_sort_pop s1 ss := if ss is s2 :: ss' then merge_sort_pop (merge s2 s1) ss' else s1. Fixpoint merge_sort_rec ss s := if s is [:: x1, x2 & s'] then let s1 := if leT x1 x2 then [:: x1; x2] else [:: x2; x1] in merge_sort_rec (merge_sort_push s1 ss) s' else merge_sort_pop s ss. Definition sort := merge_sort_rec [::]. (* The following definition `sort_rec1` is an auxiliary function for *) (* inductive reasoning on `sort`. One can rewrite `sort le s` to *) (* `sort_rec1 le [::] s` by `sortE` and apply the simple structural induction *) (* on `s` to reason about it. *) Fixpoint sort_rec1 ss s := if s is x :: s then sort_rec1 (merge_sort_push [:: x] ss) s else merge_sort_pop [::] ss. Lemma sortE s : sort s = sort_rec1 [::] s. Proof. transitivity (sort_rec1 [:: nil] s); last by case: s. rewrite /sort; move: [::] {2}_.+1 (ltnSn (size s)./2) => ss n. by elim: n => // n IHn in ss s *; case: s => [|x [|y s]] //= /IHn->. Qed. Lemma count_merge (p : pred T) s1 s2 : count p (merge s1 s2) = count p (s1 ++ s2). Proof. rewrite count_cat; elim: s1 s2 => // x s1 IH1. elim=> //= [|y s2 IH2]; first by rewrite addn0. by case: leT; rewrite /= ?IH1 ?IH2 !addnA [_ + p y]addnAC [p x + p y]addnC. Qed. Lemma size_merge s1 s2 : size (merge s1 s2) = size (s1 ++ s2). Proof. exact: (count_merge predT). Qed. Lemma allrel_merge s1 s2 : allrel leT s1 s2 -> merge s1 s2 = s1 ++ s2. Proof. elim: s1 s2 => [|x s1 IHs1] [|y s2]; rewrite ?cats0 //=. by rewrite allrel_consl /= -andbA => /and3P [-> _ /IHs1->]. Qed. Lemma count_sort (p : pred T) s : count p (sort s) = count p s. Proof. rewrite sortE -[RHS]/(sumn [seq count p x | x <- [::]] + count p s). elim: s [::] => [|x s ihs] ss. rewrite [LHS]/=; elim: ss [::] => //= s ss ihss t. by rewrite ihss count_merge count_cat addnCA addnA. rewrite {}ihs -[in RHS]cat1s count_cat addnA; congr addn; rewrite addnC. elim: {x s} ss [:: x] => [|[|x s] ss ihss] t //. by rewrite [LHS]/= add0n ihss count_merge count_cat -addnA addnCA. Qed. Lemma pairwise_sort s : pairwise leT s -> sort s = s. Proof. pose catss := foldr (fun x => cat ^~ x) (Nil T). rewrite -{1 3}[s]/(catss [::] ++ s) sortE; elim: s [::] => /= [|x s ihs] ss. elim: ss [::] => //= s ss ihss t; rewrite -catA => ssst. rewrite -ihss ?allrel_merge //; move: ssst; rewrite !pairwise_cat. by case/and4P. rewrite (catA _ [:: _]) => ssxs. suff x_ss_E: catss (merge_sort_push [:: x] ss) = catss ([:: x] :: ss). by rewrite -[catss _ ++ _]/(catss ([:: x] :: ss)) -x_ss_E ihs // x_ss_E. move: ssxs; rewrite pairwise_cat => /and3P [_ + _]. elim: ss [:: x] => {x s ihs} //= -[|x s] ss ihss t h_pairwise; rewrite /= cats0 // allrel_merge ?ihss ?catA //. by move: h_pairwise; rewrite -catA !pairwise_cat => /and4P []. Qed. Remark size_merge_sort_push s1 : let graded ss := forall i, size (nth [::] ss i) \in pred2 0 (2 ^ (i + 1)) in size s1 = 2 -> {homo merge_sort_push s1 : ss / graded ss}. Proof. set n := {2}1; rewrite -[RHS]/(2 ^ n) => graded sz_s1 ss. elim: ss => [|s2 ss IHss] in (n) graded s1 sz_s1 * => sz_ss i //=. by case: i => [|[]] //; rewrite sz_s1 inE eqxx orbT. case: s2 i => [|x s2] [|i] //= in sz_ss *; first by rewrite sz_s1 inE eqxx orbT. exact: (sz_ss i.+1). rewrite addSnnS; apply: IHss i => [|i]; last by rewrite -addSnnS (sz_ss i.+1). by rewrite size_merge size_cat sz_s1 (eqP (sz_ss 0)) addnn expnS mul2n. Qed. Section Stability. Variable leT' : rel T. Hypothesis (leT_total : total leT) (leT'_tr : transitive leT'). Let leT_lex := [rel x y | leT x y && (leT y x ==> leT' x y)]. Lemma merge_stable_path x s1 s2 : allrel leT' s1 s2 -> path leT_lex x s1 -> path leT_lex x s2 -> path leT_lex x (merge s1 s2). Proof. elim: s1 s2 x => //= x s1 ih1; elim => //= y s2 ih2 h. rewrite allrel_cons2 => /and4P [xy' xs2 ys1 s1s2] /andP [hx xs1] /andP [hy ys2]. case: ifP => xy /=; rewrite (hx, hy) /=. - by apply: ih1; rewrite ?allrel_consr ?ys1 //= xy xy' implybT. - by apply: ih2; have:= leT_total x y; rewrite ?allrel_consl ?xs2 ?xy //= => ->. Qed. Lemma merge_stable_sorted s1 s2 : allrel leT' s1 s2 -> sorted leT_lex s1 -> sorted leT_lex s2 -> sorted leT_lex (merge s1 s2). Proof. case: s1 s2 => [|x s1] [|y s2] //=; rewrite allrel_consl allrel_consr /= -andbA. case/and4P => [xy' xs2 ys1 s1s2] xs1 ys2; rewrite -/(merge (_ :: _)). by case: ifP (leT_total x y) => /= xy yx; apply/merge_stable_path; rewrite /= ?(allrel_consl, allrel_consr, xs2, ys1, xy, yx, xy', implybT). Qed. End Stability. Hypothesis leT_total : total leT. Let leElex : leT =2 [rel x y | leT x y && (leT y x ==> true)]. Proof. by move=> ? ? /=; rewrite implybT andbT. Qed. Lemma merge_path x s1 s2 : path leT x s1 -> path leT x s2 -> path leT x (merge s1 s2). Proof. by rewrite !(eq_path leElex); apply/merge_stable_path/allrelT. Qed. Lemma merge_sorted s1 s2 : sorted leT s1 -> sorted leT s2 -> sorted leT (merge s1 s2). Proof. by rewrite !(eq_sorted leElex); apply/merge_stable_sorted/allrelT. Qed. Hypothesis leT_tr : transitive leT. Lemma sorted_merge s t : sorted leT (s ++ t) -> merge s t = s ++ t. Proof. by rewrite sorted_pairwise // pairwise_cat => /and3P[/allrel_merge]. Qed. Lemma sorted_sort s : sorted leT s -> sort s = s. Proof. by rewrite sorted_pairwise //; apply/pairwise_sort. Qed. Lemma mergeA : associative merge. Proof. elim=> // x xs IHxs; elim=> // y ys IHys; elim=> [|z zs IHzs] /=. by case: ifP. case: ifP; case: ifP => /= lexy leyz. - by rewrite lexy (leT_tr lexy leyz) -IHxs /= leyz. - by rewrite lexy leyz -IHys. - case: ifP => lexz; first by rewrite -IHxs //= leyz. by rewrite -!/(merge (_ :: _)) IHzs /= lexy. - suff->: leT x z = false by rewrite leyz // -!/(merge (_ :: _)) IHzs /= lexy. by apply/contraFF/leT_tr: leyz; have := leT_total x y; rewrite lexy. Qed. End SortSeq. Arguments merge {T} relT !s1 !s2 : rename. Arguments size_merge {T} leT s1 s2. Arguments allrel_merge {T leT s1 s2}. Arguments pairwise_sort {T leT s}. Arguments merge_path {T leT} leT_total {x s1 s2}. Arguments merge_sorted {T leT} leT_total {s1 s2}. Arguments sorted_merge {T leT} leT_tr {s t}. Arguments sorted_sort {T leT} leT_tr {s}. Arguments mergeA {T leT} leT_total leT_tr. Section SortMap. Variables (T T' : Type) (f : T' -> T). Section Monotonicity. Variables (leT' : rel T') (leT : rel T). Hypothesis f_mono : {mono f : x y / leT' x y >-> leT x y}. Lemma map_merge : {morph map f : s1 s2 / merge leT' s1 s2 >-> merge leT s1 s2}. Proof. elim=> //= x s1 IHs1; elim => [|y s2 IHs2] //=; rewrite f_mono. by case: leT'; rewrite /= ?IHs1 ?IHs2. Qed. Lemma map_sort : {morph map f : s1 / sort leT' s1 >-> sort leT s1}. Proof. move=> s; rewrite !sortE -[[::] in RHS]/(map (map f) [::]). elim: s [::] => /= [|x s ihs] ss; rewrite -/(map f [::]) -/(map f [:: _]); first by elim: ss [::] => //= x ss ihss ?; rewrite ihss map_merge. rewrite ihs -/(map f [:: x]); congr sort_rec1. by elim: ss [:: x] => {x s ihs} [|[|x s] ss ihss] //= ?; rewrite ihss map_merge. Qed. End Monotonicity. Variable leT : rel T. Lemma merge_map s1 s2 : merge leT (map f s1) (map f s2) = map f (merge (relpre f leT) s1 s2). Proof. exact/esym/map_merge. Qed. Lemma sort_map s : sort leT (map f s) = map f (sort (relpre f leT) s). Proof. exact/esym/map_sort. Qed. End SortMap. Arguments map_merge {T T' f leT' leT}. Arguments map_sort {T T' f leT' leT}. Arguments merge_map {T T' f leT}. Arguments sort_map {T T' f leT}. Lemma sorted_sort_in T (P : {pred T}) (leT : rel T) : {in P & &, transitive leT} -> forall s : seq T, all P s -> sorted leT s -> sort leT s = s. Proof. move=> /in3_sig ? _ /all_sigP[s ->]. by rewrite sort_map sorted_map => /sorted_sort->. Qed. Arguments sorted_sort_in {T P leT} leT_tr {s}. Section EqSortSeq. Variables (T : eqType) (leT : rel T). Lemma perm_merge s1 s2 : perm_eql (merge leT s1 s2) (s1 ++ s2). Proof. by apply/permPl/permP => ?; rewrite count_merge. Qed. Lemma mem_merge s1 s2 : merge leT s1 s2 =i s1 ++ s2. Proof. by apply: perm_mem; rewrite perm_merge. Qed. Lemma merge_uniq s1 s2 : uniq (merge leT s1 s2) = uniq (s1 ++ s2). Proof. by apply: perm_uniq; rewrite perm_merge. Qed. Lemma perm_sort s : perm_eql (sort leT s) s. Proof. by apply/permPl/permP => ?; rewrite count_sort. Qed. Lemma mem_sort s : sort leT s =i s. Proof. exact/perm_mem/permPl/perm_sort. Qed. Lemma sort_uniq s : uniq (sort leT s) = uniq s. Proof. exact/perm_uniq/permPl/perm_sort. Qed. Lemma eq_count_merge (p : pred T) s1 s1' s2 s2' : count p s1 = count p s1' -> count p s2 = count p s2' -> count p (merge leT s1 s2) = count p (merge leT s1' s2'). Proof. by rewrite !count_merge !count_cat => -> ->. Qed. End EqSortSeq. Lemma perm_iota_sort (T : Type) (leT : rel T) x0 s : {i_s : seq nat | perm_eq i_s (iota 0 (size s)) & sort leT s = map (nth x0 s) i_s}. Proof. exists (sort (relpre (nth x0 s) leT) (iota 0 (size s))). by rewrite perm_sort. by rewrite -[s in LHS](mkseq_nth x0) sort_map. Qed. Lemma all_merge (T : Type) (P : {pred T}) (leT : rel T) s1 s2 : all P (merge leT s1 s2) = all P s1 && all P s2. Proof. elim: s1 s2 => //= x s1 IHs1; elim=> [|y s2 IHs2]; rewrite ?andbT //=. by case: ifP => _; rewrite /= ?IHs1 ?IHs2 //=; bool_congr. Qed. Lemma all_sort (T : Type) (P : {pred T}) (leT : rel T) s : all P (sort leT s) = all P s. Proof. case: s => // x s; move: (x :: s) => {}s. by rewrite -(mkseq_nth x s) sort_map !all_map; apply/perm_all/permPl/perm_sort. Qed. Lemma size_sort (T : Type) (leT : rel T) s : size (sort leT s) = size s. Proof. exact: (count_sort _ predT). Qed. Lemma ltn_sorted_uniq_leq s : sorted ltn s = uniq s && sorted leq s. Proof. rewrite (sorted_pairwise leq_trans) (sorted_pairwise ltn_trans) uniq_pairwise. by rewrite -pairwise_relI; apply/eq_pairwise => ? ?; rewrite ltn_neqAle. Qed. Lemma gtn_sorted_uniq_geq s : sorted gtn s = uniq s && sorted geq s. Proof. by rewrite -rev_sorted ltn_sorted_uniq_leq rev_sorted rev_uniq. Qed. Lemma iota_sorted i n : sorted leq (iota i n). Proof. by elim: n i => // [[|n] //= IHn] i; rewrite IHn leqW. Qed. Lemma iota_ltn_sorted i n : sorted ltn (iota i n). Proof. by rewrite ltn_sorted_uniq_leq iota_sorted iota_uniq. Qed. Section Stability_iota. Variables (leN : rel nat) (leN_total : total leN). Let lt_lex := [rel n m | leN n m && (leN m n ==> (n < m))]. Let Fixpoint push_invariant (ss : seq (seq nat)) := if ss is s :: ss' then [&& sorted lt_lex s, allrel gtn s (flatten ss') & push_invariant ss'] else true. Let push_stable s1 ss : push_invariant (s1 :: ss) -> push_invariant (merge_sort_push leN s1 ss). Proof. elim: ss s1 => [] // [] //= m s2 ss ihss s1; rewrite -cat_cons allrel_catr. move=> /and5P[sorted_s1 /andP[s1s2 s1ss] sorted_s2 s2ss hss]; apply: ihss. rewrite /= hss andbT merge_stable_sorted //=; last by rewrite allrelC. by apply/allrelP => ? ?; rewrite mem_merge mem_cat => /orP[]; apply/allrelP. Qed. Let pop_stable s1 ss : push_invariant (s1 :: ss) -> sorted lt_lex (merge_sort_pop leN s1 ss). Proof. elim: ss s1 => [s1 /and3P[]|s2 ss ihss s1] //=; rewrite allrel_catr. move=> /and5P[sorted_s1 /andP[s1s2 s1ss] sorted_s2 s2ss hss]; apply: ihss. rewrite /= hss andbT merge_stable_sorted //=; last by rewrite allrelC. by apply/allrelP => ? ?; rewrite mem_merge mem_cat => /orP[]; apply/allrelP. Qed. Lemma sort_iota_stable n : sorted lt_lex (sort leN (iota 0 n)). Proof. rewrite sortE. have/andP[]: all (gtn 0) (flatten [::]) && push_invariant [::] by []. elim: n 0 [::] => [|n ihn] m ss hss1 hss2; first exact: pop_stable. apply/ihn/push_stable; last by rewrite /= allrel1l hss1. have: all (gtn m.+1) (flatten ([:: m] :: ss)). by rewrite /= leqnn; apply: sub_all hss1 => ? /leqW. elim: ss [:: _] {hss1 hss2} => [|[|? ?] ? ihss] //= ? ?. by rewrite ihss //= all_cat all_merge -andbA andbCA -!all_cat. Qed. End Stability_iota. Lemma sort_pairwise_stable T (leT leT' : rel T) : total leT -> forall s : seq T, pairwise leT' s -> sorted [rel x y | leT x y && (leT y x ==> leT' x y)] (sort leT s). Proof. move=> leT_total s pairwise_s; case Ds: s => // [x s1]. rewrite -{s1}Ds -(mkseq_nth x s) sort_map. apply/homo_sorted_in/sort_iota_stable/(fun _ _ => leT_total _ _)/allss => y z. rewrite !mem_sort !mem_iota !leq0n add0n /= => ys zs /andP [->] /=. by case: (leT _ _); first apply: pairwiseP. Qed. Lemma sort_stable T (leT leT' : rel T) : total leT -> transitive leT' -> forall s : seq T, sorted leT' s -> sorted [rel x y | leT x y && (leT y x ==> leT' x y)] (sort leT s). Proof. move=> leT_total leT'_tr s; rewrite sorted_pairwise //. exact: sort_pairwise_stable. Qed. Lemma sort_stable_in T (P : {pred T}) (leT leT' : rel T) : {in P &, total leT} -> {in P & &, transitive leT'} -> forall s : seq T, all P s -> sorted leT' s -> sorted [rel x y | leT x y && (leT y x ==> leT' x y)] (sort leT s). Proof. move=> /in2_sig leT_total /in3_sig leT_tr _ /all_sigP[s ->]. by rewrite sort_map !sorted_map; apply: sort_stable. Qed. Lemma filter_sort T (leT : rel T) : total leT -> transitive leT -> forall p s, filter p (sort leT s) = sort leT (filter p s). Proof. move=> leT_total leT_tr p s; case Ds: s => // [x s1]. pose leN := relpre (nth x s) leT. pose lt_lex := [rel n m | leN n m && (leN m n ==> (n < m))]. have lt_lex_tr: transitive lt_lex. rewrite /lt_lex /leN => ? ? ? /= /andP [xy xy'] /andP [yz yz']. rewrite (leT_tr _ _ _ xy yz); apply/implyP => zx; move: xy' yz'. by rewrite (leT_tr _ _ _ yz zx) (leT_tr _ _ _ zx xy); apply: ltn_trans. rewrite -{s1}Ds -(mkseq_nth x s) !(filter_map, sort_map); congr map. apply/(@irr_sorted_eq _ lt_lex); rewrite /lt_lex /leN //=. - by move=> ?; rewrite /= ltnn implybF andbN. - exact/sorted_filter/sort_iota_stable. - exact/sort_stable/sorted_filter/iota_ltn_sorted/ltn_trans/ltn_trans. - by move=> ?; rewrite !(mem_filter, mem_sort). Qed. Lemma filter_sort_in T (P : {pred T}) (leT : rel T) : {in P &, total leT} -> {in P & &, transitive leT} -> forall p s, all P s -> filter p (sort leT s) = sort leT (filter p s). Proof. move=> /in2_sig leT_total /in3_sig leT_tr p _ /all_sigP[s ->]. by rewrite !(sort_map, filter_map) filter_sort. Qed. Section Stability_mask. Variables (T : Type) (leT : rel T). Variables (leT_total : total leT) (leT_tr : transitive leT). Lemma mask_sort s m : {m_s : bitseq | mask m_s (sort leT s) = sort leT (mask m s)}. Proof. case Ds: {-}s => [|x s1]; [by rewrite Ds; case: m; exists [::] | clear s1 Ds]. rewrite -(mkseq_nth x s) -map_mask !sort_map. exists [seq i \in mask m (iota 0 (size s)) | i <- sort (xrelpre (nth x s) leT) (iota 0 (size s))]. rewrite -map_mask -filter_mask [in RHS]mask_filter ?iota_uniq ?filter_sort //. by move=> ? ? ?; exact: leT_tr. Qed. Lemma sorted_mask_sort s m : sorted leT (mask m s) -> {m_s | mask m_s (sort leT s) = mask m s}. Proof. by move/(sorted_sort leT_tr) <-; exact: mask_sort. Qed. End Stability_mask. Section Stability_mask_in. Variables (T : Type) (P : {pred T}) (leT : rel T). Hypothesis leT_total : {in P &, total leT}. Hypothesis leT_tr : {in P & &, transitive leT}. Let le_sT := relpre (val : sig P -> _) leT. Let le_sT_total : total le_sT := in2_sig leT_total. Let le_sT_tr : transitive le_sT := in3_sig leT_tr. Lemma mask_sort_in s m : all P s -> {m_s : bitseq | mask m_s (sort leT s) = sort leT (mask m s)}. Proof. move=> /all_sigP [{}s ->]; case: (mask_sort (leT := le_sT) _ _ s m) => //. by move=> m' m'E; exists m'; rewrite -map_mask !sort_map -map_mask m'E. Qed. Lemma sorted_mask_sort_in s m : all P s -> sorted leT (mask m s) -> {m_s | mask m_s (sort leT s) = mask m s}. Proof. move=> ? /(sorted_sort_in leT_tr _) <-; [exact: mask_sort_in | exact: all_mask]. Qed. End Stability_mask_in. Section Stability_subseq. Variables (T : eqType) (leT : rel T). Variables (leT_total : total leT) (leT_tr : transitive leT). Lemma subseq_sort : {homo sort leT : t s / subseq t s}. Proof. move=> _ s /subseqP [m _ ->]; have [m' <-] := mask_sort leT_total leT_tr s m. exact: mask_subseq. Qed. Lemma sorted_subseq_sort t s : subseq t s -> sorted leT t -> subseq t (sort leT s). Proof. by move=> subseq_ts /(sorted_sort leT_tr) <-; exact: subseq_sort. Qed. Lemma mem2_sort s x y : leT x y -> mem2 s x y -> mem2 (sort leT s) x y. Proof. move=> lexy /[!mem2E] /subseq_sort. by case: eqP => // _; rewrite {1}/sort /= lexy /=. Qed. End Stability_subseq. Section Stability_subseq_in. Variables (T : eqType) (leT : rel T). Lemma subseq_sort_in t s : {in s &, total leT} -> {in s & &, transitive leT} -> subseq t s -> subseq (sort leT t) (sort leT s). Proof. move=> leT_total leT_tr /subseqP [m _ ->]. have [m' <-] := mask_sort_in leT_total leT_tr m (allss _). exact: mask_subseq. Qed. Lemma sorted_subseq_sort_in t s : {in s &, total leT} -> {in s & &, transitive leT} -> subseq t s -> sorted leT t -> subseq t (sort leT s). Proof. move=> ? leT_tr ? /(sorted_sort_in leT_tr) <-; last exact/allP/mem_subseq. exact: subseq_sort_in. Qed. Lemma mem2_sort_in s : {in s &, total leT} -> {in s & &, transitive leT} -> forall x y, leT x y -> mem2 s x y -> mem2 (sort leT s) x y. Proof. move=> leT_total leT_tr x y lexy; rewrite !mem2E. by move/subseq_sort_in; case: (_ == _); rewrite /sort /= ?lexy; apply. Qed. End Stability_subseq_in. Lemma sort_sorted T (leT : rel T) : total leT -> forall s, sorted leT (sort leT s). Proof. move=> leT_total s; apply/sub_sorted/sort_stable => //= [? ? /andP[] //|]. by case: s => // x s; elim: s x => /=. Qed. Lemma sort_sorted_in T (P : {pred T}) (leT : rel T) : {in P &, total leT} -> forall s : seq T, all P s -> sorted leT (sort leT s). Proof. by move=> /in2_sig ? _ /all_sigP[s ->]; rewrite sort_map sorted_map sort_sorted. Qed. Arguments sort_sorted {T leT} leT_total s. Arguments sort_sorted_in {T P leT} leT_total {s}. Lemma perm_sortP (T : eqType) (leT : rel T) : total leT -> transitive leT -> antisymmetric leT -> forall s1 s2, reflect (sort leT s1 = sort leT s2) (perm_eq s1 s2). Proof. move=> leT_total leT_tr leT_asym s1 s2. apply: (iffP idP) => eq12; last by rewrite -(perm_sort leT) eq12 perm_sort. apply: (sorted_eq leT_tr leT_asym); rewrite ?sort_sorted //. by rewrite perm_sort (permPl eq12) -(perm_sort leT). Qed. Lemma perm_sort_inP (T : eqType) (leT : rel T) (s1 s2 : seq T) : {in s1 &, total leT} -> {in s1 & &, transitive leT} -> {in s1 &, antisymmetric leT} -> reflect (sort leT s1 = sort leT s2) (perm_eq s1 s2). Proof. move=> /in2_sig leT_total /in3_sig leT_tr /in2_sig/(_ _ _ _)/val_inj leT_asym. apply: (iffP idP) => s1s2; last by rewrite -(perm_sort leT) s1s2 perm_sort. move: (s1s2); have /all_sigP[s1' ->] := allss s1. have /all_sigP[{s1s2}s2 ->] : all [in s1] s2 by rewrite -(perm_all _ s1s2). by rewrite !sort_map => /(perm_map_inj val_inj) /(perm_sortP leT_total)->. Qed. Lemma homo_sort_map (T : Type) (T' : eqType) (f : T -> T') leT leT' : antisymmetric (relpre f leT') -> transitive (relpre f leT') -> total leT -> {homo f : x y / leT x y >-> leT' x y} -> forall s : seq T, sort leT' (map f s) = map f (sort leT s). Proof. move=> leT'_asym leT'_trans leT_total f_homo s; case Ds: s => // [x s']. rewrite -{}Ds -(mkseq_nth x s) [in RHS]sort_map -!map_comp /comp. apply: (@sorted_eq_in _ leT') => [? ? ?|? ?|||]; rewrite ?mem_sort. - by move=> /mapP[? _ ->] /mapP[? _ ->] /mapP[? _ ->]; apply/leT'_trans. - by move=> /mapP[? _ ->] /mapP[? _ ->] /leT'_asym ->. - apply: (sort_sorted_in _ (allss _)) => _ _ /mapP[y _ ->] /mapP[z _ ->]. by case/orP: (leT_total (nth x s y) (nth x s z)) => /f_homo ->; rewrite ?orbT. - by rewrite map_comp -sort_map; exact/homo_sorted/sort_sorted. - by rewrite perm_sort perm_map // perm_sym perm_sort. Qed. Lemma homo_sort_map_in (T : Type) (T' : eqType) (P : {pred T}) (f : T -> T') leT leT' : {in P &, antisymmetric (relpre f leT')} -> {in P & &, transitive (relpre f leT')} -> {in P &, total leT} -> {in P &, {homo f : x y / leT x y >-> leT' x y}} -> forall s : seq T, all P s -> sort leT' [seq f x | x <- s] = [seq f x | x <- sort leT s]. Proof. move=> /in2_sig leT'_asym /in3_sig leT'_trans /in2_sig leT_total. move=> /in2_sig f_homo _ /all_sigP[s ->]. rewrite [in RHS]sort_map -!map_comp /comp. by apply: homo_sort_map => // ? ? /leT'_asym /val_inj. Qed. (* Function trajectories. *) Notation fpath f := (path (coerced_frel f)). Notation fcycle f := (cycle (coerced_frel f)). Notation ufcycle f := (ucycle (coerced_frel f)). Prenex Implicits path next prev cycle ucycle mem2. Section Trajectory. Variables (T : Type) (f : T -> T). Fixpoint traject x n := if n is n'.+1 then x :: traject (f x) n' else [::]. Lemma trajectS x n : traject x n.+1 = x :: traject (f x) n. Proof. by []. Qed. Lemma trajectSr x n : traject x n.+1 = rcons (traject x n) (iter n f x). Proof. by elim: n x => //= n IHn x; rewrite IHn -iterSr. Qed. Lemma last_traject x n : last x (traject (f x) n) = iter n f x. Proof. by case: n => // n; rewrite iterSr trajectSr last_rcons. Qed. Lemma traject_iteri x n : traject x n = iteri n (fun i => rcons^~ (iter i f x)) [::]. Proof. by elim: n => //= n <-; rewrite -trajectSr. Qed. Lemma size_traject x n : size (traject x n) = n. Proof. by elim: n x => //= n IHn x //=; rewrite IHn. Qed. Lemma nth_traject i n : i < n -> forall x, nth x (traject x n) i = iter i f x. Proof. elim: n => // n IHn; rewrite ltnS => le_i_n x. rewrite trajectSr nth_rcons size_traject. by case: ltngtP le_i_n => [? _||->] //; apply: IHn. Qed. Lemma trajectD m n x : traject x (m + n) = traject x m ++ traject (iter m f x) n. Proof. by elim: m => //m IHm in x *; rewrite addSn !trajectS IHm -iterSr. Qed. Lemma take_traject n k x : k <= n -> take k (traject x n) = traject x k. Proof. by move=> /subnKC<-; rewrite trajectD take_size_cat ?size_traject. Qed. End Trajectory. Section EqTrajectory. Variables (T : eqType) (f : T -> T). Lemma eq_fpath f' : f =1 f' -> fpath f =2 fpath f'. Proof. by move/eq_frel/eq_path. Qed. Lemma eq_fcycle f' : f =1 f' -> fcycle f =1 fcycle f'. Proof. by move/eq_frel/eq_cycle. Qed. Lemma fpathE x p : fpath f x p -> p = traject f (f x) (size p). Proof. by elim: p => //= y p IHp in x * => /andP[/eqP{y}<- /IHp<-]. Qed. Lemma fpathP x p : reflect (exists n, p = traject f (f x) n) (fpath f x p). Proof. apply: (iffP idP) => [/fpathE->|[n->]]; first by exists (size p). by elim: n => //= n IHn in x *; rewrite eqxx IHn. Qed. Lemma fpath_traject x n : fpath f x (traject f (f x) n). Proof. by apply/(fpathP x); exists n. Qed. Definition looping x n := iter n f x \in traject f x n. Lemma loopingP x n : reflect (forall m, iter m f x \in traject f x n) (looping x n). Proof. apply: (iffP idP) => loop_n; last exact: loop_n. case: n => // n in loop_n *; elim=> [|m /= IHm]; first exact: mem_head. move: (fpath_traject x n) loop_n; rewrite /looping !iterS -last_traject /=. move: (iter m f x) IHm => y /splitPl[p1 p2 def_y]. rewrite cat_path last_cat def_y; case: p2 => // z p2 /and3P[_ /eqP-> _] _. by rewrite inE mem_cat mem_head !orbT. Qed. Lemma trajectP x n y : reflect (exists2 i, i < n & y = iter i f x) (y \in traject f x n). Proof. elim: n x => [|n IHn] x /=; first by right; case. rewrite inE; have [-> | /= neq_xy] := eqP; first by left; exists 0. apply: {IHn}(iffP (IHn _)) => [[i] | [[|i]]] // lt_i_n ->. by exists i.+1; rewrite ?iterSr. by exists i; rewrite ?iterSr. Qed. Lemma looping_uniq x n : uniq (traject f x n.+1) = ~~ looping x n. Proof. rewrite /looping; elim: n x => [|n IHn] x //. rewrite [n.+1 in LHS]lock [iter]lock /= -!lock {}IHn -iterSr -negb_or inE. congr (~~ _); apply: orb_id2r => /trajectP no_loop. apply/idP/eqP => [/trajectP[m le_m_n def_x] | {1}<-]; last first. by rewrite iterSr -last_traject mem_last. have loop_m: looping x m.+1 by rewrite /looping iterSr -def_x mem_head. have/trajectP[[|i] // le_i_m def_fn1x] := loopingP _ _ loop_m n.+1. by case: no_loop; exists i; rewrite -?iterSr // -ltnS (leq_trans le_i_m). Qed. End EqTrajectory. Arguments fpathP {T f x p}. Arguments loopingP {T f x n}. Arguments trajectP {T f x n y}. Prenex Implicits traject. Section Fcycle. Variables (T : eqType) (f : T -> T) (p : seq T) (f_p : fcycle f p). Lemma nextE (x : T) (p_x : x \in p) : next p x = f x. Proof. exact/esym/eqP/(next_cycle f_p). Qed. Lemma mem_fcycle : {homo f : x / x \in p}. Proof. by move=> x xp; rewrite -nextE// mem_next. Qed. Lemma inj_cycle : {in p &, injective f}. Proof. apply: can_in_inj (iter (size p).-1 f) _ => x /rot_to[i q rip]. have /fpathE qxE : fcycle f (x :: q) by rewrite -rip rot_cycle. have -> : size p = size (rcons q x) by rewrite size_rcons -(size_rot i) rip. by rewrite -iterSr -last_traject prednK -?qxE ?size_rcons// last_rcons. Qed. End Fcycle. Section UniqCycle. Variables (n0 : nat) (T : eqType) (e : rel T) (p : seq T). Hypothesis Up : uniq p. Lemma prev_next : cancel (next p) (prev p). Proof. move=> x; rewrite prev_nth mem_next next_nth; case p_x: (x \in p) => //. case Dp: p Up p_x => // [y q]; rewrite [uniq _]/= -Dp => /andP[q'y Uq] p_x. rewrite -[RHS](nth_index y p_x); congr (nth y _ _); set i := index x p. have: i <= size q by rewrite -index_mem -/i Dp in p_x. case: ltngtP => // [lt_i_q|->] _; first by rewrite index_uniq. by apply/eqP; rewrite nth_default // eqn_leq index_size leqNgt index_mem. Qed. Lemma next_prev : cancel (prev p) (next p). Proof. move=> x; rewrite next_nth mem_prev prev_nth; case p_x: (x \in p) => //. case def_p: p p_x => // [y q]; rewrite -def_p => p_x. rewrite index_uniq //; last by rewrite def_p ltnS index_size. case q_x: (x \in q); first exact: nth_index. rewrite nth_default; last by rewrite leqNgt index_mem q_x. by apply/eqP; rewrite def_p inE q_x orbF eq_sym in p_x. Qed. Lemma cycle_next : fcycle (next p) p. Proof. case def_p: p Up => [|x q] Uq //; rewrite -[in next _]def_p. apply/(pathP x)=> i; rewrite size_rcons => le_i_q. rewrite -cats1 -cat_cons nth_cat le_i_q /= next_nth {}def_p mem_nth //. rewrite index_uniq // nth_cat /= ltn_neqAle andbC -ltnS le_i_q. by case: (i =P _) => //= ->; rewrite subnn nth_default. Qed. Lemma cycle_prev : cycle (fun x y => x == prev p y) p. Proof. apply: etrans cycle_next; symmetry; case def_p: p => [|x q] //. by apply: eq_path; rewrite -def_p; apply: (can2_eq prev_next next_prev). Qed. Lemma cycle_from_next : (forall x, x \in p -> e x (next p x)) -> cycle e p. Proof. case: p (next p) cycle_next => //= [x q] n; rewrite -(belast_rcons x q x). move: {q}(rcons q x) => q n_q /allP. by elim: q x n_q => //= _ q IHq x /andP[/eqP <- n_q] /andP[-> /IHq->]. Qed. Lemma cycle_from_prev : (forall x, x \in p -> e (prev p x) x) -> cycle e p. Proof. move=> e_p; apply: cycle_from_next => x. by rewrite -mem_next => /e_p; rewrite prev_next. Qed. Lemma next_rot : next (rot n0 p) =1 next p. Proof. move=> x; have n_p := cycle_next; rewrite -(rot_cycle n0) in n_p. case p_x: (x \in p); last by rewrite !next_nth mem_rot p_x. by rewrite (eqP (next_cycle n_p _)) ?mem_rot. Qed. Lemma prev_rot : prev (rot n0 p) =1 prev p. Proof. move=> x; have p_p := cycle_prev; rewrite -(rot_cycle n0) in p_p. case p_x: (x \in p); last by rewrite !prev_nth mem_rot p_x. by rewrite (eqP (prev_cycle p_p _)) ?mem_rot. Qed. End UniqCycle. Section UniqRotrCycle. Variables (n0 : nat) (T : eqType) (p : seq T). Hypothesis Up : uniq p. Lemma next_rotr : next (rotr n0 p) =1 next p. Proof. exact: next_rot. Qed. Lemma prev_rotr : prev (rotr n0 p) =1 prev p. Proof. exact: prev_rot. Qed. End UniqRotrCycle. Section UniqCycleRev. Variable T : eqType. Implicit Type p : seq T. Lemma prev_rev p : uniq p -> prev (rev p) =1 next p. Proof. move=> Up x; case p_x: (x \in p); last first. by rewrite next_nth prev_nth mem_rev p_x. case/rot_to: p_x (Up) => [i q def_p] Urp; rewrite -rev_uniq in Urp. rewrite -(prev_rotr i Urp); do 2 rewrite -(prev_rotr 1) ?rotr_uniq //. rewrite -rev_rot -(next_rot i Up) {i p Up Urp}def_p. by case: q => // y q; rewrite !rev_cons !(=^~ rcons_cons, rotr1_rcons) /= eqxx. Qed. Lemma next_rev p : uniq p -> next (rev p) =1 prev p. Proof. by move=> Up x; rewrite -[p in RHS]revK prev_rev // rev_uniq. Qed. End UniqCycleRev. Section MapPath. Variables (T T' : Type) (h : T' -> T) (e : rel T) (e' : rel T'). Definition rel_base (b : pred T) := forall x' y', ~~ b (h x') -> e (h x') (h y') = e' x' y'. Lemma map_path b x' p' (Bb : rel_base b) : ~~ has (preim h b) (belast x' p') -> path e (h x') (map h p') = path e' x' p'. Proof. by elim: p' x' => [|y' p' IHp'] x' //= /norP[/Bb-> /IHp'->]. Qed. End MapPath. Section MapEqPath. Variables (T T' : eqType) (h : T' -> T) (e : rel T) (e' : rel T'). Hypothesis Ih : injective h. Lemma mem2_map x' y' p' : mem2 (map h p') (h x') (h y') = mem2 p' x' y'. Proof. by rewrite [LHS]/mem2 (index_map Ih) -map_drop mem_map. Qed. Lemma next_map p : uniq p -> forall x, next (map h p) (h x) = h (next p x). Proof. move=> Up x; case p_x: (x \in p); last by rewrite !next_nth (mem_map Ih) p_x. case/rot_to: p_x => i p' def_p. rewrite -(next_rot i Up); rewrite -(map_inj_uniq Ih) in Up. rewrite -(next_rot i Up) -map_rot {i p Up}def_p /=. by case: p' => [|y p''] //=; rewrite !eqxx. Qed. Lemma prev_map p : uniq p -> forall x, prev (map h p) (h x) = h (prev p x). Proof. move=> Up x; rewrite -[x in LHS](next_prev Up) -(next_map Up). by rewrite prev_next ?map_inj_uniq. Qed. End MapEqPath. Definition fun_base (T T' : eqType) (h : T' -> T) f f' := rel_base h (frel f) (frel f'). Section CycleArc. Variable T : eqType. Implicit Type p : seq T. Definition arc p x y := let px := rot (index x p) p in take (index y px) px. Lemma arc_rot i p : uniq p -> {in p, arc (rot i p) =2 arc p}. Proof. move=> Up x p_x y; congr (fun q => take (index y q) q); move: Up p_x {y}. rewrite -{1 2 5 6}(cat_take_drop i p) /rot cat_uniq => /and3P[_ Up12 _]. rewrite !drop_cat !take_cat !index_cat mem_cat orbC. case p2x: (x \in drop i p) => /= => [_ | p1x]. rewrite index_mem p2x [x \in _](negbTE (hasPn Up12 _ p2x)) /= addKn. by rewrite ltnNge leq_addr catA. by rewrite p1x index_mem p1x addKn ltnNge leq_addr /= catA. Qed. Lemma left_arc x y p1 p2 (p := x :: p1 ++ y :: p2) : uniq p -> arc p x y = x :: p1. Proof. rewrite /arc /p [index x _]/= eqxx rot0 -cat_cons cat_uniq index_cat. move: (x :: p1) => xp1 /and3P[_ /norP[/= /negbTE-> _] _]. by rewrite eqxx addn0 take_size_cat. Qed. Lemma right_arc x y p1 p2 (p := x :: p1 ++ y :: p2) : uniq p -> arc p y x = y :: p2. Proof. rewrite -[p]cat_cons -rot_size_cat rot_uniq => Up. by rewrite arc_rot ?left_arc ?mem_head. Qed. Variant rot_to_arc_spec p x y := RotToArcSpec i p1 p2 of x :: p1 = arc p x y & y :: p2 = arc p y x & rot i p = x :: p1 ++ y :: p2 : rot_to_arc_spec p x y. Lemma rot_to_arc p x y : uniq p -> x \in p -> y \in p -> x != y -> rot_to_arc_spec p x y. Proof. move=> Up p_x p_y ne_xy; case: (rot_to p_x) (p_y) (Up) => [i q def_p] q_y. rewrite -(mem_rot i) def_p inE eq_sym (negbTE ne_xy) in q_y. rewrite -(rot_uniq i) def_p. case/splitPr: q / q_y def_p => q1 q2 def_p Uq12; exists i q1 q2 => //. by rewrite -(arc_rot i Up p_x) def_p left_arc. by rewrite -(arc_rot i Up p_y) def_p right_arc. Qed. End CycleArc. Prenex Implicits arc.
OfSequence.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.Category.Preorder import Mathlib.CategoryTheory.EqToHom /-! # Functors from the category of the ordered set `ℕ` In this file, we provide a constructor `Functor.ofSequence` for functors `ℕ ⥤ C` which takes as an input a sequence of morphisms `f : X n ⟶ X (n + 1)` for all `n : ℕ`. We also provide a constructor `NatTrans.ofSequence` for natural transformations between functors `ℕ ⥤ C` which allows to check the naturality condition only for morphisms `n ⟶ n + 1`. The duals of the above for functors `ℕᵒᵖ ⥤ C` are given by `Functor.ofOpSequence` and `NatTrans.ofOpSequence`. -/ namespace CategoryTheory open Category variable {C : Type*} [Category C] namespace Functor variable {X : ℕ → C} (f : ∀ n, X n ⟶ X (n + 1)) namespace OfSequence lemma congr_f (i j : ℕ) (h : i = j) : f i = eqToHom (by rw [h]) ≫ f j ≫ eqToHom (by rw [h]) := by subst h simp /-- The morphism `X i ⟶ X j` obtained by composing morphisms of the form `X n ⟶ X (n + 1)` when `i ≤ j`. -/ def map : ∀ {X : ℕ → C} (_ : ∀ n, X n ⟶ X (n + 1)) (i j : ℕ), i ≤ j → (X i ⟶ X j) | _, _, 0, 0 => fun _ ↦ 𝟙 _ | _, f, 0, 1 => fun _ ↦ f 0 | _, f, 0, l + 1 => fun _ ↦ f 0 ≫ map (fun n ↦ f (n + 1)) 0 l (by omega) | _, _, _ + 1, 0 => nofun | _, f, k + 1, l + 1 => fun _ ↦ map (fun n ↦ f (n + 1)) k l (by omega) lemma map_id (i : ℕ) : map f i i (by omega) = 𝟙 _ := by revert X f induction i with | zero => intros; rfl | succ _ hi => intro X f apply hi lemma map_le_succ (i : ℕ) : map f i (i + 1) (by omega) = f i := by revert X f induction i with | zero => intros; rfl | succ _ hi => intro X f apply hi @[reassoc] lemma map_comp (i j k : ℕ) (hij : i ≤ j) (hjk : j ≤ k) : map f i k (hij.trans hjk) = map f i j hij ≫ map f j k hjk := by revert X f j k induction i with | zero => intros X f j revert X f induction j with | zero => intros X f k hij hjk rw [map_id, id_comp] | succ j hj => rintro X f (_ | _ | k) hij hjk · omega · obtain rfl : j = 0 := by omega rw [map_id, comp_id] · simp only [map, Nat.reduceAdd] rw [hj (fun n ↦ f (n + 1)) (k + 1) (by omega) (by omega)] obtain _ | j := j all_goals simp [map] | succ i hi => rintro X f (_ | j) (_ | k) · omega · omega · omega · intros exact hi _ j k (by omega) (by omega) -- `map` has good definitional properties when applied to explicit natural numbers example : map f 5 5 (by omega) = 𝟙 _ := rfl example : map f 0 3 (by omega) = f 0 ≫ f 1 ≫ f 2 := rfl example : map f 3 7 (by omega) = f 3 ≫ f 4 ≫ f 5 ≫ f 6 := rfl end OfSequence /-- The functor `ℕ ⥤ C` constructed from a sequence of morphisms `f : X n ⟶ X (n + 1)` for all `n : ℕ`. -/ @[simps obj] def ofSequence : ℕ ⥤ C where obj := X map {i j} φ := OfSequence.map f i j (leOfHom φ) map_id i := OfSequence.map_id f i map_comp {i j k} α β := OfSequence.map_comp f i j k (leOfHom α) (leOfHom β) @[simp] lemma ofSequence_map_homOfLE_succ (n : ℕ) : (ofSequence f).map (homOfLE (Nat.le_add_right n 1)) = f n := OfSequence.map_le_succ f n end Functor namespace NatTrans variable {F G : ℕ ⥤ C} (app : ∀ (n : ℕ), F.obj n ⟶ G.obj n) (naturality : ∀ (n : ℕ), F.map (homOfLE (n.le_add_right 1)) ≫ app (n + 1) = app n ≫ G.map (homOfLE (n.le_add_right 1))) /-- Constructor for natural transformations `F ⟶ G` in `ℕ ⥤ C` which takes as inputs the morphisms `F.obj n ⟶ G.obj n` for all `n : ℕ` and the naturality condition only for morphisms of the form `n ⟶ n + 1`. -/ @[simps app] def ofSequence : F ⟶ G where app := app naturality := by intro i j φ obtain ⟨k, hk⟩ := Nat.exists_eq_add_of_le (leOfHom φ) obtain rfl := Subsingleton.elim φ (homOfLE (by omega)) revert i j induction k with | zero => intro i j hk obtain rfl : j = i := by omega simp | succ k hk => intro i j hk' obtain rfl : j = i + k + 1 := by omega simp only [← homOfLE_comp (show i ≤ i + k by omega) (show i + k ≤ i + k + 1 by omega), Functor.map_comp, assoc, naturality, reassoc_of% (hk rfl)] end NatTrans namespace Functor variable {X : ℕ → C} (f : ∀ n, X (n + 1) ⟶ X n) /-- The functor `ℕᵒᵖ ⥤ C` constructed from a sequence of morphisms `f : X (n + 1) ⟶ X n` for all `n : ℕ`. -/ @[simps! obj] def ofOpSequence : ℕᵒᵖ ⥤ C := (ofSequence (fun n ↦ (f n).op)).leftOp -- `ofOpSequence` has good definitional properties when applied to explicit natural numbers example : (ofOpSequence f).map (homOfLE (show 5 ≤ 5 by omega)).op = 𝟙 _ := rfl example : (ofOpSequence f).map (homOfLE (show 0 ≤ 3 by omega)).op = (f 2 ≫ f 1) ≫ f 0 := rfl example : (ofOpSequence f).map (homOfLE (show 3 ≤ 7 by omega)).op = ((f 6 ≫ f 5) ≫ f 4) ≫ f 3 := rfl @[simp] lemma ofOpSequence_map_homOfLE_succ (n : ℕ) : (ofOpSequence f).map (homOfLE (Nat.le_add_right n 1)).op = f n := by simp [ofOpSequence] end Functor namespace NatTrans variable {F G : ℕᵒᵖ ⥤ C} (app : ∀ (n : ℕ), F.obj ⟨n⟩ ⟶ G.obj ⟨n⟩) (naturality : ∀ (n : ℕ), F.map (homOfLE (n.le_add_right 1)).op ≫ app n = app (n + 1) ≫ G.map (homOfLE (n.le_add_right 1)).op) /-- Constructor for natural transformations `F ⟶ G` in `ℕᵒᵖ ⥤ C` which takes as inputs the morphisms `F.obj ⟨n⟩ ⟶ G.obj ⟨n⟩` for all `n : ℕ` and the naturality condition only for morphisms of the form `n ⟶ n + 1`. -/ @[simps!] def ofOpSequence : F ⟶ G where app n := app n.unop naturality _ _ f := by let φ : G.rightOp ⟶ F.rightOp := ofSequence (fun n ↦ (app n).op) (fun n ↦ Quiver.Hom.unop_inj (naturality n).symm) exact Quiver.Hom.op_inj (φ.naturality f.unop).symm end NatTrans end CategoryTheory
Prod.lean
/- Copyright (c) 2023 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import Mathlib.MeasureTheory.Measure.Prod import Mathlib.Probability.Kernel.Composition.CompProd import Mathlib.Probability.Kernel.Composition.CompMap /-! # Product and composition of kernels We define the product `κ ×ₖ η` of s-finite kernels `κ : Kernel α β` and `η : Kernel α γ`, which is a kernel from `α` to `β × γ`. ## Main definitions * `prod (κ : Kernel α β) (η : Kernel α γ) : Kernel α (β × γ)`: product of 2 s-finite kernels. `∫⁻ bc, f bc ∂((κ ×ₖ η) a) = ∫⁻ b, ∫⁻ c, f (b, c) ∂(η a) ∂(κ a)` ## Main statements * `lintegral_prod`: Lebesgue integral of a function against a product of kernels. * Instances stating that `IsMarkovKernel`, `IsZeroOrMarkovKernel`, `IsFiniteKernel` and `IsSFiniteKernel` are stable by product. ## Notations * `κ ×ₖ η = ProbabilityTheory.Kernel.prod κ η` -/ open MeasureTheory open scoped ENNReal namespace ProbabilityTheory namespace Kernel variable {α β γ : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} {mγ : MeasurableSpace γ} variable {γ δ : Type*} {mγ : MeasurableSpace γ} {mδ : MeasurableSpace δ} /-- Product of two kernels. This is meaningful only when the kernels are s-finite. -/ noncomputable def prod (κ : Kernel α β) (η : Kernel α γ) : Kernel α (β × γ) := κ ⊗ₖ swapLeft (prodMkLeft β η) @[inherit_doc] scoped[ProbabilityTheory] infixl:100 " ×ₖ " => ProbabilityTheory.Kernel.prod @[simp] lemma zero_prod (η : Kernel α γ) : (0 : Kernel α β) ×ₖ η = 0 := by simp [prod] @[simp] lemma prod_zero (κ : Kernel α β) : κ ×ₖ (0 : Kernel α γ) = 0 := by simp [prod] @[simp] lemma prod_of_not_isSFiniteKernel_left {κ : Kernel α β} (η : Kernel α γ) (h : ¬ IsSFiniteKernel κ) : κ ×ₖ η = 0 := by simp [prod, h] @[simp] lemma prod_of_not_isSFiniteKernel_right (κ : Kernel α β) {η : Kernel α γ} (h : ¬ IsSFiniteKernel η) : κ ×ₖ η = 0 := by cases isEmpty_or_nonempty β with | inl h => simp [eq_zero_of_isEmpty_right κ] | inr h => rw [prod, compProd_of_not_isSFiniteKernel_right] simpa [swapLeft_prodMkLeft, isSFiniteKernel_prodMkRight_iff] theorem prod_apply' (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel α γ) [IsSFiniteKernel η] (a : α) {s : Set (β × γ)} (hs : MeasurableSet s) : (κ ×ₖ η) a s = ∫⁻ b : β, (η a) (Prod.mk b ⁻¹' s) ∂κ a := by simp_rw [prod, compProd_apply hs, swapLeft_apply _ _, prodMkLeft_apply, Prod.swap_prod_mk] lemma prod_apply (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel α γ) [IsSFiniteKernel η] (a : α) : (κ ×ₖ η) a = (κ a).prod (η a) := by ext s hs rw [prod_apply' _ _ _ hs, Measure.prod_apply hs] lemma prod_const (μ : Measure β) [SFinite μ] (ν : Measure γ) [SFinite ν] : const α μ ×ₖ const α ν = const α (μ.prod ν) := by ext x rw [const_apply, prod_apply, const_apply, const_apply] theorem lintegral_prod (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel α γ) [IsSFiniteKernel η] (a : α) {g : β × γ → ℝ≥0∞} (hg : Measurable g) : ∫⁻ c, g c ∂(κ ×ₖ η) a = ∫⁻ b, ∫⁻ c, g (b, c) ∂η a ∂κ a := by simp_rw [prod, lintegral_compProd _ _ _ hg, swapLeft_apply, prodMkLeft_apply, Prod.swap_prod_mk] theorem lintegral_prod_symm (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel α γ) [IsSFiniteKernel η] (a : α) {g : β × γ → ℝ≥0∞} (hg : Measurable g) : ∫⁻ c, g c ∂(κ ×ₖ η) a = ∫⁻ c, ∫⁻ b, g (b, c) ∂κ a ∂η a := by rw [prod_apply, MeasureTheory.lintegral_prod_symm _ hg.aemeasurable] theorem lintegral_deterministic_prod {f : α → β} (hf : Measurable f) (κ : Kernel α γ) [IsSFiniteKernel κ] (a : α) {g : (β × γ) → ℝ≥0∞} (hg : Measurable g) : ∫⁻ p, g p ∂((deterministic f hf) ×ₖ κ) a = ∫⁻ c, g (f a, c) ∂κ a := by rw [lintegral_prod _ _ _ hg, lintegral_deterministic' _ hg.lintegral_prod_right'] theorem lintegral_prod_deterministic {f : α → γ} (hf : Measurable f) (κ : Kernel α β) [IsSFiniteKernel κ] (a : α) {g : (β × γ) → ℝ≥0∞} (hg : Measurable g) : ∫⁻ p, g p ∂(κ ×ₖ (deterministic f hf)) a = ∫⁻ b, g (b, f a) ∂κ a := by rw [lintegral_prod_symm _ _ _ hg, lintegral_deterministic' _ hg.lintegral_prod_left'] theorem lintegral_id_prod {f : (α × β) → ℝ≥0∞} (hf : Measurable f) (κ : Kernel α β) [IsSFiniteKernel κ] (a : α) : ∫⁻ p, f p ∂(Kernel.id ×ₖ κ) a = ∫⁻ b, f (a, b) ∂κ a := by rw [Kernel.id, lintegral_deterministic_prod _ _ _ hf, id_eq] theorem lintegral_prod_id {f : (α × β) → ℝ≥0∞} (hf : Measurable f) (κ : Kernel β α) [IsSFiniteKernel κ] (b : β) : ∫⁻ p, f p ∂(κ ×ₖ Kernel.id) b = ∫⁻ a, f (a, b) ∂κ b := by rw [Kernel.id, lintegral_prod_deterministic _ _ _ hf, id_eq] theorem deterministic_prod_apply' {f : α → β} (mf : Measurable f) (κ : Kernel α γ) [IsSFiniteKernel κ] (a : α) {s : Set (β × γ)} (hs : MeasurableSet s) : ((Kernel.deterministic f mf) ×ₖ κ) a s = κ a (Prod.mk (f a) ⁻¹' s) := by rw [prod_apply' _ _ _ hs, lintegral_deterministic'] exact measurable_measure_prodMk_left hs theorem id_prod_apply' (κ : Kernel α β) [IsSFiniteKernel κ] (a : α) {s : Set (α × β)} (hs : MeasurableSet s) : (Kernel.id ×ₖ κ) a s = κ a (Prod.mk a ⁻¹' s) := by rw [Kernel.id, deterministic_prod_apply' _ _ _ hs, id_eq] instance IsMarkovKernel.prod (κ : Kernel α β) [IsMarkovKernel κ] (η : Kernel α γ) [IsMarkovKernel η] : IsMarkovKernel (κ ×ₖ η) := by rw [Kernel.prod]; infer_instance nonrec instance IsZeroOrMarkovKernel.prod (κ : Kernel α β) [h : IsZeroOrMarkovKernel κ] (η : Kernel α γ) [IsZeroOrMarkovKernel η] : IsZeroOrMarkovKernel (κ ×ₖ η) := by rcases eq_zero_or_isMarkovKernel κ with rfl | h · simp only [prod, swapLeft_prodMkLeft, compProd_zero_left]; infer_instance rcases eq_zero_or_isMarkovKernel η with rfl | h' · simp only [prod, swapLeft, prodMkLeft_zero, comap_zero, compProd_zero_right]; infer_instance infer_instance instance IsFiniteKernel.prod (κ : Kernel α β) [IsFiniteKernel κ] (η : Kernel α γ) [IsFiniteKernel η] : IsFiniteKernel (κ ×ₖ η) := by rw [Kernel.prod]; infer_instance instance IsSFiniteKernel.prod (κ : Kernel α β) (η : Kernel α γ) : IsSFiniteKernel (κ ×ₖ η) := by rw [Kernel.prod]; infer_instance @[simp] lemma fst_prod (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel α γ) [IsMarkovKernel η] : fst (κ ×ₖ η) = κ := by rw [prod]; simp @[simp] lemma snd_prod (κ : Kernel α β) [IsMarkovKernel κ] (η : Kernel α γ) [IsSFiniteKernel η] : snd (κ ×ₖ η) = η := by ext x; simp [snd_apply, prod_apply] lemma comap_prod (κ : Kernel β γ) [IsSFiniteKernel κ] (η : Kernel β δ) [IsSFiniteKernel η] {f : α → β} (hf : Measurable f) : (κ ×ₖ η).comap f hf = (κ.comap f hf) ×ₖ (η.comap f hf) := by ext1 x rw [comap_apply, prod_apply, prod_apply, comap_apply, comap_apply] lemma map_prod_map {ε} {mε : MeasurableSpace ε} (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel α δ) [IsSFiniteKernel η] {f : β → γ} (hf : Measurable f) {g : δ → ε} (hg : Measurable g) : (κ.map f) ×ₖ (η.map g) = (κ ×ₖ η).map (Prod.map f g) := by ext1 x rw [map_apply _ (hf.prodMap hg), prod_apply κ, ← Measure.map_prod_map _ _ hf hg, prod_apply, map_apply _ hf, map_apply _ hg] lemma map_prod_eq (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel α γ) [IsSFiniteKernel η] {f : β → δ} (hf : Measurable f) : (κ.map f) ×ₖ η = (κ ×ₖ η).map (Prod.map f id) := by rw [← map_prod_map _ _ hf measurable_id, map_id] lemma comap_prod_swap (κ : Kernel α β) (η : Kernel γ δ) [IsSFiniteKernel κ] [IsSFiniteKernel η] : comap (prodMkRight α η ×ₖ prodMkLeft γ κ) Prod.swap measurable_swap = map (prodMkRight γ κ ×ₖ prodMkLeft α η) Prod.swap := by rw [ext_fun_iff] intro x f hf rw [lintegral_comap, lintegral_map _ measurable_swap _ hf, lintegral_prod _ _ _ hf, lintegral_prod] swap; · fun_prop simp only [prodMkRight_apply, Prod.fst_swap, Prod.swap_prod_mk, lintegral_prodMkLeft, Prod.snd_swap] refine (lintegral_lintegral_swap ?_).symm fun_prop lemma map_prod_swap (κ : Kernel α β) (η : Kernel α γ) [IsSFiniteKernel κ] [IsSFiniteKernel η] : map (κ ×ₖ η) Prod.swap = η ×ₖ κ := by rw [ext_fun_iff] intro x f hf rw [lintegral_map _ measurable_swap _ hf, lintegral_prod, lintegral_prod _ _ _ hf] swap; · fun_prop refine (lintegral_lintegral_swap ?_).symm fun_prop @[simp] lemma swap_prod {κ : Kernel α β} [IsSFiniteKernel κ] {η : Kernel α γ} [IsSFiniteKernel η] : (swap β γ) ∘ₖ (κ ×ₖ η) = (η ×ₖ κ) := by rw [swap_comp_eq_map, map_prod_swap] lemma deterministic_prod_deterministic {f : α → β} {g : α → γ} (hf : Measurable f) (hg : Measurable g) : deterministic f hf ×ₖ deterministic g hg = deterministic (fun a ↦ (f a, g a)) (hf.prodMk hg) := by ext; simp_rw [prod_apply, deterministic_apply, Measure.dirac_prod_dirac] lemma id_prod_eq : @Kernel.id (α × β) inferInstance = (deterministic Prod.fst measurable_fst) ×ₖ (deterministic Prod.snd measurable_snd) := by rw [deterministic_prod_deterministic] rfl theorem comp_eq_snd_compProd (η : Kernel β γ) [IsSFiniteKernel η] (κ : Kernel α β) [IsSFiniteKernel κ] : η ∘ₖ κ = snd (κ ⊗ₖ prodMkLeft α η) := by ext a s hs rw [comp_apply' _ _ _ hs, snd_apply' _ _ hs, compProd_apply] swap · exact measurable_snd hs simp [← Set.preimage_comp] @[simp] lemma snd_compProd_prodMkLeft (κ : Kernel α β) (η : Kernel β γ) [IsSFiniteKernel κ] [IsSFiniteKernel η] : snd (κ ⊗ₖ prodMkLeft α η) = η ∘ₖ κ := by ext a s hs rw [snd_apply' _ _ hs, compProd_apply, comp_apply' _ _ _ hs] · rfl · exact measurable_snd hs lemma compProd_prodMkLeft_eq_comp (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel β γ) [IsSFiniteKernel η] : κ ⊗ₖ (prodMkLeft α η) = (Kernel.id ×ₖ η) ∘ₖ κ := by ext a s hs rw [comp_eq_snd_compProd, compProd_apply hs, snd_apply' _ _ hs, compProd_apply] swap; · exact measurable_snd hs simp only [prodMkLeft_apply, ← Set.preimage_comp, Prod.snd_comp_mk, Set.preimage_id_eq, id_eq, prod_apply' _ _ _ hs, id_apply] congr with b rw [lintegral_dirac'] exact measurable_measure_prodMk_left hs lemma prodAssoc_prod (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel α γ) [IsSFiniteKernel η] (ξ : Kernel α δ) [IsSFiniteKernel ξ] : ((κ ×ₖ ξ) ×ₖ η).map MeasurableEquiv.prodAssoc = κ ×ₖ (ξ ×ₖ η) := by ext1 a rw [map_apply _ (by fun_prop), prod_apply, prod_apply, Measure.prodAssoc_prod, prod_apply, prod_apply] lemma prod_const_comp {δ} {mδ : MeasurableSpace δ} (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel β γ) [IsSFiniteKernel η] (μ : Measure δ) [SFinite μ] : (η ×ₖ (const β μ)) ∘ₖ κ = (η ∘ₖ κ) ×ₖ (const α μ) := by ext x s ms simp_rw [comp_apply' _ _ _ ms, prod_apply' _ _ _ ms, const_apply, lintegral_comp _ _ _ (measurable_measure_prodMk_left ms)] lemma const_prod_comp {δ} {mδ : MeasurableSpace δ} (κ : Kernel α β) [IsSFiniteKernel κ] (μ : Measure γ) [SFinite μ] (η : Kernel β δ) [IsSFiniteKernel η] : ((const β μ) ×ₖ η) ∘ₖ κ = (const α μ) ×ₖ (η ∘ₖ κ) := by ext x s ms simp_rw [comp_apply' _ _ _ ms, prod_apply, Measure.prod_apply_symm ms, const_apply, lintegral_comp _ _ _ (measurable_measure_prodMk_right ms)] end Kernel end ProbabilityTheory
Adjunctions.lean
/- Copyright (c) 2019 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison, Johannes Hölzl -/ import Mathlib.Algebra.Category.Grp.Preadditive import Mathlib.GroupTheory.FreeAbelianGroup import Mathlib.CategoryTheory.Limits.Types.Shapes /-! # Adjunctions regarding the category of (abelian) groups This file contains construction of basic adjunctions concerning the category of groups and the category of abelian groups. ## Main definitions * `AddCommGrp.free`: constructs the functor associating to a type `X` the free abelian group with generators `x : X`. * `Grp.free`: constructs the functor associating to a type `X` the free group with generators `x : X`. * `Grp.abelianize`: constructs the functor which associates to a group `G` its abelianization `Gᵃᵇ`. ## Main statements * `AddCommGrp.adj`: proves that `AddCommGrp.free` is the left adjoint of the forgetful functor from abelian groups to types. * `Grp.adj`: proves that `Grp.free` is the left adjoint of the forgetful functor from groups to types. * `abelianizeAdj`: proves that `Grp.abelianize` is left adjoint to the forgetful functor from abelian groups to groups. -/ assert_not_exists Cardinal noncomputable section universe u open CategoryTheory Limits namespace AddCommGrp /-- The free functor `Type u ⥤ AddCommGroup` sending a type `X` to the free abelian group with generators `x : X`. -/ def free : Type u ⥤ AddCommGrp where obj α := of (FreeAbelianGroup α) map f := ofHom (FreeAbelianGroup.map f) map_id _ := AddCommGrp.ext FreeAbelianGroup.map_id_apply map_comp _ _ := AddCommGrp.ext FreeAbelianGroup.map_comp_apply @[simp] theorem free_obj_coe {α : Type u} : (free.obj α : Type u) = FreeAbelianGroup α := rfl -- This currently can't be a `simp` lemma, -- because `free_obj_coe` will simplify implicit arguments in the LHS. -- (The `simpNF` linter will, correctly, complain.) theorem free_map_coe {α β : Type u} {f : α → β} (x : FreeAbelianGroup α) : (free.map f) x = f <$> x := rfl /-- The free-forgetful adjunction for abelian groups. -/ def adj : free ⊣ forget AddCommGrp.{u} := Adjunction.mkOfHomEquiv { homEquiv := fun _ _ => ConcreteCategory.homEquiv.trans FreeAbelianGroup.lift.symm -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11041): used to be just `by intros; ext; rfl`. homEquiv_naturality_left_symm := by intros ext simp apply FreeAbelianGroup.lift_comp } instance : free.{u}.IsLeftAdjoint := ⟨_, ⟨adj⟩⟩ instance : (forget AddCommGrp.{u}).IsRightAdjoint := ⟨_, ⟨adj⟩⟩ /-- As an example, we now give a high-powered proof that the monomorphisms in `AddCommGroup` are just the injective functions. (This proof works in all universes.) -/ example {G H : AddCommGrp.{u}} (f : G ⟶ H) [Mono f] : Function.Injective f := (mono_iff_injective (f : G → H)).mp (Functor.map_mono (forget AddCommGrp) f) instance : (free.{u}).PreservesMonomorphisms where preserves {X Y} f _ := by by_cases hX : IsEmpty X · constructor intros apply (IsInitial.isInitialObj free _ ((Types.initial_iff_empty X).2 hX).some).isZero.eq_of_tgt · simp only [not_isEmpty_iff] at hX have hf : Function.Injective f := by rwa [← mono_iff_injective] obtain ⟨g, hg⟩ := hf.hasLeftInverse have : IsSplitMono f := IsSplitMono.mk' { retraction := g } infer_instance end AddCommGrp namespace Grp /-- The free functor `Type u ⥤ Group` sending a type `X` to the free group with generators `x : X`. -/ def free : Type u ⥤ Grp where obj α := of (FreeGroup α) map f := ofHom (FreeGroup.map f) /-- The free-forgetful adjunction for groups. -/ def adj : free ⊣ forget Grp.{u} := Adjunction.mkOfHomEquiv { homEquiv := fun _ _ => ConcreteCategory.homEquiv.trans FreeGroup.lift.symm homEquiv_naturality_left_symm := by intros ext : 1 -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11041): `ext` doesn't apply this theorem anymore apply FreeGroup.ext_hom intros rfl } instance : (forget Grp.{u}).IsRightAdjoint := ⟨_, ⟨adj⟩⟩ section Abelianization /-- The abelianization functor `Group ⥤ CommGroup` sending a group `G` to its abelianization `Gᵃᵇ`. -/ def abelianize : Grp.{u} ⥤ CommGrp.{u} where obj G := CommGrp.of (Abelianization G) map f := CommGrp.ofHom (Abelianization.lift (Abelianization.of.comp f.hom)) map_id := by intros ext : 1 apply (Equiv.apply_eq_iff_eq_symm_apply Abelianization.lift).mpr rfl map_comp := by intros ext : 1 apply (Equiv.apply_eq_iff_eq_symm_apply Abelianization.lift).mpr rfl /-- The abelianization-forgetful adjunction from `Group` to `CommGroup`. -/ def abelianizeAdj : abelianize ⊣ forget₂ CommGrp.{u} Grp.{u} := Adjunction.mkOfHomEquiv { homEquiv := fun _ _ => ((ConcreteCategory.homEquiv (C := CommGrp)).trans Abelianization.lift.symm).trans (ConcreteCategory.homEquiv (C := Grp)).symm -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11041): used to be just `by intros; ext1; rfl`. homEquiv_naturality_left_symm := by intros ext simp only apply Eq.symm apply Abelianization.lift_unique intros apply Abelianization.lift_apply_of } end Abelianization end Grp /-- The functor taking a monoid to its subgroup of units. -/ @[simps!] def MonCat.units : MonCat.{u} ⥤ Grp.{u} where obj R := Grp.of Rˣ map f := Grp.ofHom <| Units.map f.hom map_id _ := Grp.ext fun _ => Units.ext rfl map_comp _ _ := Grp.ext fun _ => Units.ext rfl /-- The forgetful-units adjunction between `Grp` and `MonCat`. -/ def Grp.forget₂MonAdj : forget₂ Grp MonCat ⊣ MonCat.units.{u} := Adjunction.mk' { homEquiv _ Y := { toFun f := ofHom (MonoidHom.toHomUnits f.hom) invFun f := MonCat.ofHom ((Units.coeHom Y).comp f.hom) } unit := { app X := ofHom (@toUnits X _) naturality _ _ _ := Grp.ext fun _ => Units.ext rfl } counit := { app X := MonCat.ofHom (Units.coeHom X) naturality _ _ _ := MonCat.ext fun _ => rfl } } instance : MonCat.units.{u}.IsRightAdjoint := ⟨_, ⟨Grp.forget₂MonAdj⟩⟩ /-- The functor taking a monoid to its subgroup of units. -/ @[simps!] def CommMonCat.units : CommMonCat.{u} ⥤ CommGrp.{u} where obj R := CommGrp.of Rˣ map f := CommGrp.ofHom <| Units.map f.hom map_id _ := CommGrp.ext fun _ => Units.ext rfl map_comp _ _ := CommGrp.ext fun _ => Units.ext rfl /-- The forgetful-units adjunction between `CommGrp` and `CommMonCat`. -/ def CommGrp.forget₂CommMonAdj : forget₂ CommGrp CommMonCat ⊣ CommMonCat.units.{u} := Adjunction.mk' { homEquiv := fun _ Y ↦ { toFun f := ofHom (MonoidHom.toHomUnits f.hom) invFun f := CommMonCat.ofHom ((Units.coeHom Y).comp f.hom) } unit.app X := ofHom toUnits.toMonoidHom -- `aesop` can find the following proof but it takes `0.5`s. unit.naturality _ _ _ := CommGrp.ext fun _ => Units.ext rfl counit.app X := CommMonCat.ofHom (Units.coeHom X) -- `aesop` can find the following proof but it takes `0.5`s. counit.naturality _ _ _ := CommMonCat.ext fun _ => rfl -- `aesop` can find the following proof but it takes `0.2`s. homEquiv_unit := by intros; rfl -- `aesop` can find the following proof but it takes `0.2`s. homEquiv_counit := by intros; rfl } instance : CommMonCat.units.{u}.IsRightAdjoint := ⟨_, ⟨CommGrp.forget₂CommMonAdj⟩⟩
order.v
(* (c) Copyright 2006-2019 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat choice seq. From mathcomp Require Import path fintype tuple bigop finset div prime finfun. From mathcomp Require Import finset. From mathcomp Require Export preorder. (******************************************************************************) (* Types equipped with order relations *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This files defines types equipped with order relations. *) (* *) (* * How to use orders in MathComp? *) (* Use one of the following modules implementing different theories (all *) (* located in the module Order): *) (* Order.LTheory: partially ordered types and lattices excluding complement *) (* and totality related theorems *) (* Order.CTheory: complemented lattices including Order.LTheory *) (* Order.TTheory: totally ordered types including Order.LTheory *) (* Order.Theory: ordered types including all of the above theory modules *) (* To access the definitions, notations, and the theory from, say, *) (* "Order.Xyz", insert "Import Order.Xyz." at the top of your scripts. You can*) (* also "Import Order.Def." to enjoy shorter notations (e.g., min instead of *) (* Order.min, nondecreasing instead of Order.nondecreasing, etc.). *) (* *) (* In order to reason about abstract orders, notations are accessible by *) (* opening the scope "order_scope" bound to the delimiting key "O"; however, *) (* when dealing with another notation scope providing order notations for *) (* a concrete instance (e.g., "ring_scope"), it is not recommended to open *) (* "order_scope" at the same time. *) (* *) (* * Control of inference (parsing) and printing *) (* One characteristic of ordered types is that one carrier type may have *) (* several orders. For example, natural numbers can be totally or partially *) (* ordered by the less than or equal relation, the divisibility relation, and *) (* their dual relations. Therefore, we need a way to control inference of *) (* ordered type instances and printing of generic relations and operations on *) (* ordered types. As a rule of thumb, we use the carrier type or its "alias" *) (* (named copy) to control inference (using canonical structures), and use a *) (* "display" to control the printing of notations. *) (* *) (* Each generic interface and operation for ordered types has, as its first *) (* argument, a "display" of type Order.disp_t. For example, the less than or *) (* equal relation has type: *) (* Order.le : forall {d : Order.disp_t} {T : porderType d}, rel T, *) (* where porderType d is the structure of partially ordered types with *) (* display d. (@Order.le dvd_display _ m n) is printed as m %| n because *) (* ordered type instances associated to the display dvd_display is intended *) (* to represent natural numbers partially ordered by the divisibility *) (* relation. *) (* *) (* We stress that order structure inference can be triggered only from the *) (* carrier type (or its alias), but not the display. For example, writing *) (* m %| n for m and n of type nat does not trigger an inference of the *) (* divisibility relation on natural numbers, which is associated to an alias *) (* natdvd for nat; such an inference should be triggered through the use of *) (* the corresponding alias, i.e., (m : natdvd) %| n. In other words, displays *) (* are merely used to inform the user and the notation mechanism of what the *) (* inference did; they are not additional input for the inference. *) (* *) (* See below for various aliases and their associated displays. *) (* *) (* NB: algebra/ssrnum.v provides the display ring_display to change the *) (* scope of the usual notations to ring_scope. *) (* *) (* Instantiating d with Disp tt tt or an unknown display will lead to a *) (* default display for notations. *) (* *) (* Alternative notation displays can be defined by : *) (* 1. declaring a new opaque definition of type unit. Using the idiom *) (* `Fact my_display : Order.disp_t. Proof. exact: Disp tt tt. Qed.` *) (* 2. using this symbol to tag canonical porderType structures using *) (* `HB.instance Definition _ := isPOrder.Build my_display my_type ...`, *) (* 3. declaring notations for the main operations of this library, by *) (* setting the first argument of the definition to the display, e.g. *) (* `Notation my_syndef_le x y := @Order.le my_display _ x y.` or *) (* `Notation "x <=< y" := @Order.lt my_display _ x y (at level ...).` *) (* Non overloaded notations will default to the default display. *) (* We suggest the user to refer to the example of natdvd below as a guideline *) (* example to add their own displays. *) (* *) (* * Interfaces *) (* We provide the following interfaces for types equipped with an order: *) (* *) (* porderType d == the type of partially ordered types *) (* The HB class is called POrder. *) (* bPOrderType d == porderType with a bottom element (\bot) *) (* The HB class is called BPOrder. *) (* tPOrderType d == porderType with a top element (\top) *) (* The HB class is called TPOrder. *) (* tbPOrderType d == porderType with both a top and a bottom *) (* The HB class is called TBPOrder. *) (* meetSemilatticeType d == the type of meet semilattices *) (* The HB class is called MeetSemilattice. *) (* bMeetSemilatticeType d == meetSemilatticeType with a bottom element *) (* The HB class is called BMeetSemilattice. *) (* tMeetSemilatticeType d == meetSemilatticeType with a top element *) (* The HB class is called TMeetSemilattice. *) (* tbMeetSemilatticeType d == meetSemilatticeType with both a top and a *) (* bottom *) (* The HB class is called TBMeetSemilattice. *) (* joinSemilatticeType d == the type of join semilattices *) (* The HB class is called JoinSemilattice. *) (* bJoinSemilatticeType d == joinSemilatticeType with a bottom element *) (* The HB class is called BJoinSemilattice. *) (* tJoinSemilatticeType d == joinSemilatticeType with a top element *) (* The HB class is called TJoinSemilattice. *) (* tbJoinSemilatticeType d == joinSemilatticeType with both a top and a *) (* bottom *) (* The HB class is called TBJoinSemilattice. *) (* latticeType d == the type of lattices *) (* The HB class is called Lattice. *) (* bLatticeType d == latticeType with a bottom element *) (* The HB class is called BLattice. *) (* tLatticeType d == latticeType with a top element *) (* The HB class is called TLattice. *) (* tbLatticeType d == latticeType with both a top and a bottom *) (* The HB class is called TBLattice. *) (* distrLatticeType d == the type of distributive lattices *) (* The HB class is called DistrLattice. *) (* bDistrLatticeType d == distrLatticeType with a bottom element *) (* The HB class is called BDistrLattice. *) (* tDistrLatticeType d == distrLatticeType with a top element *) (* The HB class is called TDistrLattice. *) (* tbDistrLatticeType d == distrLatticeType with both a top and a bottom *) (* The HB class is called TBDistrLattice. *) (* orderType d == the type of totally ordered types *) (* The HB class is called Total. *) (* bOrderType d == orderType with a bottom element *) (* The HB class is called BTotal. *) (* tOrderType d == orderType with a top element *) (* The HB class is called TTotal. *) (* tbOrderType d == orderType with both a top and a bottom *) (* The HB class is called TBTotal. *) (* cDistrLatticeType d == the type of relatively complemented *) (* distributive lattices, where each interval *) (* [a, b] is equipped with a complement operation*) (* The HB class is called CDistrLattice. *) (* cbDistrLatticeType d == the type of sectionally complemented *) (* distributive lattices, equipped with a bottom,*) (* a relative complement operation, and a *) (* difference operation, i.e., a complement *) (* operation for each interval of the form *) (* [\bot, b] *) (* The HB class is called CBDistrLattice. *) (* ctDistrLatticeType d == the type of dually sectionally complemented *) (* distributive lattices, equipped with a top, *) (* a relative complement operation, and a *) (* dual difference operation, i.e. a complement *) (* operation for each interval of the form *) (* [a, \top] *) (* The HB class is called CTDistrLattice. *) (* ctbDistrLatticeType d == the type of complemented distributive *) (* lattices, equipped with top, bottom, *) (* difference, dual difference, and complement *) (* The HB class is called CTBDistrLattice. *) (* finPOrderType d == the type of partially ordered finite types *) (* The HB class is called FinPOrder. *) (* finBPOrderType d == finPOrderType with a bottom element *) (* The HB class is called FinBPOrder. *) (* finTPOrderType d == finPOrderType with a top element *) (* The HB class is called FinTPOrder. *) (* finTBPOrderType d == finPOrderType with both a top and a bottom *) (* The HB class is called FinTBPOrder. *) (* finMeetSemilatticeType d == the type of finite meet semilattice types *) (* The HB class is called FinMeetSemilattice. *) (* finBMeetSemilatticeType d == finMeetSemilatticeType with a bottom element *) (* Note that finTMeetSemilatticeType is just *) (* finTBLatticeType. *) (* The HB class is called FinBMeetSemilattice. *) (* finJoinSemilatticeType d == the type of finite join semilattice types *) (* The HB class is called FinJoinSemilattice. *) (* finTJoinSemilatticeType d == finJoinSemilatticeType with a top element *) (* Note that finBJoinSemilatticeType is just *) (* finTBLatticeType. *) (* The HB class is called FinTJoinSemilattice. *) (* finLatticeType d == the type of finite lattices *) (* The HB class is called FinLattice. *) (* finTBLatticeType d == the type of nonempty finite lattices *) (* The HB class is called FinTBLattice. *) (* finDistrLatticeType d == the type of finite distributive lattices *) (* The HB class is called FinDistrLattice. *) (* finTBDistrLatticeType d == the type of nonempty finite distributive *) (* lattices *) (* The HB class is called FinTBDistrLattice. *) (* finOrderType d == the type of totally ordered finite types *) (* The HB class is called FinTotal. *) (* finTBOrderType d == the type of nonempty totally ordered finite *) (* types *) (* The HB class is called FinTBTotal. *) (* finCDistrLatticeType d == the type of finite relatively complemented *) (* distributive lattices *) (* The HB class is called FinCDistrLattice. *) (* finCTBDistrLatticeType d == the type of finite complemented distributive *) (* lattices *) (* The HB class is called FinCTBDistrLattice. *) (* *) (* and their joins with subType: *) (* *) (* subPOrder d T P d' == join of porderType d' and subType *) (* (P : pred T) such that val is monotonic *) (* The HB class is called SubPOrder. *) (* meetSubLattice d T P d' == join of latticeType d' and subType *) (* (P : pred T) such that val is monotonic and *) (* a morphism for meet *) (* The HB class is called MeetSubLattice. *) (* joinSubLattice d T P d' == join of latticeType d' and subType *) (* (P : pred T) such that val is monotonic and *) (* a morphism for join *) (* The HB class is called JoinSubLattice. *) (* subLattice d T P d' == join of JoinSubLattice and MeetSubLattice *) (* The HB class is called SubLattice. *) (* bJoinSubLattice d T P d' == join of JoinSubLattice and BLattice *) (* such that val is a morphism for \bot *) (* The HB class is called BJoinSubLattice. *) (* tMeetSubLattice d T P d' == join of MeetSubLattice and TLattice *) (* such that val is a morphism for \top *) (* The HB class is called TMeetSubLattice. *) (* bSubLattice d T P d' == join of SubLattice and BLattice *) (* such that val is a morphism for \bot *) (* The HB class is called BSubLattice. *) (* tSubLattice d T P d' == join of SubLattice and TLattice *) (* such that val is a morphism for \top *) (* The HB class is called BSubLattice. *) (* subOrder d T P d' == join of orderType d' and *) (* subLatticeType d T P d' *) (* The HB class is called SubOrder. *) (* subPOrderLattice d T P d' == join of SubPOrder and Lattice *) (* The HB class is called SubPOrderLattice. *) (* subPOrderBLattice d T P d' == join of SubPOrder and BLattice *) (* The HB class is called SubPOrderBLattice. *) (* subPOrderTLattice d T P d' == join of SubPOrder and TLattice *) (* The HB class is called SubPOrderTLattice. *) (* subPOrderTBLattice d T P d' == join of SubPOrder and TBLattice *) (* The HB class is called SubPOrderTBLattice. *) (* meetSubBLattice d T P d' == join of MeetSubLattice and BLattice *) (* The HB class is called MeetSubBLattice. *) (* meetSubTLattice d T P d' == join of MeetSubLattice and TLattice *) (* The HB class is called MeetSubTLattice. *) (* meetSubTBLattice d T P d' == join of MeetSubLattice and TBLattice *) (* The HB class is called MeetSubTBLattice. *) (* joinSubBLattice d T P d' == join of JoinSubLattice and BLattice *) (* The HB class is called JoinSubBLattice. *) (* joinSubTLattice d T P d' == join of JoinSubLattice and TLattice *) (* The HB class is called JoinSubTLattice. *) (* joinSubTBLattice d T P d' == join of JoinSubLattice and TBLattice *) (* The HB class is called JoinSubTBLattice. *) (* subBLattice d T P d' == join of SubLattice and BLattice *) (* The HB class is called SubBLattice. *) (* subTLattice d T P d' == join of SubLattice and TLattice *) (* The HB class is called SubTLattice. *) (* subTBLattice d T P d' == join of SubLattice and TBLattice *) (* The HB class is called SubTBLattice. *) (* bJoinSubTLattice d T P d' == join of BJoinSubLattice and TBLattice *) (* The HB class is called BJoinSubTLattice. *) (* tMeetSubBLattice d T P d' == join of TMeetSubLattice and TBLattice *) (* The HB class is called TMeetSubBLattice. *) (* bSubTLattice d T P d' == join of BSubLattice and TBLattice *) (* The HB class is called BSubTLattice. *) (* tSubBLattice d T P d' == join of TSubLattice and TBLattice *) (* The HB class is called TSubBLattice. *) (* tbSubBLattice d T P d' == join of BSubLattice and TSubLattice *) (* The HB class is called TBSubLattice. *) (* *) (* Morphisms between the above structures: *) (* *) (* MeetLatticeMorphism.type d T d' T', *) (* JoinLatticeMorphism.type d T d' T', *) (* LatticeMorphism.type d T d' T' == nondecreasing function between two *) (* lattices which are morphism for meet, join, and *) (* meet/join respectively *) (* BLatticeMorphism.type d T d' T' := {blmorphism T -> T'}, *) (* TLatticeMorphism.type d T d' T' := {tlmorphism T -> T'}, *) (* TBLatticeMorphism.type d T d' T' := {tblmorphism T -> T'} *) (* == nondecreasing function between two lattices with *) (* bottom/top which are morphism for bottom/top *) (* *) (* Closedness predicates for the algebraic structures: *) (* *) (* meetLatticeClosed d T == predicate closed under meet on T : latticeType d *) (* The HB class is MeetLatticeClosed. *) (* joinLatticeClosed d T == predicate closed under join on T : latticeType d *) (* The HB class is JoinLatticeClosed. *) (* latticeClosed d T == predicate closed under meet and join *) (* The HB class is JoinLatticeClosed. *) (* bLatticeClosed d T == predicate that contains bottom *) (* The HB class is BLatticeClosed. *) (* tLatticeClosed d T == predicate that contains top *) (* The HB class is TLatticeClosed. *) (* tbLatticeClosed d T == predicate that contains top and bottom *) (* the HB class ie TBLatticeClosed. *) (* bJoinLatticeClosed d T == predicate that contains bottom and is closed *) (* under join *) (* The HB class is BJoinLatticeClosed. *) (* tMeetLatticeClosed d T == predicate that contains top and is closed under *) (* meet *) (* The HB class is TMeetLatticeClosed. *) (* *) (* * Useful lemmas: *) (* On orderType, leP, ltP, and ltgtP are the three main lemmas for case *) (* analysis. *) (* On porderType, one may use comparableP, comparable_leP, comparable_ltP, *) (* and comparable_ltgtP, which are the four main lemmas for case analysis. *) (* *) (* * Order relations and operations: *) (* In general, an overloaded relation or operation on ordered types takes the *) (* following arguments: *) (* 1. a display d of type Order.disp_t, *) (* 2. an instance T of the minimal structure it operates on, and *) (* 3. operands. *) (* Here is the exhaustive list of all such operations together with their *) (* default notation (defined in order_scope unless specified otherwise). *) (* *) (* For T of type porderType d, x and y of type T, and C of type bool: *) (* x <= y := @Order.le d T x y *) (* <-> x is less than or equal to y. *) (* x < y := @Order.lt d T x y *) (* <-> x is less than y, i.e., (y != x) && (x <= y). *) (* x >= y := y <= x *) (* <-> x is greater than or equal to y. *) (* x > y := y < x *) (* <-> x is greater than y. *) (* x >=< y := @Order.comparable d T x y (:= (x <= y) || (y <= x)) *) (* <-> x and y are comparable. *) (* x >< y := ~~ x >=< y *) (* <-> x and y are incomparable. *) (* x <= y ?= iff C := @Order.leif d T x y C (:= (x <= y) * ((x == y) = C)) *) (* <-> x is less than y, or equal iff C is true. *) (* x < y ?<= if C := @Order.lteif d T x y C (:= if C then x <= y else x < y)*) (* <-> x is smaller than y, and strictly if C is false. *) (* Order.min x y := if x < y then x else y *) (* Order.max x y := if x < y then y else x *) (* f \min g == the function x |-> Order.min (f x) (g x); *) (* f \min g simplifies on application. *) (* f \max g == the function x |-> Order.max (f x) (g x); *) (* f \max g simplifies on application. *) (* nondecreasing f <-> the function f : T -> T' is nondecreasing, *) (* where T and T' are porderType *) (* := {homo f : x y / x <= y} *) (* Unary (partially applied) versions of order notations: *) (* >= y := @Order.le d T y *) (* == a predicate characterizing elements greater than or *) (* equal to y *) (* > y := @Order.lt d T y *) (* <= y := @Order.ge d T y *) (* < y := @Order.gt d T y *) (* >=< y := [pred x | @Order.comparable d T x y] *) (* >< y := [pred x | ~~ @Order.comparable d T x y] *) (* 0-ary versions of order notations (in function_scope): *) (* <=%O := @Order.le d T *) (* <%O := @Order.lt d T *) (* >=%O := @Order.ge d T *) (* >%O := @Order.gt d T *) (* >=<%O := @Order.comparable d T *) (* <?=%O := @Order.leif d T *) (* <?<=%O := @Order.lteif d T *) (* -> These conventions are compatible with Haskell's, *) (* where ((< y) x) = (x < y) = ((<) x y), *) (* except that we write <%O instead of (<). *) (* *) (* For T of type bPOrderType d: *) (* \bot := @Order.bottom d T *) (* == the bottom element of type T *) (* \max_<range> e := \big[Order.max / Order.bottom]_<range> e *) (* == iterated max of a preorder with a bottom *) (* the possible <range>s are documented in bigop.v *) (* For T of type tPOrderType d: *) (* \top := @Order.top d T *) (* == the top element of type T *) (* \min_<range> e := \big[Order.max / Order.top]_<range> e *) (* == iterated min of a preorder with a top *) (* the possible <range>s are documented in bigop.v *) (* *) (* For T of type meetSemilatticeType d, and x, y of type T: *) (* x `&` y := @Order.meet d T x y *) (* == the meet of x and y *) (* For T of type joinSemilatticeType d, and x, y of type T: *) (* x `|` y := @Order.join d T x y *) (* == the join of x and y *) (* *) (* For T of type tMeetSemilatticeType d: *) (* \meet_<range> e := \big[Order.meet / Order.top]_<range> e *) (* == iterated meet of a meet-semilattice with a top *) (* the possible <range>s are documented in bigop.v *) (* For T of type bJoinSemilatticeType d: *) (* \join_<range> e := \big[Order.join / Order.bottom]_<range> e *) (* == iterated join of a join-semilattice with a bottom *) (* the possible <range>s are documented in bigop.v *) (* *) (* For T of type cDistrLatticeType d, and x, y, z of type T: *) (* rcompl x y z == the (relative) complement of z in [x, y] *) (* *) (* For T of type cbDistrLatticeType d, and x, y of type T: *) (* x `\` y := @Order.diff d T x y *) (* == the (sectional) complement of y in [\bot, x], *) (* i.e., rcompl \bot x y *) (* *) (* For T of type ctDistrLatticeType d, and x, y of type T: *) (* codiff x y == the (dual sectional) complement of y in [x, \top], *) (* i.e., rcompl x \top y *) (* *) (* For T of type ctbDistrLatticeType d, and x of type T: *) (* ~` x := @Order.compl d T x *) (* == the complement of x in [\bot, \top], *) (* i.e., rcompl \bot \top x *) (* *) (* For preorderType we provide the following operations: *) (* [arg min_(i < i0 | P) M] == a value i : T minimizing M : R, subject to *) (* the condition P (i may appear in P and M), and *) (* provided P holds for i0. *) (* [arg max_(i > i0 | P) M] == a value i maximizing M subject to P and *) (* provided P holds for i0. *) (* [arg min_(i < i0 in A) M] == an i \in A minimizing M if i0 \in A. *) (* [arg max_(i > i0 in A) M] == an i \in A maximizing M if i0 \in A. *) (* [arg min_(i < i0) M] == an i : T minimizing M, given i0 : T. *) (* [arg max_(i > i0) M] == an i : T maximizing M, given i0 : T. *) (* with head symbols Order.arg_min and Order.arg_max *) (* The user may use extremumP or extremum_inP to eliminate them. *) (* *) (* -> patterns for contextual rewriting: *) (* leLHS := (X in (X <= _)%O)%pattern *) (* leRHS := (X in (_ <= X)%O)%pattern *) (* ltLHS := (X in (X < _)%O)%pattern *) (* ltRHS := (X in (_ < X)%O)%pattern *) (* *) (* We provide aliases for various types and their displays: *) (* natdvd := nat (associated with display dvd_display) *) (* == an alias for nat which is canonically ordered using *) (* divisibility predicate dvdn *) (* Notation %|, %<|, gcd, lcm are used instead of *) (* <=, <, meet and join. *) (* T^d := dual T, *) (* where dual is a new definition for (fun T => T) *) (* (associated with dual_display d where d is a display) *) (* == an alias for T, such that if T is canonically *) (* ordered, then T^d is canonically ordered with the *) (* dual order, and displayed with an extra ^d in the *) (* notation, i.e., <=^d, <^d, >=<^d, ><^d, `&`^d, `|`^d *) (* are used and displayed instead of *) (* <=, <, >=<, ><, `&`, `|` *) (* T *prod[d] T' := T * T' *) (* == an alias for the cartesian product such that, *) (* if T and T' are canonically ordered, *) (* then T *prod[d] T' is canonically ordered in product *) (* order, i.e., *) (* (x1, x2) <= (y1, y2) = (x1 <= y1) && (x2 <= y2), *) (* and displayed in display d *) (* T *p T' := T *prod[prod_display d d'] T' *) (* where d and d' are the displays of T and T', *) (* respectively, and prod_display adds an extra ^p to *) (* all notations *) (* T *lexi[d] T' := T * T' *) (* == an alias for the cartesian product such that, *) (* if T and T' are canonically ordered, *) (* then T *lexi[d] T' is canonically ordered in *) (* lexicographic order, *) (* i.e., (x1, x2) <= (y1, y2) = *) (* (x1 <= y1) && ((x1 >= y1) ==> (x2 <= y2)) *) (* and (x1, x2) < (y1, y2) = *) (* (x1 <= y1) && ((x1 >= y1) ==> (x2 < y2)) *) (* and displayed in display d *) (* T *l T' := T *lexi[lexi_display d d'] T' *) (* where d and d' are the displays of T and T', *) (* respectively, and lexi_display adds an extra ^l to *) (* all notations *) (* seqprod_with d T := seq T *) (* == an alias for seq, such that if T is canonically *) (* ordered, then seqprod_with d T is canonically ordered *) (* in product order, i.e., *) (* [:: x1, .., xn] <= [y1, .., yn] = *) (* (x1 <= y1) && ... && (xn <= yn) *) (* and displayed in display d *) (* n.-tupleprod[d] T == same with n.tuple T *) (* seqprod T := seqprod_with (seqprod_display d) T *) (* where d is the display of T, and seqprod_display adds *) (* an extra ^sp to all notations *) (* n.-tupleprod T := n.-tuple[seqprod_display d] T *) (* where d is the display of T *) (* seqlexi_with d T := seq T *) (* == an alias for seq, such that if T is canonically *) (* ordered, then seqprod_with d T is canonically ordered *) (* in lexicographic order, i.e., *) (* [:: x1, .., xn] <= [y1, .., yn] = *) (* (x1 <= x2) && ((x1 >= y1) ==> ((x2 <= y2) && ...)) *) (* and displayed in display d *) (* n.-tuplelexi[d] T == same with n.tuple T *) (* seqlexi T := lexiprod_with (seqlexi_display d) T *) (* where d is the display of T, and seqlexi_display adds *) (* an extra ^sl to all notations *) (* n.-tuplelexi T := n.-tuple[seqlexi_display d] T *) (* where d is the display of T *) (* {subset[d] T} := {set T} *) (* == an alias for set which is canonically ordered by the *) (* subset order and displayed in display d *) (* {subset T} := {subset[subset_display] T} *) (* *) (* The following notations are provided to build substructures: *) (* [SubChoice_isSubPOrder of U by <: with disp] == *) (* [SubChoice_isSubPOrder of U by <:] == porderType mixin for a subType *) (* whose base type is a porderType *) (* [SubPOrder_isSubLattice of U by <: with disp] == *) (* [SubPOrder_isSubLattice of U by <:] == *) (* [SubChoice_isSubLattice of U by <: with disp] == *) (* [SubChoice_isSubLattice of U by <:] == latticeType mixin for a subType *) (* whose base type is a latticeType and whose *) (* predicate is a latticeClosed *) (* [SubPOrder_isBSubLattice of U by <: with disp] == *) (* [SubPOrder_isBSubLattice of U by <:] == *) (* [SubChoice_isBSubLattice of U by <: with disp] == *) (* [SubChoice_isBSubLattice of U by <:] == blatticeType mixin for a subType *) (* whose base type is a blatticeType and whose *) (* predicate is both a latticeClosed *) (* and a bLatticeClosed *) (* [SubPOrder_isTSubLattice of U by <: with disp] == *) (* [SubPOrder_isTSubLattice of U by <:] == *) (* [SubChoice_isTSubLattice of U by <: with disp] == *) (* [SubChoice_isTSubLattice of U by <:] == tlatticeType mixin for a subType *) (* whose base type is a tlatticeType and whose *) (* predicate is both a latticeClosed *) (* and a tLatticeClosed *) (* [SubPOrder_isTBSubLattice of U by <: with disp] == *) (* [SubPOrder_isTBSubLattice of U by <:] == *) (* [SubChoice_isTBSubLattice of U by <: with disp] == *) (* [SubChoice_isTBSubLattice of U by <:] == tblatticeType mixin for a subType *) (* whose base type is a tblatticeType and whose *) (* predicate is both a latticeClosed *) (* and a tbLatticeClosed *) (* [SubLattice_isSubOrder of U by <: with disp] == *) (* [SubLattice_isSubOrder of U by <:] == *) (* [SubPOrder_isSubOrder of U by <: with disp] == *) (* [SubPOrder_isSubOrder of U by <:] == *) (* [SubChoice_isSubOrder of U by <: with disp] == *) (* [SubChoice_isSubOrder of U by <:] == orderType mixin for a subType whose *) (* base type is an orderType *) (* [POrder of U by <:] == porderType mixin for a subType whose base type is *) (* a porderType *) (* [Order of U by <:] == orderType mixin for a subType whose base type is *) (* an orderType *) (* *) (* We provide expected instances of ordered types for bool, nat (for leq and *) (* and dvdn), 'I_n, 'I_n.+1 (with a top and bottom), nat for dvdn, *) (* T *prod[disp] T', T *lexi[disp] T', {t : T & T' x} (with lexicographic *) (* ordering), seqprod_with d T (using product order), seqlexi_with d T *) (* (with lexicographic ordering), n.-tupleprod[disp] (using product order), *) (* n.-tuplelexi[d] T (with lexicographic ordering), on {subset[disp] T} *) (* (using subset order) and all possible finite type instances. *) (* (Use `HB.about type` to discover the instances on type.) *) (* *) (* In order to get a canonical order on prod, seq, tuple or set, one may *) (* import modules DefaultProdOrder or DefaultProdLexiOrder, *) (* DefaultSeqProdOrder or DefaultSeqLexiOrder, *) (* DefaultTupleProdOrder or DefaultTupleLexiOrder, *) (* and DefaultSetSubsetOrder. *) (* *) (* We also provide specialized versions of some theorems from path.v. *) (* *) (* We provide Order.enum_val, Order.enum_rank, and Order.enum_rank_in, which *) (* are monotonic variations of enum_val, enum_rank, and enum_rank_in *) (* whenever the type is porderType, and their monotonicity is provided if *) (* this order is total. The theory is in the module Order (Order.enum_valK, *) (* Order.enum_rank_inK, etc) but Order.Enum can be imported to shorten these. *) (* *) (* We provide an opaque monotonous bijection tagnat.sig / tagnat.rank between *) (* the finite types {i : 'I_n & 'I_(p_ i)} and 'I_(\sum_i p_ i): *) (* tagnat.sig : 'I_(\sum_i p_ i) -> {i : 'I_n & 'I_(p_ i)} *) (* tagnat.rank : {i : 'I_n & 'I_(p_ i)} -> 'I_(\sum_i p_ i) *) (* tagnat.sig1 : 'I_(\sum_i p_ i) -> 'I_n *) (* tagnat.sig2 : forall p : 'I_(\sum_i p_ i), 'I_(p_ (tagnat.sig1 p)) *) (* tagnat.Rank : forall i, 'I_(p_ i) -> 'I_(\sum_i p_ i) *) (* *) (* Acknowledgments: This file is based on prior work by D. Dreyer, G. *) (* Gonthier, A. Nanevski, P-Y Strub, B. Ziliani *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope order_scope. Delimit Scope order_scope with O. Local Open Scope order_scope. (* Reserved notations for lattice operations *) Reserved Notation "A `&` B" (at level 48, left associativity). Reserved Notation "A `|` B" (at level 52, left associativity). Reserved Notation "A `\` B" (at level 50, left associativity). Reserved Notation "~` A" (at level 35, right associativity). (* Reserved notations for dual order *) Reserved Notation "A `&^d` B" (at level 48, left associativity). Reserved Notation "A `|^d` B" (at level 52, left associativity). Reserved Notation "A `\^d` B" (at level 50, left associativity). Reserved Notation "~^d` A" (at level 35, right associativity). (* Reserved notations for product ordering of prod *) Reserved Notation "A `&^p` B" (at level 48, left associativity). Reserved Notation "A `|^p` B" (at level 52, left associativity). Reserved Notation "A `\^p` B" (at level 50, left associativity). Reserved Notation "~^p` A" (at level 35, right associativity). (* Reserved notations for product ordering of seq *) Reserved Notation "A `&^sp` B" (at level 48, left associativity). Reserved Notation "A `|^sp` B" (at level 52, left associativity). Reserved Notation "A `\^sp` B" (at level 50, left associativity). Reserved Notation "~^sp` A" (at level 35, right associativity). (* Reserved notations for lexicographic ordering of prod *) Reserved Notation "A `&^l` B" (at level 48, left associativity). Reserved Notation "A `|^l` B" (at level 52, left associativity). Reserved Notation "A `\^l` B" (at level 50, left associativity). Reserved Notation "~^l` A" (at level 35, right associativity). (* Reserved notations for lexicographic ordering of seq *) Reserved Notation "A `&^sl` B" (at level 48, left associativity). Reserved Notation "A `|^sl` B" (at level 52, left associativity). Reserved Notation "A `\^sl` B" (at level 50, left associativity). Reserved Notation "~^sl` A" (at level 35, right associativity). (* Reserved notations for divisibility *) Reserved Notation "\gcd_ i F" (at level 34, F at level 41, i at level 0, format "'[' \gcd_ i '/ ' F ']'"). Reserved Notation "\gcd_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \gcd_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\gcd_ ( i <- r ) F" (F at level 41, format "'[' \gcd_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\gcd_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \gcd_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\gcd_ ( m <= i < n ) F" (F at level 41, format "'[' \gcd_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\gcd_ ( i | P ) F" (F at level 41, format "'[' \gcd_ ( i | P ) '/ ' F ']'"). Reserved Notation "\gcd_ ( i : t | P ) F" (F at level 41). Reserved Notation "\gcd_ ( i : t ) F" (F at level 41). Reserved Notation "\gcd_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \gcd_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\gcd_ ( i < n ) F" (F at level 41, format "'[' \gcd_ ( i < n ) F ']'"). Reserved Notation "\gcd_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \gcd_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\gcd_ ( i 'in' A ) F" (F at level 41, format "'[' \gcd_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\lcm_ i F" (at level 34, F at level 41, i at level 0, format "'[' \lcm_ i '/ ' F ']'"). Reserved Notation "\lcm_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \lcm_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\lcm_ ( i <- r ) F" (F at level 41, format "'[' \lcm_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\lcm_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \lcm_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\lcm_ ( m <= i < n ) F" (F at level 41, format "'[' \lcm_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\lcm_ ( i | P ) F" (F at level 41, format "'[' \lcm_ ( i | P ) '/ ' F ']'"). Reserved Notation "\lcm_ ( i : t | P ) F" (F at level 41). Reserved Notation "\lcm_ ( i : t ) F" (F at level 41). Reserved Notation "\lcm_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \lcm_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\lcm_ ( i < n ) F" (F at level 41, format "'[' \lcm_ ( i < n ) F ']'"). Reserved Notation "\lcm_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \lcm_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\lcm_ ( i 'in' A ) F" (F at level 41, format "'[' \lcm_ ( i 'in' A ) '/ ' F ']'"). (* Reserved notations for iterative meet and join *) Reserved Notation "\meet_ i F" (at level 34, F at level 41, i at level 0, format "'[' \meet_ i '/ ' F ']'"). Reserved Notation "\meet_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \meet_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\meet_ ( i <- r ) F" (F at level 41, format "'[' \meet_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\meet_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \meet_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\meet_ ( m <= i < n ) F" (F at level 41, format "'[' \meet_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\meet_ ( i | P ) F" (F at level 41, format "'[' \meet_ ( i | P ) '/ ' F ']'"). Reserved Notation "\meet_ ( i : t | P ) F" (F at level 41). Reserved Notation "\meet_ ( i : t ) F" (F at level 41). Reserved Notation "\meet_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \meet_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\meet_ ( i < n ) F" (F at level 41, format "'[' \meet_ ( i < n ) F ']'"). Reserved Notation "\meet_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \meet_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\meet_ ( i 'in' A ) F" (F at level 41, format "'[' \meet_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\join_ i F" (at level 34, F at level 41, i at level 0, format "'[' \join_ i '/ ' F ']'"). Reserved Notation "\join_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \join_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\join_ ( i <- r ) F" (F at level 41, format "'[' \join_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\join_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \join_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\join_ ( m <= i < n ) F" (F at level 41, format "'[' \join_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\join_ ( i | P ) F" (F at level 41, format "'[' \join_ ( i | P ) '/ ' F ']'"). Reserved Notation "\join_ ( i : t | P ) F" (F at level 41). Reserved Notation "\join_ ( i : t ) F" (F at level 41). Reserved Notation "\join_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \join_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\join_ ( i < n ) F" (F at level 41, format "'[' \join_ ( i < n ) F ']'"). Reserved Notation "\join_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \join_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\join_ ( i 'in' A ) F" (F at level 41, format "'[' \join_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\meet^d_ i F" (at level 34, F at level 41, i at level 0, format "'[' \meet^d_ i '/ ' F ']'"). Reserved Notation "\meet^d_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \meet^d_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\meet^d_ ( i <- r ) F" (F at level 41, format "'[' \meet^d_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\meet^d_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \meet^d_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\meet^d_ ( m <= i < n ) F" (F at level 41, format "'[' \meet^d_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\meet^d_ ( i | P ) F" (F at level 41, format "'[' \meet^d_ ( i | P ) '/ ' F ']'"). Reserved Notation "\meet^d_ ( i : t | P ) F" (F at level 41). Reserved Notation "\meet^d_ ( i : t ) F" (F at level 41). Reserved Notation "\meet^d_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \meet^d_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\meet^d_ ( i < n ) F" (F at level 41, format "'[' \meet^d_ ( i < n ) F ']'"). Reserved Notation "\meet^d_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \meet^d_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\meet^d_ ( i 'in' A ) F" (F at level 41, format "'[' \meet^d_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\join^d_ i F" (at level 34, F at level 41, i at level 0, format "'[' \join^d_ i '/ ' F ']'"). Reserved Notation "\join^d_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \join^d_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\join^d_ ( i <- r ) F" (F at level 41, format "'[' \join^d_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\join^d_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \join^d_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\join^d_ ( m <= i < n ) F" (F at level 41, format "'[' \join^d_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\join^d_ ( i | P ) F" (F at level 41, format "'[' \join^d_ ( i | P ) '/ ' F ']'"). Reserved Notation "\join^d_ ( i : t | P ) F" (F at level 41). Reserved Notation "\join^d_ ( i : t ) F" (F at level 41). Reserved Notation "\join^d_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \join^d_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\join^d_ ( i < n ) F" (F at level 41, format "'[' \join^d_ ( i < n ) F ']'"). Reserved Notation "\join^d_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \join^d_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\join^d_ ( i 'in' A ) F" (F at level 41, format "'[' \join^d_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\meet^p_ i F" (at level 34, F at level 41, i at level 0, format "'[' \meet^p_ i '/ ' F ']'"). Reserved Notation "\meet^p_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \meet^p_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\meet^p_ ( i <- r ) F" (F at level 41, format "'[' \meet^p_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\meet^p_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \meet^p_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\meet^p_ ( m <= i < n ) F" (F at level 41, format "'[' \meet^p_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\meet^p_ ( i | P ) F" (F at level 41, format "'[' \meet^p_ ( i | P ) '/ ' F ']'"). Reserved Notation "\meet^p_ ( i : t | P ) F" (F at level 41). Reserved Notation "\meet^p_ ( i : t ) F" (F at level 41). Reserved Notation "\meet^p_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \meet^p_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\meet^p_ ( i < n ) F" (F at level 41, format "'[' \meet^p_ ( i < n ) F ']'"). Reserved Notation "\meet^p_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \meet^p_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\meet^p_ ( i 'in' A ) F" (F at level 41, format "'[' \meet^p_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\join^p_ i F" (at level 34, F at level 41, i at level 0, format "'[' \join^p_ i '/ ' F ']'"). Reserved Notation "\join^p_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \join^p_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\join^p_ ( i <- r ) F" (F at level 41, format "'[' \join^p_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\join^p_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \join^p_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\join^p_ ( m <= i < n ) F" (F at level 41, format "'[' \join^p_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\join^p_ ( i | P ) F" (F at level 41, format "'[' \join^p_ ( i | P ) '/ ' F ']'"). Reserved Notation "\join^p_ ( i : t | P ) F" (F at level 41). Reserved Notation "\join^p_ ( i : t ) F" (F at level 41). Reserved Notation "\join^p_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \join^p_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\join^p_ ( i < n ) F" (F at level 41, format "'[' \join^p_ ( i < n ) F ']'"). Reserved Notation "\join^p_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \join^p_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\join^p_ ( i 'in' A ) F" (F at level 41, format "'[' \join^p_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\min^p_ i F" (at level 34, F at level 41, i at level 0, format "'[' \min^p_ i '/ ' F ']'"). Reserved Notation "\min^p_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \min^p_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\min^p_ ( i <- r ) F" (F at level 41, format "'[' \min^p_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\min^p_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \min^p_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\min^p_ ( m <= i < n ) F" (F at level 41, format "'[' \min^p_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\min^p_ ( i | P ) F" (F at level 41, format "'[' \min^p_ ( i | P ) '/ ' F ']'"). Reserved Notation "\min^p_ ( i : t | P ) F" (F at level 41). Reserved Notation "\min^p_ ( i : t ) F" (F at level 41). Reserved Notation "\min^p_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \min^p_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\min^p_ ( i < n ) F" (F at level 41, format "'[' \min^p_ ( i < n ) F ']'"). Reserved Notation "\min^p_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \min^p_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\min^p_ ( i 'in' A ) F" (F at level 41, format "'[' \min^p_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\max^p_ i F" (at level 34, F at level 41, i at level 0, format "'[' \max^p_ i '/ ' F ']'"). Reserved Notation "\max^p_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \max^p_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\max^p_ ( i <- r ) F" (F at level 41, format "'[' \max^p_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\max^p_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \max^p_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\max^p_ ( m <= i < n ) F" (F at level 41, format "'[' \max^p_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\max^p_ ( i | P ) F" (F at level 41, format "'[' \max^p_ ( i | P ) '/ ' F ']'"). Reserved Notation "\max^p_ ( i : t | P ) F" (F at level 41). Reserved Notation "\max^p_ ( i : t ) F" (F at level 41). Reserved Notation "\max^p_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \max^p_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\max^p_ ( i < n ) F" (F at level 41, format "'[' \max^p_ ( i < n ) F ']'"). Reserved Notation "\max^p_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \max^p_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\max^p_ ( i 'in' A ) F" (F at level 41, format "'[' \max^p_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\meet^sp_ i F" (at level 34, F at level 41, i at level 0, format "'[' \meet^sp_ i '/ ' F ']'"). Reserved Notation "\meet^sp_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \meet^sp_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\meet^sp_ ( i <- r ) F" (F at level 41, format "'[' \meet^sp_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\meet^sp_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \meet^sp_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\meet^sp_ ( m <= i < n ) F" (F at level 41, format "'[' \meet^sp_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\meet^sp_ ( i | P ) F" (F at level 41, format "'[' \meet^sp_ ( i | P ) '/ ' F ']'"). Reserved Notation "\meet^sp_ ( i : t | P ) F" (F at level 41). Reserved Notation "\meet^sp_ ( i : t ) F" (F at level 41). Reserved Notation "\meet^sp_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \meet^sp_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\meet^sp_ ( i < n ) F" (F at level 41, format "'[' \meet^sp_ ( i < n ) F ']'"). Reserved Notation "\meet^sp_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \meet^sp_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\meet^sp_ ( i 'in' A ) F" (F at level 41, format "'[' \meet^sp_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\join^sp_ i F" (at level 34, F at level 41, i at level 0, format "'[' \join^sp_ i '/ ' F ']'"). Reserved Notation "\join^sp_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \join^sp_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\join^sp_ ( i <- r ) F" (F at level 41, format "'[' \join^sp_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\join^sp_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \join^sp_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\join^sp_ ( m <= i < n ) F" (F at level 41, format "'[' \join^sp_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\join^sp_ ( i | P ) F" (F at level 41, format "'[' \join^sp_ ( i | P ) '/ ' F ']'"). Reserved Notation "\join^sp_ ( i : t | P ) F" (F at level 41). Reserved Notation "\join^sp_ ( i : t ) F" (F at level 41). Reserved Notation "\join^sp_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \join^sp_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\join^sp_ ( i < n ) F" (F at level 41, format "'[' \join^sp_ ( i < n ) F ']'"). Reserved Notation "\join^sp_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \join^sp_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\join^sp_ ( i 'in' A ) F" (F at level 41, format "'[' \join^sp_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\min^sp_ i F" (at level 34, F at level 41, i at level 0, format "'[' \min^sp_ i '/ ' F ']'"). Reserved Notation "\min^sp_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \min^sp_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\min^sp_ ( i <- r ) F" (F at level 41, format "'[' \min^sp_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\min^sp_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \min^sp_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\min^sp_ ( m <= i < n ) F" (F at level 41, format "'[' \min^sp_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\min^sp_ ( i | P ) F" (F at level 41, format "'[' \min^sp_ ( i | P ) '/ ' F ']'"). Reserved Notation "\min^sp_ ( i : t | P ) F" (F at level 41). Reserved Notation "\min^sp_ ( i : t ) F" (F at level 41). Reserved Notation "\min^sp_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \min^sp_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\min^sp_ ( i < n ) F" (F at level 41, format "'[' \min^sp_ ( i < n ) F ']'"). Reserved Notation "\min^sp_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \min^sp_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\min^sp_ ( i 'in' A ) F" (F at level 41, format "'[' \min^sp_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\max^sp_ i F" (at level 34, F at level 41, i at level 0, format "'[' \max^sp_ i '/ ' F ']'"). Reserved Notation "\max^sp_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \max^sp_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\max^sp_ ( i <- r ) F" (F at level 41, format "'[' \max^sp_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\max^sp_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \max^sp_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\max^sp_ ( m <= i < n ) F" (F at level 41, format "'[' \max^sp_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\max^sp_ ( i | P ) F" (F at level 41, format "'[' \max^sp_ ( i | P ) '/ ' F ']'"). Reserved Notation "\max^sp_ ( i : t | P ) F" (F at level 41). Reserved Notation "\max^sp_ ( i : t ) F" (F at level 41). Reserved Notation "\max^sp_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \max^sp_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\max^sp_ ( i < n ) F" (F at level 41, format "'[' \max^sp_ ( i < n ) F ']'"). Reserved Notation "\max^sp_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \max^sp_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\max^sp_ ( i 'in' A ) F" (F at level 41, format "'[' \max^sp_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\meet^l_ i F" (at level 34, F at level 41, i at level 0, format "'[' \meet^l_ i '/ ' F ']'"). Reserved Notation "\meet^l_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \meet^l_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\meet^l_ ( i <- r ) F" (F at level 41, format "'[' \meet^l_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\meet^l_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \meet^l_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\meet^l_ ( m <= i < n ) F" (F at level 41, format "'[' \meet^l_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\meet^l_ ( i | P ) F" (F at level 41, format "'[' \meet^l_ ( i | P ) '/ ' F ']'"). Reserved Notation "\meet^l_ ( i : t | P ) F" (F at level 41). Reserved Notation "\meet^l_ ( i : t ) F" (F at level 41). Reserved Notation "\meet^l_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \meet^l_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\meet^l_ ( i < n ) F" (F at level 41, format "'[' \meet^l_ ( i < n ) F ']'"). Reserved Notation "\meet^l_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \meet^l_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\meet^l_ ( i 'in' A ) F" (F at level 41, format "'[' \meet^l_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\join^l_ i F" (at level 34, F at level 41, i at level 0, format "'[' \join^l_ i '/ ' F ']'"). Reserved Notation "\join^l_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \join^l_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\join^l_ ( i <- r ) F" (F at level 41, format "'[' \join^l_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\join^l_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \join^l_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\join^l_ ( m <= i < n ) F" (F at level 41, format "'[' \join^l_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\join^l_ ( i | P ) F" (F at level 41, format "'[' \join^l_ ( i | P ) '/ ' F ']'"). Reserved Notation "\join^l_ ( i : t | P ) F" (F at level 41). Reserved Notation "\join^l_ ( i : t ) F" (F at level 41). Reserved Notation "\join^l_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \join^l_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\join^l_ ( i < n ) F" (F at level 41, format "'[' \join^l_ ( i < n ) F ']'"). Reserved Notation "\join^l_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \join^l_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\join^l_ ( i 'in' A ) F" (F at level 41, format "'[' \join^l_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\min^l_ i F" (at level 34, F at level 41, i at level 0, format "'[' \min^l_ i '/ ' F ']'"). Reserved Notation "\min^l_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \min^l_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\min^l_ ( i <- r ) F" (F at level 41, format "'[' \min^l_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\min^l_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \min^l_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\min^l_ ( m <= i < n ) F" (F at level 41, format "'[' \min^l_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\min^l_ ( i | P ) F" (F at level 41, format "'[' \min^l_ ( i | P ) '/ ' F ']'"). Reserved Notation "\min^l_ ( i : t | P ) F" (F at level 41). Reserved Notation "\min^l_ ( i : t ) F" (F at level 41). Reserved Notation "\min^l_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \min^l_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\min^l_ ( i < n ) F" (F at level 41, format "'[' \min^l_ ( i < n ) F ']'"). Reserved Notation "\min^l_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \min^l_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\min^l_ ( i 'in' A ) F" (F at level 41, format "'[' \min^l_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\max^l_ i F" (at level 34, F at level 41, i at level 0, format "'[' \max^l_ i '/ ' F ']'"). Reserved Notation "\max^l_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \max^l_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\max^l_ ( i <- r ) F" (F at level 41, format "'[' \max^l_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\max^l_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \max^l_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\max^l_ ( m <= i < n ) F" (F at level 41, format "'[' \max^l_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\max^l_ ( i | P ) F" (F at level 41, format "'[' \max^l_ ( i | P ) '/ ' F ']'"). Reserved Notation "\max^l_ ( i : t | P ) F" (F at level 41). Reserved Notation "\max^l_ ( i : t ) F" (F at level 41). Reserved Notation "\max^l_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \max^l_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\max^l_ ( i < n ) F" (F at level 41, format "'[' \max^l_ ( i < n ) F ']'"). Reserved Notation "\max^l_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \max^l_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\max^l_ ( i 'in' A ) F" (F at level 41, format "'[' \max^l_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "'{' 'omorphism' U '->' V '}'" (U at level 98, V at level 99, format "{ 'omorphism' U -> V }"). Reserved Notation "'{' 'mlmorphism' U '->' V '}'" (U at level 98, V at level 99, format "{ 'mlmorphism' U -> V }"). Reserved Notation "'{' 'jlmorphism' U '->' V '}'" (U at level 98, V at level 99, format "{ 'jlmorphism' U -> V }"). Reserved Notation "'{' 'lmorphism' U '->' V '}'" (U at level 98, V at level 99, format "{ 'lmorphism' U -> V }"). Reserved Notation "'{' 'blmorphism' U '->' V '}'" (U at level 98, V at level 99, format "{ 'blmorphism' U -> V }"). Reserved Notation "'{' 'tlmorphism' U '->' V '}'" (U at level 98, V at level 99, format "{ 'tlmorphism' U -> V }"). Reserved Notation "'{' 'tblmorphism' U '->' V '}'" (U at level 98, V at level 99, format "{ 'tblmorphism' U -> V }"). Module Order. Export Order. #[key="T", primitive] HB.mixin Record Preorder_isDuallyPOrder (d : disp_t) T of Preorder d T := { le_anti : antisymmetric (@le d T); ge_anti : antisymmetric (fun x y => @le d T y x); }. #[short(type="porderType")] HB.structure Definition POrder (d : disp_t) := { T of Preorder d T & Preorder_isDuallyPOrder d T }. #[short(type="bPOrderType")] HB.structure Definition BPOrder d := { T of hasBottom d T & POrder d T }. #[short(type="tPOrderType")] HB.structure Definition TPOrder d := { T of hasTop d T & POrder d T }. #[short(type="tbPOrderType")] HB.structure Definition TBPOrder d := { T of hasTop d T & BPOrder d T }. Module POrderExports. Arguments le_trans {d s} [_ _ _]. End POrderExports. HB.export POrderExports. (* Bind Scope order_scope with POrder.sort. *) #[key="T", primitive] HB.mixin Record POrder_isMeetSemilattice d (T : Type) of POrder d T := { meet : T -> T -> T; lexI : forall x y z, (x <= meet y z) = (x <= y) && (x <= z); }. #[key="T", primitive] HB.mixin Record POrder_isJoinSemilattice d T of POrder d T := { join : T -> T -> T; leUx : forall x y z, (join x y <= z) = (x <= z) && (y <= z); }. #[short(type="meetSemilatticeType")] HB.structure Definition MeetSemilattice d := { T of POrder d T & POrder_isMeetSemilattice d T }. #[short(type="bMeetSemilatticeType")] HB.structure Definition BMeetSemilattice d := { T of MeetSemilattice d T & hasBottom d T }. #[short(type="tMeetSemilatticeType")] HB.structure Definition TMeetSemilattice d := { T of MeetSemilattice d T & hasTop d T }. #[short(type="tbMeetSemilatticeType")] HB.structure Definition TBMeetSemilattice d := { T of BMeetSemilattice d T & hasTop d T }. #[short(type="joinSemilatticeType")] HB.structure Definition JoinSemilattice d := { T of POrder d T & POrder_isJoinSemilattice d T }. #[short(type="bJoinSemilatticeType")] HB.structure Definition BJoinSemilattice d := { T of JoinSemilattice d T & hasBottom d T }. #[short(type="tJoinSemilatticeType")] HB.structure Definition TJoinSemilattice d := { T of JoinSemilattice d T & hasTop d T }. #[short(type="tbJoinSemilatticeType")] HB.structure Definition TBJoinSemilattice d := { T of BJoinSemilattice d T & hasTop d T }. #[short(type="latticeType")] HB.structure Definition Lattice d := { T of JoinSemilattice d T & POrder_isMeetSemilattice d T }. #[short(type="bLatticeType")] HB.structure Definition BLattice d := { T of Lattice d T & hasBottom d T }. #[short(type="tLatticeType")] HB.structure Definition TLattice d := { T of Lattice d T & hasTop d T }. #[short(type="tbLatticeType")] HB.structure Definition TBLattice d := { T of BLattice d T & hasTop d T }. Section LatticeDef. Context {disp : disp_t} {T : latticeType disp}. Variant lel_xor_gt (x y : T) : T -> T -> T -> T -> T -> T -> T -> T -> bool -> bool -> Set := | LelNotGt of x <= y : lel_xor_gt x y x x y y x x y y true false | GtlNotLe of y < x : lel_xor_gt x y y y x x y y x x false true. Variant ltl_xor_ge (x y : T) : T -> T -> T -> T -> T -> T -> T -> T -> bool -> bool -> Set := | LtlNotGe of x < y : ltl_xor_ge x y x x y y x x y y false true | GelNotLt of y <= x : ltl_xor_ge x y y y x x y y x x true false. Variant comparel (x y : T) : T -> T -> T -> T -> T -> T -> T -> T -> bool -> bool -> bool -> bool -> bool -> bool -> Set := | ComparelLt of x < y : comparel x y x x y y x x y y false false false true false true | ComparelGt of y < x : comparel x y y y x x y y x x false false true false true false | ComparelEq of x = y : comparel x y x x x x x x x x true true true true false false. Variant incomparel (x y : T) : T -> T -> T -> T -> T -> T -> T -> T -> bool -> bool -> bool -> bool -> bool -> bool -> bool -> bool -> Set := | InComparelLt of x < y : incomparel x y x x y y x x y y false false false true false true true true | InComparelGt of y < x : incomparel x y y y x x y y x x false false true false true false true true | InComparel of x >< y : incomparel x y x y y x (meet y x) (meet x y) (join y x) (join x y) false false false false false false false false | InComparelEq of x = y : incomparel x y x x x x x x x x true true true true false false true true. End LatticeDef. Module LatticeSyntax. Notation "x `&` y" := (meet x y) : order_scope. Notation "x `|` y" := (join x y) : order_scope. End LatticeSyntax. HB.export LatticeSyntax. Module BLatticeSyntax. Notation "\join_ ( i <- r | P ) F" := (\big[@join _ _ / \bot]_(i <- r | P%B) F%O) : order_scope. Notation "\join_ ( i <- r ) F" := (\big[@join _ _ / \bot]_(i <- r) F%O) : order_scope. Notation "\join_ ( i | P ) F" := (\big[@join _ _ / \bot]_(i | P%B) F%O) : order_scope. Notation "\join_ i F" := (\big[@join _ _ / \bot]_i F%O) : order_scope. Notation "\join_ ( i : I | P ) F" := (\big[@join _ _ / \bot]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\join_ ( i : I ) F" := (\big[@join _ _ / \bot]_(i : I) F%O) (only parsing) : order_scope. Notation "\join_ ( m <= i < n | P ) F" := (\big[@join _ _ / \bot]_(m <= i < n | P%B) F%O) : order_scope. Notation "\join_ ( m <= i < n ) F" := (\big[@join _ _ / \bot]_(m <= i < n) F%O) : order_scope. Notation "\join_ ( i < n | P ) F" := (\big[@join _ _ / \bot]_(i < n | P%B) F%O) : order_scope. Notation "\join_ ( i < n ) F" := (\big[@join _ _ / \bot]_(i < n) F%O) : order_scope. Notation "\join_ ( i 'in' A | P ) F" := (\big[@join _ _ / \bot]_(i in A | P%B) F%O) : order_scope. Notation "\join_ ( i 'in' A ) F" := (\big[@join _ _ / \bot]_(i in A) F%O) : order_scope. End BLatticeSyntax. HB.export BLatticeSyntax. Module TLatticeSyntax. Notation "\meet_ ( i <- r | P ) F" := (\big[meet / \top]_(i <- r | P%B) F%O) : order_scope. Notation "\meet_ ( i <- r ) F" := (\big[meet / \top]_(i <- r) F%O) : order_scope. Notation "\meet_ ( i | P ) F" := (\big[meet / \top]_(i | P%B) F%O) : order_scope. Notation "\meet_ i F" := (\big[meet / \top]_i F%O) : order_scope. Notation "\meet_ ( i : I | P ) F" := (\big[meet / \top]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\meet_ ( i : I ) F" := (\big[meet / \top]_(i : I) F%O) (only parsing) : order_scope. Notation "\meet_ ( m <= i < n | P ) F" := (\big[meet / \top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\meet_ ( m <= i < n ) F" := (\big[meet / \top]_(m <= i < n) F%O) : order_scope. Notation "\meet_ ( i < n | P ) F" := (\big[meet / \top]_(i < n | P%B) F%O) : order_scope. Notation "\meet_ ( i < n ) F" := (\big[meet / \top]_(i < n) F%O) : order_scope. Notation "\meet_ ( i 'in' A | P ) F" := (\big[meet / \top]_(i in A | P%B) F%O) : order_scope. Notation "\meet_ ( i 'in' A ) F" := (\big[meet / \top]_(i in A) F%O) : order_scope. End TLatticeSyntax. HB.export TLatticeSyntax. #[key="T", primitive] HB.mixin Record Lattice_isDistributive d (T : Type) of Lattice d T := { meetUl : @left_distributive T T meet join; joinIl : @left_distributive T T join meet; (* dual of meetUl *) }. #[short(type="distrLatticeType")] HB.structure Definition DistrLattice d := { T of Lattice_isDistributive d T & Lattice d T }. #[short(type="bDistrLatticeType")] HB.structure Definition BDistrLattice d := { T of DistrLattice d T & hasBottom d T }. #[short(type="tDistrLatticeType")] HB.structure Definition TDistrLattice d := { T of DistrLattice d T & hasTop d T }. #[short(type="tbDistrLatticeType")] HB.structure Definition TBDistrLattice d := { T of BDistrLattice d T & hasTop d T }. #[key="T", primitive] HB.mixin Record DistrLattice_isTotal d T of DistrLattice d T := { le_total : total (<=%O : rel T) }. #[short(type="orderType")] HB.structure Definition Total d := { T of DistrLattice_isTotal d T & DistrLattice d T }. #[short(type="bOrderType")] HB.structure Definition BTotal d := { T of Total d T & hasBottom d T }. #[short(type="tOrderType")] HB.structure Definition TTotal d := { T of Total d T & hasTop d T }. #[short(type="tbOrderType")] HB.structure Definition TBTotal d := { T of BTotal d T & hasTop d T }. #[key="T", primitive] HB.mixin Record DistrLattice_hasRelativeComplement d T of DistrLattice d T := { (* rcompl x y z is the complement of z in the interval [x, y]. *) rcompl : T -> T -> T -> T; rcomplPmeet : forall x y z, ((x `&` y) `|` z) `&` rcompl x y z = x `&` y; rcomplPjoin : forall x y z, ((y `|` x) `&` z) `|` rcompl x y z = y `|` x; }. #[short(type="cDistrLatticeType")] HB.structure Definition CDistrLattice d := { T of DistrLattice d T & DistrLattice_hasRelativeComplement d T }. #[key="T", primitive] HB.mixin Record CDistrLattice_hasSectionalComplement d T of CDistrLattice d T & hasBottom d T := { diff : T -> T -> T; (* FIXME: a bug in HB prevents us writing "rcompl \bot x y" *) diffErcompl : forall x y, diff x y = rcompl (\bot : T) x y; }. #[short(type="cbDistrLatticeType")] HB.structure Definition CBDistrLattice d := { T of CDistrLattice d T & hasBottom d T & CDistrLattice_hasSectionalComplement d T }. #[key="T", primitive] HB.mixin Record CDistrLattice_hasDualSectionalComplement d T of CDistrLattice d T & hasTop d T := { codiff : T -> T -> T; codiffErcompl : forall x y, codiff x y = rcompl x \top y; }. #[short(type="ctDistrLatticeType")] HB.structure Definition CTDistrLattice d := { T of CDistrLattice d T & hasTop d T & CDistrLattice_hasDualSectionalComplement d T }. Module Import CBDistrLatticeSyntax. Notation "x `\` y" := (diff x y) : order_scope. End CBDistrLatticeSyntax. #[key="T", primitive] HB.mixin Record CDistrLattice_hasComplement d T of CTDistrLattice d T & CBDistrLattice d T := { compl : T -> T; (* FIXME: a bug in HB prevents us writing "\top `\` x" and "codiff \bot x" *) complEdiff : forall x : T, compl x = (\top : T) `\` x; complEcodiff : forall x : T, compl x = codiff (\bot : T) x; }. #[short(type="ctbDistrLatticeType")] HB.structure Definition CTBDistrLattice d := { T of CBDistrLattice d T & CTDistrLattice d T & CDistrLattice_hasComplement d T }. Module Import CTBDistrLatticeSyntax. Notation "~` A" := (compl A) : order_scope. End CTBDistrLatticeSyntax. (**********) (* FINITE *) (**********) #[short(type="finPOrderType")] HB.structure Definition FinPOrder d := { T of Finite T & POrder d T }. #[short(type="finBPOrderType")] HB.structure Definition FinBPOrder d := { T of FinPOrder d T & hasBottom d T }. #[short(type="finTPOrderType")] HB.structure Definition FinTPOrder d := { T of FinPOrder d T & hasTop d T }. #[short(type="finTBPOrderType")] HB.structure Definition FinTBPOrder d := { T of FinBPOrder d T & hasTop d T }. #[short(type="finMeetSemilatticeType")] HB.structure Definition FinMeetSemilattice d := { T of Finite T & MeetSemilattice d T }. #[short(type="finBMeetSemilatticeType")] HB.structure Definition FinBMeetSemilattice d := { T of Finite T & BMeetSemilattice d T }. #[short(type="finJoinSemilatticeType")] HB.structure Definition FinJoinSemilattice d := { T of Finite T & JoinSemilattice d T }. #[short(type="finTJoinSemilatticeType")] HB.structure Definition FinTJoinSemilattice d := { T of Finite T & TJoinSemilattice d T }. #[short(type="finLatticeType")] HB.structure Definition FinLattice d := { T of Finite T & Lattice d T }. #[short(type="finTBLatticeType")] HB.structure Definition FinTBLattice d := { T of Finite T & TBLattice d T }. #[short(type="finDistrLatticeType")] HB.structure Definition FinDistrLattice d := { T of Finite T & DistrLattice d T }. #[short(type="finTBDistrLatticeType")] HB.structure Definition FinTBDistrLattice d := { T of Finite T & TBDistrLattice d T }. #[short(type="finOrderType")] HB.structure Definition FinTotal d := { T of Finite T & Total d T }. #[short(type="finTBOrderType")] HB.structure Definition FinTBTotal d := { T of Finite T & TBTotal d T }. #[short(type="finCDistrLatticeType")] HB.structure Definition FinCDistrLattice d := { T of Finite T & CDistrLattice d T }. #[short(type="finCTBDistrLatticeType")] HB.structure Definition FinCTBDistrLattice d := { T of Finite T & CTBDistrLattice d T }. (********) (* DUAL *) (********) Notation dual_meet := (@meet (dual_display _) _). Notation dual_join := (@join (dual_display _) _). Module Import DualSyntax. Notation "x `&^d` y" := (dual_meet x y) : order_scope. Notation "x `|^d` y" := (dual_join x y) : order_scope. (* The following Local Notations are here to define the \join^d_ and \meet^d_ *) (* notations later. Do not remove them. *) Local Notation "\bot" := dual_bottom. Local Notation "\top" := dual_top. Local Notation join := dual_join. Local Notation meet := dual_meet. Local Notation min := dual_min. Local Notation max := dual_max. Notation "\join^d_ ( i <- r | P ) F" := (\big[join / \bot]_(i <- r | P%B) F%O) : order_scope. Notation "\join^d_ ( i <- r ) F" := (\big[join / \bot]_(i <- r) F%O) : order_scope. Notation "\join^d_ ( i | P ) F" := (\big[join / \bot]_(i | P%B) F%O) : order_scope. Notation "\join^d_ i F" := (\big[join / \bot]_i F%O) : order_scope. Notation "\join^d_ ( i : I | P ) F" := (\big[join / \bot]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\join^d_ ( i : I ) F" := (\big[join / \bot]_(i : I) F%O) (only parsing) : order_scope. Notation "\join^d_ ( m <= i < n | P ) F" := (\big[join / \bot]_(m <= i < n | P%B) F%O) : order_scope. Notation "\join^d_ ( m <= i < n ) F" := (\big[join / \bot]_(m <= i < n) F%O) : order_scope. Notation "\join^d_ ( i < n | P ) F" := (\big[join / \bot]_(i < n | P%B) F%O) : order_scope. Notation "\join^d_ ( i < n ) F" := (\big[join / \bot]_(i < n) F%O) : order_scope. Notation "\join^d_ ( i 'in' A | P ) F" := (\big[join / \bot]_(i in A | P%B) F%O) : order_scope. Notation "\join^d_ ( i 'in' A ) F" := (\big[join / \bot]_(i in A) F%O) : order_scope. Notation "\meet^d_ ( i <- r | P ) F" := (\big[meet / \top]_(i <- r | P%B) F%O) : order_scope. Notation "\meet^d_ ( i <- r ) F" := (\big[meet / \top]_(i <- r) F%O) : order_scope. Notation "\meet^d_ ( i | P ) F" := (\big[meet / \top]_(i | P%B) F%O) : order_scope. Notation "\meet^d_ i F" := (\big[meet / \top]_i F%O) : order_scope. Notation "\meet^d_ ( i : I | P ) F" := (\big[meet / \top]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\meet^d_ ( i : I ) F" := (\big[meet / \top]_(i : I) F%O) (only parsing) : order_scope. Notation "\meet^d_ ( m <= i < n | P ) F" := (\big[meet / \top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\meet^d_ ( m <= i < n ) F" := (\big[meet / \top]_(m <= i < n) F%O) : order_scope. Notation "\meet^d_ ( i < n | P ) F" := (\big[meet / \top]_(i < n | P%B) F%O) : order_scope. Notation "\meet^d_ ( i < n ) F" := (\big[meet / \top]_(i < n) F%O) : order_scope. Notation "\meet^d_ ( i 'in' A | P ) F" := (\big[meet / \top]_(i in A | P%B) F%O) : order_scope. Notation "\meet^d_ ( i 'in' A ) F" := (\big[meet / \top]_(i in A) F%O) : order_scope. Notation "\meet^d_ ( i <- r | P ) F" := (\big[meet / \top]_(i <- r | P%B) F%O) : order_scope. Notation "\meet^d_ ( i <- r ) F" := (\big[meet / \top]_(i <- r) F%O) : order_scope. Notation "\meet^d_ ( i | P ) F" := (\big[meet / \top]_(i | P%B) F%O) : order_scope. Notation "\meet^d_ i F" := (\big[meet / \top]_i F%O) : order_scope. Notation "\meet^d_ ( i : I | P ) F" := (\big[meet / \top]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\meet^d_ ( i : I ) F" := (\big[meet / \top]_(i : I) F%O) (only parsing) : order_scope. Notation "\meet^d_ ( m <= i < n | P ) F" := (\big[meet / \top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\meet^d_ ( m <= i < n ) F" := (\big[meet / \top]_(m <= i < n) F%O) : order_scope. Notation "\meet^d_ ( i < n | P ) F" := (\big[meet / \top]_(i < n | P%B) F%O) : order_scope. Notation "\meet^d_ ( i < n ) F" := (\big[meet / \top]_(i < n) F%O) : order_scope. Notation "\meet^d_ ( i 'in' A | P ) F" := (\big[meet / \top]_(i in A | P%B) F%O) : order_scope. Notation "\meet^d_ ( i 'in' A ) F" := (\big[meet / \top]_(i in A) F%O) : order_scope. Notation "\min^d_ i F" := (\big[min/top]_i F) : order_scope. Notation "\min^d_ ( i <- r | P ) F" := (\big[min/top]_(i <- r | P%B) F%O) : order_scope. Notation "\min^d_ ( i < r ) F" := (\big[min/top]_(i <- r) F%O) : order_scope. Notation "\min^d_ ( m <= i < n | P ) F" := (\big[min/top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\min^d_ ( m <= i < n ) F" := (\big[min/top]_(m <= i < n) F%O) : order_scope. Notation "\min^d_ ( i | P ) F" := (\big[min/top]_(i | P%B) F%O) : order_scope. Notation "\min^d_ ( i : t | P ) F" := (\big[min/top]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\min^d_ ( i : t ) F" := (\big[min/top]_(i : t) F%O) (only parsing) : order_scope. Notation "\min^d_ ( i < n | P ) F" := (\big[min/top]_(i < n | P%B) F%O) : order_scope. Notation "\min^d_ ( i < n ) F" := (\big[min/top]_(i < n) F%O) : order_scope. Notation "\min^d_ ( i 'in' A | P ) F" := (\big[min/top]_(i in A | P%B) F%O) : order_scope. Notation "\min^d_ ( i 'in' A ) F" := (\big[min/top]_(i in A) F%O) : order_scope. Notation "\max^d_ i F" := (\big[max/bottom]_i F%O) : order_scope. Notation "\max^d_ ( i <- r | P ) F" := (\big[max/bottom]_(i <- r | P%B) F%O) : order_scope. Notation "\max^d_ ( i < r ) F" := (\big[max/bottom]_(i <- r) F%O) : order_scope. Notation "\max^d_ ( m <= i < n | P ) F" := (\big[max/bottom]_(m <= i < n | P%B) F%O) : order_scope. Notation "\max^d_ ( m <= i < n ) F" := (\big[max/bottom]_(m <= i < n) F%O) : order_scope. Notation "\max^d_ ( i | P ) F" := (\big[max/bottom]_(i | P%B) F%O) : order_scope. Notation "\max^d_ ( i : t | P ) F" := (\big[max/bottom]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\max^d_ ( i : t ) F" := (\big[max/bottom]_(i : t) F%O) (only parsing) : order_scope. Notation "\max^d_ ( i < n | P ) F" := (\big[max/bottom]_(i < n | P%B) F%O) : order_scope. Notation "\max^d_ ( i < n ) F" := (\big[max/bottom]_(i < n) F%O) : order_scope. Notation "\max^d_ ( i 'in' A | P ) F" := (\big[max/bottom]_(i in A | P%B) F%O) : order_scope. Notation "\max^d_ ( i 'in' A ) F" := (\big[max/bottom]_(i in A) F%O) : order_scope. End DualSyntax. (* FIXME: we have two issues in the dual instance declarations in the DualOrder module below: 1. HB.saturate is slow, and 2. if we declare them by HB.instance, some declarations fail because it unfolds [dual] and the generated instance does not typecheck (math-comp/hierarchy-builder#257). *) Module DualOrder. HB.instance Definition _ (d : disp_t) (T : porderType d) := Preorder_isDuallyPOrder.Build (dual_display d) T^d ge_anti le_anti. HB.instance Definition _ d (T : joinSemilatticeType d) := POrder_isMeetSemilattice.Build (dual_display d) T^d (fun x y z => leUx y z x). Lemma meetEdual d (T : joinSemilatticeType d) (x y : T) : ((x : T^d) `&^d` y) = (x `|` y). Proof. by []. Qed. HB.instance Definition _ d (T : meetSemilatticeType d) := POrder_isJoinSemilattice.Build (dual_display d) T^d (fun x y z => lexI z x y). Lemma joinEdual d (T : meetSemilatticeType d) (x y : T) : ((x : T^d) `|^d` y) = (x `&` y). Proof. by []. Qed. HB.saturate. HB.instance Definition _ d (T : distrLatticeType d) := Lattice_isDistributive.Build (dual_display d) T^d joinIl meetUl. HB.instance Definition _ d (T : orderType d) := DistrLattice_isTotal.Build (dual_display d) T^d (fun x y => le_total y x). HB.saturate. HB.instance Definition _ d (T : cDistrLatticeType d) := DistrLattice_hasRelativeComplement.Build (dual_display d) T^d (fun x y => rcomplPjoin y x) (fun x y => rcomplPmeet y x). HB.instance Definition _ d (T : ctDistrLatticeType d) := CDistrLattice_hasSectionalComplement.Build (dual_display d) T^d codiffErcompl. HB.instance Definition _ d (T : cbDistrLatticeType d) := CDistrLattice_hasDualSectionalComplement.Build (dual_display d) T^d diffErcompl. HB.instance Definition _ d (T : ctbDistrLatticeType d) := CDistrLattice_hasComplement.Build (dual_display d) T^d complEcodiff complEdiff. HB.saturate. End DualOrder. HB.export DualOrder. (**********) (* THEORY *) (**********) Module Import POrderTheory. Include PreorderTheory. Section POrderTheory. Context {disp : disp_t} {T : porderType disp}. Implicit Types (x y : T) (s : seq T). Lemma le_anti: antisymmetric (<=%O : rel T). Proof. exact: le_anti. Qed. Lemma ge_anti: antisymmetric (>=%O : rel T). Proof. by move=> x y /le_anti. Qed. Lemma eq_le x y: (x == y) = (x <= y <= x). Proof. by apply/eqP/idP => [->|/le_anti]; rewrite ?lexx. Qed. Lemma lt_def x y : (x < y) = (y != x) && (x <= y). Proof. rewrite andbC lt_le_def; case/boolP: (x <= y) => //= xy. congr negb; apply/idP/eqP => [yx|->]; last exact/lexx. by apply/le_anti; rewrite yx. Qed. Lemma lt_neqAle x y: (x < y) = (x != y) && (x <= y). Proof. by rewrite lt_def eq_sym. Qed. Lemma le_eqVlt x y: (x <= y) = (x == y) || (x < y). Proof. by rewrite lt_neqAle; case: eqP => //= ->; rewrite lexx. Qed. Definition lte_anti := (=^~ eq_le, @lt_asym disp T, @lt_le_asym disp T, @le_lt_asym disp T). Lemma lt_sorted_uniq_le s : sorted <%O s = uniq s && sorted <=%O s. Proof. rewrite le_sorted_pairwise lt_sorted_pairwise uniq_pairwise -pairwise_relI. by apply/eq_pairwise => ? ?; rewrite lt_neqAle. Qed. Lemma le_sorted_eq s1 s2 : sorted <=%O s1 -> sorted <=%O s2 -> perm_eq s1 s2 -> s1 = s2. Proof. exact/sorted_eq/le_anti/le_trans. Qed. Lemma count_lt_le_mem x s : (count (< x) s < count (<= x) s)%N = (x \in s). Proof. have := count_predUI (pred1 x) (< x) s. have -> : count (predI (pred1 x) (< x)) s = 0%N. rewrite (@eq_count _ _ pred0) ?count_pred0 // => y /=. by rewrite lt_neqAle; case: eqP => //= ->; rewrite eqxx. have /eq_count-> : [predU1 x & < x] =1 (<= x) by move=> y /=; rewrite le_eqVlt. by rewrite addn0 => ->; rewrite -add1n leq_add2r -has_count has_pred1. Qed. Lemma comparable_ltgtP x y : x >=< y -> compare x y (min y x) (min x y) (max y x) (max x y) (y == x) (x == y) (x >= y) (x <= y) (x > y) (x < y). Proof. rewrite /min /max />=<%O !le_eqVlt [y == x]eq_sym. have := (eqVneq x y, (boolP (x < y), boolP (y < x))). move=> [[->//|neq_xy /=] [[] xy [] //=]] ; do ?by rewrite ?ltxx; constructor. by rewrite ltxx in xy. by rewrite le_gtF // ltW. Qed. Lemma comparable_leP x y : x >=< y -> le_xor_gt x y (min y x) (min x y) (max y x) (max x y) (x <= y) (y < x). Proof. by move=> /comparable_ltgtP [?|?|->]; constructor; rewrite // ltW. Qed. Lemma comparable_ltP x y : x >=< y -> lt_xor_ge x y (min y x) (min x y) (max y x) (max x y) (y <= x) (x < y). Proof. by move=> /comparable_ltgtP [?|?|->]; constructor; rewrite // ltW. Qed. Lemma comparableP x y : incompare x y (min y x) (min x y) (max y x) (max x y) (y == x) (x == y) (x >= y) (x <= y) (x > y) (x < y) (y >=< x) (x >=< y). Proof. rewrite ![y >=< _]comparable_sym; have [c_xy|i_xy] := boolP (x >=< y). by case: (comparable_ltgtP c_xy) => ?; constructor. by rewrite /min /max ?incomparable_eqF ?incomparable_leF; rewrite ?incomparable_ltF// 1?comparable_sym //; constructor. Qed. (* leif *) Lemma leifP x y C : reflect (x <= y ?= iff C) (if C then x == y else x < y). Proof. rewrite /leif le_eqVlt; apply: (iffP idP)=> [|[]]. by case: C => [/eqP->|lxy]; rewrite ?eqxx // lxy lt_eqF. by move=> /orP[/eqP->|lxy] <-; rewrite ?eqxx // lt_eqF. Qed. Lemma leif_trans x1 x2 x3 C12 C23 : x1 <= x2 ?= iff C12 -> x2 <= x3 ?= iff C23 -> x1 <= x3 ?= iff C12 && C23. Proof. move=> ltx12 ltx23; apply/leifP; rewrite -ltx12. case eqx12: (x1 == x2). by rewrite (eqP eqx12) lt_neqAle !ltx23 andbT; case C23. by rewrite (@lt_le_trans _ _ x2) ?ltx23 // lt_neqAle eqx12 ltx12. Qed. Lemma leif_le x y : x <= y -> x <= y ?= iff (x >= y). Proof. by move=> lexy; split=> //; rewrite eq_le lexy. Qed. Lemma leif_eq x y : x <= y -> x <= y ?= iff (x == y). Proof. by []. Qed. Lemma ge_leif x y C : x <= y ?= iff C -> (y <= x) = C. Proof. by case=> le_xy; rewrite eq_le le_xy. Qed. Lemma lt_leif x y C : x <= y ?= iff C -> (x < y) = ~~ C. Proof. by move=> le_xy; rewrite lt_neqAle !le_xy andbT. Qed. Lemma ltNleif x y C : x <= y ?= iff ~~ C -> (x < y) = C. Proof. by move=> /lt_leif; rewrite negbK. Qed. (* lteif *) Lemma lteif_anti C1 C2 x y : (x < y ?<= if C1) && (y < x ?<= if C2) = C1 && C2 && (x == y). Proof. by case: C1 C2 => [][]; rewrite lte_anti. Qed. Lemma lteifN C x y : x < y ?<= if ~~ C -> ~~ (y < x ?<= if C). Proof. by case: C => /=; case: comparableP. Qed. (* min and max *) Lemma minEle x y : min x y = if x <= y then x else y. Proof. by case: comparableP. Qed. Lemma maxEle x y : max x y = if x <= y then y else x. Proof. by case: comparableP. Qed. Lemma comparable_minEgt x y : x >=< y -> min x y = if x > y then y else x. Proof. by case: comparableP. Qed. Lemma comparable_maxEgt x y : x >=< y -> max x y = if x > y then x else y. Proof. by case: comparableP. Qed. Lemma comparable_minEge x y : x >=< y -> min x y = if x >= y then y else x. Proof. by case: comparableP. Qed. Lemma comparable_maxEge x y : x >=< y -> max x y = if x >= y then x else y. Proof. by case: comparableP. Qed. Lemma min_l x y : x <= y -> min x y = x. Proof. by case: comparableP. Qed. Lemma min_r x y : y <= x -> min x y = y. Proof. by case: comparableP. Qed. Lemma max_l x y : y <= x -> max x y = x. Proof. by case: comparableP. Qed. Lemma max_r x y : x <= y -> max x y = y. Proof. by case: comparableP. Qed. Lemma eq_minl x y : (min x y == x) = (x <= y). Proof. by rewrite !(fun_if, if_arg) eqxx; case: comparableP. Qed. Lemma eq_maxr x y : (max x y == y) = (x <= y). Proof. by rewrite !(fun_if, if_arg) eqxx; case: comparableP. Qed. Lemma min_idPl x y : reflect (min x y = x) (x <= y). Proof. by rewrite -eq_minl; apply/eqP. Qed. Lemma max_idPr x y : reflect (max x y = y) (x <= y). Proof. by rewrite -eq_maxr; apply/eqP. Qed. Section Comparable2. Context (z x y : T) (cmp_xy : x >=< y). Lemma comparable_minC : min x y = min y x. Proof. by case: comparableP cmp_xy. Qed. Lemma comparable_maxC : max x y = max y x. Proof. by case: comparableP cmp_xy. Qed. Lemma comparable_eq_minr : (min x y == y) = (y <= x). Proof. by rewrite !(fun_if, if_arg) eqxx; case: comparableP cmp_xy. Qed. Lemma comparable_eq_maxl : (max x y == x) = (y <= x). Proof. by rewrite !(fun_if, if_arg) eqxx; case: comparableP cmp_xy. Qed. Lemma comparable_min_idPr : reflect (min x y = y) (y <= x). Proof. by rewrite -comparable_eq_minr; apply/eqP. Qed. Lemma comparable_max_idPl : reflect (max x y = x) (y <= x). Proof. by rewrite -comparable_eq_maxl; apply/eqP. Qed. Lemma comparable_lteifNE C : x >=< y -> x < y ?<= if ~~ C = ~~ (y < x ?<= if C). Proof. by case: C => /=; case: comparableP. Qed. End Comparable2. Section Comparable3. Context (x y z : T) (cmp_xy : x >=< y) (cmp_xz : x >=< z) (cmp_yz : y >=< z). Let P := comparableP. Lemma comparable_max_minl : max (min x y) z = min (max x z) (max y z). Proof. move: cmp_xy cmp_xz cmp_yz; rewrite !(fun_if, if_arg)/=. move: (P x y) (P x z) (P y z). move=> [xy|xy|xy|<-] [xz|xz|xz|<-] [yz|yz|yz|//->]//= _; rewrite ?ltxx//. - by have := lt_trans xy (lt_trans yz xz); rewrite ltxx. - by have := lt_trans xy (lt_trans xz yz); rewrite ltxx. Qed. End Comparable3. Section Comparable4. Context (x y z w : T) (cmp_xy : x >=< y) (cmp_zw : z >=< w). Lemma comparable_le_min2 : x <= z -> y <= w -> Order.min x y <= Order.min z w. Proof. move: cmp_xy cmp_zw => /comparable_leP[] xy /comparable_leP[] zw // xz yw. - exact: le_trans xy yw. - exact: le_trans (ltW xy) xz. Qed. Lemma comparable_le_max2 : x <= z -> y <= w -> Order.max x y <= Order.max z w. Proof. move: cmp_xy cmp_zw => /comparable_leP[] xy /comparable_leP[] zw // xz yw. - exact: le_trans yw (ltW zw). - exact: le_trans xz zw. Qed. End Comparable4. Lemma comparable_minAC x y z : x >=< y -> x >=< z -> y >=< z -> min (min x y) z = min (min x z) y. Proof. move=> xy xz yz; rewrite -comparable_minA// [min y z]comparable_minC//. by rewrite comparable_minA// 1?comparable_sym. Qed. Lemma comparable_maxAC x y z : x >=< y -> x >=< z -> y >=< z -> max (max x y) z = max (max x z) y. Proof. move=> xy xz yz; rewrite -comparable_maxA// [max y z]comparable_maxC//. by rewrite comparable_maxA// 1?comparable_sym. Qed. Lemma comparable_minCA x y z : x >=< y -> x >=< z -> y >=< z -> min x (min y z) = min y (min x z). Proof. move=> xy xz yz; rewrite comparable_minA// [min x y]comparable_minC//. by rewrite -comparable_minA// 1?comparable_sym. Qed. Lemma comparable_maxCA x y z : x >=< y -> x >=< z -> y >=< z -> max x (max y z) = max y (max x z). Proof. move=> xy xz yz; rewrite comparable_maxA// [max x y]comparable_maxC//. by rewrite -comparable_maxA// 1?comparable_sym. Qed. Lemma comparable_minACA x y z t : x >=< y -> x >=< z -> x >=< t -> y >=< z -> y >=< t -> z >=< t -> min (min x y) (min z t) = min (min x z) (min y t). Proof. move=> xy xz xt yz yt zt; rewrite comparable_minA// ?comparable_minl//. rewrite [min _ z]comparable_minAC// -comparable_minA// ?comparable_minl//. by rewrite inE comparable_sym. Qed. Lemma comparable_maxACA x y z t : x >=< y -> x >=< z -> x >=< t -> y >=< z -> y >=< t -> z >=< t -> max (max x y) (max z t) = max (max x z) (max y t). Proof. move=> xy xz xt yz yt zt; rewrite comparable_maxA// ?comparable_maxl//. rewrite [max _ z]comparable_maxAC// -comparable_maxA// ?comparable_maxl//. by rewrite inE comparable_sym. Qed. Lemma comparable_min_maxr x y z : x >=< y -> x >=< z -> y >=< z -> min x (max y z) = max (min x y) (min x z). Proof. move=> xy xz yz; rewrite ![min x _]comparable_minC// ?comparable_maxr//. by rewrite comparable_min_maxl// 1?comparable_sym. Qed. (* monotonicity *) Lemma mono_in_leif (A : {pred T}) (f : T -> T) C : {in A &, {mono f : x y / x <= y}} -> {in A &, forall x y, (f x <= f y ?= iff C) = (x <= y ?= iff C)}. Proof. by move=> mf x y Ax Ay; rewrite /leif !eq_le !mf. Qed. Lemma mono_leif (f : T -> T) C : {mono f : x y / x <= y} -> forall x y, (f x <= f y ?= iff C) = (x <= y ?= iff C). Proof. by move=> mf x y; rewrite /leif !eq_le !mf. Qed. Lemma nmono_in_leif (A : {pred T}) (f : T -> T) C : {in A &, {mono f : x y /~ x <= y}} -> {in A &, forall x y, (f x <= f y ?= iff C) = (y <= x ?= iff C)}. Proof. by move=> mf x y Ax Ay; rewrite /leif !eq_le !mf. Qed. Lemma nmono_leif (f : T -> T) C : {mono f : x y /~ x <= y} -> forall x y, (f x <= f y ?= iff C) = (y <= x ?= iff C). Proof. by move=> mf x y; rewrite /leif !eq_le !mf. Qed. Section bigminmax. Context (I : Type) (r : seq I) (f : I -> T) (x0 x : T) (P : pred I). Lemma bigmax_le : x0 <= x -> (forall i, P i -> f i <= x) -> \big[max/x0]_(i <- r | P i) f i <= x. Proof. by move=> ? ?; elim/big_ind: _ => // *; rewrite maxEle; case: ifPn. Qed. Lemma le_bigmin : x <= x0 -> (forall i, P i -> x <= f i) -> x <= \big[min/x0]_(i <- r | P i) f i. Proof. by move=> ? ?; elim/big_ind: _ => // *; rewrite minEle; case: ifPn. Qed. End bigminmax. End POrderTheory. #[global] Hint Resolve comparable_minr comparable_minl : core. #[global] Hint Resolve comparable_maxr comparable_maxl : core. Section ContraTheory. Context {disp1 disp2 : disp_t} {T1 : porderType disp1} {T2 : porderType disp2}. Implicit Types (x y : T1) (z t : T2) (b : bool) (m n : nat) (P : Prop). Lemma contra_leT b x y : (~~ b -> x < y) -> (y <= x -> b). Proof. by case: comparableP; case: b. Qed. Lemma contra_ltT b x y : (~~ b -> x <= y) -> (y < x -> b). Proof. by case: comparableP; case: b. Qed. Lemma contra_leN b x y : (b -> x < y) -> (y <= x -> ~~ b). Proof. by case: comparableP; case: b. Qed. Lemma contra_ltN b x y : (b -> x <= y) -> (y < x -> ~~ b). Proof. by case: comparableP; case: b. Qed. Lemma contra_le_not P x y : (P -> x < y) -> (y <= x -> ~ P). Proof. by case: comparableP => // _ PF _ /PF. Qed. Lemma contra_lt_not P x y : (P -> x <= y) -> (y < x -> ~ P). Proof. by case: comparableP => // _ PF _ /PF. Qed. Lemma contra_leF b x y : (b -> x < y) -> (y <= x -> b = false). Proof. by case: comparableP; case: b => // _ /implyP. Qed. Lemma contra_ltF b x y : (b -> x <= y) -> (y < x -> b = false). Proof. by case: comparableP; case: b => // _ /implyP. Qed. Lemma contra_le_leq x y m n : ((n < m)%N -> y < x) -> (x <= y -> (m <= n)%N). Proof. by case: comparableP; case: ltngtP. Qed. Lemma contra_le_ltn x y m n : ((n <= m)%N -> y < x) -> (x <= y -> (m < n)%N). Proof. by case: comparableP; case: ltngtP. Qed. Lemma contra_lt_leq x y m n : ((n < m)%N -> y <= x) -> (x < y -> (m <= n)%N). Proof. by case: comparableP; case: ltngtP. Qed. Lemma contra_lt_ltn x y m n : ((n <= m)%N -> y <= x) -> (x < y -> (m < n)%N). Proof. by case: comparableP; case: ltngtP. Qed. End ContraTheory. Section POrderMonotonyTheory. Context {disp disp' : disp_t} {T : porderType disp} {T' : porderType disp'}. Context (D D' : {pred T}) (f : T -> T'). Let leT_anti := @le_anti _ T. Hint Resolve lexx lt_neqAle : core. Let ge_antiT : antisymmetric (>=%O : rel T). Proof. by move=> ? ? /le_anti. Qed. Lemma ltW_homo : {homo f : x y / x < y} -> {homo f : x y / x <= y}. Proof. exact: homoW. Qed. Lemma ltW_nhomo : {homo f : x y /~ x < y} -> {homo f : x y /~ x <= y}. Proof. by apply: homoW=> // x y; rewrite eq_sym. Qed. Lemma inj_homo_lt : injective f -> {homo f : x y / x <= y} -> {homo f : x y / x < y}. Proof. exact: inj_homo. Qed. Lemma inj_nhomo_lt : injective f -> {homo f : x y /~ x <= y} -> {homo f : x y /~ x < y}. Proof. by apply: inj_homo=> // x y; rewrite eq_sym. Qed. Lemma inc_inj : {mono f : x y / x <= y} -> injective f. Proof. exact: mono_inj. Qed. Lemma dec_inj : {mono f : x y /~ x <= y} -> injective f. Proof. exact: mono_inj. Qed. (* Monotony in D D' *) Lemma ltW_homo_in : {in D & D', {homo f : x y / x < y}} -> {in D & D', {homo f : x y / x <= y}}. Proof. exact: homoW_in. Qed. Lemma ltW_nhomo_in : {in D & D', {homo f : x y /~ x < y}} -> {in D & D', {homo f : x y /~ x <= y}}. Proof. by apply: homoW_in=> // x y; rewrite eq_sym. Qed. Lemma inj_homo_lt_in : {in D & D', injective f} -> {in D & D', {homo f : x y / x <= y}} -> {in D & D', {homo f : x y / x < y}}. Proof. exact: inj_homo_in. Qed. Lemma inj_nhomo_lt_in : {in D & D', injective f} -> {in D & D', {homo f : x y /~ x <= y}} -> {in D & D', {homo f : x y /~ x < y}}. Proof. by apply: inj_homo_in=> // x y; rewrite eq_sym. Qed. Lemma inc_inj_in : {in D &, {mono f : x y / x <= y}} -> {in D &, injective f}. Proof. exact: mono_inj_in. Qed. Lemma dec_inj_in : {in D &, {mono f : x y /~ x <= y}} -> {in D &, injective f}. Proof. exact: mono_inj_in. Qed. End POrderMonotonyTheory. End POrderTheory. Arguments leifP {disp T x y C}. Arguments mono_in_leif [disp T A f C]. Arguments nmono_in_leif [disp T A f C]. Arguments mono_leif [disp T f C]. Arguments nmono_leif [disp T f C]. Arguments min_idPl {disp T x y}. Arguments max_idPr {disp T x y}. Arguments comparable_min_idPr {disp T x y _}. Arguments comparable_max_idPl {disp T x y _}. Module Import BPOrderTheory. Export BPreorderTheory. Section BPOrderTheory. Context {disp : disp_t} {T : bPOrderType disp}. Implicit Types (x y : T). Lemma lex0 x : (x <= \bot) = (x == \bot). Proof. by rewrite le_eqVlt ltx0 orbF. Qed. Lemma lt0x x : (\bot < x) = (x != \bot). Proof. by rewrite lt_def le0x andbT. Qed. Variant eq0_xor_gt0 x : bool -> bool -> Set := Eq0NotPOs : x = \bot -> eq0_xor_gt0 x true false | POsNotEq0 : \bot < x -> eq0_xor_gt0 x false true. Lemma posxP x : eq0_xor_gt0 x (x == \bot) (\bot < x). Proof. by rewrite lt0x; have [] := eqVneq; constructor; rewrite ?lt0x. Qed. End BPOrderTheory. End BPOrderTheory. Module Import TPOrderTheory. Section TPOrderTheory. Context {disp : disp_t} {T : tPOrderType disp}. Implicit Types (x y : T). Lemma le1x x : (\top <= x) = (x == \top). Proof. exact: (@lex0 _ T^d). Qed. Lemma ltx1 x : (x < \top) = (x != \top). Proof. exact: (@lt0x _ T^d). Qed. End TPOrderTheory. End TPOrderTheory. Module Import MeetTheory. Section MeetTheory. Context {disp : disp_t} {L : meetSemilatticeType disp}. Implicit Types (x y : L). (* interaction with order *) Lemma lexI x y z : (x <= y `&` z) = (x <= y) && (x <= z). Proof. exact: lexI. Qed. Lemma leIr x y : y `&` x <= x. Proof. by have:= le_refl (meet y x); rewrite lexI => /andP []. Qed. Lemma leIl x y : x `&` y <= x. Proof. by have:= le_refl (meet x y); rewrite lexI => /andP []. Qed. Lemma leIxl x y z : y <= x -> y `&` z <= x. Proof. exact/le_trans/leIl. Qed. Lemma leIxr x y z : z <= x -> y `&` z <= x. Proof. exact/le_trans/leIr. Qed. Lemma leIx2 x y z : (y <= x) || (z <= x) -> y `&` z <= x. Proof. by case/orP => [/leIxl|/leIxr]. Qed. Lemma leEmeet x y : (x <= y) = (x `&` y == x). Proof. by rewrite eq_le lexI leIl lexx. Qed. Lemma eq_meetl x y : (x `&` y == x) = (x <= y). Proof. by apply/esym/leEmeet. Qed. Lemma eq_meetr x y : (x `&` y == y) = (y <= x). Proof. by rewrite eq_le lexI leIr lexx andbT. Qed. Lemma meet_idPl {x y} : reflect (x `&` y = x) (x <= y). Proof. by rewrite -eq_meetl; apply/eqP. Qed. Lemma meet_idPr {x y} : reflect (y `&` x = x) (x <= y). Proof. by rewrite -eq_meetr; apply/eqP. Qed. Lemma meet_l x y : x <= y -> x `&` y = x. Proof. exact/meet_idPl. Qed. Lemma meet_r x y : y <= x -> x `&` y = y. Proof. exact/meet_idPr. Qed. Lemma leIidl x y : (x <= x `&` y) = (x <= y). Proof. by rewrite lexI lexx. Qed. Lemma leIidr x y : (x <= y `&` x) = (x <= y). Proof. by rewrite lexI lexx andbT. Qed. Lemma leI2 x y z t : x <= z -> y <= t -> x `&` y <= z `&` t. Proof. by move=> xz yt; rewrite lexI !leIx2 ?xz ?yt ?orbT //. Qed. (* algebraic properties *) Lemma meetC : commutative (@meet _ L). Proof. by move=> x y; apply: le_anti; rewrite !lexI !leIr !leIl. Qed. Lemma meetA : associative (@meet _ L). Proof. move=> x y z; apply: le_anti. rewrite !lexI leIr leIl /= andbT -andbA. rewrite ![_ `&` (_ `&` _) <= _]leIxr ?(leIr, leIl) //=. by rewrite leIxl ?leIl // leIxl // leIr. Qed. HB.instance Definition _ := SemiGroup.isComLaw.Build L meet meetA meetC. Lemma meetxx : idempotent_op (@meet _ L). Proof. by move=> x; apply/eqP; rewrite -leEmeet. Qed. Lemma meetAC : right_commutative (@meet _ L). Proof. by move=> x y z; rewrite -!meetA [X in _ `&` X]meetC. Qed. Lemma meetCA : left_commutative (@meet _ L). Proof. by move=> x y z; rewrite !meetA [X in X `&` _]meetC. Qed. Lemma meetACA : interchange (@meet _ L) (@meet _ L). Proof. by move=> x y z t; rewrite !meetA [X in X `&` _]meetAC. Qed. Lemma meetKI y x : x `&` (x `&` y) = x `&` y. Proof. by rewrite meetA meetxx. Qed. Lemma meetIK y x : (x `&` y) `&` y = x `&` y. Proof. by rewrite -meetA meetxx. Qed. Lemma meetKIC y x : x `&` (y `&` x) = x `&` y. Proof. by rewrite meetC meetIK meetC. Qed. Lemma meetIKC y x : y `&` x `&` y = x `&` y. Proof. by rewrite meetAC meetC meetxx. Qed. End MeetTheory. End MeetTheory. Arguments meet_idPl {disp L x y}. Arguments meet_idPr {disp L x y}. Module Import BMeetTheory. Section BMeetTheory. Context {disp : disp_t} {L : bMeetSemilatticeType disp}. Lemma meet0x : left_zero \bot (@meet _ L). Proof. by move=> x; apply/eqP; rewrite -leEmeet. Qed. Lemma meetx0 : right_zero \bot (@meet _ L). Proof. by move=> x; rewrite meetC meet0x. Qed. HB.instance Definition _ := Monoid.isMulLaw.Build L \bot meet meet0x meetx0. End BMeetTheory. End BMeetTheory. Module Import TMeetTheory. Section TMeetTheory. Context {disp : disp_t} {L : tMeetSemilatticeType disp}. Implicit Types (I : finType) (T : eqType) (x y : L). Lemma meetx1 : right_id \top (@meet _ L). Proof. by move=> x; apply/eqP; rewrite -leEmeet. Qed. Lemma meet1x : left_id \top (@meet _ L). Proof. by move=> x; apply/eqP; rewrite meetC meetx1. Qed. Lemma meet_eq1 x y : (x `&` y == \top) = (x == \top) && (y == \top). Proof. apply/idP/idP; last by move=> /andP[/eqP-> /eqP->]; rewrite meetx1. by move=> /eqP xIy1; rewrite -!le1x -xIy1 leIl leIr. Qed. HB.instance Definition _ := Monoid.isMonoidLaw.Build L \top meet meet1x meetx1. Lemma meets_inf_seq T (r : seq T) (P : {pred T}) (F : T -> L) (x : T) : x \in r -> P x -> \meet_(i <- r | P i) F i <= F x. Proof. by move=> xr Px; rewrite (big_rem x) ?Px //= leIl. Qed. Lemma meets_max_seq T (r : seq T) (P : {pred T}) (F : T -> L) (x : T) (u : L) : x \in r -> P x -> F x <= u -> \meet_(x <- r | P x) F x <= u. Proof. by move=> ? ?; apply/le_trans/meets_inf_seq. Qed. Lemma meets_inf I (j : I) (P : {pred I}) (F : I -> L) : P j -> \meet_(i | P i) F i <= F j. Proof. exact: meets_inf_seq. Qed. Lemma meets_max I (j : I) (u : L) (P : {pred I}) (F : I -> L) : P j -> F j <= u -> \meet_(i | P i) F i <= u. Proof. exact: meets_max_seq. Qed. Lemma meets_ge J (r : seq J) (P : {pred J}) (F : J -> L) (u : L) : (forall x : J, P x -> u <= F x) -> u <= \meet_(x <- r | P x) F x. Proof. by move=> leFm; elim/big_rec: _ => // i x Px xu; rewrite lexI leFm. Qed. Lemma meetsP_seq T (r : seq T) (P : {pred T}) (F : T -> L) (l : L) : reflect (forall x : T, x \in r -> P x -> l <= F x) (l <= \meet_(x <- r | P x) F x). Proof. apply: (iffP idP) => leFm => [x xr Px|]. exact/(le_trans leFm)/meets_inf_seq. by rewrite big_seq_cond meets_ge// => x /andP[/leFm]. Qed. Lemma meetsP I (l : L) (P : {pred I}) (F : I -> L) : reflect (forall i : I, P i -> l <= F i) (l <= \meet_(i | P i) F i). Proof. by apply: (iffP (meetsP_seq _ _ _ _)) => H ? ?; apply: H. Qed. Lemma le_meets I (A B : {set I}) (F : I -> L) : A \subset B -> \meet_(i in B) F i <= \meet_(i in A) F i. Proof. by move=> /subsetP AB; apply/meetsP => i iA; apply/meets_inf/AB. Qed. Lemma meets_setU I (A B : {set I}) (F : I -> L) : \meet_(i in (A :|: B)) F i = \meet_(i in A) F i `&` \meet_(i in B) F i. Proof. rewrite -!big_enum; have /= <- := @big_cat _ _ meet. apply/eq_big_idem; first exact: meetxx. by move=> ?; rewrite mem_cat !fintype.mem_enum inE. Qed. Lemma meets_seq I (r : seq I) (F : I -> L) : \meet_(i <- r) F i = \meet_(i in r) F i. Proof. by rewrite -big_enum; apply/eq_big_idem => ?; rewrite /= ?meetxx ?fintype.mem_enum. Qed. End TMeetTheory. End TMeetTheory. Module Import JoinTheory. Section JoinTheory. Context {disp : disp_t} {L : joinSemilatticeType disp}. Implicit Types (x y : L). (* interaction with order *) Lemma leUx x y z : (x `|` y <= z) = (x <= z) && (y <= z). Proof. exact: leUx. Qed. Lemma leUr x y : x <= y `|` x. Proof. exact: (@leIr _ L^d). Qed. Lemma leUl x y : x <= x `|` y. Proof. exact: (@leIl _ L^d). Qed. Lemma lexUl x y z : x <= y -> x <= y `|` z. Proof. exact: (@leIxl _ L^d). Qed. Lemma lexUr x y z : x <= z -> x <= y `|` z. Proof. exact: (@leIxr _ L^d). Qed. Lemma lexU2 x y z : (x <= y) || (x <= z) -> x <= y `|` z. Proof. exact: (@leIx2 _ L^d). Qed. Lemma leEjoin x y : (x <= y) = (x `|` y == y). Proof. by rewrite [LHS](@leEmeet _ L^d) meetC. Qed. Lemma eq_joinl x y : (x `|` y == x) = (y <= x). Proof. exact: (@eq_meetl _ L^d). Qed. Lemma eq_joinr x y : (x `|` y == y) = (x <= y). Proof. exact: (@eq_meetr _ L^d). Qed. Lemma join_idPl {x y} : reflect (y `|` x = y) (x <= y). Proof. exact: (@meet_idPl _ L^d). Qed. Lemma join_idPr {x y} : reflect (x `|` y = y) (x <= y). Proof. exact: (@meet_idPr _ L^d). Qed. Lemma join_l x y : y <= x -> x `|` y = x. Proof. exact/join_idPl. Qed. Lemma join_r x y : x <= y -> x `|` y = y. Proof. exact/join_idPr. Qed. Lemma leUidl x y : (x `|` y <= y) = (x <= y). Proof. exact: (@leIidr _ L^d). Qed. Lemma leUidr x y : (y `|` x <= y) = (x <= y). Proof. exact: (@leIidl _ L^d). Qed. Lemma leU2 x y z t : x <= z -> y <= t -> x `|` y <= z `|` t. Proof. exact: (@leI2 _ L^d). Qed. (* algebraic properties *) Lemma joinC : commutative (@join _ L). Proof. exact: (@meetC _ L^d). Qed. Lemma joinA : associative (@join _ L). Proof. exact: (@meetA _ L^d). Qed. HB.instance Definition _ := SemiGroup.isComLaw.Build L join joinA joinC. Lemma joinxx : idempotent_op (@join _ L). Proof. exact: (@meetxx _ L^d). Qed. Lemma joinAC : right_commutative (@join _ L). Proof. exact: (@meetAC _ L^d). Qed. Lemma joinCA : left_commutative (@join _ L). Proof. exact: (@meetCA _ L^d). Qed. Lemma joinACA : interchange (@join _ L) (@join _ L). Proof. exact: (@meetACA _ L^d). Qed. Lemma joinKU y x : x `|` (x `|` y) = x `|` y. Proof. exact: (@meetKI _ L^d). Qed. Lemma joinUK y x : (x `|` y) `|` y = x `|` y. Proof. exact: (@meetIK _ L^d). Qed. Lemma joinKUC y x : x `|` (y `|` x) = x `|` y. Proof. exact: (@meetKIC _ L^d). Qed. Lemma joinUKC y x : y `|` x `|` y = x `|` y. Proof. exact: (@meetIKC _ L^d). Qed. End JoinTheory. End JoinTheory. Arguments join_idPl {disp L x y}. Arguments join_idPr {disp L x y}. Module Import BJoinTheory. Section BJoinTheory. Context {disp : disp_t} {L : bJoinSemilatticeType disp}. Implicit Types (I : finType) (T : eqType) (x y : L). Lemma joinx0 : right_id \bot (@join _ L). Proof. exact: (@meetx1 _ L^d). Qed. Lemma join0x : left_id \bot (@join _ L). Proof. exact: (@meet1x _ L^d). Qed. Lemma join_eq0 x y : (x `|` y == \bot) = (x == \bot) && (y == \bot). Proof. exact: (@meet_eq1 _ L^d). Qed. HB.instance Definition _ := Monoid.isMonoidLaw.Build L \bot join join0x joinx0. Lemma joins_sup_seq T (r : seq T) (P : {pred T}) (F : T -> L) (x : T) : x \in r -> P x -> F x <= \join_(i <- r | P i) F i. Proof. exact: (@meets_inf_seq _ L^d). Qed. Lemma joins_min_seq T (r : seq T) (P : {pred T}) (F : T -> L) (x : T) (l : L) : x \in r -> P x -> l <= F x -> l <= \join_(x <- r | P x) F x. Proof. exact: (@meets_max_seq _ L^d). Qed. Lemma joins_sup I (j : I) (P : {pred I}) (F : I -> L) : P j -> F j <= \join_(i | P i) F i. Proof. exact: (@meets_inf _ L^d). Qed. Lemma joins_min I (j : I) (l : L) (P : {pred I}) (F : I -> L) : P j -> l <= F j -> l <= \join_(i | P i) F i. Proof. exact: (@meets_max _ L^d). Qed. Lemma joins_le J (r : seq J) (P : {pred J}) (F : J -> L) (u : L) : (forall x : J, P x -> F x <= u) -> \join_(x <- r | P x) F x <= u. Proof. exact: (@meets_ge _ L^d). Qed. Lemma joinsP_seq T (r : seq T) (P : {pred T}) (F : T -> L) (u : L) : reflect (forall x : T, x \in r -> P x -> F x <= u) (\join_(x <- r | P x) F x <= u). Proof. exact: (@meetsP_seq _ L^d). Qed. Lemma joinsP I (u : L) (P : {pred I}) (F : I -> L) : reflect (forall i : I, P i -> F i <= u) (\join_(i | P i) F i <= u). Proof. exact: (@meetsP _ L^d). Qed. Lemma le_joins I (A B : {set I}) (F : I -> L) : A \subset B -> \join_(i in A) F i <= \join_(i in B) F i. Proof. exact: (@le_meets _ L^d). Qed. Lemma joins_setU I (A B : {set I}) (F : I -> L) : \join_(i in (A :|: B)) F i = \join_(i in A) F i `|` \join_(i in B) F i. Proof. exact: (@meets_setU _ L^d). Qed. Lemma joins_seq I (r : seq I) (F : I -> L) : \join_(i <- r) F i = \join_(i in r) F i. Proof. exact: (@meets_seq _ L^d). Qed. End BJoinTheory. End BJoinTheory. Module Import TJoinTheory. Section TJoinTheory. Context {disp : disp_t} {L : tJoinSemilatticeType disp}. Lemma joinx1 : right_zero \top (@join _ L). Proof. exact: (@meetx0 _ L^d). Qed. Lemma join1x : left_zero \top (@join _ L). Proof. exact: (@meet0x _ L^d). Qed. HB.instance Definition _ := Monoid.isMulLaw.Build L \top join join1x joinx1. End TJoinTheory. End TJoinTheory. Module Import LatticeTheory. Section LatticeTheory. Context {disp : disp_t} {L : latticeType disp}. Implicit Types (x y : L). Lemma meetUK x y : (x `&` y) `|` y = y. Proof. exact/join_idPr/leIr. Qed. Lemma meetUKC x y : (y `&` x) `|` y = y. Proof. by rewrite meetC meetUK. Qed. Lemma meetKUC y x : x `|` (y `&` x) = x. Proof. by rewrite joinC meetUK. Qed. Lemma meetKU y x : x `|` (x `&` y) = x. Proof. by rewrite meetC meetKUC. Qed. Lemma joinIK x y : (x `|` y) `&` y = y. Proof. exact/meet_idPr/leUr. Qed. Lemma joinIKC x y : (y `|` x) `&` y = y. Proof. by rewrite joinC joinIK. Qed. Lemma joinKIC y x : x `&` (y `|` x) = x. Proof. by rewrite meetC joinIK. Qed. Lemma joinKI y x : x `&` (x `|` y) = x. Proof. by rewrite joinC joinKIC. Qed. (* comparison predicates *) Lemma lcomparableP x y : incomparel x y (min y x) (min x y) (max y x) (max x y) (y `&` x) (x `&` y) (y `|` x) (x `|` y) (y == x) (x == y) (x >= y) (x <= y) (x > y) (x < y) (y >=< x) (x >=< y). Proof. by case: (comparableP x) => [hxy|hxy|hxy|->]; do 1?have hxy' := ltW hxy; rewrite ?(meetxx, joinxx); rewrite ?(meet_l hxy', meet_r hxy', join_l hxy', join_r hxy'); constructor. Qed. Lemma lcomparable_ltgtP x y : x >=< y -> comparel x y (min y x) (min x y) (max y x) (max x y) (y `&` x) (x `&` y) (y `|` x) (x `|` y) (y == x) (x == y) (x >= y) (x <= y) (x > y) (x < y). Proof. by case: (lcomparableP x) => // *; constructor. Qed. Lemma lcomparable_leP x y : x >=< y -> lel_xor_gt x y (min y x) (min x y) (max y x) (max x y) (y `&` x) (x `&` y) (y `|` x) (x `|` y) (x <= y) (y < x). Proof. by move/lcomparable_ltgtP => [/ltW xy|xy|->]; constructor. Qed. Lemma lcomparable_ltP x y : x >=< y -> ltl_xor_ge x y (min y x) (min x y) (max y x) (max x y) (y `&` x) (x `&` y) (y `|` x) (x `|` y) (y <= x) (x < y). Proof. by move=> /lcomparable_ltgtP [xy|/ltW xy|->]; constructor. Qed. End LatticeTheory. End LatticeTheory. Module Import DistrLatticeTheory. Section DistrLatticeTheory. Context {disp : disp_t} {L : distrLatticeType disp}. Lemma meetUl : left_distributive (@meet _ L) (@join _ L). Proof. exact: meetUl. Qed. Lemma meetUr : right_distributive (@meet _ L) (@join _ L). Proof. by move=> x y z; rewrite ![x `&` _]meetC meetUl. Qed. Lemma joinIl : left_distributive (@join _ L) (@meet _ L). Proof. exact: joinIl. Qed. Lemma joinIr : right_distributive (@join _ L) (@meet _ L). Proof. by move=> x y z; rewrite ![x `|` _]joinC joinIl. Qed. #[warning="-HB.no-new-instance"] HB.instance Definition _ := Monoid.isAddLaw.Build L meet join meetUl meetUr. HB.instance Definition _ := Monoid.isAddLaw.Build L join meet joinIl joinIr. End DistrLatticeTheory. End DistrLatticeTheory. Module Import BDistrLatticeTheory. Section BDistrLatticeTheory. Context {disp : disp_t} {L : bDistrLatticeType disp}. Implicit Types (x y z : L). Lemma leU2l_le y t x z : x `&` t = \bot -> x `|` y <= z `|` t -> x <= z. Proof. by move=> xIt0 /(leI2 (lexx x)); rewrite joinKI meetUr xIt0 joinx0 leIidl. Qed. Lemma leU2r_le y t x z : x `&` t = \bot -> y `|` x <= t `|` z -> x <= z. Proof. by rewrite joinC [_ `|` z]joinC => /leU2l_le H /H. Qed. Lemma disjoint_lexUl z x y : x `&` z = \bot -> (x <= y `|` z) = (x <= y). Proof. move=> xz0; apply/idP/idP=> xy; last by rewrite lexU2 ?xy. by apply: (@leU2l_le x z); rewrite ?joinxx. Qed. Lemma disjoint_lexUr z x y : x `&` z = \bot -> (x <= z `|` y) = (x <= y). Proof. by move=> xz0; rewrite joinC; rewrite disjoint_lexUl. Qed. Lemma leU2E x y z t : x `&` t = \bot -> y `&` z = \bot -> (x `|` y <= z `|` t) = (x <= z) && (y <= t). Proof. move=> dxt dyz; apply/idP/andP; last by case=> ? ?; exact: leU2. by move=> lexyzt; rewrite (leU2l_le _ lexyzt) // (leU2r_le _ lexyzt). Qed. Lemma joins_disjoint (I : finType) (d : L) (P : {pred I}) (F : I -> L) : (forall i : I, P i -> d `&` F i = \bot) -> d `&` \join_(i | P i) F i = \bot. Proof. move=> d_Fi_disj; have : \big[andb/true]_(i | P i) (d `&` F i == \bot). rewrite big_all_cond; apply/allP => i _ /=. by apply/implyP => /d_Fi_disj ->. elim/big_rec2: _ => [|i y]; first by rewrite meetx0. case; rewrite (andbF, andbT) // => Pi /(_ isT) dy /eqP dFi. by rewrite meetUr dy dFi joinxx. Qed. End BDistrLatticeTheory. End BDistrLatticeTheory. Module Import TDistrLatticeTheory. Section TDistrLatticeTheory. Context {disp : disp_t} {L : tDistrLatticeType disp}. Implicit Types (x y : L). Lemma leI2l_le y t x z : y `|` z = \top -> x `&` y <= z `&` t -> x <= z. Proof. by rewrite joinC; exact: (@leU2l_le _ L^d). Qed. Lemma leI2r_le y t x z : y `|` z = \top -> y `&` x <= t `&` z -> x <= z. Proof. by rewrite joinC; exact: (@leU2r_le _ L^d). Qed. Lemma cover_leIxl z x y : z `|` y = \top -> (x `&` z <= y) = (x <= y). Proof. by rewrite joinC; exact: (@disjoint_lexUl _ L^d). Qed. Lemma cover_leIxr z x y : z `|` y = \top -> (z `&` x <= y) = (x <= y). Proof. by rewrite joinC; exact: (@disjoint_lexUr _ L^d). Qed. Lemma leI2E x y z t : x `|` t = \top -> y `|` z = \top -> (x `&` y <= z `&` t) = (x <= z) && (y <= t). Proof. by move=> ? ?; apply: (@leU2E _ L^d); rewrite meetC. Qed. Lemma meets_total (I : finType) (d : L) (P : {pred I}) (F : I -> L) : (forall i : I, P i -> d `|` F i = \top) -> d `|` \meet_(i | P i) F i = \top. Proof. exact: (@joins_disjoint _ L^d). Qed. End TDistrLatticeTheory. End TDistrLatticeTheory. Module Import TotalTheory. Section TotalTheory. Context {disp : disp_t} {T : orderType disp}. Implicit Types (x y z t : T) (s : seq T). Definition le_total : total (<=%O : rel T) := le_total. Hint Resolve le_total : core. Lemma ge_total : total (>=%O : rel T). Proof. by move=> ? ?; apply: le_total. Qed. Hint Resolve ge_total : core. Lemma comparableT x y : x >=< y. Proof. exact: le_total. Qed. Hint Extern 0 (is_true (_ >=< _)%O) => solve [apply: comparableT] : core. Lemma sort_le_sorted s : sorted <=%O (sort <=%O s). Proof. exact: sort_sorted. Qed. Hint Resolve sort_le_sorted : core. Lemma sort_lt_sorted s : sorted <%O (sort <=%O s) = uniq s. Proof. by rewrite lt_sorted_uniq_le sort_uniq sort_le_sorted andbT. Qed. Lemma perm_sort_leP s1 s2 : reflect (sort <=%O s1 = sort <=%O s2) (perm_eq s1 s2). Proof. exact/perm_sortP/le_anti/le_trans/le_total. Qed. Lemma filter_sort_le p s : filter p (sort <=%O s) = sort <=%O (filter p s). Proof. exact/filter_sort/le_trans/le_total. Qed. Lemma mask_sort_le s (m : bitseq) : {m_s : bitseq | mask m_s (sort <=%O s) = sort <=%O (mask m s)}. Proof. exact/mask_sort/le_trans/le_total. Qed. Lemma sorted_mask_sort_le s (m : bitseq) : sorted <=%O (mask m s) -> {m_s : bitseq | mask m_s (sort <=%O s) = mask m s}. Proof. exact/sorted_mask_sort/le_trans/le_total. Qed. Lemma subseq_sort_le : {homo sort <=%O : s1 s2 / @subseq T s1 s2}. Proof. exact/subseq_sort/le_trans/le_total. Qed. Lemma sorted_subseq_sort_le s1 s2 : subseq s1 s2 -> sorted <=%O s1 -> subseq s1 (sort <=%O s2). Proof. exact/sorted_subseq_sort/le_trans/le_total. Qed. Lemma mem2_sort_le s x y : x <= y -> mem2 s x y -> mem2 (sort <=%O s) x y. Proof. exact/mem2_sort/le_trans/le_total. Qed. Lemma leNgt x y : (x <= y) = ~~ (y < x). Proof. exact: comparable_leNgt. Qed. Lemma ltNge x y : (x < y) = ~~ (y <= x). Proof. exact: comparable_ltNge. Qed. Definition ltgtP x y := LatticeTheory.lcomparable_ltgtP (comparableT x y). Definition leP x y := LatticeTheory.lcomparable_leP (comparableT x y). Definition ltP x y := LatticeTheory.lcomparable_ltP (comparableT x y). Lemma wlog_le P : (forall x y, P y x -> P x y) -> (forall x y, x <= y -> P x y) -> forall x y, P x y. Proof. by move=> sP hP x y; case: (leP x y) => [| /ltW] /hP // /sP. Qed. Lemma wlog_lt P : (forall x, P x x) -> (forall x y, (P y x -> P x y)) -> (forall x y, x < y -> P x y) -> forall x y, P x y. Proof. by move=> rP sP hP x y; case: (ltgtP x y) => [||->] // /hP // /sP. Qed. Lemma neq_lt x y : (x != y) = (x < y) || (y < x). Proof. by case: ltgtP. Qed. Lemma lt_total x y : x != y -> (x < y) || (y < x). Proof. by case: ltgtP. Qed. Lemma eq_leLR x y z t : (x <= y -> z <= t) -> (y < x -> t < z) -> (x <= y) = (z <= t). Proof. by rewrite !ltNge => ? /contraTT ?; apply/idP/idP. Qed. Lemma eq_leRL x y z t : (x <= y -> z <= t) -> (y < x -> t < z) -> (z <= t) = (x <= y). Proof. by move=> *; apply/esym/eq_leLR. Qed. Lemma eq_ltLR x y z t : (x < y -> z < t) -> (y <= x -> t <= z) -> (x < y) = (z < t). Proof. by rewrite !leNgt => ? /contraTT ?; apply/idP/idP. Qed. Lemma eq_ltRL x y z t : (x < y -> z < t) -> (y <= x -> t <= z) -> (z < t) = (x < y). Proof. by move=> *; apply/esym/eq_ltLR. Qed. (* max and min is join and meet *) Lemma meetEtotal x y : x `&` y = min x y. Proof. by case: leP. Qed. Lemma joinEtotal x y : x `|` y = max x y. Proof. by case: leP. Qed. (* max and min theory *) Lemma minEgt x y : min x y = if x > y then y else x. Proof. by case: ltP. Qed. Lemma maxEgt x y : max x y = if x > y then x else y. Proof. by case: ltP. Qed. Lemma minEge x y : min x y = if x >= y then y else x. Proof. by case: leP. Qed. Lemma maxEge x y : max x y = if x >= y then x else y. Proof. by case: leP. Qed. Lemma minC : commutative (min : T -> T -> T). Proof. by move=> x y; apply: comparable_minC. Qed. Lemma maxC : commutative (max : T -> T -> T). Proof. by move=> x y; apply: comparable_maxC. Qed. Lemma minA : associative (min : T -> T -> T). Proof. by move=> x y z; apply: comparable_minA. Qed. Lemma maxA : associative (max : T -> T -> T). Proof. by move=> x y z; apply: comparable_maxA. Qed. Lemma minAC : right_commutative (min : T -> T -> T). Proof. by move=> x y z; apply: comparable_minAC. Qed. Lemma maxAC : right_commutative (max : T -> T -> T). Proof. by move=> x y z; apply: comparable_maxAC. Qed. Lemma minCA : left_commutative (min : T -> T -> T). Proof. by move=> x y z; apply: comparable_minCA. Qed. Lemma maxCA : left_commutative (max : T -> T -> T). Proof. by move=> x y z; apply: comparable_maxCA. Qed. Lemma minACA : interchange (min : T -> T -> T) min. Proof. by move=> x y z t; apply: comparable_minACA. Qed. Lemma maxACA : interchange (max : T -> T -> T) max. Proof. by move=> x y z t; apply: comparable_maxACA. Qed. Lemma eq_minr x y : (min x y == y) = (y <= x). Proof. exact: comparable_eq_minr. Qed. Lemma eq_maxl x y : (max x y == x) = (y <= x). Proof. exact: comparable_eq_maxl. Qed. Lemma min_idPr x y : reflect (min x y = y) (y <= x). Proof. exact: comparable_min_idPr. Qed. Lemma max_idPl x y : reflect (max x y = x) (y <= x). Proof. exact: comparable_max_idPl. Qed. Lemma le_min z x y : (z <= min x y) = (z <= x) && (z <= y). Proof. exact: comparable_le_min. Qed. Lemma ge_min z x y : (min x y <= z) = (x <= z) || (y <= z). Proof. exact: comparable_ge_min. Qed. Lemma lt_min z x y : (z < min x y) = (z < x) && (z < y). Proof. exact: comparable_lt_min. Qed. Lemma gt_min z x y : (min x y < z) = (x < z) || (y < z). Proof. exact: comparable_gt_min. Qed. Lemma le_max z x y : (z <= max x y) = (z <= x) || (z <= y). Proof. exact: comparable_le_max. Qed. Lemma ge_max z x y : (max x y <= z) = (x <= z) && (y <= z). Proof. exact: comparable_ge_max. Qed. Lemma lt_max z x y : (z < max x y) = (z < x) || (z < y). Proof. exact: comparable_lt_max. Qed. Lemma gt_max z x y : (max x y < z) = (x < z) && (y < z). Proof. exact: comparable_gt_max. Qed. Lemma minxK x y : max (min x y) y = y. Proof. exact: comparable_minxK. Qed. Lemma minKx x y : max x (min x y) = x. Proof. exact: comparable_minKx. Qed. Lemma maxxK x y : min (max x y) y = y. Proof. exact: comparable_maxxK. Qed. Lemma maxKx x y : min x (max x y) = x. Proof. exact: comparable_maxKx. Qed. Lemma max_minl : left_distributive (max : T -> T -> T) min. Proof. by move=> x y z; apply: comparable_max_minl. Qed. Lemma min_maxl : left_distributive (min : T -> T -> T) max. Proof. by move=> x y z; apply: comparable_min_maxl. Qed. Lemma max_minr : right_distributive (max : T -> T -> T) min. Proof. by move=> x y z; apply: comparable_max_minr. Qed. Lemma min_maxr : right_distributive (min : T -> T -> T) max. Proof. by move=> x y z; apply: comparable_min_maxr. Qed. HB.instance Definition _ := SemiGroup.isComLaw.Build T max maxA maxC. HB.instance Definition _ := SemiGroup.isComLaw.Build T min minA minC. Lemma leIx x y z : (meet y z <= x) = (y <= x) || (z <= x). Proof. by rewrite meetEtotal ge_min. Qed. Lemma lexU x y z : (x <= join y z) = (x <= y) || (x <= z). Proof. by rewrite joinEtotal le_max. Qed. Lemma ltxI x y z : (x < meet y z) = (x < y) && (x < z). Proof. by rewrite !ltNge leIx negb_or. Qed. Lemma ltIx x y z : (meet y z < x) = (y < x) || (z < x). Proof. by rewrite !ltNge lexI negb_and. Qed. Lemma ltxU x y z : (x < join y z) = (x < y) || (x < z). Proof. by rewrite !ltNge leUx negb_and. Qed. Lemma ltUx x y z : (join y z < x) = (y < x) && (z < x). Proof. by rewrite !ltNge lexU negb_or. Qed. Definition ltexI := (@lexI _ T, ltxI). Definition lteIx := (leIx, ltIx). Definition ltexU := (lexU, ltxU). Definition lteUx := (@leUx _ T, ltUx). Lemma le_min2 x y z t : x <= z -> y <= t -> Order.min x y <= Order.min z t. Proof. exact: comparable_le_min2. Qed. Lemma le_max2 x y z t : x <= z -> y <= t -> Order.max x y <= Order.max z t. Proof. exact: comparable_le_max2. Qed. (* lteif *) Lemma lteifNE x y C : x < y ?<= if ~~ C = ~~ (y < x ?<= if C). Proof. by case: C => /=; case: leP. Qed. Lemma lteif_minr z x y C : (z < min x y ?<= if C) = (z < x ?<= if C) && (z < y ?<= if C). Proof. by case: C; rewrite /= (le_min, lt_min). Qed. Lemma lteif_minl z x y C : (min x y < z ?<= if C) = (x < z ?<= if C) || (y < z ?<= if C). Proof. by case: C; rewrite /= (ge_min, gt_min). Qed. Lemma lteif_maxr z x y C : (z < max x y ?<= if C) = (z < x ?<= if C) || (z < y ?<= if C). Proof. by case: C; rewrite /= (le_max, lt_max). Qed. Lemma lteif_maxl z x y C : (max x y < z ?<= if C) = (x < z ?<= if C) && (y < z ?<= if C). Proof. by case: C; rewrite /= (ge_max, gt_max). Qed. Section ArgExtremum. Context (I : finType) (i0 : I) (P : {pred I}) (F : I -> T) (Pi0 : P i0). Lemma arg_minP: extremum_spec <=%O P F (arg_min i0 P F). Proof. by apply: extremumP => //; apply: le_trans. Qed. Lemma arg_maxP: extremum_spec >=%O P F (arg_max i0 P F). Proof. by apply: extremumP => //; [apply: ge_refl | apply: ge_trans]. Qed. End ArgExtremum. Lemma count_le_gt x s : count (<= x) s = size s - count (> x) s. Proof. by rewrite -(count_predC (> x)) addKn; apply: eq_count => y; rewrite /= leNgt. Qed. Lemma count_lt_ge x s : count (< x) s = size s - count (>= x) s. Proof. by rewrite -(count_predC (>= x)) addKn; apply: eq_count => y; rewrite /= ltNge. Qed. Section bigminmax_Type. Context (I : Type) (r : seq I) (x : T). Implicit Types (P : pred I) (F : I -> T). Lemma bigmin_mkcond P F : \big[min/x]_(i <- r | P i) F i = \big[min/x]_(i <- r) (if P i then F i else x). Proof. by rewrite big_mkcond_idem //= minxx. Qed. Lemma bigmax_mkcond P F : \big[max/x]_(i <- r | P i) F i = \big[max/x]_(i <- r) if P i then F i else x. Proof. by rewrite big_mkcond_idem //= maxxx. Qed. Lemma bigmin_mkcondl P Q F : \big[min/x]_(i <- r | P i && Q i) F i = \big[min/x]_(i <- r | Q i) if P i then F i else x. Proof. rewrite bigmin_mkcond [RHS]bigmin_mkcond. by apply: eq_bigr => i _; case: P; case: Q. Qed. Lemma bigmin_mkcondr P Q F : \big[min/x]_(i <- r | P i && Q i) F i = \big[min/x]_(i <- r | P i) if Q i then F i else x. Proof. by under eq_bigl do rewrite andbC; apply: bigmin_mkcondl. Qed. Lemma bigmax_mkcondl P Q F : \big[max/x]_(i <- r | P i && Q i) F i = \big[max/x]_(i <- r | Q i) if P i then F i else x. Proof. rewrite bigmax_mkcond [RHS]bigmax_mkcond. by apply: eq_bigr => i _; case: P; case: Q. Qed. Lemma bigmax_mkcondr P Q F : \big[max/x]_(i <- r | P i && Q i) F i = \big[max/x]_(i <- r | P i) if Q i then F i else x. Proof. by under eq_bigl do rewrite andbC; apply: bigmax_mkcondl. Qed. Lemma bigmin_split P F1 F2 : \big[min/x]_(i <- r | P i) (min (F1 i) (F2 i)) = min (\big[min/x]_(i <- r | P i) F1 i) (\big[min/x]_(i <- r | P i) F2 i). Proof. by rewrite big_split_idem //= minxx. Qed. Lemma bigmax_split P F1 F2 : \big[max/x]_(i <- r | P i) (max (F1 i) (F2 i)) = max (\big[max/x]_(i <- r | P i) F1 i) (\big[max/x]_(i <- r | P i) F2 i). Proof. by rewrite big_split_idem //= maxxx. Qed. Lemma bigmin_idl P F : \big[min/x]_(i <- r | P i) F i = min x (\big[min/x]_(i <- r | P i) F i). Proof. by rewrite minC big_id_idem //= minxx. Qed. Lemma bigmax_idl P F : \big[max/x]_(i <- r | P i) F i = max x (\big[max/x]_(i <- r | P i) F i). Proof. by rewrite maxC big_id_idem //= maxxx. Qed. Lemma bigmin_idr P F : \big[min/x]_(i <- r | P i) F i = min (\big[min/x]_(i <- r | P i) F i) x. Proof. by rewrite [LHS]bigmin_idl minC. Qed. Lemma bigmax_idr P F : \big[max/x]_(i <- r | P i) F i = max (\big[max/x]_(i <- r | P i) F i) x. Proof. by rewrite [LHS]bigmax_idl maxC. Qed. Lemma bigminID a P F : \big[min/x]_(i <- r | P i) F i = min (\big[min/x]_(i <- r | P i && a i) F i) (\big[min/x]_(i <- r | P i && ~~ a i) F i). Proof. by rewrite (bigID_idem _ _ a) //= minxx. Qed. Lemma bigmaxID a P F : \big[max/x]_(i <- r | P i) F i = max (\big[max/x]_(i <- r | P i && a i) F i) (\big[max/x]_(i <- r | P i && ~~ a i) F i). Proof. by rewrite (bigID_idem _ _ a) //= maxxx. Qed. End bigminmax_Type. Let ge_min_id (x y : T) : x >= min x y. Proof. by rewrite ge_min lexx. Qed. Let le_max_id (x y : T) : x <= max x y. Proof. by rewrite le_max lexx. Qed. Lemma sub_bigmin [x0] I r (P P' : {pred I}) (F : I -> T) : (forall i, P' i -> P i) -> \big[min/x0]_(i <- r | P i) F i <= \big[min/x0]_(i <- r | P' i) F i. Proof. exact: (sub_le_big ge_refl). Qed. Lemma sub_bigmax [x0] I r (P P' : {pred I}) (F : I -> T) : (forall i, P i -> P' i) -> \big[max/x0]_(i <- r | P i) F i <= \big[max/x0]_(i <- r | P' i) F i. Proof. exact: sub_le_big. Qed. (* FIXME: Remove that. *) Local Notation "'{subset' x '<=' y '}'" := (sub_mem (mem x) (mem y)) (at level 0, x, y at level 1). Lemma sub_bigmin_seq [x0] (I : eqType) r r' P (F : I -> T) : {subset r' <= r} -> \big[min/x0]_(i <- r | P i) F i <= \big[min/x0]_(i <- r' | P i) F i. Proof. exact: (idem_sub_le_big ge_refl _ minxx). Qed. Lemma sub_bigmax_seq [x0] (I : eqType) r r' P (F : I -> T) : {subset r <= r'} -> \big[max/x0]_(i <- r | P i) F i <= \big[max/x0]_(i <- r' | P i) F i. Proof. exact: (idem_sub_le_big _ _ maxxx). Qed. Lemma sub_bigmin_cond [x0] (I : eqType) r r' P P' (F : I -> T) : {subset ([seq i <- r | P i]) <= ([seq i <- r' | P' i])} -> \big[min/x0]_(i <- r' | P' i) F i <= \big[min/x0]_(i <- r | P i) F i. Proof. exact: (idem_sub_le_big_cond ge_refl _ minxx). Qed. Lemma sub_bigmax_cond [x0] (I : eqType) r r' P P' (F : I -> T) : {subset ([seq i <- r | P i]) <= ([seq i <- r' | P' i])} -> \big[max/x0]_(i <- r | P i) F i <= \big[max/x0]_(i <- r' | P' i) F i. Proof. exact: (idem_sub_le_big_cond _ _ maxxx). Qed. Lemma sub_in_bigmin [x0] [I : eqType] (r : seq I) (P P' : {pred I}) F : {in r, forall i, P' i -> P i} -> \big[min/x0]_(i <- r | P i) F i <= \big[min/x0]_(i <- r | P' i) F i. Proof. exact: (sub_in_le_big ge_refl). Qed. Lemma sub_in_bigmax [x0] [I : eqType] (r : seq I) (P P' : {pred I}) F : {in r, forall i, P i -> P' i} -> \big[max/x0]_(i <- r | P i) F i <= \big[max/x0]_(i <- r | P' i) F i. Proof. exact: sub_in_le_big. Qed. Lemma le_bigmin_nat [x0] n m n' m' P (F : nat -> T) : (n <= n')%N -> (m' <= m)%N -> \big[min/x0]_(n <= i < m | P i) F i <= \big[min/x0]_(n' <= i < m' | P i) F i. Proof. exact: (le_big_nat ge_refl). Qed. Lemma le_bigmax_nat [x0] n m n' m' P (F : nat -> T) : (n' <= n)%N -> (m <= m')%N -> \big[max/x0]_(n <= i < m | P i) F i <= \big[max/x0]_(n' <= i < m' | P i) F i. Proof. exact: le_big_nat. Qed. Lemma le_bigmin_nat_cond [x0] n m n' m' (P P' : pred nat) (F : nat -> T) : (n <= n')%N -> (m' <= m)%N -> (forall i, (n' <= i < m')%N -> P' i -> P i) -> \big[min/x0]_(n <= i < m | P i) F i <= \big[min/x0]_(n' <= i < m' | P' i) F i. Proof. exact: (le_big_nat_cond ge_refl). Qed. Lemma le_bigmax_nat_cond [x0] n m n' m' (P P' : {pred nat}) (F : nat -> T) : (n' <= n)%N -> (m <= m')%N -> (forall i, (n <= i < m)%N -> P i -> P' i) -> \big[max/x0]_(n <= i < m | P i) F i <= \big[max/x0]_(n' <= i < m' | P' i) F i. Proof. exact: le_big_nat_cond. Qed. Lemma le_bigmin_ord [x0] n m (P : pred nat) (F : nat -> T) : (m <= n)%N -> \big[min/x0]_(i < n | P i) F i <= \big[min/x0]_(i < m | P i) F i. Proof. exact: (le_big_ord ge_refl). Qed. Lemma le_bigmax_ord [x0] n m (P : {pred nat}) (F : nat -> T) : (n <= m)%N -> \big[max/x0]_(i < n | P i) F i <= \big[max/x0]_(i < m | P i) F i. Proof. exact: le_big_ord. Qed. Lemma le_bigmin_ord_cond [x0] n m (P P' : pred nat) (F : nat -> T) : (m <= n)%N -> (forall i : 'I_m, P' i -> P i) -> \big[min/x0]_(i < n | P i) F i <= \big[min/x0]_(i < m | P' i) F i. Proof. exact: (le_big_ord_cond ge_refl). Qed. Lemma le_bigmax_ord_cond [x0] n m (P P' : {pred nat}) (F : nat -> T) : (n <= m)%N -> (forall i : 'I_n, P i -> P' i) -> \big[max/x0]_(i < n | P i) F i <= \big[max/x0]_(i < m | P' i) F i. Proof. exact: le_big_ord_cond. Qed. Lemma subset_bigmin [x0] [I : finType] [A A' P : {pred I}] (F : I -> T) : A' \subset A -> \big[min/x0]_(i in A | P i) F i <= \big[min/x0]_(i in A' | P i) F i. Proof. exact: (subset_le_big ge_refl). Qed. Lemma subset_bigmax [x0] [I : finType] (A A' P : {pred I}) (F : I -> T) : A \subset A' -> \big[max/x0]_(i in A | P i) F i <= \big[max/x0]_(i in A' | P i) F i. Proof. exact: subset_le_big. Qed. Lemma subset_bigmin_cond [x0] (I : finType) (A A' P P' : {pred I}) (F : I -> T) : [set i in A' | P' i] \subset [set i in A | P i] -> \big[min/x0]_(i in A | P i) F i <= \big[min/x0]_(i in A' | P' i) F i. Proof. exact: (subset_le_big_cond ge_refl). Qed. Lemma subset_bigmax_cond [x0] (I : finType) (A A' P P' : {pred I}) (F : I -> T) : [set i in A | P i] \subset [set i in A' | P' i] -> \big[max/x0]_(i in A | P i) F i <= \big[max/x0]_(i in A' | P' i) F i. Proof. exact: subset_le_big_cond. Qed. Section bigminmax_eqType. Context (I : eqType) (r : seq I) (x : T). Implicit Types (P : pred I) (F : I -> T). Lemma bigmin_le_id P F : \big[min/x]_(i <- r | P i) F i <= x. Proof. by rewrite bigmin_idl. Qed. Lemma bigmax_ge_id P F : \big[max/x]_(i <- r | P i) F i >= x. Proof. by rewrite bigmax_idl. Qed. Lemma bigmin_eq_id P F : (forall i, P i -> x <= F i) -> \big[min/x]_(i <- r | P i) F i = x. Proof. by move=> x_le; apply: le_anti; rewrite bigmin_le_id le_bigmin. Qed. Lemma bigmax_eq_id P F : (forall i, P i -> x >= F i) -> \big[max/x]_(i <- r | P i) F i = x. Proof. by move=> x_ge; apply: le_anti; rewrite bigmax_ge_id bigmax_le. Qed. End bigminmax_eqType. Section bigminmax_finType. Context (I : finType) (x : T). Implicit Types (P : pred I) (F : I -> T). Lemma bigminD1 j P F : P j -> \big[min/x]_(i | P i) F i = min (F j) (\big[min/x]_(i | P i && (i != j)) F i). Proof. by move/(bigD1 _) ->. Qed. Lemma bigmaxD1 j P F : P j -> \big[max/x]_(i | P i) F i = max (F j) (\big[max/x]_(i | P i && (i != j)) F i). Proof. by move/(bigD1 _) ->. Qed. Lemma bigmin_le_cond j P F : P j -> \big[min/x]_(i | P i) F i <= F j. Proof. have := mem_index_enum j; rewrite unlock; elim: (index_enum I) => //= i l ih. rewrite inE => /orP [/eqP-> ->|/ih leminlfi Pi]; first by rewrite ge_min lexx. by case: ifPn => Pj; [rewrite ge_min leminlfi// orbC|exact: leminlfi]. Qed. Lemma le_bigmax_cond j P F : P j -> F j <= \big[max/x]_(i | P i) F i. Proof. by move=> Pj; rewrite (bigmaxD1 _ Pj) le_max lexx. Qed. Lemma bigmin_le j F : \big[min/x]_i F i <= F j. Proof. exact: bigmin_le_cond. Qed. Lemma le_bigmax F j : F j <= \big[max/x]_i F i. Proof. exact: le_bigmax_cond. Qed. Lemma bigmin_inf j P m F : P j -> F j <= m -> \big[min/x]_(i | P i) F i <= m. Proof. by move=> Pj ?; apply: le_trans (bigmin_le_cond _ Pj) _. Qed. (* NB: as of [2022-08-02], bigop.bigmax_sup already exists for nat *) Lemma bigmax_sup j P m F : P j -> m <= F j -> m <= \big[max/x]_(i | P i) F i. Proof. by move=> Pj ?; apply: le_trans (le_bigmax_cond _ Pj). Qed. Lemma bigmin_geP m P F : reflect (m <= x /\ forall i, P i -> m <= F i) (m <= \big[min/x]_(i | P i) F i). Proof. apply: (iffP idP) => [lemFi|[lemx lemPi]]; [split|exact: le_bigmin]. - by rewrite (le_trans lemFi)// bigmin_idl ge_min lexx. - by move=> i Pi; rewrite (le_trans lemFi)// (bigminD1 _ Pi)// le_minl lexx. Qed. Lemma bigmax_leP m P F : reflect (x <= m /\ forall i, P i -> F i <= m) (\big[max/x]_(i | P i) F i <= m). Proof. apply: (iffP idP) => [|[? ?]]; last exact: bigmax_le. rewrite bigmax_idl ge_max => /andP[-> leFm]; split=> // i Pi. by apply: le_trans leFm; exact: le_bigmax_cond. Qed. Lemma bigmin_gtP m P F : reflect (m < x /\ forall i, P i -> m < F i) (m < \big[min/x]_(i | P i) F i). Proof. apply: (iffP idP) => [lemFi|[lemx lemPi]]; [split|exact: lt_bigmin]. - by rewrite (lt_le_trans lemFi)// bigmin_idl ge_min lexx. - by move=> i Pi; rewrite (lt_le_trans lemFi)// (bigminD1 _ Pi)// le_minl lexx. Qed. Lemma bigmax_ltP m P F : reflect (x < m /\ forall i, P i -> F i < m) (\big[max/x]_(i | P i) F i < m). Proof. apply: (iffP idP) => [|[? ?]]; last exact: bigmax_lt. rewrite bigmax_idl gt_max => /andP[-> ltFm]; split=> // i Pi. by apply: le_lt_trans ltFm; exact: le_bigmax_cond. Qed. Lemma bigmin_eq_arg j P F : P j -> (forall i, P i -> F i <= x) -> \big[min/x]_(i | P i) F i = F [arg min_(i < j | P i) F i]. Proof. move=> Pi0; case: arg_minP => //= i Pi PF PFx. apply/eqP; rewrite eq_le bigmin_le_cond //=. by apply/bigmin_geP; split => //; exact: PFx. Qed. Lemma bigmax_eq_arg j P F : P j -> (forall i, P i -> x <= F i) -> \big[max/x]_(i | P i) F i = F [arg max_(i > j | P i) F i]. Proof. move=> Pi0; case: arg_maxP => //= i Pi PF PxF. apply/eqP; rewrite eq_le le_bigmax_cond // andbT. by apply/bigmax_leP; split => //; exact: PxF. Qed. Lemma eq_bigmin j P F : P j -> (forall i, P i -> F i <= x) -> {i0 | i0 \in P & \big[min/x]_(i | P i) F i = F i0}. Proof. by move=> Pi0 Hx; rewrite (bigmin_eq_arg Pi0) //; eexists=> //; case: arg_minP. Qed. Lemma eq_bigmax j P F : P j -> (forall i, P i -> x <= F i) -> {i0 | i0 \in P & \big[max/x]_(i | P i) F i = F i0}. Proof. by move=> Pi0 Hx; rewrite (bigmax_eq_arg Pi0) //; eexists=> //; case: arg_maxP. Qed. Lemma le_bigmin2 P F1 F2 : (forall i, P i -> F1 i <= F2 i) -> \big[min/x]_(i | P i) F1 i <= \big[min/x]_(i | P i) F2 i. Proof. move=> FG; elim/big_ind2 : _ => // a b e f ba fe. rewrite ge_min 2!le_min ba fe /= andbT. move: (le_total a e) => /orP[/(le_trans ba)-> // | /(le_trans fe)->]. by rewrite orbT. Qed. Lemma le_bigmax2 P F1 F2 : (forall i, P i -> F1 i <= F2 i) -> \big[max/x]_(i | P i) F1 i <= \big[max/x]_(i | P i) F2 i. Proof. move=> FG; elim/big_ind2 : _ => // a b e f ba fe. rewrite le_max 2!ge_max ba fe /= andbT; have [//|/= af] := leP f a. by rewrite (le_trans ba) // (le_trans _ fe) // ltW. Qed. Lemma bigmaxUl (A B : {set I}) F : \big[max/x]_(i in A) F i <= \big[max/x]_(i in A :|: B) F i. Proof. by apply: sub_bigmax => t; rewrite in_setU => ->. Qed. Lemma bigmaxUr (A B : {set I}) F : \big[max/x]_(i in B) F i <= \big[max/x]_(i in A :|: B) F i. Proof. by under [leRHS]eq_bigl do rewrite setUC; apply: bigmaxUl. Qed. Lemma bigminUl (A B : {set I}) F : \big[min/x]_(i in A) F i >= \big[min/x]_(i in A :|: B) F i. Proof. by apply: sub_bigmin => t; rewrite in_setU => ->. Qed. Lemma bigminUr (A B : {set I}) F : \big[min/x]_(i in B) F i >= \big[min/x]_(i in A :|: B) F i. Proof. by under [leLHS]eq_bigl do rewrite setUC; apply: bigminUl. Qed. Lemma bigmaxIl (A B : {set I}) F : \big[max/x]_(i in A) F i >= \big[max/x]_(i in A :&: B) F i. Proof. by apply: sub_bigmax => t; rewrite in_setI => /andP[-> _]. Qed. Lemma bigmaxIr (A B : {set I}) F : \big[max/x]_(i in B) F i >= \big[max/x]_(i in A :&: B) F i. Proof. by under eq_bigl do rewrite setIC; apply: bigmaxIl. Qed. Lemma bigminIl (A B : {set I}) F : \big[min/x]_(i in A) F i <= \big[min/x]_(i in A :&: B) F i. Proof. by apply: sub_bigmin => t; rewrite in_setI => /andP[->_]. Qed. Lemma bigminIr (A B : {set I}) F : \big[min/x]_(i in B) F i <= \big[min/x]_(i in A :&: B) F i. Proof. by under [leRHS]eq_bigl do rewrite setIC; apply: bigminIl. Qed. Lemma bigmaxD (A B : {set I}) F : \big[max/x]_(i in B) F i >= \big[max/x]_(i in B :\: A) F i. Proof. by apply: sub_bigmax => t; rewrite in_setD => /andP[_->]. Qed. Lemma bigminD (A B : {set I}) F : \big[min/x]_(i in B) F i <= \big[min/x]_(i in B :\: A) F i. Proof. by apply: sub_bigmin => t; rewrite in_setD => /andP[_->]. Qed. Lemma bigmaxU (A B : {set I}) F : \big[max/x]_(i in A :|: B) F i = max (\big[max/x]_(i in A) F i) (\big[max/x]_(i in B) F i). Proof. apply: le_anti; rewrite ge_max bigmaxUl bigmaxUr !andbT; apply/bigmax_leP. split=> [|i /[!in_setU]/orP[iA|iB]]; first by rewrite le_max bigmax_ge_id. - by rewrite le_max le_bigmax_cond. - by rewrite le_max orbC le_bigmax_cond. Qed. Lemma bigminU (A B : {set I}) F : \big[min/x]_(i in A :|: B) F i = min (\big[min/x]_(i in A) F i) (\big[min/x]_(i in B) F i). Proof. apply: le_anti; rewrite le_min bigminUl bigminUr !andbT; apply/bigmin_geP. split=> [|i /[!in_setU]/orP[iA|iB]]; first by rewrite ge_min bigmin_le_id. - by rewrite ge_min bigmin_le_cond. - by rewrite ge_min orbC bigmin_le_cond. Qed. Lemma bigmin_set1 j F : \big[min/x]_(i in [set j]) F i = min (F j) x. Proof. exact: big_set1E. Qed. Lemma bigmax_set1 j F : \big[max/x]_(i in [set j]) F i = max (F j) x. Proof. exact: big_set1E. Qed. End bigminmax_finType. Lemma bigmin_imset [I J : finType] x [h : I -> J] [A : {set I}] (F : J -> T) : \big[min/x]_(j in [set h x | x in A]) F j = \big[min/x]_(i in A) F (h i). Proof. by apply: big_imset_idem; apply: minxx. Qed. Lemma bigmax_imset [I J : finType] x [h : I -> J] [A : {set I}] (F : J -> T) : \big[max/x]_(j in [set h x | x in A]) F j = \big[max/x]_(i in A) F (h i). Proof. by apply: big_imset_idem; apply: maxxx. Qed. End TotalTheory. #[global] Hint Resolve le_total : core. #[global] Hint Resolve ge_total : core. #[global] Hint Extern 0 (is_true (_ >=< _)%O) => solve [apply: comparableT] : core. #[global] Hint Resolve sort_le_sorted : core. Arguments min_idPr {disp T x y}. Arguments max_idPl {disp T x y}. Arguments bigmin_mkcond {disp T I r}. Arguments bigmax_mkcond {disp T I r}. Arguments bigminID {disp T I r}. Arguments bigmaxID {disp T I r}. Arguments bigminD1 {disp T I x} j. Arguments bigmaxD1 {disp T I x} j. Arguments bigmin_inf {disp T I x} j. Arguments bigmax_sup {disp T I x} j. Arguments bigmin_eq_arg {disp T I} x j. Arguments bigmax_eq_arg {disp T I} x j. Arguments eq_bigmin {disp T I x} j. Arguments eq_bigmax {disp T I x} j. (* FIXME: some lemmas in the following section should hold for any porderType *) Module Import DualTotalTheory. Section DualTotalTheory. Context {disp : disp_t} {T : orderType disp}. Implicit Type s : seq T. Lemma sorted_filter_gt x s : sorted <=%O s -> [seq y <- s | x < y] = drop (count (<= x) s) s. Proof. move=> s_sorted; rewrite count_le_gt -[LHS]revK -filter_rev. rewrite (@sorted_filter_lt _ T^d); first by rewrite take_rev revK count_rev. by rewrite rev_sorted. Qed. Lemma sorted_filter_ge x s : sorted <=%O s -> [seq y <- s | x <= y] = drop (count (< x) s) s. Proof. move=> s_sorted; rewrite count_lt_ge -[LHS]revK -filter_rev. rewrite (@sorted_filter_le _ T^d); first by rewrite take_rev revK count_rev. by rewrite rev_sorted. Qed. Lemma nth_count_ge x x0 s i : sorted <=%O s -> (count (< x) s <= i < size s)%N -> x <= nth x0 s i. Proof. move=> ss /andP[ige ilt]; rewrite -(subnKC ige) -nth_drop -sorted_filter_ge //. apply/(all_nthP _ (filter_all _ _)). by rewrite size_filter ltn_subLR // count_lt_ge subnK // count_size. Qed. Lemma nth_count_gt x x0 s i : sorted <=%O s -> (count (<= x) s <= i < size s)%N -> x < nth x0 s i. Proof. move=> ss /andP[ige ilt]; rewrite -(subnKC ige) -nth_drop -sorted_filter_gt //. apply/(all_nthP _ (filter_all _ _)). by rewrite size_filter ltn_subLR // count_le_gt subnK // count_size. Qed. Lemma nth_count_eq x x0 s i : sorted <=%O s -> (count (< x) s <= i < count (<= x) s)%N -> nth x0 s i = x. Proof. move=> ss /andP[ige ilt]; apply/le_anti. by rewrite nth_count_le// nth_count_ge// ige (leq_trans ilt (count_size _ _)). Qed. End DualTotalTheory. End DualTotalTheory. (* contra lemmas *) Section ContraTheory. Context {disp1 disp2 : disp_t} {T1 : porderType disp1} {T2 : orderType disp2}. Implicit Types (x y : T1) (z t : T2) (b : bool) (m n : nat) (P : Prop). Lemma contraTle b z t : (t < z -> ~~ b) -> (b -> z <= t). Proof. exact: comparable_contraTle. Qed. Lemma contraTlt b z t : (t <= z -> ~~ b) -> (b -> z < t). Proof. exact: comparable_contraTlt. Qed. Lemma contraPle P z t : (t < z -> ~ P) -> (P -> z <= t). Proof. exact: comparable_contraPle. Qed. Lemma contraPlt P z t : (t <= z -> ~ P) -> (P -> z < t). Proof. exact: comparable_contraPlt. Qed. Lemma contraNle b z t : (t < z -> b) -> (~~ b -> z <= t). Proof. exact: comparable_contraNle. Qed. Lemma contraNlt b z t : (t <= z -> b) -> (~~ b -> z < t). Proof. exact: comparable_contraNlt. Qed. Lemma contra_not_le P z t : (t < z -> P) -> (~ P -> z <= t). Proof. exact: comparable_contra_not_le. Qed. Lemma contra_not_lt P z t : (t <= z -> P) -> (~ P -> z < t). Proof. exact: comparable_contra_not_lt. Qed. Lemma contraFle b z t : (t < z -> b) -> (b = false -> z <= t). Proof. exact: comparable_contraFle. Qed. Lemma contraFlt b z t : (t <= z -> b) -> (b = false -> z < t). Proof. exact: comparable_contraFlt. Qed. Lemma contra_leq_le m n z t : (t < z -> (n < m)%N) -> ((m <= n)%N -> z <= t). Proof. exact: comparable_contra_leq_le. Qed. Lemma contra_leq_lt m n z t : (t <= z -> (n < m)%N) -> ((m <= n)%N -> z < t). Proof. exact: comparable_contra_leq_lt. Qed. Lemma contra_ltn_le m n z t : (t < z -> (n <= m)%N) -> ((m < n)%N -> z <= t). Proof. exact: comparable_contra_ltn_le. Qed. Lemma contra_ltn_lt m n z t : (t <= z -> (n <= m)%N) -> ((m < n)%N -> z < t). Proof. exact: comparable_contra_ltn_lt. Qed. Lemma contra_le x y z t : (t < z -> y < x) -> (x <= y -> z <= t). Proof. exact: comparable_contra_le. Qed. Lemma contra_le_lt x y z t : (t <= z -> y < x) -> (x <= y -> z < t). Proof. exact: comparable_contra_le_lt. Qed. Lemma contra_lt_le x y z t : (t < z -> y <= x) -> (x < y -> z <= t). Proof. exact: comparable_contra_lt_le. Qed. Lemma contra_lt x y z t : (t <= z -> y <= x) -> (x < y -> z < t). Proof. exact: comparable_contra_lt. Qed. End ContraTheory. Section TotalMonotonyTheory. Context {disp disp' : disp_t} {T : orderType disp} {T' : porderType disp'}. Context (D : {pred T}) (f : T -> T'). Implicit Types (x y z : T) (u v w : T'). Let leT_anti := @le_anti _ T. Let leT'_anti := @le_anti _ T'. Let ltT_neqAle := @lt_neqAle _ T. Let ltT'_neqAle := @lt_neqAle _ T'. Let ltT_def := @lt_def _ T. Let leT_total := @le_total _ T. Lemma le_mono : {homo f : x y / x < y} -> {mono f : x y / x <= y}. Proof. exact: total_homo_mono. Qed. Lemma le_nmono : {homo f : x y /~ x < y} -> {mono f : x y /~ x <= y}. Proof. by apply: total_homo_mono => // x y; rewrite eq_sym. Qed. Lemma le_mono_in : {in D &, {homo f : x y / x < y}} -> {in D &, {mono f : x y / x <= y}}. Proof. exact: total_homo_mono_in. Qed. Lemma le_nmono_in : {in D &, {homo f : x y /~ x < y}} -> {in D &, {mono f : x y /~ x <= y}}. Proof. by apply: total_homo_mono_in => // x y; rewrite eq_sym. Qed. End TotalMonotonyTheory. End TotalTheory. Module Import CDistrLatticeTheory. Section CDistrLatticeTheory. Context {disp : disp_t} {L : cDistrLatticeType disp}. Implicit Types (x y z : L). Lemma rcomplPmeet x y z : ((x `&` y) `|` z) `&` rcompl x y z = x `&` y. Proof. exact: rcomplPmeet. Qed. Lemma rcomplPjoin x y z : ((y `|` x) `&` z) `|` rcompl x y z = y `|` x. Proof. exact: rcomplPjoin. Qed. Lemma rcomplKI x y z : x <= y -> (x `|` z) `&` rcompl x y z = x. Proof. by move=> lexy; have := rcomplPmeet x y z; rewrite (meet_l lexy). Qed. Lemma rcomplKU x y z : x <= y -> (y `&` z) `|` rcompl x y z = y. Proof. by move=> lexy; have := rcomplPjoin x y z; rewrite (join_l lexy). Qed. End CDistrLatticeTheory. End CDistrLatticeTheory. Module Import CBDistrLatticeTheory. Section CBDistrLatticeTheory. Context {disp : disp_t} {L : cbDistrLatticeType disp}. Implicit Types (x y z : L). Lemma diffErcompl x y : x `\` y = rcompl \bot x y. Proof. exact: diffErcompl. Qed. Lemma diffKI x y : y `&` (x `\` y) = \bot. Proof. by have := rcomplKI y (le0x x); rewrite join0x diffErcompl. Qed. Lemma diffIK x y : (x `\` y) `&` y = \bot. Proof. by rewrite meetC diffKI. Qed. Lemma meetIB z x y : (z `&` y) `&` (x `\` y) = \bot. Proof. by rewrite -meetA diffKI meetx0. Qed. Lemma meetBI z x y : (x `\` y) `&` (z `&` y) = \bot. Proof. by rewrite meetC meetIB. Qed. Lemma joinIB y x : (x `&` y) `|` (x `\` y) = x. Proof. by rewrite diffErcompl rcomplKU. Qed. Lemma joinBI y x : (x `\` y) `|` (x `&` y) = x. Proof. by rewrite joinC joinIB. Qed. Lemma joinIBC y x : (y `&` x) `|` (x `\` y) = x. Proof. by rewrite meetC joinIB. Qed. Lemma joinBIC y x : (x `\` y) `|` (y `&` x) = x. Proof. by rewrite meetC joinBI. Qed. Lemma leBx x y : x `\` y <= x. Proof. by rewrite -[leRHS](joinIB y) leUr. Qed. Hint Resolve leBx : core. Lemma diffxx x : x `\` x = \bot. Proof. by have := diffKI x x; rewrite meet_r. Qed. Lemma leBl z x y : x <= y -> x `\` z <= y `\` z. Proof. rewrite -[leLHS](joinIB z) -[leRHS](joinIB z). by rewrite leU2E ?meetIB ?meetBI // => /andP []. Qed. Lemma diffKU y x : y `|` (x `\` y) = y `|` x. Proof. apply/eqP; rewrite eq_le leU2 //= leUx leUl. by apply/meet_idPl; have := joinIB y x; rewrite joinIl join_l. Qed. Lemma diffUK y x : (x `\` y) `|` y = x `|` y. Proof. by rewrite joinC diffKU joinC. Qed. Lemma leBKU y x : y <= x -> y `|` (x `\` y) = x. Proof. by move=> /join_r {2}<-; rewrite diffKU. Qed. Lemma leBUK y x : y <= x -> (x `\` y) `|` y = x. Proof. by move=> leyx; rewrite joinC leBKU. Qed. Lemma leBLR x y z : (x `\` y <= z) = (x <= y `|` z). Proof. apply/idP/idP; first by move=> /join_r <-; rewrite joinA diffKU joinAC leUr. by rewrite -{1}[x](joinIB y) => /(leU2r_le (diffIK _ _)). Qed. Lemma diffUx x y z : (x `|` y) `\` z = (x `\` z) `|` (y `\` z). Proof. apply/eqP; rewrite eq_le leUx !leBl ?leUr ?leUl ?andbT //. by rewrite leBLR joinA diffKU joinAC diffKU joinAC -joinA leUr. Qed. Lemma diff_eq0 x y : (x `\` y == \bot) = (x <= y). Proof. by rewrite -lex0 leBLR joinx0. Qed. Lemma joinxB x y z : x `|` (y `\` z) = ((x `|` y) `\` z) `|` (x `&` z). Proof. by rewrite diffUx joinAC joinBI. Qed. Lemma joinBx x y z : (y `\` z) `|` x = ((y `|` x) `\` z) `|` (z `&` x). Proof. by rewrite ![_ `|` x]joinC ![_ `&` x]meetC joinxB. Qed. Lemma leBr z x y : x <= y -> z `\` y <= z `\` x. Proof. by move=> lexy; rewrite leBLR joinxB meet_r ?leBUK ?leUr ?lexUl. Qed. Lemma leB2 x y z t : x <= z -> t <= y -> x `\` y <= z `\` t. Proof. by move=> /(@leBl t) ? /(@leBr x) /le_trans ->. Qed. Lemma meet_eq0E_diff z x y : x <= z -> (x `&` y == \bot) = (x <= z `\` y). Proof. move=> xz; apply/idP/idP; last by move=> /meet_r <-; rewrite -meetA meetBI. by move=> /eqP xIy_eq0; rewrite -[x](joinIB y) xIy_eq0 join0x leBl. Qed. Lemma leBRL x y z : (x <= z `\` y) = (x <= z) && (x `&` y == \bot). Proof. apply/idP/idP => [xyz|]; first by rewrite (@meet_eq0E_diff z) // (le_trans xyz). by move=> /andP [?]; rewrite -meet_eq0E_diff. Qed. Lemma eq_diff x y z : (x `\` y == z) = (z <= x <= y `|` z) && (z `&` y == \bot). Proof. by rewrite eq_le leBLR leBRL andbCA andbA. Qed. Lemma diffxU x y z : z `\` (x `|` y) = (z `\` x) `&` (z `\` y). Proof. apply/eqP; rewrite eq_le lexI !leBr ?leUl ?leUr //=. rewrite leBRL leIx2 ?leBx //= meetUr meetAC diffIK -meetA diffIK. by rewrite meet0x meetx0 joinx0. Qed. Lemma diffx0 x : x `\` \bot = x. Proof. by apply/eqP; rewrite eq_diff join0x meetx0 lexx eqxx. Qed. Lemma diff0x x : \bot `\` x = \bot. Proof. by apply/eqP; rewrite eq_diff joinx0 meet0x lexx eqxx le0x. Qed. Lemma diffIx x y z : (x `&` y) `\` z = (x `\` z) `&` (y `\` z). Proof. apply/eqP; rewrite eq_diff joinIr ?leI2 ?diffKU ?leUr ?leBx //=. by rewrite -meetA diffIK meetx0. Qed. Lemma meetxB x y z : x `&` (y `\` z) = (x `&` y) `\` z. Proof. by rewrite diffIx -{1}[x](joinBI z) meetUl meetIB joinx0. Qed. Lemma meetBx x y z : (x `\` y) `&` z = (x `&` z) `\` y. Proof. by rewrite ![_ `&` z]meetC meetxB. Qed. Lemma diffxI x y z : x `\` (y `&` z) = (x `\` y) `|` (x `\` z). Proof. apply/eqP; rewrite eq_diff leUx !leBx //= joinIl joinA joinCA !diffKU. rewrite joinCA -joinA [_ `|` x]joinC ![x `|` _]join_l //. by rewrite -joinIl leUr /= meetUl {1}[_ `&` z]meetC ?meetBI joinx0. Qed. Lemma diffBx x y z : (x `\` y) `\` z = x `\` (y `|` z). Proof. apply/eqP; rewrite eq_diff leBr ?leUl //=. by rewrite diffxU joinIr diffKU -joinIr meet_l ?leUr //= -meetA diffIK meetx0. Qed. Lemma diffxB x y z : x `\` (y `\` z) = (x `\` y) `|` (x `&` z). Proof. rewrite -[y in RHS](joinIB z) diffxU joinIl diffxI -joinA joinBI join_r //. by rewrite joinBx meetKU meetA meetAC diffIK meet0x joinx0 meet_r. Qed. Lemma joinBK x y : (y `|` x) `\` x = (y `\` x). Proof. by rewrite diffUx diffxx joinx0. Qed. Lemma joinBKC x y : (x `|` y) `\` x = (y `\` x). Proof. by rewrite diffUx diffxx join0x. Qed. Lemma disj_le x y : x `&` y == \bot -> x <= y = (x == \bot). Proof. by rewrite [x == \bot]eq_sym -eq_meetl => /eqP ->. Qed. Lemma disj_leC x y : y `&` x == \bot -> x <= y = (x == \bot). Proof. by rewrite meetC => /disj_le. Qed. Lemma disj_diffl x y : x `&` y == \bot -> x `\` y = x. Proof. by move=> dxy; apply/eqP; rewrite eq_diff dxy lexx leUr. Qed. Lemma disj_diffr x y : x `&` y == \bot -> y `\` x = y. Proof. by rewrite meetC => /disj_diffl. Qed. Lemma lt0B x y : x < y -> \bot < y `\` x. Proof. by move=> ?; rewrite lt_leAnge le0x leBLR joinx0 /= lt_geF. Qed. End CBDistrLatticeTheory. End CBDistrLatticeTheory. Module Import CTDistrLatticeTheory. Section CTDistrLatticeTheory. Context {disp : disp_t} {L : ctDistrLatticeType disp}. Implicit Types (x y z : L). Lemma codiffErcompl x y : codiff x y = rcompl x \top y. Proof. exact: codiffErcompl. Qed. (* TODO: complete this theory module *) End CTDistrLatticeTheory. End CTDistrLatticeTheory. Module Import CTBDistrLatticeTheory. Section CTBDistrLatticeTheory. Context {disp : disp_t} {L : ctbDistrLatticeType disp}. Implicit Types (x y z : L). Lemma complEdiff x : ~` x = \top `\` x. Proof. exact: complEdiff. Qed. #[deprecated(since="mathcomp 2.3.0", note="Use complEdiff instead.")] Notation complE := complEdiff. Lemma complEcodiff x : ~` x = codiff \bot x. Proof. exact: complEcodiff. Qed. Lemma complErcompl x : ~` x = rcompl \bot \top x. Proof. by rewrite complEdiff diffErcompl. Qed. Lemma diff1x x : \top `\` x = ~` x. Proof. exact/esym/complEdiff. Qed. Lemma diffE x y : x `\` y = x `&` ~` y. Proof. by rewrite complEdiff meetxB meetx1. Qed. Lemma complK : involutive (@compl _ L). Proof. by move=> x; rewrite !complEdiff diffxB diffxx meet1x join0x. Qed. Lemma compl_inj : injective (@compl _ L). Proof. exact/inv_inj/complK. Qed. Lemma disj_leC x y : (x `&` y == \bot) = (x <= ~` y). Proof. by rewrite -diff_eq0 diffE complK. Qed. Lemma leCx x y : (~` x <= y) = (~` y <= x). Proof. by rewrite !complEdiff !leBLR joinC. Qed. Lemma lexC x y : (x <= ~` y) = (y <= ~` x). Proof. by rewrite -[x in LHS]complK leCx complK. Qed. Lemma leC x y : (~` x <= ~` y) = (y <= x). Proof. by rewrite leCx complK. Qed. Lemma complU x y : ~` (x `|` y) = ~` x `&` ~` y. Proof. by rewrite !complEdiff diffxU. Qed. Lemma complI x y : ~` (x `&` y) = ~` x `|` ~` y. Proof. by rewrite !complEdiff diffxI. Qed. Lemma joinxC x : x `|` ~` x = \top. Proof. by rewrite complEdiff diffKU joinx1. Qed. Lemma joinCx x : ~` x `|` x = \top. Proof. by rewrite joinC joinxC. Qed. Lemma meetxC x : x `&` ~` x = \bot. Proof. by rewrite complEdiff diffKI. Qed. Lemma meetCx x : ~` x `&` x = \bot. Proof. by rewrite meetC meetxC. Qed. Lemma compl1 : ~` \top = \bot :> L. Proof. by rewrite complEdiff diffxx. Qed. Lemma compl0 : ~` \bot = \top :> L. Proof. by rewrite -compl1 complK. Qed. Lemma complB x y : ~` (x `\` y) = ~` x `|` y. Proof. by rewrite diffE complI complK. Qed. Lemma leBC x y : x `\` y <= ~` y. Proof. by rewrite leBLR joinxC lex1. Qed. Lemma compl_joins (J : Type) (r : seq J) (P : {pred J}) (F : J -> L) : ~` (\join_(j <- r | P j) F j) = \meet_(j <- r | P j) ~` F j. Proof. by elim/big_rec2: _=> [|i x y ? <-]; rewrite ?compl0 ?complU. Qed. Lemma compl_meets (J : Type) (r : seq J) (P : {pred J}) (F : J -> L) : ~` (\meet_(j <- r | P j) F j) = \join_(j <- r | P j) ~` F j. Proof. by elim/big_rec2: _=> [|i x y ? <-]; rewrite ?compl1 ?complI. Qed. End CTBDistrLatticeTheory. End CTBDistrLatticeTheory. (*************) (* FACTORIES *) (*************) (* porderType *) HB.factory Record Preorder_isPOrder (d : disp_t) T of Preorder d T := { le_anti : antisymmetric (@le d T); }. HB.builders Context (d : disp_t) T of Preorder_isPOrder d T. Let ge_anti : antisymmetric (fun x y => @le d T y x). Proof. by move=> x y; rewrite andbC; apply: le_anti. Qed. HB.instance Definition _ := Preorder_isDuallyPOrder.Build d T le_anti ge_anti. HB.end. HB.factory Record isPOrder (d : disp_t) T of Choice T := { le : rel T; lt : rel T; lt_def : forall x y, lt x y = (y != x) && (le x y); le_refl : reflexive le; le_anti : antisymmetric le; le_trans : transitive le; }. HB.builders Context (d : disp_t) T of isPOrder d T. Let lt_le_def x y : lt x y = le x y && ~~ le y x. Proof. rewrite lt_def andbC; case /boolP: (le x y) => //= xy. have [->|/negP xyE /=] := eqVneq y x; first by rewrite le_refl. by apply/esym/negP => yx; apply/xyE/eqP/le_anti; rewrite yx. Qed. HB.instance Definition _ := isPreorder.Build d T lt_le_def le_refl le_trans. HB.instance Definition _ := Preorder_isPOrder.Build d T le_anti. HB.end. HB.factory Record Le_isPOrder (d : disp_t) T of Choice T := { le : rel T; le_refl : reflexive le; le_anti : antisymmetric le; le_trans : transitive le; }. HB.builders Context (d : disp_t) T of Le_isPOrder d T. (* TODO: print nice error message when keyed type is not provided *) HB.instance Definition _ := @Le_isPreorder.Build d T le le_refl le_trans. HB.instance Definition _ := @Preorder_isPOrder.Build d T le_anti. HB.end. HB.factory Record LtLe_isPOrder (d : disp_t) T of Choice T := { le : rel T; lt : rel T; le_def : forall x y, le x y = (x == y) || lt x y; lt_irr : irreflexive lt; lt_trans : transitive lt; }. HB.builders Context (d : disp_t) T of LtLe_isPOrder d T. HB.instance Definition _ := @LtLe_isPreorder.Build d T le lt le_def lt_irr lt_trans. Let le_anti : antisymmetric le. Proof. move=> x y; rewrite !le_def [y == _]eq_sym. have [//|neq_xy/=] := eqVneq x y => /andP[xy yx]. by have := lt_trans xy yx; rewrite lt_irr. Qed. HB.instance Definition _ := @Preorder_isPOrder.Build d T le_anti. HB.end. HB.factory Record Lt_isPOrder (d : disp_t) T of Choice T := { lt : rel T; lt_irr : irreflexive lt; lt_trans : transitive lt; }. HB.builders Context d T of Lt_isPOrder d T. #[warning="-HB.no-new-instance"] HB.instance Definition _ := @LtLe_isPOrder.Build d T _ lt (fun _ _ => erefl) lt_irr lt_trans. HB.end. (* meetSemilatticeType and joinSemilatticeType *) HB.factory Record POrder_Meet_isSemilattice d T of POrder d T := { meet : T -> T -> T; meetC : commutative meet; meetA : associative meet; leEmeet : forall x y, (x <= y) = (meet x y == x); }. HB.builders Context d T of POrder_Meet_isSemilattice d T. Fact meetxx : idempotent_op meet. Proof. by move=> x; apply/eqP; rewrite -leEmeet. Qed. Fact lexI x y z : (x <= meet y z) = (x <= y) && (x <= z). Proof. rewrite !leEmeet; apply/eqP/andP => [<-|[/eqP<- /eqP<-]]. split; apply/eqP; last by rewrite meetA -meetA meetxx. by rewrite -!meetA (meetC z) (meetA y) meetxx. by rewrite -!meetA (meetC z) -meetA (meetA y) !meetxx. Qed. HB.instance Definition _ := @POrder_isMeetSemilattice.Build d T meet lexI. HB.end. HB.factory Record POrder_Join_isSemilattice d T of POrder d T := { join : T -> T -> T; joinC : commutative join; joinA : associative join; leEjoin : forall x y, (y <= x) = (join x y == x); }. HB.builders Context d T of POrder_Join_isSemilattice d T. Fact joinxx : idempotent_op join. Proof. by move=> x; apply/eqP; rewrite -leEjoin. Qed. Fact leUx x y z : (join x y <= z) = (x <= z) && (y <= z). rewrite !leEjoin; apply/eqP/andP => [<-|[/eqP<- /eqP<-]]. split; apply/eqP; last by rewrite joinA -joinA joinxx. by rewrite -joinA (joinC _ x) (joinA x) joinxx. by rewrite -!joinA (joinC y) -joinA (joinA x) !joinxx. Qed. HB.instance Definition _ := @POrder_isJoinSemilattice.Build d T join leUx. HB.end. (* latticeType *) HB.factory Record POrder_MeetJoin_isLattice d T of POrder d T := { meet : T -> T -> T; join : T -> T -> T; meetP : forall x y z, (x <= meet y z) = (x <= y) && (x <= z); joinP : forall x y z, (join x y <= z) = (x <= z) && (y <= z); }. HB.builders Context d T of POrder_MeetJoin_isLattice d T. HB.instance Definition _ := @POrder_isMeetSemilattice.Build d T meet meetP. HB.instance Definition _ := @POrder_isJoinSemilattice.Build d T join joinP. HB.end. HB.factory Record POrder_isLattice d T of POrder d T := { meet : T -> T -> T; join : T -> T -> T; meetC : commutative meet; joinC : commutative join; meetA : associative meet; joinA : associative join; joinKI : forall y x, meet x (join x y) = x; meetKU : forall y x, join x (meet x y) = x; leEmeet : forall x y, (x <= y) = (meet x y == x); }. HB.builders Context d T of POrder_isLattice d T. Fact leEjoin x y : (y <= x) = (join x y == x). Proof. rewrite leEmeet; apply/eqP/eqP => <-. by rewrite meetC meetKU. by rewrite joinC joinKI. Qed. Fact meetxx : idempotent_op meet. Proof. by move=> x; apply/eqP; rewrite -leEmeet. Qed. Fact lexI x y z : (x <= meet y z) = (x <= y) && (x <= z). Proof. rewrite !leEmeet; apply/eqP/andP => [<-|[/eqP<- /eqP<-]]. split; apply/eqP; last by rewrite meetA -meetA meetxx. by rewrite -!meetA (meetC z) (meetA y) meetxx. by rewrite -!meetA (meetC z) -meetA (meetA y) !meetxx. Qed. Fact joinxx : idempotent_op join. Proof. by move=> x; apply/eqP; rewrite -leEjoin. Qed. Fact leUx x y z : (join x y <= z) = (x <= z) && (y <= z). rewrite !leEjoin; apply/eqP/andP => [<-|[/eqP<- /eqP<-]]. split; apply/eqP; last by rewrite joinA -joinA joinxx. by rewrite -joinA (joinC _ x) (joinA x) joinxx. by rewrite -!joinA (joinC y) -joinA (joinA x) !joinxx. Qed. HB.instance Definition _ := @POrder_MeetJoin_isLattice.Build d T meet join lexI leUx. HB.end. (* distrLatticeType *) HB.factory Record Lattice_Meet_isDistrLattice d T of Lattice d T := { meetUl : @left_distributive T T meet join; }. HB.builders Context d T of Lattice_Meet_isDistrLattice d T. Let meetUr : right_distributive (@meet _ T) (@join _ T). Proof. by move=> x y z; rewrite ![x `&` _]meetC meetUl. Qed. Let joinIl : left_distributive (@join _ T) (@meet _ T). Proof. by move=> x y z; rewrite meetUr joinIK meetUl -joinA meetUKC. Qed. HB.instance Definition _ := Lattice_isDistributive.Build d T meetUl joinIl. HB.end. HB.factory Record POrder_Meet_isDistrLattice d T of POrder d T := { meet : T -> T -> T; join : T -> T -> T; meetC : commutative meet; joinC : commutative join; meetA : associative meet; joinA : associative join; joinKI : forall y x, meet x (join x y) = x; meetKU : forall y x, join x (meet x y) = x; leEmeet : forall x y, (x <= y) = (meet x y == x); meetUl : left_distributive meet join; }. HB.builders Context d T of POrder_Meet_isDistrLattice d T. HB.instance Definition _ := @POrder_isLattice.Build d T meet join meetC joinC meetA joinA joinKI meetKU leEmeet. HB.instance Definition _ := Lattice_Meet_isDistrLattice.Build d T meetUl. HB.end. HB.factory Record isMeetJoinDistrLattice (d : disp_t) T of Choice T := { le : rel T; lt : rel T; meet : T -> T -> T; join : T -> T -> T; le_def : forall x y : T, le x y = (meet x y == x); lt_def : forall x y : T, lt x y = (y != x) && le x y; meetC : commutative meet; joinC : commutative join; meetA : associative meet; joinA : associative join; joinKI : forall y x : T, meet x (join x y) = x; meetKU : forall y x : T, join x (meet x y) = x; meetUl : left_distributive meet join; meetxx : idempotent_op meet; }. HB.builders Context d T of isMeetJoinDistrLattice d T. Fact le_refl : reflexive le. Proof. by move=> x; rewrite le_def meetxx. Qed. Fact le_anti : antisymmetric le. Proof. by move=> x y; rewrite !le_def meetC => /andP [] /eqP {2}<- /eqP ->. Qed. Fact le_trans : transitive le. Proof. move=> y x z; rewrite !le_def => /eqP lexy /eqP leyz; apply/eqP. by rewrite -[in LHS]lexy -meetA leyz lexy. Qed. Fact lt_le_def x y : lt x y = (le x y) && ~~ (le y x). Proof. rewrite lt_def andbC; case/boolP: (le x y) => //= xy. congr negb; apply/eqP/idP => [->|yx]; first exact/le_refl. by apply/le_anti/andP; split. Qed. HB.instance Definition _ := isPreorder.Build d T lt_le_def le_refl le_trans. HB.instance Definition _ := Preorder_isPOrder.Build d T le_anti. HB.instance Definition _ := @POrder_Meet_isDistrLattice.Build d T meet join meetC joinC meetA joinA joinKI meetKU le_def meetUl. HB.end. (* complemented lattices *) HB.factory Record BDistrLattice_hasSectionalComplement d T of BDistrLattice d T := { diff : T -> T -> T; diffKI : forall x y, y `&` diff x y = \bot; joinIB : forall x y, (x `&` y) `|` diff x y = x; }. Module hasRelativeComplement. #[deprecated(since="mathcomp 2.3.0", note="Use BDistrLattice_hasSectionalComplement.Build instead.")] Notation Build d T := (BDistrLattice_hasSectionalComplement.Build d T) (only parsing). End hasRelativeComplement. #[deprecated(since="mathcomp 2.3.0", note="Use BDistrLattice_hasSectionalComplement instead.")] Notation hasRelativeComplement d T := (BDistrLattice_hasSectionalComplement d T) (only parsing). HB.builders Context d T of BDistrLattice_hasSectionalComplement d T. Definition rcompl x y z := (x `&` y) `|` diff (y `|` x) z. Fact rcomplPmeet x y z : ((x `&` y) `|` z) `&` rcompl x y z = x `&` y. Proof. by rewrite meetUr joinIKC meetUl diffKI joinx0 meetKU. Qed. Fact rcomplPjoin x y z : ((y `|` x) `&` z) `|` rcompl x y z = y `|` x. Proof. by rewrite joinCA joinIB joinA meetUK joinC. Qed. HB.instance Definition _ := @DistrLattice_hasRelativeComplement.Build d T rcompl rcomplPmeet rcomplPjoin. Fact diffErcompl x y : diff x y = rcompl \bot x y. Proof. by rewrite /rcompl meet0x join0x joinx0. Qed. HB.instance Definition _ := @CDistrLattice_hasSectionalComplement.Build d T diff diffErcompl. HB.end. HB.factory Record TDistrLattice_hasDualSectionalComplement d T of TDistrLattice d T := { codiff : T -> T -> T; codiffKU : forall x y, y `|` codiff x y = \top; meetUB : forall x y, (x `|` y) `&` codiff x y = x; }. HB.builders Context d T of TDistrLattice_hasDualSectionalComplement d T. Definition rcompl x y z := (y `|` x) `&` codiff (x `&` y) z. Fact rcomplPmeet x y z : ((x `&` y) `|` z) `&` rcompl x y z = x `&` y. Proof. by rewrite meetCA meetUB meetA joinIK. Qed. Fact rcomplPjoin x y z : ((y `|` x) `&` z) `|` rcompl x y z = y `|` x. Proof. by rewrite joinIr meetUKC joinIl codiffKU meetx1 joinKI. Qed. HB.instance Definition _ := @DistrLattice_hasRelativeComplement.Build d T rcompl rcomplPmeet rcomplPjoin. Fact codiffErcompl x y : codiff x y = rcompl x \top y. Proof. by rewrite /rcompl join1x meet1x meetx1. Qed. HB.instance Definition _ := @CDistrLattice_hasDualSectionalComplement.Build d T codiff codiffErcompl. HB.end. HB.factory Record CBDistrLattice_hasComplement d T of CBDistrLattice d T & hasTop d T := { compl : T -> T; complEdiff : forall x, compl x = (\top : T) `\` x; (* FIXME *) }. Module hasComplement. #[deprecated(since="mathcomp 2.3.0", note="Use CBDistrLattice_hasComplement.Build instead.")] Notation Build d T := (CBDistrLattice_hasComplement.Build d T) (only parsing). End hasComplement. #[deprecated(since="mathcomp 2.3.0", note="Use CBDistrLattice_hasComplement instead.")] Notation hasComplement d T := (CBDistrLattice_hasComplement d T) (only parsing). HB.builders Context d T of CBDistrLattice_hasComplement d T. HB.instance Definition _ := @CDistrLattice_hasDualSectionalComplement.Build d T (fun x y => rcompl x \top y) (fun _ _ => erefl). Fact complEcodiff (x : T) : compl x = codiff (\bot : T) x. Proof. by rewrite complEdiff diffErcompl. Qed. HB.instance Definition _ := @CDistrLattice_hasComplement.Build d T compl complEdiff complEcodiff. HB.end. HB.factory Record CTDistrLattice_hasComplement d T of CTDistrLattice d T & hasBottom d T := { compl : T -> T; complEcodiff : forall x, compl x = codiff (\bot : T) x; }. HB.builders Context d T of CTDistrLattice_hasComplement d T. HB.instance Definition _ := @CDistrLattice_hasSectionalComplement.Build d T (fun x y => rcompl (\bot : T) x y) (fun _ _ => erefl). Fact complEdiff (x : T) : compl x = (\top : T) `\` x. Proof. by rewrite complEcodiff codiffErcompl. Qed. HB.instance Definition _ := @CDistrLattice_hasComplement.Build d T compl complEdiff complEcodiff. HB.end. HB.factory Record TBDistrLattice_hasComplement d T of TBDistrLattice d T := { compl : T -> T; joinxC : forall x, x `|` compl x = \top; meetxC : forall x, x `&` compl x = \bot; }. HB.builders Context d T of TBDistrLattice_hasComplement d T. Definition diff x y := x `&` compl y. Definition codiff x y := x `|` compl y. Definition rcompl x y z := (x `&` y) `|` diff (y `|` x) z. Fact diffKI x y : y `&` diff x y = \bot. Proof. by rewrite meetCA meetxC meetx0. Qed. Fact joinIB x y : (x `&` y) `|` diff x y = x. Proof. by rewrite -meetUr joinxC meetx1. Qed. HB.instance Definition _ := @BDistrLattice_hasSectionalComplement.Build d T diff diffKI joinIB. Fact codiffErcompl x y : codiff x y = rcompl x \top y. Proof. by rewrite /rcompl /diff join1x meetx1 meet1x. Qed. HB.instance Definition _ := @CDistrLattice_hasDualSectionalComplement.Build d T codiff codiffErcompl. Fact complEdiff x : compl x = diff \top x. Proof. exact/esym/meet1x. Qed. Fact complEcodiff x : compl x = codiff \bot x. Proof. exact/esym/join0x. Qed. HB.instance Definition _ := @CDistrLattice_hasComplement.Build d T compl complEdiff complEcodiff. HB.end. (* orderType *) HB.factory Record Lattice_isTotal d T of Lattice d T := { le_total : total (<=%O : rel T) }. HB.builders Context d T of Lattice_isTotal d T. Fact meetUl : @left_distributive T T meet join. Proof. pose leP x y := lcomparable_leP (le_total x y); move=> x y z; apply/esym. by case: (leP x y) (leP x z) (leP y z) => [|/ltW] xy [|/ltW] xz [|/ltW] yz; (apply/join_idPl || apply/join_idPr) => //; apply: le_trans xy. Qed. HB.instance Definition _ := Lattice_Meet_isDistrLattice.Build d T meetUl. HB.instance Definition _ := DistrLattice_isTotal.Build d T le_total. HB.end. HB.factory Record POrder_isTotal d T of POrder d T := { le_total : total (<=%O : rel T) }. HB.builders Context d T of POrder_isTotal d T. Implicit Types (x y z : T). Let comparableT x y : x >=< y := le_total x y. Fact ltgtP x y : compare x y (min y x) (min x y) (max y x) (max x y) (y == x) (x == y) (x >= y) (x <= y) (x > y) (x < y). Proof. exact: comparable_ltgtP. Qed. Fact leP x y : le_xor_gt x y (min y x) (min x y) (max y x) (max x y) (x <= y) (y < x). Proof. exact: comparable_leP. Qed. Definition meet := @min _ T. Definition join := @max _ T. Fact meetC : commutative meet. Proof. by move=> x y; rewrite /meet; have [] := ltgtP. Qed. Fact joinC : commutative join. Proof. by move=> x y; rewrite /join; have [] := ltgtP. Qed. Fact meetA : associative meet. Proof. move=> x y z; rewrite /meet /min !(fun_if, if_arg). case: (leP z y) (leP y x) (leP z x) => [] zy [] yx [] zx//=. by have := le_lt_trans (le_trans zy yx) zx; rewrite ltxx. by apply/eqP; rewrite eq_le zx ltW// (lt_trans yx). Qed. Fact joinA : associative join. Proof. move=> x y z; rewrite /meet /min !(fun_if, if_arg). case: (leP z y) (leP y x) (leP z x) => [] zy [] yx [] zx//=. by have := le_lt_trans (le_trans zy yx) zx; rewrite ltxx. by apply/eqP; rewrite eq_le zx ltW// (lt_trans yx). Qed. Fact joinKI y x : meet x (join x y) = x. Proof. rewrite /meet /join /min /max !(fun_if, if_arg). by have []// := ltgtP x y; rewrite ltxx. Qed. Fact meetKU y x : join x (meet x y) = x. Proof. rewrite /meet /join /min /max !(fun_if, if_arg). by have []// := ltgtP x y; rewrite ltxx. Qed. Fact leEmeet x y : (x <= y) = (meet x y == x). Proof. by rewrite /meet; case: leP => ?; rewrite ?eqxx ?lt_eqF. Qed. HB.instance Definition _ := @POrder_isLattice.Build d T meet join meetC joinC meetA joinA joinKI meetKU leEmeet. HB.instance Definition _ := Lattice_isTotal.Build d T comparableT. HB.end. HB.factory Record isOrder (d : disp_t) T of Choice T := { le : rel T; lt : rel T; meet : T -> T -> T; join : T -> T -> T; lt_def : forall x y, lt x y = (y != x) && le x y; meet_def : forall x y, meet x y = if lt x y then x else y; join_def : forall x y, join x y = if lt x y then y else x; le_anti : antisymmetric le; le_trans : transitive le; le_total : total le; }. HB.builders Context d T of isOrder d T. Fact le_refl : reflexive le. Proof. by move=> x; case: (le x x) (le_total x x). Qed. Fact lt_le_def x y : lt x y = (le x y) && ~~ (le y x). Proof. rewrite lt_def andbC; case/boolP: (le x y) => //= xy. congr negb; apply/eqP/idP => [->|yx]; first exact/le_refl. by apply/le_anti/andP; split. Qed. HB.instance Definition _ := isPreorder.Build d T lt_le_def le_refl le_trans. HB.instance Definition _ := Preorder_isPOrder.Build d T le_anti. Section GeneratedOrder. Local Definition T' := T. HB.instance Definition _ := POrder.on T'. HB.instance Definition _ := POrder_isTotal.Build d T' le_total. Implicit Types (x y z : T'). Fact meetE x y : meet x y = x `&` y. Proof. by rewrite meet_def. Qed. Fact joinE x y : join x y = x `|` y. Proof. by rewrite join_def. Qed. Fact meetC : commutative meet. Proof. by move=> *; rewrite !meetE meetC. Qed. Fact joinC : commutative join. Proof. by move=> *; rewrite !joinE joinC. Qed. Fact meetA : associative meet. Proof. by move=> *; rewrite !meetE meetA. Qed. Fact joinA : associative join. Proof. by move=> *; rewrite !joinE joinA. Qed. Fact joinKI y x : meet x (join x y) = x. Proof. by rewrite meetE joinE joinKI. Qed. Fact meetKU y x : join x (meet x y) = x. Proof. by rewrite meetE joinE meetKU. Qed. Fact meetUl : left_distributive meet join. Proof. by move=> *; rewrite !meetE !joinE meetUl. Qed. Fact meetxx : idempotent_op meet. Proof. by move=> *; rewrite meetE meetxx. Qed. Fact le_def x y : x <= y = (meet x y == x). Proof. by rewrite meetE (eq_meetl x y). Qed. End GeneratedOrder. HB.instance Definition _ := @POrder_Meet_isDistrLattice.Build d T meet join meetC joinC meetA joinA joinKI meetKU le_def meetUl. HB.instance Definition _ := DistrLattice_isTotal.Build d T le_total. HB.end. HB.factory Record LtOrder (d : disp_t) T of Choice T := { le : rel T; lt : rel T; meet : T -> T -> T; join : T -> T -> T; le_def : forall x y, le x y = (x == y) || lt x y; meet_def : forall x y, meet x y = if lt x y then x else y; join_def : forall x y, join x y = if lt x y then y else x; lt_irr : irreflexive lt; lt_trans : transitive lt; lt_total : forall x y, x != y -> lt x y || lt y x; }. HB.builders Context d T of LtOrder d T. Fact lt_def x y : lt x y = (y != x) && le x y. Proof. by rewrite le_def; case: eqVneq => //= ->; rewrite lt_irr. Qed. Fact meet_def_le x y : meet x y = if lt x y then x else y. Proof. by rewrite meet_def lt_def; case: eqP. Qed. Fact join_def_le x y : join x y = if lt x y then y else x. Proof. by rewrite join_def lt_def; case: eqP. Qed. Fact le_anti : antisymmetric le. Proof. move=> x y; rewrite !le_def; case: eqVneq => //= _ /andP [] hxy. by move/(lt_trans hxy); rewrite lt_irr. Qed. Fact le_trans : transitive le. Proof. move=> y x z; rewrite !le_def; case: eqVneq => [->|_] //=. by case: eqVneq => [-> ->|_ hxy /(lt_trans hxy) ->]; rewrite orbT. Qed. Fact le_total : total le. Proof. by move=> x y; rewrite !le_def; case: eqVneq => //; exact: lt_total. Qed. HB.instance Definition _ := isOrder.Build d T lt_def meet_def_le join_def_le le_anti le_trans le_total. HB.end. HB.factory Record MonoTotal disp T of POrder disp T := { disp' : disp_t; T' : orderType disp'; f : T -> T'; f_mono : {mono f : x y / x <= y} }. HB.builders Context disp T of MonoTotal disp T. Fact totalT : total (<=%O : rel T). Proof. by move=> x y; rewrite -!f_mono le_total. Qed. HB.instance Definition _ := POrder_isTotal.Build disp T totalT. HB.end. Module CancelPartial. Import PreCancelPartial. Section CancelPartial. Variables (disp : disp_t) (T : choiceType). Variables (disp' : disp_t) (T' : porderType disp') (f : T -> T'). Section Pcan. Variables (f' : T' -> option T) (f_can : pcancel f f'). Fact anti : antisymmetric (le f). Proof. by move=> ? ? /le_anti; apply: pcan_inj. Qed. Fact lt_def x y : lt f x y = (y != x) && le f x y. Proof. by rewrite /lt lt_def (inj_eq (pcan_inj f_can)). Qed. Definition Pcan := isPOrder.Build disp (Choice.Pack (Choice.class T)) lt_def (@refl T disp' T' f) anti (@trans T disp' T' f). End Pcan. Definition Can f' (f_can : cancel f f') := Pcan (can_pcan f_can). End CancelPartial. End CancelPartial. Notation PCanIsPartial := CancelPartial.Pcan. Notation CanIsPartial := CancelPartial.Can. #[export] HB.instance Definition _ (disp : disp_t) (T : choiceType) (disp' : disp_t) (T' : porderType disp') (f : T -> T') (f' : T' -> option T) (f_can : pcancel f f') := Preorder_isPOrder.Build disp (pcan_type f_can) (CancelPartial.anti f_can). #[export] HB.instance Definition _ (disp : disp_t) (T : choiceType) (disp' : disp_t) (T' : porderType disp') (f : T -> T') (f' : T' -> T) (f_can : cancel f f') := Preorder_isPOrder.Build disp (can_type f_can) (CancelPartial.anti (can_pcan f_can)). Section CancelTotal. Variables (disp : disp_t) (T : choiceType). Variables (disp' : disp_t) (T' : orderType disp') (f : T -> T'). Section PCan. Variables (f' : T' -> option T) (f_can : pcancel f f'). #[local] HB.instance Definition _ := MonoTotal.Build disp (pcan_type f_can) (fun _ _ => erefl). Definition PCanIsTotal : DistrLattice_isTotal _ (pcan_type f_can) := Total.on (pcan_type f_can). End PCan. Section Can. Variables (f' : T' -> T) (f_can : cancel f f'). #[local] HB.instance Definition _ := MonoTotal.Build disp (can_type f_can) (fun _ _ => erefl). Definition CanIsTotal : DistrLattice_isTotal _ (can_type f_can) := Total.on (can_type f_can). End Can. End CancelTotal. HB.factory Record IsoLattice disp T of POrder disp T := { disp' : disp_t; T' : latticeType disp'; f : T -> T'; f' : T' -> T; f_can : cancel f f'; f'_can : cancel f' f; f_mono : {mono f : x y / x <= y}; }. HB.builders Context disp T of IsoLattice disp T. Definition meet (x y : T) := f' (meet (f x) (f y)). Definition join (x y : T) := f' (join (f x) (f y)). Fact meetC : commutative meet. Proof. by move=> x y; rewrite /meet meetC. Qed. Fact joinC : commutative join. Proof. by move=> x y; rewrite /join joinC. Qed. Fact meetA : associative meet. Proof. by move=> y x z; rewrite /meet !f'_can meetA. Qed. Fact joinA : associative join. Proof. by move=> y x z; rewrite /join !f'_can joinA. Qed. Fact joinKI y x : meet x (join x y) = x. Proof. by rewrite /meet /join f'_can joinKI f_can. Qed. Fact meetKI y x : join x (meet x y) = x. Proof. by rewrite /join /meet f'_can meetKU f_can. Qed. Fact meet_eql x y : (x <= y) = (meet x y == x). Proof. by rewrite /meet -(can_eq f_can) f'_can eq_meetl f_mono. Qed. HB.instance Definition _ := POrder_isLattice.Build _ T meetC joinC meetA joinA joinKI meetKI meet_eql. HB.end. HB.factory Record IsoDistrLattice disp T of POrder disp T := { disp' : disp_t; T' : distrLatticeType disp'; f : T -> T'; f' : T' -> T; f_can : cancel f f'; f'_can : cancel f' f; f_mono : {mono f : x y / x <= y}; }. HB.builders Context disp T of IsoDistrLattice disp T. HB.instance Definition _ := IsoLattice.Build _ T f_can f'_can f_mono. Fact meetUl : left_distributive (meet : T -> T -> T) join. Proof. by move=> x y z; rewrite /meet /join /= !f'_can meetUl. Qed. HB.instance Definition _ := Lattice_Meet_isDistrLattice.Build _ T meetUl. HB.end. (* Morphism hierarchy. *) Export OrderMorphismTheory. Lemma omorph_lt (d : disp_t) (T : porderType d) (d' : disp_t) (T' : porderType d') (f : {omorphism T -> T'}) : injective f -> {homo f : x y / x < y}. Proof. by move/inj_homo_lt; apply; apply: omorph_le. Qed. Definition meet_morphism d (T : latticeType d) d' (T' : latticeType d') (f : T -> T') : Prop := {morph f : x y / x `&` y}. Definition join_morphism d (T : latticeType d) d' (T' : latticeType d') (f : T -> T') : Prop := {morph f : x y / x `|` y}. HB.mixin Record isMeetLatticeMorphism d (T : latticeType d) d' (T' : latticeType d') (apply : T -> T') := { omorphI_subproof : meet_morphism apply; }. HB.mixin Record isJoinLatticeMorphism d (T : latticeType d) d' (T' : latticeType d') (apply : T -> T') := { omorphU_subproof : join_morphism apply; }. HB.structure Definition MeetLatticeMorphism d (T : latticeType d) d' (T' : latticeType d') := {f of isMeetLatticeMorphism d T d' T' f & @OrderMorphism d T d' T' f}. HB.structure Definition JoinLatticeMorphism d (T : latticeType d) d' (T' : latticeType d') := {f of isJoinLatticeMorphism d T d' T' f & @OrderMorphism d T d' T' f}. HB.structure Definition LatticeMorphism d (T : latticeType d) d' (T' : latticeType d') := {f of @MeetLatticeMorphism d T d' T' f & @JoinLatticeMorphism d T d' T' f}. HB.factory Record isLatticeMorphism d (T : latticeType d) d' (T' : latticeType d') (f : T -> T') of @OrderMorphism d T d' T' f := { omorphI_subproof : meet_morphism f; omorphU_subproof : join_morphism f; }. HB.builders Context d T d' T' f of isLatticeMorphism d T d' T' f. HB.instance Definition _ := isMeetLatticeMorphism.Build d T d' T' f omorphI_subproof. HB.instance Definition _ := isJoinLatticeMorphism.Build d T d' T' f omorphU_subproof. HB.end. Module LatticeMorphismExports. Notation "{ 'mlmorphism' T -> T' }" := (@MeetLatticeMorphism.type _ T%type _ T'%type) : type_scope. Notation "{ 'jlmorphism' T -> T' }" := (@JoinLatticeMorphism.type _ T%type _ T'%type) : type_scope. Notation "{ 'lmorphism' T -> T' }" := (@LatticeMorphism.type _ T%type _ T'%type) : type_scope. Notation "[ 'mlmorphism' 'of' f 'as' g ]" := (MeetLatticeMorphism.clone _ _ _ _ f%function g) (format "[ 'mlmorphism' 'of' f 'as' g ]") : form_scope. Notation "[ 'mlmorphism' 'of' f ]" := (MeetLatticeMorphism.clone _ _ _ _ f%function _) (format "[ 'mlmorphism' 'of' f ]") : form_scope. Notation "[ 'jlmorphism' 'of' f 'as' g ]" := (JoinLatticeMorphism.clone _ _ _ _ f%function g) (format "[ 'jlmorphism' 'of' f 'as' g ]") : form_scope. Notation "[ 'jlmorphism' 'of' f ]" := (JoinLatticeMorphism.clone _ _ _ _ f%function _) (format "[ 'jlmorphism' 'of' f ]") : form_scope. Notation "[ 'lmorphism' 'of' f 'as' g ]" := (LatticeMorphism.clone _ _ _ _ f%function g) (format "[ 'lmorphism' 'of' f 'as' g ]") : form_scope. Notation "[ 'lmorphism' 'of' f ]" := (LatticeMorphism.clone _ _ _ _ f%function _) (format "[ 'lmorphism' 'of' f ]") : form_scope. End LatticeMorphismExports. HB.export LatticeMorphismExports. Module Import LatticeMorphismTheory. Section LatticeMorphismTheory. Section Properties. Variables (d : disp_t) (T : latticeType d) (d' : disp_t) (T' : latticeType d'). Lemma omorphI (f : {mlmorphism T -> T'}) : {morph f : x y / x `&` y}. Proof. exact: omorphI_subproof. Qed. Lemma omorphU (f : {jlmorphism T -> T'}) : {morph f : x y / x `|` y}. Proof. exact: omorphU_subproof. Qed. End Properties. Section IdCompFun. Variables (d : disp_t) (T : latticeType d) (d' : disp_t) (T' : latticeType d'). Variables (d'' : disp_t) (T'' : latticeType d''). Section MeetCompFun. Variables (f : {mlmorphism T' -> T''}) (g : {mlmorphism T -> T'}). Fact idfun_is_meet_morphism : meet_morphism (@idfun T). Proof. by []. Qed. #[export] HB.instance Definition _ := isMeetLatticeMorphism.Build d T d T idfun idfun_is_meet_morphism. Fact comp_is_meet_morphism : meet_morphism (f \o g). Proof. by move=> x y; rewrite /= !omorphI. Qed. #[export] HB.instance Definition _ := isMeetLatticeMorphism.Build d T d'' T'' (f \o g) comp_is_meet_morphism. End MeetCompFun. Section JoinCompFun. Variables (f : {jlmorphism T' -> T''}) (g : {jlmorphism T -> T'}). Fact idfun_is_join_morphism : join_morphism (@idfun T). Proof. by []. Qed. #[export] HB.instance Definition _ := isJoinLatticeMorphism.Build d T d T idfun idfun_is_join_morphism. Fact comp_is_join_morphism : join_morphism (f \o g). Proof. by move=> x y; rewrite /= !omorphU. Qed. #[export] HB.instance Definition _ := isJoinLatticeMorphism.Build d T d'' T'' (f \o g) comp_is_join_morphism. End JoinCompFun. End IdCompFun. End LatticeMorphismTheory. End LatticeMorphismTheory. HB.mixin Record isBLatticeMorphism d (T : bLatticeType d) d' (T' : bLatticeType d') (apply : T -> T') := { omorph0_subproof : apply \bot = \bot; }. HB.mixin Record isTLatticeMorphism d (T : tLatticeType d) d' (T' : tLatticeType d') (apply : T -> T') := { omorph1_subproof : apply \top = \top; }. HB.structure Definition BLatticeMorphism d (T : bLatticeType d) d' (T' : bLatticeType d') := {f of isBLatticeMorphism d T d' T' f}. HB.structure Definition TLatticeMorphism d (T : tLatticeType d) d' (T' : tLatticeType d') := {f of isTLatticeMorphism d T d' T' f}. HB.structure Definition TBLatticeMorphism d (T : tbLatticeType d) d' (T' : tbLatticeType d') := {f of @BLatticeMorphism d T d' T' f & @TLatticeMorphism d T d' T' f}. Module TBLatticeMorphismExports. Notation "{ 'blmorphism' T -> T' }" := (@BLatticeMorphism.type _ T%type _ T'%type) : type_scope. Notation "{ 'tlmorphism' T -> T' }" := (@TLatticeMorphism.type _ T%type _ T'%type) : type_scope. Notation "{ 'tblmorphism' T -> T' }" := (@TBLatticeMorphism.type _ T%type _ T'%type) : type_scope. End TBLatticeMorphismExports. HB.export TBLatticeMorphismExports. Module Import BLatticeMorphismTheory. Section BLatticeMorphismTheory. Section Properties. Variables (d : disp_t) (T : bLatticeType d). Variables (d' : disp_t) (T' : bLatticeType d'). Variables (f : {blmorphism T -> T'}). Lemma omorph0 : f \bot = \bot. Proof. exact: omorph0_subproof. Qed. End Properties. Section IdCompFun. Variables (d : disp_t) (T : bLatticeType d). Variables (d' : disp_t) (T' : bLatticeType d'). Variables (d'' : disp_t) (T'' : bLatticeType d''). Variables (f : {blmorphism T' -> T''}) (g : {blmorphism T -> T'}). Fact idfun_is_bottom_morphism : (@idfun T) \bot = \bot. Proof. by []. Qed. #[export] HB.instance Definition _ := isBLatticeMorphism.Build d T d T idfun idfun_is_bottom_morphism. Fact comp_is_bottom_morphism : (f \o g) \bot = \bot. Proof. by rewrite /= !omorph0. Qed. #[export] HB.instance Definition _ := isBLatticeMorphism.Build d T d'' T'' (f \o g) comp_is_bottom_morphism. End IdCompFun. End BLatticeMorphismTheory. End BLatticeMorphismTheory. Module Import TLatticeMorphismTheory. Section TLatticeMorphismTheory. Section Properties. Variables (d : disp_t) (T : tLatticeType d). Variables (d' : disp_t) (T' : tLatticeType d'). Variables (f : {tlmorphism T -> T'}). Lemma omorph1 : f \top = \top. Proof. exact: omorph1_subproof. Qed. End Properties. Section IdCompFun. Variables (d : disp_t) (T : tLatticeType d). Variables (d' : disp_t) (T' : tLatticeType d'). Variables (d'' : disp_t) (T'' : tLatticeType d''). Variables (f : {tlmorphism T' -> T''}) (g : {tlmorphism T -> T'}). Fact idfun_is_top_morphism : (@idfun T) \top = \top. Proof. by []. Qed. #[export] HB.instance Definition _ := isTLatticeMorphism.Build d T d T idfun idfun_is_top_morphism. Fact comp_is_top_morphism : (f \o g) \top = \top. Proof. by rewrite /= !omorph1. Qed. #[export] HB.instance Definition _ := isTLatticeMorphism.Build d T d'' T'' (f \o g) comp_is_top_morphism. End IdCompFun. End TLatticeMorphismTheory. End TLatticeMorphismTheory. Module Import ClosedPredicates. Section ClosedPredicates. Variable (d : disp_t) (T : latticeType d). Variable S : {pred T}. Definition meet_closed := {in S &, forall u v, u `&` v \in S}. Definition join_closed := {in S &, forall u v, u `|` v \in S}. End ClosedPredicates. End ClosedPredicates. (* Mixins for stability properties *) HB.mixin Record isMeetLatticeClosed d (T : latticeType d) (S : {pred T}) := { opredI : meet_closed S; }. HB.mixin Record isJoinLatticeClosed d (T : latticeType d) (S : {pred T}) := { opredU : join_closed S; }. HB.mixin Record isBLatticeClosed d (T : bLatticeType d) (S : {pred T}) := { opred0 : \bot \in S; }. HB.mixin Record isTLatticeClosed d (T : tLatticeType d) (S : {pred T}) := { opred1 : \top \in S; }. (* Structures for stability properties *) #[short(type="meetLatticeClosed")] HB.structure Definition MeetLatticeClosed d T := {S of isMeetLatticeClosed d T S}. #[short(type="joinLatticeClosed")] HB.structure Definition JoinLatticeClosed d T := {S of isJoinLatticeClosed d T S}. #[short(type="latticeClosed")] HB.structure Definition LatticeClosed d T := {S of @MeetLatticeClosed d T S & @JoinLatticeClosed d T S}. #[short(type="bLatticeClosed")] HB.structure Definition BLatticeClosed d T := {S of isBLatticeClosed d T S}. #[short(type="bJoinLatticeClosed")] HB.structure Definition BJoinLatticeClosed d T := {S of isBLatticeClosed d T S & @JoinLatticeClosed d T S}. #[short(type="tLatticeClosed")] HB.structure Definition TLatticeClosed d T := {S of isTLatticeClosed d T S}. #[short(type="tMeetLatticeClosed")] HB.structure Definition TMeetLatticeClosed d T := {S of isTLatticeClosed d T S & @MeetLatticeClosed d T S}. #[short(type="tbLatticeClosed")] HB.structure Definition TBLatticeClosed d (T : tbLatticeType d) := {S of @BLatticeClosed d T S & @TLatticeClosed d T S}. HB.factory Record isLatticeClosed d (T : latticeType d) (S : {pred T}) := { opredI : meet_closed S; opredU : join_closed S; }. HB.builders Context d T S of isLatticeClosed d T S. HB.instance Definition _ := isMeetLatticeClosed.Build d T S opredI. HB.instance Definition _ := isJoinLatticeClosed.Build d T S opredU. HB.end. HB.factory Record isTBLatticeClosed d (T : tbLatticeType d) (S : {pred T}) := { opredI : meet_closed S; opredU : join_closed S; opred0 : \bot \in S; opred1 : \top \in S; }. HB.builders Context d T S of isTBLatticeClosed d T S. HB.instance Definition _ := isLatticeClosed.Build d T S opredI opredU. HB.instance Definition _ := isBLatticeClosed.Build d T S opred0. HB.instance Definition _ := isTLatticeClosed.Build d T S opred1. HB.end. Module Import LatticePred. Section LatticePred. Variables (d : disp_t) (T : latticeType d). Lemma opredI (S : meetLatticeClosed T) : {in S &, forall u v, u `&` v \in S}. Proof. exact: opredI. Qed. Lemma opredU (S : joinLatticeClosed T) : {in S &, forall u v, u `|` v \in S}. Proof. exact: opredU. Qed. End LatticePred. Section BLatticePred. Variables (d : disp_t) (T : bLatticeType d). Lemma opred0 (S : bLatticeClosed T) : \bot \in S. Proof. exact: opred0. Qed. Lemma opred_joins (S : bJoinLatticeClosed T) I r (P : pred I) F : (forall i, P i -> F i \in S) -> \join_(i <- r | P i) F i \in S. Proof. by move=> FS; elim/big_ind: _; [exact: opred0 | exact: opredU |]. Qed. End BLatticePred. Section TLatticePred. Variables (d : disp_t) (T : tLatticeType d). Lemma opred1 (S : tLatticeClosed T) : \top \in S. Proof. exact: opred1. Qed. Lemma opred_meets (S : tMeetLatticeClosed T) I r (P : pred I) F : (forall i, P i -> F i \in S) -> \meet_(i <- r | P i) F i \in S. Proof. by move=> FS; elim/big_ind: _; [exact: opred1 | exact: opredI |]. Qed. End TLatticePred. End LatticePred. #[short(type="subPOrder")] HB.structure Definition SubPOrder d (T : porderType d) S d' := { U of SubEquality T S U & POrder d' U & isSubPreorder d T S d' U }. HB.factory Record SubChoice_isSubPOrder d (T : porderType d) S (d' : disp_t) U of SubChoice T S U := {}. HB.builders Context d T S d' U of SubChoice_isSubPOrder d T S d' U. HB.instance Definition _ := SubChoice_isSubPreorder.Build d T S d' U. HB.instance Definition _ := Preorder_isPOrder.Build d' U (@CancelPartial.anti U d T _ _ (@valK _ _ U)). HB.end. #[export] HB.instance Definition _ d (T : porderType d) (S : pred T) (d' : disp_t) (U : subType S) := SubChoice_isSubPOrder.Build d T S d' (sub_type U). HB.mixin Record isMeetSubLattice d (T : latticeType d) (S : pred T) d' U of SubType T S U & Lattice d' U := { valI_subproof : {morph (val : U -> T) : x y / x `&` y}; }. HB.mixin Record isJoinSubLattice d (T : latticeType d) (S : pred T) d' U of SubType T S U & Lattice d' U := { valU_subproof : {morph (val : U -> T) : x y / x `|` y}; }. #[short(type="subPOrderLattice")] HB.structure Definition SubPOrderLattice d (T : latticeType d) S d' := { U of @SubPOrder d T S d' U & Lattice d' U }. #[short(type="subPOrderBLattice")] HB.structure Definition SubPOrderBLattice d (T : latticeType d) S d' := { U of @SubPOrderLattice d T S d' U & BLattice d' U }. #[short(type="subPOrderTLattice")] HB.structure Definition SubPOrderTLattice d (T : latticeType d) S d' := { U of @SubPOrderLattice d T S d' U & TLattice d' U }. #[short(type="subPOrderTBLattice")] HB.structure Definition SubPOrderTBLattice d (T : latticeType d) S d' := { U of @SubPOrderLattice d T S d' U & TBLattice d' U }. #[short(type="meetSubLattice")] HB.structure Definition MeetSubLattice d (T : latticeType d) S d' := { U of @SubPOrderLattice d T S d' U & isMeetSubLattice d T S d' U }. #[short(type="meetSubBLattice")] HB.structure Definition MeetSubBLattice d (T : latticeType d) S d' := { U of @MeetSubLattice d T S d' U & BLattice d' U }. #[short(type="meetSubTLattice")] HB.structure Definition MeetSubTLattice d (T : latticeType d) S d' := { U of @MeetSubLattice d T S d' U & TLattice d' U }. #[short(type="meetSubTBLattice")] HB.structure Definition MeetSubTBLattice d (T : latticeType d) S d' := { U of @MeetSubLattice d T S d' U & TBLattice d' U }. #[short(type="joinSubLattice")] HB.structure Definition JoinSubLattice d (T : latticeType d) S d' := { U of @SubPOrderLattice d T S d' U & isJoinSubLattice d T S d' U }. #[short(type="joinSubBLattice")] HB.structure Definition JoinSubBLattice d (T : latticeType d) S d' := { U of @JoinSubLattice d T S d' U & BLattice d' U }. #[short(type="joinSubTLattice")] HB.structure Definition JoinSubTLattice d (T : latticeType d) S d' := { U of @JoinSubLattice d T S d' U & TLattice d' U }. #[short(type="joinSubTBLattice")] HB.structure Definition JoinSubTBLattice d (T : latticeType d) S d' := { U of @JoinSubLattice d T S d' U & TBLattice d' U }. #[short(type="subLattice")] HB.structure Definition SubLattice d (T : latticeType d) S d' := { U of @MeetSubLattice d T S d' U & @JoinSubLattice d T S d' U }. #[short(type="subBLattice")] HB.structure Definition SubBLattice d (T : latticeType d) S d' := { U of @SubLattice d T S d' U & BLattice d' U }. #[short(type="subTLattice")] HB.structure Definition SubTLattice d (T : latticeType d) S d' := { U of @SubLattice d T S d' U & TLattice d' U }. #[short(type="subTBLattice")] HB.structure Definition SubTBLattice d (T : latticeType d) S d' := { U of @SubLattice d T S d' U & TBLattice d' U }. #[export, warning="-HB.no-new-instance"] HB.instance Definition _ (d : disp_t) (T : latticeType d) (S : pred T) d' (U : MeetSubLattice.type S d') := isMeetLatticeMorphism.Build d' U d T val valI_subproof. #[export, warning="-HB.no-new-instance"] HB.instance Definition _ (d : disp_t) (T : latticeType d) (S : pred T) d' (U : JoinSubLattice.type S d') := isJoinLatticeMorphism.Build d' U d T val valU_subproof. HB.factory Record SubPOrder_isSubLattice d (T : latticeType d) S d' U of @SubPOrder d T S d' U := { opredI_subproof : meet_closed S; opredU_subproof : join_closed S; }. HB.builders Context d T S d' U of SubPOrder_isSubLattice d T S d' U. HB.instance Definition _ := isLatticeClosed.Build d T S opredI_subproof opredU_subproof. Let inU v Sv : U := Sub v Sv. Let meetU (u1 u2 : U) : U := inU (opredI (valP u1) (valP u2)). Let joinU (u1 u2 : U) : U := inU (opredU (valP u1) (valP u2)). Let meetUC : commutative meetU. Proof. by move=> x y; apply: val_inj; rewrite !SubK meetC. Qed. Let joinUC : commutative joinU. Proof. by move=> x y; apply: val_inj; rewrite !SubK joinC. Qed. Let meetUA : associative meetU. Proof. by move=> x y z; apply: val_inj; rewrite !SubK meetA. Qed. Let joinUA : associative joinU. Proof. by move=> x y z; apply: val_inj; rewrite !SubK joinA. Qed. Lemma joinUKI y x : meetU x (joinU x y) = x. Proof. by apply: val_inj; rewrite !SubK joinKI. Qed. Let meetUKU y x : joinU x (meetU x y) = x. Proof. by apply: val_inj; rewrite !SubK meetKU. Qed. Let le_meetU x y : (x <= y) = (meetU x y == x). Proof. by rewrite -le_val -(inj_eq val_inj) SubK leEmeet. Qed. HB.instance Definition _ := POrder_isLattice.Build d' U meetUC joinUC meetUA joinUA joinUKI meetUKU le_meetU. Fact valI : meet_morphism (val : U -> T). Proof. by move=> x y; rewrite !SubK. Qed. Fact valU : join_morphism (val : U -> T). Proof. by move=> x y; rewrite !SubK. Qed. HB.instance Definition _ := isMeetSubLattice.Build d T S d' U valI. HB.instance Definition _ := isJoinSubLattice.Build d T S d' U valU. HB.end. HB.factory Record SubChoice_isSubLattice d (T : latticeType d) S (d' : disp_t) U of SubChoice T S U := { opredI_subproof : meet_closed S; opredU_subproof : join_closed S; }. HB.builders Context d T S d' U of SubChoice_isSubLattice d T S d' U. HB.instance Definition _ := SubChoice_isSubPOrder.Build d T S d' U. HB.instance Definition _ := SubPOrder_isSubLattice.Build d T S d' U opredI_subproof opredU_subproof. HB.end. HB.mixin Record isBSubLattice d (T : bLatticeType d) (S : pred T) d' U of SubType T S U & BLattice d' U := { val0_subproof : (val : U -> T) \bot = \bot; }. #[short(type="bJoinSubLattice")] HB.structure Definition BJoinSubLattice d (T : bLatticeType d) S d' := { U of @JoinSubLattice d T S d' U & BLattice d' U & isBSubLattice d T S d' U }. #[short(type="bJoinSubTLattice")] HB.structure Definition BJoinSubTLattice d (T : bLatticeType d) S d' := { U of @BJoinSubLattice d T S d' U & TBLattice d' U }. #[short(type="bSubLattice")] HB.structure Definition BSubLattice d (T : bLatticeType d) S d' := { U of @SubLattice d T S d' U & @BJoinSubLattice d T S d' U }. #[short(type="bSubTLattice")] HB.structure Definition BSubTLattice d (T : bLatticeType d) S d' := { U of @BSubLattice d T S d' U & TBLattice d' U }. #[export] HB.instance Definition _ (d : disp_t) (T : bLatticeType d) (S : pred T) d' (U : BJoinSubLattice.type S d') := isBLatticeMorphism.Build d' U d T val val0_subproof. HB.factory Record SubPOrder_isBSubLattice d (T : bLatticeType d) S d' U of @SubPOrder d T S d' U & Lattice d' U := { opred0_subproof : \bot \in S; }. HB.builders Context d T S d' U of SubPOrder_isBSubLattice d T S d' U. Let inU v Sv : U := Sub v Sv. Let zeroU : U := inU opred0_subproof. Fact le0x x : zeroU <= x. Proof. by rewrite -le_val /= SubK le0x. Qed. HB.instance Definition _ := hasBottom.Build d' U le0x. Fact val0 : (val : U -> T) \bot = \bot. Proof. by rewrite SubK. Qed. #[warning="-HB.no-new-instance"] HB.instance Definition _ := isBSubLattice.Build d T S d' U val0. HB.end. HB.factory Record SubChoice_isBSubLattice d (T : bLatticeType d) S (d' : disp_t) U of SubChoice T S U := { opredI_subproof : meet_closed S; opredU_subproof : join_closed S; opred0_subproof : \bot \in S; }. HB.builders Context d T S d' U of SubChoice_isBSubLattice d T S d' U. HB.instance Definition _ := SubChoice_isSubLattice.Build d T S d' U opredI_subproof opredU_subproof. HB.instance Definition _ := SubPOrder_isBSubLattice.Build d T S d' U opred0_subproof. HB.end. HB.mixin Record isTSubLattice d (T : tLatticeType d) (S : pred T) d' U of SubType T S U & TLattice d' U := { val1_subproof : (val : U -> T) \top = \top; }. #[short(type="tMeetSubLattice")] HB.structure Definition TMeetSubLattice d (T : tLatticeType d) S d' := { U of @MeetSubLattice d T S d' U & TLattice d' U & isTSubLattice d T S d' U }. #[short(type="tMeetSubBLattice")] HB.structure Definition TMeetSubBLattice d (T : tLatticeType d) S d' := { U of @TMeetSubLattice d T S d' U & TBLattice d' U }. #[short(type="tSubLattice")] HB.structure Definition TSubLattice d (T : tLatticeType d) S d' := { U of @SubLattice d T S d' U & @TMeetSubLattice d T S d' U }. #[short(type="tSubBLattice")] HB.structure Definition TSubBLattice d (T : tLatticeType d) S d' := { U of @TSubLattice d T S d' U & TBLattice d' U }. #[export] HB.instance Definition _ (d : disp_t) (T : tLatticeType d) (S : pred T) d' (U : TMeetSubLattice.type S d') := isTLatticeMorphism.Build d' U d T val val1_subproof. HB.factory Record SubPOrder_isTSubLattice d (T : tLatticeType d) S d' U of @SubPOrder d T S d' U & Lattice d' U := { opred1_subproof : \top \in S; }. HB.builders Context d T S d' U of SubPOrder_isTSubLattice d T S d' U. Let inU v Sv : U := Sub v Sv. Let oneU : U := inU opred1_subproof. Fact lex1 x : x <= oneU. Proof. by rewrite -le_val /= SubK lex1. Qed. HB.instance Definition _ := hasTop.Build d' U lex1. Fact val1 : (val : U -> T) \top = \top. Proof. by rewrite SubK. Qed. #[warning="-HB.no-new-instance"] HB.instance Definition _ := isTSubLattice.Build d T S d' U val1. HB.end. HB.factory Record SubChoice_isTSubLattice d (T : tLatticeType d) S (d' : disp_t) U of SubChoice T S U := { opredI_subproof : meet_closed S; opredU_subproof : join_closed S; opred1_subproof : \top \in S; }. HB.builders Context d T S d' U of SubChoice_isTSubLattice d T S d' U. HB.instance Definition _ := SubChoice_isSubLattice.Build d T S d' U opredI_subproof opredU_subproof. HB.instance Definition _ := SubPOrder_isTSubLattice.Build d T S d' U opred1_subproof. HB.end. #[short(type="tbSubLattice")] HB.structure Definition TBSubLattice d (T : tbLatticeType d) S d' := { U of @BSubLattice d T S d' U & @TSubLattice d T S d' U}. #[export] HB.instance Definition _ (d : disp_t) (T : tbLatticeType d) (S : pred T) d' (U : TBSubLattice.type S d') := BLatticeMorphism.on (val : U -> T). HB.factory Record SubPOrder_isTBSubLattice d (T : tbLatticeType d) S d' U of @SubPOrder d T S d' U & Lattice d' U := { opred0_subproof : \bot \in S; opred1_subproof : \top \in S; }. HB.builders Context d T S d' U of SubPOrder_isTBSubLattice d T S d' U. HB.instance Definition _ := SubPOrder_isBSubLattice.Build d T S d' U opred0_subproof. HB.instance Definition _ := SubPOrder_isTSubLattice.Build d T S d' U opred1_subproof. HB.end. HB.factory Record SubChoice_isTBSubLattice d (T : tbLatticeType d) S (d' : disp_t) U of SubChoice T S U := { opredI_subproof : meet_closed S; opredU_subproof : join_closed S; opred0_subproof : \bot \in S; opred1_subproof : \top \in S; }. HB.builders Context d T S d' U of SubChoice_isTBSubLattice d T S d' U. HB.instance Definition _ := SubChoice_isSubLattice.Build d T S d' U opredI_subproof opredU_subproof. HB.instance Definition _ := SubPOrder_isTBSubLattice.Build d T S d' U opred0_subproof opred1_subproof. HB.end. #[short(type="subOrder")] HB.structure Definition SubOrder d (T : orderType d) S d' := { U of @SubLattice d T S d' U & Total d' U }. HB.factory Record SubLattice_isSubOrder d (T : orderType d) S d' U of @SubLattice d T S d' U := {}. HB.builders Context d T S d' U of SubLattice_isSubOrder d T S d' U. Lemma totalU : total (<=%O : rel U). Proof. by move=> x y; rewrite -!le_val le_total. Qed. HB.instance Definition _ := Lattice_isTotal.Build d' U totalU. HB.end. HB.factory Record SubPOrder_isSubOrder d (T : orderType d) S d' U of @SubPOrder d T S d' U := {}. HB.builders Context d T S d' U of SubPOrder_isSubOrder d T S d' U. Fact opredI : meet_closed S. Proof. by move=> x y Sx Sy; rewrite meetEtotal; case: leP. Qed. Fact opredU : join_closed S. Proof. by move=> x y Sx Sy; rewrite joinEtotal; case: leP. Qed. HB.instance Definition _ := SubPOrder_isSubLattice.Build d T S d' U opredI opredU. HB.instance Definition _ := SubLattice_isSubOrder.Build d T S d' U. HB.end. HB.factory Record SubChoice_isSubOrder d (T : orderType d) S (d' : disp_t) U of @SubChoice T S U := {}. HB.builders Context d T S d' U of SubChoice_isSubOrder d T S d' U. HB.instance Definition _ := SubChoice_isSubPOrder.Build d T S d' U. HB.instance Definition _ := SubPOrder_isSubOrder.Build d T S d' U. HB.end. Module SubOrderExports. Notation "[ 'SubChoice_isSubPOrder' 'of' U 'by' <: ]" := (SubChoice_isSubPOrder.Build _ _ _ _ U) (format "[ 'SubChoice_isSubPOrder' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubChoice_isSubPOrder' 'of' U 'by' <: 'with' disp ]" := (SubChoice_isSubPOrder.Build _ _ _ disp U) (format "[ 'SubChoice_isSubPOrder' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubPOrder_isSubLattice' 'of' U 'by' <: ]" := (SubPOrder_isSubLattice.Build _ _ _ _ U (@opredI _ _ _) (@opredU _ _ _)) (format "[ 'SubPOrder_isSubLattice' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubPOrder_isSubLattice' 'of' U 'by' <: 'with' disp ]" := (SubPOrder_isSubLattice.Build _ _ _ disp U (@opredI _ _ _) (@opredU _ _ _)) (format "[ 'SubPOrder_isSubLattice' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubChoice_isSubLattice' 'of' U 'by' <: ]" := (SubChoice_isSubLattice.Build _ _ _ _ U (@opredI _ _ _) (@opredU _ _ _)) (format "[ 'SubChoice_isSubLattice' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubChoice_isSubLattice' 'of' U 'by' <: 'with' disp ]" := (SubChoice_isSubLattice.Build _ _ _ disp U (@opredI _ _ _) (@opredU _ _ _)) (format "[ 'SubChoice_isSubLattice' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubPOrder_isBSubLattice' 'of' U 'by' <: ]" := (SubPOrder_isBSubLattice.Build _ _ _ _ U (opred0 _)) (format "[ 'SubPOrder_isBSubLattice' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubPOrder_isBSubLattice' 'of' U 'by' <: 'with' disp ]" := (SubPOrder_isBSubLattice.Build _ _ _ disp U (opred0 _)) (format "[ 'SubPOrder_isBSubLattice' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubChoice_isBSubLattice' 'of' U 'by' <: ]" := (SubChoice_isBSubLattice.Build _ _ _ _ U (@opredI _ _ _) (@opredU _ _ _) (opred0 _)) (format "[ 'SubChoice_isBSubLattice' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubChoice_isBSubLattice' 'of' U 'by' <: 'with' disp ]" := (SubChoice_isBSubLattice.Build _ _ _ disp U (@opredI _ _ _) (@opredU _ _ _) (opred0 _)) (format "[ 'SubChoice_isBSubLattice' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubPOrder_isTSubLattice' 'of' U 'by' <: ]" := (SubPOrder_isTSubLattice.Build _ _ _ _ U (opred1 _)) (format "[ 'SubPOrder_isTSubLattice' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubPOrder_isTSubLattice' 'of' U 'by' <: 'with' disp ]" := (SubPOrder_isTSubLattice.Build _ _ _ disp U (opred1 _)) (format "[ 'SubPOrder_isTSubLattice' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubChoice_isTSubLattice' 'of' U 'by' <: ]" := (SubChoice_isTSubLattice.Build _ _ _ _ U (@opredI _ _ _) (@opredU _ _ _) (opred1 _)) (format "[ 'SubChoice_isTSubLattice' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubChoice_isTSubLattice' 'of' U 'by' <: 'with' disp ]" := (SubChoice_isTSubLattice.Build _ _ _ disp U (@opredI _ _ _) (@opredU _ _ _) (opred1 _)) (format "[ 'SubChoice_isTSubLattice' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubPOrder_isTBSubLattice' 'of' U 'by' <: ]" := (SubPOrder_isTBSubLattice.Build _ _ _ _ U (opred0 _) (opred1 _)) (format "[ 'SubPOrder_isTBSubLattice' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubPOrder_isTBSubLattice' 'of' U 'by' <: 'with' disp ]" := (SubPOrder_isTBSubLattice.Build _ _ _ disp U (opred0 _) (opred1 _)) (format "[ 'SubPOrder_isTBSubLattice' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubChoice_isTBSubLattice' 'of' U 'by' <: ]" := (SubChoice_isTBSubLattice.Build _ _ _ _ U (@opredI _ _ _) (@opredU _ _ _) (opred0 _) (opred1 _)) (format "[ 'SubChoice_isTBSubLattice' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubChoice_isTBSubLattice' 'of' U 'by' <: 'with' disp ]" := (SubChoice_isTBSubLattice.Build _ _ _ disp U (@opredI _ _ _) (@opredU _ _ _) (opred0 _) (opred1 _)) (format "[ 'SubChoice_isTBSubLattice' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubLattice_isSubOrder' 'of' U 'by' <: ]" := (SubLattice_isSubOrder.Build _ _ _ _ U) (format "[ 'SubLattice_isSubOrder' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubLattice_isSubOrder' 'of' U 'by' <: 'with' disp ]" := (SubLattice_isSubOrder.Build _ _ _ disp U) (format "[ 'SubLattice_isSubOrder' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubPOrder_isSubOrder' 'of' U 'by' <: ]" := (SubPOrder_isSubOrder.Build _ _ _ _ U) (format "[ 'SubPOrder_isSubOrder' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubPOrder_isSubOrder' 'of' U 'by' <: 'with' disp ]" := (SubPOrder_isSubOrder.Build _ _ _ disp U) (format "[ 'SubPOrder_isSubOrder' 'of' U 'by' <: 'with' disp ]") : form_scope. Notation "[ 'SubChoice_isSubOrder' 'of' U 'by' <: ]" := (SubChoice_isSubOrder.Build _ _ _ _ U) (format "[ 'SubChoice_isSubOrder' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubChoice_isSubOrder' 'of' U 'by' <: 'with' disp ]" := (SubChoice_isSubOrder.Build _ _ _ disp U) (format "[ 'SubChoice_isSubOrder' 'of' U 'by' <: 'with' disp ]") : form_scope. End SubOrderExports. HB.export SubOrderExports. Module DeprecatedSubOrder. Section Total. Context {disp : disp_t} {T : orderType disp} (P : {pred T}) (sT : subType P). #[export] HB.instance Definition _ := SubPOrder_isSubOrder.Build disp T P disp (sub_type sT). End Total. Module Exports. HB.reexport DeprecatedSubOrder. Notation "[ 'POrder' 'of' T 'by' <: ]" := (POrder.copy T%type (sub_type T%type)) (format "[ 'POrder' 'of' T 'by' <: ]") : form_scope. Notation "[ 'Order' 'of' T 'by' <: ]" := (Total.copy T%type (sub_type T%type)) (only parsing) : form_scope. End Exports. End DeprecatedSubOrder. HB.export DeprecatedSubOrder.Exports. (*************) (* INSTANCES *) (*************) (********************) (* Instances on nat *) (********************) (******************************************************************************) (* This is an example of creation of multiple instances on the same type, *) (* with distinct displays, using natural numbers. *) (* We declare two distinct canonical orders: *) (* - leq which is total, and where meet and join are minn and maxn, on nat *) (* - dvdn which is partial, and where meet and join are gcdn and lcmn, *) (* on natdvd *) (******************************************************************************) (******************************************************************************) (* The Module NatOrder defines leq as the canonical order on the type nat, *) (* i.e., without creating an alias. We define and use nat_display and proceed *) (* like a standard canonical structure declaration, except that we use this *) (* display. We also use a single factory LeOrderMixin to instantiate three *) (* different canonical declarations porderType, distrLatticeType, orderType. *) (* We finish by providing theorems to convert the operations of ordered and *) (* lattice types to their definition without structure abstraction. *) (******************************************************************************) Module NatOrder. Section NatOrder. Export NatOrder. #[export] HB.instance Definition _ := Preorder_isPOrder.Build nat_display nat anti_leq. #[export] HB.instance Definition _ := POrder_isTotal.Build nat_display nat leq_total. End NatOrder. Module Exports. HB.reexport NatOrder. End Exports. End NatOrder. HB.export NatOrder.Exports. Module NatMonotonyTheory. Section NatMonotonyTheory. Export NatMonotonyTheory. Context {disp : disp_t} {T : porderType disp}. Variables (D : {pred nat}) (f : nat -> T). Hypothesis Dconvex : {in D &, forall i j k, i < k < j -> k \in D}. Lemma incn_inP : {in D, forall i, i.+1 \in D -> f i < f i.+1} -> {in D &, {mono f : i j / i <= j}}. Proof. by move=> f_inc; apply/le_mono_in/homo_ltn_lt_in. Qed. Lemma decn_inP : {in D, forall i, i.+1 \in D -> f i > f i.+1} -> {in D &, {mono f : i j /~ i <= j}}. Proof. by move=> f_dec; apply/le_nmono_in/nhomo_ltn_lt_in. Qed. Lemma incnP : (forall i, f i < f i.+1) -> {mono f : i j / i <= j}. Proof. by move=> f_inc; apply/le_mono/homo_ltn_lt. Qed. Lemma decnP : (forall i, f i > f i.+1) -> {mono f : i j /~ i <= j}. Proof. by move=> f_dec; apply/le_nmono/nhomo_ltn_lt. Qed. End NatMonotonyTheory. Arguments incn_inP {disp T} [D f]. Arguments decn_inP {disp T} [D f]. Arguments incnP {disp T} [f]. Arguments decnP {disp T} [f]. End NatMonotonyTheory. (****************************************************************************) (* The Module DvdSyntax introduces a new set of notations using the newly *) (* created display dvd_display. We first define the display as an opaque *) (* definition of type disp_t, and we use it as the first argument of the *) (* operator which display we want to change from the default one (here le, *) (* lt, dvd sdvd, meet, join, top and bottom, as well as big op notations on *) (* gcd and lcm). This notations will now be used for any ordered type which *) (* first parameter is set to dvd_display. *) (****************************************************************************) Module DvdSyntax. Export DvdSyntax. Notation gcd := (@meet dvd_display _). Notation "@ 'gcd' T" := (@meet dvd_display T) (at level 10, T at level 8, only parsing) : function_scope. Notation lcm := (@join dvd_display _). Notation "@ 'lcm' T" := (@join dvd_display T) (at level 10, T at level 8, only parsing) : function_scope. Notation "\gcd_ ( i <- r | P ) F" := (\big[gcd/nat0]_(i <- r | P%B) F%O) : order_scope. Notation "\gcd_ ( i <- r ) F" := (\big[gcd/nat0]_(i <- r) F%O) : order_scope. Notation "\gcd_ ( i | P ) F" := (\big[gcd/nat0]_(i | P%B) F%O) : order_scope. Notation "\gcd_ i F" := (\big[gcd/nat0]_i F%O) : order_scope. Notation "\gcd_ ( i : I | P ) F" := (\big[gcd/nat0]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\gcd_ ( i : I ) F" := (\big[gcd/nat0]_(i : I) F%O) (only parsing) : order_scope. Notation "\gcd_ ( m <= i < n | P ) F" := (\big[gcd/nat0]_(m <= i < n | P%B) F%O) : order_scope. Notation "\gcd_ ( m <= i < n ) F" := (\big[gcd/nat0]_(m <= i < n) F%O) : order_scope. Notation "\gcd_ ( i < n | P ) F" := (\big[gcd/nat0]_(i < n | P%B) F%O) : order_scope. Notation "\gcd_ ( i < n ) F" := (\big[gcd/nat0]_(i < n) F%O) : order_scope. Notation "\gcd_ ( i 'in' A | P ) F" := (\big[gcd/nat0]_(i in A | P%B) F%O) : order_scope. Notation "\gcd_ ( i 'in' A ) F" := (\big[gcd/nat0]_(i in A) F%O) : order_scope. Notation "\lcm_ ( i <- r | P ) F" := (\big[lcm/nat1]_(i <- r | P%B) F%O) : order_scope. Notation "\lcm_ ( i <- r ) F" := (\big[lcm/nat1]_(i <- r) F%O) : order_scope. Notation "\lcm_ ( i | P ) F" := (\big[lcm/nat1]_(i | P%B) F%O) : order_scope. Notation "\lcm_ i F" := (\big[lcm/nat1]_i F%O) : order_scope. Notation "\lcm_ ( i : I | P ) F" := (\big[lcm/nat1]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\lcm_ ( i : I ) F" := (\big[lcm/nat1]_(i : I) F%O) (only parsing) : order_scope. Notation "\lcm_ ( m <= i < n | P ) F" := (\big[lcm/nat1]_(m <= i < n | P%B) F%O) : order_scope. Notation "\lcm_ ( m <= i < n ) F" := (\big[lcm/nat1]_(m <= i < n) F%O) : order_scope. Notation "\lcm_ ( i < n | P ) F" := (\big[lcm/nat1]_(i < n | P%B) F%O) : order_scope. Notation "\lcm_ ( i < n ) F" := (\big[lcm/nat1]_(i < n) F%O) : order_scope. Notation "\lcm_ ( i 'in' A | P ) F" := (\big[lcm/nat1]_(i in A | P%B) F%O) : order_scope. Notation "\lcm_ ( i 'in' A ) F" := (\big[lcm/nat1]_(i in A) F%O) : order_scope. End DvdSyntax. (******************************************************************************) (* The Module NatDvd defines dvdn as the canonical order on NatDvd.t, which *) (* is abbreviated using the notation natdvd at the end of the module. *) (* We use the newly defined dvd_display, described above. *) (* We first recover structures that are common to both nat and natdvd *) (* (eqType, choiceType, countType) through the copy mechanism, then we use *) (* a single factory MeetJoinMixin to instantiate both porderType and *) (* distrLatticeType canonical structures, and end with top and bottom. *) (* We finish by providing theorems to convert the operations of ordered and *) (* lattice types to their definition without structure abstraction. *) (******************************************************************************) Module NatDvd. Export NatDvd. Section NatDvd. Implicit Types (m n p : natdvd). Lemma lcmnn n : lcmn n n = n. Proof. by case: n => // n; rewrite /lcmn gcdnn mulnK. Qed. Lemma le_def m n : m %| n = (gcdn m n == m)%N. Proof. by apply/gcdn_idPl/eqP. Qed. Lemma joinKI n m : gcdn m (lcmn m n) = m. Proof. by rewrite (gcdn_idPl _)// dvdn_lcml. Qed. Lemma meetKU n m : lcmn m (gcdn m n) = m. Proof. by rewrite (lcmn_idPl _)// dvdn_gcdl. Qed. Lemma meetUl : left_distributive gcdn lcmn. Proof. move=> [|m'] [|n'] [|p'] //=; rewrite ?lcmnn ?lcm0n ?lcmn0 ?gcd0n ?gcdn0//. - by rewrite gcdnC meetKU. - by rewrite lcmnC gcdnC meetKU. apply: eqn_from_log; rewrite ?(gcdn_gt0, lcmn_gt0)//= => p. by rewrite !(logn_gcd, logn_lcm) ?(gcdn_gt0, lcmn_gt0)// minn_maxl. Qed. Fact dvdn_anti : antisymmetric dvdn. Proof. by move=> a b => /andP[] /gcdn_idPl + /gcdn_idPr => ->. Qed. #[export] HB.instance Definition _ := Preorder_isPOrder.Build dvd_display t dvdn_anti. #[export] HB.instance Definition _ := @POrder_Meet_isDistrLattice.Build dvd_display t gcdn lcmn gcdnC lcmnC gcdnA lcmnA joinKI meetKU le_def meetUl. Import DvdSyntax. Lemma sdvdE (m n : t) : m %<| n = (n != m) && (m %| n). Proof. exact/lt_def. Qed. Lemma gcdE : gcd = gcdn :> (t -> t -> t). Proof. by []. Qed. Lemma lcmE : lcm = lcmn :> (t -> t -> t). Proof. by []. Qed. End NatDvd. Module Exports. HB.reexport NatDvd. Definition sdvdEnat := sdvdE. Definition gcdEnat := gcdE. Definition lcmEnat := lcmE. End Exports. End NatDvd. HB.export NatDvd.Exports. (************************) (* Instances on ordinal *) (************************) Module OrdinalOrder. Export OrdinalOrder. #[export] HB.instance Definition _ (n : nat) := [SubChoice_isSubOrder of 'I_n by <: with ord_display]. End OrdinalOrder. HB.export OrdinalOrder. (*********************) (* Instances on bool *) (*********************) Module BoolOrder. Export BoolOrder. Section BoolOrder. Implicit Types (x y : bool). Fact andbE x y : x && y = if (x < y)%N then x else y. Proof. by case: x y => [] []. Qed. Fact orbE x y : x || y = if (x < y)%N then y else x. Proof. by case: x y => [] []. Qed. Fact anti : antisymmetric (leq : rel bool). Proof. by move=> x y /anti_leq /(congr1 odd); rewrite !oddb. Qed. #[export] HB.instance Definition _ := Preorder_isPOrder.Build bool_display bool anti. Fact orKb b a : a && (a || b) = a. Proof. by rewrite orbC orKb. Qed. Fact andKb y x : x || x && y = x. Proof. by rewrite andbC andKb. Qed. Fact leEmeet x y : (x <= y) = (x && y == x). Proof. by case: x; case: y. Qed. #[export] HB.instance Definition _ := @POrder_Meet_isDistrLattice.Build bool_display bool andb orb andbC orbC andbA orbA orKb andKb leEmeet andb_orl. #[export] HB.instance Definition _ := DistrLattice_isTotal.Build bool_display bool leq_total. #[export] HB.instance Definition _ := @TBDistrLattice_hasComplement.Build _ bool negb orbN andbN. Lemma andEbool : meet = andb. Proof. by []. Qed. Lemma orEbool : meet = andb. Proof. by []. Qed. Lemma subEbool x y : x `\` y = x && ~~ y. Proof. by []. Qed. Lemma complEbool : compl = negb. Proof. by []. Qed. End BoolOrder. Module Exports. HB.reexport BoolOrder. Definition leEbool := leEbool. Definition ltEbool := ltEbool. Definition andEbool := andEbool. Definition orEbool := orEbool. Definition subEbool := subEbool. Definition complEbool := complEbool. End Exports. End BoolOrder. HB.export BoolOrder.Exports. (******************************) (* Definition of prod_display *) (******************************) Module Import ProdSyntax. Export ProdSyntax. (* The following Local Notations are here to define the \join^p_ and \meet^p_ *) (* notations later. Do not remove them. *) Local Notation "\bot" := (@bottom (prod_display _ _) _). Local Notation "\top" := (@top (prod_display _ _) _). Local Notation meet := (@meet (prod_display _ _) _). Local Notation join := (@join (prod_display _ _) _). Local Notation min := (@min (prod_display _ _) _). Local Notation max := (@max (prod_display _ _) _). Notation "x `&^p` y" := (meet x y) : order_scope. Notation "x `|^p` y" := (join x y) : order_scope. Notation "\join^p_ ( i <- r | P ) F" := (\big[join / \bot]_(i <- r | P%B) F%O) : order_scope. Notation "\join^p_ ( i <- r ) F" := (\big[join / \bot]_(i <- r) F%O) : order_scope. Notation "\join^p_ ( i | P ) F" := (\big[join / \bot]_(i | P%B) F%O) : order_scope. Notation "\join^p_ i F" := (\big[join / \bot]_i F%O) : order_scope. Notation "\join^p_ ( i : I | P ) F" := (\big[join / \bot]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\join^p_ ( i : I ) F" := (\big[join / \bot]_(i : I) F%O) (only parsing) : order_scope. Notation "\join^p_ ( m <= i < n | P ) F" := (\big[join / \bot]_(m <= i < n | P%B) F%O) : order_scope. Notation "\join^p_ ( m <= i < n ) F" := (\big[join / \bot]_(m <= i < n) F%O) : order_scope. Notation "\join^p_ ( i < n | P ) F" := (\big[join / \bot]_(i < n | P%B) F%O) : order_scope. Notation "\join^p_ ( i < n ) F" := (\big[join / \bot]_(i < n) F%O) : order_scope. Notation "\join^p_ ( i 'in' A | P ) F" := (\big[join / \bot]_(i in A | P%B) F%O) : order_scope. Notation "\join^p_ ( i 'in' A ) F" := (\big[join / \bot]_(i in A) F%O) : order_scope. Notation "\meet^p_ ( i <- r | P ) F" := (\big[meet / \top]_(i <- r | P%B) F%O) : order_scope. Notation "\meet^p_ ( i <- r ) F" := (\big[meet / \top]_(i <- r) F%O) : order_scope. Notation "\meet^p_ ( i | P ) F" := (\big[meet / \top]_(i | P%B) F%O) : order_scope. Notation "\meet^p_ i F" := (\big[meet / \top]_i F%O) : order_scope. Notation "\meet^p_ ( i : I | P ) F" := (\big[meet / \top]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\meet^p_ ( i : I ) F" := (\big[meet / \top]_(i : I) F%O) (only parsing) : order_scope. Notation "\meet^p_ ( m <= i < n | P ) F" := (\big[meet / \top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\meet^p_ ( m <= i < n ) F" := (\big[meet / \top]_(m <= i < n) F%O) : order_scope. Notation "\meet^p_ ( i < n | P ) F" := (\big[meet / \top]_(i < n | P%B) F%O) : order_scope. Notation "\meet^p_ ( i < n ) F" := (\big[meet / \top]_(i < n) F%O) : order_scope. Notation "\meet^p_ ( i 'in' A | P ) F" := (\big[meet / \top]_(i in A | P%B) F%O) : order_scope. Notation "\meet^p_ ( i 'in' A ) F" := (\big[meet / \top]_(i in A) F%O) : order_scope. Notation "\min^p_ i F" := (\big[min/top]_i F) : order_scope. Notation "\min^p_ ( i <- r | P ) F" := (\big[min/top]_(i <- r | P%B) F%O) : order_scope. Notation "\min^p_ ( i < r ) F" := (\big[min/top]_(i <- r) F%O) : order_scope. Notation "\min^p_ ( m <= i < n | P ) F" := (\big[min/top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\min^p_ ( m <= i < n ) F" := (\big[min/top]_(m <= i < n) F%O) : order_scope. Notation "\min^p_ ( i | P ) F" := (\big[min/top]_(i | P%B) F%O) : order_scope. Notation "\min^p_ ( i : t | P ) F" := (\big[min/top]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\min^p_ ( i : t ) F" := (\big[min/top]_(i : t) F%O) (only parsing) : order_scope. Notation "\min^p_ ( i < n | P ) F" := (\big[min/top]_(i < n | P%B) F%O) : order_scope. Notation "\min^p_ ( i < n ) F" := (\big[min/top]_(i < n) F%O) : order_scope. Notation "\min^p_ ( i 'in' A | P ) F" := (\big[min/top]_(i in A | P%B) F%O) : order_scope. Notation "\min^p_ ( i 'in' A ) F" := (\big[min/top]_(i in A) F%O) : order_scope. Notation "\max^p_ i F" := (\big[max/bottom]_i F%O) : order_scope. Notation "\max^p_ ( i <- r | P ) F" := (\big[max/bottom]_(i <- r | P%B) F%O) : order_scope. Notation "\max^p_ ( i < r ) F" := (\big[max/bottom]_(i <- r) F%O) : order_scope. Notation "\max^p_ ( m <= i < n | P ) F" := (\big[max/bottom]_(m <= i < n | P%B) F%O) : order_scope. Notation "\max^p_ ( m <= i < n ) F" := (\big[max/bottom]_(m <= i < n) F%O) : order_scope. Notation "\max^p_ ( i | P ) F" := (\big[max/bottom]_(i | P%B) F%O) : order_scope. Notation "\max^p_ ( i : t | P ) F" := (\big[max/bottom]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\max^p_ ( i : t ) F" := (\big[max/bottom]_(i : t) F%O) (only parsing) : order_scope. Notation "\max^p_ ( i < n | P ) F" := (\big[max/bottom]_(i < n | P%B) F%O) : order_scope. Notation "\max^p_ ( i < n ) F" := (\big[max/bottom]_(i < n) F%O) : order_scope. Notation "\max^p_ ( i 'in' A | P ) F" := (\big[max/bottom]_(i in A | P%B) F%O) : order_scope. Notation "\max^p_ ( i 'in' A ) F" := (\big[max/bottom]_(i in A) F%O) : order_scope. End ProdSyntax. Module Import SeqProdSyntax. Export SeqProdSyntax. (* The following Local Notations are here to define the \join^sp_ and *) (* \meet^sp_ notations later. Do not remove them. *) Local Notation "\bot" := (@bottom (seqprod_display _) _). Local Notation "\top" := (@top (seqprod_display _) _). Local Notation meet := (@meet (seqprod_display _) _). Local Notation join := (@join (seqprod_display _) _). Local Notation min := (@min (seqprod_display _) _). Local Notation max := (@max (seqprod_display _) _). Notation "x `&^sp` y" := (meet x y) : order_scope. Notation "x `|^sp` y" := (join x y) : order_scope. Notation "\join^sp_ ( i <- r | P ) F" := (\big[join / \bot]_(i <- r | P%B) F%O) : order_scope. Notation "\join^sp_ ( i <- r ) F" := (\big[join / \bot]_(i <- r) F%O) : order_scope. Notation "\join^sp_ ( i | P ) F" := (\big[join / \bot]_(i | P%B) F%O) : order_scope. Notation "\join^sp_ i F" := (\big[join / \bot]_i F%O) : order_scope. Notation "\join^sp_ ( i : I | P ) F" := (\big[join / \bot]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\join^sp_ ( i : I ) F" := (\big[join / \bot]_(i : I) F%O) (only parsing) : order_scope. Notation "\join^sp_ ( m <= i < n | P ) F" := (\big[join / \bot]_(m <= i < n | P%B) F%O) : order_scope. Notation "\join^sp_ ( m <= i < n ) F" := (\big[join / \bot]_(m <= i < n) F%O) : order_scope. Notation "\join^sp_ ( i < n | P ) F" := (\big[join / \bot]_(i < n | P%B) F%O) : order_scope. Notation "\join^sp_ ( i < n ) F" := (\big[join / \bot]_(i < n) F%O) : order_scope. Notation "\join^sp_ ( i 'in' A | P ) F" := (\big[join / \bot]_(i in A | P%B) F%O) : order_scope. Notation "\join^sp_ ( i 'in' A ) F" := (\big[join / \bot]_(i in A) F%O) : order_scope. Notation "\meet^sp_ ( i <- r | P ) F" := (\big[meet / \top]_(i <- r | P%B) F%O) : order_scope. Notation "\meet^sp_ ( i <- r ) F" := (\big[meet / \top]_(i <- r) F%O) : order_scope. Notation "\meet^sp_ ( i | P ) F" := (\big[meet / \top]_(i | P%B) F%O) : order_scope. Notation "\meet^sp_ i F" := (\big[meet / \top]_i F%O) : order_scope. Notation "\meet^sp_ ( i : I | P ) F" := (\big[meet / \top]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\meet^sp_ ( i : I ) F" := (\big[meet / \top]_(i : I) F%O) (only parsing) : order_scope. Notation "\meet^sp_ ( m <= i < n | P ) F" := (\big[meet / \top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\meet^sp_ ( m <= i < n ) F" := (\big[meet / \top]_(m <= i < n) F%O) : order_scope. Notation "\meet^sp_ ( i < n | P ) F" := (\big[meet / \top]_(i < n | P%B) F%O) : order_scope. Notation "\meet^sp_ ( i < n ) F" := (\big[meet / \top]_(i < n) F%O) : order_scope. Notation "\meet^sp_ ( i 'in' A | P ) F" := (\big[meet / \top]_(i in A | P%B) F%O) : order_scope. Notation "\meet^sp_ ( i 'in' A ) F" := (\big[meet / \top]_(i in A) F%O) : order_scope. Notation "\min^sp_ i F" := (\big[min/top]_i F) : order_scope. Notation "\min^sp_ ( i <- r | P ) F" := (\big[min/top]_(i <- r | P%B) F%O) : order_scope. Notation "\min^sp_ ( i < r ) F" := (\big[min/top]_(i <- r) F%O) : order_scope. Notation "\min^sp_ ( m <= i < n | P ) F" := (\big[min/top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\min^sp_ ( m <= i < n ) F" := (\big[min/top]_(m <= i < n) F%O) : order_scope. Notation "\min^sp_ ( i | P ) F" := (\big[min/top]_(i | P%B) F%O) : order_scope. Notation "\min^sp_ ( i : t | P ) F" := (\big[min/top]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\min^sp_ ( i : t ) F" := (\big[min/top]_(i : t) F%O) (only parsing) : order_scope. Notation "\min^sp_ ( i < n | P ) F" := (\big[min/top]_(i < n | P%B) F%O) : order_scope. Notation "\min^sp_ ( i < n ) F" := (\big[min/top]_(i < n) F%O) : order_scope. Notation "\min^sp_ ( i 'in' A | P ) F" := (\big[min/top]_(i in A | P%B) F%O) : order_scope. Notation "\min^sp_ ( i 'in' A ) F" := (\big[min/top]_(i in A) F%O) : order_scope. Notation "\max^sp_ i F" := (\big[max/bottom]_i F%O) : order_scope. Notation "\max^sp_ ( i <- r | P ) F" := (\big[max/bottom]_(i <- r | P%B) F%O) : order_scope. Notation "\max^sp_ ( i < r ) F" := (\big[max/bottom]_(i <- r) F%O) : order_scope. Notation "\max^sp_ ( m <= i < n | P ) F" := (\big[max/bottom]_(m <= i < n | P%B) F%O) : order_scope. Notation "\max^sp_ ( m <= i < n ) F" := (\big[max/bottom]_(m <= i < n) F%O) : order_scope. Notation "\max^sp_ ( i | P ) F" := (\big[max/bottom]_(i | P%B) F%O) : order_scope. Notation "\max^sp_ ( i : t | P ) F" := (\big[max/bottom]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\max^sp_ ( i : t ) F" := (\big[max/bottom]_(i : t) F%O) (only parsing) : order_scope. Notation "\max^sp_ ( i < n | P ) F" := (\big[max/bottom]_(i < n | P%B) F%O) : order_scope. Notation "\max^sp_ ( i < n ) F" := (\big[max/bottom]_(i < n) F%O) : order_scope. Notation "\max^sp_ ( i 'in' A | P ) F" := (\big[max/bottom]_(i in A | P%B) F%O) : order_scope. Notation "\max^sp_ ( i 'in' A ) F" := (\big[max/bottom]_(i in A) F%O) : order_scope. End SeqProdSyntax. Module Import LexiSyntax. Export LexiSyntax. Notation meetlexi := (@meet (lexi_display _ _) _). Notation joinlexi := (@join (lexi_display _ _) _). Notation "x `&^l` y" := (meetlexi x y) : order_scope. Notation "x `|^l` y" := (joinlexi x y) : order_scope. (* The following Local Notations are here to define the \join^l_ and \meet^l_ *) (* notations later. Do not remove them. *) Local Notation "\bot" := (@bottom (lexi_display _ _) _). Local Notation "\top" := (@top (lexi_display _ _) _). Local Notation meet := (@meet (lexi_display _ _) _). Local Notation join := (@join (lexi_display _ _) _). Local Notation min := (@min (lexi_display _ _) _). Local Notation max := (@max (lexi_display _ _) _). Notation "\join^l_ ( i <- r | P ) F" := (\big[join / \bot]_(i <- r | P%B) F%O) : order_scope. Notation "\join^l_ ( i <- r ) F" := (\big[join / \bot]_(i <- r) F%O) : order_scope. Notation "\join^l_ ( i | P ) F" := (\big[join / \bot]_(i | P%B) F%O) : order_scope. Notation "\join^l_ i F" := (\big[join / \bot]_i F%O) : order_scope. Notation "\join^l_ ( i : I | P ) F" := (\big[join / \bot]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\join^l_ ( i : I ) F" := (\big[join / \bot]_(i : I) F%O) (only parsing) : order_scope. Notation "\join^l_ ( m <= i < n | P ) F" := (\big[join / \bot]_(m <= i < n | P%B) F%O) : order_scope. Notation "\join^l_ ( m <= i < n ) F" := (\big[join / \bot]_(m <= i < n) F%O) : order_scope. Notation "\join^l_ ( i < n | P ) F" := (\big[join / \bot]_(i < n | P%B) F%O) : order_scope. Notation "\join^l_ ( i < n ) F" := (\big[join / \bot]_(i < n) F%O) : order_scope. Notation "\join^l_ ( i 'in' A | P ) F" := (\big[join / \bot]_(i in A | P%B) F%O) : order_scope. Notation "\join^l_ ( i 'in' A ) F" := (\big[join / \bot]_(i in A) F%O) : order_scope. Notation "\meet^l_ ( i <- r | P ) F" := (\big[meet / \top]_(i <- r | P%B) F%O) : order_scope. Notation "\meet^l_ ( i <- r ) F" := (\big[meet / \top]_(i <- r) F%O) : order_scope. Notation "\meet^l_ ( i | P ) F" := (\big[meet / \top]_(i | P%B) F%O) : order_scope. Notation "\meet^l_ i F" := (\big[meet / \top]_i F%O) : order_scope. Notation "\meet^l_ ( i : I | P ) F" := (\big[meet / \top]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\meet^l_ ( i : I ) F" := (\big[meet / \top]_(i : I) F%O) (only parsing) : order_scope. Notation "\meet^l_ ( m <= i < n | P ) F" := (\big[meet / \top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\meet^l_ ( m <= i < n ) F" := (\big[meet / \top]_(m <= i < n) F%O) : order_scope. Notation "\meet^l_ ( i < n | P ) F" := (\big[meet / \top]_(i < n | P%B) F%O) : order_scope. Notation "\meet^l_ ( i < n ) F" := (\big[meet / \top]_(i < n) F%O) : order_scope. Notation "\meet^l_ ( i 'in' A | P ) F" := (\big[meet / \top]_(i in A | P%B) F%O) : order_scope. Notation "\meet^l_ ( i 'in' A ) F" := (\big[meet / \top]_(i in A) F%O) : order_scope. Notation "\min^l_ i F" := (\big[min/top]_i F) : order_scope. Notation "\min^l_ ( i <- r | P ) F" := (\big[min/top]_(i <- r | P%B) F%O) : order_scope. Notation "\min^l_ ( i < r ) F" := (\big[min/top]_(i <- r) F%O) : order_scope. Notation "\min^l_ ( m <= i < n | P ) F" := (\big[min/top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\min^l_ ( m <= i < n ) F" := (\big[min/top]_(m <= i < n) F%O) : order_scope. Notation "\min^l_ ( i | P ) F" := (\big[min/top]_(i | P%B) F%O) : order_scope. Notation "\min^l_ ( i : t | P ) F" := (\big[min/top]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\min^l_ ( i : t ) F" := (\big[min/top]_(i : t) F%O) (only parsing) : order_scope. Notation "\min^l_ ( i < n | P ) F" := (\big[min/top]_(i < n | P%B) F%O) : order_scope. Notation "\min^l_ ( i < n ) F" := (\big[min/top]_(i < n) F%O) : order_scope. Notation "\min^l_ ( i 'in' A | P ) F" := (\big[min/top]_(i in A | P%B) F%O) : order_scope. Notation "\min^l_ ( i 'in' A ) F" := (\big[min/top]_(i in A) F%O) : order_scope. Notation "\max^l_ i F" := (\big[max/bottom]_i F%O) : order_scope. Notation "\max^l_ ( i <- r | P ) F" := (\big[max/bottom]_(i <- r | P%B) F%O) : order_scope. Notation "\max^l_ ( i < r ) F" := (\big[max/bottom]_(i <- r) F%O) : order_scope. Notation "\max^l_ ( m <= i < n | P ) F" := (\big[max/bottom]_(m <= i < n | P%B) F%O) : order_scope. Notation "\max^l_ ( m <= i < n ) F" := (\big[max/bottom]_(m <= i < n) F%O) : order_scope. Notation "\max^l_ ( i | P ) F" := (\big[max/bottom]_(i | P%B) F%O) : order_scope. Notation "\max^l_ ( i : t | P ) F" := (\big[max/bottom]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\max^l_ ( i : t ) F" := (\big[max/bottom]_(i : t) F%O) (only parsing) : order_scope. Notation "\max^l_ ( i < n | P ) F" := (\big[max/bottom]_(i < n | P%B) F%O) : order_scope. Notation "\max^l_ ( i < n ) F" := (\big[max/bottom]_(i < n) F%O) : order_scope. Notation "\max^l_ ( i 'in' A | P ) F" := (\big[max/bottom]_(i in A | P%B) F%O) : order_scope. Notation "\max^l_ ( i 'in' A ) F" := (\big[max/bottom]_(i in A) F%O) : order_scope. End LexiSyntax. Module Import SeqLexiSyntax. Export SeqLexiSyntax. Notation meetlexi := (@meet (seqlexi_display _) _). Notation joinlexi := (@join (seqlexi_display _) _). Notation "x `&^l` y" := (meetlexi x y) : order_scope. Notation "x `|^l` y" := (joinlexi x y) : order_scope. (* The following Local Notations are here to define the \join^l_ and \meet^l_ *) (* notations later. Do not remove them. *) Local Notation "\bot" := (@bottom (lexi_display _ _) _). Local Notation "\top" := (@top (lexi_display _ _) _). Local Notation meet := (@meet (lexi_display _ _) _). Local Notation join := (@join (lexi_display _ _) _). Local Notation min := (@min (lexi_display _ _) _). Local Notation max := (@max (lexi_display _ _) _). Notation "\join^l_ ( i <- r | P ) F" := (\big[join / \bot]_(i <- r | P%B) F%O) : order_scope. Notation "\join^l_ ( i <- r ) F" := (\big[join / \bot]_(i <- r) F%O) : order_scope. Notation "\join^l_ ( i | P ) F" := (\big[join / \bot]_(i | P%B) F%O) : order_scope. Notation "\join^l_ i F" := (\big[join / \bot]_i F%O) : order_scope. Notation "\join^l_ ( i : I | P ) F" := (\big[join / \bot]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\join^l_ ( i : I ) F" := (\big[join / \bot]_(i : I) F%O) (only parsing) : order_scope. Notation "\join^l_ ( m <= i < n | P ) F" := (\big[join / \bot]_(m <= i < n | P%B) F%O) : order_scope. Notation "\join^l_ ( m <= i < n ) F" := (\big[join / \bot]_(m <= i < n) F%O) : order_scope. Notation "\join^l_ ( i < n | P ) F" := (\big[join / \bot]_(i < n | P%B) F%O) : order_scope. Notation "\join^l_ ( i < n ) F" := (\big[join / \bot]_(i < n) F%O) : order_scope. Notation "\join^l_ ( i 'in' A | P ) F" := (\big[join / \bot]_(i in A | P%B) F%O) : order_scope. Notation "\join^l_ ( i 'in' A ) F" := (\big[join / \bot]_(i in A) F%O) : order_scope. Notation "\meet^l_ ( i <- r | P ) F" := (\big[meet / \top]_(i <- r | P%B) F%O) : order_scope. Notation "\meet^l_ ( i <- r ) F" := (\big[meet / \top]_(i <- r) F%O) : order_scope. Notation "\meet^l_ ( i | P ) F" := (\big[meet / \top]_(i | P%B) F%O) : order_scope. Notation "\meet^l_ i F" := (\big[meet / \top]_i F%O) : order_scope. Notation "\meet^l_ ( i : I | P ) F" := (\big[meet / \top]_(i : I | P%B) F%O) (only parsing) : order_scope. Notation "\meet^l_ ( i : I ) F" := (\big[meet / \top]_(i : I) F%O) (only parsing) : order_scope. Notation "\meet^l_ ( m <= i < n | P ) F" := (\big[meet / \top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\meet^l_ ( m <= i < n ) F" := (\big[meet / \top]_(m <= i < n) F%O) : order_scope. Notation "\meet^l_ ( i < n | P ) F" := (\big[meet / \top]_(i < n | P%B) F%O) : order_scope. Notation "\meet^l_ ( i < n ) F" := (\big[meet / \top]_(i < n) F%O) : order_scope. Notation "\meet^l_ ( i 'in' A | P ) F" := (\big[meet / \top]_(i in A | P%B) F%O) : order_scope. Notation "\meet^l_ ( i 'in' A ) F" := (\big[meet / \top]_(i in A) F%O) : order_scope. Notation "\min^l_ i F" := (\big[min/top]_i F) : order_scope. Notation "\min^l_ ( i <- r | P ) F" := (\big[min/top]_(i <- r | P%B) F%O) : order_scope. Notation "\min^l_ ( i < r ) F" := (\big[min/top]_(i <- r) F%O) : order_scope. Notation "\min^l_ ( m <= i < n | P ) F" := (\big[min/top]_(m <= i < n | P%B) F%O) : order_scope. Notation "\min^l_ ( m <= i < n ) F" := (\big[min/top]_(m <= i < n) F%O) : order_scope. Notation "\min^l_ ( i | P ) F" := (\big[min/top]_(i | P%B) F%O) : order_scope. Notation "\min^l_ ( i : t | P ) F" := (\big[min/top]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\min^l_ ( i : t ) F" := (\big[min/top]_(i : t) F%O) (only parsing) : order_scope. Notation "\min^l_ ( i < n | P ) F" := (\big[min/top]_(i < n | P%B) F%O) : order_scope. Notation "\min^l_ ( i < n ) F" := (\big[min/top]_(i < n) F%O) : order_scope. Notation "\min^l_ ( i 'in' A | P ) F" := (\big[min/top]_(i in A | P%B) F%O) : order_scope. Notation "\min^l_ ( i 'in' A ) F" := (\big[min/top]_(i in A) F%O) : order_scope. Notation "\max^l_ i F" := (\big[max/bottom]_i F%O) : order_scope. Notation "\max^l_ ( i <- r | P ) F" := (\big[max/bottom]_(i <- r | P%B) F%O) : order_scope. Notation "\max^l_ ( i < r ) F" := (\big[max/bottom]_(i <- r) F%O) : order_scope. Notation "\max^l_ ( m <= i < n | P ) F" := (\big[max/bottom]_(m <= i < n | P%B) F%O) : order_scope. Notation "\max^l_ ( m <= i < n ) F" := (\big[max/bottom]_(m <= i < n) F%O) : order_scope. Notation "\max^l_ ( i | P ) F" := (\big[max/bottom]_(i | P%B) F%O) : order_scope. Notation "\max^l_ ( i : t | P ) F" := (\big[max/bottom]_(i : t | P%B) F%O) (only parsing) : order_scope. Notation "\max^l_ ( i : t ) F" := (\big[max/bottom]_(i : t) F%O) (only parsing) : order_scope. Notation "\max^l_ ( i < n | P ) F" := (\big[max/bottom]_(i < n | P%B) F%O) : order_scope. Notation "\max^l_ ( i < n ) F" := (\big[max/bottom]_(i < n) F%O) : order_scope. Notation "\max^l_ ( i 'in' A | P ) F" := (\big[max/bottom]_(i in A | P%B) F%O) : order_scope. Notation "\max^l_ ( i 'in' A ) F" := (\big[max/bottom]_(i in A) F%O) : order_scope. End SeqLexiSyntax. (************************************************) (* We declare an alias of the cartesian product *) (* which has canonical product order. *) (************************************************) Module ProdOrder. Export ProdOrder. Local Open Scope type_scope. (* FIXME *) Section POrder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : porderType disp1) (T2 : porderType disp2). Fact anti : antisymmetric (@le disp1 disp2 disp2 T1 T2). Proof. case=> [? ?] [? ?]. by rewrite andbAC andbA andbAC -andbA => /= /andP [] /le_anti -> /le_anti ->. Qed. End POrder. Section POrder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : porderType disp1) (T2 : porderType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Let T1' : Type := T1. HB.instance Definition _ := POrder.on T1'. Let T2' : Type := T2. HB.instance Definition _ := POrder.on T2'. #[export] HB.instance Definition _ := Preorder_isDuallyPOrder.Build disp3 (T1 * T2) (@anti _ _ T1' T2') (@anti _ _ T1^d T2^d). Lemma ltEprod x y : (x < y) = [&& x != y, x.1 <= y.1 & x.2 <= y.2]. Proof. by rewrite lt_neqAle. Qed. Lemma lt_pair (x1 y1 : T1) (x2 y2 : T2) : (x1, x2) < (y1, y2) :> T1 * T2 = [&& (x1 != y1) || (x2 != y2), x1 <= y1 & x2 <= y2]. Proof. by rewrite ltEprod negb_and. Qed. End POrder. Section MeetSemilattice. Context (disp1 disp2 : disp_t). Context (T1 : meetSemilatticeType disp1) (T2 : meetSemilatticeType disp2). Local Notation "T1 * T2" := (type (Disp tt tt) T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Let meet x y := (x.1 `&` y.1, x.2 `&` y.2). Fact lexI x y z : (x <= meet y z) = (x <= y) && (x <= z). Proof. by rewrite leEprod !lexI andbACA. Qed. End MeetSemilattice. Section MeetSemilattice. Context (disp1 disp2 disp3 : disp_t). Context (T1 : meetSemilatticeType disp1) (T2 : meetSemilatticeType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Let T1' : Type := T1. HB.instance Definition _ := MeetSemilattice.on T1'. Let T2' : Type := T2. HB.instance Definition _ := MeetSemilattice.on T2'. Definition meet x y := (x.1 `&` y.1, x.2 `&` y.2). #[export] HB.instance Definition _ := @POrder_isMeetSemilattice.Build disp3 (T1 * T2) meet (@lexI _ _ T1' T2'). Lemma meetEprod x y : x `&` y = (x.1 `&` y.1, x.2 `&` y.2). Proof. by []. Qed. End MeetSemilattice. Section JoinSemilattice. Context (disp1 disp2 disp3 : disp_t). Context (T1 : joinSemilatticeType disp1) (T2 : joinSemilatticeType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Definition join x y := (x.1 `|` y.1, x.2 `|` y.2). #[export] HB.instance Definition _ := @POrder_isJoinSemilattice.Build disp3 (T1 * T2) join (fun x y z => @lexI _ _ T1^d T2^d z x y). Lemma joinEprod x y : x `|` y = (x.1 `|` y.1, x.2 `|` y.2). Proof. by []. Qed. End JoinSemilattice. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : bPOrderType disp1) (T2 : bPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tPOrderType disp1) (T2 : tPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tbPOrderType disp1) (T2 : tbPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : bMeetSemilatticeType disp1) (T2 : bMeetSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tMeetSemilatticeType disp1) (T2 : tMeetSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tbMeetSemilatticeType disp1) (T2 : tbMeetSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : bJoinSemilatticeType disp1) (T2 : bJoinSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tJoinSemilatticeType disp1) (T2 : tJoinSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tbJoinSemilatticeType disp1) (T2 : tbJoinSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : latticeType disp1) (T2 : latticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : bLatticeType disp1) (T2 : bLatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tLatticeType disp1) (T2 : tLatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tbLatticeType disp1) (T2 : tbLatticeType disp2) := POrder.on (type disp3 T1 T2). (* /FIXME *) Section DistrLattice. Context (disp1 disp2 : disp_t). Context (T1 : distrLatticeType disp1) (T2 : distrLatticeType disp2). Local Notation "T1 * T2" := (type (Disp tt tt) T1 T2) : type_scope. Fact meetUl : @left_distributive (T1 * T2) _ Order.meet Order.join. Proof. by move=> ? ? ?; rewrite meetEprod !meetUl. Qed. End DistrLattice. Section DistrLattice. Context (disp1 disp2 disp3 : disp_t). Context (T1 : distrLatticeType disp1) (T2 : distrLatticeType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Let T1' : Type := T1. HB.instance Definition _ := DistrLattice.on T1'. Let T2' : Type := T2. HB.instance Definition _ := DistrLattice.on T2'. #[export] HB.instance Definition _ := Lattice_isDistributive.Build disp3 (T1 * T2) (@meetUl _ _ T1' T2') (@meetUl _ _ T1^d T2^d). End DistrLattice. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : bDistrLatticeType disp1) (T2 : bDistrLatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tDistrLatticeType disp1) (T2 : tDistrLatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tbDistrLatticeType disp1) (T2 : tbDistrLatticeType disp2) := POrder.on (type disp3 T1 T2). (* /FIXME *) Section CDistrLattice. Context (disp1 disp2 : disp_t). Context (T1 : cDistrLatticeType disp1) (T2 : cDistrLatticeType disp2). Local Notation "T1 * T2" := (type (Disp tt tt) T1 T2) : type_scope. Implicit Types (x y z : T1 * T2). Let rcompl x y z := (rcompl x.1 y.1 z.1, rcompl x.2 y.2 z.2). Fact rcomplPmeet x y z : ((x `&` y) `|` z) `&` rcompl x y z = x `&` y. Proof. by rewrite !(meetEprod, joinEprod) !rcomplPmeet. Qed. End CDistrLattice. Section CDistrLattice. Context (disp1 disp2 disp3 : disp_t). Context (T1 : cDistrLatticeType disp1) (T2 : cDistrLatticeType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x y z : T1 * T2). Let T1' : Type := T1. HB.instance Definition _ := CDistrLattice.on T1'. Let T2' : Type := T2. HB.instance Definition _ := CDistrLattice.on T2'. Definition rcompl x y z := (rcompl x.1 y.1 z.1, rcompl x.2 y.2 z.2). #[export] HB.instance Definition _ := @DistrLattice_hasRelativeComplement.Build disp3 (T1 * T2) rcompl (@rcomplPmeet _ _ T1' T2') (fun x y => @rcomplPmeet _ _ T1^d T2^d y x). Lemma rcomplEprod x y z : rcompl x y z = (Order.rcompl x.1 y.1 z.1, Order.rcompl x.2 y.2 z.2). Proof. by []. Qed. End CDistrLattice. Section CBDistrLattice. Context (disp1 disp2 : disp_t). Context (T1 : cbDistrLatticeType disp1) (T2 : cbDistrLatticeType disp2). Local Notation "T1 * T2" := (type (Disp tt tt) T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Let diff x y := (diff x.1 y.1, diff x.2 y.2). Fact diffErcompl x y : diff x y = rcompl \bot x y. Proof. by rewrite /diff !diffErcompl. Qed. End CBDistrLattice. Section CBDistrLattice. Context (disp1 disp2 disp3 : disp_t). Context (T1 : cbDistrLatticeType disp1) (T2 : cbDistrLatticeType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Let T1' : Type := T1. HB.instance Definition _ := CBDistrLattice.on T1'. Let T2' : Type := T2. HB.instance Definition _ := CBDistrLattice.on T2'. Definition diff x y := (diff x.1 y.1, diff x.2 y.2). #[export] HB.instance Definition _ := @CDistrLattice_hasSectionalComplement.Build disp3 (T1 * T2) diff (@diffErcompl _ _ T1' T2'). Lemma diffEprod x y : x `\` y = (x.1 `\` y.1, x.2 `\` y.2). Proof. by []. Qed. End CBDistrLattice. Section CTDistrLattice. Context (disp1 disp2 disp3 : disp_t). Context (T1 : ctDistrLatticeType disp1) (T2 : ctDistrLatticeType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Definition codiff x y := (codiff x.1 y.1, codiff x.2 y.2). #[export] HB.instance Definition _ := @CDistrLattice_hasDualSectionalComplement.Build disp3 (T1 * T2) codiff (@diffErcompl _ _ T1^d T2^d). Lemma codiffEprod x y : codiff x y = (Order.codiff x.1 y.1, Order.codiff x.2 y.2). Proof. by []. Qed. End CTDistrLattice. Section CTBDistrLattice. Context (disp1 disp2 : disp_t). Context (T1 : ctbDistrLatticeType disp1) (T2 : ctbDistrLatticeType disp2). Local Notation "T1 * T2" := (type (Disp tt tt) T1 T2) : type_scope. Implicit Types (x : T1 * T2). Let compl x := (~` x.1, ~` x.2). Fact complEdiff x : compl x = (\top : T1 * T2) `\` x. Proof. by rewrite /compl !complEdiff. Qed. End CTBDistrLattice. Section CTBDistrLattice. Context (disp1 disp2 disp3 : disp_t). Context (T1 : ctbDistrLatticeType disp1) (T2 : ctbDistrLatticeType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x : T1 * T2). Let T1' : Type := T1. HB.instance Definition _ := CTBDistrLattice.on T1'. Let T2' : Type := T2. HB.instance Definition _ := CTBDistrLattice.on T2'. Definition compl x := (~` x.1, ~` x.2). #[export] HB.instance Definition _ := @CDistrLattice_hasComplement.Build _ (T1 * T2) compl (@complEdiff _ _ T1' T2') (@complEdiff _ _ T1^d T2^d). Lemma complEprod x : ~` x = (~` x.1, ~` x.2). Proof. by []. Qed. End CTBDistrLattice. (* FIXME: use HB.saturate *) Section FinOrder. Context (disp1 disp2 disp3 : disp_t). #[export] HB.instance Definition _ (T1 : finPOrderType disp1) (T2 : finPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finBPOrderType disp1) (T2 : finBPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTPOrderType disp1) (T2 : finTPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTBPOrderType disp1) (T2 : finTBPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finMeetSemilatticeType disp1) (T2 : finMeetSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finBMeetSemilatticeType disp1) (T2 : finBMeetSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finJoinSemilatticeType disp1) (T2 : finJoinSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTJoinSemilatticeType disp1) (T2 : finTJoinSemilatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finLatticeType disp1) (T2 : finLatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTBLatticeType disp1) (T2 : finTBLatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finDistrLatticeType disp1) (T2 : finDistrLatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTBDistrLatticeType disp1) (T2 : finTBDistrLatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finCDistrLatticeType disp1) (T2 : finCDistrLatticeType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finCTBDistrLatticeType disp1) (T2 : finCTBDistrLatticeType disp2) := POrder.on (type disp3 T1 T2). End FinOrder. (* /FIXME *) Module Exports. HB.reexport ProdOrder. Definition ltEprod := @ltEprod. Definition lt_pair := @lt_pair. Definition meetEprod := @meetEprod. Definition joinEprod := @joinEprod. Definition rcomplEprod := @rcomplEprod. Definition diffEprod := @diffEprod. Definition codiffEprod := @codiffEprod. Definition complEprod := @complEprod. End Exports. End ProdOrder. HB.export ProdOrder.Exports. Module DefaultProdOrder. Export DefaultProdOrder. Section DefaultProdOrder. Context {disp1 disp2 : disp_t}. Let prod T1 T2 := T1 *prod[prod_display disp1 disp2] T2. (* FIXME: Scopes of arguments are broken in several places. *) (* FIXME: Declaring a bunch of copies is still a bit painful. *) HB.instance Definition _ (T1 : porderType disp1) (T2 : porderType disp2) := POrder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : bPOrderType disp1) (T2 : bPOrderType disp2) := BPOrder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tPOrderType disp1) (T2 : tPOrderType disp2) := TPOrder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tbPOrderType disp1) (T2 : tbPOrderType disp2) := TBPOrder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : meetSemilatticeType disp1) (T2 : meetSemilatticeType disp2) := MeetSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : bMeetSemilatticeType disp1) (T2 : bMeetSemilatticeType disp2) := BMeetSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tMeetSemilatticeType disp1) (T2 : tMeetSemilatticeType disp2) := TMeetSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tbMeetSemilatticeType disp1) (T2 : tbMeetSemilatticeType disp2) := TBMeetSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : joinSemilatticeType disp1) (T2 : joinSemilatticeType disp2) := JoinSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : bJoinSemilatticeType disp1) (T2 : bJoinSemilatticeType disp2) := BJoinSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tJoinSemilatticeType disp1) (T2 : tJoinSemilatticeType disp2) := TJoinSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tbJoinSemilatticeType disp1) (T2 : tbJoinSemilatticeType disp2) := TBJoinSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : latticeType disp1) (T2 : latticeType disp2) := Lattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : bLatticeType disp1) (T2 : bLatticeType disp2) := BLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tLatticeType disp1) (T2 : tLatticeType disp2) := TLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tbLatticeType disp1) (T2 : tbLatticeType disp2) := TBLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : distrLatticeType disp1) (T2 : distrLatticeType disp2) := DistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : bDistrLatticeType disp1) (T2 : bDistrLatticeType disp2) := BDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tDistrLatticeType disp1) (T2 : tDistrLatticeType disp2) := TDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tbDistrLatticeType disp1) (T2 : tbDistrLatticeType disp2) := TBDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : cDistrLatticeType disp1) (T2 : cDistrLatticeType disp2) := CDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : cbDistrLatticeType disp1) (T2 : cbDistrLatticeType disp2) := CBDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : ctDistrLatticeType disp1) (T2 : ctDistrLatticeType disp2) := CTDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : ctbDistrLatticeType disp1) (T2 : ctbDistrLatticeType disp2) := CTBDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finPOrderType disp1) (T2 : finPOrderType disp2) := FinPOrder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finBPOrderType disp1) (T2 : finBPOrderType disp2) := FinBPOrder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finTPOrderType disp1) (T2 : finTPOrderType disp2) := FinTPOrder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finTBPOrderType disp1) (T2 : finTBPOrderType disp2) := FinTBPOrder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finMeetSemilatticeType disp1) (T2 : finMeetSemilatticeType disp2) := FinMeetSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finBMeetSemilatticeType disp1) (T2 : finBMeetSemilatticeType disp2) := FinBMeetSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finJoinSemilatticeType disp1) (T2 : finJoinSemilatticeType disp2) := FinJoinSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finTJoinSemilatticeType disp1) (T2 : finTJoinSemilatticeType disp2) := FinTJoinSemilattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finLatticeType disp1) (T2 : finLatticeType disp2) := FinLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finTBLatticeType disp1) (T2 : finTBLatticeType disp2) := FinTBLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finDistrLatticeType disp1) (T2 : finDistrLatticeType disp2) := FinDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finTBDistrLatticeType disp1) (T2 : finTBDistrLatticeType disp2) := FinTBDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finCDistrLatticeType disp1) (T2 : finCDistrLatticeType disp2) := FinCDistrLattice.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finCTBDistrLatticeType disp1) (T2 : finCTBDistrLatticeType disp2) := FinCTBDistrLattice.copy (T1 * T2)%type (prod T1 T2). (* /FIXME *) End DefaultProdOrder. End DefaultProdOrder. (*********************************************************) (* We declare lexicographic ordering on dependent pairs. *) (*********************************************************) Module SigmaOrder. Section SigmaOrder. Context {disp1 disp2 : disp_t}. Section POrder. Context (T : porderType disp1) (T' : T -> porderType disp2). Implicit Types (x y : {t : T & T' t}). Definition le x y := (tag x <= tag y) && ((tag x >= tag y) ==> (tagged x <= tagged_as x y)). Definition lt x y := (tag x <= tag y) && ((tag x >= tag y) ==> (tagged x < tagged_as x y)). Fact refl : reflexive le. Proof. by move=> [x x']; rewrite /le tagged_asE/= !lexx. Qed. Fact anti : antisymmetric le. Proof. rewrite /le => -[x x'] [y y']/=; case: comparableP => //= eq_xy. by case: _ / eq_xy in y' *; rewrite !tagged_asE => /le_anti ->. Qed. Fact trans : transitive le. Proof. move=> [y y'] [x x'] [z z'] /andP[/= lexy lexy'] /andP[/= leyz leyz']. rewrite /= /le (le_trans lexy) //=; apply/implyP => lezx. elim: _ / (@le_anti _ _ x y) in y' z' lexy' leyz' *; last first. by rewrite lexy (le_trans leyz). elim: _ / (@le_anti _ _ x z) in z' leyz' *; last by rewrite (le_trans lexy). by rewrite lexx !tagged_asE/= in lexy' leyz' *; rewrite (le_trans lexy'). Qed. Fact lt_le_def x y : lt x y = le x y && ~~ le y x. Proof. rewrite /lt /le; case: x y => [x x'] [y y']//=. case: (comparableP x y) => //= xy. by subst y; rewrite !tagged_asE lt_le_def. Qed. #[export] HB.instance Definition _ := isPreorder.Build disp2 {t : T & T' t} lt_le_def refl trans. #[export] HB.instance Definition _ := Preorder_isPOrder.Build disp2 {t : T & T' t} anti. Lemma leEsig x y : x <= y = (tag x <= tag y) && ((tag x >= tag y) ==> (tagged x <= tagged_as x y)). Proof. by []. Qed. Lemma ltEsig x y : x < y = (tag x <= tag y) && ((tag x >= tag y) ==> (tagged x < tagged_as x y)). Proof. by []. Qed. Lemma le_Taggedl x (u : T' (tag x)) : (Tagged T' u <= x) = (u <= tagged x). Proof. by case: x => [t v]/= in u *; rewrite leEsig/= lexx/= tagged_asE. Qed. Lemma le_Taggedr x (u : T' (tag x)) : (x <= Tagged T' u) = (tagged x <= u). Proof. by case: x => [t v]/= in u *; rewrite leEsig/= lexx/= tagged_asE. Qed. Lemma lt_Taggedl x (u : T' (tag x)) : (Tagged T' u < x) = (u < tagged x). Proof. by case: x => [t v]/= in u *; rewrite ltEsig/= lexx/= tagged_asE. Qed. Lemma lt_Taggedr x (u : T' (tag x)) : (x < Tagged T' u) = (tagged x < u). Proof. by case: x => [t v]/= in u *; rewrite ltEsig/= lexx/= tagged_asE. Qed. End POrder. Section BPOrder. Context (T : bPOrderType disp1) (T' : T -> bPOrderType disp2). Fact le0x (x : {t : T & T' t}) : Tagged T' (\bot : T' \bot) <= x. Proof. by rewrite leEsig /= !le0x implybT. Qed. #[export] HB.instance Definition _ := hasBottom.Build _ {t : T & T' t} le0x. Lemma botEsig : \bot = Tagged T' (\bot : T' \bot). Proof. by []. Qed. End BPOrder. Section TPOrder. Context (T : tPOrderType disp1) (T' : T -> tPOrderType disp2). Fact lex1 (x : {t : T & T' t}) : x <= Tagged T' (\top : T' \top). Proof. rewrite leEsig /=; case: comparableP (lex1 (tag x)) => //=. by case: x => //= x px x0; rewrite x0 in px *; rewrite tagged_asE lex1. Qed. #[export] HB.instance Definition _ := hasTop.Build _ {t : T & T' t} lex1. Lemma topEsig : \top = Tagged T' (\top : T' \top). Proof. by []. Qed. End TPOrder. Section Total. Context (T : orderType disp1) (T' : T -> orderType disp2). Implicit Types (x y : {t : T & T' t}). Fact total : total (<=%O : rel {t : T & T' t}). Proof. move=> x y; rewrite !leEsig; case: (ltgtP (tag x) (tag y)) => //=. case: x y => [x x'] [y y']/= eqxy; elim: _ /eqxy in y' *. by rewrite !tagged_asE le_total. Qed. #[export] HB.instance Definition _ := POrder_isTotal.Build _ {t : T & T' t} total. End Total. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (T : bOrderType disp1) (T' : T -> bOrderType disp2) := POrder.on {t : T & T' t}. #[export] HB.instance Definition _ (T : tOrderType disp1) (T' : T -> tOrderType disp2) := POrder.on {t : T & T' t}. #[export] HB.instance Definition _ (T : tbOrderType disp1) (T' : T -> tbOrderType disp2) := POrder.on {t : T & T' t}. #[export] HB.instance Definition _ (T : finPOrderType disp1) (T' : T -> finPOrderType disp2) := POrder.on {t : T & T' t}. #[export] HB.instance Definition _ (T : finBPOrderType disp1) (T' : T -> finBPOrderType disp2) := POrder.on {t : T & T' t}. #[export] HB.instance Definition _ (T : finTPOrderType disp1) (T' : T -> finTPOrderType disp2) := POrder.on {t : T & T' t}. #[export] HB.instance Definition _ (T : finTBPOrderType disp1) (T' : T -> finTBPOrderType disp2) := POrder.on {t : T & T' t}. #[export] HB.instance Definition _ (T : finOrderType disp1) (T' : T -> finOrderType disp2) := POrder.on {t : T & T' t}. #[export] HB.instance Definition _ (T : finTBOrderType disp1) (T' : T -> finTBOrderType disp2) := POrder.on {t : T & T' t}. (* /FIXME *) End SigmaOrder. Module Exports. HB.reexport SigmaOrder. Definition leEsig := @leEsig. Definition ltEsig := @ltEsig. Definition le_Taggedl := @le_Taggedl. Definition lt_Taggedl := @lt_Taggedl. Definition le_Taggedr := @le_Taggedr. Definition lt_Taggedr := @lt_Taggedr. Definition topEsig := @topEsig. Definition botEsig := @botEsig. End Exports. End SigmaOrder. HB.export SigmaOrder.Exports. (*************************************************) (* We declare an alias of the cartesian product, *) (* which has canonical lexicographic order. *) (*************************************************) Module ProdLexiOrder. Export ProdLexiOrder. Local Open Scope type_scope. (* FIXME *) Section POrder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : porderType disp1) (T2 : porderType disp2). Fact anti : antisymmetric (@le disp1 disp2 disp2 T1 T2). Proof. by rewrite /le => -[x x'] [y y'] /=; case: comparableP => //= -> /le_anti->. Qed. End POrder. Section POrder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : porderType disp1) (T2 : porderType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Let T1' : Type := T1. HB.instance Definition _ := POrder.on T1'. Let T2' : Type := T2. HB.instance Definition _ := POrder.on T2'. #[export] HB.instance Definition _ := Preorder_isDuallyPOrder.Build disp3 (T1 * T2) (@anti _ _ T1' T2') (@anti _ _ T1^d T2^d). End POrder. Section Total. Context (disp1 disp2 disp3 : disp_t). Context (T1 : orderType disp1) (T2 : orderType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Fact total : total (<=%O : rel (T1 * T2)). Proof. by move=> x y; rewrite !leEprodlexi; case: ltgtP => //= _; exact: le_total. Qed. (* FIXME: In order to dualize this instance, we have to dualize the *) (* [POrder_isTotal] factory. However, [min] and max are not definitional dual *) (* (while [min x y] and [max y x] are). *) #[export] HB.instance Definition _ := POrder_isTotal.Build _ (T1 * T2) total. End Total. (* FIXME: use HB.saturate *) Section ProdLexiOrder. Context (disp1 disp2 disp3 : disp_t). #[export] HB.instance Definition _ (T1 : finPOrderType disp1) (T2 : finPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finBPOrderType disp1) (T2 : finBPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTPOrderType disp1) (T2 : finTPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTBPOrderType disp1) (T2 : finTBPOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finOrderType disp1) (T2 : finOrderType disp2) := POrder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTBOrderType disp1) (T2 : finTBOrderType disp2) := POrder.on (type disp3 T1 T2). End ProdLexiOrder. (* /FIXME *) Module Exports. HB.reexport ProdLexiOrder. End Exports. End ProdLexiOrder. HB.export ProdLexiOrder.Exports. Module DefaultProdLexiOrder. Export DefaultProdLexiOrder. Section DefaultProdLexiOrder. Context {disp1 disp2 : disp_t}. Let prodlexi T1 T2 := T1 *lexi[lexi_display disp1 disp2] T2. (* FIXME: Scopes of arguments are broken in several places. *) (* FIXME: Declaring a bunch of copies is still a bit painful. *) HB.instance Definition _ (T1 : porderType disp1) (T2 : porderType disp2) := POrder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : orderType disp1) (T2 : orderType disp2) := Total.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finPOrderType disp1) (T2 : finPOrderType disp2) := FinPOrder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finBPOrderType disp1) (T2 : finBPOrderType disp2) := FinBPOrder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finTPOrderType disp1) (T2 : finTPOrderType disp2) := FinTPOrder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finTBPOrderType disp1) (T2 : finTBPOrderType disp2) := FinTBPOrder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finOrderType disp1) (T2 : finOrderType disp2) := FinTotal.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finTBOrderType disp1) (T2 : finTBOrderType disp2) := FinTBTotal.copy (T1 * T2)%type (prodlexi T1 T2). (* /FIXME *) End DefaultProdLexiOrder. End DefaultProdLexiOrder. (*****************************************) (* We declare an alias of the sequences, *) (* which has canonical product order. *) (*****************************************) Module SeqProdOrder. Export SeqProdOrder. Section SeqProdOrder. Context {disp disp' : disp_t}. Local Notation seq := (type disp'). Section POrder. Variable T : porderType disp. Implicit Types s : seq T. Fact anti : antisymmetric (@le disp disp' T). Proof. by elim=> [|x s ihs] [|y s'] //=; rewrite andbACA => /andP[/le_anti-> /ihs->]. Qed. #[export] HB.instance Definition _ := Preorder_isPOrder.Build disp' (seq T) anti. End POrder. Section MeetSemilattice. Context (T : meetSemilatticeType disp). Implicit Types (s : seq T). Fixpoint meet s1 s2 := match s1, s2 with | x1 :: s1', x2 :: s2' => (x1 `&` x2) :: meet s1' s2' | _, _ => [::] end. Fact lexI s1 s2 s3 : (s1 <= meet s2 s3) = (s1 <= s2) && (s1 <= s3). Proof. elim: s1 s2 s3 => [|x s1 IHs1] [|y s2] [|z s3] //=; first by rewrite andbF. by rewrite leEseq lexI IHs1 andbACA. Qed. #[export] HB.instance Definition _ := @POrder_isMeetSemilattice.Build _ (seq T) meet lexI. Lemma meetEseq s1 s2 : s1 `&` s2 = [seq x.1 `&` x.2 | x <- zip s1 s2]. Proof. by elim: s1 s2 => [|x s1 ihs1] [|y s2]//=; rewrite -ihs1. Qed. Lemma meet_cons x1 s1 x2 s2 : (x1 :: s1 : seq T) `&` (x2 :: s2) = (x1 `&` x2) :: s1 `&` s2. Proof. by []. Qed. End MeetSemilattice. Section JoinSemilattice. Context (T : joinSemilatticeType disp). Implicit Types (s : seq T). Fixpoint join s1 s2 := match s1, s2 with | [::], _ => s2 | _, [::] => s1 | x1 :: s1', x2 :: s2' => (x1 `|` x2) :: join s1' s2' end. Fact leUx s1 s2 s3 : (join s1 s2 <= s3) = (s1 <= s3) && (s2 <= s3). Proof. elim : s1 s2 s3 => [|x s1 IHs1] [|y s2] [|z s3] //=; first by rewrite andbT. by rewrite leEseq leUx IHs1 andbACA. Qed. #[export] HB.instance Definition _ := @POrder_isJoinSemilattice.Build _ (seq T) join leUx. Lemma joinEseq s1 s2 : s1 `|` s2 = match s1, s2 with | [::], _ => s2 | _, [::] => s1 | x1 :: s1', x2 :: s2' => (x1 `|` x2) :: ((s1' : seq _) `|` s2') end. Proof. by case: s1. Qed. Lemma join_cons x1 s1 x2 s2 : (x1 :: s1 : seq T) `|` (x2 :: s2) = (x1 `|` x2) :: s1 `|` s2. Proof. by []. Qed. End JoinSemilattice. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (T : latticeType disp) := POrder.on (seq T). (* /FIXME *) Section DistrLattice. Context (T : distrLatticeType disp). Fact meetUl : left_distributive (@meet T) (@join T). Proof. by elim=> [|? ? ih] [|? ?] [|? ?] //=; rewrite meetUl ih. Qed. #[export] HB.instance Definition _ := Lattice_Meet_isDistrLattice.Build _ (seq T) meetUl. End DistrLattice. End SeqProdOrder. Module Exports. HB.reexport SeqProdOrder. Definition meetEseq := @meetEseq. Definition meet_cons := @meet_cons. Definition joinEseq := @joinEseq. End Exports. End SeqProdOrder. HB.export SeqProdOrder.Exports. Module DefaultSeqProdOrder. Export DefaultSeqProdOrder. Section DefaultSeqProdOrder. Context {disp : disp_t}. HB.instance Definition _ (T : porderType disp) := POrder.copy (seq T) (seqprod T). HB.instance Definition _ (T : meetSemilatticeType disp) := BMeetSemilattice.copy (seq T) (seqprod T). HB.instance Definition _ (T : joinSemilatticeType disp) := BJoinSemilattice.copy (seq T) (seqprod T). HB.instance Definition _ (T : latticeType disp) := BLattice.copy (seq T) (seqprod T). HB.instance Definition _ (T : distrLatticeType disp) := BDistrLattice.copy (seq T) (seqprod T). End DefaultSeqProdOrder. End DefaultSeqProdOrder. (*********************************************) (* We declare an alias of the sequences, *) (* which has canonical lexicographic order. *) (*********************************************) Module SeqLexiOrder. Export SeqLexiOrder. Section SeqLexiOrder. Context {disp disp' : disp_t}. Local Notation seq := (type disp'). Section POrder. Variable T : porderType disp. Implicit Types s : seq T. Fact anti: antisymmetric (@le disp disp' T). Proof. move=> x y /andP []; elim: x y => [|x sx ih] [|y sy] //=. by case: comparableP => //= -> lesxsy /(ih _ lesxsy) ->. Qed. #[export] HB.instance Definition _ := Preorder_isPOrder.Build disp' (seq T) anti. Lemma neqhead_lexiE (x y : T) s1 s2 : x != y -> (x :: s1 <= y :: s2 :> seq _) = (x < y). Proof. by rewrite lexi_cons; case: comparableP. Qed. Lemma neqhead_ltxiE (x y : T) s1 s2 : x != y -> (x :: s1 < y :: s2 :> seq _) = (x < y). Proof. by rewrite ltxi_cons; case: (comparableP x y). Qed. End POrder. Section Total. Context (T : orderType disp). Fact total : total (<=%O : rel (seq T)). Proof. by elim=> [|x1 s1 ihs1] [|x2 s2]//=; rewrite !lexi_cons; case: ltgtP => /=. Qed. #[export] HB.instance Definition _ := POrder_isTotal.Build _ (seq T) total. End Total. End SeqLexiOrder. Module Exports. HB.reexport SeqLexiOrder. Definition neqhead_lexiE := @neqhead_lexiE. Definition neqhead_ltxiE := @neqhead_ltxiE. End Exports. End SeqLexiOrder. HB.export SeqLexiOrder.Exports. Module DefaultSeqLexiOrder. Export DefaultSeqLexiOrder. Section DefaultSeqLexiOrder. Context {disp : disp_t}. HB.instance Definition _ (T : porderType disp) := POrder.copy (seq T) (seqlexi T). HB.instance Definition _ (T : orderType disp) := BTotal.copy (seq T) (seqlexi T). End DefaultSeqLexiOrder. End DefaultSeqLexiOrder. (***************************************) (* We declare an alias of the tuples, *) (* which has canonical product order. *) (***************************************) Module TupleProdOrder. Export TupleProdOrder. Import DefaultSeqProdOrder. Section TupleProdOrder. Context {disp disp' : disp_t}. Local Notation "n .-tuple" := (type disp' n) : type_scope. Section POrder. Implicit Types (T : porderType disp). #[export, warning="-HB.no-new-instance"] HB.instance Definition _ n T := SubChoice.on (n.-tuple T). #[export] HB.instance Definition _ n T := [SubChoice_isSubPOrder of n.-tuple T by <: with disp']. End POrder. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (n : nat) (T : bPOrderType disp) := POrder.on (n.-tuple T). (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (n : nat) (T : tPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tbPOrderType disp) := POrder.on (n.-tuple T). (* /FIXME *) Section MeetSemilattice. Context (n : nat) (T : meetSemilatticeType disp). Implicit Types (t : n.-tuple T). Definition meet t1 t2 : n.-tuple T := [tuple tnth t1 i `&` tnth t2 i | i < n]. Fact lexI t1 t2 t3 : (t1 <= meet t2 t3) = (t1 <= t2) && (t1 <= t3). Proof. rewrite !leEtprod; apply/forallP/andP => [H|[Ht12 Ht13] i]; last first. by rewrite tnth_mktuple lexI (forallP Ht12) (forallP Ht13). by split; apply/forallP => i; move: (H i); rewrite tnth_mktuple lexI => /andP[]. Qed. #[export] HB.instance Definition _ := @POrder_isMeetSemilattice.Build _ (n.-tuple T) meet lexI. Lemma tnth_meet t1 t2 i : tnth (t1 `&` t2) i = tnth t1 i `&` tnth t2 i. Proof. exact: tnth_mktuple. Qed. Lemma meetEtprod t1 t2 : t1 `&` t2 = [tuple tnth t1 i `&` tnth t2 i | i < n]. Proof. by []. Qed. End MeetSemilattice. Section JoinSemilattice. Context (n : nat) (T : joinSemilatticeType disp). Implicit Types (t : n.-tuple T). Definition join t1 t2 : n.-tuple T := [tuple tnth t1 i `|` tnth t2 i | i < n]. Fact leUx t1 t2 t3 : (join t1 t2 <= t3) = (t1 <= t3) && (t2 <= t3). Proof. rewrite !leEtprod; apply/forallP/andP => [H|[Ht13 Ht23] i]; last first. by rewrite tnth_mktuple leUx (forallP Ht13) (forallP Ht23). by split; apply/forallP => i; move: (H i); rewrite tnth_mktuple leUx => /andP[]. Qed. #[export] HB.instance Definition _ := @POrder_isJoinSemilattice.Build _ (n.-tuple T) join leUx. Lemma tnth_join t1 t2 i : tnth (t1 `|` t2) i = tnth t1 i `|` tnth t2 i. Proof. exact: tnth_mktuple. Qed. Lemma joinEtprod t1 t2 : t1 `|` t2 = [tuple tnth t1 i `|` tnth t2 i | i < n]. Proof. by []. Qed. End JoinSemilattice. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (n : nat) (T : bMeetSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tMeetSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tbMeetSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : bJoinSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tJoinSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tbJoinSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : latticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : bLatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tLatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tbLatticeType disp) := POrder.on (n.-tuple T). (* /FIXME *) Section DistrLattice. Context (n : nat) (T : distrLatticeType disp). Implicit Types (t : n.-tuple T). Fact meetUl : left_distributive (@meet n T) (@join n T). Proof. by move=> t1 t2 t3; apply: eq_from_tnth => i; rewrite !tnth_mktuple meetUl. Qed. #[export] HB.instance Definition _ := Lattice_Meet_isDistrLattice.Build _ (n.-tuple T) meetUl. End DistrLattice. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (n : nat) (T : bDistrLatticeType disp) := DistrLattice.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tDistrLatticeType disp) := DistrLattice.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tbDistrLatticeType disp) := DistrLattice.on (n.-tuple T). (* /FIXME *) Section CDistrLattice. Context (n : nat) (T : cDistrLatticeType disp). Implicit Types (t : n.-tuple T). Definition rcompl t1 t2 t3 := [tuple rcompl (tnth t1 i) (tnth t2 i) (tnth t3 i) | i < n]. Fact rcomplPmeet x y z : ((x `&` y) `|` z) `&` rcompl x y z = x `&` y. Proof. by apply: eq_from_tnth => i; rewrite !tnth_mktuple rcomplPmeet. Qed. Fact rcomplPjoin x y z : ((y `|` x) `&` z) `|` rcompl x y z = y `|` x. Proof. by apply: eq_from_tnth => i; rewrite !tnth_mktuple rcomplPjoin. Qed. #[export] HB.instance Definition _ := @DistrLattice_hasRelativeComplement.Build _ (n.-tuple T) rcompl rcomplPmeet rcomplPjoin. Lemma tnth_rcompl t1 t2 t3 i : tnth (Order.rcompl t1 t2 t3) i = Order.rcompl (tnth t1 i) (tnth t2 i) (tnth t3 i). Proof. exact: tnth_mktuple. Qed. Lemma rcomplEtprod t1 t2 t3 : Order.rcompl t1 t2 t3 = [tuple Order.rcompl (tnth t1 i) (tnth t2 i) (tnth t3 i) | i < n]. Proof. by []. Qed. End CDistrLattice. Section CBDistrLattice. Context (n : nat) (T : cbDistrLatticeType disp). Implicit Types (t : n.-tuple T). Definition diff t1 t2 : n.-tuple T := [tuple tnth t1 i `\` tnth t2 i | i < n]. Fact diffErcompl t1 t2 : diff t1 t2 = rcompl \bot t1 t2. Proof. by apply: eq_from_tnth => i; rewrite !tnth_mktuple diffErcompl. Qed. #[export] HB.instance Definition _ := @CDistrLattice_hasSectionalComplement.Build _ (n.-tuple T) diff diffErcompl. Lemma tnth_diff t1 t2 i : tnth (diff t1 t2) i = tnth t1 i `\` tnth t2 i. Proof. exact: tnth_mktuple. Qed. Lemma diffEtprod t1 t2 : t1 `\` t2 = [tuple tnth t1 i `\` tnth t2 i | i < n]. Proof. by []. Qed. End CBDistrLattice. Section CTDistrLattice. Context (n : nat) (T : ctDistrLatticeType disp). Implicit Types (t : n.-tuple T). Definition codiff t1 t2 : n.-tuple T := [tuple Order.codiff (tnth t1 i) (tnth t2 i) | i < n]. Fact codiffErcompl t1 t2 : codiff t1 t2 = rcompl t1 \top t2. Proof. by apply: eq_from_tnth => i; rewrite !tnth_mktuple codiffErcompl. Qed. #[export] HB.instance Definition _ := @CDistrLattice_hasDualSectionalComplement.Build _ (n.-tuple T) codiff codiffErcompl. Lemma tnth_codiff t1 t2 i : tnth (Order.codiff t1 t2) i = Order.codiff (tnth t1 i) (tnth t2 i). Proof. exact: tnth_mktuple. Qed. Lemma codiffEtprod t1 t2 : Order.codiff t1 t2 = [tuple Order.codiff (tnth t1 i) (tnth t2 i) | i < n]. Proof. by []. Qed. End CTDistrLattice. Section CTBDistrLattice. Context (n : nat) (T : ctbDistrLatticeType disp). Implicit Types (t : n.-tuple T). Definition compl t : n.-tuple T := map_tuple compl t. Fact complEdiff t : compl t = (\top : n.-tuple T) `\` t. Proof. by apply: eq_from_tnth => i; rewrite tnth_map !tnth_mktuple complEdiff. Qed. Fact complEcodiff t : compl t = codiff (\bot : n.-tuple T) t. Proof. by apply: eq_from_tnth => i; rewrite tnth_map !tnth_mktuple complEcodiff. Qed. #[export] HB.instance Definition _ := @CDistrLattice_hasComplement.Build _ (n.-tuple T) compl complEdiff complEcodiff. Lemma tnth_compl t i : tnth (~` t) i = ~` tnth t i. Proof. by rewrite tnth_map. Qed. Lemma complEtprod t : ~` t = map_tuple Order.compl t. Proof. by []. Qed. End CTBDistrLattice. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (n : nat) (T : finPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finBPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTBPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finMeetSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finBMeetSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finJoinSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTJoinSemilatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finLatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTBLatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finDistrLatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTBDistrLatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finCDistrLatticeType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finCTBDistrLatticeType disp) := POrder.on (n.-tuple T). (* /FIXME *) End TupleProdOrder. Module Exports. HB.reexport TupleProdOrder. Definition tnth_meet := @tnth_meet. Definition meetEtprod := @meetEtprod. Definition tnth_join := @tnth_join. Definition joinEtprod := @joinEtprod. Definition tnth_rcompl := @tnth_rcompl. Definition rcomplEtprod := @rcomplEtprod. Definition tnth_diff := @tnth_diff. Definition diffEtprod := @diffEtprod. Definition tnth_codiff := @tnth_codiff. Definition codiffEtprod := @codiffEtprod. Definition tnth_compl := @tnth_compl. Definition complEtprod := @complEtprod. End Exports. End TupleProdOrder. HB.export TupleProdOrder.Exports. Module DefaultTupleProdOrder. Export DefaultTupleProdOrder. Section DefaultTupleProdOrder. Context {disp : disp_t}. HB.instance Definition _ n (T : porderType disp) := POrder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : bPOrderType disp) := BPOrder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tPOrderType disp) := TPOrder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tbPOrderType disp) := TBPOrder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : meetSemilatticeType disp) := MeetSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : bMeetSemilatticeType disp) := BMeetSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tMeetSemilatticeType disp) := TMeetSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tbMeetSemilatticeType disp) := TBMeetSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : joinSemilatticeType disp) := JoinSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : bJoinSemilatticeType disp) := BJoinSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tJoinSemilatticeType disp) := TJoinSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tbJoinSemilatticeType disp) := TBJoinSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : latticeType disp) := Lattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : bLatticeType disp) := BLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tLatticeType disp) := TLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tbLatticeType disp) := TBLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : distrLatticeType disp) := DistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : bDistrLatticeType disp) := BDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tDistrLatticeType disp) := TDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tbDistrLatticeType disp) := TBDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : cDistrLatticeType disp) := CDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : cbDistrLatticeType disp) := CBDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : ctDistrLatticeType disp) := CTDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : ctbDistrLatticeType disp) := CTBDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finPOrderType disp) := FinPOrder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finBPOrderType disp) := FinBPOrder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finTPOrderType disp) := FinTPOrder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finTBPOrderType disp) := FinTBPOrder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finMeetSemilatticeType disp) := FinMeetSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finBMeetSemilatticeType disp) := FinBMeetSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finJoinSemilatticeType disp) := FinJoinSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finTJoinSemilatticeType disp) := FinTJoinSemilattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finLatticeType disp) := FinLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finTBLatticeType disp) := FinTBLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finDistrLatticeType disp) := FinDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finTBDistrLatticeType disp) := FinTBDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finCDistrLatticeType disp) := FinCDistrLattice.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : finCTBDistrLatticeType disp) := FinCTBDistrLattice.copy (n.-tuple T) (n.-tupleprod T). End DefaultTupleProdOrder. End DefaultTupleProdOrder. (*********************************************) (* We declare an alias of the tuples, *) (* which has canonical lexicographic order. *) (*********************************************) Module TupleLexiOrder. Export TupleLexiOrder. Section TupleLexiOrder. Import DefaultSeqLexiOrder. Context {disp disp' : disp_t}. Local Notation "n .-tuple" := (type disp' n) : type_scope. Section POrder. Implicit Types (n : nat) (T : porderType disp). #[export] HB.instance Definition _ n T := [SubChoice_isSubPOrder of n.-tuple T by <: with disp']. Lemma lexi_tupleP n T (t1 t2 : n.-tuple T) : reflect (exists k : 'I_n.+1, forall i : 'I_n, (i <= k)%N -> tnth t1 i <= tnth t2 i ?= iff (i != k :> nat)) (t1 <= t2). Proof. elim: n => [|n IHn] in t1 t2 *. by rewrite tuple0 [t2]tuple0/= lexx; constructor; exists ord0 => -[]. case: (tupleP t1) (tupleP t2) => [x1 {}t1] [x2 {}t2]. rewrite [_ <= _]lexi_cons; apply: (iffP idP) => [|[k leif_xt12]]. case: comparableP => //= [ltx12 _|-> /IHn[k kP]]. exists ord0 => i; rewrite leqn0 => /eqP/(@ord_inj n.+1 i ord0)->. by apply/leifP; rewrite !tnth0. exists (lift ord0 k) => i; case: (unliftP ord0 i) => [j ->|-> _]. by rewrite !ltnS => /kP; rewrite !tnthS. by apply/leifP; rewrite !tnth0 eqxx. have /= := leif_xt12 ord0 isT; rewrite !tnth0 => leif_x12. rewrite leif_x12/=; move: leif_x12 leif_xt12 => /leifP. case: (unliftP ord0 k) => {k} [k-> /eqP<-{x2}|-> /lt_geF->//] leif_xt12. rewrite lexx implyTb; apply/IHn; exists k => i le_ik. by have := leif_xt12 (lift ord0 i) le_ik; rewrite !tnthS. Qed. Lemma ltxi_tupleP n T (t1 t2 : n.-tuple T) : reflect (exists k : 'I_n, forall i : 'I_n, (i <= k)%N -> tnth t1 i <= tnth t2 i ?= iff (i != k :> nat)) (t1 < t2). Proof. elim: n => [|n IHn] in t1 t2 *. by rewrite tuple0 [t2]tuple0/= ltxx; constructor => - [] []. case: (tupleP t1) (tupleP t2) => [x1 {}t1] [x2 {}t2]. rewrite [_ < _]ltxi_cons; apply: (iffP idP) => [|[k leif_xt12]]. case: (comparableP x1 x2) => //= [ltx12 _|-> /IHn[k kP]]. exists ord0 => i; rewrite leqn0 => /eqP/(@ord_inj n.+1 i ord0)->. by apply/leifP; rewrite !tnth0. exists (lift ord0 k) => i; case: (unliftP ord0 i) => {i} [i ->|-> _]. by rewrite !ltnS => /kP; rewrite !tnthS. by apply/leifP; rewrite !tnth0 eqxx. have /= := leif_xt12 ord0 isT; rewrite !tnth0 => leif_x12. rewrite leif_x12/=; move: leif_x12 leif_xt12 => /leifP. case: (unliftP ord0 k) => {k} [k-> /eqP<-{x2}|-> /lt_geF->//] leif_xt12. rewrite lexx implyTb; apply/IHn; exists k => i le_ik. by have := leif_xt12 (lift ord0 i) le_ik; rewrite !tnthS. Qed. Lemma ltxi_tuplePlt n T (t1 t2 : n.-tuple T) : reflect (exists2 k : 'I_n, forall i : 'I_n, (i < k)%N -> tnth t1 i = tnth t2 i & tnth t1 k < tnth t2 k) (t1 < t2). Proof. apply: (iffP (ltxi_tupleP _ _)) => [[k kP]|[k kP ltk12]]. exists k => [i i_lt|]; last by rewrite (lt_leif (kP _ _)) ?eqxx ?leqnn. by have /eqTleif->// := kP i (ltnW i_lt); rewrite ltn_eqF. by exists k => i; case: ltngtP => //= [/kP-> _|/ord_inj-> _]; apply/leifP. Qed. End POrder. #[export] HB.instance Definition _ n (T : orderType disp) := [SubChoice_isSubOrder of n.-tuple T by <: with disp']. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (n : nat) (T : bPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tbPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : bOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tbOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finBPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTBPOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finOrderType disp) := POrder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTBOrderType disp) := POrder.on (n.-tuple T). (* /FIXME *) End TupleLexiOrder. Module Exports. HB.reexport TupleLexiOrder. Definition lexi_tupleP := @lexi_tupleP. Arguments lexi_tupleP {disp disp' n T t1 t2}. Definition ltxi_tupleP := @ltxi_tupleP. Arguments ltxi_tupleP {disp disp' n T t1 t2}. Definition ltxi_tuplePlt := @ltxi_tuplePlt. Arguments ltxi_tuplePlt {disp disp' n T t1 t2}. End Exports. End TupleLexiOrder. HB.export TupleLexiOrder.Exports. Module DefaultTupleLexiOrder. Export DefaultTupleLexiOrder. Section DefaultTupleLexiOrder. Context {disp : disp_t}. HB.instance Definition _ n (T : porderType disp) := POrder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : bPOrderType disp) := BPOrder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : tPOrderType disp) := TPOrder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : tbPOrderType disp) := TBPOrder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : orderType disp) := Lattice.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : orderType disp) := DistrLattice.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : orderType disp) := Total.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : bOrderType disp) := BTotal.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : tOrderType disp) := TTotal.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : tbOrderType disp) := TBTotal.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : finPOrderType disp) := FinPOrder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : finBPOrderType disp) := FinBPOrder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : finTPOrderType disp) := FinTPOrder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : finTBPOrderType disp) := FinTBPOrder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : finOrderType disp) := FinTotal.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : finTBOrderType disp) := FinTBTotal.copy (n.-tuple T) (n.-tuplelexi T). End DefaultTupleLexiOrder. End DefaultTupleLexiOrder. (*********************************************) (* We declare an alias of the sets, *) (* which is canonically ordered by inclusion *) (*********************************************) Module SetSubsetOrder. Export SetSubsetOrder. Section SetSubsetOrder. Context {disp : disp_t} {T : finType}. Local Notation "{ 'subset' T }" := (type disp T). Implicit Type (A B C : type disp T). Lemma setKUC B A : A :&: (A :|: B) = A. Proof. by rewrite setUC setKU. Qed. Lemma setKIC B A : A :|: (A :&: B) = A. Proof. by rewrite setIC setKI. Qed. Fact le_anti : antisymmetric (fun A B => A \subset B). Proof. by move=> A B ABA; apply/eqP; rewrite eqEsubset. Qed. #[export] HB.instance Definition _ := Preorder_isPOrder.Build disp {subset T} le_anti. #[export] HB.instance Definition _ := POrder_Meet_isDistrLattice.Build disp {subset T} (@setIC _) (@setUC _) (@setIA _) (@setUA _) setKUC setKIC le_def (@setIUl _). Lemma setIDv A B : B :&: (A :\: B) = set0. Proof. apply/eqP; rewrite -subset0; apply/subsetP => x. by rewrite !inE => /and3P[->]. Qed. #[export] HB.instance Definition _ := @BDistrLattice_hasSectionalComplement.Build disp {subset T} (@setD _) setIDv (@setID _). Lemma setTDsym A : ~: A = setT :\: A. Proof. by rewrite setTD. Qed. #[export] HB.instance Definition _ := CBDistrLattice_hasComplement.Build disp {subset T} setTDsym. Lemma meetEsubset A B : A `&` B = A :&: B. Proof. by []. Qed. Lemma joinEsubset A B : A `|` B = A :|: B. Proof. by []. Qed. Lemma botEsubset : \bot = set0 :> {subset T}. Proof. by []. Qed. Lemma topEsubset : \top = setT :> {subset T}. Proof. by []. Qed. Lemma subEsubset A B : A `\` B = A :\: B. Proof. by []. Qed. Lemma complEsubset A : ~` A = ~: A. Proof. by []. Qed. End SetSubsetOrder. Module Exports. HB.reexport. Definition meetEsubset := @meetEsubset. Definition joinEsubset := @joinEsubset. Definition botEsubset := @botEsubset. Definition topEsubset := @topEsubset. Definition subEsubset := @subEsubset. Definition complEsubset := @complEsubset. End Exports. End SetSubsetOrder. Export SetSubsetOrder.Exports. Module DefaultSetSubsetOrder. Export DefaultSetSubsetOrder. HB.instance Definition _ (T : finType) := CTBDistrLattice.copy {set T} {subset T}. End DefaultSetSubsetOrder. Lemma mono_unique d (T T' : finPOrderType d) (f g : T -> T') : total (<=%O : rel T) -> (#|T'| <= #|T|)%N -> {mono f : x y / x <= y} -> {mono g : x y / x <= y} -> f =1 g. Proof. move=> le_total leT'T lef leg x0; move: {+}x0. suff: finfun f = finfun g by move=> /ffunP + x => /(_ x); rewrite !ffunE. apply: (can_inj fgraphK); apply/val_inj => /=; rewrite !codomE. under eq_map do rewrite ffunE; under [RHS]eq_map do rewrite ffunE. have [finj ginj] := (inc_inj lef, inc_inj leg). have [f' fK f'K] := inj_card_bij finj leT'T. have [g' gK g'K] := inj_card_bij ginj leT'T. apply/eqP; have : [seq f i | i <- enum T] = [seq g i | i <- enum T]. apply: (@sorted_eq _ <=%O le_trans le_anti); rewrite ?mono_sorted_enum//. apply: uniq_perm; rewrite ?map_inj_uniq ?sort_uniq ?fintype.enum_uniq//. move=> x; apply/mapP/mapP => -[y _ ->]. by exists (g' (f y)); rewrite ?mem_enum. by exists (f' (g y)); rewrite ?mem_enum. move=> /eqP; rewrite !eq_map_all all_map [in X in _ -> X]all_map. by have /permPl/perm_all-> := perm_sort <=%O (fintype.enum T). Qed. (* This module should be exported on demand, as in module tagnat below *) Module Import EnumVal. Export EnumVal. Section EnumVal. Import OrdinalOrder.Exports. Variables (d : disp_t) (T : finPOrderType d). Implicit Types (x : T) (A : {pred T}). Section total. (* We circumvent a shortcoming of finOrderType *) (* which requires the type to be nonempty and we do not want to rule this out *) Hypothesis (leT_total : total (<=%O : rel T)). Lemma le_enum_val A : {mono @enum_val _ _ A : i j / i <= j}. Proof. apply: le_mono => i j le_ij. rewrite /enum_val (set_nth_default (enum_default j)) -?cardE//. apply: (sorted_ltn_nth lt_trans); rewrite -?topredE/= -?cardE//. by rewrite lt_sorted_uniq_le enum_uniq/= sort_sorted. Qed. Lemma le_enum_rank_in x0 A (Ax0 : x0 \in A) : {in A &, {mono enum_rank_in Ax0 : x y / x <= y}}. Proof. apply: can_mono_in (@in2W _ _ predT predT _ (@le_enum_val A)) => //. exact/onW_can_in/enum_rankK_in. Qed. Lemma le_enum_rank : {mono @enum_rank d T : i j / i <= j}. Proof. exact: (can_mono (@enum_rankK _ _) (@le_enum_val predT)). Qed. End total. End EnumVal. End EnumVal. Notation le_enum_val := le_enum_val. Notation le_enum_rank_in := le_enum_rank_in. Notation le_enum_rank := le_enum_rank. Module Syntax. Export PreOSyntax. Export DualSyntax. Export DvdSyntax. Export LatticeSyntax. Export BLatticeSyntax. Export TLatticeSyntax. Export CBDistrLatticeSyntax. Export CTBDistrLatticeSyntax. Export DualSyntax. Export DvdSyntax. End Syntax. Module LTheory. Export PreorderTheory. Export BPreorderTheory. Export TPreorderTheory. Export DualPreorder. (* FIXME? *) Export PreOCoercions. Export PreorderTheory. Export POrderTheory. Export BPOrderTheory. Export TPOrderTheory. Export MeetTheory. Export BMeetTheory. Export TMeetTheory. Export JoinTheory. Export BJoinTheory. Export TJoinTheory. Export LatticeTheory. Export DistrLatticeTheory. Export BDistrLatticeTheory. Export TDistrLatticeTheory. Export DualTotalTheory. (* FIXME? *) Export DualOrder. (* FIXME? *) Export OrderMorphismTheory. Export LatticeMorphismTheory. Export BLatticeMorphismTheory. Export TLatticeMorphismTheory. Export ClosedPredicates. Export LatticePred. Export SubPreorderTheory. End LTheory. Module CTheory. Export LTheory. Export CDistrLatticeTheory. Export CBDistrLatticeTheory. Export CTDistrLatticeTheory. Export CTBDistrLatticeTheory. End CTheory. Module TTheory. Export LTheory TotalTheory. End TTheory. Module Theory. Export CTheory TotalTheory. End Theory. Module Exports. HB.reexport. End Exports. End Order. Export Order.Exports. Export Order.Syntax. Export order.Order.Exports. Export Order.POrder.Exports. Export Order.BPOrder.Exports. Export Order.TPOrder.Exports. Export Order.TBPOrder.Exports. Export Order.MeetSemilattice.Exports. Export Order.BMeetSemilattice.Exports. Export Order.TMeetSemilattice.Exports. Export Order.TBMeetSemilattice.Exports. Export Order.JoinSemilattice.Exports. Export Order.BJoinSemilattice.Exports. Export Order.TJoinSemilattice.Exports. Export Order.TBJoinSemilattice.Exports. Export Order.Lattice.Exports. Export Order.BLattice.Exports. Export Order.TLattice.Exports. Export Order.TBLattice.Exports. Export Order.DistrLattice.Exports. Export Order.BDistrLattice.Exports. Export Order.TDistrLattice.Exports. Export Order.TBDistrLattice.Exports. Export Order.Total.Exports. Export Order.BTotal.Exports. Export Order.TTotal.Exports. Export Order.TBTotal.Exports. Export Order.CDistrLattice.Exports. Export Order.CBDistrLattice.Exports. Export Order.CTDistrLattice.Exports. Export Order.CTBDistrLattice.Exports. Export Order.FinPOrder.Exports. Export Order.FinBPOrder.Exports. Export Order.FinTPOrder.Exports. Export Order.FinTBPOrder.Exports. Export Order.FinMeetSemilattice.Exports. Export Order.FinBMeetSemilattice.Exports. Export Order.FinJoinSemilattice.Exports. Export Order.FinTJoinSemilattice.Exports. Export Order.FinLattice.Exports. Export Order.FinTBLattice.Exports. Export Order.FinDistrLattice.Exports. Export Order.FinTBDistrLattice.Exports. Export Order.FinTotal.Exports. Export Order.FinTBTotal.Exports. Export Order.FinCDistrLattice.Exports. Export Order.FinCTBDistrLattice.Exports. (* FIXME: check if covered by Order.Exports *) (* Export Order.NatOrder.Exports. *) (* Export Order.NatMonotonyTheory. *) (* Export Order.NatDvd.Exports. *) (* Export Order.OrdinalOrder.Exports. *) (* Export Order.BoolOrder.Exports. *) (* Export Order.ProdOrder.Exports. *) (* Export Order.SigmaOrder.Exports. *) (* Export Order.ProdLexiOrder.Exports. *) (* Export Order.SeqProdOrder.Exports. *) (* Export Order.SeqLexiOrder.Exports. *) (* Export Order.TupleProdOrder.Exports. *) (* Export Order.TupleLexiOrder.Exports. *) Module DefaultProdOrder := Order.DefaultProdOrder. Module DefaultSeqProdOrder := Order.DefaultSeqProdOrder. Module DefaultTupleProdOrder := Order.DefaultTupleProdOrder. Module DefaultProdLexiOrder := Order.DefaultProdLexiOrder. Module DefaultSeqLexiOrder := Order.DefaultSeqLexiOrder. Module DefaultTupleLexiOrder := Order.DefaultTupleLexiOrder. Import Order.Theory. Module tagnat. Section tagnat. Import Order.EnumVal. Context {n : nat} {p_ : 'I_n -> nat}. Local Notation ordsum := 'I_(\sum_i p_ i)%N. Local Notation T := {i & 'I_(p_ i)}. Implicit Types (i : 'I_n) (s : ordsum) (p : T). Lemma card : #|{: T}| = \sum_i p_ i. Proof. rewrite card_tagged sumnE/= big_map big_enum. by apply: eq_bigr => i _; rewrite card_ord. Qed. Definition sig : ordsum -> T := enum_val \o cast_ord (esym card). Definition rank : T -> ordsum := cast_ord card \o enum_rank. Lemma sigK : cancel sig rank. Proof. by move=> s; rewrite /sig/rank/= enum_valK cast_ord_comp cast_ord_id. Qed. Lemma sig_inj : injective sig. Proof. exact: can_inj sigK. Qed. Lemma rankK : cancel rank sig. Proof. by move=> p; rewrite /sig/rank/= cast_ord_comp cast_ord_id enum_rankK. Qed. Lemma rank_inj : injective rank. Proof. exact: can_inj rankK. Qed. Definition sig1 s : 'I_n := tag (sig s). Definition sig2 s : 'I_(p_ (sig1 s)) := tagged (sig s). Definition Rank i (j : 'I_(p_ i)) := rank (Tagged _ j). Lemma sigE12 s : sig s = @Tagged _ (sig1 s) _ (sig2 s). Proof. by rewrite /sig1 /sig2; case: sig. Qed. Lemma rankE p : rank p = @Rank (tag p) (tagged p). Proof. by case: p. Qed. Lemma sig2K s : Rank (sig2 s) = s. Proof. by rewrite -rankE sigK. Qed. Lemma Rank1K i0 (k : 'I_(p_ i0)) : sig1 (Rank k) = i0. Proof. by rewrite /sig1 /Rank/= rankK/=. Qed. Lemma Rank2K i0 (k : 'I_(p_ i0)) : sig2 (Rank k) = cast_ord (congr1 p_ (esym (Rank1K k))) k. Proof. by apply: val_inj; rewrite /sig2/sig1/Rank/= rankK. Qed. #[local] Hint Resolve sigK rankK : core. Lemma rank_bij : bijective rank. Proof. by exists sig. Qed. Lemma sig_bij : bijective sig. Proof. by exists rank. Qed. Lemma rank_bij_on : {on [pred _ | true], bijective rank}. Proof. exact/onW_bij/rank_bij. Qed. Lemma sig_bij_on : {on [pred _ | true], bijective sig}. Proof. exact/onW_bij/sig_bij. Qed. Lemma le_sig : {mono sig : i j / i <= j}. Proof. by move=> i j; rewrite /sig/= le_enum_val//; apply: le_total. Qed. Lemma le_sig1 : {homo sig1 : i j / i <= j}. Proof. by move=> i j; rewrite /sig1/= -le_sig leEsig/=; case: leP. Qed. Lemma le_rank : {mono rank : p q / p <= q}. Proof. exact: can_mono le_sig. Qed. Lemma le_Rank i : {mono @Rank i : j k / j <= k}. Proof. by move=> j k; rewrite /Rank le_rank/= leEsig/= tagged_asE lexx. Qed. Lemma lt_sig : {mono sig : i j / i < j}. Proof. by move=> i j; rewrite !ltNge le_sig. Qed. Lemma lt_rank : {mono rank : p q / p < q}. Proof. by move=> p q; rewrite !ltNge le_rank. Qed. Lemma lt_Rank i : {mono @Rank i : j k / j < k}. Proof. by move=> j k; rewrite !ltNge le_Rank. Qed. Lemma eq_Rank i i' (j : 'I_(p_ i)) (j': 'I_(p_ i')) : (Rank j == Rank j' :> nat) = (i == i') && (j == j' :> nat). Proof. rewrite val_eqE /Rank -(can_eq sigK) !rankK. case: (i =P i') => ii' /=; last by case: eqVneq => // -[]. by case: _ / ii' in j' *; rewrite eq_Tagged. Qed. Lemma rankEsum p : rank p = \sum_(i < n | (i < tag p)%N) p_ i + tagged p :> nat. Proof. pose sum p := \sum_(i < n | (i < tag p)%N) p_ i + tagged p. rewrite -/(sum _); have sumlt : forall p, (sum p < \sum_i p_ i)%N. rewrite /sum => -[/= i j]. rewrite [ltnRHS](bigID [pred i' : 'I__ | (i' < i)%N])/= ltn_add2l. by rewrite (bigD1 i) ?ltnn//= ltn_addr. suff: rank =1 (fun p => Ordinal (sumlt p)) by move=> /(_ p)/(congr1 val). apply: (Order.mono_unique _ _ le_rank) => //=. - exact: le_total. - by rewrite card card_ord. apply: le_mono => /= -[i j] -[i' j']; rewrite ltEsig/= !ltEord/= /sum leEord/=. case: (ltngtP i i') => //= [ltii' _|/val_inj ii']; last first. by rewrite -ii' in j' *; rewrite tagged_asE => ltjj'; rewrite ltn_add2l. rewrite ltn_addr// (@leq_trans (\sum_(i0 < n | (i0 < i)%N) p_ i0 + p_ i))%N//. by rewrite ltn_add2l. rewrite [leqRHS](bigID [pred i' : 'I__ | (i' < i)%N])/=. rewrite leq_add//; last first. by rewrite (bigD1 i) ?ltnn ?ltii'//= leq_addr. rewrite [leqRHS](eq_bigl [pred k : 'I_n | (k < i)%N])// => k/=. by case: (ltnP k i); rewrite ?andbF// => /ltn_trans->. Qed. Lemma RankEsum i j : @Rank i j = \sum_(k < n | (k < i)%N) p_ k + j :> nat. Proof. by rewrite /Rank rankEsum/=. Qed. Lemma rect s : s = \sum_(i < n | (i < sig1 s)%N) p_ i + sig2 s :> nat. Proof. by rewrite -[s]sigK rankEsum /= sigK. Qed. Lemma eqRank (i0 j : nat) (li0 : (i0 < n)%N) (lj : (j < p_ (Ordinal li0))%N) : (\sum_(i < n | (i < i0)%N) p_ i) + j = Rank (Ordinal lj) :> nat. Proof. by rewrite RankEsum. Qed. End tagnat. End tagnat. Arguments tagnat.Rank {n p_}.
NormNum.lean
/- Copyright (c) 2025. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: euprunin -/ import Mathlib.Tactic.NormNum.Basic import Mathlib.Tactic.NormNum.OfScientific import Mathlib.Tactic.NormNum.Eq import Mathlib.Tactic.NormNum.Ineq import Mathlib.Tactic.NormNum.Pow import Mathlib.Tactic.NormNum.Inv import Mathlib.Tactic.NormNum.DivMod import Mathlib.Data.Rat.Cast.Order /-! We register `norm_num` with the `hint` tactic. -/ register_hint norm_num
SplitSimplicialObject.lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.AlgebraicTopology.SimplicialObject.Split import Mathlib.AlgebraicTopology.DoldKan.Degeneracies import Mathlib.AlgebraicTopology.DoldKan.FunctorN /-! # Split simplicial objects in preadditive categories In this file we define a functor `nondegComplex : SimplicialObject.Split C ⥤ ChainComplex C ℕ` when `C` is a preadditive category with finite coproducts, and get an isomorphism `toKaroubiNondegComplexFunctorIsoN₁ : nondegComplex ⋙ toKaroubi _ ≅ forget C ⋙ DoldKan.N₁`. (See `Equivalence.lean` for the general strategy of proof of the Dold-Kan equivalence.) -/ open CategoryTheory CategoryTheory.Limits CategoryTheory.Category CategoryTheory.Preadditive CategoryTheory.Idempotents Opposite AlgebraicTopology AlgebraicTopology.DoldKan Simplicial DoldKan namespace SimplicialObject namespace Splitting variable {C : Type*} [Category C] {X : SimplicialObject C} (s : Splitting X) /-- The projection on a summand of the coproduct decomposition given by a splitting of a simplicial object. -/ noncomputable def πSummand [HasZeroMorphisms C] {Δ : SimplexCategoryᵒᵖ} (A : IndexSet Δ) : X.obj Δ ⟶ s.N A.1.unop.len := s.desc Δ (fun B => by by_cases h : B = A · exact eqToHom (by subst h; rfl) · exact 0) @[reassoc (attr := simp)] theorem cofan_inj_πSummand_eq_id [HasZeroMorphisms C] {Δ : SimplexCategoryᵒᵖ} (A : IndexSet Δ) : (s.cofan Δ).inj A ≫ s.πSummand A = 𝟙 _ := by simp [πSummand] @[reassoc (attr := simp)] theorem cofan_inj_πSummand_eq_zero [HasZeroMorphisms C] {Δ : SimplexCategoryᵒᵖ} (A B : IndexSet Δ) (h : B ≠ A) : (s.cofan Δ).inj A ≫ s.πSummand B = 0 := by dsimp [πSummand] rw [ι_desc, dif_neg h.symm] variable [Preadditive C] theorem decomposition_id (Δ : SimplexCategoryᵒᵖ) : 𝟙 (X.obj Δ) = ∑ A : IndexSet Δ, s.πSummand A ≫ (s.cofan Δ).inj A := by apply s.hom_ext' intro A dsimp erw [comp_id, comp_sum, Finset.sum_eq_single A, cofan_inj_πSummand_eq_id_assoc] · intro B _ h₂ rw [s.cofan_inj_πSummand_eq_zero_assoc _ _ h₂, zero_comp] · simp @[reassoc (attr := simp)] theorem σ_comp_πSummand_id_eq_zero {n : ℕ} (i : Fin (n + 1)) : X.σ i ≫ s.πSummand (IndexSet.id (op ⦋n + 1⦌)) = 0 := by apply s.hom_ext' intro A dsimp only [SimplicialObject.σ] rw [comp_zero, s.cofan_inj_epi_naturality_assoc A (SimplexCategory.σ i).op, cofan_inj_πSummand_eq_zero] rw [ne_comm] change ¬(A.epiComp (SimplexCategory.σ i).op).EqId rw [IndexSet.eqId_iff_len_eq] have h := SimplexCategory.len_le_of_epi A.e dsimp at h ⊢ omega /-- If a simplicial object `X` in an additive category is split, then `PInfty` vanishes on all the summands of `X _⦋n⦌` which do not correspond to the identity of `⦋n⦌`. -/ theorem cofan_inj_comp_PInfty_eq_zero {X : SimplicialObject C} (s : SimplicialObject.Splitting X) {n : ℕ} (A : SimplicialObject.Splitting.IndexSet (op ⦋n⦌)) (hA : ¬A.EqId) : (s.cofan _).inj A ≫ PInfty.f n = 0 := by rw [SimplicialObject.Splitting.IndexSet.eqId_iff_mono] at hA rw [SimplicialObject.Splitting.cofan_inj_eq, assoc, degeneracy_comp_PInfty X n A.e hA, comp_zero] theorem comp_PInfty_eq_zero_iff {Z : C} {n : ℕ} (f : Z ⟶ X _⦋n⦌) : f ≫ PInfty.f n = 0 ↔ f ≫ s.πSummand (IndexSet.id (op ⦋n⦌)) = 0 := by constructor · intro h rcases n with _ | n · dsimp at h rw [comp_id] at h rw [h, zero_comp] · have h' := f ≫= PInfty_f_add_QInfty_f (n + 1) dsimp at h' rw [comp_id, comp_add, h, zero_add] at h' rw [← h', assoc, QInfty_f, decomposition_Q, Preadditive.sum_comp, Preadditive.comp_sum, Finset.sum_eq_zero] intro i _ simp only [assoc, σ_comp_πSummand_id_eq_zero, comp_zero] · intro h rw [← comp_id f, assoc, s.decomposition_id, Preadditive.sum_comp, Preadditive.comp_sum, Fintype.sum_eq_zero] intro A by_cases hA : A.EqId · dsimp at hA subst hA rw [assoc, reassoc_of% h, zero_comp] · simp only [assoc, s.cofan_inj_comp_PInfty_eq_zero A hA, comp_zero] @[reassoc (attr := simp)] theorem PInfty_comp_πSummand_id (n : ℕ) : PInfty.f n ≫ s.πSummand (IndexSet.id (op ⦋n⦌)) = s.πSummand (IndexSet.id (op ⦋n⦌)) := by conv_rhs => rw [← id_comp (s.πSummand _)] symm rw [← sub_eq_zero, ← sub_comp, ← comp_PInfty_eq_zero_iff, sub_comp, id_comp, PInfty_f_idem, sub_self] @[reassoc (attr := simp)] theorem πSummand_comp_cofan_inj_id_comp_PInfty_eq_PInfty (n : ℕ) : s.πSummand (IndexSet.id (op ⦋n⦌)) ≫ (s.cofan _).inj (IndexSet.id (op ⦋n⦌)) ≫ PInfty.f n = PInfty.f n := by conv_rhs => rw [← id_comp (PInfty.f n)] dsimp only [AlternatingFaceMapComplex.obj_X] rw [s.decomposition_id, Preadditive.sum_comp] rw [Fintype.sum_eq_single (IndexSet.id (op ⦋n⦌)), assoc] rintro A (hA : ¬A.EqId) rw [assoc, s.cofan_inj_comp_PInfty_eq_zero A hA, comp_zero] /-- The differentials `s.d i j : s.N i ⟶ s.N j` on nondegenerate simplices of a split simplicial object are induced by the differentials on the alternating face map complex. -/ @[simp] noncomputable def d (i j : ℕ) : s.N i ⟶ s.N j := (s.cofan _).inj (IndexSet.id (op ⦋i⦌)) ≫ K[X].d i j ≫ s.πSummand (IndexSet.id (op ⦋j⦌)) theorem ιSummand_comp_d_comp_πSummand_eq_zero (j k : ℕ) (A : IndexSet (op ⦋j⦌)) (hA : ¬A.EqId) : (s.cofan _).inj A ≫ K[X].d j k ≫ s.πSummand (IndexSet.id (op ⦋k⦌)) = 0 := by rw [A.eqId_iff_mono] at hA rw [← assoc, ← s.comp_PInfty_eq_zero_iff, assoc, ← PInfty.comm j k, s.cofan_inj_eq, assoc, degeneracy_comp_PInfty_assoc X j A.e hA, zero_comp, comp_zero] /-- If `s` is a splitting of a simplicial object `X` in a preadditive category, `s.nondegComplex` is a chain complex which is given in degree `n` by the nondegenerate `n`-simplices of `X`. -/ @[simps] noncomputable def nondegComplex : ChainComplex C ℕ where X := s.N d := s.d shape i j hij := by simp only [d, K[X].shape i j hij, zero_comp, comp_zero] d_comp_d' i j k _ _ := by simp only [d, assoc] have eq : K[X].d i j ≫ 𝟙 (X.obj (op ⦋j⦌)) ≫ K[X].d j k ≫ s.πSummand (IndexSet.id (op ⦋k⦌)) = 0 := by simp rw [s.decomposition_id] at eq classical rw [Fintype.sum_eq_add_sum_compl (IndexSet.id (op ⦋j⦌)), add_comp, comp_add, assoc, Preadditive.sum_comp, Preadditive.comp_sum, Finset.sum_eq_zero, add_zero] at eq swap · intro A hA simp only [Finset.mem_compl, Finset.mem_singleton] at hA simp only [assoc, ιSummand_comp_d_comp_πSummand_eq_zero _ _ _ _ hA, comp_zero] rw [eq, comp_zero] /-- The chain complex `s.nondegComplex` attached to a splitting of a simplicial object `X` becomes isomorphic to the normalized Moore complex `N₁.obj X` defined as a formal direct factor in the category `Karoubi (ChainComplex C ℕ)`. -/ @[simps] noncomputable def toKaroubiNondegComplexIsoN₁ : (toKaroubi _).obj s.nondegComplex ≅ N₁.obj X where hom := { f := { f := fun n => (s.cofan _).inj (IndexSet.id (op ⦋n⦌)) ≫ PInfty.f n comm' := fun i j _ => by dsimp rw [assoc, assoc, assoc, πSummand_comp_cofan_inj_id_comp_PInfty_eq_PInfty, HomologicalComplex.Hom.comm] } comm := by ext n dsimp rw [id_comp, assoc, PInfty_f_idem] } inv := { f := { f := fun n => s.πSummand (IndexSet.id (op ⦋n⦌)) comm' := fun i j _ => by dsimp slice_rhs 1 1 => rw [← id_comp (K[X].d i j)] dsimp only [AlternatingFaceMapComplex.obj_X] rw [s.decomposition_id, sum_comp, sum_comp, Finset.sum_eq_single (IndexSet.id (op ⦋i⦌)), assoc, assoc] · intro A _ hA simp only [assoc, s.ιSummand_comp_d_comp_πSummand_eq_zero _ _ _ hA, comp_zero] · simp only [Finset.mem_univ, not_true, IsEmpty.forall_iff] } comm := by ext n dsimp simp only [comp_id, PInfty_comp_πSummand_id] } hom_inv_id := by ext n simp only [assoc, PInfty_comp_πSummand_id, Karoubi.comp_f, HomologicalComplex.comp_f, cofan_inj_πSummand_eq_id] rfl inv_hom_id := by ext n simp only [πSummand_comp_cofan_inj_id_comp_PInfty_eq_PInfty, Karoubi.comp_f, HomologicalComplex.comp_f, N₁_obj_p, Karoubi.id_f] end Splitting namespace Split variable {C : Type*} [Category C] [Preadditive C] [HasFiniteCoproducts C] /-- The functor which sends a split simplicial object in a preadditive category to the chain complex which consists of nondegenerate simplices. -/ @[simps] noncomputable def nondegComplexFunctor : Split C ⥤ ChainComplex C ℕ where obj S := S.s.nondegComplex map {S₁ S₂} Φ := { f := Φ.f comm' := fun i j _ => by dsimp erw [← cofan_inj_naturality_symm_assoc Φ (Splitting.IndexSet.id (op ⦋i⦌)), ((alternatingFaceMapComplex C).map Φ.F).comm_assoc i j] simp only [assoc] congr 2 apply S₁.s.hom_ext' intro A dsimp [alternatingFaceMapComplex] rw [cofan_inj_naturality_symm_assoc Φ A] by_cases h : A.EqId · dsimp at h subst h rw [Splitting.cofan_inj_πSummand_eq_id] dsimp rw [comp_id, Splitting.cofan_inj_πSummand_eq_id_assoc] · rw [S₁.s.cofan_inj_πSummand_eq_zero_assoc _ _ (Ne.symm h), S₂.s.cofan_inj_πSummand_eq_zero _ _ (Ne.symm h), zero_comp, comp_zero] } /-- The natural isomorphism (in `Karoubi (ChainComplex C ℕ)`) between the chain complex of nondegenerate simplices of a split simplicial object and the normalized Moore complex defined as a formal direct factor of the alternating face map complex. -/ @[simps!] noncomputable def toKaroubiNondegComplexFunctorIsoN₁ : nondegComplexFunctor ⋙ toKaroubi (ChainComplex C ℕ) ≅ forget C ⋙ DoldKan.N₁ := NatIso.ofComponents (fun S => S.s.toKaroubiNondegComplexIsoN₁) fun Φ => by ext n dsimp simp only [assoc, PInfty_f_idem_assoc] erw [← Split.cofan_inj_naturality_symm_assoc Φ (Splitting.IndexSet.id (op ⦋n⦌))] rw [PInfty_f_naturality] end Split end SimplicialObject
Basic.lean
/- Copyright (c) 2024 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import Mathlib.NumberTheory.GaussSum import Mathlib.NumberTheory.MulChar.Lemmas import Mathlib.RingTheory.RootsOfUnity.Lemmas /-! # Jacobi Sums This file defines the *Jacobi sum* of two multiplicative characters `χ` and `ψ` on a finite commutative ring `R` with values in another commutative ring `R'`: `jacobiSum χ ψ = ∑ x : R, χ x * ψ (1 - x)` (see `jacobiSum`) and provides some basic results and API lemmas on Jacobi sums. ## References We essentially follow * [K. Ireland, M. Rosen, *A classical introduction to modern number theory* (Section 8.3)][IrelandRosen1990] but generalize where appropriate. This is based on Lean code written as part of the bachelor's thesis of Alexander Spahl. -/ open Finset /-! ### Jacobi sums: definition and first properties -/ section Def -- need `Fintype` instead of `Finite` to make `jacobiSum` computable. variable {R R' : Type*} [CommRing R] [Fintype R] [CommRing R'] /-- The *Jacobi sum* of two multiplicative characters on a finite commutative ring. -/ def jacobiSum (χ ψ : MulChar R R') : R' := ∑ x : R, χ x * ψ (1 - x) lemma jacobiSum_comm (χ ψ : MulChar R R') : jacobiSum χ ψ = jacobiSum ψ χ := by simp only [jacobiSum, mul_comm (χ _)] rw [← (Equiv.subLeft 1).sum_comp] simp only [Equiv.subLeft_apply, sub_sub_cancel] /-- The Jacobi sum is compatible with ring homomorphisms. -/ lemma jacobiSum_ringHomComp {R'' : Type*} [CommRing R''] (χ ψ : MulChar R R') (f : R' →+* R'') : jacobiSum (χ.ringHomComp f) (ψ.ringHomComp f) = f (jacobiSum χ ψ) := by simp only [jacobiSum, MulChar.ringHomComp, MulChar.coe_mk, MonoidHom.coe_mk, OneHom.coe_mk, map_sum, map_mul] end Def /-! ### Jacobi sums over finite fields -/ section CommRing variable {F R : Type*} [CommRing F] [Nontrivial F] [Fintype F] [DecidableEq F] [CommRing R] /-- The Jacobi sum of two multiplicative characters on a nontrivial finite commutative ring `F` can be written as a sum over `F \ {0,1}`. -/ lemma jacobiSum_eq_sum_sdiff (χ ψ : MulChar F R) : jacobiSum χ ψ = ∑ x ∈ univ \ {0,1}, χ x * ψ (1 - x) := by simp only [jacobiSum, subset_univ, sum_sdiff_eq_sub, sub_eq_add_neg, left_eq_add, neg_eq_zero] apply sum_eq_zero simp only [mem_insert, mem_singleton, forall_eq_or_imp, χ.map_zero, neg_zero, add_zero, map_one, mul_one, forall_eq, add_neg_cancel, ψ.map_zero, mul_zero, and_self] private lemma jacobiSum_eq_aux (χ ψ : MulChar F R) : jacobiSum χ ψ = ∑ x : F, χ x + ∑ x : F, ψ x - Fintype.card F + ∑ x ∈ univ \ {0, 1}, (χ x - 1) * (ψ (1 - x) - 1) := by rw [jacobiSum] conv => enter [1, 2, x] rw [show ∀ x y : R, x * y = x + y - 1 + (x - 1) * (y - 1) by intros; ring] rw [sum_add_distrib, sum_sub_distrib, sum_add_distrib] conv => enter [1, 1, 1, 2, 2, x]; rw [← Equiv.subLeft_apply 1] rw [(Equiv.subLeft 1).sum_comp ψ, Fintype.card_eq_sum_ones, Nat.cast_sum, Nat.cast_one, sum_sdiff_eq_sub (subset_univ _), ← sub_zero (_ - _ + _), add_sub_assoc] congr rw [sum_pair zero_ne_one, sub_zero, ψ.map_one, χ.map_one, sub_self, mul_zero, zero_mul, add_zero] end CommRing section FiniteField variable {F R : Type*} [Field F] [Fintype F] [CommRing R] /-- The Jacobi sum of twice the trivial multiplicative character on a finite field `F` equals `#F-2`. -/ theorem jacobiSum_trivial_trivial : jacobiSum (MulChar.trivial F R) (MulChar.trivial F R) = Fintype.card F - 2 := by classical rw [jacobiSum_eq_sum_sdiff] have : ∀ x ∈ univ \ {0, 1}, (MulChar.trivial F R) x * (MulChar.trivial F R) (1 - x) = 1 := by intros x hx rw [← map_mul, MulChar.trivial_apply, if_pos] simp only [mem_sdiff, mem_univ, mem_insert, mem_singleton, not_or, ← ne_eq, true_and] at hx simpa only [isUnit_iff_ne_zero, mul_ne_zero_iff, ne_eq, sub_eq_zero, @eq_comm _ _ x] using hx calc ∑ x ∈ univ \ {0, 1}, (MulChar.trivial F R) x * (MulChar.trivial F R) (1 - x) _ = ∑ _ ∈ univ \ {0, 1}, 1 := sum_congr rfl this _ = #(univ \ {0, 1}) := (cast_card _).symm _ = Fintype.card F - 2 := by rw [card_sdiff (subset_univ _), card_univ, card_pair zero_ne_one, Nat.cast_sub <| Nat.add_one_le_of_lt Fintype.one_lt_card, Nat.cast_two] /-- If `1` is the trivial multiplicative character on a finite field `F`, then `J(1,1) = #F-2`. -/ theorem jacobiSum_one_one : jacobiSum (1 : MulChar F R) 1 = Fintype.card F - 2 := jacobiSum_trivial_trivial variable [IsDomain R] -- needed for `MulChar.sum_eq_zero_of_ne_one` /-- If `χ` is a nontrivial multiplicative character on a finite field `F`, then `J(1,χ) = -1`. -/ theorem jacobiSum_one_nontrivial {χ : MulChar F R} (hχ : χ ≠ 1) : jacobiSum 1 χ = -1 := by classical have : ∑ x ∈ univ \ {0, 1}, ((1 : MulChar F R) x - 1) * (χ (1 - x) - 1) = 0 := by apply Finset.sum_eq_zero simp +contextual only [mem_sdiff, mem_univ, mem_insert, mem_singleton, not_or, ← isUnit_iff_ne_zero, true_and, MulChar.one_apply, sub_self, zero_mul, implies_true] simp only [jacobiSum_eq_aux, MulChar.sum_one_eq_card_units, MulChar.sum_eq_zero_of_ne_one hχ, add_zero, Fintype.card_eq_card_units_add_one (α := F), Nat.cast_add, Nat.cast_one, sub_add_cancel_left, this] /-- If `χ` is a nontrivial multiplicative character on a finite field `F`, then `J(χ,χ⁻¹) = -χ(-1)`. -/ theorem jacobiSum_nontrivial_inv {χ : MulChar F R} (hχ : χ ≠ 1) : jacobiSum χ χ⁻¹ = -χ (-1) := by classical rw [jacobiSum] conv => enter [1, 2, x]; rw [MulChar.inv_apply', ← map_mul, ← div_eq_mul_inv] rw [sum_eq_sum_diff_singleton_add (mem_univ (1 : F)), sub_self, div_zero, χ.map_zero, add_zero] have : ∑ x ∈ univ \ {1}, χ (x / (1 - x)) = ∑ x ∈ univ \ {-1}, χ x := by refine sum_bij' (fun a _ ↦ a / (1 - a)) (fun b _ ↦ b / (1 + b)) (fun x hx ↦ ?_) (fun y hy ↦ ?_) (fun x hx ↦ ?_) (fun y hy ↦ ?_) (fun _ _ ↦ rfl) · simp only [mem_sdiff, mem_univ, mem_singleton, true_and] at hx ⊢ rw [div_eq_iff <| sub_ne_zero.mpr ((ne_eq ..).symm ▸ hx).symm, mul_sub, mul_one, neg_one_mul, sub_neg_eq_add, right_eq_add, neg_eq_zero] exact one_ne_zero · simp only [mem_sdiff, mem_univ, mem_singleton, true_and] at hy ⊢ rw [div_eq_iff fun h ↦ hy <| eq_neg_of_add_eq_zero_right h, one_mul, right_eq_add] exact one_ne_zero · simp only [mem_sdiff, mem_univ, mem_singleton, true_and] at hx rw [eq_comm, ← sub_eq_zero] at hx field_simp · simp only [mem_sdiff, mem_univ, mem_singleton, true_and] at hy rw [eq_comm, neg_eq_iff_eq_neg, ← sub_eq_zero, sub_neg_eq_add] at hy field_simp rw [this, ← add_eq_zero_iff_eq_neg, ← sum_eq_sum_diff_singleton_add (mem_univ (-1 : F))] exact MulChar.sum_eq_zero_of_ne_one hχ /-- If `χ` and `φ` are multiplicative characters on a finite field `F` such that `χφ` is nontrivial, then `g(χφ) * J(χ,φ) = g(χ) * g(φ)`. -/ theorem jacobiSum_mul_nontrivial {χ φ : MulChar F R} (h : χ * φ ≠ 1) (ψ : AddChar F R) : gaussSum (χ * φ) ψ * jacobiSum χ φ = gaussSum χ ψ * gaussSum φ ψ := by classical rw [gaussSum_mul _ _ ψ, sum_eq_sum_diff_singleton_add (mem_univ (0 : F))] conv => enter [2, 2, 2, x] rw [zero_sub, neg_eq_neg_one_mul x, map_mul, mul_left_comm (χ x) (φ (-1)), ← MulChar.mul_apply, ψ.map_zero_eq_one, mul_one] rw [← mul_sum _ _ (φ (-1)), MulChar.sum_eq_zero_of_ne_one h, mul_zero, add_zero] have sum_eq : ∀ t ∈ univ \ {0}, (∑ x : F, χ x * φ (t - x)) * ψ t = (∑ y : F, χ (t * y) * φ (t - (t * y))) * ψ t := by intro t ht simp only [mem_sdiff, mem_univ, mem_singleton, true_and] at ht exact congrArg (· * ψ t) (Equiv.sum_comp (Equiv.mulLeft₀ t ht) _).symm simp_rw [← sum_mul, sum_congr rfl sum_eq, ← mul_one_sub, map_mul, mul_assoc] conv => enter [2, 2, t, 1, 2, x, 2]; rw [← mul_assoc, mul_comm (χ x) (φ t)] simp_rw [← mul_assoc, ← MulChar.mul_apply, mul_assoc, ← mul_sum, mul_right_comm] rw [← jacobiSum, ← sum_mul, gaussSum, sum_eq_sum_diff_singleton_add (mem_univ (0 : F)), (χ * φ).map_zero, zero_mul, add_zero] end FiniteField section field_field variable {F F' : Type*} [Fintype F] [Field F] [Field F'] /-- If `χ` and `φ` are multiplicative characters on a finite field `F` with values in another field `F'` and such that `χφ` is nontrivial, then `J(χ,φ) = g(χ) * g(φ) / g(χφ)`. -/ theorem jacobiSum_eq_gaussSum_mul_gaussSum_div_gaussSum (h : (Fintype.card F : F') ≠ 0) {χ φ : MulChar F F'} (hχφ : χ * φ ≠ 1) {ψ : AddChar F F'} (hψ : ψ.IsPrimitive) : jacobiSum χ φ = gaussSum χ ψ * gaussSum φ ψ / gaussSum (χ * φ) ψ := by rw [eq_div_iff <| gaussSum_ne_zero_of_nontrivial h hχφ hψ, mul_comm] exact jacobiSum_mul_nontrivial hχφ ψ open AddChar MulChar in /-- If `χ` and `φ` are multiplicative characters on a finite field `F` with values in another field `F'` such that `χ`, `φ` and `χφ` are all nontrivial and `char F' ≠ char F`, then `J(χ,φ) * J(χ⁻¹,φ⁻¹) = #F` (in `F'`). -/ lemma jacobiSum_mul_jacobiSum_inv (h : ringChar F' ≠ ringChar F) {χ φ : MulChar F F'} (hχ : χ ≠ 1) (hφ : φ ≠ 1) (hχφ : χ * φ ≠ 1) : jacobiSum χ φ * jacobiSum χ⁻¹ φ⁻¹ = Fintype.card F := by obtain ⟨n, hp, hc⟩ := FiniteField.card F (ringChar F) -- Obtain primitive additive character `ψ : F → FF'`. let ψ := FiniteField.primitiveChar F F' h -- the target field of `ψ` let FF' := CyclotomicField ψ.n F' -- Consider `χ` and `φ` as characters `F → FF'`. let χ' := χ.ringHomComp (algebraMap F' FF') let φ' := φ.ringHomComp (algebraMap F' FF') have hinj := (algebraMap F' FF').injective apply hinj rw [map_mul, ← jacobiSum_ringHomComp, ← jacobiSum_ringHomComp] have Hχφ : χ' * φ' ≠ 1 := by rw [← ringHomComp_mul] exact (MulChar.ringHomComp_ne_one_iff hinj).mpr hχφ have Hχφ' : χ'⁻¹ * φ'⁻¹ ≠ 1 := by rwa [← mul_inv, inv_ne_one] have Hχ : χ' ≠ 1 := (MulChar.ringHomComp_ne_one_iff hinj).mpr hχ have Hφ : φ' ≠ 1 := (MulChar.ringHomComp_ne_one_iff hinj).mpr hφ have Hcard : (Fintype.card F : FF') ≠ 0 := by intro H simp only [hc, Nat.cast_pow, ne_eq, PNat.ne_zero, not_false_eq_true, pow_eq_zero_iff] at H exact h <| (Algebra.ringChar_eq F' FF').trans <| CharP.ringChar_of_prime_eq_zero hp H have H := (gaussSum_mul_gaussSum_eq_card Hχφ ψ.prim).trans_ne Hcard apply_fun (gaussSum (χ' * φ') ψ.char * gaussSum (χ' * φ')⁻¹ ψ.char⁻¹ * ·) using mul_right_injective₀ H simp only rw [mul_mul_mul_comm, jacobiSum_mul_nontrivial Hχφ, mul_inv, ← ringHomComp_inv, ← ringHomComp_inv, jacobiSum_mul_nontrivial Hχφ', map_natCast, ← mul_mul_mul_comm, gaussSum_mul_gaussSum_eq_card Hχ ψ.prim, gaussSum_mul_gaussSum_eq_card Hφ ψ.prim, ← mul_inv, gaussSum_mul_gaussSum_eq_card Hχφ ψ.prim] end field_field section image variable {F R : Type*} [Fintype F] [Field F] [CommRing R] [IsDomain R] /-- If `χ` and `φ` are multiplicative characters on a finite field `F` satisfying `χ^n = φ^n = 1` and with values in an integral domain `R`, and `μ` is a primitive `n`th root of unity in `R`, then the Jacobi sum `J(χ,φ)` is in `ℤ[μ] ⊆ R`. -/ lemma jacobiSum_mem_algebraAdjoin_of_pow_eq_one {n : ℕ} [NeZero n] {χ φ : MulChar F R} (hχ : χ ^ n = 1) (hφ : φ ^ n = 1) {μ : R} (hμ : IsPrimitiveRoot μ n) : jacobiSum χ φ ∈ Algebra.adjoin ℤ {μ} := Subalgebra.sum_mem _ fun _ _ ↦ Subalgebra.mul_mem _ (MulChar.apply_mem_algebraAdjoin_of_pow_eq_one hχ hμ _) (MulChar.apply_mem_algebraAdjoin_of_pow_eq_one hφ hμ _) open Algebra in private lemma MulChar.exists_apply_sub_one_eq_mul_sub_one {n : ℕ} [NeZero n] {χ : MulChar F R} {μ : R} (hχ : χ ^ n = 1) (hμ : IsPrimitiveRoot μ n) {x : F} (hx : x ≠ 0) : ∃ z ∈ Algebra.adjoin ℤ {μ}, χ x - 1 = z * (μ - 1) := by obtain ⟨k, _, hk⟩ := exists_apply_eq_pow hχ hμ hx refine hk ▸ ⟨(Finset.range k).sum (μ ^ ·), ?_, (geom_sum_mul μ k).symm⟩ exact Subalgebra.sum_mem _ fun m _ ↦ Subalgebra.pow_mem _ (self_mem_adjoin_singleton _ μ) _ private lemma MulChar.exists_apply_sub_one_mul_apply_sub_one {n : ℕ} [NeZero n] {χ ψ : MulChar F R} {μ : R} (hχ : χ ^ n = 1) (hψ : ψ ^ n = 1) (hμ : IsPrimitiveRoot μ n) (x : F) : ∃ z ∈ Algebra.adjoin ℤ {μ}, (χ x - 1) * (ψ (1 - x) - 1) = z * (μ - 1) ^ 2 := by rcases eq_or_ne x 0 with rfl | hx₀ · exact ⟨0, Subalgebra.zero_mem _, by rw [sub_zero, ψ.map_one, sub_self, mul_zero, zero_mul]⟩ rcases eq_or_ne x 1 with rfl | hx₁ · exact ⟨0, Subalgebra.zero_mem _, by rw [χ.map_one, sub_self, zero_mul, zero_mul]⟩ obtain ⟨z₁, hz₁, Hz₁⟩ := MulChar.exists_apply_sub_one_eq_mul_sub_one hχ hμ hx₀ obtain ⟨z₂, hz₂, Hz₂⟩ := MulChar.exists_apply_sub_one_eq_mul_sub_one hψ hμ (sub_ne_zero_of_ne hx₁.symm) rewrite [Hz₁, Hz₂, sq] exact ⟨z₁ * z₂, Subalgebra.mul_mem _ hz₁ hz₂, mul_mul_mul_comm ..⟩ /-- If `χ` and `ψ` are multiplicative characters of order dividing `n` on a finite field `F` with values in an integral domain `R` and `μ` is a primitive `n`th root of unity in `R`, then `J(χ,ψ) = -1 + z*(μ - 1)^2` for some `z ∈ ℤ[μ] ⊆ R`. (We assume that `#F ≡ 1 mod n`.) Note that we do not state this as a divisibility in `R`, as this would give a weaker statement. -/ lemma exists_jacobiSum_eq_neg_one_add {n : ℕ} (hn : 2 < n) {χ ψ : MulChar F R} {μ : R} (hχ : χ ^ n = 1) (hψ : ψ ^ n = 1) (hn' : n ∣ Fintype.card F - 1) (hμ : IsPrimitiveRoot μ n) : ∃ z ∈ Algebra.adjoin ℤ {μ}, jacobiSum χ ψ = -1 + z * (μ - 1) ^ 2 := by obtain ⟨q, hq⟩ := hn' rw [Nat.sub_eq_iff_eq_add NeZero.one_le] at hq obtain ⟨z₁, hz₁, Hz₁⟩ := hμ.self_sub_one_pow_dvd_order hn by_cases hχ₀ : χ = 1 <;> by_cases hψ₀ : ψ = 1 · rw [hχ₀, hψ₀, jacobiSum_one_one] refine ⟨q * z₁, Subalgebra.mul_mem _ (Subalgebra.natCast_mem _ q) hz₁, ?_⟩ rw [hq, Nat.cast_add, Nat.cast_mul, Hz₁] ring · refine ⟨0, Subalgebra.zero_mem _, ?_⟩ rw [hχ₀, jacobiSum_one_nontrivial hψ₀, zero_mul, add_zero] · refine ⟨0, Subalgebra.zero_mem _, ?_⟩ rw [jacobiSum_comm, hψ₀, jacobiSum_one_nontrivial hχ₀, zero_mul, add_zero] · classical rw [jacobiSum_eq_aux, MulChar.sum_eq_zero_of_ne_one hχ₀, MulChar.sum_eq_zero_of_ne_one hψ₀, hq] have : NeZero n := ⟨by omega⟩ have H := MulChar.exists_apply_sub_one_mul_apply_sub_one hχ hψ hμ have Hcs x := (H x).choose_spec refine ⟨-q * z₁ + ∑ x ∈ (univ \ {0, 1} : Finset F), (H x).choose, ?_, ?_⟩ · refine Subalgebra.add_mem _ (Subalgebra.mul_mem _ (Subalgebra.neg_mem _ ?_) hz₁) ?_ · exact Subalgebra.natCast_mem .. · exact Subalgebra.sum_mem _ fun x _ ↦ (Hcs x).1 · conv => enter [1, 2, 2, x]; rw [(Hcs x).2] rw [← Finset.sum_mul, Nat.cast_add, Nat.cast_mul, Hz₁] ring end image section GaussSum variable {F R : Type*} [Fintype F] [Field F] [CommRing R] [IsDomain R] lemma gaussSum_pow_eq_prod_jacobiSum_aux (χ : MulChar F R) (ψ : AddChar F R) {n : ℕ} (hn₁ : 0 < n) (hn₂ : n < orderOf χ) : gaussSum χ ψ ^ n = gaussSum (χ ^ n) ψ * ∏ j ∈ Ico 1 n, jacobiSum χ (χ ^ j) := by induction n, hn₁ using Nat.le_induction with | base => simp only [pow_one, le_refl, Ico_eq_empty_of_le, prod_empty, mul_one] | succ n hn ih => specialize ih <| lt_trans (Nat.lt_succ_self n) hn₂ have gauss_rw : gaussSum (χ ^ n) ψ * gaussSum χ ψ = jacobiSum χ (χ ^ n) * gaussSum (χ ^ (n + 1)) ψ := by have hχn : χ * (χ ^ n) ≠ 1 := pow_succ' χ n ▸ pow_ne_one_of_lt_orderOf n.add_one_ne_zero hn₂ rw [mul_comm, ← jacobiSum_mul_nontrivial hχn, mul_comm, ← pow_succ'] apply_fun (· * gaussSum χ ψ) at ih rw [mul_right_comm, ← pow_succ, gauss_rw] at ih rw [ih, Finset.prod_Ico_succ_top hn, mul_rotate, mul_assoc] /-- If `χ` is a multiplicative character of order `n ≥ 2` on a finite field `F`, then `g(χ)^n = χ(-1) * #F * J(χ,χ) * J(χ,χ²) * ... * J(χ,χⁿ⁻²)`. -/ theorem gaussSum_pow_eq_prod_jacobiSum {χ : MulChar F R} {ψ : AddChar F R} (hχ : 2 ≤ orderOf χ) (hψ : ψ.IsPrimitive) : gaussSum χ ψ ^ orderOf χ = χ (-1) * Fintype.card F * ∏ i ∈ Ico 1 (orderOf χ - 1), jacobiSum χ (χ ^ i) := by have := gaussSum_pow_eq_prod_jacobiSum_aux χ ψ (n := orderOf χ - 1) (by omega) (by omega) apply_fun (gaussSum χ ψ * ·) at this rw [← pow_succ', Nat.sub_one_add_one_eq_of_pos (by omega)] at this have hχ₁ : χ ≠ 1 := fun h ↦ ((orderOf_one (G := MulChar F R) ▸ h ▸ hχ).trans_lt Nat.one_lt_two).false rw [this, ← mul_assoc, gaussSum_mul_gaussSum_pow_orderOf_sub_one hχ₁ hψ] end GaussSum
AmpleSet.lean
/- Copyright (c) 2021 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Floris van Doorn -/ import Mathlib.Algebra.CharP.Invertible import Mathlib.Analysis.Normed.Module.Convex import Mathlib.Analysis.NormedSpace.Connected import Mathlib.LinearAlgebra.AffineSpace.ContinuousAffineEquiv /-! # Ample subsets of real vector spaces In this file we study ample sets in real vector spaces. A set is ample if all its connected component have full convex hull. Ample sets are an important ingredient for defining ample differential relations. ## Main results - `ampleSet_empty` and `ampleSet_univ`: the empty set and `univ` are ample - `AmpleSet.union`: the union of two ample sets is ample - `AmpleSet.{pre}image`: being ample is invariant under continuous affine equivalences; `AmpleSet.{pre}image_iff` are "iff" versions of these - `AmpleSet.vadd`: in particular, ample-ness is invariant under affine translations - `AmpleSet.of_one_lt_codim`: a linear subspace of codimension at least two has an ample complement. This is the crucial geometric ingredient which allows to apply convex integration to the theory of immersions in positive codimension. ## Implementation notes A priori, the definition of ample subset asks for a vector space structure and a topology on the ambient type without any link between those structures. In practice, we care most about using these for finite dimensional vector spaces with their natural topology. All vector spaces in the file are real vector spaces. While the definition generalises to other connected fields, that is not useful in practice. ## Tags ample set -/ /-! ## Definition and invariance -/ open Set variable {F : Type*} [AddCommGroup F] [Module ℝ F] [TopologicalSpace F] /-- A subset of a topological real vector space is ample if the convex hull of each of its connected components is the full space. -/ def AmpleSet (s : Set F) : Prop := ∀ x ∈ s, convexHull ℝ (connectedComponentIn s x) = univ /-- A whole vector space is ample. -/ @[simp] theorem ampleSet_univ {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] : AmpleSet (univ : Set F) := by intro x _ rw [connectedComponentIn_univ, PreconnectedSpace.connectedComponent_eq_univ, convexHull_univ] /-- The empty set in a vector space is ample. -/ @[simp] theorem ampleSet_empty : AmpleSet (∅ : Set F) := fun _ ↦ False.elim namespace AmpleSet /-- The union of two ample sets is ample. -/ theorem union {s t : Set F} (hs : AmpleSet s) (ht : AmpleSet t) : AmpleSet (s ∪ t) := by intro x hx rcases hx with (h | h) <;> -- The connected component of `x ∈ s` in `s ∪ t` contains the connected component of `x` in `s`, -- hence is also full; similarly for `t`. [have hx := hs x h; have hx := ht x h] <;> rw [← Set.univ_subset_iff, ← hx] <;> apply convexHull_mono <;> apply connectedComponentIn_mono <;> [apply subset_union_left; apply subset_union_right] variable {E : Type*} [AddCommGroup E] [Module ℝ E] [TopologicalSpace E] /-- Images of ample sets under continuous affine equivalences are ample. -/ theorem image {s : Set E} (h : AmpleSet s) (L : E ≃ᴬ[ℝ] F) : AmpleSet (L '' s) := forall_mem_image.mpr fun x hx ↦ calc (convexHull ℝ) (connectedComponentIn (L '' s) (L x)) _ = (convexHull ℝ) (L '' (connectedComponentIn s x)) := .symm <| congrArg _ <| L.toHomeomorph.image_connectedComponentIn hx _ = L '' (convexHull ℝ (connectedComponentIn s x)) := .symm <| L.toAffineMap.image_convexHull _ _ = univ := by rw [h x hx, image_univ, L.surjective.range_eq] /-- A set is ample iff its image under a continuous affine equivalence is. -/ theorem image_iff {s : Set E} (L : E ≃ᴬ[ℝ] F) : AmpleSet (L '' s) ↔ AmpleSet s := ⟨fun h ↦ (L.symm_image_image s) ▸ h.image L.symm, fun h ↦ h.image L⟩ /-- Pre-images of ample sets under continuous affine equivalences are ample. -/ theorem preimage {s : Set F} (h : AmpleSet s) (L : E ≃ᴬ[ℝ] F) : AmpleSet (L ⁻¹' s) := by rw [← L.image_symm_eq_preimage] exact h.image L.symm /-- A set is ample iff its pre-image under a continuous affine equivalence is. -/ theorem preimage_iff {s : Set F} (L : E ≃ᴬ[ℝ] F) : AmpleSet (L ⁻¹' s) ↔ AmpleSet s := ⟨fun h ↦ L.image_preimage s ▸ h.image L, fun h ↦ h.preimage L⟩ open scoped Pointwise /-- Affine translations of ample sets are ample. -/ theorem vadd [ContinuousAdd E] {s : Set E} (h : AmpleSet s) {y : E} : AmpleSet (y +ᵥ s) := h.image (ContinuousAffineEquiv.constVAdd ℝ E y) /-- A set is ample iff its affine translation is. -/ theorem vadd_iff [ContinuousAdd E] {s : Set E} {y : E} : AmpleSet (y +ᵥ s) ↔ AmpleSet s := AmpleSet.image_iff (ContinuousAffineEquiv.constVAdd ℝ E y) /-! ## Subspaces of codimension at least two have ample complement -/ section Codimension /-- Let `E` be a linear subspace in a real vector space. If `E` has codimension at least two, its complement is ample. -/ theorem of_one_lt_codim [IsTopologicalAddGroup F] [ContinuousSMul ℝ F] {E : Submodule ℝ F} (hcodim : 1 < Module.rank ℝ (F ⧸ E)) : AmpleSet (Eᶜ : Set F) := fun x hx ↦ by rw [E.connectedComponentIn_eq_self_of_one_lt_codim hcodim hx, eq_univ_iff_forall] intro y by_cases h : y ∈ E · obtain ⟨z, hz⟩ : ∃ z, z ∉ E := by rw [← not_forall, ← Submodule.eq_top_iff'] rintro rfl simp at hcodim refine segment_subset_convexHull ?_ ?_ (mem_segment_sub_add y z) <;> simpa [sub_eq_add_neg, Submodule.add_mem_iff_right _ h] · exact subset_convexHull ℝ (Eᶜ : Set F) h end Codimension end AmpleSet
Typeclasses.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.MeasureTheory.Measure.Typeclasses.Finite import Mathlib.MeasureTheory.Measure.Typeclasses.NoAtoms import Mathlib.MeasureTheory.Measure.Typeclasses.Probability import Mathlib.MeasureTheory.Measure.Typeclasses.SFinite deprecated_module (since := "2025-04-13")
IsCofibrant.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.AlgebraicTopology.ModelCategory.Instances import Mathlib.CategoryTheory.Limits.Shapes.Terminal /-! # Fibrant and cofibrant objects in a model category Once a category `C` has been endowed with a `CategoryWithCofibrations C` instance, it is possible to define the property `IsCofibrant X` for any `X : C` as an abbreviation for `Cofibration (initial.to X : ⊥_ C ⟶ X)`. (Fibrant objects are defined similarly.) -/ open CategoryTheory Limits namespace HomotopicalAlgebra variable {C : Type*} [Category C] section variable [CategoryWithCofibrations C] [HasInitial C] /-- An object `X` is cofibrant if `⊥_ C ⟶ X` is a cofibration. -/ abbrev IsCofibrant (X : C) : Prop := Cofibration (initial.to X) lemma isCofibrant_iff (X : C) : IsCofibrant X ↔ Cofibration (initial.to X) := Iff.rfl lemma isCofibrant_iff_of_isInitial [(cofibrations C).RespectsIso] {A X : C} (i : A ⟶ X) (hA : IsInitial A) : IsCofibrant X ↔ Cofibration i := by simp only [cofibration_iff] apply (cofibrations C).arrow_mk_iso_iff exact Arrow.isoMk (IsInitial.uniqueUpToIso initialIsInitial hA) (Iso.refl _) lemma isCofibrant_of_cofibration [(cofibrations C).IsStableUnderComposition] {X Y : C} (i : X ⟶ Y) [Cofibration i] [hX : IsCofibrant X] : IsCofibrant Y := by rw [isCofibrant_iff] at hX ⊢ rw [Subsingleton.elim (initial.to Y) (initial.to X ≫ i)] infer_instance section variable (X Y : C) [(cofibrations C).IsStableUnderCobaseChange] [HasInitial C] [HasBinaryCoproduct X Y] instance [hY : IsCofibrant Y] : Cofibration (coprod.inl : X ⟶ X ⨿ Y) := by rw [isCofibrant_iff] at hY rw [cofibration_iff] at hY ⊢ exact MorphismProperty.of_isPushout ((IsPushout.of_isColimit_binaryCofan_of_isInitial (colimit.isColimit (pair X Y)) initialIsInitial).flip) hY instance [HasInitial C] [HasBinaryCoproduct X Y] [hX : IsCofibrant X] : Cofibration (coprod.inr : Y ⟶ X ⨿ Y) := by rw [isCofibrant_iff] at hX rw [cofibration_iff] at hX ⊢ exact MorphismProperty.of_isPushout (IsPushout.of_isColimit_binaryCofan_of_isInitial (colimit.isColimit (pair X Y)) initialIsInitial) hX end end section variable [CategoryWithFibrations C] [HasTerminal C] /-- An object `X` is fibrant if `X ⟶ ⊤_ C` is a fibration. -/ abbrev IsFibrant (X : C) : Prop := Fibration (terminal.from X) lemma isFibrant_iff (X : C) : IsFibrant X ↔ Fibration (terminal.from X) := Iff.rfl lemma isFibrant_iff_of_isTerminal [(fibrations C).RespectsIso] {X Y : C} (p : X ⟶ Y) (hY : IsTerminal Y) : IsFibrant X ↔ Fibration p := by simp only [fibration_iff] symm apply (fibrations C).arrow_mk_iso_iff exact Arrow.isoMk (Iso.refl _) (IsTerminal.uniqueUpToIso hY terminalIsTerminal) lemma isFibrant_of_fibration [(fibrations C).IsStableUnderComposition] {X Y : C} (p : X ⟶ Y) [Fibration p] [hY : IsFibrant Y] : IsFibrant X := by rw [isFibrant_iff] at hY ⊢ rw [Subsingleton.elim (terminal.from X) (p ≫ terminal.from Y)] infer_instance section variable (X Y : C) [(fibrations C).IsStableUnderBaseChange] [HasTerminal C] [HasBinaryProduct X Y] instance [hY : IsFibrant Y] : Fibration (prod.fst : X ⨯ Y ⟶ X) := by rw [isFibrant_iff] at hY rw [fibration_iff] at hY ⊢ exact MorphismProperty.of_isPullback (IsPullback.of_isLimit_binaryFan_of_isTerminal (limit.isLimit (pair X Y)) terminalIsTerminal).flip hY instance [HasTerminal C] [HasBinaryProduct X Y] [hX : IsFibrant X] : Fibration (prod.snd : X ⨯ Y ⟶ Y) := by rw [isFibrant_iff] at hX rw [fibration_iff] at hX ⊢ exact MorphismProperty.of_isPullback (IsPullback.of_isLimit_binaryFan_of_isTerminal (limit.isLimit (pair X Y)) terminalIsTerminal) hX end end end HomotopicalAlgebra
ClusterPt.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Jeremy Avigad -/ import Mathlib.Topology.Neighborhoods /-! # Lemmas on cluster and accumulation points In this file we prove various lemmas on [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. A filter `F` on `X` has `x` as a cluster point if `ClusterPt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : α → X` clusters at `x` along `F : Filter α` if `MapClusterPt x F f : ClusterPt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `MapClusterPt x atTop u`. -/ open Set Filter Topology universe u v w variable {X : Type u} [TopologicalSpace X] {Y : Type v} {ι : Sort w} {α β : Type*} {x : X} {s s₁ s₂ t : Set X} theorem clusterPt_sup {F G : Filter X} : ClusterPt x (F ⊔ G) ↔ ClusterPt x F ∨ ClusterPt x G := by simp only [ClusterPt, inf_sup_left, sup_neBot] theorem ClusterPt.neBot {F : Filter X} (h : ClusterPt x F) : NeBot (𝓝 x ⊓ F) := h theorem Filter.HasBasis.clusterPt_iff {ιX ιF} {pX : ιX → Prop} {sX : ιX → Set X} {pF : ιF → Prop} {sF : ιF → Set X} {F : Filter X} (hX : (𝓝 x).HasBasis pX sX) (hF : F.HasBasis pF sF) : ClusterPt x F ↔ ∀ ⦃i⦄, pX i → ∀ ⦃j⦄, pF j → (sX i ∩ sF j).Nonempty := hX.inf_basis_neBot_iff hF theorem Filter.HasBasis.clusterPt_iff_frequently {ι} {p : ι → Prop} {s : ι → Set X} {F : Filter X} (hx : (𝓝 x).HasBasis p s) : ClusterPt x F ↔ ∀ i, p i → ∃ᶠ x in F, x ∈ s i := by simp only [hx.clusterPt_iff F.basis_sets, Filter.frequently_iff, inter_comm (s _), Set.Nonempty, id, mem_inter_iff] theorem clusterPt_iff_frequently {F : Filter X} : ClusterPt x F ↔ ∀ s ∈ 𝓝 x, ∃ᶠ y in F, y ∈ s := (𝓝 x).basis_sets.clusterPt_iff_frequently theorem ClusterPt.frequently {F : Filter X} {p : X → Prop} (hx : ClusterPt x F) (hp : ∀ᶠ y in 𝓝 x, p y) : ∃ᶠ y in F, p y := clusterPt_iff_frequently.mp hx {y | p y} hp theorem Filter.HasBasis.clusterPt_iff_frequently' {ι} {p : ι → Prop} {s : ι → Set X} {F : Filter X} (hx : F.HasBasis p s) : ClusterPt x F ↔ ∀ i, p i → ∃ᶠ x in 𝓝 x, x ∈ s i := by simp only [(𝓝 x).basis_sets.clusterPt_iff hx, Filter.frequently_iff] exact ⟨fun h a b c d ↦ h d b, fun h a b c d ↦ h c d b⟩ theorem clusterPt_iff_frequently' {F : Filter X} : ClusterPt x F ↔ ∀ s ∈ F, ∃ᶠ y in 𝓝 x, y ∈ s := F.basis_sets.clusterPt_iff_frequently' theorem ClusterPt.frequently' {F : Filter X} {p : X → Prop} (hx : ClusterPt x F) (hp : ∀ᶠ y in F, p y) : ∃ᶠ y in 𝓝 x, p y := clusterPt_iff_frequently'.mp hx {y | p y} hp theorem clusterPt_iff_nonempty {F : Filter X} : ClusterPt x F ↔ ∀ ⦃U : Set X⦄, U ∈ 𝓝 x → ∀ ⦃V⦄, V ∈ F → (U ∩ V).Nonempty := inf_neBot_iff @[deprecated (since := "2025-03-16")] alias clusterPt_iff := clusterPt_iff_nonempty theorem clusterPt_iff_not_disjoint {F : Filter X} : ClusterPt x F ↔ ¬Disjoint (𝓝 x) F := by rw [disjoint_iff, ClusterPt, neBot_iff] protected theorem Filter.HasBasis.clusterPt_iff_forall_mem_closure {ι} {p : ι → Prop} {s : ι → Set X} {F : Filter X} (hF : F.HasBasis p s) : ClusterPt x F ↔ ∀ i, p i → x ∈ closure (s i) := by simp only [(nhds_basis_opens _).clusterPt_iff hF, mem_closure_iff] tauto theorem clusterPt_iff_forall_mem_closure {F : Filter X} : ClusterPt x F ↔ ∀ s ∈ F, x ∈ closure s := F.basis_sets.clusterPt_iff_forall_mem_closure alias ⟨ClusterPt.mem_closure_of_mem, _⟩ := clusterPt_iff_forall_mem_closure /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. See also `mem_closure_iff_clusterPt`. -/ theorem clusterPt_principal_iff : ClusterPt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).Nonempty := inf_principal_neBot_iff theorem clusterPt_principal_iff_frequently : ClusterPt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [clusterPt_principal_iff, frequently_iff, Set.Nonempty, mem_inter_iff] theorem ClusterPt.of_le_nhds {f : Filter X} (H : f ≤ 𝓝 x) [NeBot f] : ClusterPt x f := by rwa [ClusterPt, inf_eq_right.mpr H] theorem ClusterPt.of_le_nhds' {f : Filter X} (H : f ≤ 𝓝 x) (_hf : NeBot f) : ClusterPt x f := ClusterPt.of_le_nhds H theorem ClusterPt.of_nhds_le {f : Filter X} (H : 𝓝 x ≤ f) : ClusterPt x f := by simp only [ClusterPt, inf_eq_left.mpr H, nhds_neBot] theorem ClusterPt.mono {f g : Filter X} (H : ClusterPt x f) (h : f ≤ g) : ClusterPt x g := NeBot.mono H <| inf_le_inf_left _ h theorem ClusterPt.of_inf_left {f g : Filter X} (H : ClusterPt x <| f ⊓ g) : ClusterPt x f := H.mono inf_le_left theorem ClusterPt.of_inf_right {f g : Filter X} (H : ClusterPt x <| f ⊓ g) : ClusterPt x g := H.mono inf_le_right section MapClusterPt variable {F : Filter α} {u : α → X} {x : X} theorem mapClusterPt_def : MapClusterPt x F u ↔ ClusterPt x (map u F) := Iff.rfl alias ⟨MapClusterPt.clusterPt, _⟩ := mapClusterPt_def theorem Filter.EventuallyEq.mapClusterPt_iff {v : α → X} (h : u =ᶠ[F] v) : MapClusterPt x F u ↔ MapClusterPt x F v := by simp only [mapClusterPt_def, map_congr h] alias ⟨MapClusterPt.congrFun, _⟩ := Filter.EventuallyEq.mapClusterPt_iff theorem MapClusterPt.mono {G : Filter α} (h : MapClusterPt x F u) (hle : F ≤ G) : MapClusterPt x G u := h.clusterPt.mono (map_mono hle) theorem MapClusterPt.tendsto_comp' [TopologicalSpace Y] {f : X → Y} {y : Y} (hf : Tendsto f (𝓝 x ⊓ map u F) (𝓝 y)) (hu : MapClusterPt x F u) : MapClusterPt y F (f ∘ u) := (tendsto_inf.2 ⟨hf, tendsto_map.mono_left inf_le_right⟩).neBot (hx := hu) theorem MapClusterPt.tendsto_comp [TopologicalSpace Y] {f : X → Y} {y : Y} (hf : Tendsto f (𝓝 x) (𝓝 y)) (hu : MapClusterPt x F u) : MapClusterPt y F (f ∘ u) := hu.tendsto_comp' (hf.mono_left inf_le_left) theorem MapClusterPt.continuousAt_comp [TopologicalSpace Y] {f : X → Y} (hf : ContinuousAt f x) (hu : MapClusterPt x F u) : MapClusterPt (f x) F (f ∘ u) := hu.tendsto_comp hf theorem Filter.HasBasis.mapClusterPt_iff_frequently {ι : Sort*} {p : ι → Prop} {s : ι → Set X} (hx : (𝓝 x).HasBasis p s) : MapClusterPt x F u ↔ ∀ i, p i → ∃ᶠ a in F, u a ∈ s i := by simp_rw [MapClusterPt, hx.clusterPt_iff_frequently, frequently_map] theorem mapClusterPt_iff_frequently : MapClusterPt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := (𝓝 x).basis_sets.mapClusterPt_iff_frequently @[deprecated (since := "2025-03-16")] alias mapClusterPt_iff := mapClusterPt_iff_frequently theorem MapClusterPt.frequently (h : MapClusterPt x F u) {p : X → Prop} (hp : ∀ᶠ y in 𝓝 x, p y) : ∃ᶠ a in F, p (u a) := h.clusterPt.frequently hp theorem mapClusterPt_comp {φ : α → β} {u : β → X} : MapClusterPt x F (u ∘ φ) ↔ MapClusterPt x (map φ F) u := Iff.rfl theorem Filter.Tendsto.mapClusterPt [NeBot F] (h : Tendsto u F (𝓝 x)) : MapClusterPt x F u := .of_le_nhds h theorem MapClusterPt.of_comp {φ : β → α} {p : Filter β} (h : Tendsto φ p F) (H : MapClusterPt x p (u ∘ φ)) : MapClusterPt x F u := H.clusterPt.mono <| map_mono h end MapClusterPt theorem accPt_sup {x : X} {F G : Filter X} : AccPt x (F ⊔ G) ↔ AccPt x F ∨ AccPt x G := by simp only [AccPt, inf_sup_left, sup_neBot] theorem accPt_iff_clusterPt {x : X} {F : Filter X} : AccPt x F ↔ ClusterPt x (𝓟 {x}ᶜ ⊓ F) := by rw [AccPt, nhdsWithin, ClusterPt, inf_assoc] @[deprecated (since := "2025-04-20")] alias acc_iff_cluster := accPt_iff_clusterPt /-- `x` is an accumulation point of a set `C` iff it is a cluster point of `C ∖ {x}`. -/ theorem accPt_principal_iff_clusterPt {x : X} {C : Set X} : AccPt x (𝓟 C) ↔ ClusterPt x (𝓟 (C \ { x })) := by rw [accPt_iff_clusterPt, inf_principal, inter_comm, diff_eq] @[deprecated (since := "2025-04-20")] alias acc_principal_iff_cluster := accPt_principal_iff_clusterPt /-- `x` is an accumulation point of a set `C` iff every neighborhood of `x` contains a point of `C` other than `x`. -/ theorem accPt_iff_nhds {x : X} {C : Set X} : AccPt x (𝓟 C) ↔ ∀ U ∈ 𝓝 x, ∃ y ∈ U ∩ C, y ≠ x := by simp [accPt_principal_iff_clusterPt, clusterPt_principal_iff, Set.Nonempty, and_assoc] /-- `x` is an accumulation point of a set `C` iff there are points near `x` in `C` and different from `x`. -/ theorem accPt_iff_frequently {x : X} {C : Set X} : AccPt x (𝓟 C) ↔ ∃ᶠ y in 𝓝 x, y ≠ x ∧ y ∈ C := by simp [accPt_principal_iff_clusterPt, clusterPt_principal_iff_frequently, and_comm] /-- Variant of `accPt_iff_frequently`: A point `x` is an accumulation point of a set `C` iff points in punctured neighborhoods are frequently contained in `C`. -/ theorem accPt_iff_frequently_nhdsNE {X : Type*} [TopologicalSpace X] {x : X} {C : Set X} : AccPt x (𝓟 C) ↔ ∃ᶠ (y : X) in 𝓝[≠] x, y ∈ C := by have : (∃ᶠ z in 𝓝[≠] x, z ∈ C) ↔ ∃ᶠ z in 𝓝 x, z ∈ C ∧ z ∈ ({x} : Set X)ᶜ := frequently_inf_principal.trans <| by simp only [and_comm] rw [accPt_iff_frequently, this] congr! 2 tauto theorem accPt_principal_iff_nhdsWithin : AccPt x (𝓟 s) ↔ (𝓝[s \ {x}] x).NeBot := by rw [accPt_principal_iff_clusterPt, ClusterPt, nhdsWithin] /-- If `x` is an accumulation point of `F` and `F ≤ G`, then `x` is an accumulation point of `G`. -/ theorem AccPt.mono {F G : Filter X} (h : AccPt x F) (hFG : F ≤ G) : AccPt x G := NeBot.mono h (inf_le_inf_left _ hFG) theorem AccPt.clusterPt {x : X} {F : Filter X} (h : AccPt x F) : ClusterPt x F := (accPt_iff_clusterPt.mp h).mono inf_le_right theorem clusterPt_principal {x : X} {C : Set X} : ClusterPt x (𝓟 C) ↔ x ∈ C ∨ AccPt x (𝓟 C) := by constructor · intro h by_contra! hc rw [accPt_principal_iff_clusterPt] at hc simp_all only [not_false_eq_true, diff_singleton_eq_self, not_true_eq_false, hc.1] · rintro (h | h) · exact clusterPt_principal_iff.mpr fun _ mem ↦ ⟨x, ⟨mem_of_mem_nhds mem, h⟩⟩ · exact h.clusterPt /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ theorem isClosed_setOf_clusterPt {f : Filter X} : IsClosed { x | ClusterPt x f } := by simp only [clusterPt_iff_forall_mem_closure, setOf_forall] exact isClosed_biInter fun _ _ ↦ isClosed_closure theorem mem_closure_iff_clusterPt : x ∈ closure s ↔ ClusterPt x (𝓟 s) := mem_closure_iff_frequently.trans clusterPt_principal_iff_frequently.symm alias ⟨_, ClusterPt.mem_closure⟩ := mem_closure_iff_clusterPt theorem mem_closure_iff_nhds_ne_bot : x ∈ closure s ↔ 𝓝 x ⊓ 𝓟 s ≠ ⊥ := mem_closure_iff_clusterPt.trans neBot_iff theorem mem_closure_iff_nhdsWithin_neBot : x ∈ closure s ↔ NeBot (𝓝[s] x) := mem_closure_iff_clusterPt lemma notMem_closure_iff_nhdsWithin_eq_bot : x ∉ closure s ↔ 𝓝[s] x = ⊥ := by rw [mem_closure_iff_nhdsWithin_neBot, not_neBot] @[deprecated (since := "2025-05-23")] alias not_mem_closure_iff_nhdsWithin_eq_bot := notMem_closure_iff_nhdsWithin_eq_bot /-- If `x` is not an isolated point of a topological space, then `{x}ᶜ` is dense in the whole space. -/ theorem dense_compl_singleton (x : X) [NeBot (𝓝[≠] x)] : Dense ({x}ᶜ : Set X) := by intro y rcases eq_or_ne y x with (rfl | hne) · rwa [mem_closure_iff_nhdsWithin_neBot] · exact subset_closure hne /-- If `x` is not an isolated point of a topological space, then the closure of `{x}ᶜ` is the whole space. -/ theorem closure_compl_singleton (x : X) [NeBot (𝓝[≠] x)] : closure {x}ᶜ = (univ : Set X) := (dense_compl_singleton x).closure_eq /-- If `x` is not an isolated point of a topological space, then the interior of `{x}` is empty. -/ @[simp] theorem interior_singleton (x : X) [NeBot (𝓝[≠] x)] : interior {x} = (∅ : Set X) := interior_eq_empty_iff_dense_compl.2 (dense_compl_singleton x) theorem not_isOpen_singleton (x : X) [NeBot (𝓝[≠] x)] : ¬IsOpen ({x} : Set X) := dense_compl_singleton_iff_not_open.1 (dense_compl_singleton x) theorem closure_eq_cluster_pts : closure s = { a | ClusterPt a (𝓟 s) } := Set.ext fun _ => mem_closure_iff_clusterPt theorem mem_closure_iff_nhds : x ∈ closure s ↔ ∀ t ∈ 𝓝 x, (t ∩ s).Nonempty := mem_closure_iff_clusterPt.trans clusterPt_principal_iff theorem mem_closure_iff_nhds' : x ∈ closure s ↔ ∀ t ∈ 𝓝 x, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, Set.inter_nonempty_iff_exists_right, SetCoe.exists, exists_prop] theorem mem_closure_iff_comap_neBot : x ∈ closure s ↔ NeBot (comap ((↑) : s → X) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_neBot_iff, Set.inter_nonempty_iff_exists_right, SetCoe.exists, exists_prop] theorem mem_closure_iff_nhds_basis' {p : ι → Prop} {s : ι → Set X} (h : (𝓝 x).HasBasis p s) : x ∈ closure t ↔ ∀ i, p i → (s i ∩ t).Nonempty := mem_closure_iff_clusterPt.trans <| (h.clusterPt_iff (hasBasis_principal _)).trans <| by simp only [forall_const] theorem mem_closure_iff_nhds_basis {p : ι → Prop} {s : ι → Set X} (h : (𝓝 x).HasBasis p s) : x ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := (mem_closure_iff_nhds_basis' h).trans <| by simp only [Set.Nonempty, mem_inter_iff, and_comm] theorem clusterPt_iff_lift'_closure {F : Filter X} : ClusterPt x F ↔ pure x ≤ (F.lift' closure) := by simp_rw [clusterPt_iff_forall_mem_closure, (hasBasis_pure _).le_basis_iff F.basis_sets.lift'_closure, id, singleton_subset_iff, true_and, exists_const] theorem clusterPt_iff_lift'_closure' {F : Filter X} : ClusterPt x F ↔ (F.lift' closure ⊓ pure x).NeBot := by rw [clusterPt_iff_lift'_closure, inf_comm] constructor · intro h simp [h, pure_neBot] · intro h U hU simp_rw [← forall_mem_nonempty_iff_neBot, mem_inf_iff] at h simpa using h ({x} ∩ U) ⟨{x}, by simp, U, hU, rfl⟩ @[simp] theorem clusterPt_lift'_closure_iff {F : Filter X} : ClusterPt x (F.lift' closure) ↔ ClusterPt x F := by simp [clusterPt_iff_lift'_closure, lift'_lift'_assoc (monotone_closure X) (monotone_closure X)] theorem isClosed_iff_clusterPt : IsClosed s ↔ ∀ a, ClusterPt a (𝓟 s) → a ∈ s := calc IsClosed s ↔ closure s ⊆ s := closure_subset_iff_isClosed.symm _ ↔ ∀ a, ClusterPt a (𝓟 s) → a ∈ s := by simp only [subset_def, mem_closure_iff_clusterPt] theorem isClosed_iff_nhds : IsClosed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).Nonempty) → x ∈ s := by simp_rw [isClosed_iff_clusterPt, ClusterPt, inf_principal_neBot_iff] lemma isClosed_iff_forall_filter : IsClosed s ↔ ∀ x, ∀ F : Filter X, F.NeBot → F ≤ 𝓟 s → F ≤ 𝓝 x → x ∈ s := by simp_rw [isClosed_iff_clusterPt] exact ⟨fun hs x F F_ne FS Fx ↦ hs _ <| NeBot.mono F_ne (le_inf Fx FS), fun hs x hx ↦ hs x (𝓝 x ⊓ 𝓟 s) hx inf_le_right inf_le_left⟩ theorem mem_closure_of_mem_closure_union (h : x ∈ closure (s₁ ∪ s₂)) (h₁ : s₁ᶜ ∈ 𝓝 x) : x ∈ closure s₂ := by rw [mem_closure_iff_nhds_ne_bot] at * rwa [← sup_principal, inf_sup_left, inf_principal_eq_bot.mpr h₁, bot_sup_eq] at h
Instances.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Batteries.Data.DList.Lemmas import Mathlib.Control.Traversable.Equiv import Mathlib.Control.Traversable.Instances /-! # Traversable instance for DLists This file provides the equivalence between `List α` and `DList α` and the traversable instance for `DList`. -/ open Function Equiv namespace Batteries variable (α : Type*) /-- The natural equivalence between lists and difference lists, using `DList.ofList` and `DList.toList`. -/ def DList.listEquivDList : List α ≃ DList α where toFun := DList.ofList invFun := DList.toList left_inv _ := DList.toList_ofList _ right_inv _ := DList.ofList_toList _ instance : Traversable DList := Equiv.traversable DList.listEquivDList instance : LawfulTraversable DList := Equiv.isLawfulTraversable DList.listEquivDList instance {α} : Inhabited (DList α) := ⟨DList.empty⟩ end Batteries
Completion.lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Analysis.Normed.Group.Uniform import Mathlib.Topology.Algebra.GroupCompletion import Mathlib.Topology.MetricSpace.Completion /-! # Completion of a normed group In this file we prove that the completion of a (semi)normed group is a normed group. ## Tags normed group, completion -/ noncomputable section namespace UniformSpace namespace Completion variable (E : Type*) instance [UniformSpace E] [Norm E] : Norm (Completion E) where norm := Completion.extension Norm.norm @[simp] theorem norm_coe {E} [SeminormedAddCommGroup E] (x : E) : ‖(x : Completion E)‖ = ‖x‖ := Completion.extension_coe uniformContinuous_norm x instance [SeminormedAddCommGroup E] : NormedAddCommGroup (Completion E) where dist_eq x y := by induction x, y using Completion.induction_on₂ · refine isClosed_eq (Completion.uniformContinuous_extension₂ _).continuous ?_ exact Continuous.comp Completion.continuous_extension continuous_sub · rw [← Completion.coe_sub, norm_coe, Completion.dist_eq, dist_eq_norm] @[simp] theorem nnnorm_coe {E} [SeminormedAddCommGroup E] (x : E) : ‖(x : Completion E)‖₊ = ‖x‖₊ := by simp [nnnorm] @[simp] lemma enorm_coe {E} [SeminormedAddCommGroup E] (x : E) : ‖(x : Completion E)‖ₑ = ‖x‖ₑ := by simp [enorm] end Completion end UniformSpace
Subadditive.lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Order.Filter.AtTopBot.Archimedean import Mathlib.Order.Filter.AtTopBot.Finite import Mathlib.Order.Filter.AtTopBot.Prod import Mathlib.Topology.Algebra.Ring.Real /-! # Convergence of subadditive sequences A subadditive sequence `u : ℕ → ℝ` is a sequence satisfying `u (m + n) ≤ u m + u n` for all `m, n`. We define this notion as `Subadditive u`, and prove in `Subadditive.tendsto_lim` that, if `u n / n` is bounded below, then it converges to a limit (that we denote by `Subadditive.lim` for convenience). This result is known as Fekete's lemma in the literature. ## TODO Define a bundled `SubadditiveHom`, use it. -/ noncomputable section open Set Filter Topology /-- A real-valued sequence is subadditive if it satisfies the inequality `u (m + n) ≤ u m + u n` for all `m, n`. -/ def Subadditive (u : ℕ → ℝ) : Prop := ∀ m n, u (m + n) ≤ u m + u n namespace Subadditive variable {u : ℕ → ℝ} (h : Subadditive u) /-- The limit of a bounded-below subadditive sequence. The fact that the sequence indeed tends to this limit is given in `Subadditive.tendsto_lim` -/ @[nolint unusedArguments, irreducible] protected def lim (_h : Subadditive u) := sInf ((fun n : ℕ => u n / n) '' Ici 1) theorem lim_le_div (hbdd : BddBelow (range fun n => u n / n)) {n : ℕ} (hn : n ≠ 0) : h.lim ≤ u n / n := by rw [Subadditive.lim] exact csInf_le (hbdd.mono <| image_subset_range _ _) ⟨n, hn.bot_lt, rfl⟩ include h in theorem apply_mul_add_le (k n r) : u (k * n + r) ≤ k * u n + u r := by induction k with | zero => simp only [Nat.cast_zero, zero_mul, zero_add]; rfl | succ k IH => calc u ((k + 1) * n + r) = u (n + (k * n + r)) := by congr 1; ring _ ≤ u n + u (k * n + r) := h _ _ _ ≤ u n + (k * u n + u r) := add_le_add_left IH _ _ = (k + 1 : ℕ) * u n + u r := by simp; ring include h in theorem eventually_div_lt_of_div_lt {L : ℝ} {n : ℕ} (hn : n ≠ 0) (hL : u n / n < L) : ∀ᶠ p in atTop, u p / p < L := by /- It suffices to prove the statement for each arithmetic progression `(n * · + r)`. -/ refine .atTop_of_arithmetic hn fun r _ => ?_ /- `(k * u n + u r) / (k * n + r)` tends to `u n / n < L`, hence `(k * u n + u r) / (k * n + r) < L` for sufficiently large `k`. -/ have A : Tendsto (fun x : ℝ => (u n + u r / x) / (n + r / x)) atTop (𝓝 ((u n + 0) / (n + 0))) := (tendsto_const_nhds.add <| tendsto_const_nhds.div_atTop tendsto_id).div (tendsto_const_nhds.add <| tendsto_const_nhds.div_atTop tendsto_id) <| by simpa have B : Tendsto (fun x => (x * u n + u r) / (x * n + r)) atTop (𝓝 (u n / n)) := by rw [add_zero, add_zero] at A refine A.congr' <| (eventually_ne_atTop 0).mono fun x hx => ?_ simp only [add_div' _ _ _ hx, div_div_div_cancel_right₀ hx, mul_comm] refine ((B.comp tendsto_natCast_atTop_atTop).eventually (gt_mem_nhds hL)).mono fun k hk => ?_ /- Finally, we use an upper estimate on `u (k * n + r)` to get an estimate on `u (k * n + r) / (k * n + r)`. -/ rw [mul_comm] refine lt_of_le_of_lt ?_ hk simp only [(· ∘ ·), ← Nat.cast_add, ← Nat.cast_mul] gcongr apply h.apply_mul_add_le /-- Fekete's lemma: a subadditive sequence which is bounded below converges. -/ theorem tendsto_lim (hbdd : BddBelow (range fun n => u n / n)) : Tendsto (fun n => u n / n) atTop (𝓝 h.lim) := by refine tendsto_order.2 ⟨fun l hl => ?_, fun L hL => ?_⟩ · refine eventually_atTop.2 ⟨1, fun n hn => hl.trans_le (h.lim_le_div hbdd (zero_lt_one.trans_le hn).ne')⟩ · obtain ⟨n, npos, hn⟩ : ∃ n : ℕ, 0 < n ∧ u n / n < L := by rw [Subadditive.lim] at hL rcases exists_lt_of_csInf_lt (by simp) hL with ⟨x, hx, xL⟩ rcases (mem_image _ _ _).1 hx with ⟨n, hn, rfl⟩ exact ⟨n, zero_lt_one.trans_le hn, xL⟩ exact h.eventually_div_lt_of_div_lt npos.ne' hn end Subadditive
Holor.lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import Mathlib.Data.Nat.Find import Mathlib.Algebra.Module.Pi import Mathlib.Algebra.BigOperators.Group.Finset.Basic /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `List ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : Holor α ds₁` and `x₂ : Holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ universe u open List /-- `HolorIndex ds` is the type of valid index tuples used to identify an entry of a holor of dimensions `ds`. -/ def HolorIndex (ds : List ℕ) : Type := { is : List ℕ // Forall₂ (· < ·) is ds } namespace HolorIndex variable {ds₁ ds₂ ds₃ : List ℕ} /-- Take the first elements of a `HolorIndex`. -/ def take : ∀ {ds₁ : List ℕ}, HolorIndex (ds₁ ++ ds₂) → HolorIndex ds₁ | ds, is => ⟨List.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2⟩ /-- Drop the first elements of a `HolorIndex`. -/ def drop : ∀ {ds₁ : List ℕ}, HolorIndex (ds₁ ++ ds₂) → HolorIndex ds₂ | ds, is => ⟨List.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2⟩ theorem cast_type (is : List ℕ) (eq : ds₁ = ds₂) (h : Forall₂ (· < ·) is ds₁) : (cast (congr_arg HolorIndex eq) ⟨is, h⟩).val = is := by subst eq; rfl /-- Right associator for `HolorIndex` -/ def assocRight : HolorIndex (ds₁ ++ ds₂ ++ ds₃) → HolorIndex (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg HolorIndex (append_assoc ds₁ ds₂ ds₃)) /-- Left associator for `HolorIndex` -/ def assocLeft : HolorIndex (ds₁ ++ (ds₂ ++ ds₃)) → HolorIndex (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg HolorIndex (append_assoc ds₁ ds₂ ds₃).symm) theorem take_take : ∀ t : HolorIndex (ds₁ ++ ds₂ ++ ds₃), t.assocRight.take = t.take.take | ⟨is, h⟩ => Subtype.eq <| by simp [assocRight, take, cast_type, List.take_take, Nat.le_add_right] theorem drop_take : ∀ t : HolorIndex (ds₁ ++ ds₂ ++ ds₃), t.assocRight.drop.take = t.take.drop | ⟨is, h⟩ => Subtype.eq (by simp [assocRight, take, drop, cast_type, List.drop_take]) theorem drop_drop : ∀ t : HolorIndex (ds₁ ++ ds₂ ++ ds₃), t.assocRight.drop.drop = t.drop | ⟨is, h⟩ => Subtype.eq (by simp [assocRight, drop, cast_type, List.drop_drop]) end HolorIndex /-- Holor (indexed collections of tensor coefficients) -/ def Holor (α : Type u) (ds : List ℕ) := HolorIndex ds → α namespace Holor variable {α : Type} {d : ℕ} {ds : List ℕ} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} instance [Inhabited α] : Inhabited (Holor α ds) := ⟨fun _ => default⟩ instance [Zero α] : Zero (Holor α ds) := ⟨fun _ => 0⟩ instance [Add α] : Add (Holor α ds) := ⟨fun x y t => x t + y t⟩ instance [Neg α] : Neg (Holor α ds) := ⟨fun a t => -a t⟩ instance [AddSemigroup α] : AddSemigroup (Holor α ds) := Pi.addSemigroup instance [AddCommSemigroup α] : AddCommSemigroup (Holor α ds) := Pi.addCommSemigroup instance [AddMonoid α] : AddMonoid (Holor α ds) := Pi.addMonoid instance [AddCommMonoid α] : AddCommMonoid (Holor α ds) := Pi.addCommMonoid instance [AddGroup α] : AddGroup (Holor α ds) := Pi.addGroup instance [AddCommGroup α] : AddCommGroup (Holor α ds) := Pi.addCommGroup -- scalar product instance [Mul α] : SMul α (Holor α ds) := ⟨fun a x => fun t => a * x t⟩ instance [Semiring α] : Module α (Holor α ds) := Pi.module _ _ _ /-- The tensor product of two holors. -/ def mul [Mul α] (x : Holor α ds₁) (y : Holor α ds₂) : Holor α (ds₁ ++ ds₂) := fun t => x t.take * y t.drop local infixl:70 " ⊗ " => mul theorem cast_type (eq : ds₁ = ds₂) (a : Holor α ds₁) : cast (congr_arg (Holor α) eq) a = fun t => a (cast (congr_arg HolorIndex eq.symm) t) := by subst eq; rfl /-- Right associator for `Holor` -/ def assocRight : Holor α (ds₁ ++ ds₂ ++ ds₃) → Holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (Holor α) (append_assoc ds₁ ds₂ ds₃)) /-- Left associator for `Holor` -/ def assocLeft : Holor α (ds₁ ++ (ds₂ ++ ds₃)) → Holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (Holor α) (append_assoc ds₁ ds₂ ds₃).symm) theorem mul_assoc0 [Semigroup α] (x : Holor α ds₁) (y : Holor α ds₂) (z : Holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assocLeft := funext fun t : HolorIndex (ds₁ ++ ds₂ ++ ds₃) => by rw [assocLeft] unfold mul rw [mul_assoc, ← HolorIndex.take_take, ← HolorIndex.drop_take, ← HolorIndex.drop_drop, cast_type] · rfl rw [append_assoc] theorem mul_assoc [Semigroup α] (x : Holor α ds₁) (y : Holor α ds₂) (z : Holor α ds₃) : mul (mul x y) z ≍ mul x (mul y z) := by simp [cast_heq, mul_assoc0, assocLeft] theorem mul_left_distrib [Distrib α] (x : Holor α ds₁) (y : Holor α ds₂) (z : Holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext fun t => left_distrib (x t.take) (y t.drop) (z t.drop) theorem mul_right_distrib [Distrib α] (x : Holor α ds₁) (y : Holor α ds₁) (z : Holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext fun t => add_mul (x t.take) (y t.take) (z t.drop) @[simp] nonrec theorem zero_mul {α : Type} [MulZeroClass α] (x : Holor α ds₂) : (0 : Holor α ds₁) ⊗ x = 0 := funext fun t => zero_mul (x (HolorIndex.drop t)) @[simp] nonrec theorem mul_zero {α : Type} [MulZeroClass α] (x : Holor α ds₁) : x ⊗ (0 : Holor α ds₂) = 0 := funext fun t => mul_zero (x (HolorIndex.take t)) theorem mul_scalar_mul [Mul α] (x : Holor α []) (y : Holor α ds) : x ⊗ y = x ⟨[], Forall₂.nil⟩ • y := by simp +unfoldPartialApp [mul, SMul.smul, HolorIndex.take, HolorIndex.drop, HSMul.hSMul] -- holor slices /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : Holor α (d :: ds)) (i : ℕ) (h : i < d) : Holor α ds := fun is : HolorIndex ds => x ⟨i :: is.1, Forall₂.cons h is.2⟩ /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unitVec [Monoid α] [AddMonoid α] (d : ℕ) (j : ℕ) : Holor α [d] := fun ti => if ti.1 = [j] then 1 else 0 theorem holor_index_cons_decomp (p : HolorIndex (d :: ds) → Prop) : ∀ t : HolorIndex (d :: ds), (∀ i is, ∀ h : t.1 = i :: is, p ⟨i :: is, by rw [← h]; exact t.2⟩) → p t | ⟨[], hforall₂⟩, _ => absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨i :: is, _⟩, hp => hp i is rfl /-- Two holors are equal if all their slices are equal. -/ theorem slice_eq (x : Holor α (d :: ds)) (y : Holor α (d :: ds)) (h : slice x = slice y) : x = y := funext fun t : HolorIndex (d :: ds) => holor_index_cons_decomp (fun t => x t = y t) t fun i is hiis => have hiisdds : Forall₂ (· < ·) (i :: is) (d :: ds) := by rw [← hiis]; exact t.2 have hid : i < d := (forall₂_cons.1 hiisdds).1 have hisds : Forall₂ (· < ·) is ds := (forall₂_cons.1 hiisdds).2 calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ := congr_arg x (Subtype.eq rfl) _ = slice y i hid ⟨is, hisds⟩ := by rw [h] _ = y ⟨i :: is, _⟩ := congr_arg y (Subtype.eq rfl) theorem slice_unitVec_mul [Semiring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : Holor α ds) : slice (unitVec d j ⊗ x) i hid = if i = j then x else 0 := funext fun t : HolorIndex ds => if h : i = j then by simp [slice, mul, HolorIndex.take, unitVec, HolorIndex.drop, h] else by simp [slice, mul, HolorIndex.take, unitVec, HolorIndex.drop, h]; rfl theorem slice_add [Add α] (i : ℕ) (hid : i < d) (x : Holor α (d :: ds)) (y : Holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := funext fun t => by simp [slice, (· + ·), Add.add] theorem slice_zero [Zero α] (i : ℕ) (hid : i < d) : slice (0 : Holor α (d :: ds)) i hid = 0 := rfl theorem slice_sum [AddCommMonoid α] {β : Type} (i : ℕ) (hid : i < d) (s : Finset β) (f : β → Holor α (d :: ds)) : (∑ x ∈ s, slice (f x) i hid) = slice (∑ x ∈ s, f x) i hid := by letI := Classical.decEq β refine Finset.induction_on s ?_ ?_ · simp [slice_zero] · intro _ _ h_not_in ih rw [Finset.sum_insert h_not_in, ih, slice_add, Finset.sum_insert h_not_in] /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] theorem sum_unitVec_mul_slice [Semiring α] (x : Holor α (d :: ds)) : (∑ i ∈ (Finset.range d).attach, unitVec d i ⊗ slice x i (Nat.succ_le_of_lt (Finset.mem_range.1 i.prop))) = x := by apply slice_eq _ _ _ ext i hid rw [← slice_sum] simp only [slice_unitVec_mul hid] rw [Finset.sum_eq_single (Subtype.mk i <| Finset.mem_range.2 hid)] · simp · intro (b : { x // x ∈ Finset.range d }) (_ : b ∈ (Finset.range d).attach) (hbi : b ≠ ⟨i, _⟩) have hbi' : i ≠ b := by simpa only [Ne, Subtype.ext_iff, Subtype.coe_mk] using hbi.symm simp [hbi'] · intro (hid' : Subtype.mk i _ ∉ Finset.attach (Finset.range d)) exfalso exact absurd (Finset.mem_attach _ _) hid' -- CP rank /-- `CPRankMax1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive CPRankMax1 [Mul α] : ∀ {ds}, Holor α ds → Prop | nil (x : Holor α []) : CPRankMax1 x | cons {d} {ds} (x : Holor α [d]) (y : Holor α ds) : CPRankMax1 y → CPRankMax1 (x ⊗ y) /-- `CPRankMax N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive CPRankMax [Mul α] [AddMonoid α] : ℕ → ∀ {ds}, Holor α ds → Prop | zero {ds} : CPRankMax 0 (0 : Holor α ds) | succ (n) {ds} (x : Holor α ds) (y : Holor α ds) : CPRankMax1 x → CPRankMax n y → CPRankMax (n + 1) (x + y) theorem cprankMax_nil [Mul α] [AddMonoid α] (x : Holor α nil) : CPRankMax 1 x := by have h := CPRankMax.succ 0 x 0 (CPRankMax1.nil x) CPRankMax.zero rwa [add_zero x, zero_add] at h theorem cprankMax_1 [Mul α] [AddMonoid α] {x : Holor α ds} (h : CPRankMax1 x) : CPRankMax 1 x := by have h' := CPRankMax.succ 0 x 0 h CPRankMax.zero rwa [zero_add, add_zero] at h' theorem cprankMax_add [Mul α] [AddMonoid α] : ∀ {m : ℕ} {n : ℕ} {x : Holor α ds} {y : Holor α ds}, CPRankMax m x → CPRankMax n y → CPRankMax (m + n) (x + y) | 0, n, x, y, hx, hy => by match hx with | CPRankMax.zero => simp only [zero_add, hy] | m + 1, n, _, y, CPRankMax.succ _ x₁ x₂ hx₁ hx₂, hy => by suffices CPRankMax (m + n + 1) (x₁ + (x₂ + y)) by simpa only [add_comm, add_assoc, add_left_comm] using this apply CPRankMax.succ · assumption · exact cprankMax_add hx₂ hy theorem cprankMax_mul [NonUnitalNonAssocSemiring α] : ∀ (n : ℕ) (x : Holor α [d]) (y : Holor α ds), CPRankMax n y → CPRankMax n (x ⊗ y) | 0, x, _, CPRankMax.zero => by simp [mul_zero x, CPRankMax.zero] | n + 1, x, _, CPRankMax.succ _ y₁ y₂ hy₁ hy₂ => by rw [mul_left_distrib] rw [Nat.add_comm] apply cprankMax_add · exact cprankMax_1 (CPRankMax1.cons _ _ hy₁) · exact cprankMax_mul _ x y₂ hy₂ theorem cprankMax_sum [NonUnitalNonAssocSemiring α] {β} {n : ℕ} (s : Finset β) (f : β → Holor α ds) : (∀ x ∈ s, CPRankMax n (f x)) → CPRankMax (s.card * n) (∑ x ∈ s, f x) := letI := Classical.decEq β Finset.induction_on s (by simp [CPRankMax.zero]) (by intro x s (h_x_notin_s : x ∉ s) ih h_cprank simp only [Finset.sum_insert h_x_notin_s, Finset.card_insert_of_notMem h_x_notin_s] rw [Nat.right_distrib] simp only [Nat.one_mul, Nat.add_comm] have ih' : CPRankMax (Finset.card s * n) (∑ x ∈ s, f x) := by apply ih intro (x : β) (h_x_in_s : x ∈ s) simp only [h_cprank, Finset.mem_insert_of_mem, h_x_in_s] exact cprankMax_add (h_cprank x (Finset.mem_insert_self x s)) ih') theorem cprankMax_upper_bound [Semiring α] : ∀ {ds}, ∀ x : Holor α ds, CPRankMax ds.prod x | [], x => cprankMax_nil x | d :: ds, x => by have h_summands : ∀ i : { x // x ∈ Finset.range d }, CPRankMax ds.prod (unitVec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)) := fun i => cprankMax_mul _ _ _ (cprankMax_upper_bound (slice x i.1 (mem_range.1 i.2))) have h_dds_prod : (List.cons d ds).prod = Finset.card (Finset.range d) * prod ds := by simp [Finset.card_range] have : CPRankMax (Finset.card (Finset.attach (Finset.range d)) * prod ds) (∑ i ∈ Finset.attach (Finset.range d), unitVec d i.val ⊗ slice x i.val (mem_range.1 i.2)) := cprankMax_sum (Finset.range d).attach _ fun i _ => h_summands i have h_cprankMax_sum : CPRankMax (Finset.card (Finset.range d) * prod ds) (∑ i ∈ Finset.attach (Finset.range d), unitVec d i.val ⊗ slice x i.val (mem_range.1 i.2)) := by rwa [Finset.card_attach] at this rw [← sum_unitVec_mul_slice x] rw [h_dds_prod] exact h_cprankMax_sum /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ noncomputable def cprank [Ring α] (x : Holor α ds) : Nat := @Nat.find (fun n => CPRankMax n x) (Classical.decPred _) ⟨ds.prod, cprankMax_upper_bound x⟩ theorem cprank_upper_bound [Ring α] : ∀ {ds}, ∀ x : Holor α ds, cprank x ≤ ds.prod := fun {ds} x => letI := Classical.decPred fun n : ℕ => CPRankMax n x Nat.find_min' ⟨ds.prod, show (fun n => CPRankMax n x) ds.prod from cprankMax_upper_bound x⟩ (cprankMax_upper_bound x) end Holor