filename
stringlengths
5
30
content
stringlengths
22
296k
FrobeniusNumber.lean
/- Copyright (c) 2021 Alex Zhao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Zhao -/ import Mathlib.Algebra.Group.Submonoid.Membership import Mathlib.Data.Nat.ModEq import Mathlib.Tactic.Ring import Mathlib.Tactic.Zify /-! # Frobenius Number in Two Variables In this file we first define a predicate for Frobenius numbers, then solve the 2-variable variant of this problem. ## Theorem Statement Given a finite set of relatively prime integers all greater than 1, their Frobenius number is the largest positive integer that cannot be expressed as a sum of nonnegative multiples of these integers. Here we show the Frobenius number of two relatively prime integers `m` and `n` greater than 1 is `m * n - m - n`. This result is also known as the Chicken McNugget Theorem. ## Implementation Notes First we define Frobenius numbers in general using `IsGreatest` and `AddSubmonoid.closure`. Then we proceed to compute the Frobenius number of `m` and `n`. For the upper bound, we begin with an auxiliary lemma showing `m * n` is not attainable, then show `m * n - m - n` is not attainable. Then for the construction, we create a `k_1` which is `k mod n` and `0 mod m`, then show it is at most `k`. Then `k_1` is a multiple of `m`, so `(k-k_1)` is a multiple of n, and we're done. ## Tags frobenius number, chicken mcnugget, chinese remainder theorem, add_submonoid.closure -/ open Nat /-- A natural number `n` is the **Frobenius number** of a set of natural numbers `s` if it is an upper bound on the complement of the additive submonoid generated by `s`. In other words, it is the largest number that can not be expressed as a sum of numbers in `s`. -/ def FrobeniusNumber (n : ℕ) (s : Set ℕ) : Prop := IsGreatest { k | k ∉ AddSubmonoid.closure s } n variable {m n : ℕ} /-- The **Chicken McNugget theorem** stating that the Frobenius number of positive numbers `m` and `n` is `m * n - m - n`. -/ theorem frobeniusNumber_pair (cop : Coprime m n) (hm : 1 < m) (hn : 1 < n) : FrobeniusNumber (m * n - m - n) {m, n} := by simp_rw [FrobeniusNumber, AddSubmonoid.mem_closure_pair] have hmn : m + n ≤ m * n := add_le_mul hm hn constructor · push_neg intro a b h apply cop.mul_add_mul_ne_mul (add_one_ne_zero a) (add_one_ne_zero b) simp only [Nat.sub_sub, smul_eq_mul] at h zify [hmn] at h ⊢ rw [← sub_eq_zero] at h ⊢ rw [← h] ring · intro k hk dsimp at hk contrapose! hk let x := chineseRemainder cop 0 k have hx : x.val < m * n := chineseRemainder_lt_mul cop 0 k (ne_bot_of_gt hm) (ne_bot_of_gt hn) suffices key : x.1 ≤ k by obtain ⟨a, ha⟩ := modEq_zero_iff_dvd.mp x.2.1 obtain ⟨b, hb⟩ := (modEq_iff_dvd' key).mp x.2.2 exact ⟨a, b, by rw [mul_comm, ← ha, mul_comm, ← hb, Nat.add_sub_of_le key]⟩ refine ModEq.le_of_lt_add x.2.2 (lt_of_le_of_lt ?_ (add_lt_add_right hk n)) rw [Nat.sub_add_cancel (le_tsub_of_add_le_left hmn)] exact ModEq.le_of_lt_add (x.2.1.trans (modEq_zero_iff_dvd.mpr (Nat.dvd_sub (dvd_mul_right m n) dvd_rfl)).symm) (lt_of_lt_of_le hx le_tsub_add)
mxalgebra.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 bigop finset fingroup perm order. From mathcomp Require Import div prime binomial ssralg finalg zmodp matrix. (*****************************************************************************) (* In this file we develop the rank and row space theory of matrices, based *) (* on an extended Gaussian elimination procedure similar to LUP *) (* decomposition. This provides us with a concrete but generic model of *) (* finite dimensional vector spaces and F-algebras, in which vectors, linear *) (* functions, families, bases, subspaces, ideals and subrings are all *) (* represented using matrices. This model can be used as a foundation for *) (* the usual theory of abstract linear algebra, but it can also be used to *) (* develop directly substantial theories, such as the theory of finite group *) (* linear representation. *) (* Here we define the following concepts and notations: *) (* Gaussian_elimination A == a permuted triangular decomposition (L, U, r) *) (* of A, with L a column permutation of a lower triangular *) (* invertible matrix, U a row permutation of an upper *) (* triangular invertible matrix, and r the rank of A, all *) (* satisfying the identity L *m pid_mx r *m U = A. *) (* \rank A == the rank of A. *) (* row_free A <=> the rows of A are linearly free (i.e., the rank and *) (* height of A are equal). *) (* row_full A <=> the row-space of A spans all row-vectors (i.e., the *) (* rank and width of A are equal). *) (* col_ebase A == the extended column basis of A (the first matrix L *) (* returned by Gaussian_elimination A). *) (* row_ebase A == the extended row base of A (the second matrix U *) (* returned by Gaussian_elimination A). *) (* col_base A == a basis for the columns of A: a row-full matrix *) (* consisting of the first \rank A columns of col_ebase A. *) (* row_base A == a basis for the rows of A: a row-free matrix consisting *) (* of the first \rank A rows of row_ebase A. *) (* pinvmx A == a partial inverse for A in its row space (or on its *) (* column space, equivalently). In particular, if u is a *) (* row vector in the row_space of A, then u *m pinvmx A is *) (* the row vector of the coefficients of a decomposition *) (* of u as a sub of rows of A. *) (* kermx A == the row kernel of A : a square matrix whose row space *) (* consists of all u such that u *m A = 0 (it consists of *) (* the inverse of col_ebase A, with the top \rank A rows *) (* zeroed out). Also, kermx A is a partial right inverse *) (* to col_ebase A, in the row space annihilated by A. *) (* cokermx A == the cokernel of A : a square matrix whose column space *) (* consists of all v such that A *m v = 0 (it consists of *) (* the inverse of row_ebase A, with the leftmost \rank A *) (* columns zeroed out). *) (* maxrankfun A == injective function f so that rowsub f A is a submatrix *) (* of A with the same rank as A. *) (* fullrankfun fA == injective function f so that rowsub f A is row full, *) (* where fA is a proof of row_full A *) (* eigenvalue g a <=> a is an eigenvalue of the square matrix g. *) (* eigenspace g a == a square matrix whose row space is the eigenspace of *) (* the eigenvalue a of g (or 0 if a is not an eigenvalue). *) (* We use a different scope %MS for matrix row-space set-like operations; to *) (* avoid confusion, this scope should not be opened globally. Note that the *) (* the arguments of \rank _ and the operations below have default scope %MS. *) (* (A <= B)%MS <=> the row-space of A is included in the row-space of B. *) (* We test for this by testing if cokermx B annihilates A. *) (* (A < B)%MS <=> the row-space of A is properly included in the *) (* row-space of B. *) (* (A <= B <= C)%MS == (A <= B)%MS && (B <= C)%MS, and similarly for *) (* (A < B <= C)%MS, (A < B <= C)%MS and (A < B < C)%MS. *) (* (A == B)%MS == (A <= B <= A)%MS (A and B have the same row-space). *) (* (A :=: B)%MS == A and B behave identically wrt. \rank and <=. This *) (* triple rewrite rule is the Prop version of (A == B)%MS. *) (* Note that :=: cannot be treated as a setoid-style *) (* Equivalence because its arguments can have different *) (* types: A and B need not have the same number of rows, *) (* and often don't (e.g., in row_base A :=: A). *) (* <<A>>%MS == a square matrix with the same row-space as A; <<A>>%MS *) (* is a canonical representation of the subspace generated *) (* by A, viewed as a list of row-vectors: if (A == B)%MS, *) (* then <<A>>%MS = <<B>>%MS. *) (* (A + B)%MS == a square matrix whose row-space is the sum of the *) (* row-spaces of A and B; thus (A + B == col_mx A B)%MS. *) (* (\sum_i <expr i>)%MS == the "big" version of (_ + _)%MS; as the latter *) (* has a canonical abelian monoid structure, most generic *) (* bigop lemmas apply (the other bigop indexing notations *) (* are also defined). *) (* (A :&: B)%MS == a square matrix whose row-space is the intersection of *) (* the row-spaces of A and B. *) (* (\bigcap_i <expr i>)%MS == the "big" version of (_ :&: _)%MS, which also *) (* has a canonical abelian monoid structure. *) (* A^C%MS == a square matrix whose row-space is a complement to the *) (* the row-space of A (it consists of row_ebase A with the *) (* top \rank A rows zeroed out). *) (* (A :\: B)%MS == a square matrix whose row-space is a complement of the *) (* the row-space of (A :&: B)%MS in the row-space of A. *) (* We have (A :\: B := A :&: (capmx_gen A B)^C)%MS, where *) (* capmx_gen A B is a rectangular matrix equivalent to *) (* (A :&: B)%MS, i.e., (capmx_gen A B == A :&: B)%MS. *) (* proj_mx A B == a square matrix that projects (A + B)%MS onto A *) (* parallel to B, when (A :&: B)%MS = 0 (A and B must also *) (* be square). *) (* mxdirect S == the sum expression S is a direct sum. This is a NON *) (* EXTENSIONAL notation: the exact boolean expression is *) (* inferred from the syntactic form of S (expanding *) (* definitions, however); both (\sum_(i | _) _)%MS and *) (* (_ + _)%MS sums are recognized. This construct uses a *) (* variant of the reflexive ("quote") canonical structure, *) (* mxsum_expr. The structure also recognizes sums of *) (* matrix ranks, so that lemmas concerning the rank of *) (* direct sums can be used bidirectionally. *) (* stablemx V f <=> the matrix f represents an endomorphism that preserves V *) (* := (V *m f <= V)%MS *) (* The next set of definitions let us represent F-algebras using matrices: *) (* 'A[F]_(m, n) == the type of matrices encoding (sub)algebras of square *) (* n x n matrices, via mxvec; as in the matrix type *) (* notation, m and F can be omitted (m defaults to n ^ 2). *) (* := 'M[F]_(m, n ^ 2). *) (* (A \in R)%MS <=> the square matrix A belongs to the linear set of *) (* matrices (most often, a sub-algebra) encoded by the *) (* row space of R. This is simply notation, so all the *) (* lemmas and rewrite rules for (_ <= _)%MS can apply. *) (* := (mxvec A <= R)%MS. *) (* (R * S)%MS == a square n^2 x n^2 matrix whose row-space encodes the *) (* linear set of n x n matrices generated by the pointwise *) (* product of the sets of matrices encoded by R and S. *) (* 'C(R)%MS == a square matrix encoding the centraliser of the set of *) (* square matrices encoded by R. *) (* 'C_S(R)%MS := (S :&: 'C(R))%MS (the centraliser of R in S). *) (* 'Z(R)%MS == the center of R (i.e., 'C_R(R)%MS). *) (* left_mx_ideal R S <=> S is a left ideal for R (R * S <= S)%MS. *) (* right_mx_ideal R S <=> S is a right ideal for R (S * R <= S)%MS. *) (* mx_ideal R S <=> S is a bilateral ideal for R. *) (* mxring_id R e <-> e is an identity element for R (Prop predicate). *) (* has_mxring_id R <=> R has a nonzero identity element (bool predicate). *) (* mxring R <=> R encodes a nontrivial subring. *) (*****************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope matrix_set_scope. Import GroupScope. Import GRing.Theory. Local Open Scope ring_scope. Reserved Notation "\rank A" (at level 10, A at level 8, format "\rank A"). Reserved Notation "A ^C" (format "A ^C"). Notation "''A_' ( m , n )" := 'M_(m, n ^ 2) (format "''A_' ( m , n )") : type_scope. Notation "''A_' ( n )" := 'A_(n ^ 2, n) (only parsing) : type_scope. Notation "''A_' n" := 'A_(n) (n at next level, format "''A_' n") : type_scope. Notation "''A' [ F ]_ ( m , n )" := 'M[F]_(m, n ^ 2) (only parsing) : type_scope. Notation "''A' [ F ]_ ( n )" := 'A[F]_(n ^ 2, n) (only parsing) : type_scope. Notation "''A' [ F ]_ n" := 'A[F]_(n) (n at level 2, only parsing) : type_scope. Delimit Scope matrix_set_scope with MS. Local Notation simp := (Monoid.Theory.simpm, oppr0). (*****************************************************************************) (******************** Rank and row-space theory ******************************) (*****************************************************************************) (* Decomposition with double pivoting; computes the rank, row and column *) (* images, kernels, and complements of a matrix. *) Fixpoint Gaussian_elimination_ {F : fieldType} {m n} : 'M[F]_(m, n) -> 'M_m * 'M_n * nat := match m, n with | _.+1, _.+1 => fun A : 'M_(1 + _, 1 + _) => if [pick ij | A ij.1 ij.2 != 0] is Some (i, j) then let a := A i j in let A1 := xrow i 0 (xcol j 0 A) in let u := ursubmx A1 in let v := a^-1 *: dlsubmx A1 in let: (L, U, r) := Gaussian_elimination_ (drsubmx A1 - v *m u) in (xrow i 0 (block_mx 1 0 v L), xcol j 0 (block_mx a%:M u 0 U), r.+1) else (1%:M, 1%:M, 0) | _, _ => fun _ => (1%:M, 1%:M, 0) end. HB.lock Definition Gaussian_elimination := @Gaussian_elimination_. Canonical Gaussian_elimination_unlockable := Unlockable Gaussian_elimination.unlock. HB.lock Definition mxrank (F : fieldType) m n (A : 'M_(m, n)) := if [|| m == 0 | n == 0]%N then 0 else (@Gaussian_elimination F m n A).2. Canonical mxrank_unlockable := Unlockable mxrank.unlock. Section RowSpaceTheoryDefs. Variable F : fieldType. Implicit Types m n p r : nat. Local Notation "''M_' ( m , n )" := 'M[F]_(m, n) : type_scope. Local Notation "''M_' n" := 'M[F]_(n, n) : type_scope. Variables (m n : nat) (A : 'M_(m, n)). Local Notation mxrank := (@mxrank F m n A). Let LUr := @Gaussian_elimination F m n A. Definition col_ebase := LUr.1.1. Definition row_ebase := LUr.1.2. Definition row_free := mxrank == m. Definition row_full := mxrank == n. Definition row_base : 'M_(mxrank, n) := pid_mx mxrank *m row_ebase. Definition col_base : 'M_(m, mxrank) := col_ebase *m pid_mx mxrank. Definition complmx : 'M_n := copid_mx mxrank *m row_ebase. Definition kermx : 'M_m := copid_mx mxrank *m invmx col_ebase. Definition cokermx : 'M_n := invmx row_ebase *m copid_mx mxrank. Definition pinvmx : 'M_(n, m) := invmx row_ebase *m pid_mx mxrank *m invmx col_ebase. End RowSpaceTheoryDefs. Implicit Types F : fieldType. HB.lock Definition submx F m1 m2 n (A : 'M[F]_(m1, n)) (B : 'M_(m2, n)) := A *m cokermx B == 0. Canonical submx_unlockable := Unlockable submx.unlock. Arguments mxrank {F} {m%_N n%_N} A%_MS. Arguments complmx {F} {m%_N n%_N} A%_MS. Arguments submx {F} {m1%_N m2%_N n%_N} A%_MS B%_MS : rename. Local Notation "\rank A" := (mxrank A) : nat_scope. Local Notation "A ^C" := (complmx A) : matrix_set_scope. Local Notation "A <= B" := (submx A B) : matrix_set_scope. Local Notation "A <= B <= C" := ((A <= B) && (B <= C))%MS : matrix_set_scope. Local Notation "A == B" := (A <= B <= A)%MS : matrix_set_scope. Definition ltmx F m1 m2 n (A : 'M[F]_(m1, n)) (B : 'M_(m2, n)) := (A <= B)%MS && ~~ (B <= A)%MS. Arguments ltmx {F} {m1%_N m2%_N n%_N} A%_MS B%_MS. Local Notation "A < B" := (ltmx A B) : matrix_set_scope. Definition eqmx F m1 m2 n (A : 'M[F]_(m1, n)) (B : 'M_(m2, n)) := prod (\rank A = \rank B) (forall m3 (C : 'M_(m3, n)), ((A <= C) = (B <= C)) * ((C <= A) = (C <= B)))%MS. Arguments eqmx {F} {m1%_N m2%_N n%_N} A%_MS B%_MS. Local Notation "A :=: B" := (eqmx A%MS B%MS) : matrix_set_scope. Notation stablemx V f := (V%MS *m f%R <= V%MS)%MS. Section LtmxIdentities. Variable F : fieldType. Implicit Types m n p r : nat. Local Notation "''M_' ( m , n )" := 'M[F]_(m, n) : type_scope. Local Notation "''M_' n" := 'M[F]_(n, n) : type_scope. Variables (m1 m2 n : nat) (A : 'M_(m1, n)) (B : 'M_(m2, n)). Lemma ltmxE : (A < B)%MS = ((A <= B)%MS && ~~ (B <= A)%MS). Proof. by []. Qed. Lemma ltmxW : (A < B)%MS -> (A <= B)%MS. Proof. by case/andP. Qed. Lemma ltmxEneq : (A < B)%MS = (A <= B)%MS && ~~ (A == B)%MS. Proof. by apply: andb_id2l => ->. Qed. Lemma submxElt : (A <= B)%MS = (A == B)%MS || (A < B)%MS. Proof. by rewrite -andb_orr orbN andbT. Qed. End LtmxIdentities. (* The definition of the row-space operator is rigged to return the identity *) (* matrix for full matrices. To allow for further tweaks that will make the *) (* row-space intersection operator strictly commutative and monoidal, we *) (* slightly generalize some auxiliary definitions: we parametrize the *) (* "equivalent subspace and identity" choice predicate equivmx by a boolean *) (* determining whether the matrix should be the identity (so for genmx A its *) (* value is row_full A), and introduce a "quasi-identity" predicate qidmx *) (* that selects non-square full matrices along with the identity matrix 1%:M *) (* (this does not affect genmx, which chooses a square matrix). *) (* The choice witness for genmx A is either 1%:M for a row-full A, or else *) (* row_base A padded with null rows. *) Local Definition qidmx F m n (A : 'M[F]_(m, n)) := if m == n then A == pid_mx n else row_full A. Local Definition equivmx F m n (A : 'M[F]_(m, n)) idA (B : 'M_n) := (B == A)%MS && (qidmx B == idA). Local Definition equivmx_spec F m n (A : 'M[F]_(m, n)) idA (B : 'M_n) := prod (B :=: A)%MS (qidmx B = idA). Local Definition genmx_witness F m n (A : 'M[F]_(m, n)) : 'M_n := if row_full A then 1%:M else pid_mx (\rank A) *m row_ebase A. HB.lock Definition genmx F m n (A : 'M[F]_(m, n)) : 'M_n := choose (equivmx A (row_full A)) (genmx_witness A). Canonical genmx_unlockable := Unlockable genmx.unlock. Arguments genmx {F} {n m}%_N A%_MS : rename. Local Notation "<< A >>" := (genmx A%MS) : matrix_set_scope. (* The setwise sum is tweaked so that 0 is a strict identity element for *) (* square matrices, because this lets us use the bigop component. As a result *) (* setwise sum is not quite strictly extensional. *) Local Definition addsmx_nop F m n (A : 'M[F]_(m, n)) := conform_mx <<A>>%MS A. HB.lock Definition addsmx F m1 m2 n (A : 'M[F]_(m1, n)) (B : 'M_(m2, n)) : 'M_n := if A == 0 then addsmx_nop B else if B == 0 then addsmx_nop A else <<col_mx A B>>%MS. Canonical addsmx_unlockable := Unlockable addsmx.unlock. Arguments addsmx {F} {m1%_N m2%_N n%_N} A%_MS B%_MS : rename. Local Notation "A + B" := (addsmx A B) : matrix_set_scope. Local Notation "\sum_ ( i | P ) B" := (\big[addsmx/0]_(i | P) B%MS) : matrix_set_scope. Local Notation "\sum_ ( i <- r | P ) B" := (\big[addsmx/0]_(i <- r | P) B%MS) : matrix_set_scope. (* The set intersection is similarly biased so that the identity matrix is a *) (* strict identity. This is somewhat more delicate than for the sum, because *) (* the test for the identity is non-extensional. This forces us to actually *) (* bias the choice operator so that it does not accidentally map an *) (* intersection of non-identity matrices to 1%:M; this would spoil *) (* associativity: if B :&: C = 1%:M but B and C are not identity, then for a *) (* square matrix A we have A :&: (B :&: C) = A != (A :&: B) :&: C in general. *) (* To complicate matters there may not be a square non-singular matrix *) (* different than 1%:M, since we could be dealing with 'M['F_2]_1. We *) (* sidestep the issue by making all non-square row-full matrices identities, *) (* and choosing a normal representative that preserves the qidmx property. *) (* Thus A :&: B = 1%:M iff A and B are both identities, and this suffices for *) (* showing that associativity is strict. *) Local Definition capmx_witness F m n (A : 'M[F]_(m, n)) := if row_full A then conform_mx 1%:M A else <<A>>%MS. Local Definition capmx_norm F m n (A : 'M[F]_(m, n)) := choose (equivmx A (qidmx A)) (capmx_witness A). Local Definition capmx_nop F m n (A : 'M[F]_(m, n)) := conform_mx (capmx_norm A) A. Definition capmx_gen F m1 m2 n (A : 'M[F]_(m1, n)) (B : 'M_(m2, n)) := lsubmx (kermx (col_mx A B)) *m A. HB.lock Definition capmx F m1 m2 n (A : 'M[F]_(m1, n)) (B : 'M_(m2, n)) : 'M_n := if qidmx A then capmx_nop B else if qidmx B then capmx_nop A else if row_full B then capmx_norm A else capmx_norm (capmx_gen A B). Canonical capmx_unlockable := Unlockable capmx.unlock. Arguments capmx {F} {m1%_N m2%_N n%_N} A%_MS B%_MS : rename. Local Notation "A :&: B" := (capmx A B) : matrix_set_scope. Local Notation "\bigcap_ ( i | P ) B" := (\big[capmx/1%:M]_(i | P) B) : matrix_set_scope. HB.lock Definition diffmx F m1 m2 n (A : 'M[F]_(m1, n)) (B : 'M_(m2, n)) : 'M_n := <<capmx_gen A (capmx_gen A B)^C>>%MS. Canonical diffmx_unlockable := Unlockable diffmx.unlock. Arguments diffmx {F} {m1%_N m2%_N n%_N} A%_MS B%_MS : rename. Local Notation "A :\: B" := (diffmx A B) : matrix_set_scope. Section RowSpaceTheory. Variable F : fieldType. Implicit Types m n p r : nat. Local Notation "''M_' ( m , n )" := 'M[F]_(m, n) : type_scope. Local Notation "''M_' n" := 'M[F]_(n, n) : type_scope. Definition proj_mx n (U V : 'M_n) : 'M_n := pinvmx (col_mx U V) *m col_mx U 0. Local Notation GaussE := Gaussian_elimination_. Fact mxrankE m n (A : 'M_(m, n)) : \rank A = (GaussE A).2. Proof. by rewrite mxrank.unlock unlock /=; case: m n A => [|m] [|n]. Qed. Lemma rank_leq_row m n (A : 'M_(m, n)) : \rank A <= m. Proof. rewrite mxrankE. elim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=. by move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=. Qed. Lemma row_leq_rank m n (A : 'M_(m, n)) : (m <= \rank A) = row_free A. Proof. by rewrite /row_free eqn_leq rank_leq_row. Qed. Lemma rank_leq_col m n (A : 'M_(m, n)) : \rank A <= n. Proof. rewrite mxrankE. elim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=. by move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=. Qed. Lemma col_leq_rank m n (A : 'M_(m, n)) : (n <= \rank A) = row_full A. Proof. by rewrite /row_full eqn_leq rank_leq_col. Qed. Lemma eq_row_full m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :=: B)%MS -> row_full A = row_full B. Proof. by rewrite /row_full => ->. Qed. Let unitmx1F := @unitmx1 F. Lemma row_ebase_unit m n (A : 'M_(m, n)) : row_ebase A \in unitmx. Proof. rewrite /row_ebase unlock; elim: m n A => [|m IHm] [|n] //= A. case: pickP => [[i j] /= nzAij | //=]; move: (_ - _) => B. case: GaussE (IHm _ B) => [[L U] r] /= uU. rewrite unitmxE xcolE det_mulmx (@det_ublock _ 1) det_scalar1 !unitrM. by rewrite unitfE nzAij -!unitmxE uU unitmx_perm. Qed. Lemma col_ebase_unit m n (A : 'M_(m, n)) : col_ebase A \in unitmx. Proof. rewrite /col_ebase unlock; elim: m n A => [|m IHm] [|n] //= A. case: pickP => [[i j] _|] //=; move: (_ - _) => B. case: GaussE (IHm _ B) => [[L U] r] /= uL. rewrite unitmxE xrowE det_mulmx (@det_lblock _ 1) det1 mul1r unitrM. by rewrite -unitmxE unitmx_perm. Qed. Hint Resolve rank_leq_row rank_leq_col row_ebase_unit col_ebase_unit : core. Lemma mulmx_ebase m n (A : 'M_(m, n)) : col_ebase A *m pid_mx (\rank A) *m row_ebase A = A. Proof. rewrite mxrankE /col_ebase /row_ebase unlock. elim: m n A => [n A | m IHm]; first by rewrite [A]flatmx0 [_ *m _]flatmx0. case=> [A | n]; first by rewrite [_ *m _]thinmx0 [A]thinmx0. rewrite -(add1n m) -?(add1n n) => A /=. case: pickP => [[i0 j0] | A0] /=; last first. apply/matrixP=> i j; rewrite pid_mx_0 mulmx0 mul0mx mxE. by move/eqP: (A0 (i, j)). set a := A i0 j0 => nz_a; set A1 := xrow _ _ _. set u := ursubmx _; set v := _ *: _; set B : 'M_(m, n) := _ - _. move: (rank_leq_col B) (rank_leq_row B) {IHm}(IHm n B); rewrite mxrankE. case: (GaussE B) => [[L U] r] /= r_m r_n defB. have ->: pid_mx (1 + r) = block_mx 1 0 0 (pid_mx r) :> 'M[F]_(1 + m, 1 + n). rewrite -(subnKC r_m) -(subnKC r_n) pid_mx_block -col_mx0 -row_mx0. by rewrite block_mxA castmx_id col_mx0 row_mx0 -scalar_mx_block -pid_mx_block. rewrite xcolE xrowE mulmxA -xcolE -!mulmxA. rewrite !(addr0, add0r, mulmx0, mul0mx, mulmx_block, mul1mx) mulmxA defB. rewrite addrC subrK mul_mx_scalar scalerA divff // scale1r. have ->: a%:M = ulsubmx A1 by rewrite [_ A1]mx11_scalar !mxE !lshift0 !tpermR. rewrite submxK /A1 xrowE !xcolE -!mulmxA mulmxA -!perm_mxM !tperm2 !perm_mx1. by rewrite mulmx1 mul1mx. Qed. Lemma mulmx_base m n (A : 'M_(m, n)) : col_base A *m row_base A = A. Proof. by rewrite mulmxA -[col_base A *m _]mulmxA pid_mx_id ?mulmx_ebase. Qed. Lemma mulmx1_min_rank r m n (A : 'M_(m, n)) M N : M *m A *m N = 1%:M :> 'M_r -> r <= \rank A. Proof. by rewrite -{1}(mulmx_base A) mulmxA -mulmxA; move/mulmx1_min. Qed. Arguments mulmx1_min_rank [r m n A]. Lemma mulmx_max_rank r m n (M : 'M_(m, r)) (N : 'M_(r, n)) : \rank (M *m N) <= r. Proof. set MN := M *m N; set rMN := \rank _. pose L : 'M_(rMN, m) := pid_mx rMN *m invmx (col_ebase MN). pose U : 'M_(n, rMN) := invmx (row_ebase MN) *m pid_mx rMN. suffices: L *m M *m (N *m U) = 1%:M by apply: mulmx1_min. rewrite mulmxA -(mulmxA L) -[M *m N]mulmx_ebase -/MN. by rewrite !mulmxA mulmxKV // mulmxK // !pid_mx_id /rMN ?pid_mx_1. Qed. Arguments mulmx_max_rank [r m n]. Lemma mxrank_tr m n (A : 'M_(m, n)) : \rank A^T = \rank A. Proof. apply/eqP; rewrite eqn_leq -{3}[A]trmxK -{1}(mulmx_base A) -{1}(mulmx_base A^T). by rewrite !trmx_mul !mulmx_max_rank. Qed. Lemma mxrank_add m n (A B : 'M_(m, n)) : \rank (A + B)%R <= \rank A + \rank B. Proof. by rewrite -{1}(mulmx_base A) -{1}(mulmx_base B) -mul_row_col mulmx_max_rank. Qed. Lemma mxrankM_maxl m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : \rank (A *m B) <= \rank A. Proof. by rewrite -{1}(mulmx_base A) -mulmxA mulmx_max_rank. Qed. Lemma mxrankM_maxr m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : \rank (A *m B) <= \rank B. Proof. by rewrite -mxrank_tr -(mxrank_tr B) trmx_mul mxrankM_maxl. Qed. Lemma mxrank_scale m n a (A : 'M_(m, n)) : \rank (a *: A) <= \rank A. Proof. by rewrite -mul_scalar_mx mxrankM_maxr. Qed. Lemma mxrank_scale_nz m n a (A : 'M_(m, n)) : a != 0 -> \rank (a *: A) = \rank A. Proof. move=> nza; apply/eqP; rewrite eqn_leq -{3}[A]scale1r -(mulVf nza). by rewrite -scalerA !mxrank_scale. Qed. Lemma mxrank_opp m n (A : 'M_(m, n)) : \rank (- A) = \rank A. Proof. by rewrite -scaleN1r mxrank_scale_nz // oppr_eq0 oner_eq0. Qed. Lemma mxrank0 m n : \rank (0 : 'M_(m, n)) = 0%N. Proof. by apply/eqP; rewrite -leqn0 -(@mulmx0 _ m 0 n 0) mulmx_max_rank. Qed. Lemma mxrank_eq0 m n (A : 'M_(m, n)) : (\rank A == 0) = (A == 0). Proof. apply/eqP/eqP=> [rA0 | ->{A}]; last exact: mxrank0. move: (col_base A) (row_base A) (mulmx_base A); rewrite rA0 => Ac Ar <-. by rewrite [Ac]thinmx0 mul0mx. Qed. Lemma mulmx_coker m n (A : 'M_(m, n)) : A *m cokermx A = 0. Proof. by rewrite -{1}[A]mulmx_ebase -!mulmxA mulKVmx // mul_pid_mx_copid ?mulmx0. Qed. Lemma submxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A <= B)%MS = (A *m cokermx B == 0). Proof. by rewrite unlock. Qed. Lemma mulmxKpV m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A <= B)%MS -> A *m pinvmx B *m B = A. Proof. rewrite submxE !mulmxA mulmxBr mulmx1 subr_eq0 => /eqP defA. rewrite -{4}[B]mulmx_ebase -!mulmxA mulKmx //. by rewrite (mulmxA (pid_mx _)) pid_mx_id // !mulmxA -{}defA mulmxKV. Qed. Lemma mulmxVp m n (A : 'M[F]_(m, n)) : row_free A -> A *m pinvmx A = 1%:M. Proof. move=> fA; rewrite -[X in X *m _]mulmx_ebase !mulmxA mulmxK ?row_ebase_unit//. rewrite -[X in X *m _]mulmxA mul_pid_mx !minnn (minn_idPr _) ?rank_leq_col//. by rewrite (eqP fA) pid_mx_1 mulmx1 mulmxV ?col_ebase_unit. Qed. Lemma mulmxKp p m n (B : 'M[F]_(m, n)) : row_free B -> cancel ((@mulmx _ p _ _)^~ B) (mulmx^~ (pinvmx B)). Proof. by move=> ? A; rewrite -mulmxA mulmxVp ?mulmx1. Qed. Lemma submxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (exists D, A = D *m B) (A <= B)%MS. Proof. apply: (iffP idP) => [/mulmxKpV | [D ->]]; first by exists (A *m pinvmx B). by rewrite submxE -mulmxA mulmx_coker mulmx0. Qed. Arguments submxP {m1 m2 n A B}. Lemma submx_refl m n (A : 'M_(m, n)) : (A <= A)%MS. Proof. by rewrite submxE mulmx_coker. Qed. Hint Resolve submx_refl : core. Lemma submxMl m n p (D : 'M_(m, n)) (A : 'M_(n, p)) : (D *m A <= A)%MS. Proof. by rewrite submxE -mulmxA mulmx_coker mulmx0. Qed. Lemma submxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) : (A <= B)%MS -> (A *m C <= B *m C)%MS. Proof. by case/submxP=> D ->; rewrite -mulmxA submxMl. Qed. Lemma mulmx_sub m n1 n2 p (C : 'M_(m, n1)) A (B : 'M_(n2, p)) : (A <= B -> C *m A <= B)%MS. Proof. by case/submxP=> D ->; rewrite mulmxA submxMl. Qed. Lemma submx_trans m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : (A <= B -> B <= C -> A <= C)%MS. Proof. by case/submxP=> D ->{A}; apply: mulmx_sub. Qed. Lemma ltmx_sub_trans m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : (A < B)%MS -> (B <= C)%MS -> (A < C)%MS. Proof. case/andP=> sAB ltAB sBC; rewrite ltmxE (submx_trans sAB) //. by apply: contra ltAB; apply: submx_trans. Qed. Lemma sub_ltmx_trans m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : (A <= B)%MS -> (B < C)%MS -> (A < C)%MS. Proof. move=> sAB /andP[sBC ltBC]; rewrite ltmxE (submx_trans sAB) //. by apply: contra ltBC => sCA; apply: submx_trans sAB. Qed. Lemma ltmx_trans m n : transitive (@ltmx F m m n). Proof. by move=> A B C; move/ltmxW; apply: sub_ltmx_trans. Qed. Lemma ltmx_irrefl m n : irreflexive (@ltmx F m m n). Proof. by move=> A; rewrite /ltmx submx_refl andbF. Qed. Lemma sub0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) <= A)%MS. Proof. by rewrite submxE mul0mx. Qed. Lemma submx0null m1 m2 n (A : 'M[F]_(m1, n)) : (A <= (0 : 'M_(m2, n)))%MS -> A = 0. Proof. by case/submxP=> D; rewrite mulmx0. Qed. Lemma submx0 m n (A : 'M_(m, n)) : (A <= (0 : 'M_n))%MS = (A == 0). Proof. by apply/idP/eqP=> [|->]; [apply: submx0null | apply: sub0mx]. Qed. Lemma lt0mx m n (A : 'M_(m, n)) : ((0 : 'M_n) < A)%MS = (A != 0). Proof. by rewrite /ltmx sub0mx submx0. Qed. Lemma ltmx0 m n (A : 'M[F]_(m, n)) : (A < (0 : 'M_n))%MS = false. Proof. by rewrite /ltmx sub0mx andbF. Qed. Lemma eqmx0P m n (A : 'M_(m, n)) : reflect (A = 0) (A == (0 : 'M_n))%MS. Proof. by rewrite submx0 sub0mx andbT; apply: eqP. Qed. Lemma eqmx_eq0 m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :=: B)%MS -> (A == 0) = (B == 0). Proof. by move=> eqAB; rewrite -!submx0 eqAB. Qed. Lemma addmx_sub m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) : (A <= C)%MS -> (B <= C)%MS -> ((A + B)%R <= C)%MS. Proof. by case/submxP=> A' ->; case/submxP=> B' ->; rewrite -mulmxDl submxMl. Qed. Lemma rowsub_sub m1 m2 n (f : 'I_m2 -> 'I_m1) (A : 'M_(m1, n)) : (rowsub f A <= A)%MS. Proof. by rewrite rowsubE mulmx_sub. Qed. Lemma summx_sub m1 m2 n (B : 'M_(m2, n)) I (r : seq I) (P : pred I) (A_ : I -> 'M_(m1, n)) : (forall i, P i -> A_ i <= B)%MS -> ((\sum_(i <- r | P i) A_ i)%R <= B)%MS. Proof. by move=> leAB; elim/big_ind: _ => // [|C D]; [apply/sub0mx | apply/addmx_sub]. Qed. Lemma scalemx_sub m1 m2 n a (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A <= B)%MS -> (a *: A <= B)%MS. Proof. by case/submxP=> A' ->; rewrite scalemxAl submxMl. Qed. Lemma row_sub m n i (A : 'M_(m, n)) : (row i A <= A)%MS. Proof. exact: rowsub_sub. Qed. Lemma eq_row_sub m n v (A : 'M_(m, n)) i : row i A = v -> (v <= A)%MS. Proof. by move <-; rewrite row_sub. Qed. Arguments eq_row_sub [m n v A]. Lemma nz_row_sub m n (A : 'M_(m, n)) : (nz_row A <= A)%MS. Proof. by rewrite /nz_row; case: pickP => [i|] _; rewrite ?row_sub ?sub0mx. Qed. Lemma row_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (forall i, row i A <= B)%MS (A <= B)%MS. Proof. apply: (iffP idP) => [sAB i|sAB]. by apply: submx_trans sAB; apply: row_sub. rewrite submxE; apply/eqP/row_matrixP=> i; apply/eqP. by rewrite row_mul row0 -submxE. Qed. Arguments row_subP {m1 m2 n A B}. Lemma rV_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (forall v : 'rV_n, v <= A -> v <= B)%MS (A <= B)%MS. Proof. apply: (iffP idP) => [sAB v Av | sAB]; first exact: submx_trans sAB. by apply/row_subP=> i; rewrite sAB ?row_sub. Qed. Arguments rV_subP {m1 m2 n A B}. Lemma row_subPn m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (exists i, ~~ (row i A <= B)%MS) (~~ (A <= B)%MS). Proof. by rewrite (sameP row_subP forallP); apply: forallPn. Qed. Lemma sub_rVP n (u v : 'rV[F]_n) : reflect (exists a, u = a *: v) (u <= v)%MS. Proof. apply: (iffP submxP) => [[w ->] | [a ->]]. by exists (w 0 0); rewrite -mul_scalar_mx -mx11_scalar. by exists a%:M; rewrite mul_scalar_mx. Qed. Lemma rank_rV n (v : 'rV[F]_n) : \rank v = (v != 0). Proof. case: eqP => [-> | nz_v]; first by rewrite mxrank0. by apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0; apply/eqP. Qed. Lemma rowV0Pn m n (A : 'M_(m, n)) : reflect (exists2 v : 'rV_n, v <= A & v != 0)%MS (A != 0). Proof. rewrite -submx0; apply: (iffP idP) => [| [v svA]]; last first. by rewrite -submx0; apply: contra (submx_trans _). by case/row_subPn=> i; rewrite submx0; exists (row i A); rewrite ?row_sub. Qed. Lemma rowV0P m n (A : 'M_(m, n)) : reflect (forall v : 'rV_n, v <= A -> v = 0)%MS (A == 0). Proof. rewrite -[A == 0]negbK; case: rowV0Pn => IH. by right; case: IH => v svA nzv IH; case/eqP: nzv; apply: IH. by left=> v svA; apply/eqP/idPn=> nzv; case: IH; exists v. Qed. Lemma submx_full m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : row_full B -> (A <= B)%MS. Proof. by rewrite submxE /cokermx => /eqnP->; rewrite /copid_mx pid_mx_1 subrr !mulmx0. Qed. Lemma row_fullP m n (A : 'M_(m, n)) : reflect (exists B, B *m A = 1%:M) (row_full A). Proof. apply: (iffP idP) => [Afull | [B kA]]. by exists (1%:M *m pinvmx A); apply: mulmxKpV (submx_full _ Afull). by rewrite [_ A]eqn_leq rank_leq_col (mulmx1_min_rank B 1%:M) ?mulmx1. Qed. Arguments row_fullP {m n A}. Lemma row_full_inj m n p A : row_full A -> injective (@mulmx F m n p A). Proof. case/row_fullP=> A' A'K; apply: can_inj (mulmx A') _ => B. by rewrite mulmxA A'K mul1mx. Qed. Lemma row_freeP m n (A : 'M_(m, n)) : reflect (exists B, A *m B = 1%:M) (row_free A). Proof. rewrite /row_free -mxrank_tr. apply: (iffP row_fullP) => [] [B kA]; by exists B^T; rewrite -trmx1 -kA trmx_mul ?trmxK. Qed. Lemma row_free_inj m n p A : row_free A -> injective ((@mulmx F m n p)^~ A). Proof. case/row_freeP=> A' AK; apply: can_inj (mulmx^~ A') _ => B. by rewrite -mulmxA AK mulmx1. Qed. (* A variant of row_free_inj that exposes mulmxr, an alias for mulmx^~ *) (* but which is canonically additive *) Definition row_free_injr m n p A : row_free A -> injective (mulmxr A) := @row_free_inj m n p A. Lemma row_free_unit n (A : 'M_n) : row_free A = (A \in unitmx). Proof. apply/row_fullP/idP=> [[A'] | uA]; first by case/mulmx1_unit. by exists (invmx A); rewrite mulVmx. Qed. Lemma row_full_unit n (A : 'M_n) : row_full A = (A \in unitmx). Proof. exact: row_free_unit. Qed. Lemma mxrank_unit n (A : 'M_n) : A \in unitmx -> \rank A = n. Proof. by rewrite -row_full_unit => /eqnP. Qed. Lemma mxrank1 n : \rank (1%:M : 'M_n) = n. Proof. exact: mxrank_unit. Qed. Lemma mxrank_delta m n i j : \rank (delta_mx i j : 'M_(m, n)) = 1. Proof. apply/eqP; rewrite eqn_leq lt0n mxrank_eq0. rewrite -{1}(mul_delta_mx (0 : 'I_1)) mulmx_max_rank. by apply/eqP; move/matrixP; move/(_ i j); move/eqP; rewrite !mxE !eqxx oner_eq0. Qed. Lemma mxrankS m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A <= B)%MS -> \rank A <= \rank B. Proof. by case/submxP=> D ->; rewrite mxrankM_maxr. Qed. Lemma submx1 m n (A : 'M_(m, n)) : (A <= 1%:M)%MS. Proof. by rewrite submx_full // row_full_unit unitmx1. Qed. Lemma sub1mx m n (A : 'M_(m, n)) : (1%:M <= A)%MS = row_full A. Proof. apply/idP/idP; last exact: submx_full. by move/mxrankS; rewrite mxrank1 col_leq_rank. Qed. Lemma ltmx1 m n (A : 'M_(m, n)) : (A < 1%:M)%MS = ~~ row_full A. Proof. by rewrite /ltmx sub1mx submx1. Qed. Lemma lt1mx m n (A : 'M_(m, n)) : (1%:M < A)%MS = false. Proof. by rewrite /ltmx submx1 andbF. Qed. Lemma pinvmxE n (A : 'M[F]_n) : A \in unitmx -> pinvmx A = invmx A. Proof. move=> A_unit; apply: (@row_free_inj _ _ _ A); rewrite ?row_free_unit//. by rewrite -[pinvmx _]mul1mx mulmxKpV ?sub1mx ?row_full_unit// mulVmx. Qed. Lemma mulVpmx m n (A : 'M[F]_(m, n)) : row_full A -> pinvmx A *m A = 1%:M. Proof. by move=> fA; rewrite -[pinvmx _]mul1mx mulmxKpV// sub1mx. Qed. Lemma pinvmx_free m n (A : 'M[F]_(m, n)) : row_full A -> row_free (pinvmx A). Proof. by move=> /mulVpmx pAA1; apply/row_freeP; exists A. Qed. Lemma pinvmx_full m n (A : 'M[F]_(m, n)) : row_free A -> row_full (pinvmx A). Proof. by move=> /mulmxVp ApA1; apply/row_fullP; exists A. Qed. Lemma eqmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (A :=: B)%MS (A == B)%MS. Proof. apply: (iffP andP) => [[sAB sBA] | eqAB]; last by rewrite !eqAB. split=> [|m3 C]; first by apply/eqP; rewrite eqn_leq !mxrankS. split; first by apply/idP/idP; apply: submx_trans. by apply/idP/idP=> sC; apply: submx_trans sC _. Qed. Arguments eqmxP {m1 m2 n A B}. Lemma rV_eqP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (forall u : 'rV_n, (u <= A) = (u <= B))%MS (A == B)%MS. Proof. apply: (iffP idP) => [eqAB u | eqAB]; first by rewrite (eqmxP eqAB). by apply/andP; split; apply/rV_subP=> u; rewrite eqAB. Qed. Lemma mulmxP (m n : nat) (A B : 'M[F]_(m, n)) : reflect (forall u : 'rV_m, u *m A = u *m B) (A == B). Proof. apply: (iffP eqP) => [-> //|eqAB]. apply: (@row_full_inj _ _ _ 1%:M); first by rewrite row_full_unit unitmx1. by apply/row_matrixP => i; rewrite !row_mul eqAB. Qed. Lemma eqmx_refl m1 n (A : 'M_(m1, n)) : (A :=: A)%MS. Proof. by []. Qed. Lemma eqmx_sym m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :=: B)%MS -> (B :=: A)%MS. Proof. by move=> eqAB; split=> [|m3 C]; rewrite !eqAB. Qed. Lemma eqmx_trans m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : (A :=: B)%MS -> (B :=: C)%MS -> (A :=: C)%MS. Proof. by move=> eqAB eqBC; split=> [|m4 D]; rewrite !eqAB !eqBC. Qed. Lemma eqmx_rank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A == B)%MS -> \rank A = \rank B. Proof. by move/eqmxP->. Qed. Lemma lt_eqmx m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :=: B)%MS -> forall C : 'M_(m3, n), (((A < C) = (B < C))%MS * ((C < A) = (C < B))%MS)%type. Proof. by move=> eqAB C; rewrite /ltmx !eqAB. Qed. Lemma eqmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) : (A :=: B)%MS -> (A *m C :=: B *m C)%MS. Proof. by move=> eqAB; apply/eqmxP; rewrite !submxMr ?eqAB. Qed. Lemma eqmxMfull m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : row_full A -> (A *m B :=: B)%MS. Proof. case/row_fullP=> A' A'A; apply/eqmxP; rewrite submxMl /=. by apply/submxP; exists A'; rewrite mulmxA A'A mul1mx. Qed. Lemma eqmx0 m n : ((0 : 'M[F]_(m, n)) :=: (0 : 'M_n))%MS. Proof. by apply/eqmxP; rewrite !sub0mx. Qed. Lemma eqmx_scale m n a (A : 'M_(m, n)) : a != 0 -> (a *: A :=: A)%MS. Proof. move=> nz_a; apply/eqmxP; rewrite scalemx_sub //. by rewrite -{1}[A]scale1r -(mulVf nz_a) -scalerA scalemx_sub. Qed. Lemma eqmx_opp m n (A : 'M_(m, n)) : (- A :=: A)%MS. Proof. by rewrite -scaleN1r; apply: eqmx_scale => //; rewrite oppr_eq0 oner_eq0. Qed. Lemma submxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) : row_free C -> (A *m C <= B *m C)%MS = (A <= B)%MS. Proof. case/row_freeP=> C' C_C'_1; apply/idP/idP=> sAB; last exact: submxMr. by rewrite -[A]mulmx1 -[B]mulmx1 -C_C'_1 !mulmxA submxMr. Qed. Lemma eqmxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) : row_free C -> (A *m C :=: B *m C)%MS -> (A :=: B)%MS. Proof. by move=> Cfree eqAB; apply/eqmxP; move/eqmxP: eqAB; rewrite !submxMfree. Qed. Lemma mxrankMfree m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : row_free B -> \rank (A *m B) = \rank A. Proof. by move=> Bfree; rewrite -mxrank_tr trmx_mul eqmxMfull /row_full mxrank_tr. Qed. Lemma eq_row_base m n (A : 'M_(m, n)) : (row_base A :=: A)%MS. Proof. apply/eqmxP/andP; split; apply/submxP. exists (pid_mx (\rank A) *m invmx (col_ebase A)). by rewrite -{8}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id. exists (col_ebase A *m pid_mx (\rank A)). by rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase. Qed. Lemma row_base0 (m n : nat) : row_base (0 : 'M[F]_(m, n)) = 0. Proof. by apply/eqmx0P; rewrite !eq_row_base !sub0mx. Qed. Let qidmx_eq1 n (A : 'M_n) : qidmx A = (A == 1%:M). Proof. by rewrite /qidmx eqxx pid_mx_1. Qed. Let genmx_witnessP m n (A : 'M_(m, n)) : equivmx A (row_full A) (genmx_witness A). Proof. rewrite /equivmx qidmx_eq1 /genmx_witness. case fullA: (row_full A); first by rewrite eqxx sub1mx submx1 fullA. set B := _ *m _; have defB : (B == A)%MS. apply/andP; split; apply/submxP. exists (pid_mx (\rank A) *m invmx (col_ebase A)). by rewrite -{3}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id. exists (col_ebase A *m pid_mx (\rank A)). by rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase. rewrite defB -negb_add addbF; case: eqP defB => // ->. by rewrite sub1mx fullA. Qed. Lemma genmxE m n (A : 'M_(m, n)) : (<<A>> :=: A)%MS. Proof. by rewrite unlock; apply/eqmxP; case/andP: (chooseP (genmx_witnessP A)). Qed. Lemma eq_genmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :=: B -> <<A>> = <<B>>)%MS. Proof. move=> eqAB; rewrite unlock. have{} eqAB: equivmx A (row_full A) =1 equivmx B (row_full B). by move=> C; rewrite /row_full /equivmx !eqAB. rewrite (eq_choose eqAB) (choose_id _ (genmx_witnessP B)) //. by rewrite -eqAB genmx_witnessP. Qed. Lemma genmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (<<A>> = <<B>>)%MS (A == B)%MS. Proof. apply: (iffP idP) => eqAB; first exact: eq_genmx (eqmxP _). by rewrite -!(genmxE A) eqAB !genmxE andbb. Qed. Arguments genmxP {m1 m2 n A B}. Lemma genmx0 m n : <<0 : 'M_(m, n)>>%MS = 0. Proof. by apply/eqP; rewrite -submx0 genmxE sub0mx. Qed. Lemma genmx1 n : <<1%:M : 'M_n>>%MS = 1%:M. Proof. rewrite unlock; case/andP: (chooseP (@genmx_witnessP n n 1%:M)) => _ /eqP. by rewrite qidmx_eq1 row_full_unit unitmx1 => /eqP. Qed. Lemma genmx_id m n (A : 'M_(m, n)) : (<<<<A>>>> = <<A>>)%MS. Proof. exact/eq_genmx/genmxE. Qed. Lemma row_base_free m n (A : 'M_(m, n)) : row_free (row_base A). Proof. by apply/eqnP; rewrite eq_row_base. Qed. Lemma mxrank_gen m n (A : 'M_(m, n)) : \rank <<A>>%MS = \rank A. Proof. by rewrite genmxE. Qed. Lemma col_base_full m n (A : 'M_(m, n)) : row_full (col_base A). Proof. apply/row_fullP; exists (pid_mx (\rank A) *m invmx (col_ebase A)). by rewrite !mulmxA mulmxKV // pid_mx_id // pid_mx_1. Qed. Hint Resolve row_base_free col_base_full : core. Lemma mxrank_leqif_sup m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A <= B)%MS -> \rank A <= \rank B ?= iff (B <= A)%MS. Proof. move=> sAB; split; first by rewrite mxrankS. apply/idP/idP=> [| sBA]; last by rewrite eqn_leq !mxrankS. case/submxP: sAB => D ->; set r := \rank B; rewrite -(mulmx_base B) mulmxA. rewrite mxrankMfree // => /row_fullP[E kE]. by rewrite -[rB in _ *m rB]mul1mx -kE -(mulmxA E) (mulmxA _ E) submxMl. Qed. Lemma mxrank_leqif_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A <= B)%MS -> \rank A <= \rank B ?= iff (A == B)%MS. Proof. by move=> sAB; rewrite sAB; apply: mxrank_leqif_sup. Qed. Lemma ltmxErank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A < B)%MS = (A <= B)%MS && (\rank A < \rank B). Proof. by apply: andb_id2l => sAB; rewrite (ltn_leqif (mxrank_leqif_sup sAB)). Qed. Lemma rank_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A < B)%MS -> \rank A < \rank B. Proof. by rewrite ltmxErank => /andP[]. Qed. Lemma eqmx_cast m1 m2 n (A : 'M_(m1, n)) e : ((castmx e A : 'M_(m2, n)) :=: A)%MS. Proof. by case: e A; case: m2 / => A e; rewrite castmx_id. Qed. Lemma row_full_castmx m1 m2 n (A : 'M_(m1, n)) e : row_full (castmx e A : 'M_(m2, n)) = row_full A. Proof. exact/eq_row_full/eqmx_cast. Qed. Lemma row_free_castmx m1 m2 n (A : 'M_(m1, n)) e : row_free (castmx e A : 'M_(m2, n)) = row_free A. Proof. by rewrite /row_free eqmx_cast; congr (_ == _); rewrite e.1. Qed. Lemma eqmx_conform m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (conform_mx A B :=: A \/ conform_mx A B :=: B)%MS. Proof. case: (eqVneq m2 m1) => [-> | neqm12] in B *. by right; rewrite conform_mx_id. by left; rewrite nonconform_mx ?neqm12. Qed. Let eqmx_sum_nop m n (A : 'M_(m, n)) : (addsmx_nop A :=: A)%MS. Proof. case: (eqmx_conform <<A>>%MS A) => // eq_id_gen. exact: eqmx_trans (genmxE A). Qed. Lemma rowsub_comp_sub (m n p q : nat) f (g : 'I_n -> 'I_p) (A : 'M_(m, q)) : (rowsub (f \o g) A <= rowsub f A)%MS. Proof. by rewrite rowsub_comp rowsubE mulmx_sub. Qed. Lemma submx_rowsub (m n p q : nat) (h : 'I_n -> 'I_p) f g (A : 'M_(m, q)) : f =1 g \o h -> (rowsub f A <= rowsub g A)%MS. Proof. by move=> /eq_rowsub->; rewrite rowsub_comp_sub. Qed. Arguments submx_rowsub [m1 m2 m3 n] h [f g A] _ : rename. Lemma eqmx_rowsub_comp_perm (m1 m2 n : nat) (s : 'S_m2) f (A : 'M_(m1, n)) : (rowsub (f \o s) A :=: rowsub f A)%MS. Proof. rewrite rowsub_comp rowsubE; apply: eqmxMfull. by rewrite -perm_mxEsub row_full_unit unitmx_perm. Qed. Lemma eqmx_rowsub_comp (m n p q : nat) f (g : 'I_n -> 'I_p) (A : 'M_(m, q)) : p <= n -> injective g -> (rowsub (f \o g) A :=: rowsub f A)%MS. Proof. move=> leq_pn g_inj; have eq_np : n == p by rewrite eqn_leq leq_pn (inj_leq g). rewrite (eqP eq_np) in g g_inj *. rewrite (eq_rowsub (f \o (perm g_inj))); last by move=> i; rewrite /= permE. exact: eqmx_rowsub_comp_perm. Qed. Lemma eqmx_rowsub (m n p q : nat) (h : 'I_n -> 'I_p) f g (A : 'M_(m, q)) : injective h -> p <= n -> f =1 g \o h -> (rowsub f A :=: rowsub g A)%MS. Proof. by move=> leq_pn h_inj /eq_rowsub->; apply: eqmx_rowsub_comp. Qed. Arguments eqmx_rowsub [m1 m2 m3 n] h [f g A] _ : rename. Section AddsmxSub. Variable (m1 m2 n : nat) (A : 'M[F]_(m1, n)) (B : 'M[F]_(m2, n)). Lemma col_mx_sub m3 (C : 'M_(m3, n)) : (col_mx A B <= C)%MS = (A <= C)%MS && (B <= C)%MS. Proof. rewrite !submxE mul_col_mx -col_mx0. by apply/eqP/andP; [case/eq_col_mx=> -> -> | case; do 2!move/eqP->]. Qed. Lemma addsmxE : (A + B :=: col_mx A B)%MS. Proof. have:= submx_refl (col_mx A B); rewrite col_mx_sub; case/andP=> sAS sBS. rewrite unlock; do 2?case: eqP => [AB0 | _]; last exact: genmxE. by apply/eqmxP; rewrite !eqmx_sum_nop sBS col_mx_sub AB0 sub0mx /=. by apply/eqmxP; rewrite !eqmx_sum_nop sAS col_mx_sub AB0 sub0mx andbT /=. Qed. Lemma addsmx_sub m3 (C : 'M_(m3, n)) : (A + B <= C)%MS = (A <= C)%MS && (B <= C)%MS. Proof. by rewrite addsmxE col_mx_sub. Qed. Lemma addsmxSl : (A <= A + B)%MS. Proof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed. Lemma addsmxSr : (B <= A + B)%MS. Proof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed. Lemma addsmx_idPr : reflect (A + B :=: B)%MS (A <= B)%MS. Proof. have:= @eqmxP _ _ _ (A + B)%MS B. by rewrite addsmxSr addsmx_sub submx_refl !andbT. Qed. Lemma addsmx_idPl : reflect (A + B :=: A)%MS (B <= A)%MS. Proof. have:= @eqmxP _ _ _ (A + B)%MS A. by rewrite addsmxSl addsmx_sub submx_refl !andbT. Qed. End AddsmxSub. Lemma adds0mx m1 m2 n (B : 'M_(m2, n)) : ((0 : 'M_(m1, n)) + B :=: B)%MS. Proof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSr /= andbT. Qed. Lemma addsmx0 m1 m2 n (A : 'M_(m1, n)) : (A + (0 : 'M_(m2, n)) :=: A)%MS. Proof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSl /= !andbT. Qed. Let addsmx_nop_eq0 m n (A : 'M_(m, n)) : (addsmx_nop A == 0) = (A == 0). Proof. by rewrite -!submx0 eqmx_sum_nop. Qed. Let addsmx_nop0 m n : addsmx_nop (0 : 'M_(m, n)) = 0. Proof. by apply/eqP; rewrite addsmx_nop_eq0. Qed. Let addsmx_nop_id n (A : 'M_n) : addsmx_nop A = A. Proof. exact: conform_mx_id. Qed. Lemma addsmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A + B = B + A)%MS. Proof. have: (A + B == B + A)%MS. by apply/andP; rewrite !addsmx_sub andbC -addsmx_sub andbC -addsmx_sub. move/genmxP; rewrite [@addsmx]unlock -!submx0 !submx0. by do 2!case: eqP => [// -> | _]; rewrite ?genmx_id ?addsmx_nop0. Qed. Lemma adds0mx_id m1 n (B : 'M_n) : ((0 : 'M_(m1, n)) + B)%MS = B. Proof. by rewrite unlock eqxx addsmx_nop_id. Qed. Lemma addsmx0_id m2 n (A : 'M_n) : (A + (0 : 'M_(m2, n)))%MS = A. Proof. by rewrite addsmxC adds0mx_id. Qed. Lemma addsmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : (A + (B + C) = A + B + C)%MS. Proof. have: (A + (B + C) :=: A + B + C)%MS. by apply/eqmxP/andP; rewrite !addsmx_sub -andbA andbA -!addsmx_sub. rewrite {1 3}[in @addsmx _ m1]unlock [in @addsmx _ n]unlock !addsmx_nop_id -!submx0. rewrite !addsmx_sub ![@addsmx]unlock -!submx0; move/eq_genmx. by do 3!case: (_ <= 0)%MS; rewrite //= !genmx_id. Qed. HB.instance Definition _ n := Monoid.isComLaw.Build (matrix F n n) 0%MS addsmx.body (@addsmxA n n n n) (@addsmxC n n n) (@adds0mx_id n n). Lemma addsmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) : ((A + B)%MS *m C :=: A *m C + B *m C)%MS. Proof. by apply/eqmxP; rewrite !addsmxE -!mul_col_mx !submxMr ?addsmxE. Qed. Lemma addsmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) (D : 'M_(m4, n)) : (A <= C -> B <= D -> A + B <= C + D)%MS. Proof. move=> sAC sBD. by rewrite addsmx_sub {1}addsmxC !(submx_trans _ (addsmxSr _ _)). Qed. Lemma addmx_sub_adds m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m, n)) (C : 'M_(m1, n)) (D : 'M_(m2, n)) : (A <= C -> B <= D -> (A + B)%R <= C + D)%MS. Proof. move=> sAC; move/(addsmxS sAC); apply: submx_trans. by rewrite addmx_sub ?addsmxSl ?addsmxSr. Qed. Lemma addsmx_addKl n m1 m2 (A : 'M_(m1, n)) (B C : 'M_(m2, n)) : (B <= A)%MS -> (A + (B + C)%R :=: A + C)%MS. Proof. move=> sBA; apply/eqmxP; rewrite !addsmx_sub !addsmxSl. by rewrite -{3}[C](addKr B) !addmx_sub_adds ?eqmx_opp. Qed. Lemma addsmx_addKr n m1 m2 (A B : 'M_(m1, n)) (C : 'M_(m2, n)) : (B <= C)%MS -> ((A + B)%R + C :=: A + C)%MS. Proof. by rewrite -!(addsmxC C) addrC; apply: addsmx_addKl. Qed. Lemma adds_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) (D : 'M_(m4, n)) : (A :=: C -> B :=: D -> A + B :=: C + D)%MS. Proof. by move=> eqAC eqBD; apply/eqmxP; rewrite !addsmxS ?eqAC ?eqBD. Qed. Lemma genmx_adds m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (<<(A + B)%MS>> = <<A>> + <<B>>)%MS. Proof. rewrite -(eq_genmx (adds_eqmx (genmxE A) (genmxE B))). by rewrite [@addsmx]unlock !addsmx_nop_id !(fun_if (@genmx _ _ _)) !genmx_id. Qed. Lemma sub_addsmxP m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : reflect (exists u, A = u.1 *m B + u.2 *m C) (A <= B + C)%MS. Proof. apply: (iffP idP) => [|[u ->]]; last by rewrite addmx_sub_adds ?submxMl. rewrite addsmxE; case/submxP=> u ->; exists (lsubmx u, rsubmx u). by rewrite -mul_row_col hsubmxK. Qed. Arguments sub_addsmxP {m1 m2 m3 n A B C}. Variable I : finType. Implicit Type P : pred I. Lemma genmx_sums P n (B_ : I -> 'M_n) : <<(\sum_(i | P i) B_ i)%MS>>%MS = (\sum_(i | P i) <<B_ i>>)%MS. Proof. exact: (big_morph _ (@genmx_adds n n n) (@genmx0 n n)). Qed. Lemma sumsmx_sup i0 P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) : P i0 -> (A <= B_ i0)%MS -> (A <= \sum_(i | P i) B_ i)%MS. Proof. by move=> Pi0 sAB; apply: submx_trans sAB _; rewrite (bigD1 i0) // addsmxSl. Qed. Arguments sumsmx_sup i0 [P m n A B_]. Lemma sumsmx_subP P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) : reflect (forall i, P i -> A_ i <= B)%MS (\sum_(i | P i) A_ i <= B)%MS. Proof. apply: (iffP idP) => [sAB i Pi | sAB]. by apply: submx_trans sAB; apply: sumsmx_sup Pi _. by elim/big_rec: _ => [|i Ai Pi sAiB]; rewrite ?sub0mx // addsmx_sub sAB. Qed. Lemma summx_sub_sums P m n (A : I -> 'M[F]_(m, n)) B : (forall i, P i -> A i <= B i)%MS -> ((\sum_(i | P i) A i)%R <= \sum_(i | P i) B i)%MS. Proof. by move=> sAB; apply: summx_sub => i Pi; rewrite (sumsmx_sup i) ?sAB. Qed. Lemma sumsmxS P n (A B : I -> 'M[F]_n) : (forall i, P i -> A i <= B i)%MS -> (\sum_(i | P i) A i <= \sum_(i | P i) B i)%MS. Proof. by move=> sAB; apply/sumsmx_subP=> i Pi; rewrite (sumsmx_sup i) ?sAB. Qed. Lemma eqmx_sums P n (A B : I -> 'M[F]_n) : (forall i, P i -> A i :=: B i)%MS -> (\sum_(i | P i) A i :=: \sum_(i | P i) B i)%MS. Proof. by move=> eqAB; apply/eqmxP; rewrite !sumsmxS // => i; move/eqAB->. Qed. Lemma sub_sums_genmxP P m n p (A : 'M_(m, p)) (B_ : I -> 'M_(n, p)) : reflect (exists u_ : I -> 'M_(m, n), A = \sum_(i | P i) u_ i *m B_ i) (A <= \sum_(i | P i) <<B_ i>>)%MS. Proof. apply: (iffP idP) => [| [u_ ->]]; last first. by apply: summx_sub_sums => i _; rewrite genmxE; apply: submxMl. have [b] := ubnP #|P|; elim: b => // b IHb in P A *. case: (pickP P) => [i Pi | P0 _]; last first. rewrite big_pred0 //; move/submx0null->. by exists (fun _ => 0); rewrite big_pred0. rewrite (cardD1x Pi) (bigD1 i) //= => /IHb{b IHb} /= IHi. rewrite (adds_eqmx (genmxE _) (eqmx_refl _)) => /sub_addsmxP[u ->]. have [u_ ->] := IHi _ (submxMl u.2 _). exists [eta u_ with i |-> u.1]; rewrite (bigD1 i Pi)/= eqxx; congr (_ + _). by apply: eq_bigr => j /andP[_ /negPf->]. Qed. Lemma sub_sumsmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) : reflect (exists u_, A = \sum_(i | P i) u_ i *m B_ i) (A <= \sum_(i | P i) B_ i)%MS. Proof. by rewrite -(eqmx_sums (fun _ _ => genmxE _)); apply/sub_sums_genmxP. Qed. Lemma sumsmxMr_gen P m n A (B : 'M[F]_(m, n)) : ((\sum_(i | P i) A i)%MS *m B :=: \sum_(i | P i) <<A i *m B>>)%MS. Proof. apply/eqmxP/andP; split; last first. by apply/sumsmx_subP=> i Pi; rewrite genmxE submxMr ?(sumsmx_sup i). have [u ->] := sub_sumsmxP _ _ _ (submx_refl (\sum_(i | P i) A i)%MS). by rewrite mulmx_suml summx_sub_sums // => i _; rewrite genmxE -mulmxA submxMl. Qed. Lemma sumsmxMr P n (A_ : I -> 'M[F]_n) (B : 'M_n) : ((\sum_(i | P i) A_ i)%MS *m B :=: \sum_(i | P i) (A_ i *m B))%MS. Proof. by apply: eqmx_trans (sumsmxMr_gen _ _ _) (eqmx_sums _) => i _; apply: genmxE. Qed. Lemma rank_pid_mx m n r : r <= m -> r <= n -> \rank (pid_mx r : 'M_(m, n)) = r. Proof. do 2!move/subnKC <-; rewrite pid_mx_block block_mxEv row_mx0 -addsmxE addsmx0. by rewrite -mxrank_tr tr_row_mx trmx0 trmx1 -addsmxE addsmx0 mxrank1. Qed. Lemma rank_copid_mx n r : r <= n -> \rank (copid_mx r : 'M_n) = (n - r)%N. Proof. move/subnKC <-; rewrite /copid_mx pid_mx_block scalar_mx_block. rewrite opp_block_mx !oppr0 add_block_mx !addr0 subrr block_mxEv row_mx0. rewrite -addsmxE adds0mx -mxrank_tr tr_row_mx trmx0 trmx1. by rewrite -addsmxE adds0mx mxrank1 addKn. Qed. Lemma mxrank_compl m n (A : 'M_(m, n)) : \rank A^C = (n - \rank A)%N. Proof. by rewrite mxrankMfree ?row_free_unit ?rank_copid_mx. Qed. Lemma mxrank_ker m n (A : 'M_(m, n)) : \rank (kermx A) = (m - \rank A)%N. Proof. by rewrite mxrankMfree ?row_free_unit ?unitmx_inv ?rank_copid_mx. Qed. Lemma kermx_eq0 n m (A : 'M_(m, n)) : (kermx A == 0) = row_free A. Proof. by rewrite -mxrank_eq0 mxrank_ker subn_eq0 row_leq_rank. Qed. Lemma mxrank_coker m n (A : 'M_(m, n)) : \rank (cokermx A) = (n - \rank A)%N. Proof. by rewrite eqmxMfull ?row_full_unit ?unitmx_inv ?rank_copid_mx. Qed. Lemma cokermx_eq0 n m (A : 'M_(m, n)) : (cokermx A == 0) = row_full A. Proof. by rewrite -mxrank_eq0 mxrank_coker subn_eq0 col_leq_rank. Qed. Lemma mulmx_ker m n (A : 'M_(m, n)) : kermx A *m A = 0. Proof. by rewrite -{2}[A]mulmx_ebase !mulmxA mulmxKV // mul_copid_mx_pid ?mul0mx. Qed. Lemma mulmxKV_ker m n p (A : 'M_(n, p)) (B : 'M_(m, n)) : B *m A = 0 -> B *m col_ebase A *m kermx A = B. Proof. rewrite mulmxA mulmxBr mulmx1 mulmxBl mulmxK //. rewrite -{1}[A]mulmx_ebase !mulmxA => /(canRL (mulmxK (row_ebase_unit A))). rewrite mul0mx // => BA0; apply: (canLR (addrK _)). by rewrite -(pid_mx_id _ _ n (rank_leq_col A)) mulmxA BA0 !mul0mx addr0. Qed. Lemma sub_kermxP p m n (A : 'M_(m, n)) (B : 'M_(p, m)) : reflect (B *m A = 0) (B <= kermx A)%MS. Proof. apply: (iffP submxP) => [[D ->]|]; first by rewrite -mulmxA mulmx_ker mulmx0. by move/mulmxKV_ker; exists (B *m col_ebase A). Qed. Lemma sub_kermx p m n (A : 'M_(m, n)) (B : 'M_(p, m)) : (B <= kermx A)%MS = (B *m A == 0). Proof. exact/sub_kermxP/eqP. Qed. Lemma kermx0 m n : (kermx (0 : 'M_(m, n)) :=: 1%:M)%MS. Proof. by apply/eqmxP; rewrite submx1/= sub_kermx mulmx0. Qed. Lemma mulmx_free_eq0 m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : row_free B -> (A *m B == 0) = (A == 0). Proof. by rewrite -sub_kermx -kermx_eq0 => /eqP->; rewrite submx0. Qed. Lemma inj_row_free m n (A : 'M_(m, n)) : (forall v : 'rV_m, v *m A = 0 -> v = 0) -> row_free A. Proof. move=> Ainj; rewrite -kermx_eq0; apply/eqP/row_matrixP => i. by rewrite row0; apply/Ainj; rewrite -row_mul mulmx_ker row0. Qed. Lemma row_freePn m n (M : 'M[F]_(m, n)) : reflect (exists i, (row i M <= row' i M)%MS) (~~ row_free M). Proof. rewrite -kermx_eq0; apply: (iffP (rowV0Pn _)) => [|[i0 /submxP[D rM]]]. move=> [v /sub_kermxP vM_eq0 /rV0Pn[i0 vi0_neq0]]; exists i0. have := vM_eq0; rewrite mulmx_sum_row (bigD1_ord i0)//=. move=> /(canRL (addrK _))/(canRL (scalerK _))->//. rewrite sub0r scalerN -scaleNr scalemx_sub// summx_sub// => l _. by rewrite scalemx_sub// -row_rowsub row_sub. exists (\row_j oapp (D 0) (- 1) (unlift i0 j)); last first. by apply/rV0Pn; exists i0; rewrite !mxE unlift_none/= oppr_eq0 oner_eq0. apply/sub_kermxP; rewrite mulmx_sum_row (bigD1_ord i0)//= !mxE. rewrite unlift_none scaleN1r rM mulmx_sum_row addrC -sumrB big1 // => l _. by rewrite !mxE liftK row_rowsub subrr. Qed. Lemma negb_row_free m n (M : 'M[F]_(m, n)) : ~~ row_free M = [exists i, (row i M <= row' i M)%MS]. Proof. exact/row_freePn/existsP. Qed. Lemma mulmx0_rank_max m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : A *m B = 0 -> \rank A + \rank B <= n. Proof. move=> AB0; rewrite -{3}(subnK (rank_leq_row B)) leq_add2r. by rewrite -mxrank_ker mxrankS // sub_kermx AB0. Qed. Lemma mxrank_Frobenius m n p q (A : 'M_(m, n)) B (C : 'M_(p, q)) : \rank (A *m B) + \rank (B *m C) <= \rank B + \rank (A *m B *m C). Proof. rewrite -{2}(mulmx_base (A *m B)) -mulmxA (eqmxMfull _ (col_base_full _)). set C2 := row_base _ *m C. rewrite -{1}(subnK (rank_leq_row C2)) -(mxrank_ker C2) addnAC leq_add2r. rewrite addnC -{1}(mulmx_base B) -mulmxA eqmxMfull //. set C1 := _ *m C; rewrite -{2}(subnKC (rank_leq_row C1)) leq_add2l -mxrank_ker. rewrite -(mxrankMfree _ (row_base_free (A *m B))). have: (row_base (A *m B) <= row_base B)%MS by rewrite !eq_row_base submxMl. case/submxP=> D defD; rewrite defD mulmxA mxrankMfree ?mxrankS //. by rewrite sub_kermx -mulmxA (mulmxA D) -defD -/C2 mulmx_ker. Qed. Lemma mxrank_mul_min m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : \rank A + \rank B - n <= \rank (A *m B). Proof. by have:= mxrank_Frobenius A 1%:M B; rewrite mulmx1 mul1mx mxrank1 leq_subLR. Qed. Lemma addsmx_compl_full m n (A : 'M_(m, n)) : row_full (A + A^C)%MS. Proof. rewrite /row_full addsmxE; apply/row_fullP. exists (row_mx (pinvmx A) (cokermx A)); rewrite mul_row_col. rewrite -{2}[A]mulmx_ebase -!mulmxA mulKmx // -mulmxDr !mulmxA. by rewrite pid_mx_id ?copid_mx_id // -mulmxDl addrC subrK mul1mx mulVmx. Qed. Lemma sub_capmx_gen m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : (A <= capmx_gen B C)%MS = (A <= B)%MS && (A <= C)%MS. Proof. apply/idP/andP=> [sAI | [/submxP[B' ->{A}] /submxP[C' eqBC']]]. rewrite !(submx_trans sAI) ?submxMl // /capmx_gen. have:= mulmx_ker (col_mx B C); set K := kermx _. rewrite -{1}[K]hsubmxK mul_row_col; move/(canRL (addrK _))->. by rewrite add0r -mulNmx submxMl. have: (row_mx B' (- C') <= kermx (col_mx B C))%MS. by rewrite sub_kermx mul_row_col eqBC' mulNmx subrr. case/submxP=> D; rewrite -[kermx _]hsubmxK mul_mx_row. by case/eq_row_mx=> -> _; rewrite -mulmxA submxMl. Qed. Let capmx_witnessP m n (A : 'M_(m, n)) : equivmx A (qidmx A) (capmx_witness A). Proof. rewrite /equivmx qidmx_eq1 /qidmx /capmx_witness. rewrite -sub1mx; case s1A: (1%:M <= A)%MS => /=; last first. rewrite !genmxE submx_refl /= -negb_add; apply: contra {s1A}(negbT s1A). have [<- | _] := eqP; first by rewrite genmxE. by case: eqP A => //= -> A /eqP ->; rewrite pid_mx_1. case: (m =P n) => [-> | ne_mn] in A s1A *. by rewrite conform_mx_id submx_refl pid_mx_1 eqxx. by rewrite nonconform_mx ?submx1 ?s1A ?eqxx //; case: eqP. Qed. Let capmx_normP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_norm A). Proof. by case/andP: (chooseP (capmx_witnessP A)) => /eqmxP defN /eqP. Qed. Let capmx_norm_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : qidmx A = qidmx B -> (A == B)%MS -> capmx_norm A = capmx_norm B. Proof. move=> eqABid /eqmxP eqAB. have{eqABid} eqAB: equivmx A (qidmx A) =1 equivmx B (qidmx B). by move=> C; rewrite /equivmx eqABid !eqAB. rewrite {1}/capmx_norm (eq_choose eqAB). by apply: choose_id; first rewrite -eqAB; apply: capmx_witnessP. Qed. Let capmx_nopP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_nop A). Proof. rewrite /capmx_nop; case: (eqVneq m n) => [-> | ne_mn] in A *. by rewrite conform_mx_id. by rewrite nonconform_mx ?ne_mn //; apply: capmx_normP. Qed. Let sub_qidmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : qidmx B -> (A <= B)%MS. Proof. rewrite /qidmx => idB; apply: {A}submx_trans (submx1 A) _. by case: eqP B idB => [-> _ /eqP-> | _ B]; rewrite (=^~ sub1mx, pid_mx_1). Qed. Let qidmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : qidmx (A :&: B)%MS = qidmx A && qidmx B. Proof. rewrite unlock -sub1mx. case idA: (qidmx A); case idB: (qidmx B); try by rewrite capmx_nopP. case s1B: (_ <= B)%MS; first by rewrite capmx_normP. apply/idP=> /(sub_qidmx 1%:M). by rewrite capmx_normP sub_capmx_gen s1B andbF. Qed. Let capmx_eq_norm m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : qidmx A = qidmx B -> (A :&: B)%MS = capmx_norm (A :&: B)%MS. Proof. move=> eqABid; rewrite unlock -sub1mx {}eqABid. have norm_id m (C : 'M_(m, n)) (N := capmx_norm C) : capmx_norm N = N. by apply: capmx_norm_eq; rewrite ?capmx_normP ?andbb. case idB: (qidmx B); last by case: ifP; rewrite norm_id. rewrite /capmx_nop; case: (eqVneq m2 n) => [-> | neqm2n] in B idB *. have idN := idB; rewrite -{1}capmx_normP !qidmx_eq1 in idN idB. by rewrite conform_mx_id (eqP idN) (eqP idB). by rewrite nonconform_mx ?neqm2n ?norm_id. Qed. Lemma capmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B :=: capmx_gen A B)%MS. Proof. rewrite unlock -sub1mx; apply/eqmxP. have:= submx_refl (capmx_gen A B); rewrite !sub_capmx_gen => /andP[sIA sIB]. case idA: (qidmx A); first by rewrite !capmx_nopP submx_refl sub_qidmx. case idB: (qidmx B); first by rewrite !capmx_nopP submx_refl sub_qidmx. case s1B: (1%:M <= B)%MS; rewrite !capmx_normP ?sub_capmx_gen sIA ?sIB //=. by rewrite submx_refl (submx_trans (submx1 _)). Qed. Lemma capmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= A)%MS. Proof. by rewrite capmxE submxMl. Qed. Lemma sub_capmx m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) : (A <= B :&: C)%MS = (A <= B)%MS && (A <= C)%MS. Proof. by rewrite capmxE sub_capmx_gen. Qed. Lemma capmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B = B :&: A)%MS. Proof. have [eqAB|] := eqVneq (qidmx A) (qidmx B). rewrite (capmx_eq_norm eqAB) (capmx_eq_norm (esym eqAB)). apply: capmx_norm_eq; first by rewrite !qidmx_cap andbC. by apply/andP; split; rewrite !sub_capmx andbC -sub_capmx. by rewrite negb_eqb !unlock => /addbP <-; case: (qidmx A). Qed. Lemma capmxSr m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= B)%MS. Proof. by rewrite capmxC capmxSl. Qed. Lemma capmx_idPr n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (A :&: B :=: B)%MS (B <= A)%MS. Proof. have:= @eqmxP _ _ _ (A :&: B)%MS B. by rewrite capmxSr sub_capmx submx_refl !andbT. Qed. Lemma capmx_idPl n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (A :&: B :=: A)%MS (A <= B)%MS. Proof. by rewrite capmxC; apply: capmx_idPr. Qed. Lemma capmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) (D : 'M_(m4, n)) : (A <= C -> B <= D -> A :&: B <= C :&: D)%MS. Proof. by move=> sAC sBD; rewrite sub_capmx {1}capmxC !(submx_trans (capmxSr _ _)). Qed. Lemma cap_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) (D : 'M_(m4, n)) : (A :=: C -> B :=: D -> A :&: B :=: C :&: D)%MS. Proof. by move=> eqAC eqBD; apply/eqmxP; rewrite !capmxS ?eqAC ?eqBD. Qed. Lemma capmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) : ((A :&: B) *m C <= A *m C :&: B *m C)%MS. Proof. by rewrite sub_capmx !submxMr ?capmxSl ?capmxSr. Qed. Lemma cap0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) :&: A)%MS = 0. Proof. exact: submx0null (capmxSl _ _). Qed. Lemma capmx0 m1 m2 n (A : 'M_(m1, n)) : (A :&: (0 : 'M_(m2, n)))%MS = 0. Proof. exact: submx0null (capmxSr _ _). Qed. Lemma capmxT m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : row_full B -> (A :&: B :=: A)%MS. Proof. rewrite -sub1mx => s1B; apply/eqmxP. by rewrite capmxSl sub_capmx submx_refl (submx_trans (submx1 A)). Qed. Lemma capTmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : row_full A -> (A :&: B :=: B)%MS. Proof. by move=> Afull; apply/eqmxP; rewrite capmxC !capmxT ?andbb. Qed. Let capmx_nop_id n (A : 'M_n) : capmx_nop A = A. Proof. by rewrite /capmx_nop conform_mx_id. Qed. Lemma cap1mx n (A : 'M_n) : (1%:M :&: A = A)%MS. Proof. by rewrite unlock qidmx_eq1 eqxx capmx_nop_id. Qed. Lemma capmx1 n (A : 'M_n) : (A :&: 1%:M = A)%MS. Proof. by rewrite capmxC cap1mx. Qed. Lemma genmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : <<A :&: B>>%MS = (<<A>> :&: <<B>>)%MS. Proof. rewrite -(eq_genmx (cap_eqmx (genmxE A) (genmxE B))). case idAB: (qidmx <<A>> || qidmx <<B>>)%MS. rewrite [@capmx]unlock !capmx_nop_id !(fun_if (@genmx _ _ _)) !genmx_id. by case: (qidmx _) idAB => //= ->. case idA: (qidmx _) idAB => //= idB; rewrite {2}capmx_eq_norm ?idA //. set C := (_ :&: _)%MS; have eq_idC: row_full C = qidmx C. rewrite qidmx_cap idA -sub1mx sub_capmx genmxE; apply/andP=> [[s1A]]. by case/idP: idA; rewrite qidmx_eq1 -genmx1 (sameP eqP genmxP) submx1. rewrite unlock /capmx_norm eq_idC. by apply: choose_id (capmx_witnessP _); rewrite -eq_idC genmx_witnessP. Qed. Lemma capmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : (A :&: (B :&: C) = A :&: B :&: C)%MS. Proof. rewrite (capmxC A B) capmxC; wlog idA: m1 m3 A C / qidmx A. move=> IH; case idA: (qidmx A); first exact: IH. case idC: (qidmx C); first by rewrite -IH. rewrite (@capmx_eq_norm n m3) ?qidmx_cap ?idA ?idC ?andbF //. rewrite capmx_eq_norm ?qidmx_cap ?idA ?idC ?andbF //. apply: capmx_norm_eq; first by rewrite !qidmx_cap andbAC. by apply/andP; split; rewrite !sub_capmx andbAC -!sub_capmx. rewrite -!(capmxC A) [in @capmx _ m1]unlock idA capmx_nop_id. have [eqBC|] := eqVneq (qidmx B) (qidmx C). rewrite (@capmx_eq_norm n) ?capmx_nopP // capmx_eq_norm //. by apply: capmx_norm_eq; rewrite ?qidmx_cap ?capmxS ?capmx_nopP. by rewrite !unlock capmx_nopP capmx_nop_id; do 2?case: (qidmx _) => //. Qed. HB.instance Definition _ n := Monoid.isComLaw.Build (matrix F n n) 1%:M capmx.body (@capmxA n n n n) (@capmxC n n n) (@cap1mx n). Lemma bigcapmx_inf i0 P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) : P i0 -> (A_ i0 <= B -> \bigcap_(i | P i) A_ i <= B)%MS. Proof. by move=> Pi0; apply: submx_trans; rewrite (bigD1 i0) // capmxSl. Qed. Lemma sub_bigcapmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) : reflect (forall i, P i -> A <= B_ i)%MS (A <= \bigcap_(i | P i) B_ i)%MS. Proof. apply: (iffP idP) => [sAB i Pi | sAB]. by apply: (submx_trans sAB); rewrite (bigcapmx_inf Pi). by elim/big_rec: _ => [|i Pi C sAC]; rewrite ?submx1 // sub_capmx sAB. Qed. Lemma genmx_bigcap P n (A_ : I -> 'M_n) : (<<\bigcap_(i | P i) A_ i>> = \bigcap_(i | P i) <<A_ i>>)%MS. Proof. exact: (big_morph _ (@genmx_cap n n n) (@genmx1 n)). Qed. Lemma matrix_modl m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : (A <= C -> A + (B :&: C) :=: (A + B) :&: C)%MS. Proof. move=> sAC; set D := ((A + B) :&: C)%MS; apply/eqmxP. rewrite sub_capmx addsmxS ?capmxSl // addsmx_sub sAC capmxSr /=. have: (D <= B + A)%MS by rewrite addsmxC capmxSl. case/sub_addsmxP=> u defD; rewrite defD addrC addmx_sub_adds ?submxMl //. rewrite sub_capmx submxMl -[_ *m B](addrK (u.2 *m A)) -defD. by rewrite addmx_sub ?capmxSr // eqmx_opp mulmx_sub. Qed. Lemma matrix_modr m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) : (C <= A -> (A :&: B) + C :=: A :&: (B + C))%MS. Proof. by rewrite !(capmxC A) -!(addsmxC C); apply: matrix_modl. Qed. Lemma capmx_compl m n (A : 'M_(m, n)) : (A :&: A^C)%MS = 0. Proof. set D := (A :&: A^C)%MS; have: (D <= D)%MS by []. rewrite sub_capmx andbC => /andP[/submxP[B defB]]. rewrite submxE => /eqP; rewrite defB -!mulmxA mulKVmx ?copid_mx_id //. by rewrite mulmxA => ->; rewrite mul0mx. Qed. Lemma mxrank_mul_ker m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : (\rank (A *m B) + \rank (A :&: kermx B))%N = \rank A. Proof. apply/eqP; set K := kermx B; set C := (A :&: K)%MS. rewrite -(eqmxMr B (eq_row_base A)); set K' := _ *m B. rewrite -{2}(subnKC (rank_leq_row K')) -mxrank_ker eqn_add2l. rewrite -(mxrankMfree _ (row_base_free A)) mxrank_leqif_sup. by rewrite sub_capmx -(eq_row_base A) submxMl sub_kermx -mulmxA mulmx_ker/=. have /submxP[C' defC]: (C <= row_base A)%MS by rewrite eq_row_base capmxSl. by rewrite defC submxMr // sub_kermx mulmxA -defC -sub_kermx capmxSr. Qed. Lemma mxrank_injP m n p (A : 'M_(m, n)) (f : 'M_(n, p)) : reflect (\rank (A *m f) = \rank A) ((A :&: kermx f)%MS == 0). Proof. rewrite -mxrank_eq0 -(eqn_add2l (\rank (A *m f))). by rewrite mxrank_mul_ker addn0 eq_sym; apply: eqP. Qed. Lemma mxrank_disjoint_sum m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B)%MS = 0 -> \rank (A + B)%MS = (\rank A + \rank B)%N. Proof. move=> AB0; pose Ar := row_base A; pose Br := row_base B. have [Afree Bfree]: row_free Ar /\ row_free Br by rewrite !row_base_free. have: (Ar :&: Br <= A :&: B)%MS by rewrite capmxS ?eq_row_base. rewrite {}AB0 submx0 -mxrank_eq0 capmxE mxrankMfree //. set Cr := col_mx Ar Br; set Crl := lsubmx _; rewrite mxrank_eq0 => /eqP Crl0. rewrite -(adds_eqmx (eq_row_base _) (eq_row_base _)) addsmxE -/Cr. suffices K0: kermx Cr = 0. by apply/eqP; rewrite eqn_leq rank_leq_row -subn_eq0 -mxrank_ker K0 mxrank0. move/eqP: (mulmx_ker Cr); rewrite -[kermx Cr]hsubmxK mul_row_col -/Crl Crl0. rewrite mul0mx add0r -mxrank_eq0 mxrankMfree // mxrank_eq0 => /eqP->. exact: row_mx0. Qed. Lemma diffmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :\: B :=: A :&: (capmx_gen A B)^C)%MS. Proof. by rewrite unlock; apply/eqmxP; rewrite !genmxE !capmxE andbb. Qed. Lemma genmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (<<A :\: B>> = A :\: B)%MS. Proof. by rewrite [@diffmx]unlock genmx_id. Qed. Lemma diffmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :\: B <= A)%MS. Proof. by rewrite diffmxE capmxSl. Qed. Lemma capmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : ((A :\: B) :&: B)%MS = 0. Proof. apply/eqP; pose C := capmx_gen A B; rewrite -submx0 -(capmx_compl C). by rewrite sub_capmx -capmxE sub_capmx andbAC -sub_capmx -diffmxE -sub_capmx. Qed. Lemma addsmx_diff_cap_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :\: B + A :&: B :=: A)%MS. Proof. apply/eqmxP; rewrite addsmx_sub capmxSl diffmxSl /=. set C := (A :\: B)%MS; set D := capmx_gen A B. suffices sACD: (A <= C + D)%MS. by rewrite (submx_trans sACD) ?addsmxS ?capmxE. have:= addsmx_compl_full D; rewrite /row_full addsmxE. case/row_fullP=> U /(congr1 (mulmx A)); rewrite mulmx1. rewrite -[U]hsubmxK mul_row_col mulmxDr addrC 2!mulmxA. set V := _ *m _ => defA; rewrite -defA; move/(canRL (addrK _)): defA => defV. suffices /submxP[W ->]: (V <= C)%MS by rewrite -mul_row_col addsmxE submxMl. rewrite diffmxE sub_capmx {1}defV -mulNmx addmx_sub 1?mulmx_sub //. by rewrite -capmxE capmxSl. Qed. Lemma mxrank_cap_compl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (\rank (A :&: B) + \rank (A :\: B))%N = \rank A. Proof. rewrite addnC -mxrank_disjoint_sum ?addsmx_diff_cap_eq //. by rewrite (capmxC A) capmxA capmx_diff cap0mx. Qed. Lemma mxrank_sum_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (\rank (A + B) + \rank (A :&: B) = \rank A + \rank B)%N. Proof. set C := (A :&: B)%MS; set D := (A :\: B)%MS. have rDB: \rank (A + B)%MS = \rank (D + B)%MS. apply/eqP; rewrite mxrank_leqif_sup; first by rewrite addsmxS ?diffmxSl. by rewrite addsmx_sub addsmxSr -(addsmx_diff_cap_eq A B) addsmxS ?capmxSr. rewrite {1}rDB mxrank_disjoint_sum ?capmx_diff //. by rewrite addnC addnA mxrank_cap_compl. Qed. Lemma mxrank_adds_leqif m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : \rank (A + B) <= \rank A + \rank B ?= iff (A :&: B <= (0 : 'M_n))%MS. Proof. rewrite -mxrank_sum_cap; split; first exact: leq_addr. by rewrite addnC (@eqn_add2r _ 0) eq_sym mxrank_eq0 -submx0. Qed. (* rank of block matrices with 0s inside *) Lemma rank_col_mx0 m n p (A : 'M_(m, n)) : \rank (col_mx A (0 : 'M_(p, n))) = \rank A. Proof. by rewrite -addsmxE addsmx0. Qed. Lemma rank_col_0mx m n p (A : 'M_(m, n)) : \rank (col_mx (0 : 'M_(p, n)) A) = \rank A. Proof. by rewrite -addsmxE adds0mx. Qed. Lemma rank_row_mx0 m n p (A : 'M_(m, n)) : \rank (row_mx A (0 : 'M_(m, p))) = \rank A. Proof. by rewrite -mxrank_tr -[RHS]mxrank_tr tr_row_mx trmx0 rank_col_mx0. Qed. Lemma rank_row_0mx m n p (A : 'M_(m, n)) : \rank (row_mx (0 : 'M_(m, p)) A) = \rank A. Proof. by rewrite -mxrank_tr -[RHS]mxrank_tr tr_row_mx trmx0 rank_col_0mx. Qed. Lemma rank_diag_block_mx m n p q (A : 'M_(m, n)) (B : 'M_(p, q)) : \rank (block_mx A 0 0 B) = (\rank A + \rank B)%N. Proof. rewrite block_mxEv -addsmxE mxrank_disjoint_sum ?rank_row_mx0 ?rank_row_0mx//. apply/eqP/rowV0P => v; rewrite sub_capmx => /andP[/submxP[x ->]]. rewrite mul_mx_row mulmx0 => /submxP[y]; rewrite mul_mx_row mulmx0. by move=> /eq_row_mx[-> _]; rewrite row_mx0. Qed. (* Subspace projection matrix *) Lemma proj_mx_sub m n U V (W : 'M_(m, n)) : (W *m proj_mx U V <= U)%MS. Proof. by rewrite !mulmx_sub // -addsmxE addsmx0. Qed. Lemma proj_mx_compl_sub m n U V (W : 'M_(m, n)) : (W <= U + V -> W - W *m proj_mx U V <= V)%MS. Proof. rewrite addsmxE => sWUV; rewrite mulmxA -{1}(mulmxKpV sWUV) -mulmxBr. by rewrite mulmx_sub // opp_col_mx add_col_mx subrr subr0 -addsmxE adds0mx. Qed. Lemma proj_mx_id m n U V (W : 'M_(m, n)) : (U :&: V = 0)%MS -> (W <= U)%MS -> W *m proj_mx U V = W. Proof. move=> dxUV sWU; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV. rewrite sub_capmx addmx_sub ?eqmx_opp ?proj_mx_sub //= -eqmx_opp opprB. by rewrite proj_mx_compl_sub // (submx_trans sWU) ?addsmxSl. Qed. Lemma proj_mx_0 m n U V (W : 'M_(m, n)) : (U :&: V = 0)%MS -> (W <= V)%MS -> W *m proj_mx U V = 0. Proof. move=> dxUV sWV; apply/eqP; rewrite -submx0 -dxUV. rewrite sub_capmx proj_mx_sub /= -[_ *m _](subrK W) addmx_sub // -eqmx_opp. by rewrite opprB proj_mx_compl_sub // (submx_trans sWV) ?addsmxSr. Qed. Lemma add_proj_mx m n U V (W : 'M_(m, n)) : (U :&: V = 0)%MS -> (W <= U + V)%MS -> W *m proj_mx U V + W *m proj_mx V U = W. Proof. move=> dxUV sWUV; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV. rewrite -addrA sub_capmx {2}addrCA -!(opprB W). by rewrite !{1}addmx_sub ?proj_mx_sub ?eqmx_opp ?proj_mx_compl_sub // addsmxC. Qed. Lemma proj_mx_proj n (U V : 'M_n) : let P := proj_mx U V in (U :&: V = 0)%MS -> P *m P = P. Proof. by move=> P dxUV; rewrite -[P in P *m _]mul1mx proj_mx_id ?proj_mx_sub ?mul1mx. Qed. (* Completing a partially injective matrix to get a unit matrix. *) Lemma complete_unitmx m n (U : 'M_(m, n)) (f : 'M_n) : \rank (U *m f) = \rank U -> {g : 'M_n | g \in unitmx & U *m f = U *m g}. Proof. move=> injfU; pose V := <<U>>%MS; pose W := V *m f. pose g := proj_mx V (V^C)%MS *m f + cokermx V *m row_ebase W. have defW: V *m g = W. rewrite mulmxDr mulmxA proj_mx_id ?genmxE ?capmx_compl //. by rewrite mulmxA mulmx_coker mul0mx addr0. exists g; last first. have /submxP[u ->]: (U <= V)%MS by rewrite genmxE. by rewrite -!mulmxA defW. rewrite -row_full_unit -sub1mx; apply/submxP. have: (invmx (col_ebase W) *m W <= V *m g)%MS by rewrite defW submxMl. case/submxP=> v def_v; exists (invmx (row_ebase W) *m (v *m V + (V^C)%MS)). rewrite -mulmxA mulmxDl -mulmxA -def_v -{3}[W]mulmx_ebase -mulmxA. rewrite mulKmx ?col_ebase_unit // [_ *m g]mulmxDr mulmxA. rewrite (proj_mx_0 (capmx_compl _)) // mul0mx add0r 2!mulmxA. rewrite mulmxK ?row_ebase_unit // copid_mx_id ?rank_leq_row //. rewrite (eqmxMr _ (genmxE U)) injfU genmxE addrC -mulmxDl subrK. by rewrite mul1mx mulVmx ?row_ebase_unit. Qed. (* Two matrices with the same shape represent the same subspace *) (* iff they differ only by a change of basis. *) Lemma eqmxMunitP m n (U V : 'M_(m, n)) : reflect (exists2 P, P \in unitmx & U = P *m V) (U == V)%MS. Proof. apply: (iffP eqmxP) => [eqUV | [P Punit ->]]; last first. by apply/eqmxMfull; rewrite row_full_unit. have [D defU]: exists D, U = D *m V by apply/submxP; rewrite eqUV. have{eqUV} [Pt Pt_unit defUt]: {Pt | Pt \in unitmx & V^T *m D^T = V^T *m Pt}. by apply/complete_unitmx; rewrite -trmx_mul -defU !mxrank_tr eqUV. by exists Pt^T; last apply/trmx_inj; rewrite ?unitmx_tr // defU !trmx_mul trmxK. Qed. (* Mapping between two subspaces with the same dimension. *) Lemma eq_rank_unitmx m1 m2 n (U : 'M_(m1, n)) (V : 'M_(m2, n)) : \rank U = \rank V -> {f : 'M_n | f \in unitmx & V :=: U *m f}%MS. Proof. move=> eqrUV; pose f := invmx (row_ebase <<U>>%MS) *m row_ebase <<V>>%MS. have defUf: (<<U>> *m f :=: <<V>>)%MS. rewrite -[<<U>>%MS]mulmx_ebase mulmxA mulmxK ?row_ebase_unit // -mulmxA. rewrite genmxE eqrUV -genmxE -{3}[<<V>>%MS]mulmx_ebase -mulmxA. move: (pid_mx _ *m _) => W; apply/eqmxP. by rewrite !eqmxMfull ?andbb // row_full_unit col_ebase_unit. have{defUf} defV: (V :=: U *m f)%MS. by apply/eqmxP; rewrite -!(eqmxMr f (genmxE U)) !defUf !genmxE andbb. have injfU: \rank (U *m f) = \rank U by rewrite -defV eqrUV. by have [g injg defUg] := complete_unitmx injfU; exists g; rewrite -?defUg. Qed. (* maximal rank and full rank submatrices *) Section MaxRankSubMatrix. Variables (m n : nat) (A : 'M_(m, n)). Definition maxrankfun : 'I_m ^ \rank A := [arg max_(f > finfun (widen_ord (rank_leq_row A))) \rank (rowsub f A)]. Local Notation mxf := maxrankfun. Lemma maxrowsub_free : row_free (rowsub mxf A). Proof. rewrite /mxf; case: arg_maxnP => //= f _ fM; apply/negP => /negP rfA. have [i NriA] : exists i, ~~ (row i A <= rowsub f A)%MS. by apply/row_subPn; apply: contraNN rfA => /mxrankS; rewrite row_leq_rank. have [j rjfA] : exists j, (row (f j) A <= rowsub (f \o lift j) A)%MS. case/row_freePn: rfA => j. by rewrite row_rowsub row'Esub -mxsub_comp; exists j. pose g : 'I_m ^ \rank A := finfun [eta f with j |-> i]. suff: (rowsub f A < rowsub g A)%MS by rewrite ltmxErank andbC ltnNge fM. rewrite ltmxE; apply/andP; split; last first. apply: contra NriA; apply: submx_trans. by rewrite (eq_row_sub j)// row_rowsub ffunE/= eqxx. apply/row_subP => k; rewrite !row_rowsub. have [->|/negPf eq_kjF] := eqVneq k j; last first. by rewrite (eq_row_sub k)// row_rowsub ffunE/= eq_kjF. rewrite (submx_trans rjfA)// (submx_rowsub (lift j))// => l /=. by rewrite ffunE/= eq_sym (negPf (neq_lift _ _)). Qed. Lemma eq_maxrowsub : (rowsub mxf A :=: A)%MS. Proof. apply/eqmxP; rewrite -(eq_leqif (mxrank_leqif_eq _))//. exact: maxrowsub_free. apply/row_subP => i; apply/submxP; exists (delta_mx 0 (mxf i)). by rewrite -rowE; apply/rowP => j; rewrite !mxE. Qed. Lemma maxrankfun_inj : injective mxf. Proof. move=> i j eqAij; have /row_free_inj := maxrowsub_free. move=> /(_ 1) /(_ (delta_mx 0 i) (delta_mx 0 j)). rewrite -!rowE !row_rowsub eqAij => /(_ erefl) /matrixP /(_ 0 i) /eqP. by rewrite !mxE !eqxx/=; case: (i =P j); rewrite // oner_eq0. Qed. Variable (rkA : row_full A). Lemma maxrowsub_full : row_full (rowsub mxf A). Proof. by rewrite /row_full eq_maxrowsub. Qed. Hint Resolve maxrowsub_full : core. Definition fullrankfun : 'I_m ^ n := finfun (mxf \o cast_ord (esym (eqP rkA))). Local Notation frf := fullrankfun. Lemma fullrowsub_full : row_full (rowsub frf A). Proof. by rewrite mxsub_ffunl rowsub_comp rowsub_cast esymK row_full_castmx. Qed. Lemma fullrowsub_unit : rowsub frf A \in unitmx. Proof. by rewrite -row_full_unit fullrowsub_full. Qed. Lemma fullrowsub_free : row_free (rowsub frf A). Proof. by rewrite row_free_unit fullrowsub_unit. Qed. Lemma mxrank_fullrowsub : \rank (rowsub frf A) = n. Proof. exact/eqP/fullrowsub_full. Qed. Lemma eq_fullrowsub : (rowsub frf A :=: A)%MS. Proof. rewrite mxsub_ffunl rowsub_comp rowsub_cast esymK. exact: (eqmx_trans (eqmx_cast _ _) eq_maxrowsub). Qed. Lemma fullrankfun_inj : injective frf. Proof. by move=> i j; rewrite !ffunE => /maxrankfun_inj /(congr1 val)/= /val_inj. Qed. End MaxRankSubMatrix. Section SumExpr. (* This is the infrastructure to support the mxdirect predicate. We use a *) (* bespoke canonical structure to decompose a matrix expression into binary *) (* and n-ary products, using some of the "quote" technology. This lets us *) (* characterize direct sums as set sums whose rank is equal to the sum of the *) (* ranks of the individual terms. The mxsum_expr/proper_mxsum_expr structures *) (* below supply both the decomposition and the calculation of the rank sum. *) (* The mxsum_spec dependent predicate family expresses the consistency of *) (* these two decompositions. *) (* The main technical difficulty we need to overcome is the fact that *) (* the "catch-all" case of canonical structures has a priority lower than *) (* constant expansion. However, it is undesirable that local abbreviations *) (* be opaque for the direct-sum predicate, e.g., not be able to handle *) (* let S := (\sum_(i | P i) LargeExpression i)%MS in mxdirect S -> ...). *) (* As in "quote", we use the interleaving of constant expansion and *) (* canonical projection matching to achieve our goal: we use a "wrapper" type *) (* (indeed, the wrapped T type defined in ssrfun.v) with a self-inserting *) (* non-primitive constructor to gain finer control over the type and *) (* structure inference process. The innermost, primitive, constructor flags *) (* trivial sums; it is initially hidden by an eta-expansion, which has been *) (* made into a (default) canonical structure -- this lets type inference *) (* automatically insert this outer tag. *) (* In detail, we define three types *) (* mxsum_spec S r <-> There exists a finite list of matrices A1, ..., Ak *) (* such that S is the set sum of the Ai, and r is the sum *) (* of the ranks of the Ai, i.e., S = (A1 + ... + Ak)%MS *) (* and r = \rank A1 + ... + \rank Ak. Note that *) (* mxsum_spec is a recursive dependent predicate family *) (* whose elimination rewrites simultaneaously S, r and *) (* the height of S. *) (* proper_mxsum_expr n == The interface for proper sum expressions; this is *) (* a double-entry interface, keyed on both the matrix sum *) (* value and the rank sum. The matrix value is restricted *) (* to square matrices, as the "+"%MS operator always *) (* returns a square matrix. This interface has two *) (* canonical instances, for binary and n-ary sums. *) (* mxsum_expr m n == The interface for general sum expressions, comprising *) (* both proper sums and trivial sums consisting of a *) (* single matrix. The key values are WRAPPED as this lets *) (* us give priority to the "proper sum" interpretation *) (* (see below). To allow for trivial sums, the matrix key *) (* can have any dimension. The mxsum_expr interface has *) (* two canonical instances, for trivial and proper sums, *) (* keyed to the Wrap and wrap constructors, respectively. *) (* The projections for the two interfaces above are *) (* proper_mxsum_val, mxsum_val : these are respectively coercions to 'M_n *) (* and wrapped 'M_(m, n); thus, the matrix sum for an *) (* S : mxsum_expr m n can be written unwrap S. *) (* proper_mxsum_rank, mxsum_rank : projections to the nat and wrapped nat, *) (* respectively; the rank sum for S : mxsum_expr m n is *) (* thus written unwrap (mxsum_rank S). *) (* The mxdirect A predicate actually gets A in a phantom argument, which is *) (* used to infer an (implicit) S : mxsum_expr such that unwrap S = A; the *) (* actual definition is \rank (unwrap S) == unwrap (mxsum_rank S). *) (* Note that the inference of S is inherently ambiguous: ANY matrix can be *) (* viewed as a trivial sum, including one whose description is manifestly a *) (* proper sum. We use the wrapped type and the interaction between delta *) (* reduction and canonical structure inference to resolve this ambiguity in *) (* favor of proper sums, as follows: *) (* - The phantom type sets up a unification problem of the form *) (* unwrap (mxsum_val ?S) = A *) (* with unknown evar ?S : mxsum_expr m n. *) (* - As the constructor wrap is also a default Canonical instance for the *) (* wrapped type, so A is immediately replaced with unwrap (wrap A) and *) (* we get the residual unification problem *) (* mxsum_val ?S = wrap A *) (* - Now Coq tries to apply the proper sum Canonical instance, which has *) (* key projection wrap (proper_mxsum_val ?PS) where ?PS is a fresh evar *) (* (of type proper_mxsum_expr n). This can only succeed if m = n, and if *) (* a solution can be found to the recursive unification problem *) (* proper_mxsum_val ?PS = A *) (* This causes Coq to look for one of the two canonical constants for *) (* proper_mxsum_val (addsmx or bigop) at the head of A, delta-expanding *) (* A as needed, and then inferring recursively mxsum_expr structures for *) (* the last argument(s) of that constant. *) (* - If the above step fails then the wrap constant is expanded, revealing *) (* the primitive Wrap constructor; the unification problem now becomes *) (* mxsum_val ?S = Wrap A *) (* which fits perfectly the trivial sum canonical structure, whose key *) (* projection is Wrap ?B where ?B is a fresh evar. Thus the inference *) (* succeeds, and returns the trivial sum. *) (* Note that the rank projections also register canonical values, so that the *) (* same process can be used to infer a sum structure from the rank sum. In *) (* that case, however, there is no ambiguity and the inference can fail, *) (* because the rank sum for a trivial sum is not an arbitrary integer -- it *) (* must be of the form \rank ?B. It is nevertheless necessary to use the *) (* wrapped nat type for the rank sums, because in the non-trivial case the *) (* head constant of the nat expression is determined by the proper_mxsum_expr *) (* canonical structure, so the mxsum_expr structure must use a generic *) (* constant, namely wrap. *) Inductive mxsum_spec n : forall m, 'M[F]_(m, n) -> nat -> Prop := | TrivialMxsum m A : @mxsum_spec n m A (\rank A) | ProperMxsum m1 m2 T1 T2 r1 r2 of @mxsum_spec n m1 T1 r1 & @mxsum_spec n m2 T2 r2 : mxsum_spec (T1 + T2)%MS (r1 + r2)%N. Arguments mxsum_spec {n%_N m%_N} T%_MS r%_N. Structure mxsum_expr m n := Mxsum { mxsum_val :> wrapped 'M_(m, n); mxsum_rank : wrapped nat; _ : mxsum_spec (unwrap mxsum_val) (unwrap mxsum_rank) }. Canonical trivial_mxsum m n A := @Mxsum m n (Wrap A) (Wrap (\rank A)) (TrivialMxsum A). Structure proper_mxsum_expr n := ProperMxsumExpr { proper_mxsum_val :> 'M_n; proper_mxsum_rank : nat; _ : mxsum_spec proper_mxsum_val proper_mxsum_rank }. Definition proper_mxsumP n (S : proper_mxsum_expr n) := let: ProperMxsumExpr _ _ termS := S return mxsum_spec S (proper_mxsum_rank S) in termS. Canonical sum_mxsum n (S : proper_mxsum_expr n) := @Mxsum n n (wrap (S : 'M_n)) (wrap (proper_mxsum_rank S)) (proper_mxsumP S). Section Binary. Variable (m1 m2 n : nat) (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n). Fact binary_mxsum_proof : mxsum_spec (unwrap S1 + unwrap S2) (unwrap (mxsum_rank S1) + unwrap (mxsum_rank S2)). Proof. by case: S1 S2 => [A1 r1 A1P] [A2 r2 A2P]; right. Qed. Canonical binary_mxsum_expr := ProperMxsumExpr binary_mxsum_proof. End Binary. Section Nary. Context J (r : seq J) (P : pred J) n (S_ : J -> mxsum_expr n n). Fact nary_mxsum_proof : mxsum_spec (\sum_(j <- r | P j) unwrap (S_ j)) (\sum_(j <- r | P j) unwrap (mxsum_rank (S_ j))). Proof. elim/big_rec2: _ => [|j]; first by rewrite -(mxrank0 n n); left. by case: (S_ j); right. Qed. Canonical nary_mxsum_expr := ProperMxsumExpr nary_mxsum_proof. End Nary. Definition mxdirect_def m n T of phantom 'M_(m, n) (unwrap (mxsum_val T)) := \rank (unwrap T) == unwrap (mxsum_rank T). End SumExpr. Notation mxdirect A := (mxdirect_def (Phantom 'M_(_,_) A%MS)). Lemma mxdirectP n (S : proper_mxsum_expr n) : reflect (\rank S = proper_mxsum_rank S) (mxdirect S). Proof. exact: eqnP. Qed. Arguments mxdirectP {n S}. Lemma mxdirect_trivial m n A : mxdirect (unwrap (@trivial_mxsum m n A)). Proof. exact: eqxx. Qed. Lemma mxrank_sum_leqif m n (S : mxsum_expr m n) : \rank (unwrap S) <= unwrap (mxsum_rank S) ?= iff mxdirect (unwrap S). Proof. rewrite /mxdirect_def; case: S => [[A] [r] /= defAr]; split=> //=. elim: m A r / defAr => // m1 m2 A1 A2 r1 r2 _ leAr1 _ leAr2. by apply: leq_trans (leq_add leAr1 leAr2); rewrite mxrank_adds_leqif. Qed. Lemma mxdirectE m n (S : mxsum_expr m n) : mxdirect (unwrap S) = (\rank (unwrap S) == unwrap (mxsum_rank S)). Proof. by []. Qed. Lemma mxdirectEgeq m n (S : mxsum_expr m n) : mxdirect (unwrap S) = (\rank (unwrap S) >= unwrap (mxsum_rank S)). Proof. by rewrite (geq_leqif (mxrank_sum_leqif S)). Qed. Section BinaryDirect. Variables m1 m2 n : nat. Lemma mxdirect_addsE (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n) : mxdirect (unwrap S1 + unwrap S2) = [&& mxdirect (unwrap S1), mxdirect (unwrap S2) & unwrap S1 :&: unwrap S2 == 0]%MS. Proof. rewrite (@mxdirectE n) /=. have:= leqif_add (mxrank_sum_leqif S1) (mxrank_sum_leqif S2). move/(leqif_trans (mxrank_adds_leqif (unwrap S1) (unwrap S2)))=> ->. by rewrite andbC -andbA submx0. Qed. Lemma mxdirect_addsP (A : 'M_(m1, n)) (B : 'M_(m2, n)) : reflect (A :&: B = 0)%MS (mxdirect (A + B)). Proof. by rewrite mxdirect_addsE !mxdirect_trivial; apply: eqP. Qed. End BinaryDirect. Section NaryDirect. Variables (P : pred I) (n : nat). Let TIsum A_ i := (A_ i :&: (\sum_(j | P j && (j != i)) A_ j) = 0 :> 'M_n)%MS. Let mxdirect_sums_recP (S_ : I -> mxsum_expr n n) : reflect (forall i, P i -> mxdirect (unwrap (S_ i)) /\ TIsum (unwrap \o S_) i) (mxdirect (\sum_(i | P i) (unwrap (S_ i)))). Proof. rewrite /TIsum; apply: (iffP eqnP) => /= [dxS i Pi | dxS]. set Si' := (\sum_(j | _) unwrap (S_ j))%MS. have: mxdirect (unwrap (S_ i) + Si') by apply/eqnP; rewrite /= -!(bigD1 i). by rewrite mxdirect_addsE => /and3P[-> _ /eqP]. set Q := P; have [m] := ubnP #|Q|; have: Q \subset P by []. elim: m Q => // m IHm Q /subsetP-sQP. case: (pickP Q) => [i Qi | Q0]; last by rewrite !big_pred0 ?mxrank0. rewrite (cardD1x Qi) !((bigD1 i) Q) //=. move/IHm=> <- {IHm}/=; last by apply/subsetP=> j /andP[/sQP]. case: (dxS i (sQP i Qi)) => /eqnP=> <- TiQ_0; rewrite mxrank_disjoint_sum //. apply/eqP; rewrite -submx0 -{2}TiQ_0 capmxS //=. by apply/sumsmx_subP=> j /= /andP[Qj i'j]; rewrite (sumsmx_sup j) ?[P j]sQP. Qed. Lemma mxdirect_sumsP (A_ : I -> 'M_n) : reflect (forall i, P i -> A_ i :&: (\sum_(j | P j && (j != i)) A_ j) = 0)%MS (mxdirect (\sum_(i | P i) A_ i)). Proof. apply: (iffP (mxdirect_sums_recP _)) => dxA i /dxA; first by case. by rewrite mxdirect_trivial. Qed. Lemma mxdirect_sumsE (S_ : I -> mxsum_expr n n) (xunwrap := unwrap) : reflect (and (forall i, P i -> mxdirect (unwrap (S_ i))) (mxdirect (\sum_(i | P i) (xunwrap (S_ i))))) (mxdirect (\sum_(i | P i) (unwrap (S_ i)))). Proof. apply: (iffP (mxdirect_sums_recP _)) => [dxS | [dxS_ dxS] i Pi]. by do [split; last apply/mxdirect_sumsP] => i; case/dxS. by split; [apply: dxS_ | apply: mxdirect_sumsP Pi]. Qed. End NaryDirect. Section SubDaddsmx. Variables m m1 m2 n : nat. Variables (A : 'M[F]_(m, n)) (B1 : 'M[F]_(m1, n)) (B2 : 'M[F]_(m2, n)). Variant sub_daddsmx_spec : Prop := SubDaddsmxSpec A1 A2 of (A1 <= B1)%MS & (A2 <= B2)%MS & A = A1 + A2 & forall C1 C2, (C1 <= B1)%MS -> (C2 <= B2)%MS -> A = C1 + C2 -> C1 = A1 /\ C2 = A2. Lemma sub_daddsmx : (B1 :&: B2 = 0)%MS -> (A <= B1 + B2)%MS -> sub_daddsmx_spec. Proof. move=> dxB /sub_addsmxP[u defA]. exists (u.1 *m B1) (u.2 *m B2); rewrite ?submxMl // => C1 C2 sCB1 sCB2. move/(canLR (addrK _)) => defC1. suffices: (C2 - u.2 *m B2 <= B1 :&: B2)%MS. by rewrite dxB submx0 subr_eq0 -defC1 defA; move/eqP->; rewrite addrK. rewrite sub_capmx -opprB -{1}(canLR (addKr _) defA) -addrA defC1. by rewrite !(eqmx_opp, addmx_sub) ?submxMl. Qed. End SubDaddsmx. Section SubDsumsmx. Variables (P : pred I) (m n : nat) (A : 'M[F]_(m, n)) (B : I -> 'M[F]_n). Variant sub_dsumsmx_spec : Prop := SubDsumsmxSpec A_ of forall i, P i -> (A_ i <= B i)%MS & A = \sum_(i | P i) A_ i & forall C, (forall i, P i -> C i <= B i)%MS -> A = \sum_(i | P i) C i -> {in SimplPred P, C =1 A_}. Lemma sub_dsumsmx : mxdirect (\sum_(i | P i) B i) -> (A <= \sum_(i | P i) B i)%MS -> sub_dsumsmx_spec. Proof. move/mxdirect_sumsP=> dxB /sub_sumsmxP[u defA]. pose A_ i := u i *m B i. exists A_ => //= [i _ | C sCB defAC i Pi]; first exact: submxMl. apply/eqP; rewrite -subr_eq0 -submx0 -{dxB}(dxB i Pi) /=. rewrite sub_capmx addmx_sub ?eqmx_opp ?submxMl ?sCB //=. rewrite -(subrK A (C i)) -addrA -opprB addmx_sub ?eqmx_opp //. rewrite addrC defAC (bigD1 i) // addKr /= summx_sub // => j Pi'j. by rewrite (sumsmx_sup j) ?sCB //; case/andP: Pi'j. rewrite addrC defA (bigD1 i) // addKr /= summx_sub // => j Pi'j. by rewrite (sumsmx_sup j) ?submxMl. Qed. End SubDsumsmx. Section Eigenspace. Variables (n : nat) (g : 'M_n). Definition eigenspace a := kermx (g - a%:M). Definition eigenvalue : pred F := fun a => eigenspace a != 0. Lemma eigenspaceP a m (W : 'M_(m, n)) : reflect (W *m g = a *: W) (W <= eigenspace a)%MS. Proof. by rewrite sub_kermx mulmxBr subr_eq0 mul_mx_scalar; apply/eqP. Qed. Lemma eigenvalueP a : reflect (exists2 v : 'rV_n, v *m g = a *: v & v != 0) (eigenvalue a). Proof. by apply: (iffP (rowV0Pn _)) => [] [v]; move/eigenspaceP; exists v. Qed. Notation stablemx V f := (V%MS *m f%R <= V%MS)%MS. Lemma eigenvectorP {v : 'rV_n} : reflect (exists a, (v <= eigenspace a)%MS) (stablemx v g). Proof. by apply: (iffP (sub_rVP _ _)) => -[a] /eigenspaceP; exists a. Qed. Lemma mxdirect_sum_eigenspace (P : pred I) a_ : {in P &, injective a_} -> mxdirect (\sum_(i | P i) eigenspace (a_ i)). Proof. have [m] := ubnP #|P|; elim: m P => // m IHm P lePm inj_a. apply/mxdirect_sumsP=> i Pi; apply/eqP/rowV0P => v. rewrite sub_capmx => /andP[/eigenspaceP def_vg]. set Vi' := (\sum_(i | _) _)%MS => Vi'v. have dxVi': mxdirect Vi'. rewrite (cardD1x Pi) in lePm; apply: IHm => //. by apply: sub_in2 inj_a => j /andP[]. case/sub_dsumsmx: Vi'v => // u Vi'u def_v _. rewrite def_v big1 // => j Pi'j; apply/eqP. have nz_aij: a_ i - a_ j != 0. by case/andP: Pi'j => Pj ne_ji; rewrite subr_eq0 eq_sym (inj_in_eq inj_a). case: (sub_dsumsmx dxVi' (sub0mx 1 _)) => C _ _ uniqC. rewrite -(eqmx_eq0 (eqmx_scale _ nz_aij)). rewrite (uniqC (fun k => (a_ i - a_ k) *: u k)) => // [|k Pi'k|]. - by rewrite -(uniqC (fun _ => 0)) ?big1 // => k Pi'k; apply: sub0mx. - by rewrite scalemx_sub ?Vi'u. rewrite -{1}(subrr (v *m g)) {1}def_vg def_v scaler_sumr mulmx_suml -sumrB. by apply: eq_bigr => k /Vi'u/eigenspaceP->; rewrite scalerBl. Qed. End Eigenspace. End RowSpaceTheory. #[global] Hint Resolve submx_refl : core. Arguments submxP {F m1 m2 n A B}. Arguments eq_row_sub [F m n v A]. Arguments row_subP {F m1 m2 n A B}. Arguments rV_subP {F m1 m2 n A B}. Arguments row_subPn {F m1 m2 n A B}. Arguments sub_rVP {F n u v}. Arguments rV_eqP {F m1 m2 n A B}. Arguments rowV0Pn {F m n A}. Arguments rowV0P {F m n A}. Arguments eqmx0P {F m n A}. Arguments row_fullP {F m n A}. Arguments row_freeP {F m n A}. Arguments eqmxP {F m1 m2 n A B}. Arguments genmxP {F m1 m2 n A B}. Arguments addsmx_idPr {F m1 m2 n A B}. Arguments addsmx_idPl {F m1 m2 n A B}. Arguments sub_addsmxP {F m1 m2 m3 n A B C}. Arguments sumsmx_sup [F I] i0 [P m n A B_]. Arguments sumsmx_subP {F I P m n A_ B}. Arguments sub_sumsmxP {F I P m n A B_}. Arguments sub_kermxP {F p m n A B}. Arguments capmx_idPr {F n m1 m2 A B}. Arguments capmx_idPl {F n m1 m2 A B}. Arguments bigcapmx_inf [F I] i0 [P m n A_ B]. Arguments sub_bigcapmxP {F I P m n A B_}. Arguments mxrank_injP {F m n} p {A f}. Arguments mxdirectP {F n S}. Arguments mxdirect_addsP {F m1 m2 n A B}. Arguments mxdirect_sumsP {F I P n A_}. Arguments mxdirect_sumsE {F I P n S_}. Arguments eigenspaceP {F n g a m W}. Arguments eigenvalueP {F n g a}. Arguments submx_rowsub [F m1 m2 m3 n] h [f g A] _ : rename. Arguments eqmx_rowsub [F m1 m2 m3 n] h [f g A] _ : rename. Arguments mxrank {F m%_N n%_N} A%_MS. Arguments complmx {F m%_N n%_N} A%_MS. Arguments row_full {F m%_N n%_N} A%_MS. Arguments submx {F m1%_N m2%_N n%_N} A%_MS B%_MS : rename. Arguments ltmx {F m1%_N m2%_N n%_N} A%_MS B%_MS. Arguments eqmx {F m1%_N m2%_N n%_N} A%_MS B%_MS. Arguments addsmx {F m1%_N m2%_N n%_N} A%_MS B%_MS : rename. Arguments capmx {F m1%_N m2%_N n%_N} A%_MS B%_MS : rename. Arguments diffmx {F m1%_N m2%_N n%_N} A%_MS B%_MS : rename. Arguments genmx {F m%_N n%_N} A%_R : rename. Notation "\rank A" := (mxrank A) : nat_scope. Notation "<< A >>" := (genmx A) : matrix_set_scope. Notation "A ^C" := (complmx A) : matrix_set_scope. Notation "A <= B" := (submx A B) : matrix_set_scope. Notation "A < B" := (ltmx A B) : matrix_set_scope. Notation "A <= B <= C" := ((submx A B) && (submx B C)) : matrix_set_scope. Notation "A < B <= C" := (ltmx A B && submx B C) : matrix_set_scope. Notation "A <= B < C" := (submx A B && ltmx B C) : matrix_set_scope. Notation "A < B < C" := (ltmx A B && ltmx B C) : matrix_set_scope. Notation "A == B" := ((submx A B) && (submx B A)) : matrix_set_scope. Notation "A :=: B" := (eqmx A B) : matrix_set_scope. Notation "A + B" := (addsmx A B) : matrix_set_scope. Notation "A :&: B" := (capmx A B) : matrix_set_scope. Notation "A :\: B" := (diffmx A B) : matrix_set_scope. Notation mxdirect S := (mxdirect_def (Phantom 'M_(_,_) S%MS)). Notation "\sum_ ( i <- r | P ) B" := (\big[addsmx/0%R]_(i <- r | P%B) B%MS) : matrix_set_scope. Notation "\sum_ ( i <- r ) B" := (\big[addsmx/0%R]_(i <- r) B%MS) : matrix_set_scope. Notation "\sum_ ( m <= i < n | P ) B" := (\big[addsmx/0%R]_(m <= i < n | P%B) B%MS) : matrix_set_scope. Notation "\sum_ ( m <= i < n ) B" := (\big[addsmx/0%R]_(m <= i < n) B%MS) : matrix_set_scope. Notation "\sum_ ( i | P ) B" := (\big[addsmx/0%R]_(i | P%B) B%MS) : matrix_set_scope. Notation "\sum_ i B" := (\big[addsmx/0%R]_i B%MS) : matrix_set_scope. Notation "\sum_ ( i : t | P ) B" := (\big[addsmx/0%R]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope. Notation "\sum_ ( i : t ) B" := (\big[addsmx/0%R]_(i : t) B%MS) (only parsing) : matrix_set_scope. Notation "\sum_ ( i < n | P ) B" := (\big[addsmx/0%R]_(i < n | P%B) B%MS) : matrix_set_scope. Notation "\sum_ ( i < n ) B" := (\big[addsmx/0%R]_(i < n) B%MS) : matrix_set_scope. Notation "\sum_ ( i 'in' A | P ) B" := (\big[addsmx/0%R]_(i in A | P%B) B%MS) : matrix_set_scope. Notation "\sum_ ( i 'in' A ) B" := (\big[addsmx/0%R]_(i in A) B%MS) : matrix_set_scope. Notation "\bigcap_ ( i <- r | P ) B" := (\big[capmx/1%:M]_(i <- r | P%B) B%MS) : matrix_set_scope. Notation "\bigcap_ ( i <- r ) B" := (\big[capmx/1%:M]_(i <- r) B%MS) : matrix_set_scope. Notation "\bigcap_ ( m <= i < n | P ) B" := (\big[capmx/1%:M]_(m <= i < n | P%B) B%MS) : matrix_set_scope. Notation "\bigcap_ ( m <= i < n ) B" := (\big[capmx/1%:M]_(m <= i < n) B%MS) : matrix_set_scope. Notation "\bigcap_ ( i | P ) B" := (\big[capmx/1%:M]_(i | P%B) B%MS) : matrix_set_scope. Notation "\bigcap_ i B" := (\big[capmx/1%:M]_i B%MS) : matrix_set_scope. Notation "\bigcap_ ( i : t | P ) B" := (\big[capmx/1%:M]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope. Notation "\bigcap_ ( i : t ) B" := (\big[capmx/1%:M]_(i : t) B%MS) (only parsing) : matrix_set_scope. Notation "\bigcap_ ( i < n | P ) B" := (\big[capmx/1%:M]_(i < n | P%B) B%MS) : matrix_set_scope. Notation "\bigcap_ ( i < n ) B" := (\big[capmx/1%:M]_(i < n) B%MS) : matrix_set_scope. Notation "\bigcap_ ( i 'in' A | P ) B" := (\big[capmx/1%:M]_(i in A | P%B) B%MS) : matrix_set_scope. Notation "\bigcap_ ( i 'in' A ) B" := (\big[capmx/1%:M]_(i in A) B%MS) : matrix_set_scope. Section Stability. Variable (F : fieldType). Lemma eqmx_stable m m' n (V : 'M[F]_(m, n)) (V' : 'M[F]_(m', n)) (f : 'M[F]_n) : (V :=: V')%MS -> stablemx V f = stablemx V' f. Proof. by move=> eqVV'; rewrite (eqmxMr _ eqVV') eqVV'. Qed. Section FixedDim. Variables (m n : nat) (V W : 'M[F]_(m, n)) (f g : 'M[F]_n). Lemma stablemx_row_base : (stablemx (row_base V) f) = (stablemx V f). Proof. by apply: eqmx_stable; apply: eq_row_base. Qed. Lemma stablemx_full : row_full V -> stablemx V f. Proof. exact: submx_full. Qed. Lemma stablemxM : stablemx V f -> stablemx V g -> stablemx V (f *m g). Proof. by move=> f_stab /(submx_trans _)->//; rewrite mulmxA submxMr. Qed. Lemma stablemxD : stablemx V f -> stablemx V g -> stablemx V (f + g). Proof. by move=> f_stab g_stab; rewrite mulmxDr addmx_sub. Qed. Lemma stablemxN : stablemx V (- f) = stablemx V f. Proof. by rewrite mulmxN eqmx_opp. Qed. Lemma stablemxC x : stablemx V x%:M. Proof. by rewrite mul_mx_scalar scalemx_sub. Qed. Lemma stablemx0 : stablemx V 0. Proof. by rewrite mulmx0 sub0mx. Qed. Lemma stableDmx : stablemx V f -> stablemx W f -> stablemx (V + W)%MS f. Proof. by move=> fV fW; rewrite addsmxMr addsmxS. Qed. Lemma stableNmx : stablemx (- V) f = stablemx V f. Proof. by rewrite mulNmx !eqmx_opp. Qed. Lemma stable0mx : stablemx (0 : 'M_(m, n)) f. Proof. by rewrite mul0mx. Qed. End FixedDim. Lemma stableCmx (m n : nat) x (f : 'M[F]_(m, n)) : stablemx x%:M f. Proof. have [->|x_neq0] := eqVneq x 0; first by rewrite mul_scalar_mx scale0r sub0mx. by rewrite -![x%:M]scalemx1 eqmx_scale// submx_full// -sub1mx. Qed. Lemma stablemx_sums (n : nat) (I : finType) (V_ : I -> 'M[F]_n) (f : 'M_n) : (forall i, stablemx (V_ i) f) -> stablemx (\sum_i V_ i)%MS f. Proof. by move=> fV; rewrite sumsmxMr; apply/sumsmx_subP => i; rewrite (sumsmx_sup i). Qed. Lemma stablemx_unit (n : nat) (V f : 'M[F]_n) : V \in unitmx -> stablemx V f. Proof. by move=> Vunit; rewrite submx_full ?row_full_unit. Qed. Section Commutation. Variable (n : nat). Implicit Types (f g : 'M[F]_n). Lemma comm_mx_stable (f g : 'M[F]_n) : comm_mx f g -> stablemx f g. Proof. by move=> comm_fg; rewrite [_ *m _]comm_fg mulmx_sub. Qed. Lemma comm_mx_stable_ker (f g : 'M[F]_n) : comm_mx f g -> stablemx (kermx f) g. Proof. move=> comm_fg; apply/sub_kermxP. by rewrite -mulmxA -[g *m _]comm_fg mulmxA mulmx_ker mul0mx. Qed. Lemma comm_mx_stable_eigenspace (f g : 'M[F]_n) a : comm_mx f g -> stablemx (eigenspace f a) g. Proof. move=> cfg; rewrite comm_mx_stable_ker//. by apply/comm_mx_sym/comm_mxB => //; apply:comm_mx_scalar. Qed. End Commutation. End Stability. Section DirectSums. Variables (F : fieldType) (I : finType) (P : pred I). Lemma mxdirect_delta n f : {in P &, injective f} -> mxdirect (\sum_(i | P i) <<delta_mx 0 (f i) : 'rV[F]_n>>). Proof. pose fP := image f P => Uf; have UfP: uniq fP by apply/dinjectiveP. suffices /mxdirectP : mxdirect (\sum_i <<delta_mx 0 i : 'rV[F]_n>>). rewrite /= !(bigID [in fP] predT) -!big_uniq //= !big_map !big_enum. by move/mxdirectP; rewrite mxdirect_addsE => /andP[]. apply/mxdirectP=> /=; transitivity (mxrank (1%:M : 'M[F]_n)). apply/eqmx_rank; rewrite submx1 mx1_sum_delta summx_sub_sums // => i _. by rewrite -(mul_delta_mx (0 : 'I_1)) genmxE submxMl. rewrite mxrank1 -[LHS]card_ord -sum1_card. by apply/eq_bigr=> i _; rewrite /= mxrank_gen mxrank_delta. Qed. End DirectSums. Section CardGL. Variable F : finFieldType. Lemma card_GL n : n > 0 -> #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N. Proof. case: n => // n' _; set n := n'.+1; set p := #|F|. rewrite big_nat_rev big_add1 -bin2_sum expn_sum -big_split /=. pose fr m := [pred A : 'M[F]_(m, n) | \rank A == m]. set m := n; rewrite [in m.+1]/m; transitivity #|fr m|. by rewrite cardsT /= card_sub; apply: eq_card => A; rewrite -row_free_unit. have: m <= n by []; elim: m => [_ | m IHm /ltnW-le_mn]. rewrite (@eq_card1 _ (0 : 'M_(0, n))) ?big_geq //= => A. by rewrite flatmx0 !inE mxrank.unlock !eqxx. rewrite big_nat_recr // -{}IHm //= !subSS mulnBr muln1 -expnD subnKC //. rewrite -sum_nat_const /= -sum1_card -add1n. rewrite (partition_big dsubmx (fr m)) /= => [|A]; last first. rewrite !inE -{1}(vsubmxK A); move: {A}(_ A) (_ A) => Ad Au Afull. rewrite eqn_leq rank_leq_row -(leq_add2l (\rank Au)) -mxrank_sum_cap. rewrite {1 3}[@mxrank]lock addsmxE (eqnP Afull) -lock -addnA. by rewrite leq_add ?rank_leq_row ?leq_addr. apply: eq_bigr => A rAm; rewrite (reindex (col_mx^~ A)) /=; last first. exists usubmx => [v _ | vA]; first by rewrite col_mxKu. by case/andP=> _ /eqP <-; rewrite vsubmxK. transitivity #|~: [set v *m A | v in 'rV_m]|; last first. rewrite cardsCs setCK card_imset ?card_mx ?card_ord ?mul1n //. have [B AB1] := row_freeP rAm; apply: can_inj (mulmx^~ B) _ => v. by rewrite -mulmxA AB1 mulmx1. rewrite -sum1_card; apply: eq_bigl => v; rewrite !inE col_mxKd eqxx. rewrite andbT eqn_leq rank_leq_row /= -(leq_add2r (\rank (v :&: A)%MS)). rewrite -addsmxE mxrank_sum_cap (eqnP rAm) addnAC leq_add2r. rewrite (ltn_leqif (mxrank_leqif_sup _)) ?capmxSl // sub_capmx submx_refl. by congr (~~ _); apply/submxP/imsetP=> [] [u]; exists u. Qed. (* An alternate, somewhat more elementary proof, that does not rely on the *) (* row-space theory, but directly performs the LUP decomposition. *) Lemma LUP_card_GL n : n > 0 -> #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N. Proof. case: n => // n' _; set n := n'.+1; set p := #|F|. rewrite cardsT /= card_sub /GRing.unit /= big_add1 /= -bin2_sum -/n /=. elim: {n'}n => [|n IHn]. rewrite !big_geq // mul1n (@eq_card _ _ predT) ?card_mx //= => M. by rewrite {1}[M]flatmx0 -(flatmx0 1%:M) unitmx1. rewrite !big_nat_recr //= expnD mulnAC mulnA -{}IHn -mulnA mulnC. set LHS := #|_|; rewrite -[n.+1]muln1 -{2}[n]mul1n {}/LHS. rewrite -!card_mx subn1 -(cardC1 0) -mulnA; set nzC := predC1 _. rewrite -sum1_card (partition_big lsubmx nzC) => [|A]; last first. rewrite unitmxE unitfE; apply: contra; move/eqP=> v0. rewrite -[A]hsubmxK v0 -[n.+1]/(1 + n)%N -col_mx0. rewrite -[rsubmx _]vsubmxK -det_tr tr_row_mx !tr_col_mx !trmx0. by rewrite det_lblock [0]mx11_scalar det_scalar1 mxE mul0r. rewrite -sum_nat_const; apply: eq_bigr => /= v /cV0Pn[k nza]. have xrkK: involutive (@xrow F _ _ 0 k). by move=> m A /=; rewrite /xrow -row_permM tperm2 row_perm1. rewrite (reindex_inj (inv_inj (xrkK (1 + n)%N))) /= -[n.+1]/(1 + n)%N. rewrite (partition_big ursubmx xpredT) //= -sum_nat_const. apply: eq_bigr => u _; set a : F := v _ _ in nza. set v1 : 'cV_(1 + n) := xrow 0 k v. have def_a: usubmx v1 = a%:M. by rewrite [_ v1]mx11_scalar mxE lshift0 mxE tpermL. pose Schur := dsubmx v1 *m (a^-1 *: u). pose L : 'M_(1 + n) := block_mx a%:M 0 (dsubmx v1) 1%:M. pose U B : 'M_(1 + n) := block_mx 1 (a^-1 *: u) 0 B. rewrite (reindex (fun B => L *m U B)); last first. exists (fun A1 => drsubmx A1 - Schur) => [B _ | A1]. by rewrite mulmx_block block_mxKdr mul1mx addrC addKr. rewrite !inE mulmx_block !mulmx0 mul0mx !mulmx1 !addr0 mul1mx addrC subrK. rewrite mul_scalar_mx scalerA divff // scale1r andbC; case/and3P => /eqP <- _. rewrite -{1}(hsubmxK A1) xrowE mul_mx_row row_mxKl -xrowE => /eqP def_v. rewrite -def_a block_mxEh vsubmxK /v1 -def_v xrkK. apply: trmx_inj; rewrite tr_row_mx tr_col_mx trmx_ursub trmx_drsub trmx_lsub. by rewrite hsubmxK vsubmxK. rewrite -sum1_card; apply: eq_bigl => B; rewrite xrowE unitmxE. rewrite !det_mulmx unitrM -unitmxE unitmx_perm det_lblock det_ublock. rewrite !det_scalar1 det1 mulr1 mul1r unitrM unitfE nza -unitmxE. rewrite mulmx_block !mulmx0 mul0mx !addr0 !mulmx1 mul1mx block_mxKur. rewrite mul_scalar_mx scalerA divff // scale1r eqxx andbT. by rewrite block_mxEh mul_mx_row row_mxKl -def_a vsubmxK -xrowE xrkK eqxx andbT. Qed. Lemma card_GL_1 : #|'GL_1[F]| = #|F|.-1. Proof. by rewrite card_GL // mul1n big_nat1 expn1 subn1. Qed. Lemma card_GL_2 : #|'GL_2[F]| = (#|F| * #|F|.-1 ^ 2 * #|F|.+1)%N. Proof. rewrite card_GL // big_ltn // big_nat1 expn1 -(addn1 #|F|) -subn1 -!mulnA. by rewrite -subn_sqr. Qed. End CardGL. Lemma logn_card_GL_p n p : prime p -> logn p #|'GL_n(p)| = 'C(n, 2). Proof. move=> p_pr; have p_gt1 := prime_gt1 p_pr. have p_i_gt0: p ^ _ > 0 by move=> i; rewrite expn_gt0 ltnW. have <- : #|'GL_n.-1.+1(p)| = #|'GL_n(p)| by []. rewrite (card_GL _ (ltn0Sn n.-1)) card_ord Fp_cast // big_add1 /=. pose p'gt0 m := m > 0 /\ logn p m = 0. suffices [Pgt0 p'P]: p'gt0 (\prod_(0 <= i < n.-1.+1) (p ^ i.+1 - 1))%N. by rewrite lognM // p'P pfactorK // addn0; case n. apply: big_ind => [|m1 m2 [m10 p'm1] [m20]|i _]; rewrite {}/p'gt0 ?logn1 //. by rewrite muln_gt0 m10 lognM ?p'm1. rewrite lognE -if_neg subn_gt0 p_pr /= -{1 2}(exp1n i.+1) ltn_exp2r // p_gt1. by rewrite dvdn_subr ?dvdn_exp // gtnNdvd. Qed. Section MatrixAlgebra. Variables F : fieldType. Local Notation "A \in R" := (@submx F _ _ _ (mxvec A) R). Lemma mem0mx m n (R : 'A_(m, n)) : 0 \in R. Proof. by rewrite linear0 sub0mx. Qed. Lemma memmx0 n A : (A \in (0 : 'A_n)) -> A = 0. Proof. by rewrite submx0 mxvec_eq0; move/eqP. Qed. Lemma memmx1 n (A : 'M_n) : (A \in mxvec 1%:M) = is_scalar_mx A. Proof. apply/sub_rVP/is_scalar_mxP=> [[a] | [a ->]]. by rewrite -linearZ scale_scalar_mx mulr1 => /(can_inj mxvecK); exists a. by exists a; rewrite -linearZ scale_scalar_mx mulr1. Qed. Lemma memmx_subP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) : reflect (forall A, A \in R1 -> A \in R2) (R1 <= R2)%MS. Proof. apply: (iffP idP) => [sR12 A R1_A | sR12]; first exact: submx_trans sR12. by apply/rV_subP=> vA; rewrite -(vec_mxK vA); apply: sR12. Qed. Arguments memmx_subP {m1 m2 n R1 R2}. Lemma memmx_eqP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) : reflect (forall A, (A \in R1) = (A \in R2)) (R1 == R2)%MS. Proof. apply: (iffP eqmxP) => [eqR12 A | eqR12]; first by rewrite eqR12. by apply/eqmxP/rV_eqP=> vA; rewrite -(vec_mxK vA) eqR12. Qed. Arguments memmx_eqP {m1 m2 n R1 R2}. Lemma memmx_addsP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) : reflect (exists D, [/\ D.1 \in R1, D.2 \in R2 & A = D.1 + D.2]) (A \in R1 + R2)%MS. Proof. apply: (iffP sub_addsmxP) => [[u /(canRL mxvecK)->] | [D []]]. exists (vec_mx (u.1 *m R1), vec_mx (u.2 *m R2)). by rewrite /= linearD !vec_mxK !submxMl. case/submxP=> u1 defD1 /submxP[u2 defD2] ->. by exists (u1, u2); rewrite linearD /= defD1 defD2. Qed. Arguments memmx_addsP {m1 m2 n A R1 R2}. Lemma memmx_sumsP (I : finType) (P : pred I) n (A : 'M_n) R_ : reflect (exists2 A_, A = \sum_(i | P i) A_ i & forall i, A_ i \in R_ i) (A \in \sum_(i | P i) R_ i)%MS. Proof. apply: (iffP sub_sumsmxP) => [[C defA] | [A_ -> R_A] {A}]. exists (fun i => vec_mx (C i *m R_ i)) => [|i]. by rewrite -linear_sum -defA /= mxvecK. by rewrite vec_mxK submxMl. exists (fun i => mxvec (A_ i) *m pinvmx (R_ i)). by rewrite linear_sum; apply: eq_bigr => i _; rewrite mulmxKpV. Qed. Arguments memmx_sumsP {I P n A R_}. Lemma has_non_scalar_mxP m n (R : 'A_(m, n)) : (1%:M \in R)%MS -> reflect (exists2 A, A \in R & ~~ is_scalar_mx A)%MS (1 < \rank R). Proof. case: (posnP n) => [-> | n_gt0] in R *; set S := mxvec _ => sSR. by rewrite [R]thinmx0 mxrank0; right; case; rewrite /is_scalar_mx ?insubF. have rankS: \rank S = 1%N. apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0 mxvec_eq0. by rewrite -mxrank_eq0 mxrank1 -lt0n. rewrite -{2}rankS (ltn_leqif (mxrank_leqif_sup sSR)). apply: (iffP idP) => [/row_subPn[i] | [A sAR]]. rewrite -[row i R]vec_mxK memmx1; set A := vec_mx _ => nsA. by exists A; rewrite // vec_mxK row_sub. by rewrite -memmx1; apply/contra/submx_trans. Qed. Definition mulsmx m1 m2 n (R1 : 'A[F]_(m1, n)) (R2 : 'A_(m2, n)) := (\sum_i <<R1 *m lin_mx (mulmxr (vec_mx (row i R2)))>>)%MS. Arguments mulsmx {m1%_N m2%_N n%_N} R1%_MS R2%_MS. Local Notation "R1 * R2" := (mulsmx R1 R2) : matrix_set_scope. Lemma genmx_muls m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) : <<(R1 * R2)%MS>>%MS = (R1 * R2)%MS. Proof. by rewrite genmx_sums; apply: eq_bigr => i; rewrite genmx_id. Qed. Lemma mem_mulsmx m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) A1 A2 : (A1 \in R1 -> A2 \in R2 -> A1 *m A2 \in R1 * R2)%MS. Proof. move=> R_A1 R_A2; rewrite -[A2]mxvecK; case/submxP: R_A2 => a ->{A2}. rewrite mulmx_sum_row !linear_sum summx_sub // => i _. rewrite 3!linearZ scalemx_sub {a}//= (sumsmx_sup i) // genmxE. rewrite -[A1]mxvecK; case/submxP: R_A1 => a ->{A1}. by apply/submxP; exists a; rewrite mulmxA mul_rV_lin. Qed. Lemma mulsmx_subP m1 m2 m n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R : 'A_(m, n)) : reflect (forall A1 A2, A1 \in R1 -> A2 \in R2 -> A1 *m A2 \in R) (R1 * R2 <= R)%MS. Proof. apply: (iffP memmx_subP) => [sR12R A1 A2 R_A1 R_A2 | sR12R A]. by rewrite sR12R ?mem_mulsmx. case/memmx_sumsP=> A_ -> R_A; rewrite linear_sum summx_sub //= => j _. rewrite (submx_trans (R_A _)) // genmxE; apply/row_subP=> i. by rewrite row_mul mul_rV_lin sR12R ?vec_mxK ?row_sub. Qed. Arguments mulsmx_subP {m1 m2 m n R1 R2 R}. Lemma mulsmxS m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) : (R1 <= R3 -> R2 <= R4 -> R1 * R2 <= R3 * R4)%MS. Proof. move=> sR13 sR24; apply/mulsmx_subP=> A1 A2 R_A1 R_A2. by apply: mem_mulsmx; [apply: submx_trans sR13 | apply: submx_trans sR24]. Qed. Lemma muls_eqmx m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) : (R1 :=: R3 -> R2 :=: R4 -> R1 * R2 = R3 * R4)%MS. Proof. move=> eqR13 eqR24; rewrite -(genmx_muls R1 R2) -(genmx_muls R3 R4). by apply/genmxP; rewrite !mulsmxS ?eqR13 ?eqR24. Qed. Lemma mulsmxP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) : reflect (exists2 A1, forall i, A1 i \in R1 & exists2 A2, forall i, A2 i \in R2 & A = \sum_(i < n ^ 2) A1 i *m A2 i) (A \in R1 * R2)%MS. Proof. apply: (iffP idP) => [R_A|[A1 R_A1 [A2 R_A2 ->{A}]]]; last first. by rewrite linear_sum summx_sub // => i _; rewrite mem_mulsmx. have{R_A}: (A \in R1 * <<R2>>)%MS. by apply: memmx_subP R_A; rewrite mulsmxS ?genmxE. case/memmx_sumsP=> A_ -> R_A; pose A2_ i := vec_mx (row i <<R2>>%MS). pose A1_ i := mxvec (A_ i) *m pinvmx (R1 *m lin_mx (mulmxr (A2_ i))) *m R1. exists (vec_mx \o A1_) => [i|]; first by rewrite vec_mxK submxMl. exists A2_ => [i|]; first by rewrite vec_mxK -(genmxE R2) row_sub. apply: eq_bigr => i _; rewrite -[_ *m _](mx_rV_lin (mulmxr (A2_ i))). by rewrite -mulmxA mulmxKpV ?mxvecK // -(genmxE (_ *m _)) R_A. Qed. Arguments mulsmxP {m1 m2 n A R1 R2}. Lemma mulsmxA m1 m2 m3 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) : (R1 * (R2 * R3) = R1 * R2 * R3)%MS. Proof. rewrite -(genmx_muls (_ * _)%MS) -genmx_muls; apply/genmxP/andP; split. apply/mulsmx_subP=> A1 A23 R_A1; case/mulsmxP=> A2 R_A2 [A3 R_A3 ->{A23}]. by rewrite !linear_sum summx_sub //= => i _; rewrite mulmxA !mem_mulsmx. apply/mulsmx_subP=> _ A3 /mulsmxP[A1 R_A1 [A2 R_A2 ->]] R_A3. rewrite mulmx_suml linear_sum summx_sub //= => i _. by rewrite -mulmxA !mem_mulsmx. Qed. Lemma mulsmxDl m1 m2 m3 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) : ((R1 + R2) * R3 = R1 * R3 + R2 * R3)%MS. Proof. rewrite -(genmx_muls R2 R3) -(genmx_muls R1 R3) -genmx_muls -genmx_adds. apply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=. apply/mulsmx_subP=> _ A3 /memmx_addsP[A [R_A1 R_A2 ->]] R_A3. by rewrite mulmxDl linearD addmx_sub_adds ?mem_mulsmx. Qed. Lemma mulsmxDr m1 m2 m3 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) : (R1 * (R2 + R3) = R1 * R2 + R1 * R3)%MS. Proof. rewrite -(genmx_muls R1 R3) -(genmx_muls R1 R2) -genmx_muls -genmx_adds. apply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=. apply/mulsmx_subP=> A1 _ R_A1 /memmx_addsP[A [R_A2 R_A3 ->]]. by rewrite mulmxDr linearD addmx_sub_adds ?mem_mulsmx. Qed. Lemma mulsmx0 m1 m2 n (R1 : 'A_(m1, n)) : (R1 * (0 : 'A_(m2, n)) = 0)%MS. Proof. apply/eqP; rewrite -submx0; apply/mulsmx_subP=> A1 A0 _. by rewrite [A0 \in 0]eqmx0 => /memmx0->; rewrite mulmx0 mem0mx. Qed. Lemma muls0mx m1 m2 n (R2 : 'A_(m2, n)) : ((0 : 'A_(m1, n)) * R2 = 0)%MS. Proof. apply/eqP; rewrite -submx0; apply/mulsmx_subP=> A0 A2. by rewrite [A0 \in 0]eqmx0 => /memmx0->; rewrite mul0mx mem0mx. Qed. Definition left_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) := (R1 * R2 <= R2)%MS. Definition right_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) := (R2 * R1 <= R2)%MS. Definition mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) := left_mx_ideal R1 R2 && right_mx_ideal R1 R2. Definition mxring_id m n (R : 'A_(m, n)) e := [/\ e != 0, e \in R, forall A, A \in R -> e *m A = A & forall A, A \in R -> A *m e = A]%MS. Definition has_mxring_id m n (R : 'A[F]_(m , n)) := (R != 0) && (row_mx 0 (row_mx (mxvec R) (mxvec R)) <= row_mx (cokermx R) (row_mx (lin_mx (mulmx R \o lin_mulmx)) (lin_mx (mulmx R \o lin_mulmxr))))%MS. Definition mxring m n (R : 'A_(m, n)) := left_mx_ideal R R && has_mxring_id R. Lemma mxring_idP m n (R : 'A_(m, n)) : reflect (exists e, mxring_id R e) (has_mxring_id R). Proof. apply: (iffP andP) => [[nzR] | [e [nz_e Re ideR idRe]]]. case/submxP=> v; rewrite -[v]vec_mxK; move/vec_mx: v => e. rewrite !mul_mx_row; case/eq_row_mx => /eqP. rewrite eq_sym -submxE => Re. case/eq_row_mx; rewrite !{1}mul_rV_lin1 /= mxvecK. set u := (_ *m _) => /(can_inj mxvecK) idRe /(can_inj mxvecK) ideR. exists e; split=> // [ | A /submxP[a defA] | A /submxP[a defA]]. - by apply: contra nzR; rewrite ideR => /eqP->; rewrite !linear0. - by rewrite -{2}[A]mxvecK defA idRe mulmxA mx_rV_lin -defA /= mxvecK. by rewrite -{2}[A]mxvecK defA ideR mulmxA mx_rV_lin -defA /= mxvecK. split. by apply: contraNneq nz_e => R0; rewrite R0 eqmx0 in Re; rewrite (memmx0 Re). apply/submxP; exists (mxvec e); rewrite !mul_mx_row !{1}mul_rV_lin1. rewrite submxE in Re; rewrite {Re}(eqP Re). congr (row_mx 0 (row_mx (mxvec _) (mxvec _))); apply/row_matrixP=> i. by rewrite !row_mul !mul_rV_lin1 /= mxvecK ideR vec_mxK ?row_sub. by rewrite !row_mul !mul_rV_lin1 /= mxvecK idRe vec_mxK ?row_sub. Qed. Arguments mxring_idP {m n R}. Section CentMxDef. Variables (m n : nat) (R : 'A[F]_(m, n)). Definition cent_mx_fun (B : 'M[F]_n) := R *m lin_mx (mulmxr B \- mulmx B). Lemma cent_mx_fun_is_linear : linear cent_mx_fun. Proof. move=> a A B; apply/row_matrixP=> i; rewrite linearP row_mul mul_rV_lin. rewrite /= [row i _ as v in a *: v]row_mul mul_rV_lin row_mul mul_rV_lin. by rewrite -linearP -(linearP (mulmx (vec_mx (row i R)) \- mulmxr _)). Qed. HB.instance Definition _ := GRing.isSemilinear.Build F 'M[F]_n 'M[F]_(m, n * n) _ cent_mx_fun (GRing.semilinear_linear cent_mx_fun_is_linear). Definition cent_mx := kermx (lin_mx cent_mx_fun). Definition center_mx := (R :&: cent_mx)%MS. End CentMxDef. Local Notation "''C' ( R )" := (cent_mx R) : matrix_set_scope. Local Notation "''Z' ( R )" := (center_mx R) : matrix_set_scope. Lemma cent_rowP m n B (R : 'A_(m, n)) : reflect (forall i (A := vec_mx (row i R)), A *m B = B *m A) (B \in 'C(R))%MS. Proof. apply: (iffP sub_kermxP); rewrite mul_vec_lin => cBE. move/(canRL mxvecK): cBE => cBE i A /=; move/(congr1 (row i)): cBE. rewrite row_mul mul_rV_lin -/A; move/(canRL mxvecK). by move/(canRL (subrK _)); rewrite !linear0 add0r. apply: (canLR vec_mxK); apply/row_matrixP=> i. by rewrite row_mul mul_rV_lin /= cBE subrr !linear0. Qed. Arguments cent_rowP {m n B R}. Lemma cent_mxP m n B (R : 'A_(m, n)) : reflect (forall A, A \in R -> A *m B = B *m A) (B \in 'C(R))%MS. Proof. apply: (iffP cent_rowP) => cEB => [A sAE | i A]. rewrite -[A]mxvecK -(mulmxKpV sAE); move: (mxvec A *m _) => u. rewrite !mulmx_sum_row !linear_sum mulmx_suml; apply: eq_bigr => i _ /=. by rewrite 2!linearZ -scalemxAl /= cEB. by rewrite cEB // vec_mxK row_sub. Qed. Arguments cent_mxP {m n B R}. Lemma scalar_mx_cent m n a (R : 'A_(m, n)) : (a%:M \in 'C(R))%MS. Proof. by apply/cent_mxP=> A _; apply: scalar_mxC. Qed. Lemma center_mx_sub m n (R : 'A_(m, n)) : ('Z(R) <= R)%MS. Proof. exact: capmxSl. Qed. Lemma center_mxP m n A (R : 'A_(m, n)) : reflect (A \in R /\ forall B, B \in R -> B *m A = A *m B) (A \in 'Z(R))%MS. Proof. rewrite sub_capmx; case R_A: (A \in R); last by right; case. by apply: (iffP cent_mxP) => [cAR | [_ cAR]]. Qed. Arguments center_mxP {m n A R}. Lemma mxring_id_uniq m n (R : 'A_(m, n)) e1 e2 : mxring_id R e1 -> mxring_id R e2 -> e1 = e2. Proof. by case=> [_ Re1 idRe1 _] [_ Re2 _ ide2R]; rewrite -(idRe1 _ Re2) ide2R. Qed. Lemma cent_mx_ideal m n (R : 'A_(m, n)) : left_mx_ideal 'C(R)%MS 'C(R)%MS. Proof. apply/mulsmx_subP=> A1 A2 C_A1 C_A2; apply/cent_mxP=> B R_B. by rewrite mulmxA (cent_mxP C_A1) // -!mulmxA (cent_mxP C_A2). Qed. Lemma cent_mx_ring m n (R : 'A_(m, n)) : n > 0 -> mxring 'C(R)%MS. Proof. move=> n_gt0; rewrite /mxring cent_mx_ideal; apply/mxring_idP. exists 1%:M; split=> [||A _|A _]; rewrite ?mulmx1 ?mul1mx ?scalar_mx_cent //. by rewrite -mxrank_eq0 mxrank1 -lt0n. Qed. Lemma mxdirect_adds_center m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) : mx_ideal (R1 + R2)%MS R1 -> mx_ideal (R1 + R2)%MS R2 -> mxdirect (R1 + R2) -> ('Z((R1 + R2)%MS) :=: 'Z(R1) + 'Z(R2))%MS. Proof. case/andP=> idlR1 idrR1 /andP[idlR2 idrR2] /mxdirect_addsP dxR12. apply/eqmxP/andP; split. apply/memmx_subP=> z0; rewrite sub_capmx => /andP[]. case/memmx_addsP=> z [R1z1 R2z2 ->{z0}] Cz. rewrite linearD addmx_sub_adds //= ?sub_capmx ?R1z1 ?R2z2 /=. apply/cent_mxP=> A R1_A; have R_A := submx_trans R1_A (addsmxSl R1 R2). have Rz2 := submx_trans R2z2 (addsmxSr R1 R2). rewrite -{1}[z.1](addrK z.2) mulmxBr (cent_mxP Cz) // mulmxDl. rewrite [A *m z.2]memmx0 1?[z.2 *m A]memmx0 ?addrK //. by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2). by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2). apply/cent_mxP=> A R2_A; have R_A := submx_trans R2_A (addsmxSr R1 R2). have Rz1 := submx_trans R1z1 (addsmxSl R1 R2). rewrite -{1}[z.2](addKr z.1) mulmxDr (cent_mxP Cz) // mulmxDl. rewrite mulmxN [A *m z.1]memmx0 1?[z.1 *m A]memmx0 ?addKr //. by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2). by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2). rewrite addsmx_sub; apply/andP; split. apply/memmx_subP=> z; rewrite sub_capmx => /andP[R1z cR1z]. have Rz := submx_trans R1z (addsmxSl R1 R2). rewrite sub_capmx Rz; apply/cent_mxP=> A0. case/memmx_addsP=> A [R1_A1 R2_A2] ->{A0}. have R_A2 := submx_trans R2_A2 (addsmxSr R1 R2). rewrite mulmxDl mulmxDr (cent_mxP cR1z) //; congr (_ + _). rewrite [A.2 *m z]memmx0 1?[z *m A.2]memmx0 //. by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2). by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2). apply/memmx_subP=> z; rewrite !sub_capmx => /andP[R2z cR2z]. have Rz := submx_trans R2z (addsmxSr R1 R2); rewrite Rz. apply/cent_mxP=> _ /memmx_addsP[A [R1_A1 R2_A2 ->]]. rewrite mulmxDl mulmxDr (cent_mxP cR2z _ R2_A2) //; congr (_ + _). have R_A1 := submx_trans R1_A1 (addsmxSl R1 R2). rewrite [A.1 *m z]memmx0 1?[z *m A.1]memmx0 //. by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2). by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2). Qed. Lemma mxdirect_sums_center (I : finType) m n (R : 'A_(m, n)) R_ : (\sum_i R_ i :=: R)%MS -> mxdirect (\sum_i R_ i) -> (forall i : I, mx_ideal R (R_ i)) -> ('Z(R) :=: \sum_i 'Z(R_ i))%MS. Proof. move=> defR dxR idealR. have sR_R: (R_ _ <= R)%MS by move=> i; rewrite -defR (sumsmx_sup i). have anhR i j A B : i != j -> A \in R_ i -> B \in R_ j -> A *m B = 0. move=> ne_ij RiA RjB; apply: memmx0. have [[_ idRiR] [idRRj _]] := (andP (idealR i), andP (idealR j)). rewrite -(mxdirect_sumsP dxR j) // sub_capmx (sumsmx_sup i) //. by rewrite (mulsmx_subP idRRj) // (memmx_subP (sR_R i)). by rewrite (mulsmx_subP idRiR) // (memmx_subP (sR_R j)). apply/eqmxP/andP; split. apply/memmx_subP=> Z; rewrite sub_capmx => /andP[]. rewrite -{1}defR => /memmx_sumsP[z ->{Z} Rz cRz]. apply/memmx_sumsP; exists z => // i; rewrite sub_capmx Rz. apply/cent_mxP=> A RiA; have:= cent_mxP cRz A (memmx_subP (sR_R i) A RiA). rewrite (bigD1 i) //= mulmxDl mulmxDr mulmx_suml mulmx_sumr. by rewrite !big1 ?addr0 // => j; last rewrite eq_sym; move/anhR->. apply/sumsmx_subP => i _; apply/memmx_subP=> z; rewrite sub_capmx. case/andP=> Riz cRiz; rewrite sub_capmx (memmx_subP (sR_R i)) //=. apply/cent_mxP=> A; rewrite -{1}defR; case/memmx_sumsP=> a -> R_a. rewrite (bigD1 i) // mulmxDl mulmxDr mulmx_suml mulmx_sumr. rewrite !big1 => [|j|j]; first by rewrite !addr0 (cent_mxP cRiz). by rewrite eq_sym => /anhR->. by move/anhR->. Qed. End MatrixAlgebra. Arguments mulsmx {F m1%_N m2%_N n%_N} R1%_MS R2%_MS. Arguments left_mx_ideal {F m1%_N m2%_N n%_N} R%_MS S%_MS : rename. Arguments right_mx_ideal {F m1%_N m2%_N n%_N} R%_MS S%_MS : rename. Arguments mx_ideal {F m1%_N m2%_N n%_N} R%_MS S%_MS : rename. Arguments mxring_id {F m%_N n%_N} R%_MS e%_R. Arguments has_mxring_id {F m%_N n%_N} R%_MS. Arguments mxring {F m%_N n%_N} R%_MS. Arguments cent_mx {F m%_N n%_N} R%_MS. Arguments center_mx {F m%_N n%_N} R%_MS. Notation "A \in R" := (submx (mxvec A) R) : matrix_set_scope. Notation "R * S" := (mulsmx R S) : matrix_set_scope. Notation "''C' ( R )" := (cent_mx R) : matrix_set_scope. Notation "''C_' R ( S )" := (R :&: 'C(S))%MS : matrix_set_scope. Notation "''C_' ( R ) ( S )" := ('C_R(S))%MS (only parsing) : matrix_set_scope. Notation "''Z' ( R )" := (center_mx R) : matrix_set_scope. Arguments memmx_subP {F m1 m2 n R1 R2}. Arguments memmx_eqP {F m1 m2 n R1 R2}. Arguments memmx_addsP {F m1 m2 n} A {R1 R2}. Arguments memmx_sumsP {F I P n A R_}. Arguments mulsmx_subP {F m1 m2 m n R1 R2 R}. Arguments mulsmxP {F m1 m2 n A R1 R2}. Arguments mxring_idP F {m n R}. Arguments cent_rowP {F m n B R}. Arguments cent_mxP {F m n B R}. Arguments center_mxP {F m n A R}. (* Parametricity for the row-space/F-algebra theory. *) Section MapMatrixSpaces. Variables (aF rF : fieldType) (f : {rmorphism aF -> rF}). Local Notation "A ^f" := (map_mx f A) : ring_scope. Lemma Gaussian_elimination_map m n (A : 'M_(m, n)) : Gaussian_elimination_ A^f = ((col_ebase A)^f, (row_ebase A)^f, \rank A). Proof. rewrite mxrankE /row_ebase /col_ebase unlock. elim: m n A => [|m IHm] [|n] A /=; rewrite ?map_mx1 //. set pAnz := [pred k | A k.1 k.2 != 0]. rewrite (@eq_pick _ _ pAnz) => [|k]; last by rewrite /= mxE fmorph_eq0. case: {+}(pick _) => [[i j]|]; last by rewrite !map_mx1. rewrite mxE -fmorphV -map_xcol -map_xrow -map_dlsubmx -map_drsubmx. rewrite -map_ursubmx -map_mxZ -map_mxM -map_mxB {}IHm /=. case: {+}(Gaussian_elimination_ _) => [[L U] r] /=; rewrite map_xrow map_xcol. by rewrite !(@map_block_mx _ _ f 1 _ 1) !map_mx0 ?map_mx1 ?map_scalar_mx. Qed. Lemma mxrank_map m n (A : 'M_(m, n)) : \rank A^f = \rank A. Proof. by rewrite mxrankE Gaussian_elimination_map. Qed. Lemma row_free_map m n (A : 'M_(m, n)) : row_free A^f = row_free A. Proof. by rewrite /row_free mxrank_map. Qed. Lemma row_full_map m n (A : 'M_(m, n)) : row_full A^f = row_full A. Proof. by rewrite /row_full mxrank_map. Qed. Lemma map_row_ebase m n (A : 'M_(m, n)) : (row_ebase A)^f = row_ebase A^f. Proof. by rewrite {2}/row_ebase unlock Gaussian_elimination_map. Qed. Lemma map_col_ebase m n (A : 'M_(m, n)) : (col_ebase A)^f = col_ebase A^f. Proof. by rewrite {2}/col_ebase unlock Gaussian_elimination_map. Qed. Lemma map_row_base m n (A : 'M_(m, n)) : (row_base A)^f = castmx (mxrank_map A, erefl n) (row_base A^f). Proof. move: (mxrank_map A); rewrite {2}/row_base mxrank_map => eqrr. by rewrite castmx_id map_mxM map_pid_mx map_row_ebase. Qed. Lemma map_col_base m n (A : 'M_(m, n)) : (col_base A)^f = castmx (erefl m, mxrank_map A) (col_base A^f). Proof. move: (mxrank_map A); rewrite {2}/col_base mxrank_map => eqrr. by rewrite castmx_id map_mxM map_pid_mx map_col_ebase. Qed. Lemma map_pinvmx m n (A : 'M_(m, n)) : (pinvmx A)^f = pinvmx A^f. Proof. rewrite !map_mxM !map_invmx map_row_ebase map_col_ebase. by rewrite map_pid_mx -mxrank_map. Qed. Lemma map_kermx m n (A : 'M_(m, n)) : (kermx A)^f = kermx A^f. Proof. by rewrite !map_mxM map_invmx map_col_ebase -mxrank_map map_copid_mx. Qed. Lemma map_cokermx m n (A : 'M_(m, n)) : (cokermx A)^f = cokermx A^f. Proof. by rewrite !map_mxM map_invmx map_row_ebase -mxrank_map map_copid_mx. Qed. Lemma map_submx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A^f <= B^f)%MS = (A <= B)%MS. Proof. by rewrite !submxE -map_cokermx -map_mxM map_mx_eq0. Qed. Lemma map_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A^f < B^f)%MS = (A < B)%MS. Proof. by rewrite /ltmx !map_submx. Qed. Lemma map_eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A^f :=: B^f)%MS <-> (A :=: B)%MS. Proof. split=> [/eqmxP|eqAB]; first by rewrite !map_submx => /eqmxP. by apply/eqmxP; rewrite !map_submx !eqAB !submx_refl. Qed. Lemma map_genmx m n (A : 'M_(m, n)) : (<<A>>^f :=: <<A^f>>)%MS. Proof. by apply/eqmxP; rewrite !(genmxE, map_submx) andbb. Qed. Lemma map_addsmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (((A + B)%MS)^f :=: A^f + B^f)%MS. Proof. by apply/eqmxP; rewrite !addsmxE -map_col_mx !map_submx !addsmxE andbb. Qed. Lemma map_capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (capmx_gen A B)^f = capmx_gen A^f B^f. Proof. by rewrite map_mxM map_lsubmx map_kermx map_col_mx. Qed. Lemma map_capmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : ((A :&: B)^f :=: A^f :&: B^f)%MS. Proof. by apply/eqmxP; rewrite !capmxE -map_capmx_gen !map_submx -!capmxE andbb. Qed. Lemma map_complmx m n (A : 'M_(m, n)) : (A^C^f = A^f^C)%MS. Proof. by rewrite map_mxM map_row_ebase -mxrank_map map_copid_mx. Qed. Lemma map_diffmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : ((A :\: B)^f :=: A^f :\: B^f)%MS. Proof. apply/eqmxP; rewrite !diffmxE -map_capmx_gen -map_complmx. by rewrite -!map_capmx !map_submx -!diffmxE andbb. Qed. Lemma map_eigenspace n (g : 'M_n) a : (eigenspace g a)^f = eigenspace g^f (f a). Proof. by rewrite map_kermx map_mxB ?map_scalar_mx. Qed. Lemma eigenvalue_map n (g : 'M_n) a : eigenvalue g^f (f a) = eigenvalue g a. Proof. by rewrite /eigenvalue -map_eigenspace map_mx_eq0. Qed. Lemma memmx_map m n A (E : 'A_(m, n)) : (A^f \in E^f)%MS = (A \in E)%MS. Proof. by rewrite -map_mxvec map_submx. Qed. Lemma map_mulsmx m1 m2 n (E1 : 'A_(m1, n)) (E2 : 'A_(m2, n)) : ((E1 * E2)%MS^f :=: E1^f * E2^f)%MS. Proof. rewrite /mulsmx; elim/big_rec2: _ => [|i A Af _ eqA]; first by rewrite map_mx0. apply: (eqmx_trans (map_addsmx _ _)); apply: adds_eqmx {A Af}eqA. apply/eqmxP; rewrite !map_genmx !genmxE map_mxM. apply/rV_eqP=> u; congr (u <= _ *m _)%MS. by apply: map_lin_mx => //= A; rewrite map_mxM // map_vec_mx map_row. Qed. Lemma map_cent_mx m n (E : 'A_(m, n)) : ('C(E)%MS)^f = 'C(E^f)%MS. Proof. rewrite map_kermx; congr kermx; apply: map_lin_mx => A; rewrite map_mxM. by congr (_ *m _); apply: map_lin_mx => B; rewrite map_mxB ?map_mxM. Qed. Lemma map_center_mx m n (E : 'A_(m, n)) : (('Z(E))^f :=: 'Z(E^f))%MS. Proof. by rewrite /center_mx -map_cent_mx; apply: map_capmx. Qed. End MapMatrixSpaces. Section RowColDiagBlockMatrix. Import tagnat. Context {F : fieldType} {n : nat} {p_ : 'I_n -> nat}. Lemma eqmx_col {m} (V_ : forall i, 'M[F]_(p_ i, m)) : (\mxcol_i V_ i :=: \sum_i <<V_ i>>)%MS. Proof. apply/eqmxP/andP; split. apply/row_subP => i; rewrite row_mxcol. by rewrite (sumsmx_sup (sig1 i))// genmxE row_sub. apply/sumsmx_subP => i0 _; rewrite genmxE; apply/row_subP => j. apply: (eq_row_sub (Rank _ j)); apply/rowP => k. by rewrite !mxE Rank2K; case: _ / esym; rewrite cast_ord_id. Qed. Lemma rank_mxdiag (V_ : forall i, 'M[F]_(p_ i)) : (\rank (\mxdiag_i V_ i) = \sum_i \rank (V_ i))%N. Proof. elim: {+}n {+}p_ V_ => [|m IHm] q_ V_. by move: (\mxdiag__ _); rewrite !big_ord0 => M; rewrite flatmx0 mxrank0. rewrite mxdiag_recl [RHS]big_ord_recl/= -IHm. by case: _ / mxsize_recl; rewrite ?castmx_id rank_diag_block_mx. Qed. End RowColDiagBlockMatrix.
poly.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice. From mathcomp Require Import fintype bigop finset tuple div ssralg. From mathcomp Require Import countalg binomial. (******************************************************************************) (* This file provides a library for univariate polynomials over ring *) (* structures; it also provides an extended theory for polynomials whose *) (* coefficients range over commutative rings and integral domains. *) (* *) (* {poly R} == the type of polynomials with coefficients of type R, *) (* represented as lists with a non zero last element *) (* (big endian representation); the coefficient type R *) (* must have a canonical nzRingType structure cR. In *) (* fact {poly R} denotes the concrete type polynomial *) (* cR; R is just a phantom argument that lets type *) (* inferencereconstruct the (hidden) nzRingType *) (* structure cR. *) (* p : seq R == the big-endian sequence of coefficients of p, via *) (* the coercion polyseq : polynomial >-> seq. *) (* Poly s == the polynomial with coefficient sequence s (ignoring *) (* trailing zeroes). *) (* \poly_(i < n) E(i) == the polynomial of degree at most n - 1 whose *) (* coefficients are given by the general term E(i) *) (* 0, 1, - p, p + q, == the usual ring operations: {poly R} has a canonical *) (* p * q, p ^+ n, ... nzRingType structure, which is commutative / integral*) (* when R is commutative / integral, respectively. *) (* polyC c, c%:P == the constant polynomial c *) (* 'X == the (unique) variable *) (* 'X^n == a power of 'X; 'X^0 is 1, 'X^1 is convertible to 'X *) (* p`_i == the coefficient of 'X^i in p; this is in fact just *) (* the ring_scope notation generic seq-indexing using *) (* nth 0%R, combined with the polyseq coercion. *) (* *** The multi-rule coefE simplifies p`_i *) (* coefp i == the linear function p |-> p`_i (self-exapanding). *) (* size p == 1 + the degree of p, or 0 if p = 0 (this is the *) (* generic seq function combined with polyseq). *) (* lead_coef p == the coefficient of the highest monomial in p, or 0 *) (* if p = 0 (hence lead_coef p = 0 iff p = 0) *) (* p \is monic <=> lead_coef p == 1 (0 is not monic). *) (* p \is a polyOver S <=> the coefficients of p satisfy S; S should have a *) (* key that should be (at least) an addrPred. *) (* p.[x] == the evaluation of a polynomial p at a point x using *) (* the Horner scheme *) (* *** The multi-rule hornerE (resp., hornerE_comm) unwinds *) (* horner evaluation of a polynomial expression (resp., *) (* in a non commutative ring, with side conditions). *) (* p^`() == formal derivative of p *) (* p^`(n) == formal n-derivative of p *) (* p^`N(n) == formal n-derivative of p divided by n! *) (* p \Po q == polynomial composition; because this is naturally a *) (* a linear morphism in the first argument, this *) (* notation is transposed (q comes before p for redex *) (* selection, etc). *) (* := \sum(i < size p) p`_i *: q ^+ i *) (* odd_poly p == monomials of odd degree of p *) (* even_poly p == monomials of even degree of p *) (* take_poly n p == polynomial p without its monomials of degree >= n *) (* drop_poly n p == polynomial p divided by X^n *) (* comm_poly p x == x and p.[x] commute; this is a sufficient condition *) (* for evaluating (q * p).[x] as q.[x] * p.[x] when R *) (* is not commutative. *) (* comm_coef p x == x commutes with all the coefficients of p (clearly, *) (* this implies comm_poly p x). *) (* root p x == x is a root of p, i.e., p.[x] = 0 *) (* n.-unity_root x == x is an nth root of unity, i.e., a root of 'X^n - 1 *) (* n.-primitive_root x == x is a primitive nth root of unity, i.e., n is the *) (* least positive integer m > 0 such that x ^+ m = 1. *) (* *** The submodule poly.UnityRootTheory can be used to *) (* import selectively the part of the theory of roots *) (* of unity that doesn't mention polynomials explicitly *) (* map_poly f p == the image of the polynomial by the function f (which *) (* (locally, p^f) is usually a ring morphism). *) (* p^:P == p lifted to {poly {poly R}} (:= map_poly polyC p). *) (* commr_rmorph f u == u commutes with the image of f (i.e., with all f x). *) (* horner_morph cfu == given cfu : commr_rmorph f u, the function mapping p *) (* to the value of map_poly f p at u; this is a ring *) (* morphism from {poly R} to the codomain of f when f *) (* is a ring morphism. *) (* horner_eval u == the function mapping p to p.[u]; this function can *) (* only be used for u in a commutative ring, so it is *) (* always a linear ring morphism from {poly R} to R. *) (* horner_alg a == given a in some R-algebra A, the function evaluating *) (* a polynomial p at a; it is always a linear ring *) (* morphism from {poly R} to A. *) (* diff_roots x y == x and y are distinct roots; if R is a field, this *) (* just means x != y, but this concept is generalized *) (* to the case where R is only a ring with units (i.e., *) (* a unitRingType); in which case it means that x and y *) (* commute, and that the difference x - y is a unit *) (* (i.e., has a multiplicative inverse) in R. *) (* to just x != y). *) (* uniq_roots s == s is a sequence or pairwise distinct roots, in the *) (* sense of diff_roots p above. *) (* *** We only show that these operations and properties are transferred by *) (* morphisms whose domain is a field (thus ensuring injectivity). *) (* We prove the factor_theorem, and the max_poly_roots inequality relating *) (* the number of distinct roots of a polynomial and its size. *) (* The some polynomial lemmas use following suffix interpretation : *) (* C - constant polynomial (as in polyseqC : a%:P = nseq (a != 0) a). *) (* X - the polynomial variable 'X (as in coefX : 'X`_i = (i == 1%N)). *) (* Xn - power of 'X (as in monicXn : monic 'X^n). *) (* *) (* Pdeg2.Field (exported by the present library) : theory of the degree 2 *) (* polynomials. *) (* Pdeg2.FieldMonic : theory of Pdeg2.Field specialized to monic polynomials. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope unity_root_scope. Import GRing.Theory. Local Open Scope ring_scope. Reserved Notation "{ 'poly' T }" (format "{ 'poly' T }"). Reserved Notation "c %:P" (format "c %:P"). Reserved Notation "p ^:P" (format "p ^:P"). Reserved Notation "'X". Reserved Notation "''X^' n" (at level 1, format "''X^' n"). Reserved Notation "\poly_ ( i < n ) E" (at level 34, E at level 36, i, n at level 50, format "\poly_ ( i < n ) E"). Reserved Notation "p \Po q" (at level 50). Reserved Notation "p ^`N ( n )" (format "p ^`N ( n )"). Reserved Notation "n .-unity_root" (format "n .-unity_root"). Reserved Notation "n .-primitive_root" (format "n .-primitive_root"). Local Notation simp := Monoid.simpm. Section Polynomial. Variable R : nzSemiRingType. (* Defines a polynomial as a sequence with <> 0 last element *) Record polynomial := Polynomial {polyseq :> seq R; _ : last 1 polyseq != 0}. HB.instance Definition _ := [isSub for polyseq]. HB.instance Definition _ := [Choice of polynomial by <:]. Lemma poly_inj : injective polyseq. Proof. exact: val_inj. Qed. Definition coefp i (p : polynomial) := p`_i. End Polynomial. (* We need to break off the section here to let the Bind Scope directives *) (* take effect. *) Bind Scope ring_scope with polynomial. Arguments polynomial R%_type. Arguments polyseq {R} p%_R. Arguments poly_inj {R} [p1%_R p2%_R] : rename. Arguments coefp {R} i%_N / p%_R. Notation "{ 'poly' T }" := (polynomial T) : type_scope. Section SemiPolynomialTheory. Variable R : nzSemiRingType. Implicit Types (a b c x y z : R) (p q r d : {poly R}). Definition lead_coef p := p`_(size p).-1. Lemma lead_coefE p : lead_coef p = p`_(size p).-1. Proof. by []. Qed. Definition poly_nil := @Polynomial R [::] (oner_neq0 R). Definition polyC c : {poly R} := insubd poly_nil [:: c]. Local Notation "c %:P" := (polyC c). (* Remember the boolean (c != 0) is coerced to 1 if true and 0 if false *) Lemma polyseqC c : c%:P = nseq (c != 0) c :> seq R. Proof. by rewrite val_insubd /=; case: (c == 0). Qed. Lemma size_polyC c : size c%:P = (c != 0). Proof. by rewrite polyseqC size_nseq. Qed. Lemma coefC c i : c%:P`_i = if i == 0 then c else 0. Proof. by rewrite polyseqC; case: i => [|[]]; case: eqP. Qed. Lemma polyCK : cancel polyC (coefp 0). Proof. by move=> c; rewrite [coefp 0 _]coefC. Qed. Lemma polyC_inj : injective polyC. Proof. by move=> c1 c2 eqc12; have:= coefC c2 0; rewrite -eqc12 coefC. Qed. Lemma lead_coefC c : lead_coef c%:P = c. Proof. by rewrite /lead_coef polyseqC; case: eqP. Qed. (* Extensional interpretation (poly <=> nat -> R) *) Lemma polyP p q : nth 0 p =1 nth 0 q <-> p = q. Proof. split=> [eq_pq | -> //]; apply: poly_inj. without loss lt_pq: p q eq_pq / size p < size q. move=> IH; case: (ltngtP (size p) (size q)); try by move/IH->. by move/(@eq_from_nth _ 0); apply. case: q => q nz_q /= in lt_pq eq_pq *; case/eqP: nz_q. by rewrite (last_nth 0) -(subnKC lt_pq) /= -eq_pq nth_default ?leq_addr. Qed. Lemma size1_polyC p : size p <= 1 -> p = (p`_0)%:P. Proof. move=> le_p_1; apply/polyP=> i; rewrite coefC. by case: i => // i; rewrite nth_default // (leq_trans le_p_1). Qed. (* Builds a polynomial by extension. *) Definition cons_poly c p : {poly R} := if p is Polynomial ((_ :: _) as s) ns then @Polynomial R (c :: s) ns else c%:P. Lemma polyseq_cons c p : cons_poly c p = (if ~~ nilp p then c :: p else c%:P) :> seq R. Proof. by case: p => [[]]. Qed. Lemma size_cons_poly c p : size (cons_poly c p) = (if nilp p && (c == 0) then 0 else (size p).+1). Proof. by case: p => [[|c' s] _] //=; rewrite size_polyC; case: eqP. Qed. Lemma coef_cons c p i : (cons_poly c p)`_i = if i == 0 then c else p`_i.-1. Proof. by case: p i => [[|c' s] _] [] //=; rewrite polyseqC; case: eqP => //= _ []. Qed. (* Build a polynomial directly from a list of coefficients. *) Definition Poly := foldr cons_poly 0%:P. Lemma PolyK c s : last c s != 0 -> Poly s = s :> seq R. Proof. case: s => {c}/= [_ |c s]; first by rewrite polyseqC eqxx. elim: s c => /= [|a s IHs] c nz_c; rewrite polyseq_cons ?{}IHs //. by rewrite !polyseqC !eqxx nz_c. Qed. Lemma polyseqK p : Poly p = p. Proof. by apply: poly_inj; apply: PolyK (valP p). Qed. Lemma size_Poly s : size (Poly s) <= size s. Proof. elim: s => [|c s IHs] /=; first by rewrite polyseqC eqxx. by rewrite polyseq_cons; case: ifP => // _; rewrite size_polyC; case: (~~ _). Qed. Lemma coef_Poly s i : (Poly s)`_i = s`_i. Proof. by elim: s i => [|c s IHs] /= [|i]; rewrite !(coefC, eqxx, coef_cons) /=. Qed. (* Build a polynomial from an infinite sequence of coefficients and a bound. *) Definition poly_expanded_def n E := Poly (mkseq E n). Fact poly_key : unit. Proof. by []. Qed. Definition poly := locked_with poly_key poly_expanded_def. Canonical poly_unlockable := [unlockable fun poly]. Local Notation "\poly_ ( i < n ) E" := (poly n (fun i : nat => E)). Lemma polyseq_poly n E : E n.-1 != 0 -> \poly_(i < n) E i = mkseq [eta E] n :> seq R. Proof. rewrite unlock; case: n => [|n] nzEn; first by rewrite polyseqC eqxx. by rewrite (@PolyK 0) // -nth_last nth_mkseq size_mkseq. Qed. Lemma size_poly n E : size (\poly_(i < n) E i) <= n. Proof. by rewrite unlock (leq_trans (size_Poly _)) ?size_mkseq. Qed. Lemma size_poly_eq n E : E n.-1 != 0 -> size (\poly_(i < n) E i) = n. Proof. by move/polyseq_poly->; apply: size_mkseq. Qed. Lemma coef_poly n E k : (\poly_(i < n) E i)`_k = (if k < n then E k else 0). Proof. rewrite unlock coef_Poly. have [lt_kn | le_nk] := ltnP k n; first by rewrite nth_mkseq. by rewrite nth_default // size_mkseq. Qed. Lemma lead_coef_poly n E : n > 0 -> E n.-1 != 0 -> lead_coef (\poly_(i < n) E i) = E n.-1. Proof. by case: n => // n _ nzE; rewrite /lead_coef size_poly_eq // coef_poly leqnn. Qed. Lemma coefK p : \poly_(i < size p) p`_i = p. Proof. by apply/polyP=> i; rewrite coef_poly; case: ltnP => // /(nth_default 0)->. Qed. (* Nmodule structure for polynomial *) Definition add_poly_def p q := \poly_(i < maxn (size p) (size q)) (p`_i + q`_i). Fact add_poly_key : unit. Proof. by []. Qed. Definition add_poly := locked_with add_poly_key add_poly_def. Canonical add_poly_unlockable := [unlockable fun add_poly]. Fact coef_add_poly p q i : (add_poly p q)`_i = p`_i + q`_i. Proof. rewrite unlock coef_poly; case: leqP => //. by rewrite geq_max => /andP[le_p_i le_q_i]; rewrite !nth_default ?add0r. Qed. Fact add_polyA : associative add_poly. Proof. by move=> p q r; apply/polyP=> i; rewrite !coef_add_poly addrA. Qed. Fact add_polyC : commutative add_poly. Proof. by move=> p q; apply/polyP=> i; rewrite !coef_add_poly addrC. Qed. Fact add_poly0 : left_id 0%:P add_poly. Proof. by move=> p; apply/polyP=> i; rewrite coef_add_poly coefC if_same add0r. Qed. HB.instance Definition _ := GRing.isNmodule.Build (polynomial R) add_polyA add_polyC add_poly0. (* Properties of the zero polynomial *) Lemma polyC0 : 0%:P = 0 :> {poly R}. Proof. by []. Qed. Lemma polyseq0 : (0 : {poly R}) = [::] :> seq R. Proof. by rewrite polyseqC eqxx. Qed. Lemma size_poly0 : size (0 : {poly R}) = 0%N. Proof. by rewrite polyseq0. Qed. Lemma coef0 i : (0 : {poly R})`_i = 0. Proof. by rewrite coefC if_same. Qed. Lemma lead_coef0 : lead_coef 0 = 0 :> R. Proof. exact: lead_coefC. Qed. Lemma size_poly_eq0 p : (size p == 0) = (p == 0). Proof. by rewrite size_eq0 -polyseq0. Qed. Lemma size_poly_leq0 p : (size p <= 0) = (p == 0). Proof. by rewrite leqn0 size_poly_eq0. Qed. Lemma size_poly_leq0P p : reflect (p = 0) (size p <= 0). Proof. by apply: (iffP idP); rewrite size_poly_leq0; move/eqP. Qed. Lemma size_poly_gt0 p : (0 < size p) = (p != 0). Proof. by rewrite lt0n size_poly_eq0. Qed. Lemma gt_size_poly_neq0 p n : (size p > n)%N -> p != 0. Proof. by move=> /(leq_ltn_trans _) h; rewrite -size_poly_eq0 lt0n_neq0 ?h. Qed. Lemma nil_poly p : nilp p = (p == 0). Proof. exact: size_poly_eq0. Qed. Lemma poly0Vpos p : {p = 0} + {size p > 0}. Proof. by rewrite lt0n size_poly_eq0; case: eqVneq; [left | right]. Qed. Lemma polySpred p : p != 0 -> size p = (size p).-1.+1. Proof. by rewrite -size_poly_eq0 -lt0n => /prednK. Qed. Lemma lead_coef_eq0 p : (lead_coef p == 0) = (p == 0). Proof. rewrite -nil_poly /lead_coef nth_last. by case: p => [[|x s] /= /negbTE // _]; rewrite eqxx. Qed. Lemma polyC_eq0 (c : R) : (c%:P == 0) = (c == 0). Proof. by rewrite -nil_poly polyseqC; case: (c == 0). Qed. Lemma size_poly1P p : reflect (exists2 c, c != 0 & p = c%:P) (size p == 1). Proof. apply: (iffP eqP) => [pC | [c nz_c ->]]; last by rewrite size_polyC nz_c. have def_p: p = (p`_0)%:P by rewrite -size1_polyC ?pC. by exists p`_0; rewrite // -polyC_eq0 -def_p -size_poly_eq0 pC. Qed. Lemma size_polyC_leq1 (c : R) : (size c%:P <= 1)%N. Proof. by rewrite size_polyC; case: (c == 0). Qed. Lemma leq_sizeP p i : reflect (forall j, i <= j -> p`_j = 0) (size p <= i). Proof. apply: (iffP idP) => [hp j hij| hp]. by apply: nth_default; apply: leq_trans hij. case: (eqVneq p) (lead_coef_eq0 p) => [->|p0]; first by rewrite size_poly0. rewrite leqNgt; apply/contraFN => hs. by apply/eqP/hp; rewrite -ltnS (ltn_predK hs). Qed. (* Size, leading coef, morphism properties of coef *) Lemma coefD p q i : (p + q)`_i = p`_i + q`_i. Proof. exact: coef_add_poly. Qed. Lemma polyCD : {morph polyC : a b / a + b}. Proof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefD !coefC ?addr0. Qed. Lemma size_polyD p q : size (p + q) <= maxn (size p) (size q). Proof. by rewrite -[+%R]/add_poly unlock; exact: size_poly. Qed. Lemma size_polyDl p q : size p > size q -> size (p + q) = size p. Proof. move=> ltqp; rewrite -[+%R]/add_poly unlock size_poly_eq (maxn_idPl (ltnW _))//. by rewrite addrC nth_default ?simp ?nth_last //; case: p ltqp => [[]]. Qed. Lemma size_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) : size (\sum_(i <- r | P i) F i) <= \max_(i <- r | P i) size (F i). Proof. elim/big_rec2: _ => [|i p q _ IHp]; first by rewrite size_poly0. by rewrite -(maxn_idPr IHp) maxnA leq_max size_polyD. Qed. Lemma lead_coefDl p q : size p > size q -> lead_coef (p + q) = lead_coef p. Proof. move=> ltqp; rewrite /lead_coef coefD size_polyDl //. by rewrite addrC nth_default ?simp // -ltnS (ltn_predK ltqp). Qed. Lemma lead_coefDr p q : size q > size p -> lead_coef (p + q) = lead_coef q. Proof. by move/lead_coefDl<-; rewrite addrC. Qed. (* Polynomial semiring structure. *) Definition mul_poly_def p q := \poly_(i < (size p + size q).-1) (\sum_(j < i.+1) p`_j * q`_(i - j)). Fact mul_poly_key : unit. Proof. by []. Qed. Definition mul_poly := locked_with mul_poly_key mul_poly_def. Canonical mul_poly_unlockable := [unlockable fun mul_poly]. Fact coef_mul_poly p q i : (mul_poly p q)`_i = \sum_(j < i.+1) p`_j * q`_(i - j)%N. Proof. rewrite unlock coef_poly -subn1 ltn_subRL add1n; case: leqP => // le_pq_i1. rewrite big1 // => j _; have [lq_q_ij | gt_q_ij] := leqP (size q) (i - j). by rewrite [q`__]nth_default ?mulr0. rewrite nth_default ?mul0r // -(leq_add2r (size q)) (leq_trans le_pq_i1) //. by rewrite -leq_subLR -subnSK. Qed. Fact coef_mul_poly_rev p q i : (mul_poly p q)`_i = \sum_(j < i.+1) p`_(i - j)%N * q`_j. Proof. rewrite coef_mul_poly (reindex_inj rev_ord_inj) /=. by apply: eq_bigr => j _; rewrite (sub_ordK j). Qed. Fact mul_polyA : associative mul_poly. Proof. move=> p q r; apply/polyP=> i; rewrite coef_mul_poly coef_mul_poly_rev. pose coef3 j k := p`_j * (q`_(i - j - k)%N * r`_k). transitivity (\sum_(j < i.+1) \sum_(k < i.+1 | k <= i - j) coef3 j k). apply: eq_bigr => /= j _; rewrite coef_mul_poly_rev big_distrr /=. by rewrite (big_ord_narrow_leq (leq_subr _ _)). rewrite (exchange_big_dep predT) //=; apply: eq_bigr => k _. transitivity (\sum_(j < i.+1 | j <= i - k) coef3 j k). apply: eq_bigl => j; rewrite -ltnS -(ltnS j) -!subSn ?leq_ord //. by rewrite -subn_gt0 -(subn_gt0 j) -!subnDA addnC. rewrite (big_ord_narrow_leq (leq_subr _ _)) coef_mul_poly big_distrl /=. by apply: eq_bigr => j _; rewrite /coef3 -!subnDA addnC mulrA. Qed. Fact mul_1poly : left_id 1%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Fact mul_poly1 : right_id 1%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly_rev big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Fact mul_polyDl : left_distributive mul_poly +%R. Proof. move=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split. by apply: eq_bigr => j _; rewrite coefD mulrDl. Qed. Fact mul_polyDr : right_distributive mul_poly +%R. Proof. move=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split. by apply: eq_bigr => j _; rewrite coefD mulrDr. Qed. Fact mul_0poly : left_zero 0%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp // coefC; case: ifP. Qed. Fact mul_poly0 : right_zero 0%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly_rev big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp // coefC; case: ifP. Qed. Fact poly1_neq0 : 1%:P != 0 :> {poly R}. Proof. by rewrite polyC_eq0 oner_neq0. Qed. HB.instance Definition _ := GRing.Nmodule_isNzSemiRing.Build (polynomial R) mul_polyA mul_1poly mul_poly1 mul_polyDl mul_polyDr mul_0poly mul_poly0 poly1_neq0. Lemma polyC1 : 1%:P = 1 :> {poly R}. Proof. by []. Qed. Lemma polyseq1 : (1 : {poly R}) = [:: 1] :> seq R. Proof. by rewrite polyseqC oner_neq0. Qed. Lemma size_poly1 : size (1 : {poly R}) = 1. Proof. by rewrite polyseq1. Qed. Lemma coef1 i : (1 : {poly R})`_i = (i == 0)%:R. Proof. by case: i => [|i]; rewrite polyseq1 /= ?nth_nil. Qed. Lemma lead_coef1 : lead_coef 1 = 1 :> R. Proof. exact: lead_coefC. Qed. Lemma coefM p q i : (p * q)`_i = \sum_(j < i.+1) p`_j * q`_(i - j)%N. Proof. exact: coef_mul_poly. Qed. Lemma coefMr p q i : (p * q)`_i = \sum_(j < i.+1) p`_(i - j)%N * q`_j. Proof. exact: coef_mul_poly_rev. Qed. Lemma coef0M p q : (p * q)`_0 = p`_0 * q`_0. Proof. by rewrite coefM big_ord1. Qed. Lemma coef0_prod I rI (F : I -> {poly R}) P : (\prod_(i <- rI| P i) F i)`_0 = \prod_(i <- rI | P i) (F i)`_0. Proof. by apply: (big_morph _ coef0M); rewrite coef1 eqxx. Qed. Lemma size_polyMleq p q : size (p * q) <= (size p + size q).-1. Proof. by rewrite -[*%R]/mul_poly unlock size_poly. Qed. Lemma mul_lead_coef p q : lead_coef p * lead_coef q = (p * q)`_(size p + size q).-2. Proof. pose dp := (size p).-1; pose dq := (size q).-1. have [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 !mul0r coef0. have [-> | nz_q] := eqVneq q 0; first by rewrite lead_coef0 !mulr0 coef0. have ->: (size p + size q).-2 = (dp + dq)%N. by do 2!rewrite polySpred // addSn addnC. have lt_p_pq: dp < (dp + dq).+1 by rewrite ltnS leq_addr. rewrite coefM (bigD1 (Ordinal lt_p_pq)) ?big1 ?simp ?addKn //= => i. rewrite -val_eqE neq_ltn /= => /orP[lt_i_p | gt_i_p]; last first. by rewrite nth_default ?mul0r //; rewrite -polySpred in gt_i_p. rewrite [q`__]nth_default ?mulr0 //= -subSS -{1}addnS -polySpred //. by rewrite addnC -addnBA ?leq_addr. Qed. Lemma size_proper_mul p q : lead_coef p * lead_coef q != 0 -> size (p * q) = (size p + size q).-1. Proof. apply: contraNeq; rewrite mul_lead_coef eqn_leq size_polyMleq -ltnNge => lt_pq. by rewrite nth_default // -subn1 -(leq_add2l 1) -leq_subLR leq_sub2r. Qed. Lemma lead_coef_proper_mul p q : let c := lead_coef p * lead_coef q in c != 0 -> lead_coef (p * q) = c. Proof. by move=> /= nz_c; rewrite mul_lead_coef -size_proper_mul. Qed. Lemma size_poly_prod_leq (I : finType) (P : pred I) (F : I -> {poly R}) : size (\prod_(i | P i) F i) <= (\sum_(i | P i) size (F i)).+1 - #|P|. Proof. rewrite -sum1_card. elim/big_rec3: _ => [|i n m p _ IHp]; first by rewrite size_poly1. have [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0. rewrite (leq_trans (size_polyMleq _ _)) // subnS -!subn1 leq_sub2r //. rewrite -addnS -addnBA ?leq_add2l // ltnW // -subn_gt0 (leq_trans _ IHp) //. by rewrite polySpred. Qed. Lemma coefCM c p i : (c%:P * p)`_i = c * p`_i. Proof. rewrite coefM big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Lemma coefMC c p i : (p * c%:P)`_i = p`_i * c. Proof. rewrite coefMr big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Lemma polyCM : {morph polyC : a b / a * b}. Proof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefCM !coefC ?simp. Qed. Lemma size_poly_exp_leq p n : size (p ^+ n) <= ((size p).-1 * n).+1. Proof. elim: n => [|n IHn]; first by rewrite size_poly1. have [-> | nzp] := poly0Vpos p; first by rewrite exprS mul0r size_poly0. rewrite exprS (leq_trans (size_polyMleq _ _)) //. by rewrite -{1}(prednK nzp) mulnS -addnS leq_add2l. Qed. End SemiPolynomialTheory. #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyD`")] Notation size_add := size_polyD (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyDl`")] Notation size_addl := size_polyDl (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyMleq`")] Notation size_mul_leq := size_polyMleq (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_poly_prod_leq`")] Notation size_prod_leq := size_poly_prod_leq (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_poly_exp_leq`")] Notation size_exp_leq := size_poly_exp_leq (only parsing). Section PolynomialTheory. Variable R : nzRingType. Implicit Types (a b c x y z : R) (p q r d : {poly R}). Local Notation "c %:P" := (polyC c). Local Notation "\poly_ ( i < n ) E" := (poly n (fun i : nat => E)). (* Zmodule structure for polynomial *) Definition opp_poly_def p := \poly_(i < size p) - p`_i. Fact opp_poly_key : unit. Proof. by []. Qed. Definition opp_poly := locked_with opp_poly_key opp_poly_def. Canonical opp_poly_unlockable := [unlockable fun opp_poly]. Fact coef_opp_poly p i : (opp_poly p)`_i = - p`_i. Proof. rewrite unlock coef_poly /=. by case: leqP => // le_p_i; rewrite nth_default ?oppr0. Qed. Fact add_polyN : left_inverse 0%:P opp_poly (@add_poly _). Proof. move=> p; apply/polyP=> i. by rewrite coef_add_poly coef_opp_poly coefC if_same addNr. Qed. HB.instance Definition _ := GRing.Nmodule_isZmodule.Build (polynomial R) add_polyN. (* Size, leading coef, morphism properties of coef *) Lemma coefN p i : (- p)`_i = - p`_i. Proof. exact: coef_opp_poly. Qed. Lemma coefB p q i : (p - q)`_i = p`_i - q`_i. Proof. by rewrite coefD coefN. Qed. HB.instance Definition _ i := GRing.isZmodMorphism.Build {poly R} R (coefp i) (fun p => (coefB p)^~ i). Lemma coefMn p n i : (p *+ n)`_i = p`_i *+ n. Proof. exact: (raddfMn (coefp i)). Qed. Lemma coefMNn p n i : (p *- n)`_i = p`_i *- n. Proof. by rewrite coefN coefMn. Qed. Lemma coef_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) k : (\sum_(i <- r | P i) F i)`_k = \sum_(i <- r | P i) (F i)`_k. Proof. exact: (raddf_sum (coefp k)). Qed. Lemma polyCN : {morph (@polyC R) : c / - c}. Proof. by move=> c; apply/polyP=> [[|i]]; rewrite coefN !coefC ?oppr0. Qed. Lemma polyCB : {morph (@polyC R) : a b / a - b}. Proof. by move=> a b; rewrite polyCD polyCN. Qed. HB.instance Definition _ := GRing.isZmodMorphism.Build R {poly R} (@polyC _) polyCB. Lemma polyCMn n : {morph (@polyC R) : c / c *+ n}. Proof. exact: raddfMn. Qed. Lemma size_polyN p : size (- p) = size p. Proof. by apply/eqP; rewrite eqn_leq -{3}(opprK p) -[-%R]/opp_poly unlock !size_poly. Qed. Lemma lead_coefN p : lead_coef (- p) = - lead_coef p. Proof. by rewrite /lead_coef size_polyN coefN. Qed. (* Polynomial ring structure. *) Fact polyC_is_monoid_morphism : monoid_morphism (@polyC R). Proof. by split; last apply: polyCM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `polyC_is_monoid_morphism` instead")] Definition polyC_multiplicative := (fun g => (g.2, g.1)) polyC_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build R {poly R} (@polyC R) polyC_is_monoid_morphism. Lemma polyC_exp n : {morph (@polyC R) : c / c ^+ n}. Proof. exact: rmorphXn. Qed. Lemma polyC_natr n : n%:R%:P = n%:R :> {poly R}. Proof. by rewrite rmorph_nat. Qed. Lemma pchar_poly : [pchar {poly R}] =i [pchar R]. Proof. move=> p; rewrite !inE; congr (_ && _). apply/eqP/eqP=> [/(congr1 val) /=|]; last by rewrite -polyC_natr => ->. by rewrite polyseq0 -polyC_natr polyseqC; case: eqP. Qed. Lemma size_Msign p n : size ((-1) ^+ n * p) = size p. Proof. by rewrite -signr_odd; case: (odd n); rewrite ?mul1r// mulN1r size_polyN. Qed. Fact coefp0_is_monoid_morphism : monoid_morphism (coefp 0 : {poly R} -> R). Proof. split=> [|p q]; first by rewrite polyCK. by rewrite [coefp 0 _]coefM big_ord_recl big_ord0 addr0. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `coefp0_is_monoid_morphism` instead")] Definition coefp0_multiplicative := (fun g => (g.2, g.1)) coefp0_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly R} R (coefp 0) coefp0_is_monoid_morphism. (* Algebra structure of polynomials. *) Definition scale_poly_def a (p : {poly R}) := \poly_(i < size p) (a * p`_i). Fact scale_poly_key : unit. Proof. by []. Qed. Definition scale_poly := locked_with scale_poly_key scale_poly_def. Canonical scale_poly_unlockable := [unlockable fun scale_poly]. Fact scale_polyE a p : scale_poly a p = a%:P * p. Proof. apply/polyP=> n; rewrite unlock coef_poly coefCM. by case: leqP => // le_p_n; rewrite nth_default ?mulr0. Qed. Fact scale_polyA a b p : scale_poly a (scale_poly b p) = scale_poly (a * b) p. Proof. by rewrite !scale_polyE mulrA polyCM. Qed. Fact scale_1poly : left_id 1 scale_poly. Proof. by move=> p; rewrite scale_polyE mul1r. Qed. Fact scale_polyDr a : {morph scale_poly a : p q / p + q}. Proof. by move=> p q; rewrite !scale_polyE mulrDr. Qed. Fact scale_polyDl p : {morph scale_poly^~ p : a b / a + b}. Proof. by move=> a b /=; rewrite !scale_polyE raddfD mulrDl. Qed. Fact scale_polyAl a p q : scale_poly a (p * q) = scale_poly a p * q. Proof. by rewrite !scale_polyE mulrA. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build R (polynomial R) scale_polyA scale_1poly scale_polyDr scale_polyDl. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build R (polynomial R) scale_polyAl. Lemma mul_polyC a p : a%:P * p = a *: p. Proof. by rewrite -scale_polyE. Qed. Lemma scale_polyC a b : a *: b%:P = (a * b)%:P. Proof. by rewrite -mul_polyC polyCM. Qed. Lemma alg_polyC a : a%:A = a%:P :> {poly R}. Proof. by rewrite -mul_polyC mulr1. Qed. Lemma coefZ a p i : (a *: p)`_i = a * p`_i. Proof. rewrite -[*:%R]/scale_poly unlock coef_poly. by case: leqP => // le_p_n; rewrite nth_default ?mulr0. Qed. Lemma size_scale_leq a p : size (a *: p) <= size p. Proof. by rewrite -[*:%R]/scale_poly unlock size_poly. Qed. HB.instance Definition _ i := GRing.isScalable.Build R {poly R} R *%R (coefp i) (fun a => (coefZ a) ^~ i). HB.instance Definition _ := GRing.Linear.on (coefp 0). (* The indeterminate, at last! *) Definition polyX_def := @Poly R [:: 0; 1]. Fact polyX_key : unit. Proof. by []. Qed. Definition polyX : {poly R} := locked_with polyX_key polyX_def. Canonical polyX_unlockable := [unlockable of polyX]. Local Notation "'X" := polyX. Lemma polyseqX : 'X = [:: 0; 1] :> seq R. Proof. by rewrite unlock !polyseq_cons nil_poly eqxx /= polyseq1. Qed. Lemma size_polyX : size 'X = 2. Proof. by rewrite polyseqX. Qed. Lemma polyX_eq0 : ('X == 0) = false. Proof. by rewrite -size_poly_eq0 size_polyX. Qed. Lemma coefX i : 'X`_i = (i == 1)%:R. Proof. by case: i => [|[|i]]; rewrite polyseqX //= nth_nil. Qed. Lemma lead_coefX : lead_coef 'X = 1. Proof. by rewrite /lead_coef polyseqX. Qed. Lemma commr_polyX p : GRing.comm p 'X. Proof. apply/polyP=> i; rewrite coefMr coefM. by apply: eq_bigr => j _; rewrite coefX commr_nat. Qed. Lemma coefMX p i : (p * 'X)`_i = (if (i == 0)%N then 0 else p`_i.-1). Proof. rewrite coefMr big_ord_recl coefX ?simp. case: i => [|i]; rewrite ?big_ord0 //= big_ord_recl polyseqX subn1 /=. by rewrite big1 ?simp // => j _; rewrite nth_nil !simp. Qed. Lemma coefXM p i : ('X * p)`_i = (if (i == 0)%N then 0 else p`_i.-1). Proof. by rewrite -commr_polyX coefMX. Qed. Lemma cons_poly_def p a : cons_poly a p = p * 'X + a%:P. Proof. apply/polyP=> i; rewrite coef_cons coefD coefMX coefC. by case: ifP; rewrite !simp. Qed. Lemma poly_ind (K : {poly R} -> Type) : K 0 -> (forall p c, K p -> K (p * 'X + c%:P)) -> (forall p, K p). Proof. move=> K0 Kcons p; rewrite -[p]polyseqK. by elim: {p}(p : seq R) => //= p c IHp; rewrite cons_poly_def; apply: Kcons. Qed. Lemma polyseqXaddC a : 'X + a%:P = [:: a; 1] :> seq R. Proof. by rewrite -['X]mul1r -cons_poly_def polyseq_cons polyseq1. Qed. Lemma polyseqXsubC a : 'X - a%:P = [:: - a; 1] :> seq R. Proof. by rewrite -polyCN polyseqXaddC. Qed. Lemma size_XsubC a : size ('X - a%:P) = 2. Proof. by rewrite polyseqXsubC. Qed. Lemma size_XaddC b : size ('X + b%:P) = 2. Proof. by rewrite -[b]opprK rmorphN size_XsubC. Qed. Lemma lead_coefXaddC a : lead_coef ('X + a%:P) = 1. Proof. by rewrite lead_coefE polyseqXaddC. Qed. Lemma lead_coefXsubC a : lead_coef ('X - a%:P) = 1. Proof. by rewrite lead_coefE polyseqXsubC. Qed. Lemma polyXsubC_eq0 a : ('X - a%:P == 0) = false. Proof. by rewrite -nil_poly polyseqXsubC. Qed. Lemma size_MXaddC p c : size (p * 'X + c%:P) = (if (p == 0) && (c == 0) then 0 else (size p).+1). Proof. by rewrite -cons_poly_def size_cons_poly nil_poly. Qed. Lemma polyseqMX p : p != 0 -> p * 'X = 0 :: p :> seq R. Proof. by move=> nz_p; rewrite -[p * _]addr0 -cons_poly_def polyseq_cons nil_poly nz_p. Qed. Lemma size_mulX p : p != 0 -> size (p * 'X) = (size p).+1. Proof. by move/polyseqMX->. Qed. Lemma lead_coefMX p : lead_coef (p * 'X) = lead_coef p. Proof. have [-> | nzp] := eqVneq p 0; first by rewrite mul0r. by rewrite /lead_coef !nth_last polyseqMX. Qed. Lemma size_XmulC a : a != 0 -> size ('X * a%:P) = 2. Proof. by move=> nz_a; rewrite -commr_polyX size_mulX ?polyC_eq0 ?size_polyC nz_a. Qed. Local Notation "''X^' n" := ('X ^+ n). Lemma coefXn n i : 'X^n`_i = (i == n)%:R. Proof. by elim: n i => [|n IHn] [|i]; rewrite ?coef1 // exprS coefXM ?IHn. Qed. Lemma polyseqXn n : 'X^n = rcons (nseq n 0) 1 :> seq R. Proof. elim: n => [|n IHn]; rewrite ?polyseq1 // exprSr. by rewrite polyseqMX -?size_poly_eq0 IHn ?size_rcons. Qed. Lemma size_polyXn n : size 'X^n = n.+1. Proof. by rewrite polyseqXn size_rcons size_nseq. Qed. Lemma commr_polyXn p n : GRing.comm p 'X^n. Proof. exact/commrX/commr_polyX. Qed. Lemma lead_coefXn n : lead_coef 'X^n = 1. Proof. by rewrite /lead_coef nth_last polyseqXn last_rcons. Qed. Lemma lead_coefXnaddC n c : 0 < n -> lead_coef ('X^n + c%:P) = 1. Proof. move=> n_gt0; rewrite lead_coefDl ?lead_coefXn//. by rewrite size_polyC size_polyXn ltnS (leq_trans (leq_b1 _)). Qed. Lemma lead_coefXnsubC n c : 0 < n -> lead_coef ('X^n - c%:P) = 1. Proof. by move=> n_gt0; rewrite -polyCN lead_coefXnaddC. Qed. Lemma size_XnaddC n c : 0 < n -> size ('X^n + c%:P) = n.+1. Proof. by move=> *; rewrite size_polyDl ?size_polyXn// size_polyC; case: eqP. Qed. Lemma size_XnsubC n c : 0 < n -> size ('X^n - c%:P) = n.+1. Proof. by move=> *; rewrite -polyCN size_XnaddC. Qed. Lemma polyseqMXn n p : p != 0 -> p * 'X^n = ncons n 0 p :> seq R. Proof. case: n => [|n] nz_p; first by rewrite mulr1. elim: n => [|n IHn]; first exact: polyseqMX. by rewrite exprSr mulrA polyseqMX -?nil_poly IHn. Qed. Lemma coefMXn n p i : (p * 'X^n)`_i = if i < n then 0 else p`_(i - n). Proof. have [-> | /polyseqMXn->] := eqVneq p 0; last exact: nth_ncons. by rewrite mul0r !coef0 if_same. Qed. Lemma size_mulXn n p : p != 0 -> size (p * 'X^n) = (n + size p)%N. Proof. elim: n p => [p p_neq0| n IH p p_neq0]; first by rewrite mulr1. by rewrite exprS mulrA IH -?size_poly_eq0 size_mulX // addnS. Qed. Lemma coefXnM n p i : ('X^n * p)`_i = if i < n then 0 else p`_(i - n). Proof. by rewrite -commr_polyXn coefMXn. Qed. Lemma coef_sumMXn I (r : seq I) (P : pred I) (p : I -> R) (n : I -> nat) k : (\sum_(i <- r | P i) p i *: 'X^(n i))`_k = \sum_(i <- r | P i && (n i == k)) p i. Proof. rewrite coef_sum big_mkcondr; apply: eq_bigr => i Pi. by rewrite coefZ coefXn mulr_natr mulrb eq_sym. Qed. (* Expansion of a polynomial as an indexed sum *) Lemma poly_def n E : \poly_(i < n) E i = \sum_(i < n) E i *: 'X^i. Proof. by apply/polyP => i; rewrite coef_sumMXn coef_poly big_ord1_eq. Qed. (* Monic predicate *) Definition monic_pred := fun p => lead_coef p == 1. Arguments monic_pred _ /. Definition monic := [qualify p | monic_pred p]. Lemma monicE p : (p \is monic) = (lead_coef p == 1). Proof. by []. Qed. Lemma monicP p : reflect (lead_coef p = 1) (p \is monic). Proof. exact: eqP. Qed. Lemma monic1 : 1 \is monic. Proof. exact/eqP/lead_coef1. Qed. Lemma monicX : 'X \is monic. Proof. exact/eqP/lead_coefX. Qed. Lemma monicXn n : 'X^n \is monic. Proof. exact/eqP/lead_coefXn. Qed. Lemma monic_neq0 p : p \is monic -> p != 0. Proof. by rewrite -lead_coef_eq0 => /eqP->; apply: oner_neq0. Qed. Lemma lead_coef_monicM p q : p \is monic -> lead_coef (p * q) = lead_coef q. Proof. have [-> | nz_q] := eqVneq q 0; first by rewrite mulr0. by move/monicP=> mon_p; rewrite lead_coef_proper_mul mon_p mul1r ?lead_coef_eq0. Qed. Lemma lead_coef_Mmonic p q : q \is monic -> lead_coef (p * q) = lead_coef p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite mul0r. by move/monicP=> mon_q; rewrite lead_coef_proper_mul mon_q mulr1 ?lead_coef_eq0. Qed. Lemma size_monicM p q : p \is monic -> q != 0 -> size (p * q) = (size p + size q).-1. Proof. move/monicP=> mon_p nz_q. by rewrite size_proper_mul // mon_p mul1r lead_coef_eq0. Qed. Lemma size_Mmonic p q : p != 0 -> q \is monic -> size (p * q) = (size p + size q).-1. Proof. move=> nz_p /monicP mon_q. by rewrite size_proper_mul // mon_q mulr1 lead_coef_eq0. Qed. Lemma monicMl p q : p \is monic -> (p * q \is monic) = (q \is monic). Proof. by move=> mon_p; rewrite !monicE lead_coef_monicM. Qed. Lemma monicMr p q : q \is monic -> (p * q \is monic) = (p \is monic). Proof. by move=> mon_q; rewrite !monicE lead_coef_Mmonic. Qed. Fact monic_mulr_closed : mulr_closed monic. Proof. by split=> [|p q mon_p]; rewrite (monic1, monicMl). Qed. HB.instance Definition _ := GRing.isMulClosed.Build {poly R} monic_pred monic_mulr_closed. Lemma monic_exp p n : p \is monic -> p ^+ n \is monic. Proof. exact: rpredX. Qed. Lemma monic_prod I rI (P : pred I) (F : I -> {poly R}): (forall i, P i -> F i \is monic) -> \prod_(i <- rI | P i) F i \is monic. Proof. exact: rpred_prod. Qed. Lemma monicXaddC c : 'X + c%:P \is monic. Proof. exact/eqP/lead_coefXaddC. Qed. Lemma monicXsubC c : 'X - c%:P \is monic. Proof. exact/eqP/lead_coefXsubC. Qed. Lemma monic_prod_XsubC I rI (P : pred I) (F : I -> R) : \prod_(i <- rI | P i) ('X - (F i)%:P) \is monic. Proof. by apply: monic_prod => i _; apply: monicXsubC. Qed. Lemma lead_coef_prod_XsubC I rI (P : pred I) (F : I -> R) : lead_coef (\prod_(i <- rI | P i) ('X - (F i)%:P)) = 1. Proof. exact/eqP/monic_prod_XsubC. Qed. Lemma size_prod_XsubC I rI (F : I -> R) : size (\prod_(i <- rI) ('X - (F i)%:P)) = (size rI).+1. Proof. elim: rI => [|i r /= <-]; rewrite ?big_nil ?size_poly1 // big_cons. rewrite size_monicM ?monicXsubC ?monic_neq0 ?monic_prod_XsubC //. by rewrite size_XsubC. Qed. Lemma size_exp_XsubC n a : size (('X - a%:P) ^+ n) = n.+1. Proof. rewrite -[n]card_ord -prodr_const -big_filter size_prod_XsubC. by have [e _ _ [_ ->]] := big_enumP. Qed. Lemma monicXnaddC n c : 0 < n -> 'X^n + c%:P \is monic. Proof. by move=> n_gt0; rewrite monicE lead_coefXnaddC. Qed. Lemma monicXnsubC n c : 0 < n -> 'X^n - c%:P \is monic. Proof. by move=> n_gt0; rewrite monicE lead_coefXnsubC. Qed. (* Some facts about regular elements. *) Lemma lreg_lead p : GRing.lreg (lead_coef p) -> GRing.lreg p. Proof. move/mulrI_eq0=> reg_p; apply: mulrI0_lreg => q /eqP; apply: contraTeq => nz_q. by rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0. Qed. Lemma rreg_lead p : GRing.rreg (lead_coef p) -> GRing.rreg p. Proof. move/mulIr_eq0=> reg_p; apply: mulIr0_rreg => q /eqP; apply: contraTeq => nz_q. by rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0. Qed. Lemma lreg_lead0 p : GRing.lreg (lead_coef p) -> p != 0. Proof. by move/lreg_neq0; rewrite lead_coef_eq0. Qed. Lemma rreg_lead0 p : GRing.rreg (lead_coef p) -> p != 0. Proof. by move/rreg_neq0; rewrite lead_coef_eq0. Qed. Lemma lreg_size c p : GRing.lreg c -> size (c *: p) = size p. Proof. move=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite scaler0. rewrite -mul_polyC size_proper_mul; first by rewrite size_polyC lreg_neq0. by rewrite lead_coefC mulrI_eq0 ?lead_coef_eq0. Qed. Lemma lreg_polyZ_eq0 c p : GRing.lreg c -> (c *: p == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /lreg_size->. Qed. Lemma lead_coef_lreg c p : GRing.lreg c -> lead_coef (c *: p) = c * lead_coef p. Proof. by move=> reg_c; rewrite !lead_coefE coefZ lreg_size. Qed. Lemma rreg_size c p : GRing.rreg c -> size (p * c%:P) = size p. Proof. move=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite mul0r. rewrite size_proper_mul; first by rewrite size_polyC rreg_neq0 ?addn1. by rewrite lead_coefC mulIr_eq0 ?lead_coef_eq0. Qed. Lemma rreg_polyMC_eq0 c p : GRing.rreg c -> (p * c%:P == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /rreg_size->. Qed. Lemma rreg_div0 q r d : GRing.rreg (lead_coef d) -> size r < size d -> (q * d + r == 0) = (q == 0) && (r == 0). Proof. move=> reg_d lt_r_d; rewrite addrC addr_eq0. have [-> | nz_q] := eqVneq q 0; first by rewrite mul0r oppr0. apply: contraTF lt_r_d => /eqP->; rewrite -leqNgt size_polyN. rewrite size_proper_mul ?mulIr_eq0 ?lead_coef_eq0 //. by rewrite (polySpred nz_q) leq_addl. Qed. Lemma monic_comreg p : p \is monic -> GRing.comm p (lead_coef p)%:P /\ GRing.rreg (lead_coef p). Proof. by move/monicP->; split; [apply: commr1 | apply: rreg1]. Qed. Lemma monic_lreg p : p \is monic -> GRing.lreg p. Proof. by move=> /eqP lp1; apply/lreg_lead; rewrite lp1; apply/lreg1. Qed. Lemma monic_rreg p : p \is monic -> GRing.rreg p. Proof. by move=> /eqP lp1; apply/rreg_lead; rewrite lp1; apply/rreg1. Qed. (* Horner evaluation of polynomials *) Implicit Types s rs : seq R. Fixpoint horner_rec s x := if s is a :: s' then horner_rec s' x * x + a else 0. Definition horner p := horner_rec p. Local Notation "p .[ x ]" := (horner p x) : ring_scope. Lemma horner0 x : (0 : {poly R}).[x] = 0. Proof. by rewrite /horner polyseq0. Qed. Lemma hornerC c x : (c%:P).[x] = c. Proof. by rewrite /horner polyseqC; case: eqP; rewrite /= ?simp. Qed. Lemma hornerX x : 'X.[x] = x. Proof. by rewrite /horner polyseqX /= !simp. Qed. Lemma horner_cons p c x : (cons_poly c p).[x] = p.[x] * x + c. Proof. rewrite /horner polyseq_cons; case: nilP => //= ->. by rewrite !simp -/(_.[x]) hornerC. Qed. Lemma horner_coef0 p : p.[0] = p`_0. Proof. by rewrite /horner; case: (p : seq R) => //= c p'; rewrite !simp. Qed. Lemma hornerMXaddC p c x : (p * 'X + c%:P).[x] = p.[x] * x + c. Proof. by rewrite -cons_poly_def horner_cons. Qed. Lemma hornerMX p x : (p * 'X).[x] = p.[x] * x. Proof. by rewrite -[p * 'X]addr0 hornerMXaddC addr0. Qed. Lemma horner_Poly s x : (Poly s).[x] = horner_rec s x. Proof. by elim: s => [|a s /= <-]; rewrite (horner0, horner_cons). Qed. Lemma horner_coef p x : p.[x] = \sum_(i < size p) p`_i * x ^+ i. Proof. rewrite /horner. elim: {p}(p : seq R) => /= [|a s ->]; first by rewrite big_ord0. rewrite big_ord_recl simp addrC big_distrl /=. by congr (_ + _); apply: eq_bigr => i _; rewrite -mulrA exprSr. Qed. Lemma horner_coef_wide n p x : size p <= n -> p.[x] = \sum_(i < n) p`_i * x ^+ i. Proof. move=> le_p_n. rewrite horner_coef (big_ord_widen n (fun i => p`_i * x ^+ i)) // big_mkcond. by apply: eq_bigr => i _; case: ltnP => // le_p_i; rewrite nth_default ?simp. Qed. Lemma horner_poly n E x : (\poly_(i < n) E i).[x] = \sum_(i < n) E i * x ^+ i. Proof. rewrite (@horner_coef_wide n) ?size_poly //. by apply: eq_bigr => i _; rewrite coef_poly ltn_ord. Qed. Lemma hornerN p x : (- p).[x] = - p.[x]. Proof. rewrite -[-%R]/opp_poly unlock horner_poly horner_coef -sumrN /=. by apply: eq_bigr => i _; rewrite mulNr. Qed. Lemma hornerD p q x : (p + q).[x] = p.[x] + q.[x]. Proof. rewrite -[+%R]/(@add_poly R) unlock horner_poly; set m := maxn _ _. rewrite !(@horner_coef_wide m) ?leq_max ?leqnn ?orbT // -big_split /=. by apply: eq_bigr => i _; rewrite -mulrDl. Qed. Lemma hornerXsubC a x : ('X - a%:P).[x] = x - a. Proof. by rewrite hornerD hornerN hornerC hornerX. Qed. Lemma horner_sum I (r : seq I) (P : pred I) F x : (\sum_(i <- r | P i) F i).[x] = \sum_(i <- r | P i) (F i).[x]. Proof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (horner0, hornerD). Qed. Lemma hornerCM a p x : (a%:P * p).[x] = a * p.[x]. Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !(mulr0, horner0). by rewrite mulrDr mulrA -polyCM !hornerMXaddC IHp mulrDr mulrA. Qed. Lemma hornerZ c p x : (c *: p).[x] = c * p.[x]. Proof. by rewrite -mul_polyC hornerCM. Qed. Lemma hornerMn n p x : (p *+ n).[x] = p.[x] *+ n. Proof. by elim: n => [| n IHn]; rewrite ?horner0 // !mulrS hornerD IHn. Qed. Definition comm_coef p x := forall i, p`_i * x = x * p`_i. Definition comm_poly p x := x * p.[x] = p.[x] * x. Lemma comm_coef_poly p x : comm_coef p x -> comm_poly p x. Proof. move=> cpx; rewrite /comm_poly !horner_coef big_distrl big_distrr /=. by apply: eq_bigr => i _; rewrite /= mulrA -cpx -!mulrA commrX. Qed. Lemma comm_poly0 x : comm_poly 0 x. Proof. by rewrite /comm_poly !horner0 !simp. Qed. Lemma comm_poly1 x : comm_poly 1 x. Proof. by rewrite /comm_poly !hornerC !simp. Qed. Lemma comm_polyX x : comm_poly 'X x. Proof. by rewrite /comm_poly !hornerX. Qed. Lemma comm_polyD p q x: comm_poly p x -> comm_poly q x -> comm_poly (p + q) x. Proof. by rewrite /comm_poly hornerD mulrDr mulrDl => -> ->. Qed. Lemma commr_horner a b p : GRing.comm a b -> comm_coef p a -> GRing.comm a p.[b]. Proof. move=> cab cpa; rewrite horner_coef; apply: commr_sum => i _. by apply: commrM => //; apply: commrX. Qed. Lemma hornerM_comm p q x : comm_poly q x -> (p * q).[x] = p.[x] * q.[x]. Proof. move=> comm_qx. elim/poly_ind: p => [|p c IHp]; first by rewrite !(simp, horner0). rewrite mulrDl hornerD hornerCM -mulrA -commr_polyX mulrA hornerMX. by rewrite {}IHp -mulrA -comm_qx mulrA -mulrDl hornerMXaddC. Qed. Lemma comm_polyM p q x: comm_poly p x -> comm_poly q x -> comm_poly (p * q) x. Proof. by move=> px qx; rewrite /comm_poly hornerM_comm// mulrA px -mulrA qx mulrA. Qed. Lemma horner_exp_comm p x n : comm_poly p x -> (p ^+ n).[x] = p.[x] ^+ n. Proof. move=> comm_px; elim: n => [|n IHn]; first by rewrite hornerC. by rewrite !exprSr -IHn hornerM_comm. Qed. Lemma comm_poly_exp p n x: comm_poly p x -> comm_poly (p ^+ n) x. Proof. by move=> px; rewrite /comm_poly !horner_exp_comm// commrX. Qed. Lemma hornerXn x n : ('X^n).[x] = x ^+ n. Proof. by rewrite horner_exp_comm /comm_poly hornerX. Qed. Definition hornerE_comm := (hornerD, hornerN, hornerX, hornerC, horner_cons, simp, hornerCM, hornerZ, (fun p x => hornerM_comm p (comm_polyX x))). Definition root p : pred R := fun x => p.[x] == 0. Lemma mem_root p x : x \in root p = (p.[x] == 0). Proof. by []. Qed. Lemma rootE p x : (root p x = (p.[x] == 0)) * ((x \in root p) = (p.[x] == 0)). Proof. by []. Qed. Lemma rootP p x : reflect (p.[x] = 0) (root p x). Proof. exact: eqP. Qed. Lemma rootPt p x : reflect (p.[x] == 0) (root p x). Proof. exact: idP. Qed. Lemma rootPf p x : reflect ((p.[x] == 0) = false) (~~ root p x). Proof. exact: negPf. Qed. Lemma rootC a x : root a%:P x = (a == 0). Proof. by rewrite rootE hornerC. Qed. Lemma root0 x : root 0 x. Proof. by rewrite rootC. Qed. Lemma root1 x : ~~ root 1 x. Proof. by rewrite rootC oner_eq0. Qed. Lemma rootX x : root 'X x = (x == 0). Proof. by rewrite rootE hornerX. Qed. Lemma rootN p x : root (- p) x = root p x. Proof. by rewrite rootE hornerN oppr_eq0. Qed. Lemma root_size_gt1 a p : p != 0 -> root p a -> 1 < size p. Proof. rewrite ltnNge => nz_p; apply: contraL => /size1_polyC Dp. by rewrite Dp rootC -polyC_eq0 -Dp. Qed. Lemma root_XsubC a x : root ('X - a%:P) x = (x == a). Proof. by rewrite rootE hornerXsubC subr_eq0. Qed. Lemma root_XaddC a x : root ('X + a%:P) x = (x == - a). Proof. by rewrite -root_XsubC rmorphN opprK. Qed. Theorem factor_theorem p a : reflect (exists q, p = q * ('X - a%:P)) (root p a). Proof. apply: (iffP eqP) => [pa0 | [q ->]]; last first. by rewrite hornerM_comm /comm_poly hornerXsubC subrr ?simp. exists (\poly_(i < size p) horner_rec (drop i.+1 p) a). apply/polyP=> i; rewrite mulrBr coefB coefMX coefMC !coef_poly. apply: canRL (addrK _) _; rewrite addrC; have [le_p_i | lt_i_p] := leqP. rewrite nth_default // !simp drop_oversize ?if_same //. exact: leq_trans (leqSpred _). case: i => [|i] in lt_i_p *; last by rewrite ltnW // (drop_nth 0 lt_i_p). by rewrite drop1 /= -{}pa0 /horner; case: (p : seq R) lt_i_p. Qed. Lemma multiplicity_XsubC p a : {m | exists2 q, (p != 0) ==> ~~ root q a & p = q * ('X - a%:P) ^+ m}. Proof. have [n le_p_n] := ubnP (size p); elim: n => // n IHn in p le_p_n *. have [-> | nz_p /=] := eqVneq p 0; first by exists 0, 0; rewrite ?mul0r. have [/sig_eqW[p1 Dp] | nz_pa] := altP (factor_theorem p a); last first. by exists 0%N, p; rewrite ?mulr1. have nz_p1: p1 != 0 by apply: contraNneq nz_p => p1_0; rewrite Dp p1_0 mul0r. have /IHn[m /sig2_eqW[q nz_qa Dp1]]: size p1 < n. by rewrite Dp size_Mmonic ?monicXsubC // size_XsubC addn2 in le_p_n. by exists m.+1, q; [rewrite nz_p1 in nz_qa | rewrite exprSr mulrA -Dp1]. Qed. (* Roots of unity. *) #[deprecated(since="mathcomp 2.3.0",note="Use size_XnsubC instead.")] Lemma size_Xn_sub_1 n : n > 0 -> size ('X^n - 1 : {poly R}) = n.+1. Proof. exact/size_XnsubC. Qed. #[deprecated(since="mathcomp 2.3.0'",note="Use monicXnsubC instead.")] Lemma monic_Xn_sub_1 n : n > 0 -> 'X^n - 1 \is monic. Proof. exact/monicXnsubC. Qed. Definition root_of_unity n : pred R := root ('X^n - 1). Local Notation "n .-unity_root" := (root_of_unity n) : ring_scope. Lemma unity_rootE n z : n.-unity_root z = (z ^+ n == 1). Proof. by rewrite /root_of_unity rootE hornerD hornerN hornerXn hornerC subr_eq0. Qed. Lemma unity_rootP n z : reflect (z ^+ n = 1) (n.-unity_root z). Proof. by rewrite unity_rootE; apply: eqP. Qed. Definition primitive_root_of_unity n z := (n > 0) && [forall i : 'I_n, i.+1.-unity_root z == (i.+1 == n)]. Local Notation "n .-primitive_root" := (primitive_root_of_unity n) : ring_scope. Lemma prim_order_exists n z : n > 0 -> z ^+ n = 1 -> {m | m.-primitive_root z & (m %| n)}. Proof. move=> n_gt0 zn1. have: exists m, (m > 0) && (z ^+ m == 1) by exists n; rewrite n_gt0 /= zn1. case/ex_minnP=> m /andP[m_gt0 /eqP zm1] m_min. exists m. apply/andP; split=> //; apply/eqfunP=> [[i]] /=. rewrite leq_eqVlt unity_rootE. case: eqP => [-> _ | _]; first by rewrite zm1 eqxx. by apply: contraTF => zi1; rewrite -leqNgt m_min. have: n %% m < m by rewrite ltn_mod. apply: contraLR; rewrite -lt0n -leqNgt => nm_gt0; apply: m_min. by rewrite nm_gt0 /= expr_mod ?zn1. Qed. Section OnePrimitive. Variables (n : nat) (z : R). Hypothesis prim_z : n.-primitive_root z. Lemma prim_order_gt0 : n > 0. Proof. by case/andP: prim_z. Qed. Let n_gt0 := prim_order_gt0. Lemma prim_expr_order : z ^+ n = 1. Proof. case/andP: prim_z => _; rewrite -(prednK n_gt0) => /forallP/(_ ord_max). by rewrite unity_rootE eqxx eqb_id => /eqP. Qed. Lemma prim_expr_mod i : z ^+ (i %% n) = z ^+ i. Proof. exact: expr_mod prim_expr_order. Qed. Lemma prim_order_dvd i : (n %| i) = (z ^+ i == 1). Proof. move: n_gt0; rewrite -prim_expr_mod /dvdn -(ltn_mod i). case: {i}(i %% n)%N => [|i] lt_i; first by rewrite !eqxx. case/andP: prim_z => _ /forallP/(_ (Ordinal (ltnW lt_i)))/eqP. by rewrite unity_rootE eqn_leq andbC leqNgt lt_i. Qed. Lemma eq_prim_root_expr i j : (z ^+ i == z ^+ j) = (i == j %[mod n]). Proof. wlog le_ji: i j / j <= i. move=> IH; case: (leqP j i) => [|/ltnW] /IH //. by rewrite eq_sym (eq_sym (j %% n)%N). rewrite -{1}(subnKC le_ji) exprD -prim_expr_mod eqn_mod_dvd //. rewrite prim_order_dvd; apply/eqP/eqP=> [|->]; last by rewrite mulr1. move/(congr1 ( *%R (z ^+ (n - j %% n)))); rewrite mulrA -exprD. by rewrite subnK ?prim_expr_order ?mul1r // ltnW ?ltn_mod. Qed. Lemma exp_prim_root k : (n %/ gcdn k n).-primitive_root (z ^+ k). Proof. set d := gcdn k n; have d_gt0: (0 < d)%N by rewrite gcdn_gt0 orbC n_gt0. have [d_dv_k d_dv_n]: (d %| k /\ d %| n)%N by rewrite dvdn_gcdl dvdn_gcdr. set q := (n %/ d)%N; rewrite /q.-primitive_root ltn_divRL // n_gt0. apply/forallP=> i; rewrite unity_rootE -exprM -prim_order_dvd. rewrite -(divnK d_dv_n) -/q -(divnK d_dv_k) mulnAC dvdn_pmul2r //. apply/eqP; apply/idP/idP=> [|/eqP->]; last by rewrite dvdn_mull. rewrite Gauss_dvdr; first by rewrite eqn_leq ltn_ord; apply: dvdn_leq. by rewrite /coprime gcdnC -(eqn_pmul2r d_gt0) mul1n muln_gcdl !divnK. Qed. Lemma dvdn_prim_root m : (m %| n)%N -> m.-primitive_root (z ^+ (n %/ m)). Proof. set k := (n %/ m)%N => m_dv_n; rewrite -{1}(mulKn m n_gt0) -divnA // -/k. by rewrite -{1}(@gcdn_idPl k n _) ?exp_prim_root // -(divnK m_dv_n) dvdn_mulr. Qed. Lemma prim_root_eq0 : (z == 0) = (n == 0%N). Proof. rewrite gtn_eqF//; apply/eqP => z0; have /esym/eqP := prim_expr_order. by rewrite z0 expr0n gtn_eqF//= oner_eq0. Qed. End OnePrimitive. Lemma prim_root_exp_coprime n z k : n.-primitive_root z -> n.-primitive_root (z ^+ k) = coprime k n. Proof. move=> prim_z; have n_gt0 := prim_order_gt0 prim_z. apply/idP/idP=> [prim_zk | co_k_n]. set d := gcdn k n; have dv_d_n: (d %| n)%N := dvdn_gcdr _ _. rewrite /coprime -/d -(eqn_pmul2r n_gt0) mul1n -{2}(gcdnMl n d). rewrite -{2}(divnK dv_d_n) (mulnC _ d) -muln_gcdr (gcdn_idPr _) //. rewrite (prim_order_dvd prim_zk) -exprM -(prim_order_dvd prim_z). by rewrite muln_divCA_gcd dvdn_mulr. have zkn_1: z ^+ k ^+ n = 1 by rewrite exprAC (prim_expr_order prim_z) expr1n. have{zkn_1} [m prim_zk dv_m_n]:= prim_order_exists n_gt0 zkn_1. suffices /eqP <-: m == n by []. rewrite eqn_dvd dv_m_n -(@Gauss_dvdr n k m) 1?coprime_sym //=. by rewrite (prim_order_dvd prim_z) exprM (prim_expr_order prim_zk). Qed. (* Lifting a ring predicate to polynomials. *) Implicit Type S : {pred R}. Definition polyOver_pred S := fun p : {poly R} => all (mem S) p. Arguments polyOver_pred _ _ /. Definition polyOver S := [qualify a p | polyOver_pred S p]. Lemma polyOverS (S1 S2 : {pred R}) : {subset S1 <= S2} -> {subset polyOver S1 <= polyOver S2}. Proof. by move=> sS12 p /(all_nthP 0)S1p; apply/(all_nthP 0)=> i /S1p; apply: sS12. Qed. Lemma polyOver0 S : 0 \is a polyOver S. Proof. by rewrite qualifE /= polyseq0. Qed. Lemma polyOver_poly S n E : (forall i, i < n -> E i \in S) -> \poly_(i < n) E i \is a polyOver S. Proof. move=> S_E; apply/(all_nthP 0)=> i lt_i_p /=; rewrite coef_poly. by case: ifP => [/S_E// | /idP[]]; apply: leq_trans lt_i_p (size_poly n E). Qed. Section PolyOverAdd. Variable S : addrClosed R. Lemma polyOverP {p} : reflect (forall i, p`_i \in S) (p \in polyOver S). Proof. apply: (iffP (all_nthP 0)) => [Sp i | Sp i _]; last exact: Sp. by have [/Sp // | /(nth_default 0)->] := ltnP i (size p); apply: rpred0. Qed. Lemma polyOverC c : (c%:P \in polyOver S) = (c \in S). Proof. by rewrite [LHS]qualifE /= polyseqC; case: eqP => [->|] /=; rewrite ?andbT ?rpred0. Qed. Fact polyOver_addr_closed : addr_closed (polyOver S). Proof. split=> [|p q Sp Sq]; first exact: polyOver0. by apply/polyOverP=> i; rewrite coefD rpredD ?(polyOverP _). Qed. HB.instance Definition _ := GRing.isAddClosed.Build {poly R} (polyOver_pred S) polyOver_addr_closed. End PolyOverAdd. Section PolyOverSemiRing2. Variable S : semiring2Closed R. Lemma polyOver_mulr_2closed : GRing.mulr_2closed (polyOver S). Proof. move=> p q /polyOverP Sp /polyOverP Sq; apply/polyOverP=> i. by rewrite coefM rpred_sum // => j _; rewrite rpredM. Qed. HB.instance Definition _ := GRing.isMul2Closed.Build {poly R} (polyOver_pred S) polyOver_mulr_2closed. End PolyOverSemiRing2. Fact polyOverNr (zmodS : zmodClosed R) : oppr_closed (polyOver zmodS). Proof. by move=> p /polyOverP Sp; apply/polyOverP=> i; rewrite coefN rpredN. Qed. HB.instance Definition _ (zmodS : zmodClosed R) := GRing.isOppClosed.Build {poly R} (polyOver_pred zmodS) (@polyOverNr _). Section PolyOverSemiring. Variable S : semiringClosed R. Fact polyOver_mul1_closed : 1 \in (polyOver S). Proof. by rewrite polyOverC rpred1. Qed. HB.instance Definition _ := GRing.isMul1Closed.Build {poly R} (polyOver_pred S) polyOver_mul1_closed. Lemma polyOverZ : {in S & polyOver S, forall c p, c *: p \is a polyOver S}. Proof. by move=> c p Sc /polyOverP Sp; apply/polyOverP=> i; rewrite coefZ rpredM ?Sp. Qed. Lemma polyOverX : 'X \in polyOver S. Proof. by rewrite qualifE /= polyseqX /= rpred0 rpred1. Qed. Lemma polyOverXn n : 'X^n \in polyOver S. Proof. by rewrite rpredX// polyOverX. Qed. Lemma rpred_horner : {in polyOver S & S, forall p x, p.[x] \in S}. Proof. move=> p x /polyOverP Sp Sx; rewrite horner_coef rpred_sum // => i _. by rewrite rpredM ?rpredX. Qed. End PolyOverSemiring. Section PolyOverRing. Variable S : subringClosed R. HB.instance Definition _ := GRing.MulClosed.on (polyOver_pred S). Lemma polyOverXaddC c : ('X + c%:P \in polyOver S) = (c \in S). Proof. by rewrite rpredDl ?polyOverX ?polyOverC. Qed. Lemma polyOverXnaddC n c : ('X^n + c%:P \is a polyOver S) = (c \in S). Proof. by rewrite rpredDl ?polyOverXn// ?polyOverC. Qed. Lemma polyOverXsubC c : ('X - c%:P \in polyOver S) = (c \in S). Proof. by rewrite rpredBl ?polyOverX ?polyOverC. Qed. Lemma polyOverXnsubC n c : ('X^n - c%:P \is a polyOver S) = (c \in S). Proof. by rewrite rpredBl ?polyOverXn// ?polyOverC. Qed. End PolyOverRing. (* Single derivative. *) Definition deriv p := \poly_(i < (size p).-1) (p`_i.+1 *+ i.+1). Local Notation "a ^` ()" := (deriv a). Lemma coef_deriv p i : p^`()`_i = p`_i.+1 *+ i.+1. Proof. rewrite coef_poly -subn1 ltn_subRL. by case: leqP => // /(nth_default 0) ->; rewrite mul0rn. Qed. Lemma polyOver_deriv (ringS : semiringClosed R) : {in polyOver ringS, forall p, p^`() \is a polyOver ringS}. Proof. by move=> p /polyOverP Kp; apply/polyOverP=> i; rewrite coef_deriv rpredMn ?Kp. Qed. Lemma derivC c : c%:P^`() = 0. Proof. by apply/polyP=> i; rewrite coef_deriv coef0 coefC mul0rn. Qed. Lemma derivX : ('X)^`() = 1. Proof. by apply/polyP=> [[|i]]; rewrite coef_deriv coef1 coefX ?mul0rn. Qed. Lemma derivXn n : ('X^n)^`() = 'X^(n.-1) *+ n. Proof. case: n => [|n]; first exact: derivC. apply/polyP=> i; rewrite coef_deriv coefMn !coefXn eqSS. by case: eqP => [-> // | _]; rewrite !mul0rn. Qed. Fact deriv_is_linear : linear deriv. Proof. move=> k p q; apply/polyP=> i. by rewrite !(coef_deriv, coefD, coefZ) mulrnDl mulrnAr. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly R} _ deriv (GRing.semilinear_linear deriv_is_linear). Lemma deriv0 : 0^`() = 0. Proof. exact: linear0. Qed. Lemma derivD : {morph deriv : p q / p + q}. Proof. exact: linearD. Qed. Lemma derivN : {morph deriv : p / - p}. Proof. exact: linearN. Qed. Lemma derivB : {morph deriv : p q / p - q}. Proof. exact: linearB. Qed. Lemma derivXsubC (a : R) : ('X - a%:P)^`() = 1. Proof. by rewrite derivB derivX derivC subr0. Qed. Lemma derivMn n p : (p *+ n)^`() = p^`() *+ n. Proof. exact: linearMn. Qed. Lemma derivMNn n p : (p *- n)^`() = p^`() *- n. Proof. exact: linearMNn. Qed. Lemma derivZ c p : (c *: p)^`() = c *: p^`(). Proof. exact: linearZ. Qed. Lemma deriv_mulC c p : (c%:P * p)^`() = c%:P * p^`(). Proof. by rewrite !mul_polyC derivZ. Qed. Lemma derivMXaddC p c : (p * 'X + c%:P)^`() = p + p^`() * 'X. Proof. apply/polyP=> i; rewrite raddfD /= derivC addr0 coefD !(coefMX, coef_deriv). by case: i; rewrite ?addr0. Qed. Lemma derivM p q : (p * q)^`() = p^`() * q + p * q^`(). Proof. elim/poly_ind: p => [|p b IHp]; first by rewrite !(mul0r, add0r, derivC). rewrite mulrDl -mulrA -commr_polyX mulrA -[_ * 'X]addr0 raddfD /= !derivMXaddC. by rewrite deriv_mulC IHp !mulrDl -!mulrA !commr_polyX !addrA. Qed. Definition derivE := Eval lazy beta delta [morphism_2 morphism_1] in (derivZ, deriv_mulC, derivC, derivX, derivMXaddC, derivXsubC, derivM, derivB, derivD, derivN, derivXn, derivM, derivMn). (* Iterated derivative. *) Definition derivn n p := iter n deriv p. Local Notation "a ^` ( n )" := (derivn n a) : ring_scope. Lemma derivn0 p : p^`(0) = p. Proof. by []. Qed. Lemma derivn1 p : p^`(1) = p^`(). Proof. by []. Qed. Lemma derivnS p n : p^`(n.+1) = p^`(n)^`(). Proof. by []. Qed. Lemma derivSn p n : p^`(n.+1) = p^`()^`(n). Proof. exact: iterSr. Qed. Lemma coef_derivn n p i : p^`(n)`_i = p`_(n + i) *+ (n + i) ^_ n. Proof. elim: n i => [|n IHn] i; first by rewrite ffactn0 mulr1n. by rewrite derivnS coef_deriv IHn -mulrnA ffactnSr addSnnS addKn. Qed. Lemma polyOver_derivn (ringS : semiringClosed R) : {in polyOver ringS, forall p n, p^`(n) \is a polyOver ringS}. Proof. move=> p /polyOverP Kp /= n; apply/polyOverP=> i. by rewrite coef_derivn rpredMn. Qed. Fact derivn_is_linear n : linear (derivn n). Proof. by elim: n => // n IHn a p q; rewrite derivnS IHn linearP. Qed. HB.instance Definition _ n := GRing.isSemilinear.Build R {poly R} {poly R} _ (derivn n) (GRing.semilinear_linear (derivn_is_linear n)). Lemma derivnC c n : c%:P^`(n) = if n == 0 then c%:P else 0. Proof. by case: n => // n; rewrite derivSn derivC linear0. Qed. Lemma derivnD n : {morph derivn n : p q / p + q}. Proof. exact: linearD. Qed. Lemma derivnB n : {morph derivn n : p q / p - q}. Proof. exact: linearB. Qed. Lemma derivnMn n m p : (p *+ m)^`(n) = p^`(n) *+ m. Proof. exact: linearMn. Qed. Lemma derivnMNn n m p : (p *- m)^`(n) = p^`(n) *- m. Proof. exact: linearMNn. Qed. Lemma derivnN n : {morph derivn n : p / - p}. Proof. exact: linearN. Qed. Lemma derivnZ n : scalable (derivn n). Proof. exact: linearZZ. Qed. Lemma derivnXn m n : ('X^m)^`(n) = 'X^(m - n) *+ m ^_ n. Proof. apply/polyP=>i; rewrite coef_derivn coefMn !coefXn. case: (ltnP m n) => [lt_m_n | le_m_n]. by rewrite eqn_leq leqNgt ltn_addr // mul0rn ffact_small. by rewrite -{1 3}(subnKC le_m_n) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn. Qed. Lemma derivnMXaddC n p c : (p * 'X + c%:P)^`(n.+1) = p^`(n) *+ n.+1 + p^`(n.+1) * 'X. Proof. elim: n => [|n IHn]; first by rewrite derivn1 derivMXaddC. rewrite derivnS IHn derivD derivM derivX mulr1 derivMn -!derivnS. by rewrite addrA addrAC -mulrSr. Qed. Lemma derivn_poly0 p n : size p <= n -> p^`(n) = 0. Proof. move=> le_p_n; apply/polyP=> i; rewrite coef_derivn. rewrite nth_default; first by rewrite mul0rn coef0. exact/(leq_trans le_p_n)/leq_addr. Qed. Lemma lt_size_deriv (p : {poly R}) : p != 0 -> size p^`() < size p. Proof. by move=> /polySpred->; apply: size_poly. Qed. (* A normalising version of derivation to get the division by n! in Taylor *) Definition nderivn n p := \poly_(i < size p - n) (p`_(n + i) *+ 'C(n + i, n)). Local Notation "a ^`N ( n )" := (nderivn n a) : ring_scope. Lemma coef_nderivn n p i : p^`N(n)`_i = p`_(n + i) *+ 'C(n + i, n). Proof. rewrite coef_poly ltn_subRL; case: leqP => // le_p_ni. by rewrite nth_default ?mul0rn. Qed. (* Here is the division by n! *) Lemma nderivn_def n p : p^`(n) = p^`N(n) *+ n`!. Proof. by apply/polyP=> i; rewrite coefMn coef_nderivn coef_derivn -mulrnA bin_ffact. Qed. Lemma polyOver_nderivn (ringS : semiringClosed R) : {in polyOver ringS, forall p n, p^`N(n) \in polyOver ringS}. Proof. move=> p /polyOverP Sp /= n; apply/polyOverP=> i. by rewrite coef_nderivn rpredMn. Qed. Lemma nderivn0 p : p^`N(0) = p. Proof. by rewrite -[p^`N(0)](nderivn_def 0). Qed. Lemma nderivn1 p : p^`N(1) = p^`(). Proof. by rewrite -[p^`N(1)](nderivn_def 1). Qed. Lemma nderivnC c n : (c%:P)^`N(n) = if n == 0 then c%:P else 0. Proof. apply/polyP=> i; rewrite coef_nderivn. by case: n => [|n]; rewrite ?bin0 // coef0 coefC mul0rn. Qed. Lemma nderivnXn m n : ('X^m)^`N(n) = 'X^(m - n) *+ 'C(m, n). Proof. apply/polyP=> i; rewrite coef_nderivn coefMn !coefXn. have [lt_m_n | le_n_m] := ltnP m n. by rewrite eqn_leq leqNgt ltn_addr // mul0rn bin_small. by rewrite -{1 3}(subnKC le_n_m) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn. Qed. Fact nderivn_is_linear n : linear (nderivn n). Proof. move=> k p q; apply/polyP=> i. by rewrite !(coef_nderivn, coefD, coefZ) mulrnDl mulrnAr. Qed. HB.instance Definition _ n := GRing.isSemilinear.Build R {poly R} {poly R} _ (nderivn n) (GRing.semilinear_linear (nderivn_is_linear n)). Lemma nderivnD n : {morph nderivn n : p q / p + q}. Proof. exact: linearD. Qed. Lemma nderivnB n : {morph nderivn n : p q / p - q}. Proof. exact: linearB. Qed. Lemma nderivnMn n m p : (p *+ m)^`N(n) = p^`N(n) *+ m. Proof. exact: linearMn. Qed. Lemma nderivnMNn n m p : (p *- m)^`N(n) = p^`N(n) *- m. Proof. exact: linearMNn. Qed. Lemma nderivnN n : {morph nderivn n : p / - p}. Proof. exact: linearN. Qed. Lemma nderivnZ n : scalable (nderivn n). Proof. exact: linearZZ. Qed. Lemma nderivnMXaddC n p c : (p * 'X + c%:P)^`N(n.+1) = p^`N(n) + p^`N(n.+1) * 'X. Proof. apply/polyP=> i; rewrite coef_nderivn !coefD !coefMX coefC. rewrite !addSn /= !coef_nderivn addr0 binS mulrnDr addrC; congr (_ + _). by rewrite addSnnS; case: i; rewrite // addn0 bin_small. Qed. Lemma nderivn_poly0 p n : size p <= n -> p^`N(n) = 0. Proof. move=> le_p_n; apply/polyP=> i; rewrite coef_nderivn. rewrite nth_default; first by rewrite mul0rn coef0. exact/(leq_trans le_p_n)/leq_addr. Qed. Lemma nderiv_taylor p x h : GRing.comm x h -> p.[x + h] = \sum_(i < size p) p^`N(i).[x] * h ^+ i. Proof. move/commrX=> cxh; elim/poly_ind: p => [|p c IHp]. by rewrite size_poly0 big_ord0 horner0. rewrite hornerMXaddC size_MXaddC. have [-> | nz_p] := eqVneq p 0. rewrite horner0 !simp; have [-> | _] := c =P 0; first by rewrite big_ord0. by rewrite size_poly0 big_ord_recl big_ord0 nderivn0 hornerC !simp. rewrite big_ord_recl nderivn0 !simp hornerMXaddC addrAC; congr (_ + _). rewrite mulrDr {}IHp !big_distrl polySpred //= big_ord_recl /= mulr1 -addrA. rewrite nderivn0 /bump /(addn 1) /=; congr (_ + _). rewrite !big_ord_recr /= nderivnMXaddC -mulrA -exprSr -polySpred // !addrA. congr (_ + _); last by rewrite (nderivn_poly0 (leqnn _)) !simp. rewrite addrC -big_split /=; apply: eq_bigr => i _. by rewrite nderivnMXaddC !hornerE_comm /= mulrDl -!mulrA -exprSr cxh. Qed. Lemma nderiv_taylor_wide n p x h : GRing.comm x h -> size p <= n -> p.[x + h] = \sum_(i < n) p^`N(i).[x] * h ^+ i. Proof. move/nderiv_taylor=> -> le_p_n. rewrite (big_ord_widen n (fun i => p^`N(i).[x] * h ^+ i)) // big_mkcond. apply: eq_bigr => i _; case: leqP => // /nderivn_poly0->. by rewrite horner0 simp. Qed. Lemma eq_poly n E1 E2 : (forall i, i < n -> E1 i = E2 i) -> poly n E1 = poly n E2 :> {poly R}. Proof. by move=> E; rewrite !poly_def; apply: eq_bigr => i _; rewrite E. Qed. End PolynomialTheory. #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyN`")] Notation size_opp := size_polyN (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pchar_poly instead.")] Notation char_poly := pchar_poly (only parsing). Prenex Implicits polyC polyCK Poly polyseqK lead_coef root horner polyOver. Arguments monic {R}. Notation "\poly_ ( i < n ) E" := (poly n (fun i => E)) : ring_scope. Notation "c %:P" := (polyC c) : ring_scope. Notation "'X" := (polyX _) : ring_scope. Notation "''X^' n" := ('X ^+ n) : ring_scope. Notation "p .[ x ]" := (horner p x) : ring_scope. Notation "n .-unity_root" := (root_of_unity n) : ring_scope. Notation "n .-primitive_root" := (primitive_root_of_unity n) : ring_scope. Notation "a ^` ()" := (deriv a) : ring_scope. Notation "a ^` ( n )" := (derivn n a) : ring_scope. Notation "a ^`N ( n )" := (nderivn n a) : ring_scope. Arguments monic_pred _ _ /. Arguments monicP {R p}. Arguments rootP {R p x}. Arguments rootPf {R p x}. Arguments rootPt {R p x}. Arguments unity_rootP {R n z}. Arguments polyOver_pred _ _ _ /. Arguments polyOverP {R S p}. Arguments polyC_inj {R} [x1 x2] eq_x12P. Arguments eq_poly {R n} [E1] E2 eq_E12. Section IdomainPrimRoot. Variables (R : idomainType) (n : nat) (z : R). Hypothesis prim_z : n.-primitive_root z. Import prime. Let n_gt0 := prim_order_gt0 prim_z. Lemma prim_root_pcharF p : (p %| n)%N -> p \in [pchar R] = false. Proof. move=> pn; apply: contraTF isT => pchar_p; have p_prime := pcharf_prime pchar_p. have /dvdnP[[|k] n_eq_kp] := pn; first by rewrite n_eq_kp in (n_gt0). have /eqP := prim_expr_order prim_z; rewrite n_eq_kp exprM. rewrite -pFrobenius_autE -(pFrobenius_aut1 pchar_p) -subr_eq0 -rmorphB/=. rewrite pFrobenius_autE expf_eq0// prime_gt0//= subr_eq0 => /eqP. move=> /eqP; rewrite -(prim_order_dvd prim_z) n_eq_kp. rewrite -[X in _ %| X]muln1 dvdn_pmul2l ?dvdn1// => /eqP peq1. by rewrite peq1 in p_prime. Qed. Lemma pchar_prim_root : [pchar R]^'.-nat n. Proof. by apply/pnatP=> // p pp pn; rewrite inE/= prim_root_pcharF. Qed. Lemma prim_root_pi_eq0 m : \pi(n).-nat m -> m%:R != 0 :> R. Proof. by rewrite natf_neq0_pchar; apply: sub_in_pnat => p _; apply: pnatPpi pchar_prim_root. Qed. Lemma prim_root_dvd_eq0 m : (m %| n)%N -> m%:R != 0 :> R. Proof. case: m => [|m mn]; first by rewrite dvd0n gtn_eqF. by rewrite prim_root_pi_eq0 ?(sub_in_pnat (in1W (pi_of_dvd mn _))) ?pnat_pi. Qed. Lemma prim_root_natf_neq0 : n%:R != 0 :> R. Proof. by rewrite prim_root_dvd_eq0. Qed. End IdomainPrimRoot. #[deprecated(since="mathcomp 2.4.0", note="Use prim_root_pcharF instead.")] Notation prim_root_charF := prim_root_pcharF (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pchar_prim_root instead.")] Notation char_prim_root := pchar_prim_root (only parsing). (* Container morphism. *) Section MapPoly. Section Definitions. Variables (aR rR : nzRingType) (f : aR -> rR). Definition map_poly (p : {poly aR}) := \poly_(i < size p) f p`_i. (* Alternative definition; the one above is more convenient because it lets *) (* us use the lemmas on \poly, e.g., size (map_poly p) <= size p is an *) (* instance of size_poly. *) Lemma map_polyE p : map_poly p = Poly (map f p). Proof. rewrite /map_poly unlock; congr Poly. apply: (@eq_from_nth _ 0); rewrite size_mkseq ?size_map // => i lt_i_p. by rewrite [RHS](nth_map 0) ?nth_mkseq. Qed. Definition commr_rmorph u := forall x, GRing.comm u (f x). Definition horner_morph u of commr_rmorph u := fun p => (map_poly p).[u]. End Definitions. Variables aR rR : nzRingType. Section Combinatorial. Variables (iR : nzRingType) (f : aR -> rR). Local Notation "p ^f" := (map_poly f p) : ring_scope. Lemma map_poly0 : 0^f = 0. Proof. by rewrite map_polyE polyseq0. Qed. Lemma eq_map_poly (g : aR -> rR) : f =1 g -> map_poly f =1 map_poly g. Proof. by move=> eq_fg p; rewrite !map_polyE (eq_map eq_fg). Qed. Lemma map_poly_id g (p : {poly iR}) : {in (p : seq iR), g =1 id} -> map_poly g p = p. Proof. by move=> g_id; rewrite map_polyE map_id_in ?polyseqK. Qed. Lemma coef_map_id0 p i : f 0 = 0 -> (p^f)`_i = f p`_i. Proof. by move=> f0; rewrite coef_poly; case: ltnP => // le_p_i; rewrite nth_default. Qed. Lemma map_Poly_id0 s : f 0 = 0 -> (Poly s)^f = Poly (map f s). Proof. move=> f0; apply/polyP=> j; rewrite coef_map_id0 ?coef_Poly //. have [/(nth_map 0 0)->// | le_s_j] := ltnP j (size s). by rewrite !nth_default ?size_map. Qed. Lemma map_poly_comp_id0 (g : iR -> aR) p : f 0 = 0 -> map_poly (f \o g) p = (map_poly g p)^f. Proof. by move=> f0; rewrite map_polyE map_comp -map_Poly_id0 -?map_polyE. Qed. Lemma size_map_poly_id0 p : f (lead_coef p) != 0 -> size p^f = size p. Proof. by move=> nz_fp; apply: size_poly_eq. Qed. Lemma map_poly_eq0_id0 p : f (lead_coef p) != 0 -> (p^f == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /size_map_poly_id0->. Qed. Lemma lead_coef_map_id0 p : f 0 = 0 -> f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p). Proof. by move=> f0 nz_fp; rewrite lead_coefE coef_map_id0 ?size_map_poly_id0. Qed. Hypotheses (inj_f : injective f) (f_0 : f 0 = 0). Lemma size_map_inj_poly p : size p^f = size p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite map_poly0 !size_poly0. by rewrite size_map_poly_id0 // -f_0 (inj_eq inj_f) lead_coef_eq0. Qed. Lemma map_inj_poly : injective (map_poly f). Proof. move=> p q /polyP eq_pq; apply/polyP=> i; apply: inj_f. by rewrite -!coef_map_id0 ?eq_pq. Qed. Lemma lead_coef_map_inj p : lead_coef p^f = f (lead_coef p). Proof. by rewrite !lead_coefE size_map_inj_poly coef_map_id0. Qed. End Combinatorial. Lemma map_polyK (f : aR -> rR) g : cancel g f -> f 0 = 0 -> cancel (map_poly g) (map_poly f). Proof. by move=> gK f_0 p; rewrite /= -map_poly_comp_id0 ?map_poly_id // => x _ //=. Qed. Lemma eq_in_map_poly_id0 (f g : aR -> rR) (S : addrClosed aR) : f 0 = 0 -> g 0 = 0 -> {in S, f =1 g} -> {in polyOver S, map_poly f =1 map_poly g}. Proof. move=> f0 g0 eq_fg p pP; apply/polyP => i. by rewrite !coef_map_id0// eq_fg// (polyOverP _). Qed. Lemma eq_in_map_poly (f g : {additive aR -> rR}) (S : addrClosed aR) : {in S, f =1 g} -> {in polyOver S, map_poly f =1 map_poly g}. Proof. by move=> /eq_in_map_poly_id0; apply; rewrite //?raddf0. Qed. Section Additive. Variables (iR : nzRingType) (f : {additive aR -> rR}). Local Notation "p ^f" := (map_poly (GRing.Additive.sort f) p) : ring_scope. Lemma coef_map p i : p^f`_i = f p`_i. Proof. exact: coef_map_id0 (raddf0 f). Qed. Lemma map_Poly s : (Poly s)^f = Poly (map f s). Proof. exact: map_Poly_id0 (raddf0 f). Qed. Lemma map_poly_comp (g : iR -> aR) p : map_poly (f \o g) p = map_poly f (map_poly g p). Proof. exact: map_poly_comp_id0 (raddf0 f). Qed. Fact map_poly_is_zmod_morphism : zmod_morphism (map_poly f). Proof. by move=> p q; apply/polyP=> i; rewrite !(coef_map, coefB) raddfB. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `map_poly_is_zmod_morphism` instead")] Definition map_poly_is_additive := map_poly_is_zmod_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build {poly aR} {poly rR} (map_poly f) map_poly_is_zmod_morphism. Lemma map_polyC a : (a%:P)^f = (f a)%:P. Proof. by apply/polyP=> i; rewrite !(coef_map, coefC) -!mulrb raddfMn. Qed. Lemma lead_coef_map_eq p : f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p). Proof. exact: lead_coef_map_id0 (raddf0 f). Qed. End Additive. Variable f : {rmorphism aR -> rR}. Implicit Types p : {poly aR}. Local Notation "p ^f" := (map_poly (GRing.RMorphism.sort f) p) : ring_scope. Fact map_poly_is_monoid_morphism : monoid_morphism (map_poly f). Proof. split=> [|p q]; apply/polyP=> i. by rewrite !(coef_map, coef1) /= rmorph_nat. rewrite coef_map /= !coefM /= !rmorph_sum; apply: eq_bigr => j _. by rewrite !coef_map rmorphM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `map_poly_is_monoid_morphism` instead")] Definition map_poly_is_multiplicative := (fun g => (g.2, g.1)) map_poly_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly aR} {poly rR} (map_poly f) map_poly_is_monoid_morphism. Lemma map_polyZ c p : (c *: p)^f = f c *: p^f. Proof. by apply/polyP=> i; rewrite !(coef_map, coefZ) /= rmorphM. Qed. HB.instance Definition _ := GRing.isScalable.Build aR {poly aR} {poly rR} (f \; *:%R) (map_poly f) map_polyZ. Lemma map_polyX : ('X)^f = 'X. Proof. by apply/polyP=> i; rewrite coef_map !coefX /= rmorph_nat. Qed. Lemma map_polyXn n : ('X^n)^f = 'X^n. Proof. by rewrite rmorphXn /= map_polyX. Qed. Lemma map_polyXaddC x : ('X + x%:P)^f = 'X + (f x)%:P. Proof. by rewrite raddfD/= map_polyX map_polyC. Qed. Lemma map_polyXsubC x : ('X - x%:P)^f = 'X - (f x)%:P. Proof. by rewrite raddfB/= map_polyX map_polyC. Qed. Lemma map_prod_XsubC I (rI : seq I) P F : (\prod_(i <- rI | P i) ('X - (F i)%:P))^f = \prod_(i <- rI | P i) ('X - (f (F i))%:P). Proof. by rewrite rmorph_prod//; apply/eq_bigr => x /=; rewrite map_polyXsubC. Qed. Lemma prod_map_poly (ar : seq aR) P : \prod_(x <- map f ar | P x) ('X - x%:P) = (\prod_(x <- ar | P (f x)) ('X - x%:P))^f. Proof. by rewrite big_map map_prod_XsubC. Qed. Lemma monic_map p : p \is monic -> p^f \is monic. Proof. move/monicP=> mon_p; rewrite monicE. by rewrite lead_coef_map_eq mon_p /= rmorph1 ?oner_neq0. Qed. Lemma horner_map p x : p^f.[f x] = f p.[x]. Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !(rmorph0, horner0). rewrite hornerMXaddC !rmorphD !rmorphM /=. by rewrite map_polyX map_polyC hornerMXaddC IHp. Qed. Lemma map_comm_poly p x : comm_poly p x -> comm_poly p^f (f x). Proof. by rewrite /comm_poly horner_map -!rmorphM // => ->. Qed. Lemma map_comm_coef p x : comm_coef p x -> comm_coef p^f (f x). Proof. by move=> cpx i; rewrite coef_map -!rmorphM ?cpx. Qed. Lemma rmorph_root p x : root p x -> root p^f (f x). Proof. by move/eqP=> px0; rewrite rootE horner_map px0 rmorph0. Qed. Lemma rmorph_unity_root n z : n.-unity_root z -> n.-unity_root (f z). Proof. move/rmorph_root; rewrite rootE rmorphB hornerD hornerN. by rewrite /= map_polyXn rmorph1 hornerC hornerXn subr_eq0 unity_rootE. Qed. Section HornerMorph. Variable u : rR. Hypothesis cfu : commr_rmorph f u. Lemma horner_morphC a : horner_morph cfu a%:P = f a. Proof. by rewrite /horner_morph map_polyC hornerC. Qed. Lemma horner_morphX : horner_morph cfu 'X = u. Proof. by rewrite /horner_morph map_polyX hornerX. Qed. Fact horner_is_linear : linear_for (f \; *%R) (horner_morph cfu). Proof. by move=> c p q; rewrite /horner_morph linearP /= hornerD hornerZ. Qed. Fact horner_is_monoid_morphism : monoid_morphism (horner_morph cfu). Proof. split=> [|p q]; first by rewrite /horner_morph rmorph1 hornerC. rewrite /horner_morph rmorphM /= hornerM_comm //. by apply: comm_coef_poly => i; rewrite coef_map cfu. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `horner_is_monoid_morphism` instead")] Definition horner_is_multiplicative := (fun g => (g.2, g.1)) horner_is_monoid_morphism. HB.instance Definition _ := GRing.isSemilinear.Build aR {poly aR} rR _ (horner_morph cfu) (GRing.semilinear_linear horner_is_linear). HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly aR} rR (horner_morph cfu) horner_is_monoid_morphism. End HornerMorph. Lemma deriv_map p : p^f^`() = (p^`())^f. Proof. by apply/polyP => i; rewrite !(coef_map, coef_deriv) //= rmorphMn. Qed. Lemma derivn_map p n : p^f^`(n) = (p^`(n))^f. Proof. by apply/polyP => i; rewrite !(coef_map, coef_derivn) //= rmorphMn. Qed. Lemma nderivn_map p n : p^f^`N(n) = (p^`N(n))^f. Proof. by apply/polyP => i; rewrite !(coef_map, coef_nderivn) //= rmorphMn. Qed. End MapPoly. Lemma mapf_root (F : fieldType) (R : nzRingType) (f : {rmorphism F -> R}) (p : {poly F}) (x : F) : root (map_poly f p) (f x) = root p x. Proof. by rewrite !rootE horner_map fmorph_eq0. Qed. (* Morphisms from the polynomial ring, and the initiality of polynomials *) (* with respect to these. *) Section MorphPoly. Variable (aR rR : nzRingType) (pf : {rmorphism {poly aR} -> rR}). Lemma poly_morphX_comm : commr_rmorph (pf \o polyC) (pf 'X). Proof. by move=> a; rewrite /GRing.comm /= -!rmorphM // commr_polyX. Qed. Lemma poly_initial : pf =1 horner_morph poly_morphX_comm. Proof. apply: poly_ind => [|p a IHp]; first by rewrite !rmorph0. by rewrite !rmorphD !rmorphM /= -{}IHp horner_morphC ?horner_morphX. Qed. End MorphPoly. Notation "p ^:P" := (map_poly polyC p) : ring_scope. Section PolyCompose. Variable R : nzRingType. Implicit Types p q : {poly R}. Definition comp_poly q p := p^:P.[q]. Local Notation "p \Po q" := (comp_poly q p) : ring_scope. Lemma size_map_polyC p : size p^:P = size p. Proof. exact/(size_map_inj_poly polyC_inj). Qed. Lemma map_polyC_eq0 p : (p^:P == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 size_map_polyC. Qed. Lemma root_polyC p x : root p^:P x%:P = root p x. Proof. by rewrite rootE horner_map polyC_eq0. Qed. Lemma comp_polyE p q : p \Po q = \sum_(i < size p) p`_i *: q^+i. Proof. by rewrite [p \Po q]horner_poly; apply: eq_bigr => i _; rewrite mul_polyC. Qed. Lemma coef_comp_poly p q n : (p \Po q)`_n = \sum_(i < size p) p`_i * (q ^+ i)`_n. Proof. by rewrite comp_polyE coef_sum; apply: eq_bigr => i; rewrite coefZ. Qed. Lemma polyOver_comp (ringS : semiringClosed R) : {in polyOver ringS &, forall p q, p \Po q \in polyOver ringS}. Proof. move=> p q /polyOverP Sp Sq; rewrite comp_polyE rpred_sum // => i _. by rewrite polyOverZ ?rpredX. Qed. Lemma comp_polyCr p c : p \Po c%:P = p.[c]%:P. Proof. exact: horner_map. Qed. Lemma comp_poly0r p : p \Po 0 = (p`_0)%:P. Proof. by rewrite comp_polyCr horner_coef0. Qed. Lemma comp_polyC c p : c%:P \Po p = c%:P. Proof. by rewrite /(_ \Po p) map_polyC hornerC. Qed. Fact comp_poly_is_linear p : linear (comp_poly p). Proof. move=> a q r. by rewrite /comp_poly rmorphD /= map_polyZ !hornerE_comm mul_polyC. Qed. HB.instance Definition _ p := GRing.isSemilinear.Build R {poly R} {poly R} _ (comp_poly p) (GRing.semilinear_linear (comp_poly_is_linear p)). Lemma comp_poly0 p : 0 \Po p = 0. Proof. exact: raddf0. Qed. Lemma comp_polyD p q r : (p + q) \Po r = (p \Po r) + (q \Po r). Proof. exact: raddfD. Qed. Lemma comp_polyB p q r : (p - q) \Po r = (p \Po r) - (q \Po r). Proof. exact: raddfB. Qed. Lemma comp_polyZ c p q : (c *: p) \Po q = c *: (p \Po q). Proof. exact: linearZZ. Qed. Lemma comp_polyXr p : p \Po 'X = p. Proof. by rewrite -{2}/(idfun p) poly_initial. Qed. Lemma comp_polyX p : 'X \Po p = p. Proof. by rewrite /(_ \Po p) map_polyX hornerX. Qed. Lemma comp_poly_MXaddC c p q : (p * 'X + c%:P) \Po q = (p \Po q) * q + c%:P. Proof. by rewrite /(_ \Po q) rmorphD rmorphM /= map_polyX map_polyC hornerMXaddC. Qed. Lemma comp_polyXaddC_K p z : (p \Po ('X + z%:P)) \Po ('X - z%:P) = p. Proof. have addzK: ('X + z%:P) \Po ('X - z%:P) = 'X. by rewrite raddfD /= comp_polyC comp_polyX subrK. elim/poly_ind: p => [|p c IHp]; first by rewrite !comp_poly0. rewrite comp_poly_MXaddC linearD /= comp_polyC {1}/comp_poly rmorphM /=. by rewrite hornerM_comm /comm_poly -!/(_ \Po _) ?IHp ?addzK ?commr_polyX. Qed. Lemma size_comp_poly_leq p q : size (p \Po q) <= ((size p).-1 * (size q).-1).+1. Proof. rewrite comp_polyE (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _. rewrite (leq_trans (size_scale_leq _ _))//. rewrite (leq_trans (size_poly_exp_leq _ _))//. by rewrite ltnS mulnC leq_mul // -{2}(subnKC (valP i)) leq_addr. Qed. Lemma comp_Xn_poly p n : 'X^n \Po p = p ^+ n. Proof. by rewrite /(_ \Po p) map_polyXn hornerXn. Qed. Lemma coef_comp_poly_Xn p n i : 0 < n -> (p \Po 'X^n)`_i = if n %| i then p`_(i %/ n) else 0. Proof. move=> n_gt0; rewrite comp_polyE; under eq_bigr do rewrite -exprM mulnC. rewrite coef_sumMXn/=; case: dvdnP => [[j ->]|nD]; last first. by rewrite big1// => j /eqP ?; case: nD; exists j. under eq_bigl do rewrite eqn_mul2r gtn_eqF//. by rewrite big_ord1_eq if_nth ?leqVgt ?mulnK. Qed. Lemma comp_poly_Xn p n : 0 < n -> p \Po 'X^n = \poly_(i < size p * n) if n %| i then p`_(i %/ n) else 0. Proof. move=> n_gt0; apply/polyP => i; rewrite coef_comp_poly_Xn // coef_poly. case: dvdnP => [[k ->]|]; last by rewrite if_same. by rewrite mulnK // ltn_mul2r n_gt0 if_nth ?leqVgt. Qed. End PolyCompose. Notation "p \Po q" := (comp_poly q p) : ring_scope. Lemma map_comp_poly (aR rR : nzRingType) (f : {rmorphism aR -> rR}) p q : map_poly f (p \Po q) = map_poly f p \Po map_poly f q. Proof. elim/poly_ind: p => [|p a IHp]; first by rewrite !raddf0. rewrite comp_poly_MXaddC !rmorphD !rmorphM /= !map_polyC map_polyX. by rewrite comp_poly_MXaddC -IHp. Qed. Section Surgery. Variable R : nzRingType. Implicit Type p q : {poly R}. (* Even part of a polynomial *) Definition even_poly p : {poly R} := \poly_(i < uphalf (size p)) p`_i.*2. Lemma size_even_poly p : size (even_poly p) <= uphalf (size p). Proof. exact: size_poly. Qed. Lemma coef_even_poly p i : (even_poly p)`_i = p`_i.*2. Proof. by rewrite coef_poly gtn_uphalf_double if_nth ?leqVgt. Qed. Lemma even_polyE s p : size p <= s.*2 -> even_poly p = \poly_(i < s) p`_i.*2. Proof. move=> pLs2; apply/polyP => i; rewrite coef_even_poly !coef_poly if_nth //. by case: ltnP => //= ?; rewrite (leq_trans pLs2) ?leq_double. Qed. Lemma size_even_poly_eq p : odd (size p) -> size (even_poly p) = uphalf (size p). Proof. move=> p_even; rewrite size_poly_eq// double_pred odd_uphalfK//=. by rewrite lead_coef_eq0 -size_poly_eq0; case: size p_even. Qed. Lemma even_polyD p q : even_poly (p + q) = even_poly p + even_poly q. Proof. by apply/polyP => i; rewrite !(coef_even_poly, coefD). Qed. Lemma even_polyZ k p : even_poly (k *: p) = k *: even_poly p. Proof. by apply/polyP => i; rewrite !(coefZ, coef_even_poly). Qed. Fact even_poly_is_linear : linear even_poly. Proof. by move=> k p q; rewrite even_polyD even_polyZ. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly R} _ even_poly (GRing.semilinear_linear even_poly_is_linear). Lemma even_polyC (c : R) : even_poly c%:P = c%:P. Proof. by apply/polyP => i; rewrite coef_even_poly !coefC; case: i. Qed. (* Odd part of a polynomial *) Definition odd_poly p : {poly R} := \poly_(i < (size p)./2) p`_i.*2.+1. Lemma size_odd_poly p : size (odd_poly p) <= (size p)./2. Proof. exact: size_poly. Qed. Lemma coef_odd_poly p i : (odd_poly p)`_i = p`_i.*2.+1. Proof. by rewrite coef_poly gtn_half_double if_nth ?leqVgt. Qed. Lemma odd_polyE s p : size p <= s.*2.+1 -> odd_poly p = \poly_(i < s) p`_i.*2.+1. Proof. move=> pLs2; apply/polyP => i; rewrite coef_odd_poly !coef_poly if_nth //. by case: ltnP => //= ?; rewrite (leq_trans pLs2) ?ltnS ?leq_double. Qed. Lemma odd_polyC (c : R) : odd_poly c%:P = 0. Proof. by apply/polyP => i; rewrite coef_odd_poly !coefC; case: i. Qed. Lemma odd_polyD p q : odd_poly (p + q) = odd_poly p + odd_poly q. Proof. by apply/polyP => i; rewrite !(coef_odd_poly, coefD). Qed. Lemma odd_polyZ k p : odd_poly (k *: p) = k *: odd_poly p. Proof. by apply/polyP => i; rewrite !(coefZ, coef_odd_poly). Qed. Fact odd_poly_is_linear : linear odd_poly. Proof. by move=> k p q; rewrite odd_polyD odd_polyZ. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly R} _ odd_poly (GRing.semilinear_linear odd_poly_is_linear). Lemma size_odd_poly_eq p : ~~ odd (size p) -> size (odd_poly p) = (size p)./2. Proof. have [->|p_neq0] := eqVneq p 0; first by rewrite odd_polyC size_poly0. move=> p_odd; rewrite size_poly_eq// -subn1 doubleB subn2 even_halfK//. rewrite prednK ?lead_coef_eq0// ltn_predRL. by move: p_neq0 p_odd; rewrite -size_poly_eq0; case: (size p) => [|[]]. Qed. Lemma odd_polyMX p : odd_poly (p * 'X) = even_poly p. Proof. have [->|pN0] := eqVneq p 0; first by rewrite mul0r even_polyC odd_polyC. by apply/polyP => i; rewrite !coef_poly size_mulX // coefMX. Qed. Lemma even_polyMX p : even_poly (p * 'X) = odd_poly p * 'X. Proof. have [->|pN0] := eqVneq p 0; first by rewrite mul0r even_polyC odd_polyC mul0r. by apply/polyP => -[|i]; rewrite !(coefMX, coef_poly, if_same, size_mulX). Qed. Lemma sum_even_poly p : \sum_(i < size p | ~~ odd i) p`_i *: 'X^i = even_poly p \Po 'X^2. Proof. apply/polyP => i; rewrite coef_comp_poly_Xn// coef_sumMXn coef_even_poly. rewrite (big_ord1_cond_eq _ _ (negb \o _))/= -dvdn2 andbC -muln2. by case: dvdnP => //= -[k ->]; rewrite mulnK// if_nth ?leqVgt. Qed. Lemma sum_odd_poly p : \sum_(i < size p | odd i) p`_i *: 'X^i = (odd_poly p \Po 'X^2) * 'X. Proof. apply/polyP => i; rewrite coefMX coef_comp_poly_Xn// coef_sumMXn coef_odd_poly/=. case: i => [|i]//=; first by rewrite big_andbC big1// => -[[|j]//]. rewrite big_ord1_cond_eq/= -dvdn2 andbC -muln2. by case: dvdnP => //= -[k ->]; rewrite mulnK// if_nth ?leqVgt. Qed. (* Decomposition in odd and even part *) Lemma poly_even_odd p : even_poly p \Po 'X^2 + (odd_poly p \Po 'X^2) * 'X = p. Proof. rewrite -sum_even_poly -sum_odd_poly addrC -(bigID _ xpredT). by rewrite -[RHS]coefK poly_def. Qed. (* take and drop for polynomials *) Definition take_poly m p := \poly_(i < m) p`_i. Lemma size_take_poly m p : size (take_poly m p) <= m. Proof. exact: size_poly. Qed. Lemma coef_take_poly m p i : (take_poly m p)`_i = if i < m then p`_i else 0. Proof. exact: coef_poly. Qed. Lemma take_poly_id m p : size p <= m -> take_poly m p = p. Proof. move=> /leq_trans gep; apply/polyP => i; rewrite coef_poly if_nth//=. by case: ltnP => // /gep->. Qed. Lemma take_polyD m p q : take_poly m (p + q) = take_poly m p + take_poly m q. Proof. by apply/polyP => i; rewrite !(coefD, coef_poly); case: leqP; rewrite ?add0r. Qed. Lemma take_polyZ k m p : take_poly m (k *: p) = k *: take_poly m p. Proof. apply/polyP => i; rewrite !(coefZ, coef_take_poly); case: leqP => //. by rewrite mulr0. Qed. Fact take_poly_is_linear m : linear (take_poly m). Proof. by move=> k p q; rewrite take_polyD take_polyZ. Qed. HB.instance Definition _ m := GRing.isSemilinear.Build R {poly R} {poly R} _ (take_poly m) (GRing.semilinear_linear (take_poly_is_linear m)). Lemma take_poly_sum m I r P (p : I -> {poly R}) : take_poly m (\sum_(i <- r | P i) p i) = \sum_(i <- r| P i) take_poly m (p i). Proof. exact: linear_sum. Qed. Lemma take_poly0l p : take_poly 0 p = 0. Proof. exact/size_poly_leq0P/size_take_poly. Qed. Lemma take_poly0r m : take_poly m 0 = 0. Proof. exact: linear0. Qed. Lemma take_polyMXn m n p : take_poly m (p * 'X^n) = take_poly (m - n) p * 'X^n. Proof. have [->|/eqP p_neq0] := p =P 0; first by rewrite !(mul0r, take_poly0r). apply/polyP => i; rewrite !(coef_take_poly, coefMXn). by have [iLn|nLi] := leqP n i; rewrite ?if_same// ltn_sub2rE. Qed. Lemma take_polyMXn_0 n p : take_poly n (p * 'X^n) = 0. Proof. by rewrite take_polyMXn subnn take_poly0l mul0r. Qed. Lemma take_polyDMXn n p q : size p <= n -> take_poly n (p + q * 'X^n) = p. Proof. by move=> ?; rewrite take_polyD take_poly_id// take_polyMXn_0 addr0. Qed. Definition drop_poly m p := \poly_(i < size p - m) p`_(i + m). Lemma coef_drop_poly m p i : (drop_poly m p)`_i = p`_(i + m). Proof. by rewrite coef_poly ltn_subRL addnC if_nth ?leqVgt. Qed. Lemma drop_poly_eq0 m p : size p <= m -> drop_poly m p = 0. Proof. move=> sLm; apply/polyP => i; rewrite coef_poly coef0 ltn_subRL addnC. by rewrite if_nth ?leqVgt// nth_default// (leq_trans _ (leq_addl _ _)). Qed. Lemma size_drop_poly n p : size (drop_poly n p) = (size p - n)%N. Proof. have [pLn|nLp] := leqP (size p) n. by rewrite (eqP pLn) drop_poly_eq0 ?size_poly0. have p_neq0 : p != 0 by rewrite -size_poly_gt0 (leq_trans _ nLp). by rewrite size_poly_eq// predn_sub subnK ?lead_coef_eq0// -ltnS -polySpred. Qed. Lemma sum_drop_poly n p : \sum_(n <= i < size p) p`_i *: 'X^i = drop_poly n p * 'X^n. Proof. rewrite (big_addn 0) big_mkord /drop_poly poly_def mulr_suml. by apply: eq_bigr => i _; rewrite exprD scalerAl. Qed. Lemma drop_polyD m p q : drop_poly m (p + q) = drop_poly m p + drop_poly m q. Proof. by apply/polyP => i; rewrite coefD !coef_drop_poly coefD. Qed. Lemma drop_polyZ k m p : drop_poly m (k *: p) = k *: drop_poly m p. Proof. by apply/polyP => i; rewrite coefZ !coef_drop_poly coefZ. Qed. Fact drop_poly_is_linear m : linear (drop_poly m). Proof. by move=> k p q; rewrite drop_polyD drop_polyZ. Qed. HB.instance Definition _ m := GRing.isSemilinear.Build R {poly R} {poly R} _ (drop_poly m) (GRing.semilinear_linear (drop_poly_is_linear m)). Lemma drop_poly_sum m I r P (p : I -> {poly R}) : drop_poly m (\sum_(i <- r | P i) p i) = \sum_(i <- r | P i) drop_poly m (p i). Proof. exact: linear_sum. Qed. Lemma drop_poly0l p : drop_poly 0 p = p. Proof. by apply/polyP => i; rewrite coef_poly subn0 addn0 if_nth ?leqVgt. Qed. Lemma drop_poly0r m : drop_poly m 0 = 0. Proof. exact: linear0. Qed. Lemma drop_polyMXn m n p : drop_poly m (p * 'X^n) = drop_poly (m - n) p * 'X^(n - m). Proof. have [->|p_neq0] := eqVneq p 0; first by rewrite mul0r !drop_poly0r mul0r. apply/polyP => i; rewrite !(coefMXn, coef_drop_poly) ltn_subRL [(m + i)%N]addnC. have [i_small|i_big]// := ltnP; congr nth. by have [mn|/ltnW mn] := leqP m n; rewrite (eqP mn) (addn0, subn0) (subnBA, addnBA). Qed. Lemma drop_polyMXn_id n p : drop_poly n (p * 'X^ n) = p. Proof. by rewrite drop_polyMXn subnn drop_poly0l expr0 mulr1. Qed. Lemma drop_polyDMXn n p q : size p <= n -> drop_poly n (p + q * 'X^n) = q. Proof. by move=> ?; rewrite drop_polyD drop_poly_eq0// drop_polyMXn_id add0r. Qed. Lemma poly_take_drop n p : take_poly n p + drop_poly n p * 'X^n = p. Proof. apply/polyP => i; rewrite coefD coefMXn coef_take_poly coef_drop_poly. by case: ltnP => ni; rewrite ?addr0 ?add0r//= subnK. Qed. Lemma eqp_take_drop n p q : take_poly n p = take_poly n q -> drop_poly n p = drop_poly n q -> p = q. Proof. by move=> tpq dpq; rewrite -[p](poly_take_drop n) -[q](poly_take_drop n) tpq dpq. Qed. End Surgery. Definition coefE := (coef0, coef1, coefC, coefX, coefXn, coef_sumMXn, coefZ, coefMC, coefCM, coefXnM, coefMXn, coefXM, coefMX, coefMNn, coefMn, coefN, coefB, coefD, coef_even_poly, coef_odd_poly, coef_take_poly, coef_drop_poly, coef_cons, coef_Poly, coef_poly, coef_deriv, coef_nderivn, coef_derivn, coef_map, coef_sum, coef_comp_poly_Xn, coef_comp_poly). Section PolynomialComNzRing. Variable R : comNzRingType. Implicit Types p q : {poly R}. Fact poly_mul_comm p q : p * q = q * p. Proof. apply/polyP=> i; rewrite coefM coefMr. by apply: eq_bigr => j _; rewrite mulrC. Qed. HB.instance Definition _ := GRing.PzRing_hasCommutativeMul.Build (polynomial R) poly_mul_comm. HB.instance Definition _ := GRing.Lalgebra_isComAlgebra.Build R (polynomial R). Lemma coef_prod_XsubC (ps : seq R) (n : nat) : (n <= size ps)%N -> (\prod_(p <- ps) ('X - p%:P))`_n = (-1) ^+ (size ps - n)%N * \sum_(I in {set 'I_(size ps)} | #|I| == (size ps - n)%N) \prod_(i in I) ps`_i. Proof. move=> nle. under eq_bigr => i _ do rewrite addrC -raddfN/=. rewrite -{1}(in_tupleE ps) -(map_tnth_enum (_ ps)) big_map. rewrite enumT bigA_distr /= coef_sum. transitivity (\sum_(I in {set 'I_(size ps)}) if #|I| == (size ps - n)%N then \prod_(i < size ps | i \in I) - ps`_i else 0). apply eq_bigr => I _. rewrite big_if/= big_const iter_mulr_1 -rmorph_prod/= coefCM coefXn. under eq_bigr => i _ do rewrite (tnth_nth 0)/=. rewrite -[#|I| == _](eqn_add2r n) subnK//. rewrite -[X in (_ + _)%N == X]card_ord -(cardC I) eqn_add2l. by case: ifP; rewrite ?mulr1 ?mulr0. by rewrite -big_mkcond mulr_sumr/=; apply: eq_bigr => I /eqP <-; rewrite prodrN. Qed. Lemma coefPn_prod_XsubC (ps : seq R) : size ps != 0 -> (\prod_(p <- ps) ('X - p%:P))`_(size ps).-1 = - \sum_(p <- ps) p. Proof. rewrite coef_prod_XsubC ?leq_pred// => ps0. have -> : (size ps - (size ps).-1 = 1)%N. by move: ps0; case: (size ps) => // n _; exact: subSnn. rewrite expr1 mulN1r; congr GRing.opp. set f : 'I_(size ps) -> {set 'I_(size ps)} := fun a => [set a]. transitivity (\sum_(I in imset f (mem setT)) \prod_(i in I) ps`_i). apply: congr_big => // I /=. by apply/cards1P/imsetP => [[a ->] | [a _ ->]]; exists a. rewrite big_imset/=; last first. by move=> i j _ _ ij; apply/set1P; rewrite -/(f j) -ij set11. rewrite -[in RHS](in_tupleE ps) -(map_tnth_enum (_ ps)) big_map enumT. apply: congr_big => // i; first exact: in_setT. by rewrite big_set1 (tnth_nth 0). Qed. Lemma coef0_prod_XsubC (ps : seq R) : (\prod_(p <- ps) ('X - p%:P))`_0 = (-1) ^+ (size ps) * \prod_(p <- ps) p. Proof. rewrite coef_prod_XsubC// subn0; congr GRing.mul. transitivity (\sum_(I in [set setT : {set 'I_(size ps)}]) \prod_(i in I) ps`_i). apply: congr_big =>// i/=. apply/idP/set1P => [/eqP cardE | ->]; last by rewrite cardsT card_ord. by apply/eqP; rewrite eqEcard subsetT cardsT card_ord cardE leqnn. rewrite big_set1 -[in RHS](in_tupleE ps) -(map_tnth_enum (_ ps)) big_map enumT. apply: congr_big => // i; first exact: in_setT. by rewrite (tnth_nth 0). Qed. Lemma hornerM p q x : (p * q).[x] = p.[x] * q.[x]. Proof. by rewrite hornerM_comm //; apply: mulrC. Qed. Lemma horner_exp p x n : (p ^+ n).[x] = p.[x] ^+ n. Proof. by rewrite horner_exp_comm //; apply: mulrC. Qed. Lemma horner_prod I r (P : pred I) (F : I -> {poly R}) x : (\prod_(i <- r | P i) F i).[x] = \prod_(i <- r | P i) (F i).[x]. Proof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (hornerM, hornerC). Qed. Definition hornerE := (hornerD, hornerN, hornerX, hornerC, horner_exp, simp, hornerCM, hornerZ, hornerM, horner_cons). Definition horner_eval (x : R) := horner^~ x. Lemma horner_evalE x p : horner_eval x p = p.[x]. Proof. by []. Qed. Fact horner_eval_is_linear x : linear_for *%R (horner_eval x). Proof. have cxid: commr_rmorph idfun x by apply: mulrC. have evalE : horner_eval x =1 horner_morph cxid. by move=> p; congr _.[x]; rewrite map_poly_id. by move=> c p q; rewrite !evalE linearP. Qed. Fact horner_eval_is_monoid_morphism x : monoid_morphism (horner_eval x). Proof. have cxid: commr_rmorph idfun x by apply: mulrC. have evalE : horner_eval x =1 horner_morph cxid. by move=> p; congr _.[x]; rewrite map_poly_id. by split=> [|p q]; rewrite !evalE ?rmorph1// rmorphM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `horner_eval_is_monoid_morphism` instead")] Definition horner_eval_is_multiplicative x := (fun g => (g.2, g.1)) (horner_eval_is_monoid_morphism x). HB.instance Definition _ x := GRing.isSemilinear.Build R {poly R} R _ (horner_eval x) (GRing.semilinear_linear (horner_eval_is_linear x)). HB.instance Definition _ x := GRing.isMonoidMorphism.Build {poly R} R (horner_eval x) (horner_eval_is_monoid_morphism x). Section HornerAlg. Variable A : algType R. (* For univariate polys, commutativity is not needed *) Section Defs. Variable a : A. Lemma in_alg_comm : commr_rmorph (in_alg A) a. Proof. move=> r /=; by rewrite /GRing.comm comm_alg. Qed. Definition horner_alg := horner_morph in_alg_comm. Lemma horner_algC c : horner_alg c%:P = c%:A. Proof. exact: horner_morphC. Qed. Lemma horner_algX : horner_alg 'X = a. Proof. exact: horner_morphX. Qed. HB.instance Definition _ := GRing.LRMorphism.on horner_alg. End Defs. Variable (pf : {lrmorphism {poly R} -> A}). Lemma poly_alg_initial : pf =1 horner_alg (pf 'X). Proof. apply: poly_ind => [|p a IHp]; first by rewrite !rmorph0. rewrite !rmorphD !rmorphM /= -{}IHp horner_algC ?horner_algX. by rewrite -alg_polyC rmorph_alg. Qed. End HornerAlg. Fact comp_poly_is_monoid_morphism q : monoid_morphism (comp_poly q). Proof. split=> [|p1 p2]; first by rewrite comp_polyC. by rewrite /comp_poly rmorphM hornerM_comm //; apply: mulrC. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `comp_poly_is_monoid_morphism` instead")] Definition comp_poly_multiplicative q := (fun g => (g.2, g.1)) (comp_poly_is_monoid_morphism q). HB.instance Definition _ q := GRing.isMonoidMorphism.Build _ _ (comp_poly q) (comp_poly_is_monoid_morphism q). Lemma comp_polyM p q r : (p * q) \Po r = (p \Po r) * (q \Po r). Proof. exact: rmorphM. Qed. Lemma comp_polyA p q r : p \Po (q \Po r) = (p \Po q) \Po r. Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !comp_polyC. by rewrite !comp_polyD !comp_polyM !comp_polyX IHp !comp_polyC. Qed. Lemma horner_comp p q x : (p \Po q).[x] = p.[q.[x]]. Proof. by apply: polyC_inj; rewrite -!comp_polyCr comp_polyA. Qed. Lemma root_comp p q x : root (p \Po q) x = root p (q.[x]). Proof. by rewrite !rootE horner_comp. Qed. Lemma deriv_comp p q : (p \Po q) ^`() = (p ^`() \Po q) * q^`(). Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !(deriv0, comp_poly0) mul0r. rewrite comp_poly_MXaddC derivD derivC derivM IHp derivMXaddC comp_polyD. by rewrite comp_polyM comp_polyX addr0 addrC mulrAC -mulrDl. Qed. Lemma deriv_exp p n : (p ^+ n)^`() = p^`() * p ^+ n.-1 *+ n. Proof. elim: n => [|n IHn]; first by rewrite expr0 mulr0n derivC. by rewrite exprS derivM {}IHn (mulrC p) mulrnAl -mulrA -exprSr mulrS; case n. Qed. Definition derivCE := (derivE, deriv_exp). End PolynomialComNzRing. Section PolynomialIdomain. (* Integral domain structure on poly *) Variable R : idomainType. Implicit Types (a b x y : R) (p q r m : {poly R}). Lemma size_mul p q : p != 0 -> q != 0 -> size (p * q) = (size p + size q).-1. Proof. by move=> nz_p nz_q; rewrite -size_proper_mul ?mulf_neq0 ?lead_coef_eq0. Qed. Fact poly_idomainAxiom p q : p * q = 0 -> (p == 0) || (q == 0). Proof. move=> pq0; apply/norP=> [[p_nz q_nz]]; move/eqP: (size_mul p_nz q_nz). by rewrite eq_sym pq0 size_poly0 (polySpred p_nz) (polySpred q_nz) addnS. Qed. Definition poly_unit : pred {poly R} := fun p => (size p == 1) && (p`_0 \in GRing.unit). Definition poly_inv p := if p \in poly_unit then (p`_0)^-1%:P else p. Fact poly_mulVp : {in poly_unit, left_inverse 1 poly_inv *%R}. Proof. move=> p Up; rewrite /poly_inv Up. by case/andP: Up => /size_poly1P[c _ ->]; rewrite coefC -polyCM => /mulVr->. Qed. Fact poly_intro_unit p q : q * p = 1 -> p \in poly_unit. Proof. move=> pq1; apply/andP; split; last first. apply/unitrP; exists q`_0. by rewrite 2!mulrC -!/(coefp 0 _) -rmorphM pq1 rmorph1. have: size (q * p) == 1 by rewrite pq1 size_poly1. have [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0. have [-> | nz_q] := eqVneq q 0; first by rewrite mul0r size_poly0. rewrite size_mul // (polySpred nz_p) (polySpred nz_q) addnS addSn !eqSS. by rewrite addn_eq0 => /andP[]. Qed. Fact poly_inv_out : {in [predC poly_unit], poly_inv =1 id}. Proof. by rewrite /poly_inv => p /negbTE/= ->. Qed. HB.instance Definition _ := GRing.ComNzRing_hasMulInverse.Build (polynomial R) poly_mulVp poly_intro_unit poly_inv_out. HB.instance Definition _ := GRing.ComUnitRing_isIntegral.Build (polynomial R) poly_idomainAxiom. Lemma poly_unitE p : (p \in GRing.unit) = (size p == 1) && (p`_0 \in GRing.unit). Proof. by []. Qed. Lemma poly_invE p : p ^-1 = if p \in GRing.unit then (p`_0)^-1%:P else p. Proof. by []. Qed. Lemma polyCV c : c%:P^-1 = (c^-1)%:P. Proof. have [/rmorphV-> // | nUc] := boolP (c \in GRing.unit). by rewrite !invr_out // poly_unitE coefC (negbTE nUc) andbF. Qed. Lemma rootM p q x : root (p * q) x = root p x || root q x. Proof. by rewrite !rootE hornerM mulf_eq0. Qed. Lemma rootZ x a p : a != 0 -> root (a *: p) x = root p x. Proof. by move=> nz_a; rewrite -mul_polyC rootM rootC (negPf nz_a). Qed. Lemma root_exp p n a: comm_poly p a -> (0 < n)%N -> root (p ^+ n) a = root p a. Proof. by move=> ? n0; rewrite !rootE horner_exp_comm// expf_eq0 n0. Qed. Lemma size_scale a p : a != 0 -> size (a *: p) = size p. Proof. by move/lregP/lreg_size->. Qed. Lemma size_Cmul a p : a != 0 -> size (a%:P * p) = size p. Proof. by rewrite mul_polyC => /size_scale->. Qed. Lemma lead_coefM p q : lead_coef (p * q) = lead_coef p * lead_coef q. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, lead_coef0). have [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, lead_coef0). by rewrite lead_coef_proper_mul // mulf_neq0 ?lead_coef_eq0. Qed. Lemma lead_coef_prod I rI (P : {pred I}) (p : I -> {poly R}) : lead_coef (\prod_(i <- rI | P i) p i) = \prod_(i <- rI | P i) lead_coef (p i). Proof. by apply/big_morph/lead_coef1; apply: lead_coefM. Qed. Lemma lead_coefZ a p : lead_coef (a *: p) = a * lead_coef p. Proof. by rewrite -mul_polyC lead_coefM lead_coefC. Qed. Lemma scale_poly_eq0 a p : (a *: p == 0) = (a == 0) || (p == 0). Proof. by rewrite -mul_polyC mulf_eq0 polyC_eq0. Qed. Lemma size_prod (I : finType) (P : pred I) (F : I -> {poly R}) : (forall i, P i -> F i != 0) -> size (\prod_(i | P i) F i) = ((\sum_(i | P i) size (F i)).+1 - #|P|)%N. Proof. move=> nzF; transitivity (\sum_(i | P i) (size (F i)).-1).+1; last first. apply: canRL (addKn _) _; rewrite addnS -sum1_card -big_split /=. by congr _.+1; apply: eq_bigr => i /nzF/polySpred. elim/big_rec2: _ => [|i d p /nzF nzFi IHp]; first by rewrite size_poly1. by rewrite size_mul // -?size_poly_eq0 IHp // addnS polySpred. Qed. Lemma size_prod_seq (I : eqType) (s : seq I) (F : I -> {poly R}) : (forall i, i \in s -> F i != 0) -> size (\prod_(i <- s) F i) = ((\sum_(i <- s) size (F i)).+1 - size s)%N. Proof. move=> nzF; rewrite big_tnth size_prod; last by move=> i; rewrite nzF ?mem_tnth. by rewrite cardT /= size_enum_ord [in RHS]big_tnth. Qed. Lemma size_mul_eq1 p q : (size (p * q) == 1) = ((size p == 1) && (size q == 1)). Proof. have [->|pNZ] := eqVneq p 0; first by rewrite mul0r size_poly0. have [->|qNZ] := eqVneq q 0; first by rewrite mulr0 size_poly0 andbF. rewrite size_mul //. by move: pNZ qNZ; rewrite -!size_poly_gt0; (do 2 case: size) => //= n [|[|]]. Qed. Lemma size_prod_seq_eq1 (I : eqType) (s : seq I) (P : pred I) (F : I -> {poly R}) : reflect (forall i, P i && (i \in s) -> size (F i) = 1) (size (\prod_(i <- s | P i) F i) == 1%N). Proof. rewrite (big_morph _ (id1:=true) size_mul_eq1) ?size_polyC ?oner_neq0//. rewrite big_all_cond; apply/(iffP allP). by move=> h i /andP[Pi ins]; apply/eqP/(implyP (h i ins) Pi). by move=> h i ins; apply/implyP => Pi; rewrite h ?Pi. Qed. Lemma size_prod_eq1 (I : finType) (P : pred I) (F : I -> {poly R}) : reflect (forall i, P i -> size (F i) = 1) (size (\prod_(i | P i) F i) == 1). Proof. apply: (iffP (size_prod_seq_eq1 _ _ _)) => Hi i. by move=> Pi; apply: Hi; rewrite Pi /= mem_index_enum. by rewrite mem_index_enum andbT; apply: Hi. Qed. Lemma size_exp p n : (size (p ^+ n)).-1 = ((size p).-1 * n)%N. Proof. elim: n => [|n IHn]; first by rewrite size_poly1 muln0. have [-> | nz_p] := eqVneq p 0; first by rewrite exprS mul0r size_poly0. rewrite exprS size_mul ?expf_neq0 // mulnS -{}IHn. by rewrite polySpred // [size (p ^+ n)]polySpred ?expf_neq0 ?addnS. Qed. Lemma lead_coef_exp p n : lead_coef (p ^+ n) = lead_coef p ^+ n. Proof. elim: n => [|n IHn]; first by rewrite !expr0 lead_coef1. by rewrite !exprS lead_coefM IHn. Qed. Lemma root_prod_XsubC rs x : root (\prod_(a <- rs) ('X - a%:P)) x = (x \in rs). Proof. elim: rs => [|a rs IHrs]; first by rewrite rootE big_nil hornerC oner_eq0. by rewrite big_cons rootM IHrs root_XsubC. Qed. Lemma root_exp_XsubC n a x : root (('X - a%:P) ^+ n.+1) x = (x == a). Proof. by rewrite rootE horner_exp expf_eq0 [_ == 0]root_XsubC. Qed. Lemma size_comp_poly p q : (size (p \Po q)).-1 = ((size p).-1 * (size q).-1)%N. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite comp_poly0 size_poly0. have [/size1_polyC-> | nc_q] := leqP (size q) 1. by rewrite comp_polyCr !size_polyC -!sub1b -!subnS muln0. have nz_q: q != 0 by rewrite -size_poly_eq0 -(subnKC nc_q). rewrite mulnC comp_polyE (polySpred nz_p) /= big_ord_recr /= addrC. rewrite size_polyDl size_scale ?lead_coef_eq0 ?size_exp //=. rewrite [ltnRHS]polySpred ?expf_neq0 // ltnS size_exp. rewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _. rewrite (leq_trans (size_scale_leq _ _)) // polySpred ?expf_neq0 //. by rewrite size_exp -(subnKC nc_q) ltn_pmul2l. Qed. Lemma lead_coef_comp p q : size q > 1 -> lead_coef (p \Po q) = (lead_coef p) * lead_coef q ^+ (size p).-1. Proof. move=> q_gt1; rewrite !lead_coefE coef_comp_poly size_comp_poly. have [->|nz_p] := eqVneq p 0; first by rewrite size_poly0 big_ord0 coef0 mul0r. rewrite polySpred //= big_ord_recr /= big1 ?add0r => [|i _]. by rewrite -!lead_coefE -lead_coef_exp !lead_coefE size_exp mulnC. rewrite [X in _ * X]nth_default ?mulr0 ?(leq_trans (size_poly_exp_leq _ _)) //. by rewrite mulnC ltn_mul2r -subn1 subn_gt0 q_gt1 /=. Qed. Lemma comp_poly_eq0 p q : size q > 1 -> (p \Po q == 0) = (p == 0). Proof. move=> sq_gt1; rewrite -!lead_coef_eq0 lead_coef_comp //. rewrite mulf_eq0 expf_eq0 !lead_coef_eq0 -[q == 0]size_poly_leq0. by rewrite [_ <= 0]leqNgt (leq_ltn_trans _ sq_gt1) ?andbF ?orbF. Qed. Lemma size_comp_poly2 p q : size q = 2 -> size (p \Po q) = size p. Proof. move=> sq2; have [->|pN0] := eqVneq p 0; first by rewrite comp_polyC. by rewrite polySpred ?size_comp_poly ?comp_poly_eq0 ?sq2 // muln1 polySpred. Qed. Lemma comp_poly2_eq0 p q : size q = 2 -> (p \Po q == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /size_comp_poly2->. Qed. Theorem max_poly_roots p rs : p != 0 -> all (root p) rs -> uniq rs -> size rs < size p. Proof. elim: rs p => [p pn0 _ _ | r rs ihrs p pn0] /=; first by rewrite size_poly_gt0. case/andP => rpr arrs /andP [rnrs urs]; case/factor_theorem: rpr => q epq. have [q0 | ?] := eqVneq q 0; first by move: pn0; rewrite epq q0 mul0r eqxx. have -> : size p = (size q).+1. by rewrite epq size_Mmonic ?monicXsubC // size_XsubC addnC. suff /eq_in_all h : {in rs, root q =1 root p} by apply: ihrs => //; rewrite h. move=> x xrs; rewrite epq rootM root_XsubC orbC; case: (eqVneq x r) => // exr. by move: rnrs; rewrite -exr xrs. Qed. Lemma roots_geq_poly_eq0 p (rs : seq R) : all (root p) rs -> uniq rs -> (size rs >= size p)%N -> p = 0. Proof. by move=> ??; apply: contraTeq => ?; rewrite leqNgt max_poly_roots. Qed. End PolynomialIdomain. (* FIXME: these are seamingly artificial ways to close the inheritance graph *) (* We make parameters more and more precise to trigger completion by HB *) HB.instance Definition _ (R : countNzRingType) := [Countable of polynomial R by <:]. HB.instance Definition _ (R : countComNzRingType) := [Countable of polynomial R by <:]. HB.instance Definition _ (R : countIdomainType) := [Countable of polynomial R by <:]. Section MapFieldPoly. Variables (F : fieldType) (R : nzRingType) (f : {rmorphism F -> R}). Local Notation "p ^f" := (map_poly f p) : ring_scope. Lemma size_map_poly p : size p^f = size p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite rmorph0 !size_poly0. by rewrite size_poly_eq // fmorph_eq0 // lead_coef_eq0. Qed. Lemma lead_coef_map p : lead_coef p^f = f (lead_coef p). Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !(rmorph0, lead_coef0). by rewrite lead_coef_map_eq // fmorph_eq0 // lead_coef_eq0. Qed. Lemma map_poly_eq0 p : (p^f == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 size_map_poly. Qed. Lemma map_poly_inj : injective (map_poly f). Proof. move=> p q eqfpq; apply/eqP; rewrite -subr_eq0 -map_poly_eq0. by rewrite rmorphB /= eqfpq subrr. Qed. Lemma map_monic p : (p^f \is monic) = (p \is monic). Proof. by rewrite [in LHS]monicE lead_coef_map fmorph_eq1. Qed. Lemma map_poly_com p x : comm_poly p^f (f x). Proof. exact: map_comm_poly (mulrC x _). Qed. Lemma fmorph_root p x : root p^f (f x) = root p x. Proof. by rewrite rootE horner_map // fmorph_eq0. Qed. Lemma fmorph_unity_root n z : n.-unity_root (f z) = n.-unity_root z. Proof. by rewrite !unity_rootE -(inj_eq (fmorph_inj f)) rmorphXn ?rmorph1. Qed. Lemma fmorph_primitive_root n z : n.-primitive_root (f z) = n.-primitive_root z. Proof. by congr (_ && _); apply: eq_forallb => i; rewrite fmorph_unity_root. Qed. End MapFieldPoly. Arguments map_poly_inj {F R} f [p1 p2] : rename. Section MaxRoots. Variable R : unitRingType. Implicit Types (x y : R) (rs : seq R) (p : {poly R}). Definition diff_roots (x y : R) := (x * y == y * x) && (y - x \in GRing.unit). Fixpoint uniq_roots rs := if rs is x :: rs' then all (diff_roots x) rs' && uniq_roots rs' else true. Lemma uniq_roots_prod_XsubC p rs : all (root p) rs -> uniq_roots rs -> exists q, p = q * \prod_(z <- rs) ('X - z%:P). Proof. elim: rs => [|z rs IHrs] /=; first by rewrite big_nil; exists p; rewrite mulr1. case/andP=> rpz rprs /andP[drs urs]; case: IHrs => {urs rprs}// q def_p. have [|q' def_q] := factor_theorem q z _; last first. by exists q'; rewrite big_cons mulrA -def_q. rewrite {p}def_p in rpz. elim/last_ind: rs drs rpz => [|rs t IHrs] /=; first by rewrite big_nil mulr1. rewrite all_rcons => /andP[/andP[/eqP czt Uzt] /IHrs{}IHrs]. rewrite -cats1 big_cat big_seq1 /= mulrA rootE hornerM_comm; last first. by rewrite /comm_poly hornerXsubC mulrBl mulrBr czt. rewrite hornerXsubC -opprB mulrN oppr_eq0 -(mul0r (t - z)). by rewrite (inj_eq (mulIr Uzt)) => /IHrs. Qed. Theorem max_ring_poly_roots p rs : p != 0 -> all (root p) rs -> uniq_roots rs -> size rs < size p. Proof. move=> nz_p _ /(@uniq_roots_prod_XsubC p)[// | q def_p]; rewrite def_p in nz_p *. have nz_q: q != 0 by apply: contraNneq nz_p => ->; rewrite mul0r. rewrite size_Mmonic ?monic_prod_XsubC // (polySpred nz_q) addSn /=. by rewrite size_prod_XsubC leq_addl. Qed. Lemma all_roots_prod_XsubC p rs : size p = (size rs).+1 -> all (root p) rs -> uniq_roots rs -> p = lead_coef p *: \prod_(z <- rs) ('X - z%:P). Proof. move=> size_p /uniq_roots_prod_XsubC def_p Urs. case/def_p: Urs => q -> {p def_p} in size_p *. have [q0 | nz_q] := eqVneq q 0; first by rewrite q0 mul0r size_poly0 in size_p. have{q nz_q size_p} /size_poly1P[c _ ->]: size q == 1. rewrite -(eqn_add2r (size rs)) add1n -size_p. by rewrite size_Mmonic ?monic_prod_XsubC // size_prod_XsubC addnS. by rewrite lead_coef_Mmonic ?monic_prod_XsubC // lead_coefC mul_polyC. Qed. End MaxRoots. Section FieldRoots. Variable F : fieldType. Implicit Types (p : {poly F}) (rs : seq F). Lemma poly2_root p : size p = 2 -> {r | root p r}. Proof. case: p => [[|p0 [|p1 []]] //= nz_p1]; exists (- p0 / p1). by rewrite /root addr_eq0 /= mul0r add0r mulrC divfK ?opprK. Qed. Lemma uniq_rootsE rs : uniq_roots rs = uniq rs. Proof. elim: rs => //= r rs ->; congr (_ && _); rewrite -has_pred1 -all_predC. by apply: eq_all => t; rewrite /diff_roots mulrC eqxx unitfE subr_eq0. Qed. Lemma root_ZXsubC (a b r : F) : a != 0 -> root (a *: 'X - b%:P) r = (r == b / a). Proof. move=> a0; rewrite rootE !hornerE. by rewrite -[r in RHS]divr1 eqr_div ?oner_neq0// mulr1 mulrC subr_eq0. Qed. Section UnityRoots. Variable n : nat. Lemma max_unity_roots rs : n > 0 -> all n.-unity_root rs -> uniq rs -> size rs <= n. Proof. move=> n_gt0 rs_n_1 Urs; have szPn := size_XnsubC (1 : F) n_gt0. by rewrite -ltnS -szPn max_poly_roots -?size_poly_eq0 ?szPn. Qed. Lemma mem_unity_roots rs : n > 0 -> all n.-unity_root rs -> uniq rs -> size rs = n -> n.-unity_root =i rs. Proof. move=> n_gt0 rs_n_1 Urs sz_rs_n x; rewrite -topredE /=. apply/idP/idP=> xn1; last exact: (allP rs_n_1). apply: contraFT (ltnn n) => not_rs_x. by rewrite -{1}sz_rs_n (@max_unity_roots (x :: rs)) //= ?xn1 ?not_rs_x. Qed. (* Showing the existence of a primitive root requires the theory in cyclic. *) Variable z : F. Hypothesis prim_z : n.-primitive_root z. Let zn := [seq z ^+ i | i <- index_iota 0 n]. Lemma factor_Xn_sub_1 : \prod_(0 <= i < n) ('X - (z ^+ i)%:P) = 'X^n - 1. Proof. transitivity (\prod_(w <- zn) ('X - w%:P)); first by rewrite big_map. have n_gt0: n > 0 := prim_order_gt0 prim_z. rewrite (@all_roots_prod_XsubC _ ('X^n - 1) zn); first 1 last. - by rewrite size_XnsubC // size_map size_iota subn0. - apply/allP=> _ /mapP[i _ ->] /=; rewrite rootE !hornerE. by rewrite exprAC (prim_expr_order prim_z) expr1n subrr. - rewrite uniq_rootsE map_inj_in_uniq ?iota_uniq // => i j. rewrite !mem_index_iota => ltin ltjn /eqP. by rewrite (eq_prim_root_expr prim_z) !modn_small // => /eqP. by rewrite (monicP (monicXnsubC 1 n_gt0)) scale1r. Qed. Lemma prim_rootP x : x ^+ n = 1 -> {i : 'I_n | x = z ^+ i}. Proof. move=> xn1; pose logx := [pred i : 'I_n | x == z ^+ i]. case: (pickP logx) => [i /eqP-> | no_i]; first by exists i. case: notF; suffices{no_i}: x \in zn. case/mapP=> i; rewrite mem_index_iota => lt_i_n def_x. by rewrite -(no_i (Ordinal lt_i_n)) /= -def_x. rewrite -root_prod_XsubC big_map factor_Xn_sub_1. by rewrite [root _ x]unity_rootE xn1. Qed. End UnityRoots. End FieldRoots. Section MapPolyRoots. Variables (F : fieldType) (R : unitRingType) (f : {rmorphism F -> R}). Lemma map_diff_roots x y : diff_roots (f x) (f y) = (x != y). Proof. rewrite /diff_roots -rmorphB // fmorph_unit // subr_eq0 //. by rewrite rmorph_comm // eqxx eq_sym. Qed. Lemma map_uniq_roots s : uniq_roots (map f s) = uniq s. Proof. elim: s => //= x s ->; congr (_ && _); elim: s => //= y s ->. by rewrite map_diff_roots -negb_or. Qed. End MapPolyRoots. Section AutPolyRoot. (* The action of automorphisms on roots of unity. *) Variable F : fieldType. Implicit Types u v : {rmorphism F -> F}. Lemma aut_prim_rootP u z n : n.-primitive_root z -> {k | coprime k n & u z = z ^+ k}. Proof. move=> prim_z; have:= prim_z; rewrite -(fmorph_primitive_root u) => prim_uz. have [[k _] /= def_uz] := prim_rootP prim_z (prim_expr_order prim_uz). by exists k; rewrite // -(prim_root_exp_coprime _ prim_z) -def_uz. Qed. Lemma aut_unity_rootP u z n : n > 0 -> z ^+ n = 1 -> {k | u z = z ^+ k}. Proof. by move=> _ /prim_order_exists[// | m /(aut_prim_rootP u)[k]]; exists k. Qed. Lemma aut_unity_rootC u v z n : n > 0 -> z ^+ n = 1 -> u (v z) = v (u z). Proof. move=> n_gt0 /(aut_unity_rootP _ n_gt0) def_z. have [[i def_uz] [j def_vz]] := (def_z u, def_z v). by rewrite def_vz def_uz !rmorphXn /= def_vz def_uz exprAC. Qed. End AutPolyRoot. Module UnityRootTheory. Notation "n .-unity_root" := (root_of_unity n) : unity_root_scope. Notation "n .-primitive_root" := (primitive_root_of_unity n) : unity_root_scope. Open Scope unity_root_scope. Definition unity_rootE := unity_rootE. Definition unity_rootP := @unity_rootP. Arguments unity_rootP {R n z}. Definition prim_order_exists := prim_order_exists. Notation prim_order_gt0 := prim_order_gt0. Notation prim_expr_order := prim_expr_order. Definition prim_expr_mod := prim_expr_mod. Definition prim_order_dvd := prim_order_dvd. Definition eq_prim_root_expr := eq_prim_root_expr. Definition rmorph_unity_root := rmorph_unity_root. Definition fmorph_unity_root := fmorph_unity_root. Definition fmorph_primitive_root := fmorph_primitive_root. Definition max_unity_roots := max_unity_roots. Definition mem_unity_roots := mem_unity_roots. Definition prim_rootP := prim_rootP. End UnityRootTheory. Module Export Pdeg2. Module Export Field. Section Pdeg2Field. Variable F : fieldType. Hypothesis nz2 : 2 != 0 :> F. Variable p : {poly F}. Hypothesis degp : size p = 3. Let a := p`_2. Let b := p`_1. Let c := p`_0. Let pneq0 : p != 0. Proof. by rewrite -size_poly_gt0 degp. Qed. Let aneq0 : a != 0. Proof. by move: pneq0; rewrite -lead_coef_eq0 lead_coefE degp. Qed. Let a2neq0 : 2 * a != 0. Proof. by rewrite mulf_neq0. Qed. Let sqa2neq0 : (2 * a) ^+ 2 != 0. Proof. exact: expf_neq0. Qed. Let aa4 : 4 * a * a = (2 * a)^+2. Proof. by rewrite expr2 mulrACA mulrA -natrM. Qed. Let splitr (x : F) : x = x / 2 + x / 2. Proof. by apply: (mulIf nz2); rewrite -mulrDl mulfVK// mulr_natr mulr2n. Qed. Let pE : p = a *: 'X^2 + b *: 'X + c%:P. Proof. apply/polyP => + /[!coefE] => -[|[|[|i]]] /=; rewrite !Monoid.simpm//. by rewrite nth_default// degp. Qed. Let delta := b ^+ 2 - 4 * a * c. Lemma deg2_poly_canonical : p = a *: (('X + (b / (2 * a))%:P)^+2 - (delta / (4 * a ^+ 2))%:P). Proof. rewrite pE sqrrD -!addrA scalerDr; congr +%R; rewrite addrA scalerDr; congr +%R. - rewrite -mulrDr -polyCD -!mul_polyC mulrA mulrAC -polyCM. by rewrite [a * _]mulrC mulrDl invfM -!mulrA mulVf// mulr1 -splitr. - rewrite [a ^+ 2]expr2 mulrA aa4 -polyC_exp -polyCB expr_div_n -mulrBl subKr. by rewrite scale_polyC mulrCA mulrACA aa4 mulrCA mulfV// mulr1. Qed. Variable r : F. Hypothesis r_sqrt_delta : r ^+ 2 = delta. Let r1 := (- b - r) / (2 * a). Let r2 := (- b + r) / (2 * a). Lemma deg2_poly_factor : p = a *: ('X - r1%:P) * ('X - r2%:P). Proof. rewrite [p]deg2_poly_canonical//= -/a -/b -/c -/delta /r1 /r2. rewrite ![(- b + _) * _]mulrDl 2!polyCD 2!opprD 2!addrA !mulNr !polyCN !opprK. rewrite -scalerAl [in RHS]mulrC -subr_sqr -polyC_exp -[4]/(2 * 2)%:R natrM. by rewrite -expr2 -exprMn [in RHS]exprMn exprVn r_sqrt_delta. Qed. Lemma deg2_poly_root1 : root p r1. Proof. apply/factor_theorem. by exists (a *: ('X - r2%:P)); rewrite deg2_poly_factor -!scalerAl mulrC. Qed. Lemma deg2_poly_root2 : root p r2. Proof. apply/factor_theorem. by exists (a *: ('X - r1%:P)); rewrite deg2_poly_factor -!scalerAl. Qed. End Pdeg2Field. End Field. Module FieldMonic. Section Pdeg2FieldMonic. Variable F : fieldType. Hypothesis nz2 : 2 != 0 :> F. Variable p : {poly F}. Hypothesis degp : size p = 3. Hypothesis monicp : p \is monic. Let a := p`_2. Let b := p`_1. Let c := p`_0. Let a1 : a = 1. Proof. by move: (monicP monicp); rewrite lead_coefE degp. Qed. Let delta := b ^+ 2 - 4 * c. Lemma deg2_poly_canonical : p = (('X + (b / 2)%:P)^+2 - (delta / 4)%:P). Proof. by rewrite [p]deg2_poly_canonical// -/a a1 scale1r expr1n !mulr1. Qed. Variable r : F. Hypothesis r_sqrt_delta : r ^+ 2 = delta. Let r1 := (- b - r) / 2. Let r2 := (- b + r) / 2. Lemma deg2_poly_factor : p = ('X - r1%:P) * ('X - r2%:P). Proof. by rewrite [p](@deg2_poly_factor _ _ _ _ r)// -/a a1 !mulr1 ?scale1r. Qed. Lemma deg2_poly_root1 : root p r1. Proof. rewrite /r1 -[2]mulr1 -[X in 2 * X]a1. by apply: deg2_poly_root1; rewrite // -/a a1 mulr1. Qed. Lemma deg2_poly_root2 : root p r2. Proof. rewrite /r2 -[2]mulr1 -[X in 2 * X]a1. by apply: deg2_poly_root2; rewrite // -/a a1 mulr1. Qed. End Pdeg2FieldMonic. End FieldMonic. End Pdeg2. Section DecField. Variable F : decFieldType. Lemma dec_factor_theorem (p : {poly F}) : {s : seq F & {q : {poly F} | p = q * \prod_(x <- s) ('X - x%:P) /\ (q != 0 -> forall x, ~~ root q x)}}. Proof. pose polyT (p : seq F) := (foldr (fun c f => f * 'X_0 + c%:T) (0%R)%:T p)%T. have eval_polyT (q : {poly F}) x : GRing.eval [:: x] (polyT q) = q.[x]. by rewrite /horner; elim: (val q) => //= ? ? ->. have [n] := ubnP (size p); elim: n => // n IHn in p *. have /decPcases /= := @satP F [::] ('exists 'X_0, polyT p == 0%T). case: ifP => [_ /sig_eqW[x]|_ noroot]; last first. exists [::], p; rewrite big_nil mulr1; split => // p_neq0 x. by apply/negP=> /rootP rpx; apply: noroot; exists x; rewrite eval_polyT. rewrite eval_polyT => /rootP/factor_theorem/sig_eqW[p1 ->]. have [->|nz_p1] := eqVneq p1 0; first by exists [::], 0; rewrite !mul0r eqxx. rewrite size_Mmonic ?monicXsubC // size_XsubC addn2 => /IHn[s [q [-> irr_q]]]. by exists (rcons s x), q; rewrite -cats1 big_cat big_seq1 mulrA. Qed. End DecField. Module PreClosedField. Section UseAxiom. Variable F : fieldType. Hypothesis closedF : GRing.closed_field_axiom F. Implicit Type p : {poly F}. Lemma closed_rootP p : reflect (exists x, root p x) (size p != 1). Proof. have [-> | nz_p] := eqVneq p 0. by rewrite size_poly0; left; exists 0; rewrite root0. rewrite neq_ltn [in _ < 1]polySpred //=. apply: (iffP idP) => [p_gt1 | [a]]; last exact: root_size_gt1. pose n := (size p).-1; have n_gt0: n > 0 by rewrite -ltnS -polySpred. have [a Dan] := closedF (fun i => - p`_i / lead_coef p) n_gt0. exists a; apply/rootP; rewrite horner_coef polySpred // big_ord_recr /= -/n. rewrite {}Dan mulr_sumr -big_split big1 //= => i _. by rewrite -!mulrA mulrCA mulNr mulVKf ?subrr ?lead_coef_eq0. Qed. Lemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0). Proof. apply: (iffP idP) => [nz_p | [x]]; last first. by apply: contraNneq => ->; apply: root0. have [[x /rootP p1x0]|] := altP (closed_rootP (p - 1)). by exists x; rewrite -[p](subrK 1) /root hornerD p1x0 add0r hornerC oner_eq0. rewrite negbK => /size_poly1P[c _ /(canRL (subrK 1)) Dp]. by exists 0; rewrite Dp -raddfD polyC_eq0 rootC in nz_p *. Qed. End UseAxiom. End PreClosedField. Section ClosedField. Variable F : closedFieldType. Implicit Type p : {poly F}. Let closedF := @solve_monicpoly F. Lemma closed_rootP p : reflect (exists x, root p x) (size p != 1). Proof. exact: PreClosedField.closed_rootP. Qed. Lemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0). Proof. exact: PreClosedField.closed_nonrootP. Qed. Lemma closed_field_poly_normal p : {r : seq F | p = lead_coef p *: \prod_(z <- r) ('X - z%:P)}. Proof. apply: sig_eqW; have [r [q [->]]] /= := dec_factor_theorem p. have [->|] := eqVneq; first by exists [::]; rewrite mul0r lead_coef0 scale0r. have [[x rqx ? /(_ isT x) /negP /(_ rqx)] //|] := altP (closed_rootP q). rewrite negbK => /size_poly1P [c c_neq0-> _ _]; exists r. rewrite mul_polyC lead_coefZ (monicP _) ?mulr1 //. by rewrite monic_prod => // i; rewrite monicXsubC. Qed. End ClosedField.
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, Joey van Langen, Casper Putz -/ import Mathlib.Algebra.CharP.Algebra import Mathlib.Algebra.CharP.Reduced import Mathlib.Algebra.Field.ZMod import Mathlib.Data.Nat.Prime.Int import Mathlib.Data.ZMod.ValMinAbs import Mathlib.LinearAlgebra.FreeModule.Finite.Matrix import Mathlib.FieldTheory.Finiteness import Mathlib.FieldTheory.Perfect import Mathlib.FieldTheory.Separable import Mathlib.RingTheory.IntegralDomain /-! # Finite fields This file contains basic results about finite fields. Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. See `RingTheory.IntegralDomain` for the fact that the unit group of a finite field is a cyclic group, as well as the fact that every finite integral domain is a field (`Fintype.fieldOfDomain`). ## Main results 1. `Fintype.card_units`: The unit group of a finite field has cardinality `q - 1`. 2. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is - `q-1` if `q-1 ∣ i` - `0` otherwise 3. `FiniteField.card`: The cardinality `q` is a power of the characteristic of `K`. See `FiniteField.card'` for a variant. ## Notation Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. ## Implementation notes While `Fintype Kˣ` can be inferred from `Fintype K` in the presence of `DecidableEq K`, in this file we take the `Fintype Kˣ` argument directly to reduce the chance of typeclass diamonds, as `Fintype` carries data. -/ variable {K : Type*} {R : Type*} local notation "q" => Fintype.card K open Finset open scoped Polynomial namespace FiniteField section Polynomial variable [CommRing R] [IsDomain R] open Polynomial /-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n` polynomial -/ theorem card_image_polynomial_eval [DecidableEq R] [Fintype R] {p : R[X]} (hp : 0 < p.degree) : Fintype.card R ≤ natDegree p * #(univ.image fun x => eval x p) := Finset.card_le_mul_card_image _ _ (fun a _ => calc _ = #(p - C a).roots.toFinset := congr_arg card (by simp [Finset.ext_iff, ← mem_roots_sub_C hp]) _ ≤ Multiset.card (p - C a).roots := Multiset.toFinset_card_le _ _ ≤ _ := card_roots_sub_C' hp) /-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/ theorem exists_root_sum_quadratic [Fintype R] {f g : R[X]} (hf2 : degree f = 2) (hg2 : degree g = 2) (hR : Fintype.card R % 2 = 1) : ∃ a b, f.eval a + g.eval b = 0 := letI := Classical.decEq R suffices ¬Disjoint (univ.image fun x : R => eval x f) (univ.image fun x : R => eval x (-g)) by simp only [disjoint_left, mem_image] at this push_neg at this rcases this with ⟨x, ⟨a, _, ha⟩, ⟨b, _, hb⟩⟩ exact ⟨a, b, by rw [ha, ← hb, eval_neg, neg_add_cancel]⟩ fun hd : Disjoint _ _ => lt_irrefl (2 * #((univ.image fun x : R => eval x f) ∪ univ.image fun x : R => eval x (-g))) <| calc 2 * #((univ.image fun x : R => eval x f) ∪ univ.image fun x : R => eval x (-g)) ≤ 2 * Fintype.card R := Nat.mul_le_mul_left _ (Finset.card_le_univ _) _ = Fintype.card R + Fintype.card R := two_mul _ _ < natDegree f * #(univ.image fun x : R => eval x f) + natDegree (-g) * #(univ.image fun x : R => eval x (-g)) := (add_lt_add_of_lt_of_le (lt_of_le_of_ne (card_image_polynomial_eval (by rw [hf2]; decide)) (mt (congr_arg (· % 2)) (by simp [natDegree_eq_of_degree_eq_some hf2, hR]))) (card_image_polynomial_eval (by rw [degree_neg, hg2]; decide))) _ = 2 * #((univ.image fun x : R => eval x f) ∪ univ.image fun x : R => eval x (-g)) := by rw [card_union_of_disjoint hd] simp [natDegree_eq_of_degree_eq_some hf2, natDegree_eq_of_degree_eq_some hg2, mul_add] end Polynomial theorem prod_univ_units_id_eq_neg_one [CommRing K] [IsDomain K] [Fintype Kˣ] : ∏ x : Kˣ, x = (-1 : Kˣ) := by classical have : (∏ x ∈ (@univ Kˣ _).erase (-1), x) = 1 := prod_involution (fun x _ => x⁻¹) (by simp) (fun a => by simp +contextual [Units.inv_eq_self_iff]) (fun a => by simp [@inv_eq_iff_eq_inv _ _ a]) (by simp) rw [← insert_erase (mem_univ (-1 : Kˣ)), prod_insert (notMem_erase _ _), this, mul_one] theorem card_cast_subgroup_card_ne_zero [Ring K] [NoZeroDivisors K] [Nontrivial K] (G : Subgroup Kˣ) [Fintype G] : (Fintype.card G : K) ≠ 0 := by let n := Fintype.card G intro nzero have ⟨p, char_p⟩ := CharP.exists K have hd : p ∣ n := (CharP.cast_eq_zero_iff K p n).mp nzero cases CharP.char_is_prime_or_zero K p with | inr pzero => exact (Fintype.card_pos).ne' <| Nat.eq_zero_of_zero_dvd <| pzero ▸ hd | inl pprime => have fact_pprime := Fact.mk pprime -- G has an element x of order p by Cauchy's theorem have ⟨x, hx⟩ := exists_prime_orderOf_dvd_card p hd -- F has an element u (= ↑↑x) of order p let u := ((x : Kˣ) : K) have hu : orderOf u = p := by rwa [orderOf_units, Subgroup.orderOf_coe] -- u ^ p = 1 implies (u - 1) ^ p = 0 and hence u = 1 ... have h : u = 1 := by rw [← sub_left_inj, sub_self 1] apply pow_eq_zero (n := p) rw [sub_pow_char_of_commute, one_pow, ← hu, pow_orderOf_eq_one, sub_self] exact Commute.one_right u -- ... meaning x didn't have order p after all, contradiction apply pprime.one_lt.ne rw [← hu, h, orderOf_one] /-- The sum of a nontrivial subgroup of the units of a field is zero. -/ theorem sum_subgroup_units_eq_zero [Ring K] [NoZeroDivisors K] {G : Subgroup Kˣ} [Fintype G] (hg : G ≠ ⊥) : ∑ x : G, (x.val : K) = 0 := by rw [Subgroup.ne_bot_iff_exists_ne_one] at hg rcases hg with ⟨a, ha⟩ -- The action of a on G as an embedding let a_mul_emb : G ↪ G := mulLeftEmbedding a -- ... and leaves G unchanged have h_unchanged : Finset.univ.map a_mul_emb = Finset.univ := by simp -- Therefore the sum of x over a G is the sum of a x over G have h_sum_map := Finset.univ.sum_map a_mul_emb fun x => ((x : Kˣ) : K) -- ... and the former is the sum of x over G. -- By algebraic manipulation, we have Σ G, x = ∑ G, a x = a ∑ G, x simp only [h_unchanged, mulLeftEmbedding_apply, Subgroup.coe_mul, Units.val_mul, ← mul_sum, a_mul_emb] at h_sum_map -- thus one of (a - 1) or ∑ G, x is zero have hzero : (((a : Kˣ) : K) - 1) = 0 ∨ ∑ x : ↥G, ((x : Kˣ) : K) = 0 := by rw [← mul_eq_zero, sub_mul, ← h_sum_map, one_mul, sub_self] apply Or.resolve_left hzero contrapose! ha ext rwa [← sub_eq_zero] /-- The sum of a subgroup of the units of a field is 1 if the subgroup is trivial and 1 otherwise -/ @[simp] theorem sum_subgroup_units [Ring K] [NoZeroDivisors K] {G : Subgroup Kˣ} [Fintype G] [Decidable (G = ⊥)] : ∑ x : G, (x.val : K) = if G = ⊥ then 1 else 0 := by by_cases G_bot : G = ⊥ · subst G_bot simp only [univ_unique, sum_singleton, ↓reduceIte, Units.val_eq_one, OneMemClass.coe_eq_one] rw [Set.default_coe_singleton] rfl · simp only [G_bot, ite_false] exact sum_subgroup_units_eq_zero G_bot @[simp] theorem sum_subgroup_pow_eq_zero [CommRing K] [NoZeroDivisors K] {G : Subgroup Kˣ} [Fintype G] {k : ℕ} (k_pos : k ≠ 0) (k_lt_card_G : k < Fintype.card G) : ∑ x : G, ((x : Kˣ) : K) ^ k = 0 := by rw [← Nat.card_eq_fintype_card] at k_lt_card_G nontriviality K have := NoZeroDivisors.to_isDomain K rcases (exists_pow_ne_one_of_isCyclic k_pos k_lt_card_G) with ⟨a, ha⟩ rw [Finset.sum_eq_multiset_sum] have h_multiset_map : Finset.univ.val.map (fun x : G => ((x : Kˣ) : K) ^ k) = Finset.univ.val.map (fun x : G => ((x : Kˣ) : K) ^ k * ((a : Kˣ) : K) ^ k) := by simp_rw [← mul_pow] have as_comp : (fun x : ↥G => (((x : Kˣ) : K) * ((a : Kˣ) : K)) ^ k) = (fun x : ↥G => ((x : Kˣ) : K) ^ k) ∘ fun x : ↥G => x * a := by funext x simp only [Function.comp_apply, Subgroup.coe_mul, Units.val_mul] rw [as_comp, ← Multiset.map_map] congr rw [eq_comm] exact Multiset.map_univ_val_equiv (Equiv.mulRight a) have h_multiset_map_sum : (Multiset.map (fun x : G => ((x : Kˣ) : K) ^ k) Finset.univ.val).sum = (Multiset.map (fun x : G => ((x : Kˣ) : K) ^ k * ((a : Kˣ) : K) ^ k) Finset.univ.val).sum := by rw [h_multiset_map] rw [Multiset.sum_map_mul_right] at h_multiset_map_sum have hzero : (((a : Kˣ) : K) ^ k - 1 : K) * (Multiset.map (fun i : G => (i.val : K) ^ k) Finset.univ.val).sum = 0 := by rw [sub_mul, mul_comm, ← h_multiset_map_sum, one_mul, sub_self] rw [mul_eq_zero] at hzero refine hzero.resolve_left fun h => ha ?_ ext rw [← sub_eq_zero] simp_rw [SubmonoidClass.coe_pow, Units.val_pow_eq_pow_val, OneMemClass.coe_one, Units.val_one, h] section variable [GroupWithZero K] [Fintype K] theorem pow_card_sub_one_eq_one (a : K) (ha : a ≠ 0) : a ^ (q - 1) = 1 := by calc a ^ (Fintype.card K - 1) = (Units.mk0 a ha ^ (Fintype.card K - 1) : Kˣ).1 := by rw [Units.val_pow_eq_pow_val, Units.val_mk0] _ = 1 := by classical rw [← Fintype.card_units, pow_card_eq_one] rfl theorem pow_card (a : K) : a ^ q = a := by by_cases h : a = 0; · rw [h]; apply zero_pow Fintype.card_ne_zero rw [← Nat.succ_pred_eq_of_pos Fintype.card_pos, pow_succ, Nat.pred_eq_sub_one, pow_card_sub_one_eq_one a h, one_mul] theorem pow_card_pow (n : ℕ) (a : K) : a ^ q ^ n = a := by induction n with | zero => simp | succ n ih => simp [pow_succ, pow_mul, ih, pow_card] end variable (K) [Field K] [Fintype K] /-- The cardinality `q` is a power of the characteristic of `K`. -/ @[stacks 09HY "first part"] theorem card (p : ℕ) [CharP K p] : ∃ n : ℕ+, Nat.Prime p ∧ q = p ^ (n : ℕ) := by haveI hp : Fact p.Prime := ⟨CharP.char_is_prime K p⟩ letI : Module (ZMod p) K := { (ZMod.castHom dvd_rfl K : ZMod p →+* _).toModule with } obtain ⟨n, h⟩ := VectorSpace.card_fintype (ZMod p) K rw [ZMod.card] at h refine ⟨⟨n, ?_⟩, hp.1, h⟩ apply Or.resolve_left (Nat.eq_zero_or_pos n) rintro rfl rw [pow_zero] at h have : (0 : K) = 1 := by apply Fintype.card_le_one_iff.mp (le_of_eq h) exact absurd this zero_ne_one -- this statement doesn't use `q` because we want `K` to be an explicit parameter theorem card' : ∃ (p : ℕ), CharP K p ∧ ∃ (n : ℕ+), Nat.Prime p ∧ Fintype.card K = p ^ (n : ℕ) := let ⟨p, hc⟩ := CharP.exists K ⟨p, hc, @FiniteField.card K _ _ p hc⟩ lemma isPrimePow_card : IsPrimePow (Fintype.card K) := by obtain ⟨p, _, n, hp, hn⟩ := card' K exact ⟨p, n, Nat.prime_iff.mp hp, n.prop, hn.symm⟩ theorem cast_card_eq_zero : (q : K) = 0 := by simp theorem forall_pow_eq_one_iff (i : ℕ) : (∀ x : Kˣ, x ^ i = 1) ↔ q - 1 ∣ i := by classical obtain ⟨x, hx⟩ := IsCyclic.exists_generator (α := Kˣ) rw [← Nat.card_eq_fintype_card, ← Nat.card_units, ← orderOf_eq_card_of_forall_mem_zpowers hx, orderOf_dvd_iff_pow_eq_one] constructor · intro h; apply h · intro h y simp_rw [← mem_powers_iff_mem_zpowers] at hx rcases hx y with ⟨j, rfl⟩ rw [← pow_mul, mul_comm, pow_mul, h, one_pow] /-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q` is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/ theorem sum_pow_units [DecidableEq K] (i : ℕ) : (∑ x : Kˣ, (x ^ i : K)) = if q - 1 ∣ i then -1 else 0 := by let φ : Kˣ →* K := { toFun := fun x => x ^ i map_one' := by simp map_mul' := by intros; simp [mul_pow] } have : Decidable (φ = 1) := by classical infer_instance calc (∑ x : Kˣ, φ x) = if φ = 1 then Fintype.card Kˣ else 0 := sum_hom_units φ _ = if q - 1 ∣ i then -1 else 0 := by suffices q - 1 ∣ i ↔ φ = 1 by simp only [this] split_ifs; swap · exact Nat.cast_zero · rw [Fintype.card_units, Nat.cast_sub, cast_card_eq_zero, Nat.cast_one, zero_sub] show 1 ≤ q; exact Fintype.card_pos_iff.mpr ⟨0⟩ rw [← forall_pow_eq_one_iff, DFunLike.ext_iff] apply forall_congr'; intro x; simp [φ, Units.ext_iff] /-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q` is equal to `0` if `i < q - 1`. -/ theorem sum_pow_lt_card_sub_one (i : ℕ) (h : i < q - 1) : ∑ x : K, x ^ i = 0 := by by_cases hi : i = 0 · simp only [hi, nsmul_one, sum_const, pow_zero, card_univ, cast_card_eq_zero] classical have hiq : ¬q - 1 ∣ i := by contrapose! h; exact Nat.le_of_dvd (Nat.pos_of_ne_zero hi) h let φ : Kˣ ↪ K := ⟨fun x ↦ x, Units.val_injective⟩ have : univ.map φ = univ \ {0} := by ext x simpa only [mem_map, mem_univ, Function.Embedding.coeFn_mk, true_and, mem_sdiff, mem_singleton, φ] using isUnit_iff_ne_zero calc ∑ x : K, x ^ i = ∑ x ∈ univ \ {(0 : K)}, x ^ i := by rw [← sum_sdiff ({0} : Finset K).subset_univ, sum_singleton, zero_pow hi, add_zero] _ = ∑ x : Kˣ, (x ^ i : K) := by simp [φ, ← this, univ.sum_map φ] _ = 0 := by rw [sum_pow_units K i, if_neg]; exact hiq section frobenius variable (R) [CommRing R] [Algebra K R] /-- If `R` is an algebra over a finite field `K`, the Frobenius `K`-algebra endomorphism of `R` is given by raising every element of `R` to its `#K`-th power. -/ @[simps!] def frobeniusAlgHom : R →ₐ[K] R where __ := powMonoidHom q map_zero' := zero_pow Fintype.card_pos.ne' map_add' _ _ := by obtain ⟨p, _, _, hp, card_eq⟩ := card' K nontriviality R have : CharP R p := charP_of_injective_algebraMap' K R p have : ExpChar R p := .prime hp simp only [OneHom.toFun_eq_coe, MonoidHom.toOneHom_coe, powMonoidHom_apply, card_eq] exact add_pow_expChar_pow .. commutes' _ := by simp [← RingHom.map_pow, pow_card] theorem coe_frobeniusAlgHom : ⇑(frobeniusAlgHom K R) = (· ^ q) := rfl /-- If `R` is a perfect ring and an algebra over a finite field `K`, the Frobenius `K`-algebra endomorphism of `R` is an automorphism. -/ @[simps!] noncomputable def frobeniusAlgEquiv (p : ℕ) [ExpChar R p] [PerfectRing R p] : R ≃ₐ[K] R := .ofBijective (frobeniusAlgHom K R) <| by obtain ⟨p', _, n, hp, card_eq⟩ := card' K rw [coe_frobeniusAlgHom, card_eq] have : ExpChar K p' := ExpChar.prime hp nontriviality R have := ExpChar.eq ‹_› (expChar_of_injective_algebraMap (algebraMap K R).injective p') subst this apply bijective_iterateFrobenius variable (L : Type*) [Field L] [Algebra K L] /-- If `L/K` is an algebraic extension of a finite field, the Frobenius `K`-algebra endomorphism of `L` is an automorphism. -/ @[simps!] noncomputable def frobeniusAlgEquivOfAlgebraic [Algebra.IsAlgebraic K L] : L ≃ₐ[K] L := (Algebra.IsAlgebraic.algEquivEquivAlgHom K L).symm (frobeniusAlgHom K L) theorem coe_frobeniusAlgEquivOfAlgebraic [Algebra.IsAlgebraic K L] : ⇑(frobeniusAlgEquivOfAlgebraic K L) = (· ^ q) := rfl lemma coe_frobeniusAlgEquivOfAlgebraic_iterate [Algebra.IsAlgebraic K L] (n : ℕ) : (⇑(frobeniusAlgEquivOfAlgebraic K L))^[n] = (· ^ (Fintype.card K ^ n)) := pow_iterate (Fintype.card K) n variable [Finite L] open Polynomial in theorem orderOf_frobeniusAlgHom : orderOf (frobeniusAlgHom K L) = Module.finrank K L := (orderOf_eq_iff Module.finrank_pos).mpr <| by have := Fintype.ofFinite L refine ⟨DFunLike.ext _ _ fun x ↦ ?_, fun m lt pos eq ↦ ?_⟩ · simp_rw [AlgHom.coe_pow, coe_frobeniusAlgHom, pow_iterate, AlgHom.one_apply, ← Module.card_eq_pow_finrank, pow_card] have := card_le_degree_of_subset_roots (R := L) (p := X ^ q ^ m - X) (Z := univ) fun x _ ↦ by simp_rw [mem_roots', IsRoot, eval_sub, eval_pow, eval_X] have := DFunLike.congr_fun eq x rw [AlgHom.coe_pow, coe_frobeniusAlgHom, pow_iterate, AlgHom.one_apply, ← sub_eq_zero] at this refine ⟨fun h ↦ ?_, this⟩ simpa [if_neg (Nat.one_lt_pow pos.ne' Fintype.one_lt_card).ne] using congr_arg (coeff · 1) h refine this.not_gt (((natDegree_sub_le ..).trans_eq ?_).trans_lt <| (Nat.pow_lt_pow_right Fintype.one_lt_card lt).trans_eq Module.card_eq_pow_finrank.symm) simp [Nat.one_le_pow _ _ Fintype.card_pos] theorem orderOf_frobeniusAlgEquivOfAlgebraic : orderOf (frobeniusAlgEquivOfAlgebraic K L) = Module.finrank K L := by simpa [orderOf_eq_iff Module.finrank_pos, DFunLike.ext_iff] using orderOf_frobeniusAlgHom K L theorem bijective_frobeniusAlgHom_pow : Function.Bijective fun n : Fin (Module.finrank K L) ↦ frobeniusAlgHom K L ^ n.1 := let e := (finCongr <| orderOf_frobeniusAlgHom K L).symm.trans <| finEquivPowers (orderOf_pos_iff.mp <| orderOf_frobeniusAlgHom K L ▸ Module.finrank_pos) (Subtype.val_injective.comp e.injective).bijective_of_nat_card_le ((card_algHom_le_finrank K L L).trans_eq <| by simp) theorem bijective_frobeniusAlgEquivOfAlgebraic_pow : Function.Bijective fun n : Fin (Module.finrank K L) ↦ frobeniusAlgEquivOfAlgebraic K L ^ n.1 := ((Algebra.IsAlgebraic.algEquivEquivAlgHom K L).bijective.of_comp_iff' _).mp <| by simpa only [Function.comp_def, map_pow] using bijective_frobeniusAlgHom_pow K L instance (K L) [Finite L] [Field K] [Field L] [Algebra K L] : IsCyclic (L ≃ₐ[K] L) where exists_zpow_surjective := have := Finite.of_injective _ (algebraMap K L).injective have := Fintype.ofFinite K ⟨frobeniusAlgEquivOfAlgebraic K L, fun f ↦ have ⟨n, hn⟩ := (bijective_frobeniusAlgEquivOfAlgebraic_pow K L).2 f; ⟨n, hn⟩⟩ open Polynomial in theorem minpoly_frobeniusAlgHom : minpoly K (frobeniusAlgHom K L).toLinearMap = X ^ Module.finrank K L - 1 := minpoly.eq_of_linearIndependent _ _ (leadingCoeff_X_pow_sub_one Module.finrank_pos) (LinearMap.ext fun x ↦ by simpa [sub_eq_zero, Module.End.coe_pow, orderOf_frobeniusAlgHom] using congr($(pow_orderOf_eq_one (frobeniusAlgHom K L)) x)) _ (degree_X_pow_sub_C Module.finrank_pos _) <| by simpa [← AlgHom.toEnd_apply, ← map_pow] using (linearIndependent_algHom_toLinearMap K L L |>.restrict_scalars' K).comp _ (bijective_frobeniusAlgHom_pow K L).1 end frobenius open Polynomial section variable [Fintype K] (K' : Type*) [Field K'] {p n : ℕ} theorem X_pow_card_sub_X_natDegree_eq (hp : 1 < p) : (X ^ p - X : K'[X]).natDegree = p := by have h1 : (X : K'[X]).degree < (X ^ p : K'[X]).degree := by rw [degree_X_pow, degree_X] exact mod_cast hp rw [natDegree_eq_of_degree_eq (degree_sub_eq_left_of_degree_lt h1), natDegree_X_pow] theorem X_pow_card_pow_sub_X_natDegree_eq (hn : n ≠ 0) (hp : 1 < p) : (X ^ p ^ n - X : K'[X]).natDegree = p ^ n := X_pow_card_sub_X_natDegree_eq K' <| Nat.one_lt_pow hn hp theorem X_pow_card_sub_X_ne_zero (hp : 1 < p) : (X ^ p - X : K'[X]) ≠ 0 := ne_zero_of_natDegree_gt <| calc 1 < _ := hp _ = _ := (X_pow_card_sub_X_natDegree_eq K' hp).symm theorem X_pow_card_pow_sub_X_ne_zero (hn : n ≠ 0) (hp : 1 < p) : (X ^ p ^ n - X : K'[X]) ≠ 0 := X_pow_card_sub_X_ne_zero K' <| Nat.one_lt_pow hn hp end theorem roots_X_pow_card_sub_X : roots (X ^ q - X : K[X]) = Finset.univ.val := by classical have aux : (X ^ q - X : K[X]) ≠ 0 := X_pow_card_sub_X_ne_zero K Fintype.one_lt_card have : (roots (X ^ q - X : K[X])).toFinset = Finset.univ := by rw [eq_univ_iff_forall] intro x rw [Multiset.mem_toFinset, mem_roots aux, IsRoot.def, eval_sub, eval_pow, eval_X, sub_eq_zero, pow_card] rw [← this, Multiset.toFinset_val, eq_comm, Multiset.dedup_eq_self] apply nodup_roots rw [separable_def] convert isCoprime_one_right.neg_right (R := K[X]) using 1 rw [derivative_sub, derivative_X, derivative_X_pow, Nat.cast_card_eq_zero K, C_0, zero_mul, zero_sub] variable {K} theorem frobenius_pow {p : ℕ} [Fact p.Prime] [CharP K p] {n : ℕ} (hcard : q = p ^ n) : frobenius K p ^ n = 1 := by ext x; conv_rhs => rw [RingHom.one_def, RingHom.id_apply, ← pow_card x, hcard] clear hcard induction n with | zero => simp | succ n hn => rw [pow_succ', pow_succ, pow_mul, RingHom.mul_def, RingHom.comp_apply, frobenius_def, hn] open Polynomial theorem expand_card (f : K[X]) : expand K q f = f ^ q := by obtain ⟨p, hp⟩ := CharP.exists K letI := hp rcases FiniteField.card K p with ⟨⟨n, npos⟩, ⟨hp, hn⟩⟩ haveI : Fact p.Prime := ⟨hp⟩ dsimp at hn rw [hn, ← map_expand_pow_char, frobenius_pow hn, RingHom.one_def, map_id] end FiniteField namespace ZMod open FiniteField Polynomial theorem sq_add_sq (p : ℕ) [hp : Fact p.Prime] (x : ZMod p) : ∃ a b : ZMod p, a ^ 2 + b ^ 2 = x := by rcases hp.1.eq_two_or_odd with hp2 | hp_odd · subst p change Fin 2 at x fin_cases x · use 0; simp · use 0, 1; simp let f : (ZMod p)[X] := X ^ 2 let g : (ZMod p)[X] := X ^ 2 - C x obtain ⟨a, b, hab⟩ : ∃ a b, f.eval a + g.eval b = 0 := @exists_root_sum_quadratic _ _ _ _ f g (degree_X_pow 2) (degree_X_pow_sub_C (by decide) _) (by rw [ZMod.card, hp_odd]) refine ⟨a, b, ?_⟩ rw [← sub_eq_zero] simpa only [f, g, eval_C, eval_X, eval_pow, eval_sub, ← add_sub_assoc] using hab end ZMod /-- If `p` is a prime natural number and `x` is an integer number, then there exist natural numbers `a ≤ p / 2` and `b ≤ p / 2` such that `a ^ 2 + b ^ 2 ≡ x [ZMOD p]`. This is a version of `ZMod.sq_add_sq` with estimates on `a` and `b`. -/ theorem Nat.sq_add_sq_zmodEq (p : ℕ) [Fact p.Prime] (x : ℤ) : ∃ a b : ℕ, a ≤ p / 2 ∧ b ≤ p / 2 ∧ (a : ℤ) ^ 2 + (b : ℤ) ^ 2 ≡ x [ZMOD p] := by rcases ZMod.sq_add_sq p x with ⟨a, b, hx⟩ refine ⟨a.valMinAbs.natAbs, b.valMinAbs.natAbs, ZMod.natAbs_valMinAbs_le _, ZMod.natAbs_valMinAbs_le _, ?_⟩ rw [← a.coe_valMinAbs, ← b.coe_valMinAbs] at hx push_cast rw [sq_abs, sq_abs, ← ZMod.intCast_eq_intCast_iff] exact mod_cast hx /-- If `p` is a prime natural number and `x` is a natural number, then there exist natural numbers `a ≤ p / 2` and `b ≤ p / 2` such that `a ^ 2 + b ^ 2 ≡ x [MOD p]`. This is a version of `ZMod.sq_add_sq` with estimates on `a` and `b`. -/ theorem Nat.sq_add_sq_modEq (p : ℕ) [Fact p.Prime] (x : ℕ) : ∃ a b : ℕ, a ≤ p / 2 ∧ b ≤ p / 2 ∧ a ^ 2 + b ^ 2 ≡ x [MOD p] := by simpa only [← Int.natCast_modEq_iff] using Nat.sq_add_sq_zmodEq p x namespace CharP theorem sq_add_sq (R : Type*) [Ring R] [IsDomain R] (p : ℕ) [NeZero p] [CharP R p] (x : ℤ) : ∃ a b : ℕ, ((a : R) ^ 2 + (b : R) ^ 2) = x := by haveI := char_is_prime_of_pos R p obtain ⟨a, b, hab⟩ := ZMod.sq_add_sq p x refine ⟨a.val, b.val, ?_⟩ simpa using congr_arg (ZMod.castHom dvd_rfl R) hab end CharP open scoped Nat open ZMod /-- The **Fermat-Euler totient theorem**. `Nat.ModEq.pow_totient` is an alternative statement of the same theorem. -/ @[simp] theorem ZMod.pow_totient {n : ℕ} (x : (ZMod n)ˣ) : x ^ φ n = 1 := by cases n · rw [Nat.totient_zero, pow_zero] · rw [← card_units_eq_totient, pow_card_eq_one] /-- The **Fermat-Euler totient theorem**. `ZMod.pow_totient` is an alternative statement of the same theorem. -/ theorem Nat.ModEq.pow_totient {x n : ℕ} (h : Nat.Coprime x n) : x ^ φ n ≡ 1 [MOD n] := by rw [← ZMod.natCast_eq_natCast_iff] let x' : Units (ZMod n) := ZMod.unitOfCoprime _ h have := ZMod.pow_totient x' apply_fun ((fun (x : Units (ZMod n)) => (x : ZMod n)) : Units (ZMod n) → ZMod n) at this simpa only [Nat.succ_eq_add_one, Nat.cast_pow, Units.val_one, Nat.cast_one, coe_unitOfCoprime, Units.val_pow_eq_pow_val] /-- For each `n ≥ 0`, the unit group of `ZMod n` is finite. -/ instance instFiniteZModUnits : (n : ℕ) → Finite (ZMod n)ˣ | 0 => Finite.of_fintype ℤˣ | _ + 1 => inferInstance open FiniteField namespace ZMod variable {p : ℕ} [Fact p.Prime] instance : Subsingleton (Subfield (ZMod p)) := subsingleton_of_bot_eq_top <| top_unique (a := ⊥) fun n _ ↦ have := zsmul_mem (one_mem (⊥ : Subfield (ZMod p))) n.val by rwa [natCast_zsmul, Nat.smul_one_eq_cast, ZMod.natCast_zmod_val] at this theorem fieldRange_castHom_eq_bot (p : ℕ) [Fact p.Prime] [DivisionRing K] [CharP K p] : (ZMod.castHom (m := p) dvd_rfl K).fieldRange = (⊥ : Subfield K) := by rw [RingHom.fieldRange_eq_map, ← Subfield.map_bot (K := ZMod p), Subsingleton.elim ⊥] /-- A variation on Fermat's little theorem. See `ZMod.pow_card_sub_one_eq_one` -/ @[simp] theorem pow_card (x : ZMod p) : x ^ p = x := by have h := FiniteField.pow_card x; rwa [ZMod.card p] at h @[simp] theorem pow_card_pow {n : ℕ} (x : ZMod p) : x ^ p ^ n = x := by induction n with | zero => simp | succ n ih => simp [pow_succ, pow_mul, ih, pow_card] @[simp] theorem frobenius_zmod (p : ℕ) [Fact p.Prime] : frobenius (ZMod p) p = RingHom.id _ := by ext a rw [frobenius_def, ZMod.pow_card, RingHom.id_apply] -- This was a `simp` lemma, but now the LHS simplifies to `φ p`. theorem card_units (p : ℕ) [Fact p.Prime] : Fintype.card (ZMod p)ˣ = p - 1 := by rw [Fintype.card_units, card] /-- **Fermat's Little Theorem**: for every unit `a` of `ZMod p`, we have `a ^ (p - 1) = 1`. -/ theorem units_pow_card_sub_one_eq_one (p : ℕ) [Fact p.Prime] (a : (ZMod p)ˣ) : a ^ (p - 1) = 1 := by rw [← card_units p, pow_card_eq_one] /-- **Fermat's Little Theorem**: for all nonzero `a : ZMod p`, we have `a ^ (p - 1) = 1`. -/ theorem pow_card_sub_one_eq_one {a : ZMod p} (ha : a ≠ 0) : a ^ (p - 1) = 1 := by have h := FiniteField.pow_card_sub_one_eq_one a ha rwa [ZMod.card p] at h lemma pow_card_sub_one (a : ZMod p) : a ^ (p - 1) = if a ≠ 0 then 1 else 0 := by split_ifs with ha · exact pow_card_sub_one_eq_one ha · simp [of_not_not ha, (Fact.out : p.Prime).one_lt, tsub_eq_zero_iff_le] theorem orderOf_units_dvd_card_sub_one (u : (ZMod p)ˣ) : orderOf u ∣ p - 1 := orderOf_dvd_of_pow_eq_one <| units_pow_card_sub_one_eq_one _ _ theorem orderOf_dvd_card_sub_one {a : ZMod p} (ha : a ≠ 0) : orderOf a ∣ p - 1 := orderOf_dvd_of_pow_eq_one <| pow_card_sub_one_eq_one ha open Polynomial theorem expand_card (f : Polynomial (ZMod p)) : expand (ZMod p) p f = f ^ p := by have h := FiniteField.expand_card f; rwa [ZMod.card p] at h end ZMod /-- **Fermat's Little Theorem**: for all `a : ℤ` coprime to `p`, we have `a ^ (p - 1) ≡ 1 [ZMOD p]`. -/ theorem Int.ModEq.pow_card_sub_one_eq_one {p : ℕ} (hp : Nat.Prime p) {n : ℤ} (hpn : IsCoprime n p) : n ^ (p - 1) ≡ 1 [ZMOD p] := by haveI : Fact p.Prime := ⟨hp⟩ have : ¬(n : ZMod p) = 0 := by rw [CharP.intCast_eq_zero_iff _ p, ← (Nat.prime_iff_prime_int.mp hp).coprime_iff_not_dvd] · exact hpn.symm simpa [← ZMod.intCast_eq_intCast_iff] using ZMod.pow_card_sub_one_eq_one this /-- **Fermat's Little Theorem**: for all `n : ℕ` coprime to `p`, we have `n ^ (p - 1) ≡ 1 [MOD p]`. -/ theorem Nat.ModEq.pow_card_sub_one_eq_one {p : ℕ} (hp : p.Prime) {n : ℕ} (hpn : n.Coprime p) : n ^ (p - 1) ≡ 1 [MOD p] := by rw [← Int.natCast_modEq_iff, Nat.cast_pow, Nat.cast_one] exact Int.ModEq.pow_card_sub_one_eq_one hp (isCoprime_iff_coprime.mpr hpn) /-- **Fermat's Little Theorem**: for all `n : ℕ` coprime to `p`, we have `(n ^ (p - 1) - 1) % p = 0`. -/ theorem Nat.pow_card_sub_one_sub_one_mod_card {p : ℕ} (hp : p.Prime) {n : ℕ} (hpn : n.Coprime p) : (n ^ (p - 1) - 1) % p = 0 := Nat.sub_mod_eq_zero_of_mod_eq (Nat.ModEq.pow_card_sub_one_eq_one hp hpn) theorem pow_pow_modEq_one (p m a : ℕ) : (1 + p * a) ^ (p ^ m) ≡ 1 [MOD p ^ m] := by induction m with | zero => exact Nat.modEq_one | succ m hm => rw [Nat.ModEq.comm, add_comm, Nat.modEq_iff_dvd' (Nat.one_le_pow' _ _)] at hm obtain ⟨d, hd⟩ := hm rw [tsub_eq_iff_eq_add_of_le (Nat.one_le_pow' _ _), add_comm] at hd rw [pow_succ, pow_mul, hd, add_pow, Finset.sum_range_succ', pow_zero, one_mul, one_pow, one_mul, Nat.choose_zero_right, Nat.cast_one] refine Nat.ModEq.add_right 1 (Nat.modEq_zero_iff_dvd.mpr ?_) simp_rw [one_pow, mul_one, pow_succ', mul_assoc, ← Finset.mul_sum] refine mul_dvd_mul_left (p ^ m) (dvd_mul_of_dvd_right (Finset.dvd_sum fun k hk ↦ ?_) d) cases m · rw [pow_zero, pow_one, one_mul, add_comm, add_left_inj] at hd cases k <;> simp [← hd, mul_assoc, pow_succ'] · cases k <;> simp [mul_assoc, pow_succ'] theorem ZMod.eq_one_or_isUnit_sub_one {n p k : ℕ} [Fact p.Prime] (hn : n = p ^ k) (a : ZMod n) (ha : (orderOf a).Coprime n) : a = 1 ∨ IsUnit (a - 1) := by rcases eq_or_ne n 0 with rfl | hn0 · exact Or.inl (orderOf_eq_one_iff.mp ((orderOf a).coprime_zero_right.mp ha)) rcases eq_or_ne a 0 with rfl | ha0 · exact Or.inr (zero_sub (1 : ZMod n) ▸ isUnit_neg_one) have : NeZero n := ⟨hn0⟩ obtain ⟨a, rfl⟩ := ZMod.natCast_zmod_surjective a rw [← orderOf_eq_one_iff, or_iff_not_imp_right] refine fun h ↦ ha.eq_one_of_dvd ?_ rw [orderOf_dvd_iff_pow_eq_one, ← Nat.cast_pow, ← Nat.cast_one, ZMod.natCast_eq_natCast_iff, hn] replace ha0 : 1 ≤ a := by contrapose! ha0 rw [Nat.lt_one_iff.mp ha0, Nat.cast_zero] rw [← Nat.cast_one, ← Nat.cast_sub ha0, ZMod.isUnit_iff_coprime, hn] at h obtain ⟨b, hb⟩ := not_imp_comm.mp (Nat.Prime.coprime_pow_of_not_dvd Fact.out) h rw [tsub_eq_iff_eq_add_of_le ha0, add_comm] at hb exact hb ▸ pow_pow_modEq_one p k b section prime_subfield variable {F : Type*} [Field F] theorem mem_bot_iff_intCast (p : ℕ) [Fact p.Prime] (K) [DivisionRing K] [CharP K p] {x : K} : x ∈ (⊥ : Subfield K) ↔ ∃ n : ℤ, n = x := by simp [← fieldRange_castHom_eq_bot p, ZMod.intCast_surjective.exists] variable (F) (p : ℕ) [Fact p.Prime] [CharP F p] theorem Subfield.card_bot : Nat.card (⊥ : Subfield F) = p := by rw [← fieldRange_castHom_eq_bot p, ← Nat.card_eq_of_bijective _ (RingHom.rangeRestrictField_bijective _), Nat.card_zmod] /-- The prime subfield is finite. -/ def Subfield.fintypeBot : Fintype (⊥ : Subfield F) := Fintype.subtype (univ.map ⟨_, (ZMod.castHom (m := p) dvd_rfl F).injective⟩) fun _ ↦ by simp_rw [Finset.mem_map, mem_univ, true_and, ← fieldRange_castHom_eq_bot p]; rfl open Polynomial theorem Subfield.roots_X_pow_char_sub_X_bot : letI := Subfield.fintypeBot F p (X ^ p - X : (⊥ : Subfield F)[X]).roots = Finset.univ.val := by let _ := Subfield.fintypeBot F p conv_lhs => rw [← card_bot F p, ← Fintype.card_eq_nat_card] exact FiniteField.roots_X_pow_card_sub_X _ theorem Subfield.splits_bot : Splits (RingHom.id (⊥ : Subfield F)) (X ^ p - X) := by let _ := Subfield.fintypeBot F p rw [splits_iff_card_roots, roots_X_pow_char_sub_X_bot, ← Finset.card_def, Finset.card_univ, FiniteField.X_pow_card_sub_X_natDegree_eq _ (Fact.out (p := p.Prime)).one_lt, Fintype.card_eq_nat_card, card_bot F p] theorem Subfield.mem_bot_iff_pow_eq_self {x : F} : x ∈ (⊥ : Subfield F) ↔ x ^ p = x := by have := roots_X_pow_char_sub_X_bot F p ▸ Polynomial.roots_map (Subfield.subtype _) (splits_bot F p) ▸ Multiset.mem_map (b := x) simpa [sub_eq_zero, iff_comm, FiniteField.X_pow_card_sub_X_ne_zero F (Fact.out : p.Prime).one_lt] end prime_subfield namespace FiniteField variable {F : Type*} [Field F] section Finite variable [Finite F] /-- In a finite field of characteristic `2`, all elements are squares. -/ theorem isSquare_of_char_two (hF : ringChar F = 2) (a : F) : IsSquare a := have : CharP F 2 := ringChar.of_eq hF isSquare_of_charTwo' a /-- In a finite field of odd characteristic, not every element is a square. -/ theorem exists_nonsquare (hF : ringChar F ≠ 2) : ∃ a : F, ¬IsSquare a := by -- Idea: the squaring map on `F` is not injective, hence not surjective have h : ¬Function.Injective fun x : F ↦ x * x := fun h ↦ h.ne (Ring.neg_one_ne_one_of_char_ne_two hF) <| by simp simpa [Finite.injective_iff_surjective, Function.Surjective, IsSquare, eq_comm] using h end Finite variable [Fintype F] /-- The finite field `F` has even cardinality iff it has characteristic `2`. -/ theorem even_card_iff_char_two : ringChar F = 2 ↔ Fintype.card F % 2 = 0 := by rcases FiniteField.card F (ringChar F) with ⟨n, hp, h⟩ rw [h, ← Nat.even_iff, Nat.even_pow, hp.even_iff] simp theorem even_card_of_char_two (hF : ringChar F = 2) : Fintype.card F % 2 = 0 := even_card_iff_char_two.mp hF theorem odd_card_of_char_ne_two (hF : ringChar F ≠ 2) : Fintype.card F % 2 = 1 := Nat.mod_two_ne_zero.mp (mt even_card_iff_char_two.mpr hF) /-- If `F` has odd characteristic, then for nonzero `a : F`, we have that `a ^ (#F / 2) = ±1`. -/ theorem pow_dichotomy (hF : ringChar F ≠ 2) {a : F} (ha : a ≠ 0) : a ^ (Fintype.card F / 2) = 1 ∨ a ^ (Fintype.card F / 2) = -1 := by have h₁ := FiniteField.pow_card_sub_one_eq_one a ha rw [← Nat.two_mul_odd_div_two (FiniteField.odd_card_of_char_ne_two hF), mul_comm, pow_mul, pow_two] at h₁ exact mul_self_eq_one_iff.mp h₁ /-- A unit `a` of a finite field `F` of odd characteristic is a square if and only if `a ^ (#F / 2) = 1`. -/ theorem unit_isSquare_iff (hF : ringChar F ≠ 2) (a : Fˣ) : IsSquare a ↔ a ^ (Fintype.card F / 2) = 1 := by classical obtain ⟨g, hg⟩ := IsCyclic.exists_generator (α := Fˣ) obtain ⟨n, hn⟩ : a ∈ Submonoid.powers g := by rw [mem_powers_iff_mem_zpowers]; apply hg have hodd := Nat.two_mul_odd_div_two (FiniteField.odd_card_of_char_ne_two hF) constructor · rintro ⟨y, rfl⟩ rw [← pow_two, ← pow_mul, hodd] apply_fun Units.val using Units.val_injective push_cast exact FiniteField.pow_card_sub_one_eq_one (y : F) (Units.ne_zero y) · subst a; intro h rw [← Nat.card_eq_fintype_card] at hodd h have key : 2 * (Nat.card F / 2) ∣ n * (Nat.card F / 2) := by rw [← pow_mul] at h rw [hodd, ← Nat.card_units, ← orderOf_eq_card_of_forall_mem_zpowers hg] apply orderOf_dvd_of_pow_eq_one h have : 0 < Nat.card F / 2 := Nat.div_pos Finite.one_lt_card (by simp) obtain ⟨m, rfl⟩ := Nat.dvd_of_mul_dvd_mul_right this key refine ⟨g ^ m, ?_⟩ dsimp rw [mul_comm, pow_mul, pow_two] /-- A non-zero `a : F` is a square if and only if `a ^ (#F / 2) = 1`. -/ theorem isSquare_iff (hF : ringChar F ≠ 2) {a : F} (ha : a ≠ 0) : IsSquare a ↔ a ^ (Fintype.card F / 2) = 1 := by apply (iff_congr _ (by simp [Units.ext_iff])).mp (FiniteField.unit_isSquare_iff hF (Units.mk0 a ha)) simp only [IsSquare, Units.ext_iff, Units.val_mk0, Units.val_mul] constructor · rintro ⟨y, hy⟩; exact ⟨y, hy⟩ · rintro ⟨y, rfl⟩ have hy : y ≠ 0 := by rintro rfl; simp at ha refine ⟨Units.mk0 y hy, ?_⟩; simp end FiniteField
LargeColimits.lean
/- Copyright (c) 2025 Sophie Morel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sophie Morel -/ import Mathlib.Algebra.Category.Grp.Colimits import Mathlib.Algebra.Module.CharacterModule import Mathlib.Algebra.Group.Equiv.Basic /-! # Existence of "big" colimits in the category of additive commutative groups If `F : J ⥤ AddCommGrp.{w}` is a functor, we show that `F` admits a colimit if and only if `Colimits.Quot F` (the quotient of the direct sum of the commutative groups `F.obj j` by the relations given by the morphisms in the diagram) is `w`-small. -/ universe w u v open CategoryTheory Limits namespace AddCommGrp variable {J : Type u} [Category.{v} J] {F : J ⥤ AddCommGrp.{w}} (c : Cocone F) open Colimits /-- If `c` is a cocone of `F` such that `Quot.desc F c` is bijective, then `c` is a colimit cocone of `F`. -/ lemma isColimit_iff_bijective_desc [DecidableEq J] : Nonempty (IsColimit c) ↔ Function.Bijective (Quot.desc F c) := by refine ⟨fun ⟨hc⟩ => ?_, fun h ↦ Nonempty.intro (isColimit_of_bijective_desc F c h)⟩ change Function.Bijective (Quot.desc F c).toIntLinearMap rw [← CharacterModule.dual_bijective_iff_bijective] refine ⟨fun χ ψ eq ↦ ?_, fun χ ↦ ?_⟩ · apply AddEquiv.ulift.symm.addMonoidHomCongrRightEquiv.injective apply ofHom_injective refine hc.hom_ext (fun j ↦ ?_) ext x rw [ConcreteCategory.comp_apply, ConcreteCategory.comp_apply, ← Quot.ι_desc _ c j x] exact DFunLike.congr_fun eq (Quot.ι F j x) · set c' : Cocone F := { pt := AddCommGrp.of (ULift (AddCircle (1 : ℚ))) ι := { app j := AddCommGrp.ofHom (((@AddEquiv.ulift _ _).symm.toAddMonoidHom.comp χ).comp (Quot.ι F j)) naturality {j j'} u := by ext dsimp rw [Quot.map_ι F (f := u)] } } use AddEquiv.ulift.toAddMonoidHom.comp (hc.desc c').hom refine Quot.addMonoidHom_ext _ (fun j x ↦ ?_) dsimp rw [Quot.ι_desc] change AddEquiv.ulift ((c.ι.app j ≫ hc.desc c') x) = _ rw [hc.fac] dsimp [c'] rw [AddEquiv.apply_symm_apply] /-- A functor `F : J ⥤ AddCommGrp.{w}` has a colimit if and only if `Colimits.Quot F` is `w`-small. -/ lemma hasColimit_iff_small_quot [DecidableEq J] : HasColimit F ↔ Small.{w} (Quot F) := ⟨fun _ ↦ Small.mk ⟨_, ⟨(Equiv.ofBijective _ ((isColimit_iff_bijective_desc (colimit.cocone F)).mp ⟨colimit.isColimit _⟩))⟩⟩, hasColimit_of_small_quot F⟩ end AddCommGrp
Equidecomp.lean
/- Copyright (c) 2024 Felix Weilacher. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Felix Weilacher -/ import Mathlib.Algebra.Group.Action.Defs import Mathlib.Logic.Equiv.PartialEquiv import Mathlib.Algebra.Group.Pointwise.Finset.Basic /-! # Equidecompositions This file develops the basic theory of equidecompositions. ## Main Definitions Let `G` be a group acting on a space `X`, and `A B : Set X`. An *equidecomposition* of `A` and `B` is typically defined as a finite partition of `A` together with a finite list of elements of `G` of the same size such that applying each element to the matching piece of the partition yields a partition of `B`. This yields a bijection `f : A ≃ B` where, given `a : A`, `f a = γ • a` for `γ : G` the group element for `a`'s piece of the partition. Reversing this is easy, and so we get an equivalent (up to the choice of group elements) definition: an *Equidecomposition* of `A` and `B` is a bijection `f : A ≃ B` such that for some `S : Finset G`, `f a ∈ S • a` for all `a`. We take this as our definition as it is easier to work with. It is implemented as an element `PartialEquiv X X` with source `A` and target `B`. ## Implementation Notes * Equidecompositions are implemented as elements of `PartialEquiv X X` together with a `Finset` of elements of the acting group and a proof that every point in the source is moved by an element in the finset. * The requirement that `G` be a group is relaxed where possible. * We introduce a non-standard predicate, `IsDecompOn`, to state that a function satisfies the main combinatorial property of equidecompositions, even if it is not injective or surjective. ## TODO * Prove that if two sets equidecompose into subsets of eachother, they are equidecomposable (Schroeder-Bernstein type theorem) * Define equidecomposability into subsets as a preorder on sets and prove that its induced equivalence relation is equidecomposability. * Prove the definition of equidecomposition used here is equivalent to the more familiar one using partitions. -/ variable {X G : Type*} {A B C : Set X} open Function Set Pointwise PartialEquiv namespace Equidecomp section SMul variable [SMul G X] /-- Let `G` act on a space `X` and `A : Set X`. We say `f : X → X` is a decomposition on `A` as witnessed by some `S : Finset G` if for all `a ∈ A`, the value `f a` can be obtained by applying some element of `S` to `a` instead. More familiarly, the restriction of `f` to `A` is the result of partitioning `A` into finitely many pieces, then applying a single element of `G` to each piece. -/ def IsDecompOn (f : X → X) (A : Set X) (S : Finset G) : Prop := ∀ a ∈ A, ∃ g ∈ S, f a = g • a variable (X G) /-- Let `G` act on a space `X`. An `Equidecomposition` with respect to `X` and `G` is a partial bijection `f : PartialEquiv X X` with the property that for some set `elements : Finset G`, (which we record), for each `a ∈ f.source`, `f a` can be obtained by applying some `g ∈ elements` instead. We call `f` an equidecomposition of `f.source` with `f.target`. More familiarly, `f` is the result of partitioning `f.source` into finitely many pieces, then applying a single element of `G` to each to get a partition of `f.target`. -/ structure _root_.Equidecomp extends PartialEquiv X X where isDecompOn' : ∃ S : Finset G, IsDecompOn toFun source S variable {X G} /-- Note that `Equidecomp X G` is not `FunLike`. -/ instance : CoeFun (Equidecomp X G) fun _ => X → X := ⟨fun f => f.toFun⟩ /-- A finite set of group elements witnessing that `f` is an equidecomposition. -/ noncomputable def witness (f : Equidecomp X G) : Finset G := f.isDecompOn'.choose theorem isDecompOn (f : Equidecomp X G) : IsDecompOn f f.source f.witness := f.isDecompOn'.choose_spec theorem apply_mem_target {f : Equidecomp X G} {x : X} (h : x ∈ f.source) : f x ∈ f.target := by simp [h] theorem toPartialEquiv_injective : Injective <| toPartialEquiv (X := X) (G := G) := by intro ⟨_, _, _⟩ _ _ congr theorem IsDecompOn.mono {f f' : X → X} {A A' : Set X} {S : Finset G} (h : IsDecompOn f A S) (hA' : A' ⊆ A) (hf' : EqOn f f' A') : IsDecompOn f' A' S := by intro a ha rw [← hf' ha] exact h a (hA' ha) /-- The restriction of an equidecomposition as an equidecomposition. -/ @[simps!] def restr (f : Equidecomp X G) (A : Set X) : Equidecomp X G where toPartialEquiv := f.toPartialEquiv.restr A isDecompOn' := ⟨f.witness, f.isDecompOn.mono (source_restr_subset_source _ _) fun _ ↦ congrFun rfl⟩ @[simp] theorem toPartialEquiv_restr (f : Equidecomp X G) (A : Set X) : (f.restr A).toPartialEquiv = f.toPartialEquiv.restr A := rfl theorem source_restr (f : Equidecomp X G) {A : Set X} (hA : A ⊆ f.source) : (f.restr A).source = A := by rw [restr_source, inter_eq_self_of_subset_right hA] theorem restr_of_source_subset {f : Equidecomp X G} {A : Set X} (hA : f.source ⊆ A) : f.restr A = f := by apply toPartialEquiv_injective rw [toPartialEquiv_restr, PartialEquiv.restr_eq_of_source_subset hA] @[simp] theorem restr_univ (f : Equidecomp X G) : f.restr univ = f := restr_of_source_subset <| subset_univ _ end SMul section Monoid variable [Monoid G] [MulAction G X] variable (X G) /-- The identity function is an equidecomposition of the space with itself. -/ @[simps toPartialEquiv] def refl : Equidecomp X G where toPartialEquiv := .refl _ isDecompOn' := ⟨{1}, by simp [IsDecompOn]⟩ variable {X} {G} open scoped Classical in theorem IsDecompOn.comp' {g f : X → X} {B A : Set X} {T S : Finset G} (hg : IsDecompOn g B T) (hf : IsDecompOn f A S) : IsDecompOn (g ∘ f) (A ∩ f ⁻¹' B) (T * S) := by intro _ ⟨aA, aB⟩ rcases hf _ aA with ⟨γ, γ_mem, hγ⟩ rcases hg _ aB with ⟨δ, δ_mem, hδ⟩ use δ * γ, Finset.mul_mem_mul δ_mem γ_mem rwa [mul_smul, ← hγ] open scoped Classical in theorem IsDecompOn.comp {g f : X → X} {B A : Set X} {T S : Finset G} (hg : IsDecompOn g B T) (hf : IsDecompOn f A S) (h : MapsTo f A B) : IsDecompOn (g ∘ f) A (T * S) := by rw [left_eq_inter.mpr h] exact hg.comp' hf /-- The composition of two equidecompositions as an equidecomposition. -/ @[simps toPartialEquiv, trans] noncomputable def trans (f g : Equidecomp X G) : Equidecomp X G where toPartialEquiv := f.toPartialEquiv.trans g.toPartialEquiv isDecompOn' := by classical exact ⟨g.witness * f.witness, g.isDecompOn.comp' f.isDecompOn⟩ end Monoid section Group variable [Group G] [MulAction G X] open scoped Classical in theorem IsDecompOn.of_leftInvOn {f g : X → X} {A : Set X} {S : Finset G} (hf : IsDecompOn f A S) (h : LeftInvOn g f A) : IsDecompOn g (f '' A) S⁻¹ := by rintro _ ⟨a, ha, rfl⟩ rcases hf a ha with ⟨γ, γ_mem, hγ⟩ use γ⁻¹, Finset.inv_mem_inv γ_mem rw [hγ, inv_smul_smul, ← hγ, h ha] /-- The inverse function of an equidecomposition as an equidecomposition. -/ @[symm, simps toPartialEquiv] noncomputable def symm (f : Equidecomp X G) : Equidecomp X G where toPartialEquiv := f.toPartialEquiv.symm isDecompOn' := by classical exact ⟨f.witness⁻¹, by convert f.isDecompOn.of_leftInvOn f.leftInvOn rw [image_source_eq_target, symm_source]⟩ theorem map_target {f : Equidecomp X G} {x : X} (h : x ∈ f.target) : f.symm x ∈ f.source := f.toPartialEquiv.map_target h theorem left_inv {f : Equidecomp X G} {x : X} (h : x ∈ f.source) : f.toPartialEquiv.symm (f x) = x := by simp [h] theorem right_inv {f : Equidecomp X G} {x : X} (h : x ∈ f.target) : f (f.toPartialEquiv.symm x) = x := by simp [h] @[simp] theorem symm_symm (f : Equidecomp X G) : f.symm.symm = f := rfl theorem symm_involutive : Function.Involutive (symm : Equidecomp X G → _) := symm_symm theorem symm_bijective : Function.Bijective (symm : Equidecomp X G → _) := symm_involutive.bijective @[simp] theorem refl_symm : (refl X G).symm = refl X G := rfl @[simp] theorem restr_refl_symm (A : Set X) : ((Equidecomp.refl X G).restr A).symm = (Equidecomp.refl X G).restr A := rfl end Group end Equidecomp
Defs.lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import Mathlib.Topology.MetricSpace.Pseudo.Defs /-! # Metric spaces This file defines metric spaces and shows some of their basic properties. Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. This includes open and closed sets, compactness, completeness, continuity and uniform continuity. TODO (anyone): Add "Main results" section. ## Implementation notes A lot of elementary properties don't require `eq_of_dist_eq_zero`, hence are stated and proven for `PseudoMetricSpace`s in `PseudoMetric.lean`. ## Tags metric, pseudo_metric, dist -/ assert_not_exists Finset.sum open Set Filter Bornology open scoped NNReal Uniformity universe u v w variable {α : Type u} {β : Type v} {X ι : Type*} variable [PseudoMetricSpace α] /-- A metric space is a type endowed with a `ℝ`-valued distance `dist` satisfying `dist x y = 0 ↔ x = y`, commutativity `dist x y = dist y x`, and the triangle inequality `dist x z ≤ dist x y + dist y z`. See pseudometric spaces (`PseudoMetricSpace`) for the similar class with the `dist x y = 0 ↔ x = y` assumption weakened to `dist x x = 0`. Any metric space is a T1 topological space and a uniform space (see `TopologicalSpace`, `T1Space`, `UniformSpace`), where the topology and uniformity come from the metric. We make the uniformity/topology part of the data instead of deriving it from the metric. This eg ensures that we do not get a diamond when doing `[MetricSpace α] [MetricSpace β] : TopologicalSpace (α × β)`: The product metric and product topology agree, but not definitionally so. See Note [forgetful inheritance]. -/ class MetricSpace (α : Type u) : Type u extends PseudoMetricSpace α where eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y /-- Two metric space structures with the same distance coincide. -/ @[ext] theorem MetricSpace.ext {α : Type*} {m m' : MetricSpace α} (h : m.toDist = m'.toDist) : m = m' := by cases m; cases m'; congr; ext1; assumption /-- Construct a metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def MetricSpace.ofDistTopology {α : Type u} [TopologicalSpace α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : Set α, IsOpen s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) (eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : MetricSpace α := { PseudoMetricSpace.ofDistTopology dist dist_self dist_comm dist_triangle H with eq_of_dist_eq_zero := eq_of_dist_eq_zero _ _ } variable {γ : Type w} [MetricSpace γ] theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y := MetricSpace.eq_of_dist_eq_zero @[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y := Iff.intro eq_of_dist_eq_zero fun this => this ▸ dist_self _ @[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y := by simpa only [not_iff_not] using dist_eq_zero @[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y := by simpa only [not_le] using not_congr dist_le_zero theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_lt_imp_le_of_dense dist_nonneg h) /-- Deduce the equality of points from the vanishing of the nonnegative distance -/ theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y := by simp only [NNReal.eq_iff, ← dist_nndist, imp_self, NNReal.coe_zero, dist_eq_zero] /-- Characterize the equality of points as the vanishing of the nonnegative distance -/ @[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y := by simp only [NNReal.eq_iff, ← dist_nndist, NNReal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y := by simp only [NNReal.eq_iff, ← dist_nndist, NNReal.coe_zero, zero_eq_dist] namespace Metric variable {x : γ} {s : Set γ} @[simp] theorem closedBall_zero : closedBall x 0 = {x} := Set.ext fun _ => dist_le_zero @[simp] theorem sphere_zero : sphere x 0 = {x} := Set.ext fun _ => dist_eq_zero theorem subsingleton_closedBall (x : γ) {r : ℝ} (hr : r ≤ 0) : (closedBall x r).Subsingleton := by rcases hr.lt_or_eq with (hr | rfl) · rw [closedBall_eq_empty.2 hr] exact subsingleton_empty · rw [closedBall_zero] exact subsingleton_singleton theorem subsingleton_sphere (x : γ) {r : ℝ} (hr : r ≤ 0) : (sphere x r).Subsingleton := (subsingleton_closedBall x hr).anti sphere_subset_closedBall end Metric /-- Build a new metric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. See Note [reducible non-instances]. -/ abbrev MetricSpace.replaceUniformity {γ} [U : UniformSpace γ] (m : MetricSpace γ) (H : 𝓤[U] = 𝓤[PseudoEMetricSpace.toUniformSpace]) : MetricSpace γ where toPseudoMetricSpace := PseudoMetricSpace.replaceUniformity m.toPseudoMetricSpace H eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _ theorem MetricSpace.replaceUniformity_eq {γ} [U : UniformSpace γ] (m : MetricSpace γ) (H : 𝓤[U] = 𝓤[PseudoEMetricSpace.toUniformSpace]) : m.replaceUniformity H = m := by ext; rfl /-- Build a new metric space from an old one where the bundled topological structure is provably (but typically non-definitionaly) equal to some given topological structure. See Note [forgetful inheritance]. See Note [reducible non-instances]. -/ abbrev MetricSpace.replaceTopology {γ} [U : TopologicalSpace γ] (m : MetricSpace γ) (H : U = m.toPseudoMetricSpace.toUniformSpace.toTopologicalSpace) : MetricSpace γ := @MetricSpace.replaceUniformity γ (m.toUniformSpace.replaceTopology H) m rfl theorem MetricSpace.replaceTopology_eq {γ} [U : TopologicalSpace γ] (m : MetricSpace γ) (H : U = m.toPseudoMetricSpace.toUniformSpace.toTopologicalSpace) : m.replaceTopology H = m := by ext; rfl /-- Build a new metric space from an old one where the bundled bornology structure is provably (but typically non-definitionaly) equal to some given bornology structure. See Note [forgetful inheritance]. See Note [reducible non-instances]. -/ abbrev MetricSpace.replaceBornology {α} [B : Bornology α] (m : MetricSpace α) (H : ∀ s, @IsBounded _ B s ↔ @IsBounded _ PseudoMetricSpace.toBornology s) : MetricSpace α := { PseudoMetricSpace.replaceBornology _ H, m with toBornology := B } theorem MetricSpace.replaceBornology_eq {α} [m : MetricSpace α] [B : Bornology α] (H : ∀ s, @IsBounded _ B s ↔ @IsBounded _ PseudoMetricSpace.toBornology s) : MetricSpace.replaceBornology _ H = m := by ext rfl instance : MetricSpace Empty where dist _ _ := 0 dist_self _ := rfl dist_comm _ _ := rfl edist _ _ := 0 eq_of_dist_eq_zero _ := Subsingleton.elim _ _ dist_triangle _ _ _ := show (0 : ℝ) ≤ 0 + 0 by rw [add_zero] toUniformSpace := inferInstance uniformity_dist := Subsingleton.elim _ _ instance : MetricSpace PUnit.{u + 1} where dist _ _ := 0 dist_self _ := rfl dist_comm _ _ := rfl edist _ _ := 0 eq_of_dist_eq_zero _ := Subsingleton.elim _ _ dist_triangle _ _ _ := show (0 : ℝ) ≤ 0 + 0 by rw [add_zero] toUniformSpace := inferInstance uniformity_dist := by simp +contextual [principal_univ, eq_top_of_neBot (𝓤 PUnit)] /-! ### `Additive`, `Multiplicative` The distance on those type synonyms is inherited without change. -/ open Additive Multiplicative section variable [Dist X] instance : Dist (Additive X) := ‹Dist X› instance : Dist (Multiplicative X) := ‹Dist X› @[simp] theorem dist_ofMul (a b : X) : dist (ofMul a) (ofMul b) = dist a b := rfl @[simp] theorem dist_ofAdd (a b : X) : dist (ofAdd a) (ofAdd b) = dist a b := rfl @[simp] theorem dist_toMul (a b : Additive X) : dist a.toMul b.toMul = dist a b := rfl @[simp] theorem dist_toAdd (a b : Multiplicative X) : dist a.toAdd b.toAdd = dist a b := rfl end instance [MetricSpace X] : MetricSpace (Additive X) := ‹MetricSpace X› instance [MetricSpace X] : MetricSpace (Multiplicative X) := ‹MetricSpace X› /-! ### Order dual The distance on this type synonym is inherited without change. -/ open OrderDual section variable [Dist X] instance : Dist Xᵒᵈ := ‹Dist X› @[simp] theorem dist_toDual (a b : X) : dist (toDual a) (toDual b) = dist a b := rfl @[simp] theorem dist_ofDual (a b : Xᵒᵈ) : dist (ofDual a) (ofDual b) = dist a b := rfl end instance [MetricSpace X] : MetricSpace Xᵒᵈ := ‹MetricSpace X›
nmodule.v
From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype choice ssrnat seq. From mathcomp Require Import bigop fintype finfun monoid. (******************************************************************************) (* Additive group-like structures *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file defines the following algebraic structures: *) (* *) (* baseAddMagmaType == type with an addition operator *) (* The HB class is called BaseAddMagma. *) (* ChoiceBaseAddMagma.type == join of baseAddMagmaType and choiceType *) (* The HB class is called ChoiceBaseAddMagma. *) (* addMagmaType == additive magma *) (* The HB class is called AddMagma. *) (* addSemigroupType == additive semigroup *) (* The HB class is called AddSemigroup. *) (* baseAddUMagmaType == pointed additive magma *) (* The HB class is called BaseAddUMagma. *) (* ChoiceBaseAddUMagma.type == join of baseAddUMagmaType and choiceType *) (* The HB class is called ChoiceBaseUMagma. *) (* addUmagmaType == additive unitary magma *) (* The HB class is called AddUMagma. *) (* nmodType == additive monoid *) (* The HB class is called Nmodule. *) (* baseZmodType == pointed additive magma with an opposite *) (* operator *) (* The HB class is called BaseZmodule. *) (* zmodType == abelian group *) (* The HB class is called Group. *) (* *) (* and their joins with subType: *) (* *) (* subBaseAddUMagmaType V P == join of baseAddUMagmaType and subType *) (* (P : pred V) such that val is additive *) (* The HB class is called SubBaseAddUMagma. *) (* subAddUMagmaType V P == join of addUMagmaType and subType (P : pred V)*) (* such that val is additive *) (* The HB class is called SubAddUMagma. *) (* subNmodType V P == join of nmodType and subType (P : pred V) *) (* such that val is additive *) (* The HB class is called SubNmodule. *) (* subZmodType V P == join of zmodType and subType (P : pred V) *) (* such that val is additive *) (* The HB class is called SubZmodule. *) (* *) (* Morphisms between the above structures (see below for details): *) (* *) (* {additive U -> V} == nmod (resp. zmod) morphism between nmodType *) (* (resp. zmodType) instances U and V. *) (* The HB class is called Additive. *) (* *) (* Closedness predicates for the algebraic structures: *) (* *) (* mulgClosed V == predicate closed under multiplication on G : magmaType *) (* The HB class is called MulClosed. *) (* umagmaClosed V == predicate closed under multiplication and containing 1 *) (* on G : baseUMagmaType *) (* The HB class is called UMagmaClosed. *) (* invgClosed V == predicate closed under inversion on G : baseGroupType *) (* The HB class is called InvClosed. *) (* groupClosed V == predicate closed under multiplication and inversion and *) (* containing 1 on G : baseGroupType *) (* The HB class is called InvClosed. *) (* *) (* Canonical properties of the algebraic structures: *) (* * addMagmaType (additive magmas): *) (* x + y == the addition of x and y *) (* addr_closed S <-> collective predicate S is closed under addition *) (* *) (* * baseAddUMagmaType (pointed additive magmas): *) (* 0 == the zero of a unitary additive magma *) (* x *+ n == n times x, with n in nat (non-negative), *) (* i.e. x + (x + .. (x + x)..) (n terms); x *+ 1 is *) (* thus convertible to x, and x *+ 2 to x + x *) (* \sum_<range> e == iterated sum for a baseAddUMagmaType (cf bigop.v)*) (* e`_i == nth 0 e i, when e : seq M and M has an *) (* addUMagmaType structure *) (* support f == 0.-support f, i.e., [pred x | f x != 0] *) (* addumagma_closed S <-> collective predicate S is closed under *) (* addition and contains 0 *) (* *) (* * nmodType (abelian monoids): *) (* nmod_closed S := addumagma_closed S *) (* *) (* * baseZmodType (pointed additive magmas with an opposite operator): *) (* - x == the opposite of x *) (* x - y == x + (- y) *) (* x *- n == - (x *+ n) *) (* oppr_closed S <-> collective predicate S is closed under opposite *) (* subr_closed S <-> collective predicate S is closed under *) (* subtraction *) (* zmod_closed S <-> collective predicate S is closed under *) (* subtraction and contains 1 *) (* *) (* In addition to this structure hierarchy, we also develop a separate, *) (* parallel hierarchy for morphisms linking these structures: *) (* *) (* * Additive (nmod or zmod morphisms): *) (* nmod_morphism f <-> f of type U -> V is an nmod morphism, i.e., f *) (* maps the Nmodule structure of U to that of V, 0 *) (* to 0 and + to + *) (* := (f 0 = 0) * {morph f : x y / x + y} *) (* zmod_morphisme f <-> f of type U -> V is a zmod morphism, i.e., f *) (* maps the Zmodule structure of U to that of V, 0 *) (* to 0, - to - and + to + (equivalently, binary - *) (* to -) *) (* := {morph f : u v / u - v} *) (* {additive U -> V} == the interface type for a Structure (keyed on *) (* a function f : U -> V) that encapsulates the *) (* nmod_morphism property; both U and V must have *) (* canonical baseAddUMagmaType instances *) (* When both U and V have zmodType instances, it is *) (* a zmod morphism. *) (* := Algebra.Additive.type U V *) (* *) (* Notations are defined in scope ring_scope (delimiter %R) *) (* This library also extends the conventional suffixes described in library *) (* ssrbool.v with the following: *) (* 0 -- unitary additive magma 0, as in addr0 : x + 0 = x *) (* D -- additive magma addition, as in mulrnDr : *) (* x *+ (m + n) = x *+ m + x *+ n *) (* B -- z-module subtraction, as in opprB : - (x - y) = y - x *) (* Mn -- ring by nat multiplication, as in raddfMn : f (x *+ n) = f x *+ n *) (* N -- z-module opposite, as in mulNr : (- x) * y = - (x * y) *) (* The operator suffixes D, B are also used for the corresponding operations *) (* on nat, as in mulrDr : x *+ (m + n) = x *+ m + x *+ n. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope ring_scope. Delimit Scope ring_scope with R. Local Open Scope ring_scope. Reserved Notation "+%R" (at level 0). Reserved Notation "-%R" (at level 0). Reserved Notation "n %:R" (at level 1, left associativity, format "n %:R"). Reserved Notation "\0" (at level 0). Reserved Notation "f \+ g" (at level 50, left associativity). Reserved Notation "f \- g" (at level 50, left associativity). Reserved Notation "\- f" (at level 35, f at level 35). Reserved Notation "'{' 'additive' U '->' V '}'" (at level 0, U at level 98, V at level 99, format "{ 'additive' U -> V }"). Module Import Algebra. HB.mixin Record hasAdd V := { add : V -> V -> V }. #[short(type="baseAddMagmaType")] HB.structure Definition BaseAddMagma := {V of hasAdd V}. Module BaseAddMagmaExports. Bind Scope ring_scope with BaseAddMagma.sort. End BaseAddMagmaExports. HB.export BaseAddMagmaExports. HB.structure Definition ChoiceBaseAddMagma := {V of BaseAddMagma V & Choice V}. Module ChoiceBaseAddMagmaExports. Bind Scope ring_scope with ChoiceBaseAddMagma.sort. End ChoiceBaseAddMagmaExports. HB.export ChoiceBaseAddMagmaExports. Local Notation "+%R" := (@add _) : function_scope. Local Notation "x + y" := (add x y) : ring_scope. Definition to_multiplicative := @id Type. #[export] HB.instance Definition _ (V : choiceType) := Choice.on (to_multiplicative V). #[export] HB.instance Definition _ (V : baseAddMagmaType) := hasMul.Build (to_multiplicative V) (@add V). (* FIXME: HB.saturate *) #[export] HB.instance Definition _ (V : ChoiceBaseAddMagma.type) := Magma.on (to_multiplicative V). Section BaseAddMagmaTheory. Variables V : baseAddMagmaType. Section ClosedPredicates. Variable S : {pred V}. Definition addr_closed := {in S &, forall u v, u + v \in S}. End ClosedPredicates. End BaseAddMagmaTheory. HB.mixin Record BaseAddMagma_isAddMagma V of BaseAddMagma V := { addrC : commutative (@add V) }. #[short(type="addMagmaType")] HB.structure Definition AddMagma := {V of BaseAddMagma_isAddMagma V & ChoiceBaseAddMagma V}. HB.factory Record isAddMagma V of Choice V := { add : V -> V -> V; addrC : commutative add }. HB.builders Context V of isAddMagma V. HB.instance Definition _ := hasAdd.Build V add. HB.instance Definition _ := BaseAddMagma_isAddMagma.Build V addrC. HB.end. Module AddMagmaExports. Bind Scope ring_scope with AddMagma.sort. End AddMagmaExports. HB.export AddMagmaExports. Section AddMagmaTheory. Variables V : addMagmaType. Lemma commuteT x y : @commute (to_multiplicative V) x y. Proof. exact/addrC. Qed. End AddMagmaTheory. HB.mixin Record AddMagma_isAddSemigroup V of AddMagma V := { addrA : associative (@add V) }. #[short(type="addSemigroupType")] HB.structure Definition AddSemigroup := {V of AddMagma_isAddSemigroup V & AddMagma V}. HB.factory Record isAddSemigroup V of Choice V := { add : V -> V -> V; addrC : commutative add; addrA : associative add }. HB.builders Context V of isAddSemigroup V. HB.instance Definition _ := isAddMagma.Build V addrC. HB.instance Definition _ := AddMagma_isAddSemigroup.Build V addrA. HB.end. Module AddSemigroupExports. Bind Scope ring_scope with AddSemigroup.sort. End AddSemigroupExports. HB.export AddSemigroupExports. #[export] HB.instance Definition _ (V : addSemigroupType) := Magma_isSemigroup.Build (to_multiplicative V) addrA. Section AddSemigroupTheory. Variables V : addSemigroupType. Lemma addrCA : @left_commutative V V +%R. Proof. by move=> x y z; rewrite !addrA [x + _]addrC. Qed. Lemma addrAC : @right_commutative V V +%R. Proof. by move=> x y z; rewrite -!addrA [y + _]addrC. Qed. Lemma addrACA : @interchange V +%R +%R. Proof. by move=> x y z t; rewrite -!addrA [y + (z + t)]addrCA. Qed. End AddSemigroupTheory. HB.mixin Record hasZero V := { zero : V }. #[short(type="baseAddUMagmaType")] HB.structure Definition BaseAddUMagma := {V of hasZero V & BaseAddMagma V}. Module BaseAddUMagmaExports. Bind Scope ring_scope with BaseAddUMagma.sort. End BaseAddUMagmaExports. HB.export BaseAddUMagmaExports. HB.structure Definition ChoiceBaseAddUMagma := {V of BaseAddUMagma V & Choice V}. Module ChoiceBaseAddUMagmaExports. Bind Scope ring_scope with ChoiceBaseAddUMagma.sort. End ChoiceBaseAddUMagmaExports. HB.export ChoiceBaseAddUMagmaExports. Local Notation "0" := (@zero _) : ring_scope. Definition natmul (V : baseAddUMagmaType) (x : V) n : V := iterop n +%R x 0. Arguments natmul : simpl never. Local Notation "x *+ n" := (natmul x n) : ring_scope. #[export] HB.instance Definition _ (V : baseAddUMagmaType) := hasOne.Build (to_multiplicative V) (@zero V). (* FIXME: HB.saturate *) #[export] HB.instance Definition _ (V : ChoiceBaseAddUMagma.type) := BaseUMagma.on (to_multiplicative V). Section BaseAddUMagmaTheory. Variable V : baseAddUMagmaType. Implicit Types x : V. Lemma mulr0n x : x *+ 0 = 0. Proof. by []. Qed. Lemma mulr1n x : x *+ 1 = x. Proof. by []. Qed. Lemma mulr2n x : x *+ 2 = x + x. Proof. by []. Qed. Lemma mulrb x (b : bool) : x *+ b = (if b then x else 0). Proof. exact: (@expgb (to_multiplicative V)). Qed. Lemma mulrSS x n : x *+ n.+2 = x + x *+ n.+1. Proof. by []. Qed. Section ClosedPredicates. Variable S : {pred V}. Definition addumagma_closed := 0 \in S /\ addr_closed S. End ClosedPredicates. End BaseAddUMagmaTheory. HB.mixin Record BaseAddUMagma_isAddUMagma V of BaseAddUMagma V := { add0r : left_id zero (@add V) }. HB.factory Record isAddUMagma V of Choice V := { add : V -> V -> V; zero : V; addrC : commutative add; add0r : left_id zero add }. HB.builders Context V of isAddUMagma V. HB.instance Definition _ := isAddMagma.Build V addrC. HB.instance Definition _ := hasZero.Build V zero. #[warning="-HB.no-new-instance"] HB.instance Definition _ := BaseAddUMagma_isAddUMagma.Build V add0r. HB.end. #[short(type="addUMagmaType")] HB.structure Definition AddUMagma := {V of isAddUMagma V & Choice V}. Lemma addr0 (V : addUMagmaType) : right_id (@zero V) add. Proof. by move=> x; rewrite addrC add0r. Qed. Local Notation "\sum_ ( i <- r | P ) F" := (\big[+%R/0]_(i <- r | P) F). Local Notation "\sum_ ( m <= i < n ) F" := (\big[+%R/0]_(m <= i < n) F). Local Notation "\sum_ ( i < n ) F" := (\big[+%R/0]_(i < n) F). Local Notation "\sum_ ( i 'in' A ) F" := (\big[+%R/0]_(i in A) F). Import Monoid.Theory. #[export] HB.instance Definition _ (V : addUMagmaType) := Magma_isUMagma.Build (to_multiplicative V) add0r (@addr0 V). HB.factory Record isNmodule V of Choice V := { zero : V; add : V -> V -> V; addrA : associative add; addrC : commutative add; add0r : left_id zero add }. HB.builders Context V of isNmodule V. HB.instance Definition _ := isAddUMagma.Build V addrC add0r. HB.instance Definition _ := AddMagma_isAddSemigroup.Build V addrA. HB.end. Module AddUMagmaExports. Bind Scope ring_scope with AddUMagma.sort. End AddUMagmaExports. HB.export AddUMagmaExports. #[short(type="nmodType")] HB.structure Definition Nmodule := {V of isNmodule V & Choice V}. Module NmoduleExports. Bind Scope ring_scope with Nmodule.sort. End NmoduleExports. HB.export NmoduleExports. #[export] HB.instance Definition _ (V : nmodType) := UMagma_isMonoid.Build (to_multiplicative V) addrA. #[export] HB.instance Definition _ (V : nmodType) := Monoid.isComLaw.Build V 0%R +%R addrA addrC add0r. Section NmoduleTheory. Variable V : nmodType. Implicit Types x y : V. Let G := to_multiplicative V. (* addrA, addrC and add0r in the structure *) (* addr0 proved above *) Lemma mulrS x n : x *+ n.+1 = x + (x *+ n). Proof. exact: (@expgS G). Qed. Lemma mulrSr x n : x *+ n.+1 = x *+ n + x. Proof. exact: (@expgSr G). Qed. Lemma mul0rn n : 0 *+ n = 0 :> V. Proof. exact: (@expg1n G). Qed. Lemma mulrnDl n : {morph (fun x => x *+ n) : x y / x + y}. Proof. by move=> x y; apply/(@expgMn G)/commuteT. Qed. Lemma mulrnDr x m n : x *+ (m + n) = x *+ m + x *+ n. Proof. exact: (@expgnDr G). Qed. Lemma mulrnA x m n : x *+ (m * n) = x *+ m *+ n. Proof. exact: (@expgnA G). Qed. Lemma mulrnAC x m n : x *+ m *+ n = x *+ n *+ m. Proof. exact: (@expgnAC G). Qed. Lemma iter_addr n x y : iter n (+%R x) y = x *+ n + y. Proof. exact: (@iter_mulg G). Qed. Lemma iter_addr_0 n x : iter n (+%R x) 0 = x *+ n. Proof. exact: (@iter_mulg_1 G). Qed. Lemma sumrMnl I r P (F : I -> V) n : \sum_(i <- r | P i) F i *+ n = (\sum_(i <- r | P i) F i) *+ n. Proof. by rewrite (big_morph _ (mulrnDl n) (mul0rn _)). Qed. Lemma sumrMnr x I r P (F : I -> nat) : \sum_(i <- r | P i) x *+ F i = x *+ (\sum_(i <- r | P i) F i). Proof. by rewrite (big_morph _ (mulrnDr x) (erefl _)). Qed. Lemma sumr_const (I : finType) (A : pred I) x : \sum_(i in A) x = x *+ #|A|. Proof. by rewrite big_const -iteropE. Qed. Lemma sumr_const_nat m n x : \sum_(n <= i < m) x = x *+ (m - n). Proof. by rewrite big_const_nat iter_addr_0. Qed. End NmoduleTheory. Notation nmod_closed := addumagma_closed. HB.mixin Record hasOpp V := { opp : V -> V }. #[short(type="baseZmodType")] HB.structure Definition BaseZmodule := {V of hasOpp V & BaseAddUMagma V}. Module BaseZmodExports. Bind Scope ring_scope with BaseZmodule.sort. End BaseZmodExports. HB.export BaseZmodExports. Local Notation "-%R" := (@opp _) : ring_scope. Local Notation "- x" := (opp x) : ring_scope. Local Notation "x - y" := (x + - y) : ring_scope. Local Notation "x *- n" := (- (x *+ n)) : ring_scope. Section ClosedPredicates. Variable (U : baseZmodType) (S : {pred U}). Definition oppr_closed := {in S, forall u, - u \in S}. Definition subr_closed := {in S &, forall u v, u - v \in S}. Definition zmod_closed := 0 \in S /\ subr_closed. End ClosedPredicates. HB.mixin Record BaseZmoduleNmodule_isZmodule V of BaseZmodule V := { addNr : left_inverse zero opp (@add V) }. #[short(type="zmodType")] HB.structure Definition Zmodule := {V of BaseZmoduleNmodule_isZmodule V & BaseZmodule V & Nmodule V}. HB.factory Record Nmodule_isZmodule V of Nmodule V := { opp : V -> V; addNr : left_inverse zero opp add }. HB.builders Context V of Nmodule_isZmodule V. HB.instance Definition _ := hasOpp.Build V opp. HB.instance Definition _ := BaseZmoduleNmodule_isZmodule.Build V addNr. HB.end. HB.factory Record isZmodule V of Choice V := { zero : V; opp : V -> V; add : V -> V -> V; addrA : associative add; addrC : commutative add; add0r : left_id zero add; addNr : left_inverse zero opp add }. HB.builders Context V of isZmodule V. HB.instance Definition _ := isNmodule.Build V addrA addrC add0r. HB.instance Definition _ := Nmodule_isZmodule.Build V addNr. HB.end. Module ZmoduleExports. Bind Scope ring_scope with Zmodule.sort. End ZmoduleExports. HB.export ZmoduleExports. Lemma addrN (V : zmodType) : @right_inverse V V V 0 -%R +%R. Proof. by move=> x; rewrite addrC addNr. Qed. #[export] HB.instance Definition _ (V : baseZmodType) := hasInv.Build (to_multiplicative V) (@opp V). #[export] HB.instance Definition _ (V : zmodType) := Monoid_isGroup.Build (to_multiplicative V) addNr (@addrN V). Section ZmoduleTheory. Variable V : zmodType. Implicit Types x y : V. Let G := to_multiplicative V. Definition subrr := addrN. Lemma addKr : @left_loop V V -%R +%R. Proof. exact: (@mulKg G). Qed. Lemma addNKr : @rev_left_loop V V -%R +%R. Proof. exact: (@mulVKg G). Qed. Lemma addrK : @right_loop V V -%R +%R. Proof. exact: (@mulgK G). Qed. Lemma addrNK : @rev_right_loop V V -%R +%R. Proof. exact: (@mulgVK G). Qed. Definition subrK := addrNK. Lemma subKr x : involutive (fun y => x - y). Proof. by move=> y; exact/(@divKg G)/commuteT. Qed. Lemma addrI : @right_injective V V V +%R. Proof. exact: (@mulgI G). Qed. Lemma addIr : @left_injective V V V +%R. Proof. exact: (@mulIg G). Qed. Lemma subrI : right_injective (fun x y => x - y). Proof. exact: (@divgI G). Qed. Lemma subIr : left_injective (fun x y => x - y). Proof. exact: (@divIg G). Qed. Lemma opprK : @involutive V -%R. Proof. exact: (@invgK G). Qed. Lemma oppr_inj : @injective V V -%R. Proof. exact: (@invg_inj G). Qed. Lemma oppr0 : -0 = 0 :> V. Proof. exact: (@invg1 G). Qed. Lemma oppr_eq0 x : (- x == 0) = (x == 0). Proof. exact: (@invg_eq1 G). Qed. Lemma subr0 x : x - 0 = x. Proof. exact: (@divg1 G). Qed. Lemma sub0r x : 0 - x = - x. Proof. exact: (@div1g G). Qed. Lemma opprB x y : - (x - y) = y - x. Proof. exact: (@invgF G). Qed. Lemma opprD : {morph -%R: x y / x + y : V}. Proof. by move=> x y; rewrite -[y in LHS]opprK opprB addrC. Qed. Lemma addrKA z x y : (x + z) - (z + y) = x - y. Proof. by rewrite opprD addrA addrK. Qed. Lemma subrKA z x y : (x - z) + (z + y) = x + y. Proof. exact: (@divgKA G). Qed. Lemma addr0_eq x y : x + y = 0 -> - x = y. Proof. exact: (@mulg1_eq G). Qed. Lemma subr0_eq x y : x - y = 0 -> x = y. Proof. exact: (@divg1_eq G). Qed. Lemma subr_eq x y z : (x - z == y) = (x == y + z). Proof. exact: (@divg_eq G). Qed. Lemma subr_eq0 x y : (x - y == 0) = (x == y). Proof. exact: (@divg_eq1 G). Qed. Lemma addr_eq0 x y : (x + y == 0) = (x == - y). Proof. exact: (@mulg_eq1 G). Qed. Lemma eqr_opp x y : (- x == - y) = (x == y). Proof. exact: (@eqg_inv G). Qed. Lemma eqr_oppLR x y : (- x == y) = (x == - y). Proof. exact: (@eqg_invLR G). Qed. Lemma mulNrn x n : (- x) *+ n = x *- n. Proof. exact: (@expVgn G). Qed. Lemma mulrnBl n : {morph (fun x => x *+ n) : x y / x - y}. Proof. by move=> x y; exact/(@expgnFl G)/commuteT. Qed. Lemma mulrnBr x m n : n <= m -> x *+ (m - n) = x *+ m - x *+ n. Proof. exact: (@expgnFr G). Qed. Lemma sumrN I r P (F : I -> V) : (\sum_(i <- r | P i) - F i = - (\sum_(i <- r | P i) F i)). Proof. by rewrite (big_morph _ opprD oppr0). Qed. Lemma sumrB I r (P : pred I) (F1 F2 : I -> V) : \sum_(i <- r | P i) (F1 i - F2 i) = \sum_(i <- r | P i) F1 i - \sum_(i <- r | P i) F2 i. Proof. by rewrite -sumrN -big_split /=. Qed. Lemma telescope_sumr n m (f : nat -> V) : n <= m -> \sum_(n <= k < m) (f k.+1 - f k) = f m - f n. Proof. move=> nm; rewrite (telescope_big (fun i j => f j - f i)). by case: ltngtP nm => // ->; rewrite subrr. by move=> k /andP[nk km]/=; rewrite addrC subrKA. Qed. Lemma telescope_sumr_eq n m (f u : nat -> V) : n <= m -> (forall k, (n <= k < m)%N -> u k = f k.+1 - f k) -> \sum_(n <= k < m) u k = f m - f n. Proof. by move=> ? uE; under eq_big_nat do rewrite uE //=; exact: telescope_sumr. Qed. Section ClosedPredicates. Variable (S : {pred V}). Lemma zmod_closedN : zmod_closed S -> oppr_closed S. Proof. exact: (@group_closedV G). Qed. Lemma zmod_closedD : zmod_closed S -> addr_closed S. Proof. exact: (@group_closedM G). Qed. Lemma zmod_closed0D : zmod_closed S -> nmod_closed S. Proof. by move=> z; split; [case: z|apply: zmod_closedD]. Qed. End ClosedPredicates. End ZmoduleTheory. Arguments addrI {V} y [x1 x2]. Arguments addIr {V} x [x1 x2]. Arguments opprK {V}. Arguments oppr_inj {V} [x1 x2]. Definition nmod_morphism (U V : baseAddUMagmaType) (f : U -> V) : Prop := (f 0 = 0) * {morph f : x y / x + y}. #[deprecated(since="mathcomp 2.5.0", note="use `nmod_morphism` instead")] Definition semi_additive := nmod_morphism. HB.mixin Record isNmodMorphism (U V : baseAddUMagmaType) (apply : U -> V) := { nmod_morphism_subproof : nmod_morphism apply; }. Module isSemiAdditive. #[deprecated(since="mathcomp 2.5.0", note="Use isNmodMorphism.Build instead.")] Notation Build U V apply := (isNmodMorphism.Build U V apply) (only parsing). End isSemiAdditive. #[mathcomp(axiom="nmod_morphism")] HB.structure Definition Additive (U V : baseAddUMagmaType) := {f of isNmodMorphism U V f}. Definition zmod_morphism (U V : zmodType) (f : U -> V) := {morph f : x y / x - y}. #[deprecated(since="mathcomp 2.5.0", note="use `zmod_morphism` instead")] Definition additive := zmod_morphism. HB.factory Record isZmodMorphism (U V : zmodType) (apply : U -> V) := { zmod_morphism_subproof : zmod_morphism apply; }. Module isAdditive. #[deprecated(since="mathcomp 2.5.0", note="Use isZmodMorphism.Build instead.")] Notation Build U V apply := (isZmodMorphism.Build U V apply) (only parsing). End isAdditive. HB.builders Context U V apply of isZmodMorphism U V apply. Local Lemma raddf0 : apply 0 = 0. Proof. by rewrite -[0]subr0 zmod_morphism_subproof subrr. Qed. Local Lemma raddfD : {morph apply : x y / x + y}. Proof. move=> x y; rewrite -[y in LHS]opprK -[- y]add0r. by rewrite !zmod_morphism_subproof raddf0 sub0r opprK. Qed. HB.instance Definition _ := isNmodMorphism.Build U V apply (conj raddf0 raddfD). HB.end. Module AdditiveExports. Notation "{ 'additive' U -> V }" := (Additive.type U%type V%type) : type_scope. End AdditiveExports. HB.export AdditiveExports. Section AdditiveTheory. Variables (U V : baseAddUMagmaType) (f : {additive U -> V}). Lemma raddf0 : f 0 = 0. Proof. exact: nmod_morphism_subproof.1. Qed. Lemma raddfD : {morph f : x y / x + y}. Proof. exact: nmod_morphism_subproof.2. Qed. End AdditiveTheory. Definition to_fmultiplicative U V := @id (to_multiplicative U -> to_multiplicative V). #[export] HB.instance Definition _ U V (f : {additive U -> V}) := isMultiplicative.Build (to_multiplicative U) (to_multiplicative V) (to_fmultiplicative f) (@raddfD _ _ f). #[export] HB.instance Definition _ (U V : baseAddUMagmaType) (f : {additive U -> V}) := Multiplicative_isUMagmaMorphism.Build (to_multiplicative U) (to_multiplicative V) (to_fmultiplicative f) (@raddf0 _ _ f). Section LiftedAddMagma. Variables (U : Type) (V : baseAddMagmaType). Definition add_fun (f g : U -> V) x := f x + g x. End LiftedAddMagma. Section LiftedNmod. Variables (U : Type) (V : baseAddUMagmaType). Definition null_fun of U : V := 0. End LiftedNmod. Section LiftedZmod. Variables (U : Type) (V : baseZmodType). Definition opp_fun (f : U -> V) x := - f x. Definition sub_fun (f g : U -> V) x := f x - g x. End LiftedZmod. Arguments null_fun {_} V _ /. Arguments add_fun {_ _} f g _ /. Arguments opp_fun {_ _} f _ /. Arguments sub_fun {_ _} f g _ /. Local Notation "\0" := (null_fun _) : function_scope. Local Notation "f \+ g" := (add_fun f g) : function_scope. Local Notation "\- f" := (opp_fun f) : function_scope. Local Notation "f \- g" := (sub_fun f g) : function_scope. Section Nmod. Variables (U V : addUMagmaType) (f : {additive U -> V}). Let g := to_fmultiplicative f. Lemma raddf_eq0 x : injective f -> (f x == 0) = (x == 0). Proof. exact: (@gmulf_eq1 _ _ g). Qed. Lemma raddfMn n : {morph f : x / x *+ n}. Proof. exact: (@gmulfXn _ _ g). Qed. Lemma raddf_sum I r (P : pred I) E : f (\sum_(i <- r | P i) E i) = \sum_(i <- r | P i) f (E i). Proof. exact: (@gmulf_prod _ _ g). Qed. Lemma can2_nmod_morphism f' : cancel f f' -> cancel f' f -> nmod_morphism f'. Proof. split; first exact/(@can2_gmulf1 _ _ g). exact/(@can2_gmulfM _ _ g). Qed. #[deprecated(since="mathcomp 2.5.0", note="use `can2_nmod_morphism` instead")] Definition can2_semi_additive := can2_nmod_morphism. End Nmod. Section Zmod. Variables (U V : zmodType) (f : {additive U -> V}). Let g := to_fmultiplicative f. Lemma raddfN : {morph f : x / - x}. Proof. exact: (@gmulfV _ _ g). Qed. Lemma raddfB : {morph f : x y / x - y}. Proof. exact: (@gmulfF _ _ g). Qed. Lemma raddf_inj : (forall x, f x = 0 -> x = 0) -> injective f. Proof. exact: (@gmulf_inj _ _ g). Qed. Lemma raddfMNn n : {morph f : x / x *- n}. Proof. exact: (@gmulfXVn _ _ g). Qed. Lemma can2_zmod_morphism f' : cancel f f' -> cancel f' f -> zmod_morphism f'. Proof. by move=> fK f'K x y /=; apply: (canLR fK); rewrite raddfB !f'K. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `can2_zmod_morphism` instead")] Definition can2_additive := can2_zmod_morphism. End Zmod. Section AdditiveTheory. Section AddCFun. Variables (U : baseAddUMagmaType) (V : nmodType). Implicit Types (f g : {additive U -> V}). Fact add_fun_nmod_morphism f g : nmod_morphism (add_fun f g). Proof. by split=> [|x y]; rewrite /= ?raddf0 ?addr0// !raddfD addrCA -!addrA addrCA. Qed. #[export] HB.instance Definition _ f g := isNmodMorphism.Build U V (add_fun f g) (add_fun_nmod_morphism f g). End AddCFun. Section AddFun. Variables (U V W : baseAddUMagmaType). Variables (f : {additive V -> W}) (g : {additive U -> V}). Fact idfun_is_nmod_morphism : nmod_morphism (@idfun U). Proof. by []. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U U idfun idfun_is_nmod_morphism. Fact comp_is_nmod_morphism : nmod_morphism (f \o g). Proof. by split=> [|x y]; rewrite /= ?raddf0// !raddfD. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U W (f \o g) comp_is_nmod_morphism. End AddFun. Section AddFun. Variables (U : baseAddUMagmaType) (V : addUMagmaType) (W : nmodType). Variables (f g : {additive U -> W}). Fact null_fun_is_nmod_morphism : nmod_morphism (\0 : U -> V). Proof. by split=> // x y /=; rewrite addr0. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U V (\0 : U -> V) null_fun_is_nmod_morphism. End AddFun. Section AddVFun. Variables (U : baseAddUMagmaType) (V : zmodType). Variables (f g : {additive U -> V}). Fact opp_is_zmod_morphism : zmod_morphism (-%R : V -> V). Proof. by move=> x y; rewrite /= opprD. Qed. #[export] HB.instance Definition _ := isZmodMorphism.Build V V -%R opp_is_zmod_morphism. Fact opp_fun_is_zmod_morphism : nmod_morphism (\- f). Proof. split=> [|x y]; first by rewrite -[LHS]/(- (f 0)) raddf0 oppr0. by rewrite -[LHS]/(- (f (x + y))) !raddfD/=. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U V (opp_fun f) opp_fun_is_zmod_morphism. Fact sub_fun_is_zmod_morphism : nmod_morphism (f \- g). Proof. split=> [|x y]/=; first by rewrite !raddf0 addr0. by rewrite !raddfD/= addrACA. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U V (f \- g) sub_fun_is_zmod_morphism. End AddVFun. End AdditiveTheory. (* Mixins for stability properties *) HB.mixin Record isAddClosed (V : baseAddUMagmaType) (S : {pred V}) := { nmod_closed_subproof : addumagma_closed S }. HB.mixin Record isOppClosed (V : zmodType) (S : {pred V}) := { oppr_closed_subproof : oppr_closed S }. (* Structures for stability properties *) #[short(type="addrClosed")] HB.structure Definition AddClosed V := {S of isAddClosed V S}. #[short(type="opprClosed")] HB.structure Definition OppClosed V := {S of isOppClosed V S}. #[short(type="zmodClosed")] HB.structure Definition ZmodClosed V := {S of OppClosed V S & AddClosed V S}. (* Factories for stability properties *) HB.factory Record isZmodClosed (V : zmodType) (S : V -> bool) := { zmod_closed_subproof : zmod_closed S }. HB.builders Context V S of isZmodClosed V S. HB.instance Definition _ := isOppClosed.Build V S (zmod_closedN zmod_closed_subproof). HB.instance Definition _ := isAddClosed.Build V S (zmod_closed0D zmod_closed_subproof). HB.end. Definition to_pmultiplicative (T : Type) := @id {pred to_multiplicative T}. #[export] HB.instance Definition _ (U : baseAddUMagmaType) (S : addrClosed U) := isMulClosed.Build (to_multiplicative U) (to_pmultiplicative S) (snd nmod_closed_subproof). #[export] HB.instance Definition _ (U : baseAddUMagmaType) (S : addrClosed U) := isMul1Closed.Build (to_multiplicative U) (to_pmultiplicative S) (fst nmod_closed_subproof). #[export] HB.instance Definition _ (U : zmodType) (S : opprClosed U) := isInvClosed.Build (to_multiplicative U) (to_pmultiplicative S) oppr_closed_subproof. (* FIXME: HB.saturate *) #[export] HB.instance Definition _ (U : zmodType) (S : zmodClosed U) := InvClosed.on (to_pmultiplicative S). Section BaseAddUMagmaPred. Variables (V : baseAddUMagmaType). Section BaseAddUMagmaPred. Variables S : addrClosed V. Lemma rpred0 : 0 \in S. Proof. by case: (@nmod_closed_subproof V S). Qed. Lemma rpredD : {in S &, forall u v, u + v \in S}. Proof. by case: (@nmod_closed_subproof V S). Qed. Lemma rpred0D : addumagma_closed S. Proof. exact: nmod_closed_subproof. Qed. Lemma rpredMn n : {in S, forall u, u *+ n \in S}. Proof. exact: (@gpredXn _ (to_pmultiplicative S)). Qed. Lemma rpred_sum I r (P : pred I) F : (forall i, P i -> F i \in S) -> \sum_(i <- r | P i) F i \in S. Proof. by move=> IH; elim/big_ind: _; [apply: rpred0 | apply: rpredD |]. Qed. End BaseAddUMagmaPred. End BaseAddUMagmaPred. Section ZmodPred. Variables (V : zmodType). Section Opp. Variable S : opprClosed V. Lemma rpredNr : {in S, forall u, - u \in S}. Proof. exact: oppr_closed_subproof. Qed. Lemma rpredN : {mono -%R: u / u \in S}. Proof. exact: (gpredV (to_pmultiplicative S)). Qed. End Opp. Section Zmod. Variables S : zmodClosed V. Let T := to_pmultiplicative S. Lemma rpredB : {in S &, forall u v, u - v \in S}. Proof. exact: (@gpredF _ T). Qed. Lemma rpredBC u v : u - v \in S = (v - u \in S). Proof. exact: (@gpredFC _ T). Qed. Lemma rpredMNn n: {in S, forall u, u *- n \in S}. Proof. exact: (@gpredXNn _ T). Qed. Lemma rpredDr x y : x \in S -> (y + x \in S) = (y \in S). Proof. exact: (@gpredMr _ T). Qed. Lemma rpredDl x y : x \in S -> (x + y \in S) = (y \in S). Proof. exact: (@gpredMl _ T). Qed. Lemma rpredBr x y : x \in S -> (y - x \in S) = (y \in S). Proof. exact: (@gpredFr _ T). Qed. Lemma rpredBl x y : x \in S -> (x - y \in S) = (y \in S). Proof. exact: (@gpredFl _ T). Qed. Lemma zmodClosedP : zmod_closed S. Proof. split; [ exact: (@rpred0D V S).1 | exact: rpredB ]. Qed. End Zmod. End ZmodPred. HB.mixin Record isSubBaseAddUMagma (V : baseAddUMagmaType) (S : pred V) U of SubType V S U & BaseAddUMagma U := { valD0_subproof : nmod_morphism (val : U -> V) }. #[short(type="subBaseAddUMagma")] HB.structure Definition SubBaseAddUMagma (V : baseAddUMagmaType) S := { U of SubChoice V S U & BaseAddUMagma U & isSubBaseAddUMagma V S U }. #[short(type="subAddUMagma")] HB.structure Definition SubAddUMagma (V : addUMagmaType) S := { U of SubChoice V S U & AddUMagma U & isSubBaseAddUMagma V S U }. #[short(type="subNmodType")] HB.structure Definition SubNmodule (V : nmodType) S := { U of SubChoice V S U & Nmodule U & isSubBaseAddUMagma V S U}. Section subBaseAddUMagma. Context (V : baseAddUMagmaType) (S : pred V) (U : subBaseAddUMagma S). Notation val := (val : U -> V). #[export] HB.instance Definition _ := isNmodMorphism.Build U V val valD0_subproof. Lemma valD : {morph val : x y / x + y}. Proof. exact: raddfD. Qed. Lemma val0 : val 0 = 0. Proof. exact: raddf0. Qed. End subBaseAddUMagma. HB.factory Record SubChoice_isSubAddUMagma (V : addUMagmaType) S U of SubChoice V S U := { addumagma_closed_subproof : addumagma_closed S }. HB.builders Context V S U of SubChoice_isSubAddUMagma V S U. HB.instance Definition _ := isAddClosed.Build V S addumagma_closed_subproof. Let inU v Sv : U := Sub v Sv. Let addU (u1 u2 : U) := inU (rpredD (valP u1) (valP u2)). Let oneU := inU (fst addumagma_closed_subproof). Lemma addrC : commutative addU. Proof. by move=> x y; apply/val_inj; rewrite !SubK addrC. Qed. Lemma add0r : left_id oneU addU. Proof. by move=> x; apply/val_inj; rewrite !SubK add0r. Qed. HB.instance Definition _ := isAddUMagma.Build U addrC add0r. Lemma valD0 : nmod_morphism (val : U -> V). Proof. by split=> [|x y]; rewrite !SubK. Qed. HB.instance Definition _ := isSubBaseAddUMagma.Build V S U valD0. HB.end. HB.factory Record SubChoice_isSubNmodule (V : nmodType) S U of SubChoice V S U := { nmod_closed_subproof : nmod_closed S }. HB.builders Context V S U of SubChoice_isSubNmodule V S U. HB.instance Definition _ := SubChoice_isSubAddUMagma.Build V S U nmod_closed_subproof. Lemma addrA : associative (@add U). Proof. by move=> x y z; apply/val_inj; rewrite !SubK addrA. Qed. HB.instance Definition _ := AddMagma_isAddSemigroup.Build U addrA. HB.end. #[short(type="subZmodType")] HB.structure Definition SubZmodule (V : zmodType) S := { U of SubChoice V S U & Zmodule U & isSubBaseAddUMagma V S U}. Section zmod_morphism. Context (V : zmodType) (S : pred V) (U : SubZmodule.type S). Notation val := (val : U -> V). Lemma valB : {morph val : x y / x - y}. Proof. exact: raddfB. Qed. Lemma valN : {morph val : x / - x}. Proof. exact: raddfN. Qed. End zmod_morphism. HB.factory Record isSubZmodule (V : zmodType) S U of SubChoice V S U & Zmodule U := { valB_subproof : zmod_morphism (val : U -> V) }. HB.builders Context V S U of isSubZmodule V S U. Fact valD0 : nmod_morphism (val : U -> V). Proof. have val0: (val : U -> V) 0 = 0. by rewrite -[X in val X](subr0 0) valB_subproof subrr. split=> // x y; apply/(@subIr _ (val y)). by rewrite -valB_subproof -!addrA !subrr !addr0. Qed. HB.instance Definition _ := isSubBaseAddUMagma.Build V S U valD0. HB.end. HB.factory Record SubChoice_isSubZmodule (V : zmodType) S U of SubChoice V S U := { zmod_closed_subproof : zmod_closed S }. HB.builders Context V S U of SubChoice_isSubZmodule V S U. HB.instance Definition _ := isZmodClosed.Build V S zmod_closed_subproof. HB.instance Definition _ := SubChoice_isSubNmodule.Build V S U nmod_closed_subproof. Let inU v Sv : U := Sub v Sv. Let oppU (u : U) := inU (rpredNr (valP u)). HB.instance Definition _ := hasOpp.Build U oppU. Lemma addNr : left_inverse 0 oppU (@add U). Proof. by move=> x; apply/val_inj; rewrite !SubK addNr. Qed. HB.instance Definition _ := Nmodule_isZmodule.Build U addNr. HB.end. Module SubExports. Notation "[ 'SubChoice_isSubNmodule' 'of' U 'by' <: ]" := (SubChoice_isSubNmodule.Build _ _ U rpred0D) (at level 0, format "[ 'SubChoice_isSubNmodule' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubChoice_isSubZmodule' 'of' U 'by' <: ]" := (SubChoice_isSubZmodule.Build _ _ U (zmodClosedP _)) (at level 0, format "[ 'SubChoice_isSubZmodule' 'of' U 'by' <: ]") : form_scope. End SubExports. HB.export SubExports. Module AllExports. HB.reexport. End AllExports. End Algebra. Export AllExports. Notation "0" := (@zero _) : ring_scope. Notation "-%R" := (@opp _) : ring_scope. Notation "- x" := (opp x) : ring_scope. Notation "+%R" := (@add _) : function_scope. Notation "x + y" := (add x y) : ring_scope. Notation "x - y" := (add x (- y)) : ring_scope. Arguments natmul : simpl never. Notation "x *+ n" := (natmul x n) : ring_scope. Notation "x *- n" := (opp (x *+ n)) : ring_scope. Notation "s `_ i" := (seq.nth 0%R s%R i) : ring_scope. Notation support := 0.-support. Notation "1" := (@one _) : ring_scope. Notation "- 1" := (opp 1) : ring_scope. Notation "n %:R" := (natmul 1 n) : ring_scope. Notation "\sum_ ( i <- r | P ) F" := (\big[+%R/0%R]_(i <- r | P%B) F%R) : ring_scope. Notation "\sum_ ( i <- r ) F" := (\big[+%R/0%R]_(i <- r) F%R) : ring_scope. Notation "\sum_ ( m <= i < n | P ) F" := (\big[+%R/0%R]_(m <= i < n | P%B) F%R) : ring_scope. Notation "\sum_ ( m <= i < n ) F" := (\big[+%R/0%R]_(m <= i < n) F%R) : ring_scope. Notation "\sum_ ( i | P ) F" := (\big[+%R/0%R]_(i | P%B) F%R) : ring_scope. Notation "\sum_ i F" := (\big[+%R/0%R]_i F%R) : ring_scope. Notation "\sum_ ( i : t | P ) F" := (\big[+%R/0%R]_(i : t | P%B) F%R) (only parsing) : ring_scope. Notation "\sum_ ( i : t ) F" := (\big[+%R/0%R]_(i : t) F%R) (only parsing) : ring_scope. Notation "\sum_ ( i < n | P ) F" := (\big[+%R/0%R]_(i < n | P%B) F%R) : ring_scope. Notation "\sum_ ( i < n ) F" := (\big[+%R/0%R]_(i < n) F%R) : ring_scope. Notation "\sum_ ( i 'in' A | P ) F" := (\big[+%R/0%R]_(i in A | P%B) F%R) : ring_scope. Notation "\sum_ ( i 'in' A ) F" := (\big[+%R/0%R]_(i in A) F%R) : ring_scope. Section FinFunBaseAddMagma. Variable (aT : finType) (rT : baseAddMagmaType). Implicit Types f g : {ffun aT -> rT}. Definition ffun_add f g := [ffun a => f a + g a]. HB.instance Definition _ := hasAdd.Build {ffun aT -> rT} ffun_add. End FinFunBaseAddMagma. Section FinFunAddMagma. Variable (aT : finType) (rT : addMagmaType). Implicit Types f g : {ffun aT -> rT}. Fact ffun_addrC : commutative (@ffun_add aT rT). Proof. by move=> f1 f2; apply/ffunP => a; rewrite !ffunE addrC. Qed. HB.instance Definition _ := BaseAddMagma_isAddMagma.Build {ffun aT -> rT} ffun_addrC. End FinFunAddMagma. Section FinFunAddSemigroup. Variable (aT : finType) (rT : addSemigroupType). Implicit Types f g : {ffun aT -> rT}. Fact ffun_addrA : associative (@ffun_add aT rT). Proof. by move=> f g h; apply/ffunP => a; rewrite !ffunE addrA. Qed. HB.instance Definition _ := AddMagma_isAddSemigroup.Build {ffun aT -> rT} ffun_addrA. End FinFunAddSemigroup. Section FinFunBaseAddUMagma. Variable (aT : finType) (rT : baseAddUMagmaType). Implicit Types f g : {ffun aT -> rT}. Definition ffun_zero := [ffun a : aT => (0 : rT)]. HB.instance Definition _ := hasZero.Build {ffun aT -> rT} ffun_zero. End FinFunBaseAddUMagma. Section FinFunAddUMagma. Variable (aT : finType) (rT : addUMagmaType). Implicit Types f g : {ffun aT -> rT}. Fact ffun_add0r : left_id (@ffun_zero aT rT) (@ffun_add aT rT). Proof. by move=> f; apply/ffunP => a; rewrite !ffunE add0r. Qed. HB.instance Definition _ := BaseAddUMagma_isAddUMagma.Build {ffun aT -> rT} ffun_add0r. End FinFunAddUMagma. (* FIXME: HB.saturate *) HB.instance Definition _ (aT : finType) (rT : ChoiceBaseAddMagma.type) := BaseAddMagma.on {ffun aT -> rT}. HB.instance Definition _ (aT : finType) (rT : ChoiceBaseAddUMagma.type) := BaseAddMagma.on {ffun aT -> rT}. Section FinFunNmod. Variable (aT : finType) (rT : nmodType). Implicit Types f g : {ffun aT -> rT}. (* FIXME: HB.saturate *) HB.instance Definition _ := AddSemigroup.on {ffun aT -> rT}. Lemma ffunMnE f n x : (f *+ n) x = f x *+ n. Proof. elim: n => [|n IHn]; first by rewrite ffunE. by rewrite !mulrS ffunE IHn. Qed. Section Sum. Variables (I : Type) (r : seq I) (P : pred I) (F : I -> {ffun aT -> rT}). Lemma sum_ffunE x : (\sum_(i <- r | P i) F i) x = \sum_(i <- r | P i) F i x. Proof. by elim/big_rec2: _ => // [|i _ y _ <-]; rewrite !ffunE. Qed. Lemma sum_ffun : \sum_(i <- r | P i) F i = [ffun x => \sum_(i <- r | P i) F i x]. Proof. by apply/ffunP=> i; rewrite sum_ffunE ffunE. Qed. End Sum. End FinFunNmod. Section FinFunZmod. Variable (aT : finType) (rT : zmodType). Implicit Types f g : {ffun aT -> rT}. Definition ffun_opp f := [ffun a => - f a]. HB.instance Definition _ := hasOpp.Build {ffun aT -> rT} ffun_opp. Fact ffun_addNr : left_inverse 0 ffun_opp +%R. Proof. by move=> f; apply/ffunP => a; rewrite !ffunE addNr. Qed. HB.instance Definition _ := Nmodule_isZmodule.Build {ffun aT -> rT} ffun_addNr. End FinFunZmod. Section PairBaseAddMagma. Variables U V : baseAddMagmaType. Definition add_pair (a b : U * V) := (a.1 + b.1, a.2 + b.2). HB.instance Definition _ := hasAdd.Build (U * V)%type add_pair. End PairBaseAddMagma. Section PairAddMagma. Variables U V : addMagmaType. Fact pair_addrC : commutative (@add_pair U V). Proof. by move=> a b; congr pair; exact: addrC. Qed. HB.instance Definition _ := BaseAddMagma_isAddMagma.Build (U * V)%type pair_addrC. End PairAddMagma. Section PairAddSemigroup. Variables U V : addSemigroupType. Fact pair_addrA : associative (@add_pair U V). Proof. by move=> [] al ar [] bl br [] cl cr; rewrite /add_pair !addrA. Qed. HB.instance Definition _ := AddMagma_isAddSemigroup.Build (U * V)%type pair_addrA. End PairAddSemigroup. Section PairBaseAddUMagma. Variables U V : baseAddUMagmaType. Definition pair_zero : U * V := (0, 0). HB.instance Definition _ := hasZero.Build (U * V)%type pair_zero. Fact fst_is_zmod_morphism : nmod_morphism (@fst U V). Proof. by []. Qed. Fact snd_is_zmod_morphism : nmod_morphism (@snd U V). Proof. by []. Qed. HB.instance Definition _ := isNmodMorphism.Build _ _ (@fst U V) fst_is_zmod_morphism. HB.instance Definition _ := isNmodMorphism.Build _ _ (@snd U V) snd_is_zmod_morphism. End PairBaseAddUMagma. Section PairAddUMagma. Variables U V : addUMagmaType. Fact pair_add0r : left_id (@pair_zero U V) (@add_pair U V). Proof. by move=> [] al ar; rewrite /add_pair !add0r. Qed. HB.instance Definition _ := BaseAddUMagma_isAddUMagma.Build (U * V)%type pair_add0r. End PairAddUMagma. (* FIXME: HB.saturate *) HB.instance Definition _ (U V : ChoiceBaseAddMagma.type) := BaseAddMagma.on (U * V)%type. HB.instance Definition _ (U V : ChoiceBaseAddUMagma.type) := BaseAddMagma.on (U * V)%type. HB.instance Definition _ (U V : nmodType) := AddSemigroup.on (U * V)%type. (* /FIXME *) Section PairZmodule. Variables U V : zmodType. Definition pair_opp (a : U * V) := (- a.1, - a.2). HB.instance Definition _ := hasOpp.Build (U * V)%type pair_opp. Fact pair_addNr : left_inverse 0 pair_opp +%R. Proof. by move=> [] al ar; rewrite /pair_opp; congr pair; apply/addNr. Qed. HB.instance Definition _ := Nmodule_isZmodule.Build (U * V)%type pair_addNr. End PairZmodule. (* zmodType structure on bool *) HB.instance Definition _ := isZmodule.Build bool addbA addbC addFb addbb. (* nmodType structure on nat *) HB.instance Definition _ := isNmodule.Build nat addnA addnC add0n. HB.instance Definition _ (V : nmodType) (x : V) := isNmodMorphism.Build nat V (natmul x) (mulr0n x, mulrnDr x). Lemma natr0E : 0 = 0%N. Proof. by []. Qed. Lemma natrDE n m : n + m = (n + m)%N. Proof. by []. Qed. Definition natrE := (natr0E, natrDE).
PosDef.lean
import Mathlib.LinearAlgebra.Matrix.PosDef open Matrix open scoped ComplexOrder variable {n 𝕜 : Type*} [Fintype n] [RCLike 𝕜] [DecidableEq n] {A : Matrix n n 𝕜} (hA : PosSemidef A) -- test for custom elaborator /-- info: (⋯ : A.PosSemidef).sqrt : Matrix n n 𝕜 -/ #guard_msgs in #check (id hA).sqrt
HaveI.lean
/- Copyright (c) 2023 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import Mathlib.Init /-! # Variants of `haveI`/`letI` for use in do-notation. This files implements the `haveI'` and `letI'` macros which have the same semantics as `haveI` and `letI`, but are `doElem`s and can be used inside do-notation. They need an apostrophe after their name for disambiguation with the term variants. This is necessary because the do-notation has a hardcoded list of keywords which can appear both as term-mode and do-elem syntax (like for example `let` or `have`). -/ namespace Mathlib.Tactic.HaveI local syntax "haveIDummy" letDecl : term macro_rules | `(assert! haveIDummy $hd:letDecl; $body) => `(haveI $hd:letDecl; $body) /-- `haveI'` behaves like `have`, but inlines the value instead of producing a `have` term. (This is the do-notation version of the term-mode `haveI`.) -/ macro "haveI' " hd:letDecl : doElem => `(doElem| assert! haveIDummy $hd:letDecl) local syntax "letIDummy" letDecl : term macro_rules | `(assert! letIDummy $hd:letDecl; $body) => `(letI $hd:letDecl; $body) /-- `letI` behaves like `let`, but inlines the value instead of producing a `let` term. (This is the do-notation version of the term-mode `haveI`.) -/ macro "letI' " hd:letDecl : doElem => `(doElem| assert! letIDummy $hd:letDecl) end Mathlib.Tactic.HaveI
seq.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat. (******************************************************************************) (* The seq type is the ssreflect type for sequences; it is an alias for the *) (* standard Coq list type. The ssreflect library equips it with many *) (* operations, as well as eqType and predType (and, later, choiceType) *) (* structures. The operations are geared towards reflection: they generally *) (* expect and provide boolean predicates, e.g., the membership predicate *) (* expects an eqType. To avoid any confusion we do not Import the Coq List *) (* module. *) (* As there is no true subtyping in Coq, we don't use a type for non-empty *) (* sequences; rather, we pass explicitly the head and tail of the sequence. *) (* The empty sequence is especially bothersome for subscripting, since it *) (* forces us to pass a default value. This default value can often be hidden *) (* by a notation. *) (* Here is the list of seq operations: *) (* ** Constructors: *) (* seq T == the type of sequences of items of type T. *) (* bitseq == seq bool. *) (* [::], nil, Nil T == the empty sequence (of type T). *) (* x :: s, cons x s, Cons T x s == the sequence x followed by s (of type T). *) (* [:: x] == the singleton sequence. *) (* [:: x_0; ...; x_n] == the explicit sequence of the x_i. *) (* [:: x_0, ..., x_n & s] == the sequence of the x_i, followed by s. *) (* rcons s x == the sequence s, followed by x. *) (* All of the above, except rcons, can be used in patterns. We define a view *) (* lastP and an induction principle last_ind that can be used to decompose *) (* or traverse a sequence in a right to left order. The view lemma lastP has *) (* a dependent family type, so the ssreflect tactic case/lastP: p => [|p' x] *) (* will generate two subgoals in which p has been replaced by [::] and by *) (* rcons p' x, respectively. *) (* ** Factories: *) (* nseq n x == a sequence of n x's. *) (* ncons n x s == a sequence of n x's, followed by s. *) (* seqn n x_0 ... x_n-1 == the sequence of the x_i; can be partially applied. *) (* iota m n == the sequence m, m + 1, ..., m + n - 1. *) (* mkseq f n == the sequence f 0, f 1, ..., f (n - 1). *) (* ** Sequential access: *) (* head x0 s == the head (zero'th item) of s if s is non-empty, else x0. *) (* ohead s == None if s is empty, else Some x when the head of s is x. *) (* behead s == s minus its head, i.e., s' if s = x :: s', else [::]. *) (* last x s == the last element of x :: s (which is non-empty). *) (* belast x s == x :: s minus its last item. *) (* ** Dimensions: *) (* size s == the number of items (length) in s. *) (* shape ss == the sequence of sizes of the items of the sequence of *) (* sequences ss. *) (* ** Random access: *) (* nth x0 s i == the item i of s (numbered from 0), or x0 if s does *) (* not have at least i+1 items (i.e., size x <= i) *) (* s`_i == standard notation for nth x0 s i for a default x0, *) (* e.g., 0 for rings. *) (* onth s i == Some x if x is the i^th idem of s (numbered from 0), *) (* or None if size s <= i) *) (* set_nth x0 s i y == s where item i has been changed to y; if s does not *) (* have an item i, it is first padded with copies of x0 *) (* to size i+1. *) (* incr_nth s i == the nat sequence s with item i incremented (s is *) (* first padded with 0's to size i+1, if needed). *) (* ** Predicates: *) (* nilp s <=> s is [::]. *) (* := (size s == 0). *) (* x \in s == x appears in s (this requires an eqType for T). *) (* index x s == the first index at which x appears in s, or size s if *) (* x \notin s. *) (* has a s <=> a holds for some item in s, where a is an applicative *) (* bool predicate. *) (* all a s <=> a holds for all items in s. *) (* 'has_aP <-> the view reflect (exists2 x, x \in s & A x) (has a s), *) (* where aP x : reflect (A x) (a x). *) (* 'all_aP <=> the view for reflect {in s, forall x, A x} (all a s). *) (* all2 r s t <=> the (bool) relation r holds for all _respective_ items *) (* in s and t, which must also have the same size, i.e., *) (* for s := [:: x1; ...; x_m] and t := [:: y1; ...; y_n], *) (* the condition [&& r x_1 y_1, ..., r x_n y_n & m == n]. *) (* find p s == the index of the first item in s for which p holds, *) (* or size s if no such item is found. *) (* count p s == the number of items of s for which p holds. *) (* count_mem x s == the multiplicity of x in s, i.e., count (pred1 x) s. *) (* tally s == a tally of s, i.e., a sequence of (item, multiplicity) *) (* pairs for all items in sequence s (without duplicates). *) (* incr_tally bs x == increment the multiplicity of x in the tally bs, or add *) (* x with multiplicity 1 at then end if x is not in bs. *) (* bs \is a wf_tally <=> bs is well-formed tally, with no duplicate items or *) (* null multiplicities. *) (* tally_seq bs == the expansion of a tally bs into a sequence where each *) (* (x, n) pair expands into a sequence of n x's. *) (* constant s <=> all items in s are identical (trivial if s = [::]). *) (* uniq s <=> all the items in s are pairwise different. *) (* subseq s1 s2 <=> s1 is a subsequence of s2, i.e., s1 = mask m s2 for *) (* some m : bitseq (see below). *) (* infix s1 s2 <=> s1 is a contiguous subsequence of s2, i.e., *) (* s ++ s1 ++ s' = s2 for some sequences s, s'. *) (* prefix s1 s2 <=> s1 is a subchain of s2 appearing at the beginning *) (* of s2. *) (* suffix s1 s2 <=> s1 is a subchain of s2 appearing at the end of s2. *) (* infix_index s1 s2 <=> the first index at which s1 appears in s2, *) (* or (size s2).+1 if infix s1 s2 is false. *) (* perm_eq s1 s2 <=> s2 is a permutation of s1, i.e., s1 and s2 have the *) (* items (with the same repetitions), but possibly in a *) (* different order. *) (* perm_eql s1 s2 <-> s1 and s2 behave identically on the left of perm_eq. *) (* perm_eqr s1 s2 <-> s1 and s2 behave identically on the right of perm_eq. *) (* --> These left/right transitive versions of perm_eq make it easier to *) (* chain a sequence of equivalences. *) (* permutations s == a duplicate-free list of all permutations of s. *) (* ** Filtering: *) (* filter p s == the subsequence of s consisting of all the items *) (* for which the (boolean) predicate p holds. *) (* rem x s == the subsequence of s, where the first occurrence *) (* of x has been removed (compare filter (predC1 x) s *) (* where ALL occurrences of x are removed). *) (* undup s == the subsequence of s containing only the first *) (* occurrence of each item in s, i.e., s with all *) (* duplicates removed. *) (* mask m s == the subsequence of s selected by m : bitseq, with *) (* item i of s selected by bit i in m (extra items or *) (* bits are ignored. *) (* ** Surgery: *) (* s1 ++ s2, cat s1 s2 == the concatenation of s1 and s2. *) (* take n s == the sequence containing only the first n items of s *) (* (or all of s if size s <= n). *) (* drop n s == s minus its first n items ([::] if size s <= n) *) (* rot n s == s rotated left n times (or s if size s <= n). *) (* := drop n s ++ take n s *) (* rotr n s == s rotated right n times (or s if size s <= n). *) (* rev s == the (linear time) reversal of s. *) (* catrev s1 s2 == the reversal of s1 followed by s2 (this is the *) (* recursive form of rev). *) (* ** Dependent iterator: for s : seq S and t : S -> seq T *) (* [seq E | x <- s, y <- t] := flatten [seq [seq E | x <- t] | y <- s] *) (* == the sequence of all the f x y, with x and y drawn from *) (* s and t, respectively, in row-major order, *) (* and where t is possibly dependent in elements of s *) (* allpairs_dep f s t := self expanding definition for *) (* [seq f x y | x <- s, y <- t y] *) (* ** Iterators: for s == [:: x_1, ..., x_n], t == [:: y_1, ..., y_m], *) (* allpairs f s t := same as allpairs_dep but where t is non dependent, *) (* i.e. self expanding definition for *) (* [seq f x y | x <- s, y <- t] *) (* := [:: f x_1 y_1; ...; f x_1 y_m; f x_2 y_1; ...; f x_n y_m] *) (* allrel r xs ys := all [pred x | all (r x) ys] xs *) (* <=> r x y holds whenever x is in xs and y is in ys *) (* all2rel r xs := allrel r xs xs *) (* <=> the proposition r x y holds for all possible x, y in xs.*) (* pairwise r xs <=> the relation r holds for any i-th and j-th element of *) (* xs such that i < j. *) (* map f s == the sequence [:: f x_1, ..., f x_n]. *) (* pmap pf s == the sequence [:: y_i1, ..., y_ik] where i1 < ... < ik, *) (* pf x_i = Some y_i, and pf x_j = None iff j is not in *) (* {i1, ..., ik}. *) (* foldr f a s == the right fold of s by f (i.e., the natural iterator). *) (* := f x_1 (f x_2 ... (f x_n a)) *) (* sumn s == x_1 + (x_2 + ... + (x_n + 0)) (when s : seq nat). *) (* foldl f a s == the left fold of s by f. *) (* := f (f ... (f a x_1) ... x_n-1) x_n *) (* scanl f a s == the sequence of partial accumulators of foldl f a s. *) (* := [:: f a x_1; ...; foldl f a s] *) (* pairmap f a s == the sequence of f applied to consecutive items in a :: s. *) (* := [:: f a x_1; f x_1 x_2; ...; f x_n-1 x_n] *) (* zip s t == itemwise pairing of s and t (dropping any extra items). *) (* := [:: (x_1, y_1); ...; (x_mn, y_mn)] with mn = minn n m. *) (* unzip1 s == [:: (x_1).1; ...; (x_n).1] when s : seq (S * T). *) (* unzip2 s == [:: (x_1).2; ...; (x_n).2] when s : seq (S * T). *) (* flatten s == x_1 ++ ... ++ x_n ++ [::] when s : seq (seq T). *) (* reshape r s == s reshaped into a sequence of sequences whose sizes are *) (* given by r (truncating if s is too long or too short). *) (* := [:: [:: x_1; ...; x_r1]; *) (* [:: x_(r1 + 1); ...; x_(r0 + r1)]; *) (* ...; *) (* [:: x_(r1 + ... + r(k-1) + 1); ...; x_(r0 + ... rk)]] *) (* flatten_index sh r c == the index, in flatten ss, of the item of indexes *) (* (r, c) in any sequence of sequences ss of shape sh *) (* := sh_1 + sh_2 + ... + sh_r + c *) (* reshape_index sh i == the index, in reshape sh s, of the sequence *) (* containing the i-th item of s. *) (* reshape_offset sh i == the offset, in the (reshape_index sh i)-th *) (* sequence of reshape sh s of the i-th item of s *) (* ** Notation for manifest comprehensions: *) (* [seq x <- s | C] := filter (fun x => C) s. *) (* [seq E | x <- s] := map (fun x => E) s. *) (* [seq x <- s | C1 & C2] := [seq x <- s | C1 && C2]. *) (* [seq E | x <- s & C] := [seq E | x <- [seq x | C]]. *) (* --> The above allow optional type casts on the eigenvariables, as in *) (* [seq x : T <- s | C] or [seq E | x : T <- s, y : U <- t]. The cast may be *) (* needed as type inference considers E or C before s. *) (* We are quite systematic in providing lemmas to rewrite any composition *) (* of two operations. "rev", whose simplifications are not natural, is *) (* protected with simpl never. *) (* ** The following are equivalent: *) (* [<-> P0; P1; ..; Pn] <-> P0, P1, ..., Pn are all equivalent. *) (* := P0 -> P1 -> ... -> Pn -> P0 *) (* if T : [<-> P0; P1; ..; Pn] is such an equivalence, and i, j are in nat *) (* then T i j is a proof of the equivalence Pi <-> Pj between Pi and Pj; *) (* when i (resp. j) is out of bounds, Pi (resp. Pj) defaults to P0. *) (* The tactic tfae splits the goal into n+1 implications to prove. *) (* An example of use can be found in fingraph theorem orbitPcycle. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope seq_scope. Reserved Notation "[ '<->' P0 ; P1 ; .. ; Pn ]" (format "[ '<->' '[' P0 ; '/' P1 ; '/' .. ; '/' Pn ']' ]"). Delimit Scope seq_scope with SEQ. Open Scope seq_scope. (* Inductive seq (T : Type) : Type := Nil | Cons of T & seq T. *) Notation seq := list. Bind Scope seq_scope with list. Arguments cons {T%_type} x s%_SEQ : rename. Arguments nil {T%_type} : rename. Notation Cons T := (@cons T) (only parsing). Notation Nil T := (@nil T) (only parsing). (* As :: and ++ are (improperly) declared in Init.datatypes, we only rebind *) (* them here. *) Infix "::" := cons : seq_scope. Notation "[ :: ]" := nil (format "[ :: ]") : seq_scope. Notation "[ :: x1 ]" := (x1 :: [::]) (format "[ :: x1 ]") : seq_scope. Notation "[ :: x & s ]" := (x :: s) (only parsing) : seq_scope. Notation "[ :: x1 , x2 , .. , xn & s ]" := (x1 :: x2 :: .. (xn :: s) ..) (format "'[hv' [ :: '[' x1 , '/' x2 , '/' .. , '/' xn ']' '/ ' & s ] ']'" ) : seq_scope. Notation "[ :: x1 ; x2 ; .. ; xn ]" := (x1 :: x2 :: .. [:: xn] ..) (format "[ :: '[' x1 ; '/' x2 ; '/' .. ; '/' xn ']' ]" ) : seq_scope. Section Sequences. Variable n0 : nat. (* numerical parameter for take, drop et al *) Variable T : Type. (* must come before the implicit Type *) Variable x0 : T. (* default for head/nth *) Implicit Types x y z : T. Implicit Types m n : nat. Implicit Type s : seq T. Fixpoint size s := if s is _ :: s' then (size s').+1 else 0. Lemma size0nil s : size s = 0 -> s = [::]. Proof. by case: s. Qed. Definition nilp s := size s == 0. Lemma nilP s : reflect (s = [::]) (nilp s). Proof. by case: s => [|x s]; constructor. Qed. Definition ohead s := if s is x :: _ then Some x else None. Definition head s := if s is x :: _ then x else x0. Definition behead s := if s is _ :: s' then s' else [::]. Lemma size_behead s : size (behead s) = (size s).-1. Proof. by case: s. Qed. (* Factories *) Definition ncons n x := iter n (cons x). Definition nseq n x := ncons n x [::]. Lemma size_ncons n x s : size (ncons n x s) = n + size s. Proof. by elim: n => //= n ->. Qed. Lemma size_nseq n x : size (nseq n x) = n. Proof. by rewrite size_ncons addn0. Qed. (* n-ary, dependently typed constructor. *) Fixpoint seqn_type n := if n is n'.+1 then T -> seqn_type n' else seq T. Fixpoint seqn_rec f n : seqn_type n := if n is n'.+1 return seqn_type n then fun x => seqn_rec (fun s => f (x :: s)) n' else f [::]. Definition seqn := seqn_rec id. (* Sequence catenation "cat". *) Fixpoint cat s1 s2 := if s1 is x :: s1' then x :: s1' ++ s2 else s2 where "s1 ++ s2" := (cat s1 s2) : seq_scope. Lemma cat0s s : [::] ++ s = s. Proof. by []. Qed. Lemma cat1s x s : [:: x] ++ s = x :: s. Proof. by []. Qed. Lemma cat_cons x s1 s2 : (x :: s1) ++ s2 = x :: s1 ++ s2. Proof. by []. Qed. Lemma cat_nseq n x s : nseq n x ++ s = ncons n x s. Proof. by elim: n => //= n ->. Qed. Lemma nseqD n1 n2 x : nseq (n1 + n2) x = nseq n1 x ++ nseq n2 x. Proof. by rewrite cat_nseq /nseq /ncons iterD. Qed. Lemma cats0 s : s ++ [::] = s. Proof. by elim: s => //= x s ->. Qed. Lemma catA s1 s2 s3 : s1 ++ s2 ++ s3 = (s1 ++ s2) ++ s3. Proof. by elim: s1 => //= x s1 ->. Qed. Lemma size_cat s1 s2 : size (s1 ++ s2) = size s1 + size s2. Proof. by elim: s1 => //= x s1 ->. Qed. Lemma cat_nilp s1 s2 : nilp (s1 ++ s2) = nilp s1 && nilp s2. Proof. by case: s1. Qed. (* last, belast, rcons, and last induction. *) Fixpoint rcons s z := if s is x :: s' then x :: rcons s' z else [:: z]. Lemma rcons_cons x s z : rcons (x :: s) z = x :: rcons s z. Proof. by []. Qed. Lemma cats1 s z : s ++ [:: z] = rcons s z. Proof. by elim: s => //= x s ->. Qed. Fixpoint last x s := if s is x' :: s' then last x' s' else x. Fixpoint belast x s := if s is x' :: s' then x :: (belast x' s') else [::]. Lemma lastI x s : x :: s = rcons (belast x s) (last x s). Proof. by elim: s x => [|y s IHs] x //=; rewrite IHs. Qed. Lemma last_cons x y s : last x (y :: s) = last y s. Proof. by []. Qed. Lemma size_rcons s x : size (rcons s x) = (size s).+1. Proof. by rewrite -cats1 size_cat addnC. Qed. Lemma size_belast x s : size (belast x s) = size s. Proof. by elim: s x => [|y s IHs] x //=; rewrite IHs. Qed. Lemma last_cat x s1 s2 : last x (s1 ++ s2) = last (last x s1) s2. Proof. by elim: s1 x => [|y s1 IHs] x //=; rewrite IHs. Qed. Lemma last_rcons x s z : last x (rcons s z) = z. Proof. by rewrite -cats1 last_cat. Qed. Lemma belast_cat x s1 s2 : belast x (s1 ++ s2) = belast x s1 ++ belast (last x s1) s2. Proof. by elim: s1 x => [|y s1 IHs] x //=; rewrite IHs. Qed. Lemma belast_rcons x s z : belast x (rcons s z) = x :: s. Proof. by rewrite lastI -!cats1 belast_cat. Qed. Lemma cat_rcons x s1 s2 : rcons s1 x ++ s2 = s1 ++ x :: s2. Proof. by rewrite -cats1 -catA. Qed. Lemma rcons_cat x s1 s2 : rcons (s1 ++ s2) x = s1 ++ rcons s2 x. Proof. by rewrite -!cats1 catA. Qed. Variant last_spec : seq T -> Type := | LastNil : last_spec [::] | LastRcons s x : last_spec (rcons s x). Lemma lastP s : last_spec s. Proof. case: s => [|x s]; [left | rewrite lastI; right]. Qed. Lemma last_ind P : P [::] -> (forall s x, P s -> P (rcons s x)) -> forall s, P s. Proof. move=> Hnil Hlast s; rewrite -(cat0s s). elim: s [::] Hnil => [|x s2 IHs] s1 Hs1; first by rewrite cats0. by rewrite -cat_rcons; apply/IHs/Hlast. Qed. (* Sequence indexing. *) Fixpoint nth s n {struct n} := if s is x :: s' then if n is n'.+1 then @nth s' n' else x else x0. Fixpoint set_nth s n y {struct n} := if s is x :: s' then if n is n'.+1 then x :: @set_nth s' n' y else y :: s' else ncons n x0 [:: y]. Lemma nth0 s : nth s 0 = head s. Proof. by []. Qed. Lemma nth_default s n : size s <= n -> nth s n = x0. Proof. by elim: s n => [|x s IHs] []. Qed. Lemma if_nth s b n : b || (size s <= n) -> (if b then nth s n else x0) = nth s n. Proof. by case: leqP; case: ifP => //= *; rewrite nth_default. Qed. Lemma nth_nil n : nth [::] n = x0. Proof. by case: n. Qed. Lemma nth_seq1 n x : nth [:: x] n = if n == 0 then x else x0. Proof. by case: n => [|[]]. Qed. Lemma last_nth x s : last x s = nth (x :: s) (size s). Proof. by elim: s x => [|y s IHs] x /=. Qed. Lemma nth_last s : nth s (size s).-1 = last x0 s. Proof. by case: s => //= x s; rewrite last_nth. Qed. Lemma nth_behead s n : nth (behead s) n = nth s n.+1. Proof. by case: s n => [|x s] [|n]. Qed. Lemma nth_cat s1 s2 n : nth (s1 ++ s2) n = if n < size s1 then nth s1 n else nth s2 (n - size s1). Proof. by elim: s1 n => [|x s1 IHs] []. Qed. Lemma nth_rcons s x n : nth (rcons s x) n = if n < size s then nth s n else if n == size s then x else x0. Proof. by elim: s n => [|y s IHs] [] //=; apply: nth_nil. Qed. Lemma nth_rcons_default s i : nth (rcons s x0) i = nth s i. Proof. by rewrite nth_rcons; case: ltngtP => //[/ltnW ?|->]; rewrite nth_default. Qed. Lemma nth_ncons m x s n : nth (ncons m x s) n = if n < m then x else nth s (n - m). Proof. by elim: m n => [|m IHm] []. Qed. Lemma nth_nseq m x n : nth (nseq m x) n = (if n < m then x else x0). Proof. by elim: m n => [|m IHm] []. Qed. Lemma eq_from_nth s1 s2 : size s1 = size s2 -> (forall i, i < size s1 -> nth s1 i = nth s2 i) -> s1 = s2. Proof. elim: s1 s2 => [|x1 s1 IHs1] [|x2 s2] //= [eq_sz] eq_s12. by rewrite [x1](eq_s12 0) // (IHs1 s2) // => i; apply: (eq_s12 i.+1). Qed. Lemma size_set_nth s n y : size (set_nth s n y) = maxn n.+1 (size s). Proof. rewrite maxnC; elim: s n => [|x s IHs] [|n] //=. - by rewrite size_ncons addn1. - by rewrite IHs maxnSS. Qed. Lemma set_nth_nil n y : set_nth [::] n y = ncons n x0 [:: y]. Proof. by case: n. Qed. Lemma nth_set_nth s n y : nth (set_nth s n y) =1 [eta nth s with n |-> y]. Proof. elim: s n => [|x s IHs] [|n] [|m] //=; rewrite ?nth_nil ?IHs // nth_ncons eqSS. case: ltngtP => // [lt_nm | ->]; last by rewrite subnn. by rewrite nth_default // subn_gt0. Qed. Lemma set_set_nth s n1 y1 n2 y2 (s2 := set_nth s n2 y2) : set_nth (set_nth s n1 y1) n2 y2 = if n1 == n2 then s2 else set_nth s2 n1 y1. Proof. have [-> | ne_n12] := eqVneq. apply: eq_from_nth => [|i _]; first by rewrite !size_set_nth maxnA maxnn. by do 2!rewrite !nth_set_nth /=; case: eqP. apply: eq_from_nth => [|i _]; first by rewrite !size_set_nth maxnCA. by do 2!rewrite !nth_set_nth /=; case: eqP => // ->; case: eqVneq ne_n12. Qed. (* find, count, has, all. *) Section SeqFind. Variable a : pred T. Fixpoint find s := if s is x :: s' then if a x then 0 else (find s').+1 else 0. Fixpoint filter s := if s is x :: s' then if a x then x :: filter s' else filter s' else [::]. Fixpoint count s := if s is x :: s' then a x + count s' else 0. Fixpoint has s := if s is x :: s' then a x || has s' else false. Fixpoint all s := if s is x :: s' then a x && all s' else true. Lemma size_filter s : size (filter s) = count s. Proof. by elim: s => //= x s <-; case (a x). Qed. Lemma has_count s : has s = (0 < count s). Proof. by elim: s => //= x s ->; case (a x). Qed. Lemma size_filter_gt0 s : (size (filter s) > 0) = (has s). Proof. by rewrite size_filter -has_count. Qed. Lemma count_size s : count s <= size s. Proof. by elim: s => //= x s; case: (a x); last apply: leqW. Qed. Lemma all_count s : all s = (count s == size s). Proof. elim: s => //= x s; case: (a x) => _ //=. by rewrite add0n eqn_leq andbC ltnNge count_size. Qed. Lemma filter_all s : all (filter s). Proof. by elim: s => //= x s IHs; case: ifP => //= ->. Qed. Lemma all_filterP s : reflect (filter s = s) (all s). Proof. apply: (iffP idP) => [| <-]; last exact: filter_all. by elim: s => //= x s IHs /andP[-> Hs]; rewrite IHs. Qed. Lemma filter_id s : filter (filter s) = filter s. Proof. by apply/all_filterP; apply: filter_all. Qed. Lemma has_find s : has s = (find s < size s). Proof. by elim: s => //= x s IHs; case (a x); rewrite ?leqnn. Qed. Lemma find_size s : find s <= size s. Proof. by elim: s => //= x s IHs; case (a x). Qed. Lemma find_cat s1 s2 : find (s1 ++ s2) = if has s1 then find s1 else size s1 + find s2. Proof. by elim: s1 => //= x s1 IHs; case: (a x) => //; rewrite IHs (fun_if succn). Qed. Lemma has_nil : has [::] = false. Proof. by []. Qed. Lemma has_seq1 x : has [:: x] = a x. Proof. exact: orbF. Qed. Lemma has_nseq n x : has (nseq n x) = (0 < n) && a x. Proof. by elim: n => //= n ->; apply: andKb. Qed. Lemma has_seqb (b : bool) x : has (nseq b x) = b && a x. Proof. by rewrite has_nseq lt0b. Qed. Lemma all_nil : all [::] = true. Proof. by []. Qed. Lemma all_seq1 x : all [:: x] = a x. Proof. exact: andbT. Qed. Lemma all_nseq n x : all (nseq n x) = (n == 0) || a x. Proof. by elim: n => //= n ->; apply: orKb. Qed. Lemma all_nseqb (b : bool) x : all (nseq b x) = b ==> a x. Proof. by rewrite all_nseq eqb0 implybE. Qed. Lemma filter_nseq n x : filter (nseq n x) = nseq (a x * n) x. Proof. by elim: n => /= [|n ->]; case: (a x). Qed. Lemma count_nseq n x : count (nseq n x) = a x * n. Proof. by rewrite -size_filter filter_nseq size_nseq. Qed. Lemma find_nseq n x : find (nseq n x) = ~~ a x * n. Proof. by elim: n => /= [|n ->]; case: (a x). Qed. Lemma nth_find s : has s -> a (nth s (find s)). Proof. by elim: s => //= x s IHs; case a_x: (a x). Qed. Lemma before_find s i : i < find s -> a (nth s i) = false. Proof. by elim: s i => //= x s IHs; case: ifP => // a'x [|i] // /(IHs i). Qed. Lemma hasNfind s : ~~ has s -> find s = size s. Proof. by rewrite has_find; case: ltngtP (find_size s). Qed. Lemma filter_cat s1 s2 : filter (s1 ++ s2) = filter s1 ++ filter s2. Proof. by elim: s1 => //= x s1 ->; case (a x). Qed. Lemma filter_rcons s x : filter (rcons s x) = if a x then rcons (filter s) x else filter s. Proof. by rewrite -!cats1 filter_cat /=; case (a x); rewrite /= ?cats0. Qed. Lemma count_cat s1 s2 : count (s1 ++ s2) = count s1 + count s2. Proof. by rewrite -!size_filter filter_cat size_cat. Qed. Lemma has_cat s1 s2 : has (s1 ++ s2) = has s1 || has s2. Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs orbA. Qed. Lemma has_rcons s x : has (rcons s x) = a x || has s. Proof. by rewrite -cats1 has_cat has_seq1 orbC. Qed. Lemma all_cat s1 s2 : all (s1 ++ s2) = all s1 && all s2. Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs andbA. Qed. Lemma all_rcons s x : all (rcons s x) = a x && all s. Proof. by rewrite -cats1 all_cat all_seq1 andbC. Qed. End SeqFind. Lemma find_pred0 s : find pred0 s = size s. Proof. by []. Qed. Lemma find_predT s : find predT s = 0. Proof. by case: s. Qed. Lemma eq_find a1 a2 : a1 =1 a2 -> find a1 =1 find a2. Proof. by move=> Ea; elim=> //= x s IHs; rewrite Ea IHs. Qed. Lemma eq_filter a1 a2 : a1 =1 a2 -> filter a1 =1 filter a2. Proof. by move=> Ea; elim=> //= x s IHs; rewrite Ea IHs. Qed. Lemma eq_count a1 a2 : a1 =1 a2 -> count a1 =1 count a2. Proof. by move=> Ea s; rewrite -!size_filter (eq_filter Ea). Qed. Lemma eq_has a1 a2 : a1 =1 a2 -> has a1 =1 has a2. Proof. by move=> Ea s; rewrite !has_count (eq_count Ea). Qed. Lemma eq_all a1 a2 : a1 =1 a2 -> all a1 =1 all a2. Proof. by move=> Ea s; rewrite !all_count (eq_count Ea). Qed. Lemma all_filter (p q : pred T) xs : all p (filter q xs) = all [pred i | q i ==> p i] xs. Proof. by elim: xs => //= x xs <-; case: (q x). Qed. Section SubPred. Variable (a1 a2 : pred T). Hypothesis s12 : subpred a1 a2. Lemma sub_find s : find a2 s <= find a1 s. Proof. by elim: s => //= x s IHs; case: ifP => // /(contraFF (@s12 x))->. Qed. Lemma sub_has s : has a1 s -> has a2 s. Proof. by rewrite !has_find; apply: leq_ltn_trans (sub_find s). Qed. Lemma sub_count s : count a1 s <= count a2 s. Proof. by elim: s => //= x s; apply: leq_add; case a1x: (a1 x); rewrite // s12. Qed. Lemma sub_all s : all a1 s -> all a2 s. Proof. by rewrite !all_count !eqn_leq !count_size => /leq_trans-> //; apply: sub_count. Qed. End SubPred. Lemma filter_pred0 s : filter pred0 s = [::]. Proof. by elim: s. Qed. Lemma filter_predT s : filter predT s = s. Proof. by elim: s => //= x s ->. Qed. Lemma filter_predI a1 a2 s : filter (predI a1 a2) s = filter a1 (filter a2 s). Proof. by elim: s => //= x s ->; rewrite andbC; case: (a2 x). Qed. Lemma count_pred0 s : count pred0 s = 0. Proof. by rewrite -size_filter filter_pred0. Qed. Lemma count_predT s : count predT s = size s. Proof. by rewrite -size_filter filter_predT. Qed. Lemma count_predUI a1 a2 s : count (predU a1 a2) s + count (predI a1 a2) s = count a1 s + count a2 s. Proof. elim: s => //= x s IHs; rewrite /= addnACA [RHS]addnACA IHs. by case: (a1 x) => //; rewrite addn0. Qed. Lemma count_predC a s : count a s + count (predC a) s = size s. Proof. by elim: s => //= x s IHs; rewrite addnACA IHs; case: (a _). Qed. Lemma count_filter a1 a2 s : count a1 (filter a2 s) = count (predI a1 a2) s. Proof. by rewrite -!size_filter filter_predI. Qed. Lemma has_pred0 s : has pred0 s = false. Proof. by rewrite has_count count_pred0. Qed. Lemma has_predT s : has predT s = (0 < size s). Proof. by rewrite has_count count_predT. Qed. Lemma has_predC a s : has (predC a) s = ~~ all a s. Proof. by elim: s => //= x s ->; case (a x). Qed. Lemma has_predU a1 a2 s : has (predU a1 a2) s = has a1 s || has a2 s. Proof. by elim: s => //= x s ->; rewrite -!orbA; do !bool_congr. Qed. Lemma all_pred0 s : all pred0 s = (size s == 0). Proof. by rewrite all_count count_pred0 eq_sym. Qed. Lemma all_predT s : all predT s. Proof. by rewrite all_count count_predT. Qed. Lemma allT (a : pred T) s : (forall x, a x) -> all a s. Proof. by move/eq_all->; apply/all_predT. Qed. Lemma all_predC a s : all (predC a) s = ~~ has a s. Proof. by elim: s => //= x s ->; case (a x). Qed. Lemma all_predI a1 a2 s : all (predI a1 a2) s = all a1 s && all a2 s. Proof. apply: (can_inj negbK); rewrite negb_and -!has_predC -has_predU. by apply: eq_has => x; rewrite /= negb_and. Qed. (* Surgery: drop, take, rot, rotr. *) Fixpoint drop n s {struct s} := match s, n with | _ :: s', n'.+1 => drop n' s' | _, _ => s end. Lemma drop_behead : drop n0 =1 iter n0 behead. Proof. by elim: n0 => [|n IHn] [|x s] //; rewrite iterSr -IHn. Qed. Lemma drop0 s : drop 0 s = s. Proof. by case: s. Qed. Lemma drop1 : drop 1 =1 behead. Proof. by case=> [|x [|y s]]. Qed. Lemma drop_oversize n s : size s <= n -> drop n s = [::]. Proof. by elim: s n => [|x s IHs] []. Qed. Lemma drop_size s : drop (size s) s = [::]. Proof. by rewrite drop_oversize // leqnn. Qed. Lemma drop_cons x s : drop n0 (x :: s) = if n0 is n.+1 then drop n s else x :: s. Proof. by []. Qed. Lemma size_drop s : size (drop n0 s) = size s - n0. Proof. by elim: s n0 => [|x s IHs] []. Qed. Lemma drop_cat s1 s2 : drop n0 (s1 ++ s2) = if n0 < size s1 then drop n0 s1 ++ s2 else drop (n0 - size s1) s2. Proof. by elim: s1 n0 => [|x s1 IHs] []. Qed. Lemma drop_size_cat n s1 s2 : size s1 = n -> drop n (s1 ++ s2) = s2. Proof. by move <-; elim: s1 => //=; rewrite drop0. Qed. Lemma nconsK n x : cancel (ncons n x) (drop n). Proof. by elim: n => // -[]. Qed. Lemma drop_drop s n1 n2 : drop n1 (drop n2 s) = drop (n1 + n2) s. Proof. by elim: s n2 => // x s ihs [|n2]; rewrite ?drop0 ?addn0 ?addnS /=. Qed. Fixpoint take n s {struct s} := match s, n with | x :: s', n'.+1 => x :: take n' s' | _, _ => [::] end. Lemma take0 s : take 0 s = [::]. Proof. by case: s. Qed. Lemma take_oversize n s : size s <= n -> take n s = s. Proof. by elim: s n => [|x s IHs] [|n] //= /IHs->. Qed. Lemma take_size s : take (size s) s = s. Proof. exact: take_oversize. Qed. Lemma take_cons x s : take n0 (x :: s) = if n0 is n.+1 then x :: (take n s) else [::]. Proof. by []. Qed. Lemma drop_rcons s : n0 <= size s -> forall x, drop n0 (rcons s x) = rcons (drop n0 s) x. Proof. by elim: s n0 => [|y s IHs] []. Qed. Lemma cat_take_drop s : take n0 s ++ drop n0 s = s. Proof. by elim: s n0 => [|x s IHs] [|n] //=; rewrite IHs. Qed. Lemma size_takel s : n0 <= size s -> size (take n0 s) = n0. Proof. by move/subKn; rewrite -size_drop -[in size s](cat_take_drop s) size_cat addnK. Qed. Lemma size_take s : size (take n0 s) = if n0 < size s then n0 else size s. Proof. have [le_sn | lt_ns] := leqP (size s) n0; first by rewrite take_oversize. by rewrite size_takel // ltnW. Qed. Lemma size_take_min s : size (take n0 s) = minn n0 (size s). Proof. exact: size_take. Qed. Lemma take_cat s1 s2 : take n0 (s1 ++ s2) = if n0 < size s1 then take n0 s1 else s1 ++ take (n0 - size s1) s2. Proof. elim: s1 n0 => [|x s1 IHs] [|n] //=. by rewrite ltnS subSS -(fun_if (cons x)) -IHs. Qed. Lemma take_size_cat n s1 s2 : size s1 = n -> take n (s1 ++ s2) = s1. Proof. by move <-; elim: s1 => [|x s1 IHs]; rewrite ?take0 //= IHs. Qed. Lemma takel_cat s1 s2 : n0 <= size s1 -> take n0 (s1 ++ s2) = take n0 s1. Proof. by rewrite take_cat; case: ltngtP => // ->; rewrite subnn take0 take_size cats0. Qed. Lemma nth_drop s i : nth (drop n0 s) i = nth s (n0 + i). Proof. rewrite -[s in RHS]cat_take_drop nth_cat size_take ltnNge. case: ltnP => [?|le_s_n0]; rewrite ?(leq_trans le_s_n0) ?leq_addr ?addKn //=. by rewrite drop_oversize // !nth_default. Qed. Lemma find_ltn p s i : has p (take i s) -> find p s < i. Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs. Qed. Lemma has_take p s i : has p s -> has p (take i s) = (find p s < i). Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs ->. Qed. Lemma has_take_leq (p : pred T) (s : seq T) i : i <= size s -> has p (take i s) = (find p s < i). Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs ->. Qed. Lemma nth_take i : i < n0 -> forall s, nth (take n0 s) i = nth s i. Proof. move=> lt_i_n0 s; case lt_n0_s: (n0 < size s). by rewrite -[s in RHS]cat_take_drop nth_cat size_take lt_n0_s /= lt_i_n0. by rewrite -[s in LHS]cats0 take_cat lt_n0_s /= cats0. Qed. Lemma take_min i j s : take (minn i j) s = take i (take j s). Proof. by elim: s i j => //= a l IH [|i] [|j] //=; rewrite minnSS IH. Qed. Lemma take_takel i j s : i <= j -> take i (take j s) = take i s. Proof. by move=> ?; rewrite -take_min (minn_idPl _). Qed. Lemma take_taker i j s : j <= i -> take i (take j s) = take j s. Proof. by move=> ?; rewrite -take_min (minn_idPr _). Qed. Lemma take_drop i j s : take i (drop j s) = drop j (take (i + j) s). Proof. by rewrite addnC; elim: s i j => // x s IHs [|i] [|j] /=. Qed. Lemma takeD i j s : take (i + j) s = take i s ++ take j (drop i s). Proof. elim: i j s => [|i IHi] [|j] [|a s] //; first by rewrite take0 addn0 cats0. by rewrite addSn /= IHi. Qed. Lemma takeC i j s : take i (take j s) = take j (take i s). Proof. by rewrite -!take_min minnC. Qed. Lemma take_nseq i j x : i <= j -> take i (nseq j x) = nseq i x. Proof. by move=>/subnKC <-; rewrite nseqD take_size_cat // size_nseq. Qed. Lemma drop_nseq i j x : drop i (nseq j x) = nseq (j - i) x. Proof. case: (leqP i j) => [/subnKC {1}<-|/ltnW j_le_i]. by rewrite nseqD drop_size_cat // size_nseq. by rewrite drop_oversize ?size_nseq // (eqP j_le_i). Qed. (* drop_nth and take_nth below do NOT use the default n0, because the "n" *) (* can be inferred from the condition, whereas the nth default value x0 *) (* will have to be given explicitly (and this will provide "d" as well). *) Lemma drop_nth n s : n < size s -> drop n s = nth s n :: drop n.+1 s. Proof. by elim: s n => [|x s IHs] [|n] Hn //=; rewrite ?drop0 1?IHs. Qed. Lemma take_nth n s : n < size s -> take n.+1 s = rcons (take n s) (nth s n). Proof. by elim: s n => [|x s IHs] //= [|n] Hn /=; rewrite ?take0 -?IHs. Qed. (* Rotation *) Definition rot n s := drop n s ++ take n s. Lemma rot0 s : rot 0 s = s. Proof. by rewrite /rot drop0 take0 cats0. Qed. Lemma size_rot s : size (rot n0 s) = size s. Proof. by rewrite -[s in RHS]cat_take_drop /rot !size_cat addnC. Qed. Lemma rot_oversize n s : size s <= n -> rot n s = s. Proof. by move=> le_s_n; rewrite /rot take_oversize ?drop_oversize. Qed. Lemma rot_size s : rot (size s) s = s. Proof. exact: rot_oversize. Qed. Lemma has_rot s a : has a (rot n0 s) = has a s. Proof. by rewrite has_cat orbC -has_cat cat_take_drop. Qed. Lemma rot_size_cat s1 s2 : rot (size s1) (s1 ++ s2) = s2 ++ s1. Proof. by rewrite /rot take_size_cat ?drop_size_cat. Qed. Definition rotr n s := rot (size s - n) s. Lemma rotK : cancel (rot n0) (rotr n0). Proof. move=> s; rewrite /rotr size_rot -size_drop {2}/rot. by rewrite rot_size_cat cat_take_drop. Qed. Lemma rot_inj : injective (rot n0). Proof. exact (can_inj rotK). Qed. (* (efficient) reversal *) Fixpoint catrev s1 s2 := if s1 is x :: s1' then catrev s1' (x :: s2) else s2. Definition rev s := catrev s [::]. Lemma catrev_catl s t u : catrev (s ++ t) u = catrev t (catrev s u). Proof. by elim: s u => /=. Qed. Lemma catrev_catr s t u : catrev s (t ++ u) = catrev s t ++ u. Proof. by elim: s t => //= x s IHs t; rewrite -IHs. Qed. Lemma catrevE s t : catrev s t = rev s ++ t. Proof. by rewrite -catrev_catr. Qed. Lemma rev_cons x s : rev (x :: s) = rcons (rev s) x. Proof. by rewrite -cats1 -catrevE. Qed. Lemma size_rev s : size (rev s) = size s. Proof. by elim: s => // x s IHs; rewrite rev_cons size_rcons IHs. Qed. Lemma rev_nilp s : nilp (rev s) = nilp s. Proof. by rewrite /nilp size_rev. Qed. Lemma rev_cat s t : rev (s ++ t) = rev t ++ rev s. Proof. by rewrite -catrev_catr -catrev_catl. Qed. Lemma rev_rcons s x : rev (rcons s x) = x :: rev s. Proof. by rewrite -cats1 rev_cat. Qed. Lemma revK : involutive rev. Proof. by elim=> //= x s IHs; rewrite rev_cons rev_rcons IHs. Qed. Lemma nth_rev n s : n < size s -> nth (rev s) n = nth s (size s - n.+1). Proof. elim/last_ind: s => // s x IHs in n *. rewrite rev_rcons size_rcons ltnS subSS -cats1 nth_cat /=. case: n => [|n] lt_n_s; first by rewrite subn0 ltnn subnn. by rewrite subnSK //= leq_subr IHs. Qed. Lemma filter_rev a s : filter a (rev s) = rev (filter a s). Proof. by elim: s => //= x s IH; rewrite fun_if !rev_cons filter_rcons IH. Qed. Lemma count_rev a s : count a (rev s) = count a s. Proof. by rewrite -!size_filter filter_rev size_rev. Qed. Lemma has_rev a s : has a (rev s) = has a s. Proof. by rewrite !has_count count_rev. Qed. Lemma all_rev a s : all a (rev s) = all a s. Proof. by rewrite !all_count count_rev size_rev. Qed. Lemma rev_nseq n x : rev (nseq n x) = nseq n x. Proof. by elim: n => // n IHn; rewrite -[in LHS]addn1 nseqD rev_cat IHn. Qed. End Sequences. Prenex Implicits size ncons nseq head ohead behead last rcons belast. Arguments seqn {T} n. Prenex Implicits cat take drop rot rotr catrev. Prenex Implicits find count nth all has filter. Arguments rev {T} s : simpl never. Arguments nth : simpl nomatch. Arguments set_nth : simpl nomatch. Arguments take : simpl nomatch. Arguments drop : simpl nomatch. Arguments nilP {T s}. Arguments all_filterP {T a s}. Arguments rotK n0 {T} s : rename. Arguments rot_inj {n0 T} [s1 s2] eq_rot_s12 : rename. Arguments revK {T} s : rename. Notation count_mem x := (count (pred_of_simpl (pred1 x))). Infix "++" := cat : seq_scope. Notation "[ 'seq' x <- s | C ]" := (filter (fun x => C%B) s) (x at level 99, format "[ '[hv' 'seq' x <- s '/ ' | C ] ']'") : seq_scope. Notation "[ 'seq' x <- s | C1 & C2 ]" := [seq x <- s | C1 && C2] (format "[ '[hv' 'seq' x <- s '/ ' | C1 '/ ' & C2 ] ']'") : seq_scope. Notation "[ 'seq' ' x <- s | C ]" := (filter (fun x => C%B) s) (x strict pattern, format "[ '[hv' 'seq' ' x <- s '/ ' | C ] ']'") : seq_scope. Notation "[ 'seq' ' x <- s | C1 & C2 ]" := [seq x <- s | C1 && C2] (x strict pattern, format "[ '[hv' 'seq' ' x <- s '/ ' | C1 '/ ' & C2 ] ']'") : seq_scope. Notation "[ 'seq' x : T <- s | C ]" := (filter (fun x : T => C%B) s) (only parsing). Notation "[ 'seq' x : T <- s | C1 & C2 ]" := [seq x : T <- s | C1 && C2] (only parsing). (* Double induction/recursion. *) Lemma seq_ind2 {S T} (P : seq S -> seq T -> Type) : P [::] [::] -> (forall x y s t, size s = size t -> P s t -> P (x :: s) (y :: t)) -> forall s t, size s = size t -> P s t. Proof. by move=> Pnil Pcons; elim=> [|x s IHs] [|y t] //= [eq_sz]; apply/Pcons/IHs. Qed. Section AllIff. (* The Following Are Equivalent *) (* We introduce a specific conjunction, used to chain the consecutive *) (* items in a circular list of implications *) Inductive all_iff_and (P Q : Prop) : Prop := AllIffConj of P & Q. Definition all_iff (P0 : Prop) (Ps : seq Prop) : Prop := let fix loop (P : Prop) (Qs : seq Prop) : Prop := if Qs is Q :: Qs then all_iff_and (P -> Q) (loop Q Qs) else P -> P0 in loop P0 Ps. Lemma all_iffLR P0 Ps : all_iff P0 Ps -> forall m n, nth P0 (P0 :: Ps) m -> nth P0 (P0 :: Ps) n. Proof. move=> iffPs; have PsS n: nth P0 Ps n -> nth P0 Ps n.+1. elim: n P0 Ps iffPs => [|n IHn] P0 [|P [|Q Ps]] //= [iP0P] //; first by case. by rewrite nth_nil. by case=> iPQ iffPs; apply: IHn; split=> // /iP0P. have{PsS} lePs: {homo nth P0 Ps : m n / m <= n >-> (m -> n)}. by move=> m n /subnK<-; elim: {n}(n - m) => // n IHn /IHn; apply: PsS. move=> m n P_m; have{m P_m} hP0: P0. case: m P_m => //= m /(lePs m _ (leq_maxl m (size Ps))). by rewrite nth_default ?leq_maxr. case: n =>// n; apply: lePs 0 n (leq0n n) _. by case: Ps iffPs hP0 => // P Ps []. Qed. Lemma all_iffP P0 Ps : all_iff P0 Ps -> forall m n, nth P0 (P0 :: Ps) m <-> nth P0 (P0 :: Ps) n. Proof. by move=> /all_iffLR-iffPs m n; split => /iffPs. Qed. End AllIff. Arguments all_iffLR {P0 Ps}. Arguments all_iffP {P0 Ps}. Coercion all_iffP : all_iff >-> Funclass. (* This means "the following are all equivalent: P0, ... Pn" *) Notation "[ '<->' P0 ; P1 ; .. ; Pn ]" := (all_iff P0 (@cons Prop P1 (.. (@cons Prop Pn nil) ..))) : form_scope. Ltac tfae := do !apply: AllIffConj. Section FindSpec. Variable (T : Type) (a : {pred T}) (s : seq T). Variant find_spec : bool -> nat -> Type := | NotFound of ~~ has a s : find_spec false (size s) | Found (i : nat) of i < size s & (forall x0, a (nth x0 s i)) & (forall x0 j, j < i -> a (nth x0 s j) = false) : find_spec true i. Lemma findP : find_spec (has a s) (find a s). Proof. have [a_s|aNs] := boolP (has a s); last by rewrite hasNfind//; constructor. by constructor=> [|x0|x0]; rewrite -?has_find ?nth_find//; apply: before_find. Qed. End FindSpec. Arguments findP {T}. Section RotRcons. Variable T : Type. Implicit Types (x : T) (s : seq T). Lemma rot1_cons x s : rot 1 (x :: s) = rcons s x. Proof. by rewrite /rot /= take0 drop0 -cats1. Qed. Lemma rcons_inj s1 s2 x1 x2 : rcons s1 x1 = rcons s2 x2 :> seq T -> (s1, x1) = (s2, x2). Proof. by rewrite -!rot1_cons => /rot_inj[-> ->]. Qed. Lemma rcons_injl x : injective (rcons^~ x). Proof. by move=> s1 s2 /rcons_inj[]. Qed. Lemma rcons_injr s : injective (rcons s). Proof. by move=> x1 x2 /rcons_inj[]. Qed. End RotRcons. Arguments rcons_inj {T s1 x1 s2 x2} eq_rcons : rename. Arguments rcons_injl {T} x [s1 s2] eq_rcons : rename. Arguments rcons_injr {T} s [x1 x2] eq_rcons : rename. (* Equality and eqType for seq. *) Section EqSeq. Variables (n0 : nat) (T : eqType) (x0 : T). Local Notation nth := (nth x0). Implicit Types (x y z : T) (s : seq T). Fixpoint eqseq s1 s2 {struct s2} := match s1, s2 with | [::], [::] => true | x1 :: s1', x2 :: s2' => (x1 == x2) && eqseq s1' s2' | _, _ => false end. Lemma eqseqP : Equality.axiom eqseq. Proof. move; elim=> [|x1 s1 IHs] [|x2 s2]; do [by constructor | simpl]. have [<-|neqx] := x1 =P x2; last by right; case. by apply: (iffP (IHs s2)) => [<-|[]]. Qed. HB.instance Definition _ := hasDecEq.Build (seq T) eqseqP. Lemma eqseqE : eqseq = eq_op. Proof. by []. Qed. Lemma eqseq_cons x1 x2 s1 s2 : (x1 :: s1 == x2 :: s2) = (x1 == x2) && (s1 == s2). Proof. by []. Qed. Lemma eqseq_cat s1 s2 s3 s4 : size s1 = size s2 -> (s1 ++ s3 == s2 ++ s4) = (s1 == s2) && (s3 == s4). Proof. elim: s1 s2 => [|x1 s1 IHs] [|x2 s2] //= [sz12]. by rewrite !eqseq_cons -andbA IHs. Qed. Lemma eqseq_rcons s1 s2 x1 x2 : (rcons s1 x1 == rcons s2 x2) = (s1 == s2) && (x1 == x2). Proof. by rewrite -(can_eq revK) !rev_rcons eqseq_cons andbC (can_eq revK). Qed. Lemma size_eq0 s : (size s == 0) = (s == [::]). Proof. exact: (sameP nilP eqP). Qed. Lemma nilpE s : nilp s = (s == [::]). Proof. by case: s. Qed. Lemma has_filter a s : has a s = (filter a s != [::]). Proof. by rewrite -size_eq0 size_filter has_count lt0n. Qed. (* mem_seq and index. *) (* mem_seq defines a predType for seq. *) Fixpoint mem_seq (s : seq T) := if s is y :: s' then xpredU1 y (mem_seq s') else xpred0. Definition seq_eqclass := seq T. Identity Coercion seq_of_eqclass : seq_eqclass >-> seq. Coercion pred_of_seq (s : seq_eqclass) : {pred T} := mem_seq s. Canonical seq_predType := PredType (pred_of_seq : seq T -> pred T). (* The line below makes mem_seq a canonical instance of topred. *) Canonical mem_seq_predType := PredType mem_seq. Lemma in_cons y s x : (x \in y :: s) = (x == y) || (x \in s). Proof. by []. Qed. Lemma in_nil x : (x \in [::]) = false. Proof. by []. Qed. Lemma mem_seq1 x y : (x \in [:: y]) = (x == y). Proof. by rewrite in_cons orbF. Qed. (* to be repeated after the Section discharge. *) Let inE := (mem_seq1, in_cons, inE). Lemma forall_cons {P : T -> Prop} {a s} : {in a::s, forall x, P x} <-> P a /\ {in s, forall x, P x}. Proof. split=> [A|[A B]]; last by move => x /predU1P [-> //|]; apply: B. by split=> [|b Hb]; apply: A; rewrite !inE ?eqxx ?Hb ?orbT. Qed. Lemma exists_cons {P : T -> Prop} {a s} : (exists2 x, x \in a::s & P x) <-> P a \/ exists2 x, x \in s & P x. Proof. split=> [[x /predU1P[->|x_s] Px]|]; [by left| by right; exists x|]. by move=> [?|[x x_s ?]]; [exists a|exists x]; rewrite ?inE ?eqxx ?x_s ?orbT. Qed. Lemma mem_seq2 x y z : (x \in [:: y; z]) = xpred2 y z x. Proof. by rewrite !inE. Qed. Lemma mem_seq3 x y z t : (x \in [:: y; z; t]) = xpred3 y z t x. Proof. by rewrite !inE. Qed. Lemma mem_seq4 x y z t u : (x \in [:: y; z; t; u]) = xpred4 y z t u x. Proof. by rewrite !inE. Qed. Lemma mem_cat x s1 s2 : (x \in s1 ++ s2) = (x \in s1) || (x \in s2). Proof. by elim: s1 => //= y s1 IHs; rewrite !inE /= -orbA -IHs. Qed. Lemma mem_rcons s y : rcons s y =i y :: s. Proof. by move=> x; rewrite -cats1 /= mem_cat mem_seq1 orbC in_cons. Qed. Lemma mem_head x s : x \in x :: s. Proof. exact: predU1l. Qed. Lemma mem_last x s : last x s \in x :: s. Proof. by rewrite lastI mem_rcons mem_head. Qed. Lemma mem_behead s : {subset behead s <= s}. Proof. by case: s => // y s x; apply: predU1r. Qed. Lemma mem_belast s y : {subset belast y s <= y :: s}. Proof. by move=> x ys'x; rewrite lastI mem_rcons mem_behead. Qed. Lemma mem_nth s n : n < size s -> nth s n \in s. Proof. by elim: s n => // x s IHs [_|n sz_s]; rewrite ?mem_head // mem_behead ?IHs. Qed. Lemma mem_take s x : x \in take n0 s -> x \in s. Proof. by move=> s0x; rewrite -(cat_take_drop n0 s) mem_cat /= s0x. Qed. Lemma mem_drop s x : x \in drop n0 s -> x \in s. Proof. by move=> s0'x; rewrite -(cat_take_drop n0 s) mem_cat /= s0'x orbT. Qed. Lemma last_eq s z x y : x != y -> z != y -> (last x s == y) = (last z s == y). Proof. by move=> /negPf xz /negPf yz; case: s => [|t s]//; rewrite xz yz. Qed. Section Filters. Implicit Type a : pred T. Lemma hasP {a s} : reflect (exists2 x, x \in s & a x) (has a s). Proof. elim: s => [|y s IHs] /=; first by right; case. exact: equivP (orPP idP IHs) (iff_sym exists_cons). Qed. Lemma allP {a s} : reflect {in s, forall x, a x} (all a s). Proof. elim: s => [|/= y s IHs]; first by left. exact: equivP (andPP idP IHs) (iff_sym forall_cons). Qed. Lemma hasPn a s : reflect {in s, forall x, ~~ a x} (~~ has a s). Proof. by rewrite -all_predC; apply: allP. Qed. Lemma allPn a s : reflect (exists2 x, x \in s & ~~ a x) (~~ all a s). Proof. by rewrite -has_predC; apply: hasP. Qed. Lemma allss s : all [in s] s. Proof. exact/allP. Qed. Lemma mem_filter a x s : (x \in filter a s) = a x && (x \in s). Proof. rewrite andbC; elim: s => //= y s IHs. rewrite (fun_if (fun s' : seq T => x \in s')) !in_cons {}IHs. by case: eqP => [->|_]; case (a y); rewrite /= ?andbF. Qed. Variables (a : pred T) (s : seq T) (A : T -> Prop). Hypothesis aP : forall x, reflect (A x) (a x). Lemma hasPP : reflect (exists2 x, x \in s & A x) (has a s). Proof. by apply: (iffP hasP) => -[x ? /aP]; exists x. Qed. Lemma allPP : reflect {in s, forall x, A x} (all a s). Proof. by apply: (iffP allP) => a_s x /a_s/aP. Qed. End Filters. Section EqIn. Variables a1 a2 : pred T. Lemma eq_in_filter s : {in s, a1 =1 a2} -> filter a1 s = filter a2 s. Proof. by elim: s => //= x s IHs /forall_cons [-> /IHs ->]. Qed. Lemma eq_in_find s : {in s, a1 =1 a2} -> find a1 s = find a2 s. Proof. by elim: s => //= x s IHs /forall_cons [-> /IHs ->]. Qed. Lemma eq_in_count s : {in s, a1 =1 a2} -> count a1 s = count a2 s. Proof. by move/eq_in_filter=> eq_a12; rewrite -!size_filter eq_a12. Qed. Lemma eq_in_all s : {in s, a1 =1 a2} -> all a1 s = all a2 s. Proof. by move=> eq_a12; rewrite !all_count eq_in_count. Qed. Lemma eq_in_has s : {in s, a1 =1 a2} -> has a1 s = has a2 s. Proof. by move/eq_in_filter=> eq_a12; rewrite !has_filter eq_a12. Qed. End EqIn. Lemma eq_has_r s1 s2 : s1 =i s2 -> has^~ s1 =1 has^~ s2. Proof. by move=> Es a; apply/hasP/hasP=> -[x sx ax]; exists x; rewrite ?Es in sx *. Qed. Lemma eq_all_r s1 s2 : s1 =i s2 -> all^~ s1 =1 all^~ s2. Proof. by move=> Es a; apply/negb_inj; rewrite -!has_predC (eq_has_r Es). Qed. Lemma has_sym s1 s2 : has [in s1] s2 = has [in s2] s1. Proof. by apply/hasP/hasP=> -[x]; exists x. Qed. Lemma has_pred1 x s : has (pred1 x) s = (x \in s). Proof. by rewrite -(eq_has (mem_seq1^~ x)) (has_sym [:: x]) /= orbF. Qed. Lemma mem_rev s : rev s =i s. Proof. by move=> a; rewrite -!has_pred1 has_rev. Qed. (* Constant sequences, i.e., the image of nseq. *) Definition constant s := if s is x :: s' then all (pred1 x) s' else true. Lemma all_pred1P x s : reflect (s = nseq (size s) x) (all (pred1 x) s). Proof. elim: s => [|y s IHs] /=; first by left. case: eqP => [->{y} | ne_xy]; last by right=> [] [? _]; case ne_xy. by apply: (iffP IHs) => [<- //| []]. Qed. Lemma all_pred1_constant x s : all (pred1 x) s -> constant s. Proof. by case: s => //= y s /andP[/eqP->]. Qed. Lemma all_pred1_nseq x n : all (pred1 x) (nseq n x). Proof. by rewrite all_nseq /= eqxx orbT. Qed. Lemma mem_nseq n x y : (y \in nseq n x) = (0 < n) && (y == x). Proof. by rewrite -has_pred1 has_nseq eq_sym. Qed. Lemma nseqP n x y : reflect (y = x /\ n > 0) (y \in nseq n x). Proof. by rewrite mem_nseq andbC; apply: (iffP andP) => -[/eqP]. Qed. Lemma constant_nseq n x : constant (nseq n x). Proof. exact: all_pred1_constant (all_pred1_nseq x n). Qed. (* Uses x0 *) Lemma constantP s : reflect (exists x, s = nseq (size s) x) (constant s). Proof. apply: (iffP idP) => [| [x ->]]; last exact: constant_nseq. case: s => [|x s] /=; first by exists x0. by move/all_pred1P=> def_s; exists x; rewrite -def_s. Qed. (* Duplicate-freenes. *) Fixpoint uniq s := if s is x :: s' then (x \notin s') && uniq s' else true. Lemma cons_uniq x s : uniq (x :: s) = (x \notin s) && uniq s. Proof. by []. Qed. Lemma cat_uniq s1 s2 : uniq (s1 ++ s2) = [&& uniq s1, ~~ has [in s1] s2 & uniq s2]. Proof. elim: s1 => [|x s1 IHs]; first by rewrite /= has_pred0. by rewrite has_sym /= mem_cat !negb_or has_sym IHs -!andbA; do !bool_congr. Qed. Lemma uniq_catC s1 s2 : uniq (s1 ++ s2) = uniq (s2 ++ s1). Proof. by rewrite !cat_uniq has_sym andbCA andbA andbC. Qed. Lemma uniq_catCA s1 s2 s3 : uniq (s1 ++ s2 ++ s3) = uniq (s2 ++ s1 ++ s3). Proof. by rewrite !catA -!(uniq_catC s3) !(cat_uniq s3) uniq_catC !has_cat orbC. Qed. Lemma rcons_uniq s x : uniq (rcons s x) = (x \notin s) && uniq s. Proof. by rewrite -cats1 uniq_catC. Qed. Lemma filter_uniq s a : uniq s -> uniq (filter a s). Proof. elim: s => //= x s IHs /andP[s'x]; case: ifP => //= a_x /IHs->. by rewrite mem_filter a_x s'x. Qed. Lemma rot_uniq s : uniq (rot n0 s) = uniq s. Proof. by rewrite /rot uniq_catC cat_take_drop. Qed. Lemma rev_uniq s : uniq (rev s) = uniq s. Proof. elim: s => // x s IHs. by rewrite rev_cons -cats1 cat_uniq /= andbT andbC mem_rev orbF IHs. Qed. Lemma count_memPn x s : reflect (count_mem x s = 0) (x \notin s). Proof. by rewrite -has_pred1 has_count -eqn0Ngt; apply: eqP. Qed. Lemma count_uniq_mem s x : uniq s -> count_mem x s = (x \in s). Proof. elim: s => //= y s IHs /andP[/negbTE s'y /IHs-> {IHs}]. by rewrite in_cons; case: (eqVneq y x) => // <-; rewrite s'y. Qed. Lemma leq_uniq_countP x s1 s2 : uniq s1 -> reflect (x \in s1 -> x \in s2) (count_mem x s1 <= count_mem x s2). Proof. move/count_uniq_mem->; case: (boolP (_ \in _)) => //= _; last by constructor. by rewrite -has_pred1 has_count; apply: (iffP idP) => //; apply. Qed. Lemma leq_uniq_count s1 s2 : uniq s1 -> {subset s1 <= s2} -> (forall x, count_mem x s1 <= count_mem x s2). Proof. by move=> s1_uniq s1_s2 x; apply/leq_uniq_countP/s1_s2. Qed. Lemma filter_pred1_uniq s x : uniq s -> x \in s -> filter (pred1 x) s = [:: x]. Proof. move=> uniq_s s_x; rewrite (all_pred1P _ _ (filter_all _ _)). by rewrite size_filter count_uniq_mem ?s_x. Qed. (* Removing duplicates *) Fixpoint undup s := if s is x :: s' then if x \in s' then undup s' else x :: undup s' else [::]. Lemma size_undup s : size (undup s) <= size s. Proof. by elim: s => //= x s IHs; case: (x \in s) => //=; apply: ltnW. Qed. Lemma mem_undup s : undup s =i s. Proof. move=> x; elim: s => //= y s IHs. by case s_y: (y \in s); rewrite !inE IHs //; case: eqP => [->|]. Qed. Lemma undup_uniq s : uniq (undup s). Proof. by elim: s => //= x s IHs; case s_x: (x \in s); rewrite //= mem_undup s_x. Qed. Lemma undup_id s : uniq s -> undup s = s. Proof. by elim: s => //= x s IHs /andP[/negbTE-> /IHs->]. Qed. Lemma ltn_size_undup s : (size (undup s) < size s) = ~~ uniq s. Proof. by elim: s => //= x s IHs; case s_x: (x \in s); rewrite //= ltnS size_undup. Qed. Lemma filter_undup p s : filter p (undup s) = undup (filter p s). Proof. elim: s => //= x s IHs; rewrite (fun_if undup) [_ = _]fun_if /= mem_filter /=. by rewrite (fun_if (filter p)) /= IHs; case: ifP => -> //=; apply: if_same. Qed. Lemma undup_nil s : undup s = [::] -> s = [::]. Proof. by case: s => //= x s; rewrite -mem_undup; case: ifP; case: undup. Qed. Lemma undup_cat s t : undup (s ++ t) = [seq x <- undup s | x \notin t] ++ undup t. Proof. by elim: s => //= x s ->; rewrite mem_cat; do 2 case: in_mem => //=. Qed. Lemma undup_rcons s x : undup (rcons s x) = rcons [seq y <- undup s | y != x] x. Proof. by rewrite -!cats1 undup_cat; congr cat; apply: eq_filter => y; rewrite inE. Qed. Lemma count_undup s p : count p (undup s) <= count p s. Proof. by rewrite -!size_filter filter_undup size_undup. Qed. Lemma has_undup p s : has p (undup s) = has p s. Proof. by apply: eq_has_r => x; rewrite mem_undup. Qed. Lemma all_undup p s : all p (undup s) = all p s. Proof. by apply: eq_all_r => x; rewrite mem_undup. Qed. (* Lookup *) Definition index x := find (pred1 x). Lemma index_size x s : index x s <= size s. Proof. by rewrite /index find_size. Qed. Lemma index_mem x s : (index x s < size s) = (x \in s). Proof. by rewrite -has_pred1 has_find. Qed. Lemma memNindex x s : x \notin s -> index x s = size s. Proof. by rewrite -has_pred1 => /hasNfind. Qed. Lemma nth_index x s : x \in s -> nth s (index x s) = x. Proof. by rewrite -has_pred1 => /(nth_find x0)/eqP. Qed. Lemma index_inj s : {in s &, injective (index ^~ s)}. Proof. by move=> x y x_s y_s eidx; rewrite -(nth_index x_s) eidx nth_index. Qed. Lemma index_cat x s1 s2 : index x (s1 ++ s2) = if x \in s1 then index x s1 else size s1 + index x s2. Proof. by rewrite /index find_cat has_pred1. Qed. Lemma index_ltn x s i : x \in take i s -> index x s < i. Proof. by rewrite -has_pred1; apply: find_ltn. Qed. Lemma in_take x s i : x \in s -> (x \in take i s) = (index x s < i). Proof. by rewrite -?has_pred1; apply: has_take. Qed. Lemma in_take_leq x s i : i <= size s -> (x \in take i s) = (index x s < i). Proof. by rewrite -?has_pred1; apply: has_take_leq. Qed. Lemma index_nth i s : i < size s -> index (nth s i) s <= i. Proof. move=> lti; rewrite -ltnS index_ltn// -(@nth_take i.+1)// mem_nth // size_take. by case: ifP. Qed. Lemma nthK s: uniq s -> {in gtn (size s), cancel (nth s) (index^~ s)}. Proof. elim: s => //= x s IHs /andP[s'x Us] i; rewrite inE ltnS eq_sym -if_neg. by case: i => /= [_|i lt_i_s]; rewrite ?eqxx ?IHs ?(memPn s'x) ?mem_nth. Qed. Lemma index_uniq i s : i < size s -> uniq s -> index (nth s i) s = i. Proof. by move/nthK. Qed. Lemma index_head x s : index x (x :: s) = 0. Proof. by rewrite /= eqxx. Qed. Lemma index_last x s : uniq (x :: s) -> index (last x s) (x :: s) = size s. Proof. rewrite lastI rcons_uniq -cats1 index_cat size_belast. by case: ifP => //=; rewrite eqxx addn0. Qed. Lemma nth_uniq s i j : i < size s -> j < size s -> uniq s -> (nth s i == nth s j) = (i == j). Proof. by move=> lti ltj /nthK/can_in_eq->. Qed. Lemma uniqPn s : reflect (exists i j, [/\ i < j, j < size s & nth s i = nth s j]) (~~ uniq s). Proof. apply: (iffP idP) => [|[i [j [ltij ltjs]]]]; last first. by apply: contra_eqN => Us; rewrite nth_uniq ?ltn_eqF // (ltn_trans ltij). elim: s => // x s IHs /nandP[/negbNE | /IHs[i [j]]]; last by exists i.+1, j.+1. by exists 0, (index x s).+1; rewrite !ltnS index_mem /= nth_index. Qed. Lemma uniqP s : reflect {in gtn (size s) &, injective (nth s)} (uniq s). Proof. apply: (iffP idP) => [/nthK/can_in_inj// | nth_inj]. apply/uniqPn => -[i [j [ltij ltjs /nth_inj/eqP/idPn]]]. by rewrite !inE (ltn_trans ltij ltjs) ltn_eqF //=; case. Qed. Lemma mem_rot s : rot n0 s =i s. Proof. by move=> x; rewrite -[s in RHS](cat_take_drop n0) !mem_cat /= orbC. Qed. Lemma eqseq_rot s1 s2 : (rot n0 s1 == rot n0 s2) = (s1 == s2). Proof. exact/inj_eq/rot_inj. Qed. Lemma drop_index s (n := index x0 s) : x0 \in s -> drop n s = x0 :: drop n.+1 s. Proof. by move=> xs; rewrite (drop_nth x0) ?index_mem ?nth_index. Qed. (* lemmas about the pivot pattern [_ ++ _ :: _] *) Lemma index_pivot x s1 s2 (s := s1 ++ x :: s2) : x \notin s1 -> index x s = size s1. Proof. by rewrite index_cat/= eqxx addn0; case: ifPn. Qed. Lemma take_pivot x s2 s1 (s := s1 ++ x :: s2) : x \notin s1 -> take (index x s) s = s1. Proof. by move=> /index_pivot->; rewrite take_size_cat. Qed. Lemma rev_pivot x s1 s2 : rev (s1 ++ x :: s2) = rev s2 ++ x :: rev s1. Proof. by rewrite rev_cat rev_cons cat_rcons. Qed. Lemma eqseq_pivot2l x s1 s2 s3 s4 : x \notin s1 -> x \notin s3 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. move=> xNs1 xNs3; apply/idP/idP => [E|/andP[/eqP-> /eqP->]//]. suff S : size s1 = size s3 by rewrite eqseq_cat// eqseq_cons eqxx in E. by rewrite -(index_pivot s2 xNs1) (eqP E) index_pivot. Qed. Lemma eqseq_pivot2r x s1 s2 s3 s4 : x \notin s2 -> x \notin s4 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. move=> xNs2 xNs4; rewrite -(can_eq revK) !rev_pivot. by rewrite eqseq_pivot2l ?mem_rev // !(can_eq revK) andbC. Qed. Lemma eqseq_pivotl x s1 s2 s3 s4 : x \notin s1 -> x \notin s2 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. move=> xNs1 xNs2; apply/idP/idP => [E|/andP[/eqP-> /eqP->]//]. rewrite -(@eqseq_pivot2l x)//; have /eqP/(congr1 (count_mem x)) := E. rewrite !count_cat/= eqxx !addnS (count_memPn _ _ xNs1) (count_memPn _ _ xNs2). by move=> -[/esym/eqP]; rewrite addn_eq0 => /andP[/eqP/count_memPn]. Qed. Lemma eqseq_pivotr x s1 s2 s3 s4 : x \notin s3 -> x \notin s4 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. by move=> *; rewrite eq_sym eqseq_pivotl//; case: eqVneq => /=. Qed. Lemma uniq_eqseq_pivotl x s1 s2 s3 s4 : uniq (s1 ++ x :: s2) -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. by rewrite uniq_catC/= mem_cat => /andP[/norP[? ?] _]; rewrite eqseq_pivotl. Qed. Lemma uniq_eqseq_pivotr x s1 s2 s3 s4 : uniq (s3 ++ x :: s4) -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. by move=> ?; rewrite eq_sym uniq_eqseq_pivotl//; case: eqVneq => /=. Qed. End EqSeq. Arguments eqseq : simpl nomatch. Notation "'has_ view" := (hasPP _ (fun _ => view)) (at level 4, right associativity, format "''has_' view"). Notation "'all_ view" := (allPP _ (fun _ => view)) (at level 4, right associativity, format "''all_' view"). Section RotIndex. Variables (T : eqType). Implicit Types x y z : T. Lemma rot_index s x (i := index x s) : x \in s -> rot i s = x :: (drop i.+1 s ++ take i s). Proof. by move=> x_s; rewrite /rot drop_index. Qed. Variant rot_to_spec s x := RotToSpec i s' of rot i s = x :: s'. Lemma rot_to s x : x \in s -> rot_to_spec s x. Proof. by move=> /rot_index /RotToSpec. Qed. End RotIndex. Definition inE := (mem_seq1, in_cons, inE). Prenex Implicits mem_seq1 constant uniq undup index. Arguments eqseq {T} !_ !_. Arguments pred_of_seq {T} s x /. Arguments eqseqP {T x y}. Arguments hasP {T a s}. Arguments hasPn {T a s}. Arguments allP {T a s}. Arguments allPn {T a s}. Arguments nseqP {T n x y}. Arguments count_memPn {T x s}. Arguments uniqPn {T} x0 {s}. Arguments uniqP {T} x0 {s}. Arguments forall_cons {T P a s}. Arguments exists_cons {T P a s}. (* Since both `all [in s] s`, `all (mem s) s`, and `all (pred_of_seq s) s` *) (* may appear in goals, the following hint has to be declared using the *) (* `Hint Extern` command. Additionally, `mem` and `pred_of_seq` in the above *) (* terms do not reduce to each other; thus, stating `allss` in the form of *) (* one of them makes `apply: allss` fail for the other case. Since both `mem` *) (* and `pred_of_seq` reduce to `mem_seq`, the following explicit type *) (* annotation for `allss` makes it work for both cases. *) #[export] Hint Extern 0 (is_true (all _ _)) => apply: (allss : forall T s, all (mem_seq s) s) : core. Section NthTheory. Lemma nthP (T : eqType) (s : seq T) x x0 : reflect (exists2 i, i < size s & nth x0 s i = x) (x \in s). Proof. apply: (iffP idP) => [|[n Hn <-]]; last exact: mem_nth. by exists (index x s); [rewrite index_mem | apply nth_index]. Qed. Variable T : Type. Implicit Types (a : pred T) (x : T). Lemma has_nthP a s x0 : reflect (exists2 i, i < size s & a (nth x0 s i)) (has a s). Proof. elim: s => [|x s IHs] /=; first by right; case. case nax: (a x); first by left; exists 0. by apply: (iffP IHs) => [[i]|[[|i]]]; [exists i.+1 | rewrite nax | exists i]. Qed. Lemma all_nthP a s x0 : reflect (forall i, i < size s -> a (nth x0 s i)) (all a s). Proof. rewrite -(eq_all (fun x => negbK (a x))) all_predC. case: (has_nthP _ _ x0) => [na_s | a_s]; [right=> a_s | left=> i lti]. by case: na_s => i lti; rewrite a_s. by apply/idPn=> na_si; case: a_s; exists i. Qed. Lemma set_nthE s x0 n x : set_nth x0 s n x = if n < size s then take n s ++ x :: drop n.+1 s else s ++ ncons (n - size s) x0 [:: x]. Proof. elim: s n => [|a s IH] n /=; first by rewrite subn0 set_nth_nil. case: n => [|n]; first by rewrite drop0. by rewrite ltnS /=; case: ltnP (IH n) => _ ->. Qed. Lemma count_set_nth a s x0 n x : count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n) * (n < size s) + (a x0) * (n - size s). Proof. rewrite set_nthE; case: ltnP => [nlts|nges]; last first. rewrite -cat_nseq !count_cat count_nseq /=. by rewrite muln0 addn0 subn0 addnAC addnA. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. rewrite -[in count a s](cat_take_drop n s) [drop n s](drop_nth x0)//. by rewrite !count_cat/= muln1 muln0 addn0 addnAC !addnA [in RHS]addnAC addnK. Qed. Lemma count_set_nth_ltn a s x0 n x : n < size s -> count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n). Proof. move=> nlts; rewrite count_set_nth nlts muln1. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. by rewrite muln0 addn0. Qed. Lemma count_set_nthF a s x0 n x : ~~ a x0 -> count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n). Proof. move=> /negbTE ax0; rewrite count_set_nth ax0 mul0n addn0. case: ltnP => [_|nges]; first by rewrite muln1. by rewrite nth_default// ax0 subn0. Qed. End NthTheory. Lemma set_nth_default T s (y0 x0 : T) n : n < size s -> nth x0 s n = nth y0 s n. Proof. by elim: s n => [|y s' IHs] [|n] //= /IHs. Qed. Lemma headI T s (x : T) : rcons s x = head x s :: behead (rcons s x). Proof. by case: s. Qed. Arguments nthP {T s x}. Arguments has_nthP {T a s}. Arguments all_nthP {T a s}. Definition bitseq := seq bool. #[hnf] HB.instance Definition _ := Equality.on bitseq. Canonical bitseq_predType := Eval hnf in [predType of bitseq]. (* Generalizations of splitP (from path.v): split_find_nth and split_find *) Section FindNth. Variables (T : Type). Implicit Types (x : T) (p : pred T) (s : seq T). Variant split_find_nth_spec p : seq T -> seq T -> seq T -> T -> Type := FindNth x s1 s2 of p x & ~~ has p s1 : split_find_nth_spec p (rcons s1 x ++ s2) s1 s2 x. Lemma split_find_nth x0 p s (i := find p s) : has p s -> split_find_nth_spec p s (take i s) (drop i.+1 s) (nth x0 s i). Proof. move=> p_s; rewrite -[X in split_find_nth_spec _ X](cat_take_drop i s). rewrite (drop_nth x0 _) -?has_find// -cat_rcons. by constructor; [apply: nth_find | rewrite has_take -?leqNgt]. Qed. Variant split_find_spec p : seq T -> seq T -> seq T -> Type := FindSplit x s1 s2 of p x & ~~ has p s1 : split_find_spec p (rcons s1 x ++ s2) s1 s2. Lemma split_find p s (i := find p s) : has p s -> split_find_spec p s (take i s) (drop i.+1 s). Proof. by case: s => // x ? in i * => ?; case: split_find_nth => //; constructor. Qed. Lemma nth_rcons_cat_find x0 p s1 s2 x (s := rcons s1 x ++ s2) : p x -> ~~ has p s1 -> nth x0 s (find p s) = x. Proof. move=> pz pNs1; rewrite /s cat_rcons find_cat (negPf pNs1). by rewrite nth_cat/= pz addn0 subnn ltnn. Qed. End FindNth. (* Incrementing the ith nat in a seq nat, padding with 0's if needed. This *) (* allows us to use nat seqs as bags of nats. *) Fixpoint incr_nth v i {struct i} := if v is n :: v' then if i is i'.+1 then n :: incr_nth v' i' else n.+1 :: v' else ncons i 0 [:: 1]. Arguments incr_nth : simpl nomatch. Lemma nth_incr_nth v i j : nth 0 (incr_nth v i) j = (i == j) + nth 0 v j. Proof. elim: v i j => [|n v IHv] [|i] [|j] //=; rewrite ?eqSS ?addn0 //; try by case j. elim: i j => [|i IHv] [|j] //=; rewrite ?eqSS //; by case j. Qed. Lemma size_incr_nth v i : size (incr_nth v i) = if i < size v then size v else i.+1. Proof. elim: v i => [|n v IHv] [|i] //=; first by rewrite size_ncons /= addn1. by rewrite IHv; apply: fun_if. Qed. Lemma incr_nth_inj v : injective (incr_nth v). Proof. move=> i j /(congr1 (nth 0 ^~ i)); apply: contra_eq => neq_ij. by rewrite !nth_incr_nth eqn_add2r eqxx /nat_of_bool ifN_eqC. Qed. Lemma incr_nthC v i j : incr_nth (incr_nth v i) j = incr_nth (incr_nth v j) i. Proof. apply: (@eq_from_nth _ 0) => [|k _]; last by rewrite !nth_incr_nth addnCA. by do !rewrite size_incr_nth leqNgt if_neg -/(maxn _ _); apply: maxnAC. Qed. (* Equality up to permutation *) Section PermSeq. Variable T : eqType. Implicit Type s : seq T. Definition perm_eq s1 s2 := all [pred x | count_mem x s1 == count_mem x s2] (s1 ++ s2). Lemma permP s1 s2 : reflect (count^~ s1 =1 count^~ s2) (perm_eq s1 s2). Proof. apply: (iffP allP) => /= [eq_cnt1 a | eq_cnt x _]; last exact/eqP. have [n le_an] := ubnP (count a (s1 ++ s2)); elim: n => // n IHn in a le_an *. have [/eqP|] := posnP (count a (s1 ++ s2)). by rewrite count_cat addn_eq0; do 2!case: eqP => // ->. rewrite -has_count => /hasP[x s12x a_x]; pose a' := predD1 a x. have cnt_a' s: count a s = count_mem x s + count a' s. rewrite -count_predUI -[LHS]addn0 -(count_pred0 s). by congr (_ + _); apply: eq_count => y /=; case: eqP => // ->. rewrite !cnt_a' (eqnP (eq_cnt1 _ s12x)) (IHn a') // -ltnS. apply: leq_trans le_an. by rewrite ltnS cnt_a' -add1n leq_add2r -has_count has_pred1. Qed. Lemma perm_refl s : perm_eq s s. Proof. exact/permP. Qed. Hint Resolve perm_refl : core. Lemma perm_sym : symmetric perm_eq. Proof. by move=> s1 s2; apply/permP/permP=> eq_s12 a. Qed. Lemma perm_trans : transitive perm_eq. Proof. by move=> s2 s1 s3 /permP-eq12 /permP/(ftrans eq12)/permP. Qed. Notation perm_eql s1 s2 := (perm_eq s1 =1 perm_eq s2). Notation perm_eqr s1 s2 := (perm_eq^~ s1 =1 perm_eq^~ s2). Lemma permEl s1 s2 : perm_eql s1 s2 -> perm_eq s1 s2. Proof. by move->. Qed. Lemma permPl s1 s2 : reflect (perm_eql s1 s2) (perm_eq s1 s2). Proof. apply: (iffP idP) => [eq12 s3 | -> //]; apply/idP/idP; last exact: perm_trans. by rewrite -!(perm_sym s3) => /perm_trans; apply. Qed. Lemma permPr s1 s2 : reflect (perm_eqr s1 s2) (perm_eq s1 s2). Proof. by apply/(iffP idP) => [/permPl eq12 s3| <- //]; rewrite !(perm_sym s3) eq12. Qed. Lemma perm_catC s1 s2 : perm_eql (s1 ++ s2) (s2 ++ s1). Proof. by apply/permPl/permP=> a; rewrite !count_cat addnC. Qed. Lemma perm_cat2l s1 s2 s3 : perm_eq (s1 ++ s2) (s1 ++ s3) = perm_eq s2 s3. Proof. apply/permP/permP=> eq23 a; apply/eqP; by move/(_ a)/eqP: eq23; rewrite !count_cat eqn_add2l. Qed. Lemma perm_catl s t1 t2 : perm_eq t1 t2 -> perm_eql (s ++ t1) (s ++ t2). Proof. by move=> eq_t12; apply/permPl; rewrite perm_cat2l. Qed. Lemma perm_cons x s1 s2 : perm_eq (x :: s1) (x :: s2) = perm_eq s1 s2. Proof. exact: (perm_cat2l [::x]). Qed. Lemma perm_cat2r s1 s2 s3 : perm_eq (s2 ++ s1) (s3 ++ s1) = perm_eq s2 s3. Proof. by do 2!rewrite perm_sym perm_catC; apply: perm_cat2l. Qed. Lemma perm_catr s1 s2 t : perm_eq s1 s2 -> perm_eql (s1 ++ t) (s2 ++ t). Proof. by move=> eq_s12; apply/permPl; rewrite perm_cat2r. Qed. Lemma perm_cat s1 s2 t1 t2 : perm_eq s1 s2 -> perm_eq t1 t2 -> perm_eq (s1 ++ t1) (s2 ++ t2). Proof. by move=> /perm_catr-> /perm_catl->. Qed. Lemma perm_catAC s1 s2 s3 : perm_eql ((s1 ++ s2) ++ s3) ((s1 ++ s3) ++ s2). Proof. by apply/permPl; rewrite -!catA perm_cat2l perm_catC. Qed. Lemma perm_catCA s1 s2 s3 : perm_eql (s1 ++ s2 ++ s3) (s2 ++ s1 ++ s3). Proof. by apply/permPl; rewrite !catA perm_cat2r perm_catC. Qed. Lemma perm_catACA s1 s2 s3 s4 : perm_eql ((s1 ++ s2) ++ (s3 ++ s4)) ((s1 ++ s3) ++ (s2 ++ s4)). Proof. by apply/permPl; rewrite perm_catAC !catA perm_catAC. Qed. Lemma perm_rcons x s : perm_eql (rcons s x) (x :: s). Proof. by move=> /= s2; rewrite -cats1 perm_catC. Qed. Lemma perm_rot n s : perm_eql (rot n s) s. Proof. by move=> /= s2; rewrite perm_catC cat_take_drop. Qed. Lemma perm_rotr n s : perm_eql (rotr n s) s. Proof. exact: perm_rot. Qed. Lemma perm_rev s : perm_eql (rev s) s. Proof. by apply/permPl/permP=> i; rewrite count_rev. Qed. Lemma perm_filter s1 s2 a : perm_eq s1 s2 -> perm_eq (filter a s1) (filter a s2). Proof. by move/permP=> s12_count; apply/permP=> Q; rewrite !count_filter. Qed. Lemma perm_filterC a s : perm_eql (filter a s ++ filter (predC a) s) s. Proof. apply/permPl; elim: s => //= x s IHs. by case: (a x); last rewrite /= -cat1s perm_catCA; rewrite perm_cons. Qed. Lemma perm_size s1 s2 : perm_eq s1 s2 -> size s1 = size s2. Proof. by move/permP=> eq12; rewrite -!count_predT eq12. Qed. Lemma perm_mem s1 s2 : perm_eq s1 s2 -> s1 =i s2. Proof. by move/permP=> eq12 x; rewrite -!has_pred1 !has_count eq12. Qed. Lemma perm_nilP s : reflect (s = [::]) (perm_eq s [::]). Proof. by apply: (iffP idP) => [/perm_size/eqP/nilP | ->]. Qed. Lemma perm_consP x s t : reflect (exists i u, rot i t = x :: u /\ perm_eq u s) (perm_eq t (x :: s)). Proof. apply: (iffP idP) => [eq_txs | [i [u [Dt eq_us]]]]. have /rot_to[i u Dt]: x \in t by rewrite (perm_mem eq_txs) mem_head. by exists i, u; rewrite -(perm_cons x) -Dt perm_rot. by rewrite -(perm_rot i) Dt perm_cons. Qed. Lemma perm_has s1 s2 a : perm_eq s1 s2 -> has a s1 = has a s2. Proof. by move/perm_mem/eq_has_r. Qed. Lemma perm_all s1 s2 a : perm_eq s1 s2 -> all a s1 = all a s2. Proof. by move/perm_mem/eq_all_r. Qed. Lemma perm_small_eq s1 s2 : size s2 <= 1 -> perm_eq s1 s2 -> s1 = s2. Proof. move=> s2_le1 eqs12; move/perm_size: eqs12 s2_le1 (perm_mem eqs12). by case: s2 s1 => [|x []] // [|y []] // _ _ /(_ x) /[!(inE, eqxx)] /eqP->. Qed. Lemma uniq_leq_size s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s1 <= size s2. Proof. elim: s1 s2 => //= x s1 IHs s2 /andP[not_s1x Us1] /forall_cons[s2x ss12]. have [i s3 def_s2] := rot_to s2x; rewrite -(size_rot i s2) def_s2. apply: IHs => // y s1y; have:= ss12 y s1y. by rewrite -(mem_rot i) def_s2 inE (negPf (memPn _ y s1y)). Qed. Lemma leq_size_uniq s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s2 <= size s1 -> uniq s2. Proof. elim: s1 s2 => [[] | x s1 IHs s2] // Us1x; have /andP[not_s1x Us1] := Us1x. case/forall_cons => /rot_to[i s3 def_s2] ss12 le_s21. rewrite -(rot_uniq i) -(size_rot i) def_s2 /= in le_s21 *. have ss13 y (s1y : y \in s1): y \in s3. by have:= ss12 y s1y; rewrite -(mem_rot i) def_s2 inE (negPf (memPn _ y s1y)). rewrite IHs // andbT; apply: contraL _ le_s21 => s3x; rewrite -leqNgt. by apply/(uniq_leq_size Us1x)/allP; rewrite /= s3x; apply/allP. Qed. Lemma uniq_size_uniq s1 s2 : uniq s1 -> s1 =i s2 -> uniq s2 = (size s2 == size s1). Proof. move=> Us1 eqs12; apply/idP/idP=> [Us2 | /eqP eq_sz12]. by rewrite eqn_leq !uniq_leq_size // => y; rewrite eqs12. by apply: (leq_size_uniq Us1) => [y|]; rewrite (eqs12, eq_sz12). Qed. Lemma uniq_min_size s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s2 <= size s1 -> (size s1 = size s2) * (s1 =i s2). Proof. move=> Us1 ss12 le_s21; have Us2: uniq s2 := leq_size_uniq Us1 ss12 le_s21. suffices: s1 =i s2 by split; first by apply/eqP; rewrite -uniq_size_uniq. move=> x; apply/idP/idP=> [/ss12// | s2x]; apply: contraLR le_s21 => not_s1x. rewrite -ltnNge (@uniq_leq_size (x :: s1)) /= ?not_s1x //. by apply/allP; rewrite /= s2x; apply/allP. Qed. Lemma eq_uniq s1 s2 : size s1 = size s2 -> s1 =i s2 -> uniq s1 = uniq s2. Proof. move=> eq_sz12 eq_s12. by apply/idP/idP=> Us; rewrite (uniq_size_uniq Us) ?eq_sz12 ?eqxx. Qed. Lemma perm_uniq s1 s2 : perm_eq s1 s2 -> uniq s1 = uniq s2. Proof. by move=> eq_s12; apply/eq_uniq; [apply/perm_size | apply/perm_mem]. Qed. Lemma uniq_perm s1 s2 : uniq s1 -> uniq s2 -> s1 =i s2 -> perm_eq s1 s2. Proof. move=> Us1 Us2 eq12; apply/allP=> x _; apply/eqP. by rewrite !count_uniq_mem ?eq12. Qed. Lemma perm_undup s1 s2 : s1 =i s2 -> perm_eq (undup s1) (undup s2). Proof. by move=> Es12; rewrite uniq_perm ?undup_uniq // => s; rewrite !mem_undup. Qed. Lemma count_mem_uniq s : (forall x, count_mem x s = (x \in s)) -> uniq s. Proof. move=> count1_s; have Uus := undup_uniq s. suffices: perm_eq s (undup s) by move/perm_uniq->. by apply/allP=> x _; apply/eqP; rewrite (count_uniq_mem x Uus) mem_undup. Qed. Lemma eq_count_undup a s1 s2 : {in a, s1 =i s2} -> count a (undup s1) = count a (undup s2). Proof. move=> s1_eq_s2; rewrite -!size_filter !filter_undup. apply/perm_size/perm_undup => x. by rewrite !mem_filter; case: (boolP (a x)) => //= /s1_eq_s2. Qed. Lemma catCA_perm_ind P : (forall s1 s2 s3, P (s1 ++ s2 ++ s3) -> P (s2 ++ s1 ++ s3)) -> (forall s1 s2, perm_eq s1 s2 -> P s1 -> P s2). Proof. move=> PcatCA s1 s2 eq_s12; rewrite -[s1]cats0 -[s2]cats0. elim: s2 nil => [|x s2 IHs] s3 in s1 eq_s12 *. by case: s1 {eq_s12}(perm_size eq_s12). have /rot_to[i s' def_s1]: x \in s1 by rewrite (perm_mem eq_s12) mem_head. rewrite -(cat_take_drop i s1) -catA => /PcatCA. rewrite catA -/(rot i s1) def_s1 /= -cat1s => /PcatCA/IHs/PcatCA; apply. by rewrite -(perm_cons x) -def_s1 perm_rot. Qed. Lemma catCA_perm_subst R F : (forall s1 s2 s3, F (s1 ++ s2 ++ s3) = F (s2 ++ s1 ++ s3) :> R) -> (forall s1 s2, perm_eq s1 s2 -> F s1 = F s2). Proof. move=> FcatCA s1 s2 /catCA_perm_ind => ind_s12. by apply: (ind_s12 (eq _ \o F)) => //= *; rewrite FcatCA. Qed. End PermSeq. Notation perm_eql s1 s2 := (perm_eq s1 =1 perm_eq s2). Notation perm_eqr s1 s2 := (perm_eq^~ s1 =1 perm_eq^~ s2). Arguments permP {T s1 s2}. Arguments permPl {T s1 s2}. Arguments permPr {T s1 s2}. Prenex Implicits perm_eq. #[global] Hint Resolve perm_refl : core. Section RotrLemmas. Variables (n0 : nat) (T : Type) (T' : eqType). Implicit Types (x : T) (s : seq T). Lemma size_rotr s : size (rotr n0 s) = size s. Proof. by rewrite size_rot. Qed. Lemma mem_rotr (s : seq T') : rotr n0 s =i s. Proof. by move=> x; rewrite mem_rot. Qed. Lemma rotr_size_cat s1 s2 : rotr (size s2) (s1 ++ s2) = s2 ++ s1. Proof. by rewrite /rotr size_cat addnK rot_size_cat. Qed. Lemma rotr1_rcons x s : rotr 1 (rcons s x) = x :: s. Proof. by rewrite -rot1_cons rotK. Qed. Lemma has_rotr a s : has a (rotr n0 s) = has a s. Proof. by rewrite has_rot. Qed. Lemma rotr_uniq (s : seq T') : uniq (rotr n0 s) = uniq s. Proof. by rewrite rot_uniq. Qed. Lemma rotrK : cancel (@rotr T n0) (rot n0). Proof. move=> s; have [lt_n0s | ge_n0s] := ltnP n0 (size s). by rewrite -{1}(subKn (ltnW lt_n0s)) -{1}[size s]size_rotr; apply: rotK. by rewrite -[in RHS](rot_oversize ge_n0s) /rotr (eqnP ge_n0s) rot0. Qed. Lemma rotr_inj : injective (@rotr T n0). Proof. exact (can_inj rotrK). Qed. Lemma take_rev s : take n0 (rev s) = rev (drop (size s - n0) s). Proof. set m := _ - n0; rewrite -[s in LHS](cat_take_drop m) rev_cat take_cat. rewrite size_rev size_drop -minnE minnC leq_min ltnn /m. by have [_|/eqnP->] := ltnP; rewrite ?subnn take0 cats0. Qed. Lemma rev_take s : rev (take n0 s) = drop (size s - n0) (rev s). Proof. by rewrite -[s in take _ s]revK take_rev revK size_rev. Qed. Lemma drop_rev s : drop n0 (rev s) = rev (take (size s - n0) s). Proof. set m := _ - n0; rewrite -[s in LHS](cat_take_drop m) rev_cat drop_cat. rewrite size_rev size_drop -minnE minnC leq_min ltnn /m. by have [_|/eqnP->] := ltnP; rewrite ?take0 // subnn drop0. Qed. Lemma rev_drop s : rev (drop n0 s) = take (size s - n0) (rev s). Proof. by rewrite -[s in drop _ s]revK drop_rev revK size_rev. Qed. Lemma rev_rotr s : rev (rotr n0 s) = rot n0 (rev s). Proof. by rewrite rev_cat -take_rev -drop_rev. Qed. Lemma rev_rot s : rev (rot n0 s) = rotr n0 (rev s). Proof. by apply: canLR revK _; rewrite rev_rotr revK. Qed. End RotrLemmas. Arguments rotrK n0 {T} s : rename. Arguments rotr_inj {n0 T} [s1 s2] eq_rotr_s12 : rename. Section RotCompLemmas. Variable T : Type. Implicit Type s : seq T. Lemma rotD m n s : m + n <= size s -> rot (m + n) s = rot m (rot n s). Proof. move=> sz_s; rewrite [LHS]/rot -[take _ s](cat_take_drop n). rewrite 5!(catA, =^~ rot_size_cat) !cat_take_drop. by rewrite size_drop !size_takel ?leq_addl ?addnK. Qed. Lemma rotS n s : n < size s -> rot n.+1 s = rot 1 (rot n s). Proof. exact: (@rotD 1). Qed. Lemma rot_add_mod m n s : n <= size s -> m <= size s -> rot m (rot n s) = rot (if m + n <= size s then m + n else m + n - size s) s. Proof. move=> Hn Hm; case: leqP => [/rotD // | /ltnW Hmn]; symmetry. by rewrite -{2}(rotK n s) /rotr -rotD size_rot addnBA ?subnK ?addnK. Qed. Lemma rot_minn n s : rot n s = rot (minn n (size s)) s. Proof. by case: (leqP n (size s)) => // /leqW ?; rewrite rot_size rot_oversize. Qed. Definition rot_add s n m (k := size s) (p := minn m k + minn n k) := locked (if p <= k then p else p - k). Lemma leq_rot_add n m s : rot_add s n m <= size s. Proof. by unlock rot_add; case: ifP; rewrite // leq_subLR leq_add // geq_minr. Qed. Lemma rot_addC n m s : rot_add s n m = rot_add s m n. Proof. by unlock rot_add; rewrite ![minn n _ + _]addnC. Qed. Lemma rot_rot_add n m s : rot m (rot n s) = rot (rot_add s n m) s. Proof. unlock rot_add. by rewrite (rot_minn n) (rot_minn m) rot_add_mod ?size_rot ?geq_minr. Qed. Lemma rot_rot m n s : rot m (rot n s) = rot n (rot m s). Proof. by rewrite rot_rot_add rot_addC -rot_rot_add. Qed. Lemma rot_rotr m n s : rot m (rotr n s) = rotr n (rot m s). Proof. by rewrite [RHS]/rotr size_rot rot_rot. Qed. Lemma rotr_rotr m n s : rotr m (rotr n s) = rotr n (rotr m s). Proof. by rewrite /rotr !size_rot rot_rot. Qed. End RotCompLemmas. Section Mask. Variables (n0 : nat) (T : Type). Implicit Types (m : bitseq) (s : seq T). Fixpoint mask m s {struct m} := match m, s with | b :: m', x :: s' => if b then x :: mask m' s' else mask m' s' | _, _ => [::] end. Lemma mask_false s n : mask (nseq n false) s = [::]. Proof. by elim: s n => [|x s IHs] [|n] /=. Qed. Lemma mask_true s n : size s <= n -> mask (nseq n true) s = s. Proof. by elim: s n => [|x s IHs] [|n] //= Hn; congr (_ :: _); apply: IHs. Qed. Lemma mask0 m : mask m [::] = [::]. Proof. by case: m. Qed. Lemma mask0s s : mask [::] s = [::]. Proof. by []. Qed. Lemma mask1 b x : mask [:: b] [:: x] = nseq b x. Proof. by case: b. Qed. Lemma mask_cons b m x s : mask (b :: m) (x :: s) = nseq b x ++ mask m s. Proof. by case: b. Qed. Lemma size_mask m s : size m = size s -> size (mask m s) = count id m. Proof. by move: m s; apply: seq_ind2 => // -[] x m s /= _ ->. Qed. Lemma mask_cat m1 m2 s1 s2 : size m1 = size s1 -> mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2. Proof. by move: m1 s1; apply: seq_ind2 => // -[] m1 x1 s1 /= _ ->. Qed. Lemma mask_rcons b m x s : size m = size s -> mask (rcons m b) (rcons s x) = mask m s ++ nseq b x. Proof. by move=> ms; rewrite -!cats1 mask_cat//; case: b. Qed. Lemma all_mask a m s : all a s -> all a (mask m s). Proof. by elim: s m => [|x s IHs] [|[] m]//= /andP[ax /IHs->]; rewrite ?ax. Qed. Lemma has_mask_cons a b m x s : has a (mask (b :: m) (x :: s)) = b && a x || has a (mask m s). Proof. by case: b. Qed. Lemma has_mask a m s : has a (mask m s) -> has a s. Proof. by apply/contraTT; rewrite -!all_predC; apply: all_mask. Qed. Lemma rev_mask m s : size m = size s -> rev (mask m s) = mask (rev m) (rev s). Proof. move: m s; apply: seq_ind2 => //= b x m s eq_size_sm IH. by case: b; rewrite !rev_cons mask_rcons ?IH ?size_rev// (cats1, cats0). Qed. Lemma mask_rot m s : size m = size s -> mask (rot n0 m) (rot n0 s) = rot (count id (take n0 m)) (mask m s). Proof. move=> Ems; rewrite mask_cat ?size_drop ?Ems // -rot_size_cat. by rewrite size_mask -?mask_cat ?size_take ?Ems // !cat_take_drop. Qed. Lemma resize_mask m s : {m1 | size m1 = size s & mask m s = mask m1 s}. Proof. exists (take (size s) m ++ nseq (size s - size m) false). by elim: s m => [|x s IHs] [|b m] //=; rewrite (size_nseq, IHs). by elim: s m => [|x s IHs] [|b m] //=; rewrite (mask_false, IHs). Qed. Lemma takeEmask i s : take i s = mask (nseq i true) s. Proof. by elim: i s => [s|i IHi []// ? ?]; rewrite ?take0 //= IHi. Qed. Lemma dropEmask i s : drop i s = mask (nseq i false ++ nseq (size s - i) true) s. Proof. by elim: i s => [s|? ? []//]; rewrite drop0/= mask_true// subn0. Qed. End Mask. Arguments mask _ !_ !_. Section EqMask. Variables (n0 : nat) (T : eqType). Implicit Types (s : seq T) (m : bitseq). Lemma mem_mask_cons x b m y s : (x \in mask (b :: m) (y :: s)) = b && (x == y) || (x \in mask m s). Proof. by case: b. Qed. Lemma mem_mask x m s : x \in mask m s -> x \in s. Proof. by rewrite -!has_pred1 => /has_mask. Qed. Lemma in_mask x m s : uniq s -> x \in mask m s = (x \in s) && nth false m (index x s). Proof. elim: s m => [|y s IHs] [|[] m]//= /andP[yNs ?]; rewrite ?in_cons ?IHs //=; by have [->|neq_xy] //= := eqVneq; rewrite ?andbF // (negPf yNs). Qed. Lemma mask_uniq s : uniq s -> forall m, uniq (mask m s). Proof. elim: s => [|x s IHs] Uxs [|b m] //=. case: b Uxs => //= /andP[s'x Us]; rewrite {}IHs // andbT. by apply: contra s'x; apply: mem_mask. Qed. Lemma mem_mask_rot m s : size m = size s -> mask (rot n0 m) (rot n0 s) =i mask m s. Proof. by move=> Ems x; rewrite mask_rot // mem_rot. Qed. End EqMask. Section Subseq. Variable T : eqType. Implicit Type s : seq T. Fixpoint subseq s1 s2 := if s2 is y :: s2' then if s1 is x :: s1' then subseq (if x == y then s1' else s1) s2' else true else s1 == [::]. Lemma sub0seq s : subseq [::] s. Proof. by case: s. Qed. Lemma subseq0 s : subseq s [::] = (s == [::]). Proof. by []. Qed. Lemma subseq_refl s : subseq s s. Proof. by elim: s => //= x s IHs; rewrite eqxx. Qed. Hint Resolve subseq_refl : core. Lemma subseqP s1 s2 : reflect (exists2 m, size m = size s2 & s1 = mask m s2) (subseq s1 s2). Proof. elim: s2 s1 => [|y s2 IHs2] [|x s1]. - by left; exists [::]. - by right=> -[m /eqP/nilP->]. - by left; exists (nseq (size s2).+1 false); rewrite ?size_nseq //= mask_false. apply: {IHs2}(iffP (IHs2 _)) => [] [m sz_m def_s1]. by exists ((x == y) :: m); rewrite /= ?sz_m // -def_s1; case: eqP => // ->. case: eqP => [_ | ne_xy]; last first. by case: m def_s1 sz_m => [|[] m] //; [case | move=> -> [<-]; exists m]. pose i := index true m; have def_m_i: take i m = nseq (size (take i m)) false. apply/all_pred1P; apply/(all_nthP true) => j. rewrite size_take ltnNge geq_min negb_or -ltnNge => /andP[lt_j_i _]. rewrite nth_take //= -negb_add addbF -addbT -negb_eqb. by rewrite [_ == _](before_find _ lt_j_i). have lt_i_m: i < size m. rewrite ltnNge; apply/negP=> le_m_i; rewrite take_oversize // in def_m_i. by rewrite def_m_i mask_false in def_s1. rewrite size_take lt_i_m in def_m_i. exists (take i m ++ drop i.+1 m). rewrite size_cat size_take size_drop lt_i_m. by rewrite sz_m in lt_i_m *; rewrite subnKC. rewrite {s1 def_s1}[s1](congr1 behead def_s1). rewrite -[s2](cat_take_drop i) -[m in LHS](cat_take_drop i) {}def_m_i -cat_cons. have sz_i_s2: size (take i s2) = i by apply: size_takel; rewrite sz_m in lt_i_m. rewrite lastI cat_rcons !mask_cat ?size_nseq ?size_belast ?mask_false //=. by rewrite (drop_nth true) // nth_index -?index_mem. Qed. Lemma mask_subseq m s : subseq (mask m s) s. Proof. by apply/subseqP; have [m1] := resize_mask m s; exists m1. Qed. Lemma subseq_trans : transitive subseq. Proof. move=> _ _ s /subseqP[m2 _ ->] /subseqP[m1 _ ->]. elim: s => [|x s IHs] in m2 m1 *; first by rewrite !mask0. case: m1 => [|[] m1]; first by rewrite mask0. case: m2 => [|[] m2] //; first by rewrite /= eqxx IHs. case/subseqP: (IHs m2 m1) => m sz_m def_s; apply/subseqP. by exists (false :: m); rewrite //= sz_m. case/subseqP: (IHs m2 m1) => m sz_m def_s; apply/subseqP. by exists (false :: m); rewrite //= sz_m. Qed. Lemma cat_subseq s1 s2 s3 s4 : subseq s1 s3 -> subseq s2 s4 -> subseq (s1 ++ s2) (s3 ++ s4). Proof. case/subseqP=> m1 sz_m1 -> /subseqP [m2 sz_m2 ->]; apply/subseqP. by exists (m1 ++ m2); rewrite ?size_cat ?mask_cat ?sz_m1 ?sz_m2. Qed. Lemma prefix_subseq s1 s2 : subseq s1 (s1 ++ s2). Proof. by rewrite -[s1 in subseq s1]cats0 cat_subseq ?sub0seq. Qed. Lemma suffix_subseq s1 s2 : subseq s2 (s1 ++ s2). Proof. exact: cat_subseq (sub0seq s1) _. Qed. Lemma take_subseq s i : subseq (take i s) s. Proof. by rewrite -[s in X in subseq _ X](cat_take_drop i) prefix_subseq. Qed. Lemma drop_subseq s i : subseq (drop i s) s. Proof. by rewrite -[s in X in subseq _ X](cat_take_drop i) suffix_subseq. Qed. Lemma mem_subseq s1 s2 : subseq s1 s2 -> {subset s1 <= s2}. Proof. by case/subseqP=> m _ -> x; apply: mem_mask. Qed. Lemma sub1seq x s : subseq [:: x] s = (x \in s). Proof. by elim: s => //= y s /[1!inE]; case: ifP; rewrite ?sub0seq. Qed. Lemma size_subseq s1 s2 : subseq s1 s2 -> size s1 <= size s2. Proof. by case/subseqP=> m sz_m ->; rewrite size_mask -sz_m ?count_size. Qed. Lemma size_subseq_leqif s1 s2 : subseq s1 s2 -> size s1 <= size s2 ?= iff (s1 == s2). Proof. move=> sub12; split; first exact: size_subseq. apply/idP/eqP=> [|-> //]; case/subseqP: sub12 => m sz_m ->{s1}. rewrite size_mask -sz_m // -all_count -(eq_all eqb_id). by move/(@all_pred1P _ true)->; rewrite sz_m mask_true. Qed. Lemma subseq_anti : antisymmetric subseq. Proof. move=> s1 s2 /andP[] /size_subseq_leqif /leqifP. by case: eqP => [//|_] + /size_subseq; rewrite ltnNge => /negP. Qed. Lemma subseq_cons s x : subseq s (x :: s). Proof. exact: suffix_subseq [:: x] s. Qed. Lemma cons_subseq s1 s2 x : subseq (x :: s1) s2 -> subseq s1 s2. Proof. exact/subseq_trans/subseq_cons. Qed. Lemma subseq_rcons s x : subseq s (rcons s x). Proof. by rewrite -cats1 prefix_subseq. Qed. Lemma subseq_uniq s1 s2 : subseq s1 s2 -> uniq s2 -> uniq s1. Proof. by case/subseqP=> m _ -> Us2; apply: mask_uniq. Qed. Lemma take_uniq s n : uniq s -> uniq (take n s). Proof. exact/subseq_uniq/take_subseq. Qed. Lemma drop_uniq s n : uniq s -> uniq (drop n s). Proof. exact/subseq_uniq/drop_subseq. Qed. Lemma undup_subseq s : subseq (undup s) s. Proof. elim: s => //= x s; case: (_ \in _); last by rewrite eqxx. by case: (undup s) => //= y u; case: (_ == _) => //=; apply: cons_subseq. Qed. Lemma subseq_rev s1 s2 : subseq (rev s1) (rev s2) = subseq s1 s2. Proof. wlog suff W : s1 s2 / subseq s1 s2 -> subseq (rev s1) (rev s2). by apply/idP/idP => /W //; rewrite !revK. by case/subseqP => m size_m ->; rewrite rev_mask // mask_subseq. Qed. Lemma subseq_cat2l s s1 s2 : subseq (s ++ s1) (s ++ s2) = subseq s1 s2. Proof. by elim: s => // x s IHs; rewrite !cat_cons /= eqxx. Qed. Lemma subseq_cat2r s s1 s2 : subseq (s1 ++ s) (s2 ++ s) = subseq s1 s2. Proof. by rewrite -subseq_rev !rev_cat subseq_cat2l subseq_rev. Qed. Lemma subseq_rot p s n : subseq p s -> exists2 k, k <= n & subseq (rot k p) (rot n s). Proof. move=> /subseqP[m size_m ->]. exists (count id (take n m)); last by rewrite -mask_rot // mask_subseq. by rewrite (leq_trans (count_size _ _))// size_take_min geq_minl. Qed. End Subseq. Prenex Implicits subseq. Arguments subseqP {T s1 s2}. #[global] Hint Resolve subseq_refl : core. Section Rem. Variables (T : eqType) (x : T). Fixpoint rem s := if s is y :: t then (if y == x then t else y :: rem t) else s. Lemma rem_cons y s : rem (y :: s) = if y == x then s else y :: rem s. Proof. by []. Qed. Lemma remE s : rem s = take (index x s) s ++ drop (index x s).+1 s. Proof. by elim: s => //= y s ->; case: eqVneq; rewrite ?drop0. Qed. Lemma rem_id s : x \notin s -> rem s = s. Proof. by elim: s => //= y s IHs /norP[neq_yx /IHs->]; case: eqVneq neq_yx. Qed. Lemma perm_to_rem s : x \in s -> perm_eq s (x :: rem s). Proof. move=> xs; rewrite remE -[X in perm_eq X](cat_take_drop (index x s)). by rewrite drop_index// -cat1s perm_catCA cat1s. Qed. Lemma size_rem s : x \in s -> size (rem s) = (size s).-1. Proof. by move/perm_to_rem/perm_size->. Qed. Lemma rem_subseq s : subseq (rem s) s. Proof. elim: s => //= y s IHs; rewrite eq_sym. by case: ifP => _; [apply: subseq_cons | rewrite eqxx]. Qed. Lemma rem_uniq s : uniq s -> uniq (rem s). Proof. by apply: subseq_uniq; apply: rem_subseq. Qed. Lemma mem_rem s : {subset rem s <= s}. Proof. exact: mem_subseq (rem_subseq s). Qed. Lemma rem_mem y s : y != x -> y \in s -> y \in rem s. Proof. move=> yx; elim: s => [//|z s IHs] /=. rewrite inE => /orP[/eqP<-|ys]; first by rewrite (negbTE yx) inE eqxx. by case: ifP => _ //; rewrite inE IHs ?orbT. Qed. Lemma rem_filter s : uniq s -> rem s = filter (predC1 x) s. Proof. elim: s => //= y s IHs /andP[not_s_y /IHs->]. by case: eqP => //= <-; apply/esym/all_filterP; rewrite all_predC has_pred1. Qed. Lemma mem_rem_uniq s : uniq s -> rem s =i [predD1 s & x]. Proof. by move/rem_filter=> -> y; rewrite mem_filter. Qed. Lemma mem_rem_uniqF s : uniq s -> x \in rem s = false. Proof. by move/mem_rem_uniq->; rewrite inE eqxx. Qed. Lemma count_rem P s : count P (rem s) = count P s - (x \in s) && P x. Proof. have [/perm_to_rem/permP->|xNs]/= := boolP (x \in s); first by rewrite addKn. by rewrite subn0 rem_id. Qed. Lemma count_mem_rem y s : count_mem y (rem s) = count_mem y s - (x == y). Proof. rewrite count_rem; have []//= := boolP (x \in s). by case: eqP => // <- /count_memPn->. Qed. End Rem. Section Map. Variables (n0 : nat) (T1 : Type) (x1 : T1). Variables (T2 : Type) (x2 : T2) (f : T1 -> T2). Fixpoint map s := if s is x :: s' then f x :: map s' else [::]. Lemma map_cons x s : map (x :: s) = f x :: map s. Proof. by []. Qed. Lemma map_nseq x : map (nseq n0 x) = nseq n0 (f x). Proof. by elim: n0 => // *; congr (_ :: _). Qed. Lemma map_cat s1 s2 : map (s1 ++ s2) = map s1 ++ map s2. Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs. Qed. Lemma size_map s : size (map s) = size s. Proof. by elim: s => //= x s ->. Qed. Lemma behead_map s : behead (map s) = map (behead s). Proof. by case: s. Qed. Lemma nth_map n s : n < size s -> nth x2 (map s) n = f (nth x1 s n). Proof. by elim: s n => [|x s IHs] []. Qed. Lemma map_rcons s x : map (rcons s x) = rcons (map s) (f x). Proof. by rewrite -!cats1 map_cat. Qed. Lemma last_map s x : last (f x) (map s) = f (last x s). Proof. by elim: s x => /=. Qed. Lemma belast_map s x : belast (f x) (map s) = map (belast x s). Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed. Lemma filter_map a s : filter a (map s) = map (filter (preim f a) s). Proof. by elim: s => //= x s IHs; rewrite (fun_if map) /= IHs. Qed. Lemma find_map a s : find a (map s) = find (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma has_map a s : has a (map s) = has (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma all_map a s : all a (map s) = all (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma all_mapT (a : pred T2) s : (forall x, a (f x)) -> all a (map s). Proof. by rewrite all_map => /allT->. Qed. Lemma count_map a s : count a (map s) = count (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma map_take s : map (take n0 s) = take n0 (map s). Proof. by elim: n0 s => [|n IHn] [|x s] //=; rewrite IHn. Qed. Lemma map_drop s : map (drop n0 s) = drop n0 (map s). Proof. by elim: n0 s => [|n IHn] [|x s] //=; rewrite IHn. Qed. Lemma map_rot s : map (rot n0 s) = rot n0 (map s). Proof. by rewrite /rot map_cat map_take map_drop. Qed. Lemma map_rotr s : map (rotr n0 s) = rotr n0 (map s). Proof. by apply: canRL (rotK n0) _; rewrite -map_rot rotrK. Qed. Lemma map_rev s : map (rev s) = rev (map s). Proof. by elim: s => //= x s IHs; rewrite !rev_cons -!cats1 map_cat IHs. Qed. Lemma map_mask m s : map (mask m s) = mask m (map s). Proof. by elim: m s => [|[|] m IHm] [|x p] //=; rewrite IHm. Qed. Lemma inj_map : injective f -> injective map. Proof. by move=> injf; elim=> [|x s IHs] [|y t] //= [/injf-> /IHs->]. Qed. Lemma inj_in_map (A : {pred T1}) : {in A &, injective f} -> {in [pred s | all [in A] s] &, injective map}. Proof. move=> injf; elim=> [|x s IHs] [|y t] //= /andP[Ax As] /andP[Ay At]. by case=> /injf-> // /IHs->. Qed. End Map. (* Sequence indexing with error. *) Section onth. Variable T : Type. Implicit Types x y z : T. Implicit Types m n : nat. Implicit Type s : seq T. Fixpoint onth s n {struct n} : option T := if s isn't x :: s then None else if n isn't n.+1 then Some x else onth s n. Lemma odflt_onth x0 s n : odflt x0 (onth s n) = nth x0 s n. Proof. by elim: n s => [|? ?] []. Qed. Lemma onthE s : onth s =1 nth None (map Some s). Proof. by move=> n; elim: n s => [|? ?] []. Qed. Lemma onth_nth x0 x t n : onth t n = Some x -> nth x0 t n = x. Proof. by move=> tn; rewrite -odflt_onth tn. Qed. Lemma onth0n n : onth [::] n = None. Proof. by case: n. Qed. Lemma onth1P x y n : onth [:: x] n = Some y <-> n = 0 /\ x = y. Proof. by case: n => [|[]]; split=> // -[] // _ ->. Qed. Lemma onthTE s n : onth s n = (n < size s) :> bool. Proof. by elim: n s => [|? ?] []. Qed. Lemma onthNE s n: ~~ onth s n = (size s <= n). Proof. by rewrite onthTE -leqNgt. Qed. Lemma onth_default n s : size s <= n -> onth s n = None. Proof. by rewrite -onthNE; case: onth. Qed. Lemma onth_cat s1 s2 n : onth (s1 ++ s2) n = if n < size s1 then onth s1 n else onth s2 (n - size s1). Proof. by elim: n s1 => [|? ?] []. Qed. Lemma onth_nseq x n m : onth (nseq n x) m = if m < n then Some x else None. Proof. by rewrite onthE/= -nth_nseq map_nseq. Qed. Lemma eq_onthP {s1 s2} : [<-> s1 = s2; forall i : nat, i < maxn (size s1) (size s2) -> onth s1 i = onth s2 i; forall i : nat, onth s1 i = onth s2 i]. Proof. tfae=> [->//|eqs12 i|eqs12]. have := eqs12 i; case: ltnP => [_ ->//|]. by rewrite geq_max => /andP[is1 is2] _; rewrite !onth_default. have /eqP eq_size_12 : size s1 == size s2. by rewrite eqn_leq -!onthNE eqs12 onthNE -eqs12 onthNE !leqnn. apply/(inj_map Some_inj)/(@eq_from_nth _ None); rewrite !size_map//. by move=> i _; rewrite -!onthE eqs12. Qed. Lemma eq_from_onth [s1 s2 : seq T] : (forall i : nat, onth s1 i = onth s2 i) -> s1 = s2. Proof. by move/(eq_onthP 0 2). Qed. Lemma eq_from_onth_le [s1 s2 : seq T] : (forall i : nat, i < maxn (size s1) (size s2) -> onth s1 i = onth s2 i) -> s1 = s2. Proof. by move/(eq_onthP 0 1). Qed. End onth. Lemma onth_map {T S} n (s : seq T) (f : T -> S) : onth (map f s) n = omap f (onth s n). Proof. by elim: s n => [|x s IHs] []. Qed. Lemma inj_onth_map {T S} n (s : seq T) (f : T -> S) x : injective f -> onth (map f s) n = Some (f x) -> onth s n = Some x. Proof. by rewrite onth_map => /inj_omap + fs; apply. Qed. Section onthEqType. Variables T : eqType. Implicit Types x y z : T. Implicit Types i m n : nat. Implicit Type s : seq T. Lemma onthP s x : reflect (exists i, onth s i = Some x) (x \in s). Proof. elim: s => [|y s IHs]; first by constructor=> -[] []. rewrite in_cons; case: eqVneq => [->|/= Nxy]; first by constructor; exists 0. apply: (iffP idP) => [/IHs[i <-]|[[|i]//=]]; first by exists i.+1. by move=> [eq_xy]; rewrite eq_xy eqxx in Nxy. by move=> six; apply/IHs; exists i. Qed. Lemma onthPn s x : reflect (forall i, onth s i != Some x) (x \notin s). Proof. apply: (iffP idP); first by move=> /onthP + i; apply: contra_not_neq; exists i. by move=> nsix; apply/onthP => -[n /eqP/negPn]; rewrite nsix. Qed. Lemma onth_inj s n m : uniq s -> minn m n < size s -> onth s n = onth s m -> n = m. Proof. elim: s m n => [|x s IHs]//= [|m] [|n]//=; rewrite ?minnSS !ltnS. - by move=> /andP[+ _] _ /eqP => /onthPn/(_ _)/negPf->. - by move=> /andP[+ _] _ /esym /eqP => /onthPn/(_ _)/negPf->. by move=> /andP[xNs /IHs]/[apply]/[apply]->. Qed. End onthEqType. Arguments onthP {T s x}. Arguments onthPn {T s x}. Arguments onth_nth {T}. Arguments onth_inj {T}. Notation "[ 'seq' E | i <- s ]" := (map (fun i => E) s) (i binder, format "[ '[hv' 'seq' E '/ ' | i <- s ] ']'") : seq_scope. Notation "[ 'seq' E | i <- s & C ]" := [seq E | i <- [seq i <- s | C]] (i binder, format "[ '[hv' 'seq' E '/ ' | i <- s '/ ' & C ] ']'") : seq_scope. Notation "[ 'seq' E : R | i <- s ]" := (@map _ R (fun i => E) s) (i binder, only parsing) : seq_scope. Notation "[ 'seq' E : R | i <- s & C ]" := [seq E : R | i <- [seq i <- s | C]] (i binder, only parsing) : seq_scope. Lemma filter_mask T a (s : seq T) : filter a s = mask (map a s) s. Proof. by elim: s => //= x s <-; case: (a x). Qed. Lemma all_sigP T a (s : seq T) : all a s -> {s' : seq (sig a) | s = map sval s'}. Proof. elim: s => /= [_|x s ihs /andP [ax /ihs [s' ->]]]; first by exists [::]. by exists (exist a x ax :: s'). Qed. Section MiscMask. Lemma leq_count_mask T (P : {pred T}) m s : count P (mask m s) <= count P s. Proof. by elim: s m => [|x s IHs] [|[] m]//=; rewrite ?leq_add2l (leq_trans (IHs _)) ?leq_addl. Qed. Variable (T : eqType). Implicit Types (s : seq T) (m : bitseq). Lemma mask_filter s m : uniq s -> mask m s = [seq i <- s | i \in mask m s]. Proof. elim: m s => [|[] m IH] [|x s /= /andP[/negP xS uS]]; rewrite ?filter_pred0 //. rewrite inE eqxx /=; congr cons; rewrite [LHS]IH//. by apply/eq_in_filter => ? /[1!inE]; case: eqP => [->|]. by case: ifP => [/mem_mask //|_]; apply: IH. Qed. Lemma leq_count_subseq P s1 s2 : subseq s1 s2 -> count P s1 <= count P s2. Proof. by move=> /subseqP[m _ ->]; rewrite leq_count_mask. Qed. Lemma count_maskP s1 s2 : (forall x, count_mem x s1 <= count_mem x s2) <-> exists2 m : bitseq, size m = size s2 & perm_eq s1 (mask m s2). Proof. split=> [s1_le|[m _ /permP s1ms2 x]]; last by rewrite s1ms2 leq_count_mask. suff [m mP]: exists m, perm_eq s1 (mask m s2). by have [m' sm' eqm] := resize_mask m s2; exists m'; rewrite -?eqm. elim: s2 => [|x s2 IHs]//= in s1 s1_le *. by exists [::]; apply/allP => x _/=; rewrite eqn_leq s1_le. have [y|m s1s2] := IHs (rem x s1); first by rewrite count_mem_rem leq_subLR. exists ((x \in s1) :: m); have [|/rem_id<-//] := boolP (x \in s1). by move/perm_to_rem/permPl->; rewrite perm_cons. Qed. Lemma count_subseqP s1 s2 : (forall x, count_mem x s1 <= count_mem x s2) <-> exists2 s, subseq s s2 & perm_eq s1 s. Proof. split=> [/count_maskP[m _]|]; first by exists (mask m s2); rewrite ?mask_subseq. by move=> -[_/subseqP[m sm ->] ?]; apply/count_maskP; exists m. Qed. End MiscMask. Section FilterSubseq. Variable T : eqType. Implicit Types (s : seq T) (a : pred T). Lemma filter_subseq a s : subseq (filter a s) s. Proof. by apply/subseqP; exists (map a s); rewrite ?size_map ?filter_mask. Qed. Lemma subseq_filter s1 s2 a : subseq s1 (filter a s2) = all a s1 && subseq s1 s2. Proof. elim: s2 s1 => [|x s2 IHs] [|y s1] //=; rewrite ?andbF ?sub0seq //. by case a_x: (a x); rewrite /= !IHs /=; case: eqP => // ->; rewrite a_x. Qed. Lemma subseq_uniqP s1 s2 : uniq s2 -> reflect (s1 = filter [in s1] s2) (subseq s1 s2). Proof. move=> uniq_s2; apply: (iffP idP) => [ss12 | ->]; last exact: filter_subseq. apply/eqP; rewrite -size_subseq_leqif ?subseq_filter ?(introT allP) //. apply/eqP/esym/perm_size. rewrite uniq_perm ?filter_uniq ?(subseq_uniq ss12) // => x. by rewrite mem_filter; apply: andb_idr; apply: (mem_subseq ss12). Qed. Lemma uniq_subseq_pivot x (s1 s2 s3 s4 : seq T) (s := s3 ++ x :: s4) : uniq s -> subseq (s1 ++ x :: s2) s = (subseq s1 s3 && subseq s2 s4). Proof. move=> uniq_s; apply/idP/idP => [sub_s'_s|/andP[? ?]]; last first. by rewrite cat_subseq //= eqxx. have uniq_s' := subseq_uniq sub_s'_s uniq_s. have/eqP {sub_s'_s uniq_s} := subseq_uniqP _ uniq_s sub_s'_s. rewrite !filter_cat /= mem_cat inE eqxx orbT /=. rewrite uniq_eqseq_pivotl // => /andP [/eqP -> /eqP ->]. by rewrite !filter_subseq. Qed. Lemma perm_to_subseq s1 s2 : subseq s1 s2 -> {s3 | perm_eq s2 (s1 ++ s3)}. Proof. elim Ds2: s2 s1 => [|y s2' IHs] [|x s1] //=; try by exists s2; rewrite Ds2. case: eqP => [-> | _] /IHs[s3 perm_s2] {IHs}. by exists s3; rewrite perm_cons. by exists (rcons s3 y); rewrite -cat_cons -perm_rcons -!cats1 catA perm_cat2r. Qed. Lemma subseq_rem x : {homo rem x : s1 s2 / @subseq T s1 s2}. Proof. move=> s1 s2; elim: s2 s1 => [|x2 s2 IHs2] [|x1 s1]; rewrite ?sub0seq //=. have [->|_] := eqVneq x1 x2; first by case: eqP => //= _ /IHs2; rewrite eqxx. move=> /IHs2/subseq_trans->//. by have [->|_] := eqVneq x x2; [apply: rem_subseq|apply: subseq_cons]. Qed. End FilterSubseq. Arguments subseq_uniqP [T s1 s2]. Section EqMap. Variables (n0 : nat) (T1 : eqType) (x1 : T1). Variables (T2 : eqType) (x2 : T2) (f : T1 -> T2). Implicit Type s : seq T1. Lemma map_f s x : x \in s -> f x \in map f s. Proof. by elim: s => //= y s IHs /predU1P[->|/IHs]; [apply: predU1l | apply: predU1r]. Qed. Lemma mapP s y : reflect (exists2 x, x \in s & y = f x) (y \in map f s). Proof. elim: s => [|x s IHs]; [by right; case|rewrite /= inE]. exact: equivP (orPP eqP IHs) (iff_sym exists_cons). Qed. Lemma subset_mapP (s : seq T1) (s' : seq T2) : {subset s' <= map f s} <-> exists2 t, all (mem s) t & s' = map f t. Proof. split => [|[r /allP/= rE ->] _ /mapP[x xr ->]]; last by rewrite map_f ?rE. elim: s' => [|x s' IHs'] subss'; first by exists [::]. have /mapP[y ys ->] := subss' _ (mem_head _ _). have [x' x's'|t st ->] := IHs'; first by rewrite subss'// inE x's' orbT. by exists (y :: t); rewrite //= ys st. Qed. Lemma map_uniq s : uniq (map f s) -> uniq s. Proof. elim: s => //= x s IHs /andP[not_sfx /IHs->]; rewrite andbT. by apply: contra not_sfx => sx; apply/mapP; exists x. Qed. Lemma map_inj_in_uniq s : {in s &, injective f} -> uniq (map f s) = uniq s. Proof. elim: s => //= x s IHs //= injf; congr (~~ _ && _). apply/mapP/idP=> [[y sy /injf] | ]; last by exists x. by rewrite mem_head mem_behead // => ->. by apply: IHs => y z sy sz; apply: injf => //; apply: predU1r. Qed. Lemma map_subseq s1 s2 : subseq s1 s2 -> subseq (map f s1) (map f s2). Proof. case/subseqP=> m sz_m ->; apply/subseqP. by exists m; rewrite ?size_map ?map_mask. Qed. Lemma nth_index_map s x0 x : {in s &, injective f} -> x \in s -> nth x0 s (index (f x) (map f s)) = x. Proof. elim: s => //= y s IHs inj_f s_x; rewrite (inj_in_eq inj_f) ?mem_head //. move: s_x; rewrite inE; have [-> // | _] := eqVneq; apply: IHs. by apply: sub_in2 inj_f => z; apply: predU1r. Qed. Lemma perm_map s t : perm_eq s t -> perm_eq (map f s) (map f t). Proof. by move/permP=> Est; apply/permP=> a; rewrite !count_map Est. Qed. Lemma sub_map s1 s2 : {subset s1 <= s2} -> {subset map f s1 <= map f s2}. Proof. by move=> sub_s ? /mapP[x x_s ->]; rewrite map_f ?sub_s. Qed. Lemma eq_mem_map s1 s2 : s1 =i s2 -> map f s1 =i map f s2. Proof. by move=> Es x; apply/idP/idP; apply: sub_map => ?; rewrite Es. Qed. Hypothesis Hf : injective f. Lemma mem_map s x : (f x \in map f s) = (x \in s). Proof. by apply/mapP/idP=> [[y Hy /Hf->] //|]; exists x. Qed. Lemma index_map s x : index (f x) (map f s) = index x s. Proof. by rewrite /index; elim: s => //= y s IHs; rewrite (inj_eq Hf) IHs. Qed. Lemma map_inj_uniq s : uniq (map f s) = uniq s. Proof. by apply: map_inj_in_uniq; apply: in2W. Qed. Lemma undup_map_inj s : undup (map f s) = map f (undup s). Proof. by elim: s => //= s0 s ->; rewrite mem_map //; case: (_ \in _). Qed. Lemma perm_map_inj s t : perm_eq (map f s) (map f t) -> perm_eq s t. Proof. move/permP=> Est; apply/allP=> x _ /=. have Dx: pred1 x =1 preim f (pred1 (f x)) by move=> y /=; rewrite inj_eq. by rewrite !(eq_count Dx) -!count_map Est. Qed. End EqMap. Arguments mapP {T1 T2 f s y}. Arguments subset_mapP {T1 T2}. Lemma map_of_seq (T1 : eqType) T2 (s : seq T1) (fs : seq T2) (y0 : T2) : {f | uniq s -> size fs = size s -> map f s = fs}. Proof. exists (fun x => nth y0 fs (index x s)) => uAs eq_sz. apply/esym/(@eq_from_nth _ y0); rewrite ?size_map eq_sz // => i ltis. by have x0 : T1 by [case: (s) ltis]; rewrite (nth_map x0) // index_uniq. Qed. Section MapComp. Variable S T U : Type. Lemma map_id (s : seq T) : map id s = s. Proof. by elim: s => //= x s ->. Qed. Lemma eq_map (f g : S -> T) : f =1 g -> map f =1 map g. Proof. by move=> Ef; elim=> //= x s ->; rewrite Ef. Qed. Lemma map_comp (f : T -> U) (g : S -> T) s : map (f \o g) s = map f (map g s). Proof. by elim: s => //= x s ->. Qed. Lemma mapK (f : S -> T) (g : T -> S) : cancel f g -> cancel (map f) (map g). Proof. by move=> fK; elim=> //= x s ->; rewrite fK. Qed. Lemma mapK_in (A : {pred S}) (f : S -> T) (g : T -> S) : {in A, cancel f g} -> {in [pred s | all [in A] s], cancel (map f) (map g)}. Proof. by move=> fK; elim=> //= x s IHs /andP[/fK-> /IHs->]. Qed. End MapComp. Lemma eq_in_map (S : eqType) T (f g : S -> T) (s : seq S) : {in s, f =1 g} <-> map f s = map g s. Proof. elim: s => //= x s IHs; split=> [/forall_cons[-> ?]|]; first by rewrite IHs.1. by move=> -[? ?]; apply/forall_cons; split=> [//|]; apply: IHs.2. Qed. Lemma map_id_in (T : eqType) f (s : seq T) : {in s, f =1 id} -> map f s = s. Proof. by move/eq_in_map->; apply: map_id. Qed. (* Map a partial function *) Section Pmap. Variables (aT rT : Type) (f : aT -> option rT) (g : rT -> aT). Fixpoint pmap s := if s is x :: s' then let r := pmap s' in oapp (cons^~ r) r (f x) else [::]. Lemma map_pK : pcancel g f -> cancel (map g) pmap. Proof. by move=> gK; elim=> //= x s ->; rewrite gK. Qed. Lemma size_pmap s : size (pmap s) = count [eta f] s. Proof. by elim: s => //= x s <-; case: (f _). Qed. Lemma pmapS_filter s : map some (pmap s) = map f (filter [eta f] s). Proof. by elim: s => //= x s; case fx: (f x) => //= [u] <-; congr (_ :: _). Qed. Hypothesis fK : ocancel f g. Lemma pmap_filter s : map g (pmap s) = filter [eta f] s. Proof. by elim: s => //= x s <-; rewrite -{3}(fK x); case: (f _). Qed. Lemma pmap_cat s t : pmap (s ++ t) = pmap s ++ pmap t. Proof. by elim: s => //= x s ->; case/f: x. Qed. Lemma all_pmap (p : pred rT) s : all p (pmap s) = all [pred i | oapp p true (f i)] s. Proof. by elim: s => //= x s <-; case: f. Qed. End Pmap. Lemma eq_in_pmap (aT : eqType) rT (f1 f2 : aT -> option rT) s : {in s, f1 =1 f2} -> pmap f1 s = pmap f2 s. Proof. by elim: s => //= a s IHs /forall_cons [-> /IHs ->]. Qed. Lemma eq_pmap aT rT (f1 f2 : aT -> option rT) : f1 =1 f2 -> pmap f1 =1 pmap f2. Proof. by move=> Ef; elim => //= a s ->; rewrite Ef. Qed. Section EqPmap. Variables (aT rT : eqType) (f : aT -> option rT) (g : rT -> aT). Lemma mem_pmap s u : (u \in pmap f s) = (Some u \in map f s). Proof. by elim: s => //= x s IHs; rewrite in_cons -IHs; case: (f x). Qed. Hypothesis fK : ocancel f g. Lemma can2_mem_pmap : pcancel g f -> forall s u, (u \in pmap f s) = (g u \in s). Proof. by move=> gK s u; rewrite -(mem_map (pcan_inj gK)) pmap_filter // mem_filter gK. Qed. Lemma pmap_uniq s : uniq s -> uniq (pmap f s). Proof. move/(filter_uniq f); rewrite -(pmap_filter fK); exact: map_uniq. Qed. Lemma perm_pmap s t : perm_eq s t -> perm_eq (pmap f s) (pmap f t). Proof. move=> eq_st; apply/(perm_map_inj Some_inj); rewrite !pmapS_filter. exact/perm_map/perm_filter. Qed. End EqPmap. Section PmapSub. Variables (T : Type) (p : pred T) (sT : subType p). Lemma size_pmap_sub s : size (pmap (insub : T -> option sT) s) = count p s. Proof. by rewrite size_pmap (eq_count (isSome_insub _)). Qed. End PmapSub. Section EqPmapSub. Variables (T : eqType) (p : pred T) (sT : subEqType p). Let insT : T -> option sT := insub. Lemma mem_pmap_sub s u : (u \in pmap insT s) = (val u \in s). Proof. exact/(can2_mem_pmap (insubK _))/valK. Qed. Lemma pmap_sub_uniq s : uniq s -> uniq (pmap insT s). Proof. exact: (pmap_uniq (insubK _)). Qed. End EqPmapSub. (* Index sequence *) Fixpoint iota m n := if n is n'.+1 then m :: iota m.+1 n' else [::]. Lemma size_iota m n : size (iota m n) = n. Proof. by elim: n m => //= n IHn m; rewrite IHn. Qed. Lemma iotaD m n1 n2 : iota m (n1 + n2) = iota m n1 ++ iota (m + n1) n2. Proof. by elim: n1 m => [|n1 IHn1] m; rewrite ?addn0 // -addSnnS /= -IHn1. Qed. Lemma iotaDl m1 m2 n : iota (m1 + m2) n = map (addn m1) (iota m2 n). Proof. by elim: n m2 => //= n IHn m2; rewrite -addnS IHn. Qed. Lemma nth_iota p m n i : i < n -> nth p (iota m n) i = m + i. Proof. by move/subnKC <-; rewrite addSnnS iotaD nth_cat size_iota ltnn subnn. Qed. Lemma mem_iota m n i : (i \in iota m n) = (m <= i < m + n). Proof. elim: n m => [|n IHn] /= m; first by rewrite addn0 ltnNge andbN. by rewrite in_cons IHn addnS ltnS; case: ltngtP => // ->; rewrite leq_addr. Qed. Lemma iota_uniq m n : uniq (iota m n). Proof. by elim: n m => //= n IHn m; rewrite mem_iota ltnn /=. Qed. Lemma take_iota k m n : take k (iota m n) = iota m (minn k n). Proof. have [lt_k_n|le_n_k] := ltnP. by elim: k n lt_k_n m => [|k IHk] [|n] //= H m; rewrite IHk. by apply: take_oversize; rewrite size_iota. Qed. Lemma drop_iota k m n : drop k (iota m n) = iota (m + k) (n - k). Proof. by elim: k m n => [|k IHk] m [|n] //=; rewrite ?addn0 // IHk addnS subSS. Qed. Lemma filter_iota_ltn m n j : j <= n -> [seq i <- iota m n | i < m + j] = iota m j. Proof. elim: n m j => [m j|n IHn m [|j] jlen]; first by rewrite leqn0 => /eqP ->. rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => i. by rewrite addn0 ltnNge mem_iota => /andP[->]. by rewrite /= addnS leq_addr -addSn IHn. Qed. Lemma filter_iota_leq n m j : j < n -> [seq i <- iota m n | i <= m + j] = iota m j.+1. Proof. elim: n m j => [//|n IHn] m [|j] jlen /=; rewrite leq_addr. rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => i. by rewrite addn0 leqNgt mem_iota => /andP[->]. by rewrite addnS -addSn IHn -1?ltnS. Qed. (* Making a sequence of a specific length, using indexes to compute items. *) Section MakeSeq. Variables (T : Type) (x0 : T). Definition mkseq f n : seq T := map f (iota 0 n). Lemma size_mkseq f n : size (mkseq f n) = n. Proof. by rewrite size_map size_iota. Qed. Lemma mkseqS f n : mkseq f n.+1 = rcons (mkseq f n) (f n). Proof. by rewrite /mkseq -addn1 iotaD add0n map_cat cats1. Qed. Lemma eq_mkseq f g : f =1 g -> mkseq f =1 mkseq g. Proof. by move=> Efg n; apply: eq_map Efg _. Qed. Lemma nth_mkseq f n i : i < n -> nth x0 (mkseq f n) i = f i. Proof. by move=> Hi; rewrite (nth_map 0) ?nth_iota ?size_iota. Qed. Lemma mkseq_nth s : mkseq (nth x0 s) (size s) = s. Proof. by apply: (@eq_from_nth _ x0); rewrite size_mkseq // => i Hi; rewrite nth_mkseq. Qed. Variant mkseq_spec s : seq T -> Type := | MapIota n f : s = mkseq f n -> mkseq_spec s (mkseq f n). Lemma mkseqP s : mkseq_spec s s. Proof. by rewrite -[s]mkseq_nth; constructor. Qed. Lemma map_nth_iota0 s i : i <= size s -> [seq nth x0 s j | j <- iota 0 i] = take i s. Proof. by move=> ile; rewrite -[s in RHS]mkseq_nth -map_take take_iota (minn_idPl _). Qed. Lemma map_nth_iota s i j : j <= size s - i -> [seq nth x0 s k | k <- iota i j] = take j (drop i s). Proof. elim: i => [|i IH] in s j *; first by rewrite subn0 drop0 => /map_nth_iota0->. case: s => [|x s /IH<-]; first by rewrite leqn0 => /eqP->. by rewrite -add1n iotaDl -map_comp. Qed. End MakeSeq. Section MakeEqSeq. Variable T : eqType. Lemma mkseq_uniqP (f : nat -> T) n : reflect {in gtn n &, injective f} (uniq (mkseq f n)). Proof. apply: (equivP (uniqP (f 0))); rewrite size_mkseq. by split=> injf i j lti ltj; have:= injf i j lti ltj; rewrite !nth_mkseq. Qed. Lemma mkseq_uniq (f : nat -> T) n : injective f -> uniq (mkseq f n). Proof. by move/map_inj_uniq->; apply: iota_uniq. Qed. Lemma perm_iotaP {s t : seq T} x0 (It := iota 0 (size t)) : reflect (exists2 Is, perm_eq Is It & s = map (nth x0 t) Is) (perm_eq s t). Proof. apply: (iffP idP) => [Est | [Is eqIst ->]]; last first. by rewrite -{2}[t](mkseq_nth x0) perm_map. elim: t => [|x t IHt] in s It Est *. by rewrite (perm_small_eq _ Est) //; exists [::]. have /rot_to[k s1 Ds]: x \in s by rewrite (perm_mem Est) mem_head. have [|Is1 eqIst1 Ds1] := IHt s1; first by rewrite -(perm_cons x) -Ds perm_rot. exists (rotr k (0 :: map succn Is1)). by rewrite perm_rot /It /= perm_cons (iotaDl 1) perm_map. by rewrite map_rotr /= -map_comp -(@eq_map _ _ (nth x0 t)) // -Ds1 -Ds rotK. Qed. End MakeEqSeq. Arguments perm_iotaP {T s t}. Section FoldRight. Variables (T : Type) (R : Type) (f : T -> R -> R) (z0 : R). Fixpoint foldr s := if s is x :: s' then f x (foldr s') else z0. End FoldRight. Section FoldRightComp. Variables (T1 T2 : Type) (h : T1 -> T2). Variables (R : Type) (f : T2 -> R -> R) (z0 : R). Lemma foldr_cat s1 s2 : foldr f z0 (s1 ++ s2) = foldr f (foldr f z0 s2) s1. Proof. by elim: s1 => //= x s1 ->. Qed. Lemma foldr_rcons s x : foldr f z0 (rcons s x) = foldr f (f x z0) s. Proof. by rewrite -cats1 foldr_cat. Qed. Lemma foldr_map s : foldr f z0 (map h s) = foldr (fun x z => f (h x) z) z0 s. Proof. by elim: s => //= x s ->. Qed. End FoldRightComp. (* Quick characterization of the null sequence. *) Definition sumn := foldr addn 0. Lemma sumn_ncons x n s : sumn (ncons n x s) = x * n + sumn s. Proof. by rewrite mulnC; elim: n => //= n ->; rewrite addnA. Qed. Lemma sumn_nseq x n : sumn (nseq n x) = x * n. Proof. by rewrite sumn_ncons addn0. Qed. Lemma sumn_cat s1 s2 : sumn (s1 ++ s2) = sumn s1 + sumn s2. Proof. by elim: s1 => //= x s1 ->; rewrite addnA. Qed. Lemma sumn_count T (a : pred T) s : sumn [seq a i : nat | i <- s] = count a s. Proof. by elim: s => //= s0 s /= ->. Qed. Lemma sumn_rcons s n : sumn (rcons s n) = sumn s + n. Proof. by rewrite -cats1 sumn_cat /= addn0. Qed. Lemma perm_sumn s1 s2 : perm_eq s1 s2 -> sumn s1 = sumn s2. Proof. by apply/catCA_perm_subst: s1 s2 => s1 s2 s3; rewrite !sumn_cat addnCA. Qed. Lemma sumn_rot s n : sumn (rot n s) = sumn s. Proof. by apply/perm_sumn; rewrite perm_rot. Qed. Lemma sumn_rev s : sumn (rev s) = sumn s. Proof. by apply/perm_sumn; rewrite perm_rev. Qed. Lemma natnseq0P s : reflect (s = nseq (size s) 0) (sumn s == 0). Proof. apply: (iffP idP) => [|->]; last by rewrite sumn_nseq. by elim: s => //= x s IHs; rewrite addn_eq0 => /andP[/eqP-> /IHs <-]. Qed. Lemma sumn_set_nth s x0 n x : sumn (set_nth x0 s n x) = sumn s + x - (nth x0 s n) * (n < size s) + x0 * (n - size s). Proof. rewrite set_nthE; case: ltnP => [nlts|nges]; last first. by rewrite sumn_cat sumn_ncons /= addn0 muln0 subn0 addnAC addnA. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. rewrite -[in sumn s](cat_take_drop n s) [drop n s](drop_nth x0)//. by rewrite !sumn_cat /= muln1 muln0 addn0 addnAC !addnA [in RHS]addnAC addnK. Qed. Lemma sumn_set_nth_ltn s x0 n x : n < size s -> sumn (set_nth x0 s n x) = sumn s + x - nth x0 s n. Proof. move=> nlts; rewrite sumn_set_nth nlts muln1. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. by rewrite muln0 addn0. Qed. Lemma sumn_set_nth0 s n x : sumn (set_nth 0 s n x) = sumn s + x - nth 0 s n. Proof. rewrite sumn_set_nth mul0n addn0. by case: ltnP => [_|nges]; rewrite ?muln1// nth_default. Qed. Section FoldLeft. Variables (T R : Type) (f : R -> T -> R). Fixpoint foldl z s := if s is x :: s' then foldl (f z x) s' else z. Lemma foldl_rev z s : foldl z (rev s) = foldr (fun x z => f z x) z s. Proof. by elim/last_ind: s z => // s x IHs z; rewrite rev_rcons -cats1 foldr_cat -IHs. Qed. Lemma foldl_cat z s1 s2 : foldl z (s1 ++ s2) = foldl (foldl z s1) s2. Proof. by rewrite -(revK (s1 ++ s2)) foldl_rev rev_cat foldr_cat -!foldl_rev !revK. Qed. Lemma foldl_rcons z s x : foldl z (rcons s x) = f (foldl z s) x. Proof. by rewrite -cats1 foldl_cat. Qed. End FoldLeft. Section Folds. Variables (T : Type) (f : T -> T -> T). Hypotheses (fA : associative f) (fC : commutative f). Lemma foldl_foldr x0 l : foldl f x0 l = foldr f x0 l. Proof. elim: l x0 => [//|x1 l IHl] x0 /=; rewrite {}IHl. by elim: l x0 x1 => [//|x2 l IHl] x0 x1 /=; rewrite IHl !fA [f x2 x1]fC. Qed. End Folds. Section Scan. Variables (T1 : Type) (x1 : T1) (T2 : Type) (x2 : T2). Variables (f : T1 -> T1 -> T2) (g : T1 -> T2 -> T1). Fixpoint pairmap x s := if s is y :: s' then f x y :: pairmap y s' else [::]. Lemma size_pairmap x s : size (pairmap x s) = size s. Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed. Lemma pairmap_cat x s1 s2 : pairmap x (s1 ++ s2) = pairmap x s1 ++ pairmap (last x s1) s2. Proof. by elim: s1 x => //= y s1 IHs1 x; rewrite IHs1. Qed. Lemma nth_pairmap s n : n < size s -> forall x, nth x2 (pairmap x s) n = f (nth x1 (x :: s) n) (nth x1 s n). Proof. by elim: s n => [|y s IHs] [|n] //= Hn x; apply: IHs. Qed. Fixpoint scanl x s := if s is y :: s' then let x' := g x y in x' :: scanl x' s' else [::]. Lemma size_scanl x s : size (scanl x s) = size s. Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed. Lemma scanl_cat x s1 s2 : scanl x (s1 ++ s2) = scanl x s1 ++ scanl (foldl g x s1) s2. Proof. by elim: s1 x => //= y s1 IHs1 x; rewrite IHs1. Qed. Lemma scanl_rcons x s1 y : scanl x (rcons s1 y) = rcons (scanl x s1) (foldl g x (rcons s1 y)). Proof. by rewrite -!cats1 scanl_cat foldl_cat. Qed. Lemma nth_cons_scanl s n : n <= size s -> forall x, nth x1 (x :: scanl x s) n = foldl g x (take n s). Proof. by elim: s n => [|y s IHs] [|n] Hn x //=; rewrite IHs. Qed. Lemma nth_scanl s n : n < size s -> forall x, nth x1 (scanl x s) n = foldl g x (take n.+1 s). Proof. by move=> n_lt x; rewrite -nth_cons_scanl. Qed. Lemma scanlK : (forall x, cancel (g x) (f x)) -> forall x, cancel (scanl x) (pairmap x). Proof. by move=> Hfg x s; elim: s x => //= y s IHs x; rewrite Hfg IHs. Qed. Lemma pairmapK : (forall x, cancel (f x) (g x)) -> forall x, cancel (pairmap x) (scanl x). Proof. by move=> Hgf x s; elim: s x => //= y s IHs x; rewrite Hgf IHs. Qed. End Scan. Prenex Implicits mask map pmap foldr foldl scanl pairmap. Section Zip. Variables (S T : Type) (r : S -> T -> bool). Fixpoint zip (s : seq S) (t : seq T) {struct t} := match s, t with | x :: s', y :: t' => (x, y) :: zip s' t' | _, _ => [::] end. Definition unzip1 := map (@fst S T). Definition unzip2 := map (@snd S T). Fixpoint all2 s t := match s, t with | [::], [::] => true | x :: s, y :: t => r x y && all2 s t | _, _ => false end. Lemma zip_unzip s : zip (unzip1 s) (unzip2 s) = s. Proof. by elim: s => [|[x y] s /= ->]. Qed. Lemma unzip1_zip s t : size s <= size t -> unzip1 (zip s t) = s. Proof. by elim: s t => [|x s IHs] [|y t] //= le_s_t; rewrite IHs. Qed. Lemma unzip2_zip s t : size t <= size s -> unzip2 (zip s t) = t. Proof. by elim: s t => [|x s IHs] [|y t] //= le_t_s; rewrite IHs. Qed. Lemma size1_zip s t : size s <= size t -> size (zip s t) = size s. Proof. by elim: s t => [|x s IHs] [|y t] //= Hs; rewrite IHs. Qed. Lemma size2_zip s t : size t <= size s -> size (zip s t) = size t. Proof. by elim: s t => [|x s IHs] [|y t] //= Hs; rewrite IHs. Qed. Lemma size_zip s t : size (zip s t) = minn (size s) (size t). Proof. by elim: s t => [|x s IHs] [|t2 t] //=; rewrite IHs minnSS. Qed. Lemma zip_cat s1 s2 t1 t2 : size s1 = size t1 -> zip (s1 ++ s2) (t1 ++ t2) = zip s1 t1 ++ zip s2 t2. Proof. by move: s1 t1; apply: seq_ind2 => //= x y s1 t1 _ ->. Qed. Lemma nth_zip x y s t i : size s = size t -> nth (x, y) (zip s t) i = (nth x s i, nth y t i). Proof. by elim: i s t => [|i IHi] [|y1 s1] [|y2 t] //= [/IHi->]. Qed. Lemma nth_zip_cond p s t i : nth p (zip s t) i = (if i < size (zip s t) then (nth p.1 s i, nth p.2 t i) else p). Proof. rewrite size_zip ltnNge geq_min. by elim: s t i => [|x s IHs] [|y t] [|i] //=; rewrite ?orbT -?IHs. Qed. Lemma zip_rcons s t x y : size s = size t -> zip (rcons s x) (rcons t y) = rcons (zip s t) (x, y). Proof. by move=> eq_sz; rewrite -!cats1 zip_cat //= eq_sz. Qed. Lemma rev_zip s t : size s = size t -> rev (zip s t) = zip (rev s) (rev t). Proof. move: s t; apply: seq_ind2 => //= x y s t eq_sz IHs. by rewrite !rev_cons IHs zip_rcons ?size_rev. Qed. Lemma all2E s t : all2 s t = (size s == size t) && all [pred xy | r xy.1 xy.2] (zip s t). Proof. by elim: s t => [|x s IHs] [|y t] //=; rewrite IHs andbCA. Qed. Lemma zip_map I f g (s : seq I) : zip (map f s) (map g s) = [seq (f i, g i) | i <- s]. Proof. by elim: s => //= i s ->. Qed. Lemma unzip1_map_nth_zip x y s t l : size s = size t -> unzip1 [seq nth (x, y) (zip s t) i | i <- l] = [seq nth x s i | i <- l]. Proof. by move=> st; elim: l => [//=|n l IH /=]; rewrite nth_zip ?IH ?st. Qed. Lemma unzip2_map_nth_zip x y s t l : size s = size t -> unzip2 [seq nth (x, y) (zip s t) i | i <- l] = [seq nth y t i | i <- l]. Proof. by move=> st; elim: l => [//=|n l IH /=]; rewrite nth_zip ?IH ?st. Qed. End Zip. Lemma zip_uniql (S T : eqType) (s : seq S) (t : seq T) : uniq s -> uniq (zip s t). Proof. case: s t => [|s0 s] [|t0 t] //; apply: contraTT => /(uniqPn (s0, t0)) [i [j]]. case=> o z; rewrite !nth_zip_cond !ifT ?js ?(ltn_trans o)// => -[n _]. by apply/(uniqPn s0); exists i, j; rewrite o n (leq_trans z) ?size_zip?geq_minl. Qed. Lemma zip_uniqr (S T : eqType) (s : seq S) (t : seq T) : uniq t -> uniq (zip s t). Proof. case: s t => [|s0 s] [|t0 t] //; apply: contraTT => /(uniqPn (s0, t0)) [i [j]]. case=> o z; rewrite !nth_zip_cond !ifT ?js ?(ltn_trans o)// => -[_ n]. by apply/(uniqPn t0); exists i, j; rewrite o n (leq_trans z) ?size_zip?geq_minr. Qed. Lemma perm_zip_sym (S T : eqType) (s1 s2 : seq S) (t1 t2 : seq T) : perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq (zip t1 s1) (zip t2 s2). Proof. have swap t s : zip t s = map (fun u => (u.2, u.1)) (zip s t). by elim: s t => [|x s +] [|y t]//= => ->. by rewrite [zip t1 s1]swap [zip t2 s2]swap; apply: perm_map. Qed. Lemma perm_zip1 {S T : eqType} (t1 t2 : seq T) (s1 s2 : seq S): size s1 = size t1 -> size s2 = size t2 -> perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq s1 s2. Proof. wlog [x y] : s1 s2 t1 t2 / (S * T)%type => [hwlog|]. case: s2 t2 => [|x s2] [|y t2] //; last exact: hwlog. by case: s1 t1 => [|u s1] [|v t1]//= _ _ /perm_nilP. move=> eq1 eq2 /(perm_iotaP (x, y))[ns nsP /(congr1 (@unzip1 _ _))]. rewrite unzip1_zip ?unzip1_map_nth_zip -?eq1// => ->. by apply/(perm_iotaP x); exists ns; rewrite // size_zip -eq2 minnn in nsP. Qed. Lemma perm_zip2 {S T : eqType} (s1 s2 : seq S) (t1 t2 : seq T) : size s1 = size t1 -> size s2 = size t2 -> perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq t1 t2. Proof. by move=> ? ? ?; rewrite (@perm_zip1 _ _ s1 s2) 1?perm_zip_sym. Qed. Prenex Implicits zip unzip1 unzip2 all2. Lemma eqseq_all (T : eqType) (s t : seq T) : (s == t) = all2 eq_op s t. Proof. by elim: s t => [|x s +] [|y t]//= => <-. Qed. Lemma eq_map_all I (T : eqType) (f g : I -> T) (s : seq I) : (map f s == map g s) = all [pred xy | xy.1 == xy.2] [seq (f i, g i) | i <- s]. Proof. by rewrite eqseq_all all2E !size_map eqxx zip_map. Qed. Section Flatten. Variable T : Type. Implicit Types (s : seq T) (ss : seq (seq T)). Definition flatten := foldr cat (Nil T). Definition shape := map (@size T). Fixpoint reshape sh s := if sh is n :: sh' then take n s :: reshape sh' (drop n s) else [::]. Definition flatten_index sh r c := sumn (take r sh) + c. Definition reshape_index sh i := find (pred1 0) (scanl subn i.+1 sh). Definition reshape_offset sh i := i - sumn (take (reshape_index sh i) sh). Lemma size_flatten ss : size (flatten ss) = sumn (shape ss). Proof. by elim: ss => //= s ss <-; rewrite size_cat. Qed. Lemma flatten_cat ss1 ss2 : flatten (ss1 ++ ss2) = flatten ss1 ++ flatten ss2. Proof. by elim: ss1 => //= s ss1 ->; rewrite catA. Qed. Lemma size_reshape sh s : size (reshape sh s) = size sh. Proof. by elim: sh s => //= s0 sh IHsh s; rewrite IHsh. Qed. Lemma nth_reshape (sh : seq nat) l n : nth [::] (reshape sh l) n = take (nth 0 sh n) (drop (sumn (take n sh)) l). Proof. elim: n sh l => [| n IHn] [| sh0 sh] l; rewrite ?take0 ?drop0 //=. by rewrite addnC -drop_drop; apply: IHn. Qed. Lemma flattenK ss : reshape (shape ss) (flatten ss) = ss. Proof. by elim: ss => //= s ss IHss; rewrite take_size_cat ?drop_size_cat ?IHss. Qed. Lemma reshapeKr sh s : size s <= sumn sh -> flatten (reshape sh s) = s. Proof. elim: sh s => [[]|n sh IHsh] //= s sz_s; rewrite IHsh ?cat_take_drop //. by rewrite size_drop leq_subLR. Qed. Lemma reshapeKl sh s : size s >= sumn sh -> shape (reshape sh s) = sh. Proof. elim: sh s => [[]|n sh IHsh] //= s sz_s. rewrite size_takel; last exact: leq_trans (leq_addr _ _) sz_s. by rewrite IHsh // -(leq_add2l n) size_drop -maxnE leq_max sz_s orbT. Qed. Lemma flatten_rcons ss s : flatten (rcons ss s) = flatten ss ++ s. Proof. by rewrite -cats1 flatten_cat /= cats0. Qed. Lemma flatten_seq1 s : flatten [seq [:: x] | x <- s] = s. Proof. by elim: s => //= s0 s ->. Qed. Lemma count_flatten ss P : count P (flatten ss) = sumn [seq count P x | x <- ss]. Proof. by elim: ss => //= s ss IHss; rewrite count_cat IHss. Qed. Lemma filter_flatten ss (P : pred T) : filter P (flatten ss) = flatten [seq filter P i | i <- ss]. Proof. by elim: ss => // s ss /= <-; apply: filter_cat. Qed. Lemma rev_flatten ss : rev (flatten ss) = flatten (rev (map rev ss)). Proof. by elim: ss => //= s ss IHss; rewrite rev_cons flatten_rcons -IHss rev_cat. Qed. Lemma nth_shape ss i : nth 0 (shape ss) i = size (nth [::] ss i). Proof. rewrite /shape; case: (ltnP i (size ss)) => Hi; first exact: nth_map. by rewrite !nth_default // size_map. Qed. Lemma shape_rev ss : shape (rev ss) = rev (shape ss). Proof. exact: map_rev. Qed. Lemma eq_from_flatten_shape ss1 ss2 : flatten ss1 = flatten ss2 -> shape ss1 = shape ss2 -> ss1 = ss2. Proof. by move=> Eflat Esh; rewrite -[LHS]flattenK Eflat Esh flattenK. Qed. Lemma rev_reshape sh s : size s = sumn sh -> rev (reshape sh s) = map rev (reshape (rev sh) (rev s)). Proof. move=> sz_s; apply/(canLR revK)/eq_from_flatten_shape. rewrite reshapeKr ?sz_s // -rev_flatten reshapeKr ?revK //. by rewrite size_rev sumn_rev sz_s. transitivity (rev (shape (reshape (rev sh) (rev s)))). by rewrite !reshapeKl ?revK ?size_rev ?sz_s ?sumn_rev. rewrite shape_rev; congr (rev _); rewrite -[RHS]map_comp. by under eq_map do rewrite /= size_rev. Qed. Lemma reshape_rcons s sh n (m := sumn sh) : m + n = size s -> reshape (rcons sh n) s = rcons (reshape sh (take m s)) (drop m s). Proof. move=> Dmn; apply/(can_inj revK); rewrite rev_reshape ?rev_rcons ?sumn_rcons //. rewrite /= take_rev drop_rev -Dmn addnK revK -rev_reshape //. by rewrite size_takel // -Dmn leq_addr. Qed. Lemma flatten_indexP sh r c : c < nth 0 sh r -> flatten_index sh r c < sumn sh. Proof. move=> lt_c_sh; rewrite -[sh in sumn sh](cat_take_drop r) sumn_cat ltn_add2l. suffices lt_r_sh: r < size sh by rewrite (drop_nth 0 lt_r_sh) ltn_addr. by case: ltnP => // le_sh_r; rewrite nth_default in lt_c_sh. Qed. Lemma reshape_indexP sh i : i < sumn sh -> reshape_index sh i < size sh. Proof. rewrite /reshape_index; elim: sh => //= n sh IHsh in i *; rewrite subn_eq0. by have [// | le_n_i] := ltnP i n; rewrite -leq_subLR subSn // => /IHsh. Qed. Lemma reshape_offsetP sh i : i < sumn sh -> reshape_offset sh i < nth 0 sh (reshape_index sh i). Proof. rewrite /reshape_offset /reshape_index; elim: sh => //= n sh IHsh in i *. rewrite subn_eq0; have [| le_n_i] := ltnP i n; first by rewrite subn0. by rewrite -leq_subLR /= subnDA subSn // => /IHsh. Qed. Lemma reshape_indexK sh i : flatten_index sh (reshape_index sh i) (reshape_offset sh i) = i. Proof. rewrite /reshape_offset /reshape_index /flatten_index -subSKn. elim: sh => //= n sh IHsh in i *; rewrite subn_eq0; have [//|le_n_i] := ltnP. by rewrite /= subnDA subSn // -addnA IHsh subnKC. Qed. Lemma flatten_indexKl sh r c : c < nth 0 sh r -> reshape_index sh (flatten_index sh r c) = r. Proof. rewrite /reshape_index /flatten_index. elim: sh r => [|n sh IHsh] [|r] //= lt_c_sh; first by rewrite ifT. by rewrite -addnA -addnS addKn IHsh. Qed. Lemma flatten_indexKr sh r c : c < nth 0 sh r -> reshape_offset sh (flatten_index sh r c) = c. Proof. rewrite /reshape_offset /reshape_index /flatten_index. elim: sh r => [|n sh IHsh] [|r] //= lt_c_sh; first by rewrite ifT ?subn0. by rewrite -addnA -addnS addKn /= subnDl IHsh. Qed. Lemma nth_flatten x0 ss i (r := reshape_index (shape ss) i) : nth x0 (flatten ss) i = nth x0 (nth [::] ss r) (reshape_offset (shape ss) i). Proof. rewrite /reshape_offset -subSKn {}/r /reshape_index. elim: ss => //= s ss IHss in i *; rewrite subn_eq0 nth_cat. by have [//|le_s_i] := ltnP; rewrite subnDA subSn /=. Qed. Lemma reshape_leq sh i1 i2 (r1 := reshape_index sh i1) (c1 := reshape_offset sh i1) (r2 := reshape_index sh i2) (c2 := reshape_offset sh i2) : (i1 <= i2) = ((r1 < r2) || ((r1 == r2) && (c1 <= c2))). Proof. rewrite {}/r1 {}/c1 {}/r2 {}/c2 /reshape_offset /reshape_index. elim: sh => [|s0 s IHs] /= in i1 i2 *; rewrite ?subn0 ?subn_eq0 //. have [[] i1s0 [] i2s0] := (ltnP i1 s0, ltnP i2 s0); first by rewrite !subn0. - by apply: leq_trans i2s0; apply/ltnW. - by apply/negP => /(leq_trans i1s0); rewrite leqNgt i2s0. by rewrite !subSn // !eqSS !ltnS !subnDA -IHs leq_subLR subnKC. Qed. End Flatten. Prenex Implicits flatten shape reshape. Lemma map_flatten S T (f : T -> S) ss : map f (flatten ss) = flatten (map (map f) ss). Proof. by elim: ss => // s ss /= <-; apply: map_cat. Qed. Lemma flatten_map1 (S T : Type) (f : S -> T) s : flatten [seq [:: f x] | x <- s] = map f s. Proof. by elim: s => //= s0 s ->. Qed. Lemma undup_flatten_nseq n (T : eqType) (s : seq T) : 0 < n -> undup (flatten (nseq n s)) = undup s. Proof. elim: n => [|[|n]/= IHn]//= _; rewrite ?cats0// undup_cat {}IHn//. rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => x. by rewrite mem_undup mem_cat => ->. Qed. Lemma sumn_flatten (ss : seq (seq nat)) : sumn (flatten ss) = sumn (map sumn ss). Proof. by elim: ss => // s ss /= <-; apply: sumn_cat. Qed. Lemma map_reshape T S (f : T -> S) sh s : map (map f) (reshape sh s) = reshape sh (map f s). Proof. by elim: sh s => //= sh0 sh IHsh s; rewrite map_take IHsh map_drop. Qed. Section EqFlatten. Variables S T : eqType. Lemma flattenP (A : seq (seq T)) x : reflect (exists2 s, s \in A & x \in s) (x \in flatten A). Proof. elim: A => /= [|s A IH_A]; [by right; case | rewrite mem_cat]. by apply: equivP (iff_sym exists_cons); apply: (orPP idP IH_A). Qed. Arguments flattenP {A x}. Lemma flatten_mapP (A : S -> seq T) s y : reflect (exists2 x, x \in s & y \in A x) (y \in flatten (map A s)). Proof. apply: (iffP flattenP) => [[_ /mapP[x sx ->]] | [x sx]] Axy; first by exists x. by exists (A x); rewrite ?map_f. Qed. Lemma perm_flatten (ss1 ss2 : seq (seq T)) : perm_eq ss1 ss2 -> perm_eq (flatten ss1) (flatten ss2). Proof. move=> eq_ss; apply/permP=> a; apply/catCA_perm_subst: ss1 ss2 eq_ss. by move=> ss1 ss2 ss3; rewrite !flatten_cat !count_cat addnCA. Qed. End EqFlatten. Arguments flattenP {T A x}. Arguments flatten_mapP {S T A s y}. Notation "[ 'seq' E | x <- s , y <- t ]" := (flatten [seq [seq E | y <- t] | x <- s]) (x binder, y binder, format "[ '[hv' 'seq' E '/ ' | x <- s , '/ ' y <- t ] ']'") : seq_scope. Notation "[ 'seq' E : R | x <- s , y <- t ]" := (flatten [seq [seq E : R | y <- t] | x <- s]) (x binder, y binder, only parsing) : seq_scope. Section PrefixSuffixInfix. Variables T : eqType. Implicit Type s : seq T. Fixpoint prefix s1 s2 {struct s2} := if s1 isn't x :: s1' then true else if s2 isn't y :: s2' then false else (x == y) && prefix s1' s2'. Lemma prefixE s1 s2 : prefix s1 s2 = (take (size s1) s2 == s1). Proof. by elim: s2 s1 => [|y s2 +] [|x s1]//= => ->; rewrite eq_sym. Qed. Lemma prefix_refl s : prefix s s. Proof. by rewrite prefixE take_size. Qed. Lemma prefixs0 s : prefix s [::] = (s == [::]). Proof. by case: s. Qed. Lemma prefix0s s : prefix [::] s. Proof. by case: s. Qed. Lemma prefix_cons s1 s2 x y : prefix (x :: s1) (y :: s2) = (x == y) && prefix s1 s2. Proof. by []. Qed. Lemma prefix_catr s1 s2 s1' s3 : size s1 = size s1' -> prefix (s1 ++ s2) (s1' ++ s3) = (s1 == s1') && prefix s2 s3. Proof. elim: s1 s1' => [|x s1 IHs1] [|y s1']//= [eqs1]. by rewrite IHs1// eqseq_cons andbA. Qed. Lemma prefix_prefix s1 s2 : prefix s1 (s1 ++ s2). Proof. by rewrite prefixE take_cat ltnn subnn take0 cats0. Qed. Hint Resolve prefix_prefix : core. Lemma prefixP {s1 s2} : reflect (exists s2' : seq T, s2 = s1 ++ s2') (prefix s1 s2). Proof. apply: (iffP idP) => [|[{}s2 ->]]; last exact: prefix_prefix. by rewrite prefixE => /eqP<-; exists (drop (size s1) s2); rewrite cat_take_drop. Qed. Lemma prefix_trans : transitive prefix. Proof. by move=> _ s2 _ /prefixP[s1 ->] /prefixP[s3 ->]; rewrite -catA. Qed. Lemma prefixs1 s x : prefix s [:: x] = (s == [::]) || (s == [:: x]). Proof. by case: s => //= y s; rewrite prefixs0 eqseq_cons. Qed. Lemma catl_prefix s1 s2 s3 : prefix (s1 ++ s3) s2 -> prefix s1 s2. Proof. by move=> /prefixP [s2'] ->; rewrite -catA. Qed. Lemma prefix_catl s1 s2 s3 : prefix s1 s2 -> prefix s1 (s2 ++ s3). Proof. by move=> /prefixP [s2'] ->; rewrite -catA. Qed. Lemma prefix_rcons s x : prefix s (rcons s x). Proof. by rewrite -cats1 prefix_prefix. Qed. Definition suffix s1 s2 := prefix (rev s1) (rev s2). Lemma suffixE s1 s2 : suffix s1 s2 = (drop (size s2 - size s1) s2 == s1). Proof. by rewrite /suffix prefixE take_rev (can_eq revK) size_rev. Qed. Lemma suffix_refl s : suffix s s. Proof. exact: prefix_refl. Qed. Lemma suffixs0 s : suffix s [::] = (s == [::]). Proof. by rewrite /suffix prefixs0 -!nilpE rev_nilp. Qed. Lemma suffix0s s : suffix [::] s. Proof. exact: prefix0s. Qed. Lemma prefix_rev s1 s2 : prefix (rev s1) (rev s2) = suffix s1 s2. Proof. by []. Qed. Lemma prefix_revLR s1 s2 : prefix (rev s1) s2 = suffix s1 (rev s2). Proof. by rewrite -prefix_rev revK. Qed. Lemma suffix_rev s1 s2 : suffix (rev s1) (rev s2) = prefix s1 s2. Proof. by rewrite -prefix_rev !revK. Qed. Lemma suffix_revLR s1 s2 : suffix (rev s1) s2 = prefix s1 (rev s2). Proof. by rewrite -prefix_rev revK. Qed. Lemma suffix_suffix s1 s2 : suffix s2 (s1 ++ s2). Proof. by rewrite /suffix rev_cat prefix_prefix. Qed. Hint Resolve suffix_suffix : core. Lemma suffixP {s1 s2} : reflect (exists s2' : seq T, s2 = s2' ++ s1) (suffix s1 s2). Proof. apply: (iffP prefixP) => [[s2' rev_s2]|[s2' ->]]; exists (rev s2'); last first. by rewrite rev_cat. by rewrite -[s2]revK rev_s2 rev_cat revK. Qed. Lemma suffix_trans : transitive suffix. Proof. by move=> _ s2 _ /suffixP[s1 ->] /suffixP[s3 ->]; rewrite catA. Qed. Lemma suffix_rcons s1 s2 x y : suffix (rcons s1 x) (rcons s2 y) = (x == y) && suffix s1 s2. Proof. by rewrite /suffix 2!rev_rcons prefix_cons. Qed. Lemma suffix_catl s1 s2 s3 s3' : size s3 = size s3' -> suffix (s1 ++ s3) (s2 ++ s3') = (s3 == s3') && suffix s1 s2. Proof. by move=> eqs3; rewrite /suffix !rev_cat prefix_catr ?size_rev// (can_eq revK). Qed. Lemma suffix_catr s1 s2 s3 : suffix s1 s2 -> suffix s1 (s3 ++ s2). Proof. by move=> /suffixP [s2'] ->; rewrite catA suffix_suffix. Qed. Lemma catl_suffix s s1 s2 : suffix (s ++ s1) s2 -> suffix s1 s2. Proof. by move=> /suffixP [s2'] ->; rewrite catA suffix_suffix. Qed. Lemma suffix_cons s x : suffix s (x :: s). Proof. by rewrite /suffix rev_cons prefix_rcons. Qed. Fixpoint infix s1 s2 := if s2 is y :: s2' then prefix s1 s2 || infix s1 s2' else s1 == [::]. Fixpoint infix_index s1 s2 := if prefix s1 s2 then 0 else if s2 is y :: s2' then (infix_index s1 s2').+1 else 1. Lemma infix0s s : infix [::] s. Proof. by case: s. Qed. Lemma infixs0 s : infix s [::] = (s == [::]). Proof. by case: s. Qed. Lemma infix_consl s1 y s2 : infix s1 (y :: s2) = prefix s1 (y :: s2) || infix s1 s2. Proof. by []. Qed. Lemma infix_indexss s : infix_index s s = 0. Proof. by case: s => //= x s; rewrite eqxx prefix_refl. Qed. Lemma infix_index_le s1 s2 : infix_index s1 s2 <= (size s2).+1. Proof. by elim: s2 => [|x s2'] /=; case: ifP. Qed. Lemma infixTindex s1 s2 : (infix_index s1 s2 <= size s2) = infix s1 s2. Proof. by elim: s2 s1 => [|y s2 +] [|x s1]//= => <-; case: ifP. Qed. Lemma infixPn s1 s2 : reflect (infix_index s1 s2 = (size s2).+1) (~~ infix s1 s2). Proof. rewrite -infixTindex -ltnNge; apply: (iffP idP) => [s2lt|->//]. by apply/eqP; rewrite eqn_leq s2lt infix_index_le. Qed. Lemma infix_index0s s : infix_index [::] s = 0. Proof. by case: s. Qed. Lemma infix_indexs0 s : infix_index s [::] = (s != [::]). Proof. by case: s. Qed. Lemma infixE s1 s2 : infix s1 s2 = (take (size s1) (drop (infix_index s1 s2) s2) == s1). Proof. elim: s2 s1 => [|y s2 +] [|x s1]//= => -> /=. by case: ifP => // /andP[/eqP-> ps1s2/=]; rewrite eqseq_cons -prefixE eqxx. Qed. Lemma infix_refl s : infix s s. Proof. by rewrite infixE infix_indexss// drop0 take_size. Qed. Lemma prefixW s1 s2 : prefix s1 s2 -> infix s1 s2. Proof. by elim: s2 s1 => [|y s2 IHs2] [|x s1]//=->. Qed. Lemma prefix_infix s1 s2 : infix s1 (s1 ++ s2). Proof. exact: prefixW. Qed. Hint Resolve prefix_infix : core. Lemma infix_infix s1 s2 s3 : infix s2 (s1 ++ s2 ++ s3). Proof. by elim: s1 => //= x s1 ->; rewrite orbT. Qed. Hint Resolve infix_infix : core. Lemma suffix_infix s1 s2 : infix s2 (s1 ++ s2). Proof. by rewrite -[X in s1 ++ X]cats0. Qed. Hint Resolve suffix_infix : core. Lemma infixP {s1 s2} : reflect (exists s s' : seq T, s2 = s ++ s1 ++ s') (infix s1 s2). Proof. apply: (iffP idP) => [|[p [s {s2}->]]]//=; rewrite infixE => /eqP<-. set k := infix_index _ _; exists (take k s2), (drop (size s1 + k) s2). by rewrite -drop_drop !cat_take_drop. Qed. Lemma infix_rev s1 s2 : infix (rev s1) (rev s2) = infix s1 s2. Proof. gen have sr : s1 s2 / infix s1 s2 -> infix (rev s1) (rev s2); last first. by apply/idP/idP => /sr; rewrite ?revK. by move=> /infixP[s [p ->]]; rewrite !rev_cat -catA. Qed. Lemma suffixW s1 s2 : suffix s1 s2 -> infix s1 s2. Proof. by rewrite -infix_rev; apply: prefixW. Qed. Lemma infix_trans : transitive infix. Proof. move=> s s1 s2 /infixP[s1p [s1s def_s]] /infixP[sp [ss def_s2]]. by apply/infixP; exists (sp ++ s1p),(s1s ++ ss); rewrite def_s2 def_s -!catA. Qed. Lemma infix_revLR s1 s2 : infix (rev s1) s2 = infix s1 (rev s2). Proof. by rewrite -infix_rev revK. Qed. Lemma infix_rconsl s1 s2 y : infix s1 (rcons s2 y) = suffix s1 (rcons s2 y) || infix s1 s2. Proof. rewrite -infix_rev rev_rcons infix_consl. by rewrite -rev_rcons prefix_rev infix_rev. Qed. Lemma infix_cons s x : infix s (x :: s). Proof. by rewrite -cat1s suffix_infix. Qed. Lemma infixs1 s x : infix s [:: x] = (s == [::]) || (s == [:: x]). Proof. by rewrite infix_consl prefixs1 orbC orbA orbb. Qed. Lemma catl_infix s s1 s2 : infix (s ++ s1) s2 -> infix s1 s2. Proof. apply: infix_trans; exact/suffixW/suffix_suffix. Qed. Lemma catr_infix s s1 s2 : infix (s1 ++ s) s2 -> infix s1 s2. Proof. by rewrite -infix_rev rev_cat => /catl_infix; rewrite infix_rev. Qed. Lemma cons2_infix s1 s2 x : infix (x :: s1) (x :: s2) -> infix s1 s2. Proof. by rewrite /= eqxx /= -cat1s => /orP[/prefixW//|]; exact: catl_infix. Qed. Lemma rcons2_infix s1 s2 x : infix (rcons s1 x) (rcons s2 x) -> infix s1 s2. Proof. by rewrite -infix_rev !rev_rcons => /cons2_infix; rewrite infix_rev. Qed. Lemma catr2_infix s s1 s2 : infix (s ++ s1) (s ++ s2) -> infix s1 s2. Proof. by elim: s => //= x s IHs /cons2_infix. Qed. Lemma catl2_infix s s1 s2 : infix (s1 ++ s) (s2 ++ s) -> infix s1 s2. Proof. by rewrite -infix_rev !rev_cat => /catr2_infix; rewrite infix_rev. Qed. Lemma infix_catl s1 s2 s3 : infix s1 s2 -> infix s1 (s3 ++ s2). Proof. by move=> is12; apply: infix_trans is12 (suffix_infix _ _). Qed. Lemma infix_catr s1 s2 s3 : infix s1 s2 -> infix s1 (s2 ++ s3). Proof. case: s3 => [|x s /infixP [p [sf]] ->]; first by rewrite cats0. by rewrite -catA; apply: infix_catl; rewrite -catA prefix_infix. Qed. Lemma prefix_infix_trans s2 s1 s3 : prefix s1 s2 -> infix s2 s3 -> infix s1 s3. Proof. by move=> /prefixW/infix_trans; apply. Qed. Lemma suffix_infix_trans s2 s1 s3 : suffix s1 s2 -> infix s2 s3 -> infix s1 s3. Proof. by move=> /suffixW/infix_trans; apply. Qed. Lemma infix_prefix_trans s2 s1 s3 : infix s1 s2 -> prefix s2 s3 -> infix s1 s3. Proof. by move=> + /prefixW; apply: infix_trans. Qed. Lemma infix_suffix_trans s2 s1 s3 : infix s1 s2 -> suffix s2 s3 -> infix s1 s3. Proof. by move=> + /suffixW; apply: infix_trans. Qed. Lemma prefix_suffix_trans s2 s1 s3 : prefix s1 s2 -> suffix s2 s3 -> infix s1 s3. Proof. by move=> /prefixW + /suffixW +; apply: infix_trans. Qed. Lemma suffix_prefix_trans s2 s1 s3 : suffix s1 s2 -> prefix s2 s3 -> infix s1 s3. Proof. by move=> /suffixW + /prefixW +; apply: infix_trans. Qed. Lemma infixW s1 s2 : infix s1 s2 -> subseq s1 s2. Proof. move=> /infixP[sp [ss ->]]. exact: subseq_trans (prefix_subseq _ _) (suffix_subseq _ _). Qed. Lemma mem_infix s1 s2 : infix s1 s2 -> {subset s1 <= s2}. Proof. by move=> /infixW subH; apply: mem_subseq. Qed. Lemma infix1s s x : infix [:: x] s = (x \in s). Proof. by elim: s => // x' s /= ->; rewrite in_cons prefix0s andbT. Qed. Lemma prefix1s s x : prefix [:: x] s -> x \in s. Proof. by rewrite -infix1s => /prefixW. Qed. Lemma suffix1s s x : suffix [:: x] s -> x \in s. Proof. by rewrite -infix1s => /suffixW. Qed. Lemma infix_rcons s x : infix s (rcons s x). Proof. by rewrite -cats1 prefix_infix. Qed. Lemma infix_uniq s1 s2 : infix s1 s2 -> uniq s2 -> uniq s1. Proof. by move=> /infixW /subseq_uniq subH. Qed. Lemma prefix_uniq s1 s2 : prefix s1 s2 -> uniq s2 -> uniq s1. Proof. by move=> /prefixW /infix_uniq preH. Qed. Lemma suffix_uniq s1 s2 : suffix s1 s2 -> uniq s2 -> uniq s1. Proof. by move=> /suffixW /infix_uniq preH. Qed. Lemma prefix_take s i : prefix (take i s) s. Proof. by rewrite -{2}[s](cat_take_drop i). Qed. Lemma suffix_drop s i : suffix (drop i s) s. Proof. by rewrite -{2}[s](cat_take_drop i). Qed. Lemma infix_take s i : infix (take i s) s. Proof. by rewrite prefixW // prefix_take. Qed. Lemma prefix_drop_gt0 s i : ~~ prefix (drop i s) s -> i > 0. Proof. by case: i => //=; rewrite drop0 ltnn prefix_refl. Qed. Lemma infix_drop s i : infix (drop i s) s. Proof. by rewrite -{2}[s](cat_take_drop i). Qed. Lemma consr_infix s1 s2 x : infix (x :: s1) s2 -> infix [:: x] s2. Proof. by rewrite -cat1s => /catr_infix. Qed. Lemma consl_infix s1 s2 x : infix (x :: s1) s2 -> infix s1 s2. Proof. by rewrite -cat1s => /catl_infix. Qed. Lemma prefix_index s1 s2 : prefix s1 s2 -> infix_index s1 s2 = 0. Proof. by case: s1 s2 => [|x s1] [|y s2] //= ->. Qed. Lemma size_infix s1 s2 : infix s1 s2 -> size s1 <= size s2. Proof. by move=> /infixW; apply: size_subseq. Qed. Lemma size_prefix s1 s2 : prefix s1 s2 -> size s1 <= size s2. Proof. by move=> /prefixW; apply: size_infix. Qed. Lemma size_suffix s1 s2 : suffix s1 s2 -> size s1 <= size s2. Proof. by move=> /suffixW; apply: size_infix. Qed. End PrefixSuffixInfix. Section AllPairsDep. Variables (S S' : Type) (T T' : S -> Type) (R : Type). Implicit Type f : forall x, T x -> R. Definition allpairs_dep f s t := [seq f x y | x <- s, y <- t x]. Lemma size_allpairs_dep f s t : size [seq f x y | x <- s, y <- t x] = sumn [seq size (t x) | x <- s]. Proof. by elim: s => //= x s IHs; rewrite size_cat size_map IHs. Qed. Lemma allpairs0l f t : [seq f x y | x <- [::], y <- t x] = [::]. Proof. by []. Qed. Lemma allpairs0r f s : [seq f x y | x <- s, y <- [::]] = [::]. Proof. by elim: s. Qed. Lemma allpairs1l f x t : [seq f x y | x <- [:: x], y <- t x] = [seq f x y | y <- t x]. Proof. exact: cats0. Qed. Lemma allpairs1r f s y : [seq f x y | x <- s, y <- [:: y x]] = [seq f x (y x) | x <- s]. Proof. exact: flatten_map1. Qed. Lemma allpairs_cons f x s t : [seq f x y | x <- x :: s, y <- t x] = [seq f x y | y <- t x] ++ [seq f x y | x <- s, y <- t x]. Proof. by []. Qed. Lemma eq_allpairs (f1 f2 : forall x, T x -> R) s t : (forall x, f1 x =1 f2 x) -> [seq f1 x y | x <- s, y <- t x] = [seq f2 x y | x <- s, y <- t x]. Proof. by move=> eq_f; under eq_map do under eq_map do rewrite eq_f. Qed. Lemma eq_allpairsr (f : forall x, T x -> R) s t1 t2 : (forall x, t1 x = t2 x) -> [seq f x y | x <- s, y <- t1 x] = [seq f x y | x <- s, y <- t2 x]. Proof. by move=> eq_t; under eq_map do rewrite eq_t. Qed. Lemma allpairs_cat f s1 s2 t : [seq f x y | x <- s1 ++ s2, y <- t x] = [seq f x y | x <- s1, y <- t x] ++ [seq f x y | x <- s2, y <- t x]. Proof. by rewrite map_cat flatten_cat. Qed. Lemma allpairs_rcons f x s t : [seq f x y | x <- rcons s x, y <- t x] = [seq f x y | x <- s, y <- t x] ++ [seq f x y | y <- t x]. Proof. by rewrite -cats1 allpairs_cat allpairs1l. Qed. Lemma allpairs_mapl f (g : S' -> S) s t : [seq f x y | x <- map g s, y <- t x] = [seq f (g x) y | x <- s, y <- t (g x)]. Proof. by rewrite -map_comp. Qed. Lemma allpairs_mapr f (g : forall x, T' x -> T x) s t : [seq f x y | x <- s, y <- map (g x) (t x)] = [seq f x (g x y) | x <- s, y <- t x]. Proof. by under eq_map do rewrite -map_comp. Qed. End AllPairsDep. Arguments allpairs_dep {S T R} f s t /. Lemma map_allpairs S T R R' (g : R' -> R) f s t : map g [seq f x y | x : S <- s, y : T x <- t x] = [seq g (f x y) | x <- s, y <- t x]. Proof. by rewrite map_flatten allpairs_mapl allpairs_mapr. Qed. Section AllPairsNonDep. Variables (S T R : Type) (f : S -> T -> R). Implicit Types (s : seq S) (t : seq T). Definition allpairs s t := [seq f x y | x <- s, y <- t]. Lemma size_allpairs s t : size [seq f x y | x <- s, y <- t] = size s * size t. Proof. by elim: s => //= x s IHs; rewrite size_cat size_map IHs. Qed. End AllPairsNonDep. Arguments allpairs {S T R} f s t /. Section EqAllPairsDep. Variables (S : eqType) (T : S -> eqType). Implicit Types (R : eqType) (s : seq S) (t : forall x, seq (T x)). Lemma allpairsPdep R (f : forall x, T x -> R) s t (z : R) : reflect (exists x y, [/\ x \in s, y \in t x & z = f x y]) (z \in [seq f x y | x <- s, y <- t x]). Proof. apply: (iffP flatten_mapP); first by case=> x sx /mapP[y ty ->]; exists x, y. by case=> x [y [sx ty ->]]; exists x; last apply: map_f. Qed. Variable R : eqType. Implicit Type f : forall x, T x -> R. Lemma allpairs_f_dep f s t x y : x \in s -> y \in t x -> f x y \in [seq f x y | x <- s, y <- t x]. Proof. by move=> sx ty; apply/allpairsPdep; exists x, y. Qed. Lemma eq_in_allpairs_dep f1 f2 s t : {in s, forall x, {in t x, f1 x =1 f2 x}} <-> [seq f1 x y : R | x <- s, y <- t x] = [seq f2 x y | x <- s, y <- t x]. Proof. split=> [eq_f | eq_fst x s_x]. by congr flatten; apply/eq_in_map=> x s_x; apply/eq_in_map/eq_f. apply/eq_in_map; apply/eq_in_map: x s_x; apply/eq_from_flatten_shape => //. by rewrite /shape -!map_comp; apply/eq_map=> x /=; rewrite !size_map. Qed. Lemma perm_allpairs_dep f s1 t1 s2 t2 : perm_eq s1 s2 -> {in s1, forall x, perm_eq (t1 x) (t2 x)} -> perm_eq [seq f x y | x <- s1, y <- t1 x] [seq f x y | x <- s2, y <- t2 x]. Proof. elim: s1 s2 t1 t2 => [s2 t1 t2 |a s1 IH s2 t1 t2 perm_s2 perm_t1]. by rewrite perm_sym => /perm_nilP->. have mem_a : a \in s2 by rewrite -(perm_mem perm_s2) inE eqxx. rewrite -[s2](cat_take_drop (index a s2)). rewrite allpairs_cat (drop_nth a) ?index_mem //= nth_index //=. rewrite perm_sym perm_catC -catA perm_cat //; last first. rewrite perm_catC -allpairs_cat. rewrite -remE perm_sym IH // => [|x xI]; last first. by apply: perm_t1; rewrite inE xI orbT. by rewrite -(perm_cons a) (perm_trans perm_s2 (perm_to_rem _)). have /perm_t1 : a \in a :: s1 by rewrite inE eqxx. rewrite perm_sym; elim: (t2 a) (t1 a) => /= [s4|b s3 IH1 s4 perm_s4]. by rewrite perm_sym => /perm_nilP->. have mem_b : b \in s4 by rewrite -(perm_mem perm_s4) inE eqxx. rewrite -[s4](cat_take_drop (index b s4)). rewrite map_cat /= (drop_nth b) ?index_mem //= nth_index //=. rewrite perm_sym perm_catC /= perm_cons // perm_catC -map_cat. rewrite -remE perm_sym IH1 // -(perm_cons b). by apply: perm_trans perm_s4 (perm_to_rem _). Qed. Lemma mem_allpairs_dep f s1 t1 s2 t2 : s1 =i s2 -> {in s1, forall x, t1 x =i t2 x} -> [seq f x y | x <- s1, y <- t1 x] =i [seq f x y | x <- s2, y <- t2 x]. Proof. move=> eq_s eq_t z; apply/allpairsPdep/allpairsPdep=> -[x [y [sx ty ->]]]; by exists x, y; rewrite -eq_s in sx *; rewrite eq_t in ty *. Qed. Lemma allpairs_uniq_dep f s t (st := [seq Tagged T y | x <- s, y <- t x]) : let g (p : {x : S & T x}) : R := f (tag p) (tagged p) in uniq s -> {in s, forall x, uniq (t x)} -> {in st &, injective g} -> uniq [seq f x y | x <- s, y <- t x]. Proof. move=> g Us Ut; rewrite -(map_allpairs g (existT T)) => /map_inj_in_uniq->{f g}. elim: s Us => //= x s IHs /andP[s'x Us] in st Ut *; rewrite {st}cat_uniq. rewrite {}IHs {Us}// ?andbT => [|x1 s_s1]; last exact/Ut/mem_behead. have injT: injective (existT T x) by move=> y z /eqP; rewrite eq_Tagged => /eqP. rewrite (map_inj_in_uniq (in2W injT)) {injT}Ut ?mem_head // has_sym has_map. by apply: contra s'x => /hasP[y _ /allpairsPdep[z [_ [? _ /(congr1 tag)/=->]]]]. Qed. End EqAllPairsDep. Arguments allpairsPdep {S T R f s t z}. Section MemAllPairs. Variables (S : Type) (T : S -> Type) (R : eqType). Implicit Types (f : forall x, T x -> R) (s : seq S). Lemma perm_allpairs_catr f s t1 t2 : perm_eql [seq f x y | x <- s, y <- t1 x ++ t2 x] ([seq f x y | x <- s, y <- t1 x] ++ [seq f x y | x <- s, y <- t2 x]). Proof. apply/permPl; rewrite perm_sym; elim: s => //= x s ihs. by rewrite perm_catACA perm_cat ?map_cat. Qed. Lemma mem_allpairs_catr f s y0 t : [seq f x y | x <- s, y <- y0 x ++ t x] =i [seq f x y | x <- s, y <- y0 x] ++ [seq f x y | x <- s, y <- t x]. Proof. exact/perm_mem/permPl/perm_allpairs_catr. Qed. Lemma perm_allpairs_consr f s y0 t : perm_eql [seq f x y | x <- s, y <- y0 x :: t x] ([seq f x (y0 x) | x <- s] ++ [seq f x y | x <- s, y <- t x]). Proof. by apply/permPl; rewrite (perm_allpairs_catr _ _ (fun=> [:: _])) allpairs1r. Qed. Lemma mem_allpairs_consr f s t y0 : [seq f x y | x <- s, y <- y0 x :: t x] =i [seq f x (y0 x) | x <- s] ++ [seq f x y | x <- s, y <- t x]. Proof. exact/perm_mem/permPl/perm_allpairs_consr. Qed. Lemma allpairs_rconsr f s y0 t : perm_eql [seq f x y | x <- s, y <- rcons (t x) (y0 x)] ([seq f x y | x <- s, y <- t x] ++ [seq f x (y0 x) | x <- s]). Proof. apply/permPl; rewrite -(eq_allpairsr _ _ (fun=> cats1 _ _)). by rewrite perm_allpairs_catr allpairs1r. Qed. Lemma mem_allpairs_rconsr f s t y0 : [seq f x y | x <- s, y <- rcons (t x) (y0 x)] =i ([seq f x y | x <- s, y <- t x] ++ [seq f x (y0 x) | x <- s]). Proof. exact/perm_mem/permPl/allpairs_rconsr. Qed. End MemAllPairs. Lemma all_allpairsP (S : eqType) (T : S -> eqType) (R : Type) (p : pred R) (f : forall x : S, T x -> R) (s : seq S) (t : forall x : S, seq (T x)) : reflect (forall (x : S) (y : T x), x \in s -> y \in t x -> p (f x y)) (all p [seq f x y | x <- s, y <- t x]). Proof. elim: s => [|x s IHs]; first by constructor. rewrite /= all_cat all_map /preim. apply/(iffP andP)=> [[/allP /= ? ? x' y x'_in_xs]|p_xs_t]. by move: x'_in_xs y => /[1!inE] /predU1P [-> //|? ?]; exact: IHs. split; first by apply/allP => ?; exact/p_xs_t/mem_head. by apply/IHs => x' y x'_in_s; apply: p_xs_t; rewrite inE x'_in_s orbT. Qed. Arguments all_allpairsP {S T R p f s t}. Section EqAllPairs. Variables S T R : eqType. Implicit Types (f : S -> T -> R) (s : seq S) (t : seq T). Lemma allpairsP f s t (z : R) : reflect (exists p, [/\ p.1 \in s, p.2 \in t & z = f p.1 p.2]) (z \in [seq f x y | x <- s, y <- t]). Proof. by apply: (iffP allpairsPdep) => [[x[y]]|[[x y]]]; [exists (x, y)|exists x, y]. Qed. Lemma allpairs_f f s t x y : x \in s -> y \in t -> f x y \in [seq f x y | x <- s, y <- t]. Proof. exact: allpairs_f_dep. Qed. Lemma eq_in_allpairs f1 f2 s t : {in s & t, f1 =2 f2} <-> [seq f1 x y : R | x <- s, y <- t] = [seq f2 x y | x <- s, y <- t]. Proof. split=> [eq_f | /eq_in_allpairs_dep-eq_f x y /eq_f/(_ y)//]. by apply/eq_in_allpairs_dep=> x /eq_f. Qed. Lemma perm_allpairs f s1 t1 s2 t2 : perm_eq s1 s2 -> perm_eq t1 t2 -> perm_eq [seq f x y | x <- s1, y <- t1] [seq f x y | x <- s2, y <- t2]. Proof. by move=> perm_s perm_t; apply: perm_allpairs_dep. Qed. Lemma mem_allpairs f s1 t1 s2 t2 : s1 =i s2 -> t1 =i t2 -> [seq f x y | x <- s1, y <- t1] =i [seq f x y | x <- s2, y <- t2]. Proof. by move=> eq_s eq_t; apply: mem_allpairs_dep. Qed. Lemma allpairs_uniq f s t (st := [seq (x, y) | x <- s, y <- t]) : uniq s -> uniq t -> {in st &, injective (uncurry f)} -> uniq [seq f x y | x <- s, y <- t]. Proof. move=> Us Ut inj_f; rewrite -(map_allpairs (uncurry f) (@pair S T)) -/st. rewrite map_inj_in_uniq // allpairs_uniq_dep {Us Ut st inj_f}//. by apply: in2W => -[x1 y1] [x2 y2] /= [-> ->]. Qed. End EqAllPairs. Arguments allpairsP {S T R f s t z}. Arguments perm_nilP {T s}. Arguments perm_consP {T x s t}. Section AllRel. Variables (T S : Type) (r : T -> S -> bool). Implicit Types (x : T) (y : S) (xs : seq T) (ys : seq S). Definition allrel xs ys := all [pred x | all (r x) ys] xs. Lemma allrel0l ys : allrel [::] ys. Proof. by []. Qed. Lemma allrel0r xs : allrel xs [::]. Proof. by elim: xs. Qed. Lemma allrel_consl x xs ys : allrel (x :: xs) ys = all (r x) ys && allrel xs ys. Proof. by []. Qed. Lemma allrel_consr xs y ys : allrel xs (y :: ys) = all (r^~ y) xs && allrel xs ys. Proof. exact: all_predI. Qed. Lemma allrel_cons2 x y xs ys : allrel (x :: xs) (y :: ys) = [&& r x y, all (r x) ys, all (r^~ y) xs & allrel xs ys]. Proof. by rewrite /= allrel_consr -andbA. Qed. Lemma allrel1l x ys : allrel [:: x] ys = all (r x) ys. Proof. exact: andbT. Qed. Lemma allrel1r xs y : allrel xs [:: y] = all (r^~ y) xs. Proof. by rewrite allrel_consr allrel0r andbT. Qed. Lemma allrel_catl xs xs' ys : allrel (xs ++ xs') ys = allrel xs ys && allrel xs' ys. Proof. exact: all_cat. Qed. Lemma allrel_catr xs ys ys' : allrel xs (ys ++ ys') = allrel xs ys && allrel xs ys'. Proof. elim: ys => /= [|y ys ihys]; first by rewrite allrel0r. by rewrite !allrel_consr ihys andbA. Qed. Lemma allrel_maskl m xs ys : allrel xs ys -> allrel (mask m xs) ys. Proof. by elim: m xs => [|[] m IHm] [|x xs] //= /andP [xys /IHm->]; rewrite ?xys. Qed. Lemma allrel_maskr m xs ys : allrel xs ys -> allrel xs (mask m ys). Proof. by elim: xs => //= x xs IHxs /andP [/all_mask->]. Qed. Lemma allrel_filterl a xs ys : allrel xs ys -> allrel (filter a xs) ys. Proof. by rewrite filter_mask; apply: allrel_maskl. Qed. Lemma allrel_filterr a xs ys : allrel xs ys -> allrel xs (filter a ys). Proof. by rewrite filter_mask; apply: allrel_maskr. Qed. Lemma allrel_allpairsE xs ys : allrel xs ys = all id [seq r x y | x <- xs, y <- ys]. Proof. by elim: xs => //= x xs ->; rewrite all_cat all_map. Qed. End AllRel. Arguments allrel {T S} r xs ys : simpl never. Arguments allrel0l {T S} r ys. Arguments allrel0r {T S} r xs. Arguments allrel_consl {T S} r x xs ys. Arguments allrel_consr {T S} r xs y ys. Arguments allrel1l {T S} r x ys. Arguments allrel1r {T S} r xs y. Arguments allrel_catl {T S} r xs xs' ys. Arguments allrel_catr {T S} r xs ys ys'. Arguments allrel_maskl {T S} r m xs ys. Arguments allrel_maskr {T S} r m xs ys. Arguments allrel_filterl {T S} r a xs ys. Arguments allrel_filterr {T S} r a xs ys. Arguments allrel_allpairsE {T S} r xs ys. Notation all2rel r xs := (allrel r xs xs). Lemma sub_in_allrel {T S : Type} (P : {pred T}) (Q : {pred S}) (r r' : T -> S -> bool) : {in P & Q, forall x y, r x y -> r' x y} -> forall xs ys, all P xs -> all Q ys -> allrel r xs ys -> allrel r' xs ys. Proof. move=> rr' + ys; elim=> //= x xs IHxs /andP [Px Pxs] Qys. rewrite !allrel_consl => /andP [+ {}/IHxs-> //]; rewrite andbT. by elim: ys Qys => //= y ys IHys /andP [Qy Qys] /andP [/rr'-> // /IHys->]. Qed. Lemma sub_allrel {T S : Type} (r r' : T -> S -> bool) : (forall x y, r x y -> r' x y) -> forall xs ys, allrel r xs ys -> allrel r' xs ys. Proof. by move=> rr' xs ys; apply/sub_in_allrel/all_predT/all_predT; apply: in2W. Qed. Lemma eq_in_allrel {T S : Type} (P : {pred T}) (Q : {pred S}) r r' : {in P & Q, r =2 r'} -> forall xs ys, all P xs -> all Q ys -> allrel r xs ys = allrel r' xs ys. Proof. move=> rr' xs ys Pxs Qys. by apply/idP/idP; apply/sub_in_allrel/Qys/Pxs => ? ? ? ?; rewrite rr'. Qed. Lemma eq_allrel {T S : Type} (r r' : T -> S -> bool) : r =2 r' -> allrel r =2 allrel r'. Proof. by move=> rr' xs ys; apply/eq_in_allrel/all_predT/all_predT. Qed. Lemma allrelC {T S : Type} (r : T -> S -> bool) xs ys : allrel r xs ys = allrel (fun y => r^~ y) ys xs. Proof. by elim: xs => [|x xs ih]; [elim: ys | rewrite allrel_consr -ih]. Qed. Lemma allrel_mapl {T T' S : Type} (f : T' -> T) (r : T -> S -> bool) xs ys : allrel r (map f xs) ys = allrel (fun x => r (f x)) xs ys. Proof. exact: all_map. Qed. Lemma allrel_mapr {T S S' : Type} (f : S' -> S) (r : T -> S -> bool) xs ys : allrel r xs (map f ys) = allrel (fun x y => r x (f y)) xs ys. Proof. by rewrite allrelC allrel_mapl allrelC. Qed. Lemma allrelP {T S : eqType} {r : T -> S -> bool} {xs ys} : reflect {in xs & ys, forall x y, r x y} (allrel r xs ys). Proof. by rewrite allrel_allpairsE; exact: all_allpairsP. Qed. Lemma allrelT {T S : Type} (xs : seq T) (ys : seq S) : allrel (fun _ _ => true) xs ys = true. Proof. by elim: xs => //= ? ?; rewrite allrel_consl all_predT. Qed. Lemma allrel_relI {T S : Type} (r r' : T -> S -> bool) xs ys : allrel (fun x y => r x y && r' x y) xs ys = allrel r xs ys && allrel r' xs ys. Proof. by rewrite -all_predI; apply: eq_all => ?; rewrite /= -all_predI. Qed. Lemma allrel_revl {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) : allrel r (rev s1) s2 = allrel r s1 s2. Proof. exact: all_rev. Qed. Lemma allrel_revr {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) : allrel r s1 (rev s2) = allrel r s1 s2. Proof. by rewrite allrelC allrel_revl allrelC. Qed. Lemma allrel_rev2 {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) : allrel r (rev s1) (rev s2) = allrel r s1 s2. Proof. by rewrite allrel_revr allrel_revl. Qed. Lemma eq_allrel_meml {T : eqType} {S} (r : T -> S -> bool) (s1 s1' : seq T) s2 : s1 =i s1' -> allrel r s1 s2 = allrel r s1' s2. Proof. by move=> eqs1; apply: eq_all_r. Qed. Lemma eq_allrel_memr {T} {S : eqType} (r : T -> S -> bool) s1 (s2 s2' : seq S) : s2 =i s2' -> allrel r s1 s2 = allrel r s1 s2'. Proof. by rewrite ![allrel _ s1 _]allrelC; apply: eq_allrel_meml. Qed. Lemma eq_allrel_mem2 {T S : eqType} (r : T -> S -> bool) (s1 s1' : seq T) (s2 s2' : seq S) : s1 =i s1' -> s2 =i s2' -> allrel r s1 s2 = allrel r s1' s2'. Proof. by move=> /eq_allrel_meml -> /eq_allrel_memr ->. Qed. Section All2Rel. Variable (T : nonPropType) (r : rel T). Implicit Types (x y z : T) (xs : seq T). Hypothesis (rsym : symmetric r). Lemma all2rel1 x : all2rel r [:: x] = r x x. Proof. by rewrite /allrel /= !andbT. Qed. Lemma all2rel2 x y : all2rel r [:: x; y] = r x x && r y y && r x y. Proof. by rewrite /allrel /= rsym; do 3 case: r. Qed. Lemma all2rel_cons x xs : all2rel r (x :: xs) = [&& r x x, all (r x) xs & all2rel r xs]. Proof. rewrite allrel_cons2; congr andb; rewrite andbA -all_predI; congr andb. by elim: xs => //= y xs ->; rewrite rsym andbb. Qed. End All2Rel. Section Pairwise. Variables (T : Type) (r : T -> T -> bool). Implicit Types (x y : T) (xs ys : seq T). Fixpoint pairwise xs : bool := if xs is x :: xs then all (r x) xs && pairwise xs else true. Lemma pairwise_cons x xs : pairwise (x :: xs) = all (r x) xs && pairwise xs. Proof. by []. Qed. Lemma pairwise_cat xs ys : pairwise (xs ++ ys) = [&& allrel r xs ys, pairwise xs & pairwise ys]. Proof. by elim: xs => //= x xs ->; rewrite all_cat -!andbA; bool_congr. Qed. Lemma pairwise_rcons xs x : pairwise (rcons xs x) = all (r^~ x) xs && pairwise xs. Proof. by rewrite -cats1 pairwise_cat allrel1r andbT. Qed. Lemma pairwise2 x y : pairwise [:: x; y] = r x y. Proof. by rewrite /= !andbT. Qed. Lemma pairwise_mask m xs : pairwise xs -> pairwise (mask m xs). Proof. by elim: m xs => [|[] m IHm] [|x xs] //= /andP [? ?]; rewrite ?IHm // all_mask. Qed. Lemma pairwise_filter a xs : pairwise xs -> pairwise (filter a xs). Proof. by rewrite filter_mask; apply: pairwise_mask. Qed. Lemma pairwiseP x0 xs : reflect {in gtn (size xs) &, {homo nth x0 xs : i j / i < j >-> r i j}} (pairwise xs). Proof. elim: xs => /= [|x xs IHxs]; first exact: (iffP idP). apply: (iffP andP) => [[r_x_xs pxs] i j|Hnth]; rewrite -?topredE /= ?ltnS. by case: i j => [|i] [|j] //= gti gtj ij; [exact/all_nthP | exact/IHxs]. split; last by apply/IHxs => // i j; apply/(Hnth i.+1 j.+1). by apply/(all_nthP x0) => i gti; apply/(Hnth 0 i.+1). Qed. Lemma pairwise_all2rel : reflexive r -> symmetric r -> forall xs, pairwise xs = all2rel r xs. Proof. by move=> r_refl r_sym; elim => //= x xs ->; rewrite all2rel_cons // r_refl. Qed. End Pairwise. Arguments pairwise {T} r xs. Arguments pairwise_cons {T} r x xs. Arguments pairwise_cat {T} r xs ys. Arguments pairwise_rcons {T} r xs x. Arguments pairwise2 {T} r x y. Arguments pairwise_mask {T r} m {xs}. Arguments pairwise_filter {T r} a {xs}. Arguments pairwiseP {T r} x0 {xs}. Arguments pairwise_all2rel {T r} r_refl r_sym xs. Lemma sub_in_pairwise {T : Type} (P : {pred T}) (r r' : rel T) : {in P &, subrel r r'} -> forall xs, all P xs -> pairwise r xs -> pairwise r' xs. Proof. move=> rr'; elim=> //= x xs IHxs /andP [Px Pxs] /andP [+ {}/IHxs->] //. rewrite andbT; elim: xs Pxs => //= x' xs IHxs /andP [? ?] /andP [+ /IHxs->] //. by rewrite andbT; apply: rr'. Qed. Lemma sub_pairwise {T : Type} (r r' : rel T) xs : subrel r r' -> pairwise r xs -> pairwise r' xs. Proof. by move=> rr'; apply/sub_in_pairwise/all_predT; apply: in2W. Qed. Lemma eq_in_pairwise {T : Type} (P : {pred T}) (r r' : rel T) : {in P &, r =2 r'} -> forall xs, all P xs -> pairwise r xs = pairwise r' xs. Proof. move=> rr' xs Pxs. by apply/idP/idP; apply/sub_in_pairwise/Pxs => ? ? ? ?; rewrite rr'. Qed. Lemma eq_pairwise {T : Type} (r r' : rel T) : r =2 r' -> pairwise r =i pairwise r'. Proof. by move=> rr' xs; apply/eq_in_pairwise/all_predT. Qed. Lemma pairwise_map {T T' : Type} (f : T' -> T) (r : rel T) xs : pairwise r (map f xs) = pairwise (relpre f r) xs. Proof. by elim: xs => //= x xs ->; rewrite all_map. Qed. Lemma pairwise_relI {T : Type} (r r' : rel T) (s : seq T) : pairwise [rel x y | r x y && r' x y] s = pairwise r s && pairwise r' s. Proof. by elim: s => //= x s ->; rewrite andbACA all_predI. Qed. Section EqPairwise. Variables (T : eqType) (r : T -> T -> bool). Implicit Types (xs ys : seq T). Lemma subseq_pairwise xs ys : subseq xs ys -> pairwise r ys -> pairwise r xs. Proof. by case/subseqP => m _ ->; apply: pairwise_mask. Qed. Lemma uniq_pairwise xs : uniq xs = pairwise [rel x y | x != y] xs. Proof. elim: xs => //= x xs ->; congr andb; rewrite -has_pred1 -all_predC. by elim: xs => //= x' xs ->; case: eqVneq. Qed. Lemma pairwise_uniq xs : irreflexive r -> pairwise r xs -> uniq xs. Proof. move=> r_irr; rewrite uniq_pairwise; apply/sub_pairwise => x y. by apply: contraTneq => ->; rewrite r_irr. Qed. Lemma pairwise_eq : antisymmetric r -> forall xs ys, pairwise r xs -> pairwise r ys -> perm_eq xs ys -> xs = ys. Proof. move=> r_asym; elim=> [|x xs IHxs] [|y ys] //=; try by move=> ? ? /perm_size. move=> /andP [r_x_xs pxs] /andP [r_y_ys pys] eq_xs_ys. move: (mem_head y ys) (mem_head x xs). rewrite -(perm_mem eq_xs_ys) [x \in _](perm_mem eq_xs_ys) !inE. case: eqVneq eq_xs_ys => /= [->|ne_xy] eq_xs_ys ys_x xs_y. by rewrite (IHxs ys) // -(perm_cons x). by case/eqP: ne_xy; apply: r_asym; rewrite (allP r_x_xs) ?(allP r_y_ys). Qed. Lemma pairwise_trans s : antisymmetric r -> pairwise r s -> {in s & &, transitive r}. Proof. move=> /(_ _ _ _)/eqP r_anti + y x z => /pairwiseP-/(_ y) ltP ys xs zs. have [-> //|neqxy] := eqVneq x y; have [-> //|neqzy] := eqVneq z y. move=> lxy lyz; move: ys xs zs lxy neqxy lyz neqzy. move=> /(nthP y)[j jlt <-] /(nthP y)[i ilt <-] /(nthP y)[k klt <-]. have [ltij|ltji|->] := ltngtP i j; last 2 first. - by move=> leij; rewrite r_anti// leij ltP. - by move=> lejj; rewrite r_anti// lejj. move=> _ _; have [ltjk|ltkj|->] := ltngtP j k; last 2 first. - by move=> lejk; rewrite r_anti// lejk ltP. - by move=> lekk; rewrite r_anti// lekk. by move=> _ _; apply: (ltP) => //; apply: ltn_trans ltjk. Qed. End EqPairwise. Arguments subseq_pairwise {T r xs ys}. Arguments uniq_pairwise {T} xs. Arguments pairwise_uniq {T r xs}. Arguments pairwise_eq {T r} r_asym {xs ys}. Section Permutations. Variable T : eqType. Implicit Types (x : T) (s t : seq T) (bs : seq (T * nat)) (acc : seq (seq T)). Fixpoint incr_tally bs x := if bs isn't b :: bs then [:: (x, 1)] else if x == b.1 then (x, b.2.+1) :: bs else b :: incr_tally bs x. Definition tally s := foldl incr_tally [::] s. Definition wf_tally := [qualify a bs : seq (T * nat) | uniq (unzip1 bs) && (0 \notin unzip2 bs)]. Definition tally_seq bs := flatten [seq nseq b.2 b.1 | b <- bs]. Local Notation tseq := tally_seq. Lemma size_tally_seq bs : size (tally_seq bs) = sumn (unzip2 bs). Proof. by rewrite size_flatten /shape -map_comp; under eq_map do rewrite /= size_nseq. Qed. Lemma tally_seqK : {in wf_tally, cancel tally_seq tally}. Proof. move=> bs /andP[]; elim: bs => [|[x [|n]] bs IHbs] //= /andP[bs'x Ubs] bs'0. rewrite inE /tseq /tally /= -[n.+1]addn1 in bs'0 *. elim: n 1 => /= [|n IHn] m; last by rewrite eqxx IHn addnS. rewrite -{}[in RHS]IHbs {Ubs bs'0}// /tally /tally_seq add0n. elim: bs bs'x [::] => [|[y n] bs IHbs] //= /[1!inE] /norP[y'x bs'x]. by elim: n => [|n IHn] bs1 /=; [rewrite IHbs | rewrite eq_sym ifN // IHn]. Qed. Lemma incr_tallyP x : {homo incr_tally^~ x : bs / bs \in wf_tally}. Proof. move=> bs /andP[]; rewrite unfold_in. elim: bs => [|[y [|n]] bs IHbs] //= /andP[bs'y Ubs] /[1!inE] /= bs'0. have [<- | y'x] /= := eqVneq y; first by rewrite bs'y Ubs. rewrite -andbA {}IHbs {Ubs bs'0}// andbT. elim: bs bs'y => [|b bs IHbs] /=; rewrite inE ?y'x // => /norP[b'y bs'y]. by case: ifP => _; rewrite /= inE negb_or ?y'x // b'y IHbs. Qed. Lemma tallyP s : tally s \is a wf_tally. Proof. rewrite /tally; set bs := [::]; have: bs \in wf_tally by []. by elim: s bs => //= x s IHs bs /(incr_tallyP x)/IHs. Qed. Lemma tallyK s : perm_eq (tally_seq (tally s)) s. Proof. rewrite -[s in perm_eq _ s]cats0 -[nil]/(tseq [::]) /tally. elim: s [::] => //= x s IHs bs; rewrite {IHs}(permPl (IHs _)). rewrite perm_sym -cat1s perm_catCA {s}perm_cat2l. elim: bs => //= b bs IHbs; case: eqP => [-> | _] //=. by rewrite -cat1s perm_catCA perm_cat2l. Qed. Lemma tallyEl s : perm_eq (unzip1 (tally s)) (undup s). Proof. have /andP[Ubs bs'0] := tallyP s; set bs := tally s in Ubs bs'0 *. rewrite uniq_perm ?undup_uniq {Ubs}// => x. rewrite mem_undup -(perm_mem (tallyK s)) -/bs. elim: bs => [|[y [|m]] bs IHbs] //= in bs'0 *. by rewrite inE IHbs // mem_cat mem_nseq. Qed. Lemma tallyE s : perm_eq (tally s) [seq (x, count_mem x s) | x <- undup s]. Proof. have /andP[Ubs _] := tallyP s; pose b := [fun s x => (x, count_mem x (tseq s))]. suffices /permPl->: perm_eq (tally s) (map (b (tally s)) (unzip1 (tally s))). congr perm_eq: (perm_map (b (tally s)) (tallyEl s)). by under eq_map do rewrite /= (permP (tallyK s)). elim: (tally s) Ubs => [|[x m] bs IH] //= /andP[bs'x /IH-IHbs {IH}]. rewrite /tseq /= -/(tseq _) count_cat count_nseq /= eqxx mul1n. rewrite (count_memPn _) ?addn0 ?perm_cons; last first. apply: contra bs'x; elim: {b IHbs}bs => //= b bs IHbs. by rewrite mem_cat mem_nseq inE andbC; case: (_ == _). congr perm_eq: IHbs; apply/eq_in_map=> y bs_y; congr (y, _). by rewrite count_cat count_nseq /= (negPf (memPnC bs'x y bs_y)). Qed. Lemma perm_tally s1 s2 : perm_eq s1 s2 -> perm_eq (tally s1) (tally s2). Proof. move=> eq_s12; apply: (@perm_trans _ [seq (x, count_mem x s2) | x <- undup s1]). by congr perm_eq: (tallyE s1); under eq_map do rewrite (permP eq_s12). by rewrite (permPr (tallyE s2)); apply/perm_map/perm_undup/(perm_mem eq_s12). Qed. Lemma perm_tally_seq bs1 bs2 : perm_eq bs1 bs2 -> perm_eq (tally_seq bs1) (tally_seq bs2). Proof. by move=> Ebs12; rewrite perm_flatten ?perm_map. Qed. Local Notation perm_tseq := perm_tally_seq. Lemma perm_count_undup s : perm_eq (flatten [seq nseq (count_mem x s) x | x <- undup s]) s. Proof. by rewrite -(permPr (tallyK s)) (permPr (perm_tseq (tallyE s))) /tseq -map_comp. Qed. Local Fixpoint cons_perms_ perms_rec (s : seq T) bs bs2 acc := if bs isn't b :: bs1 then acc else if b isn't (x, m.+1) then cons_perms_ perms_rec s bs1 bs2 acc else let acc_xs := perms_rec (x :: s) ((x, m) :: bs1 ++ bs2) acc in cons_perms_ perms_rec s bs1 (b :: bs2) acc_xs. Local Fixpoint perms_rec n s bs acc := if n isn't n.+1 then s :: acc else cons_perms_ (perms_rec n) s bs [::] acc. Local Notation cons_perms n := (cons_perms_ (perms_rec n) [::]). Definition permutations s := perms_rec (size s) [::] (tally s) [::]. Let permsP s : exists n bs, [/\ permutations s = perms_rec n [::] bs [::], size (tseq bs) == n, perm_eq (tseq bs) s & uniq (unzip1 bs)]. Proof. have /andP[Ubs _] := tallyP s; exists (size s), (tally s). by rewrite (perm_size (tallyK s)) tallyK. Qed. Local Notation bsCA := (permEl (perm_catCA _ [:: _] _)). Let cons_permsE : forall n x bs bs1 bs2, let cp := cons_perms n bs bs2 in let perms s := perms_rec n s bs1 [::] in cp (perms [:: x]) = cp [::] ++ [seq rcons t x | t <- perms [::]]. Proof. pose is_acc f := forall acc, f acc = f [::] ++ acc. (* f is accumulating. *) have cpE: forall f & forall s bs, is_acc (f s bs), is_acc (cons_perms_ f _ _ _). move=> s bs bs2 f fE acc; elim: bs => [|[x [|m]] bs IHbs] //= in s bs2 acc *. by rewrite fE IHbs catA -IHbs. have prE: is_acc (perms_rec _ _ _) by elim=> //= n IHn s bs; apply: cpE. pose has_suffix f := forall s : seq T, f s = [seq t ++ s | t <- f [::]]. suffices prEs n bs: has_suffix (fun s => perms_rec n s bs [::]). move=> n x bs bs1 bs2 /=; rewrite cpE // prEs. by under eq_map do rewrite cats1. elim: n bs => //= n IHn bs s; elim: bs [::] => [|[x [|m]] bs IHbs] //= bs1. rewrite cpE // IHbs IHn [in RHS]cpE // [in RHS]IHn map_cat -map_comp. by congr (_ ++ _); apply: eq_map => t /=; rewrite -catA. Qed. Lemma mem_permutations s t : (t \in permutations s) = perm_eq t s. Proof. have{s} [n [bs [-> Dn /permPr<- _]]] := permsP s. elim: n => [|n IHn] /= in t bs Dn *. by rewrite inE (nilP Dn); apply/eqP/perm_nilP. rewrite -[bs in tseq bs]cats0 in Dn *; have x0 : T by case: (tseq _) Dn. rewrite -[RHS](@andb_idl (last x0 t \in tseq bs)); last first. case/lastP: t {IHn} => [|t x] Dt; first by rewrite -(perm_size Dt) in Dn. by rewrite -[bs]cats0 -(perm_mem Dt) last_rcons mem_rcons mem_head. elim: bs [::] => [|[x [|m]] bs IHbs] //= bs2 in Dn *. rewrite cons_permsE -!cat_cons !mem_cat (mem_nseq m.+1) orbC andb_orl. rewrite {}IHbs ?(perm_size (perm_tseq bsCA)) //= (permPr (perm_tseq bsCA)). congr (_ || _); apply/mapP/andP=> [[t1 Dt1 ->] | [/eqP]]. by rewrite last_rcons perm_rcons perm_cons IHn in Dt1 *. case/lastP: t => [_ /perm_size//|t y]; rewrite last_rcons perm_rcons => ->. by rewrite perm_cons; exists t; rewrite ?IHn. Qed. Lemma permutations_uniq s : uniq (permutations s). Proof. have{s} [n [bs [-> Dn _ Ubs]]] := permsP s. elim: n => //= n IHn in bs Dn Ubs *; rewrite -[bs]cats0 /unzip1 in Dn Ubs. elim: bs [::] => [|[x [|m]] bs IHbs] //= bs2 in Dn Ubs *. by case/andP: Ubs => _ /IHbs->. rewrite /= cons_permsE cat_uniq has_sym andbCA andbC. rewrite {}IHbs; first 1 last; first by rewrite (perm_size (perm_tseq bsCA)). by rewrite (perm_uniq (perm_map _ bsCA)). rewrite (map_inj_uniq (rcons_injl x)) {}IHn {Dn}//=. have: x \notin unzip1 bs by apply: contraL Ubs; rewrite map_cat mem_cat => ->. move: {bs2 m Ubs}(perms_rec n _ _ _) (_ :: bs2) => ts. elim: bs => [|[y [|m]] bs IHbs] //= /[1!inE] bs2 /norP[x'y /IHbs//]. rewrite cons_permsE has_cat negb_or has_map => ->. by apply/hasPn=> t _; apply: contra x'y => /mapP[t1 _ /rcons_inj[_ ->]]. Qed. Notation perms := permutations. Lemma permutationsE s : 0 < size s -> perm_eq (perms s) [seq x :: t | x <- undup s, t <- perms (rem x s)]. Proof. move=> nt_s; apply/uniq_perm=> [||t]; first exact: permutations_uniq. apply/allpairs_uniq_dep=> [|x _|]; rewrite ?undup_uniq ?permutations_uniq //. by case=> [_ _] [x t] _ _ [-> ->]. rewrite mem_permutations; apply/idP/allpairsPdep=> [Dt | [x [t1 []]]]. rewrite -(perm_size Dt) in nt_s; case: t nt_s => // x t _ in Dt *. have s_x: x \in s by rewrite -(perm_mem Dt) mem_head. exists x, t; rewrite mem_undup mem_permutations; split=> //. by rewrite -(perm_cons x) (permPl Dt) perm_to_rem. rewrite mem_undup mem_permutations -(perm_cons x) => s_x Dt1 ->. by rewrite (permPl Dt1) perm_sym perm_to_rem. Qed. Lemma permutationsErot x s (le_x := fun t => iota 0 (index x t + 1)) : perm_eq (perms (x :: s)) [seq rot i (x :: t) | t <- perms s, i <- le_x t]. Proof. have take'x t i: i <= index x t -> i <= size t /\ x \notin take i t. move=> le_i_x; have le_i_t: i <= size t := leq_trans le_i_x (index_size x t). case: (nthP x) => // -[j lt_j_i /eqP]; rewrite size_takel // in lt_j_i. by rewrite nth_take // [_ == _](before_find x (leq_trans lt_j_i le_i_x)). pose xrot t i := rot i (x :: t); pose xrotV t := index x (rev (rot 1 t)). have xrotK t: {in le_x t, cancel (xrot t) xrotV}. move=> i; rewrite mem_iota addn1 /xrotV => /take'x[le_i_t ti'x]. rewrite -rotD ?rev_cat //= rev_cons cat_rcons index_cat mem_rev size_rev. by rewrite ifN // size_takel //= eqxx addn0. apply/uniq_perm=> [||t]; first exact: permutations_uniq. apply/allpairs_uniq_dep=> [|t _|]; rewrite ?permutations_uniq ?iota_uniq //. move=> _ _ /allpairsPdep[t [i [_ ? ->]]] /allpairsPdep[u [j [_ ? ->]]] Etu. have Eij: i = j by rewrite -(xrotK t i) // /xrot Etu xrotK. by move: Etu; rewrite Eij => /rot_inj[->]. rewrite mem_permutations; apply/esym; apply/allpairsPdep/idP=> [[u [i]] | Dt]. rewrite mem_permutations => -[Du _ /(canLR (rotK i))]; rewrite /rotr. by set j := (j in rot j _) => Dt; apply/perm_consP; exists j, u. pose r := rev (rot 1 t); pose i := index x r; pose u := rev (take i r). have r_x: x \in r by rewrite mem_rev mem_rot (perm_mem Dt) mem_head. have [v Duv]: {v | rot i (x :: u ++ v) = t}; first exists (rev (drop i.+1 r)). rewrite -rev_cat -rev_rcons -rot1_cons -cat_cons -(nth_index x r_x). by rewrite -drop_nth ?index_mem // rot_rot !rev_rot revK rotK rotrK. exists (u ++ v), i; rewrite mem_permutations -(perm_cons x) -(perm_rot i) Duv. rewrite mem_iota addn1 ltnS /= index_cat mem_rev size_rev. by have /take'x[le_i_t ti'x] := leqnn i; rewrite ifN ?size_takel ?leq_addr. Qed. Lemma size_permutations s : uniq s -> size (permutations s) = (size s)`!. Proof. move Dn: (size s) => n Us; elim: n s => [[]|n IHn s] //= in Dn Us *. rewrite (perm_size (permutationsE _)) ?Dn // undup_id // factS -Dn. rewrite -(size_iota 0 n`!) -(size_allpairs (fun=>id)) !size_allpairs_dep. by apply/congr1/eq_in_map=> x sx; rewrite size_iota IHn ?size_rem ?Dn ?rem_uniq. Qed. Lemma permutations_all_uniq s : uniq s -> all uniq (permutations s). Proof. by move=> Us; apply/allP=> t; rewrite mem_permutations => /perm_uniq->. Qed. Lemma perm_permutations s t : perm_eq s t -> perm_eq (permutations s) (permutations t). Proof. move=> Est; apply/uniq_perm; try exact: permutations_uniq. by move=> u; rewrite !mem_permutations (permPr Est). Qed. End Permutations.
Prod.lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Data.Set.Finite.Basic import Mathlib.Data.Fintype.Prod import Mathlib.Data.Fintype.Pi import Mathlib.Algebra.Order.Group.Multiset import Mathlib.Data.Vector.Basic import Mathlib.Tactic.ApplyFun import Mathlib.Data.ULift import Mathlib.Data.Set.NAry /-! # Finiteness of products -/ assert_not_exists OrderedRing MonoidWithZero variable {α β : Type*} namespace Finite instance [Finite α] [Finite β] : Finite (α × β) := by haveI := Fintype.ofFinite α haveI := Fintype.ofFinite β infer_instance instance {α β : Sort*} [Finite α] [Finite β] : Finite (PProd α β) := of_equiv _ Equiv.pprodEquivProdPLift.symm theorem prod_left (β) [Finite (α × β)] [Nonempty β] : Finite α := of_surjective (Prod.fst : α × β → α) Prod.fst_surjective theorem prod_right (α) [Finite (α × β)] [Nonempty α] : Finite β := of_surjective (Prod.snd : α × β → β) Prod.snd_surjective end Finite instance Pi.finite {α : Sort*} {β : α → Sort*} [Finite α] [∀ a, Finite (β a)] : Finite (∀ a, β a) := by classical haveI := Fintype.ofFinite (PLift α) haveI := fun a => Fintype.ofFinite (PLift (β a)) exact Finite.of_equiv (∀ a : PLift α, PLift (β (Equiv.plift a))) (Equiv.piCongr Equiv.plift fun _ => Equiv.plift) instance Function.Embedding.finite {α β : Sort*} [Finite β] : Finite (α ↪ β) := by rcases isEmpty_or_nonempty (α ↪ β) with _ | h · infer_instance · refine h.elim fun f => ?_ haveI : Finite α := Finite.of_injective _ f.injective exact Finite.of_injective _ DFunLike.coe_injective instance Equiv.finite_right {α β : Sort*} [Finite β] : Finite (α ≃ β) := Finite.of_injective Equiv.toEmbedding fun e₁ e₂ h => Equiv.ext <| by convert DFunLike.congr_fun h using 0 instance Equiv.finite_left {α β : Sort*} [Finite α] : Finite (α ≃ β) := Finite.of_equiv _ ⟨Equiv.symm, Equiv.symm, Equiv.symm_symm, Equiv.symm_symm⟩ @[to_additive] instance MulEquiv.finite_left {α β : Type*} [Mul α] [Mul β] [Finite α] : Finite (α ≃* β) := Finite.of_injective toEquiv toEquiv_injective @[to_additive] instance MulEquiv.finite_right {α β : Type*} [Mul α] [Mul β] [Finite β] : Finite (α ≃* β) := Finite.of_injective toEquiv toEquiv_injective open Set Function variable {γ : Type*} namespace Set /-! ### Fintype instances Every instance here should have a corresponding `Set.Finite` constructor in the next section. -/ section FintypeInstances instance fintypeProd (s : Set α) (t : Set β) [Fintype s] [Fintype t] : Fintype (s ×ˢ t : Set (α × β)) := Fintype.ofFinset (s.toFinset ×ˢ t.toFinset) <| by simp instance fintypeOffDiag [DecidableEq α] (s : Set α) [Fintype s] : Fintype s.offDiag := Fintype.ofFinset s.toFinset.offDiag <| by simp /-- `image2 f s t` is `Fintype` if `s` and `t` are. -/ instance fintypeImage2 [DecidableEq γ] (f : α → β → γ) (s : Set α) (t : Set β) [hs : Fintype s] [ht : Fintype t] : Fintype (image2 f s t : Set γ) := by rw [← image_prod] apply Set.fintypeImage end FintypeInstances end Set /-! ### Finite instances There is seemingly some overlap between the following instances and the `Fintype` instances in `Data.Set.Finite`. While every `Fintype` instance gives a `Finite` instance, those instances that depend on `Fintype` or `Decidable` instances need an additional `Finite` instance to be able to generally apply. Some set instances do not appear here since they are consequences of others, for example `Subtype.Finite` for subsets of a finite type. -/ namespace Finite.Set instance finite_prod (s : Set α) (t : Set β) [Finite s] [Finite t] : Finite (s ×ˢ t : Set (α × β)) := Finite.of_equiv _ (Equiv.Set.prod s t).symm instance finite_image2 (f : α → β → γ) (s : Set α) (t : Set β) [Finite s] [Finite t] : Finite (image2 f s t : Set γ) := by rw [← image_prod] infer_instance end Finite.Set namespace Set /-! ### Constructors for `Set.Finite` Every constructor here should have a corresponding `Fintype` instance in the previous section (or in the `Fintype` module). The implementation of these constructors ideally should be no more than `Set.toFinite`, after possibly setting up some `Fintype` and classical `Decidable` instances. -/ section SetFiniteConstructors section Prod variable {s : Set α} {t : Set β} protected theorem Finite.prod (hs : s.Finite) (ht : t.Finite) : (s ×ˢ t : Set (α × β)).Finite := by have := hs.to_subtype have := ht.to_subtype apply toFinite theorem Finite.of_prod_left (h : (s ×ˢ t : Set (α × β)).Finite) : t.Nonempty → s.Finite := fun ⟨b, hb⟩ => (h.image Prod.fst).subset fun a ha => ⟨(a, b), ⟨ha, hb⟩, rfl⟩ theorem Finite.of_prod_right (h : (s ×ˢ t : Set (α × β)).Finite) : s.Nonempty → t.Finite := fun ⟨a, ha⟩ => (h.image Prod.snd).subset fun b hb => ⟨(a, b), ⟨ha, hb⟩, rfl⟩ protected theorem Infinite.prod_left (hs : s.Infinite) (ht : t.Nonempty) : (s ×ˢ t).Infinite := fun h => hs <| h.of_prod_left ht protected theorem Infinite.prod_right (ht : t.Infinite) (hs : s.Nonempty) : (s ×ˢ t).Infinite := fun h => ht <| h.of_prod_right hs protected theorem infinite_prod : (s ×ˢ t).Infinite ↔ s.Infinite ∧ t.Nonempty ∨ t.Infinite ∧ s.Nonempty := by refine ⟨fun h => ?_, ?_⟩ · simp_rw [Set.Infinite, @and_comm ¬_, ← Classical.not_imp] by_contra! exact h ((this.1 h.nonempty.snd).prod <| this.2 h.nonempty.fst) · rintro (h | h) · exact h.1.prod_left h.2 · exact h.1.prod_right h.2 theorem finite_prod : (s ×ˢ t).Finite ↔ (s.Finite ∨ t = ∅) ∧ (t.Finite ∨ s = ∅) := by simp only [← not_infinite, Set.infinite_prod, not_or, not_and_or, not_nonempty_iff_eq_empty] protected theorem Finite.offDiag {s : Set α} (hs : s.Finite) : s.offDiag.Finite := (hs.prod hs).subset s.offDiag_subset_prod protected theorem Finite.image2 (f : α → β → γ) (hs : s.Finite) (ht : t.Finite) : (image2 f s t).Finite := by have := hs.to_subtype have := ht.to_subtype apply toFinite end Prod end SetFiniteConstructors /-! ### Properties -/ theorem Finite.toFinset_prod {s : Set α} {t : Set β} (hs : s.Finite) (ht : t.Finite) : hs.toFinset ×ˢ ht.toFinset = (hs.prod ht).toFinset := Finset.ext <| by simp theorem Finite.toFinset_offDiag {s : Set α} [DecidableEq α] (hs : s.Finite) : hs.offDiag.toFinset = hs.toFinset.offDiag := Finset.ext <| by simp theorem finite_image_fst_and_snd_iff {s : Set (α × β)} : (Prod.fst '' s).Finite ∧ (Prod.snd '' s).Finite ↔ s.Finite := ⟨fun h => (h.1.prod h.2).subset fun _ h => ⟨mem_image_of_mem _ h, mem_image_of_mem _ h⟩, fun h => ⟨h.image _, h.image _⟩⟩ /-! ### Infinite sets -/ variable {s t : Set α} section Image2 variable {f : α → β → γ} {s : Set α} {t : Set β} {a : α} {b : β} protected theorem Infinite.image2_left (hs : s.Infinite) (hb : b ∈ t) (hf : InjOn (fun a => f a b) s) : (image2 f s t).Infinite := (hs.image hf).mono <| image_subset_image2_left hb protected theorem Infinite.image2_right (ht : t.Infinite) (ha : a ∈ s) (hf : InjOn (f a) t) : (image2 f s t).Infinite := (ht.image hf).mono <| image_subset_image2_right ha theorem infinite_image2 (hfs : ∀ b ∈ t, InjOn (fun a => f a b) s) (hft : ∀ a ∈ s, InjOn (f a) t) : (image2 f s t).Infinite ↔ s.Infinite ∧ t.Nonempty ∨ t.Infinite ∧ s.Nonempty := by refine ⟨fun h => Set.infinite_prod.1 ?_, ?_⟩ · rw [← image_uncurry_prod] at h exact h.of_image _ · rintro (⟨hs, b, hb⟩ | ⟨ht, a, ha⟩) · exact hs.image2_left hb (hfs _ hb) · exact ht.image2_right ha (hft _ ha) lemma finite_image2 (hfs : ∀ b ∈ t, InjOn (f · b) s) (hft : ∀ a ∈ s, InjOn (f a) t) : (image2 f s t).Finite ↔ s.Finite ∧ t.Finite ∨ s = ∅ ∨ t = ∅ := by rw [← not_infinite, infinite_image2 hfs hft] simp [not_or, -not_and, not_and_or, not_nonempty_iff_eq_empty] aesop end Image2 end Set
Subobjects.lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Algebra.Group.Subgroup.Defs import Mathlib.Algebra.Group.Submonoid.DistribMulAction import Mathlib.Algebra.Ring.Action.Basic /-! # Instances of `MulSemiringAction` for subobjects These are defined in this file as `Semiring`s are not available yet where `Submonoid` and `Subgroup` are defined. Instances for `Subsemiring` and `Subring` are provided next to the other scalar actions instances for those subobjects. -/ assert_not_exists RelIso variable {M G R : Type*} variable [Monoid M] [Group G] [Semiring R] instance (priority := low) [MulSemiringAction M R] {S : Type*} [SetLike S M] (s : S) [SubmonoidClass S M] : MulSemiringAction s R := { inferInstanceAs (DistribMulAction s R), inferInstanceAs (MulDistribMulAction s R) with } /-- A stronger version of `Submonoid.distribMulAction`. -/ instance Submonoid.mulSemiringAction [MulSemiringAction M R] (H : Submonoid M) : MulSemiringAction H R := inferInstance /-- A stronger version of `Subgroup.distribMulAction`. -/ instance Subgroup.mulSemiringAction [MulSemiringAction G R] (H : Subgroup G) : MulSemiringAction H R := inferInstance
Extend.lean
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Topology.Category.LightProfinite.AsLimit import Mathlib.Topology.Category.Profinite.Extend /-! # Extending cones in `LightProfinite` Let `(Sₙ)_{n : ℕᵒᵖ}` be a sequential inverse system of finite sets and let `S` be its limit in `Profinite`. Let `G` be a functor from `LightProfinite` to a category `C` and suppose that `G` preserves the limit described above. Suppose further that the projection maps `S ⟶ Sₙ` are epimorphic for all `n`. Then `G.obj S` is isomorphic to a limit indexed by `StructuredArrow S toLightProfinite` (see `LightProfinite.Extend.isLimitCone`). We also provide the dual result for a functor of the form `G : LightProfiniteᵒᵖ ⥤ C`. We apply this to define `LightProfinite.diagram'`, `LightProfinite.asLimitCone'`, and `LightProfinite.asLimit'`, analogues to their unprimed versions in `Mathlib/Topology/Category/LightProfinite/AsLimit.lean`, in which the indexing category is `StructuredArrow S toLightProfinite` instead of `ℕᵒᵖ`. -/ universe u open CategoryTheory Limits FintypeCat Functor attribute [local instance] FintypeCat.discreteTopology namespace LightProfinite variable {F : ℕᵒᵖ ⥤ FintypeCat.{u}} (c : Cone <| F ⋙ toLightProfinite) namespace Extend /-- Given a sequential cone in `LightProfinite` consisting of finite sets, we obtain a functor from the indexing category to `StructuredArrow c.pt toLightProfinite`. -/ @[simps] def functor : ℕᵒᵖ ⥤ StructuredArrow c.pt toLightProfinite where obj i := StructuredArrow.mk (c.π.app i) map f := StructuredArrow.homMk (F.map f) (c.w f) -- We check that the original diagram factors through `LightProfinite.Extend.functor`. example : functor c ⋙ StructuredArrow.proj c.pt toLightProfinite ≅ F := Iso.refl _ /-- Given a sequential cone in `LightProfinite` consisting of finite sets, we obtain a functor from the opposite of the indexing category to `CostructuredArrow toProfinite.op ⟨c.pt⟩`. -/ @[simps! obj map] def functorOp : ℕ ⥤ CostructuredArrow toLightProfinite.op ⟨c.pt⟩ := (functor c).rightOp ⋙ StructuredArrow.toCostructuredArrow _ _ -- We check that the opposite of the original diagram factors through `Profinite.Extend.functorOp`. example : functorOp c ⋙ CostructuredArrow.proj toLightProfinite.op ⟨c.pt⟩ ≅ F.rightOp := Iso.refl _ -- We check that `Profinite.Extend.functor` factors through `LightProfinite.Extend.functor`, -- via the equivalence `StructuredArrow.post _ _ lightToProfinite`. example : functor c ⋙ (StructuredArrow.post _ _ lightToProfinite) = Profinite.Extend.functor (lightToProfinite.mapCone c) := rfl /-- If the projection maps in the cone are epimorphic and the cone is limiting, then `LightProfinite.Extend.functor` is initial. -/ theorem functor_initial (hc : IsLimit c) [∀ i, Epi (c.π.app i)] : Initial (functor c) := by rw [initial_iff_comp_equivalence _ (StructuredArrow.post _ _ lightToProfinite)] have : ∀ i, Epi ((lightToProfinite.mapCone c).π.app i) := fun i ↦ inferInstanceAs (Epi (lightToProfinite.map (c.π.app i))) exact Profinite.Extend.functor_initial _ (isLimitOfPreserves lightToProfinite hc) /-- If the projection maps in the cone are epimorphic and the cone is limiting, then `LightProfinite.Extend.functorOp` is final. -/ theorem functorOp_final (hc : IsLimit c) [∀ i, Epi (c.π.app i)] : Final (functorOp c) := by have := functor_initial c hc have : ((StructuredArrow.toCostructuredArrow toLightProfinite c.pt)).IsEquivalence := (inferInstance : (structuredArrowOpEquivalence _ _).functor.IsEquivalence ) have : (functor c).rightOp.Final := inferInstanceAs ((opOpEquivalence ℕ).inverse ⋙ (functor c).op).Final exact Functor.final_comp (functor c).rightOp _ section Limit variable {C : Type*} [Category C] (G : LightProfinite ⥤ C) /-- Given a functor `G` from `LightProfinite` and `S : LightProfinite`, we obtain a cone on `(StructuredArrow.proj S toLightProfinite ⋙ toLightProfinite ⋙ G)` with cone point `G.obj S`. Whiskering this cone with `LightProfinite.Extend.functor c` gives `G.mapCone c` as we check in the example below. -/ def cone (S : LightProfinite) : Cone (StructuredArrow.proj S toLightProfinite ⋙ toLightProfinite ⋙ G) where pt := G.obj S π := { app := fun i ↦ G.map i.hom naturality := fun _ _ f ↦ (by have := f.w simp only [const_obj_obj, StructuredArrow.left_eq_id, const_obj_map, Category.id_comp, StructuredArrow.w] at this simp only [const_obj_obj, comp_obj, StructuredArrow.proj_obj, const_obj_map, Category.id_comp, Functor.comp_map, StructuredArrow.proj_map, ← map_comp, StructuredArrow.w]) } example : G.mapCone c = (cone G c.pt).whisker (functor c) := rfl /-- If `c` and `G.mapCone c` are limit cones and the projection maps in `c` are epimorphic, then `cone G c.pt` is a limit cone. -/ noncomputable def isLimitCone (hc : IsLimit c) [∀ i, Epi (c.π.app i)] (hc' : IsLimit <| G.mapCone c) : IsLimit (cone G c.pt) := (functor_initial c hc).isLimitWhiskerEquiv _ _ hc' end Limit section Colimit variable {C : Type*} [Category C] (G : LightProfiniteᵒᵖ ⥤ C) /-- Given a functor `G` from `LightProfiniteᵒᵖ` and `S : LightProfinite`, we obtain a cocone on `(CostructuredArrow.proj toLightProfinite.op ⟨S⟩ ⋙ toLightProfinite.op ⋙ G)` with cocone point `G.obj ⟨S⟩`. Whiskering this cocone with `LightProfinite.Extend.functorOp c` gives `G.mapCocone c.op` as we check in the example below. -/ @[simps] def cocone (S : LightProfinite) : Cocone (CostructuredArrow.proj toLightProfinite.op ⟨S⟩ ⋙ toLightProfinite.op ⋙ G) where pt := G.obj ⟨S⟩ ι := { app := fun i ↦ G.map i.hom naturality := fun _ _ f ↦ (by have := f.w simp only [op_obj, const_obj_obj, op_map, CostructuredArrow.right_eq_id, const_obj_map, Category.comp_id] at this simp only [comp_obj, CostructuredArrow.proj_obj, op_obj, const_obj_obj, Functor.comp_map, CostructuredArrow.proj_map, op_map, ← map_comp, this, const_obj_map, Category.comp_id]) } example : G.mapCocone c.op = (cocone G c.pt).whisker ((opOpEquivalence ℕ).functor ⋙ functorOp c) := rfl /-- If `c` is a limit cone, `G.mapCocone c.op` is a colimit cone and the projection maps in `c` are epimorphic, then `cocone G c.pt` is a colimit cone. -/ noncomputable def isColimitCocone (hc : IsLimit c) [∀ i, Epi (c.π.app i)] (hc' : IsColimit <| G.mapCocone c.op) : IsColimit (cocone G c.pt) := haveI := functorOp_final c hc (Functor.final_comp (opOpEquivalence ℕ).functor (functorOp c)).isColimitWhiskerEquiv _ _ hc' end Colimit end Extend open Extend section LightProfiniteAsLimit variable (S : LightProfinite.{u}) /-- A functor `StructuredArrow S toLightProfinite ⥤ FintypeCat` whose limit in `LightProfinite` is isomorphic to `S`. -/ abbrev fintypeDiagram' : StructuredArrow S toLightProfinite ⥤ FintypeCat := StructuredArrow.proj S toLightProfinite /-- An abbreviation for `S.fintypeDiagram' ⋙ toLightProfinite`. -/ abbrev diagram' : StructuredArrow S toLightProfinite ⥤ LightProfinite := S.fintypeDiagram' ⋙ toLightProfinite /-- A cone over `S.diagram'` whose cone point is `S`. -/ def asLimitCone' : Cone (S.diagram') := cone (𝟭 _) S instance (i : ℕᵒᵖ) : Epi (S.asLimitCone.π.app i) := (epi_iff_surjective _).mpr (S.proj_surjective _) /-- `S.asLimitCone'` is a limit cone. -/ noncomputable def asLimit' : IsLimit S.asLimitCone' := isLimitCone _ (𝟭 _) S.asLimit S.asLimit /-- A bundled version of `S.asLimitCone'` and `S.asLimit'`. -/ noncomputable def lim' : LimitCone S.diagram' := ⟨S.asLimitCone', S.asLimit'⟩ end LightProfiniteAsLimit end LightProfinite
Order.lean
/- Copyright (c) 2021 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson, Yaël Dillies -/ import Mathlib.Data.Finset.Lattice.Fold import Mathlib.Data.Finset.Order import Mathlib.Data.Set.Finite.Basic import Mathlib.Data.Set.Finite.Range import Mathlib.Order.Atoms /-! # Order structures on finite types This file provides order instances on fintypes. ## Computable instances On a `Fintype`, we can construct * an `OrderBot` from `SemilatticeInf`. * an `OrderTop` from `SemilatticeSup`. * a `BoundedOrder` from `Lattice`. Those are marked as `def` to avoid defeqness issues. ## Completion instances Those instances are noncomputable because the definitions of `sSup` and `sInf` use `Set.toFinset` and set membership is undecidable in general. On a `Fintype`, we can promote: * a `Lattice` to a `CompleteLattice`. * a `DistribLattice` to a `CompleteDistribLattice`. * a `LinearOrder` to a `CompleteLinearOrder`. * a `BooleanAlgebra` to a `CompleteAtomicBooleanAlgebra`. Those are marked as `def` to avoid typeclass loops. ## Concrete instances We provide a few instances for concrete types: * `Fin.completeLinearOrder` * `Bool.completeLinearOrder` * `Bool.completeBooleanAlgebra` -/ open Finset namespace Fintype variable {ι α : Type*} [Fintype ι] [Fintype α] section Nonempty variable (α) [Nonempty α] -- See note [reducible non-instances] /-- Constructs the `⊥` of a finite nonempty `SemilatticeInf`. -/ abbrev toOrderBot [SemilatticeInf α] : OrderBot α where bot := univ.inf' univ_nonempty id bot_le a := inf'_le _ <| mem_univ a -- See note [reducible non-instances] /-- Constructs the `⊤` of a finite nonempty `SemilatticeSup` -/ abbrev toOrderTop [SemilatticeSup α] : OrderTop α where top := univ.sup' univ_nonempty id le_top a := le_sup' id <| mem_univ a -- See note [reducible non-instances] /-- Constructs the `⊤` and `⊥` of a finite nonempty `Lattice`. -/ abbrev toBoundedOrder [Lattice α] : BoundedOrder α := { toOrderBot α, toOrderTop α with } end Nonempty section BoundedOrder variable (α) open scoped Classical in -- See note [reducible non-instances] /-- A finite bounded lattice is complete. -/ noncomputable abbrev toCompleteLattice [Lattice α] [BoundedOrder α] : CompleteLattice α where __ := ‹Lattice α› __ := ‹BoundedOrder α› sSup := fun s => s.toFinset.sup id sInf := fun s => s.toFinset.inf id le_sSup := fun _ _ ha => Finset.le_sup (f := id) (Set.mem_toFinset.mpr ha) sSup_le := fun _ _ ha => Finset.sup_le fun _ hb => ha _ <| Set.mem_toFinset.mp hb sInf_le := fun _ _ ha => Finset.inf_le (Set.mem_toFinset.mpr ha) le_sInf := fun _ _ ha => Finset.le_inf fun _ hb => ha _ <| Set.mem_toFinset.mp hb -- See note [reducible non-instances] /-- A finite bounded distributive lattice is completely distributive. -/ noncomputable abbrev toCompleteDistribLatticeMinimalAxioms [DistribLattice α] [BoundedOrder α] : CompleteDistribLattice.MinimalAxioms α where __ := toCompleteLattice α iInf_sup_le_sup_sInf := fun a s => by convert (Finset.inf_sup_distrib_left s.toFinset id a).ge using 1 rw [Finset.inf_eq_iInf] simp_rw [Set.mem_toFinset] rfl inf_sSup_le_iSup_inf := fun a s => by convert (Finset.sup_inf_distrib_left s.toFinset id a).le using 1 rw [Finset.sup_eq_iSup] simp_rw [Set.mem_toFinset] rfl -- See note [reducible non-instances] /-- A finite bounded distributive lattice is completely distributive. -/ noncomputable abbrev toCompleteDistribLattice [DistribLattice α] [BoundedOrder α] : CompleteDistribLattice α := .ofMinimalAxioms (toCompleteDistribLatticeMinimalAxioms _) -- See note [reducible non-instances] /-- A finite bounded linear order is complete. If the `α` is already a `BiheytingAlgebra`, then prefer to construct this instance manually using `Fintype.toCompleteLattice` instead, to avoid creating a diamond with `LinearOrder.toBiheytingAlgebra`. -/ noncomputable abbrev toCompleteLinearOrder [LinearOrder α] [BoundedOrder α] : CompleteLinearOrder α := { toCompleteLattice α, ‹LinearOrder α›, LinearOrder.toBiheytingAlgebra _ with } -- See note [reducible non-instances] /-- A finite boolean algebra is complete. -/ noncomputable abbrev toCompleteBooleanAlgebra [BooleanAlgebra α] : CompleteBooleanAlgebra α where __ := ‹BooleanAlgebra α› __ := Fintype.toCompleteDistribLattice α -- See note [reducible non-instances] /-- A finite boolean algebra is complete and atomic. -/ noncomputable abbrev toCompleteAtomicBooleanAlgebra [BooleanAlgebra α] : CompleteAtomicBooleanAlgebra α := (toCompleteBooleanAlgebra α).toCompleteAtomicBooleanAlgebra end BoundedOrder section Nonempty variable (α) [Nonempty α] -- See note [reducible non-instances] /-- A nonempty finite lattice is complete. If the lattice is already a `BoundedOrder`, then use `Fintype.toCompleteLattice` instead, as this gives definitional equality for `⊥` and `⊤`. -/ noncomputable abbrev toCompleteLatticeOfNonempty [Lattice α] : CompleteLattice α := @toCompleteLattice _ _ _ <| toBoundedOrder α -- See note [reducible non-instances] /-- A nonempty finite linear order is complete. If the linear order is already a `BoundedOrder`, then use `Fintype.toCompleteLinearOrder` instead, as this gives definitional equality for `⊥` and `⊤`. -/ noncomputable abbrev toCompleteLinearOrderOfNonempty [LinearOrder α] : CompleteLinearOrder α := @toCompleteLinearOrder _ _ _ <| toBoundedOrder α end Nonempty end Fintype /-! ### Concrete instances -/ noncomputable instance Fin.completeLinearOrder {n : ℕ} [NeZero n] : CompleteLinearOrder (Fin n) := Fintype.toCompleteLinearOrder _ noncomputable instance Bool.completeBooleanAlgebra : CompleteBooleanAlgebra Bool := Fintype.toCompleteBooleanAlgebra _ noncomputable instance Bool.completeLinearOrder : CompleteLinearOrder Bool where __ := Fintype.toCompleteLattice _ __ : BiheytingAlgebra Bool := inferInstance __ : LinearOrder Bool := inferInstance noncomputable instance Bool.completeAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra Bool := Fintype.toCompleteAtomicBooleanAlgebra _ /-! ### Directed Orders -/ variable {α : Type*} {r : α → α → Prop} [IsTrans α r] {β γ : Type*} [Nonempty γ] {f : γ → α} [Finite β] theorem Directed.finite_set_le (D : Directed r f) {s : Set γ} (hs : s.Finite) : ∃ z, ∀ i ∈ s, r (f i) (f z) := by convert D.finset_le hs.toFinset using 3; rw [Set.Finite.mem_toFinset] theorem Directed.finite_le (D : Directed r f) (g : β → γ) : ∃ z, ∀ i, r (f (g i)) (f z) := by classical obtain ⟨z, hz⟩ := D.finite_set_le (Set.finite_range g) exact ⟨z, fun i => hz (g i) ⟨i, rfl⟩⟩ variable [Nonempty α] [Preorder α] theorem Finite.exists_le [IsDirected α (· ≤ ·)] (f : β → α) : ∃ M, ∀ i, f i ≤ M := directed_id.finite_le _ theorem Finite.exists_ge [IsDirected α (· ≥ ·)] (f : β → α) : ∃ M, ∀ i, M ≤ f i := directed_id.finite_le (r := (· ≥ ·)) _ theorem Set.Finite.exists_le [IsDirected α (· ≤ ·)] {s : Set α} (hs : s.Finite) : ∃ M, ∀ i ∈ s, i ≤ M := directed_id.finite_set_le hs theorem Set.Finite.exists_ge [IsDirected α (· ≥ ·)] {s : Set α} (hs : s.Finite) : ∃ M, ∀ i ∈ s, M ≤ i := directed_id.finite_set_le (r := (· ≥ ·)) hs @[simp] theorem Finite.bddAbove_range [IsDirected α (· ≤ ·)] (f : β → α) : BddAbove (Set.range f) := by obtain ⟨M, hM⟩ := Finite.exists_le f refine ⟨M, fun a ha => ?_⟩ obtain ⟨b, rfl⟩ := ha exact hM b @[simp] theorem Finite.bddBelow_range [IsDirected α (· ≥ ·)] (f : β → α) : BddBelow (Set.range f) := by obtain ⟨M, hM⟩ := Finite.exists_ge f refine ⟨M, fun a ha => ?_⟩ obtain ⟨b, rfl⟩ := ha exact hM b
Projective.lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Kim Morrison -/ import Mathlib.Algebra.Category.ModuleCat.EpiMono import Mathlib.Algebra.Group.Shrink import Mathlib.Algebra.Module.Projective import Mathlib.CategoryTheory.Preadditive.Projective.Basic /-! # The category of `R`-modules has enough projectives. -/ universe v u w open CategoryTheory Module ModuleCat variable {R : Type u} [Ring R] (P : ModuleCat.{v} R) instance ModuleCat.projective_of_categoryTheory_projective [Module.Projective R P] : CategoryTheory.Projective P := by refine ⟨fun E X epi => ?_⟩ obtain ⟨f, h⟩ := Module.projective_lifting_property X.hom E.hom ((ModuleCat.epi_iff_surjective _).mp epi) exact ⟨ofHom f, hom_ext h⟩ instance ModuleCat.projective_of_module_projective [Small.{v} R] [Projective P] : Module.Projective R P := by refine Module.Projective.of_lifting_property ?_ intro _ _ _ _ _ _ f g s have : Epi (↟f) := (ModuleCat.epi_iff_surjective (↟f)).mpr s exact ⟨(Projective.factorThru (↟g) (↟f)).hom, ModuleCat.hom_ext_iff.mp <| Projective.factorThru_comp (↟g) (↟f)⟩ /-- The categorical notion of projective object agrees with the explicit module-theoretic notion. -/ theorem IsProjective.iff_projective [Small.{v} R] (P : Type v) [AddCommGroup P] [Module R P] : Module.Projective R P ↔ Projective (of R P) := ⟨fun _ => (of R P).projective_of_categoryTheory_projective, fun _ => (of R P).projective_of_module_projective⟩ namespace ModuleCat variable {M : ModuleCat.{v} R} -- We transport the corresponding result from `Module.Projective`. /-- Modules that have a basis are projective. -/ theorem projective_of_free {ι : Type w} (b : Basis ι R M) : Projective M := have : Module.Projective R M := Module.Projective.of_basis b M.projective_of_categoryTheory_projective /-- The category of modules has enough projectives, since every module is a quotient of a free module. -/ instance enoughProjectives [Small.{v} R] : EnoughProjectives (ModuleCat.{v} R) where presentation M := let e : Basis M R (M →₀ Shrink.{v} R) := ⟨Finsupp.mapRange.linearEquiv (Shrink.linearEquiv R R)⟩ ⟨{p := ModuleCat.of R (M →₀ Shrink.{v} R) projective := projective_of_free e f := ofHom <| e.constr ℕ _root_.id epi := by rw [epi_iff_range_eq_top, LinearMap.range_eq_top] refine fun m ↦ ⟨Finsupp.single m 1, ?_⟩ simp [e, Basis.constr_apply] }⟩ end ModuleCat
LogDeriv.lean
/- Copyright (c) 2024 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import Mathlib.Analysis.Calculus.Deriv.ZPow /-! # Logarithmic Derivatives We define the logarithmic derivative of a function f as `deriv f / f`. We then prove some basic facts about this, including how it changes under multiplication and composition. -/ noncomputable section open Filter Function open scoped Topology variable {𝕜 𝕜' : Type*} [NontriviallyNormedField 𝕜] [NontriviallyNormedField 𝕜'] [NormedAlgebra 𝕜 𝕜'] /-- The logarithmic derivative of a function defined as `deriv f /f`. Note that it will be zero at `x` if `f` is not DifferentiableAt `x`. -/ def logDeriv (f : 𝕜 → 𝕜') := deriv f / f theorem logDeriv_apply (f : 𝕜 → 𝕜') (x : 𝕜) : logDeriv f x = deriv f x / f x := rfl lemma logDeriv_eq_zero_of_not_differentiableAt (f : 𝕜 → 𝕜') (x : 𝕜) (h : ¬DifferentiableAt 𝕜 f x) : logDeriv f x = 0 := by simp only [logDeriv_apply, deriv_zero_of_not_differentiableAt h, zero_div] @[simp] theorem logDeriv_id (x : 𝕜) : logDeriv id x = 1 / x := by simp [logDeriv_apply] @[simp] theorem logDeriv_id' (x : 𝕜) : logDeriv (·) x = 1 / x := logDeriv_id x @[simp] theorem logDeriv_const (a : 𝕜') : logDeriv (fun _ : 𝕜 ↦ a) = 0 := by ext simp [logDeriv_apply] theorem logDeriv_mul {f g : 𝕜 → 𝕜'} (x : 𝕜) (hf : f x ≠ 0) (hg : g x ≠ 0) (hdf : DifferentiableAt 𝕜 f x) (hdg : DifferentiableAt 𝕜 g x) : logDeriv (fun z => f z * g z) x = logDeriv f x + logDeriv g x := by simp only [logDeriv_apply] field_simp [mul_comm] theorem logDeriv_div {f g : 𝕜 → 𝕜'} (x : 𝕜) (hf : f x ≠ 0) (hg : g x ≠ 0) (hdf : DifferentiableAt 𝕜 f x) (hdg : DifferentiableAt 𝕜 g x) : logDeriv (fun z => f z / g z) x = logDeriv f x - logDeriv g x := by simp only [logDeriv_apply] field_simp [mul_comm] ring theorem logDeriv_mul_const {f : 𝕜 → 𝕜'} (x : 𝕜) (a : 𝕜') (ha : a ≠ 0) : logDeriv (fun z => f z * a) x = logDeriv f x := by simp only [logDeriv_apply, deriv_mul_const_field, mul_div_mul_right _ _ ha] theorem logDeriv_const_mul {f : 𝕜 → 𝕜'} (x : 𝕜) (a : 𝕜') (ha : a ≠ 0) : logDeriv (fun z => a * f z) x = logDeriv f x := by simp only [logDeriv_apply, deriv_const_mul_field, mul_div_mul_left _ _ ha] /-- The logarithmic derivative of a finite product is the sum of the logarithmic derivatives. -/ theorem logDeriv_prod {ι : Type*} (s : Finset ι) (f : ι → 𝕜 → 𝕜') (x : 𝕜) (hf : ∀ i ∈ s, f i x ≠ 0) (hd : ∀ i ∈ s, DifferentiableAt 𝕜 (f i) x) : logDeriv (∏ i ∈ s, f i ·) x = ∑ i ∈ s, logDeriv (f i) x := by induction s using Finset.cons_induction with | empty => simp | cons a s ha ih => rw [Finset.forall_mem_cons] at hf hd simp_rw [Finset.prod_cons, Finset.sum_cons] rw [logDeriv_mul, ih hf.2 hd.2] · exact hf.1 · simpa [Finset.prod_eq_zero_iff] using hf.2 · exact hd.1 · exact .fun_finset_prod hd.2 lemma logDeriv_fun_zpow {f : 𝕜 → 𝕜'} {x : 𝕜} (hdf : DifferentiableAt 𝕜 f x) (n : ℤ) : logDeriv (f · ^ n) x = n * logDeriv f x := by rcases eq_or_ne n 0 with rfl | hn; · simp rcases eq_or_ne (f x) 0 with hf | hf · simp [logDeriv_apply, zero_zpow, *] · rw [logDeriv_apply, ← comp_def (·^n), deriv_comp _ (differentiableAt_zpow.2 <| .inl hf) hdf, deriv_zpow, logDeriv_apply] field_simp [zpow_ne_zero, zpow_sub_one₀ hf] ring lemma logDeriv_fun_pow {f : 𝕜 → 𝕜'} {x : 𝕜} (hdf : DifferentiableAt 𝕜 f x) (n : ℕ) : logDeriv (f · ^ n) x = n * logDeriv f x := mod_cast logDeriv_fun_zpow hdf n @[simp] lemma logDeriv_zpow (x : 𝕜) (n : ℤ) : logDeriv (· ^ n) x = n / x := by rw [logDeriv_fun_zpow (by fun_prop), logDeriv_id', mul_one_div] @[simp] lemma logDeriv_pow (x : 𝕜) (n : ℕ) : logDeriv (· ^ n) x = n / x := mod_cast logDeriv_zpow x n @[simp] lemma logDeriv_inv (x : 𝕜) : logDeriv (·⁻¹) x = -1 / x := by simpa using logDeriv_zpow x (-1) theorem logDeriv_comp {f : 𝕜' → 𝕜'} {g : 𝕜 → 𝕜'} {x : 𝕜} (hf : DifferentiableAt 𝕜' f (g x)) (hg : DifferentiableAt 𝕜 g x) : logDeriv (f ∘ g) x = logDeriv f (g x) * deriv g x := by simp only [logDeriv, Pi.div_apply, deriv_comp _ hf hg, comp_apply] ring
Schur.lean
/- Copyright (c) 2020 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Kim Morrison -/ import Mathlib.Algebra.Group.Ext import Mathlib.CategoryTheory.Simple import Mathlib.CategoryTheory.Linear.Basic import Mathlib.CategoryTheory.Endomorphism import Mathlib.FieldTheory.IsAlgClosed.Spectrum /-! # Schur's lemma We first prove the part of Schur's Lemma that holds in any preadditive category with kernels, that any nonzero morphism between simple objects is an isomorphism. Second, we prove Schur's lemma for `𝕜`-linear categories with finite dimensional hom spaces, over an algebraically closed field `𝕜`: the hom space `X ⟶ Y` between simple objects `X` and `Y` is at most one dimensional, and is 1-dimensional iff `X` and `Y` are isomorphic. -/ namespace CategoryTheory open CategoryTheory.Limits variable {C : Type*} [Category C] variable [Preadditive C] -- See also `epi_of_nonzero_to_simple`, which does not require `Preadditive C`. theorem mono_of_nonzero_from_simple [HasKernels C] {X Y : C} [Simple X] {f : X ⟶ Y} (w : f ≠ 0) : Mono f := Preadditive.mono_of_kernel_zero (kernel_zero_of_nonzero_from_simple w) /-- The part of **Schur's lemma** that holds in any preadditive category with kernels: that a nonzero morphism between simple objects is an isomorphism. -/ theorem isIso_of_hom_simple [HasKernels C] {X Y : C} [Simple X] [Simple Y] {f : X ⟶ Y} (w : f ≠ 0) : IsIso f := haveI := mono_of_nonzero_from_simple w isIso_of_mono_of_nonzero w /-- As a corollary of Schur's lemma for preadditive categories, any morphism between simple objects is (exclusively) either an isomorphism or zero. -/ theorem isIso_iff_nonzero [HasKernels C] {X Y : C} [Simple X] [Simple Y] (f : X ⟶ Y) : IsIso f ↔ f ≠ 0 := ⟨fun I => by intro h apply id_nonzero X simp only [← IsIso.hom_inv_id f, h, zero_comp], fun w => isIso_of_hom_simple w⟩ open scoped Classical in /-- In any preadditive category with kernels, the endomorphisms of a simple object form a division ring. -/ noncomputable instance [HasKernels C] {X : C} [Simple X] : DivisionRing (End X) where inv f := if h : f = 0 then 0 else haveI := isIso_of_hom_simple h; inv f exists_pair_ne := ⟨𝟙 X, 0, id_nonzero _⟩ inv_zero := dif_pos rfl mul_inv_cancel f hf := by dsimp rw [dif_neg hf] haveI := isIso_of_hom_simple hf exact IsIso.inv_hom_id f nnqsmul := _ nnqsmul_def := fun _ _ => rfl qsmul := _ qsmul_def := fun _ _ => rfl open Module section variable (𝕜 : Type*) [DivisionRing 𝕜] /-- Part of **Schur's lemma** for `𝕜`-linear categories: the hom space between two non-isomorphic simple objects is 0-dimensional. -/ theorem finrank_hom_simple_simple_eq_zero_of_not_iso [HasKernels C] [Linear 𝕜 C] {X Y : C} [Simple X] [Simple Y] (h : (X ≅ Y) → False) : finrank 𝕜 (X ⟶ Y) = 0 := haveI := subsingleton_of_forall_eq (0 : X ⟶ Y) fun f => by have p := not_congr (isIso_iff_nonzero f) simp only [Classical.not_not, Ne] at p exact p.mp fun _ => h (asIso f) finrank_zero_of_subsingleton end variable (𝕜 : Type*) [Field 𝕜] variable [IsAlgClosed 𝕜] [Linear 𝕜 C] -- Porting note: the defeq issue in lean3 described below is no longer a problem in Lean4. -- In the proof below we have some difficulty using `I : FiniteDimensional 𝕜 (X ⟶ X)` -- where we need a `FiniteDimensional 𝕜 (End X)`. -- These are definitionally equal, but without eta reduction Lean can't see this. -- To get around this, we use `convert I`, -- then check the various instances agree field-by-field, -- We prove this with the explicit `isIso_iff_nonzero` assumption, -- rather than just `[Simple X]`, as this form is useful for -- Müger's formulation of semisimplicity. /-- An auxiliary lemma for Schur's lemma. If `X ⟶ X` is finite dimensional, and every nonzero endomorphism is invertible, then `X ⟶ X` is 1-dimensional. -/ theorem finrank_endomorphism_eq_one {X : C} (isIso_iff_nonzero : ∀ f : X ⟶ X, IsIso f ↔ f ≠ 0) [I : FiniteDimensional 𝕜 (X ⟶ X)] : finrank 𝕜 (X ⟶ X) = 1 := by have id_nonzero := (isIso_iff_nonzero (𝟙 X)).mp (by infer_instance) refine finrank_eq_one (𝟙 X) id_nonzero ?_ intro f have : Nontrivial (End X) := nontrivial_of_ne _ _ id_nonzero have : FiniteDimensional 𝕜 (End X) := I obtain ⟨c, nu⟩ := spectrum.nonempty_of_isAlgClosed_of_finiteDimensional 𝕜 (End.of f) use c rw [spectrum.mem_iff, IsUnit.sub_iff, isUnit_iff_isIso, isIso_iff_nonzero, Ne, Classical.not_not, sub_eq_zero, Algebra.algebraMap_eq_smul_one] at nu exact nu.symm variable [HasKernels C] /-- **Schur's lemma** for endomorphisms in `𝕜`-linear categories. -/ theorem finrank_endomorphism_simple_eq_one (X : C) [Simple X] [FiniteDimensional 𝕜 (X ⟶ X)] : finrank 𝕜 (X ⟶ X) = 1 := finrank_endomorphism_eq_one 𝕜 isIso_iff_nonzero theorem endomorphism_simple_eq_smul_id {X : C} [Simple X] [FiniteDimensional 𝕜 (X ⟶ X)] (f : X ⟶ X) : ∃ c : 𝕜, c • 𝟙 X = f := (finrank_eq_one_iff_of_nonzero' (𝟙 X) (id_nonzero X)).mp (finrank_endomorphism_simple_eq_one 𝕜 X) f /-- Endomorphisms of a simple object form a field if they are finite dimensional. This can't be an instance as `𝕜` would be undetermined. -/ noncomputable def fieldEndOfFiniteDimensional (X : C) [Simple X] [I : FiniteDimensional 𝕜 (X ⟶ X)] : Field (End X) := by classical exact { (inferInstance : DivisionRing (End X)) with mul_comm := fun f g => by obtain ⟨c, rfl⟩ := endomorphism_simple_eq_smul_id 𝕜 f obtain ⟨d, rfl⟩ := endomorphism_simple_eq_smul_id 𝕜 g simp [← mul_smul, mul_comm c d] } -- There is a symmetric argument that uses `[FiniteDimensional 𝕜 (Y ⟶ Y)]` instead, -- but we don't bother proving that here. /-- **Schur's lemma** for `𝕜`-linear categories: if hom spaces are finite dimensional, then the hom space between simples is at most 1-dimensional. See `finrank_hom_simple_simple_eq_one_iff` and `finrank_hom_simple_simple_eq_zero_iff` below for the refinements when we know whether or not the simples are isomorphic. -/ theorem finrank_hom_simple_simple_le_one (X Y : C) [FiniteDimensional 𝕜 (X ⟶ X)] [Simple X] [Simple Y] : finrank 𝕜 (X ⟶ Y) ≤ 1 := by obtain (h|h) := subsingleton_or_nontrivial (X ⟶ Y) · rw [finrank_zero_of_subsingleton] exact zero_le_one · obtain ⟨f, nz⟩ := (nontrivial_iff_exists_ne 0).mp h haveI fi := (isIso_iff_nonzero f).mpr nz refine finrank_le_one f ?_ intro g obtain ⟨c, w⟩ := endomorphism_simple_eq_smul_id 𝕜 (g ≫ inv f) exact ⟨c, by simpa using w =≫ f⟩ theorem finrank_hom_simple_simple_eq_one_iff (X Y : C) [FiniteDimensional 𝕜 (X ⟶ X)] [FiniteDimensional 𝕜 (X ⟶ Y)] [Simple X] [Simple Y] : finrank 𝕜 (X ⟶ Y) = 1 ↔ Nonempty (X ≅ Y) := by fconstructor · intro h rw [finrank_eq_one_iff'] at h obtain ⟨f, nz, -⟩ := h rw [← isIso_iff_nonzero] at nz exact ⟨asIso f⟩ · rintro ⟨f⟩ have le_one := finrank_hom_simple_simple_le_one 𝕜 X Y have zero_lt : 0 < finrank 𝕜 (X ⟶ Y) := finrank_pos_iff_exists_ne_zero.mpr ⟨f.hom, (isIso_iff_nonzero f.hom).mp inferInstance⟩ omega theorem finrank_hom_simple_simple_eq_zero_iff (X Y : C) [FiniteDimensional 𝕜 (X ⟶ X)] [FiniteDimensional 𝕜 (X ⟶ Y)] [Simple X] [Simple Y] : finrank 𝕜 (X ⟶ Y) = 0 ↔ IsEmpty (X ≅ Y) := by rw [← not_nonempty_iff, ← not_congr (finrank_hom_simple_simple_eq_one_iff 𝕜 X Y)] have := finrank_hom_simple_simple_le_one 𝕜 X Y omega open scoped Classical in theorem finrank_hom_simple_simple (X Y : C) [∀ X Y : C, FiniteDimensional 𝕜 (X ⟶ Y)] [Simple X] [Simple Y] : finrank 𝕜 (X ⟶ Y) = if Nonempty (X ≅ Y) then 1 else 0 := by split_ifs with h · exact (finrank_hom_simple_simple_eq_one_iff 𝕜 X Y).2 h · exact (finrank_hom_simple_simple_eq_zero_iff 𝕜 X Y).2 (not_nonempty_iff.mp h) end CategoryTheory
tuple.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. From mathcomp Require Import seq choice fintype path. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. (******************************************************************************) (* This file defines tuples, i.e., sequences with a fixed (known) length, *) (* and sequences with bounded length. *) (* For tuples we define: *) (* n.-tuple T == the type of n-tuples of elements of type T *) (* [tuple of s] == the tuple whose underlying sequence (value) is s *) (* The size of s must be known: specifically, Coq must *) (* be able to infer a Canonical tuple projecting on s. *) (* in_tuple s == the (size s).-tuple with value s *) (* [tuple] == the empty tuple *) (* [tuple x1; ..; xn] == the explicit n.-tuple <x1; ..; xn> *) (* [tuple E | i < n] == the n.-tuple with general term E (i : 'I_n is bound *) (* in E) *) (* tcast Emn t == the m.-tuple t cast as an n.-tuple using Emn : m = n *) (* As n.-tuple T coerces to seq t, all seq operations (size, nth, ...) can be *) (* applied to t : n.-tuple T; we provide a few specialized instances when *) (* avoids the need for a default value. *) (* tsize t == the size of t (the n in n.-tuple T) *) (* tnth t i == the i'th component of t, where i : 'I_n *) (* [tnth t i] == the i'th component of t, where i : nat and i < n *) (* is convertible to true *) (* thead t == the first element of t, when n is m.+1 for some m *) (* For bounded sequences we define: *) (* n.-bseq T == the type of bounded sequences of elements of type T, *) (* the length of a bounded sequence is smaller or *) (* or equal to n *) (* [bseq of s] == the bounded sequence whose underlying value is s *) (* The size of s must be known. *) (* in_bseq s == the (size s).-bseq with value s *) (* [bseq] == the empty bseq *) (* insub_bseq n s == the n.-bseq of value s if size s <= n, else [bseq] *) (* [bseq x1; ..; xn] == the explicit n.-bseq <x1; ..; xn> *) (* cast_bseq Emn t == the m.-bseq t cast as an n.-tuple using Emn : m = n *) (* widen_bseq Lmn t == the m.-bseq t cast as an n.-tuple using Lmn : m <= n *) (* Most seq constructors (cons, behead, cat, rcons, belast, take, drop, rot, *) (* rotr, map, ...) can be used to build tuples and bounded sequences via *) (* the [tuple of s] and [bseq of s] constructs respectively. *) (* Tuples and bounded sequences are actually instances of subType of seq, *) (* and inherit all combinatorial structures, including the finType structure. *) (* Some useful lemmas and definitions: *) (* tuple0 : [tuple] is the only 0.-tuple *) (* bseq0 : [bseq] is the only 0.-bseq *) (* tupleP : elimination view for n.+1.-tuple *) (* ord_tuple n : the n.-tuple of all i : 'I_n *) (******************************************************************************) Section TupleDef. Variables (n : nat) (T : Type). Structure tuple_of : Type := Tuple {tval :> seq T; _ : size tval == n}. HB.instance Definition _ := [isSub for tval]. Implicit Type t : tuple_of. Definition tsize of tuple_of := n. Lemma size_tuple t : size t = n. Proof. exact: (eqP (valP t)). Qed. Lemma tnth_default t : 'I_n -> T. Proof. by rewrite -(size_tuple t); case: (tval t) => [|//] []. Qed. Definition tnth t i := nth (tnth_default t i) t i. Lemma tnth_nth x t i : tnth t i = nth x t i. Proof. by apply: set_nth_default; rewrite size_tuple. Qed. Lemma tnth_onth x t i : tnth t i = x <-> onth t i = Some x. Proof. rewrite (tnth_nth x) onthE (nth_map x) ?size_tuple//. by split; [move->|case]. Qed. Lemma map_tnth_enum t : map (tnth t) (enum 'I_n) = t. Proof. case def_t: {-}(val t) => [|x0 t']. by rewrite [enum _]size0nil // -cardE card_ord -(size_tuple t) def_t. apply: (@eq_from_nth _ x0) => [|i]; rewrite size_map. by rewrite -cardE size_tuple card_ord. move=> lt_i_e; have lt_i_n: i < n by rewrite -cardE card_ord in lt_i_e. by rewrite (nth_map (Ordinal lt_i_n)) // (tnth_nth x0) nth_enum_ord. Qed. Lemma eq_from_tnth t1 t2 : tnth t1 =1 tnth t2 -> t1 = t2. Proof. by move/eq_map=> eq_t; apply: val_inj; rewrite /= -!map_tnth_enum eq_t. Qed. Definition tuple t mkT : tuple_of := mkT (let: Tuple _ tP := t return size t == n in tP). Lemma tupleE t : tuple (fun sP => @Tuple t sP) = t. Proof. by case: t. Qed. End TupleDef. Notation "n .-tuple" := (tuple_of n) (format "n .-tuple") : type_scope. Notation "{ 'tuple' n 'of' T }" := (n.-tuple T : predArgType) (only parsing) : type_scope. Notation "[ 'tuple' 'of' s ]" := (tuple (fun sP => @Tuple _ _ s sP)) (format "[ 'tuple' 'of' s ]") : form_scope. Notation "[ 'tnth' t i ]" := (tnth t (@Ordinal (tsize t) i (erefl true))) (t, i at level 8, format "[ 'tnth' t i ]") : form_scope. Canonical nil_tuple T := Tuple (isT : @size T [::] == 0). Canonical cons_tuple n T x (t : n.-tuple T) := Tuple (valP t : size (x :: t) == n.+1). Notation "[ 'tuple' x1 ; .. ; xn ]" := [tuple of x1 :: .. [:: xn] ..] (format "[ 'tuple' '[' x1 ; '/' .. ; '/' xn ']' ]") : form_scope. Notation "[ 'tuple' ]" := [tuple of [::]] (format "[ 'tuple' ]") : form_scope. Section CastTuple. Variable T : Type. Definition in_tuple (s : seq T) := Tuple (eqxx (size s)). Definition tcast m n (eq_mn : m = n) t := let: erefl in _ = n := eq_mn return n.-tuple T in t. Lemma tcastE m n (eq_mn : m = n) t i : tnth (tcast eq_mn t) i = tnth t (cast_ord (esym eq_mn) i). Proof. by case: n / eq_mn in i *; rewrite cast_ord_id. Qed. Lemma tcast_id n (eq_nn : n = n) t : tcast eq_nn t = t. Proof. by rewrite (eq_axiomK eq_nn). Qed. Lemma tcastK m n (eq_mn : m = n) : cancel (tcast eq_mn) (tcast (esym eq_mn)). Proof. by case: n / eq_mn. Qed. Lemma tcastKV m n (eq_mn : m = n) : cancel (tcast (esym eq_mn)) (tcast eq_mn). Proof. by case: n / eq_mn. Qed. Lemma tcast_trans m n p (eq_mn : m = n) (eq_np : n = p) t: tcast (etrans eq_mn eq_np) t = tcast eq_np (tcast eq_mn t). Proof. by case: n / eq_mn eq_np; case: p /. Qed. Lemma tvalK n (t : n.-tuple T) : in_tuple t = tcast (esym (size_tuple t)) t. Proof. by apply: val_inj => /=; case: _ / (esym _). Qed. Lemma val_tcast m n (eq_mn : m = n) (t : m.-tuple T) : tcast eq_mn t = t :> seq T. Proof. by case: n / eq_mn. Qed. Lemma in_tupleE s : in_tuple s = s :> seq T. Proof. by []. Qed. End CastTuple. Section SeqTuple. Variables (n m : nat) (T U rT : Type). Implicit Type t : n.-tuple T. Lemma rcons_tupleP t x : size (rcons t x) == n.+1. Proof. by rewrite size_rcons size_tuple. Qed. Canonical rcons_tuple t x := Tuple (rcons_tupleP t x). Lemma nseq_tupleP x : @size T (nseq n x) == n. Proof. by rewrite size_nseq. Qed. Canonical nseq_tuple x := Tuple (nseq_tupleP x). Lemma iota_tupleP : size (iota m n) == n. Proof. by rewrite size_iota. Qed. Canonical iota_tuple := Tuple iota_tupleP. Lemma behead_tupleP t : size (behead t) == n.-1. Proof. by rewrite size_behead size_tuple. Qed. Canonical behead_tuple t := Tuple (behead_tupleP t). Lemma belast_tupleP x t : size (belast x t) == n. Proof. by rewrite size_belast size_tuple. Qed. Canonical belast_tuple x t := Tuple (belast_tupleP x t). Lemma cat_tupleP t (u : m.-tuple T) : size (t ++ u) == n + m. Proof. by rewrite size_cat !size_tuple. Qed. Canonical cat_tuple t u := Tuple (cat_tupleP t u). Lemma take_tupleP t : size (take m t) == minn m n. Proof. by rewrite size_take size_tuple eqxx. Qed. Canonical take_tuple t := Tuple (take_tupleP t). Lemma drop_tupleP t : size (drop m t) == n - m. Proof. by rewrite size_drop size_tuple. Qed. Canonical drop_tuple t := Tuple (drop_tupleP t). Lemma rev_tupleP t : size (rev t) == n. Proof. by rewrite size_rev size_tuple. Qed. Canonical rev_tuple t := Tuple (rev_tupleP t). Lemma rot_tupleP t : size (rot m t) == n. Proof. by rewrite size_rot size_tuple. Qed. Canonical rot_tuple t := Tuple (rot_tupleP t). Lemma rotr_tupleP t : size (rotr m t) == n. Proof. by rewrite size_rotr size_tuple. Qed. Canonical rotr_tuple t := Tuple (rotr_tupleP t). Lemma map_tupleP f t : @size rT (map f t) == n. Proof. by rewrite size_map size_tuple. Qed. Canonical map_tuple f t := Tuple (map_tupleP f t). Lemma scanl_tupleP f x t : @size rT (scanl f x t) == n. Proof. by rewrite size_scanl size_tuple. Qed. Canonical scanl_tuple f x t := Tuple (scanl_tupleP f x t). Lemma pairmap_tupleP f x t : @size rT (pairmap f x t) == n. Proof. by rewrite size_pairmap size_tuple. Qed. Canonical pairmap_tuple f x t := Tuple (pairmap_tupleP f x t). Lemma zip_tupleP t (u : n.-tuple U) : size (zip t u) == n. Proof. by rewrite size1_zip !size_tuple. Qed. Canonical zip_tuple t u := Tuple (zip_tupleP t u). Lemma allpairs_tupleP f t (u : m.-tuple U) : @size rT (allpairs f t u) == n * m. Proof. by rewrite size_allpairs !size_tuple. Qed. Canonical allpairs_tuple f t u := Tuple (allpairs_tupleP f t u). Lemma sort_tupleP r t : size (sort r t) == n. Proof. by rewrite size_sort size_tuple. Qed. Canonical sort_tuple r t := Tuple (sort_tupleP r t). Definition thead (u : n.+1.-tuple T) := tnth u ord0. Lemma tnth0 x t : tnth [tuple of x :: t] ord0 = x. Proof. by []. Qed. Lemma tnthS x t i : tnth [tuple of x :: t] (lift ord0 i) = tnth t i. Proof. by rewrite (tnth_nth (tnth_default t i)). Qed. Lemma theadE x t : thead [tuple of x :: t] = x. Proof. by []. Qed. Lemma tuple0 : all_equal_to ([tuple] : 0.-tuple T). Proof. by move=> t; apply: val_inj; case: t => [[]]. Qed. Variant tuple1_spec : n.+1.-tuple T -> Type := Tuple1spec x t : tuple1_spec [tuple of x :: t]. Lemma tupleP u : tuple1_spec u. Proof. case: u => [[|x s] //= sz_s]; pose t := @Tuple n _ s sz_s. by rewrite (_ : Tuple _ = [tuple of x :: t]) //; apply: val_inj. Qed. Lemma tnth_map f t i : tnth [tuple of map f t] i = f (tnth t i) :> rT. Proof. by apply: nth_map; rewrite size_tuple. Qed. Lemma tnth_nseq x i : tnth [tuple of nseq n x] i = x. Proof. by rewrite !(tnth_nth (tnth_default (nseq_tuple x) i)) nth_nseq ltn_ord. Qed. End SeqTuple. Lemma tnth_behead n T (t : n.+1.-tuple T) i : tnth [tuple of behead t] i = tnth t (inord i.+1). Proof. by case/tupleP: t => x t; rewrite !(tnth_nth x) inordK ?ltnS. Qed. Lemma tuple_eta n T (t : n.+1.-tuple T) : t = [tuple of thead t :: behead t]. Proof. by case/tupleP: t => x t; apply: val_inj. Qed. Section tnth_shift. Context {T : Type} {n1 n2} (t1 : n1.-tuple T) (t2 : n2.-tuple T). Lemma tnth_lshift i : tnth [tuple of t1 ++ t2] (lshift n2 i) = tnth t1 i. Proof. have x0 := tnth_default t1 i; rewrite !(tnth_nth x0). by rewrite nth_cat size_tuple /= ltn_ord. Qed. Lemma tnth_rshift j : tnth [tuple of t1 ++ t2] (rshift n1 j) = tnth t2 j. Proof. have x0 := tnth_default t2 j; rewrite !(tnth_nth x0). by rewrite nth_cat size_tuple ltnNge leq_addr /= addKn. Qed. End tnth_shift. Section TupleQuantifiers. Variables (n : nat) (T : Type). Implicit Types (a : pred T) (t : n.-tuple T). Lemma forallb_tnth a t : [forall i, a (tnth t i)] = all a t. Proof. apply: negb_inj; rewrite -has_predC -has_map negb_forall. apply/existsP/(has_nthP true) => [[i a_t_i] | [i lt_i_n a_t_i]]. by exists i; rewrite ?size_tuple // -tnth_nth tnth_map. rewrite size_tuple in lt_i_n; exists (Ordinal lt_i_n). by rewrite -tnth_map (tnth_nth true). Qed. Lemma existsb_tnth a t : [exists i, a (tnth t i)] = has a t. Proof. by apply: negb_inj; rewrite negb_exists -all_predC -forallb_tnth. Qed. Lemma all_tnthP a t : reflect (forall i, a (tnth t i)) (all a t). Proof. by rewrite -forallb_tnth; apply: forallP. Qed. Lemma has_tnthP a t : reflect (exists i, a (tnth t i)) (has a t). Proof. by rewrite -existsb_tnth; apply: existsP. Qed. End TupleQuantifiers. Arguments all_tnthP {n T a t}. Arguments has_tnthP {n T a t}. Section EqTuple. Variables (n : nat) (T : eqType). HB.instance Definition _ : hasDecEq (n.-tuple T) := [Equality of n.-tuple T by <:]. Canonical tuple_predType := PredType (pred_of_seq : n.-tuple T -> pred T). Lemma eqEtuple (t1 t2 : n.-tuple T) : (t1 == t2) = [forall i, tnth t1 i == tnth t2 i]. Proof. by apply/eqP/'forall_eqP => [->|/eq_from_tnth]. Qed. Lemma memtE (t : n.-tuple T) : mem t = mem (tval t). Proof. by []. Qed. Lemma mem_tnth i (t : n.-tuple T) : tnth t i \in t. Proof. by rewrite mem_nth ?size_tuple. Qed. Lemma memt_nth x0 (t : n.-tuple T) i : i < n -> nth x0 t i \in t. Proof. by move=> i_lt_n; rewrite mem_nth ?size_tuple. Qed. Lemma tnthP (t : n.-tuple T) x : reflect (exists i, x = tnth t i) (x \in t). Proof. apply: (iffP idP) => [/(nthP x)[i ltin <-] | [i ->]]; last exact: mem_tnth. by rewrite size_tuple in ltin; exists (Ordinal ltin); rewrite (tnth_nth x). Qed. Lemma seq_tnthP (s : seq T) x : x \in s -> {i | x = tnth (in_tuple s) i}. Proof. move=> s_x; pose i := index x s; have lt_i: i < size s by rewrite index_mem. by exists (Ordinal lt_i); rewrite (tnth_nth x) nth_index. Qed. Lemma tuple_uniqP (t : n.-tuple T) : reflect (injective (tnth t)) (uniq t). Proof. case: {+}n => [|m] in t *; first by rewrite tuple0; constructor => -[]. pose x0 := tnth t ord0; apply/(equivP (uniqP x0)); split=> tinj i j. by rewrite !(tnth_nth x0) => /tinj/val_inj; apply; rewrite size_tuple inE. rewrite !size_tuple !inE => im jm; have := tinj (Ordinal im) (Ordinal jm). by rewrite !(tnth_nth x0) => /[apply]-[]. Qed. End EqTuple. HB.instance Definition _ n (T : choiceType) := [Choice of n.-tuple T by <:]. HB.instance Definition _ n (T : countType) := [Countable of n.-tuple T by <:]. Module Type FinTupleSig. Section FinTupleSig. Variables (n : nat) (T : finType). Parameter enum : seq (n.-tuple T). Axiom enumP : Finite.axiom enum. Axiom size_enum : size enum = #|T| ^ n. End FinTupleSig. End FinTupleSig. Module FinTuple : FinTupleSig. Section FinTuple. Variables (n : nat) (T : finType). Definition enum : seq (n.-tuple T) := let extend e := flatten (codom (fun x => map (cons x) e)) in pmap insub (iter n extend [::[::]]). Lemma enumP : Finite.axiom enum. Proof. case=> /= t t_n; rewrite -(count_map _ (pred1 t)) (pmap_filter (insubK _)). rewrite count_filter -(@eq_count _ (pred1 t)) => [|s /=]; last first. by rewrite isSome_insub; case: eqP=> // ->. elim: n t t_n => [|m IHm] [|x t] //= {}/IHm; move: (iter m _ _) => em IHm. transitivity (x \in T : nat); rewrite // -mem_enum codomE. elim: (fintype.enum T) (enum_uniq T) => //= y e IHe /andP[/negPf ney]. rewrite count_cat count_map inE /preim /= [in LHS]/eq_op /= eq_sym => /IHe->. by case: eqP => [->|_]; rewrite ?(ney, count_pred0, IHm). Qed. Lemma size_enum : size enum = #|T| ^ n. Proof. rewrite /= cardE size_pmap_sub; elim: n => //= m IHm. rewrite expnS /codom /image_mem; elim: {2 3}(fintype.enum T) => //= x e IHe. by rewrite count_cat {}IHe count_map IHm. Qed. End FinTuple. End FinTuple. Section UseFinTuple. Variables (n : nat) (T : finType). (* tuple_finMixin could, in principle, be made Canonical to allow for folding *) (* Finite.enum of a finite tuple type (see comments around eqE in eqtype.v), *) (* but in practice it will not work because the mixin_enum projector *) (* has been buried under an opaque alias, to avoid some performance issues *) (* during type inference. *) HB.instance Definition _ := isFinite.Build (n.-tuple T) (@FinTuple.enumP n T). Lemma card_tuple : #|{:n.-tuple T}| = #|T| ^ n. Proof. by rewrite [#|_|]cardT enumT unlock FinTuple.size_enum. Qed. Lemma enum_tupleP (A : {pred T}) : size (enum A) == #|A|. Proof. by rewrite -cardE. Qed. Canonical enum_tuple A := Tuple (enum_tupleP A). Definition ord_tuple : n.-tuple 'I_n := Tuple (introT eqP (size_enum_ord n)). Lemma val_ord_tuple : val ord_tuple = enum 'I_n. Proof. by []. Qed. Lemma tuple_map_ord U (t : n.-tuple U) : t = [tuple of map (tnth t) ord_tuple]. Proof. by apply: val_inj => /=; rewrite map_tnth_enum. Qed. Lemma tnth_ord_tuple i : tnth ord_tuple i = i. Proof. apply: val_inj; rewrite (tnth_nth i) -(nth_map _ 0) ?size_tuple //. by rewrite /= enumT unlock val_ord_enum nth_iota. Qed. Section ImageTuple. Variables (T' : Type) (f : T -> T') (A : {pred T}). Canonical image_tuple : #|A|.-tuple T' := [tuple of image f A]. Canonical codom_tuple : #|T|.-tuple T' := [tuple of codom f]. End ImageTuple. Section MkTuple. Variables (T' : Type) (f : 'I_n -> T'). Definition mktuple := map_tuple f ord_tuple. Lemma tnth_mktuple i : tnth mktuple i = f i. Proof. by rewrite tnth_map tnth_ord_tuple. Qed. Lemma nth_mktuple x0 (i : 'I_n) : nth x0 mktuple i = f i. Proof. by rewrite -tnth_nth tnth_mktuple. Qed. End MkTuple. Lemma eq_mktuple T' (f1 f2 : 'I_n -> T') : f1 =1 f2 -> mktuple f1 = mktuple f2. Proof. by move=> eq_f; apply eq_from_tnth=> i; rewrite !tnth_map eq_f. Qed. End UseFinTuple. Notation "[ 'tuple' F | i < n ]" := (mktuple (fun i : 'I_n => F)) (i at level 0, format "[ '[hv' 'tuple' F '/' | i < n ] ']'") : form_scope. Arguments eq_mktuple {n T'} [f1] f2 eq_f12. Section BseqDef. Variables (n : nat) (T : Type). Structure bseq_of : Type := Bseq {bseqval :> seq T; _ : size bseqval <= n}. HB.instance Definition _ := [isSub for bseqval]. Implicit Type bs : bseq_of. Lemma size_bseq bs : size bs <= n. Proof. by case: bs. Qed. Definition bseq bs mkB : bseq_of := mkB (let: Bseq _ bsP := bs return size bs <= n in bsP). Lemma bseqE bs : bseq (fun sP => @Bseq bs sP) = bs. Proof. by case: bs. Qed. End BseqDef. Canonical nil_bseq n T := Bseq (isT : @size T [::] <= n). Canonical cons_bseq n T x (t : bseq_of n T) := Bseq (valP t : size (x :: t) <= n.+1). Notation "n .-bseq" := (bseq_of n) (format "n .-bseq") : type_scope. Notation "{ 'bseq' n 'of' T }" := (n.-bseq T : predArgType) (only parsing) : type_scope. Notation "[ 'bseq' 'of' s ]" := (bseq (fun sP => @Bseq _ _ s sP)) (format "[ 'bseq' 'of' s ]") : form_scope. Notation "[ 'bseq' x1 ; .. ; xn ]" := [bseq of x1 :: .. [:: xn] ..] (format "[ 'bseq' '[' x1 ; '/' .. ; '/' xn ']' ]") : form_scope. Notation "[ 'bseq' ]" := [bseq of [::]] (format "[ 'bseq' ]") : form_scope. Coercion bseq_of_tuple n T (t : n.-tuple T) : n.-bseq T := Bseq (eq_leq (size_tuple t)). Definition insub_bseq n T (s : seq T) : n.-bseq T := insubd [bseq] s. Lemma size_insub_bseq n T (s : seq T) : size (insub_bseq n s) <= size s. Proof. by rewrite /insub_bseq /insubd; case: insubP => // ? ? ->. Qed. Section CastBseq. Variable T : Type. Definition in_bseq (s : seq T) : (size s).-bseq T := Bseq (leqnn (size s)). Definition cast_bseq m n (eq_mn : m = n) bs := let: erefl in _ = n := eq_mn return n.-bseq T in bs. Definition widen_bseq m n (lemn : m <= n) (bs : m.-bseq T) : n.-bseq T := @Bseq n T bs (leq_trans (size_bseq bs) lemn). Lemma cast_bseq_id n (eq_nn : n = n) bs : cast_bseq eq_nn bs = bs. Proof. by rewrite (eq_axiomK eq_nn). Qed. Lemma cast_bseqK m n (eq_mn : m = n) : cancel (cast_bseq eq_mn) (cast_bseq (esym eq_mn)). Proof. by case: n / eq_mn. Qed. Lemma cast_bseqKV m n (eq_mn : m = n) : cancel (cast_bseq (esym eq_mn)) (cast_bseq eq_mn). Proof. by case: n / eq_mn. Qed. Lemma cast_bseq_trans m n p (eq_mn : m = n) (eq_np : n = p) bs : cast_bseq (etrans eq_mn eq_np) bs = cast_bseq eq_np (cast_bseq eq_mn bs). Proof. by case: n / eq_mn eq_np; case: p /. Qed. Lemma size_cast_bseq m n (eq_mn : m = n) (bs : m.-bseq T) : size (cast_bseq eq_mn bs) = size bs. Proof. by case: n / eq_mn. Qed. Lemma widen_bseq_id n (lenn : n <= n) (bs : n.-bseq T) : widen_bseq lenn bs = bs. Proof. exact: val_inj. Qed. Lemma cast_bseqEwiden m n (eq_mn : m = n) (bs : m.-bseq T) : cast_bseq eq_mn bs = widen_bseq (eq_leq eq_mn) bs. Proof. by case: n / eq_mn; rewrite widen_bseq_id. Qed. Lemma widen_bseqK m n (lemn : m <= n) (lenm : n <= m) : cancel (@widen_bseq m n lemn) (widen_bseq lenm). Proof. by move=> t; apply: val_inj. Qed. Lemma widen_bseq_trans m n p (lemn : m <= n) (lenp : n <= p) (bs : m.-bseq T) : widen_bseq (leq_trans lemn lenp) bs = widen_bseq lenp (widen_bseq lemn bs). Proof. exact/val_inj. Qed. Lemma size_widen_bseq m n (lemn : m <= n) (bs : m.-bseq T) : size (widen_bseq lemn bs) = size bs. Proof. by []. Qed. Lemma in_bseqE s : in_bseq s = s :> seq T. Proof. by []. Qed. Lemma widen_bseq_in_bseq n (bs : n.-bseq T) : widen_bseq (size_bseq bs) (in_bseq bs) = bs. Proof. exact: val_inj. Qed. End CastBseq. Section SeqBseq. Variables (n m : nat) (T U rT : Type). Implicit Type s : n.-bseq T. Lemma rcons_bseqP s x : size (rcons s x) <= n.+1. Proof. by rewrite size_rcons ltnS size_bseq. Qed. Canonical rcons_bseq s x := Bseq (rcons_bseqP s x). Lemma behead_bseqP s : size (behead s) <= n.-1. Proof. rewrite size_behead -!subn1; apply/leq_sub2r/size_bseq. Qed. Canonical behead_bseq s := Bseq (behead_bseqP s). Lemma belast_bseqP x s : size (belast x s) <= n. Proof. by rewrite size_belast; apply/size_bseq. Qed. Canonical belast_bseq x s := Bseq (belast_bseqP x s). Lemma cat_bseqP s (s' : m.-bseq T) : size (s ++ s') <= n + m. Proof. by rewrite size_cat; apply/leq_add/size_bseq/size_bseq. Qed. Canonical cat_bseq s (s' : m.-bseq T) := Bseq (cat_bseqP s s'). Lemma take_bseqP s : size (take m s) <= n. Proof. by rewrite size_take_min (leq_trans _ (size_bseq s)) // geq_minr. Qed. Canonical take_bseq s := Bseq (take_bseqP s). Lemma drop_bseqP s : size (drop m s) <= n - m. Proof. by rewrite size_drop; apply/leq_sub2r/size_bseq. Qed. Canonical drop_bseq s := Bseq (drop_bseqP s). Lemma rev_bseqP s : size (rev s) <= n. Proof. by rewrite size_rev size_bseq. Qed. Canonical rev_bseq s := Bseq (rev_bseqP s). Lemma rot_bseqP s : size (rot m s) <= n. Proof. by rewrite size_rot size_bseq. Qed. Canonical rot_bseq s := Bseq (rot_bseqP s). Lemma rotr_bseqP s : size (rotr m s) <= n. Proof. by rewrite size_rotr size_bseq. Qed. Canonical rotr_bseq s := Bseq (rotr_bseqP s). Lemma map_bseqP f s : @size rT (map f s) <= n. Proof. by rewrite size_map size_bseq. Qed. Canonical map_bseq f s := Bseq (map_bseqP f s). Lemma scanl_bseqP f x s : @size rT (scanl f x s) <= n. Proof. by rewrite size_scanl size_bseq. Qed. Canonical scanl_bseq f x s := Bseq (scanl_bseqP f x s). Lemma pairmap_bseqP f x s : @size rT (pairmap f x s) <= n. Proof. by rewrite size_pairmap size_bseq. Qed. Canonical pairmap_bseq f x s := Bseq (pairmap_bseqP f x s). Lemma allpairs_bseqP f s (s' : m.-bseq U) : @size rT (allpairs f s s') <= n * m. Proof. by rewrite size_allpairs; apply/leq_mul/size_bseq/size_bseq. Qed. Canonical allpairs_bseq f s (s' : m.-bseq U) := Bseq (allpairs_bseqP f s s'). Lemma sort_bseqP r s : size (sort r s) <= n. Proof. by rewrite size_sort size_bseq. Qed. Canonical sort_bseq r s := Bseq (sort_bseqP r s). Lemma bseq0 : all_equal_to ([bseq] : 0.-bseq T). Proof. by move=> s; apply: val_inj; case: s => [[]]. Qed. End SeqBseq. HB.instance Definition bseq_hasDecEq n (T : eqType) := [Equality of n.-bseq T by <:]. Canonical bseq_predType n (T : eqType) := Eval hnf in PredType (fun t : n.-bseq T => mem_seq t). Lemma membsE n (T : eqType) (bs : n.-bseq T) : mem bs = mem (bseqval bs). Proof. by []. Qed. HB.instance Definition bseq_hasChoice n (T : choiceType) := [Choice of n.-bseq T by <:]. HB.instance Definition bseq_isCountable n (T : countType) := [Countable of n.-bseq T by <:]. Definition bseq_tagged_tuple n T (s : n.-bseq T) : {k : 'I_n.+1 & k.-tuple T} := Tagged _ (in_tuple s : (Ordinal (size_bseq s : size s < n.+1)).-tuple _). Arguments bseq_tagged_tuple {n T}. Definition tagged_tuple_bseq n T (t : {k : 'I_n.+1 & k.-tuple T}) : n.-bseq T := widen_bseq (leq_ord (tag t)) (tagged t). Arguments tagged_tuple_bseq {n T}. Lemma bseq_tagged_tupleK {n T} : cancel (@bseq_tagged_tuple n T) tagged_tuple_bseq. Proof. by move=> bs; apply/val_inj. Qed. Lemma tagged_tuple_bseqK {n T} : cancel (@tagged_tuple_bseq n T) bseq_tagged_tuple. Proof. move=> [[k lt_kn] t]; apply: eq_existT_curried => [|k_eq]; apply/val_inj. by rewrite /= size_tuple. by refine (let: erefl := k_eq in _). Qed. Lemma bseq_tagged_tuple_bij {n T} : bijective (@bseq_tagged_tuple n T). Proof. exact/Bijective/tagged_tuple_bseqK/bseq_tagged_tupleK. Qed. Lemma tagged_tuple_bseq_bij {n T} : bijective (@tagged_tuple_bseq n T). Proof. exact/Bijective/bseq_tagged_tupleK/tagged_tuple_bseqK. Qed. #[global] Hint Resolve bseq_tagged_tuple_bij tagged_tuple_bseq_bij : core. #[non_forgetful_inheritance] HB.instance Definition _ n (T : finType) := isFinite.Build (n.-bseq T) (pcan_enumP (can_pcan (@bseq_tagged_tupleK n T))).
Find.lean
/- Copyright (c) 2021 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Mathlib.Init import Batteries.Util.Cache import Lean.HeadIndex import Lean.Elab.Command /-! # The `#find` command and tactic. The `#find` command finds definitions & lemmas using pattern matching on the type. For instance: ```lean #find _ + _ = _ + _ #find ?n + _ = _ + ?n #find (_ : Nat) + _ = _ + _ #find Nat → Nat ``` Inside tactic proofs, there is a `#find` tactic with the same syntax, or the `find` tactic which looks for lemmas which are `apply`able against the current goal. -/ open Lean Std open Lean.Meta open Lean.Elab open Batteries.Tactic namespace Mathlib.Tactic.Find private partial def matchHyps : List Expr → List Expr → List Expr → MetaM Bool | p::ps, oldHyps, h::newHyps => do let pt ← inferType p let t ← inferType h if (← isDefEq pt t) then matchHyps ps [] (oldHyps ++ newHyps) else matchHyps (p::ps) (h::oldHyps) newHyps | [], _, _ => pure true | _::_, _, [] => pure false -- from Lean.Server.Completion private def isBlackListed (declName : Name) : MetaM Bool := do let env ← getEnv pure <| declName.isInternal || isAuxRecursor env declName || isNoConfusion env declName <||> isRec declName <||> isMatcher declName initialize findDeclsPerHead : DeclCache (Std.HashMap HeadIndex (Array Name)) ← DeclCache.mk "#find: init cache" failure {} fun _ c headMap ↦ do if (← isBlackListed c.name) then return headMap -- TODO: this should perhaps use `forallTelescopeReducing` instead, -- to avoid leaking metavariables. let (_, _, ty) ← forallMetaTelescopeReducing c.type let head := ty.toHeadIndex pure <| headMap.insert head (headMap.getD head #[] |>.push c.name) def findType (t : Expr) : TermElabM Unit := withReducible do let t ← instantiateMVars t let head := (← forallMetaTelescopeReducing t).2.2.toHeadIndex let pat ← abstractMVars t let env ← getEnv let mut numFound := 0 for n in (← findDeclsPerHead.get).getD head #[] do let c := env.find? n |>.get! let cTy := c.instantiateTypeLevelParams (← mkFreshLevelMVars c.numLevelParams) let found ← forallTelescopeReducing cTy fun cParams cTy' ↦ do let pat := pat.expr.instantiateLevelParamsArray pat.paramNames (← mkFreshLevelMVars pat.numMVars).toArray let (_, _, pat) ← lambdaMetaTelescope pat let (patParams, _, pat) ← forallMetaTelescopeReducing pat isDefEq cTy' pat <&&> matchHyps patParams.toList [] cParams.toList if found then numFound := numFound + 1 if numFound > 20 then logInfo m!"maximum number of search results reached" break logInfo m!"{n}: {cTy}" open Lean.Elab.Command in /- The `#find` command finds definitions & lemmas using pattern matching on the type. For instance: ```lean #find _ + _ = _ + _ #find ?n + _ = _ + ?n #find (_ : Nat) + _ = _ + _ #find Nat → Nat ``` Inside tactic proofs, the `#find` tactic can be used instead. There is also the `find` tactic which looks for lemmas which are `apply`able against the current goal. -/ elab "#find " t:term : command => liftTermElabM do let t ← Term.elabTerm t none Term.synthesizeSyntheticMVars (postpone := .no) (ignoreStuckTC := true) findType t /- (Note that you'll get an error trying to run these here: ``cannot evaluate `[init]` declaration 'findDeclsPerHead' in the same module`` but they will work fine in a new file!) -/ -- #find _ + _ = _ + _ -- #find _ + _ = _ + _ -- #find ?n + _ = _ + ?n -- #find (_ : Nat) + _ = _ + _ -- #find Nat → Nat -- #find ?n ≤ ?m → ?n + _ ≤ ?m + _ open Lean.Elab.Tactic /- Display theorems (and definitions) whose result type matches the current goal, i.e. which should be `apply`able. ```lean example : True := by find ``` `find` will not affect the goal by itself and should be removed from the finished proof. For a command that takes the type to search for as an argument, see `#find`, which is also available as a tactic. -/ elab "find" : tactic => do findType (← getMainTarget) /- Tactic version of the `#find` command. See also the `find` tactic to search for theorems matching the current goal. -/ elab "#find " t:term : tactic => do let t ← Term.elabTerm t none Term.synthesizeSyntheticMVars (postpone := .no) (ignoreStuckTC := true) findType t end Mathlib.Tactic.Find
Finset.lean
/- Copyright (c) 2023 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey -/ import Mathlib.Data.Finset.Prod import Mathlib.Data.Fintype.Pi /-! # Fin-indexed tuples of finsets -/ open Fin Fintype namespace Fin variable {n : ℕ} {α : Fin (n + 1) → Type*} {f : ∀ i, α i} {s : ∀ i, Finset (α i)} {p : Fin (n + 1)} lemma mem_piFinset_iff_zero_tail : f ∈ Fintype.piFinset s ↔ f 0 ∈ s 0 ∧ tail f ∈ piFinset (tail s) := by simp only [Fintype.mem_piFinset, forall_fin_succ, tail] lemma mem_piFinset_iff_last_init : f ∈ piFinset s ↔ f (last n) ∈ s (last n) ∧ init f ∈ piFinset (init s) := by simp only [Fintype.mem_piFinset, forall_fin_succ', init, and_comm] lemma mem_piFinset_iff_pivot_removeNth (p : Fin (n + 1)) : f ∈ piFinset s ↔ f p ∈ s p ∧ removeNth p f ∈ piFinset (removeNth p s) := by simp only [Fintype.mem_piFinset, forall_iff_succAbove p, removeNth] lemma cons_mem_piFinset_cons {x_zero : α 0} {x_tail : (i : Fin n) → α i.succ} {s_zero : Finset (α 0)} {s_tail : (i : Fin n) → Finset (α i.succ)} : cons x_zero x_tail ∈ piFinset (cons s_zero s_tail) ↔ x_zero ∈ s_zero ∧ x_tail ∈ piFinset s_tail := by simp_rw [mem_piFinset_iff_zero_tail, cons_zero, tail_cons] lemma snoc_mem_piFinset_snoc {x_last : α (last n)} {x_init : (i : Fin n) → α i.castSucc} {s_last : Finset (α (last n))} {s_init : (i : Fin n) → Finset (α i.castSucc)} : snoc x_init x_last ∈ piFinset (snoc s_init s_last) ↔ x_last ∈ s_last ∧ x_init ∈ piFinset s_init := by simp_rw [mem_piFinset_iff_last_init, init_snoc, snoc_last] lemma insertNth_mem_piFinset_insertNth {x_pivot : α p} {x_remove : ∀ i, α (succAbove p i)} {s_pivot : Finset (α p)} {s_remove : ∀ i, Finset (α (succAbove p i))} : insertNth p x_pivot x_remove ∈ piFinset (insertNth p s_pivot s_remove) ↔ x_pivot ∈ s_pivot ∧ x_remove ∈ piFinset s_remove := by simp [mem_piFinset_iff_pivot_removeNth p] end Fin namespace Finset variable {n : ℕ} {α : Fin (n + 1) → Type*} {p : Fin (n + 1)} (S : ∀ i, Finset (α i)) lemma map_consEquiv_filter_piFinset (P : (∀ i, α (succ i)) → Prop) [DecidablePred P] : {r ∈ piFinset S | P (tail r)}.map (consEquiv α).symm.toEmbedding = S 0 ×ˢ {r ∈ piFinset (tail S) | P r} := by unfold tail; ext; simp [Fin.forall_iff_succ, and_assoc] lemma map_snocEquiv_filter_piFinset (P : (∀ i, α (castSucc i)) → Prop) [DecidablePred P] : {r ∈ piFinset S | P (init r)}.map (snocEquiv α).symm.toEmbedding = S (last _) ×ˢ {r ∈ piFinset (init S) | P r} := by unfold init; ext; simp [Fin.forall_iff_castSucc, and_assoc] lemma map_insertNthEquiv_filter_piFinset (P : (∀ i, α (p.succAbove i)) → Prop) [DecidablePred P] : {r ∈ piFinset S | P (p.removeNth r)}.map (p.insertNthEquiv α).symm.toEmbedding = S p ×ˢ {r ∈ piFinset (p.removeNth S) | P r} := by unfold removeNth; ext; simp [Fin.forall_iff_succAbove p, and_assoc] lemma filter_piFinset_eq_map_consEquiv (P : (∀ i, α (succ i)) → Prop) [DecidablePred P] : {r ∈ piFinset S | P (tail r)} = (S 0 ×ˢ {r ∈ piFinset (tail S) | P r}).map (consEquiv α).toEmbedding := by simp [← map_consEquiv_filter_piFinset, map_map] lemma filter_piFinset_eq_map_snocEquiv (P : (∀ i, α (castSucc i)) → Prop) [DecidablePred P] : {r ∈ piFinset S | P (init r)} = (S (last _) ×ˢ {r ∈ piFinset (init S) | P r}).map (snocEquiv α).toEmbedding := by simp [← map_snocEquiv_filter_piFinset, map_map] lemma filter_piFinset_eq_map_insertNthEquiv (P : (∀ i, α (p.succAbove i)) → Prop) [DecidablePred P] : {r ∈ piFinset S | P (p.removeNth r)} = (S p ×ˢ {r ∈ piFinset (p.removeNth S) | P r}).map (p.insertNthEquiv α).toEmbedding := by simp [← map_insertNthEquiv_filter_piFinset, map_map] lemma card_consEquiv_filter_piFinset (P : (∀ i, α (succ i)) → Prop) [DecidablePred P] : {r ∈ piFinset S | P (tail r)}.card = (S 0).card * {r ∈ piFinset (tail S) | P r}.card := by rw [← card_product, ← map_consEquiv_filter_piFinset, card_map] lemma card_snocEquiv_filter_piFinset (P : (∀ i, α (castSucc i)) → Prop) [DecidablePred P] : {r ∈ piFinset S | P (init r)}.card = (S (last _)).card * {r ∈ piFinset (init S) | P r}.card := by rw [← card_product, ← map_snocEquiv_filter_piFinset, card_map] lemma card_insertNthEquiv_filter_piFinset (P : (∀ i, α (p.succAbove i)) → Prop) [DecidablePred P] : {r ∈ piFinset S | P (p.removeNth r)}.card = (S p).card * {r ∈ piFinset (p.removeNth S) | P r}.card := by rw [← card_product, ← map_insertNthEquiv_filter_piFinset, card_map] end Finset
AdaptationNote.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 Mathlib.Init import Lean.Meta.Tactic.TryThis /-! # Adaptation notes This file defines a `#adaptation_note` command. Adaptation notes are comments that are used to indicate that a piece of code has been changed to accommodate a change in Lean core. They typically require further action/maintenance to be taken in the future. -/ open Lean initialize registerTraceClass `adaptationNote /-- General function implementing adaptation notes. -/ def reportAdaptationNote (f : Syntax → Meta.Tactic.TryThis.Suggestion) : MetaM Unit := do let stx ← getRef if let some doc := stx[1].getOptional? then trace[adaptationNote] (Lean.TSyntax.getDocString ⟨doc⟩) else logError "Adaptation notes must be followed by a /-- comment -/" let trailing := if let .original (trailing := s) .. := stx[0].getTailInfo then s else default let doc : Syntax := Syntax.node2 .none ``Parser.Command.docComment (mkAtom "/--") (mkAtom "comment -/") -- Optional: copy the original whitespace after the `#adaptation_note` token -- to after the docstring comment let doc := doc.updateTrailing trailing let stx' := (← getRef) let stx' := stx'.setArg 0 stx'[0].unsetTrailing let stx' := stx'.setArg 1 (mkNullNode #[doc]) Meta.Tactic.TryThis.addSuggestion (← getRef) (f stx') (origSpan? := ← getRef) /-- Adaptation notes are comments that are used to indicate that a piece of code has been changed to accommodate a change in Lean core. They typically require further action/maintenance to be taken in the future. -/ elab (name := adaptationNoteCmd) "#adaptation_note " (docComment)? : command => do Elab.Command.liftTermElabM <| reportAdaptationNote (fun s => (⟨s⟩ : TSyntax `tactic)) @[inherit_doc adaptationNoteCmd] elab "#adaptation_note " (docComment)? : tactic => reportAdaptationNote (fun s => (⟨s⟩ : TSyntax `tactic)) @[inherit_doc adaptationNoteCmd] syntax (name := adaptationNoteTermStx) "#adaptation_note " (docComment)? term : term /-- Elaborator for adaptation notes. -/ @[term_elab adaptationNoteTermStx] def adaptationNoteTermElab : Elab.Term.TermElab | `(#adaptation_note $[$_]? $t) => fun expectedType? => do reportAdaptationNote (fun s => (⟨s⟩ : Term)) Elab.Term.elabTerm t expectedType? | _ => fun _ => Elab.throwUnsupportedSyntax #adaptation_note /-- This is a test -/ example : True := by #adaptation_note /-- This is a test -/ trivial example : True := #adaptation_note /-- This is a test -/ trivial
Ray.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Yaël Dillies -/ import Mathlib.LinearAlgebra.Ray import Mathlib.Analysis.NormedSpace.Real import Mathlib.Algebra.Ring.Regular /-! # Rays in a real normed vector space In this file we prove some lemmas about the `SameRay` predicate in case of a real normed space. In this case, for two vectors `x y` in the same ray, the norm of their sum is equal to the sum of their norms and `‖y‖ • x = ‖x‖ • y`. -/ open Real variable {E : Type*} [SeminormedAddCommGroup E] [NormedSpace ℝ E] {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] namespace SameRay variable {x y : E} /-- If `x` and `y` are on the same ray, then the triangle inequality becomes the equality: the norm of `x + y` is the sum of the norms of `x` and `y`. The converse is true for a strictly convex space. -/ theorem norm_add (h : SameRay ℝ x y) : ‖x + y‖ = ‖x‖ + ‖y‖ := by rcases h.exists_eq_smul with ⟨u, a, b, ha, hb, -, rfl, rfl⟩ rw [← add_smul, norm_smul_of_nonneg (add_nonneg ha hb), norm_smul_of_nonneg ha, norm_smul_of_nonneg hb, add_mul] theorem norm_sub (h : SameRay ℝ x y) : ‖x - y‖ = |‖x‖ - ‖y‖| := by rcases h.exists_eq_smul with ⟨u, a, b, ha, hb, -, rfl, rfl⟩ wlog hab : b ≤ a generalizing a b with H · rw [SameRay.sameRay_comm] at h rw [norm_sub_rev, abs_sub_comm] exact H b a hb ha h (le_of_not_ge hab) rw [← sub_nonneg] at hab rw [← sub_smul, norm_smul_of_nonneg hab, norm_smul_of_nonneg ha, norm_smul_of_nonneg hb, ← sub_mul, abs_of_nonneg (mul_nonneg hab (norm_nonneg _))] theorem norm_smul_eq (h : SameRay ℝ x y) : ‖x‖ • y = ‖y‖ • x := by rcases h.exists_eq_smul with ⟨u, a, b, ha, hb, -, rfl, rfl⟩ simp only [norm_smul_of_nonneg, *, mul_smul] rw [smul_comm, smul_comm b, smul_comm a b u] end SameRay variable {x y : F} theorem norm_injOn_ray_left (hx : x ≠ 0) : { y | SameRay ℝ x y }.InjOn norm := by rintro y hy z hz h rcases hy.exists_nonneg_left hx with ⟨r, hr, rfl⟩ rcases hz.exists_nonneg_left hx with ⟨s, hs, rfl⟩ rw [norm_smul, norm_smul, mul_left_inj' (norm_ne_zero_iff.2 hx), norm_of_nonneg hr, norm_of_nonneg hs] at h rw [h] theorem norm_injOn_ray_right (hy : y ≠ 0) : { x | SameRay ℝ x y }.InjOn norm := by simpa only [SameRay.sameRay_comm] using norm_injOn_ray_left hy theorem sameRay_iff_norm_smul_eq : SameRay ℝ x y ↔ ‖x‖ • y = ‖y‖ • x := ⟨SameRay.norm_smul_eq, fun h => or_iff_not_imp_left.2 fun hx => or_iff_not_imp_left.2 fun hy => ⟨‖y‖, ‖x‖, norm_pos_iff.2 hy, norm_pos_iff.2 hx, h.symm⟩⟩ /-- Two nonzero vectors `x y` in a real normed space are on the same ray if and only if the unit vectors `‖x‖⁻¹ • x` and `‖y‖⁻¹ • y` are equal. -/ theorem sameRay_iff_inv_norm_smul_eq_of_ne (hx : x ≠ 0) (hy : y ≠ 0) : SameRay ℝ x y ↔ ‖x‖⁻¹ • x = ‖y‖⁻¹ • y := by rw [inv_smul_eq_iff₀, smul_comm, eq_comm, inv_smul_eq_iff₀, sameRay_iff_norm_smul_eq] <;> rwa [norm_ne_zero_iff] alias ⟨SameRay.inv_norm_smul_eq, _⟩ := sameRay_iff_inv_norm_smul_eq_of_ne /-- Two vectors `x y` in a real normed space are on the ray if and only if one of them is zero or the unit vectors `‖x‖⁻¹ • x` and `‖y‖⁻¹ • y` are equal. -/ theorem sameRay_iff_inv_norm_smul_eq : SameRay ℝ x y ↔ x = 0 ∨ y = 0 ∨ ‖x‖⁻¹ • x = ‖y‖⁻¹ • y := by rcases eq_or_ne x 0 with (rfl | hx); · simp [SameRay.zero_left] rcases eq_or_ne y 0 with (rfl | hy); · simp [SameRay.zero_right] simp only [sameRay_iff_inv_norm_smul_eq_of_ne hx hy, *, false_or] /-- Two vectors of the same norm are on the same ray if and only if they are equal. -/ theorem sameRay_iff_of_norm_eq (h : ‖x‖ = ‖y‖) : SameRay ℝ x y ↔ x = y := by obtain rfl | hy := eq_or_ne y 0 · rw [norm_zero, norm_eq_zero] at h exact iff_of_true (SameRay.zero_right _) h · exact ⟨fun hxy => norm_injOn_ray_right hy hxy SameRay.rfl h, fun hxy => hxy ▸ SameRay.rfl⟩ theorem not_sameRay_iff_of_norm_eq (h : ‖x‖ = ‖y‖) : ¬SameRay ℝ x y ↔ x ≠ y := (sameRay_iff_of_norm_eq h).not /-- If two points on the same ray have the same norm, then they are equal. -/ theorem SameRay.eq_of_norm_eq (h : SameRay ℝ x y) (hn : ‖x‖ = ‖y‖) : x = y := (sameRay_iff_of_norm_eq hn).mp h /-- The norms of two vectors on the same ray are equal if and only if they are equal. -/ theorem SameRay.norm_eq_iff (h : SameRay ℝ x y) : ‖x‖ = ‖y‖ ↔ x = y := ⟨h.eq_of_norm_eq, fun h => h ▸ rfl⟩
Register.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.Init import Lean.Meta.Tactic.Simp.SimpTheorems import Lean.Meta.Tactic.Simp.RegisterCommand import Lean.LabelAttribute /-! # Attributes used in `Mathlib` In this file we define all `simp`-like and `label`-like attributes used in `Mathlib`. We declare all of them in one file for two reasons: - in Lean 4, one cannot use an attribute in the same file where it was declared; - this way it is easy to see which simp sets contain a given lemma. -/ /-- Simp set for `functor_norm` -/ register_simp_attr functor_norm -- Porting note: -- in mathlib3 we declared `monad_norm` using: -- mk_simp_attribute monad_norm none with functor_norm -- This syntax is not supported by mathlib4's `register_simp_attr`. -- See https://github.com/leanprover-community/mathlib4/issues/802 -- TODO: add `@[monad_norm]` to all `@[functor_norm] lemmas /-- Simp set for `functor_norm` -/ register_simp_attr monad_norm /-- The simpset `field_simps` is used by the tactic `field_simp` to reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are division-free. -/ register_simp_attr field_simps /-- Simp attribute for lemmas about `Even` -/ register_simp_attr parity_simps /-- "Simp attribute for lemmas about `RCLike`" -/ register_simp_attr rclike_simps /-- The simpset `rify_simps` is used by the tactic `rify` to move expressions from `ℕ`, `ℤ`, or `ℚ` to `ℝ`. -/ register_simp_attr rify_simps /-- The simpset `qify_simps` is used by the tactic `qify` to move expressions from `ℕ` or `ℤ` to `ℚ` which gives a well-behaved division. -/ register_simp_attr qify_simps /-- The simpset `zify_simps` is used by the tactic `zify` to move expressions from `ℕ` to `ℤ` which gives a well-behaved subtraction. -/ register_simp_attr zify_simps /-- The simpset `mfld_simps` records several simp lemmas that are especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining readability. The typical use case is the following, in a file on manifolds: If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar, mfld_simps]` and paste its output. The list of lemmas should be reasonable (contrary to the output of `squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick enough. -/ register_simp_attr mfld_simps /-- Simp set for integral rules. -/ register_simp_attr integral_simps /-- simp set for the manipulation of typevec and arrow expressions -/ register_simp_attr typevec /-- Simplification rules for ghost equations. -/ register_simp_attr ghost_simps /-- The `@[nontriviality]` simp set is used by the `nontriviality` tactic to automatically discharge theorems about the trivial case (where we know `Subsingleton α` and many theorems in e.g. groups are trivially true). -/ register_simp_attr nontriviality /-- A stub attribute for `is_poly`. -/ register_label_attr is_poly /-- A simp set for the `fin_omega` wrapper around `omega`. -/ register_simp_attr fin_omega /-- A simp set for simplifying expressions involving `⊤` in `enat_to_nat`. -/ register_simp_attr enat_to_nat_top /-- A simp set for pushing coercions from `ℕ` to `ℕ∞` in `enat_to_nat`. -/ register_simp_attr enat_to_nat_coe /-- A simp set for the `pnat_to_nat` tactic. -/ register_simp_attr pnat_to_nat_coe
Split.lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.AlgebraicTopology.SimplicialObject.Basic import Mathlib.CategoryTheory.Limits.Shapes.Products import Mathlib.Data.Fintype.Sigma /-! # Split simplicial objects In this file, we introduce the notion of split simplicial object. If `C` is a category that has finite coproducts, a splitting `s : Splitting X` of a simplicial object `X` in `C` consists of the datum of a sequence of objects `s.N : ℕ → C` (which we shall refer to as "nondegenerate simplices") and a sequence of morphisms `s.ι n : s.N n → X _⦋n⦌` that have the property that a certain canonical map identifies `X _⦋n⦌` with the coproduct of objects `s.N i` indexed by all possible epimorphisms `⦋n⦌ ⟶ ⦋i⦌` in `SimplexCategory`. (We do not assume that the morphisms `s.ι n` are monomorphisms: in the most common categories, this would be a consequence of the axioms.) Simplicial objects equipped with a splitting form a category `SimplicialObject.Split C`. ## References * [Stacks: Splitting simplicial objects] https://stacks.math.columbia.edu/tag/017O -/ noncomputable section open CategoryTheory CategoryTheory.Category CategoryTheory.Limits Opposite SimplexCategory open Simplicial universe u variable {C : Type*} [Category C] namespace SimplicialObject namespace Splitting /-- The index set which appears in the definition of split simplicial objects. -/ def IndexSet (Δ : SimplexCategoryᵒᵖ) := Σ Δ' : SimplexCategoryᵒᵖ, { α : Δ.unop ⟶ Δ'.unop // Epi α } namespace IndexSet /-- The element in `Splitting.IndexSet Δ` attached to an epimorphism `f : Δ ⟶ Δ'`. -/ @[simps] def mk {Δ Δ' : SimplexCategory} (f : Δ ⟶ Δ') [Epi f] : IndexSet (op Δ) := ⟨op Δ', f, inferInstance⟩ variable {Δ : SimplexCategoryᵒᵖ} (A : IndexSet Δ) /-- The epimorphism in `SimplexCategory` associated to `A : Splitting.IndexSet Δ` -/ def e := A.2.1 instance : Epi A.e := A.2.2 theorem ext' : A = ⟨A.1, ⟨A.e, A.2.2⟩⟩ := rfl theorem ext (A₁ A₂ : IndexSet Δ) (h₁ : A₁.1 = A₂.1) (h₂ : A₁.e ≫ eqToHom (by rw [h₁]) = A₂.e) : A₁ = A₂ := by rcases A₁ with ⟨Δ₁, ⟨α₁, hα₁⟩⟩ rcases A₂ with ⟨Δ₂, ⟨α₂, hα₂⟩⟩ simp only at h₁ subst h₁ simp only [eqToHom_refl, comp_id, IndexSet.e] at h₂ simp only [h₂] instance : Fintype (IndexSet Δ) := Fintype.ofInjective (fun A => ⟨⟨A.1.unop.len, Nat.lt_succ_iff.mpr (len_le_of_epi A.e)⟩, A.e.toOrderHom⟩ : IndexSet Δ → Sigma fun k : Fin (Δ.unop.len + 1) => Fin (Δ.unop.len + 1) → Fin (k + 1)) (by rintro ⟨Δ₁, α₁⟩ ⟨Δ₂, α₂⟩ h₁ induction' Δ₁ using Opposite.rec with Δ₁ induction' Δ₂ using Opposite.rec with Δ₂ simp only [unop_op, Sigma.mk.inj_iff, Fin.mk.injEq] at h₁ have h₂ : Δ₁ = Δ₂ := by ext1 simpa only [Fin.mk_eq_mk] using h₁.1 subst h₂ refine ext _ _ rfl ?_ ext : 2 exact eq_of_heq h₁.2) variable (Δ) /-- The distinguished element in `Splitting.IndexSet Δ` which corresponds to the identity of `Δ`. -/ @[simps] def id : IndexSet Δ := ⟨Δ, ⟨𝟙 _, by infer_instance⟩⟩ instance : Inhabited (IndexSet Δ) := ⟨id Δ⟩ variable {Δ} /-- The condition that an element `Splitting.IndexSet Δ` is the distinguished element `Splitting.IndexSet.Id Δ`. -/ @[simp] def EqId : Prop := A = id _ theorem eqId_iff_eq : A.EqId ↔ A.1 = Δ := by constructor · intro h dsimp at h rw [h] rfl · intro h rcases A with ⟨_, ⟨f, hf⟩⟩ simp only at h subst h refine ext _ _ rfl ?_ simp only [eqToHom_refl, comp_id] exact eq_id_of_epi f theorem eqId_iff_len_eq : A.EqId ↔ A.1.unop.len = Δ.unop.len := by rw [eqId_iff_eq] constructor · intro h rw [h] · intro h rw [← unop_inj_iff] ext exact h theorem eqId_iff_len_le : A.EqId ↔ Δ.unop.len ≤ A.1.unop.len := by rw [eqId_iff_len_eq] constructor · intro h rw [h] · exact le_antisymm (len_le_of_epi A.e) theorem eqId_iff_mono : A.EqId ↔ Mono A.e := by constructor · intro h dsimp at h subst h dsimp only [id, e] infer_instance · intro rw [eqId_iff_len_le] exact len_le_of_mono A.e /-- Given `A : IndexSet Δ₁`, if `p.unop : unop Δ₂ ⟶ unop Δ₁` is an epi, this is the obvious element in `A : IndexSet Δ₂` associated to the composition of epimorphisms `p.unop ≫ A.e`. -/ @[simps] def epiComp {Δ₁ Δ₂ : SimplexCategoryᵒᵖ} (A : IndexSet Δ₁) (p : Δ₁ ⟶ Δ₂) [Epi p.unop] : IndexSet Δ₂ := ⟨A.1, ⟨p.unop ≫ A.e, epi_comp _ _⟩⟩ variable {Δ' : SimplexCategoryᵒᵖ} (θ : Δ ⟶ Δ') /-- When `A : IndexSet Δ` and `θ : Δ → Δ'` is a morphism in `SimplexCategoryᵒᵖ`, an element in `IndexSet Δ'` can be defined by using the epi-mono factorisation of `θ.unop ≫ A.e`. -/ def pull : IndexSet Δ' := mk (factorThruImage (θ.unop ≫ A.e)) @[reassoc] theorem fac_pull : (A.pull θ).e ≫ image.ι (θ.unop ≫ A.e) = θ.unop ≫ A.e := image.fac _ end IndexSet variable (N : ℕ → C) (Δ : SimplexCategoryᵒᵖ) (X : SimplicialObject C) (φ : ∀ n, N n ⟶ X _⦋n⦌) /-- Given a sequences of objects `N : ℕ → C` in a category `C`, this is a family of objects indexed by the elements `A : Splitting.IndexSet Δ`. The `Δ`-simplices of a split simplicial objects shall identify to the coproduct of objects in such a family. -/ @[simp, nolint unusedArguments] def summand (A : IndexSet Δ) : C := N A.1.unop.len /-- The cofan for `summand N Δ` induced by morphisms `N n ⟶ X _⦋n⦌` for all `n : ℕ`. -/ def cofan' (Δ : SimplexCategoryᵒᵖ) : Cofan (summand N Δ) := Cofan.mk (X.obj Δ) (fun A => φ A.1.unop.len ≫ X.map A.e.op) end Splitting /-- A splitting of a simplicial object `X` consists of the datum of a sequence of objects `N`, a sequence of morphisms `ι : N n ⟶ X _⦋n⦌` such that for all `Δ : SimplexCategoryᵒᵖ`, the canonical map `Splitting.map X ι Δ` is an isomorphism. -/ structure Splitting (X : SimplicialObject C) where /-- The "nondegenerate simplices" `N n` for all `n : ℕ`. -/ N : ℕ → C /-- The "inclusion" `N n ⟶ X _⦋n⦌` for all `n : ℕ`. -/ ι : ∀ n, N n ⟶ X _⦋n⦌ /-- For each `Δ`, `X.obj Δ` identifies to the coproduct of the objects `N A.1.unop.len` for all `A : IndexSet Δ`. -/ isColimit' : ∀ Δ : SimplexCategoryᵒᵖ, IsColimit (Splitting.cofan' N X ι Δ) namespace Splitting variable {X Y : SimplicialObject C} (s : Splitting X) /-- The cofan for `summand s.N Δ` induced by a splitting of a simplicial object. -/ def cofan (Δ : SimplexCategoryᵒᵖ) : Cofan (summand s.N Δ) := Cofan.mk (X.obj Δ) (fun A => s.ι A.1.unop.len ≫ X.map A.e.op) /-- The cofan `s.cofan Δ` is colimit. -/ def isColimit (Δ : SimplexCategoryᵒᵖ) : IsColimit (s.cofan Δ) := s.isColimit' Δ @[reassoc] theorem cofan_inj_eq {Δ : SimplexCategoryᵒᵖ} (A : IndexSet Δ) : (s.cofan Δ).inj A = s.ι A.1.unop.len ≫ X.map A.e.op := rfl theorem cofan_inj_id (n : ℕ) : (s.cofan _).inj (IndexSet.id (op ⦋n⦌)) = s.ι n := by simp [IndexSet.id, IndexSet.e, cofan_inj_eq] /-- As it is stated in `Splitting.hom_ext`, a morphism `f : X ⟶ Y` from a split simplicial object to any simplicial object is determined by its restrictions `s.φ f n : s.N n ⟶ Y _⦋n⦌` to the distinguished summands in each degree `n`. -/ @[simp] def φ (f : X ⟶ Y) (n : ℕ) : s.N n ⟶ Y _⦋n⦌ := s.ι n ≫ f.app (op ⦋n⦌) @[reassoc (attr := simp)] theorem cofan_inj_comp_app (f : X ⟶ Y) {Δ : SimplexCategoryᵒᵖ} (A : IndexSet Δ) : (s.cofan Δ).inj A ≫ f.app Δ = s.φ f A.1.unop.len ≫ Y.map A.e.op := by simp only [cofan_inj_eq_assoc, φ, assoc] rw [NatTrans.naturality] theorem hom_ext' {Z : C} {Δ : SimplexCategoryᵒᵖ} (f g : X.obj Δ ⟶ Z) (h : ∀ A : IndexSet Δ, (s.cofan Δ).inj A ≫ f = (s.cofan Δ).inj A ≫ g) : f = g := Cofan.IsColimit.hom_ext (s.isColimit Δ) _ _ h theorem hom_ext (f g : X ⟶ Y) (h : ∀ n : ℕ, s.φ f n = s.φ g n) : f = g := by ext Δ apply s.hom_ext' intro A induction' Δ using Opposite.rec with Δ induction' Δ using SimplexCategory.rec with n dsimp simp only [s.cofan_inj_comp_app, h] /-- The map `X.obj Δ ⟶ Z` obtained by providing a family of morphisms on all the terms of decomposition given by a splitting `s : Splitting X` -/ def desc {Z : C} (Δ : SimplexCategoryᵒᵖ) (F : ∀ A : IndexSet Δ, s.N A.1.unop.len ⟶ Z) : X.obj Δ ⟶ Z := Cofan.IsColimit.desc (s.isColimit Δ) F @[reassoc (attr := simp)] theorem ι_desc {Z : C} (Δ : SimplexCategoryᵒᵖ) (F : ∀ A : IndexSet Δ, s.N A.1.unop.len ⟶ Z) (A : IndexSet Δ) : (s.cofan Δ).inj A ≫ s.desc Δ F = F A := by apply Cofan.IsColimit.fac /-- A simplicial object that is isomorphic to a split simplicial object is split. -/ @[simps] def ofIso (e : X ≅ Y) : Splitting Y where N := s.N ι n := s.ι n ≫ e.hom.app (op ⦋n⦌) isColimit' Δ := IsColimit.ofIsoColimit (s.isColimit Δ ) (Cofan.ext (e.app Δ) (fun A => by simp [cofan, cofan'])) @[reassoc] theorem cofan_inj_epi_naturality {Δ₁ Δ₂ : SimplexCategoryᵒᵖ} (A : IndexSet Δ₁) (p : Δ₁ ⟶ Δ₂) [Epi p.unop] : (s.cofan Δ₁).inj A ≫ X.map p = (s.cofan Δ₂).inj (A.epiComp p) := by dsimp [cofan] rw [assoc, ← X.map_comp] rfl end Splitting variable (C) /-- The category `SimplicialObject.Split C` is the category of simplicial objects in `C` equipped with a splitting, and morphisms are morphisms of simplicial objects which are compatible with the splittings. -/ @[ext] structure Split where /-- the underlying simplicial object -/ X : SimplicialObject C /-- a splitting of the simplicial object -/ s : Splitting X namespace Split variable {C} /-- The object in `SimplicialObject.Split C` attached to a splitting `s : Splitting X` of a simplicial object `X`. -/ @[simps] def mk' {X : SimplicialObject C} (s : Splitting X) : Split C := ⟨X, s⟩ /-- Morphisms in `SimplicialObject.Split C` are morphisms of simplicial objects that are compatible with the splittings. -/ structure Hom (S₁ S₂ : Split C) where /-- the morphism between the underlying simplicial objects -/ F : S₁.X ⟶ S₂.X /-- the morphism between the "nondegenerate" `n`-simplices for all `n : ℕ` -/ f : ∀ n : ℕ, S₁.s.N n ⟶ S₂.s.N n comm : ∀ n : ℕ, S₁.s.ι n ≫ F.app (op ⦋n⦌) = f n ≫ S₂.s.ι n := by cat_disch @[ext] theorem Hom.ext {S₁ S₂ : Split C} (Φ₁ Φ₂ : Hom S₁ S₂) (h : ∀ n : ℕ, Φ₁.f n = Φ₂.f n) : Φ₁ = Φ₂ := by rcases Φ₁ with ⟨F₁, f₁, c₁⟩ rcases Φ₂ with ⟨F₂, f₂, c₂⟩ have h' : f₁ = f₂ := by ext apply h subst h' simp only [mk.injEq, and_true] apply S₁.s.hom_ext intro n dsimp rw [c₁, c₂] attribute [simp, reassoc] Hom.comm end Split instance : Category (Split C) where Hom := Split.Hom id S := { F := 𝟙 _ f := fun _ => 𝟙 _ } comp Φ₁₂ Φ₂₃ := { F := Φ₁₂.F ≫ Φ₂₃.F f := fun n => Φ₁₂.f n ≫ Φ₂₃.f n comm := fun n => by dsimp simp only [assoc, Split.Hom.comm_assoc, Split.Hom.comm] } variable {C} namespace Split @[ext] theorem hom_ext {S₁ S₂ : Split C} (Φ₁ Φ₂ : S₁ ⟶ S₂) (h : ∀ n : ℕ, Φ₁.f n = Φ₂.f n) : Φ₁ = Φ₂ := Hom.ext _ _ h theorem congr_F {S₁ S₂ : Split C} {Φ₁ Φ₂ : S₁ ⟶ S₂} (h : Φ₁ = Φ₂) : Φ₁.f = Φ₂.f := by rw [h] theorem congr_f {S₁ S₂ : Split C} {Φ₁ Φ₂ : S₁ ⟶ S₂} (h : Φ₁ = Φ₂) (n : ℕ) : Φ₁.f n = Φ₂.f n := by rw [h] @[simp] theorem id_F (S : Split C) : (𝟙 S : S ⟶ S).F = 𝟙 S.X := rfl @[simp] theorem id_f (S : Split C) (n : ℕ) : (𝟙 S : S ⟶ S).f n = 𝟙 (S.s.N n) := rfl @[simp] theorem comp_F {S₁ S₂ S₃ : Split C} (Φ₁₂ : S₁ ⟶ S₂) (Φ₂₃ : S₂ ⟶ S₃) : (Φ₁₂ ≫ Φ₂₃).F = Φ₁₂.F ≫ Φ₂₃.F := rfl @[simp] theorem comp_f {S₁ S₂ S₃ : Split C} (Φ₁₂ : S₁ ⟶ S₂) (Φ₂₃ : S₂ ⟶ S₃) (n : ℕ) : (Φ₁₂ ≫ Φ₂₃).f n = Φ₁₂.f n ≫ Φ₂₃.f n := rfl -- This is not a `@[simp]` lemma as it can later be proved by `simp`. @[reassoc] theorem cofan_inj_naturality_symm {S₁ S₂ : Split C} (Φ : S₁ ⟶ S₂) {Δ : SimplexCategoryᵒᵖ} (A : Splitting.IndexSet Δ) : (S₁.s.cofan Δ).inj A ≫ Φ.F.app Δ = Φ.f A.1.unop.len ≫ (S₂.s.cofan Δ).inj A := by rw [S₁.s.cofan_inj_eq, S₂.s.cofan_inj_eq, assoc, Φ.F.naturality, ← Φ.comm_assoc] variable (C) /-- The functor `SimplicialObject.Split C ⥤ SimplicialObject C` which forgets the splitting. -/ @[simps] def forget : Split C ⥤ SimplicialObject C where obj S := S.X map Φ := Φ.F /-- The functor `SimplicialObject.Split C ⥤ C` which sends a simplicial object equipped with a splitting to its nondegenerate `n`-simplices. -/ @[simps] def evalN (n : ℕ) : Split C ⥤ C where obj S := S.s.N n map Φ := Φ.f n /-- The inclusion of each summand in the coproduct decomposition of simplices in split simplicial objects is a natural transformation of functors `SimplicialObject.Split C ⥤ C` -/ @[simps] def natTransCofanInj {Δ : SimplexCategoryᵒᵖ} (A : Splitting.IndexSet Δ) : evalN C A.1.unop.len ⟶ forget C ⋙ (evaluation SimplexCategoryᵒᵖ C).obj Δ where app S := (S.s.cofan Δ).inj A naturality _ _ Φ := (cofan_inj_naturality_symm Φ A).symm end Split end SimplicialObject
Calculus.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.Geometry.Euclidean.Inversion.Basic import Mathlib.Analysis.InnerProductSpace.Calculus import Mathlib.Analysis.Calculus.Deriv.Inv import Mathlib.Tactic.AdaptationNote /-! # Derivative of the inversion In this file we prove a formula for the derivative of `EuclideanGeometry.inversion c R`. ## Implementation notes Since `fderiv` and related definitions do not work for affine spaces, we deal with an inner product space in this file. ## Keywords inversion, derivative -/ open Metric Function AffineMap Set AffineSubspace open scoped Topology RealInnerProductSpace variable {E F : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [NormedAddCommGroup F] [InnerProductSpace ℝ F] open EuclideanGeometry section DotNotation variable {c x : E → F} {R : E → ℝ} {s : Set E} {a : E} {n : ℕ∞} protected theorem ContDiffWithinAt.inversion (hc : ContDiffWithinAt ℝ n c s a) (hR : ContDiffWithinAt ℝ n R s a) (hx : ContDiffWithinAt ℝ n x s a) (hne : x a ≠ c a) : ContDiffWithinAt ℝ n (fun a ↦ inversion (c a) (R a) (x a)) s a := (((hR.div (hx.dist ℝ hc hne) (dist_ne_zero.2 hne)).pow _).smul (hx.sub hc)).add hc protected theorem ContDiffOn.inversion (hc : ContDiffOn ℝ n c s) (hR : ContDiffOn ℝ n R s) (hx : ContDiffOn ℝ n x s) (hne : ∀ a ∈ s, x a ≠ c a) : ContDiffOn ℝ n (fun a ↦ inversion (c a) (R a) (x a)) s := fun a ha ↦ (hc a ha).inversion (hR a ha) (hx a ha) (hne a ha) protected nonrec theorem ContDiffAt.inversion (hc : ContDiffAt ℝ n c a) (hR : ContDiffAt ℝ n R a) (hx : ContDiffAt ℝ n x a) (hne : x a ≠ c a) : ContDiffAt ℝ n (fun a ↦ inversion (c a) (R a) (x a)) a := hc.inversion hR hx hne protected nonrec theorem ContDiff.inversion (hc : ContDiff ℝ n c) (hR : ContDiff ℝ n R) (hx : ContDiff ℝ n x) (hne : ∀ a, x a ≠ c a) : ContDiff ℝ n (fun a ↦ inversion (c a) (R a) (x a)) := contDiff_iff_contDiffAt.2 fun a ↦ hc.contDiffAt.inversion hR.contDiffAt hx.contDiffAt (hne a) protected theorem DifferentiableWithinAt.inversion (hc : DifferentiableWithinAt ℝ c s a) (hR : DifferentiableWithinAt ℝ R s a) (hx : DifferentiableWithinAt ℝ x s a) (hne : x a ≠ c a) : DifferentiableWithinAt ℝ (fun a ↦ inversion (c a) (R a) (x a)) s a := -- TODO: Use `.div` https://github.com/leanprover-community/mathlib4/issues/5870 (((hR.mul <| (hx.dist ℝ hc hne).inv (dist_ne_zero.2 hne)).pow _).smul (hx.sub hc)).add hc protected theorem DifferentiableOn.inversion (hc : DifferentiableOn ℝ c s) (hR : DifferentiableOn ℝ R s) (hx : DifferentiableOn ℝ x s) (hne : ∀ a ∈ s, x a ≠ c a) : DifferentiableOn ℝ (fun a ↦ inversion (c a) (R a) (x a)) s := fun a ha ↦ (hc a ha).inversion (hR a ha) (hx a ha) (hne a ha) protected theorem DifferentiableAt.inversion (hc : DifferentiableAt ℝ c a) (hR : DifferentiableAt ℝ R a) (hx : DifferentiableAt ℝ x a) (hne : x a ≠ c a) : DifferentiableAt ℝ (fun a ↦ inversion (c a) (R a) (x a)) a := by rw [← differentiableWithinAt_univ] at * exact hc.inversion hR hx hne protected theorem Differentiable.inversion (hc : Differentiable ℝ c) (hR : Differentiable ℝ R) (hx : Differentiable ℝ x) (hne : ∀ a, x a ≠ c a) : Differentiable ℝ (fun a ↦ inversion (c a) (R a) (x a)) := fun a ↦ (hc a).inversion (hR a) (hx a) (hne a) end DotNotation namespace EuclideanGeometry variable {c x : F} {R : ℝ} /-- Formula for the Fréchet derivative of `EuclideanGeometry.inversion c R`. -/ theorem hasFDerivAt_inversion (hx : x ≠ c) : HasFDerivAt (inversion c R) ((R / dist x c) ^ 2 • ((ℝ ∙ (x - c))ᗮ.reflection : F →L[ℝ] F)) x := by rcases add_left_surjective c x with ⟨x, rfl⟩ have : HasFDerivAt (inversion c R) (?_ : F →L[ℝ] F) (c + x) := by simp +unfoldPartialApp only [inversion] simp_rw [dist_eq_norm, div_pow, div_eq_mul_inv] have A := (hasFDerivAt_id (𝕜 := ℝ) (c + x)).sub_const c have B := ((hasDerivAt_inv <| by simpa using hx).comp_hasFDerivAt _ A.norm_sq).const_mul (R ^ 2) exact (B.smul A).add_const c refine this.congr_fderiv (LinearMap.ext_on_codisjoint (Submodule.isCompl_orthogonal_of_hasOrthogonalProjection (K := ℝ ∙ x)).codisjoint (LinearMap.eqOn_span' ?_) fun y hy ↦ ?_) · have : ((‖x‖ ^ 2) ^ 2)⁻¹ * (‖x‖ ^ 2) = (‖x‖ ^ 2)⁻¹ := by rw [← div_eq_inv_mul, sq (‖x‖ ^ 2), div_self_mul_self'] simp [Submodule.reflection_orthogonalComplement_singleton_eq_neg, real_inner_self_eq_norm_sq, two_mul, this, div_eq_mul_inv, mul_add, add_smul, mul_pow] · simp [Submodule.mem_orthogonal_singleton_iff_inner_right.1 hy, Submodule.reflection_mem_subspace_eq_self hy, div_eq_mul_inv, mul_pow] end EuclideanGeometry
div.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. (******************************************************************************) (* This file deals with divisibility for natural numbers. *) (* It contains the definitions of: *) (* edivn m d == the pair composed of the quotient and remainder *) (* of the Euclidean division of m by d. *) (* m %/ d == quotient of the Euclidean division of m by d. *) (* m %% d == remainder of the Euclidean division of m by d. *) (* m = n %[mod d] <-> m equals n modulo d. *) (* m == n %[mod d] <=> m equals n modulo d (boolean version). *) (* m <> n %[mod d] <-> m differs from n modulo d. *) (* m != n %[mod d] <=> m differs from n modulo d (boolean version). *) (* d %| m <=> d divides m. *) (* gcdn m n == the GCD of m and n. *) (* egcdn m n == the extended GCD (Bezout coefficient pair) of m and n. *) (* If egcdn m n = (u, v), then gcdn m n = m * u - n * v. *) (* lcmn m n == the LCM of m and n. *) (* coprime m n <=> m and n are coprime (:= gcdn m n == 1). *) (* chinese m n r s == witness of the chinese remainder theorem. *) (* We adjoin an m to operator suffixes to indicate a nested %% (modn), as in *) (* modnDml : m %% d + n = m + n %[mod d]. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. (** Euclidean division *) Definition edivn_rec d := fix loop m q := if m - d is m'.+1 then loop m' q.+1 else (q, m). Definition edivn m d := if d > 0 then edivn_rec d.-1 m 0 else (0, m). Variant edivn_spec m d : nat * nat -> Type := EdivnSpec q r of m = q * d + r & (d > 0) ==> (r < d) : edivn_spec m d (q, r). Lemma edivnP m d : edivn_spec m d (edivn m d). Proof. rewrite -[m in edivn_spec m]/(0 * d + m) /edivn; case: d => //= d. elim/ltn_ind: m 0 => -[|m] IHm q //=; rewrite subn_if_gt. case: ltnP => // le_dm; rewrite -[in m.+1](subnKC le_dm) -addSn. by rewrite addnA -mulSnr; apply/IHm/leq_subr. Qed. Lemma edivn_eq d q r : r < d -> edivn (q * d + r) d = (q, r). Proof. move=> lt_rd; have d_gt0: 0 < d by apply: leq_trans lt_rd. case: edivnP lt_rd => q' r'; rewrite d_gt0 /=. wlog: q q' r r' / q <= q' by case/orP: (leq_total q q'); last symmetry; eauto. have [||-> _ /addnI ->] //= := ltngtP q q'. rewrite -(leq_pmul2r d_gt0) => /leq_add lt_qr _ eq_qr _ /lt_qr {lt_qr}. by rewrite addnS ltnNge mulSn -addnA eq_qr addnCA addnA leq_addr. Qed. Definition divn m d := (edivn m d).1. Notation "m %/ d" := (divn m d) : nat_scope. (* We redefine modn so that it is structurally decreasing. *) Definition modn_rec d := fix loop m := if m - d is m'.+1 then loop m' else m. Definition modn m d := if d > 0 then modn_rec d.-1 m else m. Notation "m %% d" := (modn m d) : nat_scope. Notation "m = n %[mod d ]" := (m %% d = n %% d) : nat_scope. Notation "m == n %[mod d ]" := (m %% d == n %% d) : nat_scope. Notation "m <> n %[mod d ]" := (m %% d <> n %% d) : nat_scope. Notation "m != n %[mod d ]" := (m %% d != n %% d) : nat_scope. Lemma modn_def m d : m %% d = (edivn m d).2. Proof. case: d => //= d; rewrite /modn /edivn /=; elim/ltn_ind: m 0 => -[|m] IHm q //=. by rewrite !subn_if_gt; case: (d <= m) => //; apply/IHm/leq_subr. Qed. Lemma edivn_def m d : edivn m d = (m %/ d, m %% d). Proof. by rewrite /divn modn_def; case: (edivn m d). Qed. Lemma divn_eq m d : m = m %/ d * d + m %% d. Proof. by rewrite /divn modn_def; case: edivnP. Qed. Lemma div0n d : 0 %/ d = 0. Proof. by case: d. Qed. Lemma divn0 m : m %/ 0 = 0. Proof. by []. Qed. Lemma mod0n d : 0 %% d = 0. Proof. by case: d. Qed. Lemma modn0 m : m %% 0 = m. Proof. by []. Qed. Lemma divn_small m d : m < d -> m %/ d = 0. Proof. by move=> lt_md; rewrite /divn (edivn_eq 0). Qed. Lemma divnMDl q m d : 0 < d -> (q * d + m) %/ d = q + m %/ d. Proof. move=> d_gt0; rewrite [in LHS](divn_eq m d) addnA -mulnDl. by rewrite /divn edivn_eq // modn_def; case: edivnP; rewrite d_gt0. Qed. Lemma mulnK m d : 0 < d -> m * d %/ d = m. Proof. by move=> d_gt0; rewrite -[m * d]addn0 divnMDl // div0n addn0. Qed. Lemma mulKn m d : 0 < d -> d * m %/ d = m. Proof. by move=> d_gt0; rewrite mulnC mulnK. Qed. Lemma expnB p m n : p > 0 -> m >= n -> p ^ (m - n) = p ^ m %/ p ^ n. Proof. by move=> p_gt0 /subnK-Dm; rewrite -[in RHS]Dm expnD mulnK // expn_gt0 p_gt0. Qed. Lemma modn1 m : m %% 1 = 0. Proof. by rewrite modn_def; case: edivnP => ? []. Qed. Lemma divn1 m : m %/ 1 = m. Proof. by rewrite [RHS](@divn_eq m 1) // modn1 addn0 muln1. Qed. Lemma divnn d : d %/ d = (0 < d). Proof. by case: d => // d; rewrite -[n in n %/ _]muln1 mulKn. Qed. Lemma divnMl p m d : p > 0 -> p * m %/ (p * d) = m %/ d. Proof. move=> p_gt0; have [->|d_gt0] := posnP d; first by rewrite muln0. rewrite [RHS]/divn; case: edivnP; rewrite d_gt0 /= => q r ->{m} lt_rd. rewrite mulnDr mulnCA divnMDl; last by rewrite muln_gt0 p_gt0. by rewrite addnC divn_small // ltn_pmul2l. Qed. Arguments divnMl [p m d]. Lemma divnMr p m d : p > 0 -> m * p %/ (d * p) = m %/ d. Proof. by move=> p_gt0; rewrite -!(mulnC p) divnMl. Qed. Arguments divnMr [p m d]. Lemma ltn_mod m d : (m %% d < d) = (0 < d). Proof. by case: d => // d; rewrite modn_def; case: edivnP. Qed. Lemma ltn_pmod m d : 0 < d -> m %% d < d. Proof. by rewrite ltn_mod. Qed. Lemma leq_divM m d : m %/ d * d <= m. Proof. by rewrite [leqRHS](divn_eq m d) leq_addr. Qed. #[deprecated(since="mathcomp 2.4.0", note="Renamed to leq_divM.")] Notation leq_trunc_div := leq_divM. Lemma leq_mod m d : m %% d <= m. Proof. by rewrite [leqRHS](divn_eq m d) leq_addl. Qed. Lemma leq_div m d : m %/ d <= m. Proof. by case: d => // d; apply: leq_trans (leq_pmulr _ _) (leq_divM _ _). Qed. Lemma ltn_ceil m d : 0 < d -> m < (m %/ d).+1 * d. Proof. by move=> d_gt0; rewrite [in m.+1](divn_eq m d) -addnS mulSnr leq_add2l ltn_mod. Qed. Lemma ltn_divLR m n d : d > 0 -> (m %/ d < n) = (m < n * d). Proof. move=> d_gt0; apply/idP/idP. by rewrite -(leq_pmul2r d_gt0); apply: leq_trans (ltn_ceil _ _). rewrite !ltnNge -(@leq_pmul2r d n) //; apply: contra => le_nd_floor. exact: leq_trans le_nd_floor (leq_divM _ _). Qed. Lemma leq_divRL m n d : d > 0 -> (m <= n %/ d) = (m * d <= n). Proof. by move=> d_gt0; rewrite leqNgt ltn_divLR // -leqNgt. Qed. Lemma ltn_Pdiv m d : 1 < d -> 0 < m -> m %/ d < m. Proof. by move=> d_gt1 m_gt0; rewrite ltn_divLR ?ltn_Pmulr // ltnW. Qed. Lemma divn_gt0 d m : 0 < d -> (0 < m %/ d) = (d <= m). Proof. by move=> d_gt0; rewrite leq_divRL ?mul1n. Qed. Lemma leq_div2r d m n : m <= n -> m %/ d <= n %/ d. Proof. have [-> //| d_gt0 le_mn] := posnP d. by rewrite leq_divRL // (leq_trans _ le_mn) -?leq_divRL. Qed. Lemma leq_div2l m d e : 0 < d -> d <= e -> m %/ e <= m %/ d. Proof. move/leq_divRL=> -> le_de. by apply: leq_trans (leq_divM m e); apply: leq_mul. Qed. Lemma edivnD m n d (offset := m %% d + n %% d >= d) : 0 < d -> edivn (m + n) d = (m %/ d + n %/ d + offset, m %% d + n %% d - offset * d). Proof. rewrite {}/offset; case: d => // d _; rewrite /divn !modn_def. case: (edivnP m d.+1) (edivnP n d.+1) => [/= q r -> r_lt] [/= p s -> s_lt]. rewrite addnACA -mulnDl; have [r_le s_le] := (ltnW r_lt, ltnW s_lt). have [d_ge|d_lt] := leqP; first by rewrite addn0 mul0n subn0 edivn_eq. rewrite addn1 mul1n -[in LHS](subnKC d_lt) addnA -mulSnr edivn_eq//. by rewrite ltn_subLR// -addnS leq_add. Qed. Lemma divnD m n d : 0 < d -> (m + n) %/ d = (m %/ d) + (n %/ d) + (m %% d + n %% d >= d). Proof. by move=> /(@edivnD m n); rewrite edivn_def => -[]. Qed. Lemma modnD m n d : 0 < d -> (m + n) %% d = m %% d + n %% d - (m %% d + n %% d >= d) * d. Proof. by move=> /(@edivnD m n); rewrite edivn_def => -[]. Qed. Lemma leqDmod m n d : 0 < d -> (d <= m %% d + n %% d) = ((m + n) %% d < n %% d). Proof. move=> d_gt0; rewrite modnD//. have [d_le|_] := leqP d; last by rewrite subn0 ltnNge leq_addl. by rewrite -(ltn_add2r d) mul1n (subnK d_le) addnC ltn_add2l ltn_pmod. Qed. Lemma divnB n m d : 0 < d -> (m - n) %/ d = (m %/ d) - (n %/ d) - (m %% d < n %% d). Proof. move=> d_gt0; have [mn|/ltnW nm] := leqP m n. by rewrite (eqP mn) (eqP (leq_div2r _ _)) ?div0n. by rewrite -[in m %/ d](subnK nm) divnD// addnAC addnK leqDmod ?subnK ?addnK. Qed. Lemma modnB m n d : 0 < d -> n <= m -> (m - n) %% d = (m %% d < n %% d) * d + m %% d - n %% d. Proof. move=> d_gt0 nm; rewrite -[in m %% _](subnK nm) -leqDmod// modnD//. have [d_le|_] := leqP d; last by rewrite mul0n add0n subn0 addnK. by rewrite mul1n addnBA// addnC !addnK. Qed. Lemma edivnB m n d (offset := m %% d < n %% d) : 0 < d -> n <= m -> edivn (m - n) d = (m %/ d - n %/ d - offset, offset * d + m %% d - n %% d). Proof. by move=> d_gt0 le_nm; rewrite edivn_def divnB// modnB. Qed. Lemma leq_divDl p m n : (m + n) %/ p <= m %/ p + n %/ p + 1. Proof. by have [->//|p_gt0] := posnP p; rewrite divnD// !leq_add// leq_b1. Qed. Lemma geq_divBl k m p : k %/ p - m %/ p <= (k - m) %/ p + 1. Proof. rewrite leq_subLR addnA; apply: leq_trans (leq_divDl _ _ _). by rewrite -maxnE leq_div2r ?leq_maxr. Qed. Lemma divnMA m n p : m %/ (n * p) = m %/ n %/ p. Proof. case: n p => [|n] [|p]; rewrite ?muln0 ?div0n //. rewrite [in RHS](divn_eq m (n.+1 * p.+1)) mulnA mulnAC !divnMDl //. by rewrite [_ %/ p.+1]divn_small ?addn0 // ltn_divLR // mulnC ltn_mod. Qed. Lemma divnAC m n p : m %/ n %/ p = m %/ p %/ n. Proof. by rewrite -!divnMA mulnC. Qed. Lemma modn_small m d : m < d -> m %% d = m. Proof. by move=> lt_md; rewrite [RHS](divn_eq m d) divn_small. Qed. Lemma modn_mod m d : m %% d = m %[mod d]. Proof. by case: d => // d; apply: modn_small; rewrite ltn_mod. Qed. Lemma modnMDl p m d : p * d + m = m %[mod d]. Proof. have [->|d_gt0] := posnP d; first by rewrite muln0. by rewrite [in LHS](divn_eq m d) addnA -mulnDl modn_def edivn_eq // ltn_mod. Qed. Lemma muln_modr p m d : p * (m %% d) = (p * m) %% (p * d). Proof. have [->//|p_gt0] := posnP p; apply: (@addnI (p * (m %/ d * d))). by rewrite -mulnDr -divn_eq mulnCA -(divnMl p_gt0) -divn_eq. Qed. Lemma muln_modl p m d : (m %% d) * p = (m * p) %% (d * p). Proof. by rewrite -!(mulnC p); apply: muln_modr. Qed. Lemma modn_divl m n d : (m %/ d) %% n = m %% (n * d) %/ d. Proof. case: d n => [|d] [|n] //; rewrite [in LHS]/divn [in LHS]modn_def. case: (edivnP m d.+1) edivnP => [/= _ r -> le_rd] [/= q s -> le_sn]. rewrite mulnDl -mulnA -addnA modnMDl modn_small ?divnMDl ?divn_small ?addn0//. by rewrite mulSnr -addnS leq_add ?leq_mul2r. Qed. Lemma modnDl m d : d + m = m %[mod d]. Proof. by rewrite -[m %% _](modnMDl 1) mul1n. Qed. Lemma modnDr m d : m + d = m %[mod d]. Proof. by rewrite addnC modnDl. Qed. Lemma modnn d : d %% d = 0. Proof. by rewrite [d %% d](modnDr 0) mod0n. Qed. Lemma modnMl p d : p * d %% d = 0. Proof. by rewrite -[p * d]addn0 modnMDl mod0n. Qed. Lemma modnMr p d : d * p %% d = 0. Proof. by rewrite mulnC modnMl. Qed. Lemma modnDml m n d : m %% d + n = m + n %[mod d]. Proof. by rewrite [in RHS](divn_eq m d) -addnA modnMDl. Qed. Lemma modnDmr m n d : m + n %% d = m + n %[mod d]. Proof. by rewrite !(addnC m) modnDml. Qed. Lemma modnDm m n d : m %% d + n %% d = m + n %[mod d]. Proof. by rewrite modnDml modnDmr. Qed. Lemma eqn_modDl p m n d : (p + m == p + n %[mod d]) = (m == n %[mod d]). Proof. case: d => [|d]; first by rewrite !modn0 eqn_add2l. apply/eqP/eqP=> eq_mn; last by rewrite -modnDmr eq_mn modnDmr. rewrite -(modnMDl p m) -(modnMDl p n) !mulnSr -!addnA. by rewrite -modnDmr eq_mn modnDmr. Qed. Lemma eqn_modDr p m n d : (m + p == n + p %[mod d]) = (m == n %[mod d]). Proof. by rewrite -!(addnC p) eqn_modDl. Qed. Lemma modnMml m n d : m %% d * n = m * n %[mod d]. Proof. by rewrite [in RHS](divn_eq m d) mulnDl mulnAC modnMDl. Qed. Lemma modnMmr m n d : m * (n %% d) = m * n %[mod d]. Proof. by rewrite !(mulnC m) modnMml. Qed. Lemma modnMm m n d : m %% d * (n %% d) = m * n %[mod d]. Proof. by rewrite modnMml modnMmr. Qed. Lemma modn2 m : m %% 2 = odd m. Proof. by elim: m => //= m IHm; rewrite -addn1 -modnDml IHm; case odd. Qed. Lemma divn2 m : m %/ 2 = m./2. Proof. by rewrite [in RHS](divn_eq m 2) modn2 muln2 addnC half_bit_double. Qed. Lemma odd_mod m d : odd d = false -> odd (m %% d) = odd m. Proof. by move=> d_even; rewrite [in RHS](divn_eq m d) oddD oddM d_even andbF. Qed. Lemma modnXm m n a : (a %% n) ^ m = a ^ m %[mod n]. Proof. by elim: m => // m IHm; rewrite !expnS -modnMmr IHm modnMml modnMmr. Qed. Lemma modnMDXl p m n d : (p * d + m) ^ n = m ^ n %[mod d]. Proof. by elim: n => // n IH; rewrite !expnS -modnMm IH modnMDl modnMm. Qed. (** Divisibility **) Definition dvdn d m := m %% d == 0. Notation "m %| d" := (dvdn m d) : nat_scope. Lemma dvdnP d m : reflect (exists k, m = k * d) (d %| m). Proof. apply: (iffP eqP) => [md0 | [k ->]]; last by rewrite modnMl. by exists (m %/ d); rewrite [LHS](divn_eq m d) md0 addn0. Qed. Arguments dvdnP {d m}. Lemma dvdn0 d : d %| 0. Proof. by case: d. Qed. Lemma dvd0n n : (0 %| n) = (n == 0). Proof. by case: n. Qed. Lemma dvdn1 d : (d %| 1) = (d == 1). Proof. by case: d => [|[|d]] //; rewrite /dvdn modn_small. Qed. Lemma dvd1n m : 1 %| m. Proof. by rewrite /dvdn modn1. Qed. Lemma dvdn_gt0 d m : m > 0 -> d %| m -> d > 0. Proof. by case: d => // /prednK <-. Qed. Lemma dvdnn m : m %| m. Proof. by rewrite /dvdn modnn. Qed. Lemma dvdn_mull d m n : d %| n -> d %| m * n. Proof. by case/dvdnP=> n' ->; rewrite /dvdn mulnA modnMl. Qed. Lemma dvdn_mulr d m n : d %| m -> d %| m * n. Proof. by move=> d_m; rewrite mulnC dvdn_mull. Qed. #[global] Hint Resolve dvdn0 dvd1n dvdnn dvdn_mull dvdn_mulr : core. Lemma dvdn_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2. Proof. by move=> /dvdnP[q1 ->] /dvdnP[q2 ->]; rewrite mulnCA -mulnA 2?dvdn_mull. Qed. Lemma dvdn_trans n d m : d %| n -> n %| m -> d %| m. Proof. by move=> d_dv_n /dvdnP[n1 ->]; apply: dvdn_mull. Qed. Lemma dvdn_eq d m : (d %| m) = (m %/ d * d == m). Proof. apply/eqP/eqP=> [modm0 | <-]; last exact: modnMl. by rewrite [RHS](divn_eq m d) modm0 addn0. Qed. Lemma dvdn2 n : (2 %| n) = ~~ odd n. Proof. by rewrite /dvdn modn2; case (odd n). Qed. Lemma dvdn_odd m n : m %| n -> odd n -> odd m. Proof. by move=> m_dv_n; apply: contraTT; rewrite -!dvdn2 => /dvdn_trans->. Qed. Lemma divnK d m : d %| m -> m %/ d * d = m. Proof. by rewrite dvdn_eq; move/eqP. Qed. Lemma leq_divLR d m n : d %| m -> (m %/ d <= n) = (m <= n * d). Proof. by case: d m => [|d] [|m] ///divnK=> {2}<-; rewrite leq_pmul2r. Qed. Lemma ltn_divRL d m n : d %| m -> (n < m %/ d) = (n * d < m). Proof. by move=> dv_d_m; rewrite !ltnNge leq_divLR. Qed. Lemma eqn_div d m n : d > 0 -> d %| m -> (n == m %/ d) = (n * d == m). Proof. by move=> d_gt0 dv_d_m; rewrite -(eqn_pmul2r d_gt0) divnK. Qed. Lemma eqn_mul d m n : d > 0 -> d %| m -> (m == n * d) = (m %/ d == n). Proof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqn_div // eq_sym. Qed. Lemma divn_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d. Proof. case: d m => [[] //| d m] dv_d_m; apply/eqP. by rewrite eqn_div ?dvdn_mulr // mulnAC divnK. Qed. Lemma muln_divA d m n : d %| n -> m * (n %/ d) = m * n %/ d. Proof. by move=> dv_d_m; rewrite !(mulnC m) divn_mulAC. Qed. Lemma muln_divCA d m n : d %| m -> d %| n -> m * (n %/ d) = n * (m %/ d). Proof. by move=> dv_d_m dv_d_n; rewrite mulnC divn_mulAC ?muln_divA. Qed. Lemma divnA m n p : p %| n -> m %/ (n %/ p) = m * p %/ n. Proof. by case: p => [|p] dv_n; rewrite -[in RHS](divnK dv_n) // divnMr. Qed. Lemma modn_dvdm m n d : d %| m -> n %% m = n %[mod d]. Proof. by case/dvdnP=> q def_m; rewrite [in RHS](divn_eq n m) def_m mulnA modnMDl. Qed. Lemma dvdn_leq d m : 0 < m -> d %| m -> d <= m. Proof. by move=> m_gt0 /dvdnP[[|k] Dm]; rewrite Dm // leq_addr in m_gt0 *. Qed. Lemma gtnNdvd n d : 0 < n -> n < d -> (d %| n) = false. Proof. by move=> n_gt0 lt_nd; rewrite /dvdn eqn0Ngt modn_small ?n_gt0. Qed. Lemma eqn_dvd m n : (m == n) = (m %| n) && (n %| m). Proof. case: m n => [|m] [|n] //; apply/idP/andP => [/eqP -> //| []]. by rewrite eqn_leq => Hmn Hnm; do 2 rewrite dvdn_leq //. Qed. Lemma dvdn_pmul2l p d m : 0 < p -> (p * d %| p * m) = (d %| m). Proof. by case: p => // p _; rewrite /dvdn -muln_modr // muln_eq0. Qed. Arguments dvdn_pmul2l [p d m]. Lemma dvdn_pmul2r p d m : 0 < p -> (d * p %| m * p) = (d %| m). Proof. by move=> p_gt0; rewrite -!(mulnC p) dvdn_pmul2l. Qed. Arguments dvdn_pmul2r [p d m]. Lemma dvdn_divLR p d m : 0 < p -> p %| d -> (d %/ p %| m) = (d %| m * p). Proof. by move=> /(@dvdn_pmul2r p _ m) <- /divnK->. Qed. Lemma dvdn_divRL p d m : p %| m -> (d %| m %/ p) = (d * p %| m). Proof. have [-> | /(@dvdn_pmul2r p d) <- /divnK-> //] := posnP p. by rewrite divn0 muln0 dvdn0. Qed. Lemma dvdn_div d m : d %| m -> m %/ d %| m. Proof. by move/divnK=> {2}<-; apply: dvdn_mulr. Qed. Lemma dvdn_exp2l p m n : m <= n -> p ^ m %| p ^ n. Proof. by move/subnK <-; rewrite expnD dvdn_mull. Qed. Lemma dvdn_Pexp2l p m n : p > 1 -> (p ^ m %| p ^ n) = (m <= n). Proof. move=> p_gt1; case: leqP => [|gt_n_m]; first exact: dvdn_exp2l. by rewrite gtnNdvd ?ltn_exp2l ?expn_gt0 // ltnW. Qed. Lemma dvdn_exp2r m n k : m %| n -> m ^ k %| n ^ k. Proof. by case/dvdnP=> q ->; rewrite expnMn dvdn_mull. Qed. Lemma divn_modl m n d : d %| n -> (m %% n) %/ d = (m %/ d) %% (n %/ d). Proof. by move=> dvd_dn; rewrite modn_divl divnK. Qed. Lemma dvdn_addr m d n : d %| m -> (d %| m + n) = (d %| n). Proof. by case/dvdnP=> q ->; rewrite /dvdn modnMDl. Qed. Lemma dvdn_addl n d m : d %| n -> (d %| m + n) = (d %| m). Proof. by rewrite addnC; apply: dvdn_addr. Qed. Lemma dvdn_add d m n : d %| m -> d %| n -> d %| m + n. Proof. by move/dvdn_addr->. Qed. Lemma dvdn_add_eq d m n : d %| m + n -> (d %| m) = (d %| n). Proof. by move=> dv_d_mn; apply/idP/idP => [/dvdn_addr | /dvdn_addl] <-. Qed. Lemma dvdn_subr d m n : n <= m -> d %| m -> (d %| m - n) = (d %| n). Proof. by move=> le_n_m dv_d_m; apply: dvdn_add_eq; rewrite subnK. Qed. Lemma dvdn_subl d m n : n <= m -> d %| n -> (d %| m - n) = (d %| m). Proof. by move=> le_n_m dv_d_m; rewrite -(dvdn_addl _ dv_d_m) subnK. Qed. Lemma dvdn_sub d m n : d %| m -> d %| n -> d %| m - n. Proof. by case: (leqP n m) => [le_nm /dvdn_subr <- // | /ltnW/eqnP ->]; rewrite dvdn0. Qed. Lemma dvdn_exp k d m : 0 < k -> d %| m -> d %| (m ^ k). Proof. by case: k => // k _ d_dv_m; rewrite expnS dvdn_mulr. Qed. Lemma dvdn_fact m n : 0 < m <= n -> m %| n`!. Proof. case: m => //= m; elim: n => //= n IHn; rewrite ltnS. have [/IHn/dvdn_mull->||-> _] // := ltngtP m n; exact: dvdn_mulr. Qed. #[global] Hint Resolve dvdn_add dvdn_sub dvdn_exp : core. Lemma eqn_mod_dvd d m n : n <= m -> (m == n %[mod d]) = (d %| m - n). Proof. by move/subnK=> Dm; rewrite -[n in LHS]add0n -[in LHS]Dm eqn_modDr mod0n. Qed. Lemma divnDMl q m d : 0 < d -> (m + q * d) %/ d = (m %/ d) + q. Proof. by move=> d_gt0; rewrite addnC divnMDl// addnC. Qed. Lemma divnMBl q m d : 0 < d -> (q * d - m) %/ d = q - (m %/ d) - (~~ (d %| m)). Proof. by move=> d_gt0; rewrite divnB// mulnK// modnMl lt0n. Qed. Lemma divnBMl q m d : (m - q * d) %/ d = (m %/ d) - q. Proof. by case: d => [|d]//=; rewrite divnB// mulnK// modnMl ltn0 subn0. Qed. Lemma divnDl m n d : d %| m -> (m + n) %/ d = m %/ d + n %/ d. Proof. by case: d => // d /divnK-Dm; rewrite -[in LHS]Dm divnMDl. Qed. Lemma divnDr m n d : d %| n -> (m + n) %/ d = m %/ d + n %/ d. Proof. by move=> dv_n; rewrite addnC divnDl // addnC. Qed. Lemma divnBl m n d : d %| m -> (m - n) %/ d = m %/ d - (n %/ d) - (~~ (d %| n)). Proof. by case: d => [|d] // /divnK-Dm; rewrite -[in LHS]Dm divnMBl. Qed. Lemma divnBr m n d : d %| n -> (m - n) %/ d = m %/ d - n %/ d. Proof. by case: d => [|d]// /divnK-Dm; rewrite -[in LHS]Dm divnBMl. Qed. Lemma edivnS m d : 0 < d -> edivn m.+1 d = if d %| m.+1 then ((m %/ d).+1, 0) else (m %/ d, (m %% d).+1). Proof. case: d => [|[|d]] //= _; first by rewrite edivn_def modn1 dvd1n !divn1. rewrite -addn1 /dvdn modn_def edivnD//= (@modn_small 1)// (@divn_small 1)//. rewrite addn1 addn0 ltnS; have [||<-] := ltngtP d.+1. - by rewrite ltnNge -ltnS ltn_pmod. - by rewrite addn0 mul0n subn0. - by rewrite addn1 mul1n subnn. Qed. Lemma modnS m d : m.+1 %% d = if d %| m.+1 then 0 else (m %% d).+1. Proof. by case: d => [|d]//; rewrite modn_def edivnS//; case: ifP. Qed. Lemma divnS m d : 0 < d -> m.+1 %/ d = (d %| m.+1) + m %/ d. Proof. by move=> d_gt0; rewrite /divn edivnS//; case: ifP. Qed. Lemma divn_pred m d : m.-1 %/ d = (m %/ d) - (d %| m). Proof. by case: d m => [|d] [|m]; rewrite ?divn1 ?dvd1n ?subn1//= divnS// addnC addnK. Qed. Lemma modn_pred m d : d != 1 -> 0 < m -> m.-1 %% d = if d %| m then d.-1 else (m %% d).-1. Proof. rewrite -subn1; case: d m => [|[|d]] [|m]//= _ _. by rewrite ?modn1 ?dvd1n ?modn0 ?subn1. rewrite modnB// (@modn_small 1)// [_ < _]leqn0 /dvdn mulnbl/= subn1. by case: eqP => // ->; rewrite addn0. Qed. Lemma edivn_pred m d : d != 1 -> 0 < m -> edivn m.-1 d = if d %| m then ((m %/ d).-1, d.-1) else (m %/ d, (m %% d).-1). Proof. move=> d_neq1 m_gt0; rewrite edivn_def divn_pred modn_pred//. by case: ifP; rewrite ?subn0 ?subn1. Qed. (***********************************************************************) (* A function that computes the gcd of 2 numbers *) (***********************************************************************) Fixpoint gcdn m n := let n' := n %% m in if n' is 0 then m else if m - n'.-1 is m'.+1 then gcdn (m' %% n') n' else n'. Arguments gcdn : simpl never. Lemma gcdnE m n : gcdn m n = if m == 0 then n else gcdn (n %% m) m. Proof. elim/ltn_ind: m n => -[|m] IHm [|n] //=; rewrite /gcdn -/gcdn. case def_p: (_ %% _) => // [p]. have{def_p} lt_pm: p.+1 < m.+1 by rewrite -def_p ltn_pmod. rewrite {}IHm // subn_if_gt ltnW //=; congr gcdn. by rewrite -(subnK (ltnW lt_pm)) modnDr. Qed. Lemma gcdnn : idempotent_op gcdn. Proof. by case=> // n; rewrite gcdnE modnn. Qed. Lemma gcdnC : commutative gcdn. Proof. move=> m n; wlog lt_nm: m n / n < m by have [? ->|? <-|-> //] := ltngtP n m. by rewrite gcdnE -[in m == 0](ltn_predK lt_nm) modn_small. Qed. Lemma gcd0n : left_id 0 gcdn. Proof. by case. Qed. Lemma gcdn0 : right_id 0 gcdn. Proof. by case. Qed. Lemma gcd1n : left_zero 1 gcdn. Proof. by move=> n; rewrite gcdnE modn1. Qed. Lemma gcdn1 : right_zero 1 gcdn. Proof. by move=> n; rewrite gcdnC gcd1n. Qed. Lemma dvdn_gcdr m n : gcdn m n %| n. Proof. elim/ltn_ind: m n => -[|m] IHm [|n] //=. rewrite gcdnE; case def_p: (_ %% _) => [|p]; first by rewrite /dvdn def_p. have lt_pm: p < m by rewrite -ltnS -def_p ltn_pmod. rewrite /= (divn_eq n.+1 m.+1) def_p dvdn_addr ?dvdn_mull //; last exact: IHm. by rewrite gcdnE /= IHm // (ltn_trans (ltn_pmod _ _)). Qed. Lemma dvdn_gcdl m n : gcdn m n %| m. Proof. by rewrite gcdnC dvdn_gcdr. Qed. Lemma gcdn_gt0 m n : (0 < gcdn m n) = (0 < m) || (0 < n). Proof. by case: m n => [|m] [|n] //; apply: (@dvdn_gt0 _ m.+1) => //; apply: dvdn_gcdl. Qed. Lemma gcdnMDl k m n : gcdn m (k * m + n) = gcdn m n. Proof. by rewrite !(gcdnE m) modnMDl mulnC; case: m. Qed. Lemma gcdnDl m n : gcdn m (m + n) = gcdn m n. Proof. by rewrite -[m in m + n]mul1n gcdnMDl. Qed. Lemma gcdnDr m n : gcdn m (n + m) = gcdn m n. Proof. by rewrite addnC gcdnDl. Qed. Lemma gcdnMl n m : gcdn n (m * n) = n. Proof. by case: n => [|n]; rewrite gcdnE modnMl // muln0. Qed. Lemma gcdnMr n m : gcdn n (n * m) = n. Proof. by rewrite mulnC gcdnMl. Qed. Lemma gcdn_idPl {m n} : reflect (gcdn m n = m) (m %| n). Proof. by apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (gcdnMl, dvdn_gcdr). Qed. Lemma gcdn_idPr {m n} : reflect (gcdn m n = n) (n %| m). Proof. by rewrite gcdnC; apply: gcdn_idPl. Qed. Lemma expn_min e m n : e ^ minn m n = gcdn (e ^ m) (e ^ n). Proof. by case: leqP => [|/ltnW] /(dvdn_exp2l e) /gcdn_idPl; rewrite gcdnC. Qed. Lemma gcdn_modr m n : gcdn m (n %% m) = gcdn m n. Proof. by rewrite [in RHS](divn_eq n m) gcdnMDl. Qed. Lemma gcdn_modl m n : gcdn (m %% n) n = gcdn m n. Proof. by rewrite !(gcdnC _ n) gcdn_modr. Qed. (* Extended gcd, which computes Bezout coefficients. *) Fixpoint Bezout_rec km kn qs := if qs is q :: qs' then Bezout_rec kn (NatTrec.add_mul q kn km) qs' else (km, kn). Fixpoint egcdn_rec m n s qs := if s is s'.+1 then let: (q, r) := edivn m n in if r > 0 then egcdn_rec n r s' (q :: qs) else if odd (size qs) then qs else q.-1 :: qs else [::0]. Definition egcdn m n := Bezout_rec 0 1 (egcdn_rec m n n [::]). Variant egcdn_spec m n : nat * nat -> Type := EgcdnSpec km kn of km * m = kn * n + gcdn m n & kn * gcdn m n < m : egcdn_spec m n (km, kn). Lemma egcd0n n : egcdn 0 n = (1, 0). Proof. by case: n. Qed. Lemma egcdnP m n : m > 0 -> egcdn_spec m n (egcdn m n). Proof. have [-> /= | n_gt0 m_gt0] := posnP n; first by split; rewrite // mul1n gcdn0. rewrite /egcdn; set s := (s in egcdn_rec _ _ s); pose bz := Bezout_rec n m [::]. have: n < s.+1 by []; move defSpec: (egcdn_spec bz.2 bz.1) s => Spec s. elim: s => [[]|s IHs] //= in n m (qs := [::]) bz defSpec n_gt0 m_gt0 *. case: edivnP => q r def_m; rewrite n_gt0 ltnS /= => lt_rn le_ns1. case: posnP => [r0 {s le_ns1 IHs lt_rn}|r_gt0]; last first. by apply: IHs => //=; [rewrite natTrecE -def_m | rewrite (leq_trans lt_rn)]. rewrite {r}r0 addn0 in def_m; set b := odd _; pose d := gcdn m n. pose km := ~~ b : nat; pose kn := if b then 1 else q.-1. rewrite [bz in Spec bz](_ : _ = Bezout_rec km kn qs); last first. by rewrite /kn /km; case: (b) => //=; rewrite natTrecE addn0 muln1. have def_d: d = n by rewrite /d def_m gcdnC gcdnE modnMl gcd0n -[n]prednK. have: km * m + 2 * b * d = kn * n + d. rewrite {}/kn {}/km def_m def_d -mulSnr; case: b; rewrite //= addn0 mul1n. by rewrite prednK //; apply: dvdn_gt0 m_gt0 _; rewrite def_m dvdn_mulr. have{def_m}: kn * d <= m. have q_gt0 : 0 < q by rewrite def_m muln_gt0 n_gt0 ?andbT in m_gt0. by rewrite /kn; case b; rewrite def_d def_m leq_pmul2r // leq_pred. have{def_d}: km * d <= n by rewrite -[n]mul1n def_d leq_pmul2r // leq_b1. move: km {q}kn m_gt0 n_gt0 defSpec; rewrite {}/b {}/d {}/bz. elim: qs m n => [|q qs IHq] n r kn kr n_gt0 r_gt0 /=. set d := gcdn n r; rewrite mul0n addn0 => <- le_kn_r _ def_d; split=> //. have d_gt0: 0 < d by rewrite gcdn_gt0 n_gt0. have /ltn_pmul2l<-: 0 < kn by rewrite -(ltn_pmul2r n_gt0) def_d ltn_addl. by rewrite def_d -addn1 leq_add // mulnCA leq_mul2l le_kn_r orbT. rewrite !natTrecE; set m := _ + r; set km := _ + kn; pose d := gcdn m n. have ->: gcdn n r = d by rewrite [d]gcdnC gcdnMDl. have m_gt0: 0 < m by rewrite addn_gt0 r_gt0 orbT. have d_gt0: 0 < d by rewrite gcdn_gt0 m_gt0. move=> {}/IHq IHq le_kn_r le_kr_n def_d; apply: IHq => //; rewrite -/d. by rewrite mulnDl leq_add // -mulnA leq_mul2l le_kr_n orbT. apply: (@addIn d); rewrite mulnDr -addnA addnACA -def_d addnACA mulnA. rewrite -!mulnDl -mulnDr -addnA [kr * _]mulnC; congr addn. by rewrite addnC addn_negb muln1 mul2n addnn. Qed. Lemma Bezoutl m n : m > 0 -> {a | a < m & m %| gcdn m n + a * n}. Proof. move=> m_gt0; case: (egcdnP n m_gt0) => km kn def_d lt_kn_m. exists kn; last by rewrite addnC -def_d dvdn_mull. apply: leq_ltn_trans lt_kn_m. by rewrite -{1}[kn]muln1 leq_mul2l gcdn_gt0 m_gt0 orbT. Qed. Lemma Bezoutr m n : n > 0 -> {a | a < n & n %| gcdn m n + a * m}. Proof. by rewrite gcdnC; apply: Bezoutl. Qed. (* Back to the gcd. *) Lemma dvdn_gcd p m n : p %| gcdn m n = (p %| m) && (p %| n). Proof. apply/idP/andP=> [dv_pmn | [dv_pm dv_pn]]. by rewrite !(dvdn_trans dv_pmn) ?dvdn_gcdl ?dvdn_gcdr. have [->|n_gt0] := posnP n; first by rewrite gcdn0. case: (Bezoutr m n_gt0) => // km _ /(dvdn_trans dv_pn). by rewrite dvdn_addl // dvdn_mull. Qed. Lemma gcdnAC : right_commutative gcdn. Proof. suffices dvd m n p: gcdn (gcdn m n) p %| gcdn (gcdn m p) n. by move=> m n p; apply/eqP; rewrite eqn_dvd !dvd. rewrite !dvdn_gcd dvdn_gcdr. by rewrite !(dvdn_trans (dvdn_gcdl _ p)) ?dvdn_gcdl ?dvdn_gcdr. Qed. Lemma gcdnA : associative gcdn. Proof. by move=> m n p; rewrite !(gcdnC m) gcdnAC. Qed. Lemma gcdnCA : left_commutative gcdn. Proof. by move=> m n p; rewrite !gcdnA (gcdnC m). Qed. Lemma gcdnACA : interchange gcdn gcdn. Proof. by move=> m n p q; rewrite -!gcdnA (gcdnCA n). Qed. Lemma muln_gcdr : right_distributive muln gcdn. Proof. move=> p m n; have [-> //|p_gt0] := posnP p. elim/ltn_ind: m n => m IHm n; rewrite gcdnE [RHS]gcdnE muln_eq0 (gtn_eqF p_gt0). by case: posnP => // m_gt0; rewrite -muln_modr //=; apply/IHm/ltn_pmod. Qed. Lemma muln_gcdl : left_distributive muln gcdn. Proof. by move=> m n p; rewrite -!(mulnC p) muln_gcdr. Qed. Lemma gcdn_def d m n : d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) -> gcdn m n = d. Proof. move=> dv_dm dv_dn gdv_d; apply/eqP. by rewrite eqn_dvd dvdn_gcd dv_dm dv_dn gdv_d ?dvdn_gcdl ?dvdn_gcdr. Qed. Lemma muln_divCA_gcd n m : n * (m %/ gcdn n m) = m * (n %/ gcdn n m). Proof. by rewrite muln_divCA ?dvdn_gcdl ?dvdn_gcdr. Qed. (* We derive the lcm directly. *) Definition lcmn m n := m * n %/ gcdn m n. Lemma lcmnC : commutative lcmn. Proof. by move=> m n; rewrite /lcmn mulnC gcdnC. Qed. Lemma lcm0n : left_zero 0 lcmn. Proof. by move=> n; apply: div0n. Qed. Lemma lcmn0 : right_zero 0 lcmn. Proof. by move=> n; rewrite lcmnC lcm0n. Qed. Lemma lcm1n : left_id 1 lcmn. Proof. by move=> n; rewrite /lcmn gcd1n mul1n divn1. Qed. Lemma lcmn1 : right_id 1 lcmn. Proof. by move=> n; rewrite lcmnC lcm1n. Qed. Lemma muln_lcm_gcd m n : lcmn m n * gcdn m n = m * n. Proof. by apply/eqP; rewrite divnK ?dvdn_mull ?dvdn_gcdr. Qed. Lemma lcmn_gt0 m n : (0 < lcmn m n) = (0 < m) && (0 < n). Proof. by rewrite -muln_gt0 ltn_divRL ?dvdn_mull ?dvdn_gcdr. Qed. Lemma muln_lcmr : right_distributive muln lcmn. Proof. case=> // m n p; rewrite /lcmn -muln_gcdr -!mulnA divnMl // mulnCA. by rewrite muln_divA ?dvdn_mull ?dvdn_gcdr. Qed. Lemma muln_lcml : left_distributive muln lcmn. Proof. by move=> m n p; rewrite -!(mulnC p) muln_lcmr. Qed. Lemma lcmnA : associative lcmn. Proof. move=> m n p; rewrite [LHS]/lcmn [RHS]/lcmn mulnC. rewrite !divn_mulAC ?dvdn_mull ?dvdn_gcdr // -!divnMA ?dvdn_mulr ?dvdn_gcdl //. rewrite mulnC mulnA !muln_gcdr; congr (_ %/ _). by rewrite ![_ * lcmn _ _]mulnC !muln_lcm_gcd !muln_gcdl -!(mulnC m) gcdnA. Qed. Lemma lcmnCA : left_commutative lcmn. Proof. by move=> m n p; rewrite !lcmnA (lcmnC m). Qed. Lemma lcmnAC : right_commutative lcmn. Proof. by move=> m n p; rewrite -!lcmnA (lcmnC n). Qed. Lemma lcmnACA : interchange lcmn lcmn. Proof. by move=> m n p q; rewrite -!lcmnA (lcmnCA n). Qed. Lemma dvdn_lcml d1 d2 : d1 %| lcmn d1 d2. Proof. by rewrite /lcmn -muln_divA ?dvdn_gcdr ?dvdn_mulr. Qed. Lemma dvdn_lcmr d1 d2 : d2 %| lcmn d1 d2. Proof. by rewrite lcmnC dvdn_lcml. Qed. Lemma dvdn_lcm d1 d2 m : lcmn d1 d2 %| m = (d1 %| m) && (d2 %| m). Proof. case: d1 d2 => [|d1] [|d2]; try by case: m => [|m]; rewrite ?lcmn0 ?andbF. rewrite -(@dvdn_pmul2r (gcdn d1.+1 d2.+1)) ?gcdn_gt0 // muln_lcm_gcd. by rewrite muln_gcdr dvdn_gcd {1}mulnC andbC !dvdn_pmul2r. Qed. Lemma lcmnMl m n : lcmn m (m * n) = m * n. Proof. by case: m => // m; rewrite /lcmn gcdnMr mulKn. Qed. Lemma lcmnMr m n : lcmn n (m * n) = m * n. Proof. by rewrite mulnC lcmnMl. Qed. Lemma lcmn_idPr {m n} : reflect (lcmn m n = n) (m %| n). Proof. by apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (lcmnMr, dvdn_lcml). Qed. Lemma lcmn_idPl {m n} : reflect (lcmn m n = m) (n %| m). Proof. by rewrite lcmnC; apply: lcmn_idPr. Qed. Lemma expn_max e m n : e ^ maxn m n = lcmn (e ^ m) (e ^ n). Proof. by case: leqP => [|/ltnW] /(dvdn_exp2l e) /lcmn_idPl; rewrite lcmnC. Qed. (* Coprime factors *) Definition coprime m n := gcdn m n == 1. Lemma coprime1n n : coprime 1 n. Proof. by rewrite /coprime gcd1n. Qed. Lemma coprimen1 n : coprime n 1. Proof. by rewrite /coprime gcdn1. Qed. Lemma coprime_sym m n : coprime m n = coprime n m. Proof. by rewrite /coprime gcdnC. Qed. Lemma coprime_modl m n : coprime (m %% n) n = coprime m n. Proof. by rewrite /coprime gcdn_modl. Qed. Lemma coprime_modr m n : coprime m (n %% m) = coprime m n. Proof. by rewrite /coprime gcdn_modr. Qed. Lemma coprime2n n : coprime 2 n = odd n. Proof. by rewrite -coprime_modr modn2; case: (odd n). Qed. Lemma coprimen2 n : coprime n 2 = odd n. Proof. by rewrite coprime_sym coprime2n. Qed. Lemma coprimeSn n : coprime n.+1 n. Proof. by rewrite -coprime_modl (modnDr 1) coprime_modl coprime1n. Qed. Lemma coprimenS n : coprime n n.+1. Proof. by rewrite coprime_sym coprimeSn. Qed. Lemma coprimePn n : n > 0 -> coprime n.-1 n. Proof. by case: n => // n _; rewrite coprimenS. Qed. Lemma coprimenP n : n > 0 -> coprime n n.-1. Proof. by case: n => // n _; rewrite coprimeSn. Qed. Lemma coprimeP n m : n > 0 -> reflect (exists u, u.1 * n - u.2 * m = 1) (coprime n m). Proof. move=> n_gt0; apply: (iffP eqP) => [<-| [[kn km] /= kn_km_1]]. by have [kn km kg _] := egcdnP m n_gt0; exists (kn, km); rewrite kg addKn. apply gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m. by rewrite -kn_km_1 dvdn_subr ?dvdn_mull // ltnW // -subn_gt0 kn_km_1. Qed. Lemma modn_coprime k n : 0 < k -> (exists u, (k * u) %% n = 1) -> coprime k n. Proof. move=> k_gt0 [u Hu]; apply/coprimeP=> //. by exists (u, k * u %/ n); rewrite /= mulnC {1}(divn_eq (k * u) n) addKn. Qed. Lemma Gauss_dvd m n p : coprime m n -> (m * n %| p) = (m %| p) && (n %| p). Proof. by move=> co_mn; rewrite -muln_lcm_gcd (eqnP co_mn) muln1 dvdn_lcm. Qed. Lemma Gauss_dvdr m n p : coprime m n -> (m %| n * p) = (m %| p). Proof. case: n => [|n] co_mn; first by case: m co_mn => [|[]] // _; rewrite !dvd1n. by symmetry; rewrite mulnC -(@dvdn_pmul2r n.+1) ?Gauss_dvd // andbC dvdn_mull. Qed. Lemma Gauss_dvdl m n p : coprime m p -> (m %| n * p) = (m %| n). Proof. by rewrite mulnC; apply: Gauss_dvdr. Qed. Lemma dvdn_double_leq m n : m %| n -> odd m -> ~~ odd n -> 0 < n -> m.*2 <= n. Proof. move=> m_dv_n odd_m even_n n_gt0. by rewrite -muln2 dvdn_leq // Gauss_dvd ?coprimen2 ?m_dv_n ?dvdn2. Qed. Lemma dvdn_double_ltn m n : m %| n.-1 -> odd m -> odd n -> 1 < n -> m.*2 < n. Proof. by case: n => //; apply: dvdn_double_leq. Qed. Lemma Gauss_gcdr p m n : coprime p m -> gcdn p (m * n) = gcdn p n. Proof. move=> co_pm; apply/eqP; rewrite eqn_dvd !dvdn_gcd !dvdn_gcdl /=. rewrite andbC dvdn_mull ?dvdn_gcdr //= -(@Gauss_dvdr _ m) ?dvdn_gcdr //. by rewrite /coprime gcdnAC (eqnP co_pm) gcd1n. Qed. Lemma Gauss_gcdl p m n : coprime p n -> gcdn p (m * n) = gcdn p m. Proof. by move=> co_pn; rewrite mulnC Gauss_gcdr. Qed. Lemma coprimeMr p m n : coprime p (m * n) = coprime p m && coprime p n. Proof. case co_pm: (coprime p m) => /=; first by rewrite /coprime Gauss_gcdr. apply/eqP=> co_p_mn; case/eqnP: co_pm; apply gcdn_def => // d dv_dp dv_dm. by rewrite -co_p_mn dvdn_gcd dv_dp dvdn_mulr. Qed. Lemma coprimeMl p m n : coprime (m * n) p = coprime m p && coprime n p. Proof. by rewrite -!(coprime_sym p) coprimeMr. Qed. Lemma coprime_pexpl k m n : 0 < k -> coprime (m ^ k) n = coprime m n. Proof. case: k => // k _; elim: k => [|k IHk]; first by rewrite expn1. by rewrite expnS coprimeMl -IHk; case coprime. Qed. Lemma coprime_pexpr k m n : 0 < k -> coprime m (n ^ k) = coprime m n. Proof. by move=> k_gt0; rewrite !(coprime_sym m) coprime_pexpl. Qed. Lemma coprimeXl k m n : coprime m n -> coprime (m ^ k) n. Proof. by case: k => [|k] co_pm; rewrite ?coprime1n // coprime_pexpl. Qed. Lemma coprimeXr k m n : coprime m n -> coprime m (n ^ k). Proof. by rewrite !(coprime_sym m); apply: coprimeXl. Qed. Lemma coprime_dvdl m n p : m %| n -> coprime n p -> coprime m p. Proof. by case/dvdnP=> d ->; rewrite coprimeMl => /andP[]. Qed. Lemma coprime_dvdr m n p : m %| n -> coprime p n -> coprime p m. Proof. by rewrite !(coprime_sym p); apply: coprime_dvdl. Qed. Lemma coprime_egcdn n m : n > 0 -> coprime (egcdn n m).1 (egcdn n m).2. Proof. move=> n_gt0; case: (egcdnP m n_gt0) => kn km /= /eqP. have [/dvdnP[u defn] /dvdnP[v defm]] := (dvdn_gcdl n m, dvdn_gcdr n m). rewrite -[gcdn n m]mul1n {1}defm {1}defn !mulnA -mulnDl addnC. rewrite eqn_pmul2r ?gcdn_gt0 ?n_gt0 //; case: kn => // kn /eqP def_knu _. by apply/coprimeP=> //; exists (u, v); rewrite mulnC def_knu mulnC addnK. Qed. Lemma dvdn_pexp2r m n k : k > 0 -> (m ^ k %| n ^ k) = (m %| n). Proof. move=> k_gt0; apply/idP/idP=> [dv_mn_k|]; last exact: dvdn_exp2r. have [->|n_gt0] := posnP n; first by rewrite dvdn0. have [n' def_n] := dvdnP (dvdn_gcdr m n); set d := gcdn m n in def_n. have [m' def_m] := dvdnP (dvdn_gcdl m n); rewrite -/d in def_m. have d_gt0: d > 0 by rewrite gcdn_gt0 n_gt0 orbT. rewrite def_m def_n !expnMn dvdn_pmul2r ?expn_gt0 ?d_gt0 // in dv_mn_k. have: coprime (m' ^ k) (n' ^ k). rewrite coprime_pexpl // coprime_pexpr // /coprime -(eqn_pmul2r d_gt0) mul1n. by rewrite muln_gcdl -def_m -def_n. rewrite /coprime -gcdn_modr (eqnP dv_mn_k) gcdn0 -(exp1n k). by rewrite (inj_eq (expIn k_gt0)) def_m; move/eqP->; rewrite mul1n dvdn_gcdr. Qed. Section Chinese. (***********************************************************************) (* The chinese remainder theorem *) (***********************************************************************) Variables m1 m2 : nat. Hypothesis co_m12 : coprime m1 m2. Lemma chinese_remainder x y : (x == y %[mod m1 * m2]) = (x == y %[mod m1]) && (x == y %[mod m2]). Proof. wlog le_yx : x y / y <= x; last by rewrite !eqn_mod_dvd // Gauss_dvd. by have [?|/ltnW ?] := leqP y x; last rewrite !(eq_sym (x %% _)); apply. Qed. (***********************************************************************) (* A function that solves the chinese remainder problem *) (***********************************************************************) Definition chinese r1 r2 := r1 * m2 * (egcdn m2 m1).1 + r2 * m1 * (egcdn m1 m2).1. Lemma chinese_modl r1 r2 : chinese r1 r2 = r1 %[mod m1]. Proof. rewrite /chinese; case: (posnP m2) co_m12 => [-> /eqnP | m2_gt0 _]. by rewrite gcdn0 => ->; rewrite !modn1. case: egcdnP => // k2 k1 def_m1 _. rewrite mulnAC -mulnA def_m1 gcdnC (eqnP co_m12) mulnDr mulnA muln1. by rewrite addnAC (mulnAC _ m1) -mulnDl modnMDl. Qed. Lemma chinese_modr r1 r2 : chinese r1 r2 = r2 %[mod m2]. Proof. rewrite /chinese; case: (posnP m1) co_m12 => [-> /eqnP | m1_gt0 _]. by rewrite gcd0n => ->; rewrite !modn1. case: (egcdnP m2) => // k1 k2 def_m2 _. rewrite addnC mulnAC -mulnA def_m2 (eqnP co_m12) mulnDr mulnA muln1. by rewrite addnAC (mulnAC _ m2) -mulnDl modnMDl. Qed. Lemma chinese_mod x : x = chinese (x %% m1) (x %% m2) %[mod m1 * m2]. Proof. apply/eqP; rewrite chinese_remainder //. by rewrite chinese_modl chinese_modr !modn_mod !eqxx. Qed. End Chinese.
Tangent.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, Floris van Doorn -/ import Mathlib.Geometry.Manifold.MFDeriv.Atlas import Mathlib.Geometry.Manifold.MFDeriv.UniqueDifferential import Mathlib.Geometry.Manifold.VectorBundle.Tangent import Mathlib.Geometry.Manifold.Diffeomorph /-! # Derivatives of maps in the tangent bundle This file contains properties of derivatives which need the manifold structure of the tangent bundle. Notably, it includes formulas for the tangent maps to charts, and unique differentiability statements for subsets of the tangent bundle. -/ open Bundle Set open scoped Manifold variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] {I : ModelWithCorners 𝕜 E H} {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] {E' : Type*} [NormedAddCommGroup E'] [NormedSpace 𝕜 E'] {H' : Type*} [TopologicalSpace H'] {I' : ModelWithCorners 𝕜 E' H'} {M' : Type*} [TopologicalSpace M'] [ChartedSpace H' M'] [IsManifold I' 1 M'] /-- The derivative of the chart at a base point is the chart of the tangent bundle, composed with the identification between the tangent bundle of the model space and the product space. -/ theorem tangentMap_chart {p q : TangentBundle I M} (h : q.1 ∈ (chartAt H p.1).source) : tangentMap I I (chartAt H p.1) q = (TotalSpace.toProd _ _).symm ((chartAt (ModelProd H E) p : TangentBundle I M → ModelProd H E) q) := by dsimp [tangentMap] rw [MDifferentiableAt.mfderiv] · rfl · exact mdifferentiableAt_atlas (chart_mem_atlas _ _) h /-- The derivative of the inverse of the chart at a base point is the inverse of the chart of the tangent bundle, composed with the identification between the tangent bundle of the model space and the product space. -/ theorem tangentMap_chart_symm {p : TangentBundle I M} {q : TangentBundle I H} (h : q.1 ∈ (chartAt H p.1).target) : tangentMap I I (chartAt H p.1).symm q = (chartAt (ModelProd H E) p).symm (TotalSpace.toProd H E q) := by dsimp only [tangentMap] rw [MDifferentiableAt.mfderiv (mdifferentiableAt_atlas_symm (chart_mem_atlas _ _) h)] simp only [TangentBundle.chartAt, tangentBundleCore, mfld_simps, (· ∘ ·)] -- `simp` fails to apply `PartialEquiv.prod_symm` with `ModelProd` congr exact ((chartAt H (TotalSpace.proj p)).right_inv h).symm lemma mfderiv_chartAt_eq_tangentCoordChange {x y : M} (hsrc : x ∈ (chartAt H y).source) : mfderiv I I (chartAt H y) x = tangentCoordChange I x y x := by have := mdifferentiableAt_atlas (I := I) (ChartedSpace.chart_mem_atlas _) hsrc simp [mfderiv, if_pos this, Function.comp_assoc] /-- The preimage under the projection from the tangent bundle of a set with unique differential in the basis also has unique differential. -/ theorem UniqueMDiffOn.tangentBundle_proj_preimage {s : Set M} (hs : UniqueMDiffOn I s) : UniqueMDiffOn I.tangent (π E (TangentSpace I) ⁻¹' s) := hs.bundle_preimage _ /-- To write a linear map between tangent spaces in coordinates amounts to precomposing and postcomposing it with derivatives of extended charts. Concrete version of `inTangentCoordinates_eq`. -/ lemma inTangentCoordinates_eq_mfderiv_comp {N : Type*} {f : N → M} {g : N → M'} {ϕ : Π x : N, TangentSpace I (f x) →L[𝕜] TangentSpace I' (g x)} {x₀ : N} {x : N} (hx : f x ∈ (chartAt H (f x₀)).source) (hy : g x ∈ (chartAt H' (g x₀)).source) : inTangentCoordinates I I' f g ϕ x₀ x = (mfderiv I' 𝓘(𝕜, E') (extChartAt I' (g x₀)) (g x)) ∘L (ϕ x) ∘L (mfderivWithin 𝓘(𝕜, E) I (extChartAt I (f x₀)).symm (range I) (extChartAt I (f x₀) (f x))) := by rw [inTangentCoordinates_eq _ _ _ hx hy, tangentBundleCore_coordChange] congr · have : MDifferentiableAt I' 𝓘(𝕜, E') (extChartAt I' (g x₀)) (g x) := mdifferentiableAt_extChartAt hy simp_all [mfderiv] · simp only [mfderivWithin, writtenInExtChartAt, modelWithCornersSelf_coe, range_id, inter_univ] rw [if_pos] · simp [Function.comp_def, PartialHomeomorph.left_inv (chartAt H (f x₀)) hx] · apply mdifferentiableWithinAt_extChartAt_symm apply (extChartAt I (f x₀)).map_source simpa using hx open Bundle variable (I) in /-- The canonical identification between the tangent bundle to the model space and the product, as a diffeomorphism -/ def tangentBundleModelSpaceDiffeomorph (n : ℕ∞) : TangentBundle I H ≃ₘ^n⟮I.tangent, I.prod 𝓘(𝕜, E)⟯ ModelProd H E where __ := TotalSpace.toProd H E contMDiff_toFun := contMDiff_tangentBundleModelSpaceHomeomorph contMDiff_invFun := contMDiff_tangentBundleModelSpaceHomeomorph_symm
abel.lean
import Mathlib.Tactic.Abel set_option linter.unusedVariables false variable {α : Type _} {a b : α} example [AddCommMonoid α] : a + (b + a) = a + a + b := by abel example [AddCommGroup α] : (a + b) - ((b + a) + a) = -a := by abel example [AddCommGroup α] (x : α) : x - 0 = x := by abel example [AddCommMonoid α] : (3 : ℕ) • a = a + (2 : ℕ) • a := by abel example [AddCommGroup α] : (3 : ℤ) • a = a + (2 : ℤ) • a := by abel example [AddCommGroup α] (a b : α) : a-2•b = a -2•b := by abel example [AddCommMonoid α] (a b : α) : a + (b + a) = a + a + b := by abel1 example [AddCommGroup α] (a b : α) : (a + b) - ((b + a) + a) = -a := by abel1 example [AddCommGroup α] (x : α) : x - 0 = x := by abel1 example [AddCommMonoid α] (a : α) : (3 : ℕ) • a = a + (2 : ℕ) • a := by abel1 example [AddCommGroup α] (a : α) : (3 : ℤ) • a = a + (2 : ℤ) • a := by abel1 example [AddCommGroup α] (a b : α) : a - 2•b = a - 2•b := by abel1 example [AddCommGroup α] (a : α) : 0 + a = a := by abel1 example [AddCommGroup α] (n : ℕ) (a : α) : n • a = n • a := by abel1 example [AddCommGroup α] (n : ℕ) (a : α) : 0 + n • a = n • a := by abel1 example [AddCommMonoid α] (a b c d e : α) : a + (b + (a + (c + (a + (d + (a + e)))))) = e + d + c + b + 4 • a := by abel1 example [AddCommGroup α] (a b c d e : α) : a + (b + (a + (c + (a + (d + (a + e)))))) = e + d + c + b + 4 • a := by abel1 example [AddCommGroup α] (a b c d : α) : a + b + (c + d - a) = b + c + d := by abel1 example [AddCommGroup α] (a b c : α) : a + b + c + (c - a - a) = (-1)•a + b + 2•c := by abel1 -- Make sure we fail on some non-equalities. example [AddCommMonoid α] (a b c d e : α) : a + (b + (a + (c + (a + (d + (a + e)))))) = e + d + c + b + 3 • a ∨ True := by fail_if_success left; abel1 right; trivial example [AddCommGroup α] (a b c d e : α) : a + (b + (a + (c + (a + (d + (a + e)))))) = e + d + c + b + 3 • a ∨ True := by fail_if_success left; abel1 right; trivial example [AddCommGroup α] (a b c d : α) : a + b + (c + d - a) = b + c - d ∨ True := by fail_if_success left; abel1 right; trivial example [AddCommGroup α] (a b c : α) : a + b + c + (c - a - a) = (-1)•a + b + c ∨ True := by fail_if_success left; abel1 right; trivial /-- `MyTrue` should be opaque to `abel`. -/ private def MyTrue := True /-- error: abel_nf made no progress -/ #guard_msgs in example : MyTrue := by abel_nf -- `abel!` should see through terms that are definitionally equal, def id' (x : α) := x example [AddCommGroup α] (a b : α) : a + b - b - id' a = 0 := by fail_if_success abel1 abel1! -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Interaction.20of.20abel.20with.20casting/near/319895001 example [AddCommGroup α] : True := by have : ∀ (p q r s : α), s + p - q = s - r - (q - r - p) := by intro p q r s abel trivial -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Interaction.20of.20abel.20with.20casting/near/319897374 example [AddCommGroup α] (x y z : α) : y = x + z - (x - y + z) := by have : True := trivial abel -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/abel.20bug.3F/near/368707560 example [AddCommGroup α] (a b s : α) : -b + (s - a) = s - b - a := by abel_nf -- inspired by automated testing example : True := by have := 0 abel_nf /-- error: abel_nf made no progress -/ #guard_msgs in example : False := by abel_nf /-- error: abel_nf made no progress -/ #guard_msgs in example [AddCommGroup α] (x y z : α) (w : x = y + z) : False := by abel_nf at w example [AddCommGroup α] (x y z : α) (h : False) (w : x - x = y + z) : False := by abel_nf at w guard_hyp w : 0 = y + z assumption /-- error: abel_nf made no progress -/ #guard_msgs in example [AddCommGroup α] (x y z : α) (_w : x = y + z) : False := by abel_nf at * -- Prior to https://github.com/leanprover/lean4/pull/2917 this would fail -- (the `at *` would close the goal, -- and then error when trying to work on the hypotheses because there was no goal.) example [AddCommGroup α] (x y z : α) (_w : x = y + z) : x - x = 0 := by abel_nf at * /-- error: abel_nf made no progress -/ -- Ideally this would specify that it made no progress at `w`. #guard_msgs in example [AddCommGroup α] (x y z : α) (w : x = y + z) : x - x = 0 := by abel_nf at w ⊢ /-- error: abel_nf made no progress -/ -- Ideally this would specify that it made no progress at `⊢`. #guard_msgs in example [AddCommGroup α] (x y z : α) (w : x - x = y + z) : x = 0 := by abel_nf at w ⊢ example [AddCommGroup α] (x y z : α) (h : False) (w : x - x = y + z) : False := by abel_nf at * guard_hyp w : 0 = y + z assumption section abbrev myId (a : ℤ) : ℤ := a /- Test that when `abel_nf` normalizes multiple expressions which contain a particular atom, it uses a form for that atom which is consistent between expressions. We can't use `guard_hyp h :ₛ` here, as while it does tell apart `x` and `myId x`, it also complains about differing instance paths. -/ /-- trace: α : Type _ a b : α x : ℤ R : ℤ → ℤ → Prop hR : Reflexive R h : R (2 • myId x) (2 • myId x) ⊢ True -/ #guard_msgs (trace) in set_option pp.mvars false in example (x : ℤ) (R : ℤ → ℤ → Prop) (hR : Reflexive R) : True := by have h : R (myId x + x) (x + myId x) := hR .. abel_nf at h trace_state trivial end -- Test that `abel_nf` doesn't unfold local let expressions, and `abel_nf!` does example [AddCommGroup α] (x : α) (f : α → α) : True := by let y := x have : x = y := by fail_if_success abel_nf abel_nf! have : x - y = 0 := by abel_nf abel_nf! have : f x = f y := by fail_if_success abel_nf abel_nf! have : f x - f y = 0 := by abel_nf abel_nf! trivial
CommRing_integralClosure.lean
import Mathlib -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/category.20theory.20import.20breaks.20CommRing.20synthesis/near/449132250 variable (R : Type) (A : Type) [CommRing R] [CommRing A] [Algebra R A] /-- info: (integralClosure R A).toCommRing -/ #guard_msgs in #synth CommRing (integralClosure R A)
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.
morphism.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 choice. From mathcomp Require Import fintype finfun bigop finset fingroup. (******************************************************************************) (* This file contains the definitions of: *) (* *) (* {morphism D >-> rT} == *) (* the structure type of functions that are group morphisms mapping a *) (* domain set D : {set aT} to a type rT; rT must have a finGroupType *) (* structure, and D is usually a group (most of the theory expects this). *) (* mfun == the coercion projecting {morphism D >-> rT} to aT -> rT *) (* *) (* Basic examples: *) (* idm D == the identity morphism with domain D, or more precisely *) (* the identity function, but with a canonical *) (* {morphism G -> gT} structure. *) (* trivm D == the trivial morphism with domain D. *) (* If f has a {morphism D >-> rT} structure *) (* 'dom f == D, the domain of f. *) (* f @* A == the image of A by f, where f is defined. *) (* := f @: (D :&: A) *) (* f @*^-1 R == the pre-image of R by f, where f is defined. *) (* := D :&: f @^-1: R *) (* 'ker f == the kernel of f. *) (* := f @*^-1 1 *) (* 'ker_G f == the kernel of f restricted to G. *) (* := G :&: 'ker f (this is a pure notation) *) (* 'injm f <=> f injective on D. *) (* <-> ker f \subset 1 (this is a pure notation) *) (* invm injf == the inverse morphism of f, with domain f @* D, when f *) (* is injective (injf : 'injm f). *) (* restrm f sDom == the restriction of f to a subset A of D, given *) (* (sDom : A \subset D); restrm f sDom is transparently *) (* identical to f; the restrmP and domP lemmas provide *) (* opaque restrictions. *) (* *) (* G \isog H <=> G and H are isomorphic as groups. *) (* H \homg G <=> H is a homomorphic image of G. *) (* isom G H f <=> f maps G isomorphically to H, provided D contains G. *) (* := f @: G^# == H^# *) (* *) (* If, moreover, g : {morphism G >-> gT} with G : {group aT}, *) (* factm sKer sDom == the (natural) factor morphism mapping f @* G to g @* G *) (* with sDom : G \subset D, sKer : 'ker f \subset 'ker g. *) (* ifactm injf g == the (natural) factor morphism mapping f @* G to g @* G *) (* when f is injective (injf : 'injm f); here g must *) (* denote an actual morphism structure, not its function *) (* projection. *) (* *) (* If g has a {morphism G >-> aT} structure for any G : {group gT}, then *) (* f \o g has a canonical {morphism g @*^-1 D >-> rT} structure. *) (* *) (* Finally, for an arbitrary function f : aT -> rT *) (* morphic D f <=> f preserves group multiplication in D, i.e., *) (* f (x * y) = (f x) * (f y) for all x, y in D. *) (* morphm fM == a function identical to f, but with a canonical *) (* {morphism D >-> rT} structure, given fM : morphic D f. *) (* misom D C f <=> f is a morphism that maps D isomorphically to C. *) (* := morphic D f && isom D C f *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Reserved Notation "x \isog y" (at level 70). Section MorphismStructure. Variables aT rT : finGroupType. Structure morphism (D : {set aT}) : Type := Morphism { mfun :> aT -> FinGroup.sort rT; _ : {in D &, {morph mfun : x y / x * y}} }. (* We give the 'lightest' possible specification to define morphisms: local *) (* congruence, in D, with the group law of aT. We then provide the properties *) (* for the 'textbook' notion of morphism, when the required structures are *) (* available (e.g. its domain is a group). *) Definition morphism_for D of phant rT := morphism D. Definition clone_morphism D f := let: Morphism _ fM := f return {type of @Morphism D for f} -> morphism_for D (Phant rT) in fun k => k fM. Variables (D A : {set aT}) (R : {set rT}) (x : aT) (y : rT) (f : aT -> rT). Variant morphim_spec : Prop := MorphimSpec z & z \in D & z \in A & y = f z. Lemma morphimP : reflect morphim_spec (y \in f @: (D :&: A)). Proof. apply: (iffP imsetP) => [] [z]; first by case/setIP; exists z. by exists z; first apply/setIP. Qed. Lemma morphpreP : reflect (x \in D /\ f x \in R) (x \in D :&: f @^-1: R). Proof. by rewrite !inE; apply: andP. Qed. End MorphismStructure. Notation "{ 'morphism' D >-> T }" := (morphism_for D (Phant T)) (format "{ 'morphism' D >-> T }") : type_scope. Notation "[ 'morphism' D 'of' f ]" := (@clone_morphism _ _ D _ (fun fM => @Morphism _ _ D f fM)) (format "[ 'morphism' D 'of' f ]") : form_scope. Notation "[ 'morphism' 'of' f ]" := (clone_morphism (@Morphism _ _ _ f)) (format "[ 'morphism' 'of' f ]") : form_scope. Arguments morphimP {aT rT D A y f}. Arguments morphpreP {aT rT D R x f}. (* Domain, image, preimage, kernel, using phantom types to infer the domain. *) Section MorphismOps1. Variables (aT rT : finGroupType) (D : {set aT}) (f : {morphism D >-> rT}). Lemma morphM : {in D &, {morph f : x y / x * y}}. Proof. by case f. Qed. Notation morPhantom := (phantom (aT -> rT)). Definition MorPhantom := Phantom (aT -> rT). Definition dom of morPhantom f := D. Definition morphim of morPhantom f := fun A => f @: (D :&: A). Definition morphpre of morPhantom f := fun R : {set rT} => D :&: f @^-1: R. Definition ker mph := morphpre mph 1. End MorphismOps1. Arguments morphim _ _ _%_g _ _ _%_g. Arguments morphpre _ _ _%_g _ _ _%_g. Notation "''dom' f" := (dom (MorPhantom f)) (at level 10, f at level 8, format "''dom' f") : group_scope. Notation "''ker' f" := (ker (MorPhantom f)) (at level 10, f at level 8, format "''ker' f") : group_scope. Notation "''ker_' H f" := (H :&: 'ker f) (at level 10, H at level 2, f at level 8, format "''ker_' H f") : group_scope. Notation "f @* A" := (morphim (MorPhantom f) A) (at level 24, format "f @* A") : group_scope. Notation "f @*^-1 R" := (morphpre (MorPhantom f) R) (at level 24, format "f @*^-1 R") : group_scope. Notation "''injm' f" := (pred_of_set ('ker f) \subset pred_of_set 1) (at level 10, f at level 8, format "''injm' f") : group_scope. Section MorphismTheory. Variables aT rT : finGroupType. Implicit Types A B : {set aT}. Implicit Types G H : {group aT}. Implicit Types R S : {set rT}. Implicit Types M : {group rT}. (* Most properties of morphims hold only when the domain is a group. *) Variables (D : {group aT}) (f : {morphism D >-> rT}). Lemma morph1 : f 1 = 1. Proof. by apply: (mulgI (f 1)); rewrite -morphM ?mulg1. Qed. Lemma morph_prod I r (P : pred I) F : (forall i, P i -> F i \in D) -> f (\prod_(i <- r | P i) F i) = \prod_( i <- r | P i) f (F i). Proof. move=> D_F; elim/(big_load (fun x => x \in D)): _. elim/big_rec2: _ => [|i _ x Pi [Dx <-]]; first by rewrite morph1. by rewrite groupM ?morphM // D_F. Qed. Lemma morphV : {in D, {morph f : x / x^-1}}. Proof. move=> x Dx; apply: (mulgI (f x)). by rewrite -morphM ?groupV // !mulgV morph1. Qed. Lemma morphJ : {in D &, {morph f : x y / x ^ y}}. Proof. by move=> * /=; rewrite !morphM ?morphV // ?groupM ?groupV. Qed. Lemma morphX n : {in D, {morph f : x / x ^+ n}}. Proof. by elim: n => [|n IHn] x Dx; rewrite ?morph1 // !expgS morphM ?(groupX, IHn). Qed. Lemma morphR : {in D &, {morph f : x y / [~ x, y]}}. Proof. by move=> * /=; rewrite morphM ?(groupV, groupJ) // morphJ ?morphV. Qed. (* Morphic image, preimage properties w.r.t. set-theoretic operations. *) Lemma morphimE A : f @* A = f @: (D :&: A). Proof. by []. Qed. Lemma morphpreE R : f @*^-1 R = D :&: f @^-1: R. Proof. by []. Qed. Lemma kerE : 'ker f = f @*^-1 1. Proof. by []. Qed. Lemma morphimEsub A : A \subset D -> f @* A = f @: A. Proof. by move=> sAD; rewrite /morphim (setIidPr sAD). Qed. Lemma morphimEdom : f @* D = f @: D. Proof. exact: morphimEsub. Qed. Lemma morphimIdom A : f @* (D :&: A) = f @* A. Proof. by rewrite /morphim setIA setIid. Qed. Lemma morphpreIdom R : D :&: f @*^-1 R = f @*^-1 R. Proof. by rewrite /morphim setIA setIid. Qed. Lemma morphpreIim R : f @*^-1 (f @* D :&: R) = f @*^-1 R. Proof. apply/setP=> x; rewrite morphimEdom !inE. by case Dx: (x \in D); rewrite // imset_f. Qed. Lemma morphimIim A : f @* D :&: f @* A = f @* A. Proof. by apply/setIidPr; rewrite imsetS // setIid subsetIl. Qed. Lemma mem_morphim A x : x \in D -> x \in A -> f x \in f @* A. Proof. by move=> Dx Ax; apply/morphimP; exists x. Qed. Lemma mem_morphpre R x : x \in D -> f x \in R -> x \in f @*^-1 R. Proof. by move=> Dx Rfx; apply/morphpreP. Qed. Lemma morphimS A B : A \subset B -> f @* A \subset f @* B. Proof. by move=> sAB; rewrite imsetS ?setIS. Qed. Lemma morphim_sub A : f @* A \subset f @* D. Proof. by rewrite imsetS // setIid subsetIl. Qed. Lemma leq_morphim A : #|f @* A| <= #|A|. Proof. by apply: (leq_trans (leq_imset_card _ _)); rewrite subset_leq_card ?subsetIr. Qed. Lemma morphpreS R S : R \subset S -> f @*^-1 R \subset f @*^-1 S. Proof. by move=> sRS; rewrite setIS ?preimsetS. Qed. Lemma morphpre_sub R : f @*^-1 R \subset D. Proof. exact: subsetIl. Qed. Lemma morphim_setIpre A R : f @* (A :&: f @*^-1 R) = f @* A :&: R. Proof. apply/setP=> fa; apply/morphimP/setIP=> [[a Da] | [/morphimP[a Da Aa ->] Rfa]]. by rewrite !inE Da /= => /andP[Aa Rfa] ->; rewrite mem_morphim. by exists a; rewrite // !inE Aa Da. Qed. Lemma morphim0 : f @* set0 = set0. Proof. by rewrite morphimE setI0 imset0. Qed. Lemma morphim_eq0 A : A \subset D -> (f @* A == set0) = (A == set0). Proof. by rewrite imset_eq0 => /setIidPr->. Qed. Lemma morphim_set1 x : x \in D -> f @* [set x] = [set f x]. Proof. by rewrite /morphim -sub1set => /setIidPr->; apply: imset_set1. Qed. Lemma morphim1 : f @* 1 = 1. Proof. by rewrite morphim_set1 ?morph1. Qed. Lemma morphimV A : f @* A^-1 = (f @* A)^-1. Proof. wlog suffices: A / f @* A^-1 \subset (f @* A)^-1. by move=> IH; apply/eqP; rewrite eqEsubset IH -invSg invgK -{1}(invgK A) IH. apply/subsetP=> _ /morphimP[x Dx Ax' ->]; rewrite !inE in Ax' *. by rewrite -morphV // imset_f // inE groupV Dx. Qed. Lemma morphpreV R : f @*^-1 R^-1 = (f @*^-1 R)^-1. Proof. apply/setP=> x; rewrite !inE groupV; case Dx: (x \in D) => //=. by rewrite morphV. Qed. Lemma morphimMl A B : A \subset D -> f @* (A * B) = f @* A * f @* B. Proof. move=> sAD; rewrite /morphim setIC -group_modl // (setIidPr sAD). apply/setP=> fxy; apply/idP/idP. case/imsetP=> _ /imset2P[x y Ax /setIP[Dy By] ->] ->{fxy}. by rewrite morphM // (subsetP sAD, imset2_f) // imset_f // inE By. case/imset2P=> _ _ /imsetP[x Ax ->] /morphimP[y Dy By ->] ->{fxy}. by rewrite -morphM // (subsetP sAD, imset_f) // mem_mulg // inE By. Qed. Lemma morphimMr A B : B \subset D -> f @* (A * B) = f @* A * f @* B. Proof. move=> sBD; apply: invg_inj. by rewrite invMg -!morphimV invMg morphimMl // -invGid invSg. Qed. Lemma morphpreMl R S : R \subset f @* D -> f @*^-1 (R * S) = f @*^-1 R * f @*^-1 S. Proof. move=> sRfD; apply/setP=> x; rewrite !inE. apply/andP/imset2P=> [[Dx] | [y z]]; last first. rewrite !inE => /andP[Dy Rfy] /andP[Dz Rfz] ->. by rewrite ?(groupM, morphM, imset2_f). case/imset2P=> fy fz Rfy Rfz def_fx. have /morphimP[y Dy _ def_fy]: fy \in f @* D := subsetP sRfD fy Rfy. exists y (y^-1 * x); last by rewrite mulKVg. by rewrite !inE Dy -def_fy. by rewrite !inE groupM ?(morphM, morphV, groupV) // def_fx -def_fy mulKg. Qed. Lemma morphimJ A x : x \in D -> f @* (A :^ x) = f @* A :^ f x. Proof. move=> Dx; rewrite !conjsgE morphimMl ?(morphimMr, sub1set, groupV) //. by rewrite !(morphim_set1, groupV, morphV). Qed. Lemma morphpreJ R x : x \in D -> f @*^-1 (R :^ f x) = f @*^-1 R :^ x. Proof. move=> Dx; apply/setP=> y; rewrite conjIg !inE conjGid // !mem_conjg inE. by case Dy: (y \in D); rewrite // morphJ ?(morphV, groupV). Qed. Lemma morphim_class x A : x \in D -> A \subset D -> f @* (x ^: A) = f x ^: f @* A. Proof. move=> Dx sAD; rewrite !morphimEsub ?class_subG // /class -!imset_comp. by apply: eq_in_imset => y Ay /=; rewrite morphJ // (subsetP sAD). Qed. Lemma classes_morphim A : A \subset D -> classes (f @* A) = [set f @* xA | xA in classes A]. Proof. move=> sAD; rewrite morphimEsub // /classes -!imset_comp. apply: eq_in_imset => x /(subsetP sAD) Dx /=. by rewrite morphim_class ?morphimEsub. Qed. Lemma morphimT : f @* setT = f @* D. Proof. by rewrite -morphimIdom setIT. Qed. Lemma morphimU A B : f @* (A :|: B) = f @* A :|: f @* B. Proof. by rewrite -imsetU -setIUr. Qed. Lemma morphimI A B : f @* (A :&: B) \subset f @* A :&: f @* B. Proof. by rewrite subsetI // ?morphimS ?(subsetIl, subsetIr). Qed. Lemma morphpre0 : f @*^-1 set0 = set0. Proof. by rewrite morphpreE preimset0 setI0. Qed. Lemma morphpreT : f @*^-1 setT = D. Proof. by rewrite morphpreE preimsetT setIT. Qed. Lemma morphpreU R S : f @*^-1 (R :|: S) = f @*^-1 R :|: f @*^-1 S. Proof. by rewrite -setIUr -preimsetU. Qed. Lemma morphpreI R S : f @*^-1 (R :&: S) = f @*^-1 R :&: f @*^-1 S. Proof. by rewrite -setIIr -preimsetI. Qed. Lemma morphpreD R S : f @*^-1 (R :\: S) = f @*^-1 R :\: f @*^-1 S. Proof. by apply/setP=> x /[!inE]; case: (x \in D). Qed. (* kernel, domain properties *) Lemma kerP x : x \in D -> reflect (f x = 1) (x \in 'ker f). Proof. by move=> Dx; rewrite 2!inE Dx; apply: set1P. Qed. Lemma dom_ker : {subset 'ker f <= D}. Proof. by move=> x /morphpreP[]. Qed. Lemma mker x : x \in 'ker f -> f x = 1. Proof. by move=> Kx; apply/kerP=> //; apply: dom_ker. Qed. Lemma mkerl x y : x \in 'ker f -> y \in D -> f (x * y) = f y. Proof. by move=> Kx Dy; rewrite morphM // ?(dom_ker, mker Kx, mul1g). Qed. Lemma mkerr x y : x \in D -> y \in 'ker f -> f (x * y) = f x. Proof. by move=> Dx Ky; rewrite morphM // ?(dom_ker, mker Ky, mulg1). Qed. Lemma rcoset_kerP x y : x \in D -> y \in D -> reflect (f x = f y) (x \in 'ker f :* y). Proof. move=> Dx Dy; rewrite mem_rcoset !inE groupM ?morphM ?groupV //=. by rewrite morphV // -eq_mulgV1; apply: eqP. Qed. Lemma ker_rcoset x y : x \in D -> y \in D -> f x = f y -> exists2 z, z \in 'ker f & x = z * y. Proof. by move=> Dx Dy eqfxy; apply/rcosetP; apply/rcoset_kerP. Qed. Lemma ker_norm : D \subset 'N('ker f). Proof. apply/subsetP=> x Dx /[1!inE]; apply/subsetP=> _ /imsetP[y Ky ->]. by rewrite !inE groupJ ?morphJ // ?dom_ker //= mker ?conj1g. Qed. Lemma ker_normal : 'ker f <| D. Proof. by rewrite /(_ <| D) subsetIl ker_norm. Qed. Lemma morphimGI G A : 'ker f \subset G -> f @* (G :&: A) = f @* G :&: f @* A. Proof. move=> sKG; apply/eqP; rewrite eqEsubset morphimI setIC. apply/subsetP=> _ /setIP[/morphimP[x Dx Ax ->] /morphimP[z Dz Gz]]. case/ker_rcoset=> {Dz}// y Ky def_x. have{z Gz y Ky def_x} Gx: x \in G by rewrite def_x groupMl // (subsetP sKG). by rewrite imset_f ?inE // Dx Gx Ax. Qed. Lemma morphimIG A G : 'ker f \subset G -> f @* (A :&: G) = f @* A :&: f @* G. Proof. by move=> sKG; rewrite setIC morphimGI // setIC. Qed. Lemma morphimD A B : f @* A :\: f @* B \subset f @* (A :\: B). Proof. rewrite subDset -morphimU morphimS //. by rewrite setDE setUIr setUCr setIT subsetUr. Qed. Lemma morphimDG A G : 'ker f \subset G -> f @* (A :\: G) = f @* A :\: f @* G. Proof. move=> sKG; apply/eqP; rewrite eqEsubset morphimD andbT !setDE subsetI. rewrite morphimS ?subsetIl // -[~: f @* G]setU0 -subDset setDE setCK. by rewrite -morphimIG //= setIAC -setIA setICr setI0 morphim0. Qed. Lemma morphimD1 A : (f @* A)^# \subset f @* A^#. Proof. by rewrite -!set1gE -morphim1 morphimD. Qed. (* group structure preservation *) Lemma morphpre_groupset M : group_set (f @*^-1 M). Proof. apply/group_setP; split=> [|x y]; rewrite !inE ?(morph1, group1) //. by case/andP=> Dx Mfx /andP[Dy Mfy]; rewrite morphM ?groupM. Qed. Lemma morphim_groupset G : group_set (f @* G). Proof. apply/group_setP; split=> [|_ _ /morphimP[x Dx Gx ->] /morphimP[y Dy Gy ->]]. by rewrite -morph1 imset_f ?group1. by rewrite -morphM ?imset_f ?inE ?groupM. Qed. Canonical morphpre_group fPh M := @group _ (morphpre fPh M) (morphpre_groupset M). Canonical morphim_group fPh G := @group _ (morphim fPh G) (morphim_groupset G). Canonical ker_group fPh : {group aT} := Eval hnf in [group of ker fPh]. Lemma morph_dom_groupset : group_set (f @: D). Proof. by rewrite -morphimEdom groupP. Qed. Canonical morph_dom_group := group morph_dom_groupset. Lemma morphpreMr R S : S \subset f @* D -> f @*^-1 (R * S) = f @*^-1 R * f @*^-1 S. Proof. move=> sSfD; apply: invg_inj. by rewrite invMg -!morphpreV invMg morphpreMl // -invSg invgK invGid. Qed. Lemma morphimK A : A \subset D -> f @*^-1 (f @* A) = 'ker f * A. Proof. move=> sAD; apply/setP=> x; rewrite !inE. apply/idP/idP=> [/andP[Dx /morphimP[y Dy Ay eqxy]] | /imset2P[z y Kz Ay ->{x}]]. rewrite -(mulgKV y x) mem_mulg // !inE !(groupM, morphM, groupV) //. by rewrite morphV //= eqxy mulgV. have [Dy Dz]: y \in D /\ z \in D by rewrite (subsetP sAD) // dom_ker. by rewrite groupM // morphM // mker // mul1g imset_f // inE Dy. Qed. Lemma morphimGK G : 'ker f \subset G -> G \subset D -> f @*^-1 (f @* G) = G. Proof. by move=> sKG sGD; rewrite morphimK // mulSGid. Qed. Lemma morphpre_set1 x : x \in D -> f @*^-1 [set f x] = 'ker f :* x. Proof. by move=> Dx; rewrite -morphim_set1 // morphimK ?sub1set. Qed. Lemma morphpreK R : R \subset f @* D -> f @* (f @*^-1 R) = R. Proof. move=> sRfD; apply/setP=> y; apply/morphimP/idP=> [[x _] | Ry]. by rewrite !inE; case/andP=> _ Rfx ->. have /morphimP[x Dx _ defy]: y \in f @* D := subsetP sRfD y Ry. by exists x; rewrite // !inE Dx -defy. Qed. Lemma morphim_ker : f @* 'ker f = 1. Proof. by rewrite morphpreK ?sub1G. Qed. Lemma ker_sub_pre M : 'ker f \subset f @*^-1 M. Proof. by rewrite morphpreS ?sub1G. Qed. Lemma ker_normal_pre M : 'ker f <| f @*^-1 M. Proof. by rewrite /normal ker_sub_pre subIset ?ker_norm. Qed. Lemma morphpreSK R S : R \subset f @* D -> (f @*^-1 R \subset f @*^-1 S) = (R \subset S). Proof. move=> sRfD; apply/idP/idP=> [sf'RS|]; last exact: morphpreS. suffices: R \subset f @* D :&: S by rewrite subsetI sRfD. rewrite -(morphpreK sRfD) -[_ :&: S]morphpreK (morphimS, subsetIl) //. by rewrite morphpreI morphimGK ?subsetIl // setIA setIid. Qed. Lemma sub_morphim_pre A R : A \subset D -> (f @* A \subset R) = (A \subset f @*^-1 R). Proof. move=> sAD; rewrite -morphpreSK (morphimS, morphimK) //. apply/idP/idP; first by apply: subset_trans; apply: mulG_subr. by move/(mulgS ('ker f)); rewrite -morphpreMl ?(sub1G, mul1g). Qed. Lemma morphpre_proper R S : R \subset f @* D -> S \subset f @* D -> (f @*^-1 R \proper f @*^-1 S) = (R \proper S). Proof. by move=> dQ dR; rewrite /proper !morphpreSK. Qed. Lemma sub_morphpre_im R G : 'ker f \subset G -> G \subset D -> R \subset f @* D -> (f @*^-1 R \subset G) = (R \subset f @* G). Proof. by symmetry; rewrite -morphpreSK ?morphimGK. Qed. Lemma ker_trivg_morphim A : (A \subset 'ker f) = (A \subset D) && (f @* A \subset [1]). Proof. case sAD: (A \subset D); first by rewrite sub_morphim_pre. by rewrite subsetI sAD. Qed. Lemma morphimSK A B : A \subset D -> (f @* A \subset f @* B) = (A \subset 'ker f * B). Proof. move=> sAD; transitivity (A \subset 'ker f * (D :&: B)). by rewrite -morphimK ?subsetIl // -sub_morphim_pre // /morphim setIA setIid. by rewrite setIC group_modl (subsetIl, subsetI) // andbC sAD. Qed. Lemma morphimSGK A G : A \subset D -> 'ker f \subset G -> (f @* A \subset f @* G) = (A \subset G). Proof. by move=> sGD skfK; rewrite morphimSK // mulSGid. Qed. Lemma ltn_morphim A : [1] \proper 'ker_A f -> #|f @* A| < #|A|. Proof. case/properP; rewrite sub1set => /setIP[A1 _] [x /setIP[Ax kx] x1]. rewrite (cardsD1 1 A) A1 ltnS -{1}(setD1K A1) morphimU morphim1. rewrite (setUidPr _) ?sub1set; last first. by rewrite -(mker kx) mem_morphim ?(dom_ker kx) // inE x1. by rewrite (leq_trans (leq_imset_card _ _)) ?subset_leq_card ?subsetIr. Qed. (* injectivity of image and preimage *) Lemma morphpre_inj : {in [pred R : {set rT} | R \subset f @* D] &, injective (fun R => f @*^-1 R)}. Proof. exact: can_in_inj morphpreK. Qed. Lemma morphim_injG : {in [pred G : {group aT} | 'ker f \subset G & G \subset D] &, injective (fun G => f @* G)}. Proof. move=> G H /andP[sKG sGD] /andP[sKH sHD] eqfGH. by apply: val_inj; rewrite /= -(morphimGK sKG sGD) eqfGH morphimGK. Qed. Lemma morphim_inj G H : ('ker f \subset G) && (G \subset D) -> ('ker f \subset H) && (H \subset D) -> f @* G = f @* H -> G :=: H. Proof. by move=> nsGf nsHf /morphim_injG->. Qed. (* commutation with generated groups and cycles *) Lemma morphim_gen A : A \subset D -> f @* <<A>> = <<f @* A>>. Proof. move=> sAD; apply/eqP. rewrite eqEsubset andbC gen_subG morphimS; last exact: subset_gen. by rewrite sub_morphim_pre gen_subG // -sub_morphim_pre // subset_gen. Qed. Lemma morphim_cycle x : x \in D -> f @* <[x]> = <[f x]>. Proof. by move=> Dx; rewrite morphim_gen (sub1set, morphim_set1). Qed. Lemma morphimY A B : A \subset D -> B \subset D -> f @* (A <*> B) = f @* A <*> f @* B. Proof. by move=> sAD sBD; rewrite morphim_gen ?morphimU // subUset sAD. Qed. Lemma morphpre_gen R : 1 \in R -> R \subset f @* D -> f @*^-1 <<R>> = <<f @*^-1 R>>. Proof. move=> R1 sRfD; apply/eqP. rewrite eqEsubset andbC gen_subG morphpreS; last exact: subset_gen. rewrite -{1}(morphpreK sRfD) -morphim_gen ?subsetIl // morphimGK //=. by rewrite sub_gen // setIS // preimsetS ?sub1set. by rewrite gen_subG subsetIl. Qed. (* commutator, normaliser, normal, center properties*) Lemma morphimR A B : A \subset D -> B \subset D -> f @* [~: A, B] = [~: f @* A, f @* B]. Proof. move/subsetP=> sAD /subsetP sBD. rewrite morphim_gen; last first; last congr <<_>>. by apply/subsetP=> _ /imset2P[x y Ax By ->]; rewrite groupR; auto. apply/setP=> fz; apply/morphimP/imset2P=> [[z _] | [fx fy]]. case/imset2P=> x y Ax By -> -> {z fz}. have Dx := sAD x Ax; have Dy := sBD y By. by exists (f x) (f y); rewrite ?(imset_f, morphR) // ?(inE, Dx, Dy). case/morphimP=> x Dx Ax ->{fx}; case/morphimP=> y Dy By ->{fy} -> {fz}. by exists [~ x, y]; rewrite ?(inE, morphR, groupR, imset2_f). Qed. Lemma morphim_norm A : f @* 'N(A) \subset 'N(f @* A). Proof. apply/subsetP=> fx; case/morphimP=> x Dx Nx -> {fx}. by rewrite inE -morphimJ ?(normP Nx). Qed. Lemma morphim_norms A B : A \subset 'N(B) -> f @* A \subset 'N(f @* B). Proof. by move=> nBA; apply: subset_trans (morphim_norm B); apply: morphimS. Qed. Lemma morphim_subnorm A B : f @* 'N_A(B) \subset 'N_(f @* A)(f @* B). Proof. exact: subset_trans (morphimI A _) (setIS _ (morphim_norm B)). Qed. Lemma morphim_normal A B : A <| B -> f @* A <| f @* B. Proof. by case/andP=> sAB nAB; rewrite /(_ <| _) morphimS // morphim_norms. Qed. Lemma morphim_cent1 x : x \in D -> f @* 'C[x] \subset 'C[f x]. Proof. by move=> Dx; rewrite -(morphim_set1 Dx) morphim_norm. Qed. Lemma morphim_cent1s A x : x \in D -> A \subset 'C[x] -> f @* A \subset 'C[f x]. Proof. by move=> Dx cAx; apply: subset_trans (morphim_cent1 Dx); apply: morphimS. Qed. Lemma morphim_subcent1 A x : x \in D -> f @* 'C_A[x] \subset 'C_(f @* A)[f x]. Proof. by move=> Dx; rewrite -(morphim_set1 Dx) morphim_subnorm. Qed. Lemma morphim_cent A : f @* 'C(A) \subset 'C(f @* A). Proof. apply/bigcapsP=> fx; case/morphimP=> x Dx Ax ->{fx}. by apply: subset_trans (morphim_cent1 Dx); apply: morphimS; apply: bigcap_inf. Qed. Lemma morphim_cents A B : A \subset 'C(B) -> f @* A \subset 'C(f @* B). Proof. by move=> cBA; apply: subset_trans (morphim_cent B); apply: morphimS. Qed. Lemma morphim_subcent A B : f @* 'C_A(B) \subset 'C_(f @* A)(f @* B). Proof. exact: subset_trans (morphimI A _) (setIS _ (morphim_cent B)). Qed. Lemma morphim_abelian A : abelian A -> abelian (f @* A). Proof. exact: morphim_cents. Qed. Lemma morphpre_norm R : f @*^-1 'N(R) \subset 'N(f @*^-1 R). Proof. by apply/subsetP=> x /[!inE] /andP[Dx Nfx]; rewrite -morphpreJ ?morphpreS. Qed. Lemma morphpre_norms R S : R \subset 'N(S) -> f @*^-1 R \subset 'N(f @*^-1 S). Proof. by move=> nSR; apply: subset_trans (morphpre_norm S); apply: morphpreS. Qed. Lemma morphpre_normal R S : R \subset f @* D -> S \subset f @* D -> (f @*^-1 R <| f @*^-1 S) = (R <| S). Proof. move=> sRfD sSfD; apply/idP/andP=> [|[sRS nSR]]. by move/morphim_normal; rewrite !morphpreK //; case/andP. by rewrite /(_ <| _) (subset_trans _ (morphpre_norm _)) morphpreS. Qed. Lemma morphpre_subnorm R S : f @*^-1 'N_R(S) \subset 'N_(f @*^-1 R)(f @*^-1 S). Proof. by rewrite morphpreI setIS ?morphpre_norm. Qed. Lemma morphim_normG G : 'ker f \subset G -> G \subset D -> f @* 'N(G) = 'N_(f @* D)(f @* G). Proof. move=> sKG sGD; apply/eqP; rewrite eqEsubset -{1}morphimIdom morphim_subnorm. rewrite -(morphpreK (subsetIl _ _)) morphimS //= morphpreI subIset // orbC. by rewrite -{2}(morphimGK sKG sGD) morphpre_norm. Qed. Lemma morphim_subnormG A G : 'ker f \subset G -> G \subset D -> f @* 'N_A(G) = 'N_(f @* A)(f @* G). Proof. move=> sKB sBD; rewrite morphimIG ?normsG // morphim_normG //. by rewrite setICA setIA morphimIim. Qed. Lemma morphpre_cent1 x : x \in D -> 'C_D[x] \subset f @*^-1 'C[f x]. Proof. move=> Dx; rewrite -sub_morphim_pre ?subsetIl //. by apply: subset_trans (morphim_cent1 Dx); rewrite morphimS ?subsetIr. Qed. Lemma morphpre_cent1s R x : x \in D -> R \subset f @* D -> f @*^-1 R \subset 'C[x] -> R \subset 'C[f x]. Proof. by move=> Dx sRfD; move/(morphim_cent1s Dx); rewrite morphpreK. Qed. Lemma morphpre_subcent1 R x : x \in D -> 'C_(f @*^-1 R)[x] \subset f @*^-1 'C_R[f x]. Proof. move=> Dx; rewrite -morphpreIdom -setIA setICA morphpreI setIS //. exact: morphpre_cent1. Qed. Lemma morphpre_cent A : 'C_D(A) \subset f @*^-1 'C(f @* A). Proof. rewrite -sub_morphim_pre ?subsetIl // morphimGI ?(subsetIl, subIset) // orbC. by rewrite (subset_trans (morphim_cent _)). Qed. Lemma morphpre_cents A R : R \subset f @* D -> f @*^-1 R \subset 'C(A) -> R \subset 'C(f @* A). Proof. by move=> sRfD; move/morphim_cents; rewrite morphpreK. Qed. Lemma morphpre_subcent R A : 'C_(f @*^-1 R)(A) \subset f @*^-1 'C_R(f @* A). Proof. by rewrite -morphpreIdom -setIA setICA morphpreI setIS //; apply: morphpre_cent. Qed. (* local injectivity properties *) Lemma injmP : reflect {in D &, injective f} ('injm f). Proof. apply: (iffP subsetP) => [injf x y Dx Dy | injf x /= Kx]. by case/ker_rcoset=> // z /injf/set1P->; rewrite mul1g. have Dx := dom_ker Kx; apply/set1P/injf => //. by apply/rcoset_kerP; rewrite // mulg1. Qed. Lemma card_im_injm : (#|f @* D| == #|D|) = 'injm f. Proof. by rewrite morphimEdom (sameP imset_injP injmP). Qed. Section Injective. Hypothesis injf : 'injm f. Lemma ker_injm : 'ker f = 1. Proof. exact/trivgP. Qed. Lemma injmK A : A \subset D -> f @*^-1 (f @* A) = A. Proof. by move=> sAD; rewrite morphimK // ker_injm // mul1g. Qed. Lemma injm_morphim_inj A B : A \subset D -> B \subset D -> f @* A = f @* B -> A = B. Proof. by move=> sAD sBD eqAB; rewrite -(injmK sAD) eqAB injmK. Qed. Lemma card_injm A : A \subset D -> #|f @* A| = #|A|. Proof. move=> sAD; rewrite morphimEsub // card_in_imset //. exact: (sub_in2 (subsetP sAD) (injmP injf)). Qed. Lemma order_injm x : x \in D -> #[f x] = #[x]. Proof. by move=> Dx; rewrite orderE -morphim_cycle // card_injm ?cycle_subG. Qed. Lemma injm1 x : x \in D -> f x = 1 -> x = 1. Proof. by move=> Dx; move/(kerP Dx); rewrite ker_injm; move/set1P. Qed. Lemma morph_injm_eq1 x : x \in D -> (f x == 1) = (x == 1). Proof. by move=> Dx; rewrite -morph1 (inj_in_eq (injmP injf)) ?group1. Qed. Lemma injmSK A B : A \subset D -> (f @* A \subset f @* B) = (A \subset B). Proof. by move=> sAD; rewrite morphimSK // ker_injm mul1g. Qed. Lemma sub_morphpre_injm R A : A \subset D -> R \subset f @* D -> (f @*^-1 R \subset A) = (R \subset f @* A). Proof. by move=> sAD sRfD; rewrite -morphpreSK ?injmK. Qed. Lemma injm_eq A B : A \subset D -> B \subset D -> (f @* A == f @* B) = (A == B). Proof. by move=> sAD sBD; rewrite !eqEsubset !injmSK. Qed. Lemma morphim_injm_eq1 A : A \subset D -> (f @* A == 1) = (A == 1). Proof. by move=> sAD; rewrite -morphim1 injm_eq ?sub1G. Qed. Lemma injmI A B : f @* (A :&: B) = f @* A :&: f @* B. Proof. rewrite -morphimIdom setIIr -4!(injmK (subsetIl D _), =^~ morphimIdom). by rewrite -morphpreI morphpreK // subIset ?morphim_sub. Qed. Lemma injmD1 A : f @* A^# = (f @* A)^#. Proof. by have:= morphimDG A injf; rewrite morphim1. Qed. Lemma nclasses_injm A : A \subset D -> #|classes (f @* A)| = #|classes A|. Proof. move=> sAD; rewrite classes_morphim // card_in_imset //. move=> _ _ /imsetP[x Ax ->] /imsetP[y Ay ->]. by apply: injm_morphim_inj; rewrite // class_subG ?(subsetP sAD). Qed. Lemma injm_norm A : A \subset D -> f @* 'N(A) = 'N_(f @* D)(f @* A). Proof. move=> sAD; apply/eqP; rewrite -morphimIdom eqEsubset morphim_subnorm. rewrite -sub_morphpre_injm ?subsetIl // morphpreI injmK // setIS //. by rewrite -{2}(injmK sAD) morphpre_norm. Qed. Lemma injm_norms A B : A \subset D -> B \subset D -> (f @* A \subset 'N(f @* B)) = (A \subset 'N(B)). Proof. by move=> sAD sBD; rewrite -injmSK // injm_norm // subsetI morphimS. Qed. Lemma injm_normal A B : A \subset D -> B \subset D -> (f @* A <| f @* B) = (A <| B). Proof. by move=> sAD sBD; rewrite /normal injmSK ?injm_norms. Qed. Lemma injm_subnorm A B : B \subset D -> f @* 'N_A(B) = 'N_(f @* A)(f @* B). Proof. by move=> sBD; rewrite injmI injm_norm // setICA setIA morphimIim. Qed. Lemma injm_cent1 x : x \in D -> f @* 'C[x] = 'C_(f @* D)[f x]. Proof. by move=> Dx; rewrite injm_norm ?morphim_set1 ?sub1set. Qed. Lemma injm_subcent1 A x : x \in D -> f @* 'C_A[x] = 'C_(f @* A)[f x]. Proof. by move=> Dx; rewrite injm_subnorm ?morphim_set1 ?sub1set. Qed. Lemma injm_cent A : A \subset D -> f @* 'C(A) = 'C_(f @* D)(f @* A). Proof. move=> sAD; apply/eqP; rewrite -morphimIdom eqEsubset morphim_subcent. apply/subsetP=> fx; case/setIP; case/morphimP=> x Dx _ ->{fx} cAfx. rewrite mem_morphim // inE Dx -sub1set centsC cent_set1 -injmSK //. by rewrite injm_cent1 // subsetI morphimS // -cent_set1 centsC sub1set. Qed. Lemma injm_cents A B : A \subset D -> B \subset D -> (f @* A \subset 'C(f @* B)) = (A \subset 'C(B)). Proof. by move=> sAD sBD; rewrite -injmSK // injm_cent // subsetI morphimS. Qed. Lemma injm_subcent A B : B \subset D -> f @* 'C_A(B) = 'C_(f @* A)(f @* B). Proof. by move=> sBD; rewrite injmI injm_cent // setICA setIA morphimIim. Qed. Lemma injm_abelian A : A \subset D -> abelian (f @* A) = abelian A. Proof. by move=> sAD; rewrite /abelian -subsetIidl -injm_subcent // injmSK ?subsetIidl. Qed. End Injective. Lemma eq_morphim (g : {morphism D >-> rT}): {in D, f =1 g} -> forall A, f @* A = g @* A. Proof. by move=> efg A; apply: eq_in_imset; apply: sub_in1 efg => x /setIP[]. Qed. Lemma eq_in_morphim B A (g : {morphism B >-> rT}) : D :&: A = B :&: A -> {in A, f =1 g} -> f @* A = g @* A. Proof. move=> eqDBA eqAfg; rewrite /morphim /= eqDBA. by apply: eq_in_imset => x /setIP[_]/eqAfg. Qed. End MorphismTheory. Notation "''ker' f" := (ker_group (MorPhantom f)) : Group_scope. Notation "''ker_' G f" := (G :&: 'ker f)%G : Group_scope. Notation "f @* G" := (morphim_group (MorPhantom f) G) : Group_scope. Notation "f @*^-1 M" := (morphpre_group (MorPhantom f) M) : Group_scope. Notation "f @: D" := (morph_dom_group f D) : Group_scope. Arguments injmP {aT rT D f}. Arguments morphpreK {aT rT D f} [R] sRf. Section IdentityMorphism. Variable gT : finGroupType. Implicit Types A B : {set gT}. Implicit Type G : {group gT}. Definition idm of {set gT} := fun x : gT => x : FinGroup.sort gT. Lemma idm_morphM A : {in A & , {morph idm A : x y / x * y}}. Proof. by []. Qed. Canonical idm_morphism A := Morphism (@idm_morphM A). Lemma injm_idm G : 'injm (idm G). Proof. by apply/injmP=> x y _ _. Qed. Lemma ker_idm G : 'ker (idm G) = 1. Proof. by apply/trivgP; apply: injm_idm. Qed. Lemma morphim_idm A B : B \subset A -> idm A @* B = B. Proof. rewrite /morphim /= /idm => /setIidPr->. by apply/setP=> x; apply/imsetP/idP=> [[y By ->]|Bx]; last exists x. Qed. Lemma morphpre_idm A B : idm A @*^-1 B = A :&: B. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma im_idm A : idm A @* A = A. Proof. exact: morphim_idm. Qed. End IdentityMorphism. Arguments idm {_} _%_g _%_g. Section RestrictedMorphism. Variables aT rT : finGroupType. Variables A D : {set aT}. Implicit Type B : {set aT}. Implicit Type R : {set rT}. Definition restrm of A \subset D := @id (aT -> FinGroup.sort rT). Section Props. Hypothesis sAD : A \subset D. Variable f : {morphism D >-> rT}. Local Notation fA := (restrm sAD (mfun f)). Canonical restrm_morphism := @Morphism aT rT A fA (sub_in2 (subsetP sAD) (morphM f)). Lemma morphim_restrm B : fA @* B = f @* (A :&: B). Proof. by rewrite {2}/morphim setIA (setIidPr sAD). Qed. Lemma restrmEsub B : B \subset A -> fA @* B = f @* B. Proof. by rewrite morphim_restrm => /setIidPr->. Qed. Lemma im_restrm : fA @* A = f @* A. Proof. exact: restrmEsub. Qed. Lemma morphpre_restrm R : fA @*^-1 R = A :&: f @*^-1 R. Proof. by rewrite setIA (setIidPl sAD). Qed. Lemma ker_restrm : 'ker fA = 'ker_A f. Proof. exact: morphpre_restrm. Qed. Lemma injm_restrm : 'injm f -> 'injm fA. Proof. by apply: subset_trans; rewrite ker_restrm subsetIr. Qed. End Props. Lemma restrmP (f : {morphism D >-> rT}) : A \subset 'dom f -> {g : {morphism A >-> rT} | [/\ g = f :> (aT -> rT), 'ker g = 'ker_A f, forall R, g @*^-1 R = A :&: f @*^-1 R & forall B, B \subset A -> g @* B = f @* B]}. Proof. move=> sAD; exists (restrm_morphism sAD f). split=> // [|R|B sBA]; first 1 [exact: ker_restrm | exact: morphpre_restrm]. by rewrite morphim_restrm (setIidPr sBA). Qed. Lemma domP (f : {morphism D >-> rT}) : 'dom f = A -> {g : {morphism A >-> rT} | [/\ g = f :> (aT -> rT), 'ker g = 'ker f, forall R, g @*^-1 R = f @*^-1 R & forall B, g @* B = f @* B]}. Proof. by move <-; exists f. Qed. End RestrictedMorphism. Arguments restrm {_ _ _%_g _%_g} _ _%_g. Arguments restrmP {aT rT A D}. Arguments domP {aT rT A D}. Section TrivMorphism. Variables aT rT : finGroupType. Definition trivm of {set aT} & aT := 1 : FinGroup.sort rT. Lemma trivm_morphM (A : {set aT}) : {in A &, {morph trivm A : x y / x * y}}. Proof. by move=> x y /=; rewrite mulg1. Qed. Canonical triv_morph A := Morphism (@trivm_morphM A). Lemma morphim_trivm (G H : {group aT}) : trivm G @* H = 1. Proof. apply/setP=> /= y; rewrite inE; apply/idP/eqP=> [|->]; first by case/morphimP. by apply/morphimP; exists (1 : aT); rewrite /= ?group1. Qed. Lemma ker_trivm (G : {group aT}) : 'ker (trivm G) = G. Proof. by apply/setIidPl/subsetP=> x _; rewrite !inE /=. Qed. End TrivMorphism. Arguments trivm {aT rT} _%_g _%_g. (* The composition of two morphisms is a Canonical morphism instance. *) Section MorphismComposition. Variables gT hT rT : finGroupType. Variables (G : {group gT}) (H : {group hT}). Variable f : {morphism G >-> hT}. Variable g : {morphism H >-> rT}. Local Notation gof := (mfun g \o mfun f). Lemma comp_morphM : {in f @*^-1 H &, {morph gof: x y / x * y}}. Proof. by move=> x y; rewrite /= !inE => /andP[? ?] /andP[? ?]; rewrite !morphM. Qed. Canonical comp_morphism := Morphism comp_morphM. Lemma ker_comp : 'ker gof = f @*^-1 'ker g. Proof. by apply/setP=> x; rewrite !inE andbA. Qed. Lemma injm_comp : 'injm f -> 'injm g -> 'injm gof. Proof. by move=> injf; rewrite ker_comp; move/trivgP=> ->. Qed. Lemma morphim_comp (A : {set gT}) : gof @* A = g @* (f @* A). Proof. apply/setP=> z; apply/morphimP/morphimP=> [[x]|[y Hy fAy ->{z}]]. rewrite !inE => /andP[Gx Hfx]; exists (f x) => //. by apply/morphimP; exists x. by case/morphimP: fAy Hy => x Gx Ax ->{y} Hfx; exists x; rewrite ?inE ?Gx. Qed. Lemma morphpre_comp (C : {set rT}) : gof @*^-1 C = f @*^-1 (g @*^-1 C). Proof. by apply/setP=> z; rewrite !inE andbA. Qed. End MorphismComposition. (* The factor morphism *) Section FactorMorphism. Variables aT qT rT : finGroupType. Variables G H : {group aT}. Variable f : {morphism G >-> rT}. Variable q : {morphism H >-> qT}. Definition factm of 'ker q \subset 'ker f & G \subset H := fun x => f (repr (q @*^-1 [set x])). Hypothesis sKqKf : 'ker q \subset 'ker f. Hypothesis sGH : G \subset H. Notation ff := (factm sKqKf sGH). Lemma factmE x : x \in G -> ff (q x) = f x. Proof. rewrite /ff => Gx; have Hx := subsetP sGH x Gx. have /mem_repr: x \in q @*^-1 [set q x] by rewrite !inE Hx /=. case/morphpreP; move: (repr _) => y Hy /set1P. by case/ker_rcoset=> // z Kz ->; rewrite mkerl ?(subsetP sKqKf). Qed. Lemma factm_morphM : {in q @* G &, {morph ff : x y / x * y}}. Proof. move=> _ _ /morphimP[x Hx Gx ->] /morphimP[y Hy Gy ->]. by rewrite -morphM ?factmE ?groupM // morphM. Qed. Canonical factm_morphism := Morphism factm_morphM. Lemma morphim_factm (A : {set aT}) : ff @* (q @* A) = f @* A. Proof. rewrite -morphim_comp /= {1}/morphim /= morphimGK //; last first. by rewrite (subset_trans sKqKf) ?subsetIl. apply/setP=> y; apply/morphimP/morphimP; by case=> x Gx Ax ->{y}; exists x; rewrite //= factmE. Qed. Lemma morphpre_factm (C : {set rT}) : ff @*^-1 C = q @* (f @*^-1 C). Proof. apply/setP=> y /[!inE]/=; apply/andP/morphimP=> [[]|[x Hx]]; last first. by case/morphpreP=> Gx Cfx ->; rewrite factmE ?imset_f ?inE ?Hx. case/morphimP=> x Hx Gx ->; rewrite factmE //. by exists x; rewrite // !inE Gx. Qed. Lemma ker_factm : 'ker ff = q @* 'ker f. Proof. exact: morphpre_factm. Qed. Lemma injm_factm : 'injm f -> 'injm ff. Proof. by rewrite ker_factm => /trivgP->; rewrite morphim1. Qed. Lemma injm_factmP : reflect ('ker f = 'ker q) ('injm ff). Proof. rewrite ker_factm -morphimIdom sub_morphim_pre ?subsetIl //. rewrite setIA (setIidPr sGH) (sameP setIidPr eqP) (setIidPl _) // eq_sym. exact: eqP. Qed. Lemma ker_factm_loc (K : {group aT}) : 'ker_(q @* K) ff = q @* 'ker_K f. Proof. by rewrite ker_factm -morphimIG. Qed. End FactorMorphism. Prenex Implicits factm. Section InverseMorphism. Variables aT rT : finGroupType. Implicit Types A B : {set aT}. Implicit Types C D : {set rT}. Variables (G : {group aT}) (f : {morphism G >-> rT}). Hypothesis injf : 'injm f. Lemma invm_subker : 'ker f \subset 'ker (idm G). Proof. by rewrite ker_idm. Qed. Definition invm := factm invm_subker (subxx _). Canonical invm_morphism := Eval hnf in [morphism of invm]. Lemma invmE : {in G, cancel f invm}. Proof. exact: factmE. Qed. Lemma invmK : {in f @* G, cancel invm f}. Proof. by move=> fx; case/morphimP=> x _ Gx ->; rewrite invmE. Qed. Lemma morphpre_invm A : invm @*^-1 A = f @* A. Proof. by rewrite morphpre_factm morphpre_idm morphimIdom. Qed. Lemma morphim_invm A : A \subset G -> invm @* (f @* A) = A. Proof. by move=> sAG; rewrite morphim_factm morphim_idm. Qed. Lemma morphim_invmE C : invm @* C = f @*^-1 C. Proof. rewrite -morphpreIdom -(morphim_invm (subsetIl _ _)). by rewrite morphimIdom -morphpreIim morphpreK (subsetIl, morphimIdom). Qed. Lemma injm_proper A B : A \subset G -> B \subset G -> (f @* A \proper f @* B) = (A \proper B). Proof. move=> dA dB; rewrite -morphpre_invm -(morphpre_invm B). by rewrite morphpre_proper ?morphim_invm. Qed. Lemma injm_invm : 'injm invm. Proof. by move/can_in_inj/injmP: invmK. Qed. Lemma ker_invm : 'ker invm = 1. Proof. by move/trivgP: injm_invm. Qed. Lemma im_invm : invm @* (f @* G) = G. Proof. exact: morphim_invm. Qed. End InverseMorphism. Prenex Implicits invm. Section InjFactm. Variables (gT aT rT : finGroupType) (D G : {group gT}). Variables (g : {morphism G >-> rT}) (f : {morphism D >-> aT}) (injf : 'injm f). Definition ifactm := tag (domP [morphism of g \o invm injf] (morphpre_invm injf G)). Lemma ifactmE : {in D, forall x, ifactm (f x) = g x}. Proof. rewrite /ifactm => x Dx; case: domP => f' /= [def_f' _ _ _]. by rewrite {f'}def_f' //= invmE. Qed. Lemma morphim_ifactm (A : {set gT}) : A \subset D -> ifactm @* (f @* A) = g @* A. Proof. rewrite /ifactm => sAD; case: domP => _ /= [_ _ _ ->]. by rewrite morphim_comp morphim_invm. Qed. Lemma im_ifactm : G \subset D -> ifactm @* (f @* G) = g @* G. Proof. exact: morphim_ifactm. Qed. Lemma morphpre_ifactm C : ifactm @*^-1 C = f @* (g @*^-1 C). Proof. rewrite /ifactm; case: domP => _ /= [_ _ -> _]. by rewrite morphpre_comp morphpre_invm. Qed. Lemma ker_ifactm : 'ker ifactm = f @* 'ker g. Proof. exact: morphpre_ifactm. Qed. Lemma injm_ifactm : 'injm g -> 'injm ifactm. Proof. by rewrite ker_ifactm => /trivgP->; rewrite morphim1. Qed. End InjFactm. (* Reflected (boolean) form of morphism and isomorphism properties. *) Section ReflectProp. Variables aT rT : finGroupType. Section Defs. Variables (A : {set aT}) (B : {set rT}). (* morphic is the morphM property of morphisms seen through morphicP. *) Definition morphic (f : aT -> rT) := [forall u in [predX A & A], f (u.1 * u.2) == f u.1 * f u.2]. Definition isom f := f @: A^# == B^#. Definition misom f := morphic f && isom f. Definition isog := [exists f : {ffun aT -> rT}, misom f]. Section MorphicProps. Variable f : aT -> rT. Lemma morphicP : reflect {in A &, {morph f : x y / x * y}} (morphic f). Proof. apply: (iffP forallP) => [fM x y Ax Ay | fM [x y] /=]. by apply/eqP; have:= fM (x, y); rewrite inE /= Ax Ay. by apply/implyP=> /andP[Ax Ay]; rewrite fM. Qed. Definition morphm of morphic f := f : aT -> FinGroup.sort rT. Lemma morphmE fM : morphm fM = f. Proof. by []. Qed. Canonical morphm_morphism fM := @Morphism _ _ A (morphm fM) (morphicP fM). End MorphicProps. Lemma misomP f : reflect {fM : morphic f & isom (morphm fM)} (misom f). Proof. by apply: (iffP andP) => [] [fM fiso] //; exists fM. Qed. Lemma misom_isog f : misom f -> isog. Proof. case/andP=> fM iso_f; apply/existsP; exists (finfun f). apply/andP; split; last by rewrite /misom /isom !(eq_imset _ (ffunE f)). by apply/forallP=> u; rewrite !ffunE; apply: forallP fM u. Qed. Lemma isom_isog (D : {group aT}) (f : {morphism D >-> rT}) : A \subset D -> isom f -> isog. Proof. move=> sAD isof; apply: (@misom_isog f); rewrite /misom isof andbT. by apply/morphicP; apply: (sub_in2 (subsetP sAD) (morphM f)). Qed. Lemma isog_isom : isog -> {f : {morphism A >-> rT} | isom f}. Proof. by case/existsP/sigW=> f /misomP[fM isom_f]; exists (morphm_morphism fM). Qed. End Defs. Infix "\isog" := isog. Arguments isom_isog [A B D]. (* The real reflection properties only hold for true groups and morphisms. *) Section Main. Variables (G : {group aT}) (H : {group rT}). Lemma isomP (f : {morphism G >-> rT}) : reflect ('injm f /\ f @* G = H) (isom G H f). Proof. apply: (iffP eqP) => [eqfGH | [injf <-]]; last first. by rewrite -injmD1 // morphimEsub ?subsetDl. split. apply/subsetP=> x /morphpreP[Gx fx1]; have: f x \notin H^# by rewrite inE fx1. by apply: contraR => ntx; rewrite -eqfGH imset_f // inE ntx. rewrite morphimEdom -{2}(setD1K (group1 G)) imsetU eqfGH. by rewrite imset_set1 morph1 setD1K. Qed. Lemma isogP : reflect (exists2 f : {morphism G >-> rT}, 'injm f & f @* G = H) (G \isog H). Proof. apply: (iffP idP) => [/isog_isom[f /isomP[]] | [f injf fG]]; first by exists f. by apply: (isom_isog f) => //; apply/isomP. Qed. Variable f : {morphism G >-> rT}. Hypothesis isoGH : isom G H f. Lemma isom_inj : 'injm f. Proof. by have /isomP[] := isoGH. Qed. Lemma isom_im : f @* G = H. Proof. by have /isomP[] := isoGH. Qed. Lemma isom_card : #|G| = #|H|. Proof. by rewrite -isom_im card_injm ?isom_inj. Qed. Lemma isom_sub_im : H \subset f @* G. Proof. by rewrite isom_im. Qed. Definition isom_inv := restrm isom_sub_im (invm isom_inj). End Main. Variables (G : {group aT}) (f : {morphism G >-> rT}). Lemma morphim_isom (H : {group aT}) (K : {group rT}) : H \subset G -> isom H K f -> f @* H = K. Proof. by case/(restrmP f)=> g [gf _ _ <- //]; rewrite -gf; case/isomP. Qed. Lemma sub_isom (A : {set aT}) (C : {set rT}) : A \subset G -> f @* A = C -> 'injm f -> isom A C f. Proof. move=> sAG; case: (restrmP f sAG) => g [_ _ _ img] <-{C} injf. rewrite /isom -morphimEsub ?morphimDG ?morphim1 //. by rewrite subDset setUC subsetU ?sAG. Qed. Lemma sub_isog (A : {set aT}) : A \subset G -> 'injm f -> isog A (f @* A). Proof. by move=> sAG injf; apply: (isom_isog f sAG); apply: sub_isom. Qed. Lemma restr_isom_to (A : {set aT}) (C R : {group rT}) (sAG : A \subset G) : f @* A = C -> isom G R f -> isom A C (restrm sAG f). Proof. by move=> defC /isomP[inj_f _]; apply: sub_isom. Qed. Lemma restr_isom (A : {group aT}) (R : {group rT}) (sAG : A \subset G) : isom G R f -> isom A (f @* A) (restrm sAG f). Proof. exact: restr_isom_to. Qed. End ReflectProp. Arguments isom {_ _} _%_g _%_g _. Arguments morphic {_ _} _%_g _. Arguments misom _ _ _%_g _%_g _. Arguments isog {_ _} _%_g _%_g. Arguments morphicP {aT rT A f}. Arguments misomP {aT rT A B f}. Arguments isom_isog [aT rT A B D]. Arguments isomP {aT rT G H f}. Arguments isogP {aT rT G H}. Prenex Implicits morphm. Notation "x \isog y":= (isog x y). Section Isomorphisms. Variables gT hT kT : finGroupType. Variables (G : {group gT}) (H : {group hT}) (K : {group kT}). Lemma idm_isom : isom G G (idm G). Proof. exact: sub_isom (im_idm G) (injm_idm G). Qed. Lemma isog_refl : G \isog G. Proof. exact: isom_isog idm_isom. Qed. Lemma card_isog : G \isog H -> #|G| = #|H|. Proof. by case/isogP=> f injf <-; apply: isom_card (f) _; apply/isomP. Qed. Lemma isog_abelian : G \isog H -> abelian G = abelian H. Proof. by case/isogP=> f injf <-; rewrite injm_abelian. Qed. Lemma trivial_isog : G :=: 1 -> H :=: 1 -> G \isog H. Proof. move=> -> ->; apply/isogP. exists [morphism of @trivm gT hT 1]; rewrite /= ?morphim1 //. by rewrite ker_trivm; apply: subxx. Qed. Lemma isog_eq1 : G \isog H -> (G :==: 1) = (H :==: 1). Proof. by move=> isoGH; rewrite !trivg_card1 card_isog. Qed. Lemma isom_sym (f : {morphism G >-> hT}) (isoGH : isom G H f) : isom H G (isom_inv isoGH). Proof. rewrite sub_isom 1?injm_restrm ?injm_invm // im_restrm. by rewrite -(isom_im isoGH) im_invm. Qed. Lemma isog_symr : G \isog H -> H \isog G. Proof. by case/isog_isom=> f /isom_sym/isom_isog->. Qed. Lemma isog_trans : G \isog H -> H \isog K -> G \isog K. Proof. case/isogP=> f injf <-; case/isogP=> g injg <-. have defG: f @*^-1 (f @* G) = G by rewrite morphimGK ?subsetIl. rewrite -morphim_comp -{1 8}defG. by apply/isogP; exists [morphism of g \o f]; rewrite ?injm_comp. Qed. Lemma nclasses_isog : G \isog H -> #|classes G| = #|classes H|. Proof. by case/isogP=> f injf <-; rewrite nclasses_injm. Qed. End Isomorphisms. Section IsoBoolEquiv. Variables gT hT kT : finGroupType. Variables (G : {group gT}) (H : {group hT}) (K : {group kT}). Lemma isog_sym : (G \isog H) = (H \isog G). Proof. by apply/idP/idP; apply: isog_symr. Qed. Lemma isog_transl : G \isog H -> (G \isog K) = (H \isog K). Proof. by move=> iso; apply/idP/idP; apply: isog_trans; rewrite // -isog_sym. Qed. Lemma isog_transr : G \isog H -> (K \isog G) = (K \isog H). Proof. by move=> iso; apply/idP/idP; move/isog_trans; apply; rewrite // -isog_sym. Qed. End IsoBoolEquiv. Section Homg. Implicit Types rT gT aT : finGroupType. Definition homg rT aT (C : {set rT}) (D : {set aT}) := [exists (f : {ffun aT -> rT} | morphic D f), f @: D == C]. Lemma homgP rT aT (C : {set rT}) (D : {set aT}) : reflect (exists f : {morphism D >-> rT}, f @* D = C) (homg C D). Proof. apply: (iffP exists_eq_inP) => [[f fM <-] | [f <-]]. by exists (morphm_morphism fM); rewrite /morphim /= setIid. exists (finfun f); first by apply/morphicP=> x y Dx Dy; rewrite !ffunE morphM. by rewrite /morphim setIid; apply: eq_imset => x; rewrite ffunE. Qed. Lemma morphim_homg aT rT (A D : {set aT}) (f : {morphism D >-> rT}) : A \subset D -> homg (f @* A) A. Proof. move=> sAD; apply/homgP; exists (restrm_morphism sAD f). by rewrite morphim_restrm setIid. Qed. Lemma leq_homg rT aT (C : {set rT}) (G : {group aT}) : homg C G -> #|C| <= #|G|. Proof. by case/homgP=> f <-; apply: leq_morphim. Qed. Lemma homg_refl aT (A : {set aT}) : homg A A. Proof. by apply/homgP; exists (idm_morphism A); rewrite im_idm. Qed. Lemma homg_trans aT (B : {set aT}) rT (C : {set rT}) gT (G : {group gT}) : homg C B -> homg B G -> homg C G. Proof. move=> homCB homBG; case/homgP: homBG homCB => fG <- /homgP[fK <-]. by rewrite -morphim_comp morphim_homg // -sub_morphim_pre. Qed. Lemma isogEcard rT aT (G : {group rT}) (H : {group aT}) : (G \isog H) = (homg G H) && (#|H| <= #|G|). Proof. rewrite isog_sym; apply/isogP/andP=> [[f injf <-] | []]. by rewrite leq_eqVlt eq_sym card_im_injm injf morphim_homg. case/homgP=> f <-; rewrite leq_eqVlt eq_sym card_im_injm. by rewrite ltnNge leq_morphim orbF; exists f. Qed. Lemma isog_hom rT aT (G : {group rT}) (H : {group aT}) : G \isog H -> homg G H. Proof. by rewrite isogEcard; case/andP. Qed. Lemma isogEhom rT aT (G : {group rT}) (H : {group aT}) : (G \isog H) = homg G H && homg H G. Proof. apply/idP/andP=> [isoGH | [homGH homHG]]. by rewrite !isog_hom // isog_sym. by rewrite isogEcard homGH leq_homg. Qed. Lemma eq_homgl gT aT rT (G : {group gT}) (H : {group aT}) (K : {group rT}) : G \isog H -> homg G K = homg H K. Proof. by rewrite isogEhom => /andP[homGH homHG]; apply/idP/idP; apply: homg_trans. Qed. Lemma eq_homgr gT rT aT (G : {group gT}) (H : {group rT}) (K : {group aT}) : G \isog H -> homg K G = homg K H. Proof. rewrite isogEhom => /andP[homGH homHG]. by apply/idP/idP=> homK; apply: homg_trans homK _. Qed. End Homg. Arguments homg _ _ _%_g _%_g. Notation "G \homg H" := (homg G H) (at level 70, no associativity) : group_scope. Arguments homgP {rT aT C D}. (* Isomorphism between a group and its subtype. *) Section SubMorphism. Variables (gT : finGroupType) (G : {group gT}). Canonical sgval_morphism := Morphism (@sgvalM _ G). Canonical subg_morphism := Morphism (@subgM _ G). Lemma injm_sgval : 'injm sgval. Proof. exact/injmP/(in2W subg_inj). Qed. Lemma injm_subg : 'injm (subg G). Proof. exact/injmP/(can_in_inj subgK). Qed. Hint Resolve injm_sgval injm_subg : core. Lemma ker_sgval : 'ker sgval = 1. Proof. exact/trivgP. Qed. Lemma ker_subg : 'ker (subg G) = 1. Proof. exact/trivgP. Qed. Lemma im_subg : subg G @* G = [subg G]. Proof. apply/eqP; rewrite -subTset morphimEdom. by apply/subsetP=> u _; rewrite -(sgvalK u) imset_f ?subgP. Qed. Lemma sgval_sub A : sgval @* A \subset G. Proof. by apply/subsetP=> x; case/imsetP=> u _ ->; apply: subgP. Qed. Lemma sgvalmK A : subg G @* (sgval @* A) = A. Proof. apply/eqP; rewrite eqEcard !card_injm ?subsetT ?sgval_sub // leqnn andbT. rewrite -morphim_comp; apply/subsetP=> _ /morphimP[v _ Av ->] /=. by rewrite sgvalK. Qed. Lemma subgmK (A : {set gT}) : A \subset G -> sgval @* (subg G @* A) = A. Proof. move=> sAG; apply/eqP; rewrite eqEcard !card_injm ?subsetT //. rewrite leqnn andbT -morphim_comp morphimE /= morphpreT. by apply/subsetP=> _ /morphimP[v Gv Av ->] /=; rewrite subgK. Qed. Lemma im_sgval : sgval @* [subg G] = G. Proof. by rewrite -{2}im_subg subgmK. Qed. Lemma isom_subg : isom G [subg G] (subg G). Proof. by apply/isomP; rewrite im_subg. Qed. Lemma isom_sgval : isom [subg G] G sgval. Proof. by apply/isomP; rewrite im_sgval. Qed. Lemma isog_subg : isog G [subg G]. Proof. exact: isom_isog isom_subg. Qed. End SubMorphism. Arguments sgvalmK {gT G} A. Arguments subgmK {gT G} [A] sAG.
Bilinear.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.Prod /-! # The derivative of bounded bilinear maps For detailed documentation of the Fréchet derivative, see the module docstring of `Mathlib/Analysis/Calculus/FDeriv/Basic.lean`. This file contains the usual formulas (and existence assertions) for the derivative of bounded bilinear maps. -/ open Asymptotics Topology 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'] section BilinearMap /-! ### Derivative of a bounded bilinear map -/ variable {b : E × F → G} {u : Set (E × F)} open NormedField -- TODO: rewrite/golf using analytic functions? @[fun_prop] theorem IsBoundedBilinearMap.hasStrictFDerivAt (h : IsBoundedBilinearMap 𝕜 b) (p : E × F) : HasStrictFDerivAt b (h.deriv p) p := by simp only [hasStrictFDerivAt_iff_isLittleO] simp only [← map_add_left_nhds_zero (p, p), isLittleO_map] set T := (E × F) × E × F calc _ = fun x ↦ h.deriv (x.1 - x.2) (x.2.1, x.1.2) := by ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩ rcases p with ⟨x, y⟩ simp only [map_sub, deriv_apply, Function.comp_apply, Prod.mk_add_mk, h.add_right, h.add_left, Prod.mk_sub_mk, h.map_sub_left, h.map_sub_right, sub_add_sub_cancel] abel -- _ =O[𝓝 (0 : T)] fun x ↦ ‖x.1 - x.2‖ * ‖(x.2.1, x.1.2)‖ := -- h.toContinuousLinearMap.deriv₂.isBoundedBilinearMap.isBigO_comp -- _ = o[𝓝 0] fun x ↦ ‖x.1 - x.2‖ * 1 := _ _ =o[𝓝 (0 : T)] fun x ↦ x.1 - x.2 := by -- TODO : add 2 `calc` steps instead of the next 3 lines refine h.toContinuousLinearMap.deriv₂.isBoundedBilinearMap.isBigO_comp.trans_isLittleO ?_ suffices (fun x : T ↦ ‖x.1 - x.2‖ * ‖(x.2.1, x.1.2)‖) =o[𝓝 0] fun x ↦ ‖x.1 - x.2‖ * 1 by simpa only [mul_one, isLittleO_norm_right] using this refine (isBigO_refl _ _).mul_isLittleO ((isLittleO_one_iff _).2 ?_) -- TODO: `continuity` fails exact (continuous_snd.fst.prodMk continuous_fst.snd).norm.tendsto' _ _ (by simp) _ = _ := by simp [T, Function.comp_def] @[fun_prop] theorem IsBoundedBilinearMap.hasFDerivAt (h : IsBoundedBilinearMap 𝕜 b) (p : E × F) : HasFDerivAt b (h.deriv p) p := (h.hasStrictFDerivAt p).hasFDerivAt @[fun_prop] theorem IsBoundedBilinearMap.hasFDerivWithinAt (h : IsBoundedBilinearMap 𝕜 b) (p : E × F) : HasFDerivWithinAt b (h.deriv p) u p := (h.hasFDerivAt p).hasFDerivWithinAt @[fun_prop] theorem IsBoundedBilinearMap.differentiableAt (h : IsBoundedBilinearMap 𝕜 b) (p : E × F) : DifferentiableAt 𝕜 b p := (h.hasFDerivAt p).differentiableAt @[fun_prop] theorem IsBoundedBilinearMap.differentiableWithinAt (h : IsBoundedBilinearMap 𝕜 b) (p : E × F) : DifferentiableWithinAt 𝕜 b u p := (h.differentiableAt p).differentiableWithinAt protected theorem IsBoundedBilinearMap.fderiv (h : IsBoundedBilinearMap 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := HasFDerivAt.fderiv (h.hasFDerivAt p) protected theorem IsBoundedBilinearMap.fderivWithin (h : IsBoundedBilinearMap 𝕜 b) (p : E × F) (hxs : UniqueDiffWithinAt 𝕜 u p) : fderivWithin 𝕜 b u p = h.deriv p := by rw [DifferentiableAt.fderivWithin (h.differentiableAt p) hxs] exact h.fderiv p @[fun_prop] theorem IsBoundedBilinearMap.differentiable (h : IsBoundedBilinearMap 𝕜 b) : Differentiable 𝕜 b := fun x => h.differentiableAt x @[fun_prop] theorem IsBoundedBilinearMap.differentiableOn (h : IsBoundedBilinearMap 𝕜 b) : DifferentiableOn 𝕜 b u := h.differentiable.differentiableOn variable (B : E →L[𝕜] F →L[𝕜] G) @[fun_prop] theorem ContinuousLinearMap.hasFDerivWithinAt_of_bilinear {f : G' → E} {g : G' → F} {f' : G' →L[𝕜] E} {g' : G' →L[𝕜] F} {x : G'} {s : Set G'} (hf : HasFDerivWithinAt f f' s x) (hg : HasFDerivWithinAt g g' s x) : HasFDerivWithinAt (fun y => B (f y) (g y)) (B.precompR G' (f x) g' + B.precompL G' f' (g x)) s x := by -- need `by exact` to deal with tricky unification exact (B.isBoundedBilinearMap.hasFDerivAt (f x, g x)).comp_hasFDerivWithinAt x (hf.prodMk hg) @[fun_prop] theorem ContinuousLinearMap.hasFDerivAt_of_bilinear {f : G' → E} {g : G' → F} {f' : G' →L[𝕜] E} {g' : G' →L[𝕜] F} {x : G'} (hf : HasFDerivAt f f' x) (hg : HasFDerivAt g g' x) : HasFDerivAt (fun y => B (f y) (g y)) (B.precompR G' (f x) g' + B.precompL G' f' (g x)) x := by -- need `by exact` to deal with tricky unification exact (B.isBoundedBilinearMap.hasFDerivAt (f x, g x)).comp x (hf.prodMk hg) @[fun_prop] theorem ContinuousLinearMap.hasStrictFDerivAt_of_bilinear {f : G' → E} {g : G' → F} {f' : G' →L[𝕜] E} {g' : G' →L[𝕜] F} {x : G'} (hf : HasStrictFDerivAt f f' x) (hg : HasStrictFDerivAt g g' x) : HasStrictFDerivAt (fun y => B (f y) (g y)) (B.precompR G' (f x) g' + B.precompL G' f' (g x)) x := (B.isBoundedBilinearMap.hasStrictFDerivAt (f x, g x)).comp x (hf.prodMk hg) theorem ContinuousLinearMap.fderivWithin_of_bilinear {f : G' → E} {g : G' → F} {x : G'} {s : Set G'} (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) (hs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (fun y => B (f y) (g y)) s x = B.precompR G' (f x) (fderivWithin 𝕜 g s x) + B.precompL G' (fderivWithin 𝕜 f s x) (g x) := (B.hasFDerivWithinAt_of_bilinear hf.hasFDerivWithinAt hg.hasFDerivWithinAt).fderivWithin hs theorem ContinuousLinearMap.fderiv_of_bilinear {f : G' → E} {g : G' → F} {x : G'} (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : fderiv 𝕜 (fun y => B (f y) (g y)) x = B.precompR G' (f x) (fderiv 𝕜 g x) + B.precompL G' (fderiv 𝕜 f x) (g x) := (B.hasFDerivAt_of_bilinear hf.hasFDerivAt hg.hasFDerivAt).fderiv end BilinearMap end
Normed.lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Analysis.Calculus.BumpFunction.Basic import Mathlib.MeasureTheory.Integral.Bochner.ContinuousLinearMap import Mathlib.MeasureTheory.Measure.Lebesgue.EqHaar /-! # Normed bump function In this file we define `ContDiffBump.normed f μ` to be the bump function `f` normalized so that `∫ x, f.normed μ x ∂μ = 1` and prove some properties of this function. -/ noncomputable section open Function Filter Set Metric MeasureTheory Module Measure open scoped Topology namespace ContDiffBump variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [HasContDiffBump E] [MeasurableSpace E] {c : E} (f : ContDiffBump c) {x : E} {n : ℕ∞} {μ : Measure E} /-- A bump function normed so that `∫ x, f.normed μ x ∂μ = 1`. -/ protected def normed (μ : Measure E) : E → ℝ := fun x => f x / ∫ x, f x ∂μ theorem normed_def {μ : Measure E} (x : E) : f.normed μ x = f x / ∫ x, f x ∂μ := rfl theorem nonneg_normed (x : E) : 0 ≤ f.normed μ x := div_nonneg f.nonneg <| integral_nonneg f.nonneg' theorem contDiff_normed {n : ℕ∞} : ContDiff ℝ n (f.normed μ) := f.contDiff.div_const _ theorem continuous_normed : Continuous (f.normed μ) := f.continuous.div_const _ theorem normed_sub (x : E) : f.normed μ (c - x) = f.normed μ (c + x) := by simp_rw [f.normed_def, f.sub] theorem normed_neg (f : ContDiffBump (0 : E)) (x : E) : f.normed μ (-x) = f.normed μ x := by simp_rw [f.normed_def, f.neg] variable [BorelSpace E] [FiniteDimensional ℝ E] [IsLocallyFiniteMeasure μ] protected theorem integrable : Integrable f μ := f.continuous.integrable_of_hasCompactSupport f.hasCompactSupport protected theorem integrable_normed : Integrable (f.normed μ) μ := f.integrable.div_const _ section variable [μ.IsOpenPosMeasure] theorem integral_pos : 0 < ∫ x, f x ∂μ := by refine (integral_pos_iff_support_of_nonneg f.nonneg' f.integrable).mpr ?_ rw [f.support_eq] exact measure_ball_pos μ c f.rOut_pos theorem integral_normed : ∫ x, f.normed μ x ∂μ = 1 := by simp_rw [ContDiffBump.normed, div_eq_mul_inv, mul_comm (f _), ← smul_eq_mul, integral_smul] exact inv_mul_cancel₀ f.integral_pos.ne' theorem support_normed_eq : Function.support (f.normed μ) = Metric.ball c f.rOut := by unfold ContDiffBump.normed rw [support_div, f.support_eq, support_const f.integral_pos.ne', inter_univ] theorem tsupport_normed_eq : tsupport (f.normed μ) = Metric.closedBall c f.rOut := by rw [tsupport, f.support_normed_eq, closure_ball _ f.rOut_pos.ne'] theorem hasCompactSupport_normed : HasCompactSupport (f.normed μ) := by simp only [HasCompactSupport, f.tsupport_normed_eq (μ := μ), isCompact_closedBall] theorem tendsto_support_normed_smallSets {ι} {φ : ι → ContDiffBump c} {l : Filter ι} (hφ : Tendsto (fun i => (φ i).rOut) l (𝓝 0)) : Tendsto (fun i => Function.support fun x => (φ i).normed μ x) l (𝓝 c).smallSets := by simp_rw [NormedAddCommGroup.tendsto_nhds_zero, Real.norm_eq_abs, abs_eq_self.mpr (φ _).rOut_pos.le] at hφ rw [nhds_basis_ball.smallSets.tendsto_right_iff] refine fun ε hε ↦ (hφ ε hε).mono fun i hi ↦ ?_ rw [(φ i).support_normed_eq] exact ball_subset_ball hi.le variable (μ) theorem integral_normed_smul {X} [NormedAddCommGroup X] [NormedSpace ℝ X] [CompleteSpace X] (z : X) : ∫ x, f.normed μ x • z ∂μ = z := by simp_rw [integral_smul_const, f.integral_normed (μ := μ), one_smul] end variable (μ) theorem measure_closedBall_le_integral : μ.real (closedBall c f.rIn) ≤ ∫ x, f x ∂μ := by calc μ.real (closedBall c f.rIn) = ∫ x in closedBall c f.rIn, 1 ∂μ := by simp _ = ∫ x in closedBall c f.rIn, f x ∂μ := setIntegral_congr_fun measurableSet_closedBall (fun x hx ↦ (one_of_mem_closedBall f hx).symm) _ ≤ ∫ x, f x ∂μ := setIntegral_le_integral f.integrable (Eventually.of_forall (fun x ↦ f.nonneg)) theorem normed_le_div_measure_closedBall_rIn [μ.IsOpenPosMeasure] (x : E) : f.normed μ x ≤ 1 / μ.real (closedBall c f.rIn) := by rw [normed_def] gcongr · exact ENNReal.toReal_pos (measure_closedBall_pos _ _ f.rIn_pos).ne' measure_closedBall_lt_top.ne · exact f.le_one · exact f.measure_closedBall_le_integral μ theorem integral_le_measure_closedBall : ∫ x, f x ∂μ ≤ μ.real (closedBall c f.rOut) := by calc ∫ x, f x ∂μ = ∫ x in closedBall c f.rOut, f x ∂μ := by apply (setIntegral_eq_integral_of_forall_compl_eq_zero (fun x hx ↦ ?_)).symm apply f.zero_of_le_dist (le_of_lt _) simpa using hx _ ≤ ∫ x in closedBall c f.rOut, 1 ∂μ := by apply setIntegral_mono f.integrable.integrableOn _ (fun x ↦ f.le_one) simp [measure_closedBall_lt_top] _ = μ.real (closedBall c f.rOut) := by simp theorem measure_closedBall_div_le_integral [IsAddHaarMeasure μ] (K : ℝ) (h : f.rOut ≤ K * f.rIn) : μ.real (closedBall c f.rOut) / K ^ finrank ℝ E ≤ ∫ x, f x ∂μ := by have K_pos : 0 < K := by simpa [f.rIn_pos, not_lt.2 f.rIn_pos.le] using mul_pos_iff.1 (f.rOut_pos.trans_le h) apply le_trans _ (f.measure_closedBall_le_integral μ) rw [div_le_iff₀ (pow_pos K_pos _), addHaar_real_closedBall' _ _ f.rIn_pos.le, addHaar_real_closedBall' _ _ f.rOut_pos.le, mul_assoc, mul_comm _ (K ^ _), ← mul_assoc, ← mul_pow, mul_comm _ K] gcongr exact f.rOut_pos.le theorem normed_le_div_measure_closedBall_rOut [IsAddHaarMeasure μ] (K : ℝ) (h : f.rOut ≤ K * f.rIn) (x : E) : f.normed μ x ≤ K ^ finrank ℝ E / μ.real (closedBall c f.rOut) := by have K_pos : 0 < K := by simpa [f.rIn_pos, not_lt.2 f.rIn_pos.le] using mul_pos_iff.1 (f.rOut_pos.trans_le h) have : f x / ∫ y, f y ∂μ ≤ 1 / ∫ y, f y ∂μ := by gcongr · exact f.integral_pos.le · exact f.le_one apply this.trans rw [div_le_div_iff₀ f.integral_pos, one_mul, ← div_le_iff₀' (pow_pos K_pos _)] · exact f.measure_closedBall_div_le_integral μ K h · exact ENNReal.toReal_pos (measure_closedBall_pos _ _ f.rOut_pos).ne' measure_closedBall_lt_top.ne end ContDiffBump
Subfield.lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import Mathlib.Algebra.Field.Subfield.Defs import Mathlib.Algebra.Order.Ring.InjSurj /-! # Ordered instances on subfields -/ namespace Subfield variable {K : Type*} /-- A subfield of an ordered field is a ordered field. -/ instance toIsStrictOrderedRing [Field K] [LinearOrder K] [IsStrictOrderedRing K] (s : Subfield K) : IsStrictOrderedRing s := Subtype.coe_injective.isStrictOrderedRing Subtype.val rfl rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) fun _ => rfl end Subfield
qpoly.v
From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import fintype tuple bigop binomial finset finfun ssralg. From mathcomp Require Import countalg finalg poly polydiv perm fingroup matrix. From mathcomp Require Import mxalgebra mxpoly vector countalg. (******************************************************************************) (* This file defines the algebras R[X]/<p> and their theory. *) (* It mimics the zmod file for polynomials *) (* First, it defines polynomials of bounded size (equivalent of 'I_n), *) (* gives it a structure of choice, finite and countable ring, ..., and *) (* lmodule, when possible. *) (* Internally, the construction uses poly_rV and rVpoly, but they should not *) (* be exposed. *) (* We provide two bases: the 'X^i and the lagrange polynomials. *) (* {poly_n R} == the type of polynomial of size at most n *) (* irreducibleb p == boolean decision procedure for irreducibility *) (* of a bounded size polynomial over a finite idomain *) (* Considering {poly_n F} over a field F, it is a vectType and *) (* 'nX^i == 'X^i as an element of {poly_n R} *) (* polynX == [tuple 'X^0, ..., 'X^(n - 1)], basis of {poly_n R} *) (* x.-lagrange == lagrange basis of {poly_n R} wrt x : nat -> F *) (* x.-lagrange_ i == the ith lagrange polynomial wrt the sampling points x *) (* Second, it defines polynomials quotiented by a poly (equivalent of 'Z_p), *) (* as bounded polynomial. As we are aiming to build a ring structure we need *) (* the polynomial to be monic and of size greater than one. If it is not the *) (* case we quotient by 'X *) (* mk_monic p == the actual polynomial on which we quotient *) (* if p is monic and of size > 1 it is p otherwise 'X *) (* {poly %/ p} == defined as {poly_(size (mk_poly p)).-1 R} on which *) (* there is a ring structure *) (* in_qpoly q == turn the polynomial q into an element of {poly %/ p} by *) (* taking a modulo *) (* 'qX == in_qpoly 'X *) (* The last part that defines the field structure when the quotient is an *) (* irreducible polynomial is defined in field/qfpoly *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory. Import Pdiv.CommonRing. Import Pdiv.RingMonic. Import Pdiv.Field. Import FinRing.Theory. Local Open Scope ring_scope. Reserved Notation "'{poly_' n R }" (n at level 2, format "'{poly_' n R }"). Reserved Notation "''nX^' i" (at level 1, format "''nX^' i"). Reserved Notation "x .-lagrange" (format "x .-lagrange"). Reserved Notation "x .-lagrange_" (format "x .-lagrange_"). Reserved Notation "'qX". Reserved Notation "{ 'poly' '%/' p }" (p at level 2, format "{ 'poly' '%/' p }"). Section poly_of_size_zmod. Context {R : nzRingType}. Implicit Types (n : nat). Section poly_of_size. Variable (n : nat). Definition poly_of_size_pred := fun p : {poly R} => size p <= n. Arguments poly_of_size_pred _ /. Definition poly_of_size := [qualify a p | poly_of_size_pred p]. Lemma npoly_submod_closed : submod_closed poly_of_size. Proof. split=> [|x p q sp sq]; rewrite qualifE/= ?size_polyC ?eqxx//. rewrite (leq_trans (size_polyD _ _)) // geq_max. by rewrite (leq_trans (size_scale_leq _ _)). Qed. HB.instance Definition _ := GRing.isSubmodClosed.Build R {poly R} poly_of_size_pred npoly_submod_closed. End poly_of_size. Arguments poly_of_size_pred _ _ /. Section npoly. Variable (n : nat). Record npoly : predArgType := NPoly { polyn :> {poly R}; _ : polyn \is a poly_of_size n }. HB.instance Definition _ := [isSub for @polyn]. Lemma npoly_is_a_poly_of_size (p : npoly) : val p \is a poly_of_size n. Proof. by case: p. Qed. Hint Resolve npoly_is_a_poly_of_size : core. Lemma size_npoly (p : npoly) : size p <= n. Proof. exact: npoly_is_a_poly_of_size. Qed. Hint Resolve size_npoly : core. HB.instance Definition _ := [Choice of npoly by <:]. HB.instance Definition _ := [SubChoice_isSubLmodule of npoly by <:]. Definition npoly_rV : npoly -> 'rV[R]_n := poly_rV \o val. Definition rVnpoly : 'rV[R]_n -> npoly := insubd (0 : npoly) \o rVpoly. Arguments rVnpoly /. Arguments npoly_rV /. Lemma npoly_rV_K : cancel npoly_rV rVnpoly. Proof. move=> p /=; apply/val_inj. by rewrite val_insubd [_ \is a _]size_poly ?poly_rV_K. Qed. Lemma rVnpolyK : cancel rVnpoly npoly_rV. Proof. by move=> p /=; rewrite val_insubd [_ \is a _]size_poly rVpolyK. Qed. Hint Resolve npoly_rV_K rVnpolyK : core. Lemma npoly_vect_axiom : Vector.axiom n npoly. Proof. by exists npoly_rV; [exact:linearPZ | exists rVnpoly]. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build R npoly npoly_vect_axiom. End npoly. End poly_of_size_zmod. Arguments npoly {R}%_type n%_N. Notation "'{poly_' n R }" := (@npoly R n) : type_scope. #[global] Hint Resolve size_npoly npoly_is_a_poly_of_size : core. Arguments poly_of_size_pred _ _ _ /. Arguments npoly : clear implicits. HB.instance Definition _ (R : countNzRingType) n := [Countable of {poly_n R} by <:]. HB.instance Definition _ (R : finNzRingType) n : isFinite {poly_n R} := CanIsFinite (@npoly_rV_K R n). Section npoly_theory. Context (R : nzRingType) {n : nat}. Lemma polyn_is_linear : linear (@polyn _ _ : {poly_n R} -> _). Proof. by []. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly_n R} {poly R} _ (polyn (n:=n)) (GRing.semilinear_linear polyn_is_linear). Canonical mk_npoly (E : nat -> R) : {poly_n R} := @NPoly R _ (\poly_(i < n) E i) (size_poly _ _). Fact size_npoly0 : size (0 : {poly R}) <= n. Proof. by rewrite size_poly0. Qed. Definition npoly0 := NPoly (size_npoly0). Fact npolyp_key : unit. Proof. exact: tt. Qed. Definition npolyp : {poly R} -> {poly_n R} := locked_with npolyp_key (mk_npoly \o (nth 0)). Definition npoly_of_seq := npolyp \o Poly. Lemma npolyP (p q : {poly_n R}) : nth 0 p =1 nth 0 q <-> p = q. Proof. by split => [/polyP/val_inj|->]. Qed. Lemma coef_npolyp (p : {poly R}) i : (npolyp p)`_i = if i < n then p`_i else 0. Proof. by rewrite /npolyp unlock /= coef_poly. Qed. Lemma big_coef_npoly (p : {poly_n R}) i : n <= i -> p`_i = 0. Proof. by move=> i_big; rewrite nth_default // (leq_trans _ i_big) ?size_npoly. Qed. Lemma npolypK (p : {poly R}) : size p <= n -> npolyp p = p :> {poly R}. Proof. move=> spn; apply/polyP=> i; rewrite coef_npolyp. by have [i_big|i_small] // := ltnP; rewrite nth_default ?(leq_trans spn). Qed. Lemma coefn_sum (I : Type) (r : seq I) (P : pred I) (F : I -> {poly_n R}) (k : nat) : (\sum_(i <- r | P i) F i)`_k = \sum_(i <- r | P i) (F i)`_k. Proof. by rewrite !raddf_sum //= coef_sum. Qed. End npoly_theory. Arguments mk_npoly {R} n E. Arguments npolyp {R} n p. Section fin_npoly. Variable R : finNzRingType. Variable n : nat. Implicit Types p q : {poly_n R}. Definition npoly_enum : seq {poly_n R} := if n isn't n.+1 then [:: npoly0 _] else pmap insub [seq \poly_(i < n.+1) c (inord i) | c : (R ^ n.+1)%type]. Lemma npoly_enum_uniq : uniq npoly_enum. Proof. rewrite /npoly_enum; case: n=> [|k] //. rewrite pmap_sub_uniq // map_inj_uniq => [|f g eqfg]; rewrite ?enum_uniq //. apply/ffunP => /= i; have /(congr1 (fun p : {poly _} => p`_i)) := eqfg. by rewrite !coef_poly ltn_ord inord_val. Qed. Lemma mem_npoly_enum p : p \in npoly_enum. Proof. rewrite /npoly_enum; case: n => [|k] // in p *. case: p => [p sp] /=. by rewrite in_cons -val_eqE /= -size_poly_leq0 [size _ <= _]sp. rewrite mem_pmap_sub; apply/mapP. eexists [ffun i : 'I__ => p`_i]; first by rewrite mem_enum. apply/polyP => i; rewrite coef_poly. have [i_small|i_big] := ltnP; first by rewrite ffunE /= inordK. by rewrite nth_default // 1?(leq_trans _ i_big) // size_npoly. Qed. Lemma card_npoly : #|{poly_n R}| = (#|R| ^ n)%N. Proof. rewrite -(card_imset _ (can_inj (@npoly_rV_K _ _))) eq_cardT. by rewrite -cardT /= card_mx mul1n. by move=> v; apply/imsetP; exists (rVnpoly v); rewrite ?rVnpolyK //. Qed. End fin_npoly. Section Irreducible. Variable R : finIdomainType. Variable p : {poly R}. Definition irreducibleb := ((1 < size p) && [forall q : {poly_((size p).-1) R}, (Pdiv.Ring.rdvdp q p)%R ==> (size q <= 1)])%N. Lemma irreducibleP : reflect (irreducible_poly p) irreducibleb. Proof. rewrite /irreducibleb /irreducible_poly. apply: (iffP idP) => [/andP[sp /'forall_implyP /= Fp]|[sp Fpoly]]. have sp_gt0 : size p > 0 by case: size sp. have p_neq0 : p != 0 by rewrite -size_poly_eq0; case: size sp. split => // q sq_neq1 dvd_qp; rewrite -dvdp_size_eqp // eqn_leq dvdp_leq //=. apply: contraNT sq_neq1; rewrite -ltnNge => sq_lt_sp. have q_small: (size q <= (size p).-1)%N by rewrite -ltnS prednK. rewrite Pdiv.Idomain.dvdpE in dvd_qp. have /= := Fp (NPoly q_small) dvd_qp. rewrite leq_eqVlt ltnS => /orP[//|]; rewrite size_poly_leq0 => /eqP q_eq0. by rewrite -Pdiv.Idomain.dvdpE q_eq0 dvd0p (negPf p_neq0) in dvd_qp. have sp_gt0 : size p > 0 by case: size sp. rewrite sp /=; apply/'forall_implyP => /= q. rewrite -Pdiv.Idomain.dvdpE=> dvd_qp. have [/eqP->//|/Fpoly/(_ dvd_qp)/eqp_size sq_eq_sp] := boolP (size q == 1%N). by have := size_npoly q; rewrite sq_eq_sp -ltnS prednK ?ltnn. Qed. End Irreducible. Section Vspace. Variable (K : fieldType) (n : nat). Lemma dim_polyn : \dim (fullv : {vspace {poly_n K}}) = n. Proof. by rewrite [LHS]mxrank_gen mxrank1. Qed. Definition npolyX : n.-tuple {poly_n K} := [tuple npolyp n 'X^i | i < n]. Notation "''nX^' i" := (tnth npolyX i). Lemma npolyXE (i : 'I_n) : 'nX^i = 'X^i :> {poly _}. Proof. by rewrite tnth_map tnth_ord_tuple npolypK // size_polyXn. Qed. Lemma nth_npolyX (i : 'I_n) : npolyX`_i = 'nX^i. Proof. by rewrite -tnth_nth. Qed. Lemma npolyX_free : free npolyX. Proof. apply/freeP=> u /= sum_uX_eq0 i; have /npolyP /(_ i) := sum_uX_eq0. rewrite (@big_morph _ _ _ 0%R +%R) // coef_sum coef0. rewrite (bigD1 i) ?big1 /= ?addr0 ?coefZ ?(nth_map 0%N) ?size_iota //. by rewrite nth_npolyX npolyXE coefXn eqxx mulr1. move=> j; rewrite -val_eqE /= => neq_ji. by rewrite nth_npolyX npolyXE coefZ coefXn eq_sym (negPf neq_ji) mulr0. Qed. Lemma npolyX_full : basis_of fullv npolyX. Proof. by rewrite basisEfree npolyX_free subvf size_map size_enum_ord dim_polyn /=. Qed. Lemma npolyX_coords (p : {poly_n K}) i : coord npolyX i p = p`_i. Proof. rewrite [p in RHS](coord_basis npolyX_full) ?memvf // coefn_sum. rewrite (bigD1 i) //= coefZ nth_npolyX npolyXE coefXn eqxx mulr1 big1 ?addr0//. move=> j; rewrite -val_eqE => /= neq_ji. by rewrite coefZ nth_npolyX npolyXE coefXn eq_sym (negPf neq_ji) mulr0. Qed. Lemma npolyX_gen (p : {poly K}) : (size p <= n)%N -> p = \sum_(i < n) p`_i *: 'nX^i. Proof. move=> sp; rewrite -[p](@npolypK _ n) //. rewrite [npolyp _ _ in LHS](coord_basis npolyX_full) ?memvf //. rewrite (@big_morph _ _ _ 0%R +%R) // !raddf_sum. by apply: eq_bigr=> i _; rewrite npolyX_coords //= nth_npolyX npolyXE. Qed. Section lagrange. Variables (x : nat -> K). Notation lagrange_def := (fun i :'I_n => let k := i in let p := \prod_(j < n | j != k) ('X - (x j)%:P) in (p.[x k]^-1)%:P * p). Fact lagrange_key : unit. Proof. exact: tt. Qed. Definition lagrange := locked_with lagrange_key [tuple npolyp n (lagrange_def i) | i < n]. Notation lagrange_ := (tnth lagrange). Hypothesis n_gt0 : (0 < n)%N. Hypothesis x_inj : injective x. Let lagrange_def_sample (i j : 'I_n) : (lagrange_def i).[x j] = (i == j)%:R. Proof. clear n_gt0; rewrite hornerM hornerC; set p := (\prod_(_ < _ | _) _). have [<-|neq_ij] /= := altP eqP. rewrite mulVf // horner_prod; apply/prodf_neq0 => k neq_ki. by rewrite hornerXsubC subr_eq0 inj_eq // eq_sym. rewrite [X in _ * X]horner_prod (bigD1 j) 1?eq_sym //=. by rewrite hornerXsubC subrr mul0r mulr0. Qed. Let size_lagrange_def i : size (lagrange_def i) = n. Proof. rewrite size_Cmul; last first. suff : (lagrange_def i).[x i] != 0. by rewrite hornerE mulf_eq0 => /norP []. by rewrite lagrange_def_sample ?eqxx ?oner_eq0. rewrite size_prod /=; last first. by move=> j neq_ji; rewrite polyXsubC_eq0. rewrite (eq_bigr (fun=> (2 * 1)%N)); last first. by move=> j neq_ji; rewrite size_XsubC. rewrite -big_distrr /= sum1_card cardC1 card_ord /=. by case: (n) {i} n_gt0 => ?; rewrite mul2n -addnn -addSn addnK. Qed. Lemma lagrangeE i : lagrange_ i = lagrange_def i :> {poly _}. Proof. rewrite [lagrange]unlock tnth_map. by rewrite [val _]npolypK tnth_ord_tuple // size_lagrange_def. Qed. Lemma nth_lagrange (i : 'I_n) : lagrange`_i = lagrange_ i. Proof. by rewrite -tnth_nth. Qed. Lemma size_lagrange_ i : size (lagrange_ i) = n. Proof. by rewrite lagrangeE size_lagrange_def. Qed. Lemma size_lagrange : size lagrange = n. Proof. by rewrite size_tuple. Qed. Lemma lagrange_sample (i j : 'I_n) : (lagrange_ i).[x j] = (i == j)%:R. Proof. by rewrite lagrangeE lagrange_def_sample. Qed. Lemma lagrange_free : free lagrange. Proof. apply/freeP=> lambda eq_l i. have /(congr1 (fun p : {poly__ _} => p.[x i])) := eq_l. rewrite (@big_morph _ _ _ 0%R +%R) // horner_sum horner0. rewrite (bigD1 i) // big1 => [|j /= /negPf ji] /=; by rewrite ?hornerE nth_lagrange lagrange_sample ?eqxx ?ji ?mulr1 ?mulr0. Qed. Lemma lagrange_full : basis_of fullv lagrange. Proof. by rewrite basisEfree lagrange_free subvf size_lagrange dim_polyn /=. Qed. Lemma lagrange_coords (p : {poly_n K}) i : coord lagrange i p = p.[x i]. Proof. rewrite [p in RHS](coord_basis lagrange_full) ?memvf //. rewrite (@big_morph _ _ _ 0%R +%R) // horner_sum. rewrite (bigD1 i) // big1 => [|j /= /negPf ji] /=; by rewrite ?hornerE nth_lagrange lagrange_sample ?eqxx ?ji ?mulr1 ?mulr0. Qed. Lemma lagrange_gen (p : {poly K}) : (size p <= n)%N -> p = \sum_(i < n) p.[x i]%:P * lagrange_ i. Proof. move=> sp; rewrite -[p](@npolypK _ n) //. rewrite [npolyp _ _ in LHS](coord_basis lagrange_full) ?memvf //. rewrite (@big_morph _ _ _ 0%R +%R) //; apply: eq_bigr=> i _. by rewrite lagrange_coords mul_polyC nth_lagrange. Qed. End lagrange. End Vspace. Notation "''nX^' i" := (tnth (npolyX _) i) : ring_scope. Notation "x .-lagrange" := (lagrange x) : ring_scope. Notation "x .-lagrange_" := (tnth x.-lagrange) : ring_scope. Section Qpoly. Variable R : nzRingType. Variable h : {poly R}. Definition mk_monic := if (1 < size h)%N && (h \is monic) then h else 'X. Definition qpoly := {poly_(size mk_monic).-1 R}. End Qpoly. Notation "{ 'poly' '%/' p }" := (qpoly p) : type_scope. Section QpolyProp. Variable R : nzRingType. Variable h : {poly R}. Lemma monic_mk_monic : (mk_monic h) \is monic. Proof. rewrite /mk_monic; case: leqP=> [_|/=]; first by apply: monicX. by case E : (h \is monic) => [->//|] => _; apply: monicX. Qed. Lemma size_mk_monic_gt1 : (1 < size (mk_monic h))%N. Proof. by rewrite !fun_if size_polyX; case: leqP => //=; rewrite if_same. Qed. Lemma size_mk_monic_gt0 : (0 < size (mk_monic h))%N. Proof. by rewrite (leq_trans _ size_mk_monic_gt1). Qed. Lemma mk_monic_neq0 : mk_monic h != 0. Proof. by rewrite -size_poly_gt0 size_mk_monic_gt0. Qed. Lemma size_mk_monic (p : {poly %/ h}) : size p < size (mk_monic h). Proof. have: (p : {poly R}) \is a poly_of_size (size (mk_monic h)).-1 by case: p. by rewrite qualifE/= -ltnS prednK // size_mk_monic_gt0. Qed. (* standard inject *) Lemma poly_of_size_mod p : rmodp p (mk_monic h) \is a poly_of_size (size (mk_monic h)).-1. Proof. rewrite qualifE/= -ltnS prednK ?size_mk_monic_gt0 //. by apply: ltn_rmodpN0; rewrite mk_monic_neq0. Qed. Definition in_qpoly p : {poly %/ h} := NPoly (poly_of_size_mod p). Lemma in_qpoly_small (p : {poly R}) : size p < size (mk_monic h) -> in_qpoly p = p :> {poly R}. Proof. exact: rmodp_small. Qed. Lemma in_qpoly0 : in_qpoly 0 = 0. Proof. by apply/val_eqP; rewrite /= rmod0p. Qed. Lemma in_qpolyD p q : in_qpoly (p + q) = in_qpoly p + in_qpoly q. Proof. by apply/val_eqP=> /=; rewrite rmodpD ?monic_mk_monic. Qed. Lemma in_qpolyZ a p : in_qpoly (a *: p) = a *: in_qpoly p. Proof. apply/val_eqP=> /=; rewrite rmodpZ ?monic_mk_monic //. Qed. Fact in_qpoly_is_linear : linear in_qpoly. Proof. by move=> k p q; rewrite in_qpolyD in_qpolyZ. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly_(size (mk_monic h)).-1 R} _ in_qpoly (GRing.semilinear_linear in_qpoly_is_linear). Lemma qpolyC_proof k : (k%:P : {poly R}) \is a poly_of_size (size (mk_monic h)).-1. Proof. rewrite qualifE/= -ltnS size_polyC prednK ?size_mk_monic_gt0 //. by rewrite (leq_ltn_trans _ size_mk_monic_gt1) //; case: eqP. Qed. Definition qpolyC k : {poly %/ h} := NPoly (qpolyC_proof k). Lemma qpolyCE k : qpolyC k = k%:P :> {poly R}. Proof. by []. Qed. Lemma qpolyC0 : qpolyC 0 = 0. Proof. by apply/val_eqP/eqP. Qed. Definition qpoly1 := qpolyC 1. Definition qpoly_mul (q1 q2 : {poly %/ h}) : {poly %/ h} := in_qpoly ((q1 : {poly R}) * q2). Lemma qpoly_mul1z : left_id qpoly1 qpoly_mul. Proof. by move=> x; apply: val_inj; rewrite /= mul1r rmodp_small // size_mk_monic. Qed. Lemma qpoly_mulz1 : right_id qpoly1 qpoly_mul. Proof. by move=> x; apply: val_inj; rewrite /= mulr1 rmodp_small // size_mk_monic. Qed. Lemma qpoly_nontrivial : qpoly1 != 0. Proof. by apply/eqP/val_eqP; rewrite /= oner_eq0. Qed. Definition qpolyX := in_qpoly 'X. Notation "'qX" := qpolyX. Lemma qpolyXE : 2 < size h -> h \is monic -> 'qX = 'X :> {poly R}. Proof. move=> sh_gt2 h_mo. by rewrite in_qpoly_small // size_polyX /mk_monic ifT // (ltn_trans _ sh_gt2). Qed. End QpolyProp. Notation "'qX" := (qpolyX _) : ring_scope. Lemma mk_monic_X (R : nzRingType) : mk_monic 'X = 'X :> {poly R}. Proof. by rewrite /mk_monic size_polyX monicX. Qed. Lemma mk_monic_Xn (R : nzRingType) n : mk_monic 'X^n = 'X^(n.-1.+1) :> {poly R}. Proof. by case: n => [|n]; rewrite /mk_monic size_polyXn monicXn /= ?expr1. Qed. Lemma card_qpoly (R : finNzRingType) (h : {poly R}): #|{poly %/ h}| = #|R| ^ (size (mk_monic h)).-1. Proof. by rewrite card_npoly. Qed. Lemma card_monic_qpoly (R : finNzRingType) (h : {poly R}): 1 < size h -> h \is monic -> #|{poly %/ h}| = #|R| ^ (size h).-1. Proof. by move=> sh_gt1 hM; rewrite card_qpoly /mk_monic sh_gt1 hM. Qed. Section QRing. Variable A : comNzRingType. Variable h : {poly A}. (* Ring operations *) Lemma qpoly_mulC : commutative (@qpoly_mul A h). Proof. by move=> p q; apply: val_inj; rewrite /= mulrC. Qed. Lemma qpoly_mulA : associative (@qpoly_mul A h). Proof. have rPM := monic_mk_monic h; move=> p q r; apply: val_inj. by rewrite /= rmodp_mulml // rmodp_mulmr // mulrA. Qed. Lemma qpoly_mul_addr : right_distributive (@qpoly_mul A h) +%R. Proof. have rPM := monic_mk_monic h; move=> p q r; apply: val_inj. by rewrite /= !(mulrDr, rmodp_mulmr, rmodpD). Qed. Lemma qpoly_mul_addl : left_distributive (@qpoly_mul A h) +%R. Proof. by move=> p q r; rewrite -!(qpoly_mulC r) qpoly_mul_addr. Qed. HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build {poly__ A} qpoly_mulA qpoly_mulC (@qpoly_mul1z _ h) qpoly_mul_addl (@qpoly_nontrivial _ h). HB.instance Definition _ := GRing.ComNzRing.on {poly %/ h}. Lemma in_qpoly1 : in_qpoly h 1 = 1. Proof. apply/val_eqP/eqP/in_qpoly_small. by rewrite size_polyC oner_eq0 /= size_mk_monic_gt1. Qed. Lemma in_qpolyM q1 q2 : in_qpoly h (q1 * q2) = in_qpoly h q1 * in_qpoly h q2. Proof. apply/val_eqP => /=. by rewrite rmodp_mulml ?rmodp_mulmr // monic_mk_monic. Qed. Fact in_qpoly_monoid_morphism : monoid_morphism (in_qpoly h). Proof. by split; [ apply: in_qpoly1 | apply: in_qpolyM]. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `in_qpoly_is_monoid_morphism` instead")] Definition in_qpoly_is_multiplicative := (fun g => (g.2,g.1)) in_qpoly_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly A} {poly %/ h} (in_qpoly h) in_qpoly_monoid_morphism. Lemma poly_of_qpoly_sum I (r : seq I) (P1 : pred I) (F : I -> {poly %/ h}) : ((\sum_(i <- r | P1 i) F i) = \sum_(p <- r | P1 p) ((F p) : {poly A}) :> {poly A})%R. Proof. by elim/big_rec2: _ => // i p q IH <-. Qed. Lemma poly_of_qpolyD (p q : {poly %/ h}) : p + q= (p : {poly A}) + q :> {poly A}. Proof. by []. Qed. Lemma qpolyC_natr p : (p%:R : {poly %/ h}) = p%:R :> {poly A}. Proof. by elim: p => //= p IH; rewrite !mulrS poly_of_qpolyD IH. Qed. Lemma pchar_qpoly : [pchar {poly %/ h}] =i [pchar A]. Proof. move=> p; rewrite !inE; congr (_ && _). apply/eqP/eqP=> [/(congr1 val) /=|pE]; last first. by apply: val_inj => //=; rewrite qpolyC_natr /= -polyC_natr pE. rewrite !qpolyC_natr -!polyC_natr => /(congr1 val) /=. by rewrite polyseqC polyseq0; case: eqP. Qed. Lemma poly_of_qpolyM (p q : {poly %/ h}) : p * q = rmodp ((p : {poly A}) * q) (mk_monic h) :> {poly A}. Proof. by []. Qed. Lemma poly_of_qpolyX (p : {poly %/ h}) n : p ^+ n = rmodp ((p : {poly A}) ^+ n) (mk_monic h) :> {poly A}. Proof. have HhQ := monic_mk_monic h. elim: n => //= [|n IH]. rewrite rmodp_small // size_polyC ?(leq_ltn_trans _ (size_mk_monic_gt1 _)) //. by case: eqP. by rewrite exprS /= IH // rmodp_mulmr // -exprS. Qed. Lemma qpolyCN (a : A) : qpolyC h (- a) = -(qpolyC h a). Proof. apply: val_inj; rewrite /= raddfN //= raddfN. Qed. Lemma qpolyCD : {morph (qpolyC h) : a b / a + b >-> a + b}%R. Proof. by move=> a b; apply/val_eqP/eqP=> /=; rewrite -!raddfD. Qed. Lemma qpolyCM : {morph (qpolyC h) : a b / a * b >-> a * b}%R. Proof. move=> a b; apply/val_eqP/eqP=> /=; rewrite -polyCM rmodp_small //=. have := qpolyC_proof h (a * b). by rewrite qualifE/= -ltnS prednK // size_mk_monic_gt0. Qed. Lemma qpolyC_is_zmod_morphism : zmod_morphism (qpolyC h). Proof. by move=> x y; rewrite qpolyCD qpolyCN. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `qpolyC_is_zmod_morphism` instead")] Definition qpolyC_is_additive := qpolyC_is_zmod_morphism. Lemma qpolyC_is_monoid_morphism : monoid_morphism (qpolyC h). Proof. by split=> // x y; rewrite qpolyCM. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `qpolyC_is_monoid_morphism` instead")] Definition qpolyC_is_multiplicative := (fun g => (g.2,g.1)) qpolyC_is_monoid_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build A {poly %/ h} (qpolyC h) qpolyC_is_zmod_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build A {poly %/ h} (qpolyC h) qpolyC_is_monoid_morphism. Definition qpoly_scale k (p : {poly %/ h}) : {poly %/ h} := (k *: p)%R. Fact qpoly_scaleA a b p : qpoly_scale a (qpoly_scale b p) = qpoly_scale (a * b) p. Proof. by apply/val_eqP; rewrite /= scalerA. Qed. Fact qpoly_scale1l : left_id 1%R qpoly_scale. Proof. by move=> p; apply/val_eqP; rewrite /= scale1r. Qed. Fact qpoly_scaleDr a : {morph qpoly_scale a : p q / (p + q)%R}. Proof. by move=> p q; apply/val_eqP; rewrite /= scalerDr. Qed. Fact qpoly_scaleDl p : {morph qpoly_scale^~ p : a b / a + b}%R. Proof. by move=> a b; apply/val_eqP; rewrite /= scalerDl. Qed. Fact qpoly_scaleAl a p q : qpoly_scale a (p * q) = (qpoly_scale a p * q). Proof. by apply/val_eqP; rewrite /= -scalerAl rmodpZ // monic_mk_monic. Qed. Fact qpoly_scaleAr a p q : qpoly_scale a (p * q) = p * (qpoly_scale a q). Proof. by apply/val_eqP; rewrite /= -scalerAr rmodpZ // monic_mk_monic. Qed. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build A {poly__ A} qpoly_scaleAl. HB.instance Definition _ := GRing.Lalgebra.on {poly %/ h}. HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build A {poly__ A} qpoly_scaleAr. HB.instance Definition _ := GRing.Algebra.on {poly %/ h}. Lemma poly_of_qpolyZ (p : {poly %/ h}) a : a *: p = a *: (p : {poly A}) :> {poly A}. Proof. by []. Qed. End QRing. #[deprecated(since="mathcomp 2.4.0", note="Use pchar_qpoly instead.")] Notation char_qpoly := (pchar_qpoly) (only parsing). Section Field. Variable R : fieldType. Variable h : {poly R}. Local Notation hQ := (mk_monic h). Definition qpoly_inv (p : {poly %/ h}) := if coprimep hQ p then let v : {poly %/ h} := in_qpoly h (egcdp hQ p).2 in ((lead_coef (v * p)) ^-1 *: v) else p. (* Ugly *) Lemma qpoly_mulVz (p : {poly %/ h}) : coprimep hQ p -> (qpoly_inv p * p = 1)%R. Proof. have hQM := monic_mk_monic h. move=> hCp; apply: val_inj; rewrite /qpoly_inv /in_qpoly hCp /=. have p_neq0 : p != 0%R. apply/eqP=> pZ; move: hCp; rewrite pZ. rewrite coprimep0 -size_poly_eq1. by case: size (size_mk_monic_gt1 h) => [|[]]. have F : (egcdp hQ p).1 * hQ + (egcdp hQ p).2 * p %= 1. apply: eqp_trans _ (_ : gcdp hQ p %= _). rewrite eqp_sym. by case: (egcdpP (mk_monic_neq0 h) p_neq0). by rewrite -size_poly_eq1. rewrite rmodp_mulml // -scalerAl rmodpZ // rmodp_mulml //. rewrite -[rmodp]/Pdiv.Ring.rmodp -!Pdiv.IdomainMonic.modpE //. have := eqp_modpl hQ F. rewrite modpD // modp_mull add0r // . rewrite [(1 %% _)%R]modp_small => // [egcdE|]; last first. by rewrite size_polyC oner_eq0 size_mk_monic_gt1. rewrite {2}(eqpfP egcdE) lead_coefC divr1 alg_polyC scale_polyC mulVf //. rewrite lead_coef_eq0. apply/eqP => egcdZ. by move: egcdE; rewrite -size_poly_eq1 egcdZ size_polyC eq_sym eqxx. Qed. Lemma qpoly_mulzV (p : {poly %/ h}) : coprimep hQ p -> (p * (qpoly_inv p) = 1)%R. Proof. by move=> hCp; rewrite /= mulrC qpoly_mulVz. Qed. Lemma qpoly_intro_unit (p q : {poly %/ h}) : (q * p = 1)%R -> coprimep hQ p. Proof. have hQM := monic_mk_monic h. case; rewrite -[rmodp]/Pdiv.Ring.rmodp -!Pdiv.IdomainMonic.modpE // => qp1. have:= coprimep1 hQ. rewrite -coprimep_modr -[1%R]qp1 !coprimep_modr coprimepMr; by case/andP. Qed. Lemma qpoly_inv_out (p : {poly %/ h}) : ~~ coprimep hQ p -> qpoly_inv p = p. Proof. by rewrite /qpoly_inv => /negPf->. Qed. HB.instance Definition _ := GRing.ComNzRing_hasMulInverse.Build {poly__ _} qpoly_mulVz qpoly_intro_unit qpoly_inv_out. HB.instance Definition _ := GRing.ComUnitAlgebra.on {poly %/ h}. Lemma irreducible_poly_coprime (A : idomainType) (p q : {poly A}) : irreducible_poly p -> coprimep p q = ~~(p %| q)%R. Proof. case => H1 H2; apply/coprimepP/negP. move=> sPq H. by have := sPq p (dvdpp _) H; rewrite -size_poly_eq1; case: size H1 => [|[]]. move=> pNDq d dDp dPq. rewrite -size_poly_eq1; case: eqP => // /eqP /(H2 _) => /(_ dDp) dEp. by case: pNDq; rewrite -(eqp_dvdl _ dEp). Qed. End Field.
Relrank.lean
/- Copyright (c) 2024 Jz Pan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jz Pan -/ import Mathlib.FieldTheory.IntermediateField.Adjoin.Basic /-! # Relative rank of subfields and intermediate fields This file contains basics about the relative rank of subfields and intermediate fields. ## Main definitions - `Subfield.relrank A B`, `IntermediateField.relrank A B`: defined to be `[B : A ⊓ B]` as a `Cardinal`. In particular, when `A ≤ B` it is `[B : A]`, the degree of the field extension `B / A`. This is similar to `Subgroup.relindex` but it is `Cardinal` valued. - `Subfield.relfinrank A B`, `IntermediateField.relfinrank A B`: the `Nat` version of `Subfield.relrank A B` and `IntermediateField.relrank A B`, respectively. If `B / A ⊓ B` is an infinite extension, then it is zero. This is similar to `Subgroup.relindex`. -/ open Module Cardinal universe u v w namespace Subfield variable {E : Type v} [Field E] {L : Type w} [Field L] variable (A B C : Subfield E) /-- `Subfield.relrank A B` is defined to be `[B : A ⊓ B]` as a `Cardinal`, in particular, when `A ≤ B` it is `[B : A]`, the degree of the field extension `B / A`. This is similar to `Subgroup.relindex` but it is `Cardinal` valued. -/ noncomputable def relrank := Module.rank ↥(A ⊓ B) (extendScalars (inf_le_right : A ⊓ B ≤ B)) /-- The `Nat` version of `Subfield.relrank`. If `B / A ⊓ B` is an infinite extension, then it is zero. -/ noncomputable def relfinrank := finrank ↥(A ⊓ B) (extendScalars (inf_le_right : A ⊓ B ≤ B)) theorem relfinrank_eq_toNat_relrank : relfinrank A B = toNat (relrank A B) := rfl variable {A B C} theorem relrank_eq_of_inf_eq (h : A ⊓ C = B ⊓ C) : relrank A C = relrank B C := by simp_rw [relrank] congr! theorem relfinrank_eq_of_inf_eq (h : A ⊓ C = B ⊓ C) : relfinrank A C = relfinrank B C := congr(toNat $(relrank_eq_of_inf_eq h)) /-- If `A ≤ B`, then `Subfield.relrank A B` is `[B : A]`. -/ theorem relrank_eq_rank_of_le (h : A ≤ B) : relrank A B = Module.rank A (extendScalars h) := by rw [relrank] have := inf_of_le_left h congr! /-- If `A ≤ B`, then `Subfield.relfinrank A B` is `[B : A]`. -/ theorem relfinrank_eq_finrank_of_le (h : A ≤ B) : relfinrank A B = finrank A (extendScalars h) := congr(toNat $(relrank_eq_rank_of_le h)) variable (A B C) theorem inf_relrank_right : relrank (A ⊓ B) B = relrank A B := relrank_eq_rank_of_le (inf_le_right : A ⊓ B ≤ B) theorem inf_relfinrank_right : relfinrank (A ⊓ B) B = relfinrank A B := congr(toNat $(inf_relrank_right A B)) theorem inf_relrank_left : relrank (A ⊓ B) A = relrank B A := by rw [inf_comm, inf_relrank_right] theorem inf_relfinrank_left : relfinrank (A ⊓ B) A = relfinrank B A := congr(toNat $(inf_relrank_left A B)) @[simp] theorem relrank_self : relrank A A = 1 := by rw [relrank_eq_rank_of_le (le_refl A), extendScalars_self, IntermediateField.rank_bot] @[simp] theorem relfinrank_self : relfinrank A A = 1 := by simp [relfinrank_eq_toNat_relrank] variable {A B} in theorem relrank_eq_one_of_le (h : B ≤ A) : relrank A B = 1 := by rw [← inf_relrank_right, inf_eq_right.2 h, relrank_self] variable {A B} in theorem relfinrank_eq_one_of_le (h : B ≤ A) : relfinrank A B = 1 := by simp [relfinrank_eq_toNat_relrank, relrank_eq_one_of_le h] variable {A B} in theorem relrank_mul_rank_top (h : A ≤ B) : relrank A B * Module.rank B E = Module.rank A E := by rw [relrank_eq_rank_of_le h] letI : Algebra A B := (inclusion h).toAlgebra haveI : IsScalarTower A B E := IsScalarTower.of_algebraMap_eq' rfl exact rank_mul_rank A B E variable {A B} in theorem relfinrank_mul_finrank_top (h : A ≤ B) : relfinrank A B * finrank B E = finrank A E := by simpa using congr(toNat $(relrank_mul_rank_top h)) @[simp] theorem relrank_top_left : relrank ⊤ A = 1 := relrank_eq_one_of_le le_top @[simp] theorem relfinrank_top_left : relfinrank ⊤ A = 1 := relfinrank_eq_one_of_le le_top @[simp] theorem relrank_top_right : relrank A ⊤ = Module.rank A E := by let _ : AddCommMonoid (⊤ : IntermediateField A E) := inferInstance rw [relrank_eq_rank_of_le (show A ≤ ⊤ from le_top), extendScalars_top, IntermediateField.topEquiv.toLinearEquiv.rank_eq] @[simp] theorem relfinrank_top_right : relfinrank A ⊤ = finrank A E := by simp [relfinrank_eq_toNat_relrank, finrank] theorem lift_relrank_map_map (f : E →+* L) : lift.{v} (relrank (A.map f) (B.map f)) = lift.{w} (relrank A B) := -- typeclass inference is slow .symm <| Algebra.lift_rank_eq_of_equiv_equiv (((A ⊓ B).equivMapOfInjective f f.injective).trans <| .subringCongr <| by rw [← map_inf]; rfl) (B.equivMapOfInjective f f.injective) rfl theorem relrank_map_map {L : Type v} [Field L] (f : E →+* L) : relrank (A.map f) (B.map f) = relrank A B := by simpa only [lift_id] using lift_relrank_map_map A B f theorem lift_relrank_comap (f : L →+* E) (B : Subfield L) : lift.{v} (relrank (A.comap f) B) = lift.{w} (relrank A (B.map f)) := (lift_relrank_map_map _ _ f).symm.trans <| congr_arg lift <| relrank_eq_of_inf_eq <| by rw [map_comap_eq, f.fieldRange_eq_map, inf_assoc, ← map_inf, top_inf_eq] theorem relrank_comap {L : Type v} [Field L] (f : L →+* E) (B : Subfield L) : relrank (A.comap f) B = relrank A (B.map f) := by simpa only [lift_id] using A.lift_relrank_comap f B theorem relfinrank_comap (f : L →+* E) (B : Subfield L) : relfinrank (A.comap f) B = relfinrank A (B.map f) := by simpa using congr(toNat $(lift_relrank_comap A f B)) theorem lift_rank_comap (f : L →+* E) : lift.{v} (Module.rank (A.comap f) L) = lift.{w} (relrank A f.fieldRange) := by simpa only [relrank_top_right, ← RingHom.fieldRange_eq_map] using lift_relrank_comap A f ⊤ theorem rank_comap {L : Type v} [Field L] (f : L →+* E) : Module.rank (A.comap f) L = relrank A f.fieldRange := by simpa only [lift_id] using A.lift_rank_comap f theorem finrank_comap (f : L →+* E) : finrank (A.comap f) L = relfinrank A f.fieldRange := by simpa using congr(toNat $(lift_rank_comap A f)) theorem relfinrank_map_map (f : E →+* L) : relfinrank (A.map f) (B.map f) = relfinrank A B := by simpa using congr(toNat $(lift_relrank_map_map A B f)) theorem lift_relrank_comap_comap_eq_lift_relrank_inf (f : L →+* E) : lift.{v} (relrank (A.comap f) (B.comap f)) = lift.{w} (relrank A (B ⊓ f.fieldRange)) := by conv_lhs => rw [← lift_relrank_map_map _ _ f, map_comap_eq, map_comap_eq] congr 1 apply relrank_eq_of_inf_eq rw [inf_assoc, inf_left_comm _ B, inf_of_le_left (le_refl _)] theorem relrank_comap_comap_eq_relrank_inf {L : Type v} [Field L] (f : L →+* E) : relrank (A.comap f) (B.comap f) = relrank A (B ⊓ f.fieldRange) := by simpa only [lift_id] using lift_relrank_comap_comap_eq_lift_relrank_inf A B f theorem relfinrank_comap_comap_eq_relfinrank_inf (f : L →+* E) : relfinrank (A.comap f) (B.comap f) = relfinrank A (B ⊓ f.fieldRange) := by simpa using congr(toNat $(lift_relrank_comap_comap_eq_lift_relrank_inf A B f)) theorem lift_relrank_comap_comap_eq_lift_relrank_of_le (f : L →+* E) (h : B ≤ f.fieldRange) : lift.{v} (relrank (A.comap f) (B.comap f)) = lift.{w} (relrank A B) := by simpa only [inf_of_le_left h] using lift_relrank_comap_comap_eq_lift_relrank_inf A B f theorem relrank_comap_comap_eq_relrank_of_le {L : Type v} [Field L] (f : L →+* E) (h : B ≤ f.fieldRange) : relrank (A.comap f) (B.comap f) = relrank A B := by simpa only [lift_id] using lift_relrank_comap_comap_eq_lift_relrank_of_le A B f h theorem relfinrank_comap_comap_eq_relfinrank_of_le (f : L →+* E) (h : B ≤ f.fieldRange) : relfinrank (A.comap f) (B.comap f) = relfinrank A B := by simpa using congr(toNat $(lift_relrank_comap_comap_eq_lift_relrank_of_le A B f h)) theorem lift_relrank_comap_comap_eq_lift_relrank_of_surjective (f : L →+* E) (h : Function.Surjective f) : lift.{v} (relrank (A.comap f) (B.comap f)) = lift.{w} (relrank A B) := lift_relrank_comap_comap_eq_lift_relrank_of_le A B f fun x _ ↦ h x theorem relrank_comap_comap_eq_relrank_of_surjective {L : Type v} [Field L] (f : L →+* E) (h : Function.Surjective f) : relrank (A.comap f) (B.comap f) = relrank A B := by simpa using lift_relrank_comap_comap_eq_lift_relrank_of_surjective A B f h theorem relfinrank_comap_comap_eq_relfinrank_of_surjective (f : L →+* E) (h : Function.Surjective f) : relfinrank (A.comap f) (B.comap f) = relfinrank A B := by simpa using congr(toNat $(lift_relrank_comap_comap_eq_lift_relrank_of_surjective A B f h)) variable {A B} in theorem relrank_dvd_rank_top_of_le (h : A ≤ B) : relrank A B ∣ Module.rank A E := dvd_of_mul_right_eq _ (relrank_mul_rank_top h) variable {A B} in theorem relfinrank_dvd_finrank_top_of_le (h : A ≤ B) : relfinrank A B ∣ finrank A E := dvd_of_mul_right_eq _ (relfinrank_mul_finrank_top h) variable {A B C} in theorem relrank_mul_relrank (h1 : A ≤ B) (h2 : B ≤ C) : relrank A B * relrank B C = relrank A C := by have h3 := h1.trans h2 rw [relrank_eq_rank_of_le h1, relrank_eq_rank_of_le h2, relrank_eq_rank_of_le h3] letI : Algebra A B := (inclusion h1).toAlgebra letI : Algebra B C := (inclusion h2).toAlgebra letI : Algebra A C := (inclusion h3).toAlgebra haveI : IsScalarTower A B C := IsScalarTower.of_algebraMap_eq' rfl exact rank_mul_rank A B C variable {A B C} in theorem relfinrank_mul_relfinrank (h1 : A ≤ B) (h2 : B ≤ C) : relfinrank A B * relfinrank B C = relfinrank A C := by simpa using congr(toNat $(relrank_mul_relrank h1 h2)) theorem relrank_inf_mul_relrank : A.relrank (B ⊓ C) * B.relrank C = (A ⊓ B).relrank C := by rw [← inf_relrank_right A (B ⊓ C), ← inf_relrank_right B C, ← inf_relrank_right (A ⊓ B) C, inf_assoc, relrank_mul_relrank inf_le_right inf_le_right] theorem relfinrank_inf_mul_relfinrank : A.relfinrank (B ⊓ C) * B.relfinrank C = (A ⊓ B).relfinrank C := by simpa using congr(toNat $(relrank_inf_mul_relrank A B C)) variable {B C} in theorem relrank_mul_relrank_eq_inf_relrank (h : B ≤ C) : relrank A B * relrank B C = (A ⊓ B).relrank C := by simpa only [inf_of_le_left h] using relrank_inf_mul_relrank A B C variable {B C} in theorem relfinrank_mul_relfinrank_eq_inf_relfinrank (h : B ≤ C) : relfinrank A B * relfinrank B C = (A ⊓ B).relfinrank C := by simpa using congr(toNat $(relrank_mul_relrank_eq_inf_relrank A h)) variable {A B} in theorem relrank_inf_mul_relrank_of_le (h : A ≤ B) : A.relrank (B ⊓ C) * B.relrank C = A.relrank C := by simpa only [inf_of_le_left h] using relrank_inf_mul_relrank A B C variable {A B} in theorem relfinrank_inf_mul_relfinrank_of_le (h : A ≤ B) : A.relfinrank (B ⊓ C) * B.relfinrank C = A.relfinrank C := by simpa using congr(toNat $(relrank_inf_mul_relrank_of_le C h)) variable {A B} in theorem relrank_dvd_of_le_left (h : A ≤ B) : B.relrank C ∣ A.relrank C := dvd_of_mul_left_eq _ (relrank_inf_mul_relrank_of_le C h) variable {A B} in theorem relfinrank_dvd_of_le_left (h : A ≤ B) : B.relfinrank C ∣ A.relfinrank C := dvd_of_mul_left_eq _ (relfinrank_inf_mul_relfinrank_of_le C h) end Subfield namespace IntermediateField variable {F : Type u} {E : Type v} [Field F] [Field E] [Algebra F E] variable {L : Type w} [Field L] [Algebra F L] variable (A B C : IntermediateField F E) /-- `IntermediateField.relrank A B` is defined to be `[B : A ⊓ B]` as a `Cardinal`, in particular, when `A ≤ B` it is `[B : A]`, the degree of the field extension `B / A`. This is similar to `Subgroup.relindex` but it is `Cardinal` valued. -/ noncomputable def relrank := A.toSubfield.relrank B.toSubfield /-- The `Nat` version of `IntermediateField.relrank`. If `B / A ⊓ B` is an infinite extension, then it is zero. -/ noncomputable def relfinrank := A.toSubfield.relfinrank B.toSubfield theorem relfinrank_eq_toNat_relrank : relfinrank A B = toNat (relrank A B) := rfl variable {A B C} theorem relrank_eq_of_inf_eq (h : A ⊓ C = B ⊓ C) : relrank A C = relrank B C := Subfield.relrank_eq_of_inf_eq congr(toSubfield $h) theorem relfinrank_eq_of_inf_eq (h : A ⊓ C = B ⊓ C) : relfinrank A C = relfinrank B C := congr(toNat $(relrank_eq_of_inf_eq h)) /-- If `A ≤ B`, then `IntermediateField.relrank A B` is `[B : A]` -/ theorem relrank_eq_rank_of_le (h : A ≤ B) : relrank A B = Module.rank A (extendScalars h) := Subfield.relrank_eq_rank_of_le h /-- If `A ≤ B`, then `IntermediateField.relrank A B` is `[B : A]` -/ theorem relfinrank_eq_finrank_of_le (h : A ≤ B) : relfinrank A B = finrank A (extendScalars h) := congr(toNat $(relrank_eq_rank_of_le h)) variable (A B C) theorem inf_relrank_right : relrank (A ⊓ B) B = relrank A B := relrank_eq_rank_of_le (inf_le_right : A ⊓ B ≤ B) theorem inf_relfinrank_right : relfinrank (A ⊓ B) B = relfinrank A B := congr(toNat $(inf_relrank_right A B)) theorem inf_relrank_left : relrank (A ⊓ B) A = relrank B A := by rw [inf_comm, inf_relrank_right] theorem inf_relfinrank_left : relfinrank (A ⊓ B) A = relfinrank B A := congr(toNat $(inf_relrank_left A B)) @[simp] theorem relrank_self : relrank A A = 1 := A.toSubfield.relrank_self @[simp] theorem relfinrank_self : relfinrank A A = 1 := A.toSubfield.relfinrank_self variable {A B} in theorem relrank_eq_one_of_le (h : B ≤ A) : relrank A B = 1 := by rw [← inf_relrank_right, inf_eq_right.2 h, relrank_self] variable {A B} in theorem relfinrank_eq_one_of_le (h : B ≤ A) : relfinrank A B = 1 := by simp [relfinrank_eq_toNat_relrank, relrank_eq_one_of_le h] theorem lift_rank_comap (f : L →ₐ[F] E) : Cardinal.lift.{v} (Module.rank (A.comap f) L) = Cardinal.lift.{w} (relrank A f.fieldRange) := A.toSubfield.lift_rank_comap f.toRingHom theorem rank_comap {L : Type v} [Field L] [Algebra F L] (f : L →ₐ[F] E) : Module.rank (A.comap f) L = relrank A f.fieldRange := by simpa only [lift_id] using A.lift_rank_comap f theorem finrank_comap (f : L →ₐ[F] E) : finrank (A.comap f) L = relfinrank A f.fieldRange := by simpa using congr(toNat $(lift_rank_comap A f)) theorem lift_relrank_comap (f : L →ₐ[F] E) (B : IntermediateField F L) : Cardinal.lift.{v} (relrank (A.comap f) B) = Cardinal.lift.{w} (relrank A (B.map f)) := A.toSubfield.lift_relrank_comap f.toRingHom B.toSubfield theorem relrank_comap {L : Type v} [Field L] [Algebra F L] (f : L →ₐ[F] E) (B : IntermediateField F L) : relrank (A.comap f) B = relrank A (B.map f) := by simpa only [lift_id] using A.lift_relrank_comap f B theorem relfinrank_comap (f : L →ₐ[F] E) (B : IntermediateField F L) : relfinrank (A.comap f) B = relfinrank A (B.map f) := by simpa using congr(toNat $(lift_relrank_comap A f B)) theorem lift_relrank_map_map (f : E →ₐ[F] L) : Cardinal.lift.{v} (relrank (A.map f) (B.map f)) = Cardinal.lift.{w} (relrank A B) := by rw [← lift_relrank_comap, comap_map] theorem relrank_map_map {L : Type v} [Field L] [Algebra F L] (f : E →ₐ[F] L) : relrank (A.map f) (B.map f) = relrank A B := by simpa only [lift_id] using lift_relrank_map_map A B f theorem relfinrank_map_map (f : E →ₐ[F] L) : relfinrank (A.map f) (B.map f) = relfinrank A B := by simpa using congr(toNat $(lift_relrank_map_map A B f)) theorem lift_relrank_comap_comap_eq_lift_relrank_inf (f : L →ₐ[F] E) : Cardinal.lift.{v} (relrank (A.comap f) (B.comap f)) = Cardinal.lift.{w} (relrank A (B ⊓ f.fieldRange)) := A.toSubfield.lift_relrank_comap_comap_eq_lift_relrank_inf B.toSubfield f.toRingHom theorem relrank_comap_comap_eq_relrank_inf {L : Type v} [Field L] [Algebra F L] (f : L →ₐ[F] E) : relrank (A.comap f) (B.comap f) = relrank A (B ⊓ f.fieldRange) := by simpa only [lift_id] using lift_relrank_comap_comap_eq_lift_relrank_inf A B f theorem relfinrank_comap_comap_eq_relfinrank_inf (f : L →ₐ[F] E) : relfinrank (A.comap f) (B.comap f) = relfinrank A (B ⊓ f.fieldRange) := by simpa using congr(toNat $(lift_relrank_comap_comap_eq_lift_relrank_inf A B f)) theorem lift_relrank_comap_comap_eq_lift_relrank_of_le (f : L →ₐ[F] E) (h : B ≤ f.fieldRange) : Cardinal.lift.{v} (relrank (A.comap f) (B.comap f)) = Cardinal.lift.{w} (relrank A B) := by simpa only [inf_of_le_left h] using lift_relrank_comap_comap_eq_lift_relrank_inf A B f theorem relrank_comap_comap_eq_relrank_of_le {L : Type v} [Field L] [Algebra F L] (f : L →ₐ[F] E) (h : B ≤ f.fieldRange) : relrank (A.comap f) (B.comap f) = relrank A B := by simpa only [lift_id] using lift_relrank_comap_comap_eq_lift_relrank_of_le A B f h theorem relfinrank_comap_comap_eq_relfinrank_of_le (f : L →ₐ[F] E) (h : B ≤ f.fieldRange) : relfinrank (A.comap f) (B.comap f) = relfinrank A B := by simpa using congr(toNat $(lift_relrank_comap_comap_eq_lift_relrank_of_le A B f h)) theorem lift_relrank_comap_comap_eq_lift_relrank_of_surjective (f : L →ₐ[F] E) (h : Function.Surjective f) : Cardinal.lift.{v} (relrank (A.comap f) (B.comap f)) = Cardinal.lift.{w} (relrank A B) := lift_relrank_comap_comap_eq_lift_relrank_of_le A B f fun x _ ↦ h x theorem relrank_comap_comap_eq_relrank_of_surjective {L : Type v} [Field L] [Algebra F L] (f : L →ₐ[F] E) (h : Function.Surjective f) : relrank (A.comap f) (B.comap f) = relrank A B := by simpa using lift_relrank_comap_comap_eq_lift_relrank_of_surjective A B f h theorem relfinrank_comap_comap_eq_relfinrank_of_surjective (f : L →ₐ[F] E) (h : Function.Surjective f) : relfinrank (A.comap f) (B.comap f) = relfinrank A B := by simpa using congr(toNat $(lift_relrank_comap_comap_eq_lift_relrank_of_surjective A B f h)) variable {A B} in theorem relrank_mul_rank_top (h : A ≤ B) : relrank A B * Module.rank B E = Module.rank A E := Subfield.relrank_mul_rank_top h variable {A B} in theorem relfinrank_mul_finrank_top (h : A ≤ B) : relfinrank A B * finrank B E = finrank A E := by simpa using congr(toNat $(relrank_mul_rank_top h)) variable {A B} in theorem rank_bot_mul_relrank (h : A ≤ B) : Module.rank F A * relrank A B = Module.rank F B := by rw [relrank_eq_rank_of_le h] letI : Algebra A B := (inclusion h).toAlgebra haveI : IsScalarTower F A B := IsScalarTower.of_algebraMap_eq' rfl exact rank_mul_rank F A B variable {A B} in theorem finrank_bot_mul_relfinrank (h : A ≤ B) : finrank F A * relfinrank A B = finrank F B := by simpa using congr(toNat $(rank_bot_mul_relrank h)) variable {A B} in theorem relrank_dvd_rank_top_of_le (h : A ≤ B) : relrank A B ∣ Module.rank A E := dvd_of_mul_right_eq _ (relrank_mul_rank_top h) variable {A B} in theorem relfinrank_dvd_finrank_top_of_le (h : A ≤ B) : relfinrank A B ∣ finrank A E := dvd_of_mul_right_eq _ (relfinrank_mul_finrank_top h) theorem relrank_dvd_rank_bot : relrank A B ∣ Module.rank F B := inf_relrank_right A B ▸ dvd_of_mul_left_eq _ (rank_bot_mul_relrank inf_le_right) theorem relfinrank_dvd_finrank_bot : relfinrank A B ∣ finrank F B := inf_relfinrank_right A B ▸ dvd_of_mul_left_eq _ (finrank_bot_mul_relfinrank inf_le_right) variable {A B C} in theorem relrank_mul_relrank (h1 : A ≤ B) (h2 : B ≤ C) : relrank A B * relrank B C = relrank A C := Subfield.relrank_mul_relrank h1 h2 variable {A B C} in theorem relfinrank_mul_relfinrank (h1 : A ≤ B) (h2 : B ≤ C) : relfinrank A B * relfinrank B C = relfinrank A C := by simpa using congr(toNat $(relrank_mul_relrank h1 h2)) theorem relrank_inf_mul_relrank : A.relrank (B ⊓ C) * B.relrank C = (A ⊓ B).relrank C := Subfield.relrank_inf_mul_relrank A.toSubfield B.toSubfield C.toSubfield theorem relfinrank_inf_mul_relfinrank : A.relfinrank (B ⊓ C) * B.relfinrank C = (A ⊓ B).relfinrank C := by simpa using congr(toNat $(relrank_inf_mul_relrank A B C)) variable {B C} in theorem relrank_mul_relrank_eq_inf_relrank (h : B ≤ C) : relrank A B * relrank B C = (A ⊓ B).relrank C := by simpa only [inf_of_le_left h] using relrank_inf_mul_relrank A B C variable {B C} in theorem relfinrank_mul_relfinrank_eq_inf_relfinrank (h : B ≤ C) : relfinrank A B * relfinrank B C = (A ⊓ B).relfinrank C := by simpa using congr(toNat $(relrank_mul_relrank_eq_inf_relrank A h)) variable {A B} in theorem relrank_inf_mul_relrank_of_le (h : A ≤ B) : A.relrank (B ⊓ C) * B.relrank C = A.relrank C := by simpa only [inf_of_le_left h] using relrank_inf_mul_relrank A B C variable {A B} in theorem relfinrank_inf_mul_relfinrank_of_le (h : A ≤ B) : A.relfinrank (B ⊓ C) * B.relfinrank C = A.relfinrank C := by simpa using congr(toNat $(relrank_inf_mul_relrank_of_le C h)) @[simp] theorem relrank_top_left : relrank ⊤ A = 1 := relrank_eq_one_of_le le_top @[simp] theorem relfinrank_top_left : relfinrank ⊤ A = 1 := relfinrank_eq_one_of_le le_top @[simp] theorem relrank_top_right : relrank A ⊤ = Module.rank A E := by rw [← relrank_mul_rank_top (show A ≤ ⊤ from le_top), IntermediateField.rank_top, mul_one] @[simp] theorem relfinrank_top_right : relfinrank A ⊤ = finrank A E := by simp [relfinrank_eq_toNat_relrank, finrank] @[simp] theorem relrank_bot_left : relrank ⊥ A = Module.rank F A := by rw [← rank_bot_mul_relrank (show ⊥ ≤ A from bot_le), IntermediateField.rank_bot, one_mul] @[simp] theorem relfinrank_bot_left : relfinrank ⊥ A = finrank F A := by simp [relfinrank_eq_toNat_relrank, finrank] @[simp] theorem relrank_bot_right : relrank A ⊥ = 1 := relrank_eq_one_of_le bot_le @[simp] theorem relfinrank_bot_right : relfinrank A ⊥ = 1 := relfinrank_eq_one_of_le bot_le variable {A B} in theorem relrank_dvd_of_le_left (h : A ≤ B) : B.relrank C ∣ A.relrank C := dvd_of_mul_left_eq _ (relrank_inf_mul_relrank_of_le C h) variable {A B} in theorem relfinrank_dvd_of_le_left (h : A ≤ B) : B.relfinrank C ∣ A.relfinrank C := dvd_of_mul_left_eq _ (relfinrank_inf_mul_relfinrank_of_le C h) end IntermediateField
Dini.lean
/- Copyright (c) 2024 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.Normed.Order.Lattice import Mathlib.Topology.ContinuousMap.Ordered import Mathlib.Topology.UniformSpace.CompactConvergence /-! # Dini's Theorem This file proves Dini's theorem, which states that if `F n` is a monotone increasing sequence of continuous real-valued functions on a compact set `s` converging pointwise to a continuous function `f`, then `F n` converges uniformly to `f`. We generalize the codomain from `ℝ` to a normed lattice additive commutative group `G`. This theorem is true in a different generality as well: when `G` is a linearly ordered topological group with the order topology. This weakens the norm assumption, in exchange for strengthening to a linear order. This separate generality is not included in this file, but that generality was included in initial drafts of the original [PR #19068](https://github.com/leanprover-community/mathlib4/pull/19068) and can be recovered if necessary. The key idea of the proof is to use a particular basis of `𝓝 0` which consists of open sets that are somehow monotone in the sense that if `s` is in the basis, and `0 ≤ x ≤ y`, then `y ∈ s → x ∈ s`, and so the proof would work on any topological ordered group possessing such a basis. In the case of a linearly ordered topological group with the order topology, this basis is `nhds_basis_Ioo`. In the case of a normed lattice additive commutative group, this basis is `nhds_basis_ball`, and the fact that this basis satisfies the monotonicity criterion corresponds to `HasSolidNorm`. -/ open Filter Topology variable {ι α G : Type*} [Preorder ι] [TopologicalSpace α] [NormedAddCommGroup G] [Lattice G] [HasSolidNorm G] [IsOrderedAddMonoid G] section Unbundled open Metric variable {F : ι → α → G} {f : α → G} namespace Monotone /-- **Dini's theorem**: if `F n` is a monotone increasing collection of continuous functions converging pointwise to a continuous function `f`, then `F n` converges locally uniformly to `f`. -/ lemma tendstoLocallyUniformly_of_forall_tendsto (hF_cont : ∀ i, Continuous (F i)) (hF_mono : Monotone F) (hf : Continuous f) (h_tendsto : ∀ x, Tendsto (F · x) atTop (𝓝 (f x))) : TendstoLocallyUniformly F f atTop := by refine (atTop : Filter ι).eq_or_neBot.elim (fun h ↦ ?eq_bot) (fun _ ↦ ?_) case eq_bot => simp [h, tendstoLocallyUniformly_iff_forall_tendsto] have F_le_f (x : α) (n : ι) : F n x ≤ f x := by refine ge_of_tendsto (h_tendsto x) ?_ filter_upwards [Ici_mem_atTop n] with m hnm exact hF_mono hnm x simp_rw [Metric.tendstoLocallyUniformly_iff, dist_eq_norm'] intro ε ε_pos x simp_rw +singlePass [tendsto_iff_norm_sub_tendsto_zero] at h_tendsto obtain ⟨n, hn⟩ := (h_tendsto x).eventually (eventually_lt_nhds ε_pos) |>.exists refine ⟨{y | ‖F n y - f y‖ < ε}, ⟨isOpen_lt (by fun_prop) continuous_const |>.mem_nhds hn, ?_⟩⟩ filter_upwards [eventually_ge_atTop n] with m hnm z hz refine norm_le_norm_of_abs_le_abs ?_ |>.trans_lt hz simp only [abs_of_nonpos (sub_nonpos_of_le (F_le_f _ _)), neg_sub, sub_le_sub_iff_left] exact hF_mono hnm z /-- **Dini's theorem**: if `F n` is a monotone increasing collection of continuous functions on a set `s` converging pointwise to a continuous function `f`, then `F n` converges locally uniformly to `f`. -/ lemma tendstoLocallyUniformlyOn_of_forall_tendsto {s : Set α} (hF_cont : ∀ i, ContinuousOn (F i) s) (hF_mono : ∀ x ∈ s, Monotone (F · x)) (hf : ContinuousOn f s) (h_tendsto : ∀ x ∈ s, Tendsto (F · x) atTop (𝓝 (f x))) : TendstoLocallyUniformlyOn F f atTop s := by rw [tendstoLocallyUniformlyOn_iff_tendstoLocallyUniformly_comp_coe] exact tendstoLocallyUniformly_of_forall_tendsto (hF_cont · |>.restrict) (fun _ _ h x ↦ hF_mono _ x.2 h) hf.restrict (fun x ↦ h_tendsto x x.2) /-- **Dini's theorem**: if `F n` is a monotone increasing collection of continuous functions on a compact space converging pointwise to a continuous function `f`, then `F n` converges uniformly to `f`. -/ lemma tendstoUniformly_of_forall_tendsto [CompactSpace α] (hF_cont : ∀ i, Continuous (F i)) (hF_mono : Monotone F) (hf : Continuous f) (h_tendsto : ∀ x, Tendsto (F · x) atTop (𝓝 (f x))) : TendstoUniformly F f atTop := tendstoLocallyUniformly_iff_tendstoUniformly_of_compactSpace.mp <| tendstoLocallyUniformly_of_forall_tendsto hF_cont hF_mono hf h_tendsto /-- **Dini's theorem**: if `F n` is a monotone increasing collection of continuous functions on a compact set `s` converging pointwise to a continuous function `f`, then `F n` converges uniformly to `f`. -/ lemma tendstoUniformlyOn_of_forall_tendsto {s : Set α} (hs : IsCompact s) (hF_cont : ∀ i, ContinuousOn (F i) s) (hF_mono : ∀ x ∈ s, Monotone (F · x)) (hf : ContinuousOn f s) (h_tendsto : ∀ x ∈ s, Tendsto (F · x) atTop (𝓝 (f x))) : TendstoUniformlyOn F f atTop s := tendstoLocallyUniformlyOn_iff_tendstoUniformlyOn_of_compact hs |>.mp <| tendstoLocallyUniformlyOn_of_forall_tendsto hF_cont hF_mono hf h_tendsto end Monotone namespace Antitone /-- **Dini's theorem**: if `F n` is a monotone decreasing collection of continuous functions on a converging pointwise to a continuous function `f`, then `F n` converges locally uniformly to `f`. -/ lemma tendstoLocallyUniformly_of_forall_tendsto (hF_cont : ∀ i, Continuous (F i)) (hF_anti : Antitone F) (hf : Continuous f) (h_tendsto : ∀ x, Tendsto (F · x) atTop (𝓝 (f x))) : TendstoLocallyUniformly F f atTop := Monotone.tendstoLocallyUniformly_of_forall_tendsto (G := Gᵒᵈ) hF_cont hF_anti hf h_tendsto /-- **Dini's theorem**: if `F n` is a monotone decreasing collection of continuous functions on a set `s` converging pointwise to a continuous function `f`, then `F n` converges locally uniformly to `f`. -/ lemma tendstoLocallyUniformlyOn_of_forall_tendsto {s : Set α} (hF_cont : ∀ i, ContinuousOn (F i) s) (hF_anti : ∀ x ∈ s, Antitone (F · x)) (hf : ContinuousOn f s) (h_tendsto : ∀ x ∈ s, Tendsto (F · x) atTop (𝓝 (f x))) : TendstoLocallyUniformlyOn F f atTop s := Monotone.tendstoLocallyUniformlyOn_of_forall_tendsto (G := Gᵒᵈ) hF_cont hF_anti hf h_tendsto /-- **Dini's theorem**: if `F n` is a monotone decreasing collection of continuous functions on a compact space converging pointwise to a continuous function `f`, then `F n` converges uniformly to `f`. -/ lemma tendstoUniformly_of_forall_tendsto [CompactSpace α] (hF_cont : ∀ i, Continuous (F i)) (hF_anti : Antitone F) (hf : Continuous f) (h_tendsto : ∀ x, Tendsto (F · x) atTop (𝓝 (f x))) : TendstoUniformly F f atTop := Monotone.tendstoUniformly_of_forall_tendsto (G := Gᵒᵈ) hF_cont hF_anti hf h_tendsto /-- **Dini's theorem**: if `F n` is a monotone decreasing collection of continuous functions on a compact set `s` converging pointwise to a continuous `f`, then `F n` converges uniformly to `f`. -/ lemma tendstoUniformlyOn_of_forall_tendsto {s : Set α} (hs : IsCompact s) (hF_cont : ∀ i, ContinuousOn (F i) s) (hF_anti : ∀ x ∈ s, Antitone (F · x)) (hf : ContinuousOn f s) (h_tendsto : ∀ x ∈ s, Tendsto (F · x) atTop (𝓝 (f x))) : TendstoUniformlyOn F f atTop s := Monotone.tendstoUniformlyOn_of_forall_tendsto (G := Gᵒᵈ) hs hF_cont hF_anti hf h_tendsto end Antitone end Unbundled namespace ContinuousMap variable {F : ι → C(α, G)} {f : C(α, G)} /-- **Dini's theorem**: if `F n` is a monotone increasing collection of continuous functions converging pointwise to a continuous function `f`, then `F n` converges to `f` in the compact-open topology. -/ lemma tendsto_of_monotone_of_pointwise (hF_mono : Monotone F) (h_tendsto : ∀ x, Tendsto (F · x) atTop (𝓝 (f x))) : Tendsto F atTop (𝓝 f) := tendsto_of_tendstoLocallyUniformly <| hF_mono.tendstoLocallyUniformly_of_forall_tendsto (F · |>.continuous) f.continuous h_tendsto /-- **Dini's theorem**: if `F n` is a monotone decreasing collection of continuous functions converging pointwise to a continuous function `f`, then `F n` converges to `f` in the compact-open topology. -/ lemma tendsto_of_antitone_of_pointwise (hF_anti : Antitone F) (h_tendsto : ∀ x, Tendsto (F · x) atTop (𝓝 (f x))) : Tendsto F atTop (𝓝 f) := tendsto_of_monotone_of_pointwise (G := Gᵒᵈ) hF_anti h_tendsto end ContinuousMap
all_character.v
From mathcomp Require Export character. From mathcomp Require Export classfun. From mathcomp Require Export inertia. From mathcomp Require Export integral_char. From mathcomp Require Export mxabelem. From mathcomp Require Export mxrepresentation. From mathcomp Require Export vcharacter.
DominatedConvergence.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 -/ import Mathlib.MeasureTheory.Integral.Lebesgue.Markov import Mathlib.MeasureTheory.Integral.Lebesgue.Sub /-! # Dominated convergence theorem Lebesgue's dominated convergence theorem states that the limit and Lebesgue integral of a sequence of (almost everywhere) measurable functions can be swapped if the functions are pointwise dominated by a fixed function. This file provides a few variants of the result. -/ open Filter ENNReal Topology namespace MeasureTheory variable {α : Type*} [MeasurableSpace α] {μ : Measure α} theorem limsup_lintegral_le {f : ℕ → α → ℝ≥0∞} (g : α → ℝ≥0∞) (hf_meas : ∀ n, Measurable (f n)) (h_bound : ∀ n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ ≠ ∞) : limsup (fun n => ∫⁻ a, f n a ∂μ) atTop ≤ ∫⁻ a, limsup (fun n => f n a) atTop ∂μ := calc limsup (fun n => ∫⁻ a, f n a ∂μ) atTop = ⨅ n : ℕ, ⨆ i ≥ n, ∫⁻ a, f i a ∂μ := limsup_eq_iInf_iSup_of_nat _ ≤ ⨅ n : ℕ, ∫⁻ a, ⨆ i ≥ n, f i a ∂μ := iInf_mono fun _ => iSup₂_lintegral_le _ _ = ∫⁻ a, ⨅ n : ℕ, ⨆ i ≥ n, f i a ∂μ := by refine (lintegral_iInf ?_ ?_ ?_).symm · intro n exact .biSup _ (Set.to_countable _) (fun i _ ↦ hf_meas i) · intro n m hnm a exact iSup_le_iSup_of_subset fun i hi => le_trans hnm hi · refine ne_top_of_le_ne_top h_fin (lintegral_mono_ae ?_) refine (ae_all_iff.2 h_bound).mono fun n hn => ?_ exact iSup_le fun i => iSup_le fun _ => hn i _ = ∫⁻ a, limsup (fun n => f n a) atTop ∂μ := by simp only [limsup_eq_iInf_iSup_of_nat] /-- **Dominated convergence theorem** for nonnegative `Measurable` functions. -/ theorem tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀ n, Measurable (F n)) (h_bound : ∀ n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, Tendsto (fun n => F n a) atTop (𝓝 (f a))) : Tendsto (fun n => ∫⁻ a, F n a ∂μ) atTop (𝓝 (∫⁻ a, f a ∂μ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf (fun n : ℕ => F n a) atTop ∂μ := lintegral_congr_ae <| h_lim.mono fun _ h => h.liminf_eq.symm _ ≤ liminf (fun n => ∫⁻ a, F n a ∂μ) atTop := lintegral_liminf_le hF_meas) (calc limsup (fun n : ℕ => ∫⁻ a, F n a ∂μ) atTop ≤ ∫⁻ a, limsup (fun n => F n a) atTop ∂μ := limsup_lintegral_le _ hF_meas h_bound h_fin _ = ∫⁻ a, f a ∂μ := lintegral_congr_ae <| h_lim.mono fun _ h => h.limsup_eq) /-- **Dominated convergence theorem** for nonnegative `AEMeasurable` functions. -/ theorem tendsto_lintegral_of_dominated_convergence' {F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀ n, AEMeasurable (F n) μ) (h_bound : ∀ n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, Tendsto (fun n => F n a) atTop (𝓝 (f a))) : Tendsto (fun n => ∫⁻ a, F n a ∂μ) atTop (𝓝 (∫⁻ a, f a ∂μ)) := by have : ∀ n, ∫⁻ a, F n a ∂μ = ∫⁻ a, (hF_meas n).mk (F n) a ∂μ := fun n => lintegral_congr_ae (hF_meas n).ae_eq_mk simp_rw [this] apply tendsto_lintegral_of_dominated_convergence bound (fun n => (hF_meas n).measurable_mk) _ h_fin · have : ∀ n, ∀ᵐ a ∂μ, (hF_meas n).mk (F n) a = F n a := fun n => (hF_meas n).ae_eq_mk.symm have : ∀ᵐ a ∂μ, ∀ n, (hF_meas n).mk (F n) a = F n a := ae_all_iff.mpr this filter_upwards [this, h_lim] with a H H' simp_rw [H] exact H' · intro n filter_upwards [h_bound n, (hF_meas n).ae_eq_mk] with a H H' rwa [H'] at H /-- **Dominated convergence theorem** for filters with a countable basis. -/ theorem tendsto_lintegral_filter_of_dominated_convergence {ι} {l : Filter ι} [l.IsCountablyGenerated] {F : ι → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀ᶠ n in l, Measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, Tendsto (fun n => F n a) l (𝓝 (f a))) : Tendsto (fun n => ∫⁻ a, F n a ∂μ) l (𝓝 <| ∫⁻ a, f a ∂μ) := by rw [tendsto_iff_seq_tendsto] intro x xl have hxl := by rw [tendsto_atTop'] at xl exact xl have h := inter_mem hF_meas h_bound replace h := hxl _ h rcases h with ⟨k, h⟩ rw [← tendsto_add_atTop_iff_nat k] refine tendsto_lintegral_of_dominated_convergence ?_ ?_ ?_ ?_ ?_ · exact bound · intro refine (h _ ?_).1 exact Nat.le_add_left _ _ · intro refine (h _ ?_).2 exact Nat.le_add_left _ _ · assumption · refine h_lim.mono fun a h_lim => ?_ apply @Tendsto.comp _ _ _ (fun n => x (n + k)) fun n => F n a · assumption rw [tendsto_add_atTop_iff_nat] assumption /-- If a monotone sequence of functions has an upper bound and the sequence of integrals of these functions tends to the integral of the upper bound, then the sequence of functions converges almost everywhere to the upper bound. Auxiliary version assuming moreover that the functions in the sequence are ae measurable. -/ lemma tendsto_of_lintegral_tendsto_of_monotone_aux {α : Type*} {mα : MeasurableSpace α} {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} {μ : Measure α} (hf_meas : ∀ n, AEMeasurable (f n) μ) (hF_meas : AEMeasurable F μ) (hf_tendsto : Tendsto (fun i ↦ ∫⁻ a, f i a ∂μ) atTop (𝓝 (∫⁻ a, F a ∂μ))) (hf_mono : ∀ᵐ a ∂μ, Monotone (fun i ↦ f i a)) (h_bound : ∀ᵐ a ∂μ, ∀ i, f i a ≤ F a) (h_int_finite : ∫⁻ a, F a ∂μ ≠ ∞) : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F a)) := by have h_bound_finite : ∀ᵐ a ∂μ, F a ≠ ∞ := by filter_upwards [ae_lt_top' hF_meas h_int_finite] with a ha using ha.ne have h_exists : ∀ᵐ a ∂μ, ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) := by filter_upwards [h_bound, h_bound_finite, hf_mono] with a h_le h_fin h_mono have h_tendsto : Tendsto (fun i ↦ f i a) atTop atTop ∨ ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) := tendsto_of_monotone h_mono rcases h_tendsto with h_absurd | h_tendsto · rw [tendsto_atTop_atTop_iff_of_monotone h_mono] at h_absurd obtain ⟨i, hi⟩ := h_absurd (F a + 1) refine absurd (hi.trans (h_le _)) (not_le.mpr ?_) exact ENNReal.lt_add_right h_fin one_ne_zero · exact h_tendsto classical let F' : α → ℝ≥0∞ := fun a ↦ if h : ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) then h.choose else ∞ have hF'_tendsto : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F' a)) := by filter_upwards [h_exists] with a ha simp_rw [F', dif_pos ha] exact ha.choose_spec suffices F' =ᵐ[μ] F by filter_upwards [this, hF'_tendsto] with a h_eq h_tendsto using h_eq ▸ h_tendsto have hF'_le : F' ≤ᵐ[μ] F := by filter_upwards [h_bound, hF'_tendsto] with a h_le h_tendsto exact le_of_tendsto' h_tendsto (fun m ↦ h_le _) suffices ∫⁻ a, F' a ∂μ = ∫⁻ a, F a ∂μ from ae_eq_of_ae_le_of_lintegral_le hF'_le (this ▸ h_int_finite) hF_meas this.symm.le refine tendsto_nhds_unique ?_ hf_tendsto exact lintegral_tendsto_of_tendsto_of_monotone hf_meas hf_mono hF'_tendsto /-- If a monotone sequence of functions has an upper bound and the sequence of integrals of these functions tends to the integral of the upper bound, then the sequence of functions converges almost everywhere to the upper bound. -/ lemma tendsto_of_lintegral_tendsto_of_monotone {α : Type*} {mα : MeasurableSpace α} {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} {μ : Measure α} (hF_meas : AEMeasurable F μ) (hf_tendsto : Tendsto (fun i ↦ ∫⁻ a, f i a ∂μ) atTop (𝓝 (∫⁻ a, F a ∂μ))) (hf_mono : ∀ᵐ a ∂μ, Monotone (fun i ↦ f i a)) (h_bound : ∀ᵐ a ∂μ, ∀ i, f i a ≤ F a) (h_int_finite : ∫⁻ a, F a ∂μ ≠ ∞) : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F a)) := by have : ∀ n, ∃ g : α → ℝ≥0∞, Measurable g ∧ g ≤ f n ∧ ∫⁻ a, f n a ∂μ = ∫⁻ a, g a ∂μ := fun n ↦ exists_measurable_le_lintegral_eq _ _ choose g gmeas gf hg using this let g' : ℕ → α → ℝ≥0∞ := Nat.rec (g 0) (fun n I x ↦ max (g (n + 1) x) (I x)) have M n : Measurable (g' n) := by induction n with | zero => simp [g', gmeas 0] | succ n ih => exact Measurable.max (gmeas (n + 1)) ih have I : ∀ n x, g n x ≤ g' n x := by intro n x cases n with | zero | succ => simp [g'] have I' : ∀ᵐ x ∂μ, ∀ n, g' n x ≤ f n x := by filter_upwards [hf_mono] with x hx n induction n with | zero => simpa [g'] using gf 0 x | succ n ih => exact max_le (gf (n + 1) x) (ih.trans (hx (Nat.le_succ n))) have Int_eq n : ∫⁻ x, g' n x ∂μ = ∫⁻ x, f n x ∂μ := by apply le_antisymm · apply lintegral_mono_ae filter_upwards [I'] with x hx using hx n · rw [hg n] exact lintegral_mono (I n) have : ∀ᵐ a ∂μ, Tendsto (fun i ↦ g' i a) atTop (𝓝 (F a)) := by apply tendsto_of_lintegral_tendsto_of_monotone_aux _ hF_meas _ _ _ h_int_finite · exact fun n ↦ (M n).aemeasurable · simp_rw [Int_eq] exact hf_tendsto · exact Eventually.of_forall (fun x ↦ monotone_nat_of_le_succ (fun n ↦ le_max_right _ _)) · filter_upwards [h_bound, I'] with x h'x hx n using (hx n).trans (h'x n) filter_upwards [this, I', h_bound] with x hx h'x h''x exact tendsto_of_tendsto_of_tendsto_of_le_of_le hx tendsto_const_nhds h'x h''x /-- If an antitone sequence of functions has a lower bound and the sequence of integrals of these functions tends to the integral of the lower bound, then the sequence of functions converges almost everywhere to the lower bound. -/ lemma tendsto_of_lintegral_tendsto_of_antitone {α : Type*} {mα : MeasurableSpace α} {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} {μ : Measure α} (hf_meas : ∀ n, AEMeasurable (f n) μ) (hf_tendsto : Tendsto (fun i ↦ ∫⁻ a, f i a ∂μ) atTop (𝓝 (∫⁻ a, F a ∂μ))) (hf_mono : ∀ᵐ a ∂μ, Antitone (fun i ↦ f i a)) (h_bound : ∀ᵐ a ∂μ, ∀ i, F a ≤ f i a) (h0 : ∫⁻ a, f 0 a ∂μ ≠ ∞) : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F a)) := by have h_int_finite : ∫⁻ a, F a ∂μ ≠ ∞ := by refine ((lintegral_mono_ae ?_).trans_lt h0.lt_top).ne filter_upwards [h_bound] with a ha using ha 0 have h_exists : ∀ᵐ a ∂μ, ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) := by filter_upwards [hf_mono] with a h_mono rcases _root_.tendsto_of_antitone h_mono with h | h · refine ⟨0, h.mono_right ?_⟩ rw [OrderBot.atBot_eq] exact pure_le_nhds _ · exact h classical let F' : α → ℝ≥0∞ := fun a ↦ if h : ∃ l, Tendsto (fun i ↦ f i a) atTop (𝓝 l) then h.choose else ∞ have hF'_tendsto : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (F' a)) := by filter_upwards [h_exists] with a ha simp_rw [F', dif_pos ha] exact ha.choose_spec suffices F' =ᵐ[μ] F by filter_upwards [this, hF'_tendsto] with a h_eq h_tendsto using h_eq ▸ h_tendsto have hF'_le : F ≤ᵐ[μ] F' := by filter_upwards [h_bound, hF'_tendsto] with a h_le h_tendsto exact ge_of_tendsto' h_tendsto (fun m ↦ h_le _) suffices ∫⁻ a, F' a ∂μ = ∫⁻ a, F a ∂μ by refine (ae_eq_of_ae_le_of_lintegral_le hF'_le h_int_finite ?_ this.le).symm exact ENNReal.aemeasurable_of_tendsto hf_meas hF'_tendsto refine tendsto_nhds_unique ?_ hf_tendsto exact lintegral_tendsto_of_tendsto_of_antitone hf_meas hf_mono h0 hF'_tendsto end MeasureTheory
Sheafification.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.Category.ModuleCat.Presheaf.Abelian import Mathlib.Algebra.Category.ModuleCat.Presheaf.Sheafify import Mathlib.Algebra.Category.ModuleCat.Presheaf.Limits import Mathlib.Algebra.Category.ModuleCat.Sheaf.Limits import Mathlib.CategoryTheory.Sites.LocallyBijective import Mathlib.CategoryTheory.Sites.Sheafification import Mathlib.CategoryTheory.Functor.ReflectsIso.Balanced /-! # The sheafification functor for presheaves of modules In this file, we construct a functor `PresheafOfModules.sheafification α : PresheafOfModules R₀ ⥤ SheafOfModules R` for a locally bijective morphism `α : R₀ ⟶ R.val` where `R₀` is a presheaf of rings and `R` a sheaf of rings. In particular, if `α` is the identity of `R.val`, we obtain the sheafification functor `PresheafOfModules R.val ⥤ SheafOfModules R`. -/ universe v v' u u' open CategoryTheory Category Limits variable {C : Type u'} [Category.{v'} C] {J : GrothendieckTopology C} {R₀ : Cᵒᵖ ⥤ RingCat.{u}} {R : Sheaf J RingCat.{u}} (α : R₀ ⟶ R.val) [Presheaf.IsLocallyInjective J α] [Presheaf.IsLocallySurjective J α] [J.WEqualsLocallyBijective AddCommGrp.{v}] namespace PresheafOfModules section variable [HasWeakSheafify J AddCommGrp.{v}] /-- Given a locally bijective morphism `α : R₀ ⟶ R.val` where `R₀` is a presheaf of rings and `R` a sheaf of rings (i.e. `R` identifies to the sheafification of `R₀`), this is the associated sheaf of modules functor `PresheafOfModules.{v} R₀ ⥤ SheafOfModules.{v} R`. -/ @[simps! -isSimp map] noncomputable def sheafification : PresheafOfModules.{v} R₀ ⥤ SheafOfModules.{v} R where obj M₀ := sheafify α (CategoryTheory.toSheafify J M₀.presheaf) map f := sheafifyMap _ _ _ f ((toPresheaf R₀ ⋙ presheafToSheaf J AddCommGrp).map f) (by apply toSheafify_naturality) map_id M₀ := by ext1 apply (toPresheaf _).map_injective simp rfl map_comp _ _ := by ext1 apply (toPresheaf _).map_injective simp rfl /-- The sheafification of presheaves of modules commutes with the functor which forgets the module structures. -/ noncomputable def sheafificationCompToSheaf : sheafification.{v} α ⋙ SheafOfModules.toSheaf _ ≅ toPresheaf _ ⋙ presheafToSheaf J AddCommGrp := Iso.refl _ /-- The sheafification of presheaves of modules commutes with the functor which forgets the module structures. -/ noncomputable def sheafificationCompForgetCompToPresheaf : sheafification.{v} α ⋙ SheafOfModules.forget _ ⋙ toPresheaf _ ≅ toPresheaf _ ⋙ presheafToSheaf J AddCommGrp ⋙ sheafToPresheaf J AddCommGrp := Iso.refl _ /-- The bijection between types of morphisms which is part of the adjunction `sheafificationAdjunction`. -/ noncomputable def sheafificationHomEquiv {P : PresheafOfModules.{v} R₀} {F : SheafOfModules.{v} R} : ((sheafification α).obj P ⟶ F) ≃ (P ⟶ (restrictScalars α).obj ((SheafOfModules.forget _).obj F)) := by apply sheafifyHomEquiv lemma toPresheaf_map_sheafificationHomEquiv_def {P : PresheafOfModules.{v} R₀} {F : SheafOfModules.{v} R} (f : (sheafification α).obj P ⟶ F) : (toPresheaf R₀).map (sheafificationHomEquiv α f) = CategoryTheory.toSheafify J P.presheaf ≫ (toPresheaf R.val).map f.val := rfl lemma toPresheaf_map_sheafificationHomEquiv {P : PresheafOfModules.{v} R₀} {F : SheafOfModules.{v} R} (f : (sheafification α).obj P ⟶ F) : (toPresheaf R₀).map (sheafificationHomEquiv α f) = (sheafificationAdjunction J AddCommGrp).homEquiv P.presheaf ((SheafOfModules.toSheaf _).obj F) ((SheafOfModules.toSheaf _).map f) := by rw [toPresheaf_map_sheafificationHomEquiv_def, Adjunction.homEquiv_unit] dsimp lemma toSheaf_map_sheafificationHomEquiv_symm {P : PresheafOfModules.{v} R₀} {F : SheafOfModules.{v} R} (g : P ⟶ (restrictScalars α).obj ((SheafOfModules.forget _).obj F)) : (SheafOfModules.toSheaf _).map ((sheafificationHomEquiv α).symm g) = (((sheafificationAdjunction J AddCommGrp).homEquiv P.presheaf ((SheafOfModules.toSheaf R).obj F)).symm ((toPresheaf R₀).map g)) := by obtain ⟨f, rfl⟩ := (sheafificationHomEquiv α).surjective g apply ((sheafificationAdjunction J AddCommGrp).homEquiv _ _).injective rw [Equiv.apply_symm_apply, Adjunction.homEquiv_unit, Equiv.symm_apply_apply] rfl /-- Given a locally bijective morphism `α : R₀ ⟶ R.val` where `R₀` is a presheaf of rings and `R` a sheaf of rings, this is the adjunction `sheafification.{v} α ⊣ SheafOfModules.forget R ⋙ restrictScalars α`. -/ noncomputable def sheafificationAdjunction : sheafification.{v} α ⊣ SheafOfModules.forget R ⋙ restrictScalars α := Adjunction.mkOfHomEquiv { homEquiv := fun _ _ ↦ sheafificationHomEquiv α homEquiv_naturality_left_symm := fun {P₀ Q₀ N} f g ↦ by apply (SheafOfModules.toSheaf _).map_injective rw [Functor.map_comp] erw [toSheaf_map_sheafificationHomEquiv_symm, toSheaf_map_sheafificationHomEquiv_symm α g] rw [Functor.map_comp] apply (CategoryTheory.sheafificationAdjunction J AddCommGrp.{v}).homEquiv_naturality_left_symm homEquiv_naturality_right := fun {P₀ M N} f g ↦ by apply (toPresheaf _).map_injective erw [toPresheaf_map_sheafificationHomEquiv] } lemma sheafificationAdjunction_homEquiv_apply {P : PresheafOfModules.{v} R₀} {F : SheafOfModules.{v} R} (f : (sheafification α).obj P ⟶ F) : (sheafificationAdjunction α).homEquiv P F f = sheafificationHomEquiv α f := rfl @[simp] lemma toPresheaf_map_sheafificationAdjunction_unit_app (M₀ : PresheafOfModules.{v} R₀) : (toPresheaf _).map ((sheafificationAdjunction α).unit.app M₀) = CategoryTheory.toSheafify J M₀.presheaf := rfl instance : (sheafification.{v} α).IsLeftAdjoint := (sheafificationAdjunction α).isLeftAdjoint end section variable [HasSheafify J AddCommGrp.{v}] noncomputable instance : PreservesFiniteLimits (sheafification.{v} α ⋙ SheafOfModules.toSheaf.{v} R) := comp_preservesFiniteLimits (toPresheaf.{v} R₀) (presheafToSheaf J AddCommGrp) instance : (SheafOfModules.toSheaf.{v} R ⋙ sheafToPresheaf _ _).ReflectsIsomorphisms := inferInstanceAs (SheafOfModules.forget.{v} R ⋙ toPresheaf _).ReflectsIsomorphisms instance : (SheafOfModules.toSheaf.{v} R).ReflectsIsomorphisms := reflectsIsomorphisms_of_comp (SheafOfModules.toSheaf.{v} R) (sheafToPresheaf J _) noncomputable instance : ReflectsFiniteLimits (SheafOfModules.toSheaf.{v} R) where reflects _ _ _ := inferInstance noncomputable instance : PreservesFiniteLimits (sheafification.{v} α) := preservesFiniteLimits_of_reflects_of_preserves (sheafification.{v} α) (SheafOfModules.toSheaf.{v} R) end end PresheafOfModules
Imo2008Q4.lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales -/ import Mathlib.Data.Real.Basic import Mathlib.Data.Real.Sqrt import Mathlib.Data.NNReal.Basic import Mathlib.Tactic.LinearCombination /-! # IMO 2008 Q4 Find all functions `f : (0,∞) → (0,∞)` (so, `f` is a function from the positive real numbers to the positive real numbers) such that ``` (f(w)^2 + f(x)^2)/(f(y^2) + f(z^2)) = (w^2 + x^2)/(y^2 + z^2) ``` for all positive real numbers `w`, `x`, `y`, `z`, satisfying `wx = yz`. # Solution The desired theorem is that either `f = fun x => x` or `f = fun x => 1/x` -/ open Real namespace Imo2008Q4 theorem abs_eq_one_of_pow_eq_one (x : ℝ) (n : ℕ) (hn : n ≠ 0) (h : x ^ n = 1) : |x| = 1 := by rw [← pow_left_inj₀ (abs_nonneg x) zero_le_one hn, one_pow, pow_abs, h, abs_one] end Imo2008Q4 open Imo2008Q4 theorem imo2008_q4 (f : ℝ → ℝ) (H₁ : ∀ x > 0, f x > 0) : (∀ w x y z : ℝ, 0 < w → 0 < x → 0 < y → 0 < z → w * x = y * z → (f w ^ 2 + f x ^ 2) / (f (y ^ 2) + f (z ^ 2)) = (w ^ 2 + x ^ 2) / (y ^ 2 + z ^ 2)) ↔ (∀ x > 0, f x = x) ∨ ∀ x > 0, f x = 1 / x := by constructor; swap -- proof that f(x) = x and f(x) = 1/x satisfy the condition · rintro (h | h) · intro w x y z hw hx hy hz _ rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)] · intro w x y z hw hx hy hz hprod rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)] have hp2 : w ^ 2 * x ^ 2 = y ^ 2 * z ^ 2 := by linear_combination (w * x + y * z) * hprod field_simp [hp2] ring -- proof that the only solutions are f(x) = x or f(x) = 1/x intro H₂ have h₀ : f 1 ≠ 0 := by specialize H₁ 1 zero_lt_one; exact ne_of_gt H₁ have h₁ : f 1 = 1 := by specialize H₂ 1 1 1 1 zero_lt_one zero_lt_one zero_lt_one zero_lt_one rfl norm_num [← two_mul] at H₂ rw [mul_div_mul_left (f 1 ^ 2) (f 1) two_ne_zero] at H₂ rwa [← (div_eq_iff h₀).mpr (sq (f 1))] have h₂ : ∀ x > 0, (f x - x) * (f x - 1 / x) = 0 := by intro x hx have h1xss : 1 * x = sqrt x * sqrt x := by rw [one_mul, mul_self_sqrt (le_of_lt hx)] specialize H₂ 1 x (sqrt x) (sqrt x) zero_lt_one hx (sqrt_pos.mpr hx) (sqrt_pos.mpr hx) h1xss rw [h₁, one_pow 2, sq_sqrt (le_of_lt hx), ← two_mul (f x), ← two_mul x] at H₂ have hfx_ne_0 : f x ≠ 0 := by specialize H₁ x hx; exact ne_of_gt H₁ field_simp at H₂ ⊢ linear_combination 1 / 2 * H₂ have h₃ : ∀ x > 0, f x = x ∨ f x = 1 / x := by simpa [sub_eq_zero] using h₂ by_contra! h rcases h with ⟨⟨b, hb, hfb₁⟩, ⟨a, ha, hfa₁⟩⟩ obtain hfa₂ := Or.resolve_right (h₃ a ha) hfa₁ -- f(a) ≠ 1/a, f(a) = a obtain hfb₂ := Or.resolve_left (h₃ b hb) hfb₁ -- f(b) ≠ b, f(b) = 1/b have hab : a * b > 0 := mul_pos ha hb have habss : a * b = sqrt (a * b) * sqrt (a * b) := (mul_self_sqrt (le_of_lt hab)).symm specialize H₂ a b (sqrt (a * b)) (sqrt (a * b)) ha hb (sqrt_pos.mpr hab) (sqrt_pos.mpr hab) habss rw [sq_sqrt (le_of_lt hab), ← two_mul (f (a * b)), ← two_mul (a * b)] at H₂ rw [hfa₂, hfb₂] at H₂ have h2ab_ne_0 : 2 * (a * b) ≠ 0 := by positivity specialize h₃ (a * b) hab rcases h₃ with hab₁ | hab₂ -- f(ab) = ab → b^4 = 1 → b = 1 → f(b) = b → false · rw [hab₁, div_left_inj' h2ab_ne_0] at H₂ field_simp at H₂ have hb₁ : b ^ 4 = 1 := by linear_combination -H₂ obtain hb₂ := abs_eq_one_of_pow_eq_one b 4 (show 4 ≠ 0 by simp) hb₁ rw [abs_of_pos hb] at hb₂; rw [hb₂] at hfb₁; exact hfb₁ h₁ -- f(ab) = 1/ab → a^4 = 1 → a = 1 → f(a) = 1/a → false · have hb_ne_0 : b ≠ 0 := ne_of_gt hb field_simp [hab₂] at H₂ have H₃ : 2 * b ^ 4 * (a ^ 4 - 1) = 0 := by linear_combination H₂ have h2b4_ne_0 : 2 * b ^ 4 ≠ 0 := mul_ne_zero two_ne_zero (pow_ne_zero 4 hb_ne_0) have ha₁ : a ^ 4 = 1 := by simpa [sub_eq_zero, h2b4_ne_0, hb_ne_0] using H₃ obtain ha₂ := abs_eq_one_of_pow_eq_one a 4 (show 4 ≠ 0 by simp) ha₁ rw [abs_of_pos ha] at ha₂; rw [ha₂] at hfa₁; norm_num at hfa₁; contradiction
UnitInterval.lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kim Morrison -/ import Mathlib.Algebra.Order.Interval.Set.Instances import Mathlib.Order.Interval.Set.ProjIcc import Mathlib.Topology.Algebra.Ring.Real /-! # The unit interval, as a topological space Use `open unitInterval` to turn on the notation `I := Set.Icc (0 : ℝ) (1 : ℝ)`. We provide basic instances, as well as a custom tactic for discharging `0 ≤ ↑x`, `0 ≤ 1 - ↑x`, `↑x ≤ 1`, and `1 - ↑x ≤ 1` when `x : I`. -/ noncomputable section open Topology Filter Set Int Set.Icc /-! ### The unit interval -/ /-- The unit interval `[0,1]` in ℝ. -/ abbrev unitInterval : Set ℝ := Set.Icc 0 1 @[inherit_doc] scoped[unitInterval] notation "I" => unitInterval namespace unitInterval theorem zero_mem : (0 : ℝ) ∈ I := ⟨le_rfl, zero_le_one⟩ theorem one_mem : (1 : ℝ) ∈ I := ⟨zero_le_one, le_rfl⟩ theorem mul_mem {x y : ℝ} (hx : x ∈ I) (hy : y ∈ I) : x * y ∈ I := ⟨mul_nonneg hx.1 hy.1, mul_le_one₀ hx.2 hy.1 hy.2⟩ theorem div_mem {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hxy : x ≤ y) : x / y ∈ I := ⟨div_nonneg hx hy, div_le_one_of_le₀ hxy hy⟩ theorem fract_mem (x : ℝ) : fract x ∈ I := ⟨fract_nonneg _, (fract_lt_one _).le⟩ theorem mem_iff_one_sub_mem {t : ℝ} : t ∈ I ↔ 1 - t ∈ I := by rw [mem_Icc, mem_Icc] constructor <;> intro <;> constructor <;> linarith lemma univ_eq_Icc : (univ : Set I) = Icc (0 : I) (1 : I) := Icc_bot_top.symm @[norm_cast] theorem coe_ne_zero {x : I} : (x : ℝ) ≠ 0 ↔ x ≠ 0 := coe_eq_zero.not @[norm_cast] theorem coe_ne_one {x : I} : (x : ℝ) ≠ 1 ↔ x ≠ 1 := coe_eq_one.not @[simp, norm_cast] theorem coe_pos {x : I} : (0 : ℝ) < x ↔ 0 < x := Iff.rfl @[simp, norm_cast] theorem coe_lt_one {x : I} : (x : ℝ) < 1 ↔ x < 1 := Iff.rfl theorem mul_le_left {x y : I} : x * y ≤ x := Subtype.coe_le_coe.mp <| mul_le_of_le_one_right x.2.1 y.2.2 theorem mul_le_right {x y : I} : x * y ≤ y := Subtype.coe_le_coe.mp <| mul_le_of_le_one_left y.2.1 x.2.2 /-- Unit interval central symmetry. -/ def symm : I → I := fun t => ⟨1 - t, mem_iff_one_sub_mem.mp t.prop⟩ @[inherit_doc] scoped notation "σ" => unitInterval.symm @[simp] theorem symm_zero : σ 0 = 1 := Subtype.ext <| by simp [symm] @[simp] theorem symm_one : σ 1 = 0 := Subtype.ext <| by simp [symm] @[simp] theorem symm_symm (x : I) : σ (σ x) = x := Subtype.ext <| by simp [symm] theorem symm_involutive : Function.Involutive (symm : I → I) := symm_symm theorem symm_bijective : Function.Bijective (symm : I → I) := symm_involutive.bijective @[simp] theorem coe_symm_eq (x : I) : (σ x : ℝ) = 1 - x := rfl lemma image_coe_preimage_symm {s : Set I} : Subtype.val '' (σ ⁻¹' s) = (1 - ·) ⁻¹' (Subtype.val '' s) := by simp [symm_involutive, ← Function.Involutive.image_eq_preimage, image_image] @[simp] theorem symm_projIcc (x : ℝ) : symm (projIcc 0 1 zero_le_one x) = projIcc 0 1 zero_le_one (1 - x) := by ext rcases le_total x 0 with h₀ | h₀ · simp [projIcc_of_le_left, projIcc_of_right_le, h₀] · rcases le_total x 1 with h₁ | h₁ · lift x to I using ⟨h₀, h₁⟩ simp_rw [← coe_symm_eq, projIcc_val] · simp [projIcc_of_le_left, projIcc_of_right_le, h₁] @[continuity, fun_prop] theorem continuous_symm : Continuous σ := Continuous.subtype_mk (by fun_prop) _ /-- `unitInterval.symm` as a `Homeomorph`. -/ @[simps] def symmHomeomorph : I ≃ₜ I where toFun := symm invFun := symm left_inv := symm_symm right_inv := symm_symm theorem strictAnti_symm : StrictAnti σ := fun _ _ h ↦ sub_lt_sub_left (α := ℝ) h _ @[simp] theorem symm_inj {i j : I} : σ i = σ j ↔ i = j := symm_bijective.injective.eq_iff theorem half_le_symm_iff (t : I) : 1 / 2 ≤ (σ t : ℝ) ↔ (t : ℝ) ≤ 1 / 2 := by rw [coe_symm_eq, le_sub_iff_add_le, add_comm, ← le_sub_iff_add_le, sub_half] @[simp] lemma symm_eq_one {i : I} : σ i = 1 ↔ i = 0 := by rw [← symm_zero, symm_inj] @[simp] lemma symm_eq_zero {i : I} : σ i = 0 ↔ i = 1 := by rw [← symm_one, symm_inj] @[simp] theorem symm_le_symm {i j : I} : σ i ≤ σ j ↔ j ≤ i := by simp only [symm, Subtype.mk_le_mk, sub_le_sub_iff, add_le_add_iff_left, Subtype.coe_le_coe] theorem le_symm_comm {i j : I} : i ≤ σ j ↔ j ≤ σ i := by rw [← symm_le_symm, symm_symm] theorem symm_le_comm {i j : I} : σ i ≤ j ↔ σ j ≤ i := by rw [← symm_le_symm, symm_symm] @[simp] theorem symm_lt_symm {i j : I} : σ i < σ j ↔ j < i := by simp only [symm, Subtype.mk_lt_mk, sub_lt_sub_iff_left, Subtype.coe_lt_coe] theorem lt_symm_comm {i j : I} : i < σ j ↔ j < σ i := by rw [← symm_lt_symm, symm_symm] theorem symm_lt_comm {i j : I} : σ i < j ↔ σ j < i := by rw [← symm_lt_symm, symm_symm] instance : ConnectedSpace I := Subtype.connectedSpace ⟨nonempty_Icc.mpr zero_le_one, isPreconnected_Icc⟩ /-- Verify there is an instance for `CompactSpace I`. -/ example : CompactSpace I := by infer_instance theorem nonneg (x : I) : 0 ≤ (x : ℝ) := x.2.1 theorem one_minus_nonneg (x : I) : 0 ≤ 1 - (x : ℝ) := by simpa using x.2.2 theorem le_one (x : I) : (x : ℝ) ≤ 1 := x.2.2 theorem one_minus_le_one (x : I) : 1 - (x : ℝ) ≤ 1 := by simpa using x.2.1 theorem add_pos {t : I} {x : ℝ} (hx : 0 < x) : 0 < (x + t : ℝ) := add_pos_of_pos_of_nonneg hx <| nonneg _ /-- like `unitInterval.nonneg`, but with the inequality in `I`. -/ theorem nonneg' {t : I} : 0 ≤ t := t.2.1 /-- like `unitInterval.le_one`, but with the inequality in `I`. -/ theorem le_one' {t : I} : t ≤ 1 := t.2.2 protected lemma pos_iff_ne_zero {x : I} : 0 < x ↔ x ≠ 0 := bot_lt_iff_ne_bot protected lemma lt_one_iff_ne_one {x : I} : x < 1 ↔ x ≠ 1 := lt_top_iff_ne_top lemma eq_one_or_eq_zero_of_le_mul {i j : I} (h : i ≤ j * i) : i = 0 ∨ j = 1 := by contrapose! h rw [← unitInterval.lt_one_iff_ne_one, ← coe_lt_one, ← unitInterval.pos_iff_ne_zero, ← coe_pos] at h rw [← Subtype.coe_lt_coe, coe_mul] simpa using mul_lt_mul_of_pos_right h.right h.left instance : Nontrivial I := ⟨⟨1, 0, (one_ne_zero <| congrArg Subtype.val ·)⟩⟩ theorem mul_pos_mem_iff {a t : ℝ} (ha : 0 < a) : a * t ∈ I ↔ t ∈ Set.Icc (0 : ℝ) (1 / a) := by constructor <;> rintro ⟨h₁, h₂⟩ <;> constructor · exact nonneg_of_mul_nonneg_right h₁ ha · rwa [le_div_iff₀ ha, mul_comm] · exact mul_nonneg ha.le h₁ · rwa [le_div_iff₀ ha, mul_comm] at h₂ theorem two_mul_sub_one_mem_iff {t : ℝ} : 2 * t - 1 ∈ I ↔ t ∈ Set.Icc (1 / 2 : ℝ) 1 := by constructor <;> rintro ⟨h₁, h₂⟩ <;> constructor <;> linarith /-- The unit interval as a submonoid of ℝ. -/ def submonoid : Submonoid ℝ where carrier := unitInterval one_mem' := unitInterval.one_mem mul_mem' := unitInterval.mul_mem @[simp] theorem coe_unitIntervalSubmonoid : submonoid = unitInterval := rfl @[simp] theorem mem_unitIntervalSubmonoid {x} : x ∈ submonoid ↔ x ∈ unitInterval := Iff.rfl protected theorem prod_mem {ι : Type*} {t : Finset ι} {f : ι → ℝ} (h : ∀ c ∈ t, f c ∈ unitInterval) : ∏ c ∈ t, f c ∈ unitInterval := _root_.prod_mem (S := unitInterval.submonoid) h instance : LinearOrderedCommMonoidWithZero I where zero_mul i := zero_mul i mul_zero i := mul_zero i zero_le_one := nonneg' mul_le_mul_left i j h_ij k := by simp only [← Subtype.coe_le_coe, coe_mul] apply mul_le_mul le_rfl ?_ (nonneg i) (nonneg k) simp [h_ij] lemma subtype_Iic_eq_Icc (x : I) : Subtype.val⁻¹' (Iic ↑x) = Icc 0 x := by rw [preimage_subtype_val_Iic] exact Icc_bot.symm lemma subtype_Iio_eq_Ico (x : I) : Subtype.val⁻¹' (Iio ↑x) = Ico 0 x := by rw [preimage_subtype_val_Iio] exact Ico_bot.symm lemma subtype_Ici_eq_Icc (x : I) : Subtype.val⁻¹' (Ici ↑x) = Icc x 1 := by rw [preimage_subtype_val_Ici] exact Icc_top.symm lemma subtype_Ioi_eq_Ioc (x : I) : Subtype.val⁻¹' (Ioi ↑x) = Ioc x 1 := by rw [preimage_subtype_val_Ioi] exact Ioc_top.symm end unitInterval section partition namespace Set.Icc variable {α} [AddCommGroup α] [LinearOrder α] [IsOrderedAddMonoid α] {a b c d : α} (h : a ≤ b) {δ : α} -- TODO: Set.projIci, Set.projIic /-- `Set.projIcc` is a contraction. -/ lemma _root_.Set.abs_projIcc_sub_projIcc : (|projIcc a b h c - projIcc a b h d| : α) ≤ |c - d| := by wlog hdc : d ≤ c generalizing c d · rw [abs_sub_comm, abs_sub_comm c]; exact this (le_of_not_ge hdc) rw [abs_eq_self.2 (sub_nonneg.2 hdc), abs_eq_self.2 (sub_nonneg.2 <| mod_cast monotone_projIcc h hdc)] rw [← sub_nonneg] at hdc refine (max_sub_max_le_max _ _ _ _).trans (max_le (by rwa [sub_self]) ?_) refine ((le_abs_self _).trans <| abs_min_sub_min_le_max _ _ _ _).trans (max_le ?_ ?_) · rwa [sub_self, abs_zero] · exact (abs_eq_self.mpr hdc).le /-- When `h : a ≤ b` and `δ > 0`, `addNSMul h δ` is a sequence of points in the closed interval `[a,b]`, which is initially equally spaced but eventually stays at the right endpoint `b`. -/ def addNSMul (δ : α) (n : ℕ) : Icc a b := projIcc a b h (a + n • δ) omit [IsOrderedAddMonoid α] in lemma addNSMul_zero : addNSMul h δ 0 = a := by rw [addNSMul, zero_smul, add_zero, projIcc_left] lemma addNSMul_eq_right [Archimedean α] (hδ : 0 < δ) : ∃ m, ∀ n ≥ m, addNSMul h δ n = b := by obtain ⟨m, hm⟩ := Archimedean.arch (b - a) hδ refine ⟨m, fun n hn ↦ ?_⟩ rw [addNSMul, coe_projIcc, add_comm, min_eq_left_iff.mpr, max_eq_right h] exact sub_le_iff_le_add.mp (hm.trans <| nsmul_le_nsmul_left hδ.le hn) lemma monotone_addNSMul (hδ : 0 ≤ δ) : Monotone (addNSMul h δ) := fun _ _ hnm ↦ monotone_projIcc h <| (add_le_add_iff_left _).mpr (nsmul_le_nsmul_left hδ hnm) lemma abs_sub_addNSMul_le (hδ : 0 ≤ δ) {t : Icc a b} (n : ℕ) (ht : t ∈ Icc (addNSMul h δ n) (addNSMul h δ (n + 1))) : (|t - addNSMul h δ n| : α) ≤ δ := calc (|t - addNSMul h δ n| : α) = t - addNSMul h δ n := abs_eq_self.2 <| sub_nonneg.2 ht.1 _ ≤ projIcc a b h (a + (n + 1) • δ) - addNSMul h δ n := by apply sub_le_sub_right; exact ht.2 _ ≤ (|projIcc a b h (a + (n + 1) • δ) - addNSMul h δ n| : α) := le_abs_self _ _ ≤ |a + (n + 1) • δ - (a + n • δ)| := abs_projIcc_sub_projIcc h _ ≤ δ := by rw [add_sub_add_comm, sub_self, zero_add, succ_nsmul', add_sub_cancel_right] exact (abs_eq_self.mpr hδ).le end Set.Icc open scoped unitInterval /-- Any open cover `c` of a closed interval `[a, b]` in ℝ can be refined to a finite partition into subintervals. -/ lemma exists_monotone_Icc_subset_open_cover_Icc {ι} {a b : ℝ} (h : a ≤ b) {c : ι → Set (Icc a b)} (hc₁ : ∀ i, IsOpen (c i)) (hc₂ : univ ⊆ ⋃ i, c i) : ∃ t : ℕ → Icc a b, t 0 = a ∧ Monotone t ∧ (∃ m, ∀ n ≥ m, t n = b) ∧ ∀ n, ∃ i, Icc (t n) (t (n + 1)) ⊆ c i := by obtain ⟨δ, δ_pos, ball_subset⟩ := lebesgue_number_lemma_of_metric isCompact_univ hc₁ hc₂ have hδ := half_pos δ_pos refine ⟨addNSMul h (δ/2), addNSMul_zero h, monotone_addNSMul h hδ.le, addNSMul_eq_right h hδ, fun n ↦ ?_⟩ obtain ⟨i, hsub⟩ := ball_subset (addNSMul h (δ/2) n) trivial exact ⟨i, fun t ht ↦ hsub ((abs_sub_addNSMul_le h hδ.le n ht).trans_lt <| half_lt_self δ_pos)⟩ /-- Any open cover of the unit interval can be refined to a finite partition into subintervals. -/ lemma exists_monotone_Icc_subset_open_cover_unitInterval {ι} {c : ι → Set I} (hc₁ : ∀ i, IsOpen (c i)) (hc₂ : univ ⊆ ⋃ i, c i) : ∃ t : ℕ → I, t 0 = 0 ∧ Monotone t ∧ (∃ n, ∀ m ≥ n, t m = 1) ∧ ∀ n, ∃ i, Icc (t n) (t (n + 1)) ⊆ c i := by simp_rw [← Subtype.coe_inj] exact exists_monotone_Icc_subset_open_cover_Icc zero_le_one hc₁ hc₂ lemma exists_monotone_Icc_subset_open_cover_unitInterval_prod_self {ι} {c : ι → Set (I × I)} (hc₁ : ∀ i, IsOpen (c i)) (hc₂ : univ ⊆ ⋃ i, c i) : ∃ t : ℕ → I, t 0 = 0 ∧ Monotone t ∧ (∃ n, ∀ m ≥ n, t m = 1) ∧ ∀ n m, ∃ i, Icc (t n) (t (n + 1)) ×ˢ Icc (t m) (t (m + 1)) ⊆ c i := by obtain ⟨δ, δ_pos, ball_subset⟩ := lebesgue_number_lemma_of_metric isCompact_univ hc₁ hc₂ have hδ := half_pos δ_pos simp_rw [Subtype.ext_iff] have h : (0 : ℝ) ≤ 1 := zero_le_one refine ⟨addNSMul h (δ/2), addNSMul_zero h, monotone_addNSMul h hδ.le, addNSMul_eq_right h hδ, fun n m ↦ ?_⟩ obtain ⟨i, hsub⟩ := ball_subset (addNSMul h (δ/2) n, addNSMul h (δ/2) m) trivial exact ⟨i, fun t ht ↦ hsub (Metric.mem_ball.mpr <| (max_le (abs_sub_addNSMul_le h hδ.le n ht.1) <| abs_sub_addNSMul_le h hδ.le m ht.2).trans_lt <| half_lt_self δ_pos)⟩ end partition @[simp] theorem projIcc_eq_zero {x : ℝ} : projIcc (0 : ℝ) 1 zero_le_one x = 0 ↔ x ≤ 0 := projIcc_eq_left zero_lt_one @[simp] theorem projIcc_eq_one {x : ℝ} : projIcc (0 : ℝ) 1 zero_le_one x = 1 ↔ 1 ≤ x := projIcc_eq_right zero_lt_one namespace Tactic.Interactive /-- A tactic that solves `0 ≤ ↑x`, `0 ≤ 1 - ↑x`, `↑x ≤ 1`, and `1 - ↑x ≤ 1` for `x : I`. -/ macro "unit_interval" : tactic => `(tactic| (first | apply unitInterval.nonneg | apply unitInterval.one_minus_nonneg | apply unitInterval.le_one | apply unitInterval.one_minus_le_one)) example (x : unitInterval) : 0 ≤ (x : ℝ) := by unit_interval end Tactic.Interactive section variable {𝕜 : Type*} [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜] [TopologicalSpace 𝕜] [IsTopologicalRing 𝕜] -- We only need the ordering on `𝕜` here to avoid talking about flipping the interval over. -- At the end of the day I only care about `ℝ`, so I'm hesitant to put work into generalizing. /-- The image of `[0,1]` under the homeomorphism `fun x ↦ a * x + b` is `[b, a+b]`. -/ theorem affineHomeomorph_image_I (a b : 𝕜) (h : 0 < a) : affineHomeomorph a b h.ne.symm '' Set.Icc 0 1 = Set.Icc b (a + b) := by simp [h] /-- The affine homeomorphism from a nontrivial interval `[a,b]` to `[0,1]`. -/ def iccHomeoI (a b : 𝕜) (h : a < b) : Set.Icc a b ≃ₜ Set.Icc (0 : 𝕜) (1 : 𝕜) := by let e := Homeomorph.image (affineHomeomorph (b - a) a (sub_pos.mpr h).ne.symm) (Set.Icc 0 1) refine (e.trans ?_).symm apply Homeomorph.setCongr rw [affineHomeomorph_image_I _ _ (sub_pos.2 h)] simp @[simp] theorem iccHomeoI_apply_coe (a b : 𝕜) (h : a < b) (x : Set.Icc a b) : ((iccHomeoI a b h) x : 𝕜) = (x - a) / (b - a) := rfl @[simp] theorem iccHomeoI_symm_apply_coe (a b : 𝕜) (h : a < b) (x : Set.Icc (0 : 𝕜) (1 : 𝕜)) : ((iccHomeoI a b h).symm x : 𝕜) = (b - a) * x + a := rfl end section NNReal open unitInterval NNReal /-- The coercion from `I` to `ℝ≥0`. -/ def unitInterval.toNNReal : I → ℝ≥0 := fun i ↦ ⟨i.1, i.2.1⟩ @[fun_prop] lemma unitInterval.toNNReal_continuous : Continuous toNNReal := by delta toNNReal fun_prop @[simp] lemma unitInterval.coe_toNNReal (x : I) : ((toNNReal x) : ℝ) = x := rfl end NNReal
Nilpotent.lean
/- Copyright (c) 2018 Mario Carneiro, Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.RingTheory.Finiteness.Ideal import Mathlib.RingTheory.Nilpotent.Lemmas import Mathlib.RingTheory.Noetherian.Defs /-! # Nilpotent ideals in Noetherian rings ## Main results * `IsNoetherianRing.isNilpotent_nilradical` -/ open IsNoetherian theorem IsNoetherianRing.isNilpotent_nilradical (R : Type*) [CommSemiring R] [IsNoetherianRing R] : IsNilpotent (nilradical R) := by obtain ⟨n, hn⟩ := Ideal.exists_radical_pow_le_of_fg (⊥ : Ideal R) (IsNoetherian.noetherian _) exact ⟨n, eq_bot_iff.mpr hn⟩ lemma Ideal.FG.isNilpotent_iff_le_nilradical {R : Type*} [CommSemiring R] {I : Ideal R} (hI : I.FG) : IsNilpotent I ↔ I ≤ nilradical R := ⟨fun ⟨n, hn⟩ _ hx ↦ ⟨n, hn ▸ Ideal.pow_mem_pow hx n⟩, fun h ↦ let ⟨n, hn⟩ := exists_pow_le_of_le_radical_of_fg h hI; ⟨n, le_bot_iff.mp hn⟩⟩
HomCongr.lean
/- Copyright (c) 2024 Nick Ward. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nick Ward -/ import Mathlib.CategoryTheory.Enriched.Ordinary.Basic /-! # Congruence of enriched homs Recall that when `C` is both a category and a `V`-enriched category, we say it is an `EnrichedOrdinaryCategory` if it comes equipped with a sufficiently compatible equivalence between morphisms `X ⟶ Y` in `C` and morphisms `𝟙_ V ⟶ (X ⟶[V] Y)` in `V`. In such a `V`-enriched ordinary category `C`, isomorphisms in `C` induce isomorphisms between hom-objects in `V`. We define this isomorphism in `CategoryTheory.Iso.eHomCongr` and prove that it respects composition in `C`. The treatment here parallels that for unenriched categories in `Mathlib/CategoryTheory/HomCongr.lean` and that for sorts in `Mathlib/Logic/Equiv/Defs.lean` (cf. `Equiv.arrowCongr`). Note, however, that they construct equivalences between `Type`s and `Sort`s, respectively, while in this file we construct isomorphisms between objects in `V`. -/ universe v' v u u' namespace CategoryTheory namespace Iso open Category MonoidalCategory variable (V : Type u') [Category.{v'} V] [MonoidalCategory V] {C : Type u} [Category.{v} C] [EnrichedOrdinaryCategory V C] /-- Given isomorphisms `α : X ≅ X₁` and `β : Y ≅ Y₁` in `C`, we can construct an isomorphism between `V` objects `X ⟶[V] Y` and `X₁ ⟶[V] Y₁`. -/ @[simps] def eHomCongr {X Y X₁ Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) : (X ⟶[V] Y) ≅ (X₁ ⟶[V] Y₁) where hom := eHomWhiskerRight V α.inv Y ≫ eHomWhiskerLeft V X₁ β.hom inv := eHomWhiskerRight V α.hom Y₁ ≫ eHomWhiskerLeft V X β.inv hom_inv_id := by rw [← eHom_whisker_exchange] slice_lhs 2 3 => rw [← eHomWhiskerRight_comp] simp [← eHomWhiskerLeft_comp] inv_hom_id := by rw [← eHom_whisker_exchange] slice_lhs 2 3 => rw [← eHomWhiskerRight_comp] simp [← eHomWhiskerLeft_comp] lemma eHomCongr_refl (X Y : C) : eHomCongr V (Iso.refl X) (Iso.refl Y) = Iso.refl (X ⟶[V] Y) := by aesop lemma eHomCongr_trans {X₁ Y₁ X₂ Y₂ X₃ Y₃ : C} (α₁ : X₁ ≅ X₂) (β₁ : Y₁ ≅ Y₂) (α₂ : X₂ ≅ X₃) (β₂ : Y₂ ≅ Y₃) : eHomCongr V (α₁ ≪≫ α₂) (β₁ ≪≫ β₂) = eHomCongr V α₁ β₁ ≪≫ eHomCongr V α₂ β₂ := by ext; simp [eHom_whisker_exchange_assoc] lemma eHomCongr_symm {X Y X₁ Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) : (eHomCongr V α β).symm = eHomCongr V α.symm β.symm := rfl /-- `eHomCongr` respects composition of morphisms. Recall that for any composable pair of arrows `f : X ⟶ Y` and `g : Y ⟶ Z` in `C`, the composite `f ≫ g` in `C` defines a morphism `𝟙_ V ⟶ (X ⟶[V] Z)` in `V`. Composing with the isomorphism `eHomCongr V α γ` yields a morphism in `V` that can be factored through the enriched composition map as shown: `𝟙_ V ⟶ 𝟙_ V ⊗ 𝟙_ V ⟶ (X₁ ⟶[V] Y₁) ⊗ (Y₁ ⟶[V] Z₁) ⟶ (X₁ ⟶[V] Z₁)`. -/ @[reassoc] lemma eHomCongr_comp {X Y Z X₁ Y₁ Z₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (γ : Z ≅ Z₁) (f : X ⟶ Y) (g : Y ⟶ Z) : eHomEquiv V (f ≫ g) ≫ (eHomCongr V α γ).hom = (λ_ _).inv ≫ (eHomEquiv V f ≫ (eHomCongr V α β).hom) ▷ _ ≫ _ ◁ (eHomEquiv V g ≫ (eHomCongr V β γ).hom) ≫ eComp V X₁ Y₁ Z₁ := by simp only [eHomCongr, MonoidalCategory.whiskerRight_id, assoc, MonoidalCategory.whiskerLeft_comp] rw [rightUnitor_inv_naturality_assoc, rightUnitor_inv_naturality_assoc, rightUnitor_inv_naturality_assoc, hom_inv_id_assoc, ← whisker_exchange_assoc, ← whisker_exchange_assoc, ← eComp_eHomWhiskerLeft, eHom_whisker_cancel_assoc, ← eComp_eHomWhiskerRight_assoc, ← tensorHom_def_assoc, ← eHomEquiv_comp_assoc] /-- The inverse map defined by `eHomCongr` respects composition of morphisms. -/ @[reassoc] lemma eHomCongr_inv_comp {X Y Z X₁ Y₁ Z₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (γ : Z ≅ Z₁) (f : X₁ ⟶ Y₁) (g : Y₁ ⟶ Z₁) : eHomEquiv V (f ≫ g) ≫ (eHomCongr V α γ).inv = (λ_ _).inv ≫ (eHomEquiv V f ≫ (eHomCongr V α β).inv) ▷ _ ≫ _ ◁ (eHomEquiv V g ≫ (eHomCongr V β γ).inv) ≫ eComp V X Y Z := eHomCongr_comp V α.symm β.symm γ.symm f g end Iso end CategoryTheory
Polynomial.lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Algebra.MvPolynomial.Expand import Mathlib.FieldTheory.Finite.Basic import Mathlib.LinearAlgebra.Dual.Lemmas import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas import Mathlib.RingTheory.MvPolynomial.Basic /-! ## Polynomials over finite fields -/ namespace MvPolynomial variable {σ : Type*} /-- A polynomial over the integers is divisible by `n : ℕ` if and only if it is zero over `ZMod n`. -/ theorem C_dvd_iff_zmod (n : ℕ) (φ : MvPolynomial σ ℤ) : C (n : ℤ) ∣ φ ↔ map (Int.castRingHom (ZMod n)) φ = 0 := C_dvd_iff_map_hom_eq_zero _ _ (CharP.intCast_eq_zero_iff (ZMod n) n) _ section frobenius variable {p : ℕ} [Fact p.Prime] theorem frobenius_zmod (f : MvPolynomial σ (ZMod p)) : frobenius _ p f = expand p f := by apply induction_on f · intro a; rw [expand_C, frobenius_def, ← C_pow, ZMod.pow_card] · simp only [map_add]; intro _ _ hf hg; rw [hf, hg] · simp only [expand_X, map_mul] intro _ _ hf; rw [hf, frobenius_def] theorem expand_zmod (f : MvPolynomial σ (ZMod p)) : expand p f = f ^ p := (frobenius_zmod _).symm end frobenius end MvPolynomial namespace MvPolynomial noncomputable section open Set LinearMap Submodule variable {K : Type*} {σ : Type*} section Indicator variable [Fintype K] [Fintype σ] /-- Over a field, this is the indicator function as an `MvPolynomial`. -/ def indicator [CommRing K] (a : σ → K) : MvPolynomial σ K := ∏ n, (1 - (X n - C (a n)) ^ (Fintype.card K - 1)) section CommRing variable [CommRing K] theorem eval_indicator_apply_eq_one (a : σ → K) : eval a (indicator a) = 1 := by nontriviality have : 0 < Fintype.card K - 1 := tsub_pos_of_lt Fintype.one_lt_card simp only [indicator, map_prod, map_sub, map_one, map_pow, eval_X, eval_C, sub_self, zero_pow this.ne', sub_zero, Finset.prod_const_one] theorem degrees_indicator (c : σ → K) : degrees (indicator c) ≤ ∑ s : σ, (Fintype.card K - 1) • {s} := by rw [indicator] classical refine degrees_prod_le.trans <| Finset.sum_le_sum fun s _ ↦ degrees_sub_le.trans ?_ rw [degrees_one, Multiset.zero_union] refine le_trans degrees_pow_le (nsmul_le_nsmul_right ?_ _) refine degrees_sub_le.trans ?_ rw [degrees_C, Multiset.union_zero] exact degrees_X' _ theorem indicator_mem_restrictDegree (c : σ → K) : indicator c ∈ restrictDegree σ K (Fintype.card K - 1) := by classical rw [mem_restrictDegree_iff_sup, indicator] intro n refine le_trans (Multiset.count_le_of_le _ <| degrees_indicator _) (le_of_eq ?_) simp_rw [← Multiset.coe_countAddMonoidHom, map_sum, AddMonoidHom.map_nsmul, Multiset.coe_countAddMonoidHom, nsmul_eq_mul, Nat.cast_id] trans · refine Finset.sum_eq_single n ?_ ?_ · intro b _ ne simp [Multiset.count_singleton, ne, if_neg (Ne.symm _)] · intro h; exact (h <| Finset.mem_univ _).elim · rw [Multiset.count_singleton_self, mul_one] end CommRing variable [Field K] theorem eval_indicator_apply_eq_zero (a b : σ → K) (h : a ≠ b) : eval a (indicator b) = 0 := by obtain ⟨i, hi⟩ : ∃ i, a i ≠ b i := by rwa [Ne, funext_iff, not_forall] at h simp only [indicator, map_prod, map_sub, map_one, map_pow, eval_X, eval_C, Finset.prod_eq_zero_iff] refine ⟨i, Finset.mem_univ _, ?_⟩ rw [FiniteField.pow_card_sub_one_eq_one, sub_self] rwa [Ne, sub_eq_zero] end Indicator section variable (K σ) /-- `MvPolynomial.eval` as a `K`-linear map. -/ @[simps] def evalₗ [CommSemiring K] : MvPolynomial σ K →ₗ[K] (σ → K) → K where toFun p e := eval e p map_add' p q := by ext x; simp map_smul' a p := by ext e; simp variable [Field K] [Fintype K] [Finite σ] theorem map_restrict_dom_evalₗ : (restrictDegree σ K (Fintype.card K - 1)).map (evalₗ K σ) = ⊤ := by cases nonempty_fintype σ refine top_unique (SetLike.le_def.2 fun e _ => mem_map.2 ?_) classical refine ⟨∑ n : σ → K, e n • indicator n, ?_, ?_⟩ · exact sum_mem fun c _ => smul_mem _ _ (indicator_mem_restrictDegree _) · ext n simp only [evalₗ_apply, map_sum, smul_eval] rw [Finset.sum_eq_single n] <;> aesop (add simp [eval_indicator_apply_eq_zero, eval_indicator_apply_eq_one, eq_comm]) end end end MvPolynomial namespace MvPolynomial open scoped Cardinal open LinearMap Submodule universe u variable (σ : Type u) (K : Type u) [Fintype K] /-- The submodule of multivariate polynomials whose degree of each variable is strictly less than the cardinality of K. -/ def R [CommRing K] : Type u := restrictDegree σ K (Fintype.card K - 1) -- The `AddCommGroup, Module K, Inhabited` instances should be constructed by a deriving handler. noncomputable instance [CommRing K] : AddCommGroup (R σ K) := inferInstanceAs (AddCommGroup (restrictDegree σ K (Fintype.card K - 1))) noncomputable instance [CommRing K] : Module K (R σ K) := inferInstanceAs (Module K (restrictDegree σ K (Fintype.card K - 1))) noncomputable instance [CommRing K] : Inhabited (R σ K) := inferInstanceAs (Inhabited (restrictDegree σ K (Fintype.card K - 1))) /-- Evaluation in the `MvPolynomial.R` subtype. -/ noncomputable def evalᵢ [CommRing K] : R σ K →ₗ[K] (σ → K) → K := (evalₗ K σ).comp (restrictDegree σ K (Fintype.card K - 1)).subtype -- TODO: would be nice to replace this by suitable decidability assumptions open Classical in noncomputable instance decidableRestrictDegree (m : ℕ) : DecidablePred (· ∈ { n : σ →₀ ℕ | ∀ i, n i ≤ m }) := by simp only [Set.mem_setOf_eq]; infer_instance variable [Field K] open Classical in theorem rank_R [Fintype σ] : Module.rank K (R σ K) = Fintype.card (σ → K) := calc Module.rank K (R σ K) = Module.rank K (↥{ s : σ →₀ ℕ | ∀ n : σ, s n ≤ Fintype.card K - 1 } →₀ K) := LinearEquiv.rank_eq (Finsupp.supportedEquivFinsupp { s : σ →₀ ℕ | ∀ n : σ, s n ≤ Fintype.card K - 1 }) _ = #{ s : σ →₀ ℕ | ∀ n : σ, s n ≤ Fintype.card K - 1 } := by rw [rank_finsupp_self'] _ = #{ s : σ → ℕ | ∀ n : σ, s n < Fintype.card K } := by refine Quotient.sound ⟨Equiv.subtypeEquiv Finsupp.equivFunOnFinite fun f => ?_⟩ refine forall_congr' fun n => le_tsub_iff_right ?_ exact Fintype.card_pos_iff.2 ⟨0⟩ _ = #(σ → { n // n < Fintype.card K }) := (@Equiv.subtypePiEquivPi σ (fun _ => ℕ) fun _ n => n < Fintype.card K).cardinal_eq _ = #(σ → Fin (Fintype.card K)) := (Equiv.arrowCongr (Equiv.refl σ) Fin.equivSubtype.symm).cardinal_eq _ = #(σ → K) := (Equiv.arrowCongr (Equiv.refl σ) (Fintype.equivFin K).symm).cardinal_eq _ = Fintype.card (σ → K) := Cardinal.mk_fintype _ instance [Finite σ] : FiniteDimensional K (R σ K) := by cases nonempty_fintype σ classical exact IsNoetherian.iff_fg.1 (IsNoetherian.iff_rank_lt_aleph0.mpr <| by simpa only [rank_R] using Cardinal.nat_lt_aleph0 (Fintype.card (σ → K))) open Classical in theorem finrank_R [Fintype σ] : Module.finrank K (R σ K) = Fintype.card (σ → K) := Module.finrank_eq_of_rank_eq (rank_R σ K) theorem range_evalᵢ [Finite σ] : range (evalᵢ σ K) = ⊤ := by rw [evalᵢ, LinearMap.range_comp, range_subtype] exact map_restrict_dom_evalₗ K σ theorem ker_evalₗ [Finite σ] : ker (evalᵢ σ K) = ⊥ := by cases nonempty_fintype σ refine (ker_eq_bot_iff_range_eq_top_of_finrank_eq_finrank ?_).mpr (range_evalᵢ σ K) classical rw [Module.finrank_fintype_fun_eq_card, finrank_R] theorem eq_zero_of_eval_eq_zero [Finite σ] (p : MvPolynomial σ K) (h : ∀ v : σ → K, eval v p = 0) (hp : p ∈ restrictDegree σ K (Fintype.card K - 1)) : p = 0 := let p' : R σ K := ⟨p, hp⟩ have : p' ∈ ker (evalᵢ σ K) := funext h show p'.1 = (0 : R σ K).1 from congr_arg _ <| by rwa [ker_evalₗ, mem_bot] at this end MvPolynomial
ClassNumber.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.NumberTheory.ClassNumber.AdmissibleAbs import Mathlib.NumberTheory.ClassNumber.Finite import Mathlib.NumberTheory.NumberField.Discriminant.Basic import Mathlib.RingTheory.Ideal.IsPrincipal import Mathlib.NumberTheory.RamificationInertia.Basic /-! # Class numbers of number fields This file defines the class number of a number field as the (finite) cardinality of the class group of its ring of integers. It also proves some elementary results on the class number. ## Main definitions - `NumberField.classNumber`: the class number of a number field is the (finite) cardinality of the class group of its ring of integers - `isPrincipalIdealRing_of_isPrincipal_of_pow_inertiaDeg_le_of_mem_primesOver_of_mem_Icc`: let `K` be a number field and let `M K` be the Minkowski bound of `K` (by definition it is `(4 / π) ^ nrComplexPlaces K * ((finrank ℚ K)! / (finrank ℚ K) ^ (finrank ℚ K) * √|discr K|)`). To show that `𝓞 K` is a PID it is enough to show that, for all (natural) primes `p ∈ Finset.Icc 1 ⌊(M K)⌋₊`, all ideals `P` above `p` such that `p ^ (span ({p}).inertiaDeg P) ≤ ⌊(M K)⌋₊` are principal. This is the standard technique to prove that `𝓞 K` is principal, see [marcus1977number], discussion after Theorem 37. The way this theorem should be used is to first compute `⌊(M K)⌋₊` and then to use `fin_cases` to deal with the finite number of primes `p` in the interval. -/ open scoped nonZeroDivisors Real open Module NumberField InfinitePlace Ideal Nat variable (K : Type*) [Field K] [NumberField K] local notation "M " K:70 => (4 / π) ^ nrComplexPlaces K * ((finrank ℚ K)! / (finrank ℚ K) ^ (finrank ℚ K) * √|discr K|) namespace NumberField namespace RingOfIntegers noncomputable instance instFintypeClassGroup : Fintype (ClassGroup (𝓞 K)) := ClassGroup.fintypeOfAdmissibleOfFinite ℚ K AbsoluteValue.absIsAdmissible end RingOfIntegers /-- The class number of a number field is the (finite) cardinality of the class group. -/ noncomputable def classNumber : ℕ := Fintype.card (ClassGroup (𝓞 K)) theorem classNumber_ne_zero : classNumber K ≠ 0 := Fintype.card_ne_zero theorem classNumber_pos : 0 < classNumber K := Fintype.card_pos variable {K} /-- The class number of a number field is `1` iff the ring of integers is a PID. -/ theorem classNumber_eq_one_iff : classNumber K = 1 ↔ IsPrincipalIdealRing (𝓞 K) := card_classGroup_eq_one_iff theorem exists_ideal_in_class_of_norm_le (C : ClassGroup (𝓞 K)) : ∃ I : (Ideal (𝓞 K))⁰, ClassGroup.mk0 I = C ∧ absNorm (I : Ideal (𝓞 K)) ≤ M K := by obtain ⟨J, hJ⟩ := ClassGroup.mk0_surjective C⁻¹ obtain ⟨_, ⟨a, ha, rfl⟩, h_nz, h_nm⟩ := exists_ne_zero_mem_ideal_of_norm_le_mul_sqrt_discr K (FractionalIdeal.mk0 K J) obtain ⟨I₀, hI⟩ := dvd_iff_le.mpr ((span_singleton_le_iff_mem J).mpr (by exact ha)) have : I₀ ≠ 0 := by contrapose! h_nz rw [h_nz, mul_zero, zero_eq_bot, span_singleton_eq_bot] at hI rw [Algebra.linearMap_apply, hI, map_zero] let I := (⟨I₀, mem_nonZeroDivisors_iff_ne_zero.mpr this⟩ : (Ideal (𝓞 K))⁰) refine ⟨I, ?_, ?_⟩ · suffices ClassGroup.mk0 I = (ClassGroup.mk0 J)⁻¹ by rw [this, hJ, inv_inv] exact ClassGroup.mk0_eq_mk0_inv_iff.mpr ⟨a, Subtype.coe_ne_coe.1 h_nz, by rw [mul_comm, hI]⟩ · rw [← FractionalIdeal.absNorm_span_singleton (𝓞 K), Algebra.linearMap_apply, ← FractionalIdeal.coeIdeal_span_singleton, FractionalIdeal.coeIdeal_absNorm, hI, map_mul, cast_mul, Rat.cast_mul, absNorm_apply, Rat.cast_natCast, Rat.cast_natCast, FractionalIdeal.coe_mk0, FractionalIdeal.coeIdeal_absNorm, Rat.cast_natCast, mul_div_assoc, mul_assoc, mul_assoc] at h_nm refine le_of_mul_le_mul_of_pos_left h_nm ?_ exact cast_pos.mpr <| pos_of_ne_zero <| absNorm_ne_zero_of_nonZeroDivisors J end NumberField namespace RingOfIntegers variable {K} open scoped NumberField theorem isPrincipalIdealRing_of_isPrincipal_of_norm_le (h : ∀ ⦃I : (Ideal (𝓞 K))⁰⦄, absNorm (I : Ideal (𝓞 K)) ≤ M K → Submodule.IsPrincipal (I : Ideal (𝓞 K))) : IsPrincipalIdealRing (𝓞 K) := by rw [← classNumber_eq_one_iff, classNumber, Fintype.card_eq_one_iff] refine ⟨1, fun C ↦ ?_⟩ obtain ⟨I, rfl, hI⟩ := exists_ideal_in_class_of_norm_le C simpa [← ClassGroup.mk0_eq_one_iff] using h hI theorem isPrincipalIdealRing_of_isPrincipal_of_norm_le_of_isPrime (h : ∀ ⦃I : (Ideal (𝓞 K))⁰⦄, (I : Ideal (𝓞 K)).IsPrime → absNorm (I : Ideal (𝓞 K)) ≤ M K → Submodule.IsPrincipal (I : Ideal (𝓞 K))) : IsPrincipalIdealRing (𝓞 K) := by refine isPrincipalIdealRing_of_isPrincipal_of_norm_le (fun I hI ↦ ?_) rw [← mem_isPrincipalSubmonoid_iff, ← prod_normalizedFactors_eq_self (nonZeroDivisors.coe_ne_zero I)] refine Submonoid.multiset_prod_mem _ _ (fun J hJ ↦ mem_isPrincipalSubmonoid_iff.mp ?_) by_cases hJ0 : J = 0 · simpa [hJ0] using bot_isPrincipal rw [← Subtype.coe_mk J (mem_nonZeroDivisors_of_ne_zero hJ0)] refine h (((mem_normalizedFactors_iff (nonZeroDivisors.coe_ne_zero I)).mp hJ).1) ?_ exact (cast_le.mpr <| le_of_dvd (absNorm_pos_of_nonZeroDivisors I) <| absNorm_dvd_absNorm_of_le <| le_of_dvd <| UniqueFactorizationMonoid.dvd_of_mem_normalizedFactors hJ).trans hI /-- Let `K` be a number field and let `M K` be the Minkowski bound of `K` (by definition it is `(4 / π) ^ nrComplexPlaces K * ((finrank ℚ K)! / (finrank ℚ K) ^ (finrank ℚ K) * √|discr K|)`). To show that `𝓞 K` is a PID it is enough to show that, for all (natural) primes `p ∈ Finset.Icc 1 ⌊(M K)⌋₊`, all ideals `P` above `p` such that `p ^ (span ({p}).inertiaDeg P) ≤ ⌊(M K)⌋₊` are principal. This is the standard technique to prove that `𝓞 K` is principal, see [marcus1977number], discussion after Theorem 37. The way this theorem should be used is to first compute `⌊(M K)⌋₊` and then to use `fin_cases` to deal with the finite number of primes `p` in the interval. -/ theorem isPrincipalIdealRing_of_isPrincipal_of_pow_inertiaDeg_le_of_mem_primesOver_of_mem_Icc (h : ∀ p ∈ Finset.Icc 1 ⌊(M K)⌋₊, p.Prime → ∀ (P : Ideal (𝓞 K)), P ∈ primesOver (span {(p : ℤ)}) (𝓞 K) → p ^ ((span ({↑p} : Set ℤ)).inertiaDeg P) ≤ ⌊(M K)⌋₊ → Submodule.IsPrincipal P) : IsPrincipalIdealRing (𝓞 K) := by refine isPrincipalIdealRing_of_isPrincipal_of_norm_le_of_isPrime <| fun ⟨P, HP⟩ hP hPN ↦ ?_ obtain ⟨p, hp⟩ := IsPrincipalIdealRing.principal <| under ℤ P have hp0 : p ≠ 0 := fun h ↦ nonZeroDivisors.coe_ne_zero ⟨P, HP⟩ <| eq_bot_of_comap_eq_bot (R := ℤ) <| by simpa only [hp, submodule_span_eq, span_singleton_eq_bot] have hpprime := (span_singleton_prime hp0).mp simp only [← submodule_span_eq, ← hp] at hpprime have hlies : P.LiesOver (span {p}) := by rcases abs_choice p with h | h <;> simpa [h, span_singleton_neg p, ← submodule_span_eq, ← hp] using over_under P have hspan : span {↑p.natAbs} = span {p} := by rcases abs_choice p with h | h <;> simp [h] have hple : p.natAbs ^ (span {(p.natAbs : ℤ)}).inertiaDeg P ≤ ⌊(M K)⌋₊ := by refine le_floor ?_ simpa only [hspan, ← cast_pow, ← absNorm_eq_pow_inertiaDeg P (hpprime (hP.under _))] using hPN have hpabsprime := Int.prime_iff_natAbs_prime.mp (hpprime (hP.under _)) refine h _ ?_ hpabsprime _ ⟨hP, ?_⟩ hple · suffices 0 < (span {(p.natAbs : ℤ)}).inertiaDeg P by exact Finset.mem_Icc.mpr ⟨hpabsprime.one_le, le_trans (le_pow this) hple⟩ have := (isPrime_of_prime (prime_span_singleton_iff.mpr <| hpprime (hP.under _))).isMaximal <| by simp [((hpprime (hP.under _))).ne_zero] exact hspan ▸ inertiaDeg_pos .. · exact hspan ▸ hlies theorem isPrincipalIdealRing_of_abs_discr_lt (h : |discr K| < (2 * (π / 4) ^ nrComplexPlaces K * ((finrank ℚ K) ^ (finrank ℚ K) / (finrank ℚ K)!)) ^ 2) : IsPrincipalIdealRing (𝓞 K) := by have : 0 < finrank ℚ K := finrank_pos -- Lean needs to know this for `positivity` to succeed rw [← Real.sqrt_lt (by positivity) (by positivity), mul_assoc, ← inv_mul_lt_iff₀' (by positivity), mul_inv, ← inv_pow, inv_div, inv_div, mul_assoc, Int.cast_abs] at h refine isPrincipalIdealRing_of_isPrincipal_of_norm_le (fun I hI ↦ ?_) rw [absNorm_eq_one_iff.mp <| le_antisymm (lt_succ.mp (cast_lt.mp (lt_of_le_of_lt hI h))) <| one_le_iff_ne_zero.mpr (absNorm_ne_zero_of_nonZeroDivisors I)] exact top_isPrincipal end RingOfIntegers namespace Rat open NumberField theorem classNumber_eq : NumberField.classNumber ℚ = 1 := classNumber_eq_one_iff.mpr <| IsPrincipalIdealRing.of_surjective Rat.ringOfIntegersEquiv.symm Rat.ringOfIntegersEquiv.symm.surjective end Rat
lift.lean
import Mathlib.Tactic.Lift import Batteries.Tactic.PermuteGoals import Mathlib.Tactic.Coe import Mathlib.Data.Set.Defs import Mathlib.Order.WithBot import Mathlib.Algebra.Group.WithOne.Defs import Mathlib.Data.Set.Image import Mathlib.Data.Set.List import Mathlib.Data.Rat.Defs import Mathlib.Data.PNat.Defs /-! Some tests of the `lift` tactic. -/ example (n : ℤ) (hn : 0 ≤ n) : 0 ≤ n + 1 := by lift n to ℕ guard_target =ₛ 0 ≤ n swap; guard_target =ₛ 0 ≤ (n : Int) + 1; swap · exact hn · exact Int.le_add_one hn example (n : ℤ) (hn : 0 ≤ n) : 0 ≤ n + 1 := by lift n to ℕ using hn guard_target =ₛ 0 ≤ (n : Int) + 1 exact Int.le_add_one (Int.ofNat_zero_le _) example (n : ℤ) (hn : 0 ≤ n) : 0 ≤ n + 1 := by have hn' := hn lift n to ℕ using hn with k hk guard_target =ₛ 0 ≤ (k : Int) + 1 guard_hyp hk : (k : Int) = n exact Int.le_add_one hn' example (n : ℤ) (hn : 0 ≤ n) : 0 ≤ n + 1 := by have hn' := hn lift n to ℕ using hn with k guard_target =ₛ 0 ≤ (k : Int) + 1 exact Int.le_add_one hn' example (n : ℤ) (hn : 0 ≤ n) : 0 ≤ n + 1 := by lift n to ℕ using hn with k hk hn guard_target =ₛ 0 ≤ (k : Int) + 1 guard_hyp hn : 0 ≤ (k : Int) guard_hyp hk : k = n exact Int.le_add_one hn example (n : ℤ) (hn : 0 ≤ n) : 0 ≤ n + 1 := by lift n to ℕ using hn with k rfl hn guard_target =ₛ 0 ≤ (k : Int) + 1 guard_hyp hn : 0 ≤ (k : Int) exact Int.le_add_one hn example (n : ℤ) (hn : 0 ≤ n) : 0 ≤ n + 1 := by have hn' := hn lift n to ℕ using hn with k rfl guard_target =ₛ 0 ≤ (k : Int) + 1 exact Int.le_add_one hn' example (n : ℤ) (hn : 0 ≤ n) : 0 ≤ n + 1 := by have hn' := hn lift n to ℕ using hn with n guard_target =ₛ 0 ≤ (n : Int) + 1 exact Int.le_add_one hn' example (n : ℤ) (hn : 0 ≤ n) : 0 ≤ n + 1 := by -- Should fail because we didn't provide a variable name when lifting an expression fail_if_success lift n + 1 to ℕ using (Int.le_add_one hn) -- Now it should succeed lift n + 1 to ℕ using (Int.le_add_one hn) with k hk exact of_decide_eq_true rfl -- test lift of functions example (α : Type _) (f : α → ℤ) (hf : ∀ a, 0 ≤ f a) (hf' : ∀ a, f a < 1) (a : α) : 0 ≤ 2 * f a := by lift f to α → ℕ using hf guard_target =ₛ (0 : ℤ) ≤ 2 * (fun i : α ↦ (f i : ℤ)) a guard_hyp hf' : ∀ a, ((fun i : α ↦ (f i : ℤ)) a) < 1 constructor example (α : Type _) (f : α → ℤ) (hf : ∀ a, 0 ≤ f a) (_ : ∀ a, f a < 1) (a : α) : 0 ≤ 2 * f a := by lift f to α → ℕ using hf with g hg guard_target =ₛ 0 ≤ 2 * (g a : Int) guard_hyp hg : (fun i => (g i : Int)) = f constructor example (n m k x : ℤ) (hn : 0 < n) (hk : 0 ≤ k + n) (h : k + n = 2 + x) (hans : k + n = m + x) (hans2 : 0 ≤ m) : k + n = m + x := by lift n to ℕ using le_of_lt hn guard_target =ₛ k + ↑n = m + x; guard_hyp hn : (0 : ℤ) < ↑n lift m to ℕ guard_target =ₛ 0 ≤ m; swap; guard_target =ₛ k + ↑n = ↑m + x lift (k + n) to ℕ using hk with l hl exact hans exact hans2 -- fail gracefully when the lifted variable is a local definition example (h : False) : let n : ℤ := 3; n = 3 := by intro n fail_if_success lift n to ℕ exfalso; exact h instance canLift_unit : CanLift Unit Unit id (fun _ ↦ true) := ⟨fun x _ ↦ ⟨x, rfl⟩⟩ set_option linter.unusedVariables false in example (n : ℤ) (hn : 0 < n) : True := by fail_if_success lift n to ℕ using hn fail_if_success lift (n : Option ℤ) to ℕ trivial set_option linter.unusedVariables false in example (n : ℤ) : ℕ := by fail_if_success lift n to ℕ exact 0 instance canLift_subtype (R : Type _) (s : Set R) : CanLift R {x // x ∈ s} ((↑) : {x // x ∈ s} → R) (fun x => x ∈ s) := { prf := fun x hx => ⟨⟨x, hx⟩, rfl⟩ } example {R : Type _} {P : R → Prop} (x : R) (hx : P x) : P x := by lift x to {x // P x} using hx with y hy hx guard_target =ₛ P y guard_hyp hy : y = x guard_hyp hx : P y exact hx example (n : ℤ) (h_ans : n = 5) (hn : 0 ≤ 1 * n) : n = 5 := by lift n to ℕ using by { simpa [Int.one_mul] using hn } with k hk guard_target =ₛ (k : Int) = 5 guard_hyp hk : k = n guard_hyp hn : 0 ≤ 1 * (k : Int) guard_hyp h_ans : (k : Int) = 5 exact h_ans example (n : WithOne Unit) (hn : n ≠ 1) : True := by lift n to Unit · guard_target =ₛ n ≠ 1 exact hn guard_hyp n : Unit guard_hyp hn : (n : WithOne Unit) ≠ 1 trivial example (n : WithZero Unit) (hn : n ≠ 0) : True := by lift n to Unit · guard_target =ₛ n ≠ 0 exact hn guard_hyp n : Unit guard_hyp hn : (n : WithZero Unit) ≠ 0 trivial example (s : Set ℤ) (h : ∀ x ∈ s, 0 ≤ x) : True := by lift s to Set ℕ · guard_target =ₛ (∀ x ∈ s, 0 ≤ x) exact h guard_hyp s : Set ℕ guard_hyp h : ∀ (x : ℤ), x ∈ (fun (n : ℕ) => (n : ℤ)) '' s → 0 ≤ x trivial example (l : List ℤ) (h : ∀ x ∈ l, 0 ≤ x) : True := by lift l to List ℕ · guard_target =ₛ (∀ x ∈ l, 0 ≤ x) exact h guard_hyp l : List ℕ guard_hyp h : ∀ (x : ℤ), x ∈ List.map (fun (n : ℕ) => (n : ℤ)) l → 0 ≤ x trivial example (q : ℚ) (h : q.den = 1) : True := by lift q to ℤ · guard_target =ₛ q.den = 1 exact h guard_hyp q : ℤ guard_hyp h : (q : ℚ).den = 1 trivial example (x : WithTop Unit) (h : x ≠ ⊤) : True := by lift x to Unit · guard_target =ₛ x ≠ ⊤ exact h guard_hyp x : Unit guard_hyp h : (x : WithTop Unit) ≠ ⊤ trivial example (x : WithBot Unit) (h : x ≠ ⊥) : True := by lift x to Unit · guard_target =ₛ x ≠ ⊥ exact h guard_hyp x : Unit guard_hyp h : (x : WithBot Unit) ≠ ⊥ trivial example (n : ℕ) (hn : 0 < n) : True := by lift n to ℕ+ · guard_target =ₛ 0 < n exact hn guard_hyp n : ℕ+ guard_hyp hn : 0 < (n : ℕ) trivial example (n : ℕ) : n = 0 ∨ ∃ p : ℕ+, n = p := by by_cases hn : 0 < n · lift n to ℕ+ using hn right exact ⟨n, rfl⟩ · left exact Nat.eq_zero_of_not_pos hn example (n : ℤ) (hn : 0 < n) : True := by lift n to ℕ+ · guard_target =ₛ 0 < n exact hn guard_hyp n : ℕ+ guard_hyp hn : 0 < (n : ℤ) trivial -- https://leanprover.zulipchat.com/#narrow/channel/287929-mathlib4/topic/Bug.20in.20.60lift.60.20tactic.3F/near/508521400 /-- trace: case intro x : WithTop ℕ P : WithTop ℕ → Prop u : ℕ hu : ↑u = x h : P ↑u ⊢ P ↑u -/ #guard_msgs in example {x : WithTop ℕ} (hx : x ≠ ⊤) (P : WithTop ℕ → Prop) (h : P x) : P x := by lift x to ℕ using hx with u hu trace_state exact h
Init.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import Batteries.Logic import Batteries.Tactic.Init import Mathlib.Data.Int.Notation import Mathlib.Data.Nat.Notation import Mathlib.Tactic.Lemma import Mathlib.Tactic.TypeStar /-! # Basic operations on the integers This file contains some basic lemmas about integers. See note [foundational algebra order theory]. This file should not depend on anything defined in Mathlib (except for notation), so that it can be upstreamed to Batteries easily. -/ open Nat namespace Int variable {a b c d m n : ℤ} protected theorem neg_eq_neg {a b : ℤ} (h : -a = -b) : a = b := Int.neg_inj.1 h @[deprecated (since := "2025-03-07")] alias neg_nonpos_iff_nonneg := Int.neg_nonpos_iff /-! ### succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 lemma pred_succ (a : ℤ) : pred (succ a) = a := Int.add_sub_cancel _ _ lemma succ_pred (a : ℤ) : succ (pred a) = a := Int.sub_add_cancel _ _ lemma neg_succ (a : ℤ) : -succ a = pred (-a) := Int.neg_add lemma succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] lemma neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [← Int.neg_eq_comm.mp (neg_succ (-a)), Int.neg_neg] lemma pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] lemma pred_nat_succ (n : ℕ) : pred (Nat.succ n) = n := pred_succ n lemma neg_nat_succ (n : ℕ) : -(Nat.succ n : ℤ) = pred (-n) := neg_succ n lemma succ_neg_natCast_succ (n : ℕ) : succ (-Nat.succ n) = -n := succ_neg_succ n @[norm_cast] lemma natCast_pred_of_pos {n : ℕ} (h : 0 < n) : ((n - 1 : ℕ) : ℤ) = (n : ℤ) - 1 := by cases n; cases h; simp [natCast_succ] lemma lt_succ_self (a : ℤ) : a < succ a := by unfold succ; omega lemma pred_self_lt (a : ℤ) : pred a < a := by unfold pred; omega /-- Induction on integers: prove a proposition `p i` by proving the base case `p 0`, the upwards induction step `p i → p (i + 1)` and the downwards induction step `p (-i) → p (-i - 1)`. It is used as the default induction principle for the `induction` tactic. -/ @[elab_as_elim, induction_eliminator] protected lemma induction_on {motive : ℤ → Prop} (i : ℤ) (zero : motive 0) (succ : ∀ i : ℕ, motive i → motive (i + 1)) (pred : ∀ i : ℕ, motive (-i) → motive (-i - 1)) : motive i := by cases i with | ofNat i => induction i with | zero => exact zero | succ i ih => exact succ _ ih | negSucc i => suffices ∀ n : ℕ, motive (-n) from this (i + 1) intro n; induction n with | zero => simp [zero] | succ n ih => simpa [natCast_succ, Int.neg_add, Int.sub_eq_add_neg] using pred _ ih section inductionOn' variable {motive : ℤ → Sort*} (z b : ℤ) (zero : motive b) (succ : ∀ k, b ≤ k → motive k → motive (k + 1)) (pred : ∀ k ≤ b, motive k → motive (k - 1)) /-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater than `b`, and the `pred` of a number less than `b`. -/ @[elab_as_elim] protected def inductionOn' : motive z := cast (congrArg motive <| show b + (z - b) = z by rw [Int.add_comm, z.sub_add_cancel b]) <| match z - b with | .ofNat n => pos n | .negSucc n => neg n where /-- The positive case of `Int.inductionOn'`. -/ pos : ∀ n : ℕ, motive (b + n) | 0 => cast (by simp) zero | n + 1 => cast (by rw [Int.add_assoc]; rfl) <| succ _ (Int.le_add_of_nonneg_right (natCast_nonneg _)) (pos n) /-- The negative case of `Int.inductionOn'`. -/ neg : ∀ n : ℕ, motive (b + -[n+1]) | 0 => pred _ Int.le_rfl zero | n + 1 => by refine cast (by rw [Int.add_sub_assoc]; rfl) (pred _ (Int.le_of_lt ?_) (neg n)) omega variable {z b zero succ pred} lemma inductionOn'_self : b.inductionOn' b zero succ pred = zero := cast_eq_iff_heq.mpr <| .symm <| by rw [b.sub_self, ← cast_eq_iff_heq]; rfl lemma inductionOn'_sub_one (hz : z ≤ b) : (z - 1).inductionOn' b zero succ pred = pred z hz (z.inductionOn' b zero succ pred) := by apply cast_eq_iff_heq.mpr obtain ⟨n, hn⟩ := Int.eq_negSucc_of_lt_zero (show z - 1 - b < 0 by omega) rw [hn] obtain _ | n := n · change _ = -1 at hn have : z = b := by omega subst this; rw [inductionOn'_self]; exact heq_of_eq rfl · have : z = b + -[n+1] := by rw [Int.negSucc_eq] at hn ⊢; omega subst this refine (cast_heq _ _).trans ?_ congr symm rw [Int.inductionOn', cast_eq_iff_heq, show b + -[n+1] - b = -[n+1] by omega] end inductionOn' /-- Inductively define a function on `ℤ` by defining it on `ℕ` and extending it from `n` to `-n`. -/ @[elab_as_elim] protected def negInduction {motive : ℤ → Sort*} (nat : ∀ n : ℕ, motive n) (neg : (∀ n : ℕ, motive n) → ∀ n : ℕ, motive (-n)) : ∀ n : ℤ, motive n | .ofNat n => nat n | .negSucc n => neg nat <| n + 1 /-- See `Int.inductionOn'` for an induction in both directions. -/ @[elab_as_elim] protected lemma le_induction {m : ℤ} {motive : ∀ n, m ≤ n → Prop} (base : motive m m.le_refl) (succ : ∀ n hmn, motive n hmn → motive (n + 1) (le_add_one hmn)) : ∀ n hmn, motive n hmn := by refine fun n ↦ Int.inductionOn' n m ?_ ?_ ?_ · intro exact base · intro k hle hi _ exact succ k hle (hi hle) · intro k hle _ hle' omega /-- See `Int.inductionOn'` for an induction in both directions. -/ @[elab_as_elim] protected lemma le_induction_down {m : ℤ} {motive : ∀ n, n ≤ m → Prop} (base : motive m m.le_refl) (pred : ∀ n hmn, motive n hmn → motive (n - 1) (by omega)) : ∀ n hmn, motive n hmn := fun n ↦ Int.inductionOn' n m (fun _ ↦ base) (fun k hle _ hle' ↦ by omega) fun k hle hi _ ↦ pred k hle (hi hle) section strongRec variable {motive : ℤ → Sort*} (lt : ∀ n < m, motive n) (ge : ∀ n ≥ m, (∀ k < n, motive k) → motive n) /-- A strong recursor for `Int` that specifies explicit values for integers below a threshold, and is analogous to `Nat.strongRec` for integers on or above the threshold. -/ @[elab_as_elim] protected def strongRec (n : ℤ) : motive n := by refine if hnm : n < m then lt n hnm else ge n (by omega) (n.inductionOn' m lt ?_ ?_) · intro _n _ ih l _ exact if hlm : l < m then lt l hlm else ge l (by omega) fun k _ ↦ ih k (by omega) · exact fun n _ hn l _ ↦ hn l (by omega) variable {lt ge} lemma strongRec_of_lt (hn : n < m) : m.strongRec lt ge n = lt n hn := dif_pos _ end strongRec /-! ### mul -/ /-! ### natAbs -/ alias natAbs_sq := natAbs_pow_two theorem sign_mul_self_eq_natAbs (a : Int) : sign a * a = natAbs a := sign_mul_self a /-! ### `/` -/ lemma natCast_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := natCast_ediv m n lemma ediv_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : ediv a b = -((-a - 1) / b + 1) := match a, b, eq_negSucc_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ => by rw [show (- -[m+1] : ℤ) = (m + 1 : ℤ) by rfl]; rw [Int.add_sub_cancel]; rfl /-! ### mod -/ @[simp, norm_cast] lemma natCast_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl @[deprecated (since := "2025-04-16")] alias add_emod_eq_add_mod_right := add_emod_eq_add_emod_right lemma div_le_iff_of_dvd_of_pos (hb : 0 < b) (hba : b ∣ a) : a / b ≤ c ↔ a ≤ b * c := ediv_le_iff_of_dvd_of_pos hb hba lemma div_le_iff_of_dvd_of_neg (hb : b < 0) (hba : b ∣ a) : a / b ≤ c ↔ b * c ≤ a := ediv_le_iff_of_dvd_of_neg hb hba lemma div_lt_iff_of_dvd_of_pos (hb : 0 < b) (hba : b ∣ a) : a / b < c ↔ a < b * c := ediv_lt_iff_of_dvd_of_pos hb hba lemma div_lt_iff_of_dvd_of_neg (hb : b < 0) (hba : b ∣ a) : a / b < c ↔ b * c < a := ediv_lt_iff_of_dvd_of_neg hb hba lemma le_div_iff_of_dvd_of_pos (hc : 0 < c) (hcb : c ∣ b) : a ≤ b / c ↔ c * a ≤ b := le_ediv_iff_of_dvd_of_pos hc hcb lemma le_div_iff_of_dvd_of_neg (hc : c < 0) (hcb : c ∣ b) : a ≤ b / c ↔ b ≤ c * a := le_ediv_iff_of_dvd_of_neg hc hcb lemma lt_div_iff_of_dvd_of_pos (hc : 0 < c) (hcb : c ∣ b) : a < b / c ↔ c * a < b := lt_ediv_iff_of_dvd_of_pos hc hcb lemma lt_div_iff_of_dvd_of_neg (hc : c < 0) (hcb : c ∣ b) : a < b / c ↔ b < c * a := lt_ediv_iff_of_dvd_of_neg hc hcb lemma div_le_div_iff_of_dvd_of_pos_of_pos (hb : 0 < b) (hd : 0 < d) (hba : b ∣ a) (hdc : d ∣ c) : a / b ≤ c / d ↔ d * a ≤ c * b := ediv_le_ediv_iff_of_dvd_of_pos_of_pos hb hd hba hdc lemma div_le_div_iff_of_dvd_of_pos_of_neg (hb : 0 < b) (hd : d < 0) (hba : b ∣ a) (hdc : d ∣ c) : a / b ≤ c / d ↔ c * b ≤ d * a := ediv_le_ediv_iff_of_dvd_of_pos_of_neg hb hd hba hdc lemma div_le_div_iff_of_dvd_of_neg_of_pos (hb : b < 0) (hd : 0 < d) (hba : b ∣ a) (hdc : d ∣ c) : a / b ≤ c / d ↔ c * b ≤ d * a := ediv_le_ediv_iff_of_dvd_of_neg_of_pos hb hd hba hdc lemma div_le_div_iff_of_dvd_of_neg_of_neg (hb : b < 0) (hd : d < 0) (hba : b ∣ a) (hdc : d ∣ c) : a / b ≤ c / d ↔ d * a ≤ c * b := ediv_le_ediv_iff_of_dvd_of_neg_of_neg hb hd hba hdc lemma div_lt_div_iff_of_dvd_of_pos (hb : 0 < b) (hd : 0 < d) (hba : b ∣ a) (hdc : d ∣ c) : a / b < c / d ↔ d * a < c * b := ediv_lt_ediv_iff_of_dvd_of_pos hb hd hba hdc lemma div_lt_div_iff_of_dvd_of_pos_of_neg (hb : 0 < b) (hd : d < 0) (hba : b ∣ a) (hdc : d ∣ c) : a / b < c / d ↔ c * b < d * a := ediv_lt_ediv_iff_of_dvd_of_pos_of_neg hb hd hba hdc lemma div_lt_div_iff_of_dvd_of_neg_of_pos (hb : b < 0) (hd : 0 < d) (hba : b ∣ a) (hdc : d ∣ c) : a / b < c / d ↔ c * b < d * a := ediv_lt_ediv_iff_of_dvd_of_neg_of_pos hb hd hba hdc lemma div_lt_div_iff_of_dvd_of_neg_of_neg (hb : b < 0) (hd : d < 0) (hba : b ∣ a) (hdc : d ∣ c) : a / b < c / d ↔ d * a < c * b := ediv_lt_ediv_iff_of_dvd_of_neg_of_neg hb hd hba hdc /-! ### properties of `/` and `%` -/ lemma emod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := emod_two_eq n /-! ### dvd -/ lemma dvd_mul_of_div_dvd (h : b ∣ a) (hdiv : a / b ∣ c) : a ∣ b * c := dvd_mul_of_ediv_dvd h hdiv lemma div_dvd_iff_dvd_mul (h : b ∣ a) (hb : b ≠ 0) : a / b ∣ c ↔ a ∣ b * c := ediv_dvd_iff_dvd_mul h hb lemma mul_dvd_of_dvd_div (hcb : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := mul_dvd_of_dvd_ediv hcb h lemma dvd_div_of_mul_dvd (h : a * b ∣ c) : b ∣ c / a := dvd_ediv_of_mul_dvd h lemma dvd_div_iff_mul_dvd (hbc : c ∣ b) : a ∣ b / c ↔ c * a ∣ b := by simp [hbc] /-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℤ) (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬n ∣ m := (not_dvd_iff_lt_mul_succ m hn).symm lemma eq_mul_div_of_mul_eq_mul_of_dvd_left (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := by obtain ⟨k, rfl⟩ := hbc rw [Int.mul_ediv_cancel_left _ hb] rwa [Int.mul_assoc, Int.mul_eq_mul_left_iff hb] at h lemma ofNat_add_negSucc_of_ge {m n : ℕ} (h : n.succ ≤ m) : ofNat m + -[n+1] = ofNat (m - n.succ) := by rw [negSucc_eq, ofNat_eq_natCast, ofNat_eq_natCast, ← Int.natCast_one, ← Int.natCast_add, ← Int.sub_eq_add_neg, ← Int.natCast_sub h] /-! #### `/` and ordering -/ lemma le_iff_pos_of_dvd (ha : 0 < a) (hab : a ∣ b) : a ≤ b ↔ 0 < b := ⟨Int.lt_of_lt_of_le ha, (Int.le_of_dvd · hab)⟩ lemma le_add_iff_lt_of_dvd_sub (ha : 0 < a) (hab : a ∣ c - b) : a + b ≤ c ↔ b < c := by rw [Int.add_le_iff_le_sub, ← Int.sub_pos, le_iff_pos_of_dvd ha hab] /-! ### sign -/ lemma sign_add_eq_of_sign_eq : ∀ {m n : ℤ}, m.sign = n.sign → (m + n).sign = n.sign := by have : (1 : ℤ) ≠ -1 := by decide rintro ((_ | m) | m) ((_ | n) | n) <;> simp [this, this.symm] <;> omega /-! ### toNat -/ /- The following lemma is non-confluent with ``` simp only [*, @Int.lt_toNat, CharP.cast_eq_zero, @Nat.cast_pred, Int.ofNat_toNat] ``` from the default simp set, which simplifies the LHS to `max i 0 - 1`. Therefore we mark this lemma as `@[simp high]`. -/ @[simp high] lemma toNat_pred_coe_of_pos {i : ℤ} (h : 0 < i) : ((i.toNat - 1 : ℕ) : ℤ) = i - 1 := by simp only [lt_toNat, Int.cast_ofNat_Int, h, natCast_pred_of_pos, Int.le_of_lt h, toNat_of_nonneg] lemma toNat_lt_of_ne_zero {n : ℕ} (hn : n ≠ 0) : m.toNat < n ↔ m < n := by omega @[deprecated (since := "2025-05-24")] alias toNat_lt'' := toNat_lt_of_ne_zero /-- The modulus of an integer by another as a natural. Uses the E-rounding convention. -/ def natMod (m n : ℤ) : ℕ := (m % n).toNat lemma natMod_lt {n : ℕ} (hn : n ≠ 0) : m.natMod n < n := (toNat_lt_of_ne_zero hn).2 <| emod_lt_of_pos _ <| by omega /-- For use in `Mathlib/Tactic/NormNum/Pow.lean` -/ @[simp] lemma pow_eq (m : ℤ) (n : ℕ) : m.pow n = m ^ n := rfl end Int
Comma.lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.CategoryTheory.Subobject.WellPowered import Mathlib.CategoryTheory.Comma.LocallySmall import Mathlib.CategoryTheory.Limits.Preserves.Finite import Mathlib.CategoryTheory.Limits.Shapes.FiniteLimits import Mathlib.CategoryTheory.Limits.Comma /-! # Subobjects in the category of structured arrows We compute the subobjects of an object `A` in the category `StructuredArrow S T` for `T : C ⥤ D` and `S : D` as a subtype of the subobjects of `A.right`. We deduce that `StructuredArrow S T` is well-powered if `C` is. ## Main declarations * `StructuredArrow.subobjectEquiv`: the order-equivalence between `Subobject A` and a subtype of `Subobject A.right`. ## Implementation notes Our computation requires that `C` has all limits and `T` preserves all limits. Furthermore, we require that the morphisms of `C` and `D` are in the same universe. It is possible that both of these requirements can be relaxed by refining the results about limits in comma categories. We also provide the dual results. As usual, we use `Subobject (op A)` for the quotient objects of `A`. -/ noncomputable section open CategoryTheory.Limits Opposite universe w v₁ v₂ u₁ u₂ namespace CategoryTheory variable {C : Type u₁} [Category.{v₁} C] {D : Type u₂} [Category.{v₂} D] namespace StructuredArrow variable {S : D} {T : C ⥤ D} /-- Every subobject of a structured arrow can be projected to a subobject of the underlying object. -/ def projectSubobject [HasFiniteLimits C] [PreservesFiniteLimits T] {A : StructuredArrow S T} : Subobject A → Subobject A.right := by refine Subobject.lift (fun P f hf => Subobject.mk f.right) ?_ intro P Q f g hf hg i hi refine Subobject.mk_eq_mk_of_comm _ _ ((proj S T).mapIso i) ?_ exact congr_arg CommaMorphism.right hi @[simp] theorem projectSubobject_mk [HasFiniteLimits C] [PreservesFiniteLimits T] {A P : StructuredArrow S T} (f : P ⟶ A) [Mono f] : projectSubobject (Subobject.mk f) = Subobject.mk f.right := rfl theorem projectSubobject_factors [HasFiniteLimits C] [PreservesFiniteLimits T] {A : StructuredArrow S T} : ∀ P : Subobject A, ∃ q, q ≫ T.map (projectSubobject P).arrow = A.hom := Subobject.ind _ fun P f hf => ⟨P.hom ≫ T.map (Subobject.underlyingIso _).inv, by simp [← T.map_comp]⟩ /-- A subobject of the underlying object of a structured arrow can be lifted to a subobject of the structured arrow, provided that there is a morphism making the subobject into a structured arrow. -/ @[simp] def liftSubobject {A : StructuredArrow S T} (P : Subobject A.right) {q} (hq : q ≫ T.map P.arrow = A.hom) : Subobject A := Subobject.mk (homMk P.arrow hq : mk q ⟶ A) /-- Projecting and then lifting a subobject recovers the original subobject, because there is at most one morphism making the projected subobject into a structured arrow. -/ theorem lift_projectSubobject [HasFiniteLimits C] [PreservesFiniteLimits T] {A : StructuredArrow S T} : ∀ (P : Subobject A) {q} (hq : q ≫ T.map (projectSubobject P).arrow = A.hom), liftSubobject (projectSubobject P) hq = P := Subobject.ind _ (by intro P f hf q hq fapply Subobject.mk_eq_mk_of_comm · fapply isoMk · exact Subobject.underlyingIso _ · exact (cancel_mono (T.map f.right)).1 (by dsimp; simpa [← T.map_comp] using hq) · exact ext _ _ (by simp)) /-- If `A : S → T.obj B` is a structured arrow for `S : D` and `T : C ⥤ D`, then we can explicitly describe the subobjects of `A` as the subobjects `P` of `B` in `C` for which `A.hom` factors through the image of `P` under `T`. -/ def subobjectEquiv [HasFiniteLimits C] [PreservesFiniteLimits T] (A : StructuredArrow S T) : Subobject A ≃o { P : Subobject A.right // ∃ q, q ≫ T.map P.arrow = A.hom } where toFun P := ⟨projectSubobject P, projectSubobject_factors P⟩ invFun P := liftSubobject P.val P.prop.choose_spec left_inv _ := lift_projectSubobject _ _ right_inv P := Subtype.ext (by simp only [liftSubobject, homMk_right, projectSubobject_mk, Subobject.mk_arrow]) map_rel_iff' := by apply Subobject.ind₂ intro P Q f g hf hg refine ⟨fun h => Subobject.mk_le_mk_of_comm ?_ ?_, fun h => ?_⟩ · exact homMk (Subobject.ofMkLEMk _ _ h) ((cancel_mono (T.map g.right)).1 (by simp [← T.map_comp])) · simp · refine Subobject.mk_le_mk_of_comm (Subobject.ofMkLEMk _ _ h).right ?_ exact congr_arg CommaMorphism.right (Subobject.ofMkLEMk_comp h) /-- If `C` is well-powered and complete and `T` preserves limits, then `StructuredArrow S T` is well-powered. -/ instance wellPowered_structuredArrow [LocallySmall.{w} C] [WellPowered.{w} C] [HasFiniteLimits C] [PreservesFiniteLimits T] : WellPowered.{w} (StructuredArrow S T) where subobject_small X := small_map (subobjectEquiv X).toEquiv end StructuredArrow namespace CostructuredArrow variable {S : C ⥤ D} {T : D} /-- Every quotient of a costructured arrow can be projected to a quotient of the underlying object. -/ def projectQuotient [HasFiniteColimits C] [PreservesFiniteColimits S] {A : CostructuredArrow S T} : Subobject (op A) → Subobject (op A.left) := by refine Subobject.lift (fun P f hf => Subobject.mk f.unop.left.op) ?_ intro P Q f g hf hg i hi refine Subobject.mk_eq_mk_of_comm _ _ ((proj S T).mapIso i.unop).op (Quiver.Hom.unop_inj ?_) have := congr_arg Quiver.Hom.unop hi simpa using congr_arg CommaMorphism.left this @[simp] theorem projectQuotient_mk [HasFiniteColimits C] [PreservesFiniteColimits S] {A : CostructuredArrow S T} {P : (CostructuredArrow S T)ᵒᵖ} (f : P ⟶ op A) [Mono f] : projectQuotient (Subobject.mk f) = Subobject.mk f.unop.left.op := rfl theorem projectQuotient_factors [HasFiniteColimits C] [PreservesFiniteColimits S] {A : CostructuredArrow S T} : ∀ P : Subobject (op A), ∃ q, S.map (projectQuotient P).arrow.unop ≫ q = A.hom := Subobject.ind _ fun P f hf => ⟨S.map (Subobject.underlyingIso _).unop.inv ≫ P.unop.hom, by dsimp rw [← Category.assoc, ← S.map_comp, ← unop_comp] simp⟩ /-- A quotient of the underlying object of a costructured arrow can be lifted to a quotient of the costructured arrow, provided that there is a morphism making the quotient into a costructured arrow. -/ @[simp] def liftQuotient {A : CostructuredArrow S T} (P : Subobject (op A.left)) {q} (hq : S.map P.arrow.unop ≫ q = A.hom) : Subobject (op A) := Subobject.mk (homMk P.arrow.unop hq : A ⟶ mk q).op /-- Technical lemma for `lift_projectQuotient`. -/ @[simp] theorem unop_left_comp_underlyingIso_hom_unop {A : CostructuredArrow S T} {P : (CostructuredArrow S T)ᵒᵖ} (f : P ⟶ op A) [Mono f.unop.left.op] : f.unop.left ≫ (Subobject.underlyingIso f.unop.left.op).hom.unop = (Subobject.mk f.unop.left.op).arrow.unop := by conv_lhs => congr rw [← Quiver.Hom.unop_op f.unop.left] rw [← unop_comp, Subobject.underlyingIso_hom_comp_eq_mk] /-- Projecting and then lifting a quotient recovers the original quotient, because there is at most one morphism making the projected quotient into a costructured arrow. -/ theorem lift_projectQuotient [HasFiniteColimits C] [PreservesFiniteColimits S] {A : CostructuredArrow S T} : ∀ (P : Subobject (op A)) {q} (hq : S.map (projectQuotient P).arrow.unop ≫ q = A.hom), liftQuotient (projectQuotient P) hq = P := Subobject.ind _ (by intro P f hf q hq fapply Subobject.mk_eq_mk_of_comm · refine (Iso.op (isoMk ?_ ?_) : _ ≅ op (unop P)) · exact (Subobject.underlyingIso f.unop.left.op).unop · refine (cancel_epi (S.map f.unop.left)).1 ?_ simpa [← Category.assoc, ← S.map_comp] using hq · exact Quiver.Hom.unop_inj (by simp)) /-- Technical lemma for `quotientEquiv`. -/ theorem unop_left_comp_ofMkLEMk_unop {A : CostructuredArrow S T} {P Q : (CostructuredArrow S T)ᵒᵖ} {f : P ⟶ op A} {g : Q ⟶ op A} [Mono f.unop.left.op] [Mono g.unop.left.op] (h : Subobject.mk f.unop.left.op ≤ Subobject.mk g.unop.left.op) : g.unop.left ≫ (Subobject.ofMkLEMk f.unop.left.op g.unop.left.op h).unop = f.unop.left := by conv_lhs => congr rw [← Quiver.Hom.unop_op g.unop.left] rw [← unop_comp] simp only [Subobject.ofMkLEMk_comp, Quiver.Hom.unop_op] /-- If `A : S.obj B ⟶ T` is a costructured arrow for `S : C ⥤ D` and `T : D`, then we can explicitly describe the quotients of `A` as the quotients `P` of `B` in `C` for which `A.hom` factors through the image of `P` under `S`. -/ def quotientEquiv [HasFiniteColimits C] [PreservesFiniteColimits S] (A : CostructuredArrow S T) : Subobject (op A) ≃o { P : Subobject (op A.left) // ∃ q, S.map P.arrow.unop ≫ q = A.hom } where toFun P := ⟨projectQuotient P, projectQuotient_factors P⟩ invFun P := liftQuotient P.val P.prop.choose_spec left_inv _ := lift_projectQuotient _ _ right_inv P := Subtype.ext (by simp only [liftQuotient, Quiver.Hom.unop_op, homMk_left, Quiver.Hom.op_unop, projectQuotient_mk, Subobject.mk_arrow]) map_rel_iff' := by apply Subobject.ind₂ intro P Q f g hf hg refine ⟨fun h => Subobject.mk_le_mk_of_comm ?_ ?_, fun h => ?_⟩ · refine (homMk (Subobject.ofMkLEMk _ _ h).unop ((cancel_epi (S.map g.unop.left)).1 ?_)).op dsimp simp only [← S.map_comp_assoc, unop_left_comp_ofMkLEMk_unop, unop_op, CommaMorphism.w, Functor.const_obj_obj, right_eq_id, Functor.const_obj_map, Category.comp_id] · apply Quiver.Hom.unop_inj ext exact unop_left_comp_ofMkLEMk_unop _ · refine Subobject.mk_le_mk_of_comm (Subobject.ofMkLEMk _ _ h).unop.left.op ?_ refine Quiver.Hom.unop_inj ?_ have := congr_arg Quiver.Hom.unop (Subobject.ofMkLEMk_comp h) simpa only [unop_op, Functor.id_obj, Functor.const_obj_obj, MonoOver.mk'_obj, Over.mk_left, MonoOver.mk'_arrow, unop_comp, Quiver.Hom.unop_op, comp_left] using congr_arg CommaMorphism.left this /-- If `C` is well-copowered and cocomplete and `S` preserves colimits, then `CostructuredArrow S T` is well-copowered. -/ instance well_copowered_costructuredArrow [LocallySmall.{w} C] [WellPowered.{w} Cᵒᵖ] [HasFiniteColimits C] [PreservesFiniteColimits S] : WellPowered.{w} (CostructuredArrow S T)ᵒᵖ where subobject_small X := small_map (quotientEquiv (unop X)).toEquiv end CostructuredArrow end CategoryTheory
Additive.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.Group.Pi.Basic import Mathlib.Algebra.Homology.Single import Mathlib.CategoryTheory.Preadditive.AdditiveFunctor /-! # Homology is an additive functor When `V` is preadditive, `HomologicalComplex V c` is also preadditive, and `homologyFunctor` is additive. -/ universe v u open CategoryTheory CategoryTheory.Category CategoryTheory.Limits HomologicalComplex variable {ι : Type*} variable {V : Type u} [Category.{v} V] [Preadditive V] variable {W : Type*} [Category W] [Preadditive W] variable {W₁ W₂ : Type*} [Category W₁] [Category W₂] [HasZeroMorphisms W₁] [HasZeroMorphisms W₂] variable {c : ComplexShape ι} {C D : HomologicalComplex V c} variable (f : C ⟶ D) (i : ι) namespace HomologicalComplex instance : Zero (C ⟶ D) := ⟨{ f := fun _ => 0 }⟩ instance : Add (C ⟶ D) := ⟨fun f g => { f := fun i => f.f i + g.f i }⟩ instance : Neg (C ⟶ D) := ⟨fun f => { f := fun i => -f.f i }⟩ instance : Sub (C ⟶ D) := ⟨fun f g => { f := fun i => f.f i - g.f i }⟩ instance hasNatScalar : SMul ℕ (C ⟶ D) := ⟨fun n f => { f := fun i => n • f.f i comm' := fun i j _ => by simp [Preadditive.nsmul_comp, Preadditive.comp_nsmul] }⟩ instance hasIntScalar : SMul ℤ (C ⟶ D) := ⟨fun n f => { f := fun i => n • f.f i comm' := fun i j _ => by simp [Preadditive.zsmul_comp, Preadditive.comp_zsmul] }⟩ @[simp] theorem zero_f_apply (i : ι) : (0 : C ⟶ D).f i = 0 := rfl @[simp] theorem add_f_apply (f g : C ⟶ D) (i : ι) : (f + g).f i = f.f i + g.f i := rfl @[simp] theorem neg_f_apply (f : C ⟶ D) (i : ι) : (-f).f i = -f.f i := rfl @[simp] theorem sub_f_apply (f g : C ⟶ D) (i : ι) : (f - g).f i = f.f i - g.f i := rfl @[simp] theorem nsmul_f_apply (n : ℕ) (f : C ⟶ D) (i : ι) : (n • f).f i = n • f.f i := rfl @[simp] theorem zsmul_f_apply (n : ℤ) (f : C ⟶ D) (i : ι) : (n • f).f i = n • f.f i := rfl instance : AddCommGroup (C ⟶ D) := Function.Injective.addCommGroup Hom.f HomologicalComplex.hom_f_injective (by cat_disch) (by cat_disch) (by cat_disch) (by cat_disch) (by cat_disch) (by cat_disch) -- Porting note: proofs had to be provided here, otherwise Lean tries to apply -- `Preadditive.add_comp/comp_add` to `HomologicalComplex V c` instance : Preadditive (HomologicalComplex V c) where add_comp _ _ _ f f' g := by ext simp only [comp_f, add_f_apply] rw [Preadditive.add_comp] comp_add _ _ _ f g g' := by ext simp only [comp_f, add_f_apply] rw [Preadditive.comp_add] /-- The `i`-th component of a chain map, as an additive map from chain maps to morphisms. -/ @[simps!] def Hom.fAddMonoidHom {C₁ C₂ : HomologicalComplex V c} (i : ι) : (C₁ ⟶ C₂) →+ (C₁.X i ⟶ C₂.X i) := AddMonoidHom.mk' (fun f => Hom.f f i) fun _ _ => rfl instance eval_additive (i : ι) : (eval V c i).Additive where end HomologicalComplex namespace CategoryTheory /-- An additive functor induces a functor between homological complexes. This is sometimes called the "prolongation". -/ @[simps] def Functor.mapHomologicalComplex (F : W₁ ⥤ W₂) [F.PreservesZeroMorphisms] (c : ComplexShape ι) : HomologicalComplex W₁ c ⥤ HomologicalComplex W₂ c where obj C := { X := fun i => F.obj (C.X i) d := fun i j => F.map (C.d i j) shape := fun i j w => by rw [C.shape _ _ w, F.map_zero] d_comp_d' := fun i j k _ _ => by rw [← F.map_comp, C.d_comp_d, F.map_zero] } map f := { f := fun i => F.map (f.f i) comm' := fun i j _ => by dsimp rw [← F.map_comp, ← F.map_comp, f.comm] } instance (F : W₁ ⥤ W₂) [F.PreservesZeroMorphisms] (c : ComplexShape ι) : (F.mapHomologicalComplex c).PreservesZeroMorphisms where instance Functor.map_homogical_complex_additive (F : V ⥤ W) [F.Additive] (c : ComplexShape ι) : (F.mapHomologicalComplex c).Additive where variable (W₁) /-- The functor on homological complexes induced by the identity functor is isomorphic to the identity functor. -/ @[simps!] def Functor.mapHomologicalComplexIdIso (c : ComplexShape ι) : (𝟭 W₁).mapHomologicalComplex c ≅ 𝟭 _ := NatIso.ofComponents fun K => Hom.isoOfComponents fun _ => Iso.refl _ instance Functor.mapHomologicalComplex_reflects_iso (F : W₁ ⥤ W₂) [F.PreservesZeroMorphisms] [ReflectsIsomorphisms F] (c : ComplexShape ι) : ReflectsIsomorphisms (F.mapHomologicalComplex c) := ⟨fun f => by intro haveI : ∀ n : ι, IsIso (F.map (f.f n)) := fun n => ((HomologicalComplex.eval W₂ c n).mapIso (asIso ((F.mapHomologicalComplex c).map f))).isIso_hom haveI := fun n => isIso_of_reflects_iso (f.f n) F exact HomologicalComplex.Hom.isIso_of_components f⟩ variable {W₁} /-- A natural transformation between functors induces a natural transformation between those functors applied to homological complexes. -/ @[simps] def NatTrans.mapHomologicalComplex {F G : W₁ ⥤ W₂} [F.PreservesZeroMorphisms] [G.PreservesZeroMorphisms] (α : F ⟶ G) (c : ComplexShape ι) : F.mapHomologicalComplex c ⟶ G.mapHomologicalComplex c where app C := { f := fun _ => α.app _ } @[simp] theorem NatTrans.mapHomologicalComplex_id (c : ComplexShape ι) (F : W₁ ⥤ W₂) [F.PreservesZeroMorphisms] : NatTrans.mapHomologicalComplex (𝟙 F) c = 𝟙 (F.mapHomologicalComplex c) := by cat_disch @[simp] theorem NatTrans.mapHomologicalComplex_comp (c : ComplexShape ι) {F G H : W₁ ⥤ W₂} [F.PreservesZeroMorphisms] [G.PreservesZeroMorphisms] [H.PreservesZeroMorphisms] (α : F ⟶ G) (β : G ⟶ H) : NatTrans.mapHomologicalComplex (α ≫ β) c = NatTrans.mapHomologicalComplex α c ≫ NatTrans.mapHomologicalComplex β c := by cat_disch @[reassoc] theorem NatTrans.mapHomologicalComplex_naturality {c : ComplexShape ι} {F G : W₁ ⥤ W₂} [F.PreservesZeroMorphisms] [G.PreservesZeroMorphisms] (α : F ⟶ G) {C D : HomologicalComplex W₁ c} (f : C ⟶ D) : (F.mapHomologicalComplex c).map f ≫ (NatTrans.mapHomologicalComplex α c).app D = (NatTrans.mapHomologicalComplex α c).app C ≫ (G.mapHomologicalComplex c).map f := by simp /-- A natural isomorphism between functors induces a natural isomorphism between those functors applied to homological complexes. -/ @[simps!] def NatIso.mapHomologicalComplex {F G : W₁ ⥤ W₂} [F.PreservesZeroMorphisms] [G.PreservesZeroMorphisms] (α : F ≅ G) (c : ComplexShape ι) : F.mapHomologicalComplex c ≅ G.mapHomologicalComplex c where hom := NatTrans.mapHomologicalComplex α.hom c inv := NatTrans.mapHomologicalComplex α.inv c hom_inv_id := by simp only [← NatTrans.mapHomologicalComplex_comp, α.hom_inv_id, NatTrans.mapHomologicalComplex_id] inv_hom_id := by simp only [← NatTrans.mapHomologicalComplex_comp, α.inv_hom_id, NatTrans.mapHomologicalComplex_id] /-- An equivalence of categories induces an equivalences between the respective categories of homological complex. -/ @[simps] def Equivalence.mapHomologicalComplex (e : W₁ ≌ W₂) [e.functor.PreservesZeroMorphisms] (c : ComplexShape ι) : HomologicalComplex W₁ c ≌ HomologicalComplex W₂ c where functor := e.functor.mapHomologicalComplex c inverse := e.inverse.mapHomologicalComplex c unitIso := (Functor.mapHomologicalComplexIdIso W₁ c).symm ≪≫ NatIso.mapHomologicalComplex e.unitIso c counitIso := NatIso.mapHomologicalComplex e.counitIso c ≪≫ Functor.mapHomologicalComplexIdIso W₂ c end CategoryTheory namespace ChainComplex variable {α : Type*} [AddRightCancelSemigroup α] [One α] [DecidableEq α] theorem map_chain_complex_of (F : W₁ ⥤ W₂) [F.PreservesZeroMorphisms] (X : α → W₁) (d : ∀ n, X (n + 1) ⟶ X n) (sq : ∀ n, d (n + 1) ≫ d n = 0) : (F.mapHomologicalComplex _).obj (ChainComplex.of X d sq) = ChainComplex.of (fun n => F.obj (X n)) (fun n => F.map (d n)) fun n => by rw [← F.map_comp, sq n, Functor.map_zero] := by refine HomologicalComplex.ext rfl ?_ rintro i j (rfl : j + 1 = i) simp only [CategoryTheory.Functor.mapHomologicalComplex_obj_d, of_d, eqToHom_refl, comp_id, id_comp] end ChainComplex variable [HasZeroObject W₁] [HasZeroObject W₂] namespace HomologicalComplex instance (W : Type*) [Category W] [Preadditive W] [HasZeroObject W] [DecidableEq ι] (j : ι) : (single W c j).Additive where map_add {_ _ f g} := by ext; simp [single] variable (F : W₁ ⥤ W₂) [F.PreservesZeroMorphisms] (c : ComplexShape ι) [DecidableEq ι] /-- Turning an object into a complex supported at `j` then applying a functor is the same as applying the functor then forming the complex. -/ noncomputable def singleMapHomologicalComplex (j : ι) : single W₁ c j ⋙ F.mapHomologicalComplex _ ≅ F ⋙ single W₂ c j := NatIso.ofComponents (fun X => { hom := { f := fun i => if h : i = j then eqToHom (by simp [h]) else 0 } inv := { f := fun i => if h : i = j then eqToHom (by simp [h]) else 0 } hom_inv_id := by ext i dsimp split_ifs with h · simp · rw [zero_comp, ← F.map_id, (isZero_single_obj_X c j X _ h).eq_of_src (𝟙 _) 0, F.map_zero] inv_hom_id := by ext i dsimp split_ifs with h · simp · apply (isZero_single_obj_X c j _ _ h).eq_of_src }) fun f => by ext i dsimp split_ifs with h · subst h simp [single_map_f_self, singleObjXSelf, singleObjXIsoOfEq, eqToHom_map] · apply (isZero_single_obj_X c j _ _ h).eq_of_tgt @[simp] theorem singleMapHomologicalComplex_hom_app_self (j : ι) (X : W₁) : ((singleMapHomologicalComplex F c j).hom.app X).f j = F.map (singleObjXSelf c j X).hom ≫ (singleObjXSelf c j (F.obj X)).inv := by simp [singleMapHomologicalComplex, singleObjXSelf, singleObjXIsoOfEq, eqToHom_map] @[simp] theorem singleMapHomologicalComplex_hom_app_ne {i j : ι} (h : i ≠ j) (X : W₁) : ((singleMapHomologicalComplex F c j).hom.app X).f i = 0 := by simp [singleMapHomologicalComplex, h] @[simp] theorem singleMapHomologicalComplex_inv_app_self (j : ι) (X : W₁) : ((singleMapHomologicalComplex F c j).inv.app X).f j = (singleObjXSelf c j (F.obj X)).hom ≫ F.map (singleObjXSelf c j X).inv := by simp [singleMapHomologicalComplex, singleObjXSelf, singleObjXIsoOfEq, eqToHom_map] @[simp] theorem singleMapHomologicalComplex_inv_app_ne {i j : ι} (h : i ≠ j) (X : W₁) : ((singleMapHomologicalComplex F c j).inv.app X).f i = 0 := by simp [singleMapHomologicalComplex, h] end HomologicalComplex
ArithMult.lean
/- Copyright (c) 2023 Arend Mellendijk. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arend Mellendijk -/ import Mathlib.Tactic.Basic import Mathlib.Tactic.ArithMult.Init /-! # Multiplicativity We define the arith_mult tactic using aesop -/ namespace ArithmeticFunction /-- The `arith_mult` attribute used to tag `IsMultiplicative` statements for the `arith_mult` tactic. -/ macro "arith_mult" : attr => `(attr|aesop safe apply (rule_sets := [$(Lean.mkIdent `IsMultiplicative):ident])) /-- `arith_mult` solves goals of the form `IsMultiplicative f` for `f : ArithmeticFunction R` by applying lemmas tagged with the user attribute `arith_mult`. -/ macro (name := arith_mult) "arith_mult" c:Aesop.tactic_clause* : tactic => `(tactic| { aesop $c* (config := { destructProductsTransparency := .reducible, applyHypsTransparency := .default, introsTransparency? := some .reducible, enableSimp := false } ) (rule_sets := [$(Lean.mkIdent `IsMultiplicative):ident])}) /-- `arith_mult` solves goals of the form `IsMultiplicative f` for `f : ArithmeticFunction R` by applying lemmas tagged with the user attribute `arith_mult`, and prints out the generated proof term. -/ macro (name := arith_mult?) "arith_mult?" c:Aesop.tactic_clause* : tactic => `(tactic| { show_term { arith_mult $c* } }) end ArithmeticFunction
Binomial.lean
/- Copyright (c) 2023 Joachim Breitner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joachim Breitner -/ import Mathlib.Data.Nat.Choose.Sum import Mathlib.Probability.ProbabilityMassFunction.Constructions import Mathlib.Tactic.FinCases /-! # The binomial distribution This file defines the probability mass function of the binomial distribution. ## Main results * `binomial_one_eq_bernoulli`: For `n = 1`, it is equal to `PMF.bernoulli`. -/ namespace PMF open ENNReal NNReal /-- The binomial `PMF`: the probability of observing exactly `i` “heads” in a sequence of `n` independent coin tosses, each having probability `p` of coming up “heads”. -/ def binomial (p : ℝ≥0) (h : p ≤ 1) (n : ℕ) : PMF (Fin (n + 1)) := .ofFintype (fun i => ↑(p^(i : ℕ) * (1-p)^((Fin.last n - i) : ℕ) * (n.choose i : ℕ))) (by dsimp only norm_cast convert (add_pow p (1-p) n).symm · rw [Finset.sum_fin_eq_sum_range] apply Finset.sum_congr rfl intro i hi rw [Finset.mem_range] at hi rw [dif_pos hi] · rw [add_tsub_cancel_of_le (mod_cast h), one_pow]) theorem binomial_apply (p : ℝ≥0) (h : p ≤ 1) (n : ℕ) (i : Fin (n + 1)) : binomial p h n i = p^(i : ℕ) * (1-p)^((Fin.last n - i) : ℕ) * (n.choose i : ℕ) := by simp [binomial] @[simp] theorem binomial_apply_zero (p : ℝ≥0) (h : p ≤ 1) (n : ℕ) : binomial p h n 0 = (1-p)^n := by simp [binomial_apply] @[simp] theorem binomial_apply_last (p : ℝ≥0) (h : p ≤ 1) (n : ℕ) : binomial p h n (.last n) = p^n := by simp [binomial_apply] theorem binomial_apply_self (p : ℝ≥0) (h : p ≤ 1) (n : ℕ) : binomial p h n (.last n) = p^n := by simp /-- The binomial distribution on one coin is the Bernoulli distribution. -/ theorem binomial_one_eq_bernoulli (p : ℝ≥0) (h : p ≤ 1) : binomial p h 1 = (bernoulli p h).map (cond · 1 0) := by ext i; fin_cases i <;> simp [tsum_bool, binomial_apply] end PMF
Hom.lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow, Kexing Ying -/ import Mathlib.Algebra.Algebra.Bilinear import Mathlib.LinearAlgebra.Basis.Defs import Mathlib.LinearAlgebra.BilinearForm.Basic import Mathlib.LinearAlgebra.BilinearMap /-! # Bilinear form and linear maps This file describes the relation between bilinear forms and linear maps. ## TODO A lot of this file is now redundant following the replacement of the dedicated `_root_.BilinForm` structure with `LinearMap.BilinForm`, which is just an alias for `M →ₗ[R] M →ₗ[R] R`. For example `LinearMap.BilinForm.toLinHom` is now just the identity map. This redundant code should be removed. ## Notations Given any term `B` of type `BilinForm`, due to a coercion, can use the notation `B x y` to refer to the function field, ie. `B x y = B.bilin x y`. In this file we use the following type variables: - `M`, `M'`, ... are modules over the commutative semiring `R`, - `M₁`, `M₁'`, ... are modules over the commutative ring `R₁`, - `V`, ... is a vector space over the field `K`. ## References * <https://en.wikipedia.org/wiki/Bilinear_form> ## Tags Bilinear form, -/ open LinearMap (BilinForm) open LinearMap (BilinMap) open Module universe u v w variable {R : Type*} {M : Type*} [CommSemiring R] [AddCommMonoid M] [Module R M] variable {R₁ : Type*} {M₁ : Type*} [CommRing R₁] [AddCommGroup M₁] [Module R₁ M₁] variable {V : Type*} {K : Type*} [Field K] [AddCommGroup V] [Module K V] variable {B : BilinForm R M} {B₁ : BilinForm R₁ M₁} namespace LinearMap namespace BilinForm section ToLin' /-- Auxiliary definition to define `toLinHom`; see below. -/ def toLinHomAux₁ (A : BilinForm R M) (x : M) : M →ₗ[R] R := A x variable (B) theorem sum_left {α} (t : Finset α) (g : α → M) (w : M) : B (∑ i ∈ t, g i) w = ∑ i ∈ t, B (g i) w := B.map_sum₂ t g w variable (w : M) theorem sum_right {α} (t : Finset α) (w : M) (g : α → M) : B w (∑ i ∈ t, g i) = ∑ i ∈ t, B w (g i) := map_sum _ _ _ theorem sum_apply {α} (t : Finset α) (B : α → BilinForm R M) (v w : M) : (∑ i ∈ t, B i) v w = ∑ i ∈ t, B i v w := by simp only [coeFn_sum, Finset.sum_apply] variable {B} /-- The linear map obtained from a `BilinForm` by fixing the right co-ordinate and evaluating in the left. -/ def toLinHomFlip : BilinForm R M →ₗ[R] M →ₗ[R] M →ₗ[R] R := flipHom.toLinearMap theorem toLin'Flip_apply (A : BilinForm R M) (x : M) : toLinHomFlip (M := M) A x = fun y => A y x := rfl end ToLin' end BilinForm end LinearMap namespace LinearMap variable {R' : Type*} [CommSemiring R'] [Algebra R' R] [Module R' M] [IsScalarTower R' R M] /-- Apply a linear map on the output of a bilinear form. -/ @[simps!] def compBilinForm (f : R →ₗ[R'] R') (B : BilinForm R M) : BilinForm R' M := compr₂ (restrictScalars₁₂ R' R' B) f end LinearMap namespace LinearMap namespace BilinForm section Comp variable {M' : Type w} [AddCommMonoid M'] [Module R M'] /-- Apply a linear map on the left and right argument of a bilinear form. -/ def comp (B : BilinForm R M') (l r : M →ₗ[R] M') : BilinForm R M := B.compl₁₂ l r /-- Apply a linear map to the left argument of a bilinear form. -/ def compLeft (B : BilinForm R M) (f : M →ₗ[R] M) : BilinForm R M := B.comp f LinearMap.id /-- Apply a linear map to the right argument of a bilinear form. -/ def compRight (B : BilinForm R M) (f : M →ₗ[R] M) : BilinForm R M := B.comp LinearMap.id f theorem comp_comp {M'' : Type*} [AddCommMonoid M''] [Module R M''] (B : BilinForm R M'') (l r : M →ₗ[R] M') (l' r' : M' →ₗ[R] M'') : (B.comp l' r').comp l r = B.comp (l'.comp l) (r'.comp r) := rfl @[simp] theorem compLeft_compRight (B : BilinForm R M) (l r : M →ₗ[R] M) : (B.compLeft l).compRight r = B.comp l r := rfl @[simp] theorem compRight_compLeft (B : BilinForm R M) (l r : M →ₗ[R] M) : (B.compRight r).compLeft l = B.comp l r := rfl @[simp] theorem comp_apply (B : BilinForm R M') (l r : M →ₗ[R] M') (v w) : B.comp l r v w = B (l v) (r w) := rfl @[simp] theorem compLeft_apply (B : BilinForm R M) (f : M →ₗ[R] M) (v w) : B.compLeft f v w = B (f v) w := rfl @[simp] theorem compRight_apply (B : BilinForm R M) (f : M →ₗ[R] M) (v w) : B.compRight f v w = B v (f w) := rfl @[simp] theorem comp_id_left (B : BilinForm R M) (r : M →ₗ[R] M) : B.comp LinearMap.id r = B.compRight r := by ext rfl @[simp] theorem comp_id_right (B : BilinForm R M) (l : M →ₗ[R] M) : B.comp l LinearMap.id = B.compLeft l := by ext rfl @[simp] theorem compLeft_id (B : BilinForm R M) : B.compLeft LinearMap.id = B := by ext rfl @[simp] theorem compRight_id (B : BilinForm R M) : B.compRight LinearMap.id = B := by ext rfl -- Shortcut for `comp_id_{left,right}` followed by `comp{Right,Left}_id`, -- Needs higher priority to be applied @[simp high] theorem comp_id_id (B : BilinForm R M) : B.comp LinearMap.id LinearMap.id = B := by ext rfl theorem comp_inj (B₁ B₂ : BilinForm R M') {l r : M →ₗ[R] M'} (hₗ : Function.Surjective l) (hᵣ : Function.Surjective r) : B₁.comp l r = B₂.comp l r ↔ B₁ = B₂ := by constructor <;> intro h · -- B₁.comp l r = B₂.comp l r → B₁ = B₂ ext x y obtain ⟨x', hx⟩ := hₗ x subst hx obtain ⟨y', hy⟩ := hᵣ y subst hy rw [← comp_apply, ← comp_apply, h] · -- B₁ = B₂ → B₁.comp l r = B₂.comp l r rw [h] end Comp variable {M' M'' : Type*} variable [AddCommMonoid M'] [AddCommMonoid M''] [Module R M'] [Module R M''] section congr /-- Apply a linear equivalence on the arguments of a bilinear form. -/ def congr (e : M ≃ₗ[R] M') : BilinForm R M ≃ₗ[R] BilinForm R M' := LinearEquiv.congrRight (LinearEquiv.congrLeft _ _ e) ≪≫ₗ LinearEquiv.congrLeft _ _ e @[simp] theorem congr_apply (e : M ≃ₗ[R] M') (B : BilinForm R M) (x y : M') : congr e B x y = B (e.symm x) (e.symm y) := rfl @[simp] theorem congr_symm (e : M ≃ₗ[R] M') : (congr e).symm = congr e.symm := by ext simp only [congr_apply, LinearEquiv.symm_symm] rfl @[simp] theorem congr_refl : congr (LinearEquiv.refl R M) = LinearEquiv.refl R _ := LinearEquiv.ext fun _ => ext₂ fun _ _ => rfl theorem congr_trans (e : M ≃ₗ[R] M') (f : M' ≃ₗ[R] M'') : (congr e).trans (congr f) = congr (e.trans f) := rfl theorem congr_congr (e : M' ≃ₗ[R] M'') (f : M ≃ₗ[R] M') (B : BilinForm R M) : congr e (congr f B) = congr (f.trans e) B := rfl theorem congr_comp (e : M ≃ₗ[R] M') (B : BilinForm R M) (l r : M'' →ₗ[R] M') : (congr e B).comp l r = B.comp (LinearMap.comp (e.symm : M' →ₗ[R] M) l) (LinearMap.comp (e.symm : M' →ₗ[R] M) r) := rfl theorem comp_congr (e : M' ≃ₗ[R] M'') (B : BilinForm R M) (l r : M' →ₗ[R] M) : congr e (B.comp l r) = B.comp (l.comp (e.symm : M'' →ₗ[R] M')) (r.comp (e.symm : M'' →ₗ[R] M')) := rfl end congr section congrRight₂ variable {N₁ N₂ N₃ : Type*} variable [AddCommMonoid N₁] [AddCommMonoid N₂] [AddCommMonoid N₃] variable [Module R N₁] [Module R N₂] [Module R N₃] /-- When `N₁` and `N₂` are equivalent, bilinear maps on `M` into `N₁` are equivalent to bilinear maps into `N₂`. -/ def _root_.LinearEquiv.congrRight₂ (e : N₁ ≃ₗ[R] N₂) : BilinMap R M N₁ ≃ₗ[R] BilinMap R M N₂ := LinearEquiv.congrRight (LinearEquiv.congrRight e) @[simp] theorem _root_.LinearEquiv.congrRight₂_apply (e : N₁ ≃ₗ[R] N₂) (B : BilinMap R M N₁) : LinearEquiv.congrRight₂ e B = compr₂ B e := rfl @[simp] theorem _root_.LinearEquiv.congrRight₂_refl : LinearEquiv.congrRight₂ (.refl R N₁) = .refl R (BilinMap R M N₁) := rfl @[simp] theorem _root_.LinearEquiv.congrRight_symm (e : N₁ ≃ₗ[R] N₂) : (LinearEquiv.congrRight₂ e (M := M)).symm = LinearEquiv.congrRight₂ e.symm := rfl theorem _root_.LinearEquiv.congrRight₂_trans (e₁₂ : N₁ ≃ₗ[R] N₂) (e₂₃ : N₂ ≃ₗ[R] N₃) : LinearEquiv.congrRight₂ (M := M) (e₁₂ ≪≫ₗ e₂₃) = LinearEquiv.congrRight₂ e₁₂ ≪≫ₗ LinearEquiv.congrRight₂ e₂₃ := rfl end congrRight₂ section LinMulLin /-- `linMulLin f g` is the bilinear form mapping `x` and `y` to `f x * g y` -/ def linMulLin (f g : M →ₗ[R] R) : BilinForm R M := (LinearMap.mul R R).compl₁₂ f g variable {f g : M →ₗ[R] R} @[simp] theorem linMulLin_apply (x y) : linMulLin f g x y = f x * g y := rfl @[simp] theorem linMulLin_comp (l r : M' →ₗ[R] M) : (linMulLin f g).comp l r = linMulLin (f.comp l) (g.comp r) := rfl @[simp] theorem linMulLin_compLeft (l : M →ₗ[R] M) : (linMulLin f g).compLeft l = linMulLin (f.comp l) g := rfl @[simp] theorem linMulLin_compRight (r : M →ₗ[R] M) : (linMulLin f g).compRight r = linMulLin f (g.comp r) := rfl end LinMulLin section Basis variable {F₂ : BilinForm R M} variable {ι : Type*} (b : Basis ι R M) /-- Two bilinear forms are equal when they are equal on all basis vectors. -/ theorem ext_basis (h : ∀ i j, B (b i) (b j) = F₂ (b i) (b j)) : B = F₂ := b.ext fun i => b.ext fun j => h i j /-- Write out `B x y` as a sum over `B (b i) (b j)` if `b` is a basis. -/ theorem sum_repr_mul_repr_mul (x y : M) : ((b.repr x).sum fun i xi => (b.repr y).sum fun j yj => xi • yj • B (b i) (b j)) = B x y := by conv_rhs => rw [← b.linearCombination_repr x, ← b.linearCombination_repr y] simp_rw [Finsupp.linearCombination_apply, Finsupp.sum, sum_left, sum_right, smul_left, smul_right, smul_eq_mul] end Basis end BilinForm end LinearMap
IsField.lean
/- Copyright (c) 2014 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.Field.Defs import Mathlib.Tactic.Common /-! # `IsField` predicate Predicate on a (semi)ring that it is a (semi)field, i.e. that the multiplication is commutative, that it has more than one element and that all non-zero elements have a multiplicative inverse. In contrast to `Field`, which contains the data of a function associating to an element of the field its multiplicative inverse, this predicate only assumes the existence and can therefore more easily be used to e.g. transfer along ring isomorphisms. -/ universe u section IsField /-- A predicate to express that a (semi)ring is a (semi)field. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. Additionally, this is useful when trying to prove that a particular ring structure extends to a (semi)field. -/ structure IsField (R : Type u) [Semiring R] : Prop where /-- For a semiring to be a field, it must have two distinct elements. -/ exists_pair_ne : ∃ x y : R, x ≠ y /-- Fields are commutative. -/ mul_comm : ∀ x y : R, x * y = y * x /-- Nonzero elements have multiplicative inverses. -/ mul_inv_cancel : ∀ {a : R}, a ≠ 0 → ∃ b, a * b = 1 /-- Transferring from `Semifield` to `IsField`. -/ theorem Semifield.toIsField (R : Type u) [Semifield R] : IsField R where __ := ‹Semifield R› mul_inv_cancel {a} ha := ⟨a⁻¹, mul_inv_cancel₀ ha⟩ /-- Transferring from `Field` to `IsField`. -/ theorem Field.toIsField (R : Type u) [Field R] : IsField R := Semifield.toIsField _ @[simp] theorem IsField.nontrivial {R : Type u} [Semiring R] (h : IsField R) : Nontrivial R := ⟨h.exists_pair_ne⟩ lemma IsField.isDomain {R : Type u} [Semiring R] (h : IsField R) : IsDomain R where mul_left_cancel_of_ne_zero ha _ _ hb := by obtain ⟨x, hx⟩ := h.mul_inv_cancel ha simpa [← mul_assoc, h.mul_comm, hx] using congr_arg (x * ·) hb mul_right_cancel_of_ne_zero ha _ _ hb := by obtain ⟨x, hx⟩ := h.mul_inv_cancel ha simpa [mul_assoc, hx] using congr_arg (· * x) hb exists_pair_ne := h.exists_pair_ne instance {R : Type u} [Semifield R] : IsDomain R := (Semifield.toIsField _).isDomain @[simp] theorem not_isField_of_subsingleton (R : Type u) [Semiring R] [Subsingleton R] : ¬IsField R := fun h => let ⟨_, _, h⟩ := h.exists_pair_ne h (Subsingleton.elim _ _) open Classical in /-- Transferring from `IsField` to `Semifield`. -/ noncomputable def IsField.toSemifield {R : Type u} [Semiring R] (h : IsField R) : Semifield R where __ := ‹Semiring R› __ := h inv a := if ha : a = 0 then 0 else Classical.choose (h.mul_inv_cancel ha) inv_zero := dif_pos rfl mul_inv_cancel a ha := by convert Classical.choose_spec (h.mul_inv_cancel ha); exact dif_neg ha nnqsmul := _ nnqsmul_def _ _ := rfl /-- Transferring from `IsField` to `Field`. -/ noncomputable def IsField.toField {R : Type u} [Ring R] (h : IsField R) : Field R where __ := (‹Ring R›:) -- this also works without the `( :)`, but it's slow __ := h.toSemifield qsmul := _ qsmul_def := fun _ _ => rfl /-- For each field, and for each nonzero element of said field, there is a unique inverse. Since `IsField` doesn't remember the data of an `inv` function and as such, a lemma that there is a unique inverse could be useful. -/ theorem uniq_inv_of_isField (R : Type u) [Ring R] (hf : IsField R) : ∀ x : R, x ≠ 0 → ∃! y : R, x * y = 1 := by intro x hx apply existsUnique_of_exists_of_unique · exact hf.mul_inv_cancel hx · intro y z hxy hxz calc y = y * (x * z) := by rw [hxz, mul_one] _ = x * y * z := by rw [← mul_assoc, hf.mul_comm y x] _ = z := by rw [hxy, one_mul] end IsField
Basic.lean
/- Copyright (c) 2023 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Etienne Marion -/ import Mathlib.Topology.Homeomorph.Lemmas import Mathlib.Topology.Filter /-! # Proper maps between topological spaces This file develops the basic theory of proper maps between topological spaces. A map `f : X → Y` between two topological spaces is said to be **proper** if it is continuous and satisfies the following equivalent conditions: 1. `f` is closed and has compact fibers. 2. `f` is **universally closed**, in the sense that for any topological space `Z`, the map `Prod.map f id : X × Z → Y × Z` is closed. 3. For any `ℱ : Filter X`, all cluster points of `map f ℱ` are images by `f` of some cluster point of `ℱ`. We take 3 as the definition in `IsProperMap`, and we show the equivalence with 1, 2, and some other variations. ## Main statements * `isProperMap_iff_ultrafilter`: characterization of proper maps in terms of limits of ultrafilters instead of cluster points of filters. * `IsProperMap.pi_map`: any product of proper maps is proper. * `isProperMap_iff_isClosedMap_and_compact_fibers`: a map is proper if and only if it is continuous, closed, and has compact fibers ## Implementation notes In algebraic geometry, it is common to also ask that proper maps are *separated*, in the sense of [Stacks: definition OCY1](https://stacks.math.columbia.edu/tag/0CY1). We don't follow this convention because it is unclear whether it would give the right notion in all cases, and in particular for the theory of proper group actions. That means that our terminology does **NOT** align with that of [Stacks: Characterizing proper maps](https://stacks.math.columbia.edu/tag/005M), instead our definition of `IsProperMap` coincides with what they call "Bourbaki-proper". Regarding the proofs, we don't really follow Bourbaki and go for more filter-heavy proofs, as usual. In particular, their arguments rely heavily on restriction of closed maps (see `IsClosedMap.restrictPreimage`), which makes them somehow annoying to formalize in type theory. In contrast, the filter-based proofs work really well thanks to the existing API. In fact, the filter proofs work so well that I thought this would be a great pedagogical resource about how we use filters. For that reason, **all interesting proofs in this file are commented**, so don't hesitate to have a look! ## TODO * prove the equivalence with condition 3 of [Stacks: Theorem 005R](https://stacks.math.columbia.edu/tag/005R). Note that they mean something different by "universally closed". ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [Stacks: Characterizing proper maps](https://stacks.math.columbia.edu/tag/005M) -/ assert_not_exists StoneCech open Filter Topology Function Set open Prod (fst snd) variable {X Y Z W ι : Type*} [TopologicalSpace X] [TopologicalSpace Y] [TopologicalSpace Z] [TopologicalSpace W] {f : X → Y} {g : Y → Z} universe u v /-- A map `f : X → Y` between two topological spaces is said to be **proper** if it is continuous and, for all `ℱ : Filter X`, any cluster point of `map f ℱ` is the image by `f` of a cluster point of `ℱ`. -/ @[mk_iff isProperMap_iff_clusterPt, fun_prop] structure IsProperMap (f : X → Y) : Prop extends Continuous f where /-- By definition, if `f` is a proper map and `ℱ` is any filter on `X`, then any cluster point of `map f ℱ` is the image by `f` of some cluster point of `ℱ`. -/ clusterPt_of_mapClusterPt : ∀ ⦃ℱ : Filter X⦄, ∀ ⦃y : Y⦄, MapClusterPt y ℱ f → ∃ x, f x = y ∧ ClusterPt x ℱ /-- Definition of proper maps. See also `isClosedMap_iff_clusterPt` for a related criterion for closed maps. -/ add_decl_doc isProperMap_iff_clusterPt /-- By definition, a proper map is continuous. -/ @[fun_prop] lemma IsProperMap.continuous (h : IsProperMap f) : Continuous f := h.toContinuous /-- A proper map is closed. -/ lemma IsProperMap.isClosedMap (h : IsProperMap f) : IsClosedMap f := by rw [isClosedMap_iff_clusterPt] exact fun s y ↦ h.clusterPt_of_mapClusterPt (ℱ := 𝓟 s) (y := y) /-- Characterization of proper maps by ultrafilters. -/ lemma isProperMap_iff_ultrafilter : IsProperMap f ↔ Continuous f ∧ ∀ ⦃𝒰 : Ultrafilter X⦄, ∀ ⦃y : Y⦄, Tendsto f 𝒰 (𝓝 y) → ∃ x, f x = y ∧ 𝒰 ≤ 𝓝 x := by -- This is morally trivial since ultrafilters give all the information about cluster points. rw [isProperMap_iff_clusterPt] refine and_congr_right (fun _ ↦ ?_) constructor <;> intro H · intro 𝒰 y (hY : (Ultrafilter.map f 𝒰 : Filter Y) ≤ _) simp_rw [← Ultrafilter.clusterPt_iff] at hY ⊢ exact H hY · simp_rw [MapClusterPt, ClusterPt, ← Filter.push_pull', map_neBot_iff, ← exists_ultrafilter_iff, forall_exists_index] intro ℱ y 𝒰 hy rcases H (tendsto_iff_comap.mpr <| hy.trans inf_le_left) with ⟨x, hxy, hx⟩ exact ⟨x, hxy, 𝒰, le_inf hx (hy.trans inf_le_right)⟩ lemma isProperMap_iff_ultrafilter_of_t2 [T2Space Y] : IsProperMap f ↔ Continuous f ∧ ∀ ⦃𝒰 : Ultrafilter X⦄, ∀ ⦃y : Y⦄, Tendsto f 𝒰 (𝓝 y) → ∃ x, 𝒰.1 ≤ 𝓝 x := isProperMap_iff_ultrafilter.trans <| and_congr_right fun hc ↦ forall₃_congr fun _𝒰 _y hy ↦ exists_congr fun x ↦ and_iff_right_of_imp fun h ↦ tendsto_nhds_unique ((hc.tendsto x).mono_left h) hy /-- If `f` is proper and converges to `y` along some ultrafilter `𝒰`, then `𝒰` converges to some `x` such that `f x = y`. -/ lemma IsProperMap.ultrafilter_le_nhds_of_tendsto (h : IsProperMap f) ⦃𝒰 : Ultrafilter X⦄ ⦃y : Y⦄ (hy : Tendsto f 𝒰 (𝓝 y)) : ∃ x, f x = y ∧ 𝒰 ≤ 𝓝 x := (isProperMap_iff_ultrafilter.mp h).2 hy /-- The composition of two proper maps is proper. -/ lemma IsProperMap.comp (hf : IsProperMap f) (hg : IsProperMap g) : IsProperMap (g ∘ f) := by refine ⟨by fun_prop, fun ℱ z h ↦ ?_⟩ rw [mapClusterPt_comp] at h rcases hg.clusterPt_of_mapClusterPt h with ⟨y, rfl, hy⟩ rcases hf.clusterPt_of_mapClusterPt hy with ⟨x, rfl, hx⟩ use x, rfl /-- If the composition of two continuous functions `g ∘ f` is proper and `f` is surjective, then `g` is proper. -/ lemma isProperMap_of_comp_of_surj (hf : Continuous f) (hg : Continuous g) (hgf : IsProperMap (g ∘ f)) (f_surj : f.Surjective) : IsProperMap g := by refine ⟨hg, fun ℱ z h ↦ ?_⟩ rw [← ℱ.map_comap_of_surjective f_surj, ← mapClusterPt_comp] at h rcases hgf.clusterPt_of_mapClusterPt h with ⟨x, rfl, hx⟩ rw [← ℱ.map_comap_of_surjective f_surj] exact ⟨f x, rfl, hx.map hf.continuousAt tendsto_map⟩ /-- If the composition of two continuous functions `g ∘ f` is proper and `g` is injective, then `f` is proper. -/ lemma isProperMap_of_comp_of_inj {f : X → Y} {g : Y → Z} (hf : Continuous f) (hg : Continuous g) (hgf : IsProperMap (g ∘ f)) (g_inj : g.Injective) : IsProperMap f := by refine ⟨hf, fun ℱ y h ↦ ?_⟩ rcases hgf.clusterPt_of_mapClusterPt (h.map hg.continuousAt tendsto_map) with ⟨x, hx1, hx2⟩ exact ⟨x, g_inj hx1, hx2⟩ /-- If the composition of two continuous functions `f : X → Y` and `g : Y → Z` is proper and `Y` is T2, then `f` is proper. -/ lemma isProperMap_of_comp_of_t2 [T2Space Y] (hf : Continuous f) (hg : Continuous g) (hgf : IsProperMap (g ∘ f)) : IsProperMap f := by rw [isProperMap_iff_ultrafilter_of_t2] refine ⟨hf, fun 𝒰 y h ↦ ?_⟩ rw [isProperMap_iff_ultrafilter] at hgf rcases hgf.2 ((hg.tendsto y).comp h) with ⟨x, -, hx⟩ exact ⟨x, hx⟩ /-- A binary product of proper maps is proper. -/ lemma IsProperMap.prodMap {g : Z → W} (hf : IsProperMap f) (hg : IsProperMap g) : IsProperMap (Prod.map f g) := by simp_rw [isProperMap_iff_ultrafilter] at hf hg ⊢ constructor -- Continuity is clear. · exact hf.1.prodMap hg.1 -- Let `𝒰 : Ultrafilter (X × Z)`, and assume that `f × g` tends to some `(y, w) : Y × W` -- along `𝒰`. · intro 𝒰 ⟨y, w⟩ hyw -- That means that `f` tends to `y` along `map fst 𝒰` and `g` tends to `w` along `map snd 𝒰`. simp_rw [nhds_prod_eq, tendsto_prod_iff'] at hyw -- Thus, by properness of `f` and `g`, we get some `x : X` and `z : Z` such that `f x = y`, -- `g z = w`, `map fst 𝒰` tends to `x`, and `map snd 𝒰` tends to `y`. rcases hf.2 (show Tendsto f (Ultrafilter.map fst 𝒰) (𝓝 y) by simpa using hyw.1) with ⟨x, hxy, hx⟩ rcases hg.2 (show Tendsto g (Ultrafilter.map snd 𝒰) (𝓝 w) by simpa using hyw.2) with ⟨z, hzw, hz⟩ -- By the properties of the product topology, that means that `𝒰` tends to `(x, z)`, -- which completes the proof since `(f × g)(x, z) = (y, w)`. refine ⟨⟨x, z⟩, Prod.ext hxy hzw, ?_⟩ rw [nhds_prod_eq, le_prod] exact ⟨hx, hz⟩ /-- Any product of proper maps is proper. -/ lemma IsProperMap.pi_map {X Y : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, TopologicalSpace (Y i)] {f : (i : ι) → X i → Y i} (h : ∀ i, IsProperMap (f i)) : IsProperMap (fun (x : ∀ i, X i) i ↦ f i (x i)) := by simp_rw [isProperMap_iff_ultrafilter] at h ⊢ constructor -- Continuity is clear. · exact continuous_pi fun i ↦ (h i).1.comp (continuous_apply i) -- Let `𝒰 : Ultrafilter (Π i, X i)`, and assume that `Π i, f i` tends to some `y : Π i, Y i` -- along `𝒰`. · intro 𝒰 y hy -- That means that each `f i` tends to `y i` along `map (eval i) 𝒰`. have : ∀ i, Tendsto (f i) (Ultrafilter.map (eval i) 𝒰) (𝓝 (y i)) := by simpa [tendsto_pi_nhds] using hy -- Thus, by properness of all the `f i`s, we can choose some `x : Π i, X i` such that, for all -- `i`, `f i (x i) = y i` and `map (eval i) 𝒰` tends to `x i`. choose x hxy hx using fun i ↦ (h i).2 (this i) -- By the properties of the product topology, that means that `𝒰` tends to `x`, -- which completes the proof since `(Π i, f i) x = y`. refine ⟨x, funext hxy, ?_⟩ rwa [nhds_pi, le_pi] /-- The preimage of a compact set by a proper map is again compact. See also `isProperMap_iff_isCompact_preimage` which proves that this property completely characterizes proper map when the codomain is compactly generated and Hausdorff. -/ lemma IsProperMap.isCompact_preimage (h : IsProperMap f) {K : Set Y} (hK : IsCompact K) : IsCompact (f ⁻¹' K) := by rw [isCompact_iff_ultrafilter_le_nhds] -- Let `𝒰 ≤ 𝓟 (f ⁻¹' K)` an ultrafilter. intro 𝒰 h𝒰 -- In other words, we have `map f 𝒰 ≤ 𝓟 K` rw [← comap_principal, ← map_le_iff_le_comap, ← Ultrafilter.coe_map] at h𝒰 -- Thus, by compactness of `K`, the ultrafilter `map f 𝒰` tends to some `y ∈ K`. rcases hK.ultrafilter_le_nhds _ h𝒰 with ⟨y, hyK, hy⟩ -- Then, by properness of `f`, that means that `𝒰` tends to some `x ∈ f ⁻¹' {y} ⊆ f ⁻¹' K`, -- which completes the proof. rcases h.ultrafilter_le_nhds_of_tendsto hy with ⟨x, rfl, hx⟩ exact ⟨x, hyK, hx⟩ /-- A map is proper if and only if it is closed and its fibers are compact. -/ theorem isProperMap_iff_isClosedMap_and_compact_fibers : IsProperMap f ↔ Continuous f ∧ IsClosedMap f ∧ ∀ y, IsCompact (f ⁻¹' {y}) := by constructor <;> intro H -- Note: In Bourbaki, the direct implication is proved by going through universally closed maps. -- We could do the same (using a `TFAE` cycle) but proving it directly from -- `IsProperMap.isCompact_preimage` is nice enough already so we don't bother with that. · exact ⟨H.continuous, H.isClosedMap, fun y ↦ H.isCompact_preimage isCompact_singleton⟩ · rw [isProperMap_iff_clusterPt] -- Let `ℱ : Filter X` and `y` some cluster point of `map f ℱ`. refine ⟨H.1, fun ℱ y hy ↦ ?_⟩ -- That means that the singleton `pure y` meets the "closure" of `map f ℱ`, by which we mean -- `Filter.lift' (map f ℱ) closure`. But `f` is closed, so -- `closure (map f ℱ) = map f (closure ℱ)` (see `IsClosedMap.lift'_closure_map_eq`). -- Thus `map f (closure ℱ ⊓ 𝓟 (f ⁻¹' {y})) = map f (closure ℱ) ⊓ 𝓟 {y} ≠ ⊥`, hence -- `closure ℱ ⊓ 𝓟 (f ⁻¹' {y}) ≠ ⊥`. rw [H.2.1.mapClusterPt_iff_lift'_closure H.1] at hy -- Now, applying the compactness of `f ⁻¹' {y}` to the nontrivial filter -- `closure ℱ ⊓ 𝓟 (f ⁻¹' {y})`, we obtain that it has a cluster point `x ∈ f ⁻¹' {y}`. rcases H.2.2 y (f := Filter.lift' ℱ closure ⊓ 𝓟 (f ⁻¹' {y})) inf_le_right with ⟨x, hxy, hx⟩ refine ⟨x, hxy, ?_⟩ -- In particular `x` is a cluster point of `closure ℱ`. Since cluster points of `closure ℱ` -- are exactly cluster points of `ℱ` (see `clusterPt_lift'_closure_iff`), this completes -- the proof. rw [← clusterPt_lift'_closure_iff] exact hx.mono inf_le_left /-- An injective and continuous function is proper if and only if it is closed. -/ lemma isProperMap_iff_isClosedMap_of_inj (f_cont : Continuous f) (f_inj : f.Injective) : IsProperMap f ↔ IsClosedMap f := by refine ⟨fun h ↦ h.isClosedMap, fun h ↦ ?_⟩ rw [isProperMap_iff_isClosedMap_and_compact_fibers] exact ⟨f_cont, h, fun y ↦ (subsingleton_singleton.preimage f_inj).isCompact⟩ /-- A injective continuous and closed map is proper. -/ lemma isProperMap_of_isClosedMap_of_inj (f_cont : Continuous f) (f_inj : f.Injective) (f_closed : IsClosedMap f) : IsProperMap f := (isProperMap_iff_isClosedMap_of_inj f_cont f_inj).2 f_closed /-- A homeomorphism is proper. -/ @[simp] lemma Homeomorph.isProperMap (e : X ≃ₜ Y) : IsProperMap e := isProperMap_of_isClosedMap_of_inj e.continuous e.injective e.isClosedMap protected lemma IsHomeomorph.isProperMap (hf : IsHomeomorph f) : IsProperMap f := isProperMap_of_isClosedMap_of_inj hf.continuous hf.injective hf.isClosedMap /-- The identity is proper. -/ @[simp] lemma isProperMap_id : IsProperMap (id : X → X) := IsHomeomorph.id.isProperMap /-- A closed embedding is proper. -/ lemma Topology.IsClosedEmbedding.isProperMap (hf : IsClosedEmbedding f) : IsProperMap f := isProperMap_of_isClosedMap_of_inj hf.continuous hf.injective hf.isClosedMap /-- The coercion from a closed subset is proper. -/ lemma IsClosed.isProperMap_subtypeVal {C : Set X} (hC : IsClosed C) : IsProperMap ((↑) : C → X) := hC.isClosedEmbedding_subtypeVal.isProperMap /-- The restriction of a proper map to a closed subset is proper. -/ lemma IsProperMap.restrict {C : Set X} (hf : IsProperMap f) (hC : IsClosed C) : IsProperMap fun x : C ↦ f x := hC.isProperMap_subtypeVal.comp hf /-- The range of a proper map is closed. -/ lemma IsProperMap.isClosed_range (hf : IsProperMap f) : IsClosed (range f) := hf.isClosedMap.isClosed_range /-- Version of `isProperMap_iff_isClosedMap_and_compact_fibers` in terms of `cofinite` and `cocompact`. Only works when the codomain is `T1`. -/ lemma isProperMap_iff_isClosedMap_and_tendsto_cofinite [T1Space Y] : IsProperMap f ↔ Continuous f ∧ IsClosedMap f ∧ Tendsto f (cocompact X) cofinite := by simp_rw [isProperMap_iff_isClosedMap_and_compact_fibers, Tendsto, le_cofinite_iff_compl_singleton_mem, mem_map, preimage_compl] refine and_congr_right fun f_cont ↦ and_congr_right fun _ ↦ ⟨fun H y ↦ (H y).compl_mem_cocompact, fun H y ↦ ?_⟩ rcases mem_cocompact.mp (H y) with ⟨K, hK, hKy⟩ exact hK.of_isClosed_subset (isClosed_singleton.preimage f_cont) (compl_le_compl_iff_le.mp hKy) /-- A continuous map from a compact space to a T₂ space is a proper map. -/ theorem Continuous.isProperMap [CompactSpace X] [T2Space Y] (hf : Continuous f) : IsProperMap f := isProperMap_iff_isClosedMap_and_tendsto_cofinite.2 ⟨hf, hf.isClosedMap, by simp⟩ /-- A proper map `f : X → Y` is **universally closed**: for any topological space `Z`, the map `Prod.map f id : X × Z → Y × Z` is closed. We will prove in `isProperMap_iff_universally_closed` that proper maps are exactly continuous maps which have this property, but this result should be easier to use because it allows `Z` to live in any universe. -/ theorem IsProperMap.universally_closed (Z) [TopologicalSpace Z] (h : IsProperMap f) : IsClosedMap (Prod.map f id : X × Z → Y × Z) := -- `f × id` is proper as a product of proper maps, hence closed. (h.prodMap isProperMap_id).isClosedMap /-- A map `f : X → Y` is proper if and only if it is continuous and the map `(Prod.map f id : X × Filter X → Y × Filter X)` is closed. This is stronger than `isProperMap_iff_universally_closed` since it shows that there's only one space to check to get properness, but in most cases it doesn't matter. -/ theorem isProperMap_iff_isClosedMap_filter {X : Type u} {Y : Type v} [TopologicalSpace X] [TopologicalSpace Y] {f : X → Y} : IsProperMap f ↔ Continuous f ∧ IsClosedMap (Prod.map f id : X × Filter X → Y × Filter X) := by constructor <;> intro H -- The direct implication is clear. · exact ⟨H.continuous, H.universally_closed _⟩ · rw [isProperMap_iff_ultrafilter] -- Let `𝒰 : Ultrafilter X`, and assume that `f` tends to some `y` along `𝒰`. refine ⟨H.1, fun 𝒰 y hy ↦ ?_⟩ -- In `X × Filter X`, consider the closed set `F := closure {(x, ℱ) | ℱ = pure x}` let F : Set (X × Filter X) := closure {xℱ | xℱ.2 = pure xℱ.1} -- Since `f × id` is closed, the set `(f × id) '' F` is also closed. have := H.2 F isClosed_closure -- Let us show that `(y, 𝒰) ∈ (f × id) '' F`. have : (y, ↑𝒰) ∈ Prod.map f id '' F := -- Note that, by the properties of the topology on `Filter X`, the function `pure : X → Filter X` -- tends to the point `𝒰` of `Filter X` along the filter `𝒰` on `X`. Since `f` tends to `y` along -- `𝒰`, we get that the function `(f, pure) : X → (Y, Filter X)` tends to `(y, 𝒰)` along -- `𝒰`. Furthermore, each `(f, pure)(x) = (f × id)(x, pure x)` is clearly an element of -- the closed set `(f × id) '' F`, thus the limit `(y, 𝒰)` also belongs to that set. this.mem_of_tendsto (hy.prodMk_nhds (Filter.tendsto_pure_self (𝒰 : Filter X))) (Eventually.of_forall fun x ↦ ⟨⟨x, pure x⟩, subset_closure rfl, rfl⟩) -- The above shows that `(y, 𝒰) = (f x, 𝒰)`, for some `x : X` such that `(x, 𝒰) ∈ F`. rcases this with ⟨⟨x, _⟩, hx, ⟨_, _⟩⟩ -- We already know that `f x = y`, so to finish the proof we just have to check that `𝒰` tends -- to `x`. So, for `U ∈ 𝓝 x` arbitrary, let's show that `U ∈ 𝒰`. Since `𝒰` is a ultrafilter, -- it is enough to show that `Uᶜ` is not in `𝒰`. refine ⟨x, rfl, fun U hU ↦ Ultrafilter.compl_notMem_iff.mp fun hUc ↦ ?_⟩ rw [mem_closure_iff_nhds] at hx -- Indeed, if that was the case, the set `V := {𝒢 : Filter X | Uᶜ ∈ 𝒢}` would be a neighborhood -- of `𝒰` in `Filter X`, hence `U ×ˢ V` would be a neighborhood of `(x, 𝒰) : X × Filter X`. -- But recall that `(x, 𝒰) ∈ F = closure {(x, ℱ) | ℱ = pure x}`, so the neighborhood `U ×ˢ V` -- must contain some element of the form `(z, pure z)`. In other words, we have `z ∈ U` and -- `Uᶜ ∈ pure z`, which means `z ∈ Uᶜ` by the definition of pure. -- This is a contradiction, which completes the proof. rcases hx (U ×ˢ {𝒢 | Uᶜ ∈ 𝒢}) (prod_mem_nhds hU (isOpen_setOf_mem.mem_nhds hUc)) with ⟨⟨z, 𝒢⟩, ⟨⟨hz : z ∈ U, hz' : Uᶜ ∈ 𝒢⟩, rfl : 𝒢 = pure z⟩⟩ exact hz' hz
Defs.lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp, Anne Baanen -/ import Mathlib.LinearAlgebra.Finsupp.LinearCombination import Mathlib.Lean.Expr.ExtraRecognizers /-! # Linear independence This file defines linear independence in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define `LinearIndependent R v` as `Function.Injective (Finsupp.linearCombination R v)`. Here `Finsupp.linearCombination` is the linear map sending a function `f : ι →₀ R` with finite support to the linear combination of vectors from `v` with these coefficients. The goal of this file is to define linear independence and to prove that several other statements are equivalent to this one, including `ker (Finsupp.linearCombination R v) = ⊥` and some versions with explicitly written linear combinations. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `LinearIndependent R v` states that the elements of the family `v` are linearly independent. * `LinearIndepOn R v s` states that the elements of the family `v` indexed by the members of the set `s : Set ι` are linearly independent. * `LinearIndependent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : LinearIndependent R v` (using classical choice). `LinearIndependent.repr hv` is provided as a linear map. * `LinearIndependent.Maximal` states that there exists no linear independent family that strictly includes the given one. ## Main results * `Fintype.linearIndependent_iff`: if `ι` is a finite type, then any function `f : ι → R` has finite support, so we can reformulate the statement using `∑ i : ι, f i • v i` instead of a sum over an auxiliary `s : Finset ι`; ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. If you want to use sets, use the family `(fun x ↦ x : s → M)` given a set `s : Set M`. The lemmas `LinearIndependent.to_subtype_range` and `LinearIndependent.of_subtype_range` connect those two worlds. ## TODO This file contains much more than definitions. Rework proofs to hold in semirings, by avoiding the path through `ker (Finsupp.linearCombination R v) = ⊥`. ## Tags linearly dependent, linear dependence, linearly independent, linear independence -/ assert_not_exists Cardinal noncomputable section open Function Set Submodule universe u' u variable {ι : Type u'} {ι' : Type*} {R : Type*} {K : Type*} {s : Set ι} variable {M : Type*} {M' : Type*} {V : Type u} section Semiring variable {v : ι → M} variable [Semiring R] [AddCommMonoid M] [AddCommMonoid M'] variable [Module R M] [Module R M'] variable (R) (v) /-- `LinearIndependent R v` states the family of vectors `v` is linearly independent over `R`. -/ def LinearIndependent : Prop := Injective (Finsupp.linearCombination R v) open Lean PrettyPrinter.Delaborator SubExpr in /-- Delaborator for `LinearIndependent` that suggests pretty printing with type hints in case the family of vectors is over a `Set`. Type hints look like `LinearIndependent fun (v : ↑s) => ↑v` or `LinearIndependent (ι := ↑s) f`, depending on whether the family is a lambda expression or not. -/ @[app_delab LinearIndependent] def delabLinearIndependent : Delab := whenPPOption getPPNotation <| whenNotPPOption getPPAnalysisSkip <| withOptionAtCurrPos `pp.analysis.skip true do let e ← getExpr guard <| e.isAppOfArity ``LinearIndependent 7 let some _ := (e.getArg! 0).coeTypeSet? | failure let optionsPerPos ← if (e.getArg! 3).isLambda then withNaryArg 3 do return (← read).optionsPerPos.setBool (← getPos) pp.funBinderTypes.name true else withNaryArg 0 do return (← read).optionsPerPos.setBool (← getPos) `pp.analysis.namedArg true withTheReader Context ({· with optionsPerPos}) delab /-- `LinearIndepOn R v s` states that the vectors in the family `v` that are indexed by the elements of `s` are linearly independent over `R`. -/ def LinearIndepOn (s : Set ι) : Prop := LinearIndependent R (fun x : s ↦ v x) variable {R v} theorem LinearIndepOn.linearIndependent {s : Set ι} (h : LinearIndepOn R v s) : LinearIndependent R (fun x : s ↦ v x) := h theorem linearIndependent_iff_injective_finsuppLinearCombination : LinearIndependent R v ↔ Injective (Finsupp.linearCombination R v) := Iff.rfl @[deprecated (since := "2025-03-18")] alias linearIndependent_iff_injective_linearCombination := linearIndependent_iff_injective_finsuppLinearCombination alias ⟨LinearIndependent.finsuppLinearCombination_injective, _⟩ := linearIndependent_iff_injective_finsuppLinearCombination @[deprecated (since := "2025-03-18")] alias LinearIndependent.linearCombination_injective := LinearIndependent.finsuppLinearCombination_injective theorem linearIndependent_iff_injective_fintypeLinearCombination [Fintype ι] : LinearIndependent R v ↔ Injective (Fintype.linearCombination R v) := by simp [← Finsupp.linearCombination_eq_fintype_linearCombination, LinearIndependent] @[deprecated (since := "2025-03-18")] alias Fintype.linearIndependent_iff_injective := linearIndependent_iff_injective_fintypeLinearCombination alias ⟨LinearIndependent.fintypeLinearCombination_injective, _⟩ := linearIndependent_iff_injective_fintypeLinearCombination theorem LinearIndependent.injective [Nontrivial R] (hv : LinearIndependent R v) : Injective v := by simpa [comp_def] using Injective.comp hv (Finsupp.single_left_injective one_ne_zero) theorem LinearIndepOn.injOn [Nontrivial R] (hv : LinearIndepOn R v s) : InjOn v s := injOn_iff_injective.2 <| LinearIndependent.injective hv theorem LinearIndependent.smul_left_injective (hv : LinearIndependent R v) (i : ι) : Injective fun r : R ↦ r • v i := by convert hv.comp (Finsupp.single_injective i); simp theorem LinearIndependent.ne_zero [Nontrivial R] (i : ι) (hv : LinearIndependent R v) : v i ≠ 0 := by intro h have := @hv (Finsupp.single i 1 : ι →₀ R) 0 (by simpa using h) simp at this theorem LinearIndepOn.ne_zero [Nontrivial R] {i : ι} (hv : LinearIndepOn R v s) (hi : i ∈ s) : v i ≠ 0 := LinearIndependent.ne_zero ⟨i, hi⟩ hv theorem LinearIndepOn.zero_notMem_image [Nontrivial R] (hs : LinearIndepOn R v s) : 0 ∉ v '' s := fun ⟨_, hi, h0⟩ ↦ hs.ne_zero hi h0 @[deprecated (since := "2025-05-23")] alias LinearIndepOn.zero_not_mem_image := LinearIndepOn.zero_notMem_image theorem linearIndependent_empty_type [IsEmpty ι] : LinearIndependent R v := injective_of_subsingleton _ @[simp] theorem linearIndependent_zero_iff [Nontrivial R] : LinearIndependent R (0 : ι → M) ↔ IsEmpty ι := ⟨fun h ↦ not_nonempty_iff.1 fun ⟨i⟩ ↦ (h.ne_zero i rfl).elim, fun _ ↦ linearIndependent_empty_type⟩ @[simp] theorem linearIndepOn_zero_iff [Nontrivial R] : LinearIndepOn R (0 : ι → M) s ↔ s = ∅ := linearIndependent_zero_iff.trans isEmpty_coe_sort @[simp] theorem linearIndependent_subsingleton_iff [Nontrivial R] [Subsingleton M] (f : ι → M) : LinearIndependent R f ↔ IsEmpty ι := by rw [Subsingleton.elim f 0, linearIndependent_zero_iff] variable (R M) in theorem linearIndependent_empty : LinearIndependent R (fun x => x : (∅ : Set M) → M) := linearIndependent_empty_type variable (R v) in @[simp] theorem linearIndepOn_empty : LinearIndepOn R v ∅ := linearIndependent_empty_type .. theorem linearIndependent_set_coe_iff : LinearIndependent R (fun x : s ↦ v x) ↔ LinearIndepOn R v s := Iff.rfl @[deprecated (since := "2025-02-20")] alias linearIndependent_set_subtype := linearIndependent_set_coe_iff theorem linearIndependent_subtype_iff {s : Set M} : LinearIndependent R (Subtype.val : s → M) ↔ LinearIndepOn R id s := Iff.rfl theorem linearIndependent_comp_subtype_iff : LinearIndependent R (v ∘ Subtype.val : s → M) ↔ LinearIndepOn R v s := Iff.rfl /-- A subfamily of a linearly independent family (i.e., a composition with an injective map) is a linearly independent family. -/ theorem LinearIndependent.comp (h : LinearIndependent R v) (f : ι' → ι) (hf : Injective f) : LinearIndependent R (v ∘ f) := by simpa [comp_def] using Injective.comp h (Finsupp.mapDomain_injective hf) lemma LinearIndepOn.mono {t s : Set ι} (hs : LinearIndepOn R v s) (h : t ⊆ s) : LinearIndepOn R v t := hs.comp _ <| Set.inclusion_injective h -- This version makes `l₁` and `l₂` explicit. theorem linearIndependent_iffₛ : LinearIndependent R v ↔ ∀ l₁ l₂, Finsupp.linearCombination R v l₁ = Finsupp.linearCombination R v l₂ → l₁ = l₂ := Iff.rfl open Finset in theorem linearIndependent_iff'ₛ : LinearIndependent R v ↔ ∀ s : Finset ι, ∀ f g : ι → R, ∑ i ∈ s, f i • v i = ∑ i ∈ s, g i • v i → ∀ i ∈ s, f i = g i := linearIndependent_iffₛ.trans ⟨fun hv s f g eq i his ↦ by have h := hv (∑ i ∈ s, Finsupp.single i (f i)) (∑ i ∈ s, Finsupp.single i (g i)) <| by simpa only [map_sum, Finsupp.linearCombination_single] using eq have (f : ι → R) : f i = (∑ j ∈ s, Finsupp.single j (f j)) i := calc f i = (Finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (Finsupp.single i (f i)) := by { rw [Finsupp.lapply_apply, Finsupp.single_eq_same] } _ = ∑ j ∈ s, (Finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (Finsupp.single j (f j)) := Eq.symm <| Finset.sum_eq_single i (fun j _hjs hji => by rw [Finsupp.lapply_apply, Finsupp.single_eq_of_ne hji]) fun hnis => hnis.elim his _ = (∑ j ∈ s, Finsupp.single j (f j)) i := (map_sum ..).symm rw [this f, this g, h], fun hv f g hl ↦ Finsupp.ext fun _ ↦ by classical refine _root_.by_contradiction fun hni ↦ hni <| hv (f.support ∪ g.support) f g ?_ _ ?_ · rwa [← sum_subset subset_union_left, ← sum_subset subset_union_right] <;> rintro i - hi <;> rw [Finsupp.notMem_support_iff.mp hi, zero_smul] · contrapose! hni simp_rw [notMem_union, Finsupp.notMem_support_iff] at hni rw [hni.1, hni.2]⟩ theorem linearIndependent_iff''ₛ : LinearIndependent R v ↔ ∀ (s : Finset ι) (f g : ι → R), (∀ i ∉ s, f i = g i) → ∑ i ∈ s, f i • v i = ∑ i ∈ s, g i • v i → ∀ i, f i = g i := by classical exact linearIndependent_iff'ₛ.trans ⟨fun H s f g eq hv i ↦ if his : i ∈ s then H s f g hv i his else eq i his, fun H s f g eq i hi ↦ by convert H s (fun j ↦ if j ∈ s then f j else 0) (fun j ↦ if j ∈ s then g j else 0) (fun j hj ↦ (if_neg hj).trans (if_neg hj).symm) (by simp_rw [ite_smul, zero_smul, Finset.sum_extend_by_zero, eq]) i <;> exact (if_pos hi).symm⟩ theorem not_linearIndependent_iffₛ : ¬LinearIndependent R v ↔ ∃ s : Finset ι, ∃ f g : ι → R, ∑ i ∈ s, f i • v i = ∑ i ∈ s, g i • v i ∧ ∃ i ∈ s, f i ≠ g i := by rw [linearIndependent_iff'ₛ] simp only [exists_prop, not_forall] theorem Fintype.linearIndependent_iffₛ [Fintype ι] : LinearIndependent R v ↔ ∀ f g : ι → R, ∑ i, f i • v i = ∑ i, g i • v i → ∀ i, f i = g i := by simp_rw [linearIndependent_iff_injective_fintypeLinearCombination, Injective, Fintype.linearCombination_apply, funext_iff] theorem Fintype.not_linearIndependent_iffₛ [Fintype ι] : ¬LinearIndependent R v ↔ ∃ f g : ι → R, ∑ i, f i • v i = ∑ i, g i • v i ∧ ∃ i, f i ≠ g i := by simpa using not_iff_not.2 Fintype.linearIndependent_iffₛ lemma linearIndepOn_finset_iffₛ {s : Finset ι} : LinearIndepOn R v s ↔ ∀ f g : ι → R, ∑ i ∈ s, f i • v i = ∑ i ∈ s, g i • v i → ∀ i ∈ s, f i = g i := by classical simp_rw [LinearIndepOn, Fintype.linearIndependent_iffₛ] constructor · rintro hv f g hfg i hi simp_rw [← s.sum_attach] at hfg exact hv (f ∘ Subtype.val) (g ∘ Subtype.val) hfg ⟨i, hi⟩ · rintro hv f g hfg i simpa using hv (fun j ↦ if hj : j ∈ s then f ⟨j, hj⟩ else 0) (fun j ↦ if hj : j ∈ s then g ⟨j, hj⟩ else 0) (by simpa +contextual [← s.sum_attach]) i lemma not_linearIndepOn_finset_iffₛ {s : Finset ι} : ¬LinearIndepOn R v s ↔ ∃ f g : ι → R, ∑ i ∈ s, f i • v i = ∑ i ∈ s, g i • v i ∧ ∃ i ∈ s, f i ≠ g i := by simpa using linearIndepOn_finset_iffₛ.not /-- A family is linearly independent if and only if all of its finite subfamily is linearly independent. -/ theorem linearIndependent_iff_finset_linearIndependent : LinearIndependent R v ↔ ∀ (s : Finset ι), LinearIndependent R (v ∘ (Subtype.val : s → ι)) := ⟨fun H _ ↦ H.comp _ Subtype.val_injective, fun H ↦ linearIndependent_iff'ₛ.2 fun s f g eq i hi ↦ Fintype.linearIndependent_iffₛ.1 (H s) (f ∘ Subtype.val) (g ∘ Subtype.val) (by simpa only [← s.sum_coe_sort] using eq) ⟨i, hi⟩⟩ lemma linearIndepOn_iff_linearIndepOn_finset : LinearIndepOn R v s ↔ ∀ t : Finset ι, ↑t ⊆ s → LinearIndepOn R v t where mp hv t hts := hv.mono hts mpr hv := by rw [LinearIndepOn, linearIndependent_iff_finset_linearIndependent] exact fun t ↦ (hv (t.map <| .subtype _) (by simp)).comp (ι' := t) (fun x ↦ ⟨x, Finset.mem_map_of_mem _ x.2⟩) fun x ↦ by aesop /-- If the image of a family of vectors under a linear map is linearly independent, then so is the original family. -/ theorem LinearIndependent.of_comp (f : M →ₗ[R] M') (hfv : LinearIndependent R (f ∘ v)) : LinearIndependent R v := by rw [LinearIndependent, Finsupp.linearCombination_linear_comp, LinearMap.coe_comp] at hfv exact hfv.of_comp theorem LinearIndepOn.of_comp (f : M →ₗ[R] M') (hfv : LinearIndepOn R (f ∘ v) s) : LinearIndepOn R v s := LinearIndependent.of_comp f hfv /-- If `f` is a linear map injective on the span of the range of `v`, then the family `f ∘ v` is linearly independent if and only if the family `v` is linearly independent. See `LinearMap.linearIndependent_iff_of_disjoint` for the version with `Set.InjOn` replaced by `Disjoint` when working over a ring. -/ protected theorem LinearMap.linearIndependent_iff_of_injOn (f : M →ₗ[R] M') (hf_inj : Set.InjOn f (span R (Set.range v))) : LinearIndependent R (f ∘ v) ↔ LinearIndependent R v := by simp_rw [LinearIndependent, Finsupp.linearCombination_linear_comp, coe_comp] rw [hf_inj.injective_iff] rw [← Finsupp.range_linearCombination, LinearMap.range_coe] protected theorem LinearMap.linearIndepOn_iff_of_injOn (f : M →ₗ[R] M') (hf_inj : Set.InjOn f (span R (v '' s))) : LinearIndepOn R (f ∘ v) s ↔ LinearIndepOn R v s := f.linearIndependent_iff_of_injOn (by rwa [← image_eq_range]) (v := fun i : s ↦ v i) -- TODO : Rename this `LinearIndependent.of_subsingleton`. @[nontriviality] theorem linearIndependent_of_subsingleton [Subsingleton R] : LinearIndependent R v := linearIndependent_iffₛ.2 fun _l _l' _hl => Subsingleton.elim _ _ @[nontriviality] theorem LinearIndepOn.of_subsingleton [Subsingleton R] : LinearIndepOn R v s := linearIndependent_of_subsingleton theorem linearIndependent_equiv (e : ι ≃ ι') {f : ι' → M} : LinearIndependent R (f ∘ e) ↔ LinearIndependent R f := ⟨fun h ↦ comp_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective, fun h ↦ h.comp _ e.injective⟩ theorem linearIndependent_equiv' (e : ι ≃ ι') {f : ι' → M} {g : ι → M} (h : f ∘ e = g) : LinearIndependent R g ↔ LinearIndependent R f := h ▸ linearIndependent_equiv e theorem linearIndepOn_equiv (e : ι ≃ ι') {f : ι' → M} {s : Set ι} : LinearIndepOn R (f ∘ e) s ↔ LinearIndepOn R f (e '' s) := linearIndependent_equiv' (e.image s) <| by simp [funext_iff] @[simp] theorem linearIndepOn_univ : LinearIndepOn R v univ ↔ LinearIndependent R v := linearIndependent_equiv' (Equiv.Set.univ ι) rfl alias ⟨_, LinearIndependent.linearIndepOn⟩ := linearIndepOn_univ theorem linearIndepOn_iff_image {ι} {s : Set ι} {f : ι → M} (hf : Set.InjOn f s) : LinearIndepOn R f s ↔ LinearIndepOn R id (f '' s) := linearIndependent_equiv' (Equiv.Set.imageOfInjOn _ _ hf) rfl @[deprecated (since := "2025-02-14")] alias linearIndependent_image := linearIndepOn_iff_image theorem linearIndepOn_range_iff {ι} {f : ι → ι'} (hf : Injective f) (g : ι' → M) : LinearIndepOn R g (range f) ↔ LinearIndependent R (g ∘ f) := Iff.symm <| linearIndependent_equiv' (Equiv.ofInjective f hf) rfl alias ⟨LinearIndependent.of_linearIndepOn_range, _⟩ := linearIndepOn_range_iff theorem linearIndepOn_id_range_iff {ι} {f : ι → M} (hf : Injective f) : LinearIndepOn R id (range f) ↔ LinearIndependent R f := linearIndepOn_range_iff hf id alias ⟨LinearIndependent.of_linearIndepOn_id_range, _⟩ := linearIndepOn_id_range_iff @[deprecated (since := "2025-02-15")] alias linearIndependent_subtype_range := linearIndepOn_id_range_iff @[deprecated (since := "2025-02-15")] alias LinearIndependent.of_subtype_range := LinearIndependent.of_linearIndepOn_id_range theorem LinearIndependent.linearIndepOn_id (i : LinearIndependent R v) : LinearIndepOn R id (range v) := by simpa using i.comp _ (rangeSplitting_injective v) @[deprecated (since := "2025-02-15")] alias LinearIndependent.to_subtype_range := LinearIndependent.linearIndepOn_id @[deprecated (since := "2025-02-14")] alias LinearIndependent.coe_range := LinearIndependent.linearIndepOn_id /-- A version of `LinearIndependent.linearIndepOn_id` with the set range equality as a hypothesis. -/ theorem LinearIndependent.linearIndepOn_id' (hv : LinearIndependent R v) {t : Set M} (ht : Set.range v = t) : LinearIndepOn R id t := ht ▸ hv.linearIndepOn_id @[deprecated (since := "2025-02-16")] alias LinearIndependent.to_subtype_range' := LinearIndependent.linearIndepOn_id' section Indexed theorem linearIndepOn_iffₛ : LinearIndepOn R v s ↔ ∀ f ∈ Finsupp.supported R R s, ∀ g ∈ Finsupp.supported R R s, Finsupp.linearCombination R v f = Finsupp.linearCombination R v g → f = g := by simp only [LinearIndepOn, linearIndependent_iffₛ, Finsupp.mem_supported, Finsupp.linearCombination_apply, Set.subset_def, Finset.mem_coe] refine ⟨fun h l₁ h₁ l₂ h₂ eq ↦ (Finsupp.subtypeDomain_eq_iff h₁ h₂).1 <| h _ _ <| (Finsupp.sum_subtypeDomain_index h₁).trans eq ▸ (Finsupp.sum_subtypeDomain_index h₂).symm, fun h l₁ l₂ eq ↦ ?_⟩ refine Finsupp.embDomain_injective (Embedding.subtype s) <| h _ ?_ _ ?_ ?_ iterate 2 simpa using fun _ h _ ↦ h simp_rw [Finsupp.embDomain_eq_mapDomain] rwa [Finsupp.sum_mapDomain_index, Finsupp.sum_mapDomain_index] <;> intros <;> simp only [zero_smul, add_smul] @[deprecated (since := "2025-02-15")] alias linearIndependent_comp_subtypeₛ := linearIndepOn_iffₛ /-- An indexed set of vectors is linearly dependent iff there are two distinct `Finsupp.LinearCombination`s of the vectors with the same value. -/ theorem linearDepOn_iff'ₛ : ¬LinearIndepOn R v s ↔ ∃ f g : ι →₀ R, f ∈ Finsupp.supported R R s ∧ g ∈ Finsupp.supported R R s ∧ Finsupp.linearCombination R v f = Finsupp.linearCombination R v g ∧ f ≠ g := by simp [linearIndepOn_iffₛ] @[deprecated (since := "2025-02-15")] alias linearDependent_comp_subtype'ₛ := linearDepOn_iff'ₛ /-- A version of `linearDepOn_iff'ₛ` with `Finsupp.linearCombination` unfolded. -/ theorem linearDepOn_iffₛ : ¬LinearIndepOn R v s ↔ ∃ f g : ι →₀ R, f ∈ Finsupp.supported R R s ∧ g ∈ Finsupp.supported R R s ∧ ∑ i ∈ f.support, f i • v i = ∑ i ∈ g.support, g i • v i ∧ f ≠ g := linearDepOn_iff'ₛ @[deprecated (since := "2025-02-15")] alias linearDependent_comp_subtypeₛ := linearDepOn_iffₛ @[deprecated (since := "2025-02-15")] alias linearIndependent_subtypeₛ := linearIndepOn_iffₛ theorem linearIndependent_restrict_iff : LinearIndependent R (s.restrict v) ↔ LinearIndepOn R v s := Iff.rfl theorem LinearIndepOn.linearIndependent_restrict (hs : LinearIndepOn R v s) : LinearIndependent R (s.restrict v) := hs @[deprecated (since := "2025-02-15")] alias LinearIndependent.restrict_of_comp_subtype := LinearIndepOn.linearIndependent_restrict theorem linearIndepOn_iff_linearCombinationOnₛ : LinearIndepOn R v s ↔ Injective (Finsupp.linearCombinationOn ι M R v s) := by rw [← linearIndependent_restrict_iff] simp [LinearIndependent, Finsupp.linearCombination_restrict] @[deprecated (since := "2025-02-15")] alias linearIndependent_iff_linearCombinationOnₛ := linearIndepOn_iff_linearCombinationOnₛ end Indexed section repr /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ @[simps (rhsMd := default) symm_apply] def LinearIndependent.linearCombinationEquiv (hv : LinearIndependent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := by refine LinearEquiv.ofBijective (LinearMap.codRestrict (span R (range v)) (Finsupp.linearCombination R v) ?_) ⟨hv.codRestrict _, ?_⟩ · simp_rw [← Finsupp.range_linearCombination]; exact fun c ↦ ⟨c, rfl⟩ rw [← LinearMap.range_eq_top, LinearMap.range_eq_map, LinearMap.map_codRestrict, ← LinearMap.range_le_iff_comap, range_subtype, Submodule.map_top, Finsupp.range_linearCombination] -- Porting note: The original theorem generated by `simps` was -- different from the theorem on Lean 3, and not simp-normal form. @[simp] theorem LinearIndependent.linearCombinationEquiv_apply_coe (hv : LinearIndependent R v) (l : ι →₀ R) : hv.linearCombinationEquiv l = Finsupp.linearCombination R v l := rfl /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `LinearIndependent.linearCombinationEquiv`. -/ def LinearIndependent.repr (hv : LinearIndependent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.linearCombinationEquiv.symm variable (hv : LinearIndependent R v) {i : ι} @[simp] theorem LinearIndependent.linearCombination_repr (x) : Finsupp.linearCombination R v (hv.repr x) = x := Subtype.ext_iff.1 (LinearEquiv.apply_symm_apply hv.linearCombinationEquiv x) theorem LinearIndependent.linearCombination_comp_repr : (Finsupp.linearCombination R v).comp hv.repr = Submodule.subtype _ := LinearMap.ext <| hv.linearCombination_repr theorem LinearIndependent.repr_ker : LinearMap.ker hv.repr = ⊥ := by rw [LinearIndependent.repr, LinearEquiv.ker] theorem LinearIndependent.repr_range : LinearMap.range hv.repr = ⊤ := by rw [LinearIndependent.repr, LinearEquiv.range] theorem LinearIndependent.repr_eq {l : ι →₀ R} {x : span R (range v)} (eq : Finsupp.linearCombination R v l = ↑x) : hv.repr x = l := by have : ↑((LinearIndependent.linearCombinationEquiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = Finsupp.linearCombination R v l := rfl have : (LinearIndependent.linearCombinationEquiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x := by rw [eq] at this exact Subtype.ext_iff.2 this rw [← LinearEquiv.symm_apply_apply hv.linearCombinationEquiv l] rw [← this] rfl theorem LinearIndependent.repr_eq_single (i) (x : span R (range v)) (hx : ↑x = v i) : hv.repr x = Finsupp.single i 1 := by apply hv.repr_eq simp [Finsupp.linearCombination_single, hx] theorem LinearIndependent.span_repr_eq [Nontrivial R] (x) : Span.repr R (Set.range v) x = (hv.repr x).equivMapDomain (Equiv.ofInjective _ hv.injective) := by have p : (Span.repr R (Set.range v) x).equivMapDomain (Equiv.ofInjective _ hv.injective).symm = hv.repr x := by apply (LinearIndependent.linearCombinationEquiv hv).injective ext simp only [LinearIndependent.linearCombinationEquiv_apply_coe, Equiv.self_comp_ofInjective_symm, LinearIndependent.linearCombination_repr, Finsupp.linearCombination_equivMapDomain, Span.finsupp_linearCombination_repr] ext ⟨_, ⟨i, rfl⟩⟩ simp [← p] theorem LinearIndependent.eq_zero_of_smul_mem_span (hv : LinearIndependent R v) (i : ι) (a : R) (ha : a • v i ∈ span R (v '' (univ \ {i}))) : a = 0 := by rw [Finsupp.span_image_eq_map_linearCombination, mem_map] at ha rcases ha with ⟨l, hl, e⟩ rw [linearIndependent_iffₛ.1 hv l (Finsupp.single i a) (by simp [e])] at hl by_contra hn exact (notMem_of_mem_diff (hl <| by simp [hn])) (mem_singleton _) @[deprecated (since := "2025-05-13")] alias LinearIndependent.not_smul_mem_span := LinearIndependent.eq_zero_of_smul_mem_span nonrec lemma LinearIndepOn.eq_zero_of_smul_mem_span (hv : LinearIndepOn R v s) (hi : i ∈ s) (a : R) (ha : a • v i ∈ span R (v '' (s \ {i}))) : a = 0 := hv.eq_zero_of_smul_mem_span ⟨i, hi⟩ _ <| by simpa [← comp_def, image_comp, image_diff Subtype.val_injective] variable [Nontrivial R] lemma LinearIndependent.notMem_span (hv : LinearIndependent R v) (i : ι) : v i ∉ span R (v '' {i}ᶜ) := fun hi ↦ one_ne_zero <| hv.eq_zero_of_smul_mem_span i 1 <| by simpa [Set.compl_eq_univ_diff] using hi @[deprecated (since := "2025-05-23")] alias LinearIndependent.not_mem_span := LinearIndependent.notMem_span lemma LinearIndepOn.notMem_span (hv : LinearIndepOn R v s) (hi : i ∈ s) : v i ∉ span R (v '' (s \ {i})) := fun hi' ↦ one_ne_zero <| hv.eq_zero_of_smul_mem_span hi 1 <| by simpa [Set.compl_eq_univ_diff] using hi' @[deprecated (since := "2025-05-23")] alias LinearIndepOn.not_mem_span := LinearIndepOn.notMem_span lemma LinearIndepOn.notMem_span_of_insert (hv : LinearIndepOn R v (insert i s)) (hi : i ∉ s) : v i ∉ span R (v '' s) := by simpa [hi] using hv.notMem_span <| mem_insert .. @[deprecated (since := "2025-05-23")] alias LinearIndepOn.not_mem_span_of_insert := LinearIndepOn.notMem_span_of_insert end repr section Maximal universe v w /-- A linearly independent family is maximal if there is no strictly larger linearly independent family. -/ @[nolint unusedArguments] def LinearIndependent.Maximal {ι : Type w} {R : Type u} [Semiring R] {M : Type v} [AddCommMonoid M] [Module R M] {v : ι → M} (_i : LinearIndependent R v) : Prop := ∀ (s : Set M) (_i' : LinearIndependent R ((↑) : s → M)) (_h : range v ≤ s), range v = s /-- An alternative characterization of a maximal linearly independent family, quantifying over types (in the same universe as `M`) into which the indexing family injects. -/ theorem LinearIndependent.maximal_iff {ι : Type w} {R : Type u} [Semiring R] [Nontrivial R] {M : Type v} [AddCommMonoid M] [Module R M] {v : ι → M} (i : LinearIndependent R v) : i.Maximal ↔ ∀ (κ : Type v) (w : κ → M) (_i' : LinearIndependent R w) (j : ι → κ) (_h : w ∘ j = v), Surjective j := by constructor · rintro p κ w i' j rfl specialize p (range w) i'.linearIndepOn_id (range_comp_subset_range _ _) rw [range_comp, ← image_univ (f := w)] at p exact range_eq_univ.mp (image_injective.mpr i'.injective p) · intro p w i' h specialize p w ((↑) : w → M) i' (fun i => ⟨v i, range_subset_iff.mp h i⟩) (by ext simp) have q := congr_arg (fun s => ((↑) : w → M) '' s) p.range_eq dsimp at q rw [← image_univ, image_image] at q simpa using q end Maximal end Semiring section Module variable {v : ι → M} variable [Ring R] [AddCommGroup M] [AddCommGroup M'] variable [Module R M] [Module R M'] theorem linearIndependent_iff_ker : LinearIndependent R v ↔ LinearMap.ker (Finsupp.linearCombination R v) = ⊥ := LinearMap.ker_eq_bot.symm theorem linearIndependent_iff : LinearIndependent R v ↔ ∀ l, Finsupp.linearCombination R v l = 0 → l = 0 := by simp [linearIndependent_iff_ker, LinearMap.ker_eq_bot'] /-- A version of `linearIndependent_iff` where the linear combination is a `Finset` sum. -/ theorem linearIndependent_iff' : LinearIndependent R v ↔ ∀ s : Finset ι, ∀ g : ι → R, ∑ i ∈ s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := by rw [linearIndependent_iff'ₛ] refine ⟨fun h s f ↦ ?_, fun h s f g ↦ ?_⟩ · convert h s f 0; simp_rw [Pi.zero_apply, zero_smul, Finset.sum_const_zero] · rw [← sub_eq_zero, ← Finset.sum_sub_distrib] convert h s (f - g) using 3 <;> simp only [Pi.sub_apply, sub_smul, sub_eq_zero] /-- A version of `linearIndependent_iff` where the linear combination is a `Finset` sum of a function with support contained in the `Finset`. -/ theorem linearIndependent_iff'' : LinearIndependent R v ↔ ∀ (s : Finset ι) (g : ι → R), (∀ i ∉ s, g i = 0) → ∑ i ∈ s, g i • v i = 0 → ∀ i, g i = 0 := by classical exact linearIndependent_iff'.trans ⟨fun H s g hg hv i => if his : i ∈ s then H s g hv i his else hg i his, fun H s g hg i hi => by convert H s (fun j => if j ∈ s then g j else 0) (fun j hj => if_neg hj) (by simp_rw [ite_smul, zero_smul, Finset.sum_extend_by_zero, hg]) i exact (if_pos hi).symm⟩ theorem linearIndependent_add_smul_iff {c : ι → R} {i : ι} (h₀ : c i = 0) : LinearIndependent R (v + (c · • v i)) ↔ LinearIndependent R v := by simp [linearIndependent_iff_injective_finsuppLinearCombination, ← Finsupp.linearCombination_comp_addSingleEquiv i c h₀] theorem not_linearIndependent_iff : ¬LinearIndependent R v ↔ ∃ s : Finset ι, ∃ g : ι → R, ∑ i ∈ s, g i • v i = 0 ∧ ∃ i ∈ s, g i ≠ 0 := by rw [linearIndependent_iff'] simp only [exists_prop, not_forall] theorem Fintype.linearIndependent_iff [Fintype ι] : LinearIndependent R v ↔ ∀ g : ι → R, ∑ i, g i • v i = 0 → ∀ i, g i = 0 := by refine ⟨fun H g => by simpa using linearIndependent_iff'.1 H Finset.univ g, fun H => linearIndependent_iff''.2 fun s g hg hs i => H _ ?_ _⟩ rw [← hs] refine (Finset.sum_subset (Finset.subset_univ _) fun i _ hi => ?_).symm rw [hg i hi, zero_smul] theorem Fintype.not_linearIndependent_iff [Fintype ι] : ¬LinearIndependent R v ↔ ∃ g : ι → R, ∑ i, g i • v i = 0 ∧ ∃ i, g i ≠ 0 := by simpa using not_iff_not.2 Fintype.linearIndependent_iff lemma linearIndepOn_finset_iff {s : Finset ι} : LinearIndepOn R v s ↔ ∀ f : ι → R, ∑ i ∈ s, f i • v i = 0 → ∀ i ∈ s, f i = 0 := by classical simp_rw [LinearIndepOn, Fintype.linearIndependent_iff] constructor · rintro hv f hf i hi rw [← s.sum_attach] at hf exact hv (f ∘ Subtype.val) hf ⟨i, hi⟩ · rintro hv f hf₀ i simpa using hv (fun j ↦ if hj : j ∈ s then f ⟨j, hj⟩ else 0) (by simpa +contextual [← s.sum_attach]) i lemma not_linearIndepOn_finset_iff {s : Finset ι} : ¬LinearIndepOn R v s ↔ ∃ f : ι → R, ∑ i ∈ s, f i • v i = 0 ∧ ∃ i ∈ s, f i ≠ 0 := by simpa using linearIndepOn_finset_iff.not /-- If the kernel of a linear map is disjoint from the span of a family of vectors, then the family is linearly independent iff it is linearly independent after composing with the linear map. -/ protected theorem LinearMap.linearIndependent_iff_of_disjoint (f : M →ₗ[R] M') (hf_inj : Disjoint (span R (Set.range v)) (LinearMap.ker f)) : LinearIndependent R (f ∘ v) ↔ LinearIndependent R v := f.linearIndependent_iff_of_injOn <| LinearMap.injOn_of_disjoint_ker le_rfl hf_inj section LinearIndepOn /-! The following give equivalent versions of `LinearIndepOn` and its negation. -/ theorem linearIndepOn_iff : LinearIndepOn R v s ↔ ∀ l ∈ Finsupp.supported R R s, (Finsupp.linearCombination R v) l = 0 → l = 0 := linearIndepOn_iffₛ.trans ⟨fun h l hl ↦ h l hl 0 (zero_mem _), fun h f hf g hg eq ↦ sub_eq_zero.mp (h (f - g) (sub_mem hf hg) <| by rw [map_sub, eq, sub_self])⟩ @[deprecated (since := "2025-02-15")] alias linearIndependent_comp_subtype := linearIndepOn_iff @[deprecated (since := "2025-02-15")] alias linearIndependent_subtype := linearIndepOn_iff /-- An indexed set of vectors is linearly dependent iff there is a nontrivial `Finsupp.linearCombination` of the vectors that is zero. -/ theorem linearDepOn_iff' : ¬LinearIndepOn R v s ↔ ∃ f : ι →₀ R, f ∈ Finsupp.supported R R s ∧ Finsupp.linearCombination R v f = 0 ∧ f ≠ 0 := by simp [linearIndepOn_iff] @[deprecated (since := "2025-02-15")] alias linearDependent_comp_subtype' := linearDepOn_iff' /-- A version of `linearDepOn_iff'` with `Finsupp.linearCombination` unfolded. -/ theorem linearDepOn_iff : ¬LinearIndepOn R v s ↔ ∃ f : ι →₀ R, f ∈ Finsupp.supported R R s ∧ ∑ i ∈ f.support, f i • v i = 0 ∧ f ≠ 0 := linearDepOn_iff' @[deprecated (since := "2025-02-15")] alias linearDependent_comp_subtype := linearDepOn_iff theorem linearIndepOn_iff_disjoint : LinearIndepOn R v s ↔ Disjoint (Finsupp.supported R R s) (LinearMap.ker <| Finsupp.linearCombination R v) := by rw [linearIndepOn_iff, LinearMap.disjoint_ker] @[deprecated (since := "2025-02-15")] alias linearIndependent_comp_subtype_disjoint := linearIndepOn_iff_disjoint @[deprecated (since := "2025-02-15")] alias linearIndependent_subtype_disjoint := linearIndepOn_iff_disjoint theorem linearIndepOn_iff_linearCombinationOn : LinearIndepOn R v s ↔ (LinearMap.ker <| Finsupp.linearCombinationOn ι M R v s) = ⊥ := linearIndepOn_iff_linearCombinationOnₛ.trans <| LinearMap.ker_eq_bot (M := Finsupp.supported R R s).symm @[deprecated (since := "2025-02-15")] alias linearIndependent_iff_linearCombinationOn := linearIndepOn_iff_linearCombinationOn /-- A version of `linearIndepOn_iff` where the linear combination is a `Finset` sum. -/ lemma linearIndepOn_iff' : LinearIndepOn R v s ↔ ∀ (t : Finset ι) (g : ι → R), (t : Set ι) ⊆ s → ∑ i ∈ t, g i • v i = 0 → ∀ i ∈ t, g i = 0 := by classical rw [LinearIndepOn, linearIndependent_iff'] refine ⟨fun h t g hts h0 i hit ↦ ?_, fun h t g h0 i hit ↦ ?_⟩ · refine h (t.preimage _ Subtype.val_injective.injOn) (fun i ↦ g i) ?_ ⟨i, hts hit⟩ (by simpa) rwa [t.sum_preimage ((↑) : s → ι) Subtype.val_injective.injOn (fun i ↦ g i • v i)] simp only [Subtype.range_coe_subtype, setOf_mem_eq] exact fun x hxt hxs ↦ (hxs (hts hxt)) |>.elim replace h : ∀ i (hi : i ∈ s), ⟨i, hi⟩ ∈ t → ∀ (h : i ∈ s), g ⟨i, h⟩ = 0 := by simpa [h0] using h (t.image (↑)) (fun i ↦ if hi : i ∈ s then g ⟨i, hi⟩ else 0) apply h _ _ hit /-- A version of `linearIndepOn_iff` where the linear combination is a `Finset` sum of a function with support contained in the `Finset`. -/ lemma linearIndepOn_iff'' : LinearIndepOn R v s ↔ ∀ (t : Finset ι) (g : ι → R), (t : Set ι) ⊆ s → (∀ i ∉ t, g i = 0) → ∑ i ∈ t, g i • v i = 0 → ∀ i ∈ t, g i = 0 := by classical exact linearIndepOn_iff'.trans ⟨fun h t g hts htg h0 ↦ h _ _ hts h0, fun h t g hts h0 ↦ by simpa +contextual [h0] using h t (fun i ↦ if i ∈ t then g i else 0) hts⟩ end LinearIndepOn end Module /-! ### Properties which require `Ring R` -/ section Module variable {v : ι → M} variable [Ring R] [AddCommGroup M] [AddCommGroup M'] variable [Module R M] [Module R M'] open LinearMap theorem linearIndependent_iff_eq_zero_of_smul_mem_span : LinearIndependent R v ↔ ∀ (i : ι) (a : R), a • v i ∈ span R (v '' (univ \ {i})) → a = 0 := ⟨fun hv ↦ hv.eq_zero_of_smul_mem_span, fun H => linearIndependent_iff.2 fun l hl => by ext i; simp only [Finsupp.zero_apply] by_contra hn refine hn (H i _ ?_) refine (Finsupp.mem_span_image_iff_linearCombination R).2 ⟨Finsupp.single i (l i) - l, ?_, ?_⟩ · rw [Finsupp.mem_supported'] intro j hj have hij : j = i := Classical.not_not.1 fun hij : j ≠ i => hj ((mem_diff _).2 ⟨mem_univ _, fun h => hij (eq_of_mem_singleton h)⟩) simp [hij] · simp [hl]⟩ end Module /-! ### Properties which require `DivisionRing K` These can be considered generalizations of properties of linear independence in vector spaces. -/ section Module variable [DivisionRing K] [AddCommGroup V] [Module K V] variable {v : ι → V} {s t : Set ι} {x y : V} open Submodule theorem linearIndependent_iff_notMem_span : LinearIndependent K v ↔ ∀ i, v i ∉ span K (v '' (univ \ {i})) := by apply linearIndependent_iff_eq_zero_of_smul_mem_span.trans constructor · intro h i h_in_span apply one_ne_zero (h i 1 (by simp [h_in_span])) · intro h i a ha by_contra ha' exact False.elim (h _ ((smul_mem_iff _ ha').1 ha)) @[deprecated (since := "2025-05-23")] alias linearIndependent_iff_not_mem_span := linearIndependent_iff_notMem_span lemma linearIndepOn_iff_notMem_span : LinearIndepOn K v s ↔ ∀ i ∈ s, v i ∉ span K (v '' (s \ {i})) := by rw [LinearIndepOn, linearIndependent_iff_notMem_span, ← Function.comp_def] simp_rw [Set.image_comp] simp [Set.image_diff Subtype.val_injective] @[deprecated (since := "2025-05-23")] alias linearIndepOn_iff_not_mem_span := linearIndepOn_iff_notMem_span end Module
Set.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Algebra.Group.Pointwise.Set.Scalar import Mathlib.Algebra.Module.Defs import Mathlib.Algebra.Group.Pointwise.Set.Basic /-! # Pointwise operations of sets in a ring This file proves properties of pointwise operations of sets in a ring. ## Tags set multiplication, set addition, pointwise addition, pointwise multiplication, pointwise subtraction -/ assert_not_exists OrderedAddCommMonoid Field open Function open scoped Pointwise variable {α β : Type*} namespace Set section Monoid variable [Monoid α] [AddGroup β] [DistribMulAction α β] (a : α) (s : Set α) (t : Set β) @[simp] lemma smul_set_neg : a • -t = -(a • t) := by simp_rw [← image_smul, ← image_neg_eq_neg, image_image, smul_neg] @[simp] protected lemma smul_neg : s • -t = -(s • t) := by simp_rw [← image_neg_eq_neg] exact image_image2_right_comm smul_neg end Monoid section Semiring variable [Semiring α] [AddCommMonoid β] [Module α β] lemma add_smul_subset (a b : α) (s : Set β) : (a + b) • s ⊆ a • s + b • s := by rintro _ ⟨x, hx, rfl⟩ simpa only [add_smul] using add_mem_add (smul_mem_smul_set hx) (smul_mem_smul_set hx) end Semiring section Ring variable [Ring α] [AddCommGroup β] [Module α β] (a : α) (s : Set α) (t : Set β) @[simp] lemma neg_smul_set : -a • t = -(a • t) := by simp_rw [← image_smul, ← image_neg_eq_neg, image_image, neg_smul] @[simp] protected lemma neg_smul : -s • t = -(s • t) := by simp_rw [← image_neg_eq_neg] exact image2_image_left_comm neg_smul end Ring end Set
IntegrationByParts.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.Analysis.Calculus.LineDeriv.Basic import Mathlib.MeasureTheory.Integral.IntegralEqImproper /-! # Integration by parts for line derivatives Let `f, g : E → ℝ` be two differentiable functions on a real vector space endowed with a Haar measure. Then `∫ f * g' = - ∫ f' * g`, where `f'` and `g'` denote the derivatives of `f` and `g` in a given direction `v`, provided that `f * g`, `f' * g` and `f * g'` are all integrable. In this file, we prove this theorem as well as more general versions where the multiplication is replaced by a general continuous bilinear form, giving versions both for the line derivative and the Fréchet derivative. These results are derived from the one-dimensional version and a Fubini argument. ## Main statements * `integral_bilinear_hasLineDerivAt_right_eq_neg_left_of_integrable`: integration by parts in terms of line derivatives, with `HasLineDerivAt` assumptions and general bilinear form. * `integral_bilinear_hasFDerivAt_right_eq_neg_left_of_integrable`: integration by parts in terms of Fréchet derivatives, with `HasFDerivAt` assumptions and general bilinear form. * `integral_bilinear_fderiv_right_eq_neg_left_of_integrable`: integration by parts in terms of Fréchet derivatives, written with `fderiv` assumptions and general bilinear form. * `integral_smul_fderiv_eq_neg_fderiv_smul_of_integrable`: integration by parts for scalar action, in terms of Fréchet derivatives, written with `fderiv` assumptions. * `integral_mul_fderiv_eq_neg_fderiv_mul_of_integrable`: integration by parts for scalar multiplication, in terms of Fréchet derivatives, written with `fderiv` assumptions. ## Implementation notes A standard set of assumptions for integration by parts in a finite-dimensional real vector space (without boundary term) is that the functions tend to zero at infinity and have integrable derivatives. In this file, we instead assume that the functions are integrable and have integrable derivatives. These sets of assumptions are not directly comparable (an integrable function with integrable derivative does *not* have to tend to zero at infinity). The one we use is geared towards applications to Fourier transforms. TODO: prove similar theorems assuming that the functions tend to zero at infinity and have integrable derivatives. -/ open MeasureTheory Measure Module Topology variable {E F G W : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [NormedAddCommGroup F] [NormedSpace ℝ F] [NormedAddCommGroup G] [NormedSpace ℝ G] [NormedAddCommGroup W] [NormedSpace ℝ W] [MeasurableSpace E] {μ : Measure E} lemma integral_bilinear_hasLineDerivAt_right_eq_neg_left_of_integrable_aux1 [SigmaFinite μ] {f f' : E × ℝ → F} {g g' : E × ℝ → G} {B : F →L[ℝ] G →L[ℝ] W} (hf'g : Integrable (fun x ↦ B (f' x) (g x)) (μ.prod volume)) (hfg' : Integrable (fun x ↦ B (f x) (g' x)) (μ.prod volume)) (hfg : Integrable (fun x ↦ B (f x) (g x)) (μ.prod volume)) (hf : ∀ x, HasLineDerivAt ℝ f (f' x) x (0, 1)) (hg : ∀ x, HasLineDerivAt ℝ g (g' x) x (0, 1)) : ∫ x, B (f x) (g' x) ∂(μ.prod volume) = - ∫ x, B (f' x) (g x) ∂(μ.prod volume) := calc ∫ x, B (f x) (g' x) ∂(μ.prod volume) = ∫ x, (∫ t, B (f (x, t)) (g' (x, t))) ∂μ := integral_prod _ hfg' _ = ∫ x, (- ∫ t, B (f' (x, t)) (g (x, t))) ∂μ := by apply integral_congr_ae filter_upwards [hf'g.prod_right_ae, hfg'.prod_right_ae, hfg.prod_right_ae] with x hf'gx hfg'x hfgx apply integral_bilinear_hasDerivAt_right_eq_neg_left_of_integrable ?_ ?_ hfg'x hf'gx hfgx · intro t convert (hf (x, t)).scomp_of_eq t ((hasDerivAt_id t).add (hasDerivAt_const t (-t))) (by simp) <;> simp · intro t convert (hg (x, t)).scomp_of_eq t ((hasDerivAt_id t).add (hasDerivAt_const t (-t))) (by simp) <;> simp _ = - ∫ x, B (f' x) (g x) ∂(μ.prod volume) := by rw [integral_neg, integral_prod _ hf'g] variable [BorelSpace E] lemma integral_bilinear_hasLineDerivAt_right_eq_neg_left_of_integrable_aux2 [FiniteDimensional ℝ E] {μ : Measure (E × ℝ)} [IsAddHaarMeasure μ] {f f' : E × ℝ → F} {g g' : E × ℝ → G} {B : F →L[ℝ] G →L[ℝ] W} (hf'g : Integrable (fun x ↦ B (f' x) (g x)) μ) (hfg' : Integrable (fun x ↦ B (f x) (g' x)) μ) (hfg : Integrable (fun x ↦ B (f x) (g x)) μ) (hf : ∀ x, HasLineDerivAt ℝ f (f' x) x (0, 1)) (hg : ∀ x, HasLineDerivAt ℝ g (g' x) x (0, 1)) : ∫ x, B (f x) (g' x) ∂μ = - ∫ x, B (f' x) (g x) ∂μ := by let ν : Measure E := addHaar have A : ν.prod volume = (addHaarScalarFactor (ν.prod volume) μ) • μ := isAddLeftInvariant_eq_smul _ _ have Hf'g : Integrable (fun x ↦ B (f' x) (g x)) (ν.prod volume) := by rw [A]; exact hf'g.smul_measure_nnreal have Hfg' : Integrable (fun x ↦ B (f x) (g' x)) (ν.prod volume) := by rw [A]; exact hfg'.smul_measure_nnreal have Hfg : Integrable (fun x ↦ B (f x) (g x)) (ν.prod volume) := by rw [A]; exact hfg.smul_measure_nnreal rw [isAddLeftInvariant_eq_smul μ (ν.prod volume)] simp [integral_bilinear_hasLineDerivAt_right_eq_neg_left_of_integrable_aux1 Hf'g Hfg' Hfg hf hg] variable [FiniteDimensional ℝ E] [IsAddHaarMeasure μ] /-- **Integration by parts for line derivatives** Version with a general bilinear form `B`. If `B f g` is integrable, as well as `B f' g` and `B f g'` where `f'` and `g'` are derivatives of `f` and `g` in a given direction `v`, then `∫ B f g' = - ∫ B f' g`. -/ theorem integral_bilinear_hasLineDerivAt_right_eq_neg_left_of_integrable {f f' : E → F} {g g' : E → G} {v : E} {B : F →L[ℝ] G →L[ℝ] W} (hf'g : Integrable (fun x ↦ B (f' x) (g x)) μ) (hfg' : Integrable (fun x ↦ B (f x) (g' x)) μ) (hfg : Integrable (fun x ↦ B (f x) (g x)) μ) (hf : ∀ x, HasLineDerivAt ℝ f (f' x) x v) (hg : ∀ x, HasLineDerivAt ℝ g (g' x) x v) : ∫ x, B (f x) (g' x) ∂μ = - ∫ x, B (f' x) (g x) ∂μ := by by_cases hW : CompleteSpace W; swap · simp [integral, hW] rcases eq_or_ne v 0 with rfl | hv · have Hf' x : f' x = 0 := by simpa [(hasLineDerivAt_zero (f := f) (x := x)).lineDeriv] using (hf x).lineDeriv.symm have Hg' x : g' x = 0 := by simpa [(hasLineDerivAt_zero (f := g) (x := x)).lineDeriv] using (hg x).lineDeriv.symm simp [Hf', Hg'] have : Nontrivial E := nontrivial_iff.2 ⟨v, 0, hv⟩ let n := finrank ℝ E let E' := Fin (n - 1) → ℝ obtain ⟨L, hL⟩ : ∃ L : E ≃L[ℝ] (E' × ℝ), L v = (0, 1) := by have : finrank ℝ (E' × ℝ) = n := by simpa [this, E'] using Nat.sub_add_cancel finrank_pos have L₀ : E ≃L[ℝ] (E' × ℝ) := (ContinuousLinearEquiv.ofFinrankEq this).symm obtain ⟨M, hM⟩ : ∃ M : (E' × ℝ) ≃L[ℝ] (E' × ℝ), M (L₀ v) = (0, 1) := by apply SeparatingDual.exists_continuousLinearEquiv_apply_eq · simpa using hv · simp exact ⟨L₀.trans M, by simp [hM]⟩ let ν := Measure.map L μ suffices H : ∫ (x : E' × ℝ), (B (f (L.symm x))) (g' (L.symm x)) ∂ν = -∫ (x : E' × ℝ), (B (f' (L.symm x))) (g (L.symm x)) ∂ν by have : μ = Measure.map L.symm ν := by simp [ν, Measure.map_map L.symm.continuous.measurable L.continuous.measurable] have hL : IsClosedEmbedding L.symm := L.symm.toHomeomorph.isClosedEmbedding simpa [this, hL.integral_map] using H have L_emb : MeasurableEmbedding L := L.toHomeomorph.measurableEmbedding apply integral_bilinear_hasLineDerivAt_right_eq_neg_left_of_integrable_aux2 · simpa [ν, L_emb.integrable_map_iff, Function.comp_def] using hf'g · simpa [ν, L_emb.integrable_map_iff, Function.comp_def] using hfg' · simpa [ν, L_emb.integrable_map_iff, Function.comp_def] using hfg · intro x have : f = (f ∘ L.symm) ∘ (L : E →ₗ[ℝ] (E' × ℝ)) := by ext y; simp specialize hf (L.symm x) rw [this] at hf convert hf.of_comp using 1 · simp · simp [← hL] · intro x have : g = (g ∘ L.symm) ∘ (L : E →ₗ[ℝ] (E' × ℝ)) := by ext y; simp specialize hg (L.symm x) rw [this] at hg convert hg.of_comp using 1 · simp · simp [← hL] /-- **Integration by parts for Fréchet derivatives** Version with a general bilinear form `B`. If `B f g` is integrable, as well as `B f' g` and `B f g'` where `f'` and `g'` are derivatives of `f` and `g` in a given direction `v`, then `∫ B f g' = - ∫ B f' g`. -/ theorem integral_bilinear_hasFDerivAt_right_eq_neg_left_of_integrable {f : E → F} {f' : E → (E →L[ℝ] F)} {g : E → G} {g' : E → (E →L[ℝ] G)} {v : E} {B : F →L[ℝ] G →L[ℝ] W} (hf'g : Integrable (fun x ↦ B (f' x v) (g x)) μ) (hfg' : Integrable (fun x ↦ B (f x) (g' x v)) μ) (hfg : Integrable (fun x ↦ B (f x) (g x)) μ) (hf : ∀ x, HasFDerivAt f (f' x) x) (hg : ∀ x, HasFDerivAt g (g' x) x) : ∫ x, B (f x) (g' x v) ∂μ = - ∫ x, B (f' x v) (g x) ∂μ := integral_bilinear_hasLineDerivAt_right_eq_neg_left_of_integrable hf'g hfg' hfg (fun x ↦ (hf x).hasLineDerivAt v) (fun x ↦ (hg x).hasLineDerivAt v) /-- **Integration by parts for Fréchet derivatives** Version with a general bilinear form `B`. If `B f g` is integrable, as well as `B f' g` and `B f g'` where `f'` and `g'` are the derivatives of `f` and `g` in a given direction `v`, then `∫ B f g' = - ∫ B f' g`. -/ theorem integral_bilinear_fderiv_right_eq_neg_left_of_integrable {f : E → F} {g : E → G} {v : E} {B : F →L[ℝ] G →L[ℝ] W} (hf'g : Integrable (fun x ↦ B (fderiv ℝ f x v) (g x)) μ) (hfg' : Integrable (fun x ↦ B (f x) (fderiv ℝ g x v)) μ) (hfg : Integrable (fun x ↦ B (f x) (g x)) μ) (hf : Differentiable ℝ f) (hg : Differentiable ℝ g) : ∫ x, B (f x) (fderiv ℝ g x v) ∂μ = - ∫ x, B (fderiv ℝ f x v) (g x) ∂μ := integral_bilinear_hasFDerivAt_right_eq_neg_left_of_integrable hf'g hfg' hfg (fun x ↦ (hf x).hasFDerivAt) (fun x ↦ (hg x).hasFDerivAt) variable {𝕜 : Type*} [NormedField 𝕜] [NormedAlgebra ℝ 𝕜] [NormedSpace 𝕜 G] [IsScalarTower ℝ 𝕜 G] /-- **Integration by parts for Fréchet derivatives** Version with a scalar function: `∫ f • g' = - ∫ f' • g` when `f • g'` and `f' • g` and `f • g` are integrable, where `f'` and `g'` are the derivatives of `f` and `g` in a given direction `v`. -/ theorem integral_smul_fderiv_eq_neg_fderiv_smul_of_integrable {f : E → 𝕜} {g : E → G} {v : E} (hf'g : Integrable (fun x ↦ fderiv ℝ f x v • g x) μ) (hfg' : Integrable (fun x ↦ f x • fderiv ℝ g x v) μ) (hfg : Integrable (fun x ↦ f x • g x) μ) (hf : Differentiable ℝ f) (hg : Differentiable ℝ g) : ∫ x, f x • fderiv ℝ g x v ∂μ = - ∫ x, fderiv ℝ f x v • g x ∂μ := integral_bilinear_fderiv_right_eq_neg_left_of_integrable (B := ContinuousLinearMap.lsmul ℝ 𝕜) hf'g hfg' hfg hf hg /-- **Integration by parts for Fréchet derivatives** Version with two scalar functions: `∫ f * g' = - ∫ f' * g` when `f * g'` and `f' * g` and `f * g` are integrable, where `f'` and `g'` are the derivatives of `f` and `g` in a given direction `v`. -/ theorem integral_mul_fderiv_eq_neg_fderiv_mul_of_integrable {f : E → 𝕜} {g : E → 𝕜} {v : E} (hf'g : Integrable (fun x ↦ fderiv ℝ f x v * g x) μ) (hfg' : Integrable (fun x ↦ f x * fderiv ℝ g x v) μ) (hfg : Integrable (fun x ↦ f x * g x) μ) (hf : Differentiable ℝ f) (hg : Differentiable ℝ g) : ∫ x, f x * fderiv ℝ g x v ∂μ = - ∫ x, fderiv ℝ f x v * g x ∂μ := integral_bilinear_fderiv_right_eq_neg_left_of_integrable (B := ContinuousLinearMap.mul ℝ 𝕜) hf'g hfg' hfg hf hg
Exactness.lean
/- Copyright (c) 2024 Judith Ludwig, Christian Merten. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Judith Ludwig, Christian Merten -/ import Mathlib.Algebra.Exact import Mathlib.RingTheory.AdicCompletion.Functoriality import Mathlib.RingTheory.Filtration /-! # Exactness of adic completion In this file we establish exactness properties of adic completions. In particular we show: ## Main results - `AdicCompletion.map_surjective`: Adic completion preserves surjectivity. - `AdicCompletion.map_injective`: Adic completion preserves injectivity of maps between finite modules over a Noetherian ring. - `AdicCompletion.map_exact`: Over a noetherian ring adic completion is exact on finite modules. ## Implementation details All results are proven directly without using Mittag-Leffler systems. -/ universe u v w t open LinearMap namespace AdicCompletion variable {R : Type u} [CommRing R] {I : Ideal R} section Surjectivity variable {M : Type v} [AddCommGroup M] [Module R M] variable {N : Type w} [AddCommGroup N] [Module R N] variable {f : M →ₗ[R] N} /- In each step, a preimage is constructed from the preimage of the previous step by subtracting this delta. -/ private noncomputable def mapPreimageDelta (hf : Function.Surjective f) (x : AdicCauchySequence I N) {n : ℕ} {y yₙ : M} (hy : f y = x (n + 1)) (hyₙ : f yₙ = x n) : {d : (I ^ n • ⊤ : Submodule R M) | f d = f (yₙ - y) } := have h : f (yₙ - y) ∈ Submodule.map f (I ^ n • ⊤ : Submodule R M) := by rw [Submodule.map_smul'', Submodule.map_top, LinearMap.range_eq_top.2 hf, map_sub, hyₙ, hy, ← Submodule.neg_mem_iff, neg_sub, ← SModEq.sub_mem] exact AdicCauchySequence.mk_eq_mk (Nat.le_succ n) x ⟨⟨h.choose, h.choose_spec.1⟩, h.choose_spec.2⟩ /- Inductively construct preimage of cauchy sequence. -/ private noncomputable def mapPreimage (hf : Function.Surjective f) (x : AdicCauchySequence I N) : (n : ℕ) → f ⁻¹' {x n} | .zero => ⟨(hf (x 0)).choose, (hf (x 0)).choose_spec⟩ | .succ n => let y := (hf (x (n + 1))).choose have hy := (hf (x (n + 1))).choose_spec let ⟨yₙ, (hyₙ : f yₙ = x n)⟩ := mapPreimage hf x n let ⟨⟨d, _⟩, (p : f d = f (yₙ - y))⟩ := mapPreimageDelta hf x hy hyₙ ⟨yₙ - d, by simpa [p]⟩ variable (I) in /-- Adic completion preserves surjectivity -/ theorem map_surjective (hf : Function.Surjective f) : Function.Surjective (map I f) := fun y ↦ by apply AdicCompletion.induction_on I N y (fun b ↦ ?_) let a := mapPreimage hf b refine ⟨AdicCompletion.mk I M (AdicCauchySequence.mk I M (fun n ↦ (a n : M)) ?_), ?_⟩ · refine fun n ↦ SModEq.symm ?_ simp only [SModEq, mapPreimage, Submodule.Quotient.mk_sub, sub_eq_self, Submodule.Quotient.mk_eq_zero, SetLike.coe_mem, a] · exact _root_.AdicCompletion.ext fun n ↦ congrArg _ ((a n).property) end Surjectivity variable {M : Type u} [AddCommGroup M] [Module R M] variable {N : Type u} [AddCommGroup N] [Module R N] variable {P : Type u} [AddCommGroup P] [Module R P] section Injectivity variable [IsNoetherianRing R] [Module.Finite R N] (I) /-- Adic completion preserves injectivity of finite modules over a Noetherian ring. -/ theorem map_injective {f : M →ₗ[R] N} (hf : Function.Injective f) : Function.Injective (map I f) := by obtain ⟨k, hk⟩ := Ideal.exists_pow_inf_eq_pow_smul I (range f) rw [← LinearMap.ker_eq_bot, LinearMap.ker_eq_bot'] intro x apply AdicCompletion.induction_on I M x (fun a ↦ ?_) intro hx refine AdicCompletion.mk_zero_of _ _ _ ⟨42, fun n _ ↦ ⟨n + k, by omega, n, by omega, ?_⟩⟩ rw [← Submodule.comap_map_eq_of_injective hf (I ^ n • ⊤ : Submodule R M), Submodule.map_smul'', Submodule.map_top] apply (smul_mono_right _ inf_le_right : I ^ n • (I ^ k • ⊤ ⊓ (range f)) ≤ _) nth_rw 1 [show n = n + k - k by omega] rw [← hk (n + k) (show n + k ≥ k by omega)] exact ⟨by simpa using congrArg (fun x ↦ x.val (n + k)) hx, ⟨a (n + k), rfl⟩⟩ end Injectivity section variable [IsNoetherianRing R] [Module.Finite R N] variable {f : M →ₗ[R] N} {g : N →ₗ[R] P} (hf : Function.Injective f) (hfg : Function.Exact f g) (hg : Function.Surjective g) section variable {k : ℕ} (hkn : ∀ n ≥ k, I ^ n • ⊤ ⊓ LinearMap.range f = I ^ (n - k) • (I ^ k • ⊤ ⊓ LinearMap.range f)) (x : AdicCauchySequence I N) (hker : ∀ (n : ℕ), g (x n) ∈ (I ^ n • ⊤ : Submodule R P)) /- In each step, a preimage is constructed from the preimage of the previous step by adding this delta. -/ private noncomputable def mapExactAuxDelta {n : ℕ} {d : N} (hdmem : d ∈ (I ^ (k + n + 1) • ⊤ : Submodule R N)) {y yₙ : M} (hd : f y = x (k + n + 1) - d) (hyₙ : f yₙ - x (k + n) ∈ (I ^ (k + n) • ⊤ : Submodule R N)) : { d : (I ^ n • ⊤ : Submodule R M) | f (yₙ + d) - x (k + n + 1) ∈ (I ^ (k + n + 1) • ⊤ : Submodule R N) } := have h : f (y - yₙ) ∈ (I ^ (k + n) • ⊤ : Submodule R N) := by simp only [map_sub, hd] convert_to x (k + n + 1) - x (k + n) - d - (f yₙ - x (k + n)) ∈ I ^ (k + n) • ⊤ · abel · refine Submodule.sub_mem _ (Submodule.sub_mem _ ?_ ?_) hyₙ · rw [← Submodule.Quotient.eq] exact AdicCauchySequence.mk_eq_mk (by omega) _ · exact (Submodule.smul_mono_left (Ideal.pow_le_pow_right (by omega))) hdmem have hincl : I ^ (k + n - k) • (I ^ k • ⊤ ⊓ range f) ≤ I ^ (k + n - k) • (range f) := smul_mono_right _ inf_le_right have hyyₙ : y - yₙ ∈ (I ^ n • ⊤ : Submodule R M) := by convert_to y - yₙ ∈ (I ^ (k + n - k) • ⊤ : Submodule R M) · simp · rw [← Submodule.comap_map_eq_of_injective hf (I ^ (k + n - k) • ⊤ : Submodule R M), Submodule.map_smul'', Submodule.map_top] apply hincl rw [← hkn (k + n) (by omega)] exact ⟨h, ⟨y - yₙ, rfl⟩⟩ ⟨⟨y - yₙ, hyyₙ⟩, by simpa [hd, Nat.succ_eq_add_one, Nat.add_assoc]⟩ open Submodule include hfg in /-- Inductively construct preimage of cauchy sequence in kernel of `g.adicCompletion I`. -/ private noncomputable def mapExactAux : (n : ℕ) → { a : M | f a - x (k + n) ∈ (I ^ (k + n) • ⊤ : Submodule R N) } | .zero => let d := (h2 0).choose let y := (h2 0).choose_spec.choose have hdy : f y = x (k + 0) - d := (h2 0).choose_spec.choose_spec.right have hdmem := (h2 0).choose_spec.choose_spec.left ⟨y, by simpa [hdy]⟩ | .succ n => let d := (h2 <| n + 1).choose let y := (h2 <| n + 1).choose_spec.choose have hdy : f y = x (k + (n + 1)) - d := (h2 <| n + 1).choose_spec.choose_spec.right have hdmem := (h2 <| n + 1).choose_spec.choose_spec.left let ⟨yₙ, (hyₙ : f yₙ - x (k + n) ∈ (I ^ (k + n) • ⊤ : Submodule R N))⟩ := mapExactAux n let ⟨d, hd⟩ := mapExactAuxDelta hf hkn x hdmem hdy hyₙ ⟨yₙ + d, hd⟩ where h1 (n : ℕ) : g (x (k + n)) ∈ Submodule.map g (I ^ (k + n) • ⊤ : Submodule R N) := by rw [map_smul'', Submodule.map_top, range_eq_top.mpr hg] exact hker (k + n) h2 (n : ℕ) : ∃ (d : N) (y : M), d ∈ (I ^ (k + n) • ⊤ : Submodule R N) ∧ f y = x (k + n) - d := by obtain ⟨d, hdmem, hd⟩ := h1 n obtain ⟨y, hdy⟩ := (hfg (x (k + n) - d)).mp (by simp [hd]) exact ⟨d, y, hdmem, hdy⟩ end include hf hfg hg in /-- `AdicCompletion` over a Noetherian ring is exact on finitely generated modules. -/ theorem map_exact : Function.Exact (map I f) (map I g) := by refine LinearMap.exact_of_comp_eq_zero_of_ker_le_range ?_ (fun y ↦ ?_) · rw [map_comp, hfg.linearMap_comp_eq_zero, AdicCompletion.map_zero] · apply AdicCompletion.induction_on I N y (fun b ↦ ?_) intro hz obtain ⟨k, hk⟩ := Ideal.exists_pow_inf_eq_pow_smul I (LinearMap.range f) have hb (n : ℕ) : g (b n) ∈ (I ^ n • ⊤ : Submodule R P) := by simpa using congrArg (fun x ↦ x.val n) hz let a := mapExactAux hf hfg hg hk b hb refine ⟨AdicCompletion.mk I M (AdicCauchySequence.mk I M (fun n ↦ (a n : M)) ?_), ?_⟩ · refine fun n ↦ SModEq.symm ?_ simp [a, mapExactAux, SModEq] · ext n suffices h : Submodule.Quotient.mk (p := (I ^ n • ⊤ : Submodule R N)) (f (a n)) = Submodule.Quotient.mk (p := (I ^ n • ⊤ : Submodule R N)) (b (k + n)) by simp [h, AdicCauchySequence.mk_eq_mk (show n ≤ k + n by omega)] rw [Submodule.Quotient.eq] have hle : (I ^ (k + n) • ⊤ : Submodule R N) ≤ (I ^ n • ⊤ : Submodule R N) := Submodule.smul_mono_left (Ideal.pow_le_pow_right (by omega)) exact hle (a n).property end end AdicCompletion
Substs.lean
/- Copyright (c) 2022 Evan Lohn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Evan Lohn, Mario Carneiro -/ import Mathlib.Init /-! # The `substs` macro The `substs` macro applies the `subst` tactic to a list of hypothesis, in left to right order. -/ namespace Mathlib.Tactic.Substs /-- Applies the `subst` tactic to all given hypotheses from left to right. -/ syntax (name := substs) "substs" (colGt ppSpace ident)* : tactic macro_rules | `(tactic| substs $xs:ident*) => `(tactic| ($[subst $xs]*)) end Substs end Mathlib.Tactic
Prod.lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import Mathlib.Algebra.Module.Prod import Mathlib.Tactic.Abel import Mathlib.Algebra.Module.LinearMap.Defs /-! # Addition and subtraction are linear maps from the product space Note that these results use `IsLinearMap`, which is mostly discouraged. ## Tags linear algebra, vector space, module -/ variable {R : Type*} {M : Type*} [Semiring R] namespace IsLinearMap theorem isLinearMap_add [AddCommMonoid M] [Module R M] : IsLinearMap R fun x : M × M => x.1 + x.2 := by apply IsLinearMap.mk · intro x y simp only [Prod.fst_add, Prod.snd_add] abel · intro x y simp [smul_add] theorem isLinearMap_sub [AddCommGroup M] [Module R M] : IsLinearMap R fun x : M × M => x.1 - x.2 := by apply IsLinearMap.mk · intro x y simp [add_comm, add_assoc, add_left_comm, sub_eq_add_neg] · intro x y simp [smul_sub] end IsLinearMap
Basic.lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Kim Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn, Edward Ayers, Arthur Paulino -/ import Mathlib.Init import Lean.Meta.Tactic.Rewrite import Batteries.Tactic.Alias import Lean.Elab.Binders /-! # Additional operations on Expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. -/ namespace Lean namespace BinderInfo /-! ### Declarations about `BinderInfo` -/ /-- The brackets corresponding to a given `BinderInfo`. -/ def brackets : BinderInfo → String × String | BinderInfo.implicit => ("{", "}") | BinderInfo.strictImplicit => ("{{", "}}") | BinderInfo.instImplicit => ("[", "]") | _ => ("(", ")") end BinderInfo namespace Name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `Name` such that `f n != none`, then replace this prefix with the value of `f n`. -/ def mapPrefix (f : Name → Option Name) (n : Name) : Name := Id.run do if let some n' := f n then return n' match n with | anonymous => anonymous | str n' s => mkStr (mapPrefix f n') s | num n' i => mkNum (mapPrefix f n') i /-- Build a name from components. For example, ``from_components [`foo, `bar]`` becomes ``` `foo.bar```. It is the inverse of `Name.components` on list of names that have single components. -/ def fromComponents : List Name → Name := go .anonymous where /-- Auxiliary for `Name.fromComponents` -/ go : Name → List Name → Name | n, [] => n | n, s :: rest => go (s.updatePrefix n) rest /-- Update the last component of a name. -/ def updateLast (f : String → String) : Name → Name | .str n s => .str n (f s) | n => n /-- Get the last field of a name as a string. Doesn't raise an error when the last component is a numeric field. -/ def lastComponentAsString : Name → String | .str _ s => s | .num _ n => toString n | .anonymous => "" /-- `nm.splitAt n` splits a name `nm` in two parts, such that the *second* part has depth `n`, i.e. `(nm.splitAt n).2.getNumParts = n` (assuming `nm.getNumParts ≥ n`). Example: ``splitAt `foo.bar.baz.back.bat 1 = (`foo.bar.baz.back, `bat)``. -/ def splitAt (nm : Name) (n : Nat) : Name × Name := let (nm2, nm1) := nm.componentsRev.splitAt n (.fromComponents <| nm1.reverse, .fromComponents <| nm2.reverse) /-- `isPrefixOf? pre nm` returns `some post` if `nm = pre ++ post`. Note that this includes the case where `nm` has multiple more namespaces. If `pre` is not a prefix of `nm`, it returns `none`. -/ def isPrefixOf? (pre nm : Name) : Option Name := if pre == nm then some anonymous else match nm with | anonymous => none | num p' a => (isPrefixOf? pre p').map (·.num a) | str p' s => (isPrefixOf? pre p').map (·.str s) open Meta -- from Lean.Server.Completion def isBlackListed {m} [Monad m] [MonadEnv m] (declName : Name) : m Bool := do if declName == ``sorryAx then return true if declName matches .str _ "inj" then return true if declName matches .str _ "noConfusionType" then return true let env ← getEnv pure <| declName.isInternalDetail || isAuxRecursor env declName || isNoConfusion env declName <||> isRec declName <||> isMatcher declName end Name namespace ConstantInfo /-- Checks whether this `ConstantInfo` is a definition. -/ def isDef : ConstantInfo → Bool | defnInfo _ => true | _ => false /-- Checks whether this `ConstantInfo` is a theorem. -/ def isThm : ConstantInfo → Bool | thmInfo _ => true | _ => false /-- Update `ConstantVal` (the data common to all constructors of `ConstantInfo`) in a `ConstantInfo`. -/ def updateConstantVal : ConstantInfo → ConstantVal → ConstantInfo | defnInfo info, v => defnInfo {info with toConstantVal := v} | axiomInfo info, v => axiomInfo {info with toConstantVal := v} | thmInfo info, v => thmInfo {info with toConstantVal := v} | opaqueInfo info, v => opaqueInfo {info with toConstantVal := v} | quotInfo info, v => quotInfo {info with toConstantVal := v} | inductInfo info, v => inductInfo {info with toConstantVal := v} | ctorInfo info, v => ctorInfo {info with toConstantVal := v} | recInfo info, v => recInfo {info with toConstantVal := v} /-- Update the name of a `ConstantInfo`. -/ def updateName (c : ConstantInfo) (name : Name) : ConstantInfo := c.updateConstantVal {c.toConstantVal with name} /-- Update the type of a `ConstantInfo`. -/ def updateType (c : ConstantInfo) (type : Expr) : ConstantInfo := c.updateConstantVal {c.toConstantVal with type} /-- Update the level parameters of a `ConstantInfo`. -/ def updateLevelParams (c : ConstantInfo) (levelParams : List Name) : ConstantInfo := c.updateConstantVal {c.toConstantVal with levelParams} /-- Update the value of a `ConstantInfo`, if it has one. -/ def updateValue : ConstantInfo → Expr → ConstantInfo | defnInfo info, v => defnInfo {info with value := v} | thmInfo info, v => thmInfo {info with value := v} | opaqueInfo info, v => opaqueInfo {info with value := v} | d, _ => d /-- Turn a `ConstantInfo` into a declaration. -/ def toDeclaration! : ConstantInfo → Declaration | defnInfo info => Declaration.defnDecl info | thmInfo info => Declaration.thmDecl info | axiomInfo info => Declaration.axiomDecl info | opaqueInfo info => Declaration.opaqueDecl info | quotInfo _ => panic! "toDeclaration for quotInfo not implemented" | inductInfo _ => panic! "toDeclaration for inductInfo not implemented" | ctorInfo _ => panic! "toDeclaration for ctorInfo not implemented" | recInfo _ => panic! "toDeclaration for recInfo not implemented" end ConstantInfo open Meta /-- Same as `mkConst`, but with fresh level metavariables. -/ def mkConst' (constName : Name) : MetaM Expr := do return mkConst constName (← (← getConstInfo constName).levelParams.mapM fun _ => mkFreshLevelMVar) namespace Expr /-! ### Declarations about `Expr` -/ def bvarIdx? : Expr → Option Nat | bvar idx => some idx | _ => none /-- Invariant: `i : ℕ` should be less than the size of `as : Array Expr`. -/ private def getAppAppsAux : Expr → Array Expr → Nat → Array Expr | .app f a, as, i => getAppAppsAux f (as.set! i (.app f a)) (i-1) | _, as, _ => as /-- Given `f a b c`, return `#[f a, f a b, f a b c]`. Each entry in the array is an `Expr.app`, and this array has the same length as the one returned by `Lean.Expr.getAppArgs`. -/ @[inline] def getAppApps (e : Expr) : Array Expr := let dummy := mkSort levelZero let nargs := e.getAppNumArgs getAppAppsAux e (.replicate nargs dummy) (nargs-1) /-- Erase proofs in an expression by replacing them with `sorry`s. This function replaces all proofs in the expression and in the types that appear in the expression by `sorryAx`s. The resulting expression has the same type as the old one. It is useful, e.g., to verify if the proof-irrelevant part of a definition depends on a variable. -/ def eraseProofs (e : Expr) : MetaM Expr := Meta.transform (skipConstInApp := true) e (pre := fun e => do if (← Meta.isProof e) then return .continue (← mkSorry (← inferType e) true) else return .continue) /-- If an `Expr` has the form `Type u`, then return `some u`, otherwise `none`. -/ def type? : Expr → Option Level | .sort u => u.dec | _ => none /-- `isConstantApplication e` checks whether `e` is syntactically an application of the form `(fun x₁ ⋯ xₙ => H) y₁ ⋯ yₙ` where `H` does not contain the variable `xₙ`. In other words, it does a syntactic check that the expression does not depend on `yₙ`. -/ def isConstantApplication (e : Expr) := e.isApp && aux e.getAppNumArgs'.pred e.getAppFn' e.getAppNumArgs' where /-- `aux depth e n` checks whether the body of the `n`-th lambda of `e` has loose bvar `depth - 1`. -/ aux (depth : Nat) : Expr → Nat → Bool | .lam _ _ b _, n + 1 => aux depth b n | e, 0 => !e.hasLooseBVar (depth - 1) | _, _ => false /-- Counts the immediate depth of a nested `let` expression. -/ def letDepth : Expr → Nat | .letE _ _ _ b _ => b.letDepth + 1 | _ => 0 open Meta /-- Check that an expression contains no metavariables (after instantiation). -/ -- There is a `TacticM` level version of this, but it's useful to have in `MetaM`. def ensureHasNoMVars (e : Expr) : MetaM Unit := do let e ← instantiateMVars e if e.hasExprMVar then throwError "tactic failed, resulting expression contains metavariables{indentExpr e}" /-- Construct the term of type `α` for a given natural number (doing typeclass search for the `OfNat` instance required). -/ def ofNat (α : Expr) (n : Nat) : MetaM Expr := do mkAppOptM ``OfNat.ofNat #[α, mkRawNatLit n, none] /-- Construct the term of type `α` for a given integer (doing typeclass search for the `OfNat` and `Neg` instances required). -/ def ofInt (α : Expr) : Int → MetaM Expr | Int.ofNat n => Expr.ofNat α n | Int.negSucc n => do mkAppM ``Neg.neg #[← Expr.ofNat α (n + 1)] section recognizers /-- Return `some n` if `e` is one of the following - a nat literal (numeral) - `Nat.zero` - `Nat.succ x` where `isNumeral x` - `OfNat.ofNat _ x _` where `isNumeral x` -/ partial def numeral? (e : Expr) : Option Nat := if let some n := e.rawNatLit? then n else let e := e.consumeMData -- `OfNat` numerals may have `no_index` around them from `ofNat()` let f := e.getAppFn if !f.isConst then none else let fName := f.constName! if fName == ``Nat.succ && e.getAppNumArgs == 1 then (numeral? e.appArg!).map Nat.succ else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then numeral? (e.getArg! 1) else if fName == ``Nat.zero && e.getAppNumArgs == 0 then some 0 else none /-- Test if an expression is either `Nat.zero`, or `OfNat.ofNat 0`. -/ def zero? (e : Expr) : Bool := match e.numeral? with | some 0 => true | _ => false /-- Tests is if an expression matches either `x ≠ y` or `¬ (x = y)`. If it matches, returns `some (type, x, y)`. -/ def ne?' (e : Expr) : Option (Expr × Expr × Expr) := e.ne? <|> (e.not? >>= Expr.eq?) /-- `Lean.Expr.le? e` takes `e : Expr` as input. If `e` represents `a ≤ b`, then it returns `some (t, a, b)`, where `t` is the Type of `a`, otherwise, it returns `none`. -/ @[inline] def le? (p : Expr) : Option (Expr × Expr × Expr) := do let (type, _, lhs, rhs) ← p.app4? ``LE.le return (type, lhs, rhs) /-- `Lean.Expr.lt? e` takes `e : Expr` as input. If `e` represents `a < b`, then it returns `some (t, a, b)`, where `t` is the Type of `a`, otherwise, it returns `none`. -/ @[inline] def lt? (p : Expr) : Option (Expr × Expr × Expr) := do let (type, _, lhs, rhs) ← p.app4? ``LT.lt return (type, lhs, rhs) /-- Given a proposition `ty` that is an `Eq`, `Iff`, or `HEq`, returns `(tyLhs, lhs, tyRhs, rhs)`, where `lhs : tyLhs` and `rhs : tyRhs`, and where `lhs` is related to `rhs` by the respective relation. See also `Lean.Expr.iff?`, `Lean.Expr.eq?`, and `Lean.Expr.heq?`. -/ def sides? (ty : Expr) : Option (Expr × Expr × Expr × Expr) := if let some (lhs, rhs) := ty.iff? then some (.sort .zero, lhs, .sort .zero, rhs) else if let some (ty, lhs, rhs) := ty.eq? then some (ty, lhs, ty, rhs) else ty.heq? end recognizers universe u def modifyAppArgM {M : Type → Type u} [Functor M] [Pure M] (modifier : Expr → M Expr) : Expr → M Expr | app f a => mkApp f <$> modifier a | e => pure e def modifyRevArg (modifier : Expr → Expr) : Nat → Expr → Expr | 0, (.app f x) => .app f (modifier x) | (i+1), (.app f x) => .app (modifyRevArg modifier i f) x | _, e => e /-- Given `f a₀ a₁ ... aₙ₋₁`, runs `modifier` on the `i`th argument or returns the original expression if out of bounds. -/ def modifyArg (modifier : Expr → Expr) (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr := modifyRevArg modifier (n - i - 1) e /-- Given `f a₀ a₁ ... aₙ₋₁`, sets the argument on the `i`th argument to `x` or returns the original expression if out of bounds. -/ def setArg (e : Expr) (i : Nat) (x : Expr) (n := e.getAppNumArgs) : Expr := e.modifyArg (fun _ => x) i n def getRevArg? : Expr → Nat → Option Expr | app _ a, 0 => a | app f _, i+1 => getRevArg! f i | _, _ => none /-- Given `f a₀ a₁ ... aₙ₋₁`, returns the `i`th argument or none if out of bounds. -/ def getArg? (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Option Expr := getRevArg? e (n - i - 1) /-- Given `f a₀ a₁ ... aₙ₋₁`, runs `modifier` on the `i`th argument. An argument `n` may be provided which says how many arguments we are expecting `e` to have. -/ def modifyArgM {M : Type → Type u} [Monad M] (modifier : Expr → M Expr) (e : Expr) (i : Nat) (n := e.getAppNumArgs) : M Expr := do let some a := getArg? e i | return e let a ← modifier a return modifyArg (fun _ ↦ a) e i n /-- Traverses an expression `e` and renames bound variables named `old` to `new`. -/ def renameBVar (e : Expr) (old new : Name) : Expr := match e with | app fn arg => app (fn.renameBVar old new) (arg.renameBVar old new) | lam n ty bd bi => lam (if n == old then new else n) (ty.renameBVar old new) (bd.renameBVar old new) bi | forallE n ty bd bi => forallE (if n == old then new else n) (ty.renameBVar old new) (bd.renameBVar old new) bi | mdata d e' => mdata d (e'.renameBVar old new) | e => e open Lean.Meta in /-- `getBinderName e` returns `some n` if `e` is an expression of the form `∀ n, ...` and `none` otherwise. -/ def getBinderName (e : Expr) : MetaM (Option Name) := do match ← withReducible (whnf e) with | .forallE (binderName := n) .. | .lam (binderName := n) .. => pure (some n) | _ => pure none open Lean.Elab.Term /-- Annotates a `binderIdent` with the binder information from an `fvar`. -/ def addLocalVarInfoForBinderIdent (fvar : Expr) (tk : TSyntax ``binderIdent) : MetaM Unit := -- the only TermElabM thing we do in `addLocalVarInfo` is check inPattern, -- which we assume is always false for this function discard <| TermElabM.run do match tk with | `(binderIdent| $n:ident) => Elab.Term.addLocalVarInfo n fvar | tk => Elab.Term.addLocalVarInfo (Unhygienic.run `(_%$tk)) fvar /-- If `e` has a structure as type with field `fieldName`, `mkDirectProjection e fieldName` creates the projection expression `e.fieldName` -/ def mkDirectProjection (e : Expr) (fieldName : Name) : MetaM Expr := do let type ← whnf (← inferType e) let .const structName us := type.getAppFn | throwError "{e} doesn't have a structure as type" let some projName := getProjFnForField? (← getEnv) structName fieldName | throwError "{structName} doesn't have field {fieldName}" return mkAppN (.const projName us) (type.getAppArgs.push e) /-- If `e` has a structure as type with field `fieldName` (either directly or in a parent structure), `mkProjection e fieldName` creates the projection expression `e.fieldName` -/ def mkProjection (e : Expr) (fieldName : Name) : MetaM Expr := do let .const structName _ := (← whnf (← inferType e)).getAppFn | throwError "{e} doesn't have a structure as type" let some baseStruct := findField? (← getEnv) structName fieldName | throwError "No parent of {structName} has field {fieldName}" let mut e := e for projName in (getPathToBaseStructure? (← getEnv) baseStruct structName).get! do let type ← whnf (← inferType e) let .const _structName us := type.getAppFn | throwError "{e} doesn't have a structure as type" e := mkAppN (.const projName us) (type.getAppArgs.push e) mkDirectProjection e fieldName /-- If `e` is a projection of the structure constructor, reduce the projection. Otherwise returns `none`. If this function detects that expression is ill-typed, throws an error. For example, given `Prod.fst (x, y)`, returns `some x`. -/ def reduceProjStruct? (e : Expr) : MetaM (Option Expr) := do let .const cname _ := e.getAppFn | return none let some pinfo ← getProjectionFnInfo? cname | return none let args := e.getAppArgs if ha : args.size = pinfo.numParams + 1 then -- The last argument of a projection is the structure. let sarg := args[pinfo.numParams]'(ha ▸ pinfo.numParams.lt_succ_self) -- Check that the structure is a constructor expression. unless sarg.getAppFn.isConstOf pinfo.ctorName do return none let sfields := sarg.getAppArgs -- The ith projection extracts the ith field of the constructor let sidx := pinfo.numParams + pinfo.i if hs : sidx < sfields.size then return some (sfields[sidx]'hs) else throwError m!"ill-formed expression, {cname} is the {pinfo.i + 1}-th projection function \ but {sarg} does not have enough arguments" else return none /-- Returns true if `e` contains a name `n` where `p n` is true. -/ def containsConst (e : Expr) (p : Name → Bool) : Bool := Option.isSome <| e.find? fun | .const n _ => p n | _ => false /-- Rewrites `e` via some `eq`, producing a proof `e = e'` for some `e'`. Rewrites with a fresh metavariable as the ambient goal. Fails if the rewrite produces any subgoals. -/ def rewrite (e eq : Expr) : MetaM Expr := do let ⟨_, eq', []⟩ ← (← mkFreshExprMVar none).mvarId!.rewrite e eq | throwError "Expr.rewrite may not produce subgoals." return eq' /-- Rewrites the type of `e` via some `eq`, then moves `e` into the new type via `Eq.mp`. Rewrites with a fresh metavariable as the ambient goal. Fails if the rewrite produces any subgoals. -/ def rewriteType (e eq : Expr) : MetaM Expr := do mkEqMP (← (← inferType e).rewrite eq) e /-- Given `(hNotEx : Not ex)` where `ex` is of the form `Exists x, p x`, return a `forall x, Not (p x)` and a proof for it. This function handles nested existentials. -/ partial def forallNot_of_notExists (ex hNotEx : Expr) : MetaM (Expr × Expr) := do let .app (.app (.const ``Exists [lvl]) A) p := ex | failure go lvl A p hNotEx where /-- Given `(hNotEx : Not (@Exists.{lvl} A p))`, return a `forall x, Not (p x)` and a proof for it. This function handles nested existentials. -/ go (lvl : Level) (A p hNotEx : Expr) : MetaM (Expr × Expr) := do let xn ← mkFreshUserName `x withLocalDeclD xn A fun x => do let px := p.beta #[x] let notPx := mkNot px let hAllNotPx := mkApp3 (.const ``forall_not_of_not_exists [lvl]) A p hNotEx if let .app (.app (.const ``Exists [lvl']) A') p' := px then let hNotPxN ← mkFreshUserName `h withLocalDeclD hNotPxN notPx fun hNotPx => do let (qx, hQx) ← go lvl' A' p' hNotPx let allQx ← mkForallFVars #[x] qx let hNotPxImpQx ← mkLambdaFVars #[hNotPx] hQx let hAllQx ← mkLambdaFVars #[x] (.app hNotPxImpQx (.app hAllNotPx x)) return (allQx, hAllQx) else let allNotPx ← mkForallFVars #[x] notPx return (allNotPx, hAllNotPx) end Expr /-- Get the projections that are projections to parent structures. Similar to `getParentStructures`, except that this returns the (last component of the) projection names instead of the parent names. -/ def getFieldsToParents (env : Environment) (structName : Name) : Array Name := getStructureFields env structName |>.filter fun fieldName => isSubobjectField? env structName fieldName |>.isSome end Lean
Connected.lean
/- Copyright (c) 2024 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.CategoryTheory.IsConnected import Mathlib.CategoryTheory.Limits.Shapes.WidePullbacks /-! # Connected shapes In this file we prove that various shapes are connected. -/ namespace CategoryTheory open Limits instance {J} : IsConnected (WidePullbackShape J) := by apply IsConnected.of_constant_of_preserves_morphisms intros α F H suffices ∀ i, F i = F none from fun j j' ↦ (this j).trans (this j').symm rintro ⟨⟩ exacts [rfl, H (.term _)] instance {J} : IsConnected (WidePushoutShape J) := by apply IsConnected.of_constant_of_preserves_morphisms intros α F H suffices ∀ i, F i = F none from fun j j' ↦ (this j).trans (this j').symm rintro ⟨⟩ exacts [rfl, (H (.init _)).symm] end CategoryTheory
alt.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 div fintype tuple tuple bigop prime finset ssralg. From mathcomp Require Import zmodp fingroup morphism perm automorphism quotient. From mathcomp Require Import action cyclic pgroup gseries sylow. From mathcomp Require Import primitive_action nilpotent maximal. (******************************************************************************) (* Definitions of the symmetric and alternate groups, and some properties. *) (* 'Sym_T == The symmetric group over type T (which must have a finType *) (* structure). *) (* := [set: {perm T}] *) (* 'Alt_T == The alternating group over type T. *) (******************************************************************************) Unset Printing Implicit Defensive. Set Implicit Arguments. Unset Strict Implicit. Import GroupScope GRing. HB.instance Definition _ := isMulGroup.Build bool addbA addFb addbb. Section SymAltDef. Variable T : finType. Implicit Types (s : {perm T}) (x y z : T). (** Definitions of the alternate groups and some Properties **) Definition Sym : {set {perm T}} := setT. Canonical Sym_group := Eval hnf in [group of Sym]. Local Notation "'Sym_T" := Sym. Canonical sign_morph := @Morphism _ _ 'Sym_T _ (in2W (@odd_permM _)). Definition Alt := 'ker (@odd_perm T). Canonical Alt_group := Eval hnf in [group of Alt]. Local Notation "'Alt_T" := Alt. Lemma Alt_even p : (p \in 'Alt_T) = ~~ p. Proof. by rewrite !inE /=; case: odd_perm. Qed. Lemma Alt_subset : 'Alt_T \subset 'Sym_T. Proof. exact: subsetT. Qed. Lemma Alt_normal : 'Alt_T <| 'Sym_T. Proof. exact: ker_normal. Qed. Lemma Alt_norm : 'Sym_T \subset 'N('Alt_T). Proof. by case/andP: Alt_normal. Qed. Let n := #|T|. Lemma Alt_index : 1 < n -> #|'Sym_T : 'Alt_T| = 2. Proof. move=> lt1n; rewrite -card_quotient ?Alt_norm //=. have : ('Sym_T / 'Alt_T) \isog (@odd_perm T @* 'Sym_T) by apply: first_isog. case/isogP=> g /injmP/card_in_imset <-. rewrite /morphim setIid=> ->; rewrite -card_bool; apply: eq_card => b. apply/imsetP; case: b => /=; last first. by exists (1 : {perm T}); [rewrite setIid inE | rewrite odd_perm1]. case: (pickP T) lt1n => [x1 _ | d0]; last by rewrite /n eq_card0. rewrite /n (cardD1 x1) ltnS lt0n => /existsP[x2 /=]. by rewrite eq_sym andbT -odd_tperm; exists (tperm x1 x2); rewrite ?inE. Qed. Lemma card_Sym : #|'Sym_T| = n`!. Proof. rewrite -[n]cardsE -card_perm; apply: eq_card => p. by apply/idP/subsetP=> [? ?|]; rewrite !inE. Qed. Lemma card_Alt : 1 < n -> (2 * #|'Alt_T|)%N = n`!. Proof. by move/Alt_index <-; rewrite mulnC (Lagrange Alt_subset) card_Sym. Qed. Lemma Sym_trans : [transitive^n 'Sym_T, on setT | 'P]. Proof. apply/imsetP; pose t1 := [tuple of enum T]. have dt1: t1 \in n.-dtuple(setT) by rewrite inE enum_uniq; apply/subsetP. exists t1 => //; apply/setP=> t; apply/idP/imsetP=> [|[a _ ->{t}]]; last first. by apply: n_act_dtuple => //; apply/astabsP=> x; rewrite !inE. case/dtuple_onP=> injt _; have injf := inj_comp injt enum_rank_inj. exists (perm injf); first by rewrite inE. apply: eq_from_tnth => i; rewrite tnth_map /= [aperm _ _]permE; congr tnth. by rewrite (tnth_nth (enum_default i)) enum_valK. Qed. Lemma Alt_trans : [transitive^n.-2 'Alt_T, on setT | 'P]. Proof. case n_m2: n Sym_trans => [|[|m]] /= tr_m2; try exact: ntransitive0. have tr_m := ntransitive_weak (leqW (leqnSn m)) tr_m2. case/imsetP: tr_m2; case/tupleP=> x; case/tupleP=> y t. rewrite !dtuple_on_add 2![x \in _]inE inE negb_or /= -!andbA. case/and4P=> nxy ntx nty dt _; apply/imsetP; exists t => //; apply/setP=> u. apply/idP/imsetP=> [|[a _ ->{u}]]; last first. by apply: n_act_dtuple => //; apply/astabsP=> z; rewrite !inE. case/(atransP2 tr_m dt)=> /= a _ ->{u}. case odd_a: (odd_perm a); last by exists a => //; rewrite !inE /= odd_a. exists (tperm x y * a); first by rewrite !inE /= odd_permM odd_tperm nxy odd_a. apply/val_inj/eq_in_map => z tz; rewrite actM /= /aperm; congr (a _). by case: tpermP ntx nty => // <-; rewrite tz. Qed. Lemma aperm_faithful (A : {group {perm T}}) : [faithful A, on setT | 'P]. Proof. by apply/faithfulP=> /= p _ np1; apply/eqP/perm_act1P=> y; rewrite np1 ?inE. Qed. End SymAltDef. Arguments Sym T%_type. Arguments Sym_group T%_type. Arguments Alt T%_type. Arguments Alt_group T%_type. Notation "''Sym_' T" := (Sym T) (at level 8, T at level 2, format "''Sym_' T") : group_scope. Notation "''Sym_' T" := (Sym_group T) : Group_scope. Notation "''Alt_' T" := (Alt T) (at level 8, T at level 2, format "''Alt_' T") : group_scope. Notation "''Alt_' T" := (Alt_group T) : Group_scope. Lemma trivial_Alt_2 (T : finType) : #|T| <= 2 -> 'Alt_T = 1. Proof. rewrite leq_eqVlt => /predU1P[] oT. by apply: card_le1_trivg; rewrite -leq_double -mul2n card_Alt oT. suffices Sym1: 'Sym_T = 1 by apply/trivgP; rewrite -Sym1 subsetT. by apply: card1_trivg; rewrite card_Sym; case: #|T| oT; do 2?case. Qed. Lemma simple_Alt_3 (T : finType) : #|T| = 3 -> simple 'Alt_T. Proof. move=> T3; have{T3} oA: #|'Alt_T| = 3. by apply: double_inj; rewrite -mul2n card_Alt T3. apply/simpleP; split=> [|K]; [by rewrite trivg_card1 oA | case/andP=> sKH _]. have:= cardSg sKH; rewrite oA dvdn_divisors // !inE orbC /= -oA. case/pred2P=> eqK; [right | left]; apply/eqP. by rewrite eqEcard sKH eqK leqnn. by rewrite eq_sym eqEcard sub1G eqK cards1. Qed. Lemma not_simple_Alt_4 (T : finType) : #|T| = 4 -> ~~ simple 'Alt_T. Proof. move=> oT; set A := 'Alt_T. have oA: #|A| = 12 by apply: double_inj; rewrite -mul2n card_Alt oT. suffices [p]: exists p, [/\ prime p, 1 < #|A|`_p < #|A| & #|'Syl_p(A)| == 1%N]. case=> p_pr pA_int; rewrite /A; case/normal_sylowP=> P; case/pHallP. rewrite /= -/A => sPA pP nPA; apply/simpleP=> [] [_]; rewrite -pP in pA_int. by case/(_ P)=> // defP; rewrite defP oA ?cards1 in pA_int. have: #|'Syl_3(A)| \in filter [pred d | d %% 3 == 1%N] (divisors 12). by rewrite mem_filter -dvdn_divisors //= -oA card_Syl_dvd ?card_Syl_mod. rewrite /= oA mem_seq2 orbC. case/predU1P=> [oQ3|]; [exists 2 | exists 3]; split; rewrite ?p_part //. pose A3 := [set x : {perm T} | #[x] == 3]; suffices oA3: #|A :&: A3| = 8. have sQ2 P: P \in 'Syl_2(A) -> P :=: A :\: A3. rewrite inE pHallE oA p_part -natTrecE /= => /andP[sPA /eqP oP]. apply/eqP; rewrite eqEcard -(leq_add2l 8) -{1}oA3 cardsID oA oP. rewrite andbT subsetD sPA; apply/exists_inP=> -[x] /= Px. by rewrite inE => /eqP ox; have:= order_dvdG Px; rewrite oP ox. have [/= P sylP] := Sylow_exists 2 [group of A]. rewrite -(([set P] =P 'Syl_2(A)) _) ?cards1 // eqEsubset sub1set inE sylP. by apply/subsetP=> Q sylQ; rewrite inE -val_eqE /= !sQ2 // inE. rewrite -[8]/(4 * 2)%N -{}oQ3 -sum1_card -sum_nat_const. rewrite (partition_big (fun x => <[x]>%G) [in 'Syl_3(A)]) => [|x]; last first. by case/setIP=> Ax; rewrite /= !inE pHallE p_part cycle_subG Ax oA. apply: eq_bigr => Q; rewrite inE pHallE oA p_part -?natTrecE //=. case/andP=> sQA /eqP oQ; have:= oQ. rewrite (cardsD1 1) group1 -sum1_card => [[/= <-]]; apply: eq_bigl => x. rewrite setIC -val_eqE /= 2!inE in_setD1 -andbA -{4}[x]expg1 -order_dvdn dvdn1. apply/and3P/andP=> [[/eqP-> _ /eqP <-] | [ntx Qx]]; first by rewrite cycle_id. have:= order_dvdG Qx; rewrite oQ dvdn_divisors // mem_seq2 (negPf ntx) /=. by rewrite eqEcard cycle_subG Qx (subsetP sQA) // oQ /order => /eqP->. Qed. Lemma simple_Alt5_base (T : finType) : #|T| = 5 -> simple 'Alt_T. Proof. move=> oT. have F1: #|'Alt_T| = 60 by apply: double_inj; rewrite -mul2n card_Alt oT. have FF (H : {group {perm T}}): H <| 'Alt_T -> H :<>: 1 -> 20 %| #|H|. - move=> Hh1 Hh3. have [x _]: exists x, x \in T by apply/existsP/eqP; rewrite oT. have F2 := Alt_trans T; rewrite oT /= in F2. have F3: [transitive 'Alt_T, on setT | 'P] by apply: ntransitive1 F2. have F4: [primitive 'Alt_T, on setT | 'P] by apply: ntransitive_primitive F2. case: (prim_trans_norm F4 Hh1) => F5. by case: Hh3; apply/trivgP; apply: subset_trans F5 (aperm_faithful _). have F6: 5 %| #|H| by rewrite -oT -cardsT (atrans_dvd F5). have F7: 4 %| #|H|. have F7: #|[set~ x]| = 4 by rewrite cardsC1 oT. case: (pickP [in [set~ x]]) => [y Hy | ?]; last by rewrite eq_card0 in F7. pose K := 'C_H[x | 'P]%G. have F8 : K \subset H by apply: subsetIl. pose Gx := 'C_('Alt_T)[x | 'P]%G. have F9: [transitive^2 Gx, on [set~ x] | 'P]. by rewrite -[[set~ x]]setTI -setDE stab_ntransitive ?inE. have F10: [transitive Gx, on [set~ x] | 'P]. exact: ntransitive1 F9. have F11: [primitive Gx, on [set~ x] | 'P]. exact: ntransitive_primitive F9. have F12: K \subset Gx by apply: setSI; apply: normal_sub. have F13: K <| Gx by rewrite /(K <| _) F12 normsIG // normal_norm. case: (prim_trans_norm F11 F13) => Ksub; last first. by apply: dvdn_trans (cardSg F8); rewrite -F7; apply: atrans_dvd Ksub. have F14: [faithful Gx, on [set~ x] | 'P]. apply/subsetP=> g; do 2![case/setIP] => Altg cgx cgx'. apply: (subsetP (aperm_faithful 'Alt_T)). rewrite inE Altg /=; apply/astabP=> z _. case: (z =P x) => [->|]; first exact: (astab1P cgx). by move/eqP=> nxz; rewrite (astabP cgx') ?inE //. have Hreg g (z : T): g \in H -> g z = z -> g = 1. have F15 h: h \in H -> h x = x -> h = 1. move=> Hh Hhx; have: h \in K by rewrite inE Hh; apply/astab1P. by rewrite (trivGP (subset_trans Ksub F14)) => /set1P. move=> Hg Hgz; have:= in_setT x; rewrite -(atransP F3 z) ?inE //. case/imsetP=> g1 Hg1 Hg2; apply: (conjg_inj g1); rewrite conj1g. apply: F15; last by rewrite Hg2 -permM mulKVg permM Hgz. by case/normalP: Hh1 => _ nH1; rewrite -(nH1 _ Hg1) memJ_conjg. clear K F8 F12 F13 Ksub F14. case: (Cauchy _ F6) => // h Hh /eqP Horder. have diff_hnx_x n: 0 < n -> n < 5 -> x != (h ^+ n) x. move=> Hn1 Hn2; rewrite eq_sym; apply/negP => HH. have: #[h ^+ n] = 5. rewrite orderXgcd // (eqP Horder). by move: Hn1 Hn2 {HH}; do 5 (case: n => [|n] //). have Hhd2: h ^+ n \in H by rewrite groupX. by rewrite (Hreg _ _ Hhd2 (eqP HH)) order1. pose S1 := [tuple x; h x; (h ^+ 3) x]. have DnS1: S1 \in 3.-dtuple(setT). rewrite inE memtE subset_all /= !inE /= !negb_or -!andbA /= andbT. rewrite -{1}[h]expg1 !diff_hnx_x // expgSr permM. by rewrite (inj_eq perm_inj) diff_hnx_x. pose S2 := [tuple x; h x; (h ^+ 2) x]. have DnS2: S2 \in 3.-dtuple(setT). rewrite inE memtE subset_all /= !inE /= !negb_or -!andbA /= andbT. rewrite -{1}[h]expg1 !diff_hnx_x // expgSr permM. by rewrite (inj_eq perm_inj) diff_hnx_x. case: (atransP2 F2 DnS1 DnS2) => g Hg [/=]. rewrite /aperm => Hgx Hghx Hgh3x. have h_g_com: h * g = g * h. suff HH: (g * h * g^-1) * h^-1 = 1 by rewrite -[h * g]mul1g -HH !gnorm. apply: (Hreg _ x); last first. by rewrite !permM -Hgx Hghx -!permM mulKVg mulgV perm1. rewrite groupM // ?groupV // (conjgCV g) mulgK -mem_conjg. by case/normalP: Hh1 => _ ->. have: (g * (h ^+ 2) * g ^-1) x = (h ^+ 3) x. rewrite !permM -Hgx. have ->: h (h x) = (h ^+ 2) x by rewrite /= permM. by rewrite {1}Hgh3x -!permM /= mulgV mulg1 -expgSr. rewrite commuteX // mulgK {1}[expgn]lock expgS permM -lock. by move/perm_inj=> eqxhx; case/eqP: (diff_hnx_x 1%N isT isT); rewrite expg1. by rewrite (@Gauss_dvd 4 5) // F7. apply/simpleP; split => [|H Hnorm]; first by rewrite trivg_card1 F1. case Hcard1: (#|H| == 1%N); move/eqP: Hcard1 => Hcard1. by left; apply: card1_trivg; rewrite Hcard1. right; case Hcard60: (#|H| == 60); move/eqP: Hcard60 => Hcard60. by apply/eqP; rewrite eqEcard Hcard60 F1 andbT; case/andP: Hnorm. have {Hcard1 Hcard60} Hcard20: #|H| = 20. have Hdiv: 20 %| #|H| by apply: FF => // HH; case Hcard1; rewrite HH cards1. case H20: (#|H| == 20); first exact/eqP. case: Hcard60; case/andP: Hnorm; move/cardSg; rewrite F1 => Hdiv1 _. by case/dvdnP: Hdiv H20 Hdiv1 => n ->; move: n; do 4!case=> //. have prime_5: prime 5 by []. have nSyl5: #|'Syl_5(H)| = 1%N. move: (card_Syl_dvd 5 H) (card_Syl_mod H prime_5). rewrite Hcard20; case: (card _) => // n Hdiv. move: (dvdn_leq (isT: (0 < 20)%N) Hdiv). by move: (n) Hdiv; do 20 (case=> //). case: (Sylow_exists 5 H) => S; case/pHallP=> sSH oS. have{} oS: #|S| = 5 by rewrite oS p_part Hcard20. suff: 20 %| #|S| by rewrite oS. apply: FF => [|S1]; last by rewrite S1 cards1 in oS. apply: char_normal_trans Hnorm; apply: lone_subgroup_char => // Q sQH isoQS. rewrite subEproper; apply/norP=> [[nQS _]]; move: nSyl5. rewrite (cardsD1 S) (cardsD1 Q) 4!{1}inE nQS !pHallE sQH sSH Hcard20 p_part. by rewrite (card_isog isoQS) oS. Qed. Section Restrict. Variables (T : finType) (x : T). Notation T' := {y | y != x}. Lemma rfd_funP (p : {perm T}) (u : T') : let p1 := if p x == x then p else 1 in p1 (val u) != x. Proof. case: (p x =P x) => /= [pxx | _]; last by rewrite perm1 (valP u). by rewrite -[x in _ != x]pxx (inj_eq perm_inj); apply: (valP u). Qed. Definition rfd_fun p := [fun u => Sub ((_ : {perm T}) _) (rfd_funP p u) : T']. Lemma rfdP p : injective (rfd_fun p). Proof. apply: can_inj (rfd_fun p^-1) _ => u; apply: val_inj => /=. rewrite -(can_eq (permK p)) permKV eq_sym. by case: eqP => _; rewrite !(perm1, permK). Qed. Definition rfd p := perm (@rfdP p). Hypothesis card_T : 2 < #|T|. Lemma rfd_morph : {in 'C_('Sym_T)[x | 'P] &, {morph rfd : y z / y * z}}. Proof. move=> p q; rewrite !setIA !setIid; move/astab1P=> p_x; move/astab1P=> q_x. apply/permP=> u; apply: val_inj. by rewrite permE /= !permM !permE /= [p x]p_x [q x]q_x eqxx permM /=. Qed. Canonical rfd_morphism := Morphism rfd_morph. Definition rgd_fun (p : {perm T'}) := [fun x1 => if insub x1 is Some u then sval (p u) else x]. Lemma rgdP p : injective (rgd_fun p). Proof. apply: can_inj (rgd_fun p^-1) _ => y /=. case: (insubP _ y) => [u _ val_u|]; first by rewrite valK permK. by rewrite negbK; move/eqP->; rewrite insubF //= eqxx. Qed. Definition rgd p := perm (@rgdP p). Lemma rfd_odd (p : {perm T}) : p x = x -> rfd p = p :> bool. Proof. have rfd1: rfd 1 = 1. by apply/permP => u; apply: val_inj; rewrite permE /= if_same !perm1. have [n] := ubnP #|[set x | p x != x]|; elim: n p => // n IHn p le_p_n px_x. have [p_id | [x1 Hx1]] := set_0Vmem [set x | p x != x]. suffices ->: p = 1 by rewrite rfd1 !odd_perm1. by apply/permP => z; apply: contraFeq (in_set0 z); rewrite perm1 -p_id inE. have nx1x: x1 != x by apply: contraTneq Hx1 => ->; rewrite inE px_x eqxx. have npxx1: p x != x1 by apply: contraNneq nx1x => <-; rewrite px_x. have npx1x: p x1 != x by rewrite -px_x (inj_eq perm_inj). pose p1 := p * tperm x1 (p x1). have fix_p1 y: p y = y -> p1 y = y. by move=> pyy; rewrite permM; have [<-|/perm_inj<-|] := tpermP; rewrite ?pyy. have p1x_x: p1 x = x by apply: fix_p1. have{le_p_n} lt_p1_n: #|[set x | p1 x != x]| < n. move: le_p_n; rewrite ltnS (cardsD1 x1) Hx1; apply/leq_trans/subset_leq_card. rewrite subsetD1 inE permM tpermR eqxx andbT. by apply/subsetP=> y /[!inE]; apply: contraNneq=> /fix_p1->. transitivity (p1 (+) true); last first. by rewrite odd_permM odd_tperm -Hx1 inE eq_sym addbK. have ->: p = p1 * tperm x1 (p x1) by rewrite -tpermV mulgK. rewrite morphM; last 2 first; first by rewrite 2!inE; apply/astab1P. by rewrite 2!inE; apply/astab1P; rewrite -[RHS]p1x_x permM px_x. rewrite odd_permM IHn //=; congr (_ (+) _). pose x2 : T' := Sub x1 nx1x; pose px2 : T' := Sub (p x1) npx1x. suffices ->: rfd (tperm x1 (p x1)) = tperm x2 px2. by rewrite odd_tperm eq_sym; rewrite inE in Hx1. apply/permP => z; apply/val_eqP; rewrite permE /= tpermD // eqxx. by rewrite !permE /= -!val_eqE /= !(fun_if sval) /=. Qed. Lemma rfd_iso : 'C_('Alt_T)[x | 'P] \isog 'Alt_T'. Proof. have rgd_x p: rgd p x = x by rewrite permE /= insubF //= eqxx. have rfd_rgd p: rfd (rgd p) = p. apply/permP => [[z Hz]]; apply/val_eqP; rewrite !permE. by rewrite /= [rgd _ _]permE /= insubF eqxx // permE /= insubT. have sSd: 'C_('Alt_T)[x | 'P] \subset 'dom rfd. by apply/subsetP=> p /[!inE]/= /andP[]. apply/isogP; exists [morphism of restrm sSd rfd] => /=; last first. rewrite morphim_restrm setIid; apply/setP=> z; apply/morphimP/idP=> [[p _]|]. case/setIP; rewrite Alt_even => Hp; move/astab1P=> Hp1 ->. by rewrite Alt_even rfd_odd. have dz': rgd z x == x by rewrite rgd_x. move=> kz; exists (rgd z); last by rewrite /= rfd_rgd. by rewrite 2!inE (sameP astab1P eqP). rewrite 4!inE /= (sameP astab1P eqP) dz' -rfd_odd; last exact/eqP. by rewrite rfd_rgd mker // ?set11. apply/injmP=> x1 y1 /=. case/setIP=> Hax1; move/astab1P; rewrite /= /aperm => Hx1. case/setIP=> Hay1; move/astab1P; rewrite /= /aperm => Hy1 Hr. apply/permP => z. case (z =P x) => [->|]; [by rewrite Hx1 | move/eqP => nzx]. move: (congr1 (fun q : {perm T'} => q (Sub z nzx)) Hr). by rewrite !permE => [[]]; rewrite Hx1 Hy1 !eqxx. Qed. End Restrict. Lemma simple_Alt5 (T : finType) : #|T| >= 5 -> simple 'Alt_T. Proof. suff F1 n: #|T| = n + 5 -> simple 'Alt_T by move/subnK/esym/F1. elim: n T => [| n Hrec T Hde]; first exact: simple_Alt5_base. have oT: 5 < #|T| by rewrite Hde addnC. apply/simpleP; split=> [|H Hnorm]; last have [Hh1 nH] := andP Hnorm. rewrite trivg_card1 -[#|_|]half_double -mul2n card_Alt Hde addnC //. by rewrite addSn factS mulnC -(prednK (fact_gt0 _)). case E1: (pred0b T); first by rewrite /pred0b in E1; rewrite (eqP E1) in oT. case/pred0Pn: E1 => x _; have Hx := in_setT x. have F2: [transitive^4 'Alt_T, on setT | 'P]. by apply: ntransitive_weak (Alt_trans T); rewrite -(subnKC oT). have F3 := ntransitive1 (isT: 0 < 4) F2. have F4 := ntransitive_primitive (isT: 1 < 4) F2. case Hcard1: (#|H| == 1%N); move/eqP: Hcard1 => Hcard1. by left; apply: card1_trivg; rewrite Hcard1. right; case: (prim_trans_norm F4 Hnorm) => F5. by rewrite (trivGP (subset_trans F5 (aperm_faithful _))) cards1 in Hcard1. case E1: (pred0b (predD1 T x)). rewrite /pred0b in E1; move: oT. by rewrite (cardD1 x) (eqP E1); case: (T x). case/pred0Pn: E1 => y Hdy; case/andP: (Hdy) => diff_x_y Hy. pose K := 'C_H[x | 'P]%G. have F8: K \subset H by apply: subsetIl. pose Gx := 'C_('Alt_T)[x | 'P]. have F9: [transitive^3 Gx, on [set~ x] | 'P]. by rewrite -[[set~ x]]setTI -setDE stab_ntransitive ?inE. have F10: [transitive Gx, on [set~ x] | 'P]. by apply: ntransitive1 F9. have F11: [primitive Gx, on [set~ x] | 'P]. by apply: ntransitive_primitive F9. have F12: K \subset Gx by rewrite setSI // normal_sub. have F13: K <| Gx by apply/andP; rewrite normsIG. have:= prim_trans_norm F11; case/(_ K) => //= => Ksub; last first. have F14: Gx * H = 'Alt_T by apply/(subgroup_transitiveP _ _ F3). have: simple Gx. by rewrite (isog_simple (rfd_iso x)) Hrec //= card_sig cardC1 Hde. case/simpleP=> _ simGx; case/simGx: F13 => /= HH2. case Ez: (pred0b (predD1 (predD1 T x) y)). move: oT; rewrite /pred0b in Ez. by rewrite (cardD1 x) (cardD1 y) (eqP Ez) inE /= inE /= diff_x_y. case/pred0Pn: Ez => z; case/andP => diff_y_z Hdz. have [diff_x_z Hz] := andP Hdz. have: z \in [set~ x] by rewrite !inE. rewrite -(atransP Ksub y) ?inE //; case/imsetP => g. rewrite /= HH2 inE; move/eqP=> -> HH4. by case/negP: diff_y_z; rewrite HH4 act1. by rewrite /= -F14 -[Gx]HH2 (mulSGid F8). have F14: [faithful Gx, on [set~ x] | 'P]. apply: subset_trans (aperm_faithful 'Sym_T); rewrite subsetI subsetT. apply/subsetP=> g; do 2![case/setIP]=> _ cgx cgx'; apply/astabP=> z _ /=. case: (z =P x) => [->|]; first exact: (astab1P cgx). by move/eqP=> zx; rewrite [_ g](astabP cgx') ?inE. have Hreg g z: g \in H -> g z = z -> g = 1. have F15 h: h \in H -> h x = x -> h = 1. move=> Hh Hhx; have: h \in K by rewrite inE Hh; apply/astab1P. by rewrite [K](trivGP (subset_trans Ksub F14)) => /set1P. move=> Hg Hgz; have:= in_setT x; rewrite -(atransP F3 z) ?inE //. case/imsetP=> g1 Hg1 Hg2; apply: (conjg_inj g1); rewrite conj1g. apply: F15; last by rewrite Hg2 -permM mulKVg permM Hgz. by rewrite memJ_norm ?(subsetP nH). clear K F8 F12 F13 Ksub F14. have Hcard: 5 < #|H|. apply: (leq_trans oT); apply: dvdn_leq; first exact: cardG_gt0. by rewrite -cardsT (atrans_dvd F5). case Eh: (pred0b [predD1 H & 1]). by move: Hcard; rewrite /pred0b in Eh; rewrite (cardD1 1) group1 (eqP Eh). case/pred0Pn: Eh => h; case/andP => diff_1_h /= Hh. case Eg: (pred0b (predD1 (predD1 [predD1 H & 1] h) h^-1)). move: Hcard; rewrite ltnNge; case/negP. rewrite (cardD1 1) group1 (cardD1 h) (cardD1 h^-1) (eqnP Eg). by do 2!case: (_ \in _). case/pred0Pn: Eg => g; case/andP => diff_h1_g; case/andP => diff_h_g. case/andP => diff_1_g /= Hg. case diff_hx_x: (h x == x). by case/negP: diff_1_h; apply/eqP; apply: (Hreg _ _ Hh (eqP diff_hx_x)). case diff_gx_x: (g x == x). case/negP: diff_1_g; apply/eqP; apply: (Hreg _ _ Hg (eqP diff_gx_x)). case diff_gx_hx: (g x == h x). case/negP: diff_h_g; apply/eqP; symmetry; apply: (mulIg g^-1); rewrite gsimp. apply: (Hreg _ x); first by rewrite groupM // groupV. by rewrite permM -(eqP diff_gx_hx) -permM mulgV perm1. case diff_hgx_x: ((h * g) x == x). case/negP: diff_h1_g; apply/eqP; apply: (mulgI h); rewrite !gsimp. by apply: (Hreg _ x); [apply: groupM | apply/eqP]. case diff_hgx_hx: ((h * g) x == h x). case/negP: diff_1_g; apply/eqP. by apply: (Hreg _ (h x)) => //; apply/eqP; rewrite -permM. case diff_hgx_gx: ((h * g) x == g x). by case/idP: diff_hx_x; rewrite -(can_eq (permK g)) -permM. case Ez: (pred0b (predD1 (predD1 (predD1 (predD1 T x) (h x)) (g x)) ((h * g) x))). - move: oT; rewrite /pred0b in Ez. rewrite (cardD1 x) (cardD1 (h x)) (cardD1 (g x)) (cardD1 ((h * g) x)). by rewrite (eqP Ez) addnC; do 3!case: (_ x \in _). case/pred0Pn: Ez => z. case/and5P=> diff_hgx_z diff_gx_z diff_hx_z diff_x_z /= Hz. pose S1 := [tuple x; h x; g x; z]. have DnS1: S1 \in 4.-dtuple(setT). rewrite inE memtE subset_all -!andbA !negb_or /= !inE !andbT. rewrite -!(eq_sym z) diff_gx_z diff_x_z diff_hx_z. by rewrite !(eq_sym x) diff_hx_x diff_gx_x eq_sym diff_gx_hx. pose S2 := [tuple x; h x; g x; (h * g) x]. have DnS2: S2 \in 4.-dtuple(setT). rewrite inE memtE subset_all -!andbA !negb_or /= !inE !andbT !(eq_sym x). rewrite diff_hx_x diff_gx_x diff_hgx_x. by rewrite !(eq_sym (h x)) diff_gx_hx diff_hgx_hx eq_sym diff_hgx_gx. case: (atransP2 F2 DnS1 DnS2) => k Hk [/=]. rewrite /aperm => Hkx Hkhx Hkgx Hkhgx. have h_k_com: h * k = k * h. suff HH: (k * h * k^-1) * h^-1 = 1 by rewrite -[h * k]mul1g -HH !gnorm. apply: (Hreg _ x); last first. by rewrite !permM -Hkx Hkhx -!permM mulKVg mulgV perm1. by rewrite groupM // ?groupV // (conjgCV k) mulgK -mem_conjg (normsP nH). have g_k_com: g * k = k * g. suff HH: (k * g * k^-1) * g^-1 = 1 by rewrite -[g * k]mul1g -HH !gnorm. apply: (Hreg _ x); last first. by rewrite !permM -Hkx Hkgx -!permM mulKVg mulgV perm1. by rewrite groupM // ?groupV // (conjgCV k) mulgK -mem_conjg (normsP nH). have HH: (k * (h * g) * k ^-1) x = z. by rewrite 2!permM -Hkx Hkhgx -permM mulgV perm1. case/negP: diff_hgx_z. rewrite -HH !mulgA -h_k_com -!mulgA [k * _]mulgA. by rewrite -g_k_com -!mulgA mulgV mulg1. Qed. Lemma gen_tperm_circular_shift (X : finType) x y c : prime #|X| -> x != y -> #[c]%g = #|X| -> <<[set tperm x y; c]>>%g = ('Sym_X)%g. Proof. move=> Xprime neq_xy ord_c; apply/eqP; rewrite eqEsubset subsetT/=. have c_gt1 : (1 < #[c]%g)%N by rewrite ord_c prime_gt1. have cppSS : #[c]%g.-2.+2 = #|X| by rewrite ?prednK ?ltn_predRL. pose f (i : 'Z_#[c]%g) : X := Zpm i x. have [g fK gK] : bijective f. apply: inj_card_bij; rewrite ?cppSS ?card_ord// /f /Zpm => i j cijx. pose stabx := ('C_<[c]>[x | 'P])%g. have cjix : (c ^+ (j - i)%R)%g x = x. by apply: (@perm_inj _ (c ^+ i)%g); rewrite -permM -expgD_Zp// addrNK. have : (c ^+ (j - i)%R)%g \in stabx. by rewrite !inE ?groupX ?mem_gen ?sub1set ?inE// ['P%act _ _]cjix eqxx. rewrite [stabx]perm_prime_astab// => /set1gP. move=> /(congr1 (mulg (c ^+ i))); rewrite -expgD_Zp// addrC addrNK mulg1. by move=> /eqP; rewrite eq_expg_ord// ?cppSS ?ord_c// => /eqP->. pose gsf s := g \o s \o f. have gsf_inj (s : {perm X}) : injective (gsf s). apply: inj_comp; last exact: can_inj fK. by apply: inj_comp; [exact: can_inj gK|exact: perm_inj]. pose fsg s := f \o s \o g. have fsg_inj (s : {perm _}) : injective (fsg s). apply: inj_comp; last exact: can_inj gK. by apply: inj_comp; [exact: can_inj fK|exact: perm_inj]. have gsf_morphic : morphic 'Sym_X (fun s => perm (gsf_inj s)). apply/morphicP => u v _ _; apply/permP => /= i. by rewrite !permE/= !permE /gsf /= gK permM. pose phi := morphm gsf_morphic; rewrite /= in phi. have phi_inj : ('injm phi)%g. apply/subsetP => /= u /mker/=; rewrite morphmE => gsfu1. apply/set1gP/permP=> z; have /permP/(_ (g z)) := gsfu1. by rewrite !perm1 permE /gsf/= gK => /(can_inj gK). have phiT : (phi @* 'Sym_X)%g = [set: {perm 'Z_#[c]%g}]. apply/eqP; rewrite eqEsubset subsetT/=; apply/subsetP => /= u _. apply/morphimP; exists (perm (fsg_inj u)); rewrite ?in_setT//. by apply/permP => /= i; rewrite morphmE permE /gsf/fsg/= permE/= !fK. have f0 : f 0%R = x by rewrite /f /Zpm permX. pose k := g y; have k_gt0 : (k > 0)%N. by rewrite lt0n (val_eqE k 0%R) -(can_eq fK) eq_sym gK f0. have phixy : phi (tperm x y) = tperm (0%R : 'Z_#[c]) k. apply/permP => i; rewrite permE/= /gsf/=; apply: (canLR fK). by rewrite !permE/= -f0 -[y]gK !(can_eq fK) -!fun_if. have phic : phi c = perm (addrI (1%R : 'Z_#[c])). apply/permP => i; rewrite /phi morphmE !permE /gsf/=; apply: (canLR fK). by rewrite /f /Zpm -permM addrC expgD_Zp. rewrite -(injmSK phi_inj)//= morphim_gen/= ?subsetT//= -/phi. rewrite phiT /morphim !setTI/= -/phi imsetU1 imset_set1/= phixy phic. suff /gen_tpermn_circular_shift<- : coprime #[c]%g.-2.+2 (k - 0)%R by []. by rewrite subr0 prime_coprime ?gtnNdvd// ?cppSS. Qed. Section Perm_solvable. Local Open Scope nat_scope. Variable T : finType. Lemma solvable_AltF : 4 < #|T| -> solvable 'Alt_T = false. Proof. move=> card_T; apply/negP => Alt_solvable. have/simple_Alt5 Alt_simple := card_T. have := simple_sol_prime Alt_solvable Alt_simple. have lt_T n : n <= 4 -> n < #|T| by move/leq_ltn_trans; apply. have -> : #|('Alt_T)%G| = #|T|`! %/ 2 by rewrite -card_Alt ?mulKn ?lt_T. move/even_prime => [/eqP|]; apply/negP. rewrite neq_ltn leq_divRL // mulnC -[2 * 3]/(3`!). by apply/orP; right; apply/ltnW/ltn_fact/lt_T. by rewrite -dvdn2 dvdn_divRL dvdn_fact //=; apply/ltnW/lt_T. Qed. Lemma solvable_SymF : 4 < #|T| -> solvable 'Sym_T = false. Proof. by rewrite (series_sol (Alt_normal T)) => /solvable_AltF->. Qed. End Perm_solvable.
FourierTransform.lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Analysis.SpecialFunctions.Gaussian.GaussianIntegral import Mathlib.Analysis.Complex.CauchyIntegral import Mathlib.MeasureTheory.Integral.Pi import Mathlib.Analysis.Fourier.FourierTransform /-! # Fourier transform of the Gaussian We prove that the Fourier transform of the Gaussian function is another Gaussian: * `integral_cexp_quadratic`: general formula for `∫ (x : ℝ), exp (b * x ^ 2 + c * x + d)` * `fourierIntegral_gaussian`: for all complex `b` and `t` with `0 < re b`, we have `∫ x:ℝ, exp (I * t * x) * exp (-b * x^2) = (π / b) ^ (1 / 2) * exp (-t ^ 2 / (4 * b))`. * `fourierIntegral_gaussian_pi`: a variant with `b` and `t` scaled to give a more symmetric statement, and formulated in terms of the Fourier transform operator `𝓕`. We also give versions of these formulas in finite-dimensional inner product spaces, see `integral_cexp_neg_mul_sq_norm_add` and `fourierIntegral_gaussian_innerProductSpace`. -/ /-! ## Fourier integral of Gaussian functions -/ open Real Set MeasureTheory Filter Asymptotics intervalIntegral open scoped Real Topology FourierTransform RealInnerProductSpace open Complex hiding exp continuous_exp abs_of_nonneg sq_abs noncomputable section namespace GaussianFourier variable {b : ℂ} /-- The integral of the Gaussian function over the vertical edges of a rectangle with vertices at `(±T, 0)` and `(±T, c)`. -/ def verticalIntegral (b : ℂ) (c T : ℝ) : ℂ := ∫ y : ℝ in (0 : ℝ)..c, I * (cexp (-b * (T + y * I) ^ 2) - cexp (-b * (T - y * I) ^ 2)) /-- Explicit formula for the norm of the Gaussian function along the vertical edges. -/ theorem norm_cexp_neg_mul_sq_add_mul_I (b : ℂ) (c T : ℝ) : ‖cexp (-b * (T + c * I) ^ 2)‖ = exp (-(b.re * T ^ 2 - 2 * b.im * c * T - b.re * c ^ 2)) := by rw [Complex.norm_exp, neg_mul, neg_re, ← re_add_im b] simp only [sq, re_add_im, mul_re, mul_im, add_re, add_im, ofReal_re, ofReal_im, I_re, I_im] ring_nf theorem norm_cexp_neg_mul_sq_add_mul_I' (hb : b.re ≠ 0) (c T : ℝ) : ‖cexp (-b * (T + c * I) ^ 2)‖ = exp (-(b.re * (T - b.im * c / b.re) ^ 2 - c ^ 2 * (b.im ^ 2 / b.re + b.re))) := by have : b.re * T ^ 2 - 2 * b.im * c * T - b.re * c ^ 2 = b.re * (T - b.im * c / b.re) ^ 2 - c ^ 2 * (b.im ^ 2 / b.re + b.re) := by field_simp; ring rw [norm_cexp_neg_mul_sq_add_mul_I, this] theorem verticalIntegral_norm_le (hb : 0 < b.re) (c : ℝ) {T : ℝ} (hT : 0 ≤ T) : ‖verticalIntegral b c T‖ ≤ (2 : ℝ) * |c| * exp (-(b.re * T ^ 2 - (2 : ℝ) * |b.im| * |c| * T - b.re * c ^ 2)) := by -- first get uniform bound for integrand have vert_norm_bound : ∀ {T : ℝ}, 0 ≤ T → ∀ {c y : ℝ}, |y| ≤ |c| → ‖cexp (-b * (T + y * I) ^ 2)‖ ≤ exp (-(b.re * T ^ 2 - (2 : ℝ) * |b.im| * |c| * T - b.re * c ^ 2)) := by intro T hT c y hy rw [norm_cexp_neg_mul_sq_add_mul_I b] gcongr exp (- (_ - ?_ * _ - _ * ?_)) · (conv_lhs => rw [mul_assoc]); (conv_rhs => rw [mul_assoc]) gcongr _ * ?_ refine (le_abs_self _).trans ?_ rw [abs_mul] gcongr · rwa [sq_le_sq] -- now main proof apply (intervalIntegral.norm_integral_le_of_norm_le_const _).trans · rw [sub_zero] conv_lhs => simp only [mul_comm _ |c|] conv_rhs => conv => congr rw [mul_comm] rw [mul_assoc] · intro y hy have absy : |y| ≤ |c| := by rcases le_or_gt 0 c with (h | h) · rw [uIoc_of_le h] at hy rw [abs_of_nonneg h, abs_of_pos hy.1] exact hy.2 · rw [uIoc_of_ge h.le] at hy rw [abs_of_neg h, abs_of_nonpos hy.2, neg_le_neg_iff] exact hy.1.le rw [norm_mul, norm_I, one_mul, two_mul] refine (norm_sub_le _ _).trans (add_le_add (vert_norm_bound hT absy) ?_) rw [← abs_neg y] at absy simpa only [neg_mul, ofReal_neg] using vert_norm_bound hT absy theorem tendsto_verticalIntegral (hb : 0 < b.re) (c : ℝ) : Tendsto (verticalIntegral b c) atTop (𝓝 0) := by -- complete proof using squeeze theorem: rw [tendsto_zero_iff_norm_tendsto_zero] refine tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds ?_ (Eventually.of_forall fun _ => norm_nonneg _) ((eventually_ge_atTop (0 : ℝ)).mp (Eventually.of_forall fun T hT => verticalIntegral_norm_le hb c hT)) rw [(by ring : 0 = 2 * |c| * 0)] refine (tendsto_exp_atBot.comp (tendsto_neg_atTop_atBot.comp ?_)).const_mul _ apply tendsto_atTop_add_const_right simp_rw [sq, ← mul_assoc, ← sub_mul] refine Tendsto.atTop_mul_atTop₀ (tendsto_atTop_add_const_right _ _ ?_) tendsto_id exact (tendsto_const_mul_atTop_of_pos hb).mpr tendsto_id theorem integrable_cexp_neg_mul_sq_add_real_mul_I (hb : 0 < b.re) (c : ℝ) : Integrable fun x : ℝ => cexp (-b * (x + c * I) ^ 2) := by refine ⟨(Complex.continuous_exp.comp (continuous_const.mul ((continuous_ofReal.add continuous_const).pow 2))).aestronglyMeasurable, ?_⟩ rw [← hasFiniteIntegral_norm_iff] simp_rw [norm_cexp_neg_mul_sq_add_mul_I' hb.ne', neg_sub _ (c ^ 2 * _), sub_eq_add_neg _ (b.re * _), Real.exp_add] suffices Integrable fun x : ℝ => exp (-(b.re * x ^ 2)) by exact (Integrable.comp_sub_right this (b.im * c / b.re)).hasFiniteIntegral.const_mul _ simp_rw [← neg_mul] apply integrable_exp_neg_mul_sq hb theorem integral_cexp_neg_mul_sq_add_real_mul_I (hb : 0 < b.re) (c : ℝ) : ∫ x : ℝ, cexp (-b * (x + c * I) ^ 2) = (π / b) ^ (1 / 2 : ℂ) := by refine tendsto_nhds_unique (intervalIntegral_tendsto_integral (integrable_cexp_neg_mul_sq_add_real_mul_I hb c) tendsto_neg_atTop_atBot tendsto_id) ?_ set I₁ := fun T => ∫ x : ℝ in -T..T, cexp (-b * (x + c * I) ^ 2) with HI₁ let I₂ := fun T : ℝ => ∫ x : ℝ in -T..T, cexp (-b * (x : ℂ) ^ 2) let I₄ := fun T : ℝ => ∫ y : ℝ in (0 : ℝ)..c, cexp (-b * (T + y * I) ^ 2) let I₅ := fun T : ℝ => ∫ y : ℝ in (0 : ℝ)..c, cexp (-b * (-T + y * I) ^ 2) have C : ∀ T : ℝ, I₂ T - I₁ T + I * I₄ T - I * I₅ T = 0 := by intro T have := integral_boundary_rect_eq_zero_of_differentiableOn (fun z => cexp (-b * z ^ 2)) (-T) (T + c * I) (by refine Differentiable.differentiableOn (Differentiable.const_mul ?_ _).cexp exact differentiable_pow 2) simpa only [neg_im, ofReal_im, neg_zero, ofReal_zero, zero_mul, add_zero, neg_re, ofReal_re, add_re, mul_re, I_re, mul_zero, I_im, tsub_zero, add_im, mul_im, mul_one, zero_add, Algebra.id.smul_eq_mul, ofReal_neg] using this simp_rw [id, ← HI₁] have : I₁ = fun T : ℝ => I₂ T + verticalIntegral b c T := by ext1 T specialize C T rw [sub_eq_zero] at C unfold verticalIntegral rw [intervalIntegral.integral_const_mul, intervalIntegral.integral_sub] · simp_rw [(fun a b => by rw [sq]; ring_nf : ∀ a b : ℂ, (a - b * I) ^ 2 = (-a + b * I) ^ 2)] change I₁ T = I₂ T + I * (I₄ T - I₅ T) rw [mul_sub, ← C] abel all_goals apply Continuous.intervalIntegrable; continuity rw [this, ← add_zero ((π / b : ℂ) ^ (1 / 2 : ℂ)), ← integral_gaussian_complex hb] refine Tendsto.add ?_ (tendsto_verticalIntegral hb c) exact intervalIntegral_tendsto_integral (integrable_cexp_neg_mul_sq hb) tendsto_neg_atTop_atBot tendsto_id theorem _root_.integral_cexp_quadratic (hb : b.re < 0) (c d : ℂ) : ∫ x : ℝ, cexp (b * x ^ 2 + c * x + d) = (π / -b) ^ (1 / 2 : ℂ) * cexp (d - c^2 / (4 * b)) := by have hb' : b ≠ 0 := by contrapose! hb; rw [hb, zero_re] have h (x : ℝ) : cexp (b * x ^ 2 + c * x + d) = cexp (- -b * (x + c / (2 * b)) ^ 2) * cexp (d - c ^ 2 / (4 * b)) := by simp_rw [← Complex.exp_add] congr 1 field_simp ring_nf simp_rw [h, MeasureTheory.integral_mul_const] rw [← re_add_im (c / (2 * b))] simp_rw [← add_assoc, ← ofReal_add] rw [integral_add_right_eq_self fun a : ℝ ↦ cexp (- -b * (↑a + ↑(c / (2 * b)).im * I) ^ 2), integral_cexp_neg_mul_sq_add_real_mul_I ((neg_re b).symm ▸ (neg_pos.mpr hb))] lemma _root_.integrable_cexp_quadratic' (hb : b.re < 0) (c d : ℂ) : Integrable (fun (x : ℝ) ↦ cexp (b * x ^ 2 + c * x + d)) := by have hb' : b ≠ 0 := by contrapose! hb; rw [hb, zero_re] by_contra H simpa [hb', pi_ne_zero, Complex.exp_ne_zero, integral_undef H] using integral_cexp_quadratic hb c d lemma _root_.integrable_cexp_quadratic (hb : 0 < b.re) (c d : ℂ) : Integrable (fun (x : ℝ) ↦ cexp (-b * x ^ 2 + c * x + d)) := by have : (-b).re < 0 := by simpa using hb exact integrable_cexp_quadratic' this c d theorem _root_.fourierIntegral_gaussian (hb : 0 < b.re) (t : ℂ) : ∫ x : ℝ, cexp (I * t * x) * cexp (-b * x ^ 2) = (π / b) ^ (1 / 2 : ℂ) * cexp (-t ^ 2 / (4 * b)) := by conv => enter [1, 2, x]; rw [← Complex.exp_add, add_comm, ← add_zero (-b * x ^ 2 + I * t * x)] rw [integral_cexp_quadratic (show (-b).re < 0 by rwa [neg_re, neg_lt_zero]), neg_neg, zero_sub, mul_neg, div_neg, neg_neg, mul_pow, I_sq, neg_one_mul, mul_comm] theorem _root_.fourierIntegral_gaussian_pi' (hb : 0 < b.re) (c : ℂ) : (𝓕 fun x : ℝ => cexp (-π * b * x ^ 2 + 2 * π * c * x)) = fun t : ℝ => 1 / b ^ (1 / 2 : ℂ) * cexp (-π / b * (t + I * c) ^ 2) := by haveI : b ≠ 0 := by contrapose! hb; rw [hb, zero_re] have h : (-↑π * b).re < 0 := by simpa only [neg_mul, neg_re, re_ofReal_mul, neg_lt_zero] using mul_pos pi_pos hb ext1 t simp_rw [fourierIntegral_real_eq_integral_exp_smul, smul_eq_mul, ← Complex.exp_add, ← add_assoc] have (x : ℝ) : ↑(-2 * π * x * t) * I + -π * b * x ^ 2 + 2 * π * c * x = -π * b * x ^ 2 + (-2 * π * I * t + 2 * π * c) * x + 0 := by push_cast; ring simp_rw [this, integral_cexp_quadratic h, neg_mul, neg_neg] congr 2 · rw [← div_div, div_self <| ofReal_ne_zero.mpr pi_ne_zero, one_div, inv_cpow, ← one_div] rw [Ne, arg_eq_pi_iff, not_and_or, not_lt] exact Or.inl hb.le · field_simp [ofReal_ne_zero.mpr pi_ne_zero] ring_nf simp only [I_sq] ring theorem _root_.fourierIntegral_gaussian_pi (hb : 0 < b.re) : (𝓕 fun (x : ℝ) ↦ cexp (-π * b * x ^ 2)) = fun t : ℝ ↦ 1 / b ^ (1 / 2 : ℂ) * cexp (-π / b * t ^ 2) := by simpa only [mul_zero, zero_mul, add_zero] using fourierIntegral_gaussian_pi' hb 0 section InnerProductSpace variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [FiniteDimensional ℝ V] [MeasurableSpace V] [BorelSpace V] theorem integrable_cexp_neg_sum_mul_add {ι : Type*} [Fintype ι] {b : ι → ℂ} (hb : ∀ i, 0 < (b i).re) (c : ι → ℂ) : Integrable (fun (v : ι → ℝ) ↦ cexp (- ∑ i, b i * (v i : ℂ) ^ 2 + ∑ i, c i * v i)) := by simp_rw [← Finset.sum_neg_distrib, ← Finset.sum_add_distrib, Complex.exp_sum, ← neg_mul] apply Integrable.fintype_prod (f := fun i (v : ℝ) ↦ cexp (-b i * v^2 + c i * v)) (fun i ↦ ?_) convert integrable_cexp_quadratic (hb i) (c i) 0 using 3 with x simp only [add_zero] theorem integrable_cexp_neg_mul_sum_add {ι : Type*} [Fintype ι] (hb : 0 < b.re) (c : ι → ℂ) : Integrable (fun (v : ι → ℝ) ↦ cexp (- b * ∑ i, (v i : ℂ) ^ 2 + ∑ i, c i * v i)) := by simp_rw [neg_mul, Finset.mul_sum] exact integrable_cexp_neg_sum_mul_add (fun _ ↦ hb) c theorem integrable_cexp_neg_mul_sq_norm_add_of_euclideanSpace {ι : Type*} [Fintype ι] (hb : 0 < b.re) (c : ℂ) (w : EuclideanSpace ℝ ι) : Integrable (fun (v : EuclideanSpace ℝ ι) ↦ cexp (- b * ‖v‖^2 + c * ⟪w, v⟫)) := by have := EuclideanSpace.volume_preserving_measurableEquiv ι rw [← MeasurePreserving.integrable_comp_emb this.symm (MeasurableEquiv.measurableEmbedding _)] simp only [neg_mul, Function.comp_def] convert integrable_cexp_neg_mul_sum_add hb (fun i ↦ c * w i) using 3 with v simp only [EuclideanSpace.measurableEquiv, MeasurableEquiv.symm_mk, MeasurableEquiv.coe_mk, EuclideanSpace.norm_eq, Real.norm_eq_abs, sq_abs, PiLp.inner_apply, RCLike.inner_apply, conj_trivial, ofReal_sum, ofReal_mul, Finset.mul_sum, neg_mul, Finset.sum_neg_distrib, mul_assoc] norm_cast rw [sq_sqrt] · simp [Finset.mul_sum, mul_comm] · exact Finset.sum_nonneg (fun i _hi ↦ by positivity) /-- In a real inner product space, the complex exponential of minus the square of the norm plus a scalar product is integrable. Useful when discussing the Fourier transform of a Gaussian. -/ theorem integrable_cexp_neg_mul_sq_norm_add (hb : 0 < b.re) (c : ℂ) (w : V) : Integrable (fun (v : V) ↦ cexp (-b * ‖v‖^2 + c * ⟪w, v⟫)) := by let e := (stdOrthonormalBasis ℝ V).repr.symm rw [← e.measurePreserving.integrable_comp_emb e.toHomeomorph.measurableEmbedding] convert integrable_cexp_neg_mul_sq_norm_add_of_euclideanSpace hb c (e.symm w) with v simp only [neg_mul, Function.comp_apply, LinearIsometryEquiv.norm_map, LinearIsometryEquiv.symm_symm, LinearIsometryEquiv.inner_map_eq_flip] theorem integral_cexp_neg_sum_mul_add {ι : Type*} [Fintype ι] {b : ι → ℂ} (hb : ∀ i, 0 < (b i).re) (c : ι → ℂ) : ∫ v : ι → ℝ, cexp (- ∑ i, b i * (v i : ℂ) ^ 2 + ∑ i, c i * v i) = ∏ i, (π / b i) ^ (1 / 2 : ℂ) * cexp (c i ^ 2 / (4 * b i)) := by simp_rw [← Finset.sum_neg_distrib, ← Finset.sum_add_distrib, Complex.exp_sum, ← neg_mul] rw [integral_fintype_prod_volume_eq_prod (f := fun i (v : ℝ) ↦ cexp (-b i * v ^ 2 + c i * v))] congr with i have : (-b i).re < 0 := by simpa using hb i convert integral_cexp_quadratic this (c i) 0 using 1 <;> simp [div_neg] theorem integral_cexp_neg_mul_sum_add {ι : Type*} [Fintype ι] (hb : 0 < b.re) (c : ι → ℂ) : ∫ v : ι → ℝ, cexp (- b * ∑ i, (v i : ℂ) ^ 2 + ∑ i, c i * v i) = (π / b) ^ (Fintype.card ι / 2 : ℂ) * cexp ((∑ i, c i ^ 2) / (4 * b)) := by simp_rw [neg_mul, Finset.mul_sum, integral_cexp_neg_sum_mul_add (fun _ ↦ hb) c, one_div, Finset.prod_mul_distrib, Finset.prod_const, ← cpow_nat_mul, ← Complex.exp_sum, Fintype.card, Finset.sum_div, div_eq_mul_inv] theorem integral_cexp_neg_mul_sq_norm_add_of_euclideanSpace {ι : Type*} [Fintype ι] (hb : 0 < b.re) (c : ℂ) (w : EuclideanSpace ℝ ι) : ∫ v : EuclideanSpace ℝ ι, cexp (- b * ‖v‖^2 + c * ⟪w, v⟫) = (π / b) ^ (Fintype.card ι / 2 : ℂ) * cexp (c ^ 2 * ‖w‖^2 / (4 * b)) := by have := (EuclideanSpace.volume_preserving_measurableEquiv ι).symm rw [← this.integral_comp (MeasurableEquiv.measurableEmbedding _)] simp only [neg_mul] convert integral_cexp_neg_mul_sum_add hb (fun i ↦ c * w i) using 5 with _x y · simp only [EuclideanSpace.coe_measurableEquiv_symm, EuclideanSpace.norm_eq, PiLp.toLp_apply, Real.norm_eq_abs, sq_abs, neg_mul, neg_inj, mul_eq_mul_left_iff] norm_cast left rw [sq_sqrt] exact Finset.sum_nonneg (fun i _hi ↦ by positivity) · simp [PiLp.inner_apply, EuclideanSpace.measurableEquiv, Finset.mul_sum, mul_assoc] simp_rw [mul_comm] · simp only [EuclideanSpace.norm_eq, Real.norm_eq_abs, sq_abs, mul_pow, ← Finset.mul_sum] congr norm_cast rw [sq_sqrt] exact Finset.sum_nonneg (fun i _hi ↦ by positivity) theorem integral_cexp_neg_mul_sq_norm_add (hb : 0 < b.re) (c : ℂ) (w : V) : ∫ v : V, cexp (- b * ‖v‖^2 + c * ⟪w, v⟫) = (π / b) ^ (Module.finrank ℝ V / 2 : ℂ) * cexp (c ^ 2 * ‖w‖^2 / (4 * b)) := by let e := (stdOrthonormalBasis ℝ V).repr.symm rw [← e.measurePreserving.integral_comp e.toHomeomorph.measurableEmbedding] convert integral_cexp_neg_mul_sq_norm_add_of_euclideanSpace hb c (e.symm w) <;> simp [LinearIsometryEquiv.inner_map_eq_flip] theorem integral_cexp_neg_mul_sq_norm (hb : 0 < b.re) : ∫ v : V, cexp (- b * ‖v‖^2) = (π / b) ^ (Module.finrank ℝ V / 2 : ℂ) := by simpa using integral_cexp_neg_mul_sq_norm_add hb 0 (0 : V) theorem integral_rexp_neg_mul_sq_norm {b : ℝ} (hb : 0 < b) : ∫ v : V, rexp (- b * ‖v‖^2) = (π / b) ^ (Module.finrank ℝ V / 2 : ℝ) := by rw [← ofReal_inj] convert integral_cexp_neg_mul_sq_norm (show 0 < (b : ℂ).re from hb) (V := V) · change ofRealLI (∫ (v : V), rexp (-b * ‖v‖ ^ 2)) = ∫ (v : V), cexp (-↑b * ↑‖v‖ ^ 2) rw [← ofRealLI.integral_comp_comm] simp [ofRealLI] · rw [← ofReal_div, ofReal_cpow (by positivity)] simp theorem _root_.fourierIntegral_gaussian_innerProductSpace' (hb : 0 < b.re) (x w : V) : 𝓕 (fun v ↦ cexp (- b * ‖v‖^2 + 2 * π * Complex.I * ⟪x, v⟫)) w = (π / b) ^ (Module.finrank ℝ V / 2 : ℂ) * cexp (-π ^ 2 * ‖x - w‖ ^ 2 / b) := by simp only [neg_mul, fourierIntegral_eq', ofReal_neg, ofReal_mul, ofReal_ofNat, smul_eq_mul, ← Complex.exp_add, real_inner_comm w] convert integral_cexp_neg_mul_sq_norm_add hb (2 * π * Complex.I) (x - w) using 3 with v · congr 1 simp [inner_sub_left] ring · have : b ≠ 0 := by contrapose! hb; rw [hb, zero_re] simp [mul_pow] ring theorem _root_.fourierIntegral_gaussian_innerProductSpace (hb : 0 < b.re) (w : V) : 𝓕 (fun v ↦ cexp (- b * ‖v‖^2)) w = (π / b) ^ (Module.finrank ℝ V / 2 : ℂ) * cexp (-π ^ 2 * ‖w‖^2 / b) := by simpa using fourierIntegral_gaussian_innerProductSpace' hb 0 w end InnerProductSpace end GaussianFourier
CHSH.lean
/- Copyright (c) 2020 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.Algebra.CharP.Invertible import Mathlib.Algebra.Order.Star.Basic import Mathlib.Algebra.Ring.Regular import Mathlib.Data.Real.Sqrt import Mathlib.Data.Real.Star import Mathlib.Tactic.Polyrith /-! # The Clauser-Horne-Shimony-Holt inequality and Tsirelson's inequality. We establish a version of the Clauser-Horne-Shimony-Holt (CHSH) inequality (which is a generalization of Bell's inequality). This is a foundational result which implies that quantum mechanics is not a local hidden variable theory. As usually stated the CHSH inequality requires substantial language from physics and probability, but it is possible to give a statement that is purely about ordered `*`-algebras. We do that here, to avoid as many practical and logical dependencies as possible. Since the algebra of observables of any quantum system is an ordered `*`-algebra (in particular a von Neumann algebra) this is a strict generalization of the usual statement. Let `R` be a `*`-ring. A CHSH tuple in `R` consists of * four elements `A₀ A₁ B₀ B₁ : R`, such that * each `Aᵢ` and `Bⱼ` is a self-adjoint involution, and * the `Aᵢ` commute with the `Bⱼ`. The physical interpretation is that the four elements are observables (hence self-adjoint) that take values ±1 (hence involutions), and that the `Aᵢ` are spacelike separated from the `Bⱼ` (and hence commute). The CHSH inequality says that when `R` is an ordered `*`-ring (that is, a `*`-ring which is ordered, and for every `r : R`, `0 ≤ star r * r`), which is moreover *commutative*, we have `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2` On the other hand, Tsirelson's inequality says that for any ordered `*`-ring we have `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2√2` (A caveat: in the commutative case we need 2⁻¹ in the ring, and in the noncommutative case we need √2 and √2⁻¹. To keep things simple we just assume our rings are ℝ-algebras.) The proofs I've seen in the literature either assume a significant framework for quantum mechanics, or assume the ring is a `C^*`-algebra. In the `C^*`-algebra case, the order structure is completely determined by the `*`-algebra structure: `0 ≤ A` iff there exists some `B` so `A = star B * B`. There's a nice proof of both bounds in this setting at https://en.wikipedia.org/wiki/Tsirelson%27s_bound The proof given here is purely algebraic. ## Future work One can show that Tsirelson's inequality is tight. In the `*`-ring of n-by-n complex matrices, if `A ≤ λ I` for some `λ : ℝ`, then every eigenvalue has absolute value at most `λ`. There is a CHSH tuple in 4-by-4 matrices such that `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁` has `2√2` as an eigenvalue. ## References * [Clauser, Horne, Shimony, Holt, *Proposed experiment to test local hidden-variable theories*][zbMATH06785026] * [Bell, *On the Einstein Podolsky Rosen Paradox*][MR3790629] * [Tsirelson, *Quantum generalizations of Bell's inequality*][MR577178] -/ universe u /-- A CHSH tuple in a *-monoid consists of 4 self-adjoint involutions `A₀ A₁ B₀ B₁` such that the `Aᵢ` commute with the `Bⱼ`. The physical interpretation is that `A₀` and `A₁` are a pair of boolean observables which are spacelike separated from another pair `B₀` and `B₁` of boolean observables. -/ structure IsCHSHTuple {R} [Monoid R] [StarMul R] (A₀ A₁ B₀ B₁ : R) : Prop where A₀_inv : A₀ ^ 2 = 1 A₁_inv : A₁ ^ 2 = 1 B₀_inv : B₀ ^ 2 = 1 B₁_inv : B₁ ^ 2 = 1 A₀_sa : star A₀ = A₀ A₁_sa : star A₁ = A₁ B₀_sa : star B₀ = B₀ B₁_sa : star B₁ = B₁ A₀B₀_commutes : A₀ * B₀ = B₀ * A₀ A₀B₁_commutes : A₀ * B₁ = B₁ * A₀ A₁B₀_commutes : A₁ * B₀ = B₀ * A₁ A₁B₁_commutes : A₁ * B₁ = B₁ * A₁ variable {R : Type u} theorem CHSH_id [CommRing R] {A₀ A₁ B₀ B₁ : R} (A₀_inv : A₀ ^ 2 = 1) (A₁_inv : A₁ ^ 2 = 1) (B₀_inv : B₀ ^ 2 = 1) (B₁_inv : B₁ ^ 2 = 1) : (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁) * (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁) = 4 * (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁) := by -- polyrith suggests: linear_combination (2 * B₀ * B₁ + 2) * A₀_inv + (B₀ ^ 2 - 2 * B₀ * B₁ + B₁ ^ 2) * A₁_inv + (A₀ ^ 2 + 2 * A₀ * A₁ + 1) * B₀_inv + (A₀ ^ 2 - 2 * A₀ * A₁ + 1) * B₁_inv /-- Given a CHSH tuple (A₀, A₁, B₀, B₁) in a *commutative* ordered `*`-algebra over ℝ, `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2`. (We could work over ℤ[⅟2] if we wanted to!) -/ theorem CHSH_inequality_of_comm [CommRing R] [PartialOrder R] [StarRing R] [StarOrderedRing R] [Algebra ℝ R] [OrderedSMul ℝ R] (A₀ A₁ B₀ B₁ : R) (T : IsCHSHTuple A₀ A₁ B₀ B₁) : A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2 := by let P := 2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁ have i₁ : 0 ≤ P := by have idem : P * P = 4 * P := CHSH_id T.A₀_inv T.A₁_inv T.B₀_inv T.B₁_inv have idem' : P = (1 / 4 : ℝ) • (P * P) := by have h : 4 * P = (4 : ℝ) • P := by simp [map_ofNat, Algebra.smul_def] rw [idem, h, ← mul_smul] norm_num have sa : star P = P := by dsimp [P] simp only [star_add, star_sub, star_mul, star_ofNat, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa, mul_comm B₀, mul_comm B₁] simpa only [← idem', sa] using smul_nonneg (by simp : (0 : ℝ) ≤ 1 / 4) (star_mul_self_nonneg P) apply le_of_sub_nonneg simpa only [sub_add_eq_sub_sub, ← sub_add] using i₁ /-! We now prove some rather specialized lemmas in preparation for the Tsirelson inequality, which we hide in a namespace as they are unlikely to be useful elsewhere. -/ namespace TsirelsonInequality /-! Before proving Tsirelson's bound, we prepare some easy lemmas about √2. -/ -- This calculation, which we need for Tsirelson's bound, -- defeated me. Thanks for the rescue from Shing Tak Lam! theorem tsirelson_inequality_aux : √2 * √2 ^ 3 = √2 * (2 * (√2)⁻¹ + 4 * ((√2)⁻¹ * 2⁻¹)) := by ring_nf rw [mul_inv_cancel₀ (ne_of_gt (Real.sqrt_pos.2 (show (2 : ℝ) > 0 by simp)))] convert congr_arg (· ^ 2) (@Real.sq_sqrt 2 (by simp)) using 1 <;> (try simp only [← pow_mul]) <;> norm_num theorem sqrt_two_inv_mul_self : (√2)⁻¹ * (√2)⁻¹ = (2⁻¹ : ℝ) := by rw [← mul_inv] norm_num end TsirelsonInequality open TsirelsonInequality /-- In a noncommutative ordered `*`-algebra over ℝ, Tsirelson's bound for a CHSH tuple (A₀, A₁, B₀, B₁) is `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2^(3/2) • 1`. We prove this by providing an explicit sum-of-squares decomposition of the difference. (We could work over `ℤ[2^(1/2), 2^(-1/2)]` if we really wanted to!) -/ theorem tsirelson_inequality [Ring R] [PartialOrder R] [StarRing R] [StarOrderedRing R] [Algebra ℝ R] [OrderedSMul ℝ R] [StarModule ℝ R] (A₀ A₁ B₀ B₁ : R) (T : IsCHSHTuple A₀ A₁ B₀ B₁) : A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ √2 ^ 3 • (1 : R) := by -- abel will create `ℤ` multiplication. We will `simp` them away to `ℝ` multiplication. have M : ∀ (m : ℤ) (a : ℝ) (x : R), m • a • x = ((m : ℝ) * a) • x := fun m a x => by rw [← Int.cast_smul_eq_zsmul ℝ, ← mul_smul] let P := (√2)⁻¹ • (A₁ + A₀) - B₀ let Q := (√2)⁻¹ • (A₁ - A₀) + B₁ have w : √2 ^ 3 • (1 : R) - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁ = (√2)⁻¹ • (P ^ 2 + Q ^ 2) := by dsimp [P, Q] -- distribute out all the powers and products appearing on the RHS simp only [sq, sub_mul, mul_sub, add_mul, mul_add, smul_add, smul_sub] -- pull all coefficients out to the front, and combine `√2`s where possible simp only [Algebra.mul_smul_comm, Algebra.smul_mul_assoc, ← mul_smul, sqrt_two_inv_mul_self] -- replace Aᵢ * Aᵢ = 1 and Bᵢ * Bᵢ = 1 simp only [← sq, T.A₀_inv, T.A₁_inv, T.B₀_inv, T.B₁_inv] -- move Aᵢ to the left of Bᵢ simp only [← T.A₀B₀_commutes, ← T.A₀B₁_commutes, ← T.A₁B₀_commutes, ← T.A₁B₁_commutes] -- collect terms, simplify coefficients, and collect terms again: abel_nf -- all terms coincide, but the last one. Simplify all other terms simp only [M] simp only [neg_mul, mul_inv_cancel_of_invertible, add_assoc, add_comm, add_left_comm, one_smul, Int.cast_neg, neg_smul, Int.cast_ofNat] simp only [← add_assoc, ← add_smul] -- just look at the coefficients now: congr exact mul_left_cancel₀ (by simp) tsirelson_inequality_aux have pos : 0 ≤ (√2)⁻¹ • (P ^ 2 + Q ^ 2) := by have P_sa : star P = P := by simp only [P, star_smul, star_add, star_sub, star_id_of_comm, T.A₀_sa, T.A₁_sa, T.B₀_sa] have Q_sa : star Q = Q := by simp only [Q, star_smul, star_add, star_sub, star_id_of_comm, T.A₀_sa, T.A₁_sa, T.B₁_sa] have P2_nonneg : 0 ≤ P ^ 2 := by simpa only [P_sa, sq] using star_mul_self_nonneg P have Q2_nonneg : 0 ≤ Q ^ 2 := by simpa only [Q_sa, sq] using star_mul_self_nonneg Q positivity apply le_of_sub_nonneg simpa only [sub_add_eq_sub_sub, ← sub_add, w, Nat.cast_zero] using pos
Basic.lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.CategoryTheory.Whiskering import Mathlib.CategoryTheory.Functor.FullyFaithful import Mathlib.CategoryTheory.NatIso /-! # Disjoint union of categories We define the category structure on a sigma-type (disjoint union) of categories. -/ namespace CategoryTheory namespace Sigma universe w₁ w₂ w₃ v₁ v₂ u₁ u₂ variable {I : Type w₁} {C : I → Type u₁} [∀ i, Category.{v₁} (C i)] /-- The type of morphisms of a disjoint union of categories: for `X : C i` and `Y : C j`, a morphism `(i, X) ⟶ (j, Y)` if `i = j` is just a morphism `X ⟶ Y`, and if `i ≠ j` there are no such morphisms. -/ inductive SigmaHom : (Σ i, C i) → (Σ i, C i) → Type max w₁ v₁ u₁ | mk : ∀ {i : I} {X Y : C i}, (X ⟶ Y) → SigmaHom ⟨i, X⟩ ⟨i, Y⟩ namespace SigmaHom /-- The identity morphism on an object. -/ def id : ∀ X : Σ i, C i, SigmaHom X X | ⟨_, _⟩ => mk (𝟙 _) -- Porting note: reordered universes instance (X : Σ i, C i) : Inhabited (SigmaHom X X) := ⟨id X⟩ /-- Composition of sigma homomorphisms. -/ def comp : ∀ {X Y Z : Σ i, C i}, SigmaHom X Y → SigmaHom Y Z → SigmaHom X Z | _, _, _, mk f, mk g => mk (f ≫ g) -- Porting note: reordered universes instance : CategoryStruct (Σ i, C i) where Hom := SigmaHom id := id comp f g := comp f g @[simp] lemma comp_def (i : I) (X Y Z : C i) (f : X ⟶ Y) (g : Y ⟶ Z) : comp (mk f) (mk g) = mk (f ≫ g) := rfl lemma assoc : ∀ {X Y Z W : Σ i, C i} (f : X ⟶ Y) (g : Y ⟶ Z) (h : Z ⟶ W), (f ≫ g) ≫ h = f ≫ g ≫ h | _, _, _, _, mk _, mk _, mk _ => congr_arg mk (Category.assoc _ _ _) lemma id_comp : ∀ {X Y : Σ i, C i} (f : X ⟶ Y), 𝟙 X ≫ f = f | _, _, mk _ => congr_arg mk (Category.id_comp _) lemma comp_id : ∀ {X Y : Σ i, C i} (f : X ⟶ Y), f ≫ 𝟙 Y = f | _, _, mk _ => congr_arg mk (Category.comp_id _) end SigmaHom instance sigma : Category (Σ i, C i) where id_comp := SigmaHom.id_comp comp_id := SigmaHom.comp_id assoc := SigmaHom.assoc /-- The inclusion functor into the disjoint union of categories. -/ @[simps map] def incl (i : I) : C i ⥤ Σ i, C i where obj X := ⟨i, X⟩ map := SigmaHom.mk @[simp] lemma incl_obj {i : I} (X : C i) : (incl i).obj X = ⟨i, X⟩ := rfl instance (i : I) : Functor.Full (incl i : C i ⥤ Σ i, C i) where map_surjective := fun ⟨f⟩ => ⟨f, rfl⟩ instance (i : I) : Functor.Faithful (incl i : C i ⥤ Σ i, C i) where map_injective {_ _ _ _} h := by injection h section variable {D : Type u₂} [Category.{v₂} D] (F : ∀ i, C i ⥤ D) /-- To build a natural transformation over the sigma category, it suffices to specify it restricted to each subcategory. -/ def natTrans {F G : (Σ i, C i) ⥤ D} (h : ∀ i : I, incl i ⋙ F ⟶ incl i ⋙ G) : F ⟶ G where app := fun ⟨j, X⟩ => (h j).app X naturality := by rintro ⟨j, X⟩ ⟨_, _⟩ ⟨f⟩ apply (h j).naturality @[simp] lemma natTrans_app {F G : (Σ i, C i) ⥤ D} (h : ∀ i : I, incl i ⋙ F ⟶ incl i ⋙ G) (i : I) (X : C i) : (natTrans h).app ⟨i, X⟩ = (h i).app X := rfl /-- (Implementation). An auxiliary definition to build the functor `desc`. -/ def descMap : ∀ X Y : Σ i, C i, (X ⟶ Y) → ((F X.1).obj X.2 ⟶ (F Y.1).obj Y.2) | _, _, SigmaHom.mk g => (F _).map g -- Porting note: reordered universes /-- Given a collection of functors `F i : C i ⥤ D`, we can produce a functor `(Σ i, C i) ⥤ D`. The produced functor `desc F` satisfies: `incl i ⋙ desc F ≅ F i`, i.e. restricted to just the subcategory `C i`, `desc F` agrees with `F i`, and it is unique (up to natural isomorphism) with this property. This witnesses that the sigma-type is the coproduct in Cat. -/ @[simps obj] def desc : (Σ i, C i) ⥤ D where obj X := (F X.1).obj X.2 map g := descMap F _ _ g map_id := by rintro ⟨i, X⟩ apply (F i).map_id map_comp := by rintro ⟨i, X⟩ ⟨_, Y⟩ ⟨_, Z⟩ ⟨f⟩ ⟨g⟩ apply (F i).map_comp @[simp] lemma desc_map_mk {i : I} (X Y : C i) (f : X ⟶ Y) : (desc F).map (SigmaHom.mk f) = (F i).map f := rfl -- We hand-generate the simp lemmas about this since they come out cleaner. /-- This shows that when `desc F` is restricted to just the subcategory `C i`, `desc F` agrees with `F i`. -/ def inclDesc (i : I) : incl i ⋙ desc F ≅ F i := NatIso.ofComponents fun _ => Iso.refl _ @[simp] lemma inclDesc_hom_app (i : I) (X : C i) : (inclDesc F i).hom.app X = 𝟙 ((F i).obj X) := rfl @[simp] lemma inclDesc_inv_app (i : I) (X : C i) : (inclDesc F i).inv.app X = 𝟙 ((F i).obj X) := rfl /-- If `q` when restricted to each subcategory `C i` agrees with `F i`, then `q` is isomorphic to `desc F`. -/ def descUniq (q : (Σ i, C i) ⥤ D) (h : ∀ i, incl i ⋙ q ≅ F i) : q ≅ desc F := NatIso.ofComponents (fun ⟨i, X⟩ => (h i).app X) <| by rintro ⟨i, X⟩ ⟨_, _⟩ ⟨f⟩ apply (h i).hom.naturality f @[simp] lemma descUniq_hom_app (q : (Σ i, C i) ⥤ D) (h : ∀ i, incl i ⋙ q ≅ F i) (i : I) (X : C i) : (descUniq F q h).hom.app ⟨i, X⟩ = (h i).hom.app X := rfl @[simp] lemma descUniq_inv_app (q : (Σ i, C i) ⥤ D) (h : ∀ i, incl i ⋙ q ≅ F i) (i : I) (X : C i) : (descUniq F q h).inv.app ⟨i, X⟩ = (h i).inv.app X := rfl /-- If `q₁` and `q₂` when restricted to each subcategory `C i` agree, then `q₁` and `q₂` are isomorphic. -/ @[simps] def natIso {q₁ q₂ : (Σ i, C i) ⥤ D} (h : ∀ i, incl i ⋙ q₁ ≅ incl i ⋙ q₂) : q₁ ≅ q₂ where hom := natTrans fun i => (h i).hom inv := natTrans fun i => (h i).inv end section variable (C) {J : Type w₂} (g : J → I) /-- A function `J → I` induces a functor `Σ j, C (g j) ⥤ Σ i, C i`. -/ def map : (Σ j : J, C (g j)) ⥤ Σ i : I, C i := desc fun j => incl (g j) @[simp] lemma map_obj (j : J) (X : C (g j)) : (Sigma.map C g).obj ⟨j, X⟩ = ⟨g j, X⟩ := rfl @[simp] lemma map_map {j : J} {X Y : C (g j)} (f : X ⟶ Y) : (Sigma.map C g).map (SigmaHom.mk f) = SigmaHom.mk f := rfl /-- The functor `Sigma.map C g` restricted to the subcategory `C j` acts as the inclusion of `g j`. -/ @[simps!] def inclCompMap (j : J) : incl j ⋙ map C g ≅ incl (g j) := Iso.refl _ variable (I) /-- The functor `Sigma.map` applied to the identity function is just the identity functor. -/ @[simps!] def mapId : map C (id : I → I) ≅ 𝟭 (Σ i, C i) := natIso fun i => NatIso.ofComponents fun _ => Iso.refl _ variable {I} {K : Type w₃} -- Porting note: Had to expand (C ∘ g) to (fun x => C (g x)) in lemma statement -- so that the suitable category instances could be found /-- The functor `Sigma.map` applied to a composition is a composition of functors. -/ @[simps!] def mapComp (f : K → J) (g : J → I) : map (fun x ↦ C (g x)) f ⋙ (map C g :) ≅ map C (g ∘ f) := (descUniq _ _) fun k => (Functor.isoWhiskerRight (inclCompMap _ f k) (map C g :) :) ≪≫ inclCompMap _ g (f k) end namespace Functor -- variable {C} variable {D : I → Type u₁} [∀ i, Category.{v₁} (D i)] /-- Assemble an `I`-indexed family of functors into a functor between the sigma types. -/ def sigma (F : ∀ i, C i ⥤ D i) : (Σ i, C i) ⥤ Σ i, D i := desc fun i => F i ⋙ incl i end Functor namespace natTrans variable {D : I → Type u₁} [∀ i, Category.{v₁} (D i)] variable {F G : ∀ i, C i ⥤ D i} /-- Assemble an `I`-indexed family of natural transformations into a single natural transformation. -/ def sigma (α : ∀ i, F i ⟶ G i) : Functor.sigma F ⟶ Functor.sigma G where app f := SigmaHom.mk ((α f.1).app _) naturality := by rintro ⟨i, X⟩ ⟨_, _⟩ ⟨f⟩ change SigmaHom.mk _ = SigmaHom.mk _ rw [(α i).naturality] end natTrans end Sigma end CategoryTheory
CotangentLocalizationAway.lean
import Mathlib.RingTheory.Extension.Cotangent.LocalizationAway deprecated_module (since := "2025-05-11")
Construction.lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.CategoryTheory.MorphismProperty.Composition import Mathlib.CategoryTheory.MorphismProperty.IsInvertedBy import Mathlib.CategoryTheory.Category.Quiv /-! # Construction of the localized category This file constructs the localized category, obtained by formally inverting a class of maps `W : MorphismProperty C` in a category `C`. We first construct a quiver `LocQuiver W` whose objects are the same as those of `C` and whose maps are the maps in `C` and placeholders for the formal inverses of the maps in `W`. The localized category `W.Localization` is obtained by taking the quotient of the path category of `LocQuiver W` by the congruence generated by four types of relations. The obvious functor `Q W : C ⥤ W.Localization` satisfies the universal property of the localization. Indeed, if `G : C ⥤ D` sends morphisms in `W` to isomorphisms in `D` (i.e. we have `hG : W.IsInvertedBy G`), then there exists a unique functor `G' : W.Localization ⥤ D` such that `Q W ≫ G' = G`. This `G'` is `lift G hG`. The expected property of `lift G hG` if expressed by the lemma `fac` and the uniqueness is expressed by `uniq`. ## References * [P. Gabriel, M. Zisman, *Calculus of fractions and homotopy theory*][gabriel-zisman-1967] -/ noncomputable section open CategoryTheory.Category CategoryTheory.Functor namespace CategoryTheory -- category universes first for convenience universe uC' uD' uC uD variable {C : Type uC} [Category.{uC'} C] (W : MorphismProperty C) {D : Type uD} [Category.{uD'} D] namespace Localization namespace Construction /-- If `W : MorphismProperty C`, `LocQuiver W` is a quiver with the same objects as `C`, and whose morphisms are those in `C` and placeholders for formal inverses of the morphisms in `W`. -/ structure LocQuiver (W : MorphismProperty C) where /-- underlying object -/ obj : C instance : Quiver (LocQuiver W) where Hom A B := (A.obj ⟶ B.obj) ⊕ { f : B.obj ⟶ A.obj // W f } /-- The object in the path category of `LocQuiver W` attached to an object in the category `C` -/ def ιPaths (X : C) : Paths (LocQuiver W) := ⟨X⟩ /-- The morphism in the path category associated to a morphism in the original category. -/ @[simp] def ψ₁ {X Y : C} (f : X ⟶ Y) : ιPaths W X ⟶ ιPaths W Y := (Paths.of _).map (Sum.inl f) /-- The morphism in the path category corresponding to a formal inverse. -/ @[simp] def ψ₂ {X Y : C} (w : X ⟶ Y) (hw : W w) : ιPaths W Y ⟶ ιPaths W X := (Paths.of _).map (Sum.inr ⟨w, hw⟩) /-- The relations by which we take the quotient in order to get the localized category. -/ inductive relations : HomRel (Paths (LocQuiver W)) | id (X : C) : relations (ψ₁ W (𝟙 X)) (𝟙 _) | comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : relations (ψ₁ W (f ≫ g)) (ψ₁ W f ≫ ψ₁ W g) | Winv₁ {X Y : C} (w : X ⟶ Y) (hw : W w) : relations (ψ₁ W w ≫ ψ₂ W w hw) (𝟙 _) | Winv₂ {X Y : C} (w : X ⟶ Y) (hw : W w) : relations (ψ₂ W w hw ≫ ψ₁ W w) (𝟙 _) end Construction end Localization namespace MorphismProperty open Localization.Construction /-- The localized category obtained by formally inverting the morphisms in `W : MorphismProperty C` -/ def Localization := CategoryTheory.Quotient (Localization.Construction.relations W) instance : Category (Localization W) := by dsimp only [Localization] infer_instance /-- The obvious functor `C ⥤ W.Localization` -/ def Q : C ⥤ W.Localization where obj X := (Quotient.functor _).obj ((Paths.of _).obj ⟨X⟩) map f := (Quotient.functor _).map (ψ₁ W f) map_id X := Quotient.sound _ (relations.id X) map_comp f g := Quotient.sound _ (relations.comp f g) end MorphismProperty namespace Localization namespace Construction variable {W} /-- The isomorphism in `W.Localization` associated to a morphism `w` in W -/ def wIso {X Y : C} (w : X ⟶ Y) (hw : W w) : Iso (W.Q.obj X) (W.Q.obj Y) where hom := W.Q.map w inv := (Quotient.functor _).map (by dsimp; exact (Paths.of _).map (Sum.inr ⟨w, hw⟩)) hom_inv_id := Quotient.sound _ (relations.Winv₁ w hw) inv_hom_id := Quotient.sound _ (relations.Winv₂ w hw) /-- The formal inverse in `W.Localization` of a morphism `w` in `W`. -/ abbrev wInv {X Y : C} (w : X ⟶ Y) (hw : W w) := (wIso w hw).inv variable (W) in theorem _root_.CategoryTheory.MorphismProperty.Q_inverts : W.IsInvertedBy W.Q := fun _ _ w hw => (Localization.Construction.wIso w hw).isIso_hom variable (G : C ⥤ D) (hG : W.IsInvertedBy G) /-- The lifting of a functor to the path category of `LocQuiver W` -/ @[simps!] def liftToPathCategory : Paths (LocQuiver W) ⥤ D := Quiv.lift { obj := fun X => G.obj X.obj map := by intros X Y rintro (f | ⟨g, hg⟩) · exact G.map f · haveI := hG g hg exact inv (G.map g) } /-- The lifting of a functor `C ⥤ D` inverting `W` as a functor `W.Localization ⥤ D` -/ @[simps!] def lift : W.Localization ⥤ D := Quotient.lift (relations W) (liftToPathCategory G hG) (by rintro ⟨X⟩ ⟨Y⟩ f₁ f₂ r rcases r with ⟨⟩ <;> all_goals aesop) @[simp] theorem fac : W.Q ⋙ lift G hG = G := Functor.ext (fun _ => rfl) (by intro X Y f simp only [Functor.comp_map, eqToHom_refl, comp_id, id_comp] dsimp [MorphismProperty.Q, Quot.liftOn, Quotient.functor] rw [composePath_toPath]) theorem uniq (G₁ G₂ : W.Localization ⥤ D) (h : W.Q ⋙ G₁ = W.Q ⋙ G₂) : G₁ = G₂ := by suffices h' : Quotient.functor _ ⋙ G₁ = Quotient.functor _ ⋙ G₂ by refine Functor.ext ?_ ?_ · rintro ⟨⟨X⟩⟩ apply Functor.congr_obj h · rintro ⟨⟨X⟩⟩ ⟨⟨Y⟩⟩ ⟨f⟩ apply Functor.congr_hom h' refine Paths.ext_functor ?_ ?_ · ext X cases X apply Functor.congr_obj h · rintro ⟨X⟩ ⟨Y⟩ (f | ⟨w, hw⟩) · simpa only using Functor.congr_hom h f · have hw : W.Q.map w = (wIso w hw).hom := rfl have hw' := Functor.congr_hom h w simp only [Functor.comp_map, hw] at hw' refine Functor.congr_inv_of_congr_hom _ _ _ ?_ ?_ hw' all_goals apply Functor.congr_obj h variable (W) in /-- The canonical bijection between objects in a category and its localization with respect to a morphism_property `W` -/ @[simps] def objEquiv : C ≃ W.Localization where toFun := W.Q.obj invFun X := X.as.obj right_inv := by rintro ⟨⟨X⟩⟩ rfl /-- A `MorphismProperty` in `W.Localization` is satisfied by all morphisms in the localized category if it contains the image of the morphisms in the original category, the inverses of the morphisms in `W` and if it is stable under composition -/ theorem morphismProperty_is_top (P : MorphismProperty W.Localization) [P.IsStableUnderComposition] (hP₁ : ∀ ⦃X Y : C⦄ (f : X ⟶ Y), P (W.Q.map f)) (hP₂ : ∀ ⦃X Y : C⦄ (w : X ⟶ Y) (hw : W w), P (wInv w hw)) : P = ⊤ := by funext X Y f ext constructor · intro apply MorphismProperty.top_apply · intro let G : _ ⥤ W.Localization := Quotient.functor _ haveI : G.Full := Quotient.full_functor _ suffices ∀ (X₁ X₂ : Paths (LocQuiver W)) (f : X₁ ⟶ X₂), P (G.map f) by rcases X with ⟨⟨X⟩⟩ rcases Y with ⟨⟨Y⟩⟩ simpa only [Functor.map_preimage] using this _ _ (G.preimage f) intros X₁ X₂ p induction p with | nil => simpa only [Functor.map_id] using hP₁ (𝟙 X₁.obj) | @cons X₂ X₃ p g hp => let p' : X₁ ⟶X₂ := p rw [show p'.cons g = p' ≫ Quiver.Hom.toPath g by rfl, G.map_comp] refine P.comp_mem _ _ hp ?_ rcases g with (g | ⟨g, hg⟩) · apply hP₁ · apply hP₂ /-- A `MorphismProperty` in `W.Localization` is satisfied by all morphisms in the localized category if it contains the image of the morphisms in the original category, if is stable under composition and if the property is stable by passing to inverses. -/ theorem morphismProperty_is_top' (P : MorphismProperty W.Localization) [P.IsStableUnderComposition] (hP₁ : ∀ ⦃X Y : C⦄ (f : X ⟶ Y), P (W.Q.map f)) (hP₂ : ∀ ⦃X Y : W.Localization⦄ (e : X ≅ Y) (_ : P e.hom), P e.inv) : P = ⊤ := morphismProperty_is_top P hP₁ (fun _ _ w _ => hP₂ _ (hP₁ w)) namespace NatTransExtension variable {F₁ F₂ : W.Localization ⥤ D} (τ : W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂) /-- If `F₁` and `F₂` are functors `W.Localization ⥤ D` and if we have `τ : W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂`, we shall define a natural transformation `F₁ ⟶ F₂`. This is the `app` field of this natural transformation. -/ def app (X : W.Localization) : F₁.obj X ⟶ F₂.obj X := eqToHom (congr_arg F₁.obj ((objEquiv W).right_inv X).symm) ≫ τ.app ((objEquiv W).invFun X) ≫ eqToHom (congr_arg F₂.obj ((objEquiv W).right_inv X)) @[simp] theorem app_eq (X : C) : (app τ) (W.Q.obj X) = τ.app X := by simp only [app, eqToHom_refl, comp_id, id_comp] rfl end NatTransExtension /-- If `F₁` and `F₂` are functors `W.Localization ⥤ D`, a natural transformation `F₁ ⟶ F₂` can be obtained from a natural transformation `W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂`. -/ @[simps] def natTransExtension {F₁ F₂ : W.Localization ⥤ D} (τ : W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂) : F₁ ⟶ F₂ where app := NatTransExtension.app τ naturality := by suffices MorphismProperty.naturalityProperty (NatTransExtension.app τ) = ⊤ by intro X Y f simpa only [← this] using MorphismProperty.top_apply f refine morphismProperty_is_top' (MorphismProperty.naturalityProperty (NatTransExtension.app τ)) ?_ (MorphismProperty.naturalityProperty.stableUnderInverse _) intros X Y f dsimp simpa only [NatTransExtension.app_eq] using τ.naturality f @[simp] theorem whiskerLeft_natTransExtension {F G : W.Localization ⥤ D} (τ : W.Q ⋙ F ⟶ W.Q ⋙ G) : whiskerLeft W.Q (natTransExtension τ) = τ := by cat_disch -- This is not a simp lemma, because the simp norm form of the left-hand side uses `whiskerLeft`. theorem natTransExtension_hcomp {F G : W.Localization ⥤ D} (τ : W.Q ⋙ F ⟶ W.Q ⋙ G) : 𝟙 W.Q ◫ natTransExtension τ = τ := by cat_disch theorem natTrans_hcomp_injective {F G : W.Localization ⥤ D} {τ₁ τ₂ : F ⟶ G} (h : 𝟙 W.Q ◫ τ₁ = 𝟙 W.Q ◫ τ₂) : τ₁ = τ₂ := by ext X have eq := (objEquiv W).right_inv X simp only [objEquiv] at eq rw [← eq, ← NatTrans.id_hcomp_app, ← NatTrans.id_hcomp_app, h] variable (W D) namespace WhiskeringLeftEquivalence /-- The functor `(W.Localization ⥤ D) ⥤ (W.FunctorsInverting D)` induced by the composition with `W.Q : C ⥤ W.Localization`. -/ @[simps!] def functor : (W.Localization ⥤ D) ⥤ W.FunctorsInverting D := ObjectProperty.lift _ ((whiskeringLeft _ _ D).obj W.Q) fun _ => MorphismProperty.IsInvertedBy.of_comp W W.Q W.Q_inverts _ /-- The function `(W.FunctorsInverting D) ⥤ (W.Localization ⥤ D)` induced by `Construction.lift`. -/ @[simps!] def inverse : W.FunctorsInverting D ⥤ W.Localization ⥤ D where obj G := lift G.obj G.property map τ := natTransExtension (eqToHom (by rw [fac]) ≫ τ ≫ eqToHom (by rw [fac])) map_id G := natTrans_hcomp_injective (by rw [natTransExtension_hcomp] ext X simp only [NatTrans.comp_app, eqToHom_app, eqToHom_refl, comp_id, id_comp, NatTrans.hcomp_id_app, NatTrans.id_app, Functor.map_id] rfl) map_comp τ₁ τ₂ := natTrans_hcomp_injective (by ext X simp only [natTransExtension_hcomp, NatTrans.comp_app, eqToHom_app, eqToHom_refl, id_comp, comp_id, NatTrans.hcomp_app, NatTrans.id_app, Functor.map_id, natTransExtension_app, NatTransExtension.app_eq] rfl) /-- The unit isomorphism of the equivalence of categories `whiskeringLeftEquivalence W D`. -/ @[simps!] def unitIso : 𝟭 (W.Localization ⥤ D) ≅ functor W D ⋙ inverse W D := eqToIso (by refine Functor.ext (fun G => ?_) fun G₁ G₂ τ => ?_ · apply uniq dsimp [Functor] erw [fac] rfl · apply natTrans_hcomp_injective ext X simp) /-- The counit isomorphism of the equivalence of categories `WhiskeringLeftEquivalence W D`. -/ @[simps!] def counitIso : inverse W D ⋙ functor W D ≅ 𝟭 (W.FunctorsInverting D) := eqToIso (by refine Functor.ext ?_ ?_ · rintro ⟨G, hG⟩ ext exact fac G hG · rintro ⟨G₁, hG₁⟩ ⟨G₂, hG₂⟩ f ext apply NatTransExtension.app_eq) end WhiskeringLeftEquivalence /-- The equivalence of categories `(W.localization ⥤ D) ≌ (W.FunctorsInverting D)` induced by the composition with `W.Q : C ⥤ W.localization`. -/ def whiskeringLeftEquivalence : W.Localization ⥤ D ≌ W.FunctorsInverting D where functor := WhiskeringLeftEquivalence.functor W D inverse := WhiskeringLeftEquivalence.inverse W D unitIso := WhiskeringLeftEquivalence.unitIso W D counitIso := WhiskeringLeftEquivalence.counitIso W D functor_unitIso_comp F := by ext simp only [WhiskeringLeftEquivalence.unitIso_hom, eqToHom_app, eqToHom_refl, WhiskeringLeftEquivalence.counitIso_hom, eqToHom_map, eqToHom_trans] rfl end Construction end Localization end CategoryTheory
GaussNorm.lean
/- Copyright (c) 2025 Fabrizio Barroero. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fabrizio Barroero -/ import Mathlib.Analysis.Normed.Ring.Basic import Mathlib.RingTheory.PowerSeries.Order /-! # Gauss norm for power series This file defines the Gauss norm for power series. Given a power series `f` in `R⟦X⟧`, a function `v : R → ℝ` and a real number `c`, the Gauss norm is defined as the supremum of the set of all values of `v (f.coeff R i) * c ^ i` for all `i : ℕ`. In case `f` is a polynomial, `v` is a non-negative function with `v 0 = 0` and `c ≥ 0`, `f.gaussNorm v c` reduces to the Gauss norm defined in `Mathlib/RingTheory/Polynomial/GaussNorm.lean`, see `Polynomial.gaussNorm_coe_powerSeries`. ## Main Definitions and Results * `PowerSeries.gaussNorm` is the supremum of the set of all values of `v (f.coeff R i) * c ^ i` for all `i : ℕ`, where `f` is a power series in `R⟦X⟧`, `v : R → ℝ` is a function and `c` is a real number. * `PowerSeries.gaussNorm_nonneg`: if `v` is a non-negative function, then the Gauss norm is non-negative. * `PowerSeries.gaussNorm_eq_zero_iff`: if `v` is a non-negative function and `v x = 0 ↔ x = 0` for all `x : R` and `c` is positive, then the Gauss norm is zero if and only if the power series is zero. -/ namespace PowerSeries variable {R F : Type*} [Semiring R] [FunLike F R ℝ] (v : F) (c : ℝ) (f : R⟦X⟧) /-- Given a power series `f` in `R⟦X⟧`, a function `v : R → ℝ` and a real number `c`, the Gauss norm is defined as the supremum of the set of all values of `v (f.coeff R i) * c ^ i` for all `i : ℕ`. -/ noncomputable def gaussNorm : ℝ := ⨆ i : ℕ, v (f.coeff R i) * c ^ i lemma le_gaussNorm (hbd : BddAbove {x | ∃ i, v (f.coeff R i) * c ^ i = x}) (i : ℕ) : v (f.coeff R i) * c ^ i ≤ f.gaussNorm v c := le_ciSup hbd i @[simp] theorem gaussNorm_zero [ZeroHomClass F R ℝ] : gaussNorm v c 0 = 0 := by simp [gaussNorm] theorem gaussNorm_nonneg [NonnegHomClass F R ℝ] : 0 ≤ f.gaussNorm v c := by by_cases h : BddAbove (Set.range fun i ↦ v (f.coeff R i) * c ^ i) · calc 0 ≤ v (f.coeff R 0) * c ^ 0 := mul_nonneg (apply_nonneg v (f.coeff R 0)) <| pow_nonneg (le_of_lt (zero_lt_one)) 0 _ ≤ f.gaussNorm v c := le_ciSup h 0 · simp [gaussNorm, h] @[simp] theorem gaussNorm_eq_zero_iff [ZeroHomClass F R ℝ] [NonnegHomClass F R ℝ] {v : F} (h_eq_zero : ∀ x : R, v x = 0 → x = 0) {f : R⟦X⟧} {c : ℝ} (hc : 0 < c) (hbd : BddAbove (Set.range fun i ↦ v (f.coeff R i) * c ^ i)) : f.gaussNorm v c = 0 ↔ f = 0 := by refine ⟨?_, fun hf ↦ by simp [hf]⟩ contrapose! intro hf apply ne_of_gt obtain ⟨n, hn⟩ := exists_coeff_ne_zero_iff_ne_zero.mpr hf calc 0 < v (f.coeff R n) * c ^ n := by have := fun h ↦ hn (h_eq_zero ((coeff R n) f) h) positivity _ ≤ gaussNorm v c f := le_ciSup hbd n end PowerSeries
LegendreSymbol.lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import Mathlib.NumberTheory.LegendreSymbol.JacobiSymbol /-! # A `norm_num` extension for Jacobi and Legendre symbols We extend the `norm_num` tactic so that it can be used to provably compute the value of the Jacobi symbol `J(a | b)` or the Legendre symbol `legendreSym p a` when the arguments are numerals. ## Implementation notes We use the Law of Quadratic Reciprocity for the Jacobi symbol to compute the value of `J(a | b)` efficiently, roughly comparable in effort with the euclidean algorithm for the computation of the gcd of `a` and `b`. More precisely, the computation is done in the following steps. * Use `J(a | 0) = 1` (an artifact of the definition) and `J(a | 1) = 1` to deal with corner cases. * Use `J(a | b) = J(a % b | b)` to reduce to the case that `a` is a natural number. We define a version of the Jacobi symbol restricted to natural numbers for use in the following steps; see `NormNum.jacobiSymNat`. (But we'll continue to write `J(a | b)` in this description.) * Remove powers of two from `b`. This is done via `J(2a | 2b) = 0` and `J(2a+1 | 2b) = J(2a+1 | b)` (another artifact of the definition). * Now `0 ≤ a < b` and `b` is odd. If `b = 1`, then the value is `1`. If `a = 0` (and `b > 1`), then the value is `0`. Otherwise, we remove powers of two from `a` via `J(4a | b) = J(a | b)` and `J(2a | b) = ±J(a | b)`, where the sign is determined by the residue class of `b` mod 8, to reduce to `a` odd. * Once `a` is odd, we use Quadratic Reciprocity (QR) in the form `J(a | b) = ±J(b % a | a)`, where the sign is determined by the residue classes of `a` and `b` mod 4. We are then back in the previous case. We provide customized versions of these results for the various reduction steps, where we encode the residue classes mod 2, mod 4, or mod 8 by using hypotheses like `a % n = b`. In this way, the only divisions we have to compute and prove are the ones occurring in the use of QR above. -/ section Lemmas namespace Mathlib.Meta.NormNum /-- The Jacobi symbol restricted to natural numbers in both arguments. -/ def jacobiSymNat (a b : ℕ) : ℤ := jacobiSym a b /-! ### API Lemmas We repeat part of the API for `jacobiSym` with `NormNum.jacobiSymNat` and without implicit arguments, in a form that is suitable for constructing proofs in `norm_num`. -/ /-- Base cases: `b = 0`, `b = 1`, `a = 0`, `a = 1`. -/ theorem jacobiSymNat.zero_right (a : ℕ) : jacobiSymNat a 0 = 1 := by rw [jacobiSymNat, jacobiSym.zero_right] theorem jacobiSymNat.one_right (a : ℕ) : jacobiSymNat a 1 = 1 := by rw [jacobiSymNat, jacobiSym.one_right] theorem jacobiSymNat.zero_left (b : ℕ) (hb : Nat.beq (b / 2) 0 = false) : jacobiSymNat 0 b = 0 := by rw [jacobiSymNat, Nat.cast_zero, jacobiSym.zero_left ?_] calc 1 < 2 * 1 := by decide _ ≤ 2 * (b / 2) := Nat.mul_le_mul_left _ (Nat.succ_le.mpr (Nat.pos_of_ne_zero (Nat.ne_of_beq_eq_false hb))) _ ≤ b := Nat.mul_div_le b 2 theorem jacobiSymNat.one_left (b : ℕ) : jacobiSymNat 1 b = 1 := by rw [jacobiSymNat, Nat.cast_one, jacobiSym.one_left] /-- Turn a Legendre symbol into a Jacobi symbol. -/ theorem LegendreSym.to_jacobiSym (p : ℕ) (pp : Fact p.Prime) (a r : ℤ) (hr : IsInt (jacobiSym a p) r) : IsInt (legendreSym p a) r := by rwa [@jacobiSym.legendreSym.to_jacobiSym p pp a] /-- The value depends only on the residue class of `a` mod `b`. -/ theorem JacobiSym.mod_left (a : ℤ) (b ab' : ℕ) (ab r b' : ℤ) (hb' : (b : ℤ) = b') (hab : a % b' = ab) (h : (ab' : ℤ) = ab) (hr : jacobiSymNat ab' b = r) : jacobiSym a b = r := by rw [← hr, jacobiSymNat, jacobiSym.mod_left, hb', hab, ← h] theorem jacobiSymNat.mod_left (a b ab : ℕ) (r : ℤ) (hab : a % b = ab) (hr : jacobiSymNat ab b = r) : jacobiSymNat a b = r := by rw [← hr, jacobiSymNat, jacobiSymNat, _root_.jacobiSym.mod_left a b, ← hab]; rfl /-- The symbol vanishes when both entries are even (and `b / 2 ≠ 0`). -/ theorem jacobiSymNat.even_even (a b : ℕ) (hb₀ : Nat.beq (b / 2) 0 = false) (ha : a % 2 = 0) (hb₁ : b % 2 = 0) : jacobiSymNat a b = 0 := by refine jacobiSym.eq_zero_iff.mpr ⟨ne_of_gt ((Nat.pos_of_ne_zero (Nat.ne_of_beq_eq_false hb₀)).trans_le (Nat.div_le_self b 2)), fun hf => ?_⟩ have h : 2 ∣ a.gcd b := Nat.dvd_gcd (Nat.dvd_of_mod_eq_zero ha) (Nat.dvd_of_mod_eq_zero hb₁) change 2 ∣ (a : ℤ).gcd b at h rw [hf, ← even_iff_two_dvd] at h exact Nat.not_even_one h /-- When `a` is odd and `b` is even, we can replace `b` by `b / 2`. -/ theorem jacobiSymNat.odd_even (a b c : ℕ) (r : ℤ) (ha : a % 2 = 1) (hb : b % 2 = 0) (hc : b / 2 = c) (hr : jacobiSymNat a c = r) : jacobiSymNat a b = r := by have ha' : legendreSym 2 a = 1 := by simp only [legendreSym.mod 2 a, Int.ofNat_mod_ofNat, ha] decide rcases eq_or_ne c 0 with (rfl | hc') · rw [← hr, Nat.eq_zero_of_dvd_of_div_eq_zero (Nat.dvd_of_mod_eq_zero hb) hc] · haveI : NeZero c := ⟨hc'⟩ -- for `jacobiSym.mul_right` rwa [← Nat.mod_add_div b 2, hb, hc, Nat.zero_add, jacobiSymNat, jacobiSym.mul_right, ← jacobiSym.legendreSym.to_jacobiSym, ha', one_mul] /-- If `a` is divisible by `4` and `b` is odd, then we can remove the factor `4` from `a`. -/ theorem jacobiSymNat.double_even (a b c : ℕ) (r : ℤ) (ha : a % 4 = 0) (hb : b % 2 = 1) (hc : a / 4 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = r := by simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat] exact (jacobiSym.div_four_left (mod_cast ha) hb).symm /-- If `a` is even and `b` is odd, then we can remove a factor `2` from `a`, but we may have to change the sign, depending on `b % 8`. We give one version for each of the four odd residue classes mod `8`. -/ theorem jacobiSymNat.even_odd₁ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 1) (hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = r := by simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat] rw [← jacobiSym.even_odd (mod_cast ha), if_neg (by simp [hb])] rw [← Nat.mod_mod_of_dvd, hb]; norm_num theorem jacobiSymNat.even_odd₇ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 7) (hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = r := by simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat] rw [← jacobiSym.even_odd (mod_cast ha), if_neg (by simp [hb])] rw [← Nat.mod_mod_of_dvd, hb]; norm_num theorem jacobiSymNat.even_odd₃ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 3) (hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = -r := by simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat] rw [← jacobiSym.even_odd (mod_cast ha), if_pos (by simp [hb])] rw [← Nat.mod_mod_of_dvd, hb]; norm_num theorem jacobiSymNat.even_odd₅ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 5) (hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = -r := by simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat] rw [← jacobiSym.even_odd (mod_cast ha), if_pos (by simp [hb])] rw [← Nat.mod_mod_of_dvd, hb]; norm_num /-- Use quadratic reciprocity to reduce to smaller `b`. -/ theorem jacobiSymNat.qr₁ (a b : ℕ) (r : ℤ) (ha : a % 4 = 1) (hb : b % 2 = 1) (hr : jacobiSymNat b a = r) : jacobiSymNat a b = r := by rwa [jacobiSymNat, jacobiSym.quadratic_reciprocity_one_mod_four ha (Nat.odd_iff.mpr hb)] theorem jacobiSymNat.qr₁_mod (a b ab : ℕ) (r : ℤ) (ha : a % 4 = 1) (hb : b % 2 = 1) (hab : b % a = ab) (hr : jacobiSymNat ab a = r) : jacobiSymNat a b = r := jacobiSymNat.qr₁ _ _ _ ha hb <| jacobiSymNat.mod_left _ _ ab r hab hr theorem jacobiSymNat.qr₁' (a b : ℕ) (r : ℤ) (ha : a % 2 = 1) (hb : b % 4 = 1) (hr : jacobiSymNat b a = r) : jacobiSymNat a b = r := by rwa [jacobiSymNat, ← jacobiSym.quadratic_reciprocity_one_mod_four hb (Nat.odd_iff.mpr ha)] theorem jacobiSymNat.qr₁'_mod (a b ab : ℕ) (r : ℤ) (ha : a % 2 = 1) (hb : b % 4 = 1) (hab : b % a = ab) (hr : jacobiSymNat ab a = r) : jacobiSymNat a b = r := jacobiSymNat.qr₁' _ _ _ ha hb <| jacobiSymNat.mod_left _ _ ab r hab hr theorem jacobiSymNat.qr₃ (a b : ℕ) (r : ℤ) (ha : a % 4 = 3) (hb : b % 4 = 3) (hr : jacobiSymNat b a = r) : jacobiSymNat a b = -r := by rwa [jacobiSymNat, jacobiSym.quadratic_reciprocity_three_mod_four ha hb, neg_inj] theorem jacobiSymNat.qr₃_mod (a b ab : ℕ) (r : ℤ) (ha : a % 4 = 3) (hb : b % 4 = 3) (hab : b % a = ab) (hr : jacobiSymNat ab a = r) : jacobiSymNat a b = -r := jacobiSymNat.qr₃ _ _ _ ha hb <| jacobiSymNat.mod_left _ _ ab r hab hr theorem isInt_jacobiSym : {a na : ℤ} → {b nb : ℕ} → {r : ℤ} → IsInt a na → IsNat b nb → jacobiSym na nb = r → IsInt (jacobiSym a b) r | _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩ theorem isInt_jacobiSymNat : {a na : ℕ} → {b nb : ℕ} → {r : ℤ} → IsNat a na → IsNat b nb → jacobiSymNat na nb = r → IsInt (jacobiSymNat a b) r | _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩ end Mathlib.Meta.NormNum end Lemmas section Evaluation /-! ### Certified evaluation of the Jacobi symbol The following functions recursively evaluate a Jacobi symbol and construct the corresponding proof term. -/ namespace Mathlib.Meta.NormNum open Lean Elab Tactic Qq /-- This evaluates `r := jacobiSymNat a b` recursively using quadratic reciprocity and produces a proof term for the equality, assuming that `a < b` and `b` is odd. -/ partial def proveJacobiSymOdd (ea eb : Q(ℕ)) : (er : Q(ℤ)) × Q(jacobiSymNat $ea $eb = $er) := match eb.natLit! with | 1 => haveI : $eb =Q 1 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSymNat.one_right $ea)⟩ | b => match ea.natLit! with | 0 => haveI : $ea =Q 0 := ⟨⟩ have hb : Q(Nat.beq ($eb / 2) 0 = false) := (q(Eq.refl false) : Expr) ⟨mkRawIntLit 0, q(jacobiSymNat.zero_left $eb $hb)⟩ | 1 => haveI : $ea =Q 1 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSymNat.one_left $eb)⟩ | a => match a % 2 with | 0 => match a % 4 with | 0 => have ha : Q(Nat.mod $ea 4 = 0) := (q(Eq.refl 0) : Expr) have hb : Q(Nat.mod $eb 2 = 1) := (q(Eq.refl 1) : Expr) have ec : Q(ℕ) := mkRawNatLit (a / 4) have hc : Q(Nat.div $ea 4 = $ec) := (q(Eq.refl $ec) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd ec eb ⟨er, q(jacobiSymNat.double_even $ea $eb $ec $er $ha $hb $hc $p)⟩ | _ => have ha : Q(Nat.mod $ea 2 = 0) := (q(Eq.refl 0) : Expr) have ec : Q(ℕ) := mkRawNatLit (a / 2) have hc : Q(Nat.div $ea 2 = $ec) := (q(Eq.refl $ec) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd ec eb match b % 8 with | 1 => have hb : Q(Nat.mod $eb 8 = 1) := (q(Eq.refl 1) : Expr) ⟨er, q(jacobiSymNat.even_odd₁ $ea $eb $ec $er $ha $hb $hc $p)⟩ | 3 => have er' := mkRawIntLit (-er.intLit!) have hb : Q(Nat.mod $eb 8 = 3) := (q(Eq.refl 3) : Expr) show (_ : Q(ℤ)) × Q(jacobiSymNat $ea $eb = -$er) from ⟨er', q(jacobiSymNat.even_odd₃ $ea $eb $ec $er $ha $hb $hc $p)⟩ | 5 => have er' := mkRawIntLit (-er.intLit!) haveI : $er' =Q -$er := ⟨⟩ have hb : Q(Nat.mod $eb 8 = 5) := (q(Eq.refl 5) : Expr) ⟨er', q(jacobiSymNat.even_odd₅ $ea $eb $ec $er $ha $hb $hc $p)⟩ | _ => have hb : Q(Nat.mod $eb 8 = 7) := (q(Eq.refl 7) : Expr) ⟨er, q(jacobiSymNat.even_odd₇ $ea $eb $ec $er $ha $hb $hc $p)⟩ | _ => have eab : Q(ℕ) := mkRawNatLit (b % a) have hab : Q(Nat.mod $eb $ea = $eab) := (q(Eq.refl $eab) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd eab ea match a % 4 with | 1 => have ha : Q(Nat.mod $ea 4 = 1) := (q(Eq.refl 1) : Expr) have hb : Q(Nat.mod $eb 2 = 1) := (q(Eq.refl 1) : Expr) ⟨er, q(jacobiSymNat.qr₁_mod $ea $eb $eab $er $ha $hb $hab $p)⟩ | _ => match b % 4 with | 1 => have ha : Q(Nat.mod $ea 2 = 1) := (q(Eq.refl 1) : Expr) have hb : Q(Nat.mod $eb 4 = 1) := (q(Eq.refl 1) : Expr) ⟨er, q(jacobiSymNat.qr₁'_mod $ea $eb $eab $er $ha $hb $hab $p)⟩ | _ => have er' := mkRawIntLit (-er.intLit!) haveI : $er' =Q -$er := ⟨⟩ have ha : Q(Nat.mod $ea 4 = 3) := (q(Eq.refl 3) : Expr) have hb : Q(Nat.mod $eb 4 = 3) := (q(Eq.refl 3) : Expr) ⟨er', q(jacobiSymNat.qr₃_mod $ea $eb $eab $er $ha $hb $hab $p)⟩ /-- This evaluates `r := jacobiSymNat a b` and produces a proof term for the equality by removing powers of `2` from `b` and then calling `proveJacobiSymOdd`. -/ partial def proveJacobiSymNat (ea eb : Q(ℕ)) : (er : Q(ℤ)) × Q(jacobiSymNat $ea $eb = $er) := match eb.natLit! with | 0 => haveI : $eb =Q 0 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSymNat.zero_right $ea)⟩ | 1 => haveI : $eb =Q 1 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSymNat.one_right $ea)⟩ | b => match b % 2 with | 0 => match ea.natLit! with | 0 => have hb : Q(Nat.beq ($eb / 2) 0 = false) := (q(Eq.refl false) : Expr) show (er : Q(ℤ)) × Q(jacobiSymNat 0 $eb = $er) from ⟨mkRawIntLit 0, q(jacobiSymNat.zero_left $eb $hb)⟩ | 1 => show (er : Q(ℤ)) × Q(jacobiSymNat 1 $eb = $er) from ⟨mkRawIntLit 1, q(jacobiSymNat.one_left $eb)⟩ | a => match a % 2 with | 0 => have hb₀ : Q(Nat.beq ($eb / 2) 0 = false) := (q(Eq.refl false) : Expr) have ha : Q(Nat.mod $ea 2 = 0) := (q(Eq.refl 0) : Expr) have hb₁ : Q(Nat.mod $eb 2 = 0) := (q(Eq.refl 0) : Expr) ⟨mkRawIntLit 0, q(jacobiSymNat.even_even $ea $eb $hb₀ $ha $hb₁)⟩ | _ => have ha : Q(Nat.mod $ea 2 = 1) := (q(Eq.refl 1) : Expr) have hb : Q(Nat.mod $eb 2 = 0) := (q(Eq.refl 0) : Expr) have ec : Q(ℕ) := mkRawNatLit (b / 2) have hc : Q(Nat.div $eb 2 = $ec) := (q(Eq.refl $ec) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd ea ec ⟨er, q(jacobiSymNat.odd_even $ea $eb $ec $er $ha $hb $hc $p)⟩ | _ => have a := ea.natLit! if b ≤ a then have eab : Q(ℕ) := mkRawNatLit (a % b) have hab : Q(Nat.mod $ea $eb = $eab) := (q(Eq.refl $eab) : Expr) have ⟨er, p⟩ := proveJacobiSymOdd eab eb ⟨er, q(jacobiSymNat.mod_left $ea $eb $eab $er $hab $p)⟩ else proveJacobiSymOdd ea eb /-- This evaluates `r := jacobiSym a b` and produces a proof term for the equality. This is done by reducing to `r := jacobiSymNat (a % b) b`. -/ partial def proveJacobiSym (ea : Q(ℤ)) (eb : Q(ℕ)) : (er : Q(ℤ)) × Q(jacobiSym $ea $eb = $er) := match eb.natLit! with | 0 => haveI : $eb =Q 0 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSym.zero_right $ea)⟩ | 1 => haveI : $eb =Q 1 := ⟨⟩ ⟨mkRawIntLit 1, q(jacobiSym.one_right $ea)⟩ | b => have eb' := mkRawIntLit b have hb' : Q(($eb : ℤ) = $eb') := (q(Eq.refl $eb') : Expr) have ab := ea.intLit! % b have eab := mkRawIntLit ab have hab : Q(Int.emod $ea $eb' = $eab) := (q(Eq.refl $eab) : Expr) have eab' : Q(ℕ) := mkRawNatLit ab.toNat have hab' : Q(($eab' : ℤ) = $eab) := (q(Eq.refl $eab) : Expr) have ⟨er, p⟩ := proveJacobiSymNat eab' eb ⟨er, q(JacobiSym.mod_left $ea $eb $eab' $eab $er $eb' $hb' $hab $hab' $p)⟩ end Mathlib.Meta.NormNum end Evaluation section Tactic /-! ### The `norm_num` plug-in -/ namespace Tactic namespace NormNum open Lean Elab Tactic Qq Mathlib.Meta.NormNum /-- This is the `norm_num` plug-in that evaluates Jacobi symbols. -/ @[norm_num jacobiSym _ _] def evalJacobiSym : NormNumExt where eval {u α} e := do let .app (.app _ (a : Q(ℤ))) (b : Q(ℕ)) ← Meta.whnfR e | failure let ⟨ea, pa⟩ ← deriveInt a _ let ⟨eb, pb⟩ ← deriveNat b _ haveI' : u =QL 0 := ⟨⟩ haveI' : $α =Q ℤ := ⟨⟩ have ⟨er, pr⟩ := proveJacobiSym ea eb haveI' : $e =Q jacobiSym $a $b := ⟨⟩ return .isInt _ er er.intLit! q(isInt_jacobiSym $pa $pb $pr) /-- This is the `norm_num` plug-in that evaluates Jacobi symbols on natural numbers. -/ @[norm_num jacobiSymNat _ _] def evalJacobiSymNat : NormNumExt where eval {u α} e := do let .app (.app _ (a : Q(ℕ))) (b : Q(ℕ)) ← Meta.whnfR e | failure let ⟨ea, pa⟩ ← deriveNat a _ let ⟨eb, pb⟩ ← deriveNat b _ haveI' : u =QL 0 := ⟨⟩ haveI' : $α =Q ℤ := ⟨⟩ have ⟨er, pr⟩ := proveJacobiSymNat ea eb haveI' : $e =Q jacobiSymNat $a $b := ⟨⟩ return .isInt _ er er.intLit! q(isInt_jacobiSymNat $pa $pb $pr) /-- This is the `norm_num` plug-in that evaluates Legendre symbols. -/ @[norm_num legendreSym _ _] def evalLegendreSym : NormNumExt where eval {u α} e := do let .app (.app (.app _ (p : Q(ℕ))) (fp : Q(Fact (Nat.Prime $p)))) (a : Q(ℤ)) ← Meta.whnfR e | failure let ⟨ea, pa⟩ ← deriveInt a _ let ⟨ep, pp⟩ ← deriveNat p _ haveI' : u =QL 0 := ⟨⟩ haveI' : $α =Q ℤ := ⟨⟩ have ⟨er, pr⟩ := proveJacobiSym ea ep haveI' : $e =Q legendreSym $p $a := ⟨⟩ return .isInt _ er er.intLit! q(LegendreSym.to_jacobiSym $p $fp $a $er (isInt_jacobiSym $pa $pp $pr)) end NormNum end Tactic end Tactic
MultipliableUniformlyOn.lean
/- Copyright (c) 2025 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import Mathlib.Analysis.NormedSpace.FunctionSeries import Mathlib.Analysis.SpecialFunctions.Log.Summable import Mathlib.Topology.Algebra.InfiniteSum.UniformOn import Mathlib.Topology.Algebra.IsUniformGroup.Order /-! # Uniform convergence of products of functions We gather some results about the uniform convergence of infinite products, in particular those of the form `∏' i, (1 + f i x)` for a sequence `f` of complex valued functions. -/ open Filter Function Complex Finset Topology variable {α ι : Type*} {𝔖 : Set (Set α)} {K : Set α} {u : ι → ℝ} section Complex variable {f : ι → α → ℂ} lemma TendstoUniformlyOn.comp_cexp {p : Filter ι} {g : α → ℂ} (hf : TendstoUniformlyOn f g p K) (hg : BddAbove <| (fun x ↦ (g x).re) '' K) : TendstoUniformlyOn (cexp ∘ f ·) (cexp ∘ g) p K := by obtain ⟨v, hv⟩ : ∃ v, ∀ x ∈ K, (g x).re ≤ v := hg.imp <| by simp [mem_upperBounds] have : ∀ᶠ i in p, ∀ x ∈ K, (f i x).re ≤ v + 1 := hf.re.eventually_forall_le (lt_add_one v) hv refine (UniformContinuousOn.cexp _).comp_tendstoUniformlyOn_eventually (by simpa) ?_ hf exact fun x hx ↦ (hv x hx).trans (lt_add_one v).le lemma Summable.hasSumUniformlyOn_log_one_add (hu : Summable u) (h : ∀ᶠ i in cofinite, ∀ x ∈ K, ‖f i x‖ ≤ u i) : HasSumUniformlyOn (fun i x ↦ log (1 + f i x)) (fun x ↦ ∑' i, log (1 + f i x)) {K} := by simp only [hasSumUniformlyOn_iff_tendstoUniformlyOn, Set.mem_singleton_iff, forall_eq] apply tendstoUniformlyOn_tsum_of_cofinite_eventually <| hu.mul_left (3 / 2) filter_upwards [h, hu.tendsto_cofinite_zero.eventually_le_const one_half_pos] with i hi hi' x hx using (norm_log_one_add_half_le_self <| (hi x hx).trans hi').trans (by simpa using hi x hx) lemma Summable.tendstoUniformlyOn_tsum_nat_log_one_add {f : ℕ → α → ℂ} {u : ℕ → ℝ} (hu : Summable u) (h : ∀ᶠ n in atTop, ∀ x ∈ K, ‖f n x‖ ≤ u n) : TendstoUniformlyOn (fun n x ↦ ∑ m ∈ Finset.range n, log (1 + f m x)) (fun x ↦ ∑' n, log (1 + f n x)) atTop K := by rw [← Nat.cofinite_eq_atTop] at h exact (hu.hasSumUniformlyOn_log_one_add h).tendstoUniformlyOn_finsetRange rfl /-- If `x ↦ ∑' i, log (f i x)` is uniformly convergent on `𝔖`, its sum has bounded-above real part on each set in `𝔖`, and the functions `f i x` have no zeroes, then `∏' i, f i x` is uniformly convergent on `𝔖`. Note that the non-vanishing assumption is really needed here: if this assumption is dropped then one obtains a counterexample if `ι = α = ℕ` and `f i x` is `0` if `i = x` and `1` otherwise. -/ lemma hasProdUniformlyOn_of_clog (hf : SummableUniformlyOn (fun i x ↦ log (f i x)) 𝔖) (hfn : ∀ K ∈ 𝔖, ∀ x ∈ K, ∀ i, f i x ≠ 0) (hg : ∀ K ∈ 𝔖, BddAbove <| (fun x ↦ (∑' i, log (f i x)).re) '' K) : HasProdUniformlyOn f (fun x ↦ ∏' i, f i x) 𝔖 := by simp only [hasProdUniformlyOn_iff_tendstoUniformlyOn] obtain ⟨r, hr⟩ := hf.exists intro K hK suffices H : TendstoUniformlyOn (fun s x ↦ ∏ i ∈ s, f i x) (cexp ∘ r) atTop K by refine H.congr_right ((hr.tsum_eqOn hK).comp_left.symm.trans ?_) exact fun x hx ↦ (cexp_tsum_eq_tprod (hfn K hK x hx) (hf.summable hK hx)) have h1 := hr.tsum_eqOn hK simp only [hasSumUniformlyOn_iff_tendstoUniformlyOn] at hr refine ((hr K hK).comp_cexp ?_).congr ?_ · simp +contextual [← h1 _] exact hg K hK · filter_upwards with s i hi using by simp [exp_sum, fun y ↦ exp_log (hfn K hK i hi y)] lemma multipliableUniformlyOn_of_clog (hf : SummableUniformlyOn (fun i x ↦ log (f i x)) 𝔖) (hfn : ∀ K ∈ 𝔖, ∀ x ∈ K, ∀ i, f i x ≠ 0) (hg : ∀ K ∈ 𝔖, BddAbove <| (fun x ↦ (∑' i, log (f i x)).re) '' K) : MultipliableUniformlyOn f 𝔖 := ⟨_, hasProdUniformlyOn_of_clog hf hfn hg⟩ end Complex namespace Summable variable {R : Type*} [NormedCommRing R] [NormOneClass R] [CompleteSpace R] [TopologicalSpace α] {f : ι → α → R} /-- If a sequence of continuous functions `f i x` on an open compact `K` have norms eventually bounded by a summable function, then `∏' i, (1 + f i x)` is uniformly convergent on `K`. -/ lemma hasProdUniformlyOn_one_add (hK : IsCompact K) (hu : Summable u) (h : ∀ᶠ i in cofinite, ∀ x ∈ K, ‖f i x‖ ≤ u i) (hcts : ∀ i, ContinuousOn (f i) K) : HasProdUniformlyOn (fun i x ↦ 1 + f i x) (fun x ↦ ∏' i, (1 + f i x)) {K} := by simp only [hasProdUniformlyOn_iff_tendstoUniformlyOn, Set.mem_singleton_iff, tendstoUniformlyOn_iff_tendstoUniformly_comp_coe, forall_eq] by_cases hKe : K = ∅ · simp [TendstoUniformly, hKe] · haveI hCK : CompactSpace K := isCompact_iff_compactSpace.mp hK haveI hne : Nonempty K := by rwa [Set.nonempty_coe_sort, Set.nonempty_iff_ne_empty] let f' i : C(K, R) := ⟨_, continuousOn_iff_continuous_restrict.mp (hcts i)⟩ have hf'_bd : ∀ᶠ i in cofinite, ‖f' i‖ ≤ u i := by simp only [ContinuousMap.norm_le_of_nonempty] filter_upwards [h] with i hi using fun x ↦ hi x x.2 have hM : Multipliable fun i ↦ 1 + f' i := multipliable_one_add_of_summable (hu.of_norm_bounded_eventually (by simpa using hf'_bd)) convert ContinuousMap.tendsto_iff_tendstoUniformly.mp hM.hasProd · simp [f'] · exact funext fun k ↦ ContinuousMap.tprod_apply hM k lemma multipliableUniformlyOn_one_add (hK : IsCompact K) (hu : Summable u) (h : ∀ᶠ i in cofinite, ∀ x ∈ K, ‖f i x‖ ≤ u i) (hcts : ∀ i, ContinuousOn (f i) K) : MultipliableUniformlyOn (fun i x ↦ 1 + f i x) {K} := ⟨_, hasProdUniformlyOn_one_add hK hu h hcts⟩ /-- This is a version of `hasProdUniformlyOn_one_add` for sequences indexed by `ℕ`. -/ lemma hasProdUniformlyOn_nat_one_add {f : ℕ → α → R} (hK : IsCompact K) {u : ℕ → ℝ} (hu : Summable u) (h : ∀ᶠ n in atTop, ∀ x ∈ K, ‖f n x‖ ≤ u n) (hcts : ∀ n, ContinuousOn (f n) K) : HasProdUniformlyOn (fun n x ↦ 1 + f n x) (fun x ↦ ∏' i, (1 + f i x)) {K} := hasProdUniformlyOn_one_add hK hu (Nat.cofinite_eq_atTop ▸ h) hcts lemma multipliableUniformlyOn_nat_one_add {f : ℕ → α → R} (hK : IsCompact K) {u : ℕ → ℝ} (hu : Summable u) (h : ∀ᶠ n in atTop, ∀ x ∈ K, ‖f n x‖ ≤ u n) (hcts : ∀ n, ContinuousOn (f n) K) : MultipliableUniformlyOn (fun n x ↦ 1 + f n x) {K} := ⟨_, hasProdUniformlyOn_nat_one_add hK hu h hcts⟩ section LocallyCompactSpace variable [LocallyCompactSpace α] /-- If a sequence of continuous functions `f i x` on an open subset `K` have norms eventually bounded by a summable function, then `∏' i, (1 + f i x)` is locally uniformly convergent on `K`. -/ lemma hasProdLocallyUniformlyOn_one_add (hK : IsOpen K) (hu : Summable u) (h : ∀ᶠ i in cofinite, ∀ x ∈ K, ‖f i x‖ ≤ u i) (hcts : ∀ i, ContinuousOn (f i) K) : HasProdLocallyUniformlyOn (fun i x ↦ 1 + f i x) (fun x ↦ ∏' i, (1 + f i x)) K := by apply hasProdLocallyUniformlyOn_of_forall_compact hK refine fun S hS hC ↦ hasProdUniformlyOn_one_add hC hu ?_ fun i ↦ (hcts i).mono hS filter_upwards [h] with i hi a ha using hi a (hS ha) lemma multipliableLocallyUniformlyOn_one_add (hK : IsOpen K) (hu : Summable u) (h : ∀ᶠ i in cofinite, ∀ x ∈ K, ‖f i x‖ ≤ u i) (hcts : ∀ i, ContinuousOn (f i) K) : MultipliableLocallyUniformlyOn (fun i x ↦ 1 + f i x) K := ⟨_, hasProdLocallyUniformlyOn_one_add hK hu h hcts⟩ /-- This is a version of `hasProdLocallyUniformlyOn_one_add` for sequences indexed by `ℕ`. -/ lemma hasProdLocallyUniformlyOn_nat_one_add {f : ℕ → α → R} (hK : IsOpen K) {u : ℕ → ℝ} (hu : Summable u) (h : ∀ᶠ n in atTop, ∀ x ∈ K, ‖f n x‖ ≤ u n) (hcts : ∀ n, ContinuousOn (f n) K) : HasProdLocallyUniformlyOn (fun n x ↦ 1 + f n x) (fun x ↦ ∏' i, (1 + f i x)) K := hasProdLocallyUniformlyOn_one_add hK hu (Nat.cofinite_eq_atTop ▸ h) hcts lemma multipliableLocallyUniformlyOn_nat_one_add {f : ℕ → α → R} (hK : IsOpen K) {u : ℕ → ℝ} (hu : Summable u) (h : ∀ᶠ n in atTop, ∀ x ∈ K, ‖f n x‖ ≤ u n) (hcts : ∀ n, ContinuousOn (f n) K) : MultipliableLocallyUniformlyOn (fun n x ↦ 1 + f n x) K := ⟨_, hasProdLocallyUniformlyOn_nat_one_add hK hu h hcts⟩ end LocallyCompactSpace end Summable
LocallyFinsupp.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.Algebra.Group.Subgroup.Defs import Mathlib.Algebra.Group.Support import Mathlib.Algebra.Order.Pi import Mathlib.Topology.Separation.Hausdorff import Mathlib.Topology.DiscreteSubset /-! # Type of functions with locally finite support This file defines functions with locally finite support, provides supporting API. For suitable targets, it establishes functions with locally finite support as an instance of a lattice ordered commutative group. Throughout the present file, `X` denotes a topologically space and `U` a subset of `X`. -/ open Filter Function Set Topology variable {X : Type*} [TopologicalSpace X] {U : Set X} {Y : Type*} /-! ## Definition, coercion to functions and basic extensionality lemmas A function with locally finite support within `U` is a function `X → Y` whose support is locally finite within `U` and entirely contained in `U`. For T1-spaces, the theorem `supportDiscreteWithin_iff_locallyFiniteWithin` shows that the first condition is equivalent to the condition that the support `f` is discrete within `U`. -/ variable (U Y) in /-- A function with locally finite support within `U` is a triple as specified below. -/ structure Function.locallyFinsuppWithin [Zero Y] where /-- A function `X → Y` -/ toFun : X → Y /-- A proof that the support of `toFun` is contained in `U` -/ supportWithinDomain' : toFun.support ⊆ U /-- A proof the the support is locally finite within `U` -/ supportLocallyFiniteWithinDomain' : ∀ z ∈ U, ∃ t ∈ 𝓝 z, Set.Finite (t ∩ toFun.support) variable (X Y) in /-- A function with locally finite support is a function with locally finite support within `⊤ : Set X`. -/ def Function.locallyFinsupp [Zero Y] := locallyFinsuppWithin (⊤ : Set X) Y /-- For T1 spaces, the condition `supportLocallyFiniteWithinDomain'` is equivalent to saying that the support is codiscrete within `U`. -/ theorem supportDiscreteWithin_iff_locallyFiniteWithin [T1Space X] [Zero Y] {f : X → Y} (h : f.support ⊆ U) : f =ᶠ[codiscreteWithin U] 0 ↔ ∀ z ∈ U, ∃ t ∈ 𝓝 z, Set.Finite (t ∩ f.support) := by have : f.support = (U \ {x | f x = (0 : X → Y) x}) := by ext x simp only [mem_support, ne_eq, Pi.zero_apply, mem_diff, mem_setOf_eq, iff_and_self] exact (h ·) rw [EventuallyEq, Filter.Eventually, codiscreteWithin_iff_locallyFiniteComplementWithin, this] namespace Function.locallyFinsuppWithin /-- Functions with locally finite support within `U` are `FunLike`: the coercion to functions is injective. -/ instance [Zero Y] : FunLike (locallyFinsuppWithin U Y) X Y where coe D := D.toFun coe_injective' := fun ⟨_, _, _⟩ ⟨_, _, _⟩ ↦ by simp /-- This allows writing `D.support` instead of `Function.support D` -/ abbrev support [Zero Y] (D : locallyFinsuppWithin U Y) := Function.support D lemma supportWithinDomain [Zero Y] (D : locallyFinsuppWithin U Y) : D.support ⊆ U := D.supportWithinDomain' lemma supportLocallyFiniteWithinDomain [Zero Y] (D : locallyFinsuppWithin U Y) : ∀ z ∈ U, ∃ t ∈ 𝓝 z, Set.Finite (t ∩ D.support) := D.supportLocallyFiniteWithinDomain' @[ext] lemma ext [Zero Y] {D₁ D₂ : locallyFinsuppWithin U Y} (h : ∀ a, D₁ a = D₂ a) : D₁ = D₂ := DFunLike.ext _ _ h lemma coe_injective [Zero Y] : Injective (· : locallyFinsuppWithin U Y → X → Y) := DFunLike.coe_injective /-! ## Elementary properties of the support -/ /-- Simplifier lemma: Functions with locally finite support within `U` evaluate to zero outside of `U`. -/ @[simp] lemma apply_eq_zero_of_notMem [Zero Y] {z : X} (D : locallyFinsuppWithin U Y) (hz : z ∉ U) : D z = 0 := notMem_support.mp fun a ↦ hz (D.supportWithinDomain a) @[deprecated (since := "2025-05-23")] alias apply_eq_zero_of_not_mem := apply_eq_zero_of_notMem /-- On a T1 space, the support of a function with locally finite support within `U` is discrete within `U`. -/ theorem eq_zero_codiscreteWithin [Zero Y] [T1Space X] (D : locallyFinsuppWithin U Y) : D =ᶠ[Filter.codiscreteWithin U] 0 := by apply codiscreteWithin_iff_locallyFiniteComplementWithin.2 have : D.support = (U \ {x | D x = (0 : X → Y) x}) := by ext x simp only [mem_support, ne_eq, Pi.zero_apply, Set.mem_diff, Set.mem_setOf_eq, iff_and_self] exact (support_subset_iff.1 D.supportWithinDomain) x rw [← this] exact D.supportLocallyFiniteWithinDomain /-- On a T1 space, the support of a functions with locally finite support within `U` is discrete. -/ theorem discreteSupport [Zero Y] [T1Space X] (D : locallyFinsuppWithin U Y) : DiscreteTopology D.support := by have : D.support = {x | D x = 0}ᶜ ∩ U := by ext x constructor · exact fun hx ↦ ⟨by tauto, D.supportWithinDomain hx⟩ · intro hx rw [mem_inter_iff, mem_compl_iff, mem_setOf_eq] at hx tauto rw [this] apply discreteTopology_of_codiscreteWithin apply (supportDiscreteWithin_iff_locallyFiniteWithin D.supportWithinDomain).2 exact D.supportLocallyFiniteWithinDomain /-- If `X` is T1 and if `U` is closed, then the support of support of a function with locally finite support within `U` is also closed. -/ theorem closedSupport [T1Space X] [Zero Y] (D : locallyFinsuppWithin U Y) (hU : IsClosed U) : IsClosed D.support := by convert isClosed_sdiff_of_codiscreteWithin ((supportDiscreteWithin_iff_locallyFiniteWithin D.supportWithinDomain).2 D.supportLocallyFiniteWithinDomain) hU ext x constructor <;> intro hx · simp_all [D.supportWithinDomain hx] · simp_all /-- If `X` is T2 and if `U` is compact, then the support of a function with locally finite support within `U` is finite. -/ theorem finiteSupport [T2Space X] [Zero Y] (D : locallyFinsuppWithin U Y) (hU : IsCompact U) : Set.Finite D.support := (hU.of_isClosed_subset (D.closedSupport hU.isClosed) D.supportWithinDomain).finite D.discreteSupport /-! ## Lattice ordered group structure If `X` is a suitable instance, this section equips functions with locally finite support within `U` with the standard structure of a lattice ordered group, where addition, comparison, min and max are defined pointwise. -/ variable (U) in /-- Functions with locally finite support within `U` form an additive subgroup of functions X → Y. -/ protected def addSubgroup [AddCommGroup Y] : AddSubgroup (X → Y) where carrier := {f | f.support ⊆ U ∧ ∀ z ∈ U, ∃ t ∈ 𝓝 z, Set.Finite (t ∩ f.support)} zero_mem' := by simp only [support_subset_iff, ne_eq, mem_setOf_eq, Pi.zero_apply, not_true_eq_false, IsEmpty.forall_iff, implies_true, support_zero, inter_empty, finite_empty, and_true, true_and] exact fun _ _ ↦ ⟨⊤, univ_mem⟩ add_mem' {f g} hf hg := by constructor · intro x hx contrapose! hx simp [notMem_support.1 fun a ↦ hx (hf.1 a), notMem_support.1 fun a ↦ hx (hg.1 a)] · intro z hz obtain ⟨t₁, ht₁⟩ := hf.2 z hz obtain ⟨t₂, ht₂⟩ := hg.2 z hz use t₁ ∩ t₂, inter_mem ht₁.1 ht₂.1 apply Set.Finite.subset (s := (t₁ ∩ f.support) ∪ (t₂ ∩ g.support)) (ht₁.2.union ht₂.2) intro a ha simp_all only [support_subset_iff, ne_eq, mem_setOf_eq, mem_inter_iff, mem_support, Pi.add_apply, mem_union, true_and] by_contra hCon push_neg at hCon simp_all neg_mem' {f} hf := by simp_all protected lemma memAddSubgroup [AddCommGroup Y] (D : locallyFinsuppWithin U Y) : (D : X → Y) ∈ locallyFinsuppWithin.addSubgroup U := ⟨D.supportWithinDomain, D.supportLocallyFiniteWithinDomain⟩ /-- Assign a function with locally finite support within `U` to a function in the subgroup. -/ @[simps] def mk_of_mem [AddCommGroup Y] (f : X → Y) (hf : f ∈ locallyFinsuppWithin.addSubgroup U) : locallyFinsuppWithin U Y := ⟨f, hf.1, hf.2⟩ instance [AddCommGroup Y] : Zero (locallyFinsuppWithin U Y) where zero := mk_of_mem 0 <| zero_mem _ instance [AddCommGroup Y] : Add (locallyFinsuppWithin U Y) where add D₁ D₂ := mk_of_mem (D₁ + D₂) <| add_mem D₁.memAddSubgroup D₂.memAddSubgroup instance [AddCommGroup Y] : Neg (locallyFinsuppWithin U Y) where neg D := mk_of_mem (-D) <| neg_mem D.memAddSubgroup instance [AddCommGroup Y] : Sub (locallyFinsuppWithin U Y) where sub D₁ D₂ := mk_of_mem (D₁ - D₂) <| sub_mem D₁.memAddSubgroup D₂.memAddSubgroup instance [AddCommGroup Y] : SMul ℕ (locallyFinsuppWithin U Y) where smul n D := mk_of_mem (n • D) <| nsmul_mem D.memAddSubgroup n instance [AddCommGroup Y] : SMul ℤ (locallyFinsuppWithin U Y) where smul n D := mk_of_mem (n • D) <| zsmul_mem D.memAddSubgroup n @[simp] lemma coe_zero [AddCommGroup Y] : ((0 : locallyFinsuppWithin U Y) : X → Y) = 0 := rfl @[simp] lemma coe_add [AddCommGroup Y] (D₁ D₂ : locallyFinsuppWithin U Y) : (↑(D₁ + D₂) : X → Y) = D₁ + D₂ := rfl @[simp] lemma coe_neg [AddCommGroup Y] (D : locallyFinsuppWithin U Y) : (↑(-D) : X → Y) = -(D : X → Y) := rfl @[simp] lemma coe_sub [AddCommGroup Y] (D₁ D₂ : locallyFinsuppWithin U Y) : (↑(D₁ - D₂) : X → Y) = D₁ - D₂ := rfl @[simp] lemma coe_nsmul [AddCommGroup Y] (D : locallyFinsuppWithin U Y) (n : ℕ) : (↑(n • D) : X → Y) = n • (D : X → Y) := rfl @[simp] lemma coe_zsmul [AddCommGroup Y] (D : locallyFinsuppWithin U Y) (n : ℤ) : (↑(n • D) : X → Y) = n • (D : X → Y) := rfl instance [AddCommGroup Y] : AddCommGroup (locallyFinsuppWithin U Y) := Injective.addCommGroup (M₁ := locallyFinsuppWithin U Y) (M₂ := X → Y) _ coe_injective coe_zero coe_add coe_neg coe_sub coe_nsmul coe_zsmul instance [LE Y] [Zero Y] : LE (locallyFinsuppWithin U Y) where le := fun D₁ D₂ ↦ (D₁ : X → Y) ≤ D₂ lemma le_def [LE Y] [Zero Y] {D₁ D₂ : locallyFinsuppWithin U Y} : D₁ ≤ D₂ ↔ (D₁ : X → Y) ≤ (D₂ : X → Y) := ⟨(·),(·)⟩ instance [Preorder Y] [Zero Y] : LT (locallyFinsuppWithin U Y) where lt := fun D₁ D₂ ↦ (D₁ : X → Y) < D₂ lemma lt_def [Preorder Y] [Zero Y] {D₁ D₂ : locallyFinsuppWithin U Y} : D₁ < D₂ ↔ (D₁ : X → Y) < (D₂ : X → Y) := ⟨(·),(·)⟩ instance [SemilatticeSup Y] [Zero Y] : Max (locallyFinsuppWithin U Y) where max D₁ D₂ := { toFun z := max (D₁ z) (D₂ z) supportWithinDomain' := by intro x contrapose intro hx simp [notMem_support.1 fun a ↦ hx (D₁.supportWithinDomain a), notMem_support.1 fun a ↦ hx (D₂.supportWithinDomain a)] supportLocallyFiniteWithinDomain' := by intro z hz obtain ⟨t₁, ht₁⟩ := D₁.supportLocallyFiniteWithinDomain z hz obtain ⟨t₂, ht₂⟩ := D₂.supportLocallyFiniteWithinDomain z hz use t₁ ∩ t₂, inter_mem ht₁.1 ht₂.1 apply Set.Finite.subset (s := (t₁ ∩ D₁.support) ∪ (t₂ ∩ D₂.support)) (ht₁.2.union ht₂.2) intro a ha simp_all only [mem_inter_iff, mem_support, ne_eq, mem_union, true_and] by_contra hCon push_neg at hCon simp_all } @[simp] lemma max_apply [SemilatticeSup Y] [Zero Y] {D₁ D₂ : locallyFinsuppWithin U Y} {x : X} : max D₁ D₂ x = max (D₁ x) (D₂ x) := rfl instance [SemilatticeInf Y] [Zero Y] : Min (locallyFinsuppWithin U Y) where min D₁ D₂ := { toFun z := min (D₁ z) (D₂ z) supportWithinDomain' := by intro x contrapose intro hx simp [notMem_support.1 fun a ↦ hx (D₁.supportWithinDomain a), notMem_support.1 fun a ↦ hx (D₂.supportWithinDomain a)] supportLocallyFiniteWithinDomain' := by intro z hz obtain ⟨t₁, ht₁⟩ := D₁.supportLocallyFiniteWithinDomain z hz obtain ⟨t₂, ht₂⟩ := D₂.supportLocallyFiniteWithinDomain z hz use t₁ ∩ t₂, inter_mem ht₁.1 ht₂.1 apply Set.Finite.subset (s := (t₁ ∩ D₁.support) ∪ (t₂ ∩ D₂.support)) (ht₁.2.union ht₂.2) intro a ha simp_all only [mem_inter_iff, mem_support, ne_eq, mem_union, true_and] by_contra hCon push_neg at hCon simp_all } @[simp] lemma min_apply [SemilatticeInf Y] [Zero Y] {D₁ D₂ : locallyFinsuppWithin U Y} {x : X} : min D₁ D₂ x = min (D₁ x) (D₂ x) := rfl instance [Lattice Y] [Zero Y] : Lattice (locallyFinsuppWithin U Y) where le := (· ≤ ·) lt := (· < ·) le_refl := by simp [le_def] le_trans D₁ D₂ D₃ h₁₂ h₂₃ := fun x ↦ (h₁₂ x).trans (h₂₃ x) le_antisymm D₁ D₂ h₁₂ h₂₁ := by ext x exact le_antisymm (h₁₂ x) (h₂₁ x) sup := max le_sup_left D₁ D₂ := fun x ↦ by simp le_sup_right D₁ D₂ := fun x ↦ by simp sup_le D₁ D₂ D₃ h₁₃ h₂₃ := fun x ↦ by simp [h₁₃ x, h₂₃ x] inf := min inf_le_left D₁ D₂ := fun x ↦ by simp inf_le_right D₁ D₂ := fun x ↦ by simp le_inf D₁ D₂ D₃ h₁₃ h₂₃ := fun x ↦ by simp [h₁₃ x, h₂₃ x] /-- Functions with locally finite support within `U` form an ordered commutative group. -/ instance [AddCommGroup Y] [LinearOrder Y] [IsOrderedAddMonoid Y] : IsOrderedAddMonoid (locallyFinsuppWithin U Y) where add_le_add_left := fun _ _ _ _ ↦ by simpa [le_def] /-! ## Restriction -/ /-- If `V` is a subset of `U`, then functions with locally finite support within `U` restrict to functions with locally finite support within `V`, by setting their values to zero outside of `V`. -/ noncomputable def restrict [Zero Y] {V : Set X} (D : locallyFinsuppWithin U Y) (h : V ⊆ U) : locallyFinsuppWithin V Y where toFun := by classical exact fun z ↦ if hz : z ∈ V then D z else 0 supportWithinDomain' := by intro x hx simp_rw [dite_eq_ite, mem_support, ne_eq, ite_eq_right_iff, Classical.not_imp] at hx exact hx.1 supportLocallyFiniteWithinDomain' := by intro z hz obtain ⟨t, ht⟩ := D.supportLocallyFiniteWithinDomain z (h hz) use t, ht.1 apply Set.Finite.subset (s := t ∩ D.support) ht.2 intro _ _ simp_all open Classical in lemma restrict_apply [Zero Y] {V : Set X} (D : locallyFinsuppWithin U Y) (h : V ⊆ U) (z : X) : (D.restrict h) z = if z ∈ V then D z else 0 := rfl lemma restrict_eqOn [Zero Y] {V : Set X} (D : locallyFinsuppWithin U Y) (h : V ⊆ U) : Set.EqOn (D.restrict h) D V := by intro _ _ simp_all [restrict_apply] lemma restrict_eqOn_compl [Zero Y] {V : Set X} (D : locallyFinsuppWithin U Y) (h : V ⊆ U) : Set.EqOn (D.restrict h) 0 Vᶜ := by intro _ hx simp_all /-- Restriction as a group morphism -/ noncomputable def restrictMonoidHom [AddCommGroup Y] {V : Set X} (h : V ⊆ U) : locallyFinsuppWithin U Y →+ locallyFinsuppWithin V Y where toFun D := D.restrict h map_zero' := by ext x simp [restrict_apply] map_add' D₁ D₂ := by ext x by_cases hx : x ∈ V <;> simp [restrict_apply, hx] @[simp] lemma restrictMonoidHom_apply [AddCommGroup Y] {V : Set X} (D : locallyFinsuppWithin U Y) (h : V ⊆ U) : restrictMonoidHom h D = D.restrict h := by rfl /-- Restriction as a lattice morphism -/ noncomputable def restrictLatticeHom [AddCommGroup Y] [Lattice Y] {V : Set X} (h : V ⊆ U) : LatticeHom (locallyFinsuppWithin U Y) (locallyFinsuppWithin V Y) where toFun D := D.restrict h map_sup' D₁ D₂ := by ext x by_cases hx : x ∈ V <;> simp [locallyFinsuppWithin.restrict_apply, hx] map_inf' D₁ D₂ := by ext x by_cases hx : x ∈ V <;> simp [locallyFinsuppWithin.restrict_apply, hx] @[simp] lemma restrictLatticeHom_apply [AddCommGroup Y] [Lattice Y] {V : Set X} (D : locallyFinsuppWithin U Y) (h : V ⊆ U) : restrictLatticeHom h D = D.restrict h := by rfl end Function.locallyFinsuppWithin
Xgcd.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.Tactic.Ring import Mathlib.Data.PNat.Prime /-! # Euclidean algorithm for ℕ This file sets up a version of the Euclidean algorithm that only works with natural numbers. Given `0 < a, b`, it computes the unique `(w, x, y, z, d)` such that the following identities hold: * `a = (w + x) d` * `b = (y + z) d` * `w * z = x * y + 1` `d` is then the gcd of `a` and `b`, and `a' := a / d = w + x` and `b' := b / d = y + z` are coprime. This story is closely related to the structure of SL₂(ℕ) (as a free monoid on two generators) and the theory of continued fractions. ## Main declarations * `XgcdType`: Helper type in defining the gcd. Encapsulates `(wp, x, y, zp, ap, bp)`. where `wp` `zp`, `ap`, `bp` are the variables getting changed through the algorithm. * `IsSpecial`: States `wp * zp = x * y + 1` * `IsReduced`: States `ap = a ∧ bp = b` ## Notes See `Nat.Xgcd` for a very similar algorithm allowing values in `ℤ`. -/ open Nat namespace PNat /-- A term of `XgcdType` is a system of six naturals. They should be thought of as representing the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] together with the vector [a, b] = [ap + 1, bp + 1]. -/ structure XgcdType where /-- `wp` is a variable which changes through the algorithm. -/ wp : ℕ /-- `x` satisfies `a / d = w + x` at the final step. -/ x : ℕ /-- `y` satisfies `b / d = z + y` at the final step. -/ y : ℕ /-- `zp` is a variable which changes through the algorithm. -/ zp : ℕ /-- `ap` is a variable which changes through the algorithm. -/ ap : ℕ /-- `bp` is a variable which changes through the algorithm. -/ bp : ℕ deriving Inhabited namespace XgcdType variable (u : XgcdType) instance : SizeOf XgcdType := ⟨fun u => u.bp⟩ /-- The `Repr` instance converts terms to strings in a way that reflects the matrix/vector interpretation as above. -/ instance : Repr XgcdType where reprPrec | g, _ => s!"[[[{repr (g.wp + 1)}, {repr g.x}], \ [{repr g.y}, {repr (g.zp + 1)}]], \ [{repr (g.ap + 1)}, {repr (g.bp + 1)}]]" /-- Another `mk` using ℕ and ℕ+ -/ def mk' (w : ℕ+) (x : ℕ) (y : ℕ) (z : ℕ+) (a : ℕ+) (b : ℕ+) : XgcdType := mk w.val.pred x y z.val.pred a.val.pred b.val.pred /-- `w = wp + 1` -/ def w : ℕ+ := succPNat u.wp /-- `z = zp + 1` -/ def z : ℕ+ := succPNat u.zp /-- `a = ap + 1` -/ def a : ℕ+ := succPNat u.ap /-- `b = bp + 1` -/ def b : ℕ+ := succPNat u.bp /-- `r = a % b`: remainder -/ def r : ℕ := (u.ap + 1) % (u.bp + 1) /-- `q = ap / bp`: quotient -/ def q : ℕ := (u.ap + 1) / (u.bp + 1) /-- `qp = q - 1` -/ def qp : ℕ := u.q - 1 /-- The map `v` gives the product of the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] and the vector [a, b] = [ap + 1, bp + 1]. The map `vp` gives [sp, tp] such that v = [sp + 1, tp + 1]. -/ def vp : ℕ × ℕ := ⟨u.wp + u.x + u.ap + u.wp * u.ap + u.x * u.bp, u.y + u.zp + u.bp + u.y * u.ap + u.zp * u.bp⟩ /-- `v = [sp + 1, tp + 1]`, check `vp` -/ def v : ℕ × ℕ := ⟨u.w * u.a + u.x * u.b, u.y * u.a + u.z * u.b⟩ /-- `succ₂ [t.1, t.2] = [t.1.succ, t.2.succ]` -/ def succ₂ (t : ℕ × ℕ) : ℕ × ℕ := ⟨t.1.succ, t.2.succ⟩ theorem v_eq_succ_vp : u.v = succ₂ u.vp := by ext <;> dsimp [v, vp, w, z, a, b, succ₂] <;> ring_nf /-- `IsSpecial` holds if the matrix has determinant one. -/ def IsSpecial : Prop := u.wp + u.zp + u.wp * u.zp = u.x * u.y /-- `IsSpecial'` is an alternative of `IsSpecial`. -/ def IsSpecial' : Prop := u.w * u.z = succPNat (u.x * u.y) theorem isSpecial_iff : u.IsSpecial ↔ u.IsSpecial' := by dsimp [IsSpecial, IsSpecial'] let ⟨wp, x, y, zp, ap, bp⟩ := u constructor <;> intro h <;> simp only [w, succPNat, succ_eq_add_one, z] at * <;> simp only [← coe_inj, mul_coe, mk_coe] at * · simp_all [← h]; ring · simp [Nat.mul_add, Nat.add_mul, ← Nat.add_assoc] at h; rw [← h]; ring /-- `IsReduced` holds if the two entries in the vector are the same. The reduction algorithm will produce a system with this property, whose product vector is the same as for the original system. -/ def IsReduced : Prop := u.ap = u.bp /-- `IsReduced'` is an alternative of `IsReduced`. -/ def IsReduced' : Prop := u.a = u.b theorem isReduced_iff : u.IsReduced ↔ u.IsReduced' := succPNat_inj.symm /-- `flip` flips the placement of variables during the algorithm. -/ def flip : XgcdType where wp := u.zp x := u.y y := u.x zp := u.wp ap := u.bp bp := u.ap @[simp] theorem flip_w : (flip u).w = u.z := rfl @[simp] theorem flip_x : (flip u).x = u.y := rfl @[simp] theorem flip_y : (flip u).y = u.x := rfl @[simp] theorem flip_z : (flip u).z = u.w := rfl @[simp] theorem flip_a : (flip u).a = u.b := rfl @[simp] theorem flip_b : (flip u).b = u.a := rfl theorem flip_isReduced : (flip u).IsReduced ↔ u.IsReduced := by dsimp [IsReduced, flip] constructor <;> intro h <;> exact h.symm theorem flip_isSpecial : (flip u).IsSpecial ↔ u.IsSpecial := by dsimp [IsSpecial, flip] rw [mul_comm u.x, mul_comm u.zp, add_comm u.zp] theorem flip_v : (flip u).v = u.v.swap := by dsimp [v] ext · simp only ring · simp only ring /-- Properties of division with remainder for a / b. -/ theorem rq_eq : u.r + (u.bp + 1) * u.q = u.ap + 1 := Nat.mod_add_div (u.ap + 1) (u.bp + 1) theorem qp_eq (hr : u.r = 0) : u.q = u.qp + 1 := by by_cases hq : u.q = 0 · let h := u.rq_eq rw [hr, hq, mul_zero, add_zero] at h cases h · exact (Nat.succ_pred_eq_of_pos (Nat.pos_of_ne_zero hq)).symm /-- The following function provides the starting point for our algorithm. We will apply an iterative reduction process to it, which will produce a system satisfying IsReduced. The gcd can be read off from this final system. -/ def start (a b : ℕ+) : XgcdType := ⟨0, 0, 0, 0, a - 1, b - 1⟩ theorem start_isSpecial (a b : ℕ+) : (start a b).IsSpecial := by dsimp [start, IsSpecial] theorem start_v (a b : ℕ+) : (start a b).v = ⟨a, b⟩ := by dsimp [start, v, XgcdType.a, XgcdType.b, w, z] rw [one_mul, one_mul, zero_mul, zero_mul] have := a.pos have := b.pos congr <;> omega /-- `finish` happens when the reducing process ends. -/ def finish : XgcdType := XgcdType.mk u.wp ((u.wp + 1) * u.qp + u.x) u.y (u.y * u.qp + u.zp) u.bp u.bp theorem finish_isReduced : u.finish.IsReduced := by dsimp [IsReduced] rfl theorem finish_isSpecial (hs : u.IsSpecial) : u.finish.IsSpecial := by dsimp [IsSpecial, finish] at hs ⊢ rw [add_mul _ _ u.y, add_comm _ (u.x * u.y), ← hs] ring theorem finish_v (hr : u.r = 0) : u.finish.v = u.v := by let ha : u.r + u.b * u.q = u.a := u.rq_eq rw [hr, zero_add] at ha ext · change (u.wp + 1) * u.b + ((u.wp + 1) * u.qp + u.x) * u.b = u.w * u.a + u.x * u.b have : u.wp + 1 = u.w := rfl rw [this, ← ha, u.qp_eq hr] ring · change u.y * u.b + (u.y * u.qp + u.z) * u.b = u.y * u.a + u.z * u.b rw [← ha, u.qp_eq hr] ring /-- This is the main reduction step, which is used when u.r ≠ 0, or equivalently b does not divide a. -/ def step : XgcdType := XgcdType.mk (u.y * u.q + u.zp) u.y ((u.wp + 1) * u.q + u.x) u.wp u.bp (u.r - 1) /-- We will apply the above step recursively. The following result is used to ensure that the process terminates. -/ theorem step_wf (hr : u.r ≠ 0) : SizeOf.sizeOf u.step < SizeOf.sizeOf u := by change u.r - 1 < u.bp have h₀ : u.r - 1 + 1 = u.r := Nat.succ_pred_eq_of_pos (Nat.pos_of_ne_zero hr) have h₁ : u.r < u.bp + 1 := Nat.mod_lt (u.ap + 1) u.bp.succ_pos rw [← h₀] at h₁ exact lt_of_succ_lt_succ h₁ theorem step_isSpecial (hs : u.IsSpecial) : u.step.IsSpecial := by dsimp [IsSpecial, step] at hs ⊢ rw [mul_add, mul_comm u.y u.x, ← hs] ring /-- The reduction step does not change the product vector. -/ theorem step_v (hr : u.r ≠ 0) : u.step.v = u.v.swap := by let ha : u.r + u.b * u.q = u.a := u.rq_eq let hr : u.r - 1 + 1 = u.r := (add_comm _ 1).trans (add_tsub_cancel_of_le (Nat.pos_of_ne_zero hr)) ext · change ((u.y * u.q + u.z) * u.b + u.y * (u.r - 1 + 1) : ℕ) = u.y * u.a + u.z * u.b rw [← ha, hr] ring · change ((u.w * u.q + u.x) * u.b + u.w * (u.r - 1 + 1) : ℕ) = u.w * u.a + u.x * u.b rw [← ha, hr] ring /-- We can now define the full reduction function, which applies step as long as possible, and then applies finish. Note that the "have" statement puts a fact in the local context, and the equation compiler uses this fact to help construct the full definition in terms of well-founded recursion. The same fact needs to be introduced in all the inductive proofs of properties given below. -/ def reduce (u : XgcdType) : XgcdType := dite (u.r = 0) (fun _ => u.finish) fun _h => flip (reduce u.step) decreasing_by apply u.step_wf _h theorem reduce_a {u : XgcdType} (h : u.r = 0) : u.reduce = u.finish := by rw [reduce] exact if_pos h theorem reduce_b {u : XgcdType} (h : u.r ≠ 0) : u.reduce = u.step.reduce.flip := by rw [reduce] exact if_neg h theorem reduce_isReduced : ∀ u : XgcdType, u.reduce.IsReduced | u => dite (u.r = 0) (fun h => by rw [reduce_a h] exact u.finish_isReduced) fun h => by have : SizeOf.sizeOf u.step < SizeOf.sizeOf u := u.step_wf h rw [reduce_b h, flip_isReduced] apply reduce_isReduced theorem reduce_isReduced' (u : XgcdType) : u.reduce.IsReduced' := (isReduced_iff _).mp u.reduce_isReduced theorem reduce_isSpecial : ∀ u : XgcdType, u.IsSpecial → u.reduce.IsSpecial | u => dite (u.r = 0) (fun h hs => by rw [reduce_a h] exact u.finish_isSpecial hs) fun h hs => by have : SizeOf.sizeOf u.step < SizeOf.sizeOf u := u.step_wf h rw [reduce_b h] exact (flip_isSpecial _).mpr (reduce_isSpecial _ (u.step_isSpecial hs)) theorem reduce_isSpecial' (u : XgcdType) (hs : u.IsSpecial) : u.reduce.IsSpecial' := (isSpecial_iff _).mp (u.reduce_isSpecial hs) theorem reduce_v : ∀ u : XgcdType, u.reduce.v = u.v | u => dite (u.r = 0) (fun h => by rw [reduce_a h, finish_v u h]) fun h => by have : SizeOf.sizeOf u.step < SizeOf.sizeOf u := u.step_wf h rw [reduce_b h, flip_v, reduce_v (step u), step_v u h, Prod.swap_swap] end XgcdType section gcd variable (a b : ℕ+) /-- Extended Euclidean algorithm -/ def xgcd : XgcdType := (XgcdType.start a b).reduce /-- `gcdD a b = gcd a b` -/ def gcdD : ℕ+ := (xgcd a b).a /-- Final value of `w` -/ def gcdW : ℕ+ := (xgcd a b).w /-- Final value of `x` -/ def gcdX : ℕ := (xgcd a b).x /-- Final value of `y` -/ def gcdY : ℕ := (xgcd a b).y /-- Final value of `z` -/ def gcdZ : ℕ+ := (xgcd a b).z /-- Final value of `a / d` -/ def gcdA' : ℕ+ := succPNat ((xgcd a b).wp + (xgcd a b).x) /-- Final value of `b / d` -/ def gcdB' : ℕ+ := succPNat ((xgcd a b).y + (xgcd a b).zp) theorem gcdA'_coe : (gcdA' a b : ℕ) = gcdW a b + gcdX a b := by dsimp [gcdA', gcdX, gcdW, XgcdType.w] rw [add_right_comm] theorem gcdB'_coe : (gcdB' a b : ℕ) = gcdY a b + gcdZ a b := by dsimp [gcdB', gcdY, gcdZ, XgcdType.z] rw [add_assoc] theorem gcd_props : let d := gcdD a b let w := gcdW a b let x := gcdX a b let y := gcdY a b let z := gcdZ a b let a' := gcdA' a b let b' := gcdB' a b w * z = succPNat (x * y) ∧ a = a' * d ∧ b = b' * d ∧ z * a' = succPNat (x * b') ∧ w * b' = succPNat (y * a') ∧ (z * a : ℕ) = x * b + d ∧ (w * b : ℕ) = y * a + d := by intros d w x y z a' b' let u := XgcdType.start a b let ur := u.reduce have _ : d = ur.a := rfl have hb : d = ur.b := u.reduce_isReduced' have ha' : (a' : ℕ) = w + x := gcdA'_coe a b have hb' : (b' : ℕ) = y + z := gcdB'_coe a b have hdet : w * z = succPNat (x * y) := u.reduce_isSpecial' rfl constructor · exact hdet have hdet' : (w * z : ℕ) = x * y + 1 := by rw [← mul_coe, hdet, succPNat_coe] have _ : u.v = ⟨a, b⟩ := XgcdType.start_v a b let hv : Prod.mk (w * d + x * ur.b : ℕ) (y * d + z * ur.b : ℕ) = ⟨a, b⟩ := u.reduce_v.trans (XgcdType.start_v a b) rw [← hb, ← add_mul, ← add_mul, ← ha', ← hb'] at hv have ha'' : (a : ℕ) = a' * d := (congr_arg Prod.fst hv).symm have hb'' : (b : ℕ) = b' * d := (congr_arg Prod.snd hv).symm constructor · exact eq ha'' constructor · exact eq hb'' have hza' : (z * a' : ℕ) = x * b' + 1 := by rw [ha', hb', mul_add, mul_add, mul_comm (z : ℕ), hdet'] ring have hwb' : (w * b' : ℕ) = y * a' + 1 := by rw [ha', hb', mul_add, mul_add, hdet'] ring constructor · apply eq rw [succPNat_coe, Nat.succ_eq_add_one, mul_coe, hza'] constructor · apply eq rw [succPNat_coe, Nat.succ_eq_add_one, mul_coe, hwb'] rw [ha'', hb''] repeat rw [← @mul_assoc] rw [hza', hwb'] constructor <;> ring theorem gcd_eq : gcdD a b = gcd a b := by rcases gcd_props a b with ⟨_, h₁, h₂, _, _, h₅, _⟩ apply dvd_antisymm · apply dvd_gcd · exact Dvd.intro (gcdA' a b) (h₁.trans (mul_comm _ _)).symm · exact Dvd.intro (gcdB' a b) (h₂.trans (mul_comm _ _)).symm · have h₇ : (gcd a b : ℕ) ∣ gcdZ a b * a := (Nat.gcd_dvd_left a b).trans (dvd_mul_left _ _) have h₈ : (gcd a b : ℕ) ∣ gcdX a b * b := (Nat.gcd_dvd_right a b).trans (dvd_mul_left _ _) rw [h₅] at h₇ rw [dvd_iff] exact (Nat.dvd_add_iff_right h₈).mpr h₇ theorem gcd_det_eq : gcdW a b * gcdZ a b = succPNat (gcdX a b * gcdY a b) := (gcd_props a b).1 theorem gcd_a_eq : a = gcdA' a b * gcd a b := gcd_eq a b ▸ (gcd_props a b).2.1 theorem gcd_b_eq : b = gcdB' a b * gcd a b := gcd_eq a b ▸ (gcd_props a b).2.2.1 theorem gcd_rel_left' : gcdZ a b * gcdA' a b = succPNat (gcdX a b * gcdB' a b) := (gcd_props a b).2.2.2.1 theorem gcd_rel_right' : gcdW a b * gcdB' a b = succPNat (gcdY a b * gcdA' a b) := (gcd_props a b).2.2.2.2.1 theorem gcd_rel_left : (gcdZ a b * a : ℕ) = gcdX a b * b + gcd a b := gcd_eq a b ▸ (gcd_props a b).2.2.2.2.2.1 theorem gcd_rel_right : (gcdW a b * b : ℕ) = gcdY a b * a + gcd a b := gcd_eq a b ▸ (gcd_props a b).2.2.2.2.2.2 end gcd end PNat
Defs.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl, Yuyang Zhao -/ import Mathlib.Algebra.Group.Units.Basic import Mathlib.Algebra.Order.Monoid.Defs import Mathlib.Algebra.Order.Monoid.Unbundled.ExistsOfLE import Mathlib.Algebra.NeZero import Mathlib.Order.BoundedOrder.Basic /-! # Canonically ordered monoids -/ universe u variable {α : Type u} /-- An ordered additive monoid is `CanonicallyOrderedAdd` if the ordering coincides with the subtractibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other nontrivial `OrderedAddCommGroup`s. -/ class CanonicallyOrderedAdd (α : Type*) [Add α] [LE α] : Prop extends ExistsAddOfLE α where /-- For any `a` and `b`, `a ≤ a + b` -/ protected le_self_add : ∀ a b : α, a ≤ a + b attribute [instance 50] CanonicallyOrderedAdd.toExistsAddOfLE /-- An ordered monoid is `CanonicallyOrderedMul` if the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a * c`. Examples seem rare; it seems more likely that the `OrderDual` of a naturally-occurring lattice satisfies this than the lattice itself (for example, dual of the lattice of ideals of a PID or Dedekind domain satisfy this; collections of all things ≤ 1 seem to be more natural that collections of all things ≥ 1). -/ @[to_additive] class CanonicallyOrderedMul (α : Type*) [Mul α] [LE α] : Prop extends ExistsMulOfLE α where /-- For any `a` and `b`, `a ≤ a * b` -/ protected le_self_mul : ∀ a b : α, a ≤ a * b attribute [instance 50] CanonicallyOrderedMul.toExistsMulOfLE set_option linter.deprecated false in /-- A canonically ordered additive monoid is an ordered commutative additive monoid in which the ordering coincides with the subtractibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other nontrivial `OrderedAddCommGroup`s. -/ @[deprecated "Use `[OrderedAddCommMonoid α] [CanonicallyOrderedAdd α]` instead." (since := "2025-01-13")] structure CanonicallyOrderedAddCommMonoid (α : Type*) extends OrderedAddCommMonoid α, OrderBot α where /-- For `a ≤ b`, there is a `c` so `b = a + c`. -/ protected exists_add_of_le : ∀ {a b : α}, a ≤ b → ∃ c, b = a + c /-- For any `a` and `b`, `a ≤ a + b` -/ protected le_self_add : ∀ a b : α, a ≤ a + b set_option linter.deprecated false in set_option linter.existingAttributeWarning false in /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a * c`. Examples seem rare; it seems more likely that the `OrderDual` of a naturally-occurring lattice satisfies this than the lattice itself (for example, dual of the lattice of ideals of a PID or Dedekind domain satisfy this; collections of all things ≤ 1 seem to be more natural that collections of all things ≥ 1). -/ @[to_additive, deprecated "Use `[OrderedCommMonoid α] [CanonicallyOrderedMul α]` instead." (since := "2025-01-13")] structure CanonicallyOrderedCommMonoid (α : Type*) extends OrderedCommMonoid α, OrderBot α where /-- For `a ≤ b`, there is a `c` so `b = a * c`. -/ protected exists_mul_of_le : ∀ {a b : α}, a ≤ b → ∃ c, b = a * c /-- For any `a` and `b`, `a ≤ a * b` -/ protected le_self_mul : ∀ a b : α, a ≤ a * b section Mul variable [Mul α] section LE variable [LE α] [CanonicallyOrderedMul α] {a b c : α} @[to_additive] theorem le_self_mul : a ≤ a * b := CanonicallyOrderedMul.le_self_mul _ _ @[to_additive (attr := simp)] theorem self_le_mul_right (a b : α) : a ≤ a * b := le_self_mul @[to_additive] theorem le_iff_exists_mul : a ≤ b ↔ ∃ c, b = a * c := ⟨exists_mul_of_le, by rintro ⟨c, rfl⟩ exact le_self_mul⟩ end LE section Preorder variable [Preorder α] [CanonicallyOrderedMul α] {a b c : α} @[to_additive] theorem le_of_mul_le_left : a * b ≤ c → a ≤ c := le_self_mul.trans @[to_additive] theorem le_mul_of_le_left : a ≤ b → a ≤ b * c := le_self_mul.trans' @[to_additive] alias le_mul_right := le_mul_of_le_left end Preorder end Mul section CommMagma variable [CommMagma α] section LE variable [LE α] [CanonicallyOrderedMul α] {a b : α} @[to_additive] theorem le_mul_self : a ≤ b * a := by rw [mul_comm] exact le_self_mul @[to_additive (attr := simp)] theorem self_le_mul_left (a b : α) : a ≤ b * a := le_mul_self end LE section Preorder variable [Preorder α] [CanonicallyOrderedMul α] {a b c : α} @[to_additive] theorem le_of_mul_le_right : a * b ≤ c → b ≤ c := le_mul_self.trans @[to_additive] theorem le_mul_of_le_right : a ≤ c → a ≤ b * c := le_mul_self.trans' @[to_additive] alias le_mul_left := le_mul_of_le_right @[to_additive] theorem le_iff_exists_mul' : a ≤ b ↔ ∃ c, b = c * a := by simp only [mul_comm _ a, le_iff_exists_mul] end Preorder end CommMagma section MulOneClass variable [MulOneClass α] section LE variable [LE α] [CanonicallyOrderedMul α] {a b : α} @[to_additive (attr := simp) zero_le] theorem one_le (a : α) : 1 ≤ a := le_self_mul.trans_eq (one_mul _) @[to_additive] theorem isBot_one : IsBot (1 : α) := one_le end LE section Preorder variable [Preorder α] [CanonicallyOrderedMul α] {a b : α} @[to_additive] -- `(attr := simp)` can not be used here because `a` can not be inferred by `simp`. theorem one_lt_of_gt (h : a < b) : 1 < b := (one_le _).trans_lt h alias LT.lt.pos := pos_of_gt @[to_additive existing] alias LT.lt.one_lt := one_lt_of_gt end Preorder section PartialOrder variable [PartialOrder α] [CanonicallyOrderedMul α] {a b c : α} @[to_additive] theorem bot_eq_one [OrderBot α] : (⊥ : α) = 1 := isBot_one.eq_bot.symm @[to_additive (attr := simp)] theorem le_one_iff_eq_one : a ≤ 1 ↔ a = 1 := (one_le a).ge_iff_eq' @[to_additive] theorem one_lt_iff_ne_one : 1 < a ↔ a ≠ 1 := (one_le a).lt_iff_ne.trans ne_comm @[to_additive] theorem one_lt_of_ne_one (h : a ≠ 1) : 1 < a := one_lt_iff_ne_one.2 h @[to_additive] theorem eq_one_or_one_lt (a : α) : a = 1 ∨ 1 < a := (one_le a).eq_or_lt.imp_left Eq.symm @[to_additive] lemma one_notMem_iff [OrderBot α] {s : Set α} : 1 ∉ s ↔ ∀ x ∈ s, 1 < x := bot_eq_one (α := α) ▸ bot_notMem_iff @[deprecated (since := "2025-05-23")] alias zero_not_mem_iff := zero_notMem_iff @[to_additive existing, deprecated (since := "2025-05-23")] alias one_not_mem_iff := one_notMem_iff alias NE.ne.pos := pos_of_ne_zero @[to_additive existing] alias NE.ne.one_lt := one_lt_of_ne_one @[to_additive] theorem exists_one_lt_mul_of_lt (h : a < b) : ∃ (c : _) (_ : 1 < c), a * c = b := by obtain ⟨c, hc⟩ := le_iff_exists_mul.1 h.le refine ⟨c, one_lt_iff_ne_one.2 ?_, hc.symm⟩ rintro rfl simp [hc] at h @[to_additive] theorem lt_iff_exists_mul [MulLeftStrictMono α] : a < b ↔ ∃ c > 1, b = a * c := by rw [lt_iff_le_and_ne, le_iff_exists_mul, ← exists_and_right] apply exists_congr intro c rw [and_comm, and_congr_left_iff, gt_iff_lt] rintro rfl constructor · rw [one_lt_iff_ne_one] apply mt rintro rfl rw [mul_one] · rw [← (self_le_mul_right a c).lt_iff_ne] apply lt_mul_of_one_lt_right' end PartialOrder end MulOneClass section Semigroup variable [Semigroup α] section LE variable [LE α] [CanonicallyOrderedMul α] -- see Note [lower instance priority] @[to_additive] instance (priority := 10) CanonicallyOrderedMul.toMulLeftMono : MulLeftMono α where elim a b c hbc := by obtain ⟨c, hc, rfl⟩ := exists_mul_of_le hbc rw [le_iff_exists_mul] exact ⟨c, (mul_assoc _ _ _).symm⟩ end LE end Semigroup -- TODO: make it an instance @[to_additive] lemma CanonicallyOrderedMul.toIsOrderedMonoid [CommMonoid α] [PartialOrder α] [CanonicallyOrderedMul α] : IsOrderedMonoid α where mul_le_mul_left _ _ := mul_le_mul_left' section Monoid variable [Monoid α] section PartialOrder variable [PartialOrder α] [CanonicallyOrderedMul α] {a b c : α} @[to_additive] instance CanonicallyOrderedCommMonoid.toUniqueUnits : Unique αˣ where uniq a := Units.ext <| le_one_iff_eq_one.mp (le_of_mul_le_left a.mul_inv.le) end PartialOrder end Monoid section CommMonoid variable [CommMonoid α] section PartialOrder variable [PartialOrder α] [CanonicallyOrderedMul α] {a b c : α} @[to_additive (attr := simp) add_pos_iff] theorem one_lt_mul_iff : 1 < a * b ↔ 1 < a ∨ 1 < b := by simp only [one_lt_iff_ne_one, Ne, mul_eq_one, not_and_or] end PartialOrder end CommMonoid namespace NeZero theorem pos {M} [AddZeroClass M] [PartialOrder M] [CanonicallyOrderedAdd M] (a : M) [NeZero a] : 0 < a := (zero_le a).lt_of_ne <| NeZero.out.symm theorem of_gt {M} [AddZeroClass M] [Preorder M] [CanonicallyOrderedAdd M] {x y : M} (h : x < y) : NeZero y := of_pos <| pos_of_gt h -- 1 < p is still an often-used `Fact`, due to `Nat.Prime` implying it, and it implying `Nontrivial` -- on `ZMod`'s ring structure. We cannot just set this to be any `x < y`, else that becomes a -- metavariable and it will hugely slow down typeclass inference. instance (priority := 10) of_gt' {M : Type*} [AddZeroClass M] [Preorder M] [CanonicallyOrderedAdd M] [One M] {y : M} [Fact (1 < y)] : NeZero y := of_gt <| @Fact.out (1 < y) _ theorem of_ge {M} [AddZeroClass M] [PartialOrder M] [CanonicallyOrderedAdd M] {x y : M} [NeZero x] (h : x ≤ y) : NeZero y := of_pos <| lt_of_lt_of_le (pos x) h end NeZero set_option linter.deprecated false in /-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid whose ordering is a linear order. -/ @[deprecated "Use `[LinearOrderedAddCommMonoid α] [CanonicallyOrderedAdd α]` instead." (since := "2025-01-13")] structure CanonicallyLinearOrderedAddCommMonoid (α : Type*) extends CanonicallyOrderedAddCommMonoid α, LinearOrderedAddCommMonoid α set_option linter.deprecated false in set_option linter.existingAttributeWarning false in /-- A canonically linear-ordered monoid is a canonically ordered monoid whose ordering is a linear order. -/ @[to_additive, deprecated "Use `[LinearOrderedCommMonoid α] [CanonicallyOrderedMul α]` instead." (since := "2025-01-13")] structure CanonicallyLinearOrderedCommMonoid (α : Type*) extends CanonicallyOrderedCommMonoid α, LinearOrderedCommMonoid α attribute [nolint docBlame] CanonicallyLinearOrderedAddCommMonoid.toLinearOrderedAddCommMonoid attribute [nolint docBlame] CanonicallyLinearOrderedCommMonoid.toLinearOrderedCommMonoid section CanonicallyLinearOrderedCommMonoid variable [CommMonoid α] [LinearOrder α] [CanonicallyOrderedMul α] @[to_additive] theorem min_mul_distrib (a b c : α) : min a (b * c) = min a (min a b * min a c) := by rcases le_total a b with hb | hb · simp [hb, le_mul_right] · rcases le_total a c with hc | hc · simp [hc, le_mul_left] · simp [hb, hc] @[to_additive] theorem min_mul_distrib' (a b c : α) : min (a * b) c = min (min a c * min b c) c := by simpa [min_comm _ c] using min_mul_distrib c a b @[to_additive] theorem one_min (a : α) : min 1 a = 1 := min_eq_left (one_le a) @[to_additive] theorem min_one (a : α) : min a 1 = 1 := min_eq_right (one_le a) /-- In a linearly ordered monoid, we are happy for `bot_eq_one` to be a `@[simp]` lemma. -/ @[to_additive (attr := simp) /-- In a linearly ordered monoid, we are happy for `bot_eq_zero` to be a `@[simp]` lemma -/] theorem bot_eq_one' [OrderBot α] : (⊥ : α) = 1 := bot_eq_one end CanonicallyLinearOrderedCommMonoid
AddGroupWithTop.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import Mathlib.Algebra.Order.Monoid.WithTop import Mathlib.Algebra.Group.Hom.Defs import Mathlib.Algebra.CharZero.Defs import Mathlib.Algebra.Order.Monoid.Canonical.Defs /-! # Linearly ordered commutative additive groups and monoids with a top element adjoined This file sets up a special class of linearly ordered commutative additive monoids that show up as the target of so-called “valuations” in algebraic number theory. Usually, in the informal literature, these objects are constructed by taking a linearly ordered commutative additive group Γ and formally adjoining a top element: Γ ∪ {⊤}. The disadvantage is that a type such as `ENNReal` is not of that form, whereas it is a very common target for valuations. The solutions is to use a typeclass, and that is exactly what we do in this file. -/ variable {α : Type*} /-- A linearly ordered commutative monoid with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined. -/ class LinearOrderedAddCommMonoidWithTop (α : Type*) extends AddCommMonoid α, LinearOrder α, IsOrderedAddMonoid α, OrderTop α where /-- In a `LinearOrderedAddCommMonoidWithTop`, the `⊤` element is invariant under addition. -/ protected top_add' : ∀ x : α, ⊤ + x = ⊤ /-- A linearly ordered commutative group with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined. -/ class LinearOrderedAddCommGroupWithTop (α : Type*) extends LinearOrderedAddCommMonoidWithTop α, SubNegMonoid α, Nontrivial α where protected neg_top : -(⊤ : α) = ⊤ protected add_neg_cancel : ∀ a : α, a ≠ ⊤ → a + -a = 0 instance WithTop.linearOrderedAddCommMonoidWithTop [AddCommMonoid α] [LinearOrder α] [IsOrderedAddMonoid α] : LinearOrderedAddCommMonoidWithTop (WithTop α) := { top_add' := WithTop.top_add } section LinearOrderedAddCommMonoidWithTop variable [LinearOrderedAddCommMonoidWithTop α] @[simp] theorem top_add (a : α) : ⊤ + a = ⊤ := LinearOrderedAddCommMonoidWithTop.top_add' a @[simp] theorem add_top (a : α) : a + ⊤ = ⊤ := Trans.trans (add_comm _ _) (top_add _) end LinearOrderedAddCommMonoidWithTop namespace WithTop open Function namespace LinearOrderedAddCommGroup instance instNeg [AddCommGroup α] : Neg (WithTop α) where neg := Option.map fun a : α => -a /-- If `α` has subtraction, we can extend the subtraction to `WithTop α`, by setting `x - ⊤ = ⊤` and `⊤ - x = ⊤`. This definition is only registered as an instance on linearly ordered additive commutative groups, to avoid conflicting with the instance `WithTop.instSub` on types with a bottom element. -/ protected def sub [AddCommGroup α] : WithTop α → WithTop α → WithTop α | _, ⊤ => ⊤ | ⊤, (x : α) => ⊤ | (x : α), (y : α) => (x - y : α) instance instSub [AddCommGroup α] : Sub (WithTop α) where sub := WithTop.LinearOrderedAddCommGroup.sub variable [AddCommGroup α] @[simp, norm_cast] theorem coe_neg (a : α) : ((-a : α) : WithTop α) = -a := rfl @[simp] theorem neg_top : -(⊤ : WithTop α) = ⊤ := rfl @[simp, norm_cast] theorem coe_sub {a b : α} : (↑(a - b) : WithTop α) = ↑a - ↑b := rfl @[simp] theorem top_sub {a : WithTop α} : (⊤ : WithTop α) - a = ⊤ := by cases a <;> rfl @[simp] theorem sub_top {a : WithTop α} : a - ⊤ = ⊤ := by cases a <;> rfl @[simp] lemma sub_eq_top_iff {a b : WithTop α} : a - b = ⊤ ↔ (a = ⊤ ∨ b = ⊤) := by cases a <;> cases b <;> simp [← coe_sub] instance [LinearOrder α] [IsOrderedAddMonoid α] : LinearOrderedAddCommGroupWithTop (WithTop α) where __ := WithTop.linearOrderedAddCommMonoidWithTop __ := Option.nontrivial sub_eq_add_neg a b := by cases a <;> cases b <;> simp [← coe_sub, ← coe_neg, sub_eq_add_neg] neg_top := Option.map_none _ zsmul := zsmulRec add_neg_cancel := by rintro (a | a) ha · exact (ha rfl).elim · exact (WithTop.coe_add ..).symm.trans (WithTop.coe_eq_coe.2 (add_neg_cancel a)) end LinearOrderedAddCommGroup end WithTop namespace LinearOrderedAddCommGroupWithTop variable [LinearOrderedAddCommGroupWithTop α] {a b : α} attribute [simp] LinearOrderedAddCommGroupWithTop.neg_top lemma add_neg_cancel_of_ne_top {α : Type*} [LinearOrderedAddCommGroupWithTop α] {a : α} (h : a ≠ ⊤) : a + -a = 0 := LinearOrderedAddCommGroupWithTop.add_neg_cancel a h @[simp] lemma add_eq_top : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by constructor · intro h by_contra nh rw [not_or] at nh replace h := congrArg (-a + ·) h dsimp only at h rw [add_top, ← add_assoc, add_comm (-a), add_neg_cancel_of_ne_top, zero_add] at h · exact nh.2 h · exact nh.1 · rintro (rfl | rfl) · simp · simp @[simp] lemma top_ne_zero : (⊤ : α) ≠ 0 := by intro nh have ⟨a, b, h⟩ := Nontrivial.exists_pair_ne (α := α) have : a + 0 ≠ b + 0 := by simpa rw [← nh] at this simp at this @[simp] lemma neg_eq_top {a : α} : -a = ⊤ ↔ a = ⊤ where mp h := by by_contra nh replace nh := add_neg_cancel_of_ne_top nh rw [h, add_top] at nh exact top_ne_zero nh mpr h := by simp [h] instance (priority := 100) toSubtractionMonoid : SubtractionMonoid α where neg_neg a := by by_cases h : a = ⊤ · simp [h] · have h2 : ¬ -a = ⊤ := fun nh ↦ h <| neg_eq_top.mp nh replace h2 : a + (-a + - -a) = a + 0 := congrArg (a + ·) (add_neg_cancel_of_ne_top h2) rw [← add_assoc, add_neg_cancel_of_ne_top h] at h2 simp only [zero_add, add_zero] at h2 exact h2 neg_add_rev a b := by by_cases ha : a = ⊤ · simp [ha] by_cases hb : b = ⊤ · simp [hb] apply (_ : Function.Injective (a + b + ·)) · dsimp rw [add_neg_cancel_of_ne_top, ← add_assoc, add_assoc a, add_neg_cancel_of_ne_top hb, add_zero, add_neg_cancel_of_ne_top ha] simp [ha, hb] · apply Function.LeftInverse.injective (g := (-(a + b) + ·)) intro x dsimp only rw [← add_assoc, add_comm (-(a + b)), add_neg_cancel_of_ne_top, zero_add] simp [ha, hb] neg_eq_of_add a b h := by have oh := congrArg (-a + ·) h dsimp only at oh rw [add_zero, ← add_assoc, add_comm (-a), add_neg_cancel_of_ne_top, zero_add] at oh · exact oh.symm intro v simp [v] at h lemma injective_add_left_of_ne_top (b : α) (h : b ≠ ⊤) : Function.Injective (fun x ↦ x + b) := by intro x y h2 replace h2 : x + (b + -b) = y + (b + -b) := by simp [← add_assoc, h2] simpa only [LinearOrderedAddCommGroupWithTop.add_neg_cancel _ h, add_zero] using h2 lemma injective_add_right_of_ne_top (b : α) (h : b ≠ ⊤) : Function.Injective (fun x ↦ b + x) := by simpa [add_comm] using injective_add_left_of_ne_top b h lemma strictMono_add_left_of_ne_top (b : α) (h : b ≠ ⊤) : StrictMono (fun x ↦ x + b) := by apply Monotone.strictMono_of_injective · apply Monotone.add_const monotone_id · apply injective_add_left_of_ne_top _ h lemma strictMono_add_right_of_ne_top (b : α) (h : b ≠ ⊤) : StrictMono (fun x ↦ b + x) := by simpa [add_comm] using strictMono_add_left_of_ne_top b h lemma sub_pos (a b : α) : 0 < a - b ↔ b < a ∨ b = ⊤ where mp h := by refine or_iff_not_imp_right.mpr fun h2 ↦ ?_ replace h := strictMono_add_left_of_ne_top _ h2 h simp only [zero_add] at h rw [sub_eq_add_neg, add_assoc, add_comm (-b), add_neg_cancel_of_ne_top h2, add_zero] at h exact h mpr h := by rcases h with h | h · convert strictMono_add_left_of_ne_top (-b) (by simp [h.ne_top]) h using 1 · simp [add_neg_cancel_of_ne_top h.ne_top] · simp [sub_eq_add_neg] · rw [h] simp only [sub_eq_add_neg, LinearOrderedAddCommGroupWithTop.neg_top, add_top] apply lt_of_le_of_ne le_top exact Ne.symm top_ne_zero end LinearOrderedAddCommGroupWithTop
NormedSpace.lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import Mathlib.Analysis.Calculus.FDeriv.Add import Mathlib.Analysis.Calculus.FDeriv.Const import Mathlib.Analysis.NormedSpace.ConformalLinearMap /-! # Conformal Maps A continuous linear map between real normed spaces `X` and `Y` is `ConformalAt` some point `x` if it is real differentiable at that point and its differential is a conformal linear map. ## Main definitions * `ConformalAt`: the main definition of conformal maps * `Conformal`: maps that are conformal at every point ## Main results * The conformality of the composition of two conformal maps, the identity map and multiplications by nonzero constants * `conformalAt_iff_isConformalMap_fderiv`: an equivalent definition of the conformality of a map In `Analysis.Calculus.Conformal.InnerProduct`: * `conformalAt_iff`: an equivalent definition of the conformality of a map In `Geometry.Euclidean.Angle.Unoriented.Conformal`: * `ConformalAt.preserves_angle`: if a map is conformal at `x`, then its differential preserves all angles at `x` ## Tags conformal ## Warning The definition of conformality in this file does NOT require the maps to be orientation-preserving. Maps such as the complex conjugate are considered to be conformal. -/ noncomputable section variable {X Y Z : Type*} [NormedAddCommGroup X] [NormedAddCommGroup Y] [NormedAddCommGroup Z] [NormedSpace ℝ X] [NormedSpace ℝ Y] [NormedSpace ℝ Z] section LocConformality open LinearIsometry ContinuousLinearMap /-- A map `f` is said to be conformal if it has a conformal differential `f'`. -/ def ConformalAt (f : X → Y) (x : X) := ∃ f' : X →L[ℝ] Y, HasFDerivAt f f' x ∧ IsConformalMap f' theorem conformalAt_id (x : X) : ConformalAt _root_.id x := ⟨id ℝ X, hasFDerivAt_id _, isConformalMap_id⟩ theorem conformalAt_const_smul {c : ℝ} (h : c ≠ 0) (x : X) : ConformalAt (fun x' : X => c • x') x := ⟨c • ContinuousLinearMap.id ℝ X, (hasFDerivAt_id x).const_smul c, isConformalMap_const_smul h⟩ @[nontriviality] theorem Subsingleton.conformalAt [Subsingleton X] (f : X → Y) (x : X) : ConformalAt f x := ⟨0, hasFDerivAt_of_subsingleton _ _, isConformalMap_of_subsingleton _⟩ /-- A function is a conformal map if and only if its differential is a conformal linear map -/ theorem conformalAt_iff_isConformalMap_fderiv {f : X → Y} {x : X} : ConformalAt f x ↔ IsConformalMap (fderiv ℝ f x) := by constructor · rintro ⟨f', hf, hf'⟩ rwa [hf.fderiv] · intro H by_cases h : DifferentiableAt ℝ f x · exact ⟨fderiv ℝ f x, h.hasFDerivAt, H⟩ · nontriviality X exact absurd (fderiv_zero_of_not_differentiableAt h) H.ne_zero namespace ConformalAt theorem differentiableAt {f : X → Y} {x : X} (h : ConformalAt f x) : DifferentiableAt ℝ f x := let ⟨_, h₁, _⟩ := h h₁.differentiableAt theorem congr {f g : X → Y} {x : X} {u : Set X} (hx : x ∈ u) (hu : IsOpen u) (hf : ConformalAt f x) (h : ∀ x : X, x ∈ u → g x = f x) : ConformalAt g x := let ⟨f', hfderiv, hf'⟩ := hf ⟨f', hfderiv.congr_of_eventuallyEq ((hu.eventually_mem hx).mono h), hf'⟩ theorem comp {f : X → Y} {g : Y → Z} (x : X) (hg : ConformalAt g (f x)) (hf : ConformalAt f x) : ConformalAt (g ∘ f) x := by rcases hf with ⟨f', hf₁, cf⟩ rcases hg with ⟨g', hg₁, cg⟩ exact ⟨g'.comp f', hg₁.comp x hf₁, cg.comp cf⟩ theorem const_smul {f : X → Y} {x : X} {c : ℝ} (hc : c ≠ 0) (hf : ConformalAt f x) : ConformalAt (c • f) x := (conformalAt_const_smul hc <| f x).comp x hf end ConformalAt end LocConformality section GlobalConformality /-- A map `f` is conformal if it's conformal at every point. -/ def Conformal (f : X → Y) := ∀ x : X, ConformalAt f x theorem conformal_id : Conformal (id : X → X) := fun x => conformalAt_id x theorem conformal_const_smul {c : ℝ} (h : c ≠ 0) : Conformal fun x : X => c • x := fun x => conformalAt_const_smul h x namespace Conformal theorem conformalAt {f : X → Y} (h : Conformal f) (x : X) : ConformalAt f x := h x theorem differentiable {f : X → Y} (h : Conformal f) : Differentiable ℝ f := fun x => (h x).differentiableAt theorem comp {f : X → Y} {g : Y → Z} (hf : Conformal f) (hg : Conformal g) : Conformal (g ∘ f) := fun x => (hg <| f x).comp x (hf x) theorem const_smul {f : X → Y} (hf : Conformal f) {c : ℝ} (hc : c ≠ 0) : Conformal (c • f) := fun x => (hf x).const_smul hc end Conformal end GlobalConformality
finfield.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import fintype div tuple bigop prime finset fingroup. From mathcomp Require Import ssralg poly polydiv morphism action countalg. From mathcomp Require Import finalg zmodp cyclic center pgroup abelian matrix. From mathcomp Require Import mxpoly vector falgebra fieldext separable galois. From mathcomp Require ssrnum ssrint archimedean algC cyclotomic. (******************************************************************************) (* Additional constructions and results on finite fields *) (* *) (* FinFieldExtType L == a FinFieldType structure on the carrier of L, *) (* where L IS a fieldExtType F structure for an *) (* F that has a finFieldType structure. This *) (* does not take any existing finType structure *) (* on L; this should not be made canonical *) (* FinSplittingFieldType F L == a SplittingFieldType F structure on the *) (* carrier of L, where L IS a fieldExtType F for *) (* an F with a finFieldType structure; this *) (* should not be made canonical *) (* finvect_type vT == alias of vT : vecType R equipped with *) (* canonical instances for finType, finNzRing, *) (* etc structures (including FinFieldExtType *) (* above) for abstract vectType, falgType and *) (* fieldExtType over a finFieldType *) (* pPrimeCharType pcharRp == the carrier of a nzRingType R such that *) (* pcharRp : p \in [pchar R] holds. This type has*) (* canonical nzRingType, ..., fieldType *) (* structures compatible with those of R, as well*) (* as canonical lmodType 'F_p, ..., algType 'F_p *) (* structures, plus an falgType structure if R *) (* is a finUnitRingType and a splittingFieldType *) (* structure if R is a finFieldType *) (* FinSplittingFieldFor nz_p == sigma-pair whose sval is a splittingFieldType *) (* that is the splitting field for p : {poly F} *) (* over F : finFieldType, given nz_p : p != 0 *) (* PrimePowerField pr_p k_gt0 == sigma2-triple whose s2val is a finFieldType *) (* of characteristic p and order m = p ^ k, *) (* given pr_p : prime p and k_gt0 : k > 0 *) (* FinDomainFieldType domR == a finFieldType structure on a finUnitRingType *) (* R, given domR : GRing.IntegralDomain.axiom R. *) (* This is intended to be used inside proofs, *) (* where one cannot declare Canonical instances *) (* Otherwise one should construct explicitly the *) (* intermediate structures using the ssralg and *) (* finalg constructors, and finDomain_mulrC domR *) (* finDomain_fieldP domR to prove commutativity *) (* and field axioms (the former is Wedderburn's *) (* little theorem). *) (* FinDomainSplittingFieldType domR pcharRp == a splittingFieldType structure *) (* that repackages the two constructions above *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope GRing.Theory FinRing.Theory. Local Open Scope ring_scope. Section FinNzRing. Variable R : finNzRingType. Lemma finNzRing_nontrivial : [set: R] != 1%g. Proof. by apply/trivgPn; exists 1; rewrite ?inE ?oner_neq0. Qed. Lemma finNzRing_gt1 : 1 < #|R|. Proof. by rewrite -cardsT cardG_gt1 finNzRing_nontrivial. Qed. End FinNzRing. #[deprecated(since="mathcomp 2.4.0", note="Use finNzRing_nontrivial instead.")] Notation finRing_nontrivial := (finNzRing_nontrivial) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use finNzRing_gt1 instead.")] Notation finRing_gt1 := (finNzRing_gt1) (only parsing). Section FinField. Variable F : finFieldType. Lemma card_finField_unit : #|[set: {unit F}]| = #|F|.-1. Proof. by rewrite -(cardC1 0) cardsT card_sub; apply: eq_card => x; rewrite unitfE. Qed. Definition finField_unit x (nz_x : x != 0) := FinRing.unit F (etrans (unitfE x) nz_x). Lemma expf_card x : x ^+ #|F| = x :> F. Proof. rewrite -[RHS]mulr1 -(ltn_predK (finNzRing_gt1 F)) exprS. apply/eqP; rewrite -subr_eq0 -mulrBr mulf_eq0 subr_eq0 -implyNb -unitfE. apply/implyP=> Ux; rewrite -(val_unitX _ (Sub x _)) -val_unit1 val_eqE. by rewrite -order_dvdn -card_finField_unit order_dvdG ?inE. Qed. Lemma finField_genPoly : 'X^#|F| - 'X = \prod_x ('X - x%:P) :> {poly F}. Proof. set n := #|F|; set oppX := - 'X; set pF := LHS. have le_oppX_n: size oppX <= n by rewrite size_polyN size_polyX finNzRing_gt1. have: size pF = (size (enum F)).+1 by rewrite -cardE size_polyDl size_polyXn. move/all_roots_prod_XsubC->; last by rewrite uniq_rootsE enum_uniq. by rewrite big_enum lead_coefDl ?size_polyXn // lead_coefXn scale1r. by apply/allP=> x _; rewrite rootE !hornerE expf_card subrr. Qed. Lemma finPcharP : {p | prime p & p \in [pchar F]}. Proof. pose e := exponent [set: F]; have e_gt0: e > 0 by apply: exponent_gt0. have: e%:R == 0 :> F by rewrite -zmodXgE expg_exponent // inE. by case/natf0_pchar/sigW=> // p pcharFp; exists p; rewrite ?(pcharf_prime pcharFp). Qed. Lemma finField_is_abelem : is_abelem [set: F]. Proof. have [p pr_p pcharFp] := finPcharP. by apply/is_abelemP; exists p; last apply: fin_ring_pchar_abelem. Qed. Lemma card_finPcharP p n : #|F| = (p ^ n)%N -> prime p -> p \in [pchar F]. Proof. move=> oF pr_p; rewrite inE pr_p -order_dvdn. rewrite (abelem_order_p finField_is_abelem) ?inE ?oner_neq0 //=. have n_gt0: n > 0 by rewrite -(ltn_exp2l _ _ (prime_gt1 pr_p)) -oF finNzRing_gt1. by rewrite cardsT oF -(prednK n_gt0) pdiv_pfactor. Qed. End FinField. #[deprecated(since="mathcomp 2.4.0", note="Use finPcharP instead.")] Notation finCharP := (finPcharP) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use card_finPcharP instead.")] Notation card_finCharP := (card_finPcharP) (only parsing). Section CardVspace. Variables (F : finFieldType) (T : finType). Section Vector. Variable cvT : Vector F T. Let vT := Vector.Pack cvT. Lemma card_vspace (V : {vspace vT}) : #|V| = (#|F| ^ \dim V)%N. Proof. set n := \dim V; pose V2rV v := \row_i coord (vbasis V) i v. pose rV2V (rv : 'rV_n) := \sum_i rv 0 i *: (vbasis V)`_i. have rV2V_K: cancel rV2V V2rV. have freeV: free (vbasis V) := basis_free (vbasisP V). by move=> rv; apply/rowP=> i; rewrite mxE coord_sum_free. rewrite -[n]mul1n -card_mx -(card_imset _ (can_inj rV2V_K)). apply: eq_card => v; apply/idP/imsetP=> [/coord_vbasis-> | [rv _ ->]]. by exists (V2rV v) => //; apply: eq_bigr => i _; rewrite mxE. by apply: (@rpred_sum vT) => i _; rewrite rpredZ ?vbasis_mem ?memt_nth. Qed. Lemma card_vspacef : #|{: vT}%VS| = #|T|. Proof. by apply: eq_card => v; rewrite (@memvf _ vT). Qed. End Vector. Variable caT : Falgebra F T. Let aT := Falgebra.Pack caT. Lemma card_vspace1 : #|(1%VS : {vspace aT})| = #|F|. Proof. by rewrite card_vspace (dimv1 aT). Qed. End CardVspace. Definition finvect_type (vT : Type) : predArgType := vT. Section FinVector. Variables (R : finNzRingType) (vT : vectType R). Local Notation fvT := (finvect_type vT). HB.instance Definition _ := Vector.on fvT. HB.instance Definition _ := isCountable.Build fvT (pcan_pickleK (can_pcan VectorInternalTheory.v2rK)). HB.instance Definition _ := isFinite.Build fvT (pcan_enumP (can_pcan (VectorInternalTheory.v2rK : @cancel _ fvT _ _))). End FinVector. HB.instance Definition _ (F : finFieldType) (aT : falgType F) := Falgebra.on (finvect_type aT). Section FinFieldExt. Variables (F : finFieldType) (fT : fieldExtType F). Local Notation ffT := (finvect_type fT). HB.instance Definition _ := FieldExt.on ffT. Lemma ffT_splitting_subproof : SplittingField.axiom ffT. Proof. exists ('X^#|ffT| - 'X). by rewrite (@rpredB {poly fT}) 1?rpredX ?polyOverX. exists (enum ffT); first by rewrite big_enum finField_genPoly eqpxx. by apply/vspaceP=> x; rewrite memvf seqv_sub_adjoin ?mem_enum. Qed. HB.instance Definition _ := FieldExt_isSplittingField.Build F ffT ffT_splitting_subproof. End FinFieldExt. Definition FinSplittingFieldType (F : finFieldType) (fT : fieldExtType F) := HB.pack_for (splittingFieldType F) fT (SplittingField.on (finvect_type fT)). Definition FinFieldExtType (F : finFieldType) (fT : fieldExtType F) := HB.pack_for finFieldType (FinSplittingFieldType fT) (FinRing.Field.on (finvect_type fT)). Arguments FinSplittingFieldType : clear implicits. Section PrimeChar. Variable p : nat. Section PrimeCharRing. Variable R0 : nzRingType. Definition pPrimeCharType of p \in [pchar R0] : predArgType := R0. Hypothesis pcharRp : p \in [pchar R0]. Local Notation R := (pPrimeCharType pcharRp). Implicit Types (a b : 'F_p) (x y : R). HB.instance Definition _ := GRing.NzRing.on R. Definition pprimeChar_scale a x := a%:R * x. Local Infix "*p':" := pprimeChar_scale (at level 40). Let natrFp n : (inZp n : 'F_p)%:R = n%:R :> R. Proof. rewrite [in RHS](divn_eq n p) natrD mulrnA (mulrn_pchar pcharRp) add0r. by rewrite /= (Fp_cast (pcharf_prime pcharRp)). Qed. Lemma pprimeChar_scaleA a b x : a *p': (b *p': x) = (a * b) *p': x. Proof. by rewrite /pprimeChar_scale mulrA -natrM natrFp. Qed. Lemma pprimeChar_scale1 : left_id 1 pprimeChar_scale. Proof. by move=> x; rewrite /pprimeChar_scale mul1r. Qed. Lemma pprimeChar_scaleDr : right_distributive pprimeChar_scale +%R. Proof. by move=> a x y /=; rewrite /pprimeChar_scale mulrDr. Qed. Lemma pprimeChar_scaleDl x : {morph pprimeChar_scale^~ x: a b / a + b}. Proof. by move=> a b; rewrite /pprimeChar_scale natrFp natrD mulrDl. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build 'F_p R pprimeChar_scaleA pprimeChar_scale1 pprimeChar_scaleDr pprimeChar_scaleDl. Lemma pprimeChar_scaleAl (a : 'F_p) (u v : R) : a *: (u * v) = (a *: u) * v. Proof. by apply: mulrA. Qed. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build 'F_p R pprimeChar_scaleAl. Lemma pprimeChar_scaleAr (a : 'F_p) (x y : R) : a *: (x * y) = x * (a *: y). Proof. by rewrite ![a *: _]mulr_natl mulrnAr. Qed. HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build 'F_p R pprimeChar_scaleAr. End PrimeCharRing. Local Notation type := @pPrimeCharType. (* TODO: automatize parameter inference to do all of these *) HB.instance Definition _ (R : unitRingType) pcharRp := GRing.UnitRing.on (type R pcharRp). HB.instance Definition _ (R : comNzRingType) pcharRp := GRing.ComNzRing.on (type R pcharRp). HB.instance Definition _ (R : comUnitRingType) pcharRp := GRing.ComUnitRing.on (type R pcharRp). HB.instance Definition _ (R : idomainType) pcharRp := GRing.IntegralDomain.on (type R pcharRp). HB.instance Definition _ (R : fieldType) pcharRp := GRing.Field.on (type R pcharRp). Section FinNzRing. Variables (R0 : finNzRingType) (pcharRp : p \in [pchar R0]). Local Notation R := (type _ pcharRp). HB.instance Definition _ := FinGroup.on R. Let pr_p : prime p. Proof. exact: pcharf_prime pcharRp. Qed. Lemma pprimeChar_abelem : p.-abelem [set: R]. Proof. exact: fin_Fp_lmod_abelem. Qed. Lemma pprimeChar_pgroup : p.-group [set: R]. Proof. by case/and3P: pprimeChar_abelem. Qed. Lemma order_pprimeChar x : x != 0 :> R -> #[x]%g = p. Proof. by apply: (abelem_order_p pprimeChar_abelem); rewrite inE. Qed. Let n := logn p #|R|. Lemma card_pprimeChar : #|R| = (p ^ n)%N. Proof. by rewrite /n -cardsT {1}(card_pgroup pprimeChar_pgroup). Qed. Lemma pprimeChar_vectAxiom : Vector.axiom n R. Proof. have /isog_isom/=[f /isomP[injf im_f]]: [set: R] \isog [set: 'rV['F_p]_n]. rewrite (@isog_abelem_card _ _ p) fin_Fp_lmod_abelem //=. by rewrite !cardsT card_pprimeChar card_mx mul1n card_Fp. exists f; last by exists (invm injf) => x; rewrite ?invmE ?invmK ?im_f ?inE. move=> a x y; rewrite [a *: _]mulr_natl morphM ?morphX ?inE // zmodXgE. by congr (_ + _); rewrite -scaler_nat natr_Zp. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build 'F_p R pprimeChar_vectAxiom. Lemma pprimeChar_dimf : \dim {: R : vectType 'F_p } = n. Proof. by rewrite dimvf. Qed. End FinNzRing. HB.instance Definition _ (R : finUnitRingType) pcharRp := FinRing.UnitRing.on (type R pcharRp). HB.instance Definition _ (R : finComNzRingType) pcharRp := FinRing.ComNzRing.on (type R pcharRp). HB.instance Definition _ (R : finComUnitRingType) pcharRp := FinRing.ComUnitRing.on (type R pcharRp). HB.instance Definition _ (R : finIdomainType) pcharRp := FinRing.IntegralDomain.on (type R pcharRp). Section FinField. Variables (F0 : finFieldType) (pcharFp : p \in [pchar F0]). Local Notation F := (type _ pcharFp). HB.instance Definition _ := Finite.on F. HB.instance Definition _ := SplittingField.copy F (finvect_type F). End FinField. End PrimeChar. #[deprecated(since="mathcomp 2.4.0", note="Use pPrimeCharType instead.")] Notation PrimeCharType := (pPrimeCharType) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scale instead.")] Notation primeChar_scale := (pprimeChar_scale) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleA instead.")] Notation primeChar_scaleA := (pprimeChar_scaleA) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scale1 instead.")] Notation primeChar_scale1 := (pprimeChar_scale1) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleDr instead.")] Notation primeChar_scaleDr := (pprimeChar_scaleDr) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleDl instead.")] Notation primeChar_scaleDl := (pprimeChar_scaleDl) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleAl instead.")] Notation primeChar_scaleAl := (pprimeChar_scaleAl) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleAr instead.")] Notation primeChar_scaleAr := (pprimeChar_scaleAr) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_abelem instead.")] Notation primeChar_abelem := (pprimeChar_abelem) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_pgroup instead.")] Notation primeChar_pgroup := (pprimeChar_pgroup) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use order_pprimeChar instead.")] Notation order_primeChar := (order_pprimeChar) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use card_pprimeChar instead.")] Notation card_primeChar := (card_pprimeChar) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_vectAxiom instead.")] Notation primeChar_vectAxiom := (pprimeChar_vectAxiom) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_dimf instead.")] Notation primeChar_dimf := (pprimeChar_dimf) (only parsing). Section FinSplittingField. Variable F : finFieldType. (* By card_vspace order K = #|K| for any finType structure on L; however we *) (* do not want to impose the FinVector instance here. *) Let order (L : vectType F) (K : {vspace L}) := (#|F| ^ \dim K)%N. Section FinGalois. Variable L : splittingFieldType F. Implicit Types (a b : F) (x y : L) (K E : {subfield L}). Let galL K : galois K {:L}. Proof. without loss {K} ->: K / K = 1%AS. by move=> IH_K; apply: galoisS (IH_K _ (erefl _)); rewrite sub1v subvf. apply/splitting_galoisField; pose finL := FinFieldExtType L. exists ('X^#|finL| - 'X); split; first by rewrite rpredB 1?rpredX ?polyOverX. rewrite (finField_genPoly finL) -big_enum /=. by rewrite separable_prod_XsubC ?(enum_uniq finL). exists (enum finL). by rewrite (@big_enum _ _ _ _ finL) (finField_genPoly finL) eqpxx. by apply/vspaceP=> x; rewrite memvf seqv_sub_adjoin ?(mem_enum finL). Qed. Fact galLgen K : {alpha | generator 'Gal({:L} / K) alpha & forall x, alpha x = x ^+ order K}. Proof. without loss{K} ->: K / K = 1%AS; last rewrite /order dimv1 expn1. case/(_ 1%AS)=> // alpha /eqP-defGalL; rewrite /order dimv1 expn1 => Dalpha. exists (alpha ^+ \dim K)%g => [|x]; last first. elim: (\dim K) => [|n IHn]; first by rewrite gal_id. by rewrite expgSr galM ?memvf // IHn Dalpha expnSr exprM. have sGalLK: 'Gal({:L} / K) \subset <[alpha]> by rewrite -defGalL galS ?sub1v. rewrite /generator {sGalLK}(eq_subG_cyclic _ sGalLK) ?cycle_cyclic ?cycleX //. rewrite -orderE orderXdiv orderE -defGalL -?{1}galois_dim ?dimv1 ?divn1 //. by rewrite field_dimS ?subvf. pose f x := x ^+ #|F|. have idfP x: reflect (f x = x) (x \in 1%VS). apply: (iffP (vlineP _ _)) => [[a ->] | xFx]. by rewrite -in_algE -[LHS]rmorphXn expf_card. pose q := map_poly (in_alg L) ('X^#|F| - 'X). have: root q x. rewrite /q rmorphB /= map_polyXn map_polyX. by rewrite rootE !(hornerE, hornerXn) [x ^+ _]xFx subrr. have{q} ->: q = \prod_(z <- [seq b%:A | b : F]) ('X - z%:P). rewrite /q finField_genPoly rmorph_prod big_image /=. by apply: eq_bigr => b _; rewrite rmorphB /= map_polyX map_polyC. by rewrite root_prod_XsubC => /mapP[a]; exists a. have fA : zmod_morphism f. rewrite /f => x y; rewrite ?exprMn ?expr1n //. have [p _ pcharFp] := finPcharP F; rewrite (card_pprimeChar pcharFp). elim: (logn _ _) => // n IHn; rewrite expnSr !exprM {}IHn. by rewrite -(pchar_lalg L) in pcharFp; rewrite -pFrobenius_autE rmorphB. have fM : monoid_morphism f. by rewrite /f; split=> [|x y]; rewrite ?exprMn ?expr1n //. have fZ: scalable f. move=> a x; rewrite -[in LHS]mulr_algl fM. by rewrite (idfP _ _) ?mulr_algl ?memvZ // memv_line. pose faM := GRing.isZmodMorphism.Build _ _ f fA. pose fmM := GRing.isMonoidMorphism.Build _ _ f fM. pose flM := GRing.isScalable.Build _ _ _ _ f fZ. pose fLRM : {lrmorphism _ -> _} := HB.pack f faM fmM flM. have /kAut_to_gal[alpha galLalpha Dalpha]: kAut 1 {:L} (linfun fLRM). rewrite kAutfE; apply/kHomP_tmp; split=> [x /idfP | x y _ _]; rewrite !lfunE //=. exact: (rmorphM fLRM). have{} Dalpha: alpha =1 f by move=> a; rewrite -Dalpha ?memvf ?lfunE. suffices <-: fixedField [set alpha] = 1%AS. by rewrite gal_generated /generator; exists alpha. apply/vspaceP=> x; apply/fixedFieldP/idfP; rewrite ?memvf // => id_x. by rewrite -Dalpha id_x ?set11. by move=> _ /set1P->; rewrite Dalpha. Qed. Lemma finField_galois K E : (K <= E)%VS -> galois K E. Proof. move=> sKE; have /galois_fixedField <- := galL E. rewrite normal_fixedField_galois // -sub_abelian_normal ?galS //. apply: abelianS (galS _ (sub1v _)) _. by have [alpha /('Gal(_ / _) =P _)-> _] := galLgen 1; apply: cycle_abelian. Qed. Lemma finField_galois_generator K E : (K <= E)%VS -> {alpha | generator 'Gal(E / K) alpha & {in E, forall x, alpha x = x ^+ order K}}. Proof. move=> sKE; have [alpha defGalLK Dalpha] := galLgen K. have inKL_E: (K <= E <= {:L})%VS by rewrite sKE subvf. have nKE: normalField K E by have/and3P[] := finField_galois sKE. have galLKalpha: alpha \in 'Gal({:L} / K). by rewrite (('Gal(_ / _) =P _) defGalLK) cycle_id. exists (normalField_cast _ alpha) => [|x Ex]; last first. by rewrite (normalField_cast_eq inKL_E). rewrite /generator -(morphim_cycle (normalField_cast_morphism inKL_E nKE)) //. by rewrite -((_ =P <[alpha]>) defGalLK) normalField_img. Qed. End FinGalois. Lemma Fermat's_little_theorem (L : fieldExtType F) (K : {subfield L}) a : (a \in K) = (a ^+ order K == a). Proof. move: K a; wlog [{}L -> K a]: L / exists galL : splittingFieldType F, L = galL. by pose galL := FinSplittingFieldType F L => /(_ galL); apply; exists galL. have /galois_fixedField fixLK := finField_galois (subvf K). have [alpha defGalLK Dalpha] := finField_galois_generator (subvf K). rewrite -Dalpha ?memvf // -{1}fixLK (('Gal(_ / _) =P _) defGalLK). rewrite /cycle -gal_generated (galois_fixedField _) ?fixedField_galois //. by apply/fixedFieldP/eqP=> [|-> | alpha_x _ /set1P->]; rewrite ?memvf ?set11. Qed. End FinSplittingField. Section FinFieldExists. (* While the existence of finite splitting fields and of finite fields of *) (* arbitrary prime power order is mathematically straightforward, it is *) (* technically challenging to formalize in Coq. The Coq typechecker performs *) (* poorly for some of the deeply nested dependent types used in the *) (* construction, such as polynomials over extensions of extensions of finite *) (* fields. Any conversion in a nested structure parameter incurs a huge *) (* overhead as it is shared across term comparison by call-by-need evalution. *) (* The proof of FinSplittingFieldFor is contrived to mitigate this effect: *) (* the abbreviation map_poly_extField alone divides by 3 the proof checking *) (* time, by reducing the number of occurrences of field(Ext)Type structures *) (* in the subgoals; the successive, apparently redundant 'suffices' localize *) (* some of the conversions to smaller subgoals, yielding a further 8-fold *) (* time gain. In particular, we construct the splitting field as a subtype *) (* of a recursive construction rather than prove that the latter yields *) (* precisely a splitting field. *) (* The apparently redundant type annotation reduces checking time by 30%. *) Let map_poly_extField (F : fieldType) (L : fieldExtType F) := map_poly (in_alg L) : {poly F} -> {poly L}. Local Notation "p ^%:A" := (map_poly_extField _ p) (format "p ^%:A") : ring_scope. Lemma FinSplittingFieldFor (F : finFieldType) (p : {poly F}) : p != 0 -> {L : splittingFieldType F | splittingFieldFor 1 p^%:A {:L}}. Proof. have mapXsubC (f : {rmorphism _ -> _}) x: map_poly f ('X - x%:P) = 'X - (f x)%:P. by rewrite rmorphB /= map_polyX map_polyC. move=> nz_p; pose splits q := {zs | q %= \prod_(z <- zs) ('X - z%:P)}. suffices [L splitLp]: {L : fieldExtType F | splittingFieldFor 1 p^%:A {:L}}. by exists (FinSplittingFieldType F L). suffices [L [ys Dp]]: {L : fieldExtType F & splits L p^%:A}. pose Lp := subvs_of <<1 & ys>>; pose toL := linfun (vsval : Lp -> L). have [zs Dys]: {zs | map toL zs = ys}. exists (map (vsproj _) ys); rewrite -map_comp map_id_in // => y ys_y. by rewrite /= lfunE /= vsprojK ?seqv_sub_adjoin. exists Lp, zs. set lhs := (lhs in lhs %= _); set rhs := (rhs in _ %= rhs). suffices: map_poly toL lhs %= map_poly toL rhs by rewrite eqp_map. rewrite -Dys big_map in Dp; apply: etrans Dp; apply: congr2. by rewrite -map_poly_comp; apply/eq_map_poly=> x; apply: rmorph_alg. by rewrite rmorph_prod; apply/eq_bigr=> z _; apply mapXsubC. set Lzs := LHS; pose Lys := (toL @: Lzs)%VS; apply/vspaceP=> u. have: val u \in Lys by rewrite /Lys aimg_adjoin_seq aimg1 Dys (valP u). by case/memv_imgP=> v Lzs_v; rewrite memvf lfunE => /val_inj->. move: {2}_.+1 (ltnSn (size p)) => n; elim: n => // n IHn in F p nz_p * => lbn. have [Cp|C'p] := leqP (size p) 1. exists F^o, [::]. by rewrite big_nil -size_poly_eq1 size_map_poly eqn_leq Cp size_poly_gt0. have [r r_dv_p irr_r]: {r | r %| p & irreducible_poly r}. pose rVp (v : 'rV_n) (r := rVpoly v) := (1 < size r) && (r %| p). have [v0 Dp]: {v0 | rVpoly v0 = p & rVp v0}. by exists (poly_rV p); rewrite /rVp poly_rV_K ?C'p /=. case/(arg_minnP (size \o rVpoly))=> /= v; set r := rVpoly v. case/andP=> C'r r_dv_p min_r; exists r => //; split=> // q C'q q_dv_r. have nz_r: r != 0 by rewrite -size_poly_gt0 ltnW. have le_q_r: size q <= size r by rewrite dvdp_leq. have [u Dq]: {u : 'rV_n | rVpoly u = q}. by exists (poly_rV q); rewrite poly_rV_K ?(leq_trans le_q_r) ?size_poly. rewrite -dvdp_size_eqp // eqn_leq le_q_r -Dq min_r // /rVp Dq. rewrite ltn_neqAle eq_sym C'q size_poly_gt0 (dvdpN0 q_dv_r) //=. exact: dvdp_trans q_dv_r r_dv_p. have{irr_r} [K _ [x rx0 defK]] := irredp_FAdjoin irr_r. have{r rx0 r_dv_p} /factor_theorem/sig_eqW[q Dp]: root p^%:A x. by rewrite -(divpK r_dv_p) [_^%:A]rmorphM rootM rx0 orbT. have Dszp: size p = size (q * ('X - x%:P)) by rewrite -Dp size_map_poly. have nz_q: q != 0. by move: nz_p; rewrite -size_poly_eq0 Dszp size_poly_eq0 mulf_eq0 => /norP[]. have [L [zs Dq]]: {L : fieldExtType K & splits L q^%:A}. apply: (IHn (FinFieldExtType K) q nz_q). by rewrite ltnS Dszp size_mul ?polyXsubC_eq0 ?size_XsubC ?addn2 in lbn. suffices: splits L p^%:A^%:A. rewrite -[_^%:A]map_poly_comp. (* TODO_HB : had to give the F explicitly *) rewrite -(eq_map_poly (fun a : F => baseField_scaleE a 1)). by exists (baseFieldType L). exists (x%:A :: zs); rewrite big_cons; set rhs := _ * _. by rewrite Dp mulrC [_^%:A]rmorphM /= mapXsubC /= eqp_mull. Qed. Lemma pPrimePowerField p k (m := (p ^ k)%N) : prime p -> 0 < k -> {Fm : finFieldType | p \in [pchar Fm] & #|Fm| = m}. Proof. move=> pr_p k_gt0; have m_gt1: m > 1 by rewrite (ltn_exp2l 0) ?prime_gt1. have m_gt0 := ltnW m_gt1; have m1_gt0: m.-1 > 0 by rewrite -ltnS prednK. pose q := 'X^m - 'X; have Dq R: q R = ('X^(m.-1) - 1) * ('X - 0). by rewrite subr0 mulrBl mul1r -exprSr prednK. have /FinSplittingFieldFor[/= L splitLq]: q 'F_p != 0. by rewrite Dq monic_neq0 ?rpredM ?monicXsubC ?monicXnsubC. rewrite [_^%:A]rmorphB rmorphXn /= map_polyX -/(q L) in splitLq. have pcharL: p \in [pchar L] by rewrite pchar_lalg pchar_Fp. pose Fm := FinFieldExtType L; exists Fm => //. have /finField_galois_generator[/= a _ Da]: (1 <= {:L})%VS by apply: sub1v. pose Em := fixedSpace (a ^+ k)%g; rewrite card_Fp //= dimv1 expn1 in Da. have{splitLq} [zs DqL defL] := splitLq. have Uzs: uniq zs. rewrite -separable_prod_XsubC -(eqp_separable DqL) Dq separable_root andbC. rewrite /root !hornerE subr_eq0 eq_sym expr0n gtn_eqF ?oner_eq0 //=. rewrite cyclotomic.separable_Xn_sub_1 // -subn1 natrB // subr_eq0. by rewrite natrX pcharf0 // expr0n gtn_eqF // eq_sym oner_eq0. suffices /eq_card->: Fm =i zs. apply: succn_inj; rewrite (card_uniqP _) //= -(size_prod_XsubC _ id). by rewrite -(eqp_size DqL) size_polyDl size_polyXn // size_polyN size_polyX. have in_zs: zs =i Em. move=> z; rewrite -root_prod_XsubC -(eqp_root DqL) (sameP fixedSpaceP eqP). rewrite /root !hornerE subr_eq0 /= /m; congr (_ == z). elim: (k) => [|i IHi]; first by rewrite gal_id. by rewrite expgSr expnSr exprM IHi galM ?Da ?memvf. suffices defEm: Em = {:L}%VS by move=> z; rewrite in_zs defEm memvf. apply/eqP; rewrite eqEsubv subvf -defL -[Em]subfield_closed agenvS //. by rewrite subv_add sub1v; apply/span_subvP=> z; rewrite in_zs. Qed. End FinFieldExists. #[deprecated(since="mathcomp 2.4.0", note="Use pPrimePowerField instead.")] Notation PrimePowerField := (pPrimePowerField) (only parsing). Section FinDomain. Import order ssrnum ssrint archimedean algC cyclotomic Order.TTheory Num.Theory. Local Infix "%|" := dvdn. (* Hide polynomial divisibility. *) Variable R : finUnitRingType. Hypothesis domR : GRing.integral_domain_axiom R. Implicit Types x y : R. Let lregR x : x != 0 -> GRing.lreg x. Proof. by move=> xnz; apply: mulrI0_lreg => y /domR/orP[/idPn | /eqP]. Qed. Lemma finDomain_field : GRing.field_axiom R. Proof. move=> x /lregR-regx; apply/unitrP; exists (invF regx 1). by split; first apply: (regx); rewrite ?mulrA f_invF // mulr1 mul1r. Qed. (* This is Witt's proof of Wedderburn's little theorem. *) Theorem finDomain_mulrC : @commutative R R *%R. Proof. have fieldR := finDomain_field. have [p p_pr pcharRp]: exists2 p, prime p & p \in [pchar R]. have [e /prod_prime_decomp->]: {e | (e > 0)%N & e%:R == 0 :> R}. by exists #|[set: R]%G|; rewrite // -order_dvdn order_dvdG ?inE. rewrite big_seq; elim/big_rec: _ => [|[p m] /= n]; first by rewrite oner_eq0. case/mem_prime_decomp=> p_pr _ _ IHn. elim: m => [|m IHm]; rewrite ?mul1n {IHn}// expnS -mulnA natrM. by case/eqP/domR/orP=> //; exists p; last apply/andP. pose Rp := pPrimeCharType pcharRp; pose L : {vspace Rp} := fullv. pose G := [set: {unit R}]; pose ofG : {unit R} -> Rp := val. pose projG (E : {vspace Rp}) := [preim ofG of E]. have inG t nzt: Sub t (finDomain_field nzt) \in G by rewrite inE. have card_projG E: #|projG E| = (p ^ \dim E - 1)%N. transitivity #|E|.-1; last by rewrite subn1 card_vspace card_Fp. rewrite (cardD1 0) mem0v (card_preim val_inj) /=. apply: eq_card => x; congr (_ && _); rewrite [LHS]codom_val. by apply/idP/idP=> [/(memPn _ _)-> | /fieldR]; rewrite ?unitr0. pose C u := 'C[ofG u]%AS; pose Q := 'C(L)%AS; pose q := (p ^ \dim Q)%N. have defC u: 'C[u] =i projG (C u). by move=> v; rewrite cent1E !inE (sameP cent1vP eqP). have defQ: 'Z(G) =i projG Q. move=> u /[!inE]. apply/centP/centvP=> cGu v _; last exact/val_inj/cGu/memvf. by have [-> | /inG/cGu[]] := eqVneq v 0; first by rewrite commr0. have q_gt1: (1 < q)%N by rewrite (ltn_exp2l 0) ?prime_gt1 ?adim_gt0. pose n := \dim_Q L; have oG: #|G| = (q ^ n - 1)%N. rewrite -expnM mulnC divnK ?skew_field_dimS ?subvf // -card_projG. by apply: eq_card => u; rewrite !inE memvf. have oZ: #|'Z(G)| = (q - 1)%N by rewrite -card_projG; apply: eq_card. suffices n_le1: (n <= 1)%N. move=> u v; apply/centvsP: (memvf (u : Rp)) (memvf (v : Rp)) => {u v}. rewrite -(geq_leqif (dimv_leqif_sup (subvf Q))) -/L. by rewrite leq_divLR ?mul1n ?skew_field_dimS ?subvf in n_le1. without loss n_gt1: / (1 < n)%N by rewrite ltnNge; apply: wlog_neg. have [q_gt0 n_gt0] := (ltnW q_gt1, ltnW n_gt1). have [z z_prim] := C_prim_root_exists n_gt0. have zn1: z ^+ n = 1 by apply: prim_expr_order. have /eqP-n1z: `|z| == 1 by rewrite -(pexpr_eq1 n_gt0) // -normrX zn1 normr1. suffices /eqP/normCBeq[t n1t [Dq Dz]]: `|q%:R - z : algC| == `|q%:R : algC| - `|z|. suffices z1: z == 1 by rewrite leq_eqVlt -dvdn1 (prim_order_dvd z_prim) z1. by rewrite Dz n1z mul1r -(eqr_pMn2r q_gt0) Dq normr_nat mulr_natl. pose aq d : algC := (cyclotomic (z ^+ (n %/ d)) d).[q%:R]. suffices: `|aq n| <= (q - 1)%:R. rewrite eq_le lerB_dist andbT n1z normr_nat natrB //; apply: le_trans. rewrite {}/aq horner_prod divnn n_gt0 expr1 normr_prod. rewrite (bigD1 (Ordinal n_gt1)) ?coprime1n //= !hornerE ler_peMr //. elim/big_ind: _ => // [|d _]; first exact: mulr_ege1. rewrite !hornerE; apply: le_trans (lerB_dist _ _). by rewrite normr_nat normrX n1z expr1n lerBDl (leC_nat 2). have Zaq d: d %| n -> aq d \in Num.int. move/(dvdn_prim_root z_prim)=> zd_prim. rewrite rpred_horner ?rpred_nat //= -Cintr_Cyclotomic //. by apply/polyOverP=> i; rewrite coef_map ?rpred_int. suffices: (aq n %| (q - 1)%:R)%C. rewrite {1}[aq n]intrEsign ?Zaq // -(rpredMsign _ (aq n < 0)%R). rewrite dvdC_mul2l ?signr_eq0 //. have /natrP[m ->]: `|aq n| \in Num.nat by rewrite natr_norm_int ?Zaq. by rewrite leC_nat dvdC_nat; apply: dvdn_leq; rewrite subn_gt0. have prod_aq m: m %| n -> \prod_(d < n.+1 | d %| m) aq d = (q ^ m - 1)%:R. move=> m_dv_n; transitivity ('X^m - 1).[q%:R : algC]; last first. by rewrite !hornerE -natrX natrB ?expn_gt0 ?prime_gt0. rewrite (prod_cyclotomic (dvdn_prim_root z_prim m_dv_n)). have def_divm: perm_eq (divisors m) [seq d <- index_iota 0 n.+1 | d %| m]. rewrite uniq_perm ?divisors_uniq ?filter_uniq ?iota_uniq // => d. rewrite -dvdn_divisors ?(dvdn_gt0 n_gt0) // mem_filter mem_iota ltnS /=. by apply/esym/andb_idr=> d_dv_m; rewrite dvdn_leq ?(dvdn_trans d_dv_m). rewrite (perm_big _ def_divm) big_filter big_mkord horner_prod. by apply: eq_bigr => d d_dv_m; rewrite -exprM muln_divA ?divnK. have /rpredBl<-: (aq n %| #|G|%:R)%C. rewrite oG -prod_aq // (bigD1 ord_max) //= dvdC_mulr //. by apply: rpred_prod => d /andP[/Zaq]. rewrite center_class_formula addrC oZ natrD addKr natr_sum /=. apply: rpred_sum => _ /imsetP[u /setDP[_ Z'u] ->]; rewrite -/G /=. have sQC: (Q <= C u)%VS by apply/subvP=> v /centvP-cLv; apply/cent1vP/cLv/memvf. have{sQC} /dvdnP[m Dm]: \dim Q %| \dim (C u) by apply: skew_field_dimS. have m_dv_n: m %| n by rewrite dvdn_divRL // -?Dm ?skew_field_dimS ?subvf. have m_gt0: (0 < m)%N := dvdn_gt0 n_gt0 m_dv_n. have{Dm} oCu: #|'C[u]| = (q ^ m - 1)%N. by rewrite -expnM mulnC -Dm (eq_card (defC u)) card_projG. have ->: #|u ^: G|%:R = \prod_(d < n.+1 | d %| n) (aq d / aq d ^+ (d %| m)). rewrite -index_cent1 natf_indexg ?subsetT //= setTI prodf_div prod_aq // -oG. congr (_ / _); rewrite big_mkcond oCu -prod_aq //= big_mkcond /=. by apply: eq_bigr => d _; case: ifP => [/dvdn_trans->| _]; rewrite ?if_same. rewrite (bigD1 ord_max) //= [n %| m](contraNF _ Z'u) => [|n_dv_m]; last first. rewrite -sub_cent1 subEproper eq_sym eqEcard subsetT oG oCu leq_sub2r //. by rewrite leq_exp2l // dvdn_leq. rewrite divr1 dvdC_mulr //; apply/rpred_prod => d /andP[/Zaq-Zaqd _]. have [-> | nz_aqd] := eqVneq (aq d) 0; first by rewrite mul0r /=. by rewrite -[aq d]expr1 -exprB ?leq_b1 ?unitfE ?rpredX. Qed. Definition FinDomainFieldType : finFieldType := let cC := GRing.PzRing_hasCommutativeMul.Build R finDomain_mulrC in let cR : comUnitRingType := HB.pack R cC in let iC := GRing.ComUnitRing_isIntegral.Build cR domR in let iR : finIdomainType := HB.pack cR iC in let fC := GRing.UnitRing_isField.Build iR finDomain_field in HB.pack iR fC. Definition FinDomainSplittingFieldType_pchar p (pcharRp : p \in [pchar R]) := SplittingField.clone 'F_p R (@pPrimeCharType p FinDomainFieldType pcharRp). End FinDomain. #[deprecated(since="mathcomp 2.4.0", note="Use FinDomainSplittingFieldType_pchar instead.")] Notation FinDomainSplittingFieldType := (FinDomainSplittingFieldType_pchar) (only parsing).
Filtered.lean
/- Copyright (c) 2024 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.CategoryTheory.Limits.FunctorCategory.Basic import Mathlib.CategoryTheory.Limits.Filtered /-! # Functor categories have filtered colimits when the target category does These declarations cannot be in `Mathlib/CategoryTheory/Limits/FunctorCategory.lean` because that file shouldn't import `Mathlib/CategoryTheory/Limits/Filtered.lean`. -/ universe w' w v₁ v₂ u₁ u₂ namespace CategoryTheory.Limits variable {C : Type u₁} [Category.{v₁} C] {K : Type u₂} [Category.{v₂} K] instance [HasFilteredColimitsOfSize.{w', w} C] : HasFilteredColimitsOfSize.{w', w} (K ⥤ C) := ⟨fun _ => inferInstance⟩ instance [HasCofilteredLimitsOfSize.{w', w} C] : HasCofilteredLimitsOfSize.{w', w} (K ⥤ C) := ⟨fun _ => inferInstance⟩ end CategoryTheory.Limits
PowerSeries.lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import Mathlib.RingTheory.HahnSeries.Multiplication import Mathlib.RingTheory.PowerSeries.Basic import Mathlib.RingTheory.MvPowerSeries.NoZeroDivisors import Mathlib.Data.Finsupp.PWO /-! # Comparison between Hahn series and power series If `Γ` is ordered and `R` has zero, then `HahnSeries Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are partially well-ordered. With further structure on `R` and `Γ`, we can add further structure on `HahnSeries Γ R`. When `R` is a semiring and `Γ = ℕ`, then we get the more familiar semiring of formal power series with coefficients in `R`. ## Main Definitions * `toPowerSeries` the isomorphism from `HahnSeries ℕ R` to `PowerSeries R`. * `ofPowerSeries` the inverse, casting a `PowerSeries R` to a `HahnSeries ℕ R`. ## Instances * For `Finite σ`, the instance `NoZeroDivisors (HahnSeries (σ →₀ ℕ) R)`, deduced from the case of `MvPowerSeries` The case of `HahnSeries ℕ R` is taken care of by `instNoZeroDivisors`. ## TODO * Build an API for the variable `X` (defined to be `single 1 1 : HahnSeries Γ R`) in analogy to `X : R[X]` and `X : PowerSeries R` ## References - [J. van der Hoeven, *Operators on Generalized Power Series*][van_der_hoeven] -/ open Finset Function Pointwise Polynomial noncomputable section variable {Γ R : Type*} namespace HahnSeries section Semiring variable [Semiring R] /-- The ring `HahnSeries ℕ R` is isomorphic to `PowerSeries R`. -/ @[simps] def toPowerSeries : HahnSeries ℕ R ≃+* PowerSeries R where toFun f := PowerSeries.mk f.coeff invFun f := ⟨fun n => PowerSeries.coeff R n f, .of_linearOrder _⟩ left_inv f := by ext simp right_inv f := by ext simp map_add' f g := by ext simp map_mul' f g := by ext n simp only [PowerSeries.coeff_mul, PowerSeries.coeff_mk, coeff_mul] classical refine (sum_filter_ne_zero _).symm.trans <| (sum_congr ?_ fun _ _ ↦ rfl).trans <| sum_filter_ne_zero _ ext m simp only [mem_antidiagonal, mem_addAntidiagonal, and_congr_left_iff, mem_filter, mem_support] rintro h rw [and_iff_right (left_ne_zero_of_mul h), and_iff_right (right_ne_zero_of_mul h)] theorem coeff_toPowerSeries {f : HahnSeries ℕ R} {n : ℕ} : PowerSeries.coeff R n (toPowerSeries f) = f.coeff n := PowerSeries.coeff_mk _ _ theorem coeff_toPowerSeries_symm {f : PowerSeries R} {n : ℕ} : (HahnSeries.toPowerSeries.symm f).coeff n = PowerSeries.coeff R n f := rfl variable (Γ R) [Semiring Γ] [PartialOrder Γ] [IsStrictOrderedRing Γ] /-- Casts a power series as a Hahn series with coefficients from a `StrictOrderedSemiring`. -/ def ofPowerSeries : PowerSeries R →+* HahnSeries Γ R := (HahnSeries.embDomainRingHom (Nat.castAddMonoidHom Γ) Nat.strictMono_cast.injective fun _ _ => Nat.cast_le).comp (RingEquiv.toRingHom toPowerSeries.symm) variable {Γ} {R} theorem ofPowerSeries_injective : Function.Injective (ofPowerSeries Γ R) := embDomain_injective.comp toPowerSeries.symm.injective /-@[simp] Porting note: removing simp. RHS is more complicated and it makes linter failures elsewhere -/ theorem ofPowerSeries_apply (x : PowerSeries R) : ofPowerSeries Γ R x = HahnSeries.embDomain ⟨⟨((↑) : ℕ → Γ), Nat.strictMono_cast.injective⟩, by simp only [Function.Embedding.coeFn_mk] exact Nat.cast_le⟩ (toPowerSeries.symm x) := rfl theorem ofPowerSeries_apply_coeff (x : PowerSeries R) (n : ℕ) : (ofPowerSeries Γ R x).coeff n = PowerSeries.coeff R n x := by simp [ofPowerSeries_apply] @[simp] theorem ofPowerSeries_C (r : R) : ofPowerSeries Γ R (PowerSeries.C R r) = HahnSeries.C r := by ext n simp only [ofPowerSeries_apply, C, RingHom.coe_mk, MonoidHom.coe_mk, OneHom.coe_mk, coeff_single] split_ifs with hn · subst hn convert embDomain_coeff (a := 0) <;> simp · rw [embDomain_notin_image_support] simp only [not_exists, Set.mem_image, toPowerSeries_symm_apply_coeff, mem_support, PowerSeries.coeff_C] intro simp +contextual [Ne.symm hn] @[simp] theorem ofPowerSeries_X : ofPowerSeries Γ R PowerSeries.X = single 1 1 := by ext n simp only [coeff_single, ofPowerSeries_apply] split_ifs with hn · rw [hn] convert embDomain_coeff (a := 1) <;> simp · rw [embDomain_notin_image_support] simp only [not_exists, Set.mem_image, toPowerSeries_symm_apply_coeff, mem_support, PowerSeries.coeff_X] intro simp +contextual [Ne.symm hn] theorem ofPowerSeries_X_pow {R} [Semiring R] (n : ℕ) : ofPowerSeries Γ R (PowerSeries.X ^ n) = single (n : Γ) 1 := by simp -- Lemmas about converting hahn_series over fintype to and from mv_power_series /-- The ring `HahnSeries (σ →₀ ℕ) R` is isomorphic to `MvPowerSeries σ R` for a `Finite` `σ`. We take the index set of the hahn series to be `Finsupp` rather than `pi`, even though we assume `Finite σ` as this is more natural for alignment with `MvPowerSeries`. After importing `Mathlib/Algebra/Order/Pi.lean` the ring `HahnSeries (σ → ℕ) R` could be constructed instead. -/ @[simps] def toMvPowerSeries {σ : Type*} [Finite σ] : HahnSeries (σ →₀ ℕ) R ≃+* MvPowerSeries σ R where toFun f := f.coeff invFun f := ⟨(f : (σ →₀ ℕ) → R), Finsupp.isPWO _⟩ left_inv f := by ext simp right_inv f := by ext simp map_add' f g := by ext simp map_mul' f g := by ext n classical change (f * g).coeff n = _ simp_rw [coeff_mul] refine (sum_filter_ne_zero _).symm.trans <| (sum_congr ?_ fun _ _ ↦ rfl).trans <| sum_filter_ne_zero _ ext m simp only [and_congr_left_iff, mem_addAntidiagonal, mem_filter, mem_support, Finset.mem_antidiagonal] rintro h rw [and_iff_right (left_ne_zero_of_mul h), and_iff_right (right_ne_zero_of_mul h)] variable {σ : Type*} [Finite σ] -- TODO : generalize to all (?) rings of Hahn Series /-- If R has no zero divisors and `σ` is finite, then `HahnSeries (σ →₀ ℕ) R` has no zero divisors -/ instance [NoZeroDivisors R] : NoZeroDivisors (HahnSeries (σ →₀ ℕ) R) := toMvPowerSeries.toMulEquiv.noZeroDivisors (A := HahnSeries (σ →₀ ℕ) R) (MvPowerSeries σ R) theorem coeff_toMvPowerSeries {f : HahnSeries (σ →₀ ℕ) R} {n : σ →₀ ℕ} : MvPowerSeries.coeff R n (toMvPowerSeries f) = f.coeff n := rfl theorem coeff_toMvPowerSeries_symm {f : MvPowerSeries σ R} {n : σ →₀ ℕ} : (HahnSeries.toMvPowerSeries.symm f).coeff n = MvPowerSeries.coeff R n f := rfl end Semiring section Algebra variable (R) [CommSemiring R] {A : Type*} [Semiring A] [Algebra R A] /-- The `R`-algebra `HahnSeries ℕ A` is isomorphic to `PowerSeries A`. -/ @[simps!] def toPowerSeriesAlg : HahnSeries ℕ A ≃ₐ[R] PowerSeries A := { toPowerSeries with commutes' := fun r => by ext n cases n <;> simp [algebraMap_apply, PowerSeries.algebraMap_apply] } variable (Γ) [Semiring Γ] [PartialOrder Γ] [IsStrictOrderedRing Γ] /-- Casting a power series as a Hahn series with coefficients from a `StrictOrderedSemiring` is an algebra homomorphism. -/ @[simps!] def ofPowerSeriesAlg : PowerSeries A →ₐ[R] HahnSeries Γ A := (HahnSeries.embDomainAlgHom (Nat.castAddMonoidHom Γ) Nat.strictMono_cast.injective fun _ _ => Nat.cast_le).comp (AlgEquiv.toAlgHom (toPowerSeriesAlg R).symm) instance powerSeriesAlgebra {S : Type*} [CommSemiring S] [Algebra S (PowerSeries R)] : Algebra S (HahnSeries Γ R) := RingHom.toAlgebra <| (ofPowerSeries Γ R).comp (algebraMap S (PowerSeries R)) variable {R} variable {S : Type*} [CommSemiring S] [Algebra S (PowerSeries R)] theorem algebraMap_apply' (x : S) : algebraMap S (HahnSeries Γ R) x = ofPowerSeries Γ R (algebraMap S (PowerSeries R) x) := rfl @[simp] theorem _root_.Polynomial.algebraMap_hahnSeries_apply (f : R[X]) : algebraMap R[X] (HahnSeries Γ R) f = ofPowerSeries Γ R f := rfl theorem _root_.Polynomial.algebraMap_hahnSeries_injective : Function.Injective (algebraMap R[X] (HahnSeries Γ R)) := ofPowerSeries_injective.comp (Polynomial.coe_injective R) end Algebra end HahnSeries
Center.lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Jireh Loreaux -/ import Mathlib.Algebra.Group.Center import Mathlib.Algebra.Group.Subsemigroup.Defs /-! # Centers of semigroups, as subsemigroups. ## Main definitions * `Subsemigroup.center`: the center of a semigroup * `AddSubsemigroup.center`: the center of an additive semigroup We provide `Submonoid.center`, `AddSubmonoid.center`, `Subgroup.center`, `AddSubgroup.center`, `Subsemiring.center`, and `Subring.center` in other files. ## References * [Cabrera García and Rodríguez Palacios, Non-associative normed algebras. Volume 1] [cabreragarciarodriguezpalacios2014] -/ assert_not_exists RelIso Finset /-! ### `Set.center` as a `Subsemigroup`. -/ variable (M) namespace Subsemigroup section Mul variable [Mul M] /-- The center of a semigroup `M` is the set of elements that commute with everything in `M` -/ @[to_additive /-- The center of an additive semigroup `M` is the set of elements that commute with everything in `M` -/] def center : Subsemigroup M where carrier := Set.center M mul_mem' := Set.mul_mem_center -- Porting note: `coe_center` is now redundant variable {M} /-- The center of a magma is commutative and associative. -/ @[to_additive /-- The center of an additive magma is commutative and associative. -/] instance center.commSemigroup : CommSemigroup (center M) where mul_assoc _ b _ := Subtype.ext <| b.2.mid_assoc _ _ mul_comm a _ := Subtype.ext <| a.2.comm _ end Mul section Semigroup variable {M} [Semigroup M] @[to_additive] theorem mem_center_iff {z : M} : z ∈ center M ↔ ∀ g, g * z = z * g := by rw [← Semigroup.mem_center_iff] exact Iff.rfl @[to_additive] instance decidableMemCenter (a) [Decidable <| ∀ b : M, b * a = a * b] : Decidable (a ∈ center M) := decidable_of_iff' _ Semigroup.mem_center_iff end Semigroup section CommSemigroup variable [CommSemigroup M] @[to_additive (attr := simp)] theorem center_eq_top : center M = ⊤ := SetLike.coe_injective (Set.center_eq_univ M) end CommSemigroup end Subsemigroup
Basic.lean
/- Copyright (c) 2024 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import Mathlib.Algebra.Order.Star.Prod import Mathlib.Analysis.SpecialFunctions.Pow.Real import Mathlib.Analysis.CStarAlgebra.ContinuousFunctionalCalculus.Instances import Mathlib.Analysis.CStarAlgebra.ContinuousFunctionalCalculus.Unique import Mathlib.Analysis.CStarAlgebra.ContinuousFunctionalCalculus.Pi import Mathlib.Analysis.SpecialFunctions.Pow.Continuity import Mathlib.Topology.ContinuousMap.ContinuousSqrt /-! # Real powers defined via the continuous functional calculus This file defines real powers via the continuous functional calculus (CFC) and builds its API. This allows one to take real powers of matrices, operators, elements of a C⋆-algebra, etc. The square root is also defined via the non-unital CFC. ## Main declarations + `CFC.nnrpow`: the `ℝ≥0` power function based on the non-unital CFC, i.e. `cfcₙ NNReal.rpow` composed with `(↑) : ℝ≥0 → ℝ`. + `CFC.sqrt`: the square root function based on the non-unital CFC, i.e. `cfcₙ NNReal.sqrt` + `CFC.rpow`: the real power function based on the unital CFC, i.e. `cfc NNReal.rpow` ## Implementation notes We define two separate versions `CFC.nnrpow` and `CFC.rpow` due to what happens at 0. Since `NNReal.rpow 0 0 = 1`, this means that this function does not map zero to zero when the exponent is zero, and hence `CFC.nnrpow a 0 = 0` whereas `CFC.rpow a 0 = 1`. Note that the non-unital version only makes sense for nonnegative exponents, and hence we define it such that the exponent is in `ℝ≥0`. ## Notation + We define a `Pow A ℝ` instance for `CFC.rpow`, i.e `a ^ y` with `A` an operator and `y : ℝ` works as expected. Likewise, we define a `Pow A ℝ≥0` instance for `CFC.nnrpow`. Note that these are low-priority instances, in order to avoid overriding instances such as `Pow ℝ ℝ`, `Pow (A × B) ℝ` or `Pow (∀ i, A i) ℝ`. ## TODO + Relate these to the log and exp functions + Lemmas about how these functions interact with commuting `a` and `b`. + Prove the order properties (operator monotonicity and concavity/convexity) -/ open scoped NNReal namespace NNReal /-- Taking a nonnegative power of a nonnegative number. This is defined as a standalone definition in order to speed up automation such as `cfc_cont_tac`. -/ noncomputable abbrev nnrpow (a : ℝ≥0) (b : ℝ≥0) : ℝ≥0 := a ^ (b : ℝ) @[simp] lemma nnrpow_def (a b : ℝ≥0) : nnrpow a b = a ^ (b : ℝ) := rfl @[fun_prop] lemma continuous_nnrpow_const (y : ℝ≥0) : Continuous (nnrpow · y) := continuous_rpow_const zero_le_coe /- This is a "redeclaration" of the attribute to speed up the proofs in this file. -/ attribute [fun_prop] continuousOn_rpow_const lemma monotone_nnrpow_const (y : ℝ≥0) : Monotone (nnrpow · y) := monotone_rpow_of_nonneg zero_le_coe end NNReal namespace CFC section NonUnital variable {A : Type*} [PartialOrder A] [NonUnitalRing A] [TopologicalSpace A] [StarRing A] [Module ℝ A] [SMulCommClass ℝ A A] [IsScalarTower ℝ A A] [StarOrderedRing A] [NonUnitalContinuousFunctionalCalculus ℝ A IsSelfAdjoint] [NonnegSpectrumClass ℝ A] /- ## `nnrpow` -/ /-- Real powers of operators, based on the non-unital continuous functional calculus. -/ noncomputable def nnrpow (a : A) (y : ℝ≥0) : A := cfcₙ (NNReal.nnrpow · y) a /-- Enable `a ^ y` notation for `CFC.nnrpow`. This is a low-priority instance to make sure it does not take priority over other instances when they are available. -/ noncomputable instance (priority := 100) : Pow A ℝ≥0 where pow a y := nnrpow a y @[simp] lemma nnrpow_eq_pow {a : A} {y : ℝ≥0} : nnrpow a y = a ^ y := rfl @[simp] lemma nnrpow_nonneg {a : A} {x : ℝ≥0} : 0 ≤ a ^ x := cfcₙ_predicate _ a lemma nnrpow_def {a : A} {y : ℝ≥0} : a ^ y = cfcₙ (NNReal.nnrpow · y) a := rfl lemma nnrpow_add {a : A} {x y : ℝ≥0} (hx : 0 < x) (hy : 0 < y) : a ^ (x + y) = a ^ x * a ^ y := by simp only [nnrpow_def] rw [← cfcₙ_mul _ _ a] congr! 2 with z exact mod_cast z.rpow_add' <| ne_of_gt (add_pos hx hy) @[simp] lemma nnrpow_zero {a : A} : a ^ (0 : ℝ≥0) = 0 := by simp [nnrpow_def, cfcₙ_apply_of_not_map_zero] lemma nnrpow_one (a : A) (ha : 0 ≤ a := by cfc_tac) : a ^ (1 : ℝ≥0) = a := by simp only [nnrpow_def, NNReal.nnrpow_def, NNReal.coe_one, NNReal.rpow_one] change cfcₙ (id : ℝ≥0 → ℝ≥0) a = a rw [cfcₙ_id ℝ≥0 a] lemma nnrpow_two (a : A) (ha : 0 ≤ a := by cfc_tac) : a ^ (2 : ℝ≥0) = a * a := by simp only [nnrpow_def, NNReal.nnrpow_def, NNReal.coe_ofNat, NNReal.rpow_ofNat, pow_two] change cfcₙ (fun z : ℝ≥0 => id z * id z) a = a * a rw [cfcₙ_mul id id a, cfcₙ_id ℝ≥0 a] lemma nnrpow_three (a : A) (ha : 0 ≤ a := by cfc_tac) : a ^ (3 : ℝ≥0) = a * a * a := by simp only [nnrpow_def, NNReal.nnrpow_def, NNReal.coe_ofNat, NNReal.rpow_ofNat, pow_three] change cfcₙ (fun z : ℝ≥0 => id z * (id z * id z)) a = a * a * a rw [cfcₙ_mul id _ a, cfcₙ_mul id _ a, ← mul_assoc, cfcₙ_id ℝ≥0 a] @[simp] lemma zero_nnrpow {x : ℝ≥0} : (0 : A) ^ x = 0 := by simp [nnrpow_def] section Unique variable [IsTopologicalRing A] [T2Space A] @[simp] lemma nnrpow_nnrpow {a : A} {x y : ℝ≥0} : (a ^ x) ^ y = a ^ (x * y) := by by_cases ha : 0 ≤ a case pos => obtain (rfl | hx) := eq_zero_or_pos x <;> obtain (rfl | hy) := eq_zero_or_pos y all_goals try simp simp only [nnrpow_def] rw [← cfcₙ_comp _ _ a] congr! 2 with u ext simp [Real.rpow_mul] case neg => simp [nnrpow_def, cfcₙ_apply_of_not_predicate a ha] lemma nnrpow_nnrpow_inv (a : A) {x : ℝ≥0} (hx : x ≠ 0) (ha : 0 ≤ a := by cfc_tac) : (a ^ x) ^ x⁻¹ = a := by simp [mul_inv_cancel₀ hx, nnrpow_one _ ha] lemma nnrpow_inv_nnrpow (a : A) {x : ℝ≥0} (hx : x ≠ 0) (ha : 0 ≤ a := by cfc_tac) : (a ^ x⁻¹) ^ x = a := by simp [inv_mul_cancel₀ hx, nnrpow_one _ ha] lemma nnrpow_inv_eq (a b : A) {x : ℝ≥0} (hx : x ≠ 0) (ha : 0 ≤ a := by cfc_tac) (hb : 0 ≤ b := by cfc_tac) : a ^ x⁻¹ = b ↔ b ^ x = a := ⟨fun h ↦ nnrpow_inv_nnrpow a hx ▸ congr($(h) ^ x).symm, fun h ↦ nnrpow_nnrpow_inv b hx ▸ congr($(h) ^ x⁻¹).symm⟩ section prod variable {B : Type*} [PartialOrder B] [NonUnitalRing B] [TopologicalSpace B] [StarRing B] [Module ℝ B] [SMulCommClass ℝ B B] [IsScalarTower ℝ B B] [NonUnitalContinuousFunctionalCalculus ℝ B IsSelfAdjoint] [NonUnitalContinuousFunctionalCalculus ℝ (A × B) IsSelfAdjoint] [IsTopologicalRing B] [T2Space B] [NonnegSpectrumClass ℝ B] [NonnegSpectrumClass ℝ (A × B)] [StarOrderedRing B] /- Note that there is higher-priority instance of `Pow (A × B) ℝ≥0` coming from the `Pow` instance for products, hence the direct use of `nnrpow` here. -/ lemma nnrpow_map_prod {a : A} {b : B} {x : ℝ≥0} (ha : 0 ≤ a := by cfc_tac) (hb : 0 ≤ b := by cfc_tac) : nnrpow (a, b) x = (a ^ x, b ^ x) := by simp only [nnrpow_def] unfold nnrpow refine cfcₙ_map_prod (S := ℝ) _ a b (by fun_prop) ?_ rw [Prod.le_def] constructor <;> simp [ha, hb] lemma nnrpow_eq_nnrpow_prod {a : A} {b : B} {x : ℝ≥0} (ha : 0 ≤ a := by cfc_tac) (hb : 0 ≤ b := by cfc_tac) : nnrpow (a, b) x = (a, b) ^ x := nnrpow_map_prod end prod section pi variable {ι : Type*} {C : ι → Type*} [∀ i, PartialOrder (C i)] [∀ i, NonUnitalRing (C i)] [∀ i, TopologicalSpace (C i)] [∀ i, StarRing (C i)] [∀ i, StarOrderedRing (C i)] [StarOrderedRing (∀ i, C i)] [∀ i, Module ℝ (C i)] [∀ i, SMulCommClass ℝ (C i) (C i)] [∀ i, IsScalarTower ℝ (C i) (C i)] [∀ i, NonUnitalContinuousFunctionalCalculus ℝ (C i) IsSelfAdjoint] [NonUnitalContinuousFunctionalCalculus ℝ (∀ i, C i) IsSelfAdjoint] [∀ i, IsTopologicalRing (C i)] [∀ i, T2Space (C i)] [NonnegSpectrumClass ℝ (∀ i, C i)] [∀ i, NonnegSpectrumClass ℝ (C i)] /- Note that there is higher-priority instance of `Pow (∀ i, C i) ℝ≥0` coming from the `Pow` instance for pi types, hence the direct use of `nnrpow` here. -/ lemma nnrpow_map_pi {c : ∀ i, C i} {x : ℝ≥0} (hc : ∀ i, 0 ≤ c i := by cfc_tac) : nnrpow c x = fun i => (c i) ^ x := by simp only [nnrpow_def] unfold nnrpow exact cfcₙ_map_pi (S := ℝ) _ c lemma nnrpow_eq_nnrpow_pi {c : ∀ i, C i} {x : ℝ≥0} (hc : ∀ i, 0 ≤ c i := by cfc_tac) : nnrpow c x = c ^ x := nnrpow_map_pi end pi end Unique /- ## `sqrt` -/ section sqrt /-- Square roots of operators, based on the non-unital continuous functional calculus. -/ noncomputable def sqrt (a : A) : A := cfcₙ NNReal.sqrt a @[simp] lemma sqrt_nonneg (a : A) : 0 ≤ sqrt a := cfcₙ_predicate _ a lemma sqrt_eq_nnrpow (a : A) : sqrt a = a ^ (1 / 2 : ℝ≥0) := by simp only [sqrt] congr ext exact_mod_cast NNReal.sqrt_eq_rpow _ @[simp] lemma sqrt_zero : sqrt (0 : A) = 0 := by simp [sqrt] variable [IsTopologicalRing A] [T2Space A] @[simp] lemma nnrpow_sqrt {a : A} {x : ℝ≥0} : (sqrt a) ^ x = a ^ (x / 2) := by rw [sqrt_eq_nnrpow, nnrpow_nnrpow, one_div_mul_eq_div 2 x] lemma nnrpow_sqrt_two (a : A) (ha : 0 ≤ a := by cfc_tac) : (sqrt a) ^ (2 : ℝ≥0) = a := by simp only [nnrpow_sqrt, ne_eq, OfNat.ofNat_ne_zero, not_false_eq_true, div_self] rw [nnrpow_one a] lemma sqrt_mul_sqrt_self (a : A) (ha : 0 ≤ a := by cfc_tac) : sqrt a * sqrt a = a := by rw [← nnrpow_two _, nnrpow_sqrt_two _] @[simp] lemma sqrt_nnrpow {a : A} {x : ℝ≥0} : sqrt (a ^ x) = a ^ (x / 2) := by simp [sqrt_eq_nnrpow, div_eq_mul_inv] lemma sqrt_nnrpow_two (a : A) (ha : 0 ≤ a := by cfc_tac) : sqrt (a ^ (2 : ℝ≥0)) = a := by simp only [sqrt_nnrpow, ne_eq, OfNat.ofNat_ne_zero, not_false_eq_true, div_self] rw [nnrpow_one _] lemma sqrt_mul_self (a : A) (ha : 0 ≤ a := by cfc_tac) : sqrt (a * a) = a := by rw [← nnrpow_two _, sqrt_nnrpow_two _] lemma mul_self_eq {a b : A} (h : sqrt a = b) (ha : 0 ≤ a := by cfc_tac) : b * b = a := h ▸ sqrt_mul_sqrt_self _ ha lemma sqrt_unique {a b : A} (h : b * b = a) (hb : 0 ≤ b := by cfc_tac) : sqrt a = b := h ▸ sqrt_mul_self b lemma sqrt_eq_iff (a b : A) (ha : 0 ≤ a := by cfc_tac) (hb : 0 ≤ b := by cfc_tac) : sqrt a = b ↔ b * b = a := ⟨(mul_self_eq ·), (sqrt_unique ·)⟩ lemma sqrt_eq_zero_iff (a : A) (ha : 0 ≤ a := by cfc_tac) : sqrt a = 0 ↔ a = 0 := by rw [sqrt_eq_iff a _, mul_zero, eq_comm] /-- Note that the hypothesis `0 ≤ a` is necessary because the continuous functional calculi over `ℝ≥0` (for the left-hand side) and `ℝ` (for the right-hand side) use different predicates (i.e., `(0 ≤ ·)` versus `IsSelfAdjoint`). Consequently, if `a` is selfadjoint but not nonnegative, then the left-hand side is zero, but the right-hand side is (provably equal to) `CFC.sqrt a⁺`. -/ lemma sqrt_eq_real_sqrt (a : A) (ha : 0 ≤ a := by cfc_tac) : CFC.sqrt a = cfcₙ Real.sqrt a := by suffices cfcₙ (fun x : ℝ ↦ √x * √x) a = cfcₙ (fun x : ℝ ↦ x) a by rwa [cfcₙ_mul .., cfcₙ_id' .., ← sqrt_eq_iff _ (hb := cfcₙ_nonneg (fun x _ ↦ Real.sqrt_nonneg x))] at this exact cfcₙ_congr fun x hx ↦ Real.mul_self_sqrt <| quasispectrum_nonneg_of_nonneg a ha x hx section prod variable {B : Type*} [PartialOrder B] [NonUnitalRing B] [TopologicalSpace B] [StarRing B] [Module ℝ B] [SMulCommClass ℝ B B] [IsScalarTower ℝ B B] [StarOrderedRing B] [NonUnitalContinuousFunctionalCalculus ℝ B IsSelfAdjoint] [NonUnitalContinuousFunctionalCalculus ℝ (A × B) IsSelfAdjoint] [IsTopologicalRing B] [T2Space B] [NonnegSpectrumClass ℝ B] [NonnegSpectrumClass ℝ (A × B)] lemma sqrt_map_prod {a : A} {b : B} (ha : 0 ≤ a := by cfc_tac) (hb : 0 ≤ b := by cfc_tac) : sqrt (a, b) = (sqrt a, sqrt b) := by simp only [sqrt_eq_nnrpow] exact nnrpow_map_prod end prod section pi variable {ι : Type*} {C : ι → Type*} [∀ i, PartialOrder (C i)] [∀ i, NonUnitalRing (C i)] [∀ i, TopologicalSpace (C i)] [∀ i, StarRing (C i)] [∀ i, StarOrderedRing (C i)] [StarOrderedRing (∀ i, C i)] [∀ i, Module ℝ (C i)] [∀ i, SMulCommClass ℝ (C i) (C i)] [∀ i, IsScalarTower ℝ (C i) (C i)] [∀ i, NonUnitalContinuousFunctionalCalculus ℝ (C i) IsSelfAdjoint] [NonUnitalContinuousFunctionalCalculus ℝ (∀ i, C i) IsSelfAdjoint] [∀ i, IsTopologicalRing (C i)] [∀ i, T2Space (C i)] [NonnegSpectrumClass ℝ (∀ i, C i)] [∀ i, NonnegSpectrumClass ℝ (C i)] lemma sqrt_map_pi {c : ∀ i, C i} (hc : ∀ i, 0 ≤ c i := by cfc_tac) : sqrt c = fun i => sqrt (c i) := by simp only [sqrt_eq_nnrpow] exact nnrpow_map_pi end pi end sqrt end NonUnital section Unital variable {A : Type*} [PartialOrder A] [Ring A] [StarRing A] [TopologicalSpace A] [StarOrderedRing A] [Algebra ℝ A] [ContinuousFunctionalCalculus ℝ A IsSelfAdjoint] [NonnegSpectrumClass ℝ A] /- ## `rpow` -/ /-- Real powers of operators, based on the unital continuous functional calculus. -/ noncomputable def rpow (a : A) (y : ℝ) : A := cfc (fun x : ℝ≥0 => x ^ y) a /-- Enable `a ^ y` notation for `CFC.rpow`. This is a low-priority instance to make sure it does not take priority over other instances when they are available (such as `Pow ℝ ℝ`). -/ noncomputable instance (priority := 100) : Pow A ℝ where pow a y := rpow a y @[simp] lemma rpow_eq_pow {a : A} {y : ℝ} : rpow a y = a ^ y := rfl @[simp] lemma rpow_nonneg {a : A} {y : ℝ} : 0 ≤ a ^ y := cfc_predicate _ a lemma rpow_def {a : A} {y : ℝ} : a ^ y = cfc (fun x : ℝ≥0 => x ^ y) a := rfl lemma rpow_one (a : A) (ha : 0 ≤ a := by cfc_tac) : a ^ (1 : ℝ) = a := by simp only [rpow_def, NNReal.rpow_one, cfc_id' ℝ≥0 a] @[simp] lemma one_rpow {x : ℝ} : (1 : A) ^ x = (1 : A) := by simp [rpow_def] lemma rpow_zero (a : A) (ha : 0 ≤ a := by cfc_tac) : a ^ (0 : ℝ) = 1 := by simp [rpow_def, cfc_const_one ℝ≥0 a] lemma zero_rpow {x : ℝ} (hx : x ≠ 0) : rpow (0 : A) x = 0 := by simp [rpow, NNReal.zero_rpow hx] lemma rpow_natCast (a : A) (n : ℕ) (ha : 0 ≤ a := by cfc_tac) : a ^ (n : ℝ) = a ^ n := by rw [← cfc_pow_id (R := ℝ≥0) a n, rpow_def] congr simp @[simp] lemma rpow_algebraMap {x : ℝ≥0} {y : ℝ} : (algebraMap ℝ≥0 A x) ^ y = algebraMap ℝ≥0 A (x ^ y) := by rw [rpow_def, cfc_algebraMap ..] lemma rpow_add {a : A} {x y : ℝ} (ha : IsUnit a) : a ^ (x + y) = a ^ x * a ^ y := by have ha' : 0 ∉ spectrum ℝ≥0 a := spectrum.zero_notMem _ ha simp only [rpow_def] rw [← cfc_mul _ _ a] refine cfc_congr ?_ intro z hz have : z ≠ 0 := by aesop simp [NNReal.rpow_add this _ _] lemma rpow_rpow [IsTopologicalRing A] [T2Space A] (a : A) (x y : ℝ) (ha₁ : IsUnit a) (hx : x ≠ 0) (ha₂ : 0 ≤ a := by cfc_tac) : (a ^ x) ^ y = a ^ (x * y) := by have ha₁' : 0 ∉ spectrum ℝ≥0 a := spectrum.zero_notMem _ ha₁ simp only [rpow_def] rw [← cfc_comp _ _ a ha₂] refine cfc_congr fun _ _ => ?_ simp [NNReal.rpow_mul] lemma rpow_rpow_inv [IsTopologicalRing A] [T2Space A] (a : A) (x : ℝ) (ha₁ : IsUnit a) (hx : x ≠ 0) (ha₂ : 0 ≤ a := by cfc_tac) : (a ^ x) ^ x⁻¹ = a := by rw [rpow_rpow a x x⁻¹ ha₁ hx ha₂, mul_inv_cancel₀ hx, rpow_one a ha₂] lemma rpow_inv_rpow [IsTopologicalRing A] [T2Space A] (a : A) (x : ℝ) (ha₁ : IsUnit a) (hx : x ≠ 0) (ha₂ : 0 ≤ a := by cfc_tac) : (a ^ x⁻¹) ^ x = a := by simpa using rpow_rpow_inv a x⁻¹ ha₁ (inv_ne_zero hx) ha₂ lemma rpow_rpow_of_exponent_nonneg [IsTopologicalRing A] [T2Space A] (a : A) (x y : ℝ) (hx : 0 ≤ x) (hy : 0 ≤ y) (ha₂ : 0 ≤ a := by cfc_tac) : (a ^ x) ^ y = a ^ (x * y) := by simp only [rpow_def] rw [← cfc_comp _ _ a] refine cfc_congr fun _ _ => ?_ simp [NNReal.rpow_mul] lemma rpow_mul_rpow_neg {a : A} (x : ℝ) (ha : IsUnit a) (ha' : 0 ≤ a := by cfc_tac) : a ^ x * a ^ (-x) = 1 := by rw [← rpow_add ha, add_neg_cancel, rpow_zero a] lemma rpow_neg_mul_rpow {a : A} (x : ℝ) (ha : IsUnit a) (ha' : 0 ≤ a := by cfc_tac) : a ^ (-x) * a ^ x = 1 := by rw [← rpow_add ha, neg_add_cancel, rpow_zero a] lemma rpow_neg_one_eq_inv (a : Aˣ) (ha : (0 : A) ≤ a := by cfc_tac) : a ^ (-1 : ℝ) = (↑a⁻¹ : A) := by refine a.inv_eq_of_mul_eq_one_left ?_ |>.symm simpa [rpow_one (a : A)] using rpow_neg_mul_rpow 1 a.isUnit lemma rpow_neg_one_eq_cfc_inv {A : Type*} [PartialOrder A] [NormedRing A] [StarRing A] [StarOrderedRing A] [NormedAlgebra ℝ A] [NonnegSpectrumClass ℝ A] [ContinuousFunctionalCalculus ℝ A IsSelfAdjoint] (a : A) : a ^ (-1 : ℝ) = cfc (·⁻¹ : ℝ≥0 → ℝ≥0) a := cfc_congr fun x _ ↦ NNReal.rpow_neg_one x lemma rpow_neg [IsTopologicalRing A] [T2Space A] (a : Aˣ) (x : ℝ) (ha' : (0 : A) ≤ a := by cfc_tac) : (a : A) ^ (-x) = (↑a⁻¹ : A) ^ x := by suffices h₁ : ContinuousOn (fun z ↦ z ^ x) (Inv.inv '' (spectrum ℝ≥0 (a : A))) by rw [← cfc_inv_id (R := ℝ≥0) a, rpow_def, rpow_def, ← cfc_comp' (fun z => z ^ x) (Inv.inv : ℝ≥0 → ℝ≥0) (a : A) h₁] refine cfc_congr fun _ _ => ?_ simp [NNReal.rpow_neg, NNReal.inv_rpow] refine NNReal.continuousOn_rpow_const (.inl ?_) rintro ⟨z, hz, hz'⟩ exact spectrum.zero_notMem ℝ≥0 a.isUnit <| inv_eq_zero.mp hz' ▸ hz lemma rpow_intCast (a : Aˣ) (n : ℤ) (ha : (0 : A) ≤ a := by cfc_tac) : (a : A) ^ (n : ℝ) = (↑(a ^ n) : A) := by rw [← cfc_zpow (R := ℝ≥0) a n, rpow_def] refine cfc_congr fun _ _ => ?_ simp /-- `a ^ x` bundled as an element of `Aˣ` for `a : Aˣ`. -/ @[simps] noncomputable def _root_.Units.cfcRpow (a : Aˣ) (x : ℝ) (ha : (0 : A) ≤ a := by cfc_tac) : Aˣ := ⟨(a : A) ^ x, (a : A) ^ (-x), rpow_mul_rpow_neg x (by simp), rpow_neg_mul_rpow x (by simp)⟩ @[aesop safe apply] lemma _root_.IsUnit.cfcRpow {a : A} (ha : IsUnit a) (x : ℝ) (ha_nonneg : 0 ≤ a := by cfc_tac) : IsUnit (a ^ x) := ha.unit.cfcRpow x |>.isUnit lemma spectrum_rpow (a : A) (x : ℝ) (h : ContinuousOn (· ^ x) (spectrum ℝ≥0 a) := by cfc_cont_tac) (ha : 0 ≤ a := by cfc_tac) : spectrum ℝ≥0 (a ^ x) = (· ^ x) '' spectrum ℝ≥0 a := cfc_map_spectrum (· ^ x : ℝ≥0 → ℝ≥0) a ha h lemma isUnit_rpow_iff (a : A) (y : ℝ) (hy : y ≠ 0) (ha : 0 ≤ a := by cfc_tac) : IsUnit (a ^ y) ↔ IsUnit a := by nontriviality A refine ⟨fun h => ?_, fun h => h.cfcRpow y ha⟩ rw [rpow_def] at h by_cases hf : ContinuousOn (fun x : ℝ≥0 => x ^ y) (spectrum ℝ≥0 a) · rw [isUnit_cfc_iff _ a hf] at h refine spectrum.isUnit_of_zero_notMem ℝ≥0 ?_ intro h0 specialize h 0 h0 simp only [ne_eq, NNReal.rpow_eq_zero_iff, true_and, Decidable.not_not] at h exact hy h · rw [cfc_apply_of_not_continuousOn a hf] at h exact False.elim <| not_isUnit_zero h section prod variable [IsTopologicalRing A] [T2Space A] variable {B : Type*} [PartialOrder B] [Ring B] [StarRing B] [TopologicalSpace B] [StarOrderedRing B] [Algebra ℝ B] [ContinuousFunctionalCalculus ℝ B IsSelfAdjoint] [ContinuousFunctionalCalculus ℝ (A × B) IsSelfAdjoint] [IsTopologicalRing B] [T2Space B] [StarOrderedRing (A × B)] [NonnegSpectrumClass ℝ B] [NonnegSpectrumClass ℝ (A × B)] /- Note that there is higher-priority instance of `Pow (A × B) ℝ` coming from the `Pow` instance for products, hence the direct use of `rpow` here. -/ lemma rpow_map_prod {a : A} {b : B} {x : ℝ} (ha : IsUnit a) (hb : IsUnit b) (ha' : 0 ≤ a := by cfc_tac) (hb' : 0 ≤ b := by cfc_tac) : rpow (a, b) x = (a ^ x, b ^ x) := by have ha'' : 0 ∉ spectrum ℝ≥0 a := spectrum.zero_notMem _ ha have hb'' : 0 ∉ spectrum ℝ≥0 b := spectrum.zero_notMem _ hb simp only [rpow_def] unfold rpow refine cfc_map_prod (R := ℝ≥0) (S := ℝ) _ a b (by cfc_cont_tac) ?_ rw [Prod.le_def] constructor <;> simp [ha', hb'] lemma rpow_eq_rpow_prod {a : A} {b : B} {x : ℝ} (ha : IsUnit a) (hb : IsUnit b) (ha' : 0 ≤ a := by cfc_tac) (hb' : 0 ≤ b := by cfc_tac) : rpow (a, b) x = (a, b) ^ x := rpow_map_prod ha hb @[deprecated (since := "2025-05-13")] alias rpow_eq_rpow_rpod := rpow_eq_rpow_prod end prod section pi variable [IsTopologicalRing A] [T2Space A] variable {ι : Type*} {C : ι → Type*} [∀ i, PartialOrder (C i)] [∀ i, Ring (C i)] [∀ i, StarRing (C i)] [∀ i, TopologicalSpace (C i)] [∀ i, StarOrderedRing (C i)] [StarOrderedRing (∀ i, C i)] [∀ i, Algebra ℝ (C i)] [∀ i, ContinuousFunctionalCalculus ℝ (C i) IsSelfAdjoint] [ContinuousFunctionalCalculus ℝ (∀ i, C i) IsSelfAdjoint] [∀ i, IsTopologicalRing (C i)] [∀ i, T2Space (C i)] [NonnegSpectrumClass ℝ (∀ i, C i)] [∀ i, NonnegSpectrumClass ℝ (C i)] /- Note that there is a higher-priority instance of `Pow (∀ i, B i) ℝ` coming from the `Pow` instance for pi types, hence the direct use of `rpow` here. -/ lemma rpow_map_pi {c : ∀ i, C i} {x : ℝ} (hc : ∀ i, IsUnit (c i)) (hc' : ∀ i, 0 ≤ c i := by cfc_tac) : rpow c x = fun i => (c i) ^ x := by have hc'' : ∀ i, 0 ∉ spectrum ℝ≥0 (c i) := fun i => spectrum.zero_notMem _ (hc i) simp only [rpow_def] unfold rpow exact cfc_map_pi (S := ℝ) _ c lemma rpow_eq_rpow_pi {c : ∀ i, C i} {x : ℝ} (hc : ∀ i, IsUnit (c i)) (hc' : ∀ i, 0 ≤ c i := by cfc_tac) : rpow c x = c ^ x := rpow_map_pi hc end pi section unital_vs_nonunital variable [IsTopologicalRing A] [T2Space A] -- provides instance `ContinuousFunctionalCalculus.compactSpace_spectrum` open scoped ContinuousFunctionalCalculus lemma nnrpow_eq_rpow {a : A} {x : ℝ≥0} (hx : 0 < x) : a ^ x = a ^ (x : ℝ) := by rw [nnrpow_def (A := A), rpow_def, cfcₙ_eq_cfc] lemma sqrt_eq_rpow {a : A} : sqrt a = a ^ (1 / 2 : ℝ) := by have : a ^ (1 / 2 : ℝ) = a ^ ((1 / 2 : ℝ≥0) : ℝ) := rfl rw [this, ← nnrpow_eq_rpow (by simp), sqrt_eq_nnrpow a] lemma sqrt_eq_cfc {a : A} : sqrt a = cfc NNReal.sqrt a := by unfold sqrt rw [cfcₙ_eq_cfc] lemma sqrt_sq (a : A) (ha : 0 ≤ a := by cfc_tac) : sqrt (a ^ 2) = a := by rw [pow_two, sqrt_mul_self (A := A) a] lemma sq_sqrt (a : A) (ha : 0 ≤ a := by cfc_tac) : (sqrt a) ^ 2 = a := by rw [pow_two, sqrt_mul_sqrt_self (A := A) a] @[simp] lemma sqrt_algebraMap {r : ℝ≥0} : sqrt (algebraMap ℝ≥0 A r) = algebraMap ℝ≥0 A (NNReal.sqrt r) := by rw [sqrt_eq_cfc, cfc_algebraMap] @[simp] lemma sqrt_one : sqrt (1 : A) = 1 := by simp [sqrt_eq_cfc] -- TODO: relate to a strict positivity condition lemma sqrt_rpow {a : A} {x : ℝ} (h : IsUnit a) (hx : x ≠ 0) : sqrt (a ^ x) = a ^ (x / 2) := by by_cases hnonneg : 0 ≤ a case pos => simp only [sqrt_eq_rpow, div_eq_mul_inv, one_mul, rpow_rpow _ _ _ h hx] case neg => simp [sqrt_eq_cfc, rpow_def, cfc_apply_of_not_predicate a hnonneg] -- TODO: relate to a strict positivity condition lemma rpow_sqrt (a : A) (x : ℝ) (h : IsUnit a) (ha : 0 ≤ a := by cfc_tac) : (sqrt a) ^ x = a ^ (x / 2) := by rw [sqrt_eq_rpow, div_eq_mul_inv, one_mul, rpow_rpow _ _ _ h (by simp), inv_mul_eq_div] lemma sqrt_rpow_nnreal {a : A} {x : ℝ≥0} : sqrt (a ^ (x : ℝ)) = a ^ (x / 2 : ℝ) := by by_cases htriv : 0 ≤ a case neg => simp [sqrt_eq_cfc, rpow_def, cfc_apply_of_not_predicate a htriv] case pos => cases eq_zero_or_pos x with | inl hx => simp [hx, rpow_zero _ htriv] | inr h₁ => have h₂ : (x : ℝ) / 2 = NNReal.toReal (x / 2) := by simp have h₃ : 0 < x / 2 := by positivity rw [← nnrpow_eq_rpow h₁, h₂, ← nnrpow_eq_rpow h₃, sqrt_nnrpow (A := A)] lemma rpow_sqrt_nnreal {a : A} {x : ℝ≥0} (ha : 0 ≤ a := by cfc_tac) : (sqrt a) ^ (x : ℝ) = a ^ (x / 2 : ℝ) := by by_cases hx : x = 0 case pos => have ha' : 0 ≤ sqrt a := sqrt_nonneg _ simp [hx, rpow_zero _ ha', rpow_zero _ ha] case neg => have h₁ : 0 ≤ (x : ℝ) := NNReal.zero_le_coe rw [sqrt_eq_rpow, rpow_rpow_of_exponent_nonneg _ _ _ (by simp) h₁, one_div_mul_eq_div] lemma isUnit_nnrpow_iff (a : A) (y : ℝ≥0) (hy : y ≠ 0) (ha : 0 ≤ a := by cfc_tac) : IsUnit (a ^ y) ↔ IsUnit a := by rw [nnrpow_eq_rpow (pos_of_ne_zero hy)] refine isUnit_rpow_iff a y ?_ ha exact_mod_cast hy @[aesop safe apply] lemma _root_.IsUnit.cfcNNRpow (a : A) (y : ℝ≥0) (ha_unit : IsUnit a) (hy : y ≠ 0) (ha : 0 ≤ a := by cfc_tac) : IsUnit (a ^ y) := (isUnit_nnrpow_iff a y hy ha).mpr ha_unit lemma isUnit_sqrt_iff (a : A) (ha : 0 ≤ a := by cfc_tac) : IsUnit (sqrt a) ↔ IsUnit a := by rw [sqrt_eq_rpow] exact isUnit_rpow_iff a _ (by norm_num) ha @[aesop safe apply] lemma _root_.IsUnit.cfcSqrt (a : A) (ha_unit : IsUnit a) (ha : 0 ≤ a := by cfc_tac) : IsUnit (sqrt a) := (isUnit_sqrt_iff a ha).mpr ha_unit end unital_vs_nonunital end Unital end CFC
ssreflect.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From Corelib Require Export ssreflect. Global Set SsrOldRewriteGoalsOrder. Global Set Asymmetric Patterns. Global Set Bullet Behavior "None". #[deprecated(since="mathcomp 2.3.0", note="Use `Arguments def : simpl never` instead (should work fine since Coq 8.18).")] Notation nosimpl t := (nosimpl t). (** Additions to be ported to Corelib ssreflect: hide t == t, but hide t displays as <hidden> hideT t == t, but both hideT t and its inferred type display as <hidden> New ltac views: => /#[#hide#]# := insert hide in the type of the top assumption (and its body if it is a 'let'), so it displays as <hidden>. => /#[#let#]# := if the type (or body) of the top assumption is a 'let', make that 'let' the top assumption, e.g., turn (let n := 1 in m < half n) -> G into let n := 1 in m < half n -> G => /#[#fix#]# := names a 'fix' expression f in the goal G(f), by replacing the goal with let fx := hide f in G(fx), where fx is a fresh variable, and hide f displays as <hidden>. => /#[#cofix#]# := similarly, names a 'cofix' expression in the goal. **) Definition hide {T} t : T := t. Notation hideT := (@hide (hide _)) (only parsing). Notation "<hidden >" := (hide _) (at level 0, format "<hidden >", only printing) : ssr_scope. Notation "'[' 'hide' ']'" := (ltac:( move; lazymatch goal with | |- forall x : ?A, ?G => change (forall x : hide A, G) | |- let x : ?A := ?a in ?G => change (let x : hide A := @hide A a in G) | _ => fail "[hide] : no top assumption" end)) (at level 0, only parsing) : ssripat_scope. Notation "'[' 'let' ']'" := (ltac:( move; lazymatch goal with | |- forall (H : let x : ?A := ?a in ?T), ?G => change (let x : A := a in forall H : T, G) | |- let H : (let x : ?A := ?a in ?T) := ?t in ?G => change (let x : A := a in let H : T := t in G) | |- let H : ?T := (let x : ?A := ?a in ?t) in ?G => change (let x : A := a in let H : T := t in G) | _ => fail "[let]: top assumption type or body is not a 'let'" end)) (at level 0, only parsing) : ssripat_scope. Notation "'[' 'fix' ']'" := (ltac:( match goal with | |- context [?t] => is_fix t; let f := fresh "fix" in set f := t; move: @f => /[hide] | _ => fail 1 "[fix]: no visible 'fix' in goal" end)) (at level 0, only parsing) : ssripat_scope. Notation "'[' 'cofix' ']'" := (ltac:( match goal with | |- context [?t] => is_cofix t; let z := fresh "cofix" in set z := t; move: @z => /[hide] | _ => fail 1 "[cofix]: no visible 'cofix' in goal" end)) (at level 0, only parsing) : ssripat_scope.
perm.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path. From mathcomp Require Import choice fintype tuple finfun bigop finset binomial. From mathcomp Require Import fingroup morphism. (******************************************************************************) (* This file contains the definition and properties associated to the group *) (* of permutations of an arbitrary finite type. *) (* {perm T} == the type of permutations of a finite type T, i.e., *) (* injective (finite) functions from T to T. Permutations *) (* coerce to CiC functions. *) (* 'S_n == the set of all permutations of 'I_n, i.e., of *) (* {0,.., n-1} *) (* perm_on A u == u is a permutation with support A, i.e., u only *) (* displaces elements of A (u x != x implies x \in A). *) (* tperm x y == the transposition of x, y. *) (* aperm x s == the image of x under the action of the permutation s. *) (* := s x *) (* cast_perm Emn s == the 'S_m permutation cast as a 'S_n permutation using *) (* Emn : m = n *) (* porbit s x == the set of all elements that are in the same cycle of *) (* the permutation s as x, i.e., {x, s x, (s ^+ 2) x, ...}.*) (* porbits s == the set of all the cycles of the permutation s. *) (* (s : bool) == s is an odd permutation (the coercion is called *) (* odd_perm). *) (* dpair u == u is a pair (x, y) of distinct objects (i.e., x != y). *) (* Sym S == the set of permutations with support S *) (* lift_perm i j s == the permutation obtained by lifting s : 'S_n.-1 over *) (* (i |-> j), that maps i to j and lift i k to *) (* lift j (s k). *) (* Canonical structures are defined allowing permutations to be an eqType, *) (* choiceType, countType, finType, subType, finGroupType; permutations with *) (* composition form a group, therefore inherit all generic group notations: *) (* 1 == identity permutation, * == composition, ^-1 == inverse permutation. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Section PermDefSection. Variable T : finType. Inductive perm_type : predArgType := Perm (pval : {ffun T -> T}) & injectiveb pval. Definition pval p := let: Perm f _ := p in f. Definition perm_of := perm_type. Identity Coercion type_of_perm : perm_of >-> perm_type. HB.instance Definition _ := [isSub for pval]. HB.instance Definition _ := [Finite of perm_type by <:]. Lemma perm_proof (f : T -> T) : injective f -> injectiveb (finfun f). Proof. by move=> f_inj; apply/injectiveP; apply: eq_inj f_inj _ => x; rewrite ffunE. Qed. End PermDefSection. Arguments perm_of T%_type. Notation "{ 'perm' T }" := (perm_of T) (format "{ 'perm' T }") : type_scope. Arguments pval _ _%_g. Bind Scope group_scope with perm_type. Bind Scope group_scope with perm_of. Notation "''S_' n" := {perm 'I_n} (at level 8, n at level 2, format "''S_' n"). HB.lock Definition perm T f injf := Perm (@perm_proof T f injf). Canonical perm_unlock := Unlockable perm.unlock. HB.lock Definition fun_of_perm T (u : perm_type T) : T -> T := val u. Canonical fun_of_perm_unlock := Unlockable fun_of_perm.unlock. Coercion fun_of_perm : perm_type >-> Funclass. Section Theory. Variable T : finType. Implicit Types (x y : T) (s t : {perm T}) (S : {set T}). Lemma permP s t : s =1 t <-> s = t. Proof. by split=> [| -> //]; rewrite unlock => eq_sv; apply/val_inj/ffunP. Qed. Lemma pvalE s : pval s = s :> (T -> T). Proof. by rewrite [@fun_of_perm]unlock. Qed. Lemma permE f f_inj : @perm T f f_inj =1 f. Proof. by move=> x; rewrite -pvalE [@perm]unlock ffunE. Qed. Lemma perm_inj {s} : injective s. Proof. by rewrite -!pvalE; apply: (injectiveP _ (valP s)). Qed. Hint Resolve perm_inj : core. Lemma perm_onto s : codom s =i predT. Proof. by apply/subset_cardP; rewrite ?card_codom ?subset_predT. Qed. Definition perm_one := perm (@inj_id T). Lemma perm_invK s : cancel (fun x => iinv (perm_onto s x)) s. Proof. by move=> x /=; rewrite f_iinv. Qed. Definition perm_inv s := perm (can_inj (perm_invK s)). Definition perm_mul s t := perm (inj_comp (@perm_inj t) (@perm_inj s)). Lemma perm_oneP : left_id perm_one perm_mul. Proof. by move=> s; apply/permP => x; rewrite permE /= permE. Qed. Lemma perm_invP : left_inverse perm_one perm_inv perm_mul. Proof. by move=> s; apply/permP=> x; rewrite !permE /= permE f_iinv. Qed. Lemma perm_mulP : associative perm_mul. Proof. by move=> s t u; apply/permP=> x; do !rewrite permE /=. Qed. HB.instance Definition _ := isMulGroup.Build (perm_type T) perm_mulP perm_oneP perm_invP. Lemma perm1 x : (1 : {perm T}) x = x. Proof. by rewrite permE. Qed. Lemma permM s t x : (s * t) x = t (s x). Proof. by rewrite permE. Qed. Lemma permK s : cancel s s^-1. Proof. by move=> x; rewrite -permM mulgV perm1. Qed. Lemma permKV s : cancel s^-1 s. Proof. by have:= permK s^-1; rewrite invgK. Qed. Lemma permJ s t x : (s ^ t) (t x) = t (s x). Proof. by rewrite !permM permK. Qed. Lemma permX s x n : (s ^+ n) x = iter n s x. Proof. by elim: n => [|n /= <-]; rewrite ?perm1 // -permM expgSr. Qed. Lemma permX_fix s x n : s x = x -> (s ^+ n) x = x. Proof. move=> Hs; elim: n => [|n IHn]; first by rewrite expg0 perm1. by rewrite expgS permM Hs. Qed. Lemma im_permV s S : s^-1 @: S = s @^-1: S. Proof. exact: can2_imset_pre (permKV s) (permK s). Qed. Lemma preim_permV s S : s^-1 @^-1: S = s @: S. Proof. by rewrite -im_permV invgK. Qed. Definition perm_on S : pred {perm T} := fun s => [pred x | s x != x] \subset S. Lemma perm_closed S s x : perm_on S s -> (s x \in S) = (x \in S). Proof. move/subsetP=> s_on_S; have [-> // | nfix_s_x] := eqVneq (s x) x. by rewrite !s_on_S // inE /= ?(inj_eq perm_inj). Qed. Lemma perm_on1 H : perm_on H 1. Proof. by apply/subsetP=> x; rewrite inE /= perm1 eqxx. Qed. Lemma perm_onM H s t : perm_on H s -> perm_on H t -> perm_on H (s * t). Proof. move/subsetP=> sH /subsetP tH; apply/subsetP => x; rewrite inE /= permM. by have [-> /tH | /sH] := eqVneq (s x) x. Qed. Lemma perm_onV H s : perm_on H s -> perm_on H s^-1. Proof. move=> /subsetP sH; apply/subsetP => i /[!inE] sVi; apply: sH; rewrite inE. by apply: contra_neq sVi => si_id; rewrite -[in LHS]si_id permK. Qed. Lemma out_perm S u x : perm_on S u -> x \notin S -> u x = x. Proof. by move=> uS; apply: contraNeq (subsetP uS x). Qed. Lemma im_perm_on u S : perm_on S u -> u @: S = S. Proof. move=> Su; rewrite -preim_permV; apply/setP=> x. by rewrite !inE -(perm_closed _ Su) permKV. Qed. Lemma perm_on_id u S : perm_on S u -> #|S| <= 1 -> u = 1%g. Proof. rewrite leq_eqVlt ltnS leqn0 => pSu S10; apply/permP => t; rewrite perm1. case/orP : S10; last first. by move/eqP/cards0_eq => S0; apply: (out_perm pSu); rewrite S0 inE. move=> /cards1P[x Sx]. have [-> | ntx] := eqVneq t x; last by apply: (out_perm pSu); rewrite Sx inE. by apply/eqP; have := perm_closed x pSu; rewrite Sx !inE => ->. Qed. Lemma perm_onC (S1 S2 : {set T}) (u1 u2 : {perm T}) : perm_on S1 u1 -> perm_on S2 u2 -> [disjoint S1 & S2] -> commute u1 u2. Proof. move=> pS1 pS2 S12; apply/permP => t; rewrite !permM. case/boolP : (t \in S1) => tS1. have /[!disjoint_subset] /subsetP {}S12 := S12. by rewrite !(out_perm pS2) //; apply: S12; rewrite // perm_closed. case/boolP : (t \in S2) => tS2. have /[1!disjoint_sym] /[!disjoint_subset] /subsetP {}S12 := S12. by rewrite !(out_perm pS1) //; apply: S12; rewrite // perm_closed. by rewrite (out_perm pS1) // (out_perm pS2) // (out_perm pS1). Qed. Lemma imset_perm1 (S : {set T}) : [set (1 : {perm T}) x | x in S] = S. Proof. apply: im_perm_on; exact: perm_on1. Qed. Lemma tperm_proof x y : involutive [fun z => z with x |-> y, y |-> x]. Proof. move=> z /=; case: (z =P x) => [-> | ne_zx]; first by rewrite eqxx; case: eqP. by case: (z =P y) => [->| ne_zy]; [rewrite eqxx | do 2?case: eqP]. Qed. Definition tperm x y := perm (can_inj (tperm_proof x y)). Variant tperm_spec x y z : T -> Type := | TpermFirst of z = x : tperm_spec x y z y | TpermSecond of z = y : tperm_spec x y z x | TpermNone of z <> x & z <> y : tperm_spec x y z z. Lemma tpermP x y z : tperm_spec x y z (tperm x y z). Proof. by rewrite permE /=; do 2?[case: eqP => /=]; constructor; auto. Qed. Lemma tpermL x y : tperm x y x = y. Proof. by case: tpermP. Qed. Lemma tpermR x y : tperm x y y = x. Proof. by case: tpermP. Qed. Lemma tpermD x y z : x != z -> y != z -> tperm x y z = z. Proof. by case: tpermP => // ->; rewrite eqxx. Qed. Lemma tpermC x y : tperm x y = tperm y x. Proof. by apply/permP => z; do 2![case: tpermP => //] => ->. Qed. Lemma tperm1 x : tperm x x = 1. Proof. by apply/permP => z; rewrite perm1; case: tpermP. Qed. Lemma tpermK x y : involutive (tperm x y). Proof. by move=> z; rewrite !permE tperm_proof. Qed. Lemma tpermKg x y : involutive (mulg (tperm x y)). Proof. by move=> s; apply/permP=> z; rewrite !permM tpermK. Qed. Lemma tpermV x y : (tperm x y)^-1 = tperm x y. Proof. by set t := tperm x y; rewrite -{2}(mulgK t t) -mulgA tpermKg. Qed. Lemma tperm2 x y : tperm x y * tperm x y = 1. Proof. by rewrite -{1}tpermV mulVg. Qed. Lemma tperm_on x y : perm_on [set x; y] (tperm x y). Proof. by apply/subsetP => z /[!inE]; case: tpermP => [->|->|]; rewrite eqxx // orbT. Qed. Lemma card_perm A : #|perm_on A| = (#|A|)`!. Proof. pose ffA := {ffun {x | x \in A} -> T}. rewrite -ffactnn -{2}(card_sig [in A]) /= -card_inj_ffuns_on. pose fT (f : ffA) := [ffun x => oapp f x (insub x)]. pose pfT f := insubd (1 : {perm T}) (fT f). pose fA s : ffA := [ffun u => s (val u)]. rewrite -!sum1dep_card -sum1_card (reindex_onto fA pfT) => [|f]. apply: eq_bigl => p; rewrite andbC; apply/idP/and3P=> [onA | []]; first split. - apply/eqP; suffices fTAp: fT (fA p) = pval p. by apply/permP=> x; rewrite -!pvalE insubdK fTAp //; apply: (valP p). apply/ffunP=> x; rewrite ffunE pvalE. by case: insubP => [u _ <- | /out_perm->] //=; rewrite ffunE. - by apply/forallP=> [[x Ax]]; rewrite ffunE /= perm_closed. - by apply/injectiveP=> u v; rewrite !ffunE => /perm_inj; apply: val_inj. move/eqP=> <- _ _; apply/subsetP=> x; rewrite !inE -pvalE val_insubd fun_if. by rewrite if_arg ffunE; case: insubP; rewrite // pvalE perm1 if_same eqxx. case/andP=> /forallP-onA /injectiveP-f_inj. apply/ffunP=> u; rewrite ffunE -pvalE insubdK; first by rewrite ffunE valK. apply/injectiveP=> {u} x y; rewrite !ffunE. case: insubP => [u _ <-|]; case: insubP => [v _ <-|] //=; first by move/f_inj->. by move=> Ay' def_y; rewrite -def_y [_ \in A]onA in Ay'. by move=> Ax' def_x; rewrite def_x [_ \in A]onA in Ax'. Qed. End Theory. Prenex Implicits tperm permK permKV tpermK. Arguments perm_inj {T s} [x1 x2] eq_sx12. (* Shorthand for using a permutation to reindex a bigop. *) Notation reindex_perm s := (reindex_inj (@perm_inj _ s)). Lemma inj_tperm (T T' : finType) (f : T -> T') x y z : injective f -> f (tperm x y z) = tperm (f x) (f y) (f z). Proof. by move=> injf; rewrite !permE /= !(inj_eq injf) !(fun_if f). Qed. Section tpermJ. Variables (T : finType). Implicit Types (x y z : T) (s : {perm T}). Lemma tpermJ x y s : (tperm x y) ^ s = tperm (s x) (s y). Proof. by apply/permP => z; rewrite -(permKV s z) permJ; apply/inj_tperm/perm_inj. Qed. Lemma tpermJ_tperm x y z : x != z -> y != z -> tperm x z ^ tperm x y = tperm y z. Proof. by move=> nxz nyz; rewrite tpermJ tpermL [tperm _ _ z]tpermD. Qed. End tpermJ. Lemma tuple_permP {T : eqType} {n} {s : seq T} {t : n.-tuple T} : reflect (exists p : 'S_n, s = [tuple tnth t (p i) | i < n]) (perm_eq s t). Proof. apply: (iffP idP) => [|[p ->]]; last first. rewrite /= (map_comp (tnth t)) -{1}(map_tnth_enum t) perm_map //. apply: uniq_perm => [||i]; rewrite ?enum_uniq //. by apply/injectiveP; apply: perm_inj. by rewrite mem_enum -[i](permKV p) image_f. case: n => [|n] in t *; last have x0 := tnth t ord0. rewrite tuple0 => /perm_small_eq-> //. by exists 1; rewrite [mktuple _]tuple0. case/(perm_iotaP x0); rewrite size_tuple => Is eqIst ->{s}. have uniqIs: uniq Is by rewrite (perm_uniq eqIst) iota_uniq. have szIs: size Is == n.+1 by rewrite (perm_size eqIst) !size_tuple. have pP i : tnth (Tuple szIs) i < n.+1. by rewrite -[_ < _](mem_iota 0) -(perm_mem eqIst) mem_tnth. have inj_p: injective (fun i => Ordinal (pP i)). by apply/injectiveP/(@map_uniq _ _ val); rewrite -map_comp map_tnth_enum. exists (perm inj_p); rewrite -[Is]/(tval (Tuple szIs)); congr (tval _). by apply: eq_from_tnth => i; rewrite tnth_map tnth_mktuple permE (tnth_nth x0). Qed. (* Note that porbit s x is the orbit of x by <[s]> under the action aperm. *) (* Hence, the porbit lemmas below are special cases of more general lemmas *) (* on orbits that will be stated in action.v. *) (* Defining porbit directly here avoids a dependency of matrix.v on *) (* action.v and hence morphism.v. *) Definition aperm (T : finType) x (s : {perm T}) := s x. HB.lock Definition porbit (T : finType) (s : {perm T}) x := aperm x @: <[s]>. Canonical porbit_unlockable := Unlockable porbit.unlock. Definition porbits (T : finType) (s : {perm T}) := porbit s @: T. Section PermutationParity. Variable T : finType. Implicit Types (s t u v : {perm T}) (x y z a b : T). Definition odd_perm (s : perm_type T) := odd #|T| (+) odd #|porbits s|. Lemma apermE x s : aperm x s = s x. Proof. by []. Qed. Lemma mem_porbit s i x : (s ^+ i) x \in porbit s x. Proof. by rewrite [@porbit]unlock (imset_f (aperm x)) ?mem_cycle. Qed. Lemma porbit_id s x : x \in porbit s x. Proof. by rewrite -{1}[x]perm1 (mem_porbit s 0). Qed. Lemma card_porbit_neq0 s x : #|porbit s x| != 0. Proof. by rewrite -lt0n card_gt0; apply/set0Pn; exists x; exact: porbit_id. Qed. Lemma uniq_traject_porbit s x : uniq (traject s x #|porbit s x|). Proof. case def_n: #|_| => // [n]; rewrite looping_uniq. apply: contraL (card_size (traject s x n)) => /loopingP t_sx. rewrite -ltnNge size_traject -def_n ?subset_leq_card // porbit.unlock. by apply/subsetP=> _ /imsetP[_ /cycleP[i ->] ->]; rewrite /aperm permX t_sx. Qed. Lemma porbit_traject s x : porbit s x =i traject s x #|porbit s x|. Proof. apply: fsym; apply/subset_cardP. by rewrite (card_uniqP _) ?size_traject ?uniq_traject_porbit. by apply/subsetP=> _ /trajectP[i _ ->]; rewrite -permX mem_porbit. Qed. Lemma iter_porbit s x : iter #|porbit s x| s x = x. Proof. case def_n: #|_| (uniq_traject_porbit s x) => [//|n] Ut. have: looping s x n.+1. by rewrite -def_n -[looping _ _ _]porbit_traject -permX mem_porbit. rewrite /looping => /trajectP[[|i] //= lt_i_n /perm_inj eq_i_n_sx]. move: lt_i_n; rewrite ltnS ltn_neqAle andbC => /andP[le_i_n /negP[]]. by rewrite -(nth_uniq x _ _ Ut) ?size_traject ?nth_traject // eq_i_n_sx. Qed. Lemma eq_porbit_mem s x y : (porbit s x == porbit s y) = (x \in porbit s y). Proof. apply/eqP/idP; first by move<-; exact: porbit_id. rewrite porbit.unlock => /imsetP[si s_si ->]. apply/setP => z; apply/imsetP/imsetP=> [] [sj s_sj ->]. by exists (si * sj); rewrite ?groupM /aperm ?permM. exists (si^-1 * sj); first by rewrite groupM ?groupV. by rewrite /aperm permM permK. Qed. Lemma porbit_sym s x y : (x \in porbit s y) = (y \in porbit s x). Proof. by rewrite -!eq_porbit_mem eq_sym. Qed. Lemma porbit_perm s i x : porbit s ((s ^+ i) x) = porbit s x. Proof. by apply/eqP; rewrite eq_porbit_mem mem_porbit. Qed. Lemma porbitPmin s x y : y \in porbit s x -> exists2 i, i < #[s] & y = (s ^+ i) x. Proof. by rewrite porbit.unlock=> /imsetP [z /cyclePmin[ i Hi ->{z}] ->{y}]; exists i. Qed. Lemma porbitP s x y : reflect (exists i, y = (s ^+ i) x) (y \in porbit s x). Proof. apply (iffP idP) => [/porbitPmin [i _ ->]| [i ->]]; last exact: mem_porbit. by exists i. Qed. Lemma porbitV s : porbit s^-1 =1 porbit s. Proof. move=> x; apply/setP => y; rewrite porbit_sym. by apply/porbitP/porbitP => -[i ->]; exists i; rewrite expgVn ?permK ?permKV. Qed. Lemma porbitsV s : porbits s^-1 = porbits s. Proof. rewrite /porbits; apply/setP => y. by apply/imsetP/imsetP => -[x _ ->{y}]; exists x; rewrite // porbitV. Qed. Lemma porbit_setP s t x : porbit s x =i porbit t x <-> porbit s x = porbit t x. Proof. by rewrite porbit.unlock; exact: setP. Qed. Lemma porbits_mul_tperm s x y : let t := tperm x y in #|porbits (t * s)| + (x \notin porbit s y).*2 = #|porbits s| + (x != y). Proof. pose xf a b u := seq.find (pred2 a b) (traject u (u a) #|porbit u a|). have xf_size a b u: xf a b u <= #|porbit u a|. by rewrite (leq_trans (find_size _ _)) ?size_traject. have lt_xf a b u n : n < xf a b u -> ~~ pred2 a b ((u ^+ n.+1) a). move=> lt_n; apply: contraFN (before_find (u a) lt_n). by rewrite permX iterSr nth_traject // (leq_trans lt_n). pose t a b u := tperm a b * u. have tC a b u : t a b u = t b a u by rewrite /t tpermC. have tK a b: involutive (t a b) by move=> u; apply: tpermKg. have tXC a b u n: n <= xf a b u -> (t a b u ^+ n.+1) b = (u ^+ n.+1) a. elim: n => [|n IHn] lt_n_f; first by rewrite permM tpermR. rewrite !(expgSr _ n.+1) !permM {}IHn 1?ltnW //; congr (u _). by case/lt_xf/norP: lt_n_f => ne_a ne_b; rewrite tpermD // eq_sym. have eq_xf a b u: pred2 a b ((u ^+ (xf a b u).+1) a). have ua_a: a \in porbit u (u a) by rewrite porbit_sym (mem_porbit _ 1). have has_f: has (pred2 a b) (traject u (u a) #|porbit u (u a)|). by apply/hasP; exists a; rewrite /= ?eqxx -?porbit_traject. have:= nth_find (u a) has_f; rewrite has_find size_traject in has_f. rewrite -eq_porbit_mem in ua_a. by rewrite nth_traject // -iterSr -permX -(eqP ua_a). have xfC a b u: xf b a (t a b u) = xf a b u. without loss lt_a: a b u / xf b a (t a b u) < xf a b u. move=> IHab; set m := xf b a _; set n := xf a b u. by case: (ltngtP m n) => // ltx; [apply: IHab | rewrite -[m]IHab tC tK]. by move/lt_xf: (lt_a); rewrite -(tXC a b) 1?ltnW //= orbC [_ || _]eq_xf. pose ts := t x y s; rewrite /= -[_ * s]/ts. pose dp u := #|porbits u :\ porbit u y :\ porbit u x|. rewrite !(addnC #|_|) (cardsD1 (porbit ts y)) imset_f ?inE //. rewrite (cardsD1 (porbit ts x)) inE imset_f ?inE //= -/(dp ts) {}/ts. rewrite (cardsD1 (porbit s y)) (cardsD1 (porbit s x)) !(imset_f, inE) //. rewrite -/(dp s) !addnA !eq_porbit_mem andbT; congr (_ + _); last first. wlog suffices: s / dp s <= dp (t x y s). by move=> IHs; apply/eqP; rewrite eqn_leq -{2}(tK x y s) !IHs. apply/subset_leq_card/subsetP=> {dp} C. rewrite !inE andbA andbC !(eq_sym C) => /and3P[/imsetP[z _ ->{C}]]. rewrite 2!eq_porbit_mem => sxz syz. suffices ts_z: porbit (t x y s) z = porbit s z. by rewrite -ts_z !eq_porbit_mem {1 2}ts_z sxz syz imset_f ?inE. suffices exp_id n: ((t x y s) ^+ n) z = (s ^+ n) z. apply/porbit_setP => u; apply/idP/idP=> /porbitP[i ->]. by rewrite /aperm exp_id mem_porbit. by rewrite /aperm -exp_id mem_porbit. elim: n => // n IHn; rewrite !expgSr !permM {}IHn tpermD //. by apply: contraNneq sxz => ->; apply: mem_porbit. by apply: contraNneq syz => ->; apply: mem_porbit. case: eqP {dp} => [<- | ne_xy]; first by rewrite /t tperm1 mul1g porbit_id. suff ->: (x \in porbit (t x y s) y) = (x \notin porbit s y) by case: (x \in _). without loss xf_x: s x y ne_xy / (s ^+ (xf x y s).+1) x = x. move=> IHs; have ne_yx := nesym ne_xy; have:= eq_xf x y s; set n := xf x y s. case/pred2P=> [|snx]; first exact: IHs. by rewrite -[x \in _]negbK ![x \in _]porbit_sym -{}IHs ?xfC ?tXC // tC tK. rewrite -{1}xf_x -(tXC _ _ _ _ (leqnn _)) mem_porbit; symmetry. rewrite -eq_porbit_mem eq_sym eq_porbit_mem porbit_traject. apply/trajectP=> [[n _ snx]]. have: looping s x (xf x y s).+1 by rewrite /looping -permX xf_x inE eqxx. move/loopingP/(_ n); rewrite -{n}snx. case/trajectP=> [[_|i]]; first exact: nesym; rewrite ltnS -permX => lt_i def_y. by move/lt_xf: lt_i; rewrite def_y /= eqxx orbT. Qed. Lemma odd_perm1 : odd_perm 1 = false. Proof. rewrite /odd_perm card_imset ?addbb // => x y; move/eqP; rewrite eq_porbit_mem. by rewrite porbit.unlock cycle1 imset_set1 /aperm perm1 inE=> /eqP. Qed. Lemma odd_mul_tperm x y s : odd_perm (tperm x y * s) = (x != y) (+) odd_perm s. Proof. rewrite addbC -addbA -[~~ _]oddb -oddD -porbits_mul_tperm. by rewrite oddD odd_double addbF. Qed. Lemma odd_tperm x y : odd_perm (tperm x y) = (x != y). Proof. by rewrite -[_ y]mulg1 odd_mul_tperm odd_perm1 addbF. Qed. Definition dpair (eT : eqType) := [pred t | t.1 != t.2 :> eT]. Arguments dpair {eT}. Lemma prod_tpermP s : {ts : seq (T * T) | s = \prod_(t <- ts) tperm t.1 t.2 & all dpair ts}. Proof. have [n] := ubnP #|[pred x | s x != x]|; elim: n s => // n IHn s /ltnSE-le_s_n. case: (pickP (fun x => s x != x)) => [x s_x | s_id]; last first. exists nil; rewrite // big_nil; apply/permP=> x. by apply/eqP/idPn; rewrite perm1 s_id. have [|ts def_s ne_ts] := IHn (tperm x (s^-1 x) * s); last first. exists ((x, s^-1 x) :: ts); last by rewrite /= -(canF_eq (permK _)) s_x. by rewrite big_cons -def_s mulgA tperm2 mul1g. rewrite (cardD1 x) !inE s_x in le_s_n; apply: leq_ltn_trans le_s_n. apply: subset_leq_card; apply/subsetP=> y. rewrite !inE permM permE /= -(canF_eq (permK _)). have [-> | ne_yx] := eqVneq y x; first by rewrite permKV eqxx. by case: (s y =P x) => // -> _; rewrite eq_sym. Qed. Lemma odd_perm_prod ts : all dpair ts -> odd_perm (\prod_(t <- ts) tperm t.1 t.2) = odd (size ts). Proof. elim: ts => [_|t ts IHts] /=; first by rewrite big_nil odd_perm1. by case/andP=> dt12 dts; rewrite big_cons odd_mul_tperm dt12 IHts. Qed. Lemma odd_permM : {morph odd_perm : s1 s2 / s1 * s2 >-> s1 (+) s2}. Proof. move=> s1 s2; case: (prod_tpermP s1) => ts1 ->{s1} dts1. case: (prod_tpermP s2) => ts2 ->{s2} dts2. by rewrite -big_cat !odd_perm_prod ?all_cat ?dts1 // size_cat oddD. Qed. Lemma odd_permV s : odd_perm s^-1 = odd_perm s. Proof. by rewrite -{2}(mulgK s s) !odd_permM -addbA addKb. Qed. Lemma odd_permJ s1 s2 : odd_perm (s1 ^ s2) = odd_perm s1. Proof. by rewrite !odd_permM odd_permV addbC addbK. Qed. Lemma gen_tperm x : <<[set tperm x y | y in T]>>%g = [set: {perm T}]. Proof. apply/eqP; rewrite eqEsubset subsetT/=; apply/subsetP => s _. have [ts -> _] := prod_tpermP s; rewrite group_prod// => -[/= y z] _. have [<-|Nyz] := eqVneq y z; first by rewrite tperm1 group1. have [<-|Nxz] := eqVneq x z; first by rewrite tpermC mem_gen ?imset_f. by rewrite -(tpermJ_tperm Nxz Nyz) groupJ ?mem_gen ?imset_f. Qed. End PermutationParity. Coercion odd_perm : perm_type >-> bool. Arguments dpair {eT}. Prenex Implicits porbit dpair porbits aperm. Section Symmetry. Variables (T : finType) (S : {set T}). Definition Sym : {set {perm T}} := [set s | perm_on S s]. Lemma Sym_group_set : group_set Sym. Proof. apply/group_setP; split => [|s t] /[!inE]; [exact: perm_on1 | exact: perm_onM]. Qed. Canonical Sym_group : {group {perm T}} := Group Sym_group_set. Lemma card_Sym : #|Sym| = #|S|`!. Proof. by rewrite cardsE /= card_perm. Qed. End Symmetry. Section LiftPerm. (* Somewhat more specialised constructs for permutations on ordinals. *) Variable n : nat. Implicit Types i j : 'I_n.+1. Implicit Types s t : 'S_n. Lemma card_Sn : #|'S_(n)| = n`!. Proof. rewrite (eq_card (B := perm_on [set : 'I_n])). by rewrite card_perm /= cardsE /= card_ord. move=> p; rewrite inE unfold_in /perm_on /=. by apply/esym/subsetP => i _; rewrite in_set. Qed. Definition lift_perm_fun i j s k := if unlift i k is Some k' then lift j (s k') else j. Lemma lift_permK i j s : cancel (lift_perm_fun i j s) (lift_perm_fun j i s^-1). Proof. rewrite /lift_perm_fun => k. by case: (unliftP i k) => [j'|] ->; rewrite (liftK, unlift_none) ?permK. Qed. Definition lift_perm i j s := perm (can_inj (lift_permK i j s)). Lemma lift_perm_id i j s : lift_perm i j s i = j. Proof. by rewrite permE /lift_perm_fun unlift_none. Qed. Lemma lift_perm_lift i j s k' : lift_perm i j s (lift i k') = lift j (s k') :> 'I_n.+1. Proof. by rewrite permE /lift_perm_fun liftK. Qed. Lemma lift_permM i j k s t : lift_perm i j s * lift_perm j k t = lift_perm i k (s * t). Proof. apply/permP=> i1; case: (unliftP i i1) => [i2|] ->{i1}. by rewrite !(permM, lift_perm_lift). by rewrite permM !lift_perm_id. Qed. Lemma lift_perm1 i : lift_perm i i 1 = 1. Proof. by apply: (mulgI (lift_perm i i 1)); rewrite lift_permM !mulg1. Qed. Lemma lift_permV i j s : (lift_perm i j s)^-1 = lift_perm j i s^-1. Proof. by apply/eqP; rewrite eq_invg_mul lift_permM mulgV lift_perm1. Qed. Lemma odd_lift_perm i j s : lift_perm i j s = odd i (+) odd j (+) s :> bool. Proof. rewrite -{1}(mul1g s) -(lift_permM _ j) odd_permM. congr (_ (+) _); last first. case: (prod_tpermP s) => ts ->{s} _. elim: ts => [|t ts IHts] /=; first by rewrite big_nil lift_perm1 !odd_perm1. rewrite big_cons odd_mul_tperm -(lift_permM _ j) odd_permM {}IHts //. congr (_ (+) _); transitivity (tperm (lift j t.1) (lift j t.2)); last first. by rewrite odd_tperm (inj_eq (pcan_inj (liftK j))). congr odd_perm; apply/permP=> k; case: (unliftP j k) => [k'|] ->. by rewrite lift_perm_lift inj_tperm //; apply: lift_inj. by rewrite lift_perm_id tpermD // eq_sym neq_lift. suff{i j s} odd_lift0 (k : 'I_n.+1): lift_perm ord0 k 1 = odd k :> bool. rewrite -!odd_lift0 -{2}invg1 -lift_permV odd_permV -odd_permM. by rewrite lift_permM mulg1. elim: {k}(k : nat) {1 3}k (erefl (k : nat)) => [|m IHm] k def_k. by rewrite (_ : k = ord0) ?lift_perm1 ?odd_perm1 //; apply: val_inj. have le_mn: m < n.+1 by [rewrite -def_k ltnW]; pose j := Ordinal le_mn. rewrite -(mulg1 1)%g -(lift_permM _ j) odd_permM {}IHm // addbC. rewrite (_ : _ 1 = tperm j k); first by rewrite odd_tperm neq_ltn/= def_k leqnn. apply/permP=> i; case: (unliftP j i) => [i'|] ->; last first. by rewrite lift_perm_id tpermL. apply: ord_inj; rewrite lift_perm_lift !permE /= eq_sym -if_neg neq_lift. rewrite fun_if -val_eqE /= def_k /bump ltn_neqAle andbC. case: leqP => [_ | lt_i'm] /=; last by rewrite -if_neg neq_ltn leqW. by rewrite add1n eqSS; case: eqVneq. Qed. End LiftPerm. Prenex Implicits lift_perm lift_permK. Lemma permS0 : all_equal_to (1 : 'S_0). Proof. by move=> g; apply/permP; case. Qed. Lemma permS1 : all_equal_to (1 : 'S_1). Proof. by move=> g; apply/permP => i; rewrite !ord1. Qed. Lemma permS01 n : n <= 1 -> all_equal_to (1 : 'S_n). Proof. by case: n => [|[|]//=] _ g; rewrite (permS0, permS1). Qed. Section CastSn. Definition cast_perm m n (eq_mn : m = n) (s : 'S_m) := let: erefl in _ = n := eq_mn return 'S_n in s. Lemma cast_perm_id n eq_n s : cast_perm eq_n s = s :> 'S_n. Proof. by apply/permP => i; rewrite /cast_perm /= eq_axiomK. Qed. Lemma cast_ord_permE m n eq_m_n (s : 'S_m) i : @cast_ord m n eq_m_n (s i) = (cast_perm eq_m_n s) (cast_ord eq_m_n i). Proof. by subst m; rewrite cast_perm_id !cast_ord_id. Qed. Lemma cast_permE m n (eq_m_n : m = n) (s : 'S_m) (i : 'I_n) : cast_perm eq_m_n s i = cast_ord eq_m_n (s (cast_ord (esym eq_m_n) i)). Proof. by rewrite cast_ord_permE cast_ordKV. Qed. Lemma cast_perm_comp m n p (eq_m_n : m = n) (eq_n_p : n = p) s : cast_perm eq_n_p (cast_perm eq_m_n s) = cast_perm (etrans eq_m_n eq_n_p) s. Proof. by case: _ / eq_n_p. Qed. Lemma cast_permK m n eq_m_n : cancel (@cast_perm m n eq_m_n) (cast_perm (esym eq_m_n)). Proof. by subst m. Qed. Lemma cast_permKV m n eq_m_n : cancel (cast_perm (esym eq_m_n)) (@cast_perm m n eq_m_n). Proof. by subst m. Qed. Lemma cast_perm_sym m n (eq_m_n : m = n) s t : s = cast_perm eq_m_n t -> t = cast_perm (esym eq_m_n) s. Proof. by move/(canLR (cast_permK _)). Qed. Lemma cast_perm_inj m n eq_m_n : injective (@cast_perm m n eq_m_n). Proof. exact: can_inj (cast_permK eq_m_n). Qed. Lemma cast_perm_morphM m n eq_m_n : {morph @cast_perm m n eq_m_n : x y / x * y >-> x * y}. Proof. by subst m. Qed. Canonical morph_of_cast_perm m n eq_m_n := @Morphism _ _ setT (cast_perm eq_m_n) (in2W (@cast_perm_morphM m n eq_m_n)). Lemma isom_cast_perm m n eq_m_n : isom setT setT (@cast_perm m n eq_m_n). Proof. case: {n} _ / eq_m_n; apply/isomP; split. exact/injmP/(in2W (@cast_perm_inj _ _ _)). by apply/setP => /= s /[!inE]; apply/imsetP; exists s; rewrite ?inE. Qed. End CastSn.
PosPart.lean
/- Copyright (c) 2024 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.SpecialFunctions.ContinuousFunctionalCalculus.PosPart.Isometric import Mathlib.Analysis.CStarAlgebra.ContinuousFunctionalCalculus.Basic /-! # C⋆-algebraic facts about `a⁺` and `a⁻`. -/ variable {A : Type*} [NonUnitalCStarAlgebra A] [PartialOrder A] [StarOrderedRing A] namespace CStarAlgebra section SpanNonneg open Submodule /-- A C⋆-algebra is spanned by nonnegative elements of norm at most `r` -/ lemma span_nonneg_inter_closedBall {r : ℝ} (hr : 0 < r) : span ℂ ({x : A | 0 ≤ x} ∩ Metric.closedBall 0 r) = ⊤ := by rw [eq_top_iff, ← span_nonneg, span_le] intro x hx obtain (rfl | hx_pos) := eq_zero_or_norm_pos x · exact zero_mem _ · suffices (r * ‖x‖⁻¹ : ℂ)⁻¹ • ((r * ‖x‖⁻¹ : ℂ) • x) = x by rw [← this] refine smul_mem _ _ (subset_span <| Set.mem_inter ?_ ?_) · norm_cast exact smul_nonneg (by positivity) hx · simp [mul_smul, norm_smul, abs_of_pos hr, inv_mul_cancel₀ hx_pos.ne'] apply inv_smul_smul₀ norm_cast positivity /-- A C⋆-algebra is spanned by nonnegative elements of norm less than `r`. -/ lemma span_nonneg_inter_ball {r : ℝ} (hr : 0 < r) : span ℂ ({x : A | 0 ≤ x} ∩ Metric.ball 0 r) = ⊤ := by rw [eq_top_iff, ← span_nonneg_inter_closedBall (half_pos hr)] gcongr exact Metric.closedBall_subset_ball <| half_lt_self hr /-- A C⋆-algebra is spanned by nonnegative contractions. -/ lemma span_nonneg_inter_unitClosedBall : span ℂ ({x : A | 0 ≤ x} ∩ Metric.closedBall 0 1) = ⊤ := span_nonneg_inter_closedBall zero_lt_one /-- A C⋆-algebra is spanned by nonnegative strict contractions. -/ lemma span_nonneg_inter_unitBall : span ℂ ({x : A | 0 ≤ x} ∩ Metric.ball 0 1) = ⊤ := span_nonneg_inter_ball zero_lt_one end SpanNonneg open Complex in lemma exists_sum_four_nonneg {A : Type*} [NonUnitalCStarAlgebra A] [PartialOrder A] [StarOrderedRing A] (a : A) : ∃ x : Fin 4 → A, (∀ i, 0 ≤ x i) ∧ (∀ i, ‖x i‖ ≤ ‖a‖) ∧ a = ∑ i : Fin 4, I ^ (i : ℕ) • x i := by use ![(realPart a)⁺, (imaginaryPart a)⁺, (realPart a)⁻, (imaginaryPart a)⁻] rw [← and_assoc, ← forall_and] constructor · intro i fin_cases i all_goals constructor · simp cfc_tac · exact CStarAlgebra.norm_posPart_le _ |>.trans <| realPart.norm_le a · exact CStarAlgebra.norm_posPart_le _ |>.trans <| imaginaryPart.norm_le a · exact CStarAlgebra.norm_negPart_le _ |>.trans <| realPart.norm_le a · exact CStarAlgebra.norm_negPart_le _ |>.trans <| imaginaryPart.norm_le a · nth_rw 1 [← CStarAlgebra.linear_combination_nonneg a] simp only [Fin.sum_univ_four, Fin.coe_ofNat_eq_mod, Matrix.cons_val, Nat.reduceMod, I_sq, I_pow_three] module end CStarAlgebra
ContDiff.lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import Mathlib.Analysis.Calculus.ContDiff.Operations import Mathlib.Analysis.Calculus.ContDiff.RCLike import Mathlib.Analysis.Calculus.InverseFunctionTheorem.FDeriv /-! # Inverse function theorem, `C^r` case In this file we specialize the inverse function theorem to `C^r`-smooth functions. -/ noncomputable section namespace ContDiffAt variable {𝕂 : Type*} [RCLike 𝕂] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕂 E] variable {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕂 F] variable [CompleteSpace E] (f : E → F) {f' : E ≃L[𝕂] F} {a : E} {n : WithTop ℕ∞} /-- Given a `ContDiff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, returns a `PartialHomeomorph` with `to_fun = f` and `a ∈ source`. -/ def toPartialHomeomorph (hf : ContDiffAt 𝕂 n f a) (hf' : HasFDerivAt f (f' : E →L[𝕂] F) a) (hn : 1 ≤ n) : PartialHomeomorph E F := (hf.hasStrictFDerivAt' hf' hn).toPartialHomeomorph f variable {f} @[simp] theorem toPartialHomeomorph_coe (hf : ContDiffAt 𝕂 n f a) (hf' : HasFDerivAt f (f' : E →L[𝕂] F) a) (hn : 1 ≤ n) : (hf.toPartialHomeomorph f hf' hn : E → F) = f := rfl theorem mem_toPartialHomeomorph_source (hf : ContDiffAt 𝕂 n f a) (hf' : HasFDerivAt f (f' : E →L[𝕂] F) a) (hn : 1 ≤ n) : a ∈ (hf.toPartialHomeomorph f hf' hn).source := (hf.hasStrictFDerivAt' hf' hn).mem_toPartialHomeomorph_source theorem image_mem_toPartialHomeomorph_target (hf : ContDiffAt 𝕂 n f a) (hf' : HasFDerivAt f (f' : E →L[𝕂] F) a) (hn : 1 ≤ n) : f a ∈ (hf.toPartialHomeomorph f hf' hn).target := (hf.hasStrictFDerivAt' hf' hn).image_mem_toPartialHomeomorph_target /-- Given a `ContDiff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, returns a function that is locally inverse to `f`. -/ def localInverse (hf : ContDiffAt 𝕂 n f a) (hf' : HasFDerivAt f (f' : E →L[𝕂] F) a) (hn : 1 ≤ n) : F → E := (hf.hasStrictFDerivAt' hf' hn).localInverse f f' a theorem localInverse_apply_image (hf : ContDiffAt 𝕂 n f a) (hf' : HasFDerivAt f (f' : E →L[𝕂] F) a) (hn : 1 ≤ n) : hf.localInverse hf' hn (f a) = a := (hf.hasStrictFDerivAt' hf' hn).localInverse_apply_image /-- Given a `ContDiff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, the inverse function (produced by `ContDiff.toPartialHomeomorph`) is also `ContDiff`. -/ theorem to_localInverse (hf : ContDiffAt 𝕂 n f a) (hf' : HasFDerivAt f (f' : E →L[𝕂] F) a) (hn : 1 ≤ n) : ContDiffAt 𝕂 n (hf.localInverse hf' hn) (f a) := by have := hf.localInverse_apply_image hf' hn apply (hf.toPartialHomeomorph f hf' hn).contDiffAt_symm (image_mem_toPartialHomeomorph_target hf hf' hn) · convert hf' · convert hf end ContDiffAt
polyrith.lean
/- Copyright (c) 2022 Dhruv Bhatia. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dhruv Bhatia, Robert Y. Lewis, Mario Carneiro -/ import Mathlib.Tactic.Polyrith -- Except for the `import`, the doc-modules and the following `set_option`, this file is just -- comments and whitespace. Once the file gets revived, the linting can start! set_option linter.style.longLine false /-! Each call to `polyrith` makes a call to the SageCell web API at <https://sagecell.sagemath.org/>. To avoid making many API calls from CI, we only test this communication in a few tests. A full test suite is provided at the bottom of the file. -/ /-! ## Set up testing infrastructure -/ -- section tactic -- open polyrith tactic -- /-- -- For testing purposes, this behaves like `tactic.polyrith`, but takes an extra argument -- representing the expected output from a call to Sage. -- Allows for testing without actually making API calls. -- -/ -- meta def tactic.test_polyrith (only_on : bool) (hyps : list pexpr) -- (sage_out : json) (expected_args : list string) (expected_out : string) : -- tactic unit := do -- (eq_names, m, R, args) ← create_args only_on hyps, -- guard (args = expected_args) <|> -- fail!"expected arguments to Sage: {expected_args}\nbut produced: {args}", -- out ← to_string <$> process_output eq_names m R sage_out, -- guard (out = expected_out) <|> -- fail!"expected final output: {expected_out}\nbut produced: {out}" -- meta def format_string_list (input : list string) : format := -- "[" ++ (format.join <| (input.map (λ s, ("\"" : format) ++ format.of_string s ++ "\"")).intersperse ("," ++ format.line)) ++ "]" -- setup_tactic_parser -- meta def tactic.interactive.test_polyrith (restr : parse (tk "only")?) -- (hyps : parse pexpr_list?) -- (sage_out : string) (expected_args : list string) (expected_out : string) : tactic unit := do -- some sage_out ← return <| json.parse sage_out, -- tactic.test_polyrith restr.is_some (hyps.get_or_else []) sage_out expected_args expected_out -- meta def tactic.interactive.test_sage_output (restr : parse (tk "only")?) -- (hyps : parse pexpr_list?) (expected_out : string) : tactic unit := do -- expected_json ← json.parse expected_out, -- sleep 10, -- otherwise can lead to weird errors when actively editing code with polyrith calls -- (eq_names, m, R, args) ← create_args restr.is_some (hyps.get_or_else []), -- sage_out ← sage_output args, -- guard (sage_out = expected_json) <|> -- fail!"Expected output from Sage: {expected_out}\nbut produced: {sage_out}" -- /-- -- A convenience function. Given a working test, prints the code for a call to `test_sage_output`. -- -/ -- meta def tactic.interactive.create_sage_output_test (restr : parse (tk "only")?) -- (hyps : parse pexpr_list?) : tactic unit := do -- let hyps := (hyps.get_or_else []), -- sleep 10, -- otherwise can lead to weird errors when actively editing code with polyrith calls -- (eq_names, m, R, args) ← create_args restr.is_some hyps, -- sage_out ← to_string <$> sage_output args, -- let sage_out := sage_out.fold "" (λ s c, s ++ (if c = '"' then "\\\"" else to_string c)), -- let onl := if restr.is_some then "only " else "", -- let hyps := if hyps = [] then "" else to_string hyps, -- trace!"test_sage_output {onl}{hyps} \"{sage_out}\"" -- /-- -- A convenience function. Given a working test, prints the code for a call to `test_polyrith`. -- -/ -- meta def tactic.interactive.create_polyrith_test (restr : parse (tk "only")?) -- (hyps : parse pexpr_list?) : tactic unit := do -- let hyps := (hyps.get_or_else []), -- sleep 10, -- otherwise can lead to weird errors when actively editing code with polyrith calls -- (eq_names, m, R, args) ← create_args restr.is_some hyps, -- sage_out ← sage_output args, -- out ← to_string <$> process_output eq_names m R sage_out, -- let out := out.fold "" (λ s c, s ++ (if c = '"' then "\\\"" else to_string c)), -- let sage_out := (to_string sage_out).fold "" -- (λ s c, s ++ (if c = '"' then "\\\"" else to_string c)), -- let argstring := format_string_list args, -- let onl := if restr.is_some then "only " else "", -- let hyps := if hyps = [] then "" else to_string hyps, -- let trf := format.nest 2 <| format!"test_polyrith {onl}{hyps} \n\"{sage_out}\"\n{argstring}\n\"{out}\"", -- trace!"Try this: {trf}" -- end tactic -- /-! -- ## SageCell communication tests -- -/ -- example (x y : ℚ) (h1 : x*y + 2*x = 1) (h2 : x = y) : -- x*y = -2*y + 1 := by -- test_sage_output "{\"data\":[\"(poly.const 1/1)\",\"(poly.const -2/1)\"],\"success\":true}" -- linear_combination h1 - 2 * h2 -- example (w x y z : ℝ) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5) -- (h3 : x + y + 5*z + 5*w = 3) : -- x + 2.2*y + 2*z - 5*w = -8.5 := by -- test_sage_output "{\"data\":[\"(poly.const 2/1)\",\"(poly.const 1/1)\",\"(poly.const -2/1)\"],\"success\":true}" -- linear_combination 2 * h1 + h2 - 2 * h3 -- /-! ### Standard Cases over ℤ, ℚ, and ℝ -/ -- example (x y : ℤ) (h1 : 3*x + 2*y = 10) : -- 3*x + 2*y = 10 := -- by test_polyrith -- "{\"data\":[\"(poly.const 1/1)\"],\"success\":true}" -- ["ff", -- "int", -- "2", -- "[(((3 * var0) + (2 * var1)) - 10)]", -- "(((3 * var0) + (2 * var1)) - 10)"] -- "linear_combination h1" -- example (x y : ℚ) (h1 : x*y + 2*x = 1) (h2 : x = y) : -- x*y = -2*y + 1 := -- by test_polyrith -- "{\"data\":[\"(poly.const 1/1)\",\"(poly.const -2/1)\"],\"success\":true}" -- ["ff", -- "rat", -- "2", -- "[(((var0 * var1) + (2 * var0)) - 1), (var0 - var1)]", -- "((var0 * var1) - ((-2 * var1) + 1))"] -- "linear_combination h1 - 2 * h2" -- example (x y : ℝ) (h1 : x + 2 = -3) (h2 : y = 10) : -- -y + 2*x + 4 = -16 := -- by test_polyrith -- "{\"data\":[\"(poly.const 2/1)\",\"(poly.const -1/1)\"],\"success\":true}" -- ["ff", -- "real", -- "2", -- "[((var1 + 2) - -3), (var0 - 10)]", -- "(((-var0 + (2 * var1)) + 4) - -16)"] -- "linear_combination 2 * h1 - h2" -- example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) -- (hc : x + 2*y + z = 2) : -- -3*x - 3*y - 4*z = 2 := -- by test_polyrith -- "{\"data\":[\"(poly.const 1/1)\",\"(poly.const -1/1)\",\"(poly.const -2/1)\"],\"success\":true}" -- ["ff", -- "real", -- "3", -- "[(((var0 + (2 * var1)) - var2) - 4), ((((2 * var0) + var1) + var2) - -2), (((var0 + (2 * var1)) + var2) - 2)]", -- "((((-3 * var0) - (3 * var1)) - (4 * var2)) - 2)"] -- "linear_combination ha - hb - 2 * hc" -- example (w x y z : ℝ) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5) -- (h3 : x + y + 5*z + 5*w = 3) : -- x + 2.2*y + 2*z - 5*w = -8.5 := -- by test_polyrith -- "{\"data\":[\"(poly.const 2/1)\",\"(poly.const 1/1)\",\"(poly.const -2/1)\"],\"success\":true}" -- ["ff", -- "real", -- "4", -- "[(((var0 + (21/10 * var1)) + (2 * var2)) - 2), (((var0 + (8 * var2)) + (5 * var3)) - -13/2), ((((var0 + var1) + (5 * var2)) + (5 * var3)) - 3)]", -- "((((var0 + (11/5 * var1)) + (2 * var2)) - (5 * var3)) - -17/2)"] -- "linear_combination 2 * h1 + h2 - 2 * h3" -- example (a b c d : ℚ) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) : -- 2*a - 3 + 9*c + 3*d = 8 - b + 3*d - 3*a := -- by test_polyrith -- "{\"data\":[\"(poly.const 2/1)\",\"(poly.const -1/1)\",\"(poly.const 3/1)\",\"(poly.const -3/1)\"],\"success\":true}" -- ["ff", -- "rat", -- "4", -- "[(var0 - 4), (3 - var3), ((var1 * 3) - var2), (-var2 - var0)]", -- "(((((2 * var0) - 3) + (9 * var1)) + (3 * var2)) - (((8 - var3) + (3 * var2)) - (3 * var0)))"] -- "linear_combination 2 * h1 - h2 + 3 * h3 - 3 * h4" -- /-! ### Case with ambiguous identifiers -/ -- example («def evil» y : ℤ) (h1 : 3*«def evil» + 2*y = 10) : -- 3*«def evil» + 2*y = 10 := -- by test_polyrith -- "{\"data\":[\"(poly.const 1/1)\"],\"success\":true}" -- ["ff", -- "int", -- "2", -- "[(((3 * var0) + (2 * var1)) - 10)]", -- "(((3 * var0) + (2 * var1)) - 10)"] -- "linear_combination h1" -- example («¥» y : ℤ) (h1 : 3*«¥» + 2*y = 10) : -- «¥» * (3*«¥» + 2*y) = 10 * «¥» := -- by test_polyrith -- "{\"data\":[\"(poly.var 0)\"],\"success\":true}" -- ["ff", -- "int", -- "2", -- "[(((3 * var0) + (2 * var1)) - 10)]", -- "((var0 * ((3 * var0) + (2 * var1))) - (10 * var0))"] -- "linear_combination «¥» * h1" -- /-! ### Cases with arbitrary coefficients -/ -- example (a b : ℤ) (h : a = b) : -- a * a = a * b := -- by test_polyrith -- "{\"data\":[\"(poly.var 0)\"],\"success\":true}" -- ["ff", -- "int", -- "2", -- "[(var0 - var1)]", -- "((var0 * var0) - (var0 * var1))"] -- "linear_combination a * h" -- example (a b c : ℤ) (h : a = b) : -- a * c = b * c := -- by test_polyrith -- "{\"data\":[\"(poly.var 1)\"],\"success\":true}" -- ["ff", -- "int", -- "3", -- "[(var0 - var2)]", -- "((var0 * var1) - (var2 * var1))"] -- "linear_combination c * h" -- example (a b c : ℤ) (h1 : a = b) (h2 : b = 1) : -- c * a + b = c * b + 1 := -- by test_polyrith -- "{\"data\":[\"(poly.var 0)\",\"(poly.const 1/1)\"],\"success\":true}" -- ["ff", -- "int", -- "3", -- "[(var1 - var2), (var2 - 1)]", -- "(((var0 * var1) + var2) - ((var0 * var2) + 1))"] -- "linear_combination c * h1 + h2" -- example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) : -- x*x*y + y*x*y + 6*x = 3*x*y + 14 := -- by test_polyrith -- "{\"data\":[\"(poly.mul (poly.var 0) (poly.var 1))\",\"(poly.const 2/1)\"],\"success\":true}" -- ["ff", -- "rat", -- "2", -- "[((var0 + var1) - 3), ((3 * var0) - 7)]", -- "(((((var0 * var0) * var1) + ((var1 * var0) * var1)) + (6 * var0)) - (((3 * var0) * var1) + 14))"] -- "linear_combination x * y * h1 + 2 * h2" -- example (x y z w : ℚ) (hzw : z = w) : x*z + 2*y*z = x*w + 2*y*w := by -- test_polyrith -- "{\"data\":[\"(poly.add (poly.var 0) (poly.mul (poly.const 2/1) (poly.var 2)))\"],\"success\":true}" -- ["ff", -- "rat", -- "4", -- "[(var1 - var3)]", -- "(((var0 * var1) + ((2 * var2) * var1)) - ((var0 * var3) + ((2 * var2) * var3)))"] -- "linear_combination (x + 2 * y) * hzw" -- /-! ### Cases with non-hypothesis inputs/input restrictions -/ -- example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) (hignore : 3 = a + b) : -- b = 2 / 3 := by -- test_polyrith only [ha, hab] -- "{\"data\":[\"(poly.const 1/6)\",\"(poly.const 1/3)\"],\"success\":true}" -- ["ff", -- "real", -- "2", -- "[((2 * var1) - 4), ((2 * var0) - (var1 - var0))]", -- "(var0 - 2/3)"] -- "linear_combination ha / 6 + hab / 3" -- constant term : ∀ a b : ℚ, a + b = 0 -- example (a b c d : ℚ) (h : a + b = 0) (h2 : b + c = 0) : a + b + c + d = 0 := by -- test_polyrith only [term c d, h] -- "{\"data\":[\"(poly.const 1/1)\",\"(poly.const 1/1)\"],\"success\":true}" -- ["ff", -- "rat", -- "4", -- "[((var2 + var3) - 0), ((var0 + var1) - 0)]", -- "((((var0 + var1) + var2) + var3) - 0)"] -- "linear_combination term c d + h" -- constants (qc : ℚ) (hqc : qc = 2*qc) -- example (a b : ℚ) (h : ∀ p q : ℚ, p = q) : 3*a + qc = 3*b + 2*qc := by -- test_polyrith [h a b, hqc] -- "{\"data\":[\"(poly.const 3/1)\",\"(poly.const 1/1)\"],\"success\":true}" -- ["ff", -- "rat", -- "3", -- "[(var0 - var2), (var1 - (2 * var1))]", -- "(((3 * var0) + var1) - ((3 * var2) + (2 * var1)))"] -- "linear_combination 3 * h a b + hqc" -- constant bad (q : ℚ) : q = 0 -- example (a b : ℚ) : a + b^3 = 0 := by -- test_polyrith [bad a, bad (b^2)] -- "{\"data\":[\"(poly.const 1/1)\",\"(poly.var 1)\"],\"success\":true}" -- ["ff", -- "rat", -- "2", -- "[(var0 - 0), ((var1 ^ 2) - 0)]", -- "((var0 + (var1 ^ 3)) - 0)"] -- "linear_combination bad a + b * bad (b ^ 2)" -- /-! ### Case over arbitrary field/ring -/ -- example {α} [h : CommRing α] {a b c d e f : α} (h1 : a*d = b*c) (h2 : c*f = e*d) : -- c * (a*f - b*e) = 0 := by -- test_polyrith -- "{\"data\":[\"(poly.var 4)\",\"(poly.var 1)\"],\"success\":true}" -- ["ff", -- "α", -- "6", -- "[((var1 * var5) - (var3 * var0)), ((var0 * var2) - (var4 * var5))]", -- "((var0 * ((var1 * var2) - (var3 * var4))) - 0)"] -- "linear_combination e * h1 + a * h2" -- example {K : Type*} [Field K] [Invertible 2] [Invertible 3] -- {ω p q r s t x : K} (hp_nonzero : p ≠ 0) (hr : r ^ 2 = q ^ 2 + p ^ 3) (hs3 : s ^ 3 = q + r) -- (ht : t * s = p) (x : K) (H : 1 + ω + ω ^ 2 = 0) : -- x ^ 3 + 3 * p * x - 2 * q = -- (x - (s - t)) * (x - (s * ω - t * ω ^ 2)) * (x - (s * ω ^ 2 - t * ω)) := by -- have hs_nonzero : s ≠ 0 := by -- contrapose! hp_nonzero with hs_nonzero -- test_polyrith -- "{\"data\":[\"(poly.const 0/1)\",\"(poly.const 0/1)\",\"(poly.const -1/1)\",\"(poly.const 0/1)\",\"(poly.var 4)\"],\"success\":true}" -- ["ff", -- "K", -- "6", -- "[((var1 ^ 2) - ((var2 ^ 2) + (var0 ^ 3))), ((var3 ^ 3) - (var2 + var1)), ((var4 * var3) - var0), (((1 + var5) + (var5 ^ 2)) - 0), (var3 - 0)]", -- "(var0 - 0)"] -- "linear_combination -ht + t * hs_nonzero"} -- have H' : 2 * q = s ^ 3 - t ^ 3 := by -- rw [← mul_left_inj' (pow_ne_zero 3 hs_nonzero)] -- test_polyrith -- "{\"data\":[\"(poly.const -1/1)\",\"(poly.sub (poly.add (poly.neg (poly.pow (poly.var 1) 3)) (poly.var 0)) (poly.var 3))\",\"(poly.add (poly.add (poly.mul (poly.pow (poly.var 1) 2) (poly.pow (poly.var 2) 2)) (poly.mul (poly.mul (poly.var 1) (poly.var 2)) (poly.var 4))) (poly.pow (poly.var 4) 2))\",\"(poly.const 0/1)\"],\"success\":true}" -- ["ff", -- "K", -- "6", -- "[((var3 ^ 2) - ((var0 ^ 2) + (var4 ^ 3))), ((var1 ^ 3) - (var0 + var3)), ((var2 * var1) - var4), (((1 + var5) + (var5 ^ 2)) - 0)]", -- "(((2 * var0) * (var1 ^ 3)) - (((var1 ^ 3) - (var2 ^ 3)) * (var1 ^ 3)))"] -- "linear_combination -hr + (-s ^ 3 + q - r) * hs3 + (s ^ 2 * t ^ 2 + s * t * p + p ^ 2) * ht"} -- test_polyrith -- "{\"data\":[\"(poly.const 0/1)\",\"(poly.const 0/1)\",\"(poly.add (poly.add (poly.sub (poly.add (poly.add (poly.sub (poly.add (poly.sub (poly.mul (poly.var 0) (poly.pow (poly.var 5) 4)) (poly.mul (poly.var 3) (poly.pow (poly.var 5) 4))) (poly.mul (poly.var 4) (poly.pow (poly.var 5) 4))) (poly.mul (poly.var 3) (poly.pow (poly.var 5) 3))) (poly.mul (poly.var 4) (poly.pow (poly.var 5) 3))) (poly.mul (poly.mul (poly.const 3/1) (poly.var 0)) (poly.pow (poly.var 5) 2))) (poly.mul (poly.var 3) (poly.pow (poly.var 5) 2))) (poly.mul (poly.var 4) (poly.pow (poly.var 5) 2))) (poly.mul (poly.mul (poly.const 2/1) (poly.var 0)) (poly.var 5)))\",\"(poly.add (poly.sub (poly.add (poly.sub (poly.sub (poly.add (poly.add (poly.sub (poly.add (poly.sub (poly.sub (poly.add (poly.neg (poly.mul (poly.mul (poly.var 0) (poly.pow (poly.var 3) 2)) (poly.var 5))) (poly.mul (poly.pow (poly.var 3) 3) (poly.var 5))) (poly.mul (poly.mul (poly.var 0) (poly.pow (poly.var 4) 2)) (poly.var 5))) (poly.mul (poly.pow (poly.var 4) 3) (poly.var 5))) (poly.mul (poly.mul (poly.var 0) (poly.var 1)) (poly.pow (poly.var 5) 2))) (poly.mul (poly.mul (poly.var 1) (poly.var 3)) (poly.pow (poly.var 5) 2))) (poly.mul (poly.mul (poly.var 1) (poly.var 4)) (poly.pow (poly.var 5) 2))) (poly.mul (poly.pow (poly.var 0) 2) (poly.var 3))) (poly.pow (poly.var 3) 3)) (poly.mul (poly.pow (poly.var 0) 2) (poly.var 4))) (poly.pow (poly.var 4) 3)) (poly.mul (poly.mul (poly.var 0) (poly.var 1)) (poly.var 5))) (poly.mul (poly.mul (poly.const 3/1) (poly.var 0)) (poly.var 1)))\",\"(poly.const -1/1)\"],\"success\":true}" -- ["ff", -- "K", -- "7", -- "[((var6 ^ 2) - ((var2 ^ 2) + (var1 ^ 3))), ((var3 ^ 3) - (var2 + var6)), ((var4 * var3) - var1), (((1 + var5) + (var5 ^ 2)) - 0), ((2 * var2) - ((var3 ^ 3) - (var4 ^ 3)))]", -- "((((var0 ^ 3) + ((3 * var1) * var0)) - (2 * var2)) - (((var0 - (var3 - var4)) * (var0 - ((var3 * var5) - (var4 * (var5 ^ 2))))) * (var0 - ((var3 * (var5 ^ 2)) - (var4 * var5)))))"] -- "linear_combination (x * ω ^ 4 - s * ω ^ 4 + t * ω ^ 4 - s * ω ^ 3 + t * ω ^ 3 + 3 * x * ω ^ 2 - s * ω ^ 2 + -- t * ω ^ 2 + -- 2 * x * ω) * ht + (-(x * s ^ 2 * ω) + s ^ 3 * ω - x * t ^ 2 * ω - t ^ 3 * ω + x * p * ω ^ 2 - p * s * ω ^ 2 + -- p * t * ω ^ 2 + -- x ^ 2 * s - -- s ^ 3 - -- x ^ 2 * t + -- t ^ 3 - -- x * p * ω + -- 3 * x * p) * H - H'" -- /-! ## Degenerate cases -/ -- example {K : Type*} [Field K] [CharZero K] {s : K} (hs : 3 * s + 1 = 4) : s = 1 := by -- test_polyrith -- "{\"data\":[\"(poly.const 1/3)\"],\"success\":true}" -- ["ff", -- "K", -- "1", -- "[(((3 * var0) + 1) - 4)]", -- "(var0 - 1)"] -- "linear_combination hs / 3" -- example {x : ℤ} (h1 : x + 4 = 2) : x = -2 := by -- test_polyrith -- "{\"data\":[\"(poly.const 1/1)\"],\"success\":true}" -- ["ff", -- "int", -- "1", -- "[((var0 + 4) - 2)]", -- "(var0 - -2)"] -- "linear_combination h1" -- example {w : ℚ} (h1 : 3 * w + 1 = 4) : w = 1 := by -- test_polyrith -- "{\"data\":[\"(poly.const 1/3)\"],\"success\":true}" -- ["ff", -- "rat", -- "1", -- "[(((3 * var0) + 1) - 4)]", -- "(var0 - 1)"] -- "linear_combination h1 / 3" -- example {x : ℤ} (h1 : 2 * x + 3 = x) : x = -3 := by -- test_polyrith -- "{\"data\":[\"(poly.const 1/1)\"],\"success\":true}" -- ["ff", -- "int", -- "1", -- "[(((2 * var0) + 3) - var0)]", -- "(var0 - -3)"] -- "linear_combination h1" -- example {c : ℚ} (h1 : 4 * c + 1 = 3 * c - 2) : c = -3 := by -- test_polyrith -- "{\"data\":[\"(poly.const 1/1)\"],\"success\":true}" -- ["ff", -- "rat", -- "1", -- "[(((4 * var0) + 1) - ((3 * var0) - 2))]", -- "(var0 - -3)"] -- "linear_combination h1" -- example (z : ℤ) (h1 : z + 1 = 2) (h2 : z + 2 = 2) : (1 : ℤ) = 2 := by -- test_polyrith -- "{\"data\":[\"(poly.const 1/1)\",\"(poly.const -1/1)\"],\"success\":true}" -- ["ff", -- "int", -- "1", -- "[((var0 + 1) - 2), ((var0 + 2) - 2)]", -- "(1 - 2)"] -- "linear_combination h1 - h2" -- example {R} [CommRing R] (x : R) (h2 : (2 : R) = 0) : x + x = 0 := by -- test_polyrith -- "{\"data\":[\"(poly.var 0)\"],\"success\":true}" -- ["ff", -- "R", -- "1", -- "[(2 - 0)]", -- "((var0 + var0) - 0)"] -- "linear_combination x * h2" -- example {R} [CommRing R] (_x : R) (h : (2 : R) = 4) : (0 : R) = 2 := by -- test_polyrith -- "{\"data\":[\"(poly.const 1/1)\"],\"success\":true}" -- ["ff", -- "R", -- "0", -- "[(2 - 4)]", -- "(0 - 2)"] -- "linear_combination h" -- We comment the following tests so that we don't overwhelm the SageCell API. /- /-! ### Standard Cases over ℤ, ℚ, and ℝ -/ example (x y : ℤ) (h1 : 3*x + 2*y = 10) : 3*x + 2*y = 10 := by polyrith example (x y : ℚ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by polyrith -- example (x y : ℝ) (h1 : x + 2 = -3) (h2 : y = 10) : -- -y + 2*x + 4 = -16 := by -- polyrith -- example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) -- (hc : x + 2*y + z = 2) : -- -3*x - 3*y - 4*z = 2 := by -- polyrith -- example (w x y z : ℝ) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5) -- (h3 : x + y + 5*z + 5*w = 3) : -- x + 2.2*y + 2*z - 5*w = -8.5 := by -- polyrith example (a b c d : ℚ) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) : 2*a - 3 + 9*c + 3*d = 8 - b + 3*d - 3*a := by polyrith /-! ### Case with ambiguous identifiers -/ -- set_option trace.Meta.Tactic.polyrith true example («def evil» y : ℤ) (h1 : 3*«def evil» + 2*y = 10) : 3*«def evil» + 2*y = 10 := by polyrith example («¥» y : ℤ) (h1 : 3*«¥» + 2*y = 10) : «¥» * (3*«¥» + 2*y) = 10 * «¥» := by polyrith /-! ### Cases with arbitrary coefficients -/ example (a b : ℤ) (h : a = b) : a * a = a * b := by polyrith example (a b c : ℤ) (h : a = b) : a * c = b * c := by polyrith example (a b c : ℤ) (h1 : a = b) (h2 : b = 1) : c * a + b = c * b + 1 := by polyrith example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) : x*x*y + y*x*y + 6*x = 3*x*y + 14 := by polyrith example (x y z w : ℚ) (hzw : z = w) : x*z + 2*y*z = x*w + 2*y*w := by polyrith /-! ### Cases with non-hypothesis inputs/input restrictions -/ -- example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) (hignore : 3 = a + b) : -- b = 2 / 3 := -- by polyrith only [ha, hab] axiom term : ∀ a b : ℚ, a + b = 0 example (a b c d : ℚ) (h : a + b = 0) (h2 : b + c = 0) : a + b + c + d = 0 := by polyrith only [term c d, h] axiom qc : ℚ axiom hqc : qc = 2*qc example (a b : ℚ) (h : ∀ p q : ℚ, p = q) : 3*a + qc = 3*b + 2*qc := by polyrith [h a b, hqc] axiom bad (q : ℚ) : q = 0 example (a b : ℚ) : a + b^3 = 0 := by polyrith [bad a, bad (b^2)] /-! ### Case over arbitrary field/ring -/ example {α} [h : CommRing α] {a b c d e f : α} (h1 : a*d = b*c) (h2 : c*f = e*d) : c * (a*f - b*e) = 0 := by polyrith -- example {K : Type*} [Field K] [Invertible 2] [Invertible 3] -- {ω p q r s t x : K} (hp_nonzero : p ≠ 0) (hr : r ^ 2 = q ^ 2 + p ^ 3) (hs3 : s ^ 3 = q + r) -- (ht : t * s = p) (x : K) (H : 1 + ω + ω ^ 2 = 0) : -- x ^ 3 + 3 * p * x - 2 * q = -- (x - (s - t)) * (x - (s * ω - t * ω ^ 2)) * (x - (s * ω ^ 2 - t * ω)) := by -- have hs_nonzero : s ≠ 0 := by -- contrapose! hp_nonzero with hs_nonzero -- polyrith -- have H' : 2 * q = s ^ 3 - t ^ 3 := by -- rw [← mul_left_inj' (pow_ne_zero 3 hs_nonzero)] -- polyrith -- polyrith /- ### Examples with exponent -/ example (x y z : ℚ) (h : x = y) (h2 : x * y = 0) : x + y*z = 0 := by polyrith example (K : Type) [Field K] [CharZero K] {x y z : K} (h₂ : y ^ 3 + x * (3 * z ^ 2) = 0) (h₁ : x ^ 3 + z * (3 * y ^ 2) = 0) (h₀ : y * (3 * x ^ 2) + z ^ 3 = 0) (h : x ^ 3 * y + y ^ 3 * z + z ^ 3 * x = 0) : x = 0 := by polyrith /-! ### With trace enabled Here, the tactic will trace the command that gets sent to sage, and so the tactic will not prove the goal. `linear_combination` is called manually to prevent errors. -/ set_option trace.Meta.Tactic.polyrith true -- example (x y : ℝ) (h1 : x + 2 = -3) (h2 : y = 10) : -y + 2*x + 4 = -16 := by -- polyrith -- linear_combination 2 * h1 - h2 example (a b c : ℤ) (h1 : a = b) (h2 : b = 1) : c * a + b = c * b + 1 := by polyrith linear_combination c * h1 + h2 example (a b c d : ℚ) (h : a + b = 0) (h2 : b + c = 0) : a + b + c + d = 0 := by polyrith only [term c d, h] linear_combination term c d + h example (a b : ℚ) (h : ∀ p q : ℚ, p = q) : 3*a + qc = 3*b + 2*qc := by polyrith [h a b, hqc] linear_combination 3 * h a b + hqc -/ -- the following can be uncommented to regenerate the tests above. /- /-! ### Standard Cases over ℤ, ℚ, and ℝ -/ example (x y : ℤ) (h1 : 3*x + 2*y = 10) : 3*x + 2*y = 10 := by create_polyrith_test example (x y : ℚ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by create_polyrith_test example (x y : ℝ) (h1 : x + 2 = -3) (h2 : y = 10) : -y + 2*x + 4 = -16 := by create_polyrith_test example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) (hc : x + 2*y + z = 2) : -3*x - 3*y - 4*z = 2 := by create_polyrith_test example (w x y z : ℝ) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5) (h3 : x + y + 5*z + 5*w = 3) : x + 2.2*y + 2*z - 5*w = -8.5 := by create_polyrith_test example (a b c d : ℚ) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) : 2*a - 3 + 9*c + 3*d = 8 - b + 3*d - 3*a := by create_polyrith_test /-! ### Case with ambiguous identifiers -/ example («def evil» y : ℤ) (h1 : 3*«def evil» + 2*y = 10) : 3*«def evil» + 2*y = 10 := by create_polyrith_test example («¥» y : ℤ) (h1 : 3*«¥» + 2*y = 10) : «¥» * (3*«¥» + 2*y) = 10 * «¥» := by create_polyrith_test /-! ### Cases with arbitrary coefficients -/ example (a b : ℤ) (h : a = b) : a * a = a * b := by create_polyrith_test example (a b c : ℤ) (h : a = b) : a * c = b * c := by create_polyrith_test example (a b c : ℤ) (h1 : a = b) (h2 : b = 1) : c * a + b = c * b + 1 := by create_polyrith_test example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) : x*x*y + y*x*y + 6*x = 3*x*y + 14 := by create_polyrith_test example (x y z w : ℚ) (hzw : z = w) : x*z + 2*y*z = x*w + 2*y*w := by create_polyrith_test /-! ### Cases with non-hypothesis inputs/input restrictions -/ example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) (hignore : 3 = a + b) : b = 2 / 3 := by create_polyrith_test only [ha, hab] constant term : ∀ a b : ℚ, a + b = 0 example (a b c d : ℚ) (h : a + b = 0) (h2 : b + c = 0) : a + b + c + d = 0 := by create_polyrith_test only [term c d, h] constants (qc : ℚ) (hqc : qc = 2*qc) example (a b : ℚ) (h : ∀ p q : ℚ, p = q) : 3*a + qc = 3*b + 2*qc := by create_polyrith_test [h a b, hqc] constant bad (q : ℚ) : q = 0 example (a b : ℚ) : a + b^3 = 0 := by create_polyrith_test [bad a, bad (b^2)] /-! ### Case over arbitrary field/ring -/ example {α} [h : CommRing α] {a b c d e f : α} (h1 : a*d = b*c) (h2 : c*f = e*d) : c * (a*f - b*e) = 0 := by create_polyrith_test example {K : Type*} [Field K] [Invertible 2] [Invertible 3] {ω p q r s t x : K} (hp_nonzero : p ≠ 0) (hr : r ^ 2 = q ^ 2 + p ^ 3) (hs3 : s ^ 3 = q + r) (ht : t * s = p) (x : K) (H : 1 + ω + ω ^ 2 = 0) : x ^ 3 + 3 * p * x - 2 * q = (x - (s - t)) * (x - (s * ω - t * ω ^ 2)) * (x - (s * ω ^ 2 - t * ω)) := by have hs_nonzero : s ≠ 0 := by contrapose! hp_nonzero with hs_nonzero create_polyrith_test have H' : 2 * q = s ^ 3 - t ^ 3 := by rw [← mul_left_inj' (pow_ne_zero 3 hs_nonzero)] create_polyrith_test create_polyrith_test /-! ## Degenerate cases -/ example {K : Type*} [Field K] [CharZero K] {s : K} (hs : 3 * s + 1 = 4) : s = 1 := by create_polyrith_test example {x : ℤ} (h1 : x + 4 = 2) : x = -2 := by create_polyrith_test example {w : ℚ} (h1 : 3 * w + 1 = 4) : w = 1 := by create_polyrith_test example {x : ℤ} (h1 : 2 * x + 3 = x) : x = -3 := by create_polyrith_test example {c : ℚ} (h1 : 4 * c + 1 = 3 * c - 2) : c = -3 := by create_polyrith_test example (z : ℤ) (h1 : z + 1 = 2) (h2 : z + 2 = 2) : (1 : ℤ) = 2 := by create_polyrith_test -/ -- example (a b : ℤ) (h : a + b = 4) : a + b = 0 := by -- fail_if_success polyrith -- -- polyrith failed to retrieve a solution from Sage! -- -- ValueError: polynomial is not in the ideal -- sorry -- example (a : ℕ) : a = 0 := by -- have := True.intro -- polyrith -- polyrith did not find any relevant hypotheses and the goal is not provable by ring -- example (y a : ℤ) (k : ℕ) (h : a ^ k = 0) : a ^ k * y = 0 := by -- polyrith
Pairwise.lean
/- Copyright (c) 2024 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import Mathlib.Data.FunLike.Equiv import Mathlib.Logic.Pairwise /-! # Interaction of equivalences with `Pairwise` -/ open scoped Function -- required for scoped `on` notation lemma EmbeddingLike.pairwise_comp {X : Type*} {Y : Type*} {F} [FunLike F Y X] [EmbeddingLike F Y X] (f : F) {p : X → X → Prop} (h : Pairwise p) : Pairwise (p on f) := h.comp_of_injective <| EmbeddingLike.injective f lemma EquivLike.pairwise_comp_iff {X : Type*} {Y : Type*} {F} [EquivLike F Y X] (f : F) (p : X → X → Prop) : Pairwise (p on f) ↔ Pairwise p := (EquivLike.bijective f).pairwise_comp_iff
Basic.lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Analysis.Calculus.ContDiff.Operations import Mathlib.Analysis.Normed.Module.Convex import Mathlib.Analysis.RCLike.TangentCone import Mathlib.Data.Bundle import Mathlib.Geometry.Manifold.ChartedSpace /-! # `C^n` manifolds (possibly with boundary or corners) A `C^n` manifold is a manifold modelled on a normed vector space, or a subset like a half-space (to get manifolds with boundaries) for which the changes of coordinates are `C^n` maps. We define a model with corners as a map `I : H → E` embedding nicely the topological space `H` in the vector space `E` (or more precisely as a structure containing all the relevant properties). Given such a model with corners `I` on `(E, H)`, we define the groupoid of local homeomorphisms of `H` which are `C^n` when read in `E` (for any regularity `n : WithTop ℕ∞`). With this groupoid at hand and the general machinery of charted spaces, we thus get the notion of `C^n` manifold with respect to any model with corners `I` on `(E, H)`. Some texts assume manifolds to be Hausdorff and second countable. We (in mathlib) assume neither, but add these assumptions later as needed. (Quite a few results still do not require them.) ## Main definitions * `ModelWithCorners 𝕜 E H` : a structure containing information on the way a space `H` embeds in a model vector space E over the field `𝕜`. This is all that is needed to define a `C^n` manifold with model space `H`, and model vector space `E`. * `modelWithCornersSelf 𝕜 E` : trivial model with corners structure on the space `E` embedded in itself by the identity. * `contDiffGroupoid n I` : when `I` is a model with corners on `(𝕜, E, H)`, this is the groupoid of partial homeos of `H` which are of class `C^n` over the normed field `𝕜`, when read in `E`. * `IsManifold I n M` : a type class saying that the charted space `M`, modelled on the space `H`, has `C^n` changes of coordinates with respect to the model with corners `I` on `(𝕜, E, H)`. This type class is just a shortcut for `HasGroupoid M (contDiffGroupoid n I)`. We define a few constructions of smooth manifolds: * every empty type is a smooth manifold * `IsManifold.of_discreteTopoloy`: a discrete space is a smooth manifold (over the trivial model with corners on the trivial space) * the product of two smooth manifolds * the disjoint union of two manifolds (over the same charted space) As specific examples of models with corners, we define (in `Geometry.Manifold.Instances.Real`) * `modelWithCornersEuclideanHalfSpace n : ModelWithCorners ℝ (EuclideanSpace ℝ (Fin n)) (EuclideanHalfSpace n)` for the model space used to define `n`-dimensional real manifolds without boundary (with notation `𝓡 n` in the locale `Manifold`) * `modelWithCornersEuclideanHalfSpace n : ModelWithCorners ℝ (EuclideanSpace ℝ (Fin n)) (EuclideanHalfSpace n)` for the model space used to define `n`-dimensional real manifolds with boundary (with notation `𝓡∂ n` in the locale `Manifold`) * `modelWithCornersEuclideanQuadrant n : ModelWithCorners ℝ (EuclideanSpace ℝ (Fin n)) (EuclideanQuadrant n)` for the model space used to define `n`-dimensional real manifolds with corners With these definitions at hand, to invoke an `n`-dimensional `C^∞` real manifold without boundary, one could use `variable {n : ℕ} {M : Type*} [TopologicalSpace M] [ChartedSpace (EuclideanSpace ℝ (Fin n)) M] [IsManifold (𝓡 n) ∞ M]`. However, this is not the recommended way: a theorem proved using this assumption would not apply for instance to the tangent space of such a manifold, which is modelled on `(EuclideanSpace ℝ (Fin n)) × (EuclideanSpace ℝ (Fin n))` and not on `EuclideanSpace ℝ (Fin (2 * n))`! In the same way, it would not apply to product manifolds, modelled on `(EuclideanSpace ℝ (Fin n)) × (EuclideanSpace ℝ (Fin m))`. The right invocation does not focus on one specific construction, but on all constructions sharing the right properties, like `variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [FiniteDimensional ℝ E] {I : ModelWithCorners ℝ E E} [I.Boundaryless] {M : Type*} [TopologicalSpace M] [ChartedSpace E M] [IsManifold I ∞ M]` Here, `I.Boundaryless` is a typeclass property ensuring that there is no boundary (this is for instance the case for `modelWithCornersSelf`, or products of these). Note that one could consider as a natural assumption to only use the trivial model with corners `modelWithCornersSelf ℝ E`, but again in product manifolds the natural model with corners will not be this one but the product one (and they are not defeq as `(fun p : E × F ↦ (p.1, p.2))` is not defeq to the identity). So, it is important to use the above incantation to maximize the applicability of theorems. Even better, if the result should apply in a parallel way to smooth manifolds and to analytic manifolds, the last typeclass should be replaced with `[IsManifold I n M]` for `n : WithTop ℕ∞`. We also define `TangentSpace I (x : M)` as a type synonym of `E`, and `TangentBundle I M` as a type synonym for `Π (x : M), TangentSpace I x` (in the form of an abbrev of `Bundle.TotalSpace E (TangentSpace I : M → Type _)`). Apart from basic typeclasses on `TangentSpace I x`, nothing is proved about them in this file, but it is useful to have them available as definitions early on to get a clean import structure below. The smooth bundle structure is defined in `VectorBundle.Tangent`, while the definition is used to talk about manifold derivatives in `MFDeriv.Basic`, and neither file needs import the other. ## Implementation notes We want to talk about manifolds modelled on a vector space, but also on manifolds with boundary, modelled on a half space (or even manifolds with corners). For the latter examples, we still want to define smooth functions, tangent bundles, and so on. As smooth functions are well defined on vector spaces or subsets of these, one could take for model space a subtype of a vector space. With the drawback that the whole vector space itself (which is the most basic example) is not directly a subtype of itself: the inclusion of `univ : Set E` in `Set E` would show up in the definition, instead of `id`. A good abstraction covering both cases it to have a vector space `E` (with basic example the Euclidean space), a model space `H` (with basic example the upper half space), and an embedding of `H` into `E` (which can be the identity for `H = E`, or `Subtype.val` for manifolds with corners). We say that the pair `(E, H)` with their embedding is a model with corners, and we encompass all the relevant properties (in particular the fact that the image of `H` in `E` should have unique differentials) in the definition of `ModelWithCorners`. I have considered using the model with corners `I` as a typeclass argument, possibly `outParam`, to get lighter notations later on, but it did not turn out right, as on `E × F` there are two natural model with corners, the trivial (identity) one, and the product one, and they are not defeq and one needs to indicate to Lean which one we want to use. This means that when talking on objects on manifolds one will most often need to specify the model with corners one is using. For instance, the tangent bundle will be `TangentBundle I M` and the derivative will be `mfderiv I I' f`, instead of the more natural notations `TangentBundle 𝕜 M` and `mfderiv 𝕜 f` (the field has to be explicit anyway, as some manifolds could be considered both as real and complex manifolds). -/ open Topology noncomputable section universe u v w u' v' w' open Set Filter Function open scoped Manifold Topology ContDiff /-! ### Models with corners. -/ open scoped Classical in /-- A structure containing information on the way a space `H` embeds in a model vector space `E` over the field `𝕜`. This is all what is needed to define a `C^n` manifold with model space `H`, and model vector space `E`. We require that, when the field is `ℝ` or `ℂ`, the range is `ℝ`-convex, as this is what is needed to do calculus and covers the standard examples of manifolds with boundary. Over other fields, we require that the range is `univ`, as there is no relevant notion of manifold of boundary there. -/ @[ext] structure ModelWithCorners (𝕜 : Type*) [NontriviallyNormedField 𝕜] (E : Type*) [NormedAddCommGroup E] [NormedSpace 𝕜 E] (H : Type*) [TopologicalSpace H] extends PartialEquiv H E where source_eq : source = univ /-- To check this condition when the space already has a real normed space structure, use `Convex.convex_isRCLikeNormedField` which eliminates the `letI`s below, or the constructor `ModelWithCorners.of_convex_range` -/ convex_range' : if h : IsRCLikeNormedField 𝕜 then letI := h.rclike 𝕜 letI : NormedSpace ℝ E := NormedSpace.restrictScalars ℝ 𝕜 E Convex ℝ (range toPartialEquiv) else range toPartialEquiv = univ nonempty_interior' : (interior (range toPartialEquiv)).Nonempty continuous_toFun : Continuous toFun := by continuity continuous_invFun : Continuous invFun := by continuity lemma ModelWithCorners.range_eq_target {𝕜 E H : Type*} [NontriviallyNormedField 𝕜] [NormedAddCommGroup E] [NormedSpace 𝕜 E] [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) : range I.toPartialEquiv = I.target := by rw [← I.image_source_eq_target, I.source_eq, image_univ.symm] /-- If a model with corners has full range, the `convex_range'` condition is satisfied. -/ def ModelWithCorners.of_target_univ (𝕜 : Type*) [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (φ : PartialEquiv H E) (hsource : φ.source = univ) (htarget : φ.target = univ) (hcont : Continuous φ) (hcont_inv : Continuous φ.symm) : ModelWithCorners 𝕜 E H where toPartialEquiv := φ source_eq := hsource convex_range' := by have : range φ = φ.target := by rw [← φ.image_source_eq_target, hsource, image_univ.symm] simp only [this, htarget, dite_else_true] intro h letI := h.rclike 𝕜 letI := NormedSpace.restrictScalars ℝ 𝕜 E exact convex_univ nonempty_interior' := by have : range φ = φ.target := by rw [← φ.image_source_eq_target, hsource, image_univ.symm] simp [this, htarget] attribute [simp, mfld_simps] ModelWithCorners.source_eq /-- A vector space is a model with corners, denoted as `𝓘(𝕜, E)` within the `Manifold` namespace. -/ def modelWithCornersSelf (𝕜 : Type*) [NontriviallyNormedField 𝕜] (E : Type*) [NormedAddCommGroup E] [NormedSpace 𝕜 E] : ModelWithCorners 𝕜 E E := ModelWithCorners.of_target_univ 𝕜 (PartialEquiv.refl E) rfl rfl continuous_id continuous_id @[inherit_doc] scoped[Manifold] notation "𝓘(" 𝕜 ", " E ")" => modelWithCornersSelf 𝕜 E /-- A normed field is a model with corners. -/ scoped[Manifold] notation "𝓘(" 𝕜 ")" => modelWithCornersSelf 𝕜 𝕜 section variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) namespace ModelWithCorners /-- Coercion of a model with corners to a function. We don't use `e.toFun` because it is actually `e.toPartialEquiv.toFun`, so `simp` will apply lemmas about `toPartialEquiv`. While we may want to switch to this behavior later, doing it mid-port will break a lot of proofs. -/ @[coe] def toFun' (e : ModelWithCorners 𝕜 E H) : H → E := e.toFun instance : CoeFun (ModelWithCorners 𝕜 E H) fun _ => H → E := ⟨toFun'⟩ /-- The inverse to a model with corners, only registered as a `PartialEquiv`. -/ protected def symm : PartialEquiv E H := I.toPartialEquiv.symm /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def Simps.apply (𝕜 : Type*) [NontriviallyNormedField 𝕜] (E : Type*) [NormedAddCommGroup E] [NormedSpace 𝕜 E] (H : Type*) [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) : H → E := I /-- See Note [custom simps projection] -/ def Simps.symm_apply (𝕜 : Type*) [NontriviallyNormedField 𝕜] (E : Type*) [NormedAddCommGroup E] [NormedSpace 𝕜 E] (H : Type*) [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) : E → H := I.symm initialize_simps_projections ModelWithCorners (toFun → apply, invFun → symm_apply) -- Register a few lemmas to make sure that `simp` puts expressions in normal form @[simp, mfld_simps] theorem toPartialEquiv_coe : (I.toPartialEquiv : H → E) = I := rfl @[simp, mfld_simps] theorem mk_coe (e : PartialEquiv H E) (a b c d d') : ((ModelWithCorners.mk e a b c d d' : ModelWithCorners 𝕜 E H) : H → E) = (e : H → E) := rfl @[simp, mfld_simps] theorem toPartialEquiv_coe_symm : (I.toPartialEquiv.symm : E → H) = I.symm := rfl @[simp, mfld_simps] theorem mk_symm (e : PartialEquiv H E) (a b c d d') : (ModelWithCorners.mk e a b c d d' : ModelWithCorners 𝕜 E H).symm = e.symm := rfl @[continuity] protected theorem continuous : Continuous I := I.continuous_toFun protected theorem continuousAt {x} : ContinuousAt I x := I.continuous.continuousAt protected theorem continuousWithinAt {s x} : ContinuousWithinAt I s x := I.continuousAt.continuousWithinAt @[continuity] theorem continuous_symm : Continuous I.symm := I.continuous_invFun theorem continuousAt_symm {x} : ContinuousAt I.symm x := I.continuous_symm.continuousAt theorem continuousWithinAt_symm {s x} : ContinuousWithinAt I.symm s x := I.continuous_symm.continuousWithinAt theorem continuousOn_symm {s} : ContinuousOn I.symm s := I.continuous_symm.continuousOn @[simp, mfld_simps] theorem target_eq : I.target = range (I : H → E) := by rw [← image_univ, ← I.source_eq] exact I.image_source_eq_target.symm theorem nonempty_interior : (interior (range I)).Nonempty := I.nonempty_interior' theorem range_eq_univ_of_not_isRCLikeNormedField (h : ¬ IsRCLikeNormedField 𝕜) : range I = univ := by simpa [h] using I.convex_range' /-- If a set is `ℝ`-convex for some normed space structure, then it is `ℝ`-convex for the normed space structure coming from an `IsRCLikeNormedField 𝕜`. Useful when constructing model spaces to avoid diamond issues when populating the field `convex_range'`. -/ lemma _root_.Convex.convex_isRCLikeNormedField [NormedSpace ℝ E] [h : IsRCLikeNormedField 𝕜] {s : Set E} (hs : Convex ℝ s) : letI := h.rclike letI := NormedSpace.restrictScalars ℝ 𝕜 E Convex ℝ s := by letI := h.rclike letI := NormedSpace.restrictScalars ℝ 𝕜 E simp only [Convex, StarConvex] at hs ⊢ intro u hu v hv a b ha hb hab convert hs hu hv ha hb hab using 2 · rw [← @algebraMap_smul (R := ℝ) (A := 𝕜), ← @algebraMap_smul (R := ℝ) (A := 𝕜)] · rw [← @algebraMap_smul (R := ℝ) (A := 𝕜), ← @algebraMap_smul (R := ℝ) (A := 𝕜)] /-- Construct a model with corners over `ℝ` from a continuous partial equiv with convex range. -/ def of_convex_range {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] {H : Type*} [TopologicalSpace H] (φ : PartialEquiv H E) (hsource : φ.source = univ) (htarget : Convex ℝ φ.target) (hcont : Continuous φ) (hcont_inv : Continuous φ.symm) (hint : (interior φ.target).Nonempty) : ModelWithCorners ℝ E H where toPartialEquiv := φ source_eq := hsource convex_range' := by have : range φ = φ.target := by rw [← φ.image_source_eq_target, hsource, image_univ.symm] simp only [instIsRCLikeNormedField, ↓reduceDIte, this] exact htarget.convex_isRCLikeNormedField nonempty_interior' := by have : range φ = φ.target := by rw [← φ.image_source_eq_target, hsource, image_univ.symm] simp [this, hint] theorem convex_range [NormedSpace ℝ E] : Convex ℝ (range I) := by by_cases h : IsRCLikeNormedField 𝕜 · letI : RCLike 𝕜 := h.rclike have W := I.convex_range' simp only [h, ↓reduceDIte, toPartialEquiv_coe] at W simp only [Convex, StarConvex] at W ⊢ intro u hu v hv a b ha hb hab convert W hu hv ha hb hab using 2 · rw [← @algebraMap_smul (R := ℝ) (A := 𝕜)] rfl · rw [← @algebraMap_smul (R := ℝ) (A := 𝕜)] rfl · simp [range_eq_univ_of_not_isRCLikeNormedField I h, convex_univ] protected theorem uniqueDiffOn : UniqueDiffOn 𝕜 (range I) := by by_cases h : IsRCLikeNormedField 𝕜 · letI := h.rclike 𝕜 letI := NormedSpace.restrictScalars ℝ 𝕜 E apply uniqueDiffOn_convex_of_isRCLikeNormedField _ I.nonempty_interior simpa [h] using I.convex_range · simp [range_eq_univ_of_not_isRCLikeNormedField I h, uniqueDiffOn_univ] theorem range_subset_closure_interior : range I ⊆ closure (interior (range I)) := by by_cases h : IsRCLikeNormedField 𝕜 · letI := h.rclike 𝕜 letI := NormedSpace.restrictScalars ℝ 𝕜 E rw [Convex.closure_interior_eq_closure_of_nonempty_interior (𝕜 := ℝ)] · apply subset_closure · apply I.convex_range · apply I.nonempty_interior · simp [range_eq_univ_of_not_isRCLikeNormedField I h] @[simp, mfld_simps] protected theorem left_inv (x : H) : I.symm (I x) = x := by refine I.left_inv' ?_; simp protected theorem leftInverse : LeftInverse I.symm I := I.left_inv theorem injective : Injective I := I.leftInverse.injective @[simp, mfld_simps] theorem symm_comp_self : I.symm ∘ I = id := I.leftInverse.comp_eq_id protected theorem rightInvOn : RightInvOn I.symm I (range I) := I.leftInverse.rightInvOn_range @[simp, mfld_simps] protected theorem right_inv {x : E} (hx : x ∈ range I) : I (I.symm x) = x := I.rightInvOn hx theorem preimage_image (s : Set H) : I ⁻¹' (I '' s) = s := I.injective.preimage_image s protected theorem image_eq (s : Set H) : I '' s = I.symm ⁻¹' s ∩ range I := by refine (I.toPartialEquiv.image_eq_target_inter_inv_preimage ?_).trans ?_ · rw [I.source_eq]; exact subset_univ _ · rw [inter_comm, I.target_eq, I.toPartialEquiv_coe_symm] theorem isClosedEmbedding : IsClosedEmbedding I := I.leftInverse.isClosedEmbedding I.continuous_symm I.continuous theorem isClosed_range : IsClosed (range I) := I.isClosedEmbedding.isClosed_range theorem range_eq_closure_interior : range I = closure (interior (range I)) := Subset.antisymm I.range_subset_closure_interior I.isClosed_range.closure_interior_subset theorem map_nhds_eq (x : H) : map I (𝓝 x) = 𝓝[range I] I x := I.isClosedEmbedding.isEmbedding.map_nhds_eq x theorem map_nhdsWithin_eq (s : Set H) (x : H) : map I (𝓝[s] x) = 𝓝[I '' s] I x := I.isClosedEmbedding.isEmbedding.map_nhdsWithin_eq s x theorem image_mem_nhdsWithin {x : H} {s : Set H} (hs : s ∈ 𝓝 x) : I '' s ∈ 𝓝[range I] I x := I.map_nhds_eq x ▸ image_mem_map hs theorem symm_map_nhdsWithin_image {x : H} {s : Set H} : map I.symm (𝓝[I '' s] I x) = 𝓝[s] x := by rw [← I.map_nhdsWithin_eq, map_map, I.symm_comp_self, map_id] theorem symm_map_nhdsWithin_range (x : H) : map I.symm (𝓝[range I] I x) = 𝓝 x := by rw [← I.map_nhds_eq, map_map, I.symm_comp_self, map_id] theorem uniqueDiffOn_preimage {s : Set H} (hs : IsOpen s) : UniqueDiffOn 𝕜 (I.symm ⁻¹' s ∩ range I) := by rw [inter_comm] exact I.uniqueDiffOn.inter (hs.preimage I.continuous_invFun) theorem uniqueDiffOn_preimage_source {β : Type*} [TopologicalSpace β] {e : PartialHomeomorph H β} : UniqueDiffOn 𝕜 (I.symm ⁻¹' e.source ∩ range I) := I.uniqueDiffOn_preimage e.open_source theorem uniqueDiffWithinAt_image {x : H} : UniqueDiffWithinAt 𝕜 (range I) (I x) := I.uniqueDiffOn _ (mem_range_self _) theorem symm_continuousWithinAt_comp_right_iff {X} [TopologicalSpace X] {f : H → X} {s : Set H} {x : H} : ContinuousWithinAt (f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) (I x) ↔ ContinuousWithinAt f s x := by refine ⟨fun h => ?_, fun h => ?_⟩ · have := h.comp I.continuousWithinAt (mapsTo_preimage _ _) simp_rw [preimage_inter, preimage_preimage, I.left_inv, preimage_id', preimage_range, inter_univ] at this rwa [Function.comp_assoc, I.symm_comp_self] at this · rw [← I.left_inv x] at h; exact h.comp I.continuousWithinAt_symm inter_subset_left protected theorem locallyCompactSpace [LocallyCompactSpace E] (I : ModelWithCorners 𝕜 E H) : LocallyCompactSpace H := by have : ∀ x : H, (𝓝 x).HasBasis (fun s => s ∈ 𝓝 (I x) ∧ IsCompact s) fun s => I.symm '' (s ∩ range I) := fun x ↦ by rw [← I.symm_map_nhdsWithin_range] exact ((compact_basis_nhds (I x)).inf_principal _).map _ refine .of_hasBasis this ?_ rintro x s ⟨-, hsc⟩ exact (hsc.inter_right I.isClosed_range).image I.continuous_symm open TopologicalSpace protected theorem secondCountableTopology [SecondCountableTopology E] (I : ModelWithCorners 𝕜 E H) : SecondCountableTopology H := I.isClosedEmbedding.isEmbedding.secondCountableTopology include I in /-- Every manifold is a Fréchet space (T1 space) -- regardless of whether it is Hausdorff. -/ protected theorem t1Space (M : Type*) [TopologicalSpace M] [ChartedSpace H M] : T1Space M := by have : T2Space H := I.isClosedEmbedding.toIsEmbedding.t2Space exact ChartedSpace.t1Space H M end ModelWithCorners section variable (𝕜 E) /-- In the trivial model with corners, the associated `PartialEquiv` is the identity. -/ @[simp, mfld_simps] theorem modelWithCornersSelf_partialEquiv : 𝓘(𝕜, E).toPartialEquiv = PartialEquiv.refl E := rfl @[simp, mfld_simps] theorem modelWithCornersSelf_coe : (𝓘(𝕜, E) : E → E) = id := rfl @[simp, mfld_simps] theorem modelWithCornersSelf_coe_symm : (𝓘(𝕜, E).symm : E → E) = id := rfl end end section ModelWithCornersProd /-- Given two model_with_corners `I` on `(E, H)` and `I'` on `(E', H')`, we define the model with corners `I.prod I'` on `(E × E', ModelProd H H')`. This appears in particular for the manifold structure on the tangent bundle to a manifold modelled on `(E, H)`: it will be modelled on `(E × E, H × E)`. See note [Manifold type tags] for explanation about `ModelProd H H'` vs `H × H'`. -/ @[simps -isSimp] def ModelWithCorners.prod {𝕜 : Type u} [NontriviallyNormedField 𝕜] {E : Type v} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type w} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) {E' : Type v'} [NormedAddCommGroup E'] [NormedSpace 𝕜 E'] {H' : Type w'} [TopologicalSpace H'] (I' : ModelWithCorners 𝕜 E' H') : ModelWithCorners 𝕜 (E × E') (ModelProd H H') := { I.toPartialEquiv.prod I'.toPartialEquiv with toFun := fun x => (I x.1, I' x.2) invFun := fun x => (I.symm x.1, I'.symm x.2) source := { x | x.1 ∈ I.source ∧ x.2 ∈ I'.source } source_eq := by simp only [setOf_true, mfld_simps] convex_range' := by have : range (fun (x : ModelProd H H') ↦ (I x.1, I' x.2)) = range (Prod.map I I') := rfl rw [this, Set.range_prodMap] split_ifs with h · letI := h.rclike letI := NormedSpace.restrictScalars ℝ 𝕜 E; letI := NormedSpace.restrictScalars ℝ 𝕜 E' exact I.convex_range.prod I'.convex_range · simp [range_eq_univ_of_not_isRCLikeNormedField, h] nonempty_interior' := by have : range (fun (x : ModelProd H H') ↦ (I x.1, I' x.2)) = range (Prod.map I I') := rfl simp [this, interior_prod_eq, nonempty_interior] continuous_toFun := I.continuous_toFun.prodMap I'.continuous_toFun continuous_invFun := I.continuous_invFun.prodMap I'.continuous_invFun } /-- Given a finite family of `ModelWithCorners` `I i` on `(E i, H i)`, we define the model with corners `pi I` on `(Π i, E i, ModelPi H)`. See note [Manifold type tags] for explanation about `ModelPi H`. -/ def ModelWithCorners.pi {𝕜 : Type u} [NontriviallyNormedField 𝕜] {ι : Type v} [Fintype ι] {E : ι → Type w} [∀ i, NormedAddCommGroup (E i)] [∀ i, NormedSpace 𝕜 (E i)] {H : ι → Type u'} [∀ i, TopologicalSpace (H i)] (I : ∀ i, ModelWithCorners 𝕜 (E i) (H i)) : ModelWithCorners 𝕜 (∀ i, E i) (ModelPi H) where toPartialEquiv := PartialEquiv.pi fun i => (I i).toPartialEquiv source_eq := by simp only [pi_univ, mfld_simps] convex_range' := by rw [PartialEquiv.pi_apply, Set.range_piMap] split_ifs with h · letI := h.rclike letI := fun i ↦ NormedSpace.restrictScalars ℝ 𝕜 (E i) exact convex_pi fun i _hi ↦ (I i).convex_range · simp [range_eq_univ_of_not_isRCLikeNormedField, h] nonempty_interior' := by rw [PartialEquiv.pi_apply, Set.range_piMap] simp [interior_pi_set finite_univ, univ_pi_nonempty_iff, nonempty_interior] continuous_toFun := continuous_pi fun i => (I i).continuous.comp (continuous_apply i) continuous_invFun := continuous_pi fun i => (I i).continuous_symm.comp (continuous_apply i) /-- Special case of product model with corners, which is trivial on the second factor. This shows up as the model to tangent bundles. -/ abbrev ModelWithCorners.tangent {𝕜 : Type u} [NontriviallyNormedField 𝕜] {E : Type v} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type w} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) : ModelWithCorners 𝕜 (E × E) (ModelProd H E) := I.prod 𝓘(𝕜, E) variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {E' : Type*} [NormedAddCommGroup E'] [NormedSpace 𝕜 E'] {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] {H : Type*} [TopologicalSpace H] {H' : Type*} [TopologicalSpace H'] {G : Type*} [TopologicalSpace G] {I : ModelWithCorners 𝕜 E H} {J : ModelWithCorners 𝕜 F G} @[simp, mfld_simps] theorem modelWithCorners_prod_toPartialEquiv : (I.prod J).toPartialEquiv = I.toPartialEquiv.prod J.toPartialEquiv := rfl @[simp, mfld_simps] theorem modelWithCorners_prod_coe (I : ModelWithCorners 𝕜 E H) (I' : ModelWithCorners 𝕜 E' H') : (I.prod I' : _ × _ → _ × _) = Prod.map I I' := rfl @[simp, mfld_simps] theorem modelWithCorners_prod_coe_symm (I : ModelWithCorners 𝕜 E H) (I' : ModelWithCorners 𝕜 E' H') : ((I.prod I').symm : _ × _ → _ × _) = Prod.map I.symm I'.symm := rfl /-- This lemma should be erased, or at least burn in hell, as it uses bad defeq: the left model with corners is for `E times F`, the right one for `ModelProd E F`, and there's a good reason we are distinguishing them. -/ theorem modelWithCornersSelf_prod : 𝓘(𝕜, E × F) = 𝓘(𝕜, E).prod 𝓘(𝕜, F) := by ext1 <;> simp theorem ModelWithCorners.range_prod : range (I.prod J) = range I ×ˢ range J := by simp_rw [← ModelWithCorners.target_eq]; rfl end ModelWithCornersProd section Boundaryless /-- Property ensuring that the model with corners `I` defines manifolds without boundary. This differs from the more general `BoundarylessManifold`, which requires every point on the manifold to be an interior point. -/ class ModelWithCorners.Boundaryless {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) : Prop where range_eq_univ : range I = univ theorem ModelWithCorners.range_eq_univ {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) [I.Boundaryless] : range I = univ := ModelWithCorners.Boundaryless.range_eq_univ /-- If `I` is a `ModelWithCorners.Boundaryless` model, then it is a homeomorphism. -/ @[simps +simpRhs] def ModelWithCorners.toHomeomorph {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) [I.Boundaryless] : H ≃ₜ E where __ := I left_inv := I.left_inv right_inv _ := I.right_inv <| I.range_eq_univ.symm ▸ mem_univ _ /-- The trivial model with corners has no boundary -/ instance modelWithCornersSelf_boundaryless (𝕜 : Type*) [NontriviallyNormedField 𝕜] (E : Type*) [NormedAddCommGroup E] [NormedSpace 𝕜 E] : (modelWithCornersSelf 𝕜 E).Boundaryless := ⟨by simp⟩ /-- If two model with corners are boundaryless, their product also is -/ instance ModelWithCorners.range_eq_univ_prod {𝕜 : Type u} [NontriviallyNormedField 𝕜] {E : Type v} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type w} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) [I.Boundaryless] {E' : Type v'} [NormedAddCommGroup E'] [NormedSpace 𝕜 E'] {H' : Type w'} [TopologicalSpace H'] (I' : ModelWithCorners 𝕜 E' H') [I'.Boundaryless] : (I.prod I').Boundaryless := by constructor dsimp [ModelWithCorners.prod, ModelProd] rw [← prod_range_range_eq, ModelWithCorners.Boundaryless.range_eq_univ, ModelWithCorners.Boundaryless.range_eq_univ, univ_prod_univ] end Boundaryless section contDiffGroupoid /-! ### `C^n` functions on models with corners -/ variable {m n : WithTop ℕ∞} {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] {I : ModelWithCorners 𝕜 E H} {M : Type*} [TopologicalSpace M] variable (n I) in /-- Given a model with corners `(E, H)`, we define the pregroupoid of `C^n` transformations of `H` as the maps that are `C^n` when read in `E` through `I`. -/ def contDiffPregroupoid : Pregroupoid H where property f s := ContDiffOn 𝕜 n (I ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) comp {f g u v} hf hg _ _ _ := by have : I ∘ (g ∘ f) ∘ I.symm = (I ∘ g ∘ I.symm) ∘ I ∘ f ∘ I.symm := by ext x; simp simp only [this] refine hg.comp (hf.mono fun x ⟨hx1, hx2⟩ ↦ ⟨hx1.1, hx2⟩) ?_ rintro x ⟨hx1, _⟩ simp only [mfld_simps] at hx1 ⊢ exact hx1.2 id_mem := by apply ContDiffOn.congr contDiff_id.contDiffOn rintro x ⟨_, hx2⟩ rcases mem_range.1 hx2 with ⟨y, hy⟩ rw [← hy] simp only [mfld_simps] locality {f u} _ H := by apply contDiffOn_of_locally_contDiffOn rintro y ⟨hy1, hy2⟩ rcases mem_range.1 hy2 with ⟨x, hx⟩ rw [← hx] at hy1 ⊢ simp only [mfld_simps] at hy1 ⊢ rcases H x hy1 with ⟨v, v_open, xv, hv⟩ have : I.symm ⁻¹' (u ∩ v) ∩ range I = I.symm ⁻¹' u ∩ range I ∩ I.symm ⁻¹' v := by rw [preimage_inter, inter_assoc, inter_assoc] congr 1 rw [inter_comm] rw [this] at hv exact ⟨I.symm ⁻¹' v, v_open.preimage I.continuous_symm, by simpa, hv⟩ congr {f g u} _ fg hf := by apply hf.congr rintro y ⟨hy1, hy2⟩ rcases mem_range.1 hy2 with ⟨x, hx⟩ rw [← hx] at hy1 ⊢ simp only [mfld_simps] at hy1 ⊢ rw [fg _ hy1] variable (n I) in /-- Given a model with corners `(E, H)`, we define the groupoid of invertible `C^n` transformations of `H` as the invertible maps that are `C^n` when read in `E` through `I`. -/ def contDiffGroupoid : StructureGroupoid H := Pregroupoid.groupoid (contDiffPregroupoid n I) /-- Inclusion of the groupoid of `C^n` local diffeos in the groupoid of `C^m` local diffeos when `m ≤ n` -/ theorem contDiffGroupoid_le (h : m ≤ n) : contDiffGroupoid n I ≤ contDiffGroupoid m I := by rw [contDiffGroupoid, contDiffGroupoid] apply groupoid_of_pregroupoid_le intro f s hfs exact ContDiffOn.of_le hfs h /-- The groupoid of `0`-times continuously differentiable maps is just the groupoid of all partial homeomorphisms -/ theorem contDiffGroupoid_zero_eq : contDiffGroupoid 0 I = continuousGroupoid H := by apply le_antisymm le_top intro u _ -- we have to check that every partial homeomorphism belongs to `contDiffGroupoid 0 I`, -- by unfolding its definition change u ∈ contDiffGroupoid 0 I rw [contDiffGroupoid, mem_groupoid_of_pregroupoid, contDiffPregroupoid] simp only [contDiffOn_zero] constructor · refine I.continuous.comp_continuousOn (u.continuousOn.comp I.continuousOn_symm ?_) exact (mapsTo_preimage _ _).mono_left inter_subset_left · refine I.continuous.comp_continuousOn (u.symm.continuousOn.comp I.continuousOn_symm ?_) exact (mapsTo_preimage _ _).mono_left inter_subset_left -- FIXME: does this generalise to other groupoids? The argument is not specific -- to C^n functions, but uses something about the groupoid's property that is not easy to abstract. /-- Any change of coordinates with empty source belongs to `contDiffGroupoid`. -/ lemma ContDiffGroupoid.mem_of_source_eq_empty (f : PartialHomeomorph H H) (hf : f.source = ∅) : f ∈ contDiffGroupoid n I := by constructor · intro x ⟨hx, _⟩ rw [mem_preimage] at hx simp_all only [mem_empty_iff_false] · intro x ⟨hx, _⟩ have : f.target = ∅ := by simp [← f.image_source_eq_target, hf] simp_all include I in /-- Any change of coordinates with empty source belongs to `continuousGroupoid`. -/ lemma ContinuousGroupoid.mem_of_source_eq_empty (f : PartialHomeomorph H H) (hf : f.source = ∅) : f ∈ continuousGroupoid H := by rw [← contDiffGroupoid_zero_eq (I := I)] exact ContDiffGroupoid.mem_of_source_eq_empty f hf /-- An identity partial homeomorphism belongs to the `C^n` groupoid. -/ theorem ofSet_mem_contDiffGroupoid {s : Set H} (hs : IsOpen s) : PartialHomeomorph.ofSet s hs ∈ contDiffGroupoid n I := by rw [contDiffGroupoid, mem_groupoid_of_pregroupoid] suffices h : ContDiffOn 𝕜 n (I ∘ I.symm) (I.symm ⁻¹' s ∩ range I) by simp [h, contDiffPregroupoid] have : ContDiffOn 𝕜 n id (univ : Set E) := contDiff_id.contDiffOn exact this.congr_mono (fun x hx => I.right_inv hx.2) (subset_univ _) /-- The composition of a partial homeomorphism from `H` to `M` and its inverse belongs to the `C^n` groupoid. -/ theorem symm_trans_mem_contDiffGroupoid (e : PartialHomeomorph M H) : e.symm.trans e ∈ contDiffGroupoid n I := haveI : e.symm.trans e ≈ PartialHomeomorph.ofSet e.target e.open_target := PartialHomeomorph.symm_trans_self _ StructureGroupoid.mem_of_eqOnSource _ (ofSet_mem_contDiffGroupoid e.open_target) this variable {E' H' : Type*} [NormedAddCommGroup E'] [NormedSpace 𝕜 E'] [TopologicalSpace H'] /-- The product of two `C^n` partial homeomorphisms is `C^n`. -/ theorem contDiffGroupoid_prod {I : ModelWithCorners 𝕜 E H} {I' : ModelWithCorners 𝕜 E' H'} {e : PartialHomeomorph H H} {e' : PartialHomeomorph H' H'} (he : e ∈ contDiffGroupoid n I) (he' : e' ∈ contDiffGroupoid n I') : e.prod e' ∈ contDiffGroupoid n (I.prod I') := by obtain ⟨he, he_symm⟩ := he obtain ⟨he', he'_symm⟩ := he' constructor <;> simp only [PartialEquiv.prod_source, PartialHomeomorph.prod_toPartialEquiv, contDiffPregroupoid] · have h3 := ContDiffOn.prodMap he he' rw [← I.image_eq, ← I'.image_eq, prod_image_image_eq] at h3 rw [← (I.prod I').image_eq] exact h3 · have h3 := ContDiffOn.prodMap he_symm he'_symm rw [← I.image_eq, ← I'.image_eq, prod_image_image_eq] at h3 rw [← (I.prod I').image_eq] exact h3 /-- The `C^n` groupoid is closed under restriction. -/ instance : ClosedUnderRestriction (contDiffGroupoid n I) := (closedUnderRestriction_iff_id_le _).mpr (by rw [StructureGroupoid.le_iff] rintro e ⟨s, hs, hes⟩ apply (contDiffGroupoid n I).mem_of_eqOnSource' _ _ _ hes exact ofSet_mem_contDiffGroupoid hs) end contDiffGroupoid section IsManifold /-! ### `C^n` manifolds (possibly with boundary or corners) -/ /-- Typeclass defining manifolds with respect to a model with corners, over a field `𝕜`. This definition includes the model with corners `I` (which might allow boundary, corners, or not, so this class covers both manifolds with boundary and manifolds without boundary), and a smoothness parameter `n : WithTop ℕ∞` (where `n = 0` means topological manifold, `n = ∞` means smooth manifold and `n = ω` means analytic manifold). -/ class IsManifold {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) (n : WithTop ℕ∞) (M : Type*) [TopologicalSpace M] [ChartedSpace H M] : Prop extends HasGroupoid M (contDiffGroupoid n I) /-- Building a `C^n` manifold from a `HasGroupoid` assumption. -/ theorem IsManifold.mk' {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) (n : WithTop ℕ∞) (M : Type*) [TopologicalSpace M] [ChartedSpace H M] [gr : HasGroupoid M (contDiffGroupoid n I)] : IsManifold I n M := { gr with } theorem isManifold_of_contDiffOn {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) (n : WithTop ℕ∞) (M : Type*) [TopologicalSpace M] [ChartedSpace H M] (h : ∀ e e' : PartialHomeomorph M H, e ∈ atlas H M → e' ∈ atlas H M → ContDiffOn 𝕜 n (I ∘ e.symm ≫ₕ e' ∘ I.symm) (I.symm ⁻¹' (e.symm ≫ₕ e').source ∩ range I)) : IsManifold I n M where compatible := by haveI : HasGroupoid M (contDiffGroupoid n I) := hasGroupoid_of_pregroupoid _ (h _ _) apply StructureGroupoid.compatible /-- For any model with corners, the model space is a `C^n` manifold -/ instance instIsManifoldModelSpace {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] {I : ModelWithCorners 𝕜 E H} {n : WithTop ℕ∞} : IsManifold I n H := { hasGroupoid_model_space _ _ with } @[deprecated (since := "2025-04-22")] alias intIsManifoldModelSpace := instIsManifoldModelSpace end IsManifold namespace IsManifold /- We restate in the namespace `IsManifold` some lemmas that hold for general charted space with a structure groupoid, avoiding the need to specify the groupoid `contDiffGroupoid n I` explicitly. -/ variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] {I : ModelWithCorners 𝕜 E H} {n : WithTop ℕ∞} {M : Type*} [TopologicalSpace M] [ChartedSpace H M] protected theorem of_le {m n : WithTop ℕ∞} (hmn : m ≤ n) [IsManifold I n M] : IsManifold I m M := by have : HasGroupoid M (contDiffGroupoid m I) := hasGroupoid_of_le (G₁ := contDiffGroupoid n I) (by infer_instance) (contDiffGroupoid_le hmn) exact mk' I m M /-- A typeclass registering that a smoothness exponent is smaller than `∞`. Used to deduce that some manifolds are `C^n` when they are `C^∞`. -/ class _root_.ENat.LEInfty (m : WithTop ℕ∞) where out : m ≤ ∞ open ENat instance (n : ℕ) : LEInfty (n : WithTop ℕ∞) := ⟨mod_cast le_top⟩ instance (n : ℕ) [n.AtLeastTwo] : LEInfty (no_index (OfNat.ofNat n) : WithTop ℕ∞) := inferInstanceAs (LEInfty (n : WithTop ℕ∞)) instance : LEInfty (1 : WithTop ℕ∞) := inferInstanceAs (LEInfty ((1 : ℕ) : WithTop ℕ∞)) instance : LEInfty (0 : WithTop ℕ∞) := inferInstanceAs (LEInfty ((0 : ℕ) : WithTop ℕ∞)) instance {a : WithTop ℕ∞} [IsManifold I ∞ M] [h : LEInfty a] : IsManifold I a M := IsManifold.of_le h.out instance {a : WithTop ℕ∞} [IsManifold I ω M] : IsManifold I a M := IsManifold.of_le le_top instance : IsManifold I 0 M := by suffices HasGroupoid M (contDiffGroupoid 0 I) from mk' I 0 M constructor intro e e' he he' rw [contDiffGroupoid_zero_eq] trivial instance [IsManifold I 2 M] : IsManifold I 1 M := IsManifold.of_le one_le_two instance [IsManifold I 3 M] : IsManifold I 2 M := IsManifold.of_le (n := 3) (by norm_cast) variable (I n M) in /-- The maximal atlas of `M` for the `C^n` manifold with corners structure corresponding to the model with corners `I`. -/ def maximalAtlas := (contDiffGroupoid n I).maximalAtlas M theorem subset_maximalAtlas [IsManifold I n M] : atlas H M ⊆ maximalAtlas I n M := StructureGroupoid.subset_maximalAtlas _ theorem chart_mem_maximalAtlas [IsManifold I n M] (x : M) : chartAt H x ∈ maximalAtlas I n M := StructureGroupoid.chart_mem_maximalAtlas _ x theorem compatible_of_mem_maximalAtlas {e e' : PartialHomeomorph M H} (he : e ∈ maximalAtlas I n M) (he' : e' ∈ maximalAtlas I n M) : e.symm.trans e' ∈ contDiffGroupoid n I := StructureGroupoid.compatible_of_mem_maximalAtlas he he' lemma maximalAtlas_subset_of_le {m n : WithTop ℕ∞} (h : m ≤ n) : maximalAtlas I n M ⊆ maximalAtlas I m M := StructureGroupoid.maximalAtlas_mono (contDiffGroupoid_le h) variable (n) in /-- The empty set is a `C^n` manifold w.r.t. any charted space and model. -/ instance empty [IsEmpty M] : IsManifold I n M := by apply isManifold_of_contDiffOn intro e e' _ _ x hx set t := I.symm ⁻¹' (e.symm ≫ₕ e').source ∩ range I -- Since `M` is empty, the condition about compatibility of transition maps is vacuous. have : (e.symm ≫ₕ e').source = ∅ := calc (e.symm ≫ₕ e').source _ = (e.symm.source) ∩ e.symm ⁻¹' e'.source := by rw [← PartialHomeomorph.trans_source] _ = (e.symm.source) ∩ e.symm ⁻¹' ∅ := by rw [eq_empty_of_isEmpty (e'.source)] _ = (e.symm.source) ∩ ∅ := by rw [preimage_empty] _ = ∅ := inter_empty e.symm.source have : t = ∅ := calc t _ = I.symm ⁻¹' (e.symm ≫ₕ e').source ∩ range I := by rw [← Subtype.preimage_val_eq_preimage_val_iff] _ = ∅ ∩ range I := by rw [this, preimage_empty] _ = ∅ := empty_inter (range I) apply (this ▸ hx).elim attribute [local instance] ChartedSpace.of_discreteTopology in variable (n) in /-- A discrete space `M` is a smooth manifold over the trivial model on a trivial normed space. -/ theorem of_discreteTopology [DiscreteTopology M] [Unique E] : IsManifold (modelWithCornersSelf 𝕜 E) n M := by apply isManifold_of_contDiffOn _ _ _ (fun _ _ _ _ ↦ contDiff_of_subsingleton.contDiffOn) attribute [local instance] ChartedSpace.of_discreteTopology in example [Unique E] : IsManifold (𝓘(𝕜, E)) n (Fin 2) := of_discreteTopology _ /-- The product of two `C^n` manifolds is naturally a `C^n` manifold. -/ instance prod {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {E' : Type*} [NormedAddCommGroup E'] [NormedSpace 𝕜 E'] {H : Type*} [TopologicalSpace H] {I : ModelWithCorners 𝕜 E H} {H' : Type*} [TopologicalSpace H'] {I' : ModelWithCorners 𝕜 E' H'} (M : Type*) [TopologicalSpace M] [ChartedSpace H M] [IsManifold I n M] (M' : Type*) [TopologicalSpace M'] [ChartedSpace H' M'] [IsManifold I' n M'] : IsManifold (I.prod I') n (M × M') where compatible := by rintro f g ⟨f1, hf1, f2, hf2, rfl⟩ ⟨g1, hg1, g2, hg2, rfl⟩ rw [PartialHomeomorph.prod_symm, PartialHomeomorph.prod_trans] have h1 := (contDiffGroupoid n I).compatible hf1 hg1 have h2 := (contDiffGroupoid n I').compatible hf2 hg2 exact contDiffGroupoid_prod h1 h2 section DisjointUnion variable {M' : Type*} [TopologicalSpace M'] [ChartedSpace H M'] [hM : IsManifold I n M] [hM' : IsManifold I n M'] /-- The disjoint union of two `C^n` manifolds modelled on `(E, H)` is a `C^n` manifold modeled on `(E, H)`. -/ instance disjointUnion : IsManifold I n (M ⊕ M') where compatible {e} e' he he' := by obtain (h | h) := isEmpty_or_nonempty H · exact ContDiffGroupoid.mem_of_source_eq_empty _ (eq_empty_of_isEmpty _) obtain (⟨f, hf, hef⟩ | ⟨f, hf, hef⟩) := ChartedSpace.mem_atlas_sum he · obtain (⟨f', hf', he'f'⟩ | ⟨f', hf', he'f'⟩) := ChartedSpace.mem_atlas_sum he' · rw [hef, he'f', f.lift_openEmbedding_trans f' IsOpenEmbedding.inl] exact hM.compatible hf hf' · rw [hef, he'f'] apply ContDiffGroupoid.mem_of_source_eq_empty ext x exact ⟨fun ⟨hx₁, hx₂⟩ ↦ by simp_all, fun hx ↦ hx.elim⟩ · -- Analogous argument to the first case: is there a way to deduplicate? obtain (⟨f', hf', he'f'⟩ | ⟨f', hf', he'f'⟩) := ChartedSpace.mem_atlas_sum he' · rw [hef, he'f'] apply ContDiffGroupoid.mem_of_source_eq_empty ext x exact ⟨fun ⟨hx₁, hx₂⟩ ↦ by simp_all, fun hx ↦ hx.elim⟩ · rw [hef, he'f', f.lift_openEmbedding_trans f' IsOpenEmbedding.inr] exact hM'.compatible hf hf' end DisjointUnion end IsManifold theorem PartialHomeomorph.isManifold_singleton {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] {I : ModelWithCorners 𝕜 E H} {n : WithTop ℕ∞} {M : Type*} [TopologicalSpace M] (e : PartialHomeomorph M H) (h : e.source = Set.univ) : @IsManifold 𝕜 _ E _ _ H _ I n M _ (e.singletonChartedSpace h) := @IsManifold.mk' _ _ _ _ _ _ _ _ _ _ _ (id _) <| e.singleton_hasGroupoid h (contDiffGroupoid n I) theorem Topology.IsOpenEmbedding.isManifold_singleton {𝕜 E H : Type*} [NontriviallyNormedField 𝕜] [NormedAddCommGroup E] [NormedSpace 𝕜 E] [TopologicalSpace H] {I : ModelWithCorners 𝕜 E H} {n : WithTop ℕ∞} {M : Type*} [TopologicalSpace M] [Nonempty M] {f : M → H} (h : IsOpenEmbedding f) : @IsManifold 𝕜 _ E _ _ H _ I n M _ h.singletonChartedSpace := (h.toPartialHomeomorph f).isManifold_singleton (by simp) namespace TopologicalSpace.Opens open TopologicalSpace variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] {I : ModelWithCorners 𝕜 E H} {n : WithTop ℕ∞} {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I n M] (s : Opens M) instance : IsManifold I n s := { s.instHasGroupoid (contDiffGroupoid n I) with } end TopologicalSpace.Opens section TangentSpace /- We define the tangent space to `M` modelled on `I : ModelWithCorners 𝕜 E H` as a type synonym for `E`. This is enough to define linear maps between tangent spaces, for instance derivatives, but the interesting part is to define a manifold structure on the whole tangent bundle, which requires that `M` is a `C^n` manifold. The definition is put here to avoid importing all the smooth bundle structure when defining manifold derivatives. -/ set_option linter.unusedVariables false in /-- The tangent space at a point of the manifold `M`. It is just `E`. We could use instead `(tangentBundleCore I M).to_topological_vector_bundle_core.fiber x`, but we use `E` to help the kernel. The definition of `TangentSpace` is not reducible so that type class inference does not pick wrong instances. -/ @[nolint unusedArguments] def TangentSpace {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type u} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) {M : Type*} [TopologicalSpace M] [ChartedSpace H M] (_x : M) : Type u := E deriving TopologicalSpace, AddCommGroup, IsTopologicalAddGroup, Module 𝕜, ContinuousSMul 𝕜, -- the following instance derives from the previous one, but through an instance with priority 100 -- which takes a long time to be found. We register a shortcut instance instead ContinuousConstSMul 𝕜 variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) {M : Type*} [TopologicalSpace M] [ChartedSpace H M] {x : M} instance : Inhabited (TangentSpace I x) := ⟨0⟩ variable (M) in -- is empty if the base manifold is empty /-- The tangent bundle to a manifold, as a Sigma type. Defined in terms of `Bundle.TotalSpace` to be able to put a suitable topology on it. -/ abbrev TangentBundle := Bundle.TotalSpace E (TangentSpace I : M → Type _) end TangentSpace section Real variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] {H : Type*} [TopologicalSpace H] {I : ModelWithCorners ℝ E H} {M : Type*} [TopologicalSpace M] [ChartedSpace H M] {x : M} deriving instance PathConnectedSpace for TangentSpace I x end Real
Module.lean
/- Copyright (c) 2024 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import Mathlib.Algebra.Algebra.Tower import Mathlib.Algebra.BigOperators.GroupWithZero.Action import Mathlib.Tactic.Ring import Mathlib.Util.AtomM /-! # A tactic for normalization over modules This file provides the two tactics `match_scalars` and `module`. Given a goal which is an equality in a type `M` (with `M` an `AddCommMonoid`), the `match_scalars` tactic parses the LHS and RHS of the goal as linear combinations of `M`-atoms over some semiring `R`, and reduces the goal to the respective equalities of the `R`-coefficients of each atom. The `module` tactic does this and then runs the `ring` tactic on each of these coefficient-wise equalities, failing if this does not resolve them. The scalar type `R` is not pre-determined: instead it starts as `ℕ` (when each atom is initially given a scalar `(1:ℕ)`) and gets bumped up into bigger semirings when such semirings are encountered. However, to permit this, it is assumed that there is a "linear order" on all the semirings which appear in the expression: for any two semirings `R` and `S` which occur, we have either `Algebra R S` or `Algebra S R`). -/ open Lean hiding Module open Meta Elab Qq Mathlib.Tactic List namespace Mathlib.Tactic.Module /-! ### Theory of lists of pairs (scalar, vector) This section contains the lemmas which are orchestrated by the `match_scalars` and `module` tactics to prove goals in modules. The basic object which these lemmas concern is `NF R M`, a type synonym for a list of ordered pairs in `R × M`, where typically `M` is an `R`-module. -/ /-- Basic theoretical "normal form" object of the `match_scalars` and `module` tactics: a type synonym for a list of ordered pairs in `R × M`, where typically `M` is an `R`-module. This is the form to which the tactics reduce module expressions. (It is not a full "normal form" because the scalars, i.e. `R` components, are not themselves ring-normalized. But this partial normal form is more convenient for our purposes.) -/ def NF (R : Type*) (M : Type*) := List (R × M) namespace NF variable {S : Type*} {R : Type*} {M : Type*} /-- Augment a `Module.NF R M` object `l`, i.e. a list of pairs in `R × M`, by prepending another pair `p : R × M`. -/ @[match_pattern] def cons (p : R × M) (l : NF R M) : NF R M := p :: l @[inherit_doc cons] infixl:100 " ::ᵣ " => cons /-- Evaluate a `Module.NF R M` object `l`, i.e. a list of pairs in `R × M`, to an element of `M`, by forming the "linear combination" it specifies: scalar-multiply each `R` term to the corresponding `M` term, then add them all up. -/ def eval [Add M] [Zero M] [SMul R M] (l : NF R M) : M := (l.map (fun (⟨r, x⟩ : R × M) ↦ r • x)).sum @[simp] theorem eval_cons [AddMonoid M] [SMul R M] (p : R × M) (l : NF R M) : (p ::ᵣ l).eval = p.1 • p.2 + l.eval := by unfold eval cons rw [List.map_cons] rw [List.sum_cons] theorem atom_eq_eval [AddMonoid M] (x : M) : x = NF.eval [(1, x)] := by simp [eval] variable (M) in theorem zero_eq_eval [AddMonoid M] : (0:M) = NF.eval (R := ℕ) (M := M) [] := rfl theorem add_eq_eval₁ [AddMonoid M] [SMul R M] (a₁ : R × M) {a₂ : R × M} {l₁ l₂ l : NF R M} (h : l₁.eval + (a₂ ::ᵣ l₂).eval = l.eval) : (a₁ ::ᵣ l₁).eval + (a₂ ::ᵣ l₂).eval = (a₁ ::ᵣ l).eval := by simp only [eval_cons, ← h, add_assoc] theorem add_eq_eval₂ [Semiring R] [AddCommMonoid M] [Module R M] (r₁ r₂ : R) (x : M) {l₁ l₂ l : NF R M} (h : l₁.eval + l₂.eval = l.eval) : ((r₁, x) ::ᵣ l₁).eval + ((r₂, x) ::ᵣ l₂).eval = ((r₁ + r₂, x) ::ᵣ l).eval := by simp only [← h, eval_cons, add_smul, add_assoc] congr! 1 simp only [← add_assoc] congr! 1 rw [add_comm] theorem add_eq_eval₃ [Semiring R] [AddCommMonoid M] [Module R M] {a₁ : R × M} (a₂ : R × M) {l₁ l₂ l : NF R M} (h : (a₁ ::ᵣ l₁).eval + l₂.eval = l.eval) : (a₁ ::ᵣ l₁).eval + (a₂ ::ᵣ l₂).eval = (a₂ ::ᵣ l).eval := by simp only [eval_cons, ← h] nth_rw 4 [add_comm] simp only [add_assoc] congr! 2 rw [add_comm] theorem add_eq_eval {R₁ R₂ : Type*} [AddCommMonoid M] [Semiring R] [Module R M] [Semiring R₁] [Module R₁ M] [Semiring R₂] [Module R₂ M] {l₁ l₂ l : NF R M} {l₁' : NF R₁ M} {l₂' : NF R₂ M} {x₁ x₂ : M} (hx₁ : x₁ = l₁'.eval) (hx₂ : x₂ = l₂'.eval) (h₁ : l₁.eval = l₁'.eval) (h₂ : l₂.eval = l₂'.eval) (h : l₁.eval + l₂.eval = l.eval) : x₁ + x₂ = l.eval := by rw [hx₁, hx₂, ← h₁, ← h₂, h] theorem sub_eq_eval₁ [SMul R M] [AddGroup M] (a₁ : R × M) {a₂ : R × M} {l₁ l₂ l : NF R M} (h : l₁.eval - (a₂ ::ᵣ l₂).eval = l.eval) : (a₁ ::ᵣ l₁).eval - (a₂ ::ᵣ l₂).eval = (a₁ ::ᵣ l).eval := by simp only [eval_cons, ← h, sub_eq_add_neg, add_assoc] theorem sub_eq_eval₂ [Ring R] [AddCommGroup M] [Module R M] (r₁ r₂ : R) (x : M) {l₁ l₂ l : NF R M} (h : l₁.eval - l₂.eval = l.eval) : ((r₁, x) ::ᵣ l₁).eval - ((r₂, x) ::ᵣ l₂).eval = ((r₁ - r₂, x) ::ᵣ l).eval := by simp only [← h, eval_cons, sub_eq_add_neg, neg_add, add_smul, neg_smul, add_assoc] congr! 1 simp only [← add_assoc] congr! 1 rw [add_comm] theorem sub_eq_eval₃ [Ring R] [AddCommGroup M] [Module R M] {a₁ : R × M} (a₂ : R × M) {l₁ l₂ l : NF R M} (h : (a₁ ::ᵣ l₁).eval - l₂.eval = l.eval) : (a₁ ::ᵣ l₁).eval - (a₂ ::ᵣ l₂).eval = ((-a₂.1, a₂.2) ::ᵣ l).eval := by simp only [eval_cons, neg_smul, neg_add, sub_eq_add_neg, ← h, ← add_assoc] congr! 1 rw [add_comm, add_assoc] theorem sub_eq_eval {R₁ R₂ S₁ S₂ : Type*} [AddCommGroup M] [Ring R] [Module R M] [Semiring R₁] [Module R₁ M] [Semiring R₂] [Module R₂ M] [Semiring S₁] [Module S₁ M] [Semiring S₂] [Module S₂ M] {l₁ l₂ l : NF R M} {l₁' : NF R₁ M} {l₂' : NF R₂ M} {l₁'' : NF S₁ M} {l₂'' : NF S₂ M} {x₁ x₂ : M} (hx₁ : x₁ = l₁''.eval) (hx₂ : x₂ = l₂''.eval) (h₁' : l₁'.eval = l₁''.eval) (h₂' : l₂'.eval = l₂''.eval) (h₁ : l₁.eval = l₁'.eval) (h₂ : l₂.eval = l₂'.eval) (h : l₁.eval - l₂.eval = l.eval) : x₁ - x₂ = l.eval := by rw [hx₁, hx₂, ← h₁', ← h₂', ← h₁, ← h₂, h] instance [Neg R] : Neg (NF R M) where neg l := l.map fun (a, x) ↦ (-a, x) theorem eval_neg [AddCommGroup M] [Ring R] [Module R M] (l : NF R M) : (-l).eval = - l.eval := by simp only [NF.eval, List.map_map, List.sum_neg, NF.instNeg] congr ext p simp theorem zero_sub_eq_eval [AddCommGroup M] [Ring R] [Module R M] (l : NF R M) : 0 - l.eval = (-l).eval := by simp [eval_neg] theorem neg_eq_eval [AddCommGroup M] [Semiring S] [Module S M] [Ring R] [Module R M] {l : NF R M} {l₀ : NF S M} (hl : l.eval = l₀.eval) {x : M} (h : x = l₀.eval) : - x = (-l).eval := by rw [h, ← hl, eval_neg] instance [Mul R] : SMul R (NF R M) where smul r l := l.map fun (a, x) ↦ (r * a, x) @[simp] theorem smul_apply [Mul R] (r : R) (l : NF R M) : r • l = l.map fun (a, x) ↦ (r * a, x) := rfl theorem eval_smul [AddCommMonoid M] [Semiring R] [Module R M] {l : NF R M} {x : M} (h : x = l.eval) (r : R) : (r • l).eval = r • x := by unfold NF.eval at h ⊢ simp only [h, smul_sum, map_map, NF.smul_apply] congr ext p simp [mul_smul] theorem smul_eq_eval {R₀ : Type*} [AddCommMonoid M] [Semiring R] [Module R M] [Semiring R₀] [Module R₀ M] [Semiring S] [Module S M] {l : NF R M} {l₀ : NF R₀ M} {s : S} {r : R} {x : M} (hx : x = l₀.eval) (hl : l.eval = l₀.eval) (hs : r • x = s • x) : s • x = (r • l).eval := by rw [← hs, hx, ← hl, eval_smul] rfl theorem eq_cons_cons [AddMonoid M] [SMul R M] {r₁ r₂ : R} (m : M) {l₁ l₂ : NF R M} (h1 : r₁ = r₂) (h2 : l₁.eval = l₂.eval) : ((r₁, m) ::ᵣ l₁).eval = ((r₂, m) ::ᵣ l₂).eval := by simp only [NF.eval, NF.cons] at * simp [h1, h2] theorem eq_cons_const [AddCommMonoid M] [Semiring R] [Module R M] {r : R} (m : M) {n : M} {l : NF R M} (h1 : r = 0) (h2 : l.eval = n) : ((r, m) ::ᵣ l).eval = n := by simp only [NF.eval, NF.cons] at * simp [h1, h2] theorem eq_const_cons [AddCommMonoid M] [Semiring R] [Module R M] {r : R} (m : M) {n : M} {l : NF R M} (h1 : 0 = r) (h2 : n = l.eval) : n = ((r, m) ::ᵣ l).eval := by simp only [NF.eval, NF.cons] at * simp [← h1, h2] theorem eq_of_eval_eq_eval {R₁ R₂ : Type*} [AddCommMonoid M] [Semiring R] [Module R M] [Semiring R₁] [Module R₁ M] [Semiring R₂] [Module R₂ M] {l₁ l₂ : NF R M} {l₁' : NF R₁ M} {l₂' : NF R₂ M} {x₁ x₂ : M} (hx₁ : x₁ = l₁'.eval) (hx₂ : x₂ = l₂'.eval) (h₁ : l₁.eval = l₁'.eval) (h₂ : l₂.eval = l₂'.eval) (h : l₁.eval = l₂.eval) : x₁ = x₂ := by rw [hx₁, hx₂, ← h₁, ← h₂, h] variable (R) /-- Operate on a `Module.NF S M` object `l`, i.e. a list of pairs in `S × M`, where `S` is some commutative semiring, by applying to each `S`-component the algebra-map from `S` into a specified `S`-algebra `R`. -/ def algebraMap [CommSemiring S] [Semiring R] [Algebra S R] (l : NF S M) : NF R M := l.map (fun ⟨s, x⟩ ↦ (_root_.algebraMap S R s, x)) theorem eval_algebraMap [CommSemiring S] [Semiring R] [Algebra S R] [AddMonoid M] [SMul S M] [MulAction R M] [IsScalarTower S R M] (l : NF S M) : (l.algebraMap R).eval = l.eval := by simp only [NF.eval, algebraMap, map_map] congr ext simp [IsScalarTower.algebraMap_smul] end NF variable {u v : Level} /-! ### Lists of expressions representing scalars and vectors, and operations on such lists -/ /-- Basic meta-code "normal form" object of the `match_scalars` and `module` tactics: a type synonym for a list of ordered triples comprising expressions representing terms of two types `R` and `M` (where typically `M` is an `R`-module), together with a natural number "index". The natural number represents the index of the `M` term in the `AtomM` monad: this is not enforced, but is sometimes assumed in operations. Thus when items `((a₁, x₁), k)` and `((a₂, x₂), k)` appear in two different `Module.qNF` objects (i.e. with the same `ℕ`-index `k`), it is expected that the expressions `x₁` and `x₂` are the same. It is also expected that the items in a `Module.qNF` list are in strictly increasing order by natural-number index. By forgetting the natural number indices, an expression representing a `Mathlib.Tactic.Module.NF` object can be built from a `Module.qNF` object; this construction is provided as `Mathlib.Tactic.Module.qNF.toNF`. -/ abbrev qNF (R : Q(Type u)) (M : Q(Type v)) := List ((Q($R) × Q($M)) × ℕ) namespace qNF variable {M : Q(Type v)} {R : Q(Type u)} /-- Given `l` of type `qNF R M`, i.e. a list of `(Q($R) × Q($M)) × ℕ`s (two `Expr`s and a natural number), build an `Expr` representing an object of type `NF R M` (i.e. `List (R × M)`) in the in the obvious way: by forgetting the natural numbers and gluing together the `Expr`s. -/ def toNF (l : qNF R M) : Q(NF $R $M) := let l' : List Q($R × $M) := (l.map Prod.fst).map (fun (a, x) ↦ q(($a, $x))) let qt : List Q($R × $M) → Q(List ($R × $M)) := List.rec q([]) (fun e _ l ↦ q($e ::ᵣ $l)) qt l' /-- Given `l` of type `qNF R₁ M`, i.e. a list of `(Q($R₁) × Q($M)) × ℕ`s (two `Expr`s and a natural number), apply an expression representing a function with domain `R₁` to each of the `Q($R₁)` components. -/ def onScalar {u₁ u₂ : Level} {R₁ : Q(Type u₁)} {R₂ : Q(Type u₂)} (l : qNF R₁ M) (f : Q($R₁ → $R₂)) : qNF R₂ M := l.map fun ((a, x), k) ↦ ((q($f $a), x), k) /-- Given two terms `l₁`, `l₂` of type `qNF R M`, i.e. lists of `(Q($R) × Q($M)) × ℕ`s (two `Expr`s and a natural number), construct another such term `l`, which will have the property that in the `$R`-module `$M`, the sum of the "linear combinations" represented by `l₁` and `l₂` is the linear combination represented by `l`. The construction assumes, to be valid, that the lists `l₁` and `l₂` are in strictly increasing order by `ℕ`-component, and that if pairs `(a₁, x₁)` and `(a₂, x₂)` appear in `l₁`, `l₂` respectively with the same `ℕ`-component `k`, then the expressions `x₁` and `x₂` are equal. The construction is as follows: merge the two lists, except that if pairs `(a₁, x₁)` and `(a₂, x₂)` appear in `l₁`, `l₂` respectively with the same `ℕ`-component `k`, then contribute a term `(a₁ + a₂, x₁)` to the output list with `ℕ`-component `k`. -/ def add (iR : Q(Semiring $R)) : qNF R M → qNF R M → qNF R M | [], l => l | l, [] => l | ((a₁, x₁), k₁) ::ᵣ t₁, ((a₂, x₂), k₂) ::ᵣ t₂ => if k₁ < k₂ then ((a₁, x₁), k₁) ::ᵣ add iR t₁ (((a₂, x₂), k₂) ::ᵣ t₂) else if k₁ = k₂ then ((q($a₁ + $a₂), x₁), k₁) ::ᵣ add iR t₁ t₂ else ((a₂, x₂), k₂) ::ᵣ add iR (((a₁, x₁), k₁) ::ᵣ t₁) t₂ /-- Given two terms `l₁`, `l₂` of type `qNF R M`, i.e. lists of `(Q($R) × Q($M)) × ℕ`s (two `Expr`s and a natural number), recursively construct a proof that in the `$R`-module `$M`, the sum of the "linear combinations" represented by `l₁` and `l₂` is the linear combination represented by `Module.qNF.add iR l₁ l₁`. -/ def mkAddProof {iR : Q(Semiring $R)} {iM : Q(AddCommMonoid $M)} (iRM : Q(Module $R $M)) (l₁ l₂ : qNF R M) : Q(NF.eval $(l₁.toNF) + NF.eval $(l₂.toNF) = NF.eval $((qNF.add iR l₁ l₂).toNF)) := match l₁, l₂ with | [], l => (q(zero_add (NF.eval $(l.toNF))):) | l, [] => (q(add_zero (NF.eval $(l.toNF))):) | ((a₁, x₁), k₁) ::ᵣ t₁, ((a₂, x₂), k₂) ::ᵣ t₂ => if k₁ < k₂ then let pf := mkAddProof iRM t₁ (((a₂, x₂), k₂) ::ᵣ t₂) (q(NF.add_eq_eval₁ ($a₁, $x₁) $pf):) else if k₁ = k₂ then let pf := mkAddProof iRM t₁ t₂ (q(NF.add_eq_eval₂ $a₁ $a₂ $x₁ $pf):) else let pf := mkAddProof iRM (((a₁, x₁), k₁) ::ᵣ t₁) t₂ (q(NF.add_eq_eval₃ ($a₂, $x₂) $pf):) /-- Given two terms `l₁`, `l₂` of type `qNF R M`, i.e. lists of `(Q($R) × Q($M)) × ℕ`s (two `Expr`s and a natural number), construct another such term `l`, which will have the property that in the `$R`-module `$M`, the difference of the "linear combinations" represented by `l₁` and `l₂` is the linear combination represented by `l`. The construction assumes, to be valid, that the lists `l₁` and `l₂` are in strictly increasing order by `ℕ`-component, and that if pairs `(a₁, x₁)` and `(a₂, x₂)` appear in `l₁`, `l₂` respectively with the same `ℕ`-component `k`, then the expressions `x₁` and `x₂` are equal. The construction is as follows: merge the first list and the negation of the second list, except that if pairs `(a₁, x₁)` and `(a₂, x₂)` appear in `l₁`, `l₂` respectively with the same `ℕ`-component `k`, then contribute a term `(a₁ - a₂, x₁)` to the output list with `ℕ`-component `k`. -/ def sub (iR : Q(Ring $R)) : qNF R M → qNF R M → qNF R M | [], l => l.onScalar q(Neg.neg) | l, [] => l | ((a₁, x₁), k₁) ::ᵣ t₁, ((a₂, x₂), k₂) ::ᵣ t₂ => if k₁ < k₂ then ((a₁, x₁), k₁) ::ᵣ sub iR t₁ (((a₂, x₂), k₂) ::ᵣ t₂) else if k₁ = k₂ then ((q($a₁ - $a₂), x₁), k₁) ::ᵣ sub iR t₁ t₂ else ((q(-$a₂), x₂), k₂) ::ᵣ sub iR (((a₁, x₁), k₁) ::ᵣ t₁) t₂ /-- Given two terms `l₁`, `l₂` of type `qNF R M`, i.e. lists of `(Q($R) × Q($M)) × ℕ`s (two `Expr`s and a natural number), recursively construct a proof that in the `$R`-module `$M`, the difference of the "linear combinations" represented by `l₁` and `l₂` is the linear combination represented by `Module.qNF.sub iR l₁ l₁`. -/ def mkSubProof (iR : Q(Ring $R)) (iM : Q(AddCommGroup $M)) (iRM : Q(Module $R $M)) (l₁ l₂ : qNF R M) : Q(NF.eval $(l₁.toNF) - NF.eval $(l₂.toNF) = NF.eval $((qNF.sub iR l₁ l₂).toNF)) := match l₁, l₂ with | [], l => (q(NF.zero_sub_eq_eval $(l.toNF)):) | l, [] => (q(sub_zero (NF.eval $(l.toNF))):) | ((a₁, x₁), k₁) ::ᵣ t₁, ((a₂, x₂), k₂) ::ᵣ t₂ => if k₁ < k₂ then let pf := mkSubProof iR iM iRM t₁ (((a₂, x₂), k₂) ::ᵣ t₂) (q(NF.sub_eq_eval₁ ($a₁, $x₁) $pf):) else if k₁ = k₂ then let pf := mkSubProof iR iM iRM t₁ t₂ (q(NF.sub_eq_eval₂ $a₁ $a₂ $x₁ $pf):) else let pf := mkSubProof iR iM iRM (((a₁, x₁), k₁) ::ᵣ t₁) t₂ (q(NF.sub_eq_eval₃ ($a₂, $x₂) $pf):) variable {iM : Q(AddCommMonoid $M)} {u₁ : Level} {R₁ : Q(Type u₁)} {iR₁ : Q(Semiring $R₁)} (iRM₁ : Q(@Module $R₁ $M $iR₁ $iM)) {u₂ : Level} {R₂ : Q(Type u₂)} (iR₂ : Q(Semiring $R₂)) (iRM₂ : Q(@Module $R₂ $M $iR₂ $iM)) /-- Given an expression `M` representing a type which is an `AddCommMonoid` and a module over *two* semirings `R₁` and `R₂`, find the "bigger" of the two semirings. That is, we assume that it will turn out to be the case that either (1) `R₁` is an `R₂`-algebra and the `R₂` scalar action on `M` is induced from `R₁`'s scalar action on `M`, or (2) vice versa; we return the semiring `R₁` in the first case and `R₂` in the second case. Moreover, given expressions representing particular scalar multiplications of `R₁` and/or `R₂` on `M` (a `List (R₁ × M)`, a `List (R₂ × M)`, a pair `(r, x) : R₂ × M`), bump these up to the "big" ring by applying the algebra-map where needed. -/ def matchRings (l₁ : qNF R₁ M) (l₂ : qNF R₂ M) (r : Q($R₂)) (x : Q($M)) : MetaM <| Σ u : Level, Σ R : Q(Type u), Σ iR : Q(Semiring $R), Σ _ : Q(@Module $R $M $iR $iM), (Σ l₁' : qNF R M, Q(NF.eval $(l₁'.toNF) = NF.eval $(l₁.toNF))) × (Σ l₂' : qNF R M, Q(NF.eval $(l₂'.toNF) = NF.eval $(l₂.toNF))) × (Σ r' : Q($R), Q($r' • $x = $r • $x)) := do if ← withReducible <| isDefEq R₁ R₂ then -- the case when `R₁ = R₂` is handled separately, so as not to require commutativity of that ring pure ⟨u₁, R₁, iR₁, iRM₁, ⟨l₁, q(rfl)⟩, ⟨l₂, (q(@rfl _ (NF.eval $(l₂.toNF))):)⟩, r, (q(@rfl _ ($r • $x)):)⟩ -- otherwise the "smaller" of the two rings must be commutative else try -- first try to exhibit `R₂` as an `R₁`-algebra let _i₁ ← synthInstanceQ q(CommSemiring $R₁) let _i₃ ← synthInstanceQ q(Algebra $R₁ $R₂) let _i₄ ← synthInstanceQ q(IsScalarTower $R₁ $R₂ $M) assumeInstancesCommute let l₁' : qNF R₂ M := l₁.onScalar q(algebraMap $R₁ $R₂) pure ⟨u₂, R₂, iR₂, iRM₂, ⟨l₁', (q(NF.eval_algebraMap $R₂ $(l₁.toNF)):)⟩, ⟨l₂, q(rfl)⟩, r, q(rfl)⟩ catch _ => try -- then if that fails, try to exhibit `R₁` as an `R₂`-algebra let _i₁ ← synthInstanceQ q(CommSemiring $R₂) let _i₃ ← synthInstanceQ q(Algebra $R₂ $R₁) let _i₄ ← synthInstanceQ q(IsScalarTower $R₂ $R₁ $M) assumeInstancesCommute let l₂' : qNF R₁ M := l₂.onScalar q(algebraMap $R₂ $R₁) let r' : Q($R₁) := q(algebraMap $R₂ $R₁ $r) pure ⟨u₁, R₁, iR₁, iRM₁, ⟨l₁, q(rfl)⟩, ⟨l₂', (q(NF.eval_algebraMap $R₁ $(l₂.toNF)):)⟩, r', (q(IsScalarTower.algebraMap_smul $R₁ $r $x):)⟩ catch _ => throwError "match_scalars failed: {R₁} is not an {R₂}-algebra and {R₂} is not an {R₁}-algebra" end qNF /-! ### Core of the `module` tactic -/ variable {M : Q(Type v)} /-- The main algorithm behind the `match_scalars` and `module` tactics: partially-normalizing an expression in an additive commutative monoid `M` into the form c1 • x1 + c2 • x2 + ... c_k • x_k, where x1, x2, ... are distinct atoms in `M`, and c1, c2, ... are scalars. The scalar type of the expression is not pre-determined: instead it starts as `ℕ` (when each atom is initially given a scalar `(1:ℕ)`) and gets bumped up into bigger semirings when such semirings are encountered. It is assumed that there is a "linear order" on all the semirings which appear in the expression: for any two semirings `R` and `S` which occur, we have either `Algebra R S` or `Algebra S R`). TODO: implement a variant in which a semiring `R` is provided by the user, and the assumption is instead that for any semiring `S` which occurs, we have `Algebra S R`. The PR https://github.com/leanprover-community/mathlib4/pull/16984 provides a proof-of-concept implementation of this variant, but it would need some polishing before joining Mathlib. Possible TODO, if poor performance on large problems is witnessed: switch the implementation from `AtomM` to `CanonM`, per the discussion https://github.com/leanprover-community/mathlib4/pull/16593/files#r1749623191 -/ partial def parse (iM : Q(AddCommMonoid $M)) (x : Q($M)) : AtomM (Σ u : Level, Σ R : Q(Type u), Σ iR : Q(Semiring $R), Σ _ : Q(@Module $R $M $iR $iM), Σ l : qNF R M, Q($x = NF.eval $(l.toNF))) := do match x with /- parse an addition: `x₁ + x₂` -/ | ~q($x₁ + $x₂) => let ⟨_, _, _, iRM₁, l₁', pf₁'⟩ ← parse iM x₁ let ⟨_, _, _, iRM₂, l₂', pf₂'⟩ ← parse iM x₂ -- lift from the semirings of scalars parsed from `x₁`, `x₂` (say `R₁`, `R₂`) to `R₁ ⊗ R₂` let ⟨u, R, iR, iRM, ⟨l₁, pf₁⟩, ⟨l₂, pf₂⟩, _⟩ ← qNF.matchRings iRM₁ _ iRM₂ l₁' l₂' q(0) q(0) -- build the new list and proof let pf := qNF.mkAddProof iRM l₁ l₂ pure ⟨u, R, iR, iRM, qNF.add iR l₁ l₂, (q(NF.add_eq_eval $pf₁' $pf₂' $pf₁ $pf₂ $pf):)⟩ /- parse a subtraction: `x₁ - x₂` -/ | ~q(@HSub.hSub _ _ _ (@instHSub _ $iM') $x₁ $x₂) => let ⟨_, _, _, iRM₁, l₁'', pf₁''⟩ ← parse iM x₁ let ⟨_, _, _, iRM₂, l₂'', pf₂''⟩ ← parse iM x₂ -- lift from the semirings of scalars parsed from `x₁`, `x₂` (say `R₁`, `R₂`) to `R₁ ⊗ R₂ ⊗ ℤ` let iZ := q(Int.instSemiring) let iMZ ← synthInstanceQ q(Module ℤ $M) let ⟨_, _, _, iRM₁', ⟨l₁', pf₁'⟩, _, _⟩ ← qNF.matchRings iRM₁ iZ iMZ l₁'' [] q(0) q(0) let ⟨_, _, _, iRM₂', ⟨l₂', pf₂'⟩, _, _⟩ ← qNF.matchRings iRM₂ iZ iMZ l₂'' [] q(0) q(0) let ⟨u, R, iR, iRM, ⟨l₁, pf₁⟩, ⟨l₂, pf₂⟩, _⟩ ← qNF.matchRings iRM₁' _ iRM₂' l₁' l₂' q(0) q(0) let iR' ← synthInstanceQ q(Ring $R) let iM' ← synthInstanceQ q(AddCommGroup $M) assumeInstancesCommute -- build the new list and proof let pf := qNF.mkSubProof iR' iM' iRM l₁ l₂ pure ⟨u, R, iR, iRM, qNF.sub iR' l₁ l₂, q(NF.sub_eq_eval $pf₁'' $pf₂'' $pf₁' $pf₂' $pf₁ $pf₂ $pf)⟩ /- parse a negation: `-y` -/ | ~q(@Neg.neg _ $iM' $y) => let ⟨u₀, _, _, iRM₀, l₀, pf₀⟩ ← parse iM y -- lift from original semiring of scalars (say `R₀`) to `R₀ ⊗ ℤ` let _i ← synthInstanceQ q(AddCommGroup $M) let iZ := q(Int.instSemiring) let iMZ ← synthInstanceQ q(Module ℤ $M) let ⟨u, R, iR, iRM, ⟨l, pf⟩, _, _⟩ ← qNF.matchRings iRM₀ iZ iMZ l₀ [] q(0) q(0) let _i' ← synthInstanceQ q(Ring $R) assumeInstancesCommute -- build the new list and proof pure ⟨u, R, iR, iRM, l.onScalar q(Neg.neg), (q(NF.neg_eq_eval $pf $pf₀):)⟩ /- parse a scalar multiplication: `(s₀ : S) • y` -/ | ~q(@HSMul.hSMul _ _ _ (@instHSMul $S _ $iS) $s₀ $y) => let ⟨_, _, _, iRM₀, l₀, pf₀⟩ ← parse iM y let i₁ ← synthInstanceQ q(Semiring $S) let i₂ ← synthInstanceQ q(Module $S $M) assumeInstancesCommute -- lift from original semiring of scalars (say `R₀`) to `R₀ ⊗ S` let ⟨u, R, iR, iRM, ⟨l, pf_l⟩, _, ⟨s, pf_r⟩⟩ ← qNF.matchRings iRM₀ i₁ i₂ l₀ [] s₀ y -- build the new list and proof pure ⟨u, R, iR, iRM, l.onScalar q(HMul.hMul $s), (q(NF.smul_eq_eval $pf₀ $pf_l $pf_r):)⟩ /- parse a `(0:M)` -/ | ~q(0) => pure ⟨0, q(Nat), q(Nat.instSemiring), q(AddCommMonoid.toNatModule), [], q(NF.zero_eq_eval $M)⟩ /- anything else should be treated as an atom -/ | _ => let (k, ⟨x', _⟩) ← AtomM.addAtomQ x pure ⟨0, q(Nat), q(Nat.instSemiring), q(AddCommMonoid.toNatModule), [((q(1), x'), k)], q(NF.atom_eq_eval $x')⟩ /-- Given expressions `R` and `M` representing types such that `M`'s is a module over `R`'s, and given two terms `l₁`, `l₂` of type `qNF R M`, i.e. lists of `(Q($R) × Q($M)) × ℕ`s (two `Expr`s and a natural number), construct a list of new goals: that the `R`-coefficient of an `M`-atom which appears in only one list is zero, and that the `R`-coefficients of an `M`-atom which appears in both lists are equal. Also construct (dependent on these new goals) a proof that the "linear combinations" represented by `l₁` and `l₂` are equal in `M`. -/ partial def reduceCoefficientwise {R : Q(Type u)} {_ : Q(AddCommMonoid $M)} {_ : Q(Semiring $R)} (iRM : Q(Module $R $M)) (l₁ l₂ : qNF R M) : MetaM (List MVarId × Q(NF.eval $(l₁.toNF) = NF.eval $(l₂.toNF))) := do match l₁, l₂ with /- if both empty, return a `rfl` proof that `(0:M) = 0` -/ | [], [] => let pf : Q(NF.eval $(l₁.toNF) = NF.eval $(l₁.toNF)) := q(rfl) pure ([], pf) /- if one of the lists is empty and the other one is not, recurse down the nonempty one, forming goals that each of the listed coefficients is equal to zero -/ | [], ((a, x), _) ::ᵣ L => let mvar : Q((0:$R) = $a) ← mkFreshExprMVar q((0:$R) = $a) let (mvars, pf) ← reduceCoefficientwise iRM [] L pure (mvar.mvarId! :: mvars, (q(NF.eq_const_cons $x $mvar $pf):)) | ((a, x), _) ::ᵣ L, [] => let mvar : Q($a = (0:$R)) ← mkFreshExprMVar q($a = (0:$R)) let (mvars, pf) ← reduceCoefficientwise iRM L [] pure (mvar.mvarId! :: mvars, (q(NF.eq_cons_const $x $mvar $pf):)) /- if both lists are nonempty, then deal with the numerically-smallest term in either list, forming a goal that it is equal to zero (if it appears in only one list) or that its coefficients in the two lists are the same (if it appears in both lists); then recurse -/ | ((a₁, x₁), k₁) ::ᵣ L₁, ((a₂, x₂), k₂) ::ᵣ L₂ => if k₁ < k₂ then let mvar : Q($a₁ = (0:$R)) ← mkFreshExprMVar q($a₁ = (0:$R)) let (mvars, pf) ← reduceCoefficientwise iRM L₁ l₂ pure (mvar.mvarId! :: mvars, (q(NF.eq_cons_const $x₁ $mvar $pf):)) else if k₁ = k₂ then let mvar : Q($a₁ = $a₂) ← mkFreshExprMVar q($a₁ = $a₂) let (mvars, pf) ← reduceCoefficientwise iRM L₁ L₂ pure (mvar.mvarId! :: mvars, (q(NF.eq_cons_cons $x₁ $mvar $pf):)) else let mvar : Q((0:$R) = $a₂) ← mkFreshExprMVar q((0:$R) = $a₂) let (mvars, pf) ← reduceCoefficientwise iRM l₁ L₂ pure (mvar.mvarId! :: mvars, (q(NF.eq_const_cons $x₂ $mvar $pf):)) /-- Given a goal which is an equality in a type `M` (with `M` an `AddCommMonoid`), parse the LHS and RHS of the goal as linear combinations of `M`-atoms over some semiring `R`, and reduce the goal to the respective equalities of the `R`-coefficients of each atom. This is an auxiliary function which produces slightly awkward goals in `R`; they are later cleaned up by the function `Mathlib.Tactic.Module.postprocess`. -/ def matchScalarsAux (g : MVarId) : AtomM (List MVarId) := do /- Parse the goal as an equality in a type `M` of two expressions `lhs` and `rhs`, with `M` carrying an `AddCommMonoid` instance. -/ let eqData ← do match (← g.getType').eq? with | some e => pure e | none => throwError "goal {← g.getType} is not an equality" let .sort v₀ ← whnf (← inferType eqData.1) | unreachable! let some v := v₀.dec | unreachable! let ((M : Q(Type v)), (lhs : Q($M)), (rhs :Q($M))) := eqData let iM ← synthInstanceQ q(AddCommMonoid.{v} $M) /- Construct from the `lhs` expression a term `l₁` of type `qNF R₁ M` for some semiring `R₁` -- that is, a list of `(Q($R₁) × Q($M)) × ℕ`s (two `Expr`s and a natural number) -- together with a proof that `lhs` is equal to the `R₁`-linear combination in `M` this represents. -/ let e₁ ← parse iM lhs have u₁ : Level := e₁.fst have R₁ : Q(Type u₁) := e₁.snd.fst have _iR₁ : Q(Semiring.{u₁} $R₁) := e₁.snd.snd.fst let iRM₁ ← synthInstanceQ q(Module $R₁ $M) assumeInstancesCommute have l₁ : qNF R₁ M := e₁.snd.snd.snd.snd.fst let pf₁ : Q($lhs = NF.eval $(l₁.toNF)) := e₁.snd.snd.snd.snd.snd /- Do the same for the `rhs` expression, obtaining a term `l₂` of type `qNF R₂ M` for some semiring `R₂`. -/ let e₂ ← parse iM rhs have u₂ : Level := e₂.fst have R₂ : Q(Type u₂) := e₂.snd.fst have _iR₂ : Q(Semiring.{u₂} $R₂) := e₂.snd.snd.fst let iRM₂ ← synthInstanceQ q(Module $R₂ $M) have l₂ : qNF R₂ M := e₂.snd.snd.snd.snd.fst let pf₂ : Q($rhs = NF.eval $(l₂.toNF)) := e₂.snd.snd.snd.snd.snd /- Lift everything to the same scalar ring, `R`. -/ let ⟨_, _, _, iRM, ⟨l₁', pf₁'⟩, ⟨l₂', pf₂'⟩, _⟩ ← qNF.matchRings iRM₁ _ iRM₂ l₁ l₂ q(0) q(0) /- Construct a list of goals for the coefficientwise equality of these formal linear combinations, and resolve our original goal (modulo these new goals). -/ let (mvars, pf) ← reduceCoefficientwise iRM l₁' l₂' g.assign q(NF.eq_of_eval_eq_eval $pf₁ $pf₂ $pf₁' $pf₂' $pf) return mvars /-- Lemmas used to post-process the result of the `match_scalars` and `module` tactics by converting the `algebraMap` operations which (which proliferate in the constructed scalar goals) to more familiar forms: `ℕ`, `ℤ` and `ℚ` casts. -/ def algebraMapThms : Array Name := #[``eq_natCast, ``eq_intCast, ``eq_ratCast] /-- Postprocessing for the scalar goals constructed in the `match_scalars` and `module` tactics. These goals feature a proliferation of `algebraMap` operations (because the scalars start in `ℕ` and get successively bumped up by `algebraMap`s as new semirings are encountered), so we reinterpret the most commonly occurring `algebraMap`s (those out of `ℕ`, `ℤ` and `ℚ`) into their standard forms (`ℕ`, `ℤ` and `ℚ` casts) and then try to disperse the casts using the various `push_cast` lemmas. -/ def postprocess (mvarId : MVarId) : MetaM MVarId := do -- collect the available `push_cast` lemmas let mut thms : SimpTheorems := ← NormCast.pushCastExt.getTheorems -- augment this list with the `algebraMapThms` lemmas, which handle `algebraMap` operations for thm in algebraMapThms do let ⟨levelParams, _, proof⟩ ← abstractMVars (mkConst thm) thms ← thms.add (.stx (← mkFreshId) Syntax.missing) levelParams proof -- now run `simp` with these lemmas, and (importantly) *no* simprocs let ctx ← Simp.mkContext { failIfUnchanged := false } (simpTheorems := #[thms]) let (some r, _) ← simpTarget mvarId ctx (simprocs := #[]) | throwError "internal error in match_scalars tactic: postprocessing should not close goals" return r /-- Given a goal which is an equality in a type `M` (with `M` an `AddCommMonoid`), parse the LHS and RHS of the goal as linear combinations of `M`-atoms over some semiring `R`, and reduce the goal to the respective equalities of the `R`-coefficients of each atom. -/ def matchScalars (g : MVarId) : MetaM (List MVarId) := do let mvars ← AtomM.run .instances (matchScalarsAux g) mvars.mapM postprocess /-- Given a goal which is an equality in a type `M` (with `M` an `AddCommMonoid`), parse the LHS and RHS of the goal as linear combinations of `M`-atoms over some semiring `R`, and reduce the goal to the respective equalities of the `R`-coefficients of each atom. For example, this produces the goal `⊢ a * 1 + b * 1 = (b + a) * 1`: ``` example [AddCommMonoid M] [Semiring R] [Module R M] (a b : R) (x : M) : a • x + b • x = (b + a) • x := by match_scalars ``` This produces the two goals `⊢ a * (a * 1) + b * (b * 1) = 1` (from the `x` atom) and `⊢ a * -(b * 1) + b * (a * 1) = 0` (from the `y` atom): ``` example [AddCommGroup M] [Ring R] [Module R M] (a b : R) (x : M) : a • (a • x - b • y) + (b • a • y + b • b • x) = x := by match_scalars ``` This produces the goal `⊢ -2 * (a * 1) = a * (-2 * 1)`: ``` example [AddCommGroup M] [Ring R] [Module R M] (a : R) (x : M) : -(2:R) • a • x = a • (-2:ℤ) • x := by match_scalars ``` The scalar type for the goals produced by the `match_scalars` tactic is the largest scalar type encountered; for example, if `ℕ`, `ℚ` and a characteristic-zero field `K` all occur as scalars, then the goals produced are equalities in `K`. A variant of `push_cast` is used internally in `match_scalars` to interpret scalars from the other types in this largest type. If the set of scalar types encountered is not totally ordered (in the sense that for all rings `R`, `S` encountered, it holds that either `Algebra R S` or `Algebra S R`), then the `match_scalars` tactic fails. -/ elab "match_scalars" : tactic => Tactic.liftMetaTactic matchScalars /-- Given a goal which is an equality in a type `M` (with `M` an `AddCommMonoid`), parse the LHS and RHS of the goal as linear combinations of `M`-atoms over some commutative semiring `R`, and prove the goal by checking that the LHS- and RHS-coefficients of each atom are the same up to ring-normalization in `R`. (If the proofs of coefficient-wise equality will require more reasoning than just ring-normalization, use the tactic `match_scalars` instead, and then prove coefficient-wise equality by hand.) Example uses of the `module` tactic: ``` example [AddCommMonoid M] [CommSemiring R] [Module R M] (a b : R) (x : M) : a • x + b • x = (b + a) • x := by module example [AddCommMonoid M] [Field K] [CharZero K] [Module K M] (x : M) : (2:K)⁻¹ • x + (3:K)⁻¹ • x + (6:K)⁻¹ • x = x := by module example [AddCommGroup M] [CommRing R] [Module R M] (a : R) (v w : M) : (1 + a ^ 2) • (v + w) - a • (a • v - w) = v + (1 + a + a ^ 2) • w := by module example [AddCommGroup M] [CommRing R] [Module R M] (a b μ ν : R) (x y : M) : (μ - ν) • a • x = (a • μ • x + b • ν • y) - ν • (a • x + b • y) := by module ``` -/ elab "module" : tactic => Tactic.liftMetaFinishingTactic fun g ↦ do let l ← matchScalars g discard <| l.mapM fun mvar ↦ AtomM.run .instances (Ring.proveEq mvar) end Mathlib.Tactic.Module
Kleitman.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.Combinatorics.SetFamily.HarrisKleitman import Mathlib.Combinatorics.SetFamily.Intersecting /-! # Kleitman's bound on the size of intersecting families An intersecting family on `n` elements has size at most `2ⁿ⁻¹`, so we could naïvely think that two intersecting families could cover all `2ⁿ` sets. But actually that's not case because for example none of them can contain the empty set. Intersecting families are in some sense correlated. Kleitman's bound stipulates that `k` intersecting families cover at most `2ⁿ - 2ⁿ⁻ᵏ` sets. ## Main declarations * `Finset.card_biUnion_le_of_intersecting`: Kleitman's theorem. ## References * [D. J. Kleitman, *Families of non-disjoint subsets*][kleitman1966] -/ open Finset open Fintype (card) variable {ι α : Type*} [Fintype α] [DecidableEq α] [Nonempty α] /-- **Kleitman's theorem**. An intersecting family on `n` elements contains at most `2ⁿ⁻¹` sets, and each further intersecting family takes at most half of the sets that are in no previous family. -/ theorem Finset.card_biUnion_le_of_intersecting (s : Finset ι) (f : ι → Finset (Finset α)) (hf : ∀ i ∈ s, (f i : Set (Finset α)).Intersecting) : #(s.biUnion f) ≤ 2 ^ Fintype.card α - 2 ^ (Fintype.card α - #s) := by have : DecidableEq ι := by classical infer_instance obtain hs | hs := le_total (Fintype.card α) #s · rw [tsub_eq_zero_of_le hs, pow_zero] refine (card_le_card <| biUnion_subset.2 fun i hi a ha ↦ mem_compl.2 <| notMem_singleton.2 <| (hf _ hi).ne_bot ha).trans_eq ?_ rw [card_compl, Fintype.card_finset, card_singleton] induction s using Finset.cons_induction generalizing f with | empty => simp | cons i s hi ih => set f' : ι → Finset (Finset α) := fun j ↦ if hj : j ∈ cons i s hi then (hf j hj).exists_card_eq.choose else ∅ have hf₁ : ∀ j, j ∈ cons i s hi → f j ⊆ f' j ∧ 2 * #(f' j) = 2 ^ Fintype.card α ∧ (f' j : Set (Finset α)).Intersecting := by rintro j hj simp_rw [f', dif_pos hj, ← Fintype.card_finset] exact Classical.choose_spec (hf j hj).exists_card_eq have hf₂ : ∀ j, j ∈ cons i s hi → IsUpperSet (f' j : Set (Finset α)) := by refine fun j hj ↦ (hf₁ _ hj).2.2.isUpperSet' ((hf₁ _ hj).2.2.is_max_iff_card_eq.2 ?_) rw [Fintype.card_finset] exact (hf₁ _ hj).2.1 refine (card_le_card <| biUnion_mono fun j hj ↦ (hf₁ _ hj).1).trans ?_ nth_rw 1 [cons_eq_insert i] rw [biUnion_insert] refine (card_mono <| @le_sup_sdiff _ _ _ <| f' i).trans ((card_union_le _ _).trans ?_) rw [union_sdiff_left, sdiff_eq_inter_compl] refine le_of_mul_le_mul_left ?_ (pow_pos (zero_lt_two' ℕ) <| Fintype.card α + 1) rw [pow_succ, mul_add, mul_assoc, mul_comm _ 2, mul_assoc] refine (add_le_add ((mul_le_mul_left <| pow_pos (zero_lt_two' ℕ) _).2 (hf₁ _ <| mem_cons_self _ _).2.2.card_le) <| (mul_le_mul_left <| zero_lt_two' ℕ).2 <| IsUpperSet.card_inter_le_finset ?_ ?_).trans ?_ · rw [coe_biUnion] exact isUpperSet_iUnion₂ fun i hi ↦ hf₂ _ <| subset_cons _ hi · rw [coe_compl] exact (hf₂ _ <| mem_cons_self _ _).compl rw [mul_tsub, card_compl, Fintype.card_finset, mul_left_comm, mul_tsub, (hf₁ _ <| mem_cons_self _ _).2.1, two_mul, add_tsub_cancel_left, ← mul_tsub, ← mul_two, mul_assoc, ← add_mul, mul_comm] refine mul_le_mul_left' ?_ _ refine (add_le_add_left (ih _ (fun i hi ↦ (hf₁ _ <| subset_cons _ hi).2.2) ((card_le_card <| subset_cons _).trans hs)) _).trans ?_ rw [mul_tsub, two_mul, ← pow_succ', ← add_tsub_assoc_of_le (pow_right_mono₀ (one_le_two : (1 : ℕ) ≤ 2) tsub_le_self), tsub_add_eq_add_tsub hs, card_cons, add_tsub_add_eq_tsub_right]
Basic.lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Kim Morrison -/ import Mathlib.CategoryTheory.Subobject.MonoOver import Mathlib.CategoryTheory.Skeletal import Mathlib.CategoryTheory.ConcreteCategory.Basic import Mathlib.Tactic.ApplyFun import Mathlib.Tactic.CategoryTheory.Elementwise /-! # Subobjects We define `Subobject X` as the quotient (by isomorphisms) of `MonoOver X := {f : Over X // Mono f.hom}`. Here `MonoOver X` is a thin category (a pair of objects has at most one morphism between them), so we can think of it as a preorder. However as it is not skeletal, it is not a partial order. There is a coercion from `Subobject X` back to the ambient category `C` (using choice to pick a representative), and for `P : Subobject X`, `P.arrow : (P : C) ⟶ X` is the inclusion morphism. We provide * `def pullback [HasPullbacks C] (f : X ⟶ Y) : Subobject Y ⥤ Subobject X` * `def map (f : X ⟶ Y) [Mono f] : Subobject X ⥤ Subobject Y` * `def «exists_» [HasImages C] (f : X ⟶ Y) : Subobject X ⥤ Subobject Y` and prove their basic properties and relationships. These are all easy consequences of the earlier development of the corresponding functors for `MonoOver`. The subobjects of `X` form a preorder making them into a category. We have `X ≤ Y` if and only if `X.arrow` factors through `Y.arrow`: see `ofLE`/`ofLEMk`/`ofMkLE`/`ofMkLEMk` and `le_of_comm`. Similarly, to show that two subobjects are equal, we can supply an isomorphism between the underlying objects that commutes with the arrows (`eq_of_comm`). See also * `CategoryTheory.Subobject.factorThru` : an API describing factorization of morphisms through subobjects. * `CategoryTheory.Subobject.lattice` : the lattice structures on subobjects. ## Notes This development originally appeared in Bhavik Mehta's "Topos theory for Lean" repository, and was ported to mathlib by Kim Morrison. ### Implementation note Currently we describe `pullback`, `map`, etc., as functors. It may be better to just say that they are monotone functions, and even avoid using categorical language entirely when describing `Subobject X`. (It's worth keeping this in mind in future use; it should be a relatively easy change here if it looks preferable.) ### Relation to pseudoelements There is a separate development of pseudoelements in `CategoryTheory.Abelian.Pseudoelements`, as a quotient (but not by isomorphism) of `Over X`. When a morphism `f` has an image, the image represents the same pseudoelement. In a category with images `Pseudoelements X` could be constructed as a quotient of `MonoOver X`. In fact, in an abelian category (I'm not sure in what generality beyond that), `Pseudoelements X` agrees with `Subobject X`, but we haven't developed this in mathlib yet. -/ universe v₁ v₂ u₁ u₂ noncomputable section namespace CategoryTheory open CategoryTheory CategoryTheory.Category CategoryTheory.Limits variable {C : Type u₁} [Category.{v₁} C] {X Y Z : C} variable {D : Type u₂} [Category.{v₂} D] /-! We now construct the subobject lattice for `X : C`, as the quotient by isomorphisms of `MonoOver X`. Since `MonoOver X` is a thin category, we use `ThinSkeleton` to take the quotient. Essentially all the structure defined above on `MonoOver X` descends to `Subobject X`, with morphisms becoming inequalities, and isomorphisms becoming equations. -/ /-- The category of subobjects of `X : C`, defined as isomorphism classes of monomorphisms into `X`. -/ def Subobject (X : C) := ThinSkeleton (MonoOver X) instance (X : C) : PartialOrder (Subobject X) := inferInstanceAs <| PartialOrder (ThinSkeleton (MonoOver X)) namespace Subobject -- Porting note: made it a def rather than an abbreviation -- because Lean would make it too transparent /-- Convenience constructor for a subobject. -/ def mk {X A : C} (f : A ⟶ X) [Mono f] : Subobject X := (toThinSkeleton _).obj (MonoOver.mk' f) section attribute [local ext] CategoryTheory.Comma protected theorem ind {X : C} (p : Subobject X → Prop) (h : ∀ ⦃A : C⦄ (f : A ⟶ X) [Mono f], p (Subobject.mk f)) (P : Subobject X) : p P := by apply Quotient.inductionOn' intro a exact h a.arrow protected theorem ind₂ {X : C} (p : Subobject X → Subobject X → Prop) (h : ∀ ⦃A B : C⦄ (f : A ⟶ X) (g : B ⟶ X) [Mono f] [Mono g], p (Subobject.mk f) (Subobject.mk g)) (P Q : Subobject X) : p P Q := by apply Quotient.inductionOn₂' intro a b exact h a.arrow b.arrow end /-- Declare a function on subobjects of `X` by specifying a function on monomorphisms with codomain `X`. -/ protected def lift {α : Sort*} {X : C} (F : ∀ ⦃A : C⦄ (f : A ⟶ X) [Mono f], α) (h : ∀ ⦃A B : C⦄ (f : A ⟶ X) (g : B ⟶ X) [Mono f] [Mono g] (i : A ≅ B), i.hom ≫ g = f → F f = F g) : Subobject X → α := fun P => Quotient.liftOn' P (fun m => F m.arrow) fun m n ⟨i⟩ => h m.arrow n.arrow ((MonoOver.forget X ⋙ Over.forget X).mapIso i) (Over.w i.hom) @[simp] protected theorem lift_mk {α : Sort*} {X : C} (F : ∀ ⦃A : C⦄ (f : A ⟶ X) [Mono f], α) {h A} (f : A ⟶ X) [Mono f] : Subobject.lift F h (Subobject.mk f) = F f := rfl /-- The category of subobjects is equivalent to the `MonoOver` category. It is more convenient to use the former due to the partial order instance, but oftentimes it is easier to define structures on the latter. -/ noncomputable def equivMonoOver (X : C) : Subobject X ≌ MonoOver X := ThinSkeleton.equivalence _ /-- Use choice to pick a representative `MonoOver X` for each `Subobject X`. -/ noncomputable def representative {X : C} : Subobject X ⥤ MonoOver X := (equivMonoOver X).functor instance : (representative (X := X)).IsEquivalence := (equivMonoOver X).isEquivalence_functor /-- Starting with `A : MonoOver X`, we can take its equivalence class in `Subobject X` then pick an arbitrary representative using `representative.obj`. This is isomorphic (in `MonoOver X`) to the original `A`. -/ noncomputable def representativeIso {X : C} (A : MonoOver X) : representative.obj ((toThinSkeleton _).obj A) ≅ A := (equivMonoOver X).counitIso.app A /-- Use choice to pick a representative underlying object in `C` for any `Subobject X`. Prefer to use the coercion `P : C` rather than explicitly writing `underlying.obj P`. -/ noncomputable def underlying {X : C} : Subobject X ⥤ C := representative ⋙ MonoOver.forget _ ⋙ Over.forget _ instance : CoeOut (Subobject X) C where coe Y := underlying.obj Y -- Porting note: removed as it has become a syntactic tautology -- @[simp] -- theorem underlying_as_coe {X : C} (P : Subobject X) : underlying.obj P = P := -- rfl /-- If we construct a `Subobject Y` from an explicit `f : X ⟶ Y` with `[Mono f]`, then pick an arbitrary choice of underlying object `(Subobject.mk f : C)` back in `C`, it is isomorphic (in `C`) to the original `X`. -/ noncomputable def underlyingIso {X Y : C} (f : X ⟶ Y) [Mono f] : (Subobject.mk f : C) ≅ X := (MonoOver.forget _ ⋙ Over.forget _).mapIso (representativeIso (MonoOver.mk' f)) /-- The morphism in `C` from the arbitrarily chosen underlying object to the ambient object. -/ noncomputable def arrow {X : C} (Y : Subobject X) : (Y : C) ⟶ X := (representative.obj Y).obj.hom instance arrow_mono {X : C} (Y : Subobject X) : Mono Y.arrow := (representative.obj Y).property @[simp] theorem arrow_congr {A : C} (X Y : Subobject A) (h : X = Y) : eqToHom (congr_arg (fun X : Subobject A => (X : C)) h) ≫ Y.arrow = X.arrow := by induction h simp @[simp] theorem representative_coe (Y : Subobject X) : (representative.obj Y : C) = (Y : C) := rfl @[simp] theorem representative_arrow (Y : Subobject X) : (representative.obj Y).arrow = Y.arrow := rfl @[reassoc (attr := simp)] theorem underlying_arrow {X : C} {Y Z : Subobject X} (f : Y ⟶ Z) : underlying.map f ≫ arrow Z = arrow Y := Over.w (representative.map f) @[reassoc (attr := simp), elementwise (attr := simp)] theorem underlyingIso_arrow {X Y : C} (f : X ⟶ Y) [Mono f] : (underlyingIso f).inv ≫ (Subobject.mk f).arrow = f := Over.w _ @[reassoc (attr := simp)] theorem underlyingIso_hom_comp_eq_mk {X Y : C} (f : X ⟶ Y) [Mono f] : (underlyingIso f).hom ≫ f = (mk f).arrow := (Iso.eq_inv_comp _).1 (underlyingIso_arrow f).symm /-- Two morphisms into a subobject are equal exactly if the morphisms into the ambient object are equal -/ @[ext] theorem eq_of_comp_arrow_eq {X Y : C} {P : Subobject Y} {f g : X ⟶ P} (h : f ≫ P.arrow = g ≫ P.arrow) : f = g := (cancel_mono P.arrow).mp h theorem mk_le_mk_of_comm {B A₁ A₂ : C} {f₁ : A₁ ⟶ B} {f₂ : A₂ ⟶ B} [Mono f₁] [Mono f₂] (g : A₁ ⟶ A₂) (w : g ≫ f₂ = f₁) : mk f₁ ≤ mk f₂ := ⟨MonoOver.homMk _ w⟩ @[simp] theorem mk_arrow (P : Subobject X) : mk P.arrow = P := Quotient.inductionOn' P fun Q => by obtain ⟨e⟩ := @Quotient.mk_out' _ (isIsomorphicSetoid _) Q exact Quotient.sound' ⟨MonoOver.isoMk (Iso.refl _) ≪≫ e⟩ theorem le_of_comm {B : C} {X Y : Subobject B} (f : (X : C) ⟶ (Y : C)) (w : f ≫ Y.arrow = X.arrow) : X ≤ Y := by convert mk_le_mk_of_comm _ w <;> simp theorem le_mk_of_comm {B A : C} {X : Subobject B} {f : A ⟶ B} [Mono f] (g : (X : C) ⟶ A) (w : g ≫ f = X.arrow) : X ≤ mk f := le_of_comm (g ≫ (underlyingIso f).inv) <| by simp [w] theorem mk_le_of_comm {B A : C} {X : Subobject B} {f : A ⟶ B} [Mono f] (g : A ⟶ (X : C)) (w : g ≫ X.arrow = f) : mk f ≤ X := le_of_comm ((underlyingIso f).hom ≫ g) <| by simp [w] /-- To show that two subobjects are equal, it suffices to exhibit an isomorphism commuting with the arrows. -/ @[ext (iff := false)] theorem eq_of_comm {B : C} {X Y : Subobject B} (f : (X : C) ≅ (Y : C)) (w : f.hom ≫ Y.arrow = X.arrow) : X = Y := le_antisymm (le_of_comm f.hom w) <| le_of_comm f.inv <| f.inv_comp_eq.2 w.symm /-- To show that two subobjects are equal, it suffices to exhibit an isomorphism commuting with the arrows. -/ theorem eq_mk_of_comm {B A : C} {X : Subobject B} (f : A ⟶ B) [Mono f] (i : (X : C) ≅ A) (w : i.hom ≫ f = X.arrow) : X = mk f := eq_of_comm (i.trans (underlyingIso f).symm) <| by simp [w] /-- To show that two subobjects are equal, it suffices to exhibit an isomorphism commuting with the arrows. -/ theorem mk_eq_of_comm {B A : C} {X : Subobject B} (f : A ⟶ B) [Mono f] (i : A ≅ (X : C)) (w : i.hom ≫ X.arrow = f) : mk f = X := Eq.symm <| eq_mk_of_comm _ i.symm <| by rw [Iso.symm_hom, Iso.inv_comp_eq, w] /-- To show that two subobjects are equal, it suffices to exhibit an isomorphism commuting with the arrows. -/ theorem mk_eq_mk_of_comm {B A₁ A₂ : C} (f : A₁ ⟶ B) (g : A₂ ⟶ B) [Mono f] [Mono g] (i : A₁ ≅ A₂) (w : i.hom ≫ g = f) : mk f = mk g := eq_mk_of_comm _ ((underlyingIso f).trans i) <| by simp [w] lemma mk_surjective {X : C} (S : Subobject X) : ∃ (A : C) (i : A ⟶ X) (_ : Mono i), S = Subobject.mk i := ⟨_, S.arrow, inferInstance, by simp⟩ -- We make `X` and `Y` explicit arguments here so that when `ofLE` appears in goal statements -- it is possible to see its source and target -- (`h` will just display as `_`, because it is in `Prop`). /-- An inequality of subobjects is witnessed by some morphism between the corresponding objects. -/ def ofLE {B : C} (X Y : Subobject B) (h : X ≤ Y) : (X : C) ⟶ (Y : C) := underlying.map <| h.hom @[reassoc (attr := simp)] theorem ofLE_arrow {B : C} {X Y : Subobject B} (h : X ≤ Y) : ofLE X Y h ≫ Y.arrow = X.arrow := underlying_arrow _ instance {B : C} (X Y : Subobject B) (h : X ≤ Y) : Mono (ofLE X Y h) := by fconstructor intro Z f g w replace w := w =≫ Y.arrow ext simpa using w theorem ofLE_mk_le_mk_of_comm {B A₁ A₂ : C} {f₁ : A₁ ⟶ B} {f₂ : A₂ ⟶ B} [Mono f₁] [Mono f₂] (g : A₁ ⟶ A₂) (w : g ≫ f₂ = f₁) : ofLE _ _ (mk_le_mk_of_comm g w) = (underlyingIso _).hom ≫ g ≫ (underlyingIso _).inv := by ext simp [w] /-- An inequality of subobjects is witnessed by some morphism between the corresponding objects. -/ def ofLEMk {B A : C} (X : Subobject B) (f : A ⟶ B) [Mono f] (h : X ≤ mk f) : (X : C) ⟶ A := ofLE X (mk f) h ≫ (underlyingIso f).hom instance {B A : C} (X : Subobject B) (f : A ⟶ B) [Mono f] (h : X ≤ mk f) : Mono (ofLEMk X f h) := by dsimp only [ofLEMk] infer_instance @[simp] theorem ofLEMk_comp {B A : C} {X : Subobject B} {f : A ⟶ B} [Mono f] (h : X ≤ mk f) : ofLEMk X f h ≫ f = X.arrow := by simp [ofLEMk] /-- An inequality of subobjects is witnessed by some morphism between the corresponding objects. -/ def ofMkLE {B A : C} (f : A ⟶ B) [Mono f] (X : Subobject B) (h : mk f ≤ X) : A ⟶ (X : C) := (underlyingIso f).inv ≫ ofLE (mk f) X h instance {B A : C} (f : A ⟶ B) [Mono f] (X : Subobject B) (h : mk f ≤ X) : Mono (ofMkLE f X h) := by dsimp only [ofMkLE] infer_instance @[simp] theorem ofMkLE_arrow {B A : C} {f : A ⟶ B} [Mono f] {X : Subobject B} (h : mk f ≤ X) : ofMkLE f X h ≫ X.arrow = f := by simp [ofMkLE] /-- An inequality of subobjects is witnessed by some morphism between the corresponding objects. -/ def ofMkLEMk {B A₁ A₂ : C} (f : A₁ ⟶ B) (g : A₂ ⟶ B) [Mono f] [Mono g] (h : mk f ≤ mk g) : A₁ ⟶ A₂ := (underlyingIso f).inv ≫ ofLE (mk f) (mk g) h ≫ (underlyingIso g).hom instance {B A₁ A₂ : C} (f : A₁ ⟶ B) (g : A₂ ⟶ B) [Mono f] [Mono g] (h : mk f ≤ mk g) : Mono (ofMkLEMk f g h) := by dsimp only [ofMkLEMk] infer_instance @[simp] theorem ofMkLEMk_comp {B A₁ A₂ : C} {f : A₁ ⟶ B} {g : A₂ ⟶ B} [Mono f] [Mono g] (h : mk f ≤ mk g) : ofMkLEMk f g h ≫ g = f := by simp [ofMkLEMk] @[reassoc (attr := simp)] theorem ofLE_comp_ofLE {B : C} (X Y Z : Subobject B) (h₁ : X ≤ Y) (h₂ : Y ≤ Z) : ofLE X Y h₁ ≫ ofLE Y Z h₂ = ofLE X Z (h₁.trans h₂) := by simp only [ofLE, ← Functor.map_comp underlying] congr 1 @[reassoc (attr := simp)] theorem ofLE_comp_ofLEMk {B A : C} (X Y : Subobject B) (f : A ⟶ B) [Mono f] (h₁ : X ≤ Y) (h₂ : Y ≤ mk f) : ofLE X Y h₁ ≫ ofLEMk Y f h₂ = ofLEMk X f (h₁.trans h₂) := by simp only [ofLEMk, ofLE, ← Functor.map_comp_assoc underlying] congr 1 @[reassoc (attr := simp)] theorem ofLEMk_comp_ofMkLE {B A : C} (X : Subobject B) (f : A ⟶ B) [Mono f] (Y : Subobject B) (h₁ : X ≤ mk f) (h₂ : mk f ≤ Y) : ofLEMk X f h₁ ≫ ofMkLE f Y h₂ = ofLE X Y (h₁.trans h₂) := by simp only [ofMkLE, ofLEMk, ofLE, ← Functor.map_comp underlying, assoc, Iso.hom_inv_id_assoc] congr 1 @[reassoc (attr := simp)] theorem ofLEMk_comp_ofMkLEMk {B A₁ A₂ : C} (X : Subobject B) (f : A₁ ⟶ B) [Mono f] (g : A₂ ⟶ B) [Mono g] (h₁ : X ≤ mk f) (h₂ : mk f ≤ mk g) : ofLEMk X f h₁ ≫ ofMkLEMk f g h₂ = ofLEMk X g (h₁.trans h₂) := by simp only [ofLEMk, ofLE, ofMkLEMk, ← Functor.map_comp_assoc underlying, assoc, Iso.hom_inv_id_assoc] congr 1 @[reassoc (attr := simp)] theorem ofMkLE_comp_ofLE {B A₁ : C} (f : A₁ ⟶ B) [Mono f] (X Y : Subobject B) (h₁ : mk f ≤ X) (h₂ : X ≤ Y) : ofMkLE f X h₁ ≫ ofLE X Y h₂ = ofMkLE f Y (h₁.trans h₂) := by simp only [ofMkLE, ofLE, ← Functor.map_comp underlying, assoc] congr 1 @[reassoc (attr := simp)] theorem ofMkLE_comp_ofLEMk {B A₁ A₂ : C} (f : A₁ ⟶ B) [Mono f] (X : Subobject B) (g : A₂ ⟶ B) [Mono g] (h₁ : mk f ≤ X) (h₂ : X ≤ mk g) : ofMkLE f X h₁ ≫ ofLEMk X g h₂ = ofMkLEMk f g (h₁.trans h₂) := by simp only [ofMkLE, ofLEMk, ofLE, ofMkLEMk, ← Functor.map_comp_assoc underlying, assoc] congr 1 @[reassoc (attr := simp)] theorem ofMkLEMk_comp_ofMkLE {B A₁ A₂ : C} (f : A₁ ⟶ B) [Mono f] (g : A₂ ⟶ B) [Mono g] (X : Subobject B) (h₁ : mk f ≤ mk g) (h₂ : mk g ≤ X) : ofMkLEMk f g h₁ ≫ ofMkLE g X h₂ = ofMkLE f X (h₁.trans h₂) := by simp only [ofMkLE, ofLE, ofMkLEMk, ← Functor.map_comp underlying, assoc, Iso.hom_inv_id_assoc] congr 1 @[reassoc (attr := simp)] theorem ofMkLEMk_comp_ofMkLEMk {B A₁ A₂ A₃ : C} (f : A₁ ⟶ B) [Mono f] (g : A₂ ⟶ B) [Mono g] (h : A₃ ⟶ B) [Mono h] (h₁ : mk f ≤ mk g) (h₂ : mk g ≤ mk h) : ofMkLEMk f g h₁ ≫ ofMkLEMk g h h₂ = ofMkLEMk f h (h₁.trans h₂) := by simp only [ofLE, ofMkLEMk, ← Functor.map_comp_assoc underlying, assoc, Iso.hom_inv_id_assoc] congr 1 @[simp] theorem ofLE_refl {B : C} (X : Subobject B) : ofLE X X le_rfl = 𝟙 _ := by apply (cancel_mono X.arrow).mp simp @[simp] theorem ofMkLEMk_refl {B A₁ : C} (f : A₁ ⟶ B) [Mono f] : ofMkLEMk f f le_rfl = 𝟙 _ := by apply (cancel_mono f).mp simp -- As with `ofLE`, we have `X` and `Y` as explicit arguments for readability. /-- An equality of subobjects gives an isomorphism of the corresponding objects. (One could use `underlying.mapIso (eqToIso h))` here, but this is more readable.) -/ @[simps] def isoOfEq {B : C} (X Y : Subobject B) (h : X = Y) : (X : C) ≅ (Y : C) where hom := ofLE _ _ h.le inv := ofLE _ _ h.ge /-- An equality of subobjects gives an isomorphism of the corresponding objects. -/ @[simps] def isoOfEqMk {B A : C} (X : Subobject B) (f : A ⟶ B) [Mono f] (h : X = mk f) : (X : C) ≅ A where hom := ofLEMk X f h.le inv := ofMkLE f X h.ge /-- An equality of subobjects gives an isomorphism of the corresponding objects. -/ @[simps] def isoOfMkEq {B A : C} (f : A ⟶ B) [Mono f] (X : Subobject B) (h : mk f = X) : A ≅ (X : C) where hom := ofMkLE f X h.le inv := ofLEMk X f h.ge /-- An equality of subobjects gives an isomorphism of the corresponding objects. -/ @[simps] def isoOfMkEqMk {B A₁ A₂ : C} (f : A₁ ⟶ B) (g : A₂ ⟶ B) [Mono f] [Mono g] (h : mk f = mk g) : A₁ ≅ A₂ where hom := ofMkLEMk f g h.le inv := ofMkLEMk g f h.ge lemma mk_lt_mk_of_comm {X A₁ A₂ : C} {i₁ : A₁ ⟶ X} {i₂ : A₂ ⟶ X} [Mono i₁] [Mono i₂] (f : A₁ ⟶ A₂) (fac : f ≫ i₂ = i₁) (hf : ¬ IsIso f) : Subobject.mk i₁ < Subobject.mk i₂ := by obtain _ | h := (mk_le_mk_of_comm _ fac).lt_or_eq · assumption · exfalso apply hf convert (isoOfMkEqMk i₁ i₂ h).isIso_hom rw [← cancel_mono i₂, isoOfMkEqMk_hom, ofMkLEMk_comp, fac] lemma mk_lt_mk_iff_of_comm {X A₁ A₂ : C} {i₁ : A₁ ⟶ X} {i₂ : A₂ ⟶ X} [Mono i₁] [Mono i₂] (f : A₁ ⟶ A₂) (fac : f ≫ i₂ = i₁) : Subobject.mk i₁ < Subobject.mk i₂ ↔ ¬ IsIso f := ⟨fun h hf ↦ by simp only [mk_eq_mk_of_comm i₁ i₂ (asIso f) fac, lt_self_iff_false] at h, mk_lt_mk_of_comm f fac⟩ end Subobject namespace MonoOver variable {P Q : MonoOver X} (f : P ⟶ Q) include f in lemma subobjectMk_le_mk_of_hom : Subobject.mk P.obj.hom ≤ Subobject.mk Q.obj.hom := Subobject.mk_le_mk_of_comm f.left (by simp) lemma isIso_left_iff_subobjectMk_eq : IsIso f.left ↔ Subobject.mk P.1.hom = Subobject.mk Q.1.hom := ⟨fun _ ↦ Subobject.mk_eq_mk_of_comm _ _ (asIso f.left) (by simp), fun h ↦ ⟨Subobject.ofMkLEMk _ _ h.symm.le, by simp [← cancel_mono P.1.hom], by simp [← cancel_mono Q.1.hom]⟩⟩ lemma isIso_iff_subobjectMk_eq : IsIso f ↔ Subobject.mk P.1.hom = Subobject.mk Q.1.hom := by rw [isIso_iff_isIso_left, isIso_left_iff_subobjectMk_eq] end MonoOver open CategoryTheory.Limits namespace Subobject /-- Any functor `MonoOver X ⥤ MonoOver Y` descends to a functor `Subobject X ⥤ Subobject Y`, because `MonoOver Y` is thin. -/ def lower {Y : D} (F : MonoOver X ⥤ MonoOver Y) : Subobject X ⥤ Subobject Y := ThinSkeleton.map F /-- Isomorphic functors become equal when lowered to `Subobject`. (It's not as evil as usual to talk about equality between functors because the categories are thin and skeletal.) -/ theorem lower_iso (F₁ F₂ : MonoOver X ⥤ MonoOver Y) (h : F₁ ≅ F₂) : lower F₁ = lower F₂ := ThinSkeleton.map_iso_eq h /-- A ternary version of `Subobject.lower`. -/ def lower₂ (F : MonoOver X ⥤ MonoOver Y ⥤ MonoOver Z) : Subobject X ⥤ Subobject Y ⥤ Subobject Z := ThinSkeleton.map₂ F @[simp] theorem lower_comm (F : MonoOver Y ⥤ MonoOver X) : toThinSkeleton _ ⋙ lower F = F ⋙ toThinSkeleton _ := rfl /-- An adjunction between `MonoOver A` and `MonoOver B` gives an adjunction between `Subobject A` and `Subobject B`. -/ def lowerAdjunction {A : C} {B : D} {L : MonoOver A ⥤ MonoOver B} {R : MonoOver B ⥤ MonoOver A} (h : L ⊣ R) : lower L ⊣ lower R := ThinSkeleton.lowerAdjunction _ _ h /-- An equivalence between `MonoOver A` and `MonoOver B` gives an equivalence between `Subobject A` and `Subobject B`. -/ @[simps] def lowerEquivalence {A : C} {B : D} (e : MonoOver A ≌ MonoOver B) : Subobject A ≌ Subobject B where functor := lower e.functor inverse := lower e.inverse unitIso := by apply eqToIso convert ThinSkeleton.map_iso_eq e.unitIso · exact ThinSkeleton.map_id_eq.symm · exact (ThinSkeleton.map_comp_eq _ _).symm counitIso := by apply eqToIso convert ThinSkeleton.map_iso_eq e.counitIso · exact (ThinSkeleton.map_comp_eq _ _).symm · exact ThinSkeleton.map_id_eq.symm section Pullback variable [HasPullbacks C] /-- When `C` has pullbacks, a morphism `f : X ⟶ Y` induces a functor `Subobject Y ⥤ Subobject X`, by pulling back a monomorphism along `f`. -/ def pullback (f : X ⟶ Y) : Subobject Y ⥤ Subobject X := lower (MonoOver.pullback f) theorem pullback_id (x : Subobject X) : (pullback (𝟙 X)).obj x = x := by induction' x using Quotient.inductionOn' with f exact Quotient.sound ⟨MonoOver.pullbackId.app f⟩ theorem pullback_comp (f : X ⟶ Y) (g : Y ⟶ Z) (x : Subobject Z) : (pullback (f ≫ g)).obj x = (pullback f).obj ((pullback g).obj x) := by induction' x using Quotient.inductionOn' with t exact Quotient.sound ⟨(MonoOver.pullbackComp _ _).app t⟩ theorem pullback_obj_mk {A B X Y : C} {f : Y ⟶ X} {i : A ⟶ X} [Mono i] {j : B ⟶ Y} [Mono j] {f' : B ⟶ A} (h : IsPullback f' j i f) : (pullback f).obj (mk i) = mk j := ((equivMonoOver Y).inverse.mapIso (MonoOver.pullbackObjIsoOfIsPullback _ _ _ _ h)).to_eq theorem pullback_obj {X Y : C} (f : Y ⟶ X) (x : Subobject X) : (pullback f).obj x = mk (pullback.snd x.arrow f) := by obtain ⟨Z, i, _, rfl⟩ := mk_surjective x rw [pullback_obj_mk (IsPullback.of_hasPullback i f)] exact mk_eq_mk_of_comm _ _ (asIso (pullback.map i f (mk i).arrow f (underlyingIso i).inv (𝟙 _) (𝟙 _) (by simp) (by simp))) (by simp) instance (f : X ⟶ Y) : (pullback f).Faithful where lemma isPullback_aux (f : X ⟶ Y) (y : Subobject Y) : ∃ φ, IsPullback φ ((pullback f).obj y).arrow y.arrow f := by obtain ⟨A, i, ⟨_, rfl⟩⟩ := mk_surjective y rw [pullback_obj] exists (underlyingIso (pullback.snd (mk i).arrow f)).hom ≫ pullback.fst (mk i).arrow f exact IsPullback.of_iso (IsPullback.of_hasPullback (mk i).arrow f) (underlyingIso (pullback.snd (mk i).arrow f)).symm (Iso.refl _) (Iso.refl _) (Iso.refl _) (by simp) (by simp) (by simp) (by simp) /-- For any morphism `f : X ⟶ Y` and subobject `y` of `Y`, `Subobject.pullbackπ f y` is the first projection in the following pullback square: ``` (Subobject.pullback f).obj y ----pullbackπ f y---> (y : C) | | ((Subobject.pullback f).obj y).arrow y.arrow | | v v X ---------------------f-------------------> Y ``` For instance in the category of sets, `Subobject.pullbackπ f y` is the restriction of `f` to elements of `X` that are in the preimage of `y ⊆ Y`. -/ noncomputable def pullbackπ (f : X ⟶ Y) (y : Subobject Y) : ((Subobject.pullback f).obj y : C) ⟶ (y : C) := (isPullback_aux f y).choose /-- This states that `pullbackπ f y` indeed forms a pullback square (see `Subobject.pullbackπ`). -/ theorem isPullback (f : X ⟶ Y) (y : Subobject Y) : IsPullback (pullbackπ f y) ((pullback f).obj y).arrow y.arrow f := (isPullback_aux f y).choose_spec end Pullback section Map /-- We can map subobjects of `X` to subobjects of `Y` by post-composition with a monomorphism `f : X ⟶ Y`. -/ def map (f : X ⟶ Y) [Mono f] : Subobject X ⥤ Subobject Y := lower (MonoOver.map f) lemma map_mk {A X Y : C} (i : A ⟶ X) [Mono i] (f : X ⟶ Y) [Mono f] : (map f).obj (mk i) = mk (i ≫ f) := rfl theorem map_id (x : Subobject X) : (map (𝟙 X)).obj x = x := by induction' x using Quotient.inductionOn' with f exact Quotient.sound ⟨(MonoOver.mapId _).app f⟩ theorem map_comp (f : X ⟶ Y) (g : Y ⟶ Z) [Mono f] [Mono g] (x : Subobject X) : (map (f ≫ g)).obj x = (map g).obj ((map f).obj x) := by induction' x using Quotient.inductionOn' with t exact Quotient.sound ⟨(MonoOver.mapComp _ _).app t⟩ lemma map_obj_injective {X Y : C} (f : X ⟶ Y) [Mono f] : Function.Injective (Subobject.map f).obj := by intro X₁ X₂ h induction' X₁ using Subobject.ind with X₁ i₁ _ induction' X₂ using Subobject.ind with X₂ i₂ _ simp only [map_mk] at h exact mk_eq_mk_of_comm _ _ (isoOfMkEqMk _ _ h) (by simp [← cancel_mono f]) /-- Isomorphic objects have equivalent subobject lattices. -/ def mapIso {A B : C} (e : A ≅ B) : Subobject A ≌ Subobject B := lowerEquivalence (MonoOver.mapIso e) -- Porting note: the note below doesn't seem true anymore -- @[simps] here generates a lemma `map_iso_to_order_iso_to_equiv_symm_apply` -- whose left hand side is not in simp normal form. /-- In fact, there's a type level bijection between the subobjects of isomorphic objects, which preserves the order. -/ def mapIsoToOrderIso (e : X ≅ Y) : Subobject X ≃o Subobject Y where toFun := (map e.hom).obj invFun := (map e.inv).obj left_inv g := by simp_rw [← map_comp, e.hom_inv_id, map_id] right_inv g := by simp_rw [← map_comp, e.inv_hom_id, map_id] map_rel_iff' {A B} := by dsimp constructor · intro h apply_fun (map e.inv).obj at h · simpa only [← map_comp, e.hom_inv_id, map_id] using h · apply Functor.monotone · intro h apply_fun (map e.hom).obj at h · exact h · apply Functor.monotone @[simp] theorem mapIsoToOrderIso_apply (e : X ≅ Y) (P : Subobject X) : mapIsoToOrderIso e P = (map e.hom).obj P := rfl @[simp] theorem mapIsoToOrderIso_symm_apply (e : X ≅ Y) (Q : Subobject Y) : (mapIsoToOrderIso e).symm Q = (map e.inv).obj Q := rfl /-- `map f : Subobject X ⥤ Subobject Y` is the left adjoint of `pullback f : Subobject Y ⥤ Subobject X`. -/ def mapPullbackAdj [HasPullbacks C] (f : X ⟶ Y) [Mono f] : map f ⊣ pullback f := lowerAdjunction (MonoOver.mapPullbackAdj f) @[simp] theorem pullback_map_self [HasPullbacks C] (f : X ⟶ Y) [Mono f] (g : Subobject X) : (pullback f).obj ((map f).obj g) = g := by revert g exact Quotient.ind (fun g' => Quotient.sound ⟨(MonoOver.pullbackMapSelf f).app _⟩) theorem map_pullback [HasPullbacks C] {X Y Z W : C} {f : X ⟶ Y} {g : X ⟶ Z} {h : Y ⟶ W} {k : Z ⟶ W} [Mono h] [Mono g] (comm : f ≫ h = g ≫ k) (t : IsLimit (PullbackCone.mk f g comm)) (p : Subobject Y) : (map g).obj ((pullback f).obj p) = (pullback k).obj ((map h).obj p) := by revert p apply Quotient.ind' intro a apply Quotient.sound apply ThinSkeleton.equiv_of_both_ways · refine MonoOver.homMk (pullback.lift (pullback.fst _ _) _ ?_) (pullback.lift_snd _ _ _) change _ ≫ a.arrow ≫ h = (pullback.snd _ _ ≫ g) ≫ _ rw [assoc, ← comm, pullback.condition_assoc] · refine MonoOver.homMk (pullback.lift (pullback.fst _ _) (PullbackCone.IsLimit.lift t (pullback.fst _ _ ≫ a.arrow) (pullback.snd _ _) _) (PullbackCone.IsLimit.lift_fst _ _ _ ?_).symm) ?_ · rw [← pullback.condition, assoc] rfl · dsimp rw [pullback.lift_snd_assoc] apply PullbackCone.IsLimit.lift_snd end Map section Exists variable [HasImages C] /-- The functor from subobjects of `X` to subobjects of `Y` given by sending the subobject `S` to its "image" under `f`, usually denoted $\exists_f$. For instance, when `C` is the category of types, viewing `Subobject X` as `Set X` this is just `Set.image f`. This functor is left adjoint to the `pullback f` functor (shown in `existsPullbackAdj`) provided both are defined, and generalises the `map f` functor, again provided it is defined. -/ def «exists» (f : X ⟶ Y) : Subobject X ⥤ Subobject Y := lower (MonoOver.exists f) /-- When `f : X ⟶ Y` is a monomorphism, `exists f` agrees with `map f`. -/ theorem exists_iso_map (f : X ⟶ Y) [Mono f] : «exists» f = map f := lower_iso _ _ (MonoOver.existsIsoMap f) /-- `exists f : Subobject X ⥤ Subobject Y` is left adjoint to `pullback f : Subobject Y ⥤ Subobject X`. -/ def existsPullbackAdj (f : X ⟶ Y) [HasPullbacks C] : «exists» f ⊣ pullback f := lowerAdjunction (MonoOver.existsPullbackAdj f) end Exists end Subobject end CategoryTheory
finfun.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import fintype tuple. (******************************************************************************) (* This file implements a type for functions with a finite domain: *) (* {ffun aT -> rT} where aT should have a finType structure, *) (* {ffun forall x : aT, rT} for dependent functions over a finType aT, *) (* and {ffun funT} where funT expands to a product over a finType. *) (* Any eqType, choiceType, countType and finType structures on rT extend to *) (* {ffun aT -> rT} as Leibnitz equality and extensional equalities coincide. *) (* (T ^ n)%type is notation for {ffun 'I_n -> T}, which is isomorphic *) (* to n.-tuple T, but is structurally positive and thus can be used to *) (* define inductive types, e.g., Inductive tree := node n of tree ^ n (see *) (* mid-file for an expanded example). *) (* --> More generally, {ffun fT} is always structurally positive. *) (* {ffun fT} inherits combinatorial structures of rT, i.e., eqType, *) (* choiceType, countType, and finType. However, due to some limitations of *) (* the Coq 8.9 unification code the structures are only inherited in the *) (* NON dependent case, when rT does not depend on x. *) (* For f : {ffun fT} with fT := forall x : aT, rT we define *) (* f x == the image of x under f (f coerces to a CiC function) *) (* --> The coercion is structurally decreasing, e.g., Coq will accept *) (* Fixpoint size t := let: node n f := t in sumn (codom (size \o f)) + 1. *) (* as structurally decreasing on t of the inductive tree type above. *) (* {dffun fT} == alias for {ffun fT} that inherits combinatorial *) (* structures on rT, when rT DOES depend on x. *) (* total_fun g == the function induced by a dependent function g of type *) (* forall x, rT on the total space {x : aT & rT}. *) (* := fun x => Tagged (fun x => rT) (g x). *) (* tfgraph f == the total function graph of f, i.e., the #|aT|.-tuple *) (* of all the (dependent pair) values of total_fun f. *) (* finfun g == the f extensionally equal to g, and the RECOMMENDED *) (* interface for building elements of {ffun fT}. *) (* [ffun x : aT => E] := finfun (fun x : aT => E). *) (* There should be an explicit type constraint on E if *) (* type does not depend on x, due to the Coq unification *) (* limitations referred to above. *) (* ffun0 aT0 == the trivial finfun, from a proof aT0 that #|aT| = 0. *) (* f \in family F == f belongs to the family F (f x \in F x for all x) *) (* There are additional operations for non-dependent finite functions, *) (* i.e., f in {ffun aT -> rT}. *) (* [ffun x => E] := finfun (fun x => E). *) (* The type of E must not depend on x; this restriction *) (* is a mitigation of the aforementioned Coq unification *) (* limitations. *) (* [ffun=> E] := [ffun _ => E] (E should not have a dependent type). *) (* fgraph f == the function graph of f, i.e., the #|aT|.-tuple *) (* listing the values of f x, for x ranging over enum aT. *) (* Finfun G == the finfun f whose (simple) function graph is G. *) (* f \in ffun_on R == the range of f is a subset of R. *) (* y.-support f == the y-support of f, i.e., [pred x | f x != y]. *) (* Thus, y.-support f \subset D means f has y-support D. *) (* We will put Notation support := 0.-support in ssralg. *) (* f \in pffun_on y D R == f is a y-partial function from D to R: *) (* f has y-support D and f x \in R for all x \in D. *) (* f \in pfamily y D F == f belongs to the y-partial family from D to F: *) (* f has y-support D and f x \in F x for all x \in D. *) (* fprod I T_ == alternative construct to {ffun forall i : I, T_ i} for *) (* the finite product of finTypes, in a set-theoretic way *) (* := Record fprod I T_ := FProd *) (* { fprod_fun : {ffun I -> {i : I & T_ i}} ; *) (* fprod_prop : [forall i : I, tag (fprod_fun i) == i] }. *) (* fprod I T_ is endowed with a finType structure and allow these operations: *) (* [fprod i : I => F] == the dependent fprod function built from fun i:I => F *) (* := fprod_of_fun (fun i : I => F) *) (* [fprod : I => F] == [fprod _ : I => F] *) (* [fprod i => F] == [fprod i : _ => F] *) (* [fprod => F] == [fprod _ : _ => F] *) (* These fprod terms coerce into vanilla dependent functions via the coercion *) (* fun_of_fprod I T_ : fprod I T_ -> (forall i : I, T_ i). *) (* We also define the mutual bijections: *) (* fprod_of_dffun : {dffun forall i : I, T_ i} -> fprod I T_ *) (* dffun_of_fprod : fprod I T_ -> {dffun forall i : I, T_ i} *) (* of_family_tagged_with : {x in family (tagged_with T_)} -> fprod I T_ *) (* to_family_tagged_with : fprod I T_ -> {x in family (tagged_with T_)} *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Section Def. Variables (aT : finType) (rT : aT -> Type). Inductive finfun_on : seq aT -> Type := | finfun_nil : finfun_on [::] | finfun_cons x s of rT x & finfun_on s : finfun_on (x :: s). Local Fixpoint finfun_rec (g : forall x, rT x) s : finfun_on s := if s is x1 :: s1 then finfun_cons (g x1) (finfun_rec g s1) else finfun_nil. Local Fixpoint fun_of_fin_rec x s (f_s : finfun_on s) : x \in s -> rT x := if f_s is finfun_cons x1 s1 y1 f_s1 then if eqP is ReflectT Dx in reflect _ Dxb return Dxb || (x \in s1) -> rT x then fun=> ecast x (rT x) (esym Dx) y1 else fun_of_fin_rec f_s1 else fun isF => False_rect (rT x) (notF isF). Variant finfun_of (ph : phant (forall x, rT x)) : predArgType := FinfunOf of finfun_on (enum aT). Definition dfinfun_of ph := finfun_of ph. Definition fun_of_fin ph (f : finfun_of ph) x := let: FinfunOf f_aT := f in fun_of_fin_rec f_aT (mem_enum aT x). End Def. Coercion fun_of_fin : finfun_of >-> Funclass. Identity Coercion unfold_dfinfun_of : dfinfun_of >-> finfun_of. Arguments fun_of_fin {aT rT ph} f x. Notation "{ 'ffun' fT }" := (finfun_of (Phant fT)) (format "{ 'ffun' '[hv' fT ']' }") : type_scope. Notation "{ 'dffun' fT }" := (dfinfun_of (Phant fT)) (format "{ 'dffun' '[hv' fT ']' }") : type_scope. Definition exp_finIndexType n : finType := 'I_n. Notation "T ^ n" := (@finfun_of (exp_finIndexType n) (fun=> T) (Phant _)) : type_scope. Local Notation finPi aT rT := (forall x : Finite.sort aT, rT x) (only parsing). HB.lock Definition finfun aT rT g := FinfunOf (Phant (finPi aT rT)) (finfun_rec g (enum aT)). Canonical finfun_unlock := Unlockable finfun.unlock. Arguments finfun {aT rT} g. Notation "[ 'ffun' x : aT => E ]" := (finfun (fun x : aT => E)) (x name) : function_scope. Notation "[ 'ffun' x => E ]" := (@finfun _ (fun=> _) (fun x => E)) (x name, format "[ 'ffun' x => E ]") : function_scope. Notation "[ 'ffun' => E ]" := [ffun _ => E] (format "[ 'ffun' => E ]") : function_scope. (* Example outcommented. (* Examples of using finite functions as containers in recursive inductive *) (* types, and making use of the fact that the type and accessor are *) (* structurally positive and decreasing, respectively. *) Unset Elimination Schemes. Inductive tree := node n of tree ^ n. Fixpoint size t := let: node n f := t in sumn (codom (size \o f)) + 1. Example tree_step (K : tree -> Type) := forall n st (t := node st) & forall i : 'I_n, K (st i), K t. Example tree_rect K (Kstep : tree_step K) : forall t, K t. Proof. by fix IHt 1 => -[n st]; apply/Kstep=> i; apply: IHt. Defined. (* An artificial example use of dependent functions. *) Inductive tri_tree n := tri_row of {ffun forall i : 'I_n, tri_tree i}. Fixpoint tri_size n (t : tri_tree n) := let: tri_row f := t in sumn [seq tri_size (f i) | i : 'I_n] + 1. Example tri_tree_step (K : forall n, tri_tree n -> Type) := forall n st (t := tri_row st) & forall i : 'I_n, K i (st i), K n t. Example tri_tree_rect K (Kstep : tri_tree_step K) : forall n t, K n t. Proof. by fix IHt 2 => n [st]; apply/Kstep=> i; apply: IHt. Defined. Set Elimination Schemes. (* End example. *) *) (* The correspondence between finfun_of and CiC dependent functions. *) Section DepPlainTheory. Variables (aT : finType) (rT : aT -> Type). Notation fT := {ffun finPi aT rT}. Implicit Type f : fT. Fact ffun0 (aT0 : #|aT| = 0) : fT. Proof. by apply/finfun=> x; have:= card0_eq aT0 x. Qed. Lemma ffunE g x : (finfun g : fT) x = g x. Proof. rewrite unlock /=; set s := enum aT; set s_x : mem_seq s x := mem_enum _ _. by elim: s s_x => //= x1 s IHs; case: eqP => [|_]; [case: x1 / | apply: IHs]. Qed. Lemma ffunP (f1 f2 : fT) : (forall x, f1 x = f2 x) <-> f1 = f2. Proof. suffices ffunK f g: (forall x, f x = g x) -> f = finfun g. by split=> [/ffunK|] -> //; apply/esym/ffunK. case: f => f Dg; rewrite unlock; congr FinfunOf. have{} Dg x (aTx : mem_seq (enum aT) x): g x = fun_of_fin_rec f aTx. by rewrite -Dg /= (bool_irrelevance (mem_enum _ _) aTx). elim: (enum aT) / f (enum_uniq aT) => //= x1 s y f IHf /andP[s'x1 Us] in Dg *. rewrite Dg ?eqxx //=; case: eqP => // /eq_axiomK-> /= _. rewrite {}IHf // => x s_x; rewrite Dg ?s_x ?orbT //. by case: eqP (memPn s'x1 x s_x) => // _ _ /(bool_irrelevance s_x) <-. Qed. Lemma ffunK : @cancel (finPi aT rT) fT fun_of_fin finfun. Proof. by move=> f; apply/ffunP=> x; rewrite ffunE. Qed. Lemma eq_dffun (g1 g2 : forall x, rT x) : (forall x, g1 x = g2 x) -> finfun g1 = finfun g2. Proof. by move=> eq_g; apply/ffunP => x; rewrite !ffunE eq_g. Qed. Definition total_fun g x := Tagged rT (g x : rT x). Definition tfgraph f := codom_tuple (total_fun f). Lemma codom_tffun f : codom (total_fun f) = tfgraph f. Proof. by []. Qed. Local Definition tfgraph_inv (G : #|aT|.-tuple {x : aT & rT x}) : option fT := if eqfunP isn't ReflectT Dtg then None else Some [ffun x => ecast x (rT x) (Dtg x) (tagged (tnth G (enum_rank x)))]. Local Lemma tfgraphK : pcancel tfgraph tfgraph_inv. Proof. move=> f; have Dg x: tnth (tfgraph f) (enum_rank x) = total_fun f x. by rewrite tnth_map -[tnth _ _]enum_val_nth enum_rankK. rewrite /tfgraph_inv; case: eqfunP => /= [Dtg | [] x]; last by rewrite Dg. congr (Some _); apply/ffunP=> x; rewrite ffunE. by rewrite Dg in (Dx := Dtg x) *; rewrite eq_axiomK. Qed. Lemma tfgraph_inj : injective tfgraph. Proof. exact: pcan_inj tfgraphK. Qed. Definition family_mem mF := [pred f : fT | [forall x, in_mem (f x) (mF x)]]. Variables (pT : forall x, predType (rT x)) (F : forall x, pT x). (* Helper for defining notation for function families. *) Local Definition fmem F x := mem (F x : pT x). Lemma familyP f : reflect (forall x, f x \in F x) (f \in family_mem (fmem F)). Proof. exact: forallP. Qed. End DepPlainTheory. Arguments ffunK {aT rT} f : rename. Arguments ffun0 {aT rT} aT0. Arguments eq_dffun {aT rT} [g1] g2 eq_g12. Arguments total_fun {aT rT} g x. Arguments tfgraph {aT rT} f. Arguments tfgraphK {aT rT} f : rename. Arguments tfgraph_inj {aT rT} [f1 f2] : rename. Arguments fmem {aT rT pT} F x /. Arguments familyP {aT rT pT F f}. Notation family F := (family_mem (fmem F)). Section InheritedStructures. Variable aT : finType. Notation dffun_aT rT rS := {dffun forall x : aT, rT x : rS}. #[hnf] HB.instance Definition _ rT := Equality.copy (dffun_aT rT eqType) (pcan_type tfgraphK). #[hnf] HB.instance Definition _ (rT : eqType) := Equality.copy {ffun aT -> rT} {dffun forall _, rT}. #[hnf] HB.instance Definition _ rT := Choice.copy (dffun_aT rT choiceType) (pcan_type tfgraphK). #[hnf] HB.instance Definition _ (rT : choiceType) := Choice.copy {ffun aT -> rT} {dffun forall _, rT}. #[hnf] HB.instance Definition _ rT := Countable.copy (dffun_aT rT countType) (pcan_type tfgraphK). #[hnf] HB.instance Definition _ (rT : countType) := Countable.copy {ffun aT -> rT} {dffun forall _, rT}. #[hnf] HB.instance Definition _ rT := Finite.copy (dffun_aT rT finType) (pcan_type tfgraphK). #[hnf] HB.instance Definition _ (rT : finType) := Finite.copy {ffun aT -> rT} {dffun forall _, rT}. End InheritedStructures. Section FinFunTuple. Context {T : Type} {n : nat}. Definition tuple_of_finfun (f : T ^ n) : n.-tuple T := [tuple f i | i < n]. Definition finfun_of_tuple (t : n.-tuple T) : (T ^ n) := [ffun i => tnth t i]. Lemma finfun_of_tupleK : cancel finfun_of_tuple tuple_of_finfun. Proof. by move=> t; apply: eq_from_tnth => i; rewrite tnth_map ffunE tnth_ord_tuple. Qed. Lemma tuple_of_finfunK : cancel tuple_of_finfun finfun_of_tuple. Proof. by move=> f; apply/ffunP => i; rewrite ffunE tnth_map tnth_ord_tuple. Qed. End FinFunTuple. Section FunPlainTheory. Variables (aT : finType) (rT : Type). Notation fT := {ffun aT -> rT}. Implicit Types (f : fT) (R : pred rT). Definition fgraph f := codom_tuple f. Definition Finfun (G : #|aT|.-tuple rT) := [ffun x => tnth G (enum_rank x)]. Lemma tnth_fgraph f i : tnth (fgraph f) i = f (enum_val i). Proof. by rewrite tnth_map /tnth -enum_val_nth. Qed. Lemma FinfunK : cancel Finfun fgraph. Proof. by move=> G; apply/eq_from_tnth=> i; rewrite tnth_fgraph ffunE enum_valK. Qed. Lemma fgraphK : cancel fgraph Finfun. Proof. by move=> f; apply/ffunP=> x; rewrite ffunE tnth_fgraph enum_rankK. Qed. Lemma fgraph_ffun0 aT0 : fgraph (ffun0 aT0) = nil :> seq rT. Proof. by apply/nilP/eqP; rewrite size_tuple. Qed. Lemma codom_ffun f : codom f = fgraph f. Proof. by []. Qed. Lemma tagged_tfgraph f : @map _ rT tagged (tfgraph f) = fgraph f. Proof. by rewrite -map_comp. Qed. Lemma eq_ffun (g1 g2 : aT -> rT) : g1 =1 g2 -> finfun g1 = finfun g2. Proof. exact: eq_dffun. Qed. Lemma fgraph_codom f : fgraph f = codom_tuple f. Proof. exact/esym/val_inj/codom_ffun. Qed. Definition ffun_on_mem (mR : mem_pred rT) := family_mem (fun _ : aT => mR). Lemma ffun_onP R f : reflect (forall x, f x \in R) (f \in ffun_on_mem (mem R)). Proof. exact: forallP. Qed. End FunPlainTheory. Arguments Finfun {aT rT} G. Arguments fgraph {aT rT} f. Arguments FinfunK {aT rT} G : rename. Arguments fgraphK {aT rT} f : rename. Arguments eq_ffun {aT rT} [g1] g2 eq_g12. Arguments ffun_onP {aT rT R f}. Notation ffun_on R := (ffun_on_mem _ (mem R)). Notation "@ 'ffun_on' aT R" := (ffun_on R : simpl_pred (finfun_of (Phant (aT -> id _)))) (at level 10, aT, R at level 9). Lemma nth_fgraph_ord T n (x0 : T) (i : 'I_n) f : nth x0 (fgraph f) i = f i. Proof. by rewrite -[i in RHS]enum_rankK -tnth_fgraph (tnth_nth x0) enum_rank_ord. Qed. (*****************************************************************************) Section Support. Variables (aT : Type) (rT : eqType). Definition support_for y (f : aT -> rT) := [pred x | f x != y]. Lemma supportE x y f : (x \in support_for y f) = (f x != y). Proof. by []. Qed. End Support. Notation "y .-support" := (support_for y) (at level 1, format "y .-support") : function_scope. Section EqTheory. Variables (aT : finType) (rT : eqType). Notation fT := {ffun aT -> rT}. Implicit Types (y : rT) (D : {pred aT}) (R : {pred rT}) (f : fT). Lemma supportP y D g : reflect (forall x, x \notin D -> g x = y) (y.-support g \subset D). Proof. by (apply: (iffP subsetP) => Dg x; [apply: contraNeq|apply: contraR]) => /Dg->. Qed. Definition pfamily_mem y mD (mF : aT -> mem_pred rT) := family (fun i : aT => if in_mem i mD then pred_of_simpl (mF i) else pred1 y). Lemma pfamilyP (pT : predType rT) y D (F : aT -> pT) f : reflect (y.-support f \subset D /\ {in D, forall x, f x \in F x}) (f \in pfamily_mem y (mem D) (fmem F)). Proof. apply: (iffP familyP) => [/= f_pfam | [/supportP f_supp f_fam] x]. split=> [|x Ax]; last by have:= f_pfam x; rewrite Ax. by apply/subsetP=> x; case: ifP (f_pfam x) => //= _ fx0 /negP[]. by case: ifPn => Ax /=; rewrite inE /= (f_fam, f_supp). Qed. Definition pffun_on_mem y mD mR := pfamily_mem y mD (fun _ => mR). Lemma pffun_onP y D R f : reflect (y.-support f \subset D /\ {subset image f D <= R}) (f \in pffun_on_mem y (mem D) (mem R)). Proof. apply: (iffP (pfamilyP y D (fun _ => R) f)) => [] [-> f_fam]; split=> //. by move=> _ /imageP[x Ax ->]; apply: f_fam. by move=> x Ax; apply: f_fam; apply/imageP; exists x. Qed. End EqTheory. Arguments supportP {aT rT y D g}. Arguments pfamilyP {aT rT pT y D F f}. Arguments pffun_onP {aT rT y D R f}. Notation pfamily y D F := (pfamily_mem y (mem D) (fmem F)). Notation pffun_on y D R := (pffun_on_mem y (mem D) (mem R)). (*****************************************************************************) Section FinDepTheory. Variables (aT : finType) (rT : aT -> finType). Notation fT := {dffun forall x : aT, rT x}. Lemma card_family (F : forall x, pred (rT x)) : #|(family F : simpl_pred fT)| = foldr muln 1 [seq #|F x| | x : aT]. Proof. rewrite /image_mem; set E := enum aT in (uniqE := enum_uniq aT) *. have trivF x: x \notin E -> #|F x| = 1 by rewrite mem_enum. elim: E uniqE => /= [_ | x0 E IH_E /andP[E'x0 uniqE]] in F trivF *. have /fin_all_exists[f0 Ff0] x: exists y0, F x =i pred1 y0. have /pred0Pn[y Fy]: #|F x| != 0 by rewrite trivF. by exists y; apply/fsym/subset_cardP; rewrite ?subset_pred1 // card1 trivF. apply: eq_card1 (finfun f0 : fT) _ _ => f; apply/familyP/eqP=> [Ff | {f}-> x]. by apply/ffunP=> x; have /[!(Ff0, ffunE)]/eqP := Ff x. by rewrite ffunE Ff0 inE /=. have [y0 Fxy0 | Fx00] := pickP (F x0); last first. by rewrite !eq_card0 // => f; apply: contraFF (Fx00 (f x0))=> /familyP; apply. pose F1 x := if eqP is ReflectT Dx then xpred1 (ecast x (rT x) Dx y0) else F x. transitivity (#|[predX F x0 & family F1 : pred fT]|); last first. rewrite cardX {}IH_E {uniqE}// => [|x E'x]; last first. rewrite /F1; case: eqP => [Dx | /nesym/eqP-x0'x]; first exact: card1. by rewrite trivF // negb_or x0'x. congr (_ * foldr _ _ _); apply/eq_in_map=> x Ex. by rewrite /F1; case: eqP => // Dx0; rewrite Dx0 Ex in E'x0. pose g yf : fT := let: (y, f) := yf : rT x0 * fT in [ffun x => if eqP is ReflectT Dx then ecast x (rT x) Dx y else f x]. have gK: cancel (fun f : fT => (f x0, g (y0, f))) g. by move=> f; apply/ffunP=> x; rewrite !ffunE; case: eqP => //; case: x /. rewrite -(card_image (can_inj gK)); apply: eq_card => [] [y f] /=. apply/imageP/andP=> [[f1 /familyP/=Ff1] [-> ->]| [/=Fx0y /familyP/=Ff]]. split=> //; apply/familyP=> x; rewrite ffunE /F1 /=. by case: eqP => // Dx; apply: eqxx. exists (g (y, f)). by apply/familyP=> x; have:= Ff x; rewrite ffunE /F1; case: eqP; [case: x /|]. congr (_, _); first by rewrite /= ffunE; case: eqP => // Dx; rewrite eq_axiomK. by apply/ffunP=> x; have:= Ff x; rewrite !ffunE /F1; case: eqP => // Dx /eqP. Qed. Lemma card_dep_ffun : #|fT| = foldr muln 1 [seq #|rT x| | x : aT]. Proof. by rewrite -card_family; apply/esym/eq_card=> f; apply/familyP. Qed. End FinDepTheory. Section FinFunTheory. Variables aT rT : finType. Notation fT := {ffun aT -> rT}. Implicit Types (D : {pred aT}) (R : {pred rT}) (F : aT -> pred rT). Lemma card_pfamily y0 D F : #|pfamily y0 D F| = foldr muln 1 [seq #|F x| | x in D]. Proof. rewrite card_family !/(image _ _) /(enum D) -enumT /=. by elim: (enum aT) => //= x E ->; have [// | D'x] := ifP; rewrite card1 mul1n. Qed. Lemma card_pffun_on y0 D R : #|pffun_on y0 D R| = #|R| ^ #|D|. Proof. rewrite (cardE D) card_pfamily /image_mem. by elim: (enum D) => //= _ e ->; rewrite expnS. Qed. Lemma card_ffun_on R : #|@ffun_on aT R| = #|R| ^ #|aT|. Proof. rewrite card_family /image_mem cardT. by elim: (enum aT) => //= _ e ->; rewrite expnS. Qed. Lemma card_ffun : #|fT| = #|rT| ^ #|aT|. Proof. by rewrite -card_ffun_on; apply/esym/eq_card=> f; apply/forallP. Qed. End FinFunTheory. Section DependentFiniteProduct. Variables (I : finType) (T_ : I -> finType). Notation fprod_type := (forall i : I, T_ i) (only parsing). (* Definition of [fprod] := dependent product of finTypes *) Record fprod : predArgType := FProd { fprod_fun : {ffun I -> {i : I & T_ i}} ; fprod_prop : [forall i : I, tag (fprod_fun i) == i] }. Lemma tag_fprod_fun (f : fprod) i : tag (fprod_fun f i) = i. Proof. by have /'forall_eqP/(_ i) := fprod_prop f. Qed. Definition fun_of_fprod (f : fprod) : fprod_type := fun i => etagged ('forall_eqP (fprod_prop f) i). Coercion fun_of_fprod : fprod >-> Funclass. #[hnf] HB.instance Definition _ := [isSub for fprod_fun]. #[hnf] HB.instance Definition _ := [Finite of fprod by <:]. Lemma fprod_of_prod_type_subproof (f : fprod_type) : [forall i : I, tag ([ffun i => Tagged T_ (f i)] i) == i]. Proof. by apply/'forall_eqP => i /=; rewrite ffunE. Qed. Definition fprod_of_fun (f : fprod_type) : fprod := FProd (fprod_of_prod_type_subproof f). Lemma fprodK : cancel fun_of_fprod fprod_of_fun. Proof. rewrite /fun_of_fprod /fprod_of_fun; case=> f fP. by apply/val_inj/ffunP => i /=; rewrite !ffunE etaggedK. Qed. Lemma fprodE g i : fprod_of_fun g i = g i. Proof. rewrite /fprod_of_fun /fun_of_fprod/=. by move: ('forall_eqP _ _); rewrite ffunE/= => e; rewrite eq_axiomK. Qed. Lemma fprodP (f1 f2 : fprod) : (forall x, f1 x = f2 x) <-> f1 = f2. Proof. split=> [eq_f12|->//]; rewrite -[f1]fprodK -[f2]fprodK. by apply/val_inj/ffunP => i; rewrite !ffunE eq_f12. Qed. Definition dffun_of_fprod (f : fprod) : {dffun forall i : I, T_ i} := [ffun x => f x]. Definition fprod_of_dffun (f : {dffun forall i : I, T_ i}) : fprod := fprod_of_fun f. Lemma dffun_of_fprodK : cancel dffun_of_fprod fprod_of_dffun. Proof. by move=> f; apply/fprodP=> i; rewrite fprodE ffunE. Qed. #[local] Hint Resolve dffun_of_fprodK : core. Lemma fprod_of_dffunK : cancel fprod_of_dffun dffun_of_fprod. Proof. by move=> f; apply/ffunP => i; rewrite !ffunE fprodE. Qed. #[local] Hint Resolve fprod_of_dffunK : core. Lemma dffun_of_fprod_bij : bijective dffun_of_fprod. Proof. by exists fprod_of_dffun. Qed. Lemma fprod_of_dffun_bij : bijective fprod_of_dffun. Proof. by exists dffun_of_fprod. Qed. Definition to_family_tagged_with (f : fprod) : {x in family (tagged_with T_)} := exist _ (fprod_fun f) (fprod_prop f). Definition of_family_tagged_with (f : {x in family (tagged_with T_)}) : fprod := FProd (valP f). Lemma to_family_tagged_withK : cancel to_family_tagged_with of_family_tagged_with. Proof. by case=> f fP; apply/val_inj. Qed. #[local] Hint Resolve to_family_tagged_withK : core. Lemma of_family_tagged_withK : cancel of_family_tagged_with to_family_tagged_with. Proof. by case=> f fP; apply/val_inj. Qed. #[local] Hint Resolve of_family_tagged_withK : core. Lemma to_family_tagged_with_bij : bijective to_family_tagged_with. Proof. by exists of_family_tagged_with. Qed. Lemma of_family_tagged_with_bij : bijective of_family_tagged_with. Proof. by exists to_family_tagged_with. Qed. Lemma etaggedE (a : fprod) (i : I) (e : tag (fprod_fun a i) = i) : etagged e = a i. Proof. by case: a e => //= f fP e; congr etagged; apply: eq_irrelevance. Qed. End DependentFiniteProduct. Arguments to_family_tagged_with {I T_}. Arguments of_family_tagged_with {I T_}. Notation "[ 'fprod' i : I => F ]" := (fprod_of_fun (fun i : I => F)) (i name, only parsing) : function_scope. Notation "[ 'fprod' : I => F ]" := (fprod_of_fun (fun _ : I => F)) (only parsing) : function_scope. Notation "[ 'fprod' i => F ]" := [fprod i : _ => F] (i name, format "[ 'fprod' i => F ]") : function_scope. Notation "[ 'fprod' => F ]" := [fprod : _ => F] (format "[ 'fprod' => F ]") : function_scope.
Multiplier.lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux, Jon Bannon -/ import Mathlib.Analysis.CStarAlgebra.Unitization import Mathlib.Analysis.CStarAlgebra.Classes import Mathlib.Analysis.SpecialFunctions.Pow.NNReal /-! # Multiplier Algebra of a C⋆-algebra Define the multiplier algebra of a C⋆-algebra as the algebra (over `𝕜`) of double centralizers, for which we provide the localized notation `𝓜(𝕜, A)`. A double centralizer is a pair of continuous linear maps `L R : A →L[𝕜] A` satisfying the intertwining condition `R x * y = x * L y`. There is a natural embedding `A → 𝓜(𝕜, A)` which sends `a : A` to the continuous linear maps `L R : A →L[𝕜] A` given by left and right multiplication by `a`, and we provide this map as a coercion. The multiplier algebra corresponds to a non-commutative Stone–Čech compactification in the sense that when the algebra `A` is commutative, it can be identified with `C₀(X, ℂ)` for some locally compact Hausdorff space `X`, and in that case `𝓜(𝕜, A)` can be identified with `C(β X, ℂ)`. ## Implementation notes We make the hypotheses on `𝕜` as weak as possible so that, in particular, this construction works for both `𝕜 = ℝ` and `𝕜 = ℂ`. The reader familiar with C⋆-algebra theory may recognize that one only needs `L` and `R` to be functions instead of continuous linear maps, at least when `A` is a C⋆-algebra. Our intention is simply to eventually provide a constructor for this situation. We pull back the `NormedAlgebra` structure (and everything contained therein) through the ring (even algebra) homomorphism `DoubleCentralizer.toProdMulOppositeHom : 𝓜(𝕜, A) →+* (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ` which sends `a : 𝓜(𝕜, A)` to `(a.fst, MulOpposite.op a.snd)`. The star structure is provided separately. ## References * https://en.wikipedia.org/wiki/Multiplier_algebra ## TODO + Define a type synonym for `𝓜(𝕜, A)` which is equipped with the strict uniform space structure and show it is complete + Show that the image of `A` in `𝓜(𝕜, A)` is an essential ideal + Prove the universal property of `𝓜(𝕜, A)` + Construct a double centralizer from a pair of maps (not necessarily linear or continuous) `L : A → A`, `R : A → A` satisfying the centrality condition `∀ x y, R x * y = x * L y`. + Show that if `A` is unital, then `A ≃⋆ₐ[𝕜] 𝓜(𝕜, A)`. -/ open NNReal ENNReal ContinuousLinearMap MulOpposite universe u v /-- The type of *double centralizers*, also known as the *multiplier algebra* and denoted by `𝓜(𝕜, A)`, of a non-unital normed algebra. If `x : 𝓜(𝕜, A)`, then `x.fst` and `x.snd` are what is usually referred to as $L$ and $R$. -/ structure DoubleCentralizer (𝕜 : Type u) (A : Type v) [NontriviallyNormedField 𝕜] [NonUnitalNormedRing A] [NormedSpace 𝕜 A] [SMulCommClass 𝕜 A A] [IsScalarTower 𝕜 A A] extends (A →L[𝕜] A) × (A →L[𝕜] A) where /-- The centrality condition that the maps linear maps intertwine one another. -/ central : ∀ x y : A, snd x * y = x * fst y @[inherit_doc] scoped[MultiplierAlgebra] notation "𝓜(" 𝕜 ", " A ")" => DoubleCentralizer 𝕜 A open MultiplierAlgebra @[ext] lemma DoubleCentralizer.ext (𝕜 : Type u) (A : Type v) [NontriviallyNormedField 𝕜] [NonUnitalNormedRing A] [NormedSpace 𝕜 A] [SMulCommClass 𝕜 A A] [IsScalarTower 𝕜 A A] (a b : 𝓜(𝕜, A)) (h : a.toProd = b.toProd) : a = b := by cases a cases b simpa using h namespace DoubleCentralizer section NontriviallyNormed variable (𝕜 A : Type*) [NontriviallyNormedField 𝕜] [NonUnitalNormedRing A] variable [NormedSpace 𝕜 A] [SMulCommClass 𝕜 A A] [IsScalarTower 𝕜 A A] /-! ### Algebraic structure Because the multiplier algebra is defined as the algebra of double centralizers, there is a natural injection `DoubleCentralizer.toProdMulOpposite : 𝓜(𝕜, A) → (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ` defined by `fun a ↦ (a.fst, MulOpposite.op a.snd)`. We use this map to pull back the ring, module and algebra structure from `(A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ` to `𝓜(𝕜, A)`. -/ variable {𝕜 A} theorem range_toProd : Set.range toProd = { lr : (A →L[𝕜] A) × (A →L[𝕜] A) | ∀ x y, lr.2 x * y = x * lr.1 y } := Set.ext fun x => ⟨by rintro ⟨a, rfl⟩ exact a.central, fun hx => ⟨⟨x, hx⟩, rfl⟩⟩ instance instAdd : Add 𝓜(𝕜, A) where add a b := { toProd := a.toProd + b.toProd central := fun x y => show (a.snd + b.snd) x * y = x * (a.fst + b.fst) y by simp only [ContinuousLinearMap.add_apply, mul_add, add_mul, central] } instance instZero : Zero 𝓜(𝕜, A) where zero := { toProd := 0 central := fun x y => (zero_mul y).trans (mul_zero x).symm } instance instNeg : Neg 𝓜(𝕜, A) where neg a := { toProd := -a.toProd central := fun x y => show -a.snd x * y = x * -a.fst y by simp only [neg_mul, mul_neg, central] } instance instSub : Sub 𝓜(𝕜, A) where sub a b := { toProd := a.toProd - b.toProd central := fun x y => show (a.snd - b.snd) x * y = x * (a.fst - b.fst) y by simp only [ContinuousLinearMap.sub_apply, _root_.sub_mul, _root_.mul_sub, central] } section Scalars variable {S : Type*} [Monoid S] [DistribMulAction S A] [SMulCommClass 𝕜 S A] [ContinuousConstSMul S A] [IsScalarTower S A A] [SMulCommClass S A A] instance instSMul : SMul S 𝓜(𝕜, A) where smul s a := { toProd := s • a.toProd central := fun x y => show (s • a.snd) x * y = x * (s • a.fst) y by simp only [ContinuousLinearMap.smul_apply, mul_smul_comm, smul_mul_assoc, central] } @[simp] theorem smul_toProd (s : S) (a : 𝓜(𝕜, A)) : (s • a).toProd = s • a.toProd := rfl theorem smul_fst (s : S) (a : 𝓜(𝕜, A)) : (s • a).fst = s • a.fst := rfl theorem smul_snd (s : S) (a : 𝓜(𝕜, A)) : (s • a).snd = s • a.snd := rfl variable {T : Type*} [Monoid T] [DistribMulAction T A] [SMulCommClass 𝕜 T A] [ContinuousConstSMul T A] [IsScalarTower T A A] [SMulCommClass T A A] instance instIsScalarTower [SMul S T] [IsScalarTower S T A] : IsScalarTower S T 𝓜(𝕜, A) where smul_assoc _ _ a := ext (𝕜 := 𝕜) (A := A) _ _ <| smul_assoc _ _ a.toProd instance instSMulCommClass [SMulCommClass S T A] : SMulCommClass S T 𝓜(𝕜, A) where smul_comm _ _ a := ext (𝕜 := 𝕜) (A := A) _ _ <| smul_comm _ _ a.toProd instance instIsCentralScalar {R : Type*} [Semiring R] [Module R A] [SMulCommClass 𝕜 R A] [ContinuousConstSMul R A] [IsScalarTower R A A] [SMulCommClass R A A] [Module Rᵐᵒᵖ A] [IsCentralScalar R A] : IsCentralScalar R 𝓜(𝕜, A) where op_smul_eq_smul _ a := ext (𝕜 := 𝕜) (A := A) _ _ <| op_smul_eq_smul _ a.toProd end Scalars instance instOne : One 𝓜(𝕜, A) := ⟨⟨1, fun _x _y => rfl⟩⟩ instance instMul : Mul 𝓜(𝕜, A) where mul a b := { toProd := (a.fst.comp b.fst, b.snd.comp a.snd) central := fun x y => show b.snd (a.snd x) * y = x * a.fst (b.fst y) by simp only [central] } instance instNatCast : NatCast 𝓜(𝕜, A) where natCast n := ⟨n, fun x y => by rw [Prod.snd_natCast, Prod.fst_natCast] simp only [← Nat.smul_one_eq_cast, smul_apply, one_apply, mul_smul_comm, smul_mul_assoc]⟩ instance instIntCast : IntCast 𝓜(𝕜, A) where intCast n := ⟨n, fun x y => by rw [Prod.snd_intCast, Prod.fst_intCast] simp only [← Int.smul_one_eq_cast, smul_apply, one_apply, mul_smul_comm, smul_mul_assoc]⟩ instance instPow : Pow 𝓜(𝕜, A) ℕ where pow a n := ⟨a.toProd ^ n, fun x y => by induction' n with k hk generalizing x y · rfl · rw [Prod.pow_snd, Prod.pow_fst] at hk ⊢ rw [pow_succ' a.snd, mul_apply, a.central, hk, pow_succ a.fst, mul_apply]⟩ instance instInhabited : Inhabited 𝓜(𝕜, A) := ⟨0⟩ @[simp] theorem add_toProd (a b : 𝓜(𝕜, A)) : (a + b).toProd = a.toProd + b.toProd := rfl @[simp] theorem zero_toProd : (0 : 𝓜(𝕜, A)).toProd = 0 := rfl @[simp] theorem neg_toProd (a : 𝓜(𝕜, A)) : (-a).toProd = -a.toProd := rfl @[simp] theorem sub_toProd (a b : 𝓜(𝕜, A)) : (a - b).toProd = a.toProd - b.toProd := rfl @[simp] theorem one_toProd : (1 : 𝓜(𝕜, A)).toProd = 1 := rfl @[simp] theorem natCast_toProd (n : ℕ) : (n : 𝓜(𝕜, A)).toProd = n := rfl @[simp] theorem intCast_toProd (n : ℤ) : (n : 𝓜(𝕜, A)).toProd = n := rfl @[simp] theorem pow_toProd (n : ℕ) (a : 𝓜(𝕜, A)) : (a ^ n).toProd = a.toProd ^ n := rfl theorem add_fst (a b : 𝓜(𝕜, A)) : (a + b).fst = a.fst + b.fst := rfl theorem add_snd (a b : 𝓜(𝕜, A)) : (a + b).snd = a.snd + b.snd := rfl theorem zero_fst : (0 : 𝓜(𝕜, A)).fst = 0 := rfl theorem zero_snd : (0 : 𝓜(𝕜, A)).snd = 0 := rfl theorem neg_fst (a : 𝓜(𝕜, A)) : (-a).fst = -a.fst := rfl theorem neg_snd (a : 𝓜(𝕜, A)) : (-a).snd = -a.snd := rfl theorem sub_fst (a b : 𝓜(𝕜, A)) : (a - b).fst = a.fst - b.fst := rfl theorem sub_snd (a b : 𝓜(𝕜, A)) : (a - b).snd = a.snd - b.snd := rfl theorem one_fst : (1 : 𝓜(𝕜, A)).fst = 1 := rfl theorem one_snd : (1 : 𝓜(𝕜, A)).snd = 1 := rfl @[simp] theorem mul_fst (a b : 𝓜(𝕜, A)) : (a * b).fst = a.fst * b.fst := rfl @[simp] theorem mul_snd (a b : 𝓜(𝕜, A)) : (a * b).snd = b.snd * a.snd := rfl theorem natCast_fst (n : ℕ) : (n : 𝓜(𝕜, A)).fst = n := rfl theorem natCast_snd (n : ℕ) : (n : 𝓜(𝕜, A)).snd = n := rfl theorem intCast_fst (n : ℤ) : (n : 𝓜(𝕜, A)).fst = n := rfl theorem intCast_snd (n : ℤ) : (n : 𝓜(𝕜, A)).snd = n := rfl theorem pow_fst (n : ℕ) (a : 𝓜(𝕜, A)) : (a ^ n).fst = a.fst ^ n := rfl theorem pow_snd (n : ℕ) (a : 𝓜(𝕜, A)) : (a ^ n).snd = a.snd ^ n := rfl /-- The natural injection from `DoubleCentralizer.toProd` except the second coordinate inherits `MulOpposite.op`. The ring structure on `𝓜(𝕜, A)` is the pullback under this map. -/ def toProdMulOpposite : 𝓜(𝕜, A) → (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ := fun a => (a.fst, MulOpposite.op a.snd) theorem toProdMulOpposite_injective : Function.Injective (toProdMulOpposite : 𝓜(𝕜, A) → (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ) := fun _a _b h => let h' := Prod.ext_iff.mp h ext (𝕜 := 𝕜) (A := A) _ _ <| Prod.ext h'.1 <| MulOpposite.op_injective h'.2 theorem range_toProdMulOpposite : Set.range toProdMulOpposite = { lr : (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ | ∀ x y, unop lr.2 x * y = x * lr.1 y } := Set.ext fun x => ⟨by rintro ⟨a, rfl⟩ exact a.central, fun hx => ⟨⟨(x.1, unop x.2), hx⟩, Prod.ext rfl rfl⟩⟩ /-- The ring structure is inherited as the pullback under the injective map `DoubleCentralizer.toProdMulOpposite : 𝓜(𝕜, A) → (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ` -/ instance instRing : Ring 𝓜(𝕜, A) := toProdMulOpposite_injective.ring _ rfl rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ => rfl) (fun _ _ => rfl) (fun _x _n => Prod.ext rfl <| MulOpposite.op_smul _ _) (fun _x _n => Prod.ext rfl <| MulOpposite.op_smul _ _) (fun _x _n => Prod.ext rfl <| MulOpposite.op_pow _ _) (fun _ => rfl) fun _ => rfl /-- The canonical map `DoubleCentralizer.toProd` as an additive group homomorphism. -/ @[simps] noncomputable def toProdHom : 𝓜(𝕜, A) →+ (A →L[𝕜] A) × (A →L[𝕜] A) where toFun := toProd map_zero' := rfl map_add' _x _y := rfl /-- The canonical map `DoubleCentralizer.toProdMulOpposite` as a ring homomorphism. -/ @[simps] def toProdMulOppositeHom : 𝓜(𝕜, A) →+* (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ where toFun := toProdMulOpposite map_zero' := rfl map_one' := rfl map_add' _x _y := rfl map_mul' _x _y := rfl /-- The module structure is inherited as the pullback under the additive group monomorphism `DoubleCentralizer.toProd : 𝓜(𝕜, A) →+ (A →L[𝕜] A) × (A →L[𝕜] A)` -/ noncomputable instance instModule {S : Type*} [Semiring S] [Module S A] [SMulCommClass 𝕜 S A] [ContinuousConstSMul S A] [IsScalarTower S A A] [SMulCommClass S A A] : Module S 𝓜(𝕜, A) := Function.Injective.module S toProdHom (ext (𝕜 := 𝕜) (A := A)) fun _x _y => rfl -- TODO: generalize to `Algebra S 𝓜(𝕜, A)` once `ContinuousLinearMap.algebra` is generalized. instance instAlgebra : Algebra 𝕜 𝓜(𝕜, A) where algebraMap := { toFun k := { toProd := algebraMap 𝕜 ((A →L[𝕜] A) × (A →L[𝕜] A)) k central := fun x y => by simp_rw [Prod.algebraMap_apply, Algebra.algebraMap_eq_smul_one, smul_apply, one_apply, mul_smul_comm, smul_mul_assoc] } map_one' := ext (𝕜 := 𝕜) (A := A) _ _ <| map_one <| algebraMap 𝕜 ((A →L[𝕜] A) × (A →L[𝕜] A)) map_mul' _ _ := ext (𝕜 := 𝕜) (A := A) _ _ <| Prod.ext (map_mul (algebraMap 𝕜 (A →L[𝕜] A)) _ _) ((map_mul (algebraMap 𝕜 (A →L[𝕜] A)) _ _).trans (Algebra.commutes _ _)) map_zero' := ext (𝕜 := 𝕜) (A := A) _ _ <| map_zero <| algebraMap 𝕜 ((A →L[𝕜] A) × (A →L[𝕜] A)) map_add' _ _ := ext (𝕜 := 𝕜) (A := A) _ _ <| map_add (algebraMap 𝕜 ((A →L[𝕜] A) × (A →L[𝕜] A))) _ _ } commutes' _ _ := ext (𝕜 := 𝕜) (A := A) _ _ <| Prod.ext (Algebra.commutes _ _) (Algebra.commutes _ _).symm smul_def' _ _ := ext (𝕜 := 𝕜) (A := A) _ _ <| Prod.ext (Algebra.smul_def _ _) ((Algebra.smul_def _ _).trans <| Algebra.commutes _ _) @[simp] theorem algebraMap_toProd (k : 𝕜) : (algebraMap 𝕜 𝓜(𝕜, A) k).toProd = algebraMap 𝕜 _ k := rfl theorem algebraMap_fst (k : 𝕜) : (algebraMap 𝕜 𝓜(𝕜, A) k).fst = algebraMap 𝕜 _ k := rfl theorem algebraMap_snd (k : 𝕜) : (algebraMap 𝕜 𝓜(𝕜, A) k).snd = algebraMap 𝕜 _ k := rfl /-! ### Star structure -/ section Star variable [StarRing 𝕜] [StarRing A] [StarModule 𝕜 A] [NormedStarGroup A] /-- The star operation on `a : 𝓜(𝕜, A)` is given by `(star a).toProd = (star ∘ a.snd ∘ star, star ∘ a.fst ∘ star)`. -/ instance instStar : Star 𝓜(𝕜, A) where star a := { fst := (((starₗᵢ 𝕜 : A ≃ₗᵢ⋆[𝕜] A) : A →L⋆[𝕜] A).comp a.snd).comp ((starₗᵢ 𝕜 : A ≃ₗᵢ⋆[𝕜] A) : A →L⋆[𝕜] A) snd := (((starₗᵢ 𝕜 : A ≃ₗᵢ⋆[𝕜] A) : A →L⋆[𝕜] A).comp a.fst).comp ((starₗᵢ 𝕜 : A ≃ₗᵢ⋆[𝕜] A) : A →L⋆[𝕜] A) central := fun x y => by simpa only [star_mul, star_star] using (congr_arg star (a.central (star y) (star x))).symm } @[simp] theorem star_fst (a : 𝓜(𝕜, A)) (b : A) : (star a).fst b = star (a.snd (star b)) := rfl @[simp] theorem star_snd (a : 𝓜(𝕜, A)) (b : A) : (star a).snd b = star (a.fst (star b)) := rfl instance instStarAddMonoid : StarAddMonoid 𝓜(𝕜, A) := { DoubleCentralizer.instStar with star_involutive := fun x => by ext <;> simp only [star_fst, star_snd, star_star] star_add := fun x y => by ext <;> simp only [star_fst, star_snd, add_fst, add_snd, ContinuousLinearMap.add_apply, star_add] } instance instStarRing : StarRing 𝓜(𝕜, A) := { DoubleCentralizer.instStarAddMonoid with star_mul := fun a b => by ext <;> simp only [star_fst, star_snd, mul_fst, mul_snd, star_star, ContinuousLinearMap.coe_mul, Function.comp_apply] } instance instStarModule : StarModule 𝕜 𝓜(𝕜, A) := { DoubleCentralizer.instStarAddMonoid (𝕜 := 𝕜) (A := A) with star_smul := fun k a => by ext <;> exact star_smul _ _ } end Star /-! ### Coercion from an algebra into its multiplier algebra -/ variable (𝕜) in /-- The natural coercion of `A` into `𝓜(𝕜, A)` given by sending `a : A` to the pair of linear maps `Lₐ Rₐ : A →L[𝕜] A` given by left- and right-multiplication by `a`, respectively. Warning: if `A = 𝕜`, then this is a coercion which is not definitionally equal to the `algebraMap 𝕜 𝓜(𝕜, 𝕜)` coercion, but these are propositionally equal. See `DoubleCentralizer.coe_eq_algebraMap` below. -/ @[coe] protected noncomputable def coe (a : A) : 𝓜(𝕜, A) := { fst := ContinuousLinearMap.mul 𝕜 A a snd := (ContinuousLinearMap.mul 𝕜 A).flip a central := fun _x _y => mul_assoc _ _ _ } /-- The natural coercion of `A` into `𝓜(𝕜, A)` given by sending `a : A` to the pair of linear maps `Lₐ Rₐ : A →L[𝕜] A` given by left- and right-multiplication by `a`, respectively. Warning: if `A = 𝕜`, then this is a coercion which is not definitionally equal to the `algebraMap 𝕜 𝓜(𝕜, 𝕜)` coercion, but these are propositionally equal. See `DoubleCentralizer.coe_eq_algebraMap` below. -/ noncomputable instance : CoeTC A 𝓜(𝕜, A) where coe := DoubleCentralizer.coe 𝕜 @[simp, norm_cast] theorem coe_fst (a : A) : (a : 𝓜(𝕜, A)).fst = ContinuousLinearMap.mul 𝕜 A a := rfl @[simp, norm_cast] theorem coe_snd (a : A) : (a : 𝓜(𝕜, A)).snd = (ContinuousLinearMap.mul 𝕜 A).flip a := rfl theorem coe_eq_algebraMap : (DoubleCentralizer.coe 𝕜 : 𝕜 → 𝓜(𝕜, 𝕜)) = algebraMap 𝕜 𝓜(𝕜, 𝕜) := by ext x : 3 · rfl -- `fst` is defeq · refine ContinuousLinearMap.ext fun y => ?_ exact mul_comm y x -- `snd` multiplies on the wrong side /-- The coercion of an algebra into its multiplier algebra as a non-unital star algebra homomorphism. -/ @[simps] noncomputable def coeHom [StarRing 𝕜] [StarRing A] [StarModule 𝕜 A] [NormedStarGroup A] : A →⋆ₙₐ[𝕜] 𝓜(𝕜, A) where toFun a := a map_smul' _ _ := ext _ _ _ _ <| Prod.ext (map_smul _ _ _) (map_smul _ _ _) map_zero' := ext _ _ _ _ <| Prod.ext (map_zero _) (map_zero _) map_add' _ _ := ext _ _ _ _ <| Prod.ext (map_add _ _ _) (map_add _ _ _) map_mul' _ _ := ext _ _ _ _ <| Prod.ext (ContinuousLinearMap.ext fun _ => (mul_assoc _ _ _)) (ContinuousLinearMap.ext fun _ => (mul_assoc _ _ _).symm) map_star' _ := ext _ _ _ _ <| Prod.ext (ContinuousLinearMap.ext fun _ => (star_star_mul _ _).symm) (ContinuousLinearMap.ext fun _ => (star_mul_star _ _).symm) /-! ### Norm structures We define the norm structure on `𝓜(𝕜, A)` as the pullback under `DoubleCentralizer.toProdMulOppositeHom : 𝓜(𝕜, A) →+* (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ`, which provides a definitional isometric embedding. Consequently, completeness of `𝓜(𝕜, A)` is obtained by proving that the range of this map is closed. In addition, we prove that `𝓜(𝕜, A)` is a normed algebra, and, when `A` is a C⋆-algebra, we show that `𝓜(𝕜, A)` is also a C⋆-algebra. Moreover, in this case, for `a : 𝓜(𝕜, A)`, `‖a‖ = ‖a.fst‖ = ‖a.snd‖`. -/ /-- The normed group structure is inherited as the pullback under the ring monomorphism `DoubleCentralizer.toProdMulOppositeHom : 𝓜(𝕜, A) →+* (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ`. -/ noncomputable instance : NormedRing 𝓜(𝕜, A) := NormedRing.induced _ _ (toProdMulOppositeHom : 𝓜(𝕜, A) →+* (A →L[𝕜] A) × (A →L[𝕜] A)ᵐᵒᵖ) (by simpa using toProdMulOpposite_injective) -- even though the definition is actually in terms of `DoubleCentralizer.toProdMulOpposite`, we -- choose to see through that here to avoid `MulOpposite.op` appearing. theorem norm_def (a : 𝓜(𝕜, A)) : ‖a‖ = ‖toProdHom a‖ := rfl theorem nnnorm_def (a : 𝓜(𝕜, A)) : ‖a‖₊ = ‖toProdHom a‖₊ := rfl theorem norm_def' (a : 𝓜(𝕜, A)) : ‖a‖ = ‖toProdMulOppositeHom a‖ := rfl theorem nnnorm_def' (a : 𝓜(𝕜, A)) : ‖a‖₊ = ‖toProdMulOppositeHom a‖₊ := rfl noncomputable instance instNormedSpace : NormedSpace 𝕜 𝓜(𝕜, A) := { DoubleCentralizer.instModule with norm_smul_le := fun k a => (norm_smul_le k a.toProdMulOpposite :) } noncomputable instance instNormedAlgebra : NormedAlgebra 𝕜 𝓜(𝕜, A) := { DoubleCentralizer.instAlgebra, DoubleCentralizer.instNormedSpace with } theorem isUniformEmbedding_toProdMulOpposite : IsUniformEmbedding (toProdMulOpposite (𝕜 := 𝕜) (A := A)) := isUniformEmbedding_comap toProdMulOpposite_injective instance [CompleteSpace A] : CompleteSpace 𝓜(𝕜, A) := by rw [completeSpace_iff_isComplete_range isUniformEmbedding_toProdMulOpposite.isUniformInducing] apply IsClosed.isComplete simp only [range_toProdMulOpposite, Set.setOf_forall] refine isClosed_iInter fun x => isClosed_iInter fun y => isClosed_eq ?_ ?_ · exact ((ContinuousLinearMap.apply 𝕜 A _).continuous.comp <| continuous_unop.comp continuous_snd).mul continuous_const exact continuous_const.mul ((ContinuousLinearMap.apply 𝕜 A _).continuous.comp continuous_fst) variable [StarRing A] [CStarRing A] /-- For `a : 𝓜(𝕜, A)`, the norms of `a.fst` and `a.snd` coincide, and hence these also coincide with `‖a‖` which is `max (‖a.fst‖) (‖a.snd‖)`. -/ theorem norm_fst_eq_snd (a : 𝓜(𝕜, A)) : ‖a.fst‖ = ‖a.snd‖ := by -- a handy lemma for this proof have h0 : ∀ f : A →L[𝕜] A, ∀ C : ℝ≥0, (∀ b : A, ‖f b‖₊ ^ 2 ≤ C * ‖f b‖₊ * ‖b‖₊) → ‖f‖₊ ≤ C := by intro f C h have h1 : ∀ b, C * ‖f b‖₊ * ‖b‖₊ ≤ C * ‖f‖₊ * ‖b‖₊ ^ 2 := by intro b convert mul_le_mul_right' (mul_le_mul_left' (f.le_opNNNorm b) C) ‖b‖₊ using 1 ring have := NNReal.div_le_of_le_mul <| f.opNNNorm_le_bound _ <| by simpa only [sqrt_sq, sqrt_mul] using fun b ↦ sqrt_le_sqrt.2 <| (h b).trans (h1 b) convert NNReal.rpow_le_rpow this two_pos.le · simp only [NNReal.rpow_two, div_pow, sq_sqrt] simp only [sq, mul_self_div_self] · simp only [NNReal.rpow_two, sq_sqrt] have h1 : ∀ b, ‖a.fst b‖₊ ^ 2 ≤ ‖a.snd‖₊ * ‖a.fst b‖₊ * ‖b‖₊ := by intro b calc ‖a.fst b‖₊ ^ 2 = ‖star (a.fst b) * a.fst b‖₊ := by simpa only [← sq] using CStarRing.nnnorm_star_mul_self.symm _ ≤ ‖a.snd (star (a.fst b))‖₊ * ‖b‖₊ := (a.central (star (a.fst b)) b ▸ nnnorm_mul_le _ _) _ ≤ ‖a.snd‖₊ * ‖a.fst b‖₊ * ‖b‖₊ := nnnorm_star (a.fst b) ▸ mul_le_mul_right' (a.snd.le_opNNNorm _) _ have h2 : ∀ b, ‖a.snd b‖₊ ^ 2 ≤ ‖a.fst‖₊ * ‖a.snd b‖₊ * ‖b‖₊ := by intro b calc ‖a.snd b‖₊ ^ 2 = ‖a.snd b * star (a.snd b)‖₊ := by simpa only [← sq] using CStarRing.nnnorm_self_mul_star.symm _ ≤ ‖b‖₊ * ‖a.fst (star (a.snd b))‖₊ := ((a.central b (star (a.snd b))).symm ▸ nnnorm_mul_le _ _) _ = ‖a.fst (star (a.snd b))‖₊ * ‖b‖₊ := mul_comm _ _ _ ≤ ‖a.fst‖₊ * ‖a.snd b‖₊ * ‖b‖₊ := nnnorm_star (a.snd b) ▸ mul_le_mul_right' (a.fst.le_opNNNorm _) _ exact le_antisymm (h0 _ _ h1) (h0 _ _ h2) theorem nnnorm_fst_eq_snd (a : 𝓜(𝕜, A)) : ‖a.fst‖₊ = ‖a.snd‖₊ := Subtype.ext <| norm_fst_eq_snd a @[simp] theorem norm_fst (a : 𝓜(𝕜, A)) : ‖a.fst‖ = ‖a‖ := by simp only [norm_def, toProdHom_apply, Prod.norm_def, norm_fst_eq_snd, max_eq_right le_rfl] @[simp] theorem norm_snd (a : 𝓜(𝕜, A)) : ‖a.snd‖ = ‖a‖ := by rw [← norm_fst, norm_fst_eq_snd] @[simp] theorem nnnorm_fst (a : 𝓜(𝕜, A)) : ‖a.fst‖₊ = ‖a‖₊ := Subtype.ext (norm_fst a) @[simp] theorem nnnorm_snd (a : 𝓜(𝕜, A)) : ‖a.snd‖₊ = ‖a‖₊ := Subtype.ext (norm_snd a) end NontriviallyNormed section DenselyNormed variable {𝕜 A : Type*} [DenselyNormedField 𝕜] [StarRing 𝕜] variable [NonUnitalNormedRing A] [StarRing A] [CStarRing A] variable [NormedSpace 𝕜 A] [SMulCommClass 𝕜 A A] [IsScalarTower 𝕜 A A] [StarModule 𝕜 A] instance instCStarRing : CStarRing 𝓜(𝕜, A) where norm_mul_self_le := fun (a : 𝓜(𝕜, A)) => le_of_eq <| Eq.symm <| congr_arg ((↑) : ℝ≥0 → ℝ) <| show ‖star a * a‖₊ = ‖a‖₊ * ‖a‖₊ by /- The essence of the argument is this: let `a = (L,R)` and recall `‖a‖ = ‖L‖`. `star a = (star ∘ R ∘ star, star ∘ L ∘ star)`. Then for any `x y : A`, we have `‖star a * a‖ = ‖(star a * a).snd‖ = ‖R (star (L (star x))) * y‖ = ‖star (L (star x)) * L y‖` Now, on the one hand, `‖star (L (star x)) * L y‖ ≤ ‖star (L (star x))‖ * ‖L y‖ = ‖L (star x)‖ * ‖L y‖ ≤ ‖L‖ ^ 2` whenever `‖x‖, ‖y‖ ≤ 1`, so the supremum over all such `x, y` is at most `‖L‖ ^ 2`. On the other hand, for any `‖z‖ ≤ 1`, we may choose `x := star z` and `y := z` to get: `‖star (L (star x)) * L y‖ = ‖star (L z) * (L z)‖ = ‖L z‖ ^ 2`, and taking the supremum over all such `z` yields that the supremum is at least `‖L‖ ^ 2`. It is the latter part of the argument where `DenselyNormedField 𝕜` is required (for `sSup_unitClosedBall_eq_nnnorm`). -/ have hball : (Metric.closedBall (0 : A) 1).Nonempty := Metric.nonempty_closedBall.2 zero_le_one have key : ∀ x y, ‖x‖₊ ≤ 1 → ‖y‖₊ ≤ 1 → ‖a.snd (star (a.fst (star x))) * y‖₊ ≤ ‖a‖₊ * ‖a‖₊ := by intro x y hx hy rw [a.central] calc ‖star (a.fst (star x)) * a.fst y‖₊ ≤ ‖a.fst (star x)‖₊ * ‖a.fst y‖₊ := nnnorm_star (a.fst (star x)) ▸ nnnorm_mul_le _ _ _ ≤ ‖a.fst‖₊ * 1 * (‖a.fst‖₊ * 1) := (mul_le_mul' (a.fst.le_opNorm_of_le ((nnnorm_star x).trans_le hx)) (a.fst.le_opNorm_of_le hy)) _ ≤ ‖a‖₊ * ‖a‖₊ := by simp only [mul_one, nnnorm_fst, le_rfl] rw [← nnnorm_snd] simp only [mul_snd, ← sSup_unitClosedBall_eq_nnnorm, star_snd, mul_apply] simp only [← @opNNNorm_mul_apply 𝕜 _ A] simp only [← sSup_unitClosedBall_eq_nnnorm, mul_apply'] refine csSup_eq_of_forall_le_of_forall_lt_exists_gt (hball.image _) ?_ fun r hr => ?_ · rintro - ⟨x, hx, rfl⟩ refine csSup_le (hball.image _) ?_ rintro - ⟨y, hy, rfl⟩ exact key x y (mem_closedBall_zero_iff.1 hx) (mem_closedBall_zero_iff.1 hy) · simp only [Set.mem_image, exists_exists_and_eq_and] have hr' : NNReal.sqrt r < ‖a‖₊ := ‖a‖₊.sqrt_mul_self ▸ NNReal.sqrt_lt_sqrt.2 hr simp_rw [← nnnorm_fst, ← sSup_unitClosedBall_eq_nnnorm] at hr' obtain ⟨_, ⟨x, hx, rfl⟩, hxr⟩ := exists_lt_of_lt_csSup (hball.image _) hr' have hx' : ‖x‖₊ ≤ 1 := mem_closedBall_zero_iff.1 hx refine ⟨star x, mem_closedBall_zero_iff.2 ((nnnorm_star x).trans_le hx'), ?_⟩ refine lt_csSup_of_lt ?_ ⟨x, hx, rfl⟩ ?_ · refine ⟨‖a‖₊ * ‖a‖₊, ?_⟩ rintro - ⟨y, hy, rfl⟩ exact key (star x) y ((nnnorm_star x).trans_le hx') (mem_closedBall_zero_iff.1 hy) · simpa only [a.central, star_star, CStarRing.nnnorm_star_mul_self, NNReal.sq_sqrt, ← sq] using pow_lt_pow_left₀ hxr zero_le' two_ne_zero end DenselyNormed noncomputable instance {A : Type*} [NonUnitalCStarAlgebra A] : CStarAlgebra 𝓜(ℂ, A) where end DoubleCentralizer
ErdosGinzburgZiv.lean
/- Copyright (c) 2023 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Algebra.BigOperators.Ring.Finset import Mathlib.Data.Multiset.Fintype import Mathlib.FieldTheory.ChevalleyWarning /-! # The Erdős–Ginzburg–Ziv theorem This file proves the Erdős–Ginzburg–Ziv theorem as a corollary of Chevalley-Warning. This theorem states that among any (not necessarily distinct) `2 * n - 1` elements of `ZMod n`, we can find `n` elements of sum zero. ## Main declarations * `Int.erdos_ginzburg_ziv`: The Erdős–Ginzburg–Ziv theorem stated using sequences in `ℤ` * `ZMod.erdos_ginzburg_ziv`: The Erdős–Ginzburg–Ziv theorem stated using sequences in `ZMod n` -/ open Finset MvPolynomial variable {ι : Type*} section prime variable {p : ℕ} [Fact p.Prime] {s : Finset ι} set_option linter.unusedVariables false in /-- The first multivariate polynomial used in the proof of Erdős–Ginzburg–Ziv. -/ private noncomputable def f₁ (s : Finset ι) (a : ι → ZMod p) : MvPolynomial s (ZMod p) := ∑ i, X i ^ (p - 1) /-- The second multivariate polynomial used in the proof of Erdős–Ginzburg–Ziv. -/ private noncomputable def f₂ (s : Finset ι) (a : ι → ZMod p) : MvPolynomial s (ZMod p) := ∑ i : s, a i • X i ^ (p - 1) private lemma totalDegree_f₁_add_totalDegree_f₂ {a : ι → ZMod p} : (f₁ s a).totalDegree + (f₂ s a).totalDegree < 2 * p - 1 := by calc _ ≤ (p - 1) + (p - 1) := by gcongr <;> apply totalDegree_finsetSum_le <;> rintro i _ · exact (totalDegree_X_pow ..).le · exact (totalDegree_smul_le ..).trans (totalDegree_X_pow ..).le _ < 2 * p - 1 := by have := (Fact.out : p.Prime).two_le; omega /-- The prime case of the **Erdős–Ginzburg–Ziv theorem** for `ℤ/pℤ`. Any sequence of `2 * p - 1` elements of `ZMod p` contains a subsequence of `p` elements whose sum is zero. -/ private theorem ZMod.erdos_ginzburg_ziv_prime (a : ι → ZMod p) (hs : #s = 2 * p - 1) : ∃ t ⊆ s, #t = p ∧ ∑ i ∈ t, a i = 0 := by haveI : NeZero p := inferInstance classical -- Let `N` be the number of common roots of our polynomials `f₁` and `f₂` (`f s ff` and `f s tt`). set N := Fintype.card {x // eval x (f₁ s a) = 0 ∧ eval x (f₂ s a) = 0} -- Zero is a common root to `f₁` and `f₂`, so `N` is nonzero let zero_sol : {x // eval x (f₁ s a) = 0 ∧ eval x (f₂ s a) = 0} := ⟨0, by simp [f₁, f₂, map_sum, (Fact.out : p.Prime).one_lt, tsub_eq_zero_iff_le]⟩ have hN₀ : 0 < N := @Fintype.card_pos _ _ ⟨zero_sol⟩ have hs' : 2 * p - 1 = Fintype.card s := by simp [hs] -- Chevalley-Warning gives us that `p ∣ n` because the total degrees of `f₁` and `f₂` are at most -- `p - 1`, and we have `2 * p - 1 > 2 * (p - 1)` variables. have hpN : p ∣ N := char_dvd_card_solutions_of_add_lt p (totalDegree_f₁_add_totalDegree_f₂.trans_eq hs') -- Hence, `2 ≤ p ≤ N` and we can make a common root `x ≠ 0`. obtain ⟨x, hx⟩ := Fintype.exists_ne_of_one_lt_card ((Fact.out : p.Prime).one_lt.trans_le <| Nat.le_of_dvd hN₀ hpN) zero_sol -- This common root gives us the required subsequence, namely the `i ∈ s` such that `x i ≠ 0`. refine ⟨({a | x.1 a ≠ 0} : Finset _).map ⟨(↑), Subtype.val_injective⟩, ?_, ?_, ?_⟩ · simp +contextual [subset_iff] -- From `f₁ x = 0`, we get that `p` divides the number of `a` such that `x a ≠ 0`. · rw [card_map] refine Nat.eq_of_dvd_of_lt_two_mul (Finset.card_pos.2 ?_).ne' ?_ <| (Finset.card_filter_le _ _).trans_lt ?_ -- This number is nonzero because `x ≠ 0`. · rw [← Subtype.coe_ne_coe, Function.ne_iff] at hx exact hx.imp (fun a ha ↦ mem_filter.2 ⟨Finset.mem_attach _ _, ha⟩) · rw [← CharP.cast_eq_zero_iff (ZMod p), ← Finset.sum_boole] simpa only [f₁, map_sum, ZMod.pow_card_sub_one, map_pow, eval_X] using x.2.1 -- And it is at most `2 * p - 1`, so it must be `p`. · rw [univ_eq_attach, card_attach, hs] exact tsub_lt_self (mul_pos zero_lt_two (Fact.out : p.Prime).pos) zero_lt_one -- From `f₂ x = 0`, we get that `p` divides the sum of the `a ∈ s` such that `x a ≠ 0`. · simpa [f₂, ZMod.pow_card_sub_one, Finset.sum_filter] using x.2.2 /-- The prime case of the **Erdős–Ginzburg–Ziv theorem** for `ℤ`. Any sequence of `2 * p - 1` elements of `ℤ` contains a subsequence of `p` elements whose sum is divisible by `p`. -/ private theorem Int.erdos_ginzburg_ziv_prime (a : ι → ℤ) (hs : #s = 2 * p - 1) : ∃ t ⊆ s, #t = p ∧ ↑p ∣ ∑ i ∈ t, a i := by simpa [← Int.cast_sum, ZMod.intCast_zmod_eq_zero_iff_dvd] using ZMod.erdos_ginzburg_ziv_prime (Int.cast ∘ a) hs end prime section composite variable {n : ℕ} {s : Finset ι} /-- The **Erdős–Ginzburg–Ziv theorem** for `ℤ`. Any sequence of at least `2 * n - 1` elements of `ℤ` contains a subsequence of `n` elements whose sum is divisible by `n`. -/ theorem Int.erdos_ginzburg_ziv (a : ι → ℤ) (hs : 2 * n - 1 ≤ #s) : ∃ t ⊆ s, #t = n ∧ ↑n ∣ ∑ i ∈ t, a i := by classical -- Do induction on the prime factorisation of `n`. Note that we will apply the induction -- hypothesis with `ι := Finset ι`, so we need to generalise. induction n using Nat.prime_composite_induction generalizing ι with -- When `n := 0`, we can set `t := ∅`. | zero => exact ⟨∅, by simp⟩ -- When `n := 1`, we can take `t` to be any subset of `s` of size `2 * n - 1`. | one => simpa using exists_subset_card_eq hs -- When `n := p` is prime, we use the prime case `Int.erdos_ginzburg_ziv_prime`. | prime p hp => haveI := Fact.mk hp obtain ⟨t, hts, ht⟩ := exists_subset_card_eq hs obtain ⟨u, hut, hu⟩ := Int.erdos_ginzburg_ziv_prime a ht exact ⟨u, hut.trans hts, hu⟩ -- When `n := m * n` is composite, we pick (by induction hypothesis on `n`) `2 * m - 1` sets of -- size `n` and sums divisible by `n`. Then by induction hypothesis (on `m`) we can pick `m` of -- these sets whose sum is divisible by `m * n`. | composite m hm ihm n hn ihn => -- First, show that it is enough to have those `2 * m - 1` sets. suffices ∀ k ≤ 2 * m - 1, ∃ 𝒜 : Finset (Finset ι), #𝒜 = k ∧ (𝒜 : Set (Finset ι)).Pairwise _root_.Disjoint ∧ ∀ ⦃t⦄, t ∈ 𝒜 → t ⊆ s ∧ #t = n ∧ ↑n ∣ ∑ i ∈ t, a i by -- Assume `𝒜` is a family of `2 * m - 1` sets, each of size `n` and sum divisible by `n`. obtain ⟨𝒜, h𝒜card, h𝒜disj, h𝒜⟩ := this _ le_rfl -- By induction hypothesis on `m`, find a subfamily `ℬ` of size `m` such that the sum over -- `t ∈ ℬ` of `(∑ i ∈ t, a i) / n` is divisible by `m`. obtain ⟨ℬ, hℬ𝒜, hℬcard, hℬ⟩ := ihm (fun t ↦ (∑ i ∈ t, a i) / n) h𝒜card.ge -- We are done. refine ⟨ℬ.biUnion fun x ↦ x, biUnion_subset.2 fun t ht ↦ (h𝒜 <| hℬ𝒜 ht).1, ?_, ?_⟩ · rw [card_biUnion (h𝒜disj.mono hℬ𝒜), sum_const_nat fun t ht ↦ (h𝒜 <| hℬ𝒜 ht).2.1, hℬcard] rwa [sum_biUnion, Int.natCast_mul, mul_comm, ← Int.dvd_div_iff_mul_dvd, Int.sum_div] · exact fun t ht ↦ (h𝒜 <| hℬ𝒜 ht).2.2 · exact dvd_sum fun t ht ↦ (h𝒜 <| hℬ𝒜 ht).2.2 · exact h𝒜disj.mono hℬ𝒜 -- Now, let's find those `2 * m - 1` sets. rintro k hk -- We induct on the size `k ≤ 2 * m - 1` of the family we are constructing. induction k with -- For `k = 0`, the empty family trivially works. | zero => exact ⟨∅, by simp⟩ | succ k ih => -- At `k + 1`, call `𝒜` the existing family of size `k ≤ 2 * m - 2`. obtain ⟨𝒜, h𝒜card, h𝒜disj, h𝒜⟩ := ih (Nat.le_of_succ_le hk) -- There are at least `2 * (m * n) - 1 - k * n ≥ 2 * m - 1` elements in `s` that have not been -- taken in any element of `𝒜`. have : 2 * n - 1 ≤ #(s \ 𝒜.biUnion id) := by calc _ ≤ (2 * m - k) * n - 1 := by gcongr; omega _ = (2 * (m * n) - 1) - ∑ t ∈ 𝒜, #t := by rw [tsub_mul, mul_assoc, tsub_right_comm, sum_const_nat fun t ht ↦ (h𝒜 ht).2.1, h𝒜card] _ ≤ #s - #(𝒜.biUnion id) := by gcongr; exact card_biUnion_le _ ≤ #(s \ 𝒜.biUnion id) := le_card_sdiff .. -- So by the induction hypothesis on `n` we can find a new set `t` of size `n` and sum divisible -- by `n`. obtain ⟨t₀, ht₀, ht₀card, ht₀sum⟩ := ihn a this -- This set is distinct and disjoint from the previous ones, so we are done. have : t₀ ∉ 𝒜 := by rintro h obtain rfl : n = 0 := by simpa [← card_eq_zero, ht₀card] using sdiff_disjoint.mono ht₀ <| subset_biUnion_of_mem id h omega refine ⟨𝒜.cons t₀ this, by rw [card_cons, h𝒜card], ?_, ?_⟩ · simp only [cons_eq_insert, coe_insert, Set.pairwise_insert_of_symmetric symmetric_disjoint, mem_coe, ne_eq] exact ⟨h𝒜disj, fun t ht _ ↦ sdiff_disjoint.mono ht₀ <| subset_biUnion_of_mem id ht⟩ · simp only [cons_eq_insert, mem_insert, forall_eq_or_imp, and_assoc] exact ⟨ht₀.trans sdiff_subset, ht₀card, ht₀sum, h𝒜⟩ /-- The **Erdős–Ginzburg–Ziv theorem** for `ℤ/nℤ`. Any sequence of at least `2 * n - 1` elements of `ZMod n` contains a subsequence of `n` elements whose sum is zero. -/ theorem ZMod.erdos_ginzburg_ziv (a : ι → ZMod n) (hs : 2 * n - 1 ≤ #s) : ∃ t ⊆ s, #t = n ∧ ∑ i ∈ t, a i = 0 := by simpa [← ZMod.intCast_zmod_eq_zero_iff_dvd] using Int.erdos_ginzburg_ziv (ZMod.cast ∘ a) hs /-- The **Erdős–Ginzburg–Ziv theorem** for `ℤ` for multiset. Any multiset of at least `2 * n - 1` elements of `ℤ` contains a submultiset of `n` elements whose sum is divisible by `n`. -/ theorem Int.erdos_ginzburg_ziv_multiset (s : Multiset ℤ) (hs : 2 * n - 1 ≤ Multiset.card s) : ∃ t ≤ s, Multiset.card t = n ∧ ↑n ∣ t.sum := by obtain ⟨t, hts, ht⟩ := Int.erdos_ginzburg_ziv (s := s.toEnumFinset) Prod.fst (by simpa using hs) exact ⟨t.1.map Prod.fst, Multiset.map_fst_le_of_subset_toEnumFinset hts, by simpa using ht⟩ /-- The **Erdős–Ginzburg–Ziv theorem** for `ℤ/nℤ` for multiset. Any multiset of at least `2 * n - 1` elements of `ℤ` contains a submultiset of `n` elements whose sum is divisible by `n`. -/ theorem ZMod.erdos_ginzburg_ziv_multiset (s : Multiset (ZMod n)) (hs : 2 * n - 1 ≤ Multiset.card s) : ∃ t ≤ s, Multiset.card t = n ∧ t.sum = 0 := by obtain ⟨t, hts, ht⟩ := ZMod.erdos_ginzburg_ziv (s := s.toEnumFinset) Prod.fst (by simpa using hs) exact ⟨t.1.map Prod.fst, Multiset.map_fst_le_of_subset_toEnumFinset hts, by simpa using ht⟩ end composite
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.
all_order.v
Require Export order.
poly.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice. From mathcomp Require Import fintype bigop finset tuple div ssralg. From mathcomp Require Import countalg binomial. (******************************************************************************) (* This file provides a library for univariate polynomials over ring *) (* structures; it also provides an extended theory for polynomials whose *) (* coefficients range over commutative rings and integral domains. *) (* *) (* {poly R} == the type of polynomials with coefficients of type R, *) (* represented as lists with a non zero last element *) (* (big endian representation); the coefficient type R *) (* must have a canonical nzRingType structure cR. In *) (* fact {poly R} denotes the concrete type polynomial *) (* cR; R is just a phantom argument that lets type *) (* inferencereconstruct the (hidden) nzRingType *) (* structure cR. *) (* p : seq R == the big-endian sequence of coefficients of p, via *) (* the coercion polyseq : polynomial >-> seq. *) (* Poly s == the polynomial with coefficient sequence s (ignoring *) (* trailing zeroes). *) (* \poly_(i < n) E(i) == the polynomial of degree at most n - 1 whose *) (* coefficients are given by the general term E(i) *) (* 0, 1, - p, p + q, == the usual ring operations: {poly R} has a canonical *) (* p * q, p ^+ n, ... nzRingType structure, which is commutative / integral*) (* when R is commutative / integral, respectively. *) (* polyC c, c%:P == the constant polynomial c *) (* 'X == the (unique) variable *) (* 'X^n == a power of 'X; 'X^0 is 1, 'X^1 is convertible to 'X *) (* p`_i == the coefficient of 'X^i in p; this is in fact just *) (* the ring_scope notation generic seq-indexing using *) (* nth 0%R, combined with the polyseq coercion. *) (* *** The multi-rule coefE simplifies p`_i *) (* coefp i == the linear function p |-> p`_i (self-exapanding). *) (* size p == 1 + the degree of p, or 0 if p = 0 (this is the *) (* generic seq function combined with polyseq). *) (* lead_coef p == the coefficient of the highest monomial in p, or 0 *) (* if p = 0 (hence lead_coef p = 0 iff p = 0) *) (* p \is monic <=> lead_coef p == 1 (0 is not monic). *) (* p \is a polyOver S <=> the coefficients of p satisfy S; S should have a *) (* key that should be (at least) an addrPred. *) (* p.[x] == the evaluation of a polynomial p at a point x using *) (* the Horner scheme *) (* *** The multi-rule hornerE (resp., hornerE_comm) unwinds *) (* horner evaluation of a polynomial expression (resp., *) (* in a non commutative ring, with side conditions). *) (* p^`() == formal derivative of p *) (* p^`(n) == formal n-derivative of p *) (* p^`N(n) == formal n-derivative of p divided by n! *) (* p \Po q == polynomial composition; because this is naturally a *) (* a linear morphism in the first argument, this *) (* notation is transposed (q comes before p for redex *) (* selection, etc). *) (* := \sum(i < size p) p`_i *: q ^+ i *) (* odd_poly p == monomials of odd degree of p *) (* even_poly p == monomials of even degree of p *) (* take_poly n p == polynomial p without its monomials of degree >= n *) (* drop_poly n p == polynomial p divided by X^n *) (* comm_poly p x == x and p.[x] commute; this is a sufficient condition *) (* for evaluating (q * p).[x] as q.[x] * p.[x] when R *) (* is not commutative. *) (* comm_coef p x == x commutes with all the coefficients of p (clearly, *) (* this implies comm_poly p x). *) (* root p x == x is a root of p, i.e., p.[x] = 0 *) (* n.-unity_root x == x is an nth root of unity, i.e., a root of 'X^n - 1 *) (* n.-primitive_root x == x is a primitive nth root of unity, i.e., n is the *) (* least positive integer m > 0 such that x ^+ m = 1. *) (* *** The submodule poly.UnityRootTheory can be used to *) (* import selectively the part of the theory of roots *) (* of unity that doesn't mention polynomials explicitly *) (* map_poly f p == the image of the polynomial by the function f (which *) (* (locally, p^f) is usually a ring morphism). *) (* p^:P == p lifted to {poly {poly R}} (:= map_poly polyC p). *) (* commr_rmorph f u == u commutes with the image of f (i.e., with all f x). *) (* horner_morph cfu == given cfu : commr_rmorph f u, the function mapping p *) (* to the value of map_poly f p at u; this is a ring *) (* morphism from {poly R} to the codomain of f when f *) (* is a ring morphism. *) (* horner_eval u == the function mapping p to p.[u]; this function can *) (* only be used for u in a commutative ring, so it is *) (* always a linear ring morphism from {poly R} to R. *) (* horner_alg a == given a in some R-algebra A, the function evaluating *) (* a polynomial p at a; it is always a linear ring *) (* morphism from {poly R} to A. *) (* diff_roots x y == x and y are distinct roots; if R is a field, this *) (* just means x != y, but this concept is generalized *) (* to the case where R is only a ring with units (i.e., *) (* a unitRingType); in which case it means that x and y *) (* commute, and that the difference x - y is a unit *) (* (i.e., has a multiplicative inverse) in R. *) (* to just x != y). *) (* uniq_roots s == s is a sequence or pairwise distinct roots, in the *) (* sense of diff_roots p above. *) (* *** We only show that these operations and properties are transferred by *) (* morphisms whose domain is a field (thus ensuring injectivity). *) (* We prove the factor_theorem, and the max_poly_roots inequality relating *) (* the number of distinct roots of a polynomial and its size. *) (* The some polynomial lemmas use following suffix interpretation : *) (* C - constant polynomial (as in polyseqC : a%:P = nseq (a != 0) a). *) (* X - the polynomial variable 'X (as in coefX : 'X`_i = (i == 1%N)). *) (* Xn - power of 'X (as in monicXn : monic 'X^n). *) (* *) (* Pdeg2.Field (exported by the present library) : theory of the degree 2 *) (* polynomials. *) (* Pdeg2.FieldMonic : theory of Pdeg2.Field specialized to monic polynomials. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope unity_root_scope. Import GRing.Theory. Local Open Scope ring_scope. Reserved Notation "{ 'poly' T }" (format "{ 'poly' T }"). Reserved Notation "c %:P" (format "c %:P"). Reserved Notation "p ^:P" (format "p ^:P"). Reserved Notation "'X". Reserved Notation "''X^' n" (at level 1, format "''X^' n"). Reserved Notation "\poly_ ( i < n ) E" (at level 34, E at level 36, i, n at level 50, format "\poly_ ( i < n ) E"). Reserved Notation "p \Po q" (at level 50). Reserved Notation "p ^`N ( n )" (format "p ^`N ( n )"). Reserved Notation "n .-unity_root" (format "n .-unity_root"). Reserved Notation "n .-primitive_root" (format "n .-primitive_root"). Local Notation simp := Monoid.simpm. Section Polynomial. Variable R : nzSemiRingType. (* Defines a polynomial as a sequence with <> 0 last element *) Record polynomial := Polynomial {polyseq :> seq R; _ : last 1 polyseq != 0}. HB.instance Definition _ := [isSub for polyseq]. HB.instance Definition _ := [Choice of polynomial by <:]. Lemma poly_inj : injective polyseq. Proof. exact: val_inj. Qed. Definition coefp i (p : polynomial) := p`_i. End Polynomial. (* We need to break off the section here to let the Bind Scope directives *) (* take effect. *) Bind Scope ring_scope with polynomial. Arguments polynomial R%_type. Arguments polyseq {R} p%_R. Arguments poly_inj {R} [p1%_R p2%_R] : rename. Arguments coefp {R} i%_N / p%_R. Notation "{ 'poly' T }" := (polynomial T) : type_scope. Section SemiPolynomialTheory. Variable R : nzSemiRingType. Implicit Types (a b c x y z : R) (p q r d : {poly R}). Definition lead_coef p := p`_(size p).-1. Lemma lead_coefE p : lead_coef p = p`_(size p).-1. Proof. by []. Qed. Definition poly_nil := @Polynomial R [::] (oner_neq0 R). Definition polyC c : {poly R} := insubd poly_nil [:: c]. Local Notation "c %:P" := (polyC c). (* Remember the boolean (c != 0) is coerced to 1 if true and 0 if false *) Lemma polyseqC c : c%:P = nseq (c != 0) c :> seq R. Proof. by rewrite val_insubd /=; case: (c == 0). Qed. Lemma size_polyC c : size c%:P = (c != 0). Proof. by rewrite polyseqC size_nseq. Qed. Lemma coefC c i : c%:P`_i = if i == 0 then c else 0. Proof. by rewrite polyseqC; case: i => [|[]]; case: eqP. Qed. Lemma polyCK : cancel polyC (coefp 0). Proof. by move=> c; rewrite [coefp 0 _]coefC. Qed. Lemma polyC_inj : injective polyC. Proof. by move=> c1 c2 eqc12; have:= coefC c2 0; rewrite -eqc12 coefC. Qed. Lemma lead_coefC c : lead_coef c%:P = c. Proof. by rewrite /lead_coef polyseqC; case: eqP. Qed. (* Extensional interpretation (poly <=> nat -> R) *) Lemma polyP p q : nth 0 p =1 nth 0 q <-> p = q. Proof. split=> [eq_pq | -> //]; apply: poly_inj. without loss lt_pq: p q eq_pq / size p < size q. move=> IH; case: (ltngtP (size p) (size q)); try by move/IH->. by move/(@eq_from_nth _ 0); apply. case: q => q nz_q /= in lt_pq eq_pq *; case/eqP: nz_q. by rewrite (last_nth 0) -(subnKC lt_pq) /= -eq_pq nth_default ?leq_addr. Qed. Lemma size1_polyC p : size p <= 1 -> p = (p`_0)%:P. Proof. move=> le_p_1; apply/polyP=> i; rewrite coefC. by case: i => // i; rewrite nth_default // (leq_trans le_p_1). Qed. (* Builds a polynomial by extension. *) Definition cons_poly c p : {poly R} := if p is Polynomial ((_ :: _) as s) ns then @Polynomial R (c :: s) ns else c%:P. Lemma polyseq_cons c p : cons_poly c p = (if ~~ nilp p then c :: p else c%:P) :> seq R. Proof. by case: p => [[]]. Qed. Lemma size_cons_poly c p : size (cons_poly c p) = (if nilp p && (c == 0) then 0 else (size p).+1). Proof. by case: p => [[|c' s] _] //=; rewrite size_polyC; case: eqP. Qed. Lemma coef_cons c p i : (cons_poly c p)`_i = if i == 0 then c else p`_i.-1. Proof. by case: p i => [[|c' s] _] [] //=; rewrite polyseqC; case: eqP => //= _ []. Qed. (* Build a polynomial directly from a list of coefficients. *) Definition Poly := foldr cons_poly 0%:P. Lemma PolyK c s : last c s != 0 -> Poly s = s :> seq R. Proof. case: s => {c}/= [_ |c s]; first by rewrite polyseqC eqxx. elim: s c => /= [|a s IHs] c nz_c; rewrite polyseq_cons ?{}IHs //. by rewrite !polyseqC !eqxx nz_c. Qed. Lemma polyseqK p : Poly p = p. Proof. by apply: poly_inj; apply: PolyK (valP p). Qed. Lemma size_Poly s : size (Poly s) <= size s. Proof. elim: s => [|c s IHs] /=; first by rewrite polyseqC eqxx. by rewrite polyseq_cons; case: ifP => // _; rewrite size_polyC; case: (~~ _). Qed. Lemma coef_Poly s i : (Poly s)`_i = s`_i. Proof. by elim: s i => [|c s IHs] /= [|i]; rewrite !(coefC, eqxx, coef_cons) /=. Qed. (* Build a polynomial from an infinite sequence of coefficients and a bound. *) Definition poly_expanded_def n E := Poly (mkseq E n). Fact poly_key : unit. Proof. by []. Qed. Definition poly := locked_with poly_key poly_expanded_def. Canonical poly_unlockable := [unlockable fun poly]. Local Notation "\poly_ ( i < n ) E" := (poly n (fun i : nat => E)). Lemma polyseq_poly n E : E n.-1 != 0 -> \poly_(i < n) E i = mkseq [eta E] n :> seq R. Proof. rewrite unlock; case: n => [|n] nzEn; first by rewrite polyseqC eqxx. by rewrite (@PolyK 0) // -nth_last nth_mkseq size_mkseq. Qed. Lemma size_poly n E : size (\poly_(i < n) E i) <= n. Proof. by rewrite unlock (leq_trans (size_Poly _)) ?size_mkseq. Qed. Lemma size_poly_eq n E : E n.-1 != 0 -> size (\poly_(i < n) E i) = n. Proof. by move/polyseq_poly->; apply: size_mkseq. Qed. Lemma coef_poly n E k : (\poly_(i < n) E i)`_k = (if k < n then E k else 0). Proof. rewrite unlock coef_Poly. have [lt_kn | le_nk] := ltnP k n; first by rewrite nth_mkseq. by rewrite nth_default // size_mkseq. Qed. Lemma lead_coef_poly n E : n > 0 -> E n.-1 != 0 -> lead_coef (\poly_(i < n) E i) = E n.-1. Proof. by case: n => // n _ nzE; rewrite /lead_coef size_poly_eq // coef_poly leqnn. Qed. Lemma coefK p : \poly_(i < size p) p`_i = p. Proof. by apply/polyP=> i; rewrite coef_poly; case: ltnP => // /(nth_default 0)->. Qed. (* Nmodule structure for polynomial *) Definition add_poly_def p q := \poly_(i < maxn (size p) (size q)) (p`_i + q`_i). Fact add_poly_key : unit. Proof. by []. Qed. Definition add_poly := locked_with add_poly_key add_poly_def. Canonical add_poly_unlockable := [unlockable fun add_poly]. Fact coef_add_poly p q i : (add_poly p q)`_i = p`_i + q`_i. Proof. rewrite unlock coef_poly; case: leqP => //. by rewrite geq_max => /andP[le_p_i le_q_i]; rewrite !nth_default ?add0r. Qed. Fact add_polyA : associative add_poly. Proof. by move=> p q r; apply/polyP=> i; rewrite !coef_add_poly addrA. Qed. Fact add_polyC : commutative add_poly. Proof. by move=> p q; apply/polyP=> i; rewrite !coef_add_poly addrC. Qed. Fact add_poly0 : left_id 0%:P add_poly. Proof. by move=> p; apply/polyP=> i; rewrite coef_add_poly coefC if_same add0r. Qed. HB.instance Definition _ := GRing.isNmodule.Build (polynomial R) add_polyA add_polyC add_poly0. (* Properties of the zero polynomial *) Lemma polyC0 : 0%:P = 0 :> {poly R}. Proof. by []. Qed. Lemma polyseq0 : (0 : {poly R}) = [::] :> seq R. Proof. by rewrite polyseqC eqxx. Qed. Lemma size_poly0 : size (0 : {poly R}) = 0%N. Proof. by rewrite polyseq0. Qed. Lemma coef0 i : (0 : {poly R})`_i = 0. Proof. by rewrite coefC if_same. Qed. Lemma lead_coef0 : lead_coef 0 = 0 :> R. Proof. exact: lead_coefC. Qed. Lemma size_poly_eq0 p : (size p == 0) = (p == 0). Proof. by rewrite size_eq0 -polyseq0. Qed. Lemma size_poly_leq0 p : (size p <= 0) = (p == 0). Proof. by rewrite leqn0 size_poly_eq0. Qed. Lemma size_poly_leq0P p : reflect (p = 0) (size p <= 0). Proof. by apply: (iffP idP); rewrite size_poly_leq0; move/eqP. Qed. Lemma size_poly_gt0 p : (0 < size p) = (p != 0). Proof. by rewrite lt0n size_poly_eq0. Qed. Lemma gt_size_poly_neq0 p n : (size p > n)%N -> p != 0. Proof. by move=> /(leq_ltn_trans _) h; rewrite -size_poly_eq0 lt0n_neq0 ?h. Qed. Lemma nil_poly p : nilp p = (p == 0). Proof. exact: size_poly_eq0. Qed. Lemma poly0Vpos p : {p = 0} + {size p > 0}. Proof. by rewrite lt0n size_poly_eq0; case: eqVneq; [left | right]. Qed. Lemma polySpred p : p != 0 -> size p = (size p).-1.+1. Proof. by rewrite -size_poly_eq0 -lt0n => /prednK. Qed. Lemma lead_coef_eq0 p : (lead_coef p == 0) = (p == 0). Proof. rewrite -nil_poly /lead_coef nth_last. by case: p => [[|x s] /= /negbTE // _]; rewrite eqxx. Qed. Lemma polyC_eq0 (c : R) : (c%:P == 0) = (c == 0). Proof. by rewrite -nil_poly polyseqC; case: (c == 0). Qed. Lemma size_poly1P p : reflect (exists2 c, c != 0 & p = c%:P) (size p == 1). Proof. apply: (iffP eqP) => [pC | [c nz_c ->]]; last by rewrite size_polyC nz_c. have def_p: p = (p`_0)%:P by rewrite -size1_polyC ?pC. by exists p`_0; rewrite // -polyC_eq0 -def_p -size_poly_eq0 pC. Qed. Lemma size_polyC_leq1 (c : R) : (size c%:P <= 1)%N. Proof. by rewrite size_polyC; case: (c == 0). Qed. Lemma leq_sizeP p i : reflect (forall j, i <= j -> p`_j = 0) (size p <= i). Proof. apply: (iffP idP) => [hp j hij| hp]. by apply: nth_default; apply: leq_trans hij. case: (eqVneq p) (lead_coef_eq0 p) => [->|p0]; first by rewrite size_poly0. rewrite leqNgt; apply/contraFN => hs. by apply/eqP/hp; rewrite -ltnS (ltn_predK hs). Qed. (* Size, leading coef, morphism properties of coef *) Lemma coefD p q i : (p + q)`_i = p`_i + q`_i. Proof. exact: coef_add_poly. Qed. Lemma polyCD : {morph polyC : a b / a + b}. Proof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefD !coefC ?addr0. Qed. Lemma size_polyD p q : size (p + q) <= maxn (size p) (size q). Proof. by rewrite -[+%R]/add_poly unlock; exact: size_poly. Qed. Lemma size_polyDl p q : size p > size q -> size (p + q) = size p. Proof. move=> ltqp; rewrite -[+%R]/add_poly unlock size_poly_eq (maxn_idPl (ltnW _))//. by rewrite addrC nth_default ?simp ?nth_last //; case: p ltqp => [[]]. Qed. Lemma size_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) : size (\sum_(i <- r | P i) F i) <= \max_(i <- r | P i) size (F i). Proof. elim/big_rec2: _ => [|i p q _ IHp]; first by rewrite size_poly0. by rewrite -(maxn_idPr IHp) maxnA leq_max size_polyD. Qed. Lemma lead_coefDl p q : size p > size q -> lead_coef (p + q) = lead_coef p. Proof. move=> ltqp; rewrite /lead_coef coefD size_polyDl //. by rewrite addrC nth_default ?simp // -ltnS (ltn_predK ltqp). Qed. Lemma lead_coefDr p q : size q > size p -> lead_coef (p + q) = lead_coef q. Proof. by move/lead_coefDl<-; rewrite addrC. Qed. (* Polynomial semiring structure. *) Definition mul_poly_def p q := \poly_(i < (size p + size q).-1) (\sum_(j < i.+1) p`_j * q`_(i - j)). Fact mul_poly_key : unit. Proof. by []. Qed. Definition mul_poly := locked_with mul_poly_key mul_poly_def. Canonical mul_poly_unlockable := [unlockable fun mul_poly]. Fact coef_mul_poly p q i : (mul_poly p q)`_i = \sum_(j < i.+1) p`_j * q`_(i - j)%N. Proof. rewrite unlock coef_poly -subn1 ltn_subRL add1n; case: leqP => // le_pq_i1. rewrite big1 // => j _; have [lq_q_ij | gt_q_ij] := leqP (size q) (i - j). by rewrite [q`__]nth_default ?mulr0. rewrite nth_default ?mul0r // -(leq_add2r (size q)) (leq_trans le_pq_i1) //. by rewrite -leq_subLR -subnSK. Qed. Fact coef_mul_poly_rev p q i : (mul_poly p q)`_i = \sum_(j < i.+1) p`_(i - j)%N * q`_j. Proof. rewrite coef_mul_poly (reindex_inj rev_ord_inj) /=. by apply: eq_bigr => j _; rewrite (sub_ordK j). Qed. Fact mul_polyA : associative mul_poly. Proof. move=> p q r; apply/polyP=> i; rewrite coef_mul_poly coef_mul_poly_rev. pose coef3 j k := p`_j * (q`_(i - j - k)%N * r`_k). transitivity (\sum_(j < i.+1) \sum_(k < i.+1 | k <= i - j) coef3 j k). apply: eq_bigr => /= j _; rewrite coef_mul_poly_rev big_distrr /=. by rewrite (big_ord_narrow_leq (leq_subr _ _)). rewrite (exchange_big_dep predT) //=; apply: eq_bigr => k _. transitivity (\sum_(j < i.+1 | j <= i - k) coef3 j k). apply: eq_bigl => j; rewrite -ltnS -(ltnS j) -!subSn ?leq_ord //. by rewrite -subn_gt0 -(subn_gt0 j) -!subnDA addnC. rewrite (big_ord_narrow_leq (leq_subr _ _)) coef_mul_poly big_distrl /=. by apply: eq_bigr => j _; rewrite /coef3 -!subnDA addnC mulrA. Qed. Fact mul_1poly : left_id 1%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Fact mul_poly1 : right_id 1%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly_rev big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Fact mul_polyDl : left_distributive mul_poly +%R. Proof. move=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split. by apply: eq_bigr => j _; rewrite coefD mulrDl. Qed. Fact mul_polyDr : right_distributive mul_poly +%R. Proof. move=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split. by apply: eq_bigr => j _; rewrite coefD mulrDr. Qed. Fact mul_0poly : left_zero 0%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp // coefC; case: ifP. Qed. Fact mul_poly0 : right_zero 0%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly_rev big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp // coefC; case: ifP. Qed. Fact poly1_neq0 : 1%:P != 0 :> {poly R}. Proof. by rewrite polyC_eq0 oner_neq0. Qed. HB.instance Definition _ := GRing.Nmodule_isNzSemiRing.Build (polynomial R) mul_polyA mul_1poly mul_poly1 mul_polyDl mul_polyDr mul_0poly mul_poly0 poly1_neq0. Lemma polyC1 : 1%:P = 1 :> {poly R}. Proof. by []. Qed. Lemma polyseq1 : (1 : {poly R}) = [:: 1] :> seq R. Proof. by rewrite polyseqC oner_neq0. Qed. Lemma size_poly1 : size (1 : {poly R}) = 1. Proof. by rewrite polyseq1. Qed. Lemma coef1 i : (1 : {poly R})`_i = (i == 0)%:R. Proof. by case: i => [|i]; rewrite polyseq1 /= ?nth_nil. Qed. Lemma lead_coef1 : lead_coef 1 = 1 :> R. Proof. exact: lead_coefC. Qed. Lemma coefM p q i : (p * q)`_i = \sum_(j < i.+1) p`_j * q`_(i - j)%N. Proof. exact: coef_mul_poly. Qed. Lemma coefMr p q i : (p * q)`_i = \sum_(j < i.+1) p`_(i - j)%N * q`_j. Proof. exact: coef_mul_poly_rev. Qed. Lemma coef0M p q : (p * q)`_0 = p`_0 * q`_0. Proof. by rewrite coefM big_ord1. Qed. Lemma coef0_prod I rI (F : I -> {poly R}) P : (\prod_(i <- rI| P i) F i)`_0 = \prod_(i <- rI | P i) (F i)`_0. Proof. by apply: (big_morph _ coef0M); rewrite coef1 eqxx. Qed. Lemma size_polyMleq p q : size (p * q) <= (size p + size q).-1. Proof. by rewrite -[*%R]/mul_poly unlock size_poly. Qed. Lemma mul_lead_coef p q : lead_coef p * lead_coef q = (p * q)`_(size p + size q).-2. Proof. pose dp := (size p).-1; pose dq := (size q).-1. have [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 !mul0r coef0. have [-> | nz_q] := eqVneq q 0; first by rewrite lead_coef0 !mulr0 coef0. have ->: (size p + size q).-2 = (dp + dq)%N. by do 2!rewrite polySpred // addSn addnC. have lt_p_pq: dp < (dp + dq).+1 by rewrite ltnS leq_addr. rewrite coefM (bigD1 (Ordinal lt_p_pq)) ?big1 ?simp ?addKn //= => i. rewrite -val_eqE neq_ltn /= => /orP[lt_i_p | gt_i_p]; last first. by rewrite nth_default ?mul0r //; rewrite -polySpred in gt_i_p. rewrite [q`__]nth_default ?mulr0 //= -subSS -{1}addnS -polySpred //. by rewrite addnC -addnBA ?leq_addr. Qed. Lemma size_proper_mul p q : lead_coef p * lead_coef q != 0 -> size (p * q) = (size p + size q).-1. Proof. apply: contraNeq; rewrite mul_lead_coef eqn_leq size_polyMleq -ltnNge => lt_pq. by rewrite nth_default // -subn1 -(leq_add2l 1) -leq_subLR leq_sub2r. Qed. Lemma lead_coef_proper_mul p q : let c := lead_coef p * lead_coef q in c != 0 -> lead_coef (p * q) = c. Proof. by move=> /= nz_c; rewrite mul_lead_coef -size_proper_mul. Qed. Lemma size_poly_prod_leq (I : finType) (P : pred I) (F : I -> {poly R}) : size (\prod_(i | P i) F i) <= (\sum_(i | P i) size (F i)).+1 - #|P|. Proof. rewrite -sum1_card. elim/big_rec3: _ => [|i n m p _ IHp]; first by rewrite size_poly1. have [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0. rewrite (leq_trans (size_polyMleq _ _)) // subnS -!subn1 leq_sub2r //. rewrite -addnS -addnBA ?leq_add2l // ltnW // -subn_gt0 (leq_trans _ IHp) //. by rewrite polySpred. Qed. Lemma coefCM c p i : (c%:P * p)`_i = c * p`_i. Proof. rewrite coefM big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Lemma coefMC c p i : (p * c%:P)`_i = p`_i * c. Proof. rewrite coefMr big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Lemma polyCM : {morph polyC : a b / a * b}. Proof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefCM !coefC ?simp. Qed. Lemma size_poly_exp_leq p n : size (p ^+ n) <= ((size p).-1 * n).+1. Proof. elim: n => [|n IHn]; first by rewrite size_poly1. have [-> | nzp] := poly0Vpos p; first by rewrite exprS mul0r size_poly0. rewrite exprS (leq_trans (size_polyMleq _ _)) //. by rewrite -{1}(prednK nzp) mulnS -addnS leq_add2l. Qed. End SemiPolynomialTheory. #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyD`")] Notation size_add := size_polyD (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyDl`")] Notation size_addl := size_polyDl (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyMleq`")] Notation size_mul_leq := size_polyMleq (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_poly_prod_leq`")] Notation size_prod_leq := size_poly_prod_leq (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_poly_exp_leq`")] Notation size_exp_leq := size_poly_exp_leq (only parsing). Section PolynomialTheory. Variable R : nzRingType. Implicit Types (a b c x y z : R) (p q r d : {poly R}). Local Notation "c %:P" := (polyC c). Local Notation "\poly_ ( i < n ) E" := (poly n (fun i : nat => E)). (* Zmodule structure for polynomial *) Definition opp_poly_def p := \poly_(i < size p) - p`_i. Fact opp_poly_key : unit. Proof. by []. Qed. Definition opp_poly := locked_with opp_poly_key opp_poly_def. Canonical opp_poly_unlockable := [unlockable fun opp_poly]. Fact coef_opp_poly p i : (opp_poly p)`_i = - p`_i. Proof. rewrite unlock coef_poly /=. by case: leqP => // le_p_i; rewrite nth_default ?oppr0. Qed. Fact add_polyN : left_inverse 0%:P opp_poly (@add_poly _). Proof. move=> p; apply/polyP=> i. by rewrite coef_add_poly coef_opp_poly coefC if_same addNr. Qed. HB.instance Definition _ := GRing.Nmodule_isZmodule.Build (polynomial R) add_polyN. (* Size, leading coef, morphism properties of coef *) Lemma coefN p i : (- p)`_i = - p`_i. Proof. exact: coef_opp_poly. Qed. Lemma coefB p q i : (p - q)`_i = p`_i - q`_i. Proof. by rewrite coefD coefN. Qed. HB.instance Definition _ i := GRing.isZmodMorphism.Build {poly R} R (coefp i) (fun p => (coefB p)^~ i). Lemma coefMn p n i : (p *+ n)`_i = p`_i *+ n. Proof. exact: (raddfMn (coefp i)). Qed. Lemma coefMNn p n i : (p *- n)`_i = p`_i *- n. Proof. by rewrite coefN coefMn. Qed. Lemma coef_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) k : (\sum_(i <- r | P i) F i)`_k = \sum_(i <- r | P i) (F i)`_k. Proof. exact: (raddf_sum (coefp k)). Qed. Lemma polyCN : {morph (@polyC R) : c / - c}. Proof. by move=> c; apply/polyP=> [[|i]]; rewrite coefN !coefC ?oppr0. Qed. Lemma polyCB : {morph (@polyC R) : a b / a - b}. Proof. by move=> a b; rewrite polyCD polyCN. Qed. HB.instance Definition _ := GRing.isZmodMorphism.Build R {poly R} (@polyC _) polyCB. Lemma polyCMn n : {morph (@polyC R) : c / c *+ n}. Proof. exact: raddfMn. Qed. Lemma size_polyN p : size (- p) = size p. Proof. by apply/eqP; rewrite eqn_leq -{3}(opprK p) -[-%R]/opp_poly unlock !size_poly. Qed. Lemma lead_coefN p : lead_coef (- p) = - lead_coef p. Proof. by rewrite /lead_coef size_polyN coefN. Qed. (* Polynomial ring structure. *) Fact polyC_is_monoid_morphism : monoid_morphism (@polyC R). Proof. by split; last apply: polyCM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `polyC_is_monoid_morphism` instead")] Definition polyC_multiplicative := (fun g => (g.2, g.1)) polyC_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build R {poly R} (@polyC R) polyC_is_monoid_morphism. Lemma polyC_exp n : {morph (@polyC R) : c / c ^+ n}. Proof. exact: rmorphXn. Qed. Lemma polyC_natr n : n%:R%:P = n%:R :> {poly R}. Proof. by rewrite rmorph_nat. Qed. Lemma pchar_poly : [pchar {poly R}] =i [pchar R]. Proof. move=> p; rewrite !inE; congr (_ && _). apply/eqP/eqP=> [/(congr1 val) /=|]; last by rewrite -polyC_natr => ->. by rewrite polyseq0 -polyC_natr polyseqC; case: eqP. Qed. Lemma size_Msign p n : size ((-1) ^+ n * p) = size p. Proof. by rewrite -signr_odd; case: (odd n); rewrite ?mul1r// mulN1r size_polyN. Qed. Fact coefp0_is_monoid_morphism : monoid_morphism (coefp 0 : {poly R} -> R). Proof. split=> [|p q]; first by rewrite polyCK. by rewrite [coefp 0 _]coefM big_ord_recl big_ord0 addr0. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `coefp0_is_monoid_morphism` instead")] Definition coefp0_multiplicative := (fun g => (g.2, g.1)) coefp0_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly R} R (coefp 0) coefp0_is_monoid_morphism. (* Algebra structure of polynomials. *) Definition scale_poly_def a (p : {poly R}) := \poly_(i < size p) (a * p`_i). Fact scale_poly_key : unit. Proof. by []. Qed. Definition scale_poly := locked_with scale_poly_key scale_poly_def. Canonical scale_poly_unlockable := [unlockable fun scale_poly]. Fact scale_polyE a p : scale_poly a p = a%:P * p. Proof. apply/polyP=> n; rewrite unlock coef_poly coefCM. by case: leqP => // le_p_n; rewrite nth_default ?mulr0. Qed. Fact scale_polyA a b p : scale_poly a (scale_poly b p) = scale_poly (a * b) p. Proof. by rewrite !scale_polyE mulrA polyCM. Qed. Fact scale_1poly : left_id 1 scale_poly. Proof. by move=> p; rewrite scale_polyE mul1r. Qed. Fact scale_polyDr a : {morph scale_poly a : p q / p + q}. Proof. by move=> p q; rewrite !scale_polyE mulrDr. Qed. Fact scale_polyDl p : {morph scale_poly^~ p : a b / a + b}. Proof. by move=> a b /=; rewrite !scale_polyE raddfD mulrDl. Qed. Fact scale_polyAl a p q : scale_poly a (p * q) = scale_poly a p * q. Proof. by rewrite !scale_polyE mulrA. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build R (polynomial R) scale_polyA scale_1poly scale_polyDr scale_polyDl. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build R (polynomial R) scale_polyAl. Lemma mul_polyC a p : a%:P * p = a *: p. Proof. by rewrite -scale_polyE. Qed. Lemma scale_polyC a b : a *: b%:P = (a * b)%:P. Proof. by rewrite -mul_polyC polyCM. Qed. Lemma alg_polyC a : a%:A = a%:P :> {poly R}. Proof. by rewrite -mul_polyC mulr1. Qed. Lemma coefZ a p i : (a *: p)`_i = a * p`_i. Proof. rewrite -[*:%R]/scale_poly unlock coef_poly. by case: leqP => // le_p_n; rewrite nth_default ?mulr0. Qed. Lemma size_scale_leq a p : size (a *: p) <= size p. Proof. by rewrite -[*:%R]/scale_poly unlock size_poly. Qed. HB.instance Definition _ i := GRing.isScalable.Build R {poly R} R *%R (coefp i) (fun a => (coefZ a) ^~ i). HB.instance Definition _ := GRing.Linear.on (coefp 0). (* The indeterminate, at last! *) Definition polyX_def := @Poly R [:: 0; 1]. Fact polyX_key : unit. Proof. by []. Qed. Definition polyX : {poly R} := locked_with polyX_key polyX_def. Canonical polyX_unlockable := [unlockable of polyX]. Local Notation "'X" := polyX. Lemma polyseqX : 'X = [:: 0; 1] :> seq R. Proof. by rewrite unlock !polyseq_cons nil_poly eqxx /= polyseq1. Qed. Lemma size_polyX : size 'X = 2. Proof. by rewrite polyseqX. Qed. Lemma polyX_eq0 : ('X == 0) = false. Proof. by rewrite -size_poly_eq0 size_polyX. Qed. Lemma coefX i : 'X`_i = (i == 1)%:R. Proof. by case: i => [|[|i]]; rewrite polyseqX //= nth_nil. Qed. Lemma lead_coefX : lead_coef 'X = 1. Proof. by rewrite /lead_coef polyseqX. Qed. Lemma commr_polyX p : GRing.comm p 'X. Proof. apply/polyP=> i; rewrite coefMr coefM. by apply: eq_bigr => j _; rewrite coefX commr_nat. Qed. Lemma coefMX p i : (p * 'X)`_i = (if (i == 0)%N then 0 else p`_i.-1). Proof. rewrite coefMr big_ord_recl coefX ?simp. case: i => [|i]; rewrite ?big_ord0 //= big_ord_recl polyseqX subn1 /=. by rewrite big1 ?simp // => j _; rewrite nth_nil !simp. Qed. Lemma coefXM p i : ('X * p)`_i = (if (i == 0)%N then 0 else p`_i.-1). Proof. by rewrite -commr_polyX coefMX. Qed. Lemma cons_poly_def p a : cons_poly a p = p * 'X + a%:P. Proof. apply/polyP=> i; rewrite coef_cons coefD coefMX coefC. by case: ifP; rewrite !simp. Qed. Lemma poly_ind (K : {poly R} -> Type) : K 0 -> (forall p c, K p -> K (p * 'X + c%:P)) -> (forall p, K p). Proof. move=> K0 Kcons p; rewrite -[p]polyseqK. by elim: {p}(p : seq R) => //= p c IHp; rewrite cons_poly_def; apply: Kcons. Qed. Lemma polyseqXaddC a : 'X + a%:P = [:: a; 1] :> seq R. Proof. by rewrite -['X]mul1r -cons_poly_def polyseq_cons polyseq1. Qed. Lemma polyseqXsubC a : 'X - a%:P = [:: - a; 1] :> seq R. Proof. by rewrite -polyCN polyseqXaddC. Qed. Lemma size_XsubC a : size ('X - a%:P) = 2. Proof. by rewrite polyseqXsubC. Qed. Lemma size_XaddC b : size ('X + b%:P) = 2. Proof. by rewrite -[b]opprK rmorphN size_XsubC. Qed. Lemma lead_coefXaddC a : lead_coef ('X + a%:P) = 1. Proof. by rewrite lead_coefE polyseqXaddC. Qed. Lemma lead_coefXsubC a : lead_coef ('X - a%:P) = 1. Proof. by rewrite lead_coefE polyseqXsubC. Qed. Lemma polyXsubC_eq0 a : ('X - a%:P == 0) = false. Proof. by rewrite -nil_poly polyseqXsubC. Qed. Lemma size_MXaddC p c : size (p * 'X + c%:P) = (if (p == 0) && (c == 0) then 0 else (size p).+1). Proof. by rewrite -cons_poly_def size_cons_poly nil_poly. Qed. Lemma polyseqMX p : p != 0 -> p * 'X = 0 :: p :> seq R. Proof. by move=> nz_p; rewrite -[p * _]addr0 -cons_poly_def polyseq_cons nil_poly nz_p. Qed. Lemma size_mulX p : p != 0 -> size (p * 'X) = (size p).+1. Proof. by move/polyseqMX->. Qed. Lemma lead_coefMX p : lead_coef (p * 'X) = lead_coef p. Proof. have [-> | nzp] := eqVneq p 0; first by rewrite mul0r. by rewrite /lead_coef !nth_last polyseqMX. Qed. Lemma size_XmulC a : a != 0 -> size ('X * a%:P) = 2. Proof. by move=> nz_a; rewrite -commr_polyX size_mulX ?polyC_eq0 ?size_polyC nz_a. Qed. Local Notation "''X^' n" := ('X ^+ n). Lemma coefXn n i : 'X^n`_i = (i == n)%:R. Proof. by elim: n i => [|n IHn] [|i]; rewrite ?coef1 // exprS coefXM ?IHn. Qed. Lemma polyseqXn n : 'X^n = rcons (nseq n 0) 1 :> seq R. Proof. elim: n => [|n IHn]; rewrite ?polyseq1 // exprSr. by rewrite polyseqMX -?size_poly_eq0 IHn ?size_rcons. Qed. Lemma size_polyXn n : size 'X^n = n.+1. Proof. by rewrite polyseqXn size_rcons size_nseq. Qed. Lemma commr_polyXn p n : GRing.comm p 'X^n. Proof. exact/commrX/commr_polyX. Qed. Lemma lead_coefXn n : lead_coef 'X^n = 1. Proof. by rewrite /lead_coef nth_last polyseqXn last_rcons. Qed. Lemma lead_coefXnaddC n c : 0 < n -> lead_coef ('X^n + c%:P) = 1. Proof. move=> n_gt0; rewrite lead_coefDl ?lead_coefXn//. by rewrite size_polyC size_polyXn ltnS (leq_trans (leq_b1 _)). Qed. Lemma lead_coefXnsubC n c : 0 < n -> lead_coef ('X^n - c%:P) = 1. Proof. by move=> n_gt0; rewrite -polyCN lead_coefXnaddC. Qed. Lemma size_XnaddC n c : 0 < n -> size ('X^n + c%:P) = n.+1. Proof. by move=> *; rewrite size_polyDl ?size_polyXn// size_polyC; case: eqP. Qed. Lemma size_XnsubC n c : 0 < n -> size ('X^n - c%:P) = n.+1. Proof. by move=> *; rewrite -polyCN size_XnaddC. Qed. Lemma polyseqMXn n p : p != 0 -> p * 'X^n = ncons n 0 p :> seq R. Proof. case: n => [|n] nz_p; first by rewrite mulr1. elim: n => [|n IHn]; first exact: polyseqMX. by rewrite exprSr mulrA polyseqMX -?nil_poly IHn. Qed. Lemma coefMXn n p i : (p * 'X^n)`_i = if i < n then 0 else p`_(i - n). Proof. have [-> | /polyseqMXn->] := eqVneq p 0; last exact: nth_ncons. by rewrite mul0r !coef0 if_same. Qed. Lemma size_mulXn n p : p != 0 -> size (p * 'X^n) = (n + size p)%N. Proof. elim: n p => [p p_neq0| n IH p p_neq0]; first by rewrite mulr1. by rewrite exprS mulrA IH -?size_poly_eq0 size_mulX // addnS. Qed. Lemma coefXnM n p i : ('X^n * p)`_i = if i < n then 0 else p`_(i - n). Proof. by rewrite -commr_polyXn coefMXn. Qed. Lemma coef_sumMXn I (r : seq I) (P : pred I) (p : I -> R) (n : I -> nat) k : (\sum_(i <- r | P i) p i *: 'X^(n i))`_k = \sum_(i <- r | P i && (n i == k)) p i. Proof. rewrite coef_sum big_mkcondr; apply: eq_bigr => i Pi. by rewrite coefZ coefXn mulr_natr mulrb eq_sym. Qed. (* Expansion of a polynomial as an indexed sum *) Lemma poly_def n E : \poly_(i < n) E i = \sum_(i < n) E i *: 'X^i. Proof. by apply/polyP => i; rewrite coef_sumMXn coef_poly big_ord1_eq. Qed. (* Monic predicate *) Definition monic_pred := fun p => lead_coef p == 1. Arguments monic_pred _ /. Definition monic := [qualify p | monic_pred p]. Lemma monicE p : (p \is monic) = (lead_coef p == 1). Proof. by []. Qed. Lemma monicP p : reflect (lead_coef p = 1) (p \is monic). Proof. exact: eqP. Qed. Lemma monic1 : 1 \is monic. Proof. exact/eqP/lead_coef1. Qed. Lemma monicX : 'X \is monic. Proof. exact/eqP/lead_coefX. Qed. Lemma monicXn n : 'X^n \is monic. Proof. exact/eqP/lead_coefXn. Qed. Lemma monic_neq0 p : p \is monic -> p != 0. Proof. by rewrite -lead_coef_eq0 => /eqP->; apply: oner_neq0. Qed. Lemma lead_coef_monicM p q : p \is monic -> lead_coef (p * q) = lead_coef q. Proof. have [-> | nz_q] := eqVneq q 0; first by rewrite mulr0. by move/monicP=> mon_p; rewrite lead_coef_proper_mul mon_p mul1r ?lead_coef_eq0. Qed. Lemma lead_coef_Mmonic p q : q \is monic -> lead_coef (p * q) = lead_coef p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite mul0r. by move/monicP=> mon_q; rewrite lead_coef_proper_mul mon_q mulr1 ?lead_coef_eq0. Qed. Lemma size_monicM p q : p \is monic -> q != 0 -> size (p * q) = (size p + size q).-1. Proof. move/monicP=> mon_p nz_q. by rewrite size_proper_mul // mon_p mul1r lead_coef_eq0. Qed. Lemma size_Mmonic p q : p != 0 -> q \is monic -> size (p * q) = (size p + size q).-1. Proof. move=> nz_p /monicP mon_q. by rewrite size_proper_mul // mon_q mulr1 lead_coef_eq0. Qed. Lemma monicMl p q : p \is monic -> (p * q \is monic) = (q \is monic). Proof. by move=> mon_p; rewrite !monicE lead_coef_monicM. Qed. Lemma monicMr p q : q \is monic -> (p * q \is monic) = (p \is monic). Proof. by move=> mon_q; rewrite !monicE lead_coef_Mmonic. Qed. Fact monic_mulr_closed : mulr_closed monic. Proof. by split=> [|p q mon_p]; rewrite (monic1, monicMl). Qed. HB.instance Definition _ := GRing.isMulClosed.Build {poly R} monic_pred monic_mulr_closed. Lemma monic_exp p n : p \is monic -> p ^+ n \is monic. Proof. exact: rpredX. Qed. Lemma monic_prod I rI (P : pred I) (F : I -> {poly R}): (forall i, P i -> F i \is monic) -> \prod_(i <- rI | P i) F i \is monic. Proof. exact: rpred_prod. Qed. Lemma monicXaddC c : 'X + c%:P \is monic. Proof. exact/eqP/lead_coefXaddC. Qed. Lemma monicXsubC c : 'X - c%:P \is monic. Proof. exact/eqP/lead_coefXsubC. Qed. Lemma monic_prod_XsubC I rI (P : pred I) (F : I -> R) : \prod_(i <- rI | P i) ('X - (F i)%:P) \is monic. Proof. by apply: monic_prod => i _; apply: monicXsubC. Qed. Lemma lead_coef_prod_XsubC I rI (P : pred I) (F : I -> R) : lead_coef (\prod_(i <- rI | P i) ('X - (F i)%:P)) = 1. Proof. exact/eqP/monic_prod_XsubC. Qed. Lemma size_prod_XsubC I rI (F : I -> R) : size (\prod_(i <- rI) ('X - (F i)%:P)) = (size rI).+1. Proof. elim: rI => [|i r /= <-]; rewrite ?big_nil ?size_poly1 // big_cons. rewrite size_monicM ?monicXsubC ?monic_neq0 ?monic_prod_XsubC //. by rewrite size_XsubC. Qed. Lemma size_exp_XsubC n a : size (('X - a%:P) ^+ n) = n.+1. Proof. rewrite -[n]card_ord -prodr_const -big_filter size_prod_XsubC. by have [e _ _ [_ ->]] := big_enumP. Qed. Lemma monicXnaddC n c : 0 < n -> 'X^n + c%:P \is monic. Proof. by move=> n_gt0; rewrite monicE lead_coefXnaddC. Qed. Lemma monicXnsubC n c : 0 < n -> 'X^n - c%:P \is monic. Proof. by move=> n_gt0; rewrite monicE lead_coefXnsubC. Qed. (* Some facts about regular elements. *) Lemma lreg_lead p : GRing.lreg (lead_coef p) -> GRing.lreg p. Proof. move/mulrI_eq0=> reg_p; apply: mulrI0_lreg => q /eqP; apply: contraTeq => nz_q. by rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0. Qed. Lemma rreg_lead p : GRing.rreg (lead_coef p) -> GRing.rreg p. Proof. move/mulIr_eq0=> reg_p; apply: mulIr0_rreg => q /eqP; apply: contraTeq => nz_q. by rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0. Qed. Lemma lreg_lead0 p : GRing.lreg (lead_coef p) -> p != 0. Proof. by move/lreg_neq0; rewrite lead_coef_eq0. Qed. Lemma rreg_lead0 p : GRing.rreg (lead_coef p) -> p != 0. Proof. by move/rreg_neq0; rewrite lead_coef_eq0. Qed. Lemma lreg_size c p : GRing.lreg c -> size (c *: p) = size p. Proof. move=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite scaler0. rewrite -mul_polyC size_proper_mul; first by rewrite size_polyC lreg_neq0. by rewrite lead_coefC mulrI_eq0 ?lead_coef_eq0. Qed. Lemma lreg_polyZ_eq0 c p : GRing.lreg c -> (c *: p == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /lreg_size->. Qed. Lemma lead_coef_lreg c p : GRing.lreg c -> lead_coef (c *: p) = c * lead_coef p. Proof. by move=> reg_c; rewrite !lead_coefE coefZ lreg_size. Qed. Lemma rreg_size c p : GRing.rreg c -> size (p * c%:P) = size p. Proof. move=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite mul0r. rewrite size_proper_mul; first by rewrite size_polyC rreg_neq0 ?addn1. by rewrite lead_coefC mulIr_eq0 ?lead_coef_eq0. Qed. Lemma rreg_polyMC_eq0 c p : GRing.rreg c -> (p * c%:P == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /rreg_size->. Qed. Lemma rreg_div0 q r d : GRing.rreg (lead_coef d) -> size r < size d -> (q * d + r == 0) = (q == 0) && (r == 0). Proof. move=> reg_d lt_r_d; rewrite addrC addr_eq0. have [-> | nz_q] := eqVneq q 0; first by rewrite mul0r oppr0. apply: contraTF lt_r_d => /eqP->; rewrite -leqNgt size_polyN. rewrite size_proper_mul ?mulIr_eq0 ?lead_coef_eq0 //. by rewrite (polySpred nz_q) leq_addl. Qed. Lemma monic_comreg p : p \is monic -> GRing.comm p (lead_coef p)%:P /\ GRing.rreg (lead_coef p). Proof. by move/monicP->; split; [apply: commr1 | apply: rreg1]. Qed. Lemma monic_lreg p : p \is monic -> GRing.lreg p. Proof. by move=> /eqP lp1; apply/lreg_lead; rewrite lp1; apply/lreg1. Qed. Lemma monic_rreg p : p \is monic -> GRing.rreg p. Proof. by move=> /eqP lp1; apply/rreg_lead; rewrite lp1; apply/rreg1. Qed. (* Horner evaluation of polynomials *) Implicit Types s rs : seq R. Fixpoint horner_rec s x := if s is a :: s' then horner_rec s' x * x + a else 0. Definition horner p := horner_rec p. Local Notation "p .[ x ]" := (horner p x) : ring_scope. Lemma horner0 x : (0 : {poly R}).[x] = 0. Proof. by rewrite /horner polyseq0. Qed. Lemma hornerC c x : (c%:P).[x] = c. Proof. by rewrite /horner polyseqC; case: eqP; rewrite /= ?simp. Qed. Lemma hornerX x : 'X.[x] = x. Proof. by rewrite /horner polyseqX /= !simp. Qed. Lemma horner_cons p c x : (cons_poly c p).[x] = p.[x] * x + c. Proof. rewrite /horner polyseq_cons; case: nilP => //= ->. by rewrite !simp -/(_.[x]) hornerC. Qed. Lemma horner_coef0 p : p.[0] = p`_0. Proof. by rewrite /horner; case: (p : seq R) => //= c p'; rewrite !simp. Qed. Lemma hornerMXaddC p c x : (p * 'X + c%:P).[x] = p.[x] * x + c. Proof. by rewrite -cons_poly_def horner_cons. Qed. Lemma hornerMX p x : (p * 'X).[x] = p.[x] * x. Proof. by rewrite -[p * 'X]addr0 hornerMXaddC addr0. Qed. Lemma horner_Poly s x : (Poly s).[x] = horner_rec s x. Proof. by elim: s => [|a s /= <-]; rewrite (horner0, horner_cons). Qed. Lemma horner_coef p x : p.[x] = \sum_(i < size p) p`_i * x ^+ i. Proof. rewrite /horner. elim: {p}(p : seq R) => /= [|a s ->]; first by rewrite big_ord0. rewrite big_ord_recl simp addrC big_distrl /=. by congr (_ + _); apply: eq_bigr => i _; rewrite -mulrA exprSr. Qed. Lemma horner_coef_wide n p x : size p <= n -> p.[x] = \sum_(i < n) p`_i * x ^+ i. Proof. move=> le_p_n. rewrite horner_coef (big_ord_widen n (fun i => p`_i * x ^+ i)) // big_mkcond. by apply: eq_bigr => i _; case: ltnP => // le_p_i; rewrite nth_default ?simp. Qed. Lemma horner_poly n E x : (\poly_(i < n) E i).[x] = \sum_(i < n) E i * x ^+ i. Proof. rewrite (@horner_coef_wide n) ?size_poly //. by apply: eq_bigr => i _; rewrite coef_poly ltn_ord. Qed. Lemma hornerN p x : (- p).[x] = - p.[x]. Proof. rewrite -[-%R]/opp_poly unlock horner_poly horner_coef -sumrN /=. by apply: eq_bigr => i _; rewrite mulNr. Qed. Lemma hornerD p q x : (p + q).[x] = p.[x] + q.[x]. Proof. rewrite -[+%R]/(@add_poly R) unlock horner_poly; set m := maxn _ _. rewrite !(@horner_coef_wide m) ?leq_max ?leqnn ?orbT // -big_split /=. by apply: eq_bigr => i _; rewrite -mulrDl. Qed. Lemma hornerXsubC a x : ('X - a%:P).[x] = x - a. Proof. by rewrite hornerD hornerN hornerC hornerX. Qed. Lemma horner_sum I (r : seq I) (P : pred I) F x : (\sum_(i <- r | P i) F i).[x] = \sum_(i <- r | P i) (F i).[x]. Proof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (horner0, hornerD). Qed. Lemma hornerCM a p x : (a%:P * p).[x] = a * p.[x]. Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !(mulr0, horner0). by rewrite mulrDr mulrA -polyCM !hornerMXaddC IHp mulrDr mulrA. Qed. Lemma hornerZ c p x : (c *: p).[x] = c * p.[x]. Proof. by rewrite -mul_polyC hornerCM. Qed. Lemma hornerMn n p x : (p *+ n).[x] = p.[x] *+ n. Proof. by elim: n => [| n IHn]; rewrite ?horner0 // !mulrS hornerD IHn. Qed. Definition comm_coef p x := forall i, p`_i * x = x * p`_i. Definition comm_poly p x := x * p.[x] = p.[x] * x. Lemma comm_coef_poly p x : comm_coef p x -> comm_poly p x. Proof. move=> cpx; rewrite /comm_poly !horner_coef big_distrl big_distrr /=. by apply: eq_bigr => i _; rewrite /= mulrA -cpx -!mulrA commrX. Qed. Lemma comm_poly0 x : comm_poly 0 x. Proof. by rewrite /comm_poly !horner0 !simp. Qed. Lemma comm_poly1 x : comm_poly 1 x. Proof. by rewrite /comm_poly !hornerC !simp. Qed. Lemma comm_polyX x : comm_poly 'X x. Proof. by rewrite /comm_poly !hornerX. Qed. Lemma comm_polyD p q x: comm_poly p x -> comm_poly q x -> comm_poly (p + q) x. Proof. by rewrite /comm_poly hornerD mulrDr mulrDl => -> ->. Qed. Lemma commr_horner a b p : GRing.comm a b -> comm_coef p a -> GRing.comm a p.[b]. Proof. move=> cab cpa; rewrite horner_coef; apply: commr_sum => i _. by apply: commrM => //; apply: commrX. Qed. Lemma hornerM_comm p q x : comm_poly q x -> (p * q).[x] = p.[x] * q.[x]. Proof. move=> comm_qx. elim/poly_ind: p => [|p c IHp]; first by rewrite !(simp, horner0). rewrite mulrDl hornerD hornerCM -mulrA -commr_polyX mulrA hornerMX. by rewrite {}IHp -mulrA -comm_qx mulrA -mulrDl hornerMXaddC. Qed. Lemma comm_polyM p q x: comm_poly p x -> comm_poly q x -> comm_poly (p * q) x. Proof. by move=> px qx; rewrite /comm_poly hornerM_comm// mulrA px -mulrA qx mulrA. Qed. Lemma horner_exp_comm p x n : comm_poly p x -> (p ^+ n).[x] = p.[x] ^+ n. Proof. move=> comm_px; elim: n => [|n IHn]; first by rewrite hornerC. by rewrite !exprSr -IHn hornerM_comm. Qed. Lemma comm_poly_exp p n x: comm_poly p x -> comm_poly (p ^+ n) x. Proof. by move=> px; rewrite /comm_poly !horner_exp_comm// commrX. Qed. Lemma hornerXn x n : ('X^n).[x] = x ^+ n. Proof. by rewrite horner_exp_comm /comm_poly hornerX. Qed. Definition hornerE_comm := (hornerD, hornerN, hornerX, hornerC, horner_cons, simp, hornerCM, hornerZ, (fun p x => hornerM_comm p (comm_polyX x))). Definition root p : pred R := fun x => p.[x] == 0. Lemma mem_root p x : x \in root p = (p.[x] == 0). Proof. by []. Qed. Lemma rootE p x : (root p x = (p.[x] == 0)) * ((x \in root p) = (p.[x] == 0)). Proof. by []. Qed. Lemma rootP p x : reflect (p.[x] = 0) (root p x). Proof. exact: eqP. Qed. Lemma rootPt p x : reflect (p.[x] == 0) (root p x). Proof. exact: idP. Qed. Lemma rootPf p x : reflect ((p.[x] == 0) = false) (~~ root p x). Proof. exact: negPf. Qed. Lemma rootC a x : root a%:P x = (a == 0). Proof. by rewrite rootE hornerC. Qed. Lemma root0 x : root 0 x. Proof. by rewrite rootC. Qed. Lemma root1 x : ~~ root 1 x. Proof. by rewrite rootC oner_eq0. Qed. Lemma rootX x : root 'X x = (x == 0). Proof. by rewrite rootE hornerX. Qed. Lemma rootN p x : root (- p) x = root p x. Proof. by rewrite rootE hornerN oppr_eq0. Qed. Lemma root_size_gt1 a p : p != 0 -> root p a -> 1 < size p. Proof. rewrite ltnNge => nz_p; apply: contraL => /size1_polyC Dp. by rewrite Dp rootC -polyC_eq0 -Dp. Qed. Lemma root_XsubC a x : root ('X - a%:P) x = (x == a). Proof. by rewrite rootE hornerXsubC subr_eq0. Qed. Lemma root_XaddC a x : root ('X + a%:P) x = (x == - a). Proof. by rewrite -root_XsubC rmorphN opprK. Qed. Theorem factor_theorem p a : reflect (exists q, p = q * ('X - a%:P)) (root p a). Proof. apply: (iffP eqP) => [pa0 | [q ->]]; last first. by rewrite hornerM_comm /comm_poly hornerXsubC subrr ?simp. exists (\poly_(i < size p) horner_rec (drop i.+1 p) a). apply/polyP=> i; rewrite mulrBr coefB coefMX coefMC !coef_poly. apply: canRL (addrK _) _; rewrite addrC; have [le_p_i | lt_i_p] := leqP. rewrite nth_default // !simp drop_oversize ?if_same //. exact: leq_trans (leqSpred _). case: i => [|i] in lt_i_p *; last by rewrite ltnW // (drop_nth 0 lt_i_p). by rewrite drop1 /= -{}pa0 /horner; case: (p : seq R) lt_i_p. Qed. Lemma multiplicity_XsubC p a : {m | exists2 q, (p != 0) ==> ~~ root q a & p = q * ('X - a%:P) ^+ m}. Proof. have [n le_p_n] := ubnP (size p); elim: n => // n IHn in p le_p_n *. have [-> | nz_p /=] := eqVneq p 0; first by exists 0, 0; rewrite ?mul0r. have [/sig_eqW[p1 Dp] | nz_pa] := altP (factor_theorem p a); last first. by exists 0%N, p; rewrite ?mulr1. have nz_p1: p1 != 0 by apply: contraNneq nz_p => p1_0; rewrite Dp p1_0 mul0r. have /IHn[m /sig2_eqW[q nz_qa Dp1]]: size p1 < n. by rewrite Dp size_Mmonic ?monicXsubC // size_XsubC addn2 in le_p_n. by exists m.+1, q; [rewrite nz_p1 in nz_qa | rewrite exprSr mulrA -Dp1]. Qed. (* Roots of unity. *) #[deprecated(since="mathcomp 2.3.0",note="Use size_XnsubC instead.")] Lemma size_Xn_sub_1 n : n > 0 -> size ('X^n - 1 : {poly R}) = n.+1. Proof. exact/size_XnsubC. Qed. #[deprecated(since="mathcomp 2.3.0'",note="Use monicXnsubC instead.")] Lemma monic_Xn_sub_1 n : n > 0 -> 'X^n - 1 \is monic. Proof. exact/monicXnsubC. Qed. Definition root_of_unity n : pred R := root ('X^n - 1). Local Notation "n .-unity_root" := (root_of_unity n) : ring_scope. Lemma unity_rootE n z : n.-unity_root z = (z ^+ n == 1). Proof. by rewrite /root_of_unity rootE hornerD hornerN hornerXn hornerC subr_eq0. Qed. Lemma unity_rootP n z : reflect (z ^+ n = 1) (n.-unity_root z). Proof. by rewrite unity_rootE; apply: eqP. Qed. Definition primitive_root_of_unity n z := (n > 0) && [forall i : 'I_n, i.+1.-unity_root z == (i.+1 == n)]. Local Notation "n .-primitive_root" := (primitive_root_of_unity n) : ring_scope. Lemma prim_order_exists n z : n > 0 -> z ^+ n = 1 -> {m | m.-primitive_root z & (m %| n)}. Proof. move=> n_gt0 zn1. have: exists m, (m > 0) && (z ^+ m == 1) by exists n; rewrite n_gt0 /= zn1. case/ex_minnP=> m /andP[m_gt0 /eqP zm1] m_min. exists m. apply/andP; split=> //; apply/eqfunP=> [[i]] /=. rewrite leq_eqVlt unity_rootE. case: eqP => [-> _ | _]; first by rewrite zm1 eqxx. by apply: contraTF => zi1; rewrite -leqNgt m_min. have: n %% m < m by rewrite ltn_mod. apply: contraLR; rewrite -lt0n -leqNgt => nm_gt0; apply: m_min. by rewrite nm_gt0 /= expr_mod ?zn1. Qed. Section OnePrimitive. Variables (n : nat) (z : R). Hypothesis prim_z : n.-primitive_root z. Lemma prim_order_gt0 : n > 0. Proof. by case/andP: prim_z. Qed. Let n_gt0 := prim_order_gt0. Lemma prim_expr_order : z ^+ n = 1. Proof. case/andP: prim_z => _; rewrite -(prednK n_gt0) => /forallP/(_ ord_max). by rewrite unity_rootE eqxx eqb_id => /eqP. Qed. Lemma prim_expr_mod i : z ^+ (i %% n) = z ^+ i. Proof. exact: expr_mod prim_expr_order. Qed. Lemma prim_order_dvd i : (n %| i) = (z ^+ i == 1). Proof. move: n_gt0; rewrite -prim_expr_mod /dvdn -(ltn_mod i). case: {i}(i %% n)%N => [|i] lt_i; first by rewrite !eqxx. case/andP: prim_z => _ /forallP/(_ (Ordinal (ltnW lt_i)))/eqP. by rewrite unity_rootE eqn_leq andbC leqNgt lt_i. Qed. Lemma eq_prim_root_expr i j : (z ^+ i == z ^+ j) = (i == j %[mod n]). Proof. wlog le_ji: i j / j <= i. move=> IH; case: (leqP j i) => [|/ltnW] /IH //. by rewrite eq_sym (eq_sym (j %% n)%N). rewrite -{1}(subnKC le_ji) exprD -prim_expr_mod eqn_mod_dvd //. rewrite prim_order_dvd; apply/eqP/eqP=> [|->]; last by rewrite mulr1. move/(congr1 ( *%R (z ^+ (n - j %% n)))); rewrite mulrA -exprD. by rewrite subnK ?prim_expr_order ?mul1r // ltnW ?ltn_mod. Qed. Lemma exp_prim_root k : (n %/ gcdn k n).-primitive_root (z ^+ k). Proof. set d := gcdn k n; have d_gt0: (0 < d)%N by rewrite gcdn_gt0 orbC n_gt0. have [d_dv_k d_dv_n]: (d %| k /\ d %| n)%N by rewrite dvdn_gcdl dvdn_gcdr. set q := (n %/ d)%N; rewrite /q.-primitive_root ltn_divRL // n_gt0. apply/forallP=> i; rewrite unity_rootE -exprM -prim_order_dvd. rewrite -(divnK d_dv_n) -/q -(divnK d_dv_k) mulnAC dvdn_pmul2r //. apply/eqP; apply/idP/idP=> [|/eqP->]; last by rewrite dvdn_mull. rewrite Gauss_dvdr; first by rewrite eqn_leq ltn_ord; apply: dvdn_leq. by rewrite /coprime gcdnC -(eqn_pmul2r d_gt0) mul1n muln_gcdl !divnK. Qed. Lemma dvdn_prim_root m : (m %| n)%N -> m.-primitive_root (z ^+ (n %/ m)). Proof. set k := (n %/ m)%N => m_dv_n; rewrite -{1}(mulKn m n_gt0) -divnA // -/k. by rewrite -{1}(@gcdn_idPl k n _) ?exp_prim_root // -(divnK m_dv_n) dvdn_mulr. Qed. Lemma prim_root_eq0 : (z == 0) = (n == 0%N). Proof. rewrite gtn_eqF//; apply/eqP => z0; have /esym/eqP := prim_expr_order. by rewrite z0 expr0n gtn_eqF//= oner_eq0. Qed. End OnePrimitive. Lemma prim_root_exp_coprime n z k : n.-primitive_root z -> n.-primitive_root (z ^+ k) = coprime k n. Proof. move=> prim_z; have n_gt0 := prim_order_gt0 prim_z. apply/idP/idP=> [prim_zk | co_k_n]. set d := gcdn k n; have dv_d_n: (d %| n)%N := dvdn_gcdr _ _. rewrite /coprime -/d -(eqn_pmul2r n_gt0) mul1n -{2}(gcdnMl n d). rewrite -{2}(divnK dv_d_n) (mulnC _ d) -muln_gcdr (gcdn_idPr _) //. rewrite (prim_order_dvd prim_zk) -exprM -(prim_order_dvd prim_z). by rewrite muln_divCA_gcd dvdn_mulr. have zkn_1: z ^+ k ^+ n = 1 by rewrite exprAC (prim_expr_order prim_z) expr1n. have{zkn_1} [m prim_zk dv_m_n]:= prim_order_exists n_gt0 zkn_1. suffices /eqP <-: m == n by []. rewrite eqn_dvd dv_m_n -(@Gauss_dvdr n k m) 1?coprime_sym //=. by rewrite (prim_order_dvd prim_z) exprM (prim_expr_order prim_zk). Qed. (* Lifting a ring predicate to polynomials. *) Implicit Type S : {pred R}. Definition polyOver_pred S := fun p : {poly R} => all (mem S) p. Arguments polyOver_pred _ _ /. Definition polyOver S := [qualify a p | polyOver_pred S p]. Lemma polyOverS (S1 S2 : {pred R}) : {subset S1 <= S2} -> {subset polyOver S1 <= polyOver S2}. Proof. by move=> sS12 p /(all_nthP 0)S1p; apply/(all_nthP 0)=> i /S1p; apply: sS12. Qed. Lemma polyOver0 S : 0 \is a polyOver S. Proof. by rewrite qualifE /= polyseq0. Qed. Lemma polyOver_poly S n E : (forall i, i < n -> E i \in S) -> \poly_(i < n) E i \is a polyOver S. Proof. move=> S_E; apply/(all_nthP 0)=> i lt_i_p /=; rewrite coef_poly. by case: ifP => [/S_E// | /idP[]]; apply: leq_trans lt_i_p (size_poly n E). Qed. Section PolyOverAdd. Variable S : addrClosed R. Lemma polyOverP {p} : reflect (forall i, p`_i \in S) (p \in polyOver S). Proof. apply: (iffP (all_nthP 0)) => [Sp i | Sp i _]; last exact: Sp. by have [/Sp // | /(nth_default 0)->] := ltnP i (size p); apply: rpred0. Qed. Lemma polyOverC c : (c%:P \in polyOver S) = (c \in S). Proof. by rewrite [LHS]qualifE /= polyseqC; case: eqP => [->|] /=; rewrite ?andbT ?rpred0. Qed. Fact polyOver_addr_closed : addr_closed (polyOver S). Proof. split=> [|p q Sp Sq]; first exact: polyOver0. by apply/polyOverP=> i; rewrite coefD rpredD ?(polyOverP _). Qed. HB.instance Definition _ := GRing.isAddClosed.Build {poly R} (polyOver_pred S) polyOver_addr_closed. End PolyOverAdd. Section PolyOverSemiRing2. Variable S : semiring2Closed R. Lemma polyOver_mulr_2closed : GRing.mulr_2closed (polyOver S). Proof. move=> p q /polyOverP Sp /polyOverP Sq; apply/polyOverP=> i. by rewrite coefM rpred_sum // => j _; rewrite rpredM. Qed. HB.instance Definition _ := GRing.isMul2Closed.Build {poly R} (polyOver_pred S) polyOver_mulr_2closed. End PolyOverSemiRing2. Fact polyOverNr (zmodS : zmodClosed R) : oppr_closed (polyOver zmodS). Proof. by move=> p /polyOverP Sp; apply/polyOverP=> i; rewrite coefN rpredN. Qed. HB.instance Definition _ (zmodS : zmodClosed R) := GRing.isOppClosed.Build {poly R} (polyOver_pred zmodS) (@polyOverNr _). Section PolyOverSemiring. Variable S : semiringClosed R. Fact polyOver_mul1_closed : 1 \in (polyOver S). Proof. by rewrite polyOverC rpred1. Qed. HB.instance Definition _ := GRing.isMul1Closed.Build {poly R} (polyOver_pred S) polyOver_mul1_closed. Lemma polyOverZ : {in S & polyOver S, forall c p, c *: p \is a polyOver S}. Proof. by move=> c p Sc /polyOverP Sp; apply/polyOverP=> i; rewrite coefZ rpredM ?Sp. Qed. Lemma polyOverX : 'X \in polyOver S. Proof. by rewrite qualifE /= polyseqX /= rpred0 rpred1. Qed. Lemma polyOverXn n : 'X^n \in polyOver S. Proof. by rewrite rpredX// polyOverX. Qed. Lemma rpred_horner : {in polyOver S & S, forall p x, p.[x] \in S}. Proof. move=> p x /polyOverP Sp Sx; rewrite horner_coef rpred_sum // => i _. by rewrite rpredM ?rpredX. Qed. End PolyOverSemiring. Section PolyOverRing. Variable S : subringClosed R. HB.instance Definition _ := GRing.MulClosed.on (polyOver_pred S). Lemma polyOverXaddC c : ('X + c%:P \in polyOver S) = (c \in S). Proof. by rewrite rpredDl ?polyOverX ?polyOverC. Qed. Lemma polyOverXnaddC n c : ('X^n + c%:P \is a polyOver S) = (c \in S). Proof. by rewrite rpredDl ?polyOverXn// ?polyOverC. Qed. Lemma polyOverXsubC c : ('X - c%:P \in polyOver S) = (c \in S). Proof. by rewrite rpredBl ?polyOverX ?polyOverC. Qed. Lemma polyOverXnsubC n c : ('X^n - c%:P \is a polyOver S) = (c \in S). Proof. by rewrite rpredBl ?polyOverXn// ?polyOverC. Qed. End PolyOverRing. (* Single derivative. *) Definition deriv p := \poly_(i < (size p).-1) (p`_i.+1 *+ i.+1). Local Notation "a ^` ()" := (deriv a). Lemma coef_deriv p i : p^`()`_i = p`_i.+1 *+ i.+1. Proof. rewrite coef_poly -subn1 ltn_subRL. by case: leqP => // /(nth_default 0) ->; rewrite mul0rn. Qed. Lemma polyOver_deriv (ringS : semiringClosed R) : {in polyOver ringS, forall p, p^`() \is a polyOver ringS}. Proof. by move=> p /polyOverP Kp; apply/polyOverP=> i; rewrite coef_deriv rpredMn ?Kp. Qed. Lemma derivC c : c%:P^`() = 0. Proof. by apply/polyP=> i; rewrite coef_deriv coef0 coefC mul0rn. Qed. Lemma derivX : ('X)^`() = 1. Proof. by apply/polyP=> [[|i]]; rewrite coef_deriv coef1 coefX ?mul0rn. Qed. Lemma derivXn n : ('X^n)^`() = 'X^(n.-1) *+ n. Proof. case: n => [|n]; first exact: derivC. apply/polyP=> i; rewrite coef_deriv coefMn !coefXn eqSS. by case: eqP => [-> // | _]; rewrite !mul0rn. Qed. Fact deriv_is_linear : linear deriv. Proof. move=> k p q; apply/polyP=> i. by rewrite !(coef_deriv, coefD, coefZ) mulrnDl mulrnAr. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly R} _ deriv (GRing.semilinear_linear deriv_is_linear). Lemma deriv0 : 0^`() = 0. Proof. exact: linear0. Qed. Lemma derivD : {morph deriv : p q / p + q}. Proof. exact: linearD. Qed. Lemma derivN : {morph deriv : p / - p}. Proof. exact: linearN. Qed. Lemma derivB : {morph deriv : p q / p - q}. Proof. exact: linearB. Qed. Lemma derivXsubC (a : R) : ('X - a%:P)^`() = 1. Proof. by rewrite derivB derivX derivC subr0. Qed. Lemma derivMn n p : (p *+ n)^`() = p^`() *+ n. Proof. exact: linearMn. Qed. Lemma derivMNn n p : (p *- n)^`() = p^`() *- n. Proof. exact: linearMNn. Qed. Lemma derivZ c p : (c *: p)^`() = c *: p^`(). Proof. exact: linearZ. Qed. Lemma deriv_mulC c p : (c%:P * p)^`() = c%:P * p^`(). Proof. by rewrite !mul_polyC derivZ. Qed. Lemma derivMXaddC p c : (p * 'X + c%:P)^`() = p + p^`() * 'X. Proof. apply/polyP=> i; rewrite raddfD /= derivC addr0 coefD !(coefMX, coef_deriv). by case: i; rewrite ?addr0. Qed. Lemma derivM p q : (p * q)^`() = p^`() * q + p * q^`(). Proof. elim/poly_ind: p => [|p b IHp]; first by rewrite !(mul0r, add0r, derivC). rewrite mulrDl -mulrA -commr_polyX mulrA -[_ * 'X]addr0 raddfD /= !derivMXaddC. by rewrite deriv_mulC IHp !mulrDl -!mulrA !commr_polyX !addrA. Qed. Definition derivE := Eval lazy beta delta [morphism_2 morphism_1] in (derivZ, deriv_mulC, derivC, derivX, derivMXaddC, derivXsubC, derivM, derivB, derivD, derivN, derivXn, derivM, derivMn). (* Iterated derivative. *) Definition derivn n p := iter n deriv p. Local Notation "a ^` ( n )" := (derivn n a) : ring_scope. Lemma derivn0 p : p^`(0) = p. Proof. by []. Qed. Lemma derivn1 p : p^`(1) = p^`(). Proof. by []. Qed. Lemma derivnS p n : p^`(n.+1) = p^`(n)^`(). Proof. by []. Qed. Lemma derivSn p n : p^`(n.+1) = p^`()^`(n). Proof. exact: iterSr. Qed. Lemma coef_derivn n p i : p^`(n)`_i = p`_(n + i) *+ (n + i) ^_ n. Proof. elim: n i => [|n IHn] i; first by rewrite ffactn0 mulr1n. by rewrite derivnS coef_deriv IHn -mulrnA ffactnSr addSnnS addKn. Qed. Lemma polyOver_derivn (ringS : semiringClosed R) : {in polyOver ringS, forall p n, p^`(n) \is a polyOver ringS}. Proof. move=> p /polyOverP Kp /= n; apply/polyOverP=> i. by rewrite coef_derivn rpredMn. Qed. Fact derivn_is_linear n : linear (derivn n). Proof. by elim: n => // n IHn a p q; rewrite derivnS IHn linearP. Qed. HB.instance Definition _ n := GRing.isSemilinear.Build R {poly R} {poly R} _ (derivn n) (GRing.semilinear_linear (derivn_is_linear n)). Lemma derivnC c n : c%:P^`(n) = if n == 0 then c%:P else 0. Proof. by case: n => // n; rewrite derivSn derivC linear0. Qed. Lemma derivnD n : {morph derivn n : p q / p + q}. Proof. exact: linearD. Qed. Lemma derivnB n : {morph derivn n : p q / p - q}. Proof. exact: linearB. Qed. Lemma derivnMn n m p : (p *+ m)^`(n) = p^`(n) *+ m. Proof. exact: linearMn. Qed. Lemma derivnMNn n m p : (p *- m)^`(n) = p^`(n) *- m. Proof. exact: linearMNn. Qed. Lemma derivnN n : {morph derivn n : p / - p}. Proof. exact: linearN. Qed. Lemma derivnZ n : scalable (derivn n). Proof. exact: linearZZ. Qed. Lemma derivnXn m n : ('X^m)^`(n) = 'X^(m - n) *+ m ^_ n. Proof. apply/polyP=>i; rewrite coef_derivn coefMn !coefXn. case: (ltnP m n) => [lt_m_n | le_m_n]. by rewrite eqn_leq leqNgt ltn_addr // mul0rn ffact_small. by rewrite -{1 3}(subnKC le_m_n) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn. Qed. Lemma derivnMXaddC n p c : (p * 'X + c%:P)^`(n.+1) = p^`(n) *+ n.+1 + p^`(n.+1) * 'X. Proof. elim: n => [|n IHn]; first by rewrite derivn1 derivMXaddC. rewrite derivnS IHn derivD derivM derivX mulr1 derivMn -!derivnS. by rewrite addrA addrAC -mulrSr. Qed. Lemma derivn_poly0 p n : size p <= n -> p^`(n) = 0. Proof. move=> le_p_n; apply/polyP=> i; rewrite coef_derivn. rewrite nth_default; first by rewrite mul0rn coef0. exact/(leq_trans le_p_n)/leq_addr. Qed. Lemma lt_size_deriv (p : {poly R}) : p != 0 -> size p^`() < size p. Proof. by move=> /polySpred->; apply: size_poly. Qed. (* A normalising version of derivation to get the division by n! in Taylor *) Definition nderivn n p := \poly_(i < size p - n) (p`_(n + i) *+ 'C(n + i, n)). Local Notation "a ^`N ( n )" := (nderivn n a) : ring_scope. Lemma coef_nderivn n p i : p^`N(n)`_i = p`_(n + i) *+ 'C(n + i, n). Proof. rewrite coef_poly ltn_subRL; case: leqP => // le_p_ni. by rewrite nth_default ?mul0rn. Qed. (* Here is the division by n! *) Lemma nderivn_def n p : p^`(n) = p^`N(n) *+ n`!. Proof. by apply/polyP=> i; rewrite coefMn coef_nderivn coef_derivn -mulrnA bin_ffact. Qed. Lemma polyOver_nderivn (ringS : semiringClosed R) : {in polyOver ringS, forall p n, p^`N(n) \in polyOver ringS}. Proof. move=> p /polyOverP Sp /= n; apply/polyOverP=> i. by rewrite coef_nderivn rpredMn. Qed. Lemma nderivn0 p : p^`N(0) = p. Proof. by rewrite -[p^`N(0)](nderivn_def 0). Qed. Lemma nderivn1 p : p^`N(1) = p^`(). Proof. by rewrite -[p^`N(1)](nderivn_def 1). Qed. Lemma nderivnC c n : (c%:P)^`N(n) = if n == 0 then c%:P else 0. Proof. apply/polyP=> i; rewrite coef_nderivn. by case: n => [|n]; rewrite ?bin0 // coef0 coefC mul0rn. Qed. Lemma nderivnXn m n : ('X^m)^`N(n) = 'X^(m - n) *+ 'C(m, n). Proof. apply/polyP=> i; rewrite coef_nderivn coefMn !coefXn. have [lt_m_n | le_n_m] := ltnP m n. by rewrite eqn_leq leqNgt ltn_addr // mul0rn bin_small. by rewrite -{1 3}(subnKC le_n_m) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn. Qed. Fact nderivn_is_linear n : linear (nderivn n). Proof. move=> k p q; apply/polyP=> i. by rewrite !(coef_nderivn, coefD, coefZ) mulrnDl mulrnAr. Qed. HB.instance Definition _ n := GRing.isSemilinear.Build R {poly R} {poly R} _ (nderivn n) (GRing.semilinear_linear (nderivn_is_linear n)). Lemma nderivnD n : {morph nderivn n : p q / p + q}. Proof. exact: linearD. Qed. Lemma nderivnB n : {morph nderivn n : p q / p - q}. Proof. exact: linearB. Qed. Lemma nderivnMn n m p : (p *+ m)^`N(n) = p^`N(n) *+ m. Proof. exact: linearMn. Qed. Lemma nderivnMNn n m p : (p *- m)^`N(n) = p^`N(n) *- m. Proof. exact: linearMNn. Qed. Lemma nderivnN n : {morph nderivn n : p / - p}. Proof. exact: linearN. Qed. Lemma nderivnZ n : scalable (nderivn n). Proof. exact: linearZZ. Qed. Lemma nderivnMXaddC n p c : (p * 'X + c%:P)^`N(n.+1) = p^`N(n) + p^`N(n.+1) * 'X. Proof. apply/polyP=> i; rewrite coef_nderivn !coefD !coefMX coefC. rewrite !addSn /= !coef_nderivn addr0 binS mulrnDr addrC; congr (_ + _). by rewrite addSnnS; case: i; rewrite // addn0 bin_small. Qed. Lemma nderivn_poly0 p n : size p <= n -> p^`N(n) = 0. Proof. move=> le_p_n; apply/polyP=> i; rewrite coef_nderivn. rewrite nth_default; first by rewrite mul0rn coef0. exact/(leq_trans le_p_n)/leq_addr. Qed. Lemma nderiv_taylor p x h : GRing.comm x h -> p.[x + h] = \sum_(i < size p) p^`N(i).[x] * h ^+ i. Proof. move/commrX=> cxh; elim/poly_ind: p => [|p c IHp]. by rewrite size_poly0 big_ord0 horner0. rewrite hornerMXaddC size_MXaddC. have [-> | nz_p] := eqVneq p 0. rewrite horner0 !simp; have [-> | _] := c =P 0; first by rewrite big_ord0. by rewrite size_poly0 big_ord_recl big_ord0 nderivn0 hornerC !simp. rewrite big_ord_recl nderivn0 !simp hornerMXaddC addrAC; congr (_ + _). rewrite mulrDr {}IHp !big_distrl polySpred //= big_ord_recl /= mulr1 -addrA. rewrite nderivn0 /bump /(addn 1) /=; congr (_ + _). rewrite !big_ord_recr /= nderivnMXaddC -mulrA -exprSr -polySpred // !addrA. congr (_ + _); last by rewrite (nderivn_poly0 (leqnn _)) !simp. rewrite addrC -big_split /=; apply: eq_bigr => i _. by rewrite nderivnMXaddC !hornerE_comm /= mulrDl -!mulrA -exprSr cxh. Qed. Lemma nderiv_taylor_wide n p x h : GRing.comm x h -> size p <= n -> p.[x + h] = \sum_(i < n) p^`N(i).[x] * h ^+ i. Proof. move/nderiv_taylor=> -> le_p_n. rewrite (big_ord_widen n (fun i => p^`N(i).[x] * h ^+ i)) // big_mkcond. apply: eq_bigr => i _; case: leqP => // /nderivn_poly0->. by rewrite horner0 simp. Qed. Lemma eq_poly n E1 E2 : (forall i, i < n -> E1 i = E2 i) -> poly n E1 = poly n E2 :> {poly R}. Proof. by move=> E; rewrite !poly_def; apply: eq_bigr => i _; rewrite E. Qed. End PolynomialTheory. #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyN`")] Notation size_opp := size_polyN (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pchar_poly instead.")] Notation char_poly := pchar_poly (only parsing). Prenex Implicits polyC polyCK Poly polyseqK lead_coef root horner polyOver. Arguments monic {R}. Notation "\poly_ ( i < n ) E" := (poly n (fun i => E)) : ring_scope. Notation "c %:P" := (polyC c) : ring_scope. Notation "'X" := (polyX _) : ring_scope. Notation "''X^' n" := ('X ^+ n) : ring_scope. Notation "p .[ x ]" := (horner p x) : ring_scope. Notation "n .-unity_root" := (root_of_unity n) : ring_scope. Notation "n .-primitive_root" := (primitive_root_of_unity n) : ring_scope. Notation "a ^` ()" := (deriv a) : ring_scope. Notation "a ^` ( n )" := (derivn n a) : ring_scope. Notation "a ^`N ( n )" := (nderivn n a) : ring_scope. Arguments monic_pred _ _ /. Arguments monicP {R p}. Arguments rootP {R p x}. Arguments rootPf {R p x}. Arguments rootPt {R p x}. Arguments unity_rootP {R n z}. Arguments polyOver_pred _ _ _ /. Arguments polyOverP {R S p}. Arguments polyC_inj {R} [x1 x2] eq_x12P. Arguments eq_poly {R n} [E1] E2 eq_E12. Section IdomainPrimRoot. Variables (R : idomainType) (n : nat) (z : R). Hypothesis prim_z : n.-primitive_root z. Import prime. Let n_gt0 := prim_order_gt0 prim_z. Lemma prim_root_pcharF p : (p %| n)%N -> p \in [pchar R] = false. Proof. move=> pn; apply: contraTF isT => pchar_p; have p_prime := pcharf_prime pchar_p. have /dvdnP[[|k] n_eq_kp] := pn; first by rewrite n_eq_kp in (n_gt0). have /eqP := prim_expr_order prim_z; rewrite n_eq_kp exprM. rewrite -pFrobenius_autE -(pFrobenius_aut1 pchar_p) -subr_eq0 -rmorphB/=. rewrite pFrobenius_autE expf_eq0// prime_gt0//= subr_eq0 => /eqP. move=> /eqP; rewrite -(prim_order_dvd prim_z) n_eq_kp. rewrite -[X in _ %| X]muln1 dvdn_pmul2l ?dvdn1// => /eqP peq1. by rewrite peq1 in p_prime. Qed. Lemma pchar_prim_root : [pchar R]^'.-nat n. Proof. by apply/pnatP=> // p pp pn; rewrite inE/= prim_root_pcharF. Qed. Lemma prim_root_pi_eq0 m : \pi(n).-nat m -> m%:R != 0 :> R. Proof. by rewrite natf_neq0_pchar; apply: sub_in_pnat => p _; apply: pnatPpi pchar_prim_root. Qed. Lemma prim_root_dvd_eq0 m : (m %| n)%N -> m%:R != 0 :> R. Proof. case: m => [|m mn]; first by rewrite dvd0n gtn_eqF. by rewrite prim_root_pi_eq0 ?(sub_in_pnat (in1W (pi_of_dvd mn _))) ?pnat_pi. Qed. Lemma prim_root_natf_neq0 : n%:R != 0 :> R. Proof. by rewrite prim_root_dvd_eq0. Qed. End IdomainPrimRoot. #[deprecated(since="mathcomp 2.4.0", note="Use prim_root_pcharF instead.")] Notation prim_root_charF := prim_root_pcharF (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pchar_prim_root instead.")] Notation char_prim_root := pchar_prim_root (only parsing). (* Container morphism. *) Section MapPoly. Section Definitions. Variables (aR rR : nzRingType) (f : aR -> rR). Definition map_poly (p : {poly aR}) := \poly_(i < size p) f p`_i. (* Alternative definition; the one above is more convenient because it lets *) (* us use the lemmas on \poly, e.g., size (map_poly p) <= size p is an *) (* instance of size_poly. *) Lemma map_polyE p : map_poly p = Poly (map f p). Proof. rewrite /map_poly unlock; congr Poly. apply: (@eq_from_nth _ 0); rewrite size_mkseq ?size_map // => i lt_i_p. by rewrite [RHS](nth_map 0) ?nth_mkseq. Qed. Definition commr_rmorph u := forall x, GRing.comm u (f x). Definition horner_morph u of commr_rmorph u := fun p => (map_poly p).[u]. End Definitions. Variables aR rR : nzRingType. Section Combinatorial. Variables (iR : nzRingType) (f : aR -> rR). Local Notation "p ^f" := (map_poly f p) : ring_scope. Lemma map_poly0 : 0^f = 0. Proof. by rewrite map_polyE polyseq0. Qed. Lemma eq_map_poly (g : aR -> rR) : f =1 g -> map_poly f =1 map_poly g. Proof. by move=> eq_fg p; rewrite !map_polyE (eq_map eq_fg). Qed. Lemma map_poly_id g (p : {poly iR}) : {in (p : seq iR), g =1 id} -> map_poly g p = p. Proof. by move=> g_id; rewrite map_polyE map_id_in ?polyseqK. Qed. Lemma coef_map_id0 p i : f 0 = 0 -> (p^f)`_i = f p`_i. Proof. by move=> f0; rewrite coef_poly; case: ltnP => // le_p_i; rewrite nth_default. Qed. Lemma map_Poly_id0 s : f 0 = 0 -> (Poly s)^f = Poly (map f s). Proof. move=> f0; apply/polyP=> j; rewrite coef_map_id0 ?coef_Poly //. have [/(nth_map 0 0)->// | le_s_j] := ltnP j (size s). by rewrite !nth_default ?size_map. Qed. Lemma map_poly_comp_id0 (g : iR -> aR) p : f 0 = 0 -> map_poly (f \o g) p = (map_poly g p)^f. Proof. by move=> f0; rewrite map_polyE map_comp -map_Poly_id0 -?map_polyE. Qed. Lemma size_map_poly_id0 p : f (lead_coef p) != 0 -> size p^f = size p. Proof. by move=> nz_fp; apply: size_poly_eq. Qed. Lemma map_poly_eq0_id0 p : f (lead_coef p) != 0 -> (p^f == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /size_map_poly_id0->. Qed. Lemma lead_coef_map_id0 p : f 0 = 0 -> f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p). Proof. by move=> f0 nz_fp; rewrite lead_coefE coef_map_id0 ?size_map_poly_id0. Qed. Hypotheses (inj_f : injective f) (f_0 : f 0 = 0). Lemma size_map_inj_poly p : size p^f = size p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite map_poly0 !size_poly0. by rewrite size_map_poly_id0 // -f_0 (inj_eq inj_f) lead_coef_eq0. Qed. Lemma map_inj_poly : injective (map_poly f). Proof. move=> p q /polyP eq_pq; apply/polyP=> i; apply: inj_f. by rewrite -!coef_map_id0 ?eq_pq. Qed. Lemma lead_coef_map_inj p : lead_coef p^f = f (lead_coef p). Proof. by rewrite !lead_coefE size_map_inj_poly coef_map_id0. Qed. End Combinatorial. Lemma map_polyK (f : aR -> rR) g : cancel g f -> f 0 = 0 -> cancel (map_poly g) (map_poly f). Proof. by move=> gK f_0 p; rewrite /= -map_poly_comp_id0 ?map_poly_id // => x _ //=. Qed. Lemma eq_in_map_poly_id0 (f g : aR -> rR) (S : addrClosed aR) : f 0 = 0 -> g 0 = 0 -> {in S, f =1 g} -> {in polyOver S, map_poly f =1 map_poly g}. Proof. move=> f0 g0 eq_fg p pP; apply/polyP => i. by rewrite !coef_map_id0// eq_fg// (polyOverP _). Qed. Lemma eq_in_map_poly (f g : {additive aR -> rR}) (S : addrClosed aR) : {in S, f =1 g} -> {in polyOver S, map_poly f =1 map_poly g}. Proof. by move=> /eq_in_map_poly_id0; apply; rewrite //?raddf0. Qed. Section Additive. Variables (iR : nzRingType) (f : {additive aR -> rR}). Local Notation "p ^f" := (map_poly (GRing.Additive.sort f) p) : ring_scope. Lemma coef_map p i : p^f`_i = f p`_i. Proof. exact: coef_map_id0 (raddf0 f). Qed. Lemma map_Poly s : (Poly s)^f = Poly (map f s). Proof. exact: map_Poly_id0 (raddf0 f). Qed. Lemma map_poly_comp (g : iR -> aR) p : map_poly (f \o g) p = map_poly f (map_poly g p). Proof. exact: map_poly_comp_id0 (raddf0 f). Qed. Fact map_poly_is_zmod_morphism : zmod_morphism (map_poly f). Proof. by move=> p q; apply/polyP=> i; rewrite !(coef_map, coefB) raddfB. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `map_poly_is_zmod_morphism` instead")] Definition map_poly_is_additive := map_poly_is_zmod_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build {poly aR} {poly rR} (map_poly f) map_poly_is_zmod_morphism. Lemma map_polyC a : (a%:P)^f = (f a)%:P. Proof. by apply/polyP=> i; rewrite !(coef_map, coefC) -!mulrb raddfMn. Qed. Lemma lead_coef_map_eq p : f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p). Proof. exact: lead_coef_map_id0 (raddf0 f). Qed. End Additive. Variable f : {rmorphism aR -> rR}. Implicit Types p : {poly aR}. Local Notation "p ^f" := (map_poly (GRing.RMorphism.sort f) p) : ring_scope. Fact map_poly_is_monoid_morphism : monoid_morphism (map_poly f). Proof. split=> [|p q]; apply/polyP=> i. by rewrite !(coef_map, coef1) /= rmorph_nat. rewrite coef_map /= !coefM /= !rmorph_sum; apply: eq_bigr => j _. by rewrite !coef_map rmorphM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `map_poly_is_monoid_morphism` instead")] Definition map_poly_is_multiplicative := (fun g => (g.2, g.1)) map_poly_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly aR} {poly rR} (map_poly f) map_poly_is_monoid_morphism. Lemma map_polyZ c p : (c *: p)^f = f c *: p^f. Proof. by apply/polyP=> i; rewrite !(coef_map, coefZ) /= rmorphM. Qed. HB.instance Definition _ := GRing.isScalable.Build aR {poly aR} {poly rR} (f \; *:%R) (map_poly f) map_polyZ. Lemma map_polyX : ('X)^f = 'X. Proof. by apply/polyP=> i; rewrite coef_map !coefX /= rmorph_nat. Qed. Lemma map_polyXn n : ('X^n)^f = 'X^n. Proof. by rewrite rmorphXn /= map_polyX. Qed. Lemma map_polyXaddC x : ('X + x%:P)^f = 'X + (f x)%:P. Proof. by rewrite raddfD/= map_polyX map_polyC. Qed. Lemma map_polyXsubC x : ('X - x%:P)^f = 'X - (f x)%:P. Proof. by rewrite raddfB/= map_polyX map_polyC. Qed. Lemma map_prod_XsubC I (rI : seq I) P F : (\prod_(i <- rI | P i) ('X - (F i)%:P))^f = \prod_(i <- rI | P i) ('X - (f (F i))%:P). Proof. by rewrite rmorph_prod//; apply/eq_bigr => x /=; rewrite map_polyXsubC. Qed. Lemma prod_map_poly (ar : seq aR) P : \prod_(x <- map f ar | P x) ('X - x%:P) = (\prod_(x <- ar | P (f x)) ('X - x%:P))^f. Proof. by rewrite big_map map_prod_XsubC. Qed. Lemma monic_map p : p \is monic -> p^f \is monic. Proof. move/monicP=> mon_p; rewrite monicE. by rewrite lead_coef_map_eq mon_p /= rmorph1 ?oner_neq0. Qed. Lemma horner_map p x : p^f.[f x] = f p.[x]. Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !(rmorph0, horner0). rewrite hornerMXaddC !rmorphD !rmorphM /=. by rewrite map_polyX map_polyC hornerMXaddC IHp. Qed. Lemma map_comm_poly p x : comm_poly p x -> comm_poly p^f (f x). Proof. by rewrite /comm_poly horner_map -!rmorphM // => ->. Qed. Lemma map_comm_coef p x : comm_coef p x -> comm_coef p^f (f x). Proof. by move=> cpx i; rewrite coef_map -!rmorphM ?cpx. Qed. Lemma rmorph_root p x : root p x -> root p^f (f x). Proof. by move/eqP=> px0; rewrite rootE horner_map px0 rmorph0. Qed. Lemma rmorph_unity_root n z : n.-unity_root z -> n.-unity_root (f z). Proof. move/rmorph_root; rewrite rootE rmorphB hornerD hornerN. by rewrite /= map_polyXn rmorph1 hornerC hornerXn subr_eq0 unity_rootE. Qed. Section HornerMorph. Variable u : rR. Hypothesis cfu : commr_rmorph f u. Lemma horner_morphC a : horner_morph cfu a%:P = f a. Proof. by rewrite /horner_morph map_polyC hornerC. Qed. Lemma horner_morphX : horner_morph cfu 'X = u. Proof. by rewrite /horner_morph map_polyX hornerX. Qed. Fact horner_is_linear : linear_for (f \; *%R) (horner_morph cfu). Proof. by move=> c p q; rewrite /horner_morph linearP /= hornerD hornerZ. Qed. Fact horner_is_monoid_morphism : monoid_morphism (horner_morph cfu). Proof. split=> [|p q]; first by rewrite /horner_morph rmorph1 hornerC. rewrite /horner_morph rmorphM /= hornerM_comm //. by apply: comm_coef_poly => i; rewrite coef_map cfu. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `horner_is_monoid_morphism` instead")] Definition horner_is_multiplicative := (fun g => (g.2, g.1)) horner_is_monoid_morphism. HB.instance Definition _ := GRing.isSemilinear.Build aR {poly aR} rR _ (horner_morph cfu) (GRing.semilinear_linear horner_is_linear). HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly aR} rR (horner_morph cfu) horner_is_monoid_morphism. End HornerMorph. Lemma deriv_map p : p^f^`() = (p^`())^f. Proof. by apply/polyP => i; rewrite !(coef_map, coef_deriv) //= rmorphMn. Qed. Lemma derivn_map p n : p^f^`(n) = (p^`(n))^f. Proof. by apply/polyP => i; rewrite !(coef_map, coef_derivn) //= rmorphMn. Qed. Lemma nderivn_map p n : p^f^`N(n) = (p^`N(n))^f. Proof. by apply/polyP => i; rewrite !(coef_map, coef_nderivn) //= rmorphMn. Qed. End MapPoly. Lemma mapf_root (F : fieldType) (R : nzRingType) (f : {rmorphism F -> R}) (p : {poly F}) (x : F) : root (map_poly f p) (f x) = root p x. Proof. by rewrite !rootE horner_map fmorph_eq0. Qed. (* Morphisms from the polynomial ring, and the initiality of polynomials *) (* with respect to these. *) Section MorphPoly. Variable (aR rR : nzRingType) (pf : {rmorphism {poly aR} -> rR}). Lemma poly_morphX_comm : commr_rmorph (pf \o polyC) (pf 'X). Proof. by move=> a; rewrite /GRing.comm /= -!rmorphM // commr_polyX. Qed. Lemma poly_initial : pf =1 horner_morph poly_morphX_comm. Proof. apply: poly_ind => [|p a IHp]; first by rewrite !rmorph0. by rewrite !rmorphD !rmorphM /= -{}IHp horner_morphC ?horner_morphX. Qed. End MorphPoly. Notation "p ^:P" := (map_poly polyC p) : ring_scope. Section PolyCompose. Variable R : nzRingType. Implicit Types p q : {poly R}. Definition comp_poly q p := p^:P.[q]. Local Notation "p \Po q" := (comp_poly q p) : ring_scope. Lemma size_map_polyC p : size p^:P = size p. Proof. exact/(size_map_inj_poly polyC_inj). Qed. Lemma map_polyC_eq0 p : (p^:P == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 size_map_polyC. Qed. Lemma root_polyC p x : root p^:P x%:P = root p x. Proof. by rewrite rootE horner_map polyC_eq0. Qed. Lemma comp_polyE p q : p \Po q = \sum_(i < size p) p`_i *: q^+i. Proof. by rewrite [p \Po q]horner_poly; apply: eq_bigr => i _; rewrite mul_polyC. Qed. Lemma coef_comp_poly p q n : (p \Po q)`_n = \sum_(i < size p) p`_i * (q ^+ i)`_n. Proof. by rewrite comp_polyE coef_sum; apply: eq_bigr => i; rewrite coefZ. Qed. Lemma polyOver_comp (ringS : semiringClosed R) : {in polyOver ringS &, forall p q, p \Po q \in polyOver ringS}. Proof. move=> p q /polyOverP Sp Sq; rewrite comp_polyE rpred_sum // => i _. by rewrite polyOverZ ?rpredX. Qed. Lemma comp_polyCr p c : p \Po c%:P = p.[c]%:P. Proof. exact: horner_map. Qed. Lemma comp_poly0r p : p \Po 0 = (p`_0)%:P. Proof. by rewrite comp_polyCr horner_coef0. Qed. Lemma comp_polyC c p : c%:P \Po p = c%:P. Proof. by rewrite /(_ \Po p) map_polyC hornerC. Qed. Fact comp_poly_is_linear p : linear (comp_poly p). Proof. move=> a q r. by rewrite /comp_poly rmorphD /= map_polyZ !hornerE_comm mul_polyC. Qed. HB.instance Definition _ p := GRing.isSemilinear.Build R {poly R} {poly R} _ (comp_poly p) (GRing.semilinear_linear (comp_poly_is_linear p)). Lemma comp_poly0 p : 0 \Po p = 0. Proof. exact: raddf0. Qed. Lemma comp_polyD p q r : (p + q) \Po r = (p \Po r) + (q \Po r). Proof. exact: raddfD. Qed. Lemma comp_polyB p q r : (p - q) \Po r = (p \Po r) - (q \Po r). Proof. exact: raddfB. Qed. Lemma comp_polyZ c p q : (c *: p) \Po q = c *: (p \Po q). Proof. exact: linearZZ. Qed. Lemma comp_polyXr p : p \Po 'X = p. Proof. by rewrite -{2}/(idfun p) poly_initial. Qed. Lemma comp_polyX p : 'X \Po p = p. Proof. by rewrite /(_ \Po p) map_polyX hornerX. Qed. Lemma comp_poly_MXaddC c p q : (p * 'X + c%:P) \Po q = (p \Po q) * q + c%:P. Proof. by rewrite /(_ \Po q) rmorphD rmorphM /= map_polyX map_polyC hornerMXaddC. Qed. Lemma comp_polyXaddC_K p z : (p \Po ('X + z%:P)) \Po ('X - z%:P) = p. Proof. have addzK: ('X + z%:P) \Po ('X - z%:P) = 'X. by rewrite raddfD /= comp_polyC comp_polyX subrK. elim/poly_ind: p => [|p c IHp]; first by rewrite !comp_poly0. rewrite comp_poly_MXaddC linearD /= comp_polyC {1}/comp_poly rmorphM /=. by rewrite hornerM_comm /comm_poly -!/(_ \Po _) ?IHp ?addzK ?commr_polyX. Qed. Lemma size_comp_poly_leq p q : size (p \Po q) <= ((size p).-1 * (size q).-1).+1. Proof. rewrite comp_polyE (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _. rewrite (leq_trans (size_scale_leq _ _))//. rewrite (leq_trans (size_poly_exp_leq _ _))//. by rewrite ltnS mulnC leq_mul // -{2}(subnKC (valP i)) leq_addr. Qed. Lemma comp_Xn_poly p n : 'X^n \Po p = p ^+ n. Proof. by rewrite /(_ \Po p) map_polyXn hornerXn. Qed. Lemma coef_comp_poly_Xn p n i : 0 < n -> (p \Po 'X^n)`_i = if n %| i then p`_(i %/ n) else 0. Proof. move=> n_gt0; rewrite comp_polyE; under eq_bigr do rewrite -exprM mulnC. rewrite coef_sumMXn/=; case: dvdnP => [[j ->]|nD]; last first. by rewrite big1// => j /eqP ?; case: nD; exists j. under eq_bigl do rewrite eqn_mul2r gtn_eqF//. by rewrite big_ord1_eq if_nth ?leqVgt ?mulnK. Qed. Lemma comp_poly_Xn p n : 0 < n -> p \Po 'X^n = \poly_(i < size p * n) if n %| i then p`_(i %/ n) else 0. Proof. move=> n_gt0; apply/polyP => i; rewrite coef_comp_poly_Xn // coef_poly. case: dvdnP => [[k ->]|]; last by rewrite if_same. by rewrite mulnK // ltn_mul2r n_gt0 if_nth ?leqVgt. Qed. End PolyCompose. Notation "p \Po q" := (comp_poly q p) : ring_scope. Lemma map_comp_poly (aR rR : nzRingType) (f : {rmorphism aR -> rR}) p q : map_poly f (p \Po q) = map_poly f p \Po map_poly f q. Proof. elim/poly_ind: p => [|p a IHp]; first by rewrite !raddf0. rewrite comp_poly_MXaddC !rmorphD !rmorphM /= !map_polyC map_polyX. by rewrite comp_poly_MXaddC -IHp. Qed. Section Surgery. Variable R : nzRingType. Implicit Type p q : {poly R}. (* Even part of a polynomial *) Definition even_poly p : {poly R} := \poly_(i < uphalf (size p)) p`_i.*2. Lemma size_even_poly p : size (even_poly p) <= uphalf (size p). Proof. exact: size_poly. Qed. Lemma coef_even_poly p i : (even_poly p)`_i = p`_i.*2. Proof. by rewrite coef_poly gtn_uphalf_double if_nth ?leqVgt. Qed. Lemma even_polyE s p : size p <= s.*2 -> even_poly p = \poly_(i < s) p`_i.*2. Proof. move=> pLs2; apply/polyP => i; rewrite coef_even_poly !coef_poly if_nth //. by case: ltnP => //= ?; rewrite (leq_trans pLs2) ?leq_double. Qed. Lemma size_even_poly_eq p : odd (size p) -> size (even_poly p) = uphalf (size p). Proof. move=> p_even; rewrite size_poly_eq// double_pred odd_uphalfK//=. by rewrite lead_coef_eq0 -size_poly_eq0; case: size p_even. Qed. Lemma even_polyD p q : even_poly (p + q) = even_poly p + even_poly q. Proof. by apply/polyP => i; rewrite !(coef_even_poly, coefD). Qed. Lemma even_polyZ k p : even_poly (k *: p) = k *: even_poly p. Proof. by apply/polyP => i; rewrite !(coefZ, coef_even_poly). Qed. Fact even_poly_is_linear : linear even_poly. Proof. by move=> k p q; rewrite even_polyD even_polyZ. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly R} _ even_poly (GRing.semilinear_linear even_poly_is_linear). Lemma even_polyC (c : R) : even_poly c%:P = c%:P. Proof. by apply/polyP => i; rewrite coef_even_poly !coefC; case: i. Qed. (* Odd part of a polynomial *) Definition odd_poly p : {poly R} := \poly_(i < (size p)./2) p`_i.*2.+1. Lemma size_odd_poly p : size (odd_poly p) <= (size p)./2. Proof. exact: size_poly. Qed. Lemma coef_odd_poly p i : (odd_poly p)`_i = p`_i.*2.+1. Proof. by rewrite coef_poly gtn_half_double if_nth ?leqVgt. Qed. Lemma odd_polyE s p : size p <= s.*2.+1 -> odd_poly p = \poly_(i < s) p`_i.*2.+1. Proof. move=> pLs2; apply/polyP => i; rewrite coef_odd_poly !coef_poly if_nth //. by case: ltnP => //= ?; rewrite (leq_trans pLs2) ?ltnS ?leq_double. Qed. Lemma odd_polyC (c : R) : odd_poly c%:P = 0. Proof. by apply/polyP => i; rewrite coef_odd_poly !coefC; case: i. Qed. Lemma odd_polyD p q : odd_poly (p + q) = odd_poly p + odd_poly q. Proof. by apply/polyP => i; rewrite !(coef_odd_poly, coefD). Qed. Lemma odd_polyZ k p : odd_poly (k *: p) = k *: odd_poly p. Proof. by apply/polyP => i; rewrite !(coefZ, coef_odd_poly). Qed. Fact odd_poly_is_linear : linear odd_poly. Proof. by move=> k p q; rewrite odd_polyD odd_polyZ. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly R} _ odd_poly (GRing.semilinear_linear odd_poly_is_linear). Lemma size_odd_poly_eq p : ~~ odd (size p) -> size (odd_poly p) = (size p)./2. Proof. have [->|p_neq0] := eqVneq p 0; first by rewrite odd_polyC size_poly0. move=> p_odd; rewrite size_poly_eq// -subn1 doubleB subn2 even_halfK//. rewrite prednK ?lead_coef_eq0// ltn_predRL. by move: p_neq0 p_odd; rewrite -size_poly_eq0; case: (size p) => [|[]]. Qed. Lemma odd_polyMX p : odd_poly (p * 'X) = even_poly p. Proof. have [->|pN0] := eqVneq p 0; first by rewrite mul0r even_polyC odd_polyC. by apply/polyP => i; rewrite !coef_poly size_mulX // coefMX. Qed. Lemma even_polyMX p : even_poly (p * 'X) = odd_poly p * 'X. Proof. have [->|pN0] := eqVneq p 0; first by rewrite mul0r even_polyC odd_polyC mul0r. by apply/polyP => -[|i]; rewrite !(coefMX, coef_poly, if_same, size_mulX). Qed. Lemma sum_even_poly p : \sum_(i < size p | ~~ odd i) p`_i *: 'X^i = even_poly p \Po 'X^2. Proof. apply/polyP => i; rewrite coef_comp_poly_Xn// coef_sumMXn coef_even_poly. rewrite (big_ord1_cond_eq _ _ (negb \o _))/= -dvdn2 andbC -muln2. by case: dvdnP => //= -[k ->]; rewrite mulnK// if_nth ?leqVgt. Qed. Lemma sum_odd_poly p : \sum_(i < size p | odd i) p`_i *: 'X^i = (odd_poly p \Po 'X^2) * 'X. Proof. apply/polyP => i; rewrite coefMX coef_comp_poly_Xn// coef_sumMXn coef_odd_poly/=. case: i => [|i]//=; first by rewrite big_andbC big1// => -[[|j]//]. rewrite big_ord1_cond_eq/= -dvdn2 andbC -muln2. by case: dvdnP => //= -[k ->]; rewrite mulnK// if_nth ?leqVgt. Qed. (* Decomposition in odd and even part *) Lemma poly_even_odd p : even_poly p \Po 'X^2 + (odd_poly p \Po 'X^2) * 'X = p. Proof. rewrite -sum_even_poly -sum_odd_poly addrC -(bigID _ xpredT). by rewrite -[RHS]coefK poly_def. Qed. (* take and drop for polynomials *) Definition take_poly m p := \poly_(i < m) p`_i. Lemma size_take_poly m p : size (take_poly m p) <= m. Proof. exact: size_poly. Qed. Lemma coef_take_poly m p i : (take_poly m p)`_i = if i < m then p`_i else 0. Proof. exact: coef_poly. Qed. Lemma take_poly_id m p : size p <= m -> take_poly m p = p. Proof. move=> /leq_trans gep; apply/polyP => i; rewrite coef_poly if_nth//=. by case: ltnP => // /gep->. Qed. Lemma take_polyD m p q : take_poly m (p + q) = take_poly m p + take_poly m q. Proof. by apply/polyP => i; rewrite !(coefD, coef_poly); case: leqP; rewrite ?add0r. Qed. Lemma take_polyZ k m p : take_poly m (k *: p) = k *: take_poly m p. Proof. apply/polyP => i; rewrite !(coefZ, coef_take_poly); case: leqP => //. by rewrite mulr0. Qed. Fact take_poly_is_linear m : linear (take_poly m). Proof. by move=> k p q; rewrite take_polyD take_polyZ. Qed. HB.instance Definition _ m := GRing.isSemilinear.Build R {poly R} {poly R} _ (take_poly m) (GRing.semilinear_linear (take_poly_is_linear m)). Lemma take_poly_sum m I r P (p : I -> {poly R}) : take_poly m (\sum_(i <- r | P i) p i) = \sum_(i <- r| P i) take_poly m (p i). Proof. exact: linear_sum. Qed. Lemma take_poly0l p : take_poly 0 p = 0. Proof. exact/size_poly_leq0P/size_take_poly. Qed. Lemma take_poly0r m : take_poly m 0 = 0. Proof. exact: linear0. Qed. Lemma take_polyMXn m n p : take_poly m (p * 'X^n) = take_poly (m - n) p * 'X^n. Proof. have [->|/eqP p_neq0] := p =P 0; first by rewrite !(mul0r, take_poly0r). apply/polyP => i; rewrite !(coef_take_poly, coefMXn). by have [iLn|nLi] := leqP n i; rewrite ?if_same// ltn_sub2rE. Qed. Lemma take_polyMXn_0 n p : take_poly n (p * 'X^n) = 0. Proof. by rewrite take_polyMXn subnn take_poly0l mul0r. Qed. Lemma take_polyDMXn n p q : size p <= n -> take_poly n (p + q * 'X^n) = p. Proof. by move=> ?; rewrite take_polyD take_poly_id// take_polyMXn_0 addr0. Qed. Definition drop_poly m p := \poly_(i < size p - m) p`_(i + m). Lemma coef_drop_poly m p i : (drop_poly m p)`_i = p`_(i + m). Proof. by rewrite coef_poly ltn_subRL addnC if_nth ?leqVgt. Qed. Lemma drop_poly_eq0 m p : size p <= m -> drop_poly m p = 0. Proof. move=> sLm; apply/polyP => i; rewrite coef_poly coef0 ltn_subRL addnC. by rewrite if_nth ?leqVgt// nth_default// (leq_trans _ (leq_addl _ _)). Qed. Lemma size_drop_poly n p : size (drop_poly n p) = (size p - n)%N. Proof. have [pLn|nLp] := leqP (size p) n. by rewrite (eqP pLn) drop_poly_eq0 ?size_poly0. have p_neq0 : p != 0 by rewrite -size_poly_gt0 (leq_trans _ nLp). by rewrite size_poly_eq// predn_sub subnK ?lead_coef_eq0// -ltnS -polySpred. Qed. Lemma sum_drop_poly n p : \sum_(n <= i < size p) p`_i *: 'X^i = drop_poly n p * 'X^n. Proof. rewrite (big_addn 0) big_mkord /drop_poly poly_def mulr_suml. by apply: eq_bigr => i _; rewrite exprD scalerAl. Qed. Lemma drop_polyD m p q : drop_poly m (p + q) = drop_poly m p + drop_poly m q. Proof. by apply/polyP => i; rewrite coefD !coef_drop_poly coefD. Qed. Lemma drop_polyZ k m p : drop_poly m (k *: p) = k *: drop_poly m p. Proof. by apply/polyP => i; rewrite coefZ !coef_drop_poly coefZ. Qed. Fact drop_poly_is_linear m : linear (drop_poly m). Proof. by move=> k p q; rewrite drop_polyD drop_polyZ. Qed. HB.instance Definition _ m := GRing.isSemilinear.Build R {poly R} {poly R} _ (drop_poly m) (GRing.semilinear_linear (drop_poly_is_linear m)). Lemma drop_poly_sum m I r P (p : I -> {poly R}) : drop_poly m (\sum_(i <- r | P i) p i) = \sum_(i <- r | P i) drop_poly m (p i). Proof. exact: linear_sum. Qed. Lemma drop_poly0l p : drop_poly 0 p = p. Proof. by apply/polyP => i; rewrite coef_poly subn0 addn0 if_nth ?leqVgt. Qed. Lemma drop_poly0r m : drop_poly m 0 = 0. Proof. exact: linear0. Qed. Lemma drop_polyMXn m n p : drop_poly m (p * 'X^n) = drop_poly (m - n) p * 'X^(n - m). Proof. have [->|p_neq0] := eqVneq p 0; first by rewrite mul0r !drop_poly0r mul0r. apply/polyP => i; rewrite !(coefMXn, coef_drop_poly) ltn_subRL [(m + i)%N]addnC. have [i_small|i_big]// := ltnP; congr nth. by have [mn|/ltnW mn] := leqP m n; rewrite (eqP mn) (addn0, subn0) (subnBA, addnBA). Qed. Lemma drop_polyMXn_id n p : drop_poly n (p * 'X^ n) = p. Proof. by rewrite drop_polyMXn subnn drop_poly0l expr0 mulr1. Qed. Lemma drop_polyDMXn n p q : size p <= n -> drop_poly n (p + q * 'X^n) = q. Proof. by move=> ?; rewrite drop_polyD drop_poly_eq0// drop_polyMXn_id add0r. Qed. Lemma poly_take_drop n p : take_poly n p + drop_poly n p * 'X^n = p. Proof. apply/polyP => i; rewrite coefD coefMXn coef_take_poly coef_drop_poly. by case: ltnP => ni; rewrite ?addr0 ?add0r//= subnK. Qed. Lemma eqp_take_drop n p q : take_poly n p = take_poly n q -> drop_poly n p = drop_poly n q -> p = q. Proof. by move=> tpq dpq; rewrite -[p](poly_take_drop n) -[q](poly_take_drop n) tpq dpq. Qed. End Surgery. Definition coefE := (coef0, coef1, coefC, coefX, coefXn, coef_sumMXn, coefZ, coefMC, coefCM, coefXnM, coefMXn, coefXM, coefMX, coefMNn, coefMn, coefN, coefB, coefD, coef_even_poly, coef_odd_poly, coef_take_poly, coef_drop_poly, coef_cons, coef_Poly, coef_poly, coef_deriv, coef_nderivn, coef_derivn, coef_map, coef_sum, coef_comp_poly_Xn, coef_comp_poly). Section PolynomialComNzRing. Variable R : comNzRingType. Implicit Types p q : {poly R}. Fact poly_mul_comm p q : p * q = q * p. Proof. apply/polyP=> i; rewrite coefM coefMr. by apply: eq_bigr => j _; rewrite mulrC. Qed. HB.instance Definition _ := GRing.PzRing_hasCommutativeMul.Build (polynomial R) poly_mul_comm. HB.instance Definition _ := GRing.Lalgebra_isComAlgebra.Build R (polynomial R). Lemma coef_prod_XsubC (ps : seq R) (n : nat) : (n <= size ps)%N -> (\prod_(p <- ps) ('X - p%:P))`_n = (-1) ^+ (size ps - n)%N * \sum_(I in {set 'I_(size ps)} | #|I| == (size ps - n)%N) \prod_(i in I) ps`_i. Proof. move=> nle. under eq_bigr => i _ do rewrite addrC -raddfN/=. rewrite -{1}(in_tupleE ps) -(map_tnth_enum (_ ps)) big_map. rewrite enumT bigA_distr /= coef_sum. transitivity (\sum_(I in {set 'I_(size ps)}) if #|I| == (size ps - n)%N then \prod_(i < size ps | i \in I) - ps`_i else 0). apply eq_bigr => I _. rewrite big_if/= big_const iter_mulr_1 -rmorph_prod/= coefCM coefXn. under eq_bigr => i _ do rewrite (tnth_nth 0)/=. rewrite -[#|I| == _](eqn_add2r n) subnK//. rewrite -[X in (_ + _)%N == X]card_ord -(cardC I) eqn_add2l. by case: ifP; rewrite ?mulr1 ?mulr0. by rewrite -big_mkcond mulr_sumr/=; apply: eq_bigr => I /eqP <-; rewrite prodrN. Qed. Lemma coefPn_prod_XsubC (ps : seq R) : size ps != 0 -> (\prod_(p <- ps) ('X - p%:P))`_(size ps).-1 = - \sum_(p <- ps) p. Proof. rewrite coef_prod_XsubC ?leq_pred// => ps0. have -> : (size ps - (size ps).-1 = 1)%N. by move: ps0; case: (size ps) => // n _; exact: subSnn. rewrite expr1 mulN1r; congr GRing.opp. set f : 'I_(size ps) -> {set 'I_(size ps)} := fun a => [set a]. transitivity (\sum_(I in imset f (mem setT)) \prod_(i in I) ps`_i). apply: congr_big => // I /=. by apply/cards1P/imsetP => [[a ->] | [a _ ->]]; exists a. rewrite big_imset/=; last first. by move=> i j _ _ ij; apply/set1P; rewrite -/(f j) -ij set11. rewrite -[in RHS](in_tupleE ps) -(map_tnth_enum (_ ps)) big_map enumT. apply: congr_big => // i; first exact: in_setT. by rewrite big_set1 (tnth_nth 0). Qed. Lemma coef0_prod_XsubC (ps : seq R) : (\prod_(p <- ps) ('X - p%:P))`_0 = (-1) ^+ (size ps) * \prod_(p <- ps) p. Proof. rewrite coef_prod_XsubC// subn0; congr GRing.mul. transitivity (\sum_(I in [set setT : {set 'I_(size ps)}]) \prod_(i in I) ps`_i). apply: congr_big =>// i/=. apply/idP/set1P => [/eqP cardE | ->]; last by rewrite cardsT card_ord. by apply/eqP; rewrite eqEcard subsetT cardsT card_ord cardE leqnn. rewrite big_set1 -[in RHS](in_tupleE ps) -(map_tnth_enum (_ ps)) big_map enumT. apply: congr_big => // i; first exact: in_setT. by rewrite (tnth_nth 0). Qed. Lemma hornerM p q x : (p * q).[x] = p.[x] * q.[x]. Proof. by rewrite hornerM_comm //; apply: mulrC. Qed. Lemma horner_exp p x n : (p ^+ n).[x] = p.[x] ^+ n. Proof. by rewrite horner_exp_comm //; apply: mulrC. Qed. Lemma horner_prod I r (P : pred I) (F : I -> {poly R}) x : (\prod_(i <- r | P i) F i).[x] = \prod_(i <- r | P i) (F i).[x]. Proof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (hornerM, hornerC). Qed. Definition hornerE := (hornerD, hornerN, hornerX, hornerC, horner_exp, simp, hornerCM, hornerZ, hornerM, horner_cons). Definition horner_eval (x : R) := horner^~ x. Lemma horner_evalE x p : horner_eval x p = p.[x]. Proof. by []. Qed. Fact horner_eval_is_linear x : linear_for *%R (horner_eval x). Proof. have cxid: commr_rmorph idfun x by apply: mulrC. have evalE : horner_eval x =1 horner_morph cxid. by move=> p; congr _.[x]; rewrite map_poly_id. by move=> c p q; rewrite !evalE linearP. Qed. Fact horner_eval_is_monoid_morphism x : monoid_morphism (horner_eval x). Proof. have cxid: commr_rmorph idfun x by apply: mulrC. have evalE : horner_eval x =1 horner_morph cxid. by move=> p; congr _.[x]; rewrite map_poly_id. by split=> [|p q]; rewrite !evalE ?rmorph1// rmorphM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `horner_eval_is_monoid_morphism` instead")] Definition horner_eval_is_multiplicative x := (fun g => (g.2, g.1)) (horner_eval_is_monoid_morphism x). HB.instance Definition _ x := GRing.isSemilinear.Build R {poly R} R _ (horner_eval x) (GRing.semilinear_linear (horner_eval_is_linear x)). HB.instance Definition _ x := GRing.isMonoidMorphism.Build {poly R} R (horner_eval x) (horner_eval_is_monoid_morphism x). Section HornerAlg. Variable A : algType R. (* For univariate polys, commutativity is not needed *) Section Defs. Variable a : A. Lemma in_alg_comm : commr_rmorph (in_alg A) a. Proof. move=> r /=; by rewrite /GRing.comm comm_alg. Qed. Definition horner_alg := horner_morph in_alg_comm. Lemma horner_algC c : horner_alg c%:P = c%:A. Proof. exact: horner_morphC. Qed. Lemma horner_algX : horner_alg 'X = a. Proof. exact: horner_morphX. Qed. HB.instance Definition _ := GRing.LRMorphism.on horner_alg. End Defs. Variable (pf : {lrmorphism {poly R} -> A}). Lemma poly_alg_initial : pf =1 horner_alg (pf 'X). Proof. apply: poly_ind => [|p a IHp]; first by rewrite !rmorph0. rewrite !rmorphD !rmorphM /= -{}IHp horner_algC ?horner_algX. by rewrite -alg_polyC rmorph_alg. Qed. End HornerAlg. Fact comp_poly_is_monoid_morphism q : monoid_morphism (comp_poly q). Proof. split=> [|p1 p2]; first by rewrite comp_polyC. by rewrite /comp_poly rmorphM hornerM_comm //; apply: mulrC. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `comp_poly_is_monoid_morphism` instead")] Definition comp_poly_multiplicative q := (fun g => (g.2, g.1)) (comp_poly_is_monoid_morphism q). HB.instance Definition _ q := GRing.isMonoidMorphism.Build _ _ (comp_poly q) (comp_poly_is_monoid_morphism q). Lemma comp_polyM p q r : (p * q) \Po r = (p \Po r) * (q \Po r). Proof. exact: rmorphM. Qed. Lemma comp_polyA p q r : p \Po (q \Po r) = (p \Po q) \Po r. Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !comp_polyC. by rewrite !comp_polyD !comp_polyM !comp_polyX IHp !comp_polyC. Qed. Lemma horner_comp p q x : (p \Po q).[x] = p.[q.[x]]. Proof. by apply: polyC_inj; rewrite -!comp_polyCr comp_polyA. Qed. Lemma root_comp p q x : root (p \Po q) x = root p (q.[x]). Proof. by rewrite !rootE horner_comp. Qed. Lemma deriv_comp p q : (p \Po q) ^`() = (p ^`() \Po q) * q^`(). Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !(deriv0, comp_poly0) mul0r. rewrite comp_poly_MXaddC derivD derivC derivM IHp derivMXaddC comp_polyD. by rewrite comp_polyM comp_polyX addr0 addrC mulrAC -mulrDl. Qed. Lemma deriv_exp p n : (p ^+ n)^`() = p^`() * p ^+ n.-1 *+ n. Proof. elim: n => [|n IHn]; first by rewrite expr0 mulr0n derivC. by rewrite exprS derivM {}IHn (mulrC p) mulrnAl -mulrA -exprSr mulrS; case n. Qed. Definition derivCE := (derivE, deriv_exp). End PolynomialComNzRing. Section PolynomialIdomain. (* Integral domain structure on poly *) Variable R : idomainType. Implicit Types (a b x y : R) (p q r m : {poly R}). Lemma size_mul p q : p != 0 -> q != 0 -> size (p * q) = (size p + size q).-1. Proof. by move=> nz_p nz_q; rewrite -size_proper_mul ?mulf_neq0 ?lead_coef_eq0. Qed. Fact poly_idomainAxiom p q : p * q = 0 -> (p == 0) || (q == 0). Proof. move=> pq0; apply/norP=> [[p_nz q_nz]]; move/eqP: (size_mul p_nz q_nz). by rewrite eq_sym pq0 size_poly0 (polySpred p_nz) (polySpred q_nz) addnS. Qed. Definition poly_unit : pred {poly R} := fun p => (size p == 1) && (p`_0 \in GRing.unit). Definition poly_inv p := if p \in poly_unit then (p`_0)^-1%:P else p. Fact poly_mulVp : {in poly_unit, left_inverse 1 poly_inv *%R}. Proof. move=> p Up; rewrite /poly_inv Up. by case/andP: Up => /size_poly1P[c _ ->]; rewrite coefC -polyCM => /mulVr->. Qed. Fact poly_intro_unit p q : q * p = 1 -> p \in poly_unit. Proof. move=> pq1; apply/andP; split; last first. apply/unitrP; exists q`_0. by rewrite 2!mulrC -!/(coefp 0 _) -rmorphM pq1 rmorph1. have: size (q * p) == 1 by rewrite pq1 size_poly1. have [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0. have [-> | nz_q] := eqVneq q 0; first by rewrite mul0r size_poly0. rewrite size_mul // (polySpred nz_p) (polySpred nz_q) addnS addSn !eqSS. by rewrite addn_eq0 => /andP[]. Qed. Fact poly_inv_out : {in [predC poly_unit], poly_inv =1 id}. Proof. by rewrite /poly_inv => p /negbTE/= ->. Qed. HB.instance Definition _ := GRing.ComNzRing_hasMulInverse.Build (polynomial R) poly_mulVp poly_intro_unit poly_inv_out. HB.instance Definition _ := GRing.ComUnitRing_isIntegral.Build (polynomial R) poly_idomainAxiom. Lemma poly_unitE p : (p \in GRing.unit) = (size p == 1) && (p`_0 \in GRing.unit). Proof. by []. Qed. Lemma poly_invE p : p ^-1 = if p \in GRing.unit then (p`_0)^-1%:P else p. Proof. by []. Qed. Lemma polyCV c : c%:P^-1 = (c^-1)%:P. Proof. have [/rmorphV-> // | nUc] := boolP (c \in GRing.unit). by rewrite !invr_out // poly_unitE coefC (negbTE nUc) andbF. Qed. Lemma rootM p q x : root (p * q) x = root p x || root q x. Proof. by rewrite !rootE hornerM mulf_eq0. Qed. Lemma rootZ x a p : a != 0 -> root (a *: p) x = root p x. Proof. by move=> nz_a; rewrite -mul_polyC rootM rootC (negPf nz_a). Qed. Lemma root_exp p n a: comm_poly p a -> (0 < n)%N -> root (p ^+ n) a = root p a. Proof. by move=> ? n0; rewrite !rootE horner_exp_comm// expf_eq0 n0. Qed. Lemma size_scale a p : a != 0 -> size (a *: p) = size p. Proof. by move/lregP/lreg_size->. Qed. Lemma size_Cmul a p : a != 0 -> size (a%:P * p) = size p. Proof. by rewrite mul_polyC => /size_scale->. Qed. Lemma lead_coefM p q : lead_coef (p * q) = lead_coef p * lead_coef q. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, lead_coef0). have [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, lead_coef0). by rewrite lead_coef_proper_mul // mulf_neq0 ?lead_coef_eq0. Qed. Lemma lead_coef_prod I rI (P : {pred I}) (p : I -> {poly R}) : lead_coef (\prod_(i <- rI | P i) p i) = \prod_(i <- rI | P i) lead_coef (p i). Proof. by apply/big_morph/lead_coef1; apply: lead_coefM. Qed. Lemma lead_coefZ a p : lead_coef (a *: p) = a * lead_coef p. Proof. by rewrite -mul_polyC lead_coefM lead_coefC. Qed. Lemma scale_poly_eq0 a p : (a *: p == 0) = (a == 0) || (p == 0). Proof. by rewrite -mul_polyC mulf_eq0 polyC_eq0. Qed. Lemma size_prod (I : finType) (P : pred I) (F : I -> {poly R}) : (forall i, P i -> F i != 0) -> size (\prod_(i | P i) F i) = ((\sum_(i | P i) size (F i)).+1 - #|P|)%N. Proof. move=> nzF; transitivity (\sum_(i | P i) (size (F i)).-1).+1; last first. apply: canRL (addKn _) _; rewrite addnS -sum1_card -big_split /=. by congr _.+1; apply: eq_bigr => i /nzF/polySpred. elim/big_rec2: _ => [|i d p /nzF nzFi IHp]; first by rewrite size_poly1. by rewrite size_mul // -?size_poly_eq0 IHp // addnS polySpred. Qed. Lemma size_prod_seq (I : eqType) (s : seq I) (F : I -> {poly R}) : (forall i, i \in s -> F i != 0) -> size (\prod_(i <- s) F i) = ((\sum_(i <- s) size (F i)).+1 - size s)%N. Proof. move=> nzF; rewrite big_tnth size_prod; last by move=> i; rewrite nzF ?mem_tnth. by rewrite cardT /= size_enum_ord [in RHS]big_tnth. Qed. Lemma size_mul_eq1 p q : (size (p * q) == 1) = ((size p == 1) && (size q == 1)). Proof. have [->|pNZ] := eqVneq p 0; first by rewrite mul0r size_poly0. have [->|qNZ] := eqVneq q 0; first by rewrite mulr0 size_poly0 andbF. rewrite size_mul //. by move: pNZ qNZ; rewrite -!size_poly_gt0; (do 2 case: size) => //= n [|[|]]. Qed. Lemma size_prod_seq_eq1 (I : eqType) (s : seq I) (P : pred I) (F : I -> {poly R}) : reflect (forall i, P i && (i \in s) -> size (F i) = 1) (size (\prod_(i <- s | P i) F i) == 1%N). Proof. rewrite (big_morph _ (id1:=true) size_mul_eq1) ?size_polyC ?oner_neq0//. rewrite big_all_cond; apply/(iffP allP). by move=> h i /andP[Pi ins]; apply/eqP/(implyP (h i ins) Pi). by move=> h i ins; apply/implyP => Pi; rewrite h ?Pi. Qed. Lemma size_prod_eq1 (I : finType) (P : pred I) (F : I -> {poly R}) : reflect (forall i, P i -> size (F i) = 1) (size (\prod_(i | P i) F i) == 1). Proof. apply: (iffP (size_prod_seq_eq1 _ _ _)) => Hi i. by move=> Pi; apply: Hi; rewrite Pi /= mem_index_enum. by rewrite mem_index_enum andbT; apply: Hi. Qed. Lemma size_exp p n : (size (p ^+ n)).-1 = ((size p).-1 * n)%N. Proof. elim: n => [|n IHn]; first by rewrite size_poly1 muln0. have [-> | nz_p] := eqVneq p 0; first by rewrite exprS mul0r size_poly0. rewrite exprS size_mul ?expf_neq0 // mulnS -{}IHn. by rewrite polySpred // [size (p ^+ n)]polySpred ?expf_neq0 ?addnS. Qed. Lemma lead_coef_exp p n : lead_coef (p ^+ n) = lead_coef p ^+ n. Proof. elim: n => [|n IHn]; first by rewrite !expr0 lead_coef1. by rewrite !exprS lead_coefM IHn. Qed. Lemma root_prod_XsubC rs x : root (\prod_(a <- rs) ('X - a%:P)) x = (x \in rs). Proof. elim: rs => [|a rs IHrs]; first by rewrite rootE big_nil hornerC oner_eq0. by rewrite big_cons rootM IHrs root_XsubC. Qed. Lemma root_exp_XsubC n a x : root (('X - a%:P) ^+ n.+1) x = (x == a). Proof. by rewrite rootE horner_exp expf_eq0 [_ == 0]root_XsubC. Qed. Lemma size_comp_poly p q : (size (p \Po q)).-1 = ((size p).-1 * (size q).-1)%N. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite comp_poly0 size_poly0. have [/size1_polyC-> | nc_q] := leqP (size q) 1. by rewrite comp_polyCr !size_polyC -!sub1b -!subnS muln0. have nz_q: q != 0 by rewrite -size_poly_eq0 -(subnKC nc_q). rewrite mulnC comp_polyE (polySpred nz_p) /= big_ord_recr /= addrC. rewrite size_polyDl size_scale ?lead_coef_eq0 ?size_exp //=. rewrite [ltnRHS]polySpred ?expf_neq0 // ltnS size_exp. rewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _. rewrite (leq_trans (size_scale_leq _ _)) // polySpred ?expf_neq0 //. by rewrite size_exp -(subnKC nc_q) ltn_pmul2l. Qed. Lemma lead_coef_comp p q : size q > 1 -> lead_coef (p \Po q) = (lead_coef p) * lead_coef q ^+ (size p).-1. Proof. move=> q_gt1; rewrite !lead_coefE coef_comp_poly size_comp_poly. have [->|nz_p] := eqVneq p 0; first by rewrite size_poly0 big_ord0 coef0 mul0r. rewrite polySpred //= big_ord_recr /= big1 ?add0r => [|i _]. by rewrite -!lead_coefE -lead_coef_exp !lead_coefE size_exp mulnC. rewrite [X in _ * X]nth_default ?mulr0 ?(leq_trans (size_poly_exp_leq _ _)) //. by rewrite mulnC ltn_mul2r -subn1 subn_gt0 q_gt1 /=. Qed. Lemma comp_poly_eq0 p q : size q > 1 -> (p \Po q == 0) = (p == 0). Proof. move=> sq_gt1; rewrite -!lead_coef_eq0 lead_coef_comp //. rewrite mulf_eq0 expf_eq0 !lead_coef_eq0 -[q == 0]size_poly_leq0. by rewrite [_ <= 0]leqNgt (leq_ltn_trans _ sq_gt1) ?andbF ?orbF. Qed. Lemma size_comp_poly2 p q : size q = 2 -> size (p \Po q) = size p. Proof. move=> sq2; have [->|pN0] := eqVneq p 0; first by rewrite comp_polyC. by rewrite polySpred ?size_comp_poly ?comp_poly_eq0 ?sq2 // muln1 polySpred. Qed. Lemma comp_poly2_eq0 p q : size q = 2 -> (p \Po q == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /size_comp_poly2->. Qed. Theorem max_poly_roots p rs : p != 0 -> all (root p) rs -> uniq rs -> size rs < size p. Proof. elim: rs p => [p pn0 _ _ | r rs ihrs p pn0] /=; first by rewrite size_poly_gt0. case/andP => rpr arrs /andP [rnrs urs]; case/factor_theorem: rpr => q epq. have [q0 | ?] := eqVneq q 0; first by move: pn0; rewrite epq q0 mul0r eqxx. have -> : size p = (size q).+1. by rewrite epq size_Mmonic ?monicXsubC // size_XsubC addnC. suff /eq_in_all h : {in rs, root q =1 root p} by apply: ihrs => //; rewrite h. move=> x xrs; rewrite epq rootM root_XsubC orbC; case: (eqVneq x r) => // exr. by move: rnrs; rewrite -exr xrs. Qed. Lemma roots_geq_poly_eq0 p (rs : seq R) : all (root p) rs -> uniq rs -> (size rs >= size p)%N -> p = 0. Proof. by move=> ??; apply: contraTeq => ?; rewrite leqNgt max_poly_roots. Qed. End PolynomialIdomain. (* FIXME: these are seamingly artificial ways to close the inheritance graph *) (* We make parameters more and more precise to trigger completion by HB *) HB.instance Definition _ (R : countNzRingType) := [Countable of polynomial R by <:]. HB.instance Definition _ (R : countComNzRingType) := [Countable of polynomial R by <:]. HB.instance Definition _ (R : countIdomainType) := [Countable of polynomial R by <:]. Section MapFieldPoly. Variables (F : fieldType) (R : nzRingType) (f : {rmorphism F -> R}). Local Notation "p ^f" := (map_poly f p) : ring_scope. Lemma size_map_poly p : size p^f = size p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite rmorph0 !size_poly0. by rewrite size_poly_eq // fmorph_eq0 // lead_coef_eq0. Qed. Lemma lead_coef_map p : lead_coef p^f = f (lead_coef p). Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !(rmorph0, lead_coef0). by rewrite lead_coef_map_eq // fmorph_eq0 // lead_coef_eq0. Qed. Lemma map_poly_eq0 p : (p^f == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 size_map_poly. Qed. Lemma map_poly_inj : injective (map_poly f). Proof. move=> p q eqfpq; apply/eqP; rewrite -subr_eq0 -map_poly_eq0. by rewrite rmorphB /= eqfpq subrr. Qed. Lemma map_monic p : (p^f \is monic) = (p \is monic). Proof. by rewrite [in LHS]monicE lead_coef_map fmorph_eq1. Qed. Lemma map_poly_com p x : comm_poly p^f (f x). Proof. exact: map_comm_poly (mulrC x _). Qed. Lemma fmorph_root p x : root p^f (f x) = root p x. Proof. by rewrite rootE horner_map // fmorph_eq0. Qed. Lemma fmorph_unity_root n z : n.-unity_root (f z) = n.-unity_root z. Proof. by rewrite !unity_rootE -(inj_eq (fmorph_inj f)) rmorphXn ?rmorph1. Qed. Lemma fmorph_primitive_root n z : n.-primitive_root (f z) = n.-primitive_root z. Proof. by congr (_ && _); apply: eq_forallb => i; rewrite fmorph_unity_root. Qed. End MapFieldPoly. Arguments map_poly_inj {F R} f [p1 p2] : rename. Section MaxRoots. Variable R : unitRingType. Implicit Types (x y : R) (rs : seq R) (p : {poly R}). Definition diff_roots (x y : R) := (x * y == y * x) && (y - x \in GRing.unit). Fixpoint uniq_roots rs := if rs is x :: rs' then all (diff_roots x) rs' && uniq_roots rs' else true. Lemma uniq_roots_prod_XsubC p rs : all (root p) rs -> uniq_roots rs -> exists q, p = q * \prod_(z <- rs) ('X - z%:P). Proof. elim: rs => [|z rs IHrs] /=; first by rewrite big_nil; exists p; rewrite mulr1. case/andP=> rpz rprs /andP[drs urs]; case: IHrs => {urs rprs}// q def_p. have [|q' def_q] := factor_theorem q z _; last first. by exists q'; rewrite big_cons mulrA -def_q. rewrite {p}def_p in rpz. elim/last_ind: rs drs rpz => [|rs t IHrs] /=; first by rewrite big_nil mulr1. rewrite all_rcons => /andP[/andP[/eqP czt Uzt] /IHrs{}IHrs]. rewrite -cats1 big_cat big_seq1 /= mulrA rootE hornerM_comm; last first. by rewrite /comm_poly hornerXsubC mulrBl mulrBr czt. rewrite hornerXsubC -opprB mulrN oppr_eq0 -(mul0r (t - z)). by rewrite (inj_eq (mulIr Uzt)) => /IHrs. Qed. Theorem max_ring_poly_roots p rs : p != 0 -> all (root p) rs -> uniq_roots rs -> size rs < size p. Proof. move=> nz_p _ /(@uniq_roots_prod_XsubC p)[// | q def_p]; rewrite def_p in nz_p *. have nz_q: q != 0 by apply: contraNneq nz_p => ->; rewrite mul0r. rewrite size_Mmonic ?monic_prod_XsubC // (polySpred nz_q) addSn /=. by rewrite size_prod_XsubC leq_addl. Qed. Lemma all_roots_prod_XsubC p rs : size p = (size rs).+1 -> all (root p) rs -> uniq_roots rs -> p = lead_coef p *: \prod_(z <- rs) ('X - z%:P). Proof. move=> size_p /uniq_roots_prod_XsubC def_p Urs. case/def_p: Urs => q -> {p def_p} in size_p *. have [q0 | nz_q] := eqVneq q 0; first by rewrite q0 mul0r size_poly0 in size_p. have{q nz_q size_p} /size_poly1P[c _ ->]: size q == 1. rewrite -(eqn_add2r (size rs)) add1n -size_p. by rewrite size_Mmonic ?monic_prod_XsubC // size_prod_XsubC addnS. by rewrite lead_coef_Mmonic ?monic_prod_XsubC // lead_coefC mul_polyC. Qed. End MaxRoots. Section FieldRoots. Variable F : fieldType. Implicit Types (p : {poly F}) (rs : seq F). Lemma poly2_root p : size p = 2 -> {r | root p r}. Proof. case: p => [[|p0 [|p1 []]] //= nz_p1]; exists (- p0 / p1). by rewrite /root addr_eq0 /= mul0r add0r mulrC divfK ?opprK. Qed. Lemma uniq_rootsE rs : uniq_roots rs = uniq rs. Proof. elim: rs => //= r rs ->; congr (_ && _); rewrite -has_pred1 -all_predC. by apply: eq_all => t; rewrite /diff_roots mulrC eqxx unitfE subr_eq0. Qed. Lemma root_ZXsubC (a b r : F) : a != 0 -> root (a *: 'X - b%:P) r = (r == b / a). Proof. move=> a0; rewrite rootE !hornerE. by rewrite -[r in RHS]divr1 eqr_div ?oner_neq0// mulr1 mulrC subr_eq0. Qed. Section UnityRoots. Variable n : nat. Lemma max_unity_roots rs : n > 0 -> all n.-unity_root rs -> uniq rs -> size rs <= n. Proof. move=> n_gt0 rs_n_1 Urs; have szPn := size_XnsubC (1 : F) n_gt0. by rewrite -ltnS -szPn max_poly_roots -?size_poly_eq0 ?szPn. Qed. Lemma mem_unity_roots rs : n > 0 -> all n.-unity_root rs -> uniq rs -> size rs = n -> n.-unity_root =i rs. Proof. move=> n_gt0 rs_n_1 Urs sz_rs_n x; rewrite -topredE /=. apply/idP/idP=> xn1; last exact: (allP rs_n_1). apply: contraFT (ltnn n) => not_rs_x. by rewrite -{1}sz_rs_n (@max_unity_roots (x :: rs)) //= ?xn1 ?not_rs_x. Qed. (* Showing the existence of a primitive root requires the theory in cyclic. *) Variable z : F. Hypothesis prim_z : n.-primitive_root z. Let zn := [seq z ^+ i | i <- index_iota 0 n]. Lemma factor_Xn_sub_1 : \prod_(0 <= i < n) ('X - (z ^+ i)%:P) = 'X^n - 1. Proof. transitivity (\prod_(w <- zn) ('X - w%:P)); first by rewrite big_map. have n_gt0: n > 0 := prim_order_gt0 prim_z. rewrite (@all_roots_prod_XsubC _ ('X^n - 1) zn); first 1 last. - by rewrite size_XnsubC // size_map size_iota subn0. - apply/allP=> _ /mapP[i _ ->] /=; rewrite rootE !hornerE. by rewrite exprAC (prim_expr_order prim_z) expr1n subrr. - rewrite uniq_rootsE map_inj_in_uniq ?iota_uniq // => i j. rewrite !mem_index_iota => ltin ltjn /eqP. by rewrite (eq_prim_root_expr prim_z) !modn_small // => /eqP. by rewrite (monicP (monicXnsubC 1 n_gt0)) scale1r. Qed. Lemma prim_rootP x : x ^+ n = 1 -> {i : 'I_n | x = z ^+ i}. Proof. move=> xn1; pose logx := [pred i : 'I_n | x == z ^+ i]. case: (pickP logx) => [i /eqP-> | no_i]; first by exists i. case: notF; suffices{no_i}: x \in zn. case/mapP=> i; rewrite mem_index_iota => lt_i_n def_x. by rewrite -(no_i (Ordinal lt_i_n)) /= -def_x. rewrite -root_prod_XsubC big_map factor_Xn_sub_1. by rewrite [root _ x]unity_rootE xn1. Qed. End UnityRoots. End FieldRoots. Section MapPolyRoots. Variables (F : fieldType) (R : unitRingType) (f : {rmorphism F -> R}). Lemma map_diff_roots x y : diff_roots (f x) (f y) = (x != y). Proof. rewrite /diff_roots -rmorphB // fmorph_unit // subr_eq0 //. by rewrite rmorph_comm // eqxx eq_sym. Qed. Lemma map_uniq_roots s : uniq_roots (map f s) = uniq s. Proof. elim: s => //= x s ->; congr (_ && _); elim: s => //= y s ->. by rewrite map_diff_roots -negb_or. Qed. End MapPolyRoots. Section AutPolyRoot. (* The action of automorphisms on roots of unity. *) Variable F : fieldType. Implicit Types u v : {rmorphism F -> F}. Lemma aut_prim_rootP u z n : n.-primitive_root z -> {k | coprime k n & u z = z ^+ k}. Proof. move=> prim_z; have:= prim_z; rewrite -(fmorph_primitive_root u) => prim_uz. have [[k _] /= def_uz] := prim_rootP prim_z (prim_expr_order prim_uz). by exists k; rewrite // -(prim_root_exp_coprime _ prim_z) -def_uz. Qed. Lemma aut_unity_rootP u z n : n > 0 -> z ^+ n = 1 -> {k | u z = z ^+ k}. Proof. by move=> _ /prim_order_exists[// | m /(aut_prim_rootP u)[k]]; exists k. Qed. Lemma aut_unity_rootC u v z n : n > 0 -> z ^+ n = 1 -> u (v z) = v (u z). Proof. move=> n_gt0 /(aut_unity_rootP _ n_gt0) def_z. have [[i def_uz] [j def_vz]] := (def_z u, def_z v). by rewrite def_vz def_uz !rmorphXn /= def_vz def_uz exprAC. Qed. End AutPolyRoot. Module UnityRootTheory. Notation "n .-unity_root" := (root_of_unity n) : unity_root_scope. Notation "n .-primitive_root" := (primitive_root_of_unity n) : unity_root_scope. Open Scope unity_root_scope. Definition unity_rootE := unity_rootE. Definition unity_rootP := @unity_rootP. Arguments unity_rootP {R n z}. Definition prim_order_exists := prim_order_exists. Notation prim_order_gt0 := prim_order_gt0. Notation prim_expr_order := prim_expr_order. Definition prim_expr_mod := prim_expr_mod. Definition prim_order_dvd := prim_order_dvd. Definition eq_prim_root_expr := eq_prim_root_expr. Definition rmorph_unity_root := rmorph_unity_root. Definition fmorph_unity_root := fmorph_unity_root. Definition fmorph_primitive_root := fmorph_primitive_root. Definition max_unity_roots := max_unity_roots. Definition mem_unity_roots := mem_unity_roots. Definition prim_rootP := prim_rootP. End UnityRootTheory. Module Export Pdeg2. Module Export Field. Section Pdeg2Field. Variable F : fieldType. Hypothesis nz2 : 2 != 0 :> F. Variable p : {poly F}. Hypothesis degp : size p = 3. Let a := p`_2. Let b := p`_1. Let c := p`_0. Let pneq0 : p != 0. Proof. by rewrite -size_poly_gt0 degp. Qed. Let aneq0 : a != 0. Proof. by move: pneq0; rewrite -lead_coef_eq0 lead_coefE degp. Qed. Let a2neq0 : 2 * a != 0. Proof. by rewrite mulf_neq0. Qed. Let sqa2neq0 : (2 * a) ^+ 2 != 0. Proof. exact: expf_neq0. Qed. Let aa4 : 4 * a * a = (2 * a)^+2. Proof. by rewrite expr2 mulrACA mulrA -natrM. Qed. Let splitr (x : F) : x = x / 2 + x / 2. Proof. by apply: (mulIf nz2); rewrite -mulrDl mulfVK// mulr_natr mulr2n. Qed. Let pE : p = a *: 'X^2 + b *: 'X + c%:P. Proof. apply/polyP => + /[!coefE] => -[|[|[|i]]] /=; rewrite !Monoid.simpm//. by rewrite nth_default// degp. Qed. Let delta := b ^+ 2 - 4 * a * c. Lemma deg2_poly_canonical : p = a *: (('X + (b / (2 * a))%:P)^+2 - (delta / (4 * a ^+ 2))%:P). Proof. rewrite pE sqrrD -!addrA scalerDr; congr +%R; rewrite addrA scalerDr; congr +%R. - rewrite -mulrDr -polyCD -!mul_polyC mulrA mulrAC -polyCM. by rewrite [a * _]mulrC mulrDl invfM -!mulrA mulVf// mulr1 -splitr. - rewrite [a ^+ 2]expr2 mulrA aa4 -polyC_exp -polyCB expr_div_n -mulrBl subKr. by rewrite scale_polyC mulrCA mulrACA aa4 mulrCA mulfV// mulr1. Qed. Variable r : F. Hypothesis r_sqrt_delta : r ^+ 2 = delta. Let r1 := (- b - r) / (2 * a). Let r2 := (- b + r) / (2 * a). Lemma deg2_poly_factor : p = a *: ('X - r1%:P) * ('X - r2%:P). Proof. rewrite [p]deg2_poly_canonical//= -/a -/b -/c -/delta /r1 /r2. rewrite ![(- b + _) * _]mulrDl 2!polyCD 2!opprD 2!addrA !mulNr !polyCN !opprK. rewrite -scalerAl [in RHS]mulrC -subr_sqr -polyC_exp -[4]/(2 * 2)%:R natrM. by rewrite -expr2 -exprMn [in RHS]exprMn exprVn r_sqrt_delta. Qed. Lemma deg2_poly_root1 : root p r1. Proof. apply/factor_theorem. by exists (a *: ('X - r2%:P)); rewrite deg2_poly_factor -!scalerAl mulrC. Qed. Lemma deg2_poly_root2 : root p r2. Proof. apply/factor_theorem. by exists (a *: ('X - r1%:P)); rewrite deg2_poly_factor -!scalerAl. Qed. End Pdeg2Field. End Field. Module FieldMonic. Section Pdeg2FieldMonic. Variable F : fieldType. Hypothesis nz2 : 2 != 0 :> F. Variable p : {poly F}. Hypothesis degp : size p = 3. Hypothesis monicp : p \is monic. Let a := p`_2. Let b := p`_1. Let c := p`_0. Let a1 : a = 1. Proof. by move: (monicP monicp); rewrite lead_coefE degp. Qed. Let delta := b ^+ 2 - 4 * c. Lemma deg2_poly_canonical : p = (('X + (b / 2)%:P)^+2 - (delta / 4)%:P). Proof. by rewrite [p]deg2_poly_canonical// -/a a1 scale1r expr1n !mulr1. Qed. Variable r : F. Hypothesis r_sqrt_delta : r ^+ 2 = delta. Let r1 := (- b - r) / 2. Let r2 := (- b + r) / 2. Lemma deg2_poly_factor : p = ('X - r1%:P) * ('X - r2%:P). Proof. by rewrite [p](@deg2_poly_factor _ _ _ _ r)// -/a a1 !mulr1 ?scale1r. Qed. Lemma deg2_poly_root1 : root p r1. Proof. rewrite /r1 -[2]mulr1 -[X in 2 * X]a1. by apply: deg2_poly_root1; rewrite // -/a a1 mulr1. Qed. Lemma deg2_poly_root2 : root p r2. Proof. rewrite /r2 -[2]mulr1 -[X in 2 * X]a1. by apply: deg2_poly_root2; rewrite // -/a a1 mulr1. Qed. End Pdeg2FieldMonic. End FieldMonic. End Pdeg2. Section DecField. Variable F : decFieldType. Lemma dec_factor_theorem (p : {poly F}) : {s : seq F & {q : {poly F} | p = q * \prod_(x <- s) ('X - x%:P) /\ (q != 0 -> forall x, ~~ root q x)}}. Proof. pose polyT (p : seq F) := (foldr (fun c f => f * 'X_0 + c%:T) (0%R)%:T p)%T. have eval_polyT (q : {poly F}) x : GRing.eval [:: x] (polyT q) = q.[x]. by rewrite /horner; elim: (val q) => //= ? ? ->. have [n] := ubnP (size p); elim: n => // n IHn in p *. have /decPcases /= := @satP F [::] ('exists 'X_0, polyT p == 0%T). case: ifP => [_ /sig_eqW[x]|_ noroot]; last first. exists [::], p; rewrite big_nil mulr1; split => // p_neq0 x. by apply/negP=> /rootP rpx; apply: noroot; exists x; rewrite eval_polyT. rewrite eval_polyT => /rootP/factor_theorem/sig_eqW[p1 ->]. have [->|nz_p1] := eqVneq p1 0; first by exists [::], 0; rewrite !mul0r eqxx. rewrite size_Mmonic ?monicXsubC // size_XsubC addn2 => /IHn[s [q [-> irr_q]]]. by exists (rcons s x), q; rewrite -cats1 big_cat big_seq1 mulrA. Qed. End DecField. Module PreClosedField. Section UseAxiom. Variable F : fieldType. Hypothesis closedF : GRing.closed_field_axiom F. Implicit Type p : {poly F}. Lemma closed_rootP p : reflect (exists x, root p x) (size p != 1). Proof. have [-> | nz_p] := eqVneq p 0. by rewrite size_poly0; left; exists 0; rewrite root0. rewrite neq_ltn [in _ < 1]polySpred //=. apply: (iffP idP) => [p_gt1 | [a]]; last exact: root_size_gt1. pose n := (size p).-1; have n_gt0: n > 0 by rewrite -ltnS -polySpred. have [a Dan] := closedF (fun i => - p`_i / lead_coef p) n_gt0. exists a; apply/rootP; rewrite horner_coef polySpred // big_ord_recr /= -/n. rewrite {}Dan mulr_sumr -big_split big1 //= => i _. by rewrite -!mulrA mulrCA mulNr mulVKf ?subrr ?lead_coef_eq0. Qed. Lemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0). Proof. apply: (iffP idP) => [nz_p | [x]]; last first. by apply: contraNneq => ->; apply: root0. have [[x /rootP p1x0]|] := altP (closed_rootP (p - 1)). by exists x; rewrite -[p](subrK 1) /root hornerD p1x0 add0r hornerC oner_eq0. rewrite negbK => /size_poly1P[c _ /(canRL (subrK 1)) Dp]. by exists 0; rewrite Dp -raddfD polyC_eq0 rootC in nz_p *. Qed. End UseAxiom. End PreClosedField. Section ClosedField. Variable F : closedFieldType. Implicit Type p : {poly F}. Let closedF := @solve_monicpoly F. Lemma closed_rootP p : reflect (exists x, root p x) (size p != 1). Proof. exact: PreClosedField.closed_rootP. Qed. Lemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0). Proof. exact: PreClosedField.closed_nonrootP. Qed. Lemma closed_field_poly_normal p : {r : seq F | p = lead_coef p *: \prod_(z <- r) ('X - z%:P)}. Proof. apply: sig_eqW; have [r [q [->]]] /= := dec_factor_theorem p. have [->|] := eqVneq; first by exists [::]; rewrite mul0r lead_coef0 scale0r. have [[x rqx ? /(_ isT x) /negP /(_ rqx)] //|] := altP (closed_rootP q). rewrite negbK => /size_poly1P [c c_neq0-> _ _]; exists r. rewrite mul_polyC lead_coefZ (monicP _) ?mulr1 //. by rewrite monic_prod => // i; rewrite monicXsubC. Qed. End ClosedField.
DivergenceTheorem.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.Analysis.BoxIntegral.Basic import Mathlib.Analysis.BoxIntegral.Partition.Additive import Mathlib.Analysis.Calculus.FDeriv.Prod /-! # Divergence integral for Henstock-Kurzweil integral In this file we prove the Divergence Theorem for a Henstock-Kurzweil style integral. The theorem says the following. Let `f : ℝⁿ → Eⁿ` be a function differentiable on a closed rectangular box `I` with derivative `f' x : ℝⁿ →L[ℝ] Eⁿ` at `x ∈ I`. Then the divergence `fun x ↦ ∑ k, f' x eₖ k`, where `eₖ = Pi.single k 1` is the `k`-th basis vector, is integrable on `I`, and its integral is equal to the sum of integrals of `f` over the faces of `I` taken with appropriate signs. To make the proof work, we had to ban tagged partitions with “long and thin” boxes. More precisely, we use the following generalization of one-dimensional Henstock-Kurzweil integral to functions defined on a box in `ℝⁿ` (it corresponds to the value `BoxIntegral.IntegrationParams.GP = ⊥` of `BoxIntegral.IntegrationParams` in the definition of `BoxIntegral.HasIntegral`). We say that `f : ℝⁿ → E` has integral `y : E` over a box `I ⊆ ℝⁿ` if for an arbitrarily small positive `ε` and an arbitrarily large `c`, there exists a function `r : ℝⁿ → (0, ∞)` such that for any tagged partition `π` of `I` such that * `π` is a Henstock partition, i.e., each tag belongs to its box; * `π` is subordinate to `r`; * for every box of `π`, the maximum of the ratios of its sides is less than or equal to `c`, the integral sum of `f` over `π` is `ε`-close to `y`. In case of dimension one, the last condition trivially holds for any `c ≥ 1`, so this definition is equivalent to the standard definition of Henstock-Kurzweil integral. ## Tags Henstock-Kurzweil integral, integral, Stokes theorem, divergence theorem -/ open scoped NNReal ENNReal Topology BoxIntegral open ContinuousLinearMap (lsmul) open Filter Set Finset Metric open BoxIntegral.IntegrationParams (GP gp_le) noncomputable section universe u variable {E : Type u} [NormedAddCommGroup E] [NormedSpace ℝ E] {n : ℕ} namespace BoxIntegral variable [CompleteSpace E] (I : Box (Fin (n + 1))) {i : Fin (n + 1)} open MeasureTheory /-- Auxiliary lemma for the divergence theorem. -/ theorem norm_volume_sub_integral_face_upper_sub_lower_smul_le {f : (Fin (n + 1) → ℝ) → E} {f' : (Fin (n + 1) → ℝ) →L[ℝ] E} (hfc : ContinuousOn f (Box.Icc I)) {x : Fin (n + 1) → ℝ} (hxI : x ∈ (Box.Icc I)) {a : E} {ε : ℝ} (h0 : 0 < ε) (hε : ∀ y ∈ (Box.Icc I), ‖f y - a - f' (y - x)‖ ≤ ε * ‖y - x‖) {c : ℝ≥0} (hc : I.distortion ≤ c) : ‖(∏ j, (I.upper j - I.lower j)) • f' (Pi.single i 1) - (integral (I.face i) ⊥ (f ∘ i.insertNth (α := fun _ ↦ ℝ) (I.upper i)) BoxAdditiveMap.volume - integral (I.face i) ⊥ (f ∘ i.insertNth (α := fun _ ↦ ℝ) (I.lower i)) BoxAdditiveMap.volume)‖ ≤ 2 * ε * c * ∏ j, (I.upper j - I.lower j) := by -- Porting note: Lean fails to find `α` in the next line set e : ℝ → (Fin n → ℝ) → (Fin (n + 1) → ℝ) := i.insertNth (α := fun _ ↦ ℝ) /- **Plan of the proof**. The difference of the integrals of the affine function `fun y ↦ a + f' (y - x)` over the faces `x i = I.upper i` and `x i = I.lower i` is equal to the volume of `I` multiplied by `f' (Pi.single i 1)`, so it suffices to show that the integral of `f y - a - f' (y - x)` over each of these faces is less than or equal to `ε * c * vol I`. We integrate a function of the norm `≤ ε * diam I.Icc` over a box of volume `∏ j ≠ i, (I.upper j - I.lower j)`. Since `diam I.Icc ≤ c * (I.upper i - I.lower i)`, we get the required estimate. -/ have Hl : I.lower i ∈ Icc (I.lower i) (I.upper i) := Set.left_mem_Icc.2 (I.lower_le_upper i) have Hu : I.upper i ∈ Icc (I.lower i) (I.upper i) := Set.right_mem_Icc.2 (I.lower_le_upper i) have Hi : ∀ x ∈ Icc (I.lower i) (I.upper i), Integrable.{0, u, u} (I.face i) ⊥ (f ∘ e x) BoxAdditiveMap.volume := fun x hx => integrable_of_continuousOn _ (Box.continuousOn_face_Icc hfc hx) volume /- We start with an estimate: the difference of the values of `f` at the corresponding points of the faces `x i = I.lower i` and `x i = I.upper i` is `(2 * ε * diam I.Icc)`-close to the value of `f'` on `Pi.single i (I.upper i - I.lower i) = lᵢ • eᵢ`, where `lᵢ = I.upper i - I.lower i` is the length of `i`-th edge of `I` and `eᵢ = Pi.single i 1` is the `i`-th unit vector. -/ have : ∀ y ∈ Box.Icc (I.face i), ‖f' (Pi.single i (I.upper i - I.lower i)) - (f (e (I.upper i) y) - f (e (I.lower i) y))‖ ≤ 2 * ε * diam (Box.Icc I) := fun y hy ↦ by set g := fun y => f y - a - f' (y - x) with hg change ∀ y ∈ (Box.Icc I), ‖g y‖ ≤ ε * ‖y - x‖ at hε clear_value g; obtain rfl : f = fun y => a + f' (y - x) + g y := by simp [hg] convert_to ‖g (e (I.lower i) y) - g (e (I.upper i) y)‖ ≤ _ · congr 1 have := Fin.insertNth_sub_same (α := fun _ ↦ ℝ) i (I.upper i) (I.lower i) y simp only [← this, f'.map_sub]; abel · have : ∀ z ∈ Icc (I.lower i) (I.upper i), e z y ∈ (Box.Icc I) := fun z hz => I.mapsTo_insertNth_face_Icc hz hy replace hε : ∀ y ∈ (Box.Icc I), ‖g y‖ ≤ ε * diam (Box.Icc I) := by intro y hy refine (hε y hy).trans (mul_le_mul_of_nonneg_left ?_ h0.le) rw [← dist_eq_norm] exact dist_le_diam_of_mem I.isCompact_Icc.isBounded hy hxI rw [two_mul, add_mul] exact norm_sub_le_of_le (hε _ (this _ Hl)) (hε _ (this _ Hu)) calc ‖(∏ j, (I.upper j - I.lower j)) • f' (Pi.single i 1) - (integral (I.face i) ⊥ (f ∘ e (I.upper i)) BoxAdditiveMap.volume - integral (I.face i) ⊥ (f ∘ e (I.lower i)) BoxAdditiveMap.volume)‖ = ‖integral.{0, u, u} (I.face i) ⊥ (fun x : Fin n → ℝ => f' (Pi.single i (I.upper i - I.lower i)) - (f (e (I.upper i) x) - f (e (I.lower i) x))) BoxAdditiveMap.volume‖ := by rw [← integral_sub (Hi _ Hu) (Hi _ Hl), ← Box.volume_face_mul i, mul_smul, ← Box.volume_apply, ← BoxAdditiveMap.toSMul_apply, ← integral_const, ← BoxAdditiveMap.volume, ← integral_sub (integrable_const _) ((Hi _ Hu).sub (Hi _ Hl))] simp only [(· ∘ ·), Pi.sub_def, ← f'.map_smul, ← Pi.single_smul', smul_eq_mul, mul_one] _ ≤ (volume (I.face i : Set (Fin n → ℝ))).toReal * (2 * ε * c * (I.upper i - I.lower i)) := by -- The hard part of the estimate was done above, here we just replace `diam I.Icc` -- with `c * (I.upper i - I.lower i)` refine norm_integral_le_of_le_const (fun y hy => (this y hy).trans ?_) volume rw [mul_assoc (2 * ε)] gcongr exact I.diam_Icc_le_of_distortion_le i hc _ = 2 * ε * c * ∏ j, (I.upper j - I.lower j) := by rw [← measureReal_def, ← Measure.toBoxAdditive_apply, Box.volume_apply, ← I.volume_face_mul i] ac_rfl /-- If `f : ℝⁿ⁺¹ → E` is differentiable on a closed rectangular box `I` with derivative `f'`, then the partial derivative `fun x ↦ f' x (Pi.single i 1)` is Henstock-Kurzweil integrable with integral equal to the difference of integrals of `f` over the faces `x i = I.upper i` and `x i = I.lower i`. More precisely, we use a non-standard generalization of the Henstock-Kurzweil integral and we allow `f` to be non-differentiable (but still continuous) at a countable set of points. TODO: If `n > 0`, then the condition at `x ∈ s` can be replaced by a much weaker estimate but this requires either better integrability theorems, or usage of a filter depending on the countable set `s` (we need to ensure that none of the faces of a partition contain a point from `s`). -/ theorem hasIntegral_GP_pderiv (f : (Fin (n + 1) → ℝ) → E) (f' : (Fin (n + 1) → ℝ) → (Fin (n + 1) → ℝ) →L[ℝ] E) (s : Set (Fin (n + 1) → ℝ)) (hs : s.Countable) (Hs : ∀ x ∈ s, ContinuousWithinAt f (Box.Icc I) x) (Hd : ∀ x ∈ (Box.Icc I) \ s, HasFDerivWithinAt f (f' x) (Box.Icc I) x) (i : Fin (n + 1)) : HasIntegral.{0, u, u} I GP (fun x => f' x (Pi.single i 1)) BoxAdditiveMap.volume (integral.{0, u, u} (I.face i) GP (fun x => f (i.insertNth (I.upper i) x)) BoxAdditiveMap.volume - integral.{0, u, u} (I.face i) GP (fun x => f (i.insertNth (I.lower i) x)) BoxAdditiveMap.volume) := by /- Note that `f` is continuous on `I.Icc`, hence it is integrable on the faces of all boxes `J ≤ I`, thus the difference of integrals over `x i = J.upper i` and `x i = J.lower i` is a box-additive function of `J ≤ I`. -/ have Hc : ContinuousOn f (Box.Icc I) := fun x hx ↦ by by_cases hxs : x ∈ s exacts [Hs x hxs, (Hd x ⟨hx, hxs⟩).continuousWithinAt] set fI : ℝ → Box (Fin n) → E := fun y J => integral.{0, u, u} J GP (fun x => f (i.insertNth y x)) BoxAdditiveMap.volume set fb : Icc (I.lower i) (I.upper i) → Fin n →ᵇᵃ[↑(I.face i)] E := fun x => (integrable_of_continuousOn GP (Box.continuousOn_face_Icc Hc x.2) volume).toBoxAdditive set F : Fin (n + 1) →ᵇᵃ[I] E := BoxAdditiveMap.upperSubLower I i fI fb fun x _ J => rfl -- Thus our statement follows from some local estimates. change HasIntegral I GP (fun x => f' x (Pi.single i 1)) _ (F I) refine HasIntegral.of_le_Henstock_of_forall_isLittleO gp_le ?_ ?_ _ s hs ?_ ?_ ·-- We use the volume as an upper estimate. exact (volume : Measure (Fin (n + 1) → ℝ)).toBoxAdditive.restrict _ le_top · exact fun J => ENNReal.toReal_nonneg · intro c x hx ε ε0 /- Near `x ∈ s` we choose `δ` so that both vectors are small. `volume J • eᵢ` is small because `volume J ≤ (2 * δ) ^ (n + 1)` is small, and the difference of the integrals is small because each of the integrals is close to `volume (J.face i) • f x`. TODO: there should be a shorter and more readable way to formalize this simple proof. -/ have : ∀ᶠ δ in 𝓝[>] (0 : ℝ), δ ∈ Ioc (0 : ℝ) (1 / 2) ∧ (∀ᵉ (y₁ ∈ closedBall x δ ∩ (Box.Icc I)) (y₂ ∈ closedBall x δ ∩ (Box.Icc I)), ‖f y₁ - f y₂‖ ≤ ε / 2) ∧ (2 * δ) ^ (n + 1) * ‖f' x (Pi.single i 1)‖ ≤ ε / 2 := by refine .and (Ioc_mem_nhdsGT one_half_pos) (.and ?_ ?_) · rcases ((nhdsWithin_hasBasis nhds_basis_closedBall _).tendsto_iff nhds_basis_closedBall).1 (Hs x hx.2) _ (half_pos <| half_pos ε0) with ⟨δ₁, δ₁0, hδ₁⟩ filter_upwards [Ioc_mem_nhdsGT δ₁0] with δ hδ y₁ hy₁ y₂ hy₂ have : closedBall x δ ∩ (Box.Icc I) ⊆ closedBall x δ₁ ∩ (Box.Icc I) := by gcongr; exact hδ.2 rw [← dist_eq_norm] calc dist (f y₁) (f y₂) ≤ dist (f y₁) (f x) + dist (f y₂) (f x) := dist_triangle_right _ _ _ _ ≤ ε / 2 / 2 + ε / 2 / 2 := add_le_add (hδ₁ _ <| this hy₁) (hδ₁ _ <| this hy₂) _ = ε / 2 := add_halves _ · have : ContinuousWithinAt (fun δ : ℝ => (2 * δ) ^ (n + 1) * ‖f' x (Pi.single i 1)‖) (Ioi 0) 0 := ((continuousWithinAt_id.const_mul _).pow _).mul_const _ refine this.eventually (ge_mem_nhds ?_) simpa using half_pos ε0 rcases this.exists with ⟨δ, ⟨hδ0, hδ12⟩, hdfδ, hδ⟩ refine ⟨δ, hδ0, fun J hJI hJδ _ _ => add_halves ε ▸ ?_⟩ have Hl : J.lower i ∈ Icc (J.lower i) (J.upper i) := Set.left_mem_Icc.2 (J.lower_le_upper i) have Hu : J.upper i ∈ Icc (J.lower i) (J.upper i) := Set.right_mem_Icc.2 (J.lower_le_upper i) have Hi : ∀ x ∈ Icc (J.lower i) (J.upper i), Integrable.{0, u, u} (J.face i) GP (fun y => f (i.insertNth x y)) BoxAdditiveMap.volume := fun x hx => integrable_of_continuousOn _ (Box.continuousOn_face_Icc (Hc.mono <| Box.le_iff_Icc.1 hJI) hx) volume have hJδ' : Box.Icc J ⊆ closedBall x δ ∩ (Box.Icc I) := subset_inter hJδ (Box.le_iff_Icc.1 hJI) have Hmaps : ∀ z ∈ Icc (J.lower i) (J.upper i), MapsTo (i.insertNth z) (Box.Icc (J.face i)) (closedBall x δ ∩ (Box.Icc I)) := fun z hz => (J.mapsTo_insertNth_face_Icc hz).mono Subset.rfl hJδ' simp only [dist_eq_norm]; dsimp [F] rw [← integral_sub (Hi _ Hu) (Hi _ Hl)] refine (norm_sub_le _ _).trans (add_le_add ?_ ?_) · simp_rw [BoxAdditiveMap.volume_apply, norm_smul, Real.norm_eq_abs, abs_prod] refine (mul_le_mul_of_nonneg_right ?_ <| norm_nonneg _).trans hδ have : ∀ j, |J.upper j - J.lower j| ≤ 2 * δ := fun j ↦ calc dist (J.upper j) (J.lower j) ≤ dist J.upper J.lower := dist_le_pi_dist _ _ _ _ ≤ dist J.upper x + dist J.lower x := dist_triangle_right _ _ _ _ ≤ δ + δ := add_le_add (hJδ J.upper_mem_Icc) (hJδ J.lower_mem_Icc) _ = 2 * δ := (two_mul δ).symm calc ∏ j, |J.upper j - J.lower j| ≤ ∏ j : Fin (n + 1), 2 * δ := prod_le_prod (fun _ _ => abs_nonneg _) fun j _ => this j _ = (2 * δ) ^ (n + 1) := by simp · refine (norm_integral_le_of_le_const (fun y hy => hdfδ _ (Hmaps _ Hu hy) _ (Hmaps _ Hl hy)) volume).trans ?_ refine (mul_le_mul_of_nonneg_right ?_ (half_pos ε0).le).trans_eq (one_mul _) rw [Box.coe_eq_pi, measureReal_def, Real.volume_pi_Ioc_toReal (Box.lower_le_upper _)] refine prod_le_one (fun _ _ => sub_nonneg.2 <| Box.lower_le_upper _ _) fun j _ => ?_ calc J.upper (i.succAbove j) - J.lower (i.succAbove j) ≤ dist (J.upper (i.succAbove j)) (J.lower (i.succAbove j)) := le_abs_self _ _ ≤ dist J.upper J.lower := dist_le_pi_dist J.upper J.lower (i.succAbove j) _ ≤ dist J.upper x + dist J.lower x := dist_triangle_right _ _ _ _ ≤ δ + δ := add_le_add (hJδ J.upper_mem_Icc) (hJδ J.lower_mem_Icc) _ ≤ 1 / 2 + 1 / 2 := by gcongr _ = 1 := add_halves 1 · intro c x hx ε ε0 /- At a point `x ∉ s`, we unfold the definition of Fréchet differentiability, then use an estimate we proved earlier in this file. -/ rcases exists_pos_mul_lt ε0 (2 * c) with ⟨ε', ε'0, hlt⟩ rcases (nhdsWithin_hasBasis nhds_basis_closedBall _).mem_iff.1 ((Hd x hx).isLittleO.def ε'0) with ⟨δ, δ0, Hδ⟩ refine ⟨δ, δ0, fun J hle hJδ hxJ hJc => ?_⟩ simp only [BoxAdditiveMap.volume_apply, dist_eq_norm] refine (norm_volume_sub_integral_face_upper_sub_lower_smul_le _ (Hc.mono <| Box.le_iff_Icc.1 hle) hxJ ε'0 (fun y hy => Hδ ?_) (hJc rfl)).trans ?_ · exact ⟨hJδ hy, Box.le_iff_Icc.1 hle hy⟩ · rw [mul_right_comm (2 : ℝ), ← Box.volume_apply] exact mul_le_mul_of_nonneg_right hlt.le ENNReal.toReal_nonneg /-- Divergence theorem for a Henstock-Kurzweil style integral. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is differentiable on a closed rectangular box `I` with derivative `f'`, then the divergence `∑ i, f' x (Pi.single i 1) i` is Henstock-Kurzweil integrable with integral equal to the sum of integrals of `f` over the faces of `I` taken with appropriate signs. More precisely, we use a non-standard generalization of the Henstock-Kurzweil integral and we allow `f` to be non-differentiable (but still continuous) at a countable set of points. -/ theorem hasIntegral_GP_divergence_of_forall_hasDerivWithinAt (f : (Fin (n + 1) → ℝ) → Fin (n + 1) → E) (f' : (Fin (n + 1) → ℝ) → (Fin (n + 1) → ℝ) →L[ℝ] (Fin (n + 1) → E)) (s : Set (Fin (n + 1) → ℝ)) (hs : s.Countable) (Hs : ∀ x ∈ s, ContinuousWithinAt f (Box.Icc I) x) (Hd : ∀ x ∈ (Box.Icc I) \ s, HasFDerivWithinAt f (f' x) (Box.Icc I) x) : HasIntegral.{0, u, u} I GP (fun x => ∑ i, f' x (Pi.single i 1) i) BoxAdditiveMap.volume (∑ i, (integral.{0, u, u} (I.face i) GP (fun x => f (i.insertNth (I.upper i) x) i) BoxAdditiveMap.volume - integral.{0, u, u} (I.face i) GP (fun x => f (i.insertNth (I.lower i) x) i) BoxAdditiveMap.volume)) := by refine HasIntegral.sum fun i _ => ?_ simp only [hasFDerivWithinAt_pi', continuousWithinAt_pi] at Hd Hs exact hasIntegral_GP_pderiv I _ _ s hs (fun x hx => Hs x hx i) (fun x hx => Hd x hx i) i end BoxIntegral