filename
stringlengths
5
30
content
stringlengths
22
296k
Polynomial.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Kim Morrison, Jens Wagemaker -/ import Mathlib.Algebra.Polynomial.AlgebraMap /-! # Polynomials and adjoining roots ## Main results * `Polynomial.instCommSemiringAdjoinSingleton, instCommRingAdjoinSingleton`: adjoining an element to a commutative (semi)ring gives a commutative (semi)ring -/ noncomputable section open Finset open Polynomial namespace Polynomial universe u v w z variable {R : Type u} {S : Type v} {T : Type w} {A : Type z} {A' B : Type*} {a b : R} {n : ℕ} section aeval open Algebra variable [CommSemiring R] [Semiring A] [CommSemiring A'] [Semiring B] variable [Algebra R A] [Algebra R B] variable {p q : R[X]} (x : A) @[simp] theorem adjoin_X : adjoin R ({X} : Set R[X]) = ⊤ := by refine top_unique fun p _hp => ?_ set S := adjoin R ({X} : Set R[X]) rw [← sum_monomial_eq p]; simp only [← smul_X_eq_monomial] exact S.sum_mem fun n _hn => S.smul_mem (S.pow_mem (subset_adjoin rfl) _) _ variable (R) theorem _root_.Algebra.adjoin_singleton_eq_range_aeval (x : A) : adjoin R {x} = (aeval x).range := by rw [← Algebra.map_top, ← adjoin_X, AlgHom.map_adjoin, Set.image_singleton, aeval_X] @[simp] theorem aeval_mem_adjoin_singleton : aeval x p ∈ adjoin R {x} := by simp [adjoin_singleton_eq_range_aeval] theorem _root_.Algebra.adjoin_mem_exists_aeval {a : A} (h : a ∈ Algebra.adjoin R {x}) : ∃ p : R[X], aeval x p = a := by rw [Algebra.adjoin_singleton_eq_range_aeval] at h simp_all theorem _root_.Algebra.adjoin_eq_exists_aeval (a : Algebra.adjoin R {x}) : ∃ p : R[X], aeval x p = a := by have : (a : A) ∈ Algebra.adjoin R {x} := by simp set y := (a : A) with h rw [Algebra.adjoin_singleton_eq_range_aeval] at this simp_all @[elab_as_elim] theorem _root_.Algebra.adjoin_singleton_induction {M : (adjoin R {x}) → Prop} (a : adjoin R {x}) (f : ∀ (p : Polynomial R), M (⟨aeval x p, aeval_mem_adjoin_singleton R x⟩ : adjoin R {x})) : M a := by obtain ⟨p, hp⟩ := Algebra.adjoin_eq_exists_aeval _ x a aesop instance instCommSemiringAdjoinSingleton : CommSemiring <| adjoin R {x} := { mul_comm := fun ⟨p, hp⟩ ⟨q, hq⟩ ↦ by obtain ⟨p', rfl⟩ := Algebra.adjoin_singleton_eq_range_aeval R x ▸ hp obtain ⟨q', rfl⟩ := Algebra.adjoin_singleton_eq_range_aeval R x ▸ hq simp only [AlgHom.toRingHom_eq_coe, RingHom.coe_coe, MulMemClass.mk_mul_mk, ← map_mul, mul_comm p' q'] } instance instCommRingAdjoinSingleton {R A : Type*} [CommRing R] [Ring A] [Algebra R A] (x : A) : CommRing <| Algebra.adjoin R {x} := { mul_comm := mul_comm } end aeval end Polynomial
Basic.lean
/- Copyright (c) 2024 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno -/ import Mathlib.Tactic.CategoryTheory.Coherence.Basic import Mathlib.Tactic.CategoryTheory.Bicategory.Normalize import Mathlib.Tactic.CategoryTheory.Bicategory.PureCoherence /-! # `bicategory` tactic This file provides `bicategory` tactic, which solves equations in a bicategory, where the two sides only differ by replacing strings of bicategory structural morphisms (that is, associators, unitors, and identities) with different strings of structural morphisms with the same source and target. In other words, `bicategory` solves equalities where both sides have the same string diagrams. The core function for the `bicategory` tactic is provided in `Mathlib/Tactic/CategoryTheory/Coherence/Basic.lean`. See this file for more details about the implementation. -/ open Lean Meta Elab Tactic open CategoryTheory Mathlib.Tactic.BicategoryLike namespace Mathlib.Tactic.Bicategory /-- Normalize the both sides of an equality. -/ def bicategoryNf (mvarId : MVarId) : MetaM (List MVarId) := do BicategoryLike.normalForm Bicategory.Context `bicategory mvarId @[inherit_doc bicategoryNf] elab "bicategory_nf" : tactic => withMainContext do replaceMainGoal (← bicategoryNf (← getMainGoal)) /-- Use the coherence theorem for bicategories to solve equations in a bicategory, where the two sides only differ by replacing strings of bicategory structural morphisms (that is, associators, unitors, and identities) with different strings of structural morphisms with the same source and target. That is, `bicategory` can handle goals of the form `a ≫ f ≫ b ≫ g ≫ c = a' ≫ f ≫ b' ≫ g ≫ c'` where `a = a'`, `b = b'`, and `c = c'` can be proved using `bicategory_coherence`. -/ def bicategory (mvarId : MVarId) : MetaM (List MVarId) := BicategoryLike.main Bicategory.Context `bicategory mvarId @[inherit_doc bicategory] elab "bicategory" : tactic => withMainContext do replaceMainGoal <| ← bicategory <| ← getMainGoal end Mathlib.Tactic.Bicategory
character.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype choice ssrnat seq. From mathcomp Require Import path div fintype tuple finfun bigop prime order. From mathcomp Require Import ssralg poly finset gproduct fingroup morphism. From mathcomp Require Import perm automorphism quotient finalg action zmodp. From mathcomp Require Import commutator cyclic center pgroup nilpotent sylow. From mathcomp Require Import abelian matrix mxalgebra mxpoly mxrepresentation. From mathcomp Require Import vector ssrnum algC classfun archimedean. (******************************************************************************) (* This file contains the basic notions of character theory, based on Isaacs. *) (* irr G == tuple of the elements of 'CF(G) that are irreducible *) (* characters of G. *) (* Nirr G == number of irreducible characters of G. *) (* Iirr G == index type for the irreducible characters of G. *) (* := 'I_(Nirr G). *) (* 'chi_i == the i-th element of irr G, for i : Iirr G. *) (* 'chi[G]_i Note that 'chi_0 = 1, the principal character of G. *) (* 'Chi_i == an irreducible representation that affords 'chi_i. *) (* socle_of_Iirr i == the Wedderburn component of the regular representation *) (* of G, corresponding to 'Chi_i. *) (* Iirr_of_socle == the inverse of socle_of_Iirr (which is one-to-one). *) (* phi.[A]%CF == the image of A \in group_ring G under phi : 'CF(G). *) (* cfRepr rG == the character afforded by the representation rG of G. *) (* cfReg G == the regular character, afforded by the regular *) (* representation of G. *) (* detRepr rG == the linear character afforded by the determinant of rG. *) (* cfDet phi == the linear character afforded by the determinant of a *) (* representation affording phi. *) (* 'o(phi) == the "determinential order" of phi (the multiplicative *) (* order of cfDet phi. *) (* phi \is a character <=> phi : 'CF(G) is a character of G or 0. *) (* i \in irr_constt phi <=> 'chi_i is an irreducible constituent of phi: phi *) (* has a non-zero coordinate on 'chi_i over the basis irr G. *) (* xi \is a linear_char xi <=> xi : 'CF(G) is a linear character of G. *) (* 'Z(chi)%CF == the center of chi when chi is a character of G, i.e., *) (* rcenter rG where rG is a representation that affords phi. *) (* If phi is not a character then 'Z(chi)%CF = cfker phi. *) (* aut_Iirr u i == the index of cfAut u 'chi_i in irr G. *) (* conjC_Iirr i == the index of 'chi_i^*%CF in irr G. *) (* morph_Iirr i == the index of cfMorph 'chi[f @* G]_i in irr G. *) (* isom_Iirr isoG i == the index of cfIsom isoG 'chi[G]_i in irr R. *) (* mod_Iirr i == the index of ('chi[G / H]_i %% H)%CF in irr G. *) (* quo_Iirr i == the index of ('chi[G]_i / H)%CF in irr (G / H). *) (* Ind_Iirr G i == the index of 'Ind[G, H] 'chi_i, provided it is an *) (* irreducible character (such as when if H is the inertia *) (* group of 'chi_i). *) (* Res_Iirr H i == the index of 'Res[H, G] 'chi_i, provided it is an *) (* irreducible character (such as when 'chi_i is linear). *) (* sdprod_Iirr defG i == the index of cfSdprod defG 'chi_i in irr G, given *) (* defG : K ><| H = G. *) (* And, for KxK : K \x H = G. *) (* dprodl_Iirr KxH i == the index of cfDprodl KxH 'chi[K]_i in irr G. *) (* dprodr_Iirr KxH j == the index of cfDprodr KxH 'chi[H]_j in irr G. *) (* dprod_Iirr KxH (i, j) == the index of cfDprod KxH 'chi[K]_i 'chi[H]_j. *) (* inv_dprod_Iirr KxH == the inverse of dprod_Iirr KxH. *) (* The following are used to define and exploit the character table: *) (* character_table G == the character table of G, whose i-th row lists the *) (* values taken by 'chi_i on the conjugacy classes *) (* of G; this is a square Nirr G x NirrG matrix. *) (* irr_class i == the conjugacy class of G with index i : Iirr G. *) (* class_Iirr xG == the index of xG \in classes G, in Iirr G. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import Order.TTheory GroupScope GRing.Theory Num.Theory. Local Open Scope ring_scope. Section AlgC. Variable (gT : finGroupType). Lemma groupC : group_closure_field algC gT. Proof. exact: group_closure_closed_field. Qed. End AlgC. Section Tensor. Variable (F : fieldType). Fixpoint trow (n1 : nat) : forall (A : 'rV[F]_n1) m2 n2 (B : 'M[F]_(m2,n2)), 'M[F]_(m2,n1 * n2) := if n1 is n'1.+1 then fun (A : 'M[F]_(1,(1 + n'1))) m2 n2 (B : 'M[F]_(m2,n2)) => (row_mx (lsubmx A 0 0 *: B) (trow (rsubmx A) B)) else (fun _ _ _ _ => 0). Lemma trow0 n1 m2 n2 B : @trow n1 0 m2 n2 B = 0. Proof. elim: n1=> //= n1 IH. rewrite !mxE scale0r linear0. rewrite IH //; apply/matrixP=> i j; rewrite !mxE. by case: split=> *; rewrite mxE. Qed. Definition trowb n1 m2 n2 B A := @trow n1 A m2 n2 B. Lemma trowbE n1 m2 n2 A B : trowb B A = @trow n1 A m2 n2 B. Proof. by []. Qed. Lemma trowb_is_linear n1 m2 n2 (B : 'M_(m2,n2)) : linear (@trowb n1 m2 n2 B). Proof. elim: n1=> [|n1 IH] //= k A1 A2 /=; first by rewrite scaler0 add0r. rewrite !linearD /= !linearZ /= IH 2!mxE. by rewrite scalerDl -scalerA -add_row_mx -scale_row_mx. Qed. HB.instance Definition _ n1 m2 n2 B := GRing.isSemilinear.Build _ _ _ _ (trowb B) (GRing.semilinear_linear (@trowb_is_linear n1 m2 n2 B)). Lemma trow_is_linear n1 m2 n2 (A : 'rV_n1) : linear (@trow n1 A m2 n2). Proof. elim: n1 A => [|n1 IH] //= A k A1 A2 /=; first by rewrite scaler0 add0r. rewrite linearP /=; apply/matrixP=> i j; rewrite !mxE. by case: split=> a; rewrite ?IH !mxE. Qed. HB.instance Definition _ n1 m2 n2 A := GRing.isSemilinear.Build _ _ _ _ (@trow n1 A m2 n2) (GRing.semilinear_linear (@trow_is_linear n1 m2 n2 A)). Fixpoint tprod (m1 : nat) : forall n1 (A : 'M[F]_(m1,n1)) m2 n2 (B : 'M[F]_(m2,n2)), 'M[F]_(m1 * m2,n1 * n2) := if m1 is m'1.+1 return forall n1 (A : 'M[F]_(m1,n1)) m2 n2 (B : 'M[F]_(m2,n2)), 'M[F]_(m1 * m2,n1 * n2) then fun n1 (A : 'M[F]_(1 + m'1,n1)) m2 n2 B => (col_mx (trow (usubmx A) B) (tprod (dsubmx A) B)) else (fun _ _ _ _ _ => 0). Lemma dsumx_mul m1 m2 n p A B : dsubmx ((A *m B) : 'M[F]_(m1 + m2, n)) = dsubmx (A : 'M_(m1 + m2, p)) *m B. Proof. apply/matrixP=> i j /[!mxE]; apply: eq_bigr=> k _. by rewrite !mxE. Qed. Lemma usumx_mul m1 m2 n p A B : usubmx ((A *m B) : 'M[F]_(m1 + m2, n)) = usubmx (A : 'M_(m1 + m2, p)) *m B. Proof. by apply/matrixP=> i j /[!mxE]; apply: eq_bigr=> k _ /[!mxE]. Qed. Let trow_mul (m1 m2 n2 p2 : nat) (A : 'rV_m1) (B1: 'M[F]_(m2,n2)) (B2 :'M[F]_(n2,p2)) : trow A (B1 *m B2) = B1 *m trow A B2. Proof. elim: m1 A => [|m1 IH] A /=; first by rewrite mulmx0. by rewrite IH mul_mx_row -scalemxAr. Qed. Lemma tprodE m1 n1 p1 (A1 :'M[F]_(m1,n1)) (A2 :'M[F]_(n1,p1)) m2 n2 p2 (B1 :'M[F]_(m2,n2)) (B2 :'M[F]_(n2,p2)) : tprod (A1 *m A2) (B1 *m B2) = (tprod A1 B1) *m (tprod A2 B2). Proof. elim: m1 n1 p1 A1 A2 m2 n2 p2 B1 B2 => /= [|m1 IH]. by move=> *; rewrite mul0mx. move=> n1 p1 A1 A2 m2 n2 p2 B1 B2. rewrite mul_col_mx -IH. congr col_mx; last by rewrite dsumx_mul. rewrite usumx_mul. elim: n1 {A1}(usubmx (A1: 'M_(1 + m1, n1))) p1 A2=> //= [u p1 A2|]. by rewrite [A2](flatmx0) !mulmx0 -trowbE linear0. move=> n1 IH1 A p1 A2 //=. set Al := lsubmx _; set Ar := rsubmx _. set Su := usubmx _; set Sd := dsubmx _. rewrite mul_row_col -IH1. rewrite -{1}(@hsubmxK F 1 1 n1 A). rewrite -{1}(@vsubmxK F 1 n1 p1 A2). rewrite (@mul_row_col F 1 1 n1 p1). rewrite -trowbE linearD /= trowbE -/Al. congr (_ + _). rewrite {1}[Al]mx11_scalar mul_scalar_mx. by rewrite -trowbE linearZ /= trowbE -/Su trow_mul scalemxAl. Qed. Let tprod_tr m1 n1 (A :'M[F]_(m1, 1 + n1)) m2 n2 (B :'M[F]_(m2, n2)) : tprod A B = row_mx (trow (lsubmx A)^T B^T)^T (tprod (rsubmx A) B). Proof. elim: m1 n1 A m2 n2 B=> [|m1 IH] n1 A m2 n2 B //=. by rewrite trmx0 row_mx0. rewrite !IH. pose A1 := A : 'M_(1 + m1, 1 + n1). have F1: dsubmx (rsubmx A1) = rsubmx (dsubmx A1). by apply/matrixP=> i j; rewrite !mxE. have F2: rsubmx (usubmx A1) = usubmx (rsubmx A1). by apply/matrixP=> i j; rewrite !mxE. have F3: lsubmx (dsubmx A1) = dsubmx (lsubmx A1). by apply/matrixP=> i j; rewrite !mxE. rewrite tr_row_mx -block_mxEv -block_mxEh !(F1,F2,F3); congr block_mx. - by rewrite !mxE linearZ /= trmxK. by rewrite -trmx_dsub. Qed. Lemma tprod1 m n : tprod (1%:M : 'M[F]_(m,m)) (1%:M : 'M[F]_(n,n)) = 1%:M. Proof. elim: m n => [|m IH] n //=; first by rewrite [1%:M]flatmx0. rewrite tprod_tr. set u := rsubmx _; have->: u = 0. apply/matrixP=> i j; rewrite !mxE. by case: i; case: j=> /= j Hj; case. set v := lsubmx (dsubmx _); have->: v = 0. apply/matrixP=> i j; rewrite !mxE. by case: i; case: j; case. set w := rsubmx _; have->: w = 1%:M. apply/matrixP=> i j; rewrite !mxE. by case: i; case: j; case. rewrite IH -!trowbE !linear0. rewrite -block_mxEv. set z := (lsubmx _) 0 0; have->: z = 1. by rewrite /z !mxE eqxx. by rewrite scale1r scalar_mx_block. Qed. Lemma mxtrace_prod m n (A :'M[F]_(m)) (B :'M[F]_(n)) : \tr (tprod A B) = \tr A * \tr B. Proof. elim: m n A B => [|m IH] n A B //=. by rewrite [A]flatmx0 mxtrace0 mul0r. rewrite tprod_tr -block_mxEv mxtrace_block IH. rewrite linearZ/= -mulrDl -trace_mx11; congr (_ * _). pose A1 := A : 'M_(1 + m). rewrite -[A in RHS](@submxK _ 1 m 1 m A1). by rewrite (@mxtrace_block _ _ _ (ulsubmx A1)). Qed. End Tensor. (* Representation sigma type and standard representations. *) Section StandardRepresentation. Variables (R : fieldType) (gT : finGroupType) (G : {group gT}). Local Notation reprG := (mx_representation R G). Record representation := Representation {rdegree; mx_repr_of_repr :> reprG rdegree}. Lemma mx_repr0 : mx_repr G (fun _ : gT => 1%:M : 'M[R]_0). Proof. by split=> // g h Hg Hx; rewrite mulmx1. Qed. Definition grepr0 := Representation (MxRepresentation mx_repr0). Lemma add_mx_repr (rG1 rG2 : representation) : mx_repr G (fun g => block_mx (rG1 g) 0 0 (rG2 g)). Proof. split=> [|x y Hx Hy]; first by rewrite !repr_mx1 -scalar_mx_block. by rewrite mulmx_block !(mulmx0, mul0mx, addr0, add0r, repr_mxM). Qed. Definition dadd_grepr rG1 rG2 := Representation (MxRepresentation (add_mx_repr rG1 rG2)). Section DsumRepr. Variables (n : nat) (rG : reprG n). Lemma mx_rsim_dadd (U V W : 'M_n) (rU rV : representation) (modU : mxmodule rG U) (modV : mxmodule rG V) (modW : mxmodule rG W) : (U + V :=: W)%MS -> mxdirect (U + V) -> mx_rsim (submod_repr modU) rU -> mx_rsim (submod_repr modV) rV -> mx_rsim (submod_repr modW) (dadd_grepr rU rV). Proof. case: rU; case: rV=> nV rV nU rU defW dxUV /=. have tiUV := mxdirect_addsP dxUV. move=> [fU def_nU]; rewrite -{nU}def_nU in rU fU * => inv_fU hom_fU. move=> [fV def_nV]; rewrite -{nV}def_nV in rV fV * => inv_fV hom_fV. pose pU := in_submod U (proj_mx U V) *m fU. pose pV := in_submod V (proj_mx V U) *m fV. exists (val_submod 1%:M *m row_mx pU pV) => [||g Gg]. - by rewrite -defW (mxdirectP dxUV). - apply/row_freeP. pose pU' := invmx fU *m val_submod 1%:M. pose pV' := invmx fV *m val_submod 1%:M. exists (in_submod _ (col_mx pU' pV')). rewrite in_submodE mulmxA -in_submodE -mulmxA mul_row_col mulmxDr. rewrite -[pU *m _]mulmxA -[pV *m _]mulmxA !mulKVmx -?row_free_unit //. rewrite addrC (in_submodE V) 2![val_submod 1%:M *m _]mulmxA -in_submodE. rewrite addrC (in_submodE U) 2![val_submod 1%:M *m _ in X in X + _]mulmxA. rewrite -in_submodE -!val_submodE !in_submodK ?proj_mx_sub //. by rewrite add_proj_mx ?val_submodK // val_submod1 defW. rewrite mulmxA -val_submodE -[submod_repr _ g]mul1mx val_submodJ //. rewrite -(mulmxA _ (rG g)) mul_mx_row -[in RHS]mulmxA mul_row_block. rewrite !mulmx0 addr0 add0r !mul_mx_row. set W' := val_submod 1%:M; congr (row_mx _ _). rewrite 3!mulmxA in_submodE mulmxA. have hom_pU: (W' <= dom_hom_mx rG (proj_mx U V))%MS. by rewrite val_submod1 -defW proj_mx_hom. rewrite (hom_mxP hom_pU) // -in_submodE (in_submodJ modU) ?proj_mx_sub //. rewrite -(mulmxA _ _ fU) hom_fU // in_submodE -2!(mulmxA W') -in_submodE. by rewrite -mulmxA (mulmxA _ fU). rewrite 3!mulmxA in_submodE mulmxA. have hom_pV: (W' <= dom_hom_mx rG (proj_mx V U))%MS. by rewrite val_submod1 -defW addsmxC proj_mx_hom // capmxC. rewrite (hom_mxP hom_pV) // -in_submodE (in_submodJ modV) ?proj_mx_sub //. rewrite -(mulmxA _ _ fV) hom_fV // in_submodE -2!(mulmxA W') -in_submodE. by rewrite -mulmxA (mulmxA _ fV). Qed. Lemma mx_rsim_dsum (I : finType) (P : pred I) U rU (W : 'M_n) (modU : forall i, mxmodule rG (U i)) (modW : mxmodule rG W) : let S := (\sum_(i | P i) U i)%MS in (S :=: W)%MS -> mxdirect S -> (forall i, mx_rsim (submod_repr (modU i)) (rU i : representation)) -> mx_rsim (submod_repr modW) (\big[dadd_grepr/grepr0]_(i | P i) rU i). Proof. move=> /= defW dxW rsimU. rewrite mxdirectE /= -!(big_filter _ P) in dxW defW *. elim: {P}(filter P _) => [|i e IHe] in W modW dxW defW *. rewrite !big_nil /= in defW *. by exists 0 => [||? _]; rewrite ?mul0mx ?mulmx0 // /row_free -defW !mxrank0. rewrite !big_cons /= in dxW defW *. rewrite 2!(big_nth i) !big_mkord /= in IHe dxW defW. set Wi := (\sum_i _)%MS in defW dxW IHe. rewrite -mxdirectE mxdirect_addsE !mxdirectE eqxx /= -/Wi in dxW. have modWi: mxmodule rG Wi by apply: sumsmx_module. case/andP: dxW; move/(IHe Wi modWi) {IHe}; move/(_ (eqmx_refl _))=> rsimWi. by move/eqP; move/mxdirect_addsP=> dxUiWi; apply: mx_rsim_dadd (rsimU i) rsimWi. Qed. Definition muln_grepr rW k := \big[dadd_grepr/grepr0]_(i < k) rW. Lemma mx_rsim_socle (sG : socleType rG) (W : sG) (rW : representation) : let modW : mxmodule rG W := component_mx_module rG (socle_base W) in mx_rsim (socle_repr W) rW -> mx_rsim (submod_repr modW) (muln_grepr rW (socle_mult W)). Proof. set M := socle_base W => modW rsimM. have simM: mxsimple rG M := socle_simple W. have rankM_gt0: (\rank M > 0)%N by rewrite lt0n mxrank_eq0; case: simM. have [I /= U_I simU]: mxsemisimple rG W by apply: component_mx_semisimple. pose U (i : 'I_#|I|) := U_I (enum_val i). have reindexI := reindex _ (onW_bij I (enum_val_bij I)). rewrite mxdirectE /= !reindexI -mxdirectE /= => defW dxW. have isoU: forall i, mx_iso rG M (U i). move=> i; have sUiW: (U i <= W)%MS by rewrite -defW (sumsmx_sup i). exact: component_mx_iso (simU _) sUiW. have ->: socle_mult W = #|I|. rewrite -(mulnK #|I| rankM_gt0); congr (_ %/ _)%N. rewrite -defW (mxdirectP dxW) /= -sum_nat_const reindexI /=. by apply: eq_bigr => i _; rewrite -(mxrank_iso (isoU i)). have modU: mxmodule rG (U _) := mxsimple_module (simU _). suff: mx_rsim (submod_repr (modU _)) rW by apply: mx_rsim_dsum defW dxW. by move=> i; apply: mx_rsim_trans (mx_rsim_sym _) rsimM; apply/mx_rsim_iso. Qed. End DsumRepr. Section ProdRepr. Variables (n1 n2 : nat) (rG1 : reprG n1) (rG2 : reprG n2). Lemma prod_mx_repr : mx_repr G (fun g => tprod (rG1 g) (rG2 g)). Proof. split=>[|i j InG JnG]; first by rewrite !repr_mx1 tprod1. by rewrite !repr_mxM // tprodE. Qed. Definition prod_repr := MxRepresentation prod_mx_repr. End ProdRepr. Lemma prod_repr_lin n2 (rG1 : reprG 1) (rG2 : reprG n2) : {in G, forall x, let cast_n2 := esym (mul1n n2) in prod_repr rG1 rG2 x = castmx (cast_n2, cast_n2) (rG1 x 0 0 *: rG2 x)}. Proof. move=> x Gx /=; set cast_n2 := esym _; rewrite /prod_repr /= !mxE !lshift0. apply/matrixP=> i j; rewrite castmxE /=. do 2![rewrite mxE; case: splitP => [? ? | []//]]. by congr ((_ *: rG2 x) _ _); apply: val_inj. Qed. End StandardRepresentation. Arguments grepr0 {R gT G}. Prenex Implicits dadd_grepr. Section Char. Variables (gT : finGroupType) (G : {group gT}). Fact cfRepr_subproof n (rG : mx_representation algC G n) : is_class_fun <<G>> [ffun x => \tr (rG x) *+ (x \in G)]. Proof. rewrite genGid; apply: intro_class_fun => [x y Gx Gy | _ /negbTE-> //]. by rewrite groupJr // !repr_mxM ?groupM ?groupV // mxtrace_mulC repr_mxK. Qed. Definition cfRepr n rG := Cfun 0 (@cfRepr_subproof n rG). Lemma cfRepr1 n rG : @cfRepr n rG 1%g = n%:R. Proof. by rewrite cfunE group1 repr_mx1 mxtrace1. Qed. Lemma cfRepr_sim n1 n2 rG1 rG2 : mx_rsim rG1 rG2 -> @cfRepr n1 rG1 = @cfRepr n2 rG2. Proof. case/mx_rsim_def=> f12 [f21] fK def_rG1; apply/cfun_inP=> x Gx. by rewrite !cfunE def_rG1 // mxtrace_mulC mulmxA fK mul1mx. Qed. Lemma cfRepr0 : cfRepr grepr0 = 0. Proof. by apply/cfun_inP=> x Gx; rewrite !cfunE Gx mxtrace1. Qed. Lemma cfRepr_dadd rG1 rG2 : cfRepr (dadd_grepr rG1 rG2) = cfRepr rG1 + cfRepr rG2. Proof. by apply/cfun_inP=> x Gx; rewrite !cfunE Gx mxtrace_block. Qed. Lemma cfRepr_dsum I r (P : pred I) rG : cfRepr (\big[dadd_grepr/grepr0]_(i <- r | P i) rG i) = \sum_(i <- r | P i) cfRepr (rG i). Proof. exact: (big_morph _ cfRepr_dadd cfRepr0). Qed. Lemma cfRepr_muln rG k : cfRepr (muln_grepr rG k) = cfRepr rG *+ k. Proof. by rewrite cfRepr_dsum /= sumr_const card_ord. Qed. Section StandardRepr. Variables (n : nat) (rG : mx_representation algC G n). Let sG := DecSocleType rG. Let iG : irrType algC G := DecSocleType _. Definition standard_irr (W : sG) := irr_comp iG (socle_repr W). Definition standard_socle i := pick [pred W | standard_irr W == i]. Local Notation soc := standard_socle. Definition standard_irr_coef i := oapp (fun W => socle_mult W) 0 (soc i). Definition standard_grepr := \big[dadd_grepr/grepr0]_i muln_grepr (Representation (socle_repr i)) (standard_irr_coef i). Lemma mx_rsim_standard : mx_rsim rG standard_grepr. Proof. pose W i := oapp val 0 (soc i); pose S := (\sum_i W i)%MS. have C'G: [pchar algC]^'.-group G := algC'G_pchar G. have [defS dxS]: (S :=: 1%:M)%MS /\ mxdirect S. rewrite /S mxdirectE /= !(bigID soc xpredT) /=. rewrite addsmxC big1 => [|i]; last by rewrite /W; case (soc i). rewrite adds0mx_id addnC (@big1 nat) ?add0n => [|i]; last first. by rewrite /W; case: (soc i); rewrite ?mxrank0. have <-: Socle sG = 1%:M := reducible_Socle1 sG (mx_Maschke_pchar rG C'G). have [W0 _ | noW] := pickP sG; last first. suff no_i: (soc : pred iG) =1 xpred0 by rewrite /Socle !big_pred0 ?mxrank0. by move=> i; rewrite /soc; case: pickP => // W0; have:= noW W0. have irrK Wi: soc (standard_irr Wi) = Some Wi. rewrite /soc; case: pickP => [W' | /(_ Wi)] /= /eqP // eqWi. apply/eqP/socle_rsimP. apply: mx_rsim_trans (rsim_irr_comp_pchar iG C'G (socle_irr _)) (mx_rsim_sym _). by rewrite [irr_comp _ _]eqWi; apply: rsim_irr_comp_pchar (socle_irr _). have bij_irr: {on [pred i | soc i], bijective standard_irr}. exists (odflt W0 \o soc) => [Wi _ | i]; first by rewrite /= irrK. by rewrite inE /soc /=; case: pickP => //= Wi; move/eqP. rewrite !(reindex standard_irr) {bij_irr}//=. have all_soc Wi: soc (standard_irr Wi) by rewrite irrK. rewrite (eq_bigr val) => [|Wi _]; last by rewrite /W irrK. rewrite !(eq_bigl _ _ all_soc); split=> //. rewrite (eq_bigr (mxrank \o val)) => [|Wi _]; last by rewrite /W irrK. by rewrite -mxdirectE /= Socle_direct. pose modW i : mxmodule rG (W i) := if soc i is Some Wi as oWi return mxmodule rG (oapp val 0 oWi) then component_mx_module rG (socle_base Wi) else mxmodule0 rG n. apply: mx_rsim_trans (mx_rsim_sym (rsim_submod1 (mxmodule1 rG) _)) _ => //. apply: mx_rsim_dsum (modW) _ defS dxS _ => i. rewrite /W /standard_irr_coef /modW /soc; case: pickP => [Wi|_] /=; last first. rewrite /muln_grepr big_ord0. by exists 0 => [||x _]; rewrite /row_free ?mxrank0 ?mulmx0 ?mul0mx. move/eqP=> <-; apply: mx_rsim_socle. exact: rsim_irr_comp_pchar (socle_irr Wi). Qed. End StandardRepr. Definition cfReg (B : {set gT}) : 'CF(B) := #|B|%:R *: '1_[1]. Lemma cfRegE x : @cfReg G x = #|G|%:R *+ (x == 1%g). Proof. by rewrite cfunE cfuniE ?normal1 // inE mulr_natr. Qed. (* This is Isaacs, Lemma (2.10). *) Lemma cfReprReg : cfRepr (regular_repr algC G) = cfReg G. Proof. apply/cfun_inP=> x Gx; rewrite cfRegE. have [-> | ntx] := eqVneq x 1%g; first by rewrite cfRepr1. rewrite cfunE Gx [\tr _]big1 // => i _; rewrite 2!mxE /=. rewrite -(inj_eq enum_val_inj) gring_indexK ?groupM ?enum_valP //. by rewrite eq_mulVg1 mulKg (negbTE ntx). Qed. Definition xcfun (chi : 'CF(G)) A := (gring_row A *m (\col_(i < #|G|) chi (enum_val i))) 0 0. Lemma xcfun_is_zmod_morphism phi : zmod_morphism (xcfun phi). Proof. by move=> A B; rewrite /xcfun [gring_row _]linearB mulmxBl !mxE. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `xcfun_is_zmod_morphism` instead")] Definition xcfun_is_additive := xcfun_is_zmod_morphism. HB.instance Definition _ phi := GRing.isZmodMorphism.Build 'M_(gcard G) _ (xcfun phi) (xcfun_is_zmod_morphism phi). Lemma xcfunZr a phi A : xcfun phi (a *: A) = a * xcfun phi A. Proof. by rewrite /xcfun linearZ -scalemxAl mxE. Qed. (* In order to add a second canonical structure on xcfun *) Definition xcfun_r A phi := xcfun phi A. Arguments xcfun_r A phi /. Lemma xcfun_rE A chi : xcfun_r A chi = xcfun chi A. Proof. by []. Qed. Fact xcfun_r_is_zmod_morphism A : zmod_morphism (xcfun_r A). Proof. move=> phi psi; rewrite /= /xcfun !mxE -sumrB; apply: eq_bigr => i _. by rewrite !mxE !cfunE mulrBr. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `xcfun_r_is_zmod_morphism` instead")] Definition xcfun_r_is_additive := xcfun_r_is_zmod_morphism. HB.instance Definition _ A := GRing.isZmodMorphism.Build _ _ (xcfun_r A) (xcfun_r_is_zmod_morphism A). Lemma xcfunZl a phi A : xcfun (a *: phi) A = a * xcfun phi A. Proof. rewrite /xcfun !mxE big_distrr; apply: eq_bigr => i _ /=. by rewrite !mxE cfunE mulrCA. Qed. Lemma xcfun_repr n rG A : xcfun (@cfRepr n rG) A = \tr (gring_op rG A). Proof. rewrite gring_opE [gring_row A]row_sum_delta !linear_sum /xcfun !mxE. apply: eq_bigr => i _; rewrite !mxE /= !linearZ cfunE enum_valP /=. by congr (_ * \tr _); rewrite {A}/gring_mx /= -rowE rowK mxvecK. Qed. End Char. Arguments xcfun_r {_ _} A phi /. Notation "phi .[ A ]" := (xcfun phi A) : cfun_scope. Definition pred_Nirr gT B := #|@classes gT B|.-1. Arguments pred_Nirr {gT} B%_g. Notation Nirr G := (pred_Nirr G).+1. Notation Iirr G := 'I_(Nirr G). Section IrrClassDef. Variables (gT : finGroupType) (G : {group gT}). Let sG := DecSocleType (regular_repr algC G). Lemma NirrE : Nirr G = #|classes G|. Proof. by rewrite /pred_Nirr (cardD1 [1]) classes1. Qed. Fact Iirr_cast : Nirr G = #|sG|. Proof. by rewrite NirrE ?card_irr_pchar ?algC'G_pchar //; apply: groupC. Qed. Let offset := cast_ord (esym Iirr_cast) (enum_rank [1 sG]%irr). Definition socle_of_Iirr (i : Iirr G) : sG := enum_val (cast_ord Iirr_cast (i + offset)). Definition irr_of_socle (Wi : sG) : Iirr G := cast_ord (esym Iirr_cast) (enum_rank Wi) - offset. Local Notation W := socle_of_Iirr. Lemma socle_Iirr0 : W 0 = [1 sG]%irr. Proof. by rewrite /W add0r cast_ordKV enum_rankK. Qed. Lemma socle_of_IirrK : cancel W irr_of_socle. Proof. by move=> i; rewrite /irr_of_socle enum_valK cast_ordK addrK. Qed. Lemma irr_of_socleK : cancel irr_of_socle W. Proof. by move=> Wi; rewrite /W subrK cast_ordKV enum_rankK. Qed. Hint Resolve socle_of_IirrK irr_of_socleK : core. Lemma irr_of_socle_bij (A : {pred (Iirr G)}) : {on A, bijective irr_of_socle}. Proof. by apply: onW_bij; exists W. Qed. Lemma socle_of_Iirr_bij (A : {pred sG}) : {on A, bijective W}. Proof. by apply: onW_bij; exists irr_of_socle. Qed. End IrrClassDef. Prenex Implicits socle_of_IirrK irr_of_socleK. Arguments socle_of_Iirr {gT G%_G} i%_R. Notation "''Chi_' i" := (irr_repr (socle_of_Iirr i)) (at level 8, i at level 2, format "''Chi_' i"). HB.lock Definition irr gT B : (Nirr B).-tuple 'CF(B) := let irr_of i := 'Res[B, <<B>>] (@cfRepr gT _ _ 'Chi_(inord i)) in [tuple of mkseq irr_of (Nirr B)]. Arguments irr {gT} B%_g. Notation "''chi_' i" := (tnth (irr _) i%R) (at level 8, i at level 2, format "''chi_' i") : ring_scope. Notation "''chi[' G ]_ i" := (tnth (irr G) i%R) (at level 8, i at level 2, only parsing) : ring_scope. Section IrrClass. Variable (gT : finGroupType) (G : {group gT}). Implicit Types (i : Iirr G) (B : {set gT}). Open Scope group_ring_scope. Lemma congr_irr i1 i2 : i1 = i2 -> 'chi_i1 = 'chi_i2. Proof. by move->. Qed. Lemma Iirr1_neq0 : G :!=: 1%g -> inord 1 != 0 :> Iirr G. Proof. by rewrite -classes_gt1 -NirrE -val_eqE /= => /inordK->. Qed. Lemma has_nonprincipal_irr : G :!=: 1%g -> {i : Iirr G | i != 0}. Proof. by move/Iirr1_neq0; exists (inord 1). Qed. Lemma irrRepr i : cfRepr 'Chi_i = 'chi_i. Proof. rewrite irr.unlock (tnth_nth 0) nth_mkseq // -[<<G>>]/(gval _) genGidG. by rewrite cfRes_id inord_val. Qed. Lemma irr0 : 'chi[G]_0 = 1. Proof. apply/cfun_inP=> x Gx; rewrite -irrRepr cfun1E cfunE Gx. by rewrite socle_Iirr0 irr1_repr // mxtrace1 degree_irr1. Qed. Lemma cfun1_irr : 1 \in irr G. Proof. by rewrite -irr0 mem_tnth. Qed. Lemma mem_irr i : 'chi_i \in irr G. Proof. exact: mem_tnth. Qed. Lemma irrP xi : reflect (exists i, xi = 'chi_i) (xi \in irr G). Proof. apply: (iffP idP) => [/(nthP 0)[i] | [i ->]]; last exact: mem_irr. rewrite size_tuple => lt_i_G <-. by exists (Ordinal lt_i_G); rewrite (tnth_nth 0). Qed. Let sG := DecSocleType (regular_repr algC G). Let C'G := algC'G_pchar G. Let closG := @groupC _ G. Local Notation W i := (@socle_of_Iirr _ G i). Local Notation "''n_' i" := 'n_(W i). Local Notation "''R_' i" := 'R_(W i). Local Notation "''e_' i" := 'e_(W i). Lemma irr1_degree i : 'chi_i 1%g = ('n_i)%:R. Proof. by rewrite -irrRepr cfRepr1. Qed. Lemma Cnat_irr1 i : 'chi_i 1%g \in Num.nat. Proof. by rewrite irr1_degree rpred_nat. Qed. Lemma irr1_gt0 i : 0 < 'chi_i 1%g. Proof. by rewrite irr1_degree ltr0n irr_degree_gt0. Qed. Lemma irr1_neq0 i : 'chi_i 1%g != 0. Proof. by rewrite eq_le lt_geF ?irr1_gt0. Qed. Lemma irr_neq0 i : 'chi_i != 0. Proof. by apply: contraNneq (irr1_neq0 i) => ->; rewrite cfunE. Qed. Local Remark cfIirr_key : unit. Proof. by []. Qed. Definition cfIirr : forall B, 'CF(B) -> Iirr B := locked_with cfIirr_key (fun B chi => inord (index chi (irr B))). Lemma cfIirrE chi : chi \in irr G -> 'chi_(cfIirr chi) = chi. Proof. move=> chi_irr; rewrite (tnth_nth 0) [cfIirr]unlock inordK ?nth_index //. by rewrite -index_mem size_tuple in chi_irr. Qed. Lemma cfIirrPE J (f : J -> 'CF(G)) (P : pred J) : (forall j, P j -> f j \in irr G) -> forall j, P j -> 'chi_(cfIirr (f j)) = f j. Proof. by move=> irr_f j /irr_f; apply: cfIirrE. Qed. (* This is Isaacs, Corollary (2.7). *) Corollary irr_sum_square : \sum_i ('chi[G]_i 1%g) ^+ 2 = #|G|%:R. Proof. rewrite -(sum_irr_degree_pchar sG) // natr_sum. rewrite (reindex _ (socle_of_Iirr_bij _)) /=. by apply: eq_bigr => i _; rewrite irr1_degree natrX. Qed. (* This is Isaacs, Lemma (2.11). *) Lemma cfReg_sum : cfReg G = \sum_i 'chi_i 1%g *: 'chi_i. Proof. apply/cfun_inP=> x Gx. rewrite -cfReprReg cfunE Gx (mxtrace_regular_pchar sG) //=. rewrite sum_cfunE (reindex _ (socle_of_Iirr_bij _)); apply: eq_bigr => i _. by rewrite -irrRepr cfRepr1 !cfunE Gx mulr_natl. Qed. Let aG := regular_repr algC G. Let R_G := group_ring algC G. Lemma xcfun_annihilate i j A : i != j -> (A \in 'R_j)%MS -> ('chi_i).[A]%CF = 0. Proof. move=> neq_ij RjA; rewrite -irrRepr xcfun_repr. rewrite (irr_repr'_op0_pchar _ _ RjA) ?raddf0 //. by rewrite eq_sym (can_eq socle_of_IirrK). Qed. Lemma xcfunG phi x : x \in G -> phi.[aG x]%CF = phi x. Proof. by move=> Gx; rewrite /xcfun /gring_row rowK -rowE !mxE !(gring_indexK, mul1g). Qed. Lemma xcfun_mul_id i A : (A \in R_G)%MS -> ('chi_i).['e_i *m A]%CF = ('chi_i).[A]%CF. Proof. move=> RG_A; rewrite -irrRepr !xcfun_repr gring_opM //. by rewrite op_Wedderburn_id_pchar ?mul1mx. Qed. Lemma xcfun_id i j : ('chi_i).['e_j]%CF = 'chi_i 1%g *+ (i == j). Proof. have [<-{j} | /xcfun_annihilate->//] := eqVneq; last exact: Wedderburn_id_mem. by rewrite -xcfunG // repr_mx1 -(xcfun_mul_id _ (envelop_mx1 _)) mulmx1. Qed. Lemma irr_free : free (irr G). Proof. apply/freeP=> s s0 i; apply: (mulIf (irr1_neq0 i)). rewrite mul0r -(raddf0 (xcfun_r 'e_i)) -{}s0 raddf_sum /=. rewrite (bigD1 i)//= -tnth_nth xcfunZl xcfun_id eqxx big1 ?addr0 // => j ne_ji. by rewrite -tnth_nth xcfunZl xcfun_id (negbTE ne_ji) mulr0. Qed. Lemma irr_inj : injective (tnth (irr G)). Proof. by apply/injectiveP/free_uniq; rewrite map_tnth_enum irr_free. Qed. Lemma irrK : cancel (tnth (irr G)) (@cfIirr G). Proof. by move=> i; apply: irr_inj; rewrite cfIirrE ?mem_irr. Qed. Lemma irr_eq1 i : ('chi_i == 1) = (i == 0). Proof. by rewrite -irr0 (inj_eq irr_inj). Qed. Lemma cforder_irr_eq1 i : (#['chi_i]%CF == 1) = (i == 0). Proof. by rewrite -dvdn1 dvdn_cforder irr_eq1. Qed. Lemma irr_basis : basis_of 'CF(G)%VS (irr G). Proof. rewrite /basis_of irr_free andbT -dimv_leqif_eq ?subvf //. by rewrite dim_cfun (eqnP irr_free) size_tuple NirrE. Qed. Lemma eq_sum_nth_irr a : \sum_i a i *: 'chi[G]_i = \sum_i a i *: (irr G)`_i. Proof. by apply: eq_bigr => i; rewrite -tnth_nth. Qed. (* This is Isaacs, Theorem (2.8). *) Theorem cfun_irr_sum phi : {a | phi = \sum_i a i *: 'chi[G]_i}. Proof. rewrite (coord_basis irr_basis (memvf phi)) -eq_sum_nth_irr. by exists ((coord (irr G))^~ phi). Qed. Lemma cfRepr_standard n (rG : mx_representation algC G n) : cfRepr (standard_grepr rG) = \sum_i (standard_irr_coef rG (W i))%:R *: 'chi_i. Proof. rewrite cfRepr_dsum (reindex _ (socle_of_Iirr_bij _)). by apply: eq_bigr => i _; rewrite scaler_nat cfRepr_muln irrRepr. Qed. Lemma cfRepr_inj n1 n2 rG1 rG2 : @cfRepr _ G n1 rG1 = @cfRepr _ G n2 rG2 -> mx_rsim rG1 rG2. Proof. move=> eq_repr12; pose c i : algC := (standard_irr_coef _ (W i))%:R. have [rsim1 rsim2] := (mx_rsim_standard rG1, mx_rsim_standard rG2). apply: mx_rsim_trans (rsim1) (mx_rsim_sym _). suffices ->: standard_grepr rG1 = standard_grepr rG2 by []. apply: eq_bigr => Wi _; congr (muln_grepr _ _); apply/eqP; rewrite -eqC_nat. rewrite -[Wi]irr_of_socleK -!/(c _ _ _) -!(coord_sum_free (c _ _) _ irr_free). rewrite -!eq_sum_nth_irr -!cfRepr_standard. by rewrite -(cfRepr_sim rsim1) -(cfRepr_sim rsim2) eq_repr12. Qed. Lemma cfRepr_rsimP n1 n2 rG1 rG2 : reflect (mx_rsim rG1 rG2) (@cfRepr _ G n1 rG1 == @cfRepr _ G n2 rG2). Proof. by apply: (iffP eqP) => [/cfRepr_inj | /cfRepr_sim]. Qed. Lemma irr_reprP xi : reflect (exists2 rG : representation _ G, mx_irreducible rG & xi = cfRepr rG) (xi \in irr G). Proof. apply: (iffP (irrP xi)) => [[i ->] | [[n rG] irr_rG ->]]. by exists (Representation 'Chi_i); [apply: socle_irr | rewrite irrRepr]. exists (irr_of_socle (irr_comp sG rG)); rewrite -irrRepr irr_of_socleK /=. exact/cfRepr_sim/rsim_irr_comp_pchar. Qed. (* This is Isaacs, Theorem (2.12). *) Lemma Wedderburn_id_expansion i : 'e_i = #|G|%:R^-1 *: (\sum_(x in G) 'chi_i 1%g * 'chi_i x^-1%g *: aG x). Proof. have Rei: ('e_i \in 'R_i)%MS by apply: Wedderburn_id_mem. have /envelop_mxP[a def_e]: ('e_i \in R_G)%MS; last rewrite -/aG in def_e. by move: Rei; rewrite genmxE mem_sub_gring => /andP[]. apply: canRL (scalerK (neq0CG _)) _; rewrite def_e linear_sum /=. apply: eq_bigr => x Gx; have Gx' := groupVr Gx; rewrite scalerA; congr (_ *: _). transitivity (cfReg G).['e_i *m aG x^-1%g]%CF. rewrite def_e mulmx_suml raddf_sum (bigD1 x) //= -scalemxAl xcfunZr. rewrite -repr_mxM // mulgV xcfunG // cfRegE eqxx mulrC big1 ?addr0 //. move=> y /andP[Gy /negbTE neq_xy]; rewrite -scalemxAl xcfunZr -repr_mxM //. by rewrite xcfunG ?groupM // cfRegE -eq_mulgV1 neq_xy mulr0. rewrite cfReg_sum -xcfun_rE raddf_sum /= (bigD1 i) //= xcfunZl. rewrite xcfun_mul_id ?envelop_mx_id ?xcfunG ?groupV ?big1 ?addr0 // => j ne_ji. rewrite xcfunZl (xcfun_annihilate ne_ji) ?mulr0 //. have /andP[_ /(submx_trans _)-> //] := Wedderburn_ideal (W i). by rewrite mem_mulsmx // envelop_mx_id ?groupV. Qed. End IrrClass. Arguments cfReg {gT} B%_g. Prenex Implicits cfIirr irrK. Arguments irrP {gT G xi}. Arguments irr_reprP {gT G xi}. Arguments irr_inj {gT G} [x1 x2]. Section IsChar. Variable gT : finGroupType. Definition character_pred {G : {set gT}} := fun phi : 'CF(G) => [forall i, coord (irr G) i phi \in Num.nat]. Arguments character_pred _ _ /. Definition character {G : {set gT}} := [qualify a phi | @character_pred G phi]. Variable G : {group gT}. Implicit Types (phi chi xi : 'CF(G)) (i : Iirr G). Lemma irr_char i : 'chi_i \is a character. Proof. by apply/forallP=> j; rewrite (tnth_nth 0) coord_free ?irr_free. Qed. Lemma cfun1_char : (1 : 'CF(G)) \is a character. Proof. by rewrite -irr0 irr_char. Qed. Lemma cfun0_char : (0 : 'CF(G)) \is a character. Proof. by apply/forallP=> i; rewrite linear0 rpred0. Qed. Fact add_char : addr_closed (@character G). Proof. split=> [|chi xi /forallP-Nchi /forallP-Nxi]; first exact: cfun0_char. by apply/forallP=> i; rewrite linearD rpredD /=. Qed. HB.instance Definition _ := GRing.isAddClosed.Build (classfun G) character_pred add_char. Lemma char_sum_irrP {phi} : reflect (exists n, phi = \sum_i (n i)%:R *: 'chi_i) (phi \is a character). Proof. apply: (iffP idP)=> [/forallP-Nphi | [n ->]]; last first. by apply: rpred_sum => i _; rewrite scaler_nat rpredMn // irr_char. do [have [a ->] := cfun_irr_sum phi] in Nphi *; exists (Num.truncn \o a). apply: eq_bigr => i _; congr (_ *: _); have:= eqP (Nphi i). by rewrite eq_sum_nth_irr coord_sum_free ?irr_free. Qed. Lemma char_sum_irr chi : chi \is a character -> {r | chi = \sum_(i <- r) 'chi_i}. Proof. move=> Nchi; apply: sig_eqW; case/char_sum_irrP: Nchi => n {chi}->. elim/big_rec: _ => [|i _ _ [r ->]]; first by exists nil; rewrite big_nil. exists (ncons (n i) i r); rewrite scaler_nat. by elim: {n}(n i) => [|n IHn]; rewrite ?add0r //= big_cons mulrS -addrA IHn. Qed. Lemma Cnat_char1 chi : chi \is a character -> chi 1%g \in Num.nat. Proof. case/char_sum_irr=> r ->{chi}. by elim/big_rec: _ => [|i chi _ Nchi1]; rewrite cfunE ?rpredD // Cnat_irr1. Qed. Lemma char1_ge0 chi : chi \is a character -> 0 <= chi 1%g. Proof. by move/Cnat_char1/natr_ge0. Qed. Lemma char1_eq0 chi : chi \is a character -> (chi 1%g == 0) = (chi == 0). Proof. case/char_sum_irr=> r ->; apply/idP/idP=> [|/eqP->]; last by rewrite cfunE. case: r => [|i r]; rewrite ?big_nil // sum_cfunE big_cons. rewrite paddr_eq0 ?sumr_ge0 => // [||j _]; rewrite 1?ltW ?irr1_gt0 //. by rewrite (negbTE (irr1_neq0 i)). Qed. Lemma char1_gt0 chi : chi \is a character -> (0 < chi 1%g) = (chi != 0). Proof. by move=> Nchi; rewrite -char1_eq0 // natr_gt0 ?Cnat_char1. Qed. Lemma char_reprP phi : reflect (exists rG : representation algC G, phi = cfRepr rG) (phi \is a character). Proof. apply: (iffP char_sum_irrP) => [[n ->] | [[n rG] ->]]; last first. exists (fun i => standard_irr_coef rG (socle_of_Iirr i)). by rewrite -cfRepr_standard (cfRepr_sim (mx_rsim_standard rG)). exists (\big[dadd_grepr/grepr0]_i muln_grepr (Representation 'Chi_i) (n i)). rewrite cfRepr_dsum; apply: eq_bigr => i _. by rewrite cfRepr_muln irrRepr scaler_nat. Qed. Local Notation reprG := (mx_representation algC G). Lemma cfRepr_char n (rG : reprG n) : cfRepr rG \is a character. Proof. by apply/char_reprP; exists (Representation rG). Qed. Lemma cfReg_char : cfReg G \is a character. Proof. by rewrite -cfReprReg cfRepr_char. Qed. Lemma cfRepr_prod n1 n2 (rG1 : reprG n1) (rG2 : reprG n2) : cfRepr rG1 * cfRepr rG2 = cfRepr (prod_repr rG1 rG2). Proof. by apply/cfun_inP=> x Gx; rewrite !cfunE /= Gx mxtrace_prod. Qed. Lemma mul_char : mulr_closed (@character G). Proof. split=> [|_ _ /char_reprP[rG1 ->] /char_reprP[rG2 ->]]; first exact: cfun1_char. apply/char_reprP; exists (Representation (prod_repr rG1 rG2)). by rewrite cfRepr_prod. Qed. HB.instance Definition _ := GRing.isMulClosed.Build (classfun G) character_pred mul_char. End IsChar. Prenex Implicits character. Arguments character_pred _ _ _ /. Arguments char_reprP {gT G phi}. Section AutChar. Variables (gT : finGroupType) (G : {group gT}). Implicit Type u : {rmorphism algC -> algC}. Implicit Type chi : 'CF(G). Lemma cfRepr_map u n (rG : mx_representation algC G n) : cfRepr (map_repr u rG) = cfAut u (cfRepr rG). Proof. by apply/cfun_inP=> x Gx; rewrite !cfunE Gx map_reprE trace_map_mx. Qed. Lemma cfAut_char u chi : (cfAut u chi \is a character) = (chi \is a character). Proof. without loss /char_reprP[rG ->]: u chi / chi \is a character. by move=> IHu; apply/idP/idP=> ?; first rewrite -(cfAutK u chi); rewrite IHu. rewrite cfRepr_char; apply/char_reprP. by exists (Representation (map_repr u rG)); rewrite cfRepr_map. Qed. Lemma cfConjC_char chi : (chi^*%CF \is a character) = (chi \is a character). Proof. exact: cfAut_char. Qed. Lemma cfAut_char1 u (chi : 'CF(G)) : chi \is a character -> cfAut u chi 1%g = chi 1%g. Proof. by move/Cnat_char1=> Nchi1; rewrite cfunE /= aut_natr. Qed. Lemma cfAut_irr1 u i : (cfAut u 'chi[G]_i) 1%g = 'chi_i 1%g. Proof. exact: cfAut_char1 (irr_char i). Qed. Lemma cfConjC_char1 (chi : 'CF(G)) : chi \is a character -> chi^*%CF 1%g = chi 1%g. Proof. exact: cfAut_char1. Qed. Lemma cfConjC_irr1 u i : ('chi[G]_i)^*%CF 1%g = 'chi_i 1%g. Proof. exact: cfAut_irr1. Qed. End AutChar. Section Linear. Variables (gT : finGroupType) (G : {group gT}). Definition linear_char_pred {B : {set gT}} := fun phi : 'CF(B) => (phi \is a character) && (phi 1%g == 1). Arguments linear_char_pred _ _ /. Definition linear_char {B : {set gT}} := [qualify a phi | @linear_char_pred B phi]. Section OneChar. Variable xi : 'CF(G). Hypothesis CFxi : xi \is a linear_char. Lemma lin_char1: xi 1%g = 1. Proof. by case/andP: CFxi => _ /eqP. Qed. Lemma lin_charW : xi \is a character. Proof. by case/andP: CFxi. Qed. Lemma cfun1_lin_char : (1 : 'CF(G)) \is a linear_char. Proof. by rewrite qualifE/= cfun1_char /= cfun11. Qed. Lemma lin_charM : {in G &, {morph xi : x y / (x * y)%g >-> x * y}}. Proof. move=> x y Gx Gy; case/andP: CFxi => /char_reprP[[n rG] -> /=]. rewrite cfRepr1 pnatr_eq1 => /eqP n1; rewrite {n}n1 in rG *. rewrite !cfunE Gx Gy groupM //= !mulr1n repr_mxM //. by rewrite [rG x]mx11_scalar [rG y]mx11_scalar -scalar_mxM !mxtrace_scalar. Qed. Lemma lin_char_prod I r (P : pred I) (x : I -> gT) : (forall i, P i -> x i \in G) -> xi (\prod_(i <- r | P i) x i)%g = \prod_(i <- r | P i) xi (x i). Proof. move=> Gx; elim/(big_load (fun y => y \in G)): _. elim/big_rec2: _ => [|i a y Pi [Gy <-]]; first by rewrite lin_char1. by rewrite groupM ?lin_charM ?Gx. Qed. Let xiMV x : x \in G -> xi x * xi (x^-1)%g = 1. Proof. by move=> Gx; rewrite -lin_charM ?groupV // mulgV lin_char1. Qed. Lemma lin_char_neq0 x : x \in G -> xi x != 0. Proof. by move/xiMV/(congr1 (predC1 0)); rewrite /= oner_eq0 mulf_eq0 => /norP[]. Qed. Lemma lin_charV x : x \in G -> xi x^-1%g = (xi x)^-1. Proof. by move=> Gx; rewrite -[_^-1]mulr1 -(xiMV Gx) mulKf ?lin_char_neq0. Qed. Lemma lin_charX x n : x \in G -> xi (x ^+ n)%g = xi x ^+ n. Proof. move=> Gx; elim: n => [|n IHn]; first exact: lin_char1. by rewrite expgS exprS lin_charM ?groupX ?IHn. Qed. Lemma lin_char_unity_root x : x \in G -> xi x ^+ #[x] = 1. Proof. by move=> Gx; rewrite -lin_charX // expg_order lin_char1. Qed. Lemma normC_lin_char x : x \in G -> `|xi x| = 1. Proof. move=> Gx; apply/eqP; rewrite -(@pexpr_eq1 _ _ #[x]) //. by rewrite -normrX // lin_char_unity_root ?normr1. Qed. Lemma lin_charV_conj x : x \in G -> xi x^-1%g = (xi x)^*. Proof. move=> Gx; rewrite lin_charV // invC_norm mulrC normC_lin_char //. by rewrite expr1n divr1. Qed. Lemma lin_char_irr : xi \in irr G. Proof. case/andP: CFxi => /char_reprP[rG ->]; rewrite cfRepr1 pnatr_eq1 => /eqP n1. by apply/irr_reprP; exists rG => //; apply/mx_abs_irrW/linear_mx_abs_irr. Qed. Lemma mul_conjC_lin_char : xi * xi^*%CF = 1. Proof. apply/cfun_inP=> x Gx. by rewrite !cfunE cfun1E Gx -normCK normC_lin_char ?expr1n. Qed. Lemma lin_char_unitr : xi \in GRing.unit. Proof. by apply/unitrPr; exists xi^*%CF; apply: mul_conjC_lin_char. Qed. Lemma invr_lin_char : xi^-1 = xi^*%CF. Proof. by rewrite -[_^-1]mulr1 -mul_conjC_lin_char mulKr ?lin_char_unitr. Qed. Lemma fful_lin_char_inj : cfaithful xi -> {in G &, injective xi}. Proof. move=> fful_phi x y Gx Gy xi_xy; apply/eqP; rewrite eq_mulgV1 -in_set1. rewrite (subsetP fful_phi) // inE groupM ?groupV //=; apply/forallP=> z. have [Gz | G'z] := boolP (z \in G); last by rewrite !cfun0 ?groupMl ?groupV. by rewrite -mulgA lin_charM ?xi_xy -?lin_charM ?groupM ?groupV // mulKVg. Qed. End OneChar. Lemma cfAut_lin_char u (xi : 'CF(G)) : (cfAut u xi \is a linear_char) = (xi \is a linear_char). Proof. by rewrite qualifE/= cfAut_char; apply/andb_id2l=> /cfAut_char1->. Qed. Lemma cfConjC_lin_char (xi : 'CF(G)) : (xi^*%CF \is a linear_char) = (xi \is a linear_char). Proof. exact: cfAut_lin_char. Qed. Lemma card_Iirr_abelian : abelian G -> #|Iirr G| = #|G|. Proof. by rewrite card_ord NirrE card_classes_abelian => /eqP. Qed. Lemma card_Iirr_cyclic : cyclic G -> #|Iirr G| = #|G|. Proof. by move/cyclic_abelian/card_Iirr_abelian. Qed. Lemma char_abelianP : reflect (forall i : Iirr G, 'chi_i \is a linear_char) (abelian G). Proof. apply: (iffP idP) => [cGG i | CF_G]. rewrite qualifE/= irr_char /= irr1_degree. by rewrite irr_degree_abelian //; last apply: groupC. rewrite card_classes_abelian -NirrE -eqC_nat -irr_sum_square //. rewrite -{1}[Nirr G]card_ord -sumr_const; apply/eqP/eq_bigr=> i _. by rewrite lin_char1 ?expr1n ?CF_G. Qed. Lemma irr_repr_lin_char (i : Iirr G) x : x \in G -> 'chi_i \is a linear_char -> irr_repr (socle_of_Iirr i) x = ('chi_i x)%:M. Proof. move=> Gx CFi; rewrite -irrRepr cfunE Gx. move: (_ x); rewrite -[irr_degree _](@natrK algC) -irr1_degree lin_char1 //. by rewrite (natrK 1) => A; rewrite trace_mx11 -mx11_scalar. Qed. Fact linear_char_divr : divr_closed (@linear_char G). Proof. split=> [|chi xi Lchi Lxi]; first exact: cfun1_lin_char. rewrite invr_lin_char // qualifE/= cfunE. by rewrite rpredM ?lin_char1 ?mulr1 ?lin_charW //= cfConjC_lin_char. Qed. HB.instance Definition _ := GRing.isDivClosed.Build (classfun G) linear_char_pred linear_char_divr. Lemma irr_cyclic_lin i : cyclic G -> 'chi[G]_i \is a linear_char. Proof. by move/cyclic_abelian/char_abelianP. Qed. Lemma irr_prime_lin i : prime #|G| -> 'chi[G]_i \is a linear_char. Proof. by move/prime_cyclic/irr_cyclic_lin. Qed. End Linear. Prenex Implicits linear_char. Arguments linear_char_pred _ _ _ /. Section OrthogonalityRelations. Variables aT gT : finGroupType. (* This is Isaacs, Lemma (2.15) *) Lemma repr_rsim_diag (G : {group gT}) f (rG : mx_representation algC G f) x : x \in G -> let chi := cfRepr rG in exists e, [/\ (*a*) exists2 B, B \in unitmx & rG x = invmx B *m diag_mx e *m B, (*b*) (forall i, e 0 i ^+ #[x] = 1) /\ (forall i, `|e 0 i| = 1), (*c*) chi x = \sum_i e 0 i /\ `|chi x| <= chi 1%g & (*d*) chi x^-1%g = (chi x)^*]. Proof. move=> Gx; without loss cGG: G rG Gx / abelian G. have sXG: <[x]> \subset G by rewrite cycle_subG. move/(_ _ (subg_repr rG sXG) (cycle_id x) (cycle_abelian x)). by rewrite /= !cfunE !groupV Gx (cycle_id x) !group1. have [I U W simU W1 dxW]: mxsemisimple rG 1%:M. rewrite -(reducible_Socle1 (DecSocleType rG) (mx_Maschke_pchar _ (algC'G_pchar G))). exact: Socle_semisimple. have linU i: \rank (U i) = 1. by apply: mxsimple_abelian_linear cGG (simU i); apply: groupC. have castI: f = #|I|. by rewrite -(mxrank1 algC f) -W1 (eqnP dxW) /= -sum1_card; apply/eq_bigr. pose B := \matrix_j nz_row (U (enum_val (cast_ord castI j))). have rowU i: (nz_row (U i) :=: U i)%MS. apply/eqmxP; rewrite -(geq_leqif (mxrank_leqif_eq (nz_row_sub _))) linU. by rewrite lt0n mxrank_eq0 (nz_row_mxsimple (simU i)). have unitB: B \in unitmx. rewrite -row_full_unit -sub1mx -W1; apply/sumsmx_subP=> i _. pose j := cast_ord (esym castI) (enum_rank i). by rewrite (submx_trans _ (row_sub j B)) // rowK cast_ordKV enum_rankK rowU. pose e := \row_j row j (B *m rG x *m invmx B) 0 j. have rGx: rG x = invmx B *m diag_mx e *m B. rewrite -mulmxA; apply: canRL (mulKmx unitB) _. apply/row_matrixP=> j; rewrite 2!row_mul; set u := row j B. have /sub_rVP[a def_ux]: (u *m rG x <= u)%MS. rewrite /u rowK rowU (eqmxMr _ (rowU _)). exact: (mxmoduleP (mxsimple_module (simU _))). rewrite def_ux [u]rowE scalemxAl; congr (_ *m _). apply/rowP=> k; rewrite 5!mxE !row_mul def_ux [u]rowE scalemxAl mulmxK //. by rewrite !mxE !eqxx !mulr_natr eq_sym. have exp_e j: e 0 j ^+ #[x] = 1. suffices: (diag_mx e j j) ^+ #[x] = (B *m rG (x ^+ #[x])%g *m invmx B) j j. by rewrite expg_order repr_mx1 mulmx1 mulmxV // [e]lock !mxE eqxx. elim: #[x] => [|n IHn]; first by rewrite repr_mx1 mulmx1 mulmxV // !mxE eqxx. rewrite expgS repr_mxM ?groupX // {1}rGx -!mulmxA mulKVmx //. by rewrite mul_diag_mx mulmxA [M in _ = M]mxE -IHn exprS {1}mxE eqxx. have norm1_e j: `|e 0 j| = 1. by apply/eqP; rewrite -(@pexpr_eq1 _ _ #[x]) // -normrX exp_e normr1. exists e; split=> //; first by exists B. rewrite cfRepr1 !cfunE Gx rGx mxtrace_mulC mulKVmx // mxtrace_diag. split=> //=; apply: (le_trans (ler_norm_sum _ _ _)). by rewrite (eq_bigr _ (in1W norm1_e)) sumr_const card_ord lexx. rewrite !cfunE groupV !mulrb Gx rGx mxtrace_mulC mulKVmx //. rewrite -trace_map_mx map_diag_mx; set d' := diag_mx _. rewrite -[d'](mulKVmx unitB) mxtrace_mulC -[_ *m _](repr_mxK rG Gx) rGx. rewrite -!mulmxA mulKVmx // (mulmxA d'). suffices->: d' *m diag_mx e = 1%:M by rewrite mul1mx mulKmx. rewrite mulmx_diag -diag_const_mx; congr diag_mx; apply/rowP=> j. by rewrite [e]lock !mxE mulrC -normCK -lock norm1_e expr1n. Qed. Variables (A : {group aT}) (G : {group gT}). (* This is Isaacs, Lemma (2.15) (d). *) Lemma char_inv (chi : 'CF(G)) x : chi \is a character -> chi x^-1%g = (chi x)^*. Proof. case Gx: (x \in G); last by rewrite !cfun0 ?rmorph0 ?groupV ?Gx. by case/char_reprP=> rG ->; have [e [_ _ _]] := repr_rsim_diag rG Gx. Qed. Lemma irr_inv i x : 'chi[G]_i x^-1%g = ('chi_i x)^*. Proof. exact/char_inv/irr_char. Qed. (* This is Isaacs, Theorem (2.13). *) Theorem generalized_orthogonality_relation y (i j : Iirr G) : #|G|%:R^-1 * (\sum_(x in G) 'chi_i (x * y)%g * 'chi_j x^-1%g) = (i == j)%:R * ('chi_i y / 'chi_i 1%g). Proof. pose W := @socle_of_Iirr _ G; pose e k := Wedderburn_id (W k). pose aG := regular_repr algC G. have [Gy | notGy] := boolP (y \in G); last first. rewrite cfun0 // mul0r big1 ?mulr0 // => x Gx. by rewrite cfun0 ?groupMl ?mul0r. transitivity (('chi_i).[e j *m aG y]%CF / 'chi_j 1%g). rewrite [e j]Wedderburn_id_expansion -scalemxAl xcfunZr -mulrA; congr (_ * _). rewrite mulmx_suml raddf_sum big_distrl; apply: eq_bigr => x Gx /=. rewrite -scalemxAl xcfunZr -repr_mxM // xcfunG ?groupM // mulrAC mulrC. by congr (_ * _); rewrite mulrC mulKf ?irr1_neq0. rewrite mulr_natl mulrb; have [<-{j} | neq_ij] := eqVneq. by congr (_ / _); rewrite xcfun_mul_id ?envelop_mx_id ?xcfunG. rewrite (xcfun_annihilate neq_ij) ?mul0r //. case/andP: (Wedderburn_ideal (W j)) => _; apply: submx_trans. by rewrite mem_mulsmx ?Wedderburn_id_mem ?envelop_mx_id. Qed. (* This is Isaacs, Corollary (2.14). *) Corollary first_orthogonality_relation (i j : Iirr G) : #|G|%:R^-1 * (\sum_(x in G) 'chi_i x * 'chi_j x^-1%g) = (i == j)%:R. Proof. have:= generalized_orthogonality_relation 1 i j. rewrite mulrA mulfK ?irr1_neq0 // => <-; congr (_ * _). by apply: eq_bigr => x; rewrite mulg1. Qed. (* The character table. *) Definition irr_class i := enum_val (cast_ord (NirrE G) i). Definition class_Iirr xG := cast_ord (esym (NirrE G)) (enum_rank_in (classes1 G) xG). Local Notation c := irr_class. Local Notation g i := (repr (c i)). Local Notation iC := class_Iirr. Definition character_table := \matrix_(i, j) 'chi[G]_i (g j). Local Notation X := character_table. Lemma irr_classP i : c i \in classes G. Proof. exact: enum_valP. Qed. Lemma repr_irr_classK i : g i ^: G = c i. Proof. by case/repr_classesP: (irr_classP i). Qed. Lemma irr_classK : cancel c iC. Proof. by move=> i; rewrite /iC enum_valK_in cast_ordK. Qed. Lemma class_IirrK : {in classes G, cancel iC c}. Proof. by move=> xG GxG; rewrite /c cast_ordKV enum_rankK_in. Qed. Lemma reindex_irr_class R idx (op : @Monoid.com_law R idx) F : \big[op/idx]_(xG in classes G) F xG = \big[op/idx]_i F (c i). Proof. rewrite (reindex c); first by apply: eq_bigl => i; apply: enum_valP. by exists iC; [apply: in1W; apply: irr_classK | apply: class_IirrK]. Qed. (* The explicit value of the inverse is needed for the proof of the second *) (* orthogonality relation. *) Let X' := \matrix_(i, j) (#|'C_G[g i]|%:R^-1 * ('chi[G]_j (g i))^*). Let XX'_1: X *m X' = 1%:M. Proof. apply/matrixP=> i j; rewrite !mxE -first_orthogonality_relation mulr_sumr. rewrite sum_by_classes => [|u v Gu Gv]; last by rewrite -conjVg !cfunJ. rewrite reindex_irr_class /=; apply/esym/eq_bigr=> k _. rewrite !mxE irr_inv // -/(g k) -divg_index -indexgI /=. rewrite (pchar0_natf_div Cpchar) ?dvdn_indexg // index_cent1 invfM invrK. by rewrite repr_irr_classK mulrCA mulrA mulrCA. Qed. Lemma character_table_unit : X \in unitmx. Proof. by case/mulmx1_unit: XX'_1. Qed. Let uX := character_table_unit. (* This is Isaacs, Theorem (2.18). *) Theorem second_orthogonality_relation x y : y \in G -> \sum_i 'chi[G]_i x * ('chi_i y)^* = #|'C_G[x]|%:R *+ (x \in y ^: G). Proof. move=> Gy; pose i_x := iC (x ^: G); pose i_y := iC (y ^: G). have [Gx | notGx] := boolP (x \in G); last first. rewrite (contraNF (subsetP _ x) notGx) ?class_subG ?big1 // => i _. by rewrite cfun0 ?mul0r. transitivity ((#|'C_G[repr (y ^: G)]|%:R *: (X' *m X)) i_y i_x). rewrite scalemxAl !mxE; apply: eq_bigr => k _; rewrite !mxE mulrC -!mulrA. by rewrite !class_IirrK ?mem_classes // !cfun_repr mulVKf ?neq0CG. rewrite mulmx1C // !mxE -!divg_index; do 2!rewrite -indexgI index_cent1. rewrite (class_eqP (mem_repr y _)) ?class_refl // mulr_natr. rewrite (can_in_eq class_IirrK) ?mem_classes //. have [-> | not_yGx] := eqVneq; first by rewrite class_refl. by rewrite [x \in _](contraNF _ not_yGx) // => /class_eqP->. Qed. Lemma eq_irr_mem_classP x y : y \in G -> reflect (forall i, 'chi[G]_i x = 'chi_i y) (x \in y ^: G). Proof. move=> Gy; apply: (iffP idP) => [/imsetP[z Gz ->] i | xGy]; first exact: cfunJ. have Gx: x \in G. congr is_true: Gy; apply/eqP; rewrite -(can_eq oddb) -eqC_nat -!cfun1E. by rewrite -irr0 xGy. congr is_true: (class_refl G x); apply/eqP; rewrite -(can_eq oddb). rewrite -(eqn_pmul2l (cardG_gt0 'C_G[x])) -eqC_nat !mulrnA; apply/eqP. by rewrite -!second_orthogonality_relation //; apply/eq_bigr=> i _; rewrite xGy. Qed. (* This is Isaacs, Theorem (6.32) (due to Brauer). *) Lemma card_afix_irr_classes (ito : action A (Iirr G)) (cto : action A _) a : a \in A -> [acts A, on classes G | cto] -> (forall i x y, x \in G -> y \in cto (x ^: G) a -> 'chi_i x = 'chi_(ito i a) y) -> #|'Fix_ito[a]| = #|'Fix_(classes G | cto)[a]|. Proof. move=> Aa actsAG stabAchi; apply/eqP; rewrite -eqC_nat; apply/eqP. have [[cP cK] iCK] := (irr_classP, irr_classK, class_IirrK). pose icto b i := iC (cto (c i) b). have Gca i: cto (c i) a \in classes G by rewrite (acts_act actsAG). have inj_qa: injective (icto a). by apply: can_inj (icto a^-1%g) _ => i; rewrite /icto iCK ?actKin ?cK. pose Pa : 'M[algC]_(Nirr G) := perm_mx (actperm ito a). pose qa := perm inj_qa; pose Qa : 'M[algC]_(Nirr G) := perm_mx qa^-1^-1%g. transitivity (\tr Pa). rewrite -sumr_const big_mkcond; apply: eq_bigr => i _. by rewrite !mxE permE inE sub1set inE; case: ifP. symmetry; transitivity (\tr Qa). rewrite cardsE -sumr_const -big_filter_cond big_mkcond big_filter /=. rewrite reindex_irr_class; apply: eq_bigr => i _; rewrite !mxE invgK permE. by rewrite inE sub1set inE -(can_eq cK) iCK //; case: ifP. rewrite -[Pa](mulmxK uX) -[Qa](mulKmx uX) mxtrace_mulC; congr (\tr(_ *m _)). rewrite -row_permE -col_permE; apply/matrixP=> i j; rewrite !mxE. rewrite -{2}[j](permKV qa); move: {j}(_ j) => j; rewrite !permE iCK //. apply: stabAchi; first by case/repr_classesP: (cP j). by rewrite repr_irr_classK (mem_repr_classes (Gca _)). Qed. End OrthogonalityRelations. Prenex Implicits irr_class class_Iirr irr_classK. Arguments class_IirrK {gT G%_G} [xG%_g] GxG : rename. Arguments character_table {gT} G%_g. Section InnerProduct. Variable (gT : finGroupType) (G : {group gT}). Lemma cfdot_irr i j : '['chi_i, 'chi_j]_G = (i == j)%:R. Proof. rewrite -first_orthogonality_relation; congr (_ * _). by apply: eq_bigr => x Gx; rewrite irr_inv. Qed. Lemma cfnorm_irr i : '['chi[G]_i] = 1. Proof. by rewrite cfdot_irr eqxx. Qed. Lemma irr_orthonormal : orthonormal (irr G). Proof. apply/orthonormalP; split; first exact: free_uniq (irr_free G). move=> _ _ /irrP[i ->] /irrP[j ->]. by rewrite cfdot_irr (inj_eq irr_inj). Qed. Lemma coord_cfdot phi i : coord (irr G) i phi = '[phi, 'chi_i]. Proof. rewrite {2}(coord_basis (irr_basis G) (memvf phi)). rewrite cfdot_suml (bigD1 i) // cfdotZl /= -tnth_nth cfdot_irr eqxx mulr1. rewrite big1 ?addr0 // => j neq_ji; rewrite cfdotZl /= -tnth_nth cfdot_irr. by rewrite (negbTE neq_ji) mulr0. Qed. Lemma cfun_sum_cfdot phi : phi = \sum_i '[phi, 'chi_i]_G *: 'chi_i. Proof. rewrite {1}(coord_basis (irr_basis G) (memvf phi)). by apply: eq_bigr => i _; rewrite coord_cfdot -tnth_nth. Qed. Lemma cfdot_sum_irr phi psi : '[phi, psi]_G = \sum_i '[phi, 'chi_i] * '[psi, 'chi_i]^*. Proof. rewrite {1}[phi]cfun_sum_cfdot cfdot_suml; apply: eq_bigr => i _. by rewrite cfdotZl -cfdotC. Qed. Lemma Cnat_cfdot_char_irr i phi : phi \is a character -> '[phi, 'chi_i]_G \in Num.nat. Proof. by move/forallP/(_ i); rewrite coord_cfdot. Qed. Lemma cfdot_char_r phi chi : chi \is a character -> '[phi, chi]_G = \sum_i '[phi, 'chi_i] * '[chi, 'chi_i]. Proof. move=> Nchi; rewrite cfdot_sum_irr; apply: eq_bigr => i _; congr (_ * _). by rewrite conj_natr ?Cnat_cfdot_char_irr. Qed. Lemma Cnat_cfdot_char chi xi : chi \is a character -> xi \is a character -> '[chi, xi]_G \in Num.nat. Proof. move=> Nchi Nxi; rewrite cfdot_char_r ?rpred_sum // => i _. by rewrite rpredM ?Cnat_cfdot_char_irr. Qed. Lemma cfdotC_char chi xi : chi \is a character-> xi \is a character -> '[chi, xi]_G = '[xi, chi]. Proof. by move=> Nchi Nxi; rewrite cfdotC conj_natr ?Cnat_cfdot_char. Qed. Lemma irrEchar chi : (chi \in irr G) = (chi \is a character) && ('[chi] == 1). Proof. apply/irrP/andP=> [[i ->] | [Nchi]]; first by rewrite irr_char cfnorm_irr. rewrite cfdot_sum_irr => /eqP/natr_sum_eq1[i _| i [_ ci1 cj0]]. by rewrite rpredM // ?conj_natr ?Cnat_cfdot_char_irr. exists i; rewrite [chi]cfun_sum_cfdot (bigD1 i) //=. rewrite -(normr_idP (natr_ge0 (Cnat_cfdot_char_irr i Nchi))). rewrite normC_def {}ci1 sqrtC1 scale1r big1 ?addr0 // => j neq_ji. by rewrite (('[_] =P 0) _) ?scale0r // -normr_eq0 normC_def cj0 ?sqrtC0. Qed. Lemma irrWchar chi : chi \in irr G -> chi \is a character. Proof. by rewrite irrEchar => /andP[]. Qed. Lemma irrWnorm chi : chi \in irr G -> '[chi] = 1. Proof. by rewrite irrEchar => /andP[_ /eqP]. Qed. Lemma mul_lin_irr xi chi : xi \is a linear_char -> chi \in irr G -> xi * chi \in irr G. Proof. move=> Lxi; rewrite !irrEchar => /andP[Nphi /eqP <-]. rewrite rpredM // ?lin_charW //=; apply/eqP; congr (_ * _). apply: eq_bigr=> x Gx; rewrite !cfunE rmorphM/= mulrACA -(lin_charV_conj Lxi)//. by rewrite -lin_charM ?groupV // mulgV lin_char1 ?mul1r. Qed. Lemma eq_scaled_irr a b i j : (a *: 'chi[G]_i == b *: 'chi_j) = (a == b) && ((a == 0) || (i == j)). Proof. apply/eqP/andP=> [|[/eqP-> /pred2P[]-> //]]; last by rewrite !scale0r. move/(congr1 (cfdotr 'chi__)) => /= eq_ai_bj. move: {eq_ai_bj}(eq_ai_bj i) (esym (eq_ai_bj j)); rewrite !cfdotZl !cfdot_irr. by rewrite !mulr_natr !mulrb !eqxx eq_sym orbC; case: ifP => _ -> //= ->. Qed. Lemma eq_signed_irr (s t : bool) i j : ((-1) ^+ s *: 'chi[G]_i == (-1) ^+ t *: 'chi_j) = (s == t) && (i == j). Proof. by rewrite eq_scaled_irr signr_eq0 (inj_eq signr_inj). Qed. Lemma eq_scale_irr a (i j : Iirr G) : (a *: 'chi_i == a *: 'chi_j) = (a == 0) || (i == j). Proof. by rewrite eq_scaled_irr eqxx. Qed. Lemma eq_addZ_irr a b (i j r t : Iirr G) : (a *: 'chi_i + b *: 'chi_j == a *: 'chi_r + b *: 'chi_t) = [|| [&& (a == 0) || (i == r) & (b == 0) || (j == t)], [&& i == t, j == r & a == b] | [&& i == j, r == t & a == - b]]. Proof. rewrite -!eq_scale_irr; apply/eqP/idP; last first. case/orP; first by case/andP=> /eqP-> /eqP->. case/orP=> /and3P[/eqP-> /eqP-> /eqP->]; first by rewrite addrC. by rewrite !scaleNr !addNr. have [-> /addrI/eqP-> // | /=] := eqVneq. rewrite eq_scale_irr => /norP[/negP nz_a /negPf neq_ir]. move/(congr1 (cfdotr 'chi__))/esym/eqP => /= eq_cfdot. move: {eq_cfdot}(eq_cfdot i) (eq_cfdot r); rewrite eq_sym !cfdotDl !cfdotZl. rewrite !cfdot_irr !mulr_natr !mulrb !eqxx -!(eq_sym i) neq_ir !add0r. have [<- _ | _] := i =P t; first by rewrite neq_ir addr0; case: ifP => // _ ->. rewrite 2!fun_if if_arg addr0 addr_eq0; case: eqP => //= <- ->. by rewrite neq_ir 2!fun_if if_arg eq_sym addr0; case: ifP. Qed. Lemma eq_subZnat_irr (a b : nat) (i j r t : Iirr G) : (a%:R *: 'chi_i - b%:R *: 'chi_j == a%:R *: 'chi_r - b%:R *: 'chi_t) = [|| a == 0 | i == r] && [|| b == 0 | j == t] || [&& i == j, r == t & a == b]. Proof. rewrite -!scaleNr eq_addZ_irr oppr_eq0 opprK -addr_eq0 -natrD eqr_nat. by rewrite !pnatr_eq0 addn_eq0; case: a b => [|a] [|b]; rewrite ?andbF. Qed. End InnerProduct. Section IrrConstt. Variable (gT : finGroupType) (G H : {group gT}). Lemma char1_ge_norm (chi : 'CF(G)) x : chi \is a character -> `|chi x| <= chi 1%g. Proof. case/char_reprP=> rG ->; case Gx: (x \in G); last first. by rewrite cfunE cfRepr1 Gx normr0 ler0n. by have [e [_ _ []]] := repr_rsim_diag rG Gx. Qed. Lemma max_cfRepr_norm_scalar n (rG : mx_representation algC G n) x : x \in G -> `|cfRepr rG x| = cfRepr rG 1%g -> exists2 c, `|c| = 1 & rG x = c%:M. Proof. move=> Gx; have [e [[B uB def_x] [_ e1] [-> _] _]] := repr_rsim_diag rG Gx. rewrite cfRepr1 -[n in n%:R]card_ord -sumr_const -(eq_bigr _ (in1W e1)). case/normC_sum_eq1=> [i _ | c /eqP norm_c_1 def_e]; first by rewrite e1. have{} def_e: e = const_mx c by apply/rowP=> i; rewrite mxE def_e ?andbT. by exists c => //; rewrite def_x def_e diag_const_mx scalar_mxC mulmxKV. Qed. Lemma max_cfRepr_mx1 n (rG : mx_representation algC G n) x : x \in G -> cfRepr rG x = cfRepr rG 1%g -> rG x = 1%:M. Proof. move=> Gx kerGx; have [|c _ def_x] := @max_cfRepr_norm_scalar n rG x Gx. by rewrite kerGx cfRepr1 normr_nat. move/eqP: kerGx; rewrite cfRepr1 cfunE Gx {rG}def_x mxtrace_scalar. case: n => [_|n]; first by rewrite ![_%:M]flatmx0. rewrite mulrb -subr_eq0 -mulrnBl -mulr_natl mulf_eq0 pnatr_eq0 /=. by rewrite subr_eq0 => /eqP->. Qed. Definition irr_constt (B : {set gT}) phi := [pred i | '[phi, 'chi_i]_B != 0]. Lemma irr_consttE i phi : (i \in irr_constt phi) = ('[phi, 'chi_i]_G != 0). Proof. by []. Qed. Lemma constt_charP (i : Iirr G) chi : chi \is a character -> reflect (exists2 chi', chi' \is a character & chi = 'chi_i + chi') (i \in irr_constt chi). Proof. move=> Nchi; apply: (iffP idP) => [i_in_chi| [chi' Nchi' ->]]; last first. rewrite inE /= cfdotDl cfdot_irr eqxx -(eqP (Cnat_cfdot_char_irr i Nchi')). by rewrite -natrD pnatr_eq0. exists (chi - 'chi_i); last by rewrite addrC subrK. apply/forallP=> j; rewrite coord_cfdot cfdotBl cfdot_irr. have [<- | _] := eqP; last by rewrite subr0 Cnat_cfdot_char_irr. move: i_in_chi; rewrite inE; case/natrP: (Cnat_cfdot_char_irr i Nchi) => n ->. by rewrite pnatr_eq0 -lt0n => /natrB <-; apply: rpred_nat. Qed. Lemma cfun_sum_constt (phi : 'CF(G)) : phi = \sum_(i in irr_constt phi) '[phi, 'chi_i] *: 'chi_i. Proof. rewrite {1}[phi]cfun_sum_cfdot (bigID [pred i | '[phi, 'chi_i] == 0]) /=. by rewrite big1 ?add0r // => i /eqP->; rewrite scale0r. Qed. Lemma neq0_has_constt (phi : 'CF(G)) : phi != 0 -> exists i, i \in irr_constt phi. Proof. move=> nz_phi; apply/existsP; apply: contra nz_phi => /pred0P phi0. by rewrite [phi]cfun_sum_constt big_pred0. Qed. Lemma constt_irr i : irr_constt 'chi[G]_i =i pred1 i. Proof. by move=> j; rewrite !inE cfdot_irr pnatr_eq0 (eq_sym j); case: (i == j). Qed. Lemma char1_ge_constt (i : Iirr G) chi : chi \is a character -> i \in irr_constt chi -> 'chi_i 1%g <= chi 1%g. Proof. move=> {chi} _ /constt_charP[// | chi Nchi ->]. by rewrite cfunE addrC -subr_ge0 addrK char1_ge0. Qed. Lemma constt_ortho_char (phi psi : 'CF(G)) i j : phi \is a character -> psi \is a character -> i \in irr_constt phi -> j \in irr_constt psi -> '[phi, psi] = 0 -> '['chi_i, 'chi_j] = 0. Proof. move=> _ _ /constt_charP[//|phi1 Nphi1 ->] /constt_charP[//|psi1 Npsi1 ->]. rewrite cfdot_irr; case: eqP => // -> /eqP/idPn[]. rewrite cfdotDl !cfdotDr cfnorm_irr -addrA gt_eqF ?ltr_wpDr ?ltr01 //. by rewrite natr_ge0 ?rpredD ?Cnat_cfdot_char ?irr_char. Qed. End IrrConstt. Arguments irr_constt {gT B%_g} phi%_CF. Section Kernel. Variable (gT : finGroupType) (G : {group gT}). Implicit Types (phi chi xi : 'CF(G)) (H : {group gT}). Lemma cfker_repr n (rG : mx_representation algC G n) : cfker (cfRepr rG) = rker rG. Proof. apply/esym/setP=> x; rewrite inE mul1mx /=. case Gx: (x \in G); last by rewrite inE Gx. apply/eqP/idP=> Kx; last by rewrite max_cfRepr_mx1 // cfker1. rewrite inE Gx; apply/forallP=> y; rewrite !cfunE !mulrb groupMl //. by case: ifP => // Gy; rewrite repr_mxM // Kx mul1mx. Qed. Lemma cfkerEchar chi : chi \is a character -> cfker chi = [set x in G | chi x == chi 1%g]. Proof. move=> Nchi; apply/setP=> x; apply/idP/setIdP=> [Kx | [Gx /eqP chi_x]]. by rewrite (subsetP (cfker_sub chi)) // cfker1. case/char_reprP: Nchi => rG -> in chi_x *; rewrite inE Gx; apply/forallP=> y. rewrite !cfunE groupMl // !mulrb; case: ifP => // Gy. by rewrite repr_mxM // max_cfRepr_mx1 ?mul1mx. Qed. Lemma cfker_nzcharE chi : chi \is a character -> chi != 0 -> cfker chi = [set x | chi x == chi 1%g]. Proof. move=> Nchi nzchi; apply/setP=> x; rewrite cfkerEchar // !inE andb_idl //. by apply: contraLR => /cfun0-> //; rewrite eq_sym char1_eq0. Qed. Lemma cfkerEirr i : cfker 'chi[G]_i = [set x | 'chi_i x == 'chi_i 1%g]. Proof. by rewrite cfker_nzcharE ?irr_char ?irr_neq0. Qed. Lemma cfker_irr0 : cfker 'chi[G]_0 = G. Proof. by rewrite irr0 cfker_cfun1. Qed. Lemma cfaithful_reg : cfaithful (cfReg G). Proof. apply/subsetP=> x; rewrite cfkerEchar ?cfReg_char // !inE !cfRegE eqxx. by case/andP=> _; apply: contraLR => /negbTE->; rewrite eq_sym neq0CG. Qed. Lemma cfkerE chi : chi \is a character -> cfker chi = G :&: \bigcap_(i in irr_constt chi) cfker 'chi_i. Proof. move=> Nchi; rewrite cfkerEchar //; apply/setP=> x; rewrite !inE. apply: andb_id2l => Gx; rewrite {1 2}[chi]cfun_sum_constt !sum_cfunE. apply/eqP/bigcapP=> [Kx i Ci | Kx]; last first. by apply: eq_bigr => i /Kx Kx_i; rewrite !cfunE cfker1. rewrite cfkerEirr inE /= -(inj_eq (mulfI Ci)). have:= (normC_sum_upper _ Kx) i; rewrite !cfunE => -> // {Ci}i _. have chi_i_ge0: 0 <= '[chi, 'chi_i]. by rewrite natr_ge0 ?Cnat_cfdot_char_irr. by rewrite !cfunE normrM (normr_idP _) ?ler_wpM2l ?char1_ge_norm ?irr_char. Qed. Lemma TI_cfker_irr : \bigcap_i cfker 'chi[G]_i = [1]. Proof. apply/trivgP; apply: subset_trans cfaithful_reg; rewrite cfkerE ?cfReg_char //. rewrite subsetI (bigcap_min 0) //=; last by rewrite cfker_irr0. by apply/bigcapsP=> i _; rewrite bigcap_inf. Qed. Lemma cfker_constt i chi : chi \is a character -> i \in irr_constt chi -> cfker chi \subset cfker 'chi[G]_i. Proof. by move=> Nchi Ci; rewrite cfkerE ?subIset ?(bigcap_min i) ?orbT. Qed. Section KerLin. Variable xi : 'CF(G). Hypothesis lin_xi : xi \is a linear_char. Let Nxi: xi \is a character. Proof. by have [] := andP lin_xi. Qed. Lemma lin_char_der1 : G^`(1)%g \subset cfker xi. Proof. rewrite gen_subG /=; apply/subsetP=> _ /imset2P[x y Gx Gy ->]. rewrite cfkerEchar // inE groupR //= !lin_charM ?lin_charV ?in_group //. by rewrite mulrCA mulKf ?mulVf ?lin_char_neq0 // lin_char1. Qed. Lemma cforder_lin_char : #[xi]%CF = exponent (G / cfker xi)%g. Proof. apply/eqP; rewrite eqn_dvd; apply/andP; split. apply/dvdn_cforderP=> x Gx; rewrite -lin_charX // -cfQuoEker ?groupX //. rewrite morphX ?(subsetP (cfker_norm xi)) //= expg_exponent ?mem_quotient //. by rewrite cfQuo1 ?cfker_normal ?lin_char1. have abGbar: abelian (G / cfker xi) := sub_der1_abelian lin_char_der1. have [_ /morphimP[x Nx Gx ->] ->] := exponent_witness (abelian_nil abGbar). rewrite order_dvdn -morphX //= coset_id cfkerEchar // !inE groupX //=. by rewrite lin_charX ?lin_char1 // (dvdn_cforderP _ _ _). Qed. Lemma cforder_lin_char_dvdG : #[xi]%CF %| #|G|. Proof. by rewrite cforder_lin_char (dvdn_trans (exponent_dvdn _)) ?dvdn_morphim. Qed. Lemma cforder_lin_char_gt0 : (0 < #[xi]%CF)%N. Proof. by rewrite cforder_lin_char exponent_gt0. Qed. End KerLin. End Kernel. Section Restrict. Variable (gT : finGroupType) (G H : {group gT}). Lemma cfRepr_sub n (rG : mx_representation algC G n) (sHG : H \subset G) : cfRepr (subg_repr rG sHG) = 'Res[H] (cfRepr rG). Proof. by apply/cfun_inP => x Hx; rewrite cfResE // !cfunE Hx (subsetP sHG). Qed. Lemma cfRes_char chi : chi \is a character -> 'Res[H, G] chi \is a character. Proof. have [sHG | not_sHG] := boolP (H \subset G). by case/char_reprP=> rG ->; rewrite -(cfRepr_sub rG sHG) cfRepr_char. by move/Cnat_char1=> Nchi1; rewrite cfResEout // rpredZ_nat ?rpred1. Qed. Lemma cfRes_eq0 phi : phi \is a character -> ('Res[H, G] phi == 0) = (phi == 0). Proof. by move=> Nchi; rewrite -!char1_eq0 ?cfRes_char // cfRes1. Qed. Lemma cfRes_lin_char chi : chi \is a linear_char -> 'Res[H, G] chi \is a linear_char. Proof. by case/andP=> Nchi; rewrite qualifE/= cfRes_char ?cfRes1. Qed. Lemma Res_irr_neq0 i : 'Res[H, G] 'chi_i != 0. Proof. by rewrite cfRes_eq0 ?irr_neq0 ?irr_char. Qed. Lemma cfRes_lin_lin (chi : 'CF(G)) : chi \is a character -> 'Res[H] chi \is a linear_char -> chi \is a linear_char. Proof. by rewrite !qualifE/= !qualifE/= cfRes1 => -> /andP[]. Qed. Lemma cfRes_irr_irr chi : chi \is a character -> 'Res[H] chi \in irr H -> chi \in irr G. Proof. have [sHG /char_reprP[rG ->] | not_sHG Nchi] := boolP (H \subset G). rewrite -(cfRepr_sub _ sHG) => /irr_reprP[rH irrH def_rH]; apply/irr_reprP. suffices /subg_mx_irr: mx_irreducible (subg_repr rG sHG) by exists rG. by apply: mx_rsim_irr irrH; apply/cfRepr_rsimP/eqP. rewrite cfResEout // => /irrP[j Dchi_j]; apply/lin_char_irr/cfRes_lin_lin=> //. suffices j0: j = 0 by rewrite cfResEout // Dchi_j j0 irr0 rpred1. apply: contraNeq (irr1_neq0 j) => nz_j. have:= xcfun_id j 0; rewrite -Dchi_j cfunE xcfunZl -irr0 xcfun_id eqxx => ->. by rewrite (negPf nz_j). Qed. Definition Res_Iirr (A B : {set gT}) i := cfIirr ('Res[B, A] 'chi_i). Lemma Res_Iirr0 : Res_Iirr H (0 : Iirr G) = 0. Proof. by rewrite /Res_Iirr irr0 rmorph1 -irr0 irrK. Qed. Lemma lin_Res_IirrE i : 'chi[G]_i 1%g = 1 -> 'chi_(Res_Iirr H i) = 'Res 'chi_i. Proof. move=> chi1; rewrite cfIirrE ?lin_char_irr ?cfRes_lin_char //. by rewrite qualifE/= irr_char /= chi1. Qed. End Restrict. Arguments Res_Iirr {gT A%_g} B%_g i%_R. Section MoreConstt. Variables (gT : finGroupType) (G H : {group gT}). Lemma constt_Ind_Res i j : i \in irr_constt ('Ind[G] 'chi_j) = (j \in irr_constt ('Res[H] 'chi_i)). Proof. by rewrite !irr_consttE cfdotC conjC_eq0 -cfdot_Res_l. Qed. Lemma cfdot_Res_ge_constt i j psi : psi \is a character -> j \in irr_constt psi -> '['Res[H, G] 'chi_j, 'chi_i] <= '['Res[H] psi, 'chi_i]. Proof. move=> {psi} _ /constt_charP[// | psi Npsi ->]. rewrite linearD cfdotDl addrC -subr_ge0 addrK natr_ge0 //=. by rewrite Cnat_cfdot_char_irr // cfRes_char. Qed. Lemma constt_Res_trans j psi : psi \is a character -> j \in irr_constt psi -> {subset irr_constt ('Res[H, G] 'chi_j) <= irr_constt ('Res[H] psi)}. Proof. move=> Npsi Cj i; apply: contraNneq; rewrite eq_le => {1}<-. rewrite cfdot_Res_ge_constt ?natr_ge0 ?Cnat_cfdot_char_irr //. by rewrite cfRes_char ?irr_char. Qed. End MoreConstt. Section Morphim. Variables (aT rT : finGroupType) (G D : {group aT}) (f : {morphism D >-> rT}). Implicit Type chi : 'CF(f @* G). Lemma cfRepr_morphim n (rfG : mx_representation algC (f @* G) n) sGD : cfRepr (morphim_repr rfG sGD) = cfMorph (cfRepr rfG). Proof. apply/cfun_inP=> x Gx; have Dx: x \in D := subsetP sGD x Gx. by rewrite cfMorphE // !cfunE ?mem_morphim ?Gx. Qed. Lemma cfMorph_char chi : chi \is a character -> cfMorph chi \is a character. Proof. have [sGD /char_reprP[rfG ->] | outGD Nchi] := boolP (G \subset D); last first. by rewrite cfMorphEout // rpredZ_nat ?rpred1 ?Cnat_char1. apply/char_reprP; exists (Representation (morphim_repr rfG sGD)). by rewrite cfRepr_morphim. Qed. Lemma cfMorph_lin_char chi : chi \is a linear_char -> cfMorph chi \is a linear_char. Proof. by case/andP=> Nchi; rewrite qualifE/= cfMorph1 cfMorph_char. Qed. Lemma cfMorph_charE chi : G \subset D -> (cfMorph chi \is a character) = (chi \is a character). Proof. move=> sGD; apply/idP/idP=> [/char_reprP[[n rG] /=Dfchi] | /cfMorph_char//]. pose H := 'ker_G f; have kerH: H \subset rker rG. by rewrite -cfker_repr -Dfchi cfker_morph // setIS // ker_sub_pre. have nHG: G \subset 'N(H) by rewrite normsI // (subset_trans sGD) ?ker_norm. have [h injh im_h] := first_isom_loc f sGD; rewrite -/H in h injh im_h. have DfG: invm injh @*^-1 (G / H) == (f @* G)%g by rewrite morphpre_invm im_h. pose rfG := eqg_repr (morphpre_repr _ (quo_repr kerH nHG)) DfG. apply/char_reprP; exists (Representation rfG). apply/cfun_inP=> _ /morphimP[x Dx Gx ->]; rewrite -cfMorphE // Dfchi !cfunE Gx. pose xH := coset H x; have GxH: xH \in (G / H)%g by apply: mem_quotient. suffices Dfx: f x = h xH by rewrite mem_morphim //= Dfx invmE ?quo_repr_coset. by apply/set1_inj; rewrite -?morphim_set1 ?im_h ?(subsetP nHG) ?sub1set. Qed. Lemma cfMorph_lin_charE chi : G \subset D -> (cfMorph chi \is a linear_char) = (chi \is a linear_char). Proof. by rewrite qualifE/= cfMorph1 => /cfMorph_charE->. Qed. Lemma cfMorph_irr chi : G \subset D -> (cfMorph chi \in irr G) = (chi \in irr (f @* G)). Proof. by move=> sGD; rewrite !irrEchar cfMorph_charE // cfMorph_iso. Qed. Definition morph_Iirr i := cfIirr (cfMorph 'chi[f @* G]_i). Lemma morph_Iirr0 : morph_Iirr 0 = 0. Proof. by rewrite /morph_Iirr irr0 rmorph1 -irr0 irrK. Qed. Hypothesis sGD : G \subset D. Lemma morph_IirrE i : 'chi_(morph_Iirr i) = cfMorph 'chi_i. Proof. by rewrite cfIirrE ?cfMorph_irr ?mem_irr. Qed. Lemma morph_Iirr_inj : injective morph_Iirr. Proof. by move=> i j eq_ij; apply/irr_inj/cfMorph_inj; rewrite // -!morph_IirrE eq_ij. Qed. Lemma morph_Iirr_eq0 i : (morph_Iirr i == 0) = (i == 0). Proof. by rewrite -!irr_eq1 morph_IirrE cfMorph_eq1. Qed. End Morphim. Section Isom. Variables (aT rT : finGroupType) (G : {group aT}) (f : {morphism G >-> rT}). Variables (R : {group rT}) (isoGR : isom G R f). Implicit Type chi : 'CF(G). Lemma cfIsom_char chi : (cfIsom isoGR chi \is a character) = (chi \is a character). Proof. rewrite [cfIsom _]locked_withE cfMorph_charE //. by rewrite (isom_im (isom_sym _)) cfRes_id. Qed. Lemma cfIsom_lin_char chi : (cfIsom isoGR chi \is a linear_char) = (chi \is a linear_char). Proof. by rewrite qualifE/= cfIsom_char cfIsom1. Qed. Lemma cfIsom_irr chi : (cfIsom isoGR chi \in irr R) = (chi \in irr G). Proof. by rewrite !irrEchar cfIsom_char cfIsom_iso. Qed. Definition isom_Iirr i := cfIirr (cfIsom isoGR 'chi_i). Lemma isom_IirrE i : 'chi_(isom_Iirr i) = cfIsom isoGR 'chi_i. Proof. by rewrite cfIirrE ?cfIsom_irr ?mem_irr. Qed. Lemma isom_Iirr_inj : injective isom_Iirr. Proof. by move=> i j eqij; apply/irr_inj/(cfIsom_inj isoGR); rewrite -!isom_IirrE eqij. Qed. Lemma isom_Iirr_eq0 i : (isom_Iirr i == 0) = (i == 0). Proof. by rewrite -!irr_eq1 isom_IirrE cfIsom_eq1. Qed. Lemma isom_Iirr0 : isom_Iirr 0 = 0. Proof. by apply/eqP; rewrite isom_Iirr_eq0. Qed. End Isom. Arguments isom_Iirr_inj {aT rT G f R} isoGR [i1 i2] : rename. Section IsomInv. Variables (aT rT : finGroupType) (G : {group aT}) (f : {morphism G >-> rT}). Variables (R : {group rT}) (isoGR : isom G R f). Lemma isom_IirrK : cancel (isom_Iirr isoGR) (isom_Iirr (isom_sym isoGR)). Proof. by move=> i; apply: irr_inj; rewrite !isom_IirrE cfIsomK. Qed. Lemma isom_IirrKV : cancel (isom_Iirr (isom_sym isoGR)) (isom_Iirr isoGR). Proof. by move=> i; apply: irr_inj; rewrite !isom_IirrE cfIsomKV. Qed. End IsomInv. Section Sdprod. Variables (gT : finGroupType) (K H G : {group gT}). Hypothesis defG : K ><| H = G. Let nKG: G \subset 'N(K). Proof. by have [/andP[]] := sdprod_context defG. Qed. Lemma cfSdprod_char chi : (cfSdprod defG chi \is a character) = (chi \is a character). Proof. by rewrite unlock cfMorph_charE // cfIsom_char. Qed. Lemma cfSdprod_lin_char chi : (cfSdprod defG chi \is a linear_char) = (chi \is a linear_char). Proof. by rewrite qualifE/= cfSdprod_char cfSdprod1. Qed. Lemma cfSdprod_irr chi : (cfSdprod defG chi \in irr G) = (chi \in irr H). Proof. by rewrite !irrEchar cfSdprod_char cfSdprod_iso. Qed. Definition sdprod_Iirr j := cfIirr (cfSdprod defG 'chi_j). Lemma sdprod_IirrE j : 'chi_(sdprod_Iirr j) = cfSdprod defG 'chi_j. Proof. by rewrite cfIirrE ?cfSdprod_irr ?mem_irr. Qed. Lemma sdprod_IirrK : cancel sdprod_Iirr (Res_Iirr H). Proof. by move=> j; rewrite /Res_Iirr sdprod_IirrE cfSdprodK irrK. Qed. Lemma sdprod_Iirr_inj : injective sdprod_Iirr. Proof. exact: can_inj sdprod_IirrK. Qed. Lemma sdprod_Iirr_eq0 i : (sdprod_Iirr i == 0) = (i == 0). Proof. by rewrite -!irr_eq1 sdprod_IirrE cfSdprod_eq1. Qed. Lemma sdprod_Iirr0 : sdprod_Iirr 0 = 0. Proof. by apply/eqP; rewrite sdprod_Iirr_eq0. Qed. Lemma Res_sdprod_irr phi : K \subset cfker phi -> phi \in irr G -> 'Res phi \in irr H. Proof. move=> kerK /irrP[i Dphi]; rewrite irrEchar -(cfSdprod_iso defG). by rewrite cfRes_sdprodK // Dphi cfnorm_irr cfRes_char ?irr_char /=. Qed. Lemma sdprod_Res_IirrE i : K \subset cfker 'chi[G]_i -> 'chi_(Res_Iirr H i) = 'Res 'chi_i. Proof. by move=> kerK; rewrite cfIirrE ?Res_sdprod_irr ?mem_irr. Qed. Lemma sdprod_Res_IirrK i : K \subset cfker 'chi_i -> sdprod_Iirr (Res_Iirr H i) = i. Proof. by move=> kerK; rewrite /sdprod_Iirr sdprod_Res_IirrE ?cfRes_sdprodK ?irrK. Qed. End Sdprod. Arguments sdprod_Iirr_inj {gT K H G} defG [i1 i2] : rename. Section DProd. Variables (gT : finGroupType) (G K H : {group gT}). Hypothesis KxH : K \x H = G. Lemma cfDprodKl_abelian j : abelian H -> cancel ((cfDprod KxH)^~ 'chi_j) 'Res. Proof. by move=> cHH; apply: cfDprodKl; apply/lin_char1/char_abelianP. Qed. Lemma cfDprodKr_abelian i : abelian K -> cancel (cfDprod KxH 'chi_i) 'Res. Proof. by move=> cKK; apply: cfDprodKr; apply/lin_char1/char_abelianP. Qed. Lemma cfDprodl_char phi : (cfDprodl KxH phi \is a character) = (phi \is a character). Proof. exact: cfSdprod_char. Qed. Lemma cfDprodr_char psi : (cfDprodr KxH psi \is a character) = (psi \is a character). Proof. exact: cfSdprod_char. Qed. Lemma cfDprod_char phi psi : phi \is a character -> psi \is a character -> cfDprod KxH phi psi \is a character. Proof. by move=> Nphi Npsi; rewrite rpredM ?cfDprodl_char ?cfDprodr_char. Qed. Lemma cfDprod_eq1 phi psi : phi \is a character -> psi \is a character -> (cfDprod KxH phi psi == 1) = (phi == 1) && (psi == 1). Proof. move=> /Cnat_char1 Nphi /Cnat_char1 Npsi. apply/eqP/andP=> [phi_psi_1 | [/eqP-> /eqP->]]; last by rewrite cfDprod_cfun1. have /andP[/eqP phi1 /eqP psi1]: (phi 1%g == 1) && (psi 1%g == 1). by rewrite -natr_mul_eq1 // -(cfDprod1 KxH) phi_psi_1 cfun11. rewrite -[phi](cfDprodKl KxH psi1) -{2}[psi](cfDprodKr KxH phi1) phi_psi_1. by rewrite !rmorph1. Qed. Lemma cfDprodl_lin_char phi : (cfDprodl KxH phi \is a linear_char) = (phi \is a linear_char). Proof. exact: cfSdprod_lin_char. Qed. Lemma cfDprodr_lin_char psi : (cfDprodr KxH psi \is a linear_char) = (psi \is a linear_char). Proof. exact: cfSdprod_lin_char. Qed. Lemma cfDprod_lin_char phi psi : phi \is a linear_char -> psi \is a linear_char -> cfDprod KxH phi psi \is a linear_char. Proof. by move=> Nphi Npsi; rewrite rpredM ?cfSdprod_lin_char. Qed. Lemma cfDprodl_irr chi : (cfDprodl KxH chi \in irr G) = (chi \in irr K). Proof. exact: cfSdprod_irr. Qed. Lemma cfDprodr_irr chi : (cfDprodr KxH chi \in irr G) = (chi \in irr H). Proof. exact: cfSdprod_irr. Qed. Definition dprodl_Iirr i := cfIirr (cfDprodl KxH 'chi_i). Lemma dprodl_IirrE i : 'chi_(dprodl_Iirr i) = cfDprodl KxH 'chi_i. Proof. exact: sdprod_IirrE. Qed. Lemma dprodl_IirrK : cancel dprodl_Iirr (Res_Iirr K). Proof. exact: sdprod_IirrK. Qed. Lemma dprodl_Iirr_eq0 i : (dprodl_Iirr i == 0) = (i == 0). Proof. exact: sdprod_Iirr_eq0. Qed. Lemma dprodl_Iirr0 : dprodl_Iirr 0 = 0. Proof. exact: sdprod_Iirr0. Qed. Definition dprodr_Iirr j := cfIirr (cfDprodr KxH 'chi_j). Lemma dprodr_IirrE j : 'chi_(dprodr_Iirr j) = cfDprodr KxH 'chi_j. Proof. exact: sdprod_IirrE. Qed. Lemma dprodr_IirrK : cancel dprodr_Iirr (Res_Iirr H). Proof. exact: sdprod_IirrK. Qed. Lemma dprodr_Iirr_eq0 j : (dprodr_Iirr j == 0) = (j == 0). Proof. exact: sdprod_Iirr_eq0. Qed. Lemma dprodr_Iirr0 : dprodr_Iirr 0 = 0. Proof. exact: sdprod_Iirr0. Qed. Lemma cfDprod_irr i j : cfDprod KxH 'chi_i 'chi_j \in irr G. Proof. rewrite irrEchar cfDprod_char ?irr_char //=. by rewrite cfdot_dprod !cfdot_irr !eqxx mul1r. Qed. Definition dprod_Iirr ij := cfIirr (cfDprod KxH 'chi_ij.1 'chi_ij.2). Lemma dprod_IirrE i j : 'chi_(dprod_Iirr (i, j)) = cfDprod KxH 'chi_i 'chi_j. Proof. by rewrite cfIirrE ?cfDprod_irr. Qed. Lemma dprod_IirrEl i : 'chi_(dprod_Iirr (i, 0)) = cfDprodl KxH 'chi_i. Proof. by rewrite dprod_IirrE /cfDprod irr0 rmorph1 mulr1. Qed. Lemma dprod_IirrEr j : 'chi_(dprod_Iirr (0, j)) = cfDprodr KxH 'chi_j. Proof. by rewrite dprod_IirrE /cfDprod irr0 rmorph1 mul1r. Qed. Lemma dprod_Iirr_inj : injective dprod_Iirr. Proof. move=> [i1 j1] [i2 j2] /eqP; rewrite -[_ == _]oddb -(@natrK algC (_ == _)). rewrite -cfdot_irr !dprod_IirrE cfdot_dprod !cfdot_irr -natrM mulnb. by rewrite natrK oddb -xpair_eqE => /eqP. Qed. Lemma dprod_Iirr0 : dprod_Iirr (0, 0) = 0. Proof. by apply/irr_inj; rewrite dprod_IirrE !irr0 cfDprod_cfun1. Qed. Lemma dprod_Iirr0l j : dprod_Iirr (0, j) = dprodr_Iirr j. Proof. by apply/irr_inj; rewrite dprod_IirrE irr0 dprodr_IirrE cfDprod_cfun1l. Qed. Lemma dprod_Iirr0r i : dprod_Iirr (i, 0) = dprodl_Iirr i. Proof. by apply/irr_inj; rewrite dprod_IirrE irr0 dprodl_IirrE cfDprod_cfun1r. Qed. Lemma dprod_Iirr_eq0 i j : (dprod_Iirr (i, j) == 0) = (i == 0) && (j == 0). Proof. by rewrite -xpair_eqE -(inj_eq dprod_Iirr_inj) dprod_Iirr0. Qed. Lemma cfdot_dprod_irr i1 i2 j1 j2 : '['chi_(dprod_Iirr (i1, j1)), 'chi_(dprod_Iirr (i2, j2))] = ((i1 == i2) && (j1 == j2))%:R. Proof. by rewrite cfdot_irr (inj_eq dprod_Iirr_inj). Qed. Lemma dprod_Iirr_onto k : k \in codom dprod_Iirr. Proof. set D := codom _; have Df: dprod_Iirr _ \in D := codom_f dprod_Iirr _. have: 'chi_k 1%g ^+ 2 != 0 by rewrite mulf_neq0 ?irr1_neq0. apply: contraR => notDk; move/eqP: (irr_sum_square G). rewrite (bigID [in D]) (reindex _ (bij_on_codom dprod_Iirr_inj (0, 0))) /=. have ->: #|G|%:R = \sum_i \sum_j 'chi_(dprod_Iirr (i, j)) 1%g ^+ 2. rewrite -(dprod_card KxH) natrM. do 2![rewrite -irr_sum_square (mulr_suml, mulr_sumr); apply: eq_bigr => ? _]. by rewrite dprod_IirrE -exprMn -{3}(mulg1 1%g) cfDprodE. rewrite (eq_bigl _ _ Df) pair_bigA addrC -subr_eq0 addrK. by move/eqP/psumr_eq0P=> -> //= i _; rewrite irr1_degree -natrX ler0n. Qed. Definition inv_dprod_Iirr i := iinv (dprod_Iirr_onto i). Lemma dprod_IirrK : cancel dprod_Iirr inv_dprod_Iirr. Proof. by move=> p; apply: (iinv_f dprod_Iirr_inj). Qed. Lemma inv_dprod_IirrK : cancel inv_dprod_Iirr dprod_Iirr. Proof. by move=> i; apply: f_iinv. Qed. Lemma inv_dprod_Iirr0 : inv_dprod_Iirr 0 = (0, 0). Proof. by apply/(canLR dprod_IirrK); rewrite dprod_Iirr0. Qed. End DProd. Arguments dprod_Iirr_inj {gT G K H} KxH [i1 i2] : rename. Lemma dprod_IirrC (gT : finGroupType) (G K H : {group gT}) (KxH : K \x H = G) (HxK : H \x K = G) i j : dprod_Iirr KxH (i, j) = dprod_Iirr HxK (j, i). Proof. by apply: irr_inj; rewrite !dprod_IirrE; apply: cfDprodC. Qed. Section BigDprod. Variables (gT : finGroupType) (I : finType) (P : pred I). Variables (A : I -> {group gT}) (G : {group gT}). Hypothesis defG : \big[dprod/1%g]_(i | P i) A i = G. Let sAG i : P i -> A i \subset G. Proof. by move=> Pi; rewrite -(bigdprodWY defG) (bigD1 i) ?joing_subl. Qed. Lemma cfBigdprodi_char i (phi : 'CF(A i)) : phi \is a character -> cfBigdprodi defG phi \is a character. Proof. by move=> Nphi; rewrite cfDprodl_char cfRes_char. Qed. Lemma cfBigdprodi_charE i (phi : 'CF(A i)) : P i -> (cfBigdprodi defG phi \is a character) = (phi \is a character). Proof. by move=> Pi; rewrite cfDprodl_char Pi cfRes_id. Qed. Lemma cfBigdprod_char phi : (forall i, P i -> phi i \is a character) -> cfBigdprod defG phi \is a character. Proof. by move=> Nphi; apply: rpred_prod => i /Nphi; apply: cfBigdprodi_char. Qed. Lemma cfBigdprodi_lin_char i (phi : 'CF(A i)) : phi \is a linear_char -> cfBigdprodi defG phi \is a linear_char. Proof. by move=> Lphi; rewrite cfDprodl_lin_char ?cfRes_lin_char. Qed. Lemma cfBigdprodi_lin_charE i (phi : 'CF(A i)) : P i -> (cfBigdprodi defG phi \is a linear_char) = (phi \is a linear_char). Proof. by move=> Pi; rewrite qualifE/= cfBigdprodi_charE // cfBigdprodi1. Qed. Lemma cfBigdprod_lin_char phi : (forall i, P i -> phi i \is a linear_char) -> cfBigdprod defG phi \is a linear_char. Proof. by move=> Lphi; apply/rpred_prod=> i /Lphi; apply: cfBigdprodi_lin_char. Qed. Lemma cfBigdprodi_irr i chi : P i -> (cfBigdprodi defG chi \in irr G) = (chi \in irr (A i)). Proof. by move=> Pi; rewrite !irrEchar cfBigdprodi_charE ?cfBigdprodi_iso. Qed. Lemma cfBigdprod_irr chi : (forall i, P i -> chi i \in irr (A i)) -> cfBigdprod defG chi \in irr G. Proof. move=> Nchi; rewrite irrEchar cfBigdprod_char => [|i /Nchi/irrWchar] //=. by rewrite cfdot_bigdprod big1 // => i /Nchi/irrWnorm. Qed. Lemma cfBigdprod_eq1 phi : (forall i, P i -> phi i \is a character) -> (cfBigdprod defG phi == 1) = [forall (i | P i), phi i == 1]. Proof. move=> Nphi; set Phi := cfBigdprod defG phi. apply/eqP/eqfun_inP=> [Phi1 i Pi | phi1]; last first. by apply: big1 => i /phi1->; rewrite rmorph1. have Phi1_1: Phi 1%g = 1 by rewrite Phi1 cfun1E group1. have nz_Phi1: Phi 1%g != 0 by rewrite Phi1_1 oner_eq0. have [_ <-] := cfBigdprodK nz_Phi1 Pi. rewrite Phi1_1 divr1 -/Phi Phi1 rmorph1. rewrite prod_cfunE // in Phi1_1; have := natr_prod_eq1 _ Phi1_1 Pi. rewrite -(cfRes1 (A i)) cfBigdprodiK // => ->; first by rewrite scale1r. by move=> {i Pi} j /Nphi Nphi_j; rewrite Cnat_char1 ?cfBigdprodi_char. Qed. Lemma cfBigdprod_Res_lin chi : chi \is a linear_char -> cfBigdprod defG (fun i => 'Res[A i] chi) = chi. Proof. move=> Lchi; apply/cfun_inP=> _ /(mem_bigdprod defG)[x [Ax -> _]]. rewrite (lin_char_prod Lchi) ?cfBigdprodE // => [|i Pi]; last first. by rewrite (subsetP (sAG Pi)) ?Ax. by apply/eq_bigr=> i Pi; rewrite cfResE ?sAG ?Ax. Qed. Lemma cfBigdprodKlin phi : (forall i, P i -> phi i \is a linear_char) -> forall i, P i -> 'Res (cfBigdprod defG phi) = phi i. Proof. move=> Lphi i Pi; have Lpsi := cfBigdprod_lin_char Lphi. have [_ <-] := cfBigdprodK (lin_char_neq0 Lpsi (group1 G)) Pi. by rewrite !lin_char1 ?Lphi // divr1 scale1r. Qed. Lemma cfBigdprodKabelian Iphi (phi := fun i => 'chi_(Iphi i)) : abelian G -> forall i, P i -> 'Res (cfBigdprod defG phi) = 'chi_(Iphi i). Proof. move=> /(abelianS _) cGG. by apply: cfBigdprodKlin => i /sAG/cGG/char_abelianP->. Qed. End BigDprod. Section Aut. Variables (gT : finGroupType) (G : {group gT}). Implicit Type u : {rmorphism algC -> algC}. Lemma conjC_charAut u (chi : 'CF(G)) x : chi \is a character -> (u (chi x))^* = u (chi x)^*. Proof. have [Gx | /cfun0->] := boolP (x \in G); last by rewrite !rmorph0. case/char_reprP=> rG ->; have [e [_ [en1 _] [-> _] _]] := repr_rsim_diag rG Gx. by rewrite !rmorph_sum; apply: eq_bigr => i _; apply: aut_unity_rootC (en1 i). Qed. Lemma conjC_irrAut u i x : (u ('chi[G]_i x))^* = u ('chi_i x)^*. Proof. exact: conjC_charAut (irr_char i). Qed. Lemma cfdot_aut_char u (phi chi : 'CF(G)) : chi \is a character -> '[cfAut u phi, cfAut u chi] = u '[phi, chi]. Proof. by move/conjC_charAut=> Nchi; apply: cfdot_cfAut => _ /mapP[x _ ->]. Qed. Lemma cfdot_aut_irr u phi i : '[cfAut u phi, cfAut u 'chi[G]_i] = u '[phi, 'chi_i]. Proof. exact: cfdot_aut_char (irr_char i). Qed. Lemma cfAut_irr u chi : (cfAut u chi \in irr G) = (chi \in irr G). Proof. rewrite !irrEchar cfAut_char; apply/andb_id2l=> /cfdot_aut_char->. exact: fmorph_eq1. Qed. Lemma cfConjC_irr i : (('chi_i)^*)%CF \in irr G. Proof. by rewrite cfAut_irr mem_irr. Qed. Lemma irr_aut_closed u : cfAut_closed u (irr G). Proof. by move=> chi; rewrite /= cfAut_irr. Qed. Definition aut_Iirr u i := cfIirr (cfAut u 'chi[G]_i). Lemma aut_IirrE u i : 'chi_(aut_Iirr u i) = cfAut u 'chi_i. Proof. by rewrite cfIirrE ?cfAut_irr ?mem_irr. Qed. Definition conjC_Iirr := aut_Iirr conjC. Lemma conjC_IirrE i : 'chi[G]_(conjC_Iirr i) = ('chi_i)^*%CF. Proof. exact: aut_IirrE. Qed. Lemma conjC_IirrK : involutive conjC_Iirr. Proof. by move=> i; apply: irr_inj; rewrite !conjC_IirrE cfConjCK. Qed. Lemma aut_Iirr0 u : aut_Iirr u 0 = 0 :> Iirr G. Proof. by apply/irr_inj; rewrite aut_IirrE irr0 cfAut_cfun1. Qed. Lemma conjC_Iirr0 : conjC_Iirr 0 = 0 :> Iirr G. Proof. exact: aut_Iirr0. Qed. Lemma aut_Iirr_eq0 u i : (aut_Iirr u i == 0) = (i == 0). Proof. by rewrite -!irr_eq1 aut_IirrE cfAut_eq1. Qed. Lemma conjC_Iirr_eq0 i : (conjC_Iirr i == 0 :> Iirr G) = (i == 0). Proof. exact: aut_Iirr_eq0. Qed. Lemma aut_Iirr_inj u : injective (aut_Iirr u). Proof. by move=> i j eq_ij; apply/irr_inj/(cfAut_inj u); rewrite -!aut_IirrE eq_ij. Qed. End Aut. Arguments aut_Iirr_inj {gT G} u [i1 i2] : rename. Arguments conjC_IirrK {gT G} i : rename. Section Coset. Variable (gT : finGroupType). Implicit Types G H : {group gT}. Lemma cfQuo_char G H (chi : 'CF(G)) : chi \is a character -> (chi / H)%CF \is a character. Proof. move=> Nchi; without loss kerH: / H \subset cfker chi. move/contraNF=> IHchi; apply/wlog_neg=> N'chiH. suffices ->: (chi / H)%CF = (chi 1%g)%:A. by rewrite rpredZ_nat ?Cnat_char1 ?rpred1. by apply/cfunP=> x; rewrite cfunE cfun1E mulr_natr cfunElock IHchi. without loss nsHG: G chi Nchi kerH / H <| G. move=> IHchi; have nsHN := normalSG (subset_trans kerH (cfker_sub chi)). rewrite cfQuoInorm//; apply/cfRes_char/IHchi => //; first exact: cfRes_char. by apply: sub_cfker_Res => //; apply: normal_sub. have [rG Dchi] := char_reprP Nchi; rewrite Dchi cfker_repr in kerH. apply/char_reprP; exists (Representation (quo_repr kerH (normal_norm nsHG))). apply/cfun_inP=> _ /morphimP[x nHx Gx ->]; rewrite Dchi cfQuoE ?cfker_repr //=. by rewrite !cfunE Gx quo_repr_coset ?mem_quotient. Qed. Lemma cfQuo_lin_char G H (chi : 'CF(G)) : chi \is a linear_char -> (chi / H)%CF \is a linear_char. Proof. by case/andP=> Nchi; rewrite qualifE/= cfQuo_char ?cfQuo1. Qed. Lemma cfMod_char G H (chi : 'CF(G / H)) : chi \is a character -> (chi %% H)%CF \is a character. Proof. exact: cfMorph_char. Qed. Lemma cfMod_lin_char G H (chi : 'CF(G / H)) : chi \is a linear_char -> (chi %% H)%CF \is a linear_char. Proof. exact: cfMorph_lin_char. Qed. Lemma cfMod_charE G H (chi : 'CF(G / H)) : H <| G -> (chi %% H \is a character)%CF = (chi \is a character). Proof. by case/andP=> _; apply: cfMorph_charE. Qed. Lemma cfMod_lin_charE G H (chi : 'CF(G / H)) : H <| G -> (chi %% H \is a linear_char)%CF = (chi \is a linear_char). Proof. by case/andP=> _; apply: cfMorph_lin_charE. Qed. Lemma cfQuo_charE G H (chi : 'CF(G)) : H <| G -> H \subset cfker chi -> (chi / H \is a character)%CF = (chi \is a character). Proof. by move=> nsHG kerH; rewrite -cfMod_charE ?cfQuoK. Qed. Lemma cfQuo_lin_charE G H (chi : 'CF(G)) : H <| G -> H \subset cfker chi -> (chi / H \is a linear_char)%CF = (chi \is a linear_char). Proof. by move=> nsHG kerH; rewrite -cfMod_lin_charE ?cfQuoK. Qed. Lemma cfMod_irr G H chi : H <| G -> (chi %% H \in irr G)%CF = (chi \in irr (G / H)). Proof. by case/andP=> _; apply: cfMorph_irr. Qed. Definition mod_Iirr G H i := cfIirr ('chi[G / H]_i %% H)%CF. Lemma mod_Iirr0 G H : mod_Iirr (0 : Iirr (G / H)) = 0. Proof. exact: morph_Iirr0. Qed. Lemma mod_IirrE G H i : H <| G -> 'chi_(mod_Iirr i) = ('chi[G / H]_i %% H)%CF. Proof. by move=> nsHG; rewrite cfIirrE ?cfMod_irr ?mem_irr. Qed. Lemma mod_Iirr_eq0 G H i : H <| G -> (mod_Iirr i == 0) = (i == 0 :> Iirr (G / H)). Proof. by case/andP=> _ /morph_Iirr_eq0->. Qed. Lemma cfQuo_irr G H chi : H <| G -> H \subset cfker chi -> ((chi / H)%CF \in irr (G / H)) = (chi \in irr G). Proof. by move=> nsHG kerH; rewrite -cfMod_irr ?cfQuoK. Qed. Definition quo_Iirr G H i := cfIirr ('chi[G]_i / H)%CF. Lemma quo_Iirr0 G H : quo_Iirr H (0 : Iirr G) = 0. Proof. by rewrite /quo_Iirr irr0 cfQuo_cfun1 -irr0 irrK. Qed. Lemma quo_IirrE G H i : H <| G -> H \subset cfker 'chi[G]_i -> 'chi_(quo_Iirr H i) = ('chi_i / H)%CF. Proof. by move=> nsHG kerH; rewrite cfIirrE ?cfQuo_irr ?mem_irr. Qed. Lemma quo_Iirr_eq0 G H i : H <| G -> H \subset cfker 'chi[G]_i -> (quo_Iirr H i == 0) = (i == 0). Proof. by move=> nsHG kerH; rewrite -!irr_eq1 quo_IirrE ?cfQuo_eq1. Qed. Lemma mod_IirrK G H : H <| G -> cancel (@mod_Iirr G H) (@quo_Iirr G H). Proof. move=> nsHG i; apply: irr_inj. by rewrite quo_IirrE ?mod_IirrE ?cfker_mod // cfModK. Qed. Lemma quo_IirrK G H i : H <| G -> H \subset cfker 'chi[G]_i -> mod_Iirr (quo_Iirr H i) = i. Proof. by move=> nsHG kerH; apply: irr_inj; rewrite mod_IirrE ?quo_IirrE ?cfQuoK. Qed. Lemma quo_IirrKeq G H : H <| G -> forall i, (mod_Iirr (quo_Iirr H i) == i) = (H \subset cfker 'chi[G]_i). Proof. move=> nsHG i; apply/eqP/idP=> [<- | ]; last exact: quo_IirrK. by rewrite mod_IirrE ?cfker_mod. Qed. Lemma mod_Iirr_bij H G : H <| G -> {on [pred i | H \subset cfker 'chi_i], bijective (@mod_Iirr G H)}. Proof. by exists (quo_Iirr H) => [i _ | i]; [apply: mod_IirrK | apply: quo_IirrK]. Qed. Lemma sum_norm_irr_quo H G x : x \in G -> H <| G -> \sum_i `|'chi[G / H]_i (coset H x)| ^+ 2 = \sum_(i | H \subset cfker 'chi_i) `|'chi[G]_i x| ^+ 2. Proof. move=> Gx nsHG; rewrite (reindex _ (mod_Iirr_bij nsHG)) /=. by apply/esym/eq_big=> [i | i _]; rewrite mod_IirrE ?cfker_mod ?cfModE. Qed. Lemma cap_cfker_normal G H : H <| G -> \bigcap_(i | H \subset cfker 'chi[G]_i) (cfker 'chi_i) = H. Proof. move=> nsHG; have [sHG nHG] := andP nsHG; set lhs := \bigcap_(i | _) _. have nHlhs: lhs \subset 'N(H) by rewrite (bigcap_min 0) ?cfker_irr0. apply/esym/eqP; rewrite eqEsubset (introT bigcapsP) //= -quotient_sub1 //. rewrite -(TI_cfker_irr (G / H)); apply/bigcapsP=> i _. rewrite sub_quotient_pre // (bigcap_min (mod_Iirr i)) ?mod_IirrE ?cfker_mod //. by rewrite cfker_morph ?subsetIr. Qed. Lemma cfker_reg_quo G H : H <| G -> cfker (cfReg (G / H)%g %% H) = H. Proof. move=> nsHG; have [sHG nHG] := andP nsHG. apply/setP=> x; rewrite cfkerEchar ?cfMod_char ?cfReg_char //. rewrite -[in RHS in _ = RHS](setIidPr sHG) !inE; apply: andb_id2l => Gx. rewrite !cfModE // !cfRegE // morph1 eqxx. rewrite (sameP eqP (kerP _ (subsetP nHG x Gx))) ker_coset. by rewrite -!mulrnA eqr_nat eqn_pmul2l ?cardG_gt0 // (can_eq oddb) eqb_id. Qed. End Coset. Section DerivedGroup. Variable gT : finGroupType. Implicit Types G H : {group gT}. Lemma lin_irr_der1 G i : ('chi_i \is a linear_char) = (G^`(1)%g \subset cfker 'chi[G]_i). Proof. apply/idP/idP=> [|sG'K]; first exact: lin_char_der1. have nsG'G: G^`(1) <| G := der_normal 1 G. rewrite qualifE/= irr_char -[i](quo_IirrK nsG'G) // mod_IirrE //=. by rewrite cfModE // morph1 lin_char1 //; apply/char_abelianP/der_abelian. Qed. Lemma subGcfker G i : (G \subset cfker 'chi[G]_i) = (i == 0). Proof. rewrite -irr_eq1; apply/idP/eqP=> [chiG1 | ->]; last by rewrite cfker_cfun1. apply/cfun_inP=> x Gx; rewrite cfun1E Gx cfker1 ?(subsetP chiG1) ?lin_char1 //. by rewrite lin_irr_der1 (subset_trans (der_sub 1 G)). Qed. Lemma irr_prime_injP G i : prime #|G| -> reflect {in G &, injective 'chi[G]_i} (i != 0). Proof. move=> pr_G; apply: (iffP idP) => [nz_i | inj_chi]. apply: fful_lin_char_inj (irr_prime_lin i pr_G) _. by rewrite cfaithfulE -(setIidPr (cfker_sub _)) prime_TIg // subGcfker. have /trivgPn[x Gx ntx]: G :!=: 1%g by rewrite -cardG_gt1 prime_gt1. apply: contraNneq ntx => i0; apply/eqP/inj_chi=> //. by rewrite i0 irr0 !cfun1E Gx group1. Qed. (* This is Isaacs (2.23)(a). *) Lemma cap_cfker_lin_irr G : \bigcap_(i | 'chi[G]_i \is a linear_char) (cfker 'chi_i) = G^`(1)%g. Proof. rewrite -(cap_cfker_normal (der_normal 1 G)). by apply: eq_bigl => i; rewrite lin_irr_der1. Qed. (* This is Isaacs (2.23)(b) *) Lemma card_lin_irr G : #|[pred i | 'chi[G]_i \is a linear_char]| = #|G : G^`(1)%g|. Proof. have nsG'G := der_normal 1 G; rewrite (eq_card (@lin_irr_der1 G)). rewrite -(on_card_preimset (mod_Iirr_bij nsG'G)). rewrite -card_quotient ?normal_norm //. move: (der_abelian 0 G); rewrite card_classes_abelian; move/eqP<-. rewrite -NirrE -[RHS]card_ord. by apply: eq_card => i; rewrite !inE mod_IirrE ?cfker_mod. (* Alternative: use the equivalent result in modular representation theory transitivity #|@socle_of_Iirr _ G @^-1: linear_irr _|; last first. rewrite (on_card_preimset (socle_of_Iirr_bij _)). by rewrite card_linear_irr ?algC'G; last apply: groupC. by apply: eq_card => i; rewrite !inE /lin_char irr_char irr1_degree -eqC_nat. *) Qed. (* A non-trivial solvable group has a nonprincipal linear character. *) Lemma solvable_has_lin_char G : G :!=: 1%g -> solvable G -> exists2 i, 'chi[G]_i \is a linear_char & 'chi_i != 1. Proof. move=> ntG solG. suff /subsetPn[i]: ~~ ([pred i | 'chi[G]_i \is a linear_char] \subset pred1 0). by rewrite !inE -(inj_eq irr_inj) irr0; exists i. rewrite (contra (@subset_leq_card _ _ _)) // -ltnNge card1 card_lin_irr. by rewrite indexg_gt1 proper_subn // (sol_der1_proper solG). Qed. (* A combinatorial group isommorphic to the linear characters. *) Lemma lin_char_group G : {linG : finGroupType & {cF : linG -> 'CF(G) | [/\ injective cF, #|linG| = #|G : G^`(1)|, forall u, cF u \is a linear_char & forall phi, phi \is a linear_char -> exists u, phi = cF u] & [/\ cF 1%g = 1%R, {morph cF : u v / (u * v)%g >-> (u * v)%R}, forall k, {morph cF : u / (u^+ k)%g >-> u ^+ k}, {morph cF: u / u^-1%g >-> u^-1%CF} & {mono cF: u / #[u]%g >-> #[u]%CF} ]}}. Proof. pose linT := {i : Iirr G | 'chi_i \is a linear_char}. pose cF (u : linT) := 'chi_(sval u). have cFlin u: cF u \is a linear_char := svalP u. have cFinj: injective cF := inj_comp irr_inj val_inj. have inT xi : xi \is a linear_char -> {u | cF u = xi}. move=> lin_xi; have /irrP/sig_eqW[i Dxi] := lin_char_irr lin_xi. by apply: (exist _ (Sub i _)) => //; rewrite -Dxi. have [one cFone] := inT 1 (rpred1 _). pose inv u := sval (inT _ (rpredVr (cFlin u))). pose mul u v := sval (inT _ (rpredM (cFlin u) (cFlin v))). have cFmul u v: cF (mul u v) = cF u * cF v := svalP (inT _ _). have cFinv u: cF (inv u) = (cF u)^-1 := svalP (inT _ _). have mulA: associative mul by move=> u v w; apply: cFinj; rewrite !cFmul mulrA. have mul1: left_id one mul by move=> u; apply: cFinj; rewrite cFmul cFone mul1r. have mulV: left_inverse one inv mul. by move=> u; apply: cFinj; rewrite cFmul cFinv cFone mulVr ?lin_char_unitr. pose imA := isMulGroup.Build linT mulA mul1 mulV. pose linG : finGroupType := HB.pack linT imA. have cFexp k: {morph cF : u / ((u : linG) ^+ k)%g >-> u ^+ k}. by move=> u; elim: k => // k IHk; rewrite expgS exprS cFmul IHk. do [exists linG, cF; split=> //] => [|xi /inT[u <-]|u]; first 2 [by exists u]. have inj_cFI: injective (cfIirr \o cF). apply: can_inj (insubd one) _ => u; apply: val_inj. by rewrite insubdK /= ?irrK //; apply: cFlin. rewrite -(card_image inj_cFI) -card_lin_irr. apply/eq_card=> i /[1!inE]; apply/codomP/idP=> [[u ->] | /inT[u Du]]. by rewrite /= irrK; apply: cFlin. by exists u; apply: irr_inj; rewrite /= irrK. apply/eqP; rewrite eqn_dvd; apply/andP; split. by rewrite dvdn_cforder; rewrite -cFexp expg_order cFone. by rewrite order_dvdn -(inj_eq cFinj) cFone cFexp exp_cforder. Qed. Lemma cfExp_prime_transitive G (i j : Iirr G) : prime #|G| -> i != 0 -> j != 0 -> exists2 k, coprime k #['chi_i]%CF & 'chi_j = 'chi_i ^+ k. Proof. set p := #|G| => pr_p nz_i nz_j; have cycG := prime_cyclic pr_p. have [L [h [injh oL Lh h_ontoL]] [h1 hM hX _ o_h]] := lin_char_group G. rewrite (derG1P (cyclic_abelian cycG)) indexg1 -/p in oL. have /fin_all_exists[h' h'K] := h_ontoL _ (irr_cyclic_lin _ cycG). have o_h' k: k != 0 -> #[h' k] = p. rewrite -cforder_irr_eq1 h'K -o_h => nt_h'k. by apply/prime_nt_dvdP=> //; rewrite cforder_lin_char_dvdG. have{oL} genL k: k != 0 -> generator [set: L] (h' k). move=> /o_h' o_h'k; rewrite /generator eq_sym eqEcard subsetT /=. by rewrite cardsT oL -o_h'k. have [/(_ =P <[_]>)-> gen_j] := (genL i nz_i, genL j nz_j). have /cycleP[k Dj] := cycle_generator gen_j. by rewrite !h'K Dj o_h hX generator_coprime coprime_sym in gen_j *; exists k. Qed. (* This is Isaacs (2.24). *) Lemma card_subcent1_coset G H x : x \in G -> H <| G -> (#|'C_(G / H)[coset H x]| <= #|'C_G[x]|)%N. Proof. move=> Gx nsHG; rewrite -leC_nat. move: (second_orthogonality_relation x Gx); rewrite mulrb class_refl => <-. have GHx: coset H x \in (G / H)%g by apply: mem_quotient. move: (second_orthogonality_relation (coset H x) GHx). rewrite mulrb class_refl => <-. rewrite -2!(eq_bigr _ (fun _ _ => normCK _)) sum_norm_irr_quo // -subr_ge0. rewrite (bigID (fun i => H \subset cfker 'chi[G]_i)) //= [X in X + _]addrC addrK. by apply: sumr_ge0 => i _; rewrite normCK mul_conjC_ge0. Qed. End DerivedGroup. Arguments irr_prime_injP {gT G i}. (* Determinant characters and determinential order. *) Section DetRepr. Variables (gT : finGroupType) (G : {group gT}). Variables (n : nat) (rG : mx_representation algC G n). Definition det_repr_mx x : 'M_1 := (\det (rG x))%:M. Fact det_is_repr : mx_repr G det_repr_mx. Proof. split=> [|g h Gg Gh]; first by rewrite /det_repr_mx repr_mx1 det1. by rewrite /det_repr_mx repr_mxM // det_mulmx !mulmxE scalar_mxM. Qed. Canonical det_repr := MxRepresentation det_is_repr. Definition detRepr := cfRepr det_repr. Lemma detRepr_lin_char : detRepr \is a linear_char. Proof. by rewrite qualifE/= cfRepr_char cfunE group1 repr_mx1 mxtrace1 mulr1n /=. Qed. End DetRepr. HB.lock Definition cfDet (gT : finGroupType) (G : {group gT}) phi := \prod_i detRepr 'Chi_i ^+ Num.truncn '[phi, 'chi[G]_i]. Canonical cfDet_unlockable := Unlockable cfDet.unlock. Section DetOrder. Variables (gT : finGroupType) (G : {group gT}). Local Notation cfDet := (@cfDet gT G). Lemma cfDet_lin_char phi : cfDet phi \is a linear_char. Proof. rewrite unlock; apply: rpred_prod => i _; apply: rpredX. exact: detRepr_lin_char. Qed. Lemma cfDetD : {in character &, {morph cfDet : phi psi / phi + psi >-> phi * psi}}. Proof. move=> phi psi Nphi Npsi; rewrite unlock /= -big_split; apply: eq_bigr => i _ /=. by rewrite -exprD cfdotDl truncnD ?nnegrE ?natr_ge0 // Cnat_cfdot_char_irr. Qed. Lemma cfDet0 : cfDet 0 = 1. Proof. by rewrite unlock big1 // => i _; rewrite cfdot0l truncn0. Qed. Lemma cfDetMn k : {in character, {morph cfDet : phi / phi *+ k >-> phi ^+ k}}. Proof. move=> phi Nphi; elim: k => [|k IHk]; rewrite ?cfDet0 // mulrS exprS -{}IHk. by rewrite cfDetD ?rpredMn. Qed. Lemma cfDetRepr n rG : cfDet (cfRepr rG) = @detRepr _ _ n rG. Proof. transitivity (\prod_W detRepr (socle_repr W) ^+ standard_irr_coef rG W). rewrite (reindex _ (socle_of_Iirr_bij _)) unlock /=. apply: eq_bigr => i _; congr (_ ^+ _). rewrite (cfRepr_sim (mx_rsim_standard rG)) cfRepr_standard. rewrite cfdot_suml (bigD1 i) ?big1 //= => [|j i'j]; last first. by rewrite cfdotZl cfdot_irr (negPf i'j) mulr0. by rewrite cfdotZl cfnorm_irr mulr1 addr0 natrK. apply/cfun_inP=> x Gx; rewrite prod_cfunE //. transitivity (detRepr (standard_grepr rG) x); last first. rewrite !cfunE Gx !trace_mx11 !mxE eqxx !mulrb. case: (standard_grepr rG) (mx_rsim_standard rG) => /= n1 rG1 [B Dn1]. rewrite -{n1}Dn1 in rG1 B *; rewrite row_free_unit => uB rG_B. by rewrite -[rG x](mulmxK uB) rG_B // !det_mulmx mulrC -!det_mulmx mulKmx. rewrite /standard_grepr; elim/big_rec2: _ => [|W y _ _ ->]. by rewrite cfunE trace_mx11 mxE Gx det1. rewrite !cfunE Gx /= !{1}trace_mx11 !{1}mxE det_ublock; congr (_ * _). rewrite exp_cfunE //; elim: (standard_irr_coef rG W) => /= [|k IHk]. by rewrite /muln_grepr big_ord0 det1. rewrite exprS /muln_grepr big_ord_recl det_ublock -IHk; congr (_ * _). by rewrite cfunE trace_mx11 mxE Gx. Qed. Lemma cfDet_id xi : xi \is a linear_char -> cfDet xi = xi. Proof. move=> lin_xi; have /irrP[i Dxi] := lin_char_irr lin_xi. apply/cfun_inP=> x Gx; rewrite Dxi -irrRepr cfDetRepr !cfunE trace_mx11 mxE. move: lin_xi (_ x) => /andP[_]; rewrite Dxi irr1_degree pnatr_eq1 => /eqP-> X. by rewrite {1}[X]mx11_scalar det_scalar1 trace_mx11. Qed. Definition cfDet_order phi := #[cfDet phi]%CF. Definition cfDet_order_lin xi : xi \is a linear_char -> cfDet_order xi = #[xi]%CF. Proof. by rewrite /cfDet_order => /cfDet_id->. Qed. Definition cfDet_order_dvdG phi : cfDet_order phi %| #|G|. Proof. by rewrite cforder_lin_char_dvdG ?cfDet_lin_char. Qed. End DetOrder. Notation "''o' ( phi )" := (cfDet_order phi) (format "''o' ( phi )") : cfun_scope. Section CfDetOps. Implicit Types gT aT rT : finGroupType. Lemma cfDetRes gT (G H : {group gT}) phi : phi \is a character -> cfDet ('Res[H, G] phi) = 'Res (cfDet phi). Proof. move=> Nphi; have [sGH | not_sHG] := boolP (H \subset G); last first. have /natrP[n Dphi1] := Cnat_char1 Nphi. rewrite !cfResEout // Dphi1 lin_char1 ?cfDet_lin_char // scale1r. by rewrite scaler_nat cfDetMn ?cfDet_id ?rpred1 // expr1n. have [rG ->] := char_reprP Nphi; rewrite !(=^~ cfRepr_sub, cfDetRepr) //. apply: cfRepr_sim; exists 1%:M; rewrite ?row_free_unit ?unitmx1 // => x Hx. by rewrite mulmx1 mul1mx. Qed. Lemma cfDetMorph aT rT (D G : {group aT}) (f : {morphism D >-> rT}) (phi : 'CF(f @* G)) : phi \is a character -> cfDet (cfMorph phi) = cfMorph (cfDet phi). Proof. move=> Nphi; have [sGD | not_sGD] := boolP (G \subset D); last first. have /natrP[n Dphi1] := Cnat_char1 Nphi. rewrite !cfMorphEout // Dphi1 lin_char1 ?cfDet_lin_char // scale1r. by rewrite scaler_nat cfDetMn ?cfDet_id ?rpred1 // expr1n. have [rG ->] := char_reprP Nphi; rewrite !(=^~ cfRepr_morphim, cfDetRepr) //. apply: cfRepr_sim; exists 1%:M; rewrite ?row_free_unit ?unitmx1 // => x Hx. by rewrite mulmx1 mul1mx. Qed. Lemma cfDetIsom aT rT (G : {group aT}) (R : {group rT}) (f : {morphism G >-> rT}) (isoGR : isom G R f) phi : cfDet (cfIsom isoGR phi) = cfIsom isoGR (cfDet phi). Proof. rewrite unlock rmorph_prod (reindex (isom_Iirr isoGR)); last first. by exists (isom_Iirr (isom_sym isoGR)) => i; rewrite ?isom_IirrK ?isom_IirrKV. apply: eq_bigr=> i; rewrite -!cfDetRepr !irrRepr isom_IirrE rmorphXn cfIsom_iso. by rewrite /= ![in cfIsom _]unlock cfDetMorph ?cfRes_char ?cfDetRes ?irr_char. Qed. Lemma cfDet_mul_lin gT (G : {group gT}) (lambda phi : 'CF(G)) : lambda \is a linear_char -> phi \is a character -> cfDet (lambda * phi) = lambda ^+ Num.truncn (phi 1%g) * cfDet phi. Proof. case/andP=> /char_reprP[[n1 rG1] ->] /= n1_1 /char_reprP[[n2 rG2] ->] /=. do [rewrite !cfRepr1 pnatr_eq1 natrK; move/eqP] in n1_1 *. rewrite {n1}n1_1 in rG1 *; rewrite cfRepr_prod cfDetRepr. apply/cfun_inP=> x Gx; rewrite !cfunE cfDetRepr cfunE Gx !mulrb !trace_mx11. rewrite !mxE prod_repr_lin ?mulrb //=; case: _ / (esym _); rewrite detZ. congr (_ * _); case: {rG2}n2 => [|n2]; first by rewrite cfun1E Gx. by rewrite expS_cfunE //= cfunE Gx trace_mx11. Qed. End CfDetOps. Definition cfcenter (gT : finGroupType) (G : {set gT}) (phi : 'CF(G)) := if phi \is a character then [set g in G | `|phi g| == phi 1%g] else cfker phi. Notation "''Z' ( phi )" := (cfcenter phi) : cfun_scope. Section Center. Variable (gT : finGroupType) (G : {group gT}). Implicit Types (phi chi : 'CF(G)) (H : {group gT}). (* This is Isaacs (2.27)(a). *) Lemma cfcenter_repr n (rG : mx_representation algC G n) : 'Z(cfRepr rG)%CF = rcenter rG. Proof. rewrite /cfcenter /rcenter cfRepr_char /=. apply/setP=> x /[!inE]; apply/andb_id2l=> Gx. apply/eqP/is_scalar_mxP=> [|[c rG_c]]. by case/max_cfRepr_norm_scalar=> // c; exists c. rewrite -(sqrCK (char1_ge0 (cfRepr_char rG))) normC_def; congr (sqrtC _). rewrite expr2 -{2}(mulgV x) -char_inv ?cfRepr_char ?cfunE ?groupM ?groupV //. rewrite Gx group1 repr_mx1 repr_mxM ?repr_mxV ?groupV // !mulrb rG_c. by rewrite invmx_scalar -scalar_mxM !mxtrace_scalar mulrnAr mulrnAl mulr_natl. Qed. (* This is part of Isaacs (2.27)(b). *) Fact cfcenter_group_set phi : group_set ('Z(phi))%CF. Proof. have [[rG ->] | /negbTE notNphi] := altP (@char_reprP _ G phi). by rewrite cfcenter_repr groupP. by rewrite /cfcenter notNphi groupP. Qed. Canonical cfcenter_group f := Group (cfcenter_group_set f). Lemma char_cfcenterE chi x : chi \is a character -> x \in G -> (x \in ('Z(chi))%CF) = (`|chi x| == chi 1%g). Proof. by move=> Nchi Gx; rewrite /cfcenter Nchi inE Gx. Qed. Lemma irr_cfcenterE i x : x \in G -> (x \in 'Z('chi[G]_i)%CF) = (`|'chi_i x| == 'chi_i 1%g). Proof. by move/char_cfcenterE->; rewrite ?irr_char. Qed. (* This is also Isaacs (2.27)(b). *) Lemma cfcenter_sub phi : ('Z(phi))%CF \subset G. Proof. by rewrite /cfcenter /cfker !setIdE -fun_if subsetIl. Qed. Lemma cfker_center_normal phi : cfker phi <| 'Z(phi)%CF. Proof. apply: normalS (cfcenter_sub phi) (cfker_normal phi). rewrite /= /cfcenter; case: ifP => // Hphi; rewrite cfkerEchar //. apply/subsetP=> x /[!inE] /andP[-> /eqP->] /=. by rewrite ger0_norm ?char1_ge0. Qed. Lemma cfcenter_normal phi : 'Z(phi)%CF <| G. Proof. have [[rG ->] | /negbTE notNphi] := altP (@char_reprP _ _ phi). by rewrite cfcenter_repr rcenter_normal. by rewrite /cfcenter notNphi cfker_normal. Qed. (* This is Isaacs (2.27)(c). *) Lemma cfcenter_Res chi : exists2 chi1, chi1 \is a linear_char & 'Res['Z(chi)%CF] chi = chi 1%g *: chi1. Proof. have [[rG ->] | /negbTE notNphi] := altP (@char_reprP _ _ chi); last first. exists 1; first exact: cfun1_lin_char. rewrite /cfcenter notNphi; apply/cfun_inP=> x Kx. by rewrite cfunE cfun1E Kx mulr1 cfResE ?cfker_sub // cfker1. rewrite cfcenter_repr -(cfRepr_sub _ (normal_sub (rcenter_normal _))). case: rG => [[|n] rG] /=; rewrite cfRepr1. exists 1; first exact: cfun1_lin_char. by apply/cfun_inP=> x Zx; rewrite scale0r !cfunE flatmx0 raddf0 Zx. pose rZmx x := ((rG x 0 0)%:M : 'M_(1,1)). have rZmxP: mx_repr [group of rcenter rG] rZmx. split=> [|x y]; first by rewrite /rZmx repr_mx1 mxE eqxx. move=> /setIdP[Gx /is_scalar_mxP[a rGx]] /setIdP[Gy /is_scalar_mxP[b rGy]]. by rewrite /rZmx repr_mxM // rGx rGy -!scalar_mxM !mxE. exists (cfRepr (MxRepresentation rZmxP)). by rewrite qualifE/= cfRepr_char cfRepr1 eqxx. apply/cfun_inP=> x Zx; rewrite !cfunE Zx /= /rZmx mulr_natl. by case/setIdP: Zx => Gx /is_scalar_mxP[a ->]; rewrite mxE !mxtrace_scalar. Qed. (* This is Isaacs (2.27)(d). *) Lemma cfcenter_cyclic chi : cyclic ('Z(chi)%CF / cfker chi)%g. Proof. case Nchi: (chi \is a character); last first. by rewrite /cfcenter Nchi trivg_quotient cyclic1. have [-> | nz_chi] := eqVneq chi 0. rewrite quotientS1 ?cyclic1 //= /cfcenter cfkerEchar ?cfun0_char //. by apply/subsetP=> x /setIdP[Gx _]; rewrite inE Gx /= !cfunE. have [xi Lxi def_chi] := cfcenter_Res chi. set Z := ('Z(_))%CF in xi Lxi def_chi *. have sZG: Z \subset G by apply: cfcenter_sub. have ->: cfker chi = cfker xi. rewrite -(setIidPr (normal_sub (cfker_center_normal _))) -/Z. rewrite !cfkerEchar // ?lin_charW //= -/Z. apply/setP=> x /[!inE]; apply: andb_id2l => Zx. rewrite (subsetP sZG) //= -!(cfResE chi sZG) ?group1 // def_chi !cfunE. by rewrite (inj_eq (mulfI _)) ?char1_eq0. have: abelian (Z / cfker xi) by rewrite sub_der1_abelian ?lin_char_der1. have /irr_reprP[rG irrG ->] := lin_char_irr Lxi; rewrite cfker_repr. apply: mx_faithful_irr_abelian_cyclic (kquo_mx_faithful rG) _. exact/quo_mx_irr. Qed. (* This is Isaacs (2.27)(e). *) Lemma cfcenter_subset_center chi : ('Z(chi)%CF / cfker chi)%g \subset 'Z(G / cfker chi)%g. Proof. case Nchi: (chi \is a character); last first. by rewrite /cfcenter Nchi trivg_quotient sub1G. rewrite subsetI quotientS ?cfcenter_sub // quotient_cents2r //=. case/char_reprP: Nchi => rG ->{chi}; rewrite cfker_repr cfcenter_repr gen_subG. apply/subsetP=> _ /imset2P[x y /setIdP[Gx /is_scalar_mxP[c rGx]] Gy ->]. rewrite inE groupR //= !repr_mxM ?groupM ?groupV // rGx -(scalar_mxC c) -rGx. by rewrite !mulmxA !repr_mxKV. Qed. (* This is Isaacs (2.27)(f). *) Lemma cfcenter_eq_center (i : Iirr G) : ('Z('chi_i)%CF / cfker 'chi_i)%g = 'Z(G / cfker 'chi_i)%g. Proof. apply/eqP; rewrite eqEsubset; rewrite cfcenter_subset_center ?irr_char //. apply/subsetP=> _ /setIP[/morphimP[x /= _ Gx ->] cGx]; rewrite mem_quotient //=. rewrite -irrRepr cfker_repr cfcenter_repr inE Gx in cGx *. apply: mx_abs_irr_cent_scalar 'Chi_i _ _ _; first exact/groupC/socle_irr. have nKG: G \subset 'N(rker 'Chi_i) by apply: rker_norm. (* GG -- locking here is critical to prevent Coq kernel divergence. *) apply/centgmxP=> y Gy; rewrite [eq]lock -2?(quo_repr_coset (subxx _) nKG) //. move: (quo_repr _ _) => rG; rewrite -2?repr_mxM ?mem_quotient // -lock. by rewrite (centP cGx) // mem_quotient. Qed. (* This is Isaacs (2.28). *) Lemma cap_cfcenter_irr : \bigcap_i 'Z('chi[G]_i)%CF = 'Z(G). Proof. apply/esym/eqP; rewrite eqEsubset (introT bigcapsP) /= => [|i _]; last first. rewrite -(quotientSGK _ (normal_sub (cfker_center_normal _))). by rewrite cfcenter_eq_center morphim_center. by rewrite subIset // normal_norm // cfker_normal. set Z := \bigcap_i _. have sZG: Z \subset G by rewrite (bigcap_min 0) ?cfcenter_sub. rewrite subsetI sZG (sameP commG1P trivgP) -(TI_cfker_irr G). apply/bigcapsP=> i _; have nKiG := normal_norm (cfker_normal 'chi_i). rewrite -quotient_cents2 ?(subset_trans sZG) //. rewrite (subset_trans (quotientS _ (bigcap_inf i _))) //. by rewrite cfcenter_eq_center subsetIr. Qed. (* This is Isaacs (2.29). *) Lemma cfnorm_Res_leif H phi : H \subset G -> '['Res[H] phi] <= #|G : H|%:R * '[phi] ?= iff (phi \in 'CF(G, H)). Proof. move=> sHG; rewrite cfun_onE mulrCA natf_indexg // -mulrA mulKf ?neq0CG //. rewrite (big_setID H) (setIidPr sHG) /= addrC. rewrite (mono_leif (ler_pM2l _)) ?invr_gt0 ?gt0CG // -leifBLR -sumrB. rewrite big1 => [|x Hx]; last by rewrite !cfResE ?subrr. have ->: (support phi \subset H) = (G :\: H \subset [set x | phi x == 0]). rewrite subDset setUC -subDset; apply: eq_subset => x. by rewrite !inE (andb_idr (contraR _)) // => /cfun0->. rewrite (sameP subsetP forall_inP); apply: leif_0_sum => x _. by rewrite !inE /<?=%R mul_conjC_ge0 eq_sym mul_conjC_eq0. Qed. (* This is Isaacs (2.30). *) Lemma irr1_bound (i : Iirr G) : ('chi_i 1%g) ^+ 2 <= #|G : 'Z('chi_i)%CF|%:R ?= iff ('chi_i \in 'CF(G, 'Z('chi_i)%CF)). Proof. congr (_ <= _ ?= iff _): (cfnorm_Res_leif 'chi_i (cfcenter_sub 'chi_i)). have [xi Lxi ->] := cfcenter_Res 'chi_i. have /irrP[j ->] := lin_char_irr Lxi; rewrite cfdotZl cfdotZr cfdot_irr eqxx. by rewrite mulr1 irr1_degree conjC_nat. by rewrite cfdot_irr eqxx mulr1. Qed. (* This is Isaacs (2.31). *) Lemma irr1_abelian_bound (i : Iirr G) : abelian (G / 'Z('chi_i)%CF) -> ('chi_i 1%g) ^+ 2 = #|G : 'Z('chi_i)%CF|%:R. Proof. move=> AbGc; apply/eqP; rewrite irr1_bound cfun_onE; apply/subsetP=> x nz_chi_x. have Gx: x \in G by apply: contraR nz_chi_x => /cfun0->. have nKx := subsetP (normal_norm (cfker_normal 'chi_i)) _ Gx. rewrite -(quotientGK (cfker_center_normal _)) inE nKx inE /=. rewrite cfcenter_eq_center inE mem_quotient //=. apply/centP=> _ /morphimP[y nKy Gy ->]; apply/commgP; rewrite -morphR //=. set z := [~ x, y]; rewrite coset_id //. have: z \in 'Z('chi_i)%CF. apply: subsetP (mem_commg Gx Gy). by rewrite der1_min // normal_norm ?cfcenter_normal. rewrite -irrRepr cfker_repr cfcenter_repr !inE in nz_chi_x *. case/andP=> Gz /is_scalar_mxP[c Chi_z]; rewrite Gz Chi_z mul1mx /=. apply/eqP; congr _%:M; apply: (mulIf nz_chi_x); rewrite mul1r. rewrite -{2}(cfunJ _ x Gy) conjg_mulR -/z !cfunE Gx groupM // !{1}mulrb. by rewrite repr_mxM // Chi_z mul_mx_scalar mxtraceZ. Qed. (* This is Isaacs (2.32)(a). *) Lemma irr_faithful_center i : cfaithful 'chi[G]_i -> cyclic 'Z(G). Proof. rewrite (isog_cyclic (isog_center (quotient1_isog G))) /=. by move/trivgP <-; rewrite -cfcenter_eq_center cfcenter_cyclic. Qed. Lemma cfcenter_fful_irr i : cfaithful 'chi[G]_i -> 'Z('chi_i)%CF = 'Z(G). Proof. move/trivgP=> Ki1; have:= cfcenter_eq_center i; rewrite {}Ki1. have inj1: 'injm (@coset gT 1%g) by rewrite ker_coset. by rewrite -injm_center; first apply: injm_morphim_inj; rewrite ?norms1. Qed. (* This is Isaacs (2.32)(b). *) Lemma pgroup_cyclic_faithful (p : nat) : p.-group G -> cyclic 'Z(G) -> exists i, cfaithful 'chi[G]_i. Proof. pose Z := 'Ohm_1('Z(G)) => pG cycZG; have nilG := pgroup_nil pG. have [-> | ntG] := eqsVneq G [1]; first by exists 0; apply: cfker_sub. have{pG} [[p_pr _ _] pZ] := (pgroup_pdiv pG ntG, pgroupS (center_sub G) pG). have ntZ: 'Z(G) != [1] by rewrite center_nil_eq1. have{pZ} oZ: #|Z| = p by apply: Ohm1_cyclic_pgroup_prime. apply/existsP; apply: contraR ntZ => /existsPn-not_ffulG. rewrite -Ohm1_eq1 -subG1 /= -/Z -(TI_cfker_irr G); apply/bigcapsP=> i _. rewrite prime_meetG ?oZ // setIC meet_Ohm1 // meet_center_nil ?cfker_normal //. by rewrite -subG1 not_ffulG. Qed. End Center. Section Induced. Variables (gT : finGroupType) (G H : {group gT}). Implicit Types (phi : 'CF(G)) (chi : 'CF(H)). Lemma cfInd_char chi : chi \is a character -> 'Ind[G] chi \is a character. Proof. move=> Nchi; apply/forallP=> i; rewrite coord_cfdot -Frobenius_reciprocity //. by rewrite Cnat_cfdot_char ?cfRes_char ?irr_char. Qed. Lemma cfInd_eq0 chi : H \subset G -> chi \is a character -> ('Ind[G] chi == 0) = (chi == 0). Proof. move=> sHG Nchi; rewrite -!(char1_eq0) ?cfInd_char // cfInd1 //. by rewrite (mulrI_eq0 _ (mulfI _)) ?neq0CiG. Qed. Lemma Ind_irr_neq0 i : H \subset G -> 'Ind[G, H] 'chi_i != 0. Proof. by move/cfInd_eq0->; rewrite ?irr_neq0 ?irr_char. Qed. Definition Ind_Iirr (A B : {set gT}) i := cfIirr ('Ind[B, A] 'chi_i). Lemma constt_cfRes_irr i : {j | j \in irr_constt ('Res[H, G] 'chi_i)}. Proof. apply/sigW/neq0_has_constt/Res_irr_neq0. Qed. Lemma constt_cfInd_irr i : H \subset G -> {j | j \in irr_constt ('Ind[G, H] 'chi_i)}. Proof. by move=> sHG; apply/sigW/neq0_has_constt/Ind_irr_neq0. Qed. Lemma cfker_Res phi : H \subset G -> phi \is a character -> cfker ('Res[H] phi) = H :&: cfker phi. Proof. move=> sHG Nphi; apply/setP=> x; rewrite !cfkerEchar ?cfRes_char // !inE. by apply/andb_id2l=> Hx; rewrite (subsetP sHG) ?cfResE. Qed. (* This is Isaacs Lemma (5.11). *) Lemma cfker_Ind chi : H \subset G -> chi \is a character -> chi != 0 -> cfker ('Ind[G, H] chi) = gcore (cfker chi) G. Proof. move=> sHG Nchi nzchi; rewrite !cfker_nzcharE ?cfInd_char ?cfInd_eq0 //. apply/setP=> x; rewrite inE cfIndE // (can2_eq (mulVKf _) (mulKf _)) ?neq0CG //. rewrite cfInd1 // mulrA -natrM Lagrange // mulr_natl -sumr_const. apply/eqP/bigcapP=> [/normC_sum_upper ker_chiG_x y Gy | ker_chiG_x]. by rewrite mem_conjg inE ker_chiG_x ?groupV // => z _; apply: char1_ge_norm. by apply: eq_bigr => y /groupVr/ker_chiG_x; rewrite mem_conjgV inE => /eqP. Qed. Lemma cfker_Ind_irr i : H \subset G -> cfker ('Ind[G, H] 'chi_i) = gcore (cfker 'chi_i) G. Proof. by move/cfker_Ind->; rewrite ?irr_neq0 ?irr_char. Qed. End Induced. Arguments Ind_Iirr {gT A%_g} B%_g i%_R.
ContDiff.lean
/- Copyright (c) 2025 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Analysis.Calculus.ContDiff.Basic import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus /-! # Fundamental theorem of calculus for `C^1` functions We give versions of the second fundamental theorem of calculus under the strong assumption that the function is `C^1` on the interval. This is restrictive, but satisfied in many situations. -/ noncomputable section open MeasureTheory Set Filter Function Asymptotics open scoped Topology ENNReal Interval NNReal variable {ι 𝕜 E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] {f : ℝ → E} {a b : ℝ} namespace intervalIntegral variable [CompleteSpace E] /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is `C^1` on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_of_contDiffOn_Icc (h : ContDiffOn ℝ 1 f (Icc a b)) (hab : a ≤ b) : ∫ x in a..b, deriv f x = f b - f a := by rcases hab.eq_or_lt with rfl | h'ab · simp apply integral_eq_sub_of_hasDerivAt_of_le hab h.continuousOn · intro x hx apply DifferentiableAt.hasDerivAt apply ((h x ⟨hx.1.le, hx.2.le⟩).differentiableWithinAt le_rfl).differentiableAt exact Icc_mem_nhds hx.1 hx.2 · have := (h.derivWithin (m := 0) (uniqueDiffOn_Icc h'ab) (by simp)).continuousOn apply (this.intervalIntegrable_of_Icc (μ := volume) hab).congr simp only [hab, uIoc_of_le] rw [← restrict_Ioo_eq_restrict_Ioc] filter_upwards [self_mem_ae_restrict measurableSet_Ioo] with x hx exact derivWithin_of_mem_nhds (Icc_mem_nhds hx.1 hx.2) /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is `C^1` on `[a, b]`, then `∫ y in a..b, derivWithin f (Icc a b) y` equals `f b - f a`. -/ theorem integral_derivWithin_Icc_of_contDiffOn_Icc (h : ContDiffOn ℝ 1 f (Icc a b)) (hab : a ≤ b) : ∫ x in a..b, derivWithin f (Icc a b) x = f b - f a := by rw [← integral_deriv_of_contDiffOn_Icc h hab] rw [integral_of_le hab, integral_of_le hab] apply MeasureTheory.integral_congr_ae rw [← restrict_Ioo_eq_restrict_Ioc] filter_upwards [self_mem_ae_restrict measurableSet_Ioo] with x hx exact derivWithin_of_mem_nhds (Icc_mem_nhds hx.1 hx.2) /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is `C^1` on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_of_contDiffOn_uIcc (h : ContDiffOn ℝ 1 f (uIcc a b)) : ∫ x in a..b, deriv f x = f b - f a := by rcases le_or_gt a b with hab | hab · simp only [uIcc_of_le hab] at h exact integral_deriv_of_contDiffOn_Icc h hab · simp only [uIcc_of_ge hab.le] at h rw [integral_symm, integral_deriv_of_contDiffOn_Icc h hab.le] abel /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is `C^1` on `[a, b]`, then `∫ y in a..b, derivWithin f (uIcc a b) y` equals `f b - f a`. -/ theorem integral_derivWithin_uIcc_of_contDiffOn_uIcc (h : ContDiffOn ℝ 1 f (uIcc a b)) : ∫ x in a..b, derivWithin f (uIcc a b) x = f b - f a := by rcases le_or_gt a b with hab | hab · simp only [uIcc_of_le hab] at h ⊢ exact integral_derivWithin_Icc_of_contDiffOn_Icc h hab · simp only [uIcc_of_ge hab.le] at h ⊢ rw [integral_symm, integral_derivWithin_Icc_of_contDiffOn_Icc h hab.le] abel end intervalIntegral open intervalIntegral theorem enorm_sub_le_lintegral_deriv_of_contDiffOn_Icc (h : ContDiffOn ℝ 1 f (Icc a b)) (hab : a ≤ b) : ‖f b - f a‖ₑ ≤ ∫⁻ x in Icc a b, ‖deriv f x‖ₑ := by /- We want to write `f b - f a = ∫ x in Icc a b, deriv f x` and use the inequality between norm of integral and integral of norm. There is a small difficulty that this formula is not true when `E` is not complete, so we need to go first to the completion, and argue there. -/ let g := UniformSpace.Completion.toComplₗᵢ (𝕜 := ℝ) (E := E) have : ‖(g ∘ f) b - (g ∘ f) a‖ₑ = ‖f b - f a‖ₑ := by rw [← edist_eq_enorm_sub, Function.comp_def, g.isometry.edist_eq, edist_eq_enorm_sub] rw [← this, ← integral_deriv_of_contDiffOn_Icc (g.contDiff.comp_contDiffOn h) hab, integral_of_le hab, restrict_Ioc_eq_restrict_Icc] apply (enorm_integral_le_lintegral_enorm _).trans apply lintegral_mono_ae rw [← restrict_Ioo_eq_restrict_Icc] filter_upwards [self_mem_ae_restrict measurableSet_Ioo] with x hx rw [fderiv_comp_deriv]; rotate_left · exact (g.contDiff.differentiable le_rfl).differentiableAt · exact ((h x ⟨hx.1.le, hx.2.le⟩).contDiffAt (Icc_mem_nhds hx.1 hx.2)).differentiableAt le_rfl have : fderiv ℝ g (f x) = g.toContinuousLinearMap := g.toContinuousLinearMap.fderiv simp [this] theorem enorm_sub_le_lintegral_derivWithin_Icc_of_contDiffOn_Icc (h : ContDiffOn ℝ 1 f (Icc a b)) (hab : a ≤ b) : ‖f b - f a‖ₑ ≤ ∫⁻ x in Icc a b, ‖derivWithin f (Icc a b) x‖ₑ := by apply (enorm_sub_le_lintegral_deriv_of_contDiffOn_Icc h hab).trans_eq apply lintegral_congr_ae rw [← restrict_Ioo_eq_restrict_Icc] filter_upwards [self_mem_ae_restrict measurableSet_Ioo] with x hx rw [derivWithin_of_mem_nhds (Icc_mem_nhds hx.1 hx.2)]
Shrink.lean
/- Copyright (c) 2021 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.Algebra.Algebra.TransferInstance import Mathlib.Algebra.Ring.Shrink /-! # Transfer module and algebra structures from `α` to `Shrink α` -/ noncomputable section universe v variable {R α : Type*} [Small.{v} α] [CommSemiring R] namespace Shrink instance [Semiring α] [Algebra R α] : Algebra R (Shrink.{v} α) := (equivShrink α).symm.algebra _ variable (R α) in /-- Shrinking `α` to a smaller universe preserves algebra structure. -/ @[simps!] def algEquiv [Small.{v} α] [Semiring α] [Algebra R α] : Shrink.{v} α ≃ₐ[R] α := (equivShrink α).symm.algEquiv _ end Shrink /-- A small algebra is algebra equivalent to its small model. -/ @[deprecated Shrink.algEquiv (since := "2025-07-11")] def algEquivShrink (α β) [CommSemiring α] [Semiring β] [Algebra α β] [Small β] : β ≃ₐ[α] Shrink β := ((equivShrink β).symm.algEquiv α).symm
ssrnat.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From Corelib Require Import PosDef. From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype. #[export] Set Warnings "-overwriting-delimiting-key". (* remove above line when requiring Rocq >= 9.0 *) (******************************************************************************) (* A version of arithmetic on nat (natural numbers) that is better suited to *) (* small scale reflection than the Coq Arith library. It contains an *) (* extensive equational theory (including, e.g., the AGM inequality), as well *) (* as a congruence tactic. *) (* The following operations and notations are provided: *) (* *) (* successor and predecessor *) (* n.+1, n.+2, n.+3, n.+4 and n.-1, n.-2 *) (* this frees the names "S" and "pred" *) (* *) (* basic arithmetic *) (* m + n, m - n, m * n *) (* Important: m - n denotes TRUNCATED subtraction: m - n = 0 if m <= n. *) (* The definitions use simpl never to prevent undesirable computation *) (* during simplification, but remain compatible with the ones provided in *) (* the Coq.Init.Peano prelude. *) (* For computation, a module NatTrec rebinds all arithmetic notations *) (* to less convenient but also less inefficient tail-recursive functions; *) (* the auxiliary functions used by these versions are flagged with %Nrec. *) (* Also, there is support for input and output of large nat values. *) (* Num 3 082 241 inputs the number 3082241 *) (* [Num of n] outputs the value n *) (* There are coercions num >-> BinNat.N >-> nat; ssrnat rebinds the scope *) (* delimiter for BinNat.N to %num, as it uses the shorter %N for its own *) (* notations (Peano notations are flagged with %coq_nat). *) (* *) (* doubling, halving, and parity *) (* n.*2, n./2, odd n, uphalf n, with uphalf n = n.+1./2 *) (* bool coerces to nat so we can write, e.g., n = odd n + n./2.*2. *) (* *) (* iteration *) (* iter n f x0 == f ( .. (f x0)) *) (* iteri n g x0 == g n.-1 (g ... (g 0 x0)) *) (* iterop n op x x0 == op x (... op x x) (n x's) or x0 if n = 0 *) (* *) (* exponentiation, factorial *) (* m ^ n, n`! *) (* m ^ 1 is convertible to m, and m ^ 2 to m * m *) (* *) (* comparison *) (* m <= n, m < n, m >= n, m > n, m == n, m <= n <= p, etc., *) (* comparisons are BOOLEAN operators, and m == n is the generic eqType *) (* operation. *) (* Most compatibility lemmas are stated as boolean equalities; this keeps *) (* the size of the library down. All the inequalities refer to the same *) (* constant "leq"; in particular m < n is identical to m.+1 <= n. *) (* *) (* -> patterns for contextual rewriting: *) (* leqLHS := (X in (X <= _)%N)%pattern *) (* leqRHS := (X in (_ <= X)%N)%pattern *) (* ltnLHS := (X in (X < _)%N)%pattern *) (* ltnRHS := (X in (_ < X)%N)%pattern *) (* *) (* conditionally strict inequality `leqif' *) (* m <= n ?= iff condition == (m <= n) and ((m == n) = condition) *) (* This is actually a pair of boolean equalities, so rewriting with an *) (* `leqif' lemma can affect several kinds of comparison. The transitivity *) (* lemma for leqif aggregates the conditions, allowing for arguments of *) (* the form ``m <= n <= p <= m, so equality holds throughout''. *) (* *) (* maximum and minimum *) (* maxn m n, minn m n *) (* Note that maxn m n = m + (n - m), due to the truncating subtraction. *) (* Absolute difference (linear distance) between nats is defined in the int *) (* library (in the int.IntDist sublibrary), with the syntax `|m - n|. The *) (* '-' in this notation is the signed integer difference. *) (* *) (* countable choice *) (* ex_minn : forall P : pred nat, (exists n, P n) -> nat *) (* This returns the smallest n such that P n holds. *) (* ex_maxn : forall (P : pred nat) m, *) (* (exists n, P n) -> (forall n, P n -> n <= m) -> nat *) (* This returns the largest n such that P n holds (given an explicit upper *) (* bound). *) (* *) (* This file adds the following suffix conventions to those documented in *) (* ssrbool.v and eqtype.v: *) (* A (infix) -- conjunction, as in *) (* ltn_neqAle : (m < n) = (m != n) && (m <= n). *) (* B -- subtraction, as in subBn : (m - n) - p = m - (n + p). *) (* D -- addition, as in mulnDl : (m + n) * p = m * p + n * p. *) (* M -- multiplication, as in expnMn : (m * n) ^ p = m ^ p * n ^ p. *) (* p (prefix) -- positive, as in *) (* eqn_pmul2l : m > 0 -> (m * n1 == m * n2) = (n1 == n2). *) (* P -- greater than 1, as in *) (* ltn_Pmull : 1 < n -> 0 < m -> m < n * m. *) (* S -- successor, as in addSn : n.+1 + m = (n + m).+1. *) (* V (infix) -- disjunction, as in *) (* leq_eqVlt : (m <= n) = (m == n) || (m < n). *) (* X - exponentiation, as in lognX : logn p (m ^ n) = logn p m * n in *) (* file prime.v (the suffix is not used in this file). *) (* Suffixes that abbreviate operations (D, B, M and X) are used to abbreviate *) (* second-rank operations in equational lemma names that describe left-hand *) (* sides (e.g., mulnDl); they are not used to abbreviate the main operation *) (* of relational lemmas (e.g., leq_add2l). *) (* For the asymmetrical exponentiation operator expn (m ^ n) a right suffix *) (* indicates an operation on the exponent, e.g., expnM : m ^ (n1 * n2) = ...; *) (* a trailing "n" is used to indicate the left operand, e.g., *) (* expnMn : (m1 * m2) ^ n = ... The operands of other operators are selected *) (* using the l/r suffixes. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope coq_nat_scope. (* Disable Coq prelude hints to improve proof script robustness. *) #[global] Remove Hints plus_n_O plus_n_Sm mult_n_O mult_n_Sm : core. (* Declare legacy Arith operators in new scope. *) Delimit Scope coq_nat_scope with coq_nat. Notation "m + n" := (plus m n) : coq_nat_scope. Notation "m - n" := (minus m n) : coq_nat_scope. Notation "m * n" := (mult m n) : coq_nat_scope. Notation "m <= n" := (le m n) : coq_nat_scope. Notation "m < n" := (lt m n) : coq_nat_scope. Notation "m >= n" := (ge m n) : coq_nat_scope. Notation "m > n" := (gt m n) : coq_nat_scope. (* Rebind scope delimiters, reserving a scope for the "recursive", *) (* i.e., unprotected version of operators. *) Delimit Scope N_scope with num. #[warning="-hiding-delimiting-key"] Delimit Scope nat_scope with N. (* Postfix notation for the successor and predecessor functions. *) (* SSreflect uses "pred" for the generic predicate type, and S as *) (* a local bound variable. *) Notation succn := Datatypes.S. Notation predn := Peano.pred. Notation "n .+1" := (succn n) (left associativity, format "n .+1") : nat_scope. Notation "n .+2" := n.+1.+1 (left associativity, format "n .+2") : nat_scope. Notation "n .+3" := n.+2.+1 (left associativity, format "n .+3") : nat_scope. Notation "n .+4" := n.+2.+2 (left associativity, format "n .+4") : nat_scope. Notation "n .-1" := (predn n) (left associativity, format "n .-1") : nat_scope. Notation "n .-2" := n.-1.-1 (left associativity, format "n .-2") : nat_scope. Lemma succnK : cancel succn predn. Proof. by []. Qed. Lemma succn_inj : injective succn. Proof. by move=> n m []. Qed. (* Predeclare postfix doubling/halving operators. *) Reserved Notation "n .*2" (left associativity, format "n .*2"). Reserved Notation "n ./2" (left associativity, format "n ./2"). (* Canonical comparison and eqType for nat. *) Fixpoint eqn m n {struct m} := match m, n with | 0, 0 => true | m'.+1, n'.+1 => eqn m' n' | _, _ => false end. Lemma eqnP : Equality.axiom eqn. Proof. move=> n m; apply: (iffP idP) => [|<-]; last by elim n. by elim: n m => [|n IHn] [|m] //= /IHn->. Qed. HB.instance Definition _ := hasDecEq.Build nat eqnP. Arguments eqn !m !n. Arguments eqnP {x y}. Lemma eqnE : eqn = eq_op. Proof. by []. Qed. Lemma eqSS m n : (m.+1 == n.+1) = (m == n). Proof. by []. Qed. Lemma nat_irrelevance (x y : nat) (E E' : x = y) : E = E'. Proof. exact: eq_irrelevance. Qed. (* Protected addition, with a more systematic set of lemmas. *) Definition addn := plus. Arguments addn : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use addn instead.")] Definition addn_rec := addn. Notation "m + n" := (addn m n) : nat_scope. Lemma addnE : addn = plus. Proof. by []. Qed. Lemma plusE : plus = addn. Proof. by []. Qed. Lemma add0n : left_id 0 addn. Proof. by []. Qed. Lemma addSn m n : m.+1 + n = (m + n).+1. Proof. by []. Qed. Lemma add1n n : 1 + n = n.+1. Proof. by []. Qed. Lemma addn0 : right_id 0 addn. Proof. by move=> n; apply/eqP; elim: n. Qed. Lemma addnS m n : m + n.+1 = (m + n).+1. Proof. by apply/eqP; elim: m. Qed. Lemma addSnnS m n : m.+1 + n = m + n.+1. Proof. by rewrite addnS. Qed. Lemma addnCA : left_commutative addn. Proof. by move=> m n p; elim: m => //= m; rewrite addnS => <-. Qed. Lemma addnC : commutative addn. Proof. by move=> m n; rewrite -[n in LHS]addn0 addnCA addn0. Qed. Lemma addn1 n : n + 1 = n.+1. Proof. by rewrite addnC. Qed. Lemma addnA : associative addn. Proof. by move=> m n p; rewrite (addnC n) addnCA addnC. Qed. Lemma addnAC : right_commutative addn. Proof. by move=> m n p; rewrite -!addnA (addnC n). Qed. Lemma addnCAC m n p : m + n + p = p + n + m. Proof. by rewrite addnC addnA addnAC. Qed. Lemma addnACl m n p: m + n + p = n + (p + m). Proof. by rewrite (addnC m) addnC addnCA. Qed. Lemma addnACA : interchange addn addn. Proof. by move=> m n p q; rewrite -!addnA (addnCA n). Qed. Lemma addn_eq0 m n : (m + n == 0) = (m == 0) && (n == 0). Proof. by case: m; case: n. Qed. Lemma addn_eq1 m n : (m + n == 1) = ((m == 1) && (n == 0)) || ((m == 0) && (n == 1)). Proof. by case: m n => [|[|m]] [|[|n]]. Qed. Lemma eqn_add2l p m n : (p + m == p + n) = (m == n). Proof. by elim: p. Qed. Lemma eqn_add2r p m n : (m + p == n + p) = (m == n). Proof. by rewrite -!(addnC p) eqn_add2l. Qed. Lemma addnI : right_injective addn. Proof. by move=> p m n Heq; apply: eqP; rewrite -(eqn_add2l p) Heq eqxx. Qed. Lemma addIn : left_injective addn. Proof. move=> p m n; rewrite -!(addnC p); apply addnI. Qed. Lemma addn2 m : m + 2 = m.+2. Proof. by rewrite addnC. Qed. Lemma add2n m : 2 + m = m.+2. Proof. by []. Qed. Lemma addn3 m : m + 3 = m.+3. Proof. by rewrite addnC. Qed. Lemma add3n m : 3 + m = m.+3. Proof. by []. Qed. Lemma addn4 m : m + 4 = m.+4. Proof. by rewrite addnC. Qed. Lemma add4n m : 4 + m = m.+4. Proof. by []. Qed. (* Protected, structurally decreasing subtraction, and basic lemmas. *) (* Further properties depend on ordering conditions. *) Definition subn := minus. Arguments subn : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use subn instead.")] Definition subn_rec := subn. Notation "m - n" := (subn m n) : nat_scope. Lemma subnE : subn = minus. Proof. by []. Qed. Lemma minusE : minus = subn. Proof. by []. Qed. Lemma sub0n : left_zero 0 subn. Proof. by []. Qed. Lemma subn0 : right_id 0 subn. Proof. by case. Qed. Lemma subnn : self_inverse 0 subn. Proof. by elim. Qed. Lemma subSS n m : m.+1 - n.+1 = m - n. Proof. by []. Qed. Lemma subn1 n : n - 1 = n.-1. Proof. by case: n => [|[]]. Qed. Lemma subn2 n : (n - 2)%N = n.-2. Proof. by case: n => [|[|[]]]. Qed. Lemma subnDl p m n : (p + m) - (p + n) = m - n. Proof. by elim: p. Qed. Lemma subnDr p m n : (m + p) - (n + p) = m - n. Proof. by rewrite -!(addnC p) subnDl. Qed. Lemma addnK n : cancel (addn^~ n) (subn^~ n). Proof. by move=> m; rewrite (subnDr n m 0) subn0. Qed. Lemma addKn n : cancel (addn n) (subn^~ n). Proof. by move=> m; rewrite addnC addnK. Qed. Lemma subSnn n : n.+1 - n = 1. Proof. exact (addnK n 1). Qed. Lemma subnDA m n p : n - (m + p) = (n - m) - p. Proof. by elim: m n => [|m IHm] []. Qed. Lemma subnAC : right_commutative subn. Proof. by move=> m n p; rewrite -!subnDA addnC. Qed. Lemma subnS m n : m - n.+1 = (m - n).-1. Proof. by rewrite -addn1 subnDA subn1. Qed. Lemma subSKn m n : (m.+1 - n).-1 = m - n. Proof. by rewrite -subnS. Qed. (* Integer ordering, and its interaction with the other operations. *) Definition leq m n := m - n == 0. Notation "m <= n" := (leq m n) : nat_scope. Notation "m < n" := (m.+1 <= n) : nat_scope. Notation "m >= n" := (n <= m) (only parsing) : nat_scope. Notation "m > n" := (n < m) (only parsing) : nat_scope. (* For sorting, etc. *) Definition geq := [rel m n | m >= n]. Definition ltn := [rel m n | m < n]. Definition gtn := [rel m n | m > n]. Notation "m <= n <= p" := ((m <= n) && (n <= p)) : nat_scope. Notation "m < n <= p" := ((m < n) && (n <= p)) : nat_scope. Notation "m <= n < p" := ((m <= n) && (n < p)) : nat_scope. Notation "m < n < p" := ((m < n) && (n < p)) : nat_scope. Lemma ltnS m n : (m < n.+1) = (m <= n). Proof. by []. Qed. Lemma leq0n n : 0 <= n. Proof. by []. Qed. Lemma ltn0Sn n : 0 < n.+1. Proof. by []. Qed. Lemma ltn0 n : n < 0 = false. Proof. by []. Qed. Lemma leqnn n : n <= n. Proof. by elim: n. Qed. #[global] Hint Resolve leqnn : core. Lemma ltnSn n : n < n.+1. Proof. by []. Qed. Lemma eq_leq m n : m = n -> m <= n. Proof. by move->. Qed. Lemma leqnSn n : n <= n.+1. Proof. by elim: n. Qed. #[global] Hint Resolve leqnSn : core. Lemma leq_pred n : n.-1 <= n. Proof. by case: n => /=. Qed. Lemma leqSpred n : n <= n.-1.+1. Proof. by case: n => /=. Qed. Lemma ltn_predL n : (n.-1 < n) = (0 < n). Proof. by case: n => [//|n]; rewrite ltnSn. Qed. Lemma ltn_predRL m n : (m < n.-1) = (m.+1 < n). Proof. by case: n => [//|n]; rewrite succnK. Qed. Lemma ltn_predK m n : m < n -> n.-1.+1 = n. Proof. by case: n. Qed. Lemma prednK n : 0 < n -> n.-1.+1 = n. Proof. exact: ltn_predK. Qed. Lemma leqNgt m n : (m <= n) = ~~ (n < m). Proof. by elim: m n => [|m IHm] []. Qed. Lemma leqVgt m n : (m <= n) || (n < m). Proof. by rewrite leqNgt orNb. Qed. Lemma ltnNge m n : (m < n) = ~~ (n <= m). Proof. by rewrite leqNgt. Qed. Lemma ltnn n : n < n = false. Proof. by rewrite ltnNge leqnn. Qed. Lemma leqn0 n : (n <= 0) = (n == 0). Proof. by case: n. Qed. Lemma lt0n n : (0 < n) = (n != 0). Proof. by case: n. Qed. Lemma lt0n_neq0 n : 0 < n -> n != 0. Proof. by case: n. Qed. Lemma eqn0Ngt n : (n == 0) = ~~ (n > 0). Proof. by case: n. Qed. Lemma neq0_lt0n n : (n == 0) = false -> 0 < n. Proof. by case: n. Qed. #[global] Hint Resolve lt0n_neq0 neq0_lt0n : core. Lemma eqn_leq m n : (m == n) = (m <= n <= m). Proof. by elim: m n => [|m IHm] []. Qed. Lemma anti_leq : antisymmetric leq. Proof. by move=> m n; rewrite -eqn_leq => /eqP. Qed. Lemma neq_ltn m n : (m != n) = (m < n) || (n < m). Proof. by rewrite eqn_leq negb_and orbC -!ltnNge. Qed. Lemma gtn_eqF m n : m < n -> n == m = false. Proof. by rewrite eqn_leq (leqNgt n) => ->. Qed. Lemma ltn_eqF m n : m < n -> m == n = false. Proof. by move/gtn_eqF; rewrite eq_sym. Qed. Lemma ltn_geF m n : m < n -> m >= n = false. Proof. by rewrite (leqNgt n) => ->. Qed. Lemma leq_gtF m n : m <= n -> m > n = false. Proof. by rewrite (ltnNge n) => ->. Qed. Lemma leq_eqVlt m n : (m <= n) = (m == n) || (m < n). Proof. by elim: m n => [|m IHm] []. Qed. Lemma ltn_neqAle m n : (m < n) = (m != n) && (m <= n). Proof. by rewrite ltnNge leq_eqVlt negb_or -leqNgt eq_sym. Qed. Lemma leq_trans n m p : m <= n -> n <= p -> m <= p. Proof. by elim: n m p => [|i IHn] [|m] [|p] //; apply: IHn m p. Qed. Lemma leq_ltn_trans n m p : m <= n -> n < p -> m < p. Proof. by move=> Hmn; apply: leq_trans. Qed. Lemma ltnW m n : m < n -> m <= n. Proof. exact: leq_trans. Qed. #[global] Hint Resolve ltnW : core. Lemma leqW m n : m <= n -> m <= n.+1. Proof. by move=> le_mn; apply: ltnW. Qed. Lemma ltn_trans n m p : m < n -> n < p -> m < p. Proof. by move=> lt_mn /ltnW; apply: leq_trans. Qed. Lemma leq_total m n : (m <= n) || (m >= n). Proof. by rewrite -implyNb -ltnNge; apply/implyP; apply: ltnW. Qed. (* Helper lemmas to support generalized induction over a nat measure. *) (* The idiom for a proof by induction over a measure Mxy : nat involving *) (* variables x, y, ... (e.g., size x + size y) is *) (* have [n leMn] := ubnP Mxy; elim: n => // n IHn in x y ... leMn ... *. *) (* after which the current goal (possibly modified by generalizations in the *) (* in ... part) can be proven with the extra context assumptions *) (* n : nat *) (* IHn : forall x y ..., Mxy < n -> ... -> the_initial_goal *) (* leMn : Mxy < n.+1 *) (* This is preferable to the legacy idiom relying on numerical occurrence *) (* selection, which is fragile if there can be multiple occurrences of x, y, *) (* ... in the measure expression Mxy (e.g., in #|y| with x : finType and *) (* y : {set x}). *) (* The leMn statement is convertible to Mxy <= n; if it is necessary to *) (* have _exactly_ leMn : Mxy <= n, the ltnSE helper lemma may be used as *) (* follows *) (* have [n] := ubnP Mxy; elim: n => // n IHn in x y ... * => /ltnSE-leMn. *) (* We also provide alternative helper lemmas for proofs where the upper *) (* bound appears in the goal, and we assume nonstrict (in)equality. *) (* In either case the proof will have to dispatch an Mxy = 0 case. *) (* have [n defM] := ubnPleq Mxy; elim: n => [|n IHn] in x y ... defM ... *. *) (* yields two subgoals, in which Mxy has been replaced by 0 and n.+1, *) (* with the extra assumption defM : Mxy <= 0 / Mxy <= n.+1, respectively. *) (* The second goal also has the inductive assumption *) (* IHn : forall x y ..., Mxy <= n -> ... -> the_initial_goal[n / Mxy]. *) (* Using ubnPgeq or ubnPeq instead of ubnPleq yields assumptions with *) (* Mxy >= 0/n.+1 or Mxy == 0/n.+1 instead of Mxy <= 0/n.+1, respectively. *) (* These introduce a different kind of induction; for example ubnPgeq M lets *) (* us remember that n < M throughout the induction. *) (* Finally, the ltn_ind lemma provides a generalized induction view for a *) (* property of a single integer (i.e., the case Mxy := x). *) Lemma ubnP m : {n | m < n}. Proof. by exists m.+1. Qed. Lemma ltnSE m n : m < n.+1 -> m <= n. Proof. by []. Qed. Variant ubn_leq_spec m : nat -> Type := UbnLeq n of m <= n : ubn_leq_spec m n. Variant ubn_geq_spec m : nat -> Type := UbnGeq n of m >= n : ubn_geq_spec m n. Variant ubn_eq_spec m : nat -> Type := UbnEq n of m == n : ubn_eq_spec m n. Lemma ubnPleq m : ubn_leq_spec m m. Proof. by []. Qed. Lemma ubnPgeq m : ubn_geq_spec m m. Proof. by []. Qed. Lemma ubnPeq m : ubn_eq_spec m m. Proof. by []. Qed. Lemma ltn_ind P : (forall n, (forall m, m < n -> P m) -> P n) -> forall n, P n. Proof. move=> accP M; have [n leMn] := ubnP M; elim: n => // n IHn in M leMn *. by apply/accP=> p /leq_trans/(_ leMn)/IHn. Qed. (* Link to the legacy comparison predicates. *) Lemma leP m n : reflect (m <= n)%coq_nat (m <= n). Proof. apply: (iffP idP); last by elim: n / => // n _ /leq_trans->. elim: n => [|n IHn]; first by case: m. by rewrite leq_eqVlt ltnS => /predU1P[<- // | /IHn]; right. Qed. Arguments leP {m n}. Lemma le_irrelevance m n le_mn1 le_mn2 : le_mn1 = le_mn2 :> (m <= n)%coq_nat. Proof. elim/ltn_ind: n => n IHn in le_mn1 le_mn2 *; set n1 := n in le_mn1 *. pose def_n : n = n1 := erefl n; transitivity (eq_ind _ _ le_mn2 _ def_n) => //. case: n1 / le_mn1 le_mn2 => [|n1 le_mn1] {n}[|n le_mn2] in (def_n) IHn *. - by rewrite [def_n]eq_axiomK. - by case/leP/idPn: (le_mn2); rewrite -def_n ltnn. - by case/leP/idPn: (le_mn1); rewrite def_n ltnn. case: def_n (def_n) => <-{n1} def_n in le_mn1 *. by rewrite [def_n]eq_axiomK /=; congr le_S; apply: IHn. Qed. Lemma ltP m n : reflect (m < n)%coq_nat (m < n). Proof. exact leP. Qed. Arguments ltP {m n}. Lemma lt_irrelevance m n lt_mn1 lt_mn2 : lt_mn1 = lt_mn2 :> (m < n)%coq_nat. Proof. exact: (@le_irrelevance m.+1). Qed. (* Monotonicity lemmas *) Lemma leq_add2l p m n : (p + m <= p + n) = (m <= n). Proof. by elim: p. Qed. Lemma ltn_add2l p m n : (p + m < p + n) = (m < n). Proof. by rewrite -addnS; apply: leq_add2l. Qed. Lemma leq_add2r p m n : (m + p <= n + p) = (m <= n). Proof. by rewrite -!(addnC p); apply: leq_add2l. Qed. Lemma ltn_add2r p m n : (m + p < n + p) = (m < n). Proof. exact: leq_add2r p m.+1 n. Qed. Lemma leq_add m1 m2 n1 n2 : m1 <= n1 -> m2 <= n2 -> m1 + m2 <= n1 + n2. Proof. by move=> le_mn1 le_mn2; rewrite (@leq_trans (m1 + n2)) ?leq_add2l ?leq_add2r. Qed. Lemma leq_addl m n : n <= m + n. Proof. exact: (leq_add2r n 0). Qed. Lemma leq_addr m n : n <= n + m. Proof. by rewrite addnC leq_addl. Qed. Lemma ltn_addl m n p : m < n -> m < p + n. Proof. by move/leq_trans=> -> //; apply: leq_addl. Qed. Lemma ltn_addr m n p : m < n -> m < n + p. Proof. by move/leq_trans=> -> //; apply: leq_addr. Qed. Lemma addn_gt0 m n : (0 < m + n) = (0 < m) || (0 < n). Proof. by rewrite !lt0n -negb_and addn_eq0. Qed. Lemma subn_gt0 m n : (0 < n - m) = (m < n). Proof. by elim: m n => [|m IHm] [|n] //; apply: IHm n. Qed. Lemma subn_eq0 m n : (m - n == 0) = (m <= n). Proof. by []. Qed. Lemma leq_subLR m n p : (m - n <= p) = (m <= n + p). Proof. by rewrite -subn_eq0 -subnDA. Qed. Lemma leq_subr m n : n - m <= n. Proof. by rewrite leq_subLR leq_addl. Qed. Lemma ltn_subrR m n : (n < n - m) = false. Proof. by rewrite ltnNge leq_subr. Qed. Lemma leq_subrR m n : (n <= n - m) = (m == 0) || (n == 0). Proof. by case: m n => [|m] [|n]; rewrite ?subn0 ?leqnn ?ltn_subrR. Qed. Lemma ltn_subrL m n : (n - m < n) = (0 < m) && (0 < n). Proof. by rewrite ltnNge leq_subrR negb_or !lt0n. Qed. Lemma subnKC m n : m <= n -> m + (n - m) = n. Proof. by elim: m n => [|m IHm] [|n] // /(IHm n) {2}<-. Qed. Lemma addnBn m n : m + (n - m) = m - n + n. Proof. by elim: m n => [|m IHm] [|n] //; rewrite addSn addnS IHm. Qed. Lemma subnK m n : m <= n -> (n - m) + m = n. Proof. by rewrite addnC; apply: subnKC. Qed. Lemma addnBA m n p : p <= n -> m + (n - p) = m + n - p. Proof. by move=> le_pn; rewrite -[in RHS](subnK le_pn) addnA addnK. Qed. Lemma addnBAC m n p : n <= m -> m - n + p = m + p - n. Proof. by move=> le_nm; rewrite addnC addnBA // addnC. Qed. Lemma addnBCA m n p : p <= m -> p <= n -> m + (n - p) = n + (m - p). Proof. by move=> le_pm le_pn; rewrite !addnBA // addnC. Qed. Lemma addnABC m n p : p <= m -> p <= n -> m + (n - p) = m - p + n. Proof. by move=> le_pm le_pn; rewrite addnBA // addnBAC. Qed. Lemma subnBA m n p : p <= n -> m - (n - p) = m + p - n. Proof. by move=> le_pn; rewrite -[in RHS](subnK le_pn) subnDr. Qed. Lemma subnA m n p : p <= n -> n <= m -> m - (n - p) = m - n + p. Proof. by move=> le_pn lr_nm; rewrite addnBAC // subnBA. Qed. Lemma subKn m n : m <= n -> n - (n - m) = m. Proof. by move/subnBA->; rewrite addKn. Qed. Lemma subSn m n : m <= n -> n.+1 - m = (n - m).+1. Proof. by rewrite -add1n => /addnBA <-. Qed. Lemma subnSK m n : m < n -> (n - m.+1).+1 = n - m. Proof. by move/subSn. Qed. Lemma addnCBA m n p : p <= n -> m + (n - p) = n + m - p. Proof. by move=> pn; rewrite (addnC n m) addnBA. Qed. Lemma addnBr_leq n p m : n <= p -> m + (n - p) = m. Proof. by rewrite -subn_eq0 => /eqP->; rewrite addn0. Qed. Lemma addnBl_leq m n p : m <= n -> m - n + p = p. Proof. by rewrite -subn_eq0; move/eqP => ->; rewrite add0n. Qed. Lemma subnDAC m n p : m - (n + p) = m - p - n. Proof. by rewrite addnC subnDA. Qed. Lemma subnCBA m n p : p <= n -> m - (n - p) = p + m - n. Proof. by move=> pn; rewrite addnC subnBA. Qed. Lemma subnBr_leq n p m : n <= p -> m - (n - p) = m. Proof. by rewrite -subn_eq0 => /eqP->; rewrite subn0. Qed. Lemma subnBl_leq m n p : m <= n -> (m - n) - p = 0. Proof. by rewrite -subn_eq0 => /eqP->. Qed. Lemma subnBAC m n p : p <= n -> n <= m -> m - (n - p) = p + (m - n). Proof. by move=> pn nm; rewrite subnA // addnC. Qed. Lemma subDnAC m n p : p <= n -> m + n - p = n - p + m. Proof. by move=> pn; rewrite addnC -addnBAC. Qed. Lemma subDnCA m n p : p <= m -> m + n - p = n + (m - p). Proof. by move=> pm; rewrite addnC -addnBA. Qed. Lemma subDnCAC m n p : m <= p -> m + n - p = n - (p - m). Proof. by move=> mp; rewrite addnC -subnBA. Qed. Lemma addnBC m n : m - n + n = n - m + m. Proof. by rewrite -[in RHS]addnBn addnC. Qed. Lemma addnCB m n : m - n + n = m + (n - m). Proof. by rewrite addnBC addnC. Qed. Lemma addBnAC m n p : n <= m -> m - n + p = p + m - n. Proof. by move=> nm; rewrite [p + m]addnC addnBAC. Qed. Lemma addBnCAC m n p : n <= m -> n <= p -> m - n + p = p - n + m. Proof. by move=> nm np; rewrite addnC addnBA // subDnCA // addnC. Qed. Lemma addBnA m n p : n <= m -> p <= n -> m - n + p = m - (n - p). Proof. by move=> nm pn; rewrite subnBA // -subDnAC // addnC. Qed. Lemma subBnAC m n p : m - n - p = m - (p + n). Proof. by rewrite addnC -subnDA. Qed. Lemma predn_sub m n : (m - n).-1 = (m.-1 - n). Proof. by case: m => // m; rewrite subSKn. Qed. Lemma leq_sub2r p m n : m <= n -> m - p <= n - p. Proof. by move=> le_mn; rewrite leq_subLR (leq_trans le_mn) // -leq_subLR. Qed. Lemma leq_sub2l p m n : m <= n -> p - n <= p - m. Proof. rewrite -(leq_add2r (p - m)) leq_subLR. by apply: leq_trans; rewrite -leq_subLR. Qed. Lemma leq_sub m1 m2 n1 n2 : m1 <= m2 -> n2 <= n1 -> m1 - n1 <= m2 - n2. Proof. by move/(leq_sub2r n1)=> le_m12 /(leq_sub2l m2); apply: leq_trans. Qed. Lemma ltn_sub2r p m n : p < n -> m < n -> m - p < n - p. Proof. by move/subnSK <-; apply: (@leq_sub2r p.+1). Qed. Lemma ltn_sub2l p m n : m < p -> m < n -> p - n < p - m. Proof. by move/subnSK <-; apply: leq_sub2l. Qed. Lemma ltn_subRL m n p : (n < p - m) = (m + n < p). Proof. by rewrite !ltnNge leq_subLR. Qed. Lemma leq_psubRL m n p : 0 < n -> (n <= p - m) = (m + n <= p). Proof. by move=> /prednK<-; rewrite ltn_subRL addnS. Qed. Lemma ltn_psubLR m n p : 0 < p -> (m - n < p) = (m < n + p). Proof. by move=> /prednK<-; rewrite ltnS leq_subLR addnS. Qed. Lemma leq_subRL m n p : m <= p -> (n <= p - m) = (m + n <= p). Proof. by move=> /subnKC{2}<-; rewrite leq_add2l. Qed. Lemma ltn_subLR m n p : n <= m -> (m - n < p) = (m < n + p). Proof. by move=> /subnKC{2}<-; rewrite ltn_add2l. Qed. Lemma leq_subCl m n p : (m - n <= p) = (m - p <= n). Proof. by rewrite !leq_subLR // addnC. Qed. Lemma ltn_subCr m n p : (p < m - n) = (n < m - p). Proof. by rewrite !ltn_subRL // addnC. Qed. Lemma leq_psubCr m n p : 0 < p -> 0 < n -> (p <= m - n) = (n <= m - p). Proof. by move=> p_gt0 n_gt0; rewrite !leq_psubRL // addnC. Qed. Lemma ltn_psubCl m n p : 0 < p -> 0 < n -> (m - n < p) = (m - p < n). Proof. by move=> p_gt0 n_gt0; rewrite !ltn_psubLR // addnC. Qed. Lemma leq_subCr m n p : n <= m -> p <= m -> (p <= m - n) = (n <= m - p). Proof. by move=> np pm; rewrite !leq_subRL // addnC. Qed. Lemma ltn_subCl m n p : n <= m -> p <= m -> (m - n < p) = (m - p < n). Proof. by move=> nm pm; rewrite !ltn_subLR // addnC. Qed. Lemma leq_sub2rE p m n : p <= n -> (m - p <= n - p) = (m <= n). Proof. by move=> pn; rewrite leq_subLR subnKC. Qed. Lemma leq_sub2lE m n p : n <= m -> (m - p <= m - n) = (n <= p). Proof. by move=> nm; rewrite leq_subCl subKn. Qed. Lemma ltn_sub2rE p m n : p <= m -> (m - p < n - p) = (m < n). Proof. by move=> pn; rewrite ltn_subRL addnC subnK. Qed. Lemma ltn_sub2lE m n p : p <= m -> (m - p < m - n) = (n < p). Proof. by move=> pm; rewrite ltn_subCr subKn. Qed. Lemma eqn_sub2rE p m n : p <= m -> p <= n -> (m - p == n - p) = (m == n). Proof. by move=> pm pn; rewrite !eqn_leq !leq_sub2rE. Qed. Lemma eqn_sub2lE m n p : p <= m -> n <= m -> (m - p == m - n) = (p == n). Proof. by move=> pm nm; rewrite !eqn_leq !leq_sub2lE // -!eqn_leq eq_sym. Qed. (* Max and min. *) Definition maxn m n := if m < n then n else m. Definition minn m n := if m < n then m else n. Lemma max0n : left_id 0 maxn. Proof. by case. Qed. Lemma maxn0 : right_id 0 maxn. Proof. by []. Qed. Lemma maxnC : commutative maxn. Proof. by rewrite /maxn; elim=> [|m ih] [] // n; rewrite !ltnS -!fun_if ih. Qed. Lemma maxnE m n : maxn m n = m + (n - m). Proof. rewrite /maxn; elim: m n => [|m ih] [|n]; rewrite ?addn0 //. by rewrite ltnS subSS addSn -ih; case: leq. Qed. Lemma maxnAC : right_commutative maxn. Proof. by move=> m n p; rewrite !maxnE -!addnA !subnDA -!maxnE maxnC. Qed. Lemma maxnA : associative maxn. Proof. by move=> m n p; rewrite !(maxnC m) maxnAC. Qed. Lemma maxnCA : left_commutative maxn. Proof. by move=> m n p; rewrite !maxnA (maxnC m). Qed. Lemma maxnACA : interchange maxn maxn. Proof. by move=> m n p q; rewrite -!maxnA (maxnCA n). Qed. Lemma maxn_idPl {m n} : reflect (maxn m n = m) (m >= n). Proof. by rewrite -subn_eq0 -(eqn_add2l m) addn0 -maxnE; apply: eqP. Qed. Lemma maxn_idPr {m n} : reflect (maxn m n = n) (m <= n). Proof. by rewrite maxnC; apply: maxn_idPl. Qed. Lemma maxnn : idempotent_op maxn. Proof. by move=> n; apply/maxn_idPl. Qed. Lemma leq_max m n1 n2 : (m <= maxn n1 n2) = (m <= n1) || (m <= n2). Proof. without loss le_n21: n1 n2 / n2 <= n1. by case/orP: (leq_total n2 n1) => le_n12; last rewrite maxnC orbC; apply. by rewrite (maxn_idPl le_n21) orb_idr // => /leq_trans->. Qed. Lemma leq_maxl m n : m <= maxn m n. Proof. by rewrite leq_max leqnn. Qed. Lemma leq_maxr m n : n <= maxn m n. Proof. by rewrite maxnC leq_maxl. Qed. Lemma gtn_max m n1 n2 : (m > maxn n1 n2) = (m > n1) && (m > n2). Proof. by rewrite !ltnNge leq_max negb_or. Qed. Lemma geq_max m n1 n2 : (m >= maxn n1 n2) = (m >= n1) && (m >= n2). Proof. by rewrite -ltnS gtn_max. Qed. Lemma maxnSS m n : maxn m.+1 n.+1 = (maxn m n).+1. Proof. by rewrite !maxnE. Qed. Lemma addn_maxl : left_distributive addn maxn. Proof. by move=> m1 m2 n; rewrite !maxnE subnDr addnAC. Qed. Lemma addn_maxr : right_distributive addn maxn. Proof. by move=> m n1 n2; rewrite !(addnC m) addn_maxl. Qed. Lemma subn_maxl : left_distributive subn maxn. Proof. move=> m n p; apply/eqP. rewrite eqn_leq !geq_max !leq_sub2r leq_max ?leqnn ?andbT ?orbT // /maxn. by case: (_ < _); rewrite leqnn // orbT. Qed. Lemma min0n : left_zero 0 minn. Proof. by case. Qed. Lemma minn0 : right_zero 0 minn. Proof. by []. Qed. Lemma minnC : commutative minn. Proof. by rewrite /minn; elim=> [|m ih] [] // n; rewrite !ltnS -!fun_if ih. Qed. Lemma addn_min_max m n : minn m n + maxn m n = m + n. Proof. by rewrite /minn /maxn; case: (m < n) => //; exact: addnC. Qed. Lemma minnE m n : minn m n = m - (m - n). Proof. by rewrite -(subnDl n) -maxnE -addn_min_max addnK minnC. Qed. Lemma minnAC : right_commutative minn. Proof. by move=> m n p; rewrite !minnE -subnDA subnAC -maxnE maxnC maxnE subnAC subnDA. Qed. Lemma minnA : associative minn. Proof. by move=> m n p; rewrite minnC minnAC (minnC n). Qed. Lemma minnCA : left_commutative minn. Proof. by move=> m n p; rewrite !minnA (minnC n). Qed. Lemma minnACA : interchange minn minn. Proof. by move=> m n p q; rewrite -!minnA (minnCA n). Qed. Lemma minn_idPl {m n} : reflect (minn m n = m) (m <= n). Proof. rewrite (sameP maxn_idPr eqP) -(eqn_add2l m) eq_sym -addn_min_max eqn_add2r. exact: eqP. Qed. Lemma minn_idPr {m n} : reflect (minn m n = n) (m >= n). Proof. by rewrite minnC; apply: minn_idPl. Qed. Lemma minnn : idempotent_op minn. Proof. by move=> n; apply/minn_idPl. Qed. Lemma leq_min m n1 n2 : (m <= minn n1 n2) = (m <= n1) && (m <= n2). Proof. wlog le_n21: n1 n2 / n2 <= n1. by case/orP: (leq_total n2 n1) => ?; last rewrite minnC andbC; apply. rewrite /minn ltnNge le_n21 /=; case le_m_n1: (m <= n1) => //=. apply/contraFF: le_m_n1 => /leq_trans; exact. Qed. Lemma gtn_min m n1 n2 : (m > minn n1 n2) = (m > n1) || (m > n2). Proof. by rewrite !ltnNge leq_min negb_and. Qed. Lemma geq_min m n1 n2 : (m >= minn n1 n2) = (m >= n1) || (m >= n2). Proof. by rewrite -ltnS gtn_min. Qed. Lemma ltn_min m n1 n2 : (m < minn n1 n2) = (m < n1) && (m < n2). Proof. exact: leq_min. Qed. Lemma geq_minl m n : minn m n <= m. Proof. by rewrite geq_min leqnn. Qed. Lemma geq_minr m n : minn m n <= n. Proof. by rewrite minnC geq_minl. Qed. Lemma addn_minr : right_distributive addn minn. Proof. by move=> m1 m2 n; rewrite !minnE subnDl addnBA ?leq_subr. Qed. Lemma addn_minl : left_distributive addn minn. Proof. by move=> m1 m2 n; rewrite -!(addnC n) addn_minr. Qed. Lemma subn_minl : left_distributive subn minn. Proof. move=> m n p; apply/eqP. rewrite eqn_leq !leq_min !leq_sub2r geq_min ?leqnn ?orbT //= /minn. by case: (_ < _); rewrite leqnn // orbT. Qed. Lemma minnSS m n : minn m.+1 n.+1 = (minn m n).+1. Proof. by rewrite -(addn_minr 1). Qed. (* Quasi-cancellation (really, absorption) lemmas *) Lemma maxnK m n : minn (maxn m n) m = m. Proof. exact/minn_idPr/leq_maxl. Qed. Lemma maxKn m n : minn n (maxn m n) = n. Proof. exact/minn_idPl/leq_maxr. Qed. Lemma minnK m n : maxn (minn m n) m = m. Proof. exact/maxn_idPr/geq_minl. Qed. Lemma minKn m n : maxn n (minn m n) = n. Proof. exact/maxn_idPl/geq_minr. Qed. (* Distributivity. *) Lemma maxn_minl : left_distributive maxn minn. Proof. move=> m1 m2 n; wlog le_m21: m1 m2 / m2 <= m1. move=> IH; case/orP: (leq_total m2 m1) => /IH //. by rewrite minnC [in R in _ = R]minnC. rewrite (minn_idPr le_m21); apply/esym/minn_idPr. by rewrite geq_max leq_maxr leq_max le_m21. Qed. Lemma maxn_minr : right_distributive maxn minn. Proof. by move=> m n1 n2; rewrite !(maxnC m) maxn_minl. Qed. Lemma minn_maxl : left_distributive minn maxn. Proof. by move=> m1 m2 n; rewrite maxn_minr !maxn_minl -minnA maxnn (maxnC _ n) !maxnK. Qed. Lemma minn_maxr : right_distributive minn maxn. Proof. by move=> m n1 n2; rewrite !(minnC m) minn_maxl. Qed. (* Comparison predicates. *) Variant leq_xor_gtn m n : nat -> nat -> nat -> nat -> bool -> bool -> Set := | LeqNotGtn of m <= n : leq_xor_gtn m n m m n n true false | GtnNotLeq of n < m : leq_xor_gtn m n n n m m false true. Lemma leqP m n : leq_xor_gtn m n (minn n m) (minn m n) (maxn n m) (maxn m n) (m <= n) (n < m). Proof. rewrite (minnC m) /minn (maxnC m) /maxn ltnNge. by case le_mn: (m <= n); constructor; rewrite //= ltnNge le_mn. Qed. Variant ltn_xor_geq m n : nat -> nat -> nat -> nat -> bool -> bool -> Set := | LtnNotGeq of m < n : ltn_xor_geq m n m m n n false true | GeqNotLtn of n <= m : ltn_xor_geq m n n n m m true false. Lemma ltnP m n : ltn_xor_geq m n (minn n m) (minn m n) (maxn n m) (maxn m n) (n <= m) (m < n). Proof. by case: leqP; constructor. Qed. Variant eqn0_xor_gt0 n : bool -> bool -> Set := | Eq0NotPos of n = 0 : eqn0_xor_gt0 n true false | PosNotEq0 of n > 0 : eqn0_xor_gt0 n false true. Lemma posnP n : eqn0_xor_gt0 n (n == 0) (0 < n). Proof. by case: n; constructor. Qed. Variant compare_nat m n : nat -> nat -> nat -> nat -> bool -> bool -> bool -> bool -> bool -> bool -> Set := | CompareNatLt of m < n : compare_nat m n m m n n false false false true false true | CompareNatGt of m > n : compare_nat m n n n m m false false true false true false | CompareNatEq of m = n : compare_nat m n m m m m true true true true false false. Lemma ltngtP m n : compare_nat m n (minn n m) (minn m n) (maxn n m) (maxn m n) (n == m) (m == n) (n <= m) (m <= n) (n < m) (m < n). Proof. rewrite !ltn_neqAle [_ == n]eq_sym; have [mn|] := ltnP m n. by rewrite ltnW // gtn_eqF //; constructor. rewrite leq_eqVlt; case: ltnP; rewrite ?(orbT, orbF) => //= lt_nm eq_nm. by rewrite ltn_eqF //; constructor. by rewrite eq_nm (eqP eq_nm); constructor. Qed. (* Eliminating the idiom for structurally decreasing compare and subtract. *) Lemma subn_if_gt T m n F (E : T) : (if m.+1 - n is m'.+1 then F m' else E) = (if n <= m then F (m - n) else E). Proof. by have [le_nm|/eqnP-> //] := leqP; rewrite -{1}(subnK le_nm) -addSn addnK. Qed. Notation leqLHS := (X in (X <= _)%N)%pattern. Notation leqRHS := (X in (_ <= X)%N)%pattern. Notation ltnLHS := (X in (X < _)%N)%pattern. Notation ltnRHS := (X in (_ < X)%N)%pattern. (* Getting a concrete value from an abstract existence proof. *) Section ExMinn. Variable P : pred nat. Hypothesis exP : exists n, P n. Inductive acc_nat i : Prop := AccNat0 of P i | AccNatS of acc_nat i.+1. Lemma find_ex_minn : {m | P m & forall n, P n -> n >= m}. Proof. have: forall n, P n -> n >= 0 by []. have: acc_nat 0. case exP => n; rewrite -(addn0 n); elim: n 0 => [|n IHn] j; first by left. by rewrite addSnnS; right; apply: IHn. move: 0; fix find_ex_minn 2 => m IHm m_lb; case Pm: (P m); first by exists m. apply: find_ex_minn m.+1 _ _ => [|n Pn]; first by case: IHm; rewrite ?Pm. by rewrite ltn_neqAle m_lb //; case: eqP Pm => // -> /idP[]. Qed. Definition ex_minn := s2val find_ex_minn. Inductive ex_minn_spec : nat -> Type := ExMinnSpec m of P m & (forall n, P n -> n >= m) : ex_minn_spec m. Lemma ex_minnP : ex_minn_spec ex_minn. Proof. by rewrite /ex_minn; case: find_ex_minn. Qed. End ExMinn. Section ExMaxn. Variables (P : pred nat) (m : nat). Hypotheses (exP : exists i, P i) (ubP : forall i, P i -> i <= m). Lemma ex_maxn_subproof : exists i, P (m - i). Proof. by case: exP => i Pi; exists (m - i); rewrite subKn ?ubP. Qed. Definition ex_maxn := m - ex_minn ex_maxn_subproof. Variant ex_maxn_spec : nat -> Type := ExMaxnSpec i of P i & (forall j, P j -> j <= i) : ex_maxn_spec i. Lemma ex_maxnP : ex_maxn_spec ex_maxn. Proof. rewrite /ex_maxn; case: ex_minnP => i Pmi min_i; split=> // j Pj. have le_i_mj: i <= m - j by rewrite min_i // subKn // ubP. rewrite -subn_eq0 subnBA ?(leq_trans le_i_mj) ?leq_subr //. by rewrite addnC -subnBA ?ubP. Qed. End ExMaxn. Lemma eq_ex_minn P Q exP exQ : P =1 Q -> @ex_minn P exP = @ex_minn Q exQ. Proof. move=> eqPQ; case: ex_minnP => m1 Pm1 m1_lb; case: ex_minnP => m2 Pm2 m2_lb. by apply/eqP; rewrite eqn_leq m1_lb (m2_lb, eqPQ) // -eqPQ. Qed. Lemma eq_ex_maxn (P Q : pred nat) m n exP ubP exQ ubQ : P =1 Q -> @ex_maxn P m exP ubP = @ex_maxn Q n exQ ubQ. Proof. move=> eqPQ; case: ex_maxnP => i Pi max_i; case: ex_maxnP => j Pj max_j. by apply/eqP; rewrite eqn_leq max_i ?eqPQ // max_j -?eqPQ. Qed. Section Iteration. Variable T : Type. Implicit Types m n : nat. Implicit Types x y : T. Implicit Types S : {pred T}. Definition iter n f x := let fix loop m := if m is i.+1 then f (loop i) else x in loop n. Definition iteri n f x := let fix loop m := if m is i.+1 then f i (loop i) else x in loop n. Definition iterop n op x := let f i y := if i is 0 then x else op x y in iteri n f. Lemma iterSr n f x : iter n.+1 f x = iter n f (f x). Proof. by elim: n => //= n <-. Qed. Lemma iterS n f x : iter n.+1 f x = f (iter n f x). Proof. by []. Qed. Lemma iterD n m f x : iter (n + m) f x = iter n f (iter m f x). Proof. by elim: n => //= n ->. Qed. Lemma iteriS n f x : iteri n.+1 f x = f n (iteri n f x). Proof. by []. Qed. Lemma iteropS idx n op x : iterop n.+1 op x idx = iter n (op x) x. Proof. by elim: n => //= n ->. Qed. Lemma eq_iter f f' : f =1 f' -> forall n, iter n f =1 iter n f'. Proof. by move=> eq_f n x; elim: n => //= n ->; rewrite eq_f. Qed. Lemma iter_fix n f x : f x = x -> iter n f x = x. Proof. by move=> fixf; elim: n => //= n ->. Qed. Lemma eq_iteri f f' : f =2 f' -> forall n, iteri n f =1 iteri n f'. Proof. by move=> eq_f n x; elim: n => //= n ->; rewrite eq_f. Qed. Lemma eq_iterop n op op' : op =2 op' -> iterop n op =2 iterop n op'. Proof. by move=> eq_op x; apply: eq_iteri; case. Qed. Lemma iter_in f S i : {homo f : x / x \in S} -> {homo iter i f : x / x \in S}. Proof. by move=> f_in x xS; elim: i => [|i /f_in]. Qed. End Iteration. Lemma iter_succn m n : iter n succn m = m + n. Proof. by rewrite addnC; elim: n => //= n ->. Qed. Lemma iter_succn_0 n : iter n succn 0 = n. Proof. exact: iter_succn. Qed. Lemma iter_predn m n : iter n predn m = m - n. Proof. by elim: n m => /= [|n IHn] m; rewrite ?subn0 // IHn subnS. Qed. (* Multiplication. *) Definition muln := mult. Arguments muln : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use muln instead.")] Definition muln_rec := muln. Notation "m * n" := (muln m n) : nat_scope. Lemma multE : mult = muln. Proof. by []. Qed. Lemma mulnE : muln = mult. Proof. by []. Qed. Lemma mul0n : left_zero 0 muln. Proof. by []. Qed. Lemma muln0 : right_zero 0 muln. Proof. by elim. Qed. Lemma mul1n : left_id 1 muln. Proof. exact: addn0. Qed. Lemma mulSn m n : m.+1 * n = n + m * n. Proof. by []. Qed. Lemma mulSnr m n : m.+1 * n = m * n + n. Proof. exact: addnC. Qed. Lemma mulnS m n : m * n.+1 = m + m * n. Proof. by elim: m => // m; rewrite !mulSn !addSn addnCA => ->. Qed. Lemma mulnSr m n : m * n.+1 = m * n + m. Proof. by rewrite addnC mulnS. Qed. Lemma iter_addn m n p : iter n (addn m) p = m * n + p. Proof. by elim: n => /= [|n ->]; rewrite ?muln0 // mulnS addnA. Qed. Lemma iter_addn_0 m n : iter n (addn m) 0 = m * n. Proof. by rewrite iter_addn addn0. Qed. Lemma muln1 : right_id 1 muln. Proof. by move=> n; rewrite mulnSr muln0. Qed. Lemma mulnC : commutative muln. Proof. by move=> m n; elim: m => [|m]; rewrite (muln0, mulnS) // mulSn => ->. Qed. Lemma mulnDl : left_distributive muln addn. Proof. by move=> m1 m2 n; elim: m1 => //= m1 IHm; rewrite -addnA -IHm. Qed. Lemma mulnDr : right_distributive muln addn. Proof. by move=> m n1 n2; rewrite !(mulnC m) mulnDl. Qed. Lemma mulnBl : left_distributive muln subn. Proof. move=> m n [|p]; first by rewrite !muln0. by elim: m n => // [m IHm] [|n] //; rewrite mulSn subnDl -IHm. Qed. Lemma mulnBr : right_distributive muln subn. Proof. by move=> m n p; rewrite !(mulnC m) mulnBl. Qed. Lemma mulnA : associative muln. Proof. by move=> m n p; elim: m => //= m; rewrite mulSn mulnDl => ->. Qed. Lemma mulnCA : left_commutative muln. Proof. by move=> m n1 n2; rewrite !mulnA (mulnC m). Qed. Lemma mulnAC : right_commutative muln. Proof. by move=> m n p; rewrite -!mulnA (mulnC n). Qed. Lemma mulnACA : interchange muln muln. Proof. by move=> m n p q; rewrite -!mulnA (mulnCA n). Qed. Lemma muln_eq0 m n : (m * n == 0) = (m == 0) || (n == 0). Proof. by case: m n => // m [|n] //=; rewrite muln0. Qed. Lemma muln_eq1 m n : (m * n == 1) = (m == 1) && (n == 1). Proof. by case: m n => [|[|m]] [|[|n]] //; rewrite muln0. Qed. Lemma muln_gt0 m n : (0 < m * n) = (0 < m) && (0 < n). Proof. by case: m n => // m [|n] //=; rewrite muln0. Qed. Lemma leq_pmull m n : n > 0 -> m <= n * m. Proof. by move/prednK <-; apply: leq_addr. Qed. Lemma leq_pmulr m n : n > 0 -> m <= m * n. Proof. by move/leq_pmull; rewrite mulnC. Qed. Lemma leq_mul2l m n1 n2 : (m * n1 <= m * n2) = (m == 0) || (n1 <= n2). Proof. by rewrite [LHS]/leq -mulnBr muln_eq0. Qed. Lemma leq_mul2r m n1 n2 : (n1 * m <= n2 * m) = (m == 0) || (n1 <= n2). Proof. by rewrite -!(mulnC m) leq_mul2l. Qed. Lemma leq_mul m1 m2 n1 n2 : m1 <= n1 -> m2 <= n2 -> m1 * m2 <= n1 * n2. Proof. move=> le_mn1 le_mn2; apply (@leq_trans (m1 * n2)). by rewrite leq_mul2l le_mn2 orbT. by rewrite leq_mul2r le_mn1 orbT. Qed. Lemma eqn_mul2l m n1 n2 : (m * n1 == m * n2) = (m == 0) || (n1 == n2). Proof. by rewrite eqn_leq !leq_mul2l -orb_andr -eqn_leq. Qed. Lemma eqn_mul2r m n1 n2 : (n1 * m == n2 * m) = (m == 0) || (n1 == n2). Proof. by rewrite eqn_leq !leq_mul2r -orb_andr -eqn_leq. Qed. Lemma leq_pmul2l m n1 n2 : 0 < m -> (m * n1 <= m * n2) = (n1 <= n2). Proof. by move/prednK=> <-; rewrite leq_mul2l. Qed. Arguments leq_pmul2l [m n1 n2]. Lemma leq_pmul2r m n1 n2 : 0 < m -> (n1 * m <= n2 * m) = (n1 <= n2). Proof. by move/prednK <-; rewrite leq_mul2r. Qed. Arguments leq_pmul2r [m n1 n2]. Lemma eqn_pmul2l m n1 n2 : 0 < m -> (m * n1 == m * n2) = (n1 == n2). Proof. by move/prednK <-; rewrite eqn_mul2l. Qed. Arguments eqn_pmul2l [m n1 n2]. Lemma eqn_pmul2r m n1 n2 : 0 < m -> (n1 * m == n2 * m) = (n1 == n2). Proof. by move/prednK <-; rewrite eqn_mul2r. Qed. Arguments eqn_pmul2r [m n1 n2]. Lemma ltn_mul2l m n1 n2 : (m * n1 < m * n2) = (0 < m) && (n1 < n2). Proof. by rewrite lt0n !ltnNge leq_mul2l negb_or. Qed. Lemma ltn_mul2r m n1 n2 : (n1 * m < n2 * m) = (0 < m) && (n1 < n2). Proof. by rewrite lt0n !ltnNge leq_mul2r negb_or. Qed. Lemma ltn_pmul2l m n1 n2 : 0 < m -> (m * n1 < m * n2) = (n1 < n2). Proof. by move/prednK <-; rewrite ltn_mul2l. Qed. Arguments ltn_pmul2l [m n1 n2]. Lemma ltn_pmul2r m n1 n2 : 0 < m -> (n1 * m < n2 * m) = (n1 < n2). Proof. by move/prednK <-; rewrite ltn_mul2r. Qed. Arguments ltn_pmul2r [m n1 n2]. Lemma ltn_Pmull m n : 1 < n -> 0 < m -> m < n * m. Proof. by move=> lt1n m_gt0; rewrite -[ltnLHS]mul1n ltn_pmul2r. Qed. Lemma ltn_Pmulr m n : 1 < n -> 0 < m -> m < m * n. Proof. by move=> lt1n m_gt0; rewrite mulnC ltn_Pmull. Qed. Lemma ltn_mull m1 m2 n1 n2 : 0 < n2 -> m1 < n1 -> m2 <= n2 -> m1 * m2 < n1 * n2. Proof. move=> n20 lt_mn1 le_mn2. rewrite (@leq_ltn_trans (m1 * n2)) ?leq_mul2l ?le_mn2 ?orbT//. by rewrite ltn_mul2r lt_mn1 n20. Qed. Lemma ltn_mulr m1 m2 n1 n2 : 0 < n1 -> m1 <= n1 -> m2 < n2 -> m1 * m2 < n1 * n2. Proof. by move=> ? ? ?; rewrite mulnC [ltnRHS]mulnC ltn_mull. Qed. Lemma ltn_mul m1 m2 n1 n2 : m1 < n1 -> m2 < n2 -> m1 * m2 < n1 * n2. Proof. by move=> ? lt2; rewrite ltn_mull ?(leq_ltn_trans _ lt2)// ltnW. Qed. Lemma maxnMr : right_distributive muln maxn. Proof. by case=> // m n1 n2; rewrite /maxn (fun_if (muln _)) ltn_pmul2l. Qed. Lemma maxnMl : left_distributive muln maxn. Proof. by move=> m1 m2 n; rewrite -!(mulnC n) maxnMr. Qed. Lemma minnMr : right_distributive muln minn. Proof. by case=> // m n1 n2; rewrite /minn (fun_if (muln _)) ltn_pmul2l. Qed. Lemma minnMl : left_distributive muln minn. Proof. by move=> m1 m2 n; rewrite -!(mulnC n) minnMr. Qed. Lemma iterM (T : Type) (n m : nat) (f : T -> T) : iter (n * m) f =1 iter n (iter m f). Proof. by move=> x; elim: n => //= n <-; rewrite mulSn iterD. Qed. (* Exponentiation. *) Definition expn m n := iterop n muln m 1. Arguments expn : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use expn instead.")] Definition expn_rec := expn. Notation "m ^ n" := (expn m n) : nat_scope. Lemma expnE n m : expn m n = iterop n muln m 1. Proof. by []. Qed. Lemma expn0 m : m ^ 0 = 1. Proof. by []. Qed. Lemma expn1 m : m ^ 1 = m. Proof. by []. Qed. Lemma expnS m n : m ^ n.+1 = m * m ^ n. Proof. by case: n; rewrite ?muln1. Qed. Lemma expnSr m n : m ^ n.+1 = m ^ n * m. Proof. by rewrite mulnC expnS. Qed. Lemma iter_muln m n p : iter n (muln m) p = m ^ n * p. Proof. by elim: n => /= [|n ->]; rewrite ?mul1n // expnS mulnA. Qed. Lemma iter_muln_1 m n : iter n (muln m) 1 = m ^ n. Proof. by rewrite iter_muln muln1. Qed. Lemma exp0n n : 0 < n -> 0 ^ n = 0. Proof. by case: n => [|[]]. Qed. Lemma exp1n n : 1 ^ n = 1. Proof. by elim: n => // n; rewrite expnS mul1n. Qed. Lemma expnD m n1 n2 : m ^ (n1 + n2) = m ^ n1 * m ^ n2. Proof. by elim: n1 => [|n1 IHn]; rewrite !(mul1n, expnS) // IHn mulnA. Qed. Lemma expnMn m1 m2 n : (m1 * m2) ^ n = m1 ^ n * m2 ^ n. Proof. by elim: n => // n IHn; rewrite !expnS IHn -!mulnA (mulnCA m2). Qed. Lemma expnM m n1 n2 : m ^ (n1 * n2) = (m ^ n1) ^ n2. Proof. elim: n1 => [|n1 IHn]; first by rewrite exp1n. by rewrite expnD expnS expnMn IHn. Qed. Lemma expnAC m n1 n2 : (m ^ n1) ^ n2 = (m ^ n2) ^ n1. Proof. by rewrite -!expnM mulnC. Qed. Lemma expn_gt0 m n : (0 < m ^ n) = (0 < m) || (n == 0). Proof. by case: m => [|m]; elim: n => //= n IHn; rewrite expnS // addn_gt0 IHn. Qed. Lemma expn_eq0 m e : (m ^ e == 0) = (m == 0) && (e > 0). Proof. by rewrite !eqn0Ngt expn_gt0 negb_or -lt0n. Qed. Lemma ltn_expl m n : 1 < m -> n < m ^ n. Proof. move=> m_gt1; elim: n => //= n; rewrite -(leq_pmul2l (ltnW m_gt1)) expnS. by apply: leq_trans; apply: ltn_Pmull. Qed. Lemma leq_exp2l m n1 n2 : 1 < m -> (m ^ n1 <= m ^ n2) = (n1 <= n2). Proof. move=> m_gt1; elim: n1 n2 => [|n1 IHn] [|n2] //; last 1 first. - by rewrite !expnS leq_pmul2l ?IHn // ltnW. - by rewrite expn_gt0 ltnW. by rewrite leqNgt (leq_trans m_gt1) // expnS leq_pmulr // expn_gt0 ltnW. Qed. Lemma ltn_exp2l m n1 n2 : 1 < m -> (m ^ n1 < m ^ n2) = (n1 < n2). Proof. by move=> m_gt1; rewrite !ltnNge leq_exp2l. Qed. Lemma eqn_exp2l m n1 n2 : 1 < m -> (m ^ n1 == m ^ n2) = (n1 == n2). Proof. by move=> m_gt1; rewrite !eqn_leq !leq_exp2l. Qed. Lemma expnI m : 1 < m -> injective (expn m). Proof. by move=> m_gt1 e1 e2 /eqP; rewrite eqn_exp2l // => /eqP. Qed. Lemma leq_pexp2l m n1 n2 : 0 < m -> n1 <= n2 -> m ^ n1 <= m ^ n2. Proof. by case: m => [|[|m]] // _; [rewrite !exp1n | rewrite leq_exp2l]. Qed. Lemma ltn_pexp2l m n1 n2 : 0 < m -> m ^ n1 < m ^ n2 -> n1 < n2. Proof. by case: m => [|[|m]] // _; [rewrite !exp1n | rewrite ltn_exp2l]. Qed. Lemma ltn_exp2r m n e : e > 0 -> (m ^ e < n ^ e) = (m < n). Proof. move=> e_gt0; apply/idP/idP=> [|ltmn]. rewrite !ltnNge; apply: contra => lemn. by elim: e {e_gt0} => // e IHe; rewrite !expnS leq_mul. by elim: e e_gt0 => // [[|e] IHe] _; rewrite ?expn1 // ltn_mul // IHe. Qed. Lemma leq_exp2r m n e : e > 0 -> (m ^ e <= n ^ e) = (m <= n). Proof. by move=> e_gt0; rewrite leqNgt ltn_exp2r // -leqNgt. Qed. Lemma eqn_exp2r m n e : e > 0 -> (m ^ e == n ^ e) = (m == n). Proof. by move=> e_gt0; rewrite !eqn_leq !leq_exp2r. Qed. Lemma expIn e : e > 0 -> injective (expn^~ e). Proof. by move=> e_gt1 m n /eqP; rewrite eqn_exp2r // => /eqP. Qed. Lemma iterX (T : Type) (n m : nat) (f : T -> T) : iter (n ^ m) f =1 iter m (iter n) f. Proof. elim: m => //= m ihm x; rewrite expnS iterM; exact/eq_iter. Qed. (* Factorial. *) Fixpoint factorial n := if n is n'.+1 then n * factorial n' else 1. Arguments factorial : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use factorial instead.")] Definition fact_rec := factorial. Notation "n `!" := (factorial n) (at level 1, format "n `!") : nat_scope. Lemma factE n : factorial n = if n is n'.+1 then n * factorial n' else 1. Proof. by case: n. Qed. Lemma fact0 : 0`! = 1. Proof. by []. Qed. Lemma factS n : (n.+1)`! = n.+1 * n`!. Proof. by []. Qed. Lemma fact_gt0 n : n`! > 0. Proof. by elim: n => //= n IHn; rewrite muln_gt0. Qed. Lemma fact_geq n : n <= n`!. Proof. by case: n => // n; rewrite factS -(addn1 n) leq_pmulr ?fact_gt0. Qed. Lemma ltn_fact m n : 0 < m -> m < n -> m`! < n`!. Proof. case: m n => // m n _; elim: n m => // n ih [|m] ?; last by rewrite ltn_mul ?ih. by rewrite -[_.+1]muln1 leq_mul ?fact_gt0. Qed. (* Parity and bits. *) Coercion nat_of_bool (b : bool) := if b then 1 else 0. Lemma leq_b1 (b : bool) : b <= 1. Proof. by case: b. Qed. Lemma addn_negb (b : bool) : ~~ b + b = 1. Proof. by case: b. Qed. Lemma eqb0 (b : bool) : (b == 0 :> nat) = ~~ b. Proof. by case: b. Qed. Lemma eqb1 (b : bool) : (b == 1 :> nat) = b. Proof. by case: b. Qed. Lemma lt0b (b : bool) : (b > 0) = b. Proof. by case: b. Qed. Lemma sub1b (b : bool) : 1 - b = ~~ b. Proof. by case: b. Qed. Lemma mulnb (b1 b2 : bool) : b1 * b2 = b1 && b2. Proof. by case: b1; case: b2. Qed. Lemma mulnbl (b : bool) n : b * n = (if b then n else 0). Proof. by case: b; rewrite ?mul1n. Qed. Lemma mulnbr (b : bool) n : n * b = (if b then n else 0). Proof. by rewrite mulnC mulnbl. Qed. Fixpoint odd n := if n is n'.+1 then ~~ odd n' else false. Lemma oddS n : odd n.+1 = ~~ odd n. Proof. by []. Qed. Lemma oddb (b : bool) : odd b = b. Proof. by case: b. Qed. Lemma oddD m n : odd (m + n) = odd m (+) odd n. Proof. by elim: m => [|m IHn] //=; rewrite -addTb IHn addbA addTb. Qed. Lemma oddB m n : n <= m -> odd (m - n) = odd m (+) odd n. Proof. by move=> le_nm; apply: (@canRL bool) (addbK _) _; rewrite -oddD subnK. Qed. Lemma oddN i m : odd m = false -> i <= m -> odd (m - i) = odd i. Proof. by move=> oddm /oddB ->; rewrite oddm. Qed. Lemma oddM m n : odd (m * n) = odd m && odd n. Proof. by elim: m => //= m IHm; rewrite oddD -addTb andb_addl -IHm. Qed. Lemma oddX m n : odd (m ^ n) = (n == 0) || odd m. Proof. by elim: n => // n IHn; rewrite expnS oddM {}IHn orbC; case odd. Qed. (* Doubling. *) Fixpoint double n := if n is n'.+1 then (double n').+2 else 0. Arguments double : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use double instead.")] Definition double_rec := double. Notation "n .*2" := (double n) : nat_scope. Lemma doubleE n : double n = if n is n'.+1 then (double n').+2 else 0. Proof. by case: n. Qed. Lemma double0 : 0.*2 = 0. Proof. by []. Qed. Lemma doubleS n : n.+1.*2 = n.*2.+2. Proof. by []. Qed. Lemma double_pred n : n.-1.*2 = n.*2.-2. Proof. by case: n. Qed. Lemma addnn n : n + n = n.*2. Proof. by apply: eqP; elim: n => // n IHn; rewrite addnS. Qed. Lemma mul2n m : 2 * m = m.*2. Proof. by rewrite mulSn mul1n addnn. Qed. Lemma muln2 m : m * 2 = m.*2. Proof. by rewrite mulnC mul2n. Qed. Lemma doubleD m n : (m + n).*2 = m.*2 + n.*2. Proof. by rewrite -!mul2n mulnDr. Qed. Lemma doubleB m n : (m - n).*2 = m.*2 - n.*2. Proof. by elim: m n => [|m IHm] []. Qed. Lemma leq_double m n : (m.*2 <= n.*2) = (m <= n). Proof. by rewrite /leq -doubleB; case (m - n). Qed. Lemma ltn_double m n : (m.*2 < n.*2) = (m < n). Proof. by rewrite 2!ltnNge leq_double. Qed. Lemma ltn_Sdouble m n : (m.*2.+1 < n.*2) = (m < n). Proof. by rewrite -doubleS leq_double. Qed. Lemma leq_Sdouble m n : (m.*2 <= n.*2.+1) = (m <= n). Proof. by rewrite leqNgt ltn_Sdouble -leqNgt. Qed. Lemma odd_double n : odd n.*2 = false. Proof. by rewrite -addnn oddD addbb. Qed. Lemma double_gt0 n : (0 < n.*2) = (0 < n). Proof. by case: n. Qed. Lemma double_eq0 n : (n.*2 == 0) = (n == 0). Proof. by case: n. Qed. Lemma doubleMl m n : (m * n).*2 = m.*2 * n. Proof. by rewrite -!mul2n mulnA. Qed. Lemma doubleMr m n : (m * n).*2 = m * n.*2. Proof. by rewrite -!muln2 mulnA. Qed. (* Halving. *) Fixpoint half (n : nat) : nat := if n is n'.+1 then uphalf n' else n with uphalf (n : nat) : nat := if n is n'.+1 then n'./2.+1 else n where "n ./2" := (half n) : nat_scope. Lemma uphalfE n : uphalf n = n.+1./2. Proof. by []. Qed. Lemma doubleK : cancel double half. Proof. by elim=> //= n ->. Qed. Definition half_double := doubleK. Definition double_inj := can_inj doubleK. Lemma uphalf_double n : uphalf n.*2 = n. Proof. by elim: n => //= n ->. Qed. Lemma uphalf_half n : uphalf n = odd n + n./2. Proof. by elim: n => //= n ->; rewrite addnA addn_negb. Qed. Lemma odd_double_half n : odd n + n./2.*2 = n. Proof. by elim: n => //= n {3}<-; rewrite uphalf_half doubleD; case (odd n). Qed. Lemma halfK n : n./2.*2 = n - odd n. Proof. by rewrite -[n in n - _]odd_double_half addnC addnK. Qed. Lemma uphalfK n : (uphalf n).*2 = odd n + n. Proof. by rewrite uphalfE halfK/=; case: odd; rewrite ?subn1. Qed. Lemma odd_halfK n : odd n -> n./2.*2 = n.-1. Proof. by rewrite halfK => ->; rewrite subn1. Qed. Lemma even_halfK n : ~~ odd n -> n./2.*2 = n. Proof. by rewrite halfK => /negbTE->; rewrite subn0. Qed. Lemma odd_uphalfK n : odd n -> (uphalf n).*2 = n.+1. Proof. by rewrite uphalfK => ->. Qed. Lemma even_uphalfK n : ~~ odd n -> (uphalf n).*2 = n. Proof. by rewrite uphalfK => /negbTE->. Qed. Lemma half_bit_double n (b : bool) : (b + n.*2)./2 = n. Proof. by case: b; rewrite /= (half_double, uphalf_double). Qed. Lemma halfD m n : (m + n)./2 = (odd m && odd n) + (m./2 + n./2). Proof. rewrite -[n in LHS]odd_double_half addnCA. rewrite -[m in LHS]odd_double_half -addnA -doubleD. by do 2!case: odd; rewrite /= ?add0n ?half_double ?uphalf_double. Qed. Lemma half_leq m n : m <= n -> m./2 <= n./2. Proof. by move/subnK <-; rewrite halfD addnA leq_addl. Qed. Lemma geq_half_double m n : (m <= n./2) = (m.*2 <= n). Proof. rewrite -[X in _.*2 <= X]odd_double_half. case: odd; last by rewrite leq_double. by case: m => // m; rewrite doubleS ltnS ltn_double. Qed. Lemma ltn_half_double m n : (m./2 < n) = (m < n.*2). Proof. by rewrite ltnNge geq_half_double -ltnNge. Qed. Lemma leq_half_double m n : (m./2 <= n) = (m <= n.*2.+1). Proof. by case: m => [|[|m]] //; rewrite ltnS ltn_half_double. Qed. Lemma gtn_half_double m n : (n < m./2) = (n.*2.+1 < m). Proof. by rewrite ltnNge leq_half_double -ltnNge. Qed. Lemma half_gt0 n : (0 < n./2) = (1 < n). Proof. by case: n => [|[]]. Qed. Lemma uphalf_leq m n : m <= n -> uphalf m <= uphalf n. Proof. move/subnK <-; rewrite !uphalf_half oddD halfD !addnA. by do 2 case: odd; apply: leq_addl. Qed. Lemma leq_uphalf_double m n : (uphalf m <= n) = (m <= n.*2). Proof. by rewrite uphalfE leq_half_double. Qed. Lemma geq_uphalf_double m n : (m <= uphalf n) = (m.*2 <= n.+1). Proof. by rewrite uphalfE geq_half_double. Qed. Lemma gtn_uphalf_double m n : (n < uphalf m) = (n.*2 < m). Proof. by rewrite uphalfE gtn_half_double. Qed. Lemma ltn_uphalf_double m n : (uphalf m < n) = (m.+1 < n.*2). Proof. by rewrite uphalfE ltn_half_double. Qed. Lemma uphalf_gt0 n : (0 < uphalf n) = (0 < n). Proof. by case: n. Qed. Lemma odd_geq m n : odd n -> (m <= n) = (m./2.*2 <= n). Proof. move=> odd_n; rewrite -[m in LHS]odd_double_half -[n]odd_double_half odd_n. by case: (odd m); rewrite // leq_Sdouble ltnS leq_double. Qed. Lemma odd_ltn m n : odd n -> (n < m) = (n < m./2.*2). Proof. by move=> odd_n; rewrite !ltnNge odd_geq. Qed. Lemma odd_gt0 n : odd n -> n > 0. Proof. by case: n. Qed. Lemma odd_gt2 n : odd n -> n > 1 -> n > 2. Proof. by move=> odd_n n_gt1; rewrite odd_geq. Qed. (* Squares and square identities. *) Lemma mulnn m : m * m = m ^ 2. Proof. by rewrite !expnS muln1. Qed. Lemma sqrnD m n : (m + n) ^ 2 = m ^ 2 + n ^ 2 + 2 * (m * n). Proof. rewrite -!mulnn mul2n mulnDr !mulnDl (mulnC n) -!addnA. by congr (_ + _); rewrite addnA addnn addnC. Qed. Lemma sqrnB m n : n <= m -> (m - n) ^ 2 = m ^ 2 + n ^ 2 - 2 * (m * n). Proof. move/subnK <-; rewrite addnK sqrnD -addnA -addnACA -addnA. by rewrite addnn -mul2n -mulnDr -mulnDl addnK. Qed. Lemma sqrnD_sub m n : n <= m -> (m + n) ^ 2 - 4 * (m * n) = (m - n) ^ 2. Proof. move=> le_nm; rewrite -[4]/(2 * 2) -mulnA mul2n -addnn subnDA. by rewrite sqrnD addnK sqrnB. Qed. Lemma subn_sqr m n : m ^ 2 - n ^ 2 = (m - n) * (m + n). Proof. by rewrite mulnBl !mulnDr addnC (mulnC m) subnDl. Qed. Lemma ltn_sqr m n : (m ^ 2 < n ^ 2) = (m < n). Proof. by rewrite ltn_exp2r. Qed. Lemma leq_sqr m n : (m ^ 2 <= n ^ 2) = (m <= n). Proof. by rewrite leq_exp2r. Qed. Lemma sqrn_gt0 n : (0 < n ^ 2) = (0 < n). Proof. exact: (ltn_sqr 0). Qed. Lemma eqn_sqr m n : (m ^ 2 == n ^ 2) = (m == n). Proof. by rewrite eqn_exp2r. Qed. Lemma sqrn_inj : injective (expn ^~ 2). Proof. exact: expIn. Qed. (* Almost strict inequality: an inequality that is strict unless some *) (* specific condition holds, such as the Cauchy-Schwartz or the AGM *) (* inequality (we only prove the order-2 AGM here; the general one *) (* requires sequences). *) (* We formalize the concept as a rewrite multirule, that can be used *) (* both to rewrite the non-strict inequality to true, and the equality *) (* to the specific condition (for strict inequalities use the ltn_neqAle *) (* lemma); in addition, the conditional equality also coerces to a *) (* non-strict one. *) Definition leqif m n C := ((m <= n) * ((m == n) = C))%type. Notation "m <= n ?= 'iff' C" := (leqif m n C) : nat_scope. Coercion leq_of_leqif m n C (H : m <= n ?= iff C) := H.1 : m <= n. Lemma leqifP m n C : reflect (m <= n ?= iff C) (if C then m == n else m < n). Proof. rewrite ltn_neqAle; apply: (iffP idP) => [|lte]; last by rewrite !lte; case C. by case C => [/eqP-> | /andP[/negPf]]; split=> //; apply: eqxx. Qed. Lemma leqif_refl m C : reflect (m <= m ?= iff C) C. Proof. by apply: (iffP idP) => [-> | <-] //; split; rewrite ?eqxx. Qed. Lemma leqif_trans m1 m2 m3 C12 C23 : m1 <= m2 ?= iff C12 -> m2 <= m3 ?= iff C23 -> m1 <= m3 ?= iff C12 && C23. Proof. move=> ltm12 ltm23; apply/leqifP; rewrite -ltm12. have [->|eqm12] := eqVneq; first by rewrite ltn_neqAle !ltm23 andbT; case C23. by rewrite (@leq_trans m2) ?ltm23 // ltn_neqAle eqm12 ltm12. Qed. Lemma mono_leqif f : {mono f : m n / m <= n} -> forall m n C, (f m <= f n ?= iff C) = (m <= n ?= iff C). Proof. by move=> f_mono m n C; rewrite /leqif !eqn_leq !f_mono. Qed. Lemma leqif_geq m n : m <= n -> m <= n ?= iff (m >= n). Proof. by move=> lemn; split=> //; rewrite eqn_leq lemn. Qed. Lemma leqif_eq m n : m <= n -> m <= n ?= iff (m == n). Proof. by []. Qed. Lemma geq_leqif a b C : a <= b ?= iff C -> (b <= a) = C. Proof. by case=> le_ab; rewrite eqn_leq le_ab. Qed. Lemma ltn_leqif a b C : a <= b ?= iff C -> (a < b) = ~~ C. Proof. by move=> le_ab; rewrite ltnNge (geq_leqif le_ab). Qed. Lemma ltnNleqif x y C : x <= y ?= iff ~~ C -> (x < y) = C. Proof. by move=> /ltn_leqif; rewrite negbK. Qed. Lemma eq_leqif x y C : x <= y ?= iff C -> (x == y) = C. Proof. by move=> /leqifP; case: C ltngtP => [] []. Qed. Lemma eqTleqif x y C : x <= y ?= iff C -> C -> x = y. Proof. by move=> /eq_leqif<-/eqP. Qed. Lemma leqif_add m1 n1 C1 m2 n2 C2 : m1 <= n1 ?= iff C1 -> m2 <= n2 ?= iff C2 -> m1 + m2 <= n1 + n2 ?= iff C1 && C2. Proof. rewrite -(mono_leqif (leq_add2r m2)) -(mono_leqif (leq_add2l n1) m2). exact: leqif_trans. Qed. Lemma leqif_mul m1 n1 C1 m2 n2 C2 : m1 <= n1 ?= iff C1 -> m2 <= n2 ?= iff C2 -> m1 * m2 <= n1 * n2 ?= iff (n1 * n2 == 0) || (C1 && C2). Proof. case: n1 => [|n1] le1; first by case: m1 le1 => [|m1] [_ <-] //. case: n2 m2 => [|n2] [|m2] /=; try by case=> // _ <-; rewrite !muln0 ?andbF. have /leq_pmul2l-/mono_leqif<-: 0 < n1.+1 by []. by apply: leqif_trans; have /leq_pmul2r-/mono_leqif->: 0 < m2.+1. Qed. Lemma nat_Cauchy m n : 2 * (m * n) <= m ^ 2 + n ^ 2 ?= iff (m == n). Proof. without loss le_nm: m n / n <= m. by have [?|/ltnW ?] := leqP n m; last rewrite eq_sym addnC (mulnC m); apply. apply/leqifP; have [-> | ne_mn] := eqVneq; first by rewrite addnn mul2n. by rewrite -subn_gt0 -sqrnB // sqrn_gt0 subn_gt0 ltn_neqAle eq_sym ne_mn. Qed. Lemma nat_AGM2 m n : 4 * (m * n) <= (m + n) ^ 2 ?= iff (m == n). Proof. rewrite -[4]/(2 * 2) -mulnA mul2n -addnn sqrnD; apply/leqifP. by rewrite ltn_add2r eqn_add2r ltn_neqAle !nat_Cauchy; case: eqVneq. Qed. Section ContraLeq. Implicit Types (b : bool) (m n : nat) (P : Prop). Lemma contraTleq b m n : (n < m -> ~~ b) -> (b -> m <= n). Proof. by rewrite ltnNge; apply: contraTT. Qed. Lemma contraTltn b m n : (n <= m -> ~~ b) -> (b -> m < n). Proof. by rewrite ltnNge; apply: contraTN. Qed. Lemma contraPleq P m n : (n < m -> ~ P) -> (P -> m <= n). Proof. by rewrite ltnNge; apply: contraPT. Qed. Lemma contraPltn P m n : (n <= m -> ~ P) -> (P -> m < n). Proof. by rewrite ltnNge; apply: contraPN. Qed. Lemma contraNleq b m n : (n < m -> b) -> (~~ b -> m <= n). Proof. by rewrite ltnNge; apply: contraNT. Qed. Lemma contraNltn b m n : (n <= m -> b) -> (~~ b -> m < n). Proof. by rewrite ltnNge; apply: contraNN. Qed. Lemma contra_not_leq P m n : (n < m -> P) -> (~ P -> m <= n). Proof. by rewrite ltnNge; apply: contra_notT. Qed. Lemma contra_not_ltn P m n : (n <= m -> P) -> (~ P -> m < n). Proof. by rewrite ltnNge; apply: contra_notN. Qed. Lemma contraFleq b m n : (n < m -> b) -> (b = false -> m <= n). Proof. by rewrite ltnNge; apply: contraFT. Qed. Lemma contraFltn b m n : (n <= m -> b) -> (b = false -> m < n). Proof. by rewrite ltnNge; apply: contraFN. Qed. Lemma contra_leqT b m n : (~~ b -> m < n) -> (n <= m -> b). Proof. by rewrite ltnNge; apply: contraTT. Qed. Lemma contra_ltnT b m n : (~~ b -> m <= n) -> (n < m -> b). Proof. by rewrite ltnNge; apply: contraNT. Qed. Lemma contra_leqN b m n : (b -> m < n) -> (n <= m -> ~~ b). Proof. by rewrite ltnNge; apply: contraTN. Qed. Lemma contra_ltnN b m n : (b -> m <= n) -> (n < m -> ~~ b). Proof. by rewrite ltnNge; apply: contraNN. Qed. Lemma contra_leq_not P m n : (P -> m < n) -> (n <= m -> ~ P). Proof. by rewrite ltnNge; apply: contraTnot. Qed. Lemma contra_ltn_not P m n : (P -> m <= n) -> (n < m -> ~ P). Proof. by rewrite ltnNge; apply: contraNnot. Qed. Lemma contra_leqF b m n : (b -> m < n) -> (n <= m -> b = false). Proof. by rewrite ltnNge; apply: contraTF. Qed. Lemma contra_ltnF b m n : (b -> m <= n) -> (n < m -> b = false). Proof. by rewrite ltnNge; apply: contraNF. Qed. Lemma contra_leq m n p q : (q < p -> n < m) -> (m <= n -> p <= q). Proof. by rewrite !ltnNge; apply: contraTT. Qed. Lemma contra_leq_ltn m n p q : (q <= p -> n < m) -> (m <= n -> p < q). Proof. by rewrite !ltnNge; apply: contraTN. Qed. Lemma contra_ltn_leq m n p q : (q < p -> n <= m) -> (m < n -> p <= q). Proof. by rewrite !ltnNge; apply: contraNT. Qed. Lemma contra_ltn m n p q : (q <= p -> n <= m) -> (m < n -> p < q). Proof. by rewrite !ltnNge; apply: contraNN. Qed. End ContraLeq. Section Monotonicity. Variable T : Type. Lemma homo_ltn_in (D : {pred nat}) (f : nat -> T) (r : T -> T -> Prop) : (forall y x z, r x y -> r y z -> r x z) -> {in D &, forall i j k, i < k < j -> k \in D} -> {in D, forall i, i.+1 \in D -> r (f i) (f i.+1)} -> {in D &, {homo f : i j / i < j >-> r i j}}. Proof. move=> r_trans Dcx r_incr i j iD jD lt_ij; move: (lt_ij) (jD) => /subnKC<-. elim: (_ - _) => [|k ihk]; first by rewrite addn0 => Dsi; apply: r_incr. move=> DSiSk [: DSik]; apply: (r_trans _ _ _ (ihk _)); rewrite ?addnS. by abstract: DSik; apply: (Dcx _ _ iD DSiSk); rewrite ltn_addr ?addnS /=. by apply: r_incr; rewrite -?addnS. Qed. Lemma homo_ltn (f : nat -> T) (r : T -> T -> Prop) : (forall y x z, r x y -> r y z -> r x z) -> (forall i, r (f i) (f i.+1)) -> {homo f : i j / i < j >-> r i j}. Proof. by move=> /(@homo_ltn_in predT f) fr fS i j; apply: fr. Qed. Lemma homo_leq_in (D : {pred nat}) (f : nat -> T) (r : T -> T -> Prop) : (forall x, r x x) -> (forall y x z, r x y -> r y z -> r x z) -> {in D &, forall i j k, i < k < j -> k \in D} -> {in D, forall i, i.+1 \in D -> r (f i) (f i.+1)} -> {in D &, {homo f : i j / i <= j >-> r i j}}. Proof. move=> r_refl r_trans Dcx /(homo_ltn_in r_trans Dcx) lt_r i j iD jD. case: ltngtP => [? _||->] //; exact: lt_r. Qed. Lemma homo_leq (f : nat -> T) (r : T -> T -> Prop) : (forall x, r x x) -> (forall y x z, r x y -> r y z -> r x z) -> (forall i, r (f i) (f i.+1)) -> {homo f : i j / i <= j >-> r i j}. Proof. by move=> rrefl /(@homo_leq_in predT f r) fr fS i j; apply: fr. Qed. Section NatToNat. Variable (f : nat -> nat). (****************************************************************************) (* This listing of "Let"s factor out the required premises for the *) (* subsequent lemmas, putting them in the context so that "done" solves the *) (* goals quickly *) (****************************************************************************) Let ltn_neqAle := ltn_neqAle. Let gtn_neqAge x y : (y < x) = (x != y) && (y <= x). Proof. by rewrite ltn_neqAle eq_sym. Qed. Let anti_leq := anti_leq. Let anti_geq : antisymmetric geq. Proof. by move=> m n /=; rewrite andbC => /anti_leq. Qed. Let leq_total := leq_total. Lemma ltnW_homo : {homo f : m n / m < n} -> {homo f : m n / m <= n}. Proof. exact: homoW. Qed. Lemma inj_homo_ltn : injective f -> {homo f : m n / m <= n} -> {homo f : m n / m < n}. Proof. exact: inj_homo. Qed. Lemma ltnW_nhomo : {homo f : m n /~ m < n} -> {homo f : m n /~ m <= n}. Proof. exact: homoW. Qed. Lemma inj_nhomo_ltn : injective f -> {homo f : m n /~ m <= n} -> {homo f : m n /~ m < n}. Proof. exact: inj_homo. Qed. Lemma incn_inj : {mono f : m n / m <= n} -> injective f. Proof. exact: mono_inj. Qed. Lemma decn_inj : {mono f : m n /~ m <= n} -> injective f. Proof. exact: mono_inj. Qed. Lemma leqW_mono : {mono f : m n / m <= n} -> {mono f : m n / m < n}. Proof. exact: anti_mono. Qed. Lemma leqW_nmono : {mono f : m n /~ m <= n} -> {mono f : m n /~ m < n}. Proof. exact: anti_mono. Qed. Lemma leq_mono : {homo f : m n / m < n} -> {mono f : m n / m <= n}. Proof. exact: total_homo_mono. Qed. Lemma leq_nmono : {homo f : m n /~ m < n} -> {mono f : m n /~ m <= n}. Proof. exact: total_homo_mono. Qed. Variables (D D' : {pred nat}). Lemma ltnW_homo_in : {in D & D', {homo f : m n / m < n}} -> {in D & D', {homo f : m n / m <= n}}. Proof. exact: homoW_in. Qed. Lemma ltnW_nhomo_in : {in D & D', {homo f : m n /~ m < n}} -> {in D & D', {homo f : m n /~ m <= n}}. Proof. exact: homoW_in. Qed. Lemma inj_homo_ltn_in : {in D & D', injective f} -> {in D & D', {homo f : m n / m <= n}} -> {in D & D', {homo f : m n / m < n}}. Proof. exact: inj_homo_in. Qed. Lemma inj_nhomo_ltn_in : {in D & D', injective f} -> {in D & D', {homo f : m n /~ m <= n}} -> {in D & D', {homo f : m n /~ m < n}}. Proof. exact: inj_homo_in. Qed. Lemma incn_inj_in : {in D &, {mono f : m n / m <= n}} -> {in D &, injective f}. Proof. exact: mono_inj_in. Qed. Lemma decn_inj_in : {in D &, {mono f : m n /~ m <= n}} -> {in D &, injective f}. Proof. exact: mono_inj_in. Qed. Lemma leqW_mono_in : {in D &, {mono f : m n / m <= n}} -> {in D &, {mono f : m n / m < n}}. Proof. exact: anti_mono_in. Qed. Lemma leqW_nmono_in : {in D &, {mono f : m n /~ m <= n}} -> {in D &, {mono f : m n /~ m < n}}. Proof. exact: anti_mono_in. Qed. Lemma leq_mono_in : {in D &, {homo f : m n / m < n}} -> {in D &, {mono f : m n / m <= n}}. Proof. exact: total_homo_mono_in. Qed. Lemma leq_nmono_in : {in D &, {homo f : m n /~ m < n}} -> {in D &, {mono f : m n /~ m <= n}}. Proof. exact: total_homo_mono_in. Qed. End NatToNat. End Monotonicity. Lemma leq_pfact : {in [pred n | 0 < n] &, {mono factorial : m n / m <= n}}. Proof. by apply: leq_mono_in => n m n0 m0; apply: ltn_fact. Qed. Lemma leq_fact : {homo factorial : m n / m <= n}. Proof. by move=> [m|m n mn]; rewrite ?fact_gt0// leq_pfact// inE (leq_trans _ mn). Qed. Lemma ltn_pfact : {in [pred n | 0 < n] &, {mono factorial : m n / m < n}}. Proof. exact/leqW_mono_in/leq_pfact. Qed. (* Support for larger integers. The normal definitions of +, - and even *) (* IO are unsuitable for Peano integers larger than 2000 or so because *) (* they are not tail-recursive. We provide a workaround module, along *) (* with a rewrite multirule to change the tailrec operators to the *) (* normal ones. We handle IO via the NatBin module, but provide our *) (* own (more efficient) conversion functions. *) Module NatTrec. (* Usage: *) (* Import NatTrec. *) (* in section defining functions, rebinds all *) (* non-tail recursive operators. *) (* rewrite !trecE. *) (* in the correctness proof, restores operators *) Fixpoint add m n := if m is m'.+1 then m' + n.+1 else n where "n + m" := (add n m) : nat_scope. Fixpoint add_mul m n s := if m is m'.+1 then add_mul m' n (n + s) else s. Definition mul m n := if m is m'.+1 then add_mul m' n n else 0. Notation "n * m" := (mul n m) : nat_scope. Fixpoint mul_exp m n p := if n is n'.+1 then mul_exp m n' (m * p) else p. Definition exp m n := if n is n'.+1 then mul_exp m n' m else 1. Notation "n ^ m" := (exp n m) : nat_scope. Local Notation oddn := odd. Fixpoint odd n := if n is n'.+2 then odd n' else eqn n 1. Local Notation doublen := double. Definition double n := if n is n'.+1 then n' + n.+1 else 0. Notation "n .*2" := (double n) : nat_scope. Lemma addE : add =2 addn. Proof. by elim=> //= n IHn m; rewrite IHn addSnnS. Qed. Lemma doubleE : double =1 doublen. Proof. by case=> // n; rewrite -addnn -addE. Qed. Lemma add_mulE n m s : add_mul n m s = addn (muln n m) s. Proof. by elim: n => //= n IHn in m s *; rewrite IHn addE addnCA addnA. Qed. Lemma mulE : mul =2 muln. Proof. by case=> //= n m; rewrite add_mulE addnC. Qed. Lemma mul_expE m n p : mul_exp m n p = muln (expn m n) p. Proof. by elim: n => [|n IHn] in p *; rewrite ?mul1n //= expnS IHn mulE mulnCA mulnA. Qed. Lemma expE : exp =2 expn. Proof. by move=> m [|n] //=; rewrite mul_expE expnS mulnC. Qed. Lemma oddE : odd =1 oddn. Proof. move=> n; rewrite -[n in LHS]odd_double_half addnC. by elim: n./2 => //=; case (oddn n). Qed. Definition trecE := (addE, (doubleE, oddE), (mulE, add_mulE, (expE, mul_expE))). End NatTrec. Notation natTrecE := NatTrec.trecE. Definition N_eqb n m := match n, m with | N0, N0 => true | Npos p, Npos q => Pos.eqb p q | _, _ => false end. Lemma eq_binP : Equality.axiom N_eqb. Proof. move=> p q; apply: (iffP idP) => [|<-]; last by case: p => //; elim. by case: q; case: p => //; elim=> [p IHp|p IHp|] [q|q|] //= /IHp [->]. Qed. HB.instance Definition _ := hasDecEq.Build N eq_binP. Arguments N_eqb !n !m. Section NumberInterpretation. Section Trec. Import NatTrec. Fixpoint nat_of_pos p0 := match p0 with | xO p => (nat_of_pos p).*2 | xI p => (nat_of_pos p).*2.+1 | xH => 1 end. End Trec. Local Coercion nat_of_pos : positive >-> nat. Coercion nat_of_bin b := if b is Npos p then p : nat else 0. Fixpoint pos_of_nat n0 m0 := match n0, m0 with | n.+1, m.+2 => pos_of_nat n m | n.+1, 1 => xO (pos_of_nat n n) | n.+1, 0 => xI (pos_of_nat n n) | 0, _ => xH end. Definition bin_of_nat n0 := if n0 is n.+1 then Npos (pos_of_nat n n) else N0. Lemma bin_of_natK : cancel bin_of_nat nat_of_bin. Proof. have sub2nn n : n.*2 - n = n by rewrite -addnn addKn. case=> //= n; rewrite -[n in RHS]sub2nn. by elim: n {2 4}n => // m IHm [|[|n]] //=; rewrite IHm // natTrecE sub2nn. Qed. Lemma nat_of_binK : cancel nat_of_bin bin_of_nat. Proof. case=> //=; elim=> //= p; case: (nat_of_pos p) => //= n [<-]. by rewrite natTrecE !addnS {2}addnn; elim: {1 3}n. by rewrite natTrecE addnS /= addnS {2}addnn; elim: {1 3}n. Qed. Lemma nat_of_succ_pos p : Pos.succ p = p.+1 :> nat. Proof. by elim: p => //= p ->; rewrite !natTrecE. Qed. Lemma nat_of_add_pos p q : Pos.add p q = p + q :> nat. Proof. apply: @fst _ (Pos.add_carry p q = (p + q).+1 :> nat) _. elim: p q => [p IHp|p IHp|] [q|q|] //=; rewrite !natTrecE //; by rewrite ?IHp ?nat_of_succ_pos ?(doubleS, doubleD, addn1, addnS). Qed. Lemma nat_of_mul_pos p q : Pos.mul p q = p * q :> nat. Proof. elim: p => [p IHp|p IHp|] /=; rewrite ?mul1n //; by rewrite ?nat_of_add_pos /= !natTrecE IHp doubleMl. Qed. End NumberInterpretation. (* Big(ger) nat IO; usage: *) (* Num 1 072 399 *) (* to create large numbers for test cases *) (* Eval compute in [Num of some expression] *) (* to display the result of an expression that *) (* returns a larger integer. *) Record number : Type := Num {bin_of_number :> N}. Definition number_subType := Eval hnf in [isNew for bin_of_number]. HB.instance Definition _ := number_subType. HB.instance Definition _ := [Equality of number by <:]. Notation "[ 'Num' 'of' e ]" := (Num (bin_of_nat e)) (format "[ 'Num' 'of' e ]") : nat_scope. (* A congruence tactic, similar to the boolean one, along with an .+1/+ *) (* normalization tactic. *) Fixpoint pop_succn e := if e is e'.+1 then fun n => pop_succn e' n.+1 else id. Ltac pop_succn e := eval lazy beta iota delta [pop_succn] in (pop_succn e 1). Ltac succn_to_add := match goal with | |- context G [?e.+1] => let x := fresh "NatLit0" in match pop_succn e with | ?n.+1 => pose x := n.+1; let G' := context G [x] in change G' | _ ?e' ?n => pose x := n; let G' := context G [x + e'] in change G' end; succn_to_add; rewrite {}/x | _ => idtac end. Ltac nat_norm := succn_to_add; rewrite ?add0n ?addn0 -?addnA ?(addSn, addnS, add0n, addn0). Ltac nat_congr := first [ apply: (congr1 succn _) | apply: (congr1 predn _) | apply: (congr1 (addn _) _) | apply: (congr1 (subn _) _) | apply: (congr1 (addn^~ _) _) | match goal with |- (?X1 + ?X2 = ?X3) => symmetry; rewrite -1?(addnC X1) -?(addnCA X1); apply: (congr1 (addn X1) _); symmetry end ].
WithDensityFinite.lean
/- Copyright (c) 2024 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import Mathlib.LinearAlgebra.FreeModule.Basic import Mathlib.MeasureTheory.Measure.Decomposition.Exhaustion import Mathlib.Probability.ConditionalProbability /-! # s-finite measures can be written as `withDensity` of a finite measure If `μ` is an s-finite measure, then there exists a finite measure `μ.toFinite` such that a set is `μ`-null iff it is `μ.toFinite`-null. In particular, `MeasureTheory.ae μ.toFinite = MeasureTheory.ae μ` and `μ.toFinite = 0` iff `μ = 0`. As a corollary, `μ` can be represented as `μ.toFinite.withDensity (μ.rnDeriv μ.toFinite)`. Our definition of `MeasureTheory.Measure.toFinite` ensures some extra properties: - if `μ` is a finite measure, then `μ.toFinite = μ[|univ] = (μ univ)⁻¹ • μ`; - in particular, `μ.toFinite = μ` for a probability measure; - if `μ ≠ 0`, then `μ.toFinite` is a probability measure. ## Main definitions In these definitions and the results below, `μ` is an s-finite measure (`SFinite μ`). * `MeasureTheory.Measure.toFinite`: a finite measure with `μ ≪ μ.toFinite` and `μ.toFinite ≪ μ`. If `μ ≠ 0`, this is a probability measure. * `MeasureTheory.Measure.densityToFinite` (deprecated, use `MeasureTheory.Measure.rnDeriv`): the Radon-Nikodym derivative of `μ.toFinite` with respect to `μ`. ## Main statements * `absolutelyContinuous_toFinite`: `μ ≪ μ.toFinite`. * `toFinite_absolutelyContinuous`: `μ.toFinite ≪ μ`. * `ae_toFinite`: `ae μ.toFinite = ae μ`. -/ open Set open scoped ENNReal ProbabilityTheory namespace MeasureTheory variable {α : Type*} {mα : MeasurableSpace α} {μ : Measure α} /-- Auxiliary definition for `MeasureTheory.Measure.toFinite`. -/ noncomputable def Measure.toFiniteAux (μ : Measure α) [SFinite μ] : Measure α := letI := Classical.dec if IsFiniteMeasure μ then μ else (exists_isFiniteMeasure_absolutelyContinuous μ).choose /-- A finite measure obtained from an s-finite measure `μ`, such that `μ = μ.toFinite.withDensity μ.densityToFinite` (see `withDensity_densitytoFinite`). If `μ` is non-zero, this is a probability measure. -/ noncomputable def Measure.toFinite (μ : Measure α) [SFinite μ] : Measure α := μ.toFiniteAux[|univ] @[local simp] lemma ae_toFiniteAux [SFinite μ] : ae μ.toFiniteAux = ae μ := by rw [Measure.toFiniteAux] split_ifs · simp · obtain ⟨_, h₁, h₂⟩ := (exists_isFiniteMeasure_absolutelyContinuous μ).choose_spec exact h₂.ae_le.antisymm h₁.ae_le @[local instance] theorem isFiniteMeasure_toFiniteAux [SFinite μ] : IsFiniteMeasure μ.toFiniteAux := by rw [Measure.toFiniteAux] split_ifs · assumption · exact (exists_isFiniteMeasure_absolutelyContinuous μ).choose_spec.1 @[simp] lemma ae_toFinite [SFinite μ] : ae μ.toFinite = ae μ := by simp [Measure.toFinite, ProbabilityTheory.cond] @[simp] lemma toFinite_apply_eq_zero_iff [SFinite μ] {s : Set α} : μ.toFinite s = 0 ↔ μ s = 0 := by simp only [← compl_mem_ae_iff, ae_toFinite] @[simp] lemma toFinite_eq_zero_iff [SFinite μ] : μ.toFinite = 0 ↔ μ = 0 := by simp_rw [← Measure.measure_univ_eq_zero, toFinite_apply_eq_zero_iff] @[simp] lemma toFinite_zero : Measure.toFinite (0 : Measure α) = 0 := by simp lemma toFinite_eq_self [IsProbabilityMeasure μ] : μ.toFinite = μ := by rw [Measure.toFinite, Measure.toFiniteAux, if_pos, ProbabilityTheory.cond_univ] infer_instance instance [SFinite μ] : IsFiniteMeasure μ.toFinite := by rw [Measure.toFinite] infer_instance instance [SFinite μ] [NeZero μ] : IsProbabilityMeasure μ.toFinite := by apply ProbabilityTheory.cond_isProbabilityMeasure simp [ne_eq, ← compl_mem_ae_iff, ae_toFiniteAux] lemma absolutelyContinuous_toFinite (μ : Measure α) [SFinite μ] : μ ≪ μ.toFinite := Measure.ae_le_iff_absolutelyContinuous.mp ae_toFinite.ge lemma sfiniteSeq_absolutelyContinuous_toFinite (μ : Measure α) [SFinite μ] (n : ℕ) : sfiniteSeq μ n ≪ μ.toFinite := (sfiniteSeq_le μ n).absolutelyContinuous.trans (absolutelyContinuous_toFinite μ) lemma toFinite_absolutelyContinuous (μ : Measure α) [SFinite μ] : μ.toFinite ≪ μ := Measure.ae_le_iff_absolutelyContinuous.mp ae_toFinite.le lemma restrict_compl_sigmaFiniteSet [SFinite μ] : μ.restrict μ.sigmaFiniteSetᶜ = ∞ • μ.toFinite.restrict μ.sigmaFiniteSetᶜ := by rw [Measure.sigmaFiniteSet, restrict_compl_sigmaFiniteSetWRT (Measure.AbsolutelyContinuous.refl μ)] ext t ht simp only [Measure.smul_apply, smul_eq_mul] rw [Measure.restrict_apply ht, Measure.restrict_apply ht] by_cases hμt : μ (t ∩ (μ.sigmaFiniteSetWRT μ)ᶜ) = 0 · rw [hμt, toFinite_absolutelyContinuous μ hμt] · rw [ENNReal.top_mul hμt, ENNReal.top_mul] exact fun h ↦ hμt (absolutelyContinuous_toFinite μ h) end MeasureTheory
orderedzmod.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import ssrAC div fintype path bigop order finset fingroup. From mathcomp Require Import ssralg poly. (******************************************************************************) (* Number structures *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file defines some classes to manipulate number structures, i.e, *) (* structures with an order and a norm. To use this file, insert *) (* "Import Num.Theory." before your scripts. You can also "Import Num.Def." *) (* to enjoy shorter notations (e.g., minr instead of Num.min, lerif instead *) (* of Num.leif, etc.). *) (* *) (* This file defines the following number structures: *) (* *) (* porderZmodType == join of Order.POrder and GRing.Zmodule *) (* The HB class is called POrderedZmodule. *) (* *) (* The ordering symbols and notations (<, <=, >, >=, _ <= _ ?= iff _, *) (* _ < _ ?<= if _, >=<, and ><) and lattice operations (meet and join) *) (* defined in order.v are redefined for the ring_display in the ring_scope *) (* (%R). 0-ary ordering symbols for the ring_display have the suffix "%R", *) (* e.g., <%R. All the other ordering notations are the same as order.v. *) (* *) (* Over these structures, we have the following operations: *) (* x \is a Num.pos <=> x is positive (:= x > 0) *) (* x \is a Num.neg <=> x is negative (:= x < 0) *) (* x \is a Num.nneg <=> x is positive or 0 (:= x >= 0) *) (* x \is a Num.npos <=> x is negative or 0 (:= x <= 0) *) (* x \is a Num.real <=> x is real (:= x >= 0 or x < 0) *) (* *) (* - list of prefixes : *) (* p : positive *) (* n : negative *) (* sp : strictly positive *) (* sn : strictly negative *) (* i : interior = in [0, 1] or ]0, 1[ *) (* e : exterior = in [1, +oo[ or ]1; +oo[ *) (* w : non strict (weak) monotony *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "n .-root" (format "n .-root"). Reserved Notation "'i". Reserved Notation "'Re z" (at level 10, z at level 8). Reserved Notation "'Im z" (at level 10, z at level 8). Local Open Scope order_scope. Local Open Scope group_scope. Local Open Scope ring_scope. Import Order.TTheory GRing.Theory. Fact ring_display : Order.disp_t. Proof. exact. Qed. Module Num. #[short(type="porderZmodType")] HB.structure Definition POrderedZmodule := { R of Order.isPOrder ring_display R & GRing.Zmodule R }. Module Export Def. Notation ler := (@Order.le ring_display _) (only parsing). Notation "@ 'ler' R" := (@Order.le ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation ltr := (@Order.lt ring_display _) (only parsing). Notation "@ 'ltr' R" := (@Order.lt ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation ger := (@Order.ge ring_display _) (only parsing). Notation "@ 'ger' R" := (@Order.ge ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation gtr := (@Order.gt ring_display _) (only parsing). Notation "@ 'gtr' R" := (@Order.gt ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation lerif := (@Order.leif ring_display _) (only parsing). Notation "@ 'lerif' R" := (@Order.leif ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation lterif := (@Order.lteif ring_display _) (only parsing). Notation "@ 'lteif' R" := (@Order.lteif ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation comparabler := (@Order.comparable ring_display _) (only parsing). Notation "@ 'comparabler' R" := (@Order.comparable ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation maxr := (@Order.max ring_display _). Notation "@ 'maxr' R" := (@Order.max ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation minr := (@Order.min ring_display _). Notation "@ 'minr' R" := (@Order.min ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Section Def. Context {R : porderZmodType}. Definition Rpos_pred := fun x : R => 0 < x. Definition Rpos : qualifier 0 R := [qualify x | Rpos_pred x]. Definition Rneg_pred := fun x : R => x < 0. Definition Rneg : qualifier 0 R := [qualify x : R | Rneg_pred x]. Definition Rnneg_pred := fun x : R => 0 <= x. Definition Rnneg : qualifier 0 R := [qualify x : R | Rnneg_pred x]. Definition Rnpos_pred := fun x : R => x <= 0. Definition Rnpos : qualifier 0 R := [qualify x : R | Rnpos_pred x]. Definition Rreal_pred := fun x : R => (0 <= x) || (x <= 0). Definition Rreal : qualifier 0 R := [qualify x : R | Rreal_pred x]. End Def. Arguments Rpos_pred _ _ /. Arguments Rneg_pred _ _ /. Arguments Rnneg_pred _ _ /. Arguments Rreal_pred _ _ /. End Def. (* Shorter qualified names, when Num.Def is not imported. *) Notation le := ler (only parsing). Notation lt := ltr (only parsing). Notation ge := ger (only parsing). Notation gt := gtr (only parsing). Notation leif := lerif (only parsing). Notation lteif := lterif (only parsing). Notation comparable := comparabler (only parsing). Notation max := maxr. Notation min := minr. Notation pos := Rpos. Notation neg := Rneg. Notation nneg := Rnneg. Notation npos := Rnpos. Notation real := Rreal. (* (Exported) symbolic syntax. *) Module Import Syntax. Notation "<=%R" := le : function_scope. Notation ">=%R" := ge : function_scope. Notation "<%R" := lt : function_scope. Notation ">%R" := gt : function_scope. Notation "<?=%R" := leif : function_scope. Notation "<?<=%R" := lteif : function_scope. Notation ">=<%R" := comparable : function_scope. Notation "><%R" := (fun x y => ~~ (comparable x y)) : function_scope. Notation "<= y" := (ge y) : ring_scope. Notation "<= y :> T" := (<= (y : T)) (only parsing) : ring_scope. Notation ">= y" := (le y) : ring_scope. Notation ">= y :> T" := (>= (y : T)) (only parsing) : ring_scope. Notation "< y" := (gt y) : ring_scope. Notation "< y :> T" := (< (y : T)) (only parsing) : ring_scope. Notation "> y" := (lt y) : ring_scope. Notation "> y :> T" := (> (y : T)) (only parsing) : ring_scope. Notation "x <= y" := (le x y) : ring_scope. Notation "x <= y :> T" := ((x : T) <= (y : T)) (only parsing) : ring_scope. Notation "x >= y" := (y <= x) (only parsing) : ring_scope. Notation "x >= y :> T" := ((x : T) >= (y : T)) (only parsing) : ring_scope. Notation "x < y" := (lt x y) : ring_scope. Notation "x < y :> T" := ((x : T) < (y : T)) (only parsing) : ring_scope. Notation "x > y" := (y < x) (only parsing) : ring_scope. Notation "x > y :> T" := ((x : T) > (y : T)) (only parsing) : ring_scope. Notation "x <= y <= z" := ((x <= y) && (y <= z)) : ring_scope. Notation "x < y <= z" := ((x < y) && (y <= z)) : ring_scope. Notation "x <= y < z" := ((x <= y) && (y < z)) : ring_scope. Notation "x < y < z" := ((x < y) && (y < z)) : ring_scope. Notation "x <= y ?= 'iff' C" := (lerif x y C) : ring_scope. Notation "x <= y ?= 'iff' C :> R" := ((x : R) <= (y : R) ?= iff C) (only parsing) : ring_scope. Notation "x < y ?<= 'if' C" := (lterif x y C) : ring_scope. Notation "x < y ?<= 'if' C :> R" := ((x : R) < (y : R) ?<= if C) (only parsing) : ring_scope. Notation ">=< y" := [pred x | comparable x y] : ring_scope. Notation ">=< y :> T" := (>=< (y : T)) (only parsing) : ring_scope. Notation "x >=< y" := (comparable x y) : ring_scope. Notation ">< y" := [pred x | ~~ comparable x y] : ring_scope. Notation ">< y :> T" := (>< (y : T)) (only parsing) : ring_scope. Notation "x >< y" := (~~ (comparable x y)) : ring_scope. Export Order.PreOCoercions. End Syntax. Module Export Theory. End Theory. Module Exports. HB.reexport. End Exports. End Num. Export Num.Syntax Num.Exports.
FullSubcategory.lean
/- Copyright (c) 2017 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison, Reid Barton, Joël Riou -/ import Mathlib.CategoryTheory.InducedCategory import Mathlib.CategoryTheory.ObjectProperty.Basic /-! # The full subcategory associated to a property of objects Given a category `C` and `P : ObjectProperty C`, we define a category structure on the type `P.FullSubcategory` of objects in `C` satisfying `P`. -/ universe v v' u u' namespace CategoryTheory namespace ObjectProperty variable {C : Type u} [Category.{v} C] section variable (P : ObjectProperty C) /-- A subtype-like structure for full subcategories. Morphisms just ignore the property. We don't use actual subtypes since the simp-normal form `↑X` of `X.val` does not work well for full subcategories. -/ @[ext, stacks 001D "We do not define 'strictly full' subcategories."] structure FullSubcategory where /-- The category of which this is a full subcategory -/ obj : C /-- The predicate satisfied by all objects in this subcategory -/ property : P obj instance FullSubcategory.category : Category.{v} P.FullSubcategory := InducedCategory.category FullSubcategory.obj -- these lemmas are not particularly well-typed, so would probably be dangerous as simp lemmas lemma FullSubcategory.id_def (X : P.FullSubcategory) : 𝟙 X = 𝟙 X.obj := rfl lemma FullSubcategory.comp_def {X Y Z : P.FullSubcategory} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = (f ≫ g : X.obj ⟶ Z.obj) := rfl /-- The forgetful functor from a full subcategory into the original category ("forgetting" the condition). -/ def ι : P.FullSubcategory ⥤ C := inducedFunctor FullSubcategory.obj @[simp] theorem ι_obj {X} : P.ι.obj X = X.obj := rfl @[simp] theorem ι_map {X Y} {f : X ⟶ Y} : P.ι.map f = f := rfl /-- The inclusion of a full subcategory is fully faithful. -/ abbrev fullyFaithfulι : P.ι.FullyFaithful := fullyFaithfulInducedFunctor _ instance full_ι : P.ι.Full := P.fullyFaithfulι.full instance faithful_ι : P.ι.Faithful := P.fullyFaithfulι.faithful /-- Constructor for isomorphisms in `P.FullSubcategory` when `P : ObjectProperty C`. -/ @[simps] def isoMk {X Y : P.FullSubcategory} (e : P.ι.obj X ≅ P.ι.obj Y) : X ≅ Y where hom := e.hom inv := e.inv hom_inv_id := e.hom_inv_id inv_hom_id := e.inv_hom_id variable {P} {P' : ObjectProperty C} /-- If `P` and `P'` are properties of objects such that `P ≤ P'`, there is an induced functor `P.FullSubcategory ⥤ P'.FullSubcategory`. -/ @[simps] def ιOfLE (h : P ≤ P') : P.FullSubcategory ⥤ P'.FullSubcategory where obj X := ⟨X.1, h _ X.2⟩ map f := f /-- If `h : P ≤ P'`, then `ιOfLE h` is fully faithful. -/ def fullyFaithfulιOfLE (h : P ≤ P') : (ιOfLE h).FullyFaithful where preimage f := f instance full_ιOfLE (h : P ≤ P') : (ιOfLE h).Full := (fullyFaithfulιOfLE h).full instance faithful_ιOfLE (h : P ≤ P') : (ιOfLE h).Faithful := (fullyFaithfulιOfLE h).faithful @[deprecated "use ιOfLECompιIso" (since := "2025-03-04")] theorem FullSubcategory.map_inclusion (h : P ≤ P') : ιOfLE h ⋙ P'.ι = P.ι := rfl /-- If `h : P ≤ P'` is an inequality of properties of objects, this is the obvious isomorphism `ιOfLE h ⋙ P'.ι ≅ P.ι`. -/ def ιOfLECompιIso (h : P ≤ P') : ιOfLE h ⋙ P'.ι ≅ P.ι := Iso.refl _ end section lift variable {D : Type u'} [Category.{v'} D] (P Q : ObjectProperty D) (F : C ⥤ D) (hF : ∀ X, P (F.obj X)) /-- A functor which maps objects to objects satisfying a certain property induces a lift through the full subcategory of objects satisfying that property. -/ @[simps] def lift : C ⥤ FullSubcategory P where obj X := ⟨F.obj X, hF X⟩ map f := F.map f @[deprecated "use liftCompιIso" (since := "2025-03-04")] theorem FullSubcategory.lift_comp_inclusion_eq : P.lift F hF ⋙ P.ι = F := rfl /-- Composing the lift of a functor through a full subcategory with the inclusion yields the original functor. This is actually true definitionally. -/ def liftCompιIso : P.lift F hF ⋙ P.ι ≅ F := Iso.refl _ @[simp] lemma ι_obj_lift_obj (X : C) : P.ι.obj ((P.lift F hF).obj X) = F.obj X := rfl @[simp] lemma ι_obj_lift_map {X Y : C} (f : X ⟶ Y) : P.ι.map ((P.lift F hF).map f) = F.map f := rfl instance [F.Faithful] : (P.lift F hF).Faithful := Functor.Faithful.of_comp_iso (P.liftCompιIso F hF) instance [F.Full] : (P.lift F hF).Full := Functor.Full.of_comp_faithful_iso (P.liftCompιIso F hF) variable {Q} /-- When `h : P ≤ Q`, this is the canonical isomorphism `P.lift F hF ⋙ ιOfLE h ≅ Q.lift F _`. -/ def liftCompιOfLEIso (h : P ≤ Q) : P.lift F hF ⋙ ιOfLE h ≅ Q.lift F (fun X ↦ h _ (hF X)) := Iso.refl _ @[deprecated "Use liftCompιOfLEIso" (since := "2025-03-04")] theorem FullSubcategory.lift_comp_map (h : P ≤ Q) : P.lift F hF ⋙ ιOfLE h = Q.lift F (fun X ↦ h _ (hF X)) := rfl end lift end ObjectProperty @[deprecated (since := "2025-03-04")] alias FullSubcategory := ObjectProperty.FullSubcategory @[deprecated (since := "2025-03-04")] alias fullSubcategoryInclusion := ObjectProperty.ι @[deprecated (since := "2025-03-04")] alias fullSubcategoryInclusion.obj := ObjectProperty.ι_obj @[deprecated (since := "2025-03-04")] alias fullSubcategoryInclusion.map := ObjectProperty.ι_map @[deprecated (since := "2025-03-04")] alias fullyFaithfulFullSubcategoryInclusion := ObjectProperty.fullyFaithfulι @[deprecated (since := "2025-03-04")] alias FullSubcategory.map := ObjectProperty.ιOfLE @[deprecated (since := "2025-03-04")] alias FullSubcategory.lift := ObjectProperty.lift @[deprecated (since := "2025-03-04")] alias FullSubcategory.lift_comp_inclusion := ObjectProperty.liftCompιIso @[deprecated (since := "2025-03-04")] alias fullSubcategoryInclusion_obj_lift_obj := ObjectProperty.ι_obj_lift_obj @[deprecated (since := "2025-03-04")] alias fullSubcategoryInclusion_map_lift_map := ObjectProperty.ι_obj_lift_map end CategoryTheory
fraction.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq. From mathcomp Require Import ssrAC choice tuple bigop ssralg poly polydiv. From mathcomp Require Import generic_quotient. (******************************************************************************) (* Field of fraction of an integral domain *) (* *) (* This file builds the field of fraction of any integral domain. The main *) (* result of this file is the existence of the field and of the tofrac *) (* function which is a injective ring morphism from R to its fraction field *) (* {fraction R}. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory. Local Open Scope ring_scope. Local Open Scope quotient_scope. Reserved Notation "{ 'ratio' T }" (format "{ 'ratio' T }"). Reserved Notation "{ 'fraction' T }" (format "{ 'fraction' T }"). Reserved Notation "x %:F" (format "x %:F"). Section FracDomain. Variable R : nzRingType. (* ratios are pairs of R, such that the second member is nonzero *) Inductive ratio := mkRatio { frac :> R * R; _ : frac.2 != 0 }. HB.instance Definition _ := [isSub for frac]. HB.instance Definition _ := [Choice of ratio by <:]. Lemma denom_ratioP : forall f : ratio, f.2 != 0. Proof. by case. Qed. Definition ratio0 := (@mkRatio (0, 1) (oner_neq0 _)). Definition Ratio x y : ratio := insubd ratio0 (x, y). Lemma numer_Ratio x y : y != 0 -> (Ratio x y).1 = x. Proof. by move=> ny0; rewrite /Ratio /insubd insubT. Qed. Lemma denom_Ratio x y : y != 0 -> (Ratio x y).2 = y. Proof. by move=> ny0; rewrite /Ratio /insubd insubT. Qed. Definition numden_Ratio := (numer_Ratio, denom_Ratio). Variant Ratio_spec (n d : R) : ratio -> R -> R -> Type := | RatioNull of d = 0 : Ratio_spec n d ratio0 n 0 | RatioNonNull (d_neq0 : d != 0) : Ratio_spec n d (@mkRatio (n, d) d_neq0) n d. Lemma RatioP n d : Ratio_spec n d (Ratio n d) n d. Proof. rewrite /Ratio /insubd; case: insubP=> /= [x /= d_neq0 hx|]. have ->: x = @mkRatio (n, d) d_neq0 by apply: val_inj. by constructor. by rewrite negbK=> /eqP hx; rewrite {2}hx; constructor. Qed. Lemma Ratio0 x : Ratio x 0 = ratio0. Proof. by rewrite /Ratio /insubd; case: insubP; rewrite //= eqxx. Qed. End FracDomain. Arguments ratio R%_type. Notation "{ 'ratio' T }" := (ratio T) : type_scope. Notation "'\n_' x" := (frac x).1 (at level 8, x at level 2, format "'\n_' x"). Notation "'\d_' x" := (frac x).2 (at level 8, x at level 2, format "'\d_' x"). Module FracField. Section FracField. Variable R : idomainType. Local Notation frac := (R * R). Local Notation dom := (ratio R). Local Notation domP := denom_ratioP. Implicit Types x y z : dom. (* We define a relation in ratios *) Local Notation equivf_notation x y := (\n_x * \d_y == \d_x * \n_y). Definition equivf x y := equivf_notation x y. Lemma equivfE x y : equivf x y = equivf_notation x y. Proof. by []. Qed. Lemma equivf_refl : reflexive equivf. Proof. by move=> x; rewrite /equivf mulrC. Qed. Lemma equivf_sym : symmetric equivf. Proof. by move=> x y; rewrite /equivf eq_sym; congr (_==_); rewrite mulrC. Qed. Lemma equivf_trans : transitive equivf. Proof. move=> [x Px] [y Py] [z Pz]; rewrite /equivf /= mulrC => /eqP xy /eqP yz. by rewrite -(inj_eq (mulfI Px)) mulrA xy -mulrA yz mulrCA. Qed. (* we show that equivf is an equivalence *) Canonical equivf_equiv := EquivRel equivf equivf_refl equivf_sym equivf_trans. Definition type := {eq_quot equivf}. (* we recover some structure for the quotient *) HB.instance Definition _ : EqQuotient _ equivf type := EqQuotient.on type. HB.instance Definition _ := Choice.on type. (* we explain what was the equivalence on the quotient *) Lemma equivf_def (x y : ratio R) : x == y %[mod type] = (\n_x * \d_y == \d_x * \n_y). Proof. by rewrite eqmodE. Qed. Lemma equivf_r x : \n_x * \d_(repr (\pi_type x)) = \d_x * \n_(repr (\pi_type x)). Proof. by apply/eqP; rewrite -equivf_def reprK. Qed. Lemma equivf_l x : \n_(repr (\pi_type x)) * \d_x = \d_(repr (\pi_type x)) * \n_x. Proof. by apply/eqP; rewrite -equivf_def reprK. Qed. Lemma numer0 x : (\n_x == 0) = (x == (ratio0 R) %[mod_eq equivf]). Proof. by rewrite eqmodE /= !equivfE // mulr1 mulr0. Qed. Lemma Ratio_numden : forall x, Ratio \n_x \d_x = x. Proof. case=> [[n d] /= nd]; rewrite /Ratio /insubd; apply: val_inj=> /=. by case: insubP=> //=; rewrite nd. Qed. Definition tofrac := lift_embed type (fun x : R => Ratio x 1). Canonical tofrac_pi_morph := PiEmbed tofrac. Notation "x %:F" := (@tofrac x). Implicit Types a b c : type. Definition addf x y : dom := Ratio (\n_x * \d_y + \n_y * \d_x) (\d_x * \d_y). Definition add := lift_op2 type addf. Lemma pi_add : {morph \pi : x y / addf x y >-> add x y}. Proof. move=> x y; unlock add; apply/eqmodP; rewrite /= equivfE /addf /=. rewrite !numden_Ratio ?mulf_neq0 ?domP // mulrDr mulrDl; apply/eqP. symmetry; rewrite (AC (2*2) (3*1*2*4)) (AC (2*2) (3*2*1*4))/=. by rewrite !equivf_l (ACl ((2*3)*(1*4))) (ACl ((2*3)*(4*1)))/=. Qed. Canonical pi_add_morph := PiMorph2 pi_add. Definition oppf x : dom := Ratio (- \n_x) \d_x. Definition opp := lift_op1 type oppf. Lemma pi_opp : {morph \pi : x / oppf x >-> opp x}. Proof. move=> x; unlock opp; apply/eqmodP; rewrite /= /equivf /oppf /=. by rewrite !numden_Ratio ?(domP,mulf_neq0) // mulNr mulrN -equivf_r. Qed. Canonical pi_opp_morph := PiMorph1 pi_opp. Definition mulf x y : dom := Ratio (\n_x * \n_y) (\d_x * \d_y). Definition mul := lift_op2 type mulf. Lemma pi_mul : {morph \pi : x y / mulf x y >-> mul x y}. Proof. move=> x y; unlock mul; apply/eqmodP=> /=. rewrite equivfE /= /addf /= !numden_Ratio ?mulf_neq0 ?domP //. by rewrite mulrACA !equivf_r mulrACA. Qed. Canonical pi_mul_morph := PiMorph2 pi_mul. Definition invf x : dom := Ratio \d_x \n_x. Definition inv := lift_op1 type invf. Lemma pi_inv : {morph \pi : x / invf x >-> inv x}. Proof. move=> x; unlock inv; apply/eqmodP=> /=; rewrite equivfE /invf eq_sym. do 2?case: RatioP=> /= [/eqP|]; rewrite ?mul0r ?mul1r -?equivf_def ?numer0 ?reprK //. by move=> hx /eqP hx'; rewrite hx' eqxx in hx. by move=> /eqP ->; rewrite eqxx. Qed. Canonical pi_inv_morph := PiMorph1 pi_inv. Lemma addA : associative add. Proof. elim/quotW=> x; elim/quotW=> y; elim/quotW=> z; rewrite !piE. rewrite /addf /= !numden_Ratio ?mulf_neq0 ?domP // !mulrDl. by rewrite !mulrA !addrA ![_ * _ * \d_x]mulrAC. Qed. Lemma addC : commutative add. Proof. by elim/quotW=> x; elim/quotW=> y; rewrite !piE /addf addrC [\d__ * _]mulrC. Qed. Lemma add0_l : left_id 0%:F add. Proof. elim/quotW=> x; rewrite !piE /addf !numden_Ratio ?oner_eq0 //. by rewrite mul0r mul1r mulr1 add0r Ratio_numden. Qed. Lemma addN_l : left_inverse 0%:F opp add. Proof. elim/quotW=> x; apply/eqP; rewrite piE /equivf. rewrite /addf /oppf !numden_Ratio ?(oner_eq0, mulf_neq0, domP) //. by rewrite mulr1 mulr0 mulNr addNr. Qed. (* fracions form an abelian group *) HB.instance Definition _ := GRing.isZmodule.Build type addA addC add0_l addN_l. Lemma mulA : associative mul. Proof. elim/quotW=> x; elim/quotW=> y; elim/quotW=> z; rewrite !piE. by rewrite /mulf !numden_Ratio ?mulf_neq0 ?domP // !mulrA. Qed. Lemma mulC : commutative mul. Proof. elim/quotW=> x; elim/quotW=> y; rewrite !piE /mulf. by rewrite [_ * (\d_x)]mulrC [_ * (\n_x)]mulrC. Qed. Lemma mul1_l : left_id 1%:F mul. Proof. elim/quotW=> x; rewrite !piE /mulf. by rewrite !numden_Ratio ?oner_eq0 // !mul1r Ratio_numden. Qed. Lemma mul_addl : left_distributive mul add. Proof. elim/quotW=> x; elim/quotW=> y; elim/quotW=> z; apply/eqP. rewrite !piE /equivf /mulf /addf !numden_Ratio ?mulf_neq0 ?domP //; apply/eqP. rewrite !(mulrDr, mulrDl) (AC (3*(2*2)) (4*2*7*((1*3)*(6*5))))/=. by rewrite [X in _ + X](AC (3*(2*2)) (4*6*7*((1*3)*(2*5))))/=. Qed. Lemma nonzero1 : 1%:F != 0%:F :> type. Proof. by rewrite piE equivfE !numden_Ratio ?mul1r ?oner_eq0. Qed. (* fractions form a commutative ring *) HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build type mulA mulC mul1_l mul_addl nonzero1. Lemma mulV_l : forall a, a != 0%:F -> mul (inv a) a = 1%:F. Proof. elim/quotW=> x /=; rewrite !piE. rewrite /equivf !numden_Ratio ?oner_eq0 // mulr1 mulr0=> nx0. apply/eqmodP; rewrite /= equivfE. by rewrite !numden_Ratio ?(oner_eq0, mulf_neq0, domP) // !mulr1 mulrC. Qed. Lemma inv0 : inv 0%:F = 0%:F. Proof. rewrite !piE /invf !numden_Ratio ?oner_eq0 // /Ratio /insubd. do 2?case: insubP; rewrite //= ?eqxx ?oner_eq0 // => u _ hu _. by congr \pi; apply: val_inj; rewrite /= hu. Qed. (* fractions form a ring with explicit unit *) (* fractions form a field *) HB.instance Definition _ := GRing.ComNzRing_isField.Build type mulV_l inv0. End FracField. End FracField. HB.export FracField. Arguments FracField.type R%_type. Notation "{ 'fraction' T }" := (FracField.type T). Notation equivf := (@FracField.equivf _). #[global] Hint Resolve denom_ratioP : core. Section FracFieldTheory. Import FracField. Variable R : idomainType. Lemma Ratio_numden (x : {ratio R}) : Ratio \n_x \d_x = x. Proof. exact: FracField.Ratio_numden. Qed. (* exporting the embedding from R to {fraction R} *) Local Notation tofrac := (@FracField.tofrac R). Local Notation "x %:F" := (tofrac x). Lemma tofrac_is_zmod_morphism: zmod_morphism tofrac. Proof. move=> p q /=; unlock tofrac. rewrite -[X in _ = _ + X]pi_opp -[RHS]pi_add. by rewrite /addf /oppf /= !numden_Ratio ?(oner_neq0, mul1r, mulr1). Qed. #[deprecated(since="mathcomp 2.5.0", note="use `tofrac_is_zmod_morphism` instead")] Definition tofrac_is_additive := tofrac_is_zmod_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build R {fraction R} tofrac tofrac_is_zmod_morphism. Lemma tofrac_is_monoid_morphism: monoid_morphism tofrac. Proof. split=> [//|p q]; unlock tofrac; rewrite -[RHS]pi_mul. by rewrite /mulf /= !numden_Ratio ?(oner_neq0, mul1r, mulr1). Qed. #[deprecated(since="mathcomp 2.5.0", note="use `tofrac_is_monoid_morphism` instead")] Definition tofrac_is_multiplicative := tofrac_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build R {fraction R} tofrac tofrac_is_monoid_morphism. (* tests *) Lemma tofrac0 : 0%:F = 0. Proof. exact: rmorph0. Qed. Lemma tofracN : {morph tofrac: x / - x}. Proof. exact: rmorphN. Qed. Lemma tofracD : {morph tofrac: x y / x + y}. Proof. exact: rmorphD. Qed. Lemma tofracB : {morph tofrac: x y / x - y}. Proof. exact: rmorphB. Qed. Lemma tofracMn n : {morph tofrac: x / x *+ n}. Proof. exact: rmorphMn. Qed. Lemma tofracMNn n : {morph tofrac: x / x *- n}. Proof. exact: rmorphMNn. Qed. Lemma tofrac1 : 1%:F = 1. Proof. exact: rmorph1. Qed. Lemma tofracM : {morph tofrac: x y / x * y}. Proof. exact: rmorphM. Qed. Lemma tofracXn n : {morph tofrac: x / x ^+ n}. Proof. exact: rmorphXn. Qed. Lemma tofrac_eq (p q : R): (p%:F == q%:F) = (p == q). Proof. apply/eqP/eqP=> [|->//]; unlock tofrac=> /eqmodP /eqP /=. by rewrite !numden_Ratio ?(oner_eq0, mul1r, mulr1). Qed. Lemma tofrac_eq0 (p : R): (p%:F == 0) = (p == 0). Proof. by rewrite tofrac_eq. Qed. End FracFieldTheory.
Vandermonde.lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Peter Nelson -/ import Mathlib.LinearAlgebra.Matrix.Block import Mathlib.LinearAlgebra.Matrix.Nondegenerate import Mathlib.RingTheory.Localization.FractionRing /-! # Vandermonde matrix This file defines the `vandermonde` matrix and gives its determinant. For each `CommRing R`, and function `v : Fin n → R` the matrix `vandermonde v` is defined to be `Fin n` by `Fin n` matrix `V` whose `i`th row is `[1, (v i), (v i)^2, ...]`. This matrix has determinant equal to the product of `v i - v j` over all unordered pairs `i,j`, and therefore is nonsingular if and only if `v` is injective. `vandermonde v` is a special case of two more general matrices we also define. For a type `α` and functions `v w : α → R`, we write `rectVandermonde v w n` for the `α × Fin n` matrix with `i`th row `[(w i) ^ (n-1), (v i) * (w i)^(n-2), ..., (v i)^(n-1)]`. `projVandermonde v w = rectVandermonde v w n` is the square matrix case, where `α = Fin n`. The determinant of `projVandermonde v w` is the product of `v j * w i - v i * w j`, taken over all pairs `i,j` with `i < j`, which gives a similar characterization of when it it nonsingular. Since `vandermonde v w = projVandermonde v 1`, we can derive most of the API for the former in terms of the latter. These extensions of Vandermonde matrices arise in the study of complete arcs in finite geometry, coding theory, and representations of uniform matroids over finite fields. ## Main definitions * `vandermonde v`: a square matrix with the `i, j`th entry equal to `v i ^ j`. * `rectVandermonde v w n`: an `α × Fin n` matrix whose `i, j`-th entry is `(v i) ^ j * (w i) ^ (n-1-j)`. * `projVandermonde v w`: a square matrix whose `i, j`-th entry is `(v i) ^ j * (w i) ^ (n-1-j)`. ## Main results * `det_vandermonde`: `det (vandermonde v)` is the product of `v j - v i`, where `(i, j)` ranges over the set of pairs with `i < j`. * `det_projVandermonde`: `det (projVandermonde v w)` is the product of `v j * w i - v i * w j`, taken over all pairs with `i < j`. ## Implementation notes We derive the `det_vandermonde` formula from `det_projVandermonde`, which is proved using an induction argument involving row operations and division. To circumvent issues with non-invertible elements while still maintaining the generality of rings, we first prove it for fields using the private lemma `det_projVandermonde_of_field`, and then use an algebraic workaround to generalize to the ring case, stating the strictly more general form as `det_projVandermonde`. ## TODO Characterize when `rectVandermonde v w n` has linearly independent rows. -/ variable {R K : Type*} [CommRing R] [Field K] {n : ℕ} open Equiv Finset open Matrix Fin namespace Matrix /-- A matrix with rows all having the form `[b^(n-1), a * b^(n-2), ..., a ^ (n-1)]` -/ def rectVandermonde {α : Type*} (v w : α → R) (n : ℕ) : Matrix α (Fin n) R := .of fun i j ↦ (v i) ^ j.1 * (w i) ^ j.rev.1 /-- A square matrix with rows all having the form `[b^(n-1), a * b^(n-2), ..., a ^ (n-1)]` -/ def projVandermonde (v w : Fin n → R) : Matrix (Fin n) (Fin n) R := rectVandermonde v w n /-- `vandermonde v` is the square matrix with `i`th row equal to `1, v i, v i ^ 2, v i ^ 3, ...`. -/ def vandermonde (v : Fin n → R) : Matrix (Fin n) (Fin n) R := .of fun i j ↦ (v i) ^ j.1 lemma vandermonde_eq_projVandermonde (v : Fin n → R) : vandermonde v = projVandermonde v 1 := by simp [projVandermonde, rectVandermonde, vandermonde] /-- We don't mark this as `@[simp]` because the RHS is not simp-nf, and simplifying the RHS gives a bothersome `Nat` subtraction. -/ theorem projVandermonde_apply {v w : Fin n → R} {i j : Fin n} : projVandermonde v w i j = (v i) ^ j.1 * (w i) ^ j.rev.1 := rfl theorem rectVandermonde_apply {α : Type*} {v w : α → R} {i : α} {j : Fin n} : rectVandermonde v w n i j = (v i) ^ j.1 * (w i) ^ j.rev.1 := rfl @[simp] theorem vandermonde_apply (v : Fin n → R) (i j) : vandermonde v i j = v i ^ (j : ℕ) := rfl @[simp] theorem vandermonde_cons (v0 : R) (v : Fin n → R) : vandermonde (Fin.cons v0 v : Fin n.succ → R) = Fin.cons (fun (j : Fin n.succ) => v0 ^ (j : ℕ)) fun i => Fin.cons 1 fun j => v i * vandermonde v i j := by ext i j refine Fin.cases (by simp) (fun i => ?_) i refine Fin.cases (by simp) (fun j => ?_) j simp [pow_succ'] theorem vandermonde_succ (v : Fin n.succ → R) : vandermonde v = .of Fin.cons (fun (j : Fin n.succ) => v 0 ^ (j : ℕ)) fun i => Fin.cons 1 fun j => v i.succ * vandermonde (Fin.tail v) i j := by conv_lhs => rw [← Fin.cons_self_tail v, vandermonde_cons] rfl theorem vandermonde_mul_vandermonde_transpose (v w : Fin n → R) (i j) : (vandermonde v * (vandermonde w)ᵀ) i j = ∑ k : Fin n, (v i * w j) ^ (k : ℕ) := by simp only [vandermonde_apply, Matrix.mul_apply, Matrix.transpose_apply, mul_pow] theorem vandermonde_transpose_mul_vandermonde (v : Fin n → R) (i j) : ((vandermonde v)ᵀ * vandermonde v) i j = ∑ k : Fin n, v k ^ (i + j : ℕ) := by simp only [vandermonde_apply, Matrix.mul_apply, Matrix.transpose_apply, pow_add] theorem rectVandermonde_apply_zero_right {α : Type*} {v w : α → R} {i : α} (hw : w i = 0) : rectVandermonde v w (n + 1) i = Pi.single (Fin.last n) ((v i) ^ n) := by ext j obtain rfl | hlt := j.le_last.eq_or_lt · simp [rectVandermonde_apply] rw [rectVandermonde_apply, Pi.single_eq_of_ne hlt.ne, hw, zero_pow, mul_zero] simpa [Nat.sub_eq_zero_iff_le] using hlt theorem projVandermonde_apply_of_ne_zero {v w : Fin (n + 1) → K} {i j : Fin (n + 1)} (hw : w i ≠ 0) : projVandermonde v w i j = (v i) ^ j.1 * (w i) ^ n / (w i) ^ j.1 := by rw [projVandermonde_apply, eq_div_iff (by simp [hw]), mul_assoc, ← pow_add, rev_add_cast] theorem projVandermonde_apply_zero_right {v w : Fin (n + 1) → R} {i : Fin (n + 1)} (hw : w i = 0) : projVandermonde v w i = Pi.single (Fin.last n) ((v i) ^ n) := by ext j obtain rfl | hlt := j.le_last.eq_or_lt · simp [projVandermonde_apply] rw [projVandermonde_apply, Pi.single_eq_of_ne hlt.ne, hw, zero_pow, mul_zero] simpa [Nat.sub_eq_zero_iff_le] using hlt theorem projVandermonde_comp {v w : Fin n → R} (f : Fin n → Fin n) : projVandermonde (v ∘ f) (w ∘ f) = (projVandermonde v w).submatrix f id := rfl theorem projVandermonde_map {R' : Type*} [CommRing R'] (φ : R →+* R') (v w : Fin n → R) : projVandermonde (fun i ↦ φ (v i)) (fun i ↦ φ (w i)) = φ.mapMatrix (projVandermonde v w) := by ext i j simp [projVandermonde_apply] private theorem det_projVandermonde_of_field (v w : Fin n → K) : (projVandermonde v w).det = ∏ i : Fin n, ∏ j ∈ Finset.Ioi i, (v j * w i - v i * w j) := by induction n with | zero => simp | succ n ih => /- We can assume not all `w i` are zero, and therefore that `w 0 ≠ 0`, since otherwise we can swap row `0` with another nonzero row. -/ wlog h0 : w 0 ≠ 0 generalizing v w with aux · obtain h0' | ⟨i₀, hi₀ : w i₀ ≠ 0⟩ := forall_or_exists_not (w · = 0) · obtain rfl | hne := eq_or_ne n 0 · simp [projVandermonde_apply] rw [det_eq_zero_of_column_eq_zero 0 (fun i ↦ by simpa [projVandermonde_apply, h0']), Finset.prod_sigma', Finset.prod_eq_zero (i := ⟨0, Fin.last n⟩) (by simpa) (by simp [h0'])] rw [← mul_right_inj' (a := ((Equiv.swap 0 i₀).sign : K)) (by simp [show 0 ≠ i₀ by rintro rfl; contradiction]), ← det_permute, ← projVandermonde_comp, aux _ _ (by simpa), ← (Equiv.swap 0 i₀).prod_Ioi_comp_eq_sign_mul_prod (by simp)] rfl /- Let `W` be obtained from the matrix by subtracting `r = (v 0) / (w 0)` times each column from the next column, starting from the penultimate column. This doesn't change the determinant.-/ set r := v 0 / w 0 with hr set W : Matrix (Fin (n + 1)) (Fin (n + 1)) K := .of fun i ↦ (cons (projVandermonde v w i 0) (fun j ↦ projVandermonde v w i j.succ - r * projVandermonde v w i j.castSucc)) -- deleting the first row and column of `W` gives a row-scaling of a Vandermonde matrix. have hW_eq : (W.submatrix succ succ) = .of fun i j ↦ (v (succ i) - r * w (succ i)) * projVandermonde (v ∘ succ) (w ∘ succ) i j := by ext i j simp only [projVandermonde_apply, val_zero, rev_zero, val_last, val_succ, coe_castSucc, submatrix_apply, Function.comp_apply, rev_succ, W, r, rev_castSucc] simp ring /- The first row of `W` is `[(w 0)^n, 0, ..., 0]` - take a cofactor expansion along this row, and apply induction. -/ rw [det_eq_of_forall_col_eq_smul_add_pred (B := W) (c := fun _ ↦ r) (by simp [W]) (fun i j ↦ by simp [W, r, projVandermonde_apply]), det_succ_row_zero, Finset.sum_eq_single 0 _ (by simp)] · rw [succAbove_zero, hW_eq, det_mul_column, ih] field_simp [show W 0 0 = w 0 ^ n by simp [W, projVandermonde_apply], prod_univ_succ, hr] intro j _ hj0 obtain ⟨j, rfl⟩ := j.eq_succ_of_ne_zero hj0 rw [mul_eq_zero, mul_eq_zero] refine .inl (.inr ?_) simp only [of_apply, projVandermonde_apply_of_ne_zero h0, val_succ, coe_castSucc, cons_succ, W, r] ring /-- The formula for the determinant of a projective Vandermonde matrix. -/ theorem det_projVandermonde (v w : Fin n → R) : (projVandermonde v w).det = ∏ i : Fin n, ∏ j ∈ Finset.Ioi i, (v j * w i - v i * w j) := by let u (b : Bool) (i : Fin n) := (algebraMap (MvPolynomial (Fin n × Bool) ℤ) (FractionRing (MvPolynomial (Fin n × Bool) ℤ))) (MvPolynomial.X ⟨i, b⟩) have hdet := det_projVandermonde_of_field (u true) (u false) simp only [u] at hdet norm_cast at hdet rw [projVandermonde_map, ← RingHom.map_det, IsFractionRing.coe_inj] at hdet apply_fun MvPolynomial.eval₂Hom (Int.castRingHom R) (fun x ↦ (if x.2 then v else w) x.1) at hdet rw [RingHom.map_det] at hdet convert hdet <;> simp [← Matrix.ext_iff, projVandermonde_apply] /-- The formula for the determinant of a Vandermonde matrix. -/ theorem det_vandermonde (v : Fin n → R) : det (vandermonde v) = ∏ i : Fin n, ∏ j ∈ Ioi i, (v j - v i) := by simp [vandermonde_eq_projVandermonde, det_projVandermonde] theorem det_vandermonde_eq_zero_iff [IsDomain R] {v : Fin n → R} : det (vandermonde v) = 0 ↔ ∃ i j : Fin n, v i = v j ∧ i ≠ j := by constructor · simp only [det_vandermonde v, Finset.prod_eq_zero_iff, sub_eq_zero, forall_exists_index] rintro i ⟨_, j, h₁, h₂⟩ exact ⟨j, i, h₂, (mem_Ioi.mp h₁).ne'⟩ · simp only [Ne, forall_exists_index, and_imp] refine fun i j h₁ h₂ => Matrix.det_zero_of_row_eq h₂ (funext fun k => ?_) rw [vandermonde_apply, vandermonde_apply, h₁] theorem det_vandermonde_ne_zero_iff [IsDomain R] {v : Fin n → R} : det (vandermonde v) ≠ 0 ↔ Function.Injective v := by unfold Function.Injective simp only [det_vandermonde_eq_zero_iff, Ne, not_exists, not_and, Classical.not_not] @[simp] theorem det_vandermonde_add (v : Fin n → R) (a : R) : (Matrix.vandermonde fun i ↦ v i + a).det = (Matrix.vandermonde v).det := by simp [Matrix.det_vandermonde] @[simp] theorem det_vandermonde_sub (v : Fin n → R) (a : R) : (Matrix.vandermonde fun i ↦ v i - a).det = (Matrix.vandermonde v).det := by rw [← det_vandermonde_add v (- a)] simp only [← sub_eq_add_neg] theorem eq_zero_of_forall_index_sum_pow_mul_eq_zero [IsDomain R] {f v : Fin n → R} (hf : Function.Injective f) (hfv : ∀ j, (∑ i : Fin n, f j ^ (i : ℕ) * v i) = 0) : v = 0 := eq_zero_of_mulVec_eq_zero (det_vandermonde_ne_zero_iff.mpr hf) (funext hfv) theorem eq_zero_of_forall_index_sum_mul_pow_eq_zero [IsDomain R] {f v : Fin n → R} (hf : Function.Injective f) (hfv : ∀ j, (∑ i, v i * f j ^ (i : ℕ)) = 0) : v = 0 := by apply eq_zero_of_forall_index_sum_pow_mul_eq_zero hf simp_rw [mul_comm] exact hfv theorem eq_zero_of_forall_pow_sum_mul_pow_eq_zero [IsDomain R] {f v : Fin n → R} (hf : Function.Injective f) (hfv : ∀ i : Fin n, (∑ j : Fin n, v j * f j ^ (i : ℕ)) = 0) : v = 0 := eq_zero_of_vecMul_eq_zero (det_vandermonde_ne_zero_iff.mpr hf) (funext hfv) open Polynomial theorem eval_matrixOfPolynomials_eq_vandermonde_mul_matrixOfPolynomials (v : Fin n → R) (p : Fin n → R[X]) (h_deg : ∀ i, (p i).natDegree ≤ i) : Matrix.of (fun i j => ((p j).eval (v i))) = (Matrix.vandermonde v) * (Matrix.of (fun (i j : Fin n) => (p j).coeff i)) := by ext i j rw [Matrix.mul_apply, eval, Matrix.of_apply, eval₂] simp only [Matrix.vandermonde] have : (p j).support ⊆ range n := supp_subset_range <| Nat.lt_of_le_of_lt (h_deg j) <| Fin.prop j rw [sum_eq_of_subset _ (fun j => zero_mul ((v i) ^ j)) this, ← Fin.sum_univ_eq_sum_range] congr ext k rw [mul_comm, Matrix.of_apply, RingHom.id_apply, of_apply] theorem det_eval_matrixOfPolynomials_eq_det_vandermonde (v : Fin n → R) (p : Fin n → R[X]) (h_deg : ∀ i, (p i).natDegree = i) (h_monic : ∀ i, Monic <| p i) : (Matrix.vandermonde v).det = (Matrix.of (fun i j => ((p j).eval (v i)))).det := by rw [Matrix.eval_matrixOfPolynomials_eq_vandermonde_mul_matrixOfPolynomials v p (fun i ↦ Nat.le_of_eq (h_deg i)), Matrix.det_mul, Matrix.det_matrixOfPolynomials p h_deg h_monic, mul_one] end Matrix
presentation.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. From mathcomp Require Import fintype finset fingroup morphism. (******************************************************************************) (* Support for generator-and-relation presentations of groups. We provide the *) (* syntax: *) (* G \homg Grp (x_1 : ... x_n : s_1 = t_1, ..., s_m = t_m) *) (* <=> G is generated by elements x_1, ..., x_m satisfying the relations *) (* s_1 = t_1, ..., s_m = t_m, i.e., G is a homomorphic image of the *) (* group generated by the x_i, subject to the relations s_j = t_j. *) (* G \isog Grp (x_1 : ... x_n : s_1 = t_1, ..., s_m = t_m) *) (* <=> G is isomorphic to the largest finite factor of the group generated *) (* by the x_i, subject to the relations s_j = t_j. In particular, *) (* if the abstract group defined by the presentation is finite, *) (* it means that G is actually isomorphic to it. This is an *) (* intensional predicate (in Prop), as even the non-triviality of a *) (* generated group is undecidable. *) (* Syntax details: *) (* - Grp is a literal constant. *) (* - There must be at least one generator and one relation. *) (* - A relation s_j = 1 can be abbreviated as simply s_j (a.k.a. a relator). *) (* - Two consecutive relations s_j = t, s_j+1 = t can be abbreviated *) (* s_j = s_j+1 = t. *) (* - The s_j and t_j are terms built from the x_i and the standard group *) (* operators *, 1, ^-1, ^+, ^-, ^, [~ u_1, ..., u_k]; no other operator or *) (* abbreviation may be used, as the notation is implemented using static *) (* overloading. *) (* - This is the closest we could get to the notation used in Aschbacher, *) (* Grp (x_1, ... x_n : t_1,1 = ... = t_1,k1, ..., t_m,1 = ... = t_m,km) *) (* under the current limitations of the Coq Notation facility. *) (* Semantics details: *) (* - G \isog Grp (...) : Prop expands to the statement *) (* forall rT (H : {group rT}), (H \homg G) = (H \homg Grp (...)) *) (* (with rT : finGroupType). *) (* - G \homg Grp (x_1 : ... x_n : s_1 = t_1, ..., s_m = t_m) : bool, with *) (* G : {set gT}, is convertible to the boolean expression *) (* [exists t : gT * ... gT, let: (x_1, ..., x_n) := t in *) (* (<[x_1]> <*> ... <*> <[x_n]>, (s_1, ... (s_m-1, s_m) ...)) *) (* == (G, (t_1, ... (t_m-1, t_m) ...))] *) (* where the tuple comparison above is convertible to the conjunction *) (* [&& <[x_1]> <*> ... <*> <[x_n]> == G, s_1 == t_1, ... & s_m == t_m] *) (* Thus G \homg Grp (...) can be easily exploited by destructing the tuple *) (* created case/existsP, then destructing the tuple equality with case/eqP. *) (* Conversely it can be proved by using apply/existsP, providing the tuple *) (* with a single exists (u_1, ..., u_n), then using rewrite !xpair_eqE /= *) (* to expose the conjunction, and optionally using an apply/and{m+1}P view *) (* to split it into subgoals (in that case, the rewrite is in principle *) (* redundant, but necessary in practice because of the poor performance of *) (* conversion in the Coq unifier). *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Module Presentation. Section Presentation. Implicit Types gT rT : finGroupType. Implicit Type vT : finType. (* tuple value type *) Inductive term := | Cst of nat | Idx | Inv of term | Exp of term & nat | Mul of term & term | Conj of term & term | Comm of term & term. Fixpoint eval {gT} e t : gT := match t with | Cst i => nth 1 e i | Idx => 1 | Inv t1 => (eval e t1)^-1 | Exp t1 n => eval e t1 ^+ n | Mul t1 t2 => eval e t1 * eval e t2 | Conj t1 t2 => eval e t1 ^ eval e t2 | Comm t1 t2 => [~ eval e t1, eval e t2] end. Inductive formula := Eq2 of term & term | And of formula & formula. Definition Eq1 s := Eq2 s Idx. Definition Eq3 s1 s2 t := And (Eq2 s1 t) (Eq2 s2 t). Inductive rel_type := NoRel | Rel vT of vT & vT. Definition bool_of_rel r := if r is Rel vT v1 v2 then v1 == v2 else true. Local Coercion bool_of_rel : rel_type >-> bool. Definition and_rel vT (v1 v2 : vT) r := if r is Rel wT w1 w2 then Rel (v1, w1) (v2, w2) else Rel v1 v2. Fixpoint rel {gT} (e : seq gT) f r := match f with | Eq2 s t => and_rel (eval e s) (eval e t) r | And f1 f2 => rel e f1 (rel e f2 r) end. Inductive type := Generator of term -> type | Formula of formula. Definition Cast p : type := p. (* syntactic scope cast *) Local Coercion Formula : formula >-> type. Inductive env gT := Env of {set gT} & seq gT. Definition env1 {gT} (x : gT : finType) := Env <[x]> [:: x]. Fixpoint sat gT vT B n (s : vT -> env gT) p := match p with | Formula f => [exists v, let: Env A e := s v in and_rel A B (rel (rev e) f NoRel)] | Generator p' => let s' v := let: Env A e := s v.1 in Env (A <*> <[v.2]>) (v.2 :: e) in sat B n.+1 s' (p' (Cst n)) end. Definition hom gT (B : {set gT}) p := sat B 1 env1 (p (Cst 0)). Definition iso gT (B : {set gT}) p := forall rT (H : {group rT}), (H \homg B) = hom H p. End Presentation. End Presentation. Import Presentation. Coercion bool_of_rel : rel_type >-> bool. Coercion Eq1 : term >-> formula. Coercion Formula : formula >-> type. Declare Custom Entry group_presentation. Notation "x * y" := (Mul x y) (in custom group_presentation at level 40, left associativity). Notation "x ^+ n" := (Exp x n) (in custom group_presentation at level 29, n constr at level 28). Notation "x ^ y" := (Conj x y) (in custom group_presentation at level 30, right associativity). Notation "x ^-1" := (Inv x) (in custom group_presentation at level 3). Notation "x ^- n" := (Inv (Exp x n)) (in custom group_presentation at level 29, n constr at level 28). Notation "[ ~ x1 , x2 , .. , xn ]" := (Comm .. (Comm x1 x2) .. xn) (in custom group_presentation, x1, x2, xn at level 100). Notation "x = y" := (Eq2 x y) (in custom group_presentation at level 70). Notation "x = y = z" := (Eq3 x y z) (in custom group_presentation at level 70, y at next level). Notation "r1 , r2 , .. , rn" := (And .. (And r1 r2) .. rn) (in custom group_presentation at level 200). Notation "( p )" := p (in custom group_presentation, p at level 200). Notation "1" := Idx (in custom group_presentation). Notation "x" := x (in custom group_presentation at level 0, x ident). Notation "x : p" := (Generator (fun x => Cast p)) (in custom group_presentation, x ident, p custom group_presentation at level 200). Arguments hom _ _%_group_scope. Arguments iso _ _%_group_scope. Notation "H \homg 'Grp' p" := (hom H p) (p at level 0, format "H \homg 'Grp' p") : group_scope. Notation "H \isog 'Grp' p" := (iso H p) (p at level 0, format "H \isog 'Grp' p") : group_scope. Notation "H \homg 'Grp' ( x : p )" := (hom H (fun x => Cast p)) (x ident, p custom group_presentation at level 200, format "'[hv' H '/ ' \homg 'Grp' ( x : p ) ']'") : group_scope. Notation "H \isog 'Grp' ( x : p )" := (iso H (fun x => Cast p)) (x ident, p custom group_presentation at level 200, format "'[hv' H '/ ' \isog 'Grp' ( x : p ) ']'") : group_scope. Section PresentationTheory. Implicit Types gT rT : finGroupType. Import Presentation. Lemma isoGrp_hom gT (G : {group gT}) p : G \isog Grp p -> G \homg Grp p. Proof. by move <-; apply: homg_refl. Qed. Lemma isoGrpP gT (G : {group gT}) p rT (H : {group rT}) : G \isog Grp p -> reflect (#|H| = #|G| /\ H \homg Grp p) (H \isog G). Proof. move=> isoGp; apply: (iffP idP) => [isoGH | [oH homHp]]. by rewrite (card_isog isoGH) -isoGp isog_hom. by rewrite isogEcard isoGp homHp /= oH. Qed. Lemma homGrp_trans rT gT (H : {set rT}) (G : {group gT}) p : H \homg G -> G \homg Grp p -> H \homg Grp p. Proof. case/homgP=> h <-{H}; rewrite /hom; move: {p}(p _) => p. have evalG e t: all [in G] e -> eval (map h e) t = h (eval e t). move=> Ge; apply: (@proj2 (eval e t \in G)); elim: t => /=. - move=> i; case: (leqP (size e) i) => [le_e_i | lt_i_e]. by rewrite !nth_default ?size_map ?morph1. by rewrite (nth_map 1) // [_ \in G](allP Ge) ?mem_nth. - by rewrite morph1. - by move=> t [Gt ->]; rewrite groupV morphV. - by move=> t [Gt ->] n; rewrite groupX ?morphX. - by move=> t1 [Gt1 ->] t2 [Gt2 ->]; rewrite groupM ?morphM. - by move=> t1 [Gt1 ->] t2 [Gt2 ->]; rewrite groupJ ?morphJ. by move=> t1 [Gt1 ->] t2 [Gt2 ->]; rewrite groupR ?morphR. have and_relE xT x1 x2 r: @and_rel xT x1 x2 r = (x1 == x2) && r :> bool. by case: r => //=; rewrite andbT. have rsatG e f: all [in G] e -> rel e f NoRel -> rel (map h e) f NoRel. move=> Ge; have: NoRel -> NoRel by []; move: NoRel {2 4}NoRel. elim: f => [x1 x2 | f1 IH1 f2 IH2] r hr IHr; last by apply: IH1; apply: IH2. by rewrite !and_relE !evalG //; case/andP; move/eqP->; rewrite eqxx. set s := env1; set vT := gT : finType in s *. set s' := env1; set vT' := rT : finType in s' *. have (v): let: Env A e := s v in A \subset G -> all [in G] e /\ exists v', s' v' = Env (h @* A) (map h e). - rewrite /= cycle_subG andbT => Gv; rewrite morphim_cycle //. by split; last exists (h v). elim: p 1%N vT vT' s s' => /= [p IHp | f] n vT vT' s s' Gs. apply: IHp => [[v x]] /=; case: (s v) {Gs}(Gs v) => A e /= Gs. rewrite join_subG cycle_subG; case/andP=> sAG Gx; rewrite Gx. have [//|-> [v' def_v']] := Gs; split=> //; exists (v', h x); rewrite def_v'. by congr (Env _ _); rewrite morphimY ?cycle_subG // morphim_cycle. case/existsP=> v; case: (s v) {Gs}(Gs v) => /= A e Gs. rewrite and_relE => /andP[/eqP defA rel_f]. have{Gs} [|Ge [v' def_v']] := Gs; first by rewrite defA. apply/existsP; exists v'; rewrite def_v' and_relE defA eqxx /=. by rewrite -map_rev rsatG ?(eq_all_r (mem_rev e)). Qed. Lemma eq_homGrp gT rT (G : {group gT}) (H : {group rT}) p : G \isog H -> (G \homg Grp p) = (H \homg Grp p). Proof. by rewrite isogEhom => /andP[homGH homHG]; apply/idP/idP; apply: homGrp_trans. Qed. Lemma isoGrp_trans gT rT (G : {group gT}) (H : {group rT}) p : G \isog H -> H \isog Grp p -> G \isog Grp p. Proof. by move=> isoGH isoHp kT K; rewrite -isoHp; apply: eq_homgr. Qed. Lemma intro_isoGrp gT (G : {group gT}) p : G \homg Grp p -> (forall rT (H : {group rT}), H \homg Grp p -> H \homg G) -> G \isog Grp p. Proof. move=> homGp freeG rT H. by apply/idP/idP=> [homHp|]; [apply: homGrp_trans homGp | apply: freeG]. Qed. End PresentationTheory.
Hindman.lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import Mathlib.Data.Stream.Init import Mathlib.Topology.Algebra.Semigroup import Mathlib.Topology.Compactification.StoneCech import Mathlib.Algebra.BigOperators.Group.Finset.Basic /-! # Hindman's theorem on finite sums We prove Hindman's theorem on finite sums, using idempotent ultrafilters. Given an infinite sequence `a₀, a₁, a₂, …` of positive integers, the set `FS(a₀, …)` is the set of positive integers that can be expressed as a finite sum of `aᵢ`'s, without repetition. Hindman's theorem asserts that whenever the positive integers are finitely colored, there exists a sequence `a₀, a₁, a₂, …` such that `FS(a₀, …)` is monochromatic. There is also a stronger version, saying that whenever a set of the form `FS(a₀, …)` is finitely colored, there exists a sequence `b₀, b₁, b₂, …` such that `FS(b₀, …)` is monochromatic and contained in `FS(a₀, …)`. We prove both these versions for a general semigroup `M` instead of `ℕ+` since it is no harder, although this special case implies the general case. The idea of the proof is to extend the addition `(+) : M → M → M` to addition `(+) : βM → βM → βM` on the space `βM` of ultrafilters on `M`. One can prove that if `U` is an _idempotent_ ultrafilter, i.e. `U + U = U`, then any `U`-large subset of `M` contains some set `FS(a₀, …)` (see `exists_FS_of_large`). And with the help of a general topological argument one can show that any set of the form `FS(a₀, …)` is `U`-large according to some idempotent ultrafilter `U` (see `exists_idempotent_ultrafilter_le_FS`). This is enough to prove the theorem since in any finite partition of a `U`-large set, one of the parts is `U`-large. ## Main results - `FS_partition_regular`: the strong form of Hindman's theorem - `exists_FS_of_finite_cover`: the weak form of Hindman's theorem ## Tags Ramsey theory, ultrafilter -/ open Filter /-- Multiplication of ultrafilters given by `∀ᶠ m in U*V, p m ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m*m')`. -/ @[to_additive /-- Addition of ultrafilters given by `∀ᶠ m in U+V, p m ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m+m')`. -/] def Ultrafilter.mul {M} [Mul M] : Mul (Ultrafilter M) where mul U V := (· * ·) <$> U <*> V attribute [local instance] Ultrafilter.mul Ultrafilter.add /- We could have taken this as the definition of `U * V`, but then we would have to prove that it defines an ultrafilter. -/ @[to_additive] theorem Ultrafilter.eventually_mul {M} [Mul M] (U V : Ultrafilter M) (p : M → Prop) : (∀ᶠ m in ↑(U * V), p m) ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m * m') := Iff.rfl /-- Semigroup structure on `Ultrafilter M` induced by a semigroup structure on `M`. -/ @[to_additive /-- Additive semigroup structure on `Ultrafilter M` induced by an additive semigroup structure on `M`. -/] def Ultrafilter.semigroup {M} [Semigroup M] : Semigroup (Ultrafilter M) := { Ultrafilter.mul with mul_assoc := fun U V W => Ultrafilter.coe_inj.mp <| Filter.ext' fun p => by simp [Ultrafilter.eventually_mul, mul_assoc] } attribute [local instance] Ultrafilter.semigroup Ultrafilter.addSemigroup -- We don't prove `continuous_mul_right`, because in general it is false! @[to_additive] theorem Ultrafilter.continuous_mul_left {M} [Mul M] (V : Ultrafilter M) : Continuous (· * V) := ultrafilterBasis_is_basis.continuous_iff.2 <| Set.forall_mem_range.mpr fun s ↦ ultrafilter_isOpen_basic { m : M | ∀ᶠ m' in V, m * m' ∈ s } namespace Hindman /-- `FS a` is the set of finite sums in `a`, i.e. `m ∈ FS a` if `m` is the sum of a nonempty subsequence of `a`. We give a direct inductive definition instead of talking about subsequences. -/ inductive FS {M} [AddSemigroup M] : Stream' M → Set M | head (a : Stream' M) : FS a a.head | tail (a : Stream' M) (m : M) (h : FS a.tail m) : FS a m | cons (a : Stream' M) (m : M) (h : FS a.tail m) : FS a (a.head + m) /-- `FP a` is the set of finite products in `a`, i.e. `m ∈ FP a` if `m` is the product of a nonempty subsequence of `a`. We give a direct inductive definition instead of talking about subsequences. -/ @[to_additive FS] inductive FP {M} [Semigroup M] : Stream' M → Set M | head (a : Stream' M) : FP a a.head | tail (a : Stream' M) (m : M) (h : FP a.tail m) : FP a m | cons (a : Stream' M) (m : M) (h : FP a.tail m) : FP a (a.head * m) /-- If `m` and `m'` are finite products in `M`, then so is `m * m'`, provided that `m'` is obtained from a subsequence of `M` starting sufficiently late. -/ @[to_additive /-- If `m` and `m'` are finite sums in `M`, then so is `m + m'`, provided that `m'` is obtained from a subsequence of `M` starting sufficiently late. -/] theorem FP.mul {M} [Semigroup M] {a : Stream' M} {m : M} (hm : m ∈ FP a) : ∃ n, ∀ m' ∈ FP (a.drop n), m * m' ∈ FP a := by induction hm with | head a => exact ⟨1, fun m hm => FP.cons a m hm⟩ | tail a m _ ih => obtain ⟨n, hn⟩ := ih use n + 1 intro m' hm' exact FP.tail _ _ (hn _ hm') | cons a m _ ih => obtain ⟨n, hn⟩ := ih use n + 1 intro m' hm' rw [mul_assoc] exact FP.cons _ _ (hn _ hm') @[to_additive exists_idempotent_ultrafilter_le_FS] theorem exists_idempotent_ultrafilter_le_FP {M} [Semigroup M] (a : Stream' M) : ∃ U : Ultrafilter M, U * U = U ∧ ∀ᶠ m in U, m ∈ FP a := by let S : Set (Ultrafilter M) := ⋂ n, { U | ∀ᶠ m in U, m ∈ FP (a.drop n) } have h := exists_idempotent_in_compact_subsemigroup ?_ S ?_ ?_ ?_ · rcases h with ⟨U, hU, U_idem⟩ refine ⟨U, U_idem, ?_⟩ convert Set.mem_iInter.mp hU 0 · exact Ultrafilter.continuous_mul_left · apply IsCompact.nonempty_iInter_of_sequence_nonempty_isCompact_isClosed · intro n U hU filter_upwards [hU] rw [← Stream'.drop_drop, ← Stream'.tail_eq_drop] exact FP.tail _ · intro n exact ⟨pure _, mem_pure.mpr <| FP.head _⟩ · exact (ultrafilter_isClosed_basic _).isCompact · intro n apply ultrafilter_isClosed_basic · exact IsClosed.isCompact (isClosed_iInter fun i => ultrafilter_isClosed_basic _) · intro U hU V hV rw [Set.mem_iInter] at * intro n rw [Set.mem_setOf_eq, Ultrafilter.eventually_mul] filter_upwards [hU n] with m hm obtain ⟨n', hn⟩ := FP.mul hm filter_upwards [hV (n' + n)] with m' hm' apply hn simpa only [Stream'.drop_drop, add_comm] using hm' @[to_additive exists_FS_of_large] theorem exists_FP_of_large {M} [Semigroup M] (U : Ultrafilter M) (U_idem : U * U = U) (s₀ : Set M) (sU : s₀ ∈ U) : ∃ a, FP a ⊆ s₀ := by /- Informally: given a `U`-large set `s₀`, the set `s₀ ∩ { m | ∀ᶠ m' in U, m * m' ∈ s₀ }` is also `U`-large (since `U` is idempotent). Thus in particular there is an `a₀` in this intersection. Now let `s₁` be the intersection `s₀ ∩ { m | a₀ * m ∈ s₀ }`. By choice of `a₀`, this is again `U`-large, so we can repeat the argument starting from `s₁`, obtaining `a₁`, `s₂`, etc. This gives the desired infinite sequence. -/ have exists_elem : ∀ {s : Set M} (_hs : s ∈ U), (s ∩ { m | ∀ᶠ m' in U, m * m' ∈ s }).Nonempty := fun {s} hs => Ultrafilter.nonempty_of_mem (inter_mem hs <| by rwa [← U_idem] at hs) let elem : { s // s ∈ U } → M := fun p => (exists_elem p.property).some let succ : {s // s ∈ U} → {s // s ∈ U} := fun (p : {s // s ∈ U}) => ⟨p.val ∩ {m : M | elem p * m ∈ p.val}, inter_mem p.property (show (exists_elem p.property).some ∈ {m : M | ∀ᶠ (m' : M) in ↑U, m * m' ∈ p.val} from p.val.inter_subset_right (exists_elem p.property).some_mem)⟩ use Stream'.corec elem succ (Subtype.mk s₀ sU) suffices ∀ (a : Stream' M), ∀ m ∈ FP a, ∀ p, a = Stream'.corec elem succ p → m ∈ p.val by intro m hm exact this _ m hm ⟨s₀, sU⟩ rfl clear sU s₀ intro a m h induction h with | head b => rintro p rfl rw [Stream'.corec_eq, Stream'.head_cons] exact Set.inter_subset_left (Set.Nonempty.some_mem _) | tail b n h ih => rintro p rfl refine Set.inter_subset_left (ih (succ p) ?_) rw [Stream'.corec_eq, Stream'.tail_cons] | cons b n h ih => rintro p rfl have := Set.inter_subset_right (ih (succ p) ?_) · simpa only using this rw [Stream'.corec_eq, Stream'.tail_cons] /-- The strong form of **Hindman's theorem**: in any finite cover of an FP-set, one the parts contains an FP-set. -/ @[to_additive FS_partition_regular /-- The strong form of **Hindman's theorem**: in any finite cover of an FS-set, one the parts contains an FS-set. -/] theorem FP_partition_regular {M} [Semigroup M] (a : Stream' M) (s : Set (Set M)) (sfin : s.Finite) (scov : FP a ⊆ ⋃₀ s) : ∃ c ∈ s, ∃ b : Stream' M, FP b ⊆ c := let ⟨U, idem, aU⟩ := exists_idempotent_ultrafilter_le_FP a let ⟨c, cs, hc⟩ := (Ultrafilter.finite_sUnion_mem_iff sfin).mp (mem_of_superset aU scov) ⟨c, cs, exists_FP_of_large U idem c hc⟩ /-- The weak form of **Hindman's theorem**: in any finite cover of a nonempty semigroup, one of the parts contains an FP-set. -/ @[to_additive exists_FS_of_finite_cover /-- The weak form of **Hindman's theorem**: in any finite cover of a nonempty additive semigroup, one of the parts contains an FS-set. -/] theorem exists_FP_of_finite_cover {M} [Semigroup M] [Nonempty M] (s : Set (Set M)) (sfin : s.Finite) (scov : ⊤ ⊆ ⋃₀ s) : ∃ c ∈ s, ∃ a : Stream' M, FP a ⊆ c := let ⟨U, hU⟩ := exists_idempotent_of_compact_t2_of_continuous_mul_left (@Ultrafilter.continuous_mul_left M _) let ⟨c, c_s, hc⟩ := (Ultrafilter.finite_sUnion_mem_iff sfin).mp (mem_of_superset univ_mem scov) ⟨c, c_s, exists_FP_of_large U hU c hc⟩ @[to_additive FS_iter_tail_sub_FS] theorem FP_drop_subset_FP {M} [Semigroup M] (a : Stream' M) (n : ℕ) : FP (a.drop n) ⊆ FP a := by induction n with | zero => rfl | succ n ih => rw [← Stream'.drop_drop] exact _root_.trans (FP.tail _) ih @[to_additive] theorem FP.singleton {M} [Semigroup M] (a : Stream' M) (i : ℕ) : a.get i ∈ FP a := by induction i generalizing a with | zero => exact FP.head _ | succ i ih => exact FP.tail _ _ (ih _) @[to_additive] theorem FP.mul_two {M} [Semigroup M] (a : Stream' M) (i j : ℕ) (ij : i < j) : a.get i * a.get j ∈ FP a := by refine FP_drop_subset_FP _ i ?_ rw [← Stream'.head_drop] apply FP.cons rcases Nat.exists_eq_add_of_le (Nat.succ_le_of_lt ij) with ⟨d, hd⟩ -- Porting note: need to fix breakage of Set notation change _ ∈ FP _ have := FP.singleton (a.drop i).tail d rw [Stream'.tail_eq_drop, Stream'.get_drop, Stream'.get_drop] at this convert this omega @[to_additive] theorem FP.finset_prod {M} [CommMonoid M] (a : Stream' M) (s : Finset ℕ) (hs : s.Nonempty) : (s.prod fun i => a.get i) ∈ FP a := by refine FP_drop_subset_FP _ (s.min' hs) ?_ induction s using Finset.eraseInduction with | H s ih => _ rw [← Finset.mul_prod_erase _ _ (s.min'_mem hs), ← Stream'.head_drop] rcases (s.erase (s.min' hs)).eq_empty_or_nonempty with h | h · rw [h, Finset.prod_empty, mul_one] exact FP.head _ · apply FP.cons rw [Stream'.tail_eq_drop, Stream'.drop_drop, add_comm] refine Set.mem_of_subset_of_mem ?_ (ih _ (s.min'_mem hs) h) have : s.min' hs + 1 ≤ (s.erase (s.min' hs)).min' h := Nat.succ_le_of_lt (Finset.min'_lt_of_mem_erase_min' _ _ <| Finset.min'_mem _ _) obtain ⟨d, hd⟩ := Nat.exists_eq_add_of_le this rw [hd, ← Stream'.drop_drop, add_comm] apply FP_drop_subset_FP end Hindman
Finite.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Sander Dahmen, Kim Morrison -/ import Mathlib.LinearAlgebra.Dimension.Constructions import Mathlib.LinearAlgebra.Dimension.StrongRankCondition import Mathlib.LinearAlgebra.Dimension.Subsingleton import Mathlib.LinearAlgebra.FreeModule.Finite.Basic import Mathlib.SetTheory.Cardinal.Cofinality /-! # Conditions for rank to be finite Also contains characterization for when rank equals zero or rank equals one. -/ noncomputable section universe u v v' w variable {R : Type u} {M M₁ : Type v} {M' : Type v'} {ι : Type w} variable [Ring R] [AddCommGroup M] [AddCommGroup M'] [AddCommGroup M₁] variable [Module R M] [Module R M'] [Module R M₁] attribute [local instance] nontrivial_of_invariantBasisNumber open Basis Cardinal Function Module Set Submodule /-- If every finite set of linearly independent vectors has cardinality at most `n`, then the same is true for arbitrary sets of linearly independent vectors. -/ theorem linearIndependent_bounded_of_finset_linearIndependent_bounded {n : ℕ} (H : ∀ s : Finset M, (LinearIndependent R fun i : s => (i : M)) → s.card ≤ n) : ∀ s : Set M, LinearIndependent R ((↑) : s → M) → #s ≤ n := by intro s li apply Cardinal.card_le_of intro t rw [← Finset.card_map (Embedding.subtype s)] apply H apply linearIndependent_finset_map_embedding_subtype _ li theorem rank_le {n : ℕ} (H : ∀ s : Finset M, (LinearIndependent R fun i : s => (i : M)) → s.card ≤ n) : Module.rank R M ≤ n := by rw [Module.rank_def] apply ciSup_le' rintro ⟨s, li⟩ exact linearIndependent_bounded_of_finset_linearIndependent_bounded H _ li section RankZero /-- See `rank_zero_iff` for a stronger version with `NoZeroSMulDivisor R M`. -/ lemma rank_eq_zero_iff : Module.rank R M = 0 ↔ ∀ x : M, ∃ a : R, a ≠ 0 ∧ a • x = 0 := by nontriviality R constructor · contrapose! rintro ⟨x, hx⟩ rw [← Cardinal.one_le_iff_ne_zero] have : LinearIndependent R (fun _ : Unit ↦ x) := linearIndependent_iff.mpr (fun l hl ↦ Finsupp.unique_ext <| not_not.mp fun H ↦ hx _ H ((Finsupp.linearCombination_unique _ _ _).symm.trans hl)) simpa using this.cardinal_lift_le_rank · intro h rw [← le_zero_iff, Module.rank_def] apply ciSup_le' intro ⟨s, hs⟩ rw [nonpos_iff_eq_zero, Cardinal.mk_eq_zero_iff, ← not_nonempty_iff] rintro ⟨i : s⟩ obtain ⟨a, ha, ha'⟩ := h i apply ha simpa using DFunLike.congr_fun (linearIndependent_iff.mp hs (Finsupp.single i a) (by simpa)) i theorem rank_pos_of_free [Module.Free R M] [Nontrivial M] : 0 < Module.rank R M := have := Module.nontrivial R M (pos_of_ne_zero <| Cardinal.mk_ne_zero _).trans_le (Free.chooseBasis R M).linearIndependent.cardinal_le_rank variable [Nontrivial R] section variable [NoZeroSMulDivisors R M] theorem rank_zero_iff_forall_zero : Module.rank R M = 0 ↔ ∀ x : M, x = 0 := by simp_rw [rank_eq_zero_iff, smul_eq_zero, and_or_left, not_and_self_iff, false_or, exists_and_right, and_iff_right (exists_ne (0 : R))] /-- See `rank_subsingleton` for the reason that `Nontrivial R` is needed. Also see `rank_eq_zero_iff` for the version without `NoZeroSMulDivisor R M`. -/ theorem rank_zero_iff : Module.rank R M = 0 ↔ Subsingleton M := rank_zero_iff_forall_zero.trans (subsingleton_iff_forall_eq 0).symm theorem rank_pos_iff_exists_ne_zero : 0 < Module.rank R M ↔ ∃ x : M, x ≠ 0 := by rw [← not_iff_not] simpa using rank_zero_iff_forall_zero theorem rank_pos_iff_nontrivial : 0 < Module.rank R M ↔ Nontrivial M := rank_pos_iff_exists_ne_zero.trans (nontrivial_iff_exists_ne 0).symm theorem rank_pos [Nontrivial M] : 0 < Module.rank R M := rank_pos_iff_nontrivial.mpr ‹_› end theorem exists_mem_ne_zero_of_rank_pos {s : Submodule R M} (h : 0 < Module.rank R s) : ∃ b : M, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot fun eq => by rw [eq, rank_bot] at h; exact lt_irrefl _ h end RankZero section Finite theorem Module.finite_of_rank_eq_nat [Module.Free R M] {n : ℕ} (h : Module.rank R M = n) : Module.Finite R M := by nontriviality R obtain ⟨⟨ι, b⟩⟩ := Module.Free.exists_basis (R := R) (M := M) have := mk_lt_aleph0_iff.mp <| b.linearIndependent.cardinal_le_rank |>.trans_eq h |>.trans_lt <| nat_lt_aleph0 n exact Module.Finite.of_basis b theorem Module.finite_of_rank_eq_zero [NoZeroSMulDivisors R M] (h : Module.rank R M = 0) : Module.Finite R M := by nontriviality R rw [rank_zero_iff] at h infer_instance theorem Module.finite_of_rank_eq_one [Module.Free R M] (h : Module.rank R M = 1) : Module.Finite R M := Module.finite_of_rank_eq_nat <| h.trans Nat.cast_one.symm section variable [StrongRankCondition R] /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ theorem Module.Basis.nonempty_fintype_index_of_rank_lt_aleph0 {ι : Type*} (b : Basis ι R M) (h : Module.rank R M < ℵ₀) : Nonempty (Fintype ι) := by rwa [← Cardinal.lift_lt, ← b.mk_eq_rank, Cardinal.lift_aleph0, Cardinal.lift_lt_aleph0, Cardinal.lt_aleph0_iff_fintype] at h /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ noncomputable def Module.Basis.fintypeIndexOfRankLtAleph0 {ι : Type*} (b : Basis ι R M) (h : Module.rank R M < ℵ₀) : Fintype ι := Classical.choice (b.nonempty_fintype_index_of_rank_lt_aleph0 h) /-- If a module has a finite dimension, all bases are indexed by a finite set. -/ theorem Module.Basis.finite_index_of_rank_lt_aleph0 {ι : Type*} {s : Set ι} (b : Basis s R M) (h : Module.rank R M < ℵ₀) : s.Finite := Set.finite_def.2 (b.nonempty_fintype_index_of_rank_lt_aleph0 h) end namespace LinearIndependent variable [StrongRankCondition R] theorem cardinalMk_le_finrank [Module.Finite R M] {ι : Type w} {b : ι → M} (h : LinearIndependent R b) : #ι ≤ finrank R M := by rw [← lift_le.{max v w}] simpa only [← finrank_eq_rank, lift_natCast, lift_le_nat_iff] using h.cardinal_lift_le_rank theorem fintype_card_le_finrank [Module.Finite R M] {ι : Type*} [Fintype ι] {b : ι → M} (h : LinearIndependent R b) : Fintype.card ι ≤ finrank R M := by simpa using h.cardinalMk_le_finrank theorem finset_card_le_finrank [Module.Finite R M] {b : Finset M} (h : LinearIndependent R (fun x => x : b → M)) : b.card ≤ finrank R M := by rw [← Fintype.card_coe] exact h.fintype_card_le_finrank theorem lt_aleph0_of_finite {ι : Type w} [Module.Finite R M] {v : ι → M} (h : LinearIndependent R v) : #ι < ℵ₀ := by apply Cardinal.lift_lt.1 apply lt_of_le_of_lt · apply h.cardinal_lift_le_rank · rw [← finrank_eq_rank, Cardinal.lift_aleph0, Cardinal.lift_natCast] apply Cardinal.nat_lt_aleph0 theorem finite [Module.Finite R M] {ι : Type*} {f : ι → M} (h : LinearIndependent R f) : Finite ι := Cardinal.lt_aleph0_iff_finite.1 <| h.lt_aleph0_of_finite theorem setFinite [Module.Finite R M] {b : Set M} (h : LinearIndependent R fun x : b => (x : M)) : b.Finite := Cardinal.lt_aleph0_iff_set_finite.mp h.lt_aleph0_of_finite end LinearIndependent lemma exists_set_linearIndependent_of_lt_rank {n : Cardinal} (hn : n < Module.rank R M) : ∃ s : Set M, #s = n ∧ LinearIndepOn R id s := by obtain ⟨⟨s, hs⟩, hs'⟩ := exists_lt_of_lt_ciSup' (hn.trans_eq (Module.rank_def R M)) obtain ⟨t, ht, ht'⟩ := le_mk_iff_exists_subset.mp hs'.le exact ⟨t, ht', hs.mono ht⟩ lemma exists_finset_linearIndependent_of_le_rank {n : ℕ} (hn : n ≤ Module.rank R M) : ∃ s : Finset M, s.card = n ∧ LinearIndepOn R id (s : Set M) := by rcases hn.eq_or_lt with h | h · obtain ⟨⟨s, hs⟩, hs'⟩ := Cardinal.exists_eq_natCast_of_iSup_eq _ (Cardinal.bddAbove_range _) _ (h.trans (Module.rank_def R M)).symm have : Finite s := lt_aleph0_iff_finite.mp (hs' ▸ nat_lt_aleph0 n) cases nonempty_fintype s refine ⟨s.toFinset, by simpa using hs', by simpa⟩ · obtain ⟨s, hs, hs'⟩ := exists_set_linearIndependent_of_lt_rank h have : Finite s := lt_aleph0_iff_finite.mp (hs ▸ nat_lt_aleph0 n) cases nonempty_fintype s exact ⟨s.toFinset, by simpa using hs, by simpa⟩ lemma exists_linearIndependent_of_le_rank {n : ℕ} (hn : n ≤ Module.rank R M) : ∃ f : Fin n → M, LinearIndependent R f := have ⟨_, hs, hs'⟩ := exists_finset_linearIndependent_of_le_rank hn ⟨_, (linearIndependent_equiv (Finset.equivFinOfCardEq hs).symm).mpr hs'⟩ lemma natCast_le_rank_iff [Nontrivial R] {n : ℕ} : n ≤ Module.rank R M ↔ ∃ f : Fin n → M, LinearIndependent R f := ⟨exists_linearIndependent_of_le_rank, fun H ↦ by simpa using H.choose_spec.cardinal_lift_le_rank⟩ lemma natCast_le_rank_iff_finset [Nontrivial R] {n : ℕ} : n ≤ Module.rank R M ↔ ∃ s : Finset M, s.card = n ∧ LinearIndependent R ((↑) : s → M) := ⟨exists_finset_linearIndependent_of_le_rank, fun ⟨s, h₁, h₂⟩ ↦ by simpa [h₁] using h₂.cardinal_le_rank⟩ lemma exists_finset_linearIndependent_of_le_finrank {n : ℕ} (hn : n ≤ finrank R M) : ∃ s : Finset M, s.card = n ∧ LinearIndependent R ((↑) : s → M) := by by_cases h : finrank R M = 0 · rw [le_zero_iff.mp (hn.trans_eq h)] exact ⟨∅, rfl, by convert linearIndependent_empty R M using 2 <;> aesop⟩ exact exists_finset_linearIndependent_of_le_rank ((Nat.cast_le.mpr hn).trans_eq (cast_toNat_of_lt_aleph0 (toNat_ne_zero.mp h).2)) lemma exists_linearIndependent_of_le_finrank {n : ℕ} (hn : n ≤ finrank R M) : ∃ f : Fin n → M, LinearIndependent R f := have ⟨_, hs, hs'⟩ := exists_finset_linearIndependent_of_le_finrank hn ⟨_, (linearIndependent_equiv (Finset.equivFinOfCardEq hs).symm).mpr hs'⟩ variable [Module.Finite R M] [StrongRankCondition R] in theorem Module.Finite.not_linearIndependent_of_infinite {ι : Type*} [Infinite ι] (v : ι → M) : ¬LinearIndependent R v := mt LinearIndependent.finite <| @not_finite _ _ section variable [NoZeroSMulDivisors R M] theorem iSupIndep.subtype_ne_bot_le_rank [Nontrivial R] {V : ι → Submodule R M} (hV : iSupIndep V) : Cardinal.lift.{v} #{ i : ι // V i ≠ ⊥ } ≤ Cardinal.lift.{w} (Module.rank R M) := by set I := { i : ι // V i ≠ ⊥ } have hI : ∀ i : I, ∃ v ∈ V i, v ≠ (0 : M) := by intro i rw [← Submodule.ne_bot_iff] exact i.prop choose v hvV hv using hI have : LinearIndependent R v := (hV.comp Subtype.coe_injective).linearIndependent _ hvV hv exact this.cardinal_lift_le_rank variable [Module.Finite R M] [StrongRankCondition R] theorem iSupIndep.subtype_ne_bot_le_finrank_aux {p : ι → Submodule R M} (hp : iSupIndep p) : #{ i // p i ≠ ⊥ } ≤ (finrank R M : Cardinal.{w}) := by suffices Cardinal.lift.{v} #{ i // p i ≠ ⊥ } ≤ Cardinal.lift.{v} (finrank R M : Cardinal.{w}) by rwa [Cardinal.lift_le] at this calc Cardinal.lift.{v} #{ i // p i ≠ ⊥ } ≤ Cardinal.lift.{w} (Module.rank R M) := hp.subtype_ne_bot_le_rank _ = Cardinal.lift.{w} (finrank R M : Cardinal.{v}) := by rw [finrank_eq_rank] _ = Cardinal.lift.{v} (finrank R M : Cardinal.{w}) := by simp /-- If `p` is an independent family of submodules of a `R`-finite module `M`, then the number of nontrivial subspaces in the family `p` is finite. -/ noncomputable def iSupIndep.fintypeNeBotOfFiniteDimensional {p : ι → Submodule R M} (hp : iSupIndep p) : Fintype { i : ι // p i ≠ ⊥ } := by suffices #{ i // p i ≠ ⊥ } < (ℵ₀ : Cardinal.{w}) by rw [Cardinal.lt_aleph0_iff_fintype] at this exact this.some refine lt_of_le_of_lt hp.subtype_ne_bot_le_finrank_aux ?_ simp [Cardinal.nat_lt_aleph0] /-- If `p` is an independent family of submodules of a `R`-finite module `M`, then the number of nontrivial subspaces in the family `p` is bounded above by the dimension of `M`. Note that the `Fintype` hypothesis required here can be provided by `iSupIndep.fintypeNeBotOfFiniteDimensional`. -/ theorem iSupIndep.subtype_ne_bot_le_finrank {p : ι → Submodule R M} (hp : iSupIndep p) [Fintype { i // p i ≠ ⊥ }] : Fintype.card { i // p i ≠ ⊥ } ≤ finrank R M := by simpa using hp.subtype_ne_bot_le_finrank_aux end variable [Module.Finite R M] [StrongRankCondition R] section open Finset /-- If a finset has cardinality larger than the rank of a module, then there is a nontrivial linear relation amongst its elements. -/ theorem Module.exists_nontrivial_relation_of_finrank_lt_card {t : Finset M} (h : finrank R M < t.card) : ∃ f : M → R, ∑ e ∈ t, f e • e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := by obtain ⟨g, sum, z, nonzero⟩ := Fintype.not_linearIndependent_iff.mp (mt LinearIndependent.finset_card_le_finrank h.not_ge) refine ⟨Subtype.val.extend g 0, ?_, z, z.2, by rwa [Subtype.val_injective.extend_apply]⟩ rw [← Finset.sum_finset_coe]; convert sum; apply Subtype.val_injective.extend_apply /-- If a finset has cardinality larger than `finrank + 1`, then there is a nontrivial linear relation amongst its elements, such that the coefficients of the relation sum to zero. -/ theorem Module.exists_nontrivial_relation_sum_zero_of_finrank_succ_lt_card {t : Finset M} (h : finrank R M + 1 < t.card) : ∃ f : M → R, ∑ e ∈ t, f e • e = 0 ∧ ∑ e ∈ t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := by -- Pick an element x₀ ∈ t, obtain ⟨x₀, x₀_mem⟩ := card_pos.1 ((Nat.succ_pos _).trans h) -- and apply the previous lemma to the {xᵢ - x₀} let shift : M ↪ M := ⟨(· - x₀), sub_left_injective⟩ classical let t' := (t.erase x₀).map shift have h' : finrank R M < t'.card := by rw [card_map, card_erase_of_mem x₀_mem] exact Nat.lt_pred_iff.mpr h -- to obtain a function `g`. obtain ⟨g, gsum, x₁, x₁_mem, nz⟩ := exists_nontrivial_relation_of_finrank_lt_card h' -- Then obtain `f` by translating back by `x₀`, -- and setting the value of `f` at `x₀` to ensure `∑ e ∈ t, f e = 0`. let f : M → R := fun z ↦ if z = x₀ then -∑ z ∈ t.erase x₀, g (z - x₀) else g (z - x₀) refine ⟨f, ?_, ?_, ?_⟩ -- After this, it's a matter of verifying the properties, -- based on the corresponding properties for `g`. · rw [sum_map, Embedding.coeFn_mk] at gsum simp_rw [f, ← t.sum_erase_add _ x₀_mem, if_pos, neg_smul, sum_smul, ← sub_eq_add_neg, ← sum_sub_distrib, ← gsum, smul_sub] refine sum_congr rfl fun x x_mem ↦ ?_ rw [if_neg (mem_erase.mp x_mem).1] · simp_rw [f, ← t.sum_erase_add _ x₀_mem, if_pos, add_neg_eq_zero] exact sum_congr rfl fun x x_mem ↦ if_neg (mem_erase.mp x_mem).1 · obtain ⟨x₁, x₁_mem', rfl⟩ := Finset.mem_map.mp x₁_mem have := mem_erase.mp x₁_mem' exact ⟨x₁, by simpa only [f, Embedding.coeFn_mk, sub_add_cancel, this.2, true_and, if_neg this.1]⟩ end end Finite section FinrankZero section variable [Nontrivial R] /-- A (finite dimensional) space that is a subsingleton has zero `finrank`. -/ @[nontriviality] theorem Module.finrank_zero_of_subsingleton [Subsingleton M] : finrank R M = 0 := by rw [finrank, rank_subsingleton', map_zero] lemma LinearIndependent.finrank_eq_zero_of_infinite {ι} [Infinite ι] {v : ι → M} (hv : LinearIndependent R v) : finrank R M = 0 := toNat_eq_zero.mpr <| .inr hv.aleph0_le_rank section variable [NoZeroSMulDivisors R M] /-- A finite dimensional space is nontrivial if it has positive `finrank`. -/ theorem Module.nontrivial_of_finrank_pos (h : 0 < finrank R M) : Nontrivial M := rank_pos_iff_nontrivial.mp (lt_rank_of_lt_finrank h) /-- A finite dimensional space is nontrivial if it has `finrank` equal to the successor of a natural number. -/ theorem Module.nontrivial_of_finrank_eq_succ {n : ℕ} (hn : finrank R M = n.succ) : Nontrivial M := nontrivial_of_finrank_pos (R := R) (by rw [hn]; exact n.succ_pos) end variable (R M) @[simp] theorem finrank_bot : finrank R (⊥ : Submodule R M) = 0 := finrank_eq_of_rank_eq (rank_bot _ _) end section StrongRankCondition variable [StrongRankCondition R] [Module.Finite R M] /-- A finite rank torsion-free module has positive `finrank` iff it has a nonzero element. -/ theorem Module.finrank_pos_iff_exists_ne_zero [NoZeroSMulDivisors R M] : 0 < finrank R M ↔ ∃ x : M, x ≠ 0 := by rw [← @rank_pos_iff_exists_ne_zero R M, ← finrank_eq_rank] norm_cast /-- An `R`-finite torsion-free module has positive `finrank` iff it is nontrivial. -/ theorem Module.finrank_pos_iff [NoZeroSMulDivisors R M] : 0 < finrank R M ↔ Nontrivial M := by rw [← rank_pos_iff_nontrivial (R := R), ← finrank_eq_rank] norm_cast /-- A nontrivial finite dimensional space has positive `finrank`. -/ theorem Module.finrank_pos [NoZeroSMulDivisors R M] [h : Nontrivial M] : 0 < finrank R M := finrank_pos_iff.mpr h /-- See `Module.finrank_zero_iff` for the stronger version with `NoZeroSMulDivisors R M`. -/ theorem Module.finrank_eq_zero_iff : finrank R M = 0 ↔ ∀ x : M, ∃ a : R, a ≠ 0 ∧ a • x = 0 := by rw [← rank_eq_zero_iff (R := R), ← finrank_eq_rank] norm_cast /-- A finite dimensional space has zero `finrank` iff it is a subsingleton. This is the `finrank` version of `rank_zero_iff`. -/ theorem Module.finrank_zero_iff [NoZeroSMulDivisors R M] : finrank R M = 0 ↔ Subsingleton M := by rw [← rank_zero_iff (R := R), ← finrank_eq_rank] norm_cast /-- Similar to `rank_quotient_add_rank_le` but for `finrank` and a finite `M`. -/ lemma Module.finrank_quotient_add_finrank_le (N : Submodule R M) : finrank R (M ⧸ N) + finrank R N ≤ finrank R M := by haveI := nontrivial_of_invariantBasisNumber R have := rank_quotient_add_rank_le N rw [← finrank_eq_rank R M, ← finrank_eq_rank R, ← N.finrank_eq_rank] at this exact mod_cast this end StrongRankCondition theorem Module.finrank_eq_zero_of_rank_eq_zero (h : Module.rank R M = 0) : finrank R M = 0 := by delta finrank rw [h, zero_toNat] theorem Submodule.bot_eq_top_of_rank_eq_zero [NoZeroSMulDivisors R M] (h : Module.rank R M = 0) : (⊥ : Submodule R M) = ⊤ := by nontriviality R rw [rank_zero_iff] at h subsingleton /-- See `rank_subsingleton` for the reason that `Nontrivial R` is needed. -/ @[simp] theorem Submodule.rank_eq_zero [Nontrivial R] [NoZeroSMulDivisors R M] {S : Submodule R M} : Module.rank R S = 0 ↔ S = ⊥ := ⟨fun h => (Submodule.eq_bot_iff _).2 fun x hx => congr_arg Subtype.val <| ((Submodule.eq_bot_iff _).1 <| Eq.symm <| Submodule.bot_eq_top_of_rank_eq_zero h) ⟨x, hx⟩ Submodule.mem_top, fun h => by rw [h, rank_bot]⟩ @[simp] theorem Submodule.finrank_eq_zero [StrongRankCondition R] [NoZeroSMulDivisors R M] {S : Submodule R M} [Module.Finite R S] : finrank R S = 0 ↔ S = ⊥ := by rw [← Submodule.rank_eq_zero, ← finrank_eq_rank, ← @Nat.cast_zero Cardinal, Nat.cast_inj] @[simp] lemma Submodule.one_le_finrank_iff [StrongRankCondition R] [NoZeroSMulDivisors R M] {S : Submodule R M} [Module.Finite R S] : 1 ≤ finrank R S ↔ S ≠ ⊥ := by simp [← not_iff_not] @[simp] theorem Set.finrank_empty [Nontrivial R] : Set.finrank R (∅ : Set M) = 0 := by rw [Set.finrank, span_empty, finrank_bot] variable [Module.Free R M] theorem finrank_eq_zero_of_basis_imp_not_finite (h : ∀ s : Set M, Basis.{v} (s : Set M) R M → ¬s.Finite) : finrank R M = 0 := by cases subsingleton_or_nontrivial R · have := Module.subsingleton R M exact (h ∅ ⟨LinearEquiv.ofSubsingleton _ _⟩ Set.finite_empty).elim obtain ⟨_, ⟨b⟩⟩ := (Module.free_iff_set R M).mp ‹_› have := Set.Infinite.to_subtype (h _ b) exact b.linearIndependent.finrank_eq_zero_of_infinite theorem finrank_eq_zero_of_basis_imp_false (h : ∀ s : Finset M, Basis.{v} (s : Set M) R M → False) : finrank R M = 0 := finrank_eq_zero_of_basis_imp_not_finite fun s b hs => h hs.toFinset (by convert b simp) theorem finrank_eq_zero_of_not_exists_basis (h : ¬∃ s : Finset M, Nonempty (Basis (s : Set M) R M)) : finrank R M = 0 := finrank_eq_zero_of_basis_imp_false fun s b => h ⟨s, ⟨b⟩⟩ theorem finrank_eq_zero_of_not_exists_basis_finite (h : ¬∃ (s : Set M) (_ : Basis.{v} (s : Set M) R M), s.Finite) : finrank R M = 0 := finrank_eq_zero_of_basis_imp_not_finite fun s b hs => h ⟨s, b, hs⟩ theorem finrank_eq_zero_of_not_exists_basis_finset (h : ¬∃ s : Finset M, Nonempty (Basis s R M)) : finrank R M = 0 := finrank_eq_zero_of_basis_imp_false fun s b => h ⟨s, ⟨b⟩⟩ end FinrankZero section RankOne variable [NoZeroSMulDivisors R M] [StrongRankCondition R] /-- If there is a nonzero vector and every other vector is a multiple of it, then the module has dimension one. -/ theorem rank_eq_one (v : M) (n : v ≠ 0) (h : ∀ w : M, ∃ c : R, c • v = w) : Module.rank R M = 1 := by haveI := nontrivial_of_invariantBasisNumber R obtain ⟨b⟩ := (Basis.basis_singleton_iff.{_, _, u} PUnit).mpr ⟨v, n, h⟩ rw [rank_eq_card_basis b, Fintype.card_punit, Nat.cast_one] /-- If there is a nonzero vector and every other vector is a multiple of it, then the module has dimension one. -/ theorem finrank_eq_one (v : M) (n : v ≠ 0) (h : ∀ w : M, ∃ c : R, c • v = w) : finrank R M = 1 := finrank_eq_of_rank_eq (rank_eq_one v n h) /-- If every vector is a multiple of some `v : M`, then `M` has dimension at most one. -/ theorem finrank_le_one (v : M) (h : ∀ w : M, ∃ c : R, c • v = w) : finrank R M ≤ 1 := by haveI := nontrivial_of_invariantBasisNumber R rcases eq_or_ne v 0 with (rfl | hn) · haveI := _root_.subsingleton_of_forall_eq (0 : M) fun w => by obtain ⟨c, rfl⟩ := h w simp rw [finrank_zero_of_subsingleton] exact zero_le_one · exact (finrank_eq_one v hn h).le end RankOne namespace Module variable {ι : Type*} @[simp] lemma finite_finsupp_iff : Module.Finite R (ι →₀ M) ↔ IsEmpty ι ∨ Subsingleton M ∨ Module.Finite R M ∧ Finite ι where mp := by simp only [or_iff_not_imp_left, not_subsingleton_iff_nontrivial, not_isEmpty_iff] rintro h ⟨i⟩ _ obtain ⟨s, hs⟩ := id h exact ⟨.of_surjective (Finsupp.lapply (R := R) (M := M) i) (Finsupp.apply_surjective i), finite_of_span_finite_eq_top_finsupp s.finite_toSet hs⟩ mpr | .inl _ => inferInstance | .inr <| .inl h => inferInstance | .inr <| .inr h => by cases h; infer_instance @[simp high] lemma finite_finsupp_self_iff : Module.Finite R (ι →₀ R) ↔ Subsingleton R ∨ Finite ι := by simp only [finite_finsupp_iff, Finite.self, true_and, or_iff_right_iff_imp] exact fun _ ↦ .inr inferInstance end Module
interval.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import div fintype bigop order ssralg finset fingroup. From mathcomp Require Import ssrnum. (******************************************************************************) (* Intervals in ordered types *) (* *) (* This file provides support for intervals in ordered types. The datatype *) (* (interval T) gives a formal characterization of an interval, as the pair *) (* of its right and left bounds. *) (* interval T == the type of formal intervals on T. *) (* x \in i == when i is a formal interval on an ordered type, *) (* \in can be used to test membership. *) (* itvP x_in_i == where x_in_i has type x \in i, if i is ground, *) (* gives a set of rewrite rules that x_in_i implies *) (* lteBSide, bnd_simp == multirules to simplify inequalities between interval *) (* bounds *) (* miditv i == middle point of interval i *) (* *) (* When using interval.v, the lemma `in_itv` is in practice very useful. For *) (* example, the execution of the tactic `rewrite in_itv` w.r.t. an hypothesis *) (* of the form x \in `]a, b[ into a < x < b. *) (* *) (* Intervals of T form an partially ordered type (porderType) whose ordering *) (* is the subset relation. If T is a lattice, intervals also form a lattice *) (* (latticeType) whose meet and join are intersection and convex hull *) (* respectively. They are distributive if T is an orderType. *) (* *) (* We provide a set of notations to write intervals (see below) *) (* `[a, b], `]a, b], ..., `]-oo, a], ..., `]-oo, +oo[ *) (* The substrings "oo", "oc", "co", "cc" in the names of lemmas respectively *) (* stand for the intervals of the shape `]a, b[, `]a, b], `[a, b[, `[a, b]. *) (* The substrings "pinfty" and "ninfty" in the names of lemmas stand for *) (* +oo and -oo. *) (* We also provide the lemma subitvP which computes the inequalities one *) (* needs to prove when trying to prove the inclusion of intervals. *) (* *) (* Remark that we cannot implement a boolean comparison test for intervals on *) (* an arbitrary ordered types, for this problem might be undecidable. Note *) (* also that type (interval R) may contain several inhabitants coding for the *) (* same interval. However, these pathological issues do not arise when R is a *) (* real domain: we could provide a specific theory for this important case. *) (* *) (* References: *) (* - Cyril Cohen, Assia Mahboubi, Formal proofs in real algebraic geometry: *) (* from ordered fields quantifier elimination, LMCS, 2012 *) (* - Cyril Cohen, Formalized algebraic numbers: construction and first-order *) (* theory, PhD thesis, 2012, section 4.3 *) (* *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "'-oo'". Reserved Notation "'+oo'". Reserved Notation "`[ a , b ]" (format "`[ a , b ]"). Reserved Notation "`] a , b ]" (format "`] a , b ]"). Reserved Notation "`[ a , b [" (format "`[ a , b ["). Reserved Notation "`] a , b [" (format "`] a , b ["). Reserved Notation "`] '-oo' , b ]" (format "`] '-oo' , b ]"). Reserved Notation "`] '-oo' , b [" (format "`] '-oo' , b ["). Reserved Notation "`[ a , '+oo' [" (format "`[ a , '+oo' ["). Reserved Notation "`] a , '+oo' [" (format "`] a , '+oo' ["). Reserved Notation "`] -oo , '+oo' [" (format "`] -oo , '+oo' ["). Local Open Scope order_scope. Import Order.TTheory. Variant itv_bound (T : Type) : Type := BSide of bool & T | BInfty of bool. Notation BLeft := (BSide true). Notation BRight := (BSide false). Notation "'-oo'" := (BInfty _ true) : order_scope. Notation "'+oo'" := (BInfty _ false) : order_scope. Variant interval (T : Type) := Interval of itv_bound T & itv_bound T. Coercion pair_of_interval T (I : interval T) : itv_bound T * itv_bound T := let: Interval b1 b2 := I in (b1, b2). (* We provide the 9 following notations to help writing formal intervals *) Notation "`[ a , b ]" := (Interval (BLeft a) (BRight b)) : order_scope. Notation "`] a , b ]" := (Interval (BRight a) (BRight b)) : order_scope. Notation "`[ a , b [" := (Interval (BLeft a) (BLeft b)) : order_scope. Notation "`] a , b [" := (Interval (BRight a) (BLeft b)) : order_scope. Notation "`] '-oo' , b ]" := (Interval -oo (BRight b)) : order_scope. Notation "`] '-oo' , b [" := (Interval -oo (BLeft b)) : order_scope. Notation "`[ a , '+oo' [" := (Interval (BLeft a) +oo) : order_scope. Notation "`] a , '+oo' [" := (Interval (BRight a) +oo) : order_scope. Notation "`] -oo , '+oo' [" := (Interval -oo +oo) : order_scope. Notation "`[ a , b ]" := (Interval (BLeft a) (BRight b)) : ring_scope. Notation "`] a , b ]" := (Interval (BRight a) (BRight b)) : ring_scope. Notation "`[ a , b [" := (Interval (BLeft a) (BLeft b)) : ring_scope. Notation "`] a , b [" := (Interval (BRight a) (BLeft b)) : ring_scope. Notation "`] '-oo' , b ]" := (Interval -oo (BRight b)) : ring_scope. Notation "`] '-oo' , b [" := (Interval -oo (BLeft b)) : ring_scope. Notation "`[ a , '+oo' [" := (Interval (BLeft a) +oo) : ring_scope. Notation "`] a , '+oo' [" := (Interval (BRight a) +oo) : ring_scope. Notation "`] -oo , '+oo' [" := (Interval -oo +oo) : ring_scope. Fact itv_bound_display (disp : Order.disp_t) : Order.disp_t. Proof. exact. Qed. Fact interval_display (disp : Order.disp_t) : Order.disp_t. Proof. exact. Qed. Module IntervalCan. Section IntervalCan. Variable T : Type. Lemma itv_bound_can : cancel (fun b : itv_bound T => match b with BSide b x => (b, Some x) | BInfty b => (b, None) end) (fun b => match b with (b, Some x) => BSide b x | (b, None) => BInfty _ b end). Proof. by case. Qed. Lemma interval_can : @cancel _ (interval T) (fun '(Interval b1 b2) => (b1, b2)) (fun '(b1, b2) => Interval b1 b2). Proof. by case. Qed. End IntervalCan. #[export, hnf] HB.instance Definition _ (T : eqType) := Equality.copy (itv_bound T) (can_type (@itv_bound_can T)). #[export, hnf] HB.instance Definition _ (T : eqType) := Equality.copy (interval T) (can_type (@interval_can T)). #[export, hnf] HB.instance Definition _ (T : choiceType) := Choice.copy (itv_bound T) (can_type (@itv_bound_can T)). #[export, hnf] HB.instance Definition _ (T : choiceType) := Choice.copy (interval T) (can_type (@interval_can T)). #[export, hnf] HB.instance Definition _ (T : countType) := Countable.copy (itv_bound T) (can_type (@itv_bound_can T)). #[export, hnf] HB.instance Definition _ (T : countType) := Countable.copy (interval T) (can_type (@interval_can T)). #[export, hnf] HB.instance Definition _ (T : finType) := Finite.copy (itv_bound T) (can_type (@itv_bound_can T)). #[export, hnf] HB.instance Definition _ (T : finType) := Finite.copy (interval T) (can_type (@interval_can T)). Module Exports. HB.reexport. End Exports. End IntervalCan. Export IntervalCan.Exports. Section IntervalPOrder. Variable (disp : Order.disp_t) (T : porderType disp). Implicit Types (x y z : T) (b bl br : itv_bound T) (i : interval T). Definition le_bound b1 b2 := match b1, b2 with | -oo, _ | _, +oo => true | BSide b1 x1, BSide b2 x2 => x1 < x2 ?<= if b2 ==> b1 | _, _ => false end. Definition lt_bound b1 b2 := match b1, b2 with | -oo, +oo | -oo, BSide _ _ | BSide _ _, +oo => true | BSide b1 x1, BSide b2 x2 => x1 < x2 ?<= if b1 && ~~ b2 | _, _ => false end. Lemma lt_bound_def b1 b2 : lt_bound b1 b2 = (b2 != b1) && le_bound b1 b2. Proof. by case: b1 b2 => [[]?|[]][[]?|[]] //=; rewrite lt_def. Qed. Lemma le_bound_refl : reflexive le_bound. Proof. by move=> [[]?|[]] /=. Qed. Lemma le_bound_anti : antisymmetric le_bound. Proof. by case=> [[]?|[]] [[]?|[]] //=; case: comparableP => // ->. Qed. Lemma le_bound_trans : transitive le_bound. Proof. by case=> [[]?|[]] [[]?|[]] [[]?|[]] lexy leyz //; apply: (lteif_imply _ (lteif_trans lexy leyz)). Qed. HB.instance Definition _ := Order.isPOrder.Build (itv_bound_display disp) (itv_bound T) lt_bound_def le_bound_refl le_bound_anti le_bound_trans. Lemma bound_lexx c1 c2 x : (BSide c1 x <= BSide c2 x) = (c2 ==> c1). Proof. by rewrite /<=%O /= lteifxx. Qed. Lemma bound_ltxx c1 c2 x : (BSide c1 x < BSide c2 x) = (c1 && ~~ c2). Proof. by rewrite /<%O /= lteifxx. Qed. Lemma ge_pinfty b : (+oo <= b) = (b == +oo). Proof. by case: b => [|] []. Qed. Lemma le_ninfty b : (b <= -oo) = (b == -oo). Proof. by case: b => // - []. Qed. Lemma gt_pinfty b : (+oo < b) = false. Proof. by []. Qed. Lemma lt_ninfty b : (b < -oo) = false. Proof. by case: b => // -[]. Qed. Lemma ltBSide x y (b b' : bool) : BSide b x < BSide b' y = (x < y ?<= if b && ~~ b'). Proof. by []. Qed. Lemma leBSide x y (b b' : bool) : BSide b x <= BSide b' y = (x < y ?<= if b' ==> b). Proof. by []. Qed. Definition lteBSide := (ltBSide, leBSide). Lemma ltBRight_leBLeft b x : b < BRight x = (b <= BLeft x). Proof. by move: b => [[] b|[]]. Qed. Lemma leBRight_ltBLeft b x : BRight x <= b = (BLeft x < b). Proof. by move: b => [[] b|[]]. Qed. Let BLeft_ltE x y (b : bool) : BSide b x < BLeft y = (x < y). Proof. by case: b. Qed. Let BRight_leE x y (b : bool) : BSide b x <= BRight y = (x <= y). Proof. by case: b. Qed. Let BRight_BLeft_leE x y : BRight x <= BLeft y = (x < y). Proof. by []. Qed. Let BLeft_BRight_ltE x y : BLeft x < BRight y = (x <= y). Proof. by []. Qed. Let BRight_BSide_ltE x y (b : bool) : BRight x < BSide b y = (x < y). Proof. by case: b. Qed. Let BLeft_BSide_leE x y (b : bool) : BLeft x <= BSide b y = (x <= y). Proof. by case: b. Qed. Let BSide_ltE x y (b : bool) : BSide b x < BSide b y = (x < y). Proof. by case: b. Qed. Let BSide_leE x y (b : bool) : BSide b x <= BSide b y = (x <= y). Proof. by case: b. Qed. Let BInfty_leE a : a <= BInfty T false. Proof. by case: a => [[] a|[]]. Qed. Let BInfty_geE a : BInfty T true <= a. Proof. by case: a => [[] a|[]]. Qed. Let BInfty_le_eqE a : BInfty T false <= a = (a == BInfty T false). Proof. by case: a => [[] a|[]]. Qed. Let BInfty_ge_eqE a : a <= BInfty T true = (a == BInfty T true). Proof. by case: a => [[] a|[]]. Qed. Let BInfty_ltE a : a < BInfty T false = (a != BInfty T false). Proof. by case: a => [[] a|[]]. Qed. Let BInfty_gtE a : BInfty T true < a = (a != BInfty T true). Proof. by case: a => [[] a|[]]. Qed. Let BInfty_ltF a : BInfty T false < a = false. Proof. by case: a => [[] a|[]]. Qed. Let BInfty_gtF a : a < BInfty T true = false. Proof. by case: a => [[] a|[]]. Qed. Let BInfty_BInfty_ltE : BInfty T true < BInfty T false. Proof. by []. Qed. Definition bnd_simp := (BLeft_ltE, BRight_leE, BRight_BLeft_leE, BLeft_BRight_ltE, BRight_BSide_ltE, BLeft_BSide_leE, BSide_ltE, BSide_leE, BInfty_leE, BInfty_geE, BInfty_BInfty_ltE, BInfty_le_eqE, BInfty_ge_eqE, BInfty_ltE, BInfty_gtE, BInfty_ltF, BInfty_gtF, @lexx _ T, @ltxx _ T, @eqxx T). Lemma comparable_BSide_min s (x y : T) : (x >=< y)%O -> BSide s (Order.min x y) = Order.min (BSide s x) (BSide s y). Proof. by rewrite !minEle bnd_simp => /comparable_leP[]. Qed. Lemma comparable_BSide_max s (x y : T) : (x >=< y)%O -> BSide s (Order.max x y) = Order.max (BSide s x) (BSide s y). Proof. by rewrite !maxEle bnd_simp => /comparable_leP[]. Qed. Definition subitv i1 i2 := let: Interval b1l b1r := i1 in let: Interval b2l b2r := i2 in (b2l <= b1l) && (b1r <= b2r). Lemma subitv_refl : reflexive subitv. Proof. by case=> /= ? ?; rewrite !lexx. Qed. Lemma subitv_anti : antisymmetric subitv. Proof. by case=> [? ?][? ?]; rewrite andbACA => /andP[] /le_anti -> /le_anti ->. Qed. Lemma subitv_trans : transitive subitv. Proof. case=> [yl yr][xl xr][zl zr] /andP [Hl Hr] /andP [Hl' Hr'] /=. by rewrite (le_trans Hl' Hl) (le_trans Hr Hr'). Qed. HB.instance Definition _ := Order.isPOrder.Build (interval_display disp) (interval T) (fun _ _ => erefl) subitv_refl subitv_anti subitv_trans. Definition pred_of_itv i : pred T := [pred x | `[x, x] <= i]. Canonical Structure itvPredType := PredType pred_of_itv. Lemma subitvE b1l b1r b2l b2r : (Interval b1l b1r <= Interval b2l b2r) = (b2l <= b1l) && (b1r <= b2r). Proof. by []. Qed. Lemma in_itv x i : x \in i = let: Interval l u := i in match l with | BSide b lb => lb < x ?<= if b | BInfty b => b end && match u with | BSide b ub => x < ub ?<= if ~~ b | BInfty b => ~~ b end. Proof. by case: i => [[? ?|[]][|[]]]. Qed. Lemma itv_boundlr bl br x : (x \in Interval bl br) = (bl <= BLeft x) && (BRight x <= br). Proof. by []. Qed. Lemma itv_splitI bl br x : x \in Interval bl br = (x \in Interval bl +oo) && (x \in Interval -oo br). Proof. by rewrite !itv_boundlr andbT. Qed. Lemma subitvP i1 i2 : i1 <= i2 -> {subset i1 <= i2}. Proof. by move=> ? ? /le_trans; exact. Qed. (* Remove the line below when requiring Coq >= 8.20 *) #[warning="-unsupported-attributes"] #[warn(note="The lemma subset_itv was generalized in MathComp 2.4.0 and the original was renamed to subset_itv_bound.", cats="mathcomp-subset-itv")] Lemma subset_itv (x y z u : itv_bound T) : x <= y -> z <= u -> {subset Interval y z <= Interval x u}. Proof. by move=> xy zu; apply: subitvP; rewrite subitvE xy zu. Qed. #[deprecated(since="mathcomp 2.4.0", note="Use subset_itv instead.")] Lemma subset_itv_bound (r s u v : bool) x y : r <= u -> v <= s -> {subset Interval (BSide r x) (BSide s y) <= Interval (BSide u x) (BSide v y)}. Proof. by move: r s u v=> [] [] [] []// *; apply: subset_itv; rewrite bnd_simp. Qed. Lemma subset_itv_oo_cc x y : {subset `]x, y[ <= `[x, y]}. Proof. by apply: subset_itv; rewrite bnd_simp. Qed. Lemma subset_itv_oo_oc x y : {subset `]x, y[ <= `]x, y]}. Proof. by apply: subset_itv; rewrite bnd_simp. Qed. Lemma subset_itv_oo_co x y : {subset `]x, y[ <= `[x, y[}. Proof. by apply: subset_itv; rewrite bnd_simp. Qed. Lemma subset_itv_oc_cc x y : {subset `]x, y] <= `[x, y]}. Proof. by apply: subset_itv; rewrite bnd_simp. Qed. Lemma subset_itv_co_cc x y : {subset `[x, y[ <= `[x, y]}. Proof. by apply: subset_itv; rewrite bnd_simp. Qed. Lemma itvxx x : `[x, x] =i pred1 x. Proof. by move=> y; rewrite in_itv/= -eq_le eq_sym. Qed. Lemma itvxxP y x : reflect (y = x) (y \in `[x, x]). Proof. by rewrite itvxx; apply/eqP. Qed. Lemma subitvPl b1l b2l br : b2l <= b1l -> {subset Interval b1l br <= Interval b2l br}. Proof. by move=> ?; apply: subitvP; rewrite subitvE lexx andbT. Qed. Lemma subitvPr bl b1r b2r : b1r <= b2r -> {subset Interval bl b1r <= Interval bl b2r}. Proof. by move=> ?; apply: subitvP; rewrite subitvE lexx. Qed. Lemma itv_xx x cl cr y : y \in Interval (BSide cl x) (BSide cr x) = cl && ~~ cr && (y == x). Proof. by case: cl cr => [] []; rewrite [LHS]lteif_anti // eq_sym. Qed. Lemma boundl_in_itv c x b : x \in Interval (BSide c x) b = c && (BRight x <= b). Proof. by rewrite itv_boundlr bound_lexx. Qed. Lemma boundr_in_itv c x b : x \in Interval b (BSide c x) = ~~ c && (b <= BLeft x). Proof. by rewrite itv_boundlr bound_lexx implybF andbC. Qed. Definition bound_in_itv := (boundl_in_itv, boundr_in_itv). Lemma lt_in_itv bl br x : x \in Interval bl br -> bl < br. Proof. by case/andP; apply/le_lt_trans. Qed. Lemma lteif_in_itv cl cr yl yr x : x \in Interval (BSide cl yl) (BSide cr yr) -> yl < yr ?<= if cl && ~~ cr. Proof. exact: lt_in_itv. Qed. Lemma itv_ge b1 b2 : ~~ (b1 < b2) -> Interval b1 b2 =i pred0. Proof. by move=> ltb12 y; apply/contraNF: ltb12; apply/lt_in_itv. Qed. Definition itv_decompose i x : Prop := let: Interval l u := i in (match l return Prop with | BSide b lb => lb < x ?<= if b | BInfty b => b end * match u return Prop with | BSide b ub => x < ub ?<= if ~~ b | BInfty b => ~~ b end)%type. Lemma itv_dec : forall x i, reflect (itv_decompose i x) (x \in i). Proof. by move=> ? [[? ?|[]][? ?|[]]]; apply: (iffP andP); case. Qed. Arguments itv_dec {x i}. (* we compute a set of rewrite rules associated to an interval *) Definition itv_rewrite i x : Type := let: Interval l u := i in (match l with | BLeft a => (a <= x) * (x < a = false) | BRight a => (a <= x) * (a < x) * (x <= a = false) * (x < a = false) | -oo => forall x : T, x == x | +oo => forall b : bool, unkeyed b = false end * match u with | BRight b => (x <= b) * (b < x = false) | BLeft b => (x <= b) * (x < b) * (b <= x = false) * (b < x = false) | +oo => forall x : T, x == x | -oo => forall b : bool, unkeyed b = false end * match l, u with | BLeft a, BRight b => (a <= b) * (b < a = false) * (a \in `[a, b]) * (b \in `[a, b]) | BLeft a, BLeft b => (a <= b) * (a < b) * (b <= a = false) * (b < a = false) * (a \in `[a, b]) * (a \in `[a, b[) * (b \in `[a, b]) * (b \in `]a, b]) | BRight a, BRight b => (a <= b) * (a < b) * (b <= a = false) * (b < a = false) * (a \in `[a, b]) * (a \in `[a, b[) * (b \in `[a, b]) * (b \in `]a, b]) | BRight a, BLeft b => (a <= b) * (a < b) * (b <= a = false) * (b < a = false) * (a \in `[a, b]) * (a \in `[a, b[) * (b \in `[a, b]) * (b \in `]a, b]) | _, _ => forall x : T, x == x end)%type. Lemma itvP x i : x \in i -> itv_rewrite i x. Proof. case: i => [[[]a|[]][[]b|[]]] /andP [] ha hb; rewrite /= ?bound_in_itv; do ![split | apply/negbTE; rewrite (le_gtF, lt_geF)]; by [|apply: ltW | move: (lteif_trans ha hb) => //=; exact: ltW]. Qed. Arguments itvP [x i]. Lemma itv_splitU1 b x : b <= BLeft x -> Interval b (BRight x) =i [predU1 x & Interval b (BLeft x)]. Proof. move=> bx z; rewrite !inE/= !subitvE ?bnd_simp//= lt_neqAle. by case: (eqVneq z x) => [->|]//=; rewrite lexx bx. Qed. Lemma itv_split1U b x : BRight x <= b -> Interval (BLeft x) b =i [predU1 x & Interval (BRight x) b]. Proof. move=> bx z; rewrite !inE/= !subitvE ?bnd_simp//= lt_neqAle. by case: (eqVneq z x) => [->|]//=; rewrite lexx bx. Qed. End IntervalPOrder. Section IntervalLattice. Variable (disp : Order.disp_t) (T : latticeType disp). Implicit Types (x y z : T) (b bl br : itv_bound T) (i : interval T). Definition bound_meet bl br : itv_bound T := match bl, br with | -oo, _ | _, -oo => -oo | +oo, b | b, +oo => b | BSide xb x, BSide yb y => BSide (((x <= y) && xb) || ((y <= x) && yb)) (x `&` y) end. Definition bound_join bl br : itv_bound T := match bl, br with | -oo, b | b, -oo => b | +oo, _ | _, +oo => +oo | BSide xb x, BSide yb y => BSide ((~~ (x <= y) || yb) && (~~ (y <= x) || xb)) (x `|` y) end. Lemma bound_meetC : commutative bound_meet. Proof. case=> [? ?|[]][? ?|[]] //=; rewrite meetC; congr BSide. by case: lcomparableP; rewrite ?orbF // orbC. Qed. Lemma bound_joinC : commutative bound_join. Proof. case=> [? ?|[]][? ?|[]] //=; rewrite joinC; congr BSide. by case: lcomparableP; rewrite ?andbT // andbC. Qed. Lemma bound_meetA : associative bound_meet. Proof. case=> [? x|[]][? y|[]][? z|[]] //=; rewrite !lexI meetA; congr BSide. by case: (lcomparableP x y) => [|||->]; case: (lcomparableP y z) => [|||->]; case: (lcomparableP x z) => [|||//<-]; case: (lcomparableP x y); rewrite //= ?andbF ?orbF ?lexx ?orbA //; case: (lcomparableP y z). Qed. Lemma bound_joinA : associative bound_join. Proof. case=> [? x|[]][? y|[]][? z|[]] //=; rewrite !leUx joinA; congr BSide. by case: (lcomparableP x y) => [|||->]; case: (lcomparableP y z) => [|||->]; case: (lcomparableP x z) => [|||//<-]; case: (lcomparableP x y); rewrite //= ?orbT ?andbT ?lexx ?andbA //; case: (lcomparableP y z). Qed. Lemma bound_meetKU b2 b1 : bound_join b1 (bound_meet b1 b2) = b1. Proof. case: b1 b2 => [? ?|[]][? ?|[]] //=; rewrite ?meetKU ?joinxx ?leIl ?lexI ?lexx ?andbb //=; congr BSide. by case: lcomparableP; rewrite ?orbF /= ?andbb ?orbK. Qed. Lemma bound_joinKI b2 b1 : bound_meet b1 (bound_join b1 b2) = b1. Proof. case: b1 b2 => [? ?|[]][? ?|[]] //=; rewrite ?joinKI ?meetxx ?leUl ?leUx ?lexx ?orbb //=; congr BSide. by case: lcomparableP; rewrite ?orbF ?orbb ?andKb. Qed. Lemma bound_leEmeet b1 b2 : (b1 <= b2) = (bound_meet b1 b2 == b1). Proof. case: b1 b2 => [[]t[][]|[][][]] //=; rewrite ?eqxx// => t'; rewrite [LHS]/<=%O /eq_op ?andbT ?andbF ?orbF/= /eq_op/= /eq_op/=; case: lcomparableP => //=; rewrite ?eqxx//=; [| | |]. - by move/lt_eqF. - move=> ic; apply: esym; apply: contraNF ic. by move=> /eqP/meet_idPl; apply: le_comparable. - by move/lt_eqF. - move=> ic; apply: esym; apply: contraNF ic. by move=> /eqP/meet_idPl; apply: le_comparable. Qed. HB.instance Definition _ := Order.POrder_isLattice.Build (itv_bound_display disp) (itv_bound T) bound_meetC bound_joinC bound_meetA bound_joinA bound_joinKI bound_meetKU bound_leEmeet. Lemma bound_le0x b : -oo <= b. Proof. by []. Qed. Lemma bound_lex1 b : b <= +oo. Proof. by case: b => [|[]]. Qed. HB.instance Definition _ := Order.hasBottom.Build (itv_bound_display disp) (itv_bound T) bound_le0x. HB.instance Definition _ := Order.hasTop.Build (itv_bound_display disp) (itv_bound T) bound_lex1. Definition itv_meet i1 i2 : interval T := let: Interval b1l b1r := i1 in let: Interval b2l b2r := i2 in Interval (b1l `|` b2l) (b1r `&` b2r). Definition itv_join i1 i2 : interval T := let: Interval b1l b1r := i1 in let: Interval b2l b2r := i2 in Interval (b1l `&` b2l) (b1r `|` b2r). Lemma itv_meetC : commutative itv_meet. Proof. by case=> [? ?][? ?] /=; rewrite meetC joinC. Qed. Lemma itv_joinC : commutative itv_join. Proof. by case=> [? ?][? ?] /=; rewrite meetC joinC. Qed. Lemma itv_meetA : associative itv_meet. Proof. by case=> [? ?][? ?][? ?] /=; rewrite meetA joinA. Qed. Lemma itv_joinA : associative itv_join. Proof. by case=> [? ?][? ?][? ?] /=; rewrite meetA joinA. Qed. Lemma itv_meetKU i2 i1 : itv_join i1 (itv_meet i1 i2) = i1. Proof. by case: i1 i2 => [? ?][? ?] /=; rewrite meetKU joinKI. Qed. Lemma itv_joinKI i2 i1 : itv_meet i1 (itv_join i1 i2) = i1. Proof. by case: i1 i2 => [? ?][? ?] /=; rewrite meetKU joinKI. Qed. Lemma itv_leEmeet i1 i2 : (i1 <= i2) = (itv_meet i1 i2 == i1). Proof. by case: i1 i2 => [? ?] [? ?]; rewrite /eq_op/=/eq_op/= eq_meetl eq_joinl. Qed. HB.instance Definition _ := Order.POrder_isLattice.Build (interval_display disp) (interval T) itv_meetC itv_joinC itv_meetA itv_joinA itv_joinKI itv_meetKU itv_leEmeet. Lemma itv_le0x i : Interval +oo -oo <= i. Proof. by case: i => [[|[]]]. Qed. Lemma itv_lex1 i : i <= `]-oo, +oo[. Proof. by case: i => [?[|[]]]. Qed. HB.instance Definition _ := Order.hasBottom.Build (interval_display disp) (interval T) itv_le0x. HB.instance Definition _ := Order.hasTop.Build (interval_display disp) (interval T) itv_lex1. Lemma in_itvI x i1 i2 : x \in i1 `&` i2 = (x \in i1) && (x \in i2). Proof. exact: lexI. Qed. End IntervalLattice. Section IntervalTotal. Variable (disp : Order.disp_t) (T : orderType disp). Implicit Types (a b c : itv_bound T) (x y z : T) (i : interval T). Lemma BSide_min s (x y : T) : BSide s (Order.min x y) = Order.min (BSide s x) (BSide s y). Proof. exact: comparable_BSide_min. Qed. Lemma BSide_max s (x y : T) : BSide s (Order.max x y) = Order.max (BSide s x) (BSide s y). Proof. exact: comparable_BSide_max. Qed. Lemma itv_bound_total : total (<=%O : rel (itv_bound T)). Proof. by move=> [[]?|[]][[]?|[]]; rewrite /<=%O //=; case: ltgtP. Qed. HB.instance Definition _ := Order.Lattice_isTotal.Build (itv_bound_display disp) (itv_bound T) itv_bound_total. Lemma itv_meetUl : @left_distributive (interval T) _ Order.meet Order.join. Proof. by move=> [? ?][? ?][? ?]; rewrite /Order.meet /Order.join /= -meetUl -joinIl. Qed. HB.instance Definition _ := Order.Lattice_Meet_isDistrLattice.Build (interval_display disp) (interval T) itv_meetUl. Lemma itv_splitU c a b : a <= c <= b -> forall y, y \in Interval a b = (y \in Interval a c) || (y \in Interval c b). Proof. case/andP => leac lecb y. rewrite !itv_boundlr !(ltNge (BLeft y) _ : (BRight y <= _) = _). case: (leP a) (leP b) (leP c) => leay [] leby [] lecy //=. - by case: leP lecy (le_trans lecb leby). - by case: leP leay (le_trans leac lecy). Qed. Lemma itv_splitUeq x a b : x \in Interval a b -> forall y, y \in Interval a b = [|| y \in Interval a (BLeft x), y == x | y \in Interval (BRight x) b]. Proof. case/andP => ax xb y; rewrite (@itv_splitU (BLeft x)) ?ax ?ltW //. by congr orb; rewrite (@itv_splitU (BRight x)) ?bound_lexx // itv_xx. Qed. Lemma itv_total_meet3E i1 i2 i3 : i1 `&` i2 `&` i3 \in [:: i1 `&` i2; i1 `&` i3; i2 `&` i3]. Proof. case: i1 i2 i3 => [b1l b1r] [b2l b2r] [b3l b3r]; rewrite !inE /eq_op /=. case: (leP b1l b2l); case: (leP b1l b3l); case: (leP b2l b3l); case: (leP b1r b2r); case: (leP b1r b3r); case: (leP b2r b3r); rewrite ?eqxx ?orbT //= => b23r b13r b12r b23l b13l b12l. - by case: leP b13r (le_trans b12r b23r). - by case: leP b13l (le_trans b12l b23l). - by case: leP b13l (le_trans b12l b23l). - by case: leP b13r (le_trans b12r b23r). - by case: leP b13r (le_trans b12r b23r). - by case: leP b13l (lt_trans b23l b12l). - by case: leP b13r (lt_trans b23r b12r). - by case: leP b13l (lt_trans b23l b12l). - by case: leP b13r (lt_trans b23r b12r). - by case: leP b13r (lt_trans b23r b12r). Qed. Lemma itv_total_join3E i1 i2 i3 : i1 `|` i2 `|` i3 \in [:: i1 `|` i2; i1 `|` i3; i2 `|` i3]. Proof. case: i1 i2 i3 => [b1l b1r] [b2l b2r] [b3l b3r]; rewrite !inE /eq_op /=. case: (leP b1l b2l); case: (leP b1l b3l); case: (leP b2l b3l); case: (leP b1r b2r); case: (leP b1r b3r); case: (leP b2r b3r); rewrite ?eqxx ?orbT //= => b23r b13r b12r b23l b13l b12l. - by case: leP b13r (le_trans b12r b23r). - by case: leP b13r (le_trans b12r b23r). - by case: leP b13l (le_trans b12l b23l). - by case: leP b13l (le_trans b12l b23l). - by case: leP b13l (le_trans b12l b23l). - by case: leP b13r (lt_trans b23r b12r). - by case: leP b13l (lt_trans b23l b12l). - by case: leP b13l (lt_trans b23l b12l). - by case: leP b13l (lt_trans b23l b12l). - by case: leP b13r (lt_trans b23r b12r). Qed. Lemma predC_itvl a : [predC Interval -oo a] =i Interval a +oo. Proof. case: a => [b x|[]//] y. by rewrite !inE !subitvE/= bnd_simp andbT !lteBSide/= lteifNE negbK. Qed. Lemma predC_itvr a : [predC Interval a +oo] =i Interval -oo a. Proof. by move=> y; rewrite inE/= -predC_itvl negbK. Qed. Lemma predC_itv i : [predC i] =i [predU Interval -oo i.1 & Interval i.2 +oo]. Proof. case: i => [a a']; move=> x; rewrite inE/= itv_splitI negb_and. by symmetry; rewrite inE/= -predC_itvl -predC_itvr. Qed. End IntervalTotal. Local Open Scope ring_scope. Import GRing.Theory Num.Theory. Section IntervalNumDomain. Variable R : numDomainType. Implicit Types x : R. Lemma real_BSide_min b x y : x \in Num.real -> y \in Num.real -> BSide b (Order.min x y) = Order.min (BSide b x) (BSide b y). Proof. by move=> xr yr; apply/comparable_BSide_min/real_comparable. Qed. Lemma real_BSide_max b x y : x \in Num.real -> y \in Num.real -> BSide b (Order.max x y) = Order.max (BSide b x) (BSide b y). Proof. by move=> xr yr; apply/comparable_BSide_max/real_comparable. Qed. Lemma mem0_itvcc_xNx x : (0 \in `[- x, x]) = (0 <= x). Proof. by rewrite itv_boundlr [in LHS]/<=%O /= oppr_le0 andbb. Qed. Lemma mem0_itvoo_xNx x : 0 \in `]- x, x[ = (0 < x). Proof. by rewrite itv_boundlr [in LHS]/<=%O /= oppr_lt0 andbb. Qed. Lemma oppr_itv ba bb (xa xb x : R) : (- x \in Interval (BSide ba xa) (BSide bb xb)) = (x \in Interval (BSide (~~ bb) (- xb)) (BSide (~~ ba) (- xa))). Proof. by rewrite !itv_boundlr /<=%O /= !implybF negbK andbC lteifNl lteifNr. Qed. Lemma oppr_itvoo (a b x : R) : (- x \in `]a, b[) = (x \in `]- b, - a[). Proof. exact: oppr_itv. Qed. Lemma oppr_itvco (a b x : R) : (- x \in `[a, b[) = (x \in `]- b, - a]). Proof. exact: oppr_itv. Qed. Lemma oppr_itvoc (a b x : R) : (- x \in `]a, b]) = (x \in `[- b, - a[). Proof. exact: oppr_itv. Qed. Lemma oppr_itvcc (a b x : R) : (- x \in `[a, b]) = (x \in `[- b, - a]). Proof. exact: oppr_itv. Qed. Definition miditv (R : numDomainType) (i : interval R) : R := match i with | Interval (BSide _ a) (BSide _ b) => (a + b) / 2%:R | Interval -oo%O (BSide _ b) => b - 1 | Interval (BSide _ a) +oo%O => a + 1 | Interval -oo%O +oo%O => 0 | _ => 0 end. End IntervalNumDomain. Section IntervalField. Variable R : numFieldType. Implicit Types (x y z : R) (i : interval R). Local Notation mid x y := ((x + y) / 2). Lemma mid_in_itv : forall ba bb (xa xb : R), xa < xb ?<= if ba && ~~ bb -> mid xa xb \in Interval (BSide ba xa) (BSide bb xb). Proof. by move=> [] [] xa xb /= ?; apply/itv_dec; rewrite /= ?midf_lte // ?ltW. Qed. Lemma mid_in_itvoo : forall (xa xb : R), xa < xb -> mid xa xb \in `]xa, xb[. Proof. by move=> xa xb ?; apply: mid_in_itv. Qed. Lemma mid_in_itvcc : forall (xa xb : R), xa <= xb -> mid xa xb \in `[xa, xb]. Proof. by move=> xa xb ?; apply: mid_in_itv. Qed. Lemma mem_miditv i : (i.1 < i.2)%O -> miditv i \in i. Proof. move: i => [[ba a|[]] [bb b|[]]] //= ab; first exact: mid_in_itv. by rewrite !in_itv -lteifBlDl subrr lteif01. by rewrite !in_itv lteifBlDr -lteifBlDl subrr lteif01. Qed. Lemma miditv_le_left i b : (i.1 < i.2)%O -> (BSide b (miditv i) <= i.2)%O. Proof. case: i => [x y] lti; have := mem_miditv lti; rewrite inE => /andP[_ ]. by apply: le_trans; rewrite !bnd_simp. Qed. Lemma miditv_ge_right i b : (i.1 < i.2)%O -> (i.1 <= BSide b (miditv i))%O. Proof. case: i => [x y] lti; have := mem_miditv lti; rewrite inE => /andP[+ _]. by move=> /le_trans; apply; rewrite !bnd_simp. Qed. Lemma in_segmentDgt0Pr x y z : reflect (forall e, e > 0 -> y \in `[x - e, z + e]) (y \in `[x, z]). Proof. apply/(iffP idP)=> [xyz e /[dup] e_gt0 /ltW e_ge0 | xyz_e]. by rewrite in_itv /= lerBDr !ler_wpDr// (itvP xyz). by rewrite in_itv /= ; apply/andP; split; apply/ler_addgt0Pr => ? /xyz_e; rewrite in_itv /= lerBDr => /andP []. Qed. Lemma in_segmentDgt0Pl x y z : reflect (forall e, e > 0 -> y \in `[- e + x, e + z]) (y \in `[x, z]). Proof. apply/(equivP (in_segmentDgt0Pr x y z)). by split=> zxy e /zxy; rewrite [z + _]addrC [_ + x]addrC. Qed. End IntervalField.
Basic.lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Logic.Function.Basic import Mathlib.Logic.Unique import Mathlib.Util.CompileInductive import Mathlib.Tactic.Simps.NotationClass /-! # Typeclass for a type `F` with an injective map to `A → B` This typeclass is primarily for use by homomorphisms like `MonoidHom` and `LinearMap`. There is the "D"ependent version `DFunLike` and the non-dependent version `FunLike`. ## Basic usage of `DFunLike` and `FunLike` A typical type of morphisms should be declared as: ``` structure MyHom (A B : Type*) [MyClass A] [MyClass B] where (toFun : A → B) (map_op' : ∀ (x y : A), toFun (MyClass.op x y) = MyClass.op (toFun x) (toFun y)) namespace MyHom variable (A B : Type*) [MyClass A] [MyClass B] instance : FunLike (MyHom A B) A B where coe := MyHom.toFun coe_injective' := fun f g h => by cases f; cases g; congr @[ext] theorem ext {f g : MyHom A B} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h /-- Copy of a `MyHom` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : MyHom A B) (f' : A → B) (h : f' = ⇑f) : MyHom A B where toFun := f' map_op' := h.symm ▸ f.map_op' end MyHom ``` This file will then provide a `CoeFun` instance and various extensionality and simp lemmas. ## Morphism classes extending `DFunLike` and `FunLike` The `FunLike` design provides further benefits if you put in a bit more work. The first step is to extend `FunLike` to create a class of those types satisfying the axioms of your new type of morphisms. Continuing the example above: ``` /-- `MyHomClass F A B` states that `F` is a type of `MyClass.op`-preserving morphisms. You should extend this class when you extend `MyHom`. -/ class MyHomClass (F : Type*) (A B : outParam Type*) [MyClass A] [MyClass B] [FunLike F A B] : Prop := (map_op : ∀ (f : F) (x y : A), f (MyClass.op x y) = MyClass.op (f x) (f y)) @[simp] lemma map_op {F A B : Type*} [MyClass A] [MyClass B] [FunLike F A B] [MyHomClass F A B] (f : F) (x y : A) : f (MyClass.op x y) = MyClass.op (f x) (f y) := MyHomClass.map_op _ _ _ -- You can add the below instance next to `MyHomClass.instFunLike`: instance : MyHomClass (MyHom A B) A B where map_op := MyHom.map_op' -- [Insert `ext` and `copy` here] ``` Note that `A B` are marked as `outParam` even though they are not purely required to be so due to the `FunLike` parameter already filling them in. This is required to see through type synonyms, which is important in the category theory library. Also, it appears having them as `outParam` is slightly faster. The second step is to add instances of your new `MyHomClass` for all types extending `MyHom`. Typically, you can just declare a new class analogous to `MyHomClass`: ``` structure CoolerHom (A B : Type*) [CoolClass A] [CoolClass B] extends MyHom A B where (map_cool' : toFun CoolClass.cool = CoolClass.cool) class CoolerHomClass (F : Type*) (A B : outParam Type*) [CoolClass A] [CoolClass B] [FunLike F A B] extends MyHomClass F A B := (map_cool : ∀ (f : F), f CoolClass.cool = CoolClass.cool) @[simp] lemma map_cool {F A B : Type*} [CoolClass A] [CoolClass B] [FunLike F A B] [CoolerHomClass F A B] (f : F) : f CoolClass.cool = CoolClass.cool := CoolerHomClass.map_cool _ variable {A B : Type*} [CoolClass A] [CoolClass B] instance : FunLike (CoolerHom A B) A B where coe f := f.toFun coe_injective' := fun f g h ↦ by cases f; cases g; congr; apply DFunLike.coe_injective; congr instance : CoolerHomClass (CoolerHom A B) A B where map_op f := f.map_op' map_cool f := f.map_cool' -- [Insert `ext` and `copy` here] ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : MyHom A B) : sorry := sorry lemma do_something {F : Type*} [FunLike F A B] [MyHomClass F A B] (f : F) : sorry := sorry ``` This means anything set up for `MyHom`s will automatically work for `CoolerHomClass`es, and defining `CoolerHomClass` only takes a constant amount of effort, instead of linearly increasing the work per `MyHom`-related declaration. ## Design rationale The current form of FunLike was set up in pull request https://github.com/leanprover-community/mathlib4/pull/8386: https://github.com/leanprover-community/mathlib4/pull/8386 We made `FunLike` *unbundled*: child classes don't extend `FunLike`, they take a `[FunLike F A B]` parameter instead. This suits the instance synthesis algorithm better: it's easy to verify a type does **not** have a `FunLike` instance by checking the discrimination tree once instead of searching the entire `extends` hierarchy. -/ /-- The class `DFunLike F α β` expresses that terms of type `F` have an injective coercion to (dependent) functions from `α` to `β`. For non-dependent functions you can also use the abbreviation `FunLike`. This typeclass is used in the definition of the homomorphism typeclasses, such as `ZeroHomClass`, `MulHomClass`, `MonoidHomClass`, .... -/ @[notation_class* toFun Simps.findCoercionArgs] class DFunLike (F : Sort*) (α : outParam (Sort*)) (β : outParam <| α → Sort*) where /-- The coercion from `F` to a function. -/ coe : F → ∀ a : α, β a /-- The coercion to functions must be injective. -/ coe_injective' : Function.Injective coe /-- The class `FunLike F α β` (`Fun`ction-`Like`) expresses that terms of type `F` have an injective coercion to functions from `α` to `β`. `FunLike` is the non-dependent version of `DFunLike`. This typeclass is used in the definition of the homomorphism typeclasses, such as `ZeroHomClass`, `MulHomClass`, `MonoidHomClass`, .... -/ abbrev FunLike F α β := DFunLike F α fun _ => β section Dependent /-! ### `DFunLike F α β` where `β` depends on `a : α` -/ variable (F α : Sort*) (β : α → Sort*) namespace DFunLike variable {F α β} [i : DFunLike F α β] instance (priority := 100) hasCoeToFun : CoeFun F (fun _ ↦ ∀ a : α, β a) where coe := @DFunLike.coe _ _ β _ -- need to make explicit to beta reduce for non-dependent functions run_cmd Lean.Elab.Command.liftTermElabM do Lean.Meta.registerCoercion ``DFunLike.coe (some { numArgs := 5, coercee := 4, type := .coeFun }) theorem coe_eq_coe_fn : (DFunLike.coe (F := F)) = (fun f => ↑f) := rfl theorem coe_injective : Function.Injective (fun f : F ↦ (f : ∀ a : α, β a)) := DFunLike.coe_injective' @[simp] theorem coe_fn_eq {f g : F} : (f : ∀ a : α, β a) = (g : ∀ a : α, β a) ↔ f = g := ⟨fun h ↦ DFunLike.coe_injective' h, fun h ↦ by cases h; rfl⟩ theorem ext' {f g : F} (h : (f : ∀ a : α, β a) = (g : ∀ a : α, β a)) : f = g := DFunLike.coe_injective' h theorem ext'_iff {f g : F} : f = g ↔ (f : ∀ a : α, β a) = (g : ∀ a : α, β a) := coe_fn_eq.symm theorem ext (f g : F) (h : ∀ x : α, f x = g x) : f = g := DFunLike.coe_injective' (funext h) theorem ext_iff {f g : F} : f = g ↔ ∀ x, f x = g x := coe_fn_eq.symm.trans funext_iff protected theorem congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x := congr_fun (congr_arg _ h₁) x theorem ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a := ext_iff.not.trans not_forall theorem exists_ne {f g : F} (h : f ≠ g) : ∃ x, f x ≠ g x := ne_iff.mp h /-- This is not an instance to avoid slowing down every single `Subsingleton` typeclass search. -/ lemma subsingleton_cod [∀ a, Subsingleton (β a)] : Subsingleton F := coe_injective.subsingleton include β in /-- This is not an instance to avoid slowing down every single `Subsingleton` typeclass search. -/ lemma subsingleton_dom [IsEmpty α] : Subsingleton F := coe_injective.subsingleton end DFunLike end Dependent section NonDependent /-! ### `FunLike F α β` where `β` does not depend on `a : α` -/ variable {F α β : Sort*} [i : FunLike F α β] namespace DFunLike protected theorem congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y := congr (congr_arg _ h₁) h₂ protected theorem congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y := congr_arg _ h₂ theorem dite_apply {P : Prop} [Decidable P] (f : P → F) (g : ¬P → F) (x : α) : (if h : P then f h else g h) x = if h : P then f h x else g h x := by split_ifs <;> rfl theorem ite_apply {P : Prop} [Decidable P] (f g : F) (x : α) : (if P then f else g) x = if P then f x else g x := dite_apply _ _ _ end DFunLike end NonDependent
DualNumber.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Algebra.DualNumber import Mathlib.Analysis.Normed.Algebra.TrivSqZeroExt /-! # Results on `DualNumber R` related to the norm These are just restatements of similar statements about `TrivSqZeroExt R M`. ## Main results * `exp_eps` -/ open NormedSpace -- For `NormedSpace.exp`. namespace DualNumber open TrivSqZeroExt variable (𝕜 : Type*) {R : Type*} variable [Field 𝕜] [CharZero 𝕜] [CommRing R] [Algebra 𝕜 R] variable [UniformSpace R] [IsTopologicalRing R] [T2Space R] @[simp] theorem exp_eps : exp 𝕜 (eps : DualNumber R) = 1 + eps := exp_inr _ _ @[simp] theorem exp_smul_eps (r : R) : exp 𝕜 (r • eps : DualNumber R) = 1 + r • eps := by rw [eps, ← inr_smul, exp_inr] end DualNumber
Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mitchell Lee -/ import Mathlib.Algebra.BigOperators.Group.Finset.Indicator import Mathlib.Data.Fintype.BigOperators import Mathlib.Topology.Algebra.InfiniteSum.Defs import Mathlib.Topology.Algebra.Monoid.Defs /-! # Lemmas on infinite sums and products in topological monoids This file contains many simple lemmas on `tsum`, `HasSum` etc, which are placed here in order to keep the basic file of definitions as short as possible. Results requiring a group (rather than monoid) structure on the target should go in `Group.lean`. -/ noncomputable section open Filter Finset Function Topology variable {α β γ : Type*} section HasProd variable [CommMonoid α] [TopologicalSpace α] variable {f g : β → α} {a b : α} /-- Constant one function has product `1` -/ @[to_additive /-- Constant zero function has sum `0` -/] theorem hasProd_one : HasProd (fun _ ↦ 1 : β → α) 1 := by simp [HasProd, tendsto_const_nhds] @[to_additive] theorem hasProd_empty [IsEmpty β] : HasProd f 1 := by convert @hasProd_one α β _ _ @[to_additive] theorem multipliable_one : Multipliable (fun _ ↦ 1 : β → α) := hasProd_one.multipliable @[to_additive] theorem multipliable_empty [IsEmpty β] : Multipliable f := hasProd_empty.multipliable /-- See `multipliable_congr_cofinite` for a version allowing the functions to disagree on a finite set. -/ @[to_additive /-- See `summable_congr_cofinite` for a version allowing the functions to disagree on a finite set. -/] theorem multipliable_congr (hfg : ∀ b, f b = g b) : Multipliable f ↔ Multipliable g := iff_of_eq (congr_arg Multipliable <| funext hfg) /-- See `Multipliable.congr_cofinite` for a version allowing the functions to disagree on a finite set. -/ @[to_additive /-- See `Summable.congr_cofinite` for a version allowing the functions to disagree on a finite set. -/] theorem Multipliable.congr (hf : Multipliable f) (hfg : ∀ b, f b = g b) : Multipliable g := (multipliable_congr hfg).mp hf @[to_additive] lemma HasProd.congr_fun (hf : HasProd f a) (h : ∀ x : β, g x = f x) : HasProd g a := (funext h : g = f) ▸ hf @[to_additive] theorem HasProd.hasProd_of_prod_eq {g : γ → α} (h_eq : ∀ u : Finset γ, ∃ v : Finset β, ∀ v', v ⊆ v' → ∃ u', u ⊆ u' ∧ ∏ x ∈ u', g x = ∏ b ∈ v', f b) (hf : HasProd g a) : HasProd f a := le_trans (map_atTop_finset_prod_le_of_prod_eq h_eq) hf @[to_additive] theorem hasProd_iff_hasProd {g : γ → α} (h₁ : ∀ u : Finset γ, ∃ v : Finset β, ∀ v', v ⊆ v' → ∃ u', u ⊆ u' ∧ ∏ x ∈ u', g x = ∏ b ∈ v', f b) (h₂ : ∀ v : Finset β, ∃ u : Finset γ, ∀ u', u ⊆ u' → ∃ v', v ⊆ v' ∧ ∏ b ∈ v', f b = ∏ x ∈ u', g x) : HasProd f a ↔ HasProd g a := ⟨HasProd.hasProd_of_prod_eq h₂, HasProd.hasProd_of_prod_eq h₁⟩ @[to_additive] theorem Function.Injective.multipliable_iff {g : γ → β} (hg : Injective g) (hf : ∀ x ∉ Set.range g, f x = 1) : Multipliable (f ∘ g) ↔ Multipliable f := exists_congr fun _ ↦ hg.hasProd_iff hf @[to_additive (attr := simp)] theorem hasProd_extend_one {g : β → γ} (hg : Injective g) : HasProd (extend g f 1) a ↔ HasProd f a := by rw [← hg.hasProd_iff, extend_comp hg] exact extend_apply' _ _ @[to_additive (attr := simp)] theorem multipliable_extend_one {g : β → γ} (hg : Injective g) : Multipliable (extend g f 1) ↔ Multipliable f := exists_congr fun _ ↦ hasProd_extend_one hg @[to_additive] theorem hasProd_subtype_iff_mulIndicator {s : Set β} : HasProd (f ∘ (↑) : s → α) a ↔ HasProd (s.mulIndicator f) a := by rw [← Set.mulIndicator_range_comp, Subtype.range_coe, hasProd_subtype_iff_of_mulSupport_subset Set.mulSupport_mulIndicator_subset] @[to_additive] theorem multipliable_subtype_iff_mulIndicator {s : Set β} : Multipliable (f ∘ (↑) : s → α) ↔ Multipliable (s.mulIndicator f) := exists_congr fun _ ↦ hasProd_subtype_iff_mulIndicator @[to_additive (attr := simp)] theorem hasProd_subtype_mulSupport : HasProd (f ∘ (↑) : mulSupport f → α) a ↔ HasProd f a := hasProd_subtype_iff_of_mulSupport_subset <| Set.Subset.refl _ @[to_additive] protected theorem Finset.multipliable (s : Finset β) (f : β → α) : Multipliable (f ∘ (↑) : (↑s : Set β) → α) := (s.hasProd f).multipliable @[to_additive] protected theorem Set.Finite.multipliable {s : Set β} (hs : s.Finite) (f : β → α) : Multipliable (f ∘ (↑) : s → α) := by have := hs.toFinset.multipliable f rwa [hs.coe_toFinset] at this @[to_additive] theorem multipliable_of_finite_mulSupport (h : (mulSupport f).Finite) : Multipliable f := by apply multipliable_of_ne_finset_one (s := h.toFinset); simp @[to_additive] lemma Multipliable.of_finite [Finite β] {f : β → α} : Multipliable f := multipliable_of_finite_mulSupport <| Set.finite_univ.subset (Set.subset_univ _) @[to_additive] theorem hasProd_single {f : β → α} (b : β) (hf : ∀ (b') (_ : b' ≠ b), f b' = 1) : HasProd f (f b) := suffices HasProd f (∏ b' ∈ {b}, f b') by simpa using this hasProd_prod_of_ne_finset_one <| by simpa [hf] @[to_additive (attr := simp)] lemma hasProd_unique [Unique β] (f : β → α) : HasProd f (f default) := hasProd_single default (fun _ hb ↦ False.elim <| hb <| Unique.uniq ..) @[to_additive (attr := simp)] lemma hasProd_singleton (m : β) (f : β → α) : HasProd (({m} : Set β).restrict f) (f m) := hasProd_unique (Set.restrict {m} f) @[to_additive] theorem hasProd_ite_eq (b : β) [DecidablePred (· = b)] (a : α) : HasProd (fun b' ↦ if b' = b then a else 1) a := by convert @hasProd_single _ _ _ _ (fun b' ↦ if b' = b then a else 1) b (fun b' hb' ↦ if_neg hb') exact (if_pos rfl).symm @[to_additive] theorem Equiv.hasProd_iff (e : γ ≃ β) : HasProd (f ∘ e) a ↔ HasProd f a := e.injective.hasProd_iff <| by simp @[to_additive] theorem Function.Injective.hasProd_range_iff {g : γ → β} (hg : Injective g) : HasProd (fun x : Set.range g ↦ f x) a ↔ HasProd (f ∘ g) a := (Equiv.ofInjective g hg).hasProd_iff.symm @[to_additive] theorem Equiv.multipliable_iff (e : γ ≃ β) : Multipliable (f ∘ e) ↔ Multipliable f := exists_congr fun _ ↦ e.hasProd_iff @[to_additive] theorem Equiv.hasProd_iff_of_mulSupport {g : γ → α} (e : mulSupport f ≃ mulSupport g) (he : ∀ x : mulSupport f, g (e x) = f x) : HasProd f a ↔ HasProd g a := by have : (g ∘ (↑)) ∘ e = f ∘ (↑) := funext he rw [← hasProd_subtype_mulSupport, ← this, e.hasProd_iff, hasProd_subtype_mulSupport] @[to_additive] theorem hasProd_iff_hasProd_of_ne_one_bij {g : γ → α} (i : mulSupport g → β) (hi : Injective i) (hf : mulSupport f ⊆ Set.range i) (hfg : ∀ x, f (i x) = g x) : HasProd f a ↔ HasProd g a := Iff.symm <| Equiv.hasProd_iff_of_mulSupport (Equiv.ofBijective (fun x ↦ ⟨i x, fun hx ↦ x.coe_prop <| hfg x ▸ hx⟩) ⟨fun _ _ h ↦ hi <| Subtype.ext_iff.1 h, fun y ↦ (hf y.coe_prop).imp fun _ hx ↦ Subtype.ext hx⟩) hfg @[to_additive] theorem Equiv.multipliable_iff_of_mulSupport {g : γ → α} (e : mulSupport f ≃ mulSupport g) (he : ∀ x : mulSupport f, g (e x) = f x) : Multipliable f ↔ Multipliable g := exists_congr fun _ ↦ e.hasProd_iff_of_mulSupport he @[to_additive] protected theorem HasProd.map [CommMonoid γ] [TopologicalSpace γ] (hf : HasProd f a) {G} [FunLike G α γ] [MonoidHomClass G α γ] (g : G) (hg : Continuous g) : HasProd (g ∘ f) (g a) := by have : (g ∘ fun s : Finset β ↦ ∏ b ∈ s, f b) = fun s : Finset β ↦ ∏ b ∈ s, (g ∘ f) b := funext <| map_prod g _ unfold HasProd rw [← this] exact (hg.tendsto a).comp hf @[to_additive] protected theorem Topology.IsInducing.hasProd_iff [CommMonoid γ] [TopologicalSpace γ] {G} [FunLike G α γ] [MonoidHomClass G α γ] {g : G} (hg : IsInducing g) (f : β → α) (a : α) : HasProd (g ∘ f) (g a) ↔ HasProd f a := by simp_rw [HasProd, comp_apply, ← map_prod] exact hg.tendsto_nhds_iff.symm @[to_additive] protected theorem Multipliable.map [CommMonoid γ] [TopologicalSpace γ] (hf : Multipliable f) {G} [FunLike G α γ] [MonoidHomClass G α γ] (g : G) (hg : Continuous g) : Multipliable (g ∘ f) := (hf.hasProd.map g hg).multipliable @[to_additive] protected theorem Multipliable.map_iff_of_leftInverse [CommMonoid γ] [TopologicalSpace γ] {G G'} [FunLike G α γ] [MonoidHomClass G α γ] [FunLike G' γ α] [MonoidHomClass G' γ α] (g : G) (g' : G') (hg : Continuous g) (hg' : Continuous g') (hinv : Function.LeftInverse g' g) : Multipliable (g ∘ f) ↔ Multipliable f := ⟨fun h ↦ by have := h.map _ hg' rwa [← Function.comp_assoc, hinv.id] at this, fun h ↦ h.map _ hg⟩ @[to_additive] theorem Multipliable.map_tprod [CommMonoid γ] [TopologicalSpace γ] [T2Space γ] (hf : Multipliable f) {G} [FunLike G α γ] [MonoidHomClass G α γ] (g : G) (hg : Continuous g) : g (∏' i, f i) = ∏' i, g (f i) := (HasProd.tprod_eq (HasProd.map hf.hasProd g hg)).symm @[to_additive] lemma Topology.IsInducing.multipliable_iff_tprod_comp_mem_range [CommMonoid γ] [TopologicalSpace γ] [T2Space γ] {G} [FunLike G α γ] [MonoidHomClass G α γ] {g : G} (hg : IsInducing g) (f : β → α) : Multipliable f ↔ Multipliable (g ∘ f) ∧ ∏' i, g (f i) ∈ Set.range g := by constructor · intro hf constructor · exact hf.map g hg.continuous · use ∏' i, f i exact hf.map_tprod g hg.continuous · rintro ⟨hgf, a, ha⟩ use a have := hgf.hasProd simp_rw [comp_apply, ← ha] at this exact (hg.hasProd_iff f a).mp this /-- "A special case of `Multipliable.map_iff_of_leftInverse` for convenience" -/ @[to_additive /-- A special case of `Summable.map_iff_of_leftInverse` for convenience -/] protected theorem Multipliable.map_iff_of_equiv [CommMonoid γ] [TopologicalSpace γ] {G} [EquivLike G α γ] [MulEquivClass G α γ] (g : G) (hg : Continuous g) (hg' : Continuous (EquivLike.inv g : γ → α)) : Multipliable (g ∘ f) ↔ Multipliable f := Multipliable.map_iff_of_leftInverse g (g : α ≃* γ).symm hg hg' (EquivLike.left_inv g) @[to_additive] theorem Function.Surjective.multipliable_iff_of_hasProd_iff {α' : Type*} [CommMonoid α'] [TopologicalSpace α'] {e : α' → α} (hes : Function.Surjective e) {f : β → α} {g : γ → α'} (he : ∀ {a}, HasProd f (e a) ↔ HasProd g a) : Multipliable f ↔ Multipliable g := hes.exists.trans <| exists_congr <| @he variable [ContinuousMul α] @[to_additive] theorem HasProd.mul (hf : HasProd f a) (hg : HasProd g b) : HasProd (fun b ↦ f b * g b) (a * b) := by dsimp only [HasProd] at hf hg ⊢ simp_rw [prod_mul_distrib] exact hf.mul hg @[to_additive] theorem Multipliable.mul (hf : Multipliable f) (hg : Multipliable g) : Multipliable fun b ↦ f b * g b := (hf.hasProd.mul hg.hasProd).multipliable @[to_additive] theorem hasProd_prod {f : γ → β → α} {a : γ → α} {s : Finset γ} : (∀ i ∈ s, HasProd (f i) (a i)) → HasProd (fun b ↦ ∏ i ∈ s, f i b) (∏ i ∈ s, a i) := by classical exact Finset.induction_on s (by simp only [hasProd_one, prod_empty, forall_true_iff]) <| by simp +contextual only [mem_insert, forall_eq_or_imp, not_false_iff, prod_insert, and_imp] exact fun x s _ IH hx h ↦ hx.mul (IH h) @[to_additive] theorem multipliable_prod {f : γ → β → α} {s : Finset γ} (hf : ∀ i ∈ s, Multipliable (f i)) : Multipliable fun b ↦ ∏ i ∈ s, f i b := (hasProd_prod fun i hi ↦ (hf i hi).hasProd).multipliable @[to_additive] theorem HasProd.mul_disjoint {s t : Set β} (hs : Disjoint s t) (ha : HasProd (f ∘ (↑) : s → α) a) (hb : HasProd (f ∘ (↑) : t → α) b) : HasProd (f ∘ (↑) : (s ∪ t : Set β) → α) (a * b) := by rw [hasProd_subtype_iff_mulIndicator] at * rw [Set.mulIndicator_union_of_disjoint hs] exact ha.mul hb @[to_additive] theorem hasProd_prod_disjoint {ι} (s : Finset ι) {t : ι → Set β} {a : ι → α} (hs : (s : Set ι).Pairwise (Disjoint on t)) (hf : ∀ i ∈ s, HasProd (f ∘ (↑) : t i → α) (a i)) : HasProd (f ∘ (↑) : (⋃ i ∈ s, t i) → α) (∏ i ∈ s, a i) := by simp_rw [hasProd_subtype_iff_mulIndicator] at * rw [Finset.mulIndicator_biUnion _ _ hs] exact hasProd_prod hf @[to_additive] theorem HasProd.mul_isCompl {s t : Set β} (hs : IsCompl s t) (ha : HasProd (f ∘ (↑) : s → α) a) (hb : HasProd (f ∘ (↑) : t → α) b) : HasProd f (a * b) := by simpa [← hs.compl_eq] using (hasProd_subtype_iff_mulIndicator.1 ha).mul (hasProd_subtype_iff_mulIndicator.1 hb) @[to_additive] theorem HasProd.mul_compl {s : Set β} (ha : HasProd (f ∘ (↑) : s → α) a) (hb : HasProd (f ∘ (↑) : (sᶜ : Set β) → α) b) : HasProd f (a * b) := ha.mul_isCompl isCompl_compl hb @[to_additive] theorem Multipliable.mul_compl {s : Set β} (hs : Multipliable (f ∘ (↑) : s → α)) (hsc : Multipliable (f ∘ (↑) : (sᶜ : Set β) → α)) : Multipliable f := (hs.hasProd.mul_compl hsc.hasProd).multipliable @[to_additive] theorem HasProd.compl_mul {s : Set β} (ha : HasProd (f ∘ (↑) : (sᶜ : Set β) → α) a) (hb : HasProd (f ∘ (↑) : s → α) b) : HasProd f (a * b) := ha.mul_isCompl isCompl_compl.symm hb @[to_additive] theorem Multipliable.compl_add {s : Set β} (hs : Multipliable (f ∘ (↑) : (sᶜ : Set β) → α)) (hsc : Multipliable (f ∘ (↑) : s → α)) : Multipliable f := (hs.hasProd.compl_mul hsc.hasProd).multipliable /-- Version of `HasProd.update` for `CommMonoid` rather than `CommGroup`. Rather than showing that `f.update` has a specific product in terms of `HasProd`, it gives a relationship between the products of `f` and `f.update` given that both exist. -/ @[to_additive /-- Version of `HasSum.update` for `AddCommMonoid` rather than `AddCommGroup`. Rather than showing that `f.update` has a specific sum in terms of `HasSum`, it gives a relationship between the sums of `f` and `f.update` given that both exist. -/] theorem HasProd.update' {α β : Type*} [TopologicalSpace α] [CommMonoid α] [T2Space α] [ContinuousMul α] [DecidableEq β] {f : β → α} {a a' : α} (hf : HasProd f a) (b : β) (x : α) (hf' : HasProd (update f b x) a') : a * x = a' * f b := by have : ∀ b', f b' * ite (b' = b) x 1 = update f b x b' * ite (b' = b) (f b) 1 := by intro b' split_ifs with hb' · simpa only [Function.update_apply, hb', eq_self_iff_true] using mul_comm (f b) x · simp only [Function.update_apply, hb', if_false] have h := hf.mul (hasProd_ite_eq b x) simp_rw [this] at h exact HasProd.unique h (hf'.mul (hasProd_ite_eq b (f b))) /-- Version of `hasProd_ite_div_hasProd` for `CommMonoid` rather than `CommGroup`. Rather than showing that the `ite` expression has a specific product in terms of `HasProd`, it gives a relationship between the products of `f` and `ite (n = b) 0 (f n)` given that both exist. -/ @[to_additive /-- Version of `hasSum_ite_sub_hasSum` for `AddCommMonoid` rather than `AddCommGroup`. Rather than showing that the `ite` expression has a specific sum in terms of `HasSum`, it gives a relationship between the sums of `f` and `ite (n = b) 0 (f n)` given that both exist. -/] theorem eq_mul_of_hasProd_ite {α β : Type*} [TopologicalSpace α] [CommMonoid α] [T2Space α] [ContinuousMul α] [DecidableEq β] {f : β → α} {a : α} (hf : HasProd f a) (b : β) (a' : α) (hf' : HasProd (fun n ↦ ite (n = b) 1 (f n)) a') : a = a' * f b := by refine (mul_one a).symm.trans (hf.update' b 1 ?_) convert hf' apply update_apply end HasProd section tprod variable [CommMonoid α] [TopologicalSpace α] {f g : β → α} @[to_additive] theorem tprod_congr_set_coe (f : β → α) {s t : Set β} (h : s = t) : ∏' x : s, f x = ∏' x : t, f x := by rw [h] @[to_additive] theorem tprod_congr_subtype (f : β → α) {P Q : β → Prop} (h : ∀ x, P x ↔ Q x) : ∏' x : {x // P x}, f x = ∏' x : {x // Q x}, f x := tprod_congr_set_coe f <| Set.ext h @[to_additive] theorem tprod_eq_finprod (hf : (mulSupport f).Finite) : ∏' b, f b = ∏ᶠ b, f b := by simp [tprod_def, multipliable_of_finite_mulSupport hf, hf] @[to_additive] theorem tprod_eq_prod' {s : Finset β} (hf : mulSupport f ⊆ s) : ∏' b, f b = ∏ b ∈ s, f b := by rw [tprod_eq_finprod (s.finite_toSet.subset hf), finprod_eq_prod_of_mulSupport_subset _ hf] @[to_additive] theorem tprod_eq_prod {s : Finset β} (hf : ∀ b ∉ s, f b = 1) : ∏' b, f b = ∏ b ∈ s, f b := tprod_eq_prod' <| mulSupport_subset_iff'.2 hf @[to_additive (attr := simp)] theorem tprod_one : ∏' _ : β, (1 : α) = 1 := by rw [tprod_eq_finprod] <;> simp @[to_additive (attr := simp)] theorem tprod_empty [IsEmpty β] : ∏' b, f b = 1 := by rw [tprod_eq_prod (s := (∅ : Finset β))] <;> simp @[to_additive] theorem tprod_congr {f g : β → α} (hfg : ∀ b, f b = g b) : ∏' b, f b = ∏' b, g b := congr_arg tprod (funext hfg) @[to_additive] theorem tprod_fintype [Fintype β] (f : β → α) : ∏' b, f b = ∏ b, f b := by apply tprod_eq_prod; simp @[to_additive] theorem prod_eq_tprod_mulIndicator (f : β → α) (s : Finset β) : ∏ x ∈ s, f x = ∏' x, Set.mulIndicator (↑s) f x := by rw [tprod_eq_prod' (Set.mulSupport_mulIndicator_subset), Finset.prod_mulIndicator_subset _ Finset.Subset.rfl] @[to_additive] theorem tprod_bool (f : Bool → α) : ∏' i : Bool, f i = f false * f true := by rw [tprod_fintype, Fintype.prod_bool, mul_comm] @[to_additive] theorem tprod_eq_mulSingle {f : β → α} (b : β) (hf : ∀ b' ≠ b, f b' = 1) : ∏' b, f b = f b := by rw [tprod_eq_prod (s := {b}), prod_singleton] exact fun b' hb' ↦ hf b' (by simpa using hb') @[to_additive] theorem tprod_tprod_eq_mulSingle (f : β → γ → α) (b : β) (c : γ) (hfb : ∀ b' ≠ b, f b' c = 1) (hfc : ∀ b', ∀ c' ≠ c, f b' c' = 1) : ∏' (b') (c'), f b' c' = f b c := calc ∏' (b') (c'), f b' c' = ∏' b', f b' c := tprod_congr fun b' ↦ tprod_eq_mulSingle _ (hfc b') _ = f b c := tprod_eq_mulSingle _ hfb @[to_additive (attr := simp)] theorem tprod_ite_eq (b : β) [DecidablePred (· = b)] (a : α) : ∏' b', (if b' = b then a else 1) = a := by rw [tprod_eq_mulSingle b] · simp · intro b' hb'; simp [hb'] @[to_additive (attr := simp)] theorem Finset.tprod_subtype (s : Finset β) (f : β → α) : ∏' x : { x // x ∈ s }, f x = ∏ x ∈ s, f x := by rw [← prod_attach]; exact tprod_fintype _ @[to_additive] theorem Finset.tprod_subtype' (s : Finset β) (f : β → α) : ∏' x : (s : Set β), f x = ∏ x ∈ s, f x := by simp @[to_additive (attr := simp)] theorem tprod_singleton (b : β) (f : β → α) : ∏' x : ({b} : Set β), f x = f b := by rw [← coe_singleton, Finset.tprod_subtype', prod_singleton] open scoped Classical in @[to_additive] theorem Function.Injective.tprod_eq {g : γ → β} (hg : Injective g) {f : β → α} (hf : mulSupport f ⊆ Set.range g) : ∏' c, f (g c) = ∏' b, f b := by have : mulSupport f = g '' mulSupport (f ∘ g) := by rw [mulSupport_comp_eq_preimage, Set.image_preimage_eq_iff.2 hf] rw [← Function.comp_def] by_cases hf_fin : (mulSupport f).Finite · have hfg_fin : (mulSupport (f ∘ g)).Finite := hf_fin.preimage hg.injOn lift g to γ ↪ β using hg simp_rw [tprod_eq_prod' hf_fin.coe_toFinset.ge, tprod_eq_prod' hfg_fin.coe_toFinset.ge, comp_apply, ← Finset.prod_map] refine Finset.prod_congr (Finset.coe_injective ?_) fun _ _ ↦ rfl simp [this] · have hf_fin' : ¬ Set.Finite (mulSupport (f ∘ g)) := by rwa [this, Set.finite_image_iff hg.injOn] at hf_fin simp_rw [tprod_def, if_neg hf_fin, if_neg hf_fin', Multipliable, funext fun a => propext <| hg.hasProd_iff (mulSupport_subset_iff'.1 hf) (a := a)] @[to_additive] theorem Equiv.tprod_eq (e : γ ≃ β) (f : β → α) : ∏' c, f (e c) = ∏' b, f b := e.injective.tprod_eq <| by simp /-! ### `tprod` on subsets - part 1 -/ @[to_additive] theorem tprod_subtype_eq_of_mulSupport_subset {f : β → α} {s : Set β} (hs : mulSupport f ⊆ s) : ∏' x : s, f x = ∏' x, f x := Subtype.val_injective.tprod_eq <| by simpa @[to_additive] theorem tprod_subtype_mulSupport (f : β → α) : ∏' x : mulSupport f, f x = ∏' x, f x := tprod_subtype_eq_of_mulSupport_subset Set.Subset.rfl @[to_additive] theorem tprod_subtype (s : Set β) (f : β → α) : ∏' x : s, f x = ∏' x, s.mulIndicator f x := by rw [← tprod_subtype_eq_of_mulSupport_subset Set.mulSupport_mulIndicator_subset, tprod_congr] simp @[to_additive (attr := simp)] theorem tprod_univ (f : β → α) : ∏' x : (Set.univ : Set β), f x = ∏' x, f x := tprod_subtype_eq_of_mulSupport_subset <| Set.subset_univ _ @[to_additive] theorem tprod_image {g : γ → β} (f : β → α) {s : Set γ} (hg : Set.InjOn g s) : ∏' x : g '' s, f x = ∏' x : s, f (g x) := ((Equiv.Set.imageOfInjOn _ _ hg).tprod_eq fun x ↦ f x).symm @[to_additive] theorem tprod_range {g : γ → β} (f : β → α) (hg : Injective g) : ∏' x : Set.range g, f x = ∏' x, f (g x) := by rw [← Set.image_univ, tprod_image f hg.injOn] simp_rw [← comp_apply (g := g), tprod_univ (f ∘ g)] /-- If `f b = 1` for all `b ∈ t`, then the product of `f a` with `a ∈ s` is the same as the product of `f a` with `a ∈ s ∖ t`. -/ @[to_additive /-- If `f b = 0` for all `b ∈ t`, then the sum of `f a` with `a ∈ s` is the same as the sum of `f a` with `a ∈ s ∖ t`. -/] lemma tprod_setElem_eq_tprod_setElem_diff {f : β → α} (s t : Set β) (hf₀ : ∀ b ∈ t, f b = 1) : ∏' a : s, f a = ∏' a : (s \ t : Set β), f a := .symm <| (Set.inclusion_injective (t := s) Set.diff_subset).tprod_eq (f := f ∘ (↑)) <| mulSupport_subset_iff'.2 fun b hb ↦ hf₀ b <| by simpa using hb /-- If `f b = 1`, then the product of `f a` with `a ∈ s` is the same as the product of `f a` for `a ∈ s ∖ {b}`. -/ @[to_additive /-- If `f b = 0`, then the sum of `f a` with `a ∈ s` is the same as the sum of `f a` for `a ∈ s ∖ {b}`. -/] lemma tprod_eq_tprod_diff_singleton {f : β → α} (s : Set β) {b : β} (hf₀ : f b = 1) : ∏' a : s, f a = ∏' a : (s \ {b} : Set β), f a := tprod_setElem_eq_tprod_setElem_diff s {b} fun _ ha ↦ ha ▸ hf₀ @[to_additive] theorem tprod_eq_tprod_of_ne_one_bij {g : γ → α} (i : mulSupport g → β) (hi : Injective i) (hf : mulSupport f ⊆ Set.range i) (hfg : ∀ x, f (i x) = g x) : ∏' x, f x = ∏' y, g y := by rw [← tprod_subtype_mulSupport g, ← hi.tprod_eq hf] simp only [hfg] @[to_additive] theorem Equiv.tprod_eq_tprod_of_mulSupport {f : β → α} {g : γ → α} (e : mulSupport f ≃ mulSupport g) (he : ∀ x, g (e x) = f x) : ∏' x, f x = ∏' y, g y := .symm <| tprod_eq_tprod_of_ne_one_bij _ (Subtype.val_injective.comp e.injective) (by simp) he @[to_additive] theorem tprod_dite_right (P : Prop) [Decidable P] (x : β → ¬P → α) : ∏' b : β, (if h : P then (1 : α) else x b h) = if h : P then (1 : α) else ∏' b : β, x b h := by by_cases hP : P <;> simp [hP] @[to_additive] theorem tprod_dite_left (P : Prop) [Decidable P] (x : β → P → α) : ∏' b : β, (if h : P then x b h else 1) = if h : P then ∏' b : β, x b h else 1 := by by_cases hP : P <;> simp [hP] @[to_additive (attr := simp)] lemma tprod_extend_one {γ : Type*} {g : γ → β} (hg : Injective g) (f : γ → α) : ∏' y, extend g f 1 y = ∏' x, f x := by have : mulSupport (extend g f 1) ⊆ Set.range g := mulSupport_subset_iff'.2 <| extend_apply' _ _ simp_rw [← hg.tprod_eq this, hg.extend_apply] variable [T2Space α] @[to_additive] theorem Function.Surjective.tprod_eq_tprod_of_hasProd_iff_hasProd {α' : Type*} [CommMonoid α'] [TopologicalSpace α'] {e : α' → α} (hes : Function.Surjective e) (h1 : e 1 = 1) {f : β → α} {g : γ → α'} (h : ∀ {a}, HasProd f (e a) ↔ HasProd g a) : ∏' b, f b = e (∏' c, g c) := by_cases (fun x ↦ (h.mpr x.hasProd).tprod_eq) fun hg : ¬Multipliable g ↦ by have hf : ¬Multipliable f := mt (hes.multipliable_iff_of_hasProd_iff @h).1 hg simp [tprod_def, hf, hg, h1] @[to_additive] theorem tprod_eq_tprod_of_hasProd_iff_hasProd {f : β → α} {g : γ → α} (h : ∀ {a}, HasProd f a ↔ HasProd g a) : ∏' b, f b = ∏' c, g c := surjective_id.tprod_eq_tprod_of_hasProd_iff_hasProd rfl @h section ContinuousMul variable [ContinuousMul α] @[to_additive] protected theorem Multipliable.tprod_mul (hf : Multipliable f) (hg : Multipliable g) : ∏' b, (f b * g b) = (∏' b, f b) * ∏' b, g b := (hf.hasProd.mul hg.hasProd).tprod_eq @[deprecated (since := "2025-04-12")] alias tsum_add := Summable.tsum_add @[to_additive existing, deprecated (since := "2025-04-12")] alias tprod_mul := Multipliable.tprod_mul @[to_additive] protected theorem Multipliable.tprod_finsetProd {f : γ → β → α} {s : Finset γ} (hf : ∀ i ∈ s, Multipliable (f i)) : ∏' b, ∏ i ∈ s, f i b = ∏ i ∈ s, ∏' b, f i b := (hasProd_prod fun i hi ↦ (hf i hi).hasProd).tprod_eq @[deprecated (since := "2025-02-13")] alias tprod_of_prod := Multipliable.tprod_finsetProd @[deprecated (since := "2025-04-12")] alias tsum_finsetSum := Summable.tsum_finsetSum @[to_additive existing, deprecated (since := "2025-04-12")] alias tprod_finsetProd := Multipliable.tprod_finsetProd /-- Version of `tprod_eq_mul_tprod_ite` for `CommMonoid` rather than `CommGroup`. Requires a different convergence assumption involving `Function.update`. -/ @[to_additive /-- Version of `tsum_eq_add_tsum_ite` for `AddCommMonoid` rather than `AddCommGroup`. Requires a different convergence assumption involving `Function.update`. -/] protected theorem Multipliable.tprod_eq_mul_tprod_ite' [DecidableEq β] {f : β → α} (b : β) (hf : Multipliable (update f b 1)) : ∏' x, f x = f b * ∏' x, ite (x = b) 1 (f x) := calc ∏' x, f x = ∏' x, (ite (x = b) (f x) 1 * update f b 1 x) := tprod_congr fun n ↦ by split_ifs with h <;> simp [update_apply, h] _ = (∏' x, ite (x = b) (f x) 1) * ∏' x, update f b 1 x := Multipliable.tprod_mul ⟨ite (b = b) (f b) 1, hasProd_single b fun _ hb ↦ if_neg hb⟩ hf _ = ite (b = b) (f b) 1 * ∏' x, update f b 1 x := by congr exact tprod_eq_mulSingle b fun b' hb' ↦ if_neg hb' _ = f b * ∏' x, ite (x = b) 1 (f x) := by simp only [update, if_true, eq_rec_constant, dite_eq_ite] @[deprecated (since := "2025-04-12")] alias tsum_eq_add_tsum_ite' := Summable.tsum_eq_add_tsum_ite' @[to_additive existing, deprecated (since := "2025-04-12")] alias tprod_eq_mul_tprod_ite' := Multipliable.tprod_eq_mul_tprod_ite' @[to_additive] protected theorem Multipliable.tprod_mul_tprod_compl {s : Set β} (hs : Multipliable (f ∘ (↑) : s → α)) (hsc : Multipliable (f ∘ (↑) : ↑sᶜ → α)) : (∏' x : s, f x) * ∏' x : ↑sᶜ, f x = ∏' x, f x := (hs.hasProd.mul_compl hsc.hasProd).tprod_eq.symm @[deprecated (since := "2025-04-12")] alias tsum_add_tsum_compl := Summable.tsum_add_tsum_compl @[to_additive existing, deprecated (since := "2025-04-12")] alias tprod_mul_tprod_compl := Multipliable.tprod_mul_tprod_compl @[to_additive] protected theorem Multipliable.tprod_union_disjoint {s t : Set β} (hd : Disjoint s t) (hs : Multipliable (f ∘ (↑) : s → α)) (ht : Multipliable (f ∘ (↑) : t → α)) : ∏' x : ↑(s ∪ t), f x = (∏' x : s, f x) * ∏' x : t, f x := (hs.hasProd.mul_disjoint hd ht.hasProd).tprod_eq @[deprecated (since := "2025-04-12")] alias tsum_union_disjoint := Summable.tsum_union_disjoint @[to_additive existing, deprecated (since := "2025-04-12")] alias tprod_union_disjoint := Multipliable.tprod_union_disjoint @[to_additive] protected theorem Multipliable.tprod_finset_bUnion_disjoint {ι} {s : Finset ι} {t : ι → Set β} (hd : (s : Set ι).Pairwise (Disjoint on t)) (hf : ∀ i ∈ s, Multipliable (f ∘ (↑) : t i → α)) : ∏' x : ⋃ i ∈ s, t i, f x = ∏ i ∈ s, ∏' x : t i, f x := (hasProd_prod_disjoint _ hd fun i hi ↦ (hf i hi).hasProd).tprod_eq @[deprecated (since := "2025-04-12")] alias tsum_finset_bUnion_disjoint := Summable.tsum_finset_bUnion_disjoint @[to_additive existing, deprecated (since := "2025-04-12")] alias tprod_finset_bUnion_disjoint := Multipliable.tprod_finset_bUnion_disjoint end ContinuousMul end tprod section CommMonoidWithZero variable [CommMonoidWithZero α] [TopologicalSpace α] {f : β → α} lemma hasProd_zero_of_exists_eq_zero (hf : ∃ b, f b = 0) : HasProd f 0 := by obtain ⟨b, hb⟩ := hf apply tendsto_const_nhds.congr' filter_upwards [eventually_ge_atTop {b}] with s hs exact (Finset.prod_eq_zero (Finset.singleton_subset_iff.mp hs) hb).symm lemma multipliable_of_exists_eq_zero (hf : ∃ b, f b = 0) : Multipliable f := ⟨0, hasProd_zero_of_exists_eq_zero hf⟩ lemma tprod_of_exists_eq_zero [T2Space α] (hf : ∃ b, f b = 0) : ∏' b, f b = 0 := (hasProd_zero_of_exists_eq_zero hf).tprod_eq end CommMonoidWithZero
Conjugation.lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.LinearAlgebra.CliffordAlgebra.Grading import Mathlib.Algebra.Module.Opposite /-! # Conjugations This file defines the grade reversal and grade involution functions on multivectors, `reverse` and `involute`. Together, these operations compose to form the "Clifford conjugate", hence the name of this file. https://en.wikipedia.org/wiki/Clifford_algebra#Antiautomorphisms ## Main definitions * `CliffordAlgebra.involute`: the grade involution, negating each basis vector * `CliffordAlgebra.reverse`: the grade reversion, reversing the order of a product of vectors ## Main statements * `CliffordAlgebra.involute_involutive` * `CliffordAlgebra.reverse_involutive` * `CliffordAlgebra.reverse_involute_commute` * `CliffordAlgebra.involute_mem_evenOdd_iff` * `CliffordAlgebra.reverse_mem_evenOdd_iff` -/ variable {R : Type*} [CommRing R] variable {M : Type*} [AddCommGroup M] [Module R M] variable {Q : QuadraticForm R M} namespace CliffordAlgebra section Involute /-- Grade involution, inverting the sign of each basis vector. -/ def involute : CliffordAlgebra Q →ₐ[R] CliffordAlgebra Q := CliffordAlgebra.lift Q ⟨-ι Q, fun m => by simp⟩ @[simp] theorem involute_ι (m : M) : involute (ι Q m) = -ι Q m := lift_ι_apply _ _ m @[simp] theorem involute_comp_involute : involute.comp involute = AlgHom.id R (CliffordAlgebra Q) := by ext; simp theorem involute_involutive : Function.Involutive (involute : _ → CliffordAlgebra Q) := AlgHom.congr_fun involute_comp_involute @[simp] theorem involute_involute : ∀ a : CliffordAlgebra Q, involute (involute a) = a := involute_involutive /-- `CliffordAlgebra.involute` as an `AlgEquiv`. -/ @[simps!] def involuteEquiv : CliffordAlgebra Q ≃ₐ[R] CliffordAlgebra Q := AlgEquiv.ofAlgHom involute involute (AlgHom.ext <| involute_involute) (AlgHom.ext <| involute_involute) end Involute section Reverse open MulOpposite /-- `CliffordAlgebra.reverse` as an `AlgHom` to the opposite algebra -/ def reverseOp : CliffordAlgebra Q →ₐ[R] (CliffordAlgebra Q)ᵐᵒᵖ := CliffordAlgebra.lift Q ⟨(MulOpposite.opLinearEquiv R).toLinearMap ∘ₗ ι Q, fun m => unop_injective <| by simp⟩ @[simp] theorem reverseOp_ι (m : M) : reverseOp (ι Q m) = op (ι Q m) := lift_ι_apply _ _ _ /-- `CliffordAlgebra.reverseEquiv` as an `AlgEquiv` to the opposite algebra -/ @[simps! apply] def reverseOpEquiv : CliffordAlgebra Q ≃ₐ[R] (CliffordAlgebra Q)ᵐᵒᵖ := AlgEquiv.ofAlgHom reverseOp (AlgHom.opComm reverseOp) (AlgHom.unop.injective <| hom_ext <| LinearMap.ext fun _ => by simp) (hom_ext <| LinearMap.ext fun _ => by simp) @[simp] theorem reverseOpEquiv_opComm : AlgEquiv.opComm (reverseOpEquiv (Q := Q)) = reverseOpEquiv.symm := rfl /-- Grade reversion, inverting the multiplication order of basis vectors. Also called *transpose* in some literature. -/ def reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q := (opLinearEquiv R).symm.toLinearMap.comp reverseOp.toLinearMap @[simp] theorem unop_reverseOp (x : CliffordAlgebra Q) : (reverseOp x).unop = reverse x := rfl @[simp] theorem op_reverse (x : CliffordAlgebra Q) : op (reverse x) = reverseOp x := rfl @[simp] theorem reverse_ι (m : M) : reverse (ι Q m) = ι Q m := by simp [reverse] @[simp] theorem reverse.commutes (r : R) : reverse (algebraMap R (CliffordAlgebra Q) r) = algebraMap R _ r := op_injective <| reverseOp.commutes r @[simp] protected theorem reverse.map_one : reverse (1 : CliffordAlgebra Q) = 1 := op_injective (map_one reverseOp) @[simp] protected theorem reverse.map_mul (a b : CliffordAlgebra Q) : reverse (a * b) = reverse b * reverse a := op_injective (map_mul reverseOp a b) @[simp] theorem reverse_involutive : Function.Involutive (reverse (Q := Q)) := AlgHom.congr_fun reverseOpEquiv.symm_comp @[simp] theorem reverse_comp_reverse : reverse.comp reverse = (LinearMap.id : _ →ₗ[R] CliffordAlgebra Q) := LinearMap.ext reverse_involutive @[simp] theorem reverse_reverse : ∀ a : CliffordAlgebra Q, reverse (reverse a) = a := reverse_involutive /-- `CliffordAlgebra.reverse` as a `LinearEquiv`. -/ @[simps!] def reverseEquiv : CliffordAlgebra Q ≃ₗ[R] CliffordAlgebra Q := LinearEquiv.ofInvolutive reverse reverse_involutive theorem reverse_comp_involute : reverse.comp involute.toLinearMap = (involute.toLinearMap.comp reverse : _ →ₗ[R] CliffordAlgebra Q) := by ext x simp only [LinearMap.comp_apply, AlgHom.toLinearMap_apply] induction x using CliffordAlgebra.induction with | algebraMap => simp | ι => simp | mul a b ha hb => simp only [ha, hb, reverse.map_mul, map_mul] | add a b ha hb => simp only [ha, hb, reverse.map_add, map_add] /-- `CliffordAlgebra.reverse` and `CliffordAlgebra.involute` commute. Note that the composition is sometimes referred to as the "clifford conjugate". -/ theorem reverse_involute_commute : Function.Commute (reverse (Q := Q)) involute := LinearMap.congr_fun reverse_comp_involute theorem reverse_involute : ∀ a : CliffordAlgebra Q, reverse (involute a) = involute (reverse a) := reverse_involute_commute end Reverse /-! ### Statements about conjugations of products of lists -/ section List /-- Taking the reverse of the product a list of $n$ vectors lifted via `ι` is equivalent to taking the product of the reverse of that list. -/ theorem reverse_prod_map_ι : ∀ l : List M, reverse (l.map <| ι Q).prod = (l.map <| ι Q).reverse.prod | [] => by simp | x::xs => by simp [reverse_prod_map_ι xs] /-- Taking the involute of the product a list of $n$ vectors lifted via `ι` is equivalent to premultiplying by ${-1}^n$. -/ theorem involute_prod_map_ι : ∀ l : List M, involute (l.map <| ι Q).prod = (-1 : R) ^ l.length • (l.map <| ι Q).prod | [] => by simp | x::xs => by simp [pow_succ, involute_prod_map_ι xs] end List /-! ### Statements about `Submodule.map` and `Submodule.comap` -/ section Submodule variable (Q) section Involute theorem submodule_map_involute_eq_comap (p : Submodule R (CliffordAlgebra Q)) : p.map (involute : CliffordAlgebra Q →ₐ[R] CliffordAlgebra Q).toLinearMap = p.comap (involute : CliffordAlgebra Q →ₐ[R] CliffordAlgebra Q).toLinearMap := Submodule.map_equiv_eq_comap_symm involuteEquiv.toLinearEquiv _ @[simp] theorem ι_range_map_involute : (LinearMap.range (ι Q)).map (involute : CliffordAlgebra Q →ₐ[R] CliffordAlgebra Q).toLinearMap = LinearMap.range (ι Q) := (ι_range_map_lift _ _).trans (LinearMap.range_neg _) @[simp] theorem ι_range_comap_involute : (LinearMap.range (ι Q)).comap (involute : CliffordAlgebra Q →ₐ[R] CliffordAlgebra Q).toLinearMap = LinearMap.range (ι Q) := by rw [← submodule_map_involute_eq_comap, ι_range_map_involute] @[simp] theorem evenOdd_map_involute (n : ZMod 2) : (evenOdd Q n).map (involute : CliffordAlgebra Q →ₐ[R] CliffordAlgebra Q).toLinearMap = evenOdd Q n := by simp_rw [evenOdd, Submodule.map_iSup, Submodule.map_pow, ι_range_map_involute] @[simp] theorem evenOdd_comap_involute (n : ZMod 2) : (evenOdd Q n).comap (involute : CliffordAlgebra Q →ₐ[R] CliffordAlgebra Q).toLinearMap = evenOdd Q n := by rw [← submodule_map_involute_eq_comap, evenOdd_map_involute] end Involute section Reverse theorem submodule_map_reverse_eq_comap (p : Submodule R (CliffordAlgebra Q)) : p.map (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) = p.comap (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) := Submodule.map_equiv_eq_comap_symm (reverseEquiv : _ ≃ₗ[R] _) _ @[simp] theorem ι_range_map_reverse : (LinearMap.range (ι Q)).map (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) = LinearMap.range (ι Q) := by rw [reverse, reverseOp, Submodule.map_comp, ι_range_map_lift, LinearMap.range_comp, ← Submodule.map_comp] exact Submodule.map_id _ @[simp] theorem ι_range_comap_reverse : (LinearMap.range (ι Q)).comap (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) = LinearMap.range (ι Q) := by rw [← submodule_map_reverse_eq_comap, ι_range_map_reverse] /-- Like `Submodule.map_mul`, but with the multiplication reversed. -/ theorem submodule_map_mul_reverse (p q : Submodule R (CliffordAlgebra Q)) : (p * q).map (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) = q.map (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) * p.map (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) := by simp_rw [reverse, Submodule.map_comp, Submodule.map_mul, Submodule.map_unop_mul] theorem submodule_comap_mul_reverse (p q : Submodule R (CliffordAlgebra Q)) : (p * q).comap (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) = q.comap (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) * p.comap (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) := by simp_rw [← submodule_map_reverse_eq_comap, submodule_map_mul_reverse] /-- Like `Submodule.map_pow` -/ theorem submodule_map_pow_reverse (p : Submodule R (CliffordAlgebra Q)) (n : ℕ) : (p ^ n).map (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) = p.map (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) ^ n := by simp_rw [reverse, Submodule.map_comp, Submodule.map_pow, Submodule.map_unop_pow] theorem submodule_comap_pow_reverse (p : Submodule R (CliffordAlgebra Q)) (n : ℕ) : (p ^ n).comap (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) = p.comap (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) ^ n := by simp_rw [← submodule_map_reverse_eq_comap, submodule_map_pow_reverse] @[simp] theorem evenOdd_map_reverse (n : ZMod 2) : (evenOdd Q n).map (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) = evenOdd Q n := by simp_rw [evenOdd, Submodule.map_iSup, submodule_map_pow_reverse, ι_range_map_reverse] @[simp] theorem evenOdd_comap_reverse (n : ZMod 2) : (evenOdd Q n).comap (reverse : CliffordAlgebra Q →ₗ[R] CliffordAlgebra Q) = evenOdd Q n := by rw [← submodule_map_reverse_eq_comap, evenOdd_map_reverse] end Reverse @[simp] theorem involute_mem_evenOdd_iff {x : CliffordAlgebra Q} {n : ZMod 2} : involute x ∈ evenOdd Q n ↔ x ∈ evenOdd Q n := SetLike.ext_iff.mp (evenOdd_comap_involute Q n) x @[simp] theorem reverse_mem_evenOdd_iff {x : CliffordAlgebra Q} {n : ZMod 2} : reverse x ∈ evenOdd Q n ↔ x ∈ evenOdd Q n := SetLike.ext_iff.mp (evenOdd_comap_reverse Q n) x end Submodule /-! ### Related properties of the even and odd submodules TODO: show that these are `iff`s when `Invertible (2 : R)`. -/ theorem involute_eq_of_mem_even {x : CliffordAlgebra Q} (h : x ∈ evenOdd Q 0) : involute x = x := by induction x, h using even_induction with | algebraMap r => exact AlgHom.commutes _ _ | add x y _hx _hy ihx ihy => rw [map_add, ihx, ihy] | ι_mul_ι_mul m₁ m₂ x _hx ihx => rw [map_mul, map_mul, involute_ι, involute_ι, ihx, neg_mul_neg] theorem involute_eq_of_mem_odd {x : CliffordAlgebra Q} (h : x ∈ evenOdd Q 1) : involute x = -x := by induction x, h using odd_induction with | ι m => exact involute_ι _ | add x y _hx _hy ihx ihy => rw [map_add, ihx, ihy, neg_add] | ι_mul_ι_mul m₁ m₂ x _hx ihx => rw [map_mul, map_mul, involute_ι, involute_ι, ihx, neg_mul_neg, mul_neg] end CliffordAlgebra
PartitionOfUnity.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.EMetricSpace.Paracompact import Mathlib.Topology.Instances.ENNReal.Lemmas import Mathlib.Analysis.Convex.PartitionOfUnity /-! # Lemmas about (e)metric spaces that need partition of unity The main lemma in this file (see `Metric.exists_continuous_real_forall_closedBall_subset`) says the following. Let `X` be a metric space. Let `K : ι → Set X` be a locally finite family of closed sets, let `U : ι → Set X` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive continuous function `δ : C(X, → ℝ)` such that for any `i` and `x ∈ K i`, we have `Metric.closedBall x (δ x) ⊆ U i`. We also formulate versions of this lemma for extended metric spaces and for different codomains (`ℝ`, `ℝ≥0`, and `ℝ≥0∞`). We also prove a few auxiliary lemmas to be used later in a proof of the smooth version of this lemma. ## Tags metric space, partition of unity, locally finite -/ open Topology ENNReal NNReal Filter Set Function TopologicalSpace variable {ι X : Type*} namespace EMetric variable [EMetricSpace X] {K : ι → Set X} {U : ι → Set X} /-- Let `K : ι → Set X` be a locally finite family of closed sets in an emetric space. Let `U : ι → Set X` be a family of open sets such that `K i ⊆ U i` for all `i`. Then for any point `x : X`, for sufficiently small `r : ℝ≥0∞` and for `y` sufficiently close to `x`, for all `i`, if `y ∈ K i`, then `EMetric.closedBall y r ⊆ U i`. -/ theorem eventually_nhds_zero_forall_closedBall_subset (hK : ∀ i, IsClosed (K i)) (hU : ∀ i, IsOpen (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : LocallyFinite K) (x : X) : ∀ᶠ p : ℝ≥0∞ × X in 𝓝 0 ×ˢ 𝓝 x, ∀ i, p.2 ∈ K i → closedBall p.2 p.1 ⊆ U i := by suffices ∀ i, x ∈ K i → ∀ᶠ p : ℝ≥0∞ × X in 𝓝 0 ×ˢ 𝓝 x, closedBall p.2 p.1 ⊆ U i by apply mp_mem ((eventually_all_finite (hfin.point_finite x)).2 this) (mp_mem (@tendsto_snd ℝ≥0∞ _ (𝓝 0) _ _ (hfin.iInter_compl_mem_nhds hK x)) _) apply univ_mem' rintro ⟨r, y⟩ hxy hyU i hi simp only [mem_iInter, mem_compl_iff, not_imp_not, mem_preimage] at hxy exact hyU _ (hxy _ hi) intro i hi rcases nhds_basis_closed_eball.mem_iff.1 ((hU i).mem_nhds <| hKU i hi) with ⟨R, hR₀, hR⟩ rcases ENNReal.lt_iff_exists_nnreal_btwn.mp hR₀ with ⟨r, hr₀, hrR⟩ filter_upwards [prod_mem_prod (eventually_lt_nhds hr₀) (closedBall_mem_nhds x (tsub_pos_iff_lt.2 hrR))] with p hp z hz apply hR calc edist z x ≤ edist z p.2 + edist p.2 x := edist_triangle _ _ _ _ ≤ p.1 + (R - p.1) := add_le_add hz <| le_trans hp.2 <| tsub_le_tsub_left hp.1.out.le _ _ = R := add_tsub_cancel_of_le (lt_trans (by exact hp.1) hrR).le theorem exists_forall_closedBall_subset_aux₁ (hK : ∀ i, IsClosed (K i)) (hU : ∀ i, IsOpen (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : LocallyFinite K) (x : X) : ∃ r : ℝ, ∀ᶠ y in 𝓝 x, r ∈ Ioi (0 : ℝ) ∩ ENNReal.ofReal ⁻¹' ⋂ (i) (_ : y ∈ K i), { r | closedBall y r ⊆ U i } := by have := (ENNReal.continuous_ofReal.tendsto' 0 0 ENNReal.ofReal_zero).eventually (eventually_nhds_zero_forall_closedBall_subset hK hU hKU hfin x).curry rcases this.exists_gt with ⟨r, hr0, hr⟩ refine ⟨r, hr.mono fun y hy => ⟨hr0, ?_⟩⟩ rwa [mem_preimage, mem_iInter₂] theorem exists_forall_closedBall_subset_aux₂ (y : X) : Convex ℝ (Ioi (0 : ℝ) ∩ ENNReal.ofReal ⁻¹' ⋂ (i) (_ : y ∈ K i), { r | closedBall y r ⊆ U i }) := (convex_Ioi _).inter <| OrdConnected.convex <| OrdConnected.preimage_ennreal_ofReal <| ordConnected_iInter fun i => ordConnected_iInter fun (_ : y ∈ K i) => ordConnected_setOf_closedBall_subset y (U i) /-- Let `X` be an extended metric space. Let `K : ι → Set X` be a locally finite family of closed sets, let `U : ι → Set X` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive continuous function `δ : C(X, ℝ)` such that for any `i` and `x ∈ K i`, we have `EMetric.closedBall x (ENNReal.ofReal (δ x)) ⊆ U i`. -/ theorem exists_continuous_real_forall_closedBall_subset (hK : ∀ i, IsClosed (K i)) (hU : ∀ i, IsOpen (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : LocallyFinite K) : ∃ δ : C(X, ℝ), (∀ x, 0 < δ x) ∧ ∀ (i), ∀ x ∈ K i, closedBall x (ENNReal.ofReal <| δ x) ⊆ U i := by simpa only [mem_inter_iff, forall_and, mem_preimage, mem_iInter, @forall_swap ι X] using exists_continuous_forall_mem_convex_of_local_const exists_forall_closedBall_subset_aux₂ (exists_forall_closedBall_subset_aux₁ hK hU hKU hfin) /-- Let `X` be an extended metric space. Let `K : ι → Set X` be a locally finite family of closed sets, let `U : ι → Set X` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive continuous function `δ : C(X, ℝ≥0)` such that for any `i` and `x ∈ K i`, we have `EMetric.closedBall x (δ x) ⊆ U i`. -/ theorem exists_continuous_nnreal_forall_closedBall_subset (hK : ∀ i, IsClosed (K i)) (hU : ∀ i, IsOpen (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : LocallyFinite K) : ∃ δ : C(X, ℝ≥0), (∀ x, 0 < δ x) ∧ ∀ (i), ∀ x ∈ K i, closedBall x (δ x) ⊆ U i := by rcases exists_continuous_real_forall_closedBall_subset hK hU hKU hfin with ⟨δ, hδ₀, hδ⟩ lift δ to C(X, ℝ≥0) using fun x => (hδ₀ x).le refine ⟨δ, hδ₀, fun i x hi => ?_⟩ simpa only [← ENNReal.ofReal_coe_nnreal] using hδ i x hi /-- Let `X` be an extended metric space. Let `K : ι → Set X` be a locally finite family of closed sets, let `U : ι → Set X` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive continuous function `δ : C(X, ℝ≥0∞)` such that for any `i` and `x ∈ K i`, we have `EMetric.closedBall x (δ x) ⊆ U i`. -/ theorem exists_continuous_eNNReal_forall_closedBall_subset (hK : ∀ i, IsClosed (K i)) (hU : ∀ i, IsOpen (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : LocallyFinite K) : ∃ δ : C(X, ℝ≥0∞), (∀ x, 0 < δ x) ∧ ∀ (i), ∀ x ∈ K i, closedBall x (δ x) ⊆ U i := let ⟨δ, hδ₀, hδ⟩ := exists_continuous_nnreal_forall_closedBall_subset hK hU hKU hfin ⟨ContinuousMap.comp ⟨Coe.coe, ENNReal.continuous_coe⟩ δ, fun x => ENNReal.coe_pos.2 (hδ₀ x), hδ⟩ end EMetric namespace Metric variable [MetricSpace X] {K : ι → Set X} {U : ι → Set X} /-- Let `X` be a metric space. Let `K : ι → Set X` be a locally finite family of closed sets, let `U : ι → Set X` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive continuous function `δ : C(X, ℝ≥0)` such that for any `i` and `x ∈ K i`, we have `Metric.closedBall x (δ x) ⊆ U i`. -/ theorem exists_continuous_nnreal_forall_closedBall_subset (hK : ∀ i, IsClosed (K i)) (hU : ∀ i, IsOpen (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : LocallyFinite K) : ∃ δ : C(X, ℝ≥0), (∀ x, 0 < δ x) ∧ ∀ (i), ∀ x ∈ K i, closedBall x (δ x) ⊆ U i := by rcases EMetric.exists_continuous_nnreal_forall_closedBall_subset hK hU hKU hfin with ⟨δ, hδ0, hδ⟩ refine ⟨δ, hδ0, fun i x hx => ?_⟩ rw [← emetric_closedBall_nnreal] exact hδ i x hx /-- Let `X` be a metric space. Let `K : ι → Set X` be a locally finite family of closed sets, let `U : ι → Set X` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive continuous function `δ : C(X, ℝ)` such that for any `i` and `x ∈ K i`, we have `Metric.closedBall x (δ x) ⊆ U i`. -/ theorem exists_continuous_real_forall_closedBall_subset (hK : ∀ i, IsClosed (K i)) (hU : ∀ i, IsOpen (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : LocallyFinite K) : ∃ δ : C(X, ℝ), (∀ x, 0 < δ x) ∧ ∀ (i), ∀ x ∈ K i, closedBall x (δ x) ⊆ U i := let ⟨δ, hδ₀, hδ⟩ := exists_continuous_nnreal_forall_closedBall_subset hK hU hKU hfin ⟨ContinuousMap.comp ⟨Coe.coe, NNReal.continuous_coe⟩ δ, hδ₀, hδ⟩ end Metric
Basic.lean
/- Copyright (c) 2025 Fangming Li. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fangming Li -/ import Mathlib.Topology.Sober import Mathlib.Topology.Spectral.Prespectral /-! # Spectral spaces A topological space is spectral if it is T0, compact, sober, quasi-separated, and its compact open subsets form an open basis. Prime spectra of commutative semirings are spectral spaces. -/ variable (α : Type*) [TopologicalSpace α] /-- A topological space is spectral if it is T0, compact, sober, quasi-separated, and its compact open subsets form an open basis. -/ @[stacks 08YG] class SpectralSpace : Prop extends T0Space α, CompactSpace α, QuasiSober α, QuasiSeparatedSpace α, PrespectralSpace α
Factors.lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import Mathlib.Algebra.BigOperators.Group.Multiset.Basic import Mathlib.Data.PNat.Prime import Mathlib.Data.Nat.Factors import Mathlib.Data.Multiset.OrderedMonoid import Mathlib.Data.Multiset.Sort /-! # Prime factors of nonzero naturals This file defines the factorization of a nonzero natural number `n` as a multiset of primes, the multiplicity of `p` in this factors multiset being the p-adic valuation of `n`. ## Main declarations * `PrimeMultiset`: Type of multisets of prime numbers. * `FactorMultiset n`: Multiset of prime factors of `n`. -/ /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and ℕ+, as we will formalize below. -/ def PrimeMultiset := Multiset Nat.Primes deriving Inhabited, AddCommMonoid, DistribLattice, SemilatticeSup, Sub, IsOrderedCancelAddMonoid, CanonicallyOrderedAdd, OrderBot, OrderedSub namespace PrimeMultiset -- `@[derive]` doesn't work for `meta` instances unsafe instance : Repr PrimeMultiset := by delta PrimeMultiset; infer_instance /-- The multiset consisting of a single prime -/ def ofPrime (p : Nat.Primes) : PrimeMultiset := ({p} : Multiset Nat.Primes) theorem card_ofPrime (p : Nat.Primes) : Multiset.card (ofPrime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def toNatMultiset : PrimeMultiset → Multiset ℕ := fun v => v.map (↑) instance coeNat : Coe PrimeMultiset (Multiset ℕ) := ⟨toNatMultiset⟩ /-- `PrimeMultiset.coe`, the coercion from a multiset of primes to a multiset of naturals, promoted to an `AddMonoidHom`. -/ def coeNatMonoidHom : PrimeMultiset →+ Multiset ℕ := Multiset.mapAddMonoidHom (↑) @[simp] theorem coe_coeNatMonoidHom : (coeNatMonoidHom : PrimeMultiset → Multiset ℕ) = (↑) := rfl theorem coeNat_injective : Function.Injective ((↑) : PrimeMultiset → Multiset ℕ) := Multiset.map_injective Nat.Primes.coe_nat_injective theorem coeNat_ofPrime (p : Nat.Primes) : (ofPrime p : Multiset ℕ) = {(p : ℕ)} := rfl theorem coeNat_prime (v : PrimeMultiset) (p : ℕ) (h : p ∈ (v : Multiset ℕ)) : p.Prime := by rcases Multiset.mem_map.mp h with ⟨⟨_, hp'⟩, ⟨_, h_eq⟩⟩ exact h_eq ▸ hp' /-- Converts a `PrimeMultiset` to a `Multiset ℕ+`. -/ def toPNatMultiset : PrimeMultiset → Multiset ℕ+ := fun v => v.map (↑) instance coePNat : Coe PrimeMultiset (Multiset ℕ+) := ⟨toPNatMultiset⟩ /-- `coePNat`, the coercion from a multiset of primes to a multiset of positive naturals, regarded as an `AddMonoidHom`. -/ def coePNatMonoidHom : PrimeMultiset →+ Multiset ℕ+ := Multiset.mapAddMonoidHom (↑) @[simp] theorem coe_coePNatMonoidHom : (coePNatMonoidHom : PrimeMultiset → Multiset ℕ+) = (↑) := rfl theorem coePNat_injective : Function.Injective ((↑) : PrimeMultiset → Multiset ℕ+) := Multiset.map_injective Nat.Primes.coe_pnat_injective theorem coePNat_ofPrime (p : Nat.Primes) : (ofPrime p : Multiset ℕ+) = {(p : ℕ+)} := rfl theorem coePNat_prime (v : PrimeMultiset) (p : ℕ+) (h : p ∈ (v : Multiset ℕ+)) : p.Prime := by rcases Multiset.mem_map.mp h with ⟨⟨_, hp'⟩, ⟨_, h_eq⟩⟩ exact h_eq ▸ hp' instance coeMultisetPNatNat : Coe (Multiset ℕ+) (Multiset ℕ) := ⟨fun v => v.map (↑)⟩ theorem coePNat_nat (v : PrimeMultiset) : ((v : Multiset ℕ+) : Multiset ℕ) = (v : Multiset ℕ) := by change (v.map ((↑) : Nat.Primes → ℕ+)).map Subtype.val = v.map Subtype.val rw [Multiset.map_map] rfl /-- The product of a `PrimeMultiset`, as a `ℕ+`. -/ def prod (v : PrimeMultiset) : ℕ+ := (v : Multiset PNat).prod theorem coe_prod (v : PrimeMultiset) : (v.prod : ℕ) = (v : Multiset ℕ).prod := by have h : (v.prod : ℕ) = ((v.map (↑) : Multiset ℕ+).map (↑)).prod := PNat.coeMonoidHom.map_multiset_prod v.toPNatMultiset simpa [Multiset.map_map] using h theorem prod_ofPrime (p : Nat.Primes) : (ofPrime p).prod = (p : ℕ+) := Multiset.prod_singleton _ /-- If a `Multiset ℕ` consists only of primes, it can be recast as a `PrimeMultiset`. -/ def ofNatMultiset (v : Multiset ℕ) (h : ∀ p : ℕ, p ∈ v → p.Prime) : PrimeMultiset := @Multiset.pmap ℕ Nat.Primes Nat.Prime (fun p hp => ⟨p, hp⟩) v h theorem to_ofNatMultiset (v : Multiset ℕ) (h) : (ofNatMultiset v h : Multiset ℕ) = v := by dsimp [ofNatMultiset, toNatMultiset] rw [Multiset.map_pmap, Multiset.pmap_eq_map, Multiset.map_id'] theorem prod_ofNatMultiset (v : Multiset ℕ) (h) : ((ofNatMultiset v h).prod : ℕ) = (v.prod : ℕ) := by rw [coe_prod, to_ofNatMultiset] /-- If a `Multiset ℕ+` consists only of primes, it can be recast as a `PrimeMultiset`. -/ def ofPNatMultiset (v : Multiset ℕ+) (h : ∀ p : ℕ+, p ∈ v → p.Prime) : PrimeMultiset := @Multiset.pmap ℕ+ Nat.Primes PNat.Prime (fun p hp => ⟨(p : ℕ), hp⟩) v h theorem to_ofPNatMultiset (v : Multiset ℕ+) (h) : (ofPNatMultiset v h : Multiset ℕ+) = v := by dsimp [ofPNatMultiset, toPNatMultiset] have : (fun (p : ℕ+) (h : p.Prime) => ((↑) : Nat.Primes → ℕ+) ⟨p, h⟩) = fun p _ => id p := by funext p h apply Subtype.eq rfl rw [Multiset.map_pmap, this, Multiset.pmap_eq_map, Multiset.map_id] theorem prod_ofPNatMultiset (v : Multiset ℕ+) (h) : ((ofPNatMultiset v h).prod : ℕ+) = v.prod := by dsimp [prod] rw [to_ofPNatMultiset] /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def ofNatList (l : List ℕ) (h : ∀ p : ℕ, p ∈ l → p.Prime) : PrimeMultiset := ofNatMultiset (l : Multiset ℕ) h theorem prod_ofNatList (l : List ℕ) (h) : ((ofNatList l h).prod : ℕ) = l.prod := by have := prod_ofNatMultiset (l : Multiset ℕ) h rw [Multiset.prod_coe] at this exact this /-- If a `List ℕ+` consists only of primes, it can be recast as a `PrimeMultiset` with the coercion from lists to multisets. -/ def ofPNatList (l : List ℕ+) (h : ∀ p : ℕ+, p ∈ l → p.Prime) : PrimeMultiset := ofPNatMultiset (l : Multiset ℕ+) h theorem prod_ofPNatList (l : List ℕ+) (h) : (ofPNatList l h).prod = l.prod := by have := prod_ofPNatMultiset (l : Multiset ℕ+) h rw [Multiset.prod_coe] at this exact this /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid ℕ+. -/ theorem prod_zero : (0 : PrimeMultiset).prod = 1 := by exact Multiset.prod_zero theorem prod_add (u v : PrimeMultiset) : (u + v).prod = u.prod * v.prod := by change (coePNatMonoidHom (u + v)).prod = _ rw [coePNatMonoidHom.map_add] exact Multiset.prod_add _ _ theorem prod_smul (d : ℕ) (u : PrimeMultiset) : (d • u).prod = u.prod ^ d := by induction d with | zero => simp only [zero_nsmul, pow_zero, prod_zero] | succ n ih => rw [succ_nsmul, prod_add, ih, pow_succ] end PrimeMultiset namespace PNat /-- The prime factors of n, regarded as a multiset -/ def factorMultiset (n : ℕ+) : PrimeMultiset := PrimeMultiset.ofNatList (Nat.primeFactorsList n) (@Nat.prime_of_mem_primeFactorsList n) /-- The product of the factors is the original number -/ theorem prod_factorMultiset (n : ℕ+) : (factorMultiset n).prod = n := eq <| by dsimp [factorMultiset] rw [PrimeMultiset.prod_ofNatList] exact Nat.prod_primeFactorsList n.ne_zero theorem coeNat_factorMultiset (n : ℕ+) : (factorMultiset n : Multiset ℕ) = (Nat.primeFactorsList n : Multiset ℕ) := PrimeMultiset.to_ofNatMultiset (Nat.primeFactorsList n) (@Nat.prime_of_mem_primeFactorsList n) end PNat namespace PrimeMultiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factorMultiset_prod (v : PrimeMultiset) : v.prod.factorMultiset = v := by apply PrimeMultiset.coeNat_injective rw [v.prod.coeNat_factorMultiset, PrimeMultiset.coe_prod] rcases v with ⟨l⟩ dsimp [PrimeMultiset.toNatMultiset] let l' := l.map ((↑) : Nat.Primes → ℕ) have (p : ℕ) (hp : p ∈ l') : p.Prime := by simp only [List.map_subtype, List.map_id_fun', id_eq, List.mem_unattach, l'] at hp obtain ⟨hp', -⟩ := hp exact hp' exact Multiset.coe_eq_coe.mpr (@Nat.primeFactorsList_unique _ l' rfl this).symm end PrimeMultiset namespace PNat /-- Positive integers biject with multisets of primes. -/ def factorMultisetEquiv : ℕ+ ≃ PrimeMultiset where toFun := factorMultiset invFun := PrimeMultiset.prod left_inv := prod_factorMultiset right_inv := PrimeMultiset.factorMultiset_prod /-- Factoring gives a homomorphism from the multiplicative monoid ℕ+ to the additive monoid of multisets. -/ theorem factorMultiset_one : factorMultiset 1 = 0 := by simp [factorMultiset, PrimeMultiset.ofNatList, PrimeMultiset.ofNatMultiset] theorem factorMultiset_mul (n m : ℕ+) : factorMultiset (n * m) = factorMultiset n + factorMultiset m := by let u := factorMultiset n let v := factorMultiset m have : n = u.prod := (prod_factorMultiset n).symm; rw [this] have : m = v.prod := (prod_factorMultiset m).symm; rw [this] rw [← PrimeMultiset.prod_add] repeat' rw [PrimeMultiset.factorMultiset_prod] theorem factorMultiset_pow (n : ℕ+) (m : ℕ) : factorMultiset (n ^ m) = m • factorMultiset n := by let u := factorMultiset n have : n = u.prod := (prod_factorMultiset n).symm rw [this, ← PrimeMultiset.prod_smul] repeat' rw [PrimeMultiset.factorMultiset_prod] /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factorMultiset_ofPrime (p : Nat.Primes) : (p : ℕ+).factorMultiset = PrimeMultiset.ofPrime p := by apply factorMultisetEquiv.symm.injective change (p : ℕ+).factorMultiset.prod = (PrimeMultiset.ofPrime p).prod rw [(p : ℕ+).prod_factorMultiset, PrimeMultiset.prod_ofPrime] /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factorMultiset_le_iff {m n : ℕ+} : factorMultiset m ≤ factorMultiset n ↔ m ∣ n := by constructor · intro h rw [← prod_factorMultiset m, ← prod_factorMultiset m] apply Dvd.intro (n.factorMultiset - m.factorMultiset).prod rw [← PrimeMultiset.prod_add, PrimeMultiset.factorMultiset_prod, add_tsub_cancel_of_le h, prod_factorMultiset] · intro h rw [← mul_div_exact h, factorMultiset_mul] exact le_self_add theorem factorMultiset_le_iff' {m : ℕ+} {v : PrimeMultiset} : factorMultiset m ≤ v ↔ m ∣ v.prod := by let h := @factorMultiset_le_iff m v.prod rw [v.factorMultiset_prod] at h exact h end PNat namespace PrimeMultiset theorem prod_dvd_iff {u v : PrimeMultiset} : u.prod ∣ v.prod ↔ u ≤ v := by let h := @PNat.factorMultiset_le_iff' u.prod v rw [u.factorMultiset_prod] at h exact h.symm theorem prod_dvd_iff' {u : PrimeMultiset} {n : ℕ+} : u.prod ∣ n ↔ u ≤ n.factorMultiset := by let h := @prod_dvd_iff u n.factorMultiset rw [n.prod_factorMultiset] at h exact h end PrimeMultiset namespace PNat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factorMultiset_gcd (m n : ℕ+) : factorMultiset (gcd m n) = factorMultiset m ⊓ factorMultiset n := by apply le_antisymm · apply le_inf_iff.mpr; constructor <;> apply factorMultiset_le_iff.mpr · exact gcd_dvd_left m n · exact gcd_dvd_right m n · rw [← PrimeMultiset.prod_dvd_iff, prod_factorMultiset] apply dvd_gcd <;> rw [PrimeMultiset.prod_dvd_iff'] · exact inf_le_left · exact inf_le_right theorem factorMultiset_lcm (m n : ℕ+) : factorMultiset (lcm m n) = factorMultiset m ⊔ factorMultiset n := by apply le_antisymm · rw [← PrimeMultiset.prod_dvd_iff, prod_factorMultiset] apply lcm_dvd <;> rw [← factorMultiset_le_iff'] · exact le_sup_left · exact le_sup_right · apply sup_le_iff.mpr; constructor <;> apply factorMultiset_le_iff.mpr · exact dvd_lcm_left m n · exact dvd_lcm_right m n /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factorMultiset (m : ℕ+) (p : Nat.Primes) (k : ℕ) : (p : ℕ+) ^ k ∣ m ↔ k ≤ m.factorMultiset.count p := by rw [Multiset.le_count_iff_replicate_le, ← factorMultiset_le_iff, factorMultiset_pow, factorMultiset_ofPrime] congr! 2 apply Multiset.eq_replicate.mpr constructor · rw [Multiset.card_nsmul, PrimeMultiset.card_ofPrime, mul_one] · intro q h rw [PrimeMultiset.ofPrime, Multiset.nsmul_singleton _ k] at h exact Multiset.eq_of_mem_replicate h end PNat namespace PrimeMultiset theorem prod_inf (u v : PrimeMultiset) : (u ⊓ v).prod = PNat.gcd u.prod v.prod := by let n := u.prod let m := v.prod change (u ⊓ v).prod = PNat.gcd n m have : u = n.factorMultiset := u.factorMultiset_prod.symm; rw [this] have : v = m.factorMultiset := v.factorMultiset_prod.symm; rw [this] rw [← PNat.factorMultiset_gcd n m, PNat.prod_factorMultiset] theorem prod_sup (u v : PrimeMultiset) : (u ⊔ v).prod = PNat.lcm u.prod v.prod := by let n := u.prod let m := v.prod change (u ⊔ v).prod = PNat.lcm n m have : u = n.factorMultiset := u.factorMultiset_prod.symm; rw [this] have : v = m.factorMultiset := v.factorMultiset_prod.symm; rw [this] rw [← PNat.factorMultiset_lcm n m, PNat.prod_factorMultiset] end PrimeMultiset
Denumerable.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Fintype.EquivFin import Mathlib.Data.List.MinMax import Mathlib.Data.Nat.Order.Lemmas import Mathlib.Logic.Encodable.Basic /-! # Denumerable types This file defines denumerable (countably infinite) types as a typeclass extending `Encodable`. This is used to provide explicit encode/decode functions from and to `ℕ`, with the information that those functions are inverses of each other. ## Implementation notes This property already has a name, namely `α ≃ ℕ`, but here we are interested in using it as a typeclass. -/ assert_not_exists Monoid variable {α β : Type*} /-- A denumerable type is (constructively) bijective with `ℕ`. Typeclass equivalent of `α ≃ ℕ`. -/ class Denumerable (α : Type*) extends Encodable α where /-- `decode` and `encode` are inverses. -/ decode_inv : ∀ n, ∃ a ∈ decode n, encode a = n open Finset Nat namespace Denumerable section variable [Denumerable α] [Denumerable β] open Encodable theorem decode_isSome (α) [Denumerable α] (n : ℕ) : (decode (α := α) n).isSome := Option.isSome_iff_exists.2 <| (decode_inv n).imp fun _ => And.left /-- Returns the `n`-th element of `α` indexed by the decoding. -/ def ofNat (α) [Denumerable α] (n : ℕ) : α := Option.get _ (decode_isSome α n) @[simp] theorem decode_eq_ofNat (α) [Denumerable α] (n : ℕ) : decode (α := α) n = some (ofNat α n) := Option.eq_some_of_isSome _ theorem ofNat_of_decode {n b} (h : decode (α := α) n = some b) : ofNat (α := α) n = b := by simpa using h @[simp] theorem encode_ofNat (n) : encode (ofNat α n) = n := by obtain ⟨a, h, e⟩ := decode_inv (α := α) n rwa [ofNat_of_decode h] @[simp] theorem ofNat_encode (a) : ofNat α (encode a) = a := ofNat_of_decode (encodek _) /-- A denumerable type is equivalent to `ℕ`. -/ def eqv (α) [Denumerable α] : α ≃ ℕ := ⟨encode, ofNat α, ofNat_encode, encode_ofNat⟩ -- See Note [lower instance priority] instance (priority := 100) : Infinite α := Infinite.of_surjective _ (eqv α).surjective /-- A type equivalent to `ℕ` is denumerable. -/ def mk' {α} (e : α ≃ ℕ) : Denumerable α where encode := e decode := some ∘ e.symm encodek _ := congr_arg some (e.symm_apply_apply _) decode_inv _ := ⟨_, rfl, e.apply_symm_apply _⟩ /-- Denumerability is conserved by equivalences. This is transitivity of equivalence the denumerable way. -/ def ofEquiv (α) {β} [Denumerable α] (e : β ≃ α) : Denumerable β := { Encodable.ofEquiv _ e with decode_inv := fun n => by simp [decode_ofEquiv, encode_ofEquiv] } @[simp] theorem ofEquiv_ofNat (α) {β} [Denumerable α] (e : β ≃ α) (n) : @ofNat β (ofEquiv _ e) n = e.symm (ofNat α n) := by letI := ofEquiv _ e refine ofNat_of_decode ?_ rw [decode_ofEquiv e] simp /-- All denumerable types are equivalent. -/ def equiv₂ (α β) [Denumerable α] [Denumerable β] : α ≃ β := (eqv α).trans (eqv β).symm instance nat : Denumerable ℕ := ⟨fun _ => ⟨_, rfl, rfl⟩⟩ @[simp] theorem ofNat_nat (n) : ofNat ℕ n = n := rfl /-- If `α` is denumerable, then so is `Option α`. -/ instance option : Denumerable (Option α) := ⟨fun n => by cases n with | zero => refine ⟨none, ?_, encode_none⟩ rw [decode_option_zero, Option.mem_def] | succ n => refine ⟨some (ofNat α n), ?_, ?_⟩ · rw [decode_option_succ, decode_eq_ofNat, Option.map_some, Option.mem_def] rw [encode_some, encode_ofNat]⟩ /-- If `α` and `β` are denumerable, then so is their sum. -/ instance sum : Denumerable (α ⊕ β) := ⟨fun n => by suffices ∃ a ∈ @decodeSum α β _ _ n, encodeSum a = bit (bodd n) (div2 n) by simpa [bit_decomp] simp only [decodeSum, boddDiv2_eq, decode_eq_ofNat, Option.map_some, Option.mem_def, Sum.exists] cases bodd n <;> simp [bit, encodeSum, Nat.two_mul]⟩ section Sigma variable {γ : α → Type*} [∀ a, Denumerable (γ a)] /-- A denumerable collection of denumerable types is denumerable. -/ instance sigma : Denumerable (Sigma γ) := ⟨fun n => by simp⟩ @[simp] theorem sigma_ofNat_val (n : ℕ) : ofNat (Sigma γ) n = ⟨ofNat α (unpair n).1, ofNat (γ _) (unpair n).2⟩ := Option.some.inj <| by rw [← decode_eq_ofNat, decode_sigma_val]; simp end Sigma /-- If `α` and `β` are denumerable, then so is their product. -/ instance prod : Denumerable (α × β) := ofEquiv _ (Equiv.sigmaEquivProd α β).symm theorem prod_ofNat_val (n : ℕ) : ofNat (α × β) n = (ofNat α (unpair n).1, ofNat β (unpair n).2) := by simp @[simp] theorem prod_nat_ofNat : ofNat (ℕ × ℕ) = unpair := by funext; simp instance int : Denumerable ℤ := Denumerable.mk' Equiv.intEquivNat instance pnat : Denumerable ℕ+ := Denumerable.mk' Equiv.pnatEquivNat /-- The lift of a denumerable type is denumerable. -/ instance ulift : Denumerable (ULift α) := ofEquiv _ Equiv.ulift /-- The lift of a denumerable type is denumerable. -/ instance plift : Denumerable (PLift α) := ofEquiv _ Equiv.plift /-- If `α` is denumerable, then `α × α` and `α` are equivalent. -/ def pair : α × α ≃ α := equiv₂ _ _ end end Denumerable namespace Nat.Subtype open Function Encodable /-! ### Subsets of `ℕ` -/ variable {s : Set ℕ} [Infinite s] section Classical theorem exists_succ (x : s) : ∃ n, (x : ℕ) + n + 1 ∈ s := by by_contra h have (a : ℕ) (ha : a ∈ s) : a < x + 1 := lt_of_not_ge fun hax => h ⟨a - (x + 1), by rwa [Nat.add_right_comm, Nat.add_sub_cancel' hax]⟩ classical exact Fintype.false ⟨(((Multiset.range (succ x)).filter (· ∈ s)).pmap (fun (y : ℕ) (hy : y ∈ s) => Subtype.mk y hy) (by simp [-Multiset.range_succ])).toFinset, by simpa [Subtype.ext_iff_val, Multiset.mem_filter, -Multiset.range_succ] ⟩ end Classical variable [DecidablePred (· ∈ s)] /-- Returns the next natural in a set, according to the usual ordering of `ℕ`. -/ def succ (x : s) : s := have h : ∃ m, (x : ℕ) + m + 1 ∈ s := exists_succ x ⟨↑x + Nat.find h + 1, Nat.find_spec h⟩ theorem succ_le_of_lt {x y : s} (h : y < x) : succ y ≤ x := have hx : ∃ m, (y : ℕ) + m + 1 ∈ s := exists_succ _ let ⟨k, hk⟩ := Nat.exists_eq_add_of_lt h have : Nat.find hx ≤ k := Nat.find_min' _ (hk ▸ x.2) show (y : ℕ) + Nat.find hx + 1 ≤ x by omega theorem le_succ_of_forall_lt_le {x y : s} (h : ∀ z < x, z ≤ y) : x ≤ succ y := have hx : ∃ m, (y : ℕ) + m + 1 ∈ s := exists_succ _ show (x : ℕ) ≤ (y : ℕ) + Nat.find hx + 1 from le_of_not_gt fun hxy => (h ⟨_, Nat.find_spec hx⟩ hxy).not_gt <| (by omega : (y : ℕ) < (y : ℕ) + Nat.find hx + 1) theorem lt_succ_self (x : s) : x < succ x := calc (x : ℕ) ≤ (x + _) := le_add_right .. _ < (succ x) := Nat.lt_succ_self (x + _) theorem lt_succ_iff_le {x y : s} : x < succ y ↔ x ≤ y := ⟨fun h => le_of_not_gt fun h' => not_le_of_gt h (succ_le_of_lt h'), fun h => lt_of_le_of_lt h (lt_succ_self _)⟩ /-- Returns the `n`-th element of a set, according to the usual ordering of `ℕ`. -/ def ofNat (s : Set ℕ) [DecidablePred (· ∈ s)] [Infinite s] : ℕ → s | 0 => ⊥ | n + 1 => succ (ofNat s n) theorem ofNat_surjective : Surjective (ofNat s) | ⟨x, hx⟩ => by set t : List s := ((List.range x).filter fun y => y ∈ s).pmap (fun (y : ℕ) (hy : y ∈ s) => ⟨y, hy⟩) (by intros a ha; simpa using (List.mem_filter.mp ha).2) with ht have hmt : ∀ {y : s}, y ∈ t ↔ y < ⟨x, hx⟩ := by simp [List.mem_filter, Subtype.ext_iff_val, ht] cases hmax : List.maximum t with | bot => refine ⟨0, le_antisymm bot_le (le_of_not_gt fun h => List.not_mem_nil (a := (⊥ : s)) ?_)⟩ rwa [← List.maximum_eq_bot.1 hmax, hmt] | coe m => have wf : ↑m < x := by simpa using hmt.mp (List.maximum_mem hmax) rcases ofNat_surjective m with ⟨a, rfl⟩ refine ⟨a + 1, le_antisymm (succ_le_of_lt wf) ?_⟩ exact le_succ_of_forall_lt_le fun z hz => List.le_maximum_of_mem (hmt.2 hz) hmax termination_by n => n.val @[simp] theorem ofNat_range : Set.range (ofNat s) = Set.univ := ofNat_surjective.range_eq @[simp] theorem coe_comp_ofNat_range : Set.range ((↑) ∘ ofNat s : ℕ → ℕ) = s := by rw [Set.range_comp Subtype.val, ofNat_range, Set.image_univ, Subtype.range_coe] private def toFunAux (x : s) : ℕ := (List.range x).countP (· ∈ s) private theorem toFunAux_eq {s : Set ℕ} [DecidablePred (· ∈ s)] (x : s) : toFunAux x = #{y ∈ Finset.range x | y ∈ s} := by rw [toFunAux, List.countP_eq_length_filter] rfl private theorem right_inverse_aux : ∀ n, toFunAux (ofNat s n) = n | 0 => by rw [toFunAux_eq, card_eq_zero, eq_empty_iff_forall_notMem] rintro n hn rw [mem_filter, ofNat, mem_range] at hn exact bot_le.not_gt (show (⟨n, hn.2⟩ : s) < ⊥ from hn.1) | n + 1 => by have ih : toFunAux (ofNat s n) = n := right_inverse_aux n have h₁ : (ofNat s n : ℕ) ∉ {x ∈ range (ofNat s n) | x ∈ s} := by simp have h₂ : {x ∈ range (succ (ofNat s n)) | x ∈ s} = insert ↑(ofNat s n) {x ∈ range (ofNat s n) | x ∈ s} := by simp only [Finset.ext_iff, mem_insert, mem_range, mem_filter] exact fun m => ⟨fun h => by simp only [h.2, and_true] exact Or.symm (lt_or_eq_of_le ((@lt_succ_iff_le _ _ _ ⟨m, h.2⟩ _).1 h.1)), fun h => h.elim (fun h => h.symm ▸ ⟨lt_succ_self _, (ofNat s n).prop⟩) fun h => ⟨h.1.trans (lt_succ_self _), h.2⟩⟩ simp only [toFunAux_eq, ofNat] at ih ⊢ conv => rhs rw [← ih, ← card_insert_of_notMem h₁, ← h₂] /-- Any infinite set of naturals is denumerable. -/ def denumerable (s : Set ℕ) [DecidablePred (· ∈ s)] [Infinite s] : Denumerable s := Denumerable.ofEquiv ℕ { toFun := toFunAux invFun := ofNat s left_inv := leftInverse_of_surjective_of_rightInverse ofNat_surjective right_inverse_aux right_inv := right_inverse_aux } end Nat.Subtype namespace Denumerable open Encodable /-- An infinite encodable type is denumerable. -/ def ofEncodableOfInfinite (α : Type*) [Encodable α] [Infinite α] : Denumerable α := by letI := @decidableRangeEncode α _ letI : Infinite (Set.range (@encode α _)) := Infinite.of_injective _ (Equiv.ofInjective _ encode_injective).injective letI := Nat.Subtype.denumerable (Set.range (@encode α _)) exact Denumerable.ofEquiv (Set.range (@encode α _)) (equivRangeEncode α) end Denumerable /-- See also `nonempty_encodable`, `nonempty_fintype`. -/ theorem nonempty_denumerable (α : Type*) [Countable α] [Infinite α] : Nonempty (Denumerable α) := (nonempty_encodable α).map fun h => @Denumerable.ofEncodableOfInfinite _ h _ theorem nonempty_denumerable_iff {α : Type*} : Nonempty (Denumerable α) ↔ Countable α ∧ Infinite α := ⟨fun ⟨_⟩ ↦ ⟨inferInstance, inferInstance⟩, fun ⟨_, _⟩ ↦ nonempty_denumerable _⟩ instance nonempty_equiv_of_countable [Countable α] [Infinite α] [Countable β] [Infinite β] : Nonempty (α ≃ β) := by cases nonempty_denumerable α cases nonempty_denumerable β exact ⟨(Denumerable.eqv _).trans (Denumerable.eqv _).symm⟩
FiniteStability.lean
/- Copyright (c) 2024 Christian Merten. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christian Merten -/ import Mathlib.LinearAlgebra.TensorProduct.RightExactness import Mathlib.RingTheory.FinitePresentation import Mathlib.RingTheory.TensorProduct.MvPolynomial /-! # Stability of finiteness conditions in commutative algebra In this file we show that `Algebra.FiniteType` and `Algebra.FinitePresentation` are stable under base change. -/ open scoped TensorProduct universe w₁ w₂ w₃ variable {R : Type w₁} [CommRing R] variable {A : Type w₂} [CommRing A] [Algebra R A] variable (B : Type w₃) [CommRing B] [Algebra R B] namespace Algebra namespace FiniteType theorem baseChangeAux_surj {σ : Type*} {f : MvPolynomial σ R →ₐ[R] A} (hf : Function.Surjective f) : Function.Surjective (Algebra.TensorProduct.map (AlgHom.id B B) f) := by change Function.Surjective (TensorProduct.map (AlgHom.id R B) f) apply TensorProduct.map_surjective · exact Function.RightInverse.surjective (congrFun rfl) · exact hf instance baseChange [hfa : FiniteType R A] : Algebra.FiniteType B (B ⊗[R] A) := by rw [iff_quotient_mvPolynomial''] at * obtain ⟨n, f, hf⟩ := hfa let g : B ⊗[R] MvPolynomial (Fin n) R →ₐ[B] B ⊗[R] A := Algebra.TensorProduct.map (AlgHom.id B B) f have : Function.Surjective g := baseChangeAux_surj B hf use n, AlgHom.comp g (MvPolynomial.algebraTensorAlgEquiv R B).symm.toAlgHom simpa end FiniteType namespace FinitePresentation instance baseChange [FinitePresentation R A] : FinitePresentation B (B ⊗[R] A) := by obtain ⟨n, f, hsurj, hfg⟩ := ‹FinitePresentation R A› let g : B ⊗[R] MvPolynomial (Fin n) R →ₐ[B] B ⊗[R] A := Algebra.TensorProduct.map (AlgHom.id B B) f have hgsurj : Function.Surjective g := Algebra.FiniteType.baseChangeAux_surj B hsurj have hker_eq : RingHom.ker g = Ideal.map Algebra.TensorProduct.includeRight (RingHom.ker f) := Algebra.TensorProduct.lTensor_ker f hsurj have hfgg : Ideal.FG (RingHom.ker g) := by rw [hker_eq] exact Ideal.FG.map hfg _ let g' : MvPolynomial (Fin n) B →ₐ[B] B ⊗[R] A := AlgHom.comp g (MvPolynomial.algebraTensorAlgEquiv R B).symm.toAlgHom refine ⟨n, g', ?_, Ideal.fg_ker_comp _ _ ?_ hfgg ?_⟩ · simp_all [g, g'] · change Ideal.FG (RingHom.ker (AlgEquiv.symm (MvPolynomial.algebraTensorAlgEquiv R B))) simp only [RingHom.ker_equiv] exact Submodule.fg_bot · simpa using EquivLike.surjective _ end FinitePresentation end Algebra
FaaDiBruno.lean
/- Copyright (c) 2024 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Data.Finite.Card import Mathlib.Analysis.Analytic.Within import Mathlib.Analysis.Calculus.FDeriv.Analytic import Mathlib.Analysis.Calculus.ContDiff.FTaylorSeries /-! # Faa di Bruno formula The Faa di Bruno formula gives the iterated derivative of `g ∘ f` in terms of those of `g` and `f`. It is expressed in terms of partitions `I` of `{0, ..., n-1}`. For such a partition, denote by `k` its number of parts, write the parts as `I₀, ..., Iₖ₋₁` ordered so that `max I₀ < ... < max Iₖ₋₁`, and let `iₘ` be the number of elements of `Iₘ`. Then `D^n (g ∘ f) (x) (v₀, ..., vₙ₋₁) = ∑_{I partition of {0, ..., n-1}} D^k g (f x) (D^{i₀} f (x) (v_{I₀}), ..., D^{iₖ₋₁} f (x) (v_{Iₖ₋₁}))` where by `v_{Iₘ}` we mean the vectors `vᵢ` with indices in `Iₘ`, i.e., the composition of `v` with the increasing embedding of `Fin iₘ` into `Fin n` with range `Iₘ`. For instance, for `n = 2`, there are 2 partitions of `{0, 1}`, given by `{0}, {1}` and `{0, 1}`, and therefore `D^2(g ∘ f) (x) (v₀, v₁) = D^2 g (f x) (Df (x) v₀, Df (x) v₁) + Dg (f x) (D^2f (x) (v₀, v₁))`. The formula is straightforward to prove by induction, as differentiating `D^k g (f x) (D^{i₀} f (x) (v_{I₀}), ..., D^{iₖ₋₁} f (x) (v_{Iₖ₋₁}))` gives a sum with `k + 1` terms where one differentiates either `D^k g (f x)`, or one of the `D^{iₘ} f (x)`, amounting to adding to the partition `I` either a new atom `{-1}` to its left, or extending `Iₘ` by adding `-1` to it. In this way, one obtains bijectively all partitions of `{-1, ..., n}`, and the proof can go on (up to relabelling). The main difficulty is to write things down in a precise language, namely to write `D^k g (f x) (D^{i₀} f (x) (v_{I₀}), ..., D^{iₖ₋₁} f (x) (v_{Iₖ₋₁}))` as a continuous multilinear map of the `vᵢ`. For this, instead of working with partitions of `{0, ..., n-1}` and ordering their parts, we work with partitions in which the ordering is part of the data -- this is equivalent, but much more convenient to implement. We call these `OrderedFinpartition n`. Note that the implementation of `OrderedFinpartition` is very specific to the Faa di Bruno formula: as testified by the formula above, what matters is really the embedding of the parts in `Fin n`, and moreover the parts have to be ordered by `max I₀ < ... < max Iₖ₋₁` for the formula to hold in the general case where the iterated differential might not be symmetric. The defeqs with respect to `Fin.cons` are also important when doing the induction. For this reason, we do not expect this class to be useful beyond the Faa di Bruno formula, which is why it is in this file instead of a dedicated file in the `Combinatorics` folder. ## Main results Given `c : OrderedFinpartition n` and two formal multilinear series `q` and `p`, we define `c.compAlongOrderedFinpartition q p` as an `n`-multilinear map given by the formula above, i.e., `(v₁, ..., vₙ) ↦ qₖ (p_{i₁} (v_{I₁}), ..., p_{iₖ} (v_{Iₖ}))`. Then, we define `q.taylorComp p` as a formal multilinear series whose `n`-th term is the sum of `c.compAlongOrderedFinpartition q p` over all ordered finpartitions of size `n`. Finally, we prove in `HasFTaylorSeriesUptoOn.comp` that, if two functions `g` and `f` have Taylor series up to `n` given by `q` and `p`, then `g ∘ f` also has a Taylor series, given by `q.taylorComp p`. ## Implementation A first technical difficulty is to implement the extension process of `OrderedFinpartition` corresponding to adding a new atom, or appending an atom to an existing part, and defining the associated increasing parameterizations that show up in the definition of `compAlongOrderedFinpartition`. Then, one has to show that the ordered finpartitions thus obtained give exactly all ordered finpartitions of order `n+1`. For this, we define the inverse process (shrinking a finpartition of `n+1` by erasing `0`, either as an atom or from the part that contains it), and we show that these processes are inverse to each other, yielding an equivalence between `(c : OrderedFinpartition n) × Option (Fin c.length)` and `OrderedFinpartition (n + 1)`. This equivalence shows up prominently in the inductive proof of Faa di Bruno formula to identify the sums that show up. -/ noncomputable section open Set Fin Filter Function variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] {G : Type*} [NormedAddCommGroup G] [NormedSpace 𝕜 G] {s : Set E} {t : Set F} {q : F → FormalMultilinearSeries 𝕜 F G} {p : E → FormalMultilinearSeries 𝕜 E F} /-- A partition of `Fin n` into finitely many nonempty subsets, given by the increasing parameterization of these subsets. We order the subsets by increasing greatest element. This definition is tailored-made for the Faa di Bruno formula, and probably not useful elsewhere, because of the specific parameterization by `Fin n` and the peculiar ordering. -/ @[ext] structure OrderedFinpartition (n : ℕ) where /-- The number of parts in the partition -/ length : ℕ /-- The size of each part -/ partSize : Fin length → ℕ partSize_pos : ∀ m, 0 < partSize m /-- The increasing parameterization of each part -/ emb : ∀ m, (Fin (partSize m)) → Fin n emb_strictMono : ∀ m, StrictMono (emb m) /-- The parts are ordered by increasing greatest element. -/ parts_strictMono : StrictMono fun m ↦ emb m ⟨partSize m - 1, Nat.sub_one_lt_of_lt (partSize_pos m)⟩ /-- The parts are disjoint -/ disjoint : PairwiseDisjoint univ fun m ↦ range (emb m) /-- The parts cover everything -/ cover x : ∃ m, x ∈ range (emb m) deriving DecidableEq namespace OrderedFinpartition /-! ### Basic API for ordered finpartitions -/ /-- The ordered finpartition of `Fin n` into singletons. -/ @[simps -fullyApplied] def atomic (n : ℕ) : OrderedFinpartition n where length := n partSize _ := 1 partSize_pos _ := _root_.zero_lt_one emb m _ := m emb_strictMono _ := Subsingleton.strictMono _ parts_strictMono := strictMono_id disjoint _ _ _ _ h := by simpa using h cover m := by simp variable {n : ℕ} (c : OrderedFinpartition n) instance : Inhabited (OrderedFinpartition n) := ⟨atomic n⟩ @[simp] theorem default_eq : (default : OrderedFinpartition n) = atomic n := rfl lemma length_le : c.length ≤ n := by simpa only [Fintype.card_fin] using Fintype.card_le_of_injective _ c.parts_strictMono.injective lemma partSize_le (m : Fin c.length) : c.partSize m ≤ n := by simpa only [Fintype.card_fin] using Fintype.card_le_of_injective _ (c.emb_strictMono m).injective /-- Embedding of ordered finpartitions in a sigma type. The sigma type on the right is quite big, but this is enough to get finiteness of ordered finpartitions. -/ def embSigma (n : ℕ) : OrderedFinpartition n → (Σ (l : Fin (n + 1)), Σ (p : Fin l → Fin (n + 1)), Π (i : Fin l), (Fin (p i) → Fin n)) := fun c ↦ ⟨⟨c.length, Order.lt_add_one_iff.mpr c.length_le⟩, fun m ↦ ⟨c.partSize m, Order.lt_add_one_iff.mpr (c.partSize_le m)⟩, fun j ↦ c.emb j⟩ lemma injective_embSigma (n : ℕ) : Injective (embSigma n) := by rintro ⟨plength, psize, -, pemb, -, -, -, -⟩ ⟨qlength, qsize, -, qemb, -, -, -, -⟩ intro hpq simp_all only [Sigma.mk.inj_iff, true_and, mk.injEq, Fin.mk.injEq, embSigma] have : plength = qlength := hpq.1 subst this simp_all only [Sigma.mk.inj_iff, heq_eq_eq, true_and, and_true] ext i exact mk.inj_iff.mp (congr_fun hpq.1 i) /- The best proof would probably to establish the bijection with Finpartitions, but we opt for a direct argument, embedding `OrderedPartition n` in a type which is obviously finite. -/ noncomputable instance : Fintype (OrderedFinpartition n) := Fintype.ofInjective _ (injective_embSigma n) instance instUniqueZero : Unique (OrderedFinpartition 0) := by have : Subsingleton (OrderedFinpartition 0) := Fintype.card_le_one_iff_subsingleton.mp (Fintype.card_le_of_injective _ (injective_embSigma 0)) exact Unique.mk' (OrderedFinpartition 0) lemma exists_inverse {n : ℕ} (c : OrderedFinpartition n) (j : Fin n) : ∃ p : Σ m, Fin (c.partSize m), c.emb p.1 p.2 = j := by rcases c.cover j with ⟨m, r, hmr⟩ exact ⟨⟨m, r⟩, hmr⟩ lemma emb_injective : Injective (fun (p : Σ m, Fin (c.partSize m)) ↦ c.emb p.1 p.2) := by rintro ⟨m, r⟩ ⟨m', r'⟩ (h : c.emb m r = c.emb m' r') have : m = m' := by contrapose! h have A : Disjoint (range (c.emb m)) (range (c.emb m')) := c.disjoint (mem_univ m) (mem_univ m') h apply disjoint_iff_forall_ne.1 A (mem_range_self r) (mem_range_self r') subst this simpa using (c.emb_strictMono m).injective h lemma emb_ne_emb_of_ne {i j : Fin c.length} {a : Fin (c.partSize i)} {b : Fin (c.partSize j)} (h : i ≠ j) : c.emb i a ≠ c.emb j b := c.emb_injective.ne (a₁ := ⟨i, a⟩) (a₂ := ⟨j, b⟩) (by simp [h]) /-- Given `j : Fin n`, the index of the part to which it belongs. -/ noncomputable def index (j : Fin n) : Fin c.length := (c.exists_inverse j).choose.1 /-- The inverse of `c.emb` for `c : OrderedFinpartition`. It maps `j : Fin n` to the point in `Fin (c.partSize (c.index j))` which is mapped back to `j` by `c.emb (c.index j)`. -/ noncomputable def invEmbedding (j : Fin n) : Fin (c.partSize (c.index j)) := (c.exists_inverse j).choose.2 @[simp] lemma emb_invEmbedding (j : Fin n) : c.emb (c.index j) (c.invEmbedding j) = j := (c.exists_inverse j).choose_spec /-- An ordered finpartition gives an equivalence between `Fin n` and the disjoint union of the parts, each of them parameterized by `Fin (c.partSize i)`. -/ noncomputable def equivSigma : ((i : Fin c.length) × Fin (c.partSize i)) ≃ Fin n where toFun p := c.emb p.1 p.2 invFun i := ⟨c.index i, c.invEmbedding i⟩ right_inv _ := by simp left_inv _ := by apply c.emb_injective; simp @[to_additive] lemma prod_sigma_eq_prod {α : Type*} [CommMonoid α] (v : Fin n → α) : ∏ (m : Fin c.length), ∏ (r : Fin (c.partSize m)), v (c.emb m r) = ∏ i, v i := by rw [Finset.prod_sigma'] exact Fintype.prod_equiv c.equivSigma _ _ (fun p ↦ rfl) lemma length_pos (h : 0 < n) : 0 < c.length := Nat.zero_lt_of_lt (c.index ⟨0, h⟩).2 lemma neZero_length [NeZero n] (c : OrderedFinpartition n) : NeZero c.length := ⟨(c.length_pos pos').ne'⟩ lemma neZero_partSize (c : OrderedFinpartition n) (i : Fin c.length) : NeZero (c.partSize i) := .of_pos (c.partSize_pos i) attribute [local instance] neZero_length neZero_partSize instance instUniqueOne : Unique (OrderedFinpartition 1) where uniq c := by have h₁ : c.length = 1 := le_antisymm c.length_le (c.length_pos Nat.zero_lt_one) have h₂ (i) : c.partSize i = 1 := le_antisymm (c.partSize_le _) (c.partSize_pos _) have h₃ (i j) : c.emb i j = 0 := Subsingleton.elim _ _ rcases c with ⟨length, partSize, _, emb, _, _, _, _⟩ subst h₁ obtain rfl : partSize = fun _ ↦ 1 := funext h₂ simpa [OrderedFinpartition.ext_iff, funext_iff, Fin.forall_fin_one] using h₃ _ _ lemma emb_zero [NeZero n] : c.emb (c.index 0) 0 = 0 := by apply le_antisymm _ (Fin.zero_le _) conv_rhs => rw [← c.emb_invEmbedding 0] apply (c.emb_strictMono _).monotone (Fin.zero_le _) lemma partSize_eq_one_of_range_emb_eq_singleton (c : OrderedFinpartition n) {i : Fin c.length} {j : Fin n} (hc : range (c.emb i) = {j}) : c.partSize i = 1 := by have : Fintype.card (range (c.emb i)) = Fintype.card (Fin (c.partSize i)) := card_range_of_injective (c.emb_strictMono i).injective simpa [hc] using this.symm /-- If the left-most part is not `{0}`, then the part containing `0` has at least two elements: either because it's the left-most part, and then it's not just `0` by assumption, or because it's not the left-most part and then, by increasingness of maximal elements in parts, it contains a positive element. -/ lemma one_lt_partSize_index_zero (c : OrderedFinpartition (n + 1)) (hc : range (c.emb 0) ≠ {0}) : 1 < c.partSize (c.index 0) := by have : c.partSize (c.index 0) = Nat.card (range (c.emb (c.index 0))) := by rw [Nat.card_range_of_injective (c.emb_strictMono _).injective]; simp rw [this] rcases eq_or_ne (c.index 0) 0 with h | h · rw [← h] at hc have : {0} ⊂ range (c.emb (c.index 0)) := by apply ssubset_of_subset_of_ne ?_ hc.symm simpa only [singleton_subset_iff, mem_range] using ⟨0, emb_zero c⟩ simpa using Set.Finite.card_lt_card (finite_range _) this · apply one_lt_two.trans_le have : {c.emb (c.index 0) 0, c.emb (c.index 0) ⟨c.partSize (c.index 0) - 1, Nat.sub_one_lt_of_lt (c.partSize_pos _)⟩} ⊆ range (c.emb (c.index 0)) := by simp [insert_subset] simp only [emb_zero] at this convert Nat.card_mono Subtype.finite this simp only [Nat.card_eq_fintype_card, Fintype.card_ofFinset, toFinset_singleton] apply (Finset.card_pair ?_).symm exact ((Fin.zero_le _).trans_lt (c.parts_strictMono ((pos_iff_ne_zero' (c.index 0)).mpr h))).ne /-! ### Extending and shrinking ordered finpartitions We show how an ordered finpartition can be extended to the left, either by adding a new atomic part (in `extendLeft`) or adding the new element to an existing part (in `extendMiddle`). Conversely, one can shrink a finpartition by deleting the element to the left, with a different behavior if it was an atomic part (in `eraseLeft`, in which case the number of parts decreases by one) or if it belonged to a non-atomic part (in `eraseMiddle`, in which case the number of parts stays the same). These operations are inverse to each other, giving rise to an equivalence between `((c : OrderedFinpartition n) × Option (Fin c.length))` and `OrderedFinpartition (n + 1)` called `OrderedFinPartition.extendEquiv`. -/ /-- Extend an ordered partition of `n` entries, by adding a new singleton part to the left. -/ @[simps -fullyApplied length partSize] def extendLeft (c : OrderedFinpartition n) : OrderedFinpartition (n + 1) where length := c.length + 1 partSize := Fin.cons 1 c.partSize partSize_pos := Fin.cases (by simp) (by simp [c.partSize_pos]) emb := Fin.cases (fun _ ↦ 0) (fun m ↦ Fin.succ ∘ c.emb m) emb_strictMono := by refine Fin.cases ?_ (fun i ↦ ?_) · exact @Subsingleton.strictMono _ _ _ _ (by simp; infer_instance) _ · exact strictMono_succ.comp (c.emb_strictMono i) parts_strictMono i j hij := by induction j using Fin.induction with | zero => simp at hij | succ j => induction i using Fin.induction with | zero => simp | succ i => simp only [cons_succ, cases_succ, comp_apply, succ_lt_succ_iff] exact c.parts_strictMono (by simpa using hij) disjoint i hi j hj hij := by wlog h : j < i generalizing i j · exact .symm (this j (mem_univ j) i (mem_univ i) hij.symm (lt_of_le_of_ne (le_of_not_gt h) hij)) induction i using Fin.induction with | zero => simp at h | succ i => induction j using Fin.induction with | zero => simp only [onFun, cases_succ, cases_zero] apply Set.disjoint_iff_forall_ne.2 simp only [mem_range, comp_apply, exists_prop', cons_zero, ne_eq, and_imp, Nonempty.forall, forall_const, forall_eq', forall_exists_index, forall_apply_eq_imp_iff] exact fun _ ↦ succ_ne_zero _ | succ j => simp only [onFun, cases_succ] apply Set.disjoint_iff_forall_ne.2 simp only [mem_range, comp_apply, ne_eq, forall_exists_index, forall_apply_eq_imp_iff, succ_inj] intro a b apply c.emb_ne_emb_of_ne (by simpa using hij) cover := by refine Fin.cases ?_ (fun i ↦ ?_) · simp only [mem_range] exact ⟨0, ⟨0, by simp⟩, by simp⟩ · simp only [mem_range] exact ⟨Fin.succ (c.index i), Fin.cast (by simp) (c.invEmbedding i), by simp⟩ @[simp] lemma range_extendLeft_zero (c : OrderedFinpartition n) : range (c.extendLeft.emb 0) = {0} := by simp [extendLeft] apply @range_const _ _ (by simp; infer_instance) /-- Extend an ordered partition of `n` entries, by adding to the `i`-th part a new point to the left. -/ @[simps -fullyApplied length partSize] def extendMiddle (c : OrderedFinpartition n) (k : Fin c.length) : OrderedFinpartition (n + 1) where length := c.length partSize := update c.partSize k (c.partSize k + 1) partSize_pos m := by rcases eq_or_ne m k with rfl | hm · simp · simpa [hm] using c.partSize_pos m emb := by intro m by_cases h : m = k · have : update c.partSize k (c.partSize k + 1) m = c.partSize k + 1 := by rw [h]; simp exact Fin.cases 0 (succ ∘ c.emb k) ∘ Fin.cast this · have : update c.partSize k (c.partSize k + 1) m = c.partSize m := by simp [h] exact succ ∘ c.emb m ∘ Fin.cast this emb_strictMono := by intro m rcases eq_or_ne m k with rfl | hm · suffices ∀ (a' b' : Fin (c.partSize m + 1)), a' < b' → (cases (motive := fun _ ↦ Fin (n + 1)) 0 (succ ∘ c.emb m)) a' < (cases (motive := fun _ ↦ Fin (n + 1)) 0 (succ ∘ c.emb m)) b' by simp only [↓reduceDIte] intro a b hab exact this _ _ hab intro a' b' h' induction b' using Fin.induction with | zero => simp at h' | succ b => induction a' using Fin.induction with | zero => simp | succ a' => simp only [cases_succ, comp_apply, succ_lt_succ_iff] exact c.emb_strictMono m (by simpa using h') · simp only [hm, ↓reduceDIte] exact strictMono_succ.comp ((c.emb_strictMono m).comp (by exact fun ⦃a b⦄ h ↦ h)) parts_strictMono := by convert strictMono_succ.comp c.parts_strictMono with m rcases eq_or_ne m k with rfl | hm · simp only [↓reduceDIte, update_self, add_tsub_cancel_right, comp_apply, cast_mk] let a : Fin (c.partSize m + 1) := ⟨c.partSize m, lt_add_one (c.partSize m)⟩ let b : Fin (c.partSize m) := ⟨c.partSize m - 1, Nat.sub_one_lt_of_lt (c.partSize_pos m)⟩ change (cases (motive := fun _ ↦ Fin (n + 1)) 0 (succ ∘ c.emb m)) a = succ (c.emb m b) have : a = succ b := by simpa [a, b, succ] using (Nat.sub_eq_iff_eq_add (c.partSize_pos m)).mp rfl simp [this] · simp [hm] disjoint i hi j hj hij := by wlog h : i ≠ k generalizing i j · apply Disjoint.symm (this j (mem_univ j) i (mem_univ i) hij.symm ?_) simp only [ne_eq, Decidable.not_not] at h simpa [h] using hij.symm rcases eq_or_ne j k with rfl | hj · simp only [onFun, ↓reduceDIte] suffices ∀ (a' : Fin (c.partSize i)) (b' : Fin (c.partSize j + 1)), succ (c.emb i a') ≠ cases (motive := fun _ ↦ Fin (n + 1)) 0 (succ ∘ c.emb j) b' by apply Set.disjoint_iff_forall_ne.2 simp only [hij, ↓reduceDIte, mem_range, comp_apply, ne_eq, forall_exists_index, forall_apply_eq_imp_iff] intro a b apply this intro a' b' induction b' using Fin.induction with | zero => simp | succ b' => simp only [cases_succ, comp_apply, ne_eq, succ_inj] apply c.emb_ne_emb_of_ne hij · simp only [onFun, h, ↓reduceDIte, hj] apply Set.disjoint_iff_forall_ne.2 simp only [mem_range, comp_apply, ne_eq, forall_exists_index, forall_apply_eq_imp_iff, succ_inj] intro a b apply c.emb_ne_emb_of_ne hij cover := by refine Fin.cases ?_ (fun i ↦ ?_) · simp only [mem_range] exact ⟨k, ⟨0, by simp⟩, by simp⟩ · simp only [mem_range] rcases eq_or_ne (c.index i) k with rfl | hi · have A : update c.partSize (c.index i) (c.partSize (c.index i) + 1) (c.index i) = c.partSize (c.index i) + 1 := by simp exact ⟨c.index i, (succ (c.invEmbedding i)).cast A.symm , by simp⟩ · have A : update c.partSize k (c.partSize k + 1) (c.index i) = c.partSize (c.index i) := by simp [hi] exact ⟨c.index i, (c.invEmbedding i).cast A.symm, by simp [hi]⟩ lemma index_extendMiddle_zero (c : OrderedFinpartition n) (i : Fin c.length) : (c.extendMiddle i).index 0 = i := by have : (c.extendMiddle i).emb i 0 = 0 := by simp [extendMiddle] conv_rhs at this => rw [← (c.extendMiddle i).emb_invEmbedding 0] contrapose! this exact (c.extendMiddle i).emb_ne_emb_of_ne (Ne.symm this) lemma range_emb_extendMiddle_ne_singleton_zero (c : OrderedFinpartition n) (i j : Fin c.length) : range ((c.extendMiddle i).emb j) ≠ {0} := by intro h rcases eq_or_ne j i with rfl | hij · have : Fin.succ (c.emb j 0) ∈ ({0} : Set (Fin n.succ)) := by rw [← h] simp only [Nat.succ_eq_add_one, mem_range] have A : (c.extendMiddle j).partSize j = c.partSize j + 1 := by simp [extendMiddle] refine ⟨Fin.cast A.symm (succ 0), ?_⟩ simp only [extendMiddle, ↓reduceDIte, comp_apply, cast_trans, cast_eq_self, cases_succ] simp only [mem_singleton_iff] at this exact Fin.succ_ne_zero _ this · have : (c.extendMiddle i).emb j 0 ∈ range ((c.extendMiddle i).emb j) := mem_range_self 0 rw [h] at this simp only [extendMiddle, hij, ↓reduceDIte, comp_apply, cast_zero, mem_singleton_iff] at this exact Fin.succ_ne_zero _ this /-- Extend an ordered partition of `n` entries, by adding singleton to the left or appending it to one of the existing part. -/ def extend (c : OrderedFinpartition n) (i : Option (Fin c.length)) : OrderedFinpartition (n + 1) := match i with | none => c.extendLeft | some i => c.extendMiddle i @[simp] lemma extend_none (c : OrderedFinpartition n) : c.extend none = c.extendLeft := rfl @[simp] lemma extend_some (c : OrderedFinpartition n) (i : Fin c.length) : c.extend i = c.extendMiddle i := rfl /-- Given an ordered finpartition of `n+1`, with a leftmost atom equal to `{0}`, remove this atom to form an ordered finpartition of `n`. -/ def eraseLeft (c : OrderedFinpartition (n + 1)) (hc : range (c.emb 0) = {0}) : OrderedFinpartition n where length := c.length - 1 partSize := by have : c.length - 1 + 1 = c.length := Nat.sub_add_cancel (c.length_pos (Nat.zero_lt_succ n)) exact fun i ↦ c.partSize (Fin.cast this (succ i)) partSize_pos i := c.partSize_pos _ emb i j := by have : c.length - 1 + 1 = c.length := Nat.sub_add_cancel (c.length_pos (Nat.zero_lt_succ n)) refine Fin.pred (c.emb (Fin.cast this (succ i)) j) ?_ have := c.disjoint (mem_univ (Fin.cast this (succ i))) (mem_univ 0) (ne_of_beq_false rfl) exact Set.disjoint_iff_forall_ne.1 this (by simp) (by simp only [mem_singleton_iff, hc]) emb_strictMono i a b hab := by simp only [pred_lt_pred_iff, Nat.succ_eq_add_one] apply c.emb_strictMono _ hab parts_strictMono := by intro i j hij simp only [pred_lt_pred_iff, Nat.succ_eq_add_one] apply c.parts_strictMono (cast_strictMono _ (strictMono_succ hij)) disjoint i _ j _ hij := by apply Set.disjoint_iff_forall_ne.2 simp only [mem_range, ne_eq, forall_exists_index, forall_apply_eq_imp_iff, pred_inj] intro a b exact c.emb_ne_emb_of_ne ((cast_injective _).ne (by simpa using hij)) cover x := by simp only [mem_range] obtain ⟨i, j, hij⟩ : ∃ (i : Fin c.length), ∃ (j : Fin (c.partSize i)), c.emb i j = succ x := ⟨c.index (succ x), c.invEmbedding (succ x), by simp⟩ have A : c.length = c.length - 1 + 1 := (Nat.sub_add_cancel (c.length_pos (Nat.zero_lt_succ n))).symm have i_ne : i ≠ 0 := by intro h have : succ x ∈ range (c.emb i) := by rw [← hij]; apply mem_range_self rw [h, hc, mem_singleton_iff] at this exact Fin.succ_ne_zero _ this refine ⟨pred (Fin.cast A i) (by simpa using i_ne), Fin.cast (by simp) j, ?_⟩ have : x = pred (succ x) (succ_ne_zero x) := rfl rw [this] congr rw [← hij] congr 1 · simp · simp [Fin.heq_ext_iff] /-- Given an ordered finpartition of `n+1`, with a leftmost atom different from `{0}`, remove `{0}` from the atom that contains it, to form an ordered finpartition of `n`. -/ def eraseMiddle (c : OrderedFinpartition (n + 1)) (hc : range (c.emb 0) ≠ {0}) : OrderedFinpartition n where length := c.length partSize := update c.partSize (c.index 0) (c.partSize (c.index 0) - 1) partSize_pos i := by rcases eq_or_ne i (c.index 0) with rfl | hi · simpa using c.one_lt_partSize_index_zero hc · simp only [ne_eq, hi, not_false_eq_true, update_of_ne] exact c.partSize_pos i emb i j := by by_cases h : i = c.index 0 · refine Fin.pred (c.emb i (Fin.cast ?_ (succ j))) ?_ · rw [h] simpa using Nat.sub_add_cancel (c.partSize_pos (c.index 0)) · have : 0 ≤ c.emb i 0 := Fin.zero_le _ exact (this.trans_lt (c.emb_strictMono _ (succ_pos _))).ne' · refine Fin.pred (c.emb i (Fin.cast ?_ j)) ?_ · simp [h] · conv_rhs => rw [← c.emb_invEmbedding 0] exact c.emb_ne_emb_of_ne h emb_strictMono i a b hab := by rcases eq_or_ne i (c.index 0) with rfl | hi · simp only [↓reduceDIte, Nat.succ_eq_add_one, pred_lt_pred_iff] exact (c.emb_strictMono _).comp (cast_strictMono _) (by simpa using hab) · simp only [hi, ↓reduceDIte, pred_lt_pred_iff, Nat.succ_eq_add_one] exact (c.emb_strictMono _).comp (cast_strictMono _) hab parts_strictMono i j hij := by simp only [Fin.lt_iff_val_lt_val] rw [← Nat.add_lt_add_iff_right (k := 1)] convert Fin.lt_iff_val_lt_val.1 (c.parts_strictMono hij) · rcases eq_or_ne i (c.index 0) with rfl | hi · simp only [↓reduceDIte, update_self, succ_mk, cast_mk, coe_pred] have A := c.one_lt_partSize_index_zero hc rw [Nat.sub_add_cancel] · congr; omega · rw [Order.one_le_iff_pos] conv_lhs => rw [show (0 : ℕ) = c.emb (c.index 0) 0 by simp [emb_zero]] rw [← lt_iff_val_lt_val] apply c.emb_strictMono simp [lt_iff_val_lt_val] · simp only [hi, ↓reduceDIte, ne_eq, not_false_eq_true, update_of_ne, cast_mk, coe_pred] apply Nat.sub_add_cancel have : c.emb i ⟨c.partSize i - 1, Nat.sub_one_lt_of_lt (c.partSize_pos i)⟩ ≠ c.emb (c.index 0) 0 := c.emb_ne_emb_of_ne hi simp only [c.emb_zero, ne_eq, ← val_eq_val, val_zero] at this omega · rcases eq_or_ne j (c.index 0) with rfl | hj · simp only [↓reduceDIte, update_self, succ_mk, cast_mk, coe_pred] have A := c.one_lt_partSize_index_zero hc rw [Nat.sub_add_cancel] · congr; omega · rw [Order.one_le_iff_pos] conv_lhs => rw [show (0 : ℕ) = c.emb (c.index 0) 0 by simp [emb_zero]] rw [← lt_iff_val_lt_val] apply c.emb_strictMono simp [lt_iff_val_lt_val] · simp only [hj, ↓reduceDIte, ne_eq, not_false_eq_true, update_of_ne, cast_mk, coe_pred] apply Nat.sub_add_cancel have : c.emb j ⟨c.partSize j - 1, Nat.sub_one_lt_of_lt (c.partSize_pos j)⟩ ≠ c.emb (c.index 0) 0 := c.emb_ne_emb_of_ne hj simp only [c.emb_zero, ne_eq, ← val_eq_val, val_zero] at this omega disjoint i _ j _ hij := by wlog h : i ≠ c.index 0 generalizing i j · apply Disjoint.symm (this j (mem_univ j) i (mem_univ i) hij.symm ?_) simp only [ne_eq, Decidable.not_not] at h simpa [h] using hij.symm rcases eq_or_ne j (c.index 0) with rfl | hj · simp only [onFun, hij, ↓reduceDIte] apply Set.disjoint_iff_forall_ne.2 simp only [mem_range, ne_eq, forall_exists_index, forall_apply_eq_imp_iff, pred_inj] intro a b exact c.emb_ne_emb_of_ne hij · simp only [onFun, h, ↓reduceDIte, hj] apply Set.disjoint_iff_forall_ne.2 simp only [mem_range, ne_eq, forall_exists_index, forall_apply_eq_imp_iff, pred_inj] intro a b exact c.emb_ne_emb_of_ne hij cover x := by simp only [mem_range] obtain ⟨i, j, hij⟩ : ∃ (i : Fin c.length), ∃ (j : Fin (c.partSize i)), c.emb i j = succ x := ⟨c.index (succ x), c.invEmbedding (succ x), by simp⟩ rcases eq_or_ne i (c.index 0) with rfl | hi · refine ⟨c.index 0, ?_⟩ have j_ne : j ≠ 0 := by rintro rfl simp only [c.emb_zero] at hij exact (Fin.succ_ne_zero _).symm hij have je_ne' : (j : ℕ) ≠ 0 := by simpa simp only [↓reduceDIte] have A : c.partSize (c.index 0) - 1 + 1 = c.partSize (c.index 0) := Nat.sub_add_cancel (c.partSize_pos _) have B : update c.partSize (c.index 0) (c.partSize (c.index 0) - 1) (c.index 0) = c.partSize (c.index 0) - 1 := by simp refine ⟨Fin.cast B.symm (pred (Fin.cast A.symm j) ?_), ?_⟩ · simpa using j_ne · have : x = pred (succ x) (succ_ne_zero x) := rfl rw [this] simp only [pred_inj, ← hij] congr 1 rw [← val_eq_val] simp only [coe_cast, val_succ, coe_pred] omega · have A : update c.partSize (c.index 0) (c.partSize (c.index 0) - 1) i = c.partSize i := by simp [hi] exact ⟨i, Fin.cast A.symm j, by simp [hi, hij]⟩ open Classical in /-- Extending the ordered partitions of `Fin n` bijects with the ordered partitions of `Fin (n+1)`. -/ @[simps apply] def extendEquiv (n : ℕ) : ((c : OrderedFinpartition n) × Option (Fin c.length)) ≃ OrderedFinpartition (n + 1) where toFun c := c.1.extend c.2 invFun c := if h : range (c.emb 0) = {0} then ⟨c.eraseLeft h, none⟩ else ⟨c.eraseMiddle h, some (c.index 0)⟩ left_inv := by rintro ⟨c, o⟩ match o with | none => simp only [extend, range_extendLeft_zero, ↓reduceDIte, Sigma.mk.inj_iff, heq_eq_eq, and_true] rfl | some i => simp only [extend, range_emb_extendMiddle_ne_singleton_zero, ↓reduceDIte, Sigma.mk.inj_iff, heq_eq_eq, and_true, eraseMiddle, index_extendMiddle_zero] ext · rfl · simp only [heq_eq_eq, index_extendMiddle_zero] ext j rcases eq_or_ne i j with rfl | hij · simp [extendMiddle] · simp [hij.symm, extendMiddle] · refine HEq.symm (hfunext rfl ?_) simp only [heq_eq_eq, forall_eq'] intro a rcases eq_or_ne a i with rfl | hij · refine (Fin.heq_fun_iff ?_).mpr ?_ · rw [index_extendMiddle_zero] simp [extendMiddle] · simp [extendMiddle] · refine (Fin.heq_fun_iff ?_).mpr ?_ · rw [index_extendMiddle_zero] simp [extendMiddle] · simp [extendMiddle, hij] right_inv c := by by_cases h : range (c.emb 0) = {0} · have A : c.length - 1 + 1 = c.length := Nat.sub_add_cancel (c.length_pos (Nat.zero_lt_succ n)) dsimp only rw [dif_pos h] simp only [extend, extendLeft, eraseLeft] ext · exact A · refine (Fin.heq_fun_iff A).mpr (fun i ↦ ?_) simp induction i using Fin.induction with | zero => change 1 = c.partSize 0; simp [c.partSize_eq_one_of_range_emb_eq_singleton h] | succ i => simp only [cons_succ, val_succ]; rfl · refine hfunext (congrArg Fin A) ?_ simp only intro i i' h' have : i' = Fin.cast A i := eq_of_val_eq (by apply val_eq_val_of_heq h'.symm) subst this refine (Fin.heq_fun_iff ?_).mpr ?_ · induction i using Fin.induction with | zero => simp [c.partSize_eq_one_of_range_emb_eq_singleton h] | succ i => simp · intro j induction i using Fin.induction with | zero => simp only [cases_zero, cast_zero, val_eq_zero] exact (apply_eq_of_range_eq_singleton h _).symm | succ i => simp · dsimp only rw [dif_neg h] have B : c.partSize (c.index 0) - 1 + 1 = c.partSize (c.index 0) := Nat.sub_add_cancel (c.partSize_pos (c.index 0)) simp only [extend, extendMiddle, eraseMiddle, ↓reduceDIte] ext · rfl · simp only [update_self, update_idem, heq_eq_eq, update_eq_self_iff, B] · refine hfunext rfl ?_ simp only [heq_eq_eq, forall_eq'] intro i refine ((Fin.heq_fun_iff ?_).mpr ?_).symm · simp only [update_self, B, update_idem, update_eq_self] · intro j rcases eq_or_ne i (c.index 0) with rfl | hi · simp only [↓reduceDIte, comp_apply] rcases eq_or_ne j 0 with rfl | hj · simpa using c.emb_zero · let j' := Fin.pred (j.cast B.symm) (by simpa using hj) have : j = (succ j').cast B := by simp [j'] simp only [this, coe_cast, val_succ, cast_mk, cases_succ', comp_apply, succ_mk, succ_pred] rfl · simp [hi] /-! ### Applying ordered finpartitions to multilinear maps -/ /-- Given a formal multilinear series `p`, an ordered partition `c` of `n` and the index `i` of a block of `c`, we may define a function on `Fin n → E` by picking the variables in the `i`-th block of `n`, and applying the corresponding coefficient of `p` to these variables. This function is called `p.applyOrderedFinpartition c v i` for `v : Fin n → E` and `i : Fin c.k`. -/ def applyOrderedFinpartition (p : ∀ (i : Fin c.length), E [×c.partSize i]→L[𝕜] F) : (Fin n → E) → Fin c.length → F := fun v m ↦ p m (v ∘ c.emb m) lemma applyOrderedFinpartition_apply (p : ∀ (i : Fin c.length), E [×c.partSize i]→L[𝕜] F) (v : Fin n → E) : c.applyOrderedFinpartition p v = (fun m ↦ p m (v ∘ c.emb m)) := rfl theorem norm_applyOrderedFinpartition_le (p : ∀ (i : Fin c.length), E [×c.partSize i]→L[𝕜] F) (v : Fin n → E) (m : Fin c.length) : ‖c.applyOrderedFinpartition p v m‖ ≤ ‖p m‖ * ∏ i : Fin (c.partSize m), ‖v (c.emb m i)‖ := (p m).le_opNorm _ /-- Technical lemma stating how `c.applyOrderedFinpartition` commutes with updating variables. This will be the key point to show that functions constructed from `applyOrderedFinpartition` retain multilinearity. -/ theorem applyOrderedFinpartition_update_right (p : ∀ (i : Fin c.length), E [×c.partSize i]→L[𝕜] F) (j : Fin n) (v : Fin n → E) (z : E) : c.applyOrderedFinpartition p (update v j z) = update (c.applyOrderedFinpartition p v) (c.index j) (p (c.index j) (Function.update (v ∘ c.emb (c.index j)) (c.invEmbedding j) z)) := by ext m by_cases h : m = c.index j · rw [h] simp only [applyOrderedFinpartition, update_self] congr rw [← Function.update_comp_eq_of_injective] · simp · exact (c.emb_strictMono (c.index j)).injective · simp only [applyOrderedFinpartition, ne_eq, h, not_false_eq_true, update_of_ne] congr 1 apply Function.update_comp_eq_of_notMem_range have A : Disjoint (range (c.emb m)) (range (c.emb (c.index j))) := c.disjoint (mem_univ m) (mem_univ (c.index j)) h have : j ∈ range (c.emb (c.index j)) := mem_range.2 ⟨c.invEmbedding j, by simp⟩ exact Set.disjoint_right.1 A this theorem applyOrderedFinpartition_update_left (p : ∀ (i : Fin c.length), E [×c.partSize i]→L[𝕜] F) (m : Fin c.length) (v : Fin n → E) (q : E [×c.partSize m]→L[𝕜] F) : c.applyOrderedFinpartition (update p m q) v = update (c.applyOrderedFinpartition p v) m (q (v ∘ c.emb m)) := by ext d by_cases h : d = m · rw [h] simp [applyOrderedFinpartition] · simp [h, applyOrderedFinpartition] /-- Given a an ordered finite partition `c` of `n`, a continuous multilinear map `f` in `c.length` variables, and for each `m` a continuous multilinear map `p m` in `c.partSize m` variables, one can form a continuous multilinear map in `n` variables by applying `p m` to each part of the partition, and then applying `f` to the resulting vector. It is called `c.compAlongOrderedFinpartition f p`. -/ def compAlongOrderedFinpartition (f : F [×c.length]→L[𝕜] G) (p : ∀ i, E [×c.partSize i]→L[𝕜] F) : E[×n]→L[𝕜] G where toMultilinearMap := MultilinearMap.mk' (fun v ↦ f (c.applyOrderedFinpartition p v)) (fun v i x y ↦ by simp only [applyOrderedFinpartition_update_right, ContinuousMultilinearMap.map_update_add]) (fun v i c x ↦ by simp only [applyOrderedFinpartition_update_right, ContinuousMultilinearMap.map_update_smul]) cont := by apply f.cont.comp change Continuous (fun v m ↦ p m (v ∘ c.emb m)) fun_prop @[simp] lemma compAlongOrderFinpartition_apply (f : F [×c.length]→L[𝕜] G) (p : ∀ i, E [×c.partSize i]→L[𝕜] F) (v : Fin n → E) : c.compAlongOrderedFinpartition f p v = f (c.applyOrderedFinpartition p v) := rfl theorem norm_compAlongOrderedFinpartition_le (f : F [×c.length]→L[𝕜] G) (p : ∀ i, E [×c.partSize i]→L[𝕜] F) : ‖c.compAlongOrderedFinpartition f p‖ ≤ ‖f‖ * ∏ i, ‖p i‖ := by refine ContinuousMultilinearMap.opNorm_le_bound (by positivity) fun v ↦ ?_ rw [compAlongOrderFinpartition_apply, mul_assoc, ← c.prod_sigma_eq_prod, ← Finset.prod_mul_distrib] exact f.le_opNorm_mul_prod_of_le <| c.norm_applyOrderedFinpartition_le _ _ /-- Bundled version of `compAlongOrderedFinpartition`, depending linearly on `f` and multilinearly on `p`. -/ @[simps! apply_apply] def compAlongOrderedFinpartitionₗ : (F [×c.length]→L[𝕜] G) →ₗ[𝕜] MultilinearMap 𝕜 (fun i : Fin c.length ↦ E[×c.partSize i]→L[𝕜] F) (E[×n]→L[𝕜] G) where toFun f := MultilinearMap.mk' (fun p ↦ c.compAlongOrderedFinpartition f p) (fun p m q q' ↦ by ext v simp [applyOrderedFinpartition_update_left]) (fun p m a q ↦ by ext v simp [applyOrderedFinpartition_update_left]) map_add' _ _ := rfl map_smul' _ _ := rfl variable (𝕜 E F G) in /-- Bundled version of `compAlongOrderedFinpartition`, depending continuously linearly on `f` and continuously multilinearly on `p`. -/ noncomputable def compAlongOrderedFinpartitionL : (F [×c.length]→L[𝕜] G) →L[𝕜] ContinuousMultilinearMap 𝕜 (fun i ↦ E[×c.partSize i]→L[𝕜] F) (E[×n]→L[𝕜] G) := by refine MultilinearMap.mkContinuousLinear c.compAlongOrderedFinpartitionₗ 1 fun f p ↦ ?_ simp only [one_mul, compAlongOrderedFinpartitionₗ_apply_apply] apply norm_compAlongOrderedFinpartition_le @[simp] lemma compAlongOrderedFinpartitionL_apply (f : F [×c.length]→L[𝕜] G) (p : ∀ (i : Fin c.length), E [×c.partSize i]→L[𝕜] F) : c.compAlongOrderedFinpartitionL 𝕜 E F G f p = c.compAlongOrderedFinpartition f p := rfl theorem norm_compAlongOrderedFinpartitionL_le : ‖c.compAlongOrderedFinpartitionL 𝕜 E F G‖ ≤ 1 := MultilinearMap.mkContinuousLinear_norm_le _ zero_le_one _ end OrderedFinpartition /-! ### The Faa di Bruno formula -/ namespace FormalMultilinearSeries /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.compAlongComposition p c`. -/ def compAlongOrderedFinpartition {n : ℕ} (q : FormalMultilinearSeries 𝕜 F G) (p : FormalMultilinearSeries 𝕜 E F) (c : OrderedFinpartition n) : E [×n]→L[𝕜] G := c.compAlongOrderedFinpartition (q c.length) (fun m ↦ p (c.partSize m)) @[simp] theorem compAlongOrderedFinpartition_apply {n : ℕ} (q : FormalMultilinearSeries 𝕜 F G) (p : FormalMultilinearSeries 𝕜 E F) (c : OrderedFinpartition n) (v : Fin n → E) : (q.compAlongOrderedFinpartition p c) v = q c.length (c.applyOrderedFinpartition (fun m ↦ (p (c.partSize m))) v) := rfl /-- Taylor formal composition of two formal multilinear series. The `n`-th coefficient in the composition is defined to be the sum of `q.compAlongOrderedFinpartition p c` over all ordered partitions of `n`. In other words, this term (as a multilinear function applied to `v₀, ..., vₙ₋₁`) is `∑'_{k} ∑'_{I₀ ⊔ ... ⊔ Iₖ₋₁ = {0, ..., n-1}} qₖ (p_{i₀} (...), ..., p_{iₖ₋₁} (...))`, where `iₘ` is the size of `Iₘ` and one puts all variables of `Iₘ` as arguments to `p_{iₘ}`, in increasing order. The sets `I₀, ..., Iₖ₋₁` are ordered so that `max I₀ < max I₁ < ... < max Iₖ₋₁`. This definition is chosen so that the `n`-th derivative of `g ∘ f` is the Taylor composition of the iterated derivatives of `g` and of `f`. Not to be confused with another notion of composition for formal multilinear series, called just `FormalMultilinearSeries.comp`, appearing in the composition of analytic functions. -/ protected noncomputable def taylorComp (q : FormalMultilinearSeries 𝕜 F G) (p : FormalMultilinearSeries 𝕜 E F) : FormalMultilinearSeries 𝕜 E G := fun n ↦ ∑ c : OrderedFinpartition n, q.compAlongOrderedFinpartition p c end FormalMultilinearSeries theorem analyticOn_taylorComp (hq : ∀ (n : ℕ), AnalyticOn 𝕜 (fun x ↦ q x n) t) (hp : ∀ n, AnalyticOn 𝕜 (fun x ↦ p x n) s) {f : E → F} (hf : AnalyticOn 𝕜 f s) (h : MapsTo f s t) (n : ℕ) : AnalyticOn 𝕜 (fun x ↦ (q (f x)).taylorComp (p x) n) s := by apply Finset.analyticOn_fun_sum _ (fun c _ ↦ ?_) let B := c.compAlongOrderedFinpartitionL 𝕜 E F G change AnalyticOn 𝕜 ((fun p ↦ B p.1 p.2) ∘ (fun x ↦ (q (f x) c.length, fun m ↦ p x (c.partSize m)))) s apply B.analyticOnNhd_uncurry_of_multilinear.comp_analyticOn ?_ (mapsTo_univ _ _) apply AnalyticOn.prod · exact (hq c.length).comp hf h · exact AnalyticOn.pi (fun i ↦ hp _) open OrderedFinpartition /-- Composing two formal multilinear series `q` and `p` along an ordered partition extended by a new atom to the left corresponds to applying `p 1` on the first coordinates, and the initial ordered partition on the other coordinates. This is one of the terms that appears when differentiating in the Faa di Bruno formula, going from step `m` to step `m + 1`. -/ private lemma faaDiBruno_aux1 {m : ℕ} (q : FormalMultilinearSeries 𝕜 F G) (p : FormalMultilinearSeries 𝕜 E F) (c : OrderedFinpartition m) : (q.compAlongOrderedFinpartition p (c.extend none)).curryLeft = ((c.compAlongOrderedFinpartitionL 𝕜 E F G).flipMultilinear fun i ↦ p (c.partSize i)).comp ((q (c.length + 1)).curryLeft.comp ((continuousMultilinearCurryFin1 𝕜 E F) (p 1))) := by ext e v simp only [Nat.succ_eq_add_one, OrderedFinpartition.extend, extendLeft, ContinuousMultilinearMap.curryLeft_apply, FormalMultilinearSeries.compAlongOrderedFinpartition_apply, applyOrderedFinpartition_apply, ContinuousLinearMap.coe_comp', comp_apply, continuousMultilinearCurryFin1_apply, Matrix.zero_empty, ContinuousLinearMap.flipMultilinear_apply_apply, compAlongOrderedFinpartitionL_apply, compAlongOrderFinpartition_apply] congr ext j exact Fin.cases rfl (fun i ↦ rfl) j /-- Composing a formal multilinear series with an ordered partition extended by adding a left point to an already existing atom of index `i` corresponds to updating the `i`th block, using `p (c.partSize i + 1)` instead of `p (c.partSize i)` there. This is one of the terms that appears when differentiating in the Faa di Bruno formula, going from step `m` to step `m + 1`. -/ private lemma faaDiBruno_aux2 {m : ℕ} (q : FormalMultilinearSeries 𝕜 F G) (p : FormalMultilinearSeries 𝕜 E F) (c : OrderedFinpartition m) (i : Fin c.length) : (q.compAlongOrderedFinpartition p (c.extend (some i))).curryLeft = ((c.compAlongOrderedFinpartitionL 𝕜 E F G (q c.length)).toContinuousLinearMap (fun i ↦ p (c.partSize i)) i).comp (p (c.partSize i + 1)).curryLeft := by ext e v simp? [OrderedFinpartition.extend, extendMiddle, applyOrderedFinpartition_apply] says simp only [Nat.succ_eq_add_one, OrderedFinpartition.extend, extendMiddle, ContinuousMultilinearMap.curryLeft_apply, FormalMultilinearSeries.compAlongOrderedFinpartition_apply, applyOrderedFinpartition_apply, ContinuousLinearMap.coe_comp', comp_apply, ContinuousMultilinearMap.toContinuousLinearMap_apply, compAlongOrderedFinpartitionL_apply, compAlongOrderFinpartition_apply] congr ext j rcases eq_or_ne j i with rfl | hij · simp only [↓reduceDIte, update_self, ContinuousMultilinearMap.curryLeft_apply, Nat.succ_eq_add_one] apply FormalMultilinearSeries.congr _ (by simp) intro a ha h'a match a with | 0 => simp | a + 1 => simp [cons] · simp only [hij, ↓reduceDIte, ne_eq, not_false_eq_true, update_of_ne] apply FormalMultilinearSeries.congr _ (by simp [hij]) simp /-- *Faa di Bruno* formula: If two functions `g` and `f` have Taylor series up to `n` given by `q` and `p`, then `g ∘ f` also has a Taylor series, given by `q.taylorComp p`. -/ theorem HasFTaylorSeriesUpToOn.comp {n : WithTop ℕ∞} {g : F → G} {f : E → F} (hg : HasFTaylorSeriesUpToOn n g q t) (hf : HasFTaylorSeriesUpToOn n f p s) (h : MapsTo f s t) : HasFTaylorSeriesUpToOn n (g ∘ f) (fun x ↦ (q (f x)).taylorComp (p x)) s := by /- One has to check that the `m+1`-th term is the derivative of the `m`-th term. The `m`-th term is a sum, that one can differentiate term by term. Each term is a linear map into continuous multilinear maps, applied to parts of `p` and `q`. One knows how to differentiate such a map, thanks to `HasFDerivWithinAt.linear_multilinear_comp`. The terms that show up are matched, using `faaDiBruno_aux1` and `faaDiBruno_aux2`, with terms of the same form at order `m+1`. Then, one needs to check that one gets each term once and exactly once, which is given by the bijection `OrderedFinpartition.extendEquiv m`. -/ classical constructor · intro x hx simp [FormalMultilinearSeries.taylorComp, default, HasFTaylorSeriesUpToOn.zero_eq' hg (h hx)] · intro m hm x hx have A (c : OrderedFinpartition m) : HasFDerivWithinAt (fun x ↦ (q (f x)).compAlongOrderedFinpartition (p x) c) (∑ i : Option (Fin c.length), ((q (f x)).compAlongOrderedFinpartition (p x) (c.extend i)).curryLeft) s x := by let B := c.compAlongOrderedFinpartitionL 𝕜 E F G change HasFDerivWithinAt (fun y ↦ B (q (f y) c.length) (fun i ↦ p y (c.partSize i))) (∑ i : Option (Fin c.length), ((q (f x)).compAlongOrderedFinpartition (p x) (c.extend i)).curryLeft) s x have cm : (c.length : WithTop ℕ∞) ≤ m := mod_cast OrderedFinpartition.length_le c have cp i : (c.partSize i : WithTop ℕ∞) ≤ m := by exact_mod_cast OrderedFinpartition.partSize_le c i have I i : HasFDerivWithinAt (fun x ↦ p x (c.partSize i)) (p x (c.partSize i).succ).curryLeft s x := hf.fderivWithin (c.partSize i) ((cp i).trans_lt hm) x hx have J : HasFDerivWithinAt (fun x ↦ q x c.length) (q (f x) c.length.succ).curryLeft t (f x) := hg.fderivWithin c.length (cm.trans_lt hm) (f x) (h hx) have K : HasFDerivWithinAt f ((continuousMultilinearCurryFin1 𝕜 E F) (p x 1)) s x := hf.hasFDerivWithinAt (le_trans (mod_cast Nat.le_add_left 1 m) (ENat.add_one_natCast_le_withTop_of_lt hm)) hx convert HasFDerivWithinAt.linear_multilinear_comp (J.comp x K h) I B simp only [B, Nat.succ_eq_add_one, Fintype.sum_option, comp_apply, faaDiBruno_aux1, faaDiBruno_aux2] have B : HasFDerivWithinAt (fun x ↦ (q (f x)).taylorComp (p x) m) (∑ c : OrderedFinpartition m, ∑ i : Option (Fin c.length), ((q (f x)).compAlongOrderedFinpartition (p x) (c.extend i)).curryLeft) s x := HasFDerivWithinAt.fun_sum (fun c _ ↦ A c) suffices ∑ c : OrderedFinpartition m, ∑ i : Option (Fin c.length), ((q (f x)).compAlongOrderedFinpartition (p x) (c.extend i)) = (q (f x)).taylorComp (p x) (m + 1) by rw [← this] convert B ext v simp only [Nat.succ_eq_add_one, Fintype.sum_option, ContinuousMultilinearMap.curryLeft_apply, ContinuousMultilinearMap.sum_apply, ContinuousMultilinearMap.add_apply, FormalMultilinearSeries.compAlongOrderedFinpartition_apply, ContinuousLinearMap.coe_sum', Finset.sum_apply, ContinuousLinearMap.add_apply] rw [Finset.sum_sigma'] exact Fintype.sum_equiv (OrderedFinpartition.extendEquiv m) _ _ (fun p ↦ rfl) · intro m hm apply continuousOn_finset_sum _ (fun c _ ↦ ?_) let B := c.compAlongOrderedFinpartitionL 𝕜 E F G change ContinuousOn ((fun p ↦ B p.1 p.2) ∘ (fun x ↦ (q (f x) c.length, fun i ↦ p x (c.partSize i)))) s apply B.continuous_uncurry_of_multilinear.comp_continuousOn (ContinuousOn.prodMk ?_ ?_) · have : (c.length : WithTop ℕ∞) ≤ m := mod_cast OrderedFinpartition.length_le c exact (hg.cont c.length (this.trans hm)).comp hf.continuousOn h · apply continuousOn_pi.2 (fun i ↦ ?_) have : (c.partSize i : WithTop ℕ∞) ≤ m := by exact_mod_cast OrderedFinpartition.partSize_le c i exact hf.cont _ (this.trans hm)
SumsOfSquares.lean
/- Copyright (c) 2024 Florent Schaffhauser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Florent Schaffhauser, Artie Khovanov -/ import Mathlib.Algebra.Group.Subgroup.Even import Mathlib.Algebra.Order.Ring.Basic import Mathlib.Algebra.Ring.Parity -- Algebra.Group.Even can't prove `IsSquare 0` by simp import Mathlib.Algebra.Ring.Subsemiring.Basic import Mathlib.Tactic.ApplyFun /-! # Sums of squares We introduce a predicate for sums of squares in a ring. ## Main declarations - `IsSumSq : R → Prop`: for a type `R` with addition, multiplication and a zero, an inductive predicate defining the property of being a sum of squares in `R`. `0 : R` is a sum of squares and if `S` is a sum of squares, then, for all `a : R`, `a * a + s` is a sum of squares. - `AddMonoid.sumSq R` and `Subsemiring.sumSq R`: respectively the submonoid or subsemiring of sums of squares in an additive monoid or semiring `R` with multiplication. -/ variable {R : Type*} /-- The property of being a sum of squares is defined inductively by: `0 : R` is a sum of squares and if `s : R` is a sum of squares, then for all `a : R`, `a * a + s` is a sum of squares in `R`. -/ @[mk_iff] inductive IsSumSq [Mul R] [Add R] [Zero R] : R → Prop | zero : IsSumSq 0 | sq_add (a : R) {s : R} (hs : IsSumSq s) : IsSumSq (a * a + s) /-- Alternative induction scheme for `IsSumSq` which uses `IsSquare`. -/ theorem IsSumSq.rec' [Mul R] [Add R] [Zero R] {motive : (s : R) → (h : IsSumSq s) → Prop} (zero : motive 0 zero) (sq_add : ∀ {x s}, (hx : IsSquare x) → (hs : IsSumSq s) → motive s hs → motive (x + s) (by rcases hx with ⟨_, rfl⟩; exact sq_add _ hs)) {s : R} (h : IsSumSq s) : motive s h := match h with | .zero => zero | .sq_add _ hs => sq_add (.mul_self _) hs (rec' zero sq_add _) /-- In an additive monoid with multiplication, if `s₁` and `s₂` are sums of squares, then `s₁ + s₂` is a sum of squares. -/ @[aesop unsafe 90% apply] theorem IsSumSq.add [AddMonoid R] [Mul R] {s₁ s₂ : R} (h₁ : IsSumSq s₁) (h₂ : IsSumSq s₂) : IsSumSq (s₁ + s₂) := by induction h₁ <;> simp_all [add_assoc, sq_add] namespace AddSubmonoid variable {T : Type*} [AddMonoid T] [Mul T] {s : T} variable (T) in /-- In an additive monoid with multiplication `R`, `AddSubmonoid.sumSq R` is the submonoid of sums of squares in `R`. -/ @[simps] def sumSq [AddMonoid T] : AddSubmonoid T where carrier := {s : T | IsSumSq s} zero_mem' := .zero add_mem' := .add attribute [norm_cast] coe_sumSq @[simp] theorem mem_sumSq : s ∈ sumSq T ↔ IsSumSq s := Iff.rfl end AddSubmonoid /-- In an additive unital magma with multiplication, `x * x` is a sum of squares for all `x`. -/ @[simp] theorem IsSumSq.mul_self [AddZeroClass R] [Mul R] (a : R) : IsSumSq (a * a) := by simpa using sq_add a zero /-- In an additive unital magma with multiplication, squares are sums of squares (see Mathlib.Algebra.Group.Even). -/ @[aesop unsafe 80% apply] theorem IsSquare.isSumSq [AddZeroClass R] [Mul R] {x : R} (hx : IsSquare x) : IsSumSq x := by aesop attribute [simp, aesop safe] IsSumSq.zero @[simp, aesop safe] theorem IsSumSq.one [AddZeroClass R] [MulOneClass R] : IsSumSq (1 : R) := by aesop /-- In an additive monoid with multiplication `R`, the submonoid generated by the squares is the set of sums of squares in `R`. -/ @[simp] theorem AddSubmonoid.closure_isSquare [AddMonoid R] [Mul R] : closure {x : R | IsSquare x} = sumSq R := by refine closure_eq_of_le (fun x hx ↦ IsSquare.isSumSq hx) (fun x hx ↦ ?_) induction hx <;> aesop /-- In an additive commutative monoid with multiplication, a finite sum of sums of squares is a sum of squares. -/ @[aesop unsafe 90% apply] theorem IsSumSq.sum [AddCommMonoid R] [Mul R] {ι : Type*} {I : Finset ι} {s : ι → R} (hs : ∀ i ∈ I, IsSumSq <| s i) : IsSumSq (∑ i ∈ I, s i) := by simpa using sum_mem (S := AddSubmonoid.sumSq _) hs /-- In an additive commutative monoid with multiplication, `∑ i ∈ I, x i`, where each `x i` is a square, is a sum of squares. -/ theorem IsSumSq.sum_isSquare [AddCommMonoid R] [Mul R] {ι : Type*} (I : Finset ι) {x : ι → R} (hx : ∀ i ∈ I, IsSquare <| x i) : IsSumSq (∑ i ∈ I, x i) := by aesop /-- In an additive commutative monoid with multiplication, `∑ i ∈ I, a i * a i` is a sum of squares. -/ @[simp↓] theorem IsSumSq.sum_mul_self [AddCommMonoid R] [Mul R] {ι : Type*} (I : Finset ι) (a : ι → R) : IsSumSq (∑ i ∈ I, a i * a i) := by aesop @[simp↓] theorem IsSumSq.sum_sq [CommSemiring R] {ι : Type*} (I : Finset ι) (a : ι → R) : IsSumSq (∑ i ∈ I, a i ^ 2) := by aesop namespace NonUnitalSubsemiring variable {T : Type*} [NonUnitalCommSemiring T] variable (T) in /-- In a commutative (possibly non-unital) semiring `R`, `NonUnitalSubsemiring.sumSq R` is the (possibly non-unital) subsemiring of sums of squares in `R`. -/ def sumSq : NonUnitalSubsemiring T := (Subsemigroup.square T).nonUnitalSubsemiringClosure @[simp] theorem sumSq_toAddSubmonoid : (sumSq T).toAddSubmonoid = .sumSq T := by simp [sumSq, ← AddSubmonoid.closure_isSquare, Subsemigroup.nonUnitalSubsemiringClosure_toAddSubmonoid] @[simp] theorem mem_sumSq {s : T} : s ∈ sumSq T ↔ IsSumSq s := by simp [← NonUnitalSubsemiring.mem_toAddSubmonoid] @[simp, norm_cast] theorem coe_sumSq : sumSq T = {s : T | IsSumSq s} := by ext; simp @[simp] theorem closure_isSquare : closure {x : T | IsSquare x} = sumSq T := by simp [sumSq, Subsemigroup.nonUnitalSubsemiringClosure_eq_closure] end NonUnitalSubsemiring /-- In a commutative (possibly non-unital) semiring, if `s₁` and `s₂` are sums of squares, then `s₁ * s₂` is a sum of squares. -/ @[aesop unsafe 90% apply] theorem IsSumSq.mul [NonUnitalCommSemiring R] {s₁ s₂ : R} (h₁ : IsSumSq s₁) (h₂ : IsSumSq s₂) : IsSumSq (s₁ * s₂) := by simpa using mul_mem (by simpa : _ ∈ NonUnitalSubsemiring.sumSq R) (by simpa) private theorem Submonoid.square_subsemiringClosure {T : Type*} [CommSemiring T] : (Submonoid.square T).subsemiringClosure = .closure {x : T | IsSquare x} := by simp [Submonoid.subsemiringClosure_eq_closure] namespace Subsemiring variable {T : Type*} [CommSemiring T] variable (T) in /-- In a commutative semiring `R`, `Subsemiring.sumSq R` is the subsemiring of sums of squares in `R`. -/ def sumSq : Subsemiring T where __ := NonUnitalSubsemiring.sumSq T one_mem' := by simp @[simp] theorem sumSq_toNonUnitalSubsemiring : (sumSq T).toNonUnitalSubsemiring = .sumSq T := rfl @[simp] theorem mem_sumSq {s : T} : s ∈ sumSq T ↔ IsSumSq s := by simp [← Subsemiring.mem_toNonUnitalSubsemiring] @[simp, norm_cast] theorem coe_sumSq : sumSq T = {s : T | IsSumSq s} := by ext; simp @[simp] theorem closure_isSquare : closure {x : T | IsSquare x} = sumSq T := by apply_fun toNonUnitalSubsemiring using toNonUnitalSubsemiring_injective simp [← Submonoid.square_subsemiringClosure] end Subsemiring /-- In a commutative semiring, a finite product of sums of squares is a sum of squares. -/ @[aesop unsafe 50% apply] theorem IsSumSq.prod [CommSemiring R] {ι : Type*} {I : Finset ι} {x : ι → R} (hx : ∀ i ∈ I, IsSumSq <| x i) : IsSumSq (∏ i ∈ I, x i) := by simpa using prod_mem (S := Subsemiring.sumSq R) (by simpa) /-- In a linearly ordered semiring with the property `a ≤ b → ∃ c, a + c = b` (e.g. `ℕ`), sums of squares are non-negative. -/ theorem IsSumSq.nonneg {R : Type*} [Semiring R] [LinearOrder R] [IsStrictOrderedRing R] [ExistsAddOfLE R] {s : R} (hs : IsSumSq s) : 0 ≤ s := by induction hs using IsSumSq.rec' with | zero => simp | sq_add hx _ h => exact add_nonneg (IsSquare.nonneg hx) h
Limits.lean
/- Copyright (c) 2018 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison, Reid Barton -/ import Mathlib.Logic.UnivLE import Mathlib.CategoryTheory.Limits.HasLimits /-! # Limits in the category of types. We show that the category of types has all limits, by providing the usual concrete models. -/ universe u' v u w namespace CategoryTheory.Limits.Types section limit_characterization variable {J : Type v} [Category.{w} J] {F : J ⥤ Type u} /-- Given a section of a functor F into `Type*`, construct a cone over F with `PUnit` as the cone point. -/ def coneOfSection {s} (hs : s ∈ F.sections) : Cone F where pt := PUnit π := { app := fun j _ ↦ s j, naturality := fun i j f ↦ by ext; exact (hs f).symm } /-- Given a cone over a functor F into `Type*` and an element in the cone point, construct a section of F. -/ def sectionOfCone (c : Cone F) (x : c.pt) : F.sections := ⟨fun j ↦ c.π.app j x, fun f ↦ congr_fun (c.π.naturality f).symm x⟩ theorem isLimit_iff (c : Cone F) : Nonempty (IsLimit c) ↔ ∀ s ∈ F.sections, ∃! x : c.pt, ∀ j, c.π.app j x = s j := by refine ⟨fun ⟨t⟩ s hs ↦ ?_, fun h ↦ ⟨?_⟩⟩ · let cs := coneOfSection hs exact ⟨t.lift cs ⟨⟩, fun j ↦ congr_fun (t.fac cs j) ⟨⟩, fun x hx ↦ congr_fun (t.uniq cs (fun _ ↦ x) fun j ↦ funext fun _ ↦ hx j) ⟨⟩⟩ · choose x hx using fun c y ↦ h _ (sectionOfCone c y).2 exact ⟨x, fun c j ↦ funext fun y ↦ (hx c y).1 j, fun c f hf ↦ funext fun y ↦ (hx c y).2 (f y) (fun j ↦ congr_fun (hf j) y)⟩ theorem isLimit_iff_bijective_sectionOfCone (c : Cone F) : Nonempty (IsLimit c) ↔ (Types.sectionOfCone c).Bijective := by simp_rw [isLimit_iff, Function.bijective_iff_existsUnique, Subtype.forall, F.sections_ext_iff, sectionOfCone] /-- The equivalence between a limiting cone of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ noncomputable def isLimitEquivSections {c : Cone F} (t : IsLimit c) : c.pt ≃ F.sections where toFun := sectionOfCone c invFun s := t.lift (coneOfSection s.2) ⟨⟩ left_inv x := (congr_fun (t.uniq (coneOfSection _) (fun _ ↦ x) fun _ ↦ rfl) ⟨⟩).symm right_inv s := Subtype.ext (funext fun j ↦ congr_fun (t.fac (coneOfSection s.2) j) ⟨⟩) @[simp] theorem isLimitEquivSections_apply {c : Cone F} (t : IsLimit c) (j : J) (x : c.pt) : (isLimitEquivSections t x : ∀ j, F.obj j) j = c.π.app j x := rfl @[simp] theorem isLimitEquivSections_symm_apply {c : Cone F} (t : IsLimit c) (x : F.sections) (j : J) : c.π.app j ((isLimitEquivSections t).symm x) = (x : ∀ j, F.obj j) j := by conv_rhs => rw [← (isLimitEquivSections t).right_inv x] rfl end limit_characterization variable {J : Type v} [Category.{w} J] /-! We now provide two distinct implementations in the category of types. The first, in the `CategoryTheory.Limits.Types.Small` namespace, assumes `Small.{u} J` and constructs `J`-indexed limits in `Type u`. The second, in the `CategoryTheory.Limits.Types.TypeMax` namespace constructs limits for functors `F : J ⥤ Type max v u`, for `J : Type v`. This construction is slightly nicer, as the limit is definitionally just `F.sections`, rather than `Shrink F.sections`, which makes an arbitrary choice of `u`-small representative. Hopefully we might be able to entirely remove the `TypeMax` constructions, but for now they are useful glue for the later parts of the library. -/ namespace Small variable (F : J ⥤ Type u) section variable [Small.{u} F.sections] /-- (internal implementation) the limit cone of a functor, implemented as flat sections of a pi type -/ @[simps] noncomputable def limitCone : Cone F where pt := Shrink F.sections π := { app := fun j u => ((equivShrink F.sections).symm u).val j naturality := fun j j' f => by funext x simp } @[ext] lemma limitCone_pt_ext {x y : (limitCone F).pt} (w : (equivShrink F.sections).symm x = (equivShrink F.sections).symm y) : x = y := by aesop /-- (internal implementation) the fact that the proposed limit cone is the limit -/ @[simps] noncomputable def limitConeIsLimit : IsLimit (limitCone.{v, u} F) where lift s v := equivShrink F.sections { val := fun j => s.π.app j v property := fun f => congr_fun (Cone.w s f) _ } uniq := fun _ _ w => by ext x j simpa using congr_fun (w j) x end end Small theorem hasLimit_iff_small_sections (F : J ⥤ Type u) : HasLimit F ↔ Small.{u} F.sections := ⟨fun _ => .mk ⟨_, ⟨(Equiv.ofBijective _ ((isLimit_iff_bijective_sectionOfCone (limit.cone F)).mp ⟨limit.isLimit _⟩)).symm⟩⟩, fun _ => ⟨_, Small.limitConeIsLimit F⟩⟩ -- TODO: If `UnivLE` works out well, we will eventually want to deprecate these -- definitions, and probably as a first step put them in namespace or otherwise rename them. section TypeMax /-- (internal implementation) the limit cone of a functor, implemented as flat sections of a pi type -/ @[simps] noncomputable def limitCone (F : J ⥤ Type max v u) : Cone F where pt := F.sections π := { app := fun j u => u.val j naturality := fun j j' f => by funext x simp } /-- (internal implementation) the fact that the proposed limit cone is the limit -/ @[simps] noncomputable def limitConeIsLimit (F : J ⥤ Type max v u) : IsLimit (limitCone F) where lift s v := { val := fun j => s.π.app j v property := fun f => congr_fun (Cone.w s f) _ } uniq := fun _ _ w => by funext x apply Subtype.ext funext j exact congr_fun (w j) x end TypeMax /-! The results in this section have a `UnivLE.{v, u}` hypothesis, but as they only use the constructions from the `CategoryTheory.Limits.Types.UnivLE` namespace in their definitions (rather than their statements), we leave them in the main `CategoryTheory.Limits.Types` namespace. -/ section UnivLE open UnivLE instance hasLimit [Small.{u} J] (F : J ⥤ Type u) : HasLimit F := (hasLimit_iff_small_sections F).mpr inferInstance instance hasLimitsOfShape [Small.{u} J] : HasLimitsOfShape J (Type u) where /-- The category of types has all limits. More specifically, when `UnivLE.{v, u}`, the category `Type u` has all `v`-small limits. -/ @[stacks 002U] instance (priority := 1300) hasLimitsOfSize [UnivLE.{v, u}] : HasLimitsOfSize.{w, v} (Type u) where has_limits_of_shape _ := { } variable (F : J ⥤ Type u) [HasLimit F] /-- The equivalence between the abstract limit of `F` in `Type max v u` and the "concrete" definition as the sections of `F`. -/ noncomputable def limitEquivSections : limit F ≃ F.sections := isLimitEquivSections (limit.isLimit F) @[simp] theorem limitEquivSections_apply (x : limit F) (j : J) : ((limitEquivSections F) x : ∀ j, F.obj j) j = limit.π F j x := rfl @[simp] theorem limitEquivSections_symm_apply (x : F.sections) (j : J) : limit.π F j ((limitEquivSections F).symm x) = (x : ∀ j, F.obj j) j := isLimitEquivSections_symm_apply _ _ _ /-- The limit of a functor `F : J ⥤ Type _` is naturally isomorphic to `F.sections`. -/ noncomputable def limNatIsoSectionsFunctor : (lim : (J ⥤ Type max u v) ⥤ _) ≅ Functor.sectionsFunctor _ := NatIso.ofComponents (fun _ ↦ (limitEquivSections _).toIso) fun f ↦ funext fun x ↦ Subtype.ext <| funext fun _ ↦ congrFun (limMap_π f _) x -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11182): removed @[ext] /-- Construct a term of `limit F : Type u` from a family of terms `x : Π j, F.obj j` which are "coherent": `∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j'`. -/ noncomputable def Limit.mk (x : ∀ j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') : limit F := (limitEquivSections F).symm ⟨x, h _ _⟩ @[simp] theorem Limit.π_mk (x : ∀ j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') (j) : limit.π F j (Limit.mk F x h) = x j := by dsimp [Limit.mk] simp -- PROJECT: prove this for concrete categories where the forgetful functor preserves limits @[ext] theorem limit_ext (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) : x = y := by apply (limitEquivSections F).injective ext j simp [w j] @[ext] theorem limit_ext' (F : J ⥤ Type v) (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) : x = y := limit_ext F x y w theorem limit_ext_iff' (F : J ⥤ Type v) (x y : limit F) : x = y ↔ ∀ j, limit.π F j x = limit.π F j y := ⟨fun t _ => t ▸ rfl, limit_ext' _ _ _⟩ -- TODO: are there other limits lemmas that should have `_apply` versions? -- Can we generate these like with `@[reassoc]`? -- PROJECT: prove these for any concrete category where the forgetful functor preserves limits? -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11119): @[simp] was removed because the linter said it was useless --@[simp] variable {F} in theorem Limit.w_apply {j j' : J} {x : limit F} (f : j ⟶ j') : F.map f (limit.π F j x) = limit.π F j' x := congr_fun (limit.w F f) x -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11119): @[simp] was removed because the linter said it was useless theorem Limit.lift_π_apply (s : Cone F) (j : J) (x : s.pt) : limit.π F j (limit.lift F s x) = s.π.app j x := congr_fun (limit.lift_π s j) x -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11119): @[simp] was removed because the linter said it was useless theorem Limit.map_π_apply {F G : J ⥤ Type u} [HasLimit F] [HasLimit G] (α : F ⟶ G) (j : J) (x : limit F) : limit.π G j (limMap α x) = α.app j (limit.π F j x) := congr_fun (limMap_π α j) x @[simp] theorem Limit.w_apply' {F : J ⥤ Type v} {j j' : J} {x : limit F} (f : j ⟶ j') : F.map f (limit.π F j x) = limit.π F j' x := congr_fun (limit.w F f) x @[simp] theorem Limit.lift_π_apply' (F : J ⥤ Type v) (s : Cone F) (j : J) (x : s.pt) : limit.π F j (limit.lift F s x) = s.π.app j x := congr_fun (limit.lift_π s j) x @[simp] theorem Limit.map_π_apply' {F G : J ⥤ Type v} (α : F ⟶ G) (j : J) (x : limit F) : limit.π G j (limMap α x) = α.app j (limit.π F j x) := congr_fun (limMap_π α j) x end UnivLE /-! In this section we verify that instances are available as expected. -/ section instances example : HasLimitsOfSize.{w, w, max v w, max (v + 1) (w + 1)} (Type max w v) := inferInstance example : HasLimitsOfSize.{w, w, max v w, max (v + 1) (w + 1)} (Type max v w) := inferInstance example : HasLimitsOfSize.{0, 0, v, v+1} (Type v) := inferInstance example : HasLimitsOfSize.{v, v, v, v+1} (Type v) := inferInstance example [UnivLE.{v, u}] : HasLimitsOfSize.{v, v, u, u+1} (Type u) := inferInstance end instances end CategoryTheory.Limits.Types
Yoneda.lean
/- Copyright (c) 2020 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison, Bhavik Mehta -/ import Mathlib.CategoryTheory.Limits.FunctorCategory.Basic import Mathlib.CategoryTheory.Limits.Types.Yoneda import Mathlib.Util.AssertExists /-! # Limit properties relating to the (co)yoneda embedding. We calculate the colimit of `Y ↦ (X ⟶ Y)`, which is just `PUnit`. (This is used in characterising cofinal functors.) We also show the (co)yoneda embeddings preserve limits and jointly reflect them. -/ assert_not_exists AddCommMonoid open Opposite CategoryTheory Limits universe t w v u namespace CategoryTheory namespace Coyoneda variable {C : Type u} [Category.{v} C] /-- The colimit cocone over `coyoneda.obj X`, with cocone point `PUnit`. -/ @[simps] def colimitCocone (X : Cᵒᵖ) : Cocone (coyoneda.obj X) where pt := PUnit ι := { app := by cat_disch } /-- The proposed colimit cocone over `coyoneda.obj X` is a colimit cocone. -/ @[simps] def colimitCoconeIsColimit (X : Cᵒᵖ) : IsColimit (colimitCocone X) where desc s _ := s.ι.app (unop X) (𝟙 _) fac s Y := by funext f convert congr_fun (s.w f).symm (𝟙 (unop X)) simp only [coyoneda_obj_obj, Functor.const_obj_obj, types_comp_apply, coyoneda_obj_map, Category.id_comp] uniq s m w := by apply funext; rintro ⟨⟩ rw [← w] simp instance (X : Cᵒᵖ) : HasColimit (coyoneda.obj X) := HasColimit.mk { cocone := _ isColimit := colimitCoconeIsColimit X } /-- The colimit of `coyoneda.obj X` is isomorphic to `PUnit`. -/ noncomputable def colimitCoyonedaIso (X : Cᵒᵖ) : colimit (coyoneda.obj X) ≅ PUnit := by apply colimit.isoColimitCocone { cocone := _ isColimit := colimitCoconeIsColimit X } end Coyoneda variable {C : Type u} [Category.{v} C] open Limits section variable {J : Type w} [Category.{t} J] /-- The cone of `F` corresponding to an element in `(F ⋙ yoneda.obj X).sections`. -/ @[simps] def Limits.coneOfSectionCompYoneda (F : J ⥤ Cᵒᵖ) (X : C) (s : (F ⋙ yoneda.obj X).sections) : Cone F where pt := Opposite.op X π := compYonedaSectionsEquiv F X s instance yoneda_preservesLimit (F : J ⥤ Cᵒᵖ) (X : C) : PreservesLimit F (yoneda.obj X) where preserves {c} hc := by rw [Types.isLimit_iff] intro s hs exact ⟨(hc.lift (Limits.coneOfSectionCompYoneda F X ⟨s, hs⟩)).unop, fun j => Quiver.Hom.op_inj (hc.fac (Limits.coneOfSectionCompYoneda F X ⟨s, hs⟩) j), fun m hm => Quiver.Hom.op_inj (hc.uniq (Limits.coneOfSectionCompYoneda F X ⟨s, hs⟩) _ (fun j => Quiver.Hom.unop_inj (hm j)))⟩ variable (J) in noncomputable instance yoneda_preservesLimitsOfShape (X : C) : PreservesLimitsOfShape J (yoneda.obj X) where /-- The yoneda embeddings jointly reflect limits. -/ def yonedaJointlyReflectsLimits (F : J ⥤ Cᵒᵖ) (c : Cone F) (hc : ∀ X : C, IsLimit ((yoneda.obj X).mapCone c)) : IsLimit c where lift s := ((hc s.pt.unop).lift ((yoneda.obj s.pt.unop).mapCone s) (𝟙 _)).op fac s j := Quiver.Hom.unop_inj (by simpa using congr_fun ((hc s.pt.unop).fac ((yoneda.obj s.pt.unop).mapCone s) j) (𝟙 _)) uniq s m hm := Quiver.Hom.unop_inj (by apply (Types.isLimitEquivSections (hc s.pt.unop)).injective ext j have eq := congr_fun ((hc s.pt.unop).fac ((yoneda.obj s.pt.unop).mapCone s) j) (𝟙 _) dsimp at eq dsimp [Types.isLimitEquivSections, Types.sectionOfCone] rw [eq, Category.comp_id, ← hm, unop_comp]) /-- A cocone is colimit iff it becomes limit after the application of `yoneda.obj X` for all `X : C`. -/ noncomputable def Limits.Cocone.isColimitYonedaEquiv {F : J ⥤ C} (c : Cocone F) : IsColimit c ≃ ∀ (X : C), IsLimit ((yoneda.obj X).mapCone c.op) where toFun h _ := isLimitOfPreserves _ h.op invFun h := IsLimit.unop (yonedaJointlyReflectsLimits _ _ h) left_inv _ := Subsingleton.elim _ _ right_inv _ := by ext; apply Subsingleton.elim /-- The cone of `F` corresponding to an element in `(F ⋙ coyoneda.obj X).sections`. -/ @[simps] def Limits.coneOfSectionCompCoyoneda (F : J ⥤ C) (X : Cᵒᵖ) (s : (F ⋙ coyoneda.obj X).sections) : Cone F where pt := X.unop π := compCoyonedaSectionsEquiv F X.unop s instance coyoneda_preservesLimit (F : J ⥤ C) (X : Cᵒᵖ) : PreservesLimit F (coyoneda.obj X) where preserves {c} hc := by rw [Types.isLimit_iff] intro s hs exact ⟨hc.lift (Limits.coneOfSectionCompCoyoneda F X ⟨s, hs⟩), hc.fac _, hc.uniq (Limits.coneOfSectionCompCoyoneda F X ⟨s, hs⟩)⟩ variable (J) in noncomputable instance coyonedaPreservesLimitsOfShape (X : Cᵒᵖ) : PreservesLimitsOfShape J (coyoneda.obj X) where /-- The coyoneda embeddings jointly reflect limits. -/ def coyonedaJointlyReflectsLimits (F : J ⥤ C) (c : Cone F) (hc : ∀ X : Cᵒᵖ, IsLimit ((coyoneda.obj X).mapCone c)) : IsLimit c where lift s := (hc (op s.pt)).lift ((coyoneda.obj (op s.pt)).mapCone s) (𝟙 _) fac s j := by simpa using congr_fun ((hc (op s.pt)).fac ((coyoneda.obj (op s.pt)).mapCone s) j) (𝟙 _) uniq s m hm := by apply (Types.isLimitEquivSections (hc (op s.pt))).injective ext j dsimp [Types.isLimitEquivSections, Types.sectionOfCone] have eq := congr_fun ((hc (op s.pt)).fac ((coyoneda.obj (op s.pt)).mapCone s) j) (𝟙 _) dsimp at eq rw [eq, Category.id_comp, ← hm] /-- A cone is limit iff it is so after the application of `coyoneda.obj X` for all `X : Cᵒᵖ`. -/ noncomputable def Limits.Cone.isLimitCoyonedaEquiv {F : J ⥤ C} (c : Cone F) : IsLimit c ≃ ∀ (X : Cᵒᵖ), IsLimit ((coyoneda.obj X).mapCone c) where toFun h _ := isLimitOfPreserves _ h invFun h := coyonedaJointlyReflectsLimits _ _ h left_inv _ := Subsingleton.elim _ _ right_inv _ := by ext; apply Subsingleton.elim end /-- The yoneda embedding `yoneda.obj X : Cᵒᵖ ⥤ Type v` for `X : C` preserves limits. -/ instance yoneda_preservesLimits (X : C) : PreservesLimitsOfSize.{t, w} (yoneda.obj X) where /-- The coyoneda embedding `coyoneda.obj X : C ⥤ Type v` for `X : Cᵒᵖ` preserves limits. -/ instance coyoneda_preservesLimits (X : Cᵒᵖ) : PreservesLimitsOfSize.{t, w} (coyoneda.obj X) where instance yonedaFunctor_preservesLimits : PreservesLimitsOfSize.{t, w} (@yoneda C _) := by apply preservesLimits_of_evaluation intro K change PreservesLimitsOfSize (coyoneda.obj K) infer_instance noncomputable instance coyonedaFunctor_preservesLimits : PreservesLimitsOfSize.{t, w} (@coyoneda C _) := by apply preservesLimits_of_evaluation intro K change PreservesLimitsOfSize (yoneda.obj K) infer_instance noncomputable instance yonedaFunctor_reflectsLimits : ReflectsLimitsOfSize.{t, w} (@yoneda C _) := inferInstance noncomputable instance coyonedaFunctor_reflectsLimits : ReflectsLimitsOfSize.{t, w} (@coyoneda C _) := inferInstance namespace Functor section Representable variable (F : Cᵒᵖ ⥤ Type v) [F.IsRepresentable] {J : Type*} [Category J] instance representable_preservesLimit (G : J ⥤ Cᵒᵖ) : PreservesLimit G F := preservesLimit_of_natIso _ F.reprW variable (J) in instance representable_preservesLimitsOfShape : PreservesLimitsOfShape J F where instance representable_preservesLimits : PreservesLimitsOfSize.{t, w} F where end Representable section Corepresentable variable (F : C ⥤ Type v) [F.IsCorepresentable] {J : Type*} [Category J] instance corepresentable_preservesLimit (G : J ⥤ C) : PreservesLimit G F := preservesLimit_of_natIso _ F.coreprW variable (J) in instance corepresentable_preservesLimitsOfShape : PreservesLimitsOfShape J F where instance corepresentable_preservesLimits : PreservesLimitsOfSize.{t, w} F where end Corepresentable end Functor end CategoryTheory
character.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype choice ssrnat seq. From mathcomp Require Import path div fintype tuple finfun bigop prime order. From mathcomp Require Import ssralg poly finset gproduct fingroup morphism. From mathcomp Require Import perm automorphism quotient finalg action zmodp. From mathcomp Require Import commutator cyclic center pgroup nilpotent sylow. From mathcomp Require Import abelian matrix mxalgebra mxpoly mxrepresentation. From mathcomp Require Import vector ssrnum algC classfun archimedean. (******************************************************************************) (* This file contains the basic notions of character theory, based on Isaacs. *) (* irr G == tuple of the elements of 'CF(G) that are irreducible *) (* characters of G. *) (* Nirr G == number of irreducible characters of G. *) (* Iirr G == index type for the irreducible characters of G. *) (* := 'I_(Nirr G). *) (* 'chi_i == the i-th element of irr G, for i : Iirr G. *) (* 'chi[G]_i Note that 'chi_0 = 1, the principal character of G. *) (* 'Chi_i == an irreducible representation that affords 'chi_i. *) (* socle_of_Iirr i == the Wedderburn component of the regular representation *) (* of G, corresponding to 'Chi_i. *) (* Iirr_of_socle == the inverse of socle_of_Iirr (which is one-to-one). *) (* phi.[A]%CF == the image of A \in group_ring G under phi : 'CF(G). *) (* cfRepr rG == the character afforded by the representation rG of G. *) (* cfReg G == the regular character, afforded by the regular *) (* representation of G. *) (* detRepr rG == the linear character afforded by the determinant of rG. *) (* cfDet phi == the linear character afforded by the determinant of a *) (* representation affording phi. *) (* 'o(phi) == the "determinential order" of phi (the multiplicative *) (* order of cfDet phi. *) (* phi \is a character <=> phi : 'CF(G) is a character of G or 0. *) (* i \in irr_constt phi <=> 'chi_i is an irreducible constituent of phi: phi *) (* has a non-zero coordinate on 'chi_i over the basis irr G. *) (* xi \is a linear_char xi <=> xi : 'CF(G) is a linear character of G. *) (* 'Z(chi)%CF == the center of chi when chi is a character of G, i.e., *) (* rcenter rG where rG is a representation that affords phi. *) (* If phi is not a character then 'Z(chi)%CF = cfker phi. *) (* aut_Iirr u i == the index of cfAut u 'chi_i in irr G. *) (* conjC_Iirr i == the index of 'chi_i^*%CF in irr G. *) (* morph_Iirr i == the index of cfMorph 'chi[f @* G]_i in irr G. *) (* isom_Iirr isoG i == the index of cfIsom isoG 'chi[G]_i in irr R. *) (* mod_Iirr i == the index of ('chi[G / H]_i %% H)%CF in irr G. *) (* quo_Iirr i == the index of ('chi[G]_i / H)%CF in irr (G / H). *) (* Ind_Iirr G i == the index of 'Ind[G, H] 'chi_i, provided it is an *) (* irreducible character (such as when if H is the inertia *) (* group of 'chi_i). *) (* Res_Iirr H i == the index of 'Res[H, G] 'chi_i, provided it is an *) (* irreducible character (such as when 'chi_i is linear). *) (* sdprod_Iirr defG i == the index of cfSdprod defG 'chi_i in irr G, given *) (* defG : K ><| H = G. *) (* And, for KxK : K \x H = G. *) (* dprodl_Iirr KxH i == the index of cfDprodl KxH 'chi[K]_i in irr G. *) (* dprodr_Iirr KxH j == the index of cfDprodr KxH 'chi[H]_j in irr G. *) (* dprod_Iirr KxH (i, j) == the index of cfDprod KxH 'chi[K]_i 'chi[H]_j. *) (* inv_dprod_Iirr KxH == the inverse of dprod_Iirr KxH. *) (* The following are used to define and exploit the character table: *) (* character_table G == the character table of G, whose i-th row lists the *) (* values taken by 'chi_i on the conjugacy classes *) (* of G; this is a square Nirr G x NirrG matrix. *) (* irr_class i == the conjugacy class of G with index i : Iirr G. *) (* class_Iirr xG == the index of xG \in classes G, in Iirr G. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import Order.TTheory GroupScope GRing.Theory Num.Theory. Local Open Scope ring_scope. Section AlgC. Variable (gT : finGroupType). Lemma groupC : group_closure_field algC gT. Proof. exact: group_closure_closed_field. Qed. End AlgC. Section Tensor. Variable (F : fieldType). Fixpoint trow (n1 : nat) : forall (A : 'rV[F]_n1) m2 n2 (B : 'M[F]_(m2,n2)), 'M[F]_(m2,n1 * n2) := if n1 is n'1.+1 then fun (A : 'M[F]_(1,(1 + n'1))) m2 n2 (B : 'M[F]_(m2,n2)) => (row_mx (lsubmx A 0 0 *: B) (trow (rsubmx A) B)) else (fun _ _ _ _ => 0). Lemma trow0 n1 m2 n2 B : @trow n1 0 m2 n2 B = 0. Proof. elim: n1=> //= n1 IH. rewrite !mxE scale0r linear0. rewrite IH //; apply/matrixP=> i j; rewrite !mxE. by case: split=> *; rewrite mxE. Qed. Definition trowb n1 m2 n2 B A := @trow n1 A m2 n2 B. Lemma trowbE n1 m2 n2 A B : trowb B A = @trow n1 A m2 n2 B. Proof. by []. Qed. Lemma trowb_is_linear n1 m2 n2 (B : 'M_(m2,n2)) : linear (@trowb n1 m2 n2 B). Proof. elim: n1=> [|n1 IH] //= k A1 A2 /=; first by rewrite scaler0 add0r. rewrite !linearD /= !linearZ /= IH 2!mxE. by rewrite scalerDl -scalerA -add_row_mx -scale_row_mx. Qed. HB.instance Definition _ n1 m2 n2 B := GRing.isSemilinear.Build _ _ _ _ (trowb B) (GRing.semilinear_linear (@trowb_is_linear n1 m2 n2 B)). Lemma trow_is_linear n1 m2 n2 (A : 'rV_n1) : linear (@trow n1 A m2 n2). Proof. elim: n1 A => [|n1 IH] //= A k A1 A2 /=; first by rewrite scaler0 add0r. rewrite linearP /=; apply/matrixP=> i j; rewrite !mxE. by case: split=> a; rewrite ?IH !mxE. Qed. HB.instance Definition _ n1 m2 n2 A := GRing.isSemilinear.Build _ _ _ _ (@trow n1 A m2 n2) (GRing.semilinear_linear (@trow_is_linear n1 m2 n2 A)). Fixpoint tprod (m1 : nat) : forall n1 (A : 'M[F]_(m1,n1)) m2 n2 (B : 'M[F]_(m2,n2)), 'M[F]_(m1 * m2,n1 * n2) := if m1 is m'1.+1 return forall n1 (A : 'M[F]_(m1,n1)) m2 n2 (B : 'M[F]_(m2,n2)), 'M[F]_(m1 * m2,n1 * n2) then fun n1 (A : 'M[F]_(1 + m'1,n1)) m2 n2 B => (col_mx (trow (usubmx A) B) (tprod (dsubmx A) B)) else (fun _ _ _ _ _ => 0). Lemma dsumx_mul m1 m2 n p A B : dsubmx ((A *m B) : 'M[F]_(m1 + m2, n)) = dsubmx (A : 'M_(m1 + m2, p)) *m B. Proof. apply/matrixP=> i j /[!mxE]; apply: eq_bigr=> k _. by rewrite !mxE. Qed. Lemma usumx_mul m1 m2 n p A B : usubmx ((A *m B) : 'M[F]_(m1 + m2, n)) = usubmx (A : 'M_(m1 + m2, p)) *m B. Proof. by apply/matrixP=> i j /[!mxE]; apply: eq_bigr=> k _ /[!mxE]. Qed. Let trow_mul (m1 m2 n2 p2 : nat) (A : 'rV_m1) (B1: 'M[F]_(m2,n2)) (B2 :'M[F]_(n2,p2)) : trow A (B1 *m B2) = B1 *m trow A B2. Proof. elim: m1 A => [|m1 IH] A /=; first by rewrite mulmx0. by rewrite IH mul_mx_row -scalemxAr. Qed. Lemma tprodE m1 n1 p1 (A1 :'M[F]_(m1,n1)) (A2 :'M[F]_(n1,p1)) m2 n2 p2 (B1 :'M[F]_(m2,n2)) (B2 :'M[F]_(n2,p2)) : tprod (A1 *m A2) (B1 *m B2) = (tprod A1 B1) *m (tprod A2 B2). Proof. elim: m1 n1 p1 A1 A2 m2 n2 p2 B1 B2 => /= [|m1 IH]. by move=> *; rewrite mul0mx. move=> n1 p1 A1 A2 m2 n2 p2 B1 B2. rewrite mul_col_mx -IH. congr col_mx; last by rewrite dsumx_mul. rewrite usumx_mul. elim: n1 {A1}(usubmx (A1: 'M_(1 + m1, n1))) p1 A2=> //= [u p1 A2|]. by rewrite [A2](flatmx0) !mulmx0 -trowbE linear0. move=> n1 IH1 A p1 A2 //=. set Al := lsubmx _; set Ar := rsubmx _. set Su := usubmx _; set Sd := dsubmx _. rewrite mul_row_col -IH1. rewrite -{1}(@hsubmxK F 1 1 n1 A). rewrite -{1}(@vsubmxK F 1 n1 p1 A2). rewrite (@mul_row_col F 1 1 n1 p1). rewrite -trowbE linearD /= trowbE -/Al. congr (_ + _). rewrite {1}[Al]mx11_scalar mul_scalar_mx. by rewrite -trowbE linearZ /= trowbE -/Su trow_mul scalemxAl. Qed. Let tprod_tr m1 n1 (A :'M[F]_(m1, 1 + n1)) m2 n2 (B :'M[F]_(m2, n2)) : tprod A B = row_mx (trow (lsubmx A)^T B^T)^T (tprod (rsubmx A) B). Proof. elim: m1 n1 A m2 n2 B=> [|m1 IH] n1 A m2 n2 B //=. by rewrite trmx0 row_mx0. rewrite !IH. pose A1 := A : 'M_(1 + m1, 1 + n1). have F1: dsubmx (rsubmx A1) = rsubmx (dsubmx A1). by apply/matrixP=> i j; rewrite !mxE. have F2: rsubmx (usubmx A1) = usubmx (rsubmx A1). by apply/matrixP=> i j; rewrite !mxE. have F3: lsubmx (dsubmx A1) = dsubmx (lsubmx A1). by apply/matrixP=> i j; rewrite !mxE. rewrite tr_row_mx -block_mxEv -block_mxEh !(F1,F2,F3); congr block_mx. - by rewrite !mxE linearZ /= trmxK. by rewrite -trmx_dsub. Qed. Lemma tprod1 m n : tprod (1%:M : 'M[F]_(m,m)) (1%:M : 'M[F]_(n,n)) = 1%:M. Proof. elim: m n => [|m IH] n //=; first by rewrite [1%:M]flatmx0. rewrite tprod_tr. set u := rsubmx _; have->: u = 0. apply/matrixP=> i j; rewrite !mxE. by case: i; case: j=> /= j Hj; case. set v := lsubmx (dsubmx _); have->: v = 0. apply/matrixP=> i j; rewrite !mxE. by case: i; case: j; case. set w := rsubmx _; have->: w = 1%:M. apply/matrixP=> i j; rewrite !mxE. by case: i; case: j; case. rewrite IH -!trowbE !linear0. rewrite -block_mxEv. set z := (lsubmx _) 0 0; have->: z = 1. by rewrite /z !mxE eqxx. by rewrite scale1r scalar_mx_block. Qed. Lemma mxtrace_prod m n (A :'M[F]_(m)) (B :'M[F]_(n)) : \tr (tprod A B) = \tr A * \tr B. Proof. elim: m n A B => [|m IH] n A B //=. by rewrite [A]flatmx0 mxtrace0 mul0r. rewrite tprod_tr -block_mxEv mxtrace_block IH. rewrite linearZ/= -mulrDl -trace_mx11; congr (_ * _). pose A1 := A : 'M_(1 + m). rewrite -[A in RHS](@submxK _ 1 m 1 m A1). by rewrite (@mxtrace_block _ _ _ (ulsubmx A1)). Qed. End Tensor. (* Representation sigma type and standard representations. *) Section StandardRepresentation. Variables (R : fieldType) (gT : finGroupType) (G : {group gT}). Local Notation reprG := (mx_representation R G). Record representation := Representation {rdegree; mx_repr_of_repr :> reprG rdegree}. Lemma mx_repr0 : mx_repr G (fun _ : gT => 1%:M : 'M[R]_0). Proof. by split=> // g h Hg Hx; rewrite mulmx1. Qed. Definition grepr0 := Representation (MxRepresentation mx_repr0). Lemma add_mx_repr (rG1 rG2 : representation) : mx_repr G (fun g => block_mx (rG1 g) 0 0 (rG2 g)). Proof. split=> [|x y Hx Hy]; first by rewrite !repr_mx1 -scalar_mx_block. by rewrite mulmx_block !(mulmx0, mul0mx, addr0, add0r, repr_mxM). Qed. Definition dadd_grepr rG1 rG2 := Representation (MxRepresentation (add_mx_repr rG1 rG2)). Section DsumRepr. Variables (n : nat) (rG : reprG n). Lemma mx_rsim_dadd (U V W : 'M_n) (rU rV : representation) (modU : mxmodule rG U) (modV : mxmodule rG V) (modW : mxmodule rG W) : (U + V :=: W)%MS -> mxdirect (U + V) -> mx_rsim (submod_repr modU) rU -> mx_rsim (submod_repr modV) rV -> mx_rsim (submod_repr modW) (dadd_grepr rU rV). Proof. case: rU; case: rV=> nV rV nU rU defW dxUV /=. have tiUV := mxdirect_addsP dxUV. move=> [fU def_nU]; rewrite -{nU}def_nU in rU fU * => inv_fU hom_fU. move=> [fV def_nV]; rewrite -{nV}def_nV in rV fV * => inv_fV hom_fV. pose pU := in_submod U (proj_mx U V) *m fU. pose pV := in_submod V (proj_mx V U) *m fV. exists (val_submod 1%:M *m row_mx pU pV) => [||g Gg]. - by rewrite -defW (mxdirectP dxUV). - apply/row_freeP. pose pU' := invmx fU *m val_submod 1%:M. pose pV' := invmx fV *m val_submod 1%:M. exists (in_submod _ (col_mx pU' pV')). rewrite in_submodE mulmxA -in_submodE -mulmxA mul_row_col mulmxDr. rewrite -[pU *m _]mulmxA -[pV *m _]mulmxA !mulKVmx -?row_free_unit //. rewrite addrC (in_submodE V) 2![val_submod 1%:M *m _]mulmxA -in_submodE. rewrite addrC (in_submodE U) 2![val_submod 1%:M *m _ in X in X + _]mulmxA. rewrite -in_submodE -!val_submodE !in_submodK ?proj_mx_sub //. by rewrite add_proj_mx ?val_submodK // val_submod1 defW. rewrite mulmxA -val_submodE -[submod_repr _ g]mul1mx val_submodJ //. rewrite -(mulmxA _ (rG g)) mul_mx_row -[in RHS]mulmxA mul_row_block. rewrite !mulmx0 addr0 add0r !mul_mx_row. set W' := val_submod 1%:M; congr (row_mx _ _). rewrite 3!mulmxA in_submodE mulmxA. have hom_pU: (W' <= dom_hom_mx rG (proj_mx U V))%MS. by rewrite val_submod1 -defW proj_mx_hom. rewrite (hom_mxP hom_pU) // -in_submodE (in_submodJ modU) ?proj_mx_sub //. rewrite -(mulmxA _ _ fU) hom_fU // in_submodE -2!(mulmxA W') -in_submodE. by rewrite -mulmxA (mulmxA _ fU). rewrite 3!mulmxA in_submodE mulmxA. have hom_pV: (W' <= dom_hom_mx rG (proj_mx V U))%MS. by rewrite val_submod1 -defW addsmxC proj_mx_hom // capmxC. rewrite (hom_mxP hom_pV) // -in_submodE (in_submodJ modV) ?proj_mx_sub //. rewrite -(mulmxA _ _ fV) hom_fV // in_submodE -2!(mulmxA W') -in_submodE. by rewrite -mulmxA (mulmxA _ fV). Qed. Lemma mx_rsim_dsum (I : finType) (P : pred I) U rU (W : 'M_n) (modU : forall i, mxmodule rG (U i)) (modW : mxmodule rG W) : let S := (\sum_(i | P i) U i)%MS in (S :=: W)%MS -> mxdirect S -> (forall i, mx_rsim (submod_repr (modU i)) (rU i : representation)) -> mx_rsim (submod_repr modW) (\big[dadd_grepr/grepr0]_(i | P i) rU i). Proof. move=> /= defW dxW rsimU. rewrite mxdirectE /= -!(big_filter _ P) in dxW defW *. elim: {P}(filter P _) => [|i e IHe] in W modW dxW defW *. rewrite !big_nil /= in defW *. by exists 0 => [||? _]; rewrite ?mul0mx ?mulmx0 // /row_free -defW !mxrank0. rewrite !big_cons /= in dxW defW *. rewrite 2!(big_nth i) !big_mkord /= in IHe dxW defW. set Wi := (\sum_i _)%MS in defW dxW IHe. rewrite -mxdirectE mxdirect_addsE !mxdirectE eqxx /= -/Wi in dxW. have modWi: mxmodule rG Wi by apply: sumsmx_module. case/andP: dxW; move/(IHe Wi modWi) {IHe}; move/(_ (eqmx_refl _))=> rsimWi. by move/eqP; move/mxdirect_addsP=> dxUiWi; apply: mx_rsim_dadd (rsimU i) rsimWi. Qed. Definition muln_grepr rW k := \big[dadd_grepr/grepr0]_(i < k) rW. Lemma mx_rsim_socle (sG : socleType rG) (W : sG) (rW : representation) : let modW : mxmodule rG W := component_mx_module rG (socle_base W) in mx_rsim (socle_repr W) rW -> mx_rsim (submod_repr modW) (muln_grepr rW (socle_mult W)). Proof. set M := socle_base W => modW rsimM. have simM: mxsimple rG M := socle_simple W. have rankM_gt0: (\rank M > 0)%N by rewrite lt0n mxrank_eq0; case: simM. have [I /= U_I simU]: mxsemisimple rG W by apply: component_mx_semisimple. pose U (i : 'I_#|I|) := U_I (enum_val i). have reindexI := reindex _ (onW_bij I (enum_val_bij I)). rewrite mxdirectE /= !reindexI -mxdirectE /= => defW dxW. have isoU: forall i, mx_iso rG M (U i). move=> i; have sUiW: (U i <= W)%MS by rewrite -defW (sumsmx_sup i). exact: component_mx_iso (simU _) sUiW. have ->: socle_mult W = #|I|. rewrite -(mulnK #|I| rankM_gt0); congr (_ %/ _)%N. rewrite -defW (mxdirectP dxW) /= -sum_nat_const reindexI /=. by apply: eq_bigr => i _; rewrite -(mxrank_iso (isoU i)). have modU: mxmodule rG (U _) := mxsimple_module (simU _). suff: mx_rsim (submod_repr (modU _)) rW by apply: mx_rsim_dsum defW dxW. by move=> i; apply: mx_rsim_trans (mx_rsim_sym _) rsimM; apply/mx_rsim_iso. Qed. End DsumRepr. Section ProdRepr. Variables (n1 n2 : nat) (rG1 : reprG n1) (rG2 : reprG n2). Lemma prod_mx_repr : mx_repr G (fun g => tprod (rG1 g) (rG2 g)). Proof. split=>[|i j InG JnG]; first by rewrite !repr_mx1 tprod1. by rewrite !repr_mxM // tprodE. Qed. Definition prod_repr := MxRepresentation prod_mx_repr. End ProdRepr. Lemma prod_repr_lin n2 (rG1 : reprG 1) (rG2 : reprG n2) : {in G, forall x, let cast_n2 := esym (mul1n n2) in prod_repr rG1 rG2 x = castmx (cast_n2, cast_n2) (rG1 x 0 0 *: rG2 x)}. Proof. move=> x Gx /=; set cast_n2 := esym _; rewrite /prod_repr /= !mxE !lshift0. apply/matrixP=> i j; rewrite castmxE /=. do 2![rewrite mxE; case: splitP => [? ? | []//]]. by congr ((_ *: rG2 x) _ _); apply: val_inj. Qed. End StandardRepresentation. Arguments grepr0 {R gT G}. Prenex Implicits dadd_grepr. Section Char. Variables (gT : finGroupType) (G : {group gT}). Fact cfRepr_subproof n (rG : mx_representation algC G n) : is_class_fun <<G>> [ffun x => \tr (rG x) *+ (x \in G)]. Proof. rewrite genGid; apply: intro_class_fun => [x y Gx Gy | _ /negbTE-> //]. by rewrite groupJr // !repr_mxM ?groupM ?groupV // mxtrace_mulC repr_mxK. Qed. Definition cfRepr n rG := Cfun 0 (@cfRepr_subproof n rG). Lemma cfRepr1 n rG : @cfRepr n rG 1%g = n%:R. Proof. by rewrite cfunE group1 repr_mx1 mxtrace1. Qed. Lemma cfRepr_sim n1 n2 rG1 rG2 : mx_rsim rG1 rG2 -> @cfRepr n1 rG1 = @cfRepr n2 rG2. Proof. case/mx_rsim_def=> f12 [f21] fK def_rG1; apply/cfun_inP=> x Gx. by rewrite !cfunE def_rG1 // mxtrace_mulC mulmxA fK mul1mx. Qed. Lemma cfRepr0 : cfRepr grepr0 = 0. Proof. by apply/cfun_inP=> x Gx; rewrite !cfunE Gx mxtrace1. Qed. Lemma cfRepr_dadd rG1 rG2 : cfRepr (dadd_grepr rG1 rG2) = cfRepr rG1 + cfRepr rG2. Proof. by apply/cfun_inP=> x Gx; rewrite !cfunE Gx mxtrace_block. Qed. Lemma cfRepr_dsum I r (P : pred I) rG : cfRepr (\big[dadd_grepr/grepr0]_(i <- r | P i) rG i) = \sum_(i <- r | P i) cfRepr (rG i). Proof. exact: (big_morph _ cfRepr_dadd cfRepr0). Qed. Lemma cfRepr_muln rG k : cfRepr (muln_grepr rG k) = cfRepr rG *+ k. Proof. by rewrite cfRepr_dsum /= sumr_const card_ord. Qed. Section StandardRepr. Variables (n : nat) (rG : mx_representation algC G n). Let sG := DecSocleType rG. Let iG : irrType algC G := DecSocleType _. Definition standard_irr (W : sG) := irr_comp iG (socle_repr W). Definition standard_socle i := pick [pred W | standard_irr W == i]. Local Notation soc := standard_socle. Definition standard_irr_coef i := oapp (fun W => socle_mult W) 0 (soc i). Definition standard_grepr := \big[dadd_grepr/grepr0]_i muln_grepr (Representation (socle_repr i)) (standard_irr_coef i). Lemma mx_rsim_standard : mx_rsim rG standard_grepr. Proof. pose W i := oapp val 0 (soc i); pose S := (\sum_i W i)%MS. have C'G: [pchar algC]^'.-group G := algC'G_pchar G. have [defS dxS]: (S :=: 1%:M)%MS /\ mxdirect S. rewrite /S mxdirectE /= !(bigID soc xpredT) /=. rewrite addsmxC big1 => [|i]; last by rewrite /W; case (soc i). rewrite adds0mx_id addnC (@big1 nat) ?add0n => [|i]; last first. by rewrite /W; case: (soc i); rewrite ?mxrank0. have <-: Socle sG = 1%:M := reducible_Socle1 sG (mx_Maschke_pchar rG C'G). have [W0 _ | noW] := pickP sG; last first. suff no_i: (soc : pred iG) =1 xpred0 by rewrite /Socle !big_pred0 ?mxrank0. by move=> i; rewrite /soc; case: pickP => // W0; have:= noW W0. have irrK Wi: soc (standard_irr Wi) = Some Wi. rewrite /soc; case: pickP => [W' | /(_ Wi)] /= /eqP // eqWi. apply/eqP/socle_rsimP. apply: mx_rsim_trans (rsim_irr_comp_pchar iG C'G (socle_irr _)) (mx_rsim_sym _). by rewrite [irr_comp _ _]eqWi; apply: rsim_irr_comp_pchar (socle_irr _). have bij_irr: {on [pred i | soc i], bijective standard_irr}. exists (odflt W0 \o soc) => [Wi _ | i]; first by rewrite /= irrK. by rewrite inE /soc /=; case: pickP => //= Wi; move/eqP. rewrite !(reindex standard_irr) {bij_irr}//=. have all_soc Wi: soc (standard_irr Wi) by rewrite irrK. rewrite (eq_bigr val) => [|Wi _]; last by rewrite /W irrK. rewrite !(eq_bigl _ _ all_soc); split=> //. rewrite (eq_bigr (mxrank \o val)) => [|Wi _]; last by rewrite /W irrK. by rewrite -mxdirectE /= Socle_direct. pose modW i : mxmodule rG (W i) := if soc i is Some Wi as oWi return mxmodule rG (oapp val 0 oWi) then component_mx_module rG (socle_base Wi) else mxmodule0 rG n. apply: mx_rsim_trans (mx_rsim_sym (rsim_submod1 (mxmodule1 rG) _)) _ => //. apply: mx_rsim_dsum (modW) _ defS dxS _ => i. rewrite /W /standard_irr_coef /modW /soc; case: pickP => [Wi|_] /=; last first. rewrite /muln_grepr big_ord0. by exists 0 => [||x _]; rewrite /row_free ?mxrank0 ?mulmx0 ?mul0mx. move/eqP=> <-; apply: mx_rsim_socle. exact: rsim_irr_comp_pchar (socle_irr Wi). Qed. End StandardRepr. Definition cfReg (B : {set gT}) : 'CF(B) := #|B|%:R *: '1_[1]. Lemma cfRegE x : @cfReg G x = #|G|%:R *+ (x == 1%g). Proof. by rewrite cfunE cfuniE ?normal1 // inE mulr_natr. Qed. (* This is Isaacs, Lemma (2.10). *) Lemma cfReprReg : cfRepr (regular_repr algC G) = cfReg G. Proof. apply/cfun_inP=> x Gx; rewrite cfRegE. have [-> | ntx] := eqVneq x 1%g; first by rewrite cfRepr1. rewrite cfunE Gx [\tr _]big1 // => i _; rewrite 2!mxE /=. rewrite -(inj_eq enum_val_inj) gring_indexK ?groupM ?enum_valP //. by rewrite eq_mulVg1 mulKg (negbTE ntx). Qed. Definition xcfun (chi : 'CF(G)) A := (gring_row A *m (\col_(i < #|G|) chi (enum_val i))) 0 0. Lemma xcfun_is_zmod_morphism phi : zmod_morphism (xcfun phi). Proof. by move=> A B; rewrite /xcfun [gring_row _]linearB mulmxBl !mxE. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `xcfun_is_zmod_morphism` instead")] Definition xcfun_is_additive := xcfun_is_zmod_morphism. HB.instance Definition _ phi := GRing.isZmodMorphism.Build 'M_(gcard G) _ (xcfun phi) (xcfun_is_zmod_morphism phi). Lemma xcfunZr a phi A : xcfun phi (a *: A) = a * xcfun phi A. Proof. by rewrite /xcfun linearZ -scalemxAl mxE. Qed. (* In order to add a second canonical structure on xcfun *) Definition xcfun_r A phi := xcfun phi A. Arguments xcfun_r A phi /. Lemma xcfun_rE A chi : xcfun_r A chi = xcfun chi A. Proof. by []. Qed. Fact xcfun_r_is_zmod_morphism A : zmod_morphism (xcfun_r A). Proof. move=> phi psi; rewrite /= /xcfun !mxE -sumrB; apply: eq_bigr => i _. by rewrite !mxE !cfunE mulrBr. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `xcfun_r_is_zmod_morphism` instead")] Definition xcfun_r_is_additive := xcfun_r_is_zmod_morphism. HB.instance Definition _ A := GRing.isZmodMorphism.Build _ _ (xcfun_r A) (xcfun_r_is_zmod_morphism A). Lemma xcfunZl a phi A : xcfun (a *: phi) A = a * xcfun phi A. Proof. rewrite /xcfun !mxE big_distrr; apply: eq_bigr => i _ /=. by rewrite !mxE cfunE mulrCA. Qed. Lemma xcfun_repr n rG A : xcfun (@cfRepr n rG) A = \tr (gring_op rG A). Proof. rewrite gring_opE [gring_row A]row_sum_delta !linear_sum /xcfun !mxE. apply: eq_bigr => i _; rewrite !mxE /= !linearZ cfunE enum_valP /=. by congr (_ * \tr _); rewrite {A}/gring_mx /= -rowE rowK mxvecK. Qed. End Char. Arguments xcfun_r {_ _} A phi /. Notation "phi .[ A ]" := (xcfun phi A) : cfun_scope. Definition pred_Nirr gT B := #|@classes gT B|.-1. Arguments pred_Nirr {gT} B%_g. Notation Nirr G := (pred_Nirr G).+1. Notation Iirr G := 'I_(Nirr G). Section IrrClassDef. Variables (gT : finGroupType) (G : {group gT}). Let sG := DecSocleType (regular_repr algC G). Lemma NirrE : Nirr G = #|classes G|. Proof. by rewrite /pred_Nirr (cardD1 [1]) classes1. Qed. Fact Iirr_cast : Nirr G = #|sG|. Proof. by rewrite NirrE ?card_irr_pchar ?algC'G_pchar //; apply: groupC. Qed. Let offset := cast_ord (esym Iirr_cast) (enum_rank [1 sG]%irr). Definition socle_of_Iirr (i : Iirr G) : sG := enum_val (cast_ord Iirr_cast (i + offset)). Definition irr_of_socle (Wi : sG) : Iirr G := cast_ord (esym Iirr_cast) (enum_rank Wi) - offset. Local Notation W := socle_of_Iirr. Lemma socle_Iirr0 : W 0 = [1 sG]%irr. Proof. by rewrite /W add0r cast_ordKV enum_rankK. Qed. Lemma socle_of_IirrK : cancel W irr_of_socle. Proof. by move=> i; rewrite /irr_of_socle enum_valK cast_ordK addrK. Qed. Lemma irr_of_socleK : cancel irr_of_socle W. Proof. by move=> Wi; rewrite /W subrK cast_ordKV enum_rankK. Qed. Hint Resolve socle_of_IirrK irr_of_socleK : core. Lemma irr_of_socle_bij (A : {pred (Iirr G)}) : {on A, bijective irr_of_socle}. Proof. by apply: onW_bij; exists W. Qed. Lemma socle_of_Iirr_bij (A : {pred sG}) : {on A, bijective W}. Proof. by apply: onW_bij; exists irr_of_socle. Qed. End IrrClassDef. Prenex Implicits socle_of_IirrK irr_of_socleK. Arguments socle_of_Iirr {gT G%_G} i%_R. Notation "''Chi_' i" := (irr_repr (socle_of_Iirr i)) (at level 8, i at level 2, format "''Chi_' i"). HB.lock Definition irr gT B : (Nirr B).-tuple 'CF(B) := let irr_of i := 'Res[B, <<B>>] (@cfRepr gT _ _ 'Chi_(inord i)) in [tuple of mkseq irr_of (Nirr B)]. Arguments irr {gT} B%_g. Notation "''chi_' i" := (tnth (irr _) i%R) (at level 8, i at level 2, format "''chi_' i") : ring_scope. Notation "''chi[' G ]_ i" := (tnth (irr G) i%R) (at level 8, i at level 2, only parsing) : ring_scope. Section IrrClass. Variable (gT : finGroupType) (G : {group gT}). Implicit Types (i : Iirr G) (B : {set gT}). Open Scope group_ring_scope. Lemma congr_irr i1 i2 : i1 = i2 -> 'chi_i1 = 'chi_i2. Proof. by move->. Qed. Lemma Iirr1_neq0 : G :!=: 1%g -> inord 1 != 0 :> Iirr G. Proof. by rewrite -classes_gt1 -NirrE -val_eqE /= => /inordK->. Qed. Lemma has_nonprincipal_irr : G :!=: 1%g -> {i : Iirr G | i != 0}. Proof. by move/Iirr1_neq0; exists (inord 1). Qed. Lemma irrRepr i : cfRepr 'Chi_i = 'chi_i. Proof. rewrite irr.unlock (tnth_nth 0) nth_mkseq // -[<<G>>]/(gval _) genGidG. by rewrite cfRes_id inord_val. Qed. Lemma irr0 : 'chi[G]_0 = 1. Proof. apply/cfun_inP=> x Gx; rewrite -irrRepr cfun1E cfunE Gx. by rewrite socle_Iirr0 irr1_repr // mxtrace1 degree_irr1. Qed. Lemma cfun1_irr : 1 \in irr G. Proof. by rewrite -irr0 mem_tnth. Qed. Lemma mem_irr i : 'chi_i \in irr G. Proof. exact: mem_tnth. Qed. Lemma irrP xi : reflect (exists i, xi = 'chi_i) (xi \in irr G). Proof. apply: (iffP idP) => [/(nthP 0)[i] | [i ->]]; last exact: mem_irr. rewrite size_tuple => lt_i_G <-. by exists (Ordinal lt_i_G); rewrite (tnth_nth 0). Qed. Let sG := DecSocleType (regular_repr algC G). Let C'G := algC'G_pchar G. Let closG := @groupC _ G. Local Notation W i := (@socle_of_Iirr _ G i). Local Notation "''n_' i" := 'n_(W i). Local Notation "''R_' i" := 'R_(W i). Local Notation "''e_' i" := 'e_(W i). Lemma irr1_degree i : 'chi_i 1%g = ('n_i)%:R. Proof. by rewrite -irrRepr cfRepr1. Qed. Lemma Cnat_irr1 i : 'chi_i 1%g \in Num.nat. Proof. by rewrite irr1_degree rpred_nat. Qed. Lemma irr1_gt0 i : 0 < 'chi_i 1%g. Proof. by rewrite irr1_degree ltr0n irr_degree_gt0. Qed. Lemma irr1_neq0 i : 'chi_i 1%g != 0. Proof. by rewrite eq_le lt_geF ?irr1_gt0. Qed. Lemma irr_neq0 i : 'chi_i != 0. Proof. by apply: contraNneq (irr1_neq0 i) => ->; rewrite cfunE. Qed. Local Remark cfIirr_key : unit. Proof. by []. Qed. Definition cfIirr : forall B, 'CF(B) -> Iirr B := locked_with cfIirr_key (fun B chi => inord (index chi (irr B))). Lemma cfIirrE chi : chi \in irr G -> 'chi_(cfIirr chi) = chi. Proof. move=> chi_irr; rewrite (tnth_nth 0) [cfIirr]unlock inordK ?nth_index //. by rewrite -index_mem size_tuple in chi_irr. Qed. Lemma cfIirrPE J (f : J -> 'CF(G)) (P : pred J) : (forall j, P j -> f j \in irr G) -> forall j, P j -> 'chi_(cfIirr (f j)) = f j. Proof. by move=> irr_f j /irr_f; apply: cfIirrE. Qed. (* This is Isaacs, Corollary (2.7). *) Corollary irr_sum_square : \sum_i ('chi[G]_i 1%g) ^+ 2 = #|G|%:R. Proof. rewrite -(sum_irr_degree_pchar sG) // natr_sum. rewrite (reindex _ (socle_of_Iirr_bij _)) /=. by apply: eq_bigr => i _; rewrite irr1_degree natrX. Qed. (* This is Isaacs, Lemma (2.11). *) Lemma cfReg_sum : cfReg G = \sum_i 'chi_i 1%g *: 'chi_i. Proof. apply/cfun_inP=> x Gx. rewrite -cfReprReg cfunE Gx (mxtrace_regular_pchar sG) //=. rewrite sum_cfunE (reindex _ (socle_of_Iirr_bij _)); apply: eq_bigr => i _. by rewrite -irrRepr cfRepr1 !cfunE Gx mulr_natl. Qed. Let aG := regular_repr algC G. Let R_G := group_ring algC G. Lemma xcfun_annihilate i j A : i != j -> (A \in 'R_j)%MS -> ('chi_i).[A]%CF = 0. Proof. move=> neq_ij RjA; rewrite -irrRepr xcfun_repr. rewrite (irr_repr'_op0_pchar _ _ RjA) ?raddf0 //. by rewrite eq_sym (can_eq socle_of_IirrK). Qed. Lemma xcfunG phi x : x \in G -> phi.[aG x]%CF = phi x. Proof. by move=> Gx; rewrite /xcfun /gring_row rowK -rowE !mxE !(gring_indexK, mul1g). Qed. Lemma xcfun_mul_id i A : (A \in R_G)%MS -> ('chi_i).['e_i *m A]%CF = ('chi_i).[A]%CF. Proof. move=> RG_A; rewrite -irrRepr !xcfun_repr gring_opM //. by rewrite op_Wedderburn_id_pchar ?mul1mx. Qed. Lemma xcfun_id i j : ('chi_i).['e_j]%CF = 'chi_i 1%g *+ (i == j). Proof. have [<-{j} | /xcfun_annihilate->//] := eqVneq; last exact: Wedderburn_id_mem. by rewrite -xcfunG // repr_mx1 -(xcfun_mul_id _ (envelop_mx1 _)) mulmx1. Qed. Lemma irr_free : free (irr G). Proof. apply/freeP=> s s0 i; apply: (mulIf (irr1_neq0 i)). rewrite mul0r -(raddf0 (xcfun_r 'e_i)) -{}s0 raddf_sum /=. rewrite (bigD1 i)//= -tnth_nth xcfunZl xcfun_id eqxx big1 ?addr0 // => j ne_ji. by rewrite -tnth_nth xcfunZl xcfun_id (negbTE ne_ji) mulr0. Qed. Lemma irr_inj : injective (tnth (irr G)). Proof. by apply/injectiveP/free_uniq; rewrite map_tnth_enum irr_free. Qed. Lemma irrK : cancel (tnth (irr G)) (@cfIirr G). Proof. by move=> i; apply: irr_inj; rewrite cfIirrE ?mem_irr. Qed. Lemma irr_eq1 i : ('chi_i == 1) = (i == 0). Proof. by rewrite -irr0 (inj_eq irr_inj). Qed. Lemma cforder_irr_eq1 i : (#['chi_i]%CF == 1) = (i == 0). Proof. by rewrite -dvdn1 dvdn_cforder irr_eq1. Qed. Lemma irr_basis : basis_of 'CF(G)%VS (irr G). Proof. rewrite /basis_of irr_free andbT -dimv_leqif_eq ?subvf //. by rewrite dim_cfun (eqnP irr_free) size_tuple NirrE. Qed. Lemma eq_sum_nth_irr a : \sum_i a i *: 'chi[G]_i = \sum_i a i *: (irr G)`_i. Proof. by apply: eq_bigr => i; rewrite -tnth_nth. Qed. (* This is Isaacs, Theorem (2.8). *) Theorem cfun_irr_sum phi : {a | phi = \sum_i a i *: 'chi[G]_i}. Proof. rewrite (coord_basis irr_basis (memvf phi)) -eq_sum_nth_irr. by exists ((coord (irr G))^~ phi). Qed. Lemma cfRepr_standard n (rG : mx_representation algC G n) : cfRepr (standard_grepr rG) = \sum_i (standard_irr_coef rG (W i))%:R *: 'chi_i. Proof. rewrite cfRepr_dsum (reindex _ (socle_of_Iirr_bij _)). by apply: eq_bigr => i _; rewrite scaler_nat cfRepr_muln irrRepr. Qed. Lemma cfRepr_inj n1 n2 rG1 rG2 : @cfRepr _ G n1 rG1 = @cfRepr _ G n2 rG2 -> mx_rsim rG1 rG2. Proof. move=> eq_repr12; pose c i : algC := (standard_irr_coef _ (W i))%:R. have [rsim1 rsim2] := (mx_rsim_standard rG1, mx_rsim_standard rG2). apply: mx_rsim_trans (rsim1) (mx_rsim_sym _). suffices ->: standard_grepr rG1 = standard_grepr rG2 by []. apply: eq_bigr => Wi _; congr (muln_grepr _ _); apply/eqP; rewrite -eqC_nat. rewrite -[Wi]irr_of_socleK -!/(c _ _ _) -!(coord_sum_free (c _ _) _ irr_free). rewrite -!eq_sum_nth_irr -!cfRepr_standard. by rewrite -(cfRepr_sim rsim1) -(cfRepr_sim rsim2) eq_repr12. Qed. Lemma cfRepr_rsimP n1 n2 rG1 rG2 : reflect (mx_rsim rG1 rG2) (@cfRepr _ G n1 rG1 == @cfRepr _ G n2 rG2). Proof. by apply: (iffP eqP) => [/cfRepr_inj | /cfRepr_sim]. Qed. Lemma irr_reprP xi : reflect (exists2 rG : representation _ G, mx_irreducible rG & xi = cfRepr rG) (xi \in irr G). Proof. apply: (iffP (irrP xi)) => [[i ->] | [[n rG] irr_rG ->]]. by exists (Representation 'Chi_i); [apply: socle_irr | rewrite irrRepr]. exists (irr_of_socle (irr_comp sG rG)); rewrite -irrRepr irr_of_socleK /=. exact/cfRepr_sim/rsim_irr_comp_pchar. Qed. (* This is Isaacs, Theorem (2.12). *) Lemma Wedderburn_id_expansion i : 'e_i = #|G|%:R^-1 *: (\sum_(x in G) 'chi_i 1%g * 'chi_i x^-1%g *: aG x). Proof. have Rei: ('e_i \in 'R_i)%MS by apply: Wedderburn_id_mem. have /envelop_mxP[a def_e]: ('e_i \in R_G)%MS; last rewrite -/aG in def_e. by move: Rei; rewrite genmxE mem_sub_gring => /andP[]. apply: canRL (scalerK (neq0CG _)) _; rewrite def_e linear_sum /=. apply: eq_bigr => x Gx; have Gx' := groupVr Gx; rewrite scalerA; congr (_ *: _). transitivity (cfReg G).['e_i *m aG x^-1%g]%CF. rewrite def_e mulmx_suml raddf_sum (bigD1 x) //= -scalemxAl xcfunZr. rewrite -repr_mxM // mulgV xcfunG // cfRegE eqxx mulrC big1 ?addr0 //. move=> y /andP[Gy /negbTE neq_xy]; rewrite -scalemxAl xcfunZr -repr_mxM //. by rewrite xcfunG ?groupM // cfRegE -eq_mulgV1 neq_xy mulr0. rewrite cfReg_sum -xcfun_rE raddf_sum /= (bigD1 i) //= xcfunZl. rewrite xcfun_mul_id ?envelop_mx_id ?xcfunG ?groupV ?big1 ?addr0 // => j ne_ji. rewrite xcfunZl (xcfun_annihilate ne_ji) ?mulr0 //. have /andP[_ /(submx_trans _)-> //] := Wedderburn_ideal (W i). by rewrite mem_mulsmx // envelop_mx_id ?groupV. Qed. End IrrClass. Arguments cfReg {gT} B%_g. Prenex Implicits cfIirr irrK. Arguments irrP {gT G xi}. Arguments irr_reprP {gT G xi}. Arguments irr_inj {gT G} [x1 x2]. Section IsChar. Variable gT : finGroupType. Definition character_pred {G : {set gT}} := fun phi : 'CF(G) => [forall i, coord (irr G) i phi \in Num.nat]. Arguments character_pred _ _ /. Definition character {G : {set gT}} := [qualify a phi | @character_pred G phi]. Variable G : {group gT}. Implicit Types (phi chi xi : 'CF(G)) (i : Iirr G). Lemma irr_char i : 'chi_i \is a character. Proof. by apply/forallP=> j; rewrite (tnth_nth 0) coord_free ?irr_free. Qed. Lemma cfun1_char : (1 : 'CF(G)) \is a character. Proof. by rewrite -irr0 irr_char. Qed. Lemma cfun0_char : (0 : 'CF(G)) \is a character. Proof. by apply/forallP=> i; rewrite linear0 rpred0. Qed. Fact add_char : addr_closed (@character G). Proof. split=> [|chi xi /forallP-Nchi /forallP-Nxi]; first exact: cfun0_char. by apply/forallP=> i; rewrite linearD rpredD /=. Qed. HB.instance Definition _ := GRing.isAddClosed.Build (classfun G) character_pred add_char. Lemma char_sum_irrP {phi} : reflect (exists n, phi = \sum_i (n i)%:R *: 'chi_i) (phi \is a character). Proof. apply: (iffP idP)=> [/forallP-Nphi | [n ->]]; last first. by apply: rpred_sum => i _; rewrite scaler_nat rpredMn // irr_char. do [have [a ->] := cfun_irr_sum phi] in Nphi *; exists (Num.truncn \o a). apply: eq_bigr => i _; congr (_ *: _); have:= eqP (Nphi i). by rewrite eq_sum_nth_irr coord_sum_free ?irr_free. Qed. Lemma char_sum_irr chi : chi \is a character -> {r | chi = \sum_(i <- r) 'chi_i}. Proof. move=> Nchi; apply: sig_eqW; case/char_sum_irrP: Nchi => n {chi}->. elim/big_rec: _ => [|i _ _ [r ->]]; first by exists nil; rewrite big_nil. exists (ncons (n i) i r); rewrite scaler_nat. by elim: {n}(n i) => [|n IHn]; rewrite ?add0r //= big_cons mulrS -addrA IHn. Qed. Lemma Cnat_char1 chi : chi \is a character -> chi 1%g \in Num.nat. Proof. case/char_sum_irr=> r ->{chi}. by elim/big_rec: _ => [|i chi _ Nchi1]; rewrite cfunE ?rpredD // Cnat_irr1. Qed. Lemma char1_ge0 chi : chi \is a character -> 0 <= chi 1%g. Proof. by move/Cnat_char1/natr_ge0. Qed. Lemma char1_eq0 chi : chi \is a character -> (chi 1%g == 0) = (chi == 0). Proof. case/char_sum_irr=> r ->; apply/idP/idP=> [|/eqP->]; last by rewrite cfunE. case: r => [|i r]; rewrite ?big_nil // sum_cfunE big_cons. rewrite paddr_eq0 ?sumr_ge0 => // [||j _]; rewrite 1?ltW ?irr1_gt0 //. by rewrite (negbTE (irr1_neq0 i)). Qed. Lemma char1_gt0 chi : chi \is a character -> (0 < chi 1%g) = (chi != 0). Proof. by move=> Nchi; rewrite -char1_eq0 // natr_gt0 ?Cnat_char1. Qed. Lemma char_reprP phi : reflect (exists rG : representation algC G, phi = cfRepr rG) (phi \is a character). Proof. apply: (iffP char_sum_irrP) => [[n ->] | [[n rG] ->]]; last first. exists (fun i => standard_irr_coef rG (socle_of_Iirr i)). by rewrite -cfRepr_standard (cfRepr_sim (mx_rsim_standard rG)). exists (\big[dadd_grepr/grepr0]_i muln_grepr (Representation 'Chi_i) (n i)). rewrite cfRepr_dsum; apply: eq_bigr => i _. by rewrite cfRepr_muln irrRepr scaler_nat. Qed. Local Notation reprG := (mx_representation algC G). Lemma cfRepr_char n (rG : reprG n) : cfRepr rG \is a character. Proof. by apply/char_reprP; exists (Representation rG). Qed. Lemma cfReg_char : cfReg G \is a character. Proof. by rewrite -cfReprReg cfRepr_char. Qed. Lemma cfRepr_prod n1 n2 (rG1 : reprG n1) (rG2 : reprG n2) : cfRepr rG1 * cfRepr rG2 = cfRepr (prod_repr rG1 rG2). Proof. by apply/cfun_inP=> x Gx; rewrite !cfunE /= Gx mxtrace_prod. Qed. Lemma mul_char : mulr_closed (@character G). Proof. split=> [|_ _ /char_reprP[rG1 ->] /char_reprP[rG2 ->]]; first exact: cfun1_char. apply/char_reprP; exists (Representation (prod_repr rG1 rG2)). by rewrite cfRepr_prod. Qed. HB.instance Definition _ := GRing.isMulClosed.Build (classfun G) character_pred mul_char. End IsChar. Prenex Implicits character. Arguments character_pred _ _ _ /. Arguments char_reprP {gT G phi}. Section AutChar. Variables (gT : finGroupType) (G : {group gT}). Implicit Type u : {rmorphism algC -> algC}. Implicit Type chi : 'CF(G). Lemma cfRepr_map u n (rG : mx_representation algC G n) : cfRepr (map_repr u rG) = cfAut u (cfRepr rG). Proof. by apply/cfun_inP=> x Gx; rewrite !cfunE Gx map_reprE trace_map_mx. Qed. Lemma cfAut_char u chi : (cfAut u chi \is a character) = (chi \is a character). Proof. without loss /char_reprP[rG ->]: u chi / chi \is a character. by move=> IHu; apply/idP/idP=> ?; first rewrite -(cfAutK u chi); rewrite IHu. rewrite cfRepr_char; apply/char_reprP. by exists (Representation (map_repr u rG)); rewrite cfRepr_map. Qed. Lemma cfConjC_char chi : (chi^*%CF \is a character) = (chi \is a character). Proof. exact: cfAut_char. Qed. Lemma cfAut_char1 u (chi : 'CF(G)) : chi \is a character -> cfAut u chi 1%g = chi 1%g. Proof. by move/Cnat_char1=> Nchi1; rewrite cfunE /= aut_natr. Qed. Lemma cfAut_irr1 u i : (cfAut u 'chi[G]_i) 1%g = 'chi_i 1%g. Proof. exact: cfAut_char1 (irr_char i). Qed. Lemma cfConjC_char1 (chi : 'CF(G)) : chi \is a character -> chi^*%CF 1%g = chi 1%g. Proof. exact: cfAut_char1. Qed. Lemma cfConjC_irr1 u i : ('chi[G]_i)^*%CF 1%g = 'chi_i 1%g. Proof. exact: cfAut_irr1. Qed. End AutChar. Section Linear. Variables (gT : finGroupType) (G : {group gT}). Definition linear_char_pred {B : {set gT}} := fun phi : 'CF(B) => (phi \is a character) && (phi 1%g == 1). Arguments linear_char_pred _ _ /. Definition linear_char {B : {set gT}} := [qualify a phi | @linear_char_pred B phi]. Section OneChar. Variable xi : 'CF(G). Hypothesis CFxi : xi \is a linear_char. Lemma lin_char1: xi 1%g = 1. Proof. by case/andP: CFxi => _ /eqP. Qed. Lemma lin_charW : xi \is a character. Proof. by case/andP: CFxi. Qed. Lemma cfun1_lin_char : (1 : 'CF(G)) \is a linear_char. Proof. by rewrite qualifE/= cfun1_char /= cfun11. Qed. Lemma lin_charM : {in G &, {morph xi : x y / (x * y)%g >-> x * y}}. Proof. move=> x y Gx Gy; case/andP: CFxi => /char_reprP[[n rG] -> /=]. rewrite cfRepr1 pnatr_eq1 => /eqP n1; rewrite {n}n1 in rG *. rewrite !cfunE Gx Gy groupM //= !mulr1n repr_mxM //. by rewrite [rG x]mx11_scalar [rG y]mx11_scalar -scalar_mxM !mxtrace_scalar. Qed. Lemma lin_char_prod I r (P : pred I) (x : I -> gT) : (forall i, P i -> x i \in G) -> xi (\prod_(i <- r | P i) x i)%g = \prod_(i <- r | P i) xi (x i). Proof. move=> Gx; elim/(big_load (fun y => y \in G)): _. elim/big_rec2: _ => [|i a y Pi [Gy <-]]; first by rewrite lin_char1. by rewrite groupM ?lin_charM ?Gx. Qed. Let xiMV x : x \in G -> xi x * xi (x^-1)%g = 1. Proof. by move=> Gx; rewrite -lin_charM ?groupV // mulgV lin_char1. Qed. Lemma lin_char_neq0 x : x \in G -> xi x != 0. Proof. by move/xiMV/(congr1 (predC1 0)); rewrite /= oner_eq0 mulf_eq0 => /norP[]. Qed. Lemma lin_charV x : x \in G -> xi x^-1%g = (xi x)^-1. Proof. by move=> Gx; rewrite -[_^-1]mulr1 -(xiMV Gx) mulKf ?lin_char_neq0. Qed. Lemma lin_charX x n : x \in G -> xi (x ^+ n)%g = xi x ^+ n. Proof. move=> Gx; elim: n => [|n IHn]; first exact: lin_char1. by rewrite expgS exprS lin_charM ?groupX ?IHn. Qed. Lemma lin_char_unity_root x : x \in G -> xi x ^+ #[x] = 1. Proof. by move=> Gx; rewrite -lin_charX // expg_order lin_char1. Qed. Lemma normC_lin_char x : x \in G -> `|xi x| = 1. Proof. move=> Gx; apply/eqP; rewrite -(@pexpr_eq1 _ _ #[x]) //. by rewrite -normrX // lin_char_unity_root ?normr1. Qed. Lemma lin_charV_conj x : x \in G -> xi x^-1%g = (xi x)^*. Proof. move=> Gx; rewrite lin_charV // invC_norm mulrC normC_lin_char //. by rewrite expr1n divr1. Qed. Lemma lin_char_irr : xi \in irr G. Proof. case/andP: CFxi => /char_reprP[rG ->]; rewrite cfRepr1 pnatr_eq1 => /eqP n1. by apply/irr_reprP; exists rG => //; apply/mx_abs_irrW/linear_mx_abs_irr. Qed. Lemma mul_conjC_lin_char : xi * xi^*%CF = 1. Proof. apply/cfun_inP=> x Gx. by rewrite !cfunE cfun1E Gx -normCK normC_lin_char ?expr1n. Qed. Lemma lin_char_unitr : xi \in GRing.unit. Proof. by apply/unitrPr; exists xi^*%CF; apply: mul_conjC_lin_char. Qed. Lemma invr_lin_char : xi^-1 = xi^*%CF. Proof. by rewrite -[_^-1]mulr1 -mul_conjC_lin_char mulKr ?lin_char_unitr. Qed. Lemma fful_lin_char_inj : cfaithful xi -> {in G &, injective xi}. Proof. move=> fful_phi x y Gx Gy xi_xy; apply/eqP; rewrite eq_mulgV1 -in_set1. rewrite (subsetP fful_phi) // inE groupM ?groupV //=; apply/forallP=> z. have [Gz | G'z] := boolP (z \in G); last by rewrite !cfun0 ?groupMl ?groupV. by rewrite -mulgA lin_charM ?xi_xy -?lin_charM ?groupM ?groupV // mulKVg. Qed. End OneChar. Lemma cfAut_lin_char u (xi : 'CF(G)) : (cfAut u xi \is a linear_char) = (xi \is a linear_char). Proof. by rewrite qualifE/= cfAut_char; apply/andb_id2l=> /cfAut_char1->. Qed. Lemma cfConjC_lin_char (xi : 'CF(G)) : (xi^*%CF \is a linear_char) = (xi \is a linear_char). Proof. exact: cfAut_lin_char. Qed. Lemma card_Iirr_abelian : abelian G -> #|Iirr G| = #|G|. Proof. by rewrite card_ord NirrE card_classes_abelian => /eqP. Qed. Lemma card_Iirr_cyclic : cyclic G -> #|Iirr G| = #|G|. Proof. by move/cyclic_abelian/card_Iirr_abelian. Qed. Lemma char_abelianP : reflect (forall i : Iirr G, 'chi_i \is a linear_char) (abelian G). Proof. apply: (iffP idP) => [cGG i | CF_G]. rewrite qualifE/= irr_char /= irr1_degree. by rewrite irr_degree_abelian //; last apply: groupC. rewrite card_classes_abelian -NirrE -eqC_nat -irr_sum_square //. rewrite -{1}[Nirr G]card_ord -sumr_const; apply/eqP/eq_bigr=> i _. by rewrite lin_char1 ?expr1n ?CF_G. Qed. Lemma irr_repr_lin_char (i : Iirr G) x : x \in G -> 'chi_i \is a linear_char -> irr_repr (socle_of_Iirr i) x = ('chi_i x)%:M. Proof. move=> Gx CFi; rewrite -irrRepr cfunE Gx. move: (_ x); rewrite -[irr_degree _](@natrK algC) -irr1_degree lin_char1 //. by rewrite (natrK 1) => A; rewrite trace_mx11 -mx11_scalar. Qed. Fact linear_char_divr : divr_closed (@linear_char G). Proof. split=> [|chi xi Lchi Lxi]; first exact: cfun1_lin_char. rewrite invr_lin_char // qualifE/= cfunE. by rewrite rpredM ?lin_char1 ?mulr1 ?lin_charW //= cfConjC_lin_char. Qed. HB.instance Definition _ := GRing.isDivClosed.Build (classfun G) linear_char_pred linear_char_divr. Lemma irr_cyclic_lin i : cyclic G -> 'chi[G]_i \is a linear_char. Proof. by move/cyclic_abelian/char_abelianP. Qed. Lemma irr_prime_lin i : prime #|G| -> 'chi[G]_i \is a linear_char. Proof. by move/prime_cyclic/irr_cyclic_lin. Qed. End Linear. Prenex Implicits linear_char. Arguments linear_char_pred _ _ _ /. Section OrthogonalityRelations. Variables aT gT : finGroupType. (* This is Isaacs, Lemma (2.15) *) Lemma repr_rsim_diag (G : {group gT}) f (rG : mx_representation algC G f) x : x \in G -> let chi := cfRepr rG in exists e, [/\ (*a*) exists2 B, B \in unitmx & rG x = invmx B *m diag_mx e *m B, (*b*) (forall i, e 0 i ^+ #[x] = 1) /\ (forall i, `|e 0 i| = 1), (*c*) chi x = \sum_i e 0 i /\ `|chi x| <= chi 1%g & (*d*) chi x^-1%g = (chi x)^*]. Proof. move=> Gx; without loss cGG: G rG Gx / abelian G. have sXG: <[x]> \subset G by rewrite cycle_subG. move/(_ _ (subg_repr rG sXG) (cycle_id x) (cycle_abelian x)). by rewrite /= !cfunE !groupV Gx (cycle_id x) !group1. have [I U W simU W1 dxW]: mxsemisimple rG 1%:M. rewrite -(reducible_Socle1 (DecSocleType rG) (mx_Maschke_pchar _ (algC'G_pchar G))). exact: Socle_semisimple. have linU i: \rank (U i) = 1. by apply: mxsimple_abelian_linear cGG (simU i); apply: groupC. have castI: f = #|I|. by rewrite -(mxrank1 algC f) -W1 (eqnP dxW) /= -sum1_card; apply/eq_bigr. pose B := \matrix_j nz_row (U (enum_val (cast_ord castI j))). have rowU i: (nz_row (U i) :=: U i)%MS. apply/eqmxP; rewrite -(geq_leqif (mxrank_leqif_eq (nz_row_sub _))) linU. by rewrite lt0n mxrank_eq0 (nz_row_mxsimple (simU i)). have unitB: B \in unitmx. rewrite -row_full_unit -sub1mx -W1; apply/sumsmx_subP=> i _. pose j := cast_ord (esym castI) (enum_rank i). by rewrite (submx_trans _ (row_sub j B)) // rowK cast_ordKV enum_rankK rowU. pose e := \row_j row j (B *m rG x *m invmx B) 0 j. have rGx: rG x = invmx B *m diag_mx e *m B. rewrite -mulmxA; apply: canRL (mulKmx unitB) _. apply/row_matrixP=> j; rewrite 2!row_mul; set u := row j B. have /sub_rVP[a def_ux]: (u *m rG x <= u)%MS. rewrite /u rowK rowU (eqmxMr _ (rowU _)). exact: (mxmoduleP (mxsimple_module (simU _))). rewrite def_ux [u]rowE scalemxAl; congr (_ *m _). apply/rowP=> k; rewrite 5!mxE !row_mul def_ux [u]rowE scalemxAl mulmxK //. by rewrite !mxE !eqxx !mulr_natr eq_sym. have exp_e j: e 0 j ^+ #[x] = 1. suffices: (diag_mx e j j) ^+ #[x] = (B *m rG (x ^+ #[x])%g *m invmx B) j j. by rewrite expg_order repr_mx1 mulmx1 mulmxV // [e]lock !mxE eqxx. elim: #[x] => [|n IHn]; first by rewrite repr_mx1 mulmx1 mulmxV // !mxE eqxx. rewrite expgS repr_mxM ?groupX // {1}rGx -!mulmxA mulKVmx //. by rewrite mul_diag_mx mulmxA [M in _ = M]mxE -IHn exprS {1}mxE eqxx. have norm1_e j: `|e 0 j| = 1. by apply/eqP; rewrite -(@pexpr_eq1 _ _ #[x]) // -normrX exp_e normr1. exists e; split=> //; first by exists B. rewrite cfRepr1 !cfunE Gx rGx mxtrace_mulC mulKVmx // mxtrace_diag. split=> //=; apply: (le_trans (ler_norm_sum _ _ _)). by rewrite (eq_bigr _ (in1W norm1_e)) sumr_const card_ord lexx. rewrite !cfunE groupV !mulrb Gx rGx mxtrace_mulC mulKVmx //. rewrite -trace_map_mx map_diag_mx; set d' := diag_mx _. rewrite -[d'](mulKVmx unitB) mxtrace_mulC -[_ *m _](repr_mxK rG Gx) rGx. rewrite -!mulmxA mulKVmx // (mulmxA d'). suffices->: d' *m diag_mx e = 1%:M by rewrite mul1mx mulKmx. rewrite mulmx_diag -diag_const_mx; congr diag_mx; apply/rowP=> j. by rewrite [e]lock !mxE mulrC -normCK -lock norm1_e expr1n. Qed. Variables (A : {group aT}) (G : {group gT}). (* This is Isaacs, Lemma (2.15) (d). *) Lemma char_inv (chi : 'CF(G)) x : chi \is a character -> chi x^-1%g = (chi x)^*. Proof. case Gx: (x \in G); last by rewrite !cfun0 ?rmorph0 ?groupV ?Gx. by case/char_reprP=> rG ->; have [e [_ _ _]] := repr_rsim_diag rG Gx. Qed. Lemma irr_inv i x : 'chi[G]_i x^-1%g = ('chi_i x)^*. Proof. exact/char_inv/irr_char. Qed. (* This is Isaacs, Theorem (2.13). *) Theorem generalized_orthogonality_relation y (i j : Iirr G) : #|G|%:R^-1 * (\sum_(x in G) 'chi_i (x * y)%g * 'chi_j x^-1%g) = (i == j)%:R * ('chi_i y / 'chi_i 1%g). Proof. pose W := @socle_of_Iirr _ G; pose e k := Wedderburn_id (W k). pose aG := regular_repr algC G. have [Gy | notGy] := boolP (y \in G); last first. rewrite cfun0 // mul0r big1 ?mulr0 // => x Gx. by rewrite cfun0 ?groupMl ?mul0r. transitivity (('chi_i).[e j *m aG y]%CF / 'chi_j 1%g). rewrite [e j]Wedderburn_id_expansion -scalemxAl xcfunZr -mulrA; congr (_ * _). rewrite mulmx_suml raddf_sum big_distrl; apply: eq_bigr => x Gx /=. rewrite -scalemxAl xcfunZr -repr_mxM // xcfunG ?groupM // mulrAC mulrC. by congr (_ * _); rewrite mulrC mulKf ?irr1_neq0. rewrite mulr_natl mulrb; have [<-{j} | neq_ij] := eqVneq. by congr (_ / _); rewrite xcfun_mul_id ?envelop_mx_id ?xcfunG. rewrite (xcfun_annihilate neq_ij) ?mul0r //. case/andP: (Wedderburn_ideal (W j)) => _; apply: submx_trans. by rewrite mem_mulsmx ?Wedderburn_id_mem ?envelop_mx_id. Qed. (* This is Isaacs, Corollary (2.14). *) Corollary first_orthogonality_relation (i j : Iirr G) : #|G|%:R^-1 * (\sum_(x in G) 'chi_i x * 'chi_j x^-1%g) = (i == j)%:R. Proof. have:= generalized_orthogonality_relation 1 i j. rewrite mulrA mulfK ?irr1_neq0 // => <-; congr (_ * _). by apply: eq_bigr => x; rewrite mulg1. Qed. (* The character table. *) Definition irr_class i := enum_val (cast_ord (NirrE G) i). Definition class_Iirr xG := cast_ord (esym (NirrE G)) (enum_rank_in (classes1 G) xG). Local Notation c := irr_class. Local Notation g i := (repr (c i)). Local Notation iC := class_Iirr. Definition character_table := \matrix_(i, j) 'chi[G]_i (g j). Local Notation X := character_table. Lemma irr_classP i : c i \in classes G. Proof. exact: enum_valP. Qed. Lemma repr_irr_classK i : g i ^: G = c i. Proof. by case/repr_classesP: (irr_classP i). Qed. Lemma irr_classK : cancel c iC. Proof. by move=> i; rewrite /iC enum_valK_in cast_ordK. Qed. Lemma class_IirrK : {in classes G, cancel iC c}. Proof. by move=> xG GxG; rewrite /c cast_ordKV enum_rankK_in. Qed. Lemma reindex_irr_class R idx (op : @Monoid.com_law R idx) F : \big[op/idx]_(xG in classes G) F xG = \big[op/idx]_i F (c i). Proof. rewrite (reindex c); first by apply: eq_bigl => i; apply: enum_valP. by exists iC; [apply: in1W; apply: irr_classK | apply: class_IirrK]. Qed. (* The explicit value of the inverse is needed for the proof of the second *) (* orthogonality relation. *) Let X' := \matrix_(i, j) (#|'C_G[g i]|%:R^-1 * ('chi[G]_j (g i))^*). Let XX'_1: X *m X' = 1%:M. Proof. apply/matrixP=> i j; rewrite !mxE -first_orthogonality_relation mulr_sumr. rewrite sum_by_classes => [|u v Gu Gv]; last by rewrite -conjVg !cfunJ. rewrite reindex_irr_class /=; apply/esym/eq_bigr=> k _. rewrite !mxE irr_inv // -/(g k) -divg_index -indexgI /=. rewrite (pchar0_natf_div Cpchar) ?dvdn_indexg // index_cent1 invfM invrK. by rewrite repr_irr_classK mulrCA mulrA mulrCA. Qed. Lemma character_table_unit : X \in unitmx. Proof. by case/mulmx1_unit: XX'_1. Qed. Let uX := character_table_unit. (* This is Isaacs, Theorem (2.18). *) Theorem second_orthogonality_relation x y : y \in G -> \sum_i 'chi[G]_i x * ('chi_i y)^* = #|'C_G[x]|%:R *+ (x \in y ^: G). Proof. move=> Gy; pose i_x := iC (x ^: G); pose i_y := iC (y ^: G). have [Gx | notGx] := boolP (x \in G); last first. rewrite (contraNF (subsetP _ x) notGx) ?class_subG ?big1 // => i _. by rewrite cfun0 ?mul0r. transitivity ((#|'C_G[repr (y ^: G)]|%:R *: (X' *m X)) i_y i_x). rewrite scalemxAl !mxE; apply: eq_bigr => k _; rewrite !mxE mulrC -!mulrA. by rewrite !class_IirrK ?mem_classes // !cfun_repr mulVKf ?neq0CG. rewrite mulmx1C // !mxE -!divg_index; do 2!rewrite -indexgI index_cent1. rewrite (class_eqP (mem_repr y _)) ?class_refl // mulr_natr. rewrite (can_in_eq class_IirrK) ?mem_classes //. have [-> | not_yGx] := eqVneq; first by rewrite class_refl. by rewrite [x \in _](contraNF _ not_yGx) // => /class_eqP->. Qed. Lemma eq_irr_mem_classP x y : y \in G -> reflect (forall i, 'chi[G]_i x = 'chi_i y) (x \in y ^: G). Proof. move=> Gy; apply: (iffP idP) => [/imsetP[z Gz ->] i | xGy]; first exact: cfunJ. have Gx: x \in G. congr is_true: Gy; apply/eqP; rewrite -(can_eq oddb) -eqC_nat -!cfun1E. by rewrite -irr0 xGy. congr is_true: (class_refl G x); apply/eqP; rewrite -(can_eq oddb). rewrite -(eqn_pmul2l (cardG_gt0 'C_G[x])) -eqC_nat !mulrnA; apply/eqP. by rewrite -!second_orthogonality_relation //; apply/eq_bigr=> i _; rewrite xGy. Qed. (* This is Isaacs, Theorem (6.32) (due to Brauer). *) Lemma card_afix_irr_classes (ito : action A (Iirr G)) (cto : action A _) a : a \in A -> [acts A, on classes G | cto] -> (forall i x y, x \in G -> y \in cto (x ^: G) a -> 'chi_i x = 'chi_(ito i a) y) -> #|'Fix_ito[a]| = #|'Fix_(classes G | cto)[a]|. Proof. move=> Aa actsAG stabAchi; apply/eqP; rewrite -eqC_nat; apply/eqP. have [[cP cK] iCK] := (irr_classP, irr_classK, class_IirrK). pose icto b i := iC (cto (c i) b). have Gca i: cto (c i) a \in classes G by rewrite (acts_act actsAG). have inj_qa: injective (icto a). by apply: can_inj (icto a^-1%g) _ => i; rewrite /icto iCK ?actKin ?cK. pose Pa : 'M[algC]_(Nirr G) := perm_mx (actperm ito a). pose qa := perm inj_qa; pose Qa : 'M[algC]_(Nirr G) := perm_mx qa^-1^-1%g. transitivity (\tr Pa). rewrite -sumr_const big_mkcond; apply: eq_bigr => i _. by rewrite !mxE permE inE sub1set inE; case: ifP. symmetry; transitivity (\tr Qa). rewrite cardsE -sumr_const -big_filter_cond big_mkcond big_filter /=. rewrite reindex_irr_class; apply: eq_bigr => i _; rewrite !mxE invgK permE. by rewrite inE sub1set inE -(can_eq cK) iCK //; case: ifP. rewrite -[Pa](mulmxK uX) -[Qa](mulKmx uX) mxtrace_mulC; congr (\tr(_ *m _)). rewrite -row_permE -col_permE; apply/matrixP=> i j; rewrite !mxE. rewrite -{2}[j](permKV qa); move: {j}(_ j) => j; rewrite !permE iCK //. apply: stabAchi; first by case/repr_classesP: (cP j). by rewrite repr_irr_classK (mem_repr_classes (Gca _)). Qed. End OrthogonalityRelations. Prenex Implicits irr_class class_Iirr irr_classK. Arguments class_IirrK {gT G%_G} [xG%_g] GxG : rename. Arguments character_table {gT} G%_g. Section InnerProduct. Variable (gT : finGroupType) (G : {group gT}). Lemma cfdot_irr i j : '['chi_i, 'chi_j]_G = (i == j)%:R. Proof. rewrite -first_orthogonality_relation; congr (_ * _). by apply: eq_bigr => x Gx; rewrite irr_inv. Qed. Lemma cfnorm_irr i : '['chi[G]_i] = 1. Proof. by rewrite cfdot_irr eqxx. Qed. Lemma irr_orthonormal : orthonormal (irr G). Proof. apply/orthonormalP; split; first exact: free_uniq (irr_free G). move=> _ _ /irrP[i ->] /irrP[j ->]. by rewrite cfdot_irr (inj_eq irr_inj). Qed. Lemma coord_cfdot phi i : coord (irr G) i phi = '[phi, 'chi_i]. Proof. rewrite {2}(coord_basis (irr_basis G) (memvf phi)). rewrite cfdot_suml (bigD1 i) // cfdotZl /= -tnth_nth cfdot_irr eqxx mulr1. rewrite big1 ?addr0 // => j neq_ji; rewrite cfdotZl /= -tnth_nth cfdot_irr. by rewrite (negbTE neq_ji) mulr0. Qed. Lemma cfun_sum_cfdot phi : phi = \sum_i '[phi, 'chi_i]_G *: 'chi_i. Proof. rewrite {1}(coord_basis (irr_basis G) (memvf phi)). by apply: eq_bigr => i _; rewrite coord_cfdot -tnth_nth. Qed. Lemma cfdot_sum_irr phi psi : '[phi, psi]_G = \sum_i '[phi, 'chi_i] * '[psi, 'chi_i]^*. Proof. rewrite {1}[phi]cfun_sum_cfdot cfdot_suml; apply: eq_bigr => i _. by rewrite cfdotZl -cfdotC. Qed. Lemma Cnat_cfdot_char_irr i phi : phi \is a character -> '[phi, 'chi_i]_G \in Num.nat. Proof. by move/forallP/(_ i); rewrite coord_cfdot. Qed. Lemma cfdot_char_r phi chi : chi \is a character -> '[phi, chi]_G = \sum_i '[phi, 'chi_i] * '[chi, 'chi_i]. Proof. move=> Nchi; rewrite cfdot_sum_irr; apply: eq_bigr => i _; congr (_ * _). by rewrite conj_natr ?Cnat_cfdot_char_irr. Qed. Lemma Cnat_cfdot_char chi xi : chi \is a character -> xi \is a character -> '[chi, xi]_G \in Num.nat. Proof. move=> Nchi Nxi; rewrite cfdot_char_r ?rpred_sum // => i _. by rewrite rpredM ?Cnat_cfdot_char_irr. Qed. Lemma cfdotC_char chi xi : chi \is a character-> xi \is a character -> '[chi, xi]_G = '[xi, chi]. Proof. by move=> Nchi Nxi; rewrite cfdotC conj_natr ?Cnat_cfdot_char. Qed. Lemma irrEchar chi : (chi \in irr G) = (chi \is a character) && ('[chi] == 1). Proof. apply/irrP/andP=> [[i ->] | [Nchi]]; first by rewrite irr_char cfnorm_irr. rewrite cfdot_sum_irr => /eqP/natr_sum_eq1[i _| i [_ ci1 cj0]]. by rewrite rpredM // ?conj_natr ?Cnat_cfdot_char_irr. exists i; rewrite [chi]cfun_sum_cfdot (bigD1 i) //=. rewrite -(normr_idP (natr_ge0 (Cnat_cfdot_char_irr i Nchi))). rewrite normC_def {}ci1 sqrtC1 scale1r big1 ?addr0 // => j neq_ji. by rewrite (('[_] =P 0) _) ?scale0r // -normr_eq0 normC_def cj0 ?sqrtC0. Qed. Lemma irrWchar chi : chi \in irr G -> chi \is a character. Proof. by rewrite irrEchar => /andP[]. Qed. Lemma irrWnorm chi : chi \in irr G -> '[chi] = 1. Proof. by rewrite irrEchar => /andP[_ /eqP]. Qed. Lemma mul_lin_irr xi chi : xi \is a linear_char -> chi \in irr G -> xi * chi \in irr G. Proof. move=> Lxi; rewrite !irrEchar => /andP[Nphi /eqP <-]. rewrite rpredM // ?lin_charW //=; apply/eqP; congr (_ * _). apply: eq_bigr=> x Gx; rewrite !cfunE rmorphM/= mulrACA -(lin_charV_conj Lxi)//. by rewrite -lin_charM ?groupV // mulgV lin_char1 ?mul1r. Qed. Lemma eq_scaled_irr a b i j : (a *: 'chi[G]_i == b *: 'chi_j) = (a == b) && ((a == 0) || (i == j)). Proof. apply/eqP/andP=> [|[/eqP-> /pred2P[]-> //]]; last by rewrite !scale0r. move/(congr1 (cfdotr 'chi__)) => /= eq_ai_bj. move: {eq_ai_bj}(eq_ai_bj i) (esym (eq_ai_bj j)); rewrite !cfdotZl !cfdot_irr. by rewrite !mulr_natr !mulrb !eqxx eq_sym orbC; case: ifP => _ -> //= ->. Qed. Lemma eq_signed_irr (s t : bool) i j : ((-1) ^+ s *: 'chi[G]_i == (-1) ^+ t *: 'chi_j) = (s == t) && (i == j). Proof. by rewrite eq_scaled_irr signr_eq0 (inj_eq signr_inj). Qed. Lemma eq_scale_irr a (i j : Iirr G) : (a *: 'chi_i == a *: 'chi_j) = (a == 0) || (i == j). Proof. by rewrite eq_scaled_irr eqxx. Qed. Lemma eq_addZ_irr a b (i j r t : Iirr G) : (a *: 'chi_i + b *: 'chi_j == a *: 'chi_r + b *: 'chi_t) = [|| [&& (a == 0) || (i == r) & (b == 0) || (j == t)], [&& i == t, j == r & a == b] | [&& i == j, r == t & a == - b]]. Proof. rewrite -!eq_scale_irr; apply/eqP/idP; last first. case/orP; first by case/andP=> /eqP-> /eqP->. case/orP=> /and3P[/eqP-> /eqP-> /eqP->]; first by rewrite addrC. by rewrite !scaleNr !addNr. have [-> /addrI/eqP-> // | /=] := eqVneq. rewrite eq_scale_irr => /norP[/negP nz_a /negPf neq_ir]. move/(congr1 (cfdotr 'chi__))/esym/eqP => /= eq_cfdot. move: {eq_cfdot}(eq_cfdot i) (eq_cfdot r); rewrite eq_sym !cfdotDl !cfdotZl. rewrite !cfdot_irr !mulr_natr !mulrb !eqxx -!(eq_sym i) neq_ir !add0r. have [<- _ | _] := i =P t; first by rewrite neq_ir addr0; case: ifP => // _ ->. rewrite 2!fun_if if_arg addr0 addr_eq0; case: eqP => //= <- ->. by rewrite neq_ir 2!fun_if if_arg eq_sym addr0; case: ifP. Qed. Lemma eq_subZnat_irr (a b : nat) (i j r t : Iirr G) : (a%:R *: 'chi_i - b%:R *: 'chi_j == a%:R *: 'chi_r - b%:R *: 'chi_t) = [|| a == 0 | i == r] && [|| b == 0 | j == t] || [&& i == j, r == t & a == b]. Proof. rewrite -!scaleNr eq_addZ_irr oppr_eq0 opprK -addr_eq0 -natrD eqr_nat. by rewrite !pnatr_eq0 addn_eq0; case: a b => [|a] [|b]; rewrite ?andbF. Qed. End InnerProduct. Section IrrConstt. Variable (gT : finGroupType) (G H : {group gT}). Lemma char1_ge_norm (chi : 'CF(G)) x : chi \is a character -> `|chi x| <= chi 1%g. Proof. case/char_reprP=> rG ->; case Gx: (x \in G); last first. by rewrite cfunE cfRepr1 Gx normr0 ler0n. by have [e [_ _ []]] := repr_rsim_diag rG Gx. Qed. Lemma max_cfRepr_norm_scalar n (rG : mx_representation algC G n) x : x \in G -> `|cfRepr rG x| = cfRepr rG 1%g -> exists2 c, `|c| = 1 & rG x = c%:M. Proof. move=> Gx; have [e [[B uB def_x] [_ e1] [-> _] _]] := repr_rsim_diag rG Gx. rewrite cfRepr1 -[n in n%:R]card_ord -sumr_const -(eq_bigr _ (in1W e1)). case/normC_sum_eq1=> [i _ | c /eqP norm_c_1 def_e]; first by rewrite e1. have{} def_e: e = const_mx c by apply/rowP=> i; rewrite mxE def_e ?andbT. by exists c => //; rewrite def_x def_e diag_const_mx scalar_mxC mulmxKV. Qed. Lemma max_cfRepr_mx1 n (rG : mx_representation algC G n) x : x \in G -> cfRepr rG x = cfRepr rG 1%g -> rG x = 1%:M. Proof. move=> Gx kerGx; have [|c _ def_x] := @max_cfRepr_norm_scalar n rG x Gx. by rewrite kerGx cfRepr1 normr_nat. move/eqP: kerGx; rewrite cfRepr1 cfunE Gx {rG}def_x mxtrace_scalar. case: n => [_|n]; first by rewrite ![_%:M]flatmx0. rewrite mulrb -subr_eq0 -mulrnBl -mulr_natl mulf_eq0 pnatr_eq0 /=. by rewrite subr_eq0 => /eqP->. Qed. Definition irr_constt (B : {set gT}) phi := [pred i | '[phi, 'chi_i]_B != 0]. Lemma irr_consttE i phi : (i \in irr_constt phi) = ('[phi, 'chi_i]_G != 0). Proof. by []. Qed. Lemma constt_charP (i : Iirr G) chi : chi \is a character -> reflect (exists2 chi', chi' \is a character & chi = 'chi_i + chi') (i \in irr_constt chi). Proof. move=> Nchi; apply: (iffP idP) => [i_in_chi| [chi' Nchi' ->]]; last first. rewrite inE /= cfdotDl cfdot_irr eqxx -(eqP (Cnat_cfdot_char_irr i Nchi')). by rewrite -natrD pnatr_eq0. exists (chi - 'chi_i); last by rewrite addrC subrK. apply/forallP=> j; rewrite coord_cfdot cfdotBl cfdot_irr. have [<- | _] := eqP; last by rewrite subr0 Cnat_cfdot_char_irr. move: i_in_chi; rewrite inE; case/natrP: (Cnat_cfdot_char_irr i Nchi) => n ->. by rewrite pnatr_eq0 -lt0n => /natrB <-; apply: rpred_nat. Qed. Lemma cfun_sum_constt (phi : 'CF(G)) : phi = \sum_(i in irr_constt phi) '[phi, 'chi_i] *: 'chi_i. Proof. rewrite {1}[phi]cfun_sum_cfdot (bigID [pred i | '[phi, 'chi_i] == 0]) /=. by rewrite big1 ?add0r // => i /eqP->; rewrite scale0r. Qed. Lemma neq0_has_constt (phi : 'CF(G)) : phi != 0 -> exists i, i \in irr_constt phi. Proof. move=> nz_phi; apply/existsP; apply: contra nz_phi => /pred0P phi0. by rewrite [phi]cfun_sum_constt big_pred0. Qed. Lemma constt_irr i : irr_constt 'chi[G]_i =i pred1 i. Proof. by move=> j; rewrite !inE cfdot_irr pnatr_eq0 (eq_sym j); case: (i == j). Qed. Lemma char1_ge_constt (i : Iirr G) chi : chi \is a character -> i \in irr_constt chi -> 'chi_i 1%g <= chi 1%g. Proof. move=> {chi} _ /constt_charP[// | chi Nchi ->]. by rewrite cfunE addrC -subr_ge0 addrK char1_ge0. Qed. Lemma constt_ortho_char (phi psi : 'CF(G)) i j : phi \is a character -> psi \is a character -> i \in irr_constt phi -> j \in irr_constt psi -> '[phi, psi] = 0 -> '['chi_i, 'chi_j] = 0. Proof. move=> _ _ /constt_charP[//|phi1 Nphi1 ->] /constt_charP[//|psi1 Npsi1 ->]. rewrite cfdot_irr; case: eqP => // -> /eqP/idPn[]. rewrite cfdotDl !cfdotDr cfnorm_irr -addrA gt_eqF ?ltr_wpDr ?ltr01 //. by rewrite natr_ge0 ?rpredD ?Cnat_cfdot_char ?irr_char. Qed. End IrrConstt. Arguments irr_constt {gT B%_g} phi%_CF. Section Kernel. Variable (gT : finGroupType) (G : {group gT}). Implicit Types (phi chi xi : 'CF(G)) (H : {group gT}). Lemma cfker_repr n (rG : mx_representation algC G n) : cfker (cfRepr rG) = rker rG. Proof. apply/esym/setP=> x; rewrite inE mul1mx /=. case Gx: (x \in G); last by rewrite inE Gx. apply/eqP/idP=> Kx; last by rewrite max_cfRepr_mx1 // cfker1. rewrite inE Gx; apply/forallP=> y; rewrite !cfunE !mulrb groupMl //. by case: ifP => // Gy; rewrite repr_mxM // Kx mul1mx. Qed. Lemma cfkerEchar chi : chi \is a character -> cfker chi = [set x in G | chi x == chi 1%g]. Proof. move=> Nchi; apply/setP=> x; apply/idP/setIdP=> [Kx | [Gx /eqP chi_x]]. by rewrite (subsetP (cfker_sub chi)) // cfker1. case/char_reprP: Nchi => rG -> in chi_x *; rewrite inE Gx; apply/forallP=> y. rewrite !cfunE groupMl // !mulrb; case: ifP => // Gy. by rewrite repr_mxM // max_cfRepr_mx1 ?mul1mx. Qed. Lemma cfker_nzcharE chi : chi \is a character -> chi != 0 -> cfker chi = [set x | chi x == chi 1%g]. Proof. move=> Nchi nzchi; apply/setP=> x; rewrite cfkerEchar // !inE andb_idl //. by apply: contraLR => /cfun0-> //; rewrite eq_sym char1_eq0. Qed. Lemma cfkerEirr i : cfker 'chi[G]_i = [set x | 'chi_i x == 'chi_i 1%g]. Proof. by rewrite cfker_nzcharE ?irr_char ?irr_neq0. Qed. Lemma cfker_irr0 : cfker 'chi[G]_0 = G. Proof. by rewrite irr0 cfker_cfun1. Qed. Lemma cfaithful_reg : cfaithful (cfReg G). Proof. apply/subsetP=> x; rewrite cfkerEchar ?cfReg_char // !inE !cfRegE eqxx. by case/andP=> _; apply: contraLR => /negbTE->; rewrite eq_sym neq0CG. Qed. Lemma cfkerE chi : chi \is a character -> cfker chi = G :&: \bigcap_(i in irr_constt chi) cfker 'chi_i. Proof. move=> Nchi; rewrite cfkerEchar //; apply/setP=> x; rewrite !inE. apply: andb_id2l => Gx; rewrite {1 2}[chi]cfun_sum_constt !sum_cfunE. apply/eqP/bigcapP=> [Kx i Ci | Kx]; last first. by apply: eq_bigr => i /Kx Kx_i; rewrite !cfunE cfker1. rewrite cfkerEirr inE /= -(inj_eq (mulfI Ci)). have:= (normC_sum_upper _ Kx) i; rewrite !cfunE => -> // {Ci}i _. have chi_i_ge0: 0 <= '[chi, 'chi_i]. by rewrite natr_ge0 ?Cnat_cfdot_char_irr. by rewrite !cfunE normrM (normr_idP _) ?ler_wpM2l ?char1_ge_norm ?irr_char. Qed. Lemma TI_cfker_irr : \bigcap_i cfker 'chi[G]_i = [1]. Proof. apply/trivgP; apply: subset_trans cfaithful_reg; rewrite cfkerE ?cfReg_char //. rewrite subsetI (bigcap_min 0) //=; last by rewrite cfker_irr0. by apply/bigcapsP=> i _; rewrite bigcap_inf. Qed. Lemma cfker_constt i chi : chi \is a character -> i \in irr_constt chi -> cfker chi \subset cfker 'chi[G]_i. Proof. by move=> Nchi Ci; rewrite cfkerE ?subIset ?(bigcap_min i) ?orbT. Qed. Section KerLin. Variable xi : 'CF(G). Hypothesis lin_xi : xi \is a linear_char. Let Nxi: xi \is a character. Proof. by have [] := andP lin_xi. Qed. Lemma lin_char_der1 : G^`(1)%g \subset cfker xi. Proof. rewrite gen_subG /=; apply/subsetP=> _ /imset2P[x y Gx Gy ->]. rewrite cfkerEchar // inE groupR //= !lin_charM ?lin_charV ?in_group //. by rewrite mulrCA mulKf ?mulVf ?lin_char_neq0 // lin_char1. Qed. Lemma cforder_lin_char : #[xi]%CF = exponent (G / cfker xi)%g. Proof. apply/eqP; rewrite eqn_dvd; apply/andP; split. apply/dvdn_cforderP=> x Gx; rewrite -lin_charX // -cfQuoEker ?groupX //. rewrite morphX ?(subsetP (cfker_norm xi)) //= expg_exponent ?mem_quotient //. by rewrite cfQuo1 ?cfker_normal ?lin_char1. have abGbar: abelian (G / cfker xi) := sub_der1_abelian lin_char_der1. have [_ /morphimP[x Nx Gx ->] ->] := exponent_witness (abelian_nil abGbar). rewrite order_dvdn -morphX //= coset_id cfkerEchar // !inE groupX //=. by rewrite lin_charX ?lin_char1 // (dvdn_cforderP _ _ _). Qed. Lemma cforder_lin_char_dvdG : #[xi]%CF %| #|G|. Proof. by rewrite cforder_lin_char (dvdn_trans (exponent_dvdn _)) ?dvdn_morphim. Qed. Lemma cforder_lin_char_gt0 : (0 < #[xi]%CF)%N. Proof. by rewrite cforder_lin_char exponent_gt0. Qed. End KerLin. End Kernel. Section Restrict. Variable (gT : finGroupType) (G H : {group gT}). Lemma cfRepr_sub n (rG : mx_representation algC G n) (sHG : H \subset G) : cfRepr (subg_repr rG sHG) = 'Res[H] (cfRepr rG). Proof. by apply/cfun_inP => x Hx; rewrite cfResE // !cfunE Hx (subsetP sHG). Qed. Lemma cfRes_char chi : chi \is a character -> 'Res[H, G] chi \is a character. Proof. have [sHG | not_sHG] := boolP (H \subset G). by case/char_reprP=> rG ->; rewrite -(cfRepr_sub rG sHG) cfRepr_char. by move/Cnat_char1=> Nchi1; rewrite cfResEout // rpredZ_nat ?rpred1. Qed. Lemma cfRes_eq0 phi : phi \is a character -> ('Res[H, G] phi == 0) = (phi == 0). Proof. by move=> Nchi; rewrite -!char1_eq0 ?cfRes_char // cfRes1. Qed. Lemma cfRes_lin_char chi : chi \is a linear_char -> 'Res[H, G] chi \is a linear_char. Proof. by case/andP=> Nchi; rewrite qualifE/= cfRes_char ?cfRes1. Qed. Lemma Res_irr_neq0 i : 'Res[H, G] 'chi_i != 0. Proof. by rewrite cfRes_eq0 ?irr_neq0 ?irr_char. Qed. Lemma cfRes_lin_lin (chi : 'CF(G)) : chi \is a character -> 'Res[H] chi \is a linear_char -> chi \is a linear_char. Proof. by rewrite !qualifE/= !qualifE/= cfRes1 => -> /andP[]. Qed. Lemma cfRes_irr_irr chi : chi \is a character -> 'Res[H] chi \in irr H -> chi \in irr G. Proof. have [sHG /char_reprP[rG ->] | not_sHG Nchi] := boolP (H \subset G). rewrite -(cfRepr_sub _ sHG) => /irr_reprP[rH irrH def_rH]; apply/irr_reprP. suffices /subg_mx_irr: mx_irreducible (subg_repr rG sHG) by exists rG. by apply: mx_rsim_irr irrH; apply/cfRepr_rsimP/eqP. rewrite cfResEout // => /irrP[j Dchi_j]; apply/lin_char_irr/cfRes_lin_lin=> //. suffices j0: j = 0 by rewrite cfResEout // Dchi_j j0 irr0 rpred1. apply: contraNeq (irr1_neq0 j) => nz_j. have:= xcfun_id j 0; rewrite -Dchi_j cfunE xcfunZl -irr0 xcfun_id eqxx => ->. by rewrite (negPf nz_j). Qed. Definition Res_Iirr (A B : {set gT}) i := cfIirr ('Res[B, A] 'chi_i). Lemma Res_Iirr0 : Res_Iirr H (0 : Iirr G) = 0. Proof. by rewrite /Res_Iirr irr0 rmorph1 -irr0 irrK. Qed. Lemma lin_Res_IirrE i : 'chi[G]_i 1%g = 1 -> 'chi_(Res_Iirr H i) = 'Res 'chi_i. Proof. move=> chi1; rewrite cfIirrE ?lin_char_irr ?cfRes_lin_char //. by rewrite qualifE/= irr_char /= chi1. Qed. End Restrict. Arguments Res_Iirr {gT A%_g} B%_g i%_R. Section MoreConstt. Variables (gT : finGroupType) (G H : {group gT}). Lemma constt_Ind_Res i j : i \in irr_constt ('Ind[G] 'chi_j) = (j \in irr_constt ('Res[H] 'chi_i)). Proof. by rewrite !irr_consttE cfdotC conjC_eq0 -cfdot_Res_l. Qed. Lemma cfdot_Res_ge_constt i j psi : psi \is a character -> j \in irr_constt psi -> '['Res[H, G] 'chi_j, 'chi_i] <= '['Res[H] psi, 'chi_i]. Proof. move=> {psi} _ /constt_charP[// | psi Npsi ->]. rewrite linearD cfdotDl addrC -subr_ge0 addrK natr_ge0 //=. by rewrite Cnat_cfdot_char_irr // cfRes_char. Qed. Lemma constt_Res_trans j psi : psi \is a character -> j \in irr_constt psi -> {subset irr_constt ('Res[H, G] 'chi_j) <= irr_constt ('Res[H] psi)}. Proof. move=> Npsi Cj i; apply: contraNneq; rewrite eq_le => {1}<-. rewrite cfdot_Res_ge_constt ?natr_ge0 ?Cnat_cfdot_char_irr //. by rewrite cfRes_char ?irr_char. Qed. End MoreConstt. Section Morphim. Variables (aT rT : finGroupType) (G D : {group aT}) (f : {morphism D >-> rT}). Implicit Type chi : 'CF(f @* G). Lemma cfRepr_morphim n (rfG : mx_representation algC (f @* G) n) sGD : cfRepr (morphim_repr rfG sGD) = cfMorph (cfRepr rfG). Proof. apply/cfun_inP=> x Gx; have Dx: x \in D := subsetP sGD x Gx. by rewrite cfMorphE // !cfunE ?mem_morphim ?Gx. Qed. Lemma cfMorph_char chi : chi \is a character -> cfMorph chi \is a character. Proof. have [sGD /char_reprP[rfG ->] | outGD Nchi] := boolP (G \subset D); last first. by rewrite cfMorphEout // rpredZ_nat ?rpred1 ?Cnat_char1. apply/char_reprP; exists (Representation (morphim_repr rfG sGD)). by rewrite cfRepr_morphim. Qed. Lemma cfMorph_lin_char chi : chi \is a linear_char -> cfMorph chi \is a linear_char. Proof. by case/andP=> Nchi; rewrite qualifE/= cfMorph1 cfMorph_char. Qed. Lemma cfMorph_charE chi : G \subset D -> (cfMorph chi \is a character) = (chi \is a character). Proof. move=> sGD; apply/idP/idP=> [/char_reprP[[n rG] /=Dfchi] | /cfMorph_char//]. pose H := 'ker_G f; have kerH: H \subset rker rG. by rewrite -cfker_repr -Dfchi cfker_morph // setIS // ker_sub_pre. have nHG: G \subset 'N(H) by rewrite normsI // (subset_trans sGD) ?ker_norm. have [h injh im_h] := first_isom_loc f sGD; rewrite -/H in h injh im_h. have DfG: invm injh @*^-1 (G / H) == (f @* G)%g by rewrite morphpre_invm im_h. pose rfG := eqg_repr (morphpre_repr _ (quo_repr kerH nHG)) DfG. apply/char_reprP; exists (Representation rfG). apply/cfun_inP=> _ /morphimP[x Dx Gx ->]; rewrite -cfMorphE // Dfchi !cfunE Gx. pose xH := coset H x; have GxH: xH \in (G / H)%g by apply: mem_quotient. suffices Dfx: f x = h xH by rewrite mem_morphim //= Dfx invmE ?quo_repr_coset. by apply/set1_inj; rewrite -?morphim_set1 ?im_h ?(subsetP nHG) ?sub1set. Qed. Lemma cfMorph_lin_charE chi : G \subset D -> (cfMorph chi \is a linear_char) = (chi \is a linear_char). Proof. by rewrite qualifE/= cfMorph1 => /cfMorph_charE->. Qed. Lemma cfMorph_irr chi : G \subset D -> (cfMorph chi \in irr G) = (chi \in irr (f @* G)). Proof. by move=> sGD; rewrite !irrEchar cfMorph_charE // cfMorph_iso. Qed. Definition morph_Iirr i := cfIirr (cfMorph 'chi[f @* G]_i). Lemma morph_Iirr0 : morph_Iirr 0 = 0. Proof. by rewrite /morph_Iirr irr0 rmorph1 -irr0 irrK. Qed. Hypothesis sGD : G \subset D. Lemma morph_IirrE i : 'chi_(morph_Iirr i) = cfMorph 'chi_i. Proof. by rewrite cfIirrE ?cfMorph_irr ?mem_irr. Qed. Lemma morph_Iirr_inj : injective morph_Iirr. Proof. by move=> i j eq_ij; apply/irr_inj/cfMorph_inj; rewrite // -!morph_IirrE eq_ij. Qed. Lemma morph_Iirr_eq0 i : (morph_Iirr i == 0) = (i == 0). Proof. by rewrite -!irr_eq1 morph_IirrE cfMorph_eq1. Qed. End Morphim. Section Isom. Variables (aT rT : finGroupType) (G : {group aT}) (f : {morphism G >-> rT}). Variables (R : {group rT}) (isoGR : isom G R f). Implicit Type chi : 'CF(G). Lemma cfIsom_char chi : (cfIsom isoGR chi \is a character) = (chi \is a character). Proof. rewrite [cfIsom _]locked_withE cfMorph_charE //. by rewrite (isom_im (isom_sym _)) cfRes_id. Qed. Lemma cfIsom_lin_char chi : (cfIsom isoGR chi \is a linear_char) = (chi \is a linear_char). Proof. by rewrite qualifE/= cfIsom_char cfIsom1. Qed. Lemma cfIsom_irr chi : (cfIsom isoGR chi \in irr R) = (chi \in irr G). Proof. by rewrite !irrEchar cfIsom_char cfIsom_iso. Qed. Definition isom_Iirr i := cfIirr (cfIsom isoGR 'chi_i). Lemma isom_IirrE i : 'chi_(isom_Iirr i) = cfIsom isoGR 'chi_i. Proof. by rewrite cfIirrE ?cfIsom_irr ?mem_irr. Qed. Lemma isom_Iirr_inj : injective isom_Iirr. Proof. by move=> i j eqij; apply/irr_inj/(cfIsom_inj isoGR); rewrite -!isom_IirrE eqij. Qed. Lemma isom_Iirr_eq0 i : (isom_Iirr i == 0) = (i == 0). Proof. by rewrite -!irr_eq1 isom_IirrE cfIsom_eq1. Qed. Lemma isom_Iirr0 : isom_Iirr 0 = 0. Proof. by apply/eqP; rewrite isom_Iirr_eq0. Qed. End Isom. Arguments isom_Iirr_inj {aT rT G f R} isoGR [i1 i2] : rename. Section IsomInv. Variables (aT rT : finGroupType) (G : {group aT}) (f : {morphism G >-> rT}). Variables (R : {group rT}) (isoGR : isom G R f). Lemma isom_IirrK : cancel (isom_Iirr isoGR) (isom_Iirr (isom_sym isoGR)). Proof. by move=> i; apply: irr_inj; rewrite !isom_IirrE cfIsomK. Qed. Lemma isom_IirrKV : cancel (isom_Iirr (isom_sym isoGR)) (isom_Iirr isoGR). Proof. by move=> i; apply: irr_inj; rewrite !isom_IirrE cfIsomKV. Qed. End IsomInv. Section Sdprod. Variables (gT : finGroupType) (K H G : {group gT}). Hypothesis defG : K ><| H = G. Let nKG: G \subset 'N(K). Proof. by have [/andP[]] := sdprod_context defG. Qed. Lemma cfSdprod_char chi : (cfSdprod defG chi \is a character) = (chi \is a character). Proof. by rewrite unlock cfMorph_charE // cfIsom_char. Qed. Lemma cfSdprod_lin_char chi : (cfSdprod defG chi \is a linear_char) = (chi \is a linear_char). Proof. by rewrite qualifE/= cfSdprod_char cfSdprod1. Qed. Lemma cfSdprod_irr chi : (cfSdprod defG chi \in irr G) = (chi \in irr H). Proof. by rewrite !irrEchar cfSdprod_char cfSdprod_iso. Qed. Definition sdprod_Iirr j := cfIirr (cfSdprod defG 'chi_j). Lemma sdprod_IirrE j : 'chi_(sdprod_Iirr j) = cfSdprod defG 'chi_j. Proof. by rewrite cfIirrE ?cfSdprod_irr ?mem_irr. Qed. Lemma sdprod_IirrK : cancel sdprod_Iirr (Res_Iirr H). Proof. by move=> j; rewrite /Res_Iirr sdprod_IirrE cfSdprodK irrK. Qed. Lemma sdprod_Iirr_inj : injective sdprod_Iirr. Proof. exact: can_inj sdprod_IirrK. Qed. Lemma sdprod_Iirr_eq0 i : (sdprod_Iirr i == 0) = (i == 0). Proof. by rewrite -!irr_eq1 sdprod_IirrE cfSdprod_eq1. Qed. Lemma sdprod_Iirr0 : sdprod_Iirr 0 = 0. Proof. by apply/eqP; rewrite sdprod_Iirr_eq0. Qed. Lemma Res_sdprod_irr phi : K \subset cfker phi -> phi \in irr G -> 'Res phi \in irr H. Proof. move=> kerK /irrP[i Dphi]; rewrite irrEchar -(cfSdprod_iso defG). by rewrite cfRes_sdprodK // Dphi cfnorm_irr cfRes_char ?irr_char /=. Qed. Lemma sdprod_Res_IirrE i : K \subset cfker 'chi[G]_i -> 'chi_(Res_Iirr H i) = 'Res 'chi_i. Proof. by move=> kerK; rewrite cfIirrE ?Res_sdprod_irr ?mem_irr. Qed. Lemma sdprod_Res_IirrK i : K \subset cfker 'chi_i -> sdprod_Iirr (Res_Iirr H i) = i. Proof. by move=> kerK; rewrite /sdprod_Iirr sdprod_Res_IirrE ?cfRes_sdprodK ?irrK. Qed. End Sdprod. Arguments sdprod_Iirr_inj {gT K H G} defG [i1 i2] : rename. Section DProd. Variables (gT : finGroupType) (G K H : {group gT}). Hypothesis KxH : K \x H = G. Lemma cfDprodKl_abelian j : abelian H -> cancel ((cfDprod KxH)^~ 'chi_j) 'Res. Proof. by move=> cHH; apply: cfDprodKl; apply/lin_char1/char_abelianP. Qed. Lemma cfDprodKr_abelian i : abelian K -> cancel (cfDprod KxH 'chi_i) 'Res. Proof. by move=> cKK; apply: cfDprodKr; apply/lin_char1/char_abelianP. Qed. Lemma cfDprodl_char phi : (cfDprodl KxH phi \is a character) = (phi \is a character). Proof. exact: cfSdprod_char. Qed. Lemma cfDprodr_char psi : (cfDprodr KxH psi \is a character) = (psi \is a character). Proof. exact: cfSdprod_char. Qed. Lemma cfDprod_char phi psi : phi \is a character -> psi \is a character -> cfDprod KxH phi psi \is a character. Proof. by move=> Nphi Npsi; rewrite rpredM ?cfDprodl_char ?cfDprodr_char. Qed. Lemma cfDprod_eq1 phi psi : phi \is a character -> psi \is a character -> (cfDprod KxH phi psi == 1) = (phi == 1) && (psi == 1). Proof. move=> /Cnat_char1 Nphi /Cnat_char1 Npsi. apply/eqP/andP=> [phi_psi_1 | [/eqP-> /eqP->]]; last by rewrite cfDprod_cfun1. have /andP[/eqP phi1 /eqP psi1]: (phi 1%g == 1) && (psi 1%g == 1). by rewrite -natr_mul_eq1 // -(cfDprod1 KxH) phi_psi_1 cfun11. rewrite -[phi](cfDprodKl KxH psi1) -{2}[psi](cfDprodKr KxH phi1) phi_psi_1. by rewrite !rmorph1. Qed. Lemma cfDprodl_lin_char phi : (cfDprodl KxH phi \is a linear_char) = (phi \is a linear_char). Proof. exact: cfSdprod_lin_char. Qed. Lemma cfDprodr_lin_char psi : (cfDprodr KxH psi \is a linear_char) = (psi \is a linear_char). Proof. exact: cfSdprod_lin_char. Qed. Lemma cfDprod_lin_char phi psi : phi \is a linear_char -> psi \is a linear_char -> cfDprod KxH phi psi \is a linear_char. Proof. by move=> Nphi Npsi; rewrite rpredM ?cfSdprod_lin_char. Qed. Lemma cfDprodl_irr chi : (cfDprodl KxH chi \in irr G) = (chi \in irr K). Proof. exact: cfSdprod_irr. Qed. Lemma cfDprodr_irr chi : (cfDprodr KxH chi \in irr G) = (chi \in irr H). Proof. exact: cfSdprod_irr. Qed. Definition dprodl_Iirr i := cfIirr (cfDprodl KxH 'chi_i). Lemma dprodl_IirrE i : 'chi_(dprodl_Iirr i) = cfDprodl KxH 'chi_i. Proof. exact: sdprod_IirrE. Qed. Lemma dprodl_IirrK : cancel dprodl_Iirr (Res_Iirr K). Proof. exact: sdprod_IirrK. Qed. Lemma dprodl_Iirr_eq0 i : (dprodl_Iirr i == 0) = (i == 0). Proof. exact: sdprod_Iirr_eq0. Qed. Lemma dprodl_Iirr0 : dprodl_Iirr 0 = 0. Proof. exact: sdprod_Iirr0. Qed. Definition dprodr_Iirr j := cfIirr (cfDprodr KxH 'chi_j). Lemma dprodr_IirrE j : 'chi_(dprodr_Iirr j) = cfDprodr KxH 'chi_j. Proof. exact: sdprod_IirrE. Qed. Lemma dprodr_IirrK : cancel dprodr_Iirr (Res_Iirr H). Proof. exact: sdprod_IirrK. Qed. Lemma dprodr_Iirr_eq0 j : (dprodr_Iirr j == 0) = (j == 0). Proof. exact: sdprod_Iirr_eq0. Qed. Lemma dprodr_Iirr0 : dprodr_Iirr 0 = 0. Proof. exact: sdprod_Iirr0. Qed. Lemma cfDprod_irr i j : cfDprod KxH 'chi_i 'chi_j \in irr G. Proof. rewrite irrEchar cfDprod_char ?irr_char //=. by rewrite cfdot_dprod !cfdot_irr !eqxx mul1r. Qed. Definition dprod_Iirr ij := cfIirr (cfDprod KxH 'chi_ij.1 'chi_ij.2). Lemma dprod_IirrE i j : 'chi_(dprod_Iirr (i, j)) = cfDprod KxH 'chi_i 'chi_j. Proof. by rewrite cfIirrE ?cfDprod_irr. Qed. Lemma dprod_IirrEl i : 'chi_(dprod_Iirr (i, 0)) = cfDprodl KxH 'chi_i. Proof. by rewrite dprod_IirrE /cfDprod irr0 rmorph1 mulr1. Qed. Lemma dprod_IirrEr j : 'chi_(dprod_Iirr (0, j)) = cfDprodr KxH 'chi_j. Proof. by rewrite dprod_IirrE /cfDprod irr0 rmorph1 mul1r. Qed. Lemma dprod_Iirr_inj : injective dprod_Iirr. Proof. move=> [i1 j1] [i2 j2] /eqP; rewrite -[_ == _]oddb -(@natrK algC (_ == _)). rewrite -cfdot_irr !dprod_IirrE cfdot_dprod !cfdot_irr -natrM mulnb. by rewrite natrK oddb -xpair_eqE => /eqP. Qed. Lemma dprod_Iirr0 : dprod_Iirr (0, 0) = 0. Proof. by apply/irr_inj; rewrite dprod_IirrE !irr0 cfDprod_cfun1. Qed. Lemma dprod_Iirr0l j : dprod_Iirr (0, j) = dprodr_Iirr j. Proof. by apply/irr_inj; rewrite dprod_IirrE irr0 dprodr_IirrE cfDprod_cfun1l. Qed. Lemma dprod_Iirr0r i : dprod_Iirr (i, 0) = dprodl_Iirr i. Proof. by apply/irr_inj; rewrite dprod_IirrE irr0 dprodl_IirrE cfDprod_cfun1r. Qed. Lemma dprod_Iirr_eq0 i j : (dprod_Iirr (i, j) == 0) = (i == 0) && (j == 0). Proof. by rewrite -xpair_eqE -(inj_eq dprod_Iirr_inj) dprod_Iirr0. Qed. Lemma cfdot_dprod_irr i1 i2 j1 j2 : '['chi_(dprod_Iirr (i1, j1)), 'chi_(dprod_Iirr (i2, j2))] = ((i1 == i2) && (j1 == j2))%:R. Proof. by rewrite cfdot_irr (inj_eq dprod_Iirr_inj). Qed. Lemma dprod_Iirr_onto k : k \in codom dprod_Iirr. Proof. set D := codom _; have Df: dprod_Iirr _ \in D := codom_f dprod_Iirr _. have: 'chi_k 1%g ^+ 2 != 0 by rewrite mulf_neq0 ?irr1_neq0. apply: contraR => notDk; move/eqP: (irr_sum_square G). rewrite (bigID [in D]) (reindex _ (bij_on_codom dprod_Iirr_inj (0, 0))) /=. have ->: #|G|%:R = \sum_i \sum_j 'chi_(dprod_Iirr (i, j)) 1%g ^+ 2. rewrite -(dprod_card KxH) natrM. do 2![rewrite -irr_sum_square (mulr_suml, mulr_sumr); apply: eq_bigr => ? _]. by rewrite dprod_IirrE -exprMn -{3}(mulg1 1%g) cfDprodE. rewrite (eq_bigl _ _ Df) pair_bigA addrC -subr_eq0 addrK. by move/eqP/psumr_eq0P=> -> //= i _; rewrite irr1_degree -natrX ler0n. Qed. Definition inv_dprod_Iirr i := iinv (dprod_Iirr_onto i). Lemma dprod_IirrK : cancel dprod_Iirr inv_dprod_Iirr. Proof. by move=> p; apply: (iinv_f dprod_Iirr_inj). Qed. Lemma inv_dprod_IirrK : cancel inv_dprod_Iirr dprod_Iirr. Proof. by move=> i; apply: f_iinv. Qed. Lemma inv_dprod_Iirr0 : inv_dprod_Iirr 0 = (0, 0). Proof. by apply/(canLR dprod_IirrK); rewrite dprod_Iirr0. Qed. End DProd. Arguments dprod_Iirr_inj {gT G K H} KxH [i1 i2] : rename. Lemma dprod_IirrC (gT : finGroupType) (G K H : {group gT}) (KxH : K \x H = G) (HxK : H \x K = G) i j : dprod_Iirr KxH (i, j) = dprod_Iirr HxK (j, i). Proof. by apply: irr_inj; rewrite !dprod_IirrE; apply: cfDprodC. Qed. Section BigDprod. Variables (gT : finGroupType) (I : finType) (P : pred I). Variables (A : I -> {group gT}) (G : {group gT}). Hypothesis defG : \big[dprod/1%g]_(i | P i) A i = G. Let sAG i : P i -> A i \subset G. Proof. by move=> Pi; rewrite -(bigdprodWY defG) (bigD1 i) ?joing_subl. Qed. Lemma cfBigdprodi_char i (phi : 'CF(A i)) : phi \is a character -> cfBigdprodi defG phi \is a character. Proof. by move=> Nphi; rewrite cfDprodl_char cfRes_char. Qed. Lemma cfBigdprodi_charE i (phi : 'CF(A i)) : P i -> (cfBigdprodi defG phi \is a character) = (phi \is a character). Proof. by move=> Pi; rewrite cfDprodl_char Pi cfRes_id. Qed. Lemma cfBigdprod_char phi : (forall i, P i -> phi i \is a character) -> cfBigdprod defG phi \is a character. Proof. by move=> Nphi; apply: rpred_prod => i /Nphi; apply: cfBigdprodi_char. Qed. Lemma cfBigdprodi_lin_char i (phi : 'CF(A i)) : phi \is a linear_char -> cfBigdprodi defG phi \is a linear_char. Proof. by move=> Lphi; rewrite cfDprodl_lin_char ?cfRes_lin_char. Qed. Lemma cfBigdprodi_lin_charE i (phi : 'CF(A i)) : P i -> (cfBigdprodi defG phi \is a linear_char) = (phi \is a linear_char). Proof. by move=> Pi; rewrite qualifE/= cfBigdprodi_charE // cfBigdprodi1. Qed. Lemma cfBigdprod_lin_char phi : (forall i, P i -> phi i \is a linear_char) -> cfBigdprod defG phi \is a linear_char. Proof. by move=> Lphi; apply/rpred_prod=> i /Lphi; apply: cfBigdprodi_lin_char. Qed. Lemma cfBigdprodi_irr i chi : P i -> (cfBigdprodi defG chi \in irr G) = (chi \in irr (A i)). Proof. by move=> Pi; rewrite !irrEchar cfBigdprodi_charE ?cfBigdprodi_iso. Qed. Lemma cfBigdprod_irr chi : (forall i, P i -> chi i \in irr (A i)) -> cfBigdprod defG chi \in irr G. Proof. move=> Nchi; rewrite irrEchar cfBigdprod_char => [|i /Nchi/irrWchar] //=. by rewrite cfdot_bigdprod big1 // => i /Nchi/irrWnorm. Qed. Lemma cfBigdprod_eq1 phi : (forall i, P i -> phi i \is a character) -> (cfBigdprod defG phi == 1) = [forall (i | P i), phi i == 1]. Proof. move=> Nphi; set Phi := cfBigdprod defG phi. apply/eqP/eqfun_inP=> [Phi1 i Pi | phi1]; last first. by apply: big1 => i /phi1->; rewrite rmorph1. have Phi1_1: Phi 1%g = 1 by rewrite Phi1 cfun1E group1. have nz_Phi1: Phi 1%g != 0 by rewrite Phi1_1 oner_eq0. have [_ <-] := cfBigdprodK nz_Phi1 Pi. rewrite Phi1_1 divr1 -/Phi Phi1 rmorph1. rewrite prod_cfunE // in Phi1_1; have := natr_prod_eq1 _ Phi1_1 Pi. rewrite -(cfRes1 (A i)) cfBigdprodiK // => ->; first by rewrite scale1r. by move=> {i Pi} j /Nphi Nphi_j; rewrite Cnat_char1 ?cfBigdprodi_char. Qed. Lemma cfBigdprod_Res_lin chi : chi \is a linear_char -> cfBigdprod defG (fun i => 'Res[A i] chi) = chi. Proof. move=> Lchi; apply/cfun_inP=> _ /(mem_bigdprod defG)[x [Ax -> _]]. rewrite (lin_char_prod Lchi) ?cfBigdprodE // => [|i Pi]; last first. by rewrite (subsetP (sAG Pi)) ?Ax. by apply/eq_bigr=> i Pi; rewrite cfResE ?sAG ?Ax. Qed. Lemma cfBigdprodKlin phi : (forall i, P i -> phi i \is a linear_char) -> forall i, P i -> 'Res (cfBigdprod defG phi) = phi i. Proof. move=> Lphi i Pi; have Lpsi := cfBigdprod_lin_char Lphi. have [_ <-] := cfBigdprodK (lin_char_neq0 Lpsi (group1 G)) Pi. by rewrite !lin_char1 ?Lphi // divr1 scale1r. Qed. Lemma cfBigdprodKabelian Iphi (phi := fun i => 'chi_(Iphi i)) : abelian G -> forall i, P i -> 'Res (cfBigdprod defG phi) = 'chi_(Iphi i). Proof. move=> /(abelianS _) cGG. by apply: cfBigdprodKlin => i /sAG/cGG/char_abelianP->. Qed. End BigDprod. Section Aut. Variables (gT : finGroupType) (G : {group gT}). Implicit Type u : {rmorphism algC -> algC}. Lemma conjC_charAut u (chi : 'CF(G)) x : chi \is a character -> (u (chi x))^* = u (chi x)^*. Proof. have [Gx | /cfun0->] := boolP (x \in G); last by rewrite !rmorph0. case/char_reprP=> rG ->; have [e [_ [en1 _] [-> _] _]] := repr_rsim_diag rG Gx. by rewrite !rmorph_sum; apply: eq_bigr => i _; apply: aut_unity_rootC (en1 i). Qed. Lemma conjC_irrAut u i x : (u ('chi[G]_i x))^* = u ('chi_i x)^*. Proof. exact: conjC_charAut (irr_char i). Qed. Lemma cfdot_aut_char u (phi chi : 'CF(G)) : chi \is a character -> '[cfAut u phi, cfAut u chi] = u '[phi, chi]. Proof. by move/conjC_charAut=> Nchi; apply: cfdot_cfAut => _ /mapP[x _ ->]. Qed. Lemma cfdot_aut_irr u phi i : '[cfAut u phi, cfAut u 'chi[G]_i] = u '[phi, 'chi_i]. Proof. exact: cfdot_aut_char (irr_char i). Qed. Lemma cfAut_irr u chi : (cfAut u chi \in irr G) = (chi \in irr G). Proof. rewrite !irrEchar cfAut_char; apply/andb_id2l=> /cfdot_aut_char->. exact: fmorph_eq1. Qed. Lemma cfConjC_irr i : (('chi_i)^*)%CF \in irr G. Proof. by rewrite cfAut_irr mem_irr. Qed. Lemma irr_aut_closed u : cfAut_closed u (irr G). Proof. by move=> chi; rewrite /= cfAut_irr. Qed. Definition aut_Iirr u i := cfIirr (cfAut u 'chi[G]_i). Lemma aut_IirrE u i : 'chi_(aut_Iirr u i) = cfAut u 'chi_i. Proof. by rewrite cfIirrE ?cfAut_irr ?mem_irr. Qed. Definition conjC_Iirr := aut_Iirr conjC. Lemma conjC_IirrE i : 'chi[G]_(conjC_Iirr i) = ('chi_i)^*%CF. Proof. exact: aut_IirrE. Qed. Lemma conjC_IirrK : involutive conjC_Iirr. Proof. by move=> i; apply: irr_inj; rewrite !conjC_IirrE cfConjCK. Qed. Lemma aut_Iirr0 u : aut_Iirr u 0 = 0 :> Iirr G. Proof. by apply/irr_inj; rewrite aut_IirrE irr0 cfAut_cfun1. Qed. Lemma conjC_Iirr0 : conjC_Iirr 0 = 0 :> Iirr G. Proof. exact: aut_Iirr0. Qed. Lemma aut_Iirr_eq0 u i : (aut_Iirr u i == 0) = (i == 0). Proof. by rewrite -!irr_eq1 aut_IirrE cfAut_eq1. Qed. Lemma conjC_Iirr_eq0 i : (conjC_Iirr i == 0 :> Iirr G) = (i == 0). Proof. exact: aut_Iirr_eq0. Qed. Lemma aut_Iirr_inj u : injective (aut_Iirr u). Proof. by move=> i j eq_ij; apply/irr_inj/(cfAut_inj u); rewrite -!aut_IirrE eq_ij. Qed. End Aut. Arguments aut_Iirr_inj {gT G} u [i1 i2] : rename. Arguments conjC_IirrK {gT G} i : rename. Section Coset. Variable (gT : finGroupType). Implicit Types G H : {group gT}. Lemma cfQuo_char G H (chi : 'CF(G)) : chi \is a character -> (chi / H)%CF \is a character. Proof. move=> Nchi; without loss kerH: / H \subset cfker chi. move/contraNF=> IHchi; apply/wlog_neg=> N'chiH. suffices ->: (chi / H)%CF = (chi 1%g)%:A. by rewrite rpredZ_nat ?Cnat_char1 ?rpred1. by apply/cfunP=> x; rewrite cfunE cfun1E mulr_natr cfunElock IHchi. without loss nsHG: G chi Nchi kerH / H <| G. move=> IHchi; have nsHN := normalSG (subset_trans kerH (cfker_sub chi)). rewrite cfQuoInorm//; apply/cfRes_char/IHchi => //; first exact: cfRes_char. by apply: sub_cfker_Res => //; apply: normal_sub. have [rG Dchi] := char_reprP Nchi; rewrite Dchi cfker_repr in kerH. apply/char_reprP; exists (Representation (quo_repr kerH (normal_norm nsHG))). apply/cfun_inP=> _ /morphimP[x nHx Gx ->]; rewrite Dchi cfQuoE ?cfker_repr //=. by rewrite !cfunE Gx quo_repr_coset ?mem_quotient. Qed. Lemma cfQuo_lin_char G H (chi : 'CF(G)) : chi \is a linear_char -> (chi / H)%CF \is a linear_char. Proof. by case/andP=> Nchi; rewrite qualifE/= cfQuo_char ?cfQuo1. Qed. Lemma cfMod_char G H (chi : 'CF(G / H)) : chi \is a character -> (chi %% H)%CF \is a character. Proof. exact: cfMorph_char. Qed. Lemma cfMod_lin_char G H (chi : 'CF(G / H)) : chi \is a linear_char -> (chi %% H)%CF \is a linear_char. Proof. exact: cfMorph_lin_char. Qed. Lemma cfMod_charE G H (chi : 'CF(G / H)) : H <| G -> (chi %% H \is a character)%CF = (chi \is a character). Proof. by case/andP=> _; apply: cfMorph_charE. Qed. Lemma cfMod_lin_charE G H (chi : 'CF(G / H)) : H <| G -> (chi %% H \is a linear_char)%CF = (chi \is a linear_char). Proof. by case/andP=> _; apply: cfMorph_lin_charE. Qed. Lemma cfQuo_charE G H (chi : 'CF(G)) : H <| G -> H \subset cfker chi -> (chi / H \is a character)%CF = (chi \is a character). Proof. by move=> nsHG kerH; rewrite -cfMod_charE ?cfQuoK. Qed. Lemma cfQuo_lin_charE G H (chi : 'CF(G)) : H <| G -> H \subset cfker chi -> (chi / H \is a linear_char)%CF = (chi \is a linear_char). Proof. by move=> nsHG kerH; rewrite -cfMod_lin_charE ?cfQuoK. Qed. Lemma cfMod_irr G H chi : H <| G -> (chi %% H \in irr G)%CF = (chi \in irr (G / H)). Proof. by case/andP=> _; apply: cfMorph_irr. Qed. Definition mod_Iirr G H i := cfIirr ('chi[G / H]_i %% H)%CF. Lemma mod_Iirr0 G H : mod_Iirr (0 : Iirr (G / H)) = 0. Proof. exact: morph_Iirr0. Qed. Lemma mod_IirrE G H i : H <| G -> 'chi_(mod_Iirr i) = ('chi[G / H]_i %% H)%CF. Proof. by move=> nsHG; rewrite cfIirrE ?cfMod_irr ?mem_irr. Qed. Lemma mod_Iirr_eq0 G H i : H <| G -> (mod_Iirr i == 0) = (i == 0 :> Iirr (G / H)). Proof. by case/andP=> _ /morph_Iirr_eq0->. Qed. Lemma cfQuo_irr G H chi : H <| G -> H \subset cfker chi -> ((chi / H)%CF \in irr (G / H)) = (chi \in irr G). Proof. by move=> nsHG kerH; rewrite -cfMod_irr ?cfQuoK. Qed. Definition quo_Iirr G H i := cfIirr ('chi[G]_i / H)%CF. Lemma quo_Iirr0 G H : quo_Iirr H (0 : Iirr G) = 0. Proof. by rewrite /quo_Iirr irr0 cfQuo_cfun1 -irr0 irrK. Qed. Lemma quo_IirrE G H i : H <| G -> H \subset cfker 'chi[G]_i -> 'chi_(quo_Iirr H i) = ('chi_i / H)%CF. Proof. by move=> nsHG kerH; rewrite cfIirrE ?cfQuo_irr ?mem_irr. Qed. Lemma quo_Iirr_eq0 G H i : H <| G -> H \subset cfker 'chi[G]_i -> (quo_Iirr H i == 0) = (i == 0). Proof. by move=> nsHG kerH; rewrite -!irr_eq1 quo_IirrE ?cfQuo_eq1. Qed. Lemma mod_IirrK G H : H <| G -> cancel (@mod_Iirr G H) (@quo_Iirr G H). Proof. move=> nsHG i; apply: irr_inj. by rewrite quo_IirrE ?mod_IirrE ?cfker_mod // cfModK. Qed. Lemma quo_IirrK G H i : H <| G -> H \subset cfker 'chi[G]_i -> mod_Iirr (quo_Iirr H i) = i. Proof. by move=> nsHG kerH; apply: irr_inj; rewrite mod_IirrE ?quo_IirrE ?cfQuoK. Qed. Lemma quo_IirrKeq G H : H <| G -> forall i, (mod_Iirr (quo_Iirr H i) == i) = (H \subset cfker 'chi[G]_i). Proof. move=> nsHG i; apply/eqP/idP=> [<- | ]; last exact: quo_IirrK. by rewrite mod_IirrE ?cfker_mod. Qed. Lemma mod_Iirr_bij H G : H <| G -> {on [pred i | H \subset cfker 'chi_i], bijective (@mod_Iirr G H)}. Proof. by exists (quo_Iirr H) => [i _ | i]; [apply: mod_IirrK | apply: quo_IirrK]. Qed. Lemma sum_norm_irr_quo H G x : x \in G -> H <| G -> \sum_i `|'chi[G / H]_i (coset H x)| ^+ 2 = \sum_(i | H \subset cfker 'chi_i) `|'chi[G]_i x| ^+ 2. Proof. move=> Gx nsHG; rewrite (reindex _ (mod_Iirr_bij nsHG)) /=. by apply/esym/eq_big=> [i | i _]; rewrite mod_IirrE ?cfker_mod ?cfModE. Qed. Lemma cap_cfker_normal G H : H <| G -> \bigcap_(i | H \subset cfker 'chi[G]_i) (cfker 'chi_i) = H. Proof. move=> nsHG; have [sHG nHG] := andP nsHG; set lhs := \bigcap_(i | _) _. have nHlhs: lhs \subset 'N(H) by rewrite (bigcap_min 0) ?cfker_irr0. apply/esym/eqP; rewrite eqEsubset (introT bigcapsP) //= -quotient_sub1 //. rewrite -(TI_cfker_irr (G / H)); apply/bigcapsP=> i _. rewrite sub_quotient_pre // (bigcap_min (mod_Iirr i)) ?mod_IirrE ?cfker_mod //. by rewrite cfker_morph ?subsetIr. Qed. Lemma cfker_reg_quo G H : H <| G -> cfker (cfReg (G / H)%g %% H) = H. Proof. move=> nsHG; have [sHG nHG] := andP nsHG. apply/setP=> x; rewrite cfkerEchar ?cfMod_char ?cfReg_char //. rewrite -[in RHS in _ = RHS](setIidPr sHG) !inE; apply: andb_id2l => Gx. rewrite !cfModE // !cfRegE // morph1 eqxx. rewrite (sameP eqP (kerP _ (subsetP nHG x Gx))) ker_coset. by rewrite -!mulrnA eqr_nat eqn_pmul2l ?cardG_gt0 // (can_eq oddb) eqb_id. Qed. End Coset. Section DerivedGroup. Variable gT : finGroupType. Implicit Types G H : {group gT}. Lemma lin_irr_der1 G i : ('chi_i \is a linear_char) = (G^`(1)%g \subset cfker 'chi[G]_i). Proof. apply/idP/idP=> [|sG'K]; first exact: lin_char_der1. have nsG'G: G^`(1) <| G := der_normal 1 G. rewrite qualifE/= irr_char -[i](quo_IirrK nsG'G) // mod_IirrE //=. by rewrite cfModE // morph1 lin_char1 //; apply/char_abelianP/der_abelian. Qed. Lemma subGcfker G i : (G \subset cfker 'chi[G]_i) = (i == 0). Proof. rewrite -irr_eq1; apply/idP/eqP=> [chiG1 | ->]; last by rewrite cfker_cfun1. apply/cfun_inP=> x Gx; rewrite cfun1E Gx cfker1 ?(subsetP chiG1) ?lin_char1 //. by rewrite lin_irr_der1 (subset_trans (der_sub 1 G)). Qed. Lemma irr_prime_injP G i : prime #|G| -> reflect {in G &, injective 'chi[G]_i} (i != 0). Proof. move=> pr_G; apply: (iffP idP) => [nz_i | inj_chi]. apply: fful_lin_char_inj (irr_prime_lin i pr_G) _. by rewrite cfaithfulE -(setIidPr (cfker_sub _)) prime_TIg // subGcfker. have /trivgPn[x Gx ntx]: G :!=: 1%g by rewrite -cardG_gt1 prime_gt1. apply: contraNneq ntx => i0; apply/eqP/inj_chi=> //. by rewrite i0 irr0 !cfun1E Gx group1. Qed. (* This is Isaacs (2.23)(a). *) Lemma cap_cfker_lin_irr G : \bigcap_(i | 'chi[G]_i \is a linear_char) (cfker 'chi_i) = G^`(1)%g. Proof. rewrite -(cap_cfker_normal (der_normal 1 G)). by apply: eq_bigl => i; rewrite lin_irr_der1. Qed. (* This is Isaacs (2.23)(b) *) Lemma card_lin_irr G : #|[pred i | 'chi[G]_i \is a linear_char]| = #|G : G^`(1)%g|. Proof. have nsG'G := der_normal 1 G; rewrite (eq_card (@lin_irr_der1 G)). rewrite -(on_card_preimset (mod_Iirr_bij nsG'G)). rewrite -card_quotient ?normal_norm //. move: (der_abelian 0 G); rewrite card_classes_abelian; move/eqP<-. rewrite -NirrE -[RHS]card_ord. by apply: eq_card => i; rewrite !inE mod_IirrE ?cfker_mod. (* Alternative: use the equivalent result in modular representation theory transitivity #|@socle_of_Iirr _ G @^-1: linear_irr _|; last first. rewrite (on_card_preimset (socle_of_Iirr_bij _)). by rewrite card_linear_irr ?algC'G; last apply: groupC. by apply: eq_card => i; rewrite !inE /lin_char irr_char irr1_degree -eqC_nat. *) Qed. (* A non-trivial solvable group has a nonprincipal linear character. *) Lemma solvable_has_lin_char G : G :!=: 1%g -> solvable G -> exists2 i, 'chi[G]_i \is a linear_char & 'chi_i != 1. Proof. move=> ntG solG. suff /subsetPn[i]: ~~ ([pred i | 'chi[G]_i \is a linear_char] \subset pred1 0). by rewrite !inE -(inj_eq irr_inj) irr0; exists i. rewrite (contra (@subset_leq_card _ _ _)) // -ltnNge card1 card_lin_irr. by rewrite indexg_gt1 proper_subn // (sol_der1_proper solG). Qed. (* A combinatorial group isommorphic to the linear characters. *) Lemma lin_char_group G : {linG : finGroupType & {cF : linG -> 'CF(G) | [/\ injective cF, #|linG| = #|G : G^`(1)|, forall u, cF u \is a linear_char & forall phi, phi \is a linear_char -> exists u, phi = cF u] & [/\ cF 1%g = 1%R, {morph cF : u v / (u * v)%g >-> (u * v)%R}, forall k, {morph cF : u / (u^+ k)%g >-> u ^+ k}, {morph cF: u / u^-1%g >-> u^-1%CF} & {mono cF: u / #[u]%g >-> #[u]%CF} ]}}. Proof. pose linT := {i : Iirr G | 'chi_i \is a linear_char}. pose cF (u : linT) := 'chi_(sval u). have cFlin u: cF u \is a linear_char := svalP u. have cFinj: injective cF := inj_comp irr_inj val_inj. have inT xi : xi \is a linear_char -> {u | cF u = xi}. move=> lin_xi; have /irrP/sig_eqW[i Dxi] := lin_char_irr lin_xi. by apply: (exist _ (Sub i _)) => //; rewrite -Dxi. have [one cFone] := inT 1 (rpred1 _). pose inv u := sval (inT _ (rpredVr (cFlin u))). pose mul u v := sval (inT _ (rpredM (cFlin u) (cFlin v))). have cFmul u v: cF (mul u v) = cF u * cF v := svalP (inT _ _). have cFinv u: cF (inv u) = (cF u)^-1 := svalP (inT _ _). have mulA: associative mul by move=> u v w; apply: cFinj; rewrite !cFmul mulrA. have mul1: left_id one mul by move=> u; apply: cFinj; rewrite cFmul cFone mul1r. have mulV: left_inverse one inv mul. by move=> u; apply: cFinj; rewrite cFmul cFinv cFone mulVr ?lin_char_unitr. pose imA := isMulGroup.Build linT mulA mul1 mulV. pose linG : finGroupType := HB.pack linT imA. have cFexp k: {morph cF : u / ((u : linG) ^+ k)%g >-> u ^+ k}. by move=> u; elim: k => // k IHk; rewrite expgS exprS cFmul IHk. do [exists linG, cF; split=> //] => [|xi /inT[u <-]|u]; first 2 [by exists u]. have inj_cFI: injective (cfIirr \o cF). apply: can_inj (insubd one) _ => u; apply: val_inj. by rewrite insubdK /= ?irrK //; apply: cFlin. rewrite -(card_image inj_cFI) -card_lin_irr. apply/eq_card=> i /[1!inE]; apply/codomP/idP=> [[u ->] | /inT[u Du]]. by rewrite /= irrK; apply: cFlin. by exists u; apply: irr_inj; rewrite /= irrK. apply/eqP; rewrite eqn_dvd; apply/andP; split. by rewrite dvdn_cforder; rewrite -cFexp expg_order cFone. by rewrite order_dvdn -(inj_eq cFinj) cFone cFexp exp_cforder. Qed. Lemma cfExp_prime_transitive G (i j : Iirr G) : prime #|G| -> i != 0 -> j != 0 -> exists2 k, coprime k #['chi_i]%CF & 'chi_j = 'chi_i ^+ k. Proof. set p := #|G| => pr_p nz_i nz_j; have cycG := prime_cyclic pr_p. have [L [h [injh oL Lh h_ontoL]] [h1 hM hX _ o_h]] := lin_char_group G. rewrite (derG1P (cyclic_abelian cycG)) indexg1 -/p in oL. have /fin_all_exists[h' h'K] := h_ontoL _ (irr_cyclic_lin _ cycG). have o_h' k: k != 0 -> #[h' k] = p. rewrite -cforder_irr_eq1 h'K -o_h => nt_h'k. by apply/prime_nt_dvdP=> //; rewrite cforder_lin_char_dvdG. have{oL} genL k: k != 0 -> generator [set: L] (h' k). move=> /o_h' o_h'k; rewrite /generator eq_sym eqEcard subsetT /=. by rewrite cardsT oL -o_h'k. have [/(_ =P <[_]>)-> gen_j] := (genL i nz_i, genL j nz_j). have /cycleP[k Dj] := cycle_generator gen_j. by rewrite !h'K Dj o_h hX generator_coprime coprime_sym in gen_j *; exists k. Qed. (* This is Isaacs (2.24). *) Lemma card_subcent1_coset G H x : x \in G -> H <| G -> (#|'C_(G / H)[coset H x]| <= #|'C_G[x]|)%N. Proof. move=> Gx nsHG; rewrite -leC_nat. move: (second_orthogonality_relation x Gx); rewrite mulrb class_refl => <-. have GHx: coset H x \in (G / H)%g by apply: mem_quotient. move: (second_orthogonality_relation (coset H x) GHx). rewrite mulrb class_refl => <-. rewrite -2!(eq_bigr _ (fun _ _ => normCK _)) sum_norm_irr_quo // -subr_ge0. rewrite (bigID (fun i => H \subset cfker 'chi[G]_i)) //= [X in X + _]addrC addrK. by apply: sumr_ge0 => i _; rewrite normCK mul_conjC_ge0. Qed. End DerivedGroup. Arguments irr_prime_injP {gT G i}. (* Determinant characters and determinential order. *) Section DetRepr. Variables (gT : finGroupType) (G : {group gT}). Variables (n : nat) (rG : mx_representation algC G n). Definition det_repr_mx x : 'M_1 := (\det (rG x))%:M. Fact det_is_repr : mx_repr G det_repr_mx. Proof. split=> [|g h Gg Gh]; first by rewrite /det_repr_mx repr_mx1 det1. by rewrite /det_repr_mx repr_mxM // det_mulmx !mulmxE scalar_mxM. Qed. Canonical det_repr := MxRepresentation det_is_repr. Definition detRepr := cfRepr det_repr. Lemma detRepr_lin_char : detRepr \is a linear_char. Proof. by rewrite qualifE/= cfRepr_char cfunE group1 repr_mx1 mxtrace1 mulr1n /=. Qed. End DetRepr. HB.lock Definition cfDet (gT : finGroupType) (G : {group gT}) phi := \prod_i detRepr 'Chi_i ^+ Num.truncn '[phi, 'chi[G]_i]. Canonical cfDet_unlockable := Unlockable cfDet.unlock. Section DetOrder. Variables (gT : finGroupType) (G : {group gT}). Local Notation cfDet := (@cfDet gT G). Lemma cfDet_lin_char phi : cfDet phi \is a linear_char. Proof. rewrite unlock; apply: rpred_prod => i _; apply: rpredX. exact: detRepr_lin_char. Qed. Lemma cfDetD : {in character &, {morph cfDet : phi psi / phi + psi >-> phi * psi}}. Proof. move=> phi psi Nphi Npsi; rewrite unlock /= -big_split; apply: eq_bigr => i _ /=. by rewrite -exprD cfdotDl truncnD ?nnegrE ?natr_ge0 // Cnat_cfdot_char_irr. Qed. Lemma cfDet0 : cfDet 0 = 1. Proof. by rewrite unlock big1 // => i _; rewrite cfdot0l truncn0. Qed. Lemma cfDetMn k : {in character, {morph cfDet : phi / phi *+ k >-> phi ^+ k}}. Proof. move=> phi Nphi; elim: k => [|k IHk]; rewrite ?cfDet0 // mulrS exprS -{}IHk. by rewrite cfDetD ?rpredMn. Qed. Lemma cfDetRepr n rG : cfDet (cfRepr rG) = @detRepr _ _ n rG. Proof. transitivity (\prod_W detRepr (socle_repr W) ^+ standard_irr_coef rG W). rewrite (reindex _ (socle_of_Iirr_bij _)) unlock /=. apply: eq_bigr => i _; congr (_ ^+ _). rewrite (cfRepr_sim (mx_rsim_standard rG)) cfRepr_standard. rewrite cfdot_suml (bigD1 i) ?big1 //= => [|j i'j]; last first. by rewrite cfdotZl cfdot_irr (negPf i'j) mulr0. by rewrite cfdotZl cfnorm_irr mulr1 addr0 natrK. apply/cfun_inP=> x Gx; rewrite prod_cfunE //. transitivity (detRepr (standard_grepr rG) x); last first. rewrite !cfunE Gx !trace_mx11 !mxE eqxx !mulrb. case: (standard_grepr rG) (mx_rsim_standard rG) => /= n1 rG1 [B Dn1]. rewrite -{n1}Dn1 in rG1 B *; rewrite row_free_unit => uB rG_B. by rewrite -[rG x](mulmxK uB) rG_B // !det_mulmx mulrC -!det_mulmx mulKmx. rewrite /standard_grepr; elim/big_rec2: _ => [|W y _ _ ->]. by rewrite cfunE trace_mx11 mxE Gx det1. rewrite !cfunE Gx /= !{1}trace_mx11 !{1}mxE det_ublock; congr (_ * _). rewrite exp_cfunE //; elim: (standard_irr_coef rG W) => /= [|k IHk]. by rewrite /muln_grepr big_ord0 det1. rewrite exprS /muln_grepr big_ord_recl det_ublock -IHk; congr (_ * _). by rewrite cfunE trace_mx11 mxE Gx. Qed. Lemma cfDet_id xi : xi \is a linear_char -> cfDet xi = xi. Proof. move=> lin_xi; have /irrP[i Dxi] := lin_char_irr lin_xi. apply/cfun_inP=> x Gx; rewrite Dxi -irrRepr cfDetRepr !cfunE trace_mx11 mxE. move: lin_xi (_ x) => /andP[_]; rewrite Dxi irr1_degree pnatr_eq1 => /eqP-> X. by rewrite {1}[X]mx11_scalar det_scalar1 trace_mx11. Qed. Definition cfDet_order phi := #[cfDet phi]%CF. Definition cfDet_order_lin xi : xi \is a linear_char -> cfDet_order xi = #[xi]%CF. Proof. by rewrite /cfDet_order => /cfDet_id->. Qed. Definition cfDet_order_dvdG phi : cfDet_order phi %| #|G|. Proof. by rewrite cforder_lin_char_dvdG ?cfDet_lin_char. Qed. End DetOrder. Notation "''o' ( phi )" := (cfDet_order phi) (format "''o' ( phi )") : cfun_scope. Section CfDetOps. Implicit Types gT aT rT : finGroupType. Lemma cfDetRes gT (G H : {group gT}) phi : phi \is a character -> cfDet ('Res[H, G] phi) = 'Res (cfDet phi). Proof. move=> Nphi; have [sGH | not_sHG] := boolP (H \subset G); last first. have /natrP[n Dphi1] := Cnat_char1 Nphi. rewrite !cfResEout // Dphi1 lin_char1 ?cfDet_lin_char // scale1r. by rewrite scaler_nat cfDetMn ?cfDet_id ?rpred1 // expr1n. have [rG ->] := char_reprP Nphi; rewrite !(=^~ cfRepr_sub, cfDetRepr) //. apply: cfRepr_sim; exists 1%:M; rewrite ?row_free_unit ?unitmx1 // => x Hx. by rewrite mulmx1 mul1mx. Qed. Lemma cfDetMorph aT rT (D G : {group aT}) (f : {morphism D >-> rT}) (phi : 'CF(f @* G)) : phi \is a character -> cfDet (cfMorph phi) = cfMorph (cfDet phi). Proof. move=> Nphi; have [sGD | not_sGD] := boolP (G \subset D); last first. have /natrP[n Dphi1] := Cnat_char1 Nphi. rewrite !cfMorphEout // Dphi1 lin_char1 ?cfDet_lin_char // scale1r. by rewrite scaler_nat cfDetMn ?cfDet_id ?rpred1 // expr1n. have [rG ->] := char_reprP Nphi; rewrite !(=^~ cfRepr_morphim, cfDetRepr) //. apply: cfRepr_sim; exists 1%:M; rewrite ?row_free_unit ?unitmx1 // => x Hx. by rewrite mulmx1 mul1mx. Qed. Lemma cfDetIsom aT rT (G : {group aT}) (R : {group rT}) (f : {morphism G >-> rT}) (isoGR : isom G R f) phi : cfDet (cfIsom isoGR phi) = cfIsom isoGR (cfDet phi). Proof. rewrite unlock rmorph_prod (reindex (isom_Iirr isoGR)); last first. by exists (isom_Iirr (isom_sym isoGR)) => i; rewrite ?isom_IirrK ?isom_IirrKV. apply: eq_bigr=> i; rewrite -!cfDetRepr !irrRepr isom_IirrE rmorphXn cfIsom_iso. by rewrite /= ![in cfIsom _]unlock cfDetMorph ?cfRes_char ?cfDetRes ?irr_char. Qed. Lemma cfDet_mul_lin gT (G : {group gT}) (lambda phi : 'CF(G)) : lambda \is a linear_char -> phi \is a character -> cfDet (lambda * phi) = lambda ^+ Num.truncn (phi 1%g) * cfDet phi. Proof. case/andP=> /char_reprP[[n1 rG1] ->] /= n1_1 /char_reprP[[n2 rG2] ->] /=. do [rewrite !cfRepr1 pnatr_eq1 natrK; move/eqP] in n1_1 *. rewrite {n1}n1_1 in rG1 *; rewrite cfRepr_prod cfDetRepr. apply/cfun_inP=> x Gx; rewrite !cfunE cfDetRepr cfunE Gx !mulrb !trace_mx11. rewrite !mxE prod_repr_lin ?mulrb //=; case: _ / (esym _); rewrite detZ. congr (_ * _); case: {rG2}n2 => [|n2]; first by rewrite cfun1E Gx. by rewrite expS_cfunE //= cfunE Gx trace_mx11. Qed. End CfDetOps. Definition cfcenter (gT : finGroupType) (G : {set gT}) (phi : 'CF(G)) := if phi \is a character then [set g in G | `|phi g| == phi 1%g] else cfker phi. Notation "''Z' ( phi )" := (cfcenter phi) : cfun_scope. Section Center. Variable (gT : finGroupType) (G : {group gT}). Implicit Types (phi chi : 'CF(G)) (H : {group gT}). (* This is Isaacs (2.27)(a). *) Lemma cfcenter_repr n (rG : mx_representation algC G n) : 'Z(cfRepr rG)%CF = rcenter rG. Proof. rewrite /cfcenter /rcenter cfRepr_char /=. apply/setP=> x /[!inE]; apply/andb_id2l=> Gx. apply/eqP/is_scalar_mxP=> [|[c rG_c]]. by case/max_cfRepr_norm_scalar=> // c; exists c. rewrite -(sqrCK (char1_ge0 (cfRepr_char rG))) normC_def; congr (sqrtC _). rewrite expr2 -{2}(mulgV x) -char_inv ?cfRepr_char ?cfunE ?groupM ?groupV //. rewrite Gx group1 repr_mx1 repr_mxM ?repr_mxV ?groupV // !mulrb rG_c. by rewrite invmx_scalar -scalar_mxM !mxtrace_scalar mulrnAr mulrnAl mulr_natl. Qed. (* This is part of Isaacs (2.27)(b). *) Fact cfcenter_group_set phi : group_set ('Z(phi))%CF. Proof. have [[rG ->] | /negbTE notNphi] := altP (@char_reprP _ G phi). by rewrite cfcenter_repr groupP. by rewrite /cfcenter notNphi groupP. Qed. Canonical cfcenter_group f := Group (cfcenter_group_set f). Lemma char_cfcenterE chi x : chi \is a character -> x \in G -> (x \in ('Z(chi))%CF) = (`|chi x| == chi 1%g). Proof. by move=> Nchi Gx; rewrite /cfcenter Nchi inE Gx. Qed. Lemma irr_cfcenterE i x : x \in G -> (x \in 'Z('chi[G]_i)%CF) = (`|'chi_i x| == 'chi_i 1%g). Proof. by move/char_cfcenterE->; rewrite ?irr_char. Qed. (* This is also Isaacs (2.27)(b). *) Lemma cfcenter_sub phi : ('Z(phi))%CF \subset G. Proof. by rewrite /cfcenter /cfker !setIdE -fun_if subsetIl. Qed. Lemma cfker_center_normal phi : cfker phi <| 'Z(phi)%CF. Proof. apply: normalS (cfcenter_sub phi) (cfker_normal phi). rewrite /= /cfcenter; case: ifP => // Hphi; rewrite cfkerEchar //. apply/subsetP=> x /[!inE] /andP[-> /eqP->] /=. by rewrite ger0_norm ?char1_ge0. Qed. Lemma cfcenter_normal phi : 'Z(phi)%CF <| G. Proof. have [[rG ->] | /negbTE notNphi] := altP (@char_reprP _ _ phi). by rewrite cfcenter_repr rcenter_normal. by rewrite /cfcenter notNphi cfker_normal. Qed. (* This is Isaacs (2.27)(c). *) Lemma cfcenter_Res chi : exists2 chi1, chi1 \is a linear_char & 'Res['Z(chi)%CF] chi = chi 1%g *: chi1. Proof. have [[rG ->] | /negbTE notNphi] := altP (@char_reprP _ _ chi); last first. exists 1; first exact: cfun1_lin_char. rewrite /cfcenter notNphi; apply/cfun_inP=> x Kx. by rewrite cfunE cfun1E Kx mulr1 cfResE ?cfker_sub // cfker1. rewrite cfcenter_repr -(cfRepr_sub _ (normal_sub (rcenter_normal _))). case: rG => [[|n] rG] /=; rewrite cfRepr1. exists 1; first exact: cfun1_lin_char. by apply/cfun_inP=> x Zx; rewrite scale0r !cfunE flatmx0 raddf0 Zx. pose rZmx x := ((rG x 0 0)%:M : 'M_(1,1)). have rZmxP: mx_repr [group of rcenter rG] rZmx. split=> [|x y]; first by rewrite /rZmx repr_mx1 mxE eqxx. move=> /setIdP[Gx /is_scalar_mxP[a rGx]] /setIdP[Gy /is_scalar_mxP[b rGy]]. by rewrite /rZmx repr_mxM // rGx rGy -!scalar_mxM !mxE. exists (cfRepr (MxRepresentation rZmxP)). by rewrite qualifE/= cfRepr_char cfRepr1 eqxx. apply/cfun_inP=> x Zx; rewrite !cfunE Zx /= /rZmx mulr_natl. by case/setIdP: Zx => Gx /is_scalar_mxP[a ->]; rewrite mxE !mxtrace_scalar. Qed. (* This is Isaacs (2.27)(d). *) Lemma cfcenter_cyclic chi : cyclic ('Z(chi)%CF / cfker chi)%g. Proof. case Nchi: (chi \is a character); last first. by rewrite /cfcenter Nchi trivg_quotient cyclic1. have [-> | nz_chi] := eqVneq chi 0. rewrite quotientS1 ?cyclic1 //= /cfcenter cfkerEchar ?cfun0_char //. by apply/subsetP=> x /setIdP[Gx _]; rewrite inE Gx /= !cfunE. have [xi Lxi def_chi] := cfcenter_Res chi. set Z := ('Z(_))%CF in xi Lxi def_chi *. have sZG: Z \subset G by apply: cfcenter_sub. have ->: cfker chi = cfker xi. rewrite -(setIidPr (normal_sub (cfker_center_normal _))) -/Z. rewrite !cfkerEchar // ?lin_charW //= -/Z. apply/setP=> x /[!inE]; apply: andb_id2l => Zx. rewrite (subsetP sZG) //= -!(cfResE chi sZG) ?group1 // def_chi !cfunE. by rewrite (inj_eq (mulfI _)) ?char1_eq0. have: abelian (Z / cfker xi) by rewrite sub_der1_abelian ?lin_char_der1. have /irr_reprP[rG irrG ->] := lin_char_irr Lxi; rewrite cfker_repr. apply: mx_faithful_irr_abelian_cyclic (kquo_mx_faithful rG) _. exact/quo_mx_irr. Qed. (* This is Isaacs (2.27)(e). *) Lemma cfcenter_subset_center chi : ('Z(chi)%CF / cfker chi)%g \subset 'Z(G / cfker chi)%g. Proof. case Nchi: (chi \is a character); last first. by rewrite /cfcenter Nchi trivg_quotient sub1G. rewrite subsetI quotientS ?cfcenter_sub // quotient_cents2r //=. case/char_reprP: Nchi => rG ->{chi}; rewrite cfker_repr cfcenter_repr gen_subG. apply/subsetP=> _ /imset2P[x y /setIdP[Gx /is_scalar_mxP[c rGx]] Gy ->]. rewrite inE groupR //= !repr_mxM ?groupM ?groupV // rGx -(scalar_mxC c) -rGx. by rewrite !mulmxA !repr_mxKV. Qed. (* This is Isaacs (2.27)(f). *) Lemma cfcenter_eq_center (i : Iirr G) : ('Z('chi_i)%CF / cfker 'chi_i)%g = 'Z(G / cfker 'chi_i)%g. Proof. apply/eqP; rewrite eqEsubset; rewrite cfcenter_subset_center ?irr_char //. apply/subsetP=> _ /setIP[/morphimP[x /= _ Gx ->] cGx]; rewrite mem_quotient //=. rewrite -irrRepr cfker_repr cfcenter_repr inE Gx in cGx *. apply: mx_abs_irr_cent_scalar 'Chi_i _ _ _; first exact/groupC/socle_irr. have nKG: G \subset 'N(rker 'Chi_i) by apply: rker_norm. (* GG -- locking here is critical to prevent Coq kernel divergence. *) apply/centgmxP=> y Gy; rewrite [eq]lock -2?(quo_repr_coset (subxx _) nKG) //. move: (quo_repr _ _) => rG; rewrite -2?repr_mxM ?mem_quotient // -lock. by rewrite (centP cGx) // mem_quotient. Qed. (* This is Isaacs (2.28). *) Lemma cap_cfcenter_irr : \bigcap_i 'Z('chi[G]_i)%CF = 'Z(G). Proof. apply/esym/eqP; rewrite eqEsubset (introT bigcapsP) /= => [|i _]; last first. rewrite -(quotientSGK _ (normal_sub (cfker_center_normal _))). by rewrite cfcenter_eq_center morphim_center. by rewrite subIset // normal_norm // cfker_normal. set Z := \bigcap_i _. have sZG: Z \subset G by rewrite (bigcap_min 0) ?cfcenter_sub. rewrite subsetI sZG (sameP commG1P trivgP) -(TI_cfker_irr G). apply/bigcapsP=> i _; have nKiG := normal_norm (cfker_normal 'chi_i). rewrite -quotient_cents2 ?(subset_trans sZG) //. rewrite (subset_trans (quotientS _ (bigcap_inf i _))) //. by rewrite cfcenter_eq_center subsetIr. Qed. (* This is Isaacs (2.29). *) Lemma cfnorm_Res_leif H phi : H \subset G -> '['Res[H] phi] <= #|G : H|%:R * '[phi] ?= iff (phi \in 'CF(G, H)). Proof. move=> sHG; rewrite cfun_onE mulrCA natf_indexg // -mulrA mulKf ?neq0CG //. rewrite (big_setID H) (setIidPr sHG) /= addrC. rewrite (mono_leif (ler_pM2l _)) ?invr_gt0 ?gt0CG // -leifBLR -sumrB. rewrite big1 => [|x Hx]; last by rewrite !cfResE ?subrr. have ->: (support phi \subset H) = (G :\: H \subset [set x | phi x == 0]). rewrite subDset setUC -subDset; apply: eq_subset => x. by rewrite !inE (andb_idr (contraR _)) // => /cfun0->. rewrite (sameP subsetP forall_inP); apply: leif_0_sum => x _. by rewrite !inE /<?=%R mul_conjC_ge0 eq_sym mul_conjC_eq0. Qed. (* This is Isaacs (2.30). *) Lemma irr1_bound (i : Iirr G) : ('chi_i 1%g) ^+ 2 <= #|G : 'Z('chi_i)%CF|%:R ?= iff ('chi_i \in 'CF(G, 'Z('chi_i)%CF)). Proof. congr (_ <= _ ?= iff _): (cfnorm_Res_leif 'chi_i (cfcenter_sub 'chi_i)). have [xi Lxi ->] := cfcenter_Res 'chi_i. have /irrP[j ->] := lin_char_irr Lxi; rewrite cfdotZl cfdotZr cfdot_irr eqxx. by rewrite mulr1 irr1_degree conjC_nat. by rewrite cfdot_irr eqxx mulr1. Qed. (* This is Isaacs (2.31). *) Lemma irr1_abelian_bound (i : Iirr G) : abelian (G / 'Z('chi_i)%CF) -> ('chi_i 1%g) ^+ 2 = #|G : 'Z('chi_i)%CF|%:R. Proof. move=> AbGc; apply/eqP; rewrite irr1_bound cfun_onE; apply/subsetP=> x nz_chi_x. have Gx: x \in G by apply: contraR nz_chi_x => /cfun0->. have nKx := subsetP (normal_norm (cfker_normal 'chi_i)) _ Gx. rewrite -(quotientGK (cfker_center_normal _)) inE nKx inE /=. rewrite cfcenter_eq_center inE mem_quotient //=. apply/centP=> _ /morphimP[y nKy Gy ->]; apply/commgP; rewrite -morphR //=. set z := [~ x, y]; rewrite coset_id //. have: z \in 'Z('chi_i)%CF. apply: subsetP (mem_commg Gx Gy). by rewrite der1_min // normal_norm ?cfcenter_normal. rewrite -irrRepr cfker_repr cfcenter_repr !inE in nz_chi_x *. case/andP=> Gz /is_scalar_mxP[c Chi_z]; rewrite Gz Chi_z mul1mx /=. apply/eqP; congr _%:M; apply: (mulIf nz_chi_x); rewrite mul1r. rewrite -{2}(cfunJ _ x Gy) conjg_mulR -/z !cfunE Gx groupM // !{1}mulrb. by rewrite repr_mxM // Chi_z mul_mx_scalar mxtraceZ. Qed. (* This is Isaacs (2.32)(a). *) Lemma irr_faithful_center i : cfaithful 'chi[G]_i -> cyclic 'Z(G). Proof. rewrite (isog_cyclic (isog_center (quotient1_isog G))) /=. by move/trivgP <-; rewrite -cfcenter_eq_center cfcenter_cyclic. Qed. Lemma cfcenter_fful_irr i : cfaithful 'chi[G]_i -> 'Z('chi_i)%CF = 'Z(G). Proof. move/trivgP=> Ki1; have:= cfcenter_eq_center i; rewrite {}Ki1. have inj1: 'injm (@coset gT 1%g) by rewrite ker_coset. by rewrite -injm_center; first apply: injm_morphim_inj; rewrite ?norms1. Qed. (* This is Isaacs (2.32)(b). *) Lemma pgroup_cyclic_faithful (p : nat) : p.-group G -> cyclic 'Z(G) -> exists i, cfaithful 'chi[G]_i. Proof. pose Z := 'Ohm_1('Z(G)) => pG cycZG; have nilG := pgroup_nil pG. have [-> | ntG] := eqsVneq G [1]; first by exists 0; apply: cfker_sub. have{pG} [[p_pr _ _] pZ] := (pgroup_pdiv pG ntG, pgroupS (center_sub G) pG). have ntZ: 'Z(G) != [1] by rewrite center_nil_eq1. have{pZ} oZ: #|Z| = p by apply: Ohm1_cyclic_pgroup_prime. apply/existsP; apply: contraR ntZ => /existsPn-not_ffulG. rewrite -Ohm1_eq1 -subG1 /= -/Z -(TI_cfker_irr G); apply/bigcapsP=> i _. rewrite prime_meetG ?oZ // setIC meet_Ohm1 // meet_center_nil ?cfker_normal //. by rewrite -subG1 not_ffulG. Qed. End Center. Section Induced. Variables (gT : finGroupType) (G H : {group gT}). Implicit Types (phi : 'CF(G)) (chi : 'CF(H)). Lemma cfInd_char chi : chi \is a character -> 'Ind[G] chi \is a character. Proof. move=> Nchi; apply/forallP=> i; rewrite coord_cfdot -Frobenius_reciprocity //. by rewrite Cnat_cfdot_char ?cfRes_char ?irr_char. Qed. Lemma cfInd_eq0 chi : H \subset G -> chi \is a character -> ('Ind[G] chi == 0) = (chi == 0). Proof. move=> sHG Nchi; rewrite -!(char1_eq0) ?cfInd_char // cfInd1 //. by rewrite (mulrI_eq0 _ (mulfI _)) ?neq0CiG. Qed. Lemma Ind_irr_neq0 i : H \subset G -> 'Ind[G, H] 'chi_i != 0. Proof. by move/cfInd_eq0->; rewrite ?irr_neq0 ?irr_char. Qed. Definition Ind_Iirr (A B : {set gT}) i := cfIirr ('Ind[B, A] 'chi_i). Lemma constt_cfRes_irr i : {j | j \in irr_constt ('Res[H, G] 'chi_i)}. Proof. apply/sigW/neq0_has_constt/Res_irr_neq0. Qed. Lemma constt_cfInd_irr i : H \subset G -> {j | j \in irr_constt ('Ind[G, H] 'chi_i)}. Proof. by move=> sHG; apply/sigW/neq0_has_constt/Ind_irr_neq0. Qed. Lemma cfker_Res phi : H \subset G -> phi \is a character -> cfker ('Res[H] phi) = H :&: cfker phi. Proof. move=> sHG Nphi; apply/setP=> x; rewrite !cfkerEchar ?cfRes_char // !inE. by apply/andb_id2l=> Hx; rewrite (subsetP sHG) ?cfResE. Qed. (* This is Isaacs Lemma (5.11). *) Lemma cfker_Ind chi : H \subset G -> chi \is a character -> chi != 0 -> cfker ('Ind[G, H] chi) = gcore (cfker chi) G. Proof. move=> sHG Nchi nzchi; rewrite !cfker_nzcharE ?cfInd_char ?cfInd_eq0 //. apply/setP=> x; rewrite inE cfIndE // (can2_eq (mulVKf _) (mulKf _)) ?neq0CG //. rewrite cfInd1 // mulrA -natrM Lagrange // mulr_natl -sumr_const. apply/eqP/bigcapP=> [/normC_sum_upper ker_chiG_x y Gy | ker_chiG_x]. by rewrite mem_conjg inE ker_chiG_x ?groupV // => z _; apply: char1_ge_norm. by apply: eq_bigr => y /groupVr/ker_chiG_x; rewrite mem_conjgV inE => /eqP. Qed. Lemma cfker_Ind_irr i : H \subset G -> cfker ('Ind[G, H] 'chi_i) = gcore (cfker 'chi_i) G. Proof. by move/cfker_Ind->; rewrite ?irr_neq0 ?irr_char. Qed. End Induced. Arguments Ind_Iirr {gT A%_g} B%_g i%_R.
PartialEquiv.lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Data.Set.Piecewise import Mathlib.Logic.Equiv.Defs import Mathlib.Tactic.Core import Mathlib.Tactic.Attr.Core /-! # Partial equivalences This files defines equivalences between subsets of given types. An element `e` of `PartialEquiv α β` is made of two maps `e.toFun` and `e.invFun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two partial equivalences by restricting the source and target to the maximal set where the composition makes sense. As for equivs, we register a coercion to functions and use it in our simp normal form: we write `e x` and `e.symm y` instead of `e.toFun x` and `e.invFun y`. ## Main definitions * `Equiv.toPartialEquiv`: associating a partial equiv to an equiv, with source = target = univ * `PartialEquiv.symm`: the inverse of a partial equivalence * `PartialEquiv.trans`: the composition of two partial equivalences * `PartialEquiv.refl`: the identity partial equivalence * `PartialEquiv.ofSet`: the identity on a set `s` * `EqOnSource`: equivalence relation describing the "right" notion of equality for partial equivalences (see below in implementation notes) ## Implementation notes There are at least three possible implementations of partial equivalences: * equivs on subtypes * pairs of functions taking values in `Option α` and `Option β`, equal to none where the partial equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `PEquiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The `PartialEquiv` version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `toFun` and `invFun` outside of `source` and `target`). In particular, the equality notion between partial equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no partial equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal partial equivs, this is not an issue in practice. Still, we introduce an equivalence relation `EqOnSource` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `PartialEquiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ open Lean Meta Elab Tactic /-! Implementation of the `mfld_set_tac` tactic for working with the domains of partially-defined functions (`PartialEquiv`, `PartialHomeomorph`, etc). This is in a separate file from `Mathlib/Logic/Equiv/MfldSimpsAttr.lean` because attributes need a new file to become functional. -/ /-- Common `@[simps]` configuration options used for manifold-related declarations. -/ def mfld_cfg : Simps.Config where attrs := [`mfld_simps] fullyApplied := false namespace Tactic.MfldSetTac /-- A very basic tactic to show that sets showing up in manifolds coincide or are included in one another. -/ elab (name := mfldSetTac) "mfld_set_tac" : tactic => withMainContext do let g ← getMainGoal let goalTy := (← instantiateMVars (← g.getDecl).type).getAppFnArgs match goalTy with | (``Eq, #[_ty, _e₁, _e₂]) => evalTactic (← `(tactic| ( apply Set.ext; intro my_y constructor <;> · intro h_my_y try simp only [*, mfld_simps] at h_my_y try simp only [*, mfld_simps]))) | (``Subset, #[_ty, _inst, _e₁, _e₂]) => evalTactic (← `(tactic| ( intro my_y h_my_y try simp only [*, mfld_simps] at h_my_y try simp only [*, mfld_simps]))) | _ => throwError "goal should be an equality or an inclusion" attribute [mfld_simps] and_true eq_self_iff_true Function.comp_apply end Tactic.MfldSetTac open Function Set variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of `α` and `β` respectively. The (global) maps `toFun : α → β` and `invFun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `toFun` outside of `source` and of `invFun` outside of `target` are irrelevant. -/ structure PartialEquiv (α : Type*) (β : Type*) where /-- The global function which has a partial inverse. Its value outside of the `source` subset is irrelevant. -/ toFun : α → β /-- The partial inverse to `toFun`. Its value outside of the `target` subset is irrelevant. -/ invFun : β → α /-- The domain of the partial equivalence. -/ source : Set α /-- The codomain of the partial equivalence. -/ target : Set β /-- The proposition that elements of `source` are mapped to elements of `target`. -/ map_source' : ∀ ⦃x⦄, x ∈ source → toFun x ∈ target /-- The proposition that elements of `target` are mapped to elements of `source`. -/ map_target' : ∀ ⦃x⦄, x ∈ target → invFun x ∈ source /-- The proposition that `invFun` is a left-inverse of `toFun` on `source`. -/ left_inv' : ∀ ⦃x⦄, x ∈ source → invFun (toFun x) = x /-- The proposition that `invFun` is a right-inverse of `toFun` on `target`. -/ right_inv' : ∀ ⦃x⦄, x ∈ target → toFun (invFun x) = x attribute [coe] PartialEquiv.toFun namespace PartialEquiv variable (e : PartialEquiv α β) (e' : PartialEquiv β γ) instance [Inhabited α] [Inhabited β] : Inhabited (PartialEquiv α β) := ⟨⟨const α default, const β default, ∅, ∅, mapsTo_empty _ _, mapsTo_empty _ _, eqOn_empty _ _, eqOn_empty _ _⟩⟩ /-- The inverse of a partial equivalence -/ @[symm] protected def symm : PartialEquiv β α where toFun := e.invFun invFun := e.toFun source := e.target target := e.source map_source' := e.map_target' map_target' := e.map_source' left_inv' := e.right_inv' right_inv' := e.left_inv' instance : CoeFun (PartialEquiv α β) fun _ => α → β := ⟨PartialEquiv.toFun⟩ /-- See Note [custom simps projection] -/ def Simps.symm_apply (e : PartialEquiv α β) : β → α := e.symm initialize_simps_projections PartialEquiv (toFun → apply, invFun → symm_apply) theorem coe_mk (f : α → β) (g s t ml mr il ir) : (PartialEquiv.mk f g s t ml mr il ir : α → β) = f := rfl @[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) : ((PartialEquiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl @[simp, mfld_simps] theorem invFun_as_coe : e.invFun = e.symm := rfl @[simp, mfld_simps] theorem map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h /-- Variant of `e.map_source` and `map_source'`, stated for images of subsets of `source`. -/ lemma map_source'' : e '' e.source ⊆ e.target := fun _ ⟨_, hx, hex⟩ ↦ mem_of_eq_of_mem (id hex.symm) (e.map_source' hx) @[simp, mfld_simps] theorem map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] theorem left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] theorem right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h theorem target_subset_range : e.target ⊆ range e := fun x hx ↦ ⟨e.symm x, right_inv e hx⟩ theorem eq_symm_apply {x : α} {y : β} (hx : x ∈ e.source) (hy : y ∈ e.target) : x = e.symm y ↔ e x = y := ⟨fun h => by rw [← e.right_inv hy, h], fun h => by rw [← e.left_inv hx, h]⟩ protected theorem mapsTo : MapsTo e e.source e.target := fun _ => e.map_source theorem symm_mapsTo : MapsTo e.symm e.target e.source := e.symm.mapsTo protected theorem leftInvOn : LeftInvOn e.symm e e.source := fun _ => e.left_inv protected theorem rightInvOn : RightInvOn e.symm e e.target := fun _ => e.right_inv protected theorem invOn : InvOn e.symm e e.source e.target := ⟨e.leftInvOn, e.rightInvOn⟩ protected theorem injOn : InjOn e e.source := e.leftInvOn.injOn protected theorem bijOn : BijOn e e.source e.target := e.invOn.bijOn e.mapsTo e.symm_mapsTo protected theorem surjOn : SurjOn e e.source e.target := e.bijOn.surjOn /-- Interpret an `Equiv` as a `PartialEquiv` by restricting it to `s` in the domain and to `t` in the codomain. -/ @[simps -fullyApplied] def _root_.Equiv.toPartialEquivOfImageEq (e : α ≃ β) (s : Set α) (t : Set β) (h : e '' s = t) : PartialEquiv α β where toFun := e invFun := e.symm source := s target := t map_source' _ hx := h ▸ mem_image_of_mem _ hx map_target' x hx := by subst t rcases hx with ⟨x, hx, rfl⟩ rwa [e.symm_apply_apply] left_inv' x _ := e.symm_apply_apply x right_inv' x _ := e.apply_symm_apply x /-- Associate a `PartialEquiv` to an `Equiv`. -/ @[simps! (config := mfld_cfg)] def _root_.Equiv.toPartialEquiv (e : α ≃ β) : PartialEquiv α β := e.toPartialEquivOfImageEq univ univ <| by rw [image_univ, e.surjective.range_eq] instance inhabitedOfEmpty [IsEmpty α] [IsEmpty β] : Inhabited (PartialEquiv α β) := ⟨((Equiv.equivEmpty α).trans (Equiv.equivEmpty β).symm).toPartialEquiv⟩ /-- Create a copy of a `PartialEquiv` providing better definitional equalities. -/ @[simps -fullyApplied] def copy (e : PartialEquiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : Set α) (hs : e.source = s) (t : Set β) (ht : e.target = t) : PartialEquiv α β where toFun := f invFun := g source := s target := t map_source' _ := ht ▸ hs ▸ hf ▸ e.map_source map_target' _ := hs ▸ ht ▸ hg ▸ e.map_target left_inv' _ := hs ▸ hf ▸ hg ▸ e.left_inv right_inv' _ := ht ▸ hf ▸ hg ▸ e.right_inv theorem copy_eq (e : PartialEquiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : Set α) (hs : e.source = s) (t : Set β) (ht : e.target = t) : e.copy f hf g hg s hs t ht = e := by substs f g s t cases e rfl /-- Associate to a `PartialEquiv` an `Equiv` between the source and the target. -/ protected def toEquiv : e.source ≃ e.target where toFun x := ⟨e x, e.map_source x.mem⟩ invFun y := ⟨e.symm y, e.map_target y.mem⟩ left_inv := fun ⟨_, hx⟩ => Subtype.eq <| e.left_inv hx right_inv := fun ⟨_, hy⟩ => Subtype.eq <| e.right_inv hy @[simp, mfld_simps] theorem symm_source : e.symm.source = e.target := rfl @[simp, mfld_simps] theorem symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] theorem symm_symm : e.symm.symm = e := rfl theorem symm_bijective : Function.Bijective (PartialEquiv.symm : PartialEquiv α β → PartialEquiv β α) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ theorem image_source_eq_target : e '' e.source = e.target := e.bijOn.image_eq theorem forall_mem_target {p : β → Prop} : (∀ y ∈ e.target, p y) ↔ ∀ x ∈ e.source, p (e x) := by rw [← image_source_eq_target, forall_mem_image] theorem exists_mem_target {p : β → Prop} : (∃ y ∈ e.target, p y) ↔ ∃ x ∈ e.source, p (e x) := by rw [← image_source_eq_target, exists_mem_image] /-- We say that `t : Set β` is an image of `s : Set α` under a partial equivalence if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def IsImage (s : Set α) (t : Set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace IsImage variable {e} {s : Set α} {t : Set β} {x : α} theorem apply_mem_iff (h : e.IsImage s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx theorem symm_apply_mem_iff (h : e.IsImage s t) : ∀ ⦃y⦄, y ∈ e.target → (e.symm y ∈ s ↔ y ∈ t) := e.forall_mem_target.mpr fun x hx => by rw [e.left_inv hx, h hx] protected theorem symm (h : e.IsImage s t) : e.symm.IsImage t s := h.symm_apply_mem_iff @[simp] theorem symm_iff : e.symm.IsImage t s ↔ e.IsImage s t := ⟨fun h => h.symm, fun h => h.symm⟩ protected theorem mapsTo (h : e.IsImage s t) : MapsTo e (e.source ∩ s) (e.target ∩ t) := fun _ hx => ⟨e.mapsTo hx.1, (h hx.1).2 hx.2⟩ theorem symm_mapsTo (h : e.IsImage s t) : MapsTo e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.mapsTo /-- Restrict a `PartialEquiv` to a pair of corresponding sets. -/ @[simps -fullyApplied] def restr (h : e.IsImage s t) : PartialEquiv α β where toFun := e invFun := e.symm source := e.source ∩ s target := e.target ∩ t map_source' := h.mapsTo map_target' := h.symm_mapsTo left_inv' := e.leftInvOn.mono inter_subset_left right_inv' := e.rightInvOn.mono inter_subset_left theorem image_eq (h : e.IsImage s t) : e '' (e.source ∩ s) = e.target ∩ t := h.restr.image_source_eq_target theorem symm_image_eq (h : e.IsImage s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq theorem iff_preimage_eq : e.IsImage s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := by simp only [IsImage, Set.ext_iff, mem_inter_iff, mem_preimage, and_congr_right_iff] alias ⟨preimage_eq, of_preimage_eq⟩ := iff_preimage_eq theorem iff_symm_preimage_eq : e.IsImage s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias ⟨symm_preimage_eq, of_symm_preimage_eq⟩ := iff_symm_preimage_eq theorem of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.IsImage s t := of_symm_preimage_eq <| Eq.trans (of_symm_preimage_eq rfl).image_eq.symm h theorem of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.IsImage s t := of_preimage_eq <| Eq.trans (iff_preimage_eq.2 rfl).symm_image_eq.symm h protected theorem compl (h : e.IsImage s t) : e.IsImage sᶜ tᶜ := fun _ hx => not_congr (h hx) protected theorem inter {s' t'} (h : e.IsImage s t) (h' : e.IsImage s' t') : e.IsImage (s ∩ s') (t ∩ t') := fun _ hx => and_congr (h hx) (h' hx) protected theorem union {s' t'} (h : e.IsImage s t) (h' : e.IsImage s' t') : e.IsImage (s ∪ s') (t ∪ t') := fun _ hx => or_congr (h hx) (h' hx) protected theorem diff {s' t'} (h : e.IsImage s t) (h' : e.IsImage s' t') : e.IsImage (s \ s') (t \ t') := h.inter h'.compl theorem leftInvOn_piecewise {e' : PartialEquiv α β} [∀ i, Decidable (i ∈ s)] [∀ i, Decidable (i ∈ t)] (h : e.IsImage s t) (h' : e'.IsImage s t) : LeftInvOn (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := by rintro x (⟨he, hs⟩ | ⟨he, hs : x ∉ s⟩) · rw [piecewise_eq_of_mem _ _ _ hs, piecewise_eq_of_mem _ _ _ ((h he).2 hs), e.left_inv he] · rw [piecewise_eq_of_notMem _ _ _ hs, piecewise_eq_of_notMem _ _ _ ((h'.compl he).2 hs), e'.left_inv he] theorem inter_eq_of_inter_eq_of_eqOn {e' : PartialEquiv α β} (h : e.IsImage s t) (h' : e'.IsImage s t) (hs : e.source ∩ s = e'.source ∩ s) (heq : EqOn e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := by rw [← h.image_eq, ← h'.image_eq, ← hs, heq.image_eq] theorem symm_eq_on_of_inter_eq_of_eqOn {e' : PartialEquiv α β} (h : e.IsImage s t) (hs : e.source ∩ s = e'.source ∩ s) (heq : EqOn e e' (e.source ∩ s)) : EqOn e.symm e'.symm (e.target ∩ t) := by rw [← h.image_eq] rintro y ⟨x, hx, rfl⟩ have hx' := hx; rw [hs] at hx' rw [e.left_inv hx.1, heq hx, e'.left_inv hx'.1] end IsImage theorem isImage_source_target : e.IsImage e.source e.target := fun x hx => by simp [hx] theorem isImage_source_target_of_disjoint (e' : PartialEquiv α β) (hs : Disjoint e.source e'.source) (ht : Disjoint e.target e'.target) : e.IsImage e'.source e'.target := IsImage.of_image_eq <| by rw [hs.inter_eq, ht.inter_eq, image_empty] theorem image_source_inter_eq' (s : Set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := by rw [inter_comm, e.leftInvOn.image_inter', image_source_eq_target, inter_comm] theorem image_source_inter_eq (s : Set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := by rw [inter_comm, e.leftInvOn.image_inter, image_source_eq_target, inter_comm] theorem image_eq_target_inter_inv_preimage {s : Set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := by rw [← e.image_source_inter_eq', inter_eq_self_of_subset_right h] theorem symm_image_eq_source_inter_preimage {s : Set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h theorem symm_image_target_inter_eq (s : Set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ theorem symm_image_target_inter_eq' (s : Set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' s := e.symm.image_source_inter_eq' _ theorem source_inter_preimage_inv_preimage (s : Set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := Set.ext fun x => and_congr_right_iff.2 fun hx => by simp only [mem_preimage, e.left_inv hx] theorem source_inter_preimage_target_inter (s : Set β) : e.source ∩ e ⁻¹' (e.target ∩ s) = e.source ∩ e ⁻¹' s := ext fun _ => ⟨fun hx => ⟨hx.1, hx.2.2⟩, fun hx => ⟨hx.1, e.map_source hx.1, hx.2⟩⟩ theorem target_inter_inv_preimage_preimage (s : Set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ theorem symm_image_image_of_subset_source {s : Set α} (h : s ⊆ e.source) : e.symm '' (e '' s) = s := (e.leftInvOn.mono h).image_image theorem image_symm_image_of_subset_target {s : Set β} (h : s ⊆ e.target) : e '' (e.symm '' s) = s := e.symm.symm_image_image_of_subset_source h theorem source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target := e.mapsTo theorem symm_image_target_eq_source : e.symm '' e.target = e.source := e.symm.image_source_eq_target theorem target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source := e.symm_mapsTo /-- Two partial equivs that have the same `source`, same `toFun` and same `invFun`, coincide. -/ @[ext] protected theorem ext {e e' : PartialEquiv α β} (h : ∀ x, e x = e' x) (hsymm : ∀ x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := by have A : (e : α → β) = e' := by ext x exact h x have B : (e.symm : β → α) = e'.symm := by ext x exact hsymm x have I : e '' e.source = e.target := e.image_source_eq_target have I' : e' '' e'.source = e'.target := e'.image_source_eq_target rw [A, hs, I'] at I cases e; cases e' simp_all /-- Restricting a partial equivalence to `e.source ∩ s` -/ protected def restr (s : Set α) : PartialEquiv α β := (@IsImage.of_symm_preimage_eq α β e s (e.symm ⁻¹' s) rfl).restr @[simp, mfld_simps] theorem restr_coe (s : Set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] theorem restr_coe_symm (s : Set α) : ((e.restr s).symm : β → α) = e.symm := rfl @[simp, mfld_simps] theorem restr_source (s : Set α) : (e.restr s).source = e.source ∩ s := rfl theorem source_restr_subset_source (s : Set α) : (e.restr s).source ⊆ e.source := inter_subset_left @[simp, mfld_simps] theorem restr_target (s : Set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl theorem restr_eq_of_source_subset {e : PartialEquiv α β} {s : Set α} (h : e.source ⊆ s) : e.restr s = e := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) (by simp [inter_eq_self_of_subset_left h]) @[simp, mfld_simps] theorem restr_univ {e : PartialEquiv α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) /-- The identity partial equiv -/ protected def refl (α : Type*) : PartialEquiv α α := (Equiv.refl α).toPartialEquiv @[simp, mfld_simps] theorem refl_source : (PartialEquiv.refl α).source = univ := rfl @[simp, mfld_simps] theorem refl_target : (PartialEquiv.refl α).target = univ := rfl @[simp, mfld_simps] theorem refl_coe : (PartialEquiv.refl α : α → α) = id := rfl @[simp, mfld_simps] theorem refl_symm : (PartialEquiv.refl α).symm = PartialEquiv.refl α := rfl @[mfld_simps] theorem refl_restr_source (s : Set α) : ((PartialEquiv.refl α).restr s).source = s := by simp @[mfld_simps] theorem refl_restr_target (s : Set α) : ((PartialEquiv.refl α).restr s).target = s := by simp /-- The identity partial equivalence on a set `s` -/ def ofSet (s : Set α) : PartialEquiv α α where toFun := id invFun := id source := s target := s map_source' _ hx := hx map_target' _ hx := hx left_inv' _ _ := rfl right_inv' _ _ := rfl @[simp, mfld_simps] theorem ofSet_source (s : Set α) : (PartialEquiv.ofSet s).source = s := rfl @[simp, mfld_simps] theorem ofSet_target (s : Set α) : (PartialEquiv.ofSet s).target = s := rfl @[simp, mfld_simps] theorem ofSet_coe (s : Set α) : (PartialEquiv.ofSet s : α → α) = id := rfl @[simp, mfld_simps] theorem ofSet_symm (s : Set α) : (PartialEquiv.ofSet s).symm = PartialEquiv.ofSet s := rfl /-- `Function.const` as a `PartialEquiv`. It consists of two constant maps in opposite directions. -/ @[simps] def single (a : α) (b : β) : PartialEquiv α β where toFun := Function.const α b invFun := Function.const β a source := {a} target := {b} map_source' _ _ := rfl map_target' _ _ := rfl left_inv' a' ha' := by rw [eq_of_mem_singleton ha', const_apply] right_inv' b' hb' := by rw [eq_of_mem_singleton hb', const_apply] /-- Composing two partial equivs if the target of the first coincides with the source of the second. -/ @[simps] protected def trans' (e' : PartialEquiv β γ) (h : e.target = e'.source) : PartialEquiv α γ where toFun := e' ∘ e invFun := e.symm ∘ e'.symm source := e.source target := e'.target map_source' x hx := by simp [← h, hx] map_target' y hy := by simp [h, hy] left_inv' x hx := by simp [hx, ← h] right_inv' y hy := by simp [hy, h] /-- Composing two partial equivs, by restricting to the maximal domain where their composition is well defined. Within the `Manifold` namespace, there is the notation `e ≫ f` for this. -/ @[trans] protected def trans : PartialEquiv α γ := PartialEquiv.trans' (e.symm.restr e'.source).symm (e'.restr e.target) (inter_comm _ _) @[simp, mfld_simps] theorem coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] theorem coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl theorem trans_apply {x : α} : (e.trans e') x = e' (e x) := rfl theorem trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; rfl @[simp, mfld_simps] theorem trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl theorem trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := by mfld_set_tac theorem trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := by rw [e.trans_source', e.symm_image_target_inter_eq] theorem image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := (e.symm.restr e'.source).symm.image_source_eq_target @[simp, mfld_simps] theorem trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl theorem trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm theorem trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm theorem inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm theorem trans_assoc (e'' : PartialEquiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc]) @[simp, mfld_simps] theorem trans_refl : e.trans (PartialEquiv.refl β) = e := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) (by simp [trans_source]) @[simp, mfld_simps] theorem refl_trans : (PartialEquiv.refl α).trans e = e := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) (by simp [trans_source, preimage_id]) theorem trans_ofSet (s : Set β) : e.trans (ofSet s) = e.restr (e ⁻¹' s) := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) rfl theorem trans_refl_restr (s : Set β) : e.trans ((PartialEquiv.refl β).restr s) = e.restr (e ⁻¹' s) := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) (by simp [trans_source]) theorem trans_refl_restr' (s : Set β) : e.trans ((PartialEquiv.refl β).restr s) = e.restr (e.source ∩ e ⁻¹' s) := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) <| by simp only [trans_source, restr_source, refl_source, univ_inter] rw [← inter_assoc, inter_self] theorem restr_trans (s : Set α) : (e.restr s).trans e' = (e.trans e').restr s := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) <| by simp [trans_source, inter_comm, inter_assoc] /-- A lemma commonly useful when `e` and `e'` are charts of a manifold. -/ theorem mem_symm_trans_source {e' : PartialEquiv α γ} {x : α} (he : x ∈ e.source) (he' : x ∈ e'.source) : e x ∈ (e.symm.trans e').source := ⟨e.mapsTo he, by rwa [mem_preimage, PartialEquiv.symm_symm, e.left_inv he]⟩ /-- `EqOnSource e e'` means that `e` and `e'` have the same source, and coincide there. Then `e` and `e'` should really be considered the same partial equiv. -/ def EqOnSource (e e' : PartialEquiv α β) : Prop := e.source = e'.source ∧ e.source.EqOn e e' /-- `EqOnSource` is an equivalence relation. This instance provides the `≈` notation between two `PartialEquiv`s. -/ instance eqOnSourceSetoid : Setoid (PartialEquiv α β) where r := EqOnSource iseqv := by constructor <;> simp only [EqOnSource, EqOn] <;> aesop theorem eqOnSource_refl : e ≈ e := Setoid.refl _ /-- Two equivalent partial equivs have the same source. -/ theorem EqOnSource.source_eq {e e' : PartialEquiv α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent partial equivs coincide on the source. -/ theorem EqOnSource.eqOn {e e' : PartialEquiv α β} (h : e ≈ e') : e.source.EqOn e e' := h.2 /-- Two equivalent partial equivs have the same target. -/ theorem EqOnSource.target_eq {e e' : PartialEquiv α β} (h : e ≈ e') : e.target = e'.target := by simp only [← image_source_eq_target, ← source_eq h, h.2.image_eq] /-- If two partial equivs are equivalent, so are their inverses. -/ theorem EqOnSource.symm' {e e' : PartialEquiv α β} (h : e ≈ e') : e.symm ≈ e'.symm := by refine ⟨target_eq h, eqOn_of_leftInvOn_of_rightInvOn e.leftInvOn ?_ ?_⟩ <;> simp only [symm_source, target_eq h, source_eq h, e'.symm_mapsTo] exact e'.rightInvOn.congr_right e'.symm_mapsTo (source_eq h ▸ h.eqOn.symm) /-- Two equivalent partial equivs have coinciding inverses on the target. -/ theorem EqOnSource.symm_eqOn {e e' : PartialEquiv α β} (h : e ≈ e') : EqOn e.symm e'.symm e.target := -- Porting note: `h.symm'` dot notation doesn't work anymore because `h` is not recognised as -- `PartialEquiv.EqOnSource` for some reason. eqOn (symm' h) /-- Composition of partial equivs respects equivalence. -/ theorem EqOnSource.trans' {e e' : PartialEquiv α β} {f f' : PartialEquiv β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := by constructor · rw [trans_source'', trans_source'', ← target_eq he, ← hf.1] exact (he.symm'.eqOn.mono inter_subset_left).image_eq · intro x hx rw [trans_source] at hx simp [Function.comp_apply, PartialEquiv.coe_trans, (he.2 hx.1).symm, hf.2 hx.2] /-- Restriction of partial equivs respects equivalence. -/ theorem EqOnSource.restr {e e' : PartialEquiv α β} (he : e ≈ e') (s : Set α) : e.restr s ≈ e'.restr s := by constructor · simp [he.1] · intro x hx simp only [mem_inter_iff, restr_source] at hx exact he.2 hx.1 /-- Preimages are respected by equivalence. -/ theorem EqOnSource.source_inter_preimage_eq {e e' : PartialEquiv α β} (he : e ≈ e') (s : Set β) : e.source ∩ e ⁻¹' s = e'.source ∩ e' ⁻¹' s := by rw [he.eqOn.inter_preimage_eq, source_eq he] /-- Composition of a partial equivalence and its inverse is equivalent to the restriction of the identity to the source. -/ theorem self_trans_symm : e.trans e.symm ≈ ofSet e.source := by have A : (e.trans e.symm).source = e.source := by mfld_set_tac refine ⟨by rw [A, ofSet_source], fun x hx => ?_⟩ rw [A] at hx simp only [hx, mfld_simps] /-- Composition of the inverse of a partial equivalence and this partial equivalence is equivalent to the restriction of the identity to the target. -/ theorem symm_trans_self : e.symm.trans e ≈ ofSet e.target := self_trans_symm e.symm /-- Two equivalent partial equivs are equal when the source and target are `univ`. -/ theorem eq_of_eqOnSource_univ (e e' : PartialEquiv α β) (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := by refine PartialEquiv.ext (fun x => ?_) (fun x => ?_) h.1 · apply h.2 rw [s] exact mem_univ _ · apply h.symm'.2 rw [symm_source, t] exact mem_univ _ section Prod /-- The product of two partial equivalences, as a partial equivalence on the product. -/ def prod (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : PartialEquiv (α × γ) (β × δ) where source := e.source ×ˢ e'.source target := e.target ×ˢ e'.target toFun p := (e p.1, e' p.2) invFun p := (e.symm p.1, e'.symm p.2) map_source' p hp := by simp_all map_target' p hp := by simp_all left_inv' p hp := by simp_all right_inv' p hp := by simp_all @[simp, mfld_simps] theorem prod_source (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : (e.prod e').source = e.source ×ˢ e'.source := rfl @[simp, mfld_simps] theorem prod_target (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : (e.prod e').target = e.target ×ˢ e'.target := rfl @[simp, mfld_simps] theorem prod_coe (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : (e.prod e' : α × γ → β × δ) = fun p => (e p.1, e' p.2) := rfl theorem prod_coe_symm (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : ((e.prod e').symm : β × δ → α × γ) = fun p => (e.symm p.1, e'.symm p.2) := rfl @[simp, mfld_simps] theorem prod_symm (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : (e.prod e').symm = e.symm.prod e'.symm := by ext x <;> simp [prod_coe_symm] @[simp, mfld_simps] theorem refl_prod_refl : (PartialEquiv.refl α).prod (PartialEquiv.refl β) = PartialEquiv.refl (α × β) := by ext ⟨x, y⟩ <;> simp @[simp, mfld_simps] theorem prod_trans {η : Type*} {ε : Type*} (e : PartialEquiv α β) (f : PartialEquiv β γ) (e' : PartialEquiv δ η) (f' : PartialEquiv η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := by ext ⟨x, y⟩ <;> simp; tauto end Prod /-- Combine two `PartialEquiv`s using `Set.piecewise`. The source of the new `PartialEquiv` is `s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`, and similarly for the inverse function. The definition assumes `e.isImage s t` and `e'.isImage s t`. -/ @[simps -fullyApplied] def piecewise (e e' : PartialEquiv α β) (s : Set α) (t : Set β) [∀ x, Decidable (x ∈ s)] [∀ y, Decidable (y ∈ t)] (H : e.IsImage s t) (H' : e'.IsImage s t) : PartialEquiv α β where toFun := s.piecewise e e' invFun := t.piecewise e.symm e'.symm source := s.ite e.source e'.source target := t.ite e.target e'.target map_source' := H.mapsTo.piecewise_ite H'.compl.mapsTo map_target' := H.symm.mapsTo.piecewise_ite H'.symm.compl.mapsTo left_inv' := H.leftInvOn_piecewise H' right_inv' := H.symm.leftInvOn_piecewise H'.symm theorem symm_piecewise (e e' : PartialEquiv α β) {s : Set α} {t : Set β} [∀ x, Decidable (x ∈ s)] [∀ y, Decidable (y ∈ t)] (H : e.IsImage s t) (H' : e'.IsImage s t) : (e.piecewise e' s t H H').symm = e.symm.piecewise e'.symm t s H.symm H'.symm := rfl /-- Combine two `PartialEquiv`s with disjoint sources and disjoint targets. We reuse `PartialEquiv.piecewise`, then override `source` and `target` to ensure better definitional equalities. -/ @[simps! -fullyApplied] def disjointUnion (e e' : PartialEquiv α β) (hs : Disjoint e.source e'.source) (ht : Disjoint e.target e'.target) [∀ x, Decidable (x ∈ e.source)] [∀ y, Decidable (y ∈ e.target)] : PartialEquiv α β := (e.piecewise e' e.source e.target e.isImage_source_target <| e'.isImage_source_target_of_disjoint _ hs.symm ht.symm).copy _ rfl _ rfl (e.source ∪ e'.source) (ite_left _ _) (e.target ∪ e'.target) (ite_left _ _) theorem disjointUnion_eq_piecewise (e e' : PartialEquiv α β) (hs : Disjoint e.source e'.source) (ht : Disjoint e.target e'.target) [∀ x, Decidable (x ∈ e.source)] [∀ y, Decidable (y ∈ e.target)] : e.disjointUnion e' hs ht = e.piecewise e' e.source e.target e.isImage_source_target (e'.isImage_source_target_of_disjoint _ hs.symm ht.symm) := copy_eq .. section Pi variable {ι : Type*} {αi βi γi : ι → Type*} /-- The product of a family of partial equivalences, as a partial equivalence on the pi type. -/ @[simps (config := mfld_cfg) apply source target] protected def pi (ei : ∀ i, PartialEquiv (αi i) (βi i)) : PartialEquiv (∀ i, αi i) (∀ i, βi i) where toFun := Pi.map fun i ↦ ei i invFun := Pi.map fun i ↦ (ei i).symm source := pi univ fun i => (ei i).source target := pi univ fun i => (ei i).target map_source' _ hf i hi := (ei i).map_source (hf i hi) map_target' _ hf i hi := (ei i).map_target (hf i hi) left_inv' _ hf := funext fun i => (ei i).left_inv (hf i trivial) right_inv' _ hf := funext fun i => (ei i).right_inv (hf i trivial) @[simp, mfld_simps] theorem pi_symm (ei : ∀ i, PartialEquiv (αi i) (βi i)) : (PartialEquiv.pi ei).symm = .pi fun i ↦ (ei i).symm := rfl theorem pi_symm_apply (ei : ∀ i, PartialEquiv (αi i) (βi i)) : ⇑(PartialEquiv.pi ei).symm = fun f i ↦ (ei i).symm (f i) := rfl @[simp, mfld_simps] theorem pi_refl : (PartialEquiv.pi fun i ↦ PartialEquiv.refl (αi i)) = .refl (∀ i, αi i) := by ext <;> simp @[simp, mfld_simps] theorem pi_trans (ei : ∀ i, PartialEquiv (αi i) (βi i)) (ei' : ∀ i, PartialEquiv (βi i) (γi i)) : (PartialEquiv.pi ei).trans (PartialEquiv.pi ei') = .pi fun i ↦ (ei i).trans (ei' i) := by ext <;> simp [forall_and] end Pi lemma surjective_of_target_eq_univ (h : e.target = univ) : Surjective e := surjective_iff_surjOn_univ.mpr <| e.surjOn.mono (by simp) (by simp [h]) lemma injective_of_source_eq_univ (h : e.source = univ) : Injective e := by simpa [injective_iff_injOn_univ, h] using e.injOn lemma injective_symm_of_target_eq_univ (h : e.target = univ) : Injective e.symm := e.symm.injective_of_source_eq_univ h lemma surjective_symm_of_source_eq_univ (h : e.source = univ) : Surjective e.symm := e.symm.surjective_of_target_eq_univ h end PartialEquiv namespace Set -- All arguments are explicit to avoid missing information in the pretty printer output /-- A bijection between two sets `s : Set α` and `t : Set β` provides a partial equivalence between `α` and `β`. -/ @[simps -fullyApplied] noncomputable def BijOn.toPartialEquiv [Nonempty α] (f : α → β) (s : Set α) (t : Set β) (hf : BijOn f s t) : PartialEquiv α β where toFun := f invFun := invFunOn f s source := s target := t map_source' := hf.mapsTo map_target' := hf.surjOn.mapsTo_invFunOn left_inv' := hf.invOn_invFunOn.1 right_inv' := hf.invOn_invFunOn.2 /-- A map injective on a subset of its domain provides a partial equivalence. -/ @[simp, mfld_simps] noncomputable def InjOn.toPartialEquiv [Nonempty α] (f : α → β) (s : Set α) (hf : InjOn f s) : PartialEquiv α β := hf.bijOn_image.toPartialEquiv f s (f '' s) end Set namespace Equiv /- `Equiv`s give rise to `PartialEquiv`s. We set up simp lemmas to reduce most properties of the `PartialEquiv` to that of the `Equiv`. -/ variable (e : α ≃ β) (e' : β ≃ γ) @[simp, mfld_simps] theorem refl_toPartialEquiv : (Equiv.refl α).toPartialEquiv = PartialEquiv.refl α := rfl @[simp, mfld_simps] theorem symm_toPartialEquiv : e.symm.toPartialEquiv = e.toPartialEquiv.symm := rfl @[simp, mfld_simps] theorem trans_toPartialEquiv : (e.trans e').toPartialEquiv = e.toPartialEquiv.trans e'.toPartialEquiv := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) (by simp [PartialEquiv.trans_source, Equiv.toPartialEquiv]) /-- Precompose a partial equivalence with an equivalence. We modify the source and target to have better definitional behavior. -/ @[simps!] def transPartialEquiv (e : α ≃ β) (f' : PartialEquiv β γ) : PartialEquiv α γ := (e.toPartialEquiv.trans f').copy _ rfl _ rfl (e ⁻¹' f'.source) (univ_inter _) f'.target (inter_univ _) theorem transPartialEquiv_eq_trans (e : α ≃ β) (f' : PartialEquiv β γ) : e.transPartialEquiv f' = e.toPartialEquiv.trans f' := PartialEquiv.copy_eq .. @[simp, mfld_simps] theorem transPartialEquiv_trans (e : α ≃ β) (f' : PartialEquiv β γ) (f'' : PartialEquiv γ δ) : (e.transPartialEquiv f').trans f'' = e.transPartialEquiv (f'.trans f'') := by simp only [transPartialEquiv_eq_trans, PartialEquiv.trans_assoc] @[simp, mfld_simps] theorem trans_transPartialEquiv (e : α ≃ β) (e' : β ≃ γ) (f'' : PartialEquiv γ δ) : (e.trans e').transPartialEquiv f'' = e.transPartialEquiv (e'.transPartialEquiv f'') := by simp only [transPartialEquiv_eq_trans, PartialEquiv.trans_assoc, trans_toPartialEquiv] end Equiv namespace PartialEquiv /-- Postcompose a partial equivalence with an equivalence. We modify the source and target to have better definitional behavior. -/ @[simps!] def transEquiv (e : PartialEquiv α β) (f' : β ≃ γ) : PartialEquiv α γ := (e.trans f'.toPartialEquiv).copy _ rfl _ rfl e.source (inter_univ _) (f'.symm ⁻¹' e.target) (univ_inter _) theorem transEquiv_eq_trans (e : PartialEquiv α β) (e' : β ≃ γ) : e.transEquiv e' = e.trans e'.toPartialEquiv := copy_eq .. @[simp, mfld_simps] theorem transEquiv_transEquiv (e : PartialEquiv α β) (f' : β ≃ γ) (f'' : γ ≃ δ) : (e.transEquiv f').transEquiv f'' = e.transEquiv (f'.trans f'') := by simp only [transEquiv_eq_trans, trans_assoc, Equiv.trans_toPartialEquiv] @[simp, mfld_simps] theorem trans_transEquiv (e : PartialEquiv α β) (e' : PartialEquiv β γ) (f'' : γ ≃ δ) : (e.trans e').transEquiv f'' = e.trans (e'.transEquiv f'') := by simp only [transEquiv_eq_trans, trans_assoc] end PartialEquiv
GeneralizeProofs.lean
import Mathlib.Algebra.Ring.Nat import Mathlib.Tactic.GeneralizeProofs private axiom test_sorry : ∀ {α}, α set_option autoImplicit true noncomputable def List.nthLe (l : List α) (n) (_h : n < l.length) : α := test_sorry -- For debugging `generalize_proofs` -- set_option trace.Tactic.generalize_proofs true example : List.nthLe [1, 2] 1 (by simp) = 2 := by generalize_proofs h guard_hyp h :ₛ 1 < List.length [1, 2] guard_target =ₛ [1, 2].nthLe 1 h = 2 exact test_sorry example (x : ℕ) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) < 2 := by generalize_proofs a guard_hyp a :ₛ ∃ x, x < 2 guard_target =ₛ Classical.choose a < 2 exact Classical.choose_spec a example (x : ℕ) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, h⟩ : ∃ x, x < 2) := by generalize_proofs a guard_hyp a :ₛ ∃ x, x < 2 guard_target =ₛ Classical.choose a = Classical.choose a rfl example (x : ℕ) (h : x < 2) (h' : x < 1) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, (by clear h; omega)⟩ : ∃ x, x < 2) := by generalize_proofs a guard_hyp a :ₛ ∃ x, x < 2 guard_target =ₛ Classical.choose a = Classical.choose a rfl example (x : ℕ) (h h' : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, h'⟩ : ∃ x, x < 2) := by change _ at h' fail_if_success guard_target =ₛ Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, h⟩ : ∃ x, x < 2) generalize_proofs at h' fail_if_success change _ at h' guard_target =ₛ Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, h⟩ : ∃ x, x < 2) generalize_proofs a guard_target =ₛ Classical.choose a = Classical.choose a rfl example (x : ℕ) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, Nat.lt_succ_of_lt h⟩ : ∃ x, x < 3) := by generalize_proofs a a' guard_hyp a :ₛ ∃ x, x < 2 guard_hyp a' :ₛ ∃ x, x < 3 guard_target =ₛ Classical.choose a = Classical.choose a' exact test_sorry example (x : ℕ) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, Nat.lt_succ_of_lt h⟩ : ∃ x, x < 3) := by generalize_proofs guard_target = Classical.choose _ = Classical.choose _ exact test_sorry example (x : ℕ) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, Nat.lt_succ_of_lt h⟩ : ∃ x, x < 3) := by generalize_proofs _ a guard_hyp a : ∃ x, x < 3 guard_target = Classical.choose _ = Classical.choose a exact test_sorry example (a : ∃ x, x < 2) : Classical.choose a < 2 := by generalize_proofs guard_target =ₛ Classical.choose a < 2 exact Classical.choose_spec a example (a : ∃ x, x < 2) : Classical.choose a < 2 := by generalize_proofs t guard_target =ₛ Classical.choose a < 2 exact Classical.choose_spec a example (x : ℕ) (h : x < 2) (H : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) < 2 := by generalize_proofs a at H ⊢ guard_hyp a :ₛ ∃ x, x < 2 guard_hyp H :ₛ Classical.choose a < 2 guard_target =ₛ Classical.choose a < 2 exact H example (H : ∀ y, ∃ (x : ℕ) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y) : ∀ y, ∃ (x : ℕ) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y := by generalize_proofs -abstract guard_target =ₛ ∀ y, ∃ (x : ℕ) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y generalize_proofs a at H ⊢ guard_hyp a :ₛ ∀ (y w : ℕ), w < y → ∃ x, x < y guard_hyp H :ₛ ∀ (y : ℕ), ∃ x h, Classical.choose (a y x h) < y guard_target =ₛ ∀ (y : ℕ), ∃ x h, Classical.choose (a y x h) < y exact H example (H : ∀ y, ∃ (x : ℕ) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y) : ∀ y, ∃ (x : ℕ) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y := by generalize_proofs a at * guard_hyp a :ₛ ∀ (y w : ℕ), w < y → ∃ x, x < y guard_hyp H :ₛ ∀ (y : ℕ), ∃ x h, Classical.choose (a y x h) < y guard_target =ₛ ∀ (y : ℕ), ∃ x h, Classical.choose (a y x h) < y exact H namespace zulip1 /-! https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/.60generalize_proofs.60.20sometimes.20silently.20has.20no.20effect/near/407162574 -/ theorem t (x : Option Unit) : x.isSome = true := test_sorry def p : Unit → Prop := test_sorry theorem good (x : Option Unit) : p (Option.get x test_sorry) → x.isSome = true := by generalize_proofs h exact fun _ => h theorem was_bad (x : Option Unit) : p (Option.get x (t x)) → x.isSome = true := by generalize_proofs h exact fun _ => h end zulip1 section attribute [local instance] Classical.propDecidable example (H : ∀ x, x = 1) : (if h : ∃ (k : ℕ), k = 1 then Classical.choose h else 0) = 1 := by rw [dif_pos ?hc] case hc => exact ⟨1, rfl⟩ generalize_proofs h guard_hyp h :ₛ ∃ x, x = 1 guard_target =ₛ Classical.choose h = 1 apply H end section -- make sure it handles `let` declarations well -- this was https://github.com/leanprover-community/mathlib4/issues/24222 example : True := by let n : Fin 1 := ⟨0, id Nat.zero_lt_one⟩ generalize_proofs h at * guard_hyp h :ₛ 0 < 1 guard_hyp n :=ₛ ⟨0, h⟩ trivial example : True := by have h := Nat.zero_lt_one let n : Fin 1 := ⟨0, id Nat.zero_lt_one⟩ generalize_proofs at * guard_hyp h :ₛ 0 < 1 guard_hyp n :=ₛ ⟨0, h⟩ trivial example : True := by let p := id Nat.zero_lt_one generalize_proofs at * guard_hyp p :ₛ 0 < 1 trivial example : True := by let p := Nat.zero_lt_one generalize_proofs at * guard_hyp p :ₛ 0 < 1 let q := id Nat.zero_lt_one generalize_proofs at * fail_if_success change _ at q guard_hyp p :ₛ 0 < 1 trivial example (P : Sort*) (p : P) : True := by let p' : P := p generalize_proofs at * guard_hyp p :ₛ P guard_hyp p' :=ₛ p trivial example (P : True → Sort*) (p : True → P (by decide)) : True := by let p' := p (by decide) generalize_proofs h at * guard_hyp h :ₛ True guard_hyp p :ₛ True → P h guard_hyp p' :=ₛ p h exact h end /-! Extracting proofs from under let bindings -/ /-- trace: pf✝ : ∀ (n : ℕ), 0 < n + 1 ⊢ have n := 0; ↑⟨0, ⋯⟩ = 0 -/ #guard_msgs in example : have n := 0; (⟨0, id (by simp)⟩ : Fin (n + 1)).val = 0 := by generalize_proofs trace_state rfl /-- trace: pf✝ : ∀ (n : ℕ), 0 < n + 1 ⊢ have n := 0; ↑⟨0, ⋯⟩ = 0 -/ #guard_msgs in example : have n := 0; (⟨0, id (by simp)⟩ : Fin (n + 1)).val = 0 := by generalize_proofs trace_state rfl
matrix.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice. From mathcomp Require Import fintype finfun finset fingroup perm order div. From mathcomp Require Import prime binomial ssralg countalg finalg zmodp bigop. (******************************************************************************) (* Basic concrete linear algebra : definition of type for matrices, and all *) (* basic matrix operations including determinant, trace and support for block *) (* decomposition. Matrices are represented by a row-major list of their *) (* coefficients but this implementation is hidden by three levels of wrappers *) (* (Matrix/Finfun/Tuple) so the matrix type should be treated as abstract and *) (* handled using only the operations described below: *) (* 'M[R]_(m, n) == the type of m rows by n columns matrices with *) (* 'M_(m, n) coefficients in R; the [R] is optional and is usually *) (* omitted. *) (* 'M[R]_n, 'M_n == the type of n x n square matrices. *) (* 'rV[R]_n, 'rV_n == the type of 1 x n row vectors. *) (* 'cV[R]_n, 'cV_n == the type of n x 1 column vectors. *) (* \matrix_(i < m, j < n) Expr(i, j) == *) (* the m x n matrix with general coefficient Expr(i, j), *) (* with i : 'I_m and j : 'I_n. the < m bound can be omitted *) (* if it is equal to n, though usually both bounds are *) (* omitted as they can be inferred from the context. *) (* \row_(j < n) Expr(j), \col_(i < m) Expr(i) *) (* the row / column vectors with general term Expr; the *) (* parentheses can be omitted along with the bound. *) (* \matrix_(i < m) RowExpr(i) == *) (* the m x n matrix with row i given by RowExpr(i) : 'rV_n. *) (* A i j == the coefficient of matrix A : 'M_(m, n) in column j of *) (* row i, where i : 'I_m, and j : 'I_n (via the coercion *) (* fun_of_matrix : matrix >-> Funclass). *) (* const_mx a == the constant matrix whose entries are all a (dimensions *) (* should be determined by context). *) (* map_mx f A == the pointwise image of A by f, i.e., the matrix Af *) (* congruent to A with Af i j = f (A i j) for all i and j. *) (* map2_mx f A B == the pointwise image of A and B by f, i.e., the matrix *) (* ABf congruent to A with ABf i j = f (A i j) (B i j) *) (* for all i and j. *) (* A^T == the matrix transpose of A. *) (* row i A == the i'th row of A (this is a row vector). *) (* col j A == the j'th column of A (a column vector). *) (* row' i A == A with the i'th row spliced out. *) (* col' i A == A with the j'th column spliced out. *) (* xrow i1 i2 A == A with rows i1 and i2 interchanged. *) (* xcol j1 j2 A == A with columns j1 and j2 interchanged. *) (* row_perm s A == A : 'M_(m, n) with rows permuted by s : 'S_m. *) (* col_perm s A == A : 'M_(m, n) with columns permuted by s : 'S_n. *) (* row_mx Al Ar == the row block matrix <Al Ar> obtained by concatenating *) (* two matrices Al and Ar of the same height. *) (* col_mx Au Ad == the column block matrix / Au \ (Au and Ad must have the *) (* same width). \ Ad / *) (* block_mx Aul Aur Adl Adr == the block matrix / Aul Aur \ *) (* \ Adl Adr / *) (* \mxblock_(i < m, j < n) B i j *) (* == the block matrix of type 'M_(\sum_i p_ i, \sum_j q_ j) *) (* / (B 0 0) ⋯ (B 0 j) ⋯ (B 0 n) \ *) (* | ... ... ... | *) (* | (B i 0) ⋯ (B i j) ⋯ (B i n) | *) (* | ... ... ... | *) (* \ (B m 0) ⋯ (B m j) ⋯ (B m n) / *) (* where each block (B i j) has type 'M_(p_ i, q_ j). *) (* \mxdiag_(i < n) B i == the block square matrix of type 'M_(\sum_i p_ i) *) (* / (B 0) 0 \ *) (* | ... ... | *) (* | 0 (B i) 0 | *) (* | ... ... | *) (* \ 0 (B n) / *) (* where each block (B i) has type 'M_(p_ i). *) (* \mxrow_(j < n) B j == the block matrix of type 'M_(m, \sum_j q_ j). *) (* < (B 0) ... (B n) > *) (* where each block (B j) has type 'M_(m, q_ j). *) (* \mxcol_(i < m) B i == the block matrix of type 'M_(\sum_i p_ i, n) *) (* / (B 0) \ *) (* | ... | *) (* \ (B m) / *) (* where each block (B i) has type 'M(p_ i, n). *) (* [l|r]submx A == the left/right submatrices of a row block matrix A. *) (* Note that the type of A, 'M_(m, n1 + n2) indicates how A *) (* should be decomposed. *) (* [u|d]submx A == the up/down submatrices of a column block matrix A. *) (* [u|d][l|r]submx A == the upper left, etc submatrices of a block matrix A. *) (* submxblock A i j == the block submatrix of type 'M_(p_ i, q_ j) of A. *) (* The type of A, 'M_(\sum_i p_ i, \sum_i q_ i) *) (* indicates how A should be decomposed. *) (* There is no analogous for mxdiag since one can use *) (* submxblock A i i to extract a diagonal block. *) (* submxrow A j == the submatrix of type 'M_(m, q_ j) of A. The type of A, *) (* 'M_(m, \sum_j q_ j) indicates how A should be decomposed.*) (* submxrow A j == the submatrix of type 'M_(p_ i, n) of A. The type of A, *) (* 'M_(\sum_i p_ i, n) indicates how A should be decomposed.*) (* mxsub f g A == generic reordered submatrix, given by functions f and g *) (* which specify which subset of rows and columns to take *) (* and how to reorder them, e.g. picking f and g to be *) (* increasing yields traditional submatrices. *) (* := \matrix_(i, j) A (f i) (g i) *) (* rowsub f A := mxsub f id A *) (* colsub g A := mxsub id g A *) (* castmx eq_mn A == A : 'M_(m, n) cast to 'M_(m', n') using the equation *) (* pair eq_mn : (m = m') * (n = n'). This is the usual *) (* workaround for the syntactic limitations of dependent *) (* types in Coq, and can be used to introduce a block *) (* decomposition. It simplifies to A when eq_mn is the *) (* pair (erefl m, erefl n) (using rewrite /castmx /=). *) (* conform_mx B A == A if A and B have the same dimensions, else B. *) (* mxvec A == a row vector of width m * n holding all the entries of *) (* the m x n matrix A. *) (* mxvec_index i j == the index of A i j in mxvec A. *) (* vec_mx v == the inverse of mxvec, reshaping a vector of width m * n *) (* back into into an m x n rectangular matrix. *) (* In 'M[R]_(m, n), R can be any type, but 'M[R]_(m, n) inherits the eqType, *) (* choiceType, countType, finType, nmodType, and zmodType structures from R; *) (* 'M[R]_(m, n) also forms a natural lmodType R when R is a pzRingType. *) (* Square matrices of type 'M[R]_n (resp. non-trivial square matrices of type *) (* 'M[R]_n.+1) inherit the pz(Semi)RingType (resp. nz(Semi)RingType) structure*) (* from R; indeed they then have an algebra structure (lalgType R, or algType *) (* R if R is a comNzRingType, or even unitAlgType if R is a comUnitRingType). *) (* We thus provide separate syntax for the general matrix multiplication, *) (* and other operations for matrices over a pzRingType R: *) (* A *m B == the matrix product of A and B; the width of A must be *) (* equal to the height of B. *) (* a%:M == the scalar matrix with a's on the main diagonal; in *) (* particular 1%:M denotes the identity matrix, and is *) (* equal to 1%R when n is of the form n'.+1 (e.g., n >= 1). *) (* is_scalar_mx A <=> A is a scalar matrix (A = a%:M for some A). *) (* diag_mx d == the diagonal matrix whose main diagonal is d : 'rV_n. *) (* is_diag_mx A <=> A is a diagonal matrix: forall i j, i != j -> A i j = 0 *) (* is_trig_mx A <=> A is a triangular matrix: forall i j, i < j -> A i j = 0 *) (* delta_mx i j == the matrix with a 1 in row i, column j and 0 elsewhere. *) (* pid_mx r == the partial identity matrix with 1s only on the r first *) (* coefficients of the main diagonal; the dimensions of *) (* pid_mx r are determined by the context, and pid_mx r can *) (* be rectangular. *) (* copid_mx r == the complement to 1%:M of pid_mx r: a square diagonal *) (* matrix with 1s on all but the first r coefficients on *) (* its main diagonal. *) (* perm_mx s == the n x n permutation matrix for s : 'S_n. *) (* tperm_mx i1 i2 == the permutation matrix that exchanges i1 i2 : 'I_n. *) (* is_perm_mx A == A is a permutation matrix. *) (* lift0_mx A == the 1 + n square matrix block_mx 1 0 0 A when A : 'M_n. *) (* \tr A == the trace of a square matrix A. *) (* \det A == the determinant of A, using the Leibnitz formula. *) (* cofactor i j A == the i, j cofactor of A (the signed i, j minor of A), *) (* \adj A == the adjugate matrix of A (\adj A i j = cofactor j i A). *) (* A \in unitmx == A is invertible (R must be a comUnitRingType). *) (* invmx A == the inverse matrix of A if A \in unitmx A, otherwise A. *) (* A \is a mxOver S == the matrix A has its coefficients in S. *) (* comm_mx A B := A *m B = B *m A *) (* comm_mxb A B := A *m B == B *m A *) (* all_comm_mx As fs := all2rel comm_mxb fs *) (* The following operations provide a correspondence between linear functions *) (* and matrices: *) (* lin1_mx f == the m x n matrix that emulates via right product *) (* a (linear) function f : 'rV_m -> 'rV_n on ROW VECTORS *) (* lin_mx f == the (m1 * n1) x (m2 * n2) matrix that emulates, via the *) (* right multiplication on the mxvec encodings, a linear *) (* function f : 'M_(m1, n1) -> 'M_(m2, n2) *) (* lin_mul_row u := lin1_mx (mulmx u \o vec_mx) (applies a row-encoded *) (* function to the row-vector u). *) (* mulmx A == partially applied matrix multiplication (mulmx A B is *) (* displayed as A *m B), with, for A : 'M_(m, n), a *) (* canonical {linear 'M_(n, p) -> 'M(m, p}} structure. *) (* mulmxr A == self-simplifying right-hand matrix multiplication, i.e., *) (* mulmxr A B simplifies to B *m A, with, for A : 'M_(n, p), *) (* a canonical {linear 'M_(m, n) -> 'M(m, p}} structure. *) (* lin_mulmx A := lin_mx (mulmx A). *) (* lin_mulmxr A := lin_mx (mulmxr A). *) (* We also extend any finType structure of R to 'M[R]_(m, n), and define: *) (* {'GL_n[R]} == the finGroupType of units of 'M[R]_n.-1.+1. *) (* 'GL_n[R] == the general linear group of all matrices in {'GL_n(R)}. *) (* 'GL_n(p) == 'GL_n['F_p], the general linear group of a prime field. *) (* GLval u == the coercion of u : {'GL_n(R)} to a matrix. *) (* In addition to the lemmas relevant to these definitions, this file also *) (* proves several classic results, including : *) (* - The determinant is a multilinear alternate form. *) (* - The Laplace determinant expansion formulas: expand_det_[row|col]. *) (* - The Cramer rule : mul_mx_adj & mul_adj_mx. *) (* Vandermonde m a == the 'M[R]_(m, n) Vandermonde matrix, given a : 'rV_n *) (* / 1 ... 1 \ *) (* | (a 0 0) ... (a 0 (n - 1)) | *) (* | (a 0 0 ^+ 2) ... (a 0 (n - 1) ^+ 2) | *) (* | ... ... | *) (* \ (a 0 0 ^+ (m - 1)) ... (a 0 (n - 1) ^+ (m - 1)) / *) (* := \matrix_(i < m, j < n) a 0 j ^+ i. *) (* Finally, as an example of the use of block products, we program and prove *) (* the correctness of a classical linear algebra algorithm: *) (* cormen_lup A == the triangular decomposition (L, U, P) of a nontrivial *) (* square matrix A into a lower triagular matrix L with 1s *) (* on the main diagonal, an upper matrix U, and a *) (* permutation matrix P, such that P * A = L * U. *) (* This is example only; we use a different, more precise algorithm to *) (* develop the theory of matrix ranks and row spaces in mxalgebra.v *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Import GRing.Theory. Local Open Scope ring_scope. Reserved Notation "''M_' n" (at level 0, n at level 2, format "''M_' n"). Reserved Notation "''rV_' n" (at level 0, n at level 2, format "''rV_' n"). Reserved Notation "''cV_' n" (at level 0, n at level 2, format "''cV_' n"). Reserved Notation "''M_' ( n )". (* only parsing *) Reserved Notation "''M_' ( m , n )" (format "''M_' ( m , n )"). Reserved Notation "''M[' R ]_ n" (at level 0, n at level 2). (* only parsing *) Reserved Notation "''rV[' R ]_ n" (at level 0, n at level 2). (* only parsing *) Reserved Notation "''cV[' R ]_ n" (at level 0, n at level 2). (* only parsing *) Reserved Notation "''M[' R ]_ ( n )". (* only parsing *) Reserved Notation "''M[' R ]_ ( m , n )". (* only parsing *) Reserved Notation "\matrix_ i E" (at level 34, E at level 39, i at level 2, format "\matrix_ i E"). Reserved Notation "\matrix_ ( i < n ) E" (E at level 39, i, n at level 50). (* only parsing *) Reserved Notation "\matrix_ ( i , j ) E" (E at level 39, j at level 50, format "\matrix_ ( i , j ) E"). Reserved Notation "\matrix[ k ]_ ( i , j ) E" (at level 34, E at level 39, i, j at level 50, format "\matrix[ k ]_ ( i , j ) E"). Reserved Notation "\matrix_ ( i < m , j < n ) E" (E at level 39, j, n at level 50). (* only parsing *) Reserved Notation "\matrix_ ( i , j < n ) E" (E at level 39, n at level 50). (* only parsing *) Reserved Notation "\row_ j E" (at level 34, E at level 39, j at level 2, format "\row_ j E"). Reserved Notation "\row_ ( j < n ) E" (E at level 39, j, n at level 50). (* only parsing *) Reserved Notation "\col_ j E" (at level 34, E at level 39, j at level 2, format "\col_ j E"). Reserved Notation "\col_ ( j < n ) E" (E at level 39, j, n at level 50). (* only parsing *) Reserved Notation "\mxblock_ ( i , j ) E" (at level 34, E at level 39, i, j at level 50, format "\mxblock_ ( i , j ) E"). Reserved Notation "\mxblock_ ( i < m , j < n ) E" (E at level 39, m, j, n at level 50). (* only parsing *) Reserved Notation "\mxblock_ ( i , j < n ) E" (E at level 39, n at level 50). (* only parsing *) Reserved Notation "\mxrow_ j E" (at level 34, E at level 39, j at level 2, format "\mxrow_ j E"). Reserved Notation "\mxrow_ ( j < n ) E" (E at level 39, j, n at level 50). (* only parsing *) Reserved Notation "\mxcol_ j E" (at level 34, E at level 39, j at level 2, format "\mxcol_ j E"). Reserved Notation "\mxcol_ ( j < n ) E" (E at level 39, j, n at level 50). (* only parsing *) Reserved Notation "\mxdiag_ j E" (at level 34, E at level 39, j at level 2, format "\mxdiag_ j E"). Reserved Notation "\mxdiag_ ( j < n ) E" (E at level 39, j, n at level 50). (* only parsing *) Reserved Notation "x %:M" (format "x %:M"). Reserved Notation "A *m B" (at level 40, left associativity, format "A *m B"). Reserved Notation "A ^T" (format "A ^T"). Reserved Notation "\tr A" (at level 10, A at level 8, format "\tr A"). Reserved Notation "\det A" (at level 10, A at level 8, format "\det A"). Reserved Notation "\adj A" (at level 10, A at level 8, format "\adj A"). Reserved Notation "{ ''GL_' n [ R ] }" (n at level 2, format "{ ''GL_' n [ R ] }"). Reserved Notation "{ ''GL_' n ( p ) }" (p at level 10, format "{ ''GL_' n ( p ) }"). Local Notation simp := (Monoid.Theory.simpm, oppr0). (*****************************************************************************) (****************************Type Definition**********************************) (*****************************************************************************) Section MatrixDef. Variable R : Type. Variables m n : nat. (* Basic linear algebra (matrices). *) (* We use dependent types (ordinals) for the indices so that ranges are *) (* mostly inferred automatically *) Variant matrix : predArgType := Matrix of {ffun 'I_m * 'I_n -> R}. Definition mx_val A := let: Matrix g := A in g. HB.instance Definition _ := [isNew for mx_val]. Definition fun_of_matrix A (i : 'I_m) (j : 'I_n) := mx_val A (i, j). Coercion fun_of_matrix : matrix >-> Funclass. End MatrixDef. Fact matrix_key : unit. Proof. by []. Qed. HB.lock Definition matrix_of_fun R (m n : nat) (k : unit) (F : 'I_m -> 'I_n -> R) := @Matrix R m n [ffun ij => F ij.1 ij.2]. Canonical matrix_unlockable := Unlockable matrix_of_fun.unlock. Section MatrixDef2. Variable R : Type. Variables m n : nat. Implicit Type F : 'I_m -> 'I_n -> R. Lemma mxE k F : matrix_of_fun k F =2 F. Proof. by move=> i j; rewrite unlock /fun_of_matrix /= ffunE. Qed. Lemma matrixP (A B : matrix R m n) : A =2 B <-> A = B. Proof. rewrite /fun_of_matrix; split=> [/= eqAB | -> //]. by apply/val_inj/ffunP=> [[i j]]; apply: eqAB. Qed. Lemma eq_mx k F1 F2 : (F1 =2 F2) -> matrix_of_fun k F1 = matrix_of_fun k F2. Proof. by move=> eq_F; apply/matrixP => i j; rewrite !mxE eq_F. Qed. End MatrixDef2. Arguments eq_mx {R m n k} [F1] F2 eq_F12. Bind Scope ring_scope with matrix. Notation "''M[' R ]_ ( m , n )" := (matrix R m n) (only parsing): type_scope. Notation "''rV[' R ]_ n" := 'M[R]_(1, n) (only parsing) : type_scope. Notation "''cV[' R ]_ n" := 'M[R]_(n, 1) (only parsing) : type_scope. Notation "''M[' R ]_ n" := 'M[R]_(n, n) (only parsing) : type_scope. Notation "''M[' R ]_ ( n )" := 'M[R]_n (only parsing) : type_scope. Notation "''M_' ( m , n )" := 'M[_]_(m, n) : type_scope. Notation "''rV_' n" := 'M_(1, n) : type_scope. Notation "''cV_' n" := 'M_(n, 1) : type_scope. Notation "''M_' n" := 'M_(n, n) : type_scope. Notation "''M_' ( n )" := 'M_n (only parsing) : type_scope. Notation "\matrix[ k ]_ ( i , j ) E" := (matrix_of_fun k (fun i j => E)) : ring_scope. Notation "\matrix_ ( i < m , j < n ) E" := (@matrix_of_fun _ m n matrix_key (fun i j => E)) (only parsing) : ring_scope. Notation "\matrix_ ( i , j < n ) E" := (\matrix_(i < n, j < n) E) (only parsing) : ring_scope. Notation "\matrix_ ( i , j ) E" := (\matrix_(i < _, j < _) E) : ring_scope. Notation "\matrix_ ( i < m ) E" := (\matrix_(i < m, j < _) @fun_of_matrix _ 1 _ E 0 j) (only parsing) : ring_scope. Notation "\matrix_ i E" := (\matrix_(i < _) E) : ring_scope. Notation "\col_ ( i < n ) E" := (@matrix_of_fun _ n 1 matrix_key (fun i _ => E)) (only parsing) : ring_scope. Notation "\col_ i E" := (\col_(i < _) E) : ring_scope. Notation "\row_ ( j < n ) E" := (@matrix_of_fun _ 1 n matrix_key (fun _ j => E)) (only parsing) : ring_scope. Notation "\row_ j E" := (\row_(j < _) E) : ring_scope. HB.instance Definition _ (R : eqType) m n := [Equality of 'M[R]_(m, n) by <:]. HB.instance Definition _ (R : choiceType) m n := [Choice of 'M[R]_(m, n) by <:]. HB.instance Definition _ (R : countType) m n := [Countable of 'M[R]_(m, n) by <:]. HB.instance Definition _ (R : finType) m n := [Finite of 'M[R]_(m, n) by <:]. Lemma card_mx (F : finType) m n : (#|{: 'M[F]_(m, n)}| = #|F| ^ (m * n))%N. Proof. by rewrite card_sub card_ffun card_prod !card_ord. Qed. (*****************************************************************************) (****** Matrix structural operations (transpose, permutation, blocks) ********) (*****************************************************************************) Section MatrixStructural. Variable R : Type. (* Constant matrix *) Fact const_mx_key : unit. Proof. by []. Qed. Definition const_mx m n a : 'M[R]_(m, n) := \matrix[const_mx_key]_(i, j) a. Arguments const_mx {m n}. Section FixedDim. (* Definitions and properties for which we can work with fixed dimensions. *) Variables m n : nat. Implicit Type A : 'M[R]_(m, n). (* Reshape a matrix, to accommodate the block functions for instance. *) Definition castmx m' n' (eq_mn : (m = m') * (n = n')) A : 'M_(m', n') := let: erefl in _ = m' := eq_mn.1 return 'M_(m', n') in let: erefl in _ = n' := eq_mn.2 return 'M_(m, n') in A. Definition conform_mx m' n' B A := match m =P m', n =P n' with | ReflectT eq_m, ReflectT eq_n => castmx (eq_m, eq_n) A | _, _ => B end. (* Transpose a matrix *) Fact trmx_key : unit. Proof. by []. Qed. Definition trmx A := \matrix[trmx_key]_(i, j) A j i. (* Permute a matrix vertically (rows) or horizontally (columns) *) Fact row_perm_key : unit. Proof. by []. Qed. Definition row_perm (s : 'S_m) A := \matrix[row_perm_key]_(i, j) A (s i) j. Fact col_perm_key : unit. Proof. by []. Qed. Definition col_perm (s : 'S_n) A := \matrix[col_perm_key]_(i, j) A i (s j). (* Exchange two rows/columns of a matrix *) Definition xrow i1 i2 := row_perm (tperm i1 i2). Definition xcol j1 j2 := col_perm (tperm j1 j2). (* Row/Column sub matrices of a matrix *) Definition row i0 A := \row_j A i0 j. Definition col j0 A := \col_i A i j0. (* Removing a row/column from a matrix *) Definition row' i0 A := \matrix_(i, j) A (lift i0 i) j. Definition col' j0 A := \matrix_(i, j) A i (lift j0 j). (* reindexing/subindex a matrix *) Definition mxsub m' n' f g A := \matrix_(i < m', j < n') A (f i) (g j). Local Notation colsub g := (mxsub id g). Local Notation rowsub f := (mxsub f id). Lemma castmx_const m' n' (eq_mn : (m = m') * (n = n')) a : castmx eq_mn (const_mx a) = const_mx a. Proof. by case: eq_mn; case: m' /; case: n' /. Qed. Lemma trmx_const a : trmx (const_mx a) = const_mx a. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma row_perm_const s a : row_perm s (const_mx a) = const_mx a. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma col_perm_const s a : col_perm s (const_mx a) = const_mx a. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma xrow_const i1 i2 a : xrow i1 i2 (const_mx a) = const_mx a. Proof. exact: row_perm_const. Qed. Lemma xcol_const j1 j2 a : xcol j1 j2 (const_mx a) = const_mx a. Proof. exact: col_perm_const. Qed. Lemma rowP (u v : 'rV[R]_n) : u 0 =1 v 0 <-> u = v. Proof. by split=> [eq_uv | -> //]; apply/matrixP=> i; rewrite ord1. Qed. Lemma rowK u_ i0 : row i0 (\matrix_i u_ i) = u_ i0. Proof. by apply/rowP=> i'; rewrite !mxE. Qed. Lemma row_matrixP A B : (forall i, row i A = row i B) <-> A = B. Proof. split=> [eqAB | -> //]; apply/matrixP=> i j. by move/rowP/(_ j): (eqAB i); rewrite !mxE. Qed. Lemma colP (u v : 'cV[R]_m) : u^~ 0 =1 v^~ 0 <-> u = v. Proof. by split=> [eq_uv | -> //]; apply/matrixP=> i j; rewrite ord1. Qed. Lemma row_const i0 a : row i0 (const_mx a) = const_mx a. Proof. by apply/rowP=> j; rewrite !mxE. Qed. Lemma col_const j0 a : col j0 (const_mx a) = const_mx a. Proof. by apply/colP=> i; rewrite !mxE. Qed. Lemma row'_const i0 a : row' i0 (const_mx a) = const_mx a. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma col'_const j0 a : col' j0 (const_mx a) = const_mx a. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma col_perm1 A : col_perm 1 A = A. Proof. by apply/matrixP=> i j; rewrite mxE perm1. Qed. Lemma row_perm1 A : row_perm 1 A = A. Proof. by apply/matrixP=> i j; rewrite mxE perm1. Qed. Lemma col_permM s t A : col_perm (s * t) A = col_perm s (col_perm t A). Proof. by apply/matrixP=> i j; rewrite !mxE permM. Qed. Lemma row_permM s t A : row_perm (s * t) A = row_perm s (row_perm t A). Proof. by apply/matrixP=> i j; rewrite !mxE permM. Qed. Lemma col_row_permC s t A : col_perm s (row_perm t A) = row_perm t (col_perm s A). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma rowEsub i : row i = rowsub (fun=> i). Proof. by []. Qed. Lemma colEsub j : col j = colsub (fun=> j). Proof. by []. Qed. Lemma row'Esub i : row' i = rowsub (lift i). Proof. by []. Qed. Lemma col'Esub j : col' j = colsub (lift j). Proof. by []. Qed. Lemma row_permEsub s : row_perm s = rowsub s. Proof. by rewrite /row_perm /mxsub !unlock. Qed. Lemma col_permEsub s : col_perm s = colsub s. Proof. by rewrite /col_perm /mxsub !unlock. Qed. Lemma xrowEsub i1 i2 : xrow i1 i2 = rowsub (tperm i1 i2). Proof. exact: row_permEsub. Qed. Lemma xcolEsub j1 j2 : xcol j1 j2 = colsub (tperm j1 j2). Proof. exact: col_permEsub. Qed. Lemma mxsub_id : mxsub id id =1 id. Proof. by move=> A; apply/matrixP => i j; rewrite !mxE. Qed. Lemma eq_mxsub m' n' f f' g g' : f =1 f' -> g =1 g' -> @mxsub m' n' f g =1 mxsub f' g'. Proof. by move=> eq_f eq_g A; apply/matrixP => i j; rewrite !mxE eq_f eq_g. Qed. Lemma eq_rowsub m' (f f' : 'I_m' -> 'I_m) : f =1 f' -> rowsub f =1 rowsub f'. Proof. by move=> /eq_mxsub; apply. Qed. Lemma eq_colsub n' (g g' : 'I_n' -> 'I_n) : g =1 g' -> colsub g =1 colsub g'. Proof. by move=> /eq_mxsub; apply. Qed. Lemma mxsub_eq_id f g : f =1 id -> g =1 id -> mxsub f g =1 id. Proof. by move=> fid gid A; rewrite (eq_mxsub fid gid) mxsub_id. Qed. Lemma mxsub_eq_colsub n' f g : f =1 id -> @mxsub _ n' f g =1 colsub g. Proof. by move=> f_id; apply: eq_mxsub. Qed. Lemma mxsub_eq_rowsub m' f g : g =1 id -> @mxsub m' _ f g =1 rowsub f. Proof. exact: eq_mxsub. Qed. Lemma mxsub_ffunl m' n' f g : @mxsub m' n' (finfun f) g =1 mxsub f g. Proof. by apply: eq_mxsub => // i; rewrite ffunE. Qed. Lemma mxsub_ffunr m' n' f g : @mxsub m' n' f (finfun g) =1 mxsub f g. Proof. by apply: eq_mxsub => // i; rewrite ffunE. Qed. Lemma mxsub_ffun m' n' f g : @mxsub m' n' (finfun f) (finfun g) =1 mxsub f g. Proof. by move=> A; rewrite mxsub_ffunl mxsub_ffunr. Qed. Lemma mxsub_const m' n' f g a : @mxsub m' n' f g (const_mx a) = const_mx a. Proof. by apply/matrixP => i j; rewrite !mxE. Qed. End FixedDim. Local Notation colsub g := (mxsub id g). Local Notation rowsub f := (mxsub f id). Local Notation "A ^T" := (trmx A) : ring_scope. Lemma castmx_id m n erefl_mn (A : 'M_(m, n)) : castmx erefl_mn A = A. Proof. by case: erefl_mn => e_m e_n; rewrite [e_m]eq_axiomK [e_n]eq_axiomK. Qed. Lemma castmx_comp m1 n1 m2 n2 m3 n3 (eq_m1 : m1 = m2) (eq_n1 : n1 = n2) (eq_m2 : m2 = m3) (eq_n2 : n2 = n3) A : castmx (eq_m2, eq_n2) (castmx (eq_m1, eq_n1) A) = castmx (etrans eq_m1 eq_m2, etrans eq_n1 eq_n2) A. Proof. by case: m2 / eq_m1 eq_m2; case: m3 /; case: n2 / eq_n1 eq_n2; case: n3 /. Qed. Lemma castmxK m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) : cancel (castmx (eq_m, eq_n)) (castmx (esym eq_m, esym eq_n)). Proof. by case: m2 / eq_m; case: n2 / eq_n. Qed. Lemma castmxKV m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) : cancel (castmx (esym eq_m, esym eq_n)) (castmx (eq_m, eq_n)). Proof. by case: m2 / eq_m; case: n2 / eq_n. Qed. (* This can be use to reverse an equation that involves a cast. *) Lemma castmx_sym m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) A1 A2 : A1 = castmx (eq_m, eq_n) A2 -> A2 = castmx (esym eq_m, esym eq_n) A1. Proof. by move/(canLR (castmxK _ _)). Qed. Lemma eq_castmx m1 n1 m2 n2 (eq_mn eq_mn' : (m1 = m2) * (n1 = n2)) : castmx eq_mn =1 castmx eq_mn'. Proof. case: eq_mn eq_mn' => [em en] [em' en'] A. by apply: (canRL (castmxKV _ _)); rewrite castmx_comp castmx_id. Qed. Lemma castmxE m1 n1 m2 n2 (eq_mn : (m1 = m2) * (n1 = n2)) A i j : castmx eq_mn A i j = A (cast_ord (esym eq_mn.1) i) (cast_ord (esym eq_mn.2) j). Proof. by do [case: eq_mn; case: m2 /; case: n2 /] in A i j *; rewrite !cast_ord_id. Qed. Lemma conform_mx_id m n (B A : 'M_(m, n)) : conform_mx B A = A. Proof. by rewrite /conform_mx; do 2!case: eqP => // *; rewrite castmx_id. Qed. Lemma nonconform_mx m m' n n' (B : 'M_(m', n')) (A : 'M_(m, n)) : (m != m') || (n != n') -> conform_mx B A = B. Proof. by rewrite /conform_mx; do 2!case: eqP. Qed. Lemma conform_castmx m1 n1 m2 n2 m3 n3 (e_mn : (m2 = m3) * (n2 = n3)) (B : 'M_(m1, n1)) A : conform_mx B (castmx e_mn A) = conform_mx B A. Proof. by do [case: e_mn; case: m3 /; case: n3 /] in A *. Qed. Lemma trmxK m n : cancel (@trmx m n) (@trmx n m). Proof. by move=> A; apply/matrixP=> i j; rewrite !mxE. Qed. Lemma trmx_inj m n : injective (@trmx m n). Proof. exact: can_inj (@trmxK m n). Qed. Lemma trmx_cast m1 n1 m2 n2 (eq_mn : (m1 = m2) * (n1 = n2)) A : (castmx eq_mn A)^T = castmx (eq_mn.2, eq_mn.1) A^T. Proof. by case: eq_mn => eq_m eq_n; apply/matrixP=> i j; rewrite !(mxE, castmxE). Qed. Lemma trmx_conform m' n' m n (B : 'M_(m', n')) (A : 'M_(m, n)) : (conform_mx B A)^T = conform_mx B^T A^T. Proof. rewrite /conform_mx; do !case: eqP; rewrite ?mxE// => en em. by rewrite trmx_cast. Qed. Lemma tr_row_perm m n s (A : 'M_(m, n)) : (row_perm s A)^T = col_perm s A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma tr_col_perm m n s (A : 'M_(m, n)) : (col_perm s A)^T = row_perm s A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma tr_xrow m n i1 i2 (A : 'M_(m, n)) : (xrow i1 i2 A)^T = xcol i1 i2 A^T. Proof. exact: tr_row_perm. Qed. Lemma tr_xcol m n j1 j2 (A : 'M_(m, n)) : (xcol j1 j2 A)^T = xrow j1 j2 A^T. Proof. exact: tr_col_perm. Qed. Lemma row_id n i (V : 'rV_n) : row i V = V. Proof. by apply/rowP=> j; rewrite mxE [i]ord1. Qed. Lemma col_id n j (V : 'cV_n) : col j V = V. Proof. by apply/colP=> i; rewrite mxE [j]ord1. Qed. Lemma row_eq m1 m2 n i1 i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : row i1 A1 = row i2 A2 -> A1 i1 =1 A2 i2. Proof. by move/rowP=> eqA12 j; have /[!mxE] := eqA12 j. Qed. Lemma col_eq m n1 n2 j1 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : col j1 A1 = col j2 A2 -> A1^~ j1 =1 A2^~ j2. Proof. by move/colP=> eqA12 i; have /[!mxE] := eqA12 i. Qed. Lemma row'_eq m n i0 (A B : 'M_(m, n)) : row' i0 A = row' i0 B -> {in predC1 i0, A =2 B}. Proof. move=> /matrixP eqAB' i /[!inE]/[1!eq_sym]/unlift_some[i' -> _] j. by have /[!mxE] := eqAB' i' j. Qed. Lemma col'_eq m n j0 (A B : 'M_(m, n)) : col' j0 A = col' j0 B -> forall i, {in predC1 j0, A i =1 B i}. Proof. move=> /matrixP eqAB' i j /[!inE]/[1!eq_sym]/unlift_some[j' -> _]. by have /[!mxE] := eqAB' i j'. Qed. Lemma tr_row m n i0 (A : 'M_(m, n)) : (row i0 A)^T = col i0 A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma tr_row' m n i0 (A : 'M_(m, n)) : (row' i0 A)^T = col' i0 A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma tr_col m n j0 (A : 'M_(m, n)) : (col j0 A)^T = row j0 A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma tr_col' m n j0 (A : 'M_(m, n)) : (col' j0 A)^T = row' j0 A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxsub_comp m1 m2 m3 n1 n2 n3 (f : 'I_m2 -> 'I_m1) (f' : 'I_m3 -> 'I_m2) (g : 'I_n2 -> 'I_n1) (g' : 'I_n3 -> 'I_n2) (A : 'M_(m1, n1)) : mxsub (f \o f') (g \o g') A = mxsub f' g' (mxsub f g A). Proof. by apply/matrixP => i j; rewrite !mxE. Qed. Lemma rowsub_comp m1 m2 m3 n (f : 'I_m2 -> 'I_m1) (f' : 'I_m3 -> 'I_m2) (A : 'M_(m1, n)) : rowsub (f \o f') A = rowsub f' (rowsub f A). Proof. exact: mxsub_comp. Qed. Lemma colsub_comp m n n2 n3 (g : 'I_n2 -> 'I_n) (g' : 'I_n3 -> 'I_n2) (A : 'M_(m, n)) : colsub (g \o g') A = colsub g' (colsub g A). Proof. exact: mxsub_comp. Qed. Lemma mxsubrc m1 m2 n n2 f g (A : 'M_(m1, n)) : mxsub f g A = rowsub f (colsub g A) :> 'M_(m2, n2). Proof. exact: mxsub_comp. Qed. Lemma mxsubcr m1 m2 n n2 f g (A : 'M_(m1, n)) : mxsub f g A = colsub g (rowsub f A) :> 'M_(m2, n2). Proof. exact: mxsub_comp. Qed. Lemma rowsub_cast m1 m2 n (eq_m : m1 = m2) (A : 'M_(m2, n)) : rowsub (cast_ord eq_m) A = castmx (esym eq_m, erefl) A. Proof. by case: _ / eq_m in A *; apply: (mxsub_eq_id (cast_ord_id _)). Qed. Lemma colsub_cast m n1 n2 (eq_n : n1 = n2) (A : 'M_(m, n2)) : colsub (cast_ord eq_n) A = castmx (erefl, esym eq_n) A. Proof. by case: _ / eq_n in A *; apply: (mxsub_eq_id _ (cast_ord_id _)). Qed. Lemma mxsub_cast m1 m2 n1 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) A : mxsub (cast_ord eq_m) (cast_ord eq_n) A = castmx (esym eq_m, esym eq_n) A. Proof. by rewrite mxsubrc rowsub_cast colsub_cast castmx_comp/= etrans_id. Qed. Lemma castmxEsub m1 m2 n1 n2 (eq_mn : (m1 = m2) * (n1 = n2)) A : castmx eq_mn A = mxsub (cast_ord (esym eq_mn.1)) (cast_ord (esym eq_mn.2)) A. Proof. by rewrite mxsub_cast !esymK; case: eq_mn. Qed. Lemma trmx_mxsub m1 m2 n1 n2 f g (A : 'M_(m1, n1)) : (mxsub f g A)^T = mxsub g f A^T :> 'M_(n2, m2). Proof. by apply/matrixP => i j; rewrite !mxE. Qed. Lemma row_mxsub m1 m2 n1 n2 (f : 'I_m2 -> 'I_m1) (g : 'I_n2 -> 'I_n1) (A : 'M_(m1, n1)) i : row i (mxsub f g A) = row (f i) (colsub g A). Proof. by rewrite !rowEsub -!mxsub_comp. Qed. Lemma col_mxsub m1 m2 n1 n2 (f : 'I_m2 -> 'I_m1) (g : 'I_n2 -> 'I_n1) (A : 'M_(m1, n1)) i : col i (mxsub f g A) = col (g i) (rowsub f A). Proof. by rewrite !colEsub -!mxsub_comp. Qed. Lemma row_rowsub m1 m2 n (f : 'I_m2 -> 'I_m1) (A : 'M_(m1, n)) i : row i (rowsub f A) = row (f i) A. Proof. by rewrite row_mxsub mxsub_id. Qed. Lemma col_colsub m n1 n2 (g : 'I_n2 -> 'I_n1) (A : 'M_(m, n1)) i : col i (colsub g A) = col (g i) A. Proof. by rewrite col_mxsub mxsub_id. Qed. Ltac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?]. Section CutPaste. Variables m m1 m2 n n1 n2 : nat. (* Concatenating two matrices, in either direction. *) Fact row_mx_key : unit. Proof. by []. Qed. Definition row_mx (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : 'M[R]_(m, n1 + n2) := \matrix[row_mx_key]_(i, j) match split j with inl j1 => A1 i j1 | inr j2 => A2 i j2 end. Fact col_mx_key : unit. Proof. by []. Qed. Definition col_mx (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : 'M[R]_(m1 + m2, n) := \matrix[col_mx_key]_(i, j) match split i with inl i1 => A1 i1 j | inr i2 => A2 i2 j end. (* Left/Right | Up/Down submatrices of a rows | columns matrix. *) (* The shape of the (dependent) width parameters of the type of A *) (* determines which submatrix is selected. *) Fact lsubmx_key : unit. Proof. by []. Qed. Definition lsubmx (A : 'M[R]_(m, n1 + n2)) := \matrix[lsubmx_key]_(i, j) A i (lshift n2 j). Fact rsubmx_key : unit. Proof. by []. Qed. Definition rsubmx (A : 'M[R]_(m, n1 + n2)) := \matrix[rsubmx_key]_(i, j) A i (rshift n1 j). Fact usubmx_key : unit. Proof. by []. Qed. Definition usubmx (A : 'M[R]_(m1 + m2, n)) := \matrix[usubmx_key]_(i, j) A (lshift m2 i) j. Fact dsubmx_key : unit. Proof. by []. Qed. Definition dsubmx (A : 'M[R]_(m1 + m2, n)) := \matrix[dsubmx_key]_(i, j) A (rshift m1 i) j. Lemma row_mxEl A1 A2 i j : row_mx A1 A2 i (lshift n2 j) = A1 i j. Proof. by rewrite mxE (unsplitK (inl _ _)). Qed. Lemma row_mxKl A1 A2 : lsubmx (row_mx A1 A2) = A1. Proof. by apply/matrixP=> i j; rewrite mxE row_mxEl. Qed. Lemma row_mxEr A1 A2 i j : row_mx A1 A2 i (rshift n1 j) = A2 i j. Proof. by rewrite mxE (unsplitK (inr _ _)). Qed. Lemma row_mxKr A1 A2 : rsubmx (row_mx A1 A2) = A2. Proof. by apply/matrixP=> i j; rewrite mxE row_mxEr. Qed. Lemma hsubmxK A : row_mx (lsubmx A) (rsubmx A) = A. Proof. by apply/matrixP=> i j /[!mxE]; case: split_ordP => k -> /[!mxE]. Qed. Lemma col_mxEu A1 A2 i j : col_mx A1 A2 (lshift m2 i) j = A1 i j. Proof. by rewrite mxE (unsplitK (inl _ _)). Qed. Lemma col_mxKu A1 A2 : usubmx (col_mx A1 A2) = A1. Proof. by apply/matrixP=> i j; rewrite mxE col_mxEu. Qed. Lemma col_mxEd A1 A2 i j : col_mx A1 A2 (rshift m1 i) j = A2 i j. Proof. by rewrite mxE (unsplitK (inr _ _)). Qed. Lemma col_mxKd A1 A2 : dsubmx (col_mx A1 A2) = A2. Proof. by apply/matrixP=> i j; rewrite mxE col_mxEd. Qed. Lemma lsubmxEsub : lsubmx = colsub (lshift _). Proof. by rewrite /lsubmx /mxsub !unlock. Qed. Lemma rsubmxEsub : rsubmx = colsub (@rshift _ _). Proof. by rewrite /rsubmx /mxsub !unlock. Qed. Lemma usubmxEsub : usubmx = rowsub (lshift _). Proof. by rewrite /usubmx /mxsub !unlock. Qed. Lemma dsubmxEsub : dsubmx = rowsub (@rshift _ _). Proof. by rewrite /dsubmx /mxsub !unlock. Qed. Lemma eq_row_mx A1 A2 B1 B2 : row_mx A1 A2 = row_mx B1 B2 -> A1 = B1 /\ A2 = B2. Proof. move=> eqAB; move: (congr1 lsubmx eqAB) (congr1 rsubmx eqAB). by rewrite !(row_mxKl, row_mxKr). Qed. Lemma eq_col_mx A1 A2 B1 B2 : col_mx A1 A2 = col_mx B1 B2 -> A1 = B1 /\ A2 = B2. Proof. move=> eqAB; move: (congr1 usubmx eqAB) (congr1 dsubmx eqAB). by rewrite !(col_mxKu, col_mxKd). Qed. Lemma lsubmx_const (r : R) : lsubmx (const_mx r : 'M_(m, n1 + n2)) = const_mx r. Proof. by apply/matrixP => i j; rewrite !mxE. Qed. Lemma rsubmx_const (r : R) : rsubmx (const_mx r : 'M_(m, n1 + n2)) = const_mx r. Proof. by apply/matrixP => i j; rewrite !mxE. Qed. Lemma row_mx_const a : row_mx (const_mx a) (const_mx a) = const_mx a. Proof. by split_mxE. Qed. Lemma col_mx_const a : col_mx (const_mx a) (const_mx a) = const_mx a. Proof. by split_mxE. Qed. Lemma row_usubmx A i : row i (usubmx A) = row (lshift m2 i) A. Proof. by apply/rowP=> j; rewrite !mxE; congr (A _ _); apply/val_inj. Qed. Lemma row_dsubmx A i : row i (dsubmx A) = row (rshift m1 i) A. Proof. by apply/rowP=> j; rewrite !mxE; congr (A _ _); apply/val_inj. Qed. Lemma col_lsubmx A i : col i (lsubmx A) = col (lshift n2 i) A. Proof. by apply/colP=> j; rewrite !mxE; congr (A _ _); apply/val_inj. Qed. Lemma col_rsubmx A i : col i (rsubmx A) = col (rshift n1 i) A. Proof. by apply/colP=> j; rewrite !mxE; congr (A _ _); apply/val_inj. Qed. End CutPaste. Lemma row_thin_mx m n (A : 'M_(m,0)) (B : 'M_(m,n)) : row_mx A B = B. Proof. apply/matrixP=> i j; rewrite mxE; case: splitP=> [|k H]; first by case. by congr fun_of_matrix; exact: val_inj. Qed. Lemma col_flat_mx m n (A : 'M_(0,n)) (B : 'M_(m,n)) : col_mx A B = B. Proof. apply/matrixP=> i j; rewrite mxE; case: splitP => [|k H]; first by case. by congr fun_of_matrix; exact: val_inj. Qed. Lemma trmx_lsub m n1 n2 (A : 'M_(m, n1 + n2)) : (lsubmx A)^T = usubmx A^T. Proof. by split_mxE. Qed. Lemma trmx_rsub m n1 n2 (A : 'M_(m, n1 + n2)) : (rsubmx A)^T = dsubmx A^T. Proof. by split_mxE. Qed. Lemma tr_row_mx m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : (row_mx A1 A2)^T = col_mx A1^T A2^T. Proof. by split_mxE. Qed. Lemma tr_col_mx m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : (col_mx A1 A2)^T = row_mx A1^T A2^T. Proof. by split_mxE. Qed. Lemma trmx_usub m1 m2 n (A : 'M_(m1 + m2, n)) : (usubmx A)^T = lsubmx A^T. Proof. by split_mxE. Qed. Lemma trmx_dsub m1 m2 n (A : 'M_(m1 + m2, n)) : (dsubmx A)^T = rsubmx A^T. Proof. by split_mxE. Qed. Lemma vsubmxK m1 m2 n (A : 'M_(m1 + m2, n)) : col_mx (usubmx A) (dsubmx A) = A. Proof. by apply: trmx_inj; rewrite tr_col_mx trmx_usub trmx_dsub hsubmxK. Qed. Lemma cast_row_mx m m' n1 n2 (eq_m : m = m') A1 A2 : castmx (eq_m, erefl _) (row_mx A1 A2) = row_mx (castmx (eq_m, erefl n1) A1) (castmx (eq_m, erefl n2) A2). Proof. by case: m' / eq_m. Qed. Lemma cast_col_mx m1 m2 n n' (eq_n : n = n') A1 A2 : castmx (erefl _, eq_n) (col_mx A1 A2) = col_mx (castmx (erefl m1, eq_n) A1) (castmx (erefl m2, eq_n) A2). Proof. by case: n' / eq_n. Qed. (* This lemma has Prenex Implicits to help RL rewriting with castmx_sym. *) Lemma row_mxA m n1 n2 n3 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) (A3 : 'M_(m, n3)) : let cast := (erefl m, esym (addnA n1 n2 n3)) in row_mx A1 (row_mx A2 A3) = castmx cast (row_mx (row_mx A1 A2) A3). Proof. apply: (canRL (castmxKV _ _)); apply/matrixP=> i j. rewrite castmxE !mxE cast_ord_id; case: splitP => j1 /= def_j. have: (j < n1 + n2) && (j < n1) by rewrite def_j lshift_subproof /=. by move: def_j; do 2![case: splitP => // ? ->; rewrite ?mxE] => /ord_inj->. case: splitP def_j => j2 ->{j} def_j /[!mxE]. have: ~~ (j2 < n1) by rewrite -leqNgt def_j leq_addr. have: j1 < n2 by rewrite -(ltn_add2l n1) -def_j. by move: def_j; do 2![case: splitP => // ? ->] => /addnI/val_inj->. have: ~~ (j1 < n2) by rewrite -leqNgt -(leq_add2l n1) -def_j leq_addr. by case: splitP def_j => // ? ->; rewrite addnA => /addnI/val_inj->. Qed. Definition row_mxAx := row_mxA. (* bypass Prenex Implicits. *) (* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *) Lemma col_mxA m1 m2 m3 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) (A3 : 'M_(m3, n)) : let cast := (esym (addnA m1 m2 m3), erefl n) in col_mx A1 (col_mx A2 A3) = castmx cast (col_mx (col_mx A1 A2) A3). Proof. by apply: trmx_inj; rewrite trmx_cast !tr_col_mx -row_mxA. Qed. Definition col_mxAx := col_mxA. (* bypass Prenex Implicits. *) Lemma row_row_mx m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : row i0 (row_mx A1 A2) = row_mx (row i0 A1) (row i0 A2). Proof. by apply/matrixP=> i j /[!mxE]; case: (split j) => j' /[1!mxE]. Qed. Lemma col_col_mx m1 m2 n j0 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : col j0 (col_mx A1 A2) = col_mx (col j0 A1) (col j0 A2). Proof. by apply: trmx_inj; rewrite !(tr_col, tr_col_mx, row_row_mx). Qed. Lemma row'_row_mx m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : row' i0 (row_mx A1 A2) = row_mx (row' i0 A1) (row' i0 A2). Proof. by apply/matrixP=> i j /[!mxE]; case: (split j) => j' /[1!mxE]. Qed. Lemma col'_col_mx m1 m2 n j0 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : col' j0 (col_mx A1 A2) = col_mx (col' j0 A1) (col' j0 A2). Proof. by apply: trmx_inj; rewrite !(tr_col', tr_col_mx, row'_row_mx). Qed. Lemma colKl m n1 n2 j1 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : col (lshift n2 j1) (row_mx A1 A2) = col j1 A1. Proof. by apply/matrixP=> i j; rewrite !(row_mxEl, mxE). Qed. Lemma colKr m n1 n2 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : col (rshift n1 j2) (row_mx A1 A2) = col j2 A2. Proof. by apply/matrixP=> i j; rewrite !(row_mxEr, mxE). Qed. Lemma rowKu m1 m2 n i1 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : row (lshift m2 i1) (col_mx A1 A2) = row i1 A1. Proof. by apply/matrixP=> i j; rewrite !(col_mxEu, mxE). Qed. Lemma rowKd m1 m2 n i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : row (rshift m1 i2) (col_mx A1 A2) = row i2 A2. Proof. by apply/matrixP=> i j; rewrite !(col_mxEd, mxE). Qed. Lemma col'Kl m n1 n2 j1 (A1 : 'M_(m, n1.+1)) (A2 : 'M_(m, n2)) : col' (lshift n2 j1) (row_mx A1 A2) = row_mx (col' j1 A1) A2. Proof. apply/matrixP=> i /= j; symmetry; rewrite 2!mxE; case: split_ordP => j' ->. by rewrite mxE -(row_mxEl _ A2); congr (row_mx _ _ _); apply: ord_inj. rewrite -(row_mxEr A1); congr (row_mx _ _ _); apply: ord_inj => /=. by rewrite /bump -ltnS -addSn ltn_addr. Qed. Lemma row'Ku m1 m2 n i1 (A1 : 'M_(m1.+1, n)) (A2 : 'M_(m2, n)) : row' (lshift m2 i1) (@col_mx m1.+1 m2 n A1 A2) = col_mx (row' i1 A1) A2. Proof. by apply: trmx_inj; rewrite tr_col_mx !(@tr_row' _.+1) (@tr_col_mx _.+1) col'Kl. Qed. Lemma mx'_cast m n : 'I_n -> (m + n.-1)%N = (m + n).-1. Proof. by case=> j /ltn_predK <-; rewrite addnS. Qed. Lemma col'Kr m n1 n2 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : col' (rshift n1 j2) (@row_mx m n1 n2 A1 A2) = castmx (erefl m, mx'_cast n1 j2) (row_mx A1 (col' j2 A2)). Proof. apply/matrixP=> i j; symmetry; rewrite castmxE mxE cast_ord_id. case: splitP => j' /= def_j. rewrite mxE -(row_mxEl _ A2); congr (row_mx _ _ _); apply: ord_inj. by rewrite /= def_j /bump leqNgt ltn_addr. rewrite 2!mxE -(row_mxEr A1); congr (row_mx _ _ _ _); apply: ord_inj. by rewrite /= def_j /bump leq_add2l addnCA. Qed. Lemma row'Kd m1 m2 n i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : row' (rshift m1 i2) (col_mx A1 A2) = castmx (mx'_cast m1 i2, erefl n) (col_mx A1 (row' i2 A2)). Proof. by apply: trmx_inj; rewrite trmx_cast !(tr_row', tr_col_mx) col'Kr. Qed. Section Block. Variables m1 m2 n1 n2 : nat. (* Building a block matrix from 4 matrices : *) (* up left, up right, down left and down right components *) Definition block_mx Aul Aur Adl Adr : 'M_(m1 + m2, n1 + n2) := col_mx (row_mx Aul Aur) (row_mx Adl Adr). Lemma eq_block_mx Aul Aur Adl Adr Bul Bur Bdl Bdr : block_mx Aul Aur Adl Adr = block_mx Bul Bur Bdl Bdr -> [/\ Aul = Bul, Aur = Bur, Adl = Bdl & Adr = Bdr]. Proof. by case/eq_col_mx; do 2!case/eq_row_mx=> -> ->. Qed. Lemma block_mx_const a : block_mx (const_mx a) (const_mx a) (const_mx a) (const_mx a) = const_mx a. Proof. by split_mxE. Qed. Section CutBlock. Variable A : matrix R (m1 + m2) (n1 + n2). Definition ulsubmx := lsubmx (usubmx A). Definition ursubmx := rsubmx (usubmx A). Definition dlsubmx := lsubmx (dsubmx A). Definition drsubmx := rsubmx (dsubmx A). Lemma submxK : block_mx ulsubmx ursubmx dlsubmx drsubmx = A. Proof. by rewrite /block_mx !hsubmxK vsubmxK. Qed. Lemma ulsubmxEsub : ulsubmx = mxsub (lshift _) (lshift _) A. Proof. by rewrite /ulsubmx lsubmxEsub usubmxEsub -mxsub_comp. Qed. Lemma dlsubmxEsub : dlsubmx = mxsub (@rshift _ _) (lshift _) A. Proof. by rewrite /dlsubmx lsubmxEsub dsubmxEsub -mxsub_comp. Qed. Lemma ursubmxEsub : ursubmx = mxsub (lshift _) (@rshift _ _) A. Proof. by rewrite /ursubmx rsubmxEsub usubmxEsub -mxsub_comp. Qed. Lemma drsubmxEsub : drsubmx = mxsub (@rshift _ _) (@rshift _ _) A. Proof. by rewrite /drsubmx rsubmxEsub dsubmxEsub -mxsub_comp. Qed. End CutBlock. Section CatBlock. Variables (Aul : 'M[R]_(m1, n1)) (Aur : 'M[R]_(m1, n2)). Variables (Adl : 'M[R]_(m2, n1)) (Adr : 'M[R]_(m2, n2)). Let A := block_mx Aul Aur Adl Adr. Lemma block_mxEul i j : A (lshift m2 i) (lshift n2 j) = Aul i j. Proof. by rewrite col_mxEu row_mxEl. Qed. Lemma block_mxKul : ulsubmx A = Aul. Proof. by rewrite /ulsubmx col_mxKu row_mxKl. Qed. Lemma block_mxEur i j : A (lshift m2 i) (rshift n1 j) = Aur i j. Proof. by rewrite col_mxEu row_mxEr. Qed. Lemma block_mxKur : ursubmx A = Aur. Proof. by rewrite /ursubmx col_mxKu row_mxKr. Qed. Lemma block_mxEdl i j : A (rshift m1 i) (lshift n2 j) = Adl i j. Proof. by rewrite col_mxEd row_mxEl. Qed. Lemma block_mxKdl : dlsubmx A = Adl. Proof. by rewrite /dlsubmx col_mxKd row_mxKl. Qed. Lemma block_mxEdr i j : A (rshift m1 i) (rshift n1 j) = Adr i j. Proof. by rewrite col_mxEd row_mxEr. Qed. Lemma block_mxKdr : drsubmx A = Adr. Proof. by rewrite /drsubmx col_mxKd row_mxKr. Qed. Lemma block_mxEv : A = col_mx (row_mx Aul Aur) (row_mx Adl Adr). Proof. by []. Qed. End CatBlock. End Block. Section TrCutBlock. Variables m1 m2 n1 n2 : nat. Variable A : 'M[R]_(m1 + m2, n1 + n2). Lemma trmx_ulsub : (ulsubmx A)^T = ulsubmx A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma trmx_ursub : (ursubmx A)^T = dlsubmx A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma trmx_dlsub : (dlsubmx A)^T = ursubmx A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma trmx_drsub : (drsubmx A)^T = drsubmx A^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. End TrCutBlock. Section TrBlock. Variables m1 m2 n1 n2 : nat. Variables (Aul : 'M[R]_(m1, n1)) (Aur : 'M[R]_(m1, n2)). Variables (Adl : 'M[R]_(m2, n1)) (Adr : 'M[R]_(m2, n2)). Lemma tr_block_mx : (block_mx Aul Aur Adl Adr)^T = block_mx Aul^T Adl^T Aur^T Adr^T. Proof. rewrite -[_^T]submxK -trmx_ulsub -trmx_ursub -trmx_dlsub -trmx_drsub. by rewrite block_mxKul block_mxKur block_mxKdl block_mxKdr. Qed. Lemma block_mxEh : block_mx Aul Aur Adl Adr = row_mx (col_mx Aul Adl) (col_mx Aur Adr). Proof. by apply: trmx_inj; rewrite tr_block_mx tr_row_mx 2!tr_col_mx. Qed. End TrBlock. (* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *) Lemma block_mxA m1 m2 m3 n1 n2 n3 (A11 : 'M_(m1, n1)) (A12 : 'M_(m1, n2)) (A13 : 'M_(m1, n3)) (A21 : 'M_(m2, n1)) (A22 : 'M_(m2, n2)) (A23 : 'M_(m2, n3)) (A31 : 'M_(m3, n1)) (A32 : 'M_(m3, n2)) (A33 : 'M_(m3, n3)) : let cast := (esym (addnA m1 m2 m3), esym (addnA n1 n2 n3)) in let row1 := row_mx A12 A13 in let col1 := col_mx A21 A31 in let row3 := row_mx A31 A32 in let col3 := col_mx A13 A23 in block_mx A11 row1 col1 (block_mx A22 A23 A32 A33) = castmx cast (block_mx (block_mx A11 A12 A21 A22) col3 row3 A33). Proof. rewrite /= block_mxEh !col_mxA -cast_row_mx -block_mxEv -block_mxEh. rewrite block_mxEv block_mxEh !row_mxA -cast_col_mx -block_mxEh -block_mxEv. by rewrite castmx_comp etrans_id. Qed. Definition block_mxAx := block_mxA. (* Bypass Prenex Implicits *) Section Induction. Lemma row_ind m (P : forall n, 'M[R]_(m, n) -> Type) : (forall A, P 0 A) -> (forall n c A, P n A -> P (1 + n)%N (row_mx c A)) -> forall n A, P n A. Proof. move=> P0 PS; elim=> [//|n IHn] A. by rewrite -[n.+1]/(1 + n)%N in A *; rewrite -[A]hsubmxK; apply: PS. Qed. Lemma col_ind n (P : forall m, 'M[R]_(m, n) -> Type) : (forall A, P 0 A) -> (forall m r A, P m A -> P (1 + m)%N (col_mx r A)) -> forall m A, P m A. Proof. move=> P0 PS; elim=> [//|m IHm] A. by rewrite -[m.+1]/(1 + m)%N in A *; rewrite -[A]vsubmxK; apply: PS. Qed. Lemma mx_ind (P : forall m n, 'M[R]_(m, n) -> Type) : (forall m A, P m 0 A) -> (forall n A, P 0 n A) -> (forall m n x r c A, P m n A -> P (1 + m)%N (1 + n)%N (block_mx x r c A)) -> forall m n A, P m n A. Proof. move=> P0l P0r PS; elim=> [|m IHm] [|n] A; do ?by [apply: P0l|apply: P0r]. by rewrite -[A](@submxK 1 _ 1); apply: PS. Qed. Definition matrix_rect := mx_ind. Definition matrix_rec := mx_ind. Definition matrix_ind := mx_ind. Lemma sqmx_ind (P : forall n, 'M[R]_n -> Type) : (forall A, P 0 A) -> (forall n x r c A, P n A -> P (1 + n)%N (block_mx x r c A)) -> forall n A, P n A. Proof. by move=> P0 PS; elim=> [//|n IHn] A; rewrite -[A](@submxK 1 _ 1); apply: PS. Qed. Lemma ringmx_ind (P : forall n, 'M[R]_n.+1 -> Type) : (forall x, P 0 x) -> (forall n x (r : 'rV_n.+1) (c : 'cV_n.+1) A, P n A -> P (1 + n)%N (block_mx x r c A)) -> forall n A, P n A. Proof. by move=> P0 PS; elim=> [//|n IHn] A; rewrite -[A](@submxK 1 _ 1); apply: PS. Qed. Lemma mxsub_ind (weight : forall m n, 'M[R]_(m, n) -> nat) (sub : forall m n m' n', ('I_m' -> 'I_m) -> ('I_n' -> 'I_n) -> Prop) (P : forall m n, 'M[R]_(m, n) -> Type) : (forall m n (A : 'M[R]_(m, n)), (forall m' n' f g, weight m' n' (mxsub f g A) < weight m n A -> sub m n m' n' f g -> P m' n' (mxsub f g A)) -> P m n A) -> forall m n A, P m n A. Proof. move=> Psub m n A; have [k] := ubnP (weight m n A). elim: k => [//|k IHk] in m n A *. rewrite ltnS => lt_A_k; apply: Psub => m' n' f g lt_A'_A ?. by apply: IHk; apply: leq_trans lt_A_k. Qed. End Induction. (* Bijections mxvec : 'M_(m, n) <----> 'rV_(m * n) : vec_mx *) Section VecMatrix. Variables m n : nat. Lemma mxvec_cast : #|{:'I_m * 'I_n}| = (m * n)%N. Proof. by rewrite card_prod !card_ord. Qed. Definition mxvec_index (i : 'I_m) (j : 'I_n) := cast_ord mxvec_cast (enum_rank (i, j)). Variant is_mxvec_index : 'I_(m * n) -> Type := isMxvecIndex i j : is_mxvec_index (mxvec_index i j). Lemma mxvec_indexP k : is_mxvec_index k. Proof. rewrite -[k](cast_ordK (esym mxvec_cast)) esymK. by rewrite -[_ k]enum_valK; case: (enum_val _). Qed. Coercion pair_of_mxvec_index k (i_k : is_mxvec_index k) := let: isMxvecIndex i j := i_k in (i, j). Definition mxvec (A : 'M[R]_(m, n)) := castmx (erefl _, mxvec_cast) (\row_k A (enum_val k).1 (enum_val k).2). Fact vec_mx_key : unit. Proof. by []. Qed. Definition vec_mx (u : 'rV[R]_(m * n)) := \matrix[vec_mx_key]_(i, j) u 0 (mxvec_index i j). Lemma mxvecE A i j : mxvec A 0 (mxvec_index i j) = A i j. Proof. by rewrite castmxE mxE cast_ordK enum_rankK. Qed. Lemma mxvecK : cancel mxvec vec_mx. Proof. by move=> A; apply/matrixP=> i j; rewrite mxE mxvecE. Qed. Lemma vec_mxK : cancel vec_mx mxvec. Proof. by move=> u; apply/rowP=> k; case/mxvec_indexP: k => i j; rewrite mxvecE mxE. Qed. Lemma curry_mxvec_bij : {on 'I_(m * n), bijective (uncurry mxvec_index)}. Proof. exists (enum_val \o cast_ord (esym mxvec_cast)) => [[i j] _ | k _] /=. by rewrite cast_ordK enum_rankK. by case/mxvec_indexP: k => i j /=; rewrite cast_ordK enum_rankK. Qed. End VecMatrix. End MatrixStructural. Arguments const_mx {R m n}. Arguments row_mxA {R m n1 n2 n3 A1 A2 A3}. Arguments col_mxA {R m1 m2 m3 n A1 A2 A3}. Arguments block_mxA {R m1 m2 m3 n1 n2 n3 A11 A12 A13 A21 A22 A23 A31 A32 A33}. Prenex Implicits castmx trmx trmxK lsubmx rsubmx usubmx dsubmx row_mx col_mx. Prenex Implicits block_mx ulsubmx ursubmx dlsubmx drsubmx. Prenex Implicits mxvec vec_mx mxvec_indexP mxvecK vec_mxK. Arguments trmx_inj {R m n} [A1 A2] eqA12t : rename. Notation "A ^T" := (trmx A) : ring_scope. Notation colsub g := (mxsub id g). Notation rowsub f := (mxsub f id). Arguments eq_mxsub [R m n m' n' f] f' [g] g' _. Arguments eq_rowsub [R m n m' f] f' _. Arguments eq_colsub [R m n n' g] g' _. (* Matrix parametricity. *) Section MapMatrix. Variables (aT rT : Type) (f : aT -> rT). Fact map_mx_key : unit. Proof. by []. Qed. Definition map_mx m n (A : 'M_(m, n)) := \matrix[map_mx_key]_(i, j) f (A i j). Notation "A ^f" := (map_mx A) : ring_scope. Section OneMatrix. Variables (m n : nat) (A : 'M[aT]_(m, n)). Lemma map_trmx : A^f^T = A^T^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_const_mx a : (const_mx a)^f = const_mx (f a) :> 'M_(m, n). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_row i : (row i A)^f = row i A^f. Proof. by apply/rowP=> j; rewrite !mxE. Qed. Lemma map_col j : (col j A)^f = col j A^f. Proof. by apply/colP=> i; rewrite !mxE. Qed. Lemma map_row' i0 : (row' i0 A)^f = row' i0 A^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_col' j0 : (col' j0 A)^f = col' j0 A^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_mxsub m' n' g h : (@mxsub _ _ _ m' n' g h A)^f = mxsub g h A^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_row_perm s : (row_perm s A)^f = row_perm s A^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_col_perm s : (col_perm s A)^f = col_perm s A^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_xrow i1 i2 : (xrow i1 i2 A)^f = xrow i1 i2 A^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_xcol j1 j2 : (xcol j1 j2 A)^f = xcol j1 j2 A^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_castmx m' n' c : (castmx c A)^f = castmx c A^f :> 'M_(m', n'). Proof. by apply/matrixP=> i j; rewrite !(castmxE, mxE). Qed. Lemma map_conform_mx m' n' (B : 'M_(m', n')) : (conform_mx B A)^f = conform_mx B^f A^f. Proof. move: B; have [[<- <-] B|] := eqVneq (m, n) (m', n'). by rewrite !conform_mx_id. by rewrite negb_and => neq_mn B; rewrite !nonconform_mx. Qed. Lemma map_mxvec : (mxvec A)^f = mxvec A^f. Proof. by apply/rowP=> i; rewrite !(castmxE, mxE). Qed. Lemma map_vec_mx (v : 'rV_(m * n)) : (vec_mx v)^f = vec_mx v^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. End OneMatrix. Section Block. Variables m1 m2 n1 n2 : nat. Variables (Aul : 'M[aT]_(m1, n1)) (Aur : 'M[aT]_(m1, n2)). Variables (Adl : 'M[aT]_(m2, n1)) (Adr : 'M[aT]_(m2, n2)). Variables (Bh : 'M[aT]_(m1, n1 + n2)) (Bv : 'M[aT]_(m1 + m2, n1)). Variable B : 'M[aT]_(m1 + m2, n1 + n2). Lemma map_row_mx : (row_mx Aul Aur)^f = row_mx Aul^f Aur^f. Proof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed. Lemma map_col_mx : (col_mx Aul Adl)^f = col_mx Aul^f Adl^f. Proof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed. Lemma map_block_mx : (block_mx Aul Aur Adl Adr)^f = block_mx Aul^f Aur^f Adl^f Adr^f. Proof. by apply/matrixP=> i j; do 3![rewrite !mxE //; case: split => ?]. Qed. Lemma map_lsubmx : (lsubmx Bh)^f = lsubmx Bh^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_rsubmx : (rsubmx Bh)^f = rsubmx Bh^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_usubmx : (usubmx Bv)^f = usubmx Bv^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_dsubmx : (dsubmx Bv)^f = dsubmx Bv^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_ulsubmx : (ulsubmx B)^f = ulsubmx B^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_ursubmx : (ursubmx B)^f = ursubmx B^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_dlsubmx : (dlsubmx B)^f = dlsubmx B^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map_drsubmx : (drsubmx B)^f = drsubmx B^f. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. End Block. End MapMatrix. Arguments map_mx {aT rT} f {m n} A. Section MultipleMapMatrix. Context {R S T : Type} {m n : nat}. Local Notation "M ^ phi" := (map_mx phi M). Lemma map_mx_comp (f : R -> S) (g : S -> T) (M : 'M_(m, n)) : M ^ (g \o f) = (M ^ f) ^ g. Proof. by apply/matrixP => i j; rewrite !mxE. Qed. Lemma eq_in_map_mx (g f : R -> S) (M : 'M_(m, n)) : (forall i j, f (M i j) = g (M i j)) -> M ^ f = M ^ g. Proof. by move=> fg; apply/matrixP => i j; rewrite !mxE. Qed. Lemma eq_map_mx (g f : R -> S) : f =1 g -> forall (M : 'M_(m, n)), M ^ f = M ^ g. Proof. by move=> eq_fg M; apply/eq_in_map_mx. Qed. Lemma map_mx_id_in (f : R -> R) (M : 'M_(m, n)) : (forall i j, f (M i j) = M i j) -> M ^ f = M. Proof. by move=> fM; apply/matrixP => i j; rewrite !mxE. Qed. Lemma map_mx_id (f : R -> R) : f =1 id -> forall M : 'M_(m, n), M ^ f = M. Proof. by move=> fid M; rewrite map_mx_id_in. Qed. End MultipleMapMatrix. Arguments eq_map_mx {R S m n} g [f]. Arguments eq_in_map_mx {R S m n} g [f M]. Arguments map_mx_id_in {R m n} [f M]. Arguments map_mx_id {R m n} [f]. (*****************************************************************************) (********************* Matrix lifted laws *******************) (*****************************************************************************) Section Map2Matrix. Context {R S T : Type} (f : R -> S -> T). Fact map2_mx_key : unit. Proof. by []. Qed. Definition map2_mx m n (A : 'M_(m, n)) (B : 'M_(m, n)) := \matrix[map2_mx_key]_(i, j) f (A i j) (B i j). Section OneMatrix. Variables (m n : nat) (A : 'M[R]_(m, n)) (B : 'M[S]_(m, n)). Lemma map2_trmx : (map2_mx A B)^T = map2_mx A^T B^T. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_const_mx a b : map2_mx (const_mx a) (const_mx b) = const_mx (f a b) :> 'M_(m, n). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_row i : map2_mx (row i A) (row i B) = row i (map2_mx A B). Proof. by apply/rowP=> j; rewrite !mxE. Qed. Lemma map2_col j : map2_mx (col j A) (col j B) = col j (map2_mx A B). Proof. by apply/colP=> i; rewrite !mxE. Qed. Lemma map2_row' i0 : map2_mx (row' i0 A) (row' i0 B) = row' i0 (map2_mx A B). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_col' j0 : map2_mx (col' j0 A) (col' j0 B) = col' j0 (map2_mx A B). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_mxsub m' n' g h : map2_mx (@mxsub _ _ _ m' n' g h A) (@mxsub _ _ _ m' n' g h B) = mxsub g h (map2_mx A B). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_row_perm s : map2_mx (row_perm s A) (row_perm s B) = row_perm s (map2_mx A B). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_col_perm s : map2_mx (col_perm s A) (col_perm s B) = col_perm s (map2_mx A B). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_xrow i1 i2 : map2_mx (xrow i1 i2 A) (xrow i1 i2 B) = xrow i1 i2 (map2_mx A B). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_xcol j1 j2 : map2_mx (xcol j1 j2 A) (xcol j1 j2 B) = xcol j1 j2 (map2_mx A B). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_castmx m' n' c : map2_mx (castmx c A) (castmx c B) = castmx c (map2_mx A B) :> 'M_(m', n'). Proof. by apply/matrixP=> i j; rewrite !(castmxE, mxE). Qed. Lemma map2_conform_mx m' n' (A' : 'M_(m', n')) (B' : 'M_(m', n')) : map2_mx (conform_mx A' A) (conform_mx B' B) = conform_mx (map2_mx A' B') (map2_mx A B). Proof. move: A' B'; have [[<- <-] A' B'|] := eqVneq (m, n) (m', n'). by rewrite !conform_mx_id. by rewrite negb_and => neq_mn A' B'; rewrite !nonconform_mx. Qed. Lemma map2_mxvec : map2_mx (mxvec A) (mxvec B) = mxvec (map2_mx A B). Proof. by apply/rowP=> i; rewrite !(castmxE, mxE). Qed. Lemma map2_vec_mx (v : 'rV_(m * n)) (w : 'rV_(m * n)) : map2_mx (vec_mx v) (vec_mx w) = vec_mx (map2_mx v w). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. End OneMatrix. Section Block. Variables m1 m2 n1 n2 : nat. Variables (Aul : 'M[R]_(m1, n1)) (Aur : 'M[R]_(m1, n2)). Variables (Adl : 'M[R]_(m2, n1)) (Adr : 'M[R]_(m2, n2)). Variables (Bh : 'M[R]_(m1, n1 + n2)) (Bv : 'M[R]_(m1 + m2, n1)). Variable B : 'M[R]_(m1 + m2, n1 + n2). Variables (A'ul : 'M[S]_(m1, n1)) (A'ur : 'M[S]_(m1, n2)). Variables (A'dl : 'M[S]_(m2, n1)) (A'dr : 'M[S]_(m2, n2)). Variables (B'h : 'M[S]_(m1, n1 + n2)) (B'v : 'M[S]_(m1 + m2, n1)). Variable B' : 'M[S]_(m1 + m2, n1 + n2). Lemma map2_row_mx : map2_mx (row_mx Aul Aur) (row_mx A'ul A'ur) = row_mx (map2_mx Aul A'ul) (map2_mx Aur A'ur). Proof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed. Lemma map2_col_mx : map2_mx (col_mx Aul Adl) (col_mx A'ul A'dl) = col_mx (map2_mx Aul A'ul) (map2_mx Adl A'dl). Proof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed. Lemma map2_block_mx : map2_mx (block_mx Aul Aur Adl Adr) (block_mx A'ul A'ur A'dl A'dr) = block_mx (map2_mx Aul A'ul) (map2_mx Aur A'ur) (map2_mx Adl A'dl) (map2_mx Adr A'dr). Proof. by apply/matrixP=> i j; do 3![rewrite !mxE //; case: split => ?]. Qed. Lemma map2_lsubmx : map2_mx (lsubmx Bh) (lsubmx B'h) = lsubmx (map2_mx Bh B'h). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_rsubmx : map2_mx (rsubmx Bh) (rsubmx B'h) = rsubmx (map2_mx Bh B'h). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_usubmx : map2_mx (usubmx Bv) (usubmx B'v) = usubmx (map2_mx Bv B'v). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_dsubmx : map2_mx (dsubmx Bv) (dsubmx B'v) = dsubmx (map2_mx Bv B'v). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_ulsubmx : map2_mx (ulsubmx B) (ulsubmx B') = ulsubmx (map2_mx B B'). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_ursubmx : map2_mx (ursubmx B) (ursubmx B') = ursubmx (map2_mx B B'). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_dlsubmx : map2_mx (dlsubmx B) (dlsubmx B') = dlsubmx (map2_mx B B'). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma map2_drsubmx : map2_mx (drsubmx B) (drsubmx B') = drsubmx (map2_mx B B'). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. End Block. End Map2Matrix. Section Map2Eq. Context {R S T : Type} {m n : nat}. Lemma eq_in_map2_mx (f g : R -> S -> T) (M : 'M[R]_(m, n)) (M' : 'M[S]_(m, n)) : (forall i j, f (M i j) (M' i j) = g (M i j) (M' i j)) -> map2_mx f M M' = map2_mx g M M'. Proof. by move=> fg; apply/matrixP => i j; rewrite !mxE. Qed. Lemma eq_map2_mx (f g : R -> S -> T) : f =2 g -> @map2_mx _ _ _ f m n =2 @map2_mx _ _ _ g m n. Proof. by move=> eq_fg M M'; apply/eq_in_map2_mx. Qed. Lemma map2_mx_left_in (f : R -> R -> R) (M : 'M_(m, n)) (M' : 'M_(m, n)) : (forall i j, f (M i j) (M' i j) = M i j) -> map2_mx f M M' = M. Proof. by move=> fM; apply/matrixP => i j; rewrite !mxE. Qed. Lemma map2_mx_left (f : R -> R -> R) : f =2 (fun x _ => x) -> forall (M : 'M_(m, n)) (M' : 'M_(m, n)), map2_mx f M M' = M. Proof. by move=> fl M M'; rewrite map2_mx_left_in// =>i j; rewrite fl. Qed. Lemma map2_mx_right_in (f : R -> R -> R) (M : 'M_(m, n)) (M' : 'M_(m, n)) : (forall i j, f (M i j) (M' i j) = M' i j) -> map2_mx f M M' = M'. Proof. by move=> fM; apply/matrixP => i j; rewrite !mxE. Qed. Lemma map2_mx_right (f : R -> R -> R) : f =2 (fun _ x => x) -> forall (M : 'M_(m, n)) (M' : 'M_(m, n)), map2_mx f M M' = M'. Proof. by move=> fr M M'; rewrite map2_mx_right_in// =>i j; rewrite fr. Qed. End Map2Eq. Section MatrixLaws. Context {T : Type} {m n : nat} {idm : T}. Lemma map2_mxA {opm : Monoid.law idm} : associative (@map2_mx _ _ _ opm m n). Proof. by move=> A B C; apply/matrixP=> i j; rewrite !mxE Monoid.mulmA. Qed. Lemma map2_1mx {opm : Monoid.law idm} : left_id (const_mx idm) (@map2_mx _ _ _ opm m n). Proof. by move=> A; apply/matrixP=> i j; rewrite !mxE Monoid.mul1m. Qed. Lemma map2_mx1 {opm : Monoid.law idm} : right_id (const_mx idm) (@map2_mx _ _ _ opm m n). Proof. by move=> A; apply/matrixP=> i j; rewrite !mxE Monoid.mulm1. Qed. HB.instance Definition _ {opm : Monoid.law idm} := Monoid.isLaw.Build 'M_(m, n) (const_mx idm) (@map2_mx _ _ _ opm _ _) map2_mxA map2_1mx map2_mx1. Lemma map2_mxC {opm : Monoid.com_law idm} : commutative (@map2_mx _ _ _ opm m n). Proof. by move=> A B; apply/matrixP=> i j; rewrite !mxE Monoid.mulmC. Qed. HB.instance Definition _ {opm : Monoid.com_law idm} := SemiGroup.isCommutativeLaw.Build 'M_(m, n) (@map2_mx _ _ _ opm _ _) map2_mxC. Lemma map2_0mx {opm : Monoid.mul_law idm} : left_zero (const_mx idm) (@map2_mx _ _ _ opm m n). Proof. by move=> A; apply/matrixP=> i j; rewrite !mxE Monoid.mul0m. Qed. Lemma map2_mx0 {opm : Monoid.mul_law idm} : right_zero (const_mx idm) (@map2_mx _ _ _ opm m n). Proof. by move=> A; apply/matrixP=> i j; rewrite !mxE Monoid.mulm0. Qed. HB.instance Definition _ {opm : Monoid.mul_law idm} := Monoid.isMulLaw.Build 'M_(m, n) (const_mx idm) (@map2_mx _ _ _ opm _ _) map2_0mx map2_mx0. Lemma map2_mxDl {mul : T -> T -> T} {add : Monoid.add_law idm mul} : left_distributive (@map2_mx _ _ _ mul m n) (@map2_mx _ _ _ add m n). Proof. by move=> A B C; apply/matrixP=> i j; rewrite !mxE Monoid.mulmDl. Qed. Lemma map2_mxDr {mul : T -> T -> T} {add : Monoid.add_law idm mul} : right_distributive (@map2_mx _ _ _ mul m n) (@map2_mx _ _ _ add m n). Proof. by move=> A B C; apply/matrixP=> i j; rewrite !mxE Monoid.mulmDr. Qed. HB.instance Definition _ {mul : T -> T -> T} {add : Monoid.add_law idm mul} := Monoid.isAddLaw.Build 'M_(m, n) (@map2_mx _ _ _ mul _ _) (@map2_mx _ _ _ add _ _) map2_mxDl map2_mxDr. End MatrixLaws. (*****************************************************************************) (************* Matrix Nmodule (additive abelian monoid) structure ************) (*****************************************************************************) Section MatrixNmodule. Variable V : nmodType. Section FixedDim. Variables m n : nat. Implicit Types A B : 'M[V]_(m, n). Fact addmx_key : unit. Proof. by []. Qed. Definition addmx := @map2_mx V V V +%R m n. Definition addmxA : associative addmx := map2_mxA. Definition addmxC : commutative addmx := map2_mxC. Definition add0mx : left_id (const_mx 0) addmx := map2_1mx. HB.instance Definition _ := GRing.isNmodule.Build 'M[V]_(m, n) addmxA addmxC add0mx. Lemma mulmxnE A d i j : (A *+ d) i j = A i j *+ d. Proof. by elim: d => [|d IHd]; rewrite ?mulrS mxE ?IHd. Qed. Lemma summxE I r (P : pred I) (E : I -> 'M_(m, n)) i j : (\sum_(k <- r | P k) E k) i j = \sum_(k <- r | P k) E k i j. Proof. by apply: (big_morph (fun A => A i j)) => [A B|]; rewrite mxE. Qed. Fact const_mx_is_nmod_morphism : nmod_morphism const_mx. Proof. by split=> [|a b]; apply/matrixP => // i j; rewrite !mxE. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `const_mx_is_nmod_morphism` instead")] Definition const_mx_is_semi_additive := const_mx_is_nmod_morphism. HB.instance Definition _ := GRing.isNmodMorphism.Build V 'M[V]_(m, n) const_mx const_mx_is_nmod_morphism. End FixedDim. Section SemiAdditive. Variables (m n p q : nat) (f : 'I_p -> 'I_q -> 'I_m) (g : 'I_p -> 'I_q -> 'I_n). Definition swizzle_mx k (A : 'M[V]_(m, n)) := \matrix[k]_(i, j) A (f i j) (g i j). Fact swizzle_mx_is_nmod_morphism k : nmod_morphism (swizzle_mx k). Proof. by split=> [|A B]; apply/matrixP => i j; rewrite !mxE. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `swizzle_mx_is_nmod_morphism` instead")] Definition swizzle_mx_is_semi_additive := swizzle_mx_is_nmod_morphism. HB.instance Definition _ k := GRing.isNmodMorphism.Build 'M_(m, n) 'M_(p, q) (swizzle_mx k) (swizzle_mx_is_nmod_morphism k). End SemiAdditive. Local Notation SwizzleAdd op := (GRing.Additive.copy op (swizzle_mx _ _ _)). HB.instance Definition _ m n := SwizzleAdd (@trmx V m n). HB.instance Definition _ m n i := SwizzleAdd (@row V m n i). HB.instance Definition _ m n j := SwizzleAdd (@col V m n j). HB.instance Definition _ m n i := SwizzleAdd (@row' V m n i). HB.instance Definition _ m n j := SwizzleAdd (@col' V m n j). HB.instance Definition _ m n m' n' f g := SwizzleAdd (@mxsub V m n m' n' f g). HB.instance Definition _ m n s := SwizzleAdd (@row_perm V m n s). HB.instance Definition _ m n s := SwizzleAdd (@col_perm V m n s). HB.instance Definition _ m n i1 i2 := SwizzleAdd (@xrow V m n i1 i2). HB.instance Definition _ m n j1 j2 := SwizzleAdd (@xcol V m n j1 j2). HB.instance Definition _ m n1 n2 := SwizzleAdd (@lsubmx V m n1 n2). HB.instance Definition _ m n1 n2 := SwizzleAdd (@rsubmx V m n1 n2). HB.instance Definition _ m1 m2 n := SwizzleAdd (@usubmx V m1 m2 n). HB.instance Definition _ m1 m2 n := SwizzleAdd (@dsubmx V m1 m2 n). HB.instance Definition _ m n := SwizzleAdd (@vec_mx V m n). HB.instance Definition _ m n := GRing.isNmodMorphism.Build 'M_(m, n) 'rV_(m * n) mxvec (can2_nmod_morphism (@vec_mxK V m n) mxvecK). Lemma flatmx0 n : all_equal_to (0 : 'M_(0, n)). Proof. by move=> A; apply/matrixP=> [] []. Qed. Lemma thinmx0 n : all_equal_to (0 : 'M_(n, 0)). Proof. by move=> A; apply/matrixP=> i []. Qed. Lemma trmx0 m n : (0 : 'M_(m, n))^T = 0. Proof. exact: trmx_const. Qed. Lemma row0 m n i0 : row i0 (0 : 'M_(m, n)) = 0. Proof. exact: row_const. Qed. Lemma col0 m n j0 : col j0 (0 : 'M_(m, n)) = 0. Proof. exact: col_const. Qed. Lemma mxvec_eq0 m n (A : 'M_(m, n)) : (mxvec A == 0) = (A == 0). Proof. by rewrite (can2_eq mxvecK vec_mxK) raddf0. Qed. Lemma vec_mx_eq0 m n (v : 'rV_(m * n)) : (vec_mx v == 0) = (v == 0). Proof. by rewrite (can2_eq vec_mxK mxvecK) raddf0. Qed. Lemma row_mx0 m n1 n2 : row_mx 0 0 = 0 :> 'M_(m, n1 + n2). Proof. exact: row_mx_const. Qed. Lemma col_mx0 m1 m2 n : col_mx 0 0 = 0 :> 'M_(m1 + m2, n). Proof. exact: col_mx_const. Qed. Lemma block_mx0 m1 m2 n1 n2 : block_mx 0 0 0 0 = 0 :> 'M_(m1 + m2, n1 + n2). Proof. exact: block_mx_const. Qed. Ltac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?]. Lemma add_row_mx m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) B1 B2 : row_mx A1 A2 + row_mx B1 B2 = row_mx (A1 + B1) (A2 + B2). Proof. by split_mxE. Qed. Lemma add_col_mx m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) B1 B2 : col_mx A1 A2 + col_mx B1 B2 = col_mx (A1 + B1) (A2 + B2). Proof. by split_mxE. Qed. Lemma add_block_mx m1 m2 n1 n2 (Aul : 'M_(m1, n1)) Aur Adl (Adr : 'M_(m2, n2)) Bul Bur Bdl Bdr : let A := block_mx Aul Aur Adl Adr in let B := block_mx Bul Bur Bdl Bdr in A + B = block_mx (Aul + Bul) (Aur + Bur) (Adl + Bdl) (Adr + Bdr). Proof. by rewrite /= add_col_mx !add_row_mx. Qed. Lemma row_mx_eq0 (m n1 n2 : nat) (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)): (row_mx A1 A2 == 0) = (A1 == 0) && (A2 == 0). Proof. apply/eqP/andP; last by case=> /eqP-> /eqP->; rewrite row_mx0. by rewrite -row_mx0 => /eq_row_mx [-> ->]. Qed. Lemma col_mx_eq0 (m1 m2 n : nat) (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)): (col_mx A1 A2 == 0) = (A1 == 0) && (A2 == 0). Proof. by rewrite -![_ == 0](inj_eq trmx_inj) !trmx0 tr_col_mx row_mx_eq0. Qed. Lemma block_mx_eq0 m1 m2 n1 n2 (Aul : 'M_(m1, n1)) Aur Adl (Adr : 'M_(m2, n2)) : (block_mx Aul Aur Adl Adr == 0) = [&& Aul == 0, Aur == 0, Adl == 0 & Adr == 0]. Proof. by rewrite col_mx_eq0 !row_mx_eq0 !andbA. Qed. Lemma trmx_eq0 m n (A : 'M_(m, n)) : (A^T == 0) = (A == 0). Proof. by rewrite -trmx0 (inj_eq trmx_inj). Qed. Lemma matrix_eq0 m n (A : 'M_(m, n)) : (A == 0) = [forall i, forall j, A i j == 0]. Proof. apply/eqP/'forall_'forall_eqP => [-> i j|A_eq0]; first by rewrite !mxE. by apply/matrixP => i j; rewrite A_eq0 !mxE. Qed. Lemma matrix0Pn m n (A : 'M_(m, n)) : reflect (exists i j, A i j != 0) (A != 0). Proof. by rewrite matrix_eq0; apply/(iffP forallPn) => -[i /forallPn]; exists i. Qed. Lemma rV0Pn n (v : 'rV_n) : reflect (exists i, v 0 i != 0) (v != 0). Proof. apply: (iffP (matrix0Pn _)) => [[i [j]]|[j]]; last by exists 0, j. by rewrite ord1; exists j. Qed. Lemma cV0Pn n (v : 'cV_n) : reflect (exists i, v i 0 != 0) (v != 0). Proof. apply: (iffP (matrix0Pn _)) => [[i] [j]|[i]]; last by exists i, 0. by rewrite ord1; exists i. Qed. Definition nz_row m n (A : 'M_(m, n)) := oapp (fun i => row i A) 0 [pick i | row i A != 0]. Lemma nz_row_eq0 m n (A : 'M_(m, n)) : (nz_row A == 0) = (A == 0). Proof. rewrite /nz_row; symmetry; case: pickP => [i /= nzAi | Ai0]. by rewrite (negPf nzAi); apply: contraTF nzAi => /eqP->; rewrite row0 eqxx. by rewrite eqxx; apply/eqP/row_matrixP=> i; move/eqP: (Ai0 i) ->; rewrite row0. Qed. Definition is_diag_mx m n (A : 'M[V]_(m, n)) := [forall i : 'I__, forall j : 'I__, (i != j :> nat) ==> (A i j == 0)]. Lemma is_diag_mxP m n (A : 'M[V]_(m, n)) : reflect (forall i j : 'I__, i != j :> nat -> A i j = 0) (is_diag_mx A). Proof. by apply: (iffP 'forall_'forall_implyP) => /(_ _ _ _)/eqP. Qed. Lemma mx0_is_diag m n : is_diag_mx (0 : 'M[V]_(m, n)). Proof. by apply/is_diag_mxP => i j _; rewrite mxE. Qed. Lemma mx11_is_diag (M : 'M_1) : is_diag_mx M. Proof. by apply/is_diag_mxP => i j; rewrite !ord1 eqxx. Qed. Definition is_trig_mx m n (A : 'M[V]_(m, n)) := [forall i : 'I__, forall j : 'I__, (i < j)%N ==> (A i j == 0)]. Lemma is_trig_mxP m n (A : 'M[V]_(m, n)) : reflect (forall i j : 'I__, (i < j)%N -> A i j = 0) (is_trig_mx A). Proof. by apply: (iffP 'forall_'forall_implyP) => /(_ _ _ _)/eqP. Qed. Lemma is_diag_mx_is_trig m n (A : 'M[V]_(m, n)) : is_diag_mx A -> is_trig_mx A. Proof. by move=> /is_diag_mxP A_eq0; apply/is_trig_mxP=> i j lt_ij; rewrite A_eq0// ltn_eqF. Qed. Lemma mx0_is_trig m n : is_trig_mx (0 : 'M[V]_(m, n)). Proof. by apply/is_trig_mxP => i j _; rewrite mxE. Qed. Lemma mx11_is_trig (M : 'M_1) : is_trig_mx M. Proof. by apply/is_trig_mxP => i j; rewrite !ord1 ltnn. Qed. Lemma is_diag_mxEtrig m n (A : 'M[V]_(m, n)) : is_diag_mx A = is_trig_mx A && is_trig_mx A^T. Proof. apply/is_diag_mxP/andP => [Adiag|[/is_trig_mxP Atrig /is_trig_mxP ATtrig]]. by split; apply/is_trig_mxP => i j lt_ij; rewrite ?mxE ?Adiag//; [rewrite ltn_eqF|rewrite gtn_eqF]. by move=> i j; case: ltngtP => // [/Atrig|/ATtrig]; rewrite ?mxE. Qed. Lemma is_diag_trmx m n (A : 'M[V]_(m, n)) : is_diag_mx A^T = is_diag_mx A. Proof. by rewrite !is_diag_mxEtrig trmxK andbC. Qed. Lemma ursubmx_trig m1 m2 n1 n2 (A : 'M[V]_(m1 + m2, n1 + n2)) : m1 <= n1 -> is_trig_mx A -> ursubmx A = 0. Proof. move=> leq_m1_n1 /is_trig_mxP Atrig; apply/matrixP => i j. by rewrite !mxE Atrig//= ltn_addr// (@leq_trans m1). Qed. Lemma dlsubmx_diag m1 m2 n1 n2 (A : 'M[V]_(m1 + m2, n1 + n2)) : n1 <= m1 -> is_diag_mx A -> dlsubmx A = 0. Proof. move=> leq_m2_n2 /is_diag_mxP Adiag; apply/matrixP => i j. by rewrite !mxE Adiag// gtn_eqF//= ltn_addr// (@leq_trans n1). Qed. Lemma ulsubmx_trig m1 m2 n1 n2 (A : 'M[V]_(m1 + m2, n1 + n2)) : is_trig_mx A -> is_trig_mx (ulsubmx A). Proof. move=> /is_trig_mxP Atrig; apply/is_trig_mxP => i j lt_ij. by rewrite !mxE Atrig. Qed. Lemma drsubmx_trig m1 m2 n1 n2 (A : 'M[V]_(m1 + m2, n1 + n2)) : m1 <= n1 -> is_trig_mx A -> is_trig_mx (drsubmx A). Proof. move=> leq_m1_n1 /is_trig_mxP Atrig; apply/is_trig_mxP => i j lt_ij. by rewrite !mxE Atrig//= -addnS leq_add. Qed. Lemma ulsubmx_diag m1 m2 n1 n2 (A : 'M[V]_(m1 + m2, n1 + n2)) : is_diag_mx A -> is_diag_mx (ulsubmx A). Proof. rewrite !is_diag_mxEtrig trmx_ulsub. by move=> /andP[/ulsubmx_trig-> /ulsubmx_trig->]. Qed. Lemma drsubmx_diag m1 m2 n1 n2 (A : 'M[V]_(m1 + m2, n1 + n2)) : m1 = n1 -> is_diag_mx A -> is_diag_mx (drsubmx A). Proof. move=> eq_m1_n1 /is_diag_mxP Adiag; apply/is_diag_mxP => i j neq_ij. by rewrite !mxE Adiag//= eq_m1_n1 eqn_add2l. Qed. Lemma is_trig_block_mx m1 m2 n1 n2 ul ur dl dr : m1 = n1 -> @is_trig_mx (m1 + m2) (n1 + n2) (block_mx ul ur dl dr) = [&& ur == 0, is_trig_mx ul & is_trig_mx dr]. Proof. move=> eq_m1_n1; rewrite {}eq_m1_n1 in ul ur dl dr *. apply/is_trig_mxP/and3P => [Atrig|]; last first. move=> [/eqP-> /is_trig_mxP ul_trig /is_trig_mxP dr_trig] i j; rewrite !mxE. do 2![case: split_ordP => ? ->; rewrite ?mxE//=] => lt_ij; rewrite ?ul_trig//. move: lt_ij; rewrite ltnNge -ltnS. by rewrite (leq_trans (ltn_ord _))// -addnS leq_addr. by rewrite dr_trig//; move: lt_ij; rewrite ltn_add2l. split. - apply/eqP/matrixP => i j; have := Atrig (lshift _ i) (rshift _ j). rewrite !mxE; case: split_ordP => k /eqP; rewrite eq_shift// ?mxE. case: split_ordP => l /eqP; rewrite eq_shift// ?mxE => /eqP-> /eqP<- <- //. by rewrite /= (leq_trans (ltn_ord _)) ?leq_addr. - apply/is_trig_mxP => i j lt_ij; have := Atrig (lshift _ i) (lshift _ j). rewrite !mxE; case: split_ordP => k /eqP; rewrite eq_shift// ?mxE. by case: split_ordP => l /eqP; rewrite eq_shift// ?mxE => /eqP<- /eqP<- ->. - apply/is_trig_mxP => i j lt_ij; have := Atrig (rshift _ i) (rshift _ j). rewrite !mxE; case: split_ordP => k /eqP; rewrite eq_shift// ?mxE. case: split_ordP => l /eqP; rewrite eq_shift// ?mxE => /eqP<- /eqP<- -> //. by rewrite /= ltn_add2l. Qed. Lemma trigmx_ind (P : forall m n, 'M_(m, n) -> Type) : (forall m, P m 0 0) -> (forall n, P 0 n 0) -> (forall m n x c A, is_trig_mx A -> P m n A -> P (1 + m)%N (1 + n)%N (block_mx x 0 c A)) -> forall m n A, is_trig_mx A -> P m n A. Proof. move=> P0l P0r PS m n A; elim: A => {m n} [m|n|m n xx r c] A PA; do ?by rewrite (flatmx0, thinmx0); by [apply: P0l|apply: P0r]. by rewrite is_trig_block_mx => // /and3P[/eqP-> _ Atrig]; apply: PS (PA _). Qed. Lemma trigsqmx_ind (P : forall n, 'M[V]_n -> Type) : (P 0 0) -> (forall n x c A, is_trig_mx A -> P n A -> P (1 + n)%N (block_mx x 0 c A)) -> forall n A, is_trig_mx A -> P n A. Proof. move=> P0 PS n A; elim/sqmx_ind: A => {n} [|n x r c] A PA. by rewrite thinmx0; apply: P0. by rewrite is_trig_block_mx => // /and3P[/eqP-> _ Atrig]; apply: PS (PA _). Qed. Lemma is_diag_block_mx m1 m2 n1 n2 ul ur dl dr : m1 = n1 -> @is_diag_mx (m1 + m2) (n1 + n2) (block_mx ul ur dl dr) = [&& ur == 0, dl == 0, is_diag_mx ul & is_diag_mx dr]. Proof. move=> eq_m1_n1. rewrite !is_diag_mxEtrig tr_block_mx !is_trig_block_mx// trmx_eq0. by rewrite andbACA -!andbA; congr [&& _, _, _ & _]; rewrite andbCA. Qed. Lemma diagmx_ind (P : forall m n, 'M_(m, n) -> Type) : (forall m, P m 0 0) -> (forall n, P 0 n 0) -> (forall m n x c A, is_diag_mx A -> P m n A -> P (1 + m)%N (1 + n)%N (block_mx x 0 c A)) -> forall m n A, is_diag_mx A -> P m n A. Proof. move=> P0l P0r PS m n A Adiag; have Atrig := is_diag_mx_is_trig Adiag. elim/trigmx_ind: Atrig Adiag => // {}m {}n r c {}A _ PA. rewrite is_diag_block_mx => // /and4P[_ /eqP-> _ Adiag]. exact: PS (PA _). Qed. Lemma diagsqmx_ind (P : forall n, 'M[V]_n -> Type) : (P 0 0) -> (forall n x c A, is_diag_mx A -> P n A -> P (1 + n)%N (block_mx x 0 c A)) -> forall n A, is_diag_mx A -> P n A. Proof. move=> P0 PS n A; elim/sqmx_ind: A => [|{}n x r c] A PA. by rewrite thinmx0; apply: P0. rewrite is_diag_block_mx => // /and4P[/eqP-> /eqP-> _ Adiag]. exact: PS (PA _). Qed. (* Diagonal matrices *) Fact diag_mx_key : unit. Proof. by []. Qed. Definition diag_mx n (d : 'rV[V]_n) := \matrix[diag_mx_key]_(i, j) (d 0 i *+ (i == j)). Lemma tr_diag_mx n (d : 'rV_n) : (diag_mx d)^T = diag_mx d. Proof. by apply/matrixP=> i j /[!mxE]; case: eqVneq => // ->. Qed. Fact diag_mx_is_nmod_morphism n : nmod_morphism (@diag_mx n). Proof. by split=> [|A B]; apply/matrixP => i j; rewrite !mxE ?mul0rn// mulrnDl. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `diag_mx_is_nmod_morphism` instead")] Definition diag_mx_is_semi_additive := diag_mx_is_nmod_morphism. HB.instance Definition _ n := GRing.isNmodMorphism.Build 'rV_n 'M_n (@diag_mx n) (@diag_mx_is_nmod_morphism n). Lemma diag_mx_row m n (l : 'rV_n) (r : 'rV_m) : diag_mx (row_mx l r) = block_mx (diag_mx l) 0 0 (diag_mx r). Proof. apply/matrixP => i j. by do ?[rewrite !mxE; case: split_ordP => ? ->]; rewrite mxE eq_shift. Qed. Lemma diag_mxP n (A : 'M[V]_n) : reflect (exists d : 'rV_n, A = diag_mx d) (is_diag_mx A). Proof. apply: (iffP (is_diag_mxP A)) => [Adiag|[d ->] i j neq_ij]; last first. by rewrite !mxE -val_eqE (negPf neq_ij). exists (\row_i A i i); apply/matrixP => i j; rewrite !mxE. by case: (altP (i =P j)) => [->|/Adiag->]. Qed. Lemma diag_mx_is_diag n (r : 'rV[V]_n) : is_diag_mx (diag_mx r). Proof. by apply/diag_mxP; exists r. Qed. Lemma diag_mx_is_trig n (r : 'rV[V]_n) : is_trig_mx (diag_mx r). Proof. exact/is_diag_mx_is_trig/diag_mx_is_diag. Qed. (* Scalar matrix : a diagonal matrix with a constant on the diagonal *) Section ScalarMx. Variable n : nat. Fact scalar_mx_key : unit. Proof. by []. Qed. Definition scalar_mx x : 'M[V]_n := \matrix[scalar_mx_key]_(i , j) (x *+ (i == j)). Notation "x %:M" := (scalar_mx x) : ring_scope. Lemma diag_const_mx a : diag_mx (const_mx a) = a%:M :> 'M_n. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma tr_scalar_mx a : (a%:M)^T = a%:M. Proof. by apply/matrixP=> i j; rewrite !mxE eq_sym. Qed. Fact scalar_mx_is_nmod_morphism : nmod_morphism scalar_mx. Proof. by split=> [|a b]; rewrite -!diag_const_mx ?raddf0// !raddfD. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `scalar_mx_is_nmod_morphism` instead")] Definition scalar_mx_is_semi_additive := scalar_mx_is_nmod_morphism. HB.instance Definition _ := GRing.isNmodMorphism.Build V 'M_n scalar_mx scalar_mx_is_nmod_morphism. Definition is_scalar_mx (A : 'M[V]_n) := if insub 0 is Some i then A == (A i i)%:M else true. Lemma is_scalar_mxP A : reflect (exists a, A = a%:M) (is_scalar_mx A). Proof. rewrite /is_scalar_mx; case: insubP => [i _ _ | ]. by apply: (iffP eqP) => [|[a ->]]; [exists (A i i) | rewrite mxE eqxx]. rewrite -eqn0Ngt => /eqP n0; left; exists 0. by rewrite raddf0; rewrite n0 in A *; rewrite [A]flatmx0. Qed. Lemma scalar_mx_is_scalar a : is_scalar_mx a%:M. Proof. by apply/is_scalar_mxP; exists a. Qed. Lemma mx0_is_scalar : is_scalar_mx 0. Proof. by apply/is_scalar_mxP; exists 0; rewrite raddf0. Qed. Lemma scalar_mx_is_diag a : is_diag_mx a%:M. Proof. by rewrite -diag_const_mx diag_mx_is_diag. Qed. Lemma is_scalar_mx_is_diag A : is_scalar_mx A -> is_diag_mx A. Proof. by move=> /is_scalar_mxP[a ->]; apply: scalar_mx_is_diag. Qed. Lemma scalar_mx_is_trig a : is_trig_mx a%:M. Proof. by rewrite is_diag_mx_is_trig// scalar_mx_is_diag. Qed. Lemma is_scalar_mx_is_trig A : is_scalar_mx A -> is_trig_mx A. Proof. by move=> /is_scalar_mx_is_diag /is_diag_mx_is_trig. Qed. End ScalarMx. Notation "x %:M" := (scalar_mx _ x) : ring_scope. Lemma mx11_scalar (A : 'M_1) : A = (A 0 0)%:M. Proof. by apply/rowP=> j; rewrite ord1 mxE. Qed. Lemma scalar_mx_block n1 n2 a : a%:M = block_mx a%:M 0 0 a%:M :> 'M_(n1 + n2). Proof. apply/matrixP=> i j; rewrite !mxE. by do 2![case: split_ordP => ? ->; rewrite !mxE]; rewrite ?eq_shift. Qed. (* The trace. *) Section Trace. Variable n : nat. (*TODO: undergeneralize to monoid *) Definition mxtrace (A : 'M[V]_n) := \sum_i A i i. Local Notation "'\tr' A" := (mxtrace A) : ring_scope. Lemma mxtrace_tr A : \tr A^T = \tr A. Proof. by apply: eq_bigr=> i _; rewrite mxE. Qed. Fact mxtrace_is_nmod_morphism : nmod_morphism mxtrace. Proof. split=> [|A B]; first by apply: big1 => i; rewrite mxE. by rewrite -big_split /=; apply: eq_bigr => i _; rewrite mxE. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `mxtrace_is_nmod_morphism` instead")] Definition mxtrace_is_semi_additive := mxtrace_is_nmod_morphism. HB.instance Definition _ := GRing.isNmodMorphism.Build 'M_n V mxtrace mxtrace_is_nmod_morphism. Lemma mxtrace0 : \tr 0 = 0. Proof. exact: raddf0. Qed. Lemma mxtraceD A B : \tr (A + B) = \tr A + \tr B. Proof. exact: raddfD. Qed. Lemma mxtrace_diag D : \tr (diag_mx D) = \sum_j D 0 j. Proof. by apply: eq_bigr => j _; rewrite mxE eqxx. Qed. Lemma mxtrace_scalar a : \tr a%:M = a *+ n. Proof. rewrite -diag_const_mx mxtrace_diag; under eq_bigr do rewrite mxE. by rewrite sumr_const card_ord. Qed. End Trace. Local Notation "'\tr' A" := (mxtrace A) : ring_scope. Lemma trace_mx11 (A : 'M_1) : \tr A = A 0 0. Proof. by rewrite [A in LHS]mx11_scalar mxtrace_scalar. Qed. Lemma mxtrace_block n1 n2 (Aul : 'M_n1) Aur Adl (Adr : 'M_n2) : \tr (block_mx Aul Aur Adl Adr) = \tr Aul + \tr Adr. Proof. rewrite /(\tr _) big_split_ord /=. by congr (_ + _); under eq_bigr do rewrite (block_mxEul, block_mxEdr). Qed. End MatrixNmodule. Arguments is_diag_mx {V m n}. Arguments is_diag_mxP {V m n A}. Arguments is_trig_mx {V m n}. Arguments is_trig_mxP {V m n A}. Arguments scalar_mx {V n}. Arguments is_scalar_mxP {V n A}. Notation "\tr A" := (mxtrace A) : ring_scope. (* Parametricity over the semi-additive structure. *) Section MapNmodMatrix. Variables (aR rR : nmodType) (f : {additive aR -> rR}) (m n : nat). Local Notation "A ^f" := (map_mx f A) : ring_scope. Implicit Type A : 'M[aR]_(m, n). Lemma map_mx0 : 0^f = 0 :> 'M_(m, n). Proof. by rewrite map_const_mx raddf0. Qed. Lemma map_mxD A B : (A + B)^f = A^f + B^f. Proof. by apply/matrixP=> i j; rewrite !mxE raddfD. Qed. Definition map_mx_sum := big_morph _ map_mxD map_mx0. HB.instance Definition _ := GRing.isNmodMorphism.Build 'M[aR]_(m, n) 'M[rR]_(m, n) (map_mx f) (map_mx0, map_mxD). End MapNmodMatrix. Section MatrixZmodule. Variable V : zmodType. Section FixedDim. Variables m n : nat. Implicit Types A B : 'M[V]_(m, n). Fact oppmx_key : unit. Proof. by []. Qed. Definition oppmx := @map_mx V V -%R m n. Lemma addNmx : left_inverse (const_mx 0) oppmx (@addmx V m n). Proof. by move=> A; apply/matrixP=> i j; rewrite !mxE addNr. Qed. HB.instance Definition _ := GRing.Nmodule_isZmodule.Build 'M[V]_(m, n) addNmx. #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead")] Fact const_mx_is_zmod_morphism : zmod_morphism const_mx. Proof. exact: raddfB. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead"), warning="-deprecated"] Definition const_mx_is_additive := const_mx_is_zmod_morphism. End FixedDim. Section Additive. Variables (m n p q : nat) (f : 'I_p -> 'I_q -> 'I_m) (g : 'I_p -> 'I_q -> 'I_n). #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead")] Fact swizzle_mx_is_zmod_morphism k : zmod_morphism (swizzle_mx f g k). Proof. exact: raddfB. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead"), warning="-deprecated"] Definition swizzle_mx_is_additive := swizzle_mx_is_zmod_morphism. End Additive. Ltac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?]. Lemma opp_row_mx m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : - row_mx A1 A2 = row_mx (- A1) (- A2). Proof. by split_mxE. Qed. Lemma opp_col_mx m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : - col_mx A1 A2 = col_mx (- A1) (- A2). Proof. by split_mxE. Qed. Lemma opp_block_mx m1 m2 n1 n2 (Aul : 'M_(m1, n1)) Aur Adl (Adr : 'M_(m2, n2)) : - block_mx Aul Aur Adl Adr = block_mx (- Aul) (- Aur) (- Adl) (- Adr). Proof. by rewrite opp_col_mx !opp_row_mx. Qed. (* Diagonal matrices *) #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead")] Fact diag_mx_is_zmod_morphism n : zmod_morphism (@diag_mx V n). Proof. exact: raddfB. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead"), warning="-deprecated"] Definition diag_mx_is_additive := diag_mx_is_zmod_morphism. (* Scalar matrix : a diagonal matrix with a constant on the diagonal *) Section ScalarMx. Variable n : nat. #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead")] Fact scalar_mx_is_zmod_morphism : zmod_morphism (@scalar_mx V n). Proof. exact: raddfB. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead"), warning="-deprecated"] Definition scalar_mx_is_additive := scalar_mx_is_zmod_morphism. End ScalarMx. (* The trace. *) Section Trace. Variable n : nat. #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead")] Fact mxtrace_is_zmod_morphism : zmod_morphism (@mxtrace V n). Proof. exact: raddfB. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `raddfB` instead"), warning="-deprecated"] Definition mxtrace_is_additive := mxtrace_is_zmod_morphism. End Trace. End MatrixZmodule. (* Parametricity over the additive structure. *) Section MapZmodMatrix. Variables (aR rR : zmodType) (f : {additive aR -> rR}) (m n : nat). Local Notation "A ^f" := (map_mx f A) : ring_scope. Implicit Type A : 'M[aR]_(m, n). Lemma map_mxN A : (- A)^f = - A^f. Proof. exact: raddfN. Qed. Lemma map_mxB A B : (A - B)^f = A^f - B^f. Proof. exact: raddfB. Qed. End MapZmodMatrix. (*****************************************************************************) (*********** Matrix ring module, graded ring, and ring structures ************) (*****************************************************************************) Section MatrixAlgebra. Variable R : pzSemiRingType. Section SemiRingModule. (* The ring module/vector space structure *) Variables m n : nat. Implicit Types A B : 'M[R]_(m, n). Fact scalemx_key : unit. Proof. by []. Qed. Definition scalemx x A := \matrix[scalemx_key]_(i, j) (x * A i j). (* Basis *) Fact delta_mx_key : unit. Proof. by []. Qed. Definition delta_mx i0 j0 : 'M[R]_(m, n) := \matrix[delta_mx_key]_(i, j) ((i == i0) && (j == j0))%:R. Local Notation "x *m: A" := (scalemx x A) (at level 40) : ring_scope. Fact scale0mx A : 0 *m: A = 0. Proof. by apply/matrixP=> i j; rewrite !mxE mul0r. Qed. Fact scale1mx A : 1 *m: A = A. Proof. by apply/matrixP=> i j; rewrite !mxE mul1r. Qed. Fact scalemxDl A x y : (x + y) *m: A = x *m: A + y *m: A. Proof. by apply/matrixP=> i j; rewrite !mxE mulrDl. Qed. Fact scalemxDr x A B : x *m: (A + B) = x *m: A + x *m: B. Proof. by apply/matrixP=> i j; rewrite !mxE mulrDr. Qed. Fact scalemxA x y A : x *m: (y *m: A) = (x * y) *m: A. Proof. by apply/matrixP=> i j; rewrite !mxE mulrA. Qed. HB.instance Definition _ := GRing.Nmodule_isLSemiModule.Build R 'M[R]_(m, n) scalemxA scale0mx scale1mx scalemxDr scalemxDl. Lemma scalemx_const a b : a *: const_mx b = const_mx (a * b). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma matrix_sum_delta A : A = \sum_(i < m) \sum_(j < n) A i j *: delta_mx i j. Proof. apply/matrixP=> i j. rewrite summxE (bigD1_ord i) // summxE (bigD1_ord j) //= !mxE !eqxx mulr1. rewrite !big1 ?addr0 //= => [i' | j'] _. by rewrite summxE big1// => j' _; rewrite !mxE eq_liftF mulr0. by rewrite !mxE eqxx eq_liftF mulr0. Qed. End SemiRingModule. Lemma trmx_delta m n i j : (delta_mx i j)^T = delta_mx j i :> 'M[R]_(n, m). Proof. by apply/matrixP=> i' j'; rewrite !mxE andbC. Qed. Lemma delta_mx_lshift m n1 n2 i j : delta_mx i (lshift n2 j) = row_mx (delta_mx i j) 0 :> 'M_(m, n1 + n2). Proof. apply/matrixP=> i' j'; rewrite !mxE -(can_eq splitK) (unsplitK (inl _ _)). by case: split => ?; rewrite mxE ?andbF. Qed. Lemma delta_mx_rshift m n1 n2 i j : delta_mx i (rshift n1 j) = row_mx 0 (delta_mx i j) :> 'M_(m, n1 + n2). Proof. apply/matrixP=> i' j'; rewrite !mxE -(can_eq splitK) (unsplitK (inr _ _)). by case: split => ?; rewrite mxE ?andbF. Qed. Lemma delta_mx_ushift m1 m2 n i j : delta_mx (lshift m2 i) j = col_mx (delta_mx i j) 0 :> 'M_(m1 + m2, n). Proof. apply/matrixP=> i' j'; rewrite !mxE -(can_eq splitK) (unsplitK (inl _ _)). by case: split => ?; rewrite mxE. Qed. Lemma delta_mx_dshift m1 m2 n i j : delta_mx (rshift m1 i) j = col_mx 0 (delta_mx i j) :> 'M_(m1 + m2, n). Proof. apply/matrixP=> i' j'; rewrite !mxE -(can_eq splitK) (unsplitK (inr _ _)). by case: split => ?; rewrite mxE. Qed. Lemma vec_mx_delta m n i j : vec_mx (delta_mx 0 (mxvec_index i j)) = delta_mx i j :> 'M_(m, n). Proof. by apply/matrixP=> i' j'; rewrite !mxE /= [_ == _](inj_eq enum_rank_inj). Qed. Lemma mxvec_delta m n i j : mxvec (delta_mx i j) = delta_mx 0 (mxvec_index i j) :> 'rV_(m * n). Proof. by rewrite -vec_mx_delta vec_mxK. Qed. Ltac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?]. (* Scalar matrix *) Notation "x %:M" := (scalar_mx x) : ring_scope. Lemma trmx1 n : (1%:M)^T = 1%:M :> 'M[R]_n. Proof. exact: tr_scalar_mx. Qed. Lemma row1 n i : row i (1%:M : 'M_n) = delta_mx 0 i. Proof. by apply/rowP=> j; rewrite !mxE eq_sym. Qed. Lemma col1 n i : col i (1%:M : 'M_n) = delta_mx i 0. Proof. by apply/colP => j; rewrite !mxE eqxx andbT. Qed. (* Matrix multiplication using bigops. *) Fact mulmx_key : unit. Proof. by []. Qed. Definition mulmx {m n p} (A : 'M_(m, n)) (B : 'M_(n, p)) : 'M[R]_(m, p) := \matrix[mulmx_key]_(i, k) \sum_j (A i j * B j k). Local Notation "A *m B" := (mulmx A B) : ring_scope. Lemma mulmxA m n p q (A : 'M_(m, n)) (B : 'M_(n, p)) (C : 'M_(p, q)) : A *m (B *m C) = A *m B *m C. Proof. apply/matrixP=> i l /[!mxE]; under eq_bigr do rewrite mxE big_distrr/=. rewrite exchange_big; apply: eq_bigr => j _; rewrite mxE big_distrl /=. by under eq_bigr do rewrite mulrA. Qed. Lemma mul0mx m n p (A : 'M_(n, p)) : 0 *m A = 0 :> 'M_(m, p). Proof. by apply/matrixP=> i k; rewrite !mxE big1 //= => j _; rewrite mxE mul0r. Qed. Lemma mulmx0 m n p (A : 'M_(m, n)) : A *m 0 = 0 :> 'M_(m, p). Proof. by apply/matrixP=> i k; rewrite !mxE big1 // => j _; rewrite mxE mulr0. Qed. Lemma mulmxDl m n p (A1 A2 : 'M_(m, n)) (B : 'M_(n, p)) : (A1 + A2) *m B = A1 *m B + A2 *m B. Proof. apply/matrixP=> i k; rewrite !mxE -big_split /=. by apply: eq_bigr => j _; rewrite !mxE -mulrDl. Qed. Lemma mulmxDr m n p (A : 'M_(m, n)) (B1 B2 : 'M_(n, p)) : A *m (B1 + B2) = A *m B1 + A *m B2. Proof. apply/matrixP=> i k; rewrite !mxE -big_split /=. by apply: eq_bigr => j _; rewrite mxE mulrDr. Qed. HB.instance Definition _ m n p A := GRing.isNmodMorphism.Build 'M_(n, p) 'M_(m, p) (mulmx A) (mulmx0 _ A, mulmxDr A). Lemma scalemxAl m n p a (A : 'M_(m, n)) (B : 'M_(n, p)) : a *: (A *m B) = (a *: A) *m B. Proof. apply/matrixP=> i k; rewrite !mxE big_distrr /=. by apply: eq_bigr => j _; rewrite mulrA mxE. Qed. Lemma mulmx_suml m n p (A : 'M_(n, p)) I r P (B_ : I -> 'M_(m, n)) : (\sum_(i <- r | P i) B_ i) *m A = \sum_(i <- r | P i) B_ i *m A. Proof. by apply: (big_morph (mulmx^~ A)) => [B C|]; rewrite ?mul0mx ?mulmxDl. Qed. Lemma mulmx_sumr m n p (A : 'M_(m, n)) I r P (B_ : I -> 'M_(n, p)) : A *m (\sum_(i <- r | P i) B_ i) = \sum_(i <- r | P i) A *m B_ i. Proof. exact: raddf_sum. Qed. Lemma rowE m n i (A : 'M_(m, n)) : row i A = delta_mx 0 i *m A. Proof. apply/rowP=> j; rewrite !mxE (bigD1_ord i) //= mxE !eqxx mul1r. by rewrite big1 ?addr0 // => i'; rewrite mxE /= lift_eqF mul0r. Qed. Lemma colE m n i (A : 'M_(m, n)) : col i A = A *m delta_mx i 0. Proof. apply/colP=> j; rewrite !mxE (bigD1_ord i) //= mxE !eqxx mulr1. by rewrite big1 ?addr0 // => i'; rewrite mxE /= lift_eqF mulr0. Qed. Lemma mul_rVP m n A B : ((@mulmx 1 m n)^~ A =1 mulmx^~ B) <-> (A = B). Proof. by split=> [eqAB|->//]; apply/row_matrixP => i; rewrite !rowE eqAB. Qed. Lemma row_mul m n p (i : 'I_m) A (B : 'M_(n, p)) : row i (A *m B) = row i A *m B. Proof. by rewrite !rowE mulmxA. Qed. Lemma mxsub_mul m n m' n' p f g (A : 'M_(m, p)) (B : 'M_(p, n)) : mxsub f g (A *m B) = rowsub f A *m colsub g B :> 'M_(m', n'). Proof. by split_mxE; under [RHS]eq_bigr do rewrite !mxE. Qed. Lemma mul_rowsub_mx m n m' p f (A : 'M_(m, p)) (B : 'M_(p, n)) : rowsub f A *m B = rowsub f (A *m B) :> 'M_(m', n). Proof. by rewrite mxsub_mul mxsub_id. Qed. Lemma mulmx_colsub m n n' p g (A : 'M_(m, p)) (B : 'M_(p, n)) : A *m colsub g B = colsub g (A *m B) :> 'M_(m, n'). Proof. by rewrite mxsub_mul mxsub_id. Qed. Lemma mul_delta_mx_cond m n p (j1 j2 : 'I_n) (i1 : 'I_m) (k2 : 'I_p) : delta_mx i1 j1 *m delta_mx j2 k2 = delta_mx i1 k2 *+ (j1 == j2). Proof. apply/matrixP => i k; rewrite !mxE (bigD1_ord j1) //=. rewrite mulmxnE !mxE !eqxx andbT -natrM -mulrnA !mulnb !andbA andbAC. by rewrite big1 ?addr0 // => j; rewrite !mxE andbC -natrM lift_eqF. Qed. Lemma mul_delta_mx m n p (j : 'I_n) (i : 'I_m) (k : 'I_p) : delta_mx i j *m delta_mx j k = delta_mx i k. Proof. by rewrite mul_delta_mx_cond eqxx. Qed. Lemma mul_delta_mx_0 m n p (j1 j2 : 'I_n) (i1 : 'I_m) (k2 : 'I_p) : j1 != j2 -> delta_mx i1 j1 *m delta_mx j2 k2 = 0. Proof. by rewrite mul_delta_mx_cond => /negPf->. Qed. Lemma mul_diag_mx m n d (A : 'M_(m, n)) : diag_mx d *m A = \matrix_(i, j) (d 0 i * A i j). Proof. apply/matrixP=> i j; rewrite !mxE (bigD1 i) //= mxE eqxx big1 ?addr0 // => i'. by rewrite mxE eq_sym mulrnAl => /negPf->. Qed. Lemma mul_mx_diag m n (A : 'M_(m, n)) d : A *m diag_mx d = \matrix_(i, j) (A i j * d 0 j). Proof. apply/matrixP=> i j; rewrite !mxE (bigD1 j) //= mxE eqxx big1 ?addr0 // => i'. by rewrite mxE eq_sym mulrnAr; move/negPf->. Qed. Lemma mulmx_diag n (d e : 'rV_n) : diag_mx d *m diag_mx e = diag_mx (\row_j (d 0 j * e 0 j)). Proof. by apply/matrixP=> i j; rewrite mul_diag_mx !mxE mulrnAr. Qed. Lemma scalar_mxM n a b : (a * b)%:M = a%:M *m b%:M :> 'M_n. Proof. rewrite -[in RHS]diag_const_mx mul_diag_mx. by apply/matrixP => i j; rewrite !mxE mulrnAr. Qed. Lemma mul1mx m n (A : 'M_(m, n)) : 1%:M *m A = A. Proof. by rewrite -diag_const_mx mul_diag_mx; apply/matrixP => i j; rewrite !mxE mul1r. Qed. Lemma mulmx1 m n (A : 'M_(m, n)) : A *m 1%:M = A. Proof. by rewrite -diag_const_mx mul_mx_diag; apply/matrixP=> i j; rewrite !mxE mulr1. Qed. Lemma rowsubE m m' n f (A : 'M_(m, n)) : rowsub f A = rowsub f 1%:M *m A :> 'M_(m', n). Proof. by rewrite mul_rowsub_mx mul1mx. Qed. (* mulmx and col_perm, row_perm, xcol, xrow *) Lemma mul_col_perm m n p s (A : 'M_(m, n)) (B : 'M_(n, p)) : col_perm s A *m B = A *m row_perm s^-1 B. Proof. apply/matrixP=> i k; rewrite !mxE (reindex_perm s^-1). by apply: eq_bigr => j _ /=; rewrite !mxE permKV. Qed. Lemma mul_row_perm m n p s (A : 'M_(m, n)) (B : 'M_(n, p)) : A *m row_perm s B = col_perm s^-1 A *m B. Proof. by rewrite mul_col_perm invgK. Qed. Lemma mul_xcol m n p j1 j2 (A : 'M_(m, n)) (B : 'M_(n, p)) : xcol j1 j2 A *m B = A *m xrow j1 j2 B. Proof. by rewrite mul_col_perm tpermV. Qed. (* Permutation matrix *) Definition perm_mx n s : 'M_n := row_perm s (1%:M : 'M[R]_n). Definition tperm_mx n i1 i2 : 'M_n := perm_mx (tperm i1 i2). Lemma col_permE m n s (A : 'M_(m, n)) : col_perm s A = A *m perm_mx s^-1. Proof. by rewrite mul_row_perm mulmx1 invgK. Qed. Lemma row_permE m n s (A : 'M_(m, n)) : row_perm s A = perm_mx s *m A. Proof. by rewrite -[perm_mx _]mul1mx mul_row_perm mulmx1 -mul_row_perm mul1mx. Qed. Lemma xcolE m n j1 j2 (A : 'M_(m, n)) : xcol j1 j2 A = A *m tperm_mx j1 j2. Proof. by rewrite /xcol col_permE tpermV. Qed. Lemma xrowE m n i1 i2 (A : 'M_(m, n)) : xrow i1 i2 A = tperm_mx i1 i2 *m A. Proof. exact: row_permE. Qed. Lemma perm_mxEsub n s : @perm_mx n s = rowsub s 1%:M. Proof. by rewrite /perm_mx row_permEsub. Qed. Lemma tperm_mxEsub n i1 i2 : @tperm_mx n i1 i2 = rowsub (tperm i1 i2) 1%:M. Proof. by rewrite /tperm_mx perm_mxEsub. Qed. Lemma tr_perm_mx n (s : 'S_n) : (perm_mx s)^T = perm_mx s^-1. Proof. by rewrite -[_^T]mulmx1 tr_row_perm mul_col_perm trmx1 mul1mx. Qed. Lemma tr_tperm_mx n i1 i2 : (tperm_mx i1 i2)^T = tperm_mx i1 i2 :> 'M_n. Proof. by rewrite tr_perm_mx tpermV. Qed. Lemma perm_mx1 n : perm_mx 1 = 1%:M :> 'M_n. Proof. exact: row_perm1. Qed. Lemma perm_mxM n (s t : 'S_n) : perm_mx (s * t) = perm_mx s *m perm_mx t. Proof. by rewrite -row_permE -row_permM. Qed. Definition is_perm_mx n (A : 'M_n) := [exists s, A == perm_mx s]. Lemma is_perm_mxP n (A : 'M_n) : reflect (exists s, A = perm_mx s) (is_perm_mx A). Proof. by apply: (iffP existsP) => [] [s /eqP]; exists s. Qed. Lemma perm_mx_is_perm n (s : 'S_n) : is_perm_mx (perm_mx s). Proof. by apply/is_perm_mxP; exists s. Qed. Lemma is_perm_mx1 n : is_perm_mx (1%:M : 'M_n). Proof. by rewrite -perm_mx1 perm_mx_is_perm. Qed. Lemma is_perm_mxMl n (A B : 'M_n) : is_perm_mx A -> is_perm_mx (A *m B) = is_perm_mx B. Proof. case/is_perm_mxP=> s ->. apply/is_perm_mxP/is_perm_mxP=> [[t def_t] | [t ->]]; last first. by exists (s * t)%g; rewrite perm_mxM. exists (s^-1 * t)%g. by rewrite perm_mxM -def_t -!row_permE -row_permM mulVg row_perm1. Qed. Lemma is_perm_mx_tr n (A : 'M_n) : is_perm_mx A^T = is_perm_mx A. Proof. apply/is_perm_mxP/is_perm_mxP=> [[t def_t] | [t ->]]; exists t^-1%g. by rewrite -tr_perm_mx -def_t trmxK. by rewrite tr_perm_mx. Qed. Lemma is_perm_mxMr n (A B : 'M_n) : is_perm_mx B -> is_perm_mx (A *m B) = is_perm_mx A. Proof. case/is_perm_mxP=> s ->. rewrite -[s]invgK -col_permE -is_perm_mx_tr tr_col_perm row_permE. by rewrite is_perm_mxMl (perm_mx_is_perm, is_perm_mx_tr). Qed. (* Partial identity matrix (used in rank decomposition). *) Fact pid_mx_key : unit. Proof. by []. Qed. Definition pid_mx {m n} r : 'M[R]_(m, n) := \matrix[pid_mx_key]_(i, j) ((i == j :> nat) && (i < r))%:R. Lemma pid_mx_0 m n : pid_mx 0 = 0 :> 'M_(m, n). Proof. by apply/matrixP=> i j; rewrite !mxE andbF. Qed. Lemma pid_mx_1 r : pid_mx r = 1%:M :> 'M_r. Proof. by apply/matrixP=> i j; rewrite !mxE ltn_ord andbT. Qed. Lemma pid_mx_row n r : pid_mx r = row_mx 1%:M 0 :> 'M_(r, r + n). Proof. apply/matrixP=> i j; rewrite !mxE ltn_ord andbT. by case: split_ordP => j' ->; rewrite !mxE// (val_eqE (lshift n i)) eq_shift. Qed. Lemma pid_mx_col m r : pid_mx r = col_mx 1%:M 0 :> 'M_(r + m, r). Proof. apply/matrixP=> i j; rewrite !mxE andbC. by case: split_ordP => ? ->; rewrite !mxE//. Qed. Lemma pid_mx_block m n r : pid_mx r = block_mx 1%:M 0 0 0 :> 'M_(r + m, r + n). Proof. apply/matrixP=> i j; rewrite !mxE row_mx0 andbC. do ![case: split_ordP => ? -> /[!mxE]//]. by rewrite (val_eqE (lshift n _)) eq_shift. Qed. Lemma tr_pid_mx m n r : (pid_mx r)^T = pid_mx r :> 'M_(n, m). Proof. by apply/matrixP=> i j /[!mxE]; case: eqVneq => // ->. Qed. Lemma pid_mx_minv m n r : pid_mx (minn m r) = pid_mx r :> 'M_(m, n). Proof. by apply/matrixP=> i j; rewrite !mxE leq_min ltn_ord. Qed. Lemma pid_mx_minh m n r : pid_mx (minn n r) = pid_mx r :> 'M_(m, n). Proof. by apply: trmx_inj; rewrite !tr_pid_mx pid_mx_minv. Qed. Lemma mul_pid_mx m n p q r : (pid_mx q : 'M_(m, n)) *m (pid_mx r : 'M_(n, p)) = pid_mx (minn n (minn q r)). Proof. apply/matrixP=> i k; rewrite !mxE !leq_min. have [le_n_i | lt_i_n] := leqP n i. rewrite andbF big1 // => j _. by rewrite -pid_mx_minh !mxE leq_min ltnNge le_n_i andbF mul0r. rewrite (bigD1 (Ordinal lt_i_n)) //= big1 ?addr0 => [|j]. by rewrite !mxE eqxx /= -natrM mulnb andbCA. by rewrite -val_eqE /= !mxE eq_sym -natrM => /negPf->. Qed. Lemma pid_mx_id m n p r : r <= n -> (pid_mx r : 'M_(m, n)) *m (pid_mx r : 'M_(n, p)) = pid_mx r. Proof. by move=> le_r_n; rewrite mul_pid_mx minnn (minn_idPr _). Qed. Lemma pid_mxErow m n (le_mn : m <= n) : pid_mx m = rowsub (widen_ord le_mn) 1%:M. Proof. by apply/matrixP=> i j; rewrite !mxE -!val_eqE/= ltn_ord andbT. Qed. Lemma pid_mxEcol m n (le_mn : m <= n) : pid_mx n = colsub (widen_ord le_mn) 1%:M. Proof. by apply/matrixP=> i j; rewrite !mxE -!val_eqE/= ltn_ord andbT. Qed. (* Block products; we cover all 1 x 2, 2 x 1, and 2 x 2 block products. *) Lemma mul_mx_row m n p1 p2 (A : 'M_(m, n)) (Bl : 'M_(n, p1)) (Br : 'M_(n, p2)) : A *m row_mx Bl Br = row_mx (A *m Bl) (A *m Br). Proof. apply/matrixP=> i k; rewrite !mxE. by case defk: (split k) => /[!mxE]; under eq_bigr do rewrite mxE defk. Qed. Lemma mul_col_mx m1 m2 n p (Au : 'M_(m1, n)) (Ad : 'M_(m2, n)) (B : 'M_(n, p)) : col_mx Au Ad *m B = col_mx (Au *m B) (Ad *m B). Proof. apply/matrixP=> i k; rewrite !mxE. by case defi: (split i) => /[!mxE]; under eq_bigr do rewrite mxE defi. Qed. Lemma mul_row_col m n1 n2 p (Al : 'M_(m, n1)) (Ar : 'M_(m, n2)) (Bu : 'M_(n1, p)) (Bd : 'M_(n2, p)) : row_mx Al Ar *m col_mx Bu Bd = Al *m Bu + Ar *m Bd. Proof. apply/matrixP=> i k; rewrite !mxE big_split_ord /=. congr (_ + _); apply: eq_bigr => j _; first by rewrite row_mxEl col_mxEu. by rewrite row_mxEr col_mxEd. Qed. Lemma mul_col_row m1 m2 n p1 p2 (Au : 'M_(m1, n)) (Ad : 'M_(m2, n)) (Bl : 'M_(n, p1)) (Br : 'M_(n, p2)) : col_mx Au Ad *m row_mx Bl Br = block_mx (Au *m Bl) (Au *m Br) (Ad *m Bl) (Ad *m Br). Proof. by rewrite mul_col_mx !mul_mx_row. Qed. Lemma mul_row_block m n1 n2 p1 p2 (Al : 'M_(m, n1)) (Ar : 'M_(m, n2)) (Bul : 'M_(n1, p1)) (Bur : 'M_(n1, p2)) (Bdl : 'M_(n2, p1)) (Bdr : 'M_(n2, p2)) : row_mx Al Ar *m block_mx Bul Bur Bdl Bdr = row_mx (Al *m Bul + Ar *m Bdl) (Al *m Bur + Ar *m Bdr). Proof. by rewrite block_mxEh mul_mx_row !mul_row_col. Qed. Lemma mul_block_col m1 m2 n1 n2 p (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2)) (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2)) (Bu : 'M_(n1, p)) (Bd : 'M_(n2, p)) : block_mx Aul Aur Adl Adr *m col_mx Bu Bd = col_mx (Aul *m Bu + Aur *m Bd) (Adl *m Bu + Adr *m Bd). Proof. by rewrite mul_col_mx !mul_row_col. Qed. Lemma mulmx_block m1 m2 n1 n2 p1 p2 (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2)) (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2)) (Bul : 'M_(n1, p1)) (Bur : 'M_(n1, p2)) (Bdl : 'M_(n2, p1)) (Bdr : 'M_(n2, p2)) : block_mx Aul Aur Adl Adr *m block_mx Bul Bur Bdl Bdr = block_mx (Aul *m Bul + Aur *m Bdl) (Aul *m Bur + Aur *m Bdr) (Adl *m Bul + Adr *m Bdl) (Adl *m Bur + Adr *m Bdr). Proof. by rewrite mul_col_mx !mul_row_block. Qed. Lemma mulmx_lsub m n p k (A : 'M_(m, n)) (B : 'M_(n, p + k)) : A *m lsubmx B = lsubmx (A *m B). Proof. by rewrite !lsubmxEsub mulmx_colsub. Qed. Lemma mulmx_rsub m n p k (A : 'M_(m, n)) (B : 'M_(n, p + k)) : A *m rsubmx B = rsubmx (A *m B). Proof. by rewrite !rsubmxEsub mulmx_colsub. Qed. Lemma mul_usub_mx m k n p (A : 'M_(m + k, n)) (B : 'M_(n, p)) : usubmx A *m B = usubmx (A *m B). Proof. by rewrite !usubmxEsub mul_rowsub_mx. Qed. Lemma mul_dsub_mx m k n p (A : 'M_(m + k, n)) (B : 'M_(n, p)) : dsubmx A *m B = dsubmx (A *m B). Proof. by rewrite !dsubmxEsub mul_rowsub_mx. Qed. (* The trace *) Section Trace. Variable n : nat. Lemma mxtrace1 : \tr (1%:M : 'M[R]_n) = n%:R. Proof. exact: mxtrace_scalar. Qed. Lemma mxtraceZ a (A : 'M_n) : \tr (a *: A) = a * \tr A. Proof. by rewrite mulr_sumr; apply: eq_bigr=> i _; rewrite mxE. Qed. HB.instance Definition _ := GRing.isScalable.Build R 'M_n R _ (@mxtrace _ n) mxtraceZ. End Trace. Section StructuralLinear. Fact swizzle_mx_is_scalable m n p q f g k : scalable (@swizzle_mx R m n p q f g k). Proof. by move=> a A; apply/matrixP=> i j; rewrite !mxE. Qed. HB.instance Definition _ m n p q f g k := GRing.isScalable.Build R 'M[R]_(m, n) 'M[R]_(p, q) *:%R (swizzle_mx f g k) (swizzle_mx_is_scalable f g k). Local Notation SwizzleLin op := (GRing.Linear.copy op (swizzle_mx _ _ _)). HB.instance Definition _ m n := SwizzleLin (@trmx R m n). HB.instance Definition _ m n i := SwizzleLin (@row R m n i). HB.instance Definition _ m n j := SwizzleLin (@col R m n j). HB.instance Definition _ m n i := SwizzleLin (@row' R m n i). HB.instance Definition _ m n j := SwizzleLin (@col' R m n j). HB.instance Definition _ m n m' n' f g := SwizzleLin (@mxsub R m n m' n' f g). HB.instance Definition _ m n s := SwizzleLin (@row_perm R m n s). HB.instance Definition _ m n s := SwizzleLin (@col_perm R m n s). HB.instance Definition _ m n i1 i2 := SwizzleLin (@xrow R m n i1 i2). HB.instance Definition _ m n j1 j2 := SwizzleLin (@xcol R m n j1 j2). HB.instance Definition _ m n1 n2 := SwizzleLin (@lsubmx R m n1 n2). HB.instance Definition _ m n1 n2 := SwizzleLin (@rsubmx R m n1 n2). HB.instance Definition _ m1 m2 n := SwizzleLin (@usubmx R m1 m2 n). HB.instance Definition _ m1 m2 n := SwizzleLin (@dsubmx R m1 m2 n). HB.instance Definition _ m n := SwizzleLin (@vec_mx R m n). Definition mxvec_is_scalable m n := can2_scalable (@vec_mxK R m n) mxvecK. HB.instance Definition _ m n := GRing.isScalable.Build R 'M_(m, n) 'rV_(m * n) *:%R mxvec (@mxvec_is_scalable m n). End StructuralLinear. Lemma row_sum_delta n (u : 'rV_n) : u = \sum_(j < n) u 0 j *: delta_mx 0 j. Proof. by rewrite [u in LHS]matrix_sum_delta big_ord1. Qed. Lemma scale_row_mx m n1 n2 a (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : a *: row_mx A1 A2 = row_mx (a *: A1) (a *: A2). Proof. by split_mxE. Qed. Lemma scale_col_mx m1 m2 n a (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : a *: col_mx A1 A2 = col_mx (a *: A1) (a *: A2). Proof. by split_mxE. Qed. Lemma scale_block_mx m1 m2 n1 n2 a (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2)) (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2)) : a *: block_mx Aul Aur Adl Adr = block_mx (a *: Aul) (a *: Aur) (a *: Adl) (a *: Adr). Proof. by rewrite scale_col_mx !scale_row_mx. Qed. (* Diagonal matrices *) Fact diag_mx_is_scalable n : scalable (@diag_mx R n). Proof. by move=> a A; apply/matrixP=> i j; rewrite !mxE mulrnAr. Qed. HB.instance Definition _ n := GRing.isScalable.Build R 'rV_n 'M_n _ (@diag_mx _ n) (@diag_mx_is_scalable n). Lemma diag_mx_sum_delta n (d : 'rV_n) : diag_mx d = \sum_i d 0 i *: delta_mx i i. Proof. apply/matrixP=> i j; rewrite summxE (bigD1_ord i) //= !mxE eqxx /=. by rewrite eq_sym mulr_natr big1 ?addr0 // => i'; rewrite !mxE eq_liftF mulr0. Qed. Lemma row_diag_mx n (d : 'rV_n) i : row i (diag_mx d) = d 0 i *: delta_mx 0 i. Proof. by apply/rowP => j; rewrite !mxE eqxx eq_sym mulr_natr. Qed. (* Scalar matrix *) Lemma scale_scalar_mx n a1 a2 : a1 *: a2%:M = (a1 * a2)%:M :> 'M_n. Proof. by apply/matrixP=> i j; rewrite !mxE mulrnAr. Qed. Lemma scalemx1 n a : a *: 1%:M = a%:M :> 'M_n. Proof. by rewrite scale_scalar_mx mulr1. Qed. Lemma scalar_mx_sum_delta n a : a%:M = \sum_i a *: delta_mx i i :> 'M_n. Proof. by rewrite -diag_const_mx diag_mx_sum_delta; under eq_bigr do rewrite mxE. Qed. Lemma mx1_sum_delta n : 1%:M = \sum_i delta_mx i i :> 'M[R]_n. Proof. by rewrite [1%:M]scalar_mx_sum_delta -scaler_sumr scale1r. Qed. (* Right scaling associativity requires a commutative ring *) Lemma mulmx_sum_row m n (u : 'rV_m) (A : 'M_(m, n)) : u *m A = \sum_i u 0 i *: row i A. Proof. by apply/rowP => j /[!(mxE, summxE)]; apply: eq_bigr => i _ /[!mxE]. Qed. Lemma mul_scalar_mx m n a (A : 'M_(m, n)) : a%:M *m A = a *: A. Proof. by rewrite -diag_const_mx mul_diag_mx; apply/matrixP=> i j; rewrite !mxE. Qed. Section MatrixSemiRing. Variable n : nat. HB.instance Definition _ := GRing.Nmodule_isPzSemiRing.Build 'M[R]_n (@mulmxA n n n n) (@mul1mx n n) (@mulmx1 n n) (@mulmxDl n n n) (@mulmxDr n n n) (@mul0mx n n n) (@mulmx0 n n n). Lemma mulmxE : mulmx = *%R. Proof. by []. Qed. Lemma idmxE : 1%:M = 1 :> 'M_n. Proof. by []. Qed. Fact scalar_mx_is_monoid_morphism : monoid_morphism (@scalar_mx R n). Proof. by split=> //; apply: scalar_mxM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `scalar_mx_is_monoid_morphism` instead")] Definition scalar_mx_is_multiplicative := scalar_mx_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build R 'M_n (@scalar_mx _ n) scalar_mx_is_monoid_morphism. End MatrixSemiRing. (* Correspondence between matrices and linear function on row vectors. *) Section LinRowVector. Variables m n : nat. Fact lin1_mx_key : unit. Proof. by []. Qed. Definition lin1_mx (f : 'rV[R]_m -> 'rV[R]_n) := \matrix[lin1_mx_key]_(i, j) f (delta_mx 0 i) 0 j. Variable f : {linear 'rV[R]_m -> 'rV[R]_n}. Lemma mul_rV_lin1 u : u *m lin1_mx f = f u. Proof. rewrite [u in RHS]matrix_sum_delta big_ord1 linear_sum; apply/rowP=> i. by rewrite mxE summxE; apply: eq_bigr => j _; rewrite linearZ !mxE. Qed. End LinRowVector. (* Correspondence between matrices and linear function on matrices. *) Section LinMatrix. Variables m1 n1 m2 n2 : nat. Definition lin_mx (f : 'M[R]_(m1, n1) -> 'M[R]_(m2, n2)) := lin1_mx (mxvec \o f \o vec_mx). Variable f : {linear 'M[R]_(m1, n1) -> 'M[R]_(m2, n2)}. Lemma mul_rV_lin u : u *m lin_mx f = mxvec (f (vec_mx u)). Proof. exact: mul_rV_lin1. Qed. Lemma mul_vec_lin A : mxvec A *m lin_mx f = mxvec (f A). Proof. by rewrite mul_rV_lin mxvecK. Qed. Lemma mx_rV_lin u : vec_mx (u *m lin_mx f) = f (vec_mx u). Proof. by rewrite mul_rV_lin mxvecK. Qed. Lemma mx_vec_lin A : vec_mx (mxvec A *m lin_mx f) = f A. Proof. by rewrite mul_rV_lin !mxvecK. Qed. End LinMatrix. Section Mulmxr. Variables m n p : nat. Implicit Type A : 'M[R]_(m, n). Implicit Type B : 'M[R]_(n, p). Definition mulmxr B A := mulmx A B. Arguments mulmxr B A /. Fact mulmxr_is_semilinear B : semilinear (mulmxr B). Proof. by split=> [a A|A1 A2]; rewrite /= (mulmxDl, scalemxAl). Qed. HB.instance Definition _ (B : 'M_(n, p)) := GRing.isSemilinear.Build R 'M_(m, n) 'M_(m, p) _ (mulmxr B) (mulmxr_is_semilinear B). Definition lin_mulmxr B := lin_mx (mulmxr B). Fact lin_mulmxr_is_semilinear : semilinear lin_mulmxr. Proof. split=> [a A|A B]; apply/row_matrixP; case/mxvec_indexP=> i j; rewrite (linearZ, linearD) /= !rowE !mul_rV_lin /= vec_mx_delta; rewrite -(linearZ, linearD) 1?mulmxDr //=. congr mxvec; apply/row_matrixP=> k. rewrite linearZ /= !row_mul rowE mul_delta_mx_cond. by case: (k == i); [rewrite -!rowE linearZ | rewrite !mul0mx raddf0]. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R 'M_(n, p) 'M_(m * n, m * p) _ lin_mulmxr lin_mulmxr_is_semilinear. End Mulmxr. Section LiftPerm. (* Block expression of a lifted permutation matrix, for the Cormen LUP. *) Variable n : nat. (* These could be in zmodp, but that would introduce a dependency on perm. *) Definition lift0_perm s : 'S_n.+1 := lift_perm 0 0 s. Lemma lift0_perm0 s : lift0_perm s 0 = 0. Proof. exact: lift_perm_id. Qed. Lemma lift0_perm_lift s k' : lift0_perm s (lift 0 k') = lift (0 : 'I_n.+1) (s k'). Proof. exact: lift_perm_lift. Qed. Lemma lift0_permK s : cancel (lift0_perm s) (lift0_perm s^-1). Proof. by move=> i; rewrite /lift0_perm -lift_permV permK. Qed. Lemma lift0_perm_eq0 s i : (lift0_perm s i == 0) = (i == 0). Proof. by rewrite (canF_eq (lift0_permK s)) lift0_perm0. Qed. (* Block expression of a lifted permutation matrix *) Definition lift0_mx A : 'M_(1 + n) := block_mx 1 0 0 A. Lemma lift0_mx_perm s : lift0_mx (perm_mx s) = perm_mx (lift0_perm s). Proof. apply/matrixP=> /= i j; rewrite !mxE split1 /=; case: unliftP => [i'|] -> /=. rewrite lift0_perm_lift !mxE split1 /=. by case: unliftP => [j'|] ->; rewrite ?(inj_eq (lift_inj _)) /= !mxE. rewrite lift0_perm0 !mxE split1 /=. by case: unliftP => [j'|] ->; rewrite /= mxE. Qed. Lemma lift0_mx_is_perm s : is_perm_mx (lift0_mx (perm_mx s)). Proof. by rewrite lift0_mx_perm perm_mx_is_perm. Qed. End LiftPerm. Lemma exp_block_diag_mx m n (A: 'M_m.+1) (B : 'M_n.+1) k : (block_mx A 0 0 B) ^+ k = block_mx (A ^+ k) 0 0 (B ^+ k). Proof. elim: k=> [|k IHk]; first by rewrite !expr0 -scalar_mx_block. rewrite !exprS IHk [LHS](mulmx_block A _ _ _ (A ^+ k)). by rewrite !mulmx0 !mul0mx !add0r !addr0. Qed. End MatrixAlgebra. Arguments delta_mx {R m n}. Arguments perm_mx {R n}. Arguments tperm_mx {R n}. Arguments pid_mx {R m n}. Arguments lin_mulmxr {R m n p}. Prenex Implicits diag_mx is_scalar_mx. Prenex Implicits mulmx mxtrace. Arguments mul_delta_mx {R m n p}. Arguments mulmxr {_ _ _ _} B A /. #[global] Hint Extern 0 (is_true (is_diag_mx (scalar_mx _))) => apply: scalar_mx_is_diag : core. #[global] Hint Extern 0 (is_true (is_trig_mx (scalar_mx _))) => apply: scalar_mx_is_trig : core. #[global] Hint Extern 0 (is_true (is_diag_mx (diag_mx _))) => apply: diag_mx_is_diag : core. #[global] Hint Extern 0 (is_true (is_trig_mx (diag_mx _))) => apply: diag_mx_is_trig : core. Notation "a %:M" := (scalar_mx a) : ring_scope. Notation "A *m B" := (mulmx A B) : ring_scope. (* Non-commutative transpose requires multiplication in the converse ring. *) Lemma trmx_mul_rev (R : pzSemiRingType) m n p (A : 'M[R]_(m, n)) (B : 'M[R]_(n, p)) : (A *m B)^T = (B : 'M[R^c]_(n, p))^T *m (A : 'M[R^c]_(m, n))^T. Proof. by apply/matrixP=> k i /[!mxE]; apply: eq_bigr => j _ /[!mxE]. Qed. HB.instance Definition _ (R : pzRingType) m n := GRing.LSemiModule.on 'M[R]_(m, n). HB.instance Definition _ (R : pzRingType) n := GRing.PzSemiRing.on 'M[R]_n. Section MatrixNzSemiRing. Variables (R : nzSemiRingType) (n' : nat). Local Notation n := n'.+1. Lemma matrix_nonzero1 : 1%:M != 0 :> 'M[R]_n. Proof. by apply/eqP=> /matrixP/(_ 0 0)/eqP; rewrite !mxE oner_eq0. Qed. HB.instance Definition _ := GRing.PzSemiRing_isNonZero.Build 'M[R]_n matrix_nonzero1. HB.instance Definition _ := GRing.LSemiModule_isLSemiAlgebra.Build R 'M[R]_n (@scalemxAl R n n n). End MatrixNzSemiRing. HB.instance Definition _ (R : nzRingType) n := GRing.NzSemiRing.on 'M[R]_n.+1. HB.instance Definition _ (M : countNmodType) m n := [Countable of 'M[M]_(m, n) by <:]. HB.instance Definition _ (M : countZmodType) m n := [Countable of 'M[M]_(m, n) by <:]. HB.instance Definition _ (R : countNzSemiRingType) n := [Countable of 'M[R]_n.+1 by <:]. HB.instance Definition _ (R : countNzRingType) n := [Countable of 'M[R]_n.+1 by <:]. HB.instance Definition _ (V : finNmodType) (m n : nat) := [Finite of 'M[V]_(m, n) by <:]. HB.instance Definition _ (V : finZmodType) (m n : nat) := [Finite of 'M[V]_(m, n) by <:]. #[compress_coercions] HB.instance Definition _ (V : finZmodType) (m n : nat) := [finGroupMixin of 'M[V]_(m, n) for +%R]. #[compress_coercions] HB.instance Definition _ (R : finNzSemiRingType) n := [Finite of 'M[R]_n.+1 by <:]. #[compress_coercions] HB.instance Definition _ (R : finNzRingType) (m n : nat) := FinRing.Zmodule.on 'M[R]_(m, n). #[compress_coercions] HB.instance Definition _ (R : finNzRingType) n := [Finite of 'M[R]_n.+1 by <:]. (* Parametricity over the algebra structure. *) Section MapSemiRingMatrix. Variables (aR rR : pzSemiRingType) (f : {rmorphism aR -> rR}). Local Notation "A ^f" := (map_mx f A) : ring_scope. Section FixedSize. Variables m n p : nat. Implicit Type A : 'M[aR]_(m, n). Lemma map_mxZ a A : (a *: A)^f = f a *: A^f. Proof. by apply/matrixP=> i j; rewrite !mxE rmorphM. Qed. Lemma map_mxM A B : (A *m B)^f = A^f *m B^f :> 'M_(m, p). Proof. apply/matrixP=> i k; rewrite !mxE rmorph_sum //. by apply: eq_bigr => j; rewrite !mxE rmorphM. Qed. Lemma map_delta_mx i j : (delta_mx i j)^f = delta_mx i j :> 'M_(m, n). Proof. by apply/matrixP=> i' j'; rewrite !mxE rmorph_nat. Qed. Lemma map_diag_mx d : (diag_mx d)^f = diag_mx d^f :> 'M_n. Proof. by apply/matrixP=> i j; rewrite !mxE rmorphMn. Qed. Lemma map_scalar_mx a : a%:M^f = (f a)%:M :> 'M_n. Proof. by apply/matrixP=> i j; rewrite !mxE rmorphMn. Qed. Lemma map_mx1 : 1%:M^f = 1%:M :> 'M_n. Proof. by rewrite map_scalar_mx rmorph1. Qed. Lemma map_perm_mx (s : 'S_n) : (perm_mx s)^f = perm_mx s. Proof. by apply/matrixP=> i j; rewrite !mxE rmorph_nat. Qed. Lemma map_tperm_mx (i1 i2 : 'I_n) : (tperm_mx i1 i2)^f = tperm_mx i1 i2. Proof. exact: map_perm_mx. Qed. Lemma map_pid_mx r : (pid_mx r)^f = pid_mx r :> 'M_(m, n). Proof. by apply/matrixP=> i j; rewrite !mxE rmorph_nat. Qed. Lemma trace_map_mx (A : 'M_n) : \tr A^f = f (\tr A). Proof. by rewrite rmorph_sum; apply: eq_bigr => i _; rewrite mxE. Qed. End FixedSize. Lemma map_lin1_mx m n (g : 'rV_m -> 'rV_n) gf : (forall v, (g v)^f = gf v^f) -> (lin1_mx g)^f = lin1_mx gf. Proof. by move=> def_gf; apply/matrixP => i j; rewrite !mxE -map_delta_mx -def_gf mxE. Qed. Lemma map_lin_mx m1 n1 m2 n2 (g : 'M_(m1, n1) -> 'M_(m2, n2)) gf : (forall A, (g A)^f = gf A^f) -> (lin_mx g)^f = lin_mx gf. Proof. move=> def_gf; apply: map_lin1_mx => A /=. by rewrite map_mxvec def_gf map_vec_mx. Qed. Fact map_mx_is_monoid_morphism n : monoid_morphism (map_mx f : 'M_n -> 'M_n). Proof. by split; [apply: map_mx1 | apply: map_mxM]. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `map_mx_is_monoid_morphism` instead")] Definition map_mx_is_multiplicative := map_mx_is_monoid_morphism. HB.instance Definition _ n := GRing.isMonoidMorphism.Build 'M[aR]_n 'M[rR]_n (map_mx f) (map_mx_is_monoid_morphism n). End MapSemiRingMatrix. Section CommMx. (***********************************************************************) (************* Commutation property specialized to 'M[R]_n *************) (***********************************************************************) (* GRing.comm is bound to (non trivial) rings, and matrices form a *) (* (non trivial) ring only when they are square and of manifestly *) (* positive size. However during proofs in endomorphism reduction, we *) (* take restrictions, which are matrices of size #|V| (with V a matrix *) (* space) and it becomes cumbersome to state commutation between *) (* restrictions, unless we relax the setting, and this relaxation *) (* corresponds to comm_mx A B := A *m B = B *m A. *) (* As witnessed by comm_mxE, when A and B have type 'M_n.+1, *) (* comm_mx A B is convertible to GRing.comm A B. *) (* The boolean version comm_mxb is designed to be used with seq.allrel *) (***********************************************************************) Context {R : pzSemiRingType} {n : nat}. Implicit Types (f g p : 'M[R]_n) (fs : seq 'M[R]_n) (d : 'rV[R]_n) (I : Type). Definition comm_mx f g : Prop := f *m g = g *m f. Definition comm_mxb f g : bool := f *m g == g *m f. Lemma comm_mx_sym f g : comm_mx f g -> comm_mx g f. Proof. by rewrite /comm_mx. Qed. Lemma comm_mx_refl f : comm_mx f f. Proof. by []. Qed. Lemma comm_mx0 f : comm_mx f 0. Proof. by rewrite /comm_mx mulmx0 mul0mx. Qed. Lemma comm0mx f : comm_mx 0 f. Proof. by rewrite /comm_mx mulmx0 mul0mx. Qed. Lemma comm_mx1 f : comm_mx f 1%:M. Proof. by rewrite /comm_mx mulmx1 mul1mx. Qed. Lemma comm1mx f : comm_mx 1%:M f. Proof. by rewrite /comm_mx mulmx1 mul1mx. Qed. Hint Resolve comm_mx0 comm0mx comm_mx1 comm1mx : core. Lemma comm_mxD f g g' : comm_mx f g -> comm_mx f g' -> comm_mx f (g + g'). Proof. by rewrite /comm_mx mulmxDl mulmxDr => -> ->. Qed. Lemma comm_mxM f g g' : comm_mx f g -> comm_mx f g' -> comm_mx f (g *m g'). Proof. by rewrite /comm_mx mulmxA => ->; rewrite -!mulmxA => ->. Qed. Lemma comm_mx_sum I (s : seq I) (P : pred I) (F : I -> 'M[R]_n) (f : 'M[R]_n) : (forall i : I, P i -> comm_mx f (F i)) -> comm_mx f (\sum_(i <- s | P i) F i). Proof. by move=> comm_mxfF; elim/big_ind: _ => // g h; apply: comm_mxD. Qed. Lemma comm_mxP f g : reflect (comm_mx f g) (comm_mxb f g). Proof. exact: eqP. Qed. Notation all_comm_mx fs := (all2rel comm_mxb fs). Lemma all_comm_mxP fs : reflect {in fs &, forall f g, f *m g = g *m f} (all_comm_mx fs). Proof. by apply: (iffP allrelP) => fsP ? ? ? ?; apply/eqP/fsP. Qed. Lemma all_comm_mx1 f : all_comm_mx [:: f]. Proof. by rewrite /comm_mxb all2rel1. Qed. Lemma all_comm_mx2P f g : reflect (f *m g = g *m f) (all_comm_mx [:: f; g]). Proof. by rewrite /comm_mxb /= all2rel2 ?eqxx //; exact: eqP. Qed. Lemma all_comm_mx_cons f fs : all_comm_mx (f :: fs) = all (comm_mxb f) fs && all_comm_mx fs. Proof. by rewrite /comm_mxb /= all2rel_cons //= eqxx. Qed. Lemma comm_mxE : comm_mx = @GRing.comm _. Proof. by []. Qed. End CommMx. Notation all_comm_mx := (allrel comm_mxb). Section ComMatrix. (* Lemmas for matrices with coefficients in a commutative ring *) Variable R : comPzSemiRingType. Section AssocLeft. Variables m n p : nat. Implicit Type A : 'M[R]_(m, n). Implicit Type B : 'M[R]_(n, p). Lemma trmx_mul A B : (A *m B)^T = B^T *m A^T. Proof. rewrite trmx_mul_rev; apply/matrixP=> k i; rewrite !mxE. by apply: eq_bigr => j _; rewrite mulrC. Qed. Lemma scalemxAr a A B : a *: (A *m B) = A *m (a *: B). Proof. by apply: trmx_inj; rewrite trmx_mul !linearZ /= trmx_mul scalemxAl. Qed. Fact mulmx_is_scalable A : scalable (@mulmx _ m n p A). Proof. by move=> a B; rewrite scalemxAr. Qed. HB.instance Definition _ A := GRing.isScalable.Build R 'M[R]_(n, p) 'M[R]_(m, p) *:%R (mulmx A) (mulmx_is_scalable A). Definition lin_mulmx A : 'M[R]_(n * p, m * p) := lin_mx (mulmx A). Fact lin_mulmx_is_semilinear : semilinear lin_mulmx. Proof. by split=> [a A|A B]; apply/row_matrixP=> i; rewrite (linearZ, linearD) /=; rewrite !rowE !mul_rV_lin /= -(linearZ, linearD) /= (scalemxAl, mulmxDl). Qed. HB.instance Definition _ := GRing.isSemilinear.Build R 'M[R]_(m, n) 'M[R]_(n * p, m * p) _ lin_mulmx lin_mulmx_is_semilinear. End AssocLeft. Section LinMulRow. Variables m n : nat. Definition lin_mul_row u : 'M[R]_(m * n, n) := lin1_mx (mulmx u \o vec_mx). Fact lin_mul_row_is_semilinear : semilinear lin_mul_row. Proof. by split=> [a u|u v]; apply/row_matrixP=> i; rewrite (linearZ, linearD) /=; rewrite !rowE !mul_rV_lin1 /= (mulmxDl, scalemxAl). Qed. HB.instance Definition _ := GRing.isSemilinear.Build R _ _ _ lin_mul_row lin_mul_row_is_semilinear. Lemma mul_vec_lin_row A u : mxvec A *m lin_mul_row u = u *m A. Proof. by rewrite mul_rV_lin1 /= mxvecK. Qed. End LinMulRow. Lemma diag_mxC n (d e : 'rV[R]_n) : diag_mx d *m diag_mx e = diag_mx e *m diag_mx d. Proof. by rewrite !mulmx_diag; congr (diag_mx _); apply/rowP=> i; rewrite !mxE mulrC. Qed. Lemma diag_mx_comm n (d e : 'rV[R]_n) : comm_mx (diag_mx d) (diag_mx e). Proof. exact: diag_mxC. Qed. Lemma scalar_mxC m n a (A : 'M[R]_(m, n)) : A *m a%:M = a%:M *m A. Proof. rewrite -!diag_const_mx mul_mx_diag mul_diag_mx. by apply/matrixP => i j; rewrite !mxE mulrC. Qed. Lemma comm_mx_scalar n a (A : 'M[R]_n) : comm_mx A a%:M. Proof. exact: scalar_mxC. Qed. Lemma comm_scalar_mx n a (A : 'M[R]_n) : comm_mx a%:M A. Proof. exact/comm_mx_sym/comm_mx_scalar. Qed. Lemma mxtrace_mulC m n (A : 'M[R]_(m, n)) B : \tr (A *m B) = \tr (B *m A). Proof. have expand_trM C D: \tr (C *m D) = \sum_i \sum_j C i j * D j i. by apply: eq_bigr => i _; rewrite mxE. rewrite !{}expand_trM exchange_big /=. by do 2!apply: eq_bigr => ? _; apply: mulrC. Qed. Lemma mxvec_dotmul m n (A : 'M[R]_(m, n)) u v : mxvec (u^T *m v) *m (mxvec A)^T = u *m A *m v^T. Proof. transitivity (\sum_i \sum_j (u 0 i * A i j *: row j v^T)). apply/rowP=> i; rewrite {i}ord1 mxE (reindex _ (curry_mxvec_bij _ _)) /=. rewrite pair_bigA summxE; apply: eq_bigr => [[i j]] /= _. by rewrite !mxE !mxvecE mxE big_ord1 mxE mulrAC. rewrite mulmx_sum_row exchange_big; apply: eq_bigr => j _ /=. by rewrite mxE -scaler_suml. Qed. Lemma mul_mx_scalar m n a (A : 'M[R]_(m, n)) : A *m a%:M = a *: A. Proof. by rewrite scalar_mxC mul_scalar_mx. Qed. End ComMatrix. Arguments lin_mulmx {R m n p} A. Arguments lin_mul_row {R m n} u. Arguments diag_mx_comm {R n}. Arguments comm_mx_scalar {R n}. Arguments comm_scalar_mx {R n}. #[global] Hint Resolve comm_mx_scalar comm_scalar_mx : core. Section MatrixAlgebra. Variable R : pzRingType. (* Diagonal matrices *) #[deprecated(since="mathcomp 2.5.0", note="use `linearP` instead")] Fact diag_mx_is_linear n : linear (@diag_mx R n). Proof. exact: linearP. Qed. (* Scalar matrix *) Lemma mulmxN m n p (A : 'M[R]_(m, n)) (B : 'M_(n, p)) : A *m (- B) = - (A *m B). Proof. exact: raddfN. Qed. Lemma mulNmx m n p (A : 'M[R]_(m, n)) (B : 'M_(n, p)) : - A *m B = - (A *m B). Proof. exact: (raddfN (mulmxr _)). Qed. Lemma mulmxBl m n p (A1 A2 : 'M[R]_(m, n)) (B : 'M_(n, p)) : (A1 - A2) *m B = A1 *m B - A2 *m B. Proof. exact: (raddfB (mulmxr _)). Qed. Lemma mulmxBr m n p (A : 'M[R]_(m, n)) (B1 B2 : 'M_(n, p)) : A *m (B1 - B2) = A *m B1 - A *m B2. Proof. exact: raddfB. Qed. (* Partial identity matrix (used in rank decomposition). *) Definition copid_mx {n} r : 'M[R]_n := 1%:M - pid_mx r. Lemma mul_copid_mx_pid m n r : r <= m -> copid_mx r *m pid_mx r = 0 :> 'M_(m, n). Proof. by move=> le_r_m; rewrite mulmxBl mul1mx pid_mx_id ?subrr. Qed. Lemma mul_pid_mx_copid m n r : r <= n -> pid_mx r *m copid_mx r = 0 :> 'M_(m, n). Proof. by move=> le_r_n; rewrite mulmxBr mulmx1 pid_mx_id ?subrr. Qed. Lemma copid_mx_id n r : r <= n -> copid_mx r *m copid_mx r = copid_mx r :> 'M_n. Proof. by move=> le_r_n; rewrite mulmxBl mul1mx mul_pid_mx_copid // oppr0 addr0. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `linearP` instead")] Fact mulmxr_is_linear m n p B : linear (@mulmxr R m n p B). Proof. exact: linearP. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `linearP` instead")] Fact lin_mulmxr_is_linear m n p : linear (@lin_mulmxr R m n p). Proof. exact: linearP. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `scalarP` instead")] Fact mxtrace_is_scalar n : scalar (@mxtrace R n). Proof. exact: scalarP. Qed. (* Determinants and adjugates are defined here, but most of their properties *) (* only hold for matrices over a commutative ring, so their theory is *) (* deferred to that section. *) (* The determinant, in one line with the Leibniz Formula *) Definition determinant n (A : 'M_n) : R := \sum_(s : 'S_n) (-1) ^+ s * \prod_i A i (s i). (* The cofactor of a matrix on the indexes i and j *) Definition cofactor n A (i j : 'I_n) : R := (-1) ^+ (i + j) * determinant (row' i (col' j A)). (* The adjugate matrix : defined as the transpose of the matrix of cofactors *) Fact adjugate_key : unit. Proof. by []. Qed. Definition adjugate n (A : 'M_n) := \matrix[adjugate_key]_(i, j) cofactor A j i. End MatrixAlgebra. Arguments copid_mx {R n}. Prenex Implicits determinant cofactor adjugate. Notation "'\det' A" := (determinant A) : ring_scope. Notation "'\adj' A" := (adjugate A) : ring_scope. (* Parametricity over the algebra structure. *) Section MapRingMatrix. Variables (aR rR : pzRingType) (f : {rmorphism aR -> rR}). Local Notation "A ^f" := (map_mx f A) : ring_scope. Section FixedSize. Variables m n p : nat. Implicit Type A : 'M[aR]_(m, n). Lemma det_map_mx n' (A : 'M_n') : \det A^f = f (\det A). Proof. rewrite rmorph_sum //; apply: eq_bigr => s _. rewrite rmorphM /= rmorph_sign rmorph_prod; congr (_ * _). by apply: eq_bigr => i _; rewrite mxE. Qed. Lemma cofactor_map_mx (A : 'M_n) i j : cofactor A^f i j = f (cofactor A i j). Proof. by rewrite rmorphM /= rmorph_sign -det_map_mx map_row' map_col'. Qed. Lemma map_mx_adj (A : 'M_n) : (\adj A)^f = \adj A^f. Proof. by apply/matrixP=> i j; rewrite !mxE cofactor_map_mx. Qed. End FixedSize. Lemma map_copid_mx n r : (copid_mx r)^f = copid_mx r :> 'M_n. Proof. by rewrite map_mxB map_mx1 map_pid_mx. Qed. End MapRingMatrix. Section CommMx. (***********************************************************************) (************* Commutation property specialized to 'M[R]_n *************) (***********************************************************************) (* See comment on top of NzSemiRing section CommMx above. *) (***********************************************************************) Context {R : pzRingType} {n : nat}. Implicit Types (f g p : 'M[R]_n) (fs : seq 'M[R]_n) (d : 'rV[R]_n) (I : Type). Lemma comm_mxN f g : comm_mx f g -> comm_mx f (- g). Proof. by rewrite /comm_mx mulmxN mulNmx => ->. Qed. Lemma comm_mxN1 f : comm_mx f (- 1%:M). Proof. exact/comm_mxN/comm_mx1. Qed. Lemma comm_mxB f g g' : comm_mx f g -> comm_mx f g' -> comm_mx f (g - g'). Proof. by move=> fg fg'; apply/comm_mxD => //; apply/comm_mxN. Qed. End CommMx. (* Lemmas for matrices with coefficients in a commutative ring *) Section ComMatrix. Variable R : comPzRingType. #[deprecated(since="mathcomp 2.5.0", note="use `linearP` instead")] Fact lin_mulmx_is_linear m n p : linear (@lin_mulmx R m n p). Proof. exact: linearP. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `linearP` instead")] Fact lin_mul_row_is_linear m n : linear (@lin_mul_row R m n). Proof. exact: linearP. Qed. (* The theory of determinants *) Lemma determinant_multilinear n (A B C : 'M[R]_n) i0 b c : row i0 A = b *: row i0 B + c *: row i0 C -> row' i0 B = row' i0 A -> row' i0 C = row' i0 A -> \det A = b * \det B + c * \det C. Proof. rewrite -[_ + _](row_id 0); move/row_eq=> ABC. move/row'_eq=> BA; move/row'_eq=> CA. rewrite !big_distrr -big_split; apply: eq_bigr => s _ /=. rewrite -!(mulrCA (_ ^+s)) -mulrDr; congr (_ * _). rewrite !(bigD1 i0 (_ : predT i0)) //= {}ABC !mxE mulrDl !mulrA. by congr (_ * _ + _ * _); apply: eq_bigr => i i0i; rewrite ?BA ?CA. Qed. Lemma determinant_alternate n (A : 'M[R]_n) i1 i2 : i1 != i2 -> A i1 =1 A i2 -> \det A = 0. Proof. move=> neq_i12 eqA12; pose t := tperm i1 i2. have oddMt s: (t * s)%g = ~~ s :> bool by rewrite odd_permM odd_tperm neq_i12. rewrite [\det A](bigID (@odd_perm _)) /=. apply: canLR (subrK _) _; rewrite add0r -sumrN. rewrite (reindex_inj (mulgI t)); apply: eq_big => //= s. rewrite oddMt => /negPf->; rewrite mulN1r mul1r; congr (- _). rewrite (reindex_perm t); apply: eq_bigr => /= i _. by rewrite permM tpermK /t; case: tpermP => // ->; rewrite eqA12. Qed. Lemma det_tr n (A : 'M[R]_n) : \det A^T = \det A. Proof. rewrite [\det A^T](reindex_inj invg_inj) /=. apply: eq_bigr => s _ /=; rewrite !odd_permV (reindex_perm s) /=. by congr (_ * _); apply: eq_bigr => i _; rewrite mxE permK. Qed. Lemma det_perm n (s : 'S_n) : \det (perm_mx s) = (-1) ^+ s :> R. Proof. rewrite [\det _](bigD1 s) //= big1 => [|i _]; last by rewrite /= !mxE eqxx. rewrite mulr1 big1 ?addr0 => //= t Dst. case: (pickP (fun i => s i != t i)) => [i ist | Est]. by rewrite (bigD1 i) // mulrCA /= !mxE (negPf ist) mul0r. by case/eqP: Dst; apply/permP => i; move/eqP: (Est i). Qed. Lemma det1 n : \det (1%:M : 'M[R]_n) = 1. Proof. by rewrite -perm_mx1 det_perm odd_perm1. Qed. Lemma det_mx00 (A : 'M[R]_0) : \det A = 1. Proof. by rewrite flatmx0 -(flatmx0 1%:M) det1. Qed. Lemma detZ n a (A : 'M[R]_n) : \det (a *: A) = a ^+ n * \det A. Proof. rewrite big_distrr /=; apply: eq_bigr => s _; rewrite mulrCA; congr (_ * _). rewrite -[n in a ^+ n]card_ord -prodr_const -big_split /=. by apply: eq_bigr=> i _; rewrite mxE. Qed. Lemma det0 n' : \det (0 : 'M[R]_n'.+1) = 0. Proof. by rewrite -(scale0r 0) detZ exprS !mul0r. Qed. Lemma det_scalar n a : \det (a%:M : 'M[R]_n) = a ^+ n. Proof. by rewrite -{1}(mulr1 a) -scale_scalar_mx detZ det1 mulr1. Qed. Lemma det_scalar1 a : \det (a%:M : 'M[R]_1) = a. Proof. exact: det_scalar. Qed. Lemma det_mx11 (M : 'M[R]_1) : \det M = M 0 0. Proof. by rewrite {1}[M]mx11_scalar det_scalar. Qed. Lemma det_mulmx n (A B : 'M[R]_n) : \det (A *m B) = \det A * \det B. Proof. rewrite big_distrl /=. pose F := ('I_n ^ n)%type; pose AB s i j := A i j * B j (s i). transitivity (\sum_(f : F) \sum_(s : 'S_n) (-1) ^+ s * \prod_i AB s i (f i)). rewrite exchange_big; apply: eq_bigr => /= s _; rewrite -big_distrr /=. congr (_ * _); rewrite -(bigA_distr_bigA (AB s)) /=. by apply: eq_bigr => x _; rewrite mxE. rewrite (bigID (fun f : F => injectiveb f)) /= addrC big1 ?add0r => [|f Uf]. rewrite (reindex (@pval _)) /=; last first. pose in_Sn := insubd (1%g : 'S_n). by exists in_Sn => /= f Uf; first apply: val_inj; apply: insubdK. apply: eq_big => /= [s | s _]; rewrite ?(valP s) // big_distrr /=. rewrite (reindex_inj (mulgI s)); apply: eq_bigr => t _ /=. rewrite big_split /= [in LHS]mulrA mulrCA mulrA mulrCA mulrA. rewrite -signr_addb odd_permM !pvalE; congr (_ * _); symmetry. by rewrite (reindex_perm s); apply: eq_bigr => i; rewrite permM. transitivity (\det (\matrix_(i, j) B (f i) j) * \prod_i A i (f i)). rewrite mulrC big_distrr /=; apply: eq_bigr => s _. rewrite mulrCA big_split //=; congr (_ * (_ * _)). by apply: eq_bigr => x _; rewrite mxE. case/injectivePn: Uf => i1 [i2 Di12 Ef12]. by rewrite (determinant_alternate Di12) ?simp //= => j; rewrite !mxE Ef12. Qed. Lemma detM n' (A B : 'M[R]_n'.+1) : \det (A * B) = \det A * \det B. Proof. exact: det_mulmx. Qed. (* Laplace expansion lemma *) Lemma expand_cofactor n (A : 'M[R]_n) i j : cofactor A i j = \sum_(s : 'S_n | s i == j) (-1) ^+ s * \prod_(k | i != k) A k (s k). Proof. case: n A i j => [|n] A i0 j0; first by case: i0. rewrite (reindex (lift_perm i0 j0)); last first. pose ulsf i (s : 'S_n.+1) k := odflt k (unlift (s i) (s (lift i k))). have ulsfK i (s : 'S_n.+1) k: lift (s i) (ulsf i s k) = s (lift i k). rewrite /ulsf; have:= neq_lift i k. by rewrite -(can_eq (permK s)) => /unlift_some[] ? ? ->. have inj_ulsf: injective (ulsf i0 _). move=> s; apply: can_inj (ulsf (s i0) s^-1%g) _ => k'. by rewrite {1}/ulsf ulsfK !permK liftK. exists (fun s => perm (inj_ulsf s)) => [s _ | s]. by apply/permP=> k'; rewrite permE /ulsf lift_perm_lift lift_perm_id liftK. move/(s _ =P _) => si0; apply/permP=> k. case: (unliftP i0 k) => [k'|] ->; rewrite ?lift_perm_id //. by rewrite lift_perm_lift -si0 permE ulsfK. rewrite /cofactor big_distrr /=. apply: eq_big => [s | s _]; first by rewrite lift_perm_id eqxx. rewrite -signr_odd mulrA -signr_addb oddD -odd_lift_perm; congr (_ * _). case: (pickP 'I_n) => [k0 _ | n0]; last first. by rewrite !big1 // => [j /unlift_some[i] | i _]; have:= n0 i. rewrite (reindex (lift i0)). by apply: eq_big => [k | k _] /=; rewrite ?neq_lift // !mxE lift_perm_lift. exists (fun k => odflt k0 (unlift i0 k)) => k; first by rewrite liftK. by case/unlift_some=> k' -> ->. Qed. Lemma expand_det_row n (A : 'M[R]_n) i0 : \det A = \sum_j A i0 j * cofactor A i0 j. Proof. rewrite /(\det A) (partition_big (fun s : 'S_n => s i0) predT) //=. apply: eq_bigr => j0 _; rewrite expand_cofactor big_distrr /=. apply: eq_bigr => s /eqP Dsi0. rewrite mulrCA (bigID (pred1 i0)) /= big_pred1_eq Dsi0; congr (_ * (_ * _)). by apply: eq_bigl => i; rewrite eq_sym. Qed. Lemma cofactor_tr n (A : 'M[R]_n) i j : cofactor A^T i j = cofactor A j i. Proof. rewrite /cofactor addnC; congr (_ * _). rewrite -tr_row' -tr_col' det_tr; congr (\det _). by apply/matrixP=> ? ?; rewrite !mxE. Qed. Lemma cofactorZ n a (A : 'M[R]_n) i j : cofactor (a *: A) i j = a ^+ n.-1 * cofactor A i j. Proof. by rewrite {1}/cofactor !linearZ detZ mulrCA mulrA. Qed. Lemma expand_det_col n (A : 'M[R]_n) j0 : \det A = \sum_i (A i j0 * cofactor A i j0). Proof. rewrite -det_tr (expand_det_row _ j0). by under eq_bigr do rewrite cofactor_tr mxE. Qed. Lemma trmx_adj n (A : 'M[R]_n) : (\adj A)^T = \adj A^T. Proof. by apply/matrixP=> i j; rewrite !mxE cofactor_tr. Qed. Lemma adjZ n a (A : 'M[R]_n) : \adj (a *: A) = a^+n.-1 *: \adj A. Proof. by apply/matrixP=> i j; rewrite !mxE cofactorZ. Qed. (* Cramer Rule : adjugate on the left *) Lemma mul_mx_adj n (A : 'M[R]_n) : A *m \adj A = (\det A)%:M. Proof. apply/matrixP=> i1 i2 /[!mxE]; have [->|Di] := eqVneq. rewrite (expand_det_row _ i2) //=. by apply: eq_bigr => j _; congr (_ * _); rewrite mxE. pose B := \matrix_(i, j) (if i == i2 then A i1 j else A i j). have EBi12: B i1 =1 B i2 by move=> j; rewrite /= !mxE eqxx (negPf Di). rewrite -[_ *+ _](determinant_alternate Di EBi12) (expand_det_row _ i2). apply: eq_bigr => j _; rewrite !mxE eqxx; congr (_ * (_ * _)). apply: eq_bigr => s _; congr (_ * _); apply: eq_bigr => i _. by rewrite !mxE eq_sym -if_neg neq_lift. Qed. (* Cramer rule : adjugate on the right *) Lemma mul_adj_mx n (A : 'M[R]_n) : \adj A *m A = (\det A)%:M. Proof. by apply: trmx_inj; rewrite trmx_mul trmx_adj mul_mx_adj det_tr tr_scalar_mx. Qed. Lemma adj1 n : \adj (1%:M) = 1%:M :> 'M[R]_n. Proof. by rewrite -{2}(det1 n) -mul_adj_mx mulmx1. Qed. (* Left inverses are right inverses. *) Lemma mulmx1C n (A B : 'M[R]_n) : A *m B = 1%:M -> B *m A = 1%:M. Proof. move=> AB1; pose A' := \det B *: \adj A. suffices kA: A' *m A = 1%:M by rewrite -[B]mul1mx -kA -(mulmxA A') AB1 mulmx1. by rewrite -scalemxAl mul_adj_mx scale_scalar_mx mulrC -det_mulmx AB1 det1. Qed. Lemma det_ublock n1 n2 Aul (Aur : 'M[R]_(n1, n2)) Adr : \det (block_mx Aul Aur 0 Adr) = \det Aul * \det Adr. Proof. elim: n1 => [|n1 IHn1] in Aul Aur *. have ->: Aul = 1%:M by apply/matrixP=> i []. rewrite det1 mul1r; congr (\det _); apply/matrixP=> i j. by do 2![rewrite !mxE; case: splitP => [[]|k] //=; move/val_inj=> <- {k}]. rewrite (expand_det_col _ (lshift n2 0)) big_split_ord /=. rewrite addrC big1 1?simp => [|i _]; last by rewrite block_mxEdl mxE simp. rewrite (expand_det_col _ 0) big_distrl /=; apply: eq_bigr=> i _. rewrite block_mxEul -!mulrA; do 2!congr (_ * _). by rewrite col'_col_mx !col'Kl raddf0 row'Ku row'_row_mx IHn1. Qed. Lemma det_lblock n1 n2 Aul (Adl : 'M[R]_(n2, n1)) Adr : \det (block_mx Aul 0 Adl Adr) = \det Aul * \det Adr. Proof. by rewrite -det_tr tr_block_mx trmx0 det_ublock !det_tr. Qed. Lemma det_trig n (A : 'M[R]_n) : is_trig_mx A -> \det A = \prod_(i < n) A i i. Proof. elim/trigsqmx_ind => [|k x c B Bt IHB]; first by rewrite ?big_ord0 ?det_mx00. rewrite det_lblock big_ord_recl det_mx11 IHB//; congr (_ * _). by rewrite -[ord0](lshift0 _ 0) block_mxEul. by apply: eq_bigr => i; rewrite -!rshift1 block_mxEdr. Qed. Lemma det_diag n (d : 'rV[R]_n) : \det (diag_mx d) = \prod_i d 0 i. Proof. by rewrite det_trig//; apply: eq_bigr => i; rewrite !mxE eqxx. Qed. End ComMatrix. Arguments lin_mul_row {R m n} u. Arguments lin_mulmx {R m n p} A. HB.instance Definition _ (R : comNzSemiRingType) n := GRing.LSemiAlgebra_isSemiAlgebra.Build R 'M[R]_n.+1 (fun k => scalemxAr k). HB.instance Definition _ (R : comNzRingType) (n' : nat) := GRing.LSemiAlgebra.on 'M[R]_n'.+1. HB.instance Definition _ (R : finComNzRingType) (n' : nat) := [Finite of 'M[R]_n'.+1 by <:]. (* Only tall matrices have inverses. *) Lemma mulmx1_min (R : comNzRingType) m n (A : 'M[R]_(m, n)) B : A *m B = 1%:M -> m <= n. Proof. move=> AB1; rewrite leqNgt; apply/negP=> /subnKC; rewrite addSnnS. move: (_ - _)%N => m' def_m; move: AB1; rewrite -{m}def_m in A B *. rewrite -(vsubmxK A) -(hsubmxK B) mul_col_row scalar_mx_block. case/eq_block_mx=> /mulmx1C BlAu1 AuBr0 _ => /eqP/idPn[]. by rewrite -[_ B]mul1mx -BlAu1 -mulmxA AuBr0 !mulmx0 eq_sym oner_neq0. Qed. (*****************************************************************************) (********************** Matrix unit ring and inverse matrices ****************) (*****************************************************************************) Section MatrixInv. Variables R : comUnitRingType. Section Defs. Variable n : nat. Implicit Type A : 'M[R]_n. Definition unitmx : pred 'M[R]_n := fun A => \det A \is a GRing.unit. Definition invmx A := if A \in unitmx then (\det A)^-1 *: \adj A else A. Lemma unitmxE A : (A \in unitmx) = (\det A \is a GRing.unit). Proof. by []. Qed. Lemma unitmx1 : 1%:M \in unitmx. Proof. by rewrite unitmxE det1 unitr1. Qed. Lemma unitmx_perm s : perm_mx s \in unitmx. Proof. by rewrite unitmxE det_perm unitrX ?unitrN ?unitr1. Qed. Lemma unitmx_tr A : (A^T \in unitmx) = (A \in unitmx). Proof. by rewrite unitmxE det_tr. Qed. Lemma unitmxZ a A : a \is a GRing.unit -> (a *: A \in unitmx) = (A \in unitmx). Proof. by move=> Ua; rewrite !unitmxE detZ unitrM unitrX. Qed. Lemma invmx1 : invmx 1%:M = 1%:M. Proof. by rewrite /invmx det1 invr1 scale1r adj1 if_same. Qed. Lemma invmxZ a A : a *: A \in unitmx -> invmx (a *: A) = a^-1 *: invmx A. Proof. rewrite /invmx !unitmxE detZ unitrM => /andP[Ua U_A]. rewrite Ua U_A adjZ !scalerA invrM {U_A}//=. case: (posnP n) A => [-> | n_gt0] A; first by rewrite flatmx0 [_ *: _]flatmx0. rewrite unitrX_pos // in Ua; rewrite -[_ * _](mulrK Ua) mulrC -!mulrA. by rewrite -exprSr prednK // !mulrA divrK ?unitrX. Qed. Lemma invmx_scalar a : invmx a%:M = a^-1%:M. Proof. case Ua: (a%:M \in unitmx). by rewrite -scalemx1 in Ua *; rewrite invmxZ // invmx1 scalemx1. rewrite /invmx Ua; have [->|n_gt0] := posnP n; first by rewrite ![_%:M]flatmx0. by rewrite unitmxE det_scalar unitrX_pos // in Ua; rewrite invr_out ?Ua. Qed. Lemma mulVmx : {in unitmx, left_inverse 1%:M invmx mulmx}. Proof. by move=> A nsA; rewrite /invmx nsA -scalemxAl mul_adj_mx scale_scalar_mx mulVr. Qed. Lemma mulmxV : {in unitmx, right_inverse 1%:M invmx mulmx}. Proof. by move=> A nsA; rewrite /invmx nsA -scalemxAr mul_mx_adj scale_scalar_mx mulVr. Qed. Lemma mulKmx m : {in unitmx, @left_loop _ 'M_(n, m) invmx mulmx}. Proof. by move=> A uA /= B; rewrite mulmxA mulVmx ?mul1mx. Qed. Lemma mulKVmx m : {in unitmx, @rev_left_loop _ 'M_(n, m) invmx mulmx}. Proof. by move=> A uA /= B; rewrite mulmxA mulmxV ?mul1mx. Qed. Lemma mulmxK m : {in unitmx, @right_loop 'M_(m, n) _ invmx mulmx}. Proof. by move=> A uA /= B; rewrite -mulmxA mulmxV ?mulmx1. Qed. Lemma mulmxKV m : {in unitmx, @rev_right_loop 'M_(m, n) _ invmx mulmx}. Proof. by move=> A uA /= B; rewrite -mulmxA mulVmx ?mulmx1. Qed. Lemma det_inv A : \det (invmx A) = (\det A)^-1. Proof. case uA: (A \in unitmx); last by rewrite /invmx uA invr_out ?negbT. by apply: (mulrI uA); rewrite -det_mulmx mulmxV ?divrr ?det1. Qed. Lemma unitmx_inv A : (invmx A \in unitmx) = (A \in unitmx). Proof. by rewrite !unitmxE det_inv unitrV. Qed. Lemma unitmx_mul A B : (A *m B \in unitmx) = (A \in unitmx) && (B \in unitmx). Proof. by rewrite -unitrM -det_mulmx. Qed. Lemma trmx_inv (A : 'M_n) : (invmx A)^T = invmx (A^T). Proof. by rewrite (fun_if trmx) linearZ /= trmx_adj -unitmx_tr -det_tr. Qed. Lemma invmxK : involutive invmx. Proof. move=> A; case uA : (A \in unitmx); last by rewrite /invmx !uA. by apply: (can_inj (mulKVmx uA)); rewrite mulVmx // mulmxV ?unitmx_inv. Qed. Lemma mulmx1_unit A B : A *m B = 1%:M -> A \in unitmx /\ B \in unitmx. Proof. by move=> AB1; apply/andP; rewrite -unitmx_mul AB1 unitmx1. Qed. Lemma intro_unitmx A B : B *m A = 1%:M /\ A *m B = 1%:M -> unitmx A. Proof. by case=> _ /mulmx1_unit[]. Qed. Lemma invmx_out : {in [predC unitmx], invmx =1 id}. Proof. by move=> A; rewrite inE /= /invmx -if_neg => ->. Qed. End Defs. Variable n' : nat. Local Notation n := n'.+1. HB.instance Definition _ := GRing.NzRing_hasMulInverse.Build 'M[R]_n (@mulVmx n) (@mulmxV n) (@intro_unitmx n) (@invmx_out n). (* Lemmas requiring that the coefficients are in a unit ring *) Lemma detV (A : 'M_n) : \det A^-1 = (\det A)^-1. Proof. exact: det_inv. Qed. Lemma unitr_trmx (A : 'M_n) : (A^T \is a GRing.unit) = (A \is a GRing.unit). Proof. exact: unitmx_tr. Qed. Lemma trmxV (A : 'M_n) : A^-1^T = (A^T)^-1. Proof. exact: trmx_inv. Qed. Lemma perm_mxV (s : 'S_n) : perm_mx s^-1 = (perm_mx s)^-1. Proof. rewrite -[_^-1]mul1r; apply: (canRL (mulmxK (unitmx_perm s))). by rewrite -perm_mxM mulVg perm_mx1. Qed. Lemma is_perm_mxV (A : 'M_n) : is_perm_mx A^-1 = is_perm_mx A. Proof. apply/is_perm_mxP/is_perm_mxP=> [] [s defA]; exists s^-1%g. by rewrite -(invrK A) defA perm_mxV. by rewrite defA perm_mxV. Qed. End MatrixInv. Prenex Implicits unitmx invmx invmxK. Lemma block_diag_mx_unit (R : comUnitRingType) n1 n2 (Aul : 'M[R]_n1) (Adr : 'M[R]_n2) : (block_mx Aul 0 0 Adr \in unitmx) = (Aul \in unitmx) && (Adr \in unitmx). Proof. by rewrite !unitmxE det_ublock unitrM. Qed. Lemma invmx_block_diag (R : comUnitRingType) n1 n2 (Aul : 'M[R]_n1) (Adr : 'M[R]_n2) : block_mx Aul 0 0 Adr \in unitmx -> invmx (block_mx Aul 0 0 Adr) = block_mx (invmx Aul) 0 0 (invmx Adr). Proof. move=> /[dup] Aunit; rewrite block_diag_mx_unit => /andP[Aul_unit Adr_unit]. rewrite -[LHS]mul1mx; apply: (canLR (mulmxK _)) => //. rewrite [RHS](mulmx_block (invmx Aul)) !(mulmx0, mul0mx, add0r, addr0). by rewrite !mulVmx// -?scalar_mx_block. Qed. HB.instance Definition _ (R : countComUnitRingType) (n' : nat) := [Countable of 'M[R]_n'.+1 by <:]. HB.instance Definition _ (n : nat) (R : finComUnitRingType) := [Finite of 'M[R]_n.+1 by <:]. (* Finite inversible matrices and the general linear group. *) Section FinUnitMatrix. Variable n : nat. Definition GLtype (R : finComUnitRingType) := {unit 'M[R]_n.-1.+1}. Coercion GLval R (u : GLtype R) : 'M[R]_n.-1.+1 := let: FinRing.Unit A _ := u in A. End FinUnitMatrix. Bind Scope group_scope with GLtype. Arguments GLtype n%_N R%_type. Arguments GLval {n%_N R} u%_g. Notation "{ ''GL_' n [ R ] }" := (GLtype n R) : type_scope. Notation "{ ''GL_' n ( p ) }" := {'GL_n['F_p]} : type_scope. HB.instance Definition _ (n : nat) (R : finComUnitRingType) := [isSub of {'GL_n[R]} for GLval]. Section GL_unit. Variables (n : nat) (R : finComUnitRingType). HB.instance Definition _ := [Finite of {'GL_n[R]} by <:]. HB.instance Definition _ := FinGroup.on {'GL_n[R]}. Definition GLgroup := [set: {'GL_n[R]}]. Canonical GLgroup_group := Eval hnf in [group of GLgroup]. Implicit Types u v : {'GL_n[R]}. Lemma GL_1E : GLval 1 = 1. Proof. by []. Qed. Lemma GL_VE u : GLval u^-1 = (GLval u)^-1. Proof. by []. Qed. Lemma GL_VxE u : GLval u^-1 = invmx u. Proof. by []. Qed. Lemma GL_ME u v : GLval (u * v) = GLval u * GLval v. Proof. by []. Qed. Lemma GL_MxE u v : GLval (u * v) = u *m v. Proof. by []. Qed. Lemma GL_unit u : GLval u \is a GRing.unit. Proof. exact: valP. Qed. Lemma GL_unitmx u : val u \in unitmx. Proof. exact: GL_unit. Qed. Lemma GL_det u : \det u != 0. Proof. by apply: contraL (GL_unitmx u); rewrite unitmxE => /eqP->; rewrite unitr0. Qed. End GL_unit. Arguments GLgroup n%_N R%_type. Arguments GLgroup_group n%_N R%_type. Notation "''GL_' n [ R ]" := (GLgroup n R) (n at level 2, format "''GL_' n [ R ]") : group_scope. Notation "''GL_' n ( p )" := 'GL_n['F_p] (p at level 10, format "''GL_' n ( p )") : group_scope. Notation "''GL_' n [ R ]" := (GLgroup_group n R) : Group_scope. Notation "''GL_' n ( p )" := (GLgroup_group n 'F_p) : Group_scope. (*****************************************************************************) (********************** Matrices over a domain *******************************) (*****************************************************************************) Section MatrixDomain. Variable R : idomainType. Lemma scalemx_eq0 m n a (A : 'M[R]_(m, n)) : (a *: A == 0) = (a == 0) || (A == 0). Proof. case nz_a: (a == 0) / eqP => [-> | _]; first by rewrite scale0r eqxx. apply/eqP/eqP=> [aA0 | ->]; last exact: scaler0. apply/matrixP=> i j; apply/eqP; move/matrixP/(_ i j)/eqP: aA0. by rewrite !mxE mulf_eq0 nz_a. Qed. Lemma scalemx_inj m n a : a != 0 -> injective ( *:%R a : 'M[R]_(m, n) -> 'M[R]_(m, n)). Proof. move=> nz_a A B eq_aAB; apply: contraNeq nz_a. rewrite -[A == B]subr_eq0 -[a == 0]orbF => /negPf<-. by rewrite -scalemx_eq0 linearB subr_eq0 /= eq_aAB. Qed. Lemma det0P n (A : 'M[R]_n) : reflect (exists2 v : 'rV[R]_n, v != 0 & v *m A = 0) (\det A == 0). Proof. apply: (iffP eqP) => [detA0 | [v n0v vA0]]; last first. apply: contraNeq n0v => nz_detA; rewrite -(inj_eq (scalemx_inj nz_detA)). by rewrite scaler0 -mul_mx_scalar -mul_mx_adj mulmxA vA0 mul0mx. elim: n => [|n IHn] in A detA0 *. by case/idP: (oner_eq0 R); rewrite -detA0 [A]thinmx0 -(thinmx0 1%:M) det1. have [{detA0}A'0 | nzA'] := eqVneq (row 0 (\adj A)) 0; last first. exists (row 0 (\adj A)) => //; rewrite rowE -mulmxA mul_adj_mx detA0. by rewrite mul_mx_scalar scale0r. pose A' := col' 0 A; pose vA := col 0 A. have defA: A = row_mx vA A'. apply/matrixP=> i j /[!mxE]. by case: split_ordP => j' -> /[!(mxE, ord1)]; congr (A i _); apply: val_inj. have{IHn} w_ j : exists w : 'rV_n.+1, [/\ w != 0, w 0 j = 0 & w *m A' = 0]. have [|wj nzwj wjA'0] := IHn (row' j A'). by apply/eqP; move/rowP/(_ j)/eqP: A'0; rewrite !mxE mulf_eq0 signr_eq0. exists (\row_k oapp (wj 0) 0 (unlift j k)). rewrite !mxE unlift_none -wjA'0; split=> //. apply: contraNneq nzwj => w0; apply/eqP/rowP=> k'. by move/rowP/(_ (lift j k')): w0; rewrite !mxE liftK. apply/rowP=> k; rewrite !mxE (bigD1_ord j) //= mxE unlift_none mul0r add0r. by apply: eq_big => //= k'; rewrite !mxE/= liftK. have [w0 [/rV0Pn[j nz_w0j] w00_0 w0A']] := w_ 0; pose a0 := (w0 *m vA) 0 0. have{w_} [wj [nz_wj wj0_0 wjA']] := w_ j; pose aj := (wj *m vA) 0 0. have [aj0 | nz_aj] := eqVneq aj 0. exists wj => //; rewrite defA (@mul_mx_row _ _ _ 1) [_ *m _]mx11_scalar -/aj. by rewrite aj0 raddf0 wjA' row_mx0. exists (aj *: w0 - a0 *: wj). apply: contraNneq nz_aj; move/rowP/(_ j)/eqP; rewrite !mxE wj0_0 mulr0 subr0. by rewrite mulf_eq0 (negPf nz_w0j) orbF. rewrite defA (@mul_mx_row _ _ _ 1) !mulmxBl -!scalemxAl w0A' wjA' !linear0. by rewrite -mul_mx_scalar -mul_scalar_mx -!mx11_scalar subrr addr0 row_mx0. Qed. End MatrixDomain. Arguments det0P {R n A}. (* Parametricity at the field level (mx_is_scalar, unit and inverse are only *) (* mapped at this level). *) Section MapFieldMatrix. Variables (aF : fieldType) (rF : comUnitRingType) (f : {rmorphism aF -> rF}). Local Notation "A ^f" := (map_mx f A) : ring_scope. Lemma map_mx_inj {m n} : injective (map_mx f : 'M_(m, n) -> 'M_(m, n)). Proof. move=> A B eq_AB; apply/matrixP=> i j. by move/matrixP/(_ i j): eq_AB => /[!mxE]; apply: fmorph_inj. Qed. Lemma map_mx_is_scalar n (A : 'M_n) : is_scalar_mx A^f = is_scalar_mx A. Proof. rewrite /is_scalar_mx; case: (insub _) => // i. by rewrite mxE -map_scalar_mx inj_eq //; apply: map_mx_inj. Qed. Lemma map_unitmx n (A : 'M_n) : (A^f \in unitmx) = (A \in unitmx). Proof. by rewrite unitmxE det_map_mx // fmorph_unit // -unitfE. Qed. Lemma map_mx_unit n' (A : 'M_n'.+1) : (A^f \is a GRing.unit) = (A \is a GRing.unit). Proof. exact: map_unitmx. Qed. Lemma map_invmx n (A : 'M_n) : (invmx A)^f = invmx A^f. Proof. rewrite /invmx map_unitmx (fun_if (map_mx f)). by rewrite map_mxZ map_mx_adj det_map_mx fmorphV. Qed. Lemma map_mx_inv n' (A : 'M_n'.+1) : A^-1^f = A^f^-1. Proof. exact: map_invmx. Qed. Lemma map_mx_eq0 m n (A : 'M_(m, n)) : (A^f == 0) = (A == 0). Proof. by rewrite -(inj_eq map_mx_inj) raddf0. Qed. End MapFieldMatrix. Arguments map_mx_inj {aF rF f m n} [A1 A2] eqA12f : rename. (*****************************************************************************) (***************************** LUP decomposition *****************************) (*****************************************************************************) Section CormenLUP. Variable F : fieldType. (* Decomposition of the matrix A to P A = L U with *) (* - P a permutation matrix *) (* - L a unipotent lower triangular matrix *) (* - U an upper triangular matrix *) Fixpoint cormen_lup {n} := match n return let M := 'M[F]_n.+1 in M -> M * M * M with | 0 => fun A => (1, 1, A) | _.+1 => fun A => let k := odflt 0 [pick k | A k 0 != 0] in let A1 : 'M_(1 + _) := xrow 0 k A in let P1 : 'M_(1 + _) := tperm_mx 0 k in let Schur := ((A k 0)^-1 *: dlsubmx A1) *m ursubmx A1 in let: (P2, L2, U2) := cormen_lup (drsubmx A1 - Schur) in let P := block_mx 1 0 0 P2 *m P1 in let L := block_mx 1 0 ((A k 0)^-1 *: (P2 *m dlsubmx A1)) L2 in let U := block_mx (ulsubmx A1) (ursubmx A1) 0 U2 in (P, L, U) end. Lemma cormen_lup_perm n (A : 'M_n.+1) : is_perm_mx (cormen_lup A).1.1. Proof. elim: n => [|n IHn] /= in A *; first exact: is_perm_mx1. set A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/=. rewrite (is_perm_mxMr _ (perm_mx_is_perm _ _)). by case/is_perm_mxP => s ->; apply: lift0_mx_is_perm. Qed. Lemma cormen_lup_correct n (A : 'M_n.+1) : let: (P, L, U) := cormen_lup A in P * A = L * U. Proof. elim: n => [|n IHn] /= in A *; first by rewrite !mul1r. set k := odflt _ _; set A1 : 'M_(1 + _) := xrow _ _ _. set A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P' L' U']] /= IHn. rewrite -mulrA -!mulmxE -xrowE -/A1 /= -[n.+2]/(1 + n.+1)%N -{1}(submxK A1). rewrite !mulmx_block !mul0mx !mulmx0 !add0r !addr0 !mul1mx -{L' U'}[L' *m _]IHn. rewrite -scalemxAl !scalemxAr -!mulmxA addrC -mulrDr {A'}subrK. congr (block_mx _ _ (_ *m _) _). rewrite [_ *: _]mx11_scalar !mxE lshift0 tpermL {}/A1 {}/k. case: pickP => /= [k nzAk0 | no_k]; first by rewrite mulVf ?mulmx1. rewrite (_ : dlsubmx _ = 0) ?mul0mx //; apply/colP=> i. by rewrite !mxE lshift0 (elimNf eqP (no_k _)). Qed. Lemma cormen_lup_detL n (A : 'M_n.+1) : \det (cormen_lup A).1.2 = 1. Proof. elim: n => [|n IHn] /= in A *; first by rewrite det1. set A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= detL. by rewrite (@det_lblock _ 1) det1 mul1r. Qed. Lemma cormen_lup_lower n A (i j : 'I_n.+1) : i <= j -> (cormen_lup A).1.2 i j = (i == j)%:R. Proof. elim: n => [|n IHn] /= in A i j *; first by rewrite [i]ord1 [j]ord1 mxE. set A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= Ll. rewrite !mxE split1; case: unliftP => [i'|] -> /=; rewrite !mxE split1. by case: unliftP => [j'|] -> //; apply: Ll. by case: unliftP => [j'|] ->; rewrite /= mxE. Qed. Lemma cormen_lup_upper n A (i j : 'I_n.+1) : j < i -> (cormen_lup A).2 i j = 0 :> F. Proof. elim: n => [|n IHn] /= in A i j *; first by rewrite [i]ord1. set A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= Uu. rewrite !mxE split1; case: unliftP => [i'|] -> //=; rewrite !mxE split1. by case: unliftP => [j'|] ->; [apply: Uu | rewrite /= mxE]. Qed. End CormenLUP. Section mxOver. Section mxOverType. Context {m n : nat} {T : Type}. Implicit Types (S : {pred T}). Definition mxOver_pred (S : {pred T}) := fun M : 'M[T]_(m, n) => [forall i, [forall j, M i j \in S]]. Arguments mxOver_pred _ _ /. Definition mxOver (S : {pred T}) := [qualify a M | mxOver_pred S M]. Lemma mxOverP {S : {pred T}} {M : 'M[T]__} : reflect (forall i j, M i j \in S) (M \is a mxOver S). Proof. exact/'forall_forallP. Qed. Lemma mxOverS (S1 S2 : {pred T}) : {subset S1 <= S2} -> {subset mxOver S1 <= mxOver S2}. Proof. by move=> sS12 M /mxOverP S1M; apply/mxOverP=> i j; apply/sS12/S1M. Qed. Lemma mxOver_const c S : c \in S -> const_mx c \is a mxOver S. Proof. by move=> cS; apply/mxOverP => i j; rewrite !mxE. Qed. Lemma mxOver_constE c S : (m > 0)%N -> (n > 0)%N -> (const_mx c \is a mxOver S) = (c \in S). Proof. move=> m_gt0 n_gt0; apply/idP/idP; last exact: mxOver_const. by move=> /mxOverP /(_ (Ordinal m_gt0) (Ordinal n_gt0)); rewrite mxE. Qed. End mxOverType. Lemma thinmxOver {n : nat} {T : Type} (M : 'M[T]_(n, 0)) S : M \is a mxOver S. Proof. by apply/mxOverP => ? []. Qed. Lemma flatmxOver {n : nat} {T : Type} (M : 'M[T]_(0, n)) S : M \is a mxOver S. Proof. by apply/mxOverP => - []. Qed. Section mxOverZmodule. Context {M : zmodType} {m n : nat}. Implicit Types (S : {pred M}). Lemma mxOver0 S : 0 \in S -> 0 \is a @mxOver m n _ S. Proof. exact: mxOver_const. Qed. Section mxOverAdd. Variable addS : addrClosed M. Fact mxOver_add_subproof : addr_closed (@mxOver m n _ addS). Proof. split=> [|p q Sp Sq]; first by rewrite mxOver0 // ?rpred0. by apply/mxOverP=> i j; rewrite mxE rpredD // !(mxOverP _). Qed. HB.instance Definition _ := GRing.isAddClosed.Build 'M[M]_(m, n) (mxOver_pred addS) mxOver_add_subproof. End mxOverAdd. Section mxOverOpp. Variable oppS : opprClosed M. Fact mxOver_opp_subproof : oppr_closed (@mxOver m n _ oppS). Proof. by move=> A /mxOverP SA; apply/mxOverP=> i j; rewrite mxE rpredN. Qed. HB.instance Definition _ := GRing.isOppClosed.Build 'M[M]_(m, n) (mxOver_pred oppS) mxOver_opp_subproof. End mxOverOpp. HB.instance Definition _ (zmodS : zmodClosed M) := GRing.OppClosed.on (mxOver_pred zmodS). End mxOverZmodule. Section mxOverRing. Context {R : pzSemiRingType} {m n : nat}. Lemma mxOver_scalar S c : 0 \in S -> c \in S -> c%:M \is a @mxOver n n R S. Proof. by move=> S0 cS; apply/mxOverP => i j; rewrite !mxE; case: eqP. Qed. Lemma mxOver_scalarE S c : (n > 0)%N -> (c%:M \is a @mxOver n n R S) = ((n > 1) ==> (0 \in S)) && (c \in S). Proof. case: n => [|[|k]]//= _. by apply/mxOverP/idP => [/(_ ord0 ord0)|cij i j]; rewrite ?mxE ?ord1. apply/mxOverP/andP => [cij|[S0 cij] i j]; last by rewrite !mxE; case: eqP. by split; [have := cij 0 1|have := cij 0 0]; rewrite !mxE. Qed. Lemma mxOverZ (S : mulrClosed R) : {in S & mxOver S, forall a : R, forall v : 'M[R]_(m, n), a *: v \is a mxOver S}. Proof. by move=> a v aS /mxOverP vS; apply/mxOverP => i j; rewrite !mxE rpredM. Qed. Lemma mxOver_diag (S : {pred R}) k (D : 'rV[R]_k) : 0 \in S -> D \is a mxOver S -> diag_mx D \is a mxOver S. Proof. move=> S0 DS; apply/mxOverP => i j; rewrite !mxE. by case: eqP => //; rewrite (mxOverP DS). Qed. Lemma mxOver_diagE (S : {pred R}) k (D : 'rV[R]_k) : k > 0 -> (diag_mx D \is a mxOver S) = ((k > 1) ==> (0 \in S)) && (D \is a mxOver S). Proof. case: k => [|[|k]]//= in D * => _. by rewrite [diag_mx _]mx11_scalar [D in RHS]mx11_scalar !mxE. apply/idP/andP => [/mxOverP DS|[S0 DS]]; last exact: mxOver_diag. split; first by have /[!mxE] := DS 0 1. by apply/mxOverP => i j; have := DS j j; rewrite ord1 !mxE eqxx. Qed. Lemma mxOverM (S : semiringClosed R) p q r : {in mxOver S & mxOver S, forall u : 'M[R]_(p, q), forall v : 'M[R]_(q, r), u *m v \is a mxOver S}. Proof. move=> M N /mxOverP MS /mxOverP NS; apply/mxOverP => i j. by rewrite !mxE rpred_sum // => k _; rewrite rpredM. Qed. End mxOverRing. Section mxRingOver. Context {R : pzSemiRingType} {n : nat} (S : semiringClosed R). Fact mxOver_mul_subproof : mulr_closed (@mxOver n n _ S). Proof. by split; rewrite ?mxOver_scalar ?rpred0 ?rpred1//; apply: mxOverM. Qed. HB.instance Definition _ := GRing.isMulClosed.Build _ (mxOver_pred S) mxOver_mul_subproof. End mxRingOver. HB.instance Definition _ {R : pzRingType} {n : nat} (S : subringClosed R) := GRing.MulClosed.on (@mxOver_pred n n _ S). End mxOver. Section BlockMatrix. Import tagnat. Context {T : Type} {p q : nat} {p_ : 'I_p -> nat} {q_ : 'I_q -> nat}. Notation sp := (\sum_i p_ i)%N. Notation sq := (\sum_i q_ i)%N. Implicit Type (s : 'I_sp) (t : 'I_sq). Definition mxblock (B_ : forall i j, 'M[T]_(p_ i, q_ j)) := \matrix_(j, k) B_ (sig1 j) (sig1 k) (sig2 j) (sig2 k). Local Notation "\mxblock_ ( i , j ) E" := (mxblock (fun i j => E)) : ring_scope. Definition mxrow m (B_ : forall j, 'M[T]_(m, q_ j)) := \matrix_(j, k) B_ (sig1 k) j (sig2 k). Local Notation "\mxrow_ i E" := (mxrow (fun i => E)) : ring_scope. Definition mxcol n (B_ : forall i, 'M[T]_(p_ i, n)) := \matrix_(j, k) B_ (sig1 j) (sig2 j) k. Local Notation "\mxcol_ i E" := (mxcol (fun i => E)) : ring_scope. Definition submxblock (A : 'M[T]_(sp, sq)) i j := mxsub (Rank i) (Rank j) A. Definition submxrow m (A : 'M[T]_(m, sq)) j := colsub (Rank j) A. Definition submxcol n (A : 'M[T]_(sp, n)) i := rowsub (Rank i) A. Lemma mxblockEh B_ : \mxblock_(i, j) B_ i j = \mxrow_j \mxcol_i B_ i j. Proof. by apply/matrixP => k l; rewrite !mxE. Qed. Lemma mxblockEv B_ : \mxblock_(i, j) B_ i j = \mxcol_i \mxrow_j B_ i j. Proof. by apply/matrixP => k l; rewrite !mxE. Qed. Lemma submxblockEh A i j : submxblock A i j = submxcol (submxrow A j) i. Proof. by apply/matrixP => k l; rewrite !mxE. Qed. Lemma submxblockEv A i j : submxblock A i j = submxrow (submxcol A i) j. Proof. by apply/matrixP => k l; rewrite !mxE. Qed. Lemma mxblockK B_ i j : submxblock (\mxblock_(i, j) B_ i j) i j = B_ i j. Proof. apply/matrixP => k l; rewrite !mxE !Rank2K. by do !case: _ / esym; rewrite !cast_ord_id. Qed. Lemma mxrowK m B_ j : @submxrow m (\mxrow_j B_ j) j = B_ j. Proof. apply/matrixP => k l; rewrite !mxE !Rank2K. by do !case: _ / esym; rewrite !cast_ord_id. Qed. Lemma mxcolK n B_ i : @submxcol n (\mxcol_i B_ i) i = B_ i. Proof. apply/matrixP => k l; rewrite !mxE !Rank2K. by do !case: _ / esym; rewrite !cast_ord_id. Qed. Lemma submxrow_matrix B_ j : submxrow (\mxblock_(i, j) B_ i j) j = \mxcol_i B_ i j. Proof. by rewrite mxblockEh mxrowK. Qed. Lemma submxcol_matrix B_ i : submxcol (\mxblock_(i, j) B_ i j) i = \mxrow_j B_ i j. Proof. by rewrite mxblockEv mxcolK. Qed. Lemma submxblockK A : \mxblock_(i, j) (submxblock A i j) = A. Proof. by apply/matrixP => k l; rewrite !mxE !sig2K. Qed. Lemma submxrowK m (A : 'M[T]_(m, sq)) : \mxrow_j (submxrow A j) = A. Proof. by apply/matrixP => k l; rewrite !mxE !sig2K. Qed. Lemma submxcolK n (A : 'M[T]_(sp, n)) : \mxcol_i (submxcol A i) = A. Proof. by apply/matrixP => k l; rewrite !mxE !sig2K. Qed. Lemma mxblockP A B : (forall i j, submxblock A i j = submxblock B i j) <-> A = B. Proof. split=> [eqAB|->//]; apply/matrixP=> s t; have /matrixP := eqAB (sig1 s) (sig1 t). by move=> /(_ (sig2 s) (sig2 t)); rewrite !mxE !sig2K. Qed. Lemma mxrowP m (A B : 'M_(m, sq)) : (forall j, submxrow A j = submxrow B j) <-> A = B. Proof. split=> [eqAB|->//]; apply/matrixP=> i t; have /matrixP := eqAB (sig1 t). by move=> /(_ i (sig2 t)); rewrite !mxE !sig2K. Qed. Lemma mxcolP n (A B : 'M_(sp, n)) : (forall i, submxcol A i = submxcol B i) <-> A = B. Proof. split=> [eqAB|->//]; apply/matrixP=> s j; have /matrixP := eqAB (sig1 s). by move=> /(_ (sig2 s) j); rewrite !mxE !sig2K. Qed. Lemma eq_mxblockP A_ B_ : (forall i j, A_ i j = B_ i j) <-> (\mxblock_(i, j) A_ i j = \mxblock_(i, j) B_ i j). Proof. split; first by move=> e; apply/mxblockP => i j; rewrite !mxblockK. by move=> + i j => /mxblockP/(_ i j); rewrite !mxblockK. Qed. Lemma eq_mxblock A_ B_ : (forall i j, A_ i j = B_ i j) -> (\mxblock_(i, j) A_ i j = \mxblock_(i, j) B_ i j). Proof. by move=> /eq_mxblockP. Qed. Lemma eq_mxrowP m (A_ B_ : forall j, 'M[T]_(m, q_ j)) : (forall j, A_ j = B_ j) <-> (\mxrow_j A_ j = \mxrow_j B_ j). Proof. split; first by move=> e; apply/mxrowP => j; rewrite !mxrowK. by move=> + j => /mxrowP/(_ j); rewrite !mxrowK. Qed. Lemma eq_mxrow m (A_ B_ : forall j, 'M[T]_(m, q_ j)) : (forall j, A_ j = B_ j) -> (\mxrow_j A_ j = \mxrow_j B_ j). Proof. by move=> /eq_mxrowP. Qed. Lemma eq_mxcolP n (A_ B_ : forall i, 'M[T]_(p_ i, n)) : (forall i, A_ i = B_ i) <-> (\mxcol_i A_ i = \mxcol_i B_ i). Proof. split; first by move=> e; apply/mxcolP => i; rewrite !mxcolK. by move=> + i => /mxcolP/(_ i); rewrite !mxcolK. Qed. Lemma eq_mxcol n (A_ B_ : forall i, 'M[T]_(p_ i, n)) : (forall i, A_ i = B_ i) -> (\mxcol_i A_ i = \mxcol_i B_ i). Proof. by move=> /eq_mxcolP. Qed. Lemma row_mxrow m (B_ : forall j, 'M[T]_(m, q_ j)) i : row i (\mxrow_j B_ j) = \mxrow_j (row i (B_ j)). Proof. by apply/rowP => l; rewrite !mxE. Qed. Lemma col_mxrow m (B_ : forall j, 'M[T]_(m, q_ j)) j : col j (\mxrow_j B_ j) = col (sig2 j) (B_ (sig1 j)). Proof. by apply/colP => l; rewrite !mxE. Qed. Lemma row_mxcol n (B_ : forall i, 'M[T]_(p_ i, n)) i : row i (\mxcol_i B_ i) = row (sig2 i) (B_ (sig1 i)). Proof. by apply/rowP => l; rewrite !mxE. Qed. Lemma col_mxcol n (B_ : forall i, 'M[T]_(p_ i, n)) j : col j (\mxcol_i B_ i) = \mxcol_i (col j (B_ i)). Proof. by apply/colP => l; rewrite !mxE. Qed. Lemma row_mxblock B_ i : row i (\mxblock_(i, j) B_ i j) = \mxrow_j row (sig2 i) (B_ (sig1 i) j). Proof. by apply/rowP => l; rewrite !mxE. Qed. Lemma col_mxblock B_ j : col j (\mxblock_(i, j) B_ i j) = \mxcol_i col (sig2 j) (B_ i (sig1 j)). Proof. by apply/colP => l; rewrite !mxE. Qed. End BlockMatrix. Notation "\mxblock_ ( i < m , j < n ) E" := (mxblock (fun (i : 'I_m) (j : 'I_ n) => E)) (only parsing) : ring_scope. Notation "\mxblock_ ( i , j < n ) E" := (\mxblock_(i < n, j < n) E) (only parsing) : ring_scope. Notation "\mxblock_ ( i , j ) E" := (\mxblock_(i < _, j < _) E) : ring_scope. Notation "\mxrow_ ( j < m ) E" := (mxrow (fun (j : 'I_m) => E)) (only parsing) : ring_scope. Notation "\mxrow_ j E" := (\mxrow_(j < _) E) : ring_scope. Notation "\mxcol_ ( i < m ) E" := (mxcol (fun (i : 'I_m) => E)) (only parsing) : ring_scope. Notation "\mxcol_ i E" := (\mxcol_(i < _) E) : ring_scope. Lemma tr_mxblock {T : Type} {p q : nat} {p_ : 'I_p -> nat} {q_ : 'I_q -> nat} (B_ : forall i j, 'M[T]_(p_ i, q_ j)) : (\mxblock_(i, j) B_ i j)^T = \mxblock_(i, j) (B_ j i)^T. Proof. by apply/matrixP => i j; rewrite !mxE. Qed. Section SquareBlockMatrix. Context {T : Type} {p : nat} {p_ : 'I_p -> nat}. Notation sp := (\sum_i p_ i)%N. Implicit Type (s : 'I_sp). Lemma tr_mxrow n (B_ : forall j, 'M[T]_(n, p_ j)) : (\mxrow_j B_ j)^T = \mxcol_i (B_ i)^T. Proof. by apply/matrixP => i j; rewrite !mxE. Qed. Lemma tr_mxcol n (B_ : forall i, 'M[T]_(p_ i, n)) : (\mxcol_i B_ i)^T = \mxrow_i (B_ i)^T. Proof. by apply/matrixP => i j; rewrite !mxE. Qed. Lemma tr_submxblock (A : 'M[T]_sp) i j : (submxblock A i j)^T = (submxblock A^T j i). Proof. by apply/matrixP => k l; rewrite !mxE. Qed. Lemma tr_submxrow n (A : 'M[T]_(n, sp)) j : (submxrow A j)^T = (submxcol A^T j). Proof. by apply/matrixP => k l; rewrite !mxE. Qed. Lemma tr_submxcol n (A : 'M[T]_(sp, n)) i : (submxcol A i)^T = (submxrow A^T i). Proof. by apply/matrixP => k l; rewrite !mxE. Qed. End SquareBlockMatrix. Section BlockRowRecL. Import tagnat. Context {T : Type} {m : nat} {p_ : 'I_m.+1 -> nat}. Notation sp := (\sum_i p_ i)%N. Lemma mxsize_recl : (p_ ord0 + \sum_i p_ (lift ord0 i) = (\sum_i p_ i))%N. Proof. by rewrite big_ord_recl. Qed. Lemma mxrow_recl n (B_ : forall j, 'M[T]_(n, p_ j)) : \mxrow_j B_ j = castmx (erefl, mxsize_recl) (row_mx (B_ 0) (\mxrow_j B_ (lift ord0 j))). Proof. apply/mxrowP => i; rewrite mxrowK. apply/matrixP => j k; rewrite !(castmxE, mxE)/=. case: splitP => l /=; do [ rewrite [LHS]RankEsum big_mkcond big_ord_recl -big_mkcond/=; rewrite /bump/= -addnA cast_ord_id; under eq_bigl do rewrite add1n -ltn_predRL/=]. case: posnP => i0; last first. by move=> lE; have := ltn_ord l; rewrite /= -lE -ltn_subRL subnn. by rewrite (@val_inj _ _ _ i 0 i0) big_pred0_eq in k * => /val_inj->. case: posnP => i0. rewrite (@val_inj _ _ _ i 0 i0) big_pred0_eq in k l * => kE. by have := ltn_ord k; rewrite /= [val k]kE -ltn_subRL subnn. have i_lt : i.-1 < m by rewrite -subn1 ltn_subLR. set i' := lift ord0 (Ordinal i_lt). have ii' : i = i' by apply/val_inj; rewrite /=/bump/= add1n prednK. have k_lt : k < p_ i' by rewrite -ii'. move=> /addnI; rewrite eqRank => /val_inj/= /[dup] kl<-; rewrite mxE. rewrite Rank2K//; case: _ / esym; rewrite cast_ord_id/=. rewrite -/i'; set j' := Ordinal _; have : k = j' :> nat by []. by move: j'; rewrite -ii' => j' /val_inj->. Qed. End BlockRowRecL. Lemma mxcol_recu {T : Type} {p : nat} {p_ : 'I_p.+1 -> nat} m (B_ : forall j, 'M[T]_(p_ j, m)) : \mxcol_j B_ j = castmx (mxsize_recl, erefl) (col_mx (B_ 0) (\mxcol_j B_ (lift ord0 j))). Proof. by apply: trmx_inj; rewrite trmx_cast tr_col_mx !tr_mxcol mxrow_recl. Qed. Section BlockMatrixRec. Local Notation e := (mxsize_recl, mxsize_recl). Local Notation l0 := (lift ord0). Context {T : Type}. Lemma mxblock_recu {p q : nat} {p_ : 'I_p.+1 -> nat} {q_ : 'I_q -> nat} (B_ : forall i j, 'M[T]_(p_ i, q_ j)) : \mxblock_(i, j) B_ i j = castmx (mxsize_recl, erefl) (col_mx (\mxrow_j B_ ord0 j) (\mxblock_(i, j) B_ (l0 i) j)). Proof. by rewrite !mxblockEv mxcol_recu. Qed. Lemma mxblock_recl {p q : nat} {p_ : 'I_p -> nat} {q_ : 'I_q.+1 -> nat} (B_ : forall i j, 'M[T]_(p_ i, q_ j)) : \mxblock_(i, j) B_ i j = castmx (erefl, mxsize_recl) (row_mx (\mxcol_i B_ i ord0) (\mxblock_(i, j) B_ i (l0 j))). Proof. by rewrite !mxblockEh mxrow_recl. Qed. Lemma mxblock_recul {p q : nat} {p_ : 'I_p.+1 -> nat} {q_ : 'I_q.+1 -> nat} (B_ : forall i j, 'M[T]_(p_ i, q_ j)) : \mxblock_(i, j) B_ i j = castmx e (block_mx (B_ 0 0) (\mxrow_j B_ ord0 (l0 j)) (\mxcol_i B_ (l0 i) ord0) (\mxblock_(i, j) B_ (l0 i) (l0 j))). Proof. rewrite mxblock_recl mxcol_recu mxblock_recu -cast_row_mx -block_mxEh. by rewrite castmx_comp; apply: eq_castmx. Qed. Lemma mxrowEblock {q : nat} {q_ : 'I_q -> nat} m (R_ : forall j, 'M[T]_(m, q_ j)) : (\mxrow_j R_ j) = castmx (big_ord1 _ (fun=> m), erefl) (\mxblock_(i < 1, j < q) R_ j). Proof. rewrite mxblock_recu castmx_comp. apply/matrixP => i j; rewrite !castmxE !mxE/=; case: splitP => //=. by move=> k /val_inj->; rewrite ?cast_ord_id ?mxE//=. by move=> [k klt]; suff: false by []; rewrite big_ord0 in klt. Qed. Lemma mxcolEblock {p : nat} {p_ : 'I_p -> nat} n (C_ : forall i, 'M[T]_(p_ i, n)) : (\mxcol_i C_ i) = castmx (erefl, big_ord1 _ (fun=> n)) (\mxblock_(i < p, j < 1) C_ i). Proof. by apply: trmx_inj; rewrite tr_mxcol mxrowEblock trmx_cast tr_mxblock. Qed. Lemma mxEmxrow m n (A : 'M[T]_(m, n)) : A = castmx (erefl, big_ord1 _ (fun=> n)) (\mxrow__ A). Proof. apply/matrixP => i j; rewrite castmxE !mxE/= cast_ord_id. congr (A i); set j' := cast_ord _ _. suff -> : j' = (tagnat.Rank 0 j) by apply/val_inj; rewrite tagnat.Rank2K. by apply/val_inj; rewrite [RHS]tagnat.RankEsum/= big_pred0_eq add0n. Qed. Lemma mxEmxcol m n (A : 'M[T]_(m, n)) : A = castmx (big_ord1 _ (fun=> m), erefl) (\mxcol__ A). Proof. by apply: trmx_inj; rewrite trmx_cast tr_mxcol [LHS]mxEmxrow. Qed. Lemma mxEmxblock m n (A : 'M[T]_(m, n)) : A = castmx (big_ord1 _ (fun=> m), big_ord1 _ (fun=> n)) (\mxblock_(i < 1, j < 1) A). Proof. by rewrite [LHS]mxEmxrow mxrowEblock castmx_comp; apply: eq_castmx. Qed. End BlockMatrixRec. Section BlockRowNmod. Context {V : nmodType} {q : nat} {q_ : 'I_q -> nat}. Notation sq := (\sum_i q_ i)%N. Implicit Type (s : 'I_sq). Lemma mxrowD m (R_ R'_ : forall j, 'M[V]_(m, q_ j)) : \mxrow_j (R_ j + R'_ j) = \mxrow_j (R_ j) + \mxrow_j (R'_ j). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxrow0 m : \mxrow_j (0 : 'M[V]_(m, q_ j)) = 0. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxrow_const m a : \mxrow_j (const_mx a : 'M[V]_(m, q_ j)) = const_mx a. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxrow_sum (J : finType) m (R_ : forall i j, 'M[V]_(m, q_ j)) (P : {pred J}) : \mxrow_j (\sum_(i | P i) R_ i j) = \sum_(i | P i) \mxrow_j (R_ i j). Proof. apply/matrixP => i j; rewrite !(mxE, summxE). by apply: eq_bigr => l; rewrite !mxE. Qed. Lemma submxrowD m (B B' : 'M[V]_(m, sq)) j : submxrow (B + B') j = submxrow B j + submxrow B' j. Proof. by apply/matrixP => i i'; rewrite !mxE. Qed. Lemma submxrow0 m j : submxrow (0 : 'M[V]_(m, sq)) j = 0. Proof. by apply/matrixP=> i i'; rewrite !mxE. Qed. Lemma submxrow_sum (J : finType) m (R_ : forall i, 'M[V]_(m, sq)) (P : {pred J}) j: submxrow (\sum_(i | P i) R_ i) j = \sum_(i | P i) submxrow (R_ i) j. Proof. apply/matrixP => i i'; rewrite !(mxE, summxE). by apply: eq_bigr => l; rewrite !mxE. Qed. End BlockRowNmod. Section BlockRowZmod. Context {V : zmodType} {q : nat} {q_ : 'I_q -> nat}. Notation sq := (\sum_i q_ i)%N. Implicit Type (s : 'I_sq). Lemma mxrowN m (R_ : forall j, 'M[V]_(m, q_ j)) : \mxrow_j (- R_ j) = - \mxrow_j (R_ j). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxrowB m (R_ R'_ : forall j, 'M[V]_(m, q_ j)) : \mxrow_j (R_ j - R'_ j) = \mxrow_j (R_ j) - \mxrow_j (R'_ j). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma submxrowN m (B : 'M[V]_(m, sq)) j : submxrow (- B) j = - submxrow B j. Proof. by apply/matrixP => i i'; rewrite !mxE. Qed. Lemma submxrowB m (B B' : 'M[V]_(m, sq)) j : submxrow (B - B') j = submxrow B j - submxrow B' j. Proof. by apply/matrixP => i i'; rewrite !mxE. Qed. End BlockRowZmod. Section BlockRowSemiRing. Context {R : pzSemiRingType} {n : nat} {q_ : 'I_n -> nat}. Notation sq := (\sum_i q_ i)%N. Implicit Type (s : 'I_sq). Lemma mul_mxrow m n' (A : 'M[R]_(m, n')) (R_ : forall j, 'M[R]_(n', q_ j)) : A *m \mxrow_j R_ j= \mxrow_j (A *m R_ j). Proof. by apply/matrixP=> i s; rewrite !mxE; under [LHS]eq_bigr do rewrite !mxE. Qed. Lemma mul_submxrow m n' (A : 'M[R]_(m, n')) (B : 'M[R]_(n', sq)) j : A *m submxrow B j= submxrow (A *m B) j. Proof. by apply/matrixP=> i s; rewrite !mxE; under [LHS]eq_bigr do rewrite !mxE. Qed. End BlockRowSemiRing. Section BlockColNmod. Context {V : nmodType} {n : nat} {p_ : 'I_n -> nat}. Notation sp := (\sum_i p_ i)%N. Implicit Type (s : 'I_sp). Lemma mxcolD m (C_ C'_ : forall i, 'M[V]_(p_ i, m)) : \mxcol_i (C_ i + C'_ i) = \mxcol_i (C_ i) + \mxcol_i (C'_ i). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxcol0 m : \mxcol_i (0 : 'M[V]_(p_ i, m)) = 0. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxcol_const m a : \mxcol_j (const_mx a : 'M[V]_(p_ j, m)) = const_mx a. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxcol_sum (I : finType) m (C_ : forall j i, 'M[V]_(p_ i, m)) (P : {pred I}): \mxcol_i (\sum_(j | P j) C_ j i) = \sum_(j | P j) \mxcol_i (C_ j i). Proof. apply/matrixP => i j; rewrite !(mxE, summxE). by apply: eq_bigr => l; rewrite !mxE. Qed. Lemma submxcolD m (B B' : 'M[V]_(sp, m)) i : submxcol (B + B') i = submxcol B i + submxcol B' i. Proof. by apply/matrixP => j j'; rewrite !mxE. Qed. Lemma submxcol0 m i : submxcol (0 : 'M[V]_(sp, m)) i = 0. Proof. by apply/matrixP=> j j'; rewrite !mxE. Qed. Lemma submxcol_sum (I : finType) m (C_ : forall j, 'M[V]_(sp, m)) (P : {pred I}) i : submxcol (\sum_(j | P j) C_ j) i = \sum_(j | P j) submxcol (C_ j) i. Proof. apply/matrixP => j j'; rewrite !(mxE, summxE). by apply: eq_bigr => l; rewrite !mxE. Qed. End BlockColNmod. Section BlockColZmod. Context {V : zmodType} {n : nat} {p_ : 'I_n -> nat}. Notation sp := (\sum_i p_ i)%N. Implicit Type (s : 'I_sp). Lemma mxcolN m (C_ : forall i, 'M[V]_(p_ i, m)) : \mxcol_i (- C_ i) = - \mxcol_i (C_ i). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxcolB m (C_ C'_ : forall i, 'M[V]_(p_ i, m)) : \mxcol_i (C_ i - C'_ i) = \mxcol_i (C_ i) - \mxcol_i (C'_ i). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma submxcolN m (B : 'M[V]_(sp, m)) i : submxcol (- B) i = - submxcol B i. Proof. by apply/matrixP => j j'; rewrite !mxE. Qed. Lemma submxcolB m (B B' : 'M[V]_(sp, m)) i : submxcol (B - B') i = submxcol B i - submxcol B' i. Proof. by apply/matrixP => j j'; rewrite !mxE. Qed. End BlockColZmod. Section BlockColSemiRing. Context {R : pzSemiRingType} {n : nat} {p_ : 'I_n -> nat}. Notation sp := (\sum_i p_ i)%N. Implicit Type (s : 'I_sp). Lemma mxcol_mul n' m (C_ : forall i, 'M[R]_(p_ i, n')) (A : 'M[R]_(n', m)) : \mxcol_i C_ i *m A = \mxcol_i (C_ i *m A). Proof. by apply/matrixP=> i s; rewrite !mxE; under [LHS]eq_bigr do rewrite !mxE. Qed. Lemma submxcol_mul n' m (B : 'M[R]_(sp, n')) (A : 'M[R]_(n', m)) i : submxcol B i *m A = submxcol (B *m A) i. Proof. by apply/matrixP=> j s; rewrite !mxE; under [LHS]eq_bigr do rewrite !mxE. Qed. End BlockColSemiRing. Section BlockMatrixNmod. Context {V : nmodType} {m n : nat}. Context {p_ : 'I_m -> nat} {q_ : 'I_n -> nat}. Notation sp := (\sum_i p_ i)%N. Notation sq := (\sum_i q_ i)%N. Lemma mxblockD (B_ B'_ : forall i j, 'M[V]_(p_ i, q_ j)) : \mxblock_(i, j) (B_ i j + B'_ i j) = \mxblock_(i, j) (B_ i j) + \mxblock_(i, j) (B'_ i j). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxblock0 : \mxblock_(i, j) (0 : 'M[V]_(p_ i, q_ j)) = 0. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxblock_const a : \mxblock_(i, j) (const_mx a : 'M[V]_(p_ i, q_ j)) = const_mx a. Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxblock_sum (I : finType) (B_ : forall k i j, 'M[V]_(p_ i, q_ j)) (P : {pred I}): \mxblock_(i, j) (\sum_(k | P k) B_ k i j) = \sum_(k | P k) \mxblock_(i, j) (B_ k i j). Proof. apply/matrixP => i j; rewrite !(mxE, summxE). by apply: eq_bigr => l; rewrite !mxE. Qed. Lemma submxblockD (B B' : 'M[V]_(sp, sq)) i j : submxblock (B + B') i j = submxblock B i j + submxblock B' i j. Proof. by apply/matrixP => k l; rewrite !mxE. Qed. Lemma submxblock0 i j : submxblock (0 : 'M[V]_(sp, sq)) i j = 0. Proof. by apply/matrixP=> k l; rewrite !mxE. Qed. Lemma submxblock_sum (I : finType) (B_ : forall k, 'M[V]_(sp, sq)) (P : {pred I}) i j : submxblock (\sum_(k | P k) B_ k) i j = \sum_(k | P k) submxblock (B_ k) i j. Proof. apply/matrixP => k l; rewrite !(mxE, summxE). by apply: eq_bigr => p; rewrite !mxE. Qed. End BlockMatrixNmod. Section BlockMatrixZmod. Context {V : zmodType} {m n : nat}. Context {p_ : 'I_m -> nat} {q_ : 'I_n -> nat}. Notation sp := (\sum_i p_ i)%N. Notation sq := (\sum_i q_ i)%N. Lemma mxblockN (B_ : forall i j, 'M[V]_(p_ i, q_ j)) : \mxblock_(i, j) (- B_ i j) = - \mxblock_(i, j) (B_ i j). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma mxblockB (B_ B'_ : forall i j, 'M[V]_(p_ i, q_ j)) : \mxblock_(i, j) (B_ i j - B'_ i j) = \mxblock_(i, j) (B_ i j) - \mxblock_(i, j) (B'_ i j). Proof. by apply/matrixP=> i j; rewrite !mxE. Qed. Lemma submxblockN (B : 'M[V]_(sp, sq)) i j : submxblock (- B) i j = - submxblock B i j. Proof. by apply/matrixP => k l; rewrite !mxE. Qed. Lemma submxblockB (B B' : 'M[V]_(sp, sq)) i j : submxblock (B - B') i j = submxblock B i j - submxblock B' i j. Proof. by apply/matrixP => k l; rewrite !mxE. Qed. End BlockMatrixZmod. Section BlockMatrixSemiRing. Context {R : pzSemiRingType} {p q : nat} {p_ : 'I_p -> nat} {q_ : 'I_q -> nat}. Notation sp := (\sum_i p_ i)%N. Notation sq := (\sum_i q_ i)%N. Lemma mul_mxrow_mxcol m n (R_ : forall j, 'M[R]_(m, p_ j)) (C_ : forall i, 'M[R]_(p_ i, n)) : \mxrow_j R_ j *m \mxcol_i C_ i = \sum_i (R_ i *m C_ i). Proof. apply/matrixP => i j; rewrite !mxE summxE; under [RHS]eq_bigr do rewrite !mxE. rewrite sig_big_dep/= (reindex _ tagnat.sig_bij_on)/=. by apply: eq_bigr=> l _; rewrite !mxE. Qed. Lemma mul_mxcol_mxrow m (C_ : forall i, 'M[R]_(p_ i, m)) (R_ : forall j, 'M[R]_(m, q_ j)) : \mxcol_i C_ i*m \mxrow_j R_ j = \mxblock_(i, j) (C_ i *m R_ j). Proof. apply/mxblockP => i j; rewrite mxblockK. by rewrite submxblockEh -mul_submxrow -submxcol_mul mxcolK mxrowK. Qed. Lemma mul_mxrow_mxblock m (R_ : forall i, 'M[R]_(m, p_ i)) (B_ : forall i j, 'M[R]_(p_ i, q_ j)) : \mxrow_i R_ i *m \mxblock_(i, j) B_ i j = \mxrow_j (\sum_i (R_ i *m B_ i j)). Proof. rewrite mxblockEv mul_mxrow_mxcol mxrow_sum. by apply: eq_bigr => i _; rewrite mul_mxrow. Qed. Lemma mul_mxblock_mxrow m (B_ : forall i j, 'M[R]_(q_ i, p_ j)) (C_ : forall i, 'M[R]_(p_ i, m)) : \mxblock_(i, j) B_ i j *m \mxcol_j C_ j = \mxcol_i (\sum_j (B_ i j *m C_ j)). Proof. rewrite mxblockEh mul_mxrow_mxcol mxcol_sum. by apply: eq_bigr => i _; rewrite mxcol_mul. Qed. End BlockMatrixSemiRing. Lemma mul_mxblock {R : pzSemiRingType} {p q r : nat} {p_ : 'I_p -> nat} {q_ : 'I_q -> nat} {r_ : 'I_r -> nat} (A_ : forall i j, 'M[R]_(p_ i, q_ j)) (B_ : forall j k, 'M_(q_ j, r_ k)) : \mxblock_(i, j) A_ i j *m \mxblock_(j, k) B_ j k = \mxblock_(i, k) \sum_j (A_ i j *m B_ j k). Proof. rewrite mxblockEh mul_mxrow_mxblock mxblockEh; apply: eq_mxrow => i. by under [LHS]eq_bigr do rewrite mxcol_mul; rewrite -mxcol_sum. Qed. Section SquareBlockMatrixNmod. Import Order.TTheory tagnat. Context {V : nmodType} {p : nat} {p_ : 'I_p -> nat}. Notation sp := (\sum_i p_ i)%N. Implicit Type (s : 'I_sp). Lemma is_trig_mxblockP (B_ : forall i j, 'M[V]_(p_ i, p_ j)) : reflect [/\ forall (i j : 'I_p), (i < j)%N -> B_ i j = 0 & forall i, is_trig_mx (B_ i i)] (is_trig_mx (\mxblock_(i, j) B_ i j)). Proof. apply: (iffP is_trig_mxP); last first. move=> [Blt1 /(_ _)/is_trig_mxP Blt2]/= s s'; rewrite !mxE. rewrite -[_ < _]lt_sig ltEsig/= /sig1 /sig2 leEord. case: ltngtP => //= ii'; first by rewrite (Blt1 _ _ ii') mxE. move: (sig s) (sig s') ii' => -[/= i j] [/= i' +] /val_inj ii'. by case: _ / ii' => j'; rewrite tagged_asE => /Blt2->. move=> Btrig; split=> [i i' lti|i]. apply/matrixP => j j'; have := Btrig (Rank _ j) (Rank _ j'). rewrite !mxE !Rank2K; do !case: _ / esym; rewrite !cast_ord_id. rewrite /Rank [_ <= _]lt_rank. by rewrite ltEsig/= leEord ltnW//= (ltn_geF lti)//= => /(_ isT). apply/is_trig_mxP => j j' ltj; have := Btrig (Rank _ j) (Rank _ j'). rewrite !mxE !Rank2K; do! case: _ / esym; rewrite !cast_ord_id. by rewrite [_ <= _]lt_rank ltEsig/= !leEord leqnn/= tagged_asE; apply. Qed. Lemma is_trig_mxblock (B_ : forall i j, 'M[V]_(p_ i, p_ j)) : is_trig_mx (\mxblock_(i, j) B_ i j) = ([forall i : 'I_p, forall j : 'I_p, (i < j)%N ==> (B_ i j == 0)] && [forall i, is_trig_mx (B_ i i)]). Proof. by apply/is_trig_mxblockP/andP => -[] => [/(_ _ _ _)/eqP|] => /'forall_'forall_implyP => [|/(_ _ _ _)/eqP] Blt /forallP. Qed. Lemma is_diag_mxblockP (B_ : forall i j, 'M[V]_(p_ i, p_ j)) : reflect [/\ forall (i j : 'I_p), i != j -> B_ i j = 0 & forall i, is_diag_mx (B_ i i)] (is_diag_mx (\mxblock_(i, j) B_ i j)). Proof. apply: (iffP is_diag_mxP); last first. move=> [Bneq1 /(_ _)/is_diag_mxP Bneq2]/= s s'; rewrite !mxE. rewrite val_eqE -(can_eq sigK) /sig1 /sig2. move: (sig s) (sig s') => -[/= i j] [/= i' j']. rewrite -tag_eqE/= /tag_eq/= negb_and. case: eqVneq => /= [ii'|/Bneq1->]; last by rewrite !mxE. by rewrite -ii' in j' *; rewrite tagged_asE => /Bneq2. move=> Bdiag; split=> [i i' Ni|i]. apply/matrixP => j j'; have := Bdiag (Rank _ j) (Rank _ j'). rewrite !mxE !Rank2K; do !case: _ / esym; rewrite !cast_ord_id. by rewrite eq_Rank negb_and Ni; apply. apply/is_diag_mxP => j j' Nj; have := Bdiag (Rank _ j) (Rank _ j'). rewrite !mxE !Rank2K; do! case: _ / esym; rewrite !cast_ord_id. by rewrite eq_Rank negb_and val_eqE Nj orbT; apply. Qed. Lemma is_diag_mxblock (B_ : forall i j, 'M[V]_(p_ i, p_ j)) : is_diag_mx (\mxblock_(i, j) B_ i j) = ([forall i : 'I_p, forall j : 'I_p, (i != j) ==> (B_ i j == 0)] && [forall i, is_diag_mx (B_ i i)]). Proof. by apply/is_diag_mxblockP/andP => -[] => [/(_ _ _ _)/eqP|] => /'forall_'forall_implyP => [|/(_ _ _ _)/eqP] Blt /forallP. Qed. Definition mxdiag (B_ : forall i, 'M[V]_(p_ i)) : 'M[V]_(\sum_i p_ i) := \mxblock_(j, k) if j == k then conform_mx 0 (B_ j) else 0. Local Notation "\mxdiag_ i E" := (mxdiag (fun i => E)) : ring_scope. Lemma submxblock_diag (B_ : forall i, 'M[V]_(p_ i)) i : submxblock (\mxdiag_i B_ i) i i = B_ i. Proof. by rewrite mxblockK conform_mx_id eqxx. Qed. Lemma eq_mxdiagP (B_ B'_ : forall i, 'M[V]_(p_ i)) : (forall i, B_ i = B'_ i) <-> (\mxdiag_i B_ i = \mxdiag_i B'_ i). Proof. rewrite /mxdiag; split; first by move=> e; apply/eq_mxblockP => i j; rewrite e. by move=> + i => /eq_mxblockP/(_ i i); rewrite eqxx !conform_mx_id. Qed. Lemma eq_mxdiag (B_ B'_ : forall i, 'M[V]_(p_ i)) : (forall i, B_ i = B'_ i) -> (\mxdiag_i B_ i = \mxdiag_i B'_ i). Proof. by move=> /eq_mxdiagP. Qed. Lemma mxdiagD (B_ B'_ : forall i, 'M[V]_(p_ i)) : \mxdiag_i (B_ i + B'_ i) = \mxdiag_i (B_ i) + \mxdiag_i (B'_ i). Proof. rewrite /mxdiag -mxblockD; apply/eq_mxblock => i j. by case: eqVneq => [->|]; rewrite ?conform_mx_id ?addr0. Qed. Lemma mxdiag_sum (I : finType) (B_ : forall k i, 'M[V]_(p_ i)) (P : {pred I}) : \mxdiag_i (\sum_(k | P k) B_ k i) = \sum_(k | P k) \mxdiag_i (B_ k i). Proof. rewrite /mxdiag -mxblock_sum; apply/eq_mxblock => i j. case: eqVneq => [->|]; rewrite ?conform_mx_id//; last by rewrite big1. by apply: eq_bigr => k; rewrite conform_mx_id. Qed. Lemma tr_mxdiag (B_ : forall i, 'M[V]_(p_ i)) : (\mxdiag_i B_ i)^T = \mxdiag_i (B_ i)^T. Proof. rewrite tr_mxblock; apply/eq_mxblock => i j. by case: eqVneq => [->|]; rewrite ?trmx_conform ?trmx0. Qed. Lemma row_mxdiag (B_ : forall i, 'M[V]_(p_ i)) k : let B'_ i := if sig1 k == i then conform_mx 0 (B_ i) else 0 in row k (\mxdiag_ i B_ i) = row (sig2 k) (\mxrow_i B'_ i). Proof. rewrite /= row_mxblock row_mxrow; apply/eq_mxrow => i. by case: eqVneq => // e; congr row; rewrite e. Qed. Lemma col_mxdiag (B_ : forall i, 'M[V]_(p_ i)) k : let B'_ i := if sig1 k == i then conform_mx 0 (B_ i) else 0 in col k (\mxdiag_ i B_ i) = col (sig2 k) (\mxcol_i B'_ i). Proof. by rewrite /= col_mxblock col_mxcol; apply/eq_mxcol => i; rewrite eq_sym. Qed. End SquareBlockMatrixNmod. Notation "\mxdiag_ ( i < n ) E" := (mxdiag (fun i : 'I_n => E)) (only parsing) : ring_scope. Notation "\mxdiag_ i E" := (\mxdiag_(i < _) E) : ring_scope. Section SquareBlockMatrixZmod. Import Order.TTheory tagnat. Context {V : zmodType} {p : nat} {p_ : 'I_p -> nat}. Notation sp := (\sum_i p_ i)%N. Implicit Type (s : 'I_sp). Lemma mxdiagN (B_ : forall i, 'M[V]_(p_ i)) : \mxdiag_i (- B_ i) = - \mxdiag_i (B_ i). Proof. rewrite /mxdiag -mxblockN; apply/eq_mxblock => i j. by case: eqVneq => [->|]; rewrite ?conform_mx_id ?oppr0. Qed. Lemma mxdiagB (B_ B'_ : forall i, 'M[V]_(p_ i)) : \mxdiag_i (B_ i - B'_ i) = \mxdiag_i (B_ i) - \mxdiag_i (B'_ i). Proof. by rewrite mxdiagD mxdiagN. Qed. Lemma mxdiag0 : \mxdiag_i (0 : 'M[V]_(p_ i)) = 0. Proof. by under [LHS]eq_mxdiag do rewrite -[0]subr0; rewrite mxdiagB subrr. Qed. End SquareBlockMatrixZmod. Lemma mxdiag_recl {V : nmodType} {m : nat} {p_ : 'I_m.+1 -> nat} (B_ : forall i, 'M[V]_(p_ i)) : \mxdiag_i B_ i = castmx (mxsize_recl, mxsize_recl) (block_mx (B_ 0) 0 0 (\mxdiag_i B_ (lift ord0 i))). Proof. rewrite /mxdiag mxblock_recul/= !conform_mx_id. by congr (castmx _ (block_mx _ _ _ _)); rewrite ?mxrow0 ?mxcol0. Qed. Section SquareBlockMatrixSemiRing. Import tagnat. Context {R : pzSemiRingType} {p : nat} {p_ : 'I_p -> nat}. Notation sp := (\sum_i p_ i)%N. Implicit Type (s : 'I_sp). Lemma mxtrace_mxblock (B_ : forall i j, 'M[R]_(p_ i, p_ j)) : \tr (\mxblock_(i, j) B_ i j) = \sum_i \tr (B_ i i). Proof. rewrite /mxtrace sig_big_dep (reindex _ sig_bij_on)/=. by apply: eq_bigr => i _; rewrite !mxE. Qed. Lemma mxdiagZ a : \mxdiag_i (a%:M : 'M[R]_(p_ i)) = a%:M. Proof. apply/matrixP => s t; rewrite !mxE -(can_eq sigK) /sig1 /sig2. case: (sig s) (sig t) => [/= i j] [/= i' j']. case: eqP => [<-|ni] in j' *; last by rewrite !mxE; case: eqVneq => // -[]. by rewrite conform_mx_id eq_Tagged/= mxE. Qed. Lemma diag_mxrow (B_ : forall j, 'rV[R]_(p_ j)) : diag_mx (\mxrow_j B_ j) = \mxdiag_j (diag_mx (B_ j)). Proof. apply/matrixP => s s'; rewrite !mxE/= -(can_eq sigK) /sig1 /sig2. case: (sig s) (sig s') => [/= i j] [/= i' j']. rewrite -tag_eqE /tag_eq/=; case: (eqVneq i i') => ii'; rewrite ?mxE//=. by case: _ / ii' in j' *; rewrite tagged_asE/= conform_mx_id mxE. Qed. Lemma mxtrace_mxdiag (B_ : forall i, 'M[R]_(p_ i)) : \tr (\mxdiag_i B_ i) = \sum_i \tr (B_ i). Proof. by rewrite mxtrace_mxblock; apply: eq_bigr => i _; rewrite eqxx/= conform_mx_id. Qed. Lemma mul_mxdiag_mxcol m (D_ : forall i, 'M[R]_(p_ i)) (C_ : forall i, 'M[R]_(p_ i, m)): \mxdiag_i D_ i *m \mxcol_i C_ i = \mxcol_i (D_ i *m C_ i). Proof. rewrite /mxdiag mxblockEh mul_mxrow_mxcol. under [LHS]eq_bigr do rewrite mxcol_mul; rewrite -mxcol_sum. apply/eq_mxcol => i; rewrite (bigD1 i)//= eqxx conform_mx_id big1 ?addr0//. by move=> j; case: eqVneq => //=; rewrite mul0mx. Qed. End SquareBlockMatrixSemiRing. Lemma mul_mxrow_mxdiag {R : pzSemiRingType} {p : nat} {p_ : 'I_p -> nat} m (R_ : forall i, 'M[R]_(m, p_ i)) (D_ : forall i, 'M[R]_(p_ i)) : \mxrow_i R_ i *m \mxdiag_i D_ i = \mxrow_i (R_ i *m D_ i). Proof. apply: trmx_inj; rewrite trmx_mul_rev !tr_mxrow tr_mxdiag mul_mxdiag_mxcol. by apply/ eq_mxcol => i; rewrite trmx_mul_rev. Qed. Lemma mul_mxblock_mxdiag {R : pzSemiRingType} {p q : nat} {p_ : 'I_p -> nat} {q_ : 'I_q -> nat} (B_ : forall i j, 'M[R]_(p_ i, q_ j)) (D_ : forall j, 'M[R]_(q_ j)) : \mxblock_(i, j) B_ i j *m \mxdiag_j D_ j = \mxblock_(i, j) (B_ i j *m D_ j). Proof. by rewrite !mxblockEh mul_mxrow_mxdiag; under eq_mxrow do rewrite mxcol_mul. Qed. Lemma mul_mxdiag_mxblock {R : pzSemiRingType} {p q : nat} {p_ : 'I_p -> nat} {q_ : 'I_q -> nat} (D_ : forall j, 'M[R]_(p_ j)) (B_ : forall i j, 'M[R]_(p_ i, q_ j)): \mxdiag_j D_ j *m \mxblock_(i, j) B_ i j = \mxblock_(i, j) (D_ i *m B_ i j). Proof. by rewrite !mxblockEv mul_mxdiag_mxcol; under eq_mxcol do rewrite mul_mxrow. Qed. Definition Vandermonde (R : pzRingType) (m n : nat) (a : 'rV[R]_n) := \matrix_(i < m, j < n) a 0 j ^+ i. Lemma det_Vandermonde (R : comPzRingType) (n : nat) (a : 'rV[R]_n) : \det (Vandermonde n a) = \prod_(i < n) \prod_(j < n | i < j) (a 0 j - a 0 i). Proof. set V := @Vandermonde R. elim: n => [|n IHn] in a *; first by rewrite det_mx00 big1// => -[] []. pose b : 'rV_n := \row_i a 0 (lift 0 i). pose C : 'M_n := diag_mx (\row_(i < n) (b 0 i - a 0 0)). pose D : 'M_n.+1 := 1 - a 0 0 *: \matrix_(i, j) (i == j.+1 :> nat)%:R. have detD : \det D = 1. rewrite det_trig ?big_ord_recl ?mxE ?mulr0 ?subr0 ?eqxx. by rewrite ?big1 ?mulr1// => i; rewrite !mxE eqxx ltn_eqF// mulr0 subr0. by apply/is_trig_mxP => *; rewrite !mxE ![_ == _]ltn_eqF ?mulr0 ?subr0 ?leqW. suff: D * V _ _ a = block_mx 1 (const_mx 1) 0 (V _ _ b *m C) :> 'M_(1 + n). move=> /(congr1 determinant); rewrite detM detD mul1r => ->. rewrite det_ublock det1 mul1r det_mulmx IHn big_ord_recl mulrC; congr (_ * _). rewrite big_mkcond big_ord_recl/= mul1r det_diag. by under eq_bigr do rewrite !mxE. apply: eq_bigr => i _; under eq_bigr do rewrite !mxE. by rewrite big_mkcond [RHS]big_mkcond big_ord_recl/= mul1r. rewrite mulrBl mul1r -[_ * _]scalemxAl; apply/matrixP => i j; rewrite !mxE. under eq_bigr do rewrite !mxE; case: splitP => [{i}_ -> /[!ord1]|{}i ->]. rewrite !expr0 big1; last by move=> ?; rewrite mul0r. by rewrite ?mulr0 ?subr0 ?mxE; case: splitP => k; rewrite ?ord1 mxE//. under eq_bigr do rewrite eqSS mulr_natl mulrb eq_sym. rewrite -big_mkcond/= big_ord1_eq exprS ifT// ?leqW// -mulrBl !mxE/=. case: split_ordP => [{j}_ -> /[!ord1]|{}j ->]; rewrite ?lshift0 ?rshift1 ?mxE. by rewrite ?subrr ?mul0r//. under eq_bigr do rewrite !mxE mulrnAr mulrb. by rewrite -big_mkcond big_pred1_eq /= mulrC. Qed.
Notation.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Ring.Divisibility.Basic import Mathlib.Data.Ordering.Lemmas import Mathlib.Data.PNat.Basic import Mathlib.SetTheory.Ordinal.Principal import Mathlib.Tactic.NormNum /-! # Ordinal notation Constructive ordinal arithmetic for ordinals below `ε₀`. We define a type `ONote`, with constructors `0 : ONote` and `ONote.oadd e n a` representing `ω ^ e * n + a`. We say that `o` is in Cantor normal form - `ONote.NF o` - if either `o = 0` or `o = ω ^ e * n + a` with `a < ω ^ e` and `a` in Cantor normal form. The type `NONote` is the type of ordinals below `ε₀` in Cantor normal form. Various operations (addition, subtraction, multiplication, exponentiation) are defined on `ONote` and `NONote`. -/ open Ordinal Order -- The generated theorem `ONote.zero.sizeOf_spec` is flagged by `simpNF`, -- and we don't otherwise need it. set_option genSizeOfSpec false in /-- Recursive definition of an ordinal notation. `zero` denotes the ordinal 0, and `oadd e n a` is intended to refer to `ω ^ e * n + a`. For this to be a valid Cantor normal form, we must have the exponents decrease to the right, but we can't state this condition until we've defined `repr`, so we make it a separate definition `NF`. -/ inductive ONote : Type | zero : ONote | oadd : ONote → ℕ+ → ONote → ONote deriving DecidableEq compile_inductive% ONote namespace ONote /-- Notation for 0 -/ instance : Zero ONote := ⟨zero⟩ @[simp] theorem zero_def : zero = 0 := rfl instance : Inhabited ONote := ⟨0⟩ /-- Notation for 1 -/ instance : One ONote := ⟨oadd 0 1 0⟩ /-- Notation for ω -/ def omega : ONote := oadd 1 1 0 /-- The ordinal denoted by a notation -/ noncomputable def repr : ONote → Ordinal.{0} | 0 => 0 | oadd e n a => ω ^ repr e * n + repr a @[simp] theorem repr_zero : repr 0 = 0 := rfl attribute [simp] repr.eq_1 repr.eq_2 /-- Print `ω^s*n`, omitting `s` if `e = 0` or `e = 1`, and omitting `n` if `n = 1` -/ private def toString_aux (e : ONote) (n : ℕ) (s : String) : String := if e = 0 then toString n else (if e = 1 then "ω" else "ω^(" ++ s ++ ")") ++ if n = 1 then "" else "*" ++ toString n /-- Print an ordinal notation -/ def toString : ONote → String | zero => "0" | oadd e n 0 => toString_aux e n (toString e) | oadd e n a => toString_aux e n (toString e) ++ " + " ++ toString a open Lean in /-- Print an ordinal notation -/ def repr' (prec : ℕ) : ONote → Format | zero => "0" | oadd e n a => Repr.addAppParen ("oadd " ++ (repr' max_prec e) ++ " " ++ Nat.repr (n : ℕ) ++ " " ++ (repr' max_prec a)) prec instance : ToString ONote := ⟨toString⟩ instance : Repr ONote where reprPrec o prec := repr' prec o instance : Preorder ONote where le x y := repr x ≤ repr y lt x y := repr x < repr y le_refl _ := @le_refl Ordinal _ _ le_trans _ _ _ := @le_trans Ordinal _ _ _ _ lt_iff_le_not_ge _ _ := @lt_iff_le_not_ge Ordinal _ _ _ theorem lt_def {x y : ONote} : x < y ↔ repr x < repr y := Iff.rfl theorem le_def {x y : ONote} : x ≤ y ↔ repr x ≤ repr y := Iff.rfl instance : WellFoundedRelation ONote := ⟨(· < ·), InvImage.wf repr Ordinal.lt_wf⟩ /-- Convert a `Nat` into an ordinal -/ @[coe] def ofNat : ℕ → ONote | 0 => 0 | Nat.succ n => oadd 0 n.succPNat 0 -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11467): during the port we marked these lemmas with `@[eqns]` -- to emulate the old Lean 3 behaviour. @[simp] theorem ofNat_zero : ofNat 0 = 0 := rfl @[simp] theorem ofNat_succ (n) : ofNat (Nat.succ n) = oadd 0 n.succPNat 0 := rfl instance (priority := low) nat (n : ℕ) : OfNat ONote n where ofNat := ofNat n @[simp 1200] theorem ofNat_one : ofNat 1 = 1 := rfl @[simp] theorem repr_ofNat (n : ℕ) : repr (ofNat n) = n := by cases n <;> simp @[simp] theorem repr_one : repr 1 = (1 : ℕ) := repr_ofNat 1 theorem omega0_le_oadd (e n a) : ω ^ repr e ≤ repr (oadd e n a) := by refine le_trans ?_ (le_add_right _ _) simpa using (Ordinal.mul_le_mul_iff_left <| opow_pos (repr e) omega0_pos).2 (Nat.cast_le.2 n.2) theorem oadd_pos (e n a) : 0 < oadd e n a := @lt_of_lt_of_le _ _ _ (ω ^ repr e) _ (opow_pos (repr e) omega0_pos) (omega0_le_oadd e n a) /-- Comparison of ordinal notations: `ω ^ e₁ * n₁ + a₁` is less than `ω ^ e₂ * n₂ + a₂` when either `e₁ < e₂`, or `e₁ = e₂` and `n₁ < n₂`, or `e₁ = e₂`, `n₁ = n₂`, and `a₁ < a₂`. -/ def cmp : ONote → ONote → Ordering | 0, 0 => Ordering.eq | _, 0 => Ordering.gt | 0, _ => Ordering.lt | _o₁@(oadd e₁ n₁ a₁), _o₂@(oadd e₂ n₂ a₂) => (cmp e₁ e₂).then <| (_root_.cmp (n₁ : ℕ) n₂).then (cmp a₁ a₂) theorem eq_of_cmp_eq : ∀ {o₁ o₂}, cmp o₁ o₂ = Ordering.eq → o₁ = o₂ | 0, 0, _ => rfl | oadd e n a, 0, h => by injection h | 0, oadd e n a, h => by injection h | oadd e₁ n₁ a₁, oadd e₂ n₂ a₂, h => by revert h; simp only [cmp] cases h₁ : cmp e₁ e₂ <;> intro h <;> try cases h obtain rfl := eq_of_cmp_eq h₁ revert h; cases h₂ : _root_.cmp (n₁ : ℕ) n₂ <;> intro h <;> try cases h obtain rfl := eq_of_cmp_eq h rw [_root_.cmp, cmpUsing_eq_eq, not_lt, not_lt, ← le_antisymm_iff] at h₂ obtain rfl := Subtype.eq h₂ simp protected theorem zero_lt_one : (0 : ONote) < 1 := by simp only [lt_def, repr_zero, repr_one, Nat.cast_one, zero_lt_one] /-- `NFBelow o b` says that `o` is a normal form ordinal notation satisfying `repr o < ω ^ b`. -/ inductive NFBelow : ONote → Ordinal.{0} → Prop | zero {b} : NFBelow 0 b | oadd' {e n a eb b} : NFBelow e eb → NFBelow a (repr e) → repr e < b → NFBelow (oadd e n a) b /-- A normal form ordinal notation has the form `ω ^ a₁ * n₁ + ω ^ a₂ * n₂ + ⋯ + ω ^ aₖ * nₖ` where `a₁ > a₂ > ⋯ > aₖ` and all the `aᵢ` are also in normal form. We will essentially only be interested in normal form ordinal notations, but to avoid complicating the algorithms, we define everything over general ordinal notations and only prove correctness with normal form as an invariant. -/ class NF (o : ONote) : Prop where out : Exists (NFBelow o) instance NF.zero : NF 0 := ⟨⟨0, NFBelow.zero⟩⟩ theorem NFBelow.oadd {e n a b} : NF e → NFBelow a (repr e) → repr e < b → NFBelow (oadd e n a) b | ⟨⟨_, h⟩⟩ => NFBelow.oadd' h theorem NFBelow.fst {e n a b} (h : NFBelow (ONote.oadd e n a) b) : NF e := by obtain - | ⟨h₁, h₂, h₃⟩ := h; exact ⟨⟨_, h₁⟩⟩ theorem NF.fst {e n a} : NF (oadd e n a) → NF e | ⟨⟨_, h⟩⟩ => h.fst theorem NFBelow.snd {e n a b} (h : NFBelow (ONote.oadd e n a) b) : NFBelow a (repr e) := by obtain - | ⟨h₁, h₂, h₃⟩ := h; exact h₂ theorem NF.snd' {e n a} : NF (oadd e n a) → NFBelow a (repr e) | ⟨⟨_, h⟩⟩ => h.snd theorem NF.snd {e n a} (h : NF (oadd e n a)) : NF a := ⟨⟨_, h.snd'⟩⟩ theorem NF.oadd {e a} (h₁ : NF e) (n) (h₂ : NFBelow a (repr e)) : NF (oadd e n a) := ⟨⟨_, NFBelow.oadd h₁ h₂ (lt_succ _)⟩⟩ instance NF.oadd_zero (e n) [h : NF e] : NF (ONote.oadd e n 0) := h.oadd _ NFBelow.zero theorem NFBelow.lt {e n a b} (h : NFBelow (ONote.oadd e n a) b) : repr e < b := by obtain - | ⟨h₁, h₂, h₃⟩ := h; exact h₃ theorem NFBelow_zero : ∀ {o}, NFBelow o 0 ↔ o = 0 | 0 => ⟨fun _ => rfl, fun _ => NFBelow.zero⟩ | oadd _ _ _ => ⟨fun h => (not_le_of_gt h.lt).elim (Ordinal.zero_le _), fun e => e.symm ▸ NFBelow.zero⟩ theorem NF.zero_of_zero {e n a} (h : NF (ONote.oadd e n a)) (e0 : e = 0) : a = 0 := by simpa [e0, NFBelow_zero] using h.snd' theorem NFBelow.repr_lt {o b} (h : NFBelow o b) : repr o < ω ^ b := by induction h with | zero => exact opow_pos _ omega0_pos | oadd' _ _ h₃ _ IH => rw [repr] apply ((add_lt_add_iff_left _).2 IH).trans_le rw [← mul_succ] apply (mul_le_mul_left' (succ_le_of_lt (nat_lt_omega0 _)) _).trans rw [← opow_succ] exact opow_le_opow_right omega0_pos (succ_le_of_lt h₃) theorem NFBelow.mono {o b₁ b₂} (bb : b₁ ≤ b₂) (h : NFBelow o b₁) : NFBelow o b₂ := by induction h with | zero => exact zero | oadd' h₁ h₂ h₃ _ _ => constructor; exacts [h₁, h₂, lt_of_lt_of_le h₃ bb] theorem NF.below_of_lt {e n a b} (H : repr e < b) : NF (ONote.oadd e n a) → NFBelow (ONote.oadd e n a) b | ⟨⟨b', h⟩⟩ => by (obtain - | ⟨h₁, h₂, h₃⟩ := h; exact NFBelow.oadd' h₁ h₂ H) theorem NF.below_of_lt' : ∀ {o b}, repr o < ω ^ b → NF o → NFBelow o b | 0, _, _, _ => NFBelow.zero | ONote.oadd _ _ _, _, H, h => h.below_of_lt <| (opow_lt_opow_iff_right one_lt_omega0).1 <| lt_of_le_of_lt (omega0_le_oadd _ _ _) H theorem nfBelow_ofNat : ∀ n, NFBelow (ofNat n) 1 | 0 => NFBelow.zero | Nat.succ _ => NFBelow.oadd NF.zero NFBelow.zero zero_lt_one instance nf_ofNat (n) : NF (ofNat n) := ⟨⟨_, nfBelow_ofNat n⟩⟩ instance nf_one : NF 1 := by rw [← ofNat_one]; infer_instance theorem oadd_lt_oadd_1 {e₁ n₁ o₁ e₂ n₂ o₂} (h₁ : NF (oadd e₁ n₁ o₁)) (h : e₁ < e₂) : oadd e₁ n₁ o₁ < oadd e₂ n₂ o₂ := @lt_of_lt_of_le _ _ (repr (oadd e₁ n₁ o₁)) _ _ (NF.below_of_lt h h₁).repr_lt (omega0_le_oadd e₂ n₂ o₂) theorem oadd_lt_oadd_2 {e o₁ o₂ : ONote} {n₁ n₂ : ℕ+} (h₁ : NF (oadd e n₁ o₁)) (h : (n₁ : ℕ) < n₂) : oadd e n₁ o₁ < oadd e n₂ o₂ := by simp only [lt_def, repr] refine lt_of_lt_of_le ((add_lt_add_iff_left _).2 h₁.snd'.repr_lt) (le_trans ?_ (le_add_right _ _)) rwa [← mul_succ, Ordinal.mul_le_mul_iff_left (opow_pos _ omega0_pos), succ_le_iff, Nat.cast_lt] theorem oadd_lt_oadd_3 {e n a₁ a₂} (h : a₁ < a₂) : oadd e n a₁ < oadd e n a₂ := by rw [lt_def]; unfold repr exact @add_lt_add_left _ _ _ _ (repr a₁) _ h _ theorem cmp_compares : ∀ (a b : ONote) [NF a] [NF b], (cmp a b).Compares a b | 0, 0, _, _ => rfl | oadd _ _ _, 0, _, _ => oadd_pos _ _ _ | 0, oadd _ _ _, _, _ => oadd_pos _ _ _ | o₁@(oadd e₁ n₁ a₁), o₂@(oadd e₂ n₂ a₂), h₁, h₂ => by -- TODO: golf rw [cmp] have IHe := @cmp_compares _ _ h₁.fst h₂.fst simp only [Ordering.Compares, gt_iff_lt] at IHe; revert IHe cases cmp e₁ e₂ case lt => intro IHe; exact oadd_lt_oadd_1 h₁ IHe case gt => intro IHe; exact oadd_lt_oadd_1 h₂ IHe case eq => intro IHe; dsimp at IHe; subst IHe unfold _root_.cmp; cases nh : cmpUsing (· < ·) (n₁ : ℕ) n₂ <;> rw [cmpUsing, ite_eq_iff, not_lt] at nh case lt => rcases nh with nh | nh · exact oadd_lt_oadd_2 h₁ nh.left · rw [ite_eq_iff] at nh; rcases nh.right with nh | nh <;> cases nh <;> contradiction case gt => rcases nh with nh | nh · cases nh; contradiction · obtain ⟨_, nh⟩ := nh rw [ite_eq_iff] at nh; rcases nh with nh | nh · exact oadd_lt_oadd_2 h₂ nh.left · cases nh; contradiction rcases nh with nh | nh · cases nh; contradiction obtain ⟨nhl, nhr⟩ := nh rw [ite_eq_iff] at nhr rcases nhr with nhr | nhr · cases nhr; contradiction obtain rfl := Subtype.eq (nhl.eq_of_not_lt nhr.1) have IHa := @cmp_compares _ _ h₁.snd h₂.snd revert IHa; cases cmp a₁ a₂ <;> intro IHa <;> dsimp at IHa case lt => exact oadd_lt_oadd_3 IHa case gt => exact oadd_lt_oadd_3 IHa subst IHa; exact rfl theorem repr_inj {a b} [NF a] [NF b] : repr a = repr b ↔ a = b := ⟨fun e => match cmp a b, cmp_compares a b with | Ordering.lt, (h : repr a < repr b) => (ne_of_lt h e).elim | Ordering.gt, (h : repr a > repr b)=> (ne_of_gt h e).elim | Ordering.eq, h => h, congr_arg _⟩ theorem NF.of_dvd_omega0_opow {b e n a} (h : NF (ONote.oadd e n a)) (d : ω ^ b ∣ repr (ONote.oadd e n a)) : b ≤ repr e ∧ ω ^ b ∣ repr a := by have := mt repr_inj.1 (fun h => by injection h : ONote.oadd e n a ≠ 0) have L := le_of_not_gt fun l => not_le_of_gt (h.below_of_lt l).repr_lt (le_of_dvd this d) simp only [repr] at d exact ⟨L, (dvd_add_iff <| (opow_dvd_opow _ L).mul_right _).1 d⟩ theorem NF.of_dvd_omega0 {e n a} (h : NF (ONote.oadd e n a)) : ω ∣ repr (ONote.oadd e n a) → repr e ≠ 0 ∧ ω ∣ repr a := by (rw [← opow_one ω, ← one_le_iff_ne_zero]; exact h.of_dvd_omega0_opow) /-- `TopBelow b o` asserts that the largest exponent in `o`, if it exists, is less than `b`. This is an auxiliary definition for decidability of `NF`. -/ def TopBelow (b : ONote) : ONote → Prop | 0 => True | oadd e _ _ => cmp e b = Ordering.lt instance decidableTopBelow : DecidableRel TopBelow := by intro b o cases o <;> delta TopBelow <;> infer_instance theorem nfBelow_iff_topBelow {b} [NF b] : ∀ {o}, NFBelow o (repr b) ↔ NF o ∧ TopBelow b o | 0 => ⟨fun h => ⟨⟨⟨_, h⟩⟩, trivial⟩, fun _ => NFBelow.zero⟩ | oadd _ _ _ => ⟨fun h => ⟨⟨⟨_, h⟩⟩, (@cmp_compares _ b h.fst _).eq_lt.2 h.lt⟩, fun ⟨h₁, h₂⟩ => h₁.below_of_lt <| (@cmp_compares _ b h₁.fst _).eq_lt.1 h₂⟩ instance decidableNF : DecidablePred NF | 0 => isTrue NF.zero | oadd e n a => by have := decidableNF e have := decidableNF a apply decidable_of_iff (NF e ∧ NF a ∧ TopBelow e a) rw [← and_congr_right fun h => @nfBelow_iff_topBelow _ h _] exact ⟨fun ⟨h₁, h₂⟩ => NF.oadd h₁ n h₂, fun h => ⟨h.fst, h.snd'⟩⟩ /-- Auxiliary definition for `add` -/ def addAux (e : ONote) (n : ℕ+) (o : ONote) : ONote := match o with | 0 => oadd e n 0 | o'@(oadd e' n' a') => match cmp e e' with | Ordering.lt => o' | Ordering.eq => oadd e (n + n') a' | Ordering.gt => oadd e n o' /-- Addition of ordinal notations (correct only for normal input) -/ def add : ONote → ONote → ONote | 0, o => o | oadd e n a, o => addAux e n (add a o) instance : Add ONote := ⟨add⟩ @[simp] theorem zero_add (o : ONote) : 0 + o = o := rfl theorem oadd_add (e n a o) : oadd e n a + o = addAux e n (a + o) := rfl /-- Subtraction of ordinal notations (correct only for normal input) -/ def sub : ONote → ONote → ONote | 0, _ => 0 | o, 0 => o | o₁@(oadd e₁ n₁ a₁), oadd e₂ n₂ a₂ => match cmp e₁ e₂ with | Ordering.lt => 0 | Ordering.gt => o₁ | Ordering.eq => match (n₁ : ℕ) - n₂ with | 0 => if n₁ = n₂ then sub a₁ a₂ else 0 | Nat.succ k => oadd e₁ k.succPNat a₁ instance : Sub ONote := ⟨sub⟩ theorem add_nfBelow {b} : ∀ {o₁ o₂}, NFBelow o₁ b → NFBelow o₂ b → NFBelow (o₁ + o₂) b | 0, _, _, h₂ => h₂ | oadd e n a, o, h₁, h₂ => by have h' := add_nfBelow (h₁.snd.mono <| le_of_lt h₁.lt) h₂ simp only [oadd_add]; revert h'; obtain - | ⟨e', n', a'⟩ := a + o <;> intro h' · exact NFBelow.oadd h₁.fst NFBelow.zero h₁.lt have : ((e.cmp e').Compares e e') := @cmp_compares _ _ h₁.fst h'.fst cases h : cmp e e' <;> dsimp [addAux] <;> simp only [h] · exact h' · simp only [h] at this subst e' exact NFBelow.oadd h'.fst h'.snd h'.lt · simp only [h] at this exact NFBelow.oadd h₁.fst (NF.below_of_lt this ⟨⟨_, h'⟩⟩) h₁.lt instance add_nf (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ + o₂) | ⟨⟨b₁, h₁⟩⟩, ⟨⟨b₂, h₂⟩⟩ => ⟨(le_total b₁ b₂).elim (fun h => ⟨b₂, add_nfBelow (h₁.mono h) h₂⟩) fun h => ⟨b₁, add_nfBelow h₁ (h₂.mono h)⟩⟩ @[simp] theorem repr_add : ∀ (o₁ o₂) [NF o₁] [NF o₂], repr (o₁ + o₂) = repr o₁ + repr o₂ | 0, o, _, _ => by simp | oadd e n a, o, h₁, h₂ => by haveI := h₁.snd; have h' := repr_add a o conv_lhs at h' => simp [HAdd.hAdd, Add.add] have nf := ONote.add_nf a o conv at nf => simp [HAdd.hAdd, Add.add] conv in _ + o => simp [HAdd.hAdd, Add.add] rcases h : add a o with - | ⟨e', n', a'⟩ <;> simp only [add, addAux, h'.symm, h, add_assoc, repr] at nf h₁ ⊢ have := h₁.fst; haveI := nf.fst; have ee := cmp_compares e e' cases he : cmp e e' <;> simp only [he, Ordering.compares_gt, Ordering.compares_lt, Ordering.compares_eq, repr, gt_iff_lt, PNat.add_coe, Nat.cast_add] at ee ⊢ · rw [← add_assoc, @add_absorp _ (repr e') (ω ^ repr e' * (n' : ℕ))] · have := (h₁.below_of_lt ee).repr_lt unfold repr at this cases he' : e' <;> simp only [he', zero_def, opow_zero, repr, gt_iff_lt] at this ⊢ <;> exact lt_of_le_of_lt (le_add_right _ _) this · simpa using (Ordinal.mul_le_mul_iff_left <| opow_pos (repr e') omega0_pos).2 (Nat.cast_le.2 n'.pos) · rw [ee, ← add_assoc, ← mul_add] theorem sub_nfBelow : ∀ {o₁ o₂ b}, NFBelow o₁ b → NF o₂ → NFBelow (o₁ - o₂) b | 0, o, b, _, h₂ => by cases o <;> exact NFBelow.zero | oadd _ _ _, 0, _, h₁, _ => h₁ | oadd e₁ n₁ a₁, oadd e₂ n₂ a₂, b, h₁, h₂ => by have h' := sub_nfBelow h₁.snd h₂.snd simp only [HSub.hSub, Sub.sub, sub] at h' ⊢ have := @cmp_compares _ _ h₁.fst h₂.fst cases h : cmp e₁ e₂ · apply NFBelow.zero · rw [Nat.sub_eq] simp only [h, Ordering.compares_eq] at this subst e₂ cases (n₁ : ℕ) - n₂ · by_cases en : n₁ = n₂ <;> simp only [en, ↓reduceIte] · exact h'.mono (le_of_lt h₁.lt) · exact NFBelow.zero · exact NFBelow.oadd h₁.fst h₁.snd h₁.lt · exact h₁ instance sub_nf (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ - o₂) | ⟨⟨b₁, h₁⟩⟩, h₂ => ⟨⟨b₁, sub_nfBelow h₁ h₂⟩⟩ @[simp] theorem repr_sub : ∀ (o₁ o₂) [NF o₁] [NF o₂], repr (o₁ - o₂) = repr o₁ - repr o₂ | 0, o, _, h₂ => by cases o <;> exact (Ordinal.zero_sub _).symm | oadd _ _ _, 0, _, _ => (Ordinal.sub_zero _).symm | oadd e₁ n₁ a₁, oadd e₂ n₂ a₂, h₁, h₂ => by haveI := h₁.snd; haveI := h₂.snd; have h' := repr_sub a₁ a₂ conv_lhs at h' => dsimp [HSub.hSub, Sub.sub, sub] conv_lhs => dsimp only [HSub.hSub, Sub.sub]; dsimp only [sub] have ee := @cmp_compares _ _ h₁.fst h₂.fst cases h : cmp e₁ e₂ <;> simp only [h] at ee · rw [Ordinal.sub_eq_zero_iff_le.2] · rfl exact le_of_lt (oadd_lt_oadd_1 h₁ ee) · change e₁ = e₂ at ee subst e₂ dsimp only cases mn : (n₁ : ℕ) - n₂ <;> dsimp only · by_cases en : n₁ = n₂ · simpa [en] · simp only [en, ite_false] exact (Ordinal.sub_eq_zero_iff_le.2 <| le_of_lt <| oadd_lt_oadd_2 h₁ <| lt_of_le_of_ne (tsub_eq_zero_iff_le.1 mn) (mt PNat.eq en)).symm · simp only [Nat.succPNat, Nat.succ_eq_add_one, repr, PNat.mk_coe, Nat.cast_add, Nat.cast_one, add_one_eq_succ] rw [(tsub_eq_iff_eq_add_of_le <| le_of_lt <| Nat.lt_of_sub_eq_succ mn).1 mn, add_comm, Nat.cast_add, mul_add, add_assoc, add_sub_add_cancel] refine (Ordinal.sub_eq_of_add_eq <| add_absorp h₂.snd'.repr_lt <| le_trans ?_ (le_add_right _ _)).symm exact Ordinal.le_mul_left _ (Nat.cast_lt.2 <| Nat.succ_pos _) · exact (Ordinal.sub_eq_of_add_eq <| add_absorp (h₂.below_of_lt ee).repr_lt <| omega0_le_oadd _ _ _).symm /-- Multiplication of ordinal notations (correct only for normal input) -/ def mul : ONote → ONote → ONote | 0, _ => 0 | _, 0 => 0 | o₁@(oadd e₁ n₁ a₁), oadd e₂ n₂ a₂ => if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else oadd (e₁ + e₂) n₂ (mul o₁ a₂) instance : Mul ONote := ⟨mul⟩ instance : MulZeroClass ONote where mul := (· * ·) zero := 0 zero_mul o := by cases o <;> rfl mul_zero o := by cases o <;> rfl theorem oadd_mul (e₁ n₁ a₁ e₂ n₂ a₂) : oadd e₁ n₁ a₁ * oadd e₂ n₂ a₂ = if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else oadd (e₁ + e₂) n₂ (oadd e₁ n₁ a₁ * a₂) := rfl theorem oadd_mul_nfBelow {e₁ n₁ a₁ b₁} (h₁ : NFBelow (oadd e₁ n₁ a₁) b₁) : ∀ {o₂ b₂}, NFBelow o₂ b₂ → NFBelow (oadd e₁ n₁ a₁ * o₂) (repr e₁ + b₂) | 0, _, _ => NFBelow.zero | oadd e₂ n₂ a₂, b₂, h₂ => by have IH := oadd_mul_nfBelow h₁ h₂.snd by_cases e0 : e₂ = 0 <;> simp only [e0, oadd_mul, ↓reduceIte] · apply NFBelow.oadd h₁.fst h₁.snd simpa using (add_lt_add_iff_left (repr e₁)).2 (lt_of_le_of_lt (Ordinal.zero_le _) h₂.lt) · haveI := h₁.fst haveI := h₂.fst apply NFBelow.oadd · infer_instance · rwa [repr_add] · rw [repr_add, add_lt_add_iff_left] exact h₂.lt instance mul_nf : ∀ (o₁ o₂) [NF o₁] [NF o₂], NF (o₁ * o₂) | 0, o, _, h₂ => by cases o <;> exact NF.zero | oadd _ _ _, _, ⟨⟨_, hb₁⟩⟩, ⟨⟨_, hb₂⟩⟩ => ⟨⟨_, oadd_mul_nfBelow hb₁ hb₂⟩⟩ @[simp] theorem repr_mul : ∀ (o₁ o₂) [NF o₁] [NF o₂], repr (o₁ * o₂) = repr o₁ * repr o₂ | 0, o, _, h₂ => by cases o <;> exact (zero_mul _).symm | oadd _ _ _, 0, _, _ => (mul_zero _).symm | oadd e₁ n₁ a₁, oadd e₂ n₂ a₂, h₁, h₂ => by have IH : repr (mul _ _) = _ := @repr_mul _ _ h₁ h₂.snd conv => lhs simp [(· * ·)] have ao : repr a₁ + ω ^ repr e₁ * (n₁ : ℕ) = ω ^ repr e₁ * (n₁ : ℕ) := by apply add_absorp h₁.snd'.repr_lt simpa using (Ordinal.mul_le_mul_iff_left <| opow_pos _ omega0_pos).2 (Nat.cast_le.2 n₁.2) by_cases e0 : e₂ = 0 · obtain ⟨x, xe⟩ := Nat.exists_eq_succ_of_ne_zero n₂.ne_zero simp only [Mul.mul, mul, e0, ↓reduceIte, repr, PNat.mul_coe, natCast_mul, opow_zero, one_mul] simp only [xe, h₂.zero_of_zero e0, repr, add_zero] rw [natCast_succ x, add_mul_succ _ ao, mul_assoc] · simp only [repr] haveI := h₁.fst haveI := h₂.fst simp only [Mul.mul, mul, e0, ite_false, repr.eq_2, repr_add, opow_add, IH, repr, mul_add] rw [← mul_assoc] congr 2 have := mt repr_inj.1 e0 rw [add_mul_of_isSuccLimit ao (isSuccLimit_opow_left isSuccLimit_omega0 this), mul_assoc, mul_omega0_dvd (Nat.cast_pos'.2 n₁.pos) (nat_lt_omega0 _)] simpa using opow_dvd_opow ω (one_le_iff_ne_zero.2 this) /-- Calculate division and remainder of `o` mod `ω`: `split' o = (a, n)` means `o = ω * a + n`. -/ def split' : ONote → ONote × ℕ | 0 => (0, 0) | oadd e n a => if e = 0 then (0, n) else let (a', m) := split' a (oadd (e - 1) n a', m) /-- Calculate division and remainder of `o` mod `ω`: `split o = (a, n)` means `o = a + n`, where `ω ∣ a`. -/ def split : ONote → ONote × ℕ | 0 => (0, 0) | oadd e n a => if e = 0 then (0, n) else let (a', m) := split a (oadd e n a', m) /-- `scale x o` is the ordinal notation for `ω ^ x * o`. -/ def scale (x : ONote) : ONote → ONote | 0 => 0 | oadd e n a => oadd (x + e) n (scale x a) /-- `mulNat o n` is the ordinal notation for `o * n`. -/ def mulNat : ONote → ℕ → ONote | 0, _ => 0 | _, 0 => 0 | oadd e n a, m + 1 => oadd e (n * m.succPNat) a /-- Auxiliary definition to compute the ordinal notation for the ordinal exponentiation in `opow` -/ def opowAux (e a0 a : ONote) : ℕ → ℕ → ONote | _, 0 => 0 | 0, m + 1 => oadd e m.succPNat 0 | k + 1, m => scale (e + mulNat a0 k) a + (opowAux e a0 a k m) /-- Auxiliary definition to compute the ordinal notation for the ordinal exponentiation in `opow` -/ def opowAux2 (o₂ : ONote) (o₁ : ONote × ℕ) : ONote := match o₁ with | (0, 0) => if o₂ = 0 then 1 else 0 | (0, 1) => 1 | (0, m + 1) => let (b', k) := split' o₂ oadd b' (m.succPNat ^ k) 0 | (a@(oadd a0 _ _), m) => match split o₂ with | (b, 0) => oadd (a0 * b) 1 0 | (b, k + 1) => let eb := a0 * b scale (eb + mulNat a0 k) a + opowAux eb a0 (mulNat a m) k m /-- `opow o₁ o₂` calculates the ordinal notation for the ordinal exponential `o₁ ^ o₂`. -/ def opow (o₁ o₂ : ONote) : ONote := opowAux2 o₂ (split o₁) instance : Pow ONote ONote := ⟨opow⟩ theorem opow_def (o₁ o₂ : ONote) : o₁ ^ o₂ = opowAux2 o₂ (split o₁) := rfl theorem split_eq_scale_split' : ∀ {o o' m} [NF o], split' o = (o', m) → split o = (scale 1 o', m) | 0, o', m, _, p => by injection p; substs o' m; rfl | oadd e n a, o', m, h, p => by by_cases e0 : e = 0 <;> simp only [split', e0, ↓reduceIte, Prod.mk.injEq, split] at p ⊢ · rcases p with ⟨rfl, rfl⟩ exact ⟨rfl, rfl⟩ · revert p rcases h' : split' a with ⟨a', m'⟩ haveI := h.fst haveI := h.snd simp only [split_eq_scale_split' h', and_imp] have : 1 + (e - 1) = e := by refine repr_inj.1 ?_ simp only [repr_add, repr_one, Nat.cast_one, repr_sub] have := mt repr_inj.1 e0 exact Ordinal.add_sub_cancel_of_le <| one_le_iff_ne_zero.2 this intros substs o' m simp [scale, this] theorem nf_repr_split' : ∀ {o o' m} [NF o], split' o = (o', m) → NF o' ∧ repr o = ω * repr o' + m | 0, o', m, _, p => by injection p; substs o' m; simp [NF.zero] | oadd e n a, o', m, h, p => by by_cases e0 : e = 0 <;> simp only [split', e0, ↓reduceIte, Prod.mk.injEq, repr, repr_zero, opow_zero, one_mul] at p ⊢ · rcases p with ⟨rfl, rfl⟩ simp [h.zero_of_zero e0, NF.zero] · revert p rcases h' : split' a with ⟨a', m'⟩ haveI := h.fst haveI := h.snd obtain ⟨IH₁, IH₂⟩ := nf_repr_split' h' simp only [IH₂, and_imp] intros substs o' m have : (ω : Ordinal.{0}) ^ repr e = ω ^ (1 : Ordinal.{0}) * ω ^ (repr e - 1) := by have := mt repr_inj.1 e0 rw [← opow_add, Ordinal.add_sub_cancel_of_le (one_le_iff_ne_zero.2 this)] refine ⟨NF.oadd (by infer_instance) _ ?_, ?_⟩ · simp only [opow_one, repr_sub, repr_one, Nat.cast_one] at this ⊢ refine IH₁.below_of_lt' ((Ordinal.mul_lt_mul_iff_left omega0_pos).1 <| lt_of_le_of_lt (le_add_right _ m') ?_) rw [← this, ← IH₂] exact h.snd'.repr_lt · rw [this] simp [mul_add, mul_assoc, add_assoc] theorem scale_eq_mul (x) [NF x] : ∀ (o) [NF o], scale x o = oadd x 1 0 * o | 0, _ => rfl | oadd e n a, h => by simp only [HMul.hMul]; simp only [scale] haveI := h.snd by_cases e0 : e = 0 · simp_rw [scale_eq_mul] simp [Mul.mul, mul, e0, h.zero_of_zero, show x + 0 = x from repr_inj.1 (by simp)] · simp [e0, Mul.mul, mul, scale_eq_mul, (· * ·)] instance nf_scale (x) [NF x] (o) [NF o] : NF (scale x o) := by rw [scale_eq_mul] infer_instance @[simp] theorem repr_scale (x) [NF x] (o) [NF o] : repr (scale x o) = ω ^ repr x * repr o := by simp only [scale_eq_mul, repr_mul, repr, PNat.one_coe, Nat.cast_one, mul_one, add_zero] theorem nf_repr_split {o o' m} [NF o] (h : split o = (o', m)) : NF o' ∧ repr o = repr o' + m := by rcases e : split' o with ⟨a, n⟩ obtain ⟨s₁, s₂⟩ := nf_repr_split' e rw [split_eq_scale_split' e] at h injection h; substs o' n simp only [repr_scale, repr_one, Nat.cast_one, opow_one, ← s₂, and_true] infer_instance theorem split_dvd {o o' m} [NF o] (h : split o = (o', m)) : ω ∣ repr o' := by rcases e : split' o with ⟨a, n⟩ rw [split_eq_scale_split' e] at h injection h; subst o' cases nf_repr_split' e; simp theorem split_add_lt {o e n a m} [NF o] (h : split o = (oadd e n a, m)) : repr a + m < ω ^ repr e := by obtain ⟨h₁, h₂⟩ := nf_repr_split h obtain ⟨e0, d⟩ := h₁.of_dvd_omega0 (split_dvd h) apply principal_add_omega0_opow _ h₁.snd'.repr_lt (lt_of_lt_of_le (nat_lt_omega0 _) _) simpa using opow_le_opow_right omega0_pos (one_le_iff_ne_zero.2 e0) @[simp] theorem mulNat_eq_mul (n o) : mulNat o n = o * ofNat n := by cases o <;> cases n <;> rfl instance nf_mulNat (o) [NF o] (n) : NF (mulNat o n) := by simpa using ONote.mul_nf o (ofNat n) instance nf_opowAux (e a0 a) [NF e] [NF a0] [NF a] : ∀ k m, NF (opowAux e a0 a k m) := by intro k m unfold opowAux cases m with | zero => cases k <;> exact NF.zero | succ m => cases k with | zero => exact NF.oadd_zero _ _ | succ k => haveI := nf_opowAux e a0 a k simp only [mulNat_eq_mul]; infer_instance instance nf_opow (o₁ o₂) [NF o₁] [NF o₂] : NF (o₁ ^ o₂) := by rcases e₁ : split o₁ with ⟨a, m⟩ have na := (nf_repr_split e₁).1 rcases e₂ : split' o₂ with ⟨b', k⟩ haveI := (nf_repr_split' e₂).1 obtain - | ⟨a0, n, a'⟩ := a · rcases m with - | m · by_cases o₂ = 0 <;> simp only [(· ^ ·), Pow.pow, opow, opowAux2, *] <;> decide · by_cases m = 0 · simp only [(· ^ ·), Pow.pow, opow, opowAux2, *, zero_def] decide · simp only [(· ^ ·), Pow.pow, opow, opowAux2, *] infer_instance · simp only [(· ^ ·), Pow.pow, opow, opowAux2, e₁, split_eq_scale_split' e₂, mulNat_eq_mul] have := na.fst rcases k with - | k · infer_instance · cases k <;> cases m <;> infer_instance theorem scale_opowAux (e a0 a : ONote) [NF e] [NF a0] [NF a] : ∀ k m, repr (opowAux e a0 a k m) = ω ^ repr e * repr (opowAux 0 a0 a k m) | 0, m => by cases m <;> simp [opowAux] | k + 1, m => by by_cases h : m = 0 · simp [h, opowAux] · -- Porting note: rewrote proof rw [opowAux]; swap · assumption rw [opowAux]; swap · assumption rw [repr_add, repr_scale, scale_opowAux _ _ _ k] simp only [repr_add, repr_scale, opow_add, mul_assoc, zero_add, mul_add] theorem repr_opow_aux₁ {e a} [Ne : NF e] [Na : NF a] {a' : Ordinal} (e0 : repr e ≠ 0) (h : a' < (ω : Ordinal.{0}) ^ repr e) (aa : repr a = a') (n : ℕ+) : ((ω : Ordinal.{0}) ^ repr e * (n : ℕ) + a') ^ (ω : Ordinal.{0}) = (ω ^ repr e) ^ (ω : Ordinal.{0}) := by subst aa have No := Ne.oadd n (Na.below_of_lt' h) have := omega0_le_oadd e n a rw [repr] at this refine le_antisymm ?_ (opow_le_opow_left _ this) apply (opow_le_of_isSuccLimit ((opow_pos _ omega0_pos).trans_le this).ne' isSuccLimit_omega0).2 intro b l have := (No.below_of_lt (lt_succ _)).repr_lt rw [repr] at this apply (opow_le_opow_left b <| this.le).trans rw [← opow_mul, ← opow_mul] apply opow_le_opow_right omega0_pos rcases le_or_gt ω (repr e) with h | h · apply (mul_le_mul_left' (le_succ b) _).trans rw [← add_one_eq_succ, add_mul_succ _ (one_add_of_omega0_le h), add_one_eq_succ, succ_le_iff, Ordinal.mul_lt_mul_iff_left (Ordinal.pos_iff_ne_zero.2 e0)] exact isSuccLimit_omega0.succ_lt l · apply (principal_mul_omega0 (isSuccLimit_omega0.succ_lt h) l).le.trans simpa using mul_le_mul_right' (one_le_iff_ne_zero.2 e0) ω section theorem repr_opow_aux₂ {a0 a'} [N0 : NF a0] [Na' : NF a'] (m : ℕ) (d : ω ∣ repr a') (e0 : repr a0 ≠ 0) (h : repr a' + m < (ω ^ repr a0)) (n : ℕ+) (k : ℕ) : let R := repr (opowAux 0 a0 (oadd a0 n a' * ofNat m) k m) (k ≠ 0 → R < ((ω ^ repr a0) ^ succ (k : Ordinal))) ∧ ((ω ^ repr a0) ^ (k : Ordinal)) * ((ω ^ repr a0) * (n : ℕ) + repr a') + R = ((ω ^ repr a0) * (n : ℕ) + repr a' + m) ^ succ (k : Ordinal) := by intro R' haveI No : NF (oadd a0 n a') := N0.oadd n (Na'.below_of_lt' <| lt_of_le_of_lt (le_add_right _ _) h) induction k with | zero => cases m <;> simp [R', opowAux] | succ k IH => -- rename R => R' let R := repr (opowAux 0 a0 (oadd a0 n a' * ofNat m) k m) let ω0 := ω ^ repr a0 let α' := ω0 * n + repr a' change (k ≠ 0 → R < (ω0 ^ succ (k : Ordinal))) ∧ (ω0 ^ (k : Ordinal)) * α' + R = (α' + m) ^ (succ ↑k : Ordinal) at IH have RR : R' = ω0 ^ (k : Ordinal) * (α' * m) + R := by by_cases h : m = 0 · simp only [R, R', h, ONote.ofNat, Nat.cast_zero, ONote.repr, mul_zero, ONote.opowAux, add_zero] · simp only [α', ω0, R, R', ONote.repr_scale, ONote.repr, ONote.mulNat_eq_mul, ONote.opowAux, ONote.repr_ofNat, ONote.repr_mul, ONote.repr_add, Ordinal.opow_mul, ONote.zero_add] have α0 : 0 < α' := by simpa [lt_def, repr] using oadd_pos a0 n a' have ω00 : 0 < ω0 ^ (k : Ordinal) := opow_pos _ (opow_pos _ omega0_pos) have Rl : R < ω ^ (repr a0 * succ ↑k) := by by_cases k0 : k = 0 · simp only [k0, Nat.cast_zero, succ_zero, mul_one, R] refine lt_of_lt_of_le ?_ (opow_le_opow_right omega0_pos (one_le_iff_ne_zero.2 e0)) rcases m with - | m <;> simp [opowAux, omega0_pos] rw [← add_one_eq_succ, ← Nat.cast_succ] apply nat_lt_omega0 · rw [opow_mul] exact IH.1 k0 refine ⟨fun _ => ?_, ?_⟩ · rw [RR, ← opow_mul _ _ (succ k.succ)] have e0 := Ordinal.pos_iff_ne_zero.2 e0 have rr0 : 0 < repr a0 + repr a0 := lt_of_lt_of_le e0 (le_add_left _ _) apply principal_add_omega0_opow · simp only [Nat.succ_eq_add_one, Nat.cast_add, Nat.cast_one, add_one_eq_succ, opow_mul, opow_succ, mul_assoc] rw [Ordinal.mul_lt_mul_iff_left ω00, ← Ordinal.opow_add] have : _ < ω ^ (repr a0 + repr a0) := (No.below_of_lt ?_).repr_lt · exact mul_lt_omega0_opow rr0 this (nat_lt_omega0 _) · simpa using (add_lt_add_iff_left (repr a0)).2 e0 · exact lt_of_lt_of_le Rl (opow_le_opow_right omega0_pos <| mul_le_mul_left' (succ_le_succ_iff.2 (Nat.cast_le.2 (le_of_lt k.lt_succ_self))) _) calc (ω0 ^ (k.succ : Ordinal)) * α' + R' _ = (ω0 ^ succ (k : Ordinal)) * α' + ((ω0 ^ (k : Ordinal)) * α' * m + R) := by rw [natCast_succ, RR, ← mul_assoc] _ = ((ω0 ^ (k : Ordinal)) * α' + R) * α' + ((ω0 ^ (k : Ordinal)) * α' + R) * m := ?_ _ = (α' + m) ^ succ (k.succ : Ordinal) := by rw [← mul_add, natCast_succ, opow_succ, IH.2] congr 1 · have αd : ω ∣ α' := dvd_add (dvd_mul_of_dvd_left (by simpa using opow_dvd_opow ω (one_le_iff_ne_zero.2 e0)) _) d rw [mul_add (ω0 ^ (k : Ordinal)), add_assoc, ← mul_assoc, ← opow_succ, add_mul_of_isSuccLimit _ (isSuccLimit_iff_omega0_dvd.2 ⟨ne_of_gt α0, αd⟩), mul_assoc, @mul_omega0_dvd n (Nat.cast_pos'.2 n.pos) (nat_lt_omega0 _) _ αd] apply @add_absorp _ (repr a0 * succ ↑k) · refine principal_add_omega0_opow _ ?_ Rl rw [opow_mul, opow_succ, Ordinal.mul_lt_mul_iff_left ω00] exact No.snd'.repr_lt · have := mul_le_mul_left' (one_le_iff_pos.2 <| Nat.cast_pos'.2 n.pos) (ω0 ^ succ (k : Ordinal)) rw [opow_mul] simpa [-opow_succ] · cases m · have : R = 0 := by cases k <;> simp [R, opowAux] simp [this] · rw [natCast_succ, add_mul_succ] apply add_absorp Rl rw [opow_mul, opow_succ] apply mul_le_mul_left' simpa [repr] using omega0_le_oadd a0 n a' end theorem repr_opow (o₁ o₂) [NF o₁] [NF o₂] : repr (o₁ ^ o₂) = repr o₁ ^ repr o₂ := by rcases e₁ : split o₁ with ⟨a, m⟩ obtain ⟨N₁, r₁⟩ := nf_repr_split e₁ obtain - | ⟨a0, n, a'⟩ := a · rcases m with - | m · by_cases h : o₂ = 0 <;> simp [opow_def, opowAux2, e₁, h, r₁] have := mt repr_inj.1 h rw [zero_opow this] · rcases e₂ : split' o₂ with ⟨b', k⟩ obtain ⟨_, r₂⟩ := nf_repr_split' e₂ by_cases h : m = 0 · simp [opowAux2, opow_def, e₁, h, r₁, r₂] simp only [opow_def, opowAux2, e₁, r₁, e₂, r₂, repr, Nat.cast_succ, _root_.zero_add, add_zero] rw [opow_add, opow_mul, opow_omega0, add_one_eq_succ] · simp · simpa [Nat.one_le_iff_ne_zero] · rw [← Nat.cast_succ, lt_omega0] exact ⟨_, rfl⟩ · haveI := N₁.fst haveI := N₁.snd obtain ⟨a00, ad⟩ := N₁.of_dvd_omega0 (split_dvd e₁) have al := split_add_lt e₁ have aa : repr (a' + ofNat m) = repr a' + m := by simp only [ONote.repr_ofNat, ONote.repr_add] rcases e₂ : split' o₂ with ⟨b', k⟩ obtain ⟨_, r₂⟩ := nf_repr_split' e₂ simp only [opow_def, e₁, r₁, split_eq_scale_split' e₂, opowAux2, repr] rcases k with - | k · simp [r₂, opow_mul, repr_opow_aux₁ a00 al aa, add_assoc] · simp [r₂, opow_add, opow_mul, mul_assoc, add_assoc] rw [repr_opow_aux₁ a00 al aa, scale_opowAux] simp only [repr_mul, repr_scale, repr, opow_zero, PNat.val_ofNat, Nat.cast_one, mul_one, add_zero, opow_one, opow_mul] rw [← mul_add, ← add_assoc ((ω : Ordinal.{0}) ^ repr a0 * (n : ℕ))] congr 1 rw [← pow_succ, ← opow_natCast, ← opow_natCast] exact (repr_opow_aux₂ _ ad a00 al _ _).2 /-- Given an ordinal, returns: * `inl none` for `0` * `inl (some a)` for `a + 1` * `inr f` for a limit ordinal `a`, where `f i` is a sequence converging to `a` -/ def fundamentalSequence : ONote → (Option ONote) ⊕ (ℕ → ONote) | zero => Sum.inl none | oadd a m b => match fundamentalSequence b with | Sum.inr f => Sum.inr fun i => oadd a m (f i) | Sum.inl (some b') => Sum.inl (some (oadd a m b')) | Sum.inl none => match fundamentalSequence a, m.natPred with | Sum.inl none, 0 => Sum.inl (some zero) | Sum.inl none, m + 1 => Sum.inl (some (oadd zero m.succPNat zero)) | Sum.inl (some a'), 0 => Sum.inr fun i => oadd a' i.succPNat zero | Sum.inl (some a'), m + 1 => Sum.inr fun i => oadd a m.succPNat (oadd a' i.succPNat zero) | Sum.inr f, 0 => Sum.inr fun i => oadd (f i) 1 zero | Sum.inr f, m + 1 => Sum.inr fun i => oadd a m.succPNat (oadd (f i) 1 zero) private theorem exists_lt_add {α} [hα : Nonempty α] {o : Ordinal} {f : α → Ordinal} (H : ∀ ⦃a⦄, a < o → ∃ i, a < f i) {b : Ordinal} ⦃a⦄ (h : a < b + o) : ∃ i, a < b + f i := by rcases lt_or_ge a b with h | h' · obtain ⟨i⟩ := id hα exact ⟨i, h.trans_le (le_add_right _ _)⟩ · rw [← Ordinal.add_sub_cancel_of_le h', add_lt_add_iff_left] at h refine (H h).imp fun i H => ?_ rwa [← Ordinal.add_sub_cancel_of_le h', add_lt_add_iff_left] private theorem exists_lt_mul_omega0' {o : Ordinal} ⦃a⦄ (h : a < o * ω) : ∃ i : ℕ, a < o * ↑i + o := by obtain ⟨i, hi, h'⟩ := (lt_mul_iff_of_isSuccLimit isSuccLimit_omega0).1 h obtain ⟨i, rfl⟩ := lt_omega0.1 hi exact ⟨i, h'.trans_le (le_add_right _ _)⟩ private theorem exists_lt_omega0_opow' {α} {o b : Ordinal} (hb : 1 < b) (ho : IsSuccLimit o) {f : α → Ordinal} (H : ∀ ⦃a⦄, a < o → ∃ i, a < f i) ⦃a⦄ (h : a < b ^ o) : ∃ i, a < b ^ f i := by obtain ⟨d, hd, h'⟩ := (lt_opow_of_isSuccLimit (zero_lt_one.trans hb).ne' ho).1 h exact (H hd).imp fun i hi => h'.trans <| (opow_lt_opow_iff_right hb).2 hi /-- The property satisfied by `fundamentalSequence o`: * `inl none` means `o = 0` * `inl (some a)` means `o = succ a` * `inr f` means `o` is a limit ordinal and `f` is a strictly increasing sequence which converges to `o` -/ def FundamentalSequenceProp (o : ONote) : (Option ONote) ⊕ (ℕ → ONote) → Prop | Sum.inl none => o = 0 | Sum.inl (some a) => o.repr = succ a.repr ∧ (o.NF → a.NF) | Sum.inr f => IsSuccLimit o.repr ∧ (∀ i, f i < f (i + 1) ∧ f i < o ∧ (o.NF → (f i).NF)) ∧ ∀ a, a < o.repr → ∃ i, a < (f i).repr theorem fundamentalSequenceProp_inl_none (o) : FundamentalSequenceProp o (Sum.inl none) ↔ o = 0 := Iff.rfl theorem fundamentalSequenceProp_inl_some (o a) : FundamentalSequenceProp o (Sum.inl (some a)) ↔ o.repr = succ a.repr ∧ (o.NF → a.NF) := Iff.rfl theorem fundamentalSequenceProp_inr (o f) : FundamentalSequenceProp o (Sum.inr f) ↔ IsSuccLimit o.repr ∧ (∀ i, f i < f (i + 1) ∧ f i < o ∧ (o.NF → (f i).NF)) ∧ ∀ a, a < o.repr → ∃ i, a < (f i).repr := Iff.rfl theorem fundamentalSequence_has_prop (o) : FundamentalSequenceProp o (fundamentalSequence o) := by induction o with | zero => exact rfl | oadd a m b iha ihb rw [fundamentalSequence] rcases e : b.fundamentalSequence with (⟨_ | b'⟩ | f) <;> simp only [FundamentalSequenceProp] <;> rw [e, FundamentalSequenceProp] at ihb · rcases e : a.fundamentalSequence with (⟨_ | a'⟩ | f) <;> rcases e' : m.natPred with - | m' <;> simp only <;> rw [e, FundamentalSequenceProp] at iha <;> (try rw [show m = 1 by have := PNat.natPred_add_one m; rw [e'] at this; exact PNat.coe_inj.1 this.symm]) <;> (try rw [show m = (m' + 1).succPNat by rw [← e', ← PNat.coe_inj, Nat.succPNat_coe, ← Nat.add_one, PNat.natPred_add_one]]) <;> simp only [repr, iha, ihb, opow_lt_opow_iff_right one_lt_omega0, add_lt_add_iff_left, add_zero, lt_add_iff_pos_right, lt_def, mul_one, Nat.cast_zero, Nat.cast_succ, Nat.succPNat_coe, opow_succ, opow_zero, mul_add_one, PNat.one_coe, succ_zero, _root_.zero_add, zero_def] · decide · exact ⟨rfl, inferInstance⟩ · have := opow_pos (repr a') omega0_pos refine ⟨isSuccLimit_mul this isSuccLimit_omega0, fun i => ⟨this, ?_, fun H => @NF.oadd_zero _ _ (iha.2 H.fst)⟩, exists_lt_mul_omega0'⟩ rw [← mul_succ, ← natCast_succ, Ordinal.mul_lt_mul_iff_left this] apply nat_lt_omega0 · have := opow_pos (repr a') omega0_pos refine ⟨isSuccLimit_add _ (isSuccLimit_mul this isSuccLimit_omega0), fun i => ⟨this, ?_, ?_⟩, exists_lt_add exists_lt_mul_omega0'⟩ · rw [← mul_succ, ← natCast_succ, Ordinal.mul_lt_mul_iff_left this] apply nat_lt_omega0 · refine fun H => H.fst.oadd _ (NF.below_of_lt' ?_ (@NF.oadd_zero _ _ (iha.2 H.fst))) rw [repr, ← zero_def, repr, add_zero, iha.1, opow_succ, Ordinal.mul_lt_mul_iff_left this] apply nat_lt_omega0 · rcases iha with ⟨h1, h2, h3⟩ refine ⟨isSuccLimit_opow one_lt_omega0 h1, fun i => ?_, exists_lt_omega0_opow' one_lt_omega0 h1 h3⟩ obtain ⟨h4, h5, h6⟩ := h2 i exact ⟨h4, h5, fun H => @NF.oadd_zero _ _ (h6 H.fst)⟩ · rcases iha with ⟨h1, h2, h3⟩ refine ⟨isSuccLimit_add _ (isSuccLimit_opow one_lt_omega0 h1), fun i => ?_, exists_lt_add (exists_lt_omega0_opow' one_lt_omega0 h1 h3)⟩ obtain ⟨h4, h5, h6⟩ := h2 i refine ⟨h4, h5, fun H => H.fst.oadd _ (NF.below_of_lt' ?_ (@NF.oadd_zero _ _ (h6 H.fst)))⟩ rwa [repr, ← zero_def, repr, add_zero, PNat.one_coe, Nat.cast_one, mul_one, opow_lt_opow_iff_right one_lt_omega0] · refine ⟨by rw [repr, ihb.1, add_succ, repr], fun H => H.fst.oadd _ (NF.below_of_lt' ?_ (ihb.2 H.snd))⟩ have := H.snd'.repr_lt rw [ihb.1] at this exact (lt_succ _).trans this · rcases ihb with ⟨h1, h2, h3⟩ simp only [repr] exact ⟨isSuccLimit_add _ h1, fun i => ⟨oadd_lt_oadd_3 (h2 i).1, oadd_lt_oadd_3 (h2 i).2.1, fun H => H.fst.oadd _ (NF.below_of_lt' (lt_trans (h2 i).2.1 H.snd'.repr_lt) ((h2 i).2.2 H.snd))⟩, exists_lt_add h3⟩ /-- The fast growing hierarchy for ordinal notations `< ε₀`. This is a sequence of functions `ℕ → ℕ` indexed by ordinals, with the definition: * `f_0(n) = n + 1` * `f_(α + 1)(n) = f_α^[n](n)` * `f_α(n) = f_(α[n])(n)` where `α` is a limit ordinal and `α[i]` is the fundamental sequence converging to `α` -/ def fastGrowing : ONote → ℕ → ℕ | o => match fundamentalSequence o, fundamentalSequence_has_prop o with | Sum.inl none, _ => Nat.succ | Sum.inl (some a), h => have : a < o := by rw [lt_def, h.1]; apply lt_succ fun i => (fastGrowing a)^[i] i | Sum.inr f, h => fun i => have : f i < o := (h.2.1 i).2.1 fastGrowing (f i) i termination_by o => o -- Porting note: the linter bug should be fixed. @[nolint unusedHavesSuffices] theorem fastGrowing_def {o : ONote} {x} (e : fundamentalSequence o = x) : fastGrowing o = match (motive := (x : Option ONote ⊕ (ℕ → ONote)) → FundamentalSequenceProp o x → ℕ → ℕ) x, e ▸ fundamentalSequence_has_prop o with | Sum.inl none, _ => Nat.succ | Sum.inl (some a), _ => fun i => (fastGrowing a)^[i] i | Sum.inr f, _ => fun i => fastGrowing (f i) i := by subst x rw [fastGrowing] theorem fastGrowing_zero' (o : ONote) (h : fundamentalSequence o = Sum.inl none) : fastGrowing o = Nat.succ := by rw [fastGrowing_def h] theorem fastGrowing_succ (o) {a} (h : fundamentalSequence o = Sum.inl (some a)) : fastGrowing o = fun i => (fastGrowing a)^[i] i := by rw [fastGrowing_def h] theorem fastGrowing_limit (o) {f} (h : fundamentalSequence o = Sum.inr f) : fastGrowing o = fun i => fastGrowing (f i) i := by rw [fastGrowing_def h] @[simp] theorem fastGrowing_zero : fastGrowing 0 = Nat.succ := fastGrowing_zero' _ rfl @[simp] theorem fastGrowing_one : fastGrowing 1 = fun n => 2 * n := by rw [@fastGrowing_succ 1 0 rfl]; funext i; rw [two_mul, fastGrowing_zero] suffices ∀ a b, Nat.succ^[a] b = b + a from this _ _ intro a b; induction a <;> simp [*, Function.iterate_succ', Nat.add_assoc, -Function.iterate_succ] @[simp] theorem fastGrowing_two : fastGrowing 2 = fun n => (2 ^ n) * n := by rw [@fastGrowing_succ 2 1 rfl] simp /-- We can extend the fast growing hierarchy one more step to `ε₀` itself, using `ω ^ (ω ^ (⋯ ^ ω))` as the fundamental sequence converging to `ε₀` (which is not an `ONote`). Extending the fast growing hierarchy beyond this requires a definition of fundamental sequence for larger ordinals. -/ def fastGrowingε₀ (i : ℕ) : ℕ := fastGrowing ((fun a => a.oadd 1 0)^[i] 0) i theorem fastGrowingε₀_zero : fastGrowingε₀ 0 = 1 := by simp [fastGrowingε₀] theorem fastGrowingε₀_one : fastGrowingε₀ 1 = 2 := by simp [fastGrowingε₀, show oadd 0 1 0 = 1 from rfl] theorem fastGrowingε₀_two : fastGrowingε₀ 2 = 2048 := by norm_num [fastGrowingε₀, show oadd 0 1 0 = 1 from rfl, @fastGrowing_limit (oadd 1 1 0) _ rfl, show oadd 0 (2 : Nat).succPNat 0 = 3 from rfl, @fastGrowing_succ 3 2 rfl] end ONote /-- The type of normal ordinal notations. It would have been nicer to define this right in the inductive type, but `NF o` requires `repr` which requires `ONote`, so all these things would have to be defined at once, which messes up the VM representation. -/ def NONote := { o : ONote // o.NF } instance : DecidableEq NONote := by unfold NONote; infer_instance namespace NONote open ONote instance NF (o : NONote) : NF o.1 := o.2 /-- Construct a `NONote` from an ordinal notation (and infer normality) -/ def mk (o : ONote) [h : ONote.NF o] : NONote := ⟨o, h⟩ /-- The ordinal represented by an ordinal notation. This function is noncomputable because ordinal arithmetic is noncomputable. In computational applications `NONote` can be used exclusively without reference to `Ordinal`, but this function allows for correctness results to be stated. -/ noncomputable def repr (o : NONote) : Ordinal := o.1.repr instance : ToString NONote := ⟨fun x => x.1.toString⟩ instance : Repr NONote := ⟨fun x prec => x.1.repr' prec⟩ instance : Preorder NONote where le x y := repr x ≤ repr y lt x y := repr x < repr y le_refl _ := @le_refl Ordinal _ _ le_trans _ _ _ := @le_trans Ordinal _ _ _ _ lt_iff_le_not_ge _ _ := @lt_iff_le_not_ge Ordinal _ _ _ instance : Zero NONote := ⟨⟨0, NF.zero⟩⟩ instance : Inhabited NONote := ⟨0⟩ theorem lt_wf : @WellFounded NONote (· < ·) := InvImage.wf repr Ordinal.lt_wf instance : WellFoundedLT NONote := ⟨lt_wf⟩ instance : WellFoundedRelation NONote := ⟨(· < ·), lt_wf⟩ /-- Convert a natural number to an ordinal notation -/ def ofNat (n : ℕ) : NONote := ⟨ONote.ofNat n, ⟨⟨_, nfBelow_ofNat _⟩⟩⟩ /-- Compare ordinal notations -/ def cmp (a b : NONote) : Ordering := ONote.cmp a.1 b.1 theorem cmp_compares : ∀ a b : NONote, (cmp a b).Compares a b | ⟨a, ha⟩, ⟨b, hb⟩ => by dsimp [cmp] have := ONote.cmp_compares a b cases h : ONote.cmp a b <;> simp only [h] at this <;> try exact this exact Subtype.mk_eq_mk.2 this instance : LinearOrder NONote := linearOrderOfCompares cmp cmp_compares /-- Asserts that `repr a < ω ^ repr b`. Used in `NONote.recOn`. -/ def below (a b : NONote) : Prop := NFBelow a.1 (repr b) /-- The `oadd` pseudo-constructor for `NONote` -/ def oadd (e : NONote) (n : ℕ+) (a : NONote) (h : below a e) : NONote := ⟨_, NF.oadd e.2 n h⟩ /-- This is a recursor-like theorem for `NONote` suggesting an inductive definition, which can't actually be defined this way due to conflicting dependencies. -/ @[elab_as_elim] def recOn {C : NONote → Sort*} (o : NONote) (H0 : C 0) (H1 : ∀ e n a h, C e → C a → C (oadd e n a h)) : C o := by obtain ⟨o, h⟩ := o; induction o with | zero => exact H0 | oadd e n a IHe IHa => exact H1 ⟨e, h.fst⟩ n ⟨a, h.snd⟩ h.snd' (IHe _) (IHa _) /-- Addition of ordinal notations -/ instance : Add NONote := ⟨fun x y => mk (x.1 + y.1)⟩ theorem repr_add (a b) : repr (a + b) = repr a + repr b := ONote.repr_add a.1 b.1 /-- Subtraction of ordinal notations -/ instance : Sub NONote := ⟨fun x y => mk (x.1 - y.1)⟩ theorem repr_sub (a b) : repr (a - b) = repr a - repr b := ONote.repr_sub a.1 b.1 /-- Multiplication of ordinal notations -/ instance : Mul NONote := ⟨fun x y => mk (x.1 * y.1)⟩ theorem repr_mul (a b) : repr (a * b) = repr a * repr b := ONote.repr_mul a.1 b.1 /-- Exponentiation of ordinal notations -/ def opow (x y : NONote) := mk (x.1 ^ y.1) theorem repr_opow (a b) : repr (opow a b) = repr a ^ repr b := ONote.repr_opow a.1 b.1 end NONote
Fiber.lean
/- Copyright (c) 2025 Jingting Wang, Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jingting Wang, Junyan Xu -/ import Mathlib.RingTheory.Spectrum.Prime.RingHom import Mathlib.RingTheory.LocalRing.ResidueField.Ideal import Mathlib.RingTheory.Localization.BaseChange import Mathlib.RingTheory.TensorProduct.Quotient /-! # The fiber of a ring homomorphism at a prime ideal ## Main results * `PrimeSpectrum.preimageOrderIsoTensorResidueField` : We show that there is an `OrderIso` between fiber of a ring homomorphism `algebraMap R S : R →+* S` at a prime ideal `p : PrimeSpectrum R` and the prime spectrum of the tensor product of `S` and the residue field of `p`. -/ open Algebra TensorProduct in /-- The `OrderIso` between fiber of a ring homomorphism `algebraMap R S : R →+* S` at a prime ideal `p : PrimeSpectrum R` and the prime spectrum of the tensor product of `S` and the residue field of `p`. -/ noncomputable def PrimeSpectrum.preimageOrderIsoTensorResidueField (R S : Type*) [CommRing R] [CommRing S] [Algebra R S] (p : PrimeSpectrum R) : (algebraMap R S).specComap ⁻¹' {p} ≃o PrimeSpectrum (p.asIdeal.ResidueField ⊗[R] S) := by let Rp := Localization.AtPrime p.asIdeal refine .trans ?_ <| comapEquiv ((Algebra.TensorProduct.comm ..).trans <| cancelBaseChange R Rp ..).toRingEquiv refine .trans (.symm ((Ideal.primeSpectrumQuotientOrderIsoZeroLocus _).trans ?_)) <| comapEquiv (quotIdealMapEquivTensorQuot ..).toRingEquiv letI := rightAlgebra (R := R) (A := Rp) (B := S) let e := IsLocalization.primeSpectrumOrderIso (algebraMapSubmonoid S p.asIdeal.primeCompl) (Rp ⊗[R] S) |>.trans <| .setCongr _ {q | (algebraMap R S).specComap q ≤ p} <| Set.ext fun _ ↦ disjoint_comm.trans (Ideal.disjoint_map_primeCompl_iff_comap_le ..) have {q : PrimeSpectrum (Rp ⊗[R] S)} : q ∈ zeroLocus ((IsLocalRing.maximalIdeal _).map (algebraMap Rp (Rp ⊗[R] S))) ↔ p ≤ (algebraMap R S).specComap (e q) := by rw [mem_zeroLocus, SetLike.coe_subset_coe, ← Localization.AtPrime.map_eq_maximalIdeal, Ideal.map_map, Ideal.map_le_iff_le_comap, show algebraMap Rp _ = includeLeftRingHom from rfl, includeLeftRingHom_comp_algebraMap]; rfl exact { toFun q := ⟨e q, (e q).2.antisymm (this.mp q.2)⟩ invFun q := ⟨e.symm ⟨q, q.2.le⟩, this.mpr <| by rw [e.apply_symm_apply]; exact q.2.ge⟩ left_inv q := Subtype.ext (e.left_inv q) right_inv q := Subtype.ext <| by apply Subtype.ext_iff.mp (e.right_inv ⟨q, q.2.le⟩) map_rel_iff' := e.map_rel_iff }
Defs.lean
/- Copyright (c) 2020 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison, Shing Tak Lam, Mario Carneiro -/ import Mathlib.Tactic.NormNum import Mathlib.Tactic.Ring import Mathlib.Tactic.Linarith import Mathlib.Algebra.Order.Group.Nat /-! # Digits of a natural number This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. Also included is a bound on the length of `Nat.toDigits` from core. ## TODO A basic `norm_digits` tactic for proving goals of the form `Nat.digits a b = l` where `a` and `b` are numerals is not yet ported. -/ assert_not_exists Finset namespace Nat variable {n : ℕ} /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digitsAux0 : ℕ → List ℕ | 0 => [] | n + 1 => [n+1] /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digitsAux1 (n : ℕ) : List ℕ := List.replicate n 1 /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digitsAux (b : ℕ) (h : 2 ≤ b) : ℕ → List ℕ | 0 => [] | n + 1 => ((n + 1) % b) :: digitsAux b h ((n + 1) / b) decreasing_by exact Nat.div_lt_self (Nat.succ_pos _) h @[simp] theorem digitsAux_zero (b : ℕ) (h : 2 ≤ b) : digitsAux b h 0 = [] := by rw [digitsAux] theorem digitsAux_def (b : ℕ) (h : 2 ≤ b) (n : ℕ) (w : 0 < n) : digitsAux b h n = (n % b) :: digitsAux b h (n / b) := by cases n · cases w · rw [digitsAux] /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `ofDigits b L = L.foldr (fun x y ↦ x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = List.replicate n 1`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `Nat.toDigits` in core, which is used for printing numerals. In particular, `Nat.toDigits b 0 = ['0']`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → List ℕ | 0 => digitsAux0 | 1 => digitsAux1 | b + 2 => digitsAux (b + 2) (by simp) @[simp] theorem digits_zero (b : ℕ) : digits b 0 = [] := by rcases b with (_ | ⟨_ | ⟨_⟩⟩) <;> simp [digits, digitsAux0, digitsAux1] theorem digits_zero_zero : digits 0 0 = [] := rfl @[simp] theorem digits_zero_succ (n : ℕ) : digits 0 n.succ = [n+1] := rfl theorem digits_zero_succ' : ∀ {n : ℕ}, n ≠ 0 → digits 0 n = [n] | 0, h => (h rfl).elim | _ + 1, _ => rfl @[simp] theorem digits_one (n : ℕ) : digits 1 n = List.replicate n 1 := rfl -- no `@[simp]`: dsimp can prove this theorem digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl theorem digits_add_two_add_one (b n : ℕ) : digits (b + 2) (n + 1) = ((n + 1) % (b + 2)) :: digits (b + 2) ((n + 1) / (b + 2)) := by simp [digits, digitsAux_def] @[simp] lemma digits_of_two_le_of_pos {b : ℕ} (hb : 2 ≤ b) (hn : 0 < n) : Nat.digits b n = n % b :: Nat.digits b (n / b) := by rw [Nat.eq_add_of_sub_eq hb rfl, Nat.eq_add_of_sub_eq hn rfl, Nat.digits_add_two_add_one] theorem digits_def' : ∀ {b : ℕ} (_ : 1 < b) {n : ℕ} (_ : 0 < n), digits b n = (n % b) :: digits b (n / b) | 0, h => absurd h (by decide) | 1, h => absurd h (by decide) | b + 2, _ => digitsAux_def _ (by simp) _ @[simp] theorem digits_of_lt (b x : ℕ) (hx : x ≠ 0) (hxb : x < b) : digits b x = [x] := by rcases exists_eq_succ_of_ne_zero hx with ⟨x, rfl⟩ rcases Nat.exists_eq_add_of_le' ((Nat.le_add_left 1 x).trans_lt hxb) with ⟨b, rfl⟩ rw [digits_add_two_add_one, div_eq_of_lt hxb, digits_zero, mod_eq_of_lt hxb] theorem digits_add (b : ℕ) (h : 1 < b) (x y : ℕ) (hxb : x < b) (hxy : x ≠ 0 ∨ y ≠ 0) : digits b (x + b * y) = x :: digits b y := by rcases Nat.exists_eq_add_of_le' h with ⟨b, rfl : _ = _ + 2⟩ cases y · simp [hxb, hxy.resolve_right (absurd rfl)] dsimp [digits] rw [digitsAux_def] · congr · simp [Nat.add_mod, mod_eq_of_lt hxb] · simp [add_mul_div_left, div_eq_of_lt hxb] · apply Nat.succ_pos -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. /-- `ofDigits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ def ofDigits {α : Type*} [Semiring α] (b : α) : List ℕ → α | [] => 0 | h :: t => h + b * ofDigits b t theorem ofDigits_eq_foldr {α : Type*} [Semiring α] (b : α) (L : List ℕ) : ofDigits b L = List.foldr (fun x y => ↑x + b * y) 0 L := by induction' L with d L ih · rfl · dsimp [ofDigits] rw [ih] @[simp] theorem ofDigits_nil {b : ℕ} : ofDigits b [] = 0 := rfl @[simp] theorem ofDigits_singleton {b n : ℕ} : ofDigits b [n] = n := by simp [ofDigits] @[simp] theorem ofDigits_one_cons {α : Type*} [Semiring α] (h : ℕ) (L : List ℕ) : ofDigits (1 : α) (h :: L) = h + ofDigits 1 L := by simp [ofDigits] theorem ofDigits_cons {b hd} {tl : List ℕ} : ofDigits b (hd :: tl) = hd + b * ofDigits b tl := rfl theorem ofDigits_append {b : ℕ} {l1 l2 : List ℕ} : ofDigits b (l1 ++ l2) = ofDigits b l1 + b ^ l1.length * ofDigits b l2 := by induction' l1 with hd tl IH · simp [ofDigits] · rw [ofDigits, List.cons_append, ofDigits, IH, List.length_cons, pow_succ'] ring @[simp] theorem ofDigits_append_zero {b : ℕ} (l : List ℕ) : ofDigits b (l ++ [0]) = ofDigits b l := by rw [ofDigits_append, ofDigits_singleton, mul_zero, add_zero] @[simp] theorem ofDigits_replicate_zero {b k : ℕ} : ofDigits b (List.replicate k 0) = 0 := by induction k with | zero => rfl | succ k ih => simp [List.replicate, ofDigits_cons, ih] @[simp] theorem ofDigits_append_replicate_zero {b k : ℕ} (l : List ℕ) : ofDigits b (l ++ List.replicate k 0) = ofDigits b l := by rw [ofDigits_append] simp theorem ofDigits_reverse_cons {b : ℕ} (l : List ℕ) (d : ℕ) : ofDigits b (d :: l).reverse = ofDigits b l.reverse + b^l.length * d := by simp only [List.reverse_cons] rw [ofDigits_append] simp theorem ofDigits_reverse_zero_cons {b : ℕ} (l : List ℕ) : ofDigits b (0 :: l).reverse = ofDigits b l.reverse := by simp only [List.reverse_cons, ofDigits_append_zero] @[norm_cast] theorem coe_ofDigits (α : Type*) [Semiring α] (b : ℕ) (L : List ℕ) : ((ofDigits b L : ℕ) : α) = ofDigits (b : α) L := by induction' L with d L ih · simp [ofDigits] · dsimp [ofDigits]; push_cast; rw [ih] @[norm_cast] theorem coe_int_ofDigits (b : ℕ) (L : List ℕ) : ((ofDigits b L : ℕ) : ℤ) = ofDigits (b : ℤ) L := by induction' L with d L _ · rfl · dsimp [ofDigits]; push_cast; simp only theorem digits_zero_of_eq_zero {b : ℕ} (h : b ≠ 0) : ∀ {L : List ℕ} (_ : ofDigits b L = 0), ∀ l ∈ L, l = 0 | _ :: _, h0, _, List.Mem.head .. => Nat.eq_zero_of_add_eq_zero_right h0 | _ :: _, h0, _, List.Mem.tail _ hL => digits_zero_of_eq_zero h (mul_right_injective₀ h (Nat.eq_zero_of_add_eq_zero_left h0)) _ hL theorem digits_ofDigits (b : ℕ) (h : 1 < b) (L : List ℕ) (w₁ : ∀ l ∈ L, l < b) (w₂ : ∀ h : L ≠ [], L.getLast h ≠ 0) : digits b (ofDigits b L) = L := by induction' L with d L ih · dsimp [ofDigits] simp · dsimp [ofDigits] replace w₂ := w₂ (by simp) rw [digits_add b h] · rw [ih] · intro l m apply w₁ exact List.mem_cons_of_mem _ m · intro h rw [List.getLast_cons h] at w₂ convert w₂ · exact w₁ d List.mem_cons_self · by_cases h' : L = [] · rcases h' with rfl left simpa using w₂ · right contrapose! w₂ refine digits_zero_of_eq_zero h.ne_bot w₂ _ ?_ rw [List.getLast_cons h'] exact List.getLast_mem h' theorem ofDigits_digits (b n : ℕ) : ofDigits b (digits b n) = n := by rcases b with - | b · rcases n with - | n · rfl · simp · rcases b with - | b · induction' n with n ih · rfl · rw [Nat.zero_add] at ih ⊢ simp only [ih, add_comm 1, ofDigits_one_cons, Nat.cast_id, digits_one_succ] · induction n using Nat.strongRecOn with | ind n h => ?_ cases n · rw [digits_zero] rfl · simp only [digits_add_two_add_one] dsimp [ofDigits] rw [h _ (Nat.div_lt_self' _ b)] rw [Nat.mod_add_div] theorem ofDigits_one (L : List ℕ) : ofDigits 1 L = L.sum := by induction L with | nil => rfl | cons _ _ ih => simp [ofDigits, List.sum_cons, ih] /-! ### Properties This section contains various lemmas of properties relating to `digits` and `ofDigits`. -/ theorem digits_eq_nil_iff_eq_zero {b n : ℕ} : digits b n = [] ↔ n = 0 := by constructor · intro h have : ofDigits b (digits b n) = ofDigits b [] := by rw [h] convert this rw [ofDigits_digits] · rintro rfl simp theorem digits_ne_nil_iff_ne_zero {b n : ℕ} : digits b n ≠ [] ↔ n ≠ 0 := not_congr digits_eq_nil_iff_eq_zero theorem digits_eq_cons_digits_div {b n : ℕ} (h : 1 < b) (w : n ≠ 0) : digits b n = (n % b) :: digits b (n / b) := by rcases b with (_ | _ | b) · rw [digits_zero_succ' w, Nat.mod_zero, Nat.div_zero, Nat.digits_zero_zero] · norm_num at h rcases n with (_ | n) · norm_num at w · simp only [digits_add_two_add_one] theorem digits_getLast {b : ℕ} (m : ℕ) (h : 1 < b) (p q) : (digits b m).getLast p = (digits b (m / b)).getLast q := by by_cases hm : m = 0 · simp [hm] simp only [digits_eq_cons_digits_div h hm] rw [List.getLast_cons] theorem digits.injective (b : ℕ) : Function.Injective b.digits := Function.LeftInverse.injective (ofDigits_digits b) @[simp] theorem digits_inj_iff {b n m : ℕ} : b.digits n = b.digits m ↔ n = m := (digits.injective b).eq_iff theorem mul_ofDigits (n : ℕ) {b : ℕ} {l : List ℕ} : n * ofDigits b l = ofDigits b (l.map (n * ·)) := by induction l with | nil => rfl | cons hd tl ih => rw [List.map_cons, ofDigits_cons, ofDigits_cons, ← ih] ring lemma ofDigits_inj_of_len_eq {b : ℕ} (hb : 1 < b) {L1 L2 : List ℕ} (len : L1.length = L2.length) (w1 : ∀ l ∈ L1, l < b) (w2 : ∀ l ∈ L2, l < b) (h : ofDigits b L1 = ofDigits b L2) : L1 = L2 := by induction' L1 with D L ih generalizing L2 · simp only [List.length_nil] at len exact (List.length_eq_zero_iff.mp len.symm).symm obtain ⟨d, l, rfl⟩ := List.exists_cons_of_length_eq_add_one len.symm simp only [List.length_cons, add_left_inj] at len simp only [ofDigits_cons] at h have eqd : D = d := by have H : (D + b * ofDigits b L) % b = (d + b * ofDigits b l) % b := by rw [h] simpa [mod_eq_of_lt (w2 d List.mem_cons_self), mod_eq_of_lt (w1 D List.mem_cons_self)] using H simp only [eqd, add_right_inj, mul_left_cancel_iff_of_pos (zero_lt_of_lt hb)] at h have := ih len (fun a ha ↦ w1 a <| List.mem_cons_of_mem D ha) (fun a ha ↦ w2 a <| List.mem_cons_of_mem d ha) h rw [eqd, this] /-- The addition of ofDigits of two lists is equal to ofDigits of digit-wise addition of them -/ theorem ofDigits_add_ofDigits_eq_ofDigits_zipWith_of_length_eq {b : ℕ} {l1 l2 : List ℕ} (h : l1.length = l2.length) : ofDigits b l1 + ofDigits b l2 = ofDigits b (l1.zipWith (· + ·) l2) := by induction l1 generalizing l2 with | nil => simp_all [eq_comm, List.length_eq_zero_iff, ofDigits] | cons hd₁ tl₁ ih₁ => induction l2 generalizing tl₁ with | nil => simp_all | cons hd₂ tl₂ ih₂ => simp_all only [List.length_cons, ofDigits_cons, add_left_inj, eq_comm, List.zipWith_cons_cons] rw [← ih₁ h.symm, mul_add] ac_rfl /-- The digits in the base b+2 expansion of n are all less than b+2 -/ theorem digits_lt_base' {b m : ℕ} : ∀ {d}, d ∈ digits (b + 2) m → d < b + 2 := by induction m using Nat.strongRecOn with | ind n IH => ?_ intro d hd rcases n with - | n · rw [digits_zero] at hd cases hd -- base b+2 expansion of 0 has no digits rw [digits_add_two_add_one] at hd cases hd · exact n.succ.mod_lt (by linarith) · apply IH ((n + 1) / (b + 2)) · apply Nat.div_lt_self <;> omega · assumption /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ theorem digits_lt_base {b m d : ℕ} (hb : 1 < b) (hd : d ∈ digits b m) : d < b := by rcases b with (_ | _ | b) <;> try simp_all exact digits_lt_base' hd /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ theorem ofDigits_lt_base_pow_length' {b : ℕ} {l : List ℕ} (hl : ∀ x ∈ l, x < b + 2) : ofDigits (b + 2) l < (b + 2) ^ l.length := by induction' l with hd tl IH · simp [ofDigits] · rw [ofDigits, List.length_cons, pow_succ] have : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ tl.length * (b + 2) := mul_le_mul (IH fun x hx => hl _ (List.mem_cons_of_mem _ hx)) (by rfl) (by simp only [zero_le]) (Nat.zero_le _) suffices ↑hd < b + 2 by linarith exact hl hd List.mem_cons_self /-- an n-digit number in base b is less than b^n if b > 1 -/ theorem ofDigits_lt_base_pow_length {b : ℕ} {l : List ℕ} (hb : 1 < b) (hl : ∀ x ∈ l, x < b) : ofDigits b l < b ^ l.length := by rcases b with (_ | _ | b) <;> try simp_all exact ofDigits_lt_base_pow_length' hl /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ theorem lt_base_pow_length_digits' {b m : ℕ} : m < (b + 2) ^ (digits (b + 2) m).length := by convert @ofDigits_lt_base_pow_length' b (digits (b + 2) m) fun _ => digits_lt_base' rw [ofDigits_digits (b + 2) m] /-- Any number m is less than b^(number of digits in the base b representation of m) -/ theorem lt_base_pow_length_digits {b m : ℕ} (hb : 1 < b) : m < b ^ (digits b m).length := by rcases b with (_ | _ | b) <;> try simp_all exact lt_base_pow_length_digits' theorem digits_base_mul {b m : ℕ} (hb : 1 < b) (hm : 0 < m) : b.digits (b * m) = 0 :: b.digits m := by rw [digits_def' hb (by positivity)] simp [mul_div_right m (by positivity)] theorem digits_base_pow_mul {b k m : ℕ} (hb : 1 < b) (hm : 0 < m) : digits b (b ^ k * m) = List.replicate k 0 ++ digits b m := by induction k generalizing m with | zero => simp | succ k ih => rw [pow_succ', mul_assoc, digits_base_mul hb (by positivity), ih hm, List.replicate_succ, List.cons_append] theorem ofDigits_digits_append_digits {b m n : ℕ} : ofDigits b (digits b n ++ digits b m) = n + b ^ (digits b n).length * m := by rw [ofDigits_append, ofDigits_digits, ofDigits_digits] @[mono] theorem ofDigits_monotone {p q : ℕ} (L : List ℕ) (h : p ≤ q) : ofDigits p L ≤ ofDigits q L := by induction L with | nil => rfl | cons _ _ hi => simp only [ofDigits, cast_id, add_le_add_iff_left] exact Nat.mul_le_mul h hi theorem sum_le_ofDigits {p : ℕ} (L : List ℕ) (h : 1 ≤ p) : L.sum ≤ ofDigits p L := (ofDigits_one L).symm ▸ ofDigits_monotone L h theorem digit_sum_le (p n : ℕ) : List.sum (digits p n) ≤ n := by induction' n with n · exact digits_zero _ ▸ Nat.le_refl (List.sum []) · induction' p with p · rw [digits_zero_succ, List.sum_cons, List.sum_nil, add_zero] · nth_rw 2 [← ofDigits_digits p.succ (n + 1)] rw [← ofDigits_one <| digits p.succ n.succ] exact ofDigits_monotone (digits p.succ n.succ) <| Nat.succ_pos p /-- Interpreting as a base `p` number and dividing by `p` is the same as interpreting the tail. -/ lemma ofDigits_div_eq_ofDigits_tail {p : ℕ} (hpos : 0 < p) (digits : List ℕ) (w₁ : ∀ l ∈ digits, l < p) : ofDigits p digits / p = ofDigits p digits.tail := by induction' digits with hd tl · simp [ofDigits] · refine Eq.trans (add_mul_div_left hd _ hpos) ?_ rw [Nat.div_eq_of_lt <| w₁ _ List.mem_cons_self, zero_add] rfl /-- Interpreting as a base `p` number and dividing by `p^i` is the same as dropping `i`. -/ lemma ofDigits_div_pow_eq_ofDigits_drop {p : ℕ} (i : ℕ) (hpos : 0 < p) (digits : List ℕ) (w₁ : ∀ l ∈ digits, l < p) : ofDigits p digits / p ^ i = ofDigits p (digits.drop i) := by induction' i with i hi · simp · rw [Nat.pow_succ, ← Nat.div_div_eq_div_mul, hi, ofDigits_div_eq_ofDigits_tail hpos (List.drop i digits) fun x hx ↦ w₁ x <| List.mem_of_mem_drop hx, ← List.drop_one, List.drop_drop, add_comm] /-- Dividing `n` by `p^i` is like truncating the first `i` digits of `n` in base `p`. -/ lemma self_div_pow_eq_ofDigits_drop {p : ℕ} (i n : ℕ) (h : 2 ≤ p) : n / p ^ i = ofDigits p ((p.digits n).drop i) := by convert ofDigits_div_pow_eq_ofDigits_drop i (zero_lt_of_lt h) (p.digits n) (fun l hl ↦ digits_lt_base h hl) exact (ofDigits_digits p n).symm /-- Interpreting as a base `p` number and modulo `p^i` is the same as taking the first `i` digits. -/ lemma ofDigits_mod_pow_eq_ofDigits_take {p : ℕ} (i : ℕ) (hpos : 0 < p) (digits : List ℕ) (w₁ : ∀ l ∈ digits, l < p) : ofDigits p digits % p ^ i = ofDigits p (digits.take i) := by induction i generalizing digits with | zero => simp [mod_one] | succ i ih => cases digits with | nil => simp | cons hd tl => rw [List.take_succ_cons, ofDigits_cons, ofDigits_cons, ← ih _ fun x hx ↦ w₁ x <| List.mem_cons_of_mem hd hx, add_mod, mod_eq_of_lt <| lt_of_lt_of_le (w₁ hd List.mem_cons_self) (le_pow <| add_one_pos i), pow_succ', mul_mod_mul_left, mod_eq_of_lt] apply add_lt_of_lt_sub apply lt_of_lt_of_le (b := p) · exact w₁ hd List.mem_cons_self · rw [← Nat.mul_sub] exact Nat.le_mul_of_pos_right _ <| Nat.sub_pos_of_lt <| mod_lt _ <| pow_pos hpos i /-- `n` modulo `p^i` is like taking the least significant `i` digits of `n` in base `p`. -/ lemma self_mod_pow_eq_ofDigits_take {p : ℕ} (i n : ℕ) (h : 2 ≤ p) : n % p ^ i = ofDigits p ((p.digits n).take i) := by convert ofDigits_mod_pow_eq_ofDigits_take i (zero_lt_of_lt h) (p.digits n) (fun l hl ↦ digits_lt_base h hl) exact (ofDigits_digits p n).symm /-! ### `Nat.toDigits` length -/ lemma toDigitsCore_lens_eq_aux (b f : Nat) : ∀ (n : Nat) (l1 l2 : List Char), l1.length = l2.length → (Nat.toDigitsCore b f n l1).length = (Nat.toDigitsCore b f n l2).length := by induction f with (simp only [Nat.toDigitsCore]; intro n l1 l2 hlen) | zero => assumption | succ f ih => if hx : n / b = 0 then simp only [hx, if_true, List.length, congrArg (fun l ↦ l + 1) hlen] else simp only [hx, if_false] specialize ih (n / b) (Nat.digitChar (n % b) :: l1) (Nat.digitChar (n % b) :: l2) simp only [List.length, congrArg (fun l ↦ l + 1) hlen] at ih exact ih trivial lemma toDigitsCore_lens_eq (b f : Nat) : ∀ (n : Nat) (c : Char) (tl : List Char), (Nat.toDigitsCore b f n (c :: tl)).length = (Nat.toDigitsCore b f n tl).length + 1 := by induction f with (intro n c tl; simp only [Nat.toDigitsCore, List.length]) | succ f ih => grind lemma nat_repr_len_aux (n b e : Nat) (h_b_pos : 0 < b) : n < b ^ e.succ → n / b < b ^ e := by simp only [Nat.pow_succ] exact (@Nat.div_lt_iff_lt_mul b n (b ^ e) h_b_pos).mpr /-- The String representation produced by toDigitsCore has the proper length relative to the number of digits in `n < e` for some base `b`. Since this works with any base, it can be used for binary, decimal, and hex. -/ lemma toDigitsCore_length (b f n e : Nat) (h_e_pos : 0 < e) (hlt : n < b ^ e) : (Nat.toDigitsCore b f n []).length ≤ e := by induction f generalizing n e hlt h_e_pos with | zero => simp only [toDigitsCore, List.length, zero_le] | succ f ih => simp only [toDigitsCore] cases e with | zero => exact False.elim (Nat.lt_irrefl 0 h_e_pos) | succ e => cases e with | zero => rw [zero_add, pow_one] at hlt simp [Nat.div_eq_of_lt hlt] | succ e => specialize ih (n / b) _ (add_one_pos e) (Nat.div_lt_of_lt_mul <| by rwa [← pow_add_one']) split_ifs · simp only [List.length_singleton, _root_.zero_le, succ_le_succ] · simp only [toDigitsCore_lens_eq b f (n / b) (Nat.digitChar <| n % b), Nat.succ_le_succ_iff, ih] /-- The core implementation of `Nat.toDigits` returns a String with length less than or equal to the number of digits in the base-`b` number (represented by `e`). For example, the string representation of any number less than `b ^ 3` has a length less than or equal to 3. -/ lemma toDigits_length (b n e : Nat) : 0 < e → n < b ^ e → (Nat.toDigits b n).length ≤ e := toDigitsCore_length _ _ _ _ /-- The core implementation of `Nat.repr` returns a String with length less than or equal to the number of digits in the decimal number (represented by `e`). For example, the decimal string representation of any number less than 1000 (10 ^ 3) has a length less than or equal to 3. -/ lemma repr_length (n e : Nat) : 0 < e → n < 10 ^ e → (Nat.repr n).length ≤ e := toDigits_length _ _ _ /-! ### `norm_digits` tactic -/ namespace NormDigits theorem digits_succ (b n m r l) (e : r + b * m = n) (hr : r < b) (h : Nat.digits b m = l ∧ 1 < b ∧ 0 < m) : (Nat.digits b n = r :: l) ∧ 1 < b ∧ 0 < n := by rcases h with ⟨h, b2, m0⟩ have b0 : 0 < b := by omega have n0 : 0 < n := by linarith [mul_pos b0 m0] refine ⟨?_, b2, n0⟩ obtain ⟨rfl, rfl⟩ := (Nat.div_mod_unique b0).2 ⟨e, hr⟩ subst h; exact Nat.digits_def' b2 n0 theorem digits_one (b n) (n0 : 0 < n) (nb : n < b) : Nat.digits b n = [n] ∧ 1 < b ∧ 0 < n := by have b2 : 1 < b := lt_iff_add_one_le.mpr (le_trans (add_le_add_right (lt_iff_add_one_le.mp n0) 1) nb) refine ⟨?_, b2, n0⟩ rw [Nat.digits_def' b2 n0, Nat.mod_eq_of_lt nb, Nat.div_eq_zero_iff.2 <| .inr nb, Nat.digits_zero] /- Porting note: this part of the file is tactic related. open Tactic -- failed to format: unknown constant 'term.pseudo.antiquot' /-- Helper function for the `norm_digits` tactic. -/ unsafe def eval_aux ( eb : expr ) ( b : ℕ ) : expr → ℕ → instance_cache → tactic ( instance_cache × expr × expr ) | en , n , ic => do let m := n / b let r := n % b let ( ic , er ) ← ic . ofNat r let ( ic , pr ) ← norm_num.prove_lt_nat ic er eb if m = 0 then do let ( _ , pn0 ) ← norm_num.prove_pos ic en return ( ic , q( ( [ $ ( en ) ] : List Nat ) ) , q( digits_one $ ( eb ) $ ( en ) $ ( pn0 ) $ ( pr ) ) ) else do let em ← expr.of_nat q( ℕ ) m let ( _ , pe ) ← norm_num.derive q( ( $ ( er ) + $ ( eb ) * $ ( em ) : ℕ ) ) let ( ic , el , p ) ← eval_aux em m ic return ( ic , q( @ List.cons ℕ $ ( er ) $ ( el ) ) , q( digits_succ $ ( eb ) $ ( en ) $ ( em ) $ ( er ) $ ( el ) $ ( pe ) $ ( pr ) $ ( p ) ) ) /-- A tactic for normalizing expressions of the form `Nat.digits a b = l` where `a` and `b` are numerals. ``` example : Nat.digits 10 123 = [3,2,1] := by norm_num ``` -/ @[norm_num] unsafe def eval : expr → tactic (expr × expr) | q(Nat.digits $(eb) $(en)) => do let b ← expr.to_nat eb let n ← expr.to_nat en if n = 0 then return (q(([] : List ℕ)), q(Nat.digits_zero $(eb))) else if b = 0 then do let ic ← mk_instance_cache q(ℕ) let (_, pn0) ← norm_num.prove_ne_zero' ic en return (q(([$(en)] : List ℕ)), q(@Nat.digits_zero_succ' $(en) $(pn0))) else if b = 1 then do let ic ← mk_instance_cache q(ℕ) let s ← simp_lemmas.add_simp simp_lemmas.mk `list.replicate let (rhs, p2, _) ← simplify s [] q(List.replicate $(en) 1) let p ← mk_eq_trans q(Nat.digits_one $(en)) p2 return (rhs, p) else do let ic ← mk_instance_cache q(ℕ) let (_, l, p) ← eval_aux eb b en n ic let p ← mk_app `` And.left [p] return (l, p) | _ => failed -/ end NormDigits end Nat
Basic.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.CharP.Basic import Mathlib.Algebra.Module.End import Mathlib.Algebra.Ring.Prod import Mathlib.Data.Fintype.Units import Mathlib.GroupTheory.GroupAction.SubMulAction import Mathlib.GroupTheory.OrderOfElement import Mathlib.Tactic.FinCases /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `ZMod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : ZMod 0` it is the absolute value of `a` - for `a : ZMod n` with `0 < n` it is the least natural number in the equivalence class * A coercion `cast` is defined from `ZMod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ assert_not_exists Field Submodule TwoSidedIdeal open Function ZMod namespace ZMod instance : IsDomain (ZMod 0) := inferInstanceAs (IsDomain ℤ) /-- For non-zero `n : ℕ`, the ring `Fin n` is equivalent to `ZMod n`. -/ def finEquiv : ∀ (n : ℕ) [NeZero n], Fin n ≃+* ZMod n | 0, h => (h.ne _ rfl).elim | _ + 1, _ => .refl _ instance charZero : CharZero (ZMod 0) := inferInstanceAs (CharZero ℤ) /-- `val a` is a natural number defined as: - for `a : ZMod 0` it is the absolute value of `a` - for `a : ZMod n` with `0 < n` it is the least natural number in the equivalence class See `ZMod.valMinAbs` for a variant that takes values in the integers. -/ def val : ∀ {n : ℕ}, ZMod n → ℕ | 0 => Int.natAbs | n + 1 => ((↑) : Fin (n + 1) → ℕ) theorem val_lt {n : ℕ} [NeZero n] (a : ZMod n) : a.val < n := by cases n · cases NeZero.ne 0 rfl exact Fin.is_lt a theorem val_le {n : ℕ} [NeZero n] (a : ZMod n) : a.val ≤ n := a.val_lt.le @[simp] theorem val_zero : ∀ {n}, (0 : ZMod n).val = 0 | 0 => rfl | _ + 1 => rfl @[simp] theorem val_one' : (1 : ZMod 0).val = 1 := rfl @[simp] theorem val_neg' {n : ZMod 0} : (-n).val = n.val := Int.natAbs_neg n @[simp] theorem val_mul' {m n : ZMod 0} : (m * n).val = m.val * n.val := Int.natAbs_mul m n @[simp] theorem val_natCast (n a : ℕ) : (a : ZMod n).val = a % n := by cases n · rw [Nat.mod_zero] exact Int.natAbs_natCast a · apply Fin.val_natCast lemma val_natCast_of_lt {n a : ℕ} (h : a < n) : (a : ZMod n).val = a := by rwa [val_natCast, Nat.mod_eq_of_lt] lemma val_ofNat (n a : ℕ) [a.AtLeastTwo] : (ofNat(a) : ZMod n).val = ofNat(a) % n := val_natCast .. lemma val_ofNat_of_lt {n a : ℕ} [a.AtLeastTwo] (han : a < n) : (ofNat(a) : ZMod n).val = ofNat(a) := val_natCast_of_lt han theorem val_unit' {n : ZMod 0} : IsUnit n ↔ n.val = 1 := by simp only [val] rw [Int.isUnit_iff, Int.natAbs_eq_iff, Nat.cast_one] lemma eq_one_of_isUnit_natCast {n : ℕ} (h : IsUnit (n : ZMod 0)) : n = 1 := by rw [← Nat.mod_zero n, ← val_natCast, val_unit'.mp h] instance charP (n : ℕ) : CharP (ZMod n) n where cast_eq_zero_iff := by intro k rcases n with - | n · simp [zero_dvd_iff] · exact Fin.natCast_eq_zero -- Verify that `grind` can see that `ZMod n` has characteristic `n`. example (n : ℕ) : Lean.Grind.IsCharP (ZMod n) n := inferInstance @[simp] theorem addOrderOf_one (n : ℕ) : addOrderOf (1 : ZMod n) = n := CharP.eq _ (CharP.addOrderOf_one _) (ZMod.charP n) /-- This lemma works in the case in which `ZMod n` is not infinite, i.e. `n ≠ 0`. The version where `a ≠ 0` is `addOrderOf_coe'`. -/ @[simp] theorem addOrderOf_coe (a : ℕ) {n : ℕ} (n0 : n ≠ 0) : addOrderOf (a : ZMod n) = n / n.gcd a := by rcases a with - | a · simp only [Nat.cast_zero, addOrderOf_zero, Nat.gcd_zero_right, Nat.pos_of_ne_zero n0, Nat.div_self] rw [← Nat.smul_one_eq_cast, addOrderOf_nsmul' _ a.succ_ne_zero, ZMod.addOrderOf_one] /-- This lemma works in the case in which `a ≠ 0`. The version where `ZMod n` is not infinite, i.e. `n ≠ 0`, is `addOrderOf_coe`. -/ @[simp] theorem addOrderOf_coe' {a : ℕ} (n : ℕ) (a0 : a ≠ 0) : addOrderOf (a : ZMod n) = n / n.gcd a := by rw [← Nat.smul_one_eq_cast, addOrderOf_nsmul' _ a0, ZMod.addOrderOf_one] /-- We have that `ringChar (ZMod n) = n`. -/ theorem ringChar_zmod_n (n : ℕ) : ringChar (ZMod n) = n := by rw [ringChar.eq_iff] exact ZMod.charP n theorem natCast_self (n : ℕ) : (n : ZMod n) = 0 := CharP.cast_eq_zero (ZMod n) n @[simp] theorem natCast_self' (n : ℕ) : (n + 1 : ZMod (n + 1)) = 0 := by rw [← Nat.cast_add_one, natCast_self (n + 1)] lemma natCast_pow_eq_zero_of_le (p : ℕ) {m n : ℕ} (h : n ≤ m) : (p ^ m : ZMod (p ^ n)) = 0 := by obtain ⟨q, rfl⟩ := Nat.exists_eq_add_of_le h rw [pow_add, ← Nat.cast_pow] simp section UniversalProperty variable {n : ℕ} {R : Type*} section variable [AddGroupWithOne R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `ZMod.castHom` for a bundled version. -/ def cast : ∀ {n : ℕ}, ZMod n → R | 0 => Int.cast | _ + 1 => fun i => i.val @[simp] theorem cast_zero : (cast (0 : ZMod n) : R) = 0 := by delta ZMod.cast cases n · exact Int.cast_zero · simp theorem cast_eq_val [NeZero n] (a : ZMod n) : (cast a : R) = a.val := by cases n · cases NeZero.ne 0 rfl rfl variable {S : Type*} [AddGroupWithOne S] @[simp] theorem _root_.Prod.fst_zmod_cast (a : ZMod n) : (cast a : R × S).fst = cast a := by cases n · rfl · simp [ZMod.cast] @[simp] theorem _root_.Prod.snd_zmod_cast (a : ZMod n) : (cast a : R × S).snd = cast a := by cases n · rfl · simp [ZMod.cast] end /-- So-named because the coercion is `Nat.cast` into `ZMod`. For `Nat.cast` into an arbitrary ring, see `ZMod.natCast_val`. -/ theorem natCast_zmod_val {n : ℕ} [NeZero n] (a : ZMod n) : (a.val : ZMod n) = a := by cases n · cases NeZero.ne 0 rfl · apply Fin.cast_val_eq_self theorem natCast_rightInverse [NeZero n] : Function.RightInverse val ((↑) : ℕ → ZMod n) := natCast_zmod_val theorem natCast_zmod_surjective [NeZero n] : Function.Surjective ((↑) : ℕ → ZMod n) := natCast_rightInverse.surjective /-- So-named because the outer coercion is `Int.cast` into `ZMod`. For `Int.cast` into an arbitrary ring, see `ZMod.intCast_cast`. -/ @[norm_cast] theorem intCast_zmod_cast (a : ZMod n) : ((cast a : ℤ) : ZMod n) = a := by cases n · simp [ZMod.cast, ZMod] · dsimp [ZMod.cast] rw [Int.cast_natCast, natCast_zmod_val] theorem intCast_rightInverse : Function.RightInverse (cast : ZMod n → ℤ) ((↑) : ℤ → ZMod n) := intCast_zmod_cast theorem intCast_surjective : Function.Surjective ((↑) : ℤ → ZMod n) := intCast_rightInverse.surjective lemma «forall» {P : ZMod n → Prop} : (∀ x, P x) ↔ ∀ x : ℤ, P x := intCast_surjective.forall lemma «exists» {P : ZMod n → Prop} : (∃ x, P x) ↔ ∃ x : ℤ, P x := intCast_surjective.exists theorem cast_id : ∀ (n) (i : ZMod n), (ZMod.cast i : ZMod n) = i | 0, _ => Int.cast_id | _ + 1, i => natCast_zmod_val i @[simp] theorem cast_id' : (ZMod.cast : ZMod n → ZMod n) = id := funext (cast_id n) variable (R) [Ring R] /-- The coercions are respectively `Nat.cast` and `ZMod.cast`. -/ @[simp] theorem natCast_comp_val [NeZero n] : ((↑) : ℕ → R) ∘ (val : ZMod n → ℕ) = cast := by cases n · cases NeZero.ne 0 rfl rfl /-- The coercions are respectively `Int.cast`, `ZMod.cast`, and `ZMod.cast`. -/ @[simp] theorem intCast_comp_cast : ((↑) : ℤ → R) ∘ (cast : ZMod n → ℤ) = cast := by cases n · exact congr_arg (Int.cast ∘ ·) ZMod.cast_id' · ext simp [ZMod, ZMod.cast] variable {R} @[simp] theorem natCast_val [NeZero n] (i : ZMod n) : (i.val : R) = cast i := congr_fun (natCast_comp_val R) i @[simp] theorem intCast_cast (i : ZMod n) : ((cast i : ℤ) : R) = cast i := congr_fun (intCast_comp_cast R) i theorem cast_add_eq_ite {n : ℕ} (a b : ZMod n) : (cast (a + b) : ℤ) = if (n : ℤ) ≤ cast a + cast b then (cast a + cast b - n : ℤ) else cast a + cast b := by rcases n with - | n · simp; rfl change Fin (n + 1) at a b change ((((a + b) : Fin (n + 1)) : ℕ) : ℤ) = if ((n + 1 : ℕ) : ℤ) ≤ (a : ℕ) + b then _ else _ simp only [Fin.val_add_eq_ite, Int.natCast_succ] norm_cast split_ifs with h · rw [Nat.cast_sub h] congr · rfl section CharDvd /-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/ variable {m : ℕ} [CharP R m] @[simp] theorem cast_one (h : m ∣ n) : (cast (1 : ZMod n) : R) = 1 := by rcases n with - | n · exact Int.cast_one change ((1 % (n + 1) : ℕ) : R) = 1 cases n · rw [Nat.dvd_one] at h subst m subsingleton [CharP.CharOne.subsingleton] rw [Nat.mod_eq_of_lt] · exact Nat.cast_one exact Nat.lt_of_sub_eq_succ rfl @[simp] theorem cast_add (h : m ∣ n) (a b : ZMod n) : (cast (a + b : ZMod n) : R) = cast a + cast b := by cases n · apply Int.cast_add symm dsimp [ZMod, ZMod.cast, ZMod.val] rw [← Nat.cast_add, Fin.val_add, ← sub_eq_zero, ← Nat.cast_sub (Nat.mod_le _ _), @CharP.cast_eq_zero_iff R _ m] exact h.trans (Nat.dvd_sub_mod _) @[simp] theorem cast_mul (h : m ∣ n) (a b : ZMod n) : (cast (a * b : ZMod n) : R) = cast a * cast b := by cases n · apply Int.cast_mul symm dsimp [ZMod, ZMod.cast, ZMod.val] rw [← Nat.cast_mul, Fin.val_mul, ← sub_eq_zero, ← Nat.cast_sub (Nat.mod_le _ _), @CharP.cast_eq_zero_iff R _ m] exact h.trans (Nat.dvd_sub_mod _) /-- The canonical ring homomorphism from `ZMod n` to a ring of characteristic dividing `n`. See also `ZMod.lift` for a generalized version working in `AddGroup`s. -/ def castHom (h : m ∣ n) (R : Type*) [Ring R] [CharP R m] : ZMod n →+* R where toFun := cast map_zero' := cast_zero map_one' := cast_one h map_add' := cast_add h map_mul' := cast_mul h @[simp] theorem castHom_apply {h : m ∣ n} (i : ZMod n) : castHom h R i = cast i := rfl @[simp] theorem cast_sub (h : m ∣ n) (a b : ZMod n) : (cast (a - b : ZMod n) : R) = cast a - cast b := (castHom h R).map_sub a b @[simp] theorem cast_neg (h : m ∣ n) (a : ZMod n) : (cast (-a : ZMod n) : R) = -(cast a) := (castHom h R).map_neg a @[simp] theorem cast_pow (h : m ∣ n) (a : ZMod n) (k : ℕ) : (cast (a ^ k : ZMod n) : R) = (cast a) ^ k := (castHom h R).map_pow a k @[simp, norm_cast] theorem cast_natCast (h : m ∣ n) (k : ℕ) : (cast (k : ZMod n) : R) = k := map_natCast (castHom h R) k @[simp, norm_cast] theorem cast_intCast (h : m ∣ n) (k : ℤ) : (cast (k : ZMod n) : R) = k := map_intCast (castHom h R) k theorem castHom_surjective (h : m ∣ n) : Function.Surjective (castHom h (ZMod m)) := fun a ↦ by obtain ⟨a, rfl⟩ := intCast_surjective a; exact ⟨a, map_intCast ..⟩ end CharDvd section CharEq /-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/ variable [CharP R n] theorem cast_one' : (cast (1 : ZMod n) : R) = 1 := by simp theorem cast_add' (a b : ZMod n) : (cast (a + b : ZMod n) : R) = cast a + cast b := by simp theorem cast_mul' (a b : ZMod n) : (cast (a * b : ZMod n) : R) = cast a * cast b := by simp theorem cast_sub' (a b : ZMod n) : (cast (a - b : ZMod n) : R) = cast a - cast b := by simp theorem cast_pow' (a : ZMod n) (k : ℕ) : (cast (a ^ k : ZMod n) : R) = (cast a : R) ^ k := by simp @[norm_cast] theorem cast_natCast' (k : ℕ) : (cast (k : ZMod n) : R) = k := by simp @[norm_cast] theorem cast_intCast' (k : ℤ) : (cast (k : ZMod n) : R) = k := by simp variable (R) theorem castHom_injective : Function.Injective (ZMod.castHom (dvd_refl n) R) := by rw [injective_iff_map_eq_zero] intro x obtain ⟨k, rfl⟩ := ZMod.intCast_surjective x rw [map_intCast, CharP.intCast_eq_zero_iff R n, CharP.intCast_eq_zero_iff (ZMod n) n] exact id theorem castHom_bijective [Fintype R] (h : Fintype.card R = n) : Function.Bijective (ZMod.castHom (dvd_refl n) R) := by haveI : NeZero n := ⟨by intro hn rw [hn] at h exact (Fintype.card_eq_zero_iff.mp h).elim' 0⟩ rw [Fintype.bijective_iff_injective_and_card, ZMod.card, h, eq_self_iff_true, and_true] apply ZMod.castHom_injective /-- The unique ring isomorphism between `ZMod n` and a ring `R` of characteristic `n` and cardinality `n`. -/ noncomputable def ringEquiv [Fintype R] (h : Fintype.card R = n) : ZMod n ≃+* R := RingEquiv.ofBijective _ (ZMod.castHom_bijective R h) /-- The unique ring isomorphism between `ZMod p` and a ring `R` of cardinality a prime `p`. If you need any property of this isomorphism, first of all use `ringEquivOfPrime_eq_ringEquiv` below (after `have : CharP R p := ...`) and deduce it by the results about `ZMod.ringEquiv`. -/ noncomputable def ringEquivOfPrime [Fintype R] {p : ℕ} (hp : p.Prime) (hR : Fintype.card R = p) : ZMod p ≃+* R := have : Nontrivial R := Fintype.one_lt_card_iff_nontrivial.1 (hR ▸ hp.one_lt) -- The following line exists as `charP_of_card_eq_prime` in -- `Mathlib/Algebra/CharP/CharAndCard.lean`. have : CharP R p := (CharP.charP_iff_prime_eq_zero hp).2 (hR ▸ Nat.cast_card_eq_zero R) ZMod.ringEquiv R hR @[simp] lemma ringEquivOfPrime_eq_ringEquiv [Fintype R] {p : ℕ} [CharP R p] (hp : p.Prime) (hR : Fintype.card R = p) : ringEquivOfPrime R hp hR = ringEquiv R hR := rfl /-- The identity between `ZMod m` and `ZMod n` when `m = n`, as a ring isomorphism. -/ def ringEquivCongr {m n : ℕ} (h : m = n) : ZMod m ≃+* ZMod n := by rcases m with - | m <;> rcases n with - | n · exact RingEquiv.refl _ · exfalso exact n.succ_ne_zero h.symm · exfalso exact m.succ_ne_zero h · exact { finCongr h with map_mul' := fun a b => by dsimp [ZMod] ext rw [Fin.coe_cast, Fin.coe_mul, Fin.coe_mul, Fin.coe_cast, Fin.coe_cast, ← h] map_add' := fun a b => by dsimp [ZMod] ext rw [Fin.coe_cast, Fin.val_add, Fin.val_add, Fin.coe_cast, Fin.coe_cast, ← h] } @[simp] lemma ringEquivCongr_refl (a : ℕ) : ringEquivCongr (rfl : a = a) = .refl _ := by cases a <;> rfl lemma ringEquivCongr_refl_apply {a : ℕ} (x : ZMod a) : ringEquivCongr rfl x = x := by rw [ringEquivCongr_refl] rfl lemma ringEquivCongr_symm {a b : ℕ} (hab : a = b) : (ringEquivCongr hab).symm = ringEquivCongr hab.symm := by subst hab cases a <;> rfl lemma ringEquivCongr_trans {a b c : ℕ} (hab : a = b) (hbc : b = c) : (ringEquivCongr hab).trans (ringEquivCongr hbc) = ringEquivCongr (hab.trans hbc) := by subst hab hbc cases a <;> rfl lemma ringEquivCongr_ringEquivCongr_apply {a b c : ℕ} (hab : a = b) (hbc : b = c) (x : ZMod a) : ringEquivCongr hbc (ringEquivCongr hab x) = ringEquivCongr (hab.trans hbc) x := by rw [← ringEquivCongr_trans hab hbc] rfl lemma ringEquivCongr_val {a b : ℕ} (h : a = b) (x : ZMod a) : ZMod.val ((ZMod.ringEquivCongr h) x) = ZMod.val x := by subst h cases a <;> rfl lemma ringEquivCongr_intCast {a b : ℕ} (h : a = b) (z : ℤ) : ZMod.ringEquivCongr h z = z := map_intCast (ringEquivCongr h) z end CharEq end UniversalProperty variable {m n : ℕ} @[simp] theorem val_eq_zero : ∀ {n : ℕ} (a : ZMod n), a.val = 0 ↔ a = 0 | 0, _ => Int.natAbs_eq_zero | n + 1, a => by rw [Fin.ext_iff] exact Iff.rfl theorem intCast_eq_intCast_iff (a b : ℤ) (c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a ≡ b [ZMOD c] := CharP.intCast_eq_intCast (ZMod c) c theorem intCast_eq_intCast_iff' (a b : ℤ) (c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a % c = b % c := ZMod.intCast_eq_intCast_iff a b c theorem val_intCast {n : ℕ} (a : ℤ) [NeZero n] : ↑(a : ZMod n).val = a % n := by have hle : (0 : ℤ) ≤ ↑(a : ZMod n).val := Int.natCast_nonneg _ have hlt : ↑(a : ZMod n).val < (n : ℤ) := Int.ofNat_lt.mpr (ZMod.val_lt a) refine (Int.emod_eq_of_lt hle hlt).symm.trans ?_ rw [← ZMod.intCast_eq_intCast_iff', Int.cast_natCast, ZMod.natCast_val, ZMod.cast_id] theorem natCast_eq_natCast_iff (a b c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a ≡ b [MOD c] := by simpa [Int.natCast_modEq_iff] using ZMod.intCast_eq_intCast_iff a b c theorem natCast_eq_natCast_iff' (a b c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a % c = b % c := ZMod.natCast_eq_natCast_iff a b c theorem intCast_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : ZMod b) = 0 ↔ (b : ℤ) ∣ a := by rw [← Int.cast_zero, ZMod.intCast_eq_intCast_iff, Int.modEq_zero_iff_dvd] theorem intCast_eq_intCast_iff_dvd_sub (a b : ℤ) (c : ℕ) : (a : ZMod c) = ↑b ↔ ↑c ∣ b - a := by rw [ZMod.intCast_eq_intCast_iff, Int.modEq_iff_dvd] theorem natCast_eq_zero_iff (a b : ℕ) : (a : ZMod b) = 0 ↔ b ∣ a := by rw [← Nat.cast_zero, ZMod.natCast_eq_natCast_iff, Nat.modEq_zero_iff_dvd] @[deprecated (since := "2025-06-30")] alias natCast_zmod_eq_zero_iff_dvd := natCast_eq_zero_iff theorem coe_intCast (a : ℤ) : cast (a : ZMod n) = a % n := by cases n · rw [Int.ofNat_zero, Int.emod_zero, Int.cast_id]; rfl · rw [← val_intCast, val]; rfl lemma intCast_cast_add (x y : ZMod n) : (cast (x + y) : ℤ) = (cast x + cast y) % n := by rw [← ZMod.coe_intCast, Int.cast_add, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast] lemma intCast_cast_mul (x y : ZMod n) : (cast (x * y) : ℤ) = cast x * cast y % n := by rw [← ZMod.coe_intCast, Int.cast_mul, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast] lemma intCast_cast_sub (x y : ZMod n) : (cast (x - y) : ℤ) = (cast x - cast y) % n := by rw [← ZMod.coe_intCast, Int.cast_sub, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast] lemma intCast_cast_neg (x : ZMod n) : (cast (-x) : ℤ) = -cast x % n := by rw [← ZMod.coe_intCast, Int.cast_neg, ZMod.intCast_zmod_cast] @[simp] theorem val_neg_one (n : ℕ) : (-1 : ZMod n.succ).val = n := by dsimp [val, Fin.coe_neg] cases n · simp · dsimp [ZMod, ZMod.cast] rw [Fin.coe_neg_one] /-- `-1 : ZMod n` lifts to `n - 1 : R`. This avoids the characteristic assumption in `cast_neg`. -/ theorem cast_neg_one {R : Type*} [Ring R] (n : ℕ) : cast (-1 : ZMod n) = (n - 1 : R) := by rcases n with - | n · dsimp [ZMod, ZMod.cast]; simp · rw [← natCast_val, val_neg_one, Nat.cast_succ, add_sub_cancel_right] theorem cast_sub_one {R : Type*} [Ring R] {n : ℕ} (k : ZMod n) : (cast (k - 1 : ZMod n) : R) = (if k = 0 then (n : R) else cast k) - 1 := by split_ifs with hk · rw [hk, zero_sub, ZMod.cast_neg_one] · cases n · dsimp [ZMod, ZMod.cast] rw [Int.cast_sub, Int.cast_one] · dsimp [ZMod, ZMod.cast, ZMod.val] rw [Fin.coe_sub_one, if_neg] · rw [Nat.cast_sub, Nat.cast_one] rwa [Fin.ext_iff, Fin.val_zero, ← Ne, ← Nat.one_le_iff_ne_zero] at hk · exact hk theorem natCast_eq_iff (p : ℕ) (n : ℕ) (z : ZMod p) [NeZero p] : ↑n = z ↔ ∃ k, n = z.val + p * k := by constructor · rintro rfl refine ⟨n / p, ?_⟩ rw [val_natCast, Nat.mod_add_div] · rintro ⟨k, rfl⟩ rw [Nat.cast_add, natCast_zmod_val, Nat.cast_mul, natCast_self, zero_mul, add_zero] theorem intCast_eq_iff (p : ℕ) (n : ℤ) (z : ZMod p) [NeZero p] : ↑n = z ↔ ∃ k, n = z.val + p * k := by constructor · rintro rfl refine ⟨n / p, ?_⟩ rw [val_intCast, Int.emod_add_ediv] · rintro ⟨k, rfl⟩ rw [Int.cast_add, Int.cast_mul, Int.cast_natCast, Int.cast_natCast, natCast_val, ZMod.natCast_self, zero_mul, add_zero, cast_id] @[push_cast, simp] theorem intCast_mod (a : ℤ) (b : ℕ) : ((a % b : ℤ) : ZMod b) = (a : ZMod b) := by rw [ZMod.intCast_eq_intCast_iff] apply Int.mod_modEq theorem ker_intCastAddHom (n : ℕ) : (Int.castAddHom (ZMod n)).ker = AddSubgroup.zmultiples (n : ℤ) := by ext rw [Int.mem_zmultiples_iff, AddMonoidHom.mem_ker, Int.coe_castAddHom, intCast_zmod_eq_zero_iff_dvd] theorem cast_injective_of_le {m n : ℕ} [nzm : NeZero m] (h : m ≤ n) : Function.Injective (@cast (ZMod n) _ m) := by cases m with | zero => cases nzm; simp_all | succ m => rintro ⟨x, hx⟩ ⟨y, hy⟩ f simp only [cast, val, natCast_eq_natCast_iff', Nat.mod_eq_of_lt (hx.trans_le h), Nat.mod_eq_of_lt (hy.trans_le h)] at f apply Fin.ext exact f theorem cast_zmod_eq_zero_iff_of_le {m n : ℕ} [NeZero m] (h : m ≤ n) (a : ZMod m) : (cast a : ZMod n) = 0 ↔ a = 0 := by rw [← ZMod.cast_zero (n := m)] exact Injective.eq_iff' (cast_injective_of_le h) rfl @[simp] theorem natCast_toNat (p : ℕ) : ∀ {z : ℤ} (_h : 0 ≤ z), (z.toNat : ZMod p) = z | (n : ℕ), _h => by simp only [Int.cast_natCast, Int.toNat_natCast] | Int.negSucc n, h => by simp at h theorem val_injective (n : ℕ) [NeZero n] : Function.Injective (val : ZMod n → ℕ) := by cases n · cases NeZero.ne 0 rfl intro a b h dsimp [ZMod] ext exact h theorem val_one_eq_one_mod (n : ℕ) : (1 : ZMod n).val = 1 % n := by rw [← Nat.cast_one, val_natCast] theorem val_two_eq_two_mod (n : ℕ) : (2 : ZMod n).val = 2 % n := by rw [← Nat.cast_two, val_natCast] theorem val_one (n : ℕ) [Fact (1 < n)] : (1 : ZMod n).val = 1 := by rw [val_one_eq_one_mod] exact Nat.mod_eq_of_lt Fact.out lemma val_one'' : ∀ {n}, n ≠ 1 → (1 : ZMod n).val = 1 | 0, _ => rfl | 1, hn => by cases hn rfl | n + 2, _ => haveI : Fact (1 < n + 2) := ⟨by simp⟩ ZMod.val_one _ theorem val_add {n : ℕ} [NeZero n] (a b : ZMod n) : (a + b).val = (a.val + b.val) % n := by cases n · cases NeZero.ne 0 rfl · apply Fin.val_add theorem val_add_of_lt {n : ℕ} {a b : ZMod n} (h : a.val + b.val < n) : (a + b).val = a.val + b.val := by have : NeZero n := by constructor; rintro rfl; simp at h rw [ZMod.val_add, Nat.mod_eq_of_lt h] theorem val_add_val_of_le {n : ℕ} [NeZero n] {a b : ZMod n} (h : n ≤ a.val + b.val) : a.val + b.val = (a + b).val + n := by rw [val_add, Nat.add_mod_add_of_le_add_mod, Nat.mod_eq_of_lt (val_lt _), Nat.mod_eq_of_lt (val_lt _)] rwa [Nat.mod_eq_of_lt (val_lt _), Nat.mod_eq_of_lt (val_lt _)] theorem val_add_of_le {n : ℕ} [NeZero n] {a b : ZMod n} (h : n ≤ a.val + b.val) : (a + b).val = a.val + b.val - n := by rw [val_add_val_of_le h] exact eq_tsub_of_add_eq rfl theorem val_add_le {n : ℕ} (a b : ZMod n) : (a + b).val ≤ a.val + b.val := by cases n · simpa [ZMod.val] using Int.natAbs_add_le _ _ · simpa [ZMod.val_add] using Nat.mod_le _ _ theorem val_mul {n : ℕ} (a b : ZMod n) : (a * b).val = a.val * b.val % n := by cases n · rw [Nat.mod_zero] apply Int.natAbs_mul · apply Fin.val_mul theorem val_mul_le {n : ℕ} (a b : ZMod n) : (a * b).val ≤ a.val * b.val := by rw [val_mul] apply Nat.mod_le theorem val_mul_of_lt {n : ℕ} {a b : ZMod n} (h : a.val * b.val < n) : (a * b).val = a.val * b.val := by rw [val_mul] apply Nat.mod_eq_of_lt h theorem val_mul_iff_lt {n : ℕ} [NeZero n] (a b : ZMod n) : (a * b).val = a.val * b.val ↔ a.val * b.val < n := by constructor <;> intro h · rw [← h]; apply ZMod.val_lt · apply ZMod.val_mul_of_lt h instance nontrivial (n : ℕ) [Fact (1 < n)] : Nontrivial (ZMod n) := ⟨⟨0, 1, fun h => zero_ne_one <| calc 0 = (0 : ZMod n).val := by rw [val_zero] _ = (1 : ZMod n).val := congr_arg ZMod.val h _ = 1 := val_one n ⟩⟩ instance nontrivial' : Nontrivial (ZMod 0) := by delta ZMod; infer_instance lemma one_eq_zero_iff {n : ℕ} : (1 : ZMod n) = 0 ↔ n = 1 := by rw [← Nat.cast_one, natCast_eq_zero_iff, Nat.dvd_one] /-- The inversion on `ZMod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv : ∀ n : ℕ, ZMod n → ZMod n | 0, i => Int.sign i | n + 1, i => Nat.gcdA i.val (n + 1) instance (n : ℕ) : Inv (ZMod n) := ⟨inv n⟩ theorem inv_zero : ∀ n : ℕ, (0 : ZMod n)⁻¹ = 0 | 0 => Int.sign_zero | n + 1 => show (Nat.gcdA _ (n + 1) : ZMod (n + 1)) = 0 by rw [val_zero] unfold Nat.gcdA Nat.xgcd Nat.xgcdAux rfl theorem mul_inv_eq_gcd {n : ℕ} (a : ZMod n) : a * a⁻¹ = Nat.gcd a.val n := by rcases n with - | n · dsimp [ZMod] at a ⊢ calc _ = a * Int.sign a := rfl _ = a.natAbs := by rw [Int.mul_sign_self] _ = a.natAbs.gcd 0 := by rw [Nat.gcd_zero_right] · calc a * a⁻¹ = a * a⁻¹ + n.succ * Nat.gcdB (val a) n.succ := by rw [natCast_self, zero_mul, add_zero] _ = ↑(↑a.val * Nat.gcdA (val a) n.succ + n.succ * Nat.gcdB (val a) n.succ) := by push_cast rw [natCast_zmod_val] rfl _ = Nat.gcd a.val n.succ := by rw [← Nat.gcd_eq_gcd_ab a.val n.succ]; rfl @[simp] protected lemma inv_one (n : ℕ) : (1⁻¹ : ZMod n) = 1 := by obtain rfl | hn := eq_or_ne n 1 · exact Subsingleton.elim _ _ · simpa [ZMod.val_one'' hn] using mul_inv_eq_gcd (1 : ZMod n) @[simp] theorem natCast_mod (a : ℕ) (n : ℕ) : ((a % n : ℕ) : ZMod n) = a := (CharP.cast_eq_mod (ZMod n) n a).symm @[deprecated natCast_eq_natCast_iff (since := "2025-08-12")] theorem eq_iff_modEq_nat (n : ℕ) {a b : ℕ} : (a : ZMod n) = b ↔ a ≡ b [MOD n] := natCast_eq_natCast_iff a b n theorem eq_zero_iff_even {n : ℕ} : (n : ZMod 2) = 0 ↔ Even n := (CharP.cast_eq_zero_iff (ZMod 2) 2 n).trans even_iff_two_dvd.symm theorem eq_one_iff_odd {n : ℕ} : (n : ZMod 2) = 1 ↔ Odd n := by rw [← @Nat.cast_one (ZMod 2), ZMod.natCast_eq_natCast_iff, Nat.odd_iff, Nat.ModEq] theorem ne_zero_iff_odd {n : ℕ} : (n : ZMod 2) ≠ 0 ↔ Odd n := by constructor <;> · contrapose simp [eq_zero_iff_even] theorem coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : Nat.Coprime x n) : ((x : ZMod n) * (x : ZMod n)⁻¹) = 1 := by rw [Nat.Coprime, Nat.gcd_comm, Nat.gcd_rec] at h rw [mul_inv_eq_gcd, val_natCast, h, Nat.cast_one] lemma mul_val_inv (hmn : m.Coprime n) : (m * (m⁻¹ : ZMod n).val : ZMod n) = 1 := by obtain rfl | hn := eq_or_ne n 0 · simp [m.coprime_zero_right.1 hmn] haveI : NeZero n := ⟨hn⟩ rw [ZMod.natCast_zmod_val, ZMod.coe_mul_inv_eq_one _ hmn] lemma val_inv_mul (hmn : m.Coprime n) : ((m⁻¹ : ZMod n).val * m : ZMod n) = 1 := by rw [mul_comm, mul_val_inv hmn] /-- `unitOfCoprime` makes an element of `(ZMod n)ˣ` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unitOfCoprime {n : ℕ} (x : ℕ) (h : Nat.Coprime x n) : (ZMod n)ˣ := ⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩ @[simp] theorem coe_unitOfCoprime {n : ℕ} (x : ℕ) (h : Nat.Coprime x n) : (unitOfCoprime x h : ZMod n) = x := rfl theorem val_coe_unit_coprime {n : ℕ} (u : (ZMod n)ˣ) : Nat.Coprime (u : ZMod n).val n := by rcases n with - | n · rcases Int.units_eq_one_or u with (rfl | rfl) <;> simp apply Nat.coprime_of_mul_modEq_one ((u⁻¹ : Units (ZMod (n + 1))) : ZMod (n + 1)).val have := Units.ext_iff.1 (mul_inv_cancel u) rw [Units.val_one] at this rw [← natCast_eq_natCast_iff, Nat.cast_one, ← this]; clear this rw [← natCast_zmod_val ((u * u⁻¹ : Units (ZMod (n + 1))) : ZMod (n + 1))] rw [Units.val_mul, val_mul, natCast_mod] lemma isUnit_iff_coprime (m n : ℕ) : IsUnit (m : ZMod n) ↔ m.Coprime n := by refine ⟨fun H ↦ ?_, fun H ↦ (unitOfCoprime m H).isUnit⟩ have H' := val_coe_unit_coprime H.unit rw [IsUnit.unit_spec, val_natCast, Nat.coprime_iff_gcd_eq_one] at H' rw [Nat.coprime_iff_gcd_eq_one, Nat.gcd_comm, ← H'] exact Nat.gcd_rec n m lemma isUnit_prime_iff_not_dvd {n p : ℕ} (hp : p.Prime) : IsUnit (p : ZMod n) ↔ ¬p ∣ n := by rw [isUnit_iff_coprime, Nat.Prime.coprime_iff_not_dvd hp] lemma isUnit_prime_of_not_dvd {n p : ℕ} (hp : p.Prime) (h : ¬ p ∣ n) : IsUnit (p : ZMod n) := (isUnit_prime_iff_not_dvd hp).mpr h @[simp] theorem inv_coe_unit {n : ℕ} (u : (ZMod n)ˣ) : (u : ZMod n)⁻¹ = (u⁻¹ : (ZMod n)ˣ) := by have := congr_arg ((↑) : ℕ → ZMod n) (val_coe_unit_coprime u) rw [← mul_inv_eq_gcd, Nat.cast_one] at this let u' : (ZMod n)ˣ := ⟨u, (u : ZMod n)⁻¹, this, by rwa [mul_comm]⟩ have h : u = u' := by apply Units.ext rfl rw [h] rfl theorem mul_inv_of_unit {n : ℕ} (a : ZMod n) (h : IsUnit a) : a * a⁻¹ = 1 := by rcases h with ⟨u, rfl⟩ rw [inv_coe_unit, u.mul_inv] theorem inv_mul_of_unit {n : ℕ} (a : ZMod n) (h : IsUnit a) : a⁻¹ * a = 1 := by rw [mul_comm, mul_inv_of_unit a h] -- TODO: If we changed `⁻¹` so that `ZMod n` is always a `DivisionMonoid`, -- then we could use the general lemma `inv_eq_of_mul_eq_one` protected theorem inv_eq_of_mul_eq_one (n : ℕ) (a b : ZMod n) (h : a * b = 1) : a⁻¹ = b := left_inv_eq_right_inv (inv_mul_of_unit a ⟨⟨a, b, h, mul_comm a b ▸ h⟩, rfl⟩) h @[simp] theorem inv_neg_one (n : ℕ) : (-1 : ZMod n)⁻¹ = -1 := ZMod.inv_eq_of_mul_eq_one n (-1) (-1) (by simp) lemma inv_mul_eq_one_of_isUnit {n : ℕ} {a : ZMod n} (ha : IsUnit a) (b : ZMod n) : a⁻¹ * b = 1 ↔ a = b := by -- ideally, this would be `ha.inv_mul_eq_one`, but `ZMod n` is not a `DivisionMonoid`... -- (see the "TODO" above) refine ⟨fun H ↦ ?_, fun H ↦ H ▸ a.inv_mul_of_unit ha⟩ apply_fun (a * ·) at H rwa [← mul_assoc, a.mul_inv_of_unit ha, one_mul, mul_one, eq_comm] at H -- TODO: this equivalence is true for `ZMod 0 = ℤ`, but needs to use different functions. /-- Equivalence between the units of `ZMod n` and the subtype of terms `x : ZMod n` for which `x.val` is coprime to `n` -/ def unitsEquivCoprime {n : ℕ} [NeZero n] : (ZMod n)ˣ ≃ { x : ZMod n // Nat.Coprime x.val n } where toFun x := ⟨x, val_coe_unit_coprime x⟩ invFun x := unitOfCoprime x.1.val x.2 left_inv := fun ⟨_, _, _, _⟩ => Units.ext (natCast_zmod_val _) right_inv := fun ⟨_, _⟩ => by simp /-- The **Chinese remainder theorem**. For a pair of coprime natural numbers, `m` and `n`, the rings `ZMod (m * n)` and `ZMod m × ZMod n` are isomorphic. See `Ideal.quotientInfRingEquivPiQuotient` for the Chinese remainder theorem for ideals in any ring. -/ def chineseRemainder {m n : ℕ} (h : m.Coprime n) : ZMod (m * n) ≃+* ZMod m × ZMod n := let to_fun : ZMod (m * n) → ZMod m × ZMod n := ZMod.castHom (show m.lcm n ∣ m * n by simp [Nat.lcm_dvd_iff]) (ZMod m × ZMod n) let inv_fun : ZMod m × ZMod n → ZMod (m * n) := fun x => if m * n = 0 then if m = 1 then cast (RingHom.snd _ (ZMod n) x) else cast (RingHom.fst (ZMod m) _ x) else Nat.chineseRemainder h x.1.val x.2.val have inv : Function.LeftInverse inv_fun to_fun ∧ Function.RightInverse inv_fun to_fun := if hmn0 : m * n = 0 then by rcases h.eq_of_mul_eq_zero hmn0 with (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) · constructor · intro x; rfl · rintro ⟨x, y⟩ fin_cases y simp [to_fun, inv_fun, castHom, Prod.ext_iff, eq_iff_true_of_subsingleton] · constructor · intro x; rfl · rintro ⟨x, y⟩ fin_cases x simp [to_fun, inv_fun, castHom, Prod.ext_iff, eq_iff_true_of_subsingleton] else by haveI : NeZero (m * n) := ⟨hmn0⟩ haveI : NeZero m := ⟨left_ne_zero_of_mul hmn0⟩ haveI : NeZero n := ⟨right_ne_zero_of_mul hmn0⟩ have left_inv : Function.LeftInverse inv_fun to_fun := by intro x dsimp only [to_fun, inv_fun, ZMod.castHom_apply] conv_rhs => rw [← ZMod.natCast_zmod_val x] rw [if_neg hmn0, ZMod.natCast_eq_natCast_iff, ← Nat.modEq_and_modEq_iff_modEq_mul h, Prod.fst_zmod_cast, Prod.snd_zmod_cast] refine ⟨(Nat.chineseRemainder h (cast x : ZMod m).val (cast x : ZMod n).val).2.left.trans ?_, (Nat.chineseRemainder h (cast x : ZMod m).val (cast x : ZMod n).val).2.right.trans ?_⟩ · rw [← ZMod.natCast_eq_natCast_iff, ZMod.natCast_zmod_val, ZMod.natCast_val] · rw [← ZMod.natCast_eq_natCast_iff, ZMod.natCast_zmod_val, ZMod.natCast_val] exact ⟨left_inv, left_inv.rightInverse_of_card_le (by simp)⟩ { toFun := to_fun, invFun := inv_fun, map_mul' := RingHom.map_mul _ map_add' := RingHom.map_add _ left_inv := inv.1 right_inv := inv.2 } lemma subsingleton_iff {n : ℕ} : Subsingleton (ZMod n) ↔ n = 1 := by constructor · obtain (_ | _ | n) := n · simpa [ZMod] using not_subsingleton _ · simp [ZMod] · simpa [ZMod] using not_subsingleton _ · rintro rfl infer_instance lemma nontrivial_iff {n : ℕ} : Nontrivial (ZMod n) ↔ n ≠ 1 := by rw [← not_subsingleton_iff_nontrivial, subsingleton_iff] -- todo: this can be made a `Unique` instance. instance subsingleton_units : Subsingleton (ZMod 2)ˣ := ⟨by decide⟩ @[simp] theorem add_self_eq_zero_iff_eq_zero {n : ℕ} (hn : Odd n) {a : ZMod n} : a + a = 0 ↔ a = 0 := by rw [Nat.odd_iff, ← Nat.two_dvd_ne_zero, ← Nat.prime_two.coprime_iff_not_dvd] at hn rw [← mul_two, ← @Nat.cast_two (ZMod n), ← ZMod.coe_unitOfCoprime 2 hn, Units.mul_left_eq_zero] theorem ne_neg_self {n : ℕ} (hn : Odd n) {a : ZMod n} (ha : a ≠ 0) : a ≠ -a := by rwa [Ne, eq_neg_iff_add_eq_zero, add_self_eq_zero_iff_eq_zero hn] theorem neg_one_ne_one {n : ℕ} [Fact (2 < n)] : (-1 : ZMod n) ≠ 1 := CharP.neg_one_ne_one (ZMod n) n @[simp] theorem neg_eq_self_mod_two (a : ZMod 2) : -a = a := by fin_cases a <;> apply Fin.ext <;> simp; rfl @[simp] theorem intCast_abs_mod_two (a : ℤ) : (↑|a| : ZMod 2) = a := by cases le_total a 0 <;> simp [abs_of_nonneg, abs_of_nonpos, *] theorem natAbs_mod_two (a : ℤ) : (a.natAbs : ZMod 2) = a := by simp theorem val_ne_zero {n : ℕ} (a : ZMod n) : a.val ≠ 0 ↔ a ≠ 0 := (val_eq_zero a).not @[simp] theorem val_pos {n : ℕ} {a : ZMod n} : 0 < a.val ↔ a ≠ 0 := by simp [pos_iff_ne_zero] theorem val_eq_one : ∀ {n : ℕ} (_ : 1 < n) (a : ZMod n), a.val = 1 ↔ a = 1 | 0, hn, _ | 1, hn, _ => by simp at hn | n + 2, _, _ => by simp only [val, ZMod, Fin.ext_iff, Fin.val_one] theorem neg_eq_self_iff {n : ℕ} (a : ZMod n) : -a = a ↔ a = 0 ∨ 2 * a.val = n := by rw [neg_eq_iff_add_eq_zero, ← two_mul] cases n · rw [@mul_eq_zero ℤ, @mul_eq_zero ℕ, val_eq_zero] exact ⟨fun h => h.elim (by simp) Or.inl, fun h => Or.inr (h.elim id fun h => h.elim (by simp) id)⟩ conv_lhs => rw [← a.natCast_zmod_val, ← Nat.cast_two, ← Nat.cast_mul, natCast_eq_zero_iff] constructor · rintro ⟨m, he⟩ rcases m with - | m · rw [mul_zero, mul_eq_zero] at he rcases he with (⟨⟨⟩⟩ | he) exact Or.inl (a.val_eq_zero.1 he) cases m · right rwa [show 0 + 1 = 1 from rfl, mul_one] at he refine (a.val_lt.not_ge <| Nat.le_of_mul_le_mul_left ?_ zero_lt_two).elim rw [he, mul_comm] apply Nat.mul_le_mul_left simp · rintro (rfl | h) · rw [val_zero, mul_zero] apply dvd_zero · rw [h] theorem val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : ZMod n).val = a := by rw [val_natCast, Nat.mod_eq_of_lt h] theorem val_cast_zmod_lt {m : ℕ} [NeZero m] (n : ℕ) [NeZero n] (a : ZMod m) : (a.cast : ZMod n).val < m := by rcases m with (⟨⟩|⟨m⟩); · cases NeZero.ne 0 rfl by_cases h : m < n · rcases n with (⟨⟩|⟨n⟩); · simp at h rw [← natCast_val, val_cast_of_lt] · apply a.val_lt apply lt_of_le_of_lt (Nat.le_of_lt_succ (ZMod.val_lt a)) h · rw [not_lt] at h apply lt_of_lt_of_le (ZMod.val_lt _) (le_trans h (Nat.le_succ m)) theorem neg_val' {n : ℕ} [NeZero n] (a : ZMod n) : (-a).val = (n - a.val) % n := calc (-a).val = val (-a) % n := by rw [Nat.mod_eq_of_lt (-a).val_lt] _ = (n - val a) % n := Nat.ModEq.add_right_cancel' (val a) (by rw [Nat.ModEq, ← val_add, neg_add_cancel, tsub_add_cancel_of_le a.val_le, Nat.mod_self, val_zero]) theorem neg_val {n : ℕ} [NeZero n] (a : ZMod n) : (-a).val = if a = 0 then 0 else n - a.val := by rw [neg_val'] by_cases h : a = 0; · rw [if_pos h, h, val_zero, tsub_zero, Nat.mod_self] rw [if_neg h] apply Nat.mod_eq_of_lt apply Nat.sub_lt (NeZero.pos n) contrapose! h rwa [Nat.le_zero, val_eq_zero] at h theorem val_neg_of_ne_zero {n : ℕ} [nz : NeZero n] (a : ZMod n) [na : NeZero a] : (- a).val = n - a.val := by simp_all [neg_val a, na.out] theorem val_sub {n : ℕ} [NeZero n] {a b : ZMod n} (h : b.val ≤ a.val) : (a - b).val = a.val - b.val := by by_cases hb : b = 0 · cases hb; simp · have : NeZero b := ⟨hb⟩ rw [sub_eq_add_neg, val_add, val_neg_of_ne_zero, ← Nat.add_sub_assoc (le_of_lt (val_lt _)), add_comm, Nat.add_sub_assoc h, Nat.add_mod_left] apply Nat.mod_eq_of_lt (tsub_lt_of_lt (val_lt _)) theorem val_cast_eq_val_of_lt {m n : ℕ} [nzm : NeZero m] {a : ZMod m} (h : a.val < n) : (a.cast : ZMod n).val = a.val := by have nzn : NeZero n := by constructor; rintro rfl; simp at h cases m with | zero => cases nzm; simp_all | succ m => cases n with | zero => cases nzn; simp_all | succ n => exact Fin.val_cast_of_lt h theorem cast_cast_zmod_of_le {m n : ℕ} [hm : NeZero m] (h : m ≤ n) (a : ZMod m) : (cast (cast a : ZMod n) : ZMod m) = a := by have : NeZero n := ⟨((Nat.zero_lt_of_ne_zero hm.out).trans_le h).ne'⟩ rw [cast_eq_val, val_cast_eq_val_of_lt (a.val_lt.trans_le h), natCast_zmod_val] theorem val_pow {m n : ℕ} {a : ZMod n} [ilt : Fact (1 < n)] (h : a.val ^ m < n) : (a ^ m).val = a.val ^ m := by induction m with | zero => simp [ZMod.val_one] | succ m ih => have : a.val ^ m < n := by obtain rfl | ha := eq_or_ne a 0 · by_cases hm : m = 0 · cases hm; simp [ilt.out] · simp only [val_zero, ne_eq, hm, not_false_eq_true, zero_pow, Nat.zero_lt_of_lt h] · exact lt_of_le_of_lt (Nat.pow_le_pow_right (by rwa [gt_iff_lt, ZMod.val_pos]) (Nat.le_succ m)) h rw [pow_succ, ZMod.val_mul, ih this, ← pow_succ, Nat.mod_eq_of_lt h] theorem val_pow_le {m n : ℕ} [Fact (1 < n)] {a : ZMod n} : (a ^ m).val ≤ a.val ^ m := by induction m with | zero => simp [ZMod.val_one] | succ m ih => rw [pow_succ, pow_succ] apply le_trans (ZMod.val_mul_le _ _) apply Nat.mul_le_mul_right _ ih theorem natAbs_min_of_le_div_two (n : ℕ) (x y : ℤ) (he : (x : ZMod n) = y) (hl : x.natAbs ≤ n / 2) : x.natAbs ≤ y.natAbs := by rw [intCast_eq_intCast_iff_dvd_sub] at he obtain ⟨m, he⟩ := he rw [sub_eq_iff_eq_add] at he subst he obtain rfl | hm := eq_or_ne m 0 · rw [mul_zero, zero_add] apply hl.trans rw [← add_le_add_iff_right x.natAbs] refine le_trans (le_trans ((add_le_add_iff_left _).2 hl) ?_) (Int.natAbs_sub_le _ _) rw [add_sub_cancel_right, Int.natAbs_mul, Int.natAbs_natCast] refine le_trans ?_ (Nat.le_mul_of_pos_right _ <| Int.natAbs_pos.2 hm) rw [← mul_two]; apply Nat.div_mul_le_self end ZMod theorem RingHom.ext_zmod {n : ℕ} {R : Type*} [NonAssocSemiring R] (f g : ZMod n →+* R) : f = g := by ext a obtain ⟨k, rfl⟩ := ZMod.intCast_surjective a let φ : ℤ →+* R := f.comp (Int.castRingHom (ZMod n)) let ψ : ℤ →+* R := g.comp (Int.castRingHom (ZMod n)) change φ k = ψ k rw [φ.ext_int ψ] namespace ZMod variable {n : ℕ} {R : Type*} instance subsingleton_ringHom [Semiring R] : Subsingleton (ZMod n →+* R) := ⟨RingHom.ext_zmod⟩ instance subsingleton_ringEquiv [Semiring R] : Subsingleton (ZMod n ≃+* R) := ⟨fun f g => by rw [RingEquiv.coe_ringHom_inj_iff] apply RingHom.ext_zmod _ _⟩ @[simp] theorem ringHom_map_cast [NonAssocRing R] (f : R →+* ZMod n) (k : ZMod n) : f (cast k) = k := by cases n · dsimp [ZMod, ZMod.cast] at f k ⊢; simp · dsimp [ZMod.cast] rw [map_natCast, natCast_zmod_val] /-- Any ring homomorphism into `ZMod n` has a right inverse. -/ theorem ringHom_rightInverse [NonAssocRing R] (f : R →+* ZMod n) : Function.RightInverse (cast : ZMod n → R) f := ringHom_map_cast f /-- Any ring homomorphism into `ZMod n` is surjective. -/ theorem ringHom_surjective [NonAssocRing R] (f : R →+* ZMod n) : Function.Surjective f := (ringHom_rightInverse f).surjective @[simp] lemma castHom_self : ZMod.castHom dvd_rfl (ZMod n) = RingHom.id (ZMod n) := Subsingleton.elim _ _ @[simp] lemma castHom_comp {m d : ℕ} (hm : n ∣ m) (hd : m ∣ d) : (castHom hm (ZMod n)).comp (castHom hd (ZMod m)) = castHom (dvd_trans hm hd) (ZMod n) := RingHom.ext_zmod _ _ section lift variable (n) {A : Type*} [AddGroup A] /-- The map from `ZMod n` induced by `f : ℤ →+ A` that maps `n` to `0`. -/ def lift : { f : ℤ →+ A // f n = 0 } ≃ (ZMod n →+ A) := (Equiv.subtypeEquivRight <| by intro f rw [ker_intCastAddHom] constructor · rintro hf _ ⟨x, rfl⟩ simp only [f.map_zsmul, zsmul_zero, f.mem_ker, hf] · intro h exact h (AddSubgroup.mem_zmultiples _)).trans <| (Int.castAddHom (ZMod n)).liftOfRightInverse cast intCast_zmod_cast variable (f : { f : ℤ →+ A // f n = 0 }) @[simp] theorem lift_coe (x : ℤ) : lift n f (x : ZMod n) = f.val x := AddMonoidHom.liftOfRightInverse_comp_apply _ _ (fun _ => intCast_zmod_cast _) _ _ theorem lift_castAddHom (x : ℤ) : lift n f (Int.castAddHom (ZMod n) x) = f.1 x := AddMonoidHom.liftOfRightInverse_comp_apply _ _ (fun _ => intCast_zmod_cast _) _ _ @[simp] theorem lift_comp_coe : ZMod.lift n f ∘ ((↑) : ℤ → _) = f := funext <| lift_coe _ _ @[simp] theorem lift_comp_castAddHom : (ZMod.lift n f).comp (Int.castAddHom (ZMod n)) = f := AddMonoidHom.ext <| lift_castAddHom _ _ lemma lift_injective {f : {f : ℤ →+ A // f n = 0}} : Injective (lift n f) ↔ ∀ m, f.1 m = 0 → (m : ZMod n) = 0 := by simp only [← AddMonoidHom.ker_eq_bot_iff, eq_bot_iff, SetLike.le_def, ZMod.intCast_surjective.forall, ZMod.lift_coe, AddMonoidHom.mem_ker, AddSubgroup.mem_bot] end lift end ZMod /-! ### Groups of bounded torsion For `G` a group and `n` a natural number, `G` having torsion dividing `n` (`∀ x : G, n • x = 0`) can be derived from `Module R G` where `R` has characteristic dividing `n`. It is however painful to have the API for such groups `G` stated in this generality, as `R` does not appear anywhere in the lemmas' return type. Instead of writing the API in terms of a general `R`, we therefore specialise to the canonical ring of order `n`, namely `ZMod n`. This spelling `Module (ZMod n) G` has the extra advantage of providing the canonical action by `ZMod n`. It is however Type-valued, so we might want to acquire a Prop-valued version in the future. -/ section Module variable {n : ℕ} {S G : Type*} [AddCommGroup G] [SetLike S G] [AddSubgroupClass S G] {K : S} {x : G} section general variable [Module (ZMod n) G] {x : G} lemma zmod_smul_mem (hx : x ∈ K) : ∀ a : ZMod n, a • x ∈ K := by simpa [ZMod.forall, Int.cast_smul_eq_zsmul] using zsmul_mem hx /-- This cannot be made an instance because of the `[Module (ZMod n) G]` argument and the fact that `n` only appears in the second argument of `SMulMemClass`, which is an `OutParam`. -/ lemma smulMemClass : SMulMemClass S (ZMod n) G where smul_mem _ _ {_x} hx := zmod_smul_mem hx _ namespace AddSubgroupClass instance instZModSMul : SMul (ZMod n) K where smul a x := ⟨a • x, zmod_smul_mem x.2 _⟩ @[simp, norm_cast] lemma coe_zmod_smul (a : ZMod n) (x : K) : ↑(a • x) = (a • x : G) := rfl instance instZModModule : Module (ZMod n) K := Subtype.coe_injective.module _ (AddSubmonoidClass.subtype K) coe_zmod_smul end AddSubgroupClass variable (n) lemma ZModModule.char_nsmul_eq_zero (x : G) : n • x = 0 := by simp [← Nat.cast_smul_eq_nsmul (ZMod n)] variable (G) in lemma ZModModule.char_ne_one [Nontrivial G] : n ≠ 1 := by rintro rfl obtain ⟨x, hx⟩ := exists_ne (0 : G) exact hx <| by simpa using char_nsmul_eq_zero 1 x variable (G) in lemma ZModModule.two_le_char [NeZero n] [Nontrivial G] : 2 ≤ n := by have := NeZero.ne n have := char_ne_one n G omega lemma ZModModule.periodicPts_add_left [NeZero n] (x : G) : periodicPts (x + ·) = .univ := Set.eq_univ_of_forall fun y ↦ ⟨n, NeZero.pos n, by simpa [char_nsmul_eq_zero, IsPeriodicPt] using isFixedPt_id _⟩ end general section two variable [Module (ZMod 2) G] lemma ZModModule.add_self (x : G) : x + x = 0 := by simpa [two_nsmul] using char_nsmul_eq_zero 2 x lemma ZModModule.neg_eq_self (x : G) : -x = x := by simp [add_self, eq_comm, ← sub_eq_zero] lemma ZModModule.sub_eq_add (x y : G) : x - y = x + y := by simp [neg_eq_self, sub_eq_add_neg] lemma ZModModule.add_add_add_cancel (x y z : G) : (x + y) + (y + z) = x + z := by simpa [sub_eq_add] using sub_add_sub_cancel x y z end two end Module section Group variable {α : Type*} [Group α] {n : ℕ} @[to_additive (attr := simp) nsmul_zmod_val_inv_nsmul] lemma pow_zmod_val_inv_pow (hn : (Nat.card α).gcd n = 1) (a : α) : (a ^ (n⁻¹ : ZMod (Nat.card α)).val) ^ n = a := by replace hn : (Nat.card α).Coprime n := hn rw [← pow_mul', ← pow_mod_natCard, ← ZMod.val_natCast, Nat.cast_mul, ZMod.mul_val_inv hn.symm, ZMod.val_one_eq_one_mod, pow_mod_natCard, pow_one] @[to_additive (attr := simp) zmod_val_inv_nsmul_nsmul] lemma pow_pow_zmod_val_inv (hn : (Nat.card α).gcd n = 1) (a : α) : (a ^ n) ^ (n⁻¹ : ZMod (Nat.card α)).val = a := by rw [pow_right_comm, pow_zmod_val_inv_pow hn] end Group open ZMod /-- The range of `(m * · + k)` on natural numbers is the set of elements `≥ k` in the residue class of `k` mod `m`. -/ lemma Nat.range_mul_add (m k : ℕ) : Set.range (fun n : ℕ ↦ m * n + k) = {n : ℕ | (n : ZMod m) = k ∧ k ≤ n} := by ext n simp only [Set.mem_range, Set.mem_setOf_eq] conv => enter [1, 1, y]; rw [add_comm, eq_comm] refine ⟨fun ⟨a, ha⟩ ↦ ⟨?_, le_iff_exists_add.mpr ⟨_, ha⟩⟩, fun ⟨H₁, H₂⟩ ↦ ?_⟩ · simpa using congr_arg ((↑) : ℕ → ZMod m) ha · obtain ⟨a, ha⟩ := le_iff_exists_add.mp H₂ simp only [ha, Nat.cast_add, add_eq_left, ZMod.natCast_eq_zero_iff] at H₁ obtain ⟨b, rfl⟩ := H₁ exact ⟨b, ha⟩ /-- Equivalence between `ℕ` and `ZMod N × ℕ`, sending `n` to `(n mod N, n / N)`. -/ def Nat.residueClassesEquiv (N : ℕ) [NeZero N] : ℕ ≃ ZMod N × ℕ where toFun n := (↑n, n / N) invFun p := p.1.val + N * p.2 left_inv n := by simpa only [val_natCast] using mod_add_div n N right_inv p := by ext1 · simp only [add_comm p.1.val, cast_add, cast_mul, natCast_self, zero_mul, natCast_val, cast_id', id_eq, zero_add] · simp only [add_comm p.1.val, mul_add_div (NeZero.pos _), (Nat.div_eq_zero_iff).2 <| .inr p.1.val_lt, add_zero]
GRewrite.lean
/- Copyright (c) 2023 Sebastian Zimmer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Zimmer, Mario Carneiro, Heather Macbeth, Jovan Gerbscheid -/ import Mathlib.Tactic.GRewrite.Elab /-! # The generalized rewriting tactic The `grw`/`grewrite` tactic is a generalization of the `rewrite` tactic that works with relations other than equality. The core implementation of `grewrite` is in the file `Tactic.GRewrite.Core` -/
Basic.lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.Group.Action.Pi import Mathlib.Algebra.Notation.Indicator import Mathlib.Algebra.GroupWithZero.Action.Units import Mathlib.Algebra.Module.NatInt import Mathlib.Algebra.NoZeroSMulDivisors.Defs import Mathlib.Algebra.Ring.Invertible /-! # Further basic results about modules. -/ assert_not_exists Nonneg.inv Multiset open Function Set universe u v variable {α R M M₂ : Type*} @[simp] theorem Units.neg_smul [Ring R] [AddCommGroup M] [Module R M] (u : Rˣ) (x : M) : -u • x = -(u • x) := by rw [Units.smul_def, Units.val_neg, _root_.neg_smul, Units.smul_def] @[simp] theorem invOf_two_smul_add_invOf_two_smul (R) [Semiring R] [AddCommMonoid M] [Module R M] [Invertible (2 : R)] (x : M) : (⅟2 : R) • x + (⅟2 : R) • x = x := Convex.combo_self invOf_two_add_invOf_two _ theorem map_inv_natCast_smul [AddCommMonoid M] [AddCommMonoid M₂] {F : Type*} [FunLike F M M₂] [AddMonoidHomClass F M M₂] (f : F) (R S : Type*) [DivisionSemiring R] [DivisionSemiring S] [Module R M] [Module S M₂] (n : ℕ) (x : M) : f ((n⁻¹ : R) • x) = (n⁻¹ : S) • f x := by by_cases hR : (n : R) = 0 <;> by_cases hS : (n : S) = 0 · simp [hR, hS, map_zero f] · suffices ∀ y, f y = 0 by rw [this, this, smul_zero] clear x intro x rw [← inv_smul_smul₀ hS (f x), ← map_natCast_smul f R S] simp [hR, map_zero f] · suffices ∀ y, f y = 0 by simp [this] clear x intro x rw [← smul_inv_smul₀ hR x, map_natCast_smul f R S, hS, zero_smul] · rw [← inv_smul_smul₀ hS (f _), ← map_natCast_smul f R S, smul_inv_smul₀ hR] theorem map_inv_intCast_smul [AddCommGroup M] [AddCommGroup M₂] {F : Type*} [FunLike F M M₂] [AddMonoidHomClass F M M₂] (f : F) (R S : Type*) [DivisionRing R] [DivisionRing S] [Module R M] [Module S M₂] (z : ℤ) (x : M) : f ((z⁻¹ : R) • x) = (z⁻¹ : S) • f x := by obtain ⟨n, rfl | rfl⟩ := z.eq_nat_or_neg · rw [Int.cast_natCast, Int.cast_natCast, map_inv_natCast_smul _ R S] · simp_rw [Int.cast_neg, Int.cast_natCast, inv_neg, neg_smul, map_neg, map_inv_natCast_smul _ R S] /-- If `E` is a vector space over two division semirings `R` and `S`, then scalar multiplications agree on inverses of natural numbers in `R` and `S`. -/ theorem inv_natCast_smul_eq {E : Type*} (R S : Type*) [AddCommMonoid E] [DivisionSemiring R] [DivisionSemiring S] [Module R E] [Module S E] (n : ℕ) (x : E) : (n⁻¹ : R) • x = (n⁻¹ : S) • x := map_inv_natCast_smul (AddMonoidHom.id E) R S n x /-- If `E` is a vector space over two division rings `R` and `S`, then scalar multiplications agree on inverses of integer numbers in `R` and `S`. -/ theorem inv_intCast_smul_eq {E : Type*} (R S : Type*) [AddCommGroup E] [DivisionRing R] [DivisionRing S] [Module R E] [Module S E] (n : ℤ) (x : E) : (n⁻¹ : R) • x = (n⁻¹ : S) • x := map_inv_intCast_smul (AddMonoidHom.id E) R S n x /-- If `E` is a vector space over a division semiring `R` and has a monoid action by `α`, then that action commutes by scalar multiplication of inverses of natural numbers in `R`. -/ theorem inv_natCast_smul_comm {α E : Type*} (R : Type*) [AddCommMonoid E] [DivisionSemiring R] [Monoid α] [Module R E] [DistribMulAction α E] (n : ℕ) (s : α) (x : E) : (n⁻¹ : R) • s • x = s • (n⁻¹ : R) • x := (map_inv_natCast_smul (DistribMulAction.toAddMonoidHom E s) R R n x).symm /-- If `E` is a vector space over a division ring `R` and has a monoid action by `α`, then that action commutes by scalar multiplication of inverses of integers in `R` -/ theorem inv_intCast_smul_comm {α E : Type*} (R : Type*) [AddCommGroup E] [DivisionRing R] [Monoid α] [Module R E] [DistribMulAction α E] (n : ℤ) (s : α) (x : E) : (n⁻¹ : R) • s • x = s • (n⁻¹ : R) • x := (map_inv_intCast_smul (DistribMulAction.toAddMonoidHom E s) R R n x).symm namespace Function lemma support_smul_subset_left [Zero R] [Zero M] [SMulWithZero R M] (f : α → R) (g : α → M) : support (f • g) ⊆ support f := fun x hfg hf ↦ hfg <| by rw [Pi.smul_apply', hf, zero_smul] -- Changed (2024-01-21): this lemma was generalised; -- the old version is now called `support_const_smul_subset`. lemma support_smul_subset_right [Zero M] [SMulZeroClass R M] (f : α → R) (g : α → M) : support (f • g) ⊆ support g := fun x hbf hf ↦ hbf <| by rw [Pi.smul_apply', hf, smul_zero] lemma support_const_smul_of_ne_zero [Zero R] [Zero M] [SMulWithZero R M] [NoZeroSMulDivisors R M] (c : R) (g : α → M) (hc : c ≠ 0) : support (c • g) = support g := ext fun x ↦ by simp only [hc, mem_support, Pi.smul_apply, Ne, smul_eq_zero, false_or] lemma support_smul [Zero R] [Zero M] [SMulWithZero R M] [NoZeroSMulDivisors R M] (f : α → R) (g : α → M) : support (f • g) = support f ∩ support g := ext fun _ => smul_ne_zero_iff lemma support_const_smul_subset [Zero M] [SMulZeroClass R M] (a : R) (f : α → M) : support (a • f) ⊆ support f := support_smul_subset_right (fun _ ↦ a) f end Function namespace Set section SMulZeroClass variable [Zero M] [SMulZeroClass R M] lemma indicator_smul_apply (s : Set α) (r : α → R) (f : α → M) (a : α) : indicator s (fun a ↦ r a • f a) a = r a • indicator s f a := by dsimp only [indicator] split_ifs exacts [rfl, (smul_zero (r a)).symm] lemma indicator_smul (s : Set α) (r : α → R) (f : α → M) : indicator s (fun a ↦ r a • f a) = fun a ↦ r a • indicator s f a := funext <| indicator_smul_apply s r f lemma indicator_const_smul_apply (s : Set α) (r : R) (f : α → M) (a : α) : indicator s (r • f ·) a = r • indicator s f a := indicator_smul_apply s (fun _ ↦ r) f a lemma indicator_const_smul (s : Set α) (r : R) (f : α → M) : indicator s (r • f ·) = (r • indicator s f ·) := funext <| indicator_const_smul_apply s r f end SMulZeroClass section SMulWithZero variable [Zero R] [Zero M] [SMulWithZero R M] lemma indicator_smul_apply_left (s : Set α) (r : α → R) (f : α → M) (a : α) : indicator s (fun a ↦ r a • f a) a = indicator s r a • f a := by dsimp only [indicator] split_ifs exacts [rfl, (zero_smul _ (f a)).symm] lemma indicator_smul_left (s : Set α) (r : α → R) (f : α → M) : indicator s (fun a ↦ r a • f a) = fun a ↦ indicator s r a • f a := funext <| indicator_smul_apply_left _ _ _ lemma indicator_smul_const_apply (s : Set α) (r : α → R) (m : M) (a : α) : indicator s (r · • m) a = indicator s r a • m := indicator_smul_apply_left _ _ _ _ lemma indicator_smul_const (s : Set α) (r : α → R) (m : M) : indicator s (r · • m) = (indicator s r · • m) := funext <| indicator_smul_const_apply _ _ _ end SMulWithZero section MulZeroOneClass variable [MulZeroOneClass R] lemma smul_indicator_one_apply (s : Set α) (r : R) (a : α) : r • s.indicator (1 : α → R) a = s.indicator (fun _ ↦ r) a := by simp_rw [← indicator_const_smul_apply, Pi.one_apply, smul_eq_mul, mul_one] end MulZeroOneClass end Set
mathlib.lean
import Mathlib -- We verify that `exact?` copes with all of Mathlib. -- On `v4.7.0-rc1` this revealed a cache corruption problem. /-- info: Try this: exact Nat.one_pos -/ #guard_msgs in example : 0 < 1 := by exact?
Field.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca, Johan Commelin -/ import Mathlib.Algebra.Polynomial.FieldDivision import Mathlib.Algebra.Polynomial.Lifts import Mathlib.FieldTheory.Minpoly.Basic import Mathlib.RingTheory.Algebraic.Integral import Mathlib.RingTheory.LocalRing.Basic /-! # Minimal polynomials on an algebra over a field This file specializes the theory of minpoly to the setting of field extensions and derives some well-known properties, amongst which the fact that minimal polynomials are irreducible, and uniquely determined by their defining property. -/ open Polynomial Set Function minpoly namespace minpoly variable {A B : Type*} variable (A) [Field A] section Ring variable [Ring B] [Algebra A B] (x : B) /-- If an element `x` is a root of a nonzero polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. See also `minpoly.IsIntegrallyClosed.degree_le_of_ne_zero` which relaxes the assumptions on `A` in exchange for stronger assumptions on `B`. -/ theorem degree_le_of_ne_zero {p : A[X]} (pnz : p ≠ 0) (hp : Polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := calc degree (minpoly A x) ≤ degree (p * C (leadingCoeff p)⁻¹) := min A x (monic_mul_leadingCoeff_inv pnz) (by simp [hp]) _ = degree p := degree_mul_leadingCoeff_inv p pnz theorem ne_zero_of_finite (e : B) [FiniteDimensional A B] : minpoly A e ≠ 0 := minpoly.ne_zero <| .of_finite A _ /-- The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. See also `minpoly.IsIntegrallyClosed.Minpoly.unique` which relaxes the assumptions on `A` in exchange for stronger assumptions on `B`. -/ theorem unique {p : A[X]} (pmonic : p.Monic) (hp : Polynomial.aeval x p = 0) (pmin : ∀ q : A[X], q.Monic → Polynomial.aeval x q = 0 → degree p ≤ degree q) : p = minpoly A x := by have hx : IsIntegral A x := ⟨p, pmonic, hp⟩ symm; apply eq_of_sub_eq_zero by_contra hnz apply degree_le_of_ne_zero A x hnz (by simp [hp]) |>.not_gt apply degree_sub_lt _ (minpoly.ne_zero hx) · rw [(monic hx).leadingCoeff, pmonic.leadingCoeff] · exact le_antisymm (min A x pmonic hp) (pmin (minpoly A x) (monic hx) (aeval A x)) /-- If an element `x` is a root of a polynomial `p`, then the minimal polynomial of `x` divides `p`. See also `minpoly.isIntegrallyClosed_dvd` which relaxes the assumptions on `A` in exchange for stronger assumptions on `B`. -/ theorem dvd {p : A[X]} (hp : Polynomial.aeval x p = 0) : minpoly A x ∣ p := by by_cases hp0 : p = 0 · simp only [hp0, dvd_zero] have hx : IsIntegral A x := IsAlgebraic.isIntegral ⟨p, hp0, hp⟩ rw [← modByMonic_eq_zero_iff_dvd (monic hx)] by_contra hnz apply degree_le_of_ne_zero A x hnz ((aeval_modByMonic_eq_self_of_root (monic hx) (aeval _ _)).trans hp) |>.not_gt exact degree_modByMonic_lt _ (monic hx) variable {A x} in lemma dvd_iff {p : A[X]} : minpoly A x ∣ p ↔ Polynomial.aeval x p = 0 := ⟨fun ⟨q, hq⟩ ↦ by rw [hq, map_mul, aeval, zero_mul], minpoly.dvd A x⟩ theorem isRadical [IsReduced B] : IsRadical (minpoly A x) := fun n p dvd ↦ by rw [dvd_iff] at dvd ⊢; rw [map_pow] at dvd; exact IsReduced.eq_zero _ ⟨n, dvd⟩ theorem dvd_map_of_isScalarTower (A K : Type*) {R : Type*} [CommRing A] [Field K] [Ring R] [Algebra A K] [Algebra A R] [Algebra K R] [IsScalarTower A K R] (x : R) : minpoly K x ∣ (minpoly A x).map (algebraMap A K) := by refine minpoly.dvd K x ?_ rw [aeval_map_algebraMap, minpoly.aeval] theorem dvd_map_of_isScalarTower' (R : Type*) {S : Type*} (K L : Type*) [CommRing R] [CommRing S] [Field K] [Ring L] [Algebra R S] [Algebra R K] [Algebra S L] [Algebra K L] [Algebra R L] [IsScalarTower R K L] [IsScalarTower R S L] (s : S) : minpoly K (algebraMap S L s) ∣ map (algebraMap R K) (minpoly R s) := by apply minpoly.dvd K (algebraMap S L s) rw [← map_aeval_eq_aeval_map, minpoly.aeval, map_zero] rw [← IsScalarTower.algebraMap_eq, ← IsScalarTower.algebraMap_eq] /-- If `y` is a conjugate of `x` over a field `K`, then it is a conjugate over a subring `R`. -/ theorem aeval_of_isScalarTower (R : Type*) {K T U : Type*} [CommRing R] [Field K] [CommRing T] [Algebra R K] [Algebra K T] [Algebra R T] [IsScalarTower R K T] [CommSemiring U] [Algebra K U] [Algebra R U] [IsScalarTower R K U] (x : T) (y : U) (hy : Polynomial.aeval y (minpoly K x) = 0) : Polynomial.aeval y (minpoly R x) = 0 := aeval_map_algebraMap K y (minpoly R x) ▸ eval₂_eq_zero_of_dvd_of_eval₂_eq_zero (algebraMap K U) y (minpoly.dvd_map_of_isScalarTower R K x) hy /-- If a subfield `F` of `E` contains all the coefficients of `minpoly E a`, then `minpoly F a` maps to `minpoly E a` via `algebraMap F E`. -/ theorem map_algebraMap {F E A : Type*} [Field F] [Field E] [CommRing A] [Algebra F E] [Algebra E A] [Algebra F A] [IsScalarTower F E A] {a : A} (ha : IsIntegral F a) (h : minpoly E a ∈ lifts (algebraMap F E)) : (minpoly F a).map (algebraMap F E) = minpoly E a := by refine eq_of_monic_of_dvd_of_natDegree_le (minpoly.monic ha.tower_top) ((algebraMap F E).injective.monic_map_iff.mp <| minpoly.monic ha) (minpoly.dvd E a (by simp)) ?_ obtain ⟨g, hg, hgdeg, hgmon⟩ := lifts_and_natDegree_eq_and_monic h (minpoly.monic ha.tower_top) rw [natDegree_map, ← hgdeg] refine natDegree_le_of_dvd (minpoly.dvd F a ?_) hgmon.ne_zero rw [← aeval_map_algebraMap A, IsScalarTower.algebraMap_eq F E A, ← coe_mapRingHom, ← mapRingHom_comp, RingHom.comp_apply, coe_mapRingHom, coe_mapRingHom, hg, aeval_map_algebraMap, minpoly.aeval] /-- See also `minpoly.ker_eval` which relaxes the assumptions on `A` in exchange for stronger assumptions on `B`. -/ @[simp] lemma ker_aeval_eq_span_minpoly : RingHom.ker (Polynomial.aeval x) = A[X] ∙ minpoly A x := by ext p simp_rw [RingHom.mem_ker, ← minpoly.dvd_iff, Submodule.mem_span_singleton, dvd_iff_exists_eq_mul_left, smul_eq_mul, eq_comm (a := p)] variable {A x} theorem eq_of_irreducible_of_monic [Nontrivial B] {p : A[X]} (hp1 : Irreducible p) (hp2 : Polynomial.aeval x p = 0) (hp3 : p.Monic) : p = minpoly A x := let ⟨_, hq⟩ := dvd A x hp2 eq_of_monic_of_associated hp3 (monic ⟨p, ⟨hp3, hp2⟩⟩) <| mul_one (minpoly A x) ▸ hq.symm ▸ Associated.mul_left _ (associated_one_iff_isUnit.2 <| (hp1.isUnit_or_isUnit hq).resolve_left <| not_isUnit A x) theorem eq_iff_aeval_eq_zero [Nontrivial B] {p : A[X]} (irr : Irreducible p) (monic : p.Monic) : p = minpoly A x ↔ Polynomial.aeval x p = 0 := ⟨(· ▸ aeval A x), (eq_of_irreducible_of_monic irr · monic)⟩ theorem eq_iff_aeval_minpoly_eq_zero [IsDomain B] {C} [Ring C] [Algebra A C] [Nontrivial C] {b : B} (h : IsIntegral A b) {c : C} : minpoly A b = minpoly A c ↔ Polynomial.aeval c (minpoly A b) = 0 := eq_iff_aeval_eq_zero (irreducible h) (monic h) theorem eq_of_irreducible [Nontrivial B] {p : A[X]} (hp1 : Irreducible p) (hp2 : Polynomial.aeval x p = 0) : p * C p.leadingCoeff⁻¹ = minpoly A x := by have : p.leadingCoeff ≠ 0 := leadingCoeff_ne_zero.mpr hp1.ne_zero apply eq_of_irreducible_of_monic · exact Associated.irreducible ⟨⟨C p.leadingCoeff⁻¹, C p.leadingCoeff, by rwa [← C_mul, inv_mul_cancel₀, C_1], by rwa [← C_mul, mul_inv_cancel₀, C_1]⟩, rfl⟩ hp1 · rw [aeval_mul, hp2, zero_mul] · rwa [Polynomial.Monic, leadingCoeff_mul, leadingCoeff_C, mul_inv_cancel₀] theorem add_algebraMap {B : Type*} [CommRing B] [Algebra A B] (x : B) (a : A) : minpoly A (x + algebraMap A B a) = (minpoly A x).comp (X - C a) := by by_cases hx : IsIntegral A x · refine (minpoly.unique _ _ ((minpoly.monic hx).comp_X_sub_C _) ?_ fun q qmo hq => ?_).symm · simp [aeval_comp] · have : (Polynomial.aeval x) (q.comp (X + C a)) = 0 := by simpa [aeval_comp] using hq have H := minpoly.min A x (qmo.comp_X_add_C _) this rw [degree_eq_natDegree qmo.ne_zero, degree_eq_natDegree ((minpoly.monic hx).comp_X_sub_C _).ne_zero, natDegree_comp, natDegree_X_sub_C, mul_one] rwa [degree_eq_natDegree (minpoly.ne_zero hx), degree_eq_natDegree (qmo.comp_X_add_C _).ne_zero, natDegree_comp, natDegree_X_add_C, mul_one] at H · rw [minpoly.eq_zero hx, minpoly.eq_zero, zero_comp] refine fun h ↦ hx ?_ simpa only [add_sub_cancel_right] using IsIntegral.sub h (isIntegral_algebraMap (x := a)) theorem sub_algebraMap {B : Type*} [CommRing B] [Algebra A B] (x : B) (a : A) : minpoly A (x - algebraMap A B a) = (minpoly A x).comp (X + C a) := by simpa [sub_eq_add_neg] using add_algebraMap x (-a) theorem neg {B : Type*} [Ring B] [Algebra A B] (x : B) : minpoly A (- x) = (-1) ^ (natDegree (minpoly A x)) * (minpoly A x).comp (- X) := by by_cases hx : IsIntegral A x · refine (minpoly.unique _ _ ((minpoly.monic hx).neg_one_pow_natDegree_mul_comp_neg_X) ?_ fun q qmo hq => ?_).symm · simp [aeval_comp] · have : (Polynomial.aeval x) ((-1) ^ q.natDegree * q.comp (- X)) = 0 := by simpa [aeval_comp] using hq have H := minpoly.min A x qmo.neg_one_pow_natDegree_mul_comp_neg_X this have n1 := ((minpoly.monic hx).neg_one_pow_natDegree_mul_comp_neg_X).ne_zero have n2 := qmo.neg_one_pow_natDegree_mul_comp_neg_X.ne_zero rw [degree_eq_natDegree qmo.ne_zero, degree_eq_natDegree n1, natDegree_mul (by simp) (right_ne_zero_of_mul n1), natDegree_comp] rw [degree_eq_natDegree (minpoly.ne_zero hx), degree_eq_natDegree qmo.neg_one_pow_natDegree_mul_comp_neg_X.ne_zero, natDegree_mul (by simp) (right_ne_zero_of_mul n2), natDegree_comp] at H simpa using H · rw [minpoly.eq_zero hx, minpoly.eq_zero, zero_comp] · simp only [natDegree_zero, pow_zero, mul_zero] · exact IsIntegral.neg_iff.not.mpr hx theorem map_eq_of_equiv_equiv {R S T : Type*} [CommRing R] [IsDomain R] [Ring S] [Ring T] [IsDomain S] [IsDomain T] [Algebra R S] [Algebra A T] [Algebra.IsIntegral R S] {f : R ≃+* A} {g : S ≃+* T} (hcomp : (algebraMap A T).comp f = (g : S →+* T).comp (algebraMap R S)) (x : S) : map f (minpoly R x) = minpoly A (g x) := by refine minpoly.eq_of_irreducible_of_monic ?_ ?_ ?_ · rw [← mapEquiv_apply, MulEquiv.irreducible_iff] exact minpoly.irreducible (Algebra.IsIntegral.isIntegral x) · simpa using (map_aeval_eq_aeval_map hcomp (minpoly R x) x).symm · exact (monic (Algebra.IsIntegral.isIntegral x)).map _ section AlgHomFintype open scoped Classical in /-- A technical finiteness result. -/ noncomputable def Fintype.subtypeProd {E : Type*} {X : Set E} (hX : X.Finite) {L : Type*} (F : E → Multiset L) : Fintype (∀ x : X, { l : L // l ∈ F x }) := @Pi.instFintype _ _ _ (Finite.fintype hX) _ variable (F E K : Type*) [Field F] [Ring E] [CommRing K] [IsDomain K] [Algebra F E] [Algebra F K] [FiniteDimensional F E] /-- Function from Hom_K(E,L) to pi type Π (x : basis), roots of min poly of x -/ def rootsOfMinPolyPiType (φ : E →ₐ[F] K) (x : range (Module.finBasis F E : _ → E)) : { l : K // l ∈ (minpoly F x.1).aroots K } := ⟨φ x, by rw [mem_roots_map (minpoly.ne_zero_of_finite F x.val), ← aeval_def, aeval_algHom_apply, minpoly.aeval, map_zero]⟩ theorem aux_inj_roots_of_min_poly : Injective (rootsOfMinPolyPiType F E K) := by intro f g h -- needs explicit coercion on the RHS suffices (f : E →ₗ[F] K) = (g : E →ₗ[F] K) by rwa [DFunLike.ext'_iff] at this ⊢ rw [funext_iff] at h exact LinearMap.ext_on (Module.finBasis F E).span_eq fun e he => Subtype.ext_iff.mp (h ⟨e, he⟩) /-- Given field extensions `E/F` and `K/F`, with `E/F` finite, there are finitely many `F`-algebra homomorphisms `E →ₐ[K] K`. -/ noncomputable instance AlgHom.fintype : Fintype (E →ₐ[F] K) := @Fintype.ofInjective _ _ (Fintype.subtypeProd (finite_range (Module.finBasis F E)) fun e => (minpoly F e).aroots K) _ (aux_inj_roots_of_min_poly F E K) end AlgHomFintype variable (B) [Nontrivial B] /-- If `B/K` is a nontrivial algebra over a field, and `x` is an element of `K`, then the minimal polynomial of `algebraMap K B x` is `X - C x`. -/ theorem eq_X_sub_C (a : A) : minpoly A (algebraMap A B a) = X - C a := eq_X_sub_C_of_algebraMap_inj a (algebraMap A B).injective theorem eq_X_sub_C' (a : A) : minpoly A a = X - C a := eq_X_sub_C A a variable (A) /-- The minimal polynomial of `0` is `X`. -/ @[simp] theorem zero : minpoly A (0 : B) = X := by simpa only [add_zero, C_0, sub_eq_add_neg, neg_zero, RingHom.map_zero] using eq_X_sub_C B (0 : A) /-- The minimal polynomial of `1` is `X - 1`. -/ @[simp] theorem one : minpoly A (1 : B) = X - 1 := by simpa only [RingHom.map_one, C_1, sub_eq_add_neg] using eq_X_sub_C B (1 : A) end Ring section IsDomain variable [Ring B] [IsDomain B] [Algebra A B] variable {A} {x : B} /-- A minimal polynomial is prime. -/ theorem prime (hx : IsIntegral A x) : Prime (minpoly A x) := by refine ⟨minpoly.ne_zero hx, not_isUnit A x, ?_⟩ rintro p q ⟨d, h⟩ have : Polynomial.aeval x (p * q) = 0 := by simp [h, aeval A x] replace : Polynomial.aeval x p = 0 ∨ Polynomial.aeval x q = 0 := by simpa exact Or.imp (dvd A x) (dvd A x) this /-- If `L/K` is a field extension and an element `y` of `K` is a root of the minimal polynomial of an element `x ∈ L`, then `y` maps to `x` under the field embedding. -/ theorem root {x : B} (hx : IsIntegral A x) {y : A} (h : IsRoot (minpoly A x) y) : algebraMap A B y = x := by have key : minpoly A x = X - C y := eq_of_monic_of_associated (monic hx) (monic_X_sub_C y) (associated_of_dvd_dvd ((irreducible_X_sub_C y).dvd_symm (irreducible hx) (dvd_iff_isRoot.2 h)) (dvd_iff_isRoot.2 h)) have := aeval A x rwa [key, map_sub, aeval_X, aeval_C, sub_eq_zero, eq_comm] at this /-- The constant coefficient of the minimal polynomial of `x` is `0` if and only if `x = 0`. -/ @[simp] theorem coeff_zero_eq_zero (hx : IsIntegral A x) : coeff (minpoly A x) 0 = 0 ↔ x = 0 := by constructor · intro h have zero_root := zero_isRoot_of_coeff_zero_eq_zero h rw [← root hx zero_root] exact RingHom.map_zero _ · rintro rfl simp /-- The minimal polynomial of a nonzero element has nonzero constant coefficient. -/ theorem coeff_zero_ne_zero (hx : IsIntegral A x) (h : x ≠ 0) : coeff (minpoly A x) 0 ≠ 0 := by contrapose! h simpa only [hx, coeff_zero_eq_zero] using h end IsDomain end minpoly section AlgHom variable {K L} [Field K] [CommRing L] [IsDomain L] [Algebra K L] /-- The minimal polynomial (over `K`) of `σ : Gal(L/K)` is `X ^ (orderOf σ) - 1`. -/ lemma minpoly_algEquiv_toLinearMap (σ : L ≃ₐ[K] L) (hσ : IsOfFinOrder σ) : minpoly K σ.toLinearMap = X ^ (orderOf σ) - C 1 := by refine (minpoly.unique _ _ (monic_X_pow_sub_C _ hσ.orderOf_pos.ne.symm) ?_ ?_).symm · rw [map_sub] simp [← AlgEquiv.pow_toLinearMap, pow_orderOf_eq_one] · intros q hq hs rw [degree_eq_natDegree hq.ne_zero, degree_X_pow_sub_C hσ.orderOf_pos, Nat.cast_le, ← not_lt] intro H rw [aeval_eq_sum_range' H, ← Fin.sum_univ_eq_sum_range] at hs simp_rw [← AlgEquiv.pow_toLinearMap] at hs apply hq.ne_zero simpa using Fintype.linearIndependent_iff.mp (((linearIndependent_algHom_toLinearMap' K L L).comp _ AlgEquiv.coe_algHom_injective).comp _ (Subtype.val_injective.comp ((finEquivPowers hσ).injective))) (q.coeff ∘ (↑)) hs ⟨_, H⟩ /-- The minimal polynomial (over `K`) of `σ : Gal(L/K)` is `X ^ (orderOf σ) - 1`. -/ lemma minpoly_algHom_toLinearMap (σ : L →ₐ[K] L) (hσ : IsOfFinOrder σ) : minpoly K σ.toLinearMap = X ^ (orderOf σ) - C 1 := by have : orderOf σ = orderOf (AlgEquiv.algHomUnitsEquiv _ _ hσ.unit) := by rw [← MonoidHom.coe_coe, orderOf_injective, ← orderOf_units, IsOfFinOrder.val_unit] exact (AlgEquiv.algHomUnitsEquiv K L).injective rw [this, ← minpoly_algEquiv_toLinearMap] · apply congr_arg ext simp · rwa [← orderOf_pos_iff, ← this, orderOf_pos_iff] end AlgHom
Comp.lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import Mathlib.Analysis.Calculus.FDeriv.Basic /-! # The derivative of a composition (chain rule) For detailed documentation of the Fréchet derivative, see the module docstring of `Analysis/Calculus/FDeriv/Basic.lean`. This file contains the usual formulas (and existence assertions) for the derivative of composition of functions (the chain rule). -/ open Filter Asymptotics ContinuousLinearMap Set Metric Topology NNReal ENNReal noncomputable section section variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] variable {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] variable {G : Type*} [NormedAddCommGroup G] [NormedSpace 𝕜 G] variable {G' : Type*} [NormedAddCommGroup G'] [NormedSpace 𝕜 G'] variable {f g : E → F} {f' g' : E →L[𝕜] F} {x : E} {s : Set E} {L : Filter E} section Composition /-! ### Derivative of the composition of two functions For composition lemmas, we put `x` explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition. -/ variable (x) theorem HasFDerivAtFilter.comp {g : F → G} {g' : F →L[𝕜] G} {L' : Filter F} (hg : HasFDerivAtFilter g g' (f x) L') (hf : HasFDerivAtFilter f f' x L) (hL : Tendsto f L L') : HasFDerivAtFilter (g ∘ f) (g'.comp f') x L := by let eq₁ := (g'.isBigO_comp _ _).trans_isLittleO hf.isLittleO let eq₂ := (hg.isLittleO.comp_tendsto hL).trans_isBigO hf.isBigO_sub refine .of_isLittleO <| eq₂.triangle <| eq₁.congr_left fun x' => ?_ simp /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : HasFDerivAtFilter g g' (f x) (L.map f)) (hf : HasFDerivAtFilter f f' x L) : HasFDerivAtFilter (g ∘ f) (g'.comp f') x L := by have := calc (fun x' => g (f x') - g (f x) - g' (f x' - f x)) =o[L] fun x' => f x' - f x := hg.isLittleO.comp_tendsto le_rfl _ =O[L] fun x' => x' - x := hf.isBigO_sub refine .of_isLittleO <| this.triangle ?_ calc (fun x' : E => g' (f x' - f x) - g'.comp f' (x' - x)) _ =ᶠ[L] fun x' => g' (f x' - f x - f' (x' - x)) := Eventually.of_forall fun x' => by simp _ =O[L] fun x' => f x' - f x - f' (x' - x) := g'.isBigO_comp _ _ _ =o[L] fun x' => x' - x := hf.isLittleO @[fun_prop] theorem HasFDerivWithinAt.comp {g : F → G} {g' : F →L[𝕜] G} {t : Set F} (hg : HasFDerivWithinAt g g' t (f x)) (hf : HasFDerivWithinAt f f' s x) (hst : MapsTo f s t) : HasFDerivWithinAt (g ∘ f) (g'.comp f') s x := HasFDerivAtFilter.comp x hg hf <| hf.continuousWithinAt.tendsto_nhdsWithin hst @[fun_prop] theorem HasFDerivAt.comp_hasFDerivWithinAt {g : F → G} {g' : F →L[𝕜] G} (hg : HasFDerivAt g g' (f x)) (hf : HasFDerivWithinAt f f' s x) : HasFDerivWithinAt (g ∘ f) (g'.comp f') s x := hg.comp x hf hf.continuousWithinAt @[fun_prop] theorem HasFDerivWithinAt.comp_of_tendsto {g : F → G} {g' : F →L[𝕜] G} {t : Set F} (hg : HasFDerivWithinAt g g' t (f x)) (hf : HasFDerivWithinAt f f' s x) (hst : Tendsto f (𝓝[s] x) (𝓝[t] f x)) : HasFDerivWithinAt (g ∘ f) (g'.comp f') s x := HasFDerivAtFilter.comp x hg hf hst theorem HasFDerivWithinAt.comp_hasFDerivAt {g : F → G} {g' : F →L[𝕜] G} {t : Set F} (hg : HasFDerivWithinAt g g' t (f x)) (hf : HasFDerivAt f f' x) (ht : ∀ᶠ x' in 𝓝 x, f x' ∈ t) : HasFDerivAt (g ∘ f) (g' ∘L f') x := HasFDerivAtFilter.comp x hg hf <| tendsto_nhdsWithin_iff.mpr ⟨hf.continuousAt, ht⟩ theorem HasFDerivWithinAt.comp_hasFDerivAt_of_eq {g : F → G} {g' : F →L[𝕜] G} {t : Set F} {y : F} (hg : HasFDerivWithinAt g g' t y) (hf : HasFDerivAt f f' x) (ht : ∀ᶠ x' in 𝓝 x, f x' ∈ t) (hy : y = f x) : HasFDerivAt (g ∘ f) (g' ∘L f') x := by subst y; exact hg.comp_hasFDerivAt x hf ht /-- The chain rule. -/ @[fun_prop] theorem HasFDerivAt.comp {g : F → G} {g' : F →L[𝕜] G} (hg : HasFDerivAt g g' (f x)) (hf : HasFDerivAt f f' x) : HasFDerivAt (g ∘ f) (g'.comp f') x := HasFDerivAtFilter.comp x hg hf hf.continuousAt @[fun_prop] theorem DifferentiableWithinAt.comp {g : F → G} {t : Set F} (hg : DifferentiableWithinAt 𝕜 g t (f x)) (hf : DifferentiableWithinAt 𝕜 f s x) (h : MapsTo f s t) : DifferentiableWithinAt 𝕜 (g ∘ f) s x := (hg.hasFDerivWithinAt.comp x hf.hasFDerivWithinAt h).differentiableWithinAt @[fun_prop] theorem DifferentiableWithinAt.comp' {g : F → G} {t : Set F} (hg : DifferentiableWithinAt 𝕜 g t (f x)) (hf : DifferentiableWithinAt 𝕜 f s x) : DifferentiableWithinAt 𝕜 (g ∘ f) (s ∩ f ⁻¹' t) x := hg.comp x (hf.mono inter_subset_left) inter_subset_right @[fun_prop] theorem DifferentiableAt.fun_comp' {f : E → F} {g : F → G} (hg : DifferentiableAt 𝕜 g (f x)) (hf : DifferentiableAt 𝕜 f x) : DifferentiableAt 𝕜 (fun x ↦ g (f x)) x := (hg.hasFDerivAt.comp x hf.hasFDerivAt).differentiableAt @[fun_prop] theorem DifferentiableAt.comp {g : F → G} (hg : DifferentiableAt 𝕜 g (f x)) (hf : DifferentiableAt 𝕜 f x) : DifferentiableAt 𝕜 (g ∘ f) x := (hg.hasFDerivAt.comp x hf.hasFDerivAt).differentiableAt @[fun_prop] theorem DifferentiableAt.comp_differentiableWithinAt {g : F → G} (hg : DifferentiableAt 𝕜 g (f x)) (hf : DifferentiableWithinAt 𝕜 f s x) : DifferentiableWithinAt 𝕜 (g ∘ f) s x := hg.differentiableWithinAt.comp x hf (mapsTo_univ _ _) theorem fderivWithin_comp {g : F → G} {t : Set F} (hg : DifferentiableWithinAt 𝕜 g t (f x)) (hf : DifferentiableWithinAt 𝕜 f s x) (h : MapsTo f s t) (hxs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (g ∘ f) s x = (fderivWithin 𝕜 g t (f x)).comp (fderivWithin 𝕜 f s x) := (hg.hasFDerivWithinAt.comp x hf.hasFDerivWithinAt h).fderivWithin hxs theorem fderivWithin_comp_of_eq {g : F → G} {t : Set F} {y : F} (hg : DifferentiableWithinAt 𝕜 g t y) (hf : DifferentiableWithinAt 𝕜 f s x) (h : MapsTo f s t) (hxs : UniqueDiffWithinAt 𝕜 s x) (hy : f x = y) : fderivWithin 𝕜 (g ∘ f) s x = (fderivWithin 𝕜 g t (f x)).comp (fderivWithin 𝕜 f s x) := by subst hy; exact fderivWithin_comp _ hg hf h hxs /-- A variant for the derivative of a composition, written without `∘`. -/ theorem fderivWithin_comp' {g : F → G} {t : Set F} (hg : DifferentiableWithinAt 𝕜 g t (f x)) (hf : DifferentiableWithinAt 𝕜 f s x) (h : MapsTo f s t) (hxs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (fun y ↦ g (f y)) s x = (fderivWithin 𝕜 g t (f x)).comp (fderivWithin 𝕜 f s x) := fderivWithin_comp _ hg hf h hxs /-- A variant for the derivative of a composition, written without `∘`. -/ theorem fderivWithin_comp_of_eq' {g : F → G} {t : Set F} {y : F} (hg : DifferentiableWithinAt 𝕜 g t y) (hf : DifferentiableWithinAt 𝕜 f s x) (h : MapsTo f s t) (hxs : UniqueDiffWithinAt 𝕜 s x) (hy : f x = y) : fderivWithin 𝕜 (fun y ↦ g (f y)) s x = (fderivWithin 𝕜 g t (f x)).comp (fderivWithin 𝕜 f s x) := by subst hy; exact fderivWithin_comp _ hg hf h hxs /-- A version of `fderivWithin_comp` that is useful to rewrite the composition of two derivatives into a single derivative. This version always applies, but creates a new side-goal `f x = y`. -/ theorem fderivWithin_fderivWithin {g : F → G} {f : E → F} {x : E} {y : F} {s : Set E} {t : Set F} (hg : DifferentiableWithinAt 𝕜 g t y) (hf : DifferentiableWithinAt 𝕜 f s x) (h : MapsTo f s t) (hxs : UniqueDiffWithinAt 𝕜 s x) (hy : f x = y) (v : E) : fderivWithin 𝕜 g t y (fderivWithin 𝕜 f s x v) = fderivWithin 𝕜 (g ∘ f) s x v := by subst y rw [fderivWithin_comp x hg hf h hxs, coe_comp', Function.comp_apply] /-- Ternary version of `fderivWithin_comp`, with equality assumptions of basepoints added, in order to apply more easily as a rewrite from right-to-left. -/ theorem fderivWithin_comp₃ {g' : G → G'} {g : F → G} {t : Set F} {u : Set G} {y : F} {y' : G} (hg' : DifferentiableWithinAt 𝕜 g' u y') (hg : DifferentiableWithinAt 𝕜 g t y) (hf : DifferentiableWithinAt 𝕜 f s x) (h2g : MapsTo g t u) (h2f : MapsTo f s t) (h3g : g y = y') (h3f : f x = y) (hxs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (g' ∘ g ∘ f) s x = (fderivWithin 𝕜 g' u y').comp ((fderivWithin 𝕜 g t y).comp (fderivWithin 𝕜 f s x)) := by substs h3g h3f exact (hg'.hasFDerivWithinAt.comp x (hg.hasFDerivWithinAt.comp x hf.hasFDerivWithinAt h2f) <| h2g.comp h2f).fderivWithin hxs theorem fderiv_comp {g : F → G} (hg : DifferentiableAt 𝕜 g (f x)) (hf : DifferentiableAt 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := (hg.hasFDerivAt.comp x hf.hasFDerivAt).fderiv /-- A variant for the derivative of a composition, written without `∘`. -/ theorem fderiv_comp' {g : F → G} (hg : DifferentiableAt 𝕜 g (f x)) (hf : DifferentiableAt 𝕜 f x) : fderiv 𝕜 (fun y ↦ g (f y)) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := fderiv_comp x hg hf theorem fderiv_comp_fderivWithin {g : F → G} (hg : DifferentiableAt 𝕜 g (f x)) (hf : DifferentiableWithinAt 𝕜 f s x) (hxs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderivWithin 𝕜 f s x) := (hg.hasFDerivAt.comp_hasFDerivWithinAt x hf.hasFDerivWithinAt).fderivWithin hxs @[fun_prop] theorem DifferentiableOn.fun_comp {g : F → G} {t : Set F} (hg : DifferentiableOn 𝕜 g t) (hf : DifferentiableOn 𝕜 f s) (st : MapsTo f s t) : DifferentiableOn 𝕜 (fun x ↦ g (f x)) s := fun x hx => DifferentiableWithinAt.comp x (hg (f x) (st hx)) (hf x hx) st @[fun_prop] theorem DifferentiableOn.comp {g : F → G} {t : Set F} (hg : DifferentiableOn 𝕜 g t) (hf : DifferentiableOn 𝕜 f s) (st : MapsTo f s t) : DifferentiableOn 𝕜 (g ∘ f) s := fun x hx => DifferentiableWithinAt.comp x (hg (f x) (st hx)) (hf x hx) st @[fun_prop] theorem Differentiable.fun_comp {g : F → G} (hg : Differentiable 𝕜 g) (hf : Differentiable 𝕜 f) : Differentiable 𝕜 (fun x ↦ g (f x)) := fun x => DifferentiableAt.comp x (hg (f x)) (hf x) @[fun_prop] theorem Differentiable.comp {g : F → G} (hg : Differentiable 𝕜 g) (hf : Differentiable 𝕜 f) : Differentiable 𝕜 (g ∘ f) := fun x => DifferentiableAt.comp x (hg (f x)) (hf x) @[fun_prop] theorem Differentiable.comp_differentiableOn {g : F → G} (hg : Differentiable 𝕜 g) (hf : DifferentiableOn 𝕜 f s) : DifferentiableOn 𝕜 (g ∘ f) s := hg.differentiableOn.comp hf (mapsTo_univ _ _) /-- The chain rule for derivatives in the sense of strict differentiability. -/ @[fun_prop] protected theorem HasStrictFDerivAt.comp {g : F → G} {g' : F →L[𝕜] G} (hg : HasStrictFDerivAt g g' (f x)) (hf : HasStrictFDerivAt f f' x) : HasStrictFDerivAt (fun x => g (f x)) (g'.comp f') x := .of_isLittleO <| ((hg.isLittleO.comp_tendsto (hf.continuousAt.prodMap' hf.continuousAt)).trans_isBigO hf.isBigO_sub).triangle <| by simpa only [g'.map_sub, f'.coe_comp'] using (g'.isBigO_comp _ _).trans_isLittleO hf.isLittleO @[fun_prop] protected theorem Differentiable.iterate {f : E → E} (hf : Differentiable 𝕜 f) (n : ℕ) : Differentiable 𝕜 f^[n] := Nat.recOn n differentiable_id fun _ ihn => ihn.comp hf @[fun_prop] protected theorem DifferentiableOn.iterate {f : E → E} (hf : DifferentiableOn 𝕜 f s) (hs : MapsTo f s s) (n : ℕ) : DifferentiableOn 𝕜 f^[n] s := Nat.recOn n differentiableOn_id fun _ ihn => ihn.comp hf hs variable {x} protected theorem HasFDerivAtFilter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : HasFDerivAtFilter f f' x L) (hL : Tendsto f L L) (hx : f x = x) (n : ℕ) : HasFDerivAtFilter f^[n] (f' ^ n) x L := by induction n with | zero => exact hasFDerivAtFilter_id x L | succ n ihn => rw [Function.iterate_succ, pow_succ] rw [← hx] at ihn exact ihn.comp x hf hL @[fun_prop] protected theorem HasFDerivAt.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : HasFDerivAt f f' x) (hx : f x = x) (n : ℕ) : HasFDerivAt f^[n] (f' ^ n) x := by refine HasFDerivAtFilter.iterate hf ?_ hx n convert hf.continuousAt.tendsto exact hx.symm @[fun_prop] protected theorem HasFDerivWithinAt.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : HasFDerivWithinAt f f' s x) (hx : f x = x) (hs : MapsTo f s s) (n : ℕ) : HasFDerivWithinAt f^[n] (f' ^ n) s x := by refine HasFDerivAtFilter.iterate hf ?_ hx n rw [nhdsWithin] convert tendsto_inf.2 ⟨hf.continuousWithinAt, _⟩ exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right] @[fun_prop] protected theorem HasStrictFDerivAt.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : HasStrictFDerivAt f f' x) (hx : f x = x) (n : ℕ) : HasStrictFDerivAt f^[n] (f' ^ n) x := by induction n with | zero => exact hasStrictFDerivAt_id x | succ n ihn => rw [Function.iterate_succ, pow_succ] rw [← hx] at ihn exact ihn.comp x hf @[fun_prop] protected theorem DifferentiableAt.iterate {f : E → E} (hf : DifferentiableAt 𝕜 f x) (hx : f x = x) (n : ℕ) : DifferentiableAt 𝕜 f^[n] x := (hf.hasFDerivAt.iterate hx n).differentiableAt @[fun_prop] protected theorem DifferentiableWithinAt.iterate {f : E → E} (hf : DifferentiableWithinAt 𝕜 f s x) (hx : f x = x) (hs : MapsTo f s s) (n : ℕ) : DifferentiableWithinAt 𝕜 f^[n] s x := (hf.hasFDerivWithinAt.iterate hx hs n).differentiableWithinAt end Composition end
Lemmas.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Logic.Basic import Mathlib.Tactic.Convert import Mathlib.Tactic.SplitIfs import Mathlib.Tactic.Tauto /-! # More basic logic properties A few more logic lemmas. These are in their own file, rather than `Logic.Basic`, because it is convenient to be able to use the `tauto` or `split_ifs` tactics. ## Implementation notes We spell those lemmas out with `dite` and `ite` rather than the `if then else` notation because this would result in less delta-reduced statements. -/ theorem iff_assoc {a b c : Prop} : ((a ↔ b) ↔ c) ↔ (a ↔ (b ↔ c)) := by tauto theorem iff_left_comm {a b c : Prop} : (a ↔ (b ↔ c)) ↔ (b ↔ (a ↔ c)) := by tauto theorem iff_right_comm {a b c : Prop} : ((a ↔ b) ↔ c) ↔ ((a ↔ c) ↔ b) := by tauto protected alias ⟨HEq.eq, Eq.heq⟩ := heq_iff_eq variable {α : Sort*} {p q : Prop} [Decidable p] [Decidable q] {a b c : α} theorem dite_dite_distrib_left {a : p → α} {b : ¬p → q → α} {c : ¬p → ¬q → α} : (dite p a fun hp ↦ dite q (b hp) (c hp)) = dite q (fun hq ↦ (dite p a) fun hp ↦ b hp hq) fun hq ↦ (dite p a) fun hp ↦ c hp hq := by split_ifs <;> rfl theorem dite_dite_distrib_right {a : p → q → α} {b : p → ¬q → α} {c : ¬p → α} : dite p (fun hp ↦ dite q (a hp) (b hp)) c = dite q (fun hq ↦ dite p (fun hp ↦ a hp hq) c) fun hq ↦ dite p (fun hp ↦ b hp hq) c := by split_ifs <;> rfl theorem ite_dite_distrib_left {a : α} {b : q → α} {c : ¬q → α} : ite p a (dite q b c) = dite q (fun hq ↦ ite p a <| b hq) fun hq ↦ ite p a <| c hq := dite_dite_distrib_left theorem ite_dite_distrib_right {a : q → α} {b : ¬q → α} {c : α} : ite p (dite q a b) c = dite q (fun hq ↦ ite p (a hq) c) fun hq ↦ ite p (b hq) c := dite_dite_distrib_right theorem dite_ite_distrib_left {a : p → α} {b : ¬p → α} {c : ¬p → α} : (dite p a fun hp ↦ ite q (b hp) (c hp)) = ite q (dite p a b) (dite p a c) := dite_dite_distrib_left theorem dite_ite_distrib_right {a : p → α} {b : p → α} {c : ¬p → α} : dite p (fun hp ↦ ite q (a hp) (b hp)) c = ite q (dite p a c) (dite p b c) := dite_dite_distrib_right theorem ite_ite_distrib_left : ite p a (ite q b c) = ite q (ite p a b) (ite p a c) := dite_dite_distrib_left theorem ite_ite_distrib_right : ite p (ite q a b) c = ite q (ite p a c) (ite p b c) := dite_dite_distrib_right lemma Prop.forall {f : Prop → Prop} : (∀ p, f p) ↔ f True ∧ f False := ⟨fun h ↦ ⟨h _, h _⟩, by rintro ⟨h₁, h₀⟩ p; by_cases hp : p <;> simp only [hp] <;> assumption⟩ lemma Prop.exists {f : Prop → Prop} : (∃ p, f p) ↔ f True ∨ f False := ⟨fun ⟨p, h⟩ ↦ by refine (em p).imp ?_ ?_ <;> intro H <;> convert h <;> simp [H], by rintro (h | h) <;> exact ⟨_, h⟩⟩
DeriveCountable.lean
/- Copyright (c) 2024 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Lean.Meta.Transform import Lean.Meta.Inductive import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util import Mathlib.Data.Countable.Defs import Mathlib.Data.Nat.Pairing /-! # `Countable` deriving handler Adds a deriving handler for the `Countable` class. -/ namespace Mathlib.Deriving.Countable open Lean Parser.Term Elab Deriving Meta /-! ### Theory We use the `Nat.pair` function to encode an inductive type in the natural numbers, following a pattern similar to the tagged s-expressions used in Scheme/Lisp. We develop a little theory to make constructing the injectivity functions very straightforward. This is easiest to explain by example. Given a type ```lean inductive T (α : Type) | a (n : α) | b (n m : α) (t : T α) ``` the deriving handler constructs the following three declarations: ```lean noncomputable def T.toNat (α : Type) [Countable α] : T α → ℕ | a n => Nat.pair 0 (Nat.pair (encode n) 0) | b n m t => Nat.pair 1 (Nat.pair (encode n) (Nat.pair (encode m) (Nat.pair t.toNat 0))) theorem T.toNat_injective (α : Type) [Countable α] : Function.Injective (T.toNat α) := fun | a .., a .. => by refine cons_eq_imp_init ?_ refine pair_encode_step ?_; rintro ⟨⟩ intro; rfl | a .., b .. => by refine cons_eq_imp ?_; rintro ⟨⟩ | b .., a .. => by refine cons_eq_imp ?_; rintro ⟨⟩ | b .., b .. => by refine cons_eq_imp_init ?_ refine pair_encode_step ?_; rintro ⟨⟩ refine pair_encode_step ?_; rintro ⟨⟩ refine cons_eq_imp ?_; intro h; cases T.toNat_injective α h intro; rfl instance (α : Type) [Countable α] : Countable (T α) := ⟨_, T.toNat_injective α⟩ ``` -/ private noncomputable def encode {α : Sort*} [Countable α] : α → ℕ := (Countable.exists_injective_nat α).choose private noncomputable def encode_injective {α : Sort*} [Countable α] : Function.Injective (encode : α → ℕ) := (Countable.exists_injective_nat α).choose_spec /-- Initialize the injectivity argument. Pops the constructor tag. -/ private theorem cons_eq_imp_init {p : Prop} {a b b' : ℕ} (h : b = b' → p) : Nat.pair a b = Nat.pair a b' → p := by simpa [Nat.pair_eq_pair, and_imp] using h /-- Generic step of the injectivity argument, pops the head of the pairs. Used in the recursive steps where we need to supply an additional injectivity argument. -/ private theorem cons_eq_imp {p : Prop} {a b a' b' : ℕ} (h : a = a' → b = b' → p) : Nat.pair a b = Nat.pair a' b' → p := by rwa [Nat.pair_eq_pair, and_imp] /-- Specialized step of the injectivity argument, pops the head of the pairs and decodes. -/ private theorem pair_encode_step {p : Prop} {α : Sort*} [Countable α] {a b : α} {m n : ℕ} (h : a = b → m = n → p) : Nat.pair (encode a) m = Nat.pair (encode b) n → p := cons_eq_imp fun ha => h (encode_injective ha) /-! ### Implementation -/ /-! Constructing the `toNat` functions. -/ private def mkToNatMatch (ctx : Deriving.Context) (header : Header) (indVal : InductiveVal) (toFunNames : Array Name) : TermElabM Term := do let discrs ← mkDiscrs header indVal let alts ← mkAlts `(match $[$discrs],* with $alts:matchAlt*) where mkAlts : TermElabM (Array (TSyntax ``matchAlt)) := do let mut alts := #[] for ctorName in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName alts := alts.push <| ← forallTelescopeReducing ctorInfo.type fun xs _ => do let mut patterns := #[] let mut ctorArgs := #[] let mut rhsArgs : Array Term := #[] for _ in [:indVal.numIndices] do patterns := patterns.push (← `(_)) for _ in [:ctorInfo.numParams] do ctorArgs := ctorArgs.push (← `(_)) for i in [:ctorInfo.numFields] do let a := mkIdent (← mkFreshUserName `a) ctorArgs := ctorArgs.push a let x := xs[ctorInfo.numParams + i]! let xTy ← inferType x let recName? := ctx.typeInfos.findIdx? (xTy.isAppOf ·.name) |>.map (toFunNames[·]!) rhsArgs := rhsArgs.push <| ← if let some recName := recName? then `($(mkIdent recName) $a) else ``(encode $a) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs:term*)) let rhs' : Term ← rhsArgs.foldrM (init := ← `(0)) fun arg acc => ``(Nat.pair $arg $acc) let rhs : Term ← ``(Nat.pair $(quote ctorInfo.cidx) $rhs') `(matchAltExpr| | $[$patterns:term],* => $rhs) return alts /-- Constructs a function from the inductive type to `Nat`. -/ def mkToNatFuns (ctx : Deriving.Context) (toNatFnNames : Array Name) : TermElabM (TSyntax `command) := do let mut res : Array (TSyntax `command) := #[] for i in [:toNatFnNames.size] do let toNatFnName := toNatFnNames[i]! let indVal := ctx.typeInfos[i]! let header ← mkHeader ``Countable 1 indVal let body ← mkToNatMatch ctx header indVal toNatFnNames res := res.push <| ← `( private noncomputable def $(mkIdent toNatFnName):ident $header.binders:bracketedBinder* : Nat := $body:term ) `(command| mutual $[$res:command]* end) /-! Constructing the injectivity proofs for these `toNat` functions. -/ private def mkInjThmMatch (ctx : Deriving.Context) (header : Header) (indVal : InductiveVal) : TermElabM Term := do let discrs ← mkDiscrs header indVal let alts ← mkAlts `(match $[$discrs],* with $alts:matchAlt*) where mkAlts : TermElabM (Array (TSyntax ``matchAlt)) := do let mut alts := #[] for ctorName₁ in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName₁ for ctorName₂ in indVal.ctors do let mut patterns := #[] for _ in [:indVal.numIndices] do patterns := patterns.push (← `(_)) patterns := patterns ++ #[(← `($(mkIdent ctorName₁) ..)), (← `($(mkIdent ctorName₂) ..))] if ctorName₁ == ctorName₂ then alts := alts.push <| ← forallTelescopeReducing ctorInfo.type fun xs _ => do let mut tactics : Array (TSyntax `tactic) := #[] for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i]! let xTy ← inferType x let recName? := ctx.typeInfos.findIdx? (xTy.isAppOf ·.name) |>.map (ctx.auxFunNames[·]!) tactics := tactics.push <| ← if let some recName := recName? then `(tactic| ( refine $(mkCIdent ``cons_eq_imp) ?_; intro h; cases $(mkIdent recName) _ _ h )) else `(tactic| ( refine $(mkCIdent ``pair_encode_step) ?_; rintro ⟨⟩ )) tactics := tactics.push (← `(tactic| (intro; rfl))) `(matchAltExpr| | $[$patterns:term],* => cons_eq_imp_init (by $tactics:tactic*)) else if (← compatibleCtors ctorName₁ ctorName₂) then let rhs ← ``(cons_eq_imp (by rintro ⟨⟩)) alts := alts.push (← `(matchAltExpr| | $[$patterns:term],* => $rhs:term)) return alts /-- Constructs a proof that the functions created by `mkToNatFuns` are injective. -/ def mkInjThms (ctx : Deriving.Context) (toNatFnNames : Array Name) : TermElabM (TSyntax `command) := do let mut res : Array (TSyntax `command) := #[] for i in [:toNatFnNames.size] do let toNatFnName := toNatFnNames[i]! let injThmName := ctx.auxFunNames[i]! let indVal := ctx.typeInfos[i]! let header ← mkHeader ``Countable 2 indVal let body ← mkInjThmMatch ctx header indVal let f := mkIdent toNatFnName let t1 := mkIdent header.targetNames[0]! let t2 := mkIdent header.targetNames[1]! res := res.push <| ← `( private theorem $(mkIdent injThmName):ident $header.binders:bracketedBinder* : $f $t1 = $f $t2 → $t1 = $t2 := $body:term ) `(command| mutual $[$res:command]* end) /-! Assembling the `Countable` instances. -/ open TSyntax.Compat in /-- Assuming all of the auxiliary definitions exist, create all the `instance` commands for the `ToExpr` instances for the (mutual) inductive type(s). -/ private def mkCountableInstanceCmds (ctx : Deriving.Context) (typeNames : Array Name) : TermElabM (Array Command) := do let mut instances := #[] for i in [:ctx.typeInfos.size] do let indVal := ctx.typeInfos[i]! if typeNames.contains indVal.name then let auxFunName := ctx.auxFunNames[i]! let argNames ← mkInductArgNames indVal let binders ← mkImplicitBinders argNames let binders := binders ++ (← mkInstImplicitBinders ``Countable indVal argNames) let indType ← mkInductiveApp indVal argNames let type ← `($(mkCIdent ``Countable) $indType) let mut val := mkIdent auxFunName let instCmd ← `(instance $binders:implicitBinder* : $type := ⟨_, $val⟩) instances := instances.push instCmd return instances private def mkCountableCmds (indVal : InductiveVal) (declNames : Array Name) : TermElabM (Array Syntax) := do let ctx ← mkContext "countable" indVal.name let toNatFunNames : Array Name ← ctx.auxFunNames.mapM fun name => do let .str n' s := name.eraseMacroScopes | unreachable! mkFreshUserName <| .str n' (s ++ "ToNat") let cmds := #[← mkToNatFuns ctx toNatFunNames, ← mkInjThms ctx toNatFunNames] ++ (← mkCountableInstanceCmds ctx declNames) trace[Mathlib.Deriving.countable] "\n{cmds}" return cmds open Command /-- The deriving handler for the `Countable` class. Handles non-nested non-reflexive inductive types. They can be mutual too — in that case, there is an optimization to re-use all the generated functions and proofs. -/ def mkCountableInstance (declNames : Array Name) : CommandElabM Bool := do let mut seen : NameSet := {} let mut toVisit : Array InductiveVal := #[] for declName in declNames do if seen.contains declName then continue let indVal ← getConstInfoInduct declName if indVal.isNested || indVal.isReflexive then return false -- not supported yet seen := seen.append (NameSet.ofList indVal.all) toVisit := toVisit.push indVal for indVal in toVisit do let cmds ← liftTermElabM <| mkCountableCmds indVal (declNames.filter indVal.all.contains) withEnableInfoTree false do elabCommand <| mkNullNode cmds return true initialize registerDerivingHandler ``Countable mkCountableInstance registerTraceClass `Mathlib.Deriving.countable end Mathlib.Deriving.Countable
Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import Mathlib.Algebra.Order.Ring.WithTop import Mathlib.Algebra.Order.Sub.WithTop import Mathlib.Data.NNReal.Defs import Mathlib.Order.Interval.Set.WithBotTop import Mathlib.Tactic.Finiteness /-! # Extended non-negative reals We define `ENNReal = ℝ≥0∞ := WithTop ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `MeasureTheory.Measure`, and of the extended distance `edist` in an `EMetricSpace`. In this file we set up many of the instances on `ℝ≥0∞`, and provide relationships between `ℝ≥0∞` and `ℝ≥0`, and between `ℝ≥0∞` and `ℝ`. In particular, we provide a coercion from `ℝ≥0` to `ℝ≥0∞` as well as functions `ENNReal.toNNReal`, `ENNReal.ofReal` and `ENNReal.toReal`, all of which take the value zero wherever they cannot be the identity. Also included is the relationship between `ℝ≥0∞` and `ℕ`. The interaction of these functions, especially `ENNReal.ofReal` and `ENNReal.toReal`, with the algebraic and lattice structure can be found in `Data.ENNReal.Real`. This file proves many of the order properties of `ℝ≥0∞`, with the exception of the ways those relate to the algebraic structure, which are included in `Data.ENNReal.Operations`. This file also defines inversion and division: this includes `Inv` and `Div` instances on `ℝ≥0∞` making it into a `DivInvOneMonoid`. As a consequence of being a `DivInvOneMonoid`, `ℝ≥0∞` inherits a power operation with integer exponent: this and other properties is shown in `Data.ENNReal.Inv`. ## Main definitions * `ℝ≥0∞`: the extended nonnegative real numbers `[0, ∞]`; defined as `WithTop ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ℝ≥0∞` into a canonically ordered commutative semiring of characteristic zero. - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. This inversion and division include `Inv` and `Div` instances on `ℝ≥0∞`, making it into a `DivInvOneMonoid`. Further properties of these are shown in `Data.ENNReal.Inv`. * Coercions to/from other types: - coercion `ℝ≥0 → ℝ≥0∞` is defined as `Coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ℝ≥0∞`, and Lean will apply `coe` automatically; - `ENNReal.toNNReal` sends `↑p` to `p` and `∞` to `0`; - `ENNReal.toReal := coe ∘ ENNReal.toNNReal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ENNReal.ofReal := coe ∘ Real.toNNReal` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ENNReal.neTopEquivNNReal` is an equivalence between `{a : ℝ≥0∞ // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `CanLift ℝ≥0∞ ℝ≥0` instance, so one of the ways to prove theorems about an `ℝ≥0∞` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ℝ≥0∞) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0∞`: the type of the extended nonnegative real numbers; * `ℝ≥0`: the type of nonnegative real numbers `[0, ∞)`; defined in `Data.Real.NNReal`; * `∞`: a localized notation in `ENNReal` for `⊤ : ℝ≥0∞`. -/ assert_not_exists Finset open Function Set NNReal variable {α : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ def ENNReal := WithTop ℝ≥0 deriving Zero, Top, AddCommMonoidWithOne, SemilatticeSup, DistribLattice, Nontrivial @[inherit_doc] scoped[ENNReal] notation "ℝ≥0∞" => ENNReal /-- Notation for infinity as an `ENNReal` number. -/ scoped[ENNReal] notation "∞" => (⊤ : ENNReal) namespace ENNReal instance : OrderBot ℝ≥0∞ := inferInstanceAs (OrderBot (WithTop ℝ≥0)) instance : OrderTop ℝ≥0∞ := inferInstanceAs (OrderTop (WithTop ℝ≥0)) instance : BoundedOrder ℝ≥0∞ := inferInstanceAs (BoundedOrder (WithTop ℝ≥0)) instance : CharZero ℝ≥0∞ := inferInstanceAs (CharZero (WithTop ℝ≥0)) instance : Min ℝ≥0∞ := SemilatticeInf.toMin instance : Max ℝ≥0∞ := SemilatticeSup.toMax noncomputable instance : CommSemiring ℝ≥0∞ := inferInstanceAs (CommSemiring (WithTop ℝ≥0)) instance : PartialOrder ℝ≥0∞ := inferInstanceAs (PartialOrder (WithTop ℝ≥0)) instance : IsOrderedRing ℝ≥0∞ := inferInstanceAs (IsOrderedRing (WithTop ℝ≥0)) instance : CanonicallyOrderedAdd ℝ≥0∞ := inferInstanceAs (CanonicallyOrderedAdd (WithTop ℝ≥0)) instance : NoZeroDivisors ℝ≥0∞ := inferInstanceAs (NoZeroDivisors (WithTop ℝ≥0)) noncomputable instance : CompleteLinearOrder ℝ≥0∞ := inferInstanceAs (CompleteLinearOrder (WithTop ℝ≥0)) instance : DenselyOrdered ℝ≥0∞ := inferInstanceAs (DenselyOrdered (WithTop ℝ≥0)) instance : AddCommMonoid ℝ≥0∞ := inferInstanceAs (AddCommMonoid (WithTop ℝ≥0)) noncomputable instance : LinearOrder ℝ≥0∞ := inferInstanceAs (LinearOrder (WithTop ℝ≥0)) instance : IsOrderedAddMonoid ℝ≥0∞ := inferInstanceAs (IsOrderedAddMonoid (WithTop ℝ≥0)) instance instSub : Sub ℝ≥0∞ := inferInstanceAs (Sub (WithTop ℝ≥0)) instance : OrderedSub ℝ≥0∞ := inferInstanceAs (OrderedSub (WithTop ℝ≥0)) noncomputable instance : LinearOrderedAddCommMonoidWithTop ℝ≥0∞ := inferInstanceAs (LinearOrderedAddCommMonoidWithTop (WithTop ℝ≥0)) -- RFC: redefine using pattern matching? noncomputable instance : Inv ℝ≥0∞ := ⟨fun a => sInf { b | 1 ≤ a * b }⟩ noncomputable instance : DivInvMonoid ℝ≥0∞ where variable {a b c d : ℝ≥0∞} {r p q : ℝ≥0} {n : ℕ} -- TODO: add a `WithTop` instance and use it here noncomputable instance : LinearOrderedCommMonoidWithZero ℝ≥0∞ := { inferInstanceAs (LinearOrderedAddCommMonoidWithTop ℝ≥0∞), inferInstanceAs (CommSemiring ℝ≥0∞) with bot_le _ := bot_le mul_le_mul_left := fun _ _ => mul_le_mul_left' zero_le_one := zero_le 1 } instance : Unique (AddUnits ℝ≥0∞) where default := 0 uniq a := AddUnits.ext <| le_zero_iff.1 <| by rw [← a.add_neg]; exact le_self_add instance : Inhabited ℝ≥0∞ := ⟨0⟩ /-- Coercion from `ℝ≥0` to `ℝ≥0∞`. -/ @[coe, match_pattern] def ofNNReal : ℝ≥0 → ℝ≥0∞ := WithTop.some instance : Coe ℝ≥0 ℝ≥0∞ := ⟨ofNNReal⟩ /-- A version of `WithTop.recTopCoe` that uses `ENNReal.ofNNReal`. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] def recTopCoe {C : ℝ≥0∞ → Sort*} (top : C ∞) (coe : ∀ x : ℝ≥0, C x) (x : ℝ≥0∞) : C x := WithTop.recTopCoe top coe x instance canLift : CanLift ℝ≥0∞ ℝ≥0 ofNNReal (· ≠ ∞) := WithTop.canLift @[simp] theorem none_eq_top : (none : ℝ≥0∞) = ∞ := rfl @[simp] theorem some_eq_coe (a : ℝ≥0) : (Option.some a : ℝ≥0∞) = (↑a : ℝ≥0∞) := rfl @[simp] theorem some_eq_coe' (a : ℝ≥0) : (WithTop.some a : ℝ≥0∞) = (↑a : ℝ≥0∞) := rfl lemma coe_injective : Injective ((↑) : ℝ≥0 → ℝ≥0∞) := WithTop.coe_injective @[simp, norm_cast] lemma coe_inj : (p : ℝ≥0∞) = q ↔ p = q := coe_injective.eq_iff lemma coe_ne_coe : (p : ℝ≥0∞) ≠ q ↔ p ≠ q := coe_inj.not theorem range_coe' : range ofNNReal = Iio ∞ := WithTop.range_coe theorem range_coe : range ofNNReal = {∞}ᶜ := (isCompl_range_some_none ℝ≥0).symm.compl_eq.symm instance : NNRatCast ℝ≥0∞ where nnratCast r := ofNNReal r @[norm_cast] theorem coe_nnratCast (q : ℚ≥0) : ↑(q : ℝ≥0) = (q : ℝ≥0∞) := rfl /-- `toNNReal x` returns `x` if it is real, otherwise 0. -/ protected def toNNReal : ℝ≥0∞ → ℝ≥0 := WithTop.untopD 0 /-- `toReal x` returns `x` if it is real, `0` otherwise. -/ protected def toReal (a : ℝ≥0∞) : Real := a.toNNReal /-- `ofReal x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def ofReal (r : Real) : ℝ≥0∞ := r.toNNReal @[simp, norm_cast] lemma toNNReal_coe (r : ℝ≥0) : (r : ℝ≥0∞).toNNReal = r := rfl @[simp] theorem coe_toNNReal : ∀ {a : ℝ≥0∞}, a ≠ ∞ → ↑a.toNNReal = a | ofNNReal _, _ => rfl | ⊤, h => (h rfl).elim @[simp] theorem coe_comp_toNNReal_comp {ι : Type*} {f : ι → ℝ≥0∞} (hf : ∀ x, f x ≠ ∞) : (fun (x : ℝ≥0) => (x : ℝ≥0∞)) ∘ ENNReal.toNNReal ∘ f = f := by ext x simp [coe_toNNReal (hf x)] @[simp] theorem ofReal_toReal {a : ℝ≥0∞} (h : a ≠ ∞) : ENNReal.ofReal a.toReal = a := by simp [ENNReal.toReal, ENNReal.ofReal, h] @[simp] theorem toReal_ofReal {r : ℝ} (h : 0 ≤ r) : (ENNReal.ofReal r).toReal = r := max_eq_left h theorem toReal_ofReal' {r : ℝ} : (ENNReal.ofReal r).toReal = max r 0 := rfl theorem coe_toNNReal_le_self : ∀ {a : ℝ≥0∞}, ↑a.toNNReal ≤ a | ofNNReal r => by rw [toNNReal_coe] | ⊤ => le_top theorem coe_nnreal_eq (r : ℝ≥0) : (r : ℝ≥0∞) = ENNReal.ofReal r := by rw [ENNReal.ofReal, Real.toNNReal_coe] theorem ofReal_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ENNReal.ofReal x = ofNNReal ⟨x, h⟩ := (coe_nnreal_eq ⟨x, h⟩).symm theorem ofNNReal_toNNReal (x : ℝ) : (Real.toNNReal x : ℝ≥0∞) = ENNReal.ofReal x := rfl @[simp] theorem ofReal_coe_nnreal : ENNReal.ofReal p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] theorem coe_zero : ↑(0 : ℝ≥0) = (0 : ℝ≥0∞) := rfl @[simp, norm_cast] theorem coe_one : ↑(1 : ℝ≥0) = (1 : ℝ≥0∞) := rfl @[simp] theorem toReal_nonneg {a : ℝ≥0∞} : 0 ≤ a.toReal := a.toNNReal.2 @[norm_cast] theorem coe_toNNReal_eq_toReal (z : ℝ≥0∞) : (z.toNNReal : ℝ) = z.toReal := rfl @[simp] theorem toNNReal_toReal_eq (z : ℝ≥0∞) : z.toReal.toNNReal = z.toNNReal := by ext; simp [coe_toNNReal_eq_toReal] @[simp] theorem toNNReal_top : ∞.toNNReal = 0 := rfl @[deprecated (since := "2025-03-20")] alias top_toNNReal := toNNReal_top @[simp] theorem toReal_top : ∞.toReal = 0 := rfl @[deprecated (since := "2025-03-20")] alias top_toReal := toReal_top @[simp] theorem toReal_one : (1 : ℝ≥0∞).toReal = 1 := rfl @[deprecated (since := "2025-03-20")] alias one_toReal := toReal_one @[simp] theorem toNNReal_one : (1 : ℝ≥0∞).toNNReal = 1 := rfl @[deprecated (since := "2025-03-20")] alias one_toNNReal := toNNReal_one @[simp] theorem coe_toReal (r : ℝ≥0) : (r : ℝ≥0∞).toReal = r := rfl @[simp] theorem toNNReal_zero : (0 : ℝ≥0∞).toNNReal = 0 := rfl @[deprecated (since := "2025-03-20")] alias zero_toNNReal := toNNReal_zero @[simp] theorem toReal_zero : (0 : ℝ≥0∞).toReal = 0 := rfl @[deprecated (since := "2025-03-20")] alias zero_toReal := toReal_zero @[simp] theorem ofReal_zero : ENNReal.ofReal (0 : ℝ) = 0 := by simp [ENNReal.ofReal] @[simp] theorem ofReal_one : ENNReal.ofReal (1 : ℝ) = (1 : ℝ≥0∞) := by simp [ENNReal.ofReal] theorem ofReal_toReal_le {a : ℝ≥0∞} : ENNReal.ofReal a.toReal ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (ofReal_toReal ha) theorem forall_ennreal {p : ℝ≥0∞ → Prop} : (∀ a, p a) ↔ (∀ r : ℝ≥0, p r) ∧ p ∞ := Option.forall.trans and_comm theorem forall_ne_top {p : ℝ≥0∞ → Prop} : (∀ a, a ≠ ∞ → p a) ↔ ∀ r : ℝ≥0, p r := Option.forall_ne_none theorem exists_ne_top {p : ℝ≥0∞ → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := Option.exists_ne_none theorem toNNReal_eq_zero_iff (x : ℝ≥0∞) : x.toNNReal = 0 ↔ x = 0 ∨ x = ∞ := WithTop.untopD_eq_self_iff theorem toReal_eq_zero_iff (x : ℝ≥0∞) : x.toReal = 0 ↔ x = 0 ∨ x = ∞ := by simp [ENNReal.toReal, toNNReal_eq_zero_iff] theorem toNNReal_ne_zero : a.toNNReal ≠ 0 ↔ a ≠ 0 ∧ a ≠ ∞ := a.toNNReal_eq_zero_iff.not.trans not_or theorem toReal_ne_zero : a.toReal ≠ 0 ↔ a ≠ 0 ∧ a ≠ ∞ := a.toReal_eq_zero_iff.not.trans not_or theorem toNNReal_eq_one_iff (x : ℝ≥0∞) : x.toNNReal = 1 ↔ x = 1 := WithTop.untopD_eq_iff.trans <| by simp theorem toReal_eq_one_iff (x : ℝ≥0∞) : x.toReal = 1 ↔ x = 1 := by rw [ENNReal.toReal, NNReal.coe_eq_one, ENNReal.toNNReal_eq_one_iff] theorem toNNReal_ne_one : a.toNNReal ≠ 1 ↔ a ≠ 1 := a.toNNReal_eq_one_iff.not theorem toReal_ne_one : a.toReal ≠ 1 ↔ a ≠ 1 := a.toReal_eq_one_iff.not @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem coe_ne_top : (r : ℝ≥0∞) ≠ ∞ := WithTop.coe_ne_top @[simp] theorem top_ne_coe : ∞ ≠ (r : ℝ≥0∞) := WithTop.top_ne_coe @[simp] theorem coe_lt_top : (r : ℝ≥0∞) < ∞ := WithTop.coe_lt_top r @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem ofReal_ne_top {r : ℝ} : ENNReal.ofReal r ≠ ∞ := coe_ne_top @[simp] theorem ofReal_lt_top {r : ℝ} : ENNReal.ofReal r < ∞ := coe_lt_top @[simp] theorem top_ne_ofReal {r : ℝ} : ∞ ≠ ENNReal.ofReal r := top_ne_coe @[simp] theorem ofReal_toReal_eq_iff : ENNReal.ofReal a.toReal = a ↔ a ≠ ⊤ := ⟨fun h => by rw [← h] exact ofReal_ne_top, ofReal_toReal⟩ @[simp] theorem toReal_ofReal_eq_iff {a : ℝ} : (ENNReal.ofReal a).toReal = a ↔ 0 ≤ a := ⟨fun h => by rw [← h] exact toReal_nonneg, toReal_ofReal⟩ @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] theorem top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] theorem top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp] theorem zero_lt_top : 0 < ∞ := coe_lt_top @[simp, norm_cast] theorem coe_le_coe : (↑r : ℝ≥0∞) ≤ ↑q ↔ r ≤ q := WithTop.coe_le_coe @[simp, norm_cast] theorem coe_lt_coe : (↑r : ℝ≥0∞) < ↑q ↔ r < q := WithTop.coe_lt_coe -- Needed until `@[gcongr]` accepts iff statements alias ⟨_, coe_le_coe_of_le⟩ := coe_le_coe attribute [gcongr] ENNReal.coe_le_coe_of_le -- Needed until `@[gcongr]` accepts iff statements alias ⟨_, coe_lt_coe_of_lt⟩ := coe_lt_coe attribute [gcongr] ENNReal.coe_lt_coe_of_lt theorem coe_mono : Monotone ofNNReal := fun _ _ => coe_le_coe.2 theorem coe_strictMono : StrictMono ofNNReal := fun _ _ => coe_lt_coe.2 @[simp, norm_cast] theorem coe_eq_zero : (↑r : ℝ≥0∞) = 0 ↔ r = 0 := coe_inj @[simp, norm_cast] theorem zero_eq_coe : 0 = (↑r : ℝ≥0∞) ↔ 0 = r := coe_inj @[simp, norm_cast] theorem coe_eq_one : (↑r : ℝ≥0∞) = 1 ↔ r = 1 := coe_inj @[simp, norm_cast] theorem one_eq_coe : 1 = (↑r : ℝ≥0∞) ↔ 1 = r := coe_inj @[simp, norm_cast] theorem coe_pos : 0 < (r : ℝ≥0∞) ↔ 0 < r := coe_lt_coe theorem coe_ne_zero : (r : ℝ≥0∞) ≠ 0 ↔ r ≠ 0 := coe_eq_zero.not lemma coe_ne_one : (r : ℝ≥0∞) ≠ 1 ↔ r ≠ 1 := coe_eq_one.not @[simp, norm_cast] lemma coe_add (x y : ℝ≥0) : (↑(x + y) : ℝ≥0∞) = x + y := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ≥0) : (↑(x * y) : ℝ≥0∞) = x * y := rfl @[norm_cast] lemma coe_nsmul (n : ℕ) (x : ℝ≥0) : (↑(n • x) : ℝ≥0∞) = n • x := rfl @[simp, norm_cast] lemma coe_pow (x : ℝ≥0) (n : ℕ) : (↑(x ^ n) : ℝ≥0∞) = x ^ n := rfl @[simp, norm_cast] theorem coe_ofNat (n : ℕ) [n.AtLeastTwo] : ((ofNat(n) : ℝ≥0) : ℝ≥0∞) = ofNat(n) := rfl -- TODO: add lemmas about `OfNat.ofNat` and `<`/`≤` theorem coe_two : ((2 : ℝ≥0) : ℝ≥0∞) = 2 := rfl theorem toNNReal_eq_toNNReal_iff (x y : ℝ≥0∞) : x.toNNReal = y.toNNReal ↔ x = y ∨ x = 0 ∧ y = ⊤ ∨ x = ⊤ ∧ y = 0 := WithTop.untopD_eq_untopD_iff theorem toReal_eq_toReal_iff (x y : ℝ≥0∞) : x.toReal = y.toReal ↔ x = y ∨ x = 0 ∧ y = ⊤ ∨ x = ⊤ ∧ y = 0 := by simp only [ENNReal.toReal, NNReal.coe_inj, toNNReal_eq_toNNReal_iff] theorem toNNReal_eq_toNNReal_iff' {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) : x.toNNReal = y.toNNReal ↔ x = y := by simp only [ENNReal.toNNReal_eq_toNNReal_iff x y, hx, hy, and_false, false_and, or_false] theorem toReal_eq_toReal_iff' {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) : x.toReal = y.toReal ↔ x = y := by simp only [ENNReal.toReal, NNReal.coe_inj, toNNReal_eq_toNNReal_iff' hx hy] theorem one_lt_two : (1 : ℝ≥0∞) < 2 := Nat.one_lt_ofNat /-- `(1 : ℝ≥0∞) ≤ 1`, recorded as a `Fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_one_ennreal : Fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_rfl⟩ /-- `(1 : ℝ≥0∞) ≤ 2`, recorded as a `Fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_two_ennreal : Fact ((1 : ℝ≥0∞) ≤ 2) := ⟨one_le_two⟩ /-- `(1 : ℝ≥0∞) ≤ ∞`, recorded as a `Fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_top_ennreal : Fact ((1 : ℝ≥0∞) ≤ ∞) := ⟨le_top⟩ /-- The set of numbers in `ℝ≥0∞` that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def neTopEquivNNReal : { a | a ≠ ∞ } ≃ ℝ≥0 where toFun x := ENNReal.toNNReal x invFun x := ⟨x, coe_ne_top⟩ left_inv := fun x => Subtype.eq <| coe_toNNReal x.2 right_inv := toNNReal_coe theorem cinfi_ne_top [InfSet α] (f : ℝ≥0∞ → α) : ⨅ x : { x // x ≠ ∞ }, f x = ⨅ x : ℝ≥0, f x := Eq.symm <| neTopEquivNNReal.symm.surjective.iInf_congr _ fun _ => rfl theorem iInf_ne_top [CompleteLattice α] (f : ℝ≥0∞ → α) : ⨅ (x) (_ : x ≠ ∞), f x = ⨅ x : ℝ≥0, f x := by rw [iInf_subtype', cinfi_ne_top] theorem csupr_ne_top [SupSet α] (f : ℝ≥0∞ → α) : ⨆ x : { x // x ≠ ∞ }, f x = ⨆ x : ℝ≥0, f x := @cinfi_ne_top αᵒᵈ _ _ theorem iSup_ne_top [CompleteLattice α] (f : ℝ≥0∞ → α) : ⨆ (x) (_ : x ≠ ∞), f x = ⨆ x : ℝ≥0, f x := @iInf_ne_top αᵒᵈ _ _ theorem iInf_ennreal {α : Type*} [CompleteLattice α] {f : ℝ≥0∞ → α} : ⨅ n, f n = (⨅ n : ℝ≥0, f n) ⊓ f ∞ := (iInf_option f).trans (inf_comm _ _) theorem iSup_ennreal {α : Type*} [CompleteLattice α] {f : ℝ≥0∞ → α} : ⨆ n, f n = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @iInf_ennreal αᵒᵈ _ _ /-- Coercion `ℝ≥0 → ℝ≥0∞` as a `RingHom`. -/ def ofNNRealHom : ℝ≥0 →+* ℝ≥0∞ where toFun := some map_one' := coe_one map_mul' _ _ := coe_mul _ _ map_zero' := coe_zero map_add' _ _ := coe_add _ _ @[simp] theorem coe_ofNNRealHom : ⇑ofNNRealHom = some := rfl section Order theorem bot_eq_zero : (⊥ : ℝ≥0∞) = 0 := rfl -- `coe_lt_top` moved up theorem not_top_le_coe : ¬∞ ≤ ↑r := WithTop.not_top_le_coe r @[simp, norm_cast] theorem one_le_coe_iff : (1 : ℝ≥0∞) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] theorem coe_le_one_iff : ↑r ≤ (1 : ℝ≥0∞) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] theorem coe_lt_one_iff : (↑p : ℝ≥0∞) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] theorem one_lt_coe_iff : 1 < (↑p : ℝ≥0∞) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] theorem coe_natCast (n : ℕ) : ((n : ℝ≥0) : ℝ≥0∞) = n := rfl @[simp, norm_cast] lemma ofReal_natCast (n : ℕ) : ENNReal.ofReal n = n := by simp [ENNReal.ofReal] @[simp] theorem ofReal_ofNat (n : ℕ) [n.AtLeastTwo] : ENNReal.ofReal ofNat(n) = ofNat(n) := ofReal_natCast n @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem natCast_ne_top (n : ℕ) : (n : ℝ≥0∞) ≠ ∞ := WithTop.natCast_ne_top n @[simp] theorem natCast_lt_top (n : ℕ) : (n : ℝ≥0∞) < ∞ := WithTop.natCast_lt_top n @[simp, aesop (rule_sets := [finiteness]) safe apply] lemma ofNat_ne_top {n : ℕ} [Nat.AtLeastTwo n] : ofNat(n) ≠ ∞ := natCast_ne_top n @[simp] lemma ofNat_lt_top {n : ℕ} [Nat.AtLeastTwo n] : ofNat(n) < ∞ := natCast_lt_top n @[simp] theorem top_ne_natCast (n : ℕ) : ∞ ≠ n := WithTop.top_ne_natCast n @[simp] theorem top_ne_ofNat {n : ℕ} [n.AtLeastTwo] : ∞ ≠ ofNat(n) := ofNat_ne_top.symm @[simp, norm_cast] lemma natCast_le_ofNNReal : (n : ℝ≥0∞) ≤ r ↔ n ≤ r := by simp [← coe_le_coe] @[simp, norm_cast] lemma ofNNReal_le_natCast : r ≤ (n : ℝ≥0∞) ↔ r ≤ n := by simp [← coe_le_coe] @[simp, norm_cast] lemma ofNNReal_add_natCast (r : ℝ≥0) (n : ℕ) : ofNNReal (r + n) = r + n := rfl @[simp, norm_cast] lemma ofNNReal_natCast_add (n : ℕ) (r : ℝ≥0) : ofNNReal (n + r) = n + r := rfl @[simp, norm_cast] lemma ofNNReal_sub_natCast (r : ℝ≥0) (n : ℕ) : ofNNReal (r - n) = r - n := rfl @[simp, norm_cast] lemma ofNNReal_natCast_sub (n : ℕ) (r : ℝ≥0) : ofNNReal (n - r) = n - r := rfl @[simp] theorem one_lt_top : 1 < ∞ := coe_lt_top @[simp, norm_cast] theorem toNNReal_natCast (n : ℕ) : (n : ℝ≥0∞).toNNReal = n := by rw [← ENNReal.coe_natCast n, ENNReal.toNNReal_coe] @[deprecated (since := "2025-02-19")] alias toNNReal_nat := toNNReal_natCast theorem toNNReal_ofNat (n : ℕ) [n.AtLeastTwo] : ENNReal.toNNReal ofNat(n) = ofNat(n) := toNNReal_natCast n @[simp, norm_cast] theorem toReal_natCast (n : ℕ) : (n : ℝ≥0∞).toReal = n := by rw [← ENNReal.ofReal_natCast n, ENNReal.toReal_ofReal (Nat.cast_nonneg _)] @[deprecated (since := "2025-02-19")] alias toReal_nat := toReal_natCast @[simp] theorem toReal_ofNat (n : ℕ) [n.AtLeastTwo] : ENNReal.toReal ofNat(n) = ofNat(n) := toReal_natCast n lemma toNNReal_natCast_eq_toNNReal (n : ℕ) : (n : ℝ≥0∞).toNNReal = (n : ℝ).toNNReal := by rw [Real.toNNReal_of_nonneg (by positivity), ENNReal.toNNReal_natCast, mk_natCast] theorem le_coe_iff : a ≤ ↑r ↔ ∃ p : ℝ≥0, a = p ∧ p ≤ r := WithTop.le_coe_iff theorem coe_le_iff : ↑r ≤ a ↔ ∀ p : ℝ≥0, a = p → r ≤ p := WithTop.coe_le_iff theorem lt_iff_exists_coe : a < b ↔ ∃ p : ℝ≥0, a = p ∧ ↑p < b := WithTop.lt_iff_exists_coe theorem toReal_le_coe_of_le_coe {a : ℝ≥0∞} {b : ℝ≥0} (h : a ≤ b) : a.toReal ≤ b := by lift a to ℝ≥0 using ne_top_of_le_ne_top coe_ne_top h simpa using h @[simp] theorem max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := max_eq_bot theorem max_zero_left : max 0 a = a := max_eq_right (zero_le a) theorem max_zero_right : max a 0 = a := max_eq_left (zero_le a) theorem lt_iff_exists_rat_btwn : a < b ↔ ∃ q : ℚ, 0 ≤ q ∧ a < Real.toNNReal q ∧ (Real.toNNReal q : ℝ≥0∞) < b := ⟨fun h => by rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩ rcases exists_between h with ⟨c, pc, cb⟩ rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩ rcases (NNReal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩ exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩, fun ⟨_, _, qa, qb⟩ => lt_trans qa qb⟩ theorem lt_iff_exists_real_btwn : a < b ↔ ∃ r : ℝ, 0 ≤ r ∧ a < ENNReal.ofReal r ∧ (ENNReal.ofReal r : ℝ≥0∞) < b := ⟨fun h => let ⟨q, q0, aq, qb⟩ := ENNReal.lt_iff_exists_rat_btwn.1 h ⟨q, Rat.cast_nonneg.2 q0, aq, qb⟩, fun ⟨_, _, qa, qb⟩ => lt_trans qa qb⟩ theorem lt_iff_exists_nnreal_btwn : a < b ↔ ∃ r : ℝ≥0, a < r ∧ (r : ℝ≥0∞) < b := WithTop.lt_iff_exists_coe_btwn theorem lt_iff_exists_add_pos_lt : a < b ↔ ∃ r : ℝ≥0, 0 < r ∧ a + r < b := by refine ⟨fun hab => ?_, fun ⟨r, _, hr⟩ => lt_of_le_of_lt le_self_add hr⟩ rcases lt_iff_exists_nnreal_btwn.1 hab with ⟨c, ac, cb⟩ lift a to ℝ≥0 using ac.ne_top rw [coe_lt_coe] at ac refine ⟨c - a, tsub_pos_iff_lt.2 ac, ?_⟩ rwa [← coe_add, add_tsub_cancel_of_le ac.le] theorem le_of_forall_pos_le_add (h : ∀ ε : ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) : a ≤ b := by contrapose! h rcases lt_iff_exists_add_pos_lt.1 h with ⟨r, hr0, hr⟩ exact ⟨r, hr0, h.trans_le le_top, hr⟩ theorem natCast_lt_coe {n : ℕ} : n < (r : ℝ≥0∞) ↔ n < r := ENNReal.coe_natCast n ▸ coe_lt_coe theorem coe_lt_natCast {n : ℕ} : (r : ℝ≥0∞) < n ↔ r < n := ENNReal.coe_natCast n ▸ coe_lt_coe protected theorem exists_nat_gt {r : ℝ≥0∞} (h : r ≠ ∞) : ∃ n : ℕ, r < n := by lift r to ℝ≥0 using h rcases exists_nat_gt r with ⟨n, hn⟩ exact ⟨n, coe_lt_natCast.2 hn⟩ @[simp] theorem iUnion_Iio_coe_nat : ⋃ n : ℕ, Iio (n : ℝ≥0∞) = {∞}ᶜ := by ext x rw [mem_iUnion] exact ⟨fun ⟨n, hn⟩ => ne_top_of_lt hn, ENNReal.exists_nat_gt⟩ @[simp] theorem iUnion_Iic_coe_nat : ⋃ n : ℕ, Iic (n : ℝ≥0∞) = {∞}ᶜ := Subset.antisymm (iUnion_subset fun n _x hx => ne_top_of_le_ne_top (natCast_ne_top n) hx) <| iUnion_Iio_coe_nat ▸ iUnion_mono fun _ => Iio_subset_Iic_self @[simp] theorem iUnion_Ioc_coe_nat : ⋃ n : ℕ, Ioc a n = Ioi a \ {∞} := by simp only [← Ioi_inter_Iic, ← inter_iUnion, iUnion_Iic_coe_nat, diff_eq] @[simp] theorem iUnion_Ioo_coe_nat : ⋃ n : ℕ, Ioo a n = Ioi a \ {∞} := by simp only [← Ioi_inter_Iio, ← inter_iUnion, iUnion_Iio_coe_nat, diff_eq] @[simp] theorem iUnion_Icc_coe_nat : ⋃ n : ℕ, Icc a n = Ici a \ {∞} := by simp only [← Ici_inter_Iic, ← inter_iUnion, iUnion_Iic_coe_nat, diff_eq] @[simp] theorem iUnion_Ico_coe_nat : ⋃ n : ℕ, Ico a n = Ici a \ {∞} := by simp only [← Ici_inter_Iio, ← inter_iUnion, iUnion_Iio_coe_nat, diff_eq] @[simp] theorem iInter_Ici_coe_nat : ⋂ n : ℕ, Ici (n : ℝ≥0∞) = {∞} := by simp only [← compl_Iio, ← compl_iUnion, iUnion_Iio_coe_nat, compl_compl] @[simp] theorem iInter_Ioi_coe_nat : ⋂ n : ℕ, Ioi (n : ℝ≥0∞) = {∞} := by simp only [← compl_Iic, ← compl_iUnion, iUnion_Iic_coe_nat, compl_compl] @[simp, norm_cast] theorem coe_min (r p : ℝ≥0) : ((min r p : ℝ≥0) : ℝ≥0∞) = min (r : ℝ≥0∞) p := rfl @[simp, norm_cast] theorem coe_max (r p : ℝ≥0) : ((max r p : ℝ≥0) : ℝ≥0∞) = max (r : ℝ≥0∞) p := rfl theorem le_of_top_imp_top_of_toNNReal_le {a b : ℝ≥0∞} (h : a = ⊤ → b = ⊤) (h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.toNNReal ≤ b.toNNReal) : a ≤ b := by by_contra! hlt lift b to ℝ≥0 using hlt.ne_top lift a to ℝ≥0 using mt h coe_ne_top refine hlt.not_ge ?_ simpa using h_nnreal @[simp] theorem abs_toReal {x : ℝ≥0∞} : |x.toReal| = x.toReal := by cases x <;> simp end Order section CompleteLattice variable {ι : Sort*} {f : ι → ℝ≥0} theorem coe_sSup {s : Set ℝ≥0} : BddAbove s → (↑(sSup s) : ℝ≥0∞) = ⨆ a ∈ s, ↑a := WithTop.coe_sSup theorem coe_sInf {s : Set ℝ≥0} (hs : s.Nonempty) : (↑(sInf s) : ℝ≥0∞) = ⨅ a ∈ s, ↑a := WithTop.coe_sInf hs (OrderBot.bddBelow s) theorem coe_iSup {ι : Sort*} {f : ι → ℝ≥0} (hf : BddAbove (range f)) : (↑(iSup f) : ℝ≥0∞) = ⨆ a, ↑(f a) := WithTop.coe_iSup _ hf @[norm_cast] theorem coe_iInf {ι : Sort*} [Nonempty ι] (f : ι → ℝ≥0) : (↑(iInf f) : ℝ≥0∞) = ⨅ a, ↑(f a) := WithTop.coe_iInf (OrderBot.bddBelow _) theorem coe_mem_upperBounds {s : Set ℝ≥0} : ↑r ∈ upperBounds (ofNNReal '' s) ↔ r ∈ upperBounds s := by simp +contextual [upperBounds, forall_mem_image, -mem_image, *] lemma iSup_coe_eq_top : ⨆ i, (f i : ℝ≥0∞) = ⊤ ↔ ¬ BddAbove (range f) := WithTop.iSup_coe_eq_top lemma iSup_coe_lt_top : ⨆ i, (f i : ℝ≥0∞) < ⊤ ↔ BddAbove (range f) := WithTop.iSup_coe_lt_top lemma iInf_coe_eq_top : ⨅ i, (f i : ℝ≥0∞) = ⊤ ↔ IsEmpty ι := WithTop.iInf_coe_eq_top lemma iInf_coe_lt_top : ⨅ i, (f i : ℝ≥0∞) < ⊤ ↔ Nonempty ι := WithTop.iInf_coe_lt_top end CompleteLattice section Bit -- TODO: add lemmas about `OfNat.ofNat` end Bit end ENNReal open ENNReal namespace Set namespace OrdConnected variable {s : Set ℝ} {t : Set ℝ≥0} {u : Set ℝ≥0∞} theorem preimage_coe_nnreal_ennreal (h : u.OrdConnected) : ((↑) ⁻¹' u : Set ℝ≥0).OrdConnected := h.preimage_mono ENNReal.coe_mono -- TODO: generalize to `WithTop` theorem image_coe_nnreal_ennreal (h : t.OrdConnected) : ((↑) '' t : Set ℝ≥0∞).OrdConnected := by refine ⟨forall_mem_image.2 fun x hx => forall_mem_image.2 fun y hy z hz => ?_⟩ rcases ENNReal.le_coe_iff.1 hz.2 with ⟨z, rfl, -⟩ exact mem_image_of_mem _ (h.out hx hy ⟨ENNReal.coe_le_coe.1 hz.1, ENNReal.coe_le_coe.1 hz.2⟩) theorem preimage_ennreal_ofReal (h : u.OrdConnected) : (ENNReal.ofReal ⁻¹' u).OrdConnected := h.preimage_coe_nnreal_ennreal.preimage_real_toNNReal theorem image_ennreal_ofReal (h : s.OrdConnected) : (ENNReal.ofReal '' s).OrdConnected := by simpa only [image_image] using h.image_real_toNNReal.image_coe_nnreal_ennreal end OrdConnected end Set /-- While not very useful, this instance uses the same representation as `Real.instRepr`. -/ unsafe instance : Repr ℝ≥0∞ where reprPrec | (r : ℝ≥0), p => Repr.addAppParen f!"ENNReal.ofReal ({repr r.val})" p | ∞, _ => "∞" namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for the `positivity` tactic: `ENNReal.toReal`. -/ @[positivity ENNReal.toReal _] def evalENNRealtoReal : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ), ~q(ENNReal.toReal $a) => assertInstancesCommute pure (.nonnegative q(ENNReal.toReal_nonneg)) | _, _, _ => throwError "not ENNReal.toReal" /-- Extension for the `positivity` tactic: `ENNReal.ofNNReal`. -/ @[positivity ENNReal.ofNNReal _] def evalENNRealOfNNReal : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ≥0∞), ~q(ENNReal.ofNNReal $a) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure <| .positive q(ENNReal.coe_pos.mpr $pa) | _ => pure .none | _, _, _ => throwError "not ENNReal.ofNNReal" end Mathlib.Meta.Positivity
Idempotent.lean
/- Copyright (c) 2022 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import Mathlib.Algebra.GroupWithZero.Idempotent import Mathlib.Algebra.Ring.Defs import Mathlib.Order.Notation import Mathlib.Tactic.Convert import Mathlib.Algebra.Group.Torsion /-! # Idempotent elements of a ring This file proves result about idempotent elements of a ring, like: * `IsIdempotentElem.one_sub_iff`: In a (non-associative) ring, `a` is an idempotent if and only if `1 - a` is an idempotent. -/ variable {R : Type*} namespace IsIdempotentElem section NonAssocRing variable [NonAssocRing R] {a : R} lemma one_sub (h : IsIdempotentElem a) : IsIdempotentElem (1 - a) := by rw [IsIdempotentElem, mul_sub, mul_one, sub_mul, one_mul, h.eq, sub_self, sub_zero] @[simp] lemma one_sub_iff : IsIdempotentElem (1 - a) ↔ IsIdempotentElem a := ⟨fun h => sub_sub_cancel 1 a ▸ h.one_sub, IsIdempotentElem.one_sub⟩ @[simp] lemma mul_one_sub_self (h : IsIdempotentElem a) : a * (1 - a) = 0 := by rw [mul_sub, mul_one, h.eq, sub_self] @[simp] lemma one_sub_mul_self (h : IsIdempotentElem a) : (1 - a) * a = 0 := by rw [sub_mul, one_mul, h.eq, sub_self] lemma _root_.isIdempotentElem_iff_mul_one_sub_self : IsIdempotentElem a ↔ a * (1 - a) = 0 := by rw [mul_sub, mul_one, sub_eq_zero, eq_comm, IsIdempotentElem] lemma _root_.isIdempotentElem_iff_one_sub_mul_self : IsIdempotentElem a ↔ (1 - a) * a = 0 := by rw [sub_mul, one_mul, sub_eq_zero, eq_comm, IsIdempotentElem] instance : HasCompl {a : R // IsIdempotentElem a} where compl a := ⟨1 - a, a.prop.one_sub⟩ @[simp] lemma coe_compl (a : {a : R // IsIdempotentElem a}) : ↑aᶜ = (1 : R) - ↑a := rfl @[simp] lemma compl_compl (a : {a : R // IsIdempotentElem a}) : aᶜᶜ = a := by ext; simp @[simp] lemma zero_compl : (0 : {a : R // IsIdempotentElem a})ᶜ = 1 := by ext; simp @[simp] lemma one_compl : (1 : {a : R // IsIdempotentElem a})ᶜ = 0 := by ext; simp end NonAssocRing section Semiring variable [Semiring R] {a b : R} lemma of_mul_add (mul : a * b = 0) (add : a + b = 1) : IsIdempotentElem a ∧ IsIdempotentElem b := by simp_rw [IsIdempotentElem]; constructor · conv_rhs => rw [← mul_one a, ← add, mul_add, mul, add_zero] · conv_rhs => rw [← one_mul b, ← add, add_mul, mul, zero_add] end Semiring section NonUnitalRing variable [NonUnitalRing R] {a b : R} lemma add_sub_mul_of_commute (h : Commute a b) (ha : IsIdempotentElem a) (hb : IsIdempotentElem b) : IsIdempotentElem (a + b - a * b) := by simp only [IsIdempotentElem, h.eq, mul_sub, mul_add, sub_mul, add_mul, ha.eq, mul_assoc, add_sub_cancel_right, hb.eq, hb.mul_self_mul, add_sub_cancel_left, sub_right_inj] rw [← h.eq, ha.mul_self_mul, h.eq, hb.mul_self_mul, add_sub_cancel_right] end NonUnitalRing section CommRing variable [CommRing R] {a b : R} lemma add_sub_mul (hp : IsIdempotentElem a) (hq : IsIdempotentElem b) : IsIdempotentElem (a + b - a * b) := add_sub_mul_of_commute (.all ..) hp hq end CommRing /-- `a + b` is idempotent when `a` and `b` anti-commute. -/ theorem add [NonUnitalNonAssocSemiring R] {a b : R} (ha : IsIdempotentElem a) (hb : IsIdempotentElem b) (hab : a * b + b * a = 0) : IsIdempotentElem (a + b) := by simp_rw [IsIdempotentElem, mul_add, add_mul, ha.eq, hb.eq, add_add_add_comm, ← add_assoc, add_assoc a, hab, zero_add] /-- `a + b` is idempotent if and only if `a` and `b` anti-commute. -/ theorem add_iff [NonUnitalNonAssocSemiring R] [IsCancelAdd R] {a b : R} (ha : IsIdempotentElem a) (hb : IsIdempotentElem b) : IsIdempotentElem (a + b) ↔ a * b + b * a = 0 := by refine ⟨fun h ↦ ?_, ha.add hb⟩ have : a + b * a + (a * b + b) = a + b := by simpa [add_mul, mul_add, ha.eq, hb.eq] using h.eq rw [← add_right_cancel_iff (a := b), add_assoc, ← add_left_cancel_iff (a := a), ← add_assoc, add_add_add_comm] simpa [add_mul, mul_add, ha.eq, hb.eq] using h.eq /-- `b - a` is idempotent when `a * b = a` and `b * a = a`. -/ lemma sub [NonUnitalNonAssocRing R] {a b : R} (ha : IsIdempotentElem a) (hb : IsIdempotentElem b) (hab : a * b = a) (hba : b * a = a) : IsIdempotentElem (b - a) := by simp_rw [IsIdempotentElem, sub_mul, mul_sub, hab, hba, ha.eq, hb.eq, sub_self, sub_zero] /-- If idempotent `a` and element `b` anti-commute, then their product is zero. -/ theorem mul_eq_zero_of_anticommute {a b : R} [NonUnitalSemiring R] [IsAddTorsionFree R] (ha : IsIdempotentElem a) (hab : a * b + b * a = 0) : a * b = 0 := by have h : a * b * a = 0 := by rw [← nsmul_right_inj ((Nat.zero_ne_add_one 1).symm), nsmul_zero] have : a * (a * b + b * a) * a = 0 := by rw [hab, mul_zero, zero_mul] simp_rw [mul_add, add_mul, mul_assoc, ha.eq, ← mul_assoc, ha.eq, ← two_nsmul] at this exact this suffices a * a * b + a * b * a = 0 by rwa [h, add_zero, ha.eq] at this rw [mul_assoc, mul_assoc, ← mul_add, hab, mul_zero] /-- If idempotent `a` and element `b` anti-commute, then they commute. So anti-commutativity implies commutativity when one of them is idempotent. -/ lemma commute_of_anticommute {a b : R} [NonUnitalSemiring R] [IsAddTorsionFree R] (ha : IsIdempotentElem a) (hab : a * b + b * a = 0) : Commute a b := by have := mul_eq_zero_of_anticommute ha hab rw [this, zero_add] at hab rw [Commute, SemiconjBy, hab, this] theorem sub_iff [NonUnitalRing R] [IsAddTorsionFree R] {p q : R} (hp : IsIdempotentElem p) (hq : IsIdempotentElem q) : IsIdempotentElem (q - p) ↔ p * q = p ∧ q * p = p := by refine ⟨fun hqp ↦ ?_, fun ⟨h1, h2⟩ => hp.sub hq h1 h2⟩ have h : p * (q - p) + (q - p) * p = 0 := hp.add_iff hqp |>.mp ((add_sub_cancel p q).symm ▸ hq) have hpq : Commute p q := by simp_rw [IsIdempotentElem, mul_sub, sub_mul, hp.eq, hq.eq, ← sub_add_eq_sub_sub, sub_right_inj, add_sub] at hqp have h1 := congr_arg (q * ·) hqp have h2 := congr_arg (· * q) hqp simp_rw [mul_sub, mul_add, ← mul_assoc, hq.eq, add_sub_cancel_right] at h1 simp_rw [sub_mul, add_mul, mul_assoc, hq.eq, add_sub_cancel_left, ← mul_assoc] at h2 exact h2.symm.trans h1 rw [hpq.eq, and_self, ← nsmul_right_inj (by simp : 2 ≠ 0), ← zero_add (2 • p)] convert congrArg (· + 2 • p) h using 1 simp [sub_mul, mul_sub, hp.eq, hpq.eq, two_nsmul, sub_add, sub_sub] end IsIdempotentElem
test_regular_conv.v
From mathcomp Require Import all_boot all_order all_algebra all_field. Section regular. Import GRing. Goal forall R : ringType, [the lalgType R of R^o] = R :> ringType. Proof. by move=> [? []]. Qed. Goal forall R : comRingType, [the algType R of R^o] = R :> ringType. Proof. by move=> [? []]. Qed. Goal forall R : comRingType, [the comAlgType R of R^o] = R :> ringType. Proof. by move=> [? []]. Qed. Goal forall R : comUnitRingType, [the unitAlgType R of R^o] = R :> unitRingType. Proof. by move=> [? []]. Qed. Goal forall R : comUnitRingType, [the comUnitAlgType R of R^o] = R :> comUnitRingType. Proof. by move=> [? []]. Qed. Goal forall R : comUnitRingType, [the falgType R of R^o] = R :> unitRingType. Proof. by move=> [? []]. Qed. Goal forall K : fieldType, [the fieldExtType K of K^o] = K :> fieldType. Proof. by move=> [? []]. Qed. End regular.
Clopen.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import Mathlib.Data.Set.BoolIndicator import Mathlib.Topology.ContinuousOn /-! # Clopen sets A clopen set is a set that is both closed and open. -/ open Set Filter Topology TopologicalSpace universe u v variable {X : Type u} {Y : Type v} {ι : Type*} variable [TopologicalSpace X] [TopologicalSpace Y] {s t : Set X} section Clopen protected theorem IsClopen.isOpen (hs : IsClopen s) : IsOpen s := hs.2 protected theorem IsClopen.isClosed (hs : IsClopen s) : IsClosed s := hs.1 theorem isClopen_iff_frontier_eq_empty : IsClopen s ↔ frontier s = ∅ := by rw [IsClopen, ← closure_eq_iff_isClosed, ← interior_eq_iff_isOpen, frontier, diff_eq_empty] refine ⟨fun h => (h.1.trans h.2.symm).subset, fun h => ?_⟩ exact ⟨(h.trans interior_subset).antisymm subset_closure, interior_subset.antisymm (subset_closure.trans h)⟩ @[simp] alias ⟨IsClopen.frontier_eq, _⟩ := isClopen_iff_frontier_eq_empty theorem IsClopen.union (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ∪ t) := ⟨hs.1.union ht.1, hs.2.union ht.2⟩ theorem IsClopen.inter (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ∩ t) := ⟨hs.1.inter ht.1, hs.2.inter ht.2⟩ theorem isClopen_empty : IsClopen (∅ : Set X) := ⟨isClosed_empty, isOpen_empty⟩ theorem isClopen_univ : IsClopen (univ : Set X) := ⟨isClosed_univ, isOpen_univ⟩ theorem IsClopen.compl (hs : IsClopen s) : IsClopen sᶜ := ⟨hs.2.isClosed_compl, hs.1.isOpen_compl⟩ @[simp] theorem isClopen_compl_iff : IsClopen sᶜ ↔ IsClopen s := ⟨fun h => compl_compl s ▸ IsClopen.compl h, IsClopen.compl⟩ theorem IsClopen.diff (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s \ t) := hs.inter ht.compl lemma IsClopen.himp (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ⇨ t) := by simpa [himp_eq] using ht.union hs.compl theorem IsClopen.prod {t : Set Y} (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ×ˢ t) := ⟨hs.1.prod ht.1, hs.2.prod ht.2⟩ theorem isClopen_iUnion_of_finite {Y} [Finite Y] {s : Y → Set X} (h : ∀ i, IsClopen (s i)) : IsClopen (⋃ i, s i) := ⟨isClosed_iUnion_of_finite (forall_and.1 h).1, isOpen_iUnion (forall_and.1 h).2⟩ theorem Set.Finite.isClopen_biUnion {Y} {s : Set Y} {f : Y → Set X} (hs : s.Finite) (h : ∀ i ∈ s, IsClopen <| f i) : IsClopen (⋃ i ∈ s, f i) := ⟨hs.isClosed_biUnion fun i hi => (h i hi).1, isOpen_biUnion fun i hi => (h i hi).2⟩ theorem isClopen_biUnion_finset {Y} {s : Finset Y} {f : Y → Set X} (h : ∀ i ∈ s, IsClopen <| f i) : IsClopen (⋃ i ∈ s, f i) := s.finite_toSet.isClopen_biUnion h theorem isClopen_iInter_of_finite {Y} [Finite Y] {s : Y → Set X} (h : ∀ i, IsClopen (s i)) : IsClopen (⋂ i, s i) := ⟨isClosed_iInter (forall_and.1 h).1, isOpen_iInter_of_finite (forall_and.1 h).2⟩ theorem Set.Finite.isClopen_biInter {Y} {s : Set Y} (hs : s.Finite) {f : Y → Set X} (h : ∀ i ∈ s, IsClopen (f i)) : IsClopen (⋂ i ∈ s, f i) := ⟨isClosed_biInter fun i hi => (h i hi).1, hs.isOpen_biInter fun i hi => (h i hi).2⟩ theorem isClopen_biInter_finset {Y} {s : Finset Y} {f : Y → Set X} (h : ∀ i ∈ s, IsClopen (f i)) : IsClopen (⋂ i ∈ s, f i) := s.finite_toSet.isClopen_biInter h theorem IsClopen.preimage {s : Set Y} (h : IsClopen s) {f : X → Y} (hf : Continuous f) : IsClopen (f ⁻¹' s) := ⟨h.1.preimage hf, h.2.preimage hf⟩ theorem ContinuousOn.preimage_isClopen_of_isClopen {f : X → Y} {s : Set X} {t : Set Y} (hf : ContinuousOn f s) (hs : IsClopen s) (ht : IsClopen t) : IsClopen (s ∩ f ⁻¹' t) := ⟨ContinuousOn.preimage_isClosed_of_isClosed hf hs.1 ht.1, ContinuousOn.isOpen_inter_preimage hf hs.2 ht.2⟩ /-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/ theorem isClopen_inter_of_disjoint_cover_clopen {s a b : Set X} (h : IsClopen s) (cover : s ⊆ a ∪ b) (ha : IsOpen a) (hb : IsOpen b) (hab : Disjoint a b) : IsClopen (s ∩ a) := by refine ⟨?_, IsOpen.inter h.2 ha⟩ have : IsClosed (s ∩ bᶜ) := IsClosed.inter h.1 (isClosed_compl_iff.2 hb) convert this using 1 refine (inter_subset_inter_right s hab.subset_compl_right).antisymm ?_ rintro x ⟨hx₁, hx₂⟩ exact ⟨hx₁, by simpa [notMem_of_mem_compl hx₂] using cover hx₁⟩ theorem isClopen_of_disjoint_cover_open {a b : Set X} (cover : univ ⊆ a ∪ b) (ha : IsOpen a) (hb : IsOpen b) (hab : Disjoint a b) : IsClopen a := univ_inter a ▸ isClopen_inter_of_disjoint_cover_clopen isClopen_univ cover ha hb hab @[simp] theorem isClopen_discrete [DiscreteTopology X] (s : Set X) : IsClopen s := ⟨isClosed_discrete _, isOpen_discrete _⟩ theorem isClopen_range_inl : IsClopen (range (Sum.inl : X → X ⊕ Y)) := ⟨isClosed_range_inl, isOpen_range_inl⟩ theorem isClopen_range_inr : IsClopen (range (Sum.inr : Y → X ⊕ Y)) := ⟨isClosed_range_inr, isOpen_range_inr⟩ theorem isClopen_range_sigmaMk {X : ι → Type*} [∀ i, TopologicalSpace (X i)] {i : ι} : IsClopen (Set.range (@Sigma.mk ι X i)) := ⟨IsClosedEmbedding.sigmaMk.isClosed_range, IsOpenEmbedding.sigmaMk.isOpen_range⟩ protected theorem Topology.IsQuotientMap.isClopen_preimage {f : X → Y} (hf : IsQuotientMap f) {s : Set Y} : IsClopen (f ⁻¹' s) ↔ IsClopen s := and_congr hf.isClosed_preimage hf.isOpen_preimage theorem continuous_boolIndicator_iff_isClopen (U : Set X) : Continuous U.boolIndicator ↔ IsClopen U := by rw [continuous_bool_rng true, preimage_boolIndicator_true] theorem continuousOn_boolIndicator_iff_isClopen (s U : Set X) : ContinuousOn U.boolIndicator s ↔ IsClopen (((↑) : s → X) ⁻¹' U) := by rw [continuousOn_iff_continuous_restrict, ← continuous_boolIndicator_iff_isClopen] rfl end Clopen
IrreducibleDef.lean
/- Copyright (c) 2021 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import Mathlib.Data.Subtype import Mathlib.Tactic.Eqns import Mathlib.Util.TermReduce /-! # Irreducible definitions This file defines an `irreducible_def` command, which works almost like the `def` command except that the introduced definition does not reduce to the value. Instead, the command adds a `_def` lemma which can be used for rewriting. ``` irreducible_def frobnicate (a b : Nat) := a + b example : frobnicate a 0 = a := by simp [frobnicate_def] ``` -/ namespace Lean.Elab.Command open Term Meta /-- `eta_helper f = (· + 3)` elabs to `∀ x, f x = x + 3` -/ local elab "eta_helper " t:term : term => do let t ← elabTerm t none let some (_, lhs, rhs) := t.eq? | throwError "not an equation: {t}" synthesizeSyntheticMVars let rhs ← instantiateMVars rhs lambdaTelescope rhs fun xs rhs ↦ do let lhs := (mkAppN lhs xs).headBeta mkForallFVars xs <|← mkEq lhs rhs /-- `val_proj x` elabs to the *primitive projection* `@x.val`. -/ local elab "val_proj " e:term : term => do let e ← elabTerm (← `(($e : Subtype _))) none return mkProj ``Subtype 0 e /-- Executes the commands, and stops after the first error. In short, S-A-F-E. -/ local syntax "stop_at_first_error" (ppLine command)* : command open Command in elab_rules : command | `(stop_at_first_error $[$cmds]*) => do for cmd in cmds do elabCommand cmd.raw if (← get).messages.hasErrors then break syntax irredDefLemma := atomic(" (" &"lemma" " := ") ident ")" /-- Introduces an irreducible definition. `irreducible_def foo := 42` generates a constant `foo : Nat` as well as a theorem `foo_def : foo = 42`. -/ elab mods:declModifiers "irreducible_def" n_id:declId n_def:(irredDefLemma)? declSig:ppIndent(optDeclSig) val:declVal : command => do let declSig : TSyntax ``Parser.Command.optDeclSig := ⟨declSig.raw⟩ -- HACK let (n, us) ← match n_id with | `(Parser.Command.declId| $n:ident $[.{$us,*}]?) => pure (n, us) | _ => throwUnsupportedSyntax let us' := us.getD { elemsAndSeps := #[] } let n_def ← match n_def.getD ⟨mkNullNode⟩ with | `(irredDefLemma| (lemma := $id)) => pure id | _ => pure <| mkIdentFrom n <| (·.review) <| let scopes := extractMacroScopes n.getId { scopes with name := scopes.name.appendAfter "_def" } let `(Parser.Command.declModifiersF| $[$doc:docComment]? $[@[$attrs,*]]? $[$vis]? $[$prot:protected]? $[$nc:noncomputable]? $[$uns:unsafe]?) := mods | throwError "unsupported modifiers {format mods}" let attrs := attrs.getD {} let priv := vis.filter (· matches `(Parser.Command.visibility| private)) elabCommand <|<- `(stop_at_first_error $[$nc:noncomputable]? $[$uns]? def definition$[.{$us,*}]? $declSig:optDeclSig $val $[$nc:noncomputable]? $[$uns]? opaque wrapped$[.{$us,*}]? : Subtype (Eq @definition.{$us',*}) := ⟨_, rfl⟩ $[$doc:docComment]? $[private%$priv]? $[$nc:noncomputable]? $[$uns]? def $n:ident$[.{$us,*}]? := val_proj @wrapped.{$us',*} $[private%$priv]? $[$uns:unsafe]? theorem $n_def:ident $[.{$us,*}]? : eta_helper Eq @$n.{$us',*} @(delta% @definition) := by intros delta $n:ident rw [show wrapped = ⟨@definition.{$us',*}, rfl⟩ from Subtype.ext wrapped.2.symm] rfl attribute [irreducible] $n definition attribute [eqns $n_def] $n attribute [$attrs:attrInstance,*] $n) if prot.isSome then modifyEnv (addProtected · ((← getCurrNamespace) ++ n.getId)) end Lean.Elab.Command
all_order.v
Require Export order.
LocalPredicate.lean
/- Copyright (c) 2020 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kim Morrison, Adam Topaz -/ import Mathlib.Topology.Sheaves.SheafOfFunctions import Mathlib.Topology.Sheaves.Stalks import Mathlib.Topology.Sheaves.SheafCondition.UniqueGluing /-! # Functions satisfying a local predicate form a sheaf. At this stage, in `Mathlib/Topology/Sheaves/SheafOfFunctions.lean` we've proved that not-necessarily-continuous functions from a topological space into some type (or type family) form a sheaf. Why do the continuous functions form a sheaf? The point is just that continuity is a local condition, so one can use the lifting condition for functions to provide a candidate lift, then verify that the lift is actually continuous by using the factorisation condition for the lift (which guarantees that on each open set it agrees with the functions being lifted, which were assumed to be continuous). This file abstracts this argument to work for any collection of dependent functions on a topological space satisfying a "local predicate". As an application, we check that continuity is a local predicate in this sense, and provide * `TopCat.sheafToTop`: continuous functions into a topological space form a sheaf A sheaf constructed in this way has a natural map `stalkToFiber` from the stalks to the types in the ambient type family. We give conditions sufficient to show that this map is injective and/or surjective. -/ noncomputable section variable {X : TopCat} variable (T : X → Type*) open TopologicalSpace open Opposite open CategoryTheory open CategoryTheory.Limits open CategoryTheory.Limits.Types namespace TopCat /-- Given a topological space `X : TopCat` and a type family `T : X → Type`, a `P : PrelocalPredicate T` consists of: * a family of predicates `P.pred`, one for each `U : Opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : Opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate. -/ structure PrelocalPredicate where /-- The underlying predicate of a prelocal predicate -/ pred : ∀ {U : Opens X}, (∀ x : U, T x) → Prop /-- The underlying predicate should be invariant under restriction -/ res : ∀ {U V : Opens X} (i : U ⟶ V) (f : ∀ x : V, T x) (_ : pred f), pred fun x : U ↦ f (i x) variable (X) /-- Continuity is a "prelocal" predicate on functions to a fixed topological space `T`. -/ @[simps!] def continuousPrelocal (T) [TopologicalSpace T] : PrelocalPredicate fun _ : X ↦ T where pred {_} f := Continuous f res {_ _} i _ h := Continuous.comp h (Opens.isOpenEmbedding_of_le i.le).continuous /-- Satisfying the inhabited linter. -/ instance inhabitedPrelocalPredicate (T) [TopologicalSpace T] : Inhabited (PrelocalPredicate fun _ : X ↦ T) := ⟨continuousPrelocal X T⟩ variable {X} in /-- Given a topological space `X : TopCat` and a type family `T : X → Type`, a `P : LocalPredicate T` consists of: * a family of predicates `P.pred`, one for each `U : Opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : Opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate, and * a proof that given some `f : Π x : U, T x`, if for every `x : U` we can find an open set `x ∈ V ≤ U` so that the restriction of `f` to `V` satisfies the predicate, then `f` itself satisfies the predicate. -/ structure LocalPredicate extends PrelocalPredicate T where /-- A local predicate must be local --- provided that it is locally satisfied, it is also globally satisfied -/ locality : ∀ {U : Opens X} (f : ∀ x : U, T x) (_ : ∀ x : U, ∃ (V : Opens X) (_ : x.1 ∈ V) (i : V ⟶ U), pred fun x : V ↦ f (i x : U)), pred f /-- Continuity is a "local" predicate on functions to a fixed topological space `T`. -/ def continuousLocal (T) [TopologicalSpace T] : LocalPredicate fun _ : X ↦ T := { continuousPrelocal X T with locality := fun {U} f w ↦ by apply continuous_iff_continuousAt.2 intro x specialize w x rcases w with ⟨V, m, i, w⟩ dsimp at w rw [continuous_iff_continuousAt] at w specialize w ⟨x, m⟩ simpa using (Opens.isOpenEmbedding_of_le i.le).continuousAt_iff.1 w } /-- Satisfying the inhabited linter. -/ instance inhabitedLocalPredicate (T) [TopologicalSpace T] : Inhabited (LocalPredicate fun _ : X ↦ T) := ⟨continuousLocal X T⟩ variable {X T} /-- The conjunction of two prelocal predicates is prelocal. -/ def PrelocalPredicate.and (P Q : PrelocalPredicate T) : PrelocalPredicate T where pred f := P.pred f ∧ Q.pred f res i f h := ⟨P.res i f h.1, Q.res i f h.2⟩ /-- The conjunction of two prelocal predicates is prelocal. -/ def LocalPredicate.and (P Q : LocalPredicate T) : LocalPredicate T where __ := P.1.and Q.1 locality f w := by refine ⟨P.locality f ?_, Q.locality f ?_⟩ <;> (intro x; have ⟨V, hV, i, h⟩ := w x; use V, hV, i) exacts [h.1, h.2] /-- The local predicate of being a partial section of a function. -/ def isSection {T} (p : T → X) : LocalPredicate fun _ : X ↦ T where pred f := p ∘ f = (↑) res _ _ h := funext fun _ ↦ congr_fun h _ locality _ w := funext fun x ↦ have ⟨_, hV, _, h⟩ := w x; congr_fun h ⟨x, hV⟩ /-- Given a `P : PrelocalPredicate`, we can always construct a `LocalPredicate` by asking that the condition from `P` holds locally near every point. -/ def PrelocalPredicate.sheafify {T : X → Type*} (P : PrelocalPredicate T) : LocalPredicate T where pred {U} f := ∀ x : U, ∃ (V : Opens X) (_ : x.1 ∈ V) (i : V ⟶ U), P.pred fun x : V ↦ f (i x : U) res {V U} i f w x := by specialize w (i x) rcases w with ⟨V', m', i', p⟩ exact ⟨V ⊓ V', ⟨x.2, m'⟩, V.infLELeft _, P.res (V.infLERight V') _ p⟩ locality {U} f w x := by specialize w x rcases w with ⟨V, m, i, p⟩ specialize p ⟨x.1, m⟩ rcases p with ⟨V', m', i', p'⟩ exact ⟨V', m', i' ≫ i, p'⟩ namespace PrelocalPredicate theorem sheafifyOf {T : X → Type*} {P : PrelocalPredicate T} {U : Opens X} {f : ∀ x : U, T x} (h : P.pred f) : P.sheafify.pred f := fun x ↦ ⟨U, x.2, 𝟙 _, by convert h⟩ /-- For a unary operation (e.g. `x ↦ -x`) defined at each stalk, if a prelocal predicate is closed under the operation on each open set (possibly by refinement), then the sheafified predicate is also closed under the operation. See `sheafify_inductionOn'` for the version without refinement. -/ theorem sheafify_inductionOn {X : TopCat} {T : X → Type*} (P : PrelocalPredicate T) (op : {x : X} → T x → T x) (hop : ∀ {U : Opens X} {a : (x : U) → T x}, P.pred a → ∀ (p : U), ∃ (W : Opens X) (i : W ⟶ U), p.1 ∈ W ∧ P.pred fun x : W ↦ op (a (i x))) {U : Opens X} {a : (x : U) → T x} (ha : P.sheafify.pred a) : P.sheafify.pred (fun x : U ↦ op (a x)) := by intro x rcases ha x with ⟨Va, ma, ia, ha⟩ rcases hop ha ⟨x, ma⟩ with ⟨W, sa, hx, hw⟩ exact ⟨W, hx, sa ≫ ia, hw⟩ /-- For a unary operation (e.g. `x ↦ -x`) defined at each stalk, if a prelocal predicate is closed under the operation on each open set, then the sheafified predicate is also closed under the operation. See `sheafify_inductionOn` for the version with refinement. -/ theorem sheafify_inductionOn' {X : TopCat} {T : X → Type*} (P : PrelocalPredicate T) (op : {x : X} → T x → T x) (hop : ∀ {U : Opens X} {a : (x : U) → T x}, P.pred a → P.pred fun x : U ↦ op (a x)) {U : Opens X} {a : (x : U) → T x} (ha : P.sheafify.pred a) : P.sheafify.pred (fun x : U ↦ op (a x)) := P.sheafify_inductionOn op (fun ha p ↦ ⟨_, 𝟙 _, p.2, hop ha⟩) ha /-- For a binary operation (e.g. `x ↦ y ↦ x + y`) defined at each stalk, if a prelocal predicate is closed under the operation on each open set (possibly by refinement), then the sheafified predicate is also closed under the operation. See `sheafify_inductionOn₂'` for the version without refinement. -/ theorem sheafify_inductionOn₂ {X : TopCat} {T₁ T₂ T₃ : X → Type*} (P₁ : PrelocalPredicate T₁) (P₂ : PrelocalPredicate T₂) (P₃ : PrelocalPredicate T₃) (op : {x : X} → T₁ x → T₂ x → T₃ x) (hop : ∀ {U V : Opens X} {a : (x : U) → T₁ x} {b : (x : V) → T₂ x}, P₁.pred a → P₂.pred b → ∀ (p : (U ⊓ V : Opens X)), ∃ (W : Opens X) (ia : W ⟶ U) (ib : W ⟶ V), p.1 ∈ W ∧ P₃.pred fun x : W ↦ op (a (ia x)) (b (ib x))) {U : Opens X} {a : (x : U) → T₁ x} {b : (x : U) → T₂ x} (ha : P₁.sheafify.pred a) (hb : P₂.sheafify.pred b) : P₃.sheafify.pred (fun x : U ↦ op (a x) (b x)) := by intro x rcases ha x with ⟨Va, ma, ia, ha⟩ rcases hb x with ⟨Vb, mb, ib, hb⟩ rcases hop ha hb ⟨x, ma, mb⟩ with ⟨W, sa, sb, hx, hw⟩ exact ⟨W, hx, sa ≫ ia, hw⟩ /-- For a binary operation (e.g. `x ↦ y ↦ x + y`) defined at each stalk, if a prelocal predicate is closed under the operation on each open set, then the sheafified predicate is also closed under the operation. See `sheafify_inductionOn₂` for the version with refinement. -/ theorem sheafify_inductionOn₂' {X : TopCat} {T₁ T₂ T₃ : X → Type*} (P₁ : PrelocalPredicate T₁) (P₂ : PrelocalPredicate T₂) (P₃ : PrelocalPredicate T₃) (op : {x : X} → T₁ x → T₂ x → T₃ x) (hop : ∀ {U V : Opens X} {a : (x : U) → T₁ x} {b : (x : V) → T₂ x}, P₁.pred a → P₂.pred b → P₃.pred fun x : (U ⊓ V : Opens X) ↦ op (a ⟨x, x.2.1⟩) (b ⟨x, x.2.2⟩)) {U : Opens X} {a : (x : U) → T₁ x} {b : (x : U) → T₂ x} (ha : P₁.sheafify.pred a) (hb : P₂.sheafify.pred b) : P₃.sheafify.pred (fun x : U ↦ op (a x) (b x)) := P₁.sheafify_inductionOn₂ P₂ P₃ op (fun ha hb p ↦ ⟨_, Opens.infLELeft _ _, Opens.infLERight _ _, p.2, hop ha hb⟩) ha hb end PrelocalPredicate /-- The subpresheaf of dependent functions on `X` satisfying the "pre-local" predicate `P`. -/ @[simps!] def subpresheafToTypes (P : PrelocalPredicate T) : Presheaf (Type _) X where obj U := { f : ∀ x : U.unop , T x // P.pred f } map {_ _} i f := ⟨fun x ↦ f.1 (i.unop x), P.res i.unop f.1 f.2⟩ namespace subpresheafToTypes variable (P : PrelocalPredicate T) /-- The natural transformation including the subpresheaf of functions satisfying a local predicate into the presheaf of all functions. -/ def subtype : subpresheafToTypes P ⟶ presheafToTypes X T where app _ f := f.1 open TopCat.Presheaf attribute [local instance] Types.instFunLike Types.instConcreteCategory in /-- The functions satisfying a local predicate satisfy the sheaf condition. -/ theorem isSheaf (P : LocalPredicate T) : (subpresheafToTypes P.toPrelocalPredicate).IsSheaf := Presheaf.isSheaf_of_isSheafUniqueGluing_types _ fun ι U sf sf_comp ↦ by -- We show the sheaf condition in terms of unique gluing. -- First we obtain a family of sections for the underlying sheaf of functions, -- by forgetting that the predicate holds let sf' (i : ι) : (presheafToTypes X T).obj (op (U i)) := (sf i).val -- Since our original family is compatible, this one is as well have sf'_comp : (presheafToTypes X T).IsCompatible U sf' := fun i j ↦ congr_arg Subtype.val (sf_comp i j) -- So, we can obtain a unique gluing obtain ⟨gl, gl_spec, gl_uniq⟩ := (sheafToTypes X T).existsUnique_gluing U sf' -- `by exact` to help Lean infer the `ConcreteCategory` instance (by exact sf'_comp) refine ⟨⟨gl, ?_⟩, ?_, ?_⟩ · -- Our first goal is to show that this chosen gluing satisfies the -- predicate. Of course, we use locality of the predicate. apply P.locality rintro ⟨x, mem⟩ -- Once we're at a particular point `x`, we can select some open set `x ∈ U i`. choose i hi using Opens.mem_iSup.mp mem -- We claim that the predicate holds in `U i` use U i, hi, Opens.leSupr U i -- This follows, since our original family `sf` satisfies the predicate convert (sf i).property using 1 exact gl_spec i -- It remains to show that the chosen lift is really a gluing for the subsheaf and -- that it is unique. Both of which follow immediately from the corresponding facts -- in the sheaf of functions without the local predicate. · exact fun i ↦ Subtype.ext (gl_spec i) · intro gl' hgl' refine Subtype.ext ?_ exact gl_uniq gl'.1 fun i ↦ congr_arg Subtype.val (hgl' i) end subpresheafToTypes /-- The subsheaf of the sheaf of all dependently typed functions satisfying the local predicate `P`. -/ @[simps] def subsheafToTypes (P : LocalPredicate T) : Sheaf (Type _) X := ⟨subpresheafToTypes P.toPrelocalPredicate, subpresheafToTypes.isSheaf P⟩ /-- There is a canonical map from the stalk to the original fiber, given by evaluating sections. -/ def stalkToFiber (P : LocalPredicate T) (x : X) : (subsheafToTypes P).presheaf.stalk x ⟶ T x := by refine colimit.desc _ { pt := T x ι := { app := fun U f ↦ ?_ naturality := ?_ } } · exact f.1 ⟨x, (unop U).2⟩ · aesop theorem stalkToFiber_germ (P : LocalPredicate T) (U : Opens X) (x : X) (hx : x ∈ U) (f) : stalkToFiber P x ((subsheafToTypes P).presheaf.germ U x hx f) = f.1 ⟨x, hx⟩ := by simp [Presheaf.germ, stalkToFiber] /-- The `stalkToFiber` map is surjective at `x` if every point in the fiber `T x` has an allowed section passing through it. -/ theorem stalkToFiber_surjective (P : LocalPredicate T) (x : X) (w : ∀ t : T x, ∃ (U : OpenNhds x) (f : ∀ y : U.1, T y) (_ : P.pred f), f ⟨x, U.2⟩ = t) : Function.Surjective (stalkToFiber P x) := fun t ↦ by rcases w t with ⟨U, f, h, rfl⟩ fconstructor · exact (subsheafToTypes P).presheaf.germ _ x U.2 ⟨f, h⟩ · exact stalkToFiber_germ P U.1 x U.2 ⟨f, h⟩ /-- The `stalkToFiber` map is injective at `x` if any two allowed sections which agree at `x` agree on some neighborhood of `x`. -/ theorem stalkToFiber_injective (P : LocalPredicate T) (x : X) (w : ∀ (U V : OpenNhds x) (fU : ∀ y : U.1, T y) (_ : P.pred fU) (fV : ∀ y : V.1, T y) (_ : P.pred fV) (_ : fU ⟨x, U.2⟩ = fV ⟨x, V.2⟩), ∃ (W : OpenNhds x) (iU : W ⟶ U) (iV : W ⟶ V), ∀ w : W.1, fU (iU w : U.1) = fV (iV w : V.1)) : Function.Injective (stalkToFiber P x) := fun tU tV h ↦ by -- We promise to provide all the ingredients of the proof later: let Q : ∃ (W : (OpenNhds x)ᵒᵖ) (s : ∀ w : (unop W).1, T w) (hW : P.pred s), tU = (subsheafToTypes P).presheaf.germ _ x (unop W).2 ⟨s, hW⟩ ∧ tV = (subsheafToTypes P).presheaf.germ _ x (unop W).2 ⟨s, hW⟩ := ?_ · choose W s hW e using Q exact e.1.trans e.2.symm -- Then use induction to pick particular representatives of `tU tV : stalk x` obtain ⟨U, ⟨fU, hU⟩, rfl⟩ := jointly_surjective' tU obtain ⟨V, ⟨fV, hV⟩, rfl⟩ := jointly_surjective' tV -- Decompose everything into its constituent parts: dsimp simp only [stalkToFiber, Types.Colimit.ι_desc_apply'] at h specialize w (unop U) (unop V) fU hU fV hV h rcases w with ⟨W, iU, iV, w⟩ -- and put it back together again in the correct order. refine ⟨op W, fun w ↦ fU (iU w : (unop U).1), P.res ?_ _ hU, ?_⟩ · rcases W with ⟨W, m⟩ exact iU · exact ⟨colimit_sound iU.op (Subtype.eq rfl), colimit_sound iV.op (Subtype.eq (funext w).symm)⟩ universe u /-- Some repackaging: the presheaf of functions satisfying `continuousPrelocal` is just the same thing as the presheaf of continuous functions. -/ def subpresheafContinuousPrelocalIsoPresheafToTop {X : TopCat.{u}} (T : TopCat.{u}) : subpresheafToTypes (continuousPrelocal X T) ≅ presheafToTop X T := NatIso.ofComponents fun X ↦ { hom := by rintro ⟨f, c⟩; exact ofHom ⟨f, c⟩ inv := by rintro ⟨f, c⟩; exact ⟨f, c⟩ } /-- The sheaf of continuous functions on `X` with values in a space `T`. -/ def sheafToTop (T : TopCat) : Sheaf (Type _) X := ⟨presheafToTop X T, Presheaf.isSheaf_of_iso (subpresheafContinuousPrelocalIsoPresheafToTop T) (subpresheafToTypes.isSheaf (continuousLocal X T))⟩ end TopCat
intdiv.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 div choice fintype tuple prime order. From mathcomp Require Import ssralg poly ssrnum ssrint matrix. From mathcomp Require Import polydiv perm zmodp bigop. (******************************************************************************) (* This file provides various results on divisibility of integers. *) (* It defines, for m, n, d : int, *) (* (m %% d)%Z == the remainder of the Euclidean division of m by d; this is *) (* the least non-negative element of the coset m + dZ when *) (* d != 0, and m if d = 0. *) (* (m %/ d)%Z == the quotient of the Euclidean division of m by d, such *) (* that m = (m %/ d)%Z * d + (m %% d)%Z. Since for d != 0 the *) (* remainder is non-negative, (m %/ d)%Z is non-zero for *) (* negative m. *) (* (d %| m)%Z <=> m is divisible by d; dvdz d is the (collective) predicate *) (* for integers divisible by d, and (d %| m)%Z is actually *) (* (transposing) notation for m \in dvdz d. *) (* (m = n %[mod d])%Z, (m == n %[mod d])%Z, (m != n %[mod d])%Z *) (* m and n are (resp. compare, don't compare) equal mod d. *) (* gcdz m n == the (non-negative) greatest common divisor of m and n, *) (* with gcdz 0 0 = 0. *) (* lcmz m n == the (non-negative) least common multiple of m and n. *) (* coprimez m n <=> m and n are coprime. *) (* egcdz m n == the Bezout coefficients of the gcd of m and n: a pair *) (* (u, v) of coprime integers such that u*m + v*n = gcdz m n. *) (* Alternatively, a Bezoutz lemma states such u and v exist. *) (* zchinese m1 m2 n1 n2 == for coprime m1 and m2, a solution to the Chinese *) (* remainder problem for n1 and n2, i.e., and integer n such *) (* that n = n1 %[mod m1] and n = n2 %[mod m2]. *) (* zcontents p == the contents of p : {poly int}, that is, the gcd of the *) (* coefficients of p, with the same sign as the lead *) (* coefficient of p. *) (* zprimitive p == the primitive part of p : {poly int}, i.e., p divided by *) (* its contents. *) (* int_Smith_normal_form :: a theorem asserting the existence of the Smith *) (* normal form for integer matrices. *) (* Note that many of the concepts and results in this file could and perhaps *) (* should be generalized to the more general setting of integral, unique *) (* factorization, principal ideal, or Euclidean domains. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import Order.TTheory GRing.Theory Num.Theory. Local Open Scope ring_scope. Definition divz (m d : int) : int := let: (K, n) := match m with Posz n => (Posz, n) | Negz n => (Negz, n) end in sgz d * K (n %/ `|d|)%N. Definition modz (m d : int) : int := m - divz m d * d. Definition dvdz d m := (`|d| %| `|m|)%N. Definition gcdz m n := (gcdn `|m| `|n|)%:Z. Definition lcmz m n := (lcmn `|m| `|n|)%:Z. Definition egcdz m n : int * int := if m == 0 then (0, (-1) ^+ (n < 0)%R) else let: (u, v) := egcdn `|m| `|n| in (sgz m * u, - (-1) ^+ (n < 0)%R * v%:Z). Definition coprimez m n := (gcdz m n == 1). Infix "%/" := divz : int_scope. Infix "%%" := modz : int_scope. Notation "d %| m" := (m \in dvdz d) : int_scope. Notation "m = n %[mod d ]" := (modz m d = modz n d) : int_scope. Notation "m == n %[mod d ]" := (modz m d == modz n d) : int_scope. Notation "m <> n %[mod d ]" := (modz m d <> modz n d) : int_scope. Notation "m != n %[mod d ]" := (modz m d != modz n d) : int_scope. Lemma divz_nat (n d : nat) : (n %/ d)%Z = (n %/ d)%N. Proof. by case: d => // d; rewrite /divz /= mul1r. Qed. Lemma divzN m d : (m %/ - d)%Z = - (m %/ d)%Z. Proof. by case: m => n; rewrite /divz /= sgzN abszN mulNr. Qed. Lemma divz_abs (m d : int) : (m %/ `|d|)%Z = (-1) ^+ (d < 0)%R * (m %/ d)%Z. Proof. by rewrite {3}[d]intEsign !mulr_sign; case: ifP => -> //; rewrite divzN opprK. Qed. Lemma div0z d : (0 %/ d)%Z = 0. Proof. by rewrite -(canLR (signrMK _) (divz_abs _ _)) (divz_nat 0) div0n mulr0. Qed. Lemma divNz_nat m d : (d > 0)%N -> (Negz m %/ d)%Z = - (m %/ d).+1%:Z. Proof. by case: d => // d _; apply: mul1r. Qed. Lemma divz_eq m d : m = (m %/ d)%Z * d + (m %% d)%Z. Proof. by rewrite addrC subrK. Qed. Lemma modzN m d : (m %% - d)%Z = (m %% d)%Z. Proof. by rewrite /modz divzN mulrNN. Qed. Lemma modz_abs m d : (m %% `|d|%N)%Z = (m %% d)%Z. Proof. by rewrite {2}[d]intEsign mulr_sign; case: ifP; rewrite ?modzN. Qed. Lemma modz_nat (m d : nat) : (m %% d)%Z = (m %% d)%N. Proof. by apply: (canLR (addrK _)); rewrite addrC divz_nat {1}(divn_eq m d). Qed. Lemma modNz_nat m d : (d > 0)%N -> (Negz m %% d)%Z = d%:Z - 1 - (m %% d)%:Z. Proof. rewrite /modz => /divNz_nat->; apply: (canLR (addrK _)). rewrite -!addrA -!opprD -!PoszD -opprB mulnSr !addnA PoszD addrK. by rewrite addnAC -addnA mulnC -divn_eq. Qed. Lemma modz_ge0 m d : d != 0 -> 0 <= (m %% d)%Z. Proof. rewrite -absz_gt0 -modz_abs => d_gt0. case: m => n; rewrite ?modNz_nat ?modz_nat // -addrA -opprD subr_ge0. by rewrite lez_nat ltn_mod. Qed. Lemma divz0 m : (m %/ 0)%Z = 0. Proof. by case: m. Qed. Lemma mod0z d : (0 %% d)%Z = 0. Proof. by rewrite /modz div0z mul0r subrr. Qed. Lemma modz0 m : (m %% 0)%Z = m. Proof. by rewrite /modz mulr0 subr0. Qed. Lemma divz_small m d : 0 <= m < `|d|%:Z -> (m %/ d)%Z = 0. Proof. rewrite -(canLR (signrMK _) (divz_abs _ _)); case: m => // n /divn_small. by rewrite divz_nat => ->; rewrite mulr0. Qed. Lemma divzMDl q m d : d != 0 -> ((q * d + m) %/ d)%Z = q + (m %/ d)%Z. Proof. rewrite neq_lt -oppr_gt0 => nz_d. wlog{nz_d} d_gt0: q d / d > 0; last case: d => // d in d_gt0 *. move=> IH; case/orP: nz_d => /IH// /(_ (- q)). by rewrite mulrNN !divzN -opprD => /oppr_inj. wlog q_gt0: q m / q >= 0; last case: q q_gt0 => // q _. move=> IH; case: q => n; first exact: IH; rewrite NegzE mulNr. by apply: canRL (addKr _) _; rewrite -IH ?addNKr. case: m => n; first by rewrite !divz_nat divnMDl. have [le_qd_n | lt_qd_n] := leqP (q * d) n. rewrite divNz_nat // NegzE -(subnKC le_qd_n) divnMDl //. by rewrite -!addnS !PoszD !opprD !addNKr divNz_nat. rewrite divNz_nat // NegzE -PoszM subzn // divz_nat. apply: canRL (addrK _) _; congr _%:Z; rewrite addnC -divnMDl // mulSnr. rewrite -{3}(subnKC (ltn_pmod n d_gt0)) addnA addnS -divn_eq addnAC. by rewrite subnKC // divnMDl // divn_small ?addn0 // subnSK ?ltn_mod ?leq_subr. Qed. Lemma mulzK m d : d != 0 -> (m * d %/ d)%Z = m. Proof. by move=> d_nz; rewrite -[m * d]addr0 divzMDl // div0z addr0. Qed. Lemma mulKz m d : d != 0 -> (d * m %/ d)%Z = m. Proof. by move=> d_nz; rewrite mulrC mulzK. Qed. Lemma expzB p m n : p != 0 -> (m >= n)%N -> p ^+ (m - n) = (p ^+ m %/ p ^+ n)%Z. Proof. by move=> p_nz /subnK{2}<-; rewrite exprD mulzK // expf_neq0. Qed. Lemma modz1 m : (m %% 1)%Z = 0. Proof. by case: m => n; rewrite (modNz_nat, modz_nat) ?modn1. Qed. Lemma divz1 m : (m %/ 1)%Z = m. Proof. by rewrite -{1}[m]mulr1 mulzK. Qed. Lemma divzz d : (d %/ d)%Z = (d != 0). Proof. by have [-> // | d_nz] := eqVneq; rewrite -{1}[d]mul1r mulzK. Qed. Lemma ltz_pmod m d : d > 0 -> (m %% d)%Z < d. Proof. case: m d => n [] // d d_gt0; first by rewrite modz_nat ltz_nat ltn_pmod. by rewrite modNz_nat // -lezD1 addrAC subrK gerDl oppr_le0. Qed. Lemma ltz_mod m d : d != 0 -> (m %% d)%Z < `|d|. Proof. by rewrite -absz_gt0 -modz_abs => d_gt0; apply: ltz_pmod. Qed. Lemma divzMpl p m d : p > 0 -> (p * m %/ (p * d) = m %/ d)%Z. Proof. case: p => // p p_gt0; wlog d_gt0: d / d > 0; last case: d => // d in d_gt0 *. by move=> IH; case/intP: d => [|d|d]; rewrite ?mulr0 ?divz0 ?mulrN ?divzN ?IH. rewrite {1}(divz_eq m d) mulrDr mulrCA divzMDl ?mulf_neq0 ?gt_eqF // addrC. rewrite divz_small ?add0r // PoszM pmulr_rge0 ?modz_ge0 ?gt_eqF //=. by rewrite ltr_pM2l ?ltz_pmod. Qed. Arguments divzMpl [p m d]. Lemma divzMpr p m d : p > 0 -> (m * p %/ (d * p) = m %/ d)%Z. Proof. by move=> p_gt0; rewrite -!(mulrC p) divzMpl. Qed. Arguments divzMpr [p m d]. Lemma lez_floor m d : d != 0 -> (m %/ d)%Z * d <= m. Proof. by rewrite -subr_ge0; apply: modz_ge0. Qed. (* leq_mod does not extend to negative m. *) Lemma lez_div m d : (`|(m %/ d)%Z| <= `|m|)%N. Proof. wlog d_gt0: d / d > 0; last case: d d_gt0 => // d d_gt0. by move=> IH; case/intP: d => [|n|n]; rewrite ?divz0 ?divzN ?abszN // IH. case: m => n; first by rewrite divz_nat leq_div. by rewrite divNz_nat // NegzE !abszN ltnS leq_div. Qed. Lemma ltz_ceil m d : d > 0 -> m < ((m %/ d)%Z + 1) * d. Proof. by case: d => // d d_gt0; rewrite mulrDl mul1r -ltrBlDl ltz_mod ?gt_eqF. Qed. Lemma ltz_divLR m n d : d > 0 -> ((m %/ d)%Z < n) = (m < n * d). Proof. move=> d_gt0; apply/idP/idP. by rewrite -[_ < n]lezD1 -(ler_pM2r d_gt0); exact/lt_le_trans/ltz_ceil. by rewrite -(ltr_pM2r d_gt0 _ n); apply/le_lt_trans/lez_floor; rewrite gt_eqF. Qed. Lemma lez_divRL m n d : d > 0 -> (m <= (n %/ d)%Z) = (m * d <= n). Proof. by move=> d_gt0; rewrite !leNgt ltz_divLR. Qed. Lemma lez_pdiv2r d : 0 <= d -> {homo divz^~ d : m n / m <= n}. Proof. by case: d => [[|d]|]// _ [] m [] n //; rewrite /divz !mul1r; apply: leq_div2r. Qed. Lemma divz_ge0 m d : d > 0 -> ((m %/ d)%Z >= 0) = (m >= 0). Proof. by case: d m => // d [] n d_gt0; rewrite (divz_nat, divNz_nat). Qed. Lemma divzMA_ge0 m n p : n >= 0 -> (m %/ (n * p) = (m %/ n)%Z %/ p)%Z. Proof. case: n => // [[|n]] _; first by rewrite mul0r !divz0 div0z. wlog p_gt0: p / p > 0; last case: p => // p in p_gt0 *. by case/intP: p => [|p|p] IH; rewrite ?mulr0 ?divz0 ?mulrN ?divzN // IH. rewrite {2}(divz_eq m (n.+1%:Z * p)) mulrA mulrAC !divzMDl // ?gt_eqF //. rewrite [rhs in _ + rhs]divz_small ?addr0 // ltz_divLR // divz_ge0 //. by rewrite mulrC ltz_pmod ?modz_ge0 ?gt_eqF ?pmulr_lgt0. Qed. Lemma modz_small m d : 0 <= m < d -> (m %% d)%Z = m. Proof. by case: m d => //= m [] // d; rewrite modz_nat => /modn_small->. Qed. Lemma modz_mod m d : ((m %% d)%Z = m %[mod d])%Z. Proof. rewrite -!(modz_abs _ d); case: {d}`|d|%N => [|d]; first by rewrite !modz0. by rewrite modz_small ?modz_ge0 ?ltz_mod. Qed. Lemma modzMDl p m d : (p * d + m = m %[mod d])%Z. Proof. have [-> | d_nz] := eqVneq d 0; first by rewrite mulr0 add0r. by rewrite /modz divzMDl // mulrDl opprD addrACA subrr add0r. Qed. Lemma mulz_modr {p m d} : 0 < p -> p * (m %% d)%Z = ((p * m) %% (p * d))%Z. Proof. case: p => // p p_gt0; rewrite mulrBr; apply: canLR (addrK _) _. by rewrite mulrCA -(divzMpl p_gt0) subrK. Qed. Lemma mulz_modl {p m d} : 0 < p -> (m %% d)%Z * p = ((m * p) %% (d * p))%Z. Proof. by rewrite -!(mulrC p); apply: mulz_modr. Qed. Lemma modzDl m d : (d + m = m %[mod d])%Z. Proof. by rewrite -{1}[d]mul1r modzMDl. Qed. Lemma modzDr m d : (m + d = m %[mod d])%Z. Proof. by rewrite addrC modzDl. Qed. Lemma modzz d : (d %% d)%Z = 0. Proof. by rewrite -{1}[d]addr0 modzDl mod0z. Qed. Lemma modzMl p d : (p * d %% d)%Z = 0. Proof. by rewrite -[p * d]addr0 modzMDl mod0z. Qed. Lemma modzMr p d : (d * p %% d)%Z = 0. Proof. by rewrite mulrC modzMl. Qed. Lemma modzDml m n d : ((m %% d)%Z + n = m + n %[mod d])%Z. Proof. by rewrite {2}(divz_eq m d) -[_ * d + _ + n]addrA modzMDl. Qed. Lemma modzDmr m n d : (m + (n %% d)%Z = m + n %[mod d])%Z. Proof. by rewrite !(addrC m) modzDml. Qed. Lemma modzDm m n d : ((m %% d)%Z + (n %% d)%Z = m + n %[mod d])%Z. Proof. by rewrite modzDml modzDmr. Qed. Lemma eqz_modDl p m n d : (p + m == p + n %[mod d])%Z = (m == n %[mod d])%Z. Proof. have [-> | d_nz] := eqVneq d 0; first by rewrite !modz0 (inj_eq (addrI p)). apply/eqP/eqP=> eq_mn; last by rewrite -modzDmr eq_mn modzDmr. by rewrite -(addKr p m) -modzDmr eq_mn modzDmr addKr. Qed. Lemma eqz_modDr p m n d : (m + p == n + p %[mod d])%Z = (m == n %[mod d])%Z. Proof. by rewrite -!(addrC p) eqz_modDl. Qed. Lemma modzMml m n d : ((m %% d)%Z * n = m * n %[mod d])%Z. Proof. by rewrite {2}(divz_eq m d) [in RHS]mulrDl mulrAC modzMDl. Qed. (* FIXME: rewrite pattern *) Lemma modzMmr m n d : (m * (n %% d)%Z = m * n %[mod d])%Z. Proof. by rewrite !(mulrC m) modzMml. Qed. Lemma modzMm m n d : ((m %% d)%Z * (n %% d)%Z = m * n %[mod d])%Z. Proof. by rewrite modzMml modzMmr. Qed. Lemma modzXm k m d : ((m %% d)%Z ^+ k = m ^+ k %[mod d])%Z. Proof. by elim: k => // k IHk; rewrite !exprS -modzMmr IHk modzMm. Qed. Lemma modzNm m d : (- (m %% d)%Z = - m %[mod d])%Z. Proof. by rewrite -mulN1r modzMmr mulN1r. Qed. Lemma modz_absm m d : ((-1) ^+ (m < 0)%R * (m %% d)%Z = `|m|%:Z %[mod d])%Z. Proof. by rewrite modzMmr -abszEsign. Qed. (** Divisibility **) Lemma dvdzE d m : (d %| m)%Z = (`|d| %| `|m|)%N. Proof. by []. Qed. Lemma dvdz0 d : (d %| 0)%Z. Proof. exact: dvdn0. Qed. Lemma dvd0z n : (0 %| n)%Z = (n == 0). Proof. by rewrite -absz_eq0 -dvd0n. Qed. Lemma dvdz1 d : (d %| 1)%Z = (`|d|%N == 1). Proof. exact: dvdn1. Qed. Lemma dvd1z m : (1 %| m)%Z. Proof. exact: dvd1n. Qed. Lemma dvdzz m : (m %| m)%Z. Proof. exact: dvdnn. Qed. Lemma dvdz_mull d m n : (d %| n)%Z -> (d %| m * n)%Z. Proof. by rewrite !dvdzE abszM; apply: dvdn_mull. Qed. Lemma dvdz_mulr d m n : (d %| m)%Z -> (d %| m * n)%Z. Proof. by move=> d_m; rewrite mulrC dvdz_mull. Qed. #[global] Hint Resolve dvdz0 dvd1z dvdzz dvdz_mull dvdz_mulr : core. Lemma dvdz_mul d1 d2 m1 m2 : (d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2)%Z. Proof. by rewrite !dvdzE !abszM; apply: dvdn_mul. Qed. Lemma dvdz_trans n d m : (d %| n -> n %| m -> d %| m)%Z. Proof. by rewrite !dvdzE; apply: dvdn_trans. Qed. Lemma dvdzP d m : reflect (exists q, m = q * d) (d %| m)%Z. Proof. apply: (iffP dvdnP) => [] [q Dm]; last by exists `|q|%N; rewrite Dm abszM. exists ((-1) ^+ (m < 0)%R * q%:Z * (-1) ^+ (d < 0)%R). by rewrite -!mulrA -abszEsign -PoszM -Dm -intEsign. Qed. Arguments dvdzP {d m}. Lemma dvdz_mod0P d m : reflect (m %% d = 0)%Z (d %| m)%Z. Proof. apply: (iffP dvdzP) => [[q ->] | md0]; first by rewrite modzMl. by rewrite (divz_eq m d) md0 addr0; exists (m %/ d)%Z. Qed. Arguments dvdz_mod0P {d m}. Lemma dvdz_eq d m : (d %| m)%Z = ((m %/ d)%Z * d == m). Proof. by rewrite (sameP dvdz_mod0P eqP) subr_eq0 eq_sym. Qed. Lemma divzK d m : (d %| m)%Z -> (m %/ d)%Z * d = m. Proof. by rewrite dvdz_eq => /eqP. Qed. Lemma lez_divLR d m n : 0 < d -> (d %| m)%Z -> ((m %/ d)%Z <= n) = (m <= n * d). Proof. by move=> /ler_pM2r <- /divzK->. Qed. Lemma ltz_divRL d m n : 0 < d -> (d %| m)%Z -> (n < m %/ d)%Z = (n * d < m). Proof. by move=> /ltr_pM2r/(_ n)<- /divzK->. Qed. Lemma eqz_div d m n : d != 0 -> (d %| m)%Z -> (n == m %/ d)%Z = (n * d == m). Proof. by move=> /mulIf/inj_eq <- /divzK->. Qed. Lemma eqz_mul d m n : d != 0 -> (d %| m)%Z -> (m == n * d) = (m %/ d == n)%Z. Proof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqz_div // eq_sym. Qed. Lemma divz_mulAC d m n : (d %| m)%Z -> (m %/ d)%Z * n = (m * n %/ d)%Z. Proof. have [-> | d_nz] := eqVneq d 0; first by rewrite !divz0 mul0r. by move/divzK=> {2} <-; rewrite mulrAC mulzK. Qed. Lemma mulz_divA d m n : (d %| n)%Z -> m * (n %/ d)%Z = (m * n %/ d)%Z. Proof. by move=> dv_d_m; rewrite !(mulrC m) divz_mulAC. Qed. Lemma mulz_divCA d m n : (d %| m)%Z -> (d %| n)%Z -> m * (n %/ d)%Z = n * (m %/ d)%Z. Proof. by move=> dv_d_m dv_d_n; rewrite mulrC divz_mulAC ?mulz_divA. Qed. Lemma divzA m n p : (p %| n -> n %| m * p -> m %/ (n %/ p)%Z = m * p %/ n)%Z. Proof. move/divzK=> p_dv_n; have [->|] := eqVneq n 0; first by rewrite div0z !divz0. rewrite -{1 2}p_dv_n mulf_eq0 => /norP[pn_nz p_nz] /divzK; rewrite mulrA p_dv_n. by move/mulIf=> {1} <- //; rewrite mulzK. Qed. Lemma divzMA m n p : (n * p %| m -> m %/ (n * p) = (m %/ n)%Z %/ p)%Z. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 !divz0. have [-> | nz_n] := eqVneq n 0; first by rewrite mul0r !divz0 div0z. by move/divzK=> {2} <-; rewrite mulrA mulrAC !mulzK. Qed. Lemma divzAC m n p : (n * p %| m -> (m %/ n)%Z %/ p = (m %/ p)%Z %/ n)%Z. Proof. by move=> np_dv_mn; rewrite -!divzMA // mulrC. Qed. Lemma divzMl p m d : p != 0 -> (d %| m -> p * m %/ (p * d) = m %/ d)%Z. Proof. have [-> | nz_d nz_p] := eqVneq d 0; first by rewrite mulr0 !divz0. by move/divzK=> {1}<-; rewrite mulrCA mulzK ?mulf_neq0. Qed. Lemma divzMr p m d : p != 0 -> (d %| m -> m * p %/ (d * p) = m %/ d)%Z. Proof. by rewrite -!(mulrC p); apply: divzMl. Qed. Lemma dvdz_mul2l p d m : p != 0 -> (p * d %| p * m)%Z = (d %| m)%Z. Proof. by rewrite !dvdzE -absz_gt0 !abszM; apply: dvdn_pmul2l. Qed. Arguments dvdz_mul2l [p d m]. Lemma dvdz_mul2r p d m : p != 0 -> (d * p %| m * p)%Z = (d %| m)%Z. Proof. by rewrite !dvdzE -absz_gt0 !abszM; apply: dvdn_pmul2r. Qed. Arguments dvdz_mul2r [p d m]. Lemma dvdz_exp2l p m n : (m <= n)%N -> (p ^+ m %| p ^+ n)%Z. Proof. by rewrite dvdzE !abszX; apply: dvdn_exp2l. Qed. Lemma dvdz_Pexp2l p m n : `|p| > 1 -> (p ^+ m %| p ^+ n)%Z = (m <= n)%N. Proof. by rewrite dvdzE !abszX ltz_nat; apply: dvdn_Pexp2l. Qed. Lemma dvdz_exp2r m n k : (m %| n -> m ^+ k %| n ^+ k)%Z. Proof. by rewrite !dvdzE !abszX; apply: dvdn_exp2r. Qed. Fact dvdz_zmod_closed d : zmod_closed (dvdz d). Proof. split=> [|_ _ /dvdzP[p ->] /dvdzP[q ->]]; first exact: dvdz0. by rewrite -mulrBl dvdz_mull. Qed. HB.instance Definition _ d := GRing.isZmodClosed.Build int (dvdz d) (dvdz_zmod_closed d). Lemma dvdz_exp k d m : (0 < k)%N -> (d %| m -> d %| m ^+ k)%Z. Proof. by case: k => // k _ d_dv_m; rewrite exprS dvdz_mulr. Qed. Lemma eqz_mod_dvd d m n : (m == n %[mod d])%Z = (d %| m - n)%Z. Proof. apply/eqP/dvdz_mod0P=> eq_mn. by rewrite -modzDml eq_mn modzDml subrr mod0z. by rewrite -(subrK n m) -modzDml eq_mn add0r. Qed. Lemma divzDl m n d : (d %| m)%Z -> ((m + n) %/ d)%Z = (m %/ d)%Z + (n %/ d)%Z. Proof. have [-> | d_nz] := eqVneq d 0; first by rewrite !divz0. by move/divzK=> {1}<-; rewrite divzMDl. Qed. Lemma divzDr m n d : (d %| n)%Z -> ((m + n) %/ d)%Z = (m %/ d)%Z + (n %/ d)%Z. Proof. by move=> dv_n; rewrite addrC divzDl // addrC. Qed. Lemma dvdz_pcharf (R : nzRingType) p : p \in [pchar R] -> forall n : int, (p %| n)%Z = (n%:~R == 0 :> R). Proof. move=> pcharRp [] n; rewrite [LHS](dvdn_pcharf pcharRp)//. by rewrite NegzE abszN rmorphN// oppr_eq0. Qed. #[deprecated(since="mathcomp 2.4.0", note="Use dvdz_pcharf instead.")] Notation dvdz_charf chRp := (dvdz_pcharf chRp). (* Greatest common divisor *) Lemma gcdzz m : gcdz m m = `|m|%:Z. Proof. by rewrite /gcdz gcdnn. Qed. Lemma gcdzC : commutative gcdz. Proof. by move=> m n; rewrite /gcdz gcdnC. Qed. Lemma gcd0z m : gcdz 0 m = `|m|%:Z. Proof. by rewrite /gcdz gcd0n. Qed. Lemma gcdz0 m : gcdz m 0 = `|m|%:Z. Proof. by rewrite /gcdz gcdn0. Qed. Lemma gcd1z : left_zero 1 gcdz. Proof. by move=> m; rewrite /gcdz gcd1n. Qed. Lemma gcdz1 : right_zero 1 gcdz. Proof. by move=> m; rewrite /gcdz gcdn1. Qed. Lemma dvdz_gcdr m n : (gcdz m n %| n)%Z. Proof. exact: dvdn_gcdr. Qed. Lemma dvdz_gcdl m n : (gcdz m n %| m)%Z. Proof. exact: dvdn_gcdl. Qed. Lemma gcdz_eq0 m n : (gcdz m n == 0) = (m == 0) && (n == 0). Proof. by rewrite -absz_eq0 eqn0Ngt gcdn_gt0 !negb_or -!eqn0Ngt !absz_eq0. Qed. Lemma gcdNz m n : gcdz (- m) n = gcdz m n. Proof. by rewrite /gcdz abszN. Qed. Lemma gcdzN m n : gcdz m (- n) = gcdz m n. Proof. by rewrite /gcdz abszN. Qed. Lemma gcdz_modr m n : gcdz m (n %% m)%Z = gcdz m n. Proof. rewrite -modz_abs /gcdz; move/absz: m => m. have [-> | m_gt0] := posnP m; first by rewrite modz0. case: n => n; first by rewrite modz_nat gcdn_modr. rewrite modNz_nat // NegzE abszN {2}(divn_eq n m) -addnS gcdnMDl. rewrite -addrA -opprD -intS /=; set m1 := _.+1. have le_m1m: (m1 <= m)%N by apply: ltn_pmod. by rewrite subzn // !(gcdnC m) -{2 3}(subnK le_m1m) gcdnDl gcdnDr gcdnC. Qed. Lemma gcdz_modl m n : gcdz (m %% n)%Z n = gcdz m n. Proof. by rewrite -!(gcdzC n) gcdz_modr. Qed. Lemma gcdzMDl q m n : gcdz m (q * m + n) = gcdz m n. Proof. by rewrite -gcdz_modr modzMDl gcdz_modr. Qed. Lemma gcdzDl m n : gcdz m (m + n) = gcdz m n. Proof. by rewrite -{2}(mul1r m) gcdzMDl. Qed. Lemma gcdzDr m n : gcdz m (n + m) = gcdz m n. Proof. by rewrite addrC gcdzDl. Qed. Lemma gcdzMl n m : gcdz n (m * n) = `|n|%:Z. Proof. by rewrite -[m * n]addr0 gcdzMDl gcdz0. Qed. Lemma gcdzMr n m : gcdz n (n * m) = `|n|%:Z. Proof. by rewrite mulrC gcdzMl. Qed. Lemma gcdz_idPl {m n} : reflect (gcdz m n = `|m|%:Z) (m %| n)%Z. Proof. by apply: (iffP gcdn_idPl) => [<- | []]. Qed. Lemma gcdz_idPr {m n} : reflect (gcdz m n = `|n|%:Z) (n %| m)%Z. Proof. by rewrite gcdzC; apply: gcdz_idPl. Qed. Lemma expz_min e m n : e >= 0 -> e ^+ minn m n = gcdz (e ^+ m) (e ^+ n). Proof. by case: e => // e _; rewrite /gcdz !abszX -expn_min -natz -natrX !natz. Qed. Lemma dvdz_gcd p m n : (p %| gcdz m n)%Z = (p %| m)%Z && (p %| n)%Z. Proof. exact: dvdn_gcd. Qed. Lemma gcdzAC : right_commutative gcdz. Proof. by move=> m n p; rewrite /gcdz gcdnAC. Qed. Lemma gcdzA : associative gcdz. Proof. by move=> m n p; rewrite /gcdz gcdnA. Qed. Lemma gcdzCA : left_commutative gcdz. Proof. by move=> m n p; rewrite /gcdz gcdnCA. Qed. Lemma gcdzACA : interchange gcdz gcdz. Proof. by move=> m n p q; rewrite /gcdz gcdnACA. Qed. Lemma mulz_gcdr m n p : `|m|%:Z * gcdz n p = gcdz (m * n) (m * p). Proof. by rewrite -PoszM muln_gcdr -!abszM. Qed. Lemma mulz_gcdl m n p : gcdz m n * `|p|%:Z = gcdz (m * p) (n * p). Proof. by rewrite -PoszM muln_gcdl -!abszM. Qed. Lemma mulz_divCA_gcd n m : n * (m %/ gcdz n m)%Z = m * (n %/ gcdz n m)%Z. Proof. by rewrite mulz_divCA ?dvdz_gcdl ?dvdz_gcdr. Qed. (* Least common multiple *) Lemma dvdz_lcmr m n : (n %| lcmz m n)%Z. Proof. exact: dvdn_lcmr. Qed. Lemma dvdz_lcml m n : (m %| lcmz m n)%Z. Proof. exact: dvdn_lcml. Qed. Lemma dvdz_lcm d1 d2 m : ((lcmn d1 d2 %| m) = (d1 %| m) && (d2 %| m))%Z. Proof. exact: dvdn_lcm. Qed. Lemma lcmzC : commutative lcmz. Proof. by move=> m n; rewrite /lcmz lcmnC. Qed. Lemma lcm0z : left_zero 0 lcmz. Proof. by move=> x; rewrite /lcmz absz0 lcm0n. Qed. Lemma lcmz0 : right_zero 0 lcmz. Proof. by move=> x; rewrite /lcmz absz0 lcmn0. Qed. Lemma lcmz_ge0 m n : 0 <= lcmz m n. Proof. by []. Qed. Lemma lcmz_neq0 m n : (lcmz m n != 0) = (m != 0) && (n != 0). Proof. have [->|m_neq0] := eqVneq m 0; first by rewrite lcm0z. have [->|n_neq0] := eqVneq n 0; first by rewrite lcmz0. by rewrite gt_eqF// [0 < _]lcmn_gt0 !absz_gt0 m_neq0 n_neq0. Qed. (* Coprime factors *) Lemma coprimezE m n : coprimez m n = coprime `|m| `|n|. Proof. by []. Qed. Lemma coprimez_sym : symmetric coprimez. Proof. by move=> m n; apply: coprime_sym. Qed. Lemma coprimeNz m n : coprimez (- m) n = coprimez m n. Proof. by rewrite coprimezE abszN. Qed. Lemma coprimezN m n : coprimez m (- n) = coprimez m n. Proof. by rewrite coprimezE abszN. Qed. Variant egcdz_spec m n : int * int -> Type := EgcdzSpec u v of u * m + v * n = gcdz m n & coprimez u v : egcdz_spec m n (u, v). Lemma egcdzP m n : egcdz_spec m n (egcdz m n). Proof. rewrite /egcdz; have [-> | m_nz] := eqVneq. by split; [rewrite -abszEsign gcd0z | rewrite coprimezE absz_sign]. have m_gt0 : (`|m| > 0)%N by rewrite absz_gt0. case: egcdnP (coprime_egcdn `|n| m_gt0) => //= u v Duv _ co_uv; split. rewrite !mulNr -!mulrA mulrCA -abszEsg mulrCA -abszEsign. by rewrite -!PoszM Duv addnC PoszD addrK. by rewrite coprimezE abszM absz_sg m_nz mul1n mulNr abszN abszMsign. Qed. Lemma Bezoutz m n : {u : int & {v : int | u * m + v * n = gcdz m n}}. Proof. by exists (egcdz m n).1, (egcdz m n).2; case: egcdzP. Qed. Lemma coprimezP m n : reflect (exists uv, uv.1 * m + uv.2 * n = 1) (coprimez m n). Proof. apply: (iffP eqP) => [<-| [[u v] /= Duv]]. by exists (egcdz m n); case: egcdzP. congr _%:Z; apply: gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m. by rewrite -(dvdzE d 1) -Duv [m]intEsg [n]intEsg rpredD ?dvdz_mull. Qed. Lemma Gauss_dvdz m n p : coprimez m n -> (m * n %| p)%Z = (m %| p)%Z && (n %| p)%Z. Proof. by move/Gauss_dvd <-; rewrite -abszM. Qed. Lemma Gauss_dvdzr m n p : coprimez m n -> (m %| n * p)%Z = (m %| p)%Z. Proof. by rewrite dvdzE abszM => /Gauss_dvdr->. Qed. Lemma Gauss_dvdzl m n p : coprimez m p -> (m %| n * p)%Z = (m %| n)%Z. Proof. by rewrite mulrC; apply: Gauss_dvdzr. Qed. Lemma Gauss_gcdzr p m n : coprimez p m -> gcdz p (m * n) = gcdz p n. Proof. by rewrite /gcdz abszM => /Gauss_gcdr->. Qed. Lemma Gauss_gcdzl p m n : coprimez p n -> gcdz p (m * n) = gcdz p m. Proof. by move=> co_pn; rewrite mulrC Gauss_gcdzr. Qed. Lemma coprimezMr p m n : coprimez p (m * n) = coprimez p m && coprimez p n. Proof. by rewrite -coprimeMr -abszM. Qed. Lemma coprimezMl p m n : coprimez (m * n) p = coprimez m p && coprimez n p. Proof. by rewrite -coprimeMl -abszM. Qed. Lemma coprimez_pexpl k m n : (0 < k)%N -> coprimez (m ^+ k) n = coprimez m n. Proof. by rewrite /coprimez /gcdz abszX; apply: coprime_pexpl. Qed. Lemma coprimez_pexpr k m n : (0 < k)%N -> coprimez m (n ^+ k) = coprimez m n. Proof. by move=> k_gt0; rewrite !(coprimez_sym m) coprimez_pexpl. Qed. Lemma coprimezXl k m n : coprimez m n -> coprimez (m ^+ k) n. Proof. by rewrite /coprimez /gcdz abszX; apply: coprimeXl. Qed. Lemma coprimezXr k m n : coprimez m n -> coprimez m (n ^+ k). Proof. by rewrite !(coprimez_sym m); apply: coprimezXl. Qed. Lemma coprimez_dvdl m n p : (m %| n)%N -> coprimez n p -> coprimez m p. Proof. exact: coprime_dvdl. Qed. Lemma coprimez_dvdr m n p : (m %| n)%N -> coprimez p n -> coprimez p m. Proof. exact: coprime_dvdr. Qed. Lemma dvdz_pexp2r m n k : (k > 0)%N -> (m ^+ k %| n ^+ k)%Z = (m %| n)%Z. Proof. by rewrite dvdzE !abszX; apply: dvdn_pexp2r. Qed. Section Chinese. (***********************************************************************) (* The chinese remainder theorem *) (***********************************************************************) Variables m1 m2 : int. Hypothesis co_m12 : coprimez m1 m2. Lemma zchinese_remainder x y : (x == y %[mod m1 * m2])%Z = (x == y %[mod m1])%Z && (x == y %[mod m2])%Z. Proof. by rewrite !eqz_mod_dvd Gauss_dvdz. Qed. (***********************************************************************) (* A function that solves the chinese remainder problem *) (***********************************************************************) Definition zchinese r1 r2 := r1 * m2 * (egcdz m1 m2).2 + r2 * m1 * (egcdz m1 m2).1. Lemma zchinese_modl r1 r2 : (zchinese r1 r2 = r1 %[mod m1])%Z. Proof. rewrite /zchinese; have [u v /= Duv _] := egcdzP m1 m2. rewrite -{2}[r1]mulr1 -((gcdz _ _ =P 1) co_m12) -Duv. by rewrite mulrDr mulrAC addrC (mulrAC r2) !mulrA !modzMDl. Qed. Lemma zchinese_modr r1 r2 : (zchinese r1 r2 = r2 %[mod m2])%Z. Proof. rewrite /zchinese; have [u v /= Duv _] := egcdzP m1 m2. rewrite -{2}[r2]mulr1 -((gcdz _ _ =P 1) co_m12) -Duv. by rewrite mulrAC modzMDl mulrAC addrC mulrDr !mulrA modzMDl. Qed. Lemma zchinese_mod x : (x = zchinese (x %% m1)%Z (x %% m2)%Z %[mod m1 * m2])%Z. Proof. apply/eqP; rewrite zchinese_remainder //. by rewrite zchinese_modl zchinese_modr !modz_mod !eqxx. Qed. End Chinese. Section ZpolyScale. Definition zcontents (p : {poly int}) : int := sgz (lead_coef p) * \big[gcdn/0]_(i < size p) `|(p`_i)%R|%N. Lemma sgz_contents p : sgz (zcontents p) = sgz (lead_coef p). Proof. rewrite /zcontents mulrC sgzM sgz_id; set d := _%:Z. have [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 mulr0. rewrite gtr0_sgz ?mul1r // ltz_nat polySpred ?big_ord_recr //= -lead_coefE. by rewrite gcdn_gt0 orbC absz_gt0 lead_coef_eq0 nz_p. Qed. Lemma zcontents_eq0 p : (zcontents p == 0) = (p == 0). Proof. by rewrite -sgz_eq0 sgz_contents sgz_eq0 lead_coef_eq0. Qed. Lemma zcontents0 : zcontents 0 = 0. Proof. by apply/eqP; rewrite zcontents_eq0. Qed. Lemma zcontentsZ a p : zcontents (a *: p) = a * zcontents p. Proof. have [-> | nz_a] := eqVneq a 0; first by rewrite scale0r mul0r zcontents0. rewrite {2}[a]intEsg mulrCA -mulrA -PoszM big_distrr /= mulrCA mulrA -sgzM. rewrite -lead_coefZ; congr (_ * _%:Z); rewrite size_scale //. by apply: eq_bigr => i _; rewrite coefZ abszM. Qed. Lemma zcontents_monic p : p \is monic -> zcontents p = 1. Proof. move=> mon_p; rewrite /zcontents polySpred ?monic_neq0 //. by rewrite big_ord_recr /= -lead_coefE (monicP mon_p) gcdn1. Qed. Lemma dvdz_contents a p : (a %| zcontents p)%Z = (p \is a polyOver (dvdz a)). Proof. rewrite dvdzE abszM absz_sg lead_coef_eq0. have [-> | nz_p] := eqVneq; first by rewrite mul0n dvdn0 rpred0. rewrite mul1n; apply/dvdn_biggcdP/(all_nthP 0)=> a_dv_p i ltip /=. exact: (a_dv_p (Ordinal ltip)). exact: a_dv_p. Qed. Lemma map_poly_divzK {a} p : p \is a polyOver (dvdz a) -> a *: map_poly (divz^~ a) p = p. Proof. move/polyOverP=> a_dv_p; apply/polyP=> i. by rewrite coefZ coef_map_id0 ?div0z // mulrC divzK. Qed. Lemma polyOver_dvdzP a p : reflect (exists q, p = a *: q) (p \is a polyOver (dvdz a)). Proof. apply: (iffP idP) => [/map_poly_divzK | [q ->]]. by exists (map_poly (divz^~ a) p). by apply/polyOverP=> i; rewrite coefZ dvdz_mulr. Qed. Definition zprimitive p := map_poly (divz^~ (zcontents p)) p. Lemma zpolyEprim p : p = zcontents p *: zprimitive p. Proof. by rewrite map_poly_divzK // -dvdz_contents. Qed. Lemma zprimitive0 : zprimitive 0 = 0. Proof. by apply/polyP=> i; rewrite coef0 coef_map_id0 ?div0z // zcontents0 divz0. Qed. Lemma zprimitive_eq0 p : (zprimitive p == 0) = (p == 0). Proof. apply/idP/idP=> /eqP p0; first by rewrite [p]zpolyEprim p0 scaler0. by rewrite p0 zprimitive0. Qed. Lemma size_zprimitive p : size (zprimitive p) = size p. Proof. have [-> | ] := eqVneq p 0; first by rewrite zprimitive0. by rewrite {1 3}[p]zpolyEprim scale_poly_eq0 => /norP[/size_scale-> _]. Qed. Lemma sgz_lead_primitive p : sgz (lead_coef (zprimitive p)) = (p != 0). Proof. have [-> | nz_p] := eqVneq; first by rewrite zprimitive0 lead_coef0. apply: (@mulfI _ (sgz (zcontents p))); first by rewrite sgz_eq0 zcontents_eq0. by rewrite -sgzM mulr1 -lead_coefZ -zpolyEprim sgz_contents. Qed. Lemma zcontents_primitive p : zcontents (zprimitive p) = (p != 0). Proof. have [-> | nz_p] := eqVneq; first by rewrite zprimitive0 zcontents0. apply: (@mulfI _ (zcontents p)); first by rewrite zcontents_eq0. by rewrite mulr1 -zcontentsZ -zpolyEprim. Qed. Lemma zprimitive_id p : zprimitive (zprimitive p) = zprimitive p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !zprimitive0. by rewrite {2}[zprimitive p]zpolyEprim zcontents_primitive nz_p scale1r. Qed. Lemma zprimitive_monic p : p \in monic -> zprimitive p = p. Proof. by move=> mon_p; rewrite {2}[p]zpolyEprim zcontents_monic ?scale1r. Qed. Lemma zprimitiveZ a p : a != 0 -> zprimitive (a *: p) = zprimitive p. Proof. have [-> | nz_p nz_a] := eqVneq p 0; first by rewrite scaler0. apply: (@mulfI _ (a * zcontents p)%:P). by rewrite polyC_eq0 mulf_neq0 ?zcontents_eq0. by rewrite -{1}zcontentsZ !mul_polyC -zpolyEprim -scalerA -zpolyEprim. Qed. Lemma zprimitive_min p a q : p != 0 -> p = a *: q -> {b | sgz b = sgz (lead_coef q) & q = b *: zprimitive p}. Proof. move=> nz_p Dp; have /dvdzP/sig_eqW[b Db]: (a %| zcontents p)%Z. by rewrite dvdz_contents; apply/polyOver_dvdzP; exists q. suffices ->: q = b *: zprimitive p. by rewrite lead_coefZ sgzM sgz_lead_primitive nz_p mulr1; exists b. apply: (@mulfI _ a%:P). by apply: contraNneq nz_p; rewrite Dp -mul_polyC => ->; rewrite mul0r. by rewrite !mul_polyC -Dp scalerA mulrC -Db -zpolyEprim. Qed. Lemma zprimitive_irr p a q : p != 0 -> zprimitive p = a *: q -> a = sgz (lead_coef q). Proof. move=> nz_p Dp; have: p = (a * zcontents p) *: q. by rewrite mulrC -scalerA -Dp -zpolyEprim. case/zprimitive_min=> // b <- /eqP. rewrite Dp -{1}[q]scale1r scalerA -subr_eq0 -scalerBl scale_poly_eq0 subr_eq0. have{Dp} /negPf->: q != 0. by apply: contraNneq nz_p; rewrite -zprimitive_eq0 Dp => ->; rewrite scaler0. by case: b a => [[|[|b]] | [|b]] [[|[|a]] | [|a]] //; rewrite mulr0. Qed. Lemma zcontentsM p q : zcontents (p * q) = zcontents p * zcontents q. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, zcontents0). have [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, zcontents0). rewrite -[zcontents q]mulr1 {1}[p]zpolyEprim {1}[q]zpolyEprim. rewrite -scalerAl -scalerAr !zcontentsZ; congr (_ * (_ * _)). rewrite [zcontents _]intEsg sgz_contents lead_coefM sgzM !sgz_lead_primitive. apply/eqP; rewrite nz_p nz_q !mul1r [_ == _]eqn_leq absz_gt0 zcontents_eq0. rewrite mulf_neq0 ?zprimitive_eq0 // andbT leqNgt. apply/negP=> /pdivP[r r_pr r_dv_d]; pose to_r : int -> 'F_r := intr. have nz_prim_r q1: q1 != 0 -> map_poly to_r (zprimitive q1) != 0. move=> nz_q1; apply: contraTneq (prime_gt1 r_pr) => r_dv_q1. rewrite -leqNgt dvdn_leq // -(dvdzE r true) -nz_q1 -zcontents_primitive. rewrite dvdz_contents; apply/polyOverP=> i /=; rewrite dvdzE /=. have /polyP/(_ i)/eqP := r_dv_q1; rewrite coef_map coef0 /=. rewrite {1}[_`_i]intEsign rmorphM /= rmorph_sign /= mulf_eq0 signr_eq0 /=. by rewrite -val_eqE /= val_Fp_nat. suffices{nz_prim_r} /idPn[]: map_poly to_r (zprimitive p * zprimitive q) == 0. by rewrite rmorphM mulf_neq0 ?nz_prim_r. rewrite [_ * _]zpolyEprim [zcontents _]intEsign mulrC -scalerA map_polyZ /=. by rewrite scale_poly_eq0 -val_eqE /= val_Fp_nat ?(eqnP r_dv_d). Qed. Lemma zprimitiveM p q : zprimitive (p * q) = zprimitive p * zprimitive q. Proof. have [pq_0|] := eqVneq (p * q) 0. rewrite pq_0; move/eqP: pq_0; rewrite mulf_eq0. by case/pred2P=> ->; rewrite !zprimitive0 (mul0r, mulr0). rewrite -zcontents_eq0 -polyC_eq0 => /mulfI; apply; rewrite !mul_polyC. by rewrite -zpolyEprim zcontentsM -scalerA scalerAr scalerAl -!zpolyEprim. Qed. Lemma dvdpP_int p q : p %| q -> {r | q = zprimitive p * r}. Proof. case/Pdiv.Idomain.dvdpP/sig2_eqW=> [[c r] /= nz_c Dpr]. exists (zcontents q *: zprimitive r); rewrite -scalerAr. by rewrite -zprimitiveM mulrC -Dpr zprimitiveZ // -zpolyEprim. Qed. End ZpolyScale. (* Integral spans. *) Lemma int_Smith_normal_form m n (M : 'M[int]_(m, n)) : {L : 'M[int]_m & L \in unitmx & {R : 'M[int]_n & R \in unitmx & {d : seq int | sorted dvdz d & M = L *m (\matrix_(i, j) (d`_i *+ (i == j :> nat))) *m R}}}. Proof. move: {2}_.+1 (ltnSn (m + n)) => mn. elim: mn => // mn IHmn in m n M *; rewrite ltnS => le_mn. have [[i j] nzMij | no_ij] := pickP (fun k => M k.1 k.2 != 0); last first. do 2![exists 1%:M; first exact: unitmx1]; exists nil => //=. apply/matrixP=> i j; apply/eqP; rewrite mulmx1 mul1mx mxE nth_nil mul0rn. exact: negbFE (no_ij (i, j)). do [case: m i => [[]//|m] i; case: n j => [[]//|n] j /=] in M nzMij le_mn *. wlog Dj: j M nzMij / j = 0; last rewrite {j}Dj in nzMij. case/(_ 0 (xcol j 0 M)); rewrite ?mxE ?tpermR // => L uL [R uR [d dvD dM]]. exists L => //; exists (xcol j 0 R); last exists d => //=. by rewrite xcolE unitmx_mul uR unitmx_perm. by rewrite xcolE !mulmxA -dM xcolE -mulmxA -perm_mxM tperm2 perm_mx1 mulmx1. move Da: (M i 0) nzMij => a nz_a. have [A leA] := ubnP `|a|; elim: A => // A IHa in a leA m n M i Da nz_a le_mn *. wlog [j a'Mij]: m n M i Da le_mn / {j | ~~ (a %| M i j)%Z}; last first. have nz_j: j != 0 by apply: contraNneq a'Mij => ->; rewrite Da. case: n => [[[]//]|n] in j le_mn nz_j M a'Mij Da *. wlog{nz_j} Dj: j M a'Mij Da / j = 1; last rewrite {j}Dj in a'Mij. case/(_ 1 (xcol j 1 M)); rewrite ?mxE ?tpermR ?tpermD //. move=> L uL [R uR [d dvD dM]]; exists L => //. exists (xcol j 1 R); first by rewrite xcolE unitmx_mul uR unitmx_perm. exists d; rewrite //= xcolE !mulmxA -dM xcolE -mulmxA -perm_mxM tperm2. by rewrite perm_mx1 mulmx1. have [u [v]] := Bezoutz a (M i 1); set b := gcdz _ _ => Db. have{leA} ltA: (`|b| < A)%N. rewrite -ltnS (leq_trans _ leA) // ltnS ltn_neqAle andbC. rewrite dvdn_leq ?absz_gt0 ? dvdn_gcdl //=. by rewrite (contraNneq _ a'Mij) ?dvdzE // => <-; apply: dvdn_gcdr. pose t2 := [fun j : 'I_2 => [tuple _; _]`_j : int]; pose a1 := M i 1. pose Uul := \matrix_(k, j) t2 (t2 u (- (a1 %/ b)%Z) j) (t2 v (a %/ b)%Z j) k. pose U : 'M_(2 + n) := block_mx Uul 0 0 1%:M; pose M1 := M *m U. have{nz_a} nz_b: b != 0 by rewrite gcdz_eq0 (negPf nz_a). have uU: U \in unitmx. rewrite unitmxE det_ublock det1 (expand_det_col _ 0) big_ord_recl big_ord1. do 2!rewrite /cofactor [row' _ _]mx11_scalar !mxE det_scalar1 /=. rewrite mulr1 mul1r mulN1r opprK -[_ + _](mulzK _ nz_b) mulrDl. by rewrite -!mulrA !divzK ?dvdz_gcdl ?dvdz_gcdr // Db divzz nz_b unitr1. have{} Db: M1 i 0 = b. rewrite /M1 -(lshift0 n 1) [U]block_mxEh mul_mx_row row_mxEl. rewrite -[M](@hsubmxK _ _ 2) (@mul_row_col _ _ 2) mulmx0 addr0 !mxE /=. rewrite big_ord_recl big_ord1 !mxE /= [lshift _ _]((_ =P 0) _) // Da. by rewrite [lshift _ _]((_ =P 1) _) // mulrC -(mulrC v). have [L uL [R uR [d dvD dM1]]] := IHa b ltA _ _ M1 i Db nz_b le_mn. exists L => //; exists (R *m invmx U); last exists d => //. by rewrite unitmx_mul uR unitmx_inv. by rewrite mulmxA -dM1 mulmxK. move=> {A leA}IHa; wlog Di: i M Da / i = 0; last rewrite {i}Di in Da. case/(_ 0 (xrow i 0 M)); rewrite ?mxE ?tpermR // => L uL [R uR [d dvD dM]]. exists (xrow i 0 L); first by rewrite xrowE unitmx_mul unitmx_perm. exists R => //; exists d; rewrite //= xrowE -!mulmxA (mulmxA L) -dM xrowE. by rewrite mulmxA -perm_mxM tperm2 perm_mx1 mul1mx. without loss /forallP a_dvM0: / [forall j, a %| M 0%R j]%Z. case: (altP forallP) => [_ IH|/forallPn/sigW/IHa IH _]; exact: IH. without loss{Da a_dvM0} Da: M / forall j, M 0 j = a. pose Uur := col' 0 (\row_j (1 - (M 0%R j %/ a)%Z)). pose U : 'M_(1 + n) := block_mx 1 Uur 0 1%:M; pose M1 := M *m U. have uU: U \in unitmx by rewrite unitmxE det_ublock !det1 mulr1. case/(_ (M *m U)) => [j | L uL [R uR [d dvD dM]]]. rewrite -(lshift0 m 0) -[M](@submxK _ 1 _ 1) (@mulmx_block _ 1 m 1). rewrite (@col_mxEu _ 1) !mulmx1 mulmx0 addr0 [ulsubmx _]mx11_scalar. rewrite mul_scalar_mx !mxE !lshift0 Da. case: splitP => [j0 _ | j1 Dj]; rewrite ?ord1 !mxE // lshift0 rshift1. by rewrite mulrBr mulr1 mulrC divzK ?subrK. exists L => //; exists (R * U^-1); first by rewrite unitmx_mul uR unitmx_inv. by exists d; rewrite //= mulmxA -dM mulmxK. without loss{IHa} /forallP/(_ (_, _))/= a_dvM: / [forall k, a %| M k.1 k.2]%Z. case: (altP forallP) => [_|/forallPn/sigW [[i j] /= a'Mij] _]; first exact. have [|||L uL [R uR [d dvD dM]]] := IHa _ _ M^T j; rewrite ?mxE 1?addnC //. by exists i; rewrite mxE. exists R^T; last exists L^T; rewrite ?unitmx_tr //; exists d => //. rewrite -[M]trmxK dM !trmx_mul mulmxA; congr (_ *m _ *m _). by apply/matrixP=> i1 j1 /[!mxE]; case: eqVneq => // ->. without loss{nz_a a_dvM} a1: M a Da / a = 1. pose M1 := map_mx (divz^~ a) M; case/(_ M1 1)=> // [k|L uL [R uR [d dvD dM]]]. by rewrite !mxE Da divzz nz_a. exists L => //; exists R => //; exists [seq a * x | x <- d]. case: d dvD {dM} => //= x d; elim: d x => //= y d IHd x /andP[dv_xy /IHd]. by rewrite [dvdz _ _]dvdz_mul2l ?[_ \in _]dv_xy. have ->: M = a *: M1 by apply/matrixP=> i j; rewrite !mxE mulrC divzK ?a_dvM. rewrite dM scalemxAl scalemxAr; congr (_ *m _ *m _). apply/matrixP=> i j; rewrite !mxE mulrnAr; congr (_ *+ _). have [lt_i_d | le_d_i] := ltnP i (size d); first by rewrite (nth_map 0). by rewrite !nth_default ?size_map ?mulr0. rewrite {a}a1 -[m.+1]/(1 + m)%N -[n.+1]/(1 + n)%N in M Da *. pose Mu := ursubmx M; pose Ml := dlsubmx M. have{} Da: ulsubmx M = 1 by rewrite [_ M]mx11_scalar !mxE !lshift0 Da. pose M1 := - (Ml *m Mu) + drsubmx M. have [|L uL [R uR [d dvD dM1]]] := IHmn m n M1; first by rewrite -addnS ltnW. exists (block_mx 1 0 Ml L). by rewrite unitmxE det_lblock det_scalar1 mul1r. exists (block_mx 1 Mu 0 R). by rewrite unitmxE det_ublock det_scalar1 mul1r. exists (1 :: d); set D1 := \matrix_(i, j) _ in dM1. by rewrite /= path_min_sorted //; apply/allP => g _; apply: dvd1n. rewrite [D in _ *m D *m _](_ : _ = block_mx 1 0 0 D1); last first. by apply/matrixP=> i j; do 3?[rewrite ?mxE ?ord1 //=; case: splitP => ? ->]. rewrite !mulmx_block !(mul0mx, mulmx0, addr0) !mulmx1 add0r mul1mx -Da -dM1. by rewrite addNKr submxK. Qed.
nomatch.lean
set_option autoImplicit true example : False → α := nofun example : False → α := by nofun example : ¬ False := nofun example : ¬ False := by nofun example : ¬ ¬ 0 = 0 := nofun example (h : False) : α := nomatch h example (h : Nat → False) : Nat := nomatch h 1 def ComplicatedEmpty : Bool → Type | false => Empty | true => PEmpty example (h : ComplicatedEmpty b) : α := nomatch b, h example (h : Nat → ComplicatedEmpty b) : α := nomatch b, h 1
Support.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.Algebra.Group.Basic import Mathlib.Algebra.Notation.Support /-! # Support of a function In this file we prove basic properties of `Function.support f = {x | f x ≠ 0}`, and similarly for `Function.mulSupport f = {x | f x ≠ 1}`. -/ assert_not_exists CompleteLattice MonoidWithZero open Set variable {α M G : Type*} namespace Function @[to_additive] theorem mulSupport_mul [MulOneClass M] (f g : α → M) : (mulSupport fun x ↦ f x * g x) ⊆ mulSupport f ∪ mulSupport g := mulSupport_binop_subset (· * ·) (one_mul _) f g @[to_additive] theorem mulSupport_pow [Monoid M] (f : α → M) (n : ℕ) : (mulSupport fun x => f x ^ n) ⊆ mulSupport f := by induction n with | zero => simp [pow_zero] | succ n hfn => simpa only [pow_succ'] using (mulSupport_mul f _).trans (union_subset Subset.rfl hfn) section DivisionMonoid variable [DivisionMonoid G] (f g : α → G) @[to_additive (attr := simp)] theorem mulSupport_fun_inv : (mulSupport fun x => (f x)⁻¹) = mulSupport f := ext fun _ => inv_ne_one @[to_additive (attr := simp)] theorem mulSupport_inv : mulSupport f⁻¹ = mulSupport f := mulSupport_fun_inv f @[deprecated (since := "2025-07-31")] alias support_neg' := support_neg @[deprecated (since := "2025-07-31")] alias mulSupport_inv' := mulSupport_inv @[to_additive] theorem mulSupport_mul_inv : (mulSupport fun x => f x * (g x)⁻¹) ⊆ mulSupport f ∪ mulSupport g := mulSupport_binop_subset (fun a b => a * b⁻¹) (by simp) f g @[to_additive] theorem mulSupport_div : (mulSupport fun x => f x / g x) ⊆ mulSupport f ∪ mulSupport g := mulSupport_binop_subset (· / ·) one_div_one f g end DivisionMonoid end Function
DualNumber.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.Algebra.DualNumber import Mathlib.RingTheory.LocalRing.MaximalIdeal.Basic import Mathlib.RingTheory.PrincipalIdealDomain import Mathlib.RingTheory.Nilpotent.Defs /-! # Algebraic properties of dual numbers ## Main results * `DualNumber.instLocalRing`: The dual numbers over a field `K` form a local ring. * `DualNumber.instPrincipalIdealRing`: The dual numbers over a field `K` form a principal ideal ring. -/ namespace TrivSqZeroExt variable {R M : Type*} section Semiring variable [Semiring R] [AddCommMonoid M] [Module R M] [Module Rᵐᵒᵖ M] [SMulCommClass R Rᵐᵒᵖ M] lemma isNilpotent_iff_isNilpotent_fst {x : TrivSqZeroExt R M} : IsNilpotent x ↔ IsNilpotent x.fst := by constructor <;> rintro ⟨n, hn⟩ · refine ⟨n, ?_⟩ rw [← fst_pow, hn, fst_zero] · refine ⟨n * 2, ?_⟩ rw [pow_mul] ext · rw [fst_pow, fst_pow, hn, zero_pow two_ne_zero, fst_zero] · rw [pow_two, snd_mul, fst_pow, hn, MulOpposite.op_zero, zero_smul, zero_smul, zero_add, snd_zero] @[simp] lemma isNilpotent_inl_iff (r : R) : IsNilpotent (.inl r : TrivSqZeroExt R M) ↔ IsNilpotent r := by rw [isNilpotent_iff_isNilpotent_fst, fst_inl] @[simp] lemma isNilpotent_inr (x : M) : IsNilpotent (.inr x : TrivSqZeroExt R M) := by refine ⟨2, by simp [pow_two]⟩ end Semiring lemma isUnit_or_isNilpotent_of_isMaximal_isNilpotent [CommSemiring R] [AddCommGroup M] [Module R M] [Module Rᵐᵒᵖ M] [IsCentralScalar R M] (h : ∀ I : Ideal R, I.IsMaximal → IsNilpotent I) (a : TrivSqZeroExt R M) : IsUnit a ∨ IsNilpotent a := by rw [isUnit_iff_isUnit_fst, isNilpotent_iff_isNilpotent_fst] refine (em _).imp_right fun ha ↦ ?_ obtain ⟨I, hI, haI⟩ := exists_max_ideal_of_mem_nonunits (mem_nonunits_iff.mpr ha) refine (h _ hI).imp fun n hn ↦ ?_ exact hn.le (Ideal.pow_mem_pow haI _) lemma isUnit_or_isNilpotent [DivisionSemiring R] [AddCommGroup M] [Module R M] [Module Rᵐᵒᵖ M] [SMulCommClass R Rᵐᵒᵖ M] (a : TrivSqZeroExt R M) : IsUnit a ∨ IsNilpotent a := by simp [isUnit_iff_isUnit_fst, isNilpotent_iff_isNilpotent_fst, em'] end TrivSqZeroExt namespace DualNumber variable {R : Type*} lemma fst_eq_zero_iff_eps_dvd [Semiring R] {x : R[ε]} : x.fst = 0 ↔ ε ∣ x := by simp_rw [dvd_def, TrivSqZeroExt.ext_iff, TrivSqZeroExt.fst_mul, TrivSqZeroExt.snd_mul, fst_eps, snd_eps, zero_mul, zero_smul, zero_add, MulOpposite.smul_eq_mul_unop, MulOpposite.unop_op, one_mul, exists_and_left, iff_self_and] intro exact ⟨.inl x.snd, rfl⟩ lemma isNilpotent_eps [Semiring R] : IsNilpotent (ε : R[ε]) := TrivSqZeroExt.isNilpotent_inr 1 open TrivSqZeroExt lemma isNilpotent_iff_eps_dvd [DivisionSemiring R] {x : R[ε]} : IsNilpotent x ↔ ε ∣ x := by simp only [isNilpotent_iff_isNilpotent_fst, isNilpotent_iff_eq_zero, fst_eq_zero_iff_eps_dvd] section Field variable {K : Type*} instance [DivisionRing K] : IsLocalRing K[ε] where isUnit_or_isUnit_of_add_one {a b} h := by rw [add_comm, ← eq_sub_iff_add_eq] at h rcases eq_or_ne (fst a) 0 with ha|ha <;> simp [isUnit_iff_isUnit_fst, h, ha] lemma ideal_trichotomy [DivisionRing K] (I : Ideal K[ε]) : I = ⊥ ∨ I = .span {ε} ∨ I = ⊤ := by refine (eq_or_ne I ⊥).imp_right fun hb ↦ ?_ refine (eq_or_ne I ⊤).symm.imp_left fun ht ↦ ?_ have hd : ∀ x ∈ I, ε ∣ x := by intro x hxI rcases isUnit_or_isNilpotent x with hx|hx · exact absurd (Ideal.eq_top_of_isUnit_mem _ hxI hx) ht · rwa [← isNilpotent_iff_eps_dvd] have hd' : ∀ x ∈ I, x ≠ 0 → ∃ r, ε = r * x := by intro x hxI hx0 obtain ⟨r, rfl⟩ := hd _ hxI have : ε * r = (fst r) • ε := by ext <;> simp rw [this] at hxI hx0 ⊢ have hr : fst r ≠ 0 := by contrapose! hx0 simp [hx0] refine ⟨r⁻¹, ?_⟩ simp [TrivSqZeroExt.ext_iff, inv_mul_cancel₀ hr] refine le_antisymm ?_ ?_ <;> intro x <;> simp_rw [Ideal.mem_span_singleton', (commute_eps_right _).eq, eq_comm, ← dvd_def] · intro hx simp_rw [hd _ hx] · intro hx obtain ⟨p, rfl⟩ := hx obtain ⟨y, hyI, hy0⟩ := Submodule.exists_mem_ne_zero_of_ne_bot hb obtain ⟨r, hr⟩ := hd' _ hyI hy0 rw [(commute_eps_left _).eq, hr, ← mul_assoc] exact Ideal.mul_mem_left _ _ hyI lemma isMaximal_span_singleton_eps [DivisionRing K] : (Ideal.span {ε} : Ideal K[ε]).IsMaximal := by refine ⟨?_, fun I hI ↦ ?_⟩ · simp [ne_eq, Ideal.eq_top_iff_one, Ideal.mem_span_singleton', TrivSqZeroExt.ext_iff] · rcases ideal_trichotomy I with rfl | rfl | rfl <;> first | simp at hI | simp lemma maximalIdeal_eq_span_singleton_eps [Field K] : IsLocalRing.maximalIdeal K[ε] = Ideal.span {ε} := (IsLocalRing.eq_maximalIdeal isMaximal_span_singleton_eps).symm instance [DivisionRing K] : IsPrincipalIdealRing K[ε] where principal I := by rcases ideal_trichotomy I with rfl | rfl | rfl · exact bot_isPrincipal · exact ⟨_, rfl⟩ · exact top_isPrincipal lemma exists_mul_left_or_mul_right [DivisionRing K] (a b : K[ε]) : ∃ c, a * c = b ∨ b * c = a := by rcases isUnit_or_isNilpotent a with ha|ha · lift a to K[ε]ˣ using ha exact ⟨a⁻¹ * b, by simp⟩ rcases isUnit_or_isNilpotent b with hb|hb · lift b to K[ε]ˣ using hb exact ⟨b⁻¹ * a, by simp⟩ rw [isNilpotent_iff_eps_dvd] at ha hb obtain ⟨x, rfl⟩ := ha obtain ⟨y, rfl⟩ := hb suffices ∃ c, fst x * fst c = fst y ∨ fst y * fst c = fst x by simpa [TrivSqZeroExt.ext_iff] using this rcases eq_or_ne (fst x) 0 with hx|hx · refine ⟨ε, Or.inr ?_⟩ simp [hx] refine ⟨inl ((fst x)⁻¹ * fst y), ?_⟩ simp [← mul_assoc, mul_inv_cancel₀ hx] end Field end DualNumber
Part.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.Data.Part import Mathlib.Order.Hom.Basic import Mathlib.Tactic.Common /-! # Monotonicity of monadic operations on `Part` -/ open Part variable {α β γ : Type*} [Preorder α] section bind variable {f : α → Part β} {g : α → β → Part γ} lemma Monotone.partBind (hf : Monotone f) (hg : Monotone g) : Monotone fun x ↦ (f x).bind (g x) := by rintro x y h a simp only [and_imp, Part.mem_bind_iff, exists_imp] exact fun b hb ha ↦ ⟨b, hf h _ hb, hg h _ _ ha⟩ lemma Antitone.partBind (hf : Antitone f) (hg : Antitone g) : Antitone fun x ↦ (f x).bind (g x) := by rintro x y h a simp only [and_imp, Part.mem_bind_iff, exists_imp] exact fun b hb ha ↦ ⟨b, hf h _ hb, hg h _ _ ha⟩ end bind section map variable {f : β → γ} {g : α → Part β} lemma Monotone.partMap (hg : Monotone g) : Monotone fun x ↦ (g x).map f := by simpa only [← bind_some_eq_map] using hg.partBind monotone_const lemma Antitone.partMap (hg : Antitone g) : Antitone fun x ↦ (g x).map f := by simpa only [← bind_some_eq_map] using hg.partBind antitone_const end map section seq variable {β γ : Type _} {f : α → Part (β → γ)} {g : α → Part β} lemma Monotone.partSeq (hf : Monotone f) (hg : Monotone g) : Monotone fun x ↦ f x <*> g x := by simpa only [seq_eq_bind_map] using hf.partBind <| Monotone.of_apply₂ fun _ ↦ hg.partMap lemma Antitone.partSeq (hf : Antitone f) (hg : Antitone g) : Antitone fun x ↦ f x <*> g x := by simpa only [seq_eq_bind_map] using hf.partBind <| Antitone.of_apply₂ fun _ ↦ hg.partMap end seq namespace OrderHom /-- `Part.bind` as a monotone function -/ @[simps] def partBind (f : α →o Part β) (g : α →o β → Part γ) : α →o Part γ where toFun x := (f x).bind (g x) monotone' := f.2.partBind g.2 end OrderHom
EpiWithInjectiveKernel.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.ShortComplex.ShortExact import Mathlib.CategoryTheory.MorphismProperty.Composition /-! # Epimorphisms with an injective kernel In this file, we define the class of morphisms `epiWithInjectiveKernel` in an abelian category. We show that this property of morphisms is multiplicative. This shall be used in the file `Mathlib/Algebra/Homology/Factorizations/Basic.lean` in order to define morphisms of cochain complexes which satisfy this property degreewise. -/ namespace CategoryTheory open Category Limits ZeroObject Preadditive variable {C : Type*} [Category C] [Abelian C] namespace Abelian /-- The class of morphisms in an abelian category that are epimorphisms and have an injective kernel. -/ def epiWithInjectiveKernel : MorphismProperty C := fun _ _ f => Epi f ∧ Injective (kernel f) /-- A morphism `g : X ⟶ Y` is epi with an injective kernel iff there exists a morphism `f : I ⟶ X` with `I` injective such that `f ≫ g = 0` and the short complex `I ⟶ X ⟶ Y` has a splitting. -/ lemma epiWithInjectiveKernel_iff {X Y : C} (g : X ⟶ Y) : epiWithInjectiveKernel g ↔ ∃ (I : C) (_ : Injective I) (f : I ⟶ X) (w : f ≫ g = 0), Nonempty (ShortComplex.mk f g w).Splitting := by constructor · rintro ⟨_, _⟩ let S := ShortComplex.mk (kernel.ι g) g (by simp) exact ⟨_, inferInstance, _, S.zero, ⟨ShortComplex.Splitting.ofExactOfRetraction S (S.exact_of_f_is_kernel (kernelIsKernel g)) (Injective.factorThru (𝟙 _) (kernel.ι g)) (by simp [S]) inferInstance⟩⟩ · rintro ⟨I, _, f, w, ⟨σ⟩⟩ have : IsSplitEpi g := ⟨σ.s, σ.s_g⟩ let e : I ≅ kernel g := IsLimit.conePointUniqueUpToIso σ.shortExact.fIsKernel (limit.isLimit _) exact ⟨inferInstance, Injective.of_iso e inferInstance⟩ lemma epiWithInjectiveKernel_of_iso {X Y : C} (f : X ⟶ Y) [IsIso f] : epiWithInjectiveKernel f := by rw [epiWithInjectiveKernel_iff] exact ⟨0, inferInstance, 0, by simp, ⟨ShortComplex.Splitting.ofIsZeroOfIsIso _ (isZero_zero C) (by assumption)⟩⟩ instance : (epiWithInjectiveKernel : MorphismProperty C).IsMultiplicative where id_mem _ := epiWithInjectiveKernel_of_iso _ comp_mem {X Y Z} g₁ g₂ hg₁ hg₂ := by rw [epiWithInjectiveKernel_iff] at hg₁ hg₂ ⊢ obtain ⟨I₁, _, f₁, w₁, ⟨σ₁⟩⟩ := hg₁ obtain ⟨I₂, _, f₂, w₂, ⟨σ₂⟩⟩ := hg₂ refine ⟨I₁ ⊞ I₂, inferInstance, biprod.fst ≫ f₁ + biprod.snd ≫ f₂ ≫ σ₁.s, ?_, ⟨?_⟩⟩ · ext · simp [reassoc_of% w₁] · simp [reassoc_of% σ₁.s_g, w₂] · exact { r := σ₁.r ≫ biprod.inl + g₁ ≫ σ₂.r ≫ biprod.inr s := σ₂.s ≫ σ₁.s f_r := by ext · simp [σ₁.f_r] · simp [reassoc_of% w₁] · simp · simp [reassoc_of% σ₁.s_g, σ₂.f_r] s_g := by simp [reassoc_of% σ₁.s_g, σ₂.s_g] id := by dsimp have h := g₁ ≫= σ₂.id =≫ σ₁.s simp only [add_comp, assoc, comp_add, id_comp] at h rw [← σ₁.id, ← h] simp only [comp_add, add_comp, assoc, BinaryBicone.inl_fst_assoc, BinaryBicone.inr_fst_assoc, zero_comp, comp_zero, add_zero, BinaryBicone.inl_snd_assoc, BinaryBicone.inr_snd_assoc, zero_add] abel } end Abelian end CategoryTheory
PosLogEqCircleAverage.lean
/- Copyright (c) 2025 Stefan Kebekus. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stefan Kebekus -/ import Mathlib.Analysis.SpecialFunctions.Integrals.Basic import Mathlib.Analysis.SpecialFunctions.Integrals.LogTrigonometric import Mathlib.MeasureTheory.Integral.CircleAverage /-! # Representation of `log⁺` as a Circle Average If `a` is any complex number of norm one, then `log ‖· - a‖` is circle integrable over every circle in the complex plane, and the circle average `circleAverage (log ‖· - a‖) 0 1` vanishes. - Integrability is recalled in `circleIntegrability_log_norm_id_sub_const`, as a consequence of the general fact that functions of the form `log ‖meromorphic‖` are circle integrable. - The value of the integral is computed in `circleAverage_log_norm_id_sub_const₁`. TODO: As soon as the mean value theorem for harmonic functions becomes available, extend this result to arbitrary complex numbers `a`, showing that the circle average equals the positive part of the logarithm, `circleAverage (log ‖· - a‖) 0 1 = = log⁺ ‖a‖`. This result, in turn, is a major ingredient in the proof of Jensen's formula in complex analysis. -/ open Filter Interval intervalIntegral MeasureTheory Real variable {a : ℂ} /-! ## Circle Integrability -/ /-- If `a` is any complex number, the function `(log ‖· - a‖)` is circle integrable over every circle. -/ lemma circleIntegrable_log_norm_sub_const {c : ℂ} (r : ℝ) : CircleIntegrable (log ‖· - a‖) c r := circleIntegrable_log_norm_meromorphicOn (fun z hz ↦ by fun_prop) /-! ## Computing `circleAverage (log ‖· - a‖) 0 1` in case where `‖a‖ = 1`. -/ -- Integral computation used in `circleAverage_log_norm_id_sub_const₁` private lemma circleAverage_log_norm_sub_const₁_integral : ∫ x in 0..(2 * π), log (4 * sin (x / 2) ^ 2) / 2 = 0 := by calc ∫ x in 0..(2 * π), log (4 * sin (x / 2) ^ 2) / 2 _ = ∫ (x : ℝ) in 0..π, log (4 * sin x ^ 2) := by have {x : ℝ} : x / 2 = 2⁻¹ * x := by ring rw [intervalIntegral.integral_div, this, inv_mul_integral_comp_div (f := fun x ↦ log (4 * sin x ^ 2))] simp _ = ∫ (x : ℝ) in 0..π, log 4 + 2 * log (sin x) := by apply integral_congr_codiscreteWithin apply codiscreteWithin.mono (by tauto : Ι 0 π ⊆ Set.univ) have : AnalyticOnNhd ℝ (4 * sin · ^ 2) Set.univ := fun _ _ ↦ by fun_prop have := this.preimage_zero_mem_codiscrete (x := π / 2) simp only [sin_pi_div_two, one_pow, mul_one, ne_eq, OfNat.ofNat_ne_zero, not_false_eq_true, Set.preimage_compl, forall_const] at this filter_upwards [this] with a ha simp only [Set.mem_compl_iff, Set.mem_preimage, Set.mem_singleton_iff, mul_eq_zero, OfNat.ofNat_ne_zero, ne_eq, not_false_eq_true, pow_eq_zero_iff, false_or] at ha rw [log_mul (by norm_num) (by simp_all), log_pow, Nat.cast_ofNat] _ = (∫ (x : ℝ) in 0..π, log 4) + 2 * ∫ (x : ℝ) in 0..π, log (sin x) := by rw [integral_add _root_.intervalIntegrable_const (by apply intervalIntegrable_log_sin.const_mul 2), intervalIntegral.integral_const_mul] _ = 0 := by simp only [intervalIntegral.integral_const, sub_zero, smul_eq_mul, integral_log_sin_zero_pi, (by norm_num : (4 : ℝ) = 2 * 2), log_mul two_ne_zero two_ne_zero] ring /-- If `a : ℂ` has norm one, then the circle average `circleAverage (log ‖· - a‖) 0 1` vanishes. -/ @[simp] theorem circleAverage_log_norm_sub_const₁ (h : ‖a‖ = 1) : circleAverage (log ‖· - a‖) 0 1 = 0 := by -- Observing that the problem is rotation invariant, we rotate by an angle of `ζ = - arg a` and -- reduce the problem to the case where `a = 1`. The integral can then be evaluated by a direct -- computation. simp only [circleAverage, mul_inv_rev, smul_eq_mul, mul_eq_zero, inv_eq_zero, OfNat.ofNat_ne_zero, or_false] right obtain ⟨ζ, hζ⟩ : ∃ ζ, a⁻¹ = circleMap 0 1 ζ := by simp [Set.exists_range_iff.1, h] calc ∫ x in 0..(2 * π), log ‖circleMap 0 1 x - a‖ _ = ∫ x in 0..(2 * π), log ‖(circleMap 0 1 ζ) * (circleMap 0 1 x - a)‖ := by simp _ = ∫ x in 0..(2 * π), log ‖circleMap 0 1 (ζ + x) - (circleMap 0 1 ζ) * a‖ := by simp [mul_sub, circleMap, add_mul, Complex.exp_add] _ = ∫ x in 0..(2 * π), log ‖circleMap 0 1 (ζ + x) - 1‖ := by simp [← hζ, inv_mul_cancel₀ (by aesop : a ≠ 0)] _ = ∫ x in 0..(2 * π), log ‖circleMap 0 1 x - 1‖ := by have : Function.Periodic (log ‖circleMap 0 1 · - 1‖) (2 * π) := fun x ↦ by simp [periodic_circleMap 0 1 x] have := this.intervalIntegral_add_eq (t := 0) (s := ζ) simp_all [integral_comp_add_left (log ‖circleMap 0 1 · - 1‖)] _ = ∫ x in 0..(2 * π), log (4 * sin (x / 2) ^ 2) / 2 := by apply integral_congr intro x hx simp only [] rw [Complex.norm_def, log_sqrt (circleMap 0 1 x - 1).normSq_nonneg] congr calc Complex.normSq (circleMap 0 1 x - 1) _ = (cos x - 1) * (cos x - 1) + sin x * sin x := by simp [circleMap, Complex.normSq_apply] _ = sin x ^ 2 + cos x ^ 2 + 1 - 2 * cos x := by ring _ = 2 - 2 * cos x := by rw [sin_sq_add_cos_sq] norm_num _ = 2 - 2 * cos (2 * (x / 2)) := by rw [← mul_div_assoc] norm_num _ = 4 - 4 * cos (x / 2) ^ 2 := by rw [cos_two_mul] ring _ = 4 * sin (x / 2) ^ 2 := by nth_rw 1 [← mul_one 4, ← sin_sq_add_cos_sq (x / 2)] ring _ = 0 := circleAverage_log_norm_sub_const₁_integral
Isotypic.lean
/- Copyright (c) 2025 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import Mathlib.Algebra.Algebra.Pi import Mathlib.Order.CompleteSublattice import Mathlib.RingTheory.SimpleModule.Basic /-! # Isotypic modules and isotypic components ## Main definitions * `IsIsotypicOfType R M S` means that all simple submodules of the `R`-module `M` are isomorphic to `S`. Such a module `M` is isomorphic to a finsupp over `S`, see `IsIsotypicOfType.linearEquiv_finsupp`. * `IsIsotypic R M` means that all simple submodules of the `R`-module `M` are isomorphic to each other. * `isotypicComponent R M S` is the sum of all submodules of `M` isomorphic to `S`. * `isotypicComponents R M` is the set of all nontrivial isotypic components of `M` (where `S` is taken to be simple submodules). * `Submodule.IsFullyInvariant N` means that the submodule `N` of an `R`-module `M` is mapped into itself by all endomorphisms of `M`. The `fullyInvariantSubmodule`s of `M` form a complete lattice, which is atomic if `M` is semisimple, in which case the atoms are the isotypic components of `M`. A fully invariant submodule of a semiring as a module over itself is simply a two-sided ideal, see `isFullyInvariant_iff_isTwoSided`. * `iSupIndep.ringEquiv`, `iSupIndep.algEquiv`: if `M` is the direct sum of fully invariant submodules `Nᵢ`, then `End R M` is isomorphic to `Πᵢ End R Nᵢ`. This can be applied to the isotypic components of a semisimple module `M`, yielding `IsSemisimpleModule.endAlgEquiv`. ## Keywords isotypic component, fully invariant submodule -/ universe u variable (R₀ R : Type*) (M : Type u) (N S : Type*) [CommSemiring R₀] [Ring R] [Algebra R₀ R] [AddCommGroup M] [AddCommGroup N] [AddCommGroup S] [Module R M] [Module R N] [Module R S] /-- An `R`-module `M` is isotypic of type `S` if all simple submodules of `M` are isomorphic to `S`. If `M` is semisimple, it is equivalent to requiring that all simple quotients of `M` are isomorphic to `S`. -/ def IsIsotypicOfType : Prop := ∀ (m : Submodule R M) [IsSimpleModule R m], Nonempty (m ≃ₗ[R] S) /-- An `R`-module `M` is isotypic if all its simple submodules are isomorphic. -/ def IsIsotypic : Prop := ∀ (m : Submodule R M) [IsSimpleModule R m], IsIsotypicOfType R M m variable {R M S} in theorem IsIsotypicOfType.isIsotypic (h : IsIsotypicOfType R M S) : IsIsotypic R M := fun m _ m' _ ↦ ⟨(h m').some.trans (h m).some.symm⟩ @[nontriviality] theorem IsIsotypicOfType.of_subsingleton [Subsingleton M] : IsIsotypicOfType R M S := fun S ↦ have := IsSimpleModule.nontrivial R S (not_subsingleton _ S.subtype_injective.subsingleton).elim @[nontriviality] theorem IsIsotypic.of_subsingleton [Subsingleton M] : IsIsotypic R M := fun S ↦ (IsIsotypicOfType.of_subsingleton R M S).isIsotypic S theorem IsIsotypicOfType.of_isSimpleModule [IsSimpleModule R M] : IsIsotypicOfType R M M := fun S hS ↦ by rw [isSimpleModule_iff_isAtom, isAtom_iff_eq_top] at hS exact ⟨.trans (.ofEq _ _ hS) Submodule.topEquiv⟩ variable {R M N S} theorem IsIsotypicOfType.of_linearEquiv_type (h : IsIsotypicOfType R M S) (e : S ≃ₗ[R] N) : IsIsotypicOfType R M N := fun m _ ↦ ⟨(h m).some.trans e⟩ theorem IsIsotypicOfType.of_injective (h : IsIsotypicOfType R N S) (f : M →ₗ[R] N) (inj : Function.Injective f) : IsIsotypicOfType R M S := fun m ↦ have em := m.equivMapOfInjective f inj have := IsSimpleModule.congr em.symm ⟨em.trans (h (m.map f)).some⟩ theorem IsIsotypic.of_injective (h : IsIsotypic R N) (f : M →ₗ[R] N) (inj : Function.Injective f) : IsIsotypic R M := fun m _ ↦ have em := (m.equivMapOfInjective f inj).symm have := IsSimpleModule.congr em ((h (m.map f)).of_injective f inj).of_linearEquiv_type em theorem LinearEquiv.isIsotypicOfType_iff (e : M ≃ₗ[R] N) : IsIsotypicOfType R M S ↔ IsIsotypicOfType R N S := ⟨(·.of_injective _ e.symm.injective), (·.of_injective _ e.injective)⟩ theorem LinearEquiv.isIsotypicOfType_iff_type (e : N ≃ₗ[R] S) : IsIsotypicOfType R M N ↔ IsIsotypicOfType R M S := ⟨(·.of_linearEquiv_type e), (·.of_linearEquiv_type e.symm)⟩ theorem LinearEquiv.isIsotypic_iff (e : M ≃ₗ[R] N) : IsIsotypic R M ↔ IsIsotypic R N := ⟨(·.of_injective _ e.symm.injective), (·.of_injective _ e.injective)⟩ theorem isIsotypicOfType_submodule_iff {N : Submodule R M} : IsIsotypicOfType R N S ↔ ∀ m ≤ N, [IsSimpleModule R m] → Nonempty (m ≃ₗ[R] S) := by rw [Subtype.forall', ← (Submodule.MapSubtype.orderIso N).forall_congr_right] have e := Submodule.equivMapOfInjective _ N.subtype_injective simp_rw [Submodule.MapSubtype.orderIso, Equiv.coe_fn_mk, ← (e _).isSimpleModule_iff] exact forall₂_congr fun m _ ↦ ⟨fun ⟨e'⟩ ↦ ⟨(e m).symm.trans e'⟩, fun ⟨e'⟩ ↦ ⟨(e m).trans e'⟩⟩ theorem isIsotypic_submodule_iff {N : Submodule R M} : IsIsotypic R N ↔ ∀ m ≤ N, [IsSimpleModule R m] → IsIsotypicOfType R N m := by rw [Subtype.forall', ← (Submodule.MapSubtype.orderIso N).forall_congr_right] have e := Submodule.equivMapOfInjective _ N.subtype_injective simp_rw [Submodule.MapSubtype.orderIso, Equiv.coe_fn_mk, ← (e _).isSimpleModule_iff, ← (e _).isIsotypicOfType_iff_type, IsIsotypic] section Finsupp variable [IsSemisimpleModule R M] theorem IsIsotypicOfType.linearEquiv_finsupp (h : IsIsotypicOfType R M S) : ∃ ι : Type u, Nonempty (M ≃ₗ[R] ι →₀ S) := by have ⟨s, e, _, hs⟩ := IsSemisimpleModule.exists_linearEquiv_dfinsupp R M classical exact ⟨s, ⟨e.trans (DFinsupp.mapRange.linearEquiv fun m : s ↦ (h m.1).some) |>.trans (finsuppLequivDFinsupp R).symm⟩⟩ theorem IsIsotypic.linearEquiv_finsupp [Nontrivial M] (h : IsIsotypic R M) : ∃ (ι : Type u) (_ : Nonempty ι) (S : Submodule R M), IsSimpleModule R S ∧ Nonempty (M ≃ₗ[R] ι →₀ S) := by have ⟨S, hS⟩ := IsAtomic.exists_atom (Submodule R M) rw [← isSimpleModule_iff_isAtom] at hS have ⟨ι, e⟩ := (h S).linearEquiv_finsupp exact ⟨ι, (isEmpty_or_nonempty ι).resolve_left fun _ ↦ not_subsingleton _ (e.some.subsingleton), S, hS, e⟩ theorem IsIsotypicOfType.linearEquiv_fun [Module.Finite R M] (h : IsIsotypicOfType R M S) : ∃ n : ℕ, Nonempty (M ≃ₗ[R] Fin n → S) := by have ⟨n, S, e, hs⟩ := IsSemisimpleModule.exists_linearEquiv_fin_dfinsupp R M classical exact ⟨n, ⟨e.trans (DFinsupp.mapRange.linearEquiv fun i ↦ (h (S i)).some) |>.trans (finsuppLequivDFinsupp R).symm |>.trans (Finsupp.linearEquivFunOnFinite ..)⟩⟩ theorem IsIsotypic.linearEquiv_fun [Module.Finite R M] [Nontrivial M] (h : IsIsotypic R M) : ∃ (n : ℕ) (_ : NeZero n) (S : Submodule R M), IsSimpleModule R S ∧ Nonempty (M ≃ₗ[R] Fin n → S) := by have ⟨S, hS⟩ := IsAtomic.exists_atom (Submodule R M) rw [← isSimpleModule_iff_isAtom] at hS have ⟨n, e⟩ := (h S).linearEquiv_fun exact ⟨n, neZero_iff.2 <| by rintro rfl; exact not_subsingleton _ (e.some.subsingleton), S, hS, e⟩ theorem IsIsotypic.submodule_linearEquiv_fun {m : Submodule R M} [Module.Finite R m] [Nontrivial m] (h : IsIsotypic R m) : ∃ (n : ℕ) (_ : NeZero n) (S : Submodule R M), S ≤ m ∧ IsSimpleModule R S ∧ Nonempty (m ≃ₗ[R] Fin n → S) := have ⟨n, hn, S, _, ⟨e⟩⟩ := h.linearEquiv_fun let e' := S.equivMapOfInjective _ m.subtype_injective ⟨n, hn, _, m.map_subtype_le S, .congr e'.symm, ⟨e.trans <| .piCongrRight fun _ ↦ e'⟩⟩ end Finsupp variable (R M S) /-- If `S` is a simple `R`-module, the `S`-isotypic component in an `R`-module `M` is the sum of all submodules of `M` isomorphic to `S`. -/ def isotypicComponent : Submodule R M := sSup {m | Nonempty (m ≃ₗ[R] S)} /-- The set of all (nontrivial) isotypic components of a module. -/ def isotypicComponents : Set (Submodule R M) := { m | ∃ S : Submodule R M, IsSimpleModule R S ∧ m = isotypicComponent R M S } variable {R M} theorem Submodule.le_isotypicComponent (m : Submodule R M) : m ≤ isotypicComponent R M m := le_sSup ⟨.refl ..⟩ theorem bot_lt_isotypicComponent (S : Submodule R M) [IsSimpleModule R S] : ⊥ < isotypicComponent R M S := (bot_lt_iff_ne_bot.mpr <| (S.nontrivial_iff_ne_bot).mp <| IsSimpleModule.nontrivial R S).trans_le S.le_isotypicComponent theorem bot_lt_isotypicComponents {m : Submodule R M} (h : m ∈ isotypicComponents R M) : ⊥ < m := by obtain ⟨_, _, rfl⟩ := h; exact bot_lt_isotypicComponent .. instance (c : isotypicComponents R M) : Nontrivial c := Submodule.nontrivial_iff_ne_bot.mpr (bot_lt_isotypicComponents c.2).ne' instance [IsSemisimpleModule R S] : IsSemisimpleModule R (isotypicComponent R M S) := by rw [isotypicComponent, sSup_eq_iSup] refine isSemisimpleModule_biSup_of_isSemisimpleModule_submodule fun m ⟨e⟩ ↦ ?_ have := IsSemisimpleModule.congr e infer_instance instance (c : isotypicComponents R M) : IsSemisimpleModule R c := by obtain ⟨c, S, _, rfl⟩ := c; infer_instance variable {S} in theorem LinearEquiv.isotypicComponent_eq (e : N ≃ₗ[R] S) : isotypicComponent R M N = isotypicComponent R M S := congr_arg sSup <| Set.ext fun _ ↦ Nonempty.congr (·.trans e) (·.trans e.symm) section SimpleSubmodule variable (N : Submodule R M) [IsSimpleModule R N] (s : Set (Submodule R M)) open LinearMap in theorem Submodule.le_linearEquiv_of_sSup_eq_top [IsSemisimpleModule R M] (hs : sSup s = ⊤) : ∃ m ∈ s, ∃ S ≤ m, Nonempty (N ≃ₗ[R] S) := by have := IsSimpleModule.nontrivial R N have ⟨_, compl⟩ := exists_isCompl N have ⟨m, hm, ne⟩ := exists_ne_zero_of_sSup_eq_top (ne_zero_of_surjective (N.linearProjOfIsCompl_surjective compl)) _ hs have ⟨S, ⟨e⟩⟩ := linearEquiv_of_ne_zero ne exact ⟨m, hm, _, m.map_subtype_le S, ⟨e.trans (S.equivMapOfInjective _ m.subtype_injective)⟩⟩ theorem Submodule.linearEquiv_of_sSup_eq_top [h : ∀ m : s, IsSimpleModule R m] (hs : sSup s = ⊤) : ∃ S ∈ s, Nonempty (N ≃ₗ[R] S) := have := isSemisimpleModule_of_isSemisimpleModule_submodule' (fun _ ↦ inferInstance) (sSup_eq_iSup' s ▸ hs) have ⟨m, hm, _S, le, ⟨e⟩⟩ := N.le_linearEquiv_of_sSup_eq_top _ hs have := isSimpleModule_iff_isAtom.mp (IsSimpleModule.congr e.symm) have := ((isSimpleModule_iff_isAtom.mp <| h ⟨m, hm⟩).le_iff_eq this.1).mp le ⟨m, hm, ⟨e.trans (.ofEq _ _ this)⟩⟩ /-- If a simple module is contained in a sum of semisimple modules, it must be isomorphic to a submodule of one of the summands. -/ theorem Submodule.le_linearEquiv_of_le_sSup [hs : ∀ m : s, IsSemisimpleModule R m] (hN : N ≤ sSup s) : ∃ m ∈ s, ∃ S ≤ m, Nonempty (N ≃ₗ[R] S) := by rw [sSup_eq_iSup] at hN have e := LinearEquiv.ofInjective _ (inclusion_injective hN) have := IsSimpleModule.congr e.symm have := isSemisimpleModule_biSup_of_isSemisimpleModule_submodule fun m hm ↦ hs ⟨m, hm⟩ obtain ⟨_, ⟨m, hm, rfl⟩, S, le, ⟨e'⟩⟩ := LinearMap.range (inclusion hN) |>.le_linearEquiv_of_sSup_eq_top (comap (⨆ i ∈ s, i).subtype '' s) <| by rw [sSup_image, biSup_comap_subtype_eq_top] exact ⟨m, hm, _, map_le_iff_le_comap.mpr le, ⟨(e.trans e').trans (equivMapOfInjective _ (subtype_injective _) _)⟩⟩ theorem Submodule.linearEquiv_of_le_sSup [simple : ∀ m : s, IsSimpleModule R m] (hs : N ≤ sSup s) : ∃ S ∈ s, Nonempty (N ≃ₗ[R] S) := have ⟨m, hm, _S, le, ⟨e⟩⟩ := N.le_linearEquiv_of_le_sSup _ hs have := isSimpleModule_iff_isAtom.mp (.congr e.symm) have := ((isSimpleModule_iff_isAtom.mp <| simple ⟨m, hm⟩).le_iff_eq this.1).mp le ⟨m, hm, ⟨e.trans (.ofEq _ _ this)⟩⟩ end SimpleSubmodule section IsSimpleModule variable (R M) [IsSimpleModule R S] local instance (m : {m : Submodule R M | Nonempty (m ≃ₗ[R] S)}) : IsSimpleModule R m := .congr m.2.some protected theorem IsIsotypicOfType.isotypicComponent : IsIsotypicOfType R (isotypicComponent R M S) S := isIsotypicOfType_submodule_iff.mpr fun m h _ ↦ have ⟨_, ⟨e⟩, ⟨e'⟩⟩ := m.linearEquiv_of_le_sSup _ h ⟨e'.trans e⟩ protected theorem IsIsotypic.isotypicComponent : IsIsotypic R (isotypicComponent R M S) := (IsIsotypicOfType.isotypicComponent R M S).isIsotypic variable {R M} in protected theorem IsIsotypic.isotypicComponents {m : Submodule R M} (h : m ∈ isotypicComponents R M) : IsIsotypic R m := by obtain ⟨_, _, rfl⟩ := h; exact .isotypicComponent R M _ variable {R M} in theorem eq_isotypicComponent_of_le {S c : Submodule R M} (hc : c ∈ isotypicComponents R M) [IsSimpleModule R S] (le : S ≤ c) : c = isotypicComponent R M S := by obtain ⟨S', _, rfl⟩ := hc have ⟨e⟩ := isIsotypicOfType_submodule_iff.mp (.isotypicComponent R M S') _ le exact e.symm.isotypicComponent_eq theorem sSupIndep_isotypicComponents : sSupIndep (isotypicComponents R M) := fun c hc ↦ disjoint_iff.mpr <| of_not_not fun ne ↦ by set s := isotypicComponents R M \ {c} have : IsSemisimpleModule R c := by obtain ⟨S, _, rfl⟩ := hc; infer_instance have := IsSemisimpleModule.of_injective _ (Submodule.inclusion_injective (inf_le_left : c ⊓ sSup s ≤ c)) have (c : s) : IsSemisimpleModule R c := by obtain ⟨_, ⟨_, _, rfl⟩, _⟩ := c; infer_instance have ⟨S, le, _⟩ := (IsSemisimpleModule.eq_bot_or_exists_simple_le _).resolve_left ne have ⟨c', hc', S', le', ⟨e⟩⟩ := S.le_linearEquiv_of_le_sSup _ (le.trans inf_le_right) have := IsSimpleModule.congr e.symm refine hc'.2 ?_ rw [eq_isotypicComponent_of_le hc (le.trans inf_le_left), eq_isotypicComponent_of_le hc'.1 le'] exact e.symm.isotypicComponent_eq instance [IsNoetherian R M] : Finite (isotypicComponents R M) := Set.finite_coe_iff.mpr <| WellFoundedGT.finite_of_sSupIndep (sSupIndep_isotypicComponents R M) variable {R M S} theorem IsIsotypicOfType.of_isotypicComponent_eq_top (h : isotypicComponent R M S = ⊤) : IsIsotypicOfType R M S := fun m _ ↦ have ⟨_, ⟨e⟩, ⟨e'⟩⟩ := m.linearEquiv_of_sSup_eq_top _ h; ⟨e'.trans e⟩ theorem Submodule.map_le_isotypicComponent (S : Submodule R M) [IsSimpleModule R S] (f : M →ₗ[R] N) : S.map f ≤ isotypicComponent R N S := by conv_lhs => rw [← S.range_subtype, ← LinearMap.range_comp] obtain inj | eq := (f ∘ₗ S.subtype).injective_or_eq_zero · exact le_sSup ⟨.symm <| .ofInjective _ inj⟩ · simp_rw [eq, LinearMap.range_zero, bot_le] variable (S) in theorem LinearMap.le_comap_isotypicComponent (f : M →ₗ[R] N) : isotypicComponent R M S ≤ (isotypicComponent R N S).comap f := sSup_le fun m ⟨e⟩ ↦ Submodule.map_le_iff_le_comap.mp <| have := IsSimpleModule.congr e (m.map_le_isotypicComponent f).trans_eq e.isotypicComponent_eq section IsFullyInvariant variable {R M : Type*} [Semiring R] [AddCommMonoid M] [Module R M] /-- A submodule `N` an `R`-module `M` is fully invariant if `N` is mapped into itself by all `R`-linear endomorphisms of `M`. If `M` is semisimple, this is equivalent to `N` being a sum of isotypic components of `M`: see `isFullyInvariant_iff_sSup_isotypicComponents`. -/ def Submodule.IsFullyInvariant (N : Submodule R M) : Prop := ∀ f : Module.End R M, N ≤ N.comap f theorem isFullyInvariant_iff_isTwoSided {I : Ideal R} : I.IsFullyInvariant ↔ I.IsTwoSided := by simpa only [Submodule.IsFullyInvariant, ← MulOpposite.opEquiv.trans (RingEquiv.moduleEndSelf R |>.toEquiv) |>.forall_congr_right, SetLike.le_def, I.isTwoSided_iff] using forall_comm variable (R M) in /-- The fully invariant submodules of a module form a complete sublattice in the lattice of submodules. -/ def fullyInvariantSubmodule : CompleteSublattice (Submodule R M) := .mk' { N : Submodule R M | N.IsFullyInvariant } (fun _s hs f ↦ sSup_le fun _N hN ↦ (hs hN f).trans <| Submodule.comap_mono <| le_sSup hN) fun _s hs f ↦ Submodule.map_le_iff_le_comap.mp <| le_sInf fun _N hN ↦ Submodule.map_le_iff_le_comap.mpr <| (sInf_le hN).trans (hs hN f) theorem mem_fullyInvariantSubmodule_iff {m : Submodule R M} : m ∈ fullyInvariantSubmodule R M ↔ m.IsFullyInvariant := Iff.rfl end IsFullyInvariant section Equiv variable {ι : Type*} [DecidableEq ι] {N : ι → Submodule R M} (ind : iSupIndep N) (iSup_top : ⨆ i, N i = ⊤) (invar : ∀ i, (N i).IsFullyInvariant) /-- If an `R`-module `M` is the direct sum of fully invariant submodules `Nᵢ`, then `End R M` is isomorphic to `Πᵢ End R Nᵢ` as a ring. -/ noncomputable def iSupIndep.ringEquiv : Module.End R M ≃+* Π i, Module.End R (N i) where toFun f i := f.restrict (invar i f) invFun f := letI e := ind.linearEquiv iSup_top; e ∘ₗ DFinsupp.mapRange.linearMap f ∘ₗ e.symm left_inv f := LinearMap.ext fun x ↦ by exact Submodule.iSup_induction _ (motive := (_ = f ·)) (iSup_top ▸ Submodule.mem_top (x := x)) (fun i x h ↦ by simp [ind.linearEquiv_symm_apply _ h]) (by simp) fun _ _ h₁ h₂ ↦ by simpa only [map_add] using congr($h₁ + $h₂) right_inv f := by ext i x; simp [ind.linearEquiv_symm_apply _ x.2] map_add' _ _ := rfl map_mul' _ _ := rfl /-- If an `R`-module `M` is the direct sum of fully invariant submodules `Nᵢ`, then `End R M` is isomorphic to `Πᵢ End R Nᵢ` as an algebra. -/ noncomputable def iSupIndep.algEquiv [Module R₀ M] [IsScalarTower R₀ R M] : Module.End R M ≃ₐ[R₀] Π i, Module.End R (N i) where __ := ind.ringEquiv iSup_top invar commutes' _ := rfl end Equiv variable (R M S) in protected theorem Submodule.IsFullyInvariant.isotypicComponent : (isotypicComponent R M S).IsFullyInvariant := LinearMap.le_comap_isotypicComponent S theorem Submodule.IsFullyInvariant.of_mem_isotypicComponents {m : Submodule R M} (h : m ∈ isotypicComponents R M) : m.IsFullyInvariant := by obtain ⟨_, _, rfl⟩ := h; exact .isotypicComponent R M _ variable (R M) in /-- The Galois coinsertion from sets of isotypic components to fully invariant submodules. -/ def GaloisCoinsertion.setIsotypicComponents : GaloisCoinsertion (α := Set (isotypicComponents R M)) (β := fullyInvariantSubmodule R M) (fun s ↦ ⨆ c ∈ s, ⟨c, .of_mem_isotypicComponents c.2⟩) fun m ↦ {c | c.1 ≤ m} := GaloisConnection.toGaloisCoinsertion (fun _ _ ↦ iSup₂_le_iff) fun s c hc ↦ of_not_not fun hcs ↦ (bot_lt_isotypicComponents c.2).ne' <| (sSupIndep_isotypicComponents R M c.2).eq_bot_of_le <| hc.trans <| by simp_rw [CompleteSublattice.coe_iSup, iSup₂_le_iff] exact fun c hc ↦ le_sSup ⟨c.2, Subtype.coe_ne_coe.mpr (ne_of_mem_of_not_mem hc hcs)⟩ theorem le_isotypicComponent_iff [IsSemisimpleModule R M] {m : Submodule R M} : m ≤ isotypicComponent R M S ↔ IsIsotypicOfType R m S where mp h := .of_injective (.isotypicComponent R M S) _ (Submodule.inclusion_injective h) mpr h := (IsSemisimpleModule.sSup_simples_le m).ge.trans (sSup_le_sSup fun S ⟨_, le⟩ ↦ isIsotypicOfType_submodule_iff.mp h S le) theorem isotypicComponent_eq_top_iff [IsSemisimpleModule R M] : isotypicComponent R M S = ⊤ ↔ IsIsotypicOfType R M S := by rw [← top_le_iff, le_isotypicComponent_iff, Submodule.topEquiv.isIsotypicOfType_iff] open IsSemisimpleModule in theorem isFullyInvariant_iff_le_imp_isotypicComponent_le [IsSemisimpleModule R M] {m : Submodule R M} : m.IsFullyInvariant ↔ ∀ S ≤ m, [IsSimpleModule R S] → isotypicComponent R M S ≤ m where mp h S le _ := sSup_le fun S' ⟨e⟩ ↦ by have ⟨p, eq⟩ := extension_property _ S.subtype_injective (S'.subtype ∘ₗ e.symm) refine le_trans ?_ (Submodule.map_le_iff_le_comap.mpr (le.trans (h p))) rw [← S.range_subtype, ← LinearMap.range_comp, eq, e.symm.range_comp, S'.range_subtype] mpr h f := (sSup_simples_le m).ge.trans <| sSup_le fun S ⟨_, le⟩ ↦ Submodule.map_le_iff_le_comap.mp ((S.map_le_isotypicComponent f).trans (h S le)) theorem eq_isotypicComponent_iff [IsSemisimpleModule R M] {m : Submodule R M} (ne : m ≠ ⊥) : m = isotypicComponent R M S ↔ IsIsotypicOfType R m S ∧ m.IsFullyInvariant where mp := by rintro rfl; exact ⟨.isotypicComponent R M S, .isotypicComponent R M S⟩ mpr := fun ⟨iso, invar⟩ ↦ (le_isotypicComponent_iff.mpr iso).antisymm <| have ⟨S', le, _⟩ := (IsSemisimpleModule.eq_bot_or_exists_simple_le m).resolve_left ne (isIsotypicOfType_submodule_iff.mp iso S' le).some.symm.isotypicComponent_eq.trans_le (isFullyInvariant_iff_le_imp_isotypicComponent_le.mp invar _ le) end IsSimpleModule variable [IsSemisimpleModule R M] open IsSemisimpleModule theorem isIsotypic_iff_isFullyInvariant_imp_bot_or_top : IsIsotypic R M ↔ ∀ N : Submodule R M, N.IsFullyInvariant → N = ⊥ ∨ N = ⊤ where mp h N hN := (eq_bot_or_exists_simple_le N).imp_right fun ⟨S, le, _⟩ ↦ top_unique <| (isotypicComponent_eq_top_iff.mpr (h S)).ge.trans ((isFullyInvariant_iff_le_imp_isotypicComponent_le.mp hN) _ le) mpr h S _ := isotypicComponent_eq_top_iff.mp <| (h _ (.isotypicComponent R M S)).resolve_left (bot_lt_isotypicComponent S).ne' theorem mem_isotypicComponents_iff {m : Submodule R M} : m ∈ isotypicComponents R M ↔ IsIsotypic R m ∧ m.IsFullyInvariant ∧ m ≠ ⊥ where mp := by rintro ⟨S, _, rfl⟩; exact ⟨.isotypicComponent R M S, .isotypicComponent R M S, (bot_lt_isotypicComponent S).ne'⟩ mpr := fun ⟨iso, invar, ne⟩ ↦ have ⟨S, le, simple⟩ := (eq_bot_or_exists_simple_le m).resolve_left ne ⟨S, simple, (eq_isotypicComponent_iff ne).mpr ⟨isIsotypic_submodule_iff.mp iso S le, invar⟩⟩ /-- Sets of isotypic components in a semisimple module are in order-preserving 1-1 correspondence with fully invariant submodules. Consequently, the fully invariant submodules form a complete atomic Boolean algebra. -/ @[simps] def OrderIso.setIsotypicComponents : Set (isotypicComponents R M) ≃o fullyInvariantSubmodule R M where toFun s := ⨆ c ∈ s, ⟨c, .of_mem_isotypicComponents c.2⟩ invFun m := { c | c.1 ≤ m } left_inv := (GaloisCoinsertion.setIsotypicComponents R M).u_l_eq right_inv m := (iSup₂_le fun _ ↦ by exact id).antisymm <| (sSup_simples_le m.1).ge.trans <| sSup_le fun S ⟨simple, le⟩ ↦ S.le_isotypicComponent.trans <| by let c : isotypicComponents R M := ⟨_, S, simple, rfl⟩ simp_rw [← show c.1 = isotypicComponent R M S from rfl, CompleteSublattice.coe_iSup] exact le_biSup _ (isFullyInvariant_iff_le_imp_isotypicComponent_le.mp m.2 _ le) map_rel_iff' := (GaloisCoinsertion.setIsotypicComponents R M).l_le_l_iff theorem isFullyInvariant_iff_sSup_isotypicComponents {m : Submodule R M} : m.IsFullyInvariant ↔ ∃ s ⊆ isotypicComponents R M, m = sSup s := by refine ⟨fun h ↦ ⟨OrderIso.setIsotypicComponents.symm ⟨m, h⟩, ⟨?_, ?_⟩⟩, ?_⟩ · rintro _ ⟨c, _, rfl⟩; exact c.2 · convert Subtype.ext_iff.mp (OrderIso.setIsotypicComponents.right_inv ⟨m, h⟩).symm simp [sSup_image, OrderIso.setIsotypicComponents, OrderIso.symm] · rintro ⟨_, hs, rfl⟩ exact (fullyInvariantSubmodule R M).sSupClosed fun _ h ↦ .of_mem_isotypicComponents (hs h) variable (R M) in theorem sSup_isotypicComponents : sSup (isotypicComponents R M) = ⊤ := have ⟨_, h, eq⟩ := isFullyInvariant_iff_sSup_isotypicComponents.mp (fullyInvariantSubmodule R M).top_mem top_unique <| eq.le.trans (sSup_le_sSup h) namespace IsSemisimpleModule variable (R M) [Module R₀ M] [IsScalarTower R₀ R M] [DecidableEq (isotypicComponents R M)] /-- The endomorphism algebra of a semisimple module is the direct product of the endomorphism algebras of its isotypic components. -/ noncomputable def endAlgEquiv : Module.End R M ≃ₐ[R₀] Π c : isotypicComponents R M, Module.End R c.1 := ((sSupIndep_iff _).mp <| sSupIndep_isotypicComponents R M).algEquiv R₀ ((sSup_eq_iSup' _).symm.trans <| sSup_isotypicComponents R M) (.of_mem_isotypicComponents ·.2) /-- The endomorphism ring of a semisimple module is the direct product of the endomorphism rings of its isotypic components. -/ noncomputable def endRingEquiv : Module.End R M ≃+* Π c : isotypicComponents R M, Module.End R c.1 := (endAlgEquiv ℕ R M).toRingEquiv end IsSemisimpleModule
InsertNth.lean
/- Copyright (c) 2024 Lean FRO. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.Data.List.InsertIdx /-! This is a stub file for importing `Mathlib/Data/List/InsertNth.lean`, which has been renamed to `Mathlib/Data/List/InsertIdx.lean`. This file can be removed once the deprecation for `List.insertNth` is removed. -/
Unique.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Logic.IsEmpty import Mathlib.Tactic.Inhabit /-! # Types with a unique term In this file we define a typeclass `Unique`, which expresses that a type has a unique term. In other words, a type that is `Inhabited` and a `Subsingleton`. ## Main declaration * `Unique`: a typeclass that expresses that a type has a unique term. ## Main statements * `Unique.mk'`: an inhabited subsingleton type is `Unique`. This can not be an instance because it would lead to loops in typeclass inference. * `Function.Surjective.unique`: if the domain of a surjective function is `Unique`, then its codomain is `Unique` as well. * `Function.Injective.subsingleton`: if the codomain of an injective function is `Subsingleton`, then its domain is `Subsingleton` as well. * `Function.Injective.unique`: if the codomain of an injective function is `Subsingleton` and its domain is `Inhabited`, then its domain is `Unique`. ## Implementation details The typeclass `Unique α` is implemented as a type, rather than a `Prop`-valued predicate, for good definitional properties of the default term. -/ universe u v w -- Don't generate injectivity lemmas, which the `simpNF` linter will complain about. set_option genInjectivity false in /-- `Unique α` expresses that `α` is a type with a unique term `default`. This is implemented as a type, rather than a `Prop`-valued predicate, for good definitional properties of the default term. -/ @[ext] structure Unique (α : Sort u) extends Inhabited α where /-- In a `Unique` type, every term is equal to the default element (from `Inhabited`). -/ uniq : ∀ a : α, a = default attribute [class] Unique theorem unique_iff_existsUnique (α : Sort u) : Nonempty (Unique α) ↔ ∃! _ : α, True := ⟨fun ⟨u⟩ ↦ ⟨u.default, trivial, fun a _ ↦ u.uniq a⟩, fun ⟨a, _, h⟩ ↦ ⟨⟨⟨a⟩, fun _ ↦ h _ trivial⟩⟩⟩ theorem unique_subtype_iff_existsUnique {α} (p : α → Prop) : Nonempty (Unique (Subtype p)) ↔ ∃! a, p a := ⟨fun ⟨u⟩ ↦ ⟨u.default.1, u.default.2, fun a h ↦ congr_arg Subtype.val (u.uniq ⟨a, h⟩)⟩, fun ⟨a, ha, he⟩ ↦ ⟨⟨⟨⟨a, ha⟩⟩, fun ⟨b, hb⟩ ↦ by congr exact he b hb⟩⟩⟩ /-- Given an explicit `a : α` with `Subsingleton α`, we can construct a `Unique α` instance. This is a def because the typeclass search cannot arbitrarily invent the `a : α` term. Nevertheless, these instances are all equivalent by `Unique.Subsingleton.unique`. See note [reducible non-instances]. -/ abbrev uniqueOfSubsingleton {α : Sort*} [Subsingleton α] (a : α) : Unique α where default := a uniq _ := Subsingleton.elim _ _ instance PUnit.instUnique : Unique PUnit.{u} where default := PUnit.unit uniq x := subsingleton x _ @[simp] theorem PUnit.default_eq_unit : (default : PUnit) = PUnit.unit := rfl /-- Every provable proposition is unique, as all proofs are equal. -/ def uniqueProp {p : Prop} (h : p) : Unique.{0} p where default := h uniq _ := rfl instance : Unique True := uniqueProp trivial namespace Unique open Function section variable {α : Sort*} [Unique α] -- see Note [lower instance priority] instance (priority := 100) : Inhabited α := toInhabited ‹Unique α› theorem eq_default (a : α) : a = default := uniq _ a theorem default_eq (a : α) : default = a := (uniq _ a).symm -- see Note [lower instance priority] instance (priority := 100) instSubsingleton : Subsingleton α := subsingleton_of_forall_eq _ eq_default theorem forall_iff {p : α → Prop} : (∀ a, p a) ↔ p default := ⟨fun h ↦ h _, fun h x ↦ by rwa [Unique.eq_default x]⟩ theorem exists_iff {p : α → Prop} : Exists p ↔ p default := ⟨fun ⟨a, ha⟩ ↦ eq_default a ▸ ha, Exists.intro default⟩ end variable {α : Sort*} @[ext] protected theorem subsingleton_unique' : ∀ h₁ h₂ : Unique α, h₁ = h₂ | ⟨⟨x⟩, h⟩, ⟨⟨y⟩, _⟩ => by congr; rw [h x, h y] instance subsingleton_unique : Subsingleton (Unique α) := ⟨Unique.subsingleton_unique'⟩ /-- Construct `Unique` from `Inhabited` and `Subsingleton`. Making this an instance would create a loop in the class inheritance graph. -/ abbrev mk' (α : Sort u) [h₁ : Inhabited α] [Subsingleton α] : Unique α := { h₁ with uniq := fun _ ↦ Subsingleton.elim _ _ } end Unique theorem nonempty_unique (α : Sort u) [Subsingleton α] [Nonempty α] : Nonempty (Unique α) := by inhabit α exact ⟨Unique.mk' α⟩ theorem unique_iff_subsingleton_and_nonempty (α : Sort u) : Nonempty (Unique α) ↔ Subsingleton α ∧ Nonempty α := ⟨fun ⟨u⟩ ↦ by constructor <;> exact inferInstance, fun ⟨hs, hn⟩ ↦ nonempty_unique α⟩ variable {α : Sort*} @[simp] theorem Pi.default_def {β : α → Sort v} [∀ a, Inhabited (β a)] : @default (∀ a, β a) _ = fun a : α ↦ @default (β a) _ := rfl theorem Pi.default_apply {β : α → Sort v} [∀ a, Inhabited (β a)] (a : α) : @default (∀ a, β a) _ a = default := rfl instance Pi.unique {β : α → Sort v} [∀ a, Unique (β a)] : Unique (∀ a, β a) where uniq := fun _ ↦ funext fun _ ↦ Unique.eq_default _ /-- There is a unique function on an empty domain. -/ instance Pi.uniqueOfIsEmpty [IsEmpty α] (β : α → Sort v) : Unique (∀ a, β a) where default := isEmptyElim uniq _ := funext isEmptyElim theorem eq_const_of_subsingleton {β : Sort*} [Subsingleton α] (f : α → β) (a : α) : f = Function.const α (f a) := funext fun x ↦ Subsingleton.elim x a ▸ rfl theorem eq_const_of_unique {β : Sort*} [Unique α] (f : α → β) : f = Function.const α (f default) := eq_const_of_subsingleton .. theorem heq_const_of_unique [Unique α] {β : α → Sort v} (f : ∀ a, β a) : f ≍ Function.const α (f default) := (Function.hfunext rfl) fun i _ _ ↦ by rw [Subsingleton.elim i default]; rfl namespace Function variable {β : Sort*} {f : α → β} /-- If the codomain of an injective function is a subsingleton, then the domain is a subsingleton as well. -/ protected theorem Injective.subsingleton (hf : Injective f) [Subsingleton β] : Subsingleton α := ⟨fun _ _ ↦ hf <| Subsingleton.elim _ _⟩ /-- If the domain of a surjective function is a subsingleton, then the codomain is a subsingleton as well. -/ protected theorem Surjective.subsingleton [Subsingleton α] (hf : Surjective f) : Subsingleton β := ⟨hf.forall₂.2 fun x y ↦ congr_arg f <| Subsingleton.elim x y⟩ /-- If the domain of a surjective function is a singleton, then the codomain is a singleton as well. -/ protected def Surjective.unique {α : Sort u} (f : α → β) (hf : Surjective f) [Unique.{u} α] : Unique β := @Unique.mk' _ ⟨f default⟩ hf.subsingleton /-- If `α` is inhabited and admits an injective map to a subsingleton type, then `α` is `Unique`. -/ protected def Injective.unique [Inhabited α] [Subsingleton β] (hf : Injective f) : Unique α := @Unique.mk' _ _ hf.subsingleton /-- If a constant function is surjective, then the codomain is a singleton. -/ def Surjective.uniqueOfSurjectiveConst (α : Type*) {β : Type*} (b : β) (h : Function.Surjective (Function.const α b)) : Unique β := @uniqueOfSubsingleton _ (subsingleton_of_forall_eq b <| h.forall.mpr fun _ ↦ rfl) b end Function section Pi variable {ι : Sort*} {α : ι → Sort*} /-- Given one value over a unique, we get a dependent function. -/ def uniqueElim [Unique ι] (x : α (default : ι)) (i : ι) : α i := by rw [Unique.eq_default i] exact x @[simp] theorem uniqueElim_default {_ : Unique ι} (x : α (default : ι)) : uniqueElim x (default : ι) = x := rfl @[simp] theorem uniqueElim_const {β : Sort*} {_ : Unique ι} (x : β) (i : ι) : uniqueElim (α := fun _ ↦ β) x i = x := rfl end Pi -- TODO: Mario turned this off as a simp lemma in Batteries, wanting to profile it. attribute [local simp] eq_iff_true_of_subsingleton in theorem Unique.bijective {A B} [Unique A] [Unique B] {f : A → B} : Function.Bijective f := by rw [Function.bijective_iff_has_inverse] refine ⟨default, ?_, ?_⟩ <;> intro x <;> simp namespace Option /-- `Option α` is a `Subsingleton` if and only if `α` is empty. -/ theorem subsingleton_iff_isEmpty {α : Type u} : Subsingleton (Option α) ↔ IsEmpty α := ⟨fun h ↦ ⟨fun x ↦ Option.noConfusion <| @Subsingleton.elim _ h x none⟩, fun h ↦ ⟨fun x y ↦ Option.casesOn x (Option.casesOn y rfl fun x ↦ h.elim x) fun x ↦ h.elim x⟩⟩ instance {α} [IsEmpty α] : Unique (Option α) := @Unique.mk' _ _ (subsingleton_iff_isEmpty.2 ‹_›) end Option section Subtype instance Unique.subtypeEq (y : α) : Unique { x // x = y } where default := ⟨y, rfl⟩ uniq := fun ⟨x, hx⟩ ↦ by congr instance Unique.subtypeEq' (y : α) : Unique { x // y = x } where default := ⟨y, rfl⟩ uniq := fun ⟨x, hx⟩ ↦ by subst hx; congr end Subtype instance Fin.instUnique : Unique (Fin 1) where uniq _ := Subsingleton.elim _ _
Basic.lean
/- Copyright (c) 2025 Raphael Douglas Giles. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Raphael Douglas Giles, Zhixuan Dai, Zhenyan Fu, Yiming Fu, Jingting Wang, Eric Wieser -/ import Mathlib.LinearAlgebra.TensorAlgebra.Basic /-! # Symmetric Algebras Given a commutative semiring `R`, and an `R`-module `M`, we construct the symmetric algebra of `M`. This is the free commutative `R`-algebra generated (`R`-linearly) by the module `M`. ## Notation * `SymmetricAlgebra R M`: a concrete construction of the symmetric algebra defined as a quotient of the tensor algebra. It is endowed with an R-algebra structure and a commutative ring structure. * `SymmetricAlgebra.ι R`: the canonical R-linear map `M →ₗ[R] SymmetricAlgebra R M`. ## Note See `SymAlg R` instead if you are looking for the symmetrized algebra, which gives a commutative multiplication on `R` by $a \circ b = \frac{1}{2}(ab + ba)$. -/ variable (R M : Type*) [CommSemiring R] [AddCommMonoid M] [Module R M] /-- Relation on the tensor algebra which will yield the symmetric algebra when quotiented out by. -/ inductive TensorAlgebra.SymRel : TensorAlgebra R M → TensorAlgebra R M → Prop where | mul_comm (x y : M) : SymRel (ι R x * ι R y) (ι R y * ι R x) open TensorAlgebra /-- Concrete construction of the symmetric algebra of `M` by quotienting out the tensor algebra by the commutativity relation. -/ abbrev SymmetricAlgebra := RingQuot (SymRel R M) namespace SymmetricAlgebra /-- Algebra homomorphism from the tensor algebra over `M` to the symmetric algebra over `M`. -/ abbrev algHom : TensorAlgebra R M →ₐ[R] SymmetricAlgebra R M := RingQuot.mkAlgHom R (SymRel R M) lemma algHom_surjective : Function.Surjective (algHom R M) := RingQuot.mkAlgHom_surjective _ _ /-- Canonical inclusion of `M` into the symmetric algebra `SymmetricAlgebra R M`. -/ def ι : M →ₗ[R] SymmetricAlgebra R M := algHom R M ∘ₗ TensorAlgebra.ι R @[elab_as_elim] theorem induction {motive : SymmetricAlgebra R M → Prop} (algebraMap : ∀ r, motive (algebraMap R (SymmetricAlgebra R M) r)) (ι : ∀ x, motive (ι R M x)) (mul : ∀ a b, motive a → motive b → motive (a * b)) (add : ∀ a b, motive a → motive b → motive (a + b)) (a : SymmetricAlgebra R M) : motive a := by rcases algHom_surjective _ _ a with ⟨a, rfl⟩ induction a using TensorAlgebra.induction with | algebraMap r => rw [AlgHom.commutes]; exact algebraMap r | ι x => exact ι x | mul x y hx hy => rw [map_mul]; exact mul _ _ hx hy | add x y hx hy => rw [map_add]; exact add _ _ hx hy open TensorAlgebra in instance : CommSemiring (SymmetricAlgebra R M) where mul_comm a b := by change Commute a b induction b using SymmetricAlgebra.induction with | algebraMap r => exact Algebra.commute_algebraMap_right _ _ | ι x => induction a using SymmetricAlgebra.induction with | algebraMap r => exact Algebra.commute_algebraMap_left _ _ | ι y => simp [commute_iff_eq, ι, ← map_mul, RingQuot.mkAlgHom_rel _ (SymRel.mul_comm x y)] | mul a b ha hb => exact ha.mul_left hb | add a b ha hb => exact ha.add_left hb | mul b c hb hc => exact hb.mul_right hc | add b c hb hc => exact hb.add_right hc instance (R M) [CommRing R] [AddCommMonoid M] [Module R M] : CommRing (SymmetricAlgebra R M) where __ := inferInstanceAs (CommSemiring (SymmetricAlgebra R M)) __ := inferInstanceAs (Ring (RingQuot (SymRel R M))) variable {R M} {A : Type*} [CommSemiring A] [Algebra R A] /-- For any linear map `f : M →ₗ[R] A`, `SymmetricAlgebra.lift f` lifts the linear map to an R-algebra homomorphism from `SymmetricAlgebra R M` to `A`. -/ def lift : (M →ₗ[R] A) ≃ (SymmetricAlgebra R M →ₐ[R] A) := by let equiv : (TensorAlgebra R M →ₐ[R] A) ≃ {f : TensorAlgebra R M →ₐ[R] A // ∀ {x y}, (TensorAlgebra.SymRel R M) x y → f x = f y} := by refine (Equiv.subtypeUnivEquiv fun h _ _ h' ↦ ?_).symm induction h' with | mul_comm x y => rw [map_mul, map_mul, mul_comm] exact (TensorAlgebra.lift R).trans <| equiv.trans <| RingQuot.liftAlgHom R variable (f : M →ₗ[R] A) @[simp] lemma lift_ι_apply (a : M) : lift f (ι R M a) = f a := by simp [lift, ι, algHom] @[simp] lemma lift_comp_ι : lift f ∘ₗ ι R M = f := LinearMap.ext <| lift_ι_apply f @[ext] theorem algHom_ext {F G : SymmetricAlgebra R M →ₐ[R] A} (h : F ∘ₗ ι R M = (G ∘ₗ ι R M : M →ₗ[R] A)) : F = G := by ext x exact congr($h x) @[simp] lemma lift_ι : lift (ι R M) = .id R (SymmetricAlgebra R M) := by apply algHom_ext rw [lift_comp_ι] ext simp /-- The left-inverse of `algebraMap`. -/ def algebraMapInv : SymmetricAlgebra R M →ₐ[R] R := lift (0 : M →ₗ[R] R) variable (M) theorem algebraMap_leftInverse : Function.LeftInverse algebraMapInv (algebraMap R <| SymmetricAlgebra R M) := fun x => by simp [algebraMapInv] @[simp] theorem algebraMap_inj (x y : R) : algebraMap R (SymmetricAlgebra R M) x = algebraMap R (SymmetricAlgebra R M) y ↔ x = y := (algebraMap_leftInverse M).injective.eq_iff @[simp] theorem algebraMap_eq_zero_iff (x : R) : algebraMap R (SymmetricAlgebra R M) x = 0 ↔ x = 0 := map_eq_zero_iff (algebraMap _ _) (algebraMap_leftInverse _).injective @[simp] theorem algebraMap_eq_one_iff (x : R) : algebraMap R (SymmetricAlgebra R M) x = 1 ↔ x = 1 := map_eq_one_iff (algebraMap _ _) (algebraMap_leftInverse _).injective /-- A `SymmetricAlgebra` over a nontrivial semiring is nontrivial. -/ instance [Nontrivial R] : Nontrivial (SymmetricAlgebra R M) := (algebraMap_leftInverse M).injective.nontrivial end SymmetricAlgebra
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.
HomOrthogonal.lean
/- Copyright (c) 2022 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.CategoryTheory.Linear.Basic import Mathlib.CategoryTheory.Preadditive.Biproducts import Mathlib.LinearAlgebra.Matrix.InvariantBasisNumber import Mathlib.Data.Set.Subsingleton /-! # Hom orthogonal families. A family of objects in a category with zero morphisms is "hom orthogonal" if the only morphism between distinct objects is the zero morphism. We show that in any category with zero morphisms and finite biproducts, a morphism between biproducts drawn from a hom orthogonal family `s : ι → C` can be decomposed into a block diagonal matrix with entries in the endomorphism rings of the `s i`. When the category is preadditive, this decomposition is an additive equivalence, and intertwines composition and matrix multiplication. When the category is `R`-linear, the decomposition is an `R`-linear equivalence. If every object in the hom orthogonal family has an endomorphism ring with invariant basis number (e.g. if each object in the family is simple, so its endomorphism ring is a division ring, or otherwise if each endomorphism ring is commutative), then decompositions of an object as a biproduct of the family have uniquely defined multiplicities. We state this as: ``` theorem HomOrthogonal.equiv_of_iso (o : HomOrthogonal s) {f : α → ι} {g : β → ι} (i : (⨁ fun a => s (f a)) ≅ ⨁ fun b => s (g b)) : ∃ e : α ≃ β, ∀ a, g (e a) = f a ``` This is preliminary to defining semisimple categories. -/ open Matrix CategoryTheory.Limits universe v u namespace CategoryTheory variable {C : Type u} [Category.{v} C] /-- A family of objects is "hom orthogonal" if there is at most one morphism between distinct objects. (In a category with zero morphisms, that must be the zero morphism.) -/ def HomOrthogonal {ι : Type*} (s : ι → C) : Prop := Pairwise fun i j => Subsingleton (s i ⟶ s j) namespace HomOrthogonal variable {ι : Type*} {s : ι → C} theorem eq_zero [HasZeroMorphisms C] (o : HomOrthogonal s) {i j : ι} (w : i ≠ j) (f : s i ⟶ s j) : f = 0 := (o w).elim _ _ section variable [HasZeroMorphisms C] [HasFiniteBiproducts C] open scoped Classical in /-- Morphisms between two direct sums over a hom orthogonal family `s : ι → C` are equivalent to block diagonal matrices, with blocks indexed by `ι`, and matrix entries in `i`-th block living in the endomorphisms of `s i`. -/ @[simps] noncomputable def matrixDecomposition (o : HomOrthogonal s) {α β : Type} [Finite α] [Finite β] {f : α → ι} {g : β → ι} : ((⨁ fun a => s (f a)) ⟶ ⨁ fun b => s (g b)) ≃ ∀ i : ι, Matrix (g ⁻¹' {i}) (f ⁻¹' {i}) (End (s i)) where toFun z i j k := eqToHom (by rcases k with ⟨k, ⟨⟩⟩ simp) ≫ biproduct.components z k j ≫ eqToHom (by rcases j with ⟨j, ⟨⟩⟩ simp) invFun z := biproduct.matrix fun j k => if h : f j = g k then z (f j) ⟨k, by simp [h]⟩ ⟨j, by simp⟩ ≫ eqToHom (by simp [h]) else 0 left_inv z := by ext j k simp only [biproduct.matrix_π, biproduct.ι_desc] split_ifs with h · simp rfl · symm apply o.eq_zero h right_inv z := by ext i ⟨j, w⟩ ⟨k, ⟨⟩⟩ simp only [eqToHom_refl, biproduct.matrix_components, Category.id_comp] split_ifs with h · simp · exfalso exact h w.symm end section variable [Preadditive C] [HasFiniteBiproducts C] /-- `HomOrthogonal.matrixDecomposition` as an additive equivalence. -/ @[simps!] noncomputable def matrixDecompositionAddEquiv (o : HomOrthogonal s) {α β : Type} [Finite α] [Finite β] {f : α → ι} {g : β → ι} : ((⨁ fun a => s (f a)) ⟶ ⨁ fun b => s (g b)) ≃+ ∀ i : ι, Matrix (g ⁻¹' {i}) (f ⁻¹' {i}) (End (s i)) := { o.matrixDecomposition with map_add' := fun w z => by ext dsimp [biproduct.components] simp } open scoped Classical in @[simp] theorem matrixDecomposition_id (o : HomOrthogonal s) {α : Type} [Finite α] {f : α → ι} (i : ι) : o.matrixDecomposition (𝟙 (⨁ fun a => s (f a))) i = 1 := by ext ⟨b, ⟨⟩⟩ ⟨a, j_property⟩ simp only [Set.mem_preimage, Set.mem_singleton_iff] at j_property simp only [Category.comp_id, Category.id_comp, End.one_def, eqToHom_refl, Matrix.one_apply, HomOrthogonal.matrixDecomposition_apply, biproduct.components] split_ifs with h · cases h simp · simp only [Subtype.mk.injEq] at h -- Porting note: used to be `convert comp_zero`, but that does not work anymore have : biproduct.ι (fun a ↦ s (f a)) a ≫ biproduct.π (fun b ↦ s (f b)) b = 0 := by simpa using biproduct.ι_π_ne _ (Ne.symm h) rw [this, comp_zero] open scoped Classical in theorem matrixDecomposition_comp (o : HomOrthogonal s) {α β γ : Type} [Finite α] [Fintype β] [Finite γ] {f : α → ι} {g : β → ι} {h : γ → ι} (z : (⨁ fun a => s (f a)) ⟶ ⨁ fun b => s (g b)) (w : (⨁ fun b => s (g b)) ⟶ ⨁ fun c => s (h c)) (i : ι) : o.matrixDecomposition (z ≫ w) i = o.matrixDecomposition w i * o.matrixDecomposition z i := by ext ⟨c, ⟨⟩⟩ ⟨a, j_property⟩ simp only [Set.mem_preimage, Set.mem_singleton_iff] at j_property simp only [Matrix.mul_apply, Limits.biproduct.components, HomOrthogonal.matrixDecomposition_apply, Category.comp_id, Category.id_comp, Category.assoc, End.mul_def, eqToHom_refl, eqToHom_trans_assoc] conv_lhs => rw [← Category.id_comp w, ← biproduct.total] simp only [Preadditive.sum_comp, Preadditive.comp_sum] apply Finset.sum_congr_set · simp · intro b nm simp only [Set.mem_preimage, Set.mem_singleton_iff] at nm simp only [Category.assoc] -- Porting note: this used to be 4 times `convert comp_zero` have : biproduct.ι (fun b ↦ s (g b)) b ≫ w ≫ biproduct.π (fun b ↦ s (h b)) c = 0 := by apply o.eq_zero nm simp only [this, comp_zero] section variable {R : Type*} [Semiring R] [Linear R C] /-- `HomOrthogonal.MatrixDecomposition` as an `R`-linear equivalence. -/ @[simps] noncomputable def matrixDecompositionLinearEquiv (o : HomOrthogonal s) {α β : Type} [Finite α] [Finite β] {f : α → ι} {g : β → ι} : ((⨁ fun a => s (f a)) ⟶ ⨁ fun b => s (g b)) ≃ₗ[R] ∀ i : ι, Matrix (g ⁻¹' {i}) (f ⁻¹' {i}) (End (s i)) := { o.matrixDecompositionAddEquiv with map_smul' := fun w z => by ext dsimp [biproduct.components] simp } end /-! The hypothesis that `End (s i)` has invariant basis number is automatically satisfied if `s i` is simple (as then `End (s i)` is a division ring). -/ variable [∀ i, InvariantBasisNumber (End (s i))] /-- Given a hom orthogonal family `s : ι → C` for which each `End (s i)` is a ring with invariant basis number (e.g. if each `s i` is simple), if two direct sums over `s` are isomorphic, then they have the same multiplicities. -/ theorem equiv_of_iso (o : HomOrthogonal s) {α β : Type} [Finite α] [Finite β] {f : α → ι} {g : β → ι} (i : (⨁ fun a => s (f a)) ≅ ⨁ fun b => s (g b)) : ∃ e : α ≃ β, ∀ a, g (e a) = f a := by classical refine ⟨Equiv.ofPreimageEquiv ?_, fun a => Equiv.ofPreimageEquiv_map _ _⟩ intro c apply Nonempty.some apply Cardinal.eq.1 cases nonempty_fintype α; cases nonempty_fintype β simp only [Cardinal.mk_fintype, Nat.cast_inj] exact Matrix.square_of_invertible (o.matrixDecomposition i.inv c) (o.matrixDecomposition i.hom c) (by rw [← o.matrixDecomposition_comp] simp) (by rw [← o.matrixDecomposition_comp] simp) end end HomOrthogonal end CategoryTheory
UnusedTactic.lean
/- Copyright (c) 2024 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import Lean.Parser.Syntax import Batteries.Tactic.Unreachable -- Import this linter explicitly to ensure that -- this file has a valid copyright header and module docstring. import Mathlib.Tactic.Linter.Header import Mathlib.Tactic.Linter.UnusedTacticExtension /-! # The unused tactic linter The unused linter makes sure that every tactic call actually changes *something*. The inner workings of the linter are as follows. The linter inspects the goals before and after each tactic execution. If they are not identical, the linter is happy. If they are identical, then the linter checks if the tactic is whitelisted. Possible reason for whitelisting are * tactics that emit messages, such as `have?`, `extract_goal`, or `says`; * tactics that are in place to assert something, such as `guard`; * tactics that allow to work on a specific goal, such as `on_goal`; * "flow control" tactics, such as `success_if_fail` and related. The only tactic that has a bespoke criterion is `swap_var`: the reason is that the only change that `swap_var` has is to relabel the usernames of local declarations. Thus, to check that `swap_var` was used, so we inspect the names of all the local declarations before and after and see if there is some change. ## Notable exclusions * `conv` is completely ignored by the linter. * The linter does not enter a "sequence tactic": upon finding `tac <;> [tac1, tac2, ...]` the linter assumes that the tactic is doing something and does not recurse into each `tac1, tac2, ...`. This is just for lack of an implementation: it may not be hard to do this. * The tactic does not check the discharger for `linear_combination`, but checks `linear_combination` itself. The main reason is that `skip` is a common discharger tactic and the linter would then always fail whenever the user explicitly chose to pass `skip` as a discharger tactic. ## TODO * The linter seems to be silenced by `set_option ... in`: maybe it should enter `in`s? ## Implementation notes Yet another linter copied from the `unreachableTactic` linter! -/ open Lean Elab Std Linter namespace Mathlib.Linter /-- The unused tactic linter makes sure that every tactic call actually changes *something*. -/ register_option linter.unusedTactic : Bool := { defValue := true descr := "enable the unused tactic linter" } namespace UnusedTactic /-- The monad for collecting the ranges of the syntaxes that do not modify any goal. -/ abbrev M := StateRefT (Std.HashMap String.Range Syntax) IO -- Tactics that are expected to not change the state but should also not be flagged by the -- unused tactic linter. #allow_unused_tactic! Lean.Parser.Term.byTactic Lean.Parser.Tactic.tacticSeq Lean.Parser.Tactic.tacticSeq1Indented Lean.Parser.Tactic.tacticTry_ -- the following `SyntaxNodeKind`s play a role in silencing `test`s Lean.Parser.Tactic.guardHyp Lean.Parser.Tactic.guardTarget Lean.Parser.Tactic.failIfSuccess /-- A list of blacklisted syntax kinds, which are expected to have subterms that contain unevaluated tactics. -/ initialize ignoreTacticKindsRef : IO.Ref NameHashSet ← IO.mkRef <| .ofArray #[ `Mathlib.Tactic.Says.says, ``Parser.Term.binderTactic, ``Lean.Parser.Term.dynamicQuot, ``Lean.Parser.Tactic.quotSeq, ``Lean.Parser.Tactic.tacticStop_, ``Lean.Parser.Command.notation, ``Lean.Parser.Command.mixfix, ``Lean.Parser.Tactic.discharger, ``Lean.Parser.Tactic.Conv.conv, `Batteries.Tactic.seq_focus, `Mathlib.Tactic.Hint.registerHintStx, `Mathlib.Tactic.LinearCombination.linearCombination, `Mathlib.Tactic.LinearCombination'.linearCombination', `Aesop.Frontend.Parser.addRules, `Aesop.Frontend.Parser.aesopTactic, `Aesop.Frontend.Parser.aesopTactic?, -- the following `SyntaxNodeKind`s play a role in silencing `test`s ``Lean.Parser.Tactic.failIfSuccess, `Mathlib.Tactic.successIfFailWithMsg, `Mathlib.Tactic.failIfNoProgress ] /-- Is this a syntax kind that contains intentionally unused tactic subterms? -/ def isIgnoreTacticKind (ignoreTacticKinds : NameHashSet) (k : SyntaxNodeKind) : Bool := k.components.contains `Conv || "slice".isPrefixOf k.toString || k matches .str _ "quot" || ignoreTacticKinds.contains k /-- Adds a new syntax kind whose children will be ignored by the `unusedTactic` linter. This should be called from an `initialize` block. -/ def addIgnoreTacticKind (kind : SyntaxNodeKind) : IO Unit := ignoreTacticKindsRef.modify (·.insert kind) variable (ignoreTacticKinds : NameHashSet) (isTacKind : SyntaxNodeKind → Bool) in /-- Accumulates the set of tactic syntaxes that should be evaluated at least once. -/ @[specialize] partial def getTactics (stx : Syntax) : M Unit := do if let .node _ k args := stx then if !isIgnoreTacticKind ignoreTacticKinds k then args.forM getTactics if isTacKind k then if let some r := stx.getRange? true then modify fun m => m.insert r stx /-- `getNames mctx` extracts the names of all the local declarations implied by the `MetavarContext` `mctx`. -/ def getNames (mctx : MetavarContext) : List Name := let lcts := mctx.decls.toList.map (MetavarDecl.lctx ∘ Prod.snd) let locDecls := (lcts.map (PersistentArray.toList ∘ LocalContext.decls)).flatten.reduceOption locDecls.map LocalDecl.userName mutual /-- Search for tactic executions in the info tree and remove the syntax of the tactics that changed something. -/ partial def eraseUsedTacticsList (exceptions : Std.HashSet SyntaxNodeKind) (trees : PersistentArray InfoTree) : M Unit := trees.forM (eraseUsedTactics exceptions) /-- Search for tactic executions in the info tree and remove the syntax of the tactics that changed something. -/ partial def eraseUsedTactics (exceptions : Std.HashSet SyntaxNodeKind) : InfoTree → M Unit | .node i c => do if let .ofTacticInfo i := i then let stx := i.stx let kind := stx.getKind if let some r := stx.getRange? true then if exceptions.contains kind -- if the tactic is allowed to not change the goals then modify (·.erase r) else -- if the goals have changed if i.goalsAfter != i.goalsBefore then modify (·.erase r) -- bespoke check for `swap_var`: the only change that it does is -- in the usernames of local declarations, so we check the names before and after else if (kind == `Mathlib.Tactic.«tacticSwap_var__,,») && (getNames i.mctxBefore != getNames i.mctxAfter) then modify (·.erase r) eraseUsedTacticsList exceptions c | .context _ t => eraseUsedTactics exceptions t | .hole _ => pure () end /-- The main entry point to the unused tactic linter. -/ def unusedTacticLinter : Linter where run := withSetOptionIn fun stx => do unless getLinterValue linter.unusedTactic (← getLinterOptions) && (← getInfoState).enabled do return if (← get).messages.hasErrors then return if stx.isOfKind ``Mathlib.Linter.UnusedTactic.«command#show_kind_» then return let env ← getEnv let cats := (Parser.parserExtension.getState env).categories -- These lookups may fail when the linter is run in a fresh, empty environment let some tactics := Parser.ParserCategory.kinds <$> cats.find? `tactic | return let some convs := Parser.ParserCategory.kinds <$> cats.find? `conv | return let trees ← getInfoTrees let exceptions := (← allowedRef.get).union <| allowedUnusedTacticExt.getState env let go : M Unit := do getTactics (← ignoreTacticKindsRef.get) (fun k => tactics.contains k || convs.contains k) stx eraseUsedTacticsList exceptions trees let (_, map) ← go.run {} let unused := map.toArray let key (r : String.Range) := (r.start.byteIdx, (-r.stop.byteIdx : Int)) let mut last : String.Range := ⟨0, 0⟩ for (r, stx) in let _ := @lexOrd; let _ := @ltOfOrd.{0}; unused.qsort (key ·.1 < key ·.1) do if stx.getKind ∈ [``Batteries.Tactic.unreachable, ``Batteries.Tactic.unreachableConv] then continue if last.start ≤ r.start && r.stop ≤ last.stop then continue Linter.logLint linter.unusedTactic stx m!"'{stx}' tactic does nothing" last := r initialize addLinter unusedTacticLinter
sesquilinear.v
From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div. From mathcomp Require Import choice fintype tuple bigop ssralg finset fingroup. From mathcomp Require Import zmodp poly order ssrnum matrix mxalgebra vector. (******************************************************************************) (* Sesquilinear forms *) (* *) (* e_ j := the row matrix with a 1 in column j *) (* M ^ phi := map_mx phi M *) (* Notation in scope sesquilinear_scope. *) (* M ^t phi := (M ^T) ^ phi *) (* Notation in scope sesquilinear_scope. *) (* involutive_rmorphism R == the type of involutive functions *) (* R has type nzRingType. *) (* The HB class is InvolutiveRMorphism. *) (* *) (* {bilinear U -> U' -> V | s & s'} == the type of bilinear forms which are *) (* essentially functions of type U -> U' -> V *) (* U and U' are lmodType's, V is a zmodType, s and *) (* s' are scaling operations of type R -> V -> V. *) (* The HB class is Bilinear. *) (* The factory bilinear_isBilinear provides a way *) (* to instantiate a bilinear form from two *) (* GRing.linear_for proofs. *) (* {bilinear U -> V -> W | s } := {bilinear U -> V -> W | s.1 & s.2} *) (* {bilinear U -> V -> W} := {bilinear U -> V -> W | *:%R & *:%R } *) (* {biscalar U} := {bilinear U -> U -> _ | *%R & *%R } *) (* *) (* applyr f x := f ^~ x with f : U -> U' -> V *) (* form theta M u v == form defined from a matrix M *) (* := (u *m M *m (v ^t theta)) 0 0 *) (* u and v are row vectors, M is a square matrix, *) (* coefficients have type R : fieldType, *) (* theta is a morphism *) (* *) (* {hermitian U for eps & theta} == hermitian/skew-hermitian form *) (* eps is a boolean flag, *) (* (false -> hermitian, true -> skew-hermitian), *) (* theta is a function R -> R (R : nzRingType). *) (* The HB class is Hermitian. *) (* *%R is used as a the first scaling operator. *) (* theta \; *R is used as the second scaling *) (* operation of the bilinear form. *) (* The archetypal case is theta being the complex *) (* conjugate. *) (* *) (* M \is (eps, theta).-sesqui == M is a sesquilinear form *) (* *) (* orthomx theta M B == M-orthogonal complement of B *) (* := kermx (M *m B ^t theta) *) (* M is a square matrix representing a sesquilinear *) (* form, B is a rectangle matrix representing a *) (* subspace *) (* (local notation: B ^_|_) *) (* ortho theta M B == orthomx theta M B with theta a morphism *) (* A '_|_ B := (A%MS <= B^_|_)%MS *) (* This is a local notation. *) (* rad theta M := ortho theta M 1%:M *) (* (local notation: 1%:M^_|_) *) (* *) (* {symmetric U} == symmetric form *) (* := {hermitian U for false & idfun} *) (* {skew_symmetric U} == skew-symmetric form *) (* := {hermitian U for true & idfun} *) (* {hermitian_sym U for theta} := hermitian form using theta (eps = false) *) (* {dot U for theta} == type of positive definite forms *) (* The HB class is Dot. *) (* *) (* is_skew eps theta form := eps = true /\ theta = idfun *) (* is_sym eps theta form := eps = false /\ theta = idfun *) (* is_hermsym eps theta form := eps = false *) (* *) (* ortho_rec s1 s2 := elements of s1 and s2 are pairwise orthogonal *) (* pairwise_orthogonal s == elements of s are pairwise orthogonal and *) (* s does not contain 0 *) (* orthogonal s1 s2 == the inner product of an element of S1 and *) (* an element of S2 is 0 *) (* := ortho_rec s1 s2 *) (* orthonormal s == s is an orthonormal set of unit vectors *) (* *) (* isometry form1 form2 tau == tau is an isometry from form1 to form2 *) (* form1 and form2 are hermitian forms. *) (* {in D, isometry tau, to R} == local notation for now *) (* *) (* orthov (V : {vspace vT}) == the space orthogonal to V *) (* *) (* In the following definitions, we have f : {hermitian vT for eps & theta} *) (* with vT : vectType F (F : fieldType): *) (* nondegenerate f == f is non-degenerated *) (* is_symplectic f == f is a symplectic bilinear form *) (* is_orthogonal f == f is an orthogonal form *) (* is_unitary f == f is a unitary form *) (* *) (* form_of_matrix theta M U V := \tr (U *m M *m (V ^t theta)) *) (* matrix_of_form f := \matrix_(i, j) form 'e_i 'e_j *) (* M \is hermitianmx eps theta == same as M \is (eps, theta).-sesqui *) (* without the constraint that theta is a morphism *) (* *) (* symmetricmx := hermitianmx _ false idfun *) (* skewmx := hermitianmx _ true idfun *) (* hermsymmx := hermitianmx _ false conjC *) (* *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "M ^t phi" (at level 39, left associativity, format "M ^t phi"). Reserved Notation "A ^!" (format "A ^!"). Reserved Notation "A ^_|_" (format "A ^_|_"). Reserved Notation "A ''_|_' B" (at level 69, format "A ''_|_' B"). Reserved Notation "eps_theta .-sesqui" (format "eps_theta .-sesqui"). Local Open Scope ring_scope. Import GRing.Theory Order.Theory Num.Theory. Notation "''e_' j" := (delta_mx 0 j) (format "''e_' j", at level 8, j at level 2) : ring_scope. Declare Scope sesquilinear_scope. Delimit Scope sesquilinear_scope with sesqui. Local Open Scope sesquilinear_scope. Notation "M ^ phi" := (map_mx phi M) : sesquilinear_scope. Notation "M ^t phi" := ((M ^T) ^ phi) : sesquilinear_scope. (* TODO: move? *) Lemma eq_map_mx_id (R : nzRingType) m n (M : 'M[R]_(m, n)) (f : R -> R) : f =1 id -> M ^ f = M. Proof. by move=> /eq_map_mx->; rewrite map_mx_id. Qed. HB.mixin Record isInvolutive (R : nzRingType) (f : R -> R) := { involutive_subproof : involutive f }. (* TODO: move? *) #[short(type="involutive_rmorphism")] HB.structure Definition InvolutiveRMorphism (R : nzRingType) := { f of @GRing.RMorphism R R f & @isInvolutive R f }. Section InvolutiveTheory. Variable R : nzRingType. Let idfunK : involutive (@idfun R). Proof. by []. Qed. HB.instance Definition _ := isInvolutive.Build _ _ idfunK. Lemma rmorphK (f : involutive_rmorphism R) : involutive f. Proof. by move: f => [? [? ? []]]. Qed. End InvolutiveTheory. Definition conjC {C : numClosedFieldType} (c : C) : C := c^*. HB.instance Definition _ (C : numClosedFieldType) := GRing.RMorphism.on (@conjC C). Section conjC_involutive. Variable C : numClosedFieldType. Let conjCfun_involutive : involutive (@conjC C). Proof. exact: conjCK. Qed. HB.instance Definition _ := isInvolutive.Build _ (@conjC C) conjCfun_involutive. End conjC_involutive. Lemma map_mxCK {C : numClosedFieldType} m n (A : 'M[C]_(m, n)) : (A ^ conjC) ^ conjC = A. Proof. by apply/matrixP=> i j; rewrite !mxE conjCK. Qed. (*Structure revop X Y Z (f : Y -> X -> Z) := RevOp { fun_of_revop :> X -> Y -> Z; _ : forall x, f x =1 fun_of_revop^~ x }. Notation "[ 'revop' revop 'of' op ]" := (@RevOp _ _ _ revop op (fun _ _ => erefl)) (format "[ 'revop' revop 'of' op ]") : form_scope.*) HB.mixin Record isBilinear (R : nzRingType) (U U' : lmodType R) (V : zmodType) (s : R -> V -> V) (s' : R -> V -> V) (f : U -> U' -> V) := { zmod_morphisml_subproof : forall u', zmod_morphism (f ^~ u') ; zmod_morphismr_subproof : forall u, zmod_morphism (f u) ; linearl_subproof : forall u', scalable_for s (f ^~ u') ; linearr_subproof : forall u, scalable_for s' (f u) }. #[short(type="bilinear")] HB.structure Definition Bilinear (R : nzRingType) (U U' : lmodType R) (V : zmodType) (s : R -> V -> V) (s' : R -> V -> V) := {f of isBilinear R U U' V s s' f}. Definition bilinear_for (R : nzRingType) (U U' : lmodType R) (V : zmodType) (s : GRing.Scale.law R V) (s' : GRing.Scale.law R V) (f : U -> U' -> V) := ((forall u', GRing.linear_for (s : R -> V -> V) (f ^~ u')) * (forall u, GRing.linear_for s' (f u)))%type. HB.factory Record bilinear_isBilinear (R : nzRingType) (U U' : lmodType R) (V : zmodType) (s : GRing.Scale.law R V) (s' : GRing.Scale.law R V) (f : U -> U' -> V) := { bilinear_subproof : bilinear_for s s' f }. HB.builders Context R U U' V s s' f of bilinear_isBilinear R U U' V s s' f. HB.instance Definition _ := isBilinear.Build R U U' V s s' f (fun u' => zmod_morphism_linear (bilinear_subproof.1 u')) (fun u => zmod_morphism_linear (bilinear_subproof.2 u)) (fun u' => scalable_linear (bilinear_subproof.1 u')) (fun u => scalable_linear (bilinear_subproof.2 u)). HB.end. Module BilinearExports. Module Bilinear. Section bilinear. Variables (R : nzRingType) (U U' : lmodType R) (V : zmodType) (s s' : R -> V -> V). Local Notation bilinear f := (bilinear_for *:%R *:%R f). Local Notation biscalar f := (bilinear_for *%R *%R f). (* Support for right-to-left rewriting with the generic linearZ rule. *) Notation mapUUV := (@Bilinear.type R U U' V s s'). Definition map_class := mapUUV. Definition map_at_left (a : R) := mapUUV. Definition map_at_right (b : R) := mapUUV. Definition map_at_both (a b : R) := mapUUV. Structure map_for_left a s_a := MapForLeft {map_for_left_map : mapUUV; _ : s a = s_a }. Structure map_for_right b s'_b := MapForRight {map_for_right_map : mapUUV; _ : s' b = s'_b }. Structure map_for_both a b s_a s'_b := MapForBoth {map_for_both_map : mapUUV; _ : s a = s_a ; _ : s' b = s'_b }. Definition unify_map_at_left a (f : map_at_left a) := MapForLeft f (erefl (s a)). Definition unify_map_at_right b (f : map_at_right b) := MapForRight f (erefl (s' b)). Definition unify_map_at_both a b (f : map_at_both a b) := MapForBoth f (erefl (s a)) (erefl (s' b)). Structure wrapped := Wrap {unwrap : mapUUV}. Definition wrap (f : map_class) := Wrap f. End bilinear. End Bilinear. Notation "{ 'bilinear' U -> V -> W | s & t }" := (@Bilinear.type _ U%type V%type W%type s t) (U at level 98, V at level 98, W at level 99, format "{ 'bilinear' U -> V -> W | s & t }") : ring_scope. Notation "{ 'bilinear' U -> V -> W | s }" := ({bilinear U -> V -> W | s.1 & s.2}) (U at level 98, V at level 98, W at level 99, format "{ 'bilinear' U -> V -> W | s }") : ring_scope. Notation "{ 'bilinear' U -> V -> W }" := {bilinear U -> V -> W | *:%R & *:%R} (U at level 98, V at level 98, W at level 99, format "{ 'bilinear' U -> V -> W }") : ring_scope. Notation "{ 'biscalar' U }" := {bilinear U%type -> U%type -> _ | *%R & *%R} (format "{ 'biscalar' U }") : ring_scope. End BilinearExports. Export BilinearExports. #[non_forgetful_inheritance] HB.instance Definition _ (R : nzRingType) (U U' : lmodType R) (V : zmodType) (s : R -> V -> V) (s' : R -> V -> V) (f : {bilinear U -> U' -> V | s & s'}) (u : U) := @GRing.isZmodMorphism.Build U' V (f u) (@zmod_morphismr_subproof _ _ _ _ _ _ f u). #[non_forgetful_inheritance] HB.instance Definition _ (R : nzRingType) (U U' : lmodType R) (V : zmodType) (s : R -> V -> V) (s' : R -> V -> V) (f : @bilinear R U U' V s s') (u : U) := @GRing.isScalable.Build _ _ _ _ (f u) (@linearr_subproof _ _ _ _ _ _ f u). Section applyr. Variables (R : nzRingType) (U U' : lmodType R) (V : zmodType) (s s' : R -> V -> V). Definition applyr_head t (f : U -> U' -> V) u v := let: tt := t in f v u. End applyr. Notation applyr := (applyr_head tt). Coercion Bilinear.map_for_left_map : Bilinear.map_for_left >-> Bilinear.type. Coercion Bilinear.map_for_right_map : Bilinear.map_for_right >-> Bilinear.type. Coercion Bilinear.map_for_both_map : Bilinear.map_for_both >-> Bilinear.type. Coercion Bilinear.unify_map_at_left : Bilinear.map_at_left >-> Bilinear.map_for_left. Coercion Bilinear.unify_map_at_right : Bilinear.map_at_right >-> Bilinear.map_for_right. Coercion Bilinear.unify_map_at_both : Bilinear.map_at_both >-> Bilinear.map_for_both. Canonical Bilinear.unify_map_at_left. Canonical Bilinear.unify_map_at_right. Canonical Bilinear.unify_map_at_both. Coercion Bilinear.unwrap : Bilinear.wrapped >-> Bilinear.type. Coercion Bilinear.wrap : Bilinear.map_class >-> Bilinear.wrapped. Canonical Bilinear.wrap. Section BilinearTheory. Variable R : nzRingType. Section GenericProperties. Variables (U U' : lmodType R) (V : zmodType) (s : R -> V -> V) (s' : R -> V -> V). Variable f : {bilinear U -> U' -> V | s & s'}. Section GenericPropertiesr. Variable z : U. Lemma linear0r : f z 0 = 0. Proof. by rewrite raddf0. Qed. Lemma linearNr : {morph f z : x / - x}. Proof. exact: raddfN. Qed. Lemma linearDr : {morph f z : x y / x + y}. Proof. exact: raddfD. Qed. Lemma linearBr : {morph f z : x y / x - y}. Proof. exact: raddfB. Qed. Lemma linearMnr n : {morph f z : x / x *+ n}. Proof. exact: raddfMn. Qed. Lemma linearMNnr n : {morph f z : x / x *- n}. Proof. exact: raddfMNn. Qed. Lemma linear_sumr I r (P : pred I) E : f z (\sum_(i <- r | P i) E i) = \sum_(i <- r | P i) f z (E i). Proof. exact: raddf_sum. Qed. Lemma linearZr_LR : scalable_for s' (f z). Proof. exact: linearZ_LR. Qed. Lemma linearPr a : {morph f z : u v / a *: u + v >-> s' a u + v}. Proof. exact: linearP. Qed. End GenericPropertiesr. Lemma applyrE x : applyr f x =1 f^~ x. Proof. by []. Qed. Section GenericPropertiesl. Variable z : U'. HB.instance Definition _ := GRing.isZmodMorphism.Build _ _ (applyr f z) (@zmod_morphisml_subproof _ _ _ _ _ _ f z). HB.instance Definition _ := GRing.isScalable.Build _ _ _ _ (applyr f z) (@linearl_subproof _ _ _ _ _ _ f z). Lemma linear0l : f 0 z = 0. Proof. by rewrite -applyrE raddf0. Qed. Lemma linearNl : {morph f^~ z : x / - x}. Proof. by move=> ?; rewrite -applyrE raddfN. Qed. Lemma linearDl : {morph f^~ z : x y / x + y}. Proof. by move=> ? ?; rewrite -applyrE raddfD. Qed. Lemma linearBl : {morph f^~ z : x y / x - y}. Proof. by move=> ? ?; rewrite -applyrE raddfB. Qed. Lemma linearMnl n : {morph f^~ z : x / x *+ n}. Proof. by move=> ?; rewrite -applyrE raddfMn. Qed. Lemma linearMNnl n : {morph f^~ z : x / x *- n}. Proof. by move=> ?; rewrite -applyrE raddfMNn. Qed. Lemma linear_sumlz I r (P : pred I) E : f (\sum_(i <- r | P i) E i) z = \sum_(i <- r | P i) f (E i) z. Proof. by rewrite -applyrE raddf_sum. Qed. Lemma linearZl_LR : scalable_for s (f ^~ z). Proof. by move=> ? ?; rewrite -applyrE linearZ_LR. Qed. Lemma linearPl a : {morph f^~ z : u v / a *: u + v >-> s a u + v}. Proof. by move=> ? ?; rewrite -applyrE linearP. Qed. End GenericPropertiesl. End GenericProperties. Section BidirectionalLinearZ. Variables (U U' : lmodType R) (V : zmodType) (s s' : R -> V -> V). Variables (S : nzRingType) (h : GRing.Scale.law S V) (h' : GRing.Scale.law S V). Lemma linearZl z (c : S) (a : R) (h_c := h c) (f : Bilinear.map_for_left U U' s s' a h_c) u : f (a *: u) z = h_c (Bilinear.wrap f u z). Proof. by rewrite linearZl_LR; case: f => f /= ->. Qed. Lemma linearZr z c' b (h'_c' := h' c') (f : Bilinear.map_for_right U U' s s' b h'_c') u : f z (b *: u) = h'_c' (Bilinear.wrap f z u). Proof. by rewrite linearZr_LR; case: f => f /= ->. Qed. Lemma linearZlr c c' a b (h_c := h c) (h'_c' := h' c') (f : Bilinear.map_for_both U U' s s' a b h_c h'_c') u v : f (a *: u) (b *: v) = h_c (h'_c' (Bilinear.wrap f u v)). Proof. by rewrite linearZl_LR linearZ_LR; case: f => f /= -> ->. Qed. Lemma linearZrl c c' a b (h_c := h c) (h'_c' := h' c') (f : Bilinear.map_for_both U U' s s' a b h_c h'_c') u v : f (a *: u) (b *: v) = h'_c' (h_c (Bilinear.wrap f u v)). Proof. by rewrite linearZ_LR/= linearZl_LR; case: f => f /= -> ->. Qed. End BidirectionalLinearZ. End BilinearTheory. (* TODO Canonical rev_mulmx (R : nzRingType) m n p := [revop mulmxr of @mulmx R m n p]. *) (*Canonical mulmx_bilinear (R : comNzRingType) m n p := [bilinear of @mulmx R m n p].*) Lemma mulmx_is_bilinear (R : comNzRingType) m n p : bilinear_for (GRing.Scale.Law.clone _ _ *:%R _) (GRing.Scale.Law.clone _ _ *:%R _) (@mulmx R m n p). Proof. split=> [u'|u] a x y /=. - by rewrite mulmxDl scalemxAl. - by rewrite mulmxDr scalemxAr. Qed. HB.instance Definition _ (R : comNzRingType) m n p := bilinear_isBilinear.Build R [the lmodType R of 'M[R]_(m, n)] [the lmodType R of 'M[R]_(n, p)] [the zmodType of 'M[R]_(m, p)] _ _ (@mulmx R m n p) (mulmx_is_bilinear R m n p). Section BilinearForms. Variables (R : fieldType) (theta : {rmorphism R -> R}). Variables (n : nat) (M : 'M[R]_n). Implicit Types (a b : R) (u v : 'rV[R]_n) (N P Q : 'M[R]_n). Definition form u v := (u *m M *m (v ^t theta)) 0 0. Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u] : ring_scope. Lemma form0l u : '[0, u] = 0. Proof. by rewrite /form !mul0mx mxE. Qed. Lemma form0r u : '[u, 0] = 0. Proof. by rewrite /form trmx0 map_mx0 mulmx0 mxE. Qed. Lemma formDl u v w : '[u + v, w] = '[u, w] + '[v, w]. Proof. by rewrite /form !mulmxDl mxE. Qed. Lemma formDr u v w : '[u, v + w] = '[u, v] + '[u, w]. Proof. by rewrite /form linearD !map_mxD !mulmxDr mxE. Qed. Lemma formZr a u v : '[u, a *: v] = theta a * '[u, v]. Proof. by rewrite /form !(linearZ, map_mxZ) /= mxE. Qed. Lemma formZl a u v : '[a *: u, v] = a * '[u, v]. Proof. by do !rewrite /form -[_ *: _ *m _]/(mulmxr _ _) linearZ /=; rewrite mxE. Qed. Lemma formNl u v : '[- u, v] = - '[u, v]. Proof. by rewrite -scaleN1r formZl mulN1r. Qed. Lemma formNr u v : '[u, - v] = - '[u, v]. Proof. by rewrite -scaleN1r formZr rmorphN1 mulN1r. Qed. Lemma formee i j : '['e_i, 'e_j] = M i j. Proof. rewrite /form -rowE -map_trmx map_delta_mx -[M in LHS]trmxK. by rewrite -tr_col -trmx_mul -rowE !mxE. Qed. Lemma form0_eq0 : M = 0 -> forall u v, '[u, v] = 0. Proof. by rewrite/form=> -> u v; rewrite mulmx0 mul0mx mxE. Qed. End BilinearForms. HB.mixin Record isHermitianSesquilinear (R : nzRingType) (U : lmodType R) (eps : bool) (theta : R -> R) (f : U -> U -> R) := { hermitian_subproof : forall x y : U, f x y = (-1) ^+ eps * theta (f y x) }. HB.structure Definition Hermitian (R : nzRingType) (U : lmodType R) (eps : bool) (theta : R -> R) := {f of @Bilinear R U U _ ( *%R ) (theta \; *%R) f & @isHermitianSesquilinear R U eps theta f}. Notation "{ 'hermitian' U 'for' eps & theta }" := (@Hermitian.type _ U eps theta) (format "{ 'hermitian' U 'for' eps & theta }") : ring_scope. (* duplicate to trick HB *) #[non_forgetful_inheritance] HB.instance Definition _ (R : nzRingType) (U : lmodType R) (eps : bool) (theta : R -> R) (f : {hermitian U for eps & theta}) (u : U) := @GRing.isZmodMorphism.Build _ _ (f u) (@zmod_morphismr_subproof _ _ _ _ _ _ f u). #[non_forgetful_inheritance] HB.instance Definition _ (R : nzRingType) (U : lmodType R) (eps : bool) (theta : R -> R) (f : {hermitian U for eps & theta}) (u : U) := @GRing.isScalable.Build _ _ _ _ (f u) (@linearr_subproof _ _ _ _ _ _ f u). (*Variables (R : nzRingType) (U : lmodType R) (eps : bool) (theta : R -> R). Implicit Types phU : phant U. Local Coercion GRing.Scale.op : GRing.Scale.law >-> Funclass. Definition axiom (f : U -> U -> R) := forall x y : U, f x y = (-1) ^+ eps * theta (f y x). Record class_of (f : U -> U -> R) : Prop := Class { base : Bilinear.class_of ( *%R) (theta \; *%R) f; mixin : axiom f }.*) (*Canonical additiver (u : U) := Additive (base class u). Canonical linearr (u : U) := Linear (base class u). Canonical additivel (u' : U) := @GRing.Additive.Pack _ _ (Phant (U -> R)) (applyr cF u') (Bilinear.basel (base class) u'). Canonical linearl (u' : U) := @GRing.Linear.Pack _ _ _ _ (Phant (U -> R)) (applyr cF u') (Bilinear.basel (base class) u'). Canonical bilinear := @Bilinear.Pack _ _ _ _ _ _ (Phant (U -> U -> R)) cF (base class).*) (*Module Exports. Notation "{ 'hermitian' U 'for' eps & theta }" := (map eps theta (Phant U)) (format "{ 'hermitian' U 'for' eps & theta }") : ring_scope. Coercion base : class_of >-> bilmorphism_for. Coercion apply : map >-> Funclass. Notation "[ 'hermitian' 'of' f 'as' g ]" := (@clone _ _ _ _ _ _ f g _ idfun idfun) (format "[ 'hermitian' 'of' f 'as' g ]") : form_scope. Notation "[ 'hermitian' 'of' f ]" := (@clone _ _ _ _ _ _ f f _ idfun idfun) (format "[ 'hermitian' 'of' f ]") : form_scope. Notation hermitian_for := Hermitian.axiom. Notation Hermitian fM := (pack (Phant _) fM idfun). Canonical additiver. Canonical linearr. Canonical additivel. Canonical linearl. Canonical bilinear. Notation hermapplyr := (@applyr_head _ _ _ _ tt). End Exports. End Hermitian. Include Hermitian.Exports.*) Definition orthomx {R : fieldType} (theta : R -> R) n m M (B : 'M_(m, n)) : 'M_n := kermx (M *m (B ^t theta)). Section Sesquilinear. Variables (R : fieldType) (n : nat). Implicit Types (a b : R) (u v : 'rV[R]_n) (N P Q : 'M[R]_n). Section Def. Variable eps_theta : bool * {rmorphism R -> R}. Definition sesqui := [qualify M : 'M_n | M == ((-1) ^+ eps_theta.1) *: M ^t eps_theta.2]. Fact sesqui_key : pred_key sesqui. Proof. by []. Qed. Canonical sesqui_keyed := KeyedQualifier sesqui_key. End Def. Local Notation "eps_theta .-sesqui" := (sesqui eps_theta). Variables (eps : bool) (theta : {rmorphism R -> R}) (M : 'M[R]_n). Local Notation "''[' u , v ]" := (form theta M u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u] : ring_scope. Lemma sesquiE : (M \is (eps, theta).-sesqui) = (M == (-1) ^+ eps *: M ^t theta). Proof. by rewrite qualifE. Qed. Lemma sesquiP : reflect (M = (-1) ^+ eps *: M ^t theta) (M \is (eps, theta).-sesqui). Proof. by rewrite sesquiE; exact/eqP. Qed. Hypotheses (thetaK : involutive theta) (M_sesqui : M \is (eps, theta).-sesqui). Lemma trmx_sesqui : M^T = (-1) ^+ eps *: M ^ theta. Proof. rewrite [in LHS](sesquiP _) // -mul_scalar_mx trmx_mul. by rewrite tr_scalar_mx mul_mx_scalar map_trmx trmxK. Qed. Lemma maptrmx_sesqui : M^t theta = (-1) ^+ eps *: M. Proof. by rewrite trmx_sesqui map_mxZ rmorph_sign -map_mx_comp eq_map_mx_id. Qed. Lemma formC u v : '[u, v] = (-1) ^+ eps * theta '[v, u]. Proof. rewrite /form [M in LHS](sesquiP _) // -mulmxA !mxE rmorph_sum mulr_sumr. apply: eq_bigr => /= i _; rewrite !(mxE, mulr_sumr, mulr_suml, rmorph_sum). apply: eq_bigr => /= j _; rewrite !mxE !rmorphM mulrCA -!mulrA. by congr (_ * _); rewrite mulrA mulrC /= thetaK. Qed. Lemma form_eq0C u v : ('[u, v] == 0) = ('[v, u] == 0). Proof. by rewrite formC mulf_eq0 signr_eq0 /= fmorph_eq0. Qed. Definition ortho m (B : 'M_(m, n)) := orthomx theta M B. Local Notation "B ^_|_" := (ortho B) : ring_scope. Local Notation "A '_|_ B" := (A%MS <= B^_|_)%MS : ring_scope. Lemma normalE u v : (u '_|_ v) = ('[u, v] == 0). Proof. by rewrite (sameP sub_kermxP eqP) mulmxA [_ *m _^t _]mx11_scalar fmorph_eq0. Qed. Lemma form_eq0P {u v} : reflect ('[u, v] = 0) (u '_|_ v). Proof. by rewrite normalE; apply/eqP. Qed. Lemma normalP p q (A : 'M_(p, n)) (B :'M_(q, n)) : reflect (forall (u v : 'rV_n), (u <= A)%MS -> (v <= B)%MS -> u '_|_ v) (A '_|_ B). Proof. apply: (iffP idP) => AnB. move=> u v uA vB; rewrite (submx_trans uA) // (submx_trans AnB) //. apply/sub_kermxP; have /submxP [w ->] := vB. rewrite trmx_mul map_mxM !mulmxA -[kermx _ *m _ *m _]mulmxA. by rewrite [kermx _ *m _](sub_kermxP _) // mul0mx. apply/rV_subP => u /AnB /(_ _) /sub_kermxP uMv; apply/sub_kermxP. suff: forall m (v : 'rV[R]_m), (forall i, v *m 'e_i ^t theta = 0 :> 'M_1) -> v = 0. apply => i; rewrite !mulmxA -!mulmxA -map_mxM -trmx_mul uMv //. by apply/submxP; exists 'e_i. move=> /= m v Hv; apply: (can_inj (@trmxK _ _ _)). rewrite trmx0; apply/row_matrixP=> i; rewrite row0 rowE. apply: (can_inj (@trmxK _ _ _)); rewrite trmx0 trmx_mul trmxK. by rewrite -(map_delta_mx theta) map_trmx Hv. Qed. Lemma normalC p q (A : 'M_(p, n)) (B : 'M_(q, n)) : (A '_|_ B) = (B '_|_ A). Proof. gen have nC : p q A B / A '_|_ B -> B '_|_ A; last by apply/idP/idP; apply/nC. move=> AnB; apply/normalP => u v ? ?; rewrite normalE. rewrite formC mulf_eq0 ?fmorph_eq0 ?signr_eq0 /=. by rewrite -normalE (normalP _ _ AnB). Qed. Lemma normal_ortho_mx p (A : 'M_(p, n)) : ((A^_|_) '_|_ A). Proof. by []. Qed. Lemma normal_mx_ortho p (A : 'M_(p, n)) : (A '_|_ (A^_|_)). Proof. by rewrite normalC. Qed. Lemma rank_normal u : (\rank (u ^_|_) >= n.-1)%N. Proof. rewrite mxrank_ker -subn1 leq_sub2l //. by rewrite (leq_trans (mxrankM_maxr _ _)) // rank_leq_col. Qed. Definition rad := 1%:M^_|_. Lemma rad_ker : rad = kermx M. Proof. by rewrite /rad /ortho /orthomx trmx1 map_mx1 mulmx1. Qed. (* Pythagoras *) Theorem formDd u v : u '_|_ v -> '[u + v] = '[u] + '[v]. Proof. move=> uNv; rewrite formDl !formDr ['[v, u]]formC. by rewrite ['[u, v]](form_eq0P _) // rmorph0 mulr0 addr0 add0r. Qed. Lemma formZ a u : '[a *: u]= (a * theta a) * '[u]. Proof. by rewrite formZl formZr mulrA. Qed. Lemma formN u : '[- u] = '[u]. Proof. by rewrite formNr formNl opprK. Qed. Lemma form_sign m u : '[(-1) ^+ m *: u] = '[u]. Proof. by rewrite -signr_odd scaler_sign; case: odd; rewrite ?formN. Qed. Lemma formD u v : let d := '[u, v] in '[u + v] = '[u] + '[v] + (d + (-1) ^+ eps * theta d). Proof. by rewrite formDl !formDr ['[v, _]]formC [_ + '[v]]addrC addrACA. Qed. Lemma formB u v : let d := '[u, v] in '[u - v] = '[u] + '[v] - (d + (-1) ^+ eps * theta d). Proof. by rewrite formD formN !formNr rmorphN mulrN -opprD. Qed. Lemma formBd u v : u '_|_ v -> '[u - v] = '[u] + '[v]. Proof. by move=> uTv; rewrite formDd ?formN // normalE formNr oppr_eq0 -normalE. Qed. (* Lemma formJ u v : '[u ^ theta, v ^ theta] = (-1) ^+ eps * theta '[u, v]. *) (* Proof. *) (* rewrite {1}/form -map_trmx -map_mx_comp (@eq_map_mx _ _ _ _ _ id) ?map_mx_id //. *) (* set x := (_ *m _); have -> : x 0 0 = theta ((x^t theta) 0 0) by rewrite !mxE. *) (* rewrite !trmx_mul trmxK map_trmx mulmxA !map_mxM. *) (* rewrite maptrmx_sesqui -!scalemxAr -scalemxAl mxE rmorphM rmorph_sign. *) (* Lemma formJ u : '[u ^ theta] = (-1) ^+ eps * '[u]. *) (* Proof. *) (* rewrite {1}/form -map_trmx -map_mx_comp (@eq_map_mx _ _ _ _ _ id) ?map_mx_id //. *) (* set x := (_ *m _); have -> : x 0 0 = theta ((x^t theta) 0 0) by rewrite !mxE. *) (* rewrite !trmx_mul trmxK map_trmx mulmxA !map_mxM. *) (* rewrite maptrmx_sesqui -!scalemxAr -scalemxAl mxE rmorphM rmorph_sign. *) (* rewrite !map_mxM. *) (* rewrite -map_mx_comp eq_map_mx_id //. *) (* !linearZr_LR /=. linearZ. *) (* linearZl. *) (* rewrite trmx_sesqui. *) (* rewrite mapmx. *) (* rewrite map *) (* apply/matrixP. *) (* rewrite formC. *) (* Proof. by rewrite cfdot_conjC geC0_conj // cfnorm_ge0. Qed. *) (* Lemma cfCauchySchwarz u v : *) (* `|'[u, v]| ^+ 2 <= '[u] * '[v] ?= iff ~~ free (u :: v). *) (* Proof. *) (* rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC. *) (* have [-> | nz_v] /= := altP (v =P 0). *) (* by apply/lerifP; rewrite !cfdot0r normCK mul0r mulr0. *) (* without loss ou: u / '[u, v] = 0. *) (* move=> IHo; pose a := '[u, v] / '[v]; pose u1 := u - a *: v. *) (* have ou: '[u1, v] = 0. *) (* by rewrite cfdotBl cfdotZl divfK ?cfnorm_eq0 ?subrr. *) (* rewrite (canRL (subrK _) (erefl u1)) rpredDr ?rpredZ ?memv_line //. *) (* rewrite cfdotDl ou add0r cfdotZl normrM (ger0_norm (cfnorm_ge0 _)). *) (* rewrite exprMn mulrA -cfnormZ cfnormDd; last by rewrite cfdotZr ou mulr0. *) (* by have:= IHo _ ou; rewrite mulrDl -lerif_subLR subrr ou normCK mul0r. *) (* rewrite ou normCK mul0r; split; first by rewrite mulr_ge0 ?cfnorm_ge0. *) (* rewrite eq_sym mulf_eq0 orbC cfnorm_eq0 (negPf nz_v) /=. *) (* apply/idP/idP=> [|/vlineP[a {2}->]]; last by rewrite cfdotZr ou mulr0. *) (* by rewrite cfnorm_eq0 => /eqP->; apply: rpred0. *) (* Qed. *) End Sesquilinear. Notation "eps_theta .-sesqui" := (sesqui _ eps_theta) : ring_scope. Notation symmetric_form := (false, idfun).-sesqui. Notation skew := (true, idfun).-sesqui. Notation hermitian := (false, @Num.conj_op _).-sesqui. HB.mixin Record isDotProduct (R : numDomainType) (U : lmodType R) (op : U -> U -> R) := { neq0_dnorm_gt0 : forall u, u != 0 -> 0 < op u u }. HB.structure Definition Dot (R : numDomainType) (U : lmodType R) (theta : R -> R) := {op of isDotProduct R U op & @Hermitian R U false theta op}. Notation "{ 'dot' U 'for' theta }" := (@Dot.type _ U theta) (format "{ 'dot' U 'for' theta }") : ring_scope. (* duplicate to trick HB *) #[non_forgetful_inheritance] HB.instance Definition _ (R : numDomainType) (U : lmodType R) (theta : R -> R) (f : {dot U for theta}) (u : U) := @GRing.isZmodMorphism.Build _ _ (f u) (@zmod_morphismr_subproof _ _ _ _ _ _ f u). #[non_forgetful_inheritance] HB.instance Definition _ (R : numDomainType) (U : lmodType R) (theta : R -> R) (f : {dot U for theta}) (u : U) := @GRing.isScalable.Build _ _ _ _ (f u) (@linearr_subproof _ _ _ _ _ _ f u). (*Notation "{ 'dot' U 'for' theta }" := (map theta (Phant U)) (format "{ 'dot' U 'for' theta }") : ring_scope. Coercion base : class_of >-> Hermitian.class_of. Coercion apply : map >-> Funclass. Notation "[ 'dot' 'of' f 'as' g ]" := (@clone _ _ _ _ _ f g _ idfun idfun) (format "[ 'dot' 'of' f 'as' g ]") : form_scope. Notation "[ 'dot' 'of' f ]" := (@clone _ _ _ _ _ f f _ idfun idfun) (format "[ 'dot' 'of' f ]") : form_scope. Notation Dot fM := (pack fM idfun). Notation is_dot := Dot.axiom.*) Notation "{ 'symmetric' U }" := ({hermitian U for false & idfun}) (format "{ 'symmetric' U }") : ring_scope. Notation "{ 'skew_symmetric' U }" := ({hermitian U for true & idfun}) (format "{ 'skew_symmetric' U }") : ring_scope. Notation "{ 'hermitian_sym' U 'for' theta }" := ({hermitian U for false & theta}) (format "{ 'hermitian_sym' U 'for' theta }") : ring_scope. Definition is_skew (R : nzRingType) (eps : bool) (theta : R -> R) (U : lmodType R) (form : {hermitian U for eps & theta}) := (eps = true) /\ (theta =1 id). Definition is_sym (R : nzRingType) (eps : bool) (theta : R -> R) (U : lmodType R) (form : {hermitian U for eps & theta}) := (eps = false) /\ (theta =1 id). Definition is_hermsym (R : nzRingType) (eps : bool) (theta : R -> R) (U : lmodType R) (form : {hermitian U for eps & theta}) := (eps = false). Section HermitianModuleTheory. Variables (R : nzRingType) (eps : bool) (theta : {rmorphism R -> R}). Variables (U : lmodType R) (form : {hermitian U for eps & theta}). Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. Lemma hermC u v : '[u, v] = (-1) ^+ eps * theta '[v, u]. Proof. by move: form => [? [[? ? ? ?] []]] /=. Qed. Lemma hnormN u : '[- u] = '[u]. Proof. by rewrite linearNl linearNr opprK. Qed. Lemma hnorm_sign n u : '[(-1) ^+ n *: u] = '[u]. Proof. by rewrite -signr_odd scaler_sign; case: (odd n); rewrite ?hnormN. Qed. Lemma hnormD u v : let d := '[u, v] in '[u + v] = '[u] + '[v] + (d + (-1) ^+ eps * theta d). Proof. by rewrite /= addrAC -hermC linearDl 2!linearDr !addrA. Qed. Lemma hnormB u v : let d := '[u, v] in '[u - v] = '[u] + '[v] - (d + (-1) ^+ eps * theta d). Proof. by rewrite /= hnormD hnormN linearNr addrA rmorphN mulrN opprD addrA. Qed. Lemma hnormDd u v : '[u, v] = 0 -> '[u + v] = '[u] + '[v]. Proof. by move=> ouv; rewrite hnormD ouv rmorph0 mulr0 !addr0. Qed. Lemma hnormBd u v : '[u, v] = 0 -> '[u - v] = '[u] + '[v]. Proof. by move=> ouv; rewrite hnormDd ?hnormN// linearNr [X in - X]ouv oppr0. Qed. Local Notation "u '_|_ v" := ('[u, v] == 0) : ring_scope. Definition ortho_rec (s1 s2 : seq U) := all [pred u | all [pred v | u '_|_ v] s2] s1. Fixpoint pair_ortho_rec (s : seq U) := if s is v :: s' then ortho_rec [:: v] s' && pair_ortho_rec s' else true. (* We exclude 0 from pairwise orthogonal sets. *) Definition pairwise_orthogonal s := (0 \notin s) && pair_ortho_rec s. Definition orthogonal s1 s2 := (@ortho_rec s1 s2). Arguments orthogonal : simpl never. Lemma orthogonal_cons u us vs : orthogonal (u :: us) vs = orthogonal [:: u] vs && orthogonal us vs. Proof. by rewrite /orthogonal /= andbT. Qed. Definition orthonormal s := all [pred v | '[v] == 1] s && pair_ortho_rec s. Lemma orthonormal_not0 S : orthonormal S -> 0 \notin S. Proof. by case/andP=> /allP S1 _; rewrite (contra (S1 _)) //= linear0r eq_sym oner_eq0. Qed. Lemma orthonormalE S : orthonormal S = all [pred phi | '[phi] == 1] S && pairwise_orthogonal S. Proof. by rewrite -(andb_idl (@orthonormal_not0 S)) andbCA. Qed. Lemma orthonormal_orthogonal S : orthonormal S -> pairwise_orthogonal S. Proof. by rewrite orthonormalE => /andP[_]. Qed. End HermitianModuleTheory. Arguments orthogonal {R eps theta U} form s1 s2. Arguments pairwise_orthogonal {R eps theta U} form s. Arguments orthonormal {R eps theta U} form s. Section HermitianIsometry. Variables (R : nzRingType) (eps : bool) (theta : {rmorphism R -> R}). Variables (U1 U2 : lmodType R) (form1 : {hermitian U1 for eps & theta}) (form2 : {hermitian U2 for eps & theta}). Local Notation "''[' u , v ]_1" := (form1 u%R v%R) : ring_scope. Local Notation "''[' u , v ]_2" := (form2 u%R v%R) : ring_scope. Local Notation "''[' u ]_1" := (form1 u%R u%R) : ring_scope. Local Notation "''[' u ]_2" := (form2 u%R u%R): ring_scope. Definition isometry tau := forall u v, form1 (tau u) (tau v) = form2 u%R v%R. Definition isometry_from_to mD tau mR := prop_in2 mD (inPhantom (isometry tau)) /\ prop_in1 mD (inPhantom (forall u, in_mem (tau u) mR)). Local Notation "{ 'in' D , 'isometry' tau , 'to' R }" := (isometry_from_to (mem D) tau (mem R)) (format "{ 'in' D , 'isometry' tau , 'to' R }") : type_scope. End HermitianIsometry. Section HermitianVectTheory. Variables (R : fieldType) (eps : bool) (theta : {rmorphism R -> R}). Variable (U : lmodType R) (form : {hermitian U for eps & theta}). Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. Lemma herm_eq0C u v : ('[u, v] == 0) = ('[v, u] == 0). Proof. by rewrite hermC mulf_eq0 signr_eq0 /= fmorph_eq0. Qed. End HermitianVectTheory. Section HermitianFinVectTheory. Variables (F : fieldType) (eps : bool) (theta : {rmorphism F -> F}). Variables (vT : vectType F) (form : {hermitian vT for eps & theta}). Let n := \dim {:vT}. Implicit Types (u v : vT) (U V : {vspace vT}). Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. Let alpha v := (linfun (applyr form v : vT -> F^o)). Definition orthov V := (\bigcap_(i < \dim V) lker (alpha (vbasis V)`_i))%VS. Local Notation "U '_|_ V" := (U <= orthov V)%VS : vspace_scope. Lemma mem_orthovPn V u : reflect (exists2 v, v \in V & '[u, v] != 0) (u \notin orthov V). Proof. apply: (iffP idP) => [u_orthovV|[v /coord_vbasis-> uvNorthov]]; last first. apply/subv_bigcapP => uP. rewrite linear_sumr big1 ?eqxx//= in uvNorthov. move=> i _; have := uP i isT. by rewrite -memvE memv_ker lfunE/= linearZr/= => /eqP/= ->; rewrite mulr0. suff /existsP [i ui_neq0] : [exists i : 'I_(\dim V), '[u, (vbasis V)`_i] != 0]. by exists (vbasis V)`_i => //; rewrite vbasis_mem ?mem_nth ?size_tuple. apply: contraNT u_orthovV; rewrite negb_exists => /forallP ui_eq0. apply/subv_bigcapP => i _. by rewrite -memvE memv_ker lfunE /= -[_ == _]negbK. Qed. Lemma mem_orthovP V u : reflect {in V, forall v, '[u, v] = 0} (u \in orthov V). Proof. apply: (iffP idP) => [/mem_orthovPn orthovNu v vV|/(_ _ _)/eqP orthov_u]. by apply/eqP/negP=> /negP Northov_uv; apply: orthovNu; exists v. by apply/mem_orthovPn => -[v /orthov_u->]. Qed. Lemma orthov1E u : orthov <[u]> = lker (alpha u). Proof. apply/eqP; rewrite eqEsubv; apply/andP. split; apply/subvP=> v; rewrite memv_ker lfunE /=. by move=> /mem_orthovP-> //; rewrite ?memv_line. move=> vu_eq0; apply/mem_orthovP => w /vlineP[k->]. by apply/eqP; rewrite linearZ mulf_eq0 vu_eq0 orbT. Qed. Lemma orthovP U V : reflect {in U & V, forall u v, '[u, v] = 0} (U '_|_ V)%VS. Proof. apply: (iffP subvP); last by move=> H ??; apply/mem_orthovP=> ??; apply: H. by move=> /(_ _ _)/mem_orthovP; move=> H ????; apply: H. Qed. Lemma orthov_sym U V : (U '_|_ V)%VS = (V '_|_ U)%VS. Proof. by apply/orthovP/orthovP => eq0 ????; apply/eqP; rewrite herm_eq0C eq0. Qed. Lemma mem_orthov1 v u : (u \in orthov <[v]>) = ('[u, v] == 0). Proof. by rewrite orthov1E memv_ker lfunE. Qed. Lemma orthov11 u v : (<[u]> '_|_ <[v]>)%VS = ('[u, v] == 0). Proof. exact: mem_orthov1. Qed. Lemma mem_orthov1_sym v u : (u \in orthov <[v]>) = (v \in orthov <[u]>). Proof. exact: orthov_sym. Qed. Lemma orthov0 : orthov 0 = fullv. Proof. apply/eqP; rewrite eqEsubv subvf. apply/subvP => x _; rewrite mem_orthov1. by rewrite linear0r. Qed. Lemma mem_orthov_sym V u : (u \in orthov V) = (V <= orthov <[u]>)%VS. Proof. exact: orthov_sym. Qed. Lemma leq_dim_orthov1 u V : ((\dim V).-1 <= \dim (V :&: orthov <[u]>))%N. Proof. rewrite -(limg_ker_dim (alpha u) V) -orthov1E. have := dimvS (subvf (alpha u @: V)); rewrite dimvf addnC. by case: (\dim _) => [|[]] // _; rewrite leq_pred. Qed. Lemma dim_img_form_eq1 u V : u \notin orthov V -> \dim (alpha u @: V)%VS = 1%N. Proof. move=> /mem_orthovPn [v vV Northov_uv]; apply/eqP; rewrite eqn_leq /=. rewrite -[1%N as X in (_ <= X)%N](dimvf [the vectType F of F^o]) dimvS ?subvf//=. have := @dimvS _ _ <['[v, u] : F^o]> (alpha u @: V). rewrite -memvE dim_vline herm_eq0C Northov_uv; apply. by apply/memv_imgP; exists v; rewrite ?memvf// !lfunE /=. Qed. Lemma eq_dim_orthov1 u V : u \notin orthov V -> (\dim V).-1 = \dim (V :&: orthov <[u]>). Proof. rewrite -(limg_ker_dim (alpha u) V) => /dim_img_form_eq1->. by rewrite -orthov1E addn1. Qed. Lemma dim_img_form_eq0 u V : u \in orthov V -> \dim (alpha u @: V)%VS = 0%N. Proof. by move=> uV; apply/eqP; rewrite dimv_eq0 -lkerE -orthov1E orthov_sym. Qed. Lemma neq_dim_orthov1 u V : (\dim V > 0)%N -> u \in orthov V -> ((\dim V).-1 < \dim (V :&: orthov <[u]>))%N. Proof. move=> V_gt0; rewrite -(limg_ker_dim (alpha u) V) -orthov1E => u_in. rewrite dim_img_form_eq0 // addn0 (capv_idPl _) 1?orthov_sym //. by case: (\dim _) V_gt0. Qed. Lemma leqif_dim_orthov1 u V : (\dim V > 0)%N -> ((\dim V).-1 <= \dim (V :&: orthov <[u]>) ?= iff (u \notin orthov V))%N. Proof. move=> Vr_gt0; apply/leqifP. by case: (boolP (u \in _)) => /= [/neq_dim_orthov1->|/eq_dim_orthov1->]. Qed. Lemma leqif_dim_orthov1_full u : (n > 0)%N -> ((\dim {:vT}).-1 <= \dim (orthov <[u]>) ?= iff (u \notin orthov fullv))%N. Proof. by move=> n_gt0; have := @leqif_dim_orthov1 u fullv; rewrite capfv; apply. Qed. (* Link between orthov and orthovgonality of sequences *) Lemma orthogonal1P u v : reflect ('[u, v] = 0) (orthogonal form [:: u] [:: v]). Proof. by rewrite /orthogonal /= !andbT; apply: eqP. Qed. Lemma orthogonalP us vs : reflect {in us & vs, forall u v, '[u, v] = 0} (orthogonal form us vs). Proof. apply: (iffP allP) => ousvs u => [v /ousvs/allP opus /opus/eqP // | /ousvs opus]. by apply/allP=> v /= /opus->. Qed. Lemma orthogonal_oppr S R : orthogonal form S (map -%R R) = orthogonal form S R. Proof. wlog suffices IH: S R / orthogonal form S R -> orthogonal form S (map -%R R). by apply/idP/idP=> /IH; rewrite ?mapK //; apply: opprK. move/orthogonalP=> oSR; apply/orthogonalP=> xi1 _ Sxi1 /mapP[xi2 Rxi2 ->]. by rewrite linearNr /= oSR ?oppr0. Qed. Lemma orthogonalE us vs : (orthogonal form us vs) = (<<us>> '_|_ <<vs>>)%VS. Proof. apply/orthogonalP/orthovP => uvsP u v; last first. by move=> uus vvs; rewrite uvsP // memv_span. rewrite -[us]in_tupleE -[vs]in_tupleE => /coord_span-> /coord_span->. rewrite linear_sumr big1 //= => i _. rewrite linear_sumlz big1 //= => j _. by rewrite linearZlr/= uvsP ?mulr0// mem_nth. Qed. Lemma orthovE U V : (U '_|_ V)%VS = orthogonal form (vbasis U) (vbasis V). Proof. by rewrite orthogonalE !(span_basis (vbasisP _)). Qed. Notation radv := (orthov fullv). Lemma orthoDv U V W : (U + V '_|_ W)%VS = (U '_|_ W)%VS && (V '_|_ W)%VS. Proof. by rewrite subv_add. Qed. Lemma orthovD U V W : (U '_|_ V + W)%VS = (U '_|_ V)%VS && (U '_|_ W)%VS. Proof. by rewrite ![(U '_|_ _)%VS]orthov_sym orthoDv. Qed. Definition nondegenerate := radv == 0%VS. Definition is_psymplectic := [/\ nondegenerate, is_skew form & 2 \in [pchar F] -> forall u, '[u, u] = 0]. Definition is_porthogonal := [/\ nondegenerate, is_sym form & 2 \in [pchar F] -> forall u, '[u, u] = 0]. Definition is_unitary := nondegenerate /\ (is_hermsym form). End HermitianFinVectTheory. #[deprecated(since="mathcomp 2.4.0", note="Use is_psymplectic instead.")] Notation is_symplectic := is_psymplectic (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use is_porthogonal instead.")] Notation is_orthogonal := is_porthogonal (only parsing). Arguments orthogonalP {F eps theta vT form us vs}. Arguments orthovP {F eps theta vT form U V}. Arguments mem_orthovPn {F eps theta vT form V u}. Arguments mem_orthovP {F eps theta vT form V u}. Section DotVectTheory. Variables (C : numClosedFieldType). Variable (U : lmodType C) (form : {dot U for conjC}). Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. Lemma dnorm_geiff0 u : 0 <= '[u] ?= iff (u == 0). Proof. by apply/leifP; have [->|uN0] := altP eqP; rewrite ?linear0r ?neq0_dnorm_gt0. Qed. Lemma dnorm_ge0 u : 0 <= '[u]. Proof. by rewrite dnorm_geiff0. Qed. Lemma dnorm_eq0 u : ('[u] == 0) = (u == 0). Proof. by rewrite -dnorm_geiff0 eq_sym. Qed. Lemma dnorm_gt0 u : (0 < '[u]) = (u != 0). Proof. by rewrite lt_def dnorm_eq0 dnorm_ge0 andbT. Qed. Lemma sqrt_dnorm_ge0 u : 0 <= sqrtC '[u]. Proof. by rewrite sqrtC_ge0 dnorm_ge0. Qed. Lemma sqrt_dnorm_eq0 u : (sqrtC '[u] == 0) = (u == 0). Proof. by rewrite sqrtC_eq0 dnorm_eq0. Qed. Lemma sqrt_dnorm_gt0 u : (sqrtC '[u] > 0) = (u != 0). Proof. by rewrite sqrtC_gt0 dnorm_gt0. Qed. Lemma dnormZ a u : '[a *: u]= `|a| ^+ 2 * '[u]. Proof. by rewrite linearZl_LR linearZr_LR/= mulrA normCK. Qed. Lemma dnormD u v : let d := '[u, v] in '[u + v] = '[u] + '[v] + (d + d^*). Proof. by rewrite hnormD mul1r. Qed. Lemma dnormB u v : let d := '[u, v] in '[u - v] = '[u] + '[v] - (d + d^*). Proof. by rewrite hnormB mul1r. Qed. End DotVectTheory. #[global] Hint Extern 0 (is_true (0 <= Dot.sort _ _ _ (* NB: This Hint is assuming ^*, a more precise pattern would be welcome *))) => apply: dnorm_ge0 : core. Section HermitianTheory. Variables (C : numClosedFieldType) (eps : bool) (theta : {rmorphism C -> C}). Variable (U : lmodType C) (form : {dot U for conjC}). Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. Lemma pairwise_orthogonalP S : reflect (uniq (0 :: S) /\ {in S &, forall phi psi, phi != psi -> '[phi, psi] = 0}) (pairwise_orthogonal form S). Proof. rewrite /pairwise_orthogonal /=; case notS0: (~~ _); last by right; case. elim: S notS0 => [|phi S IH] /=; first by left. rewrite inE eq_sym andbT => /norP[nz_phi {}/IH IH]. have [opS | not_opS] := allP; last first. right=> [[/andP[notSp _] opS]]; case: not_opS => psi Spsi /=. by rewrite opS ?mem_head 1?mem_behead // (memPnC notSp). rewrite (contra (opS _)) /= ?dnorm_eq0 //. apply: (iffP IH) => [] [uniqS oSS]; last first. by split=> //; apply: sub_in2 oSS => psi Spsi; apply: mem_behead. split=> // psi xi; rewrite !inE => /predU1P[-> // | Spsi]. by case/predU1P=> [-> | /opS] /eqP. case/predU1P=> [-> _ | Sxi /oSS-> //]. apply/eqP; rewrite hermC. by move: (opS psi Spsi) => /= /eqP ->; rewrite rmorph0 mulr0. Qed. Lemma pairwise_orthogonal_cat R S : pairwise_orthogonal form (R ++ S) = [&& pairwise_orthogonal form R, pairwise_orthogonal form S & orthogonal form R S]. Proof. rewrite /pairwise_orthogonal mem_cat negb_or -!andbA; do !bool_congr. elim: R => [|phi R /= ->]; rewrite ?andbT// all_cat -!andbA /=. by do !bool_congr. Qed. Lemma orthonormal_cat R S : orthonormal form (R ++ S) = [&& orthonormal form R, orthonormal form S & orthogonal form R S]. Proof. rewrite !orthonormalE pairwise_orthogonal_cat all_cat -!andbA. by do !bool_congr. Qed. Lemma orthonormalP S : reflect (uniq S /\ {in S &, forall phi psi, '[phi, psi] = (phi == psi)%:R}) (orthonormal form S). Proof. rewrite orthonormalE; have [/= normS | not_normS] := allP; last first. by right=> [[_ o1S]]; case: not_normS => phi Sphi; rewrite /= o1S ?eqxx. apply: (iffP (pairwise_orthogonalP S)) => [] [uniqS oSS]. split=> // [|phi psi]; first by case/andP: uniqS. by have [-> _ /normS/eqP | /oSS] := altP eqP. split=> // [|phi psi Sphi Spsi /negbTE]; last by rewrite oSS // => ->. by rewrite /= (contra (normS _)) // linear0r eq_sym oner_eq0. Qed. Lemma sub_orthonormal S1 S2 : {subset S1 <= S2} -> uniq S1 -> orthonormal form S2 -> orthonormal form S1. Proof. move=> sS12 uniqS1 /orthonormalP[_ oS1]. by apply/orthonormalP; split; last apply: sub_in2 sS12 _ _. Qed. Lemma orthonormal2P phi psi : reflect [/\ '[phi, psi] = 0, '[phi] = 1 & '[psi] = 1] (orthonormal form [:: phi; psi]). Proof. rewrite /orthonormal /= !andbT andbC. by apply: (iffP and3P) => [] []; do 3!move/eqP->. Qed. End HermitianTheory. Section DotFinVectTheory. Variable C : numClosedFieldType. Variables (U : vectType C) (form : {dot U for conjC}). Local Notation "''[' u , v ]" := (form u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. Lemma sub_pairwise_orthogonal S1 S2 : {subset S1 <= S2} -> uniq S1 -> pairwise_orthogonal form S2 -> pairwise_orthogonal form S1. Proof. move=> sS12 uniqS1 /pairwise_orthogonalP[/andP[notS2_0 _] oS2]. apply/pairwise_orthogonalP; rewrite /= (contra (sS12 0)) //. by split=> //; apply: sub_in2 oS2. Qed. Lemma orthogonal_free S : pairwise_orthogonal form S -> free S. Proof. case/pairwise_orthogonalP=> [/=/andP[notS0 uniqS] oSS]. rewrite -(in_tupleE S); apply/freeP => a aS0 i. have S_i: S`_i \in S by apply: mem_nth. have /eqP: '[S`_i, 0] = 0 := linear0r _ _. rewrite -{2}aS0 raddf_sum /= (bigD1 i) //= big1 => [|j neq_ji]; last 1 first. by rewrite linearZ /= oSS ?mulr0 ?mem_nth // eq_sym nth_uniq. rewrite addr0 linearZ mulf_eq0 conjC_eq0 dnorm_eq0. by case/pred2P=> // Si0; rewrite -Si0 S_i in notS0. Qed. Lemma filter_pairwise_orthogonal S p : pairwise_orthogonal form S -> pairwise_orthogonal form (filter p S). Proof. move=> orthoS; apply: sub_pairwise_orthogonal (orthoS). exact: mem_subseq (filter_subseq p S). exact/filter_uniq/free_uniq/orthogonal_free. Qed. Lemma orthonormal_free S : orthonormal form S -> free S. Proof. by move/orthonormal_orthogonal/orthogonal_free. Qed. Theorem CauchySchwarz (u v : U) : `|'[u, v]| ^+ 2 <= '[u] * '[v] ?= iff ~~ free [:: u; v]. Proof. rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC. have [-> | nz_v] /= := altP (v =P 0). by apply/leifP; rewrite /= !linear0r normCK mul0r mulr0. without loss ou: u / '[u, v] = 0. move=> IHo; pose a := '[u, v] / '[v]; pose u1 := u - a *: v. have ou: '[u1, v] = 0. rewrite linearBl/=. rewrite linearZl_LR. by rewrite divfK ?dnorm_eq0 ?subrr. rewrite (canRL (subrK _) (erefl u1)) rpredDr ?rpredZ ?memv_line //. rewrite linearDl /= ou add0r. rewrite linearZl_LR/= normrM (ger0_norm (dnorm_ge0 _ _)). rewrite exprMn mulrA -dnormZ hnormDd/=; last by rewrite linearZr_LR/= ou mulr0. have:= IHo _ ou. by rewrite mulrDl -leifBLR subrr ou normCK mul0r. rewrite ou normCK mul0r; split; first by rewrite mulr_ge0. rewrite eq_sym mulf_eq0 orbC dnorm_eq0 (negPf nz_v) /=. apply/idP/idP=> [|/vlineP[a {2}->]]; last by rewrite linearZr_LR/= ou mulr0. by rewrite dnorm_eq0 => /eqP->; apply: rpred0. Qed. Lemma CauchySchwarz_sqrt u v : `|'[u, v]| <= sqrtC '[u] * sqrtC '[v] ?= iff ~~ free [:: u; v]. Proof. rewrite -(sqrCK (normr_ge0 _)) -sqrtCM ?nnegrE//. rewrite (mono_in_leif (@ler_sqrtC _)) 1?rpredM//= ?nnegrE//=. exact: CauchySchwarz. Qed. Lemma orthoP phi psi : reflect ('[phi, psi] = 0) (orthogonal form [:: phi] [:: psi]). Proof. by rewrite /orthogonal /= !andbT; apply: eqP. Qed. Lemma orthoPl phi S : reflect {in S, forall psi, '[phi, psi] = 0} (orthogonal form [:: phi] S). Proof. by rewrite [orthogonal form _ S]andbT /=; apply: (iffP allP) => ophiS ? /ophiS/eqP. Qed. Arguments orthoPl {phi S}. Lemma orthogonal_sym : symmetric (orthogonal form). Proof. apply: symmetric_from_pre => R S /orthogonalP oRS. by apply/orthogonalP=> phi psi Rpsi Sphi; rewrite hermC /= oRS ?rmorph0 ?mulr0. Qed. Lemma orthoPr S psi : reflect {in S, forall phi, '[phi, psi] = 0} (orthogonal form S [:: psi]). Proof. rewrite orthogonal_sym. by apply: (iffP orthoPl) => oSpsi phi Sphi; rewrite hermC /= oSpsi //= conjC0 mulr0. Qed. Lemma orthogonal_catl R1 R2 S : orthogonal form (R1 ++ R2) S = orthogonal form R1 S && orthogonal form R2 S. Proof. exact: all_cat. Qed. Lemma orthogonal_catr R S1 S2 : orthogonal form R (S1 ++ S2) = orthogonal form R S1 && orthogonal form R S2. Proof. by rewrite !(orthogonal_sym R) orthogonal_catl. Qed. Lemma eq_pairwise_orthogonal R S : perm_eq R S -> pairwise_orthogonal form R = pairwise_orthogonal form S. Proof. apply: catCA_perm_subst R S => R S S'. rewrite !pairwise_orthogonal_cat !orthogonal_catr (orthogonal_sym R S) -!andbA. by do !bool_congr. Qed. Lemma eq_orthonormal S0 S : perm_eq S0 S -> orthonormal form S0 = orthonormal form S. Proof. move=> eqRS; rewrite !orthonormalE (eq_all_r (perm_mem eqRS)). by rewrite (eq_pairwise_orthogonal eqRS). Qed. Lemma orthogonal_oppl S R : orthogonal form (map -%R S) R = orthogonal form S R. Proof. by rewrite -!(orthogonal_sym R) orthogonal_oppr. Qed. Lemma triangle_lerif u v : sqrtC '[u + v] <= sqrtC '[u] + sqrtC '[v] ?= iff ~~ free [:: u; v] && (0 <= coord [tuple v] 0 u). Proof. rewrite -(mono_in_leif ler_sqr) ?rpredD ?nnegrE ?sqrtC_ge0//. rewrite andbC sqrrD !sqrtCK addrAC dnormD (mono_leif (lerD2l _))/=. rewrite -mulr_natr -[_ + _](divfK (negbT (pnatr_eq0 C 2))) -/('Re _). rewrite (mono_leif (ler_pM2r _)) ?ltr0n//. have := leif_trans (leif_Re_Creal '[u, v]) (CauchySchwarz_sqrt u v). rewrite ReE; congr (_ <= _ ?= iff _); apply: andb_id2r. rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC. have [-> | nz_v] := altP (v =P 0); first by rewrite linear0 coord0. case/vlineP=> [x ->]; rewrite linearZl linearZ/= pmulr_lge0 ?dnorm_gt0 //=. by rewrite (coord_free 0) ?seq1_free // eqxx mulr1. Qed. Lemma span_orthogonal S1 S2 phi1 phi2 : orthogonal form S1 S2 -> phi1 \in <<S1>>%VS -> phi2 \in <<S2>>%VS -> '[phi1, phi2] = 0. Proof. move/orthogonalP=> oS12; do 2!move/(@coord_span _ _ _ (in_tuple _))->. rewrite linear_sumlz big1 // => i _; rewrite linear_sumr big1 // => j _. by rewrite linearZlr/= oS12 ?mem_nth ?mulr0. Qed. Lemma orthogonal_split S beta : {X : U & X \in <<S>>%VS & {Y :U | [/\ beta = X + Y, '[X, Y] = 0 & orthogonal form [:: Y] S]}}. Proof. suffices [X S_X [Y -> oYS]]: {X : _ & X \in <<S>>%VS & {Y | beta = X + Y & orthogonal form [:: Y] S}}. - exists X => //; exists Y. by rewrite hermC /= (span_orthogonal oYS) ?memv_span1 ?conjC0 // mulr0. elim: S beta => [|phi S IHS] beta. by exists 0; last exists beta; rewrite ?mem0v ?add0r. have [[UU S_U [V -> oVS]] [X S_X [Y -> oYS]]] := (IHS phi, IHS beta). pose Z := '[Y, V] / '[V] *: V; exists (X + Z). rewrite /Z -{4}(addKr UU V) scalerDr scalerN addrA addrC span_cons. by rewrite memv_add ?memvB ?memvZ ?memv_line. exists (Y - Z); first by rewrite addrCA !addrA addrK addrC. apply/orthoPl=> psi; rewrite !inE => /predU1P[-> | Spsi]; last first. by rewrite linearBl linearZl_LR /= (orthoPl oVS _ Spsi) mulr0 subr0 (orthoPl oYS). rewrite linearBl !linearDr /= (span_orthogonal oYS) // ?memv_span ?mem_head //. rewrite !linearZl_LR /= (span_orthogonal oVS _ S_U) ?mulr0 ?memv_span ?mem_head //. have [-> | nzV] := eqVneq V 0; first by rewrite linear0r !mul0r subrr. by rewrite divfK ?dnorm_eq0 ?subrr. Qed. End DotFinVectTheory. Arguments orthoP {C U form phi psi}. Arguments pairwise_orthogonalP {C U form S}. Arguments orthonormalP {C U form S}. Arguments orthoPl {C U form phi S}. Arguments orthoPr {C U form S psi}. Section BuildIsometries. Variables (C : numClosedFieldType) (U U1 U2 : vectType C). Variables (form : {dot U for conjC}) (form1 : {dot U1 for conjC}) (form2 : {dot U2 for conjC}). Definition normf1 := fun u => form1 u u. Definition normf2 := fun u => form2 u u. Lemma isometry_of_dnorm S tauS : pairwise_orthogonal form1 S -> pairwise_orthogonal form2 tauS -> map normf2 tauS = map normf1 S -> {tau : {linear U1 -> U2} | map tau S = tauS & {in <<S>>%VS &, isometry form2 form1 tau}}. Proof. move=> oS oT eq_nST; have freeS := orthogonal_free oS. have eq_sz: size tauS = size S by have:= congr1 size eq_nST; rewrite !size_map. have [tau defT] := linear_of_free S tauS; rewrite -[S]/(tval (in_tuple S)). exists tau => [|u v /coord_span-> /coord_span->]; rewrite ?raddf_sum ?defT //=. apply: eq_bigr => i _ /=; rewrite !linearZ/= !linear_sumlz; congr (_ * _). apply: eq_bigr => j _ /=; rewrite linearZ !linearZl; congr (_ * _). rewrite -!(nth_map 0 0 tau) ?{}defT //; have [-> | neq_ji] := eqVneq j i. by rewrite /= -[RHS](nth_map 0 0 normf1) -?[LHS](nth_map 0 0 normf2) ?eq_sz // eq_nST. have{oS} [/=/andP[_ uS] oS] := pairwise_orthogonalP oS. have{oT} [/=/andP[_ uT] oT] := pairwise_orthogonalP oT. by rewrite oS ?oT ?mem_nth ?nth_uniq ?eq_sz. Qed. Lemma isometry_of_free S f : free S -> {in S &, isometry form2 form1 f} -> {tau : {linear U1 -> U2} | {in S, tau =1 f} & {in <<S>>%VS &, isometry form2 form1 tau}}. Proof. move=> freeS If; have defS := free_span freeS. have [tau /(_ freeS (size_map f S))Dtau] := linear_of_free S (map f S). have {}Dtau: {in S, tau =1 f}. by move=> _ /(nthP 0)[i ltiS <-]; rewrite -!(nth_map 0 0) ?Dtau. exists tau => // _ _ /defS[a -> _] /defS[b -> _] /=. rewrite 2!{1}linear_sum /= !{1}linear_sumlz /=; apply/eq_big_seq=> xi1 Sxi1. rewrite !{1}linear_sumr; apply/eq_big_seq=> xi2 Sxi2 /=. by rewrite !linearZ /= !linearZl !Dtau //= If. Qed. Lemma isometry_raddf_inj (tau : {additive U1 -> U2}) : {in U1 &, isometry form2 form1 tau} -> {in U1 &, forall u v, u - v \in U1} -> {in U1 &, injective tau}. Proof. move=> Itau linU phi psi Uphi Upsi /eqP; rewrite -subr_eq0 -raddfB. by rewrite -(dnorm_eq0 form2) Itau ?linU // dnorm_eq0 subr_eq0 => /eqP. Qed. End BuildIsometries. Section MatrixForms. Variables (R : fieldType) (n : nat). Implicit Types (a b : R) (u v : 'rV[R]_n) (M N P Q : 'M[R]_n). Section Def. Variable theta : R -> R. Definition form_of_matrix m M (U V : 'M_(m, n)) := \tr (U *m M *m (V ^t theta)). Definition matrix_of_form (form : 'rV[R]_n -> 'rV[R]_n -> R) : 'M[R]_n := \matrix_(i, j) form 'e_i 'e_j. Implicit Type form : {bilinear 'rV[R]_n -> 'rV[R]_n -> R | *%R & theta \; *%R}. Lemma matrix_of_formE form i j : matrix_of_form form i j = form 'e_i 'e_j. Proof. by rewrite mxE. Qed. End Def. Section FormOfMatrix. Variables (m : nat) (M : 'M[R]_n). Implicit Types (U V : 'M[R]_(m, n)). Variables (theta : {rmorphism R -> R}). Local Notation "''[' U , V ]" := (form_of_matrix theta M U%R V%R) : ring_scope. Local Notation "''[' U ]" := '[U, U]%R : ring_scope. Let form_of_matrix_is_linear U : linear_for (theta \; *%R) (form_of_matrix theta M U). Proof. rewrite /form_of_matrix => k v w; rewrite -linearP/=. by rewrite linearP map_mxD map_mxZ !mulmxDr !scalemxAr. Qed. HB.instance Definition _ U := @GRing.isLinear.Build _ _ _ _ (form_of_matrix theta M U) (form_of_matrix_is_linear U). Definition form_of_matrixr U := (form_of_matrix theta M)^~U. Let form_of_matrixr_is_linear U : linear_for *%R (form_of_matrixr U). Proof. rewrite /form_of_matrixr /form_of_matrix => k v w. by rewrite -linearP /= !mulmxDl -!scalemxAl. Qed. HB.instance Definition _ U := @GRing.isLinear.Build _ _ _ _ (form_of_matrixr U) (form_of_matrixr_is_linear U). (* TODO Canonical form_of_matrixr_rev := [revop form_of_matrixr of form_of_matrix theta M]. *) Lemma form_of_matrix_is_bilinear : bilinear_for (GRing.Scale.Law.clone _ _ ( *%R ) _) (GRing.Scale.Law.clone _ _ (theta \; *%R ) _) (@form_of_matrix theta m M). Proof. split=> [u'|u] a x y /=. - by rewrite /form_of_matrix !mulmxDl linearD/= -!scalemxAl linearZ. - rewrite /form_of_matrix -linearZ/= -linearD/= [in LHS]linearD/= map_mxD. rewrite mulmxDr; congr (\tr (_ + _)). rewrite scalemxAr; congr (_ *m _). by rewrite linearZ/= map_mxZ. Qed. HB.instance Definition _ := bilinear_isBilinear.Build R _ _ _ (GRing.Scale.Law.clone _ _ ( *%R ) _) (GRing.Scale.Law.clone _ _ (theta \; *%R ) _) (@form_of_matrix theta m M) form_of_matrix_is_bilinear. (*Canonical form_of_matrix_is_bilinear := [the @bilinear _ _ _ _ of form_of_matrix theta M].*) End FormOfMatrix. Section FormOfMatrix1. Variables (M : 'M[R]_n). Variables (theta : {rmorphism R -> R}). Local Notation "''[' u , v ]" := (form_of_matrix theta M u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. Lemma rV_formee i j : '['e_i :'rV__, 'e_j] = M i j. Proof. rewrite /form_of_matrix -rowE -map_trmx map_delta_mx -[M in LHS]trmxK. by rewrite -tr_col -trmx_mul -rowE trace_mx11 !mxE. Qed. Lemma form_of_matrixK : matrix_of_form (form_of_matrix theta M) = M. Proof. by apply/matrixP => i j; rewrite !mxE rV_formee. Qed. Lemma rV_form0_eq0 : M = 0 -> forall u v, '[u, v] = 0. Proof. by rewrite /form_of_matrix => -> u v; rewrite mulmx0 mul0mx trace_mx11 mxE. Qed. End FormOfMatrix1. Section MatrixOfForm. Variable (theta : {rmorphism R -> R}). Variable form : {bilinear 'rV[R]_n -> 'rV[R]_n -> R | *%R & theta \; *%R}. Lemma matrix_of_formK : form_of_matrix theta (matrix_of_form form) =2 form. Proof. set f := (X in X =2 _); have f_eq i j : f 'e_i 'e_j = form 'e_i 'e_j. by rewrite /f rV_formee mxE. move=> u v; rewrite [u]row_sum_delta [v]row_sum_delta /f. rewrite !linear_sum/=; apply: eq_bigr => j _. rewrite !linear_sumlz/=; apply: eq_bigr => i _. by rewrite !linearZlr/= -f_eq. Qed. End MatrixOfForm. Section HermitianMx. Variable eps : bool. Section HermitianMxDef. Variable theta : R -> R. Definition hermitianmx := [qualify M : 'M_n | M == ((-1) ^+ eps) *: M ^t theta]. Fact hermitianmx_key : pred_key hermitianmx. Proof. by []. Qed. Canonical hermitianmx_keyed := KeyedQualifier hermitianmx_key. Structure hermitian_matrix := HermitianMx { mx_of_hermitian :> 'M[R]_n; _ : mx_of_hermitian \is hermitianmx }. Lemma is_hermitianmxE M : (M \is hermitianmx) = (M == (-1) ^+ eps *: M ^t theta). Proof. by rewrite qualifE. Qed. Lemma is_hermitianmxP M : reflect (M = (-1) ^+ eps *: M ^t theta) (M \is hermitianmx). Proof. by rewrite is_hermitianmxE; apply/eqP. Qed. Lemma hermitianmxE (M : hermitian_matrix) : M = ((-1) ^+ eps) *: M ^t theta :> 'M__. Proof. by apply/eqP; case: M. Qed. Lemma trmx_hermitian (M : hermitian_matrix) : M^T = ((-1) ^+ eps) *: M ^ theta :> 'M__. Proof. by rewrite {1}hermitianmxE linearZ /= map_trmx trmxK. Qed. End HermitianMxDef. Section HermitianMxTheory. Variables (theta : involutive_rmorphism R) (M : hermitian_matrix theta). Lemma maptrmx_hermitian : M^t theta = (-1) ^+ eps *: (M : 'M__). Proof. rewrite trmx_hermitian map_mxZ rmorph_sign -map_mx_comp. by rewrite (map_mx_id (rmorphK _)). Qed. Lemma form_of_matrix_is_hermitian m x y : (@form_of_matrix theta m M) x y = (-1) ^+ eps * theta ((@form_of_matrix theta m M) y x). Proof. rewrite {1}hermitianmxE /form_of_matrix. rewrite -!(scalemxAr, scalemxAl) linearZ/=; congr (_ * _). rewrite -mxtrace_tr -trace_map_mx !(trmx_mul, map_mxM, map_trmx, trmxK). by rewrite -mulmxA -!map_mx_comp !(map_mx_id (rmorphK _)). Qed. HB.instance Definition _ m := @isHermitianSesquilinear.Build _ _ _ _ _ (@form_of_matrix_is_hermitian m). Local Notation "''[' u , v ]" := (form_of_matrix theta M u%R v%R) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. Local Notation "B ^!" := (orthomx theta M B) : matrix_set_scope. Local Notation "A '_|_ B" := (A%MS <= B%MS^!)%MS : matrix_set_scope. Lemma orthomxE u v : (u '_|_ v)%MS = ('[u, v] == 0). Proof. rewrite (sameP sub_kermxP eqP) mulmxA. by rewrite [_ *m _^t _]mx11_scalar -trace_mx11 fmorph_eq0. Qed. Lemma hermmx_eq0P {u v} : reflect ('[u, v] = 0) (u '_|_ v)%MS. Proof. by rewrite orthomxE; apply/eqP. Qed. Lemma orthomxP p q (A : 'M_(p, n)) (B :'M_(q, n)) : reflect (forall (u v : 'rV_n), u <= A -> v <= B -> u '_|_ v)%MS (A '_|_ B)%MS. Proof. apply: (iffP idP) => AnB. move=> u v uA vB; rewrite (submx_trans uA) // (submx_trans AnB) //. apply/sub_kermxP; have /submxP [w ->] := vB. rewrite trmx_mul map_mxM !mulmxA -[kermx _ *m _ *m _]mulmxA. by rewrite [kermx _ *m _](sub_kermxP _) // mul0mx. apply/rV_subP => u /AnB /(_ _) /sub_kermxP uMv; apply/sub_kermxP. suff: forall m (v : 'rV[R]_m), (forall i, v *m 'e_i ^t theta = 0 :> 'M_1) -> v = 0. apply => i; rewrite !mulmxA -!mulmxA -map_mxM -trmx_mul uMv //. by apply/submxP; exists 'e_i. move=> /= m v Hv; apply: (can_inj (@trmxK _ _ _)). rewrite trmx0; apply/row_matrixP=> i; rewrite row0 rowE. apply: (can_inj (@trmxK _ _ _)); rewrite trmx0 trmx_mul trmxK. by rewrite -(map_delta_mx theta) map_trmx Hv. Qed. Lemma orthomx_sym p q (A : 'M_(p, n)) (B :'M_(q, n)) : (A '_|_ B)%MS = (B '_|_ A)%MS. Proof. gen have nC : p q A B / (A '_|_ B -> B '_|_ A)%MS; last by apply/idP/idP; apply/nC. move=> AnB; apply/orthomxP => u v ? ?; rewrite orthomxE. rewrite hermC mulf_eq0 ?fmorph_eq0 ?signr_eq0 /=. by rewrite -orthomxE (orthomxP _ _ AnB). Qed. Lemma ortho_ortho_mx p (A : 'M_(p, n)) : (A^! '_|_ A)%MS. Proof. by []. Qed. Lemma ortho_mx_ortho p (A : 'M_(p, n)) : (A '_|_ A^!)%MS. Proof. by rewrite orthomx_sym. Qed. Lemma rank_orthomx u : (\rank (u ^!) >= n.-1)%N. Proof. rewrite mxrank_ker -subn1 leq_sub2l //. by rewrite (leq_trans (mxrankM_maxr _ _)) // rank_leq_col. Qed. Local Notation radmx := (1%:M^!)%MS. Lemma radmxE : radmx = kermx M. Proof. by rewrite /orthomx /orthomx trmx1 map_mx1 mulmx1. Qed. Lemma orthoNmx k m (A : 'M[R]_(k, n)) (B : 'M[R]_(m, n)) : ((- A) '_|_ B)%MS = (A '_|_ B)%MS. Proof. by rewrite eqmx_opp. Qed. Lemma orthomxN k m (A : 'M[R]_(k, n)) (B : 'M[R]_(m, n)) : (A '_|_ (- B))%MS = (A '_|_ B)%MS. Proof. by rewrite ![(A '_|_ _)%MS]orthomx_sym orthoNmx. Qed. Lemma orthoDmx k m p (A : 'M[R]_(k, n)) (B : 'M[R]_(m, n)) (C : 'M[R]_(p, n)) : (A + B '_|_ C)%MS = (A '_|_ C)%MS && (B '_|_ C)%MS. Proof. by rewrite addsmxE !(sameP sub_kermxP eqP) mul_col_mx col_mx_eq0. Qed. Lemma orthomxD k m p (A : 'M[R]_(k, n)) (B : 'M[R]_(m, n)) (C : 'M[R]_(p, n)) : (A '_|_ B + C)%MS = (A '_|_ B)%MS && (A '_|_ C)%MS. Proof. by rewrite ![(A '_|_ _)%MS]orthomx_sym orthoDmx. Qed. Lemma orthoZmx p m a (A : 'M[R]_(p, n)) (B : 'M[R]_(m, n)) : a != 0 -> (a *: A '_|_ B)%MS = (A '_|_ B)%MS. Proof. by move=> a_neq0; rewrite eqmx_scale. Qed. Lemma orthomxZ p m a (A : 'M[R]_(p, n)) (B : 'M[R]_(m, n)) : a != 0 -> (A '_|_ (a *: B))%MS = (A '_|_ B)%MS. Proof. by move=> a_neq0; rewrite ![(A '_|_ _)%MS]orthomx_sym orthoZmx. Qed. Lemma eqmx_ortho p m (A : 'M[R]_(p, n)) (B : 'M[R]_(m, n)) : (A :=: B)%MS -> (A^! :=: B^!)%MS. Proof. move=> eqAB; apply/eqmxP. by rewrite orthomx_sym -eqAB ortho_mx_ortho orthomx_sym eqAB ortho_mx_ortho. Qed. Lemma genmx_ortho p (A : 'M[R]_(p, n)) : (<<A>>^! :=: A^!)%MS. Proof. exact: (eqmx_ortho (genmxE _)). Qed. End HermitianMxTheory. End HermitianMx. End MatrixForms. Notation symmetricmx := (hermitianmx _ false idfun). Notation skewmx := (hermitianmx _ true idfun). Notation hermsymmx := (hermitianmx _ false conjC). Lemma hermitian1mx_subproof {C : numClosedFieldType} n : (1%:M : 'M[C]_n) \is hermsymmx. Proof. by rewrite qualifE /= expr0 scale1r tr_scalar_mx map_scalar_mx conjC1. Qed. Canonical hermitian1mx {C : numClosedFieldType} n := HermitianMx (@hermitian1mx_subproof C n).
Imo1987Q1.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.Fintype.BigOperators import Mathlib.Data.Fintype.Perm import Mathlib.Dynamics.FixedPoints.Basic /-! # Formalization of IMO 1987, Q1 Let $p_{n, k}$ be the number of permutations of a set of cardinality `n ≥ 1` that fix exactly `k` elements. Prove that $∑_{k=0}^n k p_{n,k}=n!$. To prove this identity, we show that both sides are equal to the cardinality of the set `{(x : α, σ : Perm α) | σ x = x}`, regrouping by `card (fixedPoints σ)` for the left hand side and by `x` for the right hand side. The original problem assumes `n ≥ 1`. It turns out that a version with `n * (n - 1)!` in the RHS holds true for `n = 0` as well, so we first prove it, then deduce the original version in the case `n ≥ 1`. -/ variable (α : Type*) [Fintype α] [DecidableEq α] open scoped Nat open Equiv Fintype Function open Finset (range sum_const) open Set (Iic) namespace Imo1987Q1 /-- The set of pairs `(x : α, σ : Perm α)` such that `σ x = x` is equivalent to the set of pairs `(x : α, σ : Perm {x}ᶜ)`. -/ def fixedPointsEquiv : { σx : α × Perm α // σx.2 σx.1 = σx.1 } ≃ Σ x : α, Perm ({x}ᶜ : Set α) := calc { σx : α × Perm α // σx.2 σx.1 = σx.1 } ≃ Σ x : α, { σ : Perm α // σ x = x } := setProdEquivSigma _ _ ≃ Σ x : α, { σ : Perm α // ∀ y : ({x} : Set α), σ y = Equiv.refl (↥({x} : Set α)) y } := (sigmaCongrRight fun x => Equiv.setCongr <| by simp only [SetCoe.forall]; simp) _ ≃ Σ x : α, Perm ({x}ᶜ : Set α) := sigmaCongrRight fun x => by apply Equiv.Set.compl theorem card_fixed_points : card { σx : α × Perm α // σx.2 σx.1 = σx.1 } = card α * (card α - 1)! := by simp only [card_congr (fixedPointsEquiv α), card_sigma, card_perm] have (x : _) : ({x}ᶜ : Set α) = Finset.filter (· ≠ x) Finset.univ := by ext; simp simp [this] /-- Given `α : Type*` and `k : ℕ`, `fiber α k` is the set of permutations of `α` with exactly `k` fixed points. -/ def fiber (k : ℕ) : Set (Perm α) := {σ : Perm α | card (fixedPoints σ) = k} instance {k : ℕ} : Fintype (fiber α k) := by unfold fiber; infer_instance @[simp] theorem mem_fiber {σ : Perm α} {k : ℕ} : σ ∈ fiber α k ↔ card (fixedPoints σ) = k := Iff.rfl /-- `p α k` is the number of permutations of `α` with exactly `k` fixed points. -/ def p (k : ℕ) := card (fiber α k) /-- The set of triples `(k ≤ card α, σ ∈ fiber α k, x ∈ fixedPoints σ)` is equivalent to the set of pairs `(x : α, σ : Perm α)` such that `σ x = x`. The equivalence sends `(k, σ, x)` to `(x, σ)` and `(x, σ)` to `(card (fixedPoints σ), σ, x)`. It is easy to see that the cardinality of the LHS is given by `∑ k : Fin (card α + 1), k * p α k`. -/ def fixedPointsEquiv' : (Σ (k : Fin (card α + 1)) (σ : fiber α k), fixedPoints σ.1) ≃ { σx : α × Perm α // σx.2 σx.1 = σx.1 } where toFun p := ⟨⟨p.2.2, p.2.1⟩, p.2.2.2⟩ invFun p := ⟨⟨card (fixedPoints p.1.2), (card_subtype_le _).trans_lt (Nat.lt_succ_self _)⟩, ⟨p.1.2, rfl⟩, ⟨p.1.1, p.2⟩⟩ left_inv := fun ⟨⟨k, hk⟩, ⟨σ, hσ⟩, ⟨x, hx⟩⟩ => by simp only [mem_fiber] at hσ subst k; rfl right_inv := fun ⟨⟨x, σ⟩, h⟩ => rfl /-- Main statement for any `(α : Type*) [Fintype α]`. -/ theorem main_fintype : ∑ k ∈ range (card α + 1), k * p α k = card α * (card α - 1)! := by have A : ∀ (k) (σ : fiber α k), card (fixedPoints (↑σ : Perm α)) = k := fun k σ => σ.2 simpa [A, ← Fin.sum_univ_eq_sum_range, -card_ofFinset, Finset.card_univ, card_fixed_points, mul_comm] using card_congr (fixedPointsEquiv' α) /-- Main statement for permutations of `Fin n`, a version that works for `n = 0`. -/ theorem main₀ (n : ℕ) : ∑ k ∈ range (n + 1), k * p (Fin n) k = n * (n - 1)! := by simpa using main_fintype (Fin n) /-- Main statement for permutations of `Fin n`. -/ theorem main {n : ℕ} (hn : 1 ≤ n) : ∑ k ∈ range (n + 1), k * p (Fin n) k = n ! := by rw [main₀, Nat.mul_factorial_pred (Nat.one_le_iff_ne_zero.mp hn)] end Imo1987Q1
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.
Hopf_.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.Bimon_ import Mathlib.CategoryTheory.Monoidal.Conv /-! # The category of Hopf monoids in a braided monoidal category. ## TODO * Show that in a cartesian monoidal category Hopf monoids are exactly group objects. * Show that `Hopf_ (ModuleCat R) ≌ HopfAlgCat R`. -/ noncomputable section universe v₁ v₂ u₁ u₂ u open CategoryTheory MonoidalCategory variable {C : Type u₁} [Category.{v₁} C] [MonoidalCategory.{v₁} C] [BraidedCategory C] open scoped Mon_Class Comon_Class /-- A Hopf monoid in a braided category `C` is a bimonoid object in `C` equipped with an antipode. -/ class Hopf_Class (X : C) extends Bimon_Class X where /-- The antipode is an endomorphism of the underlying object of the Hopf monoid. -/ antipode : X ⟶ X antipode_left (X) : Δ ≫ antipode ▷ X ≫ μ = ε ≫ η := by cat_disch antipode_right (X) : Δ ≫ X ◁ antipode ≫ μ = ε ≫ η := by cat_disch namespace Hopf_Class @[inherit_doc] scoped notation "𝒮" => Hopf_Class.antipode @[inherit_doc] scoped notation "𝒮["M"]" => Hopf_Class.antipode (X := M) attribute [reassoc (attr := simp)] antipode_left antipode_right end Hopf_Class variable (C) /-- A Hopf monoid in a braided category `C` is a bimonoid object in `C` equipped with an antipode. -/ structure Hopf_ where /-- The underlying object in the ambient monoidal category -/ X : C [hopf : Hopf_Class X] attribute [instance] Hopf_.hopf namespace Hopf_ variable {C} /-- A Hopf monoid is a bimonoid. -/ def toBimon_ (A : Hopf_ C) : Bimon_ C := .mk' A.X /-- Morphisms of Hopf monoids are just morphisms of the underlying bimonoids. In fact they automatically intertwine the antipodes, proved below. -/ instance : Category (Hopf_ C) := inferInstanceAs <| Category (InducedCategory (Bimon_ C) Hopf_.toBimon_) end Hopf_ namespace Hopf_Class variable {C} /-- Morphisms of Hopf monoids intertwine the antipodes. -/ theorem hom_antipode {A B : C} [Hopf_Class A] [Hopf_Class B] (f : A ⟶ B) [IsBimon_Hom f] : f ≫ 𝒮 = 𝒮 ≫ f := by -- We show these elements are equal by exhibiting an element in the convolution algebra -- between `A` (as a comonoid) and `B` (as a monoid), -- such that the LHS is a left inverse, and the RHS is a right inverse. apply left_inv_eq_right_inv (M := Conv A B) (a := f) · rw [Conv.mul_eq, Conv.one_eq] simp only [comp_whiskerRight, Category.assoc] slice_lhs 3 4 => rw [← whisker_exchange] slice_lhs 2 3 => rw [← tensorHom_def] slice_lhs 1 2 => rw [← IsComon_Hom.hom_comul f] slice_lhs 2 4 => rw [antipode_left] slice_lhs 1 2 => rw [IsComon_Hom.hom_counit] · rw [Conv.mul_eq, Conv.one_eq] simp only [whiskerLeft_comp, Category.assoc] slice_lhs 2 3 => rw [← whisker_exchange] slice_lhs 3 4 => rw [← tensorHom_def] slice_lhs 3 4 => rw [← IsMon_Hom.mul_hom] slice_lhs 1 3 => rw [antipode_right] slice_lhs 2 3 => rw [IsMon_Hom.one_hom] @[reassoc (attr := simp)] theorem one_antipode (A : C) [Hopf_Class A] : η[A] ≫ 𝒮[A] = η[A] := by have := (rfl : η[A] ≫ Δ[A] ≫ (𝒮[A] ▷ A) ≫ μ[A] = _) conv at this => rhs rw [antipode_left] rw [Bimon_.one_comul_assoc, tensorHom_def_assoc, unitors_inv_equal, ← rightUnitor_inv_naturality_assoc, whisker_exchange_assoc, ← rightUnitor_inv_naturality_assoc, rightUnitor_inv_naturality_assoc] at this simpa @[reassoc (attr := simp)] theorem antipode_counit (A : C) [Hopf_Class A] : 𝒮[A] ≫ ε[A] = ε[A] := by have := (rfl : Δ[A] ≫ (𝒮[A] ▷ A) ≫ μ[A] ≫ ε[A] = _) conv at this => rhs rw [antipode_left_assoc] rw [Bimon_.mul_counit, tensorHom_def', Category.assoc, ← whisker_exchange_assoc] at this simpa [unitors_equal] /-! ## The antipode is an antihomomorphism with respect to both the monoid and comonoid structures. -/ theorem antipode_comul₁ (A : C) [Hopf_Class A] : Δ[A] ≫ 𝒮[A] ▷ A ≫ Δ[A] ▷ A ≫ (α_ A A A).hom ≫ A ◁ A ◁ Δ[A] ≫ A ◁ (α_ A A A).inv ≫ A ◁ (β_ A A).hom ▷ A ≫ A ◁ (α_ A A A).hom ≫ (α_ A A (A ⊗ A)).inv ≫ (μ[A] ⊗ₘ μ[A]) = ε[A] ≫ (λ_ (𝟙_ C)).inv ≫ (η[A] ⊗ₘ η[A]) := by slice_lhs 3 5 => rw [← associator_naturality_right, ← Category.assoc, ← tensorHom_def] slice_lhs 3 9 => rw [Bimon_.compatibility] slice_lhs 1 3 => rw [antipode_left] simp [Mon_Class.tensorObj.one_def] /-- Auxiliary calculation for `antipode_comul`. This calculation calls for some ASCII art out of This Week's Finds. ``` | | n n | \ / | | / | | / \ | | | S S | | \ / | | / | | / \ \ / \ / v v \ / v | ``` We move the left antipode up through the crossing, the right antipode down through the crossing, the right multiplication down across the strand, reassociate the comultiplications, then use `antipode_right` then `antipode_left` to simplify. -/ theorem antipode_comul₂ (A : C) [Hopf_Class A] : Δ[A] ≫ Δ[A] ▷ A ≫ (α_ A A A).hom ≫ A ◁ A ◁ Δ[A] ≫ A ◁ A ◁ (β_ A A).hom ≫ A ◁ A ◁ (𝒮[A] ⊗ₘ 𝒮[A]) ≫ A ◁ (α_ A A A).inv ≫ A ◁ (β_ A A).hom ▷ A ≫ A ◁ (α_ A A A).hom ≫ (α_ A A (A ⊗ A)).inv ≫ (μ[A] ⊗ₘ μ[A]) = ε[A] ≫ (λ_ (𝟙_ C)).inv ≫ (η[A] ⊗ₘ η[A]) := by -- We should write a version of `slice_lhs` that zooms through whiskerings. slice_lhs 6 6 => simp only [tensorHom_def', whiskerLeft_comp] slice_lhs 7 8 => rw [← whiskerLeft_comp, associator_inv_naturality_middle, whiskerLeft_comp] slice_lhs 8 9 => rw [← whiskerLeft_comp, ← comp_whiskerRight, BraidedCategory.braiding_naturality_right, comp_whiskerRight, whiskerLeft_comp] slice_lhs 9 10 => rw [← whiskerLeft_comp, associator_naturality_left, whiskerLeft_comp] slice_lhs 5 6 => rw [← whiskerLeft_comp, ← whiskerLeft_comp, ← BraidedCategory.braiding_naturality_left, whiskerLeft_comp, whiskerLeft_comp] slice_lhs 11 12 => rw [tensorHom_def', ← Category.assoc, ← associator_inv_naturality_right] slice_lhs 10 11 => rw [← whiskerLeft_comp, ← whisker_exchange, whiskerLeft_comp] slice_lhs 6 10 => simp only [← whiskerLeft_comp] rw [← BraidedCategory.hexagon_reverse_assoc, Iso.inv_hom_id_assoc, ← BraidedCategory.braiding_naturality_left] simp only [whiskerLeft_comp] rw [Comon_Class.comul_assoc_flip_assoc, Iso.inv_hom_id_assoc] slice_lhs 2 3 => simp only [← whiskerLeft_comp] rw [Comon_Class.comul_assoc] simp only [whiskerLeft_comp] slice_lhs 3 7 => simp only [← whiskerLeft_comp] rw [← associator_naturality_middle_assoc, Iso.hom_inv_id_assoc] simp only [← comp_whiskerRight] rw [antipode_right] simp only [comp_whiskerRight] simp only [whiskerLeft_comp] slice_lhs 2 3 => simp only [← whiskerLeft_comp] rw [Comon_Class.counit_comul] simp only [whiskerLeft_comp] slice_lhs 3 4 => simp only [← whiskerLeft_comp] rw [BraidedCategory.braiding_naturality_left] simp only [whiskerLeft_comp] slice_lhs 4 5 => simp only [← whiskerLeft_comp] rw [whisker_exchange] simp only [whiskerLeft_comp] slice_lhs 5 7 => rw [associator_inv_naturality_right_assoc, whisker_exchange] simp only [braiding_tensorUnit_left, whiskerLeft_comp, whiskerLeft_rightUnitor_inv, whiskerRight_id, whiskerLeft_rightUnitor, Category.assoc, Iso.hom_inv_id_assoc, Iso.inv_hom_id_assoc, whiskerLeft_inv_hom_assoc, antipode_right_assoc] rw [rightUnitor_inv_naturality_assoc, tensorHom_def] monoidal theorem antipode_comul (A : C) [Hopf_Class A] : 𝒮[A] ≫ Δ[A] = Δ[A] ≫ (β_ _ _).hom ≫ (𝒮[A] ⊗ₘ 𝒮[A]) := by -- Again, it is a "left inverse equals right inverse" argument in the convolution monoid. apply left_inv_eq_right_inv (M := Conv A (A ⊗ A)) (a := Δ[A]) · rw [Conv.mul_eq, Conv.one_eq] simp only [comp_whiskerRight, tensor_whiskerLeft, Mon_Class.tensorObj.mul_def, Category.assoc, Mon_Class.tensorObj.one_def] simp only [tensorμ] simp only [Category.assoc, Iso.inv_hom_id_assoc] exact antipode_comul₁ A · rw [Conv.mul_eq, Conv.one_eq] simp only [whiskerLeft_comp, tensor_whiskerLeft, Category.assoc, Iso.inv_hom_id_assoc, Mon_Class.tensorObj.mul_def, Mon_Class.tensorObj.one_def] simp only [tensorμ] simp only [Category.assoc, Iso.inv_hom_id_assoc] exact antipode_comul₂ A theorem mul_antipode₁ (A : C) [Hopf_Class A] : (Δ[A] ⊗ₘ Δ[A]) ≫ (α_ A A (A ⊗ A)).hom ≫ A ◁ (α_ A A A).inv ≫ A ◁ (β_ A A).hom ▷ A ≫ (α_ A (A ⊗ A) A).inv ≫ (α_ A A A).inv ▷ A ≫ μ[A] ▷ A ▷ A ≫ 𝒮[A] ▷ A ▷ A ≫ (α_ A A A).hom ≫ A ◁ μ[A] ≫ μ[A] = (ε[A] ⊗ₘ ε[A]) ≫ (λ_ (𝟙_ C)).hom ≫ η[A] := by slice_lhs 8 9 => rw [associator_naturality_left] slice_lhs 9 10 => rw [← whisker_exchange] slice_lhs 7 8 => rw [associator_naturality_left] slice_lhs 8 9 => rw [← tensorHom_def] simp /-- Auxiliary calculation for `mul_antipode`. ``` | n / \ | n | / \ | S S | \ / n / / \ / \ | / | \ / \ / v v | | ``` We move the leftmost multiplication up, so we can reassociate. We then move the rightmost comultiplication under the strand, and simplify using `antipode_right`. -/ theorem mul_antipode₂ (A : C) [Hopf_Class A] : (Δ[A] ⊗ₘ Δ[A]) ≫ (α_ A A (A ⊗ A)).hom ≫ A ◁ (α_ A A A).inv ≫ A ◁ (β_ A A).hom ▷ A ≫ (α_ A (A ⊗ A) A).inv ≫ (α_ A A A).inv ▷ A ≫ μ[A] ▷ A ▷ A ≫ (α_ A A A).hom ≫ A ◁ (β_ A A).hom ≫ A ◁ (𝒮[A] ⊗ₘ 𝒮[A]) ≫ A ◁ μ[A] ≫ μ[A] = (ε[A] ⊗ₘ ε[A]) ≫ (λ_ (𝟙_ C)).hom ≫ η[A] := by slice_lhs 7 8 => rw [associator_naturality_left] slice_lhs 8 9 => rw [← whisker_exchange] slice_lhs 9 10 => rw [← whisker_exchange] slice_lhs 11 12 => rw [Mon_Class.mul_assoc_flip] slice_lhs 10 11 => rw [associator_inv_naturality_left] slice_lhs 11 12 => simp only [← comp_whiskerRight] rw [Mon_Class.mul_assoc] simp only [comp_whiskerRight] rw [tensorHom_def] rw [tensor_whiskerLeft _ _ (β_ A A).hom] rw [pentagon_inv_inv_hom_hom_inv_assoc] slice_lhs 7 8 => rw [Iso.inv_hom_id] rw [Category.id_comp] slice_lhs 5 7 => simp only [← whiskerLeft_comp] rw [← BraidedCategory.hexagon_forward] simp only [whiskerLeft_comp] simp only [tensor_whiskerLeft, Category.assoc, Iso.inv_hom_id_assoc, pentagon_inv_inv_hom_inv_inv, whisker_assoc, Mon_Class.mul_assoc, whiskerLeft_inv_hom_assoc] slice_lhs 3 4 => simp only [← whiskerLeft_comp] rw [BraidedCategory.braiding_naturality_right] simp only [whiskerLeft_comp] rw [tensorHom_def'] simp only [whiskerLeft_comp] slice_lhs 5 6 => simp only [← whiskerLeft_comp] rw [← associator_naturality_right] simp only [whiskerLeft_comp] slice_lhs 4 5 => simp only [← whiskerLeft_comp] rw [← whisker_exchange] simp only [whiskerLeft_comp] slice_lhs 5 9 => simp only [← whiskerLeft_comp] rw [associator_inv_naturality_middle_assoc, Iso.hom_inv_id_assoc] simp only [← comp_whiskerRight] rw [antipode_right] simp only [comp_whiskerRight] simp only [whiskerLeft_comp] slice_lhs 6 7 => simp only [← whiskerLeft_comp] rw [Mon_Class.one_mul] simp only [whiskerLeft_comp] slice_lhs 3 4 => simp only [← whiskerLeft_comp] rw [← BraidedCategory.braiding_naturality_left] simp only [whiskerLeft_comp] slice_lhs 4 5 => simp only [← whiskerLeft_comp] rw [← BraidedCategory.braiding_naturality_right] simp only [whiskerLeft_comp] rw [← associator_naturality_middle_assoc] simp only [braiding_tensorUnit_right, whiskerLeft_comp] slice_lhs 6 7 => simp only [← whiskerLeft_comp] rw [Iso.inv_hom_id] simp only [whiskerLeft_comp] simp only [whiskerLeft_id, Category.id_comp] slice_lhs 5 6 => rw [whiskerLeft_rightUnitor, Category.assoc, ← rightUnitor_naturality] rw [associator_inv_naturality_right_assoc, Iso.hom_inv_id_assoc] slice_lhs 3 4 => rw [whisker_exchange] slice_lhs 1 3 => simp only [← comp_whiskerRight] rw [antipode_right] simp only [comp_whiskerRight] slice_lhs 2 3 => rw [← whisker_exchange] slice_lhs 1 2 => dsimp rw [← tensorHom_def] slice_lhs 2 3 => rw [rightUnitor_naturality] monoidal theorem mul_antipode (A : C) [Hopf_Class A] : μ[A] ≫ 𝒮[A] = (𝒮[A] ⊗ₘ 𝒮[A]) ≫ (β_ _ _).hom ≫ μ[A] := by -- Again, it is a "left inverse equals right inverse" argument in the convolution monoid. apply left_inv_eq_right_inv (M := Conv (A ⊗ A) A) (a := μ[A]) · -- Unfold the algebra structure in the convolution monoid, -- then `simp?, simp only [tensor_μ], simp?`. rw [Conv.mul_eq, Conv.one_eq] simp only [Comon_.tensorObj_comul, whiskerRight_tensor, comp_whiskerRight, Category.assoc, Comon_.tensorObj_counit] simp only [tensorμ] simp only [Category.assoc, pentagon_hom_inv_inv_inv_inv_assoc] exact mul_antipode₁ A · rw [Conv.mul_eq, Conv.one_eq] simp only [Comon_.tensorObj_comul, whiskerRight_tensor, BraidedCategory.braiding_naturality_assoc, whiskerLeft_comp, Category.assoc, Comon_.tensorObj_counit] simp only [tensorμ] simp only [Category.assoc, pentagon_hom_inv_inv_inv_inv_assoc] exact mul_antipode₂ A /-- In a commutative Hopf algebra, the antipode squares to the identity. -/ theorem antipode_antipode (A : C) [Hopf_Class A] (comm : (β_ _ _).hom ≫ μ[A] = μ[A]) : 𝒮[A] ≫ 𝒮[A] = 𝟙 A := by -- Again, it is a "left inverse equals right inverse" argument in the convolution monoid. apply left_inv_eq_right_inv (M := Conv A A) (a := 𝒮[A]) · -- Unfold the algebra structure in the convolution monoid, -- then `simp?`. rw [Conv.mul_eq, Conv.one_eq] simp only [comp_whiskerRight, Category.assoc] rw [← comm, ← tensorHom_def_assoc, ← mul_antipode] simp · rw [Conv.mul_eq, Conv.one_eq] simp end Hopf_Class end
Basic.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.LinearAlgebra.TensorProduct.RightExactness import Mathlib.RingTheory.FinitePresentation import Mathlib.RingTheory.Extension.Generators import Mathlib.RingTheory.MvPolynomial.Localization import Mathlib.RingTheory.TensorProduct.MvPolynomial /-! # Presentations of algebras A presentation of an `R`-algebra `S` is a distinguished family of generators and relations. ## Main definition - `Algebra.Presentation`: A presentation of an `R`-algebra `S` is a family of generators with 1. `rels`: The type of relations. 2. `relation : relations → MvPolynomial vars R`: The assignment of each relation to a polynomial in the generators. - `Algebra.Presentation.IsFinite`: A presentation is called finite, if both variables and relations are finite. - `Algebra.Presentation.dimension`: The dimension of a presentation is the number of generators minus the number of relations. We also give constructors for localization, base change and composition. ## TODO - Define `Hom`s of presentations. ## Notes This contribution was created as part of the AIM workshop "Formalizing algebraic geometry" in June 2024. -/ universe t w u v open TensorProduct MvPolynomial variable (R : Type u) (S : Type v) (ι : Type w) (σ : Type t) [CommRing R] [CommRing S] [Algebra R S] /-- A presentation of an `R`-algebra `S` is a family of generators with `σ → MvPolynomial ι R`: The assignment of each relation to a polynomial in the generators. -/ @[nolint checkUnivs] structure Algebra.Presentation extends Algebra.Generators R S ι where /-- The assignment of each relation to a polynomial in the generators. -/ relation : σ → toGenerators.Ring /-- The relations span the kernel of the canonical map. -/ span_range_relation_eq_ker : Ideal.span (Set.range relation) = toGenerators.ker namespace Algebra.Presentation variable {R S ι σ} variable (P : Presentation R S ι σ) @[simp] lemma aeval_val_relation (i) : aeval P.val (P.relation i) = 0 := by rw [← RingHom.mem_ker, ← P.ker_eq_ker_aeval_val, ← P.span_range_relation_eq_ker] exact Ideal.subset_span ⟨i, rfl⟩ lemma relation_mem_ker (i) : P.relation i ∈ P.ker := by rw [← P.span_range_relation_eq_ker] apply Ideal.subset_span use i /-- The polynomial algebra wrt a family of generators modulo a family of relations. -/ protected abbrev Quotient : Type (max w u) := P.Ring ⧸ P.ker /-- `P.Quotient` is `P.Ring`-isomorphic to `S` and in particular `R`-isomorphic to `S`. -/ def quotientEquiv : P.Quotient ≃ₐ[P.Ring] S := Ideal.quotientKerAlgEquivOfRightInverse (f := Algebra.ofId P.Ring S) (g := P.σ) <| fun x ↦ by rw [Algebra.ofId_apply, P.algebraMap_apply, P.aeval_val_σ] @[simp] lemma quotientEquiv_mk (p : P.Ring) : P.quotientEquiv p = algebraMap P.Ring S p := rfl @[simp] lemma quotientEquiv_symm (x : S) : P.quotientEquiv.symm x = P.σ x := rfl set_option linter.unusedVariables false in /-- Dimension of a presentation defined as the cardinality of the generators minus the cardinality of the relations. Note: this definition is completely non-sensical for non-finite presentations and even then for this to make sense, you should assume that the presentation is a complete intersection. -/ @[nolint unusedArguments] noncomputable def dimension (P : Presentation R S ι σ) : ℕ := Nat.card ι - Nat.card σ lemma fg_ker [Finite σ] : P.ker.FG := by use (Set.finite_range P.relation).toFinset simp [span_range_relation_eq_ker] @[deprecated (since := "2025-05-27")] alias ideal_fg_of_isFinite := fg_ker /-- If a presentation is finite, the corresponding quotient is of finite presentation. -/ instance [Finite σ] [Finite ι] : FinitePresentation R P.Quotient := FinitePresentation.quotient P.fg_ker lemma finitePresentation_of_isFinite [Finite σ] [Finite ι] (P : Presentation R S ι σ) : FinitePresentation R S := FinitePresentation.equiv (P.quotientEquiv.restrictScalars R) variable (R S) in lemma exists_presentation_fin [FinitePresentation R S] : ∃ n m, Nonempty (Presentation R S (Fin n) (Fin m)) := letI H := FinitePresentation.out (R := R) (A := S) letI n : ℕ := H.choose letI f : MvPolynomial (Fin n) R →ₐ[R] S := H.choose_spec.choose haveI hf : Function.Surjective f := H.choose_spec.choose_spec.1 haveI hf' : (RingHom.ker f).FG := H.choose_spec.choose_spec.2 letI H' := Submodule.fg_iff_exists_fin_generating_family.mp hf' let m : ℕ := H'.choose let v : Fin m → MvPolynomial (Fin n) R := H'.choose_spec.choose have hv : Ideal.span (Set.range v) = RingHom.ker f := H'.choose_spec.choose_spec ⟨n, m, ⟨{__ := Generators.ofSurjective (fun x ↦ f (.X x)) (by convert hf; ext; simp) relation := v span_range_relation_eq_ker := hv.trans (by congr; ext; simp) }⟩⟩ variable (R S) in /-- The index of generators to `ofFinitePresentation`. -/ noncomputable def ofFinitePresentationVars [FinitePresentation R S] : ℕ := (exists_presentation_fin R S).choose variable (R S) in /-- The index of relations to `ofFinitePresentation`. -/ noncomputable def ofFinitePresentationRels [FinitePresentation R S] : ℕ := (exists_presentation_fin R S).choose_spec.choose variable (R S) in /-- An arbitrary choice of a finite presentation of a finitely presented algebra. -/ noncomputable def ofFinitePresentation [FinitePresentation R S] : Presentation R S (Fin (ofFinitePresentationVars R S)) (Fin (ofFinitePresentationRels R S)) := (exists_presentation_fin R S).choose_spec.choose_spec.some section Construction /-- If `algebraMap R S` is bijective, the empty generators are a presentation with no relations. -/ noncomputable def ofBijectiveAlgebraMap (h : Function.Bijective (algebraMap R S)) : Presentation R S PEmpty.{w + 1} PEmpty.{t + 1} where __ := Generators.ofSurjectiveAlgebraMap h.surjective relation := PEmpty.elim span_range_relation_eq_ker := by simp only [Set.range_eq_empty, Ideal.span_empty] symm rw [← RingHom.injective_iff_ker_eq_bot] change Function.Injective (aeval PEmpty.elim) rw [aeval_injective_iff_of_isEmpty] exact h.injective lemma ofBijectiveAlgebraMap_dimension (h : Function.Bijective (algebraMap R S)) : (ofBijectiveAlgebraMap h).dimension = 0 := by simp [dimension] variable (R) in /-- The canonical `R`-presentation of `R` with no generators and no relations. -/ noncomputable def id : Presentation R R PEmpty.{w + 1} PEmpty.{t + 1} := ofBijectiveAlgebraMap Function.bijective_id lemma id_dimension : (Presentation.id R).dimension = 0 := ofBijectiveAlgebraMap_dimension (R := R) Function.bijective_id section Localization variable (r : R) [IsLocalization.Away r S] open IsLocalization.Away lemma _root_.Algebra.Generators.ker_localizationAway : (Generators.localizationAway (S := S) r).ker = Ideal.span { C r * X () - 1 } := by have : aeval (S₁ := S) (Generators.localizationAway r).val = (mvPolynomialQuotientEquiv S r).toAlgHom.comp (Ideal.Quotient.mkₐ R (Ideal.span {C r * X () - 1})) := by ext x simp only [aeval_X, Generators.localizationAway_val, AlgEquiv.toAlgHom_eq_coe, AlgHom.coe_comp, AlgHom.coe_coe, Ideal.Quotient.mkₐ_eq_mk, Function.comp_apply] rw [IsLocalization.Away.mvPolynomialQuotientEquiv_apply, aeval_X] rw [Generators.ker_eq_ker_aeval_val, this, AlgEquiv.toAlgHom_eq_coe, ← RingHom.ker_coe_toRingHom, AlgHom.comp_toRingHom, ← RingHom.comap_ker] simp only [AlgEquiv.toAlgHom_toRingHom] change Ideal.comap _ (RingHom.ker (mvPolynomialQuotientEquiv S r)) = Ideal.span {C r * X () - 1} simp [RingHom.ker_equiv, ← RingHom.ker_eq_comap_bot] variable (S) in /-- If `S` is the localization of `R` away from `r`, we can construct a natural presentation of `S` as `R`-algebra with a single generator `X` and the relation `r * X - 1 = 0`. -/ @[simps relation] noncomputable def localizationAway : Presentation R S Unit Unit where toGenerators := Generators.localizationAway r relation _ := C r * X () - 1 span_range_relation_eq_ker := by simp only [Set.range_const] exact (Generators.ker_localizationAway r).symm @[simp] lemma localizationAway_dimension_zero : (localizationAway S r).dimension = 0 := by simp [Presentation.dimension] end Localization section BaseChange variable (T) [CommRing T] [Algebra R T] (P : Presentation R S ι σ) private lemma span_range_relation_eq_ker_baseChange : Ideal.span (Set.range fun i ↦ (MvPolynomial.map (algebraMap R T)) (P.relation i)) = RingHom.ker (aeval (R := T) (S₁ := T ⊗[R] S) P.baseChange.val) := by apply le_antisymm · rw [Ideal.span_le] intro x ⟨y, hy⟩ have Z := aeval_val_relation P y apply_fun TensorProduct.includeRight (R := R) (A := T) at Z rw [map_zero] at Z simp only [SetLike.mem_coe, RingHom.mem_ker, ← Z, ← hy, TensorProduct.includeRight_apply] erw [aeval_map_algebraMap T P.baseChange.val (P.relation y)] change _ = TensorProduct.includeRight.toRingHom _ rw [map_aeval, AlgHom.toRingHom_eq_coe, RingHom.coe_coe, TensorProduct.includeRight.comp_algebraMap] rfl · intro x hx rw [RingHom.mem_ker] at hx have H := Algebra.TensorProduct.lTensor_ker (A := T) (IsScalarTower.toAlgHom R P.Ring S) P.algebraMap_surjective let e := MvPolynomial.algebraTensorAlgEquiv (R := R) (σ := ι) (A := T) have H' : e.symm x ∈ RingHom.ker (TensorProduct.map (AlgHom.id R T) (IsScalarTower.toAlgHom R P.Ring S)) := by rw [RingHom.mem_ker, ← hx] clear hx induction x using MvPolynomial.induction_on with | C a => simp only [algHom_C, TensorProduct.algebraMap_apply, algebraMap_self, RingHom.id_apply, e] rw [← MvPolynomial.algebraMap_eq, AlgEquiv.commutes] simp only [TensorProduct.algebraMap_apply, algebraMap_self, RingHom.id_apply, TensorProduct.map_tmul, AlgHom.coe_id, id_eq, map_one] | add p q hp hq => simp only [map_add, hp, hq] | mul_X p i hp => simp [hp, e] rw [H] at H' replace H' : e.symm x ∈ Ideal.map TensorProduct.includeRight P.ker := H' rw [← P.span_range_relation_eq_ker, ← Ideal.mem_comap, ← Ideal.comap_coe, ← AlgEquiv.toRingEquiv_toRingHom, Ideal.comap_coe, AlgEquiv.symm_toRingEquiv, Ideal.comap_symm, ← Ideal.map_coe, ← Ideal.map_coe _ (Ideal.span _), Ideal.map_map, Ideal.map_span, ← Set.range_comp, AlgEquiv.toRingEquiv_toRingHom, RingHom.coe_comp, RingHom.coe_coe] at H' convert H' simp [e] /-- If `P` is a presentation of `S` over `R` and `T` is an `R`-algebra, we obtain a natural presentation of `T ⊗[R] S` over `T`. -/ @[simps relation] noncomputable def baseChange : Presentation T (T ⊗[R] S) ι σ where __ := Generators.baseChange P.toGenerators relation i := MvPolynomial.map (algebraMap R T) (P.relation i) span_range_relation_eq_ker := P.span_range_relation_eq_ker_baseChange T lemma baseChange_toGenerators : (P.baseChange T).toGenerators = P.toGenerators.baseChange := rfl end BaseChange section Composition /-! ### Composition of presentations Let `S` be an `R`-algebra with presentation `P` and `T` be an `S`-algebra with presentation `Q`. In this section we construct a presentation of `T` as an `R`-algebra. For the underlying generators see `Algebra.Generators.comp`. The family of relations is indexed by `σ' ⊕ σ`. We have two canonical maps: `MvPolynomial ι R →ₐ[R] MvPolynomial (ι' ⊕ ι) R` induced by `Sum.inr` and `aux : MvPolynomial (ι' ⊕ ι) R →ₐ[R] MvPolynomial ι' S` induced by the evaluation `MvPolynomial ι R →ₐ[R] S` (see below). Now `i : σ` is mapped to the image of `P.relation i` under the first map and `j : σ'` is mapped to a pre-image under `aux` of `Q.relation j` (see `comp_relation_aux` for the construction of the pre-image and `comp_relation_aux_map` for a proof that it is indeed a pre-image). The evaluation map factors as: `MvPolynomial (ι' ⊕ ι) R →ₐ[R] MvPolynomial ι' S →ₐ[R] T`, where the first map is `aux`. The goal is to compute that the kernel of this composition is spanned by the relations indexed by `σ' ⊕ σ` (`span_range_relation_eq_ker_comp`). One easily sees that this kernel is the pre-image under `aux` of the kernel of the evaluation of `Q`, where the latter is by assumption spanned by the relations `Q.relation j`. Since `aux` is surjective (`aux_surjective`), the pre-image is the sum of the ideal spanned by the constructed pre-images of the `Q.relation j` and the kernel of `aux`. It hence remains to show that the kernel of `aux` is spanned by the image of the `P.relation i` under the canonical map `MvPolynomial ι R →ₐ[R] MvPolynomial (ι' ⊕ ι) R`. By assumption this span is the kernel of the evaluation map of `P`. For this, we use the isomorphism `MvPolynomial (ι' ⊕ ι) R ≃ₐ[R] MvPolynomial ι' (MvPolynomial ι R)` and `MvPolynomial.ker_map`. -/ variable {ι' σ' T : Type*} [CommRing T] [Algebra S T] variable (Q : Presentation S T ι' σ') (P : Presentation R S ι σ) set_option linter.unusedVariables false in /-- The evaluation map `MvPolynomial (ι' ⊕ ι) →ₐ[R] T` factors via this map. For more details, see the module docstring at the beginning of the section. -/ private noncomputable def aux (Q : Presentation S T ι' σ') (P : Presentation R S ι σ) : MvPolynomial (ι' ⊕ ι) R →ₐ[R] MvPolynomial ι' S := aeval (Sum.elim X (MvPolynomial.C ∘ P.val)) /-- A choice of pre-image of `Q.relation r` under `aux`. -/ private noncomputable def comp_relation_aux (r : σ') : MvPolynomial (ι' ⊕ ι) R := Finsupp.sum (Q.relation r) (fun x j ↦ (MvPolynomial.rename Sum.inr <| P.σ j) * monomial (x.mapDomain Sum.inl) 1) @[simp] private lemma aux_X (i : ι' ⊕ ι) : (Q.aux P) (X i) = Sum.elim X (C ∘ P.val) i := aeval_X (Sum.elim X (C ∘ P.val)) i /-- The pre-images constructed in `comp_relation_aux` are indeed pre-images under `aux`. -/ private lemma comp_relation_aux_map (r : σ') : (Q.aux P) (Q.comp_relation_aux P r) = Q.relation r := by simp only [aux, comp_relation_aux, map_finsuppSum] simp only [map_mul, aeval_rename, aeval_monomial, Sum.elim_comp_inr] conv_rhs => rw [← Finsupp.sum_single (Q.relation r)] congr ext u s m simp only [MvPolynomial.single_eq_monomial, aeval, AlgHom.coe_mk, coe_eval₂Hom] rw [monomial_eq, IsScalarTower.algebraMap_eq R S, algebraMap_eq, ← eval₂_comp_left, ← aeval_def] simp [Finsupp.prod_mapDomain_index_inj (Sum.inl_injective)] private lemma aux_surjective : Function.Surjective (Q.aux P) := fun p ↦ by induction p using MvPolynomial.induction_on with | C a => use rename Sum.inr <| P.σ a simp only [aux, aeval_rename, Sum.elim_comp_inr] have (p : MvPolynomial ι R) : aeval (C ∘ P.val) p = (C (aeval P.val p) : MvPolynomial ι' S) := by induction p using MvPolynomial.induction_on with | C a => simp | add p q hp hq => simp [hp, hq] | mul_X p i h => simp [h] simp [this] | add p q hp hq => obtain ⟨a, rfl⟩ := hp obtain ⟨b, rfl⟩ := hq exact ⟨a + b, map_add _ _ _⟩ | mul_X p i h => obtain ⟨a, rfl⟩ := h exact ⟨(a * X (Sum.inl i)), by simp⟩ private lemma aux_image_relation : Q.aux P '' (Set.range (Algebra.Presentation.comp_relation_aux Q P)) = Set.range Q.relation := by ext x constructor · rintro ⟨y, ⟨a, rfl⟩, rfl⟩ exact ⟨a, (Q.comp_relation_aux_map P a).symm⟩ · rintro ⟨y, rfl⟩ use Q.comp_relation_aux P y simp only [Set.mem_range, exists_apply_eq_apply, true_and, comp_relation_aux_map] private lemma aux_eq_comp : Q.aux P = (MvPolynomial.mapAlgHom (aeval P.val)).comp (sumAlgEquiv R ι' ι).toAlgHom := by ext i : 1 cases i <;> simp private lemma aux_ker : RingHom.ker (Q.aux P) = Ideal.map (rename Sum.inr) (RingHom.ker (aeval P.val)) := by rw [aux_eq_comp, ← AlgHom.comap_ker, MvPolynomial.ker_mapAlgHom] change Ideal.comap _ (Ideal.map (IsScalarTower.toAlgHom R (MvPolynomial ι R) _) _) = _ rw [← sumAlgEquiv_comp_rename_inr, ← Ideal.map_mapₐ, Ideal.comap_map_of_bijective] simpa using AlgEquiv.bijective (sumAlgEquiv R ι' ι) variable [Algebra R T] [IsScalarTower R S T] private lemma aeval_comp_val_eq : (aeval (Q.comp P.toGenerators).val) = (aevalTower (IsScalarTower.toAlgHom R S T) Q.val).comp (Q.aux P) := by ext i simp only [AlgHom.coe_comp, Function.comp_apply] erw [Q.aux_X P i] cases i <;> simp private lemma span_range_relation_eq_ker_comp : Ideal.span (Set.range (Sum.elim (Algebra.Presentation.comp_relation_aux Q P) fun rp ↦ (rename Sum.inr) (P.relation rp))) = (Q.comp P.toGenerators).ker := by rw [Generators.ker_eq_ker_aeval_val, Q.aeval_comp_val_eq, ← AlgHom.comap_ker] change _ = Ideal.comap _ (RingHom.ker (aeval Q.val)) rw [← Q.ker_eq_ker_aeval_val, ← Q.span_range_relation_eq_ker, ← Q.aux_image_relation P, ← Ideal.map_span, Ideal.comap_map_of_surjective' _ (Q.aux_surjective P)] rw [Set.Sum.elim_range, Ideal.span_union, Q.aux_ker, ← P.ker_eq_ker_aeval_val, ← P.span_range_relation_eq_ker, Ideal.map_span] congr ext simp /-- Given presentations of `T` over `S` and of `S` over `R`, we may construct a presentation of `T` over `R`. -/ @[simps -isSimp relation] noncomputable def comp : Presentation R T (ι' ⊕ ι) (σ' ⊕ σ) where toGenerators := Q.toGenerators.comp P.toGenerators relation := Sum.elim (Q.comp_relation_aux P) (fun rp ↦ MvPolynomial.rename Sum.inr <| P.relation rp) span_range_relation_eq_ker := Q.span_range_relation_eq_ker_comp P lemma toGenerators_comp : (Q.comp P).toGenerators = Q.toGenerators.comp P.toGenerators := rfl @[simp] lemma comp_relation_inr (r : σ) : (Q.comp P).relation (Sum.inr r) = rename Sum.inr (P.relation r) := rfl lemma comp_aeval_relation_inl (r : σ') : aeval (Sum.elim X (MvPolynomial.C ∘ P.val)) ((Q.comp P).relation (Sum.inl r)) = Q.relation r := by change (Q.aux P) _ = _ simp [comp_relation, comp_relation_aux_map] end Composition /-- Given a presentation `P` and equivalences `ι' ≃ ι` and `σ' ≃ σ`, this is the induced presentation with variables indexed by `ι'` and relations indexed by `σ'` -/ @[simps toGenerators] noncomputable def reindex (P : Presentation R S ι σ) {ι' σ' : Type*} (e : ι' ≃ ι) (f : σ' ≃ σ) : Presentation R S ι' σ' where __ := P.toGenerators.reindex e relation := rename e.symm ∘ P.relation ∘ f span_range_relation_eq_ker := by rw [Generators.ker_eq_ker_aeval_val, Generators.reindex_val, ← aeval_comp_rename, ← AlgHom.comap_ker, ← P.ker_eq_ker_aeval_val, ← P.span_range_relation_eq_ker, Set.range_comp, Set.range_comp, Equiv.range_eq_univ, Set.image_univ, ← Ideal.map_span (rename ⇑e.symm)] have hf : Function.Bijective (MvPolynomial.rename e.symm) := (renameEquiv R e.symm).bijective apply Ideal.comap_injective_of_surjective _ hf.2 simp_rw [Ideal.comap_comapₐ, rename_comp_rename, Equiv.self_comp_symm] simp [Ideal.comap_map_of_bijective _ hf, rename_id] @[simp] lemma dimension_reindex (P : Presentation R S ι σ) {ι' σ' : Type*} (e : ι' ≃ ι) (f : σ' ≃ σ) : (P.reindex e f).dimension = P.dimension := by simp [dimension, Nat.card_congr e, Nat.card_congr f] section variable {v : ι → MvPolynomial σ R} (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 presentation of a quotient `R[Xᵢ] ⧸ (vⱼ)`. If the definitional equality of the section matters, it can be explicitly provided. -/ @[simps! toGenerators] noncomputable def naive {v : ι → MvPolynomial σ R} (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) : Presentation R (MvPolynomial σ R ⧸ (Ideal.span <| Set.range v)) σ ι where __ := Generators.naive s hs relation := v span_range_relation_eq_ker := (Generators.ker_naive s hs).symm lemma naive_relation : (naive s hs).relation = v := rfl @[simp] lemma naive_relation_apply (i : ι) : (naive s hs).relation i = v i := rfl end end Construction end Presentation end Algebra
Basic.lean
/- Copyright (c) 2021 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Kim Morrison -/ import Mathlib.CategoryTheory.Comma.Basic import Mathlib.CategoryTheory.PUnit import Mathlib.CategoryTheory.Limits.Shapes.IsTerminal import Mathlib.CategoryTheory.Functor.EpiMono /-! # The category of "structured arrows" For `T : C ⥤ D`, a `T`-structured arrow with source `S : D` is just a morphism `S ⟶ T.obj Y`, for some `Y : C`. These form a category with morphisms `g : Y ⟶ Y'` making the obvious diagram commute. We prove that `𝟙 (T.obj Y)` is the initial object in `T`-structured objects with source `T.obj Y`. -/ namespace CategoryTheory -- morphism levels before object levels. See note [CategoryTheory universes]. universe v₁ v₂ v₃ v₄ v₅ v₆ u₁ u₂ u₃ u₄ u₅ u₆ variable {C : Type u₁} [Category.{v₁} C] {D : Type u₂} [Category.{v₂} D] /-- The category of `T`-structured arrows with domain `S : D` (here `T : C ⥤ D`), has as its objects `D`-morphisms of the form `S ⟶ T Y`, for some `Y : C`, and morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute. -/ -- We explicitly come from `PUnit.{1}` here to obtain the correct universe for morphisms of -- structured arrows. def StructuredArrow (S : D) (T : C ⥤ D) := Comma (Functor.fromPUnit.{0} S) T -- Porting note: not found by inferInstance instance (S : D) (T : C ⥤ D) : Category (StructuredArrow S T) := commaCategory namespace StructuredArrow /-- The obvious projection functor from structured arrows. -/ @[simps!] def proj (S : D) (T : C ⥤ D) : StructuredArrow S T ⥤ C := Comma.snd _ _ variable {S S' S'' : D} {Y Y' Y'' : C} {T T' : C ⥤ D} @[ext] lemma hom_ext {X Y : StructuredArrow S T} (f g : X ⟶ Y) (h : f.right = g.right) : f = g := CommaMorphism.ext (Subsingleton.elim _ _) h @[simp] theorem hom_eq_iff {X Y : StructuredArrow S T} (f g : X ⟶ Y) : f = g ↔ f.right = g.right := ⟨fun h ↦ by rw [h], hom_ext _ _⟩ /-- Construct a structured arrow from a morphism. -/ def mk (f : S ⟶ T.obj Y) : StructuredArrow S T := ⟨⟨⟨⟩⟩, Y, f⟩ @[simp] theorem mk_left (f : S ⟶ T.obj Y) : (mk f).left = ⟨⟨⟩⟩ := rfl @[simp] theorem mk_right (f : S ⟶ T.obj Y) : (mk f).right = Y := rfl @[simp] theorem mk_hom_eq_self (f : S ⟶ T.obj Y) : (mk f).hom = f := rfl @[reassoc (attr := simp)] theorem w {A B : StructuredArrow S T} (f : A ⟶ B) : A.hom ≫ T.map f.right = B.hom := by have := f.w; cat_disch @[simp] theorem comp_right {X Y Z : StructuredArrow S T} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).right = f.right ≫ g.right := rfl @[simp] theorem id_right (X : StructuredArrow S T) : (𝟙 X : X ⟶ X).right = 𝟙 X.right := rfl @[simp] theorem eqToHom_right {X Y : StructuredArrow S T} (h : X = Y) : (eqToHom h).right = eqToHom (by rw [h]) := by subst h simp only [eqToHom_refl, id_right] @[simp] theorem left_eq_id {X Y : StructuredArrow S T} (f : X ⟶ Y) : f.left = 𝟙 X.left := rfl /-- To construct a morphism of structured arrows, we need a morphism of the objects underlying the target, and to check that the triangle commutes. -/ @[simps right] def homMk {f f' : StructuredArrow S T} (g : f.right ⟶ f'.right) (w : f.hom ≫ T.map g = f'.hom := by cat_disch) : f ⟶ f' where left := 𝟙 f.left right := g w := by dsimp simpa using w.symm theorem homMk_surjective {f f' : StructuredArrow S T} (φ : f ⟶ f') : ∃ (ψ : f.right ⟶ f'.right) (hψ : f.hom ≫ T.map ψ = f'.hom), φ = StructuredArrow.homMk ψ hψ := ⟨φ.right, StructuredArrow.w φ, rfl⟩ /-- Given a structured arrow `X ⟶ T(Y)`, and an arrow `Y ⟶ Y'`, we can construct a morphism of structured arrows given by `(X ⟶ T(Y)) ⟶ (X ⟶ T(Y) ⟶ T(Y'))`. -/ @[simps] def homMk' (f : StructuredArrow S T) (g : f.right ⟶ Y') : f ⟶ mk (f.hom ≫ T.map g) where left := 𝟙 _ right := g lemma homMk'_id (f : StructuredArrow S T) : homMk' f (𝟙 f.right) = eqToHom (by cat_disch) := by ext simp [eqToHom_right] lemma homMk'_mk_id (f : S ⟶ T.obj Y) : homMk' (mk f) (𝟙 Y) = eqToHom (by simp) := homMk'_id _ lemma homMk'_comp (f : StructuredArrow S T) (g : f.right ⟶ Y') (g' : Y' ⟶ Y'') : homMk' f (g ≫ g') = homMk' f g ≫ homMk' (mk (f.hom ≫ T.map g)) g' ≫ eqToHom (by simp) := by ext simp [eqToHom_right] lemma homMk'_mk_comp (f : S ⟶ T.obj Y) (g : Y ⟶ Y') (g' : Y' ⟶ Y'') : homMk' (mk f) (g ≫ g') = homMk' (mk f) g ≫ homMk' (mk (f ≫ T.map g)) g' ≫ eqToHom (by simp) := homMk'_comp _ _ _ /-- Variant of `homMk'` where both objects are applications of `mk`. -/ @[simps] def mkPostcomp (f : S ⟶ T.obj Y) (g : Y ⟶ Y') : mk f ⟶ mk (f ≫ T.map g) where left := 𝟙 _ right := g lemma mkPostcomp_id (f : S ⟶ T.obj Y) : mkPostcomp f (𝟙 Y) = eqToHom (by simp) := by simp lemma mkPostcomp_comp (f : S ⟶ T.obj Y) (g : Y ⟶ Y') (g' : Y' ⟶ Y'') : mkPostcomp f (g ≫ g') = mkPostcomp f g ≫ mkPostcomp (f ≫ T.map g) g' ≫ eqToHom (by simp) := by simp /-- To construct an isomorphism of structured arrows, we need an isomorphism of the objects underlying the target, and to check that the triangle commutes. -/ @[simps! hom_right inv_right] def isoMk {f f' : StructuredArrow S T} (g : f.right ≅ f'.right) (w : f.hom ≫ T.map g.hom = f'.hom := by cat_disch) : f ≅ f' := Comma.isoMk (eqToIso (by ext)) g (by simpa using w.symm) theorem obj_ext (x y : StructuredArrow S T) (hr : x.right = y.right) (hh : x.hom ≫ T.map (eqToHom hr) = y.hom) : x = y := by cases x cases y cases hr cat_disch theorem ext {A B : StructuredArrow S T} (f g : A ⟶ B) : f.right = g.right → f = g := CommaMorphism.ext (Subsingleton.elim _ _) theorem ext_iff {A B : StructuredArrow S T} (f g : A ⟶ B) : f = g ↔ f.right = g.right := ⟨fun h => h ▸ rfl, ext f g⟩ instance proj_faithful : (proj S T).Faithful where map_injective {_ _} := ext /-- The converse of this is true with additional assumptions, see `mono_iff_mono_right`. -/ theorem mono_of_mono_right {A B : StructuredArrow S T} (f : A ⟶ B) [h : Mono f.right] : Mono f := (proj S T).mono_of_mono_map h theorem epi_of_epi_right {A B : StructuredArrow S T} (f : A ⟶ B) [h : Epi f.right] : Epi f := (proj S T).epi_of_epi_map h instance mono_homMk {A B : StructuredArrow S T} (f : A.right ⟶ B.right) (w) [h : Mono f] : Mono (homMk f w) := (proj S T).mono_of_mono_map h instance epi_homMk {A B : StructuredArrow S T} (f : A.right ⟶ B.right) (w) [h : Epi f] : Epi (homMk f w) := (proj S T).epi_of_epi_map h /-- Eta rule for structured arrows. Prefer `StructuredArrow.eta` for rewriting, since equality of objects tends to cause problems. -/ theorem eq_mk (f : StructuredArrow S T) : f = mk f.hom := rfl /-- Eta rule for structured arrows. -/ @[simps! hom_right inv_right] def eta (f : StructuredArrow S T) : f ≅ mk f.hom := isoMk (Iso.refl _) lemma mk_surjective (f : StructuredArrow S T) : ∃ (Y : C) (g : S ⟶ T.obj Y), f = mk g := ⟨_, _, eq_mk f⟩ /-- A morphism between source objects `S ⟶ S'` contravariantly induces a functor between structured arrows, `StructuredArrow S' T ⥤ StructuredArrow S T`. Ideally this would be described as a 2-functor from `D` (promoted to a 2-category with equations as 2-morphisms) to `Cat`. -/ @[simps!] def map (f : S ⟶ S') : StructuredArrow S' T ⥤ StructuredArrow S T := Comma.mapLeft _ ((Functor.const _).map f) @[simp] theorem map_mk {f : S' ⟶ T.obj Y} (g : S ⟶ S') : (map g).obj (mk f) = mk (g ≫ f) := rfl @[simp] theorem map_id {f : StructuredArrow S T} : (map (𝟙 S)).obj f = f := by rw [eq_mk f] simp @[simp] theorem map_comp {f : S ⟶ S'} {f' : S' ⟶ S''} {h : StructuredArrow S'' T} : (map (f ≫ f')).obj h = (map f).obj ((map f').obj h) := by rw [eq_mk h] simp /-- An isomorphism `S ≅ S'` induces an equivalence `StructuredArrow S T ≌ StructuredArrow S' T`. -/ @[simps!] def mapIso (i : S ≅ S') : StructuredArrow S T ≌ StructuredArrow S' T := Comma.mapLeftIso _ ((Functor.const _).mapIso i) /-- A natural isomorphism `T ≅ T'` induces an equivalence `StructuredArrow S T ≌ StructuredArrow S T'`. -/ @[simps!] def mapNatIso (i : T ≅ T') : StructuredArrow S T ≌ StructuredArrow S T' := Comma.mapRightIso _ i instance proj_reflectsIsomorphisms : (proj S T).ReflectsIsomorphisms where reflects {Y Z} f t := ⟨⟨StructuredArrow.homMk (inv ((proj S T).map f)) (by rw [Functor.map_inv, IsIso.comp_inv_eq]; simp), by constructor <;> apply CommaMorphism.ext <;> dsimp at t ⊢ <;> simp⟩⟩ open CategoryTheory.Limits /-- The identity structured arrow is initial. -/ noncomputable def mkIdInitial [T.Full] [T.Faithful] : IsInitial (mk (𝟙 (T.obj Y))) where desc c := homMk (T.preimage c.pt.hom) uniq c m _ := by apply CommaMorphism.ext · simp · apply T.map_injective simpa only [homMk_right, T.map_preimage, ← w m] using (Category.id_comp _).symm variable {A : Type u₃} [Category.{v₃} A] {B : Type u₄} [Category.{v₄} B] /-- The functor `(S, F ⋙ G) ⥤ (S, G)`. -/ @[simps!] def pre (S : D) (F : B ⥤ C) (G : C ⥤ D) : StructuredArrow S (F ⋙ G) ⥤ StructuredArrow S G := Comma.preRight _ F G instance (S : D) (F : B ⥤ C) (G : C ⥤ D) [F.Faithful] : (pre S F G).Faithful := show (Comma.preRight _ _ _).Faithful from inferInstance instance (S : D) (F : B ⥤ C) (G : C ⥤ D) [F.Full] : (pre S F G).Full := show (Comma.preRight _ _ _).Full from inferInstance instance (S : D) (F : B ⥤ C) (G : C ⥤ D) [F.EssSurj] : (pre S F G).EssSurj := show (Comma.preRight _ _ _).EssSurj from inferInstance /-- If `F` is an equivalence, then so is the functor `(S, F ⋙ G) ⥤ (S, G)`. -/ instance isEquivalence_pre (S : D) (F : B ⥤ C) (G : C ⥤ D) [F.IsEquivalence] : (pre S F G).IsEquivalence := Comma.isEquivalence_preRight _ _ _ /-- The functor `(S, F) ⥤ (G(S), F ⋙ G)`. -/ @[simps] def post (S : C) (F : B ⥤ C) (G : C ⥤ D) : StructuredArrow S F ⥤ StructuredArrow (G.obj S) (F ⋙ G) where obj X := StructuredArrow.mk (G.map X.hom) map f := StructuredArrow.homMk f.right (by simp [Functor.comp_map, ← G.map_comp, ← f.w]) instance (S : C) (F : B ⥤ C) (G : C ⥤ D) : (post S F G).Faithful where map_injective {_ _} _ _ h := by simpa [ext_iff] using h instance (S : C) (F : B ⥤ C) (G : C ⥤ D) [G.Faithful] : (post S F G).Full where map_surjective f := ⟨homMk f.right (G.map_injective (by simpa using f.w.symm)), by simp⟩ instance (S : C) (F : B ⥤ C) (G : C ⥤ D) [G.Full] : (post S F G).EssSurj where mem_essImage h := ⟨mk (G.preimage h.hom), ⟨isoMk (Iso.refl _) (by simp)⟩⟩ /-- If `G` is fully faithful, then `post S F G : (S, F) ⥤ (G(S), F ⋙ G)` is an equivalence. -/ instance isEquivalence_post (S : C) (F : B ⥤ C) (G : C ⥤ D) [G.Full] [G.Faithful] : (post S F G).IsEquivalence where section variable {L : D} {R : C ⥤ D} {L' : B} {R' : A ⥤ B} {F : C ⥤ A} {G : D ⥤ B} (α : L' ⟶ G.obj L) (β : R ⋙ G ⟶ F ⋙ R') /-- The functor `StructuredArrow L R ⥤ StructuredArrow L' R'` that is deduced from a natural transformation `R ⋙ G ⟶ F ⋙ R'` and a morphism `L' ⟶ G.obj L.` -/ @[simps!] def map₂ : StructuredArrow L R ⥤ StructuredArrow L' R' := Comma.map (F₁ := 𝟭 (Discrete PUnit)) (Discrete.natTrans (fun _ => α)) β instance faithful_map₂ [F.Faithful] : (map₂ α β).Faithful := by apply Comma.faithful_map instance full_map₂ [G.Faithful] [F.Full] [IsIso α] [IsIso β] : (map₂ α β).Full := by apply Comma.full_map instance essSurj_map₂ [F.EssSurj] [G.Full] [IsIso α] [IsIso β] : (map₂ α β).EssSurj := by apply Comma.essSurj_map noncomputable instance isEquivalenceMap₂ [F.IsEquivalence] [G.Faithful] [G.Full] [IsIso α] [IsIso β] : (map₂ α β).IsEquivalence := by apply Comma.isEquivalenceMap /-- The composition of two applications of `map₂` is naturally isomorphic to a single such one. -/ def map₂CompMap₂Iso {C' : Type u₆} [Category.{v₆} C'] {D' : Type u₅} [Category.{v₅} D'] {L'' : D'} {R'' : C' ⥤ D'} {F' : C' ⥤ C} {G' : D' ⥤ D} (α' : L ⟶ G'.obj L'') (β' : R'' ⋙ G' ⟶ F' ⋙ R) : map₂ α' β' ⋙ map₂ α β ≅ map₂ (α ≫ G.map α') ((Functor.associator _ _ _).inv ≫ Functor.whiskerRight β' _ ≫ (Functor.associator _ _ _).hom ≫ Functor.whiskerLeft _ β ≫ (Functor.associator _ _ _).inv) := NatIso.ofComponents (fun X => isoMk (Iso.refl _)) end /-- `StructuredArrow.post` is a special case of `StructuredArrow.map₂` up to natural isomorphism. -/ def postIsoMap₂ (S : C) (F : B ⥤ C) (G : C ⥤ D) : post S F G ≅ map₂ (F := 𝟭 _) (𝟙 _) (𝟙 (F ⋙ G)) := NatIso.ofComponents fun _ => isoMk <| Iso.refl _ /-- `StructuredArrow.map` is a special case of `StructuredArrow.map₂` up to natural isomorphism. -/ def mapIsoMap₂ {S S' : D} (f : S ⟶ S') : map (T := T) f ≅ map₂ (F := 𝟭 _) (G := 𝟭 _) f (𝟙 T) := NatIso.ofComponents fun _ => isoMk <| Iso.refl _ /-- `StructuredArrow.pre` is a special case of `StructuredArrow.map₂` up to natural isomorphism. -/ def preIsoMap₂ (S : D) (F : B ⥤ C) (G : C ⥤ D) : pre S F G ≅ map₂ (G := 𝟭 _) (𝟙 _) (𝟙 (F ⋙ G)) := NatIso.ofComponents fun _ => isoMk <| Iso.refl _ /-- A structured arrow is called universal if it is initial. -/ abbrev IsUniversal (f : StructuredArrow S T) := IsInitial f namespace IsUniversal variable {f g : StructuredArrow S T} theorem uniq (h : IsUniversal f) (η : f ⟶ g) : η = h.to g := h.hom_ext η (h.to g) /-- The family of morphisms out of a universal arrow. -/ def desc (h : IsUniversal f) (g : StructuredArrow S T) : f.right ⟶ g.right := (h.to g).right /-- Any structured arrow factors through a universal arrow. -/ @[reassoc (attr := simp)] theorem fac (h : IsUniversal f) (g : StructuredArrow S T) : f.hom ≫ T.map (h.desc g) = g.hom := Category.id_comp g.hom ▸ (h.to g).w.symm theorem hom_desc (h : IsUniversal f) {c : C} (η : f.right ⟶ c) : η = h.desc (mk <| f.hom ≫ T.map η) := let g := mk <| f.hom ≫ T.map η congrArg CommaMorphism.right (h.hom_ext (homMk η rfl : f ⟶ g) (h.to g)) /-- Two morphisms out of a universal `T`-structured arrow are equal if their image under `T` are equal after precomposing the universal arrow. -/ theorem hom_ext (h : IsUniversal f) {c : C} {η η' : f.right ⟶ c} (w : f.hom ≫ T.map η = f.hom ≫ T.map η') : η = η' := by rw [h.hom_desc η, h.hom_desc η', w] theorem existsUnique (h : IsUniversal f) (g : StructuredArrow S T) : ∃! η : f.right ⟶ g.right, f.hom ≫ T.map η = g.hom := ⟨h.desc g, h.fac g, fun f w ↦ h.hom_ext <| by simp [w]⟩ end IsUniversal end StructuredArrow /-- The category of `S`-costructured arrows with target `T : D` (here `S : C ⥤ D`), has as its objects `D`-morphisms of the form `S Y ⟶ T`, for some `Y : C`, and morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute. -/ -- We explicitly come from `PUnit.{1}` here to obtain the correct universe for morphisms of -- costructured arrows. def CostructuredArrow (S : C ⥤ D) (T : D) := Comma S (Functor.fromPUnit.{0} T) instance (S : C ⥤ D) (T : D) : Category (CostructuredArrow S T) := commaCategory namespace CostructuredArrow /-- The obvious projection functor from costructured arrows. -/ @[simps!] def proj (S : C ⥤ D) (T : D) : CostructuredArrow S T ⥤ C := Comma.fst _ _ variable {T T' T'' : D} {Y Y' Y'' : C} {S S' : C ⥤ D} @[ext] lemma hom_ext {X Y : CostructuredArrow S T} (f g : X ⟶ Y) (h : f.left = g.left) : f = g := CommaMorphism.ext h (Subsingleton.elim _ _) @[simp] theorem hom_eq_iff {X Y : CostructuredArrow S T} (f g : X ⟶ Y) : f = g ↔ f.left = g.left := ⟨fun h ↦ by rw [h], hom_ext _ _⟩ /-- Construct a costructured arrow from a morphism. -/ def mk (f : S.obj Y ⟶ T) : CostructuredArrow S T := ⟨Y, ⟨⟨⟩⟩, f⟩ @[simp] theorem mk_left (f : S.obj Y ⟶ T) : (mk f).left = Y := rfl @[simp] theorem mk_right (f : S.obj Y ⟶ T) : (mk f).right = ⟨⟨⟩⟩ := rfl @[simp] theorem mk_hom_eq_self (f : S.obj Y ⟶ T) : (mk f).hom = f := rfl @[reassoc] theorem w {A B : CostructuredArrow S T} (f : A ⟶ B) : S.map f.left ≫ B.hom = A.hom := by simp @[simp] theorem comp_left {X Y Z : CostructuredArrow S T} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).left = f.left ≫ g.left := rfl @[simp] theorem id_left (X : CostructuredArrow S T) : (𝟙 X : X ⟶ X).left = 𝟙 X.left := rfl @[simp] theorem eqToHom_left {X Y : CostructuredArrow S T} (h : X = Y) : (eqToHom h).left = eqToHom (by rw [h]) := by subst h simp only [eqToHom_refl, id_left] @[simp] theorem right_eq_id {X Y : CostructuredArrow S T} (f : X ⟶ Y) : f.right = 𝟙 X.right := rfl /-- To construct a morphism of costructured arrows, we need a morphism of the objects underlying the source, and to check that the triangle commutes. -/ @[simps! left] def homMk {f f' : CostructuredArrow S T} (g : f.left ⟶ f'.left) (w : S.map g ≫ f'.hom = f.hom := by cat_disch) : f ⟶ f' where left := g right := 𝟙 f.right theorem homMk_surjective {f f' : CostructuredArrow S T} (φ : f ⟶ f') : ∃ (ψ : f.left ⟶ f'.left) (hψ : S.map ψ ≫ f'.hom = f.hom), φ = CostructuredArrow.homMk ψ hψ := ⟨φ.left, CostructuredArrow.w φ, rfl⟩ /-- Given a costructured arrow `S(Y) ⟶ X`, and an arrow `Y' ⟶ Y'`, we can construct a morphism of costructured arrows given by `(S(Y) ⟶ X) ⟶ (S(Y') ⟶ S(Y) ⟶ X)`. -/ @[simps] def homMk' (f : CostructuredArrow S T) (g : Y' ⟶ f.left) : mk (S.map g ≫ f.hom) ⟶ f where left := g right := 𝟙 _ lemma homMk'_id (f : CostructuredArrow S T) : homMk' f (𝟙 f.left) = eqToHom (by cat_disch) := by ext simp [eqToHom_left] lemma homMk'_mk_id (f : S.obj Y ⟶ T) : homMk' (mk f) (𝟙 Y) = eqToHom (by simp) := homMk'_id _ lemma homMk'_comp (f : CostructuredArrow S T) (g : Y' ⟶ f.left) (g' : Y'' ⟶ Y') : homMk' f (g' ≫ g) = eqToHom (by simp) ≫ homMk' (mk (S.map g ≫ f.hom)) g' ≫ homMk' f g := by ext simp [eqToHom_left] lemma homMk'_mk_comp (f : S.obj Y ⟶ T) (g : Y' ⟶ Y) (g' : Y'' ⟶ Y') : homMk' (mk f) (g' ≫ g) = eqToHom (by simp) ≫ homMk' (mk (S.map g ≫ f)) g' ≫ homMk' (mk f) g := homMk'_comp _ _ _ /-- Variant of `homMk'` where both objects are applications of `mk`. -/ @[simps] def mkPrecomp (f : S.obj Y ⟶ T) (g : Y' ⟶ Y) : mk (S.map g ≫ f) ⟶ mk f where left := g right := 𝟙 _ lemma mkPrecomp_id (f : S.obj Y ⟶ T) : mkPrecomp f (𝟙 Y) = eqToHom (by simp) := by simp lemma mkPrecomp_comp (f : S.obj Y ⟶ T) (g : Y' ⟶ Y) (g' : Y'' ⟶ Y') : mkPrecomp f (g' ≫ g) = eqToHom (by simp) ≫ mkPrecomp (S.map g ≫ f) g' ≫ mkPrecomp f g := by simp /-- To construct an isomorphism of costructured arrows, we need an isomorphism of the objects underlying the source, and to check that the triangle commutes. -/ @[simps! hom_left inv_left] def isoMk {f f' : CostructuredArrow S T} (g : f.left ≅ f'.left) (w : S.map g.hom ≫ f'.hom = f.hom := by cat_disch) : f ≅ f' := Comma.isoMk g (eqToIso (by ext)) (by simpa using w) theorem obj_ext (x y : CostructuredArrow S T) (hl : x.left = y.left) (hh : S.map (eqToHom hl) ≫ y.hom = x.hom) : x = y := by cases x cases y cases hl cat_disch theorem ext {A B : CostructuredArrow S T} (f g : A ⟶ B) (h : f.left = g.left) : f = g := CommaMorphism.ext h (Subsingleton.elim _ _) theorem ext_iff {A B : CostructuredArrow S T} (f g : A ⟶ B) : f = g ↔ f.left = g.left := ⟨fun h => h ▸ rfl, ext f g⟩ instance proj_faithful : (proj S T).Faithful where map_injective {_ _} := ext theorem mono_of_mono_left {A B : CostructuredArrow S T} (f : A ⟶ B) [h : Mono f.left] : Mono f := (proj S T).mono_of_mono_map h /-- The converse of this is true with additional assumptions, see `epi_iff_epi_left`. -/ theorem epi_of_epi_left {A B : CostructuredArrow S T} (f : A ⟶ B) [h : Epi f.left] : Epi f := (proj S T).epi_of_epi_map h instance mono_homMk {A B : CostructuredArrow S T} (f : A.left ⟶ B.left) (w) [h : Mono f] : Mono (homMk f w) := (proj S T).mono_of_mono_map h instance epi_homMk {A B : CostructuredArrow S T} (f : A.left ⟶ B.left) (w) [h : Epi f] : Epi (homMk f w) := (proj S T).epi_of_epi_map h /-- Eta rule for costructured arrows. Prefer `CostructuredArrow.eta` for rewriting, as equality of objects tends to cause problems. -/ theorem eq_mk (f : CostructuredArrow S T) : f = mk f.hom := rfl /-- Eta rule for costructured arrows. -/ @[simps! hom_left inv_left] def eta (f : CostructuredArrow S T) : f ≅ mk f.hom := isoMk (Iso.refl _) lemma mk_surjective (f : CostructuredArrow S T) : ∃ (Y : C) (g : S.obj Y ⟶ T), f = mk g := ⟨_, _, eq_mk f⟩ /-- A morphism between target objects `T ⟶ T'` covariantly induces a functor between costructured arrows, `CostructuredArrow S T ⥤ CostructuredArrow S T'`. Ideally this would be described as a 2-functor from `D` (promoted to a 2-category with equations as 2-morphisms) to `Cat`. -/ @[simps!] def map (f : T ⟶ T') : CostructuredArrow S T ⥤ CostructuredArrow S T' := Comma.mapRight _ ((Functor.const _).map f) @[simp] theorem map_mk {f : S.obj Y ⟶ T} (g : T ⟶ T') : (map g).obj (mk f) = mk (f ≫ g) := rfl @[simp] theorem map_id {f : CostructuredArrow S T} : (map (𝟙 T)).obj f = f := by rw [eq_mk f] simp @[simp] theorem map_comp {f : T ⟶ T'} {f' : T' ⟶ T''} {h : CostructuredArrow S T} : (map (f ≫ f')).obj h = (map f').obj ((map f).obj h) := by rw [eq_mk h] simp /-- An isomorphism `T ≅ T'` induces an equivalence `CostructuredArrow S T ≌ CostructuredArrow S T'`. -/ @[simps!] def mapIso (i : T ≅ T') : CostructuredArrow S T ≌ CostructuredArrow S T' := Comma.mapRightIso _ ((Functor.const _).mapIso i) /-- A natural isomorphism `S ≅ S'` induces an equivalence `CostrucutredArrow S T ≌ CostructuredArrow S' T`. -/ @[simps!] def mapNatIso (i : S ≅ S') : CostructuredArrow S T ≌ CostructuredArrow S' T := Comma.mapLeftIso _ i instance proj_reflectsIsomorphisms : (proj S T).ReflectsIsomorphisms where reflects {Y Z} f t := ⟨⟨CostructuredArrow.homMk (inv ((proj S T).map f)) (by rw [Functor.map_inv, IsIso.inv_comp_eq]; simp), by constructor <;> ext <;> dsimp at t ⊢ <;> simp⟩⟩ open CategoryTheory.Limits /-- The identity costructured arrow is terminal. -/ noncomputable def mkIdTerminal [S.Full] [S.Faithful] : IsTerminal (mk (𝟙 (S.obj Y))) where lift c := homMk (S.preimage c.pt.hom) uniq := by rintro c m - ext apply S.map_injective simpa only [homMk_left, S.map_preimage, ← w m] using (Category.comp_id _).symm variable {A : Type u₃} [Category.{v₃} A] {B : Type u₄} [Category.{v₄} B] /-- The functor `(F ⋙ G, S) ⥤ (G, S)`. -/ @[simps!] def pre (F : B ⥤ C) (G : C ⥤ D) (S : D) : CostructuredArrow (F ⋙ G) S ⥤ CostructuredArrow G S := Comma.preLeft F G _ instance (F : B ⥤ C) (G : C ⥤ D) (S : D) [F.Faithful] : (pre F G S).Faithful := show (Comma.preLeft _ _ _).Faithful from inferInstance instance (F : B ⥤ C) (G : C ⥤ D) (S : D) [F.Full] : (pre F G S).Full := show (Comma.preLeft _ _ _).Full from inferInstance instance (F : B ⥤ C) (G : C ⥤ D) (S : D) [F.EssSurj] : (pre F G S).EssSurj := show (Comma.preLeft _ _ _).EssSurj from inferInstance /-- If `F` is an equivalence, then so is the functor `(F ⋙ G, S) ⥤ (G, S)`. -/ instance isEquivalence_pre (F : B ⥤ C) (G : C ⥤ D) (S : D) [F.IsEquivalence] : (pre F G S).IsEquivalence := Comma.isEquivalence_preLeft _ _ _ /-- The functor `(F, S) ⥤ (F ⋙ G, G(S))`. -/ @[simps] def post (F : B ⥤ C) (G : C ⥤ D) (S : C) : CostructuredArrow F S ⥤ CostructuredArrow (F ⋙ G) (G.obj S) where obj X := CostructuredArrow.mk (G.map X.hom) map f := CostructuredArrow.homMk f.left (by simp [Functor.comp_map, ← G.map_comp]) instance (F : B ⥤ C) (G : C ⥤ D) (S : C) : (post F G S).Faithful where map_injective {_ _} _ _ h := by simpa [ext_iff] using h instance (F : B ⥤ C) (G : C ⥤ D) (S : C) [G.Faithful] : (post F G S).Full where map_surjective f := ⟨homMk f.left (G.map_injective (by simpa using f.w)), by simp⟩ instance (F : B ⥤ C) (G : C ⥤ D) (S : C) [G.Full] : (post F G S).EssSurj where mem_essImage h := ⟨mk (G.preimage h.hom), ⟨isoMk (Iso.refl _) (by simp)⟩⟩ /-- If `G` is fully faithful, then `post F G S : (F, S) ⥤ (F ⋙ G, G(S))` is an equivalence. -/ instance isEquivalence_post (S : C) (F : B ⥤ C) (G : C ⥤ D) [G.Full] [G.Faithful] : (post F G S).IsEquivalence where section variable {U : A ⥤ B} {V : B} {F : C ⥤ A} {G : D ⥤ B} (α : F ⋙ U ⟶ S ⋙ G) (β : G.obj T ⟶ V) /-- The functor `CostructuredArrow S T ⥤ CostructuredArrow U V` that is deduced from a natural transformation `F ⋙ U ⟶ S ⋙ G` and a morphism `G.obj T ⟶ V` -/ @[simps!] def map₂ : CostructuredArrow S T ⥤ CostructuredArrow U V := Comma.map (F₂ := 𝟭 (Discrete PUnit)) α (Discrete.natTrans (fun _ => β)) instance faithful_map₂ [F.Faithful] : (map₂ α β).Faithful := by apply Comma.faithful_map instance full_map₂ [G.Faithful] [F.Full] [IsIso α] [IsIso β] : (map₂ α β).Full := by apply Comma.full_map instance essSurj_map₂ [F.EssSurj] [G.Full] [IsIso α] [IsIso β] : (map₂ α β).EssSurj := by apply Comma.essSurj_map noncomputable instance isEquivalenceMap₂ [F.IsEquivalence] [G.Faithful] [G.Full] [IsIso α] [IsIso β] : (map₂ α β).IsEquivalence := by apply Comma.isEquivalenceMap end /-- `CostructuredArrow.post` is a special case of `CostructuredArrow.map₂` up to natural isomorphism. -/ def postIsoMap₂ (S : C) (F : B ⥤ C) (G : C ⥤ D) : post F G S ≅ map₂ (F := 𝟭 _) (𝟙 (F ⋙ G)) (𝟙 _) := NatIso.ofComponents fun _ => isoMk <| Iso.refl _ /-- A costructured arrow is called universal if it is terminal. -/ abbrev IsUniversal (f : CostructuredArrow S T) := IsTerminal f namespace IsUniversal variable {f g : CostructuredArrow S T} theorem uniq (h : IsUniversal f) (η : g ⟶ f) : η = h.from g := h.hom_ext η (h.from g) /-- The family of morphisms into a universal arrow. -/ def lift (h : IsUniversal f) (g : CostructuredArrow S T) : g.left ⟶ f.left := (h.from g).left /-- Any costructured arrow factors through a universal arrow. -/ @[reassoc (attr := simp)] theorem fac (h : IsUniversal f) (g : CostructuredArrow S T) : S.map (h.lift g) ≫ f.hom = g.hom := Category.comp_id g.hom ▸ (h.from g).w theorem hom_desc (h : IsUniversal f) {c : C} (η : c ⟶ f.left) : η = h.lift (mk <| S.map η ≫ f.hom) := let g := mk <| S.map η ≫ f.hom congrArg CommaMorphism.left (h.hom_ext (homMk η rfl : g ⟶ f) (h.from g)) /-- Two morphisms into a universal `S`-costructured arrow are equal if their image under `S` are equal after postcomposing the universal arrow. -/ theorem hom_ext (h : IsUniversal f) {c : C} {η η' : c ⟶ f.left} (w : S.map η ≫ f.hom = S.map η' ≫ f.hom) : η = η' := by rw [h.hom_desc η, h.hom_desc η', w] theorem existsUnique (h : IsUniversal f) (g : CostructuredArrow S T) : ∃! η : g.left ⟶ f.left, S.map η ≫ f.hom = g.hom := ⟨h.lift g, h.fac g, fun f w ↦ h.hom_ext <| by simp [w]⟩ end IsUniversal end CostructuredArrow namespace Functor variable {E : Type u₃} [Category.{v₃} E] /-- Given `X : D` and `F : C ⥤ D`, to upgrade a functor `G : E ⥤ C` to a functor `E ⥤ StructuredArrow X F`, it suffices to provide maps `X ⟶ F.obj (G.obj Y)` for all `Y` making the obvious triangles involving all `F.map (G.map g)` commute. This is of course the same as providing a cone over `F ⋙ G` with cone point `X`, see `Functor.toStructuredArrowIsoToStructuredArrow`. -/ @[simps] def toStructuredArrow (G : E ⥤ C) (X : D) (F : C ⥤ D) (f : (Y : E) → X ⟶ F.obj (G.obj Y)) (h : ∀ {Y Z : E} (g : Y ⟶ Z), f Y ≫ F.map (G.map g) = f Z) : E ⥤ StructuredArrow X F where obj Y := StructuredArrow.mk (f Y) map g := StructuredArrow.homMk (G.map g) (h g) /-- Upgrading a functor `E ⥤ C` to a functor `E ⥤ StructuredArrow X F` and composing with the forgetful functor `StructuredArrow X F ⥤ C` recovers the original functor. -/ def toStructuredArrowCompProj (G : E ⥤ C) (X : D) (F : C ⥤ D) (f : (Y : E) → X ⟶ F.obj (G.obj Y)) (h : ∀ {Y Z : E} (g : Y ⟶ Z), f Y ≫ F.map (G.map g) = f Z) : G.toStructuredArrow X F f h ⋙ StructuredArrow.proj _ _ ≅ G := Iso.refl _ @[simp] lemma toStructuredArrow_comp_proj (G : E ⥤ C) (X : D) (F : C ⥤ D) (f : (Y : E) → X ⟶ F.obj (G.obj Y)) (h : ∀ {Y Z : E} (g : Y ⟶ Z), f Y ≫ F.map (G.map g) = f Z) : G.toStructuredArrow X F f h ⋙ StructuredArrow.proj _ _ = G := rfl /-- Given `F : C ⥤ D` and `X : D`, to upgrade a functor `G : E ⥤ C` to a functor `E ⥤ CostructuredArrow F X`, it suffices to provide maps `F.obj (G.obj Y) ⟶ X` for all `Y` making the obvious triangles involving all `F.map (G.map g)` commute. This is of course the same as providing a cocone over `F ⋙ G` with cocone point `X`, see `Functor.toCostructuredArrowIsoToCostructuredArrow`. -/ @[simps] def toCostructuredArrow (G : E ⥤ C) (F : C ⥤ D) (X : D) (f : (Y : E) → F.obj (G.obj Y) ⟶ X) (h : ∀ {Y Z : E} (g : Y ⟶ Z), F.map (G.map g) ≫ f Z = f Y) : E ⥤ CostructuredArrow F X where obj Y := CostructuredArrow.mk (f Y) map g := CostructuredArrow.homMk (G.map g) (h g) /-- Upgrading a functor `E ⥤ C` to a functor `E ⥤ CostructuredArrow F X` and composing with the forgetful functor `CostructuredArrow F X ⥤ C` recovers the original functor. -/ def toCostructuredArrowCompProj (G : E ⥤ C) (F : C ⥤ D) (X : D) (f : (Y : E) → F.obj (G.obj Y) ⟶ X) (h : ∀ {Y Z : E} (g : Y ⟶ Z), F.map (G.map g) ≫ f Z = f Y) : G.toCostructuredArrow F X f h ⋙ CostructuredArrow.proj _ _ ≅ G := Iso.refl _ @[simp] lemma toCostructuredArrow_comp_proj (G : E ⥤ C) (F : C ⥤ D) (X : D) (f : (Y : E) → F.obj (G.obj Y) ⟶ X) (h : ∀ {Y Z : E} (g : Y ⟶ Z), F.map (G.map g) ≫ f Z = f Y) : G.toCostructuredArrow F X f h ⋙ CostructuredArrow.proj _ _ = G := rfl end Functor open Opposite namespace StructuredArrow /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of structured arrows `d ⟶ F.obj c` to the category of costructured arrows `F.op.obj c ⟶ (op d)`. -/ @[simps] def toCostructuredArrow (F : C ⥤ D) (d : D) : (StructuredArrow d F)ᵒᵖ ⥤ CostructuredArrow F.op (op d) where obj X := @CostructuredArrow.mk _ _ _ _ _ (op X.unop.right) F.op X.unop.hom.op map f := CostructuredArrow.homMk f.unop.right.op (by simp [← op_comp]) /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of structured arrows `op d ⟶ F.op.obj c` to the category of costructured arrows `F.obj c ⟶ d`. -/ @[simps] def toCostructuredArrow' (F : C ⥤ D) (d : D) : (StructuredArrow (op d) F.op)ᵒᵖ ⥤ CostructuredArrow F d where obj X := @CostructuredArrow.mk _ _ _ _ _ (unop X.unop.right) F X.unop.hom.unop map f := CostructuredArrow.homMk f.unop.right.unop (by dsimp rw [← Quiver.Hom.unop_op (F.map (Quiver.Hom.unop f.unop.right)), ← unop_comp, ← F.op_map, ← f.unop.w] simp) end StructuredArrow namespace CostructuredArrow /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of costructured arrows `F.obj c ⟶ d` to the category of structured arrows `op d ⟶ F.op.obj c`. -/ @[simps] def toStructuredArrow (F : C ⥤ D) (d : D) : (CostructuredArrow F d)ᵒᵖ ⥤ StructuredArrow (op d) F.op where obj X := @StructuredArrow.mk _ _ _ _ _ (op X.unop.left) F.op X.unop.hom.op map f := StructuredArrow.homMk f.unop.left.op (by simp [← op_comp]) /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of costructured arrows `F.op.obj c ⟶ op d` to the category of structured arrows `d ⟶ F.obj c`. -/ @[simps] def toStructuredArrow' (F : C ⥤ D) (d : D) : (CostructuredArrow F.op (op d))ᵒᵖ ⥤ StructuredArrow d F where obj X := @StructuredArrow.mk _ _ _ _ _ (unop X.unop.left) F X.unop.hom.unop map f := StructuredArrow.homMk f.unop.left.unop (by dsimp rw [← Quiver.Hom.unop_op (F.map f.unop.left.unop), ← unop_comp, ← F.op_map, f.unop.w, Functor.const_obj_map] simp) end CostructuredArrow /-- For a functor `F : C ⥤ D` and an object `d : D`, the category of structured arrows `d ⟶ F.obj c` is contravariantly equivalent to the category of costructured arrows `F.op.obj c ⟶ op d`. -/ def structuredArrowOpEquivalence (F : C ⥤ D) (d : D) : (StructuredArrow d F)ᵒᵖ ≌ CostructuredArrow F.op (op d) where functor := StructuredArrow.toCostructuredArrow F d inverse := (CostructuredArrow.toStructuredArrow' F d).rightOp unitIso := NatIso.ofComponents (fun X => (StructuredArrow.isoMk (Iso.refl _)).op) fun {X Y} f => Quiver.Hom.unop_inj <| by apply CommaMorphism.ext <;> dsimp [StructuredArrow.isoMk, Comma.isoMk,StructuredArrow.homMk]; simp counitIso := NatIso.ofComponents (fun X => CostructuredArrow.isoMk (Iso.refl _)) fun {X Y} f => by apply CommaMorphism.ext <;> dsimp [CostructuredArrow.isoMk, Comma.isoMk, CostructuredArrow.homMk]; simp /-- For a functor `F : C ⥤ D` and an object `d : D`, the category of costructured arrows `F.obj c ⟶ d` is contravariantly equivalent to the category of structured arrows `op d ⟶ F.op.obj c`. -/ def costructuredArrowOpEquivalence (F : C ⥤ D) (d : D) : (CostructuredArrow F d)ᵒᵖ ≌ StructuredArrow (op d) F.op where functor := CostructuredArrow.toStructuredArrow F d inverse := (StructuredArrow.toCostructuredArrow' F d).rightOp unitIso := NatIso.ofComponents (fun X => (CostructuredArrow.isoMk (Iso.refl _)).op) fun {X Y} f => Quiver.Hom.unop_inj <| by apply CommaMorphism.ext <;> dsimp [CostructuredArrow.isoMk, CostructuredArrow.homMk, Comma.isoMk]; simp counitIso := NatIso.ofComponents (fun X => StructuredArrow.isoMk (Iso.refl _)) fun {X Y} f => by apply CommaMorphism.ext <;> dsimp [StructuredArrow.isoMk, StructuredArrow.homMk, Comma.isoMk]; simp section Pre variable {E : Type u₃} [Category.{v₃} E] (F : C ⥤ D) {G : D ⥤ E} {e : E} /-- The functor establishing the equivalence `StructuredArrow.preEquivalence`. -/ @[simps!] def StructuredArrow.preEquivalenceFunctor (f : StructuredArrow e G) : StructuredArrow f (pre e F G) ⥤ StructuredArrow f.right F where obj g := mk g.hom.right map φ := homMk φ.right.right <| by have := w φ simp only [Functor.const_obj_obj] at this ⊢ rw [← this, comp_right] simp /-- The inverse functor establishing the equivalence `StructuredArrow.preEquivalence`. -/ @[simps!] def StructuredArrow.preEquivalenceInverse (f : StructuredArrow e G) : StructuredArrow f.right F ⥤ StructuredArrow f (pre e F G) where obj g := mk (Y := mk (Y := g.right) (f.hom ≫ (G.map g.hom : G.obj f.right ⟶ (F ⋙ G).obj g.right))) (homMk g.hom) map φ := homMk <| homMk φ.right <| by simp only [Functor.const_obj_obj, Functor.comp_obj, mk_right, mk_left, mk_hom_eq_self, Functor.comp_map, Category.assoc, ← w φ, Functor.map_comp] /-- A structured arrow category on a `StructuredArrow.pre e F G` functor is equivalent to the structured arrow category on F -/ @[simps] def StructuredArrow.preEquivalence (f : StructuredArrow e G) : StructuredArrow f (pre e F G) ≌ StructuredArrow f.right F where functor := preEquivalenceFunctor F f inverse := preEquivalenceInverse F f unitIso := NatIso.ofComponents (fun _ => isoMk (isoMk (Iso.refl _))) counitIso := NatIso.ofComponents (fun _ => isoMk (Iso.refl _)) /-- The functor `StructuredArrow d T ⥤ StructuredArrow e (T ⋙ S)` that `u : e ⟶ S.obj d` induces via `StructuredArrow.map₂` can be expressed up to isomorphism by `StructuredArrow.preEquivalence` and `StructuredArrow.proj`. -/ def StructuredArrow.map₂IsoPreEquivalenceInverseCompProj {T : C ⥤ D} {S : D ⥤ E} {T' : C ⥤ E} (d : D) (e : E) (u : e ⟶ S.obj d) (α : T ⋙ S ⟶ T') : map₂ (F := 𝟭 _) u α ≅ (preEquivalence T (mk u)).inverse ⋙ proj (mk u) (pre _ T S) ⋙ map₂ (F := 𝟭 _) (G := 𝟭 _) (𝟙 _) α := NatIso.ofComponents fun _ => isoMk (Iso.refl _) /-- The functor establishing the equivalence `CostructuredArrow.preEquivalence`. -/ @[simps!] def CostructuredArrow.preEquivalence.functor (f : CostructuredArrow G e) : CostructuredArrow (pre F G e) f ⥤ CostructuredArrow F f.left where obj g := mk g.hom.left map φ := homMk φ.left.left <| by have := w φ simp only [Functor.const_obj_obj] at this ⊢ rw [← this, comp_left] simp /-- The inverse functor establishing the equivalence `CostructuredArrow.preEquivalence`. -/ @[simps!] def CostructuredArrow.preEquivalence.inverse (f : CostructuredArrow G e) : CostructuredArrow F f.left ⥤ CostructuredArrow (pre F G e) f where obj g := mk (Y := mk (Y := g.left) (G.map g.hom ≫ f.hom)) (homMk g.hom) map φ := homMk <| homMk φ.left <| by simp only [Functor.const_obj_obj, Functor.comp_obj, mk_left, Functor.comp_map, mk_hom_eq_self, ← w φ, Functor.map_comp, Category.assoc] /-- A costructured arrow category on a `CostructuredArrow.pre F G e` functor is equivalent to the costructured arrow category on F -/ def CostructuredArrow.preEquivalence (f : CostructuredArrow G e) : CostructuredArrow (pre F G e) f ≌ CostructuredArrow F f.left where functor := preEquivalence.functor F f inverse := preEquivalence.inverse F f unitIso := NatIso.ofComponents (fun _ => isoMk (isoMk (Iso.refl _))) counitIso := NatIso.ofComponents (fun _ => isoMk (Iso.refl _)) /-- The functor `CostructuredArrow T d ⥤ CostructuredArrow (T ⋙ S) e` that `u : S.obj d ⟶ e` induces via `CostructuredArrow.map₂` can be expressed up to isomorphism by `CostructuredArrow.preEquivalence` and `CostructuredArrow.proj`. -/ def CostructuredArrow.map₂IsoPreEquivalenceInverseCompProj (T : C ⥤ D) (S : D ⥤ E) (d : D) (e : E) (u : S.obj d ⟶ e) : map₂ (F := 𝟭 _) (U := T ⋙ S) (𝟙 (T ⋙ S)) u ≅ (preEquivalence T (mk u)).inverse ⋙ proj (pre T S _) (mk u) := NatIso.ofComponents fun _ => isoMk (Iso.refl _) end Pre section Prod section variable {C' : Type u₃} [Category.{v₃} C'] {D' : Type u₄} [Category.{v₄} D'] (S : D) (S' : D') (T : C ⥤ D) (T' : C' ⥤ D') @[reassoc (attr := simp)] theorem StructuredArrow.w_prod_fst {X Y : StructuredArrow (S, S') (T.prod T')} (f : X ⟶ Y) : X.hom.1 ≫ T.map f.right.1 = Y.hom.1 := congr_arg _root_.Prod.fst (StructuredArrow.w f) @[reassoc (attr := simp)] theorem StructuredArrow.w_prod_snd {X Y : StructuredArrow (S, S') (T.prod T')} (f : X ⟶ Y) : X.hom.2 ≫ T'.map f.right.2 = Y.hom.2 := congr_arg _root_.Prod.snd (StructuredArrow.w f) /-- Implementation; see `StructuredArrow.prodEquivalence`. -/ @[simps] def StructuredArrow.prodFunctor : StructuredArrow (S, S') (T.prod T') ⥤ StructuredArrow S T × StructuredArrow S' T' where obj f := ⟨.mk f.hom.1, .mk f.hom.2⟩ map η := ⟨StructuredArrow.homMk η.right.1 (by simp), StructuredArrow.homMk η.right.2 (by simp)⟩ /-- Implementation; see `StructuredArrow.prodEquivalence`. -/ @[simps] def StructuredArrow.prodInverse : StructuredArrow S T × StructuredArrow S' T' ⥤ StructuredArrow (S, S') (T.prod T') where obj f := .mk (Y := (f.1.right, f.2.right)) ⟨f.1.hom, f.2.hom⟩ map η := StructuredArrow.homMk ⟨η.1.right, η.2.right⟩ (by simp) /-- The natural equivalence `StructuredArrow (S, S') (T.prod T') ≌ StructuredArrow S T × StructuredArrow S' T'`. -/ @[simps] def StructuredArrow.prodEquivalence : StructuredArrow (S, S') (T.prod T') ≌ StructuredArrow S T × StructuredArrow S' T' where functor := StructuredArrow.prodFunctor S S' T T' inverse := StructuredArrow.prodInverse S S' T T' unitIso := NatIso.ofComponents (fun f => Iso.refl _) (by simp) counitIso := NatIso.ofComponents (fun f => Iso.refl _) (by simp) end section variable {C' : Type u₃} [Category.{v₃} C'] {D' : Type u₄} [Category.{v₄} D'] (S : C ⥤ D) (S' : C' ⥤ D') (T : D) (T' : D') @[reassoc (attr := simp)] theorem CostructuredArrow.w_prod_fst {A B : CostructuredArrow (S.prod S') (T, T')} (f : A ⟶ B) : S.map f.left.1 ≫ B.hom.1 = A.hom.1 := congr_arg _root_.Prod.fst (CostructuredArrow.w f) @[reassoc (attr := simp)] theorem CostructuredArrow.w_prod_snd {A B : CostructuredArrow (S.prod S') (T, T')} (f : A ⟶ B) : S'.map f.left.2 ≫ B.hom.2 = A.hom.2 := congr_arg _root_.Prod.snd (CostructuredArrow.w f) /-- Implementation; see `CostructuredArrow.prodEquivalence`. -/ @[simps] def CostructuredArrow.prodFunctor : CostructuredArrow (S.prod S') (T, T') ⥤ CostructuredArrow S T × CostructuredArrow S' T' where obj f := ⟨.mk f.hom.1, .mk f.hom.2⟩ map η := ⟨CostructuredArrow.homMk η.left.1 (by simp), CostructuredArrow.homMk η.left.2 (by simp)⟩ /-- Implementation; see `CostructuredArrow.prodEquivalence`. -/ @[simps] def CostructuredArrow.prodInverse : CostructuredArrow S T × CostructuredArrow S' T' ⥤ CostructuredArrow (S.prod S') (T, T') where obj f := .mk (Y := (f.1.left, f.2.left)) ⟨f.1.hom, f.2.hom⟩ map η := CostructuredArrow.homMk ⟨η.1.left, η.2.left⟩ (by simp) /-- The natural equivalence `CostructuredArrow (S.prod S') (T, T') ≌ CostructuredArrow S T × CostructuredArrow S' T'`. -/ @[simps] def CostructuredArrow.prodEquivalence : CostructuredArrow (S.prod S') (T, T') ≌ CostructuredArrow S T × CostructuredArrow S' T' where functor := CostructuredArrow.prodFunctor S S' T T' inverse := CostructuredArrow.prodInverse S S' T T' unitIso := NatIso.ofComponents (fun f => Iso.refl _) (by simp) counitIso := NatIso.ofComponents (fun f => Iso.refl _) (by simp) end end Prod end CategoryTheory
InstanceTransparency.lean
import Mathlib.Data.Real.Basic /-! # Test transparency level of `Div` field in `DivInvMonoid` It is desirable that particular `DivInvMonoid`s have their `Div` instance not unfold at `.instance` transparency level, in the same way that the `Div` field of a generic `DivInvMonoid` does not. To ensure this, in examples where the `Div` field is defined as `fun a b ↦ a * b⁻¹`, we hide this under one layer of other function (so for example the `Div` instance for `Rat` is defined to be `⟨Rat.div⟩`, where `Rat.div` is defined to be `fun a b ↦ a * b⁻¹`). This file checks that this and similar tricks have had the desired effect: `with_reducible_and_instances apply mul_le_mul` fails although `apply mul_le_mul` succeeds. -/ private axiom test_sorry : ∀ {α}, α set_option autoImplicit true example {a b : α} [Field α] [LinearOrder α] [IsStrictOrderedRing α] : a / 2 ≤ b / 2 := by fail_if_success with_reducible_and_instances apply mul_le_mul -- fails, as desired exact test_sorry example {a b : ℚ} : a / 2 ≤ b / 2 := by fail_if_success with_reducible_and_instances apply mul_le_mul -- fails, as desired apply mul_le_mul repeat exact test_sorry example {a b : ℝ} : a / 2 ≤ b / 2 := by fail_if_success with_reducible_and_instances apply mul_le_mul -- fails, as desired apply mul_le_mul repeat exact test_sorry
ConnectedComponents.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.Data.List.Chain import Mathlib.CategoryTheory.IsConnected import Mathlib.CategoryTheory.Sigma.Basic import Mathlib.CategoryTheory.ObjectProperty.FullSubcategory /-! # Connected components of a category Defines a type `ConnectedComponents J` indexing the connected components of a category, and the full subcategories giving each connected component: `Component j : Type u₁`. We show that each `Component j` is in fact connected. We show every category can be expressed as a disjoint union of its connected components, in particular `Decomposed J` is the category (definitionally) given by the sigma-type of the connected components of `J`, and it is shown that this is equivalent to `J`. -/ universe v₁ v₂ v₃ u₁ u₂ noncomputable section open CategoryTheory.Category namespace CategoryTheory attribute [instance 100] IsConnected.is_nonempty variable {J : Type u₁} [Category.{v₁} J] /-- This type indexes the connected components of the category `J`. -/ def ConnectedComponents (J : Type u₁) [Category.{v₁} J] : Type u₁ := Quotient (Zigzag.setoid J) /-- The map `ConnectedComponents J → ConnectedComponents K` induced by a functor `J ⥤ K`. -/ def Functor.mapConnectedComponents {K : Type u₂} [Category.{v₂} K] (F : J ⥤ K) (x : ConnectedComponents J) : ConnectedComponents K := x |> Quotient.lift (Quotient.mk (Zigzag.setoid _) ∘ F.obj) (fun _ _ ↦ Quot.sound ∘ zigzag_obj_of_zigzag F) @[simp] lemma Functor.mapConnectedComponents_mk {K : Type u₂} [Category.{v₂} K] (F : J ⥤ K) (j : J) : F.mapConnectedComponents (Quotient.mk _ j) = Quotient.mk _ (F.obj j) := rfl instance [Inhabited J] : Inhabited (ConnectedComponents J) := ⟨Quotient.mk'' default⟩ /-- Every function from connected components of a category gives a functor to discrete category -/ def ConnectedComponents.functorToDiscrete (X : Type*) (f : ConnectedComponents J → X) : J ⥤ Discrete X where obj Y := Discrete.mk (f (Quotient.mk (Zigzag.setoid _) Y)) map g := Discrete.eqToHom (congrArg f (Quotient.sound (Zigzag.of_hom g))) /-- Every functor to a discrete category gives a function from connected components -/ def ConnectedComponents.liftFunctor (J) [Category J] {X : Type*} (F : J ⥤ Discrete X) : (ConnectedComponents J → X) := Quotient.lift (fun c => (F.obj c).as) (fun _ _ h => eq_of_zigzag X (zigzag_obj_of_zigzag F h)) /-- Functions from connected components and functors to discrete category are in bijection -/ def ConnectedComponents.typeToCatHomEquiv (J) [Category J] (X : Type*) : (ConnectedComponents J → X) ≃ (J ⥤ Discrete X) where toFun := ConnectedComponents.functorToDiscrete _ invFun := ConnectedComponents.liftFunctor _ left_inv f := funext fun x ↦ by obtain ⟨x, h⟩ := Quotient.exists_rep x rw [← h] rfl right_inv fctr := Functor.hext (fun _ ↦ rfl) (fun c d f ↦ have : Subsingleton (fctr.obj c ⟶ fctr.obj d) := Discrete.instSubsingletonDiscreteHom _ _ (Subsingleton.elim (fctr.map f) _).symm.heq) /-- Given an index for a connected component, this is the property of the objects which belong to this component. -/ def ConnectedComponents.objectProperty (j : ConnectedComponents J) : ObjectProperty J := fun k => Quotient.mk'' k = j /-- Given an index for a connected component, produce the actual component as a full subcategory. -/ abbrev ConnectedComponents.Component (j : ConnectedComponents J) : Type u₁ := j.objectProperty.FullSubcategory /-- The inclusion functor from a connected component to the whole category. -/ abbrev ConnectedComponents.ι (j : ConnectedComponents J) : j.Component ⥤ J := j.objectProperty.ι /-- The connected component of an object in a category. -/ abbrev ConnectedComponents.mk (j : J) : ConnectedComponents J := Quotient.mk'' j @[deprecated (since := "2025-03-04")] alias Component := ConnectedComponents.Component @[deprecated (since := "2025-03-04")] alias Component.ι := ConnectedComponents.ι /-- Each connected component of the category is nonempty. -/ instance (j : ConnectedComponents J) : Nonempty j.Component := by induction j using Quotient.inductionOn' exact ⟨⟨_, rfl⟩⟩ instance (j : ConnectedComponents J) : Inhabited j.Component := Classical.inhabited_of_nonempty' /-- Each connected component of the category is connected. -/ instance (j : ConnectedComponents J) : IsConnected j.Component := by -- Show it's connected by constructing a zigzag (in `j.Component`) between any two objects apply isConnected_of_zigzag rintro ⟨j₁, hj₁⟩ ⟨j₂, rfl⟩ -- We know that the underlying objects j₁ j₂ have some zigzag between them in `J` have h₁₂ : Zigzag j₁ j₂ := Quotient.exact' hj₁ -- Get an explicit zigzag as a list rcases List.exists_chain_of_relationReflTransGen h₁₂ with ⟨l, hl₁, hl₂⟩ -- Everything which has a zigzag to j₂ can be lifted to the same component as `j₂`. let f : ∀ x, Zigzag x j₂ → (ConnectedComponents.mk j₂).Component := fun x h => ⟨x, Quotient.sound' h⟩ -- Everything in our chosen zigzag from `j₁` to `j₂` has a zigzag to `j₂`. have hf : ∀ a : J, a ∈ l → Zigzag a j₂ := by intro i hi apply hl₁.backwards_induction (fun t => Zigzag t j₂) _ hl₂ _ _ _ (List.mem_of_mem_tail hi) · intro j k apply Relation.ReflTransGen.head · apply Relation.ReflTransGen.refl -- Now lift the zigzag from `j₁` to `j₂` in `J` to the same thing in `j.Component`. refine ⟨l.pmap f hf, ?_, by grind⟩ refine @List.chain_pmap_of_chain _ _ _ _ _ f (fun x y _ _ h => ?_) _ _ hl₁ h₁₂ _ exact zag_of_zag_obj (ConnectedComponents.ι _) h /-- The disjoint union of `J`s connected components, written explicitly as a sigma-type with the category structure. This category is equivalent to `J`. -/ abbrev Decomposed (J : Type u₁) [Category.{v₁} J] := Σ j : ConnectedComponents J, j.Component -- This name may cause clashes further down the road, and so might need to be changed. /-- The inclusion of each component into the decomposed category. This is just `sigma.incl` but having this abbreviation helps guide typeclass search to get the right category instance on `decomposed J`. -/ abbrev inclusion (j : ConnectedComponents J) : j.Component ⥤ Decomposed J := Sigma.incl _ /-- The forward direction of the equivalence between the decomposed category and the original. -/ @[simps!] def decomposedTo (J : Type u₁) [Category.{v₁} J] : Decomposed J ⥤ J := Sigma.desc ConnectedComponents.ι @[simp] theorem inclusion_comp_decomposedTo (j : ConnectedComponents J) : inclusion j ⋙ decomposedTo J = ConnectedComponents.ι j := rfl instance : (decomposedTo J).Full where map_surjective := by rintro ⟨j', X, hX⟩ ⟨k', Y, hY⟩ f dsimp at f have : j' = k' := by rw [← hX, ← hY, Quotient.eq''] exact Relation.ReflTransGen.single (Or.inl ⟨f⟩) subst this exact ⟨Sigma.SigmaHom.mk f, rfl⟩ instance : (decomposedTo J).Faithful where map_injective := by rintro ⟨_, j, rfl⟩ ⟨_, k, hY⟩ ⟨f⟩ ⟨_⟩ rfl rfl instance : (decomposedTo J).EssSurj where mem_essImage j := ⟨⟨_, j, rfl⟩, ⟨Iso.refl _⟩⟩ instance : (decomposedTo J).IsEquivalence where /-- This gives that any category is equivalent to a disjoint union of connected categories. -/ @[simps! functor] def decomposedEquiv : Decomposed J ≌ J := (decomposedTo J).asEquivalence end CategoryTheory
CoreAttrs.lean
/- Copyright (c) 2024 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Tactic.GCongr.Core /-! # gcongr attributes for lemmas up in the import chain In this file we add `gcongr` attribute to lemmas in `Lean.Init`. We may add lemmas from other files imported by `Mathlib/Tactic/GCongr/Core` later. -/ namespace Mathlib.Tactic.GCongr variable {a b c : Prop} lemma imp_trans (h : a → b) : (b → c) → a → c := fun g ha => g (h ha) lemma imp_right_mono (h : a → b → c) : (a → b) → a → c := fun h' ha => h ha (h' ha) lemma and_right_mono (h : a → b → c) : (a ∧ b) → a ∧ c := fun ⟨ha, hb⟩ => ⟨ha, h ha hb⟩ attribute [gcongr] mt Or.imp Or.imp_left Or.imp_right And.imp And.imp_left GCongr.and_right_mono imp_imp_imp GCongr.imp_trans GCongr.imp_right_mono forall_imp Exists.imp List.Sublist.append List.Sublist.append_left List.Sublist.append_right List.Sublist.reverse List.drop_sublist_drop_left List.Sublist.drop List.Perm.append_left List.Perm.append_right List.Perm.append List.Perm.map end Mathlib.Tactic.GCongr
TermCongr.lean
/- Copyright (c) 2023 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Lean.Expr.Basic import Mathlib.Lean.Meta.CongrTheorems import Mathlib.Logic.Basic import Mathlib.Tactic.CongrExclamation /-! # `congr(...)` congruence quotations This module defines a term elaborator for generating congruence lemmas from patterns written using quotation syntax. One can write `congr($hf $hx)` with `hf : f = f'` and `hx : x = x'` to get `f x = f' x'`. While in simple cases it might be possible to use `congr_arg` or `congr_fun`, congruence quotations are more general, since for example `f` could have implicit arguments, complicated dependent types, and subsingleton instance arguments such as `Decidable` or `Fintype`. The implementation strategy is the following: 1. The pattern is elaborated twice, once with each hole replaced by the LHS and again with each hole replaced by the RHS. We do not force the hole to have any particular type while elaborating, but if the hole has a type with an obvious LHS or RHS, then we propagate this information outward. We use `Mathlib.Tactic.TermCongr.cHole` with metadata for these replacements to hold onto the hole itself. 2. Once the pattern has been elaborated twice, we unify them against the respective LHS and RHS of the target type if the target has a type with an obvious LHS and RHS. This can fill in some metavariables and help typeclass inference make progress. 3. Then we simultaneously walk along the elaborated LHS and RHS expressions to generate a congruence. When we reach `cHole`s, we make sure they elaborated in a compatible way. Each `Expr` type has some logic to come up with a suitable congruence. For applications we use a version of `Lean.Meta.mkHCongrWithArity` that tries to fill in some of the equality proofs using subsingleton lemmas. The point of elaborating the expression twice is that we let the elaborator handle activities like synthesizing instances, etc., specialized to LHS or RHS, without trying to derive one side from the other. During development there was a version using `simp` transformations, but there was no way to inform `simp` about the expected RHS, which could cause `simp` to fail because it eagerly wants to solve for instance arguments. The current version is able to use the expected LHS and RHS to fill in arguments before solving for instance arguments. -/ universe u namespace Mathlib.Tactic.TermCongr open Lean Elab Meta initialize registerTraceClass `Elab.congr /-- `congr(expr)` generates a congruence from an expression containing congruence holes of the form `$h` or `$(h)`. In these congruence holes, `h : a = b` indicates that, in the generated congruence, on the left-hand side `a` is substituted for `$h` and on the right-hand side `b` is substituted for `$h`. For example, if `h : a = b` then `congr(1 + $h) : 1 + a = 1 + b`. This is able to make use of the expected type, for example `(congr(_ + $h) : 1 + _ = _)` with `h : x = y` gives `1 + x = 1 + y`. The expected type can be an `Iff`, `Eq`, or `HEq`. If there is no expected type, then it generates an equality. Note: the process of generating a congruence lemma involves elaborating the pattern using terms with attached metadata and a reducible wrapper. We try to avoid doing so, but these terms can leak into the local context through unification. This can potentially break tactics that are sensitive to metadata or reducible functions. Please report anything that goes wrong with `congr(...)` lemmas on Zulip. For debugging, you can set `set_option trace.Elab.congr true`. -/ syntax (name := termCongr) "congr(" withoutForbidden(ppDedentIfGrouped(term)) ")" : term /-! ### Congruence holes This section sets up the way congruence holes are elaborated for `congr(...)` quotations. The basic problem is that if we have `$h` with `h : x = y`, we need to elaborate it once as `x` and once as `y`, and in both cases the term needs to remember that it's associated to `h`. -/ /-- Key for congruence hole metadata. For a `Bool` recording whether this hole is for the LHS elaboration. -/ private def congrHoleForLhsKey : Name := decl_name% /-- Key for congruence hole metadata. For a `Nat` recording how old this congruence hole is, to prevent reprocessing them if they leak into the local context. -/ private def congrHoleIndex : Name := decl_name% /-- For holding onto the hole's value along with the value of either the LHS or RHS of the hole. These occur wrapped in metadata so that they always appear as function application with exactly four arguments. Note that there is no relation between `val` and the proof. We need to decouple these to support letting the proof's elaboration be deferred until we know whether we want an iff, eq, or heq, while also allowing it to choose to elaborate as an iff, eq, or heq. Later, the congruence generator handles any discrepancies. See `Mathlib/Tactic/TermCongr/CongrResult.lean`. -/ @[reducible, nolint unusedArguments] def cHole {α : Sort u} (val : α) {p : Prop} (_pf : p) : α := val /-- For error reporting purposes, make the hole pretty print as its value. We can still see that it is a hole in the info view on mouseover. -/ @[app_unexpander cHole] def unexpandCHole : Lean.PrettyPrinter.Unexpander | `($_ $val $_) => pure val | _ => throw () /-- Create the congruence hole. Used by `elabCHole`. Saves the current mvarCounter as a proxy for age. We use this to avoid reprocessing old congruence holes that happened to leak into the local context. -/ def mkCHole (forLhs : Bool) (val pf : Expr) : MetaM Expr := do -- Create a metavariable to bump the mvarCounter. discard <| mkFreshTypeMVar let d : MData := KVMap.empty |>.insert congrHoleForLhsKey forLhs |>.insert congrHoleIndex (← getMCtx).mvarCounter return Expr.mdata d <| ← mkAppM ``cHole #[val, pf] /-- If the expression is a congruence hole, returns `(forLhs, sideVal, pf)`. If `mvarCounterSaved?` is not none, then only returns the hole if it is at least as recent. -/ def cHole? (e : Expr) (mvarCounterSaved? : Option Nat := none) : Option (Bool × Expr × Expr) := do match e with | .mdata d e' => let forLhs : Bool ← d.get? congrHoleForLhsKey let mvarCounter : Nat ← d.get? congrHoleIndex if let some mvarCounterSaved := mvarCounterSaved? then guard <| mvarCounterSaved ≤ mvarCounter let #[_, val, _, pf] := e'.getAppArgs | failure return (forLhs, val, pf) | _ => none /-- Returns any subexpression that is a recent congruence hole. -/ def hasCHole (mvarCounterSaved : Nat) (e : Expr) : Option Expr := e.find? fun e' => (cHole? e' mvarCounterSaved).isSome /-- Eliminate all congruence holes from an expression by replacing them with their values. -/ def removeCHoles (e : Expr) : Expr := e.replace fun e' => if let some (_, val, _) := cHole? e' then val else none /-- Elaborates a congruence hole and returns either the left-hand side or the right-hand side, annotated with information necessary to generate a congruence lemma. -/ def elabCHole (h : Syntax) (forLhs : Bool) (expectedType? : Option Expr) : Term.TermElabM Expr := do let pf ← Term.elabTerm h none let pfTy ← inferType pf -- Ensure that `pfTy` is a proposition unless ← isDefEq (← inferType pfTy) (.sort .zero) do throwError "Hole has type{indentD pfTy}\nbut is expected to be a Prop" if let some (_, lhs, _, rhs) := (← whnf pfTy).sides? then let val := if forLhs then lhs else rhs if let some expectedType := expectedType? then -- Propagate type hint: discard <| isDefEq expectedType (← inferType val) mkCHole forLhs val pf else -- Since `pf` doesn't yet have sides, we resort to the value and the proof being decoupled. -- These will be unified during congruence generation. mkCHole forLhs (← mkFreshExprMVar expectedType?) pf /-- (Internal for `congr(...)`) Elaborates to an expression satisfying `cHole?` that equals the LHS or RHS of `h`, if the LHS or RHS is available after elaborating `h`. Uses the expected type as a hint. -/ syntax (name := cHoleExpand) "cHole% " (&"lhs" <|> &"rhs") term : term @[term_elab cHoleExpand, inherit_doc cHoleExpand] def elabCHoleExpand : Term.TermElab := fun stx expectedType? => match stx with | `(cHole% lhs $h) => elabCHole h true expectedType? | `(cHole% rhs $h) => elabCHole h false expectedType? | _ => throwUnsupportedSyntax /-- Replace all `term` antiquotations in a term using the given `expand` function. -/ def processAntiquot (t : Term) (expand : Term → Term.TermElabM Term) : Term.TermElabM Term := do let t' ← t.raw.replaceM fun s => do if s.isAntiquots then let ks := s.antiquotKinds unless ks.any (fun (k, _) => k == `term) do throwErrorAt s "Expecting term" let h : Term := ⟨s.getCanonicalAntiquot.getAntiquotTerm⟩ expand h else pure none return ⟨t'⟩ /-- Given the pattern `t` in `congr(t)`, elaborate it for the given side by replacing antiquotations with `cHole%` terms, and ensure the elaborated term is of the expected type. -/ def elaboratePattern (t : Term) (expectedType? : Option Expr) (forLhs : Bool) : Term.TermElabM Expr := Term.withoutErrToSorry do let t' ← processAntiquot t (fun h => if forLhs then `(cHole% lhs $h) else `(cHole% rhs $h)) Term.elabTermEnsuringType t' expectedType? /-! ### Congruence generation -/ /-- Ensures the expected type is an equality. Returns the equality. The returned expression satisfies `Lean.Expr.eq?`. -/ def mkEqForExpectedType (expectedType? : Option Expr) : MetaM Expr := do let u ← mkFreshLevelMVar let ty ← mkFreshExprMVar (mkSort u) let eq := mkApp3 (mkConst ``Eq [u]) ty (← mkFreshExprMVar ty) (← mkFreshExprMVar ty) if let some expectedType := expectedType? then unless ← isDefEq expectedType eq do throwError m!"Type{indentD expectedType}\nis expected to be an equality." return eq /-- Ensures the expected type is a HEq. Returns the HEq. This expression satisfies `Lean.Expr.heq?`. -/ def mkHEqForExpectedType (expectedType? : Option Expr) : MetaM Expr := do let u ← mkFreshLevelMVar let tya ← mkFreshExprMVar (mkSort u) let tyb ← mkFreshExprMVar (mkSort u) let heq := mkApp4 (mkConst ``HEq [u]) tya (← mkFreshExprMVar tya) tyb (← mkFreshExprMVar tyb) if let some expectedType := expectedType? then unless ← isDefEq expectedType heq do throwError m!"Type{indentD expectedType}\nis expected to be a `HEq`." return heq /-- Ensures the expected type is an iff. Returns the iff. This expression satisfies `Lean.Expr.iff?`. -/ def mkIffForExpectedType (expectedType? : Option Expr) : MetaM Expr := do let a ← mkFreshExprMVar (Expr.sort .zero) let b ← mkFreshExprMVar (Expr.sort .zero) let iff := mkApp2 (Expr.const `Iff []) a b if let some expectedType := expectedType? then unless ← isDefEq expectedType iff do throwError m!"Type{indentD expectedType}\nis expected to be an `Iff`." return iff /-- Make sure that the expected type of `pf` is an iff by unification. -/ def ensureIff (pf : Expr) : MetaM Expr := do discard <| mkIffForExpectedType (← inferType pf) return pf /-- A request for a type of congruence lemma from a `CongrResult`. -/ inductive CongrType | eq | heq /-- A congruence lemma between two expressions. The proof is generated dynamically, depending on whether the resulting lemma should be an `Eq` or a `HEq`. If generating a proof impossible, then the generator can throw an error. This can be due to either an `Eq` proof being impossible or due to the lhs/rhs not being defeq to the lhs/rhs of the generated proof, which can happen for user-supplied congruence holes. This complexity is to support two features: 1. The user is free to supply Iff, Eq, and HEq lemmas in congruence holes, and we're able to transform them into whatever is appropriate for a given congruence lemma. 2. If the congruence hole is a metavariable, then we can specialize that hole to an Iff, Eq, or HEq depending on what's necessary at that site. -/ structure CongrResult where /-- The left-hand side of the congruence result. -/ lhs : Expr /-- The right-hand side of the congruence result. -/ rhs : Expr /-- A generator for an `Eq lhs rhs` or `HEq lhs rhs` proof. If such a proof is impossible, the generator can throw an error. The inferred type of the generated proof needs only be defeq to `Eq lhs rhs` or `HEq lhs rhs`. This function can assign metavariables when constructing the proof. If `pf? = none`, then `lhs` and `rhs` are defeq, and the proof is by reflexivity. -/ (pf? : Option (CongrType → MetaM Expr)) /-- Returns whether the proof is by reflexivity. Such congruence proofs are trivial. -/ def CongrResult.isRfl (res : CongrResult) : Bool := res.pf?.isNone /-- Returns the proof that `lhs = rhs`. Fails if the `CongrResult` is inapplicable. Throws an error if the `lhs` and `rhs` have non-defeq types. If `pf? = none`, this returns the `rfl` proof. -/ def CongrResult.eq (res : CongrResult) : MetaM Expr := do unless ← isDefEq (← inferType res.lhs) (← inferType res.rhs) do throwError "Expecting{indentD res.lhs}\nand{indentD res.rhs}\n\ to have definitionally equal types." match res.pf? with | some pf => pf .eq | none => mkEqRefl res.lhs /-- Returns the proof that `lhs ≍ rhs`. Fails if the `CongrResult` is inapplicable. If `pf? = none`, this returns the `rfl` proof. -/ def CongrResult.heq (res : CongrResult) : MetaM Expr := do match res.pf? with | some pf => pf .heq | none => mkHEqRefl res.lhs /-- Returns a proof of `lhs ↔ rhs`. Uses `CongrResult.eq`. -/ def CongrResult.iff (res : CongrResult) : MetaM Expr := do unless ← Meta.isProp res.lhs do throwError "Expecting{indentD res.lhs}\nto be a proposition." return mkApp3 (.const ``iff_of_eq []) res.lhs res.rhs (← res.eq) /-- Combine two congruence proofs using transitivity. Does not check that `res1.rhs` is defeq to `res2.lhs`. If both `res1` and `res2` are trivial then the result is trivial. -/ def CongrResult.trans (res1 res2 : CongrResult) : CongrResult where lhs := res1.lhs rhs := res2.rhs pf? := if res1.isRfl then res2.pf? else if res2.isRfl then res1.pf? else some fun | .eq => do mkEqTrans (← res1.eq) (← res2.eq) | .heq => do mkHEqTrans (← res1.heq) (← res2.heq) /-- Make a `CongrResult` from a LHS, a RHS, and a proof of an Iff, Eq, or HEq. The proof is allowed to have a metavariable for its type. Validates the inputs and throws errors in the `pf?` function. The `pf?` function is responsible for finally unifying the type of `pf` with `lhs` and `rhs`. -/ def CongrResult.mk' (lhs rhs : Expr) (pf : Expr) : CongrResult where lhs := lhs rhs := rhs pf? := if (isRefl? pf).isSome then none else some fun | .eq => do ensureSidesDefeq (← toEqPf) | .heq => do ensureSidesDefeq (← toHEqPf) where /-- Given a `pf` of an `Iff`, `Eq`, or `HEq`, return a proof of `Eq`. If `pf` is not obviously any of these, weakly try inserting `propext` to make an `Iff` and otherwise unify the type with `Eq`. -/ toEqPf : MetaM Expr := do let ty ← whnf (← inferType pf) if let some .. := ty.iff? then mkPropExt pf else if let some .. := ty.eq? then return pf else if let some (lhsTy, _, rhsTy, _) := ty.heq? then unless ← isDefEq lhsTy rhsTy do throwError "Cannot turn HEq proof into an equality proof. Has type{indentD ty}" mkAppM ``eq_of_heq #[pf] else if ← Meta.isProp lhs then mkPropExt (← ensureIff pf) else discard <| mkEqForExpectedType (← inferType pf) return pf /-- Given a `pf` of an `Iff`, `Eq`, or `HEq`, return a proof of `HEq`. If `pf` is not obviously any of these, weakly try making it be an `Eq` or an `Iff`, and otherwise make it be a `HEq`. -/ toHEqPf : MetaM Expr := do let ty ← whnf (← inferType pf) if let some .. := ty.iff? then mkAppM ``heq_of_eq #[← mkPropExt pf] else if let some .. := ty.eq? then mkAppM ``heq_of_eq #[pf] else if let some .. := ty.heq? then return pf else if ← withNewMCtxDepth <| isDefEq (← inferType lhs) (← inferType rhs) then mkAppM ``heq_of_eq #[← toEqPf] else discard <| mkHEqForExpectedType (← inferType pf) return pf /-- Get the sides of the type of `pf` and unify them with the respective `lhs` and `rhs`. -/ ensureSidesDefeq (pf : Expr) : MetaM Expr := do let pfTy ← inferType pf let some (_, lhs', _, rhs') := (← whnf pfTy).sides? | panic! "Unexpectedly did not generate an eq or heq" unless ← isDefEq lhs lhs' do throwError "Congruence hole has type{indentD pfTy}\n\ but its left-hand side is not definitionally equal to the expected value{indentD lhs}" unless ← isDefEq rhs rhs' do throwError "Congruence hole has type{indentD pfTy}\n\ but its right-hand side is not definitionally equal to the expected value{indentD rhs}" return pf /-- Force the lhs and rhs to be defeq. For when `dsimp`-like congruence is necessary. Clears the proof. -/ def CongrResult.defeq (res : CongrResult) : MetaM CongrResult := do if res.isRfl then return res else unless ← isDefEq res.lhs res.rhs do throwError "Cannot generate congruence because we need{indentD res.lhs}\n\ to be definitionally equal to{indentD res.rhs}" -- Propagate types into any proofs that we're dropping: discard <| res.eq return {res with pf? := none} /-- Tries to make a congruence between `lhs` and `rhs` automatically. 1. If they are defeq, returns a trivial congruence. 2. Tries using `Subsingleton.elim`. 3. Tries `proof_irrel_heq` as another effort to avoid doing congruence on proofs. 3. Otherwise throws an error. Note: `mkAppM` uses `withNewMCtxDepth`, which prevents typeclass inference from accidentally specializing `Sort _` to `Prop`, which could otherwise happen because there is a `Subsingleton Prop` instance. -/ def CongrResult.mkDefault (lhs rhs : Expr) : MetaM CongrResult := do if ← isDefEq lhs rhs then return {lhs, rhs, pf? := none} else if let some pf ← (observing? <| mkAppM ``Subsingleton.elim #[lhs, rhs]) then return CongrResult.mk' lhs rhs pf else if let some pf ← (observing? <| mkAppM ``proof_irrel_heq #[lhs, rhs]) then return CongrResult.mk' lhs rhs pf throwError "Could not generate congruence between{indentD lhs}\nand{indentD rhs}" /-- Does `CongrResult.mkDefault` but makes sure there are no lingering congruence holes. -/ def CongrResult.mkDefault' (mvarCounterSaved : Nat) (lhs rhs : Expr) : MetaM CongrResult := do if let some h := hasCHole mvarCounterSaved lhs then throwError "Left-hand side{indentD lhs}\nstill has a congruence hole{indentD h}" if let some h := hasCHole mvarCounterSaved rhs then throwError "Right-hand side{indentD rhs}\nstill has a congruence hole{indentD h}" CongrResult.mkDefault lhs rhs /-- Throw an internal error. -/ def throwCongrEx {α : Type} (lhs rhs : Expr) (msg : MessageData) : MetaM α := do throwError "congr(...) failed with left-hand side{indentD lhs}\n\ and right-hand side {indentD rhs}\n{msg}" /-- If `lhs` or `rhs` is a congruence hole, then process it. Only process ones that are at least as new as `mvarCounterSaved` since nothing prevents congruence holes from leaking into the local context. -/ def mkCongrOfCHole? (mvarCounterSaved : Nat) (lhs rhs : Expr) : MetaM (Option CongrResult) := do match cHole? lhs mvarCounterSaved, cHole? rhs mvarCounterSaved with | some (isLhs1, val1, pf1), some (isLhs2, val2, pf2) => trace[Elab.congr] "mkCongrOfCHole, both holes" unless isLhs1 == true do throwCongrEx lhs rhs "A RHS congruence hole leaked into the LHS" unless isLhs2 == false do throwCongrEx lhs rhs "A LHS congruence hole leaked into the RHS" -- Defeq checks to unify the lhs and rhs congruence holes. unless ← isDefEq (← inferType pf1) (← inferType pf2) do throwCongrEx lhs rhs "Elaborated types of congruence holes are not defeq." if let some (_, lhsVal, _, rhsVal) := (← whnf <| ← inferType pf1).sides? then unless ← isDefEq val1 lhsVal do throwError "Left-hand side of congruence hole is{indentD lhsVal}\n\ but is expected to be{indentD val1}" unless ← isDefEq val2 rhsVal do throwError "Right-hand side of congruence hole is{indentD rhsVal}\n\ but is expected to be{indentD val2}" return some <| CongrResult.mk' val1 val2 pf1 | some .., none => throwCongrEx lhs rhs "Right-hand side lost its congruence hole annotation." | none, some .. => throwCongrEx lhs rhs "Left-hand side lost its congruence hole annotation." | none, none => return none /-- Given two applications of the same arity, gives `Expr.getAppFn` of both, but if these functions are equal, gives the longest common prefix. -/ private def getJointAppFns (e e' : Expr) : Expr × Expr := if e == e' then (e, e) else match e, e' with | .app f _, .app f' _ => getJointAppFns f f' | _, _ => (e, e') /-- Monad for `mkCongrOfAux`, for caching `CongrResult`s. -/ abbrev M := MonadCacheT (Expr × Expr) CongrResult MetaM mutual /-- Implementation of `mkCongrOf`, with caching. -/ partial def mkCongrOfAux (depth : Nat) (mvarCounterSaved : Nat) (lhs rhs : Expr) : M CongrResult := do trace[Elab.congr] "mkCongrOf: {depth}, {lhs}, {rhs}, {(← mkFreshExprMVar none).mvarId!}" if depth > 1000 then throwError "congr(...) internal error: out of gas" -- Potentially metavariables get assigned as we process congruence holes, -- so instantiate them to be safe. Placeholders and implicit arguments might -- end up with congruence holes, so they indeed might need a nontrivial congruence. let lhs ← instantiateMVars lhs let rhs ← instantiateMVars rhs checkCache (lhs, rhs) fun _ => do if let some res ← mkCongrOfCHole? mvarCounterSaved lhs rhs then trace[Elab.congr] "hole processing succeeded" return res if lhs == rhs then -- There should not be any cHoles, but to be safe let's remove them. return { lhs := removeCHoles lhs, rhs := removeCHoles rhs, pf? := none } if (hasCHole mvarCounterSaved lhs).isNone && (hasCHole mvarCounterSaved rhs).isNone then -- It's safe to fastforward if the lhs and rhs are defeq and have no congruence holes. -- This is more conservative than necessary since congruence holes might only be inside -- proofs, and it is OK to ignore these. if ← isDefEq lhs rhs then return { lhs, rhs, pf? := none } if ← (isProof lhs <||> isProof rhs) then -- We don't want to look inside proofs at all. return ← CongrResult.mkDefault lhs rhs match lhs, rhs with | .app .., .app .. => mkCongrOfApp depth mvarCounterSaved lhs rhs | .lam .., .lam .. => trace[Elab.congr] "lam" let resDom ← mkCongrOfAux (depth + 1) mvarCounterSaved lhs.bindingDomain! rhs.bindingDomain! -- We do not yet support congruences in the binding domain for lambdas. discard <| resDom.defeq withLocalDecl lhs.bindingName! lhs.bindingInfo! resDom.lhs fun x => do let lhsb := lhs.bindingBody!.instantiate1 x let rhsb := rhs.bindingBody!.instantiate1 x let resBody ← mkCongrOfAux (depth + 1) mvarCounterSaved lhsb rhsb let lhs ← mkLambdaFVars #[x] resBody.lhs let rhs ← mkLambdaFVars #[x] resBody.rhs if resBody.isRfl then return {lhs, rhs, pf? := none} else let pf ← mkLambdaFVars #[x] (← resBody.eq) return CongrResult.mk' lhs rhs (← mkAppM ``funext #[pf]) | .forallE .., .forallE .. => trace[Elab.congr] "forallE" let resDom ← mkCongrOfAux (depth + 1) mvarCounterSaved lhs.bindingDomain! rhs.bindingDomain! if lhs.isArrow && rhs.isArrow then let resBody ← mkCongrOfAux (depth + 1) mvarCounterSaved lhs.bindingBody! rhs.bindingBody! let lhs := Expr.forallE lhs.bindingName! resDom.lhs resBody.lhs lhs.bindingInfo! let rhs := Expr.forallE rhs.bindingName! resDom.rhs resBody.rhs rhs.bindingInfo! if resDom.isRfl && resBody.isRfl then return {lhs, rhs, pf? := none} else return CongrResult.mk' lhs rhs (← mkImpCongr (← resDom.eq) (← resBody.eq)) else -- We do not yet support congruences in the binding domain for dependent pi types. discard <| resDom.defeq withLocalDecl lhs.bindingName! lhs.bindingInfo! resDom.lhs fun x => do let lhsb := lhs.bindingBody!.instantiate1 x let rhsb := rhs.bindingBody!.instantiate1 x let resBody ← mkCongrOfAux (depth + 1) mvarCounterSaved lhsb rhsb let lhs ← mkForallFVars #[x] resBody.lhs let rhs ← mkForallFVars #[x] resBody.rhs if resBody.isRfl then return {lhs, rhs, pf? := none} else let pf ← mkLambdaFVars #[x] (← resBody.eq) return CongrResult.mk' lhs rhs (← mkAppM ``pi_congr #[pf]) | .letE .., .letE .. => trace[Elab.congr] "letE" -- Just zeta reduce for now. Could look at `Lean.Meta.Simp.simp.simpLet` let lhs := lhs.letBody!.instantiate1 lhs.letValue! let rhs := rhs.letBody!.instantiate1 rhs.letValue! mkCongrOfAux (depth + 1) mvarCounterSaved lhs rhs | .mdata _ lhs', .mdata _ rhs' => trace[Elab.congr] "mdata" let res ← mkCongrOfAux (depth + 1) mvarCounterSaved lhs' rhs' return {res with lhs := lhs.updateMData! res.lhs, rhs := rhs.updateMData! res.rhs} | .proj n1 i1 e1, .proj n2 i2 e2 => trace[Elab.congr] "proj" -- Only handles defeq at the moment. unless n1 == n2 && i1 == i2 do throwCongrEx lhs rhs "Incompatible primitive projections" let res ← mkCongrOfAux (depth + 1) mvarCounterSaved e1 e2 discard <| res.defeq return {lhs := lhs.updateProj! res.lhs, rhs := rhs.updateProj! res.rhs, pf? := none} | _, _ => trace[Elab.congr] "base case" CongrResult.mkDefault' mvarCounterSaved lhs rhs /-- Generate congruence for applications `lhs` and `rhs`. Key detail: functions might be *overapplied* due to the values of their arguments. For example, `id id 2` is overapplied. To handle these, we need to segment the applications into their natural arities, since `mkHCongrWithArity'` does not know how to generate congruence lemmas for the overapplied case. -/ partial def mkCongrOfApp (depth : Nat) (mvarCounterSaved : Nat) (lhs rhs : Expr) : M CongrResult := do -- Even if a function is being rewritten (e.g. with `f x = g`), both sides should have the same -- number of arguments since there will be a cHole around both `f x` and `g`. let arity := lhs.getAppNumArgs trace[Elab.congr] "app, arity {arity}" unless arity == rhs.getAppNumArgs do trace[Elab.congr] "app desync (arity)" return ← CongrResult.mkDefault' mvarCounterSaved lhs rhs -- Optimization: congruences often have a shared prefix (e.g. some type parameters an instances) -- so if there's a shared prefix we use it. let mut (f, f') := getJointAppFns lhs rhs let arity := arity - f.getAppNumArgs trace[Elab.congr] "app, updated arity {arity}" if f != f' then unless ← isDefEq (← inferType f) (← inferType f') do trace[Elab.congr] "app desync (function types)" return ← CongrResult.mkDefault' mvarCounterSaved lhs rhs -- First try using `congr`/`congrFun` to build a proof as far as possible. -- We update `f`, `f'`, and `finfo` as we go. let lhsArgs := lhs.getBoundedAppArgs arity let rhsArgs := rhs.getBoundedAppArgs arity let rec /-- Argument processing loop - `i` is index into `lhsArgs`/`rhsArgs`. - `finfo` is the funinfo of `f` applied to the first `finfoIdx` arguments - `f` and `f'` are the current head functions, after the first `i` arguments have been applied. -/ go (i : Nat) (finfo : FunInfo) (finfoIdx : Nat) (f f' : Expr) (pf : Expr) : M CongrResult := do if i ≥ arity then return CongrResult.mk' f f' pf else let mut finfo := finfo let mut finfoIdx := finfoIdx unless i - finfoIdx < finfo.getArity do finfo ← getFunInfoNArgs f (arity - finfoIdx) finfoIdx := i let info := finfo.paramInfo[i - finfoIdx]! let a := lhsArgs[i]! let a' := rhsArgs[i]! let ra ← mkCongrOfAux (depth + 1) mvarCounterSaved a a' if ra.isRfl then trace[Elab.congr] "app, arg {i} by rfl" go (i + 1) finfo finfoIdx (.app f ra.lhs) (.app f' ra.rhs) (← mkCongrFun pf ra.lhs) else if !info.hasFwdDeps then trace[Elab.congr] "app, arg {i} by eq" go (i + 1) finfo finfoIdx (.app f ra.lhs) (.app f' ra.rhs) (← mkCongr pf (← ra.eq)) else -- Otherwise, we can make progress with an hcongr lemma. if (isRefl? pf).isNone then trace[Elab.congr] "app, hcongr needs transitivity" -- If there's a nontrivial proof, then since `mkHCongrWithArity'` fixes the function, -- we need to use transitivity to make the functions be the same. let lhsArgs' := (lhsArgs.extract i).map removeCHoles let lhs := mkAppN f lhsArgs' let lhs' := mkAppN f' lhsArgs' let mut pf' := pf for arg in lhsArgs' do pf' ← mkCongrFun pf' arg let res1 := CongrResult.mk' lhs lhs' pf' let res2 ← go i finfo finfoIdx f' f' (← mkEqRefl f') return res1.trans res2 else -- Get an accurate measure of the arity of `f`, following `getFunInfoNArgs`. -- No need to update `finfo` itself. let fArity ← if finfoIdx == i then pure finfo.getArity else withAtLeastTransparency .default do forallBoundedTelescope (← inferType f) (some (arity - i)) fun xs _ => pure xs.size trace[Elab.congr] "app, args {i}-{i+arity-1} by hcongr, {arity} arguments" let thm ← mkHCongrWithArity' f fArity let mut args := #[] let mut lhsArgs' := #[] let mut rhsArgs' := #[] for lhs' in lhsArgs[i:], rhs' in rhsArgs[i:], kind in thm.argKinds do match kind with | .eq => let ares ← mkCongrOfAux (depth + 1) mvarCounterSaved lhs' rhs' args := args |>.push ares.lhs |>.push ares.rhs |>.push (← ares.eq) lhsArgs' := lhsArgs'.push ares.lhs rhsArgs' := rhsArgs'.push ares.rhs | .heq => let ares ← mkCongrOfAux (depth + 1) mvarCounterSaved lhs' rhs' args := args |>.push ares.lhs |>.push ares.rhs |>.push (← ares.heq) lhsArgs' := lhsArgs'.push ares.lhs rhsArgs' := rhsArgs'.push ares.rhs | .subsingletonInst => -- Warning: we're not processing any congruence holes here. -- Users shouldn't be intentionally placing them in such arguments anyway. -- We can't throw an error because these arguments might incidentally have -- congruence holes by unification. let lhs' := removeCHoles lhs' let rhs' := removeCHoles rhs' args := args |>.push lhs' |>.push rhs' lhsArgs' := lhsArgs'.push lhs' rhsArgs' := rhsArgs'.push rhs' | _ => panic! "unexpected hcongr argument kind" let lhs' := mkAppN f lhsArgs' let rhs' := mkAppN f' rhsArgs' let res := CongrResult.mk' lhs' rhs' (mkAppN thm.proof args) if i + fArity < arity then -- There are more arguments after this. The only way this can work is if -- `res` can prove an equality. go (i + fArity) finfo finfoIdx lhs' rhs' (← res.eq) else -- Otherwise, we can return `res`, which might only be a HEq. return res let res ← mkCongrOfAux (depth + 1) mvarCounterSaved f f' let pf ← res.eq go 0 (← getFunInfoNArgs f arity) 0 res.lhs res.rhs pf end /-- Walks along both `lhs` and `rhs` simultaneously to create a congruence lemma between them. Where they are desynchronized, we fall back to the base case (using `CongrResult.mkDefault'`) since it's likely due to unification with the expected type, from `_` placeholders or implicit arguments being filled in. -/ partial def mkCongrOf (depth : Nat) (mvarCounterSaved : Nat) (lhs rhs : Expr) : MetaM CongrResult := mkCongrOfAux depth mvarCounterSaved lhs rhs |>.run /-! ### Elaborating congruence quotations -/ @[term_elab termCongr, inherit_doc termCongr] def elabTermCongr : Term.TermElab := fun stx expectedType? => do match stx with | `(congr($t)) => -- Save the current mvarCounter so that we know which cHoles are for this congr quotation. let mvarCounterSaved := (← getMCtx).mvarCounter -- Case 1: There is an expected type and it's obviously an Iff/Eq/HEq. if let some expectedType := expectedType? then if let some (expLhsTy, expLhs, expRhsTy, expRhs) := (← whnf expectedType).sides? then let lhs ← elaboratePattern t expLhsTy true let rhs ← elaboratePattern t expRhsTy false -- Note: these defeq checks can leak congruence holes. unless ← isDefEq expLhs lhs do throwError "Left-hand side of elaborated pattern{indentD lhs}\n\ is not definitionally equal to left-hand side of expected type{indentD expectedType}" unless ← isDefEq expRhs rhs do throwError "Right-hand side of elaborated pattern{indentD rhs}\n\ is not definitionally equal to right-hand side of expected type{indentD expectedType}" Term.synthesizeSyntheticMVars (postpone := .yes) let res ← mkCongrOf 0 mvarCounterSaved lhs rhs let expectedType' ← whnf expectedType let pf ← if expectedType'.iff?.isSome then res.iff else if expectedType'.isEq then res.eq else if expectedType'.isHEq then res.heq else panic! "unreachable case, sides? guarantees Iff, Eq, and HEq" return ← mkExpectedTypeHint pf expectedType -- Case 2: No expected type or it's not obviously Iff/Eq/HEq. We generate an Eq. let lhs ← elaboratePattern t none true let rhs ← elaboratePattern t none false Term.synthesizeSyntheticMVars (postpone := .yes) let res ← mkCongrOf 0 mvarCounterSaved lhs rhs let pf ← res.eq let ty ← mkEq res.lhs res.rhs mkExpectedTypeHint pf ty | _ => throwUnsupportedSyntax end TermCongr end Mathlib.Tactic
Monad.lean
/- Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import Mathlib.Algebra.MvPolynomial.Rename import Mathlib.Algebra.MvPolynomial.Variables /-! # Monad operations on `MvPolynomial` This file defines two monadic operations on `MvPolynomial`. Given `p : MvPolynomial σ R`, * `MvPolynomial.bind₁` and `MvPolynomial.join₁` operate on the variable type `σ`. * `MvPolynomial.bind₂` and `MvPolynomial.join₂` operate on the coefficient type `R`. - `MvPolynomial.bind₁ f φ` with `f : σ → MvPolynomial τ R` and `φ : MvPolynomial σ R`, is the polynomial `φ(f 1, ..., f i, ...) : MvPolynomial τ R`. - `MvPolynomial.join₁ φ` with `φ : MvPolynomial (MvPolynomial σ R) R` collapses `φ` to a `MvPolynomial σ R`, by evaluating `φ` under the map `X f ↦ f` for `f : MvPolynomial σ R`. In other words, if you have a polynomial `φ` in a set of variables indexed by a polynomial ring, you evaluate the polynomial in these indexing polynomials. - `MvPolynomial.bind₂ f φ` with `f : R →+* MvPolynomial σ S` and `φ : MvPolynomial σ R` is the `MvPolynomial σ S` obtained from `φ` by mapping the coefficients of `φ` through `f` and considering the resulting polynomial as polynomial expression in `MvPolynomial σ R`. - `MvPolynomial.join₂ φ` with `φ : MvPolynomial σ (MvPolynomial σ R)` collapses `φ` to a `MvPolynomial σ R`, by considering `φ` as polynomial expression in `MvPolynomial σ R`. These operations themselves have algebraic structure: `MvPolynomial.bind₁` and `MvPolynomial.join₁` are algebra homs and `MvPolynomial.bind₂` and `MvPolynomial.join₂` are ring homs. They interact in convenient ways with `MvPolynomial.rename`, `MvPolynomial.map`, `MvPolynomial.vars`, and other polynomial operations. Indeed, `MvPolynomial.rename` is the "map" operation for the (`bind₁`, `join₁`) pair, whereas `MvPolynomial.map` is the "map" operation for the other pair. ## Implementation notes We add a `LawfulMonad` instance for the (`bind₁`, `join₁`) pair. The second pair cannot be instantiated as a `Monad`, since it is not a monad in `Type` but in `CommRingCat` (or rather `CommSemiRingCat`). -/ noncomputable section namespace MvPolynomial open Finsupp variable {σ : Type*} {τ : Type*} variable {R S T : Type*} [CommSemiring R] [CommSemiring S] [CommSemiring T] /-- `bind₁` is the "left hand side" bind operation on `MvPolynomial`, operating on the variable type. Given a polynomial `p : MvPolynomial σ R` and a map `f : σ → MvPolynomial τ R` taking variables in `p` to polynomials in the variable type `τ`, `bind₁ f p` replaces each variable in `p` with its value under `f`, producing a new polynomial in `τ`. The coefficient type remains the same. This operation is an algebra hom. -/ def bind₁ (f : σ → MvPolynomial τ R) : MvPolynomial σ R →ₐ[R] MvPolynomial τ R := aeval f /-- `bind₂` is the "right hand side" bind operation on `MvPolynomial`, operating on the coefficient type. Given a polynomial `p : MvPolynomial σ R` and a map `f : R → MvPolynomial σ S` taking coefficients in `p` to polynomials over a new ring `S`, `bind₂ f p` replaces each coefficient in `p` with its value under `f`, producing a new polynomial over `S`. The variable type remains the same. This operation is a ring hom. -/ def bind₂ (f : R →+* MvPolynomial σ S) : MvPolynomial σ R →+* MvPolynomial σ S := eval₂Hom f X /-- `join₁` is the monadic join operation corresponding to `MvPolynomial.bind₁`. Given a polynomial `p` with coefficients in `R` whose variables are polynomials in `σ` with coefficients in `R`, `join₁ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is an algebra hom. -/ def join₁ : MvPolynomial (MvPolynomial σ R) R →ₐ[R] MvPolynomial σ R := aeval id /-- `join₂` is the monadic join operation corresponding to `MvPolynomial.bind₂`. Given a polynomial `p` with variables in `σ` whose coefficients are polynomials in `σ` with coefficients in `R`, `join₂ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is a ring hom. -/ def join₂ : MvPolynomial σ (MvPolynomial σ R) →+* MvPolynomial σ R := eval₂Hom (RingHom.id _) X @[simp] theorem aeval_eq_bind₁ (f : σ → MvPolynomial τ R) : aeval f = bind₁ f := rfl @[simp] theorem eval₂Hom_C_eq_bind₁ (f : σ → MvPolynomial τ R) : eval₂Hom C f = bind₁ f := rfl @[simp] theorem eval₂Hom_eq_bind₂ (f : R →+* MvPolynomial σ S) : eval₂Hom f X = bind₂ f := rfl section variable (σ R) @[simp] theorem aeval_id_eq_join₁ : aeval id = @join₁ σ R _ := rfl theorem eval₂Hom_C_id_eq_join₁ (φ : MvPolynomial (MvPolynomial σ R) R) : eval₂Hom C id φ = join₁ φ := rfl @[simp] theorem eval₂Hom_id_X_eq_join₂ : eval₂Hom (RingHom.id _) X = @join₂ σ R _ := rfl end -- In this file, we don't want to use these simp lemmas, -- because we first need to show how these new definitions interact -- and the proofs fall back on unfolding the definitions and call simp afterwards attribute [-simp] aeval_eq_bind₁ eval₂Hom_C_eq_bind₁ eval₂Hom_eq_bind₂ aeval_id_eq_join₁ eval₂Hom_id_X_eq_join₂ @[simp] theorem bind₁_X_right (f : σ → MvPolynomial τ R) (i : σ) : bind₁ f (X i) = f i := aeval_X f i @[simp] theorem bind₂_X_right (f : R →+* MvPolynomial σ S) (i : σ) : bind₂ f (X i) = X i := eval₂Hom_X' f X i @[simp] theorem bind₁_X_left : bind₁ (X : σ → MvPolynomial σ R) = AlgHom.id R _ := by ext1 i simp variable (f : σ → MvPolynomial τ R) theorem bind₁_C_right (f : σ → MvPolynomial τ R) (x) : bind₁ f (C x) = C x := algHom_C _ _ @[simp] theorem bind₂_C_right (f : R →+* MvPolynomial σ S) (r : R) : bind₂ f (C r) = f r := eval₂Hom_C f X r @[simp] theorem bind₂_C_left : bind₂ (C : R →+* MvPolynomial σ R) = RingHom.id _ := by ext : 2 <;> simp @[simp] theorem bind₂_comp_C (f : R →+* MvPolynomial σ S) : (bind₂ f).comp C = f := RingHom.ext <| bind₂_C_right _ @[simp] theorem join₂_map (f : R →+* MvPolynomial σ S) (φ : MvPolynomial σ R) : join₂ (map f φ) = bind₂ f φ := by simp only [join₂, bind₂, eval₂Hom_map_hom, RingHom.id_comp] @[simp] theorem join₂_comp_map (f : R →+* MvPolynomial σ S) : join₂.comp (map f) = bind₂ f := RingHom.ext <| join₂_map _ theorem aeval_id_rename (f : σ → MvPolynomial τ R) (p : MvPolynomial σ R) : aeval id (rename f p) = aeval f p := by rw [aeval_rename, Function.id_comp] @[simp] theorem join₁_rename (f : σ → MvPolynomial τ R) (φ : MvPolynomial σ R) : join₁ (rename f φ) = bind₁ f φ := aeval_id_rename _ _ @[simp] theorem bind₁_id : bind₁ (@id (MvPolynomial σ R)) = join₁ := rfl @[simp] theorem bind₂_id : bind₂ (RingHom.id (MvPolynomial σ R)) = join₂ := rfl theorem bind₁_bind₁ {υ : Type*} (f : σ → MvPolynomial τ R) (g : τ → MvPolynomial υ R) (φ : MvPolynomial σ R) : (bind₁ g) (bind₁ f φ) = bind₁ (fun i => bind₁ g (f i)) φ := by simp [bind₁, ← comp_aeval] theorem bind₁_comp_bind₁ {υ : Type*} (f : σ → MvPolynomial τ R) (g : τ → MvPolynomial υ R) : (bind₁ g).comp (bind₁ f) = bind₁ fun i => bind₁ g (f i) := by ext1 apply bind₁_bind₁ theorem bind₂_comp_bind₂ (f : R →+* MvPolynomial σ S) (g : S →+* MvPolynomial σ T) : (bind₂ g).comp (bind₂ f) = bind₂ ((bind₂ g).comp f) := by ext : 2 <;> simp theorem bind₂_bind₂ (f : R →+* MvPolynomial σ S) (g : S →+* MvPolynomial σ T) (φ : MvPolynomial σ R) : (bind₂ g) (bind₂ f φ) = bind₂ ((bind₂ g).comp f) φ := RingHom.congr_fun (bind₂_comp_bind₂ f g) φ theorem rename_comp_bind₁ {υ : Type*} (f : σ → MvPolynomial τ R) (g : τ → υ) : (rename g).comp (bind₁ f) = bind₁ fun i => rename g <| f i := by ext1 i simp theorem rename_bind₁ {υ : Type*} (f : σ → MvPolynomial τ R) (g : τ → υ) (φ : MvPolynomial σ R) : rename g (bind₁ f φ) = bind₁ (fun i => rename g <| f i) φ := AlgHom.congr_fun (rename_comp_bind₁ f g) φ theorem map_bind₂ (f : R →+* MvPolynomial σ S) (g : S →+* T) (φ : MvPolynomial σ R) : map g (bind₂ f φ) = bind₂ ((map g).comp f) φ := by simp only [bind₂, eval₂_comp_right, coe_eval₂Hom, eval₂_map] congr 1 with : 1 simp only [Function.comp_apply, map_X] theorem bind₁_comp_rename {υ : Type*} (f : τ → MvPolynomial υ R) (g : σ → τ) : (bind₁ f).comp (rename g) = bind₁ (f ∘ g) := by ext1 i simp theorem bind₁_rename {υ : Type*} (f : τ → MvPolynomial υ R) (g : σ → τ) (φ : MvPolynomial σ R) : bind₁ f (rename g φ) = bind₁ (f ∘ g) φ := AlgHom.congr_fun (bind₁_comp_rename f g) φ theorem bind₂_map (f : S →+* MvPolynomial σ T) (g : R →+* S) (φ : MvPolynomial σ R) : bind₂ f (map g φ) = bind₂ (f.comp g) φ := by simp [bind₂] @[simp] theorem map_comp_C (f : R →+* S) : (map f).comp (C : R →+* MvPolynomial σ R) = C.comp f := by ext1 apply map_C -- mixing the two monad structures theorem hom_bind₁ (f : MvPolynomial τ R →+* S) (g : σ → MvPolynomial τ R) (φ : MvPolynomial σ R) : f (bind₁ g φ) = eval₂Hom (f.comp C) (fun i => f (g i)) φ := by rw [bind₁, map_aeval, algebraMap_eq] theorem map_bind₁ (f : R →+* S) (g : σ → MvPolynomial τ R) (φ : MvPolynomial σ R) : map f (bind₁ g φ) = bind₁ (fun i : σ => (map f) (g i)) (map f φ) := by rw [hom_bind₁, map_comp_C, ← eval₂Hom_map_hom] rfl @[simp] theorem eval₂Hom_comp_C (f : R →+* S) (g : σ → S) : (eval₂Hom f g).comp C = f := by ext1 r exact eval₂_C f g r theorem eval₂Hom_bind₁ (f : R →+* S) (g : τ → S) (h : σ → MvPolynomial τ R) (φ : MvPolynomial σ R) : eval₂Hom f g (bind₁ h φ) = eval₂Hom f (fun i => eval₂Hom f g (h i)) φ := by rw [hom_bind₁, eval₂Hom_comp_C] theorem aeval_bind₁ [Algebra R S] (f : τ → S) (g : σ → MvPolynomial τ R) (φ : MvPolynomial σ R) : aeval f (bind₁ g φ) = aeval (fun i => aeval f (g i)) φ := eval₂Hom_bind₁ _ _ _ _ theorem aeval_comp_bind₁ [Algebra R S] (f : τ → S) (g : σ → MvPolynomial τ R) : (aeval f).comp (bind₁ g) = aeval fun i => aeval f (g i) := by ext1 apply aeval_bind₁ theorem eval₂Hom_comp_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* MvPolynomial σ S) : (eval₂Hom f g).comp (bind₂ h) = eval₂Hom ((eval₂Hom f g).comp h) g := by ext : 2 <;> simp theorem eval₂Hom_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* MvPolynomial σ S) (φ : MvPolynomial σ R) : eval₂Hom f g (bind₂ h φ) = eval₂Hom ((eval₂Hom f g).comp h) g φ := RingHom.congr_fun (eval₂Hom_comp_bind₂ f g h) φ theorem aeval_bind₂ [Algebra S T] (f : σ → T) (g : R →+* MvPolynomial σ S) (φ : MvPolynomial σ R) : aeval f (bind₂ g φ) = eval₂Hom ((↑(aeval f : _ →ₐ[S] _) : _ →+* _).comp g) f φ := eval₂Hom_bind₂ _ _ _ _ alias eval₂Hom_C_left := eval₂Hom_C_eq_bind₁ theorem bind₁_monomial (f : σ → MvPolynomial τ R) (d : σ →₀ ℕ) (r : R) : bind₁ f (monomial d r) = C r * ∏ i ∈ d.support, f i ^ d i := by simp only [monomial_eq, map_mul, bind₁_C_right, Finsupp.prod, map_prod, map_pow, bind₁_X_right] theorem bind₂_monomial (f : R →+* MvPolynomial σ S) (d : σ →₀ ℕ) (r : R) : bind₂ f (monomial d r) = f r * monomial d 1 := by simp only [monomial_eq, RingHom.map_mul, bind₂_C_right, Finsupp.prod, map_prod, map_pow, bind₂_X_right, C_1, one_mul] @[simp] theorem bind₂_monomial_one (f : R →+* MvPolynomial σ S) (d : σ →₀ ℕ) : bind₂ f (monomial d 1) = monomial d 1 := by rw [bind₂_monomial, f.map_one, one_mul] section theorem vars_bind₁ [DecidableEq τ] (f : σ → MvPolynomial τ R) (φ : MvPolynomial σ R) : (bind₁ f φ).vars ⊆ φ.vars.biUnion fun i => (f i).vars := by calc (bind₁ f φ).vars _ = (φ.support.sum fun x : σ →₀ ℕ => (bind₁ f) (monomial x (coeff x φ))).vars := by rw [← map_sum, ← φ.as_sum] _ ≤ φ.support.biUnion fun i : σ →₀ ℕ => ((bind₁ f) (monomial i (coeff i φ))).vars := (vars_sum_subset _ _) _ = φ.support.biUnion fun d : σ →₀ ℕ => vars (C (coeff d φ) * ∏ i ∈ d.support, f i ^ d i) := by simp only [bind₁_monomial] _ ≤ φ.support.biUnion fun d : σ →₀ ℕ => d.support.biUnion fun i => vars (f i) := ?_ -- proof below _ ≤ φ.vars.biUnion fun i : σ => vars (f i) := ?_ -- proof below · apply Finset.biUnion_mono intro d _hd calc vars (C (coeff d φ) * ∏ i ∈ d.support, f i ^ d i) ≤ (C (coeff d φ)).vars ∪ (∏ i ∈ d.support, f i ^ d i).vars := vars_mul _ _ _ ≤ (∏ i ∈ d.support, f i ^ d i).vars := by simp only [Finset.empty_union, vars_C, Finset.le_iff_subset, Finset.Subset.refl] _ ≤ d.support.biUnion fun i : σ => vars (f i ^ d i) := vars_prod _ _ ≤ d.support.biUnion fun i : σ => (f i).vars := ?_ apply Finset.biUnion_mono intro i _hi apply vars_pow · intro j simp_rw [Finset.mem_biUnion] rintro ⟨d, hd, ⟨i, hi, hj⟩⟩ exact ⟨i, (mem_vars _).mpr ⟨d, hd, hi⟩, hj⟩ end theorem mem_vars_bind₁ (f : σ → MvPolynomial τ R) (φ : MvPolynomial σ R) {j : τ} (h : j ∈ (bind₁ f φ).vars) : ∃ i : σ, i ∈ φ.vars ∧ j ∈ (f i).vars := by classical simpa only [exists_prop, Finset.mem_biUnion, mem_support_iff, Ne] using vars_bind₁ f φ h instance monad : Monad fun σ => MvPolynomial σ R where map f p := rename f p pure := X bind p f := bind₁ f p instance lawfulFunctor : LawfulFunctor fun σ => MvPolynomial σ R where map_const := by intros; rfl -- Porting note: I guess `map_const` no longer has a default implementation? id_map := by intros; simp [(· <$> ·)] comp_map := by intros; simp [(· <$> ·)] instance lawfulMonad : LawfulMonad fun σ => MvPolynomial σ R where pure_bind := by intros; simp [pure, bind] bind_assoc := by intros; simp [bind, ← bind₁_comp_bind₁] seqLeft_eq := by intros; simp [SeqLeft.seqLeft, Seq.seq, (· <$> ·), bind₁_rename]; rfl seqRight_eq := by intros; simp [SeqRight.seqRight, Seq.seq, (· <$> ·), bind₁_rename]; rfl pure_seq := by intros; simp [(· <$> ·), pure, Seq.seq] bind_pure_comp := by aesop bind_map := by aesop /- Possible TODO for the future: Enable the following definitions, and write a lot of supporting lemmas. def bind (f : R →+* mv_polynomial τ S) (g : σ → mv_polynomial τ S) : mv_polynomial σ R →+* mv_polynomial τ S := eval₂_hom f g def join (f : R →+* S) : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := aeval (map f) def ajoin [algebra R S] : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := join (algebra_map R S) -/ end MvPolynomial
Order.lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Kim Morrison, Yuyang Zhao -/ import Mathlib.Logic.Small.Defs import Mathlib.Order.GameAdd import Mathlib.SetTheory.PGame.Basic import Mathlib.Tactic.Linter.DeprecatedModule deprecated_module "This module is now at `CombinatorialGames.Game.IGame` in the CGT repo <https://github.com/vihdzp/combinatorial-games>" (since := "2025-08-06") /-! # Order properties of pregames Pregames have both a `≤` and a `<` relation, satisfying the usual properties of a `Preorder`. The relation `0 < x` means that `x` can always be won by Left, while `0 ≤ x` means that `x` can be won by Left as the second player. It turns out to be quite convenient to define various relations on top of these. We define the "less or fuzzy" relation `x ⧏ y` as `¬ y ≤ x`, the equivalence relation `x ≈ y` as `x ≤ y ∧ y ≤ x`, and the fuzzy relation `x ‖ y` as `x ⧏ y ∧ y ⧏ x`. If `0 ⧏ x`, then `x` can be won by Left as the first player. If `x ≈ 0`, then `x` can be won by the second player. If `x ‖ 0`, then `x` can be won by the first player. Statements like `zero_le_lf`, `zero_lf_le`, etc. unfold these definitions. The theorems `le_def` and `lf_def` give a recursive characterisation of each relation in terms of themselves two moves later. The theorems `zero_le`, `zero_lf`, etc. also take into account that `0` has no moves. Later, games will be defined as the quotient by the `≈` relation; that is to say, the `Antisymmetrization` of `SetTheory.PGame`. -/ namespace SetTheory.PGame open Function Relation universe u /-- The less or equal relation on pre-games. If `0 ≤ x`, then Left can win `x` as the second player. `x ≤ y` means that `0 ≤ y - x`. See `PGame.le_iff_sub_nonneg`. -/ instance le : LE PGame := ⟨Sym2.GameAdd.fix wf_isOption fun x y le => (∀ i, ¬le y (x.moveLeft i) (Sym2.GameAdd.snd_fst <| IsOption.moveLeft i)) ∧ ∀ j, ¬le (y.moveRight j) x (Sym2.GameAdd.fst_snd <| IsOption.moveRight j)⟩ /-- The less or fuzzy relation on pre-games. `x ⧏ y` is defined as `¬ y ≤ x`. If `0 ⧏ x`, then Left can win `x` as the first player. `x ⧏ y` means that `0 ⧏ y - x`. See `PGame.lf_iff_sub_zero_lf`. -/ def LF (x y : PGame) : Prop := ¬y ≤ x @[inherit_doc] scoped infixl:50 " ⧏ " => PGame.LF @[simp] protected theorem not_le {x y : PGame} : ¬x ≤ y ↔ y ⧏ x := Iff.rfl @[simp] theorem not_lf {x y : PGame} : ¬x ⧏ y ↔ y ≤ x := Classical.not_not theorem _root_.LE.le.not_gf {x y : PGame} : x ≤ y → ¬y ⧏ x := not_lf.2 theorem LF.not_ge {x y : PGame} : x ⧏ y → ¬y ≤ x := id /-- Definition of `x ≤ y` on pre-games, in terms of `⧏`. The ordering here is chosen so that `And.left` refer to moves by Left, and `And.right` refer to moves by Right. -/ theorem le_iff_forall_lf {x y : PGame} : x ≤ y ↔ (∀ i, x.moveLeft i ⧏ y) ∧ ∀ j, x ⧏ y.moveRight j := by unfold LE.le le simp only rw [Sym2.GameAdd.fix_eq] rfl /-- Definition of `x ≤ y` on pre-games built using the constructor. -/ @[simp] theorem mk_le_mk {xl xr xL xR yl yr yL yR} : mk xl xr xL xR ≤ mk yl yr yL yR ↔ (∀ i, xL i ⧏ mk yl yr yL yR) ∧ ∀ j, mk xl xr xL xR ⧏ yR j := le_iff_forall_lf theorem le_of_forall_lf {x y : PGame} (h₁ : ∀ i, x.moveLeft i ⧏ y) (h₂ : ∀ j, x ⧏ y.moveRight j) : x ≤ y := le_iff_forall_lf.2 ⟨h₁, h₂⟩ /-- Definition of `x ⧏ y` on pre-games, in terms of `≤`. The ordering here is chosen so that `or.inl` refer to moves by Left, and `or.inr` refer to moves by Right. -/ theorem lf_iff_exists_le {x y : PGame} : x ⧏ y ↔ (∃ i, x ≤ y.moveLeft i) ∨ ∃ j, x.moveRight j ≤ y := by rw [LF, le_iff_forall_lf, not_and_or] simp /-- Definition of `x ⧏ y` on pre-games built using the constructor. -/ @[simp] theorem mk_lf_mk {xl xr xL xR yl yr yL yR} : mk xl xr xL xR ⧏ mk yl yr yL yR ↔ (∃ i, mk xl xr xL xR ≤ yL i) ∨ ∃ j, xR j ≤ mk yl yr yL yR := lf_iff_exists_le theorem le_or_gf (x y : PGame) : x ≤ y ∨ y ⧏ x := by rw [← PGame.not_le] apply em theorem moveLeft_lf_of_le {x y : PGame} (h : x ≤ y) (i) : x.moveLeft i ⧏ y := (le_iff_forall_lf.1 h).1 i alias _root_.LE.le.moveLeft_lf := moveLeft_lf_of_le theorem lf_moveRight_of_le {x y : PGame} (h : x ≤ y) (j) : x ⧏ y.moveRight j := (le_iff_forall_lf.1 h).2 j alias _root_.LE.le.lf_moveRight := lf_moveRight_of_le theorem lf_of_moveRight_le {x y : PGame} {j} (h : x.moveRight j ≤ y) : x ⧏ y := lf_iff_exists_le.2 <| Or.inr ⟨j, h⟩ theorem lf_of_le_moveLeft {x y : PGame} {i} (h : x ≤ y.moveLeft i) : x ⧏ y := lf_iff_exists_le.2 <| Or.inl ⟨i, h⟩ theorem lf_of_le_mk {xl xr xL xR y} : mk xl xr xL xR ≤ y → ∀ i, xL i ⧏ y := moveLeft_lf_of_le theorem lf_of_mk_le {x yl yr yL yR} : x ≤ mk yl yr yL yR → ∀ j, x ⧏ yR j := lf_moveRight_of_le theorem mk_lf_of_le {xl xr y j} (xL) {xR : xr → PGame} : xR j ≤ y → mk xl xr xL xR ⧏ y := @lf_of_moveRight_le (mk _ _ _ _) y j theorem lf_mk_of_le {x yl yr} {yL : yl → PGame} (yR) {i} : x ≤ yL i → x ⧏ mk yl yr yL yR := @lf_of_le_moveLeft x (mk _ _ _ _) i /- We prove that `x ≤ y → y ≤ z → x ≤ z` inductively, by also simultaneously proving its cyclic reorderings. This auxiliary lemma is used during said induction. -/ private theorem le_trans_aux {x y z : PGame} (h₁ : ∀ {i}, y ≤ z → z ≤ x.moveLeft i → y ≤ x.moveLeft i) (h₂ : ∀ {j}, z.moveRight j ≤ x → x ≤ y → z.moveRight j ≤ y) (hxy : x ≤ y) (hyz : y ≤ z) : x ≤ z := le_of_forall_lf (fun i => PGame.not_le.1 fun h => (h₁ hyz h).not_gf <| hxy.moveLeft_lf i) fun j => PGame.not_le.1 fun h => (h₂ h hxy).not_gf <| hyz.lf_moveRight j instance : Preorder PGame := { PGame.le with le_refl := fun x => by induction x with | mk _ _ _ _ IHl IHr => _ exact le_of_forall_lf (fun i => lf_of_le_moveLeft (IHl i)) fun i => lf_of_moveRight_le (IHr i) le_trans := by suffices ∀ {x y z : PGame}, (x ≤ y → y ≤ z → x ≤ z) ∧ (y ≤ z → z ≤ x → y ≤ x) ∧ (z ≤ x → x ≤ y → z ≤ y) from fun x y z => this.1 intro x y z induction x generalizing y z with | _ xl xr xL xR IHxl IHxr induction y generalizing z with | _ yl yr yL yR IHyl IHyr induction z with | _ zl zr zL zR IHzl IHzr exact ⟨le_trans_aux (fun {i} => (IHxl i).2.1) fun {j} => (IHzr j).2.2, le_trans_aux (fun {i} => (IHyl i).2.2) fun {j} => (IHxr j).1, le_trans_aux (fun {i} => (IHzl i).1) fun {j} => (IHyr j).2.1⟩ lt := fun x y => x ≤ y ∧ x ⧏ y } lemma Identical.le : ∀ {x y}, x ≡ y → x ≤ y | mk _ _ _ _, mk _ _ _ _, ⟨hL, hR⟩ => le_of_forall_lf (fun i ↦ let ⟨_, hj⟩ := hL.1 i; lf_of_le_moveLeft hj.le) (fun i ↦ let ⟨_, hj⟩ := hR.2 i; lf_of_moveRight_le hj.le) lemma Identical.ge {x y} (h : x ≡ y) : y ≤ x := h.symm.le theorem lt_iff_le_and_lf {x y : PGame} : x < y ↔ x ≤ y ∧ x ⧏ y := Iff.rfl theorem lt_of_le_of_lf {x y : PGame} (h₁ : x ≤ y) (h₂ : x ⧏ y) : x < y := ⟨h₁, h₂⟩ theorem lf_of_lt {x y : PGame} (h : x < y) : x ⧏ y := h.2 alias _root_.LT.lt.lf := lf_of_lt theorem lf_irrefl (x : PGame) : ¬x ⧏ x := le_rfl.not_gf instance : IsIrrefl _ (· ⧏ ·) := ⟨lf_irrefl⟩ protected theorem not_lt {x y : PGame} : ¬ x < y ↔ y ⧏ x ∨ y ≤ x := not_lt_iff_not_le_or_ge @[trans] theorem lf_of_le_of_lf {x y z : PGame} (h₁ : x ≤ y) (h₂ : y ⧏ z) : x ⧏ z := by rw [← PGame.not_le] at h₂ ⊢ exact fun h₃ => h₂ (h₃.trans h₁) instance : Trans (· ≤ ·) (· ⧏ ·) (· ⧏ ·) := ⟨lf_of_le_of_lf⟩ @[trans] theorem lf_of_lf_of_le {x y z : PGame} (h₁ : x ⧏ y) (h₂ : y ≤ z) : x ⧏ z := by rw [← PGame.not_le] at h₁ ⊢ exact fun h₃ => h₁ (h₂.trans h₃) instance : Trans (· ⧏ ·) (· ≤ ·) (· ⧏ ·) := ⟨lf_of_lf_of_le⟩ alias _root_.LE.le.trans_lf := lf_of_le_of_lf alias LF.trans_le := lf_of_lf_of_le @[trans] theorem lf_of_lt_of_lf {x y z : PGame} (h₁ : x < y) (h₂ : y ⧏ z) : x ⧏ z := h₁.le.trans_lf h₂ @[trans] theorem lf_of_lf_of_lt {x y z : PGame} (h₁ : x ⧏ y) (h₂ : y < z) : x ⧏ z := h₁.trans_le h₂.le alias _root_.LT.lt.trans_lf := lf_of_lt_of_lf alias LF.trans_lt := lf_of_lf_of_lt theorem moveLeft_lf {x : PGame} : ∀ i, x.moveLeft i ⧏ x := le_rfl.moveLeft_lf theorem lf_moveRight {x : PGame} : ∀ j, x ⧏ x.moveRight j := le_rfl.lf_moveRight theorem lf_mk {xl xr} (xL : xl → PGame) (xR : xr → PGame) (i) : xL i ⧏ mk xl xr xL xR := @moveLeft_lf (mk _ _ _ _) i theorem mk_lf {xl xr} (xL : xl → PGame) (xR : xr → PGame) (j) : mk xl xr xL xR ⧏ xR j := @lf_moveRight (mk _ _ _ _) j /-- This special case of `PGame.le_of_forall_lf` is useful when dealing with surreals, where `<` is preferred over `⧏`. -/ theorem le_of_forall_lt {x y : PGame} (h₁ : ∀ i, x.moveLeft i < y) (h₂ : ∀ j, x < y.moveRight j) : x ≤ y := le_of_forall_lf (fun i => (h₁ i).lf) fun i => (h₂ i).lf /-- The definition of `x ≤ y` on pre-games, in terms of `≤` two moves later. Note that it's often more convenient to use `le_iff_forall_lf`, which only unfolds the definition by one step. -/ theorem le_def {x y : PGame} : x ≤ y ↔ (∀ i, (∃ i', x.moveLeft i ≤ y.moveLeft i') ∨ ∃ j, (x.moveLeft i).moveRight j ≤ y) ∧ ∀ j, (∃ i, x ≤ (y.moveRight j).moveLeft i) ∨ ∃ j', x.moveRight j' ≤ y.moveRight j := by rw [le_iff_forall_lf] conv => lhs simp only [lf_iff_exists_le] /-- The definition of `x ⧏ y` on pre-games, in terms of `⧏` two moves later. Note that it's often more convenient to use `lf_iff_exists_le`, which only unfolds the definition by one step. -/ theorem lf_def {x y : PGame} : x ⧏ y ↔ (∃ i, (∀ i', x.moveLeft i' ⧏ y.moveLeft i) ∧ ∀ j, x ⧏ (y.moveLeft i).moveRight j) ∨ ∃ j, (∀ i, (x.moveRight j).moveLeft i ⧏ y) ∧ ∀ j', x.moveRight j ⧏ y.moveRight j' := by rw [lf_iff_exists_le] conv => lhs simp only [le_iff_forall_lf] /-- The definition of `0 ≤ x` on pre-games, in terms of `0 ⧏`. -/ theorem zero_le_lf {x : PGame} : 0 ≤ x ↔ ∀ j, 0 ⧏ x.moveRight j := by rw [le_iff_forall_lf] simp /-- The definition of `x ≤ 0` on pre-games, in terms of `⧏ 0`. -/ theorem le_zero_lf {x : PGame} : x ≤ 0 ↔ ∀ i, x.moveLeft i ⧏ 0 := by rw [le_iff_forall_lf] simp /-- The definition of `0 ⧏ x` on pre-games, in terms of `0 ≤`. -/ theorem zero_lf_le {x : PGame} : 0 ⧏ x ↔ ∃ i, 0 ≤ x.moveLeft i := by rw [lf_iff_exists_le] simp /-- The definition of `x ⧏ 0` on pre-games, in terms of `≤ 0`. -/ theorem lf_zero_le {x : PGame} : x ⧏ 0 ↔ ∃ j, x.moveRight j ≤ 0 := by rw [lf_iff_exists_le] simp /-- The definition of `0 ≤ x` on pre-games, in terms of `0 ≤` two moves later. -/ theorem zero_le {x : PGame} : 0 ≤ x ↔ ∀ j, ∃ i, 0 ≤ (x.moveRight j).moveLeft i := by rw [le_def] simp /-- The definition of `x ≤ 0` on pre-games, in terms of `≤ 0` two moves later. -/ theorem le_zero {x : PGame} : x ≤ 0 ↔ ∀ i, ∃ j, (x.moveLeft i).moveRight j ≤ 0 := by rw [le_def] simp /-- The definition of `0 ⧏ x` on pre-games, in terms of `0 ⧏` two moves later. -/ theorem zero_lf {x : PGame} : 0 ⧏ x ↔ ∃ i, ∀ j, 0 ⧏ (x.moveLeft i).moveRight j := by rw [lf_def] simp /-- The definition of `x ⧏ 0` on pre-games, in terms of `⧏ 0` two moves later. -/ theorem lf_zero {x : PGame} : x ⧏ 0 ↔ ∃ j, ∀ i, (x.moveRight j).moveLeft i ⧏ 0 := by rw [lf_def] simp @[simp] theorem zero_le_of_isEmpty_rightMoves (x : PGame) [IsEmpty x.RightMoves] : 0 ≤ x := zero_le.2 isEmptyElim @[simp] theorem le_zero_of_isEmpty_leftMoves (x : PGame) [IsEmpty x.LeftMoves] : x ≤ 0 := le_zero.2 isEmptyElim /-- Given a game won by the right player when they play second, provide a response to any move by left. -/ noncomputable def rightResponse {x : PGame} (h : x ≤ 0) (i : x.LeftMoves) : (x.moveLeft i).RightMoves := Classical.choose <| le_zero.1 h i /-- Show that the response for right provided by `rightResponse` preserves the right-player-wins condition. -/ theorem rightResponse_spec {x : PGame} (h : x ≤ 0) (i : x.LeftMoves) : (x.moveLeft i).moveRight (rightResponse h i) ≤ 0 := Classical.choose_spec <| le_zero.1 h i /-- Given a game won by the left player when they play second, provide a response to any move by right. -/ noncomputable def leftResponse {x : PGame} (h : 0 ≤ x) (j : x.RightMoves) : (x.moveRight j).LeftMoves := Classical.choose <| zero_le.1 h j /-- Show that the response for left provided by `leftResponse` preserves the left-player-wins condition. -/ theorem leftResponse_spec {x : PGame} (h : 0 ≤ x) (j : x.RightMoves) : 0 ≤ (x.moveRight j).moveLeft (leftResponse h j) := Classical.choose_spec <| zero_le.1 h j /-- A small family of pre-games is bounded above. -/ lemma bddAbove_range_of_small {ι : Type*} [Small.{u} ι] (f : ι → PGame.{u}) : BddAbove (Set.range f) := by let x : PGame.{u} := ⟨Σ i, (f <| (equivShrink.{u} ι).symm i).LeftMoves, PEmpty, fun x ↦ moveLeft _ x.2, PEmpty.elim⟩ refine ⟨x, Set.forall_mem_range.2 fun i ↦ ?_⟩ rw [← (equivShrink ι).symm_apply_apply i, le_iff_forall_lf] simpa [x] using fun j ↦ @moveLeft_lf x ⟨equivShrink ι i, j⟩ /-- A small set of pre-games is bounded above. -/ lemma bddAbove_of_small (s : Set PGame.{u}) [Small.{u} s] : BddAbove s := by simpa using bddAbove_range_of_small (Subtype.val : s → PGame.{u}) /-- A small family of pre-games is bounded below. -/ lemma bddBelow_range_of_small {ι : Type*} [Small.{u} ι] (f : ι → PGame.{u}) : BddBelow (Set.range f) := by let x : PGame.{u} := ⟨PEmpty, Σ i, (f <| (equivShrink.{u} ι).symm i).RightMoves, PEmpty.elim, fun x ↦ moveRight _ x.2⟩ refine ⟨x, Set.forall_mem_range.2 fun i ↦ ?_⟩ rw [← (equivShrink ι).symm_apply_apply i, le_iff_forall_lf] simpa [x] using fun j ↦ @lf_moveRight x ⟨equivShrink ι i, j⟩ /-- A small set of pre-games is bounded below. -/ lemma bddBelow_of_small (s : Set PGame.{u}) [Small.{u} s] : BddBelow s := by simpa using bddBelow_range_of_small (Subtype.val : s → PGame.{u}) /-- The equivalence relation on pre-games. Two pre-games `x`, `y` are equivalent if `x ≤ y` and `y ≤ x`. If `x ≈ 0`, then the second player can always win `x`. -/ def Equiv (x y : PGame) : Prop := x ≤ y ∧ y ≤ x instance : IsEquiv _ PGame.Equiv where refl _ := ⟨le_rfl, le_rfl⟩ trans := fun _ _ _ ⟨xy, yx⟩ ⟨yz, zy⟩ => ⟨xy.trans yz, zy.trans yx⟩ symm _ _ := And.symm instance setoid : Setoid PGame := ⟨Equiv, refl, symm, Trans.trans⟩ theorem equiv_def {x y : PGame} : x ≈ y ↔ x ≤ y ∧ y ≤ x := Iff.rfl theorem Equiv.le {x y : PGame} (h : x ≈ y) : x ≤ y := h.1 theorem Equiv.ge {x y : PGame} (h : x ≈ y) : y ≤ x := h.2 theorem equiv_rfl {x : PGame} : x ≈ x := refl x theorem equiv_refl (x : PGame) : x ≈ x := refl x @[symm] protected theorem Equiv.symm {x y : PGame} : (x ≈ y) → (y ≈ x) := symm @[trans] protected theorem Equiv.trans {x y z : PGame} : (x ≈ y) → (y ≈ z) → (x ≈ z) := _root_.trans protected theorem equiv_comm {x y : PGame} : (x ≈ y) ↔ (y ≈ x) := comm theorem equiv_of_eq {x y : PGame} (h : x = y) : x ≈ y := by subst h; rfl lemma Identical.equiv {x y} (h : x ≡ y) : x ≈ y := ⟨h.le, h.ge⟩ @[trans] theorem le_of_le_of_equiv {x y z : PGame} (h₁ : x ≤ y) (h₂ : y ≈ z) : x ≤ z := h₁.trans h₂.1 instance : Trans ((· ≤ ·) : PGame → PGame → Prop) ((· ≈ ·) : PGame → PGame → Prop) ((· ≤ ·) : PGame → PGame → Prop) where trans := le_of_le_of_equiv @[trans] theorem le_of_equiv_of_le {x y z : PGame} (h₁ : x ≈ y) : y ≤ z → x ≤ z := h₁.1.trans instance : Trans ((· ≈ ·) : PGame → PGame → Prop) ((· ≤ ·) : PGame → PGame → Prop) ((· ≤ ·) : PGame → PGame → Prop) where trans := le_of_equiv_of_le theorem LF.not_equiv {x y : PGame} (h : x ⧏ y) : ¬(x ≈ y) := fun h' => h.not_ge h'.2 theorem LF.not_equiv' {x y : PGame} (h : x ⧏ y) : ¬(y ≈ x) := fun h' => h.not_ge h'.1 theorem LF.not_gt {x y : PGame} (h : x ⧏ y) : ¬y < x := fun h' => h.not_ge h'.le theorem le_congr_imp {x₁ y₁ x₂ y₂ : PGame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) (h : x₁ ≤ y₁) : x₂ ≤ y₂ := hx.2.trans (h.trans hy.1) theorem le_congr {x₁ y₁ x₂ y₂ : PGame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ≤ y₁ ↔ x₂ ≤ y₂ := ⟨le_congr_imp hx hy, le_congr_imp (Equiv.symm hx) (Equiv.symm hy)⟩ theorem le_congr_left {x₁ x₂ y : PGame} (hx : x₁ ≈ x₂) : x₁ ≤ y ↔ x₂ ≤ y := le_congr hx equiv_rfl theorem le_congr_right {x y₁ y₂ : PGame} (hy : y₁ ≈ y₂) : x ≤ y₁ ↔ x ≤ y₂ := le_congr equiv_rfl hy theorem lf_congr {x₁ y₁ x₂ y₂ : PGame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ⧏ y₁ ↔ x₂ ⧏ y₂ := PGame.not_le.symm.trans <| (not_congr (le_congr hy hx)).trans PGame.not_le theorem lf_congr_imp {x₁ y₁ x₂ y₂ : PGame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ⧏ y₁ → x₂ ⧏ y₂ := (lf_congr hx hy).1 theorem lf_congr_left {x₁ x₂ y : PGame} (hx : x₁ ≈ x₂) : x₁ ⧏ y ↔ x₂ ⧏ y := lf_congr hx equiv_rfl theorem lf_congr_right {x y₁ y₂ : PGame} (hy : y₁ ≈ y₂) : x ⧏ y₁ ↔ x ⧏ y₂ := lf_congr equiv_rfl hy @[trans] theorem lf_of_lf_of_equiv {x y z : PGame} (h₁ : x ⧏ y) (h₂ : y ≈ z) : x ⧏ z := lf_congr_imp equiv_rfl h₂ h₁ instance : Trans (· ⧏ ·) (· ≈ ·) (· ⧏ ·) := ⟨lf_of_lf_of_equiv⟩ @[trans] theorem lf_of_equiv_of_lf {x y z : PGame} (h₁ : x ≈ y) : y ⧏ z → x ⧏ z := lf_congr_imp (Equiv.symm h₁) equiv_rfl instance : Trans (· ≈ ·) (· ⧏ ·) (· ⧏ ·) := ⟨lf_of_equiv_of_lf⟩ @[trans] theorem lt_of_lt_of_equiv {x y z : PGame} (h₁ : x < y) (h₂ : y ≈ z) : x < z := h₁.trans_le h₂.1 instance : Trans ((· < ·) : PGame → PGame → Prop) ((· ≈ ·) : PGame → PGame → Prop) ((· < ·) : PGame → PGame → Prop) where trans := lt_of_lt_of_equiv @[trans] theorem lt_of_equiv_of_lt {x y z : PGame} (h₁ : x ≈ y) : y < z → x < z := h₁.1.trans_lt instance : Trans ((· ≈ ·) : PGame → PGame → Prop) ((· < ·) : PGame → PGame → Prop) ((· < ·) : PGame → PGame → Prop) where trans := lt_of_equiv_of_lt theorem lt_congr_imp {x₁ y₁ x₂ y₂ : PGame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) (h : x₁ < y₁) : x₂ < y₂ := hx.2.trans_lt (h.trans_le hy.1) theorem lt_congr {x₁ y₁ x₂ y₂ : PGame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ < y₁ ↔ x₂ < y₂ := ⟨lt_congr_imp hx hy, lt_congr_imp (Equiv.symm hx) (Equiv.symm hy)⟩ theorem lt_congr_left {x₁ x₂ y : PGame} (hx : x₁ ≈ x₂) : x₁ < y ↔ x₂ < y := lt_congr hx equiv_rfl theorem lt_congr_right {x y₁ y₂ : PGame} (hy : y₁ ≈ y₂) : x < y₁ ↔ x < y₂ := lt_congr equiv_rfl hy theorem lt_or_equiv_of_le {x y : PGame} (h : x ≤ y) : x < y ∨ (x ≈ y) := and_or_left.mp ⟨h, (em <| y ≤ x).symm.imp_left PGame.not_le.1⟩ theorem lf_or_equiv_or_gf (x y : PGame) : x ⧏ y ∨ (x ≈ y) ∨ y ⧏ x := by rw [or_iff_not_imp_left] intro h rcases lt_or_equiv_of_le (PGame.not_lf.1 h) with h' | h' · exact Or.inr h'.lf · exact Or.inl (Equiv.symm h') theorem equiv_congr_left {y₁ y₂ : PGame} : (y₁ ≈ y₂) ↔ ∀ x₁, (x₁ ≈ y₁) ↔ (x₁ ≈ y₂) := ⟨fun h _ => ⟨fun h' => Equiv.trans h' h, fun h' => Equiv.trans h' (Equiv.symm h)⟩, fun h => (h y₁).1 <| equiv_rfl⟩ theorem equiv_congr_right {x₁ x₂ : PGame} : (x₁ ≈ x₂) ↔ ∀ y₁, (x₁ ≈ y₁) ↔ (x₂ ≈ y₁) := ⟨fun h _ => ⟨fun h' => Equiv.trans (Equiv.symm h) h', fun h' => Equiv.trans h h'⟩, fun h => (h x₂).2 <| equiv_rfl⟩ theorem Equiv.of_exists {x y : PGame} (hl₁ : ∀ i, ∃ j, x.moveLeft i ≈ y.moveLeft j) (hr₁ : ∀ i, ∃ j, x.moveRight i ≈ y.moveRight j) (hl₂ : ∀ j, ∃ i, x.moveLeft i ≈ y.moveLeft j) (hr₂ : ∀ j, ∃ i, x.moveRight i ≈ y.moveRight j) : x ≈ y := by constructor <;> refine le_def.2 ⟨?_, ?_⟩ <;> intro i · obtain ⟨j, hj⟩ := hl₁ i exact Or.inl ⟨j, Equiv.le hj⟩ · obtain ⟨j, hj⟩ := hr₂ i exact Or.inr ⟨j, Equiv.le hj⟩ · obtain ⟨j, hj⟩ := hl₂ i exact Or.inl ⟨j, Equiv.ge hj⟩ · obtain ⟨j, hj⟩ := hr₁ i exact Or.inr ⟨j, Equiv.ge hj⟩ theorem Equiv.of_equiv {x y : PGame} (L : x.LeftMoves ≃ y.LeftMoves) (R : x.RightMoves ≃ y.RightMoves) (hl : ∀ i, x.moveLeft i ≈ y.moveLeft (L i)) (hr : ∀ j, x.moveRight j ≈ y.moveRight (R j)) : x ≈ y := by apply Equiv.of_exists <;> intro i exacts [⟨_, hl i⟩, ⟨_, hr i⟩, ⟨_, by simpa using hl (L.symm i)⟩, ⟨_, by simpa using hr (R.symm i)⟩] /-- The fuzzy, confused, or incomparable relation on pre-games. If `x ‖ 0`, then the first player can always win `x`. -/ def Fuzzy (x y : PGame) : Prop := x ⧏ y ∧ y ⧏ x @[inherit_doc] scoped infixl:50 " ‖ " => PGame.Fuzzy @[symm] theorem Fuzzy.swap {x y : PGame} : x ‖ y → y ‖ x := And.symm instance : IsSymm _ (· ‖ ·) := ⟨fun _ _ => Fuzzy.swap⟩ theorem Fuzzy.swap_iff {x y : PGame} : x ‖ y ↔ y ‖ x := ⟨Fuzzy.swap, Fuzzy.swap⟩ theorem fuzzy_irrefl (x : PGame) : ¬x ‖ x := fun h => lf_irrefl x h.1 instance : IsIrrefl _ (· ‖ ·) := ⟨fuzzy_irrefl⟩ theorem lf_iff_lt_or_fuzzy {x y : PGame} : x ⧏ y ↔ x < y ∨ x ‖ y := by simp only [lt_iff_le_and_lf, Fuzzy, ← PGame.not_le] tauto theorem lf_of_fuzzy {x y : PGame} (h : x ‖ y) : x ⧏ y := lf_iff_lt_or_fuzzy.2 (Or.inr h) alias Fuzzy.lf := lf_of_fuzzy theorem lt_or_fuzzy_of_lf {x y : PGame} : x ⧏ y → x < y ∨ x ‖ y := lf_iff_lt_or_fuzzy.1 theorem Fuzzy.not_equiv {x y : PGame} (h : x ‖ y) : ¬(x ≈ y) := fun h' => h'.1.not_gf h.2 theorem Fuzzy.not_equiv' {x y : PGame} (h : x ‖ y) : ¬(y ≈ x) := fun h' => h'.2.not_gf h.2 theorem not_fuzzy_of_le {x y : PGame} (h : x ≤ y) : ¬x ‖ y := fun h' => h'.2.not_ge h theorem not_fuzzy_of_ge {x y : PGame} (h : y ≤ x) : ¬x ‖ y := fun h' => h'.1.not_ge h theorem Equiv.not_fuzzy {x y : PGame} (h : x ≈ y) : ¬x ‖ y := not_fuzzy_of_le h.1 theorem Equiv.not_fuzzy' {x y : PGame} (h : x ≈ y) : ¬y ‖ x := not_fuzzy_of_le h.2 theorem fuzzy_congr {x₁ y₁ x₂ y₂ : PGame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ‖ y₁ ↔ x₂ ‖ y₂ := show _ ∧ _ ↔ _ ∧ _ by rw [lf_congr hx hy, lf_congr hy hx] theorem fuzzy_congr_imp {x₁ y₁ x₂ y₂ : PGame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ‖ y₁ → x₂ ‖ y₂ := (fuzzy_congr hx hy).1 theorem fuzzy_congr_left {x₁ x₂ y : PGame} (hx : x₁ ≈ x₂) : x₁ ‖ y ↔ x₂ ‖ y := fuzzy_congr hx equiv_rfl theorem fuzzy_congr_right {x y₁ y₂ : PGame} (hy : y₁ ≈ y₂) : x ‖ y₁ ↔ x ‖ y₂ := fuzzy_congr equiv_rfl hy @[trans] theorem fuzzy_of_fuzzy_of_equiv {x y z : PGame} (h₁ : x ‖ y) (h₂ : y ≈ z) : x ‖ z := (fuzzy_congr_right h₂).1 h₁ @[trans] theorem fuzzy_of_equiv_of_fuzzy {x y z : PGame} (h₁ : x ≈ y) (h₂ : y ‖ z) : x ‖ z := (fuzzy_congr_left h₁).2 h₂ /-- Exactly one of the following is true (although we don't prove this here). -/ theorem lt_or_equiv_or_gt_or_fuzzy (x y : PGame) : x < y ∨ (x ≈ y) ∨ y < x ∨ x ‖ y := by rcases le_or_gf x y with h₁ | h₁ <;> rcases le_or_gf y x with h₂ | h₂ · right left exact ⟨h₁, h₂⟩ · left exact ⟨h₁, h₂⟩ · right right left exact ⟨h₂, h₁⟩ · right right right exact ⟨h₂, h₁⟩ theorem lt_or_equiv_or_gf (x y : PGame) : x < y ∨ (x ≈ y) ∨ y ⧏ x := by rw [lf_iff_lt_or_fuzzy, Fuzzy.swap_iff] exact lt_or_equiv_or_gt_or_fuzzy x y /-! ### Interaction of relabelling with order -/ theorem Relabelling.le {x y : PGame} (r : x ≡r y) : x ≤ y := le_def.2 ⟨fun i => Or.inl ⟨_, (r.moveLeft i).le⟩, fun j => Or.inr ⟨_, (r.moveRightSymm j).le⟩⟩ termination_by x theorem Relabelling.ge {x y : PGame} (r : x ≡r y) : y ≤ x := r.symm.le /-- A relabelling lets us prove equivalence of games. -/ theorem Relabelling.equiv {x y : PGame} (r : x ≡r y) : x ≈ y := ⟨r.le, r.ge⟩ theorem Equiv.isEmpty (x : PGame) [IsEmpty x.LeftMoves] [IsEmpty x.RightMoves] : x ≈ 0 := (Relabelling.isEmpty x).equiv instance {x y : PGame} : Coe (x ≡r y) (x ≈ y) := ⟨Relabelling.equiv⟩ /-! ### Interaction of option insertion with order -/ /-- A new left option cannot hurt Left. -/ lemma le_insertLeft (x x' : PGame) : x ≤ insertLeft x x' := by rw [le_def] constructor · intro i left rcases x with ⟨xl, xr, xL, xR⟩ simp only [insertLeft, leftMoves_mk, moveLeft_mk, Sum.exists, Sum.elim_inl] left use i · intro j right rcases x with ⟨xl, xr, xL, xR⟩ simp only [rightMoves_mk, moveRight_mk, insertLeft] use j /-- A new right option cannot hurt Right. -/ lemma insertRight_le (x x' : PGame) : insertRight x x' ≤ x := by rw [le_def] constructor · intro j left rcases x with ⟨xl, xr, xL, xR⟩ simp only [leftMoves_mk, moveLeft_mk, insertRight] use j · intro i right rcases x with ⟨xl, xr, xL, xR⟩ simp only [insertRight, rightMoves_mk, moveRight_mk, Sum.exists, Sum.elim_inl] left use i /-- Adding a gift horse left option does not change the value of `x`. A gift horse left option is a game `x'` with `x' ⧏ x`. It is called "gift horse" because it seems like Left has gotten the "gift" of a new option, but actually the value of the game did not change. -/ lemma insertLeft_equiv_of_lf {x x' : PGame} (h : x' ⧏ x) : insertLeft x x' ≈ x := by rw [equiv_def] constructor · rw [le_def] constructor · intro i rcases x with ⟨xl, xr, xL, xR⟩ simp only [insertLeft, moveLeft_mk] at i ⊢ rcases i with i | _ · rw [Sum.elim_inl] left use i · rw [Sum.elim_inr] simpa only [lf_iff_exists_le] using h · intro j right rcases x with ⟨xl, xr, xL, xR⟩ simp only [insertLeft, moveRight_mk] use j · apply le_insertLeft /-- Adding a gift horse right option does not change the value of `x`. A gift horse right option is a game `x'` with `x ⧏ x'`. It is called "gift horse" because it seems like Right has gotten the "gift" of a new option, but actually the value of the game did not change. -/ lemma insertRight_equiv_of_lf {x x' : PGame} (h : x ⧏ x') : insertRight x x' ≈ x := by rw [equiv_def] constructor · apply insertRight_le · rw [le_def] constructor · intro j left rcases x with ⟨xl, xr, xL, xR⟩ simp only [insertRight, moveLeft_mk] use j · intro i rcases x with ⟨xl, xr, xL, xR⟩ simp only [insertRight, moveRight_mk] at i ⊢ rcases i with i | _ · rw [Sum.elim_inl] right use i · rw [Sum.elim_inr] simpa only [lf_iff_exists_le] using h end SetTheory.PGame
SphereNormEquiv.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Analysis.Normed.Module.Basic import Mathlib.LinearAlgebra.Basis.VectorSpace /-! # Homeomorphism between a normed space and sphere times `(0, +∞)` In this file we define a homeomorphism between nonzero elements of a normed space `E` and `Metric.sphere (0 : E) 1 × Set.Ioi (0 : ℝ)`. One may think about it as generalization of polar coordinates to any normed space. -/ variable (E : Type*) [NormedAddCommGroup E] [NormedSpace ℝ E] open Set Metric /-- The natural homeomorphism between nonzero elements of a normed space `E` and `Metric.sphere (0 : E) 1 × Set.Ioi (0 : ℝ)`. The forward map sends `⟨x, hx⟩` to `⟨‖x‖⁻¹ • x, ‖x‖⟩`, the inverse map sends `(x, r)` to `r • x`. One may think about it as generalization of polar coordinates to any normed space. -/ @[simps apply_fst_coe apply_snd_coe symm_apply_coe] noncomputable def homeomorphUnitSphereProd : ({0}ᶜ : Set E) ≃ₜ (sphere (0 : E) 1 × Ioi (0 : ℝ)) where toFun x := (⟨‖x.1‖⁻¹ • x.1, by rw [mem_sphere_zero_iff_norm, norm_smul, norm_inv, norm_norm, inv_mul_cancel₀ (norm_ne_zero_iff.2 x.2)]⟩, ⟨‖x.1‖, norm_pos_iff.2 x.2⟩) invFun x := ⟨x.2.1 • x.1.1, smul_ne_zero x.2.2.out.ne' (ne_of_mem_sphere x.1.2 one_ne_zero)⟩ left_inv x := Subtype.eq <| by simp [smul_inv_smul₀ (norm_ne_zero_iff.2 x.2)] right_inv | (⟨x, hx⟩, ⟨r, hr⟩) => by rw [mem_sphere_zero_iff_norm] at hx rw [mem_Ioi] at hr ext <;> simp [hx, norm_smul, abs_of_pos hr, hr.ne'] continuous_toFun := by refine .prodMk (.codRestrict (.smul (.inv₀ ?_ ?_) ?_) _) ?_ · fun_prop · simp · fun_prop · fun_prop continuous_invFun := by apply Continuous.subtype_mk (by fun_prop)
Finpartition.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Data.Finset.Lattice.Prod import Mathlib.Data.Fintype.Powerset import Mathlib.Data.Setoid.Basic import Mathlib.Order.Atoms import Mathlib.Order.SupIndep import Mathlib.Data.Set.Finite.Basic import Mathlib.Algebra.BigOperators.Group.Finset.Basic /-! # Finite partitions In this file, we define finite partitions. A finpartition of `a : α` is a finite set of pairwise disjoint parts `parts : Finset α` which does not contain `⊥` and whose supremum is `a`. Finpartitions of a finset are at the heart of Szemerédi's regularity lemma. They are also studied purely order theoretically in Sperner theory. ## Constructions We provide many ways to build finpartitions: * `Finpartition.ofErase`: Builds a finpartition by erasing `⊥` for you. * `Finpartition.ofSubset`: Builds a finpartition from a subset of the parts of a previous finpartition. * `Finpartition.empty`: The empty finpartition of `⊥`. * `Finpartition.indiscrete`: The indiscrete, aka trivial, aka pure, finpartition made of a single part. * `Finpartition.discrete`: The discrete finpartition of `s : Finset α` made of singletons. * `Finpartition.bind`: Puts together the finpartitions of the parts of a finpartition into a new finpartition. * `Finpartition.ofExistsUnique`: Builds a finpartition from a collection of parts such that each element is in exactly one part. * `Finpartition.ofSetoid`: With `Fintype α`, constructs the finpartition of `univ : Finset α` induced by the equivalence classes of `s : Setoid α`. * `Finpartition.atomise`: Makes a finpartition of `s : Finset α` by breaking `s` along all finsets in `F : Finset (Finset α)`. Two elements of `s` belong to the same part iff they belong to the same elements of `F`. `Finpartition.indiscrete` and `Finpartition.bind` together form the monadic structure of `Finpartition`. ## Implementation notes Forbidding `⊥` as a part follows mathematical tradition and is a pragmatic choice concerning operations on `Finpartition`. Not caring about `⊥` being a part or not breaks extensionality (it's not because the parts of `P` and the parts of `Q` have the same elements that `P = Q`). Enforcing `⊥` to be a part makes `Finpartition.bind` uglier and doesn't rid us of the need of `Finpartition.ofErase`. ## TODO The order is the wrong way around to make `Finpartition a` a graded order. Is it bad to depart from the literature and turn the order around? The specialisation to `Finset α` could be generalised to atomistic orders. -/ open Finset Function variable {α : Type*} /-- A finite partition of `a : α` is a pairwise disjoint finite set of elements whose supremum is `a`. We forbid `⊥` as a part. -/ @[ext] structure Finpartition [Lattice α] [OrderBot α] (a : α) where /-- The elements of the finite partition of `a` -/ parts : Finset α /-- The partition is supremum-independent -/ protected supIndep : parts.SupIndep id /-- The supremum of the partition is `a` -/ sup_parts : parts.sup id = a /-- No element of the partition is bottom -/ bot_notMem : ⊥ ∉ parts deriving DecidableEq namespace Finpartition section Lattice variable [Lattice α] [OrderBot α] @[deprecated (since := "2025-05-23")] alias not_bot_mem := bot_notMem /-- A `Finpartition` constructor which does not insist on `⊥` not being a part. -/ @[simps] def ofErase [DecidableEq α] {a : α} (parts : Finset α) (sup_indep : parts.SupIndep id) (sup_parts : parts.sup id = a) : Finpartition a where parts := parts.erase ⊥ supIndep := sup_indep.subset (erase_subset _ _) sup_parts := (sup_erase_bot _).trans sup_parts bot_notMem := notMem_erase _ _ /-- A `Finpartition` constructor from a bigger existing finpartition. -/ @[simps] def ofSubset {a b : α} (P : Finpartition a) {parts : Finset α} (subset : parts ⊆ P.parts) (sup_parts : parts.sup id = b) : Finpartition b := { parts := parts supIndep := P.supIndep.subset subset sup_parts := sup_parts bot_notMem := fun h ↦ P.bot_notMem (subset h) } /-- Changes the type of a finpartition to an equal one. -/ @[simps] def copy {a b : α} (P : Finpartition a) (h : a = b) : Finpartition b where parts := P.parts supIndep := P.supIndep sup_parts := h ▸ P.sup_parts bot_notMem := P.bot_notMem /-- Transfer a finpartition over an order isomorphism. -/ def map {β : Type*} [Lattice β] [OrderBot β] {a : α} (e : α ≃o β) (P : Finpartition a) : Finpartition (e a) where parts := P.parts.map e supIndep u hu _ hb hbu _ hx hxu := by rw [← map_symm_subset] at hu simp only [mem_map_equiv] at hb have := P.supIndep hu hb (by simp [hbu]) (map_rel e.symm hx) ?_ · rw [← e.symm.map_bot] at this exact e.symm.map_rel_iff.mp this · convert e.symm.map_rel_iff.mpr hxu rw [map_finset_sup, sup_map] rfl sup_parts := by simp [← P.sup_parts] bot_notMem := by rw [mem_map_equiv] convert P.bot_notMem exact e.symm.map_bot @[simp] theorem parts_map {β : Type*} [Lattice β] [OrderBot β] {a : α} {e : α ≃o β} {P : Finpartition a} : (P.map e).parts = P.parts.map e := rfl variable (α) /-- The empty finpartition. -/ @[simps] protected def empty : Finpartition (⊥ : α) where parts := ∅ supIndep := supIndep_empty _ sup_parts := Finset.sup_empty bot_notMem := notMem_empty ⊥ instance : Inhabited (Finpartition (⊥ : α)) := ⟨Finpartition.empty α⟩ @[simp] theorem default_eq_empty : (default : Finpartition (⊥ : α)) = Finpartition.empty α := rfl variable {α} {a : α} /-- The finpartition in one part, aka indiscrete finpartition. -/ @[simps] def indiscrete (ha : a ≠ ⊥) : Finpartition a where parts := {a} supIndep := supIndep_singleton _ _ sup_parts := Finset.sup_singleton bot_notMem h := ha (mem_singleton.1 h).symm variable (P : Finpartition a) protected theorem le {b : α} (hb : b ∈ P.parts) : b ≤ a := (le_sup hb).trans P.sup_parts.le theorem ne_bot {b : α} (hb : b ∈ P.parts) : b ≠ ⊥ := by intro h refine P.bot_notMem (?_) rw [h] at hb exact hb protected theorem disjoint : (P.parts : Set α).PairwiseDisjoint id := P.supIndep.pairwiseDisjoint variable {P} @[simp] theorem parts_eq_empty_iff : P.parts = ∅ ↔ a = ⊥ := by simp_rw [← P.sup_parts] refine ⟨fun h ↦ ?_, fun h ↦ eq_empty_iff_forall_notMem.2 fun b hb ↦ P.bot_notMem ?_⟩ · rw [h] exact Finset.sup_empty · rwa [← le_bot_iff.1 ((le_sup hb).trans h.le)] @[simp] theorem parts_nonempty_iff : P.parts.Nonempty ↔ a ≠ ⊥ := by rw [nonempty_iff_ne_empty, not_iff_not, parts_eq_empty_iff] theorem parts_nonempty (P : Finpartition a) (ha : a ≠ ⊥) : P.parts.Nonempty := parts_nonempty_iff.2 ha instance : Unique (Finpartition (⊥ : α)) := { (inferInstance : Inhabited (Finpartition (⊥ : α))) with uniq := fun P ↦ by ext a exact iff_of_false (fun h ↦ P.ne_bot h <| le_bot_iff.1 <| P.le h) (notMem_empty a) } -- See note [reducible non instances] /-- There's a unique partition of an atom. -/ abbrev _root_.IsAtom.uniqueFinpartition (ha : IsAtom a) : Unique (Finpartition a) where default := indiscrete ha.1 uniq P := by have h : ∀ b ∈ P.parts, b = a := fun _ hb ↦ (ha.le_iff.mp <| P.le hb).resolve_left (P.ne_bot hb) ext b refine Iff.trans ⟨h b, ?_⟩ mem_singleton.symm rintro rfl obtain ⟨c, hc⟩ := P.parts_nonempty ha.1 simp_rw [← h c hc] exact hc instance [Fintype α] [DecidableEq α] (a : α) : Fintype (Finpartition a) := @Fintype.ofSurjective { p : Finset α // p.SupIndep id ∧ p.sup id = a ∧ ⊥ ∉ p } (Finpartition a) _ (Subtype.fintype _) (fun i ↦ ⟨i.1, i.2.1, i.2.2.1, i.2.2.2⟩) fun ⟨_, y, z, w⟩ ↦ ⟨⟨_, y, z, w⟩, rfl⟩ /-! ### Refinement order -/ section Order /-- We say that `P ≤ Q` if `P` refines `Q`: each part of `P` is less than some part of `Q`. -/ instance : LE (Finpartition a) := ⟨fun P Q ↦ ∀ ⦃b⦄, b ∈ P.parts → ∃ c ∈ Q.parts, b ≤ c⟩ instance : PartialOrder (Finpartition a) := { (inferInstance : LE (Finpartition a)) with le_refl := fun _ b hb ↦ ⟨b, hb, le_rfl⟩ le_trans := fun _ Q R hPQ hQR b hb ↦ by obtain ⟨c, hc, hbc⟩ := hPQ hb obtain ⟨d, hd, hcd⟩ := hQR hc exact ⟨d, hd, hbc.trans hcd⟩ le_antisymm := fun P Q hPQ hQP ↦ by ext b refine ⟨fun hb ↦ ?_, fun hb ↦ ?_⟩ · obtain ⟨c, hc, hbc⟩ := hPQ hb obtain ⟨d, hd, hcd⟩ := hQP hc rwa [hbc.antisymm] rwa [P.disjoint.eq_of_le hb hd (P.ne_bot hb) (hbc.trans hcd)] · obtain ⟨c, hc, hbc⟩ := hQP hb obtain ⟨d, hd, hcd⟩ := hPQ hc rwa [hbc.antisymm] rwa [Q.disjoint.eq_of_le hb hd (Q.ne_bot hb) (hbc.trans hcd)] } instance [Decidable (a = ⊥)] : OrderTop (Finpartition a) where top := if ha : a = ⊥ then (Finpartition.empty α).copy ha.symm else indiscrete ha le_top P := by split_ifs with h · intro x hx simpa [h, P.ne_bot hx] using P.le hx · exact fun b hb ↦ ⟨a, mem_singleton_self _, P.le hb⟩ theorem parts_top_subset (a : α) [Decidable (a = ⊥)] : (⊤ : Finpartition a).parts ⊆ {a} := by intro b hb have hb : b ∈ Finpartition.parts (dite _ _ _) := hb split_ifs at hb · simp only [copy_parts, empty_parts, notMem_empty] at hb · exact hb theorem parts_top_subsingleton (a : α) [Decidable (a = ⊥)] : ((⊤ : Finpartition a).parts : Set α).Subsingleton := Set.subsingleton_of_subset_singleton fun _ hb ↦ mem_singleton.1 <| parts_top_subset _ hb -- TODO: this instance takes double-exponential time to generate all partitions, find a faster way instance [DecidableEq α] {s : Finset α} : Fintype (Finpartition s) where elems := s.powerset.powerset.image fun ps ↦ if h : ps.sup id = s ∧ ⊥ ∉ ps ∧ ps.SupIndep id then ⟨ps, h.2.2, h.1, h.2.1⟩ else ⊤ complete P := by refine mem_image.mpr ⟨P.parts, ?_, ?_⟩ · rw [mem_powerset]; intro p hp; rw [mem_powerset]; exact P.le hp · simp [P.supIndep, P.sup_parts, P.bot_notMem, -bot_eq_empty] end Order end Lattice section DistribLattice variable [DistribLattice α] [OrderBot α] section Inf variable [DecidableEq α] {a b c : α} instance : Min (Finpartition a) := ⟨fun P Q ↦ ofErase ((P.parts ×ˢ Q.parts).image fun bc ↦ bc.1 ⊓ bc.2) (by rw [supIndep_iff_disjoint_erase] simp only [mem_image, and_imp, forall_exists_index, id, Prod.exists, mem_product, Finset.disjoint_sup_right, mem_erase, Ne] rintro _ x₁ y₁ hx₁ hy₁ rfl _ h x₂ y₂ hx₂ hy₂ rfl rcases eq_or_ne x₁ x₂ with (rfl | xdiff) · refine Disjoint.mono inf_le_right inf_le_right (Q.disjoint hy₁ hy₂ ?_) intro t simp [t] at h exact Disjoint.mono inf_le_left inf_le_left (P.disjoint hx₁ hx₂ xdiff)) (by rw [sup_image, id_comp, sup_product_left] trans P.parts.sup id ⊓ Q.parts.sup id · simp_rw [Finset.sup_inf_distrib_right, Finset.sup_inf_distrib_left] rfl · rw [P.sup_parts, Q.sup_parts, inf_idem])⟩ @[simp] theorem parts_inf (P Q : Finpartition a) : (P ⊓ Q).parts = ((P.parts ×ˢ Q.parts).image fun bc : α × α ↦ bc.1 ⊓ bc.2).erase ⊥ := rfl instance : SemilatticeInf (Finpartition a) := { inf := Min.min inf_le_left := fun P Q b hb ↦ by obtain ⟨c, hc, rfl⟩ := mem_image.1 (mem_of_mem_erase hb) rw [mem_product] at hc exact ⟨c.1, hc.1, inf_le_left⟩ inf_le_right := fun P Q b hb ↦ by obtain ⟨c, hc, rfl⟩ := mem_image.1 (mem_of_mem_erase hb) rw [mem_product] at hc exact ⟨c.2, hc.2, inf_le_right⟩ le_inf := fun P Q R hPQ hPR b hb ↦ by obtain ⟨c, hc, hbc⟩ := hPQ hb obtain ⟨d, hd, hbd⟩ := hPR hb have h := _root_.le_inf hbc hbd refine ⟨c ⊓ d, mem_erase_of_ne_of_mem (ne_bot_of_le_ne_bot (P.ne_bot hb) h) (mem_image.2 ⟨(c, d), mem_product.2 ⟨hc, hd⟩, rfl⟩), h⟩ } end Inf theorem exists_le_of_le {a b : α} {P Q : Finpartition a} (h : P ≤ Q) (hb : b ∈ Q.parts) : ∃ c ∈ P.parts, c ≤ b := by by_contra H refine Q.ne_bot hb (disjoint_self.1 <| Disjoint.mono_right (Q.le hb) ?_) rw [← P.sup_parts, Finset.disjoint_sup_right] rintro c hc obtain ⟨d, hd, hcd⟩ := h hc refine (Q.disjoint hb hd ?_).mono_right hcd rintro rfl simp only [not_exists, not_and] at H exact H _ hc hcd theorem card_mono {a : α} {P Q : Finpartition a} (h : P ≤ Q) : #Q.parts ≤ #P.parts := by classical have : ∀ b ∈ Q.parts, ∃ c ∈ P.parts, c ≤ b := fun b ↦ exists_le_of_le h choose f hP hf using this rw [← card_attach] refine card_le_card_of_injOn (fun b ↦ f _ b.2) (fun b _ ↦ hP _ b.2) fun b _ c _ h ↦ ?_ exact Subtype.coe_injective (Q.disjoint.elim b.2 c.2 fun H ↦ P.ne_bot (hP _ b.2) <| disjoint_self.1 <| H.mono (hf _ b.2) <| h.le.trans <| hf _ c.2) variable [DecidableEq α] {a b c : α} section Bind variable {P : Finpartition a} {Q : ∀ i ∈ P.parts, Finpartition i} /-- Given a finpartition `P` of `a` and finpartitions of each part of `P`, this yields the finpartition of `a` obtained by juxtaposing all the subpartitions. -/ @[simps] def bind (P : Finpartition a) (Q : ∀ i ∈ P.parts, Finpartition i) : Finpartition a where parts := P.parts.attach.biUnion fun i ↦ (Q i.1 i.2).parts supIndep := by rw [supIndep_iff_pairwiseDisjoint] rintro a ha b hb h rw [Finset.mem_coe, Finset.mem_biUnion] at ha hb obtain ⟨⟨A, hA⟩, -, ha⟩ := ha obtain ⟨⟨B, hB⟩, -, hb⟩ := hb obtain rfl | hAB := eq_or_ne A B · exact (Q A hA).disjoint ha hb h · exact (P.disjoint hA hB hAB).mono ((Q A hA).le ha) ((Q B hB).le hb) sup_parts := by simp_rw [sup_biUnion] trans (sup P.parts id) · rw [eq_comm, ← Finset.sup_attach] exact sup_congr rfl fun b _hb ↦ (Q b.1 b.2).sup_parts.symm · exact P.sup_parts bot_notMem h := by rw [Finset.mem_biUnion] at h obtain ⟨⟨A, hA⟩, -, h⟩ := h exact (Q A hA).bot_notMem h theorem mem_bind : b ∈ (P.bind Q).parts ↔ ∃ A hA, b ∈ (Q A hA).parts := by rw [bind, mem_biUnion] constructor · rintro ⟨⟨A, hA⟩, -, h⟩ exact ⟨A, hA, h⟩ · rintro ⟨A, hA, h⟩ exact ⟨⟨A, hA⟩, mem_attach _ ⟨A, hA⟩, h⟩ theorem card_bind (Q : ∀ i ∈ P.parts, Finpartition i) : #(P.bind Q).parts = ∑ A ∈ P.parts.attach, #(Q _ A.2).parts := by apply card_biUnion rintro ⟨b, hb⟩ - ⟨c, hc⟩ - hbc rw [Function.onFun, Finset.disjoint_left] rintro d hdb hdc rw [Ne, Subtype.mk_eq_mk] at hbc exact (Q b hb).ne_bot hdb (eq_bot_iff.2 <| (le_inf ((Q b hb).le hdb) <| (Q c hc).le hdc).trans <| (P.disjoint hb hc hbc).le_bot) end Bind /-- Adds `b` to a finpartition of `a` to make a finpartition of `a ⊔ b`. -/ @[simps] def extend (P : Finpartition a) (hb : b ≠ ⊥) (hab : Disjoint a b) (hc : a ⊔ b = c) : Finpartition c where parts := insert b P.parts supIndep := by rw [supIndep_iff_pairwiseDisjoint, coe_insert] exact P.disjoint.insert fun d hd _ ↦ hab.symm.mono_right <| P.le hd sup_parts := by rwa [sup_insert, P.sup_parts, id, _root_.sup_comm] bot_notMem h := (mem_insert.1 h).elim hb.symm P.bot_notMem theorem card_extend (P : Finpartition a) (b c : α) {hb : b ≠ ⊥} {hab : Disjoint a b} {hc : a ⊔ b = c} : #(P.extend hb hab hc).parts = #P.parts + 1 := card_insert_of_notMem fun h ↦ hb <| hab.symm.eq_bot_of_le <| P.le h end DistribLattice section GeneralizedBooleanAlgebra variable [GeneralizedBooleanAlgebra α] [DecidableEq α] {a b c : α} (P : Finpartition a) /-- Restricts a finpartition to avoid a given element. -/ @[simps!] def avoid (b : α) : Finpartition (a \ b) := ofErase (P.parts.image (· \ b)) (P.disjoint.image_finset_of_le fun _ ↦ sdiff_le).supIndep (by rw [sup_image, id_comp, Finset.sup_sdiff_right, ← Function.id_def, P.sup_parts]) @[simp] theorem mem_avoid : c ∈ (P.avoid b).parts ↔ ∃ d ∈ P.parts, ¬d ≤ b ∧ d \ b = c := by simp only [avoid, ofErase, mem_erase, Ne, mem_image, ← exists_and_left, @and_left_comm (c ≠ ⊥)] refine exists_congr fun d ↦ and_congr_right' <| and_congr_left ?_ rintro rfl rw [sdiff_eq_bot_iff] end GeneralizedBooleanAlgebra end Finpartition /-! ### Finite partitions of finsets -/ namespace Finpartition variable [DecidableEq α] {s t u : Finset α} (P : Finpartition s) {a : α} lemma subset {a : Finset α} (ha : a ∈ P.parts) : a ⊆ s := P.le ha theorem nonempty_of_mem_parts {a : Finset α} (ha : a ∈ P.parts) : a.Nonempty := nonempty_iff_ne_empty.2 <| P.ne_bot ha @[simp] theorem empty_notMem_parts : ∅ ∉ P.parts := P.bot_notMem @[deprecated (since := "2025-05-23")] alias not_empty_mem_parts := empty_notMem_parts theorem ne_empty (h : t ∈ P.parts) : t ≠ ∅ := P.ne_bot h lemma eq_of_mem_parts (ht : t ∈ P.parts) (hu : u ∈ P.parts) (hat : a ∈ t) (hau : a ∈ u) : t = u := P.disjoint.elim ht hu <| not_disjoint_iff.2 ⟨a, hat, hau⟩ theorem exists_mem (ha : a ∈ s) : ∃ t ∈ P.parts, a ∈ t := by simp_rw [← P.sup_parts] at ha exact mem_sup.1 ha theorem biUnion_parts : P.parts.biUnion id = s := (sup_eq_biUnion _ _).symm.trans P.sup_parts theorem existsUnique_mem (ha : a ∈ s) : ∃! t, t ∈ P.parts ∧ a ∈ t := by obtain ⟨t, ht, ht'⟩ := P.exists_mem ha refine ⟨t, ⟨ht, ht'⟩, ?_⟩ rintro u ⟨hu, hu'⟩ exact P.eq_of_mem_parts hu ht hu' ht' /-- Construct a `Finpartition s` from a finset of finsets `parts` such that each element of `s` is in exactly one member of `parts`. This provides a converse to `Finpartition.subset`, `Finpartition.not_empty_mem_parts` and `Finpartition.existsUnique_mem`. -/ @[simps] def ofExistsUnique (parts : Finset (Finset α)) (h : ∀ p ∈ parts, p ⊆ s) (h' : ∀ a ∈ s, ∃! t ∈ parts, a ∈ t) (h'' : ∅ ∉ parts) : Finpartition s where parts := parts supIndep := by simp only [supIndep_iff_pairwiseDisjoint] intro a ha b hb hab rw [Function.onFun, Finset.disjoint_left] intro x hx hx' exact hab ((h' x (h _ ha hx)).unique ⟨ha, hx⟩ ⟨hb, hx'⟩) sup_parts := by ext i simp only [mem_sup, id_eq] constructor · rintro ⟨j, hj, hj'⟩ exact h j hj hj' · rintro hi exact (h' i hi).exists bot_notMem := h'' /-- The part of the finpartition that `a` lies in. -/ def part (a : α) : Finset α := if ha : a ∈ s then choose (hp := P.existsUnique_mem ha) else ∅ @[simp] lemma part_mem : P.part a ∈ P.parts ↔ a ∈ s := by by_cases ha : a ∈ s <;> simp [part, ha, choose_mem] @[simp] lemma part_eq_empty : P.part a = ∅ ↔ a ∉ s := ⟨fun h has ↦ P.ne_empty (P.part_mem.2 has) h, fun h ↦ by simp [part, h]⟩ @[simp] lemma part_nonempty : (P.part a).Nonempty ↔ a ∈ s := by simpa only [nonempty_iff_ne_empty] using P.part_eq_empty.not_left @[simp] lemma part_subset (a : α) : P.part a ⊆ s := by by_cases ha : a ∈ s · exact P.le <| P.part_mem.2 ha · simp [P.part_eq_empty.2 ha] @[simp] lemma mem_part_self : a ∈ P.part a ↔ a ∈ s := by by_cases ha : a ∈ s · simp [part, ha, choose_property (p := fun s => a ∈ s) P.parts (P.existsUnique_mem ha)] · simp [P.part_eq_empty.2, ha] alias ⟨_, mem_part⟩ := mem_part_self lemma part_eq_iff_mem (ht : t ∈ P.parts) : P.part a = t ↔ a ∈ t := by constructor · rintro rfl simp_all · intro hat apply P.eq_of_mem_parts (a := a) <;> simp [*, P.le ht hat] lemma part_eq_of_mem (ht : t ∈ P.parts) (hat : a ∈ t) : P.part a = t := (P.part_eq_iff_mem ht).2 hat lemma mem_part_iff_part_eq_part {b : α} (ha : a ∈ s) (hb : b ∈ s) : a ∈ P.part b ↔ P.part a = P.part b := ⟨fun c ↦ (P.part_eq_of_mem (P.part_mem.2 hb) c), fun c ↦ c ▸ P.mem_part ha⟩ theorem part_surjOn : Set.SurjOn P.part s P.parts := fun p hp ↦ by obtain ⟨x, hx⟩ := P.nonempty_of_mem_parts hp have hx' := mem_of_subset (P.le hp) hx use x, hx', (P.existsUnique_mem hx').unique ⟨P.part_mem.2 hx', P.mem_part hx'⟩ ⟨hp, hx⟩ theorem exists_subset_part_bijOn : ∃ r ⊆ s, Set.BijOn P.part r P.parts := by obtain ⟨r, hrs, hr⟩ := P.part_surjOn.exists_bijOn_subset lift r to Finset α using s.finite_toSet.subset hrs exact ⟨r, mod_cast hrs, hr⟩ theorem mem_part_iff_exists {b} : a ∈ P.part b ↔ ∃ p ∈ P.parts, a ∈ p ∧ b ∈ p := by constructor · intro h have : b ∈ s := P.part_nonempty.1 ⟨a, h⟩ refine ⟨_, ?_, h, ?_⟩ <;> simp [this] · rintro ⟨p, hp, hap, hbp⟩ obtain rfl : P.part b = p := P.part_eq_of_mem hp hbp exact hap /-- Equivalence between a finpartition's parts as a dependent sum and the partitioned set. -/ def equivSigmaParts : s ≃ Σ t : P.parts, t.1 where toFun x := ⟨⟨P.part x.1, P.part_mem.2 x.2⟩, ⟨x, P.mem_part x.2⟩⟩ invFun x := ⟨x.2, mem_of_subset (P.le x.1.2) x.2.2⟩ left_inv x := by simp right_inv x := by ext e · obtain ⟨⟨p, mp⟩, ⟨f, mf⟩⟩ := x dsimp only at mf ⊢ rw [P.part_eq_of_mem mp mf] · simp lemma exists_enumeration : ∃ f : s ≃ Σ t : P.parts, Fin #t.1, ∀ a b : s, P.part a = P.part b ↔ (f a).1 = (f b).1 := by use P.equivSigmaParts.trans ((Equiv.refl _).sigmaCongr (fun t ↦ t.1.equivFin)) simp [equivSigmaParts, Equiv.sigmaCongr, Equiv.sigmaCongrLeft] theorem sum_card_parts : ∑ i ∈ P.parts, #i = #s := by convert congr_arg Finset.card P.biUnion_parts rw [card_biUnion P.supIndep.pairwiseDisjoint] rfl /-- `⊥` is the partition in singletons, aka discrete partition. -/ instance (s : Finset α) : Bot (Finpartition s) := ⟨{ parts := s.map ⟨singleton, singleton_injective⟩ supIndep := Set.PairwiseDisjoint.supIndep <| by rw [Finset.coe_map] exact Finset.pairwiseDisjoint_range_singleton.subset (Set.image_subset_range _ _) sup_parts := by rw [sup_map, id_comp, Embedding.coeFn_mk, Finset.sup_singleton_eq_self] bot_notMem := by simp }⟩ @[simp] theorem parts_bot (s : Finset α) : (⊥ : Finpartition s).parts = s.map ⟨singleton, singleton_injective⟩ := rfl theorem card_bot (s : Finset α) : #(⊥ : Finpartition s).parts = #s := Finset.card_map _ theorem mem_bot_iff : t ∈ (⊥ : Finpartition s).parts ↔ ∃ a ∈ s, {a} = t := mem_map instance (s : Finset α) : OrderBot (Finpartition s) := { (inferInstance : Bot (Finpartition s)) with bot_le := fun P t ht ↦ by rw [mem_bot_iff] at ht obtain ⟨a, ha, rfl⟩ := ht obtain ⟨t, ht, hat⟩ := P.exists_mem ha exact ⟨t, ht, singleton_subset_iff.2 hat⟩ } theorem card_parts_le_card : #P.parts ≤ #s := by rw [← card_bot s] exact card_mono bot_le lemma card_mod_card_parts_le : #s % #P.parts ≤ #P.parts := by obtain h | h := (#P.parts).eq_zero_or_pos · rw [h] rw [Finset.card_eq_zero, parts_eq_empty_iff, bot_eq_empty, ← Finset.card_eq_zero] at h rw [h] · exact (Nat.mod_lt _ h).le section SetSetoid /-- A setoid over a finite type induces a finpartition of the type's elements, where the parts are the setoid's equivalence classes. -/ @[simps -isSimp] def ofSetSetoid (s : Setoid α) (x : Finset α) [DecidableRel s.r] : Finpartition x where parts := x.image fun a ↦ {b ∈ x | s.r a b} supIndep := by suffices ∀ (a b c d : α), s a d → s b d → (s a c ↔ s b c) by simp only [supIndep_iff_pairwiseDisjoint, Set.PairwiseDisjoint, Set.Pairwise, coe_image, Set.mem_image, mem_coe, ne_eq, onFun, id_eq, disjoint_iff_ne, forall_mem_not_eq, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, mem_filter, not_and, filter_inj', not_forall, @not_imp_comm (_ ↔ _), Decidable.not_not] intro _ _ _ _ _ _ _ _ ha _ hb exact ⟨(s.trans' hb <| s.trans' (s.symm' ha) ·), (s.trans' ha <| s.trans' (s.symm' hb) ·)⟩ simp +contextual [← Quotient.eq] sup_parts := by ext a simp_rw [sup_image, id_comp, mem_sup, mem_filter] refine ⟨(·.choose_spec.2.1), fun _ ↦ by use a⟩ bot_notMem := by suffices ∀ x₁ ∈ x, ∃ x₂ ∈ x, s x₁ x₂ by simpa [filter_eq_empty_iff] intro x _ use x theorem mem_part_ofSetSetoid_iff_rel {s : Setoid α} (x : Finset α) [DecidableRel s.r] {b : α} : b ∈ (ofSetSetoid s x).part a ↔ a ∈ x ∧ b ∈ x ∧ s a b := by suffices (∃ a₁ ∈ x, (b ∈ x ∧ s a₁ b) ∧ a ∈ x ∧ s a₁ a) ↔ a ∈ x ∧ b ∈ x ∧ s a b by simpa [mem_part_iff_exists, ofSetSetoid_parts] exact ⟨ fun ⟨c, _, ⟨hb, hcb⟩, ⟨ha, hca⟩⟩ ↦ ⟨ha, hb, s.trans' (s.symm' hca) hcb⟩, fun h ↦ ⟨a, ⟨h.1, ⟨⟨h.2.1, h.2.2⟩, ⟨h.1, s.refl _⟩⟩⟩⟩ ⟩ end SetSetoid section Setoid variable [Fintype α] /-- A setoid over a finite type induces a finpartition of the type's elements, where the parts are the setoid's equivalence classes. -/ @[simps! -isSimp] def ofSetoid (s : Setoid α) [DecidableRel s.r] : Finpartition (univ : Finset α) := ofSetSetoid s univ theorem mem_part_ofSetoid_iff_rel {s : Setoid α} [DecidableRel s.r] {b : α} : b ∈ (ofSetoid s).part a ↔ s a b := by suffices b ∈ (ofSetSetoid s univ).part a ↔ a ∈ univ ∧ b ∈ univ ∧ s a b by simpa exact mem_part_ofSetSetoid_iff_rel univ end Setoid section Atomise /-- Cuts `s` along the finsets in `F`: Two elements of `s` will be in the same part if they are in the same finsets of `F`. -/ def atomise (s : Finset α) (F : Finset (Finset α)) : Finpartition s := ofErase (F.powerset.image fun Q ↦ {i ∈ s | ∀ t ∈ F, t ∈ Q ↔ i ∈ t}) (Set.PairwiseDisjoint.supIndep fun x hx y hy h ↦ disjoint_left.mpr fun z hz1 hz2 ↦ h (by rw [mem_coe, mem_image] at hx hy obtain ⟨Q, hQ, rfl⟩ := hx obtain ⟨R, hR, rfl⟩ := hy suffices h' : Q = R by subst h' exact of_eq_true (eq_self {i ∈ s | ∀ t ∈ F, t ∈ Q ↔ i ∈ t}) rw [id, mem_filter] at hz1 hz2 rw [mem_powerset] at hQ hR ext i refine ⟨fun hi ↦ ?_, fun hi ↦ ?_⟩ · rwa [hz2.2 _ (hQ hi), ← hz1.2 _ (hQ hi)] · rwa [hz1.2 _ (hR hi), ← hz2.2 _ (hR hi)])) (by refine (Finset.sup_le fun t ht ↦ ?_).antisymm fun a ha ↦ ?_ · rw [mem_image] at ht obtain ⟨A, _, rfl⟩ := ht exact s.filter_subset _ · rw [mem_sup] refine ⟨{i ∈ s | ∀ t ∈ F, t ∈ {u ∈ F | a ∈ u} ↔ i ∈ t}, mem_image_of_mem _ (mem_powerset.2 <| filter_subset _ _), mem_filter.2 ⟨ha, fun t ht ↦ ?_⟩⟩ rw [mem_filter] exact and_iff_right ht) variable {F : Finset (Finset α)} theorem mem_atomise : t ∈ (atomise s F).parts ↔ t.Nonempty ∧ ∃ Q ⊆ F, {i ∈ s | ∀ u ∈ F, u ∈ Q ↔ i ∈ u} = t := by simp only [atomise, ofErase, bot_eq_empty, mem_erase, mem_image, nonempty_iff_ne_empty, mem_powerset] theorem atomise_empty (hs : s.Nonempty) : (atomise s ∅).parts = {s} := by simp only [atomise, powerset_empty, image_singleton, notMem_empty, IsEmpty.forall_iff, imp_true_iff, filter_True] exact erase_eq_of_notMem (notMem_singleton.2 hs.ne_empty.symm) theorem card_atomise_le : #(atomise s F).parts ≤ 2 ^ #F := (card_le_card <| erase_subset _ _).trans <| Finset.card_image_le.trans (card_powerset _).le theorem biUnion_filter_atomise (ht : t ∈ F) (hts : t ⊆ s) : {u ∈ (atomise s F).parts | u ⊆ t ∧ u.Nonempty}.biUnion id = t := by ext a refine mem_biUnion.trans ⟨fun ⟨u, hu, ha⟩ ↦ (mem_filter.1 hu).2.1 ha, fun ha ↦ ?_⟩ obtain ⟨u, hu, hau⟩ := (atomise s F).exists_mem (hts ha) refine ⟨u, mem_filter.2 ⟨hu, fun b hb ↦ ?_, _, hau⟩, hau⟩ obtain ⟨Q, _hQ, rfl⟩ := (mem_atomise.1 hu).2 rw [mem_filter] at hau hb rwa [← hb.2 _ ht, hau.2 _ ht] theorem card_filter_atomise_le_two_pow (ht : t ∈ F) : #{u ∈ (atomise s F).parts | u ⊆ t ∧ u.Nonempty} ≤ 2 ^ (#F - 1) := by suffices h : {u ∈ (atomise s F).parts | u ⊆ t ∧ u.Nonempty} ⊆ (F.erase t).powerset.image fun P ↦ {i ∈ s | ∀ x ∈ F, x ∈ insert t P ↔ i ∈ x} by refine (card_le_card h).trans (card_image_le.trans ?_) rw [card_powerset, card_erase_of_mem ht] rw [subset_iff] simp_rw [mem_image, mem_powerset, mem_filter, and_imp, Finset.Nonempty, exists_imp, mem_atomise, and_imp, Finset.Nonempty, exists_imp, and_imp] rintro P' i hi P PQ rfl hy₂ j _hj refine ⟨P.erase t, erase_subset_erase _ PQ, ?_⟩ simp only [insert_erase (((mem_filter.1 hi).2 _ ht).2 <| hy₂ hi)] end Atomise end Finpartition
algebraics_fundamentals.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun ssrnat eqtype seq choice. From mathcomp Require Import div fintype path tuple bigop finset prime order. From mathcomp Require Import ssralg poly polydiv mxpoly countalg closed_field. From mathcomp Require Import ssrnum ssrint archimedean rat intdiv fingroup. From mathcomp Require Import finalg zmodp cyclic pgroup sylow vector falgebra. From mathcomp Require Import fieldext separable galois. (******************************************************************************) (* The main result in this file is the existence theorem that underpins the *) (* construction of the algebraic numbers in file algC.v. This theorem simply *) (* asserts the existence of an algebraically closed field with an *) (* automorphism of order 2, and dubbed the Fundamental_Theorem_of_Algebraics *) (* because it is essentially the Fundamental Theorem of Algebra for algebraic *) (* numbers (the more familiar version for complex numbers can be derived by *) (* continuity). *) (* Although our proof does indeed construct exactly the algebraics, we *) (* choose not to expose this in the statement of our Theorem. In algC.v we *) (* construct the norm and partial order of the "complex field" introduced by *) (* the Theorem; as these imply is has characteristic 0, we then get the *) (* algebraics as a subfield. To avoid some duplication a few basic properties *) (* of the algebraics, such as the existence of minimal polynomials, that are *) (* required by the proof of the Theorem, are also proved here. *) (* The main theorem of closed_field supplies us directly with an algebraic *) (* closure of the rationals (as the rationals are a countable field), so all *) (* we really need to construct is a conjugation automorphism that exchanges *) (* the two roots (i and -i) of X^2 + 1, and fixes a (real) subfield of *) (* index 2. This does not require actually constructing this field: the *) (* kHomExtend construction from galois.v supplies us with an automorphism *) (* conj_n of the number field Q[z_n] = Q[x_n, i] for any x_n such that Q[x_n] *) (* does not contain i (e.g., such that Q[x_n] is real). As conj_n will extend *) (* conj_m when Q[x_n] contains x_m, it therefore suffices to construct a *) (* sequence x_n such that *) (* (1) For each n, Q[x_n] is a REAL field containing Q[x_m] for all m <= n. *) (* (2) Each z in C belongs to Q[z_n] = Q[x_n, i] for large enough n. *) (* This, of course, amounts to proving the Fundamental Theorem of Algebra. *) (* Indeed, we use a constructive variant of Artin's algebraic proof of that *) (* Theorem to replace (2) by *) (* (3) Each monic polynomial over Q[x_m] whose constant term is -c^2 for some *) (* c in Q[x_m] has a root in Q[x_n] for large enough n. *) (* We then ensure (3) by setting Q[x_n+1] = Q[x_n, y] where y is the root of *) (* of such a polynomial p found by dichotomy in some interval [0, b] with b *) (* suitably large (such that p[b] >= 0), and p is obtained by decoding n into *) (* a triple (m, p, c) that satisfies the conditions of (3) (taking x_n+1=x_n *) (* if this is not the case), thereby ensuring that all such triples are *) (* ultimately considered. *) (* In more detail, the 600-line proof consists in six (uneven) parts: *) (* (A) - Construction of number fields (~ 100 lines): in order to make use of *) (* the theory developped in falgebra, fieldext, separable and galois we *) (* construct a separate fielExtType Q z for the number field Q[z], with *) (* z in C, the closure of rat supplied by countable_algebraic_closure. *) (* The morphism (ofQ z) maps Q z to C, and the Primitive Element Theorem *) (* lets us define a predicate sQ z characterizing the image of (ofQ z), *) (* as well as a partial inverse (inQ z) to (ofQ z). *) (* (B) - Construction of the real extension Q[x, y] (~ 230 lines): here y has *) (* to be a root of a polynomial p over Q[x] satisfying the conditions of *) (* (3), and Q[x] should be real and archimedean, which we represent by *) (* a morphism from Q x to some archimedean field R, as the ssrnum and *) (* fieldext structures are not compatible. The construction starts by *) (* weakening the condition p[0] = -c^2 to p[0] <= 0 (in R), then reducing *) (* to the case where p is the minimal polynomial over Q[x] of some y (in *) (* some Q[w] that contains x and all roots of p). Then we only need to *) (* construct a realFieldType structure for Q[t] = Q[x,y] (we don't even *) (* need to show it is consistent with that of R). This amounts to fixing *) (* the sign of all z != 0 in Q[t], consistently with arithmetic in Q[t]. *) (* Now any such z is equal to q[y] for some q in Q[x][X] coprime with p. *) (* Then up + vq = 1 for Bezout coefficients u and v. As p is monic, there *) (* is some b0 >= 0 in R such that p changes sign in ab0 = [0; b0]. As R *) (* is archimedean, some iteration of the binary search for a root of p in *) (* ab0 will yield an interval ab_n such that |up[d]| < 1/2 for d in ab_n. *) (* Then |q[d]| > 1/2M > 0 for any upper bound M on |v[X]| in ab0, so q *) (* cannot change sign in ab_n (as then root-finding in ab_n would yield a *) (* d with |Mq[d]| < 1/2), so we can fix the sign of z to that of q in *) (* ab_n. *) (* (C) - Construction of the x_n and z_n (~50 lines): x_ n is obtained by *) (* iterating (B), starting with x_0 = 0, and then (A) and the PET yield *) (* z_ n. We establish (1) and (3), and that the minimal polynomial of the *) (* preimage i_ n of i over the preimage R_ n of Q[x_n] is X^2 + 1. *) (* (D) - Establish (2), i.e., prove the FTA (~180 lines). We must depart from *) (* Artin's proof because deciding membership in the union of the Q[x_n] *) (* requires the FTA, i.e., we cannot (yet) construct a maximal real *) (* subfield of C. We work around this issue by first reducing to the case *) (* where Q[z] is Galois over Q and contains i, then using induction over *) (* the degree of z over Q[z_ n] (i.e., the degree of a monic polynomial *) (* over Q[z_n] that has z as a root). We can assume that z is not in *) (* Q[z_n]; then it suffices to find some y in Q[z_n, z] \ Q[z_n] that is *) (* also in Q[z_m] for some m > n, as then we can apply induction with the *) (* minimal polynomial of z over Q[z_n, y]. In any Galois extension Q[t] *) (* of Q that contains both z and z_n, Q[x_n, z] = Q[z_n, z] is Galois *) (* over both Q[x_n] and Q[z_n]. If Gal(Q[x_n,z] / Q[x_n]) isn't a 2-group *) (* take one of its Sylow 2-groups P; the minimal polynomial p of any *) (* generator of the fixed field F of P over Q[x_n] has odd degree, hence *) (* by (3) - p[X]p[-X] and thus p has a root y in some Q[x_m], hence in *) (* Q[z_m]. As F is normal, y is in F, with minimal polynomial p, and y *) (* is not in Q[z_n] = Q[x_n, i] since p has odd degree. Otherwise, *) (* Gal(Q[z_n,z] / Q[z_n]) is a proper 2-group, and has a maximal subgroup *) (* P of index 2. The fixed field F of P has a generator w over Q[z_n] *) (* with w^2 in Q[z_n] \ Q[x_n], i.e. w^2 = u + 2iv with v != 0. From (3) *) (* X^4 - uX^2 - v^2 has a root x in some Q[x_m]; then x != 0 as v != 0, *) (* hence w^2 = y^2 for y = x + iv/x in Q[z_m], and y generates F. *) (* (E) - Construct conj and conclude (~40 lines): conj z is defined as *) (* conj_ n z with the n provided by (2); since each conj_ m is a morphism *) (* of order 2 and conj z = conj_ m z for any m >= n, it follows that conj *) (* is also a morphism of order 2. *) (* Note that (C), (D) and (E) only depend on Q[x_n] not containing i; the *) (* order structure is not used (hence we need not prove that the ordering of *) (* Q[x_m] is consistent with that of Q[x_n] for m >= n). *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import Order.TTheory GroupScope GRing.Theory Num.Theory. Local Open Scope ring_scope. Local Notation "p ^ f" := (map_poly f p) : ring_scope. Local Notation "p ^@" := (p ^ in_alg _) (format "p ^@"): ring_scope. Local Notation "<< E ; u >>" := <<E; u>>%VS. Local Notation Qmorphism C := {rmorphism rat -> C}. Lemma rat_algebraic_archimedean (C : numFieldType) (QtoC : Qmorphism C) : integralRange QtoC -> Num.archimedean_axiom C. Proof. move=> algC x. without loss x_ge0: x / 0 <= x by rewrite -normr_id; apply. have [-> | nz_x] := eqVneq x 0; first by exists 1; rewrite normr0. have [p mon_p px0] := algC x; exists (\sum_(j < size p) `|numq p`_j|)%N. rewrite ger0_norm // real_ltNge ?rpred_nat ?ger0_real //. apply: contraL px0 => lb_x; rewrite rootE gt_eqF // horner_coef size_map_poly. have x_gt0 k: 0 < x ^+ k by rewrite exprn_gt0 // lt_def nz_x. move: lb_x; rewrite polySpred ?monic_neq0 // !big_ord_recr coef_map /=. rewrite -lead_coefE (monicP mon_p) natrD [QtoC _]rmorph1 mul1r => lb_x. case: _.-1 (lb_x) => [|n]; first by rewrite !big_ord0 !add0r ltr01. rewrite -ltrBlDl add0r -(ler_pM2r (x_gt0 n)) -exprS. apply: lt_le_trans; rewrite mulrDl mul1r ltr_pwDr // -sumrN. rewrite natr_sum mulr_suml ler_sum // => j _. rewrite coef_map /= fmorph_eq_rat (le_trans (real_ler_norm _)) //. by rewrite rpredN rpredM ?rpred_rat ?rpredX // ger0_real. rewrite normrN normrM ler_pM //. rewrite normf_div -!intr_norm -!abszE ler_piMr ?ler0n //. by rewrite invf_le1 ?ler1n ?ltr0n absz_gt0. rewrite normrX ger0_norm ?(ltrW x_gt0) // ler_weXn2l ?leq_ord //. by rewrite (le_trans _ lb_x) // natr1 ler1n. Qed. Definition decidable_embedding sT T (f : sT -> T) := forall y, decidable (exists x, y = f x). Lemma rat_algebraic_decidable (C : fieldType) (QtoC : Qmorphism C) : integralRange QtoC -> decidable_embedding QtoC. Proof. have QtoCinj: injective QtoC by apply: fmorph_inj. pose ZtoQ : int -> rat := intr; pose ZtoC : int -> C := intr. have ZtoQinj: injective ZtoQ by apply: intr_inj. have defZtoC: ZtoC =1 QtoC \o ZtoQ by move=> m; rewrite /= rmorph_int. move=> algC x; have /sig2_eqW[q mon_q qx0] := algC x; pose d := (size q).-1. have [n ub_n]: {n | forall y, root q y -> `|y| < n}. have [n1 ub_n1] := monic_Cauchy_bound mon_q. have /monic_Cauchy_bound[n2 ub_n2]: (-1) ^+ d *: (q \Po - 'X) \is monic. rewrite monicE lead_coefZ lead_coef_comp ?size_polyN ?size_polyX // -/d. by rewrite lead_coefN lead_coefX (monicP mon_q) (mulrC 1) signrMK. exists (Num.max n1 n2) => y; rewrite ltNge ler_normr !leUx rootE. apply: contraL => /orP[]/andP[] => [/ub_n1/gt_eqF->// | _ /ub_n2/gt_eqF]. by rewrite hornerZ horner_comp !hornerE opprK mulf_eq0 signr_eq0 => /= ->. have [p [a nz_a Dq]] := rat_poly_scale q; pose N := Num.bound `|n * a%:~R|. pose xa : seq rat := [seq (m%:R - N%:R) / a%:~R | m <- iota 0 N.*2]. have [/sig2_eqW[y _ ->] | xa'x] := @mapP _ _ QtoC xa x; first by left; exists y. right=> [[y Dx]]; case: xa'x; exists y => //. have{x Dx qx0} qy0: root q y by rewrite Dx fmorph_root in qx0. have /dvdzP[b Da]: (denq y %| a)%Z. have /Gauss_dvdzl <-: coprimez (denq y) (numq y ^+ d). by rewrite coprimez_sym coprimezXl //; apply: coprime_num_den. pose p1 : {poly int} := a *: 'X^d - p. have Dp1: p1 ^ intr = a%:~R *: ('X^d - q). by rewrite rmorphB /= linearZ /= map_polyXn scalerBr Dq scalerKV ?intr_eq0. apply/dvdzP; exists (\sum_(i < d) p1`_i * numq y ^+ i * denq y ^+ (d - i.+1)). apply: ZtoQinj; rewrite /ZtoQ rmorphM mulr_suml rmorph_sum /=. transitivity ((p1 ^ intr).[y] * (denq y ^+ d)%:~R). rewrite Dp1 !hornerE (rootP qy0) subr0. by rewrite !rmorphXn /= numqE exprMn mulrA. have sz_p1: (size (p1 ^ ZtoQ)%R <= d)%N. rewrite Dp1 size_scale ?intr_eq0 //; apply/leq_sizeP=> i. rewrite leq_eqVlt eq_sym -polySpred ?monic_neq0 // coefB coefXn. case: eqP => [-> _ | _ /(nth_default 0)->//]. by rewrite -lead_coefE (monicP mon_q). rewrite (horner_coef_wide _ sz_p1) mulr_suml; apply: eq_bigr => i _. rewrite -!mulrA -exprSr coef_map !rmorphM !rmorphXn /= numqE exprMn -mulrA. by rewrite -exprD -addSnnS subnKC. pose m := `|(numq y * b + N)%R|%N. have Dm: m%:R = `|y * a%:~R + N%:R|. by rewrite pmulrn abszE intr_norm Da rmorphD !rmorphM /= numqE mulrAC mulrA. have ltr_Qnat n1 n2 : (n1%:R < n2%:R :> rat = _) := ltr_nat _ n1 n2. have ub_y: `|y * a%:~R| < N%:R. apply: le_lt_trans (archi_boundP (normr_ge0 _)); rewrite !normrM. by rewrite ler_pM // (le_trans _ (ler_norm n)) ?ltW ?ub_n. apply/mapP; exists m. rewrite mem_iota /= add0n -addnn -ltr_Qnat Dm natrD. by rewrite (le_lt_trans (ler_normD _ _)) // normr_nat ltrD2. rewrite Dm ger0_norm ?addrK ?mulfK ?intr_eq0 // -lerBlDl sub0r. by rewrite (le_trans (ler_norm _)) ?normrN ?ltW. Qed. Lemma minPoly_decidable_closure (F : fieldType) (L : closedFieldType) (FtoL : {rmorphism F -> L}) x : decidable_embedding FtoL -> integralOver FtoL x -> {p | [/\ p \is monic, root (p ^ FtoL) x & irreducible_poly p]}. Proof. move=> isF /sig2W[p /monicP mon_p px0]. have [r Dp] := closed_field_poly_normal (p ^ FtoL); pose n := size r. rewrite lead_coef_map {}mon_p rmorph1 scale1r in Dp. pose Fpx q := (q \is a polyOver isF) && root q x. have FpxF q: Fpx (q ^ FtoL) = root (q ^ FtoL) x. by rewrite /Fpx polyOver_poly // => j _; apply/sumboolP; exists q`_j. pose p_ (I : {set 'I_n}) := \prod_(i <- enum I) ('X - (r`_i)%:P). have{px0 Dp} /ex_minset[I /minsetP[/andP[FpI pIx0] minI]]: exists I, Fpx (p_ I). exists setT; suffices ->: p_ setT = p ^ FtoL by rewrite FpxF. by rewrite Dp (big_nth 0) big_mkord /p_ big_enum; apply/eq_bigl => i /[1!inE]. have{p} [p DpI]: {p | p_ I = p ^ FtoL}. exists (p_ I ^ (fun y => if isF y is left Fy then sval (sig_eqW Fy) else 0)). rewrite -map_poly_comp map_poly_id // => y /(allP FpI) /=. by rewrite unfold_in; case: (isF y) => // Fy _; case: (sig_eqW _). have mon_pI: p_ I \is monic by apply: monic_prod_XsubC. have mon_p: p \is monic by rewrite -(map_monic FtoL) -DpI. exists p; rewrite -DpI; split=> //; split=> [|q nCq q_dv_p]. by rewrite -(size_map_poly FtoL) -DpI (root_size_gt1 _ pIx0) ?monic_neq0. rewrite -dvdp_size_eqp //; apply/eqP. without loss mon_q: q nCq q_dv_p / q \is monic. move=> IHq; pose a := lead_coef q; pose q1 := a^-1 *: q. have nz_a: a != 0 by rewrite lead_coef_eq0 (dvdpN0 q_dv_p) ?monic_neq0. have /IHq IHq1: q1 \is monic by rewrite monicE lead_coefZ mulVf. by rewrite -IHq1 ?size_scale ?dvdpZl ?invr_eq0. without loss{nCq} qx0: q mon_q q_dv_p / root (q ^ FtoL) x. have /dvdpP[q1 Dp] := q_dv_p; rewrite DpI Dp rmorphM rootM -implyNb in pIx0. have mon_q1: q1 \is monic by rewrite Dp monicMr in mon_p. move=> IH; apply: (IH) (implyP pIx0 _) => //; apply: contra nCq => /IH IHq1. rewrite natr1E -(subnn (size q1)) {1}IHq1 ?Dp ?dvdp_mulr //. rewrite polySpred ?monic_neq0 //. by rewrite eqSS size_monicM ?monic_neq0 // -!subn1 subnAC addKn. have /dvdp_prod_XsubC[m Dq]: q ^ FtoL %| p_ I by rewrite DpI dvdp_map. pose B := [set j in mask m (enum I)]; have{} Dq: q ^ FtoL = p_ B. apply/eqP; rewrite -eqp_monic ?monic_map ?monic_prod_XsubC //. congr (_ %= _): Dq; apply: perm_big => //. by rewrite uniq_perm ?mask_uniq ?enum_uniq // => j; rewrite mem_enum inE. rewrite -!(size_map_poly FtoL) Dq -DpI (minI B) // -?Dq ?FpxF //. by apply/subsetP=> j /[1!inE] /mem_mask; rewrite mem_enum. Qed. Lemma alg_integral (F : fieldType) (L : fieldExtType F) : integralRange (in_alg L). Proof. move=> x; have [/polyOver1P[p Dp]] := (minPolyOver 1 x, monic_minPoly 1 x). by rewrite Dp map_monic; exists p; rewrite // -Dp root_minPoly. Qed. Prenex Implicits alg_integral. Arguments map_poly_inj {F R} f [p1 p2]. Theorem Fundamental_Theorem_of_Algebraics : {L : closedFieldType & {conj : {rmorphism L -> L} | involutive conj & ~ conj =1 id}}. Proof. have maxn3 n1 n2 n3: {m | [/\ n1 <= m, n2 <= m & n3 <= m]%N}. by exists (maxn n1 (maxn n2 n3)); apply/and3P; rewrite -!geq_max. have [C [/= QtoC algC]] := countable_algebraic_closure rat. exists C; have [i Di2] := GRing.imaginary_exists C. pose Qfield := fieldExtType rat. pose Cmorph (L : Qfield) := {rmorphism L -> C}. have pcharQ (L : Qfield): [pchar L] =i pred0 := ftrans (pchar_lalg L) (pchar_num _). have sepQ (L : Qfield) (K E : {subfield L}): separable K E. by apply/separableP=> u _; apply: pcharf0_separable. pose genQfield z L := {LtoC : Cmorph L & {u | LtoC u = z & <<1; u>> = fullv}}. have /all_tag[Q /all_tag[ofQ genQz]] z: {Qz : Qfield & genQfield z Qz}. have [|p [/monic_neq0 nzp pz0 irr_p]] := minPoly_decidable_closure _ (algC z). exact: rat_algebraic_decidable. pose Qz := SubFieldExtType pz0 irr_p. pose QzC : {rmorphism _ -> _} := @subfx_inj _ _ QtoC z p. exists Qz, QzC, (subfx_root QtoC z p); first exact: subfx_inj_root. apply/vspaceP=> u; rewrite memvf; apply/Fadjoin1_polyP. by have [q] := subfxEroot pz0 nzp u; exists q. have pQof z p: p^@ ^ ofQ z = p ^ QtoC. by rewrite -map_poly_comp; apply: eq_map_poly => x; rewrite !fmorph_eq_rat. have pQof2 z p u: ofQ z p^@.[u] = (p ^ QtoC).[ofQ z u]. by rewrite -horner_map pQof. have PET_Qz z (E : {subfield Q z}): {u | <<1; u>> = E}. exists (separable_generator 1 E). by rewrite -eq_adjoin_separable_generator ?sub1v. pose gen z x := exists q, x = (q ^ QtoC).[z]. have PET2 x y: {z | gen z x & gen z y}. pose Gxy := (x, y) = let: (p, q, z) := _ in ((p ^ QtoC).[z], (q ^ QtoC).[z]). suffices [[[p q] z] []]: {w | Gxy w} by exists z; [exists p | exists q]. apply/sig_eqW; have /integral_algebraic[px nz_px pxx0] := algC x. have /integral_algebraic[py nz_py pyy0] := algC y. have [n [[p Dx] [q Dy]]] := pchar0_PET nz_px pxx0 nz_py pyy0 (pchar_num _). by exists (p, q, y *+ n - x); congr (_, _). have gen_inQ z x: gen z x -> {u | ofQ z u = x}. have [u Dz _] := genQz z => /sig_eqW[q ->]. by exists q^@.[u]; rewrite pQof2 Dz. have gen_ofP z u v: reflect (gen (ofQ z u) (ofQ z v)) (v \in <<1; u>>). apply: (iffP Fadjoin1_polyP) => [[q ->]|]; first by rewrite pQof2; exists q. by case=> q; rewrite -pQof2 => /fmorph_inj->; exists q. have /all_tag[sQ genP] z: {s : pred C & forall x, reflect (gen z x) (x \in s)}. apply: all_tag (fun x => reflect (gen z x)) _ => x. have [w /gen_inQ[u <-] /gen_inQ[v <-]] := PET2 z x. by exists (v \in <<1; u>>)%VS; apply: gen_ofP. have sQtrans: transitive (fun x z => x \in sQ z). move=> x y z /genP[p ->] /genP[q ->]; apply/genP; exists (p \Po q). by rewrite map_comp_poly horner_comp. have sQid z: z \in sQ z by apply/genP; exists 'X; rewrite map_polyX hornerX. have{gen_ofP} sQof2 z u v: (ofQ z u \in sQ (ofQ z v)) = (u \in <<1; v>>%VS). exact/genP/(gen_ofP z). have sQof z v: ofQ z v \in sQ z. by have [u Dz defQz] := genQz z; rewrite -[in sQ z]Dz sQof2 defQz memvf. have{gen_inQ} sQ_inQ z x z_x := gen_inQ z x (genP z x z_x). have /all_sig[inQ inQ_K] z: {inQ | {in sQ z, cancel inQ (ofQ z)}}. by apply: all_sig_cond (fun x u => ofQ z u = x) 0 _ => x /sQ_inQ. have ofQ_K z: cancel (ofQ z) (inQ z). by move=> x; have /inQ_K/fmorph_inj := sQof z x. have sQring z: divring_closed (sQ z). have sQ_1: 1 \in sQ z by rewrite -(rmorph1 (ofQ z)) sQof. by split=> // x y /inQ_K<- /inQ_K<- /=; rewrite -(rmorphB, fmorph_div) sQof. pose sQzM z := GRing.isZmodClosed.Build _ _ (sQring z : zmod_closed _). pose sQmM z := GRing.isMulClosed.Build _ _ (sQring z). pose sQiM z := GRing.isInvClosed.Build _ _ (sQring z). pose sQC z : divringClosed _ := HB.pack (sQ z) (sQzM z) (sQmM z) (sQiM z). pose morph_ofQ x z Qxz := forall u, ofQ z (Qxz u) = ofQ x u. have QtoQ z x: x \in sQ z -> {Qxz : 'AHom(Q x, Q z) | morph_ofQ x z Qxz}. move=> z_x; pose Qxz u := inQ z (ofQ x u). have QxzE u: ofQ z (Qxz u) = ofQ x u by apply/inQ_K/(sQtrans x). have Qxza : zmod_morphism Qxz. by move=> u v; apply: (canLR (ofQ_K z)); rewrite !rmorphB !QxzE. have Qxzm : monoid_morphism Qxz. by split=> [|u v]; apply: (canLR (ofQ_K z)); rewrite ?rmorph1 ?rmorphM /= ?QxzE. have QxzaM := GRing.isZmodMorphism.Build _ _ _ Qxza. have QxzmM := GRing.isMonoidMorphism.Build _ _ _ Qxzm. have QxzlM := GRing.isScalable.Build _ _ _ _ _ (rat_linear Qxza). pose QxzLRM : {lrmorphism _ -> _} := HB.pack Qxz QxzaM QxzmM QxzlM. by exists (linfun_ahom QxzLRM) => u; rewrite lfunE QxzE. pose sQs z s := all (mem (sQ z)) s. have inQsK z s: sQs z s -> map (ofQ z) (map (inQ z) s) = s. by rewrite -map_comp => /allP/(_ _ _)/inQ_K; apply: map_id_in. have inQpK z p: p \is a polyOver (sQ z) -> (p ^ inQ z) ^ ofQ z = p. by move=> /allP/(_ _ _)/inQ_K/=/map_poly_id; rewrite -map_poly_comp. have{gen PET2 genP} PET s: {z | sQs z s & <<1 & map (inQ z) s>>%VS = fullv}. have [y /inQsK Ds]: {y | sQs y s}. elim: s => [|x s /= [y IHs]]; first by exists 0. have [z /genP z_x /genP z_y] := PET2 x y. by exists z; rewrite /= {x}z_x; apply: sub_all IHs => x /sQtrans/= ->. have [w defQs] := PET_Qz _ <<1 & map (inQ y) s>>%AS; pose z := ofQ y w. have z_s: sQs z s. rewrite -Ds /sQs all_map; apply/allP=> u s_u /=. by rewrite sQof2 defQs seqv_sub_adjoin. have [[u Dz defQz] [Qzy QzyE]] := (genQz z, QtoQ y z (sQof y w)). exists z => //; apply/eqP; rewrite eqEsubv subvf /= -defQz. rewrite -(limg_ker0 _ _ (AHom_lker0 Qzy)) aimg_adjoin_seq aimg_adjoin aimg1. rewrite -[map _ _](mapK (ofQ_K y)) -(map_comp (ofQ y)) (eq_map QzyE) inQsK //. by rewrite -defQs -(canLR (ofQ_K y) Dz) -QzyE ofQ_K. pose rp s := \prod_(z <- s) ('X - z%:P). have map_rp (f : {rmorphism _ -> _}) s: rp _ s ^ f = rp _ (map f s). rewrite rmorph_prod /rp big_map; apply: eq_bigr => x _ /=. by rewrite rmorphB /= map_polyX map_polyC. pose is_Gal z := SplittingField.axiom (Q z). have galQ x: {z | x \in sQ z & is_Gal z}. have /sig2W[p mon_p pz0] := algC x. have [s Dp] := closed_field_poly_normal (p ^ QtoC). rewrite (monicP _) ?monic_map // scale1r in Dp; have [z z_s defQz] := PET s. exists z; first by apply/(allP z_s); rewrite -root_prod_XsubC -Dp. exists p^@; first exact: alg_polyOver. exists (map (inQ z) s); last by apply/vspaceP=> u; rewrite defQz memvf. by rewrite -(eqp_map (ofQ z)) pQof Dp map_rp inQsK ?eqpxx. pose is_realC x := {R : archiRealFieldType & {rmorphism Q x -> R}}. pose realC := {x : C & is_realC x}. pose has_Rroot (xR : realC) p c (Rx := sQ (tag xR)) := [&& p \is a polyOver Rx, p \is monic, c \in Rx & p.[0] == - c ^+ 2]. pose root_in (xR : realC) p := exists2 w, w \in sQ (tag xR) & root p w. pose extendsR (xR yR : realC) := tag xR \in sQ (tag yR). have add_Rroot xR p c: {yR | extendsR xR yR & has_Rroot xR p c -> root_in yR p}. rewrite {}/extendsR; case: (has_Rroot xR p c) / and4P; last by exists xR. case: xR => x [R QxR] /= [/inQpK <-]; move: (p ^ _) => {}p mon_p /inQ_K<- Dc. have{c Dc} p0_le0: (p ^ QxR).[0] <= 0. rewrite horner_coef0 coef_map -[p`_0]ofQ_K -coef_map -horner_coef0 (eqP Dc). by rewrite -rmorphXn -rmorphN ofQ_K /= rmorphN rmorphXn oppr_le0 sqr_ge0. have [s Dp] := closed_field_poly_normal (p ^ ofQ x). have{Dp} /all_and2[s_p p_s] y: root (p ^ ofQ x) y <-> (y \in s). by rewrite Dp (monicP mon_p) scale1r root_prod_XsubC. rewrite map_monic in mon_p; have [z /andP[z_x /allP/=z_s] _] := PET (x :: s). have{z_x} [[Qxz QxzE] Dx] := (QtoQ z x z_x, inQ_K z x z_x). pose Qx := <<1; inQ z x>>%AS. have pQwx q1: q1 \is a polyOver Qx -> {q | q1 = q ^ Qxz}. move/polyOverP=> Qx_q1; exists ((q1 ^ ofQ z) ^ inQ x). apply: (map_poly_inj (ofQ z)); rewrite -map_poly_comp (eq_map_poly QxzE). by rewrite inQpK ?polyOver_poly // => j _; rewrite -Dx sQof2 Qx_q1. have /all_sig[t_ Dt] u: {t | <<1; t>> = <<Qx; u>>} by apply: PET_Qz. suffices{p_s}[u Ry px0]: {u : Q z & is_realC (ofQ z (t_ u)) & ofQ z u \in s}. exists (Tagged is_realC Ry) => [|_] /=. by rewrite -Dx sQof2 Dt subvP_adjoin ?memv_adjoin. by exists (ofQ z u); rewrite ?p_s // sQof2 Dt memv_adjoin. without loss{z_s s_p} [u Dp s_y]: p mon_p p0_le0 / {u | minPoly Qx u = p ^ Qxz & ofQ z u \in s}. - move=> IHp; move: {2}_.+1 (ltnSn (size p)) => d. elim: d => // d IHd in p mon_p s_p p0_le0 *; rewrite ltnS => le_p_d. have /closed_rootP/sig_eqW[y py0]: size (p ^ ofQ x) != 1. rewrite size_map_poly size_poly_eq1 eqp_monic ?rpred1 //. by apply: contraTneq p0_le0 => ->; rewrite rmorph1 hornerC lt_geF ?ltr01. have /s_p s_y := py0; have /z_s/sQ_inQ[u Dy] := s_y. have /pQwx[q Dq] := minPolyOver Qx u. have mon_q: q \is monic by have:= monic_minPoly Qx u; rewrite Dq map_monic. have /dvdpP/sig_eqW[r Dp]: q %| p. rewrite -(dvdp_map Qxz) -Dq minPoly_dvdp //. by apply: polyOver_poly => j _; rewrite -sQof2 QxzE Dx. by rewrite -(fmorph_root (ofQ z)) Dy -map_poly_comp (eq_map_poly QxzE). have mon_r: r \is monic by rewrite Dp monicMr in mon_p. have [q0_le0 | q0_gt0] := lerP ((q ^ QxR).[0]) 0. by apply: (IHp q) => //; exists u; rewrite ?Dy. have r0_le0: (r ^ QxR).[0] <= 0. by rewrite -(ler_pM2r q0_gt0) mul0r -hornerM -rmorphM -Dp. apply: (IHd r mon_r) => // [w rw0|]. by rewrite s_p // Dp rmorphM rootM rw0. apply: leq_trans le_p_d; rewrite Dp size_Mmonic ?monic_neq0 // addnC. by rewrite -(size_map_poly Qxz q) -Dq size_minPoly !ltnS leq_addl. exists u => {s s_y}//; set y := ofQ z (t_ u); set p1 := minPoly Qx u in Dp. have /QtoQ[Qyz QyzE]: y \in sQ z := sQof z (t_ u). pose q1_ v := Fadjoin_poly Qx u (Qyz v). have{} QyzE v: Qyz v = (q1_ v).[u]. by rewrite Fadjoin_poly_eq // -Dt -sQof2 QyzE sQof. have /all_sig2[q_ coqp Dq] v: {q | v != 0 -> coprimep p q & q ^ Qxz = q1_ v}. have /pQwx[q Dq]: q1_ v \is a polyOver Qx by apply: Fadjoin_polyOver. exists q => // nz_v; rewrite -(coprimep_map Qxz) -Dp -Dq -gcdp_eqp1. have /minPoly_irr/orP[] // := dvdp_gcdl p1 (q1_ v). by rewrite gcdp_polyOver ?minPolyOver ?Fadjoin_polyOver. rewrite -/p1 {1}/eqp dvdp_gcd => /and3P[_ _ /dvdp_leq/=/implyP]. rewrite size_minPoly ltnNge size_poly (contraNneq _ nz_v) // => q1v0. by rewrite -(fmorph_eq0 Qyz) /= QyzE q1v0 horner0. pose h2 : R := 2^-1; have nz2: 2 != 0 :> R by rewrite pnatr_eq0. pose itv ab := [pred c : R | ab.1 <= c <= ab.2]. pose wid ab : R := ab.2 - ab.1; pose mid ab := (ab.1 + ab.2) * h2. pose sub_itv ab cd := cd.1 <= ab.1 :> R /\ ab.2 <= cd.2 :> R. pose xup q ab := [/\ q.[ab.1] <= 0, q.[ab.2] >= 0 & ab.1 <= ab.2 :> R]. pose narrow q ab (c := mid ab) := if q.[c] >= 0 then (ab.1, c) else (c, ab.2). pose find k q := iter k (narrow q). have findP k q ab (cd := find k q ab): xup q ab -> [/\ xup q cd, sub_itv cd ab & wid cd = wid ab / (2 ^ k)%:R]. - rewrite {}/cd; case: ab => a b xq_ab. elim: k => /= [|k]; first by rewrite divr1. case: (find k q _) => c d [[/= qc_le0 qd_ge0 le_cd] [/= le_ac le_db] Dcd]. have [/= le_ce le_ed] := midf_le le_cd; set e := _ / _ in le_ce le_ed. rewrite expnSr natrM invfM mulrA -{}Dcd /narrow /= -[mid _]/e. have [qe_ge0 // | /ltW qe_le0] := lerP 0 q.[e]. do ?split=> //=; [exact: (le_trans le_ed) | apply: canRL (mulfK nz2) _]. by rewrite mulrBl divfK // mulr_natr opprD addrACA subrr add0r. do ?split=> //=; [exact: (le_trans le_ac) | apply: canRL (mulfK nz2) _]. by rewrite mulrBl divfK // mulr_natr opprD addrACA subrr addr0. have find_root r q ab: xup q ab -> {n | forall x, x \in itv (find n q ab) ->`|(r * q).[x]| < h2}. - move=> xab; have ub_ab := poly_itv_bound _ ab.1 ab.2. have [Mu MuP] := ub_ab r; have /all_sig[Mq MqP] j := ub_ab q^`N(j). pose d := wid ab; pose dq := \poly_(i < (size q).-1) Mq i.+1. have d_ge0: 0 <= d by rewrite subr_ge0; case: xab. have [Mdq MdqP] := poly_disk_bound dq d. pose n := Num.bound (Mu * Mdq * d); exists n => c /andP[]. have{xab} [[]] := findP n _ _ xab; case: (find n q ab) => a1 b1 /=. rewrite -/d => qa1_le0 qb1_ge0 le_ab1 [/= le_aa1 le_b1b] Dab1 le_a1c le_cb1. have /MuP lbMu: c \in itv ab. by rewrite inE (le_trans le_aa1) ?(le_trans le_cb1). have Mu_ge0: 0 <= Mu by rewrite (le_trans _ lbMu). have Mdq_ge0: 0 <= Mdq. by rewrite (le_trans _ (MdqP 0 _)) ?normr0. suffices lb1 a2 b2 (ab1 := (a1, b1)) (ab2 := (a2, b2)) : xup q ab2 /\ sub_itv ab2 ab1 -> q.[b2] - q.[a2] <= Mdq * wid ab1. + apply: le_lt_trans (_ : Mu * Mdq * wid (a1, b1) < h2); last first. rewrite {}Dab1 mulrA ltr_pdivrMr ?ltr0n ?expn_gt0 //. rewrite (lt_le_trans (archi_boundP _)) ?mulr_ge0 ?ltr_nat // -/n. rewrite ler_pdivlMl ?ltr0n // -natrM ler_nat. by case: n => // n; rewrite expnS leq_pmul2l // ltn_expl. rewrite -mulrA hornerM normrM ler_pM //. have [/ltW qc_le0 | qc_ge0] := ltrP q.[c] 0. by apply: le_trans (lb1 c b1 _); rewrite ?ler0_norm ?ler_wpDl. by apply: le_trans (lb1 a1 c _); rewrite ?ger0_norm ?ler_wpDr ?oppr_ge0. case{c le_a1c le_cb1 lbMu}=> [[/=qa2_le0 qb2_ge0 le_ab2] [/=le_a12 le_b21]]. pose h := b2 - a2; have h_ge0: 0 <= h by rewrite subr_ge0. have [-> | nz_q] := eqVneq q 0. by rewrite !horner0 subrr mulr_ge0 ?subr_ge0. rewrite -(subrK a2 b2) (addrC h) (nderiv_taylor q (mulrC a2 h)). rewrite (polySpred nz_q) big_ord_recl /= mulr1 nderivn0 addrC addKr. have [le_aa2 le_b2b] := (le_trans le_aa1 le_a12, le_trans le_b21 le_b1b). have /MqP MqPx1: a2 \in itv ab by rewrite inE le_aa2 (le_trans le_ab2). apply: le_trans (le_trans (ler_norm _) (ler_norm_sum _ _ _)) _. apply: le_trans (_ : `|dq.[h] * h| <= _); last first. by rewrite normrM ler_pM ?normr_ge0 ?MdqP // ?ger0_norm ?lerB ?h_ge0. rewrite horner_poly ger0_norm ?mulr_ge0 ?sumr_ge0 // => [|j _]; last first. by rewrite mulr_ge0 ?exprn_ge0 // (le_trans _ (MqPx1 _)). rewrite mulr_suml ler_sum // => j _; rewrite normrM -mulrA -exprSr. by rewrite ler_pM // normrX ger0_norm. have [ab0 xab0]: {ab | xup (p ^ QxR) ab}. have /monic_Cauchy_bound[b pb_gt0]: p ^ QxR \is monic by apply: monic_map. by exists (0, `|b|); rewrite /xup normr_ge0 p0_le0 ltW ?pb_gt0 ?ler_norm. pose ab_ n := find n (p ^ QxR) ab0; pose Iab_ n := itv (ab_ n). pose lim v a := (q_ v ^ QxR).[a]; pose nlim v n := lim v (ab_ n).2. have lim0 a: lim 0 a = 0. rewrite /lim; suffices /eqP ->: q_ 0 == 0 by rewrite rmorph0 horner0. by rewrite -(map_poly_eq0 Qxz) Dq /q1_ !raddf0. have limN v a: lim (- v) a = - lim v a. rewrite /lim; suffices ->: q_ (- v) = - q_ v by rewrite rmorphN hornerN. apply: (map_poly_inj Qxz). by rewrite Dq /q1_ (raddfN _ v) (raddfN _ (Qyz v)) [RHS]raddfN /= Dq. pose lim_nz n v := exists2 e, e > 0 & {in Iab_ n, forall a, e < `|lim v a| }. have /(all_sig_cond 0)[n_ nzP] v: v != 0 -> {n | lim_nz n v}. move=> nz_v; do [move/(_ v nz_v); rewrite -(coprimep_map QxR)] in coqp. have /sig_eqW[r r_pq_1] := Bezout_eq1_coprimepP _ _ coqp. have /(find_root r.1)[n ub_rp] := xab0; exists n. have [M Mgt0 ubM]: {M | 0 < M & {in Iab_ n, forall a, `|r.2.[a]| <= M}}. have [M ubM] := poly_itv_bound r.2 (ab_ n).1 (ab_ n).2. exists (Num.max 1 M) => [|s /ubM vM]; first by rewrite lt_max ltr01. by rewrite le_max orbC vM. exists (h2 / M) => [|a xn_a]; first by rewrite divr_gt0 ?invr_gt0 ?ltr0n. rewrite ltr_pdivrMr // -(ltrD2l h2) -mulr2n -mulr_natl divff //. rewrite -normr1 -(hornerC 1 a) -[1%:P]r_pq_1 hornerD. rewrite ?(le_lt_trans (ler_normD _ _)) ?ltr_leD ?ub_rp //. by rewrite mulrC hornerM normrM ler_wpM2l ?ubM. have ab_le m n: (m <= n)%N -> (ab_ n).2 \in Iab_ m. move/subnKC=> <-; move: {n}(n - m)%N => n; rewrite /ab_. have /(findP m)[/(findP n)[[_ _]]] := xab0. rewrite /find -iterD -!/(find _ _) -!/(ab_ _) addnC !inE. by move: (ab_ _) => /= ab_mn le_ab_mn [/le_trans->]. pose lt v w := 0 < nlim (w - v) (n_ (w - v)). have posN v: lt 0 (- v) = lt v 0 by rewrite /lt subr0 add0r. have posB v w: lt 0 (w - v) = lt v w by rewrite /lt subr0. have posE n v: (n_ v <= n)%N -> lt 0 v = (0 < nlim v n). rewrite /lt subr0 /nlim => /ab_le; set a := _.2; set b := _.2 => Iv_a. have [-> | /nzP[e e_gt0]] := eqVneq v 0; first by rewrite !lim0 ltxx. move: (n_ v) => m in Iv_a b * => v_gte. without loss lt0v: v v_gte / 0 < lim v b. move=> IHv; apply/idP/idP => [v_gt0 | /ltW]; first by rewrite -IHv. rewrite lt_def -normr_gt0 ?(lt_trans _ (v_gte _ _)) ?ab_le //=. rewrite !leNgt -!oppr_gt0 -!limN; apply: contra => v_lt0. by rewrite -IHv // => c /v_gte; rewrite limN normrN. rewrite lt0v (lt_trans e_gt0) ?(lt_le_trans (v_gte a Iv_a)) //. rewrite ger0_norm // leNgt; apply/negP=> /ltW lev0. have [le_a le_ab] : _ /\ a <= b := andP Iv_a. have xab: xup (q_ v ^ QxR) (a, b) by move/ltW in lt0v. have /(find_root (h2 / e)%:P)[n1] := xab; have /(findP n1)[[_ _]] := xab. case: (find _ _ _) => c d /= le_cd [/= le_ac le_db] _ /(_ c)/implyP. rewrite inE lexx le_cd hornerM hornerC normrM le_gtF //. rewrite ger0_norm ?divr_ge0 ?invr_ge0 ?ler0n ?(ltW e_gt0) // mulrAC. rewrite ler_pdivlMr // ler_wpM2l ?invr_ge0 ?ler0n // ltW // v_gte //=. by rewrite inE -/b (le_trans le_a) //= (le_trans le_cd). pose lim_pos m v := exists2 e, e > 0 & forall n, (m <= n)%N -> e < nlim v n. have posP v: reflect (exists m, lim_pos m v) (lt 0 v). apply: (iffP idP) => [v_gt0|[m [e e_gt0 v_gte]]]; last first. by rewrite (posE _ _ (leq_maxl _ m)) (lt_trans e_gt0) ?v_gte ?leq_maxr. have [|e e_gt0 v_gte] := nzP v. by apply: contraTneq v_gt0 => ->; rewrite /lt subr0 /nlim lim0 ltxx. exists (n_ v), e => // n le_vn; rewrite (posE n) // in v_gt0. by rewrite -(ger0_norm (ltW v_gt0)) v_gte ?ab_le. have posNneg v: lt 0 v -> ~~ lt v 0. case/posP=> m [d d_gt0 v_gtd]; rewrite -posN. apply: contraL d_gt0 => /posP[n [e e_gt0 nv_gte]]. rewrite lt_gtF // (lt_trans (v_gtd _ (leq_maxl m n))) // -oppr_gt0. by rewrite /nlim -limN (lt_trans e_gt0) ?nv_gte ?leq_maxr. have posVneg v: v != 0 -> lt 0 v || lt v 0. case/nzP=> e e_gt0 v_gte; rewrite -posN; set w := - v. have [m [le_vm le_wm _]] := maxn3 (n_ v) (n_ w) 0; rewrite !(posE m) //. by rewrite /nlim limN -ltr_normr (lt_trans e_gt0) ?v_gte ?ab_le. have posD v w: lt 0 v -> lt 0 w -> lt 0 (v + w). move=> /posP[m [d d_gt0 v_gtd]] /posP[n [e e_gt0 w_gte]]. apply/posP; exists (maxn m n), (d + e) => [|k]; first exact: addr_gt0. rewrite geq_max => /andP[le_mk le_nk]; rewrite /nlim /lim. have ->: q_ (v + w) = q_ v + q_ w. by apply: (map_poly_inj Qxz); rewrite rmorphD /= !{1}Dq /q1_ !raddfD. by rewrite rmorphD hornerD ltrD ?v_gtd ?w_gte. have posM v w: lt 0 v -> lt 0 w -> lt 0 (v * w). move=> /posP[m [d d_gt0 v_gtd]] /posP[n [e e_gt0 w_gte]]. have /dvdpP[r /(canRL (subrK _))Dqvw]: p %| q_ (v * w) - q_ v * q_ w. rewrite -(dvdp_map Qxz) rmorphB rmorphM /= !Dq -Dp minPoly_dvdp //. by rewrite rpredB 1?rpredM ?Fadjoin_polyOver. by rewrite rootE !hornerE -!QyzE rmorphM subrr. have /(find_root ((d * e)^-1 *: r ^ QxR))[N ub_rp] := xab0. pose f := d * e * h2; apply/posP; exists (maxn N (maxn m n)), f => [|k]. by rewrite !mulr_gt0 ?invr_gt0 ?ltr0n. rewrite !geq_max => /and3P[/ab_le/ub_rp{}ub_rp le_mk le_nk]. rewrite -(ltrD2r f) -mulr2n -mulr_natr divfK // /nlim /lim Dqvw. rewrite rmorphD hornerD /= -addrA -ltrBlDl ler_ltD //. by rewrite rmorphM hornerM ler_pM ?ltW ?v_gtd ?w_gte. rewrite -ltr_pdivrMl ?mulr_gt0 // (le_lt_trans _ ub_rp) //. by rewrite -scalerAl hornerZ -rmorphM mulrN -normrN ler_norm. pose le v w := (v == w) || lt v w. pose abs v := if le 0 v then v else - v. have absN v: abs (- v) = abs v. rewrite /abs /le !(eq_sym 0) oppr_eq0 opprK posN. have [-> | /posVneg/orP[v_gt0 | v_lt0]] := eqVneq; first by rewrite oppr0. by rewrite v_gt0 /= -if_neg posNneg. by rewrite v_lt0 /= -if_neg -(opprK v) posN posNneg ?posN. have absE v: le 0 v -> abs v = v by rewrite /abs => ->. pose RyM := Num.IntegralDomain_isLtReal.Build (Q y) posD posM posNneg posB posVneg absN absE (rrefl _). pose Ry : realFieldType := HB.pack (Q y) RyM. have QisArchi : Num.NumDomain_bounded_isArchimedean Ry. by constructor; apply: (@rat_algebraic_archimedean Ry _ alg_integral). exists (HB.pack_for archiRealFieldType _ QisArchi); apply: idfun. have some_realC: realC. suffices /all_sig[f QfK] x: {a | in_alg (Q 0) a = x}. have fA : zmod_morphism f. exact: can2_zmod_morphism (inj_can_sym QfK (fmorph_inj _)) QfK. have fM : monoid_morphism f. exact: can2_monoid_morphism (inj_can_sym QfK (fmorph_inj _)) QfK. pose faM := GRing.isZmodMorphism.Build _ _ _ fA. pose fmM := GRing.isMonoidMorphism.Build _ _ _ fM. pose fRM : {rmorphism _ -> _} := HB.pack f faM fmM. by exists 0, rat; exact: fRM. have /Fadjoin1_polyP/sig_eqW[q]: x \in <<1; 0>>%VS by rewrite -sQof2 rmorph0. by exists q.[0]; rewrite -horner_map rmorph0. pose fix xR n : realC := if n isn't n'.+1 then some_realC else if unpickle (nth 0 (CodeSeq.decode n') 1) isn't Some (p, c) then xR n' else tag (add_Rroot (xR n') p c). pose x_ n := tag (xR n). have sRle m n: (m <= n)%N -> {subset sQ (x_ m) <= sQ (x_ n)}. move/subnK <-; elim: {n}(n - m)%N => // n IHn x /IHn{IHn}Rx. rewrite addSn /x_ /=; case: (unpickle _) => [[p c]|] //=. by case: (add_Rroot _ _ _) => yR /= /(sQtrans _ x)->. have xRroot n p c: has_Rroot (xR n) p c -> {m | n <= m & root_in (xR m) p}%N. case/and4P=> Rp mon_p Rc Dc; pose m := CodeSeq.code [:: n; pickle (p, c)]. have le_n_m: (n <= m)%N by apply/ltnW/(allP (CodeSeq.ltn_code _))/mem_head. exists m.+1; rewrite ?leqW /x_ //= CodeSeq.codeK pickleK. case: (add_Rroot _ _ _) => yR /= _; apply; apply/and4P. by split=> //; first apply: polyOverS Rp; apply: (sRle n). have /all_sig[z_ /all_and3[Ri_R Ri_i defRi]] n (x := x_ n): {z | [/\ x \in sQ z, i \in sQ z & <<<<1; inQ z x>>; inQ z i>> = fullv]}. - have [z /and3P[z_x z_i _] Dzi] := PET [:: x; i]. by exists z; rewrite -adjoin_seq1 -adjoin_cons. pose i_ n := inQ (z_ n) i; pose R_ n := <<1; inQ (z_ n) (x_ n)>>%AS. have memRi n: <<R_ n; i_ n>> =i predT by move=> u; rewrite defRi memvf. have sCle m n: (m <= n)%N -> {subset sQ (z_ m) <= sQ (z_ n)}. move/sRle=> Rmn _ /sQ_inQ[u <-]. have /Fadjoin_polyP[p /polyOverP Rp ->] := memRi m u. rewrite -horner_map inQ_K ?(@rpred_horner _ (sQC _)) //=. apply/polyOver_poly=> j _. by apply: sQtrans (Ri_R n); rewrite Rmn // -(inQ_K _ _ (Ri_R m)) sQof2. have R'i n: i \notin sQ (x_ n). rewrite /x_; case: (xR n) => x [Rn QxR] /=. apply: contraL (@ltr01 Rn) => /sQ_inQ[v Di]. suffices /eqP <-: - QxR v ^+ 2 == 1 by rewrite oppr_gt0 -leNgt sqr_ge0. rewrite -rmorphXn -rmorphN fmorph_eq1 -(fmorph_eq1 (ofQ x)) rmorphN eqr_oppLR. by rewrite rmorphXn /= Di Di2. have szX2_1: size ('X^2 + 1) = 3%N. by move=> R; rewrite size_polyDl ?size_polyXn ?size_poly1. have minp_i n (p_i := minPoly (R_ n) (i_ n)): p_i = 'X^2 + 1. have p_dv_X2_1: p_i %| 'X^2 + 1. rewrite minPoly_dvdp ?rpredD ?rpredX ?rpred1 ?polyOverX //. rewrite -(fmorph_root (ofQ _)) inQ_K // rmorphD rmorph1 /= map_polyXn. by rewrite rootE hornerD hornerXn hornerC Di2 addNr. apply/eqP; rewrite -eqp_monic ?monic_minPoly //; last first. by rewrite monicE lead_coefE szX2_1 coefD coefXn coefC addr0. rewrite -dvdp_size_eqp // eqn_leq dvdp_leq -?size_poly_eq0 ?szX2_1 //= ltnNge. by rewrite size_minPoly ltnS leq_eqVlt orbF adjoin_deg_eq1 -sQof2 !inQ_K. have /all_sig[n_ FTA] z: {n | z \in sQ (z_ n)}. without loss [z_i gal_z]: z / i \in sQ z /\ is_Gal z. have [y /and3P[/sQtrans y_z /sQtrans y_i _] _] := PET [:: z; i]. have [t /sQtrans t_y gal_t] := galQ y. by case/(_ t)=> [|n]; last exists n; rewrite ?y_z ?y_i ?t_y. apply/sig_eqW; have n := 0%N. have [p]: exists p, [&& p \is monic, root p z & p \is a polyOver (sQ (z_ n))]. have [p mon_p pz0] := algC z; exists (p ^ QtoC). by rewrite map_monic mon_p pz0 -(pQof (z_ n)); apply/polyOver_poly. have [d lepd] := ubnP (size p); elim: d => // d IHd in p n lepd * => pz0. have [t [t_C t_z gal_t]]: exists t, [/\ z_ n \in sQ t, z \in sQ t & is_Gal t]. have [y /and3P[y_C y_z _]] := PET [:: z_ n; z]. by have [t /(sQtrans y)t_y] := galQ y; exists t; rewrite !t_y. pose QtMixin := FieldExt_isSplittingField.Build _ (Q t) gal_t. pose Qt : splittingFieldType rat := HB.pack (Q t) QtMixin. have /QtoQ[CnQt CnQtE] := t_C. pose Rn : {subfield Qt} := (CnQt @: R_ n)%AS; pose i_t : Qt := CnQt (i_ n). pose Cn : {subfield Qt} := <<Rn; i_t>>%AS. have defCn: Cn = limg CnQt :> {vspace Q t} by rewrite /= -aimg_adjoin defRi. have memRn u: (u \in Rn) = (ofQ t u \in sQ (x_ n)). by rewrite /= aimg_adjoin aimg1 -sQof2 CnQtE inQ_K. have memCn u: (u \in Cn) = (ofQ t u \in sQ (z_ n)). have [v Dv genCn] := genQz (z_ n). by rewrite -Dv -CnQtE sQof2 defCn -genCn aimg_adjoin aimg1. have Dit: ofQ t i_t = i by rewrite CnQtE inQ_K. have Dit2: i_t ^+ 2 = -1. by apply: (fmorph_inj (ofQ t)); rewrite rmorphXn rmorphN1 /= Dit. have dimCn: \dim_Rn Cn = 2%N. rewrite -adjoin_degreeE adjoin_degree_aimg. by apply: succn_inj; rewrite -size_minPoly minp_i szX2_1. have /sQ_inQ[u_z Dz] := t_z; pose Rz := <<Cn; u_z>>%AS. have{p lepd pz0} le_Rz_d: (\dim_Cn Rz < d)%N. rewrite -ltnS -adjoin_degreeE -size_minPoly (leq_trans _ lepd) // !ltnS. have{pz0} [mon_p pz0 Cp] := and3P pz0. have{Cp} Dp: ((p ^ inQ (z_ n)) ^ CnQt) ^ ofQ t = p. by rewrite -map_poly_comp (eq_map_poly CnQtE) inQpK. rewrite -Dp size_map_poly dvdp_leq ?monic_neq0 -?(map_monic (ofQ _)) ?Dp //. rewrite defCn minPoly_dvdp //; try by rewrite -(fmorph_root (ofQ t)) Dz Dp. by apply/polyOver_poly=> j _; rewrite memv_img ?memvf. have [sRCn sCnRz]: (Rn <= Cn)%VS /\ (Cn <= Rz)%VS by rewrite !subv_adjoin. have sRnRz := subv_trans sRCn sCnRz. have{gal_z} galRz: galois Rn Rz. apply/and3P; split; [by []|by apply: sepQ|]. apply/splitting_normalField=> //. pose QzMixin := FieldExt_isSplittingField.Build _ (Q z) gal_z. pose Qz : splittingFieldType _ := HB.pack (Q z) QzMixin. pose u : Qz := inQ z z. have /QtoQ[Qzt QztE] := t_z; exists (minPoly 1 u ^ Qzt). have /polyOver1P[q ->] := minPolyOver 1 u; apply/polyOver_poly=> j _. by rewrite coef_map linearZZ rmorph1 rpredZ ?rpred1. have [s /eqP Ds] := splitting_field_normal 1 u. rewrite Ds; exists (map Qzt s); first by rewrite map_rp eqpxx. apply/eqP; rewrite eqEsubv; apply/andP; split. apply/Fadjoin_seqP; split=> // _ /mapP[w s_w ->]. by rewrite (subvP (adjoinSl u_z (sub1v _))) // -sQof2 Dz QztE. rewrite /= adjoinC (Fadjoin_idP _) -/Rz; last first. by rewrite (subvP (adjoinSl _ (sub1v _))) // -sQof2 Dz Dit. rewrite /= -adjoin_seq1 adjoin_seqSr //; apply/allP=> /=; rewrite andbT. rewrite -(mem_map (fmorph_inj (ofQ _))) -map_comp (eq_map QztE); apply/mapP. by exists u; rewrite ?inQ_K // -root_prod_XsubC -Ds root_minPoly. have galCz: galois Cn Rz by rewrite (galoisS _ galRz) ?sRCn. have [Cz | C'z]:= boolP (u_z \in Cn); first by exists n; rewrite -Dz -memCn. pose G := 'Gal(Rz / Cn)%G; have{C'z} ntG: G :!=: 1%g. rewrite trivg_card1 -galois_dim 1?(galoisS _ galCz) ?subvv //=. by rewrite -adjoin_degreeE adjoin_deg_eq1. pose extRz m := exists2 w, ofQ t w \in sQ (z_ m) & w \in [predD Rz & Cn]. suffices [m le_n_m [w Cw /andP[C'w Rz_w]]]: exists2 m, (n <= m)%N & extRz m. pose p := minPoly <<Cn; w>> u_z; apply: (IHd (p ^ ofQ t) m). apply: leq_trans le_Rz_d; rewrite size_map_poly size_minPoly ltnS. rewrite adjoin_degreeE adjoinC (addv_idPl Rz_w) agenv_id. rewrite ltn_divLR ?adim_gt0 // mulnC. rewrite muln_divCA ?field_dimS ?subv_adjoin // ltn_Pmulr ?adim_gt0 //. by rewrite -adjoin_degreeE ltnNge leq_eqVlt orbF adjoin_deg_eq1. rewrite map_monic monic_minPoly -Dz fmorph_root root_minPoly /=. have /polyOverP Cw_p: p \is a polyOver <<Cn; w>>%VS by apply: minPolyOver. apply/polyOver_poly=> j _; have /Fadjoin_polyP[q Cq {j}->] := Cw_p j. rewrite -horner_map (@rpred_horner _ (sQC _)) //. apply/polyOver_poly=> j _. by rewrite (sCle n) // -memCn (polyOverP Cq). have [evenG | oddG] := boolP (2.-group G); last first. have [P /and3P[sPG evenP oddPG]] := Sylow_exists 2 'Gal(Rz / Rn). have [w defQw] := PET_Qz t [aspace of fixedField P]. pose pw := minPoly Rn w; pose p := (- pw * (pw \Po - 'X)) ^ ofQ t. have sz_pw: (size pw).-1 = #|'Gal(Rz / Rn) : P|. rewrite size_minPoly adjoin_degreeE -dim_fixed_galois //= -defQw. congr (\dim_Rn _); apply/esym/eqP; rewrite eqEsubv adjoinSl ?sub1v //=. by apply/FadjoinP; rewrite memv_adjoin /= defQw -galois_connection. have mon_p: p \is monic. have mon_pw: pw \is monic := monic_minPoly _ _. rewrite map_monic mulNr -mulrN monicMl // monicE. rewrite !(lead_coefN, lead_coef_comp) ?size_polyN ?size_polyX //. by rewrite lead_coefX sz_pw -signr_odd odd_2'nat oddPG mulrN1 opprK. have Dp0: p.[0] = - ofQ t pw.[0] ^+ 2. rewrite -(rmorph0 (ofQ t)) horner_map hornerM rmorphM. by rewrite horner_comp !hornerN hornerX oppr0 /= rmorphN mulNr. have Rpw: pw \is a polyOver Rn by apply: minPolyOver. have Rp: p \is a polyOver (sQ (x_ n)). apply/polyOver_poly=> j _; rewrite -memRn; apply: polyOverP j => /=. by rewrite rpredM 1?polyOver_comp ?rpredN ?polyOverX. have Rp0: ofQ t pw.[0] \in sQ (x_ n) by rewrite -memRn rpred_horner ?rpred0. have [|{mon_p Rp Rp0 Dp0}m lenm p_Rm_0] := xRroot n p (ofQ t pw.[0]). by rewrite /has_Rroot mon_p Rp Rp0 -Dp0 /=. have{p_Rm_0} [y Ry pw_y]: {y | y \in sQ (x_ m) & root (pw ^ ofQ t) y}. apply/sig2W; have [y Ry] := p_Rm_0. rewrite [p]rmorphM /= map_comp_poly !rmorphN /= map_polyX. rewrite rootM rootN root_comp hornerN hornerX. by case/orP; [exists y | exists (- y)]; rewrite ?(rpredN (sQC _)). have [u Rz_u Dy]: exists2 u, u \in Rz & y = ofQ t u. have Rz_w: w \in Rz by rewrite -sub_adjoin1v defQw capvSl. have [sg [Gsg _ Dpw]] := galois_factors sRnRz galRz w Rz_w. set s := map _ sg in Dpw. have /mapP[u /mapP[g Gg Du] ->]: y \in map (ofQ t) s. by rewrite -root_prod_XsubC -/(rp C _) -map_rp -[rp _ _]Dpw. by exists u; rewrite // Du memv_gal. have{pw_y} pw_u: root pw u by rewrite -(fmorph_root (ofQ t)) -Dy. exists m => //; exists u; first by rewrite -Dy; apply: sQtrans Ry _. rewrite inE /= Rz_u andbT; apply: contra oddG => Cu. suffices: 2.-group 'Gal(Rz / Rn). apply: pnat_dvd; rewrite -!galois_dim // ?(galoisS _ galQr) ?sRCz //. rewrite dvdn_divLR ?field_dimS ?adim_gt0 //. by rewrite mulnC muln_divCA ?field_dimS ?dvdn_mulr. congr (2.-group _): evenP; apply/eqP. rewrite eqEsubset sPG -indexg_eq1 (pnat_1 _ oddPG) // -sz_pw. have (pu := minPoly Rn u): (pu %= pw) || (pu %= 1). by rewrite minPoly_irr ?minPoly_dvdp ?minPolyOver. rewrite /= -size_poly_eq1 {1}size_minPoly orbF => /eqp_size <-. rewrite size_minPoly /= adjoin_degreeE (@pnat_dvd _ 2) // -dimCn. rewrite dvdn_divLR ?divnK ?adim_gt0 ?field_dimS ?subv_adjoin //. exact/FadjoinP. have [w Rz_w deg_w]: exists2 w, w \in Rz & adjoin_degree Cn w = 2%N. have [P sPG iPG]: exists2 P : {group gal_of Rz}, P \subset G & #|G : P| = 2%N. have [_ _ [k oG]] := pgroup_pdiv evenG ntG. have [P [sPG _ oP]] := normal_pgroup evenG (normal_refl G) (leq_pred _). by exists P => //; rewrite -divgS // oP oG pfactorK // -expnB ?subSnn. have [w defQw] := PET_Qz _ [aspace of fixedField P]. exists w; first by rewrite -sub_adjoin1v defQw capvSl. rewrite adjoin_degreeE -iPG -dim_fixed_galois // -defQw; congr (\dim_Cn _). apply/esym/eqP; rewrite eqEsubv adjoinSl ?sub1v //=; apply/FadjoinP. by rewrite memv_adjoin /= defQw -galois_connection. have nz2: 2 != 0 :> Qt by move/pcharf0P: (pcharQ (Q t)) => ->. without loss{deg_w} [C'w Cw2]: w Rz_w / w \notin Cn /\ w ^+ 2 \in Cn. pose p := minPoly Cn w; pose v := p`_1 / 2. have /polyOverP Cp: p \is a polyOver Cn := minPolyOver Cn w. have Cv: v \in Cn by rewrite rpred_div ?rpred_nat ?Cp. move/(_ (v + w)); apply; first by rewrite rpredD // subvP_adjoin. split; first by rewrite rpredDl // -adjoin_deg_eq1 deg_w. rewrite addrC -[_ ^+ 2]subr0 -(rootP (root_minPoly Cn w)) -/p. rewrite sqrrD [_ - _]addrAC rpredD ?rpredX // -mulr_natr -mulrA divfK //. rewrite [w ^+ 2 + _]addrC mulrC -rpredN opprB horner_coef. have /monicP := monic_minPoly Cn w; rewrite lead_coefE size_minPoly deg_w. by rewrite 2!big_ord_recl big_ord1 => ->; rewrite mulr1 mul1r addrK Cp. without loss R'w2: w Rz_w C'w Cw2 / w ^+ 2 \notin Rn. move=> IHw; have [Rw2 | /IHw] := boolP (w ^+ 2 \in Rn); last exact. have R'it: i_t \notin Rn by rewrite memRn Dit. pose v := 1 + i_t; have R'v: v \notin Rn by rewrite rpredDl ?rpred1. have Cv: v \in Cn by rewrite rpredD ?rpred1 ?memv_adjoin. have nz_v: v != 0 by rewrite (memPnC R'v) ?rpred0. apply: (IHw (v * w)); last 1 [|] || by rewrite fpredMl // subvP_adjoin. by rewrite exprMn rpredM // rpredX. rewrite exprMn fpredMr //=; last by rewrite expf_eq0 (memPnC C'w) ?rpred0. by rewrite sqrrD Dit2 expr1n addrC addKr -mulrnAl fpredMl ?rpred_nat. pose rect_w2 u v := [/\ u \in Rn, v \in Rn & u + i_t * (v * 2) = w ^+ 2]. have{Cw2} [u [v [Ru Rv Dw2]]]: {u : Qt & {v | rect_w2 u v}}. rewrite /rect_w2 -(Fadjoin_poly_eq Cw2); set p := Fadjoin_poly Rn i_t _. have /polyOverP Rp: p \is a polyOver Rn by apply: Fadjoin_polyOver. exists p`_0, (p`_1 / 2); split; rewrite ?rpred_div ?rpred_nat //. rewrite divfK // (horner_coef_wide _ (size_Fadjoin_poly _ _ _)) -/p. by rewrite adjoin_degreeE dimCn big_ord_recl big_ord1 mulr1 mulrC. pose p := Poly [:: - (ofQ t v ^+ 2); 0; - ofQ t u; 0; 1]. have [|m lenm [x Rx px0]] := xRroot n p (ofQ t v). rewrite /has_Rroot 2!unfold_in/= lead_coefE horner_coef0 -memRn Rv. rewrite (@PolyK _ 1) ?oner_eq0 //= !eqxx. rewrite !(rpred0 (sQC _)) ?(rpred1 (sQC _)) ?(rpredN (sQC _)) //=. by rewrite !andbT (@rpredX _ (sQC _)) -memRn. suffices [y Cy Dy2]: {y | y \in sQ (z_ m) & ofQ t w ^+ 2 == y ^+ 2}. exists m => //; exists w; last by rewrite inE C'w. by move: Dy2; rewrite eqf_sqr => /pred2P[]->; rewrite ?(rpredN (sQC _)). exists (x + i * (ofQ t v / x)). rewrite (@rpredD _ (sQC _)) 1?(@rpredM _ (sQC _)) //=. exact: (sQtrans (x_ m)). by rewrite (@rpred_div _ (sQC _)) // (sQtrans (x_ m)) // (sRle n) // -memRn. rewrite rootE /horner (@PolyK _ 1) ?oner_eq0 //= ?addr0 ?mul0r in px0. rewrite add0r mul1r -mulrA -expr2 subr_eq0 in px0. have nz_x2: x ^+ 2 != 0. apply: contraNneq R'w2 => y2_0; rewrite -Dw2 mulrCA. suffices /eqP->: v == 0 by rewrite mul0r addr0. by rewrite y2_0 mulr0 eq_sym sqrf_eq0 fmorph_eq0 in px0. apply/eqP/esym/(mulIf nz_x2); rewrite -exprMn -rmorphXn -Dw2 rmorphD rmorphM. rewrite /= Dit mulrDl -expr2 mulrA divfK; last by rewrite expf_eq0 in nz_x2. rewrite mulr_natr addrC sqrrD exprMn Di2 mulN1r -(eqP px0) -mulNr opprB. by rewrite -mulrnAl -mulrnAr -rmorphMn -!mulrDl addrAC subrK. have inFTA n z: (n_ z <= n)%N -> z = ofQ (z_ n) (inQ (z_ n) z). by move/sCle=> le_zn; rewrite inQ_K ?le_zn. pose is_cj n cj := {in R_ n, cj =1 id} /\ cj (i_ n) = - i_ n. have /all_sig[cj_ /all_and2[cj_R cj_i]] n: {cj : 'AEnd(Q (z_ n)) | is_cj n cj}. have cj_P: root (minPoly (R_ n) (i_ n) ^ \1%VF) (- i_ n). rewrite minp_i -(fmorph_root (ofQ _)) !rmorphD !rmorph1 /= !map_polyXn. by rewrite rmorphN inQ_K // rootE hornerD hornerXn hornerC sqrrN Di2 addNr. have cj_M: ahom_in fullv (kHomExtend (R_ n) \1 (i_ n) (- i_ n)). by rewrite -defRi -k1HomE kHomExtendP ?sub1v ?kHom1. exists (AHom cj_M); split=> [y /kHomExtend_id->|]; first by rewrite ?id_lfunE. by rewrite (kHomExtend_val (kHom1 1 _)). pose conj_ n z := ofQ _ (cj_ n (inQ _ z)); pose conj z := conj_ (n_ z) z. have conjK n m z: (n_ z <= n)%N -> (n <= m)%N -> conj_ m (conj_ n z) = z. move/sCle=> le_z_n le_n_m; have /le_z_n/sQ_inQ[u <-] := FTA z. have /QtoQ[Qmn QmnE]: z_ n \in sQ (z_ m) by rewrite (sCle n). rewrite /conj_ ofQ_K -!QmnE !ofQ_K -!comp_lfunE; congr (ofQ _ _). move: u (memRi n u); apply/eqlfun_inP/FadjoinP; split=> /=. apply/eqlfun_inP=> y Ry; rewrite !comp_lfunE !cj_R //. by move: Ry; rewrite -!sQof2 QmnE !inQ_K //; apply: sRle. apply/eqlfunP; rewrite !comp_lfunE cj_i !linearN /=. suffices ->: Qmn (i_ n) = i_ m by rewrite cj_i ?opprK. by apply: (fmorph_inj (ofQ _)); rewrite QmnE !inQ_K. have conjE n z: (n_ z <= n)%N -> conj z = conj_ n z. move/leq_trans=> le_zn; set x := conj z; set y := conj_ n z. have [m [le_xm le_ym le_nm]] := maxn3 (n_ x) (n_ y) n. by have /conjK/=/can_in_inj := leqnn m; apply; rewrite ?conjK // le_zn. have conjA : zmod_morphism conj. move=> x y. have [m [le_xm le_ym le_xym]] := maxn3 (n_ x) (n_ y) (n_ (x - y)). by rewrite !(conjE m) // (inFTA m x) // (inFTA m y) -?rmorphB /conj_ ?ofQ_K. have conjM : monoid_morphism conj. split=> [|x y]; first pose n1 := n_ 1. by rewrite /conj -/n1 -(rmorph1 (ofQ (z_ n1))) /conj_ ofQ_K !rmorph1. have [m [le_xm le_ym le_xym]] := maxn3 (n_ x) (n_ y) (n_ (x * y)). by rewrite !(conjE m) // (inFTA m x) // (inFTA m y) -?rmorphM /conj_ ?ofQ_K. have conjaM := GRing.isZmodMorphism.Build _ _ _ conjA. have conjmM := GRing.isMonoidMorphism.Build _ _ _ conjM. pose conjRM : {rmorphism _ -> _} := HB.pack conj conjaM conjmM. exists conjRM => [z | /(_ i)/eqP/idPn[]] /=. by have [n [/conjE-> /(conjK (n_ z))->]] := maxn3 (n_ (conj z)) (n_ z) 0. rewrite /conj/conj_ cj_i rmorphN inQ_K // eq_sym -addr_eq0 -mulr2n -mulr_natl. rewrite mulf_neq0 ?(memPnC (R'i 0)) ?(rpred0 (sQC _)) //. by have /pcharf0P-> := ftrans (fmorph_pchar QtoC) (pchar_num _). Qed.
Imo2019Q4.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Data.Nat.Factorial.BigOperators import Mathlib.Data.Nat.Multiplicity import Mathlib.Data.Nat.Prime.Int import Mathlib.Tactic.IntervalCases import Mathlib.Tactic.GCongr /-! # IMO 2019 Q4 Find all pairs `(k, n)` of positive integers such that ``` k! = (2 ^ n - 1)(2 ^ n - 2)(2 ^ n - 4)···(2 ^ n - 2 ^ (n - 1)) ``` We show in this file that this property holds iff `(k, n) = (1, 1) ∨ (k, n) = (3, 2)`. Proof sketch: The idea of the proof is to count the factors of 2 on both sides. The LHS has less than `k` factors of 2, and the RHS has exactly `n * (n - 1) / 2` factors of 2. So we know that `n * (n - 1) / 2 < k`. Now for `n ≥ 6` we have `RHS < 2 ^ (n ^ 2) < (n(n-1)/2)! < k!`. We then treat the cases `n < 6` individually. -/ open scoped Nat open Nat hiding zero_le Prime open Finset namespace Imo2019Q4 theorem upper_bound {k n : ℕ} (hk : k > 0) (h : (k ! : ℤ) = ∏ i ∈ range n, ((2 : ℤ) ^ n - (2 : ℤ) ^ i)) : n < 6 := by have h2 : ∑ i ∈ range n, i < k := by suffices emultiplicity 2 (k ! : ℤ) = ↑(∑ i ∈ range n, i : ℕ) by rw [← Nat.cast_lt (α := ℕ∞), ← this]; change emultiplicity ((2 : ℕ) : ℤ) _ < _ simp_rw [Int.natCast_emultiplicity, emultiplicity_two_factorial_lt hk.lt.ne.symm] rw [h, Finset.emultiplicity_prod Int.prime_two, Nat.cast_sum] apply sum_congr rfl; intro i hi rw [emultiplicity_sub_of_gt, emultiplicity_pow_self_of_prime Int.prime_two] rwa [emultiplicity_pow_self_of_prime Int.prime_two, emultiplicity_pow_self_of_prime Int.prime_two, Nat.cast_lt, ← mem_range] rw [← not_le]; intro hn apply _root_.ne_of_gt _ h calc ∏ i ∈ range n, ((2:ℤ) ^ n - (2:ℤ) ^ i) ≤ ∏ __ ∈ range n, (2:ℤ) ^ n := ?_ _ < ↑ k ! := ?_ · gcongr · intro i hi simp only [mem_range] at hi have : (2:ℤ) ^ i ≤ (2:ℤ) ^ n := by gcongr; norm_num linarith · apply sub_le_self positivity norm_cast calc ∏ __ ∈ range n, 2 ^ n = 2 ^ (n * n) := by rw [prod_const, card_range, ← pow_mul] _ < (∑ i ∈ range n, i)! := ?_ _ ≤ k ! := by gcongr clear h h2 induction n, hn using Nat.le_induction with | base => decide | succ n' hn' IH => let A := ∑ i ∈ range n', i have le_sum : ∑ i ∈ range 6, i ≤ A := by apply sum_le_sum_of_subset simpa using hn' calc 2 ^ ((n' + 1) * (n' + 1)) ≤ 2 ^ (n' * n' + 4 * n') := by gcongr <;> linarith _ = 2 ^ (n' * n') * (2 ^ 4) ^ n' := by rw [← pow_mul, ← pow_add] _ < A ! * (2 ^ 4) ^ n' := by gcongr _ = A ! * (15 + 1) ^ n' := rfl _ ≤ A ! * (A + 1) ^ n' := by gcongr; exact le_sum _ ≤ (A + n')! := factorial_mul_pow_le_factorial _ = (∑ i ∈ range (n' + 1), i)! := by rw [sum_range_succ] end Imo2019Q4 theorem imo2019_q4 {k n : ℕ} (hk : k > 0) (hn : n > 0) : (k ! : ℤ) = ∏ i ∈ range n, ((2:ℤ) ^ n - (2:ℤ) ^ i) ↔ (k, n) = (1, 1) ∨ (k, n) = (3, 2) := by -- The implication `←` holds. constructor swap · rintro (h | h) <;> simp [Prod.ext_iff] at h <;> rcases h with ⟨rfl, rfl⟩ <;> decide intro h -- We know that n < 6. have := Imo2019Q4.upper_bound hk h interval_cases n -- n = 1 · norm_num at h; simp [le_antisymm h (succ_le_of_lt hk)] -- n = 2 · right; congr; norm_num [prod_range_succ] at h; norm_cast at h; rwa [← factorial_inj'] norm_num all_goals exfalso; norm_num [prod_range_succ] at h; norm_cast at h -- n = 3 · refine monotone_factorial.ne_of_lt_of_lt_nat 5 ?_ ?_ _ h <;> decide -- n = 4 · refine monotone_factorial.ne_of_lt_of_lt_nat 7 ?_ ?_ _ h <;> decide -- n = 5 · refine monotone_factorial.ne_of_lt_of_lt_nat 10 ?_ ?_ _ h <;> decide
Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Data.Set.Function import Mathlib.Logic.Pairwise import Mathlib.Logic.Relation /-! # Relations holding pairwise This file develops pairwise relations and defines pairwise disjoint indexed sets. We also prove many basic facts about `Pairwise`. It is possible that an intermediate file, with more imports than `Logic.Pairwise` but not importing `Data.Set.Function` would be appropriate to hold many of these basic facts. ## Main declarations * `Set.PairwiseDisjoint`: `s.PairwiseDisjoint f` states that images under `f` of distinct elements of `s` are either equal or `Disjoint`. ## Notes The spelling `s.PairwiseDisjoint id` is preferred over `s.Pairwise Disjoint` to permit dot notation on `Set.PairwiseDisjoint`, even though the latter unfolds to something nicer. -/ open Function Order Set variable {α β γ ι ι' : Type*} {r p : α → α → Prop} section Pairwise variable {f g : ι → α} {s t : Set α} {a b : α} theorem pairwise_on_bool (hr : Symmetric r) {a b : α} : Pairwise (r on fun c => cond c a b) ↔ r a b := by simpa [Pairwise, Function.onFun] using @hr a b theorem pairwise_disjoint_on_bool [PartialOrder α] [OrderBot α] {a b : α} : Pairwise (Disjoint on fun c => cond c a b) ↔ Disjoint a b := pairwise_on_bool Disjoint.symm theorem Symmetric.pairwise_on [LinearOrder ι] (hr : Symmetric r) (f : ι → α) : Pairwise (r on f) ↔ ∀ ⦃m n⦄, m < n → r (f m) (f n) := ⟨fun h _m _n hmn => h hmn.ne, fun h _m _n hmn => hmn.lt_or_gt.elim (@h _ _) fun h' => hr (h h')⟩ theorem pairwise_disjoint_on [PartialOrder α] [OrderBot α] [LinearOrder ι] (f : ι → α) : Pairwise (Disjoint on f) ↔ ∀ ⦃m n⦄, m < n → Disjoint (f m) (f n) := Symmetric.pairwise_on Disjoint.symm f theorem pairwise_disjoint_mono [PartialOrder α] [OrderBot α] (hs : Pairwise (Disjoint on f)) (h : g ≤ f) : Pairwise (Disjoint on g) := hs.mono fun i j hij => Disjoint.mono (h i) (h j) hij theorem Pairwise.disjoint_extend_bot [PartialOrder γ] [OrderBot γ] {e : α → β} {f : α → γ} (hf : Pairwise (Disjoint on f)) (he : FactorsThrough f e) : Pairwise (Disjoint on extend e f ⊥) := by intro b₁ b₂ hne rcases em (∃ a₁, e a₁ = b₁) with ⟨a₁, rfl⟩ | hb₁ · rcases em (∃ a₂, e a₂ = b₂) with ⟨a₂, rfl⟩ | hb₂ · simpa only [onFun, he.extend_apply] using hf (ne_of_apply_ne e hne) · simpa only [onFun, extend_apply' _ _ _ hb₂] using disjoint_bot_right · simpa only [onFun, extend_apply' _ _ _ hb₁] using disjoint_bot_left namespace Set theorem Pairwise.mono (h : t ⊆ s) (hs : s.Pairwise r) : t.Pairwise r := fun _x xt _y yt => hs (h xt) (h yt) theorem Pairwise.mono' (H : r ≤ p) (hr : s.Pairwise r) : s.Pairwise p := hr.imp H theorem pairwise_top (s : Set α) : s.Pairwise ⊤ := pairwise_of_forall s _ fun _ _ => trivial protected theorem Subsingleton.pairwise (h : s.Subsingleton) (r : α → α → Prop) : s.Pairwise r := fun _x hx _y hy hne => (hne (h hx hy)).elim @[simp] theorem pairwise_empty (r : α → α → Prop) : (∅ : Set α).Pairwise r := subsingleton_empty.pairwise r @[simp] theorem pairwise_singleton (a : α) (r : α → α → Prop) : Set.Pairwise {a} r := subsingleton_singleton.pairwise r theorem pairwise_iff_of_refl [IsRefl α r] : s.Pairwise r ↔ ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → r a b := forall₄_congr fun _ _ _ _ => or_iff_not_imp_left.symm.trans <| or_iff_right_of_imp of_eq alias ⟨Pairwise.of_refl, _⟩ := pairwise_iff_of_refl theorem Nonempty.pairwise_iff_exists_forall [IsEquiv α r] {s : Set ι} (hs : s.Nonempty) : s.Pairwise (r on f) ↔ ∃ z, ∀ x ∈ s, r (f x) z := by constructor · rcases hs with ⟨y, hy⟩ refine fun H => ⟨f y, fun x hx => ?_⟩ rcases eq_or_ne x y with (rfl | hne) · apply IsRefl.refl · exact H hx hy hne · rintro ⟨z, hz⟩ x hx y hy _ exact @IsTrans.trans α r _ (f x) z (f y) (hz _ hx) (IsSymm.symm _ _ <| hz _ hy) /-- For a nonempty set `s`, a function `f` takes pairwise equal values on `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `Set.pairwise_eq_iff_exists_eq` for a version that assumes `[Nonempty ι]` instead of `Set.Nonempty s`. -/ theorem Nonempty.pairwise_eq_iff_exists_eq {s : Set α} (hs : s.Nonempty) {f : α → ι} : (s.Pairwise fun x y => f x = f y) ↔ ∃ z, ∀ x ∈ s, f x = z := hs.pairwise_iff_exists_forall theorem pairwise_iff_exists_forall [Nonempty ι] (s : Set α) (f : α → ι) {r : ι → ι → Prop} [IsEquiv ι r] : s.Pairwise (r on f) ↔ ∃ z, ∀ x ∈ s, r (f x) z := by rcases s.eq_empty_or_nonempty with (rfl | hne) · simp · exact hne.pairwise_iff_exists_forall /-- A function `f : α → ι` with nonempty codomain takes pairwise equal values on a set `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `Set.Nonempty.pairwise_eq_iff_exists_eq` for a version that assumes `Set.Nonempty s` instead of `[Nonempty ι]`. -/ theorem pairwise_eq_iff_exists_eq [Nonempty ι] (s : Set α) (f : α → ι) : (s.Pairwise fun x y => f x = f y) ↔ ∃ z, ∀ x ∈ s, f x = z := pairwise_iff_exists_forall s f theorem pairwise_union : (s ∪ t).Pairwise r ↔ s.Pairwise r ∧ t.Pairwise r ∧ ∀ a ∈ s, ∀ b ∈ t, a ≠ b → r a b ∧ r b a := by simp only [Set.Pairwise, mem_union, or_imp, forall_and] aesop theorem pairwise_union_of_symmetric (hr : Symmetric r) : (s ∪ t).Pairwise r ↔ s.Pairwise r ∧ t.Pairwise r ∧ ∀ a ∈ s, ∀ b ∈ t, a ≠ b → r a b := pairwise_union.trans <| by simp only [hr.iff, and_self_iff] theorem pairwise_insert : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b ∧ r b a := by simp only [insert_eq, pairwise_union, pairwise_singleton, true_and, mem_singleton_iff, forall_eq] theorem pairwise_insert_of_notMem (ha : a ∉ s) : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, r a b ∧ r b a := pairwise_insert.trans <| and_congr_right' <| forall₂_congr fun b hb => by simp [(ne_of_mem_of_not_mem hb ha).symm] @[deprecated (since := "2025-05-23")] alias pairwise_insert_of_not_mem := pairwise_insert_of_notMem protected theorem Pairwise.insert (hs : s.Pairwise r) (h : ∀ b ∈ s, a ≠ b → r a b ∧ r b a) : (insert a s).Pairwise r := pairwise_insert.2 ⟨hs, h⟩ theorem Pairwise.insert_of_notMem (ha : a ∉ s) (hs : s.Pairwise r) (h : ∀ b ∈ s, r a b ∧ r b a) : (insert a s).Pairwise r := (pairwise_insert_of_notMem ha).2 ⟨hs, h⟩ @[deprecated (since := "2025-05-23")] alias Pairwise.insert_of_not_mem := Pairwise.insert_of_notMem theorem pairwise_insert_of_symmetric (hr : Symmetric r) : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b := by simp only [pairwise_insert, hr.iff a, and_self_iff] theorem pairwise_insert_of_symmetric_of_notMem (hr : Symmetric r) (ha : a ∉ s) : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, r a b := by simp only [pairwise_insert_of_notMem ha, hr.iff a, and_self_iff] @[deprecated (since := "2025-05-23")] alias pairwise_insert_of_symmetric_of_not_mem := pairwise_insert_of_symmetric_of_notMem theorem Pairwise.insert_of_symmetric (hs : s.Pairwise r) (hr : Symmetric r) (h : ∀ b ∈ s, a ≠ b → r a b) : (insert a s).Pairwise r := (pairwise_insert_of_symmetric hr).2 ⟨hs, h⟩ @[deprecated Pairwise.insert_of_symmetric (since := "2025-03-19")] theorem Pairwise.insert_of_symmetric_of_notMem (hs : s.Pairwise r) (hr : Symmetric r) (ha : a ∉ s) (h : ∀ b ∈ s, r a b) : (insert a s).Pairwise r := (pairwise_insert_of_symmetric_of_notMem hr ha).2 ⟨hs, h⟩ @[deprecated (since := "2025-05-23")] alias Pairwise.insert_of_symmetric_of_not_mem := Pairwise.insert_of_symmetric_of_notMem theorem pairwise_pair : Set.Pairwise {a, b} r ↔ a ≠ b → r a b ∧ r b a := by simp [pairwise_insert] theorem pairwise_pair_of_symmetric (hr : Symmetric r) : Set.Pairwise {a, b} r ↔ a ≠ b → r a b := by simp [pairwise_insert_of_symmetric hr] theorem pairwise_univ : (univ : Set α).Pairwise r ↔ Pairwise r := by simp only [Set.Pairwise, Pairwise, mem_univ, forall_const] @[simp] theorem pairwise_bot_iff : s.Pairwise (⊥ : α → α → Prop) ↔ (s : Set α).Subsingleton := ⟨fun h _a ha _b hb => h.eq ha hb id, fun h => h.pairwise _⟩ alias ⟨Pairwise.subsingleton, _⟩ := pairwise_bot_iff /-- See also `Function.injective_iff_pairwise_ne` -/ lemma injOn_iff_pairwise_ne {s : Set ι} : InjOn f s ↔ s.Pairwise (f · ≠ f ·) := by simp only [InjOn, Set.Pairwise, not_imp_not] alias ⟨InjOn.pairwise_ne, _⟩ := injOn_iff_pairwise_ne protected theorem Pairwise.image {s : Set ι} (h : s.Pairwise (r on f)) : (f '' s).Pairwise r := forall_mem_image.2 fun _x hx ↦ forall_mem_image.2 fun _y hy hne ↦ h hx hy <| ne_of_apply_ne _ hne /-- See also `Set.Pairwise.image`. -/ theorem InjOn.pairwise_image {s : Set ι} (h : s.InjOn f) : (f '' s).Pairwise r ↔ s.Pairwise (r on f) := by simp +contextual [h.eq_iff, Set.Pairwise] lemma _root_.Pairwise.range_pairwise (hr : Pairwise (r on f)) : (Set.range f).Pairwise r := image_univ ▸ (pairwise_univ.mpr hr).image end Set end Pairwise theorem pairwise_subtype_iff_pairwise_set (s : Set α) (r : α → α → Prop) : (Pairwise fun (x : s) (y : s) => r x y) ↔ s.Pairwise r := by simp only [Pairwise, Set.Pairwise, SetCoe.forall, Ne, Subtype.ext_iff] alias ⟨Pairwise.set_of_subtype, Set.Pairwise.subtype⟩ := pairwise_subtype_iff_pairwise_set namespace Set section PartialOrderBot variable [PartialOrder α] [OrderBot α] {s t : Set ι} {f g : ι → α} /-- A set is `PairwiseDisjoint` under `f`, if the images of any distinct two elements under `f` are disjoint. `s.Pairwise Disjoint` is (definitionally) the same as `s.PairwiseDisjoint id`. We prefer the latter in order to allow dot notation on `Set.PairwiseDisjoint`, even though the former unfolds more nicely. -/ def PairwiseDisjoint (s : Set ι) (f : ι → α) : Prop := s.Pairwise (Disjoint on f) theorem PairwiseDisjoint.subset (ht : t.PairwiseDisjoint f) (h : s ⊆ t) : s.PairwiseDisjoint f := Pairwise.mono h ht theorem PairwiseDisjoint.mono_on (hs : s.PairwiseDisjoint f) (h : ∀ ⦃i⦄, i ∈ s → g i ≤ f i) : s.PairwiseDisjoint g := fun _a ha _b hb hab => (hs ha hb hab).mono (h ha) (h hb) theorem PairwiseDisjoint.mono (hs : s.PairwiseDisjoint f) (h : g ≤ f) : s.PairwiseDisjoint g := hs.mono_on fun i _ => h i @[simp] theorem pairwiseDisjoint_empty : (∅ : Set ι).PairwiseDisjoint f := pairwise_empty _ @[simp] theorem pairwiseDisjoint_singleton (i : ι) (f : ι → α) : PairwiseDisjoint {i} f := pairwise_singleton i _ theorem pairwiseDisjoint_insert {i : ι} : (insert i s).PairwiseDisjoint f ↔ s.PairwiseDisjoint f ∧ ∀ j ∈ s, i ≠ j → Disjoint (f i) (f j) := pairwise_insert_of_symmetric <| symmetric_disjoint.comap f theorem pairwiseDisjoint_insert_of_notMem {i : ι} (hi : i ∉ s) : (insert i s).PairwiseDisjoint f ↔ s.PairwiseDisjoint f ∧ ∀ j ∈ s, Disjoint (f i) (f j) := pairwise_insert_of_symmetric_of_notMem (symmetric_disjoint.comap f) hi @[deprecated (since := "2025-05-23")] alias pairwiseDisjoint_insert_of_not_mem := pairwiseDisjoint_insert_of_notMem protected theorem PairwiseDisjoint.insert (hs : s.PairwiseDisjoint f) {i : ι} (h : ∀ j ∈ s, i ≠ j → Disjoint (f i) (f j)) : (insert i s).PairwiseDisjoint f := pairwiseDisjoint_insert.2 ⟨hs, h⟩ theorem PairwiseDisjoint.insert_of_notMem (hs : s.PairwiseDisjoint f) {i : ι} (hi : i ∉ s) (h : ∀ j ∈ s, Disjoint (f i) (f j)) : (insert i s).PairwiseDisjoint f := (pairwiseDisjoint_insert_of_notMem hi).2 ⟨hs, h⟩ @[deprecated (since := "2025-05-23")] alias PairwiseDisjoint.insert_of_not_mem := PairwiseDisjoint.insert_of_notMem theorem PairwiseDisjoint.image_of_le (hs : s.PairwiseDisjoint f) {g : ι → ι} (hg : f ∘ g ≤ f) : (g '' s).PairwiseDisjoint f := by rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ h exact (hs ha hb <| ne_of_apply_ne _ h).mono (hg a) (hg b) theorem InjOn.pairwiseDisjoint_image {g : ι' → ι} {s : Set ι'} (h : s.InjOn g) : (g '' s).PairwiseDisjoint f ↔ s.PairwiseDisjoint (f ∘ g) := h.pairwise_image theorem PairwiseDisjoint.range (g : s → ι) (hg : ∀ i : s, f (g i) ≤ f i) (ht : s.PairwiseDisjoint f) : (range g).PairwiseDisjoint f := by rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy exact ((ht x.2 y.2) fun h => hxy <| congr_arg g <| Subtype.ext h).mono (hg x) (hg y) theorem pairwiseDisjoint_union : (s ∪ t).PairwiseDisjoint f ↔ s.PairwiseDisjoint f ∧ t.PairwiseDisjoint f ∧ ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → Disjoint (f i) (f j) := pairwise_union_of_symmetric <| symmetric_disjoint.comap f theorem PairwiseDisjoint.union (hs : s.PairwiseDisjoint f) (ht : t.PairwiseDisjoint f) (h : ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → Disjoint (f i) (f j)) : (s ∪ t).PairwiseDisjoint f := pairwiseDisjoint_union.2 ⟨hs, ht, h⟩ -- classical theorem PairwiseDisjoint.elim (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : ¬Disjoint (f i) (f j)) : i = j := hs.eq hi hj h lemma PairwiseDisjoint.eq_or_disjoint (h : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) : i = j ∨ Disjoint (f i) (f j) := by rw [or_iff_not_imp_right] exact h.elim hi hj lemma pairwiseDisjoint_range_iff {α β : Type*} {f : α → (Set β)} : (range f).PairwiseDisjoint id ↔ ∀ x y, f x ≠ f y → Disjoint (f x) (f y) := by aesop (add simp [PairwiseDisjoint, Set.Pairwise]) /-- If the range of `f` is pairwise disjoint, then the image of any set `s` under `f` is as well. -/ lemma _root_.Pairwise.pairwiseDisjoint (h : Pairwise (Disjoint on f)) (s : Set ι) : s.PairwiseDisjoint f := h.set_pairwise s end PartialOrderBot section SemilatticeInfBot variable [SemilatticeInf α] [OrderBot α] {s : Set ι} {f : ι → α} -- classical theorem PairwiseDisjoint.elim' (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : f i ⊓ f j ≠ ⊥) : i = j := (hs.elim hi hj) fun hij => h hij.eq_bot theorem PairwiseDisjoint.eq_of_le (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (hf : f i ≠ ⊥) (hij : f i ≤ f j) : i = j := (hs.elim' hi hj) fun h => hf <| (inf_of_le_left hij).symm.trans h end SemilatticeInfBot /-! ### Pairwise disjoint set of sets -/ variable {s : Set ι} {t : Set ι'} theorem pairwiseDisjoint_range_singleton : (range (singleton : ι → Set ι)).PairwiseDisjoint id := Pairwise.range_pairwise fun _ _ => disjoint_singleton.2 theorem pairwiseDisjoint_fiber (f : ι → α) (s : Set α) : s.PairwiseDisjoint fun a => f ⁻¹' {a} := fun _a _ _b _ h => disjoint_iff_inf_le.mpr fun _i ⟨hia, hib⟩ => h <| (Eq.symm hia).trans hib -- classical theorem PairwiseDisjoint.elim_set {s : Set ι} {f : ι → Set α} (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (a : α) (hai : a ∈ f i) (haj : a ∈ f j) : i = j := hs.elim hi hj <| not_disjoint_iff.2 ⟨a, hai, haj⟩ theorem PairwiseDisjoint.prod {f : ι → Set α} {g : ι' → Set β} (hs : s.PairwiseDisjoint f) (ht : t.PairwiseDisjoint g) : (s ×ˢ t : Set (ι × ι')).PairwiseDisjoint fun i => f i.1 ×ˢ g i.2 := fun ⟨_, _⟩ ⟨hi, hi'⟩ ⟨_, _⟩ ⟨hj, hj'⟩ hij => disjoint_left.2 fun ⟨_, _⟩ ⟨hai, hbi⟩ ⟨haj, hbj⟩ => hij <| Prod.ext (hs.elim_set hi hj _ hai haj) <| ht.elim_set hi' hj' _ hbi hbj theorem pairwiseDisjoint_pi {ι' α : ι → Type*} {s : ∀ i, Set (ι' i)} {f : ∀ i, ι' i → Set (α i)} (hs : ∀ i, (s i).PairwiseDisjoint (f i)) : ((univ : Set ι).pi s).PairwiseDisjoint fun I => (univ : Set ι).pi fun i => f _ (I i) := fun _ hI _ hJ hIJ => disjoint_left.2 fun a haI haJ => hIJ <| funext fun i => (hs i).elim_set (hI i trivial) (hJ i trivial) (a i) (haI i trivial) (haJ i trivial) /-- The partial images of a binary function `f` whose partial evaluations are injective are pairwise disjoint iff `f` is injective . -/ theorem pairwiseDisjoint_image_right_iff {f : α → β → γ} {s : Set α} {t : Set β} (hf : ∀ a ∈ s, Injective (f a)) : (s.PairwiseDisjoint fun a => f a '' t) ↔ (s ×ˢ t).InjOn fun p => f p.1 p.2 := by refine ⟨fun hs x hx y hy (h : f _ _ = _) => ?_, fun hs x hx y hy h => ?_⟩ · suffices x.1 = y.1 by exact Prod.ext this (hf _ hx.1 <| h.trans <| by rw [this]) refine hs.elim hx.1 hy.1 (not_disjoint_iff.2 ⟨_, mem_image_of_mem _ hx.2, ?_⟩) rw [h] exact mem_image_of_mem _ hy.2 · refine disjoint_iff_inf_le.mpr ?_ rintro _ ⟨⟨a, ha, hab⟩, b, hb, rfl⟩ exact h (congr_arg Prod.fst <| hs (mk_mem_prod hx ha) (mk_mem_prod hy hb) hab) /-- The partial images of a binary function `f` whose partial evaluations are injective are pairwise disjoint iff `f` is injective . -/ theorem pairwiseDisjoint_image_left_iff {f : α → β → γ} {s : Set α} {t : Set β} (hf : ∀ b ∈ t, Injective fun a => f a b) : (t.PairwiseDisjoint fun b => (fun a => f a b) '' s) ↔ (s ×ˢ t).InjOn fun p => f p.1 p.2 := by refine ⟨fun ht x hx y hy (h : f _ _ = _) => ?_, fun ht x hx y hy h => ?_⟩ · suffices x.2 = y.2 by exact Prod.ext (hf _ hx.2 <| h.trans <| by rw [this]) this refine ht.elim hx.2 hy.2 (not_disjoint_iff.2 ⟨_, mem_image_of_mem _ hx.1, ?_⟩) rw [h] exact mem_image_of_mem _ hy.1 · refine disjoint_iff_inf_le.mpr ?_ rintro _ ⟨⟨a, ha, hab⟩, b, hb, rfl⟩ exact h (congr_arg Prod.snd <| ht (mk_mem_prod ha hx) (mk_mem_prod hb hy) hab) lemma exists_ne_mem_inter_of_not_pairwiseDisjoint {f : ι → Set α} (h : ¬ s.PairwiseDisjoint f) : ∃ i ∈ s, ∃ j ∈ s, i ≠ j ∧ ∃ x : α, x ∈ f i ∩ f j := by change ¬ ∀ i, i ∈ s → ∀ j, j ∈ s → i ≠ j → ∀ t, t ≤ f i → t ≤ f j → t ≤ ⊥ at h simp only [not_forall] at h obtain ⟨i, hi, j, hj, h_ne, t, hfi, hfj, ht⟩ := h replace ht : t.Nonempty := by rwa [le_bot_iff, bot_eq_empty, ← Ne, ← nonempty_iff_ne_empty] at ht obtain ⟨x, hx⟩ := ht exact ⟨i, hi, j, hj, h_ne, x, hfi hx, hfj hx⟩ lemma exists_lt_mem_inter_of_not_pairwiseDisjoint [LinearOrder ι] {f : ι → Set α} (h : ¬ s.PairwiseDisjoint f) : ∃ i ∈ s, ∃ j ∈ s, i < j ∧ ∃ x, x ∈ f i ∩ f j := by obtain ⟨i, hi, j, hj, hne, x, hx₁, hx₂⟩ := exists_ne_mem_inter_of_not_pairwiseDisjoint h rcases lt_or_lt_iff_ne.mpr hne with h_lt | h_lt · exact ⟨i, hi, j, hj, h_lt, x, hx₁, hx₂⟩ · exact ⟨j, hj, i, hi, h_lt, x, hx₂, hx₁⟩ end Set lemma exists_ne_mem_inter_of_not_pairwise_disjoint {f : ι → Set α} (h : ¬ Pairwise (Disjoint on f)) : ∃ i j : ι, i ≠ j ∧ ∃ x, x ∈ f i ∩ f j := by rw [← pairwise_univ] at h obtain ⟨i, _hi, j, _hj, h⟩ := exists_ne_mem_inter_of_not_pairwiseDisjoint h exact ⟨i, j, h⟩ lemma exists_lt_mem_inter_of_not_pairwise_disjoint [LinearOrder ι] {f : ι → Set α} (h : ¬ Pairwise (Disjoint on f)) : ∃ i j : ι, i < j ∧ ∃ x, x ∈ f i ∩ f j := by rw [← pairwise_univ] at h obtain ⟨i, _hi, j, _hj, h⟩ := exists_lt_mem_inter_of_not_pairwiseDisjoint h exact ⟨i, j, h⟩ theorem pairwise_disjoint_fiber (f : ι → α) : Pairwise (Disjoint on fun a : α => f ⁻¹' {a}) := pairwise_univ.1 <| Set.pairwiseDisjoint_fiber f univ lemma subsingleton_setOf_mem_iff_pairwise_disjoint {f : ι → Set α} : (∀ a, {i | a ∈ f i}.Subsingleton) ↔ Pairwise (Disjoint on f) := ⟨fun h _ _ hij ↦ disjoint_left.2 fun a hi hj ↦ hij (h a hi hj), fun h _ _ hx _ hy ↦ by_contra fun hne ↦ disjoint_left.1 (h hne) hx hy⟩
Metrizable.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.MeasureTheory.Constructions.BorelSpace.Metric import Mathlib.MeasureTheory.Constructions.BorelSpace.Real import Mathlib.Topology.Metrizable.Real import Mathlib.Topology.IndicatorConstPointwise /-! # Measurable functions in (pseudo-)metrizable Borel spaces -/ open Filter MeasureTheory TopologicalSpace Topology NNReal ENNReal MeasureTheory variable {α β : Type*} [MeasurableSpace α] section Limits variable [TopologicalSpace β] [PseudoMetrizableSpace β] [MeasurableSpace β] [BorelSpace β] open Metric /-- A limit (over a general filter) of measurable functions valued in a (pseudo) metrizable space is measurable. -/ theorem measurable_of_tendsto_metrizable' {ι} {f : ι → α → β} {g : α → β} (u : Filter ι) [NeBot u] [IsCountablyGenerated u] (hf : ∀ i, Measurable (f i)) (lim : Tendsto f u (𝓝 g)) : Measurable g := by letI : PseudoMetricSpace β := pseudoMetrizableSpacePseudoMetric β apply measurable_of_isClosed' intro s h1s h2s h3s have : Measurable fun x => infNndist (g x) s := by suffices Tendsto (fun i x => infNndist (f i x) s) u (𝓝 fun x => infNndist (g x) s) from NNReal.measurable_of_tendsto' u (fun i => (hf i).infNndist) this rw [tendsto_pi_nhds] at lim ⊢ intro x exact ((continuous_infNndist_pt s).tendsto (g x)).comp (lim x) have h4s : g ⁻¹' s = (fun x => infNndist (g x) s) ⁻¹' {0} := by ext x simp [← h1s.mem_iff_infDist_zero h2s, ← NNReal.coe_eq_zero] rw [h4s] exact this (measurableSet_singleton 0) /-- A sequential limit of measurable functions valued in a (pseudo) metrizable space is measurable. -/ theorem measurable_of_tendsto_metrizable {f : ℕ → α → β} {g : α → β} (hf : ∀ i, Measurable (f i)) (lim : Tendsto f atTop (𝓝 g)) : Measurable g := measurable_of_tendsto_metrizable' atTop hf lim theorem aemeasurable_of_tendsto_metrizable_ae {ι} {μ : Measure α} {f : ι → α → β} {g : α → β} (u : Filter ι) [hu : NeBot u] [IsCountablyGenerated u] (hf : ∀ n, AEMeasurable (f n) μ) (h_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) u (𝓝 (g x))) : AEMeasurable g μ := by classical rcases u.exists_seq_tendsto with ⟨v, hv⟩ have h'f : ∀ n, AEMeasurable (f (v n)) μ := fun n => hf (v n) set p : α → (ℕ → β) → Prop := fun x f' => Tendsto (fun n => f' n) atTop (𝓝 (g x)) have hp : ∀ᵐ x ∂μ, p x fun n => f (v n) x := by filter_upwards [h_tendsto] with x hx using hx.comp hv set aeSeqLim := fun x => ite (x ∈ aeSeqSet h'f p) (g x) (⟨f (v 0) x⟩ : Nonempty β).some refine ⟨aeSeqLim, measurable_of_tendsto_metrizable' atTop (aeSeq.measurable h'f p) (tendsto_pi_nhds.mpr fun x => ?_), ?_⟩ · simp_rw [aeSeqLim, aeSeq] split_ifs with hx · simp_rw [aeSeq.mk_eq_fun_of_mem_aeSeqSet h'f hx] exact @aeSeq.fun_prop_of_mem_aeSeqSet _ α β _ _ _ _ _ h'f x hx · exact tendsto_const_nhds · exact (ite_ae_eq_of_measure_compl_zero g (fun x => (⟨f (v 0) x⟩ : Nonempty β).some) (aeSeqSet h'f p) (aeSeq.measure_compl_aeSeqSet_eq_zero h'f hp)).symm theorem aemeasurable_of_tendsto_metrizable_ae' {μ : Measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, AEMeasurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 (g x))) : AEMeasurable g μ := aemeasurable_of_tendsto_metrizable_ae atTop hf h_ae_tendsto theorem aemeasurable_of_unif_approx {β} [MeasurableSpace β] [PseudoMetricSpace β] [BorelSpace β] {μ : Measure α} {g : α → β} (hf : ∀ ε > (0 : ℝ), ∃ f : α → β, AEMeasurable f μ ∧ ∀ᵐ x ∂μ, dist (f x) (g x) ≤ ε) : AEMeasurable g μ := by obtain ⟨u, -, u_pos, u_lim⟩ : ∃ u : ℕ → ℝ, StrictAnti u ∧ (∀ n : ℕ, 0 < u n) ∧ Tendsto u atTop (𝓝 0) := exists_seq_strictAnti_tendsto (0 : ℝ) choose f Hf using fun n : ℕ => hf (u n) (u_pos n) have : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 (g x)) := by have : ∀ᵐ x ∂μ, ∀ n, dist (f n x) (g x) ≤ u n := ae_all_iff.2 fun n => (Hf n).2 filter_upwards [this] intro x hx rw [tendsto_iff_dist_tendsto_zero] exact squeeze_zero (fun n => dist_nonneg) hx u_lim exact aemeasurable_of_tendsto_metrizable_ae' (fun n => (Hf n).1) this theorem measurable_of_tendsto_metrizable_ae {μ : Measure α} [μ.IsComplete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, Measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 (g x))) : Measurable g := aemeasurable_iff_measurable.mp (aemeasurable_of_tendsto_metrizable_ae' (fun i => (hf i).aemeasurable) h_ae_tendsto) theorem measurable_limit_of_tendsto_metrizable_ae {ι} [Countable ι] [Nonempty ι] {μ : Measure α} {f : ι → α → β} {L : Filter ι} [L.IsCountablyGenerated] (hf : ∀ n, AEMeasurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, Tendsto (fun n => f n x) L (𝓝 l)) : ∃ f_lim : α → β, Measurable f_lim ∧ ∀ᵐ x ∂μ, Tendsto (fun n => f n x) L (𝓝 (f_lim x)) := by classical inhabit ι rcases eq_or_neBot L with (rfl | hL) · exact ⟨(hf default).mk _, (hf default).measurable_mk, Eventually.of_forall fun x => tendsto_bot⟩ let p : α → (ι → β) → Prop := fun x f' => ∃ l : β, Tendsto (fun n => f' n) L (𝓝 l) have hp_mem : ∀ x ∈ aeSeqSet hf p, p x fun n => f n x := fun x hx => aeSeq.fun_prop_of_mem_aeSeqSet hf hx have h_ae_eq : ∀ᵐ x ∂μ, ∀ n, aeSeq hf p n x = f n x := aeSeq.aeSeq_eq_fun_ae hf h_ae_tendsto set f_lim : α → β := fun x => dite (x ∈ aeSeqSet hf p) (fun h => (hp_mem x h).choose) fun _ => (⟨f default x⟩ : Nonempty β).some have hf_lim : ∀ x, Tendsto (fun n => aeSeq hf p n x) L (𝓝 (f_lim x)) := by intro x simp only [aeSeq, f_lim] split_ifs with h · refine (hp_mem x h).choose_spec.congr fun n => ?_ exact (aeSeq.mk_eq_fun_of_mem_aeSeqSet hf h n).symm · exact tendsto_const_nhds have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) L (𝓝 (f_lim x)) := h_ae_eq.mono fun x hx => (hf_lim x).congr hx have h_f_lim_meas : Measurable f_lim := measurable_of_tendsto_metrizable' L (aeSeq.measurable hf p) (tendsto_pi_nhds.mpr fun x => hf_lim x) exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩ end Limits section TendstoIndicator variable {α : Type*} [MeasurableSpace α] {A : Set α} variable {ι : Type*} (L : Filter ι) [IsCountablyGenerated L] {As : ι → Set α} /-- If the indicator functions of measurable sets `Aᵢ` converge to the indicator function of a set `A` along a nontrivial countably generated filter, then `A` is also measurable. -/ lemma measurableSet_of_tendsto_indicator [NeBot L] (As_mble : ∀ i, MeasurableSet (As i)) (h_lim : ∀ x, ∀ᶠ i in L, x ∈ As i ↔ x ∈ A) : MeasurableSet A := by simp_rw [← measurable_indicator_const_iff (1 : ℝ≥0∞)] at As_mble ⊢ exact ENNReal.measurable_of_tendsto' L As_mble ((tendsto_indicator_const_iff_forall_eventually L (1 : ℝ≥0∞)).mpr h_lim) /-- If the indicator functions of a.e.-measurable sets `Aᵢ` converge a.e. to the indicator function of a set `A` along a nontrivial countably generated filter, then `A` is also a.e.-measurable. -/ lemma nullMeasurableSet_of_tendsto_indicator [NeBot L] {μ : Measure α} (As_mble : ∀ i, NullMeasurableSet (As i) μ) (h_lim : ∀ᵐ x ∂μ, ∀ᶠ i in L, x ∈ As i ↔ x ∈ A) : NullMeasurableSet A μ := by simp_rw [← aemeasurable_indicator_const_iff (1 : ℝ≥0∞)] at As_mble ⊢ apply aemeasurable_of_tendsto_metrizable_ae L As_mble simpa [tendsto_indicator_const_apply_iff_eventually] using h_lim end TendstoIndicator
OfHasFiniteProducts.lean
/- Copyright (c) 2019 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison, Simon Hudon -/ import Mathlib.CategoryTheory.Monoidal.Braided.Basic import Mathlib.CategoryTheory.Limits.Preserves.Shapes.BinaryProducts import Mathlib.CategoryTheory.Limits.Preserves.Shapes.Terminal /-! # The natural monoidal structure on any category with finite (co)products. A category with a monoidal structure provided in this way is sometimes called a (co)cartesian category, although this is also sometimes used to mean a finitely complete category. (See <https://ncatlab.org/nlab/show/cartesian+category>.) As this works with either products or coproducts, and sometimes we want to think of a different monoidal structure entirely, we don't set up either construct as an instance. ## TODO Replace `monoidalOfHasFiniteProducts` and `symmetricOfHasFiniteProducts` with `CartesianMonoidalCategory.ofHasFiniteProducts`. -/ universe v u noncomputable section namespace CategoryTheory variable (C : Type u) [Category.{v} C] {X Y : C} open CategoryTheory.Limits section /-- A category with a terminal object and binary products has a natural monoidal structure. -/ def monoidalOfHasFiniteProducts [HasTerminal C] [HasBinaryProducts C] : MonoidalCategory C := letI : MonoidalCategoryStruct C := { tensorObj := fun X Y ↦ X ⨯ Y whiskerLeft := fun _ _ _ g ↦ Limits.prod.map (𝟙 _) g whiskerRight := fun {_ _} f _ ↦ Limits.prod.map f (𝟙 _) tensorHom := fun f g ↦ Limits.prod.map f g tensorUnit := ⊤_ C associator := prod.associator leftUnitor := fun P ↦ Limits.prod.leftUnitor P rightUnitor := fun P ↦ Limits.prod.rightUnitor P } .ofTensorHom (pentagon := prod.pentagon) (triangle := prod.triangle) (associator_naturality := @prod.associator_naturality _ _ _) end namespace monoidalOfHasFiniteProducts variable [HasTerminal C] [HasBinaryProducts C] attribute [local instance] monoidalOfHasFiniteProducts open scoped MonoidalCategory @[ext] theorem unit_ext {X : C} (f g : X ⟶ 𝟙_ C) : f = g := terminal.hom_ext f g @[ext] theorem tensor_ext {X Y Z : C} (f g : X ⟶ Y ⊗ Z) (w₁ : f ≫ prod.fst = g ≫ prod.fst) (w₂ : f ≫ prod.snd = g ≫ prod.snd) : f = g := Limits.prod.hom_ext w₁ w₂ @[simp] theorem tensorUnit : 𝟙_ C = ⊤_ C := rfl @[simp] theorem tensorObj (X Y : C) : X ⊗ Y = (X ⨯ Y) := rfl @[simp] theorem tensorHom {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : f ⊗ₘ g = Limits.prod.map f g := rfl @[simp] theorem whiskerLeft (X : C) {Y Z : C} (f : Y ⟶ Z) : X ◁ f = Limits.prod.map (𝟙 X) f := rfl @[simp] theorem whiskerRight {X Y : C} (f : X ⟶ Y) (Z : C) : f ▷ Z = Limits.prod.map f (𝟙 Z) := rfl @[simp] theorem leftUnitor_hom (X : C) : (λ_ X).hom = Limits.prod.snd := rfl @[simp] theorem leftUnitor_inv (X : C) : (λ_ X).inv = prod.lift (terminal.from X) (𝟙 _) := rfl @[simp] theorem rightUnitor_hom (X : C) : (ρ_ X).hom = Limits.prod.fst := rfl @[simp] theorem rightUnitor_inv (X : C) : (ρ_ X).inv = prod.lift (𝟙 _) (terminal.from X) := rfl -- We don't mark this as a simp lemma, even though in many particular -- categories the right hand side will simplify significantly further. -- For now, we'll plan to create specialised simp lemmas in each particular category. theorem associator_hom (X Y Z : C) : (α_ X Y Z).hom = prod.lift (Limits.prod.fst ≫ Limits.prod.fst) (prod.lift (Limits.prod.fst ≫ Limits.prod.snd) Limits.prod.snd) := rfl theorem associator_inv (X Y Z : C) : (α_ X Y Z).inv = prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) := rfl @[reassoc] theorem associator_hom_fst (X Y Z : C) : (α_ X Y Z).hom ≫ prod.fst = prod.fst ≫ prod.fst := by simp [associator_hom] @[reassoc] theorem associator_hom_snd_fst (X Y Z : C) : (α_ X Y Z).hom ≫ prod.snd ≫ prod.fst = prod.fst ≫ prod.snd := by simp [associator_hom] @[reassoc] theorem associator_hom_snd_snd (X Y Z : C) : (α_ X Y Z).hom ≫ prod.snd ≫ prod.snd = prod.snd := by simp [associator_hom] @[reassoc] theorem associator_inv_fst_fst (X Y Z : C) : (α_ X Y Z).inv ≫ prod.fst ≫ prod.fst = prod.fst := by simp [associator_inv] @[reassoc] theorem associator_inv_fst_snd (X Y Z : C) : (α_ X Y Z).inv ≫ prod.fst ≫ prod.snd = prod.snd ≫ prod.fst := by simp [associator_inv] @[reassoc] theorem associator_inv_snd (X Y Z : C) : (α_ X Y Z).inv ≫ prod.snd = prod.snd ≫ prod.snd := by simp [associator_inv] end monoidalOfHasFiniteProducts section attribute [local instance] monoidalOfHasFiniteProducts open MonoidalCategory /-- The monoidal structure coming from finite products is symmetric. -/ @[simps] def symmetricOfHasFiniteProducts [HasTerminal C] [HasBinaryProducts C] : SymmetricCategory C where braiding X Y := Limits.prod.braiding X Y braiding_naturality_left f X := by simp braiding_naturality_right X _ _ f := by simp hexagon_forward X Y Z := by dsimp [monoidalOfHasFiniteProducts.associator_hom]; simp hexagon_reverse X Y Z := by dsimp [monoidalOfHasFiniteProducts.associator_inv]; simp symmetry X Y := by simp end section /-- A category with an initial object and binary coproducts has a natural monoidal structure. -/ def monoidalOfHasFiniteCoproducts [HasInitial C] [HasBinaryCoproducts C] : MonoidalCategory C := letI : MonoidalCategoryStruct C := { tensorObj := fun X Y ↦ X ⨿ Y whiskerLeft := fun _ _ _ g ↦ Limits.coprod.map (𝟙 _) g whiskerRight := fun {_ _} f _ ↦ Limits.coprod.map f (𝟙 _) tensorHom := fun f g ↦ Limits.coprod.map f g tensorUnit := ⊥_ C associator := coprod.associator leftUnitor := fun P ↦ coprod.leftUnitor P rightUnitor := fun P ↦ coprod.rightUnitor P } .ofTensorHom (pentagon := coprod.pentagon) (triangle := coprod.triangle) (associator_naturality := @coprod.associator_naturality _ _ _) end namespace monoidalOfHasFiniteCoproducts variable [HasInitial C] [HasBinaryCoproducts C] attribute [local instance] monoidalOfHasFiniteCoproducts open scoped MonoidalCategory @[simp] theorem tensorObj (X Y : C) : X ⊗ Y = (X ⨿ Y) := rfl @[simp] theorem tensorHom {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : f ⊗ₘ g = Limits.coprod.map f g := rfl @[simp] theorem whiskerLeft (X : C) {Y Z : C} (f : Y ⟶ Z) : X ◁ f = Limits.coprod.map (𝟙 X) f := rfl @[simp] theorem whiskerRight {X Y : C} (f : X ⟶ Y) (Z : C) : f ▷ Z = Limits.coprod.map f (𝟙 Z) := rfl @[simp] theorem leftUnitor_hom (X : C) : (λ_ X).hom = coprod.desc (initial.to X) (𝟙 _) := rfl @[simp] theorem rightUnitor_hom (X : C) : (ρ_ X).hom = coprod.desc (𝟙 _) (initial.to X) := rfl @[simp] theorem leftUnitor_inv (X : C) : (λ_ X).inv = Limits.coprod.inr := rfl @[simp] theorem rightUnitor_inv (X : C) : (ρ_ X).inv = Limits.coprod.inl := rfl -- We don't mark this as a simp lemma, even though in many particular -- categories the right hand side will simplify significantly further. -- For now, we'll plan to create specialised simp lemmas in each particular category. theorem associator_hom (X Y Z : C) : (α_ X Y Z).hom = coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr) := rfl theorem associator_inv (X Y Z : C) : (α_ X Y Z).inv = coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) := rfl end monoidalOfHasFiniteCoproducts section attribute [local instance] monoidalOfHasFiniteCoproducts open MonoidalCategory /-- The monoidal structure coming from finite coproducts is symmetric. -/ @[simps] def symmetricOfHasFiniteCoproducts [HasInitial C] [HasBinaryCoproducts C] : SymmetricCategory C where braiding := Limits.coprod.braiding braiding_naturality_left f g := by simp braiding_naturality_right f g := by simp hexagon_forward X Y Z := by dsimp [monoidalOfHasFiniteCoproducts.associator_hom]; simp hexagon_reverse X Y Z := by dsimp [monoidalOfHasFiniteCoproducts.associator_inv]; simp symmetry X Y := by simp end namespace monoidalOfHasFiniteProducts attribute [local instance] monoidalOfHasFiniteProducts variable {C} variable {D : Type*} [Category D] (F : C ⥤ D) [HasTerminal C] [HasBinaryProducts C] [HasTerminal D] [HasBinaryProducts D] attribute [local simp] associator_hom_fst instance : F.OplaxMonoidal where η := terminalComparison F δ X Y := prodComparison F X Y δ_natural_left _ _ := by simp [prodComparison_natural] δ_natural_right _ _ := by simp [prodComparison_natural] oplax_associativity _ _ _ := by dsimp ext · dsimp simp only [Category.assoc, prod.map_fst, Category.comp_id, prodComparison_fst, ← Functor.map_comp] erw [associator_hom_fst, associator_hom_fst] simp · dsimp simp only [Category.assoc, prod.map_snd, prodComparison_snd_assoc, prodComparison_fst, ← Functor.map_comp] erw [associator_hom_snd_fst, associator_hom_snd_fst] simp · dsimp simp only [Category.assoc, prod.map_snd, prodComparison_snd_assoc, prodComparison_snd, ← Functor.map_comp] erw [associator_hom_snd_snd, associator_hom_snd_snd] simp oplax_left_unitality _ := by ext; simp [← Functor.map_comp] oplax_right_unitality _ := by ext; simp [← Functor.map_comp] open Functor.OplaxMonoidal lemma η_eq : η F = terminalComparison F := rfl lemma δ_eq (X Y : C) : δ F X Y = prodComparison F X Y := rfl variable [PreservesLimit (Functor.empty.{0} C) F] [PreservesLimitsOfShape (Discrete WalkingPair) F] instance : IsIso (η F) := by dsimp [η_eq]; infer_instance instance (X Y : C) : IsIso (δ F X Y) := by dsimp [δ_eq]; infer_instance /-- Promote a finite products preserving functor to a monoidal functor between categories equipped with the monoidal category structure given by finite products. -/ instance : F.Monoidal := .ofOplaxMonoidal F end monoidalOfHasFiniteProducts end CategoryTheory
fingroup.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice. From mathcomp Require Import fintype div path tuple bigop prime finset. From mathcomp Require Export monoid. (******************************************************************************) (* Finite groups *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file defines the main interface for finite groups: *) (* finGroupType == the structure for finite types with a group law *) (* The HB class is called FinGroup. *) (* {group gT} == type of groups with elements of type gT *) (* baseFinGroupType == the structure for finite types with a monoid law *) (* and an involutive antimorphism; finGroupType is *) (* derived from baseFinGroupType *) (* The HB class is called BaseFinGroup. *) (* FinGroupType mulVg == the finGroupType structure for an existing *) (* baseFinGroupType structure, built from a proof of *) (* the left inverse group axiom for that structure's *) (* operations *) (* [group of G] == a clone for an existing {group gT} structure on *) (* G : {set gT} (the existing structure might be for *) (* some delta-expansion of G) *) (* If gT implements finGroupType, then we can form {set gT}, the type of *) (* finite sets with elements of type gT (as finGroupType extends finType). *) (* The group law extends pointwise to {set gT}, which thus implements a sub- *) (* interface baseFinGroupType of finGroupType. To be consistent with the *) (* predType interface, this is done by coercion to FinGroup.arg_sort, an *) (* alias for FinGroup.sort. Accordingly, all pointwise group operations below *) (* have arguments of type (FinGroup.arg_sort) gT and return results of type *) (* FinGroup.sort gT. *) (* The notations below are declared in two scopes: *) (* group_scope (delimiter %g) for point operations and set constructs. *) (* Group_scope (delimiter %G) for explicit {group gT} structures. *) (* These scopes should not be opened globally, although group_scope is often *) (* opened locally in group-theory files (via Import GroupScope). *) (* As {group gT} is both a subtype and an interface structure for {set gT}, *) (* the fact that a given G : {set gT} is a group can (and usually should) be *) (* inferred by type inference with canonical structures. This means that all *) (* `group' constructions (e.g., the normaliser 'N_G(H)) actually define sets *) (* with a canonical {group gT} structure; the %G delimiter can be used to *) (* specify the actual {group gT} structure (e.g., 'N_G(H)%G). *) (* Operations on elements of a group: *) (* x * y == the group product of x and y *) (* x ^+ n == the nth power of x, i.e., x * ... * x (n times) *) (* x^-1 == the group inverse of x *) (* x ^- n == the inverse of x ^+ n (notation for (x ^+ n)^-1) *) (* 1 == the unit element *) (* x ^ y == the conjugate of x by y (i.e., y^-1 * (x * y)) *) (* [~ x, y] == the commutator of x and y (i.e., x^-1 * x ^ y) *) (* [~ x1, ..., xn] == the commutator of x1, ..., xn (associating left) *) (* \prod_(i ...) x i == the product of the x i (order-sensitive) *) (* commute x y <-> x and y commute *) (* centralises x A <-> x centralises A *) (* 'C[x] == the set of elements that commute with x *) (* 'C_G[x] == the set of elements of G that commute with x *) (* <[x]> == the cyclic subgroup generated by the element x *) (* #[x] == the order of the element x, i.e., #|<[x]>| *) (* Operations on subsets/subgroups of a finite group: *) (* H * G == {xy | x \in H, y \in G} *) (* 1 or [1] or [1 gT] == the unit group *) (* [set: gT]%G == the group of all x : gT (in Group_scope) *) (* group_set G == G contains 1 and is closed under binary product; *) (* this is the characteristic property of the *) (* {group gT} subtype of {set gT} *) (* [subg G] == the subtype, set, or group of all x \in G: this *) (* notation is defined simultaneously in %type, %g *) (* and %G scopes, and G must denote a {group gT} *) (* structure (G is in the %G scope) *) (* subg, sgval == the projection into and injection from [subg G] *) (* H^# == the set H minus the unit element *) (* repr H == some element of H if 1 \notin H != set0, else 1 *) (* (repr is defined over sets of a baseFinGroupType, *) (* so it can be used, e.g., to pick right cosets.) *) (* x *: H == left coset of H by x *) (* lcosets H G == the set of the left cosets of H by elements of G *) (* H :* x == right coset of H by x *) (* rcosets H G == the set of the right cosets of H by elements of G *) (* #|G : H| == the index of H in G, i.e., #|rcosets G H| *) (* H :^ x == the conjugate of H by x *) (* x ^: H == the conjugate class of x in H *) (* classes G == the set of all conjugate classes of G *) (* G :^: H == {G :^ x | x \in H} *) (* class_support G H == {x ^ y | x \in G, y \in H} *) (* commg_set G H == {[~ x, y] | x \in G, y \in H}; NOT the commutator! *) (* <<H>> == the subgroup generated by the set H *) (* [~: G, H] == the commmutator subgroup of G and H, i.e., *) (* <<commg_set G H>>> *) (* [~: H1, ..., Hn] == commutator subgroup of H1, ..., Hn (left assoc.) *) (* H <*> G == the subgroup generated by sets H and G (H join G) *) (* (H * G)%G == the join of G H : {group gT} (convertible, but not *) (* identical to (G <*> H)%G) *) (* (\prod_(i ...) H i)%G == the group generated by the H i *) (* {in G, centralised H} <-> G centralises H *) (* {in G, normalised H} <-> G normalises H *) (* <-> forall x, x \in G -> H :^ x = H *) (* 'N(H) == the normaliser of H *) (* 'N_G(H) == the normaliser of H in G *) (* H <| G <=> H is a normal subgroup of G *) (* 'C(H) == the centraliser of H *) (* 'C_G(H) == the centraliser of H in G *) (* gcore H G == the largest subgroup of H normalised by G *) (* If H is a subgroup of G, this is the largest *) (* normal subgroup of G contained in H). *) (* abelian H <=> H is abelian *) (* subgroups G == the set of subgroups of G, i.e., the set of all *) (* H : {group gT} such that H \subset G *) (* In the notation below G is a variable that is bound in P. *) (* [max G | P] <=> G is the largest group such that P holds *) (* [max H of G | P] <=> H is the largest group G such that P holds *) (* [max G | P & Q] := [max G | P && Q], likewise [max H of G | P & Q] *) (* [min G | P] <=> G is the smallest group such that P holds *) (* [min G | P & Q] := [min G | P && Q], likewise [min H of G | P & Q] *) (* [min H of G | P] <=> H is the smallest group G such that P holds *) (* In addition to the generic suffixes described in ssrbool.v and finset.v, *) (* we associate the following suffixes to group operations: *) (* 1 - identity element, as in group1 : 1 \in G *) (* M - multiplication, as is invMg : (x * y)^-1 = y^-1 * x^-1 *) (* Also nat multiplication, for expgM : x ^+ (m * n) = x ^+ m ^+ n *) (* D - (nat) addition, for expgD : x ^+ (m + n) = x ^+ m * x ^+ n *) (* V - inverse, as in mulgV : x * x^-1 = 1 *) (* X - exponentiation, as in conjXg : (x ^+ n) ^ y = (x ^ y) ^+ n *) (* J - conjugation, as in orderJ : #[x ^ y] = #[x] *) (* R - commutator, as in conjRg : [~ x, y] ^ z = [~ x ^ z, y ^ z] *) (* Y - join, as in centY : 'C(G <*> H) = 'C(G) :&: 'C(H) *) (* We sometimes prefix these with an `s' to indicate a set-lifted operation, *) (* e.g., conjsMg : (A * B) :^ x = A :^ x * B :^ x. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope Group_scope. Delimit Scope Group_scope with G. (* This module can be imported to open the scope for group element *) (* operations locally to a file, without exporting the Open to *) (* clients of that file (as Open would do). *) Module GroupScope. Open Scope group_scope. End GroupScope. Import GroupScope. (* These are the operation notations introduced by this file. *) Reserved Notation "[ ~ x1 , x2 , .. , xn ]" (format "'[ ' [ ~ x1 , '/' x2 , '/' .. , '/' xn ] ']'"). Reserved Notation "[ 1 gT ]" (format "[ 1 gT ]"). Reserved Notation "[ 1 ]" (format "[ 1 ]"). Reserved Notation "[ 'subg' G ]" (format "[ 'subg' G ]"). #[warning="-postfix-notation-not-level-1"] Reserved Notation "A ^#" (at level 3, format "A ^#"). Reserved Notation "A :^ x" (at level 35, right associativity). Reserved Notation "x ^: B" (at level 35, right associativity). Reserved Notation "A :^: B" (at level 35, right associativity). Reserved Notation "#| B : A |" (A at level 99, format "#| B : A |"). Reserved Notation "''N' ( A )" (format "''N' ( A )"). Reserved Notation "''N_' G ( A )" (G at level 2, format "''N_' G ( A )"). Reserved Notation "A <| B" (at level 70, no associativity). Reserved Notation "A <*> B" (at level 40, left associativity). Reserved Notation "[ ~: A1 , A2 , .. , An ]" (format "[ ~: '[' A1 , '/' A2 , '/' .. , '/' An ']' ]"). Reserved Notation "[ 'max' A 'of' G | gP ]" (format "[ '[hv' 'max' A 'of' G '/ ' | gP ']' ]"). Reserved Notation "[ 'max' G | gP ]" (format "[ '[hv' 'max' G '/ ' | gP ']' ]"). Reserved Notation "[ 'max' A 'of' G | gP & gQ ]" (format "[ '[hv' 'max' A 'of' G '/ ' | gP '/ ' & gQ ']' ]"). Reserved Notation "[ 'max' G | gP & gQ ]" (format "[ '[hv' 'max' G '/ ' | gP '/ ' & gQ ']' ]"). Reserved Notation "[ 'min' A 'of' G | gP ]" (format "[ '[hv' 'min' A 'of' G '/ ' | gP ']' ]"). Reserved Notation "[ 'min' G | gP ]" (format "[ '[hv' 'min' G '/ ' | gP ']' ]"). Reserved Notation "[ 'min' A 'of' G | gP & gQ ]" (format "[ '[hv' 'min' A 'of' G '/ ' | gP '/ ' & gQ ']' ]"). Reserved Notation "[ 'min' G | gP & gQ ]" (format "[ '[hv' 'min' G '/ ' | gP '/ ' & gQ ']' ]"). (* We split the group axiomatisation in two. We define a *) (* class of "base groups", which are basically monoids *) (* with an involutive antimorphism, from which we derive *) (* the class of groups proper. This allows us to reuse *) (* much of the group notation and algebraic axioms for *) (* group subsets, by defining a base group class on them. *) (* We use class/mixins here rather than telescopes to *) (* be able to interoperate with the type coercions. *) (* Another potential benefit (not exploited here) would *) (* be to define a class for infinite groups, which could *) (* share all of the algebraic laws. *) HB.mixin Record isMulBaseGroup G := { mulg_subdef : G -> G -> G; oneg_subdef : G; invg_subdef : G -> G; mulgA_subproof : associative mulg_subdef ; mul1g_subproof : left_id oneg_subdef mulg_subdef ; invgK_subproof : involutive invg_subdef ; invMg_subproof : {morph invg_subdef : x y / mulg_subdef x y >-> mulg_subdef y x} }. (* We want to use sort as a coercion class, both to infer *) (* argument scopes properly, and to allow groups and cosets to *) (* coerce to the base group of group subsets. *) (* However, the return type of group operations should NOT be a *) (* coercion class, since this would trump the real (head-normal) *) (* coercion class for concrete group types, thus spoiling the *) (* coercion of A * B to pred_sort in x \in A * B, or rho * tau to *) (* ffun and Funclass in (rho * tau) x, when rho tau : perm T. *) (* Therefore we define an alias of sort for argument types, and *) (* make it the default coercion FinGroup.base_type >-> Sortclass *) (* so that arguments of a functions whose parameters are of type, *) (* say, gT : finGroupType, can be coerced to the coercion class *) (* of arg_sort. Care should be taken, however, to declare the *) (* return type of functions and operators as FinGroup.sort gT *) (* rather than gT, e.g., mulg : gT -> gT -> FinGroup.sort gT. *) (* Note that since we do this here and in quotient.v for all the *) (* basic functions, the inferred return type should generally be *) (* correct. *) #[arg_sort, short(type="baseFinGroupType")] HB.structure Definition BaseFinGroup := { G of isMulBaseGroup G & Finite G }. Module BaseFinGroupExports. Bind Scope group_scope with BaseFinGroup.arg_sort. Bind Scope group_scope with BaseFinGroup.sort. End BaseFinGroupExports. HB.export BaseFinGroupExports. Module Notations. Section ElementOps. Variable T : baseFinGroupType. Notation rT := (BaseFinGroup.sort T). Definition oneg : rT := Eval unfold oneg_subdef in @oneg_subdef T. Definition mulg : T -> T -> rT := Eval unfold mulg_subdef in @mulg_subdef T. Definition invg : T -> rT := Eval unfold invg_subdef in @invg_subdef T. Definition expgn (x : T) n : rT := iterop n mulg x oneg. End ElementOps. Arguments expgn : simpl never. Notation "1" := (@oneg _) : group_scope. Notation "x1 * x2" := (mulg x1 x2) : group_scope. Notation "x ^-1" := (invg x) : group_scope. Notation "x ^+ n" := (expgn x n) : group_scope. Notation "x ^- n" := (x ^+ n)^-1 : group_scope. End Notations. HB.export Notations. HB.mixin Record BaseFinGroup_isGroup G of BaseFinGroup G := { mulVg_subproof : left_inverse (@oneg G) (@invg _) (@mulg _) }. #[short(type="finGroupType")] HB.structure Definition FinGroup := { G of BaseFinGroup_isGroup G & BaseFinGroup G }. Module FinGroupExports. Bind Scope group_scope with FinGroup.sort. End FinGroupExports. HB.export FinGroupExports. HB.factory Record isMulGroup G of Finite G := { mulg : G -> G -> G; oneg : G; invg : G -> G; mulgA : associative mulg; mul1g : left_id oneg mulg; mulVg : left_inverse oneg invg mulg; }. HB.builders Context G of isMulGroup G. Notation "1" := oneg. Infix "*" := mulg. Notation "x ^-1" := (invg x). Lemma mk_invgK : involutive invg. Proof. have mulV21 x: x^-1^-1 * 1 = x by rewrite -(mulVg x) mulgA mulVg mul1g. by move=> x; rewrite -[_ ^-1]mulV21 -(mul1g 1) mulgA !mulV21. Qed. Lemma mk_invMg : {morph invg : x y / x * y >-> y * x}. Proof. have mulgV x: x * x^-1 = 1 by rewrite -{1}[x]mk_invgK mulVg. move=> x y /=; rewrite -[y^-1 * _]mul1g -(mulVg (x * y)) -2!mulgA (mulgA y). by rewrite mulgV mul1g mulgV -(mulgV (x * y)) mulgA mulVg mul1g. Qed. HB.instance Definition _ := isMulBaseGroup.Build G mulgA mul1g mk_invgK mk_invMg. HB.instance Definition _ := BaseFinGroup_isGroup.Build G mulVg. HB.end. #[compress_coercions] HB.instance Definition _ (T : baseFinGroupType) : Finite (BaseFinGroup.arg_sort T) := Finite.class T. (* Arguments of conjg are restricted to true groups to avoid an *) (* improper interpretation of A ^ B with A and B sets, namely: *) (* {x^-1 * (y * z) | y \in A, x, z \in B} *) Definition conjg (T : finGroupType) (x y : T) := y^-1 * (x * y). Notation "x1 ^ x2" := (conjg x1 x2) : group_scope. Definition commg (T : finGroupType) (x y : T) := x^-1 * x ^ y. Notation "[ ~ x1 , x2 , .. , xn ]" := (commg .. (commg x1 x2) .. xn) : group_scope. Prenex Implicits mulg invg expgn conjg commg. Notation "\prod_ ( i <- r | P ) F" := (\big[mulg/1]_(i <- r | P%B) F%g) : group_scope. Notation "\prod_ ( i <- r ) F" := (\big[mulg/1]_(i <- r) F%g) : group_scope. Notation "\prod_ ( m <= i < n | P ) F" := (\big[mulg/1]_(m <= i < n | P%B) F%g) : group_scope. Notation "\prod_ ( m <= i < n ) F" := (\big[mulg/1]_(m <= i < n) F%g) : group_scope. Notation "\prod_ ( i | P ) F" := (\big[mulg/1]_(i | P%B) F%g) : group_scope. Notation "\prod_ i F" := (\big[mulg/1]_i F%g) : group_scope. Notation "\prod_ ( i : t | P ) F" := (\big[mulg/1]_(i : t | P%B) F%g) (only parsing) : group_scope. Notation "\prod_ ( i : t ) F" := (\big[mulg/1]_(i : t) F%g) (only parsing) : group_scope. Notation "\prod_ ( i < n | P ) F" := (\big[mulg/1]_(i < n | P%B) F%g) : group_scope. Notation "\prod_ ( i < n ) F" := (\big[mulg/1]_(i < n) F%g) : group_scope. Notation "\prod_ ( i 'in' A | P ) F" := (\big[mulg/1]_(i in A | P%B) F%g) : group_scope. Notation "\prod_ ( i 'in' A ) F" := (\big[mulg/1]_(i in A) F%g) : group_scope. Section PreGroupIdentities. Variable T : baseFinGroupType. Implicit Types x y z : T. Local Notation mulgT := (@mulg T). Lemma mulgA : associative mulgT. Proof. exact: mulgA_subproof. Qed. Lemma mul1g : left_id 1 mulgT. Proof. exact: mul1g_subproof. Qed. Lemma invgK : @involutive T invg. Proof. exact: invgK_subproof. Qed. Lemma invMg x y : (x * y)^-1 = y^-1 * x^-1. Proof. exact: invMg_subproof. Qed. Lemma invg_inj : @injective T T invg. Proof. exact: can_inj invgK. Qed. Lemma eq_invg_sym x y : (x^-1 == y) = (x == y^-1). Proof. by apply: (inv_eq invgK). Qed. Lemma invg1 : 1^-1 = 1 :> T. Proof. by apply: invg_inj; rewrite -{1}[1^-1]mul1g invMg invgK mul1g. Qed. Lemma eq_invg1 x : (x^-1 == 1) = (x == 1). Proof. by rewrite eq_invg_sym invg1. Qed. Lemma mulg1 : right_id 1 mulgT. Proof. by move=> x; apply: invg_inj; rewrite invMg invg1 mul1g. Qed. HB.instance Definition _ := Monoid.isLaw.Build T 1 mulgT mulgA mul1g mulg1. Lemma expgnE x n : x ^+ n = iterop n mulg x 1. Proof. by []. Qed. Lemma expg0 x : x ^+ 0 = 1. Proof. by []. Qed. Lemma expg1 x : x ^+ 1 = x. Proof. by []. Qed. Lemma expgS x n : x ^+ n.+1 = x * x ^+ n. Proof. by case: n => //; rewrite mulg1. Qed. Lemma expg1n n : 1 ^+ n = 1 :> T. Proof. by elim: n => // n IHn; rewrite expgS mul1g. Qed. Lemma expgD x n m : x ^+ (n + m) = x ^+ n * x ^+ m. Proof. by elim: n => [|n IHn]; rewrite ?mul1g // !expgS IHn mulgA. Qed. Lemma expgSr x n : x ^+ n.+1 = x ^+ n * x. Proof. by rewrite -addn1 expgD expg1. Qed. Lemma expgM x n m : x ^+ (n * m) = x ^+ n ^+ m. Proof. elim: m => [|m IHm]; first by rewrite muln0 expg0. by rewrite mulnS expgD IHm expgS. Qed. Lemma expgAC x m n : x ^+ m ^+ n = x ^+ n ^+ m. Proof. by rewrite -!expgM mulnC. Qed. Definition commute x y := x * y = y * x. Lemma commute_refl x : commute x x. Proof. by []. Qed. Lemma commute_sym x y : commute x y -> commute y x. Proof. by []. Qed. Lemma commute1 x : commute x 1. Proof. by rewrite /commute mulg1 mul1g. Qed. Lemma commuteM x y z : commute x y -> commute x z -> commute x (y * z). Proof. by move=> cxy cxz; rewrite /commute -mulgA -cxz !mulgA cxy. Qed. Lemma commuteX x y n : commute x y -> commute x (y ^+ n). Proof. by move=> cxy; case: n; [apply: commute1 | elim=> // n; apply: commuteM]. Qed. Lemma commuteX2 x y m n : commute x y -> commute (x ^+ m) (y ^+ n). Proof. by move=> cxy; apply/commuteX/commute_sym/commuteX. Qed. Lemma expgVn x n : x^-1 ^+ n = x ^- n. Proof. by elim: n => [|n IHn]; rewrite ?invg1 // expgSr expgS invMg IHn. Qed. Lemma expgMn x y n : commute x y -> (x * y) ^+ n = x ^+ n * y ^+ n. Proof. move=> cxy; elim: n => [|n IHn]; first by rewrite mulg1. by rewrite !expgS IHn -mulgA (mulgA y) (commuteX _ (commute_sym cxy)) !mulgA. Qed. End PreGroupIdentities. #[global] Hint Resolve commute1 : core. Arguments invg_inj {T} [x1 x2]. Prenex Implicits commute invgK. Section GroupIdentities. Variable T : finGroupType. Implicit Types x y z : T. Local Notation mulgT := (@mulg T). Lemma mulVg : left_inverse 1 invg mulgT. Proof. exact: mulVg_subproof. Qed. Lemma mulgV : right_inverse 1 invg mulgT. Proof. by move=> x; rewrite -{1}(invgK x) mulVg. Qed. Lemma mulKg : left_loop invg mulgT. Proof. by move=> x y; rewrite mulgA mulVg mul1g. Qed. Lemma mulKVg : rev_left_loop invg mulgT. Proof. by move=> x y; rewrite mulgA mulgV mul1g. Qed. Lemma mulgI : right_injective mulgT. Proof. by move=> x; apply: can_inj (mulKg x). Qed. Lemma mulgK : right_loop invg mulgT. Proof. by move=> x y; rewrite -mulgA mulgV mulg1. Qed. Lemma mulgKV : rev_right_loop invg mulgT. Proof. by move=> x y; rewrite -mulgA mulVg mulg1. Qed. Lemma mulIg : left_injective mulgT. Proof. by move=> x; apply: can_inj (mulgK x). Qed. Lemma eq_invg_mul x y : (x^-1 == y :> T) = (x * y == 1 :> T). Proof. by rewrite -(inj_eq (@mulgI x)) mulgV eq_sym. Qed. Lemma eq_mulgV1 x y : (x == y) = (x * y^-1 == 1 :> T). Proof. by rewrite -(inj_eq invg_inj) eq_invg_mul. Qed. Lemma eq_mulVg1 x y : (x == y) = (x^-1 * y == 1 :> T). Proof. by rewrite -eq_invg_mul invgK. Qed. Lemma commuteV x y : commute x y -> commute x y^-1. Proof. by move=> cxy; apply: (@mulIg y); rewrite mulgKV -mulgA cxy mulKg. Qed. Lemma conjgE x y : x ^ y = y^-1 * (x * y). Proof. by []. Qed. Lemma conjgC x y : x * y = y * x ^ y. Proof. by rewrite mulKVg. Qed. Lemma conjgCV x y : x * y = y ^ x^-1 * x. Proof. by rewrite -mulgA mulgKV invgK. Qed. Lemma conjg1 x : x ^ 1 = x. Proof. by rewrite conjgE commute1 mulKg. Qed. Lemma conj1g x : 1 ^ x = 1. Proof. by rewrite conjgE mul1g mulVg. Qed. Lemma conjMg x y z : (x * y) ^ z = x ^ z * y ^ z. Proof. by rewrite !conjgE !mulgA mulgK. Qed. Lemma conjgM x y z : x ^ (y * z) = (x ^ y) ^ z. Proof. by rewrite !conjgE invMg !mulgA. Qed. Lemma conjVg x y : x^-1 ^ y = (x ^ y)^-1. Proof. by rewrite !conjgE !invMg invgK mulgA. Qed. Lemma conjJg x y z : (x ^ y) ^ z = (x ^ z) ^ y ^ z. Proof. by rewrite 2!conjMg conjVg. Qed. Lemma conjXg x y n : (x ^+ n) ^ y = (x ^ y) ^+ n. Proof. by elim: n => [|n IHn]; rewrite ?conj1g // !expgS conjMg IHn. Qed. Lemma conjgK : @right_loop T T invg conjg. Proof. by move=> y x; rewrite -conjgM mulgV conjg1. Qed. Lemma conjgKV : @rev_right_loop T T invg conjg. Proof. by move=> y x; rewrite -conjgM mulVg conjg1. Qed. Lemma conjg_inj : @left_injective T T T conjg. Proof. by move=> y; apply: can_inj (conjgK y). Qed. Lemma conjg_eq1 x y : (x ^ y == 1) = (x == 1). Proof. by rewrite (canF_eq (conjgK _)) conj1g. Qed. Lemma conjg_prod I r (P : pred I) F z : (\prod_(i <- r | P i) F i) ^ z = \prod_(i <- r | P i) (F i ^ z). Proof. by apply: (big_morph (conjg^~ z)) => [x y|]; rewrite ?conj1g ?conjMg. Qed. Lemma commgEl x y : [~ x, y] = x^-1 * x ^ y. Proof. by []. Qed. Lemma commgEr x y : [~ x, y] = y^-1 ^ x * y. Proof. by rewrite -!mulgA. Qed. Lemma commgC x y : x * y = y * x * [~ x, y]. Proof. by rewrite -mulgA !mulKVg. Qed. Lemma commgCV x y : x * y = [~ x^-1, y^-1] * (y * x). Proof. by rewrite commgEl !mulgA !invgK !mulgKV. Qed. Lemma conjRg x y z : [~ x, y] ^ z = [~ x ^ z, y ^ z]. Proof. by rewrite !conjMg !conjVg. Qed. Lemma invg_comm x y : [~ x, y]^-1 = [~ y, x]. Proof. by rewrite commgEr conjVg invMg invgK. Qed. Lemma commgP x y : reflect (commute x y) ([~ x, y] == 1 :> T). Proof. by rewrite [[~ x, y]]mulgA -invMg -eq_mulVg1 eq_sym; apply: eqP. Qed. Lemma conjg_fixP x y : reflect (x ^ y = x) ([~ x, y] == 1 :> T). Proof. by rewrite -eq_mulVg1 eq_sym; apply: eqP. Qed. Lemma commg1_sym x y : ([~ x, y] == 1 :> T) = ([~ y, x] == 1 :> T). Proof. by rewrite -invg_comm (inv_eq invgK) invg1. Qed. Lemma commg1 x : [~ x, 1] = 1. Proof. exact/eqP/commgP. Qed. Lemma comm1g x : [~ 1, x] = 1. Proof. by rewrite -invg_comm commg1 invg1. Qed. Lemma commgg x : [~ x, x] = 1. Proof. exact/eqP/commgP. Qed. Lemma commgXg x n : [~ x, x ^+ n] = 1. Proof. exact/eqP/commgP/commuteX. Qed. Lemma commgVg x : [~ x, x^-1] = 1. Proof. exact/eqP/commgP/commuteV. Qed. Lemma commgXVg x n : [~ x, x ^- n] = 1. Proof. exact/eqP/commgP/commuteV/commuteX. Qed. (* Other commg identities should slot in here. *) End GroupIdentities. #[global] Hint Rewrite mulg1 @mul1g invg1 @mulVg mulgV (@invgK) mulgK mulgKV @invMg @mulgA : gsimpl. Ltac gsimpl := autorewrite with gsimpl; try done. Definition gsimp := (@mulg1, @mul1g, (@invg1, @invgK), (@mulgV, @mulVg)). Definition gnorm := (gsimp, (@mulgK, @mulgKV, (@mulgA, @invMg))). Arguments mulgI [T]. Arguments mulIg [T]. Arguments conjg_inj {T} x [x1 x2]. Arguments commgP {T x y}. Arguments conjg_fixP {T x y}. Section Repr. (* Plucking a set representative. *) Variable gT : baseFinGroupType. Implicit Type A : {set gT}. Definition repr A := if 1 \in A then 1 else odflt 1 [pick x in A]. Lemma mem_repr A x : x \in A -> repr A \in A. Proof. by rewrite /repr; case: ifP => // _; case: pickP => // A0; rewrite [x \in A]A0. Qed. Lemma card_mem_repr A : #|A| > 0 -> repr A \in A. Proof. by rewrite lt0n => /existsP[x]; apply: mem_repr. Qed. Lemma repr_set1 x : repr [set x] = x. Proof. by apply/set1P/card_mem_repr; rewrite cards1. Qed. Lemma repr_set0 : repr set0 = 1. Proof. by rewrite /repr; case: pickP => [x|_] /[!inE]. Qed. End Repr. Arguments mem_repr [gT A]. Section BaseSetMulDef. (* We only assume a baseFinGroupType to allow this construct to be iterated. *) Variable gT : baseFinGroupType. Implicit Types A B : {set gT}. (* Set-lifted group operations. *) Definition set_mulg A B := mulg @2: (A, B). Definition set_invg A := invg @^-1: A. (* The pre-group structure of group subsets. *) Lemma set_mul1g : left_id [set 1] set_mulg. Proof. move=> A; apply/setP=> y; apply/imset2P/idP=> [[_ x /set1P-> Ax ->] | Ay]. by rewrite mul1g. by exists (1 : gT) y; rewrite ?(set11, mul1g). Qed. Lemma set_mulgA : associative set_mulg. Proof. move=> A B C; apply/setP=> y. apply/imset2P/imset2P=> [[x1 z Ax1 /imset2P[x2 x3 Bx2 Cx3 ->] ->]| [z x3]]. by exists (x1 * x2) x3; rewrite ?mulgA //; apply/imset2P; exists x1 x2. case/imset2P=> x1 x2 Ax1 Bx2 -> Cx3 ->. by exists x1 (x2 * x3); rewrite ?mulgA //; apply/imset2P; exists x2 x3. Qed. Lemma set_invgK : involutive set_invg. Proof. by move=> A; apply/setP=> x; rewrite !inE invgK. Qed. Lemma set_invgM : {morph set_invg : A B / set_mulg A B >-> set_mulg B A}. Proof. move=> A B; apply/setP=> z; rewrite inE. apply/imset2P/imset2P=> [[x y Ax By /(canRL invgK)->] | [y x]]. by exists y^-1 x^-1; rewrite ?invMg // inE invgK. by rewrite !inE => By1 Ax1 ->; exists x^-1 y^-1; rewrite ?invMg. Qed. HB.instance Definition set_base_group := isMulBaseGroup.Build (set_type gT) set_mulgA set_mul1g set_invgK set_invgM. HB.instance Definition _ : isMulBaseGroup {set gT} := set_base_group. End BaseSetMulDef. (* Time to open the bag of dirty tricks. When we define groups down below *) (* as a subtype of {set gT}, we need them to be able to coerce to sets in *) (* both set-style contexts (x \in G) and monoid-style contexts (G * H), *) (* and we need the coercion function to be EXACTLY the structure *) (* projection in BOTH cases -- otherwise the canonical unification breaks.*) (* Alas, Coq doesn't let us use the same coercion function twice, even *) (* when the targets are convertible. Our workaround (ab)uses the module *) (* system to declare two different identity coercions on an alias class. *) Module GroupSet. Definition sort (gT : baseFinGroupType) := {set gT}. End GroupSet. Identity Coercion GroupSet_of_sort : GroupSet.sort >-> set_of. Module Type GroupSetBaseGroupSig. Definition sort (gT : baseFinGroupType) := BaseFinGroup.arg_sort {set gT}. End GroupSetBaseGroupSig. Module MakeGroupSetBaseGroup (Gset_base : GroupSetBaseGroupSig). Identity Coercion of_sort : Gset_base.sort >-> BaseFinGroup.arg_sort. End MakeGroupSetBaseGroup. Module Export GroupSetBaseGroup := MakeGroupSetBaseGroup GroupSet. HB.instance Definition _ gT : Finite (GroupSet.sort gT) := Finite.class {set gT}. Section GroupSetMulDef. (* Some of these constructs could be defined on a baseFinGroupType. *) (* We restrict them to proper finGroupType because we only develop *) (* the theory for that case. *) Variable gT : finGroupType. Implicit Types A B : {set gT}. Implicit Type x y : gT. Definition lcoset A x := mulg x @: A. Definition rcoset A x := mulg^~ x @: A. Definition lcosets A B := lcoset A @: B. Definition rcosets A B := rcoset A @: B. Definition indexg B A := #|rcosets A B|. Definition conjugate A x := conjg^~ x @: A. Definition conjugates A B := conjugate A @: B. Definition class x B := conjg x @: B. Definition classes A := class^~ A @: A. Definition class_support A B := conjg @2: (A, B). Definition commg_set A B := commg @2: (A, B). (* These will only be used later, but are defined here so that we can *) (* keep all the Notation together. *) Definition normaliser A := [set x | conjugate A x \subset A]. Definition centraliser A := \bigcap_(x in A) normaliser [set x]. Definition abelian A := A \subset centraliser A. Definition normal A B := (A \subset B) && (B \subset normaliser A). (* "normalised" and "centralise[s|d]" are intended to be used with *) (* the {in ...} form, as in abelian below. *) Definition normalised A := forall x, conjugate A x = A. Definition centralises x A := forall y, y \in A -> commute x y. Definition centralised A := forall x, centralises x A. End GroupSetMulDef. Arguments lcoset _ _%_g _%_g. Arguments rcoset _ _%_g _%_g. Arguments rcosets _ _%_g _%_g. Arguments lcosets _ _%_g _%_g. Arguments indexg _ _%_g _%_g. Arguments conjugate _ _%_g _%_g. Arguments conjugates _ _%_g _%_g. Arguments class _ _%_g _%_g. Arguments classes _ _%_g. Arguments class_support _ _%_g _%_g. Arguments commg_set _ _%_g _%_g. Arguments normaliser _ _%_g. Arguments centraliser _ _%_g. Arguments abelian _ _%_g. Arguments normal _ _%_g _%_g. Arguments normalised _ _%_g. Arguments centralises _ _%_g _%_g. Arguments centralised _ _%_g. Notation "[ 1 gT ]" := (1 : {set gT}) : group_scope. Notation "[ 1 ]" := [1 FinGroup.sort _] : group_scope. Notation "A ^#" := (A :\ 1) : group_scope. Notation "x *: A" := ([set x%g] * A) : group_scope. Notation "A :* x" := (A * [set x%g]) : group_scope. Notation "A :^ x" := (conjugate A x) : group_scope. Notation "x ^: B" := (class x B) : group_scope. Notation "A :^: B" := (conjugates A B) : group_scope. Notation "#| B : A |" := (indexg B A) : group_scope. (* No notation for lcoset and rcoset, which are to be used mostly *) (* in curried form; x *: B and A :* 1 denote singleton products, *) (* so we can use mulgA, mulg1, etc, on, say, A :* 1 * B :* x. *) (* No notation for the set commutator generator set commg_set. *) Notation "''N' ( A )" := (normaliser A) : group_scope. Notation "''N_' G ( A )" := (G%g :&: 'N(A)) : group_scope. Notation "A <| B" := (normal A B) : group_scope. Notation "''C' ( A )" := (centraliser A) : group_scope. Notation "''C_' G ( A )" := (G%g :&: 'C(A)) : group_scope. Notation "''C_' ( G ) ( A )" := 'C_G(A) (only parsing) : group_scope. Notation "''C' [ x ]" := 'N([set x%g]) : group_scope. Notation "''C_' G [ x ]" := 'N_G([set x%g]) : group_scope. Notation "''C_' ( G ) [ x ]" := 'C_G[x] (only parsing) : group_scope. Prenex Implicits repr lcoset rcoset lcosets rcosets normal. Prenex Implicits conjugate conjugates class classes class_support. Prenex Implicits commg_set normalised centralised abelian. Section BaseSetMulProp. (* Properties of the purely multiplicative structure. *) Variable gT : baseFinGroupType. Implicit Types A B C D : {set gT}. Implicit Type x y z : gT. (* Set product. We already have all the pregroup identities, so we *) (* only need to add the monotonicity rules. *) Lemma mulsgP A B x : reflect (imset2_spec mulg (mem A) (fun _ => mem B) x) (x \in A * B). Proof. exact: imset2P. Qed. Lemma mem_mulg A B x y : x \in A -> y \in B -> x * y \in A * B. Proof. by move=> Ax By; apply/mulsgP; exists x y. Qed. Lemma prodsgP (I : finType) (P : pred I) (A : I -> {set gT}) x : reflect (exists2 c, forall i, P i -> c i \in A i & x = \prod_(i | P i) c i) (x \in \prod_(i | P i) A i). Proof. have [r big_r [Ur mem_r] _] := big_enumP P. pose inA c := all (fun i => c i \in A i); rewrite -big_r; set piAx := x \in _. suffices{big_r} IHr: reflect (exists2 c, inA c r & x = \prod_(i <- r) c i) piAx. apply: (iffP IHr) => -[c inAc ->]; do [exists c; last by rewrite big_r]. by move=> i Pi; rewrite (allP inAc) ?mem_r. by apply/allP=> i; rewrite mem_r => /inAc. elim: {P mem_r}r x @piAx Ur => /= [x _ | i r IHr x /andP[r'i /IHr{}IHr]]. by rewrite unlock; apply: (iffP set1P) => [-> | [] //]; exists (fun=> x). rewrite big_cons; apply: (iffP idP) => [|[c /andP[Aci Ac] ->]]; last first. by rewrite big_cons mem_mulg //; apply/IHr=> //; exists c. case/mulsgP=> c_i _ Ac_i /IHr[c /allP-inAcr ->] ->{x}. exists [eta c with i |-> c_i]; rewrite /= ?big_cons eqxx ?Ac_i. by apply/allP=> j rj; rewrite /= ifN ?(memPn r'i) ?inAcr. by congr (_ * _); apply: eq_big_seq => j rj; rewrite ifN ?(memPn r'i). Qed. Lemma mem_prodg (I : finType) (P : pred I) (A : I -> {set gT}) c : (forall i, P i -> c i \in A i) -> \prod_(i | P i) c i \in \prod_(i | P i) A i. Proof. by move=> Ac; apply/prodsgP; exists c. Qed. Lemma mulSg A B C : A \subset B -> A * C \subset B * C. Proof. exact: imset2Sl. Qed. Lemma mulgS A B C : B \subset C -> A * B \subset A * C. Proof. exact: imset2Sr. Qed. Lemma mulgSS A B C D : A \subset B -> C \subset D -> A * C \subset B * D. Proof. exact: imset2S. Qed. Lemma mulg_subl A B : 1 \in B -> A \subset A * B. Proof. by move=> B1; rewrite -{1}(mulg1 A) mulgS ?sub1set. Qed. Lemma mulg_subr A B : 1 \in A -> B \subset A * B. Proof. by move=> A1; rewrite -{1}(mul1g B) mulSg ?sub1set. Qed. Lemma mulUg A B C : (A :|: B) * C = (A * C) :|: (B * C). Proof. exact: imset2Ul. Qed. Lemma mulgU A B C : A * (B :|: C) = (A * B) :|: (A * C). Proof. exact: imset2Ur. Qed. (* Set (pointwise) inverse. *) Lemma invUg A B : (A :|: B)^-1 = A^-1 :|: B^-1. Proof. exact: preimsetU. Qed. Lemma invIg A B : (A :&: B)^-1 = A^-1 :&: B^-1. Proof. exact: preimsetI. Qed. Lemma invDg A B : (A :\: B)^-1 = A^-1 :\: B^-1. Proof. exact: preimsetD. Qed. Lemma invCg A : (~: A)^-1 = ~: A^-1. Proof. exact: preimsetC. Qed. Lemma invSg A B : (A^-1 \subset B^-1) = (A \subset B). Proof. by rewrite !(sameP setIidPl eqP) -invIg (inj_eq invg_inj). Qed. Lemma mem_invg x A : (x \in A^-1) = (x^-1 \in A). Proof. by rewrite inE. Qed. Lemma memV_invg x A : (x^-1 \in A^-1) = (x \in A). Proof. by rewrite inE invgK. Qed. Lemma card_invg A : #|A^-1| = #|A|. Proof. exact/card_preimset/invg_inj. Qed. (* Product with singletons. *) Lemma set1gE : 1 = [set 1] :> {set gT}. Proof. by []. Qed. Lemma set1gP x : reflect (x = 1) (x \in [1 gT]). Proof. exact: set1P. Qed. Lemma mulg_set1 x y : [set x] :* y = [set x * y]. Proof. by rewrite [_ * _]imset2_set1l imset_set1. Qed. Lemma invg_set1 x : [set x]^-1 = [set x^-1]. Proof. by apply/setP=> y; rewrite !inE inv_eq //; apply: invgK. Qed. End BaseSetMulProp. Arguments set1gP {gT x}. Arguments mulsgP {gT A B x}. Arguments prodsgP {gT I P A x}. Section GroupSetMulProp. (* Constructs that need a finGroupType *) Variable gT : finGroupType. Implicit Types A B C D : {set gT}. Implicit Type x y z : gT. (* Left cosets. *) Lemma lcosetE A x : lcoset A x = x *: A. Proof. by rewrite [_ * _]imset2_set1l. Qed. Lemma card_lcoset A x : #|x *: A| = #|A|. Proof. by rewrite -lcosetE (card_imset _ (mulgI _)). Qed. Lemma mem_lcoset A x y : (y \in x *: A) = (x^-1 * y \in A). Proof. by rewrite -lcosetE [_ x](can_imset_pre _ (mulKg _)) inE. Qed. Lemma lcosetP A x y : reflect (exists2 a, a \in A & y = x * a) (y \in x *: A). Proof. by rewrite -lcosetE; apply: imsetP. Qed. Lemma lcosetsP A B C : reflect (exists2 x, x \in B & C = x *: A) (C \in lcosets A B). Proof. by apply: (iffP imsetP) => [] [x Bx ->]; exists x; rewrite ?lcosetE. Qed. Lemma lcosetM A x y : (x * y) *: A = x *: (y *: A). Proof. by rewrite -mulg_set1 mulgA. Qed. Lemma lcoset1 A : 1 *: A = A. Proof. exact: mul1g. Qed. Lemma lcosetK : left_loop invg (fun x A => x *: A). Proof. by move=> x A; rewrite -lcosetM mulVg mul1g. Qed. Lemma lcosetKV : rev_left_loop invg (fun x A => x *: A). Proof. by move=> x A; rewrite -lcosetM mulgV mul1g. Qed. Lemma lcoset_inj : right_injective (fun x A => x *: A). Proof. by move=> x; apply: can_inj (lcosetK x). Qed. Lemma lcosetS x A B : (x *: A \subset x *: B) = (A \subset B). Proof. apply/idP/idP=> sAB; last exact: mulgS. by rewrite -(lcosetK x A) -(lcosetK x B) mulgS. Qed. Lemma sub_lcoset x A B : (A \subset x *: B) = (x^-1 *: A \subset B). Proof. by rewrite -(lcosetS x^-1) lcosetK. Qed. Lemma sub_lcosetV x A B : (A \subset x^-1 *: B) = (x *: A \subset B). Proof. by rewrite sub_lcoset invgK. Qed. (* Right cosets. *) Lemma rcosetE A x : rcoset A x = A :* x. Proof. by rewrite [_ * _]imset2_set1r. Qed. Lemma card_rcoset A x : #|A :* x| = #|A|. Proof. by rewrite -rcosetE (card_imset _ (mulIg _)). Qed. Lemma mem_rcoset A x y : (y \in A :* x) = (y * x^-1 \in A). Proof. by rewrite -rcosetE [_ x](can_imset_pre A (mulgK _)) inE. Qed. Lemma rcosetP A x y : reflect (exists2 a, a \in A & y = a * x) (y \in A :* x). Proof. by rewrite -rcosetE; apply: imsetP. Qed. Lemma rcosetsP A B C : reflect (exists2 x, x \in B & C = A :* x) (C \in rcosets A B). Proof. by apply: (iffP imsetP) => [] [x Bx ->]; exists x; rewrite ?rcosetE. Qed. Lemma rcosetM A x y : A :* (x * y) = A :* x :* y. Proof. by rewrite -mulg_set1 mulgA. Qed. Lemma rcoset1 A : A :* 1 = A. Proof. exact: mulg1. Qed. Lemma rcosetK : right_loop invg (fun A x => A :* x). Proof. by move=> x A; rewrite -rcosetM mulgV mulg1. Qed. Lemma rcosetKV : rev_right_loop invg (fun A x => A :* x). Proof. by move=> x A; rewrite -rcosetM mulVg mulg1. Qed. Lemma rcoset_inj : left_injective (fun A x => A :* x). Proof. by move=> x; apply: can_inj (rcosetK x). Qed. Lemma rcosetS x A B : (A :* x \subset B :* x) = (A \subset B). Proof. apply/idP/idP=> sAB; last exact: mulSg. by rewrite -(rcosetK x A) -(rcosetK x B) mulSg. Qed. Lemma sub_rcoset x A B : (A \subset B :* x) = (A :* x ^-1 \subset B). Proof. by rewrite -(rcosetS x^-1) rcosetK. Qed. Lemma sub_rcosetV x A B : (A \subset B :* x^-1) = (A :* x \subset B). Proof. by rewrite sub_rcoset invgK. Qed. (* Inverse maps lcosets to rcosets *) Lemma invg_lcosets A B : (lcosets A B)^-1 = rcosets A^-1 B^-1. Proof. rewrite /A^-1/= -![_^-1](can_imset_pre _ invgK) -[RHS]imset_comp -imset_comp. by apply: eq_imset => x /=; rewrite lcosetE rcosetE invMg invg_set1. Qed. (* Conjugates. *) Lemma conjg_preim A x : A :^ x = (conjg^~ x^-1) @^-1: A. Proof. exact: can_imset_pre (conjgK _). Qed. Lemma mem_conjg A x y : (y \in A :^ x) = (y ^ x^-1 \in A). Proof. by rewrite conjg_preim inE. Qed. Lemma mem_conjgV A x y : (y \in A :^ x^-1) = (y ^ x \in A). Proof. by rewrite mem_conjg invgK. Qed. Lemma memJ_conjg A x y : (y ^ x \in A :^ x) = (y \in A). Proof. by rewrite mem_conjg conjgK. Qed. Lemma conjsgE A x : A :^ x = x^-1 *: (A :* x). Proof. by apply/setP=> y; rewrite mem_lcoset mem_rcoset -mulgA mem_conjg. Qed. Lemma conjsg1 A : A :^ 1 = A. Proof. by rewrite conjsgE invg1 mul1g mulg1. Qed. Lemma conjsgM A x y : A :^ (x * y) = (A :^ x) :^ y. Proof. by rewrite !conjsgE invMg -!mulg_set1 !mulgA. Qed. Lemma conjsgK : @right_loop _ gT invg conjugate. Proof. by move=> x A; rewrite -conjsgM mulgV conjsg1. Qed. Lemma conjsgKV : @rev_right_loop _ gT invg conjugate. Proof. by move=> x A; rewrite -conjsgM mulVg conjsg1. Qed. Lemma conjsg_inj : @left_injective _ gT _ conjugate. Proof. by move=> x; apply: can_inj (conjsgK x). Qed. Lemma cardJg A x : #|A :^ x| = #|A|. Proof. by rewrite (card_imset _ (conjg_inj x)). Qed. Lemma conjSg A B x : (A :^ x \subset B :^ x) = (A \subset B). Proof. by rewrite !conjsgE lcosetS rcosetS. Qed. Lemma properJ A B x : (A :^ x \proper B :^ x) = (A \proper B). Proof. by rewrite /proper !conjSg. Qed. Lemma sub_conjg A B x : (A :^ x \subset B) = (A \subset B :^ x^-1). Proof. by rewrite -(conjSg A _ x) conjsgKV. Qed. Lemma sub_conjgV A B x : (A :^ x^-1 \subset B) = (A \subset B :^ x). Proof. by rewrite -(conjSg _ B x) conjsgKV. Qed. Lemma conjg_set1 x y : [set x] :^ y = [set x ^ y]. Proof. by rewrite [_ :^ _]imset_set1. Qed. Lemma conjs1g x : 1 :^ x = 1. Proof. by rewrite conjg_set1 conj1g. Qed. Lemma conjsg_eq1 A x : (A :^ x == 1%g) = (A == 1%g). Proof. by rewrite (canF_eq (conjsgK x)) conjs1g. Qed. Lemma conjsMg A B x : (A * B) :^ x = A :^ x * B :^ x. Proof. by rewrite !conjsgE !mulgA rcosetK. Qed. Lemma conjIg A B x : (A :&: B) :^ x = A :^ x :&: B :^ x. Proof. by rewrite !conjg_preim preimsetI. Qed. Lemma conj0g x : set0 :^ x = set0. Proof. exact: imset0. Qed. Lemma conjTg x : [set: gT] :^ x = [set: gT]. Proof. by rewrite conjg_preim preimsetT. Qed. Lemma bigcapJ I r (P : pred I) (B : I -> {set gT}) x : \bigcap_(i <- r | P i) (B i :^ x) = (\bigcap_(i <- r | P i) B i) :^ x. Proof. by rewrite (big_endo (conjugate^~ x)) => // [B1 B2|]; rewrite (conjTg, conjIg). Qed. Lemma conjUg A B x : (A :|: B) :^ x = A :^ x :|: B :^ x. Proof. by rewrite !conjg_preim preimsetU. Qed. Lemma bigcupJ I r (P : pred I) (B : I -> {set gT}) x : \bigcup_(i <- r | P i) (B i :^ x) = (\bigcup_(i <- r | P i) B i) :^ x. Proof. rewrite (big_endo (conjugate^~ x)) => // [B1 B2|]; first by rewrite conjUg. exact: imset0. Qed. Lemma conjCg A x : (~: A) :^ x = ~: A :^ x. Proof. by rewrite !conjg_preim preimsetC. Qed. Lemma conjDg A B x : (A :\: B) :^ x = A :^ x :\: B :^ x. Proof. by rewrite !setDE !(conjCg, conjIg). Qed. Lemma conjD1g A x : A^# :^ x = (A :^ x)^#. Proof. by rewrite conjDg conjs1g. Qed. (* Classes; not much for now. *) Lemma memJ_class x y A : y \in A -> x ^ y \in x ^: A. Proof. exact: imset_f. Qed. Lemma classS x A B : A \subset B -> x ^: A \subset x ^: B. Proof. exact: imsetS. Qed. Lemma class_set1 x y : x ^: [set y] = [set x ^ y]. Proof. exact: imset_set1. Qed. Lemma class1g x A : x \in A -> 1 ^: A = 1. Proof. move=> Ax; apply/setP=> y. by apply/imsetP/set1P=> [[a Aa]|] ->; last exists x; rewrite ?conj1g. Qed. Lemma classVg x A : x^-1 ^: A = (x ^: A)^-1. Proof. apply/setP=> xy; rewrite inE; apply/imsetP/imsetP=> [] [y Ay def_xy]. by rewrite def_xy conjVg invgK; exists y. by rewrite -[xy]invgK def_xy -conjVg; exists y. Qed. Lemma mem_classes x A : x \in A -> x ^: A \in classes A. Proof. exact: imset_f. Qed. Lemma memJ_class_support A B x y : x \in A -> y \in B -> x ^ y \in class_support A B. Proof. by move=> Ax By; apply: imset2_f. Qed. Lemma class_supportM A B C : class_support A (B * C) = class_support (class_support A B) C. Proof. apply/setP=> x; apply/imset2P/imset2P=> [[a y Aa] | [y c]]. case/mulsgP=> b c Bb Cc -> ->{x y}. by exists (a ^ b) c; rewrite ?(imset2_f, conjgM). case/imset2P=> a b Aa Bb -> Cc ->{x y}. by exists a (b * c); rewrite ?(mem_mulg, conjgM). Qed. Lemma class_support_set1l A x : class_support [set x] A = x ^: A. Proof. exact: imset2_set1l. Qed. Lemma class_support_set1r A x : class_support A [set x] = A :^ x. Proof. exact: imset2_set1r. Qed. Lemma classM x A B : x ^: (A * B) = class_support (x ^: A) B. Proof. by rewrite -!class_support_set1l class_supportM. Qed. Lemma class_lcoset x y A : x ^: (y *: A) = (x ^ y) ^: A. Proof. by rewrite classM class_set1 class_support_set1l. Qed. Lemma class_rcoset x A y : x ^: (A :* y) = (x ^: A) :^ y. Proof. by rewrite -class_support_set1r classM. Qed. (* Conjugate set. *) Lemma conjugatesS A B C : B \subset C -> A :^: B \subset A :^: C. Proof. exact: imsetS. Qed. Lemma conjugates_set1 A x : A :^: [set x] = [set A :^ x]. Proof. exact: imset_set1. Qed. Lemma conjugates_conj A x B : (A :^ x) :^: B = A :^: (x *: B). Proof. rewrite /conjugates [x *: B]imset2_set1l -imset_comp. by apply: eq_imset => y /=; rewrite conjsgM. Qed. (* Class support. *) Lemma class_supportEl A B : class_support A B = \bigcup_(x in A) x ^: B. Proof. exact: curry_imset2l. Qed. Lemma class_supportEr A B : class_support A B = \bigcup_(x in B) A :^ x. Proof. exact: curry_imset2r. Qed. (* Groups (at last!) *) Definition group_set A := (1 \in A) && (A * A \subset A). Lemma group_setP A : reflect (1 \in A /\ {in A & A, forall x y, x * y \in A}) (group_set A). Proof. apply: (iffP andP) => [] [A1 AM]; split=> {A1}//. by move=> x y Ax Ay; apply: (subsetP AM); rewrite mem_mulg. by apply/subsetP=> _ /mulsgP[x y Ax Ay ->]; apply: AM. Qed. Structure group_type : Type := Group { gval :> GroupSet.sort gT; _ : group_set gval }. Definition group_of : predArgType := group_type. Local Notation groupT := group_of. Identity Coercion type_of_group : group_of >-> group_type. HB.instance Definition _ := [isSub for gval]. #[hnf] HB.instance Definition _ := [Finite of group_type by <:]. (* No predType or baseFinGroupType structures, as these would hide the *) (* group-to-set coercion and thus spoil unification. *) HB.instance Definition _ := SubFinite.copy groupT group_type. Definition group (A : {set gT}) gA : groupT := @Group A gA. Definition clone_group G := let: Group _ gP := G return {type of Group for G} -> groupT in fun k => k gP. Lemma group_inj : injective gval. Proof. exact: val_inj. Qed. Lemma groupP (G : groupT) : group_set G. Proof. by case: G. Qed. Lemma congr_group (H K : groupT) : H = K -> H :=: K. Proof. exact: congr1. Qed. Lemma isgroupP A : reflect (exists G : groupT, A = G) (group_set A). Proof. by apply: (iffP idP) => [gA | [[B gB] -> //]]; exists (Group gA). Qed. Lemma group_set_one : group_set 1. Proof. by rewrite /group_set set11 mulg1 subxx. Qed. Canonical one_group := group group_set_one. Canonical set1_group := @group [set 1] group_set_one. Lemma group_setT : group_set (setTfor gT). Proof. by apply/group_setP; split=> [|x y _ _]; rewrite inE. Qed. Canonical setT_group := group group_setT. End GroupSetMulProp. Arguments group_of gT%_type. Arguments lcosetP {gT A x y}. Arguments lcosetsP {gT A B C}. Arguments rcosetP {gT A x y}. Arguments rcosetsP {gT A B C}. Arguments group_setP {gT A}. Arguments setT_group gT%_type. Prenex Implicits group_set mulsgP set1gP. Notation "{ 'group' gT }" := (group_of gT) (format "{ 'group' gT }") : type_scope. Notation "[ 'group' 'of' G ]" := (clone_group (@group _ G)) (format "[ 'group' 'of' G ]") : form_scope. Bind Scope Group_scope with group_type. Bind Scope Group_scope with group_of. Notation "1" := (one_group _) : Group_scope. Notation "[ 1 gT ]" := (1%G : {group gT}) : Group_scope. Notation "[ 'set' : gT ]" := (setT_group gT) : Group_scope. (* These definitions come early so we can establish the Notation. *) HB.lock Definition generated (gT : finGroupType) (A : {set gT}) := \bigcap_(G : {group gT} | A \subset G) G. Canonical generated_unlockable := Unlockable generated.unlock. Definition gcore (gT : finGroupType) (A B : {set gT}) := \bigcap_(x in B) A :^ x. Definition joing (gT : finGroupType) (A B : {set gT}) := generated (A :|: B). Definition commutator (gT : finGroupType) (A B : {set gT}) := generated (commg_set A B). Definition cycle (gT : finGroupType) (x : gT) := generated [set x]. Definition order (gT : finGroupType) (x : gT) := #|cycle x|. Arguments commutator _ _%_g _%_g. Arguments joing _ _%_g _%_g. Arguments generated _ _%_g. (* Helper notation for defining new groups that need a bespoke finGroupType. *) (* The actual group for such a type (say, my_gT) will be the full group, *) (* i.e., [set: my_gT] or [set: my_gT]%G, but Coq will not recognize *) (* specific notation for these because of the coercions inserted during type *) (* inference, unless they are defined as [set: gsort my_gT] using the *) (* Notation below. *) Notation gsort gT := (BaseFinGroup.arg_sort gT%type) (only parsing). Notation "<< A >>" := (generated A) : group_scope. Notation "<[ x ] >" := (cycle x) : group_scope. Notation "#[ x ]" := (order x) : group_scope. Notation "A <*> B" := (joing A B) : group_scope. Notation "[ ~: A1 , A2 , .. , An ]" := (commutator .. (commutator A1 A2) .. An) : group_scope. Prenex Implicits order cycle gcore. Section GroupProp. Variable gT : finGroupType. Notation sT := {set gT}. Implicit Types A B C D : sT. Implicit Types x y z : gT. Implicit Types G H K : {group gT}. Section OneGroup. Variable G : {group gT}. Lemma valG : val G = G. Proof. by []. Qed. (* Non-triviality. *) Lemma group1 : 1 \in G. Proof. by case/group_setP: (valP G). Qed. #[local] Hint Resolve group1 : core. Lemma group1_contra x : x \notin G -> x != 1. Proof. by apply: contraNneq => ->. Qed. Lemma sub1G : [1 gT] \subset G. Proof. by rewrite sub1set. Qed. Lemma subG1 : (G \subset [1]) = (G :==: 1). Proof. by rewrite eqEsubset sub1G andbT. Qed. Lemma setI1g : 1 :&: G = 1. Proof. exact: (setIidPl sub1G). Qed. Lemma setIg1 : G :&: 1 = 1. Proof. exact: (setIidPr sub1G). Qed. Lemma subG1_contra H : G \subset H -> G :!=: 1 -> H :!=: 1. Proof. by move=> sGH; rewrite -subG1; apply: contraNneq => <-. Qed. Lemma repr_group : repr G = 1. Proof. by rewrite /repr group1. Qed. Lemma cardG_gt0 : 0 < #|G|. Proof. by rewrite lt0n; apply/existsP; exists (1 : gT). Qed. Lemma indexg_gt0 A : 0 < #|G : A|. Proof. rewrite lt0n; apply/existsP; exists A. by rewrite -{2}[A]mulg1 -rcosetE; apply: imset_f. Qed. Lemma trivgP : reflect (G :=: 1) (G \subset [1]). Proof. by rewrite subG1; apply: eqP. Qed. Lemma trivGP : reflect (G = 1%G) (G \subset [1]). Proof. by rewrite subG1; apply: eqP. Qed. Lemma proper1G : ([1] \proper G) = (G :!=: 1). Proof. by rewrite properEneq sub1G andbT eq_sym. Qed. Lemma in_one_group x : (x \in 1%G) = (x == 1). Proof. by rewrite -[x \in _]/(x \in [set 1]) !inE. Qed. Definition inE := (in_one_group, inE). Lemma trivgPn : reflect (exists2 x, x \in G & x != 1) (G :!=: 1). Proof. rewrite -subG1. by apply: (iffP subsetPn) => [] [x Gx x1]; exists x; rewrite ?inE in x1 *. Qed. Lemma trivg_card_le1 : (G :==: 1) = (#|G| <= 1). Proof. by rewrite eq_sym eqEcard cards1 sub1G. Qed. Lemma trivg_card1 : (G :==: 1) = (#|G| == 1%N). Proof. by rewrite trivg_card_le1 eqn_leq cardG_gt0 andbT. Qed. Lemma cardG_gt1 : (#|G| > 1) = (G :!=: 1). Proof. by rewrite trivg_card_le1 ltnNge. Qed. Lemma card_le1_trivg : #|G| <= 1 -> G :=: 1. Proof. by rewrite -trivg_card_le1; move/eqP. Qed. Lemma card1_trivg : #|G| = 1%N -> G :=: 1. Proof. by move=> G1; rewrite card_le1_trivg ?G1. Qed. (* Inclusion and product. *) Lemma mulG_subl A : A \subset A * G. Proof. exact: mulg_subl group1. Qed. Lemma mulG_subr A : A \subset ((G : {set gT}) * A ). Proof. exact: mulg_subr group1. Qed. Lemma mulGid : (G : {set gT}) * G = G. Proof. by apply/eqP; rewrite eqEsubset mulG_subr andbT; case/andP: (valP G). Qed. Lemma mulGS A B : (G * A \subset G * B) = (A \subset G * B). Proof. apply/idP/idP; first exact: subset_trans (mulG_subr A). by move/(mulgS G); rewrite mulgA mulGid. Qed. Lemma mulSG A B : (A * G \subset B * G) = (A \subset B * G). Proof. apply/idP/idP; first exact: subset_trans (mulG_subl A). by move/(mulSg G); rewrite -mulgA mulGid. Qed. Lemma mul_subG A B : A \subset G -> B \subset G -> A * B \subset G. Proof. by move=> sAG sBG; rewrite -mulGid mulgSS. Qed. Lemma prod_subG (I : Type) (r : seq I) (P : {pred I}) (F : I -> {set gT}) : (forall i, P i -> F i \subset G) -> \prod_(i <- r | P i) F i \subset G. Proof. move=> subFG; elim/big_rec: _ => [|/= i A /subFG]; first by rewrite sub1set. exact: mul_subG. Qed. (* Membership lemmas *) Lemma groupM x y : x \in G -> y \in G -> x * y \in G. Proof. by case/group_setP: (valP G) x y. Qed. Lemma groupX x n : x \in G -> x ^+ n \in G. Proof. by move=> Gx; elim: n => [|n IHn]; rewrite ?group1 // expgS groupM. Qed. Lemma groupVr x : x \in G -> x^-1 \in G. Proof. move=> Gx; rewrite -(mul1g x^-1) -mem_rcoset ((G :* x =P G) _) //. by rewrite eqEcard card_rcoset leqnn mul_subG ?sub1set. Qed. Lemma groupVl x : x^-1 \in G -> x \in G. Proof. by move/groupVr; rewrite invgK. Qed. Lemma groupV x : (x^-1 \in G) = (x \in G). Proof. by apply/idP/idP; [apply: groupVl | apply: groupVr]. Qed. Lemma groupMl x y : x \in G -> (x * y \in G) = (y \in G). Proof. move=> Gx; apply/idP/idP=> [Gxy|]; last exact: groupM. by rewrite -(mulKg x y) groupM ?groupVr. Qed. Lemma groupMr x y : x \in G -> (y * x \in G) = (y \in G). Proof. by move=> Gx; rewrite -[_ \in G]groupV invMg groupMl groupV. Qed. Definition in_group := (group1, groupV, (groupMl, groupX)). Lemma groupJ x y : x \in G -> y \in G -> x ^ y \in G. Proof. by move=> Gx Gy; rewrite !in_group. Qed. Lemma groupJr x y : y \in G -> (x ^ y \in G) = (x \in G). Proof. by move=> Gy; rewrite groupMl (groupMr, groupV). Qed. Lemma groupR x y : x \in G -> y \in G -> [~ x, y] \in G. Proof. by move=> Gx Gy; rewrite !in_group. Qed. Lemma group_prod I r (P : pred I) F : (forall i, P i -> F i \in G) -> \prod_(i <- r | P i) F i \in G. Proof. by move=> G_P; elim/big_ind: _ => //; apply: groupM. Qed. (* Inverse is an anti-morphism. *) Lemma invGid : G^-1 = G. Proof. by apply/setP=> x; rewrite inE groupV. Qed. Lemma inv_subG A : (A^-1 \subset G) = (A \subset G). Proof. by rewrite -{1}invGid invSg. Qed. Lemma invg_lcoset x : (x *: G)^-1 = G :* x^-1. Proof. by rewrite invMg invGid invg_set1. Qed. Lemma invg_rcoset x : (G :* x)^-1 = x^-1 *: G. Proof. by rewrite invMg invGid invg_set1. Qed. Lemma memV_lcosetV x y : (y^-1 \in x^-1 *: G) = (y \in G :* x). Proof. by rewrite -invg_rcoset memV_invg. Qed. Lemma memV_rcosetV x y : (y^-1 \in G :* x^-1) = (y \in x *: G). Proof. by rewrite -invg_lcoset memV_invg. Qed. (* Product idempotence *) Lemma mulSgGid A x : x \in A -> A \subset G -> A * G = G. Proof. move=> Ax sAG; apply/eqP; rewrite eqEsubset -{2}mulGid mulSg //=. apply/subsetP=> y Gy; rewrite -(mulKVg x y) mem_mulg // groupMr // groupV. exact: (subsetP sAG). Qed. Lemma mulGSgid A x : x \in A -> A \subset G -> G * A = G. Proof. rewrite -memV_invg -invSg invGid => Ax sAG. by apply: invg_inj; rewrite invMg invGid (mulSgGid Ax). Qed. (* Left cosets *) Lemma lcoset_refl x : x \in x *: G. Proof. by rewrite mem_lcoset mulVg group1. Qed. Lemma lcoset_sym x y : (x \in y *: G) = (y \in x *: G). Proof. by rewrite !mem_lcoset -groupV invMg invgK. Qed. Lemma lcoset_eqP {x y} : reflect (x *: G = y *: G) (x \in y *: G). Proof. suffices <-: (x *: G == y *: G) = (x \in y *: G) by apply: eqP. by rewrite eqEsubset !mulSG !sub1set lcoset_sym andbb. Qed. Lemma lcoset_transl x y z : x \in y *: G -> (x \in z *: G) = (y \in z *: G). Proof. by move=> Gyx; rewrite -2!(lcoset_sym z) (lcoset_eqP Gyx). Qed. Lemma lcoset_trans x y z : x \in y *: G -> y \in z *: G -> x \in z *: G. Proof. by move/lcoset_transl->. Qed. Lemma lcoset_id x : x \in G -> x *: G = G. Proof. by move=> Gx; rewrite (lcoset_eqP (_ : x \in 1 *: G)) mul1g. Qed. (* Right cosets, with an elimination form for repr. *) Lemma rcoset_refl x : x \in G :* x. Proof. by rewrite mem_rcoset mulgV group1. Qed. Lemma rcoset_sym x y : (x \in G :* y) = (y \in G :* x). Proof. by rewrite -!memV_lcosetV lcoset_sym. Qed. Lemma rcoset_eqP {x y} : reflect (G :* x = G :* y) (x \in G :* y). Proof. suffices <-: (G :* x == G :* y) = (x \in G :* y) by apply: eqP. by rewrite eqEsubset !mulGS !sub1set rcoset_sym andbb. Qed. Lemma rcoset_transl x y z : x \in G :* y -> (x \in G :* z) = (y \in G :* z). Proof. by move=> Gyx; rewrite -2!(rcoset_sym z) (rcoset_eqP Gyx). Qed. Lemma rcoset_trans x y z : x \in G :* y -> y \in G :* z -> x \in G :* z. Proof. by move/rcoset_transl->. Qed. Lemma rcoset_id x : x \in G -> G :* x = G. Proof. by move=> Gx; rewrite (rcoset_eqP (_ : x \in G :* 1)) mulg1. Qed. (* Elimination form. *) Variant rcoset_repr_spec x : gT -> Type := RcosetReprSpec g : g \in G -> rcoset_repr_spec x (g * x). Lemma mem_repr_rcoset x : repr (G :* x) \in G :* x. Proof. exact: mem_repr (rcoset_refl x). Qed. (* This form sometimes fails because ssreflect 1.1 delegates matching to the *) (* (weaker) primitive Coq algorithm for general (co)inductive type families. *) Lemma repr_rcosetP x : rcoset_repr_spec x (repr (G :* x)). Proof. by rewrite -[repr _](mulgKV x); split; rewrite -mem_rcoset mem_repr_rcoset. Qed. Lemma rcoset_repr x : G :* (repr (G :* x)) = G :* x. Proof. exact/rcoset_eqP/mem_repr_rcoset. Qed. (* Coset spaces. *) Lemma mem_rcosets A x : (G :* x \in rcosets G A) = (x \in G * A). Proof. apply/rcosetsP/mulsgP=> [[a Aa /rcoset_eqP/rcosetP[g]] | ]; first by exists g a. by case=> g a Gg Aa ->{x}; exists a; rewrite // rcosetM rcoset_id. Qed. Lemma mem_lcosets A x : (x *: G \in lcosets G A) = (x \in A * G). Proof. rewrite -[LHS]memV_invg invg_lcoset invg_lcosets. by rewrite -[RHS]memV_invg invMg invGid mem_rcosets. Qed. (* Conjugates. *) Lemma group_setJ A x : group_set (A :^ x) = group_set A. Proof. by rewrite /group_set mem_conjg conj1g -conjsMg conjSg. Qed. Lemma group_set_conjG x : group_set (G :^ x). Proof. by rewrite group_setJ groupP. Qed. Canonical conjG_group x := group (group_set_conjG x). Lemma conjGid : {in G, normalised G}. Proof. by move=> x Gx; apply/setP=> y; rewrite mem_conjg groupJr ?groupV. Qed. Lemma conj_subG x A : x \in G -> A \subset G -> A :^ x \subset G. Proof. by move=> Gx sAG; rewrite -(conjGid Gx) conjSg. Qed. (* Classes *) Lemma class1G : 1 ^: G = 1. Proof. exact: class1g group1. Qed. Lemma classes1 : [1] \in classes G. Proof. by rewrite -class1G mem_classes. Qed. Lemma classGidl x y : y \in G -> (x ^ y) ^: G = x ^: G. Proof. by move=> Gy; rewrite -class_lcoset lcoset_id. Qed. Lemma classGidr x : {in G, normalised (x ^: G)}. Proof. by move=> y Gy /=; rewrite -class_rcoset rcoset_id. Qed. Lemma class_refl x : x \in x ^: G. Proof. by apply/imsetP; exists 1; rewrite ?conjg1. Qed. #[local] Hint Resolve class_refl : core. Lemma class_eqP x y : reflect (x ^: G = y ^: G) (x \in y ^: G). Proof. by apply: (iffP idP) => [/imsetP[z Gz ->] | <-]; rewrite ?class_refl ?classGidl. Qed. Lemma class_sym x y : (x \in y ^: G) = (y \in x ^: G). Proof. by apply/idP/idP=> /class_eqP->. Qed. Lemma class_transl x y z : x \in y ^: G -> (x \in z ^: G) = (y \in z ^: G). Proof. by rewrite -!(class_sym z) => /class_eqP->. Qed. Lemma class_trans x y z : x \in y ^: G -> y \in z ^: G -> x \in z ^: G. Proof. by move/class_transl->. Qed. Lemma repr_class x : {y | y \in G & repr (x ^: G) = x ^ y}. Proof. set z := repr _; have: #|[set y in G | z == x ^ y]| > 0. have: z \in x ^: G by apply: (mem_repr x). by case/imsetP=> y Gy ->; rewrite (cardD1 y) inE Gy eqxx. by move/card_mem_repr; move: (repr _) => y /setIdP[Gy /eqP]; exists y. Qed. Lemma classG_eq1 x : (x ^: G == 1) = (x == 1). Proof. apply/eqP/eqP=> [xG1 | ->]; last exact: class1G. by have:= class_refl x; rewrite xG1 => /set1P. Qed. Lemma class_subG x A : x \in G -> A \subset G -> x ^: A \subset G. Proof. move=> Gx sAG; apply/subsetP=> _ /imsetP[y Ay ->]. by rewrite groupJ // (subsetP sAG). Qed. Lemma repr_classesP xG : reflect (repr xG \in G /\ xG = repr xG ^: G) (xG \in classes G). Proof. apply: (iffP imsetP) => [[x Gx ->] | []]; last by exists (repr xG). by have [y Gy ->] := repr_class x; rewrite classGidl ?groupJ. Qed. Lemma mem_repr_classes xG : xG \in classes G -> repr xG \in xG. Proof. by case/repr_classesP=> _ {2}->; apply: class_refl. Qed. Lemma classes_gt0 : 0 < #|classes G|. Proof. by rewrite (cardsD1 1) classes1. Qed. Lemma classes_gt1 : (#|classes G| > 1) = (G :!=: 1). Proof. rewrite (cardsD1 1) classes1 ltnS lt0n cards_eq0. apply/set0Pn/trivgPn=> [[xG /setD1P[nt_xG]] | [x Gx ntx]]. by case/imsetP=> x Gx def_xG; rewrite def_xG classG_eq1 in nt_xG; exists x. by exists (x ^: G); rewrite !inE classG_eq1 ntx; apply: imset_f. Qed. Lemma mem_class_support A x : x \in A -> x \in class_support A G. Proof. by move=> Ax; rewrite -[x]conjg1 memJ_class_support. Qed. Lemma class_supportGidl A x : x \in G -> class_support (A :^ x) G = class_support A G. Proof. by move=> Gx; rewrite -class_support_set1r -class_supportM lcoset_id. Qed. Lemma class_supportGidr A : {in G, normalised (class_support A G)}. Proof. by move=> x Gx /=; rewrite -class_support_set1r -class_supportM rcoset_id. Qed. Lemma class_support_subG A : A \subset G -> class_support A G \subset G. Proof. by move=> sAG; rewrite class_supportEr; apply/bigcupsP=> x Gx; apply: conj_subG. Qed. Lemma sub_class_support A : A \subset class_support A G. Proof. by rewrite class_supportEr (bigcup_max 1) ?conjsg1. Qed. Lemma class_support_id : class_support G G = G. Proof. by apply/eqP; rewrite eqEsubset sub_class_support class_support_subG. Qed. Lemma class_supportD1 A : (class_support A G)^# = cover (A^# :^: G). Proof. rewrite cover_imset class_supportEr setDE big_distrl /=. by apply: eq_bigr => x _; rewrite -setDE conjD1g. Qed. (* Subgroup Type construction. *) (* We only expect to use this for abstract groups, so we don't project *) (* the argument to a set. *) Inductive subg_of : predArgType := Subg x & x \in G. Definition sgval u := let: Subg x _ := u in x. Definition subg_of_Sub := Eval hnf in [isSub for sgval]. HB.instance Definition _ := subg_of_Sub. #[hnf] HB.instance Definition _ := [Finite of subg_of by <:]. Lemma subgP u : sgval u \in G. Proof. exact: valP. Qed. Lemma subg_inj : injective sgval. Proof. exact: val_inj. Qed. Lemma congr_subg u v : u = v -> sgval u = sgval v. Proof. exact: congr1. Qed. Definition subg_one := Subg group1. Definition subg_inv u := Subg (groupVr (subgP u)). Definition subg_mul u v := Subg (groupM (subgP u) (subgP v)). Lemma subg_oneP : left_id subg_one subg_mul. Proof. by move=> u; apply: val_inj; apply: mul1g. Qed. Lemma subg_invP : left_inverse subg_one subg_inv subg_mul. Proof. by move=> u; apply: val_inj; apply: mulVg. Qed. Lemma subg_mulP : associative subg_mul. Proof. by move=> u v w; apply: val_inj; apply: mulgA. Qed. HB.instance Definition _ := isMulGroup.Build subg_of subg_mulP subg_oneP subg_invP. Lemma sgvalM : {in setT &, {morph sgval : x y / x * y}}. Proof. by []. Qed. Lemma valgM : {in setT &, {morph val : x y / (x : subg_of) * y >-> x * y}}. Proof. by []. Qed. Definition subg : gT -> subg_of := insubd (1 : subg_of). Lemma subgK x : x \in G -> val (subg x) = x. Proof. by move=> Gx; rewrite insubdK. Qed. Lemma sgvalK : cancel sgval subg. Proof. by case=> x Gx; apply: val_inj; apply: subgK. Qed. Lemma subg_default x : (x \in G) = false -> val (subg x) = 1. Proof. by move=> Gx; rewrite val_insubd Gx. Qed. Lemma subgM : {in G &, {morph subg : x y / x * y}}. Proof. by move=> x y Gx Gy; apply: val_inj; rewrite /= !subgK ?groupM. Qed. End OneGroup. #[local] Hint Resolve group1 : core. Lemma groupD1_inj G H : G^# = H^# -> G :=: H. Proof. by move/(congr1 (setU 1)); rewrite !setD1K. Qed. Lemma invMG G H : (G * H)^-1 = H * G. Proof. by rewrite invMg !invGid. Qed. Lemma mulSGid G H : H \subset G -> H * G = G. Proof. exact: mulSgGid (group1 H). Qed. Lemma mulGSid G H : H \subset G -> G * H = G. Proof. exact: mulGSgid (group1 H). Qed. Lemma mulGidPl G H : reflect (G * H = G) (H \subset G). Proof. by apply: (iffP idP) => [|<-]; [apply: mulGSid | apply: mulG_subr]. Qed. Lemma mulGidPr G H : reflect (G * H = H) (G \subset H). Proof. by apply: (iffP idP) => [|<-]; [apply: mulSGid | apply: mulG_subl]. Qed. Lemma comm_group_setP G H : reflect (commute G H) (group_set (G * H)). Proof. rewrite /group_set (subsetP (mulG_subl _ _)) ?group1 // andbC. have <-: #|G * H| <= #|H * G| by rewrite -invMG card_invg. by rewrite -mulgA mulGS mulgA mulSG -eqEcard eq_sym; apply: eqP. Qed. Lemma card_lcosets G H : #|lcosets H G| = #|G : H|. Proof. by rewrite -card_invg invg_lcosets !invGid. Qed. (* Group Modularity equations *) Lemma group_modl A B G : A \subset G -> A * (B :&: G) = A * B :&: G. Proof. move=> sAG; apply/eqP; rewrite eqEsubset subsetI mulgS ?subsetIl //. rewrite -{2}mulGid mulgSS ?subsetIr //. apply/subsetP => _ /setIP[/mulsgP[a b Aa Bb ->] Gab]. by rewrite mem_mulg // inE Bb -(groupMl _ (subsetP sAG _ Aa)). Qed. Lemma group_modr A B G : B \subset G -> (G :&: A) * B = G :&: A * B. Proof. move=> sBG; apply: invg_inj; rewrite !(invMg, invIg) invGid !(setIC G). by rewrite group_modl // -invGid invSg. Qed. End GroupProp. #[global] Hint Extern 0 (is_true (1%g \in _)) => apply: group1 : core. #[global] Hint Extern 0 (is_true (0 < #|_|)) => apply: cardG_gt0 : core. #[global] Hint Extern 0 (is_true (0 < #|_ : _|)) => apply: indexg_gt0 : core. Notation "G :^ x" := (conjG_group G x) : Group_scope. Notation "[ 'subg' G ]" := (subg_of G) : type_scope. Notation "[ 'subg' G ]" := [set: subg_of G] : group_scope. Notation "[ 'subg' G ]" := [set: subg_of G]%G : Group_scope. Prenex Implicits subg sgval subg_of. Bind Scope group_scope with subg_of. Arguments subgK {gT G}. Arguments sgvalK {gT G}. Arguments subg_inj {gT G} [u1 u2] eq_u12 : rename. Arguments trivgP {gT G}. Arguments trivGP {gT G}. Arguments lcoset_eqP {gT G x y}. Arguments rcoset_eqP {gT G x y}. Arguments mulGidPl {gT G H}. Arguments mulGidPr {gT G H}. Arguments comm_group_setP {gT G H}. Arguments class_eqP {gT G x y}. Arguments repr_classesP {gT G xG}. Section GroupInter. Variable gT : finGroupType. Implicit Types A B : {set gT}. Implicit Types G H : {group gT}. Lemma group_setI G H : group_set (G :&: H). Proof. apply/group_setP; split=> [|x y]; rewrite !inE ?group1 //. by case/andP=> Gx Hx; rewrite !groupMl. Qed. Canonical setI_group G H := group (group_setI G H). Section Nary. Variables (I : finType) (P : pred I) (F : I -> {group gT}). Lemma group_set_bigcap : group_set (\bigcap_(i | P i) F i). Proof. by elim/big_rec: _ => [|i G _ gG]; rewrite -1?(insubdK 1%G gG) groupP. Qed. Canonical bigcap_group := group group_set_bigcap. End Nary. Lemma group_set_generated (A : {set gT}) : group_set <<A>>. Proof. by rewrite unlock group_set_bigcap. Qed. Canonical generated_group A := group (group_set_generated A). Canonical gcore_group G A : {group _} := Eval hnf in [group of gcore G A]. Canonical commutator_group A B : {group _} := Eval hnf in [group of [~: A, B]]. Canonical joing_group A B : {group _} := Eval hnf in [group of A <*> B]. Canonical cycle_group x : {group _} := Eval hnf in [group of <[x]>]. Definition joinG G H := joing_group G H. Definition subgroups A := [set G : {group gT} | G \subset A]. Lemma order_gt0 (x : gT) : 0 < #[x]. Proof. exact: cardG_gt0. Qed. End GroupInter. #[global] Hint Resolve order_gt0 : core. Arguments generated_group _ _%_g. Arguments joing_group _ _%_g _%_g. Arguments subgroups _ _%_g. Notation "G :&: H" := (setI_group G H) : Group_scope. Notation "<< A >>" := (generated_group A) : Group_scope. Notation "<[ x ] >" := (cycle_group x) : Group_scope. Notation "[ ~: A1 , A2 , .. , An ]" := (commutator_group .. (commutator_group A1 A2) .. An) : Group_scope. Notation "A <*> B" := (joing_group A B) : Group_scope. Notation "G * H" := (joinG G H) : Group_scope. Prenex Implicits joinG subgroups. Notation "\prod_ ( i <- r | P ) F" := (\big[joinG/1%G]_(i <- r | P%B) F%G) : Group_scope. Notation "\prod_ ( i <- r ) F" := (\big[joinG/1%G]_(i <- r) F%G) : Group_scope. Notation "\prod_ ( m <= i < n | P ) F" := (\big[joinG/1%G]_(m <= i < n | P%B) F%G) : Group_scope. Notation "\prod_ ( m <= i < n ) F" := (\big[joinG/1%G]_(m <= i < n) F%G) : Group_scope. Notation "\prod_ ( i | P ) F" := (\big[joinG/1%G]_(i | P%B) F%G) : Group_scope. Notation "\prod_ i F" := (\big[joinG/1%G]_i F%G) : Group_scope. Notation "\prod_ ( i : t | P ) F" := (\big[joinG/1%G]_(i : t | P%B) F%G) (only parsing) : Group_scope. Notation "\prod_ ( i : t ) F" := (\big[joinG/1%G]_(i : t) F%G) (only parsing) : Group_scope. Notation "\prod_ ( i < n | P ) F" := (\big[joinG/1%G]_(i < n | P%B) F%G) : Group_scope. Notation "\prod_ ( i < n ) F" := (\big[joinG/1%G]_(i < n) F%G) : Group_scope. Notation "\prod_ ( i 'in' A | P ) F" := (\big[joinG/1%G]_(i in A | P%B) F%G) : Group_scope. Notation "\prod_ ( i 'in' A ) F" := (\big[joinG/1%G]_(i in A) F%G) : Group_scope. Section Lagrange. Variable gT : finGroupType. Implicit Types G H K : {group gT}. Lemma LagrangeI G H : (#|G :&: H| * #|G : H|)%N = #|G|. Proof. rewrite -[#|G|]sum1_card (partition_big_imset (rcoset H)) /=. rewrite mulnC -sum_nat_const; apply: eq_bigr => _ /rcosetsP[x Gx ->]. rewrite -(card_rcoset _ x) -sum1_card; apply: eq_bigl => y. by rewrite rcosetE (sameP eqP rcoset_eqP) group_modr ?sub1set // !inE. Qed. Lemma divgI G H : #|G| %/ #|G :&: H| = #|G : H|. Proof. by rewrite -(LagrangeI G H) mulKn ?cardG_gt0. Qed. Lemma divg_index G H : #|G| %/ #|G : H| = #|G :&: H|. Proof. by rewrite -(LagrangeI G H) mulnK. Qed. Lemma dvdn_indexg G H : #|G : H| %| #|G|. Proof. by rewrite -(LagrangeI G H) dvdn_mull. Qed. Theorem Lagrange G H : H \subset G -> (#|H| * #|G : H|)%N = #|G|. Proof. by move/setIidPr=> sHG; rewrite -{1}sHG LagrangeI. Qed. Lemma cardSg G H : H \subset G -> #|H| %| #|G|. Proof. by move/Lagrange <-; rewrite dvdn_mulr. Qed. Lemma lognSg p G H : G \subset H -> logn p #|G| <= logn p #|H|. Proof. by move=> sGH; rewrite dvdn_leq_log ?cardSg. Qed. Lemma piSg G H : G \subset H -> {subset \pi(gval G) <= \pi(gval H)}. Proof. move=> sGH p; rewrite !mem_primes !cardG_gt0 => /and3P[-> _ pG]. exact: dvdn_trans (cardSg sGH). Qed. Lemma divgS G H : H \subset G -> #|G| %/ #|H| = #|G : H|. Proof. by move/Lagrange <-; rewrite mulKn. Qed. Lemma divg_indexS G H : H \subset G -> #|G| %/ #|G : H| = #|H|. Proof. by move/Lagrange <-; rewrite mulnK. Qed. Lemma coprimeSg G H p : H \subset G -> coprime #|G| p -> coprime #|H| p. Proof. by move=> sHG; apply: coprime_dvdl (cardSg sHG). Qed. Lemma coprimegS G H p : H \subset G -> coprime p #|G| -> coprime p #|H|. Proof. by move=> sHG; apply: coprime_dvdr (cardSg sHG). Qed. Lemma indexJg G H x : #|G :^ x : H :^ x| = #|G : H|. Proof. by rewrite -!divgI -conjIg !cardJg. Qed. Lemma indexgg G : #|G : G| = 1%N. Proof. by rewrite -divgS // divnn cardG_gt0. Qed. Lemma rcosets_id G : rcosets G G = [set G : {set gT}]. Proof. apply/esym/eqP; rewrite eqEcard sub1set [#|_|]indexgg cards1 andbT. by apply/rcosetsP; exists 1; rewrite ?mulg1. Qed. Lemma Lagrange_index G H K : H \subset G -> K \subset H -> (#|G : H| * #|H : K|)%N = #|G : K|. Proof. move=> sHG sKH; apply/eqP; rewrite mulnC -(eqn_pmul2l (cardG_gt0 K)). by rewrite mulnA !Lagrange // (subset_trans sKH). Qed. Lemma indexgI G H : #|G : G :&: H| = #|G : H|. Proof. by rewrite -[RHS]divgI divgS ?subsetIl. Qed. Lemma indexgS G H K : H \subset K -> #|G : K| %| #|G : H|. Proof. move=> sHK; rewrite -(@dvdn_pmul2l #|G :&: K|) ?cardG_gt0 // LagrangeI. by rewrite -(Lagrange (setIS G sHK)) mulnAC LagrangeI dvdn_mulr. Qed. Lemma indexSg G H K : H \subset K -> K \subset G -> #|K : H| %| #|G : H|. Proof. move=> sHK sKG; rewrite -(@dvdn_pmul2l #|H|) ?cardG_gt0 //. by rewrite !Lagrange ?(cardSg, subset_trans sHK). Qed. Lemma indexg_eq1 G H : (#|G : H| == 1%N) = (G \subset H). Proof. rewrite eqn_leq -(leq_pmul2l (cardG_gt0 (G :&: H))) LagrangeI muln1. by rewrite indexg_gt0 andbT (sameP setIidPl eqP) eqEcard subsetIl. Qed. Lemma indexg_gt1 G H : (#|G : H| > 1) = ~~ (G \subset H). Proof. by rewrite -indexg_eq1 eqn_leq indexg_gt0 andbT -ltnNge. Qed. Lemma index1g G H : H \subset G -> #|G : H| = 1%N -> H :=: G. Proof. by move=> sHG iHG; apply/eqP; rewrite eqEsubset sHG -indexg_eq1 iHG. Qed. Lemma indexg1 G : #|G : 1| = #|G|. Proof. by rewrite -divgS ?sub1G // cards1 divn1. Qed. Lemma indexMg G A : #|G * A : G| = #|A : G|. Proof. apply/eq_card/setP/eqP; rewrite eqEsubset andbC imsetS ?mulG_subr //. by apply/subsetP=> _ /rcosetsP[x GAx ->]; rewrite mem_rcosets. Qed. Lemma rcosets_partition_mul G H : partition (rcosets H G) (H * G). Proof. set HG := H * G; have sGHG: {subset G <= HG} by apply/subsetP/mulG_subr. have defHx x: x \in HG -> [set y in HG | rcoset H x == rcoset H y] = H :* x. move=> HGx; apply/setP=> y; rewrite inE !rcosetE (sameP eqP rcoset_eqP). by rewrite rcoset_sym; apply/andb_idl/subsetP; rewrite mulGS sub1set. have:= preim_partitionP (rcoset H) HG; congr (partition _ _); apply/setP=> Hx. apply/imsetP/idP=> [[x HGx ->] | ]; first by rewrite defHx // mem_rcosets. by case/rcosetsP=> x /sGHG-HGx ->; exists x; rewrite ?defHx. Qed. Lemma rcosets_partition G H : H \subset G -> partition (rcosets H G) G. Proof. by move=> sHG; have:= rcosets_partition_mul G H; rewrite mulSGid. Qed. Lemma LagrangeMl G H : (#|G| * #|H : G|)%N = #|G * H|. Proof. rewrite mulnC -(card_uniform_partition _ (rcosets_partition_mul H G)) //. by move=> _ /rcosetsP[x Hx ->]; rewrite card_rcoset. Qed. Lemma LagrangeMr G H : (#|G : H| * #|H|)%N = #|G * H|. Proof. by rewrite mulnC LagrangeMl -card_invg invMg !invGid. Qed. Lemma mul_cardG G H : (#|G| * #|H| = #|G * H|%g * #|G :&: H|)%N. Proof. by rewrite -LagrangeMr -(LagrangeI G H) -mulnA mulnC. Qed. Lemma dvdn_cardMg G H : #|G * H| %| #|G| * #|H|. Proof. by rewrite mul_cardG dvdn_mulr. Qed. Lemma cardMg_divn G H : #|G * H| = (#|G| * #|H|) %/ #|G :&: H|. Proof. by rewrite mul_cardG mulnK ?cardG_gt0. Qed. Lemma cardIg_divn G H : #|G :&: H| = (#|G| * #|H|) %/ #|G * H|. Proof. by rewrite mul_cardG mulKn // (cardD1 (1 * 1)) mem_mulg. Qed. Lemma TI_cardMg G H : G :&: H = 1 -> #|G * H| = (#|G| * #|H|)%N. Proof. by move=> tiGH; rewrite mul_cardG tiGH cards1 muln1. Qed. Lemma cardMg_TI G H : #|G| * #|H| <= #|G * H| -> G :&: H = 1. Proof. move=> leGH; apply: card_le1_trivg. rewrite -(@leq_pmul2l #|G * H|); first by rewrite -mul_cardG muln1. by apply: leq_trans leGH; rewrite muln_gt0 !cardG_gt0. Qed. Lemma coprime_TIg G H : coprime #|G| #|H| -> G :&: H = 1. Proof. move=> coGH; apply/eqP; rewrite trivg_card1 -dvdn1 -{}(eqnP coGH). by rewrite dvdn_gcd /= {2}setIC !cardSg ?subsetIl. Qed. Lemma prime_TIg G H : prime #|G| -> ~~ (G \subset H) -> G :&: H = 1. Proof. case/primeP=> _ /(_ _ (cardSg (subsetIl G H))). rewrite (sameP setIidPl eqP) eqEcard subsetIl => /pred2P[/card1_trivg|] //= ->. by case/negP. Qed. Lemma prime_meetG G H : prime #|G| -> G :&: H != 1 -> G \subset H. Proof. by move=> prG; apply: contraR; move/prime_TIg->. Qed. Lemma coprime_cardMg G H : coprime #|G| #|H| -> #|G * H| = (#|G| * #|H|)%N. Proof. by move=> coGH; rewrite TI_cardMg ?coprime_TIg. Qed. Lemma coprime_index_mulG G H K : H \subset G -> K \subset G -> coprime #|G : H| #|G : K| -> H * K = G. Proof. move=> sHG sKG co_iG_HK; apply/eqP; rewrite eqEcard mul_subG //=. rewrite -(@leq_pmul2r #|H :&: K|) ?cardG_gt0 // -mul_cardG. rewrite -(Lagrange sHG) -(LagrangeI K H) mulnAC setIC -mulnA. rewrite !leq_pmul2l ?cardG_gt0 // dvdn_leq // -(Gauss_dvdr _ co_iG_HK). by rewrite -(indexgI K) Lagrange_index ?indexgS ?subsetIl ?subsetIr. Qed. End Lagrange. Section GeneratedGroup. Variable gT : finGroupType. Implicit Types x y z : gT. Implicit Types A B C D : {set gT}. Implicit Types G H K : {group gT}. Lemma subset_gen A : A \subset <<A>>. Proof. rewrite [@generated]unlock; exact/bigcapsP. Qed. Lemma sub_gen A B : A \subset B -> A \subset <<B>>. Proof. by move/subset_trans=> -> //; apply: subset_gen. Qed. Lemma mem_gen x A : x \in A -> x \in <<A>>. Proof. exact: subsetP (subset_gen A) x. Qed. Lemma generatedP x A : reflect (forall G, A \subset G -> x \in G) (x \in <<A>>). Proof. rewrite [@generated]unlock; exact: bigcapP. Qed. Lemma gen_subG A G : (<<A>> \subset G) = (A \subset G). Proof. apply/idP/idP=> [|sAG]; first exact: subset_trans (subset_gen A). by apply/subsetP=> x /generatedP; apply. Qed. Lemma genGid G : <<G>> = G. Proof. by apply/eqP; rewrite eqEsubset gen_subG subset_gen andbT. Qed. Lemma genGidG G : <<G>>%G = G. Proof. by apply: val_inj; apply: genGid. Qed. Lemma gen_set_id A : group_set A -> <<A>> = A. Proof. by move=> gA; apply: (genGid (group gA)). Qed. Lemma genS A B : A \subset B -> <<A>> \subset <<B>>. Proof. by move=> sAB; rewrite gen_subG sub_gen. Qed. Lemma gen0 : <<set0>> = 1 :> {set gT}. Proof. by apply/eqP; rewrite eqEsubset sub1G gen_subG sub0set. Qed. Lemma gen_expgs A : {n | <<A>> = (1 |: A) ^+ n}. Proof. set B := (1 |: A); pose N := #|gT|. have BsubG n : B ^+ n \subset <<A>>. by elim: n => [|n IHn]; rewrite ?expgS ?mul_subG ?subUset ?sub1G ?subset_gen. have B_1 n : 1 \in B ^+ n. by elim: n => [|n IHn]; rewrite ?set11 // expgS mulUg mul1g inE IHn. case: (pickP (fun i : 'I_N => B ^+ i.+1 \subset B ^+ i)) => [n fixBn | no_fix]. exists n; apply/eqP; rewrite eqEsubset BsubG andbT. rewrite -[B ^+ n]gen_set_id ?genS ?subsetUr //. by apply: subset_trans fixBn; rewrite expgS mulUg subsetU ?mulg_subl ?orbT. rewrite /group_set B_1 /=. elim: {2}(n : nat) => [|m IHm]; first by rewrite mulg1. by apply: subset_trans fixBn; rewrite !expgSr mulgA mulSg. suffices: N < #|B ^+ N| by rewrite ltnNge max_card. have [] := ubnPgeq N; elim=> [|n IHn] lt_nN; first by rewrite cards1. apply: leq_ltn_trans (IHn (ltnW lt_nN)) (proper_card _). by rewrite /proper (no_fix (Ordinal lt_nN)) expgS mulUg mul1g subsetUl. Qed. Lemma gen_prodgP A x : reflect (exists n, exists2 c, forall i : 'I_n, c i \in A & x = \prod_i c i) (x \in <<A>>). Proof. apply: (iffP idP) => [|[n [c Ac ->]]]; last first. by apply: group_prod => i _; rewrite mem_gen ?Ac. have [n ->] := gen_expgs A; rewrite /expgn Monoid.iteropE /=. rewrite -[n]card_ord -big_const => /prodsgP[/= c Ac def_x]. have{Ac def_x} ->: x = \prod_(i | c i \in A) c i. rewrite big_mkcond {x}def_x; apply: eq_bigr => i _. by case/setU1P: (Ac i isT) => -> //; rewrite if_same. have [e <- [_ /= mem_e] _] := big_enumP [preim c of A]. pose t := in_tuple e; rewrite -[e]/(val t) big_tuple. by exists (size e), (c \o tnth t) => // i; rewrite -mem_e mem_tnth. Qed. Lemma genD A B : A \subset <<A :\: B>> -> <<A :\: B>> = <<A>>. Proof. by move=> sAB; apply/eqP; rewrite eqEsubset genS (subsetDl, gen_subG). Qed. Lemma genV A : <<A^-1>> = <<A>>. Proof. apply/eqP; rewrite eqEsubset !gen_subG -!(invSg _ <<_>>) invgK. by rewrite !invGid !subset_gen. Qed. Lemma genJ A z : <<A :^z>> = <<A>> :^ z. Proof. by apply/eqP; rewrite eqEsubset sub_conjg !gen_subG conjSg -?sub_conjg !sub_gen. Qed. Lemma conjYg A B z : (A <*> B) :^z = A :^ z <*> B :^ z. Proof. by rewrite -genJ conjUg. Qed. Lemma genD1 A x : x \in <<A :\ x>> -> <<A :\ x>> = <<A>>. Proof. move=> gA'x; apply/eqP; rewrite eqEsubset genS; last by rewrite subsetDl. rewrite gen_subG; apply/subsetP=> y Ay. by case: (y =P x) => [-> //|]; move/eqP=> nyx; rewrite mem_gen // !inE nyx. Qed. Lemma genD1id A : <<A^#>> = <<A>>. Proof. by rewrite genD1 ?group1. Qed. Notation joingT := (@joing gT) (only parsing). Notation joinGT := (@joinG gT) (only parsing). Lemma joingE A B : A <*> B = <<A :|: B>>. Proof. by []. Qed. Lemma joinGE G H : (G * H)%G = (G <*> H)%G. Proof. by []. Qed. Lemma joingC : commutative joingT. Proof. by move=> A B; rewrite /joing setUC. Qed. Lemma joing_idr A B : A <*> <<B>> = A <*> B. Proof. apply/eqP; rewrite eqEsubset gen_subG subUset gen_subG /=. by rewrite -subUset subset_gen genS // setUS // subset_gen. Qed. Lemma joing_idl A B : <<A>> <*> B = A <*> B. Proof. by rewrite -!(joingC B) joing_idr. Qed. Lemma joing_subl A B : A \subset A <*> B. Proof. by rewrite sub_gen ?subsetUl. Qed. Lemma joing_subr A B : B \subset A <*> B. Proof. by rewrite sub_gen ?subsetUr. Qed. Lemma join_subG A B G : (A <*> B \subset G) = (A \subset G) && (B \subset G). Proof. by rewrite gen_subG subUset. Qed. Lemma joing_idPl G A : reflect (G <*> A = G) (A \subset G). Proof. apply: (iffP idP) => [sHG | <-]; last by rewrite joing_subr. by rewrite joingE (setUidPl sHG) genGid. Qed. Lemma joing_idPr A G : reflect (A <*> G = G) (A \subset G). Proof. by rewrite joingC; apply: joing_idPl. Qed. Lemma joing_subP A B G : reflect (A \subset G /\ B \subset G) (A <*> B \subset G). Proof. by rewrite join_subG; apply: andP. Qed. Lemma joing_sub A B C : A <*> B = C -> A \subset C /\ B \subset C. Proof. by move <-; apply/joing_subP. Qed. Lemma genDU A B C : A \subset C -> <<C :\: A>> = <<B>> -> <<A :|: B>> = <<C>>. Proof. move=> sAC; rewrite -joingE -joing_idr => <- {B}; rewrite joing_idr. by congr <<_>>; rewrite setDE setUIr setUCr setIT; apply/setUidPr. Qed. Lemma joingA : associative joingT. Proof. by move=> A B C; rewrite joing_idl joing_idr /joing setUA. Qed. Lemma joing1G G : 1 <*> G = G. Proof. by rewrite -gen0 joing_idl /joing set0U genGid. Qed. Lemma joingG1 G : G <*> 1 = G. Proof. by rewrite joingC joing1G. Qed. Lemma genM_join G H : <<G * H>> = G <*> H. Proof. apply/eqP; rewrite eqEsubset gen_subG /= -{1}[G <*> H]mulGid. rewrite genS; last by rewrite subUset mulG_subl mulG_subr. by rewrite mulgSS ?(sub_gen, subsetUl, subsetUr). Qed. Lemma mulG_subG G H K : (G * H \subset K) = (G \subset K) && (H \subset K). Proof. by rewrite -gen_subG genM_join join_subG. Qed. Lemma mulGsubP K H G : reflect (K \subset G /\ H \subset G) (K * H \subset G). Proof. by rewrite mulG_subG; apply: andP. Qed. Lemma mulG_sub K H A : K * H = A -> K \subset A /\ H \subset A. Proof. by move <-; rewrite mulG_subl mulG_subr. Qed. Lemma trivMg G H : (G * H == 1) = (G :==: 1) && (H :==: 1). Proof. by rewrite !eqEsubset -{2}[1]mulGid mulgSS ?sub1G // !andbT mulG_subG. Qed. Lemma comm_joingE G H : commute G H -> G <*> H = G * H. Proof. by move/comm_group_setP=> gGH; rewrite -genM_join; apply: (genGid (group gGH)). Qed. Lemma joinGC : commutative joinGT. Proof. by move=> G H; apply: val_inj; apply: joingC. Qed. Lemma joinGA : associative joinGT. Proof. by move=> G H K; apply: val_inj; apply: joingA. Qed. Lemma join1G : left_id 1%G joinGT. Proof. by move=> G; apply: val_inj; apply: joing1G. Qed. Lemma joinG1 : right_id 1%G joinGT. Proof. by move=> G; apply: val_inj; apply: joingG1. Qed. HB.instance Definition _ := Monoid.isComLaw.Build {group gT} 1%G joinGT joinGA joinGC join1G. Lemma bigprodGEgen I r (P : pred I) (F : I -> {set gT}) : (\prod_(i <- r | P i) <<F i>>)%G :=: << \bigcup_(i <- r | P i) F i >>. Proof. elim/big_rec2: _ => /= [|i A _ _ ->]; first by rewrite gen0. by rewrite joing_idl joing_idr. Qed. Lemma bigprodGE I r (P : pred I) (F : I -> {group gT}) : (\prod_(i <- r | P i) F i)%G :=: << \bigcup_(i <- r | P i) F i >>. Proof. rewrite -bigprodGEgen /=; apply: congr_group. by apply: eq_bigr => i _; rewrite genGidG. Qed. Lemma mem_commg A B x y : x \in A -> y \in B -> [~ x, y] \in [~: A, B]. Proof. by move=> Ax By; rewrite mem_gen ?imset2_f. Qed. Lemma commSg A B C : A \subset B -> [~: A, C] \subset [~: B, C]. Proof. by move=> sAC; rewrite genS ?imset2S. Qed. Lemma commgS A B C : B \subset C -> [~: A, B] \subset [~: A, C]. Proof. by move=> sBC; rewrite genS ?imset2S. Qed. Lemma commgSS A B C D : A \subset B -> C \subset D -> [~: A, C] \subset [~: B, D]. Proof. by move=> sAB sCD; rewrite genS ?imset2S. Qed. Lemma der1_subG G : [~: G, G] \subset G. Proof. by rewrite gen_subG; apply/subsetP=> _ /imset2P[x y Gx Gy ->]; apply: groupR. Qed. Lemma comm_subG A B G : A \subset G -> B \subset G -> [~: A, B] \subset G. Proof. by move=> sAG sBG; apply: subset_trans (der1_subG G); apply: commgSS. Qed. Lemma commGC A B : [~: A, B] = [~: B, A]. Proof. rewrite -[[~: A, B]]genV; congr <<_>>; apply/setP=> z; rewrite inE. by apply/imset2P/imset2P=> [] [x y Ax Ay]; last rewrite -{1}(invgK z); rewrite -invg_comm => /invg_inj->; exists y x. Qed. Lemma conjsRg A B x : [~: A, B] :^ x = [~: A :^ x, B :^ x]. Proof. wlog suffices: A B x / [~: A, B] :^ x \subset [~: A :^ x, B :^ x]. move=> subJ; apply/eqP; rewrite eqEsubset subJ /= -sub_conjgV. by rewrite -{2}(conjsgK x A) -{2}(conjsgK x B). rewrite -genJ gen_subG; apply/subsetP=> _ /imsetP[_ /imset2P[y z Ay Bz ->] ->]. by rewrite conjRg mem_commg ?memJ_conjg. Qed. End GeneratedGroup. Arguments gen_prodgP {gT A x}. Arguments joing_idPl {gT G A}. Arguments joing_idPr {gT A G}. Arguments mulGsubP {gT K H G}. Arguments joing_subP {gT A B G}. Section Cycles. (* Elementary properties of cycles and order, needed in perm.v. *) (* More advanced results on the structure of cyclic groups will *) (* be given in cyclic.v. *) Variable gT : finGroupType. Implicit Types x y : gT. Implicit Types G : {group gT}. Import Monoid.Theory. Lemma cycle1 : <[1]> = [1 gT]. Proof. exact: genGid. Qed. Lemma order1 : #[1 : gT] = 1%N. Proof. by rewrite /order cycle1 cards1. Qed. Lemma cycle_id x : x \in <[x]>. Proof. by rewrite mem_gen // set11. Qed. Lemma mem_cycle x i : x ^+ i \in <[x]>. Proof. by rewrite groupX // cycle_id. Qed. Lemma cycle_subG x G : (<[x]> \subset G) = (x \in G). Proof. by rewrite gen_subG sub1set. Qed. Lemma cycle_eq1 x : (<[x]> == 1) = (x == 1). Proof. by rewrite eqEsubset sub1G andbT cycle_subG inE. Qed. Lemma orderE x : #[x] = #|<[x]>|. Proof. by []. Qed. Lemma order_eq1 x : (#[x] == 1%N) = (x == 1). Proof. by rewrite -trivg_card1 cycle_eq1. Qed. Lemma order_gt1 x : (#[x] > 1) = (x != 1). Proof. by rewrite ltnNge -trivg_card_le1 cycle_eq1. Qed. Lemma cycle_traject x : <[x]> =i traject (mulg x) 1 #[x]. Proof. set t := _ 1; apply: fsym; apply/subset_cardP; last first. by apply/subsetP=> _ /trajectP[i _ ->]; rewrite -iteropE mem_cycle. rewrite (card_uniqP _) ?size_traject //; case def_n: #[_] => // [n]. rewrite looping_uniq; apply: contraL (card_size (t n)) => /loopingP t_xi. rewrite -ltnNge size_traject -def_n ?subset_leq_card //. rewrite -(eq_subset_r (in_set _)) {}/t; set G := finset _. rewrite -[x]mulg1 -[G]gen_set_id ?genS ?sub1set ?inE ?(t_xi 1%N)//. apply/group_setP; split=> [|y z]; rewrite !inE ?(t_xi 0) //. by do 2!case/trajectP=> ? _ ->; rewrite -!iteropE -expgD [x ^+ _]iteropE. Qed. Lemma cycle2g x : #[x] = 2 -> <[x]> = [set 1; x]. Proof. by move=> ox; apply/setP=> y; rewrite cycle_traject ox !inE mulg1. Qed. Lemma cyclePmin x y : y \in <[x]> -> {i | i < #[x] & y = x ^+ i}. Proof. rewrite cycle_traject; set tx := traject _ _ #[x] => tx_y; pose i := index y tx. have lt_i_x : i < #[x] by rewrite -index_mem size_traject in tx_y. by exists i; rewrite // [x ^+ i]iteropE /= -(nth_traject _ lt_i_x) nth_index. Qed. Lemma cycleP x y : reflect (exists i, y = x ^+ i) (y \in <[x]>). Proof. by apply: (iffP idP) => [/cyclePmin[i _]|[i ->]]; [exists i | apply: mem_cycle]. Qed. Lemma expg_order x : x ^+ #[x] = 1. Proof. have: uniq (traject (mulg x) 1 #[x]). by apply/card_uniqP; rewrite size_traject -(eq_card (cycle_traject x)). case/cyclePmin: (mem_cycle x #[x]) => [] [//|i] ltix. rewrite -(subnKC ltix) addSnnS /= expgD; move: (_ - _) => j x_j1. case/andP=> /trajectP[]; exists j; first exact: leq_addl. by apply: (mulgI (x ^+ i.+1)); rewrite -iterSr iterS -iteropE -expgS mulg1. Qed. Lemma expg_mod p k x : x ^+ p = 1 -> x ^+ (k %% p) = x ^+ k. Proof. move=> xp. by rewrite {2}(divn_eq k p) expgD mulnC expgM xp expg1n mul1g. Qed. Lemma expg_mod_order x i : x ^+ (i %% #[x]) = x ^+ i. Proof. by rewrite expg_mod // expg_order. Qed. Lemma invg_expg x : x^-1 = x ^+ #[x].-1. Proof. by apply/eqP; rewrite eq_invg_mul -expgS prednK ?expg_order. Qed. Lemma invg2id x : #[x] = 2 -> x^-1 = x. Proof. by move=> ox; rewrite invg_expg ox. Qed. Lemma cycleX x i : <[x ^+ i]> \subset <[x]>. Proof. by rewrite cycle_subG; apply: mem_cycle. Qed. Lemma cycleV x : <[x^-1]> = <[x]>. Proof. by apply/eqP; rewrite eq_sym eqEsubset !cycle_subG groupV -groupV !cycle_id. Qed. Lemma orderV x : #[x^-1] = #[x]. Proof. by rewrite /order cycleV. Qed. Lemma cycleJ x y : <[x ^ y]> = <[x]> :^ y. Proof. by rewrite -genJ conjg_set1. Qed. Lemma orderJ x y : #[x ^ y] = #[x]. Proof. by rewrite /order cycleJ cardJg. Qed. End Cycles. Section Normaliser. Variable gT : finGroupType. Implicit Types x y z : gT. Implicit Types A B C D : {set gT}. Implicit Type G H K : {group gT}. Lemma normP x A : reflect (A :^ x = A) (x \in 'N(A)). Proof. suffices ->: (x \in 'N(A)) = (A :^ x == A) by apply: eqP. by rewrite eqEcard cardJg leqnn andbT inE. Qed. Arguments normP {x A}. Lemma group_set_normaliser A : group_set 'N(A). Proof. apply/group_setP; split=> [|x y Nx Ny]; rewrite inE ?conjsg1 //. by rewrite conjsgM !(normP _). Qed. Canonical normaliser_group A := group (group_set_normaliser A). Lemma normsP A B : reflect {in A, normalised B} (A \subset 'N(B)). Proof. apply: (iffP subsetP) => nBA x Ax; last by rewrite inE nBA //. by apply/normP; apply: nBA. Qed. Arguments normsP {A B}. Lemma memJ_norm x y A : x \in 'N(A) -> (y ^ x \in A) = (y \in A). Proof. by move=> Nx; rewrite -{1}(normP Nx) memJ_conjg. Qed. Lemma norms_cycle x y : (<[y]> \subset 'N(<[x]>)) = (x ^ y \in <[x]>). Proof. by rewrite cycle_subG inE -cycleJ cycle_subG. Qed. Lemma norm1 : 'N(1) = setT :> {set gT}. Proof. by apply/setP=> x; rewrite !inE conjs1g subxx. Qed. Lemma norms1 A : A \subset 'N(1). Proof. by rewrite norm1 subsetT. Qed. Lemma normCs A : 'N(~: A) = 'N(A). Proof. by apply/setP=> x; rewrite -groupV !inE conjCg setCS sub_conjg. Qed. Lemma normG G : G \subset 'N(G). Proof. by apply/normsP; apply: conjGid. Qed. Lemma normT : 'N([set: gT]) = [set: gT]. Proof. by apply/eqP; rewrite -subTset normG. Qed. Lemma normsG A G : A \subset G -> A \subset 'N(G). Proof. by move=> sAG; apply: subset_trans (normG G). Qed. Lemma normC A B : A \subset 'N(B) -> commute A B. Proof. move/subsetP=> nBA; apply/setP=> u. apply/mulsgP/mulsgP=> [[x y Ax By] | [y x By Ax]] -> {u}. by exists (y ^ x^-1) x; rewrite -?conjgCV // memJ_norm // groupV nBA. by exists x (y ^ x); rewrite -?conjgC // memJ_norm // nBA. Qed. Lemma norm_joinEl G H : G \subset 'N(H) -> G <*> H = G * H. Proof. by move/normC/comm_joingE. Qed. Lemma norm_joinEr G H : H \subset 'N(G) -> G <*> H = G * H. Proof. by move/normC=> cHG; apply: comm_joingE. Qed. Lemma norm_rlcoset G x : x \in 'N(G) -> G :* x = x *: G. Proof. by rewrite -sub1set => /normC. Qed. Lemma rcoset_mul G x y : x \in 'N(G) -> (G :* x) * (G :* y) = G :* (x * y). Proof. move/norm_rlcoset=> GxxG. by rewrite mulgA -(mulgA _ _ G) -GxxG mulgA mulGid -mulgA mulg_set1. Qed. Lemma normJ A x : 'N(A :^ x) = 'N(A) :^ x. Proof. by apply/setP=> y; rewrite mem_conjg !inE -conjsgM conjgCV conjsgM conjSg. Qed. Lemma norm_conj_norm x A B : x \in 'N(A) -> (A \subset 'N(B :^ x)) = (A \subset 'N(B)). Proof. by move=> Nx; rewrite normJ -sub_conjgV (normP _) ?groupV. Qed. Lemma norm_gen A : 'N(A) \subset 'N(<<A>>). Proof. by apply/normsP=> x Nx; rewrite -genJ (normP Nx). Qed. Lemma class_norm x G : G \subset 'N(x ^: G). Proof. by apply/normsP=> y; apply: classGidr. Qed. Lemma class_normal x G : x \in G -> x ^: G <| G. Proof. by move=> Gx; rewrite /normal class_norm class_subG. Qed. Lemma class_sub_norm G A x : G \subset 'N(A) -> (x ^: G \subset A) = (x \in A). Proof. move=> nAG; apply/subsetP/idP=> [-> // | Ax xy]; first exact: class_refl. by case/imsetP=> y Gy ->; rewrite memJ_norm ?(subsetP nAG). Qed. Lemma class_support_norm A G : G \subset 'N(class_support A G). Proof. by apply/normsP; apply: class_supportGidr. Qed. Lemma class_support_sub_norm A B G : A \subset G -> B \subset 'N(G) -> class_support A B \subset G. Proof. move=> sAG nGB; rewrite class_supportEr. by apply/bigcupsP=> x Bx; rewrite -(normsP nGB x Bx) conjSg. Qed. Section norm_trans. Variables (A B C D : {set gT}). Hypotheses (nBA : A \subset 'N(B)) (nCA : A \subset 'N(C)). Lemma norms_gen : A \subset 'N(<<B>>). Proof. exact: subset_trans nBA (norm_gen B). Qed. Lemma norms_norm : A \subset 'N('N(B)). Proof. by apply/normsP=> x Ax; rewrite -normJ (normsP nBA). Qed. Lemma normsI : A \subset 'N(B :&: C). Proof. by apply/normsP=> x Ax; rewrite conjIg !(normsP _ x Ax). Qed. Lemma normsU : A \subset 'N(B :|: C). Proof. by apply/normsP=> x Ax; rewrite conjUg !(normsP _ x Ax). Qed. Lemma normsIs : B \subset 'N(D) -> A :&: B \subset 'N(C :&: D). Proof. move/normsP=> nDB; apply/normsP=> x; case/setIP=> Ax Bx. by rewrite conjIg (normsP nCA) ?nDB. Qed. Lemma normsD : A \subset 'N(B :\: C). Proof. by apply/normsP=> x Ax; rewrite conjDg !(normsP _ x Ax). Qed. Lemma normsM : A \subset 'N(B * C). Proof. by apply/normsP=> x Ax; rewrite conjsMg !(normsP _ x Ax). Qed. Lemma normsY : A \subset 'N(B <*> C). Proof. by apply/normsP=> x Ax; rewrite -genJ conjUg !(normsP _ x Ax). Qed. Lemma normsR : A \subset 'N([~: B, C]). Proof. by apply/normsP=> x Ax; rewrite conjsRg !(normsP _ x Ax). Qed. Lemma norms_class_support : A \subset 'N(class_support B C). Proof. apply/subsetP=> x Ax; rewrite inE sub_conjg class_supportEr. apply/bigcupsP=> y Cy; rewrite -sub_conjg -conjsgM conjgC conjsgM. by rewrite (normsP nBA) // bigcup_sup ?memJ_norm ?(subsetP nCA). Qed. End norm_trans. Lemma normsIG A B G : A \subset 'N(B) -> A :&: G \subset 'N(B :&: G). Proof. by move/normsIs->; rewrite ?normG. Qed. Lemma normsGI A B G : A \subset 'N(B) -> G :&: A \subset 'N(G :&: B). Proof. by move=> nBA; rewrite !(setIC G) normsIG. Qed. Lemma norms_bigcap I r (P : pred I) A (B_ : I -> {set gT}) : A \subset \bigcap_(i <- r | P i) 'N(B_ i) -> A \subset 'N(\bigcap_(i <- r | P i) B_ i). Proof. elim/big_rec2: _ => [|i B N _ IH /subsetIP[nBiA /IH]]; last exact: normsI. by rewrite normT. Qed. Lemma norms_bigcup I r (P : pred I) A (B_ : I -> {set gT}) : A \subset \bigcap_(i <- r | P i) 'N(B_ i) -> A \subset 'N(\bigcup_(i <- r | P i) B_ i). Proof. move=> nBA; rewrite -normCs setC_bigcup norms_bigcap //. by rewrite (eq_bigr _ (fun _ _ => normCs _)). Qed. Lemma normsD1 A B : A \subset 'N(B) -> A \subset 'N(B^#). Proof. by move/normsD->; rewrite ?norms1. Qed. Lemma normD1 A : 'N(A^#) = 'N(A). Proof. apply/eqP; rewrite eqEsubset normsD1 //. rewrite -{2}(setID A 1) setIC normsU //; apply/normsP=> x _; apply/setP=> y. by rewrite conjIg conjs1g !inE mem_conjg; case: eqP => // ->; rewrite conj1g. Qed. Lemma normalP A B : reflect (A \subset B /\ {in B, normalised A}) (A <| B). Proof. by apply: (iffP andP)=> [] [sAB]; move/normsP. Qed. Lemma normal_sub A B : A <| B -> A \subset B. Proof. by case/andP. Qed. Lemma normal_norm A B : A <| B -> B \subset 'N(A). Proof. by case/andP. Qed. Lemma normalS G H K : K \subset H -> H \subset G -> K <| G -> K <| H. Proof. by move=> sKH sHG /andP[_ nKG]; rewrite /(K <| _) sKH (subset_trans sHG). Qed. Lemma normal1 G : 1 <| G. Proof. by rewrite /normal sub1set group1 norms1. Qed. Lemma normal_refl G : G <| G. Proof. by rewrite /(G <| _) normG subxx. Qed. Lemma normalG G : G <| 'N(G). Proof. by rewrite /(G <| _) normG subxx. Qed. Lemma normalSG G H : H \subset G -> H <| 'N_G(H). Proof. by move=> sHG; rewrite /normal subsetI sHG normG subsetIr. Qed. Lemma normalJ A B x : (A :^ x <| B :^ x) = (A <| B). Proof. by rewrite /normal normJ !conjSg. Qed. Lemma normalM G A B : A <| G -> B <| G -> A * B <| G. Proof. by case/andP=> sAG nAG /andP[sBG nBG]; rewrite /normal mul_subG ?normsM. Qed. Lemma normalY G A B : A <| G -> B <| G -> A <*> B <| G. Proof. by case/andP=> sAG ? /andP[sBG ?]; rewrite /normal join_subG sAG sBG ?normsY. Qed. Lemma normalYl G H : (H <| H <*> G) = (G \subset 'N(H)). Proof. by rewrite /normal joing_subl join_subG normG. Qed. Lemma normalYr G H : (H <| G <*> H) = (G \subset 'N(H)). Proof. by rewrite joingC normalYl. Qed. Lemma normalI G A B : A <| G -> B <| G -> A :&: B <| G. Proof. by case/andP=> sAG nAG /andP[_ nBG]; rewrite /normal subIset ?sAG // normsI. Qed. Lemma norm_normalI G A : G \subset 'N(A) -> G :&: A <| G. Proof. by move=> nAG; rewrite /normal subsetIl normsI ?normG. Qed. Lemma normalGI G H A : H \subset G -> A <| G -> H :&: A <| H. Proof. by move=> sHG /andP[_ nAG]; apply: norm_normalI (subset_trans sHG nAG). Qed. Lemma normal_subnorm G H : (H <| 'N_G(H)) = (H \subset G). Proof. by rewrite /normal subsetIr subsetI normG !andbT. Qed. Lemma normalD1 A G : (A^# <| G) = (A <| G). Proof. by rewrite /normal normD1 subDset (setUidPr (sub1G G)). Qed. Lemma gcore_sub A G : gcore A G \subset A. Proof. by rewrite (bigcap_min 1) ?conjsg1. Qed. Lemma gcore_norm A G : G \subset 'N(gcore A G). Proof. apply/subsetP=> x Gx; rewrite inE; apply/bigcapsP=> y Gy. by rewrite sub_conjg -conjsgM bigcap_inf ?groupM ?groupV. Qed. Lemma gcore_normal A G : A \subset G -> gcore A G <| G. Proof. by move=> sAG; rewrite /normal gcore_norm (subset_trans (gcore_sub A G)). Qed. Lemma gcore_max A B G : B \subset A -> G \subset 'N(B) -> B \subset gcore A G. Proof. move=> sBA nBG; apply/bigcapsP=> y Gy. by rewrite -sub_conjgV (normsP nBG) ?groupV. Qed. Lemma sub_gcore A B G : G \subset 'N(B) -> (B \subset gcore A G) = (B \subset A). Proof. move=> nBG; apply/idP/idP=> [sBAG | sBA]; last exact: gcore_max. exact: subset_trans (gcore_sub A G). Qed. (* An elementary proof that subgroups of index 2 are normal; it is almost as *) (* short as the "advanced" proof using group actions; besides, the fact that *) (* the coset is equal to the complement is used in extremal.v. *) Lemma rcoset_index2 G H x : H \subset G -> #|G : H| = 2 -> x \in G :\: H -> H :* x = G :\: H. Proof. move=> sHG indexHG => /setDP[Gx notHx]; apply/eqP. rewrite eqEcard -(leq_add2l #|G :&: H|) cardsID -(LagrangeI G H) indexHG muln2. rewrite (setIidPr sHG) card_rcoset addnn leqnn andbT. apply/subsetP=> _ /rcosetP[y Hy ->]; apply/setDP. by rewrite !groupMl // (subsetP sHG). Qed. Lemma index2_normal G H : H \subset G -> #|G : H| = 2 -> H <| G. Proof. move=> sHG indexHG; rewrite /normal sHG; apply/subsetP=> x Gx. case Hx: (x \in H); first by rewrite inE conjGid. rewrite inE conjsgE mulgA -sub_rcosetV -invg_rcoset. by rewrite !(rcoset_index2 sHG) ?inE ?groupV ?Hx // invDg !invGid. Qed. Lemma cent1P x y : reflect (commute x y) (x \in 'C[y]). Proof. rewrite [x \in _]inE conjg_set1 sub1set !inE (sameP eqP conjg_fixP)commg1_sym. exact: commgP. Qed. Lemma cent1id x : x \in 'C[x]. Proof. exact/cent1P. Qed. Lemma cent1E x y : (x \in 'C[y]) = (x * y == y * x). Proof. by rewrite (sameP (cent1P x y) eqP). Qed. Lemma cent1C x y : (x \in 'C[y]) = (y \in 'C[x]). Proof. by rewrite !cent1E eq_sym. Qed. Canonical centraliser_group A : {group _} := Eval hnf in [group of 'C(A)]. Lemma cent_set1 x : 'C([set x]) = 'C[x]. Proof. by apply: big_pred1 => y /=; rewrite !inE. Qed. Lemma cent1J x y : 'C[x ^ y] = 'C[x] :^ y. Proof. by rewrite -conjg_set1 normJ. Qed. Lemma centP A x : reflect (centralises x A) (x \in 'C(A)). Proof. by apply: (iffP bigcapP) => cxA y /cxA/cent1P. Qed. Lemma centsP A B : reflect {in A, centralised B} (A \subset 'C(B)). Proof. by apply: (iffP subsetP) => cAB x /cAB/centP. Qed. Lemma centsC A B : (A \subset 'C(B)) = (B \subset 'C(A)). Proof. by apply/centsP/centsP=> cAB x ? y ?; rewrite /commute -cAB. Qed. Lemma cents1 A : A \subset 'C(1). Proof. by rewrite centsC sub1G. Qed. Lemma cent1T : 'C(1) = setT :> {set gT}. Proof. by apply/eqP; rewrite -subTset cents1. Qed. Lemma cent11T : 'C[1] = setT :> {set gT}. Proof. by rewrite -cent_set1 cent1T. Qed. Lemma cent_sub A : 'C(A) \subset 'N(A). Proof. apply/subsetP=> x /centP cAx; rewrite inE. by apply/subsetP=> _ /imsetP[y Ay ->]; rewrite /conjg -cAx ?mulKg. Qed. Lemma cents_norm A B : A \subset 'C(B) -> A \subset 'N(B). Proof. by move=> cAB; apply: subset_trans (cent_sub B). Qed. Lemma centC A B : A \subset 'C(B) -> commute A B. Proof. by move=> cAB; apply: normC (cents_norm cAB). Qed. Lemma cent_joinEl G H : G \subset 'C(H) -> G <*> H = G * H. Proof. by move=> cGH; apply: norm_joinEl (cents_norm cGH). Qed. Lemma cent_joinEr G H : H \subset 'C(G) -> G <*> H = G * H. Proof. by move=> cGH; apply: norm_joinEr (cents_norm cGH). Qed. Lemma centJ A x : 'C(A :^ x) = 'C(A) :^ x. Proof. apply/setP=> y; rewrite mem_conjg; apply/centP/centP=> cAy z Az. by apply: (conjg_inj x); rewrite 2!conjMg conjgKV cAy ?memJ_conjg. by apply: (conjg_inj x^-1); rewrite 2!conjMg cAy -?mem_conjg. Qed. Lemma cent_norm A : 'N(A) \subset 'N('C(A)). Proof. by apply/normsP=> x nCx; rewrite -centJ (normP nCx). Qed. Lemma norms_cent A B : A \subset 'N(B) -> A \subset 'N('C(B)). Proof. by move=> nBA; apply: subset_trans nBA (cent_norm B). Qed. Lemma cent_normal A : 'C(A) <| 'N(A). Proof. by rewrite /(_ <| _) cent_sub cent_norm. Qed. Lemma centS A B : B \subset A -> 'C(A) \subset 'C(B). Proof. by move=> sAB; rewrite centsC (subset_trans sAB) 1?centsC. Qed. Lemma centsS A B C : A \subset B -> C \subset 'C(B) -> C \subset 'C(A). Proof. by move=> sAB cCB; apply: subset_trans cCB (centS sAB). Qed. Lemma centSS A B C D : A \subset C -> B \subset D -> C \subset 'C(D) -> A \subset 'C(B). Proof. by move=> sAC sBD cCD; apply: subset_trans (centsS sBD cCD). Qed. Lemma centI A B : 'C(A) <*> 'C(B) \subset 'C(A :&: B). Proof. by rewrite gen_subG subUset !centS ?(subsetIl, subsetIr). Qed. Lemma centU A B : 'C(A :|: B) = 'C(A) :&: 'C(B). Proof. apply/eqP; rewrite eqEsubset subsetI 2?centS ?(subsetUl, subsetUr) //=. by rewrite centsC subUset -centsC subsetIl -centsC subsetIr. Qed. Lemma cent_gen A : 'C(<<A>>) = 'C(A). Proof. by apply/setP=> x; rewrite -!sub1set centsC gen_subG centsC. Qed. Lemma cent_cycle x : 'C(<[x]>) = 'C[x]. Proof. by rewrite cent_gen cent_set1. Qed. Lemma sub_cent1 A x : (A \subset 'C[x]) = (x \in 'C(A)). Proof. by rewrite -cent_cycle centsC cycle_subG. Qed. Lemma cents_cycle x y : commute x y -> <[x]> \subset 'C(<[y]>). Proof. by move=> cxy; rewrite cent_cycle cycle_subG; apply/cent1P. Qed. Lemma cycle_abelian x : abelian <[x]>. Proof. exact: cents_cycle. Qed. Lemma centY A B : 'C(A <*> B) = 'C(A) :&: 'C(B). Proof. by rewrite cent_gen centU. Qed. Lemma centM G H : 'C(G * H) = 'C(G) :&: 'C(H). Proof. by rewrite -cent_gen genM_join centY. Qed. Lemma cent_classP x G : reflect (x ^: G = [set x]) (x \in 'C(G)). Proof. apply: (iffP (centP _ _)) => [Cx | Cx1 y Gy]. apply/eqP; rewrite eqEsubset sub1set class_refl andbT. by apply/subsetP=> _ /imsetP[y Gy ->]; rewrite !inE conjgE Cx ?mulKg. by apply/commgP/conjg_fixP/set1P; rewrite -Cx1; apply/imsetP; exists y. Qed. Lemma commG1P A B : reflect ([~: A, B] = 1) (A \subset 'C(B)). Proof. apply: (iffP (centsP A B)) => [cAB | cAB1 x Ax y By]. apply/trivgP; rewrite gen_subG; apply/subsetP=> _ /imset2P[x y Ax Ay ->]. by rewrite inE; apply/commgP; apply: cAB. by apply/commgP; rewrite -in_set1 -[[set 1]]cAB1 mem_commg. Qed. Lemma abelianE A : abelian A = (A \subset 'C(A)). Proof. by []. Qed. Lemma abelian1 : abelian [1 gT]. Proof. exact: sub1G. Qed. Lemma abelianS A B : A \subset B -> abelian B -> abelian A. Proof. by move=> sAB; apply: centSS. Qed. Lemma abelianJ A x : abelian (A :^ x) = abelian A. Proof. by rewrite /abelian centJ conjSg. Qed. Lemma abelian_gen A : abelian <<A>> = abelian A. Proof. by rewrite /abelian cent_gen gen_subG. Qed. Lemma abelianY A B : abelian (A <*> B) = [&& abelian A, abelian B & B \subset 'C(A)]. Proof. rewrite /abelian join_subG /= centY !subsetI -!andbA; congr (_ && _). by rewrite centsC andbA andbb andbC. Qed. Lemma abelianM G H : abelian (G * H) = [&& abelian G, abelian H & H \subset 'C(G)]. Proof. by rewrite -abelian_gen genM_join abelianY. Qed. Section SubAbelian. Variable A B C : {set gT}. Hypothesis cAA : abelian A. Lemma sub_abelian_cent : C \subset A -> A \subset 'C(C). Proof. by move=> sCA; rewrite centsC (subset_trans sCA). Qed. Lemma sub_abelian_cent2 : B \subset A -> C \subset A -> B \subset 'C(C). Proof. by move=> sBA; move/sub_abelian_cent; apply: subset_trans. Qed. Lemma sub_abelian_norm : C \subset A -> A \subset 'N(C). Proof. by move=> sCA; rewrite cents_norm ?sub_abelian_cent. Qed. Lemma sub_abelian_normal : (C \subset A) = (C <| A). Proof. by rewrite /normal; case sHG: (C \subset A); rewrite // sub_abelian_norm. Qed. End SubAbelian. End Normaliser. Arguments normP {gT x A}. Arguments centP {gT A x}. Arguments normsP {gT A B}. Arguments cent1P {gT x y}. Arguments normalP {gT A B}. Arguments centsP {gT A B}. Arguments commG1P {gT A B}. Arguments normaliser_group _ _%_g. Arguments centraliser_group _ _%_g. Notation "''N' ( A )" := (normaliser_group A) : Group_scope. Notation "''C' ( A )" := (centraliser_group A) : Group_scope. Notation "''C' [ x ]" := (normaliser_group [set x%g]) : Group_scope. Notation "''N_' G ( A )" := (setI_group G 'N(A)) : Group_scope. Notation "''C_' G ( A )" := (setI_group G 'C(A)) : Group_scope. Notation "''C_' ( G ) ( A )" := (setI_group G 'C(A)) (only parsing) : Group_scope. Notation "''C_' G [ x ]" := (setI_group G 'C[x]) : Group_scope. Notation "''C_' ( G ) [ x ]" := (setI_group G 'C[x]) (only parsing) : Group_scope. #[global] Hint Extern 0 (is_true (_ \subset _)) => apply: normG : core. #[global] Hint Extern 0 (is_true (_ <| _)) => apply: normal_refl : core. Section MinMaxGroup. Variable gT : finGroupType. Implicit Types gP : pred {group gT}. Definition maxgroup A gP := maxset (fun A => group_set A && gP <<A>>%G) A. Definition mingroup A gP := minset (fun A => group_set A && gP <<A>>%G) A. Variable gP : pred {group gT}. Arguments gP _%_G. Lemma ex_maxgroup : (exists G, gP G) -> {G : {group gT} | maxgroup G gP}. Proof. move=> exP; have [A maxA]: {A | maxgroup A gP}. apply: ex_maxset; case: exP => G gPG. by exists (G : {set gT}); rewrite groupP genGidG. by exists <<A>>%G; rewrite /= gen_set_id; case/andP: (maxsetp maxA). Qed. Lemma ex_mingroup : (exists G, gP G) -> {G : {group gT} | mingroup G gP}. Proof. move=> exP; have [A minA]: {A | mingroup A gP}. apply: ex_minset; case: exP => G gPG. by exists (G : {set gT}); rewrite groupP genGidG. by exists <<A>>%G; rewrite /= gen_set_id; case/andP: (minsetp minA). Qed. Variable G : {group gT}. Lemma mingroupP : reflect (gP G /\ forall H, gP H -> H \subset G -> H :=: G) (mingroup G gP). Proof. apply: (iffP minsetP); rewrite /= groupP genGidG /= => [] [-> minG]. by split=> // H gPH sGH; apply: minG; rewrite // groupP genGidG. by split=> // A; case/andP=> gA gPA; rewrite -(gen_set_id gA); apply: minG. Qed. Lemma maxgroupP : reflect (gP G /\ forall H, gP H -> G \subset H -> H :=: G) (maxgroup G gP). Proof. apply: (iffP maxsetP); rewrite /= groupP genGidG /= => [] [-> maxG]. by split=> // H gPH sGH; apply: maxG; rewrite // groupP genGidG. by split=> // A; case/andP=> gA gPA; rewrite -(gen_set_id gA); apply: maxG. Qed. Lemma maxgroupp : maxgroup G gP -> gP G. Proof. by case/maxgroupP. Qed. Lemma mingroupp : mingroup G gP -> gP G. Proof. by case/mingroupP. Qed. Hypothesis gPG : gP G. Lemma maxgroup_exists : {H : {group gT} | maxgroup H gP & G \subset H}. Proof. have [A maxA sGA]: {A | maxgroup A gP & G \subset A}. by apply: maxset_exists; rewrite groupP genGidG. by exists <<A>>%G; rewrite /= gen_set_id; case/andP: (maxsetp maxA). Qed. Lemma mingroup_exists : {H : {group gT} | mingroup H gP & H \subset G}. Proof. have [A maxA sGA]: {A | mingroup A gP & A \subset G}. by apply: minset_exists; rewrite groupP genGidG. by exists <<A>>%G; rewrite /= gen_set_id; case/andP: (minsetp maxA). Qed. End MinMaxGroup. Arguments mingroup {gT} A%_g gP. Arguments maxgroup {gT} A%_g gP. Arguments mingroupP {gT gP G}. Arguments maxgroupP {gT gP G}. Notation "[ 'max' A 'of' G | gP ]" := (maxgroup A (fun G : {group _} => gP)) : group_scope. Notation "[ 'max' G | gP ]" := [max gval G of G | gP] : group_scope. Notation "[ 'max' A 'of' G | gP & gQ ]" := [max A of G | gP && gQ] : group_scope. Notation "[ 'max' G | gP & gQ ]" := [max G | gP && gQ] : group_scope. Notation "[ 'min' A 'of' G | gP ]" := (mingroup A (fun G : {group _} => gP)) : group_scope. Notation "[ 'min' G | gP ]" := [min gval G of G | gP] : group_scope. Notation "[ 'min' A 'of' G | gP & gQ ]" := [min A of G | gP && gQ] : group_scope. Notation "[ 'min' G | gP & gQ ]" := [min G | gP && gQ] : group_scope. HB.reexport.
UpperLower.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Algebra.Order.Field.Pi import Mathlib.Algebra.Order.Pi import Mathlib.Analysis.Normed.Field.Basic import Mathlib.Analysis.Normed.Group.Pointwise import Mathlib.Topology.Algebra.Order.UpperLower import Mathlib.Topology.MetricSpace.Sequences /-! # Upper/lower/order-connected sets in normed groups The topological closure and interior of an upper/lower/order-connected set is an upper/lower/order-connected set (with the notable exception of the closure of an order-connected set). We also prove lemmas specific to `ℝⁿ`. Those are helpful to prove that order-connected sets in `ℝⁿ` are measurable. ## TODO Is there a way to generalise `IsClosed.upperClosure_pi`/`IsClosed.lowerClosure_pi` so that they also apply to `ℝ`, `ℝ × ℝ`, `EuclideanSpace ι ℝ`? `_pi` has been appended to their names to disambiguate from the other possible lemmas, but we will want there to be a single set of lemmas for all situations. -/ open Bornology Function Metric Set open scoped Pointwise variable {α ι : Type*} section NormedOrderedGroup variable [NormedCommGroup α] [PartialOrder α] [IsOrderedMonoid α] {s : Set α} @[to_additive IsUpperSet.thickening] protected theorem IsUpperSet.thickening' (hs : IsUpperSet s) (ε : ℝ) : IsUpperSet (thickening ε s) := by rw [← ball_mul_one] exact hs.mul_left @[to_additive IsLowerSet.thickening] protected theorem IsLowerSet.thickening' (hs : IsLowerSet s) (ε : ℝ) : IsLowerSet (thickening ε s) := by rw [← ball_mul_one] exact hs.mul_left @[to_additive IsUpperSet.cthickening] protected theorem IsUpperSet.cthickening' (hs : IsUpperSet s) (ε : ℝ) : IsUpperSet (cthickening ε s) := by rw [cthickening_eq_iInter_thickening''] exact isUpperSet_iInter₂ fun δ _ => hs.thickening' _ @[to_additive IsLowerSet.cthickening] protected theorem IsLowerSet.cthickening' (hs : IsLowerSet s) (ε : ℝ) : IsLowerSet (cthickening ε s) := by rw [cthickening_eq_iInter_thickening''] exact isLowerSet_iInter₂ fun δ _ => hs.thickening' _ @[to_additive upperClosure_interior_subset] lemma upperClosure_interior_subset' (s : Set α) : (upperClosure (interior s) : Set α) ⊆ interior (upperClosure s) := upperClosure_min (interior_mono subset_upperClosure) (upperClosure s).upper.interior @[to_additive lowerClosure_interior_subset] lemma lowerClosure_interior_subset' (s : Set α) : (lowerClosure (interior s) : Set α) ⊆ interior (lowerClosure s) := lowerClosure_min (interior_mono subset_lowerClosure) (lowerClosure s).lower.interior end NormedOrderedGroup /-! ### `ℝⁿ` -/ section Finite variable [Finite ι] {s : Set (ι → ℝ)} {x y : ι → ℝ} theorem IsUpperSet.mem_interior_of_forall_lt (hs : IsUpperSet s) (hx : x ∈ closure s) (h : ∀ i, x i < y i) : y ∈ interior s := by cases nonempty_fintype ι obtain ⟨ε, hε, hxy⟩ := Pi.exists_forall_pos_add_lt h obtain ⟨z, hz, hxz⟩ := Metric.mem_closure_iff.1 hx _ hε rw [dist_pi_lt_iff hε] at hxz have hyz : ∀ i, z i < y i := by refine fun i => (hxy _).trans_le' (sub_le_iff_le_add'.1 <| (le_abs_self _).trans ?_) rw [← Real.norm_eq_abs, ← dist_eq_norm'] exact (hxz _).le obtain ⟨δ, hδ, hyz⟩ := Pi.exists_forall_pos_add_lt hyz refine mem_interior.2 ⟨ball y δ, ?_, isOpen_ball, mem_ball_self hδ⟩ rintro w hw refine hs (fun i => ?_) hz simp_rw [ball_pi _ hδ, Real.ball_eq_Ioo] at hw exact ((lt_sub_iff_add_lt.2 <| hyz _).trans (hw _ <| mem_univ _).1).le theorem IsLowerSet.mem_interior_of_forall_lt (hs : IsLowerSet s) (hx : x ∈ closure s) (h : ∀ i, y i < x i) : y ∈ interior s := by cases nonempty_fintype ι obtain ⟨ε, hε, hxy⟩ := Pi.exists_forall_pos_add_lt h obtain ⟨z, hz, hxz⟩ := Metric.mem_closure_iff.1 hx _ hε rw [dist_pi_lt_iff hε] at hxz have hyz : ∀ i, y i < z i := by refine fun i => (lt_sub_iff_add_lt.2 <| hxy _).trans_le (sub_le_comm.1 <| (le_abs_self _).trans ?_) rw [← Real.norm_eq_abs, ← dist_eq_norm] exact (hxz _).le obtain ⟨δ, hδ, hyz⟩ := Pi.exists_forall_pos_add_lt hyz refine mem_interior.2 ⟨ball y δ, ?_, isOpen_ball, mem_ball_self hδ⟩ rintro w hw refine hs (fun i => ?_) hz simp_rw [ball_pi _ hδ, Real.ball_eq_Ioo] at hw exact ((hw _ <| mem_univ _).2.trans <| hyz _).le end Finite section Fintype variable [Fintype ι] {s : Set (ι → ℝ)} {a₁ a₂ b₁ b₂ x y : ι → ℝ} {δ : ℝ} -- TODO: Generalise those lemmas so that they also apply to `ℝ` and `EuclideanSpace ι ℝ` lemma dist_inf_sup_pi (x y : ι → ℝ) : dist (x ⊓ y) (x ⊔ y) = dist x y := by refine congr_arg NNReal.toReal (Finset.sup_congr rfl fun i _ ↦ ?_) simp only [Real.nndist_eq', max_sub_min_eq_abs, Pi.inf_apply, Pi.sup_apply, Real.nnabs_of_nonneg, abs_nonneg, Real.toNNReal_abs] lemma dist_mono_left_pi : MonotoneOn (dist · y) (Ici y) := by refine fun y₁ hy₁ y₂ hy₂ hy ↦ NNReal.coe_le_coe.2 (Finset.sup_mono_fun fun i _ ↦ ?_) rw [Real.nndist_eq, Real.nnabs_of_nonneg (sub_nonneg_of_le (‹y ≤ _› i : y i ≤ y₁ i)), Real.nndist_eq, Real.nnabs_of_nonneg (sub_nonneg_of_le (‹y ≤ _› i : y i ≤ y₂ i))] exact Real.toNNReal_mono (sub_le_sub_right (hy _) _) lemma dist_mono_right_pi : MonotoneOn (dist x) (Ici x) := by simpa only [dist_comm _ x] using dist_mono_left_pi (y := x) lemma dist_anti_left_pi : AntitoneOn (dist · y) (Iic y) := by refine fun y₁ hy₁ y₂ hy₂ hy ↦ NNReal.coe_le_coe.2 (Finset.sup_mono_fun fun i _ ↦ ?_) rw [Real.nndist_eq', Real.nnabs_of_nonneg (sub_nonneg_of_le (‹_ ≤ y› i : y₂ i ≤ y i)), Real.nndist_eq', Real.nnabs_of_nonneg (sub_nonneg_of_le (‹_ ≤ y› i : y₁ i ≤ y i))] exact Real.toNNReal_mono (sub_le_sub_left (hy _) _) lemma dist_anti_right_pi : AntitoneOn (dist x) (Iic x) := by simpa only [dist_comm] using dist_anti_left_pi (y := x) lemma dist_le_dist_of_le_pi (ha : a₂ ≤ a₁) (h₁ : a₁ ≤ b₁) (hb : b₁ ≤ b₂) : dist a₁ b₁ ≤ dist a₂ b₂ := (dist_mono_right_pi h₁ (h₁.trans hb) hb).trans <| dist_anti_left_pi (ha.trans <| h₁.trans hb) (h₁.trans hb) ha theorem IsUpperSet.exists_subset_ball (hs : IsUpperSet s) (hx : x ∈ closure s) (hδ : 0 < δ) : ∃ y, closedBall y (δ / 4) ⊆ closedBall x δ ∧ closedBall y (δ / 4) ⊆ interior s := by refine ⟨x + const _ (3 / 4 * δ), closedBall_subset_closedBall' ?_, ?_⟩ · rw [dist_self_add_left] refine (add_le_add_left (pi_norm_const_le <| 3 / 4 * δ) _).trans_eq ?_ simp only [norm_mul, norm_div, Real.norm_eq_abs] simp only [zero_lt_three, abs_of_pos, zero_lt_four, abs_of_pos hδ] ring obtain ⟨y, hy, hxy⟩ := Metric.mem_closure_iff.1 hx _ (div_pos hδ zero_lt_four) refine fun z hz => hs.mem_interior_of_forall_lt (subset_closure hy) fun i => ?_ rw [mem_closedBall, dist_eq_norm'] at hz rw [dist_eq_norm] at hxy replace hxy := (norm_le_pi_norm _ i).trans hxy.le replace hz := (norm_le_pi_norm _ i).trans hz dsimp at hxy hz rw [abs_sub_le_iff] at hxy hz linarith theorem IsLowerSet.exists_subset_ball (hs : IsLowerSet s) (hx : x ∈ closure s) (hδ : 0 < δ) : ∃ y, closedBall y (δ / 4) ⊆ closedBall x δ ∧ closedBall y (δ / 4) ⊆ interior s := by refine ⟨x - const _ (3 / 4 * δ), closedBall_subset_closedBall' ?_, ?_⟩ · rw [dist_self_sub_left] refine (add_le_add_left (pi_norm_const_le <| 3 / 4 * δ) _).trans_eq ?_ simp only [norm_mul, norm_div, Real.norm_eq_abs, zero_lt_three, abs_of_pos, zero_lt_four, abs_of_pos hδ] ring obtain ⟨y, hy, hxy⟩ := Metric.mem_closure_iff.1 hx _ (div_pos hδ zero_lt_four) refine fun z hz => hs.mem_interior_of_forall_lt (subset_closure hy) fun i => ?_ rw [mem_closedBall, dist_eq_norm'] at hz rw [dist_eq_norm] at hxy replace hxy := (norm_le_pi_norm _ i).trans hxy.le replace hz := (norm_le_pi_norm _ i).trans hz dsimp at hxy hz rw [abs_sub_le_iff] at hxy hz linarith end Fintype section Finite variable [Finite ι] {s : Set (ι → ℝ)} /-! #### Note The closure and frontier of an antichain might not be antichains. Take for example the union of the open segments from `(0, 2)` to `(1, 1)` and from `(2, 1)` to `(3, 0)`. `(1, 1)` and `(2, 1)` are comparable and both in the closure/frontier. -/ protected lemma IsClosed.upperClosure_pi (hs : IsClosed s) (hs' : BddBelow s) : IsClosed (upperClosure s : Set (ι → ℝ)) := by cases nonempty_fintype ι refine IsSeqClosed.isClosed fun f x hf hx ↦ ?_ choose g hg hgf using hf obtain ⟨a, ha⟩ := hx.bddAbove_range obtain ⟨b, hb, φ, hφ, hbf⟩ := tendsto_subseq_of_bounded (hs'.isBounded_inter bddAbove_Iic) fun n ↦ ⟨hg n, (hgf _).trans <| ha <| mem_range_self _⟩ exact ⟨b, closure_minimal inter_subset_left hs hb, le_of_tendsto_of_tendsto' hbf (hx.comp hφ.tendsto_atTop) fun _ ↦ hgf _⟩ protected lemma IsClosed.lowerClosure_pi (hs : IsClosed s) (hs' : BddAbove s) : IsClosed (lowerClosure s : Set (ι → ℝ)) := by cases nonempty_fintype ι refine IsSeqClosed.isClosed fun f x hf hx ↦ ?_ choose g hg hfg using hf haveI : BoundedGENhdsClass ℝ := by infer_instance obtain ⟨a, ha⟩ := hx.bddBelow_range obtain ⟨b, hb, φ, hφ, hbf⟩ := tendsto_subseq_of_bounded (hs'.isBounded_inter bddBelow_Ici) fun n ↦ ⟨hg n, (ha <| mem_range_self _).trans <| hfg _⟩ exact ⟨b, closure_minimal inter_subset_left hs hb, le_of_tendsto_of_tendsto' (hx.comp hφ.tendsto_atTop) hbf fun _ ↦ hfg _⟩ protected lemma IsClopen.upperClosure_pi (hs : IsClopen s) (hs' : BddBelow s) : IsClopen (upperClosure s : Set (ι → ℝ)) := ⟨hs.1.upperClosure_pi hs', hs.2.upperClosure⟩ protected lemma IsClopen.lowerClosure_pi (hs : IsClopen s) (hs' : BddAbove s) : IsClopen (lowerClosure s : Set (ι → ℝ)) := ⟨hs.1.lowerClosure_pi hs', hs.2.lowerClosure⟩ lemma closure_upperClosure_comm_pi (hs : BddBelow s) : closure (upperClosure s : Set (ι → ℝ)) = upperClosure (closure s) := (closure_minimal (upperClosure_anti subset_closure) <| isClosed_closure.upperClosure_pi hs.closure).antisymm <| upperClosure_min (closure_mono subset_upperClosure) (upperClosure s).upper.closure lemma closure_lowerClosure_comm_pi (hs : BddAbove s) : closure (lowerClosure s : Set (ι → ℝ)) = lowerClosure (closure s) := (closure_minimal (lowerClosure_mono subset_closure) <| isClosed_closure.lowerClosure_pi hs.closure).antisymm <| lowerClosure_min (closure_mono subset_lowerClosure) (lowerClosure s).lower.closure end Finite
ExtrClosure.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.Order.OrderClosed import Mathlib.Topology.Order.LocalExtr /-! # Maximum/minimum on the closure of a set In this file we prove several versions of the following statement: if `f : X → Y` has a (local or not) maximum (or minimum) on a set `s` at a point `a` and is continuous on the closure of `s`, then `f` has an extremum of the same type on `Closure s` at `a`. -/ open Filter Set open Topology variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [Preorder Y] [OrderClosedTopology Y] {f : X → Y} {s : Set X} {a : X} protected theorem IsMaxOn.closure (h : IsMaxOn f s a) (hc : ContinuousOn f (closure s)) : IsMaxOn f (closure s) a := fun x hx => ContinuousWithinAt.closure_le hx ((hc x hx).mono subset_closure) continuousWithinAt_const h protected theorem IsMinOn.closure (h : IsMinOn f s a) (hc : ContinuousOn f (closure s)) : IsMinOn f (closure s) a := h.dual.closure hc protected theorem IsExtrOn.closure (h : IsExtrOn f s a) (hc : ContinuousOn f (closure s)) : IsExtrOn f (closure s) a := h.elim (fun h => Or.inl <| h.closure hc) fun h => Or.inr <| h.closure hc protected theorem IsLocalMaxOn.closure (h : IsLocalMaxOn f s a) (hc : ContinuousOn f (closure s)) : IsLocalMaxOn f (closure s) a := by rcases mem_nhdsWithin.1 h with ⟨U, Uo, aU, hU⟩ refine mem_nhdsWithin.2 ⟨U, Uo, aU, ?_⟩ rintro x ⟨hxU, hxs⟩ refine ContinuousWithinAt.closure_le ?_ ?_ continuousWithinAt_const hU · rwa [mem_closure_iff_nhdsWithin_neBot, nhdsWithin_inter_of_mem, ← mem_closure_iff_nhdsWithin_neBot] exact nhdsWithin_le_nhds (Uo.mem_nhds hxU) · exact (hc _ hxs).mono (inter_subset_right.trans subset_closure) protected theorem IsLocalMinOn.closure (h : IsLocalMinOn f s a) (hc : ContinuousOn f (closure s)) : IsLocalMinOn f (closure s) a := IsLocalMaxOn.closure h.dual hc protected theorem IsLocalExtrOn.closure (h : IsLocalExtrOn f s a) (hc : ContinuousOn f (closure s)) : IsLocalExtrOn f (closure s) a := h.elim (fun h => Or.inl <| h.closure hc) fun h => Or.inr <| h.closure hc
ParallelComp.lean
/- Copyright (c) 2024 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.MeasureTheory.Measure.Prod import Mathlib.Probability.Kernel.Composition.MapComap import Mathlib.Probability.Kernel.MeasurableLIntegral /-! # Parallel composition of kernels Two kernels `κ : Kernel α β` and `η : Kernel γ δ` can be applied in parallel to give a kernel `κ ∥ₖ η` from `α × γ` to `β × δ`: `(κ ∥ₖ η) (a, c) = (κ a).prod (η c)`. ## Main definitions * `parallelComp (κ : Kernel α β) (η : Kernel γ δ) : Kernel (α × γ) (β × δ)`: parallel composition of two s-finite kernels. We define a notation `κ ∥ₖ η = parallelComp κ η`. `∫⁻ bd, g bd ∂(κ ∥ₖ η) ac = ∫⁻ b, ∫⁻ d, g (b, d) ∂η ac.2 ∂κ ac.1` ## Notations * `κ ∥ₖ η = ProbabilityTheory.Kernel.parallelComp κ η` -/ open MeasureTheory open scoped ENNReal namespace ProbabilityTheory.Kernel variable {α β γ δ : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} {mγ : MeasurableSpace γ} {mδ : MeasurableSpace δ} {κ : Kernel α β} {η : Kernel γ δ} {x : α × γ} open Classical in /-- Parallel product of two kernels. -/ noncomputable irreducible_def parallelComp (κ : Kernel α β) (η : Kernel γ δ) : Kernel (α × γ) (β × δ) := if h : IsSFiniteKernel κ ∧ IsSFiniteKernel η then { toFun := fun x ↦ (κ x.1).prod (η x.2) measurable' := by have hκ := h.1 have hη := h.2 refine Measure.measurable_of_measurable_coe _ fun s hs ↦ ?_ simp_rw [Measure.prod_apply hs] refine Measurable.lintegral_kernel_prod_right' (f := fun y ↦ prodMkLeft α η y.1 (Prod.mk y.2 ⁻¹' s)) (κ := prodMkRight γ κ) ?_ have : (fun y ↦ prodMkLeft α η y.1 (Prod.mk y.2 ⁻¹' s)) = fun y ↦ prodMkRight β (prodMkLeft α η) y (Prod.mk y.2 ⁻¹' s) := rfl rw [this] exact measurable_kernel_prodMk_left (measurable_fst.snd.prodMk measurable_snd hs) } else 0 @[inherit_doc] scoped[ProbabilityTheory] infixl:100 " ∥ₖ " => ProbabilityTheory.Kernel.parallelComp @[simp] lemma parallelComp_of_not_isSFiniteKernel_left (η : Kernel γ δ) (h : ¬ IsSFiniteKernel κ) : κ ∥ₖ η = 0 := by rw [parallelComp, dif_neg (not_and_of_not_left _ h)] @[simp] lemma parallelComp_of_not_isSFiniteKernel_right (κ : Kernel α β) (h : ¬ IsSFiniteKernel η) : κ ∥ₖ η = 0 := by rw [parallelComp, dif_neg (not_and_of_not_right _ h)] lemma parallelComp_apply (κ : Kernel α β) [IsSFiniteKernel κ] (η : Kernel γ δ) [IsSFiniteKernel η] (x : α × γ) : (κ ∥ₖ η) x = (κ x.1).prod (η x.2) := by rw [parallelComp, dif_pos ⟨inferInstance, inferInstance⟩, coe_mk] lemma parallelComp_apply' [IsSFiniteKernel κ] [IsSFiniteKernel η] {s : Set (β × δ)} (hs : MeasurableSet s) : (κ ∥ₖ η) x s = ∫⁻ b, η x.2 (Prod.mk b ⁻¹' s) ∂κ x.1 := by rw [parallelComp_apply, Measure.prod_apply hs] @[simp] lemma parallelComp_apply_univ [IsSFiniteKernel κ] [IsSFiniteKernel η] : (κ ∥ₖ η) x Set.univ = κ x.1 Set.univ * η x.2 Set.univ := by rw [parallelComp_apply, Measure.prod_apply .univ, mul_comm] simp @[simp] lemma parallelComp_zero_left (η : Kernel γ δ) : (0 : Kernel α β) ∥ₖ η = 0 := by by_cases h : IsSFiniteKernel η · ext; simp [parallelComp_apply] · exact parallelComp_of_not_isSFiniteKernel_right _ h @[simp] lemma parallelComp_zero_right (κ : Kernel α β) : κ ∥ₖ (0 : Kernel γ δ) = 0 := by by_cases h : IsSFiniteKernel κ · ext; simp [parallelComp_apply] · exact parallelComp_of_not_isSFiniteKernel_left _ h lemma lintegral_parallelComp [IsSFiniteKernel κ] [IsSFiniteKernel η] (ac : α × γ) {g : β × δ → ℝ≥0∞} (hg : Measurable g) : ∫⁻ bd, g bd ∂(κ ∥ₖ η) ac = ∫⁻ b, ∫⁻ d, g (b, d) ∂η ac.2 ∂κ ac.1 := by rw [parallelComp_apply, MeasureTheory.lintegral_prod _ hg.aemeasurable] lemma lintegral_parallelComp_symm [IsSFiniteKernel κ] [IsSFiniteKernel η] (ac : α × γ) {g : β × δ → ℝ≥0∞} (hg : Measurable g) : ∫⁻ bd, g bd ∂(κ ∥ₖ η) ac = ∫⁻ d, ∫⁻ b, g (b, d) ∂κ ac.1 ∂η ac.2 := by rw [parallelComp_apply, MeasureTheory.lintegral_prod_symm _ hg.aemeasurable] lemma parallelComp_sum_left {ι : Type*} [Countable ι] (κ : ι → Kernel α β) [∀ i, IsSFiniteKernel (κ i)] (η : Kernel γ δ) : Kernel.sum κ ∥ₖ η = Kernel.sum fun i ↦ κ i ∥ₖ η := by by_cases h : IsSFiniteKernel η swap; · simp [h] ext x simp_rw [Kernel.sum_apply, parallelComp_apply, Kernel.sum_apply, Measure.prod_sum_left] lemma parallelComp_sum_right {ι : Type*} [Countable ι] (κ : Kernel α β) (η : ι → Kernel γ δ) [∀ i, IsSFiniteKernel (η i)] : κ ∥ₖ Kernel.sum η = Kernel.sum fun i ↦ κ ∥ₖ η i := by by_cases h : IsSFiniteKernel κ swap; · simp [h] ext x simp_rw [Kernel.sum_apply, parallelComp_apply, Kernel.sum_apply, Measure.prod_sum_right] instance [IsMarkovKernel κ] [IsMarkovKernel η] : IsMarkovKernel (κ ∥ₖ η) := ⟨fun x ↦ ⟨by simp [parallelComp_apply_univ]⟩⟩ instance [IsZeroOrMarkovKernel κ] [IsZeroOrMarkovKernel η] : IsZeroOrMarkovKernel (κ ∥ₖ η) := by obtain rfl | _ := eq_zero_or_isMarkovKernel κ <;> obtain rfl | _ := eq_zero_or_isMarkovKernel η all_goals simpa using by infer_instance instance [IsFiniteKernel κ] [IsFiniteKernel η] : IsFiniteKernel (κ ∥ₖ η) := by refine ⟨⟨IsFiniteKernel.bound κ * IsFiniteKernel.bound η, ENNReal.mul_lt_top (IsFiniteKernel.bound_lt_top κ) (IsFiniteKernel.bound_lt_top η), fun a ↦ ?_⟩⟩ calc (κ ∥ₖ η) a Set.univ _ = κ a.1 Set.univ * η a.2 Set.univ := parallelComp_apply_univ _ ≤ IsFiniteKernel.bound κ * IsFiniteKernel.bound η := by gcongr · exact measure_le_bound κ a.1 Set.univ · exact measure_le_bound η a.2 Set.univ instance : IsSFiniteKernel (κ ∥ₖ η) := by by_cases h : IsSFiniteKernel κ swap · simp only [h, not_false_eq_true, parallelComp_of_not_isSFiniteKernel_left] infer_instance by_cases h : IsSFiniteKernel η swap · simp only [h, not_false_eq_true, parallelComp_of_not_isSFiniteKernel_right] infer_instance simp_rw [← kernel_sum_seq κ, ← kernel_sum_seq η, parallelComp_sum_left, parallelComp_sum_right] infer_instance end ProbabilityTheory.Kernel
Normalize.lean
/- Copyright (c) 2024 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno -/ import Lean.Meta.AppBuilder import Mathlib.Tactic.CategoryTheory.Coherence.Datatypes /-! # Normalization of 2-morphisms in bicategories This file provides a function that normalizes 2-morphisms in bicategories. The function also used to normalize morphisms in monoidal categories. This is used in the string diagram widget given in `Mathlib/Tactic/StringDiagram.lean`, as well as `monoidal` and `bicategory` tactics. We say that the 2-morphism `η` in a bicategory is in normal form if 1. `η` is of the form `α₀ ≫ η₀ ≫ α₁ ≫ η₁ ≫ ... αₘ ≫ ηₘ ≫ αₘ₊₁` where each `αᵢ` is a structural 2-morphism (consisting of associators and unitors), 2. each `ηᵢ` is a non-structural 2-morphism of the form `f₁ ◁ ... ◁ fₙ ◁ θ`, and 3. `θ` is of the form `ι₁ ◫ ... ◫ ιₗ`, and 4. each `ιᵢ` is of the form `κ ▷ g₁ ▷ ... ▷ gₖ`. Note that the horizontal composition `◫` is not currently defined for bicategories. In the monoidal category setting, the horizontal composition is defined as the `tensorHom`, denoted by `⊗`. Note that the structural morphisms `αᵢ` are not necessarily normalized, as the main purpose is to get a list of the non-structural morphisms out. Currently, the primary application of the normalization tactic in mind is drawing string diagrams, which are graphical representations of morphisms in monoidal categories, in the infoview. When drawing string diagrams, we often ignore associators and unitors (i.e., drawing morphisms in strict monoidal categories). On the other hand, in Lean, it is considered difficult to formalize the concept of strict monoidal categories due to the feature of dependent type theory. The normalization tactic can remove associators and unitors from the expression, extracting the necessary data for drawing string diagrams. The string diagrams widget is to use Penrose (https://github.com/penrose) via ProofWidget. However, it should be noted that the normalization procedure in this file does not rely on specific settings, allowing for broader application. Future plans include the following. At least I (Yuma) would like to work on these in the future, but it might not be immediate. If anyone is interested, I would be happy to discuss. - Currently, the string diagrams widget only do drawing. It would be better they also generate proofs. That is, by manipulating the string diagrams displayed in the infoview with a mouse to generate proofs. In https://github.com/leanprover-community/mathlib4/pull/10581, the string diagram widget only uses the morphisms generated by the normalization tactic and does not use proof terms ensuring that the original morphism and the normalized morphism are equal. Proof terms will be necessary for proof generation. - There is also the possibility of using homotopy.io (https://github.com/homotopy-io), a graphical proof assistant for category theory, from Lean. At this point, I have very few ideas regarding this approach. ## Main definitions - `Tactic.BicategoryLike.eval`: Given a Lean expression `e` that represents a morphism in a monoidal category, this function returns a pair of `⟨e', pf⟩` where `e'` is the normalized expression of `e` and `pf` is a proof that `e = e'`. -/ open Lean Meta namespace Mathlib.Tactic.BicategoryLike section /-- Expressions of the form `η ▷ f₁ ▷ ... ▷ fₙ`. -/ inductive WhiskerRight : Type /-- Construct the expression for an atomic 2-morphism. -/ | of (η : Atom) : WhiskerRight /-- Construct the expression for `η ▷ f`. -/ | whisker (e : Mor₂) (η : WhiskerRight) (f : Atom₁) : WhiskerRight deriving Inhabited /-- The underlying `Mor₂` term of a `WhiskerRight` term. -/ def WhiskerRight.e : WhiskerRight → Mor₂ | .of η => .of η | .whisker e .. => e /-- Expressions of the form `η₁ ⊗ ... ⊗ ηₙ`. -/ inductive HorizontalComp : Type | of (η : WhiskerRight) : HorizontalComp | cons (e : Mor₂) (η : WhiskerRight) (ηs : HorizontalComp) : HorizontalComp deriving Inhabited /-- The underlying `Mor₂` term of a `HorizontalComp` term. -/ def HorizontalComp.e : HorizontalComp → Mor₂ | .of η => η.e | .cons e .. => e /-- Expressions of the form `f₁ ◁ ... ◁ fₙ ◁ η`. -/ inductive WhiskerLeft : Type /-- Construct the expression for a right-whiskered 2-morphism. -/ | of (η : HorizontalComp) : WhiskerLeft /-- Construct the expression for `f ◁ η`. -/ | whisker (e : Mor₂) (f : Atom₁) (η : WhiskerLeft) : WhiskerLeft deriving Inhabited /-- The underlying `Mor₂` term of a `WhiskerLeft` term. -/ def WhiskerLeft.e : WhiskerLeft → Mor₂ | .of η => η.e | .whisker e .. => e /-- Whether a given 2-isomorphism is structural or not. -/ def Mor₂Iso.isStructural (α : Mor₂Iso) : Bool := match α with | .structuralAtom _ => true | .comp _ _ _ _ η θ => η.isStructural && θ.isStructural | .whiskerLeft _ _ _ _ η => η.isStructural | .whiskerRight _ _ _ η _ => η.isStructural | .horizontalComp _ _ _ _ _ η θ => η.isStructural && θ.isStructural | .inv _ _ _ η => η.isStructural | .coherenceComp _ _ _ _ _ _ η θ => η.isStructural && θ.isStructural | .of _ => false /-- Expressions for structural isomorphisms. We do not impose the condition `isStructural` since it is not needed to write the tactic. -/ abbrev Structural := Mor₂Iso /-- Normalized expressions for 2-morphisms. -/ inductive NormalExpr : Type /-- Construct the expression for a structural 2-morphism. -/ | nil (e : Mor₂) (α : Structural) : NormalExpr /-- Construct the normalized expression of a 2-morphism `α ≫ η ≫ ηs` recursively. -/ | cons (e : Mor₂) (α : Structural) (η : WhiskerLeft) (ηs : NormalExpr) : NormalExpr deriving Inhabited /-- The underlying `Mor₂` term of a `NormalExpr` term. -/ def NormalExpr.e : NormalExpr → Mor₂ | .nil e .. => e | .cons e .. => e /-- A monad equipped with the ability to construct `WhiskerRight` terms. -/ class MonadWhiskerRight (m : Type → Type) where /-- The expression for the right whiskering `η ▷ f`. -/ whiskerRightM (η : WhiskerRight) (f : Atom₁) : m WhiskerRight /-- A monad equipped with the ability to construct `HorizontalComp` terms. -/ class MonadHorizontalComp (m : Type → Type) extends MonadWhiskerRight m where /-- The expression for the horizontal composition `η ◫ ηs`. -/ hConsM (η : WhiskerRight) (ηs : HorizontalComp) : m HorizontalComp /-- A monad equipped with the ability to construct `WhiskerLeft` terms. -/ class MonadWhiskerLeft (m : Type → Type) extends MonadHorizontalComp m where /-- The expression for the left whiskering `f ▷ η`. -/ whiskerLeftM (f : Atom₁) (η : WhiskerLeft) : m WhiskerLeft /-- A monad equipped with the ability to construct `NormalExpr` terms. -/ class MonadNormalExpr (m : Type → Type) extends MonadWhiskerLeft m where /-- The expression for the structural 2-morphism `α`. -/ nilM (α : Structural) : m NormalExpr /-- The expression for the normalized 2-morphism `α ≫ η ≫ ηs`. -/ consM (headStructural : Structural) (η : WhiskerLeft) (ηs : NormalExpr) : m NormalExpr variable {m : Type → Type} [Monad m] open MonadMor₁ /-- The domain of a 2-morphism. -/ def WhiskerRight.srcM [MonadMor₁ m] : WhiskerRight → m Mor₁ | WhiskerRight.of η => return η.src | WhiskerRight.whisker _ η f => do comp₁M (← η.srcM) (.of f) /-- The codomain of a 2-morphism. -/ def WhiskerRight.tgtM [MonadMor₁ m] : WhiskerRight → m Mor₁ | WhiskerRight.of η => return η.tgt | WhiskerRight.whisker _ η f => do comp₁M (← η.tgtM) (.of f) /-- The domain of a 2-morphism. -/ def HorizontalComp.srcM [MonadMor₁ m] : HorizontalComp → m Mor₁ | HorizontalComp.of η => η.srcM | HorizontalComp.cons _ η ηs => do comp₁M (← η.srcM) (← ηs.srcM) /-- The codomain of a 2-morphism. -/ def HorizontalComp.tgtM [MonadMor₁ m] : HorizontalComp → m Mor₁ | HorizontalComp.of η => η.tgtM | HorizontalComp.cons _ η ηs => do comp₁M (← η.tgtM) (← ηs.tgtM) /-- The domain of a 2-morphism. -/ def WhiskerLeft.srcM [MonadMor₁ m] : WhiskerLeft → m Mor₁ | WhiskerLeft.of η => η.srcM | WhiskerLeft.whisker _ f η => do comp₁M (.of f) (← η.srcM) /-- The codomain of a 2-morphism. -/ def WhiskerLeft.tgtM [MonadMor₁ m] : WhiskerLeft → m Mor₁ | WhiskerLeft.of η => η.tgtM | WhiskerLeft.whisker _ f η => do comp₁M (.of f) (← η.tgtM) /-- The domain of a 2-morphism. -/ def NormalExpr.srcM [MonadMor₁ m] : NormalExpr → m Mor₁ | NormalExpr.nil _ η => η.srcM | NormalExpr.cons _ α _ _ => α.srcM /-- The codomain of a 2-morphism. -/ def NormalExpr.tgtM [MonadMor₁ m] : NormalExpr → m Mor₁ | NormalExpr.nil _ η => η.tgtM | NormalExpr.cons _ _ _ ηs => ηs.tgtM namespace NormalExpr variable [MonadMor₂Iso m] [MonadNormalExpr m] /-- The identity 2-morphism as a term of `normalExpr`. -/ def idM (f : Mor₁) : m NormalExpr := do MonadNormalExpr.nilM <| .structuralAtom <| ← MonadMor₂Iso.id₂M f /-- The associator as a term of `normalExpr`. -/ def associatorM (f g h : Mor₁) : m NormalExpr := do MonadNormalExpr.nilM <| .structuralAtom <| ← MonadMor₂Iso.associatorM f g h /-- The inverse of the associator as a term of `normalExpr`. -/ def associatorInvM (f g h : Mor₁) : m NormalExpr := do MonadNormalExpr.nilM <| ← MonadMor₂Iso.symmM <| .structuralAtom <| ← MonadMor₂Iso.associatorM f g h /-- The left unitor as a term of `normalExpr`. -/ def leftUnitorM (f : Mor₁) : m NormalExpr := do MonadNormalExpr.nilM <| .structuralAtom <| ← MonadMor₂Iso.leftUnitorM f /-- The inverse of the left unitor as a term of `normalExpr`. -/ def leftUnitorInvM (f : Mor₁) : m NormalExpr := do MonadNormalExpr.nilM <| ← MonadMor₂Iso.symmM <| .structuralAtom <| ← MonadMor₂Iso.leftUnitorM f /-- The right unitor as a term of `normalExpr`. -/ def rightUnitorM (f : Mor₁) : m NormalExpr := do MonadNormalExpr.nilM <| .structuralAtom <| ← MonadMor₂Iso.rightUnitorM f /-- The inverse of the right unitor as a term of `normalExpr`. -/ def rightUnitorInvM (f : Mor₁) : m NormalExpr := do MonadNormalExpr.nilM <| ← MonadMor₂Iso.symmM <| .structuralAtom <| ← MonadMor₂Iso.rightUnitorM f /-- Construct a `NormalExpr` expression from a `WhiskerLeft` expression. -/ def ofM [MonadMor₁ m] (η : WhiskerLeft) : m NormalExpr := do MonadNormalExpr.consM ((.structuralAtom <| ← MonadMor₂Iso.id₂M (← η.srcM))) η (← MonadNormalExpr.nilM ((.structuralAtom <| ← MonadMor₂Iso.id₂M (← η.tgtM)))) /-- Construct a `NormalExpr` expression from a Lean expression for an atomic 2-morphism. -/ def ofAtomM [MonadMor₁ m] (η : Atom) : m NormalExpr := NormalExpr.ofM <| .of <| .of <| .of η end NormalExpr /-- Convert a `NormalExpr` expression into a list of `WhiskerLeft` expressions. -/ def NormalExpr.toList : NormalExpr → List WhiskerLeft | NormalExpr.nil _ _ => [] | NormalExpr.cons _ _ η ηs => η :: NormalExpr.toList ηs end section /-- The result of evaluating an expression into normal form. -/ structure Eval.Result where /-- The normalized expression of the 2-morphism. -/ expr : NormalExpr /-- The proof that the normalized expression is equal to the original expression. -/ proof : Expr deriving Inhabited variable {m : Type → Type} /-- Evaluate the expression `α ≫ β`. -/ class MkEvalComp (m : Type → Type) where /-- Evaluate `α ≫ β` -/ mkEvalCompNilNil (α β : Structural) : m Expr /-- Evaluate `α ≫ (β ≫ η ≫ ηs)` -/ mkEvalCompNilCons (α β : Structural) (η : WhiskerLeft) (ηs : NormalExpr) : m Expr /-- Evaluate `(α ≫ η ≫ ηs) ≫ θ` -/ mkEvalCompCons (α : Structural) (η : WhiskerLeft) (ηs θ ι : NormalExpr) (e_η : Expr) : m Expr /-- Evaluatte the expression `f ◁ η`. -/ class MkEvalWhiskerLeft (m : Type → Type) where /-- Evaluatte `f ◁ α` -/ mkEvalWhiskerLeftNil (f : Mor₁) (α : Structural) : m Expr /-- Evaluate `f ◁ (α ≫ η ≫ ηs)`. -/ mkEvalWhiskerLeftOfCons (f : Atom₁) (α : Structural) (η : WhiskerLeft) (ηs θ : NormalExpr) (e_θ : Expr) : m Expr /-- Evaluate `(f ≫ g) ◁ η` -/ mkEvalWhiskerLeftComp (f g : Mor₁) (η η₁ η₂ η₃ η₄ : NormalExpr) (e_η₁ e_η₂ e_η₃ e_η₄ : Expr) : m Expr /-- Evaluate `𝟙 _ ◁ η` -/ mkEvalWhiskerLeftId (η η₁ η₂ : NormalExpr) (e_η₁ e_η₂ : Expr) : m Expr /-- Evaluate the expression `η ▷ f`. -/ class MkEvalWhiskerRight (m : Type → Type) where /-- Evaluate `η ▷ f` -/ mkEvalWhiskerRightAuxOf (η : WhiskerRight) (f : Atom₁) : m Expr /-- Evaluate `(η ◫ ηs) ▷ f` -/ mkEvalWhiskerRightAuxCons (f : Atom₁) (η : WhiskerRight) (ηs : HorizontalComp) (ηs' η₁ η₂ η₃ : NormalExpr) (e_ηs' e_η₁ e_η₂ e_η₃ : Expr) : m Expr /-- Evaluate `α ▷ f` -/ mkEvalWhiskerRightNil (α : Structural) (f : Mor₁) : m Expr /-- Evaluate ` (α ≫ η ≫ ηs) ▷ j` -/ mkEvalWhiskerRightConsOfOf (f : Atom₁) (α : Structural) (η : HorizontalComp) (ηs ηs₁ η₁ η₂ η₃ : NormalExpr) (e_ηs₁ e_η₁ e_η₂ e_η₃ : Expr) : m Expr /-- Evaluate `(α ≫ (f ◁ η) ≫ ηs) ▷ g` -/ mkEvalWhiskerRightConsWhisker (f : Atom₁) (g : Mor₁) (α : Structural) (η : WhiskerLeft) (ηs η₁ η₂ ηs₁ ηs₂ η₃ η₄ η₅ : NormalExpr) (e_η₁ e_η₂ e_ηs₁ e_ηs₂ e_η₃ e_η₄ e_η₅ : Expr) : m Expr /-- Evaluate `η ▷ (g ⊗ h)` -/ mkEvalWhiskerRightComp (g h : Mor₁) (η η₁ η₂ η₃ η₄ : NormalExpr) (e_η₁ e_η₂ e_η₃ e_η₄ : Expr) : m Expr /-- Evaluate `η ▷ 𝟙 _` -/ mkEvalWhiskerRightId (η η₁ η₂ : NormalExpr) (e_η₁ e_η₂ : Expr) : m Expr /-- Evaluate the expression `η ◫ θ`. -/ class MkEvalHorizontalComp (m : Type → Type) where /-- Evaluate `η ◫ θ` -/ mkEvalHorizontalCompAuxOf (η : WhiskerRight) (θ : HorizontalComp) : m Expr /-- Evaluate `(η ◫ ηs) ◫ θ` -/ mkEvalHorizontalCompAuxCons (η : WhiskerRight) (ηs θ : HorizontalComp) (ηθ η₁ ηθ₁ ηθ₂ : NormalExpr) (e_ηθ e_η₁ e_ηθ₁ e_ηθ₂ : Expr) : m Expr /-- Evaluate `(f ◁ η) ◫ θ` -/ mkEvalHorizontalCompAux'Whisker (f : Atom₁) (η θ : WhiskerLeft) (ηθ ηθ₁ ηθ₂ ηθ₃ : NormalExpr) (e_ηθ e_ηθ₁ e_ηθ₂ e_ηθ₃ : Expr) : m Expr /-- Evaluate `η ◫ (f ◁ θ)` -/ mkEvalHorizontalCompAux'OfWhisker (f : Atom₁) (η : HorizontalComp) (θ : WhiskerLeft) (η₁ ηθ ηθ₁ ηθ₂ : NormalExpr) (e_ηθ e_η₁ e_ηθ₁ e_ηθ₂ : Expr) : m Expr /-- Evaluate `α ◫ β` -/ mkEvalHorizontalCompNilNil (α β : Structural) : m Expr /-- Evaluate `α ◫ (β ≫ η ≫ ηs)` -/ mkEvalHorizontalCompNilCons (α β : Structural) (η : WhiskerLeft) (ηs η₁ ηs₁ η₂ η₃ : NormalExpr) (e_η₁ e_ηs₁ e_η₂ e_η₃ : Expr) : m Expr /-- Evaluate `(α ≫ η ≫ ηs) ◫ β` -/ mkEvalHorizontalCompConsNil (α β : Structural) (η : WhiskerLeft) (ηs : NormalExpr) (η₁ ηs₁ η₂ η₃ : NormalExpr) (e_η₁ e_ηs₁ e_η₂ e_η₃ : Expr) : m Expr /-- Evaluate `(α ≫ η ≫ ηs) ◫ (β ≫ θ ≫ θs)` -/ mkEvalHorizontalCompConsCons (α β : Structural) (η θ : WhiskerLeft) (ηs θs ηθ ηθs ηθ₁ ηθ₂ : NormalExpr) (e_ηθ e_ηθs e_ηθ₁ e_ηθ₂ : Expr) : m Expr /-- Evaluate the expression of a 2-morphism into a normalized form. -/ class MkEval (m : Type → Type) extends MkEvalComp m, MkEvalWhiskerLeft m, MkEvalWhiskerRight m, MkEvalHorizontalComp m where /-- Evaluate the expression `η ≫ θ` into a normalized form. -/ mkEvalComp (η θ : Mor₂) (η' θ' ηθ : NormalExpr) (e_η e_θ e_ηθ : Expr) : m Expr /-- Evaluate the expression `f ◁ η` into a normalized form. -/ mkEvalWhiskerLeft (f : Mor₁) (η : Mor₂) (η' θ : NormalExpr) (e_η e_θ : Expr) : m Expr /-- Evaluate the expression `η ▷ f` into a normalized form. -/ mkEvalWhiskerRight (η : Mor₂) (h : Mor₁) (η' θ : NormalExpr) (e_η e_θ : Expr) : m Expr /-- Evaluate the expression `η ◫ θ` into a normalized form. -/ mkEvalHorizontalComp (η θ : Mor₂) (η' θ' ι : NormalExpr) (e_η e_θ e_ι : Expr) : m Expr /-- Evaluate the atomic 2-morphism `η` into a normalized form. -/ mkEvalOf (η : Atom) : m Expr /-- Evaluate the expression `η ⊗≫ θ := η ≫ α ≫ θ` into a normalized form. -/ mkEvalMonoidalComp (η θ : Mor₂) (α : Structural) (η' θ' αθ ηαθ : NormalExpr) (e_η e_θ e_αθ e_ηαθ : Expr) : m Expr variable {ρ : Type} variable [MonadMor₂Iso (CoherenceM ρ)] [MonadNormalExpr (CoherenceM ρ)] [MkEval (CoherenceM ρ)] open MkEvalComp MonadMor₂Iso MonadNormalExpr /-- Evaluate the expression `α ≫ η` into a normalized form. -/ def evalCompNil (α : Structural) : NormalExpr → CoherenceM ρ Eval.Result | .nil _ β => do return ⟨← nilM (← comp₂M α β), ← mkEvalCompNilNil α β⟩ | .cons _ β η ηs => do return ⟨← consM (← comp₂M α β) η ηs, ← mkEvalCompNilCons α β η ηs⟩ /-- Evaluate the expression `η ≫ θ` into a normalized form. -/ def evalComp : NormalExpr → NormalExpr → CoherenceM ρ Eval.Result | .nil _ α, η => do evalCompNil α η | .cons _ α η ηs, θ => do let ⟨ι, e_ι⟩ ← evalComp ηs θ return ⟨← consM α η ι, ← mkEvalCompCons α η ηs θ ι e_ι⟩ open MkEvalWhiskerLeft variable [MonadMor₁ (CoherenceM ρ)] [MonadMor₂Iso (CoherenceM ρ)] /-- Evaluate the expression `f ◁ η` into a normalized form. -/ def evalWhiskerLeft : Mor₁ → NormalExpr → CoherenceM ρ Eval.Result | f, .nil _ α => do return ⟨← nilM (← whiskerLeftM f α), ← mkEvalWhiskerLeftNil f α⟩ | .of f, .cons _ α η ηs => do let η' ← MonadWhiskerLeft.whiskerLeftM f η let ⟨θ, e_θ⟩ ← evalWhiskerLeft (.of f) ηs let η'' ← consM (← whiskerLeftM (.of f) α) η' θ return ⟨η'', ← mkEvalWhiskerLeftOfCons f α η ηs θ e_θ⟩ | .comp _ f g, η => do let ⟨θ, e_θ⟩ ← evalWhiskerLeft g η let ⟨ι, e_ι⟩ ← evalWhiskerLeft f θ let h ← η.srcM let h' ← η.tgtM let ⟨ι', e_ι'⟩ ← evalComp ι (← NormalExpr.associatorInvM f g h') let ⟨ι'', e_ι''⟩ ← evalComp (← NormalExpr.associatorM f g h) ι' return ⟨ι'', ← mkEvalWhiskerLeftComp f g η θ ι ι' ι'' e_θ e_ι e_ι' e_ι''⟩ | .id _ _, η => do let f ← η.srcM let g ← η.tgtM let ⟨η', e_η'⟩ ← evalComp η (← NormalExpr.leftUnitorInvM g) let ⟨η'', e_η''⟩ ← evalComp (← NormalExpr.leftUnitorM f) η' return ⟨η'', ← mkEvalWhiskerLeftId η η' η'' e_η' e_η''⟩ open MkEvalWhiskerRight MkEvalHorizontalComp mutual /-- Evaluate the expression `η ▷ f` into a normalized form. -/ partial def evalWhiskerRightAux : HorizontalComp → Atom₁ → CoherenceM ρ Eval.Result | .of η, f => do let η' ← NormalExpr.ofM <| .of <| .of <| ← MonadWhiskerRight.whiskerRightM η f return ⟨η', ← mkEvalWhiskerRightAuxOf η f⟩ | .cons _ η ηs, f => do let ⟨ηs', e_ηs'⟩ ← evalWhiskerRightAux ηs f let ⟨η₁, e_η₁⟩ ← evalHorizontalComp (← NormalExpr.ofM <| .of <| .of η) ηs' let ⟨η₂, e_η₂⟩ ← evalComp η₁ (← NormalExpr.associatorInvM (← η.tgtM) (← ηs.tgtM) (.of f)) let ⟨η₃, e_η₃⟩ ← evalComp (← NormalExpr.associatorM (← η.srcM) (← ηs.srcM) (.of f)) η₂ return ⟨η₃, ← mkEvalWhiskerRightAuxCons f η ηs ηs' η₁ η₂ η₃ e_ηs' e_η₁ e_η₂ e_η₃⟩ /-- Evaluate the expression `η ▷ f` into a normalized form. -/ partial def evalWhiskerRight : NormalExpr → Mor₁ → CoherenceM ρ Eval.Result | .nil _ α, h => do return ⟨← nilM (← whiskerRightM α h), ← mkEvalWhiskerRightNil α h⟩ | .cons _ α (.of η) ηs, .of f => do let ⟨ηs₁, e_ηs₁⟩ ← evalWhiskerRight ηs (.of f) let ⟨η₁, e_η₁⟩ ← evalWhiskerRightAux η f let ⟨η₂, e_η₂⟩ ← evalComp η₁ ηs₁ let ⟨η₃, e_η₃⟩ ← evalCompNil (← whiskerRightM α (.of f)) η₂ return ⟨η₃, ← mkEvalWhiskerRightConsOfOf f α η ηs ηs₁ η₁ η₂ η₃ e_ηs₁ e_η₁ e_η₂ e_η₃⟩ | .cons _ α (.whisker _ f η) ηs, h => do let g ← η.srcM let g' ← η.tgtM let ⟨η₁, e_η₁⟩ ← evalWhiskerRight (← consM (← id₂M' g) η (← NormalExpr.idM g')) h let ⟨η₂, e_η₂⟩ ← evalWhiskerLeft (.of f) η₁ let ⟨ηs₁, e_ηs₁⟩ ← evalWhiskerRight ηs h let α' ← whiskerRightM α h let ⟨ηs₂, e_ηs₂⟩ ← evalComp (← NormalExpr.associatorInvM (.of f) g' h) ηs₁ let ⟨η₃, e_η₃⟩ ← evalComp η₂ ηs₂ let ⟨η₄, e_η₄⟩ ← evalComp (← NormalExpr.associatorM (.of f) g h) η₃ let ⟨η₅, e_η₅⟩ ← evalComp (← nilM α') η₄ return ⟨η₅, ← mkEvalWhiskerRightConsWhisker f h α η ηs η₁ η₂ ηs₁ ηs₂ η₃ η₄ η₅ e_η₁ e_η₂ e_ηs₁ e_ηs₂ e_η₃ e_η₄ e_η₅⟩ | η, .comp _ g h => do let ⟨η₁, e_η₁⟩ ← evalWhiskerRight η g let ⟨η₂, e_η₂⟩ ← evalWhiskerRight η₁ h let f ← η.srcM let f' ← η.tgtM let ⟨η₃, e_η₃⟩ ← evalComp η₂ (← NormalExpr.associatorM f' g h) let ⟨η₄, e_η₄⟩ ← evalComp (← NormalExpr.associatorInvM f g h) η₃ return ⟨η₄, ← mkEvalWhiskerRightComp g h η η₁ η₂ η₃ η₄ e_η₁ e_η₂ e_η₃ e_η₄⟩ | η, .id _ _ => do let f ← η.srcM let g ← η.tgtM let ⟨η₁, e_η₁⟩ ← evalComp η (← NormalExpr.rightUnitorInvM g) let ⟨η₂, e_η₂⟩ ← evalComp (← NormalExpr.rightUnitorM f) η₁ return ⟨η₂, ← mkEvalWhiskerRightId η η₁ η₂ e_η₁ e_η₂⟩ /-- Evaluate the expression `η ⊗ θ` into a normalized form. -/ partial def evalHorizontalCompAux : HorizontalComp → HorizontalComp → CoherenceM ρ Eval.Result | .of η, θ => do return ⟨← NormalExpr.ofM <| .of <| ← MonadHorizontalComp.hConsM η θ, ← mkEvalHorizontalCompAuxOf η θ⟩ | .cons _ η ηs, θ => do let α ← NormalExpr.associatorM (← η.srcM) (← ηs.srcM) (← θ.srcM) let α' ← NormalExpr.associatorInvM (← η.tgtM) (← ηs.tgtM) (← θ.tgtM) let ⟨ηθ, e_ηθ⟩ ← evalHorizontalCompAux ηs θ let ⟨η₁, e_η₁⟩ ← evalHorizontalComp (← NormalExpr.ofM <| .of <| .of η) ηθ let ⟨ηθ₁, e_ηθ₁⟩ ← evalComp η₁ α' let ⟨ηθ₂, e_ηθ₂⟩ ← evalComp α ηθ₁ return ⟨ηθ₂, ← mkEvalHorizontalCompAuxCons η ηs θ ηθ η₁ ηθ₁ ηθ₂ e_ηθ e_η₁ e_ηθ₁ e_ηθ₂⟩ /-- Evaluate the expression `η ⊗ θ` into a normalized form. -/ partial def evalHorizontalCompAux' : WhiskerLeft → WhiskerLeft → CoherenceM ρ Eval.Result | .of η, .of θ => evalHorizontalCompAux η θ | .whisker _ f η, θ => do let ⟨ηθ, e_ηθ⟩ ← evalHorizontalCompAux' η θ let ⟨ηθ₁, e_ηθ₁⟩ ← evalWhiskerLeft (.of f) ηθ let ⟨ηθ₂, e_ηθ₂⟩ ← evalComp ηθ₁ (← NormalExpr.associatorInvM (.of f) (← η.tgtM) (← θ.tgtM)) let ⟨ηθ₃, e_ηθ₃⟩ ← evalComp (← NormalExpr.associatorM (.of f) (← η.srcM) (← θ.srcM)) ηθ₂ return ⟨ηθ₃, ← mkEvalHorizontalCompAux'Whisker f η θ ηθ ηθ₁ ηθ₂ ηθ₃ e_ηθ e_ηθ₁ e_ηθ₂ e_ηθ₃⟩ | .of η, .whisker _ f θ => do let ⟨η₁, e_η₁⟩ ← evalWhiskerRightAux η f let ⟨ηθ, e_ηθ⟩ ← evalHorizontalComp η₁ (← NormalExpr.ofM θ) let ⟨ηθ₁, e_ηθ₁⟩ ← evalComp ηθ (← NormalExpr.associatorM (← η.tgtM) (.of f) (← θ.tgtM)) let ⟨ηθ₂, e_ηθ₂⟩ ← evalComp (← NormalExpr.associatorInvM (← η.srcM) (.of f) (← θ.srcM)) ηθ₁ return ⟨ηθ₂, ← mkEvalHorizontalCompAux'OfWhisker f η θ ηθ η₁ ηθ₁ ηθ₂ e_η₁ e_ηθ e_ηθ₁ e_ηθ₂⟩ /-- Evaluate the expression `η ⊗ θ` into a normalized form. -/ partial def evalHorizontalComp : NormalExpr → NormalExpr → CoherenceM ρ Eval.Result | .nil _ α, .nil _ β => do return ⟨← nilM <| ← horizontalCompM α β, ← mkEvalHorizontalCompNilNil α β⟩ | .nil _ α, .cons _ β η ηs => do let ⟨η₁, e_η₁⟩ ← evalWhiskerLeft (← α.tgtM) (← NormalExpr.ofM η) let ⟨ηs₁, e_ηs₁⟩ ← evalWhiskerLeft (← α.tgtM) ηs let ⟨η₂, e_η₂⟩ ← evalComp η₁ ηs₁ let ⟨η₃, e_η₃⟩ ← evalCompNil (← horizontalCompM α β) η₂ return ⟨η₃, ← mkEvalHorizontalCompNilCons α β η ηs η₁ ηs₁ η₂ η₃ e_η₁ e_ηs₁ e_η₂ e_η₃⟩ | .cons _ α η ηs, .nil _ β => do let ⟨η₁, e_η₁⟩ ← evalWhiskerRight (← NormalExpr.ofM η) (← β.tgtM) let ⟨ηs₁, e_ηs₁⟩ ← evalWhiskerRight ηs (← β.tgtM) let ⟨η₂, e_η₂⟩ ← evalComp η₁ ηs₁ let ⟨η₃, e_η₃⟩ ← evalCompNil (← horizontalCompM α β) η₂ return ⟨η₃, ← mkEvalHorizontalCompConsNil α β η ηs η₁ ηs₁ η₂ η₃ e_η₁ e_ηs₁ e_η₂ e_η₃⟩ | .cons _ α η ηs, .cons _ β θ θs => do let ⟨ηθ, e_ηθ⟩ ← evalHorizontalCompAux' η θ let ⟨ηθs, e_ηθs⟩ ← evalHorizontalComp ηs θs let ⟨ηθ₁, e_ηθ₁⟩ ← evalComp ηθ ηθs let ⟨ηθ₂, e_ηθ₂⟩ ← evalCompNil (← horizontalCompM α β) ηθ₁ return ⟨ηθ₂, ← mkEvalHorizontalCompConsCons α β η θ ηs θs ηθ ηθs ηθ₁ ηθ₂ e_ηθ e_ηθs e_ηθ₁ e_ηθ₂⟩ end open MkEval variable {ρ : Type} [MonadMor₁ (CoherenceM ρ)] [MonadMor₂Iso (CoherenceM ρ)] [MonadNormalExpr (CoherenceM ρ)] [MkEval (CoherenceM ρ)] [MonadMor₂ (CoherenceM ρ)] /-- Trace the proof of the normalization. -/ def traceProof (nm : Name) (result : Expr) : CoherenceM ρ Unit := do withTraceNode nm (fun _ => return m!"{checkEmoji} {← inferType result}") do if ← isTracingEnabledFor nm then addTrace nm m!"proof: {result}" -- TODO: It takes a while to compile. Find out why. /-- Evaluate the expression of a 2-morphism into a normalized form. -/ def eval (nm : Name) (e : Mor₂) : CoherenceM ρ Eval.Result := do withTraceNode nm (fun _ => return m!"eval: {e.e}") do match e with | .isoHom _ _ α => withTraceNode nm (fun _ => return m!"Iso.hom") do match α with | .structuralAtom α => return ⟨← nilM <| .structuralAtom α, ← mkEqRefl e.e⟩ | .of η => let η ← MonadMor₂.atomHomM η let result ← mkEvalOf η traceProof nm result return ⟨← NormalExpr.ofAtomM η, result⟩ | _ => throwError "not implemented. try dsimp first." | .isoInv _ _ α => withTraceNode nm (fun _ => return m!"Iso.inv") do match α with | .structuralAtom α => return ⟨← nilM <| (← symmM (.structuralAtom α)), ← mkEqRefl e.e⟩ | .of η => let η ← MonadMor₂.atomInvM η let result ← mkEvalOf η traceProof nm result return ⟨← NormalExpr.ofAtomM η, result⟩ | _ => throwError "not implemented. try dsimp first." | .id _ _ f => let α ← MonadMor₂Iso.id₂M f return ⟨← nilM <| .structuralAtom α, ← mkEqRefl e.e⟩ | .comp _ _ _ _ _ η θ => withTraceNode nm (fun _ => return m!"comp") do let ⟨η', e_η⟩ ← eval nm η let ⟨θ', e_θ⟩ ← eval nm θ let ⟨ηθ, pf⟩ ← evalComp η' θ' let result ← mkEvalComp η θ η' θ' ηθ e_η e_θ pf traceProof nm result return ⟨ηθ, result⟩ | .whiskerLeft _ _ f _ _ η => withTraceNode nm (fun _ => return m!"whiskerLeft") do let ⟨η', e_η⟩ ← eval nm η let ⟨θ, e_θ⟩ ← evalWhiskerLeft f η' let result ← mkEvalWhiskerLeft f η η' θ e_η e_θ traceProof nm result return ⟨θ, result⟩ | .whiskerRight _ _ _ _ η h => withTraceNode nm (fun _ => return m!"whiskerRight") do let ⟨η', e_η⟩ ← eval nm η let ⟨θ, e_θ⟩ ← evalWhiskerRight η' h let result ← mkEvalWhiskerRight η h η' θ e_η e_θ traceProof nm result return ⟨θ, result⟩ | .coherenceComp _ _ _ _ _ _ α₀ η θ => withTraceNode nm (fun _ => return m!"monoidalComp") do let ⟨η', e_η⟩ ← eval nm η let α₀ := .structuralAtom <| .coherenceHom α₀ let α ← nilM α₀ let ⟨θ', e_θ⟩ ← eval nm θ let ⟨αθ, e_αθ⟩ ← evalComp α θ' let ⟨ηαθ, e_ηαθ⟩ ← evalComp η' αθ let result ← mkEvalMonoidalComp η θ α₀ η' θ' αθ ηαθ e_η e_θ e_αθ e_ηαθ traceProof nm result return ⟨ηαθ, result⟩ | .horizontalComp _ _ _ _ _ _ η θ => withTraceNode nm (fun _ => return m!"horizontalComp") do let ⟨η', e_η⟩ ← eval nm η let ⟨θ', e_θ⟩ ← eval nm θ let ⟨ηθ, e_ηθ⟩ ← evalHorizontalComp η' θ' let result ← mkEvalHorizontalComp η θ η' θ' ηθ e_η e_θ e_ηθ traceProof nm result return ⟨ηθ, result⟩ | .of η => let result ← mkEvalOf η traceProof nm result return ⟨← NormalExpr.ofAtomM η, result⟩ end end Mathlib.Tactic.BicategoryLike
Projection.lean
/- Copyright (c) 2025 Monica Omar. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Monica Omar -/ import Mathlib.Analysis.CStarAlgebra.ContinuousFunctionalCalculus.Instances /-! # Projections in C⋆-algebras To show that an element is a star projection in a non-unital C⋆-algebra, it is enough to show that it is idempotent and normal, because self-adjointedness and normality are equivalent for idempotent elements in non-unital C⋆-algebras. -/ variable {A : Type*} [TopologicalSpace A] [NonUnitalRing A] [StarRing A] [Module ℂ A] [IsScalarTower ℂ A A] [SMulCommClass ℂ A A] [NonUnitalContinuousFunctionalCalculus ℂ A IsStarNormal] /-- An idempotent element in a non-unital C⋆-algebra is self-adjoint iff it is normal. -/ theorem IsIdempotentElem.isSelfAdjoint_iff_isStarNormal {p : A} (hp : IsIdempotentElem p) : IsSelfAdjoint p ↔ IsStarNormal p := by simp only [isSelfAdjoint_iff_isStarNormal_and_quasispectrumRestricts, QuasispectrumRestricts.real_iff, and_iff_left_iff_imp] intro h x hx rcases hp.quasispectrum_subset hx with (hx | hx) <;> simp [Set.mem_singleton_iff.mp hx] /-- An element in a non-unital C⋆-algebra is a star projection if and only if it is idempotent and normal. -/ theorem isStarProjection_iff_isIdempotentElem_and_isStarNormal {p : A} : IsStarProjection p ↔ IsIdempotentElem p ∧ IsStarNormal p := (isStarProjection_iff p).eq ▸ and_congr_right_iff.eq ▸ fun h => h.isSelfAdjoint_iff_isStarNormal
Opposites.lean
/- Copyright (c) 2025 Robin Carlier. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robin Carlier -/ import Mathlib.CategoryTheory.Monoidal.Action.Basic import Mathlib.CategoryTheory.Monoidal.Opposite /-! # Actions from the monoidal opposite of a category. In this file, given a monoidal category `C` and a category `D`, we construct a left `C`-action on `D` out of the data of a right `Cᴹᵒᵖ`-action on `D`. We also construct a right `C`-action on `D`from the data of a left `Cᴹᵒᵖ`-action on `D`. Conversely, given left/right `C`-actions on `D`, we construct a`Cᴹᵒᵖ` actions with the conjugate variance. These constructions are not made instances in order to avoid instance loops, you should bring them as local instances if you intend to use them. -/ namespace CategoryTheory.MonoidalCategory variable (C D : Type*) variable [Category C] [MonoidalCategory C] [Category D] namespace MonoidalLeftAction open scoped MonoidalLeftAction MonoidalRightAction open MonoidalOpposite /-- Define a left action of `C` on `D` from a right action of `Cᴹᵒᵖ` on `D` via the formula `c ⊙ₗ d := d ⊙ᵣ (mop c)`. -/ @[simps -isSimp] def leftActionOfMonoidalOppositeRightAction [MonoidalRightAction Cᴹᵒᵖ D] : MonoidalLeftAction C D where actionObj c d := d ⊙ᵣ mop c actionHomLeft {c c'} f d := d ⊴ᵣ f.mop actionHomRight c {d d'} f := f ⊵ᵣ mop c actionHom {c c'} {d d} f g := g ⊙ᵣₘ f.mop actionAssocIso _ _ _ := αᵣ _ _ _ actionUnitIso _ := ρᵣ _ actionHom_def _ _ := MonoidalRightAction.actionHom_def' _ _ actionAssocIso_hom_naturality _ _ _ := MonoidalRightAction.actionAssocIso_hom_naturality _ _ _ actionUnitIso_hom_naturality _ := MonoidalRightAction.actionUnitIso_hom_naturality _ rightUnitor_actionHom c d := MonoidalRightAction.actionHom_leftUnitor _ _ associator_actionHom c₁ c₂ c₃ d := by simpa only [mop_tensorObj, mop_hom_associator, MonoidalRightAction.actionHomRight_inv_hom_assoc] using (d ⊴ᵣ (α_ (mop c₃) (mop c₂) (mop c₁)).inv) ≫= MonoidalRightAction.actionHom_associator (mop c₃) (mop c₂) (mop c₁) d|>.symm /-- Define a left action of `Cᴹᵒᵖ` on `D` from a right action of `C` on `D` via the formula `mop c ⊙ₗ d = d ⊙ᵣ c`. -/ @[simps -isSimp] def monoidalOppositeLeftAction [MonoidalRightAction C D] : MonoidalLeftAction Cᴹᵒᵖ D where actionObj c d := d ⊙ᵣ unmop c actionHomLeft {c c'} f d := d ⊴ᵣ f.unmop actionHomRight c {d d'} f := f ⊵ᵣ unmop c actionHom {c c'} {d d} f g := g ⊙ᵣₘ f.unmop actionAssocIso _ _ _ := αᵣ _ _ _ actionUnitIso _ := ρᵣ _ actionHom_def _ _ := MonoidalRightAction.actionHom_def' _ _ actionAssocIso_hom_naturality _ _ _ := MonoidalRightAction.actionAssocIso_hom_naturality _ _ _ actionUnitIso_hom_naturality _ := MonoidalRightAction.actionUnitIso_hom_naturality _ rightUnitor_actionHom c d := MonoidalRightAction.actionHom_leftUnitor _ _ associator_actionHom c₁ c₂ c₃ d := by simpa only [mop_tensorObj, mop_hom_associator, MonoidalRightAction.actionHomRight_inv_hom_assoc] using (d ⊴ᵣ (α_ (unmop c₃) (unmop c₂) (unmop c₁)).inv) ≫= MonoidalRightAction.actionHom_associator (unmop c₃) (unmop c₂) (unmop c₁) d|>.symm section attribute [local instance] monoidalOppositeLeftAction variable [MonoidalRightAction C D] lemma monoidalOppositeLeftAction_actionObj_mop (c : C) (d : D) : mop c ⊙ₗ d = d ⊙ᵣ c := rfl lemma monoidalOppositeLeftAction_actionHomLeft_mop {c c' : C} (f : c ⟶ c') (d : D) : f.mop ⊵ₗ d = d ⊴ᵣ f := rfl lemma monoidalOppositeLeftAction_actionRight_mop (c : C) {d d' : D} (f : d ⟶ d') : mop c ⊴ₗ f = f ⊵ᵣ c := rfl lemma monoidalOppositeLeftAction_actionHom_mop_mop {c c' : C} {d d' : D} (f : c ⟶ c') (g : d ⟶ d') : f.mop ⊙ₗₘ g = g ⊙ᵣₘ f := rfl lemma monoidalOppositeLeftAction_actionAssocIso_mop_mop (c c' : C) (d : D) : αₗ (mop c) (mop c') d = αᵣ d c' c := rfl end end MonoidalLeftAction namespace MonoidalRightAction open scoped MonoidalLeftAction MonoidalRightAction open MonoidalOpposite /-- Define a right action of `C` on `D` from a left action of `Cᴹᵒᵖ` on `D` via the formula `d ⊙ᵣ c := (mop c) ⊙ₗ d`. -/ @[simps -isSimp] def rightActionOfMonoidalOppositeLeftAction [MonoidalLeftAction Cᴹᵒᵖ D] : MonoidalRightAction C D where actionObj d c := mop c ⊙ₗ d actionHomLeft {d d'} f c := mop c ⊴ₗ f actionHomRight d _ _ f := f.mop ⊵ₗ d actionHom {c c'} {d d'} f g := g.mop ⊙ₗₘ f actionAssocIso _ _ _ := αₗ _ _ _ actionUnitIso _ := λₗ _ actionHom_def _ _ := MonoidalLeftAction.actionHom_def' _ _ actionAssocIso_hom_naturality _ _ _ := MonoidalLeftAction.actionAssocIso_hom_naturality _ _ _ actionUnitIso_hom_naturality _ := MonoidalLeftAction.actionUnitIso_hom_naturality _ actionHom_associator c₁ c₂ c₃ d := by simpa only [mop_tensorObj, mop_hom_associator, MonoidalLeftAction.inv_hom_actionHomLeft_assoc] using (α_ (mop c₃) (mop c₂) (mop c₁)).inv ⊵ₗ d ≫= MonoidalLeftAction.associator_actionHom (mop c₃) (mop c₂) (mop c₁) d|>.symm /-- Define a right action of `Cᴹᵒᵖ` on `D` from a left action of `C` on `D` via the formula `d ⊙ᵣ mop c = c ⊙ₗ d`. -/ @[simps -isSimp] def monoidalOppositeRightAction [MonoidalLeftAction C D] : MonoidalRightAction Cᴹᵒᵖ D where actionObj d c := unmop c ⊙ₗ d actionHomLeft {d d'} f c := unmop c ⊴ₗ f actionHomRight d _ _ f := f.unmop ⊵ₗ d actionHom {c c'} {d d'} f g := g.unmop ⊙ₗₘ f actionAssocIso _ _ _ := αₗ _ _ _ actionUnitIso _ := λₗ _ actionHom_def _ _ := MonoidalLeftAction.actionHom_def' _ _ actionAssocIso_hom_naturality _ _ _ := MonoidalLeftAction.actionAssocIso_hom_naturality _ _ _ actionUnitIso_hom_naturality _ := MonoidalLeftAction.actionUnitIso_hom_naturality _ actionHom_associator c₁ c₂ c₃ d := by simpa only [mop_tensorObj, mop_hom_associator, MonoidalLeftAction.inv_hom_actionHomLeft_assoc] using (α_ (unmop c₃) (unmop c₂) (unmop c₁)).inv ⊵ₗ d ≫= MonoidalLeftAction.associator_actionHom (unmop c₃) (unmop c₂) (unmop c₁) d|>.symm section attribute [local instance] monoidalOppositeRightAction variable [MonoidalLeftAction C D] lemma monoidalOppositeRightAction_actionObj_mop (c : C) (d : D) : d ⊙ᵣ mop c = c ⊙ₗ d := rfl lemma monoidalOppositeRightAction_actionHomRight_mop {c c' : C} (f : c ⟶ c') (d : D) : d ⊴ᵣ f.mop = f ⊵ₗ d := rfl lemma monoidalOppositeRightAction_actionRight_mop (c : C) {d d' : D} (f : d ⟶ d') : f ⊵ᵣ mop c = c ⊴ₗ f := rfl lemma monoidalOppositeRightAction_actionHom_mop_mop {c c' : D} {d d' : C} (f : c ⟶ c') (g : d ⟶ d') : f ⊙ᵣₘ g.mop = g ⊙ₗₘ f := rfl lemma monoidalOppositeRightAction_actionAssocIso_mop_mop (c c' : C) (d : D) : αᵣ d (mop c) (mop c') = αₗ c' c d := rfl end end MonoidalRightAction end CategoryTheory.MonoidalCategory
Eq.lean
/- Copyright (c) 2022 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Tactic.NormNum.Inv /-! # `norm_num` extension for equalities -/ variable {α : Type*} open Lean Meta Qq namespace Mathlib.Meta.NormNum theorem isNat_eq_false [AddMonoidWithOne α] [CharZero α] : {a b : α} → {a' b' : ℕ} → IsNat a a' → IsNat b b' → Nat.beq a' b' = false → ¬a = b | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => by simpa using Nat.ne_of_beq_eq_false h theorem isInt_eq_false [Ring α] [CharZero α] : {a b : α} → {a' b' : ℤ} → IsInt a a' → IsInt b b' → decide (a' = b') = false → ¬a = b | _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => by simpa using of_decide_eq_false h theorem NNRat.invOf_denom_swap [Semiring α] (n₁ n₂ : ℕ) (a₁ a₂ : α) [Invertible a₁] [Invertible a₂] : n₁ * ⅟a₁ = n₂ * ⅟a₂ ↔ n₁ * a₂ = n₂ * a₁ := by rw [mul_invOf_eq_iff_eq_mul_right, ← Nat.commute_cast, mul_assoc, ← mul_left_eq_iff_eq_invOf_mul, Nat.commute_cast] theorem isNNRat_eq_false [Semiring α] [CharZero α] : {a b : α} → {na nb : ℕ} → {da db : ℕ} → IsNNRat a na da → IsNNRat b nb db → decide (Nat.mul na db = Nat.mul nb da) = false → ¬a = b | _, _, _, _, _, _, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by rw [NNRat.invOf_denom_swap]; exact mod_cast of_decide_eq_false h theorem Rat.invOf_denom_swap [Ring α] (n₁ n₂ : ℤ) (a₁ a₂ : α) [Invertible a₁] [Invertible a₂] : n₁ * ⅟a₁ = n₂ * ⅟a₂ ↔ n₁ * a₂ = n₂ * a₁ := by rw [mul_invOf_eq_iff_eq_mul_right, ← Int.commute_cast, mul_assoc, ← mul_left_eq_iff_eq_invOf_mul, Int.commute_cast] theorem isRat_eq_false [Ring α] [CharZero α] : {a b : α} → {na nb : ℤ} → {da db : ℕ} → IsRat a na da → IsRat b nb db → decide (Int.mul na (.ofNat db) = Int.mul nb (.ofNat da)) = false → ¬a = b | _, _, _, _, _, _, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by rw [Rat.invOf_denom_swap]; exact mod_cast of_decide_eq_false h attribute [local instance] monadLiftOptionMetaM in /-- The `norm_num` extension which identifies expressions of the form `a = b`, such that `norm_num` successfully recognises both `a` and `b`. -/ @[norm_num _ = _] def evalEq : NormNumExt where eval {v β} e := do haveI' : v =QL 0 := ⟨⟩; haveI' : $β =Q Prop := ⟨⟩ let .app (.app f a) b ← whnfR e | failure let ⟨u, α, a⟩ ← inferTypeQ' a have b : Q($α) := b haveI' : $e =Q ($a = $b) := ⟨⟩ guard <|← withNewMCtxDepth <| isDefEq f q(Eq (α := $α)) let ra ← derive a; let rb ← derive b let rec intArm (rα : Q(Ring $α)) := do let ⟨za, na, pa⟩ ← ra.toInt rα; let ⟨zb, nb, pb⟩ ← rb.toInt rα if za = zb then haveI' : $na =Q $nb := ⟨⟩ return .isTrue q(isInt_eq_true $pa $pb) else if let some _i ← inferCharZeroOfRing? rα then let r : Q(decide ($na = $nb) = false) := (q(Eq.refl false) : Expr) return .isFalse q(isInt_eq_false $pa $pb $r) else failure --TODO: nonzero characteristic ≠ let rec nnratArm (dsα : Q(DivisionSemiring $α)) := do let ⟨qa, na, da, pa⟩ ← ra.toNNRat' dsα; let ⟨qb, nb, db, pb⟩ ← rb.toNNRat' dsα if qa = qb then haveI' : $na =Q $nb := ⟨⟩ haveI' : $da =Q $db := ⟨⟩ return .isTrue q(isNNRat_eq_true $pa $pb) else if let some _i ← inferCharZeroOfDivisionSemiring? dsα then let r : Q(decide (Nat.mul $na $db = Nat.mul $nb $da) = false) := (q(Eq.refl false) : Expr) return .isFalse q(isNNRat_eq_false $pa $pb $r) else failure --TODO: nonzero characteristic ≠ let rec ratArm (dα : Q(DivisionRing $α)) := do let ⟨qa, na, da, pa⟩ ← ra.toRat' dα; let ⟨qb, nb, db, pb⟩ ← rb.toRat' dα if qa = qb then haveI' : $na =Q $nb := ⟨⟩ haveI' : $da =Q $db := ⟨⟩ return .isTrue q(isRat_eq_true $pa $pb) else if let some _i ← inferCharZeroOfDivisionRing? dα then let r : Q(decide (Int.mul $na (.ofNat $db) = Int.mul $nb (.ofNat $da)) = false) := (q(Eq.refl false) : Expr) return .isFalse q(isRat_eq_false $pa $pb $r) else failure --TODO: nonzero characteristic ≠ match ra, rb with | .isBool b₁ p₁, .isBool b₂ p₂ => have a : Q(Prop) := a; have b : Q(Prop) := b match b₁, p₁, b₂, p₂ with | true, (p₁ : Q($a)), true, (p₂ : Q($b)) => return .isTrue q(eq_of_true $p₁ $p₂) | false, (p₁ : Q(¬$a)), false, (p₂ : Q(¬$b)) => return .isTrue q(eq_of_false $p₁ $p₂) | false, (p₁ : Q(¬$a)), true, (p₂ : Q($b)) => return .isFalse q(ne_of_false_of_true $p₁ $p₂) | true, (p₁ : Q($a)), false, (p₂ : Q(¬$b)) => return .isFalse q(ne_of_true_of_false $p₁ $p₂) | .isBool .., _ | _, .isBool .. => failure | .isNegNNRat dα .., _ | _, .isNegNNRat dα .. => ratArm dα -- mixing positive rationals and negative naturals means we need to use the full rat handler | .isNNRat dsα .., .isNegNat rα .. | .isNegNat rα .., .isNNRat dsα .. => -- could alternatively try to combine `rα` and `dsα` here, but we'd have to do a defeq check -- so would still need to be in `MetaM`. ratArm (←synthInstanceQ q(DivisionRing $α)) | .isNNRat dsα .., _ | _, .isNNRat dsα .. => nnratArm dsα | .isNegNat rα .., _ | _, .isNegNat rα .. => intArm rα | .isNat _ na pa, .isNat mα nb pb => assumeInstancesCommute if na.natLit! = nb.natLit! then haveI' : $na =Q $nb := ⟨⟩ return .isTrue q(isNat_eq_true $pa $pb) else if let some _i ← inferCharZeroOfAddMonoidWithOne? mα then let r : Q(Nat.beq $na $nb = false) := (q(Eq.refl false) : Expr) return .isFalse q(isNat_eq_false $pa $pb $r) else failure --TODO: nonzero characteristic ≠ end Mathlib.Meta.NormNum
Determinant.lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov, Frédéric Dupuis, Heather Macbeth -/ import Mathlib.Topology.Algebra.Module.Equiv import Mathlib.LinearAlgebra.Determinant /-! # The determinant of a continuous linear map. -/ namespace ContinuousLinearMap /-- The determinant of a continuous linear map, mainly as a convenience device to be able to write `A.det` instead of `(A : M →ₗ[R] M).det`. -/ noncomputable abbrev det {R : Type*} [CommRing R] {M : Type*} [TopologicalSpace M] [AddCommGroup M] [Module R M] (A : M →L[R] M) : R := LinearMap.det (A : M →ₗ[R] M) theorem det_pi {ι R M : Type*} [Fintype ι] [CommRing R] [AddCommGroup M] [TopologicalSpace M] [Module R M] [Module.Free R M] [Module.Finite R M] (f : ι → M →L[R] M) : (pi (fun i ↦ (f i).comp (proj i))).det = ∏ i, (f i).det := LinearMap.det_pi _ theorem det_one_smulRight {𝕜 : Type*} [CommRing 𝕜] [TopologicalSpace 𝕜] [ContinuousMul 𝕜] (v : 𝕜) : ((1 : 𝕜 →L[𝕜] 𝕜).smulRight v).det = v := by simp end ContinuousLinearMap namespace ContinuousLinearEquiv @[simp] theorem det_coe_symm {R : Type*} [Field R] {M : Type*} [TopologicalSpace M] [AddCommGroup M] [Module R M] (A : M ≃L[R] M) : (A.symm : M →L[R] M).det = (A : M →L[R] M).det⁻¹ := LinearEquiv.det_coe_symm A.toLinearEquiv end ContinuousLinearEquiv
Ideal.lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.CategoryTheory.Limits.Preserves.Shapes.BinaryProducts import Mathlib.CategoryTheory.Limits.Preserves.Shapes.Terminal import Mathlib.CategoryTheory.Limits.Constructions.FiniteProductsOfBinaryProducts import Mathlib.CategoryTheory.Monad.Limits import Mathlib.CategoryTheory.Adjunction.FullyFaithful import Mathlib.CategoryTheory.Adjunction.Limits import Mathlib.CategoryTheory.Adjunction.Reflective import Mathlib.CategoryTheory.Closed.Cartesian import Mathlib.CategoryTheory.Subterminal /-! # Exponential ideals An exponential ideal of a cartesian closed category `C` is a subcategory `D ⊆ C` such that for any `B : D` and `A : C`, the exponential `A ⟹ B` is in `D`: resembling ring theoretic ideals. We define the notion here for inclusion functors `i : D ⥤ C` rather than explicit subcategories to preserve the principle of equivalence. We additionally show that if `C` is cartesian closed and `i : D ⥤ C` is a reflective functor, the following are equivalent. * The left adjoint to `i` preserves binary (equivalently, finite) products. * `i` is an exponential ideal. -/ universe v₁ v₂ u₁ u₂ noncomputable section namespace CategoryTheory open Category section Ideal variable {C : Type u₁} {D : Type u₂} [Category.{v₁} C] [Category.{v₁} D] {i : D ⥤ C} variable (i) [CartesianMonoidalCategory C] [CartesianClosed C] /-- The subcategory `D` of `C` expressed as an inclusion functor is an *exponential ideal* if `B ∈ D` implies `A ⟹ B ∈ D` for all `A`. -/ class ExponentialIdeal : Prop where exp_closed : ∀ {B}, i.essImage B → ∀ A, i.essImage (A ⟹ B) attribute [nolint docBlame] ExponentialIdeal.exp_closed /-- To show `i` is an exponential ideal it suffices to show that `A ⟹ iB` is "in" `D` for any `A` in `C` and `B` in `D`. -/ theorem ExponentialIdeal.mk' (h : ∀ (B : D) (A : C), i.essImage (A ⟹ i.obj B)) : ExponentialIdeal i := ⟨fun hB A => by rcases hB with ⟨B', ⟨iB'⟩⟩ exact Functor.essImage.ofIso ((exp A).mapIso iB') (h B' A)⟩ /-- The entire category viewed as a subcategory is an exponential ideal. -/ instance : ExponentialIdeal (𝟭 C) := ExponentialIdeal.mk' _ fun _ _ => ⟨_, ⟨Iso.refl _⟩⟩ open CartesianClosed /-- The subcategory of subterminal objects is an exponential ideal. -/ instance : ExponentialIdeal (subterminalInclusion C) := by apply ExponentialIdeal.mk' intro B A refine ⟨⟨A ⟹ B.1, fun Z g h => ?_⟩, ⟨Iso.refl _⟩⟩ exact uncurry_injective (B.2 (CartesianClosed.uncurry g) (CartesianClosed.uncurry h)) /-- If `D` is a reflective subcategory, the property of being an exponential ideal is equivalent to the presence of a natural isomorphism `i ⋙ exp A ⋙ leftAdjoint i ⋙ i ≅ i ⋙ exp A`, that is: `(A ⟹ iB) ≅ i L (A ⟹ iB)`, naturally in `B`. The converse is given in `ExponentialIdeal.mk_of_iso`. -/ def exponentialIdealReflective (A : C) [Reflective i] [ExponentialIdeal i] : i ⋙ exp A ⋙ reflector i ⋙ i ≅ i ⋙ exp A := by symm apply NatIso.ofComponents _ _ · intro X haveI := Functor.essImage.unit_isIso (ExponentialIdeal.exp_closed (i.obj_mem_essImage X) A) apply asIso ((reflectorAdjunction i).unit.app (A ⟹ i.obj X)) · simp [asIso] /-- Given a natural isomorphism `i ⋙ exp A ⋙ leftAdjoint i ⋙ i ≅ i ⋙ exp A`, we can show `i` is an exponential ideal. -/ theorem ExponentialIdeal.mk_of_iso [Reflective i] (h : ∀ A : C, i ⋙ exp A ⋙ reflector i ⋙ i ≅ i ⋙ exp A) : ExponentialIdeal i := by apply ExponentialIdeal.mk' intro B A exact ⟨_, ⟨(h A).app B⟩⟩ end Ideal section variable {C : Type u₁} {D : Type u₂} [Category.{v₁} C] [Category.{v₁} D] variable (i : D ⥤ C) -- Porting note: this used to be used as a local instance, -- now it can instead be used as a have when needed -- we assume HasFiniteProducts D as a hypothesis below theorem reflective_products [Limits.HasFiniteProducts C] [Reflective i] : Limits.HasFiniteProducts D := ⟨fun _ => hasLimitsOfShape_of_reflective i⟩ open CartesianClosed MonoidalCategory CartesianMonoidalCategory open Limits in /-- Given a reflective subcategory `D` of a category with chosen finite products `C`, `D` admits finite chosen products. -/ -- Note: This is not an instance as one might already have a (different) `CartesianMonoidalCategory` -- instance on `D` (as for example with sheaves). -- See note [reducible non instances] abbrev CartesianMonoidalCategory.ofReflective [CartesianMonoidalCategory C] [Reflective i] : CartesianMonoidalCategory D := .ofChosenFiniteProducts ({ cone := Limits.asEmptyCone <| (reflector i).obj (𝟙_ C) isLimit := by apply isLimitOfReflects i apply isLimitChangeEmptyCone _ isTerminalTensorUnit letI : IsIso ((reflectorAdjunction i).unit.app (𝟙_ C)) := by have := reflective_products i refine Functor.essImage.unit_isIso ⟨terminal D, ⟨PreservesTerminal.iso i |>.trans ?_⟩⟩ exact IsLimit.conePointUniqueUpToIso (limit.isLimit _) isTerminalTensorUnit exact asIso ((reflectorAdjunction i).unit.app (𝟙_ C)) }) fun X Y ↦ { cone := BinaryFan.mk ((reflector i).map (fst (i.obj X) (i.obj Y)) ≫ (reflectorAdjunction i).counit.app _) ((reflector i).map (snd (i.obj X) (i.obj Y)) ≫ (reflectorAdjunction i).counit.app _) isLimit := by apply isLimitOfReflects i apply IsLimit.equivOfNatIsoOfIso (pairComp X Y _) _ _ _|>.invFun (tensorProductIsBinaryProduct (i.obj X) (i.obj Y)) fapply BinaryFan.ext · change (reflector i ⋙ i).obj (i.obj X ⊗ i.obj Y) ≅ (𝟭 C).obj (i.obj X ⊗ i.obj Y) letI : IsIso ((reflectorAdjunction i).unit.app (i.obj X ⊗ i.obj Y)) := by apply Functor.essImage.unit_isIso haveI := reflective_products i use Limits.prod X Y constructor apply Limits.PreservesLimitPair.iso i _ _|>.trans refine Limits.IsLimit.conePointUniqueUpToIso (limit.isLimit (pair (i.obj X) (i.obj Y))) (tensorProductIsBinaryProduct _ _) exact asIso ((reflectorAdjunction i).unit.app (i.obj X ⊗ i.obj Y))|>.symm · simp only [BinaryFan.fst, Cones.postcompose, pairComp] simp [← Functor.comp_map, ← NatTrans.naturality_assoc] · simp only [BinaryFan.snd, Cones.postcompose, pairComp] simp [← Functor.comp_map, ← NatTrans.naturality_assoc] } @[deprecated (since := "2025-05-15")] noncomputable alias reflectiveChosenFiniteProducts := CartesianMonoidalCategory.ofReflective variable [CartesianMonoidalCategory C] [Reflective i] [CartesianClosed C] [CartesianMonoidalCategory D] /-- If the reflector preserves binary products, the subcategory is an exponential ideal. This is the converse of `preservesBinaryProductsOfExponentialIdeal`. -/ instance (priority := 10) exponentialIdeal_of_preservesBinaryProducts [Limits.PreservesLimitsOfShape (Discrete Limits.WalkingPair) (reflector i)] : ExponentialIdeal i := by let ir := reflectorAdjunction i let L : C ⥤ D := reflector i let η : 𝟭 C ⟶ L ⋙ i := ir.unit let ε : i ⋙ L ⟶ 𝟭 D := ir.counit apply ExponentialIdeal.mk' intro B A let q : i.obj (L.obj (A ⟹ i.obj B)) ⟶ A ⟹ i.obj B := by apply CartesianClosed.curry (ir.homEquiv _ _ _) apply _ ≫ (ir.homEquiv _ _).symm ((exp.ev A).app (i.obj B)) exact prodComparison L A _ ≫ (_ ◁ (ε.app _)) ≫ inv (prodComparison _ _ _) have : η.app (A ⟹ i.obj B) ≫ q = 𝟙 (A ⟹ i.obj B) := by dsimp rw [← curry_natural_left, curry_eq_iff, uncurry_id_eq_ev, ← ir.homEquiv_naturality_left, ir.homEquiv_apply_eq, assoc, assoc, prodComparison_natural_whiskerLeft_assoc, ← whiskerLeft_comp_assoc, ir.left_triangle_components, whiskerLeft_id, id_comp] apply IsIso.hom_inv_id_assoc haveI : IsSplitMono (η.app (A ⟹ i.obj B)) := IsSplitMono.mk' ⟨_, this⟩ apply mem_essImage_of_unit_isSplitMono variable [ExponentialIdeal i] /-- If `i` witnesses that `D` is a reflective subcategory and an exponential ideal, then `D` is itself cartesian closed. -/ def cartesianClosedOfReflective : CartesianClosed D where closed := fun B => { rightAdj := i ⋙ exp (i.obj B) ⋙ reflector i adj := by apply (exp.adjunction (i.obj B)).restrictFullyFaithful i.fullyFaithfulOfReflective i.fullyFaithfulOfReflective · symm refine NatIso.ofComponents (fun X => ?_) (fun f => ?_) · haveI := Adjunction.rightAdjoint_preservesLimits.{0, 0} (reflectorAdjunction i) apply asIso (prodComparison i B X) · dsimp [asIso] rw [prodComparison_natural_whiskerLeft] · apply (exponentialIdealReflective i _).symm } variable [BraidedCategory C] /-- We construct a bijection between morphisms `L(A ⊗ B) ⟶ X` and morphisms `LA ⊗ LB ⟶ X`. This bijection has two key properties: * It is natural in `X`: See `bijection_natural`. * When `X = LA ⨯ LB`, then the backwards direction sends the identity morphism to the product comparison morphism: See `bijection_symm_apply_id`. Together these help show that `L` preserves binary products. This should be considered *internal implementation* towards `preservesBinaryProductsOfExponentialIdeal`. -/ noncomputable def bijection (A B : C) (X : D) : ((reflector i).obj (A ⊗ B) ⟶ X) ≃ ((reflector i).obj A ⊗ (reflector i).obj B ⟶ X) := calc _ ≃ (A ⊗ B ⟶ i.obj X) := (reflectorAdjunction i).homEquiv _ _ _ ≃ (B ⊗ A ⟶ i.obj X) := (β_ _ _).homCongr (Iso.refl _) _ ≃ (A ⟶ B ⟹ i.obj X) := (exp.adjunction _).homEquiv _ _ _ ≃ (i.obj ((reflector i).obj A) ⟶ B ⟹ i.obj X) := (unitCompPartialBijective _ (ExponentialIdeal.exp_closed (i.obj_mem_essImage _) _)) _ ≃ (B ⊗ i.obj ((reflector i).obj A) ⟶ i.obj X) := ((exp.adjunction _).homEquiv _ _).symm _ ≃ (i.obj ((reflector i).obj A) ⊗ B ⟶ i.obj X) := ((β_ _ _).homCongr (Iso.refl _)) _ ≃ (B ⟶ i.obj ((reflector i).obj A) ⟹ i.obj X) := (exp.adjunction _).homEquiv _ _ _ ≃ (i.obj ((reflector i).obj B) ⟶ i.obj ((reflector i).obj A) ⟹ i.obj X) := (unitCompPartialBijective _ (ExponentialIdeal.exp_closed (i.obj_mem_essImage _) _)) _ ≃ (i.obj ((reflector i).obj A) ⊗ i.obj ((reflector i).obj B) ⟶ i.obj X) := ((exp.adjunction _).homEquiv _ _).symm _ ≃ (i.obj ((reflector i).obj A ⊗ (reflector i).obj B) ⟶ i.obj X) := haveI : Limits.PreservesLimits i := (reflectorAdjunction i).rightAdjoint_preservesLimits haveI := Limits.preservesSmallestLimits_of_preservesLimits i Iso.homCongr (prodComparisonIso _ _ _).symm (Iso.refl (i.obj X)) _ ≃ ((reflector i).obj A ⊗ (reflector i).obj B ⟶ X) := i.fullyFaithfulOfReflective.homEquiv.symm theorem bijection_symm_apply_id (A B : C) : (bijection i A B _).symm (𝟙 _) = prodComparison _ _ _ := by dsimp [bijection] -- Porting note: added erw [homEquiv_symm_apply_eq, homEquiv_symm_apply_eq, homEquiv_apply_eq, homEquiv_apply_eq] rw [comp_id, comp_id, comp_id, i.map_id, comp_id, unitCompPartialBijective_symm_apply, unitCompPartialBijective_symm_apply, uncurry_natural_left, uncurry_curry, uncurry_natural_left, uncurry_curry, ← BraidedCategory.braiding_naturality_left_assoc] erw [SymmetricCategory.symmetry_assoc, ← MonoidalCategory.whisker_exchange_assoc] -- Porting note: added dsimp only [Functor.comp_obj] rw [← tensorHom_def'_assoc, Adjunction.homEquiv_symm_apply, ← Adjunction.eq_unit_comp_map_iff, Iso.comp_inv_eq, assoc] rw [prodComparisonIso_hom i ((reflector i).obj A) ((reflector i).obj B)] apply hom_ext · rw [tensorHom_fst, assoc, assoc, prodComparison_fst, ← i.map_comp, prodComparison_fst] apply (reflectorAdjunction i).unit.naturality · rw [tensorHom_snd, assoc, assoc, prodComparison_snd, ← i.map_comp, prodComparison_snd] apply (reflectorAdjunction i).unit.naturality theorem bijection_natural (A B : C) (X X' : D) (f : (reflector i).obj (A ⊗ B) ⟶ X) (g : X ⟶ X') : bijection i _ _ _ (f ≫ g) = bijection i _ _ _ f ≫ g := by dsimp [bijection] -- Porting note: added erw [homEquiv_symm_apply_eq, homEquiv_symm_apply_eq, homEquiv_apply_eq, homEquiv_apply_eq, homEquiv_symm_apply_eq, homEquiv_symm_apply_eq, homEquiv_apply_eq, homEquiv_apply_eq] apply i.map_injective rw [Functor.FullyFaithful.map_preimage, i.map_comp, Adjunction.homEquiv_unit, Adjunction.homEquiv_unit] simp only [comp_id, Functor.map_comp, Functor.FullyFaithful.map_preimage, assoc] rw [← assoc, ← assoc, curry_natural_right _ (i.map g), unitCompPartialBijective_natural, uncurry_natural_right, ← assoc, curry_natural_right, unitCompPartialBijective_natural, uncurry_natural_right, assoc] /-- The bijection allows us to show that `prodComparison L A B` is an isomorphism, where the inverse is the forward map of the identity morphism. -/ theorem prodComparison_iso (A B : C) : IsIso (prodComparison (reflector i) A B) := ⟨⟨bijection i _ _ _ (𝟙 _), by rw [← (bijection i _ _ _).injective.eq_iff, bijection_natural, ← bijection_symm_apply_id, Equiv.apply_symm_apply, id_comp], by rw [← bijection_natural, id_comp, ← bijection_symm_apply_id, Equiv.apply_symm_apply]⟩⟩ attribute [local instance] prodComparison_iso open Limits /-- If a reflective subcategory is an exponential ideal, then the reflector preserves binary products. This is the converse of `exponentialIdeal_of_preserves_binary_products`. -/ lemma preservesBinaryProducts_of_exponentialIdeal : PreservesLimitsOfShape (Discrete WalkingPair) (reflector i) where preservesLimit {K} := letI := preservesLimit_pair_of_isIso_prodComparison (reflector i) (K.obj ⟨WalkingPair.left⟩) (K.obj ⟨WalkingPair.right⟩) Limits.preservesLimit_of_iso_diagram _ (diagramIsoPair K).symm /-- If a reflective subcategory is an exponential ideal, then the reflector preserves finite products. -/ lemma Limits.PreservesFiniteProducts.of_exponentialIdeal : PreservesFiniteProducts (reflector i) := have := preservesBinaryProducts_of_exponentialIdeal i have : PreservesLimitsOfShape _ (reflector i) := leftAdjoint_preservesTerminal_of_reflective.{0} i .of_preserves_binary_and_terminal _ @[deprecated (since := "2025-04-22")] alias preservesFiniteProducts_of_exponentialIdeal := PreservesFiniteProducts.of_exponentialIdeal end end CategoryTheory
ENatENNReal.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.ENat.Basic import Mathlib.Data.ENNReal.Basic /-! # Coercion from `ℕ∞` to `ℝ≥0∞` In this file we define a coercion from `ℕ∞` to `ℝ≥0∞` and prove some basic lemmas about this map. -/ assert_not_exists Finset open NNReal ENNReal noncomputable section namespace ENat variable {m n : ℕ∞} /-- Coercion from `ℕ∞` to `ℝ≥0∞`. -/ @[coe] def toENNReal : ℕ∞ → ℝ≥0∞ := ENat.map Nat.cast instance hasCoeENNReal : CoeTC ℕ∞ ℝ≥0∞ := ⟨toENNReal⟩ @[simp] theorem map_coe_nnreal : ENat.map ((↑) : ℕ → ℝ≥0) = ((↑) : ℕ∞ → ℝ≥0∞) := rfl /-- Coercion `ℕ∞ → ℝ≥0∞` as an `OrderEmbedding`. -/ @[simps! -fullyApplied] def toENNRealOrderEmbedding : ℕ∞ ↪o ℝ≥0∞ := Nat.castOrderEmbedding.withTopMap /-- Coercion `ℕ∞ → ℝ≥0∞` as a ring homomorphism. -/ @[simps! -fullyApplied] def toENNRealRingHom : ℕ∞ →+* ℝ≥0∞ := .ENatMap (Nat.castRingHom ℝ≥0) Nat.cast_injective @[simp, norm_cast] theorem toENNReal_top : ((⊤ : ℕ∞) : ℝ≥0∞) = ⊤ := rfl @[simp, norm_cast] theorem toENNReal_coe (n : ℕ) : ((n : ℕ∞) : ℝ≥0∞) = n := rfl @[simp, norm_cast] theorem toENNReal_ofNat (n : ℕ) [n.AtLeastTwo] : ((ofNat(n) : ℕ∞) : ℝ≥0∞) = ofNat(n) := rfl @[simp, norm_cast] theorem toENNReal_inj : (m : ℝ≥0∞) = (n : ℝ≥0∞) ↔ m = n := toENNRealOrderEmbedding.eq_iff_eq @[simp, norm_cast] lemma toENNReal_eq_top : (n : ℝ≥0∞) = ∞ ↔ n = ⊤ := by simp [← toENNReal_inj] @[norm_cast] lemma toENNReal_ne_top : (n : ℝ≥0∞) ≠ ∞ ↔ n ≠ ⊤ := by simp @[simp, norm_cast] theorem toENNReal_le : (m : ℝ≥0∞) ≤ n ↔ m ≤ n := toENNRealOrderEmbedding.le_iff_le @[simp, norm_cast] theorem toENNReal_lt : (m : ℝ≥0∞) < n ↔ m < n := toENNRealOrderEmbedding.lt_iff_lt @[simp, norm_cast] lemma toENNReal_lt_top : (n : ℝ≥0∞) < ∞ ↔ n < ⊤ := by simp [← toENNReal_lt] @[mono] theorem toENNReal_mono : Monotone ((↑) : ℕ∞ → ℝ≥0∞) := toENNRealOrderEmbedding.monotone @[mono] theorem toENNReal_strictMono : StrictMono ((↑) : ℕ∞ → ℝ≥0∞) := toENNRealOrderEmbedding.strictMono @[simp, norm_cast] theorem toENNReal_zero : ((0 : ℕ∞) : ℝ≥0∞) = 0 := map_zero toENNRealRingHom @[simp, norm_cast] theorem toENNReal_add (m n : ℕ∞) : ↑(m + n) = (m + n : ℝ≥0∞) := map_add toENNRealRingHom m n @[simp, norm_cast] theorem toENNReal_one : ((1 : ℕ∞) : ℝ≥0∞) = 1 := map_one toENNRealRingHom @[simp, norm_cast] theorem toENNReal_mul (m n : ℕ∞) : ↑(m * n) = (m * n : ℝ≥0∞) := map_mul toENNRealRingHom m n @[simp, norm_cast] theorem toENNReal_pow (x : ℕ∞) (n : ℕ) : (x ^ n : ℕ∞) = (x : ℝ≥0∞) ^ n := RingHom.map_pow toENNRealRingHom x n @[simp, norm_cast] theorem toENNReal_min (m n : ℕ∞) : ↑(min m n) = (min m n : ℝ≥0∞) := toENNReal_mono.map_min @[simp, norm_cast] theorem toENNReal_max (m n : ℕ∞) : ↑(max m n) = (max m n : ℝ≥0∞) := toENNReal_mono.map_max @[simp, norm_cast] theorem toENNReal_sub (m n : ℕ∞) : ↑(m - n) = (m - n : ℝ≥0∞) := WithTop.map_sub Nat.cast_tsub Nat.cast_zero m n end ENat
IsEmpty.lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Logic.Function.Basic import Mathlib.Logic.Relator /-! # Types that are empty In this file we define a typeclass `IsEmpty`, which expresses that a type has no elements. ## Main declaration * `IsEmpty`: a typeclass that expresses that a type is empty. -/ variable {α β γ : Sort*} /-- `IsEmpty α` expresses that `α` is empty. -/ class IsEmpty (α : Sort*) : Prop where protected false : α → False instance Empty.instIsEmpty : IsEmpty Empty := ⟨Empty.elim⟩ instance PEmpty.instIsEmpty : IsEmpty PEmpty := ⟨PEmpty.elim⟩ instance : IsEmpty False := ⟨id⟩ instance Fin.isEmpty : IsEmpty (Fin 0) := ⟨fun n ↦ Nat.not_lt_zero n.1 n.2⟩ instance Fin.isEmpty' : IsEmpty (Fin Nat.zero) := Fin.isEmpty protected theorem Function.isEmpty [IsEmpty β] (f : α → β) : IsEmpty α := ⟨fun x ↦ IsEmpty.false (f x)⟩ theorem Function.Surjective.isEmpty [IsEmpty α] {f : α → β} (hf : f.Surjective) : IsEmpty β := ⟨fun y ↦ let ⟨x, _⟩ := hf y; IsEmpty.false x⟩ -- See note [instance argument order] instance {p : α → Sort*} [∀ x, IsEmpty (p x)] [h : Nonempty α] : IsEmpty (∀ x, p x) := h.elim fun x ↦ Function.isEmpty <| Function.eval x instance PProd.isEmpty_left [IsEmpty α] : IsEmpty (PProd α β) := Function.isEmpty PProd.fst instance PProd.isEmpty_right [IsEmpty β] : IsEmpty (PProd α β) := Function.isEmpty PProd.snd instance Prod.isEmpty_left {α β} [IsEmpty α] : IsEmpty (α × β) := Function.isEmpty Prod.fst instance Prod.isEmpty_right {α β} [IsEmpty β] : IsEmpty (α × β) := Function.isEmpty Prod.snd instance Quot.instIsEmpty {α : Sort*} [IsEmpty α] {r : α → α → Prop} : IsEmpty (Quot r) := Function.Surjective.isEmpty Quot.exists_rep instance Quotient.instIsEmpty {α : Sort*} [IsEmpty α] {s : Setoid α} : IsEmpty (Quotient s) := Quot.instIsEmpty instance [IsEmpty α] [IsEmpty β] : IsEmpty (α ⊕' β) := ⟨fun x ↦ PSum.rec IsEmpty.false IsEmpty.false x⟩ instance instIsEmptySum {α β} [IsEmpty α] [IsEmpty β] : IsEmpty (α ⊕ β) := ⟨fun x ↦ Sum.rec IsEmpty.false IsEmpty.false x⟩ /-- subtypes of an empty type are empty -/ instance [IsEmpty α] (p : α → Prop) : IsEmpty (Subtype p) := ⟨fun x ↦ IsEmpty.false x.1⟩ /-- subtypes by an all-false predicate are false. -/ theorem Subtype.isEmpty_of_false {p : α → Prop} (hp : ∀ a, ¬p a) : IsEmpty (Subtype p) := ⟨fun x ↦ hp _ x.2⟩ /-- subtypes by false are false. -/ instance Subtype.isEmpty_false : IsEmpty { _a : α // False } := Subtype.isEmpty_of_false fun _ ↦ id instance Sigma.isEmpty_left {α} [IsEmpty α] {E : α → Type*} : IsEmpty (Sigma E) := Function.isEmpty Sigma.fst example [h : Nonempty α] [IsEmpty β] : IsEmpty (α → β) := by infer_instance /-- Eliminate out of a type that `IsEmpty` (without using projection notation). -/ @[elab_as_elim] def isEmptyElim [IsEmpty α] {p : α → Sort*} (a : α) : p a := (IsEmpty.false a).elim theorem isEmpty_iff : IsEmpty α ↔ α → False := ⟨@IsEmpty.false α, IsEmpty.mk⟩ namespace IsEmpty open Function universe u in /-- Eliminate out of a type that `IsEmpty` (using projection notation). -/ @[elab_as_elim] protected def elim {α : Sort u} (_ : IsEmpty α) {p : α → Sort*} (a : α) : p a := isEmptyElim a /-- Non-dependent version of `IsEmpty.elim`. Helpful if the elaborator cannot elaborate `h.elim a` correctly. -/ protected def elim' {β : Sort*} (h : IsEmpty α) (a : α) : β := (h.false a).elim protected theorem prop_iff {p : Prop} : IsEmpty p ↔ ¬p := isEmpty_iff variable [IsEmpty α] @[simp] theorem forall_iff {p : α → Prop} : (∀ a, p a) ↔ True := iff_true_intro isEmptyElim @[simp] theorem exists_iff {p : α → Prop} : (∃ a, p a) ↔ False := iff_false_intro fun ⟨x, _⟩ ↦ IsEmpty.false x -- see Note [lower instance priority] instance (priority := 100) : Subsingleton α := ⟨isEmptyElim⟩ end IsEmpty @[simp] theorem not_nonempty_iff : ¬Nonempty α ↔ IsEmpty α := ⟨fun h ↦ ⟨fun x ↦ h ⟨x⟩⟩, fun h1 h2 ↦ h2.elim h1.elim⟩ @[simp] theorem not_isEmpty_iff : ¬IsEmpty α ↔ Nonempty α := not_iff_comm.mp not_nonempty_iff @[simp] theorem isEmpty_Prop {p : Prop} : IsEmpty p ↔ ¬p := by simp only [← not_nonempty_iff, nonempty_prop] @[simp] theorem isEmpty_pi {π : α → Sort*} : IsEmpty (∀ a, π a) ↔ ∃ a, IsEmpty (π a) := by simp only [← not_nonempty_iff, Classical.nonempty_pi, not_forall] theorem isEmpty_fun : IsEmpty (α → β) ↔ Nonempty α ∧ IsEmpty β := by rw [isEmpty_pi, ← exists_true_iff_nonempty, ← exists_and_right, true_and] @[simp] theorem nonempty_fun : Nonempty (α → β) ↔ IsEmpty α ∨ Nonempty β := not_iff_not.mp <| by rw [not_or, not_nonempty_iff, not_nonempty_iff, isEmpty_fun, not_isEmpty_iff] @[simp] theorem isEmpty_sigma {α} {E : α → Type*} : IsEmpty (Sigma E) ↔ ∀ a, IsEmpty (E a) := by simp only [← not_nonempty_iff, nonempty_sigma, not_exists] @[simp] theorem isEmpty_psigma {α} {E : α → Sort*} : IsEmpty (PSigma E) ↔ ∀ a, IsEmpty (E a) := by simp only [← not_nonempty_iff, nonempty_psigma, not_exists] theorem isEmpty_subtype (p : α → Prop) : IsEmpty (Subtype p) ↔ ∀ x, ¬p x := by simp only [← not_nonempty_iff, nonempty_subtype, not_exists] @[simp] theorem isEmpty_prod {α β : Type*} : IsEmpty (α × β) ↔ IsEmpty α ∨ IsEmpty β := by simp only [← not_nonempty_iff, nonempty_prod, not_and_or] @[simp] theorem isEmpty_pprod : IsEmpty (PProd α β) ↔ IsEmpty α ∨ IsEmpty β := by simp only [← not_nonempty_iff, nonempty_pprod, not_and_or] @[simp] theorem isEmpty_sum {α β} : IsEmpty (α ⊕ β) ↔ IsEmpty α ∧ IsEmpty β := by simp only [← not_nonempty_iff, nonempty_sum, not_or] @[simp] theorem isEmpty_psum {α β} : IsEmpty (α ⊕' β) ↔ IsEmpty α ∧ IsEmpty β := by simp only [← not_nonempty_iff, nonempty_psum, not_or] @[simp] theorem isEmpty_ulift {α} : IsEmpty (ULift α) ↔ IsEmpty α := by simp only [← not_nonempty_iff, nonempty_ulift] @[simp] theorem isEmpty_plift {α} : IsEmpty (PLift α) ↔ IsEmpty α := by simp only [← not_nonempty_iff, nonempty_plift] theorem wellFounded_of_isEmpty {α} [IsEmpty α] (r : α → α → Prop) : WellFounded r := ⟨isEmptyElim⟩ variable (α) theorem isEmpty_or_nonempty : IsEmpty α ∨ Nonempty α := (em <| IsEmpty α).elim Or.inl <| Or.inr ∘ not_isEmpty_iff.mp @[simp] theorem not_isEmpty_of_nonempty [h : Nonempty α] : ¬IsEmpty α := not_isEmpty_iff.mpr h variable {α} theorem Function.extend_of_isEmpty [IsEmpty α] (f : α → β) (g : α → γ) (h : β → γ) : Function.extend f g h = h := funext fun _ ↦ (Function.extend_apply' _ _ _) fun ⟨a, _⟩ ↦ isEmptyElim a open Relator variable {α β : Type*} (R : α → β → Prop) @[simp] theorem leftTotal_empty [IsEmpty α] : LeftTotal R := by simp only [LeftTotal, IsEmpty.forall_iff] theorem leftTotal_iff_isEmpty_left [IsEmpty β] : LeftTotal R ↔ IsEmpty α := by simp only [LeftTotal, IsEmpty.exists_iff, isEmpty_iff] @[simp] theorem rightTotal_empty [IsEmpty β] : RightTotal R := by simp only [RightTotal, IsEmpty.forall_iff] theorem rightTotal_iff_isEmpty_right [IsEmpty α] : RightTotal R ↔ IsEmpty β := by simp only [RightTotal, IsEmpty.exists_iff, isEmpty_iff] @[simp] theorem biTotal_empty [IsEmpty α] [IsEmpty β] : BiTotal R := ⟨leftTotal_empty R, rightTotal_empty R⟩ theorem biTotal_iff_isEmpty_right [IsEmpty α] : BiTotal R ↔ IsEmpty β := by simp only [BiTotal, leftTotal_empty, rightTotal_iff_isEmpty_right, true_and] theorem biTotal_iff_isEmpty_left [IsEmpty β] : BiTotal R ↔ IsEmpty α := by simp only [BiTotal, leftTotal_iff_isEmpty_left, rightTotal_empty, and_true]
SumFourSquares.lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.FieldTheory.Finite.Basic /-! # Lagrange's four square theorem The main result in this file is `sum_four_squares`, a proof that every natural number is the sum of four square numbers. ## Implementation Notes The proof used is close to Lagrange's original proof. -/ open Finset Polynomial FiniteField Equiv /-- **Euler's four-square identity**. -/ theorem euler_four_squares {R : Type*} [CommRing R] (a b c d x y z w : R) : (a * x - b * y - c * z - d * w) ^ 2 + (a * y + b * x + c * w - d * z) ^ 2 + (a * z - b * w + c * x + d * y) ^ 2 + (a * w + b * z - c * y + d * x) ^ 2 = (a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2 + w ^ 2) := by ring /-- **Euler's four-square identity**, a version for natural numbers. -/ theorem Nat.euler_four_squares (a b c d x y z w : ℕ) : ((a : ℤ) * x - b * y - c * z - d * w).natAbs ^ 2 + ((a : ℤ) * y + b * x + c * w - d * z).natAbs ^ 2 + ((a : ℤ) * z - b * w + c * x + d * y).natAbs ^ 2 + ((a : ℤ) * w + b * z - c * y + d * x).natAbs ^ 2 = (a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2 + w ^ 2) := by rw [← Int.natCast_inj] push_cast simp only [sq_abs, _root_.euler_four_squares] namespace Int theorem sq_add_sq_of_two_mul_sq_add_sq {m x y : ℤ} (h : 2 * m = x ^ 2 + y ^ 2) : m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 := have : Even (x ^ 2 + y ^ 2) := by simp [← h] mul_right_injective₀ (show (2 * 2 : ℤ) ≠ 0 by decide) <| calc 2 * 2 * m = (x - y) ^ 2 + (x + y) ^ 2 := by rw [mul_assoc, h]; ring _ = (2 * ((x - y) / 2)) ^ 2 + (2 * ((x + y) / 2)) ^ 2 := by rw [Int.mul_ediv_cancel' _, Int.mul_ediv_cancel' _] <;> simpa [sq, parity_simps, ← even_iff_two_dvd] _ = 2 * 2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) := by nlinarith theorem lt_of_sum_four_squares_eq_mul {a b c d k m : ℕ} (h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m) (ha : 2 * a < m) (hb : 2 * b < m) (hc : 2 * c < m) (hd : 2 * d < m) : k < m := by nlinarith theorem exists_sq_add_sq_add_one_eq_mul (p : ℕ) [hp : Fact p.Prime] : ∃ (a b k : ℕ), 0 < k ∧ k < p ∧ a ^ 2 + b ^ 2 + 1 = k * p := by rcases hp.1.eq_two_or_odd' with (rfl | hodd) · use 1, 0, 1; simp rcases Nat.sq_add_sq_zmodEq p (-1) with ⟨a, b, ha, hb, hab⟩ rcases Int.modEq_iff_dvd.1 hab.symm with ⟨k, hk⟩ rw [sub_neg_eq_add, mul_comm] at hk have hk₀ : 0 < k := by refine pos_of_mul_pos_left ?_ (Nat.cast_nonneg p) rw [← hk] positivity lift k to ℕ using hk₀.le refine ⟨a, b, k, Nat.cast_pos.1 hk₀, ?_, mod_cast hk⟩ replace hk : a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p := mod_cast hk refine lt_of_sum_four_squares_eq_mul hk ?_ ?_ ?_ ?_ · exact (mul_le_mul' le_rfl ha).trans_lt (Nat.mul_div_lt_iff_not_dvd.2 hodd.not_two_dvd_nat) · exact (mul_le_mul' le_rfl hb).trans_lt (Nat.mul_div_lt_iff_not_dvd.2 hodd.not_two_dvd_nat) · exact lt_of_le_of_ne hp.1.two_le (hodd.ne_two_of_dvd_nat (dvd_refl _)).symm · exact hp.1.pos end Int namespace Nat open Int private theorem sum_four_squares_of_two_mul_sum_four_squares {m a b c d : ℤ} (h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m) : ∃ w x y z : ℤ, w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = m := by have : ∀ f : Fin 4 → ZMod 2, f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i : Fin 4, f i ^ 2 + f (swap i 0 1) ^ 2 = 0 ∧ f (swap i 0 2) ^ 2 + f (swap i 0 3) ^ 2 = 0 := by decide set f : Fin 4 → ℤ := ![a, b, c, d] obtain ⟨i, hσ⟩ := this (fun x => ↑(f x)) <| by rw [← @zero_mul (ZMod 2) _ m, ← show ((2 : ℤ) : ZMod 2) = 0 from rfl, ← Int.cast_mul, ← h] simp only [Int.cast_add, Int.cast_pow] rfl set σ := swap i 0 obtain ⟨x, hx⟩ : (2 : ℤ) ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2 := (CharP.intCast_eq_zero_iff (ZMod 2) 2 _).1 <| by simpa only [σ, Int.cast_pow, Int.cast_add, Equiv.swap_apply_right, ZMod.pow_card] using hσ.1 obtain ⟨y, hy⟩ : (2 : ℤ) ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2 := (CharP.intCast_eq_zero_iff (ZMod 2) 2 _).1 <| by simpa only [Int.cast_pow, Int.cast_add, ZMod.pow_card] using hσ.2 refine ⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2, (f (σ 2) + f (σ 3)) / 2, ?_⟩ rw [← Int.sq_add_sq_of_two_mul_sq_add_sq hx.symm, add_assoc, ← Int.sq_add_sq_of_two_mul_sq_add_sq hy.symm, ← mul_right_inj' two_ne_zero, ← h, mul_add] have : (∑ x, f (σ x) ^ 2) = ∑ x, f x ^ 2 := Equiv.sum_comp σ (f · ^ 2) simpa only [← hx, ← hy, Fin.sum_univ_four, add_assoc] using this /-- Lagrange's **four squares theorem** for a prime number. Use `Nat.sum_four_squares` instead. -/ protected theorem Prime.sum_four_squares {p : ℕ} (hp : p.Prime) : ∃ a b c d : ℕ, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p := by classical have := Fact.mk hp -- Find `a`, `b`, `c`, `d`, `0 < m < p` such that `a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p` have natAbs_iff {a b c d : ℤ} {k : ℕ} : a.natAbs ^ 2 + b.natAbs ^ 2 + c.natAbs ^ 2 + d.natAbs ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k := by rw [← @Nat.cast_inj ℤ]; push_cast [sq_abs]; rfl have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℕ, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p := by obtain ⟨a, b, k, hk₀, hkp, hk⟩ := exists_sq_add_sq_add_one_eq_mul p refine ⟨k, hkp, hk₀, a, b, 1, 0, ?_⟩ simpa -- Take the minimal possible `m` rcases Nat.findX hm with ⟨m, ⟨hmp, hm₀, a, b, c, d, habcd⟩, hmin⟩ -- If `m = 1`, then we are done rcases (Nat.one_le_iff_ne_zero.2 hm₀.ne').eq_or_lt with rfl | hm₁ · use a, b, c, d; simpa using habcd -- Otherwise, let us find a contradiction exfalso have : NeZero m := ⟨hm₀.ne'⟩ by_cases hm : 2 ∣ m · -- If `m` is an even number, then `(m / 2) * p` can be represented as a sum of four squares rcases hm with ⟨m, rfl⟩ rw [mul_pos_iff_of_pos_left two_pos] at hm₀ have hm₂ : m < 2 * m := by simpa [two_mul] apply_fun (Nat.cast : ℕ → ℤ) at habcd push_cast [mul_assoc] at habcd obtain ⟨_, _, _, _, h⟩ := sum_four_squares_of_two_mul_sum_four_squares habcd exact hmin m hm₂ ⟨hm₂.trans hmp, hm₀, _, _, _, _, natAbs_iff.2 h⟩ · -- For each `x` in `a`, `b`, `c`, `d`, take a number `f x ≡ x [ZMOD m]` with least possible -- absolute value obtain ⟨f, hf_lt, hf_mod⟩ : ∃ f : ℕ → ℤ, (∀ x, 2 * (f x).natAbs < m) ∧ ∀ x, (f x : ZMod m) = x := by refine ⟨fun x ↦ (x : ZMod m).valMinAbs, fun x ↦ ?_, fun x ↦ (x : ZMod m).coe_valMinAbs⟩ exact (mul_le_mul' le_rfl (x : ZMod m).natAbs_valMinAbs_le).trans_lt (Nat.mul_div_lt_iff_not_dvd.2 hm) -- Since `|f x| ^ 2 = (f x) ^ 2 ≡ x ^ 2 [ZMOD m]`, we have -- `m ∣ |f a| ^ 2 + |f b| ^ 2 + |f c| ^ 2 + |f d| ^ 2` obtain ⟨r, hr⟩ : m ∣ (f a).natAbs ^ 2 + (f b).natAbs ^ 2 + (f c).natAbs ^ 2 + (f d).natAbs ^ 2 := by simp only [← Int.natCast_dvd_natCast, ← ZMod.intCast_zmod_eq_zero_iff_dvd] push_cast [hf_mod, sq_abs] norm_cast simp [habcd] -- The quotient `r` is not zero, because otherwise `f a = f b = f c = f d = 0`, hence -- `m` divides each `a`, `b`, `c`, `d`, thus `m ∣ p` which is impossible. rcases (zero_le r).eq_or_lt with rfl | hr₀ · replace hr : f a = 0 ∧ f b = 0 ∧ f c = 0 ∧ f d = 0 := by simpa [and_assoc] using hr obtain ⟨⟨a, rfl⟩, ⟨b, rfl⟩, ⟨c, rfl⟩, ⟨d, rfl⟩⟩ : m ∣ a ∧ m ∣ b ∧ m ∣ c ∧ m ∣ d := by simp only [← ZMod.natCast_eq_zero_iff, ← hf_mod, hr, Int.cast_zero, and_self] have : m * m ∣ m * p := habcd ▸ ⟨a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2, by ring⟩ rw [mul_dvd_mul_iff_left hm₀.ne'] at this exact (hp.eq_one_or_self_of_dvd _ this).elim hm₁.ne' hmp.ne -- Since `2 * |f x| < m` for each `x ∈ {a, b, c, d}`, we have `r < m` have hrm : r < m := by rw [mul_comm] at hr apply lt_of_sum_four_squares_eq_mul hr <;> apply hf_lt -- Now it suffices to represent `r * p` as a sum of four squares -- More precisely, we will represent `(m * r) * (m * p)` as a sum of squares of four numbers, -- each of them is divisible by `m` rsuffices ⟨w, x, y, z, hw, hx, hy, hz, h⟩ : ∃ w x y z : ℤ, ↑m ∣ w ∧ ↑m ∣ x ∧ ↑m ∣ y ∧ ↑m ∣ z ∧ w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) · have : (w / m) ^ 2 + (x / m) ^ 2 + (y / m) ^ 2 + (z / m) ^ 2 = ↑(r * p) := by refine mul_left_cancel₀ (pow_ne_zero 2 (Nat.cast_ne_zero.2 hm₀.ne')) ?_ conv_rhs => rw [← Nat.cast_pow, ← Nat.cast_mul, sq m, mul_mul_mul_comm, Nat.cast_mul, ← h] simp only [mul_add, ← mul_pow, Int.mul_ediv_cancel', *] rw [← natAbs_iff] at this exact hmin r hrm ⟨hrm.trans hmp, hr₀, _, _, _, _, this⟩ -- To do the last step, we apply the Euler's four square identity once more replace hr : (f b) ^ 2 + (f a) ^ 2 + (f d) ^ 2 + (-f c) ^ 2 = ↑(m * r) := by rw [← natAbs_iff, natAbs_neg, ← hr] ac_rfl have := congr_arg₂ (· * Nat.cast ·) hr habcd simp only [← _root_.euler_four_squares, Nat.cast_add, Nat.cast_pow] at this refine ⟨_, _, _, _, ?_, ?_, ?_, ?_, this⟩ · simp [← ZMod.intCast_zmod_eq_zero_iff_dvd, hf_mod, mul_comm] · suffices ((a : ZMod m) ^ 2 + (b : ZMod m) ^ 2 + (c : ZMod m) ^ 2 + (d : ZMod m) ^ 2) = 0 by simpa [← ZMod.intCast_zmod_eq_zero_iff_dvd, hf_mod, sq, add_comm, add_assoc, add_left_comm] using this norm_cast simp [habcd] · simp [← ZMod.intCast_zmod_eq_zero_iff_dvd, hf_mod, mul_comm] · simp [← ZMod.intCast_zmod_eq_zero_iff_dvd, hf_mod, mul_comm] /-- **Four squares theorem** -/ theorem sum_four_squares (n : ℕ) : ∃ a b c d : ℕ, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = n := by -- The proof is by induction on prime factorization. The case of prime `n` was proved above, -- the inductive step follows from `Nat.euler_four_squares`. induction n using Nat.recOnMul with | zero => exact ⟨0, 0, 0, 0, rfl⟩ | one => exact ⟨1, 0, 0, 0, rfl⟩ | prime p hp => exact hp.sum_four_squares | mul m n hm hn => rcases hm with ⟨a, b, c, d, rfl⟩ rcases hn with ⟨w, x, y, z, rfl⟩ exact ⟨_, _, _, _, euler_four_squares _ _ _ _ _ _ _ _⟩ end Nat
Adjunction.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.Functor.KanExtension.Pointwise import Mathlib.CategoryTheory.Limits.Shapes.Grothendieck import Mathlib.CategoryTheory.Comma.StructuredArrow.Functor /-! # The Kan extension functor Given a functor `L : C ⥤ D`, we define the left Kan extension functor `L.lan : (C ⥤ H) ⥤ (D ⥤ H)` which sends a functor `F : C ⥤ H` to its left Kan extension along `L`. This is defined if all `F` have such a left Kan extension. It is shown that `L.lan` is the left adjoint to the functor `(D ⥤ H) ⥤ (C ⥤ H)` given by the precomposition with `L` (see `Functor.lanAdjunction`). Similarly, we define the right Kan extension functor `L.ran : (C ⥤ H) ⥤ (D ⥤ H)` which sends a functor `F : C ⥤ H` to its right Kan extension along `L`. -/ namespace CategoryTheory open Category Limits namespace Functor variable {C D : Type*} [Category C] [Category D] (L : C ⥤ D) {H : Type*} [Category H] section lan section variable [∀ (F : C ⥤ H), HasLeftKanExtension L F] /-- The left Kan extension functor `(C ⥤ H) ⥤ (D ⥤ H)` along a functor `C ⥤ D`. -/ noncomputable def lan : (C ⥤ H) ⥤ (D ⥤ H) where obj F := leftKanExtension L F map {F₁ F₂} φ := descOfIsLeftKanExtension _ (leftKanExtensionUnit L F₁) _ (φ ≫ leftKanExtensionUnit L F₂) /-- The natural transformation `F ⟶ L ⋙ (L.lan).obj G`. -/ noncomputable def lanUnit : (𝟭 (C ⥤ H)) ⟶ L.lan ⋙ (whiskeringLeft C D H).obj L where app F := leftKanExtensionUnit L F naturality {F₁ F₂} φ := by ext; simp [lan] instance (F : C ⥤ H) : (L.lan.obj F).IsLeftKanExtension (L.lanUnit.app F) := by dsimp [lan, lanUnit] infer_instance end /-- If there exists a pointwise left Kan extension of `F` along `L`, then `L.lan.obj G` is a pointwise left Kan extension of `F`. -/ noncomputable def isPointwiseLeftKanExtensionLeftKanExtensionUnit (F : C ⥤ H) [HasPointwiseLeftKanExtension L F] : (LeftExtension.mk _ (L.leftKanExtensionUnit F)).IsPointwiseLeftKanExtension := isPointwiseLeftKanExtensionOfIsLeftKanExtension (F := F) _ (leftKanExtensionUnit L F) section open CostructuredArrow variable (F : C ⥤ H) [HasPointwiseLeftKanExtension L F] /-- If a left Kan extension is pointwise, then evaluating it at an object is isomorphic to taking a colimit. -/ noncomputable def leftKanExtensionObjIsoColimit [HasLeftKanExtension L F] (X : D) : (L.leftKanExtension F).obj X ≅ colimit (proj L X ⋙ F) := LeftExtension.IsPointwiseLeftKanExtensionAt.isoColimit (F := F) (isPointwiseLeftKanExtensionLeftKanExtensionUnit L F X) @[reassoc (attr := simp)] lemma ι_leftKanExtensionObjIsoColimit_inv [HasLeftKanExtension L F] (X : D) (f : CostructuredArrow L X) : colimit.ι _ f ≫ (L.leftKanExtensionObjIsoColimit F X).inv = (L.leftKanExtensionUnit F).app f.left ≫ (L.leftKanExtension F).map f.hom := by simp [leftKanExtensionObjIsoColimit] @[reassoc (attr := simp)] lemma ι_leftKanExtensionObjIsoColimit_hom (X : D) (f : CostructuredArrow L X) : (L.leftKanExtensionUnit F).app f.left ≫ (L.leftKanExtension F).map f.hom ≫ (L.leftKanExtensionObjIsoColimit F X).hom = colimit.ι (proj L X ⋙ F) f := LeftExtension.IsPointwiseLeftKanExtensionAt.ι_isoColimit_hom (F := F) (isPointwiseLeftKanExtensionLeftKanExtensionUnit L F X) f lemma leftKanExtensionUnit_leftKanExtension_map_leftKanExtensionObjIsoColimit_hom (X : D) (f : CostructuredArrow L X) : (leftKanExtensionUnit L F).app f.left ≫ (leftKanExtension L F).map f.hom ≫ (L.leftKanExtensionObjIsoColimit F X).hom = colimit.ι (proj L X ⋙ F) f := LeftExtension.IsPointwiseLeftKanExtensionAt.ι_isoColimit_hom (F := F) (isPointwiseLeftKanExtensionLeftKanExtensionUnit L F X) f @[reassoc (attr := simp)] lemma leftKanExtensionUnit_leftKanExtensionObjIsoColimit_hom (X : C) : (L.leftKanExtensionUnit F).app X ≫ (L.leftKanExtensionObjIsoColimit F (L.obj X)).hom = colimit.ι (proj L (L.obj X) ⋙ F) (CostructuredArrow.mk (𝟙 _)) := by simpa using leftKanExtensionUnit_leftKanExtension_map_leftKanExtensionObjIsoColimit_hom L F (L.obj X) (CostructuredArrow.mk (𝟙 _)) @[instance] theorem hasColimit_map_comp_ι_comp_grothendieckProj {X Y : D} (f : X ⟶ Y) : HasColimit ((functor L).map f ⋙ Grothendieck.ι (functor L) Y ⋙ grothendieckProj L ⋙ F) := hasColimit_of_iso (isoWhiskerRight (mapCompιCompGrothendieckProj L f) F) @[deprecated (since := "2025-07-27")] alias hasColimit_map_comp_ι_comp_grotendieckProj := hasColimit_map_comp_ι_comp_grothendieckProj /-- The left Kan extension of `F : C ⥤ H` along a functor `L : C ⥤ D` is isomorphic to the fiberwise colimit of the projection functor on the Grothendieck construction of the costructured arrow category composed with `F`. -/ @[simps!] noncomputable def leftKanExtensionIsoFiberwiseColimit [HasLeftKanExtension L F] : leftKanExtension L F ≅ fiberwiseColimit (grothendieckProj L ⋙ F) := letI : ∀ X, HasColimit (Grothendieck.ι (functor L) X ⋙ grothendieckProj L ⋙ F) := fun X => hasColimit_of_iso <| Iso.symm <| isoWhiskerRight (eqToIso ((functor L).map_id X)) _ ≪≫ Functor.leftUnitor (Grothendieck.ι (functor L) X ⋙ grothendieckProj L ⋙ F) Iso.symm <| NatIso.ofComponents (fun X => HasColimit.isoOfNatIso (isoWhiskerRight (ιCompGrothendieckProj L X) F) ≪≫ (leftKanExtensionObjIsoColimit L F X).symm) fun f => colimit.hom_ext (by simp) end section HasLeftKanExtension variable [∀ (F : C ⥤ H), HasLeftKanExtension L F] variable (H) in /-- The left Kan extension functor `L.Lan` is left adjoint to the precomposition by `L`. -/ noncomputable def lanAdjunction : L.lan ⊣ (whiskeringLeft C D H).obj L := Adjunction.mkOfHomEquiv { homEquiv := fun F G => homEquivOfIsLeftKanExtension _ (L.lanUnit.app F) G homEquiv_naturality_left_symm := fun {F₁ F₂ G} f α => hom_ext_of_isLeftKanExtension _ (L.lanUnit.app F₁) _ _ (by ext X dsimp [homEquivOfIsLeftKanExtension] rw [descOfIsLeftKanExtension_fac_app, NatTrans.comp_app, ← assoc] have h := congr_app (L.lanUnit.naturality f) X dsimp at h ⊢ rw [← h, assoc, descOfIsLeftKanExtension_fac_app] ) homEquiv_naturality_right := fun {F G₁ G₂} β f => by dsimp [homEquivOfIsLeftKanExtension] rw [assoc] } variable (H) in @[simp] lemma lanAdjunction_unit : (L.lanAdjunction H).unit = L.lanUnit := by ext F : 2 dsimp [lanAdjunction, homEquivOfIsLeftKanExtension] simp lemma lanAdjunction_counit_app (G : D ⥤ H) : (L.lanAdjunction H).counit.app G = descOfIsLeftKanExtension (L.lan.obj (L ⋙ G)) (L.lanUnit.app (L ⋙ G)) G (𝟙 (L ⋙ G)) := rfl @[reassoc (attr := simp)] lemma lanUnit_app_whiskerLeft_lanAdjunction_counit_app (G : D ⥤ H) : L.lanUnit.app (L ⋙ G) ≫ whiskerLeft L ((L.lanAdjunction H).counit.app G) = 𝟙 (L ⋙ G) := by simp [lanAdjunction_counit_app] @[reassoc (attr := simp)] lemma lanUnit_app_app_lanAdjunction_counit_app_app (G : D ⥤ H) (X : C) : (L.lanUnit.app (L ⋙ G)).app X ≫ ((L.lanAdjunction H).counit.app G).app (L.obj X) = 𝟙 _ := congr_app (L.lanUnit_app_whiskerLeft_lanAdjunction_counit_app G) X lemma isIso_lanAdjunction_counit_app_iff (G : D ⥤ H) : IsIso ((L.lanAdjunction H).counit.app G) ↔ G.IsLeftKanExtension (𝟙 (L ⋙ G)) := (isLeftKanExtension_iff_isIso _ (L.lanUnit.app (L ⋙ G)) _ (by simp)).symm /-- Composing the left Kan extension of `L : C ⥤ D` with `colim` on shapes `D` is isomorphic to `colim` on shapes `C`. -/ @[simps!] noncomputable def lanCompColimIso [HasColimitsOfShape C H] [HasColimitsOfShape D H] : L.lan ⋙ colim ≅ colim (C := H) := Iso.symm <| NatIso.ofComponents (fun G ↦ (colimitIsoOfIsLeftKanExtension _ (L.lanUnit.app G)).symm) (fun f ↦ colimit.hom_ext (fun i ↦ by dsimp rw [ι_colimMap_assoc, ι_colimitIsoOfIsLeftKanExtension_inv, ι_colimitIsoOfIsLeftKanExtension_inv_assoc, ι_colimMap, ← assoc, ← assoc] congr 1 exact congr_app (L.lanUnit.naturality f) i)) end HasLeftKanExtension section HasPointwiseLeftKanExtension variable (G : C ⥤ H) [L.HasPointwiseLeftKanExtension G] variable [HasColimitsOfShape D H] instance : HasColimit (CostructuredArrow.grothendieckProj L ⋙ G) := hasColimit_of_hasColimit_fiberwiseColimit_of_hasColimit _ variable [HasColimitsOfShape C H] /-- If `G : C ⥤ H` admits a left Kan extension along a functor `L : C ⥤ D` and `H` has colimits of shape `C` and `D`, then the colimit of `G` is isomorphic to the colimit of a canonical functor `Grothendieck (CostructuredArrow.functor L) ⥤ H` induced by `L` and `G`. -/ noncomputable def colimitIsoColimitGrothendieck : colimit G ≅ colimit (CostructuredArrow.grothendieckProj L ⋙ G) := calc colimit G ≅ colimit (leftKanExtension L G) := (colimitIsoOfIsLeftKanExtension _ (L.leftKanExtensionUnit G)).symm _ ≅ colimit (fiberwiseColimit (CostructuredArrow.grothendieckProj L ⋙ G)) := HasColimit.isoOfNatIso (leftKanExtensionIsoFiberwiseColimit L G) _ ≅ colimit (CostructuredArrow.grothendieckProj L ⋙ G) := colimitFiberwiseColimitIso _ @[reassoc (attr := simp)] lemma ι_colimitIsoColimitGrothendieck_inv (X : Grothendieck (CostructuredArrow.functor L)) : colimit.ι (CostructuredArrow.grothendieckProj L ⋙ G) X ≫ (colimitIsoColimitGrothendieck L G).inv = colimit.ι G ((CostructuredArrow.proj L X.base).obj X.fiber) := by simp [colimitIsoColimitGrothendieck] @[reassoc (attr := simp)] lemma ι_colimitIsoColimitGrothendieck_hom (X : C) : colimit.ι G X ≫ (colimitIsoColimitGrothendieck L G).hom = colimit.ι (CostructuredArrow.grothendieckProj L ⋙ G) ⟨L.obj X, .mk (𝟙 _)⟩ := by rw [← Iso.eq_comp_inv] exact (ι_colimitIsoColimitGrothendieck_inv L G ⟨L.obj X, .mk (𝟙 _)⟩).symm end HasPointwiseLeftKanExtension section variable [Full L] [Faithful L] instance (F : C ⥤ H) (X : C) [HasPointwiseLeftKanExtension L F] [∀ (F : C ⥤ H), HasLeftKanExtension L F] : IsIso ((L.lanUnit.app F).app X) := (isPointwiseLeftKanExtensionLeftKanExtensionUnit L F (L.obj X)).isIso_hom_app instance (F : C ⥤ H) [HasPointwiseLeftKanExtension L F] [∀ (F : C ⥤ H), HasLeftKanExtension L F] : IsIso (L.lanUnit.app F) := NatIso.isIso_of_isIso_app _ instance coreflective [∀ (F : C ⥤ H), HasPointwiseLeftKanExtension L F] : IsIso (L.lanUnit (H := H)) := by apply NatIso.isIso_of_isIso_app _ instance (F : C ⥤ H) [HasPointwiseLeftKanExtension L F] [∀ (F : C ⥤ H), HasLeftKanExtension L F] : IsIso ((L.lanAdjunction H).unit.app F) := by rw [lanAdjunction_unit] infer_instance instance coreflective' [∀ (F : C ⥤ H), HasPointwiseLeftKanExtension L F] : IsIso (L.lanAdjunction H).unit := by apply NatIso.isIso_of_isIso_app _ end end lan section ran section variable [∀ (F : C ⥤ H), HasRightKanExtension L F] /-- The right Kan extension functor `(C ⥤ H) ⥤ (D ⥤ H)` along a functor `C ⥤ D`. -/ noncomputable def ran : (C ⥤ H) ⥤ (D ⥤ H) where obj F := rightKanExtension L F map {F₁ F₂} φ := liftOfIsRightKanExtension _ (rightKanExtensionCounit L F₂) _ (rightKanExtensionCounit L F₁ ≫ φ) /-- The natural transformation `L ⋙ (L.lan).obj G ⟶ L`. -/ noncomputable def ranCounit : L.ran ⋙ (whiskeringLeft C D H).obj L ⟶ (𝟭 (C ⥤ H)) where app F := rightKanExtensionCounit L F naturality {F₁ F₂} φ := by ext; simp [ran] instance (F : C ⥤ H) : (L.ran.obj F).IsRightKanExtension (L.ranCounit.app F) := by dsimp [ran, ranCounit] infer_instance /-- If there exists a pointwise right Kan extension of `F` along `L`, then `L.ran.obj G` is a pointwise right Kan extension of `F`. -/ noncomputable def isPointwiseRightKanExtensionRanCounit (F : C ⥤ H) [HasPointwiseRightKanExtension L F] : (RightExtension.mk _ (L.ranCounit.app F)).IsPointwiseRightKanExtension := isPointwiseRightKanExtensionOfIsRightKanExtension (F := F) _ (L.ranCounit.app F) /-- If a right Kan extension is pointwise, then evaluating it at an object is isomorphic to taking a limit. -/ noncomputable def ranObjObjIsoLimit (F : C ⥤ H) [HasPointwiseRightKanExtension L F] (X : D) : (L.ran.obj F).obj X ≅ limit (StructuredArrow.proj X L ⋙ F) := RightExtension.IsPointwiseRightKanExtensionAt.isoLimit (F := F) (isPointwiseRightKanExtensionRanCounit L F X) @[reassoc (attr := simp)] lemma ranObjObjIsoLimit_hom_π (F : C ⥤ H) [HasPointwiseRightKanExtension L F] (X : D) (f : StructuredArrow X L) : (L.ranObjObjIsoLimit F X).hom ≫ limit.π _ f = (L.ran.obj F).map f.hom ≫ (L.ranCounit.app F).app f.right := by simp [ranObjObjIsoLimit, ran, ranCounit] @[reassoc (attr := simp)] lemma ranObjObjIsoLimit_inv_π (F : C ⥤ H) [HasPointwiseRightKanExtension L F] (X : D) (f : StructuredArrow X L) : (L.ranObjObjIsoLimit F X).inv ≫ (L.ran.obj F).map f.hom ≫ (L.ranCounit.app F).app f.right = limit.π _ f := RightExtension.IsPointwiseRightKanExtensionAt.isoLimit_inv_π (F := F) (isPointwiseRightKanExtensionRanCounit L F X) f variable (H) in /-- The right Kan extension functor `L.ran` is right adjoint to the precomposition by `L`. -/ noncomputable def ranAdjunction : (whiskeringLeft C D H).obj L ⊣ L.ran := Adjunction.mkOfHomEquiv { homEquiv := fun F G => (homEquivOfIsRightKanExtension (α := L.ranCounit.app G) _ F).symm homEquiv_naturality_right := fun {F G₁ G₂} β f ↦ hom_ext_of_isRightKanExtension _ (L.ranCounit.app G₂) _ _ (by ext X dsimp [homEquivOfIsRightKanExtension] rw [liftOfIsRightKanExtension_fac_app, NatTrans.comp_app, assoc] have h := congr_app (L.ranCounit.naturality f) X dsimp at h ⊢ rw [h, liftOfIsRightKanExtension_fac_app_assoc]) homEquiv_naturality_left_symm := fun {F₁ F₂ G} β f ↦ by dsimp [homEquivOfIsRightKanExtension] rw [assoc] } variable (H) in @[simp] lemma ranAdjunction_counit : (L.ranAdjunction H).counit = L.ranCounit := by ext F : 2 dsimp [ranAdjunction, homEquivOfIsRightKanExtension] simp lemma ranAdjunction_unit_app (G : D ⥤ H) : (L.ranAdjunction H).unit.app G = liftOfIsRightKanExtension (L.ran.obj (L ⋙ G)) (L.ranCounit.app (L ⋙ G)) G (𝟙 (L ⋙ G)) := rfl @[reassoc (attr := simp)] lemma ranCounit_app_whiskerLeft_ranAdjunction_unit_app (G : D ⥤ H) : whiskerLeft L ((L.ranAdjunction H).unit.app G) ≫ L.ranCounit.app (L ⋙ G) = 𝟙 (L ⋙ G) := by simp [ranAdjunction_unit_app] @[reassoc (attr := simp)] lemma ranCounit_app_app_ranAdjunction_unit_app_app (G : D ⥤ H) (X : C) : ((L.ranAdjunction H).unit.app G).app (L.obj X) ≫ (L.ranCounit.app (L ⋙ G)).app X = 𝟙 _ := congr_app (L.ranCounit_app_whiskerLeft_ranAdjunction_unit_app G) X lemma isIso_ranAdjunction_unit_app_iff (G : D ⥤ H) : IsIso ((L.ranAdjunction H).unit.app G) ↔ G.IsRightKanExtension (𝟙 (L ⋙ G)) := (isRightKanExtension_iff_isIso _ (L.ranCounit.app (L ⋙ G)) _ (by simp)).symm /-- Composing the right Kan extension of `L : C ⥤ D` with `lim` on shapes `D` is isomorphic to `lim` on shapes `C`. -/ @[simps!] noncomputable def ranCompLimIso (L : C ⥤ D) [∀ (G : C ⥤ H), L.HasRightKanExtension G] [HasLimitsOfShape C H] [HasLimitsOfShape D H] : L.ran ⋙ lim ≅ lim (C := H) := NatIso.ofComponents (fun G ↦ limitIsoOfIsRightKanExtension _ (L.ranCounit.app G)) (fun f ↦ limit.hom_ext (fun i ↦ by dsimp rw [assoc, assoc, limMap_π, limitIsoOfIsRightKanExtension_hom_π_assoc, limitIsoOfIsRightKanExtension_hom_π, limMap_π_assoc] congr 1 exact congr_app (L.ranCounit.naturality f) i)) end section variable [Full L] [Faithful L] instance (F : C ⥤ H) (X : C) [HasPointwiseRightKanExtension L F] [∀ (F : C ⥤ H), HasRightKanExtension L F] : IsIso ((L.ranCounit.app F).app X) := (isPointwiseRightKanExtensionRanCounit L F (L.obj X)).isIso_hom_app instance (F : C ⥤ H) [HasPointwiseRightKanExtension L F] [∀ (F : C ⥤ H), HasRightKanExtension L F] : IsIso (L.ranCounit.app F) := NatIso.isIso_of_isIso_app _ instance reflective [∀ (F : C ⥤ H), HasPointwiseRightKanExtension L F] : IsIso (L.ranCounit (H := H)) := by apply NatIso.isIso_of_isIso_app _ instance (F : C ⥤ H) [HasPointwiseRightKanExtension L F] [∀ (F : C ⥤ H), HasRightKanExtension L F] : IsIso ((L.ranAdjunction H).counit.app F) := by rw [ranAdjunction_counit] infer_instance instance reflective' [∀ (F : C ⥤ H), HasPointwiseRightKanExtension L F] : IsIso (L.ranAdjunction H).counit := by apply NatIso.isIso_of_isIso_app _ end end ran end Functor end CategoryTheory
Deriv.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.Analysis.Complex.LocallyUniformLimit import Mathlib.NumberTheory.LSeries.Convergence import Mathlib.Analysis.SpecialFunctions.Pow.Deriv import Mathlib.Analysis.Complex.HalfPlane /-! # Differentiability and derivatives of L-series ## Main results * We show that the `LSeries` of `f` is differentiable at `s` when `re s` is greater than the abscissa of absolute convergence of `f` (`LSeries.hasDerivAt`) and that its derivative there is the negative of the `LSeries` of the point-wise product `log * f` (`LSeries.deriv`). * We prove similar results for iterated derivatives (`LSeries.iteratedDeriv`). * We use this to show that `LSeries f` is holomorphic on the right half-plane of absolute convergence (`LSeries.analyticOnNhd`). ## Implementation notes We introduce `LSeries.logMul` as an abbreviation for the point-wise product `log * f`, to avoid the problem that this expression does not type-check. -/ open Complex LSeries /-! ### The derivative of an L-series -/ /-- The (point-wise) product of `log : ℕ → ℂ` with `f`. -/ noncomputable abbrev LSeries.logMul (f : ℕ → ℂ) (n : ℕ) : ℂ := log n * f n /-- The derivative of the terms of an L-series. -/ lemma LSeries.hasDerivAt_term (f : ℕ → ℂ) (n : ℕ) (s : ℂ) : HasDerivAt (fun z ↦ term f z n) (-(term (logMul f) s n)) s := by rcases eq_or_ne n 0 with rfl | hn · simp [hasDerivAt_const] simp_rw [term_of_ne_zero hn, ← neg_div, ← neg_mul, mul_comm, mul_div_assoc, div_eq_mul_inv, ← cpow_neg] exact HasDerivAt.const_mul (f n) (by simpa only [mul_comm, ← mul_neg_one (log n), ← mul_assoc] using (hasDerivAt_neg' s).const_cpow (Or.inl <| Nat.cast_ne_zero.mpr hn)) /- This lemma proves two things at once, since their proofs are intertwined; we give separate non-private lemmas below that extract the two statements. -/ private lemma LSeries.LSeriesSummable_logMul_and_hasDerivAt {f : ℕ → ℂ} {s : ℂ} (h : abscissaOfAbsConv f < s.re) : LSeriesSummable (logMul f) s ∧ HasDerivAt (LSeries f) (-LSeries (logMul f) s) s := by -- The L-series of `f` is summable at some real `x < re s`. obtain ⟨x, hxs, hf⟩ := LSeriesSummable_lt_re_of_abscissaOfAbsConv_lt_re h obtain ⟨y, hxy, hys⟩ := exists_between hxs -- We work in the right half-plane `y < re z`, for some `y` such that `x < y < re s`, on which -- we have a uniform summable bound on `‖term f z ·‖`. let S : Set ℂ := {z | y < z.re} have h₀ : Summable (fun n ↦ ‖term f x n‖) := summable_norm_iff.mpr hf have h₁ (n) : DifferentiableOn ℂ (term f · n) S := fun z _ ↦ (hasDerivAt_term f n _).differentiableAt.differentiableWithinAt have h₂ : IsOpen S := isOpen_lt continuous_const continuous_re have h₃ (n z) (hz : z ∈ S) : ‖term f z n‖ ≤ ‖term f x n‖ := norm_term_le_of_re_le_re f (by simpa using (hxy.trans hz).le) n have H := hasSum_deriv_of_summable_norm h₀ h₁ h₂ h₃ hys simp_rw [(hasDerivAt_term f _ _).deriv] at H refine ⟨summable_neg_iff.mp H.summable, ?_⟩ simpa [← H.tsum_eq, tsum_neg] using ((differentiableOn_tsum_of_summable_norm h₀ h₁ h₂ h₃).differentiableAt <| h₂.mem_nhds hys).hasDerivAt /-- If `re s` is greater than the abscissa of absolute convergence of `f`, then the L-series of `f` is differentiable with derivative the negative of the L-series of the point-wise product of `log` with `f`. -/ lemma LSeries_hasDerivAt {f : ℕ → ℂ} {s : ℂ} (h : abscissaOfAbsConv f < s.re) : HasDerivAt (LSeries f) (-LSeries (logMul f) s) s := (LSeriesSummable_logMul_and_hasDerivAt h).2 /-- If `re s` is greater than the abscissa of absolute convergence of `f`, then the derivative of this L-series at `s` is the negative of the L-series of `log * f`. -/ lemma LSeries_deriv {f : ℕ → ℂ} {s : ℂ} (h : abscissaOfAbsConv f < s.re) : deriv (LSeries f) s = -LSeries (logMul f) s := (LSeries_hasDerivAt h).deriv /-- The derivative of the L-series of `f` agrees with the negative of the L-series of `log * f` on the right half-plane of absolute convergence. -/ lemma LSeries_deriv_eqOn {f : ℕ → ℂ} : {s | abscissaOfAbsConv f < s.re}.EqOn (deriv (LSeries f)) (-LSeries (logMul f)) := deriv_eqOn (isOpen_re_gt_EReal _) fun _ hs ↦ (LSeries_hasDerivAt hs).hasDerivWithinAt /-- If the L-series of `f` is summable at `s` and `re s < re s'`, then the L-series of the point-wise product of `log` with `f` is summable at `s'`. -/ lemma LSeriesSummable_logMul_of_lt_re {f : ℕ → ℂ} {s : ℂ} (h : abscissaOfAbsConv f < s.re) : LSeriesSummable (logMul f) s := (LSeriesSummable_logMul_and_hasDerivAt h).1 /-- The abscissa of absolute convergence of the point-wise product of `log` and `f` is the same as that of `f`. -/ @[simp] lemma LSeries.abscissaOfAbsConv_logMul {f : ℕ → ℂ} : abscissaOfAbsConv (logMul f) = abscissaOfAbsConv f := by apply le_antisymm <;> refine abscissaOfAbsConv_le_of_forall_lt_LSeriesSummable' fun s hs ↦ ?_ · exact LSeriesSummable_logMul_of_lt_re <| by simp [hs] · refine (LSeriesSummable_of_abscissaOfAbsConv_lt_re <| by simp [hs]) |>.norm.of_norm_bounded_eventually_nat (g := fun n ↦ ‖term (logMul f) s n‖) ?_ filter_upwards [Filter.eventually_ge_atTop <| max 1 (Nat.ceil (Real.exp 1))] with n hn simp only [term_of_ne_zero (show n ≠ 0 by omega), logMul, norm_mul, mul_div_assoc, ← natCast_log, norm_real] refine le_mul_of_one_le_left (norm_nonneg _) (.trans ?_ <| Real.le_norm_self _) simpa using Real.log_le_log (Real.exp_pos 1) <| Nat.ceil_le.mp <| (le_max_right _ _).trans hn /-! ### Higher derivatives of L-series -/ /-- The abscissa of absolute convergence of the point-wise product of a power of `log` and `f` is the same as that of `f`. -/ @[simp] lemma LSeries.absicssaOfAbsConv_logPowMul {f : ℕ → ℂ} {m : ℕ} : abscissaOfAbsConv (logMul^[m] f) = abscissaOfAbsConv f := by induction m with | zero => simp | succ n ih => simp [ih, Function.iterate_succ', Function.comp_def, -Function.comp_apply, -Function.iterate_succ] /-- If `re s` is greater than the abscissa of absolute convergence of `f`, then the `m`th derivative of this L-series is `(-1)^m` times the L-series of `log^m * f`. -/ lemma LSeries_iteratedDeriv {f : ℕ → ℂ} (m : ℕ) {s : ℂ} (h : abscissaOfAbsConv f < s.re) : iteratedDeriv m (LSeries f) s = (-1) ^ m * LSeries (logMul^[m] f) s := by induction m generalizing s with | zero => simp | succ m ih => have ih' : {s | abscissaOfAbsConv f < re s}.EqOn (iteratedDeriv m (LSeries f)) ((-1) ^ m * LSeries (logMul^[m] f)) := fun _ hs ↦ ih hs have := derivWithin_congr ih' (ih h) simp_rw [derivWithin_of_isOpen (isOpen_re_gt_EReal _) h] at this rw [iteratedDeriv_succ, this] simp [Pi.mul_def, pow_succ, Function.iterate_succ', LSeries_deriv <| absicssaOfAbsConv_logPowMul.symm ▸ h, -Function.iterate_succ] /-! ### The L-series is holomorphic -/ /-- The L-series of `f` is complex differentiable in its open half-plane of absolute convergence. -/ lemma LSeries_differentiableOn (f : ℕ → ℂ) : DifferentiableOn ℂ (LSeries f) {s | abscissaOfAbsConv f < s.re} := fun _ hz ↦ (LSeries_hasDerivAt hz).differentiableAt.differentiableWithinAt /-- The L-series of `f` is holomorphic on its open half-plane of absolute convergence. -/ lemma LSeries_analyticOnNhd (f : ℕ → ℂ) : AnalyticOnNhd ℂ (LSeries f) {s | abscissaOfAbsConv f < s.re} := (LSeries_differentiableOn f).analyticOnNhd <| isOpen_re_gt_EReal _ lemma LSeries_analyticOn (f : ℕ → ℂ) : AnalyticOn ℂ (LSeries f) {s | abscissaOfAbsConv f < s.re} := (LSeries_analyticOnNhd f).analyticOn
CalcQuestionMark.lean
import Mathlib.Tactic.Widget.Calc /-! Note that while the suggestions look incorrectly indented here, this is an artifact of the rendering to a string for `guard_msgs` (leanprover/lean4#7191). When used from the widget that appears in VSCode, they insert correctly-indented code. -/ /-- info: Create calc tactic: • calc 1 = 1 := by sorry --- warning: declaration uses 'sorry' -/ #guard_msgs in example : 1 = 1 := by have := 0 calc? /-- info: Create calc tactic: • calc a ≤ a := by sorry --- warning: declaration uses 'sorry' -/ #guard_msgs in example (a : Nat) : a ≤ a := by calc? -- an indented `calc?` /-- info: Create calc tactic: • calc a ≤ a := by sorry --- warning: declaration uses 'sorry' -/ #guard_msgs in example (a : Nat) : a ≤ a := by all_goals calc? -- a deliberately long line /-- info: Create calc tactic: • calc 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 8 + 8 + 8 + 8 := by sorry --- warning: declaration uses 'sorry' -/ #guard_msgs in example : 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 8 + 8 + 8 + 8 := by calc?
Darboux.lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Analysis.Calculus.Deriv.Add import Mathlib.Analysis.Calculus.Deriv.Mul import Mathlib.Analysis.Calculus.LocalExtr.Basic /-! # Darboux's theorem In this file we prove that the derivative of a differentiable function on an interval takes all intermediate values. The proof is based on the [Wikipedia](https://en.wikipedia.org/wiki/Darboux%27s_theorem_(analysis)) page about this theorem. -/ open Filter Set open scoped Topology variable {a b : ℝ} {f f' : ℝ → ℝ} /-- **Darboux's theorem**: if `a ≤ b` and `f' a < m < f' b`, then `f' c = m` for some `c ∈ (a, b)`. -/ theorem exists_hasDerivWithinAt_eq_of_gt_of_lt (hab : a ≤ b) (hf : ∀ x ∈ Icc a b, HasDerivWithinAt f (f' x) (Icc a b) x) {m : ℝ} (hma : f' a < m) (hmb : m < f' b) : m ∈ f' '' Ioo a b := by rcases hab.eq_or_lt with (rfl | hab') · exact (lt_asymm hma hmb).elim set g : ℝ → ℝ := fun x => f x - m * x have hg : ∀ x ∈ Icc a b, HasDerivWithinAt g (f' x - m) (Icc a b) x := by intro x hx simpa using (hf x hx).sub ((hasDerivWithinAt_id x _).const_mul m) obtain ⟨c, cmem, hc⟩ : ∃ c ∈ Icc a b, IsMinOn g (Icc a b) c := isCompact_Icc.exists_isMinOn (nonempty_Icc.2 <| hab) fun x hx => (hg x hx).continuousWithinAt have cmem' : c ∈ Ioo a b := by rcases cmem.1.eq_or_lt with (rfl | hac) -- Show that `c` can't be equal to `a` · refine absurd (sub_nonneg.1 <| nonneg_of_mul_nonneg_right ?_ (sub_pos.2 hab')) (not_le_of_gt hma) have : b - a ∈ posTangentConeAt (Icc a b) a := sub_mem_posTangentConeAt_of_segment_subset (segment_eq_Icc hab ▸ Subset.rfl) simpa only [ContinuousLinearMap.smulRight_apply, ContinuousLinearMap.one_apply] using hc.localize.hasFDerivWithinAt_nonneg (hg a (left_mem_Icc.2 hab)) this rcases cmem.2.eq_or_lt' with (rfl | hcb) -- Show that `c` can't be equal to `b` · refine absurd (sub_nonpos.1 <| nonpos_of_mul_nonneg_right ?_ (sub_lt_zero.2 hab')) (not_le_of_gt hmb) have : a - b ∈ posTangentConeAt (Icc a b) b := sub_mem_posTangentConeAt_of_segment_subset (by rw [segment_symm, segment_eq_Icc hab]) simpa only [ContinuousLinearMap.smulRight_apply, ContinuousLinearMap.one_apply] using hc.localize.hasFDerivWithinAt_nonneg (hg b (right_mem_Icc.2 hab)) this exact ⟨hac, hcb⟩ use c, cmem' rw [← sub_eq_zero] have : Icc a b ∈ 𝓝 c := by rwa [← mem_interior_iff_mem_nhds, interior_Icc] exact (hc.isLocalMin this).hasDerivAt_eq_zero ((hg c cmem).hasDerivAt this) /-- **Darboux's theorem**: if `a ≤ b` and `f' b < m < f' a`, then `f' c = m` for some `c ∈ (a, b)`. -/ theorem exists_hasDerivWithinAt_eq_of_lt_of_gt (hab : a ≤ b) (hf : ∀ x ∈ Icc a b, HasDerivWithinAt f (f' x) (Icc a b) x) {m : ℝ} (hma : m < f' a) (hmb : f' b < m) : m ∈ f' '' Ioo a b := let ⟨c, cmem, hc⟩ := exists_hasDerivWithinAt_eq_of_gt_of_lt hab (fun x hx => (hf x hx).neg) (neg_lt_neg hma) (neg_lt_neg hmb) ⟨c, cmem, neg_injective hc⟩ /-- **Darboux's theorem**: the image of a `Set.OrdConnected` set under `f'` is a `Set.OrdConnected` set, `HasDerivWithinAt` version. -/ theorem Set.OrdConnected.image_hasDerivWithinAt {s : Set ℝ} (hs : OrdConnected s) (hf : ∀ x ∈ s, HasDerivWithinAt f (f' x) s x) : OrdConnected (f' '' s) := by apply ordConnected_of_Ioo rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ - m ⟨hma, hmb⟩ rcases le_total a b with hab | hab · have : Icc a b ⊆ s := hs.out ha hb rcases exists_hasDerivWithinAt_eq_of_gt_of_lt hab (fun x hx => (hf x <| this hx).mono this) hma hmb with ⟨c, cmem, hc⟩ exact ⟨c, this <| Ioo_subset_Icc_self cmem, hc⟩ · have : Icc b a ⊆ s := hs.out hb ha rcases exists_hasDerivWithinAt_eq_of_lt_of_gt hab (fun x hx => (hf x <| this hx).mono this) hmb hma with ⟨c, cmem, hc⟩ exact ⟨c, this <| Ioo_subset_Icc_self cmem, hc⟩ /-- **Darboux's theorem**: the image of a `Set.OrdConnected` set under `f'` is a `Set.OrdConnected` set, `derivWithin` version. -/ theorem Set.OrdConnected.image_derivWithin {s : Set ℝ} (hs : OrdConnected s) (hf : DifferentiableOn ℝ f s) : OrdConnected (derivWithin f s '' s) := hs.image_hasDerivWithinAt fun x hx => (hf x hx).hasDerivWithinAt /-- **Darboux's theorem**: the image of a `Set.OrdConnected` set under `f'` is a `Set.OrdConnected` set, `deriv` version. -/ theorem Set.OrdConnected.image_deriv {s : Set ℝ} (hs : OrdConnected s) (hf : ∀ x ∈ s, DifferentiableAt ℝ f x) : OrdConnected (deriv f '' s) := hs.image_hasDerivWithinAt fun x hx => (hf x hx).hasDerivAt.hasDerivWithinAt /-- **Darboux's theorem**: the image of a convex set under `f'` is a convex set, `HasDerivWithinAt` version. -/ theorem Convex.image_hasDerivWithinAt {s : Set ℝ} (hs : Convex ℝ s) (hf : ∀ x ∈ s, HasDerivWithinAt f (f' x) s x) : Convex ℝ (f' '' s) := (hs.ordConnected.image_hasDerivWithinAt hf).convex /-- **Darboux's theorem**: the image of a convex set under `f'` is a convex set, `derivWithin` version. -/ theorem Convex.image_derivWithin {s : Set ℝ} (hs : Convex ℝ s) (hf : DifferentiableOn ℝ f s) : Convex ℝ (derivWithin f s '' s) := (hs.ordConnected.image_derivWithin hf).convex /-- **Darboux's theorem**: the image of a convex set under `f'` is a convex set, `deriv` version. -/ theorem Convex.image_deriv {s : Set ℝ} (hs : Convex ℝ s) (hf : ∀ x ∈ s, DifferentiableAt ℝ f x) : Convex ℝ (deriv f '' s) := (hs.ordConnected.image_deriv hf).convex /-- **Darboux's theorem**: if `a ≤ b` and `f' a ≤ m ≤ f' b`, then `f' c = m` for some `c ∈ [a, b]`. -/ theorem exists_hasDerivWithinAt_eq_of_ge_of_le (hab : a ≤ b) (hf : ∀ x ∈ Icc a b, HasDerivWithinAt f (f' x) (Icc a b) x) {m : ℝ} (hma : f' a ≤ m) (hmb : m ≤ f' b) : m ∈ f' '' Icc a b := (ordConnected_Icc.image_hasDerivWithinAt hf).out (mem_image_of_mem _ (left_mem_Icc.2 hab)) (mem_image_of_mem _ (right_mem_Icc.2 hab)) ⟨hma, hmb⟩ /-- **Darboux's theorem**: if `a ≤ b` and `f' b ≤ m ≤ f' a`, then `f' c = m` for some `c ∈ [a, b]`. -/ theorem exists_hasDerivWithinAt_eq_of_le_of_ge (hab : a ≤ b) (hf : ∀ x ∈ Icc a b, HasDerivWithinAt f (f' x) (Icc a b) x) {m : ℝ} (hma : f' a ≤ m) (hmb : m ≤ f' b) : m ∈ f' '' Icc a b := (ordConnected_Icc.image_hasDerivWithinAt hf).out (mem_image_of_mem _ (left_mem_Icc.2 hab)) (mem_image_of_mem _ (right_mem_Icc.2 hab)) ⟨hma, hmb⟩ /-- If the derivative of a function is never equal to `m`, then either it is always greater than `m`, or it is always less than `m`. -/ theorem hasDerivWithinAt_forall_lt_or_forall_gt_of_forall_ne {s : Set ℝ} (hs : Convex ℝ s) (hf : ∀ x ∈ s, HasDerivWithinAt f (f' x) s x) {m : ℝ} (hf' : ∀ x ∈ s, f' x ≠ m) : (∀ x ∈ s, f' x < m) ∨ ∀ x ∈ s, m < f' x := by contrapose! hf' rcases hf' with ⟨⟨b, hb, hmb⟩, ⟨a, ha, hma⟩⟩ exact (hs.ordConnected.image_hasDerivWithinAt hf).out (mem_image_of_mem f' ha) (mem_image_of_mem f' hb) ⟨hma, hmb⟩