filename
stringlengths
5
42
content
stringlengths
15
319k
Basic.lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import Mathlib.Algebra.Group.Basic import Mathlib.Algebra.Group.Commute.Defs import Mathlib.Algebra.Group.Units.Defs import Mathlib.Algebra.Regular.Defs /-! # Regular elements By definition, a regular element in a commutative ring is a non-zero divisor. Lemma `isRegular_of_ne_zero` implies that every non-zero element of an integral domain is regular. Since it assumes that the ring is a `CancelMonoidWithZero` it applies also, for instance, to `ℕ`. The lemmas in Section `MulZeroClass` show that the `0` element is (left/right-)regular if and only if the `MulZeroClass` is trivial. This is useful when figuring out stopping conditions for regular sequences: if `0` is ever an element of a regular sequence, then we can extend the sequence by adding one further `0`. The final goal is to develop part of the API to prove, eventually, results about non-zero-divisors. -/ variable {R : Type*} section Mul variable [Mul R] @[to_additive] theorem IsLeftRegular.right_of_commute {a : R} (ca : ∀ b, Commute a b) (h : IsLeftRegular a) : IsRightRegular a := fun x y xy => h <| (ca x).trans <| xy.trans <| (ca y).symm @[to_additive] theorem IsRightRegular.left_of_commute {a : R} (ca : ∀ b, Commute a b) (h : IsRightRegular a) : IsLeftRegular a := by simp only [@Commute.symm_iff R _ a] at ca exact fun x y xy => h <| (ca x).trans <| xy.trans <| (ca y).symm @[to_additive] theorem Commute.isRightRegular_iff {a : R} (ca : ∀ b, Commute a b) : IsRightRegular a ↔ IsLeftRegular a := ⟨IsRightRegular.left_of_commute ca, IsLeftRegular.right_of_commute ca⟩ @[to_additive] theorem Commute.isRegular_iff {a : R} (ca : ∀ b, Commute a b) : IsRegular a ↔ IsLeftRegular a := ⟨fun h => h.left, fun h => ⟨h, h.right_of_commute ca⟩⟩ end Mul section Semigroup variable [Semigroup R] {a b : R} /-- In a semigroup, the product of left-regular elements is left-regular. -/ @[to_additive /-- In an additive semigroup, the sum of add-left-regular elements is add-left.regular. -/] theorem IsLeftRegular.mul (lra : IsLeftRegular a) (lrb : IsLeftRegular b) : IsLeftRegular (a * b) := show Function.Injective (((a * b) * ·)) from comp_mul_left a b ▸ lra.comp lrb /-- In a semigroup, the product of right-regular elements is right-regular. -/ @[to_additive /-- In an additive semigroup, the sum of add-right-regular elements is add-right-regular. -/] theorem IsRightRegular.mul (rra : IsRightRegular a) (rrb : IsRightRegular b) : IsRightRegular (a * b) := show Function.Injective (· * (a * b)) from comp_mul_right b a ▸ rrb.comp rra /-- In a semigroup, the product of regular elements is regular. -/ @[to_additive /-- In an additive semigroup, the sum of add-regular elements is add-regular. -/] theorem IsRegular.mul (rra : IsRegular a) (rrb : IsRegular b) : IsRegular (a * b) := ⟨rra.left.mul rrb.left, rra.right.mul rrb.right⟩ /-- If an element `b` becomes left-regular after multiplying it on the left by a left-regular element, then `b` is left-regular. -/ @[to_additive /-- If an element `b` becomes add-left-regular after adding to it on the left an add-left-regular element, then `b` is add-left-regular. -/] theorem IsLeftRegular.of_mul (ab : IsLeftRegular (a * b)) : IsLeftRegular b := Function.Injective.of_comp (f := (a * ·)) (by rwa [comp_mul_left a b]) /-- An element is left-regular if and only if multiplying it on the left by a left-regular element is left-regular. -/ @[to_additive (attr := simp) /-- An element is add-left-regular if and only if adding to it on the left an add-left-regular element is add-left-regular. -/] theorem mul_isLeftRegular_iff (b : R) (ha : IsLeftRegular a) : IsLeftRegular (a * b) ↔ IsLeftRegular b := ⟨fun ab => IsLeftRegular.of_mul ab, fun ab => IsLeftRegular.mul ha ab⟩ /-- If an element `b` becomes right-regular after multiplying it on the right by a right-regular element, then `b` is right-regular. -/ @[to_additive /-- If an element `b` becomes add-right-regular after adding to it on the right an add-right-regular element, then `b` is add-right-regular. -/] theorem IsRightRegular.of_mul (ab : IsRightRegular (b * a)) : IsRightRegular b := by refine fun x y xy => ab (?_ : x * (b * a) = y * (b * a)) rw [← mul_assoc, ← mul_assoc] exact congr_arg (· * a) xy /-- An element is right-regular if and only if multiplying it on the right with a right-regular element is right-regular. -/ @[to_additive (attr := simp) /-- An element is add-right-regular if and only if adding it on the right to an add-right-regular element is add-right-regular. -/] theorem mul_isRightRegular_iff (b : R) (ha : IsRightRegular a) : IsRightRegular (b * a) ↔ IsRightRegular b := ⟨fun ab => IsRightRegular.of_mul ab, fun ab => IsRightRegular.mul ab ha⟩ /-- Two elements `a` and `b` are regular if and only if both products `a * b` and `b * a` are regular. -/ @[to_additive /-- Two elements `a` and `b` are add-regular if and only if both sums `a + b` and `b + a` are add-regular. -/] theorem isRegular_mul_and_mul_iff : IsRegular (a * b) ∧ IsRegular (b * a) ↔ IsRegular a ∧ IsRegular b := by refine ⟨?_, ?_⟩ · rintro ⟨ab, ba⟩ exact ⟨⟨IsLeftRegular.of_mul ba.left, IsRightRegular.of_mul ab.right⟩, ⟨IsLeftRegular.of_mul ab.left, IsRightRegular.of_mul ba.right⟩⟩ · rintro ⟨ha, hb⟩ exact ⟨ha.mul hb, hb.mul ha⟩ /-- The "most used" implication of `mul_and_mul_iff`, with split hypotheses, instead of `∧`. -/ @[to_additive /-- The "most used" implication of `add_and_add_iff`, with split hypotheses, instead of `∧`. -/] theorem IsRegular.and_of_mul_of_mul (ab : IsRegular (a * b)) (ba : IsRegular (b * a)) : IsRegular a ∧ IsRegular b := isRegular_mul_and_mul_iff.mp ⟨ab, ba⟩ end Semigroup section MulOneClass variable [MulOneClass R] /-- If multiplying by `1` on either side is the identity, `1` is regular. -/ @[to_additive /-- If adding `0` on either side is the identity, `0` is regular. -/] theorem isRegular_one : IsRegular (1 : R) := ⟨fun a b ab => (one_mul a).symm.trans (Eq.trans ab (one_mul b)), fun a b ab => (mul_one a).symm.trans (Eq.trans ab (mul_one b))⟩ end MulOneClass section CommSemigroup variable [CommSemigroup R] {a b : R} /-- A product is regular if and only if the factors are. -/ @[to_additive /-- A sum is add-regular if and only if the summands are. -/] theorem isRegular_mul_iff : IsRegular (a * b) ↔ IsRegular a ∧ IsRegular b := by refine Iff.trans ?_ isRegular_mul_and_mul_iff exact ⟨fun ab => ⟨ab, by rwa [mul_comm]⟩, fun rab => rab.1⟩ end CommSemigroup section Monoid variable [Monoid R] {a b : R} {n : ℕ} /-- An element admitting a left inverse is left-regular. -/ @[to_additive /-- An element admitting a left additive opposite is add-left-regular. -/] theorem isLeftRegular_of_mul_eq_one (h : b * a = 1) : IsLeftRegular a := IsLeftRegular.of_mul (a := b) (by rw [h]; exact isRegular_one.left) /-- An element admitting a right inverse is right-regular. -/ @[to_additive /-- An element admitting a right additive opposite is add-right-regular. -/] theorem isRightRegular_of_mul_eq_one (h : a * b = 1) : IsRightRegular a := IsRightRegular.of_mul (a := b) (by rw [h]; exact isRegular_one.right) /-- If `R` is a monoid, an element in `Rˣ` is regular. -/ @[to_additive /-- If `R` is an additive monoid, an element in `add_units R` is add-regular. -/] theorem Units.isRegular (a : Rˣ) : IsRegular (a : R) := ⟨isLeftRegular_of_mul_eq_one a.inv_mul, isRightRegular_of_mul_eq_one a.mul_inv⟩ /-- A unit in a monoid is regular. -/ @[to_additive /-- An additive unit in an additive monoid is add-regular. -/] theorem IsUnit.isRegular (ua : IsUnit a) : IsRegular a := by rcases ua with ⟨a, rfl⟩ exact Units.isRegular a /-- Any power of a left-regular element is left-regular. -/ @[to_additive] lemma IsLeftRegular.pow (n : ℕ) (rla : IsLeftRegular a) : IsLeftRegular (a ^ n) := by simp only [IsLeftRegular, ← mul_left_iterate, rla.iterate n] /-- Any power of a right-regular element is right-regular. -/ @[to_additive] lemma IsRightRegular.pow (n : ℕ) (rra : IsRightRegular a) : IsRightRegular (a ^ n) := by rw [IsRightRegular, ← mul_right_iterate] exact rra.iterate n /-- Any power of a regular element is regular. -/ @[to_additive] lemma IsRegular.pow (n : ℕ) (ra : IsRegular a) : IsRegular (a ^ n) := ⟨IsLeftRegular.pow n ra.left, IsRightRegular.pow n ra.right⟩ /-- An element `a` is left-regular if and only if a positive power of `a` is left-regular. -/ @[to_additive] lemma IsLeftRegular.pow_iff (n0 : 0 < n) : IsLeftRegular (a ^ n) ↔ IsLeftRegular a where mp := by rw [← Nat.succ_pred_eq_of_pos n0, pow_succ]; exact .of_mul mpr := .pow n /-- An element `a` is right-regular if and only if a positive power of `a` is right-regular. -/ @[to_additive] lemma IsRightRegular.pow_iff (n0 : 0 < n) : IsRightRegular (a ^ n) ↔ IsRightRegular a where mp := by rw [← Nat.succ_pred_eq_of_pos n0, pow_succ']; exact .of_mul mpr := .pow n /-- An element `a` is regular if and only if a positive power of `a` is regular. -/ @[to_additive] lemma IsRegular.pow_iff {n : ℕ} (n0 : 0 < n) : IsRegular (a ^ n) ↔ IsRegular a where mp h := ⟨(IsLeftRegular.pow_iff n0).mp h.left, (IsRightRegular.pow_iff n0).mp h.right⟩ mpr h := ⟨.pow n h.left, .pow n h.right⟩ end Monoid
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.
Restrict.lean
/- Copyright (c) 2025 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import Mathlib.LinearAlgebra.PerfectPairing.Basic import Mathlib.LinearAlgebra.Matrix.Basis import Mathlib.LinearAlgebra.Matrix.BaseChange /-! # Restriction to submodules and restriction of scalars for perfect pairings. We provide API for restricting perfect pairings to submodules and for restricting their scalars. ## Main definitions * `PerfectPairing.restrict`: restriction of a perfect pairing to submodules. * `PerfectPairing.restrictScalars`: restriction of scalars for a perfect pairing taking values in a subring. * `PerfectPairing.restrictScalarsField`: simultaneously restrict both the domains and scalars of a perfect pairing with coefficients in a field. -/ open Function Module Set open Submodule (span subset_span) noncomputable section namespace PerfectPairing section CommRing variable {R M N : Type*} [CommRing R] [AddCommGroup M] [Module R M] [AddCommGroup N] [Module R N] (p : PerfectPairing R M N) section Restrict variable {M' N' : Type*} [AddCommGroup M'] [Module R M'] [AddCommGroup N'] [Module R N'] (i : M' →ₗ[R] M) (j : N' →ₗ[R] N) (hi : Injective i) (hj : Injective j) (hij : p.IsPerfectCompl (LinearMap.range i) (LinearMap.range j)) include hi hj hij private lemma restrict_aux : Bijective (p.toLinearMap.compl₁₂ i j) := by refine ⟨LinearMap.ker_eq_bot.mp <| eq_bot_iff.mpr fun m hm ↦ ?_, fun f ↦ ?_⟩ · replace hm : i m ∈ (LinearMap.range j).dualAnnihilator.map p.toDualLeft.symm := by simp only [Submodule.mem_map, Submodule.mem_dualAnnihilator] refine ⟨p.toDualLeft (i m), ?_, LinearEquiv.symm_apply_apply _ _⟩ rintro - ⟨n, rfl⟩ simpa using LinearMap.congr_fun hm n suffices i m ∈ (⊥ : Submodule R M) by simpa [hi] using this simpa only [← hij.isCompl_left.inf_eq_bot, Submodule.mem_inf] using ⟨LinearMap.mem_range_self i m, hm⟩ · set F : Module.Dual R N := f ∘ₗ j.linearProjOfIsCompl _ hj hij.isCompl_right with hF have hF (n : N') : F (j n) = f n := by simp [hF] set m : M := p.toDualLeft.symm F with hm obtain ⟨-, y, ⟨m₀, rfl⟩, hy, hm'⟩ := Submodule.codisjoint_iff_exists_add_eq.mp hij.isCompl_left.codisjoint m refine ⟨m₀, LinearMap.ext fun n ↦ ?_⟩ replace hy : (p y) (j n) = 0 := by simp only [Submodule.mem_map, Submodule.mem_dualAnnihilator] at hy obtain ⟨g, hg, rfl⟩ := hy simpa only [apply_toDualLeft_symm_apply] using hg _ (LinearMap.mem_range_self j n) rw [hm, ← LinearEquiv.symm_apply_eq, map_add, LinearEquiv.symm_symm, toDualLeft_apply] at hm' simpa [← hF, ← LinearMap.congr_fun hm' (j n)] /-- The restriction of a perfect pairing to submodules (expressed as injections to provide definitional control). -/ @[simps!] def restrict : PerfectPairing R M' N' where toLinearMap := p.toLinearMap.compl₁₂ i j bijective_left := p.restrict_aux i j hi hj hij bijective_right := p.flip.restrict_aux j i hj hi hij.flip @[simp] lemma restrict_apply_apply (x : M') (y : N') : p.restrict i j hi hj hij x y = p (i x) (j y) := rfl end Restrict section RestrictScalars variable {S M' N' : Type*} [CommRing S] [Algebra S R] [Module S M] [Module S N] [IsScalarTower S R M] [IsScalarTower S R N] [NoZeroSMulDivisors S R] [Nontrivial R] [AddCommGroup M'] [Module S M'] [AddCommGroup N'] [Module S N'] (i : M' →ₗ[S] M) (j : N' →ₗ[S] N) /-- An auxiliary definition used to construct `PerfectPairing.restrictScalars`. -/ private def restrictScalarsAux (hp : ∀ m n, p (i m) (j n) ∈ (algebraMap S R).range) : M' →ₗ[S] N' →ₗ[S] S := LinearMap.restrictScalarsRange₂ i j (Algebra.linearMap S R) (FaithfulSMul.algebraMap_injective S R) p.toLinearMap hp private lemma restrictScalarsAux_injective (hi : Injective i) (hN : span R (LinearMap.range j : Set N) = ⊤) (hp : ∀ m n, p (i m) (j n) ∈ (algebraMap S R).range) : Injective (p.restrictScalarsAux i j hp) := by let f := LinearMap.restrictScalarsRange₂ i j (Algebra.linearMap S R) (FaithfulSMul.algebraMap_injective S R) p.toLinearMap hp rw [← LinearMap.ker_eq_bot] refine (Submodule.eq_bot_iff _).mpr fun x (hx : f x = 0) ↦ ?_ replace hx (n : N) : p (i x) n = 0 := by have hn : n ∈ span R (LinearMap.range j : Set N) := hN ▸ Submodule.mem_top induction hn using Submodule.span_induction with | mem z hz => obtain ⟨n', rfl⟩ := hz simpa [f] using LinearMap.congr_fun hx n' | zero => simp | add => rw [← p.toLinearMap_apply, map_add]; aesop | smul => rw [← p.toLinearMap_apply, map_smul]; aesop rw [← i.map_eq_zero_iff hi, ← p.toLinearMap.map_eq_zero_iff p.bijective_left.injective] ext n simpa using hx n private lemma restrictScalarsAux_surjective (h : ∀ g : Module.Dual S N', ∃ m, (p.toDualLeft (i m)).restrictScalars S ∘ₗ j = Algebra.linearMap S R ∘ₗ g) (hp : ∀ m n, p (i m) (j n) ∈ (algebraMap S R).range) : Surjective (p.restrictScalarsAux i j hp) := by rw [← LinearMap.range_eq_top] refine Submodule.eq_top_iff'.mpr fun g : Module.Dual S N' ↦ ?_ obtain ⟨m, hm⟩ := h g refine ⟨m, ?_⟩ ext n apply FaithfulSMul.algebraMap_injective S R change Algebra.linearMap S R _ = _ simpa [restrictScalarsAux] using LinearMap.congr_fun hm n /-- Restriction of scalars for a perfect pairing taking values in a subring. -/ def restrictScalars (hi : Injective i) (hj : Injective j) (hM : span R (LinearMap.range i : Set M) = ⊤) (hN : span R (LinearMap.range j : Set N) = ⊤) (h₁ : ∀ g : Module.Dual S N', ∃ m, (p.toDualLeft (i m)).restrictScalars S ∘ₗ j = Algebra.linearMap S R ∘ₗ g) (h₂ : ∀ g : Module.Dual S M', ∃ n, (p.toDualRight (j n)).restrictScalars S ∘ₗ i = Algebra.linearMap S R ∘ₗ g) (hp : ∀ m n, p (i m) (j n) ∈ (algebraMap S R).range) : PerfectPairing S M' N' := { toLinearMap := p.restrictScalarsAux i j hp bijective_left := ⟨p.restrictScalarsAux_injective i j hi hN hp, p.restrictScalarsAux_surjective i j h₁ hp⟩ bijective_right := ⟨p.flip.restrictScalarsAux_injective j i hj hM (fun m n ↦ hp n m), p.flip.restrictScalarsAux_surjective j i h₂ (fun m n ↦ hp n m)⟩} end RestrictScalars end CommRing section Field variable {K L M N : Type*} [Field K] [Field L] [Algebra K L] [AddCommGroup M] [AddCommGroup N] [Module L M] [Module L N] [Module K M] [Module K N] [IsScalarTower K L M] (p : PerfectPairing L M N) /-- If a perfect pairing over a field `L` takes values in a subfield `K` along two `K`-subspaces whose `L` span is full, then these subspaces induce a `K`-structure in the sense of [*Algebra I*, Bourbaki : Chapter II, §8.1 Definition 1][bourbaki1989]. -/ lemma exists_basis_basis_of_span_eq_top_of_mem_algebraMap (M' : Submodule K M) (N' : Submodule K N) (hM : span L (M' : Set M) = ⊤) (hN : span L (N' : Set N) = ⊤) (hp : ∀ᵉ (x ∈ M') (y ∈ N'), p x y ∈ (algebraMap K L).range) : ∃ (n : ℕ) (b : Basis (Fin n) L M) (b' : Basis (Fin n) K M'), ∀ i, b i = b' i := by classical have : IsReflexive L M := p.reflexive_left have : IsReflexive L N := p.reflexive_right obtain ⟨v, hv₁, hv₂, hv₃⟩ := exists_linearIndependent L (M' : Set M) rw [hM] at hv₂ let b : Basis _ L M := Basis.mk hv₃ <| by rw [← hv₂, Subtype.range_coe_subtype, Set.setOf_mem_eq] have : Fintype v := Set.Finite.fintype <| Module.Finite.finite_basis b set v' : v → M' := fun i ↦ ⟨i, hv₁ (Subtype.coe_prop i)⟩ have hv' : LinearIndependent K v' := by replace hv₃ := hv₃.restrict_scalars (R := K) <| by simp_rw [← Algebra.algebraMap_eq_smul_one] exact FaithfulSMul.algebraMap_injective K L rw [show ((↑) : v → M) = M'.subtype ∘ v' by ext; simp [v']] at hv₃ exact hv₃.of_comp suffices span K (Set.range v') = ⊤ by let e := (Module.Finite.finite_basis b).equivFin let b' : Basis _ K M' := Basis.mk hv' (by rw [this]) exact ⟨_, b.reindex e, b'.reindex e, fun i ↦ by simp [b, b', v']⟩ suffices span K v = M' by apply Submodule.map_injective_of_injective M'.injective_subtype rw [Submodule.map_span, ← Set.image_univ, Set.image_image] simpa [v'] refine le_antisymm (Submodule.span_le.mpr hv₁) fun m hm ↦ ?_ obtain ⟨w, hw₁, hw₂, hw₃⟩ := exists_linearIndependent L (N' : Set N) rw [hN] at hw₂ let bN : Basis _ L N := Basis.mk hw₃ <| by rw [← hw₂, Subtype.range_coe_subtype, Set.setOf_mem_eq] have : Fintype w := Set.Finite.fintype <| Module.Finite.finite_basis bN have e : v ≃ w := Fintype.equivOfCardEq <| by rw [← Module.finrank_eq_card_basis b, ← Module.finrank_eq_card_basis bN, p.finrank_eq] let bM := bN.dualBasis.map p.toDualLeft.symm have hbM (j : w) (x : M) (hx : x ∈ M') : bM.repr x j = p x (j : N) := by simp [bM, bN] have hj (j : w) : bM.repr m j ∈ (algebraMap K L).range := (hbM _ _ hm) ▸ hp m hm j (hw₁ j.2) replace hp (i : w) (j : v) : (bN.dualBasis.map p.toDualLeft.symm).toMatrix b i j ∈ (algebraMap K L).fieldRange := by simp only [Basis.toMatrix, Basis.map_repr, LinearEquiv.symm_symm, LinearEquiv.trans_apply, toDualLeft_apply, Basis.dualBasis_repr] exact hp (b j) (by simpa [b] using hv₁ j.2) (bN i) (by simpa [bN] using hw₁ i.2) have hA (i j) : b.toMatrix bM i j ∈ (algebraMap K L).range := Matrix.mem_subfield_of_mul_eq_one_of_mem_subfield_left e _ (by simp [bM]) hp i j have h_span : span K v = span K (Set.range b) := by simp [b] rw [h_span, Basis.mem_span_iff_repr_mem, ← Basis.toMatrix_mulVec_repr bM b m] exact fun i ↦ Subring.sum_mem _ fun j _ ↦ Subring.mul_mem _ (hA i j) (hj j) variable {M' N' : Type*} [AddCommGroup M'] [AddCommGroup N'] [Module K M'] [Module K N'] [IsScalarTower K L N] (i : M' →ₗ[K] M) (j : N' →ₗ[K] N) (hi : Injective i) (hj : Injective j) /-- An auxiliary definition used only to simplify the construction of the more general definition `PerfectPairing.restrictScalarsField`. -/ private def restrictScalarsFieldAux (hM : span L (LinearMap.range i : Set M) = ⊤) (hN : span L (LinearMap.range j : Set N) = ⊤) (hp : ∀ m n, p (i m) (j n) ∈ (algebraMap K L).range) : PerfectPairing K M' N' := by suffices FiniteDimensional K M' from mkOfInjective _ (p.restrictScalarsAux_injective i j hi hN hp) (p.flip.restrictScalarsAux_injective j i hj hM (fun m n ↦ hp n m)) obtain ⟨n, -, b', -⟩ := p.exists_basis_basis_of_span_eq_top_of_mem_algebraMap _ _ hM hN <| by rintro - ⟨m, rfl⟩ - ⟨n, rfl⟩ exact hp m n have : FiniteDimensional K (LinearMap.range i) := FiniteDimensional.of_fintype_basis b' exact Finite.equiv (LinearEquiv.ofInjective i hi).symm /-- Simultaneously restrict both the domains and scalars of a perfect pairing with coefficients in a field. -/ def restrictScalarsField (hij : p.IsPerfectCompl (span L <| LinearMap.range i) (span L <| LinearMap.range j)) (hp : ∀ m n, p (i m) (j n) ∈ (algebraMap K L).range) : PerfectPairing K M' N' := by letI P : PerfectPairing L (span L <| LinearMap.range i) (span L <| LinearMap.range j) := p.restrict (Submodule.subtype _) (Submodule.subtype _) (by simp) (by simp) (by simpa) exact P.restrictScalarsFieldAux ((LinearMap.range i).inclusionSpan L ∘ₗ i.rangeRestrict) ((LinearMap.range j).inclusionSpan L ∘ₗ j.rangeRestrict) (((LinearMap.range i).injective_inclusionSpan L).comp (by simpa)) (((LinearMap.range j).injective_inclusionSpan L).comp (by simpa)) (by rw [LinearMap.range_comp_of_range_eq_top _ (LinearMap.range_rangeRestrict _)] exact (LinearMap.range i).span_range_inclusionSpan L) (by rw [LinearMap.range_comp_of_range_eq_top _ (LinearMap.range_rangeRestrict _)] exact (LinearMap.range j).span_range_inclusionSpan L) (fun x y ↦ LinearMap.BilinMap.apply_apply_mem_of_mem_span (LinearMap.range <| Algebra.linearMap K L) (range i) (range j) ((LinearMap.restrictScalarsₗ K L _ _ _).comp (p.toLinearMap.restrictScalars K)) (by simpa) (i x) (j y) (subset_span (mem_range_self x)) (subset_span (mem_range_self y))) @[simp] lemma restrictScalarsField_apply_apply (hij : p.IsPerfectCompl (span L <| LinearMap.range i) (span L <| LinearMap.range j)) (hp : ∀ m n, p (i m) (j n) ∈ (algebraMap K L).range) (x : M') (y : N') : algebraMap K L (p.restrictScalarsField i j hi hj hij hp x y) = p (i x) (j y) := LinearMap.restrictScalarsRange₂_apply i j (Algebra.linearMap K L) (FaithfulSMul.algebraMap_injective K L) p.toLinearMap hp x y end Field end PerfectPairing
Uniform.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.Analysis.Convex.StrictConvexSpace /-! # Uniformly convex spaces This file defines uniformly convex spaces, which are real normed vector spaces in which for all strictly positive `ε`, there exists some strictly positive `δ` such that `ε ≤ ‖x - y‖` implies `‖x + y‖ ≤ 2 - δ` for all `x` and `y` of norm at most than `1`. This means that the triangle inequality is strict with a uniform bound, as opposed to strictly convex spaces where the triangle inequality is strict but not necessarily uniformly (`‖x + y‖ < ‖x‖ + ‖y‖` for all `x` and `y` not in the same ray). ## Main declarations `UniformConvexSpace E` means that `E` is a uniformly convex space. ## TODO * Milman-Pettis * Hanner's inequalities ## Tags convex, uniformly convex -/ open Set Metric open Convex Pointwise /-- A *uniformly convex space* is a real normed space where the triangle inequality is strict with a uniform bound. Namely, over the `x` and `y` of norm `1`, `‖x + y‖` is uniformly bounded above by a constant `< 2` when `‖x - y‖` is uniformly bounded below by a positive constant. -/ class UniformConvexSpace (E : Type*) [SeminormedAddCommGroup E] : Prop where uniform_convex : ∀ ⦃ε : ℝ⦄, 0 < ε → ∃ δ, 0 < δ ∧ ∀ ⦃x : E⦄, ‖x‖ = 1 → ∀ ⦃y⦄, ‖y‖ = 1 → ε ≤ ‖x - y‖ → ‖x + y‖ ≤ 2 - δ variable {E : Type*} section SeminormedAddCommGroup variable (E) [SeminormedAddCommGroup E] [UniformConvexSpace E] {ε : ℝ} theorem exists_forall_sphere_dist_add_le_two_sub (hε : 0 < ε) : ∃ δ, 0 < δ ∧ ∀ ⦃x : E⦄, ‖x‖ = 1 → ∀ ⦃y⦄, ‖y‖ = 1 → ε ≤ ‖x - y‖ → ‖x + y‖ ≤ 2 - δ := UniformConvexSpace.uniform_convex hε variable [NormedSpace ℝ E] theorem exists_forall_closed_ball_dist_add_le_two_sub (hε : 0 < ε) : ∃ δ, 0 < δ ∧ ∀ ⦃x : E⦄, ‖x‖ ≤ 1 → ∀ ⦃y⦄, ‖y‖ ≤ 1 → ε ≤ ‖x - y‖ → ‖x + y‖ ≤ 2 - δ := by have hε' : 0 < ε / 3 := div_pos hε zero_lt_three obtain ⟨δ, hδ, h⟩ := exists_forall_sphere_dist_add_le_two_sub E hε' set δ' := min (1 / 2) (min (ε / 3) <| δ / 3) refine ⟨δ', lt_min one_half_pos <| lt_min hε' (div_pos hδ zero_lt_three), fun x hx y hy hxy => ?_⟩ obtain hx' | hx' := le_or_gt ‖x‖ (1 - δ') · rw [← one_add_one_eq_two] exact (norm_add_le_of_le hx' hy).trans (sub_add_eq_add_sub _ _ _).le obtain hy' | hy' := le_or_gt ‖y‖ (1 - δ') · rw [← one_add_one_eq_two] exact (norm_add_le_of_le hx hy').trans (add_sub_assoc _ _ _).ge have hδ' : 0 < 1 - δ' := sub_pos_of_lt (min_lt_of_left_lt one_half_lt_one) have h₁ : ∀ z : E, 1 - δ' < ‖z‖ → ‖‖z‖⁻¹ • z‖ = 1 := by rintro z hz rw [norm_smul_of_nonneg (inv_nonneg.2 <| norm_nonneg _), inv_mul_cancel₀ (hδ'.trans hz).ne'] have h₂ : ∀ z : E, ‖z‖ ≤ 1 → 1 - δ' ≤ ‖z‖ → ‖‖z‖⁻¹ • z - z‖ ≤ δ' := by rintro z hz hδz nth_rw 3 [← one_smul ℝ z] rwa [← sub_smul, norm_smul_of_nonneg (sub_nonneg_of_le <| (one_le_inv₀ (hδ'.trans_le hδz)).2 hz), sub_mul, inv_mul_cancel₀ (hδ'.trans_le hδz).ne', one_mul, sub_le_comm] set x' := ‖x‖⁻¹ • x set y' := ‖y‖⁻¹ • y have hxy' : ε / 3 ≤ ‖x' - y'‖ := calc ε / 3 = ε - (ε / 3 + ε / 3) := by ring _ ≤ ‖x - y‖ - (‖x' - x‖ + ‖y' - y‖) := by gcongr · exact (h₂ _ hx hx'.le).trans <| min_le_of_right_le <| min_le_left _ _ · exact (h₂ _ hy hy'.le).trans <| min_le_of_right_le <| min_le_left _ _ _ ≤ _ := by have : ∀ x' y', x - y = x' - y' + (x - x') + (y' - y) := fun _ _ => by abel rw [sub_le_iff_le_add, norm_sub_rev _ x, ← add_assoc, this] exact norm_add₃_le calc ‖x + y‖ ≤ ‖x' + y'‖ + ‖x' - x‖ + ‖y' - y‖ := by have : ∀ x' y', x + y = x' + y' + (x - x') + (y - y') := fun _ _ => by abel rw [norm_sub_rev, norm_sub_rev y', this] exact norm_add₃_le _ ≤ 2 - δ + δ' + δ' := by gcongr exacts [h (h₁ _ hx') (h₁ _ hy') hxy', h₂ _ hx hx'.le, h₂ _ hy hy'.le] _ ≤ 2 - δ' := by suffices δ' ≤ δ / 3 by linarith exact min_le_of_right_le <| min_le_right _ _ theorem exists_forall_closed_ball_dist_add_le_two_mul_sub (hε : 0 < ε) (r : ℝ) : ∃ δ, 0 < δ ∧ ∀ ⦃x : E⦄, ‖x‖ ≤ r → ∀ ⦃y⦄, ‖y‖ ≤ r → ε ≤ ‖x - y‖ → ‖x + y‖ ≤ 2 * r - δ := by obtain hr | hr := le_or_gt r 0 · exact ⟨1, one_pos, fun x hx y hy h => (hε.not_ge <| h.trans <| (norm_sub_le _ _).trans <| add_nonpos (hx.trans hr) (hy.trans hr)).elim⟩ obtain ⟨δ, hδ, h⟩ := exists_forall_closed_ball_dist_add_le_two_sub E (div_pos hε hr) refine ⟨δ * r, mul_pos hδ hr, fun x hx y hy hxy => ?_⟩ rw [← div_le_one hr, div_eq_inv_mul, ← norm_smul_of_nonneg (inv_nonneg.2 hr.le)] at hx hy have := h hx hy simp_rw [← smul_add, ← smul_sub, norm_smul_of_nonneg (inv_nonneg.2 hr.le), ← div_eq_inv_mul, div_le_div_iff_of_pos_right hr, div_le_iff₀ hr, sub_mul] at this exact this hxy end SeminormedAddCommGroup variable [NormedAddCommGroup E] [NormedSpace ℝ E] [UniformConvexSpace E] -- See note [lower instance priority] instance (priority := 100) UniformConvexSpace.toStrictConvexSpace : StrictConvexSpace ℝ E := StrictConvexSpace.of_norm_add_ne_two fun _ _ hx hy hxy => let ⟨_, hδ, h⟩ := exists_forall_closed_ball_dist_add_le_two_sub E (norm_sub_pos_iff.2 hxy) ((h hx.le hy.le le_rfl).trans_lt <| sub_lt_self _ hδ).ne
NatAntidiagonal.lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Algebra.BigOperators.Fin import Mathlib.Algebra.Group.Fin.Tuple import Mathlib.Data.Finset.NatAntidiagonal import Mathlib.Order.Fin.Tuple /-! # Collections of tuples of naturals with the same sum This file generalizes `List.Nat.Antidiagonal n`, `Multiset.Nat.Antidiagonal n`, and `Finset.Nat.Antidiagonal n` from the pair of elements `x : ℕ × ℕ` such that `n = x.1 + x.2`, to the sequence of elements `x : Fin k → ℕ` such that `n = ∑ i, x i`. ## Main definitions * `List.Nat.antidiagonalTuple` * `Multiset.Nat.antidiagonalTuple` * `Finset.Nat.antidiagonalTuple` ## Main results * `antidiagonalTuple 2 n` is analogous to `antidiagonal n`: * `List.Nat.antidiagonalTuple_two` * `Multiset.Nat.antidiagonalTuple_two` * `Finset.Nat.antidiagonalTuple_two` ## Implementation notes While we could implement this by filtering `(Fintype.PiFinset fun _ ↦ range (n + 1))` or similar, this implementation would be much slower. In the future, we could consider generalizing `Finset.Nat.antidiagonalTuple` further to support finitely-supported functions, as is done with `cut` in `archive/100-theorems-list/45_partition.lean`. -/ /-! ### Lists -/ namespace List.Nat /-- `List.antidiagonalTuple k n` is a list of all `k`-tuples which sum to `n`. This list contains no duplicates (`List.Nat.nodup_antidiagonalTuple`), and is sorted lexicographically (`List.Nat.antidiagonalTuple_pairwise_pi_lex`), starting with `![0, ..., n]` and ending with `![n, ..., 0]`. ``` #eval antidiagonalTuple 3 2 -- [![0, 0, 2], ![0, 1, 1], ![0, 2, 0], ![1, 0, 1], ![1, 1, 0], ![2, 0, 0]] ``` -/ def antidiagonalTuple : ∀ k, ℕ → List (Fin k → ℕ) | 0, 0 => [![]] | 0, _ + 1 => [] | k + 1, n => (List.Nat.antidiagonal n).flatMap fun ni => (antidiagonalTuple k ni.2).map fun x => Fin.cons ni.1 x @[simp] theorem antidiagonalTuple_zero_zero : antidiagonalTuple 0 0 = [![]] := rfl @[simp] theorem antidiagonalTuple_zero_succ (n : ℕ) : antidiagonalTuple 0 (n + 1) = [] := rfl theorem mem_antidiagonalTuple {n : ℕ} {k : ℕ} {x : Fin k → ℕ} : x ∈ antidiagonalTuple k n ↔ ∑ i, x i = n := by induction x using Fin.consInduction generalizing n with | h0 => cases n · decide · simp | h x₀ x ih => simp_rw [Fin.sum_cons, antidiagonalTuple, List.mem_flatMap, List.mem_map, List.Nat.mem_antidiagonal, Fin.cons_inj, exists_eq_right_right, ih, @eq_comm _ _ (Prod.snd _), and_comm (a := Prod.snd _ = _), ← Prod.mk_inj (a₁ := Prod.fst _), exists_eq_right] /-- The antidiagonal of `n` does not contain duplicate entries. -/ theorem nodup_antidiagonalTuple (k n : ℕ) : List.Nodup (antidiagonalTuple k n) := by induction' k with k ih generalizing n · cases n · simp · simp simp_rw [antidiagonalTuple, List.nodup_flatMap] constructor · intro i _ exact (ih i.snd).map (Fin.cons_right_injective (α := fun _ => ℕ) i.fst) induction' n with n n_ih · exact List.pairwise_singleton _ _ · rw [List.Nat.antidiagonal_succ] refine List.Pairwise.cons (fun a ha x hx₁ hx₂ => ?_) (n_ih.map _ fun a b h x hx₁ hx₂ => ?_) · rw [List.mem_map] at hx₁ hx₂ ha obtain ⟨⟨a, -, rfl⟩, ⟨x₁, -, rfl⟩, ⟨x₂, -, h⟩⟩ := ha, hx₁, hx₂ rw [Fin.cons_inj] at h injection h.1 · rw [List.mem_map] at hx₁ hx₂ obtain ⟨⟨x₁, hx₁, rfl⟩, ⟨x₂, hx₂, h₁₂⟩⟩ := hx₁, hx₂ dsimp at h₁₂ rw [Fin.cons_inj, Nat.succ_inj] at h₁₂ obtain ⟨h₁₂, rfl⟩ := h₁₂ rw [Function.onFun, h₁₂] at h exact h (List.mem_map_of_mem hx₁) (List.mem_map_of_mem hx₂) theorem antidiagonalTuple_zero_right : ∀ k, antidiagonalTuple k 0 = [0] | 0 => (congr_arg fun x => [x]) <| Subsingleton.elim _ _ | k + 1 => by rw [antidiagonalTuple, antidiagonal_zero, List.flatMap_singleton, antidiagonalTuple_zero_right k, List.map_singleton] exact congr_arg (fun x => [x]) Matrix.cons_zero_zero @[simp] theorem antidiagonalTuple_one (n : ℕ) : antidiagonalTuple 1 n = [![n]] := by simp_rw [antidiagonalTuple, antidiagonal, List.range_succ, List.map_append, List.map_singleton, Nat.sub_self, List.flatMap_append, List.flatMap_singleton, List.flatMap_map] conv_rhs => rw [← List.nil_append [![n]]] congr 1 simp_rw [List.flatMap_eq_nil_iff, List.mem_range, List.map_eq_nil_iff] intro x hx obtain ⟨m, rfl⟩ := Nat.exists_eq_add_of_lt hx rw [add_assoc, add_tsub_cancel_left, antidiagonalTuple_zero_succ] theorem antidiagonalTuple_two (n : ℕ) : antidiagonalTuple 2 n = (antidiagonal n).map fun i => ![i.1, i.2] := by rw [antidiagonalTuple] simp_rw [antidiagonalTuple_one, List.map_singleton] rw [List.map_eq_flatMap] rfl theorem antidiagonalTuple_pairwise_pi_lex : ∀ k n, (antidiagonalTuple k n).Pairwise (Pi.Lex (· < ·) @fun _ => (· < ·)) | 0, 0 => List.pairwise_singleton _ _ | 0, _ + 1 => List.Pairwise.nil | k + 1, n => by simp_rw [antidiagonalTuple, List.pairwise_flatMap, List.pairwise_map, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] simp only [mem_antidiagonal, Prod.forall] simp only [Fin.pi_lex_lt_cons_cons, true_and, lt_self_iff_false, false_or] refine ⟨fun _ _ _ => antidiagonalTuple_pairwise_pi_lex k _, ?_⟩ induction' n with n n_ih · rw [antidiagonal_zero] exact List.pairwise_singleton _ _ · rw [antidiagonal_succ, List.pairwise_cons, List.pairwise_map] refine ⟨fun p hp x hx y hy => ?_, ?_⟩ · rw [List.mem_map, Prod.exists] at hp obtain ⟨a, b, _, rfl : (Nat.succ a, b) = p⟩ := hp exact Or.inl (Nat.zero_lt_succ _) dsimp simp_rw [Nat.succ_inj, Nat.succ_lt_succ_iff] exact n_ih end List.Nat /-! ### Multisets -/ namespace Multiset.Nat /-- `Multiset.Nat.antidiagonalTuple k n` is a multiset of `k`-tuples summing to `n` -/ def antidiagonalTuple (k n : ℕ) : Multiset (Fin k → ℕ) := List.Nat.antidiagonalTuple k n @[simp] theorem antidiagonalTuple_zero_zero : antidiagonalTuple 0 0 = {![]} := rfl @[simp] theorem antidiagonalTuple_zero_succ (n : ℕ) : antidiagonalTuple 0 n.succ = 0 := rfl theorem mem_antidiagonalTuple {n : ℕ} {k : ℕ} {x : Fin k → ℕ} : x ∈ antidiagonalTuple k n ↔ ∑ i, x i = n := List.Nat.mem_antidiagonalTuple theorem nodup_antidiagonalTuple (k n : ℕ) : (antidiagonalTuple k n).Nodup := List.Nat.nodup_antidiagonalTuple _ _ theorem antidiagonalTuple_zero_right (k : ℕ) : antidiagonalTuple k 0 = {0} := congr_arg _ (List.Nat.antidiagonalTuple_zero_right k) @[simp] theorem antidiagonalTuple_one (n : ℕ) : antidiagonalTuple 1 n = {![n]} := congr_arg _ (List.Nat.antidiagonalTuple_one n) theorem antidiagonalTuple_two (n : ℕ) : antidiagonalTuple 2 n = (antidiagonal n).map fun i => ![i.1, i.2] := congr_arg _ (List.Nat.antidiagonalTuple_two n) end Multiset.Nat /-! ### Finsets -/ namespace Finset.Nat /-- `Finset.Nat.antidiagonalTuple k n` is a finset of `k`-tuples summing to `n` -/ def antidiagonalTuple (k n : ℕ) : Finset (Fin k → ℕ) := ⟨Multiset.Nat.antidiagonalTuple k n, Multiset.Nat.nodup_antidiagonalTuple k n⟩ @[simp] theorem antidiagonalTuple_zero_zero : antidiagonalTuple 0 0 = {![]} := rfl @[simp] theorem antidiagonalTuple_zero_succ (n : ℕ) : antidiagonalTuple 0 n.succ = ∅ := rfl theorem mem_antidiagonalTuple {n : ℕ} {k : ℕ} {x : Fin k → ℕ} : x ∈ antidiagonalTuple k n ↔ ∑ i, x i = n := List.Nat.mem_antidiagonalTuple theorem antidiagonalTuple_zero_right (k : ℕ) : antidiagonalTuple k 0 = {0} := Finset.eq_of_veq (Multiset.Nat.antidiagonalTuple_zero_right k) @[simp] theorem antidiagonalTuple_one (n : ℕ) : antidiagonalTuple 1 n = {![n]} := Finset.eq_of_veq (Multiset.Nat.antidiagonalTuple_one n) theorem antidiagonalTuple_two (n : ℕ) : antidiagonalTuple 2 n = (antidiagonal n).map (piFinTwoEquiv fun _ => ℕ).symm.toEmbedding := Finset.eq_of_veq (Multiset.Nat.antidiagonalTuple_two n) section EquivProd /-- The disjoint union of antidiagonal tuples `Σ n, antidiagonalTuple k n` is equivalent to the `k`-tuple `Fin k → ℕ`. This is such an equivalence, obtained by mapping `(n, x)` to `x`. This is the tuple version of `Finset.sigmaAntidiagonalEquivProd`. -/ @[simps] def sigmaAntidiagonalTupleEquivTuple (k : ℕ) : (Σ n, antidiagonalTuple k n) ≃ (Fin k → ℕ) where toFun x := x.2 invFun x := ⟨∑ i, x i, x, mem_antidiagonalTuple.mpr rfl⟩ left_inv := fun ⟨_, _, h⟩ => Sigma.subtype_ext (mem_antidiagonalTuple.mp h) rfl end EquivProd end Finset.Nat
Basic.lean
/- Copyright (c) 2022 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import Mathlib.Algebra.GroupWithZero.Units.Lemmas import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Algebra.Order.Ring.Cast import Mathlib.Data.Fintype.BigOperators import Mathlib.Data.Sign.Defs /-! # Sign function This file defines the sign function for types with zero and a decidable less-than relation, and proves some basic theorems about it. -/ universe u variable {α : Type u} namespace SignType /-- Casting `SignType → ℤ → α` is the same as casting directly `SignType → α`. -/ @[simp, norm_cast] lemma intCast_cast {α : Type*} [AddGroupWithOne α] (s : SignType) : ((s : ℤ) : α) = s := map_cast' _ Int.cast_one Int.cast_zero (@Int.cast_one α _ ▸ Int.cast_neg 1) _ theorem pow_odd (s : SignType) {n : ℕ} (hn : Odd n) : s ^ n = s := by obtain ⟨k, rfl⟩ := hn rw [pow_add, pow_one, pow_mul, sq] cases s <;> simp theorem zpow_odd (s : SignType) {z : ℤ} (hz : Odd z) : s ^ z = s := by obtain rfl | hs := eq_or_ne s 0 · rw [zero_zpow] rintro rfl simp at hz obtain ⟨k, rfl⟩ := hz rw [zpow_add₀ hs, zpow_one, zpow_mul, zpow_two] cases s <;> simp lemma pow_even (s : SignType) {n : ℕ} (hn : Even n) (hs : s ≠ 0) : s ^ n = 1 := by cases s <;> simp_all lemma zpow_even (s : SignType) {z : ℤ} (hz : Even z) (hs : s ≠ 0) : s ^ z = 1 := by cases s <;> simp_all [Even.neg_one_zpow] /-- `SignType.cast` as a `MulWithZeroHom`. -/ @[simps] def castHom {α} [MulZeroOneClass α] [HasDistribNeg α] : SignType →*₀ α where toFun := cast map_zero' := rfl map_one' := rfl map_mul' x y := by cases x <;> cases y <;> simp [zero_eq_zero, pos_eq_one, neg_eq_neg_one] theorem univ_eq : (Finset.univ : Finset SignType) = {0, -1, 1} := by decide theorem range_eq {α} (f : SignType → α) : Set.range f = {f zero, f neg, f pos} := by classical rw [← Fintype.coe_image_univ, univ_eq] classical simp [Finset.coe_insert] @[simp, norm_cast] lemma coe_mul {α} [MulZeroOneClass α] [HasDistribNeg α] (a b : SignType) : ↑(a * b) = (a : α) * b := map_mul SignType.castHom _ _ @[simp, norm_cast] lemma coe_pow {α} [MonoidWithZero α] [HasDistribNeg α] (a : SignType) (k : ℕ) : ↑(a ^ k) = (a : α) ^ k := map_pow SignType.castHom _ _ @[simp, norm_cast] lemma coe_zpow {α} [GroupWithZero α] [HasDistribNeg α] (a : SignType) (k : ℤ) : ↑(a ^ k) = (a : α) ^ k := map_zpow₀ SignType.castHom _ _ end SignType open SignType section OrderedRing @[simp] lemma sign_intCast {α : Type*} [Ring α] [PartialOrder α] [IsOrderedRing α] [Nontrivial α] [DecidableLT α] (n : ℤ) : sign (n : α) = sign n := by simp only [sign_apply, Int.cast_pos, Int.cast_lt_zero] end OrderedRing section LinearOrderedRing variable [Ring α] [LinearOrder α] [IsStrictOrderedRing α] theorem sign_mul (x y : α) : sign (x * y) = sign x * sign y := by rcases lt_trichotomy x 0 with (hx | hx | hx) <;> rcases lt_trichotomy y 0 with (hy | hy | hy) <;> simp [hx, hy, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] @[simp] theorem sign_mul_abs (x : α) : (sign x * |x| : α) = x := by rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg] @[simp] theorem abs_mul_sign (x : α) : (|x| * sign x : α) = x := by rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg] @[simp] theorem sign_mul_self (x : α) : sign x * x = |x| := by rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg] @[simp] theorem self_mul_sign (x : α) : x * sign x = |x| := by rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg] /-- `SignType.sign` as a `MonoidWithZeroHom` for a nontrivial ordered semiring. Note that linearity is required; consider ℂ with the order `z ≤ w` iff they have the same imaginary part and `z - w ≤ 0` in the reals; then `1 + I` and `1 - I` are incomparable to zero, and thus we have: `0 * 0 = SignType.sign (1 + I) * SignType.sign (1 - I) ≠ SignType.sign 2 = 1`. (`Complex.orderedCommRing`) -/ def signHom : α →*₀ SignType where toFun := sign map_zero' := sign_zero map_one' := sign_one map_mul' := sign_mul theorem sign_pow (x : α) (n : ℕ) : sign (x ^ n) = sign x ^ n := map_pow signHom x n end LinearOrderedRing section LinearOrderedAddCommGroup variable [AddCommGroup α] [LinearOrder α] [IsOrderedAddMonoid α] theorem sign_sum {ι : Type*} {s : Finset ι} {f : ι → α} (hs : s.Nonempty) (t : SignType) (h : ∀ i ∈ s, sign (f i) = t) : sign (∑ i ∈ s, f i) = t := by cases t · simp_rw [zero_eq_zero, sign_eq_zero_iff] at h ⊢ exact Finset.sum_eq_zero h · simp_rw [neg_eq_neg_one, sign_eq_neg_one_iff] at h ⊢ exact Finset.sum_neg h hs · simp_rw [pos_eq_one, sign_eq_one_iff] at h ⊢ exact Finset.sum_pos h hs end LinearOrderedAddCommGroup open Finset Nat section exists_signed_sum /-! In this section we explicitly handle universe variables, because Lean creates a fresh universe variable for the type whose existence is asserted. But we want the type to live in the same universe as the input type. -/ private theorem exists_signed_sum_aux [DecidableEq α] (s : Finset α) (f : α → ℤ) : ∃ (β : Type u) (t : Finset β) (sgn : β → SignType) (g : β → α), (∀ b, g b ∈ s) ∧ (#t = ∑ a ∈ s, (f a).natAbs) ∧ ∀ a ∈ s, (∑ b ∈ t, if g b = a then (sgn b : ℤ) else 0) = f a := by refine ⟨(Σ _ : { x // x ∈ s }, ℕ), Finset.univ.sigma fun a => range (f a).natAbs, fun a => sign (f a.1), fun a => a.1, fun a => a.1.2, ?_, ?_⟩ · simp [sum_attach (f := fun a => (f a).natAbs)] · intro x hx simp [sum_sigma, hx, ← Int.sign_eq_sign, Int.sign_mul_abs, mul_comm |f _|, sum_attach (s := s) (f := fun y => if y = x then f y else 0)] /-- We can decompose a sum of absolute value `n` into a sum of `n` signs. -/ theorem exists_signed_sum [DecidableEq α] (s : Finset α) (f : α → ℤ) : ∃ (β : Type u) (_ : Fintype β) (sgn : β → SignType) (g : β → α), (∀ b, g b ∈ s) ∧ (Fintype.card β = ∑ a ∈ s, (f a).natAbs) ∧ ∀ a ∈ s, (∑ b, if g b = a then (sgn b : ℤ) else 0) = f a := let ⟨β, t, sgn, g, hg, ht, hf⟩ := exists_signed_sum_aux s f ⟨t, inferInstance, fun b => sgn b, fun b => g b, fun b => hg b, by simp [ht], fun a ha => (sum_attach t fun b ↦ ite (g b = a) (sgn b : ℤ) 0).trans <| hf _ ha⟩ /-- We can decompose a sum of absolute value less than `n` into a sum of at most `n` signs. -/ theorem exists_signed_sum' [Nonempty α] [DecidableEq α] (s : Finset α) (f : α → ℤ) (n : ℕ) (h : (∑ i ∈ s, (f i).natAbs) ≤ n) : ∃ (β : Type u) (_ : Fintype β) (sgn : β → SignType) (g : β → α), (∀ b, g b ∉ s → sgn b = 0) ∧ Fintype.card β = n ∧ ∀ a ∈ s, (∑ i, if g i = a then (sgn i : ℤ) else 0) = f a := by obtain ⟨β, _, sgn, g, hg, hβ, hf⟩ := exists_signed_sum s f refine ⟨β ⊕ (Fin (n - ∑ i ∈ s, (f i).natAbs)), inferInstance, Sum.elim sgn 0, Sum.elim g (Classical.arbitrary (Fin (n - Finset.sum s fun i => Int.natAbs (f i)) → α)), ?_, by simp [hβ, h], fun a ha => by simp [hf _ ha]⟩ rintro (b | b) hb · cases hb (hg _) · rfl end exists_signed_sum
Init.lean
/- Copyright (c) 2023 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import Mathlib.Init import Aesop /-! # Rule sets related to topological (pre)sheaves This module defines the `Restrict` Aesop rule set. Aesop rule sets only become visible once the file in which they're declared is imported, so we must put this declaration into its own file. -/ /- to prove subset relations -/ declare_aesop_rule_sets [Restrict]
algnum.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path. From mathcomp Require Import div choice fintype tuple finfun bigop prime. From mathcomp Require Import ssralg poly polydiv ssrnum ssrint archimedean rat. From mathcomp Require Import finalg zmodp matrix mxalgebra mxpoly vector intdiv. From mathcomp Require Import falgebra fieldext separable galois algC cyclotomic. (******************************************************************************) (* This file provides a few basic results and constructions in algebraic *) (* number theory, that are used in the character theory library. Most of *) (* these could be generalized to a more abstract setting. Note that the type *) (* of abstract number fields is simply extFieldType rat. We define here: *) (* x \in Crat_span X <=> x is a Q-linear combination of elements of *) (* X : seq algC. *) (* x \in Cint_span X <=> x is a Z-linear combination of elements of *) (* X : seq algC. *) (* x \in Aint <=> x : algC is an algebraic integer, i.e., the (monic) *) (* polynomial of x over Q has integer coefficients. *) (* (e %| a)%A <=> e divides a with respect to algebraic integers, *) (* (e %| a)%Ax i.e., a is in the algebraic integer ideal generated *) (* by e. This is is notation for a \in dvdA e, where *) (* dvdv is the (collective) predicate for the Aint *) (* ideal generated by e. As in the (e %| a)%C notation *) (* e and a can be coerced to algC from nat or int. *) (* The (e %| a)%Ax display form is a workaround for *) (* design limitations of the Coq Notation facilities. *) (* (a == b %[mod e])%A, (a != b %[mod e])%A <=> *) (* a is equal (resp. not equal) to b mod e, i.e., a and *) (* b belong to the same e * Aint class. We do not *) (* force a, b and e to be algebraic integers. *) (* #[x]%C == the multiplicative order of x, i.e., the n such that *) (* x is an nth primitive root of unity, or 0 if x is not *) (* a root of unity. *) (* In addition several lemmas prove the (constructive) existence of number *) (* fields and of automorphisms of algC. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope algC_scope. Declare Scope algC_expanded_scope. Import GRing.Theory Num.Theory. Local Open Scope ring_scope. Local Notation ZtoQ := (intr : int -> rat). Local Notation ZtoC := (intr : int -> algC). Local Notation QtoC := (ratr : rat -> algC). Local Notation intrp := (map_poly intr). Local Notation pZtoQ := (map_poly ZtoQ). Local Notation pZtoC := (map_poly ZtoC). Local Notation pQtoC := (map_poly ratr). Local Definition intr_inj_ZtoC := (intr_inj : injective ZtoC). #[local] Hint Resolve intr_inj_ZtoC : core. Section MoreAlgCaut. Implicit Type rR : unitRingType. Lemma alg_num_field (Qz : fieldExtType rat) a : a%:A = ratr a :> Qz. Proof. by rewrite -in_algE fmorph_eq_rat. Qed. Lemma rmorphZ_num (Qz : fieldExtType rat) rR (f : {rmorphism Qz -> rR}) a x : f (a *: x) = ratr a * f x. Proof. by rewrite -mulr_algl rmorphM alg_num_field fmorph_rat. Qed. Lemma fmorph_numZ (Qz1 Qz2 : fieldExtType rat) (f : {rmorphism Qz1 -> Qz2}) : scalable f. Proof. by move=> a x; rewrite rmorphZ_num -alg_num_field mulr_algl. Qed. End MoreAlgCaut. (* Number fields and rational spans. *) Lemma algC_PET (s : seq algC) : {z | exists a : nat ^ size s, z = \sum_(i < size s) s`_i *+ a i & exists ps, s = [seq (pQtoC p).[z] | p <- ps]}. Proof. elim: s => [|x s [z /sig_eqW[a Dz] /sig_eqW[ps Ds]]]. by exists 0; [exists [ffun _ => 2%N]; rewrite big_ord0 | exists nil]. have r_exists (y : algC): {r | r != 0 & root (pQtoC r) y}. have [r [_ mon_r] dv_r] := minCpolyP y. by exists r; rewrite ?monic_neq0 ?dv_r. suffices /sig_eqW[[n [|px [|pz []]]]// [Dpx Dpz]]: exists np, let zn := x *+ np.1 + z in [:: x; z] = [seq (pQtoC p).[zn] | p <- np.2]. - exists (x *+ n + z). exists [ffun i => oapp a n (unlift ord0 i)]. rewrite /= big_ord_recl ffunE unlift_none Dz; congr (_ + _). by apply: eq_bigr => i _; rewrite ffunE liftK. exists (px :: [seq p \Po pz | p <- ps]); rewrite /= -Dpx; congr (_ :: _). rewrite -map_comp Ds; apply: eq_map => p /=. by rewrite map_comp_poly horner_comp -Dpz. have [rx nz_rx rx0] := r_exists x. have [rz nz_rz rz0] := r_exists (- z). have pchar0_Q: [pchar rat] =i pred0 by apply: pchar_num. have [n [[pz Dpz] [px Dpx]]] := pchar0_PET nz_rz rz0 nz_rx rx0 pchar0_Q. by exists (n, [:: px; - pz]); rewrite /= !raddfN hornerN -[z]opprK Dpz Dpx. Qed. Lemma num_field_exists (s : seq algC) : {Qs : fieldExtType rat & {QsC : {rmorphism Qs -> algC} & {s1 : seq Qs | map QsC s1 = s & <<1 & s1>>%VS = fullv}}}. Proof. have [z /sig_eqW[a Dz] /sig_eqW[ps Ds]] := algC_PET s. suffices [Qs [QsC [z1 z1C z1gen]]]: {Qs : fieldExtType rat & {QsC : {rmorphism Qs -> algC} & {z1 : Qs | QsC z1 = z & forall xx, exists p, fieldExt_horner z1 p = xx}}}. - set inQs := fieldExt_horner z1 in z1gen *; pose s1 := map inQs ps. have inQsK p: QsC (inQs p) = (pQtoC p).[z]. rewrite /= -horner_map z1C -map_poly_comp; congr _.[z]. by apply: eq_map_poly => b /=; rewrite alg_num_field fmorph_rat. exists Qs, QsC, s1; first by rewrite -map_comp Ds (eq_map inQsK). have sz_ps: size ps = size s by rewrite Ds size_map. apply/vspaceP=> x; rewrite memvf; have [p {x}<-] := z1gen x. elim/poly_ind: p => [|p b ApQs]; first by rewrite /inQs rmorph0 mem0v. rewrite /inQs rmorphD rmorphM /= fieldExt_hornerX fieldExt_hornerC -/inQs /=. suffices ->: z1 = \sum_(i < size s) s1`_i *+ a i. rewrite memvD ?memvZ ?mem1v ?memvM ?memv_suml // => i _. by rewrite rpredMn ?seqv_sub_adjoin ?mem_nth // size_map sz_ps. apply: (fmorph_inj QsC); rewrite z1C Dz rmorph_sum; apply: eq_bigr => i _. by rewrite rmorphMn {1}Ds !(nth_map 0) ?sz_ps //= inQsK. have [r [Dr /monic_neq0 nz_r] dv_r] := minCpolyP z. have rz0: root (pQtoC r) z by rewrite dv_r. have irr_r: irreducible_poly r. by apply/(subfx_irreducibleP rz0 nz_r)=> q qz0 nzq; rewrite dvdp_leq // -dv_r. exists (SubFieldExtType rz0 irr_r), (@subfx_inj _ _ QtoC z r). exists (subfx_root _ z r) => [|x]; first exact: subfx_inj_root. by have{x} [p ->] := subfxEroot rz0 nz_r x; exists p. Qed. Definition in_Crat_span s x := exists a : rat ^ size s, x = \sum_i QtoC (a i) * s`_i. Fact Crat_span_subproof s x : decidable (in_Crat_span s x). Proof. have [Qxs [QxsC [[|x1 s1] // [<- <-] {x s} _]]] := num_field_exists (x :: s). apply: decP (x1 \in <<in_tuple s1>>%VS) _; rewrite /in_Crat_span size_map. apply: (iffP idP) => [/coord_span-> | [a Dx]]. move: (coord _) => a; exists [ffun i => a i x1]; rewrite rmorph_sum /=. by apply: eq_bigr => i _; rewrite ffunE rmorphZ_num (nth_map 0). have{Dx} ->: x1 = \sum_i a i *: s1`_i. apply: (fmorph_inj QxsC); rewrite Dx rmorph_sum /=. by apply: eq_bigr => i _; rewrite rmorphZ_num (nth_map 0). by apply: memv_suml => i _; rewrite memvZ ?memv_span ?mem_nth. Qed. Definition Crat_span s : pred algC := Crat_span_subproof s. Lemma Crat_spanP s x : reflect (in_Crat_span s x) (x \in Crat_span s). Proof. exact: sumboolP. Qed. Lemma mem_Crat_span s : {subset s <= Crat_span s}. Proof. move=> _ /(nthP 0)[ix ltxs <-]; pose i0 := Ordinal ltxs. apply/Crat_spanP; exists [ffun i => (i == i0)%:R]. rewrite (bigD1_ord i0) //= ffunE eqxx // rmorph1 mul1r. by rewrite big1 ?addr0 // => i; rewrite ffunE rmorph_nat mulr_natl lift_eqF. Qed. Fact Crat_span_zmod_closed s : zmod_closed (Crat_span s). Proof. split=> [|_ _ /Crat_spanP[x ->] /Crat_spanP[y ->]]. apply/Crat_spanP; exists 0. by apply/esym/big1=> i _; rewrite ffunE rmorph0 mul0r. apply/Crat_spanP; exists (x - y); rewrite -sumrB; apply: eq_bigr => i _. by rewrite -mulrBl -rmorphB !ffunE. Qed. HB.instance Definition _ s := GRing.isZmodClosed.Build _ (Crat_span s) (Crat_span_zmod_closed s). Section NumFieldProj. Variables (Qn : fieldExtType rat) (QnC : {rmorphism Qn -> algC}). Lemma Crat_spanZ b a : {in Crat_span b, forall x, ratr a * x \in Crat_span b}. Proof. move=> _ /Crat_spanP[a1 ->]; apply/Crat_spanP; exists [ffun i => a * a1 i]. by rewrite mulr_sumr; apply: eq_bigr => i _; rewrite ffunE mulrA -rmorphM. Qed. Lemma Crat_spanM b : {in Crat & Crat_span b, forall a x, a * x \in Crat_span b}. Proof. by move=> _ x /CratP[a ->]; apply: Crat_spanZ. Qed. (* In principle CtoQn could be taken to be additive and Q-linear, but this *) (* would require a limit construction. *) Lemma num_field_proj : {CtoQn | CtoQn 0 = 0 & cancel QnC CtoQn}. Proof. pose b := vbasis {:Qn}. have Qn_bC (u : {x | x \in Crat_span (map QnC b)}): {y | QnC y = sval u}. case: u => _ /= /Crat_spanP/sig_eqW[a ->]. exists (\sum_i a i *: b`_i); rewrite rmorph_sum /=; apply: eq_bigr => i _. by rewrite rmorphZ_num (nth_map 0) // -(size_map QnC). pose CtoQn x := oapp (fun u => sval (Qn_bC u)) 0 (insub x). suffices QnCK: cancel QnC CtoQn by exists CtoQn; rewrite // -(rmorph0 QnC) /=. move=> x; rewrite /CtoQn insubT => /= [|Qn_x]; last first. by case: (Qn_bC _) => x1 /= /fmorph_inj. rewrite (coord_vbasis (memvf x)) rmorph_sum rpred_sum //= => i _. rewrite rmorphZ_num Crat_spanZ ?mem_Crat_span // -/b. by rewrite -tnth_nth -tnth_map mem_tnth. Qed. Lemma restrict_aut_to_num_field (nu : {rmorphism algC -> algC}) : (forall x, exists y, nu (QnC x) = QnC y) -> {nu0 : {lrmorphism Qn -> Qn} | {morph QnC : x / nu0 x >-> nu x}}. Proof. move=> Qn_nu; pose nu0 x := sval (sig_eqW (Qn_nu x)). have QnC_nu0: {morph QnC : x / nu0 x >-> nu x}. by rewrite /nu0 => x; case: (sig_eqW _). have nu0a : zmod_morphism nu0. by move=> x y; apply: (fmorph_inj QnC); rewrite !(QnC_nu0, rmorphB). have nu0m : monoid_morphism nu0. split=> [|x y]; apply: (fmorph_inj QnC); rewrite ?QnC_nu0 ?rmorph1 //. by rewrite !rmorphM /= !QnC_nu0. pose nu0aM := GRing.isZmodMorphism.Build Qn Qn nu0 nu0a. pose nu0mM := GRing.isMonoidMorphism.Build Qn Qn nu0 nu0m. pose nu0RM : {rmorphism _ -> _} := HB.pack nu0 nu0aM nu0mM. pose nu0lM := GRing.isScalable.Build rat Qn Qn *:%R nu0 (fmorph_numZ nu0RM). pose nu0LRM : {lrmorphism _ -> _} := HB.pack nu0 nu0aM nu0mM nu0lM. by exists nu0LRM. Qed. Lemma map_Qnum_poly (nu : {rmorphism algC -> algC}) p : p \in polyOver 1%VS -> map_poly (nu \o QnC) p = (map_poly QnC p). Proof. move=> Qp; apply/polyP=> i; rewrite /= !coef_map /=. have /vlineP[a ->]: p`_i \in 1%VS by apply: polyOverP. by rewrite alg_num_field !fmorph_rat. Qed. End NumFieldProj. Lemma restrict_aut_to_normal_num_field (Qn : splittingFieldType rat) (QnC : {rmorphism Qn -> algC})(nu : {rmorphism algC -> algC}) : {nu0 : {lrmorphism Qn -> Qn} | {morph QnC : x / nu0 x >-> nu x}}. Proof. apply: restrict_aut_to_num_field => x. case: (splitting_field_normal 1%AS x) => rs /eqP Hrs. have: root (map_poly (nu \o QnC) (minPoly 1%AS x)) (nu (QnC x)). by rewrite fmorph_root root_minPoly. rewrite map_Qnum_poly ?minPolyOver // Hrs. rewrite [map_poly _ _](_:_ = \prod_(y <- map QnC rs) ('X - y%:P)). by rewrite root_prod_XsubC; case/mapP => y _ ?; exists y. by rewrite big_map rmorph_prod /=; apply: eq_bigr => i _; rewrite map_polyXsubC. Qed. (* Integral spans. *) Lemma dec_Cint_span (V : vectType algC) m (s : m.-tuple V) v : decidable (inIntSpan s v). Proof. have s_s (i : 'I_m): s`_i \in <<s>>%VS by rewrite memv_span ?memt_nth. have s_Zs a: \sum_(i < m) s`_i *~ a i \in <<s>>%VS. by rewrite memv_suml // => i _; rewrite -scaler_int memvZ. case s_v: (v \in <<s>>%VS); last by right=> [[a Dv]]; rewrite Dv s_Zs in s_v. pose IzT := {: 'I_m * 'I_(\dim <<s>>)}; pose Iz := 'I_#|IzT|. pose b := vbasis <<s>>. pose z_s := [seq coord b ij.2 (tnth s ij.1) | ij : IzT]. pose rank2 j i: Iz := enum_rank (i, j); pose val21 (p : Iz) := (enum_val p).1. pose inQzs w := [forall j, Crat_span z_s (coord b j w)]. have enum_pairK j: {in predT, cancel (rank2 j) val21}. by move=> i; rewrite /val21 enum_rankK. have Qz_Zs a: inQzs (\sum_(i < m) s`_i *~ a i). apply/forallP=> j; apply/Crat_spanP; rewrite /in_Crat_span size_map -cardE. exists [ffun ij => (a (val21 ij))%:Q *+ ((enum_val ij).2 == j)]. rewrite linear_sum {1}(reindex_onto _ _ (enum_pairK j)) big_mkcond /=. apply: eq_bigr => ij _ /=; rewrite nth_image (tnth_nth 0) ffunE /val21. rewrite raddfMz rmorphMn rmorph_int mulrnAl mulrzl /=. rewrite (can2_eq (@enum_rankK _) (@enum_valK _)). by case: (enum_val ij) => i j1; rewrite xpair_eqE eqxx; have [->|] := eqVneq. case Qz_v: (inQzs v); last by right=> [[a Dv]]; rewrite Dv Qz_Zs in Qz_v. have [Qz [QzC [z1s Dz_s _]]] := num_field_exists z_s. have sz_z1s: size z1s = #|IzT| by rewrite -(size_map QzC) Dz_s size_map cardE. have xv j: {x | coord b j v = QzC x}. apply: sig_eqW; have /Crat_spanP[x ->] := forallP Qz_v j. exists (\sum_ij x ij *: z1s`_ij); rewrite rmorph_sum; apply: eq_bigr => ij _. by rewrite rmorphZ_num -[in RHS](nth_map _ 0) ?Dz_s // -(size_map QzC) Dz_s. pose sz := [tuple [ffun j => z1s`_(rank2 j i)] | i < m]. have [Zsv | Zs'v] := dec_Qint_span sz [ffun j => sval (xv j)]. left; have{Zsv} [a Dv] := Zsv; exists a. transitivity (\sum_j \sum_(i < m) QzC ((sz`_i *~ a i) j) *: b`_j). rewrite {1}(coord_vbasis s_v) -/b; apply: eq_bigr => j _. rewrite -scaler_suml; congr (_ *: _). have{Dv} /ffunP/(_ j) := Dv; rewrite sum_ffunE !ffunE -rmorph_sum => <-. by case: (xv j). rewrite exchange_big; apply: eq_bigr => i _. rewrite (coord_vbasis (s_s i)) -/b mulrz_suml; apply: eq_bigr => j _. rewrite scalerMzl ffunMzE rmorphMz; congr ((_ *~ _) *: _). rewrite nth_mktuple ffunE -(nth_map _ 0) ?sz_z1s // Dz_s. by rewrite nth_image enum_rankK /= (tnth_nth 0). right=> [[a Dv]]; case: Zs'v; exists a. apply/ffunP=> j; rewrite sum_ffunE !ffunE; apply: (fmorph_inj QzC). case: (xv j) => /= _ <-; rewrite Dv linear_sum rmorph_sum /=. apply: eq_bigr => i _; rewrite nth_mktuple raddfMz !ffunMzE rmorphMz ffunE. by rewrite -(nth_map _ 0 QzC) ?sz_z1s // Dz_s nth_image enum_rankK -tnth_nth. Qed. Definition Cint_span (s : seq algC) : pred algC := fun x => dec_Cint_span (in_tuple [seq \row_(i < 1) y | y <- s]) (\row_i x). Lemma Cint_spanP n (s : n.-tuple algC) x : reflect (inIntSpan s x) (x \in Cint_span s). Proof. rewrite unfold_in; case: (dec_Cint_span _ _) => [Zs_x | Zs'x] /=. left; have{Zs_x} [] := Zs_x; rewrite /= size_map size_tuple => a /rowP/(_ 0). rewrite !mxE => ->; exists a; rewrite summxE; apply: eq_bigr => i _. by rewrite -scaler_int (nth_map 0) ?size_tuple // !mxE mulrzl. right=> [[a Dx]]; have{Zs'x} [] := Zs'x. rewrite /inIntSpan /= size_map size_tuple; exists a. apply/rowP=> i0; rewrite !mxE summxE Dx; apply: eq_bigr => i _. by rewrite -scaler_int mxE mulrzl (nth_map 0) ?size_tuple // !mxE. Qed. Lemma mem_Cint_span s : {subset s <= Cint_span s}. Proof. move=> _ /(nthP 0)[ix ltxs <-]; apply/(Cint_spanP (in_tuple s)). exists [ffun i => i == Ordinal ltxs : int]. rewrite (bigD1 (Ordinal ltxs)) //= ffunE eqxx. by rewrite big1 ?addr0 // => i; rewrite ffunE => /negbTE->. Qed. Lemma Cint_span_zmod_closed s : zmod_closed (Cint_span s). Proof. have sP := Cint_spanP (in_tuple s); split=> [|_ _ /sP[x ->] /sP[y ->]]. by apply/sP; exists 0; rewrite big1 // => i; rewrite ffunE. apply/sP; exists (x - y); rewrite -sumrB; apply: eq_bigr => i _. by rewrite !ffunE raddfB. Qed. HB.instance Definition _ s := GRing.isZmodClosed.Build _ (Cint_span s) (Cint_span_zmod_closed s). (* Automorphism extensions. *) Lemma extend_algC_subfield_aut (Qs : fieldExtType rat) (QsC : {rmorphism Qs -> algC}) (phi : {rmorphism Qs -> Qs}) : {nu : {rmorphism algC -> algC} | {morph QsC : x / phi x >-> nu x}}. Proof. pose numF_inj (Qr : fieldExtType rat) := {rmorphism Qr -> algC}. pose subAut := {Qr : _ & numF_inj Qr * {lrmorphism Qr -> Qr}}%type. pose SubAut := existT _ _ (_, _) : subAut. pose Sdom (mu : subAut) := projT1 mu. pose Sinj (mu : subAut) : {rmorphism Sdom mu -> algC} := (projT2 mu).1. pose Saut (mu : subAut) : {rmorphism Sdom mu -> Sdom mu} := (projT2 mu).2. have Sinj_poly Qr (QrC : numF_inj Qr) p: map_poly QrC (map_poly (in_alg Qr) p) = pQtoC p. - rewrite -map_poly_comp; apply: eq_map_poly => a. by rewrite /= rmorphZ_num rmorph1 mulr1. have ext1 mu0 x : {mu1 | exists y, x = Sinj mu1 y & exists2 in01 : {lrmorphism _ -> _}, Sinj mu0 =1 Sinj mu1 \o in01 & {morph in01: y / Saut mu0 y >-> Saut mu1 y}}. - pose b0 := vbasis {:Sdom mu0}. have [z _ /sig_eqW[[|px ps] // [Dx Ds]]] := algC_PET (x :: map (Sinj mu0) b0). have [p [_ mon_p] /(_ p) pz0] := minCpolyP z; rewrite dvdpp in pz0. have [r Dr] := closed_field_poly_normal (pQtoC p : {poly algC}). rewrite lead_coef_map {mon_p}(monicP mon_p) rmorph1 scale1r in Dr. have{pz0} rz: z \in r by rewrite -root_prod_XsubC -Dr. have [Qr [QrC [rr Drr genQr]]] := num_field_exists r. have{rz} [zz Dz]: {zz | QrC zz = z}. by move: rz; rewrite -Drr => /mapP/sig2_eqW[zz]; exists zz. have{ps Ds} [in01 Din01]: {in01 : {lrmorphism _ -> _} | Sinj mu0 =1 QrC \o in01}. have in01P y: {yy | Sinj mu0 y = QrC yy}. exists (\sum_i coord b0 i y *: (map_poly (in_alg Qr) ps`_i).[zz]). rewrite {1}(coord_vbasis (memvf y)) !rmorph_sum /=; apply: eq_bigr => i _. rewrite 2!rmorphZ_num -(nth_map _ 0) ?size_tuple // Ds. rewrite -horner_map Dz Sinj_poly (nth_map 0) //. by have:= congr1 size Ds; rewrite !size_map size_tuple => <-. pose in01 y := sval (in01P y). have Din01 y: Sinj mu0 y = QrC (in01 y) by rewrite /in01; case: (in01P y). pose rwM := (=^~ Din01, rmorphZ_num, rmorph1, rmorphB, rmorphM). have in01a : zmod_morphism in01. by move=> ? ?; apply: (fmorph_inj QrC); rewrite !rwM. have in01m : monoid_morphism in01. by split; try move=> ? ?; apply: (fmorph_inj QrC); rewrite !rwM /= ?rwM. have in01l : scalable in01. by try move=> ? ?; apply: (fmorph_inj QrC); rewrite !rwM. pose in01aM := GRing.isZmodMorphism.Build _ _ in01 in01a. pose in01mM := GRing.isMonoidMorphism.Build _ _ in01 in01m. pose in01lM := GRing.isScalable.Build _ _ _ _ in01 in01l. pose in01LRM : {lrmorphism _ -> _} := HB.pack in01 in01aM in01mM in01lM. by exists in01LRM. have {z zz Dz px} Dx: exists xx, x = QrC xx. exists (map_poly (in_alg Qr) px).[zz]. by rewrite -horner_map Dz Sinj_poly Dx. pose lin01 := linfun in01; pose K := (lin01 @: fullv)%VS. have memK y: reflect (exists yy, y = in01 yy) (y \in K). apply: (iffP memv_imgP) => [[yy _ ->] | [yy ->]]; by exists yy; rewrite ?lfunE ?memvf. have algK: is_aspace K. rewrite /is_aspace has_algid1; last first. by apply/memK; exists 1; rewrite rmorph1. apply/prodvP=> _ _ /memK[y1 ->] /memK[y2 ->]. by apply/memK; exists (y1 * y2); rewrite rmorphM. have ker_in01: lker lin01 == 0%VS. by apply/lker0P=> y1 y2; rewrite !lfunE; apply: fmorph_inj. pose f := (lin01 \o linfun (Saut mu0) \o lin01^-1)%VF. have Df y: f (in01 y) = in01 (Saut mu0 y). transitivity (f (lin01 y)); first by rewrite !lfunE. by do 4!rewrite lfunE /=; rewrite lker0_lfunK. have hom_f: kHom 1 (ASpace algK) f. apply/kHomP_tmp; split=> [_ /vlineP[a ->] | _ _ /memK[y1 ->] /memK[y2 ->]]. by rewrite -(rmorph_alg in01) Df /= !rmorph_alg. by rewrite -rmorphM !Df !rmorphM. pose pr := map_poly (in_alg Qr) p. have Qpr: pr \is a polyOver 1%VS. by apply/polyOverP=> i; rewrite coef_map memvZ ?memv_line. have splitQr: splittingFieldFor K pr fullv. apply: splittingFieldForS (sub1v (Sub K algK)) (subvf _) _; exists rr => //. congr (_ %= _): (eqpxx pr); apply/(map_poly_inj QrC). rewrite Sinj_poly Dr -Drr big_map rmorph_prod /=; apply: eq_bigr => zz _. by rewrite map_polyXsubC. have [f1 aut_f1 Df1]:= kHom_extends (sub1v (ASpace algK)) hom_f Qpr splitQr. pose f1mM := GRing.isMonoidMorphism.Build _ _ f1 (kHom_monoid_morphism aut_f1). pose nu : {lrmorphism _ -> _} := HB.pack (fun_of_lfun f1) f1mM. exists (SubAut Qr QrC nu) => //; exists in01 => //= y. by rewrite -Df -Df1 //; apply/memK; exists y. have phiZ: scalable phi. by move=> a y; rewrite rmorphZ_num -alg_num_field mulr_algl. pose philM := GRing.isScalable.Build _ _ _ _ phi phiZ. pose phiLRM : {lrmorphism _ -> _} := HB.pack (GRing.RMorphism.sort phi) philM. pose fix ext n := if n is i.+1 then oapp (fun x => s2val (ext1 (ext i) x)) (ext i) (unpickle i) else SubAut Qs QsC phiLRM. have mem_ext x n: (pickle x < n)%N -> {xx | Sinj (ext n) xx = x}. move=> ltxn; apply: sig_eqW; elim: n ltxn => // n IHn. rewrite ltnS leq_eqVlt => /predU1P[<- | /IHn[xx <-]] /=. by rewrite pickleK /=; case: (ext1 _ x) => mu [xx]; exists xx. case: (unpickle n) => /= [y|]; last by exists xx. case: (ext1 _ y) => mu /= _ [in_mu inj_in_mu _]. by exists (in_mu xx); rewrite inj_in_mu. pose nu x := Sinj _ (Saut _ (sval (mem_ext x _ (ltnSn _)))). have nu_inj n y: nu (Sinj (ext n) y) = Sinj (ext n) (Saut (ext n) y). rewrite /nu; case: (mem_ext _ _ _); move: _.+1 => n1 y1 Dy /=. without loss /subnK Dn1: n n1 y y1 Dy / (n <= n1)%N. by move=> IH; case/orP: (leq_total n n1) => /IH => [/(_ y) | /(_ y1)]->. move: (n1 - n)%N => k in Dn1; elim: k => [|k IHk] in n Dn1 y Dy *. by move: y1 Dy; rewrite -Dn1 => y1 /fmorph_inj ->. rewrite addSnnS in Dn1; move/IHk: Dn1 => /=. case: (unpickle _) => [z|] /=; last exact. case: (ext1 _ _) => mu /= _ [in_mu Dinj Daut]. by rewrite Dy => /(_ _ (Dinj _))->; rewrite -Daut Dinj. pose le_nu (x : algC) n := (pickle x < n)%N. have max3 x1 x2 x3: exists n, [/\ le_nu x1 n, le_nu x2 n & le_nu x3 n]. exists (maxn (pickle x1) (maxn (pickle x2) (pickle x3))).+1. by apply/and3P; rewrite /le_nu !ltnS -!geq_max. have nua : zmod_morphism nu. move=> x1 x2; have [n] := max3 (x1 - x2) x1 x2. case=> /mem_ext[y Dx] /mem_ext[y1 Dx1] /mem_ext[y2 Dx2]. rewrite -Dx nu_inj; rewrite -Dx1 -Dx2 -rmorphB in Dx. by rewrite (fmorph_inj _ Dx) !rmorphB -!nu_inj Dx1 Dx2. have num : monoid_morphism nu. split=> [|x1 x2]; first by rewrite -(rmorph1 QsC) (nu_inj 0) !rmorph1. have [n] := max3 (x1 * x2) x1 x2. case=> /mem_ext[y Dx] /mem_ext[y1 Dx1] /mem_ext[y2 Dx2]. rewrite -Dx nu_inj; rewrite -Dx1 -Dx2 -rmorphM in Dx. by rewrite (fmorph_inj _ Dx) !rmorphM /= -!nu_inj Dx1 Dx2. pose nuaM := GRing.isZmodMorphism.Build _ _ nu nua. pose numM := GRing.isMonoidMorphism.Build _ _ nu num. pose nuRM : {rmorphism _ -> _} := HB.pack nu nuaM numM. by exists nuRM => x; rewrite /= (nu_inj 0). Qed. (* Extended automorphisms of Q_n. *) Lemma Qn_aut_exists k n : coprime k n -> {u : {rmorphism algC -> algC} | forall z, z ^+ n = 1 -> u z = z ^+ k}. Proof. have [-> /eqnP | n_gt0 co_k_n] := posnP n. by rewrite gcdn0 => ->; exists idfun. have [z prim_z] := C_prim_root_exists n_gt0. have [Qn [QnC [[|zn []] // [Dz]]] genQn] := num_field_exists [:: z]. pose phi := kHomExtend 1 \1 zn (zn ^+ k). have homQn1: kHom 1 1 (\1%VF : 'End(Qn)) by rewrite kHom1. have pzn_zk0: root (map_poly \1%VF (minPoly 1 zn)) (zn ^+ k). rewrite -(fmorph_root QnC) rmorphXn /= Dz -map_poly_comp. rewrite (@eq_map_poly _ _ _ QnC) => [|a]; last by rewrite /= id_lfunE. set p1 := map_poly _ _. have [q1 Dp1]: exists q1, p1 = pQtoC q1. have aP i: (minPoly 1 zn)`_i \in 1%VS. by apply/polyOverP; apply: minPolyOver. have{aP} a_ i := sig_eqW (vlineP _ _ (aP i)). exists (\poly_(i < size (minPoly 1 zn)) sval (a_ i)). apply/polyP=> i; rewrite coef_poly coef_map coef_poly /=. case: ifP => _; rewrite ?rmorph0 //; case: (a_ i) => a /= ->. by rewrite alg_num_field fmorph_rat. have: root p1 z by rewrite -Dz fmorph_root root_minPoly. rewrite Dp1; have [q2 [Dq2 _] ->] := minCpolyP z. case/dvdpP=> r1 ->; rewrite rmorphM rootM /= -Dq2; apply/orP; right. rewrite (minCpoly_cyclotomic prim_z) /cyclotomic. rewrite (bigD1 (Ordinal (ltn_pmod k n_gt0))) ?coprime_modl //=. by rewrite rootM root_XsubC prim_expr_mod ?eqxx. have phim : monoid_morphism phi. by apply/kHom_monoid_morphism; rewrite -genQn span_seq1 /= kHomExtendP. pose phimM := GRing.isMonoidMorphism.Build _ _ phi phim. pose phiRM : {rmorphism _ -> _} := HB.pack (fun_of_lfun phi) phimM. have [nu Dnu] := extend_algC_subfield_aut QnC phiRM. exists nu => _ /(prim_rootP prim_z)[i ->]. rewrite rmorphXn /= exprAC -Dz -Dnu /= -{1}[zn]hornerX /phi. rewrite (kHomExtend_poly homQn1) ?polyOverX //. rewrite map_polyE map_id_in => [|?]; last by rewrite id_lfunE. by rewrite polyseqK hornerX rmorphXn. Qed. (* Algebraic integers. *) Definition Aint : {pred algC} := fun x => minCpoly x \is a polyOver Num.int. Lemma root_monic_Aint p x : root p x -> p \is monic -> p \is a polyOver Num.int -> x \in Aint. Proof. have pZtoQtoC pz: pQtoC (pZtoQ pz) = pZtoC pz. by rewrite -map_poly_comp; apply: eq_map_poly => b; rewrite /= rmorph_int. move=> px0 mon_p /floorpP[pz Dp]; rewrite unfold_in. move: px0; rewrite Dp -pZtoQtoC; have [q [-> mon_q] ->] := minCpolyP x. case/dvdpP_rat_int=> qz [a nz_a Dq] [r]. move/(congr1 (fun q1 => lead_coef (a *: pZtoQ q1))). rewrite rmorphM scalerAl -Dq lead_coefZ lead_coefM /=. have /monicP->: pZtoQ pz \is monic by rewrite -(map_monic QtoC) pZtoQtoC -Dp. rewrite (monicP mon_q) mul1r mulr1 lead_coef_map_inj //; last exact: intr_inj. rewrite Dq => ->; apply/polyOverP=> i; rewrite !(coefZ, coef_map). by rewrite -rmorphM /= rmorph_int. Qed. Lemma Cint_rat_Aint z : z \in Crat -> z \in Aint -> z \in Num.int. Proof. case/CratP=> a ->{z} /polyOverP/(_ 0). have [p [Dp mon_p] dv_p] := minCpolyP (ratr a); rewrite Dp coef_map. suffices /eqP->: p == 'X - a%:P by rewrite polyseqXsubC /= rmorphN rpredN. rewrite -eqp_monic ?monicXsubC // irredp_XsubC //. by rewrite -(size_map_poly QtoC) -Dp neq_ltn size_minCpoly orbT. by rewrite -dv_p fmorph_root root_XsubC. Qed. Lemma Aint_Cint : {subset Num.int <= Aint}. Proof. move=> x; rewrite -polyOverXsubC. by apply: root_monic_Aint; rewrite ?monicXsubC ?root_XsubC. Qed. Lemma Aint_int x : x%:~R \in Aint. Proof. by rewrite Aint_Cint. Qed. Lemma Aint0 : 0 \in Aint. Proof. exact: Aint_int 0. Qed. Lemma Aint1 : 1 \in Aint. Proof. exact: Aint_int 1. Qed. #[global] Hint Resolve Aint0 Aint1 : core. Lemma Aint_unity_root n x : (n > 0)%N -> n.-unity_root x -> x \in Aint. Proof. move=> n_gt0 xn1; apply: root_monic_Aint xn1 (monicXnsubC _ n_gt0) _. by apply/polyOverP=> i; rewrite coefB coefC -mulrb coefXn /= rpredB ?rpred_nat. Qed. Lemma Aint_prim_root n z : n.-primitive_root z -> z \in Aint. Proof. move=> pr_z; apply/(Aint_unity_root (prim_order_gt0 pr_z))/unity_rootP. exact: prim_expr_order. Qed. Lemma Aint_Cnat : {subset Num.nat <= Aint}. Proof. by move=> z /intr_nat/Aint_Cint. Qed. (* This is Isaacs, Lemma (3.3) *) Lemma Aint_subring_exists (X : seq algC) : {subset X <= Aint} -> {S : pred algC & (*a*) subring_closed S /\ (*b*) {subset X <= S} & (*c*) {Y : {n : nat & n.-tuple algC} & {subset tagged Y <= S} & forall x, reflect (inIntSpan (tagged Y) x) (x \in S)}}. Proof. move=> AZ_X; pose m := (size X).+1. pose n (i : 'I_m) := (size (minCpoly X`_i)).-2; pose N := (\max_i n i).+1. pose IY := family (fun i => [pred e : 'I_N | e <= n i]%N). have IY_0: 0 \in IY by apply/familyP=> // i; rewrite ffunE. pose inIY := enum_rank_in IY_0. pose Y := [seq \prod_(i < m) X`_i ^+ (f : 'I_N ^ m) i | f in IY]. have S_P := Cint_spanP [tuple of Y]; set S := Cint_span _ in S_P. have sYS: {subset Y <= S} by apply: mem_Cint_span. have S_1: 1 \in S. by apply/sYS/imageP; exists 0 => //; rewrite big1 // => i; rewrite ffunE. have SmulX (i : 'I_m): {in S, forall x, x * X`_i \in S}. move=> _ /S_P[x ->]; rewrite mulr_suml rpred_sum // => j _. rewrite mulrzAl rpredMz {x}// nth_image mulrC (bigD1 i) //= mulrA -exprS. move: {j}(enum_val j) (familyP (enum_valP j)) => f fP. have:= fP i; rewrite inE /= leq_eqVlt => /predU1P[-> | fi_ltn]; last first. apply/sYS/imageP; have fiK: (inord (f i).+1 : 'I_N) = (f i).+1 :> nat. by rewrite inordK // ltnS (bigmax_sup i). exists (finfun [eta f with i |-> inord (f i).+1]). apply/familyP=> i1; rewrite inE ffunE /= fun_if fiK. by case: eqP => [-> // | _]; apply: fP. rewrite (bigD1 i isT) ffunE /= eqxx fiK; congr (_ * _). by apply: eq_bigr => i1 /[!ffunE]/= /negPf->. have [/monicP ] := (minCpoly_monic X`_i, root_minCpoly X`_i). rewrite /root horner_coef lead_coefE -(subnKC (size_minCpoly _)) subn2. rewrite big_ord_recr /= addrC addr_eq0 => ->; rewrite mul1r => /eqP->. have /floorpP[p Dp]: X`_i \in Aint. by have [/(nth_default 0)-> | /(mem_nth 0)/AZ_X] := leqP (size X) i. rewrite -/(n i) Dp mulNr rpredN // mulr_suml rpred_sum // => [[e le_e]] /= _. rewrite coef_map -mulrA mulrzl rpredMz ?sYS //; apply/imageP. have eK: (inord e : 'I_N) = e :> nat by rewrite inordK // ltnS (bigmax_sup i). exists (finfun [eta f with i |-> inord e]). apply/familyP=> i1; rewrite inE ffunE /= fun_if eK. by case: eqP => [-> // | _]; apply: fP. rewrite (bigD1 i isT) ffunE /= eqxx eK; congr (_ * _). by apply: eq_bigr => i1 /[!ffunE] /= /negPf->. exists S; last by exists (Tagged (fun n => n.-tuple _) [tuple of Y]). split=> [|x Xx]; last first. by rewrite -[x]mul1r -(nth_index 0 Xx) (SmulX (Ordinal _)) // ltnS index_size. split=> // x y Sx Sy; first by rewrite rpredB. case/S_P: Sy => {y}[y ->]; rewrite mulr_sumr rpred_sum //= => j. rewrite mulrzAr rpredMz {y}// nth_image; move: {j}(enum_val j) => f. elim/big_rec: _ => [|i y _ IHy] in x Sx *; first by rewrite mulr1. rewrite mulrA {y}IHy //. elim: {f}(f i : nat) => [|e IHe] in x Sx *; first by rewrite mulr1. by rewrite exprS mulrA IHe // SmulX. Qed. Section AlgIntSubring. (* This is Isaacs, Theorem (3.4). *) Theorem fin_Csubring_Aint S n (Y : n.-tuple algC) : mulr_closed S -> (forall x, reflect (inIntSpan Y x) (x \in S)) -> {subset S <= Aint}. Proof. move=> mulS. pose Sm := GRing.isMulClosed.Build _ _ mulS. pose SC : mulrClosed _ := HB.pack S Sm. have ZP_C c: (ZtoC c)%:P \is a polyOver Num.int_num_subdef. by rewrite raddfMz rpred_int. move=> S_P x Sx; pose v := \row_(i < n) Y`_i. have [v0 | nz_v] := eqVneq v 0. case/S_P: Sx => {}x ->; rewrite big1 ?isAlgInt0 // => i _. by have /rowP/(_ i)/[!mxE] -> := v0; rewrite mul0rz. have sYS (i : 'I_n): x * Y`_i \in SC. by rewrite rpredM //; apply/S_P/Cint_spanP/mem_Cint_span/memt_nth. pose A := \matrix_(i, j < n) sval (sig_eqW (S_P _ (sYS j))) i. pose p := char_poly (map_mx ZtoC A). have: p \is a polyOver Num.int_num_subdef. rewrite rpred_sum // => s _; rewrite rpredMsign rpred_prod // => j _. by rewrite !mxE /= rpredB ?rpredMn ?polyOverX. apply: root_monic_Aint (char_poly_monic _). rewrite -eigenvalue_root_char; apply/eigenvalueP; exists v => //. apply/rowP=> j; case dAj: (sig_eqW (S_P _ (sYS j))) => [a DxY]. by rewrite !mxE DxY; apply: eq_bigr => i _; rewrite !mxE dAj /= mulrzr. Qed. (* This is Isaacs, Corollary (3.5). *) Corollary Aint_subring : subring_closed Aint. Proof. suff rAZ: {in Aint &, forall x y, (x - y \in Aint) * (x * y \in Aint)}. by split=> // x y AZx AZy; rewrite rAZ. move=> x y AZx AZy. have [|S [ringS] ] := @Aint_subring_exists [:: x; y]; first exact/allP/and3P. move=> /allP/and3P[Sx Sy _] [Y _ genYS]. have AZ_S := fin_Csubring_Aint ringS genYS. by have [_ S_B S_M] := ringS; rewrite !AZ_S ?S_B ?S_M. Qed. HB.instance Definition _ := GRing.isSubringClosed.Build _ Aint Aint_subring. End AlgIntSubring. Lemma Aint_aut (nu : {rmorphism algC -> algC}) x : (nu x \in Aint) = (x \in Aint). Proof. by rewrite !unfold_in minCpoly_aut. Qed. Definition dvdA (e : Algebraics.divisor) : {pred algC} := fun z => if e == 0 then z == 0 else z / e \in Aint. Delimit Scope algC_scope with A. Delimit Scope algC_expanded_scope with Ax. Notation "e %| x" := (x \in dvdA e) : algC_expanded_scope. Notation "e %| x" := (@in_mem Algebraics.divisor x (mem (dvdA e))) : algC_scope. Fact dvdA_zmod_closed e : zmod_closed (dvdA e). Proof. split=> [|x y]; first by rewrite unfold_in mul0r eqxx rpred0 ?if_same. rewrite ![(e %| _)%A]unfold_in. case: ifP => [_ x0 /eqP-> | _]; first by rewrite subr0. by rewrite mulrBl; apply: rpredB. Qed. HB.instance Definition _ e := GRing.isZmodClosed.Build _ (dvdA e) (dvdA_zmod_closed e). Definition eqAmod (e x y : Algebraics.divisor) := (e %| x - y)%A. Notation "x == y %[mod e ]" := (eqAmod e x y) : algC_scope. Notation "x != y %[mod e ]" := (~~ (eqAmod e x y)) : algC_scope. Lemma eqAmod_refl e x : (x == x %[mod e])%A. Proof. by rewrite /eqAmod subrr rpred0. Qed. #[global] Hint Resolve eqAmod_refl : core. Lemma eqAmod_sym e x y : ((x == y %[mod e]) = (y == x %[mod e]))%A. Proof. by rewrite /eqAmod -opprB rpredN. Qed. Lemma eqAmod_trans e y x z : (x == y %[mod e] -> y == z %[mod e] -> x == z %[mod e])%A. Proof. by move=> Exy Eyz; rewrite /eqAmod -[x](subrK y) -[_ - z]addrA rpredD. Qed. Lemma eqAmod_transl e x y z : (x == y %[mod e])%A -> (x == z %[mod e])%A = (y == z %[mod e])%A. Proof. by move/(sym_left_transitive (eqAmod_sym e) (@eqAmod_trans e)). Qed. Lemma eqAmod_transr e x y z : (x == y %[mod e])%A -> (z == x %[mod e])%A = (z == y %[mod e])%A. Proof. by move/(sym_right_transitive (eqAmod_sym e) (@eqAmod_trans e)). Qed. Lemma eqAmod0 e x : (x == 0 %[mod e])%A = (e %| x)%A. Proof. by rewrite /eqAmod subr0. Qed. Lemma eqAmodN e x y : (- x == y %[mod e])%A = (x == - y %[mod e])%A. Proof. by rewrite eqAmod_sym /eqAmod !opprK addrC. Qed. Lemma eqAmodDr e x y z : (y + x == z + x %[mod e])%A = (y == z %[mod e])%A. Proof. by rewrite /eqAmod addrAC opprD !addrA subrK. Qed. Lemma eqAmodDl e x y z : (x + y == x + z %[mod e])%A = (y == z %[mod e])%A. Proof. by rewrite !(addrC x) eqAmodDr. Qed. Lemma eqAmodD e x1 x2 y1 y2 : (x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 + y1 == x2 + y2 %[mod e])%A. Proof. by rewrite -(eqAmodDl e x2 y1) -(eqAmodDr e y1); apply: eqAmod_trans. Qed. Lemma eqAmodm0 e : (e == 0 %[mod e])%A. Proof. by rewrite /eqAmod subr0 unfold_in; case: ifPn => // /divff->. Qed. #[global] Hint Resolve eqAmodm0 : core. Lemma eqAmodMr e : {in Aint, forall z x y, x == y %[mod e] -> x * z == y * z %[mod e]}%A. Proof. move=> z Zz x y. rewrite /eqAmod -mulrBl ![(e %| _)%A]unfold_in mulf_eq0 mulrAC. by case: ifP => [_ -> // | _ Exy]; apply: rpredM. Qed. Lemma eqAmodMl e : {in Aint, forall z x y, x == y %[mod e] -> z * x == z * y %[mod e]}%A. Proof. by move=> z Zz x y Exy; rewrite !(mulrC z) eqAmodMr. Qed. Lemma eqAmodMl0 e : {in Aint, forall x, x * e == 0 %[mod e]}%A. Proof. by move=> x Zx; rewrite -(mulr0 x) eqAmodMl. Qed. Lemma eqAmodMr0 e : {in Aint, forall x, e * x == 0 %[mod e]}%A. Proof. by move=> x Zx; rewrite /= mulrC eqAmodMl0. Qed. Lemma eqAmod_addl_mul e : {in Aint, forall x y, x * e + y == y %[mod e]}%A. Proof. by move=> x Zx y; rewrite -{2}[y]add0r eqAmodDr eqAmodMl0. Qed. Lemma eqAmodM e : {in Aint &, forall x1 y2 x2 y1, x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 * y1 == x2 * y2 %[mod e]}%A. Proof. move=> x1 y2 Zx1 Zy2 x2 y1 eq_x /(eqAmodMl Zx1)/eqAmod_trans-> //. exact: eqAmodMr. Qed. Lemma eqAmod_rat : {in Crat & &, forall e m n, (m == n %[mod e])%A = (m == n %[mod e])%C}. Proof. move=> e m n Qe Qm Qn; rewrite /eqCmod unfold_in /eqAmod unfold_in. case: ifPn => // nz_e; apply/idP/idP=> [/Cint_rat_Aint | /Aint_Cint] -> //. by rewrite rpred_div ?rpredB. Qed. Lemma eqAmod0_rat : {in Crat &, forall e n, (n == 0 %[mod e])%A = (e %| n)%C}. Proof. by move=> e n Qe Qn; rewrite /= eqAmod_rat /eqCmod ?subr0 ?Crat0. Qed. Lemma eqAmod_nat (e m n : nat) : (m == n %[mod e])%A = (m == n %[mod e])%N. Proof. by rewrite eqAmod_rat ?rpred_nat // eqCmod_nat. Qed. Lemma eqAmod0_nat (e m : nat) : (m == 0 %[mod e])%A = (e %| m)%N. Proof. by rewrite eqAmod0_rat ?rpred_nat // dvdC_nat. Qed. (* Multiplicative order. *) Definition orderC x := let p := minCpoly x in oapp val 0 [pick n : 'I_(2 * size p ^ 2) | p == intrp 'Phi_n]. Notation "#[ x ]" := (orderC x) : C_scope. Lemma exp_orderC x : x ^+ #[x]%C = 1. Proof. rewrite /orderC; case: pickP => //= [] [n _] /= /eqP Dp. have n_gt0: (0 < n)%N. rewrite lt0n; apply: contraTneq (size_minCpoly x) => n0. by rewrite Dp n0 Cyclotomic0 rmorph1 size_poly1. have [z prim_z] := C_prim_root_exists n_gt0. rewrite prim_expr_order // -(root_cyclotomic prim_z). by rewrite -Cintr_Cyclotomic // -Dp root_minCpoly. Qed. Lemma dvdn_orderC x n : (#[x]%C %| n)%N = (x ^+ n == 1). Proof. apply/idP/eqP=> [|x_n_1]; first by apply: expr_dvd; apply: exp_orderC. have [-> | n_gt0] := posnP n; first by rewrite dvdn0. have [m prim_x m_dv_n] := prim_order_exists n_gt0 x_n_1. have{n_gt0} m_gt0 := dvdn_gt0 n_gt0 m_dv_n; congr (_ %| n)%N: m_dv_n. pose p := minCpoly x; have Dp: p = cyclotomic x m := minCpoly_cyclotomic prim_x. rewrite /orderC; case: pickP => /= [k /eqP Dp_k | no_k]; last first. suffices lt_m_2p: (m < 2 * size p ^ 2)%N. have /eqP[] := no_k (Ordinal lt_m_2p). by rewrite /= -/p Dp -Cintr_Cyclotomic. rewrite Dp size_cyclotomic (sqrnD 1) addnAC mulnDr -add1n leq_add //. suffices: (m <= \prod_(q <- primes m | q == 2) q * totient m ^ 2)%N. have [m_even | m_odd] := boolP (2%N \in primes m). by rewrite -big_filter filter_pred1_uniq ?primes_uniq // big_seq1. by rewrite big_hasC ?has_pred1 // => /leq_trans-> //; apply: leq_addl. rewrite big_mkcond totientE // -mulnn -!big_split /=. rewrite {1}[m]prod_prime_decomp // prime_decompE big_map /= !big_seq. elim/big_ind2: _ => // [n1 m1 n2 m2 | q]; first exact: leq_mul. rewrite mem_primes => /and3P[q_pr _ q_dv_m]. rewrite lognE q_pr m_gt0 q_dv_m /=; move: (logn q _) => k. rewrite !mulnA expnS leq_mul //. case: (ltngtP q 2) (prime_gt1 q_pr) => // [q_gt2|->] _. rewrite mul1n mulnAC mulnn -{1}[q]muln1 leq_mul ?expn_gt0 ?prime_gt0 //. by rewrite -(subnKC q_gt2) (ltn_exp2l 1). by rewrite !muln1 -expnS (ltn_exp2l 0). have k_prim_x: k.-primitive_root x. have k_gt0: (0 < k)%N. rewrite lt0n; apply: contraTneq (size_minCpoly x) => k0. by rewrite Dp_k k0 Cyclotomic0 rmorph1 size_poly1. have [z prim_z] := C_prim_root_exists k_gt0. rewrite -(root_cyclotomic prim_z) -Cintr_Cyclotomic //. by rewrite -Dp_k root_minCpoly. apply/eqP; rewrite eqn_dvd !(@prim_order_dvd _ _ x) //. by rewrite !prim_expr_order ?eqxx. Qed.
CharacteristicFunction.lean
/- Copyright (c) 2024 Jakob Stiefel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob Stiefel, Rémy Degenne, Thomas Zhu -/ import Mathlib.Analysis.Fourier.BoundedContinuousFunctionChar import Mathlib.Analysis.Fourier.FourierTransform import Mathlib.Analysis.InnerProductSpace.Dual import Mathlib.MeasureTheory.Group.IntegralConvolution import Mathlib.MeasureTheory.Measure.FiniteMeasureExt /-! # Characteristic Function of a Finite Measure This file defines the characteristic function of a finite measure on a topological vector space `V`. The characteristic function of a finite measure `P` on `V` is the mapping `W → ℂ, w => ∫ v, e (L v w) ∂P`, where `e` is a continuous additive character and `L : V →ₗ[ℝ] W →ₗ[ℝ] ℝ` is a bilinear map. A typical example is `V = W = ℝ` and `L v w = v * w`. The integral is expressed as `∫ v, char he hL w v ∂P`, where `char he hL w` is the bounded continuous function `fun v ↦ e (L v w)` and `he`, `hL` are continuity hypotheses on `e` and `L`. ## Main definitions * `innerProbChar`: the bounded continuous map `x ↦ exp(⟪x, t⟫ * I)` in an inner product space. This is `char` for the inner product bilinear map and the additive character `e = probChar`. * `charFun μ t`: the characteristic function of a measure `μ` at `t` in an inner product space `E`. This is defined as `∫ x, exp (⟪x, t⟫ * I) ∂μ`, where `⟪x, t⟫` is the inner product on `E`. It is equal to `∫ v, innerProbChar w v ∂P` (see `charFun_eq_integral_innerProbChar`). * `probCharDual`: the bounded continuous map `x ↦ exp (L x * I)`, for a continuous linear form `L`. * `charFunDual μ L`: the characteristic function of a measure `μ` at `L : Dual ℝ E` in a normed space `E`. This is the integral `∫ v, exp (L v * I) ∂μ`. ## Main statements * `ext_of_integral_char_eq`: Assume `e` and `L` are non-trivial. If the integrals of `char` with respect to two finite measures `P` and `P'` coincide, then `P = P'`. * `Measure.ext_of_charFun`: If the characteristic functions `charFun` of two finite measures `μ` and `ν` on a complete second-countable inner product space coincide, then `μ = ν`. * `Measure.ext_of_charFunDual`: If the characteristic functions `charFunDual` of two finite measures `μ` and `ν` on a Banach space coincide, then `μ = ν`. -/ open BoundedContinuousFunction RealInnerProductSpace Real Complex ComplexConjugate NormedSpace namespace BoundedContinuousFunction variable {E F : Type*} [SeminormedAddCommGroup E] [InnerProductSpace ℝ E] [SeminormedAddCommGroup F] [NormedSpace ℝ F] /-- The bounded continuous map `x ↦ exp(⟪x, t⟫ * I)`. -/ noncomputable def innerProbChar (t : E) : E →ᵇ ℂ := char continuous_probChar (L := bilinFormOfRealInner) continuous_inner t lemma innerProbChar_apply (t x : E) : innerProbChar t x = exp (⟪x, t⟫ * I) := rfl @[simp] lemma innerProbChar_zero : innerProbChar (0 : E) = 1 := by simp [innerProbChar] /-- The bounded continuous map `x ↦ exp (L x * I)`, for a continuous linear form `L`. -/ noncomputable def probCharDual (L : StrongDual ℝ F) : F →ᵇ ℂ := char continuous_probChar (L := isBoundedBilinearMap_apply.symm.toContinuousLinearMap.toLinearMap₁₂) isBoundedBilinearMap_apply.symm.continuous L lemma probCharDual_apply (L : StrongDual ℝ F) (x : F) : probCharDual L x = exp (L x * I) := rfl @[simp] lemma probCharDual_zero : probCharDual (0 : StrongDual ℝ F) = 1 := by simp [probCharDual] end BoundedContinuousFunction namespace MeasureTheory variable {W : Type*} [AddCommGroup W] [Module ℝ W] [TopologicalSpace W] {e : AddChar ℝ Circle} section ext variable {V : Type*} [AddCommGroup V] [Module ℝ V] [PseudoEMetricSpace V] [MeasurableSpace V] [BorelSpace V] [CompleteSpace V] [SecondCountableTopology V] {L : V →ₗ[ℝ] W →ₗ[ℝ] ℝ} /-- If the integrals of `char` with respect to two finite measures `P` and `P'` coincide, then `P = P'`. -/ theorem ext_of_integral_char_eq (he : Continuous e) (he' : e ≠ 1) (hL' : ∀ v ≠ 0, L v ≠ 0) (hL : Continuous fun p : V × W ↦ L p.1 p.2) {P P' : Measure V} [IsFiniteMeasure P] [IsFiniteMeasure P'] (h : ∀ w, ∫ v, char he hL w v ∂P = ∫ v, char he hL w v ∂P') : P = P' := by apply ext_of_forall_mem_subalgebra_integral_eq_of_pseudoEMetric_complete_countable (separatesPoints_charPoly he he' hL hL') intro _ hg simp only [mem_charPoly] at hg obtain ⟨w, hw⟩ := hg rw [hw] have hsum (P : Measure V) [IsFiniteMeasure P] : ∫ v, ∑ a ∈ w.support, w a * e (L v a) ∂P = ∑ a ∈ w.support, ∫ v, w a * e (L v a) ∂P := integral_finset_sum w.support fun a ha => Integrable.const_mul (integrable P (char he hL a)) _ rw [hsum P, hsum P'] apply Finset.sum_congr rfl fun i _ => ?_ simp only [MeasureTheory.integral_const_mul, mul_eq_mul_left_iff] exact Or.inl (h i) end ext section InnerProductSpace variable {E : Type*} {mE : MeasurableSpace E} {μ : Measure E} {t : E} /-- The characteristic function of a measure in an inner product space. -/ noncomputable def charFun [Inner ℝ E] (μ : Measure E) (t : E) : ℂ := ∫ x, exp (⟪x, t⟫ * I) ∂μ lemma charFun_apply [Inner ℝ E] (t : E) : charFun μ t = ∫ x, exp (⟪x, t⟫ * I) ∂μ := rfl lemma charFun_apply_real {μ : Measure ℝ} (t : ℝ) : charFun μ t = ∫ x, exp (t * x * I) ∂μ := by simp [charFun_apply] variable [SeminormedAddCommGroup E] [InnerProductSpace ℝ E] @[simp] lemma charFun_zero (μ : Measure E) : charFun μ 0 = μ.real Set.univ := by simp [charFun_apply] @[simp] lemma charFun_zero_measure : charFun (0 : Measure E) t = 0 := by simp [charFun_apply] @[simp] lemma charFun_neg (t : E) : charFun μ (-t) = conj (charFun μ t) := by simp [charFun_apply, ← integral_conj, ← exp_conj] /-- `charFun` as the integral of a bounded continuous function. -/ lemma charFun_eq_integral_innerProbChar : charFun μ t = ∫ v, innerProbChar t v ∂μ := by simp [charFun_apply, innerProbChar_apply] lemma charFun_eq_integral_probChar (t : E) : charFun μ t = ∫ x, (probChar ⟪x, t⟫ : ℂ) ∂μ := by simp [charFun_apply, probChar_apply] /-- `charFun` is a Fourier integral for the inner product and the character `probChar`. -/ lemma charFun_eq_fourierIntegral (t : E) : charFun μ t = VectorFourier.fourierIntegral probChar μ bilinFormOfRealInner 1 (-t) := by simp [charFun_apply, VectorFourier.fourierIntegral_probChar] /-- `charFun` is a Fourier integral for the inner product and the character `fourierChar`. -/ lemma charFun_eq_fourierIntegral' (t : E) : charFun μ t = VectorFourier.fourierIntegral fourierChar μ bilinFormOfRealInner 1 (-(2 * π)⁻¹ • t) := by simp only [charFun_apply, VectorFourier.fourierIntegral, neg_smul, bilinFormOfRealInner_apply_apply, inner_neg_right, inner_smul_right, neg_neg, fourierChar_apply', Pi.ofNat_apply, Circle.smul_def, Circle.coe_exp, ofReal_mul, ofReal_ofNat, ofReal_inv, smul_eq_mul, mul_one] congr with x rw [← mul_assoc, mul_inv_cancel₀ (by simp [pi_ne_zero]), one_mul] lemma norm_charFun_le (t : E) : ‖charFun μ t‖ ≤ μ.real Set.univ := by rw [charFun_eq_fourierIntegral] exact (VectorFourier.norm_fourierIntegral_le_integral_norm _ _ _ _ _).trans_eq (by simp) lemma norm_charFun_le_one [IsProbabilityMeasure μ] (t : E) : ‖charFun μ t‖ ≤ 1 := (norm_charFun_le _).trans_eq (by simp) lemma norm_one_sub_charFun_le_two [IsProbabilityMeasure μ] : ‖1 - charFun μ t‖ ≤ 2 := calc ‖1 - charFun μ t‖ _ ≤ ‖(1 : ℂ)‖ + ‖charFun μ t‖ := norm_sub_le _ _ _ ≤ 1 + 1 := by simp [norm_charFun_le_one] _ = 2 := by norm_num @[fun_prop, measurability] lemma stronglyMeasurable_charFun [OpensMeasurableSpace E] [SecondCountableTopology E] [SFinite μ] : StronglyMeasurable (charFun μ) := (Measurable.stronglyMeasurable (by fun_prop)).integral_prod_left @[fun_prop, measurability] lemma measurable_charFun [OpensMeasurableSpace E] [SecondCountableTopology E] [SFinite μ] : Measurable (charFun μ) := stronglyMeasurable_charFun.measurable lemma intervalIntegrable_charFun {μ : Measure ℝ} [IsFiniteMeasure μ] {a b : ℝ} : IntervalIntegrable (charFun μ) volume a b := IntervalIntegrable.mono_fun' (g := fun _ ↦ μ.real Set.univ) (by simp) stronglyMeasurable_charFun.aestronglyMeasurable (ae_of_all _ norm_charFun_le) lemma charFun_map_smul [BorelSpace E] [SecondCountableTopology E] (r : ℝ) (t : E) : charFun (μ.map (r • ·)) t = charFun μ (r • t) := by rw [charFun_apply, charFun_apply, integral_map (by fun_prop) (Measurable.aestronglyMeasurable <| by fun_prop)] simp_rw [inner_smul_right, ← real_inner_smul_left] lemma charFun_map_mul {μ : Measure ℝ} (r t : ℝ) : charFun (μ.map (r * ·)) t = charFun μ (r * t) := charFun_map_smul r t variable {E : Type*} [MeasurableSpace E] {μ ν : Measure E} {t : E} [NormedAddCommGroup E] [InnerProductSpace ℝ E] @[simp] lemma charFun_dirac [OpensMeasurableSpace E] {x : E} (t : E) : charFun (Measure.dirac x) t = cexp (⟪x, t⟫ * I) := by rw [charFun_apply, integral_dirac] lemma charFun_map_add_const [BorelSpace E] (r t : E) : charFun (μ.map (· + r)) t = charFun μ t * cexp (⟪r, t⟫ * I) := by rw [charFun_apply, charFun_apply, integral_map (by fun_prop) (by fun_prop), ← integral_mul_const] congr with a rw [← Complex.exp_add] congr rw [inner_add_left] simp only [ofReal_add] ring lemma charFun_map_const_add [BorelSpace E] (r t : E) : charFun (μ.map (r + ·)) t = charFun μ t * cexp (⟪r, t⟫ * I) := by simp_rw [add_comm r] exact charFun_map_add_const _ _ variable [BorelSpace E] [SecondCountableTopology E] /-- If the characteristic functions `charFun` of two finite measures `μ` and `ν` on a complete second-countable inner product space coincide, then `μ = ν`. -/ theorem Measure.ext_of_charFun [CompleteSpace E] [IsFiniteMeasure μ] [IsFiniteMeasure ν] (h : charFun μ = charFun ν) : μ = ν := by simp_rw [funext_iff, charFun_eq_integral_innerProbChar] at h refine ext_of_integral_char_eq continuous_probChar probChar_ne_one (L := bilinFormOfRealInner) ?_ ?_ h · exact fun v hv ↦ DFunLike.ne_iff.mpr ⟨v, inner_self_ne_zero.mpr hv⟩ · exact continuous_inner /-- The characteristic function of a convolution of measures is the product of the respective characteristic functions. -/ lemma charFun_conv [IsFiniteMeasure μ] [IsFiniteMeasure ν] (t : E) : charFun (μ ∗ ν) t = charFun μ t * charFun ν t := by simp_rw [charFun_apply] rw [integral_conv] · simp [inner_add_left, add_mul, Complex.exp_add, integral_const_mul, integral_mul_const] · exact (integrable_const (1 : ℝ)).mono (by fun_prop) (by simp) end InnerProductSpace section NormedSpace variable {E F : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] {mE : MeasurableSpace E} [NormedAddCommGroup F] [NormedSpace ℝ F] {mF : MeasurableSpace F} {μ : Measure E} {ν : Measure F} /-- The characteristic function of a measure in a normed space, function from `StrongDual ℝ E` to `ℂ` with `charFunDual μ L = ∫ v, exp (L v * I) ∂μ`. -/ noncomputable def charFunDual (μ : Measure E) (L : StrongDual ℝ E) : ℂ := ∫ v, probCharDual L v ∂μ lemma charFunDual_apply (L : StrongDual ℝ E) : charFunDual μ L = ∫ v, exp (L v * I) ∂μ := rfl lemma charFunDual_eq_charFun_map_one [OpensMeasurableSpace E] (L : StrongDual ℝ E) : charFunDual μ L = charFun (μ.map L) 1 := by rw [charFunDual_apply] have : ∫ x, cexp (L x * I) ∂μ = ∫ x, cexp (x * I) ∂(μ.map L) := by rw [integral_map] · fun_prop · exact Measurable.aestronglyMeasurable <| by fun_prop rw [this, charFun_apply] simp lemma charFun_map_eq_charFunDual_smul [OpensMeasurableSpace E] (L : StrongDual ℝ E) (u : ℝ) : charFun (μ.map L) u = charFunDual μ (u • L) := by rw [charFunDual_apply] have : ∫ x, cexp ((u • L) x * I) ∂μ = ∫ x, cexp (u * x * I) ∂(μ.map L) := by rw [integral_map] · simp · fun_prop · exact Measurable.aestronglyMeasurable <| by fun_prop rw [this, charFun_apply] simp lemma charFun_eq_charFunDual_toDualMap {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] {mE : MeasurableSpace E} {μ : Measure E} (t : E) : charFun μ t = charFunDual μ (InnerProductSpace.toDualMap ℝ E t) := by simp [charFunDual_apply, charFun_apply, real_inner_comm] lemma charFunDual_map [OpensMeasurableSpace E] [BorelSpace F] (L : E →L[ℝ] F) (L' : StrongDual ℝ F) : charFunDual (μ.map L) L' = charFunDual μ (L'.comp L) := by rw [charFunDual_eq_charFun_map_one, charFunDual_eq_charFun_map_one, Measure.map_map (by fun_prop) (by fun_prop)] simp @[simp] lemma charFunDual_dirac [OpensMeasurableSpace E] {x : E} (L : StrongDual ℝ E) : charFunDual (Measure.dirac x) L = cexp (L x * I) := by rw [charFunDual_apply, integral_dirac] lemma charFunDual_map_add_const [BorelSpace E] (r : E) (L : StrongDual ℝ E) : charFunDual (μ.map (· + r)) L = charFunDual μ L * cexp (L r * I) := by rw [charFunDual_apply, charFunDual_apply, integral_map (by fun_prop) (by fun_prop), ← integral_mul_const] congr with a rw [← Complex.exp_add] congr simp only [map_add, ofReal_add] ring lemma charFunDual_map_const_add [BorelSpace E] (r : E) (L : StrongDual ℝ E) : charFunDual (μ.map (r + ·)) L = charFunDual μ L * cexp (L r * I) := by simp_rw [add_comm r] exact charFunDual_map_add_const _ _ /-- The characteristic function of a product of measures is a product of characteristic functions. -/ lemma charFunDual_prod [SFinite μ] [SFinite ν] (L : StrongDual ℝ (E × F)) : charFunDual (μ.prod ν) L = charFunDual μ (L.comp (.inl ℝ E F)) * charFunDual ν (L.comp (.inr ℝ E F)) := by let L₁ : StrongDual ℝ E := L.comp (.inl ℝ E F) let L₂ : StrongDual ℝ F := L.comp (.inr ℝ E F) simp_rw [charFunDual_apply, ← L.comp_inl_add_comp_inr, ofReal_add, add_mul, Complex.exp_add] rw [integral_prod_mul (f := fun x ↦ cexp ((L₁ x * I))) (g := fun x ↦ cexp ((L₂ x * I)))] variable [BorelSpace E] [SecondCountableTopology E] /-- If two finite measures have the same characteristic function, then they are equal. -/ theorem Measure.ext_of_charFunDual [CompleteSpace E] {μ ν : Measure E} [IsFiniteMeasure μ] [IsFiniteMeasure ν] (h : charFunDual μ = charFunDual ν) : μ = ν := by refine ext_of_integral_char_eq continuous_probChar probChar_ne_one ?_ ?_ (fun L ↦ funext_iff.mp h L) · intro v hv rw [ne_eq, LinearMap.ext_iff] simp only [ContinuousLinearMap.toLinearMap₁₂_apply, LinearMap.zero_apply, not_forall] change ∃ L : StrongDual ℝ E, L v ≠ 0 by_contra! h exact hv (NormedSpace.eq_zero_of_forall_dual_eq_zero _ h) · exact isBoundedBilinearMap_apply.symm.continuous /-- The characteristic function of a convolution of measures is the product of the respective characteristic functions. -/ lemma charFunDual_conv {μ ν : Measure E} [IsFiniteMeasure μ] [IsFiniteMeasure ν] (L : StrongDual ℝ E) : charFunDual (μ ∗ ν) L = charFunDual μ L * charFunDual ν L := by simp_rw [charFunDual_apply] rw [integral_conv] · simp [add_mul, Complex.exp_add, integral_const_mul, integral_mul_const] · exact (integrable_const (1 : ℝ)).mono (by fun_prop) (by simp) end NormedSpace end MeasureTheory
PowTransition.lean
/- Copyright (c) 2025 Jiedong Jiang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nailin Guan, Jiedong Jiang -/ import Mathlib.LinearAlgebra.Quotient.Basic import Mathlib.RingTheory.Ideal.Quotient.Defs import Mathlib.Algebra.Algebra.Operations import Mathlib.RingTheory.Ideal.Operations import Mathlib.RingTheory.Ideal.Maps /-! # The quotient map from `R ⧸ I ^ m` to `R ⧸ I ^ n` where `m ≥ n` In this file we define the canonical quotient linear map from `M ⧸ I ^ m • ⊤` to `M ⧸ I ^ n • ⊤` and canonical quotient ring map from `R ⧸ I ^ m` to `R ⧸ I ^ n`. These definitions will be used in theorems related to `IsAdicComplete` to find a lift element from compatible sequences in the quotients. We also include results about the relation between quotients of submodules and quotients of ideals here. ## Main definitions - `Submodule.factorPow`: the linear map from `M ⧸ I ^ m • ⊤` to `M ⧸ I ^ n • ⊤` induced by the natural inclusion `I ^ n • ⊤ → I ^ m • ⊤`. - `Ideal.Quotient.factorPow`: the ring homomorphism from `R ⧸ I ^ m` to `R ⧸ I ^ n` induced by the natural inclusion `I ^ n → I ^ m`. ## Main results -/ /- Since `Mathlib/LinearAlgebra/Quotient/Basic.lean` and `Mathlib/RingTheory/Ideal/Quotient/Defs.lean` do not import each other, and the first file that imports both of them is `Mathlib/RingTheory/Ideal/Quotient/Operations.lean`, which has already established the first isomophism theorem and Chinese remainder theorem, we put these pure technical lemmas that involves both `Submodule.mapQ` and `Ideal.Quotient.factor` in this file. -/ open Ideal Quotient variable {R : Type*} [Ring R] {I J K : Ideal R} {M : Type*} [AddCommGroup M] [Module R M] lemma Ideal.Quotient.factor_ker (H : I ≤ J) [I.IsTwoSided] [J.IsTwoSided] : RingHom.ker (factor H) = J.map (Ideal.Quotient.mk I) := by ext x refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · rcases Ideal.Quotient.mk_surjective x with ⟨r, hr⟩ rw [← hr] at h ⊢ simp only [factor, RingHom.mem_ker, lift_mk, eq_zero_iff_mem] at h exact Ideal.mem_map_of_mem _ h · rcases mem_image_of_mem_map_of_surjective _ Ideal.Quotient.mk_surjective h with ⟨r, hr, eq⟩ simpa [← eq, Ideal.Quotient.eq_zero_iff_mem] using hr lemma Ideal.map_mk_comap_factor [J.IsTwoSided] [K.IsTwoSided] (hIJ : J ≤ I) (hJK : K ≤ J) : (I.map (mk J)).comap (factor hJK) = I.map (mk K) := by ext x refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · rcases mem_image_of_mem_map_of_surjective (mk J) Quotient.mk_surjective h with ⟨r, hr, eq⟩ have : x - ((mk K) r) ∈ J.map (mk K) := by simp [← factor_ker hJK, ← eq] rcases mem_image_of_mem_map_of_surjective (mk K) Quotient.mk_surjective this with ⟨s, hs, eq'⟩ rw [← add_sub_cancel ((mk K) r) x, ← eq', ← map_add] exact mem_map_of_mem (mk K) (Submodule.add_mem _ hr (hIJ hs)) · rcases mem_image_of_mem_map_of_surjective (mk K) Quotient.mk_surjective h with ⟨r, hr, eq⟩ simpa only [← eq] using mem_map_of_mem (mk J) hr namespace Submodule open Submodule section @[simp] theorem mapQ_eq_factor (h : I ≤ J) (x : R ⧸ I) : mapQ I J LinearMap.id h x = factor h x := rfl end variable (I M) lemma pow_smul_top_le {m n : ℕ} (h : m ≤ n) : (I ^ n • ⊤ : Submodule R M) ≤ I ^ m • ⊤ := smul_mono_left (Ideal.pow_le_pow_right h) /-- The linear map from `M ⧸ I ^ m • ⊤` to `M ⧸ I ^ n • ⊤` induced by the natural inclusion `I ^ n • ⊤ → I ^ m • ⊤`. To future contributors: Before adding lemmas related to `Submodule.factorPow`, please check whether it can be generalized to `Submodule.factor` and whether the corresponding (more general) lemma for `Submodule.factor` already exists. -/ abbrev factorPow {m n : ℕ} (le : m ≤ n) : M ⧸ (I ^ n • ⊤ : Submodule R M) →ₗ[R] M ⧸ (I ^ m • ⊤ : Submodule R M) := factor (smul_mono_left (Ideal.pow_le_pow_right le)) /-- `factorPow` for `n = m + 1` -/ abbrev factorPowSucc (m : ℕ) : M ⧸ (I ^ (m + 1) • ⊤ : Submodule R M) →ₗ[R] M ⧸ (I ^ m • ⊤ : Submodule R M) := factorPow I M (Nat.le_succ m) end Submodule namespace Ideal namespace Quotient variable [I.IsTwoSided] variable (I) /-- The ring homomorphism from `R ⧸ I ^ m` to `R ⧸ I ^ n` induced by the natural inclusion `I ^ n → I ^ m`. To future contributors: Before adding lemmas related to `Ideal.factorPow`, please check whether it can be generalized to `Ideal.factor` and whether the corresponding (more general) lemma for `Ideal.factor` already exists. -/ abbrev factorPow {m n : ℕ} (le : n ≤ m) : R ⧸ I ^ m →+* R ⧸ I ^ n := factor (pow_le_pow_right le) /-- `factorPow` for `m = n + 1` -/ abbrev factorPowSucc (n : ℕ) : R ⧸ I ^ (n + 1) →+* R ⧸ I ^ n := factorPow I (Nat.le_succ n) end Quotient end Ideal variable {R : Type*} [CommRing R] (I : Ideal R) lemma Ideal.map_mk_comap_factorPow {a b : ℕ} (apos : 0 < a) (le : a ≤ b) : (I.map (mk (I ^ a))).comap (factorPow I le) = I.map (mk (I ^ b)) := by apply Ideal.map_mk_comap_factor exact pow_le_self (Nat.ne_zero_of_lt apos) variable {I} in lemma factorPowSucc.isUnit_of_isUnit_image {n : ℕ} (npos : n > 0) {a : R ⧸ I ^ (n + 1)} (h : IsUnit (factorPow I n.le_succ a)) : IsUnit a := by rcases isUnit_iff_exists.mp h with ⟨b, hb, _⟩ rcases factor_surjective (pow_le_pow_right n.le_succ) b with ⟨b', hb'⟩ rw [← hb', ← map_one (factorPow I n.le_succ), ← map_mul] at hb apply (RingHom.sub_mem_ker_iff (factorPow I n.le_succ)).mpr at hb rw [factor_ker (pow_le_pow_right n.le_succ)] at hb rcases Ideal.mem_image_of_mem_map_of_surjective (Ideal.Quotient.mk (I ^ (n + 1))) Ideal.Quotient.mk_surjective hb with ⟨c, hc, eq⟩ apply isUnit_of_mul_eq_one _ (b' * (1 - ((Ideal.Quotient.mk (I ^ (n + 1))) c))) calc _ = (a * b' - 1) * (1 - ((Ideal.Quotient.mk (I ^ (n + 1))) c)) + (1 - ((Ideal.Quotient.mk (I ^ (n + 1))) c)) := by ring _ = 1 := by rw [← eq, mul_sub, mul_one, sub_add_sub_cancel', sub_eq_self, ← map_mul, Ideal.Quotient.eq_zero_iff_mem, pow_add] apply Ideal.mul_mem_mul hc (Ideal.mul_le_left (I := I ^ (n - 1)) _) simpa only [← pow_add, Nat.sub_add_cancel npos] using hc
Disintegration.lean
/- Copyright (c) 2023 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.MeasureTheory.Measure.Haar.Basic import Mathlib.Analysis.Normed.Module.FiniteDimension import Mathlib.MeasureTheory.Measure.Haar.Unique /-! # Pushing a Haar measure by a linear map We show that the push-forward of an additive Haar measure in a vector space under a surjective linear map is proportional to the Haar measure on the target space, in `LinearMap.exists_map_addHaar_eq_smul_addHaar`. We deduce disintegration properties of the Haar measure: to check that a property is true ae, it suffices to check that it is true ae along all translates of a given vector subspace. See `MeasureTheory.ae_mem_of_ae_add_linearMap_mem`. TODO: this holds more generally in any locally compact group, see [Fremlin, *Measure Theory* (volume 4, 443Q)][fremlin_vol4] -/ open MeasureTheory Measure Set open scoped ENNReal variable {𝕜 E F : Type*} [NontriviallyNormedField 𝕜] [CompleteSpace 𝕜] [NormedAddCommGroup E] [MeasurableSpace E] [BorelSpace E] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [MeasurableSpace F] [BorelSpace F] [NormedSpace 𝕜 F] {L : E →ₗ[𝕜] F} {μ : Measure E} {ν : Measure F} [IsAddHaarMeasure μ] [IsAddHaarMeasure ν] variable [LocallyCompactSpace E] variable (L μ ν) /-- The image of an additive Haar measure under a surjective linear map is proportional to a given additive Haar measure. The proportionality factor will be infinite if the linear map has a nontrivial kernel. -/ theorem LinearMap.exists_map_addHaar_eq_smul_addHaar' (h : Function.Surjective L) : ∃ (c : ℝ≥0∞), 0 < c ∧ c < ∞ ∧ μ.map L = (c * addHaar (univ : Set (LinearMap.ker L))) • ν := by /- This is true for the second projection in product spaces, as the projection of the Haar measure `μS.prod μT` is equal to the Haar measure `μT` multiplied by the total mass of `μS`. This is also true for linear equivalences, as they map Haar measure to Haar measure. The general case follows from these two and linear algebra, as `L` can be interpreted as the composition of the projection `P` on a complement `T` to its kernel `S`, together with a linear equivalence. -/ have : FiniteDimensional 𝕜 E := .of_locallyCompactSpace 𝕜 have : ProperSpace F := by rcases subsingleton_or_nontrivial E with hE|hE · have : Subsingleton F := Function.Surjective.subsingleton h infer_instance · have : ProperSpace 𝕜 := .of_locallyCompact_module 𝕜 E have : FiniteDimensional 𝕜 F := Module.Finite.of_surjective L h exact FiniteDimensional.proper 𝕜 F let S : Submodule 𝕜 E := LinearMap.ker L obtain ⟨T, hT⟩ : ∃ T : Submodule 𝕜 E, IsCompl S T := Submodule.exists_isCompl S let M : (S × T) ≃ₗ[𝕜] E := Submodule.prodEquivOfIsCompl S T hT have M_cont : Continuous M.symm := LinearMap.continuous_of_finiteDimensional _ let P : S × T →ₗ[𝕜] T := LinearMap.snd 𝕜 S T have P_cont : Continuous P := LinearMap.continuous_of_finiteDimensional _ have I : Function.Bijective (LinearMap.domRestrict L T) := ⟨LinearMap.injective_domRestrict_iff.2 (IsCompl.inf_eq_bot hT.symm), (LinearMap.surjective_domRestrict_iff h).2 hT.symm.sup_eq_top⟩ let L' : T ≃ₗ[𝕜] F := LinearEquiv.ofBijective (LinearMap.domRestrict L T) I have L'_cont : Continuous L' := LinearMap.continuous_of_finiteDimensional _ have A : L = (L' : T →ₗ[𝕜] F).comp (P.comp (M.symm : E →ₗ[𝕜] (S × T))) := by ext x obtain ⟨y, z, hyz⟩ : ∃ (y : S) (z : T), M.symm x = (y, z) := ⟨_, _, rfl⟩ have : x = M (y, z) := by rw [← hyz]; simp only [LinearEquiv.apply_symm_apply] simp [L', P, M, this] have I : μ.map L = ((μ.map M.symm).map P).map L' := by rw [Measure.map_map, Measure.map_map, A] · rfl · exact L'_cont.measurable.comp P_cont.measurable · exact M_cont.measurable · exact L'_cont.measurable · exact P_cont.measurable let μS : Measure S := addHaar let μT : Measure T := addHaar obtain ⟨c₀, c₀_pos, c₀_fin, h₀⟩ : ∃ c₀ : ℝ≥0∞, c₀ ≠ 0 ∧ c₀ ≠ ∞ ∧ μ.map M.symm = c₀ • μS.prod μT := by have : IsAddHaarMeasure (μ.map M.symm) := M.toContinuousLinearEquiv.symm.isAddHaarMeasure_map μ refine ⟨addHaarScalarFactor (μ.map M.symm) (μS.prod μT), ?_, ENNReal.coe_ne_top, isAddLeftInvariant_eq_smul _ _⟩ simpa only [ne_eq, ENNReal.coe_eq_zero] using (addHaarScalarFactor_pos_of_isAddHaarMeasure (μ.map M.symm) (μS.prod μT)).ne' have J : (μS.prod μT).map P = (μS univ) • μT := map_snd_prod obtain ⟨c₁, c₁_pos, c₁_fin, h₁⟩ : ∃ c₁ : ℝ≥0∞, c₁ ≠ 0 ∧ c₁ ≠ ∞ ∧ μT.map L' = c₁ • ν := by have : IsAddHaarMeasure (μT.map L') := L'.toContinuousLinearEquiv.isAddHaarMeasure_map μT refine ⟨addHaarScalarFactor (μT.map L') ν, ?_, ENNReal.coe_ne_top, isAddLeftInvariant_eq_smul _ _⟩ simpa only [ne_eq, ENNReal.coe_eq_zero] using (addHaarScalarFactor_pos_of_isAddHaarMeasure (μT.map L') ν).ne' refine ⟨c₀ * c₁, by simp [pos_iff_ne_zero, c₀_pos, c₁_pos], ENNReal.mul_lt_top c₀_fin.lt_top c₁_fin.lt_top, ?_⟩ simp only [I, h₀, Measure.map_smul, J, smul_smul, h₁] rw [mul_assoc, mul_comm _ c₁, ← mul_assoc] /-- The image of an additive Haar measure under a surjective linear map is proportional to a given additive Haar measure, with a positive (but maybe infinite) factor. -/ theorem LinearMap.exists_map_addHaar_eq_smul_addHaar (h : Function.Surjective L) : ∃ (c : ℝ≥0∞), 0 < c ∧ μ.map L = c • ν := by rcases L.exists_map_addHaar_eq_smul_addHaar' μ ν h with ⟨c, c_pos, -, hc⟩ exact ⟨_, by simp [c_pos, NeZero.ne addHaar], hc⟩ namespace MeasureTheory /-- Given a surjective linear map `L`, it is equivalent to require a property almost everywhere in the source or the target spaces of `L`, with respect to additive Haar measures there. -/ lemma ae_comp_linearMap_mem_iff (h : Function.Surjective L) {s : Set F} (hs : MeasurableSet s) : (∀ᵐ x ∂μ, L x ∈ s) ↔ ∀ᵐ y ∂ν, y ∈ s := by have : FiniteDimensional 𝕜 E := .of_locallyCompactSpace 𝕜 have : AEMeasurable L μ := L.continuous_of_finiteDimensional.aemeasurable apply (ae_map_iff this hs).symm.trans rcases L.exists_map_addHaar_eq_smul_addHaar μ ν h with ⟨c, c_pos, hc⟩ rw [hc] exact ae_smul_measure_iff c_pos.ne' /-- Given a linear map `L : E → F`, a property holds almost everywhere in `F` if and only if, almost everywhere in `F`, it holds almost everywhere along the subspace spanned by the image of `L`. This is an instance of a disintegration argument for additive Haar measures. -/ lemma ae_ae_add_linearMap_mem_iff [LocallyCompactSpace F] {s : Set F} (hs : MeasurableSet s) : (∀ᵐ y ∂ν, ∀ᵐ x ∂μ, y + L x ∈ s) ↔ ∀ᵐ y ∂ν, y ∈ s := by have : FiniteDimensional 𝕜 E := .of_locallyCompactSpace 𝕜 have : FiniteDimensional 𝕜 F := .of_locallyCompactSpace 𝕜 have : ProperSpace E := .of_locallyCompactSpace 𝕜 have : ProperSpace F := .of_locallyCompactSpace 𝕜 let M : F × E →ₗ[𝕜] F := LinearMap.id.coprod L have M_cont : Continuous M := M.continuous_of_finiteDimensional -- Note: https://github.com/leanprover-community/mathlib4/pull/8386 had to change `range_eq_top` into -- `range_eq_top (f := _)` have hM : Function.Surjective M := by simp [M, ← LinearMap.range_eq_top (f := _), LinearMap.range_coprod] have A : ∀ x, M x ∈ s ↔ x ∈ M ⁻¹' s := fun x ↦ Iff.rfl simp_rw [← ae_comp_linearMap_mem_iff M (ν.prod μ) ν hM hs, A] rw [Measure.ae_prod_mem_iff_ae_ae_mem] · simp only [M, mem_preimage, LinearMap.coprod_apply, LinearMap.id_coe, id_eq] · exact M_cont.measurable hs /-- To check that a property holds almost everywhere with respect to an additive Haar measure, it suffices to check it almost everywhere along all translates of a given vector subspace. This is an instance of a disintegration argument for additive Haar measures. -/ lemma ae_mem_of_ae_add_linearMap_mem [LocallyCompactSpace F] {s : Set F} (hs : MeasurableSet s) (h : ∀ y, ∀ᵐ x ∂μ, y + L x ∈ s) : ∀ᵐ y ∂ν, y ∈ s := (ae_ae_add_linearMap_mem_iff L μ ν hs).1 (Filter.Eventually.of_forall h) end MeasureTheory
Linear.lean
/- Copyright (c) 2025 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.CategoryTheory.Localization.HasLocalization import Mathlib.CategoryTheory.Center.Localization import Mathlib.CategoryTheory.Center.Linear import Mathlib.CategoryTheory.Linear.LinearFunctor /-! # Localization of linear categories If `L : C ⥤ D` is an additive localization functor between preadditive categories, and `C` is `R`-linear, we show that `D` can also be equipped with a `R`-linear structure such that `L` is a `R`-linear functor. -/ universe w v₁ v₂ u₁ u₂ namespace CategoryTheory namespace Localization variable (R : Type w) [Ring R] {C : Type u₁} [Category.{v₁} C] {D : Type u₂} [Category.{v₂} D] [Preadditive C] [Preadditive D] (L : C ⥤ D) (W : MorphismProperty C) [L.IsLocalization W] [L.Additive] [Linear R C] /-- If `L : C ⥤ D` is a localization functor and `C` is `R`-linear, then `D` is `R`-linear if we already know that `D` is preadditive and `L` is additive. -/ noncomputable def linear : Linear R D := Linear.ofRingMorphism ((CatCenter.localizationRingHom L W).comp (Linear.toCatCenter R C)) lemma functor_linear : letI := linear R L W Functor.Linear R L := by letI := linear R L W constructor intro X Y f r change L.map (r • f) = ((Linear.toCatCenter R C r).localization L W).app (L.obj X) ≫ L.map f simp only [CatCenter.localization_app, ← L.map_comp, Functor.id_obj, Linear.toCatCenter_apply_app, Linear.smul_comp, Category.id_comp] section variable [Preadditive W.Localization] [W.Q.Additive] noncomputable instance : Linear R W.Localization := Localization.linear R W.Q W noncomputable instance : Functor.Linear R W.Q := Localization.functor_linear R W.Q W end section variable [W.HasLocalization] [Preadditive W.Localization'] [W.Q'.Additive] noncomputable instance : Linear R W.Localization' := Localization.linear R W.Q' W noncomputable instance : Functor.Linear R W.Q' := Localization.functor_linear R W.Q' W end section variable {E : Type*} [Category E] (L : C ⥤ D) (W : MorphismProperty C) [L.IsLocalization W] [Preadditive E] (R : Type*) [Ring R] [Linear R C] [Linear R D] [Linear R E] [L.Linear R] lemma functor_linear_iff (F : C ⥤ E) (G : D ⥤ E) [Lifting L W F G] : F.Linear R ↔ G.Linear R := by constructor · intro have : (L ⋙ G).Linear R := Functor.linear_of_iso _ (Lifting.iso L W F G).symm have := Localization.essSurj L W rw [Functor.linear_iff] intro X r have e := L.objObjPreimageIso X have : r • 𝟙 X = e.inv ≫ (r • 𝟙 _) ≫ e.hom := by simp rw [this, G.map_comp, G.map_comp, ← L.map_id, ← L.map_smul, ← Functor.comp_map, (L ⋙ G).map_smul, Functor.map_id, Linear.smul_comp, Linear.comp_smul] dsimp rw [Category.id_comp, ← G.map_comp, e.inv_hom_id, G.map_id] · intro exact Functor.linear_of_iso _ (Lifting.iso L W F G) end end Localization end CategoryTheory
Lp.lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import Mathlib.MeasureTheory.Function.SimpleFuncDenseLp import Mathlib.MeasureTheory.Function.StronglyMeasurable.Lemmas /-! # Finitely strongly measurable functions in `Lp` Functions in `Lp` for `0 < p < ∞` are finitely strongly measurable. ## Main statements * `MemLp.aefinStronglyMeasurable`: if `MemLp f p μ` with `0 < p < ∞`, then `AEFinStronglyMeasurable f μ`. * `Lp.finStronglyMeasurable`: for `0 < p < ∞`, `Lp` functions are finitely strongly measurable. ## References * [Hytönen, Tuomas, Jan Van Neerven, Mark Veraar, and Lutz Weis. Analysis in Banach spaces. Springer, 2016.][Hytonen_VanNeerven_Veraar_Wies_2016] -/ open MeasureTheory Filter TopologicalSpace Function open scoped ENNReal Topology MeasureTheory namespace MeasureTheory local infixr:25 " →ₛ " => SimpleFunc variable {α G : Type*} {p : ℝ≥0∞} {m m0 : MeasurableSpace α} {μ : Measure α} [NormedAddCommGroup G] {f : α → G} theorem MemLp.finStronglyMeasurable_of_stronglyMeasurable (hf : MemLp f p μ) (hf_meas : StronglyMeasurable f) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : FinStronglyMeasurable f μ := by borelize G haveI : SeparableSpace (Set.range f ∪ {0} : Set G) := hf_meas.separableSpace_range_union_singleton let fs := SimpleFunc.approxOn f hf_meas.measurable (Set.range f ∪ {0}) 0 (by simp) refine ⟨fs, ?_, ?_⟩ · have h_fs_Lp : ∀ n, MemLp (fs n) p μ := SimpleFunc.memLp_approxOn_range hf_meas.measurable hf exact fun n => (fs n).measure_support_lt_top_of_memLp (h_fs_Lp n) hp_ne_zero hp_ne_top · intro x apply SimpleFunc.tendsto_approxOn apply subset_closure simp @[deprecated (since := "2025-02-21")] alias Memℒp.finStronglyMeasurable_of_stronglyMeasurable := MemLp.finStronglyMeasurable_of_stronglyMeasurable theorem MemLp.aefinStronglyMeasurable (hf : MemLp f p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : AEFinStronglyMeasurable f μ := ⟨hf.aestronglyMeasurable.mk f, ((memLp_congr_ae hf.aestronglyMeasurable.ae_eq_mk).mp hf).finStronglyMeasurable_of_stronglyMeasurable hf.aestronglyMeasurable.stronglyMeasurable_mk hp_ne_zero hp_ne_top, hf.aestronglyMeasurable.ae_eq_mk⟩ @[deprecated (since := "2025-02-21")] alias Memℒp.aefinStronglyMeasurable := MemLp.aefinStronglyMeasurable theorem Integrable.aefinStronglyMeasurable (hf : Integrable f μ) : AEFinStronglyMeasurable f μ := (memLp_one_iff_integrable.mpr hf).aefinStronglyMeasurable one_ne_zero ENNReal.coe_ne_top theorem Lp.finStronglyMeasurable (f : Lp G p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : FinStronglyMeasurable f μ := (Lp.memLp f).finStronglyMeasurable_of_stronglyMeasurable (Lp.stronglyMeasurable f) hp_ne_zero hp_ne_top end MeasureTheory
Export.lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Init import Lean.CoreM import Lean.Util.FoldConsts /-! A rudimentary export format, adapted from <https://github.com/leanprover-community/lean/blob/master/doc/export_format.md> with support for lean 4 kernel primitives. -/ open Lean open Std (HashMap HashSet) namespace Lean namespace Export /- References -/ private opaque MethodsRefPointed : NonemptyType.{0} private def MethodsRef : Type := MethodsRefPointed.type inductive Entry | name (n : Name) | level (n : Level) | expr (n : Expr) | defn (n : Name) deriving Inhabited instance : Coe Name Entry := ⟨Entry.name⟩ instance : Coe Level Entry := ⟨Entry.level⟩ instance : Coe Expr Entry := ⟨Entry.expr⟩ structure Alloc (α) [BEq α] [Hashable α] where map : Std.HashMap α Nat next : Nat deriving Inhabited structure State where names : Alloc Name := ⟨(∅ : Std.HashMap Name Nat).insert Name.anonymous 0, 1⟩ levels : Alloc Level := ⟨(∅ : Std.HashMap Level Nat).insert levelZero 0, 1⟩ exprs : Alloc Expr defs : Std.HashSet Name stk : Array (Bool × Entry) deriving Inhabited class OfState (α : Type) [BEq α] [Hashable α] where get : State → Alloc α modify : (Alloc α → Alloc α) → State → State instance : OfState Name where get s := s.names modify f s := { s with names := f s.names } instance : OfState Level where get s := s.levels modify f s := { s with levels := f s.levels } instance : OfState Expr where get s := s.exprs modify f s := { s with exprs := f s.exprs } end Export abbrev ExportM := StateT Export.State CoreM namespace Export def alloc {α} [BEq α] [Hashable α] [OfState α] (a : α) : ExportM Nat := do let n := (OfState.get (α := α) (← get)).next modify <| OfState.modify (α := α) fun s ↦ {map := s.map.insert a n, next := n + 1} pure n def exportName (n : Name) : ExportM Nat := do match (← get).names.map[n]? with | some i => pure i | none => match n with | .anonymous => pure 0 | .num p a => let i ← alloc n; IO.println s!"{i} #NI {← exportName p} {a}"; pure i | .str p s => let i ← alloc n; IO.println s!"{i} #NS {← exportName p} {s}"; pure i def exportLevel (L : Level) : ExportM Nat := do match (← get).levels.map[L]? with | some i => pure i | none => match L with | .zero => pure 0 | .succ l => let i ← alloc L; IO.println s!"{i} #US {← exportLevel l}"; pure i | .max l₁ l₂ => let i ← alloc L; IO.println s!"{i} #UM {← exportLevel l₁} {← exportLevel l₂}"; pure i | .imax l₁ l₂ => let i ← alloc L; IO.println s!"{i} #UIM {← exportLevel l₁} {← exportLevel l₂}"; pure i | .param n => let i ← alloc L; IO.println s!"{i} #UP {← exportName n}"; pure i | .mvar _ => unreachable! def biStr : BinderInfo → String | BinderInfo.default => "#BD" | BinderInfo.implicit => "#BI" | BinderInfo.strictImplicit => "#BS" | BinderInfo.instImplicit => "#BC" open ConstantInfo in mutual partial def exportExpr (E : Expr) : ExportM Nat := do match (← get).exprs.map[E]? with | some i => pure i | none => match E with | .bvar n => let i ← alloc E; IO.println s!"{i} #EV {n}"; pure i | .fvar _ => unreachable! | .mvar _ => unreachable! | .sort l => let i ← alloc E; IO.println s!"{i} #ES {← exportLevel l}"; pure i | .const n ls => exportDef n let i ← alloc E let mut s := s!"{i} #EC {← exportName n}" for l in ls do s := s ++ s!" {← exportLevel l}" IO.println s; pure i | .app e₁ e₂ => let i ← alloc E; IO.println s!"{i} #EA {← exportExpr e₁} {← exportExpr e₂}"; pure i | .lam _ e₁ e₂ d => let i ← alloc E IO.println s!"{i} #EL {biStr d} {← exportExpr e₁} {← exportExpr e₂}"; pure i | .forallE _ e₁ e₂ d => let i ← alloc E IO.println s!"{i} #EP {biStr d} {← exportExpr e₁} {← exportExpr e₂}"; pure i | .letE _ e₁ e₂ e₃ _ => let i ← alloc E IO.println s!"{i} #EP {← exportExpr e₁} {← exportExpr e₂} {← exportExpr e₃}"; pure i | .lit (.natVal n) => let i ← alloc E; IO.println s!"{i} #EN {n}"; pure i | .lit (.strVal s) => let i ← alloc E; IO.println s!"{i} #ET {s}"; pure i | .mdata _ _ => unreachable! | .proj n k e => let i ← alloc E; IO.println s!"{i} #EJ {← exportName n} {k} {← exportExpr e}"; pure i partial def exportDef (n : Name) : ExportM Unit := do if (← get).defs.contains n then return let ci ← getConstInfo n for c in ci.value!.getUsedConstants do unless (← get).defs.contains c do exportDef c match ci with | axiomInfo val => axdef "#AX" val.name val.type val.levelParams | defnInfo val => defn "#DEF" val.name val.type val.value val.levelParams | thmInfo val => defn "#THM" val.name val.type val.value val.levelParams | opaqueInfo val => defn "#CN" val.name val.type val.value val.levelParams | quotInfo _ => IO.println "#QUOT" for n in [``Quot, ``Quot.mk, ``Quot.lift, ``Quot.ind] do insert n | inductInfo val => ind val.all | ctorInfo val => ind (← getConstInfoInduct val.induct).all | recInfo val => ind val.all where insert (n : Name) : ExportM Unit := modify fun s ↦ { s with defs := s.defs.insert n } defn (ty : String) (n : Name) (t e : Expr) (ls : List Name) : ExportM Unit := do let mut s := s!"{ty} {← exportName n} {← exportExpr t} {← exportExpr e}" for l in ls do s := s ++ s!" {← exportName l}" IO.println s insert n axdef (ty : String) (n : Name) (t : Expr) (ls : List Name) : ExportM Unit := do let mut s := s!"{ty} {← exportName n} {← exportExpr t}" for l in ls do s := s ++ s!" {← exportName l}" IO.println s insert n ind : List Name → ExportM Unit | [] => unreachable! | is@(i::_) => do let val ← getConstInfoInduct i let mut s := match is.length with | 1 => s!"#IND {val.numParams}" | n => s!"#MUT {val.numParams} {n}" for j in is do insert j; insert (mkRecName j) for j in is do let val ← getConstInfoInduct j s := s ++ s!" {← exportName val.name} {← exportExpr val.type} {val.ctors.length}" for c in val.ctors do insert c s := s ++ s!" {← exportName c} {← exportExpr (← getConstInfoCtor c).type}" for j in is do s ← indbody j s for l in val.levelParams do s := s ++ s!" {← exportName l}" IO.println s indbody (ind : Name) (s : String) : ExportM String := do let val ← getConstInfoInduct ind let mut s := s ++ s!" {← exportName ind} {← exportExpr val.type} {val.ctors.length}" for c in val.ctors do s := s ++ s!" {← exportName c} {← exportExpr (← getConstInfoCtor c).type}" pure s end def runExportM {α : Type} (m : ExportM α) : CoreM α := m.run' default -- #eval runExportM (exportDef `Lean.Expr) end Export end Lean
Basic.lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import Mathlib.Data.Set.Sigma import Mathlib.Order.Filter.Defs import Mathlib.Order.Filter.Map import Mathlib.Order.Interval.Set.Basic /-! # Basic results on filter bases A filter basis `B : FilterBasis α` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. Compared to filters, filter bases do not require that any set containing an element of `B` belongs to `B`. A filter basis `B` can be used to construct `B.filter : Filter α` such that a set belongs to `B.filter` if and only if it contains an element of `B`. Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → Set α`, the proposition `h : Filter.IsBasis p s` makes sure the range of `s` bounded by `p` (ie. `s '' setOf p`) defines a filter basis `h.filterBasis`. If one already has a filter `l` on `α`, `Filter.HasBasis l p s` (where `p : ι → Prop` and `s : ι → Set α` as above) means that a set belongs to `l` if and only if it contains some `s i` with `p i`. It implies `h : Filter.IsBasis p s`, and `l = h.filterBasis.filter`. The point of this definition is that checking statements involving elements of `l` often reduces to checking them on the basis elements. We define a function `HasBasis.index (h : Filter.HasBasis l p s) (t) (ht : t ∈ l)` that returns some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual destruction of `h.mem_iff.mpr ht` using `cases` or `let`. ## Main statements * `Filter.HasBasis.mem_iff`, `HasBasis.mem_of_superset`, `HasBasis.mem_of_mem` : restate `t ∈ f` in terms of a basis; * `Filter.HasBasis.le_iff`, `Filter.HasBasis.ge_iff`, `Filter.HasBasis.le_basis_iff` : restate `l ≤ l'` in terms of bases. * `Filter.basis_sets` : all sets of a filter form a basis; * `Filter.HasBasis.inf`, `Filter.HasBasis.inf_principal`, `Filter.HasBasis.prod`, `Filter.HasBasis.prod_self`, `Filter.HasBasis.map`, `Filter.HasBasis.comap` : combinators to construct filters of `l ⊓ l'`, `l ⊓ 𝓟 t`, `l ×ˢ l'`, `l ×ˢ l`, `l.map f`, `l.comap f` respectively; * `Filter.HasBasis.tendsto_right_iff`, `Filter.HasBasis.tendsto_left_iff`, `Filter.HasBasis.tendsto_iff` : restate `Tendsto f l l'` in terms of bases. ## Implementation notes As with `Set.iUnion`/`biUnion`/`Set.sUnion`, there are three different approaches to filter bases: * `Filter.HasBasis l s`, `s : Set (Set α)`; * `Filter.HasBasis l s`, `s : ι → Set α`; * `Filter.HasBasis l p s`, `p : ι → Prop`, `s : ι → Set α`. We use the latter one because, e.g., `𝓝 x` in an `EMetricSpace` or in a `MetricSpace` has a basis of this form. The other two can be emulated using `s = id` or `p = fun _ ↦ True`. With this approach sometimes one needs to `simp` the statement provided by the `Filter.HasBasis` machinery, e.g., `simp only [true_and_iff]` or `simp only [forall_const]` can help with the case `p = fun _ ↦ True`. ## Main statements -/ assert_not_exists Finset open Set Filter variable {α β γ : Type*} {ι ι' : Sort*} /-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure FilterBasis (α : Type*) where /-- Sets of a filter basis. -/ sets : Set (Set α) /-- The set of filter basis sets is nonempty. -/ nonempty : sets.Nonempty /-- The set of filter basis sets is directed downwards. -/ inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y instance FilterBasis.nonempty_sets (B : FilterBasis α) : Nonempty B.sets := B.nonempty.to_subtype /-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/ instance {α : Type*} : Membership (Set α) (FilterBasis α) := ⟨fun B U => U ∈ B.sets⟩ @[simp] theorem FilterBasis.mem_sets {s : Set α} {B : FilterBasis α} : s ∈ B.sets ↔ s ∈ B := Iff.rfl -- For illustration purposes, the filter basis defining `(atTop : Filter ℕ)` instance : Inhabited (FilterBasis ℕ) := ⟨{ sets := range Ici nonempty := ⟨Ici 0, mem_range_self 0⟩ inter_sets := by rintro _ _ ⟨n, rfl⟩ ⟨m, rfl⟩ exact ⟨Ici (max n m), mem_range_self _, Ici_inter_Ici.symm.subset⟩ }⟩ /-- View a filter as a filter basis. -/ def Filter.asBasis (f : Filter α) : FilterBasis α := ⟨f.sets, ⟨univ, univ_mem⟩, fun {x y} hx hy => ⟨x ∩ y, inter_mem hx hy, subset_rfl⟩⟩ -- TODO: consider adding `protected`? /-- `IsBasis p s` means the image of `s` bounded by `p` is a filter basis. -/ structure Filter.IsBasis (p : ι → Prop) (s : ι → Set α) : Prop where /-- There exists at least one `i` that satisfies `p`. -/ nonempty : ∃ i, p i /-- `s` is directed downwards on `i` such that `p i`. -/ inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j namespace Filter namespace IsBasis /-- Constructs a filter basis from an indexed family of sets satisfying `IsBasis`. -/ protected def filterBasis {p : ι → Prop} {s : ι → Set α} (h : IsBasis p s) : FilterBasis α where sets := { t | ∃ i, p i ∧ s i = t } nonempty := let ⟨i, hi⟩ := h.nonempty ⟨s i, ⟨i, hi, rfl⟩⟩ inter_sets := by rintro _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩ rcases h.inter hi hj with ⟨k, hk, hk'⟩ exact ⟨_, ⟨k, hk, rfl⟩, hk'⟩ variable {p : ι → Prop} {s : ι → Set α} (h : IsBasis p s) theorem mem_filterBasis_iff {U : Set α} : U ∈ h.filterBasis ↔ ∃ i, p i ∧ s i = U := Iff.rfl end IsBasis end Filter namespace FilterBasis /-- The filter associated to a filter basis. -/ protected def filter (B : FilterBasis α) : Filter α where sets := { s | ∃ t ∈ B, t ⊆ s } univ_sets := B.nonempty.imp fun s s_in => ⟨s_in, s.subset_univ⟩ sets_of_superset := fun ⟨s, s_in, h⟩ hxy => ⟨s, s_in, Set.Subset.trans h hxy⟩ inter_sets := fun ⟨_s, s_in, hs⟩ ⟨_t, t_in, ht⟩ => let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in ⟨u, u_in, u_sub.trans (inter_subset_inter hs ht)⟩ theorem mem_filter_iff (B : FilterBasis α) {U : Set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U := Iff.rfl theorem mem_filter_of_mem (B : FilterBasis α) {U : Set α} : U ∈ B → U ∈ B.filter := fun U_in => ⟨U, U_in, Subset.refl _⟩ theorem eq_iInf_principal (B : FilterBasis α) : B.filter = ⨅ s : B.sets, 𝓟 s := by have : Directed (· ≥ ·) fun s : B.sets => 𝓟 (s : Set α) := by rintro ⟨U, U_in⟩ ⟨V, V_in⟩ rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩ use ⟨W, W_in⟩ simp only [le_principal_iff, mem_principal] exact subset_inter_iff.mp W_sub ext U simp [mem_filter_iff, mem_iInf_of_directed this] protected theorem generate (B : FilterBasis α) : generate B.sets = B.filter := by apply le_antisymm · intro U U_in rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩ exact GenerateSets.superset (GenerateSets.basic V_in) h · rw [le_generate_iff] apply mem_filter_of_mem end FilterBasis namespace Filter namespace IsBasis variable {p : ι → Prop} {s : ι → Set α} /-- Constructs a filter from an indexed family of sets satisfying `IsBasis`. -/ protected def filter (h : IsBasis p s) : Filter α := h.filterBasis.filter protected theorem mem_filter_iff (h : IsBasis p s) {U : Set α} : U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U := by simp only [IsBasis.filter, FilterBasis.mem_filter_iff, mem_filterBasis_iff, exists_exists_and_eq_and] theorem filter_eq_generate (h : IsBasis p s) : h.filter = generate { U | ∃ i, p i ∧ s i = U } := by rw [IsBasis.filter, ← h.filterBasis.generate, IsBasis.filterBasis] end IsBasis -- TODO: consider adding `protected`? /-- We say that a filter `l` has a basis `s : ι → Set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/ structure HasBasis (l : Filter α) (p : ι → Prop) (s : ι → Set α) : Prop where /-- A set `t` belongs to a filter `l` iff it includes an element of the basis. -/ mem_iff' : ∀ t : Set α, t ∈ l ↔ ∃ i, p i ∧ s i ⊆ t section SameType variable {l l' : Filter α} {p : ι → Prop} {s : ι → Set α} {t : Set α} {i : ι} {p' : ι' → Prop} {s' : ι' → Set α} {i' : ι'} /-- Definition of `HasBasis` unfolded with implicit set argument. -/ theorem HasBasis.mem_iff (hl : l.HasBasis p s) : t ∈ l ↔ ∃ i, p i ∧ s i ⊆ t := hl.mem_iff' t theorem HasBasis.eq_of_same_basis (hl : l.HasBasis p s) (hl' : l'.HasBasis p s) : l = l' := by ext t rw [hl.mem_iff, hl'.mem_iff] theorem hasBasis_iff : l.HasBasis p s ↔ ∀ t, t ∈ l ↔ ∃ i, p i ∧ s i ⊆ t := ⟨fun ⟨h⟩ => h, fun h => ⟨h⟩⟩ theorem HasBasis.ex_mem (h : l.HasBasis p s) : ∃ i, p i := (h.mem_iff.mp univ_mem).imp fun _ => And.left protected theorem HasBasis.nonempty (h : l.HasBasis p s) : Nonempty ι := h.ex_mem.nonempty protected theorem IsBasis.hasBasis (h : IsBasis p s) : HasBasis h.filter p s := ⟨fun t => by simp only [h.mem_filter_iff]⟩ protected theorem HasBasis.mem_of_superset (hl : l.HasBasis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l := hl.mem_iff.2 ⟨i, hi, ht⟩ theorem HasBasis.mem_of_mem (hl : l.HasBasis p s) (hi : p i) : s i ∈ l := hl.mem_of_superset hi Subset.rfl /-- Index of a basis set such that `s i ⊆ t` as an element of `Subtype p`. -/ noncomputable def HasBasis.index (h : l.HasBasis p s) (t : Set α) (ht : t ∈ l) : { i : ι // p i } := ⟨(h.mem_iff.1 ht).choose, (h.mem_iff.1 ht).choose_spec.1⟩ theorem HasBasis.property_index (h : l.HasBasis p s) (ht : t ∈ l) : p (h.index t ht) := (h.index t ht).2 theorem HasBasis.set_index_mem (h : l.HasBasis p s) (ht : t ∈ l) : s (h.index t ht) ∈ l := h.mem_of_mem <| h.property_index _ theorem HasBasis.set_index_subset (h : l.HasBasis p s) (ht : t ∈ l) : s (h.index t ht) ⊆ t := (h.mem_iff.1 ht).choose_spec.2 theorem HasBasis.isBasis (h : l.HasBasis p s) : IsBasis p s where nonempty := h.ex_mem inter hi hj := by simpa only [h.mem_iff] using inter_mem (h.mem_of_mem hi) (h.mem_of_mem hj) theorem HasBasis.filter_eq (h : l.HasBasis p s) : h.isBasis.filter = l := by ext U simp [h.mem_iff, IsBasis.mem_filter_iff] theorem HasBasis.eq_generate (h : l.HasBasis p s) : l = generate { U | ∃ i, p i ∧ s i = U } := by rw [← h.isBasis.filter_eq_generate, h.filter_eq] protected theorem _root_.FilterBasis.hasBasis (B : FilterBasis α) : HasBasis B.filter (fun s : Set α => s ∈ B) id := ⟨fun _ => B.mem_filter_iff⟩ theorem HasBasis.to_hasBasis' (hl : l.HasBasis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → s' i' ∈ l) : l.HasBasis p' s' := by refine ⟨fun t => ⟨fun ht => ?_, fun ⟨i', hi', ht⟩ => mem_of_superset (h' i' hi') ht⟩⟩ rcases hl.mem_iff.1 ht with ⟨i, hi, ht⟩ rcases h i hi with ⟨i', hi', hs's⟩ exact ⟨i', hi', hs's.trans ht⟩ theorem HasBasis.to_hasBasis (hl : l.HasBasis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.HasBasis p' s' := hl.to_hasBasis' h fun i' hi' => let ⟨i, hi, hss'⟩ := h' i' hi' hl.mem_iff.2 ⟨i, hi, hss'⟩ protected lemma HasBasis.congr (hl : l.HasBasis p s) {p' s'} (hp : ∀ i, p i ↔ p' i) (hs : ∀ i, p i → s i = s' i) : l.HasBasis p' s' := ⟨fun t ↦ by simp only [hl.mem_iff, ← hp]; exact exists_congr fun i ↦ and_congr_right fun hi ↦ hs i hi ▸ Iff.rfl⟩ theorem HasBasis.to_subset (hl : l.HasBasis p s) {t : ι → Set α} (h : ∀ i, p i → t i ⊆ s i) (ht : ∀ i, p i → t i ∈ l) : l.HasBasis p t := hl.to_hasBasis' (fun i hi => ⟨i, hi, h i hi⟩) ht theorem HasBasis.eventually_iff (hl : l.HasBasis p s) {q : α → Prop} : (∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x := by simpa using hl.mem_iff theorem HasBasis.frequently_iff (hl : l.HasBasis p s) {q : α → Prop} : (∃ᶠ x in l, q x) ↔ ∀ i, p i → ∃ x ∈ s i, q x := by simp only [Filter.Frequently, hl.eventually_iff]; push_neg; rfl theorem HasBasis.exists_iff (hl : l.HasBasis p s) {P : Set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) : (∃ s ∈ l, P s) ↔ ∃ i, p i ∧ P (s i) := ⟨fun ⟨_s, hs, hP⟩ => let ⟨i, hi, his⟩ := hl.mem_iff.1 hs ⟨i, hi, mono his hP⟩, fun ⟨i, hi, hP⟩ => ⟨s i, hl.mem_of_mem hi, hP⟩⟩ theorem HasBasis.forall_iff (hl : l.HasBasis p s) {P : Set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) : (∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) := ⟨fun H i hi => H (s i) <| hl.mem_of_mem hi, fun H _s hs => let ⟨i, hi, his⟩ := hl.mem_iff.1 hs mono his (H i hi)⟩ protected theorem HasBasis.neBot_iff (hl : l.HasBasis p s) : NeBot l ↔ ∀ {i}, p i → (s i).Nonempty := forall_mem_nonempty_iff_neBot.symm.trans <| hl.forall_iff fun _ _ => Nonempty.mono theorem HasBasis.eq_bot_iff (hl : l.HasBasis p s) : l = ⊥ ↔ ∃ i, p i ∧ s i = ∅ := not_iff_not.1 <| neBot_iff.symm.trans <| hl.neBot_iff.trans <| by simp only [not_exists, not_and, nonempty_iff_ne_empty] theorem basis_sets (l : Filter α) : l.HasBasis (fun s : Set α => s ∈ l) id := ⟨fun _ => exists_mem_subset_iff.symm⟩ theorem asBasis_filter (f : Filter α) : f.asBasis.filter = f := Filter.ext fun _ => exists_mem_subset_iff theorem hasBasis_self {l : Filter α} {P : Set α → Prop} : HasBasis l (fun s => s ∈ l ∧ P s) id ↔ ∀ t ∈ l, ∃ r ∈ l, P r ∧ r ⊆ t := by simp only [hasBasis_iff, id, and_assoc] exact forall_congr' fun s => ⟨fun h => h.1, fun h => ⟨h, fun ⟨t, hl, _, hts⟩ => mem_of_superset hl hts⟩⟩ theorem HasBasis.comp_surjective (h : l.HasBasis p s) {g : ι' → ι} (hg : Function.Surjective g) : l.HasBasis (p ∘ g) (s ∘ g) := ⟨fun _ => h.mem_iff.trans hg.exists⟩ theorem HasBasis.comp_equiv (h : l.HasBasis p s) (e : ι' ≃ ι) : l.HasBasis (p ∘ e) (s ∘ e) := h.comp_surjective e.surjective theorem HasBasis.to_image_id' (h : l.HasBasis p s) : l.HasBasis (fun t ↦ ∃ i, p i ∧ s i = t) id := ⟨fun _ ↦ by simp [h.mem_iff]⟩ theorem HasBasis.to_image_id {ι : Type*} {p : ι → Prop} {s : ι → Set α} (h : l.HasBasis p s) : l.HasBasis (· ∈ s '' {i | p i}) id := h.to_image_id' /-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that `p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/ theorem HasBasis.restrict (h : l.HasBasis p s) {q : ι → Prop} (hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) : l.HasBasis (fun i => p i ∧ q i) s := by refine ⟨fun t => ⟨fun ht => ?_, fun ⟨i, hpi, hti⟩ => h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩ rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩ rcases hq i hpi with ⟨j, hpj, hqj, hji⟩ exact ⟨j, ⟨hpj, hqj⟩, hji.trans hti⟩ /-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}` is a basis of `l`. -/ theorem HasBasis.restrict_subset (h : l.HasBasis p s) {V : Set α} (hV : V ∈ l) : l.HasBasis (fun i => p i ∧ s i ⊆ V) s := h.restrict fun _i hi => (h.mem_iff.1 (inter_mem hV (h.mem_of_mem hi))).imp fun _j hj => ⟨hj.1, subset_inter_iff.1 hj.2⟩ theorem HasBasis.hasBasis_self_subset {p : Set α → Prop} (h : l.HasBasis (fun s => s ∈ l ∧ p s) id) {V : Set α} (hV : V ∈ l) : l.HasBasis (fun s => s ∈ l ∧ p s ∧ s ⊆ V) id := by simpa only [and_assoc] using h.restrict_subset hV theorem HasBasis.ge_iff (hl' : l'.HasBasis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l := ⟨fun h _i' hi' => h <| hl'.mem_of_mem hi', fun h _s hs => let ⟨_i', hi', hs⟩ := hl'.mem_iff.1 hs mem_of_superset (h _ hi') hs⟩ theorem HasBasis.le_iff (hl : l.HasBasis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i, p i ∧ s i ⊆ t := by simp only [le_def, hl.mem_iff] theorem HasBasis.le_basis_iff (hl : l.HasBasis p s) (hl' : l'.HasBasis p' s') : l ≤ l' ↔ ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i' := by simp only [hl'.ge_iff, hl.mem_iff] theorem HasBasis.ext (hl : l.HasBasis p s) (hl' : l'.HasBasis p' s') (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' := by apply le_antisymm · rw [hl.le_basis_iff hl'] simpa using h' · rw [hl'.le_basis_iff hl] simpa using h theorem HasBasis.inf' (hl : l.HasBasis p s) (hl' : l'.HasBasis p' s') : (l ⊓ l').HasBasis (fun i : PProd ι ι' => p i.1 ∧ p' i.2) fun i => s i.1 ∩ s' i.2 := ⟨by intro t constructor · simp only [mem_inf_iff, hl.mem_iff, hl'.mem_iff] rintro ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, rfl⟩ exact ⟨⟨i, i'⟩, ⟨hi, hi'⟩, inter_subset_inter ht ht'⟩ · rintro ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩ exact mem_inf_of_inter (hl.mem_of_mem hi) (hl'.mem_of_mem hi') H⟩ theorem HasBasis.inf {ι ι' : Type*} {p : ι → Prop} {s : ι → Set α} {p' : ι' → Prop} {s' : ι' → Set α} (hl : l.HasBasis p s) (hl' : l'.HasBasis p' s') : (l ⊓ l').HasBasis (fun i : ι × ι' => p i.1 ∧ p' i.2) fun i => s i.1 ∩ s' i.2 := (hl.inf' hl').comp_equiv Equiv.pprodEquivProd.symm theorem hasBasis_iInf_of_directed' {ι : Type*} {ι' : ι → Sort _} [Nonempty ι] {l : ι → Filter α} (s : ∀ i, ι' i → Set α) (p : ∀ i, ι' i → Prop) (hl : ∀ i, (l i).HasBasis (p i) (s i)) (h : Directed (· ≥ ·) l) : (⨅ i, l i).HasBasis (fun ii' : Σ i, ι' i => p ii'.1 ii'.2) fun ii' => s ii'.1 ii'.2 := by refine ⟨fun t => ?_⟩ rw [mem_iInf_of_directed h, Sigma.exists] exact exists_congr fun i => (hl i).mem_iff theorem hasBasis_iInf_of_directed {ι : Type*} {ι' : Sort _} [Nonempty ι] {l : ι → Filter α} (s : ι → ι' → Set α) (p : ι → ι' → Prop) (hl : ∀ i, (l i).HasBasis (p i) (s i)) (h : Directed (· ≥ ·) l) : (⨅ i, l i).HasBasis (fun ii' : ι × ι' => p ii'.1 ii'.2) fun ii' => s ii'.1 ii'.2 := by refine ⟨fun t => ?_⟩ rw [mem_iInf_of_directed h, Prod.exists] exact exists_congr fun i => (hl i).mem_iff theorem hasBasis_biInf_of_directed' {ι : Type*} {ι' : ι → Sort _} {dom : Set ι} (hdom : dom.Nonempty) {l : ι → Filter α} (s : ∀ i, ι' i → Set α) (p : ∀ i, ι' i → Prop) (hl : ∀ i ∈ dom, (l i).HasBasis (p i) (s i)) (h : DirectedOn (l ⁻¹'o GE.ge) dom) : (⨅ i ∈ dom, l i).HasBasis (fun ii' : Σ i, ι' i => ii'.1 ∈ dom ∧ p ii'.1 ii'.2) fun ii' => s ii'.1 ii'.2 := by refine ⟨fun t => ?_⟩ rw [mem_biInf_of_directed h hdom, Sigma.exists] refine exists_congr fun i => ⟨?_, ?_⟩ · rintro ⟨hi, hti⟩ rcases (hl i hi).mem_iff.mp hti with ⟨b, hb, hbt⟩ exact ⟨b, ⟨hi, hb⟩, hbt⟩ · rintro ⟨b, ⟨hi, hb⟩, hibt⟩ exact ⟨hi, (hl i hi).mem_iff.mpr ⟨b, hb, hibt⟩⟩ theorem hasBasis_biInf_of_directed {ι : Type*} {ι' : Sort _} {dom : Set ι} (hdom : dom.Nonempty) {l : ι → Filter α} (s : ι → ι' → Set α) (p : ι → ι' → Prop) (hl : ∀ i ∈ dom, (l i).HasBasis (p i) (s i)) (h : DirectedOn (l ⁻¹'o GE.ge) dom) : (⨅ i ∈ dom, l i).HasBasis (fun ii' : ι × ι' => ii'.1 ∈ dom ∧ p ii'.1 ii'.2) fun ii' => s ii'.1 ii'.2 := by refine ⟨fun t => ?_⟩ rw [mem_biInf_of_directed h hdom, Prod.exists] refine exists_congr fun i => ⟨?_, ?_⟩ · rintro ⟨hi, hti⟩ rcases (hl i hi).mem_iff.mp hti with ⟨b, hb, hbt⟩ exact ⟨b, ⟨hi, hb⟩, hbt⟩ · rintro ⟨b, ⟨hi, hb⟩, hibt⟩ exact ⟨hi, (hl i hi).mem_iff.mpr ⟨b, hb, hibt⟩⟩ lemma hasBasis_top : (⊤ : Filter α).HasBasis (fun _ : Unit ↦ True) (fun _ ↦ Set.univ) := ⟨fun U => by simp⟩ theorem hasBasis_principal (t : Set α) : (𝓟 t).HasBasis (fun _ : Unit => True) fun _ => t := ⟨fun U => by simp⟩ theorem hasBasis_pure (x : α) : (pure x : Filter α).HasBasis (fun _ : Unit => True) fun _ => {x} := by simp only [← principal_singleton, hasBasis_principal] theorem HasBasis.sup' (hl : l.HasBasis p s) (hl' : l'.HasBasis p' s') : (l ⊔ l').HasBasis (fun i : PProd ι ι' => p i.1 ∧ p' i.2) fun i => s i.1 ∪ s' i.2 := ⟨by intro t simp_rw [mem_sup, hl.mem_iff, hl'.mem_iff, PProd.exists, union_subset_iff, ← exists_and_right, ← exists_and_left] simp only [and_assoc, and_left_comm]⟩ theorem HasBasis.sup {ι ι' : Type*} {p : ι → Prop} {s : ι → Set α} {p' : ι' → Prop} {s' : ι' → Set α} (hl : l.HasBasis p s) (hl' : l'.HasBasis p' s') : (l ⊔ l').HasBasis (fun i : ι × ι' => p i.1 ∧ p' i.2) fun i => s i.1 ∪ s' i.2 := (hl.sup' hl').comp_equiv Equiv.pprodEquivProd.symm theorem hasBasis_iSup {ι : Sort*} {ι' : ι → Type*} {l : ι → Filter α} {p : ∀ i, ι' i → Prop} {s : ∀ i, ι' i → Set α} (hl : ∀ i, (l i).HasBasis (p i) (s i)) : (⨆ i, l i).HasBasis (fun f : ∀ i, ι' i => ∀ i, p i (f i)) fun f : ∀ i, ι' i => ⋃ i, s i (f i) := hasBasis_iff.mpr fun t => by simp only [(hl _).mem_iff, Classical.skolem, forall_and, iUnion_subset_iff, mem_iSup] theorem HasBasis.sup_principal (hl : l.HasBasis p s) (t : Set α) : (l ⊔ 𝓟 t).HasBasis p fun i => s i ∪ t := ⟨fun u => by simp only [(hl.sup' (hasBasis_principal t)).mem_iff, PProd.exists, and_true, Unique.exists_iff]⟩ theorem HasBasis.sup_pure (hl : l.HasBasis p s) (x : α) : (l ⊔ pure x).HasBasis p fun i => s i ∪ {x} := by simp only [← principal_singleton, hl.sup_principal] theorem HasBasis.inf_principal (hl : l.HasBasis p s) (s' : Set α) : (l ⊓ 𝓟 s').HasBasis p fun i => s i ∩ s' := ⟨fun t => by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_setOf_eq, mem_inter_iff, and_imp]⟩ theorem HasBasis.principal_inf (hl : l.HasBasis p s) (s' : Set α) : (𝓟 s' ⊓ l).HasBasis p fun i => s' ∩ s i := by simpa only [inf_comm, inter_comm] using hl.inf_principal s' theorem HasBasis.inf_basis_neBot_iff (hl : l.HasBasis p s) (hl' : l'.HasBasis p' s') : NeBot (l ⊓ l') ↔ ∀ ⦃i⦄, p i → ∀ ⦃i'⦄, p' i' → (s i ∩ s' i').Nonempty := (hl.inf' hl').neBot_iff.trans <| by simp [@forall_swap _ ι'] theorem HasBasis.inf_neBot_iff (hl : l.HasBasis p s) : NeBot (l ⊓ l') ↔ ∀ ⦃i⦄, p i → ∀ ⦃s'⦄, s' ∈ l' → (s i ∩ s').Nonempty := hl.inf_basis_neBot_iff l'.basis_sets theorem HasBasis.inf_principal_neBot_iff (hl : l.HasBasis p s) {t : Set α} : NeBot (l ⊓ 𝓟 t) ↔ ∀ ⦃i⦄, p i → (s i ∩ t).Nonempty := (hl.inf_principal t).neBot_iff theorem HasBasis.disjoint_iff (hl : l.HasBasis p s) (hl' : l'.HasBasis p' s') : Disjoint l l' ↔ ∃ i, p i ∧ ∃ i', p' i' ∧ Disjoint (s i) (s' i') := not_iff_not.mp <| by simp only [_root_.disjoint_iff, ← Ne.eq_def, ← neBot_iff, inf_eq_inter, hl.inf_basis_neBot_iff hl', not_exists, not_and, bot_eq_empty, ← nonempty_iff_ne_empty] theorem _root_.Disjoint.exists_mem_filter_basis (h : Disjoint l l') (hl : l.HasBasis p s) (hl' : l'.HasBasis p' s') : ∃ i, p i ∧ ∃ i', p' i' ∧ Disjoint (s i) (s' i') := (hl.disjoint_iff hl').1 h theorem inf_neBot_iff : NeBot (l ⊓ l') ↔ ∀ ⦃s : Set α⦄, s ∈ l → ∀ ⦃s'⦄, s' ∈ l' → (s ∩ s').Nonempty := l.basis_sets.inf_neBot_iff theorem inf_principal_neBot_iff {s : Set α} : NeBot (l ⊓ 𝓟 s) ↔ ∀ U ∈ l, (U ∩ s).Nonempty := l.basis_sets.inf_principal_neBot_iff theorem mem_iff_inf_principal_compl {f : Filter α} {s : Set α} : s ∈ f ↔ f ⊓ 𝓟 sᶜ = ⊥ := by refine not_iff_not.1 ((inf_principal_neBot_iff.trans ?_).symm.trans neBot_iff) exact ⟨fun h hs => by simpa [Set.not_nonempty_empty] using h s hs, fun hs t ht => inter_compl_nonempty_iff.2 fun hts => hs <| mem_of_superset ht hts⟩ theorem notMem_iff_inf_principal_compl {f : Filter α} {s : Set α} : s ∉ f ↔ NeBot (f ⊓ 𝓟 sᶜ) := (not_congr mem_iff_inf_principal_compl).trans neBot_iff.symm @[deprecated (since := "2025-05-23")] alias not_mem_iff_inf_principal_compl := notMem_iff_inf_principal_compl @[simp] theorem disjoint_principal_right {f : Filter α} {s : Set α} : Disjoint f (𝓟 s) ↔ sᶜ ∈ f := by rw [mem_iff_inf_principal_compl, compl_compl, disjoint_iff] @[simp] theorem disjoint_principal_left {f : Filter α} {s : Set α} : Disjoint (𝓟 s) f ↔ sᶜ ∈ f := by rw [disjoint_comm, disjoint_principal_right] @[simp 1100] -- Porting note: higher priority for linter theorem disjoint_principal_principal {s t : Set α} : Disjoint (𝓟 s) (𝓟 t) ↔ Disjoint s t := by rw [← subset_compl_iff_disjoint_left, disjoint_principal_left, mem_principal] alias ⟨_, _root_.Disjoint.filter_principal⟩ := disjoint_principal_principal @[simp] theorem disjoint_pure_pure {x y : α} : Disjoint (pure x : Filter α) (pure y) ↔ x ≠ y := by simp only [← principal_singleton, disjoint_principal_principal, disjoint_singleton] theorem HasBasis.disjoint_iff_left (h : l.HasBasis p s) : Disjoint l l' ↔ ∃ i, p i ∧ (s i)ᶜ ∈ l' := by simp only [h.disjoint_iff l'.basis_sets, id, ← disjoint_principal_left, (hasBasis_principal _).disjoint_iff l'.basis_sets, true_and, Unique.exists_iff] theorem HasBasis.disjoint_iff_right (h : l.HasBasis p s) : Disjoint l' l ↔ ∃ i, p i ∧ (s i)ᶜ ∈ l' := disjoint_comm.trans h.disjoint_iff_left theorem le_iff_forall_inf_principal_compl {f g : Filter α} : f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ := forall₂_congr fun _ _ => mem_iff_inf_principal_compl theorem inf_neBot_iff_frequently_left {f g : Filter α} : NeBot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x := by simp only [inf_neBot_iff, frequently_iff, and_comm]; rfl theorem inf_neBot_iff_frequently_right {f g : Filter α} : NeBot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x := by rw [inf_comm] exact inf_neBot_iff_frequently_left theorem HasBasis.eq_biInf (h : l.HasBasis p s) : l = ⨅ (i) (_ : p i), 𝓟 (s i) := eq_biInf_of_mem_iff_exists_mem fun {_} => by simp only [h.mem_iff, mem_principal] theorem HasBasis.eq_iInf (h : l.HasBasis (fun _ => True) s) : l = ⨅ i, 𝓟 (s i) := by simpa only [iInf_true] using h.eq_biInf theorem hasBasis_iInf_principal {s : ι → Set α} (h : Directed (· ≥ ·) s) [Nonempty ι] : (⨅ i, 𝓟 (s i)).HasBasis (fun _ => True) s := ⟨fun t => by simpa only [true_and] using mem_iInf_of_directed (h.mono_comp _ monotone_principal.dual) t⟩ theorem hasBasis_biInf_principal {s : β → Set α} {S : Set β} (h : DirectedOn (s ⁻¹'o (· ≥ ·)) S) (ne : S.Nonempty) : (⨅ i ∈ S, 𝓟 (s i)).HasBasis (fun i => i ∈ S) s := ⟨fun t => by refine mem_biInf_of_directed ?_ ne rw [directedOn_iff_directed, ← directed_comp] at h ⊢ refine h.mono_comp _ ?_ exact fun _ _ => principal_mono.2⟩ theorem hasBasis_biInf_principal' {ι : Type*} {p : ι → Prop} {s : ι → Set α} (h : ∀ i, p i → ∀ j, p j → ∃ k, p k ∧ s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) : (⨅ (i) (_ : p i), 𝓟 (s i)).HasBasis p s := Filter.hasBasis_biInf_principal h ne theorem HasBasis.map (f : α → β) (hl : l.HasBasis p s) : (l.map f).HasBasis p fun i => f '' s i := ⟨fun t => by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩ theorem HasBasis.comap (f : β → α) (hl : l.HasBasis p s) : (l.comap f).HasBasis p fun i => f ⁻¹' s i := ⟨fun t => by simp only [mem_comap', hl.mem_iff] refine exists_congr (fun i => Iff.rfl.and ?_) exact ⟨fun h x hx => h hx rfl, fun h y hy x hx => h <| by rwa [mem_preimage, hx]⟩⟩ theorem comap_hasBasis (f : α → β) (l : Filter β) : HasBasis (comap f l) (fun s : Set β => s ∈ l) fun s => f ⁻¹' s := ⟨fun _ => mem_comap⟩ theorem HasBasis.forall_mem_mem (h : HasBasis l p s) {x : α} : (∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i := by simp only [h.mem_iff, exists_imp, and_imp] exact ⟨fun h i hi => h (s i) i hi Subset.rfl, fun h t i hi ht => ht (h i hi)⟩ protected theorem HasBasis.biInf_mem [CompleteLattice β] {f : Set α → β} (h : HasBasis l p s) (hf : Monotone f) : ⨅ t ∈ l, f t = ⨅ (i) (_ : p i), f (s i) := le_antisymm (le_iInf₂ fun i hi => iInf₂_le (s i) (h.mem_of_mem hi)) <| le_iInf₂ fun _t ht => let ⟨i, hpi, hi⟩ := h.mem_iff.1 ht iInf₂_le_of_le i hpi (hf hi) protected theorem HasBasis.biInter_mem {f : Set α → Set β} (h : HasBasis l p s) (hf : Monotone f) : ⋂ t ∈ l, f t = ⋂ (i) (_ : p i), f (s i) := h.biInf_mem hf protected theorem HasBasis.ker (h : HasBasis l p s) : l.ker = ⋂ (i) (_ : p i), s i := sInter_eq_biInter.trans <| h.biInter_mem monotone_id variable {ι'' : Type*} [Preorder ι''] (l) (s'' : ι'' → Set α) /-- `IsAntitoneBasis s` means the image of `s` is a filter basis such that `s` is decreasing. -/ structure IsAntitoneBasis : Prop extends IsBasis (fun _ => True) s'' where /-- The sequence of sets is antitone. -/ protected antitone : Antitone s'' /-- We say that a filter `l` has an antitone basis `s : ι → Set α`, if `t ∈ l` if and only if `t` includes `s i` for some `i`, and `s` is decreasing. -/ structure HasAntitoneBasis (l : Filter α) (s : ι'' → Set α) : Prop extends HasBasis l (fun _ => True) s where /-- The sequence of sets is antitone. -/ protected antitone : Antitone s protected theorem HasAntitoneBasis.map {l : Filter α} {s : ι'' → Set α} (hf : HasAntitoneBasis l s) (m : α → β) : HasAntitoneBasis (map m l) (m '' s ·) := ⟨HasBasis.map _ hf.toHasBasis, fun _ _ h => image_mono <| hf.2 h⟩ protected theorem HasAntitoneBasis.comap {l : Filter α} {s : ι'' → Set α} (hf : HasAntitoneBasis l s) (m : β → α) : HasAntitoneBasis (comap m l) (m ⁻¹' s ·) := ⟨hf.1.comap _, fun _ _ h ↦ preimage_mono (hf.2 h)⟩ lemma HasAntitoneBasis.iInf_principal {ι : Type*} [Preorder ι] [Nonempty ι] [IsDirected ι (· ≤ ·)] {s : ι → Set α} (hs : Antitone s) : (⨅ i, 𝓟 (s i)).HasAntitoneBasis s := ⟨hasBasis_iInf_principal hs.directed_ge, hs⟩ end SameType section TwoTypes variable {la : Filter α} {pa : ι → Prop} {sa : ι → Set α} {lb : Filter β} {pb : ι' → Prop} {sb : ι' → Set β} {f : α → β} theorem HasBasis.tendsto_left_iff (hla : la.HasBasis pa sa) : Tendsto f la lb ↔ ∀ t ∈ lb, ∃ i, pa i ∧ MapsTo f (sa i) t := by simp only [Tendsto, (hla.map f).le_iff, image_subset_iff] rfl theorem HasBasis.tendsto_right_iff (hlb : lb.HasBasis pb sb) : Tendsto f la lb ↔ ∀ i, pb i → ∀ᶠ x in la, f x ∈ sb i := by simp only [Tendsto, hlb.ge_iff, mem_map', Filter.Eventually] theorem HasBasis.tendsto_iff (hla : la.HasBasis pa sa) (hlb : lb.HasBasis pb sb) : Tendsto f la lb ↔ ∀ ib, pb ib → ∃ ia, pa ia ∧ ∀ x ∈ sa ia, f x ∈ sb ib := by simp [hlb.tendsto_right_iff, hla.eventually_iff] theorem Tendsto.basis_left (H : Tendsto f la lb) (hla : la.HasBasis pa sa) : ∀ t ∈ lb, ∃ i, pa i ∧ MapsTo f (sa i) t := hla.tendsto_left_iff.1 H theorem Tendsto.basis_right (H : Tendsto f la lb) (hlb : lb.HasBasis pb sb) : ∀ i, pb i → ∀ᶠ x in la, f x ∈ sb i := hlb.tendsto_right_iff.1 H theorem Tendsto.basis_both (H : Tendsto f la lb) (hla : la.HasBasis pa sa) (hlb : lb.HasBasis pb sb) : ∀ ib, pb ib → ∃ ia, pa ia ∧ MapsTo f (sa ia) (sb ib) := (hla.tendsto_iff hlb).1 H theorem HasBasis.prod_pprod (hla : la.HasBasis pa sa) (hlb : lb.HasBasis pb sb) : (la ×ˢ lb).HasBasis (fun i : PProd ι ι' => pa i.1 ∧ pb i.2) fun i => sa i.1 ×ˢ sb i.2 := (hla.comap Prod.fst).inf' (hlb.comap Prod.snd) theorem HasBasis.prod {ι ι' : Type*} {pa : ι → Prop} {sa : ι → Set α} {pb : ι' → Prop} {sb : ι' → Set β} (hla : la.HasBasis pa sa) (hlb : lb.HasBasis pb sb) : (la ×ˢ lb).HasBasis (fun i : ι × ι' => pa i.1 ∧ pb i.2) fun i => sa i.1 ×ˢ sb i.2 := (hla.comap Prod.fst).inf (hlb.comap Prod.snd) protected theorem HasBasis.principal_prod (sa : Set α) (h : lb.HasBasis pb sb) : (𝓟 sa ×ˢ lb).HasBasis pb (sa ×ˢ sb ·) := by simpa only [prod_eq_inf, comap_principal, prod_eq] using (h.comap Prod.snd).principal_inf _ protected theorem HasBasis.prod_principal (h : la.HasBasis pa sa) (sb : Set β) : (la ×ˢ 𝓟 sb).HasBasis pa (sa · ×ˢ sb) := by simpa only [prod_eq_inf, comap_principal, prod_eq] using (h.comap Prod.fst).inf_principal _ protected theorem HasBasis.top_prod (h : lb.HasBasis pb sb) : (⊤ ×ˢ lb : Filter (α × β)).HasBasis pb (univ ×ˢ sb ·) := by simpa only [principal_univ] using h.principal_prod univ protected theorem HasBasis.prod_top (h : la.HasBasis pa sa) : (la ×ˢ ⊤ : Filter (α × β)).HasBasis pa (sa · ×ˢ univ) := by simpa only [principal_univ] using h.prod_principal univ theorem HasBasis.prod_same_index {p : ι → Prop} {sb : ι → Set β} (hla : la.HasBasis p sa) (hlb : lb.HasBasis p sb) (h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) : (la ×ˢ lb).HasBasis p fun i => sa i ×ˢ sb i := by simp only [hasBasis_iff, (hla.prod_pprod hlb).mem_iff] refine fun t => ⟨?_, ?_⟩ · rintro ⟨⟨i, j⟩, ⟨hi, hj⟩, hsub : sa i ×ˢ sb j ⊆ t⟩ rcases h_dir hi hj with ⟨k, hk, ki, kj⟩ exact ⟨k, hk, (Set.prod_mono ki kj).trans hsub⟩ · rintro ⟨i, hi, h⟩ exact ⟨⟨i, i⟩, ⟨hi, hi⟩, h⟩ theorem HasBasis.prod_same_index_mono {ι : Type*} [LinearOrder ι] {p : ι → Prop} {sa : ι → Set α} {sb : ι → Set β} (hla : la.HasBasis p sa) (hlb : lb.HasBasis p sb) (hsa : MonotoneOn sa { i | p i }) (hsb : MonotoneOn sb { i | p i }) : (la ×ˢ lb).HasBasis p fun i => sa i ×ˢ sb i := hla.prod_same_index hlb fun {i j} hi hj => have : p (min i j) := min_rec' _ hi hj ⟨min i j, this, hsa this hi <| min_le_left _ _, hsb this hj <| min_le_right _ _⟩ theorem HasBasis.prod_same_index_anti {ι : Type*} [LinearOrder ι] {p : ι → Prop} {sa : ι → Set α} {sb : ι → Set β} (hla : la.HasBasis p sa) (hlb : lb.HasBasis p sb) (hsa : AntitoneOn sa { i | p i }) (hsb : AntitoneOn sb { i | p i }) : (la ×ˢ lb).HasBasis p fun i => sa i ×ˢ sb i := @HasBasis.prod_same_index_mono _ _ _ _ ιᵒᵈ _ _ _ _ hla hlb hsa.dual_left hsb.dual_left theorem HasBasis.prod_self (hl : la.HasBasis pa sa) : (la ×ˢ la).HasBasis pa fun i => sa i ×ˢ sa i := hl.prod_same_index hl fun {i j} hi hj => by simpa only [exists_prop, subset_inter_iff] using hl.mem_iff.1 (inter_mem (hl.mem_of_mem hi) (hl.mem_of_mem hj)) theorem mem_prod_self_iff {s} : s ∈ la ×ˢ la ↔ ∃ t ∈ la, t ×ˢ t ⊆ s := la.basis_sets.prod_self.mem_iff lemma eventually_prod_self_iff {r : α → α → Prop} : (∀ᶠ x in la ×ˢ la, r x.1 x.2) ↔ ∃ t ∈ la, ∀ x ∈ t, ∀ y ∈ t, r x y := mem_prod_self_iff.trans <| by simp only [prod_subset_iff, mem_setOf_eq] /-- A version of `eventually_prod_self_iff` that is more suitable for forward rewriting. -/ lemma eventually_prod_self_iff' {r : α × α → Prop} : (∀ᶠ x in la ×ˢ la, r x) ↔ ∃ t ∈ la, ∀ x ∈ t, ∀ y ∈ t, r (x, y) := Iff.symm eventually_prod_self_iff.symm theorem HasAntitoneBasis.prod {ι : Type*} [LinearOrder ι] {f : Filter α} {g : Filter β} {s : ι → Set α} {t : ι → Set β} (hf : HasAntitoneBasis f s) (hg : HasAntitoneBasis g t) : HasAntitoneBasis (f ×ˢ g) fun n => s n ×ˢ t n := ⟨hf.1.prod_same_index_anti hg.1 (hf.2.antitoneOn _) (hg.2.antitoneOn _), hf.2.set_prod hg.2⟩ theorem HasBasis.coprod {ι ι' : Type*} {pa : ι → Prop} {sa : ι → Set α} {pb : ι' → Prop} {sb : ι' → Set β} (hla : la.HasBasis pa sa) (hlb : lb.HasBasis pb sb) : (la.coprod lb).HasBasis (fun i : ι × ι' => pa i.1 ∧ pb i.2) fun i => Prod.fst ⁻¹' sa i.1 ∪ Prod.snd ⁻¹' sb i.2 := (hla.comap Prod.fst).sup (hlb.comap Prod.snd) end TwoTypes theorem map_sigma_mk_comap {π : α → Type*} {π' : β → Type*} {f : α → β} (hf : Function.Injective f) (g : ∀ a, π a → π' (f a)) (a : α) (l : Filter (π' (f a))) : map (Sigma.mk a) (comap (g a) l) = comap (Sigma.map f g) (map (Sigma.mk (f a)) l) := by refine (((basis_sets _).comap _).map _).eq_of_same_basis ?_ convert ((basis_sets l).map (Sigma.mk (f a))).comap (Sigma.map f g) apply image_sigmaMk_preimage_sigmaMap hf end Filter
CommRing.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import Mathlib.Algebra.MvPolynomial.Variables /-! # Multivariate polynomials over a ring Many results about polynomials hold when the coefficient ring is a commutative semiring. Some stronger results can be derived when we assume this semiring is a ring. This file does not define any new operations, but proves some of these stronger results. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[CommRing R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `MvPolynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : MvPolynomial σ R` -/ noncomputable section open Set Function Finsupp AddMonoidAlgebra universe u v variable {R : Type u} {S : Type v} namespace MvPolynomial variable {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section CommRing variable [CommRing R] variable {p q : MvPolynomial σ R} instance instCommRingMvPolynomial : CommRing (MvPolynomial σ R) := AddMonoidAlgebra.commRing variable (σ a a') @[simp] theorem C_sub : (C (a - a') : MvPolynomial σ R) = C a - C a' := RingHom.map_sub _ _ _ @[simp] theorem C_neg : (C (-a) : MvPolynomial σ R) = -C a := RingHom.map_neg _ _ @[simp] theorem coeff_neg (m : σ →₀ ℕ) (p : MvPolynomial σ R) : coeff m (-p) = -coeff m p := Finsupp.neg_apply _ _ @[simp] theorem coeff_sub (m : σ →₀ ℕ) (p q : MvPolynomial σ R) : coeff m (p - q) = coeff m p - coeff m q := Finsupp.sub_apply _ _ _ @[simp] theorem support_neg : (-p).support = p.support := Finsupp.support_neg p theorem support_sub [DecidableEq σ] (p q : MvPolynomial σ R) : (p - q).support ⊆ p.support ∪ q.support := Finsupp.support_sub variable {σ} (p) section Degrees @[simp] theorem degrees_neg (p : MvPolynomial σ R) : (-p).degrees = p.degrees := by rw [degrees, support_neg]; rfl theorem degrees_sub_le [DecidableEq σ] {p q : MvPolynomial σ R} : (p - q).degrees ≤ p.degrees ∪ q.degrees := by simpa [degrees_def] using AddMonoidAlgebra.supDegree_sub_le end Degrees section Degrees @[simp] theorem degreeOf_neg (i : σ) (p : MvPolynomial σ R) : degreeOf i (-p) = degreeOf i p := by rw [degreeOf, degreeOf, degrees_neg] theorem degreeOf_sub_le (i : σ) (p q : MvPolynomial σ R) : degreeOf i (p - q) ≤ max (degreeOf i p) (degreeOf i q) := by simpa only [sub_eq_add_neg, degreeOf_neg] using degreeOf_add_le i p (-q) end Degrees section Vars @[simp] theorem vars_neg : (-p).vars = p.vars := by simp [vars, degrees_neg] theorem vars_sub_subset [DecidableEq σ] : (p - q).vars ⊆ p.vars ∪ q.vars := by convert vars_add_subset p (-q) using 2 <;> simp [sub_eq_add_neg] @[simp] theorem vars_sub_of_disjoint [DecidableEq σ] (hpq : Disjoint p.vars q.vars) : (p - q).vars = p.vars ∪ q.vars := by rw [← vars_neg q] at hpq convert vars_add_of_disjoint hpq using 2 <;> simp [sub_eq_add_neg] end Vars section Eval variable [CommRing S] variable (f : R →+* S) (g : σ → S) @[simp] theorem eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := (eval₂Hom f g).map_sub _ _ theorem eval_sub (f : σ → R) : eval f (p - q) = eval f p - eval f q := eval₂_sub _ _ _ @[simp] theorem eval₂_neg : (-p).eval₂ f g = -p.eval₂ f g := (eval₂Hom f g).map_neg _ theorem eval_neg (f : σ → R) : eval f (-p) = -eval f p := eval₂_neg _ _ _ theorem hom_C (f : MvPolynomial σ ℤ →+* S) (n : ℤ) : f (C n) = (n : S) := eq_intCast (f.comp C) n /-- A ring homomorphism `f : Z[X_1, X_2, ...] → R` is determined by the evaluations `f(X_1)`, `f(X_2)`, ... -/ @[simp] theorem eval₂Hom_X {R : Type u} (c : ℤ →+* S) (f : MvPolynomial R ℤ →+* S) (x : MvPolynomial R ℤ) : eval₂ c (f ∘ X) x = f x := by apply MvPolynomial.induction_on x (fun n => by rw [hom_C f, eval₂_C] exact eq_intCast c n) (fun p q hp hq => by rw [eval₂_add, hp, hq] exact (f.map_add _ _).symm) (fun p n hp => by rw [eval₂_mul, eval₂_X, hp] exact (f.map_mul _ _).symm) /-- Ring homomorphisms out of integer polynomials on a type `σ` are the same as functions out of the type `σ`. -/ def homEquiv : (MvPolynomial σ ℤ →+* S) ≃ (σ → S) where toFun f := f ∘ X invFun f := eval₂Hom (Int.castRingHom S) f left_inv _ := RingHom.ext <| eval₂Hom_X _ _ right_inv f := funext fun x => by simp only [coe_eval₂Hom, Function.comp_apply, eval₂_X] end Eval section DegreeOf theorem degreeOf_sub_lt {x : σ} {f g : MvPolynomial σ R} {k : ℕ} (h : 0 < k) (hf : ∀ m : σ →₀ ℕ, m ∈ f.support → k ≤ m x → coeff m f = coeff m g) (hg : ∀ m : σ →₀ ℕ, m ∈ g.support → k ≤ m x → coeff m f = coeff m g) : degreeOf x (f - g) < k := by rw [degreeOf_lt_iff h] grind [degreeOf_lt_iff, mem_support_iff, coeff_sub] end DegreeOf section TotalDegree @[simp] theorem totalDegree_neg (a : MvPolynomial σ R) : (-a).totalDegree = a.totalDegree := by simp only [totalDegree, support_neg] theorem totalDegree_sub (a b : MvPolynomial σ R) : (a - b).totalDegree ≤ max a.totalDegree b.totalDegree := calc (a - b).totalDegree = (a + -b).totalDegree := by rw [sub_eq_add_neg] _ ≤ max a.totalDegree (-b).totalDegree := totalDegree_add a (-b) _ = max a.totalDegree b.totalDegree := by rw [totalDegree_neg] theorem totalDegree_sub_C_le (p : MvPolynomial σ R) (r : R) : totalDegree (p - C r) ≤ totalDegree p := (totalDegree_sub _ _).trans_eq <| by rw [totalDegree_C, Nat.max_zero] end TotalDegree end CommRing end MvPolynomial
right_actions.lean
import Mathlib.Algebra.GroupWithZero.Action.Opposite open MulOpposite renaming op → mop open AddOpposite renaming op → aop variable {α β : Type*} [SMul α β] [SMul αᵐᵒᵖ β] [VAdd α β] [VAdd αᵃᵒᵖ β] {a a₁ a₂ a₃ a₄ : α} {b : β} section delaborators section without_scope /-- info: a • b : β -/ #guard_msgs in #check a • b /-- info: MulOpposite.op a • b : β -/ #guard_msgs in #check mop a • b /-- info: a +ᵥ b : β -/ #guard_msgs in #check a +ᵥ b /-- info: AddOpposite.op a +ᵥ b : β -/ #guard_msgs in #check aop a +ᵥ b end without_scope section with_scope open scoped RightActions /-- info: a •> b : β -/ #guard_msgs in #check a • b /-- info: b <• a : β -/ #guard_msgs in #check mop a • b /-- info: a +ᵥ> b : β -/ #guard_msgs in #check a +ᵥ b /-- info: b <+ᵥ a : β -/ #guard_msgs in #check aop a +ᵥ b end with_scope end delaborators open scoped RightActions example : a •> b = a • b := rfl example : b <• a = mop a • b := rfl example : a +ᵥ> b = a +ᵥ b := rfl example : b <+ᵥ a = aop a +ᵥ b := rfl -- Left actions right-associate, right actions left-associate example : a₁ •> a₂ •> b = a₁ •> (a₂ •> b) := rfl example : b <• a₂ <• a₁ = (b <• a₂) <• a₁ := rfl example : a₁ +ᵥ> a₂ +ᵥ> b = a₁ +ᵥ> (a₂ +ᵥ> b) := rfl example : b <+ᵥ a₂ <+ᵥ a₁ = (b <+ᵥ a₂) <+ᵥ a₁ := rfl -- When left and right actions coexist, they associate to the left example : a₁ •> b <• a₂ = (a₁ •> b) <• a₂ := rfl example : a₁ •> a₂ •> b <• a₃ <• a₄ = ((a₁ •> (a₂ •> b)) <• a₃) <• a₄ := rfl example : a₁ +ᵥ> b <+ᵥ a₂ = (a₁ +ᵥ> b) <+ᵥ a₂ := rfl example : a₁ +ᵥ> a₂ +ᵥ> b <+ᵥ a₃ <+ᵥ a₄ = ((a₁ +ᵥ> (a₂ +ᵥ> b)) <+ᵥ a₃) <+ᵥ a₄ := rfl -- association is chosen to match multiplication and addition example {M} [Mul M] {x y z : M} : x •> y <• z = x * y * z := rfl example {A} [Add A] {x y z : A} : x +ᵥ> y <+ᵥ z = x + y + z := rfl
Contrapose.lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Tactic.Basic import Mathlib.Tactic.Contrapose example (p q : Prop) (h : ¬q → ¬p) : p → q := by contrapose guard_target = ¬q → ¬p exact h example (p q : Prop) (h : p) (hpq : ¬q → ¬p) : q := by contrapose h guard_target = ¬p exact hpq h example (p q : Prop) (h : p) (hpq : ¬q → ¬p) : q := by contrapose h with h' guard_target = ¬p exact hpq h' example (p q : Prop) (h : q → p) : ¬p → ¬q := by contrapose! guard_target = q → p exact h example (p q : Prop) (h : ¬p) (hpq : q → p) : ¬q := by contrapose! h guard_target = p exact hpq h example (p q : Prop) (h : ¬p) (hpq : q → p) : ¬q := by contrapose! h with h' guard_target = p exact hpq h' example (p : Prop) (h : p) : p := by fail_if_success { contrapose } exact h example (p q : Type) (h : p → q) : p → q := by fail_if_success { contrapose } exact h
Order.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.Order.Ring.InjSurj import Mathlib.Algebra.Ring.Subsemiring.Defs import Mathlib.Order.Interval.Set.Defs import Mathlib.Tactic.FastInstance /-! # `Order`ed instances for `SubsemiringClass` and `Subsemiring`. -/ namespace SubsemiringClass variable {R S : Type*} [SetLike S R] (s : S) /-- A subsemiring of an ordered semiring is an ordered semiring. -/ instance toIsOrderedRing [Semiring R] [PartialOrder R] [IsOrderedRing R] [SubsemiringClass S R] : IsOrderedRing s := Subtype.coe_injective.isOrderedRing Subtype.val rfl rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) fun _ => rfl /-- A subsemiring of a strict ordered semiring is a strict ordered semiring. -/ instance toIsStrictOrderedRing [Semiring R] [PartialOrder R] [IsStrictOrderedRing R] [SubsemiringClass S R] : IsStrictOrderedRing s := Subtype.coe_injective.isStrictOrderedRing Subtype.val rfl rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) fun _ => rfl end SubsemiringClass namespace Subsemiring variable {R : Type*} /-- A subsemiring of an ordered semiring is an ordered semiring. -/ instance toIsOrderedRing [Semiring R] [PartialOrder R] [IsOrderedRing R] (s : Subsemiring R) : IsOrderedRing s := Subtype.coe_injective.isOrderedRing Subtype.val rfl rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) fun _ => rfl /-- A subsemiring of a strict ordered semiring is a strict ordered semiring. -/ instance toIsStrictOrderedRing [Semiring R] [PartialOrder R] [IsStrictOrderedRing R] (s : Subsemiring R) : IsStrictOrderedRing s := Subtype.coe_injective.isStrictOrderedRing Subtype.val rfl rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) fun _ => rfl section nonneg variable [Semiring R] [PartialOrder R] [IsOrderedRing R] variable (R) in /-- The set of nonnegative elements in an ordered semiring, as a subsemiring. -/ @[simps] def nonneg : Subsemiring R where carrier := Set.Ici 0 mul_mem' := mul_nonneg one_mem' := zero_le_one add_mem' := add_nonneg zero_mem' := le_rfl @[simp] lemma mem_nonneg {x : R} : x ∈ nonneg R ↔ 0 ≤ x := .rfl end nonneg end Subsemiring
Pi.lean
/- Copyright (c) 2024 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.RingTheory.Smooth.Pi import Mathlib.RingTheory.Unramified.Pi import Mathlib.RingTheory.Etale.Basic /-! # Formal-étaleness of finite products of rings ## Main result - `Algebra.FormallyEtale.pi_iff`: If `I` is finite, `Π i : I, A i` is `R`-formally-étale if and only if each `A i` is `R`-formally-étale. -/ universe u v namespace Algebra.FormallyEtale variable {R : Type (max u v)} {I : Type u} (A : I → Type (max u v)) variable [CommRing R] [∀ i, CommRing (A i)] [∀ i, Algebra R (A i)] theorem pi_iff [Finite I] : FormallyEtale R (Π i, A i) ↔ ∀ i, FormallyEtale R (A i) := by simp_rw [FormallyEtale.iff_unramified_and_smooth, forall_and] rw [FormallyUnramified.pi_iff A, FormallySmooth.pi_iff A] instance [Finite I] [∀ i, FormallyEtale R (A i)] : FormallyEtale R (Π i, A i) := .of_unramified_and_smooth end Algebra.FormallyEtale
Basic.lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import Mathlib.Algebra.Algebra.Equiv import Mathlib.Algebra.Algebra.NonUnitalSubalgebra import Mathlib.RingTheory.SimpleRing.Basic /-! # Subalgebras over Commutative Semiring In this file we define `Subalgebra`s and the usual operations on them (`map`, `comap`). The `Algebra.adjoin` operation and complete lattice structure can be found in `Mathlib/Algebra/Algebra/Subalgebra/Lattice.lean`. -/ universe u u' v w w' /-- A subalgebra is a sub(semi)ring that includes the range of `algebraMap`. -/ structure Subalgebra (R : Type u) (A : Type v) [CommSemiring R] [Semiring A] [Algebra R A] : Type v extends Subsemiring A where /-- The image of `algebraMap` is contained in the underlying set of the subalgebra -/ algebraMap_mem' : ∀ r, algebraMap R A r ∈ carrier zero_mem' := (algebraMap R A).map_zero ▸ algebraMap_mem' 0 one_mem' := (algebraMap R A).map_one ▸ algebraMap_mem' 1 /-- Reinterpret a `Subalgebra` as a `Subsemiring`. -/ add_decl_doc Subalgebra.toSubsemiring namespace Subalgebra variable {R' : Type u'} {R : Type u} {A : Type v} {B : Type w} {C : Type w'} variable [CommSemiring R] variable [Semiring A] [Algebra R A] [Semiring B] [Algebra R B] [Semiring C] [Algebra R C] instance : SetLike (Subalgebra R A) A where coe s := s.carrier coe_injective' p q h := by cases p; cases q; congr; exact SetLike.coe_injective' h initialize_simps_projections Subalgebra (carrier → coe, as_prefix coe) @[simp] theorem coe_mk (s : Subsemiring A) (h) : (Subalgebra.mk (R := R) s h : Set A) = s := rfl @[simp] theorem mem_mk (s : Subsemiring A) (h) (x) : x ∈ Subalgebra.mk (R := R) s h ↔ x ∈ s := .rfl /-- The actual `Subalgebra` obtained from an element of a type satisfying `SubsemiringClass` and `SMulMemClass`. -/ @[simps] def ofClass {S R A : Type*} [CommSemiring R] [Semiring A] [Algebra R A] [SetLike S A] [SubsemiringClass S A] [SMulMemClass S R A] (s : S) : Subalgebra R A where carrier := s add_mem' := add_mem zero_mem' := zero_mem _ mul_mem' := mul_mem one_mem' := one_mem _ algebraMap_mem' r := Algebra.algebraMap_eq_smul_one (A := A) r ▸ SMulMemClass.smul_mem r (one_mem s) instance (priority := 100) : CanLift (Set A) (Subalgebra R A) (↑) (fun s ↦ (∀ {x y}, x ∈ s → y ∈ s → x + y ∈ s) ∧ (∀ {x y}, x ∈ s → y ∈ s → x * y ∈ s) ∧ ∀ (r : R), algebraMap R A r ∈ s) where prf s h := ⟨ { carrier := s zero_mem' := by simpa using h.2.2 0 add_mem' := h.1 one_mem' := by simpa using h.2.2 1 mul_mem' := h.2.1 algebraMap_mem' := h.2.2 }, rfl ⟩ instance : SubsemiringClass (Subalgebra R A) A where add_mem {s} := add_mem (s := s.toSubsemiring) mul_mem {s} := mul_mem (s := s.toSubsemiring) one_mem {s} := one_mem s.toSubsemiring zero_mem {s} := zero_mem s.toSubsemiring @[simp] theorem mem_toSubsemiring {S : Subalgebra R A} {x} : x ∈ S.toSubsemiring ↔ x ∈ S := Iff.rfl theorem mem_carrier {s : Subalgebra R A} {x : A} : x ∈ s.carrier ↔ x ∈ s := Iff.rfl @[ext] theorem ext {S T : Subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := SetLike.ext h @[simp] theorem coe_toSubsemiring (S : Subalgebra R A) : (↑S.toSubsemiring : Set A) = S := rfl theorem toSubsemiring_injective : Function.Injective (toSubsemiring : Subalgebra R A → Subsemiring A) := fun S T h => ext fun x => by rw [← mem_toSubsemiring, ← mem_toSubsemiring, h] theorem toSubsemiring_inj {S U : Subalgebra R A} : S.toSubsemiring = U.toSubsemiring ↔ S = U := toSubsemiring_injective.eq_iff /-- Copy of a subalgebra with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ @[simps coe toSubsemiring] protected def copy (S : Subalgebra R A) (s : Set A) (hs : s = ↑S) : Subalgebra R A := { S.toSubsemiring.copy s hs with carrier := s algebraMap_mem' := hs.symm ▸ S.algebraMap_mem' } theorem copy_eq (S : Subalgebra R A) (s : Set A) (hs : s = ↑S) : S.copy s hs = S := SetLike.coe_injective hs variable (S : Subalgebra R A) instance instSMulMemClass : SMulMemClass (Subalgebra R A) R A where smul_mem {S} r x hx := (Algebra.smul_def r x).symm ▸ mul_mem (S.algebraMap_mem' r) hx @[simp, aesop safe (rule_sets := [SetLike])] theorem _root_.algebraMap_mem {S R A : Type*} [CommSemiring R] [Semiring A] [Algebra R A] [SetLike S A] [OneMemClass S A] [SMulMemClass S R A] (s : S) (r : R) : algebraMap R A r ∈ s := Algebra.algebraMap_eq_smul_one (A := A) r ▸ SMulMemClass.smul_mem r (one_mem s) protected theorem algebraMap_mem (r : R) : algebraMap R A r ∈ S := algebraMap_mem S r theorem rangeS_le : (algebraMap R A).rangeS ≤ S.toSubsemiring := fun _x ⟨r, hr⟩ => hr ▸ S.algebraMap_mem r theorem range_subset : Set.range (algebraMap R A) ⊆ S := fun _x ⟨r, hr⟩ => hr ▸ S.algebraMap_mem r theorem range_le : Set.range (algebraMap R A) ≤ S := S.range_subset theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r • x ∈ S := SMulMemClass.smul_mem r hx protected theorem one_mem : (1 : A) ∈ S := one_mem S protected theorem mul_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x * y ∈ S := mul_mem hx hy protected theorem pow_mem {x : A} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S := pow_mem hx n protected theorem zero_mem : (0 : A) ∈ S := zero_mem S protected theorem add_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x + y ∈ S := add_mem hx hy protected theorem nsmul_mem {x : A} (hx : x ∈ S) (n : ℕ) : n • x ∈ S := nsmul_mem hx n protected theorem natCast_mem (n : ℕ) : (n : A) ∈ S := natCast_mem S n protected theorem list_prod_mem {L : List A} (h : ∀ x ∈ L, x ∈ S) : L.prod ∈ S := list_prod_mem h protected theorem list_sum_mem {L : List A} (h : ∀ x ∈ L, x ∈ S) : L.sum ∈ S := list_sum_mem h protected theorem multiset_sum_mem {m : Multiset A} (h : ∀ x ∈ m, x ∈ S) : m.sum ∈ S := multiset_sum_mem m h protected theorem sum_mem {ι : Type w} {t : Finset ι} {f : ι → A} (h : ∀ x ∈ t, f x ∈ S) : (∑ x ∈ t, f x) ∈ S := sum_mem h protected theorem multiset_prod_mem {R : Type u} {A : Type v} [CommSemiring R] [CommSemiring A] [Algebra R A] (S : Subalgebra R A) {m : Multiset A} (h : ∀ x ∈ m, x ∈ S) : m.prod ∈ S := multiset_prod_mem m h protected theorem prod_mem {R : Type u} {A : Type v} [CommSemiring R] [CommSemiring A] [Algebra R A] (S : Subalgebra R A) {ι : Type w} {t : Finset ι} {f : ι → A} (h : ∀ x ∈ t, f x ∈ S) : (∏ x ∈ t, f x) ∈ S := prod_mem h /-- Turn a `Subalgebra` into a `NonUnitalSubalgebra` by forgetting that it contains `1`. -/ def toNonUnitalSubalgebra (S : Subalgebra R A) : NonUnitalSubalgebra R A where __ := S smul_mem' r _x hx := S.smul_mem hx r lemma one_mem_toNonUnitalSubalgebra (S : Subalgebra R A) : (1 : A) ∈ S.toNonUnitalSubalgebra := S.one_mem instance {R A : Type*} [CommRing R] [Ring A] [Algebra R A] : SubringClass (Subalgebra R A) A := { Subalgebra.instSubsemiringClass with neg_mem := fun {S x} hx => neg_one_smul R x ▸ S.smul_mem hx _ } protected theorem neg_mem {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] (S : Subalgebra R A) {x : A} (hx : x ∈ S) : -x ∈ S := neg_mem hx protected theorem sub_mem {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] (S : Subalgebra R A) {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S := sub_mem hx hy protected theorem zsmul_mem {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] (S : Subalgebra R A) {x : A} (hx : x ∈ S) (n : ℤ) : n • x ∈ S := zsmul_mem hx n protected theorem intCast_mem {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] (S : Subalgebra R A) (n : ℤ) : (n : A) ∈ S := intCast_mem S n /-- The projection from a subalgebra of `A` to an additive submonoid of `A`. -/ @[simps coe] def toAddSubmonoid {R : Type u} {A : Type v} [CommSemiring R] [Semiring A] [Algebra R A] (S : Subalgebra R A) : AddSubmonoid A := S.toSubsemiring.toAddSubmonoid /-- A subalgebra over a ring is also a `Subring`. -/ @[simps toSubsemiring] def toSubring {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] (S : Subalgebra R A) : Subring A := { S.toSubsemiring with neg_mem' := S.neg_mem } @[simp] theorem mem_toSubring {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] {S : Subalgebra R A} {x} : x ∈ S.toSubring ↔ x ∈ S := Iff.rfl @[simp] theorem coe_toSubring {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] (S : Subalgebra R A) : (↑S.toSubring : Set A) = S := rfl theorem toSubring_injective {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] : Function.Injective (toSubring : Subalgebra R A → Subring A) := fun S T h => ext fun x => by rw [← mem_toSubring, ← mem_toSubring, h] theorem toSubring_inj {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] {S U : Subalgebra R A} : S.toSubring = U.toSubring ↔ S = U := toSubring_injective.eq_iff instance : Inhabited S := ⟨(0 : S.toSubsemiring)⟩ section /-! `Subalgebra`s inherit structure from their `Subsemiring` / `Semiring` coercions. -/ instance toSemiring {R A} [CommSemiring R] [Semiring A] [Algebra R A] (S : Subalgebra R A) : Semiring S := S.toSubsemiring.toSemiring instance toCommSemiring {R A} [CommSemiring R] [CommSemiring A] [Algebra R A] (S : Subalgebra R A) : CommSemiring S := S.toSubsemiring.toCommSemiring instance toRing {R A} [CommRing R] [Ring A] [Algebra R A] (S : Subalgebra R A) : Ring S := S.toSubring.toRing instance toCommRing {R A} [CommRing R] [CommRing A] [Algebra R A] (S : Subalgebra R A) : CommRing S := S.toSubring.toCommRing end /-- The forgetful map from `Subalgebra` to `Submodule` as an `OrderEmbedding` -/ def toSubmodule : Subalgebra R A ↪o Submodule R A where toEmbedding := { toFun := fun S => { S with carrier := S smul_mem' := fun c {x} hx ↦ (Algebra.smul_def c x).symm ▸ mul_mem (S.range_le ⟨c, rfl⟩) hx } inj' := fun _ _ h ↦ ext fun x ↦ SetLike.ext_iff.mp h x } map_rel_iff' := SetLike.coe_subset_coe.symm.trans SetLike.coe_subset_coe /- TODO: bundle other forgetful maps between algebraic substructures, e.g. `toSubsemiring` and `toSubring` in this file. -/ @[simp] theorem mem_toSubmodule {x} : x ∈ (toSubmodule S) ↔ x ∈ S := Iff.rfl @[simp] theorem coe_toSubmodule (S : Subalgebra R A) : (toSubmodule S : Set A) = S := rfl theorem toSubmodule_injective : Function.Injective (toSubmodule : Subalgebra R A → Submodule R A) := fun _S₁ _S₂ h => SetLike.ext (SetLike.ext_iff.mp h :) section /-! `Subalgebra`s inherit structure from their `Submodule` coercions. -/ instance (priority := low) module' [Semiring R'] [SMul R' R] [Module R' A] [IsScalarTower R' R A] : Module R' S := S.toSubmodule.module' instance : Module R S := S.module' instance [Semiring R'] [SMul R' R] [Module R' A] [IsScalarTower R' R A] : IsScalarTower R' R S := inferInstanceAs (IsScalarTower R' R (toSubmodule S)) /- More general form of `Subalgebra.algebra`. This instance should have low priority since it is slow to fail: before failing, it will cause a search through all `SMul R' R` instances, which can quickly get expensive. -/ instance (priority := 500) algebra' [CommSemiring R'] [SMul R' R] [Algebra R' A] [IsScalarTower R' R A] : Algebra R' S where algebraMap := (algebraMap R' A).codRestrict S fun x => by rw [Algebra.algebraMap_eq_smul_one, ← smul_one_smul R x (1 : A), ← Algebra.algebraMap_eq_smul_one] exact algebraMap_mem S _ commutes' := fun _ _ => Subtype.eq <| Algebra.commutes _ _ smul_def' := fun _ _ => Subtype.eq <| Algebra.smul_def _ _ instance algebra : Algebra R S := S.algebra' @[simp] theorem mk_algebraMap {S : Subalgebra R A} (r : R) (hr : algebraMap R A r ∈ S) : ⟨algebraMap R A r, hr⟩ = algebraMap R S r := rfl end instance noZeroSMulDivisors_bot [NoZeroSMulDivisors R A] : NoZeroSMulDivisors R S := ⟨fun {c} {x : S} h => have : c = 0 ∨ (x : A) = 0 := eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg Subtype.val h) this.imp_right (@Subtype.ext_iff _ _ x 0).mpr⟩ protected theorem coe_add (x y : S) : (↑(x + y) : A) = ↑x + ↑y := rfl protected theorem coe_mul (x y : S) : (↑(x * y) : A) = ↑x * ↑y := rfl protected theorem coe_zero : ((0 : S) : A) = 0 := rfl protected theorem coe_one : ((1 : S) : A) = 1 := rfl protected theorem coe_neg {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] {S : Subalgebra R A} (x : S) : (↑(-x) : A) = -↑x := rfl protected theorem coe_sub {R : Type u} {A : Type v} [CommRing R] [Ring A] [Algebra R A] {S : Subalgebra R A} (x y : S) : (↑(x - y) : A) = ↑x - ↑y := rfl @[simp, norm_cast] theorem coe_smul [SMul R' R] [SMul R' A] [IsScalarTower R' R A] (r : R') (x : S) : (↑(r • x) : A) = r • (x : A) := rfl @[simp, norm_cast] theorem coe_algebraMap [CommSemiring R'] [SMul R' R] [Algebra R' A] [IsScalarTower R' R A] (r : R') : ↑(algebraMap R' S r) = algebraMap R' A r := rfl protected theorem coe_pow (x : S) (n : ℕ) : (↑(x ^ n) : A) = (x : A) ^ n := SubmonoidClass.coe_pow x n protected theorem coe_eq_zero {x : S} : (x : A) = 0 ↔ x = 0 := ZeroMemClass.coe_eq_zero protected theorem coe_eq_one {x : S} : (x : A) = 1 ↔ x = 1 := OneMemClass.coe_eq_one -- todo: standardize on the names these morphisms -- compare with submodule.subtype /-- Embedding of a subalgebra into the algebra. -/ def val : S →ₐ[R] A := { toFun := ((↑) : S → A) map_zero' := rfl map_one' := rfl map_add' := fun _ _ ↦ rfl map_mul' := fun _ _ ↦ rfl commutes' := fun _ ↦ rfl } @[simp] theorem coe_val : (S.val : S → A) = ((↑) : S → A) := rfl theorem val_apply (x : S) : S.val x = (x : A) := rfl @[simp] theorem toSubsemiring_subtype : S.toSubsemiring.subtype = (S.val : S →+* A) := rfl @[simp] theorem toSubring_subtype {R A : Type*} [CommRing R] [Ring A] [Algebra R A] (S : Subalgebra R A) : S.toSubring.subtype = (S.val : S →+* A) := rfl /-- Linear equivalence between `S : Submodule R A` and `S`. Though these types are equal, we define it as a `LinearEquiv` to avoid type equalities. -/ def toSubmoduleEquiv (S : Subalgebra R A) : toSubmodule S ≃ₗ[R] S := LinearEquiv.ofEq _ _ rfl /-- Transport a subalgebra via an algebra homomorphism. -/ @[simps! coe toSubsemiring] def map (f : A →ₐ[R] B) (S : Subalgebra R A) : Subalgebra R B := { S.toSubsemiring.map (f : A →+* B) with algebraMap_mem' := fun r => f.commutes r ▸ Set.mem_image_of_mem _ (S.algebraMap_mem r) } theorem map_mono {S₁ S₂ : Subalgebra R A} {f : A →ₐ[R] B} : S₁ ≤ S₂ → S₁.map f ≤ S₂.map f := Set.image_mono theorem map_injective {f : A →ₐ[R] B} (hf : Function.Injective f) : Function.Injective (map f) := fun _S₁ _S₂ ih => ext <| Set.ext_iff.1 <| Set.image_injective.2 hf <| Set.ext <| SetLike.ext_iff.mp ih @[simp] theorem map_id (S : Subalgebra R A) : S.map (AlgHom.id R A) = S := SetLike.coe_injective <| Set.image_id _ theorem map_map (S : Subalgebra R A) (g : B →ₐ[R] C) (f : A →ₐ[R] B) : (S.map f).map g = S.map (g.comp f) := SetLike.coe_injective <| Set.image_image _ _ _ @[simp] theorem mem_map {S : Subalgebra R A} {f : A →ₐ[R] B} {y : B} : y ∈ map f S ↔ ∃ x ∈ S, f x = y := Subsemiring.mem_map theorem map_toSubmodule {S : Subalgebra R A} {f : A →ₐ[R] B} : (toSubmodule <| S.map f) = S.toSubmodule.map f.toLinearMap := SetLike.coe_injective rfl /-- Preimage of a subalgebra under an algebra homomorphism. -/ @[simps! coe toSubsemiring] def comap (f : A →ₐ[R] B) (S : Subalgebra R B) : Subalgebra R A := { S.toSubsemiring.comap (f : A →+* B) with algebraMap_mem' := fun r => show f (algebraMap R A r) ∈ S from (f.commutes r).symm ▸ S.algebraMap_mem r } attribute [norm_cast] coe_comap theorem map_le {S : Subalgebra R A} {f : A →ₐ[R] B} {U : Subalgebra R B} : map f S ≤ U ↔ S ≤ comap f U := Set.image_subset_iff theorem gc_map_comap (f : A →ₐ[R] B) : GaloisConnection (map f) (comap f) := fun _S _U => map_le @[simp] theorem mem_comap (S : Subalgebra R B) (f : A →ₐ[R] B) (x : A) : x ∈ S.comap f ↔ f x ∈ S := Iff.rfl instance noZeroDivisors {R A : Type*} [CommSemiring R] [Semiring A] [NoZeroDivisors A] [Algebra R A] (S : Subalgebra R A) : NoZeroDivisors S := inferInstanceAs (NoZeroDivisors S.toSubsemiring) instance isDomain {R A : Type*} [CommRing R] [Ring A] [IsDomain A] [Algebra R A] (S : Subalgebra R A) : IsDomain S := inferInstanceAs (IsDomain S.toSubring) end Subalgebra namespace SubalgebraClass variable {S R A : Type*} [CommSemiring R] [Semiring A] [Algebra R A] variable [SetLike S A] [SubsemiringClass S A] [hSR : SMulMemClass S R A] (s : S) instance (priority := 75) toAlgebra : Algebra R s where algebraMap := { toFun r := ⟨algebraMap R A r, algebraMap_mem s r⟩ map_one' := Subtype.ext <| by simp map_mul' _ _ := Subtype.ext <| by simp map_zero' := Subtype.ext <| by simp map_add' _ _ := Subtype.ext <| by simp} commutes' r x := Subtype.ext <| Algebra.commutes r (x : A) smul_def' r x := Subtype.ext <| (algebraMap_smul A r (x : A)).symm @[simp, norm_cast] lemma coe_algebraMap (r : R) : (algebraMap R s r : A) = algebraMap R A r := rfl /-- Embedding of a subalgebra into the algebra, as an algebra homomorphism. -/ def val (s : S) : s →ₐ[R] A := { SubsemiringClass.subtype s, SMulMemClass.subtype s with toFun := (↑) commutes' := fun _ ↦ rfl } @[simp] theorem coe_val : (val s : s → A) = ((↑) : s → A) := rfl end SubalgebraClass namespace Submodule variable {R A : Type*} [CommSemiring R] [Semiring A] [Algebra R A] variable (p : Submodule R A) /-- A submodule containing `1` and closed under multiplication is a subalgebra. -/ @[simps coe toSubsemiring] def toSubalgebra (p : Submodule R A) (h_one : (1 : A) ∈ p) (h_mul : ∀ x y, x ∈ p → y ∈ p → x * y ∈ p) : Subalgebra R A := { p with mul_mem' := fun hx hy ↦ h_mul _ _ hx hy one_mem' := h_one algebraMap_mem' := fun r => by rw [Algebra.algebraMap_eq_smul_one] exact p.smul_mem _ h_one } @[simp] theorem mem_toSubalgebra {p : Submodule R A} {h_one h_mul} {x} : x ∈ p.toSubalgebra h_one h_mul ↔ x ∈ p := Iff.rfl theorem toSubalgebra_mk (s : Submodule R A) (h1 hmul) : s.toSubalgebra h1 hmul = Subalgebra.mk ⟨⟨⟨s, @hmul⟩, h1⟩, s.add_mem, s.zero_mem⟩ (by intro r; rw [Algebra.algebraMap_eq_smul_one]; apply s.smul_mem _ h1) := rfl @[simp] theorem toSubalgebra_toSubmodule (p : Submodule R A) (h_one h_mul) : Subalgebra.toSubmodule (p.toSubalgebra h_one h_mul) = p := SetLike.coe_injective rfl @[simp] theorem _root_.Subalgebra.toSubmodule_toSubalgebra (S : Subalgebra R A) : (S.toSubmodule.toSubalgebra S.one_mem fun _ _ => S.mul_mem) = S := SetLike.coe_injective rfl end Submodule namespace AlgHom variable {R' : Type u'} {R : Type u} {A : Type v} {B : Type w} {C : Type w'} variable [CommSemiring R] variable [Semiring A] [Algebra R A] [Semiring B] [Algebra R B] [Semiring C] [Algebra R C] variable (φ : A →ₐ[R] B) /-- Range of an `AlgHom` as a subalgebra. -/ @[simps! coe toSubsemiring] protected def range (φ : A →ₐ[R] B) : Subalgebra R B := { φ.toRingHom.rangeS with algebraMap_mem' := fun r => ⟨algebraMap R A r, φ.commutes r⟩ } @[simp] theorem mem_range (φ : A →ₐ[R] B) {y : B} : y ∈ φ.range ↔ ∃ x, φ x = y := RingHom.mem_rangeS theorem mem_range_self (φ : A →ₐ[R] B) (x : A) : φ x ∈ φ.range := φ.mem_range.2 ⟨x, rfl⟩ theorem range_comp (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).range = f.range.map g := SetLike.coe_injective (Set.range_comp g f) theorem range_comp_le_range (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).range ≤ g.range := SetLike.coe_mono (Set.range_comp_subset_range f g) /-- Restrict the codomain of an algebra homomorphism. -/ def codRestrict (f : A →ₐ[R] B) (S : Subalgebra R B) (hf : ∀ x, f x ∈ S) : A →ₐ[R] S := { RingHom.codRestrict (f : A →+* B) S hf with commutes' := fun r => Subtype.eq <| f.commutes r } @[simp] theorem val_comp_codRestrict (f : A →ₐ[R] B) (S : Subalgebra R B) (hf : ∀ x, f x ∈ S) : S.val.comp (f.codRestrict S hf) = f := AlgHom.ext fun _ => rfl @[simp] theorem coe_codRestrict (f : A →ₐ[R] B) (S : Subalgebra R B) (hf : ∀ x, f x ∈ S) (x : A) : ↑(f.codRestrict S hf x) = f x := rfl theorem injective_codRestrict (f : A →ₐ[R] B) (S : Subalgebra R B) (hf : ∀ x, f x ∈ S) : Function.Injective (f.codRestrict S hf) ↔ Function.Injective f := ⟨fun H _x _y hxy => H <| Subtype.eq hxy, fun H _x _y hxy => H (congr_arg Subtype.val hxy :)⟩ /-- Restrict the codomain of an `AlgHom` `f` to `f.range`. This is the bundled version of `Set.rangeFactorization`. -/ abbrev rangeRestrict (f : A →ₐ[R] B) : A →ₐ[R] f.range := f.codRestrict f.range f.mem_range_self theorem rangeRestrict_surjective (f : A →ₐ[R] B) : Function.Surjective (f.rangeRestrict) := fun ⟨_y, hy⟩ => let ⟨x, hx⟩ := hy ⟨x, SetCoe.ext hx⟩ /-- The range of a morphism of algebras is a fintype, if the domain is a fintype. Note that this instance can cause a diamond with `Subtype.fintype` if `B` is also a fintype. -/ instance fintypeRange [Fintype A] [DecidableEq B] (φ : A →ₐ[R] B) : Fintype φ.range := Set.fintypeRange φ end AlgHom namespace AlgEquiv variable {R : Type u} {A : Type v} {B : Type w} variable [CommSemiring R] [Semiring A] [Semiring B] [Algebra R A] [Algebra R B] /-- Restrict an algebra homomorphism with a left inverse to an algebra isomorphism to its range. This is a computable alternative to `AlgEquiv.ofInjective`. -/ def ofLeftInverse {g : B → A} {f : A →ₐ[R] B} (h : Function.LeftInverse g f) : A ≃ₐ[R] f.range := { f.rangeRestrict with toFun := f.rangeRestrict invFun := g ∘ f.range.val left_inv := h right_inv := fun x => Subtype.ext <| let ⟨x', hx'⟩ := f.mem_range.mp x.prop show f (g x) = x by rw [← hx', h x'] } @[simp] theorem ofLeftInverse_apply {g : B → A} {f : A →ₐ[R] B} (h : Function.LeftInverse g f) (x : A) : ↑(ofLeftInverse h x) = f x := rfl @[simp] theorem ofLeftInverse_symm_apply {g : B → A} {f : A →ₐ[R] B} (h : Function.LeftInverse g f) (x : f.range) : (ofLeftInverse h).symm x = g x := rfl /-- Restrict an injective algebra homomorphism to an algebra isomorphism -/ noncomputable def ofInjective (f : A →ₐ[R] B) (hf : Function.Injective f) : A ≃ₐ[R] f.range := ofLeftInverse (Classical.choose_spec hf.hasLeftInverse) @[simp] theorem ofInjective_apply (f : A →ₐ[R] B) (hf : Function.Injective f) (x : A) : ↑(ofInjective f hf x) = f x := rfl /-- Restrict an algebra homomorphism between fields to an algebra isomorphism -/ noncomputable def ofInjectiveField {E F : Type*} [DivisionRing E] [Semiring F] [Nontrivial F] [Algebra R E] [Algebra R F] (f : E →ₐ[R] F) : E ≃ₐ[R] f.range := ofInjective f f.toRingHom.injective /-- Given an equivalence `e : A ≃ₐ[R] B` of `R`-algebras and a subalgebra `S` of `A`, `subalgebraMap` is the induced equivalence between `S` and `S.map e` -/ @[simps!] def subalgebraMap (e : A ≃ₐ[R] B) (S : Subalgebra R A) : S ≃ₐ[R] S.map (e : A →ₐ[R] B) := { e.toRingEquiv.subsemiringMap S.toSubsemiring with commutes' := fun r => by ext; exact e.commutes r } end AlgEquiv namespace Subalgebra open Algebra variable {R : Type u} {A : Type v} {B : Type w} variable [CommSemiring R] [Semiring A] [Algebra R A] [Semiring B] [Algebra R B] variable (S T U : Subalgebra R A) instance subsingleton_of_subsingleton [Subsingleton A] : Subsingleton (Subalgebra R A) := ⟨fun B C => ext fun x => by simp only [Subsingleton.elim x 0, zero_mem B, zero_mem C]⟩ theorem range_val : S.val.range = S := ext <| Set.ext_iff.1 <| S.val.coe_range.trans Subtype.range_val /-- The map `S → T` when `S` is a subalgebra contained in the subalgebra `T`. This is the subalgebra version of `Submodule.inclusion`, or `Subring.inclusion` -/ def inclusion {S T : Subalgebra R A} (h : S ≤ T) : S →ₐ[R] T where toFun := Set.inclusion h map_one' := rfl map_add' _ _ := rfl map_mul' _ _ := rfl map_zero' := rfl commutes' _ := rfl variable {S T U} (h : S ≤ T) theorem inclusion_injective : Function.Injective (inclusion h) := fun _ _ => Subtype.ext ∘ Subtype.mk.inj @[simp] theorem inclusion_self : inclusion (le_refl S) = AlgHom.id R S := AlgHom.ext fun _x => Subtype.ext rfl @[simp] theorem inclusion_mk (x : A) (hx : x ∈ S) : inclusion h ⟨x, hx⟩ = ⟨x, h hx⟩ := rfl theorem inclusion_right (x : T) (m : (x : A) ∈ S) : inclusion h ⟨x, m⟩ = x := Subtype.ext rfl @[simp] theorem inclusion_inclusion (hst : S ≤ T) (htu : T ≤ U) (x : S) : inclusion htu (inclusion hst x) = inclusion (le_trans hst htu) x := Subtype.ext rfl @[simp] theorem coe_inclusion (s : S) : (inclusion h s : A) = s := rfl namespace inclusion scoped instance isScalarTower_left (X) [SMul X R] [SMul X A] [IsScalarTower X R A] : letI := (inclusion h).toModule; IsScalarTower X S T := letI := (inclusion h).toModule ⟨fun x s t ↦ Subtype.ext <| by rw [← one_smul R s, ← smul_assoc, one_smul, ← one_smul R (s • t), ← smul_assoc, Algebra.smul_def, Algebra.smul_def] apply mul_assoc⟩ scoped instance isScalarTower_right (X) [MulAction A X] : letI := (inclusion h).toModule; IsScalarTower S T X := letI := (inclusion h).toModule; ⟨fun _ ↦ mul_smul _⟩ scoped instance faithfulSMul : letI := (inclusion h).toModule; FaithfulSMul S T := letI := (inclusion h).toModule ⟨fun {x y} h ↦ Subtype.ext <| by convert Subtype.ext_iff.mp (h 1) using 1 <;> exact (mul_one _).symm⟩ end inclusion variable (S) /-- Two subalgebras that are equal are also equivalent as algebras. This is the `Subalgebra` version of `LinearEquiv.ofEq` and `Equiv.setCongr`. -/ @[simps apply] def equivOfEq (S T : Subalgebra R A) (h : S = T) : S ≃ₐ[R] T where __ := LinearEquiv.ofEq _ _ (congr_arg toSubmodule h) toFun x := ⟨x, h ▸ x.2⟩ invFun x := ⟨x, h.symm ▸ x.2⟩ map_mul' _ _ := rfl commutes' _ := rfl @[simp] theorem equivOfEq_symm (S T : Subalgebra R A) (h : S = T) : (equivOfEq S T h).symm = equivOfEq T S h.symm := rfl @[simp] theorem equivOfEq_rfl (S : Subalgebra R A) : equivOfEq S S rfl = AlgEquiv.refl := by ext; rfl @[simp] theorem equivOfEq_trans (S T U : Subalgebra R A) (hST : S = T) (hTU : T = U) : (equivOfEq S T hST).trans (equivOfEq T U hTU) = equivOfEq S U (hST.trans hTU) := rfl section equivMapOfInjective variable (f : A →ₐ[R] B) theorem range_comp_val : (f.comp S.val).range = S.map f := by rw [AlgHom.range_comp, range_val] /-- An `AlgHom` between two rings restricts to an `AlgHom` from any subalgebra of the domain onto the image of that subalgebra. -/ def _root_.AlgHom.subalgebraMap : S →ₐ[R] S.map f := (f.comp S.val).codRestrict _ fun x ↦ ⟨_, x.2, rfl⟩ variable {S} in @[simp] theorem _root_.AlgHom.subalgebraMap_coe_apply (x : S) : f.subalgebraMap S x = f x := rfl theorem _root_.AlgHom.subalgebraMap_surjective : Function.Surjective (f.subalgebraMap S) := f.toAddMonoidHom.addSubmonoidMap_surjective S.toAddSubmonoid variable (hf : Function.Injective f) /-- A subalgebra is isomorphic to its image under an injective `AlgHom` -/ noncomputable def equivMapOfInjective : S ≃ₐ[R] S.map f := (AlgEquiv.ofInjective (f.comp S.val) (hf.comp Subtype.val_injective)).trans (equivOfEq _ _ (range_comp_val S f)) @[simp] theorem coe_equivMapOfInjective_apply (x : S) : ↑(equivMapOfInjective S f hf x) = f x := rfl end equivMapOfInjective /-! ## Actions by `Subalgebra`s These are just copies of the definitions about `Subsemiring` starting from `Subring.mulAction`. -/ section Actions variable {α β : Type*} /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [SMul A α] (S : Subalgebra R A) : SMul S α := inferInstanceAs (SMul S.toSubsemiring α) theorem smul_def [SMul A α] {S : Subalgebra R A} (g : S) (m : α) : g • m = (g : A) • m := rfl instance smulCommClass_left [SMul A β] [SMul α β] [SMulCommClass A α β] (S : Subalgebra R A) : SMulCommClass S α β := S.toSubsemiring.smulCommClass_left instance smulCommClass_right [SMul α β] [SMul A β] [SMulCommClass α A β] (S : Subalgebra R A) : SMulCommClass α S β := S.toSubsemiring.smulCommClass_right /-- Note that this provides `IsScalarTower S R R` which is needed by `smul_mul_assoc`. -/ instance isScalarTower_left [SMul α β] [SMul A α] [SMul A β] [IsScalarTower A α β] (S : Subalgebra R A) : IsScalarTower S α β := inferInstanceAs (IsScalarTower S.toSubsemiring α β) instance isScalarTower_mid {R S T : Type*} [CommSemiring R] [Semiring S] [AddCommMonoid T] [Algebra R S] [Module R T] [Module S T] [IsScalarTower R S T] (S' : Subalgebra R S) : IsScalarTower R S' T := ⟨fun _x y _z => smul_assoc _ (y : S) _⟩ instance [SMul A α] [FaithfulSMul A α] (S : Subalgebra R A) : FaithfulSMul S α := inferInstanceAs (FaithfulSMul S.toSubsemiring α) /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [MulAction A α] (S : Subalgebra R A) : MulAction S α := inferInstanceAs (MulAction S.toSubsemiring α) /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [AddMonoid α] [DistribMulAction A α] (S : Subalgebra R A) : DistribMulAction S α := inferInstanceAs (DistribMulAction S.toSubsemiring α) /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [Zero α] [SMulWithZero A α] (S : Subalgebra R A) : SMulWithZero S α := inferInstanceAs (SMulWithZero S.toSubsemiring α) /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [Zero α] [MulActionWithZero A α] (S : Subalgebra R A) : MulActionWithZero S α := inferInstanceAs (MulActionWithZero S.toSubsemiring α) /-- The action by a subalgebra is the action by the underlying algebra. -/ instance moduleLeft [AddCommMonoid α] [Module A α] (S : Subalgebra R A) : Module S α := inferInstanceAs (Module S.toSubsemiring α) /-- The action by a subalgebra is the action by the underlying algebra. -/ instance toAlgebra {R A : Type*} [CommSemiring R] [CommSemiring A] [Semiring α] [Algebra R A] [Algebra A α] (S : Subalgebra R A) : Algebra S α := Algebra.ofSubsemiring S.toSubsemiring theorem algebraMap_eq {R A : Type*} [CommSemiring R] [CommSemiring A] [Semiring α] [Algebra R A] [Algebra A α] (S : Subalgebra R A) : algebraMap S α = (algebraMap A α).comp S.val := rfl theorem algebraMap_def {R A : Type*} [CommSemiring R] [CommSemiring A] [Semiring α] [Algebra R A] [Algebra A α] {S : Subalgebra R A} (s : S) : algebraMap S α s = algebraMap A α (s : A) := rfl @[simp] theorem algebraMap_mk {R A : Type*} [CommSemiring R] [CommSemiring A] [Semiring α] [Algebra R A] [Algebra A α] {S : Subalgebra R A} (a : A) (ha : a ∈ S) : algebraMap S α (⟨a, ha⟩ : S) = algebraMap A α a := rfl @[simp] theorem rangeS_algebraMap {R A : Type*} [CommSemiring R] [CommSemiring A] [Algebra R A] (S : Subalgebra R A) : (algebraMap S A).rangeS = S.toSubsemiring := by rw [algebraMap_eq, Algebra.algebraMap_self, RingHom.id_comp, ← toSubsemiring_subtype, Subsemiring.rangeS_subtype] @[simp] theorem range_algebraMap {R A : Type*} [CommRing R] [CommRing A] [Algebra R A] (S : Subalgebra R A) : (algebraMap S A).range = S.toSubring := by rw [algebraMap_eq, Algebra.algebraMap_self, RingHom.id_comp, ← toSubring_subtype, Subring.range_subtype] instance noZeroSMulDivisors_top [NoZeroDivisors A] (S : Subalgebra R A) : NoZeroSMulDivisors S A := ⟨fun {c} x h => have : (c : A) = 0 ∨ x = 0 := eq_zero_or_eq_zero_of_mul_eq_zero h this.imp_left (@Subtype.ext_iff _ _ c 0).mpr⟩ end Actions section Center theorem _root_.Set.algebraMap_mem_center (r : R) : algebraMap R A r ∈ Set.center A := by simp only [Semigroup.mem_center_iff, commutes, forall_const] variable (R A) /-- The center of an algebra is the set of elements which commute with every element. They form a subalgebra. -/ @[simps! coe toSubsemiring] def center : Subalgebra R A := { Subsemiring.center A with algebraMap_mem' := Set.algebraMap_mem_center } @[simp] theorem center_toSubring (R A : Type*) [CommRing R] [Ring A] [Algebra R A] : (center R A).toSubring = Subring.center A := rfl variable {R A} instance : CommSemiring (center R A) := inferInstanceAs (CommSemiring (Subsemiring.center A)) instance {A : Type*} [Ring A] [Algebra R A] : CommRing (center R A) := inferInstanceAs (CommRing (Subring.center A)) theorem mem_center_iff {a : A} : a ∈ center R A ↔ ∀ b : A, b * a = a * b := Subsemigroup.mem_center_iff end Center section Centralizer @[simp] theorem _root_.Set.algebraMap_mem_centralizer {s : Set A} (r : R) : algebraMap R A r ∈ s.centralizer := fun _a _h => (Algebra.commutes _ _).symm variable (R) /-- The centralizer of a set as a subalgebra. -/ def centralizer (s : Set A) : Subalgebra R A := { Subsemiring.centralizer s with algebraMap_mem' := Set.algebraMap_mem_centralizer } @[simp, norm_cast] theorem coe_centralizer (s : Set A) : (centralizer R s : Set A) = s.centralizer := rfl theorem mem_centralizer_iff {s : Set A} {z : A} : z ∈ centralizer R s ↔ ∀ g ∈ s, g * z = z * g := Iff.rfl theorem center_le_centralizer (s) : center R A ≤ centralizer R s := s.center_subset_centralizer theorem centralizer_le (s t : Set A) (h : s ⊆ t) : centralizer R t ≤ centralizer R s := Set.centralizer_subset h @[simp] theorem centralizer_univ : centralizer R Set.univ = center R A := SetLike.ext' (Set.centralizer_univ A) lemma le_centralizer_centralizer {s : Subalgebra R A} : s ≤ centralizer R (centralizer R (s : Set A)) := Set.subset_centralizer_centralizer @[simp] lemma centralizer_centralizer_centralizer {s : Set A} : centralizer R s.centralizer.centralizer = centralizer R s := by apply SetLike.coe_injective simp only [coe_centralizer, Set.centralizer_centralizer_centralizer] end Centralizer end Subalgebra section Nat variable {R : Type*} [Semiring R] /-- A subsemiring is an `ℕ`-subalgebra. -/ @[simps toSubsemiring] def subalgebraOfSubsemiring (S : Subsemiring R) : Subalgebra ℕ R := { S with algebraMap_mem' := fun i => natCast_mem S i } @[simp] theorem mem_subalgebraOfSubsemiring {x : R} {S : Subsemiring R} : x ∈ subalgebraOfSubsemiring S ↔ x ∈ S := Iff.rfl end Nat section Int variable {R : Type*} [Ring R] /-- A subring is a `ℤ`-subalgebra. -/ @[simps toSubsemiring] def subalgebraOfSubring (S : Subring R) : Subalgebra ℤ R := { S with algebraMap_mem' := fun i => Int.induction_on i (by simp) (fun i ih => by simpa using S.add_mem ih S.one_mem) fun i ih => show ((-i - 1 : ℤ) : R) ∈ S by rw [Int.cast_sub, Int.cast_one] exact S.sub_mem ih S.one_mem } variable {S : Type*} [Semiring S] @[simp] theorem mem_subalgebraOfSubring {x : R} {S : Subring R} : x ∈ subalgebraOfSubring S ↔ x ∈ S := Iff.rfl end Int section Equalizer namespace AlgHom variable {R A B : Type*} [CommSemiring R] [Semiring A] [Algebra R A] [Semiring B] [Algebra R B] variable {F : Type*} /-- The equalizer of two R-algebra homomorphisms -/ @[simps coe toSubsemiring] def equalizer (ϕ ψ : F) [FunLike F A B] [AlgHomClass F R A B] : Subalgebra R A where carrier := { a | ϕ a = ψ a } zero_mem' := by simp only [Set.mem_setOf_eq, map_zero] one_mem' := by simp only [Set.mem_setOf_eq, map_one] add_mem' {x y} (hx : ϕ x = ψ x) (hy : ϕ y = ψ y) := by rw [Set.mem_setOf_eq, map_add, map_add, hx, hy] mul_mem' {x y} (hx : ϕ x = ψ x) (hy : ϕ y = ψ y) := by rw [Set.mem_setOf_eq, map_mul, map_mul, hx, hy] algebraMap_mem' x := by simp only [Set.mem_setOf_eq, AlgHomClass.commutes] variable [FunLike F A B] [AlgHomClass F R A B] @[simp] theorem mem_equalizer (φ ψ : F) (x : A) : x ∈ equalizer φ ψ ↔ φ x = ψ x := Iff.rfl theorem equalizer_toSubmodule {φ ψ : F} : Subalgebra.toSubmodule (equalizer φ ψ) = LinearMap.eqLocus φ ψ := rfl theorem le_equalizer {φ ψ : F} {S : Subalgebra R A} : S ≤ equalizer φ ψ ↔ Set.EqOn φ ψ S := Iff.rfl end AlgHom end Equalizer section MapComap namespace Subalgebra variable {R A B : Type*} [CommSemiring R] [Semiring A] [Algebra R A] [Semiring B] [Algebra R B] theorem comap_map_eq_self_of_injective {f : A →ₐ[R] B} (hf : Function.Injective f) (S : Subalgebra R A) : (S.map f).comap f = S := SetLike.coe_injective (Set.preimage_image_eq _ hf) end Subalgebra end MapComap variable {R A : Type*} [CommSemiring R] [Semiring A] [Algebra R A] /-- Turn a non-unital subalgebra containing `1` into a subalgebra. -/ def NonUnitalSubalgebra.toSubalgebra (S : NonUnitalSubalgebra R A) (h1 : (1 : A) ∈ S) : Subalgebra R A := { S with one_mem' := h1 algebraMap_mem' := fun r => (Algebra.algebraMap_eq_smul_one (R := R) (A := A) r).symm ▸ SMulMemClass.smul_mem r h1 } lemma Subalgebra.toNonUnitalSubalgebra_toSubalgebra (S : Subalgebra R A) : S.toNonUnitalSubalgebra.toSubalgebra S.one_mem = S := by cases S; rfl lemma NonUnitalSubalgebra.toSubalgebra_toNonUnitalSubalgebra (S : NonUnitalSubalgebra R A) (h1 : (1 : A) ∈ S) : (NonUnitalSubalgebra.toSubalgebra S h1).toNonUnitalSubalgebra = S := by cases S; rfl
Style.lean
/- Copyright (c) 2024 Michael Rothgang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Rothgang -/ import Lean.Elab.Command import Lean.Server.InfoUtils -- Import this linter explicitly to ensure that -- this file has a valid copyright header and module docstring. import Mathlib.Tactic.Linter.Header import Mathlib.Tactic.DeclarationNames /-! ## Style linters This file contain linters about stylistic aspects: these are only about coding style, but do not affect correctness nor global coherence of mathlib. Historically, some of these were ported from the `lint-style.py` Python script. This file defines the following linters: - the `setOption` linter checks for the presence of `set_option` commands activating options disallowed in mathlib: these are meant to be temporary, and not for polished code. It also checks for `maxHeartbeats` options being present which are not scoped to single commands. - the `missingEnd` linter checks for sections or namespaces which are not closed by the end of the file: enforcing this invariant makes minimising files or moving code between files easier - the `cdotLinter` linter checks for focusing dots `·` which are typed using a `.` instead: this is allowed Lean syntax, but it is nicer to be uniform - the `dollarSyntax` linter checks for use of the dollar sign `$` instead of the `<|` pipe operator: similarly, both symbols have the same meaning, but mathlib prefers `<|` for the symmetry with the `|>` symbol - the `lambdaSyntax` linter checks for uses of the `λ` symbol for anonymous functions, instead of the `fun` keyword: mathlib prefers the latter for reasons of readability - the `longFile` linter checks for files which have more than 1500 lines - the `longLine` linter checks for lines which have more than 100 characters - the `openClassical` linter checks for `open (scoped) Classical` statements which are not scoped to a single declaration - the `show` linter checks for `show`s that change the goal and should be replaced by `change` All of these linters are enabled in mathlib by default, but disabled globally since they enforce conventions which are inherently subjective. -/ open Lean Parser Elab Command Meta Linter namespace Mathlib.Linter /-- The `setOption` linter emits a warning on a `set_option` command, term or tactic which sets a `pp`, `profiler` or `trace` option. It also warns on an option containing `maxHeartbeats` (as these should be scoped as `set_option ... in` instead). -/ register_option linter.style.setOption : Bool := { defValue := false descr := "enable the `setOption` linter" } namespace Style.setOption /-- Whether a syntax element is a `set_option` command, tactic or term: Return the name of the option being set, if any. -/ def parseSetOption : Syntax → Option Name -- This handles all four possibilities of `_val`: a string, number, `true` and `false`. | `(command|set_option $name:ident $_val) => some name.getId | `(set_option $name:ident $_val in $_x) => some name.getId | `(tactic|set_option $name:ident $_val in $_x) => some name.getId | _ => none /-- Whether a given piece of syntax is a `set_option` command, tactic or term. -/ def isSetOption : Syntax → Bool := fun stx ↦ parseSetOption stx matches some _name /-- The `setOption` linter: this lints any `set_option` command, term or tactic which sets a `debug`, `pp`, `profiler` or `trace` option. This also warns if an option containing `maxHeartbeats` (typically, the `maxHeartbeats` or `synthInstance.maxHeartbeats` option) is set. **Why is this bad?** The `debug`, `pp`, `profiler` and `trace` options are good for debugging, but should not be used in production code. `maxHeartbeats` options should be scoped as `set_option opt in ...` (and be followed by a comment explaining the need for them; another linter enforces this). **How to fix this?** The `maxHeartbeats` options can be scoped to individual commands, if they are truly necessary. The `debug`, `pp`, `profiler` and `trace` are usually not necessary for production code, so you can simply remove them. (Some tests will intentionally use one of these options; in this case, simply allow the linter.) -/ def setOptionLinter : Linter where run := withSetOptionIn fun stx => do unless getLinterValue linter.style.setOption (← getLinterOptions) do return if (← MonadState.get).messages.hasErrors then return if let some head := stx.find? isSetOption then if let some name := parseSetOption head then let forbidden := [`debug, `pp, `profiler, `trace] if forbidden.contains name.getRoot then Linter.logLint linter.style.setOption head m!"Setting options starting with '{"', '".intercalate (forbidden.map (·.toString))}' \ is only intended for development and not for final code. \ If you intend to submit this contribution to the Mathlib project, \ please remove 'set_option {name}'." else if name.components.contains `maxHeartbeats then Linter.logLint linter.style.setOption head m!"Unscoped option {name} is not allowed:\n\ Please scope this to individual declarations, as in\n```\nset_option {name} in\n\ -- comment explaining why this is necessary\n\ example : ... := ...\n```" initialize addLinter setOptionLinter end Style.setOption /-! # The "missing end" linter The "missing end" linter emits a warning on non-closed `section`s and `namespace`s. It allows the "outermost" `noncomputable section` to be left open (whether or not it is named). -/ open Lean Elab Command /-- The "missing end" linter emits a warning on non-closed `section`s and `namespace`s. It allows the "outermost" `noncomputable section` to be left open (whether or not it is named). -/ register_option linter.style.missingEnd : Bool := { defValue := false descr := "enable the missing end linter" } namespace Style.missingEnd @[inherit_doc Mathlib.Linter.linter.style.missingEnd] def missingEndLinter : Linter where run := withSetOptionIn fun stx ↦ do -- Only run this linter at the end of a module. unless stx.isOfKind ``Lean.Parser.Command.eoi do return if getLinterValue linter.style.missingEnd (← getLinterOptions) && !(← MonadState.get).messages.hasErrors then let sc ← getScopes -- The last scope is always the "base scope", corresponding to no active `section`s or -- `namespace`s. We are interested in any *other* unclosed scopes. if sc.length == 1 then return let ends := sc.dropLast.map fun s ↦ (s.header, s.isNoncomputable) -- If the outermost scope corresponds to a `noncomputable section`, we ignore it. let ends := if ends.getLast!.2 then ends.dropLast else ends -- If there are any further un-closed scopes, we emit a warning. if !ends.isEmpty then let ending := (ends.map Prod.fst).foldl (init := "") fun a b ↦ a ++ s!"\n\nend{if b == "" then "" else " "}{b}" Linter.logLint linter.style.missingEnd stx m!"unclosed sections or namespaces; expected: '{ending}'" initialize addLinter missingEndLinter end Style.missingEnd /-! # The `cdot` linter The `cdot` linter is a syntax-linter that flags uses of the "cdot" `·` that are achieved by typing a character different from `·`. For instance, a "plain" dot `.` is allowed syntax, but is flagged by the linter. It also flags "isolated cdots", i.e. when the `·` is on its own line. -/ /-- The `cdot` linter flags uses of the "cdot" `·` that are achieved by typing a character different from `·`. For instance, a "plain" dot `.` is allowed syntax, but is flagged by the linter. It also flags "isolated cdots", i.e. when the `·` is on its own line. -/ register_option linter.style.cdot : Bool := { defValue := false descr := "enable the `cdot` linter" } /-- `isCDot? stx` checks whether `stx` is a `Syntax` node corresponding to a `cdot` typed with the character `·`. -/ def isCDot? : Syntax → Bool | .node _ ``cdotTk #[.node _ `patternIgnore #[.node _ _ #[.atom _ v]]] => v == "·" | .node _ ``Lean.Parser.Term.cdot #[.atom _ v, _] => v == "·" | _ => false /-- `findCDot stx` extracts from `stx` the syntax nodes of `kind` `Lean.Parser.Term.cdot` or `cdotTk`. -/ partial def findCDot : Syntax → Array Syntax | stx@(.node _ kind args) => let dargs := (args.map findCDot).flatten match kind with | ``Lean.Parser.Term.cdot | ``cdotTk => dargs.push stx | _ => dargs |_ => #[] /-- `unwanted_cdot stx` returns an array of syntax atoms within `stx` corresponding to `cdot`s that are not written with the character `·`. This is precisely what the `cdot` linter flags. -/ def unwanted_cdot (stx : Syntax) : Array Syntax := (findCDot stx).filter (!isCDot? ·) namespace Style @[inherit_doc linter.style.cdot] def cdotLinter : Linter where run := withSetOptionIn fun stx ↦ do unless getLinterValue linter.style.cdot (← getLinterOptions) do return if (← MonadState.get).messages.hasErrors then return for s in unwanted_cdot stx do Linter.logLint linter.style.cdot s m!"Please, use '·' (typed as `\\.`) instead of '{s}' as 'cdot'." -- We also check for isolated cdot's, i.e. when the cdot is on its own line. for cdot in Mathlib.Linter.findCDot stx do match cdot.find? (·.isOfKind `token.«· ») with | some (.node _ _ #[.atom (.original _ _ afterCDot _) _]) => if (afterCDot.takeWhile (·.isWhitespace)).contains '\n' then Linter.logLint linter.style.cdot cdot m!"This central dot `·` is isolated; please merge it with the next line." | _ => return initialize addLinter cdotLinter end Style /-! # The `dollarSyntax` linter The `dollarSyntax` linter flags uses of `<|` that are achieved by typing `$`. These are disallowed by the mathlib style guide, as using `<|` pairs better with `|>`. -/ /-- The `dollarSyntax` linter flags uses of `<|` that are achieved by typing `$`. These are disallowed by the mathlib style guide, as using `<|` pairs better with `|>`. -/ register_option linter.style.dollarSyntax : Bool := { defValue := false descr := "enable the `dollarSyntax` linter" } namespace Style.dollarSyntax /-- `findDollarSyntax stx` extracts from `stx` the syntax nodes of `kind` `$`. -/ partial def findDollarSyntax : Syntax → Array Syntax | stx@(.node _ kind args) => let dargs := (args.map findDollarSyntax).flatten match kind with | ``«term_$__» => dargs.push stx | _ => dargs |_ => #[] @[inherit_doc linter.style.dollarSyntax] def dollarSyntaxLinter : Linter where run := withSetOptionIn fun stx ↦ do unless getLinterValue linter.style.dollarSyntax (← getLinterOptions) do return if (← MonadState.get).messages.hasErrors then return for s in findDollarSyntax stx do Linter.logLint linter.style.dollarSyntax s m!"Please use '<|' instead of '$' for the pipe operator." initialize addLinter dollarSyntaxLinter end Style.dollarSyntax /-! # The `lambdaSyntax` linter The `lambdaSyntax` linter is a syntax linter that flags uses of the symbol `λ` to define anonymous functions, as opposed to the `fun` keyword. These are syntactically equivalent; mathlib style prefers the latter as it is considered more readable. -/ /-- The `lambdaSyntax` linter flags uses of the symbol `λ` to define anonymous functions. This is syntactically equivalent to the `fun` keyword; mathlib style prefers using the latter. -/ register_option linter.style.lambdaSyntax : Bool := { defValue := false descr := "enable the `lambdaSyntax` linter" } namespace Style.lambdaSyntax /-- `findLambdaSyntax stx` extracts from `stx` all syntax nodes of `kind` `Term.fun`. -/ partial def findLambdaSyntax : Syntax → Array Syntax | stx@(.node _ kind args) => let dargs := (args.map findLambdaSyntax).flatten match kind with | ``Parser.Term.fun => dargs.push stx | _ => dargs |_ => #[] @[inherit_doc linter.style.lambdaSyntax] def lambdaSyntaxLinter : Linter where run := withSetOptionIn fun stx ↦ do unless getLinterValue linter.style.lambdaSyntax (← getLinterOptions) do return if (← MonadState.get).messages.hasErrors then return for s in findLambdaSyntax stx do if let .atom _ "λ" := s[0] then Linter.logLint linter.style.lambdaSyntax s[0] m!"\ Please use 'fun' and not 'λ' to define anonymous functions.\n\ The 'λ' syntax is deprecated in mathlib4." initialize addLinter lambdaSyntaxLinter end Style.lambdaSyntax /-! # The "longFile" linter The "longFile" linter emits a warning on files which are longer than a certain number of lines (1500 by default). -/ /-- The "longFile" linter emits a warning on files which are longer than a certain number of lines (`linter.style.longFileDefValue` by default on mathlib, no limit for downstream projects). If this option is set to `N` lines, the linter warns once a file has more than `N` lines. A value of `0` silences the linter entirely. -/ register_option linter.style.longFile : Nat := { defValue := 0 descr := "enable the longFile linter" } /-- The number of lines that the `longFile` linter considers the default. -/ register_option linter.style.longFileDefValue : Nat := { defValue := 1500 descr := "a soft upper bound on the number of lines of each file" } namespace Style.longFile @[inherit_doc Mathlib.Linter.linter.style.longFile] def longFileLinter : Linter where run := withSetOptionIn fun stx ↦ do let linterBound := linter.style.longFile.get (← getOptions) if linterBound == 0 then return let defValue := linter.style.longFileDefValue.get (← getOptions) let smallOption := match stx with | `(set_option linter.style.longFile $x) => TSyntax.getNat ⟨x.raw⟩ ≤ defValue | _ => false if smallOption then logLint0Disable linter.style.longFile stx m!"The default value of the `longFile` linter is {defValue}.\n\ The current value of {linterBound} does not exceed the allowed bound.\n\ Please, remove the `set_option linter.style.longFile {linterBound}`." else -- Thanks to the above check, the linter option is either not set (and hence equal -- to the default) or set to some value *larger* than the default. -- `Parser.isTerminalCommand` allows `stx` to be `#exit`: this is useful for tests. unless Parser.isTerminalCommand stx do return -- We exclude `Mathlib.lean` from the linter: it exceeds linter's default number of allowed -- lines, and it is an auto-generated import-only file. -- TODO: if there are more such files, revise the implementation. if (← getMainModule) == `Mathlib then return if let some init := stx.getTailPos? then -- the last line: we subtract 1, since the last line is expected to be empty let lastLine := ((← getFileMap).toPosition init).line -- In this case, the file has an allowed length, and the linter option is unnecessarily set. if lastLine ≤ defValue && defValue < linterBound then logLint0Disable linter.style.longFile stx m!"The default value of the `longFile` linter is {defValue}.\n\ This file is {lastLine} lines long which does not exceed the allowed bound.\n\ Please, remove the `set_option linter.style.longFile {linterBound}`." else -- `candidate` is divisible by `100` and satisfies `lastLine + 100 < candidate ≤ lastLine + 200` -- note that either `lastLine ≤ defValue` and `defValue = linterBound` hold or -- `candidate` is necessarily bigger than `lastLine` and hence bigger than `defValue` let candidate := (lastLine / 100) * 100 + 200 let candidate := max candidate defValue -- In this case, the file is longer than the default and also than what the option says. if defValue ≤ linterBound && linterBound < lastLine then logLint0Disable linter.style.longFile stx m!"This file is {lastLine} lines long, but the limit is {linterBound}.\n\n\ You can extend the allowed length of the file using \ `set_option linter.style.longFile {candidate}`.\n\ You can completely disable this linter by setting the length limit to `0`." else -- Finally, the file exceeds the default value, but not the option: we only allow the value -- of the option to be `candidate` or `candidate + 100`. -- In particular, this flags any option that is set to an unnecessarily high value. if linterBound == candidate || linterBound + 100 == candidate then return else logLint0Disable linter.style.longFile stx m!"This file is {lastLine} lines long. \ The current limit is {linterBound}, but it is expected to be {candidate}:\n\ `set_option linter.style.longFile {candidate}`." initialize addLinter longFileLinter end Style.longFile /-! # The "longLine linter" -/ /-- The "longLine" linter emits a warning on lines longer than 100 characters. We allow lines containing URLs to be longer, though. -/ register_option linter.style.longLine : Bool := { defValue := false descr := "enable the longLine linter" } namespace Style.longLine @[inherit_doc Mathlib.Linter.linter.style.longLine] def longLineLinter : Linter where run := withSetOptionIn fun stx ↦ do unless getLinterValue linter.style.longLine (← getLinterOptions) do return if (← MonadState.get).messages.hasErrors then return -- The linter ignores the `#guard_msgs` command, in particular its doc-string. -- The linter still lints the message guarded by `#guard_msgs`. if stx.isOfKind ``Lean.guardMsgsCmd then return -- if the linter reached the end of the file, then we scan the `import` syntax instead let stx := ← do if stx.isOfKind ``Lean.Parser.Command.eoi then let fileMap ← getFileMap -- `impMods` is the syntax for the modules imported in the current file let (impMods, _) ← Parser.parseHeader { input := fileMap.source, fileName := ← getFileName, fileMap := fileMap } return impMods.raw else return stx let sstr := stx.getSubstring? let fm ← getFileMap let longLines := ((sstr.getD default).splitOn "\n").filter fun line ↦ (100 < (fm.toPosition line.stopPos).column) for line in longLines do if (line.splitOn "http").length ≤ 1 then let stringMsg := if line.contains '"' then "\nYou can use \"string gaps\" to format long strings: within a string quotation, \ using a '\\' at the end of a line allows you to continue the string on the following \ line, removing all intervening whitespace." else "" Linter.logLint linter.style.longLine (.ofRange ⟨line.startPos, line.stopPos⟩) m!"This line exceeds the 100 character limit, please shorten it!{stringMsg}" initialize addLinter longLineLinter end Style.longLine /-- The `nameCheck` linter emits a warning on declarations whose name is non-standard style. (Currently, this only includes declarations whose name includes a double underscore.) **Why is this bad?** Double underscores in theorem names can be considered non-standard style and probably have been introduced by accident. **How to fix this?** Use single underscores to separate parts of a name, following standard naming conventions. -/ register_option linter.style.nameCheck : Bool := { defValue := true descr := "enable the `nameCheck` linter" } namespace Style.nameCheck @[inherit_doc linter.style.nameCheck] def doubleUnderscore : Linter where run := withSetOptionIn fun stx => do unless getLinterValue linter.style.nameCheck (← getLinterOptions) do return if (← get).messages.hasErrors then return let mut aliases := #[] if let some exp := stx.find? (·.isOfKind `Lean.Parser.Command.export) then aliases ← getAliasSyntax exp for id in aliases.push ((stx.find? (·.isOfKind ``declId)).getD default)[0] do let declName := id.getId if id.getPos? == some default then continue if declName.hasMacroScopes then continue if id.getKind == `ident then -- Check whether the declaration name contains "__". if 1 < (declName.toString.splitOn "__").length then Linter.logLint linter.style.nameCheck id m!"The declaration '{id}' contains '__', which does not follow the mathlib naming \ conventions. Consider using single underscores instead." initialize addLinter doubleUnderscore end Style.nameCheck /-! # The "openClassical" linter -/ /-- The "openClassical" linter emits a warning on `open Classical` statements which are not scoped to a single declaration. A non-scoped `open Classical` can hide that some theorem statements would be better stated with explicit decidability statements. -/ register_option linter.style.openClassical : Bool := { defValue := false descr := "enable the openClassical linter" } namespace Style.openClassical /-- If `stx` is syntax describing an `open` command, `extractOpenNames stx` returns an array of the syntax corresponding to the opened names, omitting any renamed or hidden items. This only checks independent `open` commands: for `open ... in ...` commands, this linter returns an empty array. -/ def extractOpenNames : Syntax → Array (TSyntax `ident) | `(command|$_ in $_) => #[] -- redundant, for clarity | `(command|open $decl:openDecl) => match decl with | `(openDecl| $arg hiding $_*) => #[arg] | `(openDecl| $arg renaming $_,*) => #[arg] | `(openDecl| $arg ($_*)) => #[arg] | `(openDecl| $args*) => args | `(openDecl| scoped $args*) => args | _ => unreachable! | _ => #[] @[inherit_doc Mathlib.Linter.linter.style.openClassical] def openClassicalLinter : Linter where run stx := do unless getLinterValue linter.style.openClassical (← getLinterOptions) do return if (← get).messages.hasErrors then return -- If `stx` describes an `open` command, extract the list of opened namespaces. for stxN in (extractOpenNames stx).filter (·.getId == `Classical) do Linter.logLint linter.style.openClassical stxN "\ please avoid 'open (scoped) Classical' statements: this can hide theorem statements \ which would be better stated with explicit decidability statements.\n\ Instead, use `open Classical in` for definitions or instances, the `classical` tactic \ for proofs.\nFor theorem statements, \ either add missing decidability assumptions or use `open Classical in`." initialize addLinter openClassicalLinter end Style.openClassical /-! # The "show" linter -/ /-- The "show" linter emits a warning if the `show` tactic changed the goal. `show` should only be used to indicate intermediate goal states for proof readability. When the goal is actually changed, `change` should be preferred. -/ register_option linter.style.show : Bool := { defValue := false descr := "enable the show linter" } namespace Style.show @[inherit_doc Mathlib.Linter.linter.style.show] def showLinter : Linter where run := withSetOptionIn fun stx => do unless getLinterValue linter.style.show (← getLinterOptions) do return if (← get).messages.hasErrors then return for tree in (← getInfoTrees) do tree.foldInfoM (init := ()) fun ci i _ => do let .ofTacticInfo tac := i | return unless tac.stx.isOfKind ``Lean.Parser.Tactic.show do return let some _ := tac.stx.getRange? true | return let (goal :: goals) := tac.goalsBefore | return let (goal' :: goals') := tac.goalsAfter | return if goals != goals' then return -- `show` didn't act on first goal -> can't replace with `change` if goal == goal' then return -- same goal, no need to check let diff ← ci.runCoreM do let before ← (do instantiateMVars (← goal.getType)).run' {} { mctx := tac.mctxBefore } let after ← (do instantiateMVars (← goal'.getType)).run' {} { mctx := tac.mctxAfter } return before != after if diff then logLint linter.style.show tac.stx m!"\ The `show` tactic should only be used to indicate intermediate goal states for \ readability.\nHowever, this tactic invocation changed the goal. Please use `change` \ instead for these purposes." initialize addLinter showLinter end Style.show end Mathlib.Linter
separable.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 div. From mathcomp Require Import choice fintype tuple finfun bigop finset prime. From mathcomp Require Import binomial ssralg poly polydiv fingroup perm. From mathcomp Require Import morphism quotient gproduct finalg zmodp cyclic. From mathcomp Require Import matrix mxalgebra mxpoly polyXY vector falgebra. From mathcomp Require Import fieldext. (******************************************************************************) (* This file provides a theory of separable and inseparable field extensions. *) (* *) (* separable_poly p <=> p has no multiple roots in any field extension. *) (* separable_element K x <=> the minimal polynomial of x over K is separable. *) (* separable K E <=> every member of E is separable over K. *) (* separable_generator K E == some x \in E that generates the largest *) (* subfield K[x] that is separable over K. *) (* purely_inseparable_element K x <=> there is a [pchar L].-nat n such that *) (* x ^+ n \in K. *) (* purely_inseparable K E <=> every member of E is purely inseparable over K. *) (* *) (* Derivations are introduced to prove the adjoin_separableP Lemma: *) (* Derivation K D <=> the linear operator D satisfies the Leibniz *) (* product rule inside K. *) (* extendDerivation x D K == given a derivation D on K and a separable *) (* element x over K, this function returns the *) (* unique extension of D to K(x). *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Local Open Scope ring_scope. Import GRing.Theory. HB.lock Definition separable_poly {R : idomainType} (p : {poly R}) := coprimep p p^`(). Canonical separable_poly_unlockable := Unlockable separable_poly.unlock. Section SeparablePoly. Variable R : idomainType. Implicit Types p q d u v : {poly R}. Local Notation separable := (@separable_poly R). Local Notation lcn_neq0 := (Pdiv.Idomain.lc_expn_scalp_neq0 _). Lemma separable_poly_neq0 p : separable p -> p != 0. Proof. by apply: contraTneq => ->; rewrite unlock deriv0 coprime0p eqp01. Qed. Lemma poly_square_freeP p : (forall u v, u * v %| p -> coprimep u v) <-> (forall u, size u != 1 -> ~~ (u ^+ 2 %| p)). Proof. split=> [sq'p u | sq'p u v dvd_uv_p]. by apply: contra => /sq'p; rewrite coprimepp. rewrite coprimep_def (contraLR (sq'p _)) // (dvdp_trans _ dvd_uv_p) //. by rewrite dvdp_mul ?dvdp_gcdl ?dvdp_gcdr. Qed. Lemma separable_polyP {p} : reflect [/\ forall u v, u * v %| p -> coprimep u v & forall u, u %| p -> 1 < size u -> u^`() != 0] (separable p). Proof. apply: (iffP idP) => [sep_p | [sq'p nz_der1p]]. split=> [u v | u u_dv_p]; last first. apply: contraTneq => u'0; rewrite unlock in sep_p; rewrite -leqNgt -(eqnP sep_p). rewrite dvdp_leq -?size_poly_eq0 ?(eqnP sep_p) // dvdp_gcd u_dv_p. have /dvdpZr <-: lead_coef u ^+ scalp p u != 0 by rewrite lcn_neq0. by rewrite -derivZ -Pdiv.Idomain.divpK //= derivM u'0 mulr0 addr0 dvdp_mull. rewrite Pdiv.Idomain.dvdp_eq mulrCA mulrA; set c := _ ^+ _ => /eqP Dcp. have nz_c: c != 0 by rewrite lcn_neq0. move: sep_p; rewrite coprimep_sym unlock -(coprimepZl _ _ nz_c). rewrite -(coprimepZr _ _ nz_c) -derivZ Dcp derivM coprimepMl. by rewrite coprimep_addl_mul !coprimepMr -andbA => /and4P[]. rewrite unlock coprimep_def eqn_leq size_poly_gt0; set g := gcdp _ _. have nz_g: g != 0. rewrite -dvd0p dvdp_gcd -(mulr0 0); apply/nandP; left. by have /poly_square_freeP-> := sq'p; rewrite ?size_poly0. have [g_p]: g %| p /\ g %| p^`() by rewrite dvdp_gcdr ?dvdp_gcdl. pose c := lead_coef g ^+ scalp p g; have nz_c: c != 0 by rewrite lcn_neq0. have Dcp: c *: p = p %/ g * g by rewrite Pdiv.Idomain.divpK. rewrite nz_g andbT leqNgt -(dvdpZr _ _ nz_c) -derivZ Dcp derivM. rewrite dvdp_addr; last by rewrite dvdp_mull. rewrite Gauss_dvdpr; last by rewrite sq'p // mulrC -Dcp dvdpZl. by apply: contraL => /nz_der1p nz_g'; rewrite gtNdvdp ?nz_g' ?lt_size_deriv. Qed. Lemma separable_coprime p u v : separable p -> u * v %| p -> coprimep u v. Proof. by move=> /separable_polyP[sq'p _] /sq'p. Qed. Lemma separable_nosquare p u k : separable p -> 1 < k -> size u != 1 -> (u ^+ k %| p) = false. Proof. move=> /separable_polyP[/poly_square_freeP sq'p _] /subnKC <- /sq'p. by apply: contraNF; apply: dvdp_trans; rewrite exprD dvdp_mulr. Qed. Lemma separable_deriv_eq0 p u : separable p -> u %| p -> 1 < size u -> (u^`() == 0) = false. Proof. by move=> /separable_polyP[_ nz_der1p] u_p /nz_der1p/negPf->. Qed. Lemma dvdp_separable p q : q %| p -> separable p -> separable q. Proof. move=> /(dvdp_trans _)q_dv_p /separable_polyP[sq'p nz_der1p]. by apply/separable_polyP; split=> [u v /q_dv_p/sq'p | u /q_dv_p/nz_der1p]. Qed. Lemma separable_mul p q : separable (p * q) = [&& separable p, separable q & coprimep p q]. Proof. apply/idP/and3P => [sep_pq | [sep_p sep_q co_pq]]. rewrite !(dvdp_separable _ sep_pq) ?dvdp_mulIr ?dvdp_mulIl //. by rewrite (separable_coprime sep_pq). rewrite unlock in sep_p sep_q *. rewrite derivM coprimepMl {1}addrC mulrC !coprimep_addl_mul. by rewrite !coprimepMr (coprimep_sym q p) co_pq !andbT; apply/andP. Qed. Lemma eqp_separable p q : p %= q -> separable p = separable q. Proof. by case/andP=> p_q q_p; apply/idP/idP=> /dvdp_separable->. Qed. Lemma separable_root p x : separable (p * ('X - x%:P)) = separable p && ~~ root p x. Proof. rewrite separable_mul; apply: andb_id2l => seq_p. by rewrite unlock derivXsubC coprimep1 coprimep_XsubC. Qed. Lemma separable_prod_XsubC (r : seq R) : separable (\prod_(x <- r) ('X - x%:P)) = uniq r. Proof. elim: r => [|x r IH]; first by rewrite big_nil unlock /separable_poly coprime1p. by rewrite big_cons mulrC separable_root IH root_prod_XsubC andbC. Qed. Lemma make_separable p : p != 0 -> separable (p %/ gcdp p p^`()). Proof. set g := gcdp p p^`() => nz_p; apply/separable_polyP. have max_dvd_u (u : {poly R}): 1 < size u -> exists k, ~~ (u ^+ k %| p). move=> u_gt1; exists (size p); rewrite gtNdvdp // polySpred //. by rewrite -(ltn_subRL 1) subn1 size_exp leq_pmull // -(subnKC u_gt1). split=> [|u u_pg u_gt1]; last first. apply/eqP=> u'0 /=; have [k /negP[]] := max_dvd_u u u_gt1. elim: k => [|k IHk]; first by rewrite dvd1p. suffices: u ^+ k.+1 %| (p %/ g) * g. by rewrite Pdiv.Idomain.divpK ?dvdp_gcdl // dvdpZr ?lcn_neq0. rewrite exprS dvdp_mul // dvdp_gcd IHk //=. suffices: u ^+ k %| (p %/ u ^+ k * u ^+ k)^`(). by rewrite Pdiv.Idomain.divpK // derivZ dvdpZr ?lcn_neq0. by rewrite !derivCE u'0 mul0r mul0rn mulr0 addr0 dvdp_mull. have pg_dv_p: p %/ g %| p by rewrite divp_dvd ?dvdp_gcdl. apply/poly_square_freeP=> u; rewrite neq_ltn ltnS leqn0 size_poly_eq0. case/predU1P=> [-> | /max_dvd_u[k]]. by apply: contra nz_p; rewrite expr0n -dvd0p => /dvdp_trans->. apply: contra => u2_dv_pg; case: k; [by rewrite dvd1p | elim=> [|n IHn]]. exact: dvdp_trans (dvdp_mulr _ _) (dvdp_trans u2_dv_pg pg_dv_p). suff: u ^+ n.+2 %| (p %/ g) * g. by rewrite Pdiv.Idomain.divpK ?dvdp_gcdl // dvdpZr ?lcn_neq0. rewrite -add2n exprD dvdp_mul // dvdp_gcd. rewrite (dvdp_trans _ IHn) ?exprS ?dvdp_mull //=. suff: u ^+ n %| ((p %/ u ^+ n.+1) * u ^+ n.+1)^`(). by rewrite Pdiv.Idomain.divpK // derivZ dvdpZr ?lcn_neq0. by rewrite !derivCE dvdp_add // -1?mulr_natl ?exprS !dvdp_mull. Qed. End SeparablePoly. Arguments separable_polyP {R p}. Lemma separable_map (F : fieldType) (R : idomainType) (f : {rmorphism F -> R}) (p : {poly F}) : separable_poly (map_poly f p) = separable_poly p. Proof. by rewrite unlock deriv_map /coprimep -gcdp_map size_map_poly. Qed. Section InfinitePrimitiveElementTheorem. Local Notation "p ^ f" := (map_poly f p) : ring_scope. Variables (F L : fieldType) (iota : {rmorphism F -> L}). Variables (x y : L) (p : {poly F}). Hypotheses (nz_p : p != 0) (px_0 : root (p ^ iota) x). Let inFz z w := exists q, (q ^ iota).[z] = w. Lemma large_field_PET q : root (q ^ iota) y -> separable_poly q -> exists2 r, r != 0 & forall t (z := iota t * y - x), ~~ root r (iota t) -> inFz z x /\ inFz z y. Proof. move=> qy_0 sep_q; have nz_q := separable_poly_neq0 sep_q. have /factor_theorem[q0 Dq] := qy_0. set p1 := p ^ iota \Po ('X + x%:P); set q1 := q0 \Po ('X + y%:P). have nz_p1: p1 != 0. apply: contraNneq nz_p => /(canRL (fun r => comp_polyXaddC_K r _))/eqP. by rewrite comp_poly0 map_poly_eq0. have{sep_q} nz_q10: q1.[0] != 0. move: sep_q; rewrite -(separable_map iota) Dq separable_root => /andP[_]. by rewrite horner_comp !hornerE. have nz_q1: q1 != 0 by apply: contraNneq nz_q10 => ->; rewrite horner0. pose p2 := p1 ^ polyC \Po ('X * 'Y); pose q2 := q1 ^ polyC. have /Bezout_coprimepP[[u v]]: coprimep p2 q2. rewrite coprimep_def eqn_leq leqNgt andbC size_poly_gt0 gcdp_eq0 poly_XmY_eq0. by rewrite map_polyC_eq0 (negPf nz_p1) -resultant_eq0 div_annihilant_neq0. rewrite -size_poly_eq1 => /size_poly1P[r nzr Dr]; exists r => {nzr}// t z nz_rt. have [r1 nz_r1 r1z_0]: algebraicOver iota z. apply/algebraic_sub; last by exists p. by apply: algebraic_mul; [apply: algebraic_id | exists q]. pose Fz := subFExtend iota z r1; pose kappa : Fz -> L := subfx_inj. pose kappa' := inj_subfx iota z r1. have /eq_map_poly Diota: kappa \o kappa' =1 iota. by move=> w; rewrite /kappa /= subfx_inj_eval // map_polyC hornerC. suffices [y3]: exists y3, y = kappa y3. have [q3 ->] := subfxE y3; rewrite /kappa subfx_inj_eval // => Dy. split; [exists (t *: q3 - 'X) | by exists q3]. by rewrite rmorphB /= linearZ map_polyX !hornerE -Dy opprB addrC addrNK. pose p0 := p ^ iota \Po (iota t *: 'X - z%:P). have co_p0_q0: coprimep p0 q0. pose at_t := horner_eval (iota t); have at_t0: at_t 0 = 0 by apply: rmorph0. have /map_polyK polyCK: cancel polyC at_t by move=> w; apply: hornerC. have ->: p0 = p2 ^ at_t \Po ('X - y%:P). rewrite map_comp_poly polyCK // rmorphM /= map_polyC map_polyX /=. rewrite horner_evalE hornerX. rewrite -!comp_polyA comp_polyM comp_polyD !comp_polyC !comp_polyX. by rewrite mulrC mulrBr mul_polyC addrAC -addrA -opprB -rmorphM -rmorphB. have ->: q0 = q2 ^ at_t \Po ('X - y%:P) by rewrite polyCK ?comp_polyXaddC_K. apply/coprimep_comp_poly/Bezout_coprimepP; exists (u ^ at_t, v ^ at_t). by rewrite /= -!rmorphM -rmorphD Dr /= map_polyC polyC_eqp1. have{co_p0_q0}: gcdp p0 (q ^ iota) %= 'X - y%:P. rewrite /eqp Dq (eqp_dvdl _ (Gauss_gcdpr _ _)) // dvdp_gcdr dvdp_gcd. rewrite dvdp_mull // -root_factor_theorem rootE horner_comp !hornerE. by rewrite opprB addrC subrK. have{p0} [p3 ->]: exists p3, p0 = p3 ^ kappa. exists (p ^ kappa' \Po (kappa' t *: 'X - (subfx_eval iota z r1 'X)%:P)). rewrite map_comp_poly rmorphB /= linearZ /= map_polyC map_polyX /=. rewrite !subfx_inj_eval // map_polyC hornerC map_polyX hornerX. by rewrite -map_poly_comp Diota. rewrite -Diota map_poly_comp -gcdp_map /= -/kappa. move: (gcdp _ _) => r3 /eqpf_eq[c nz_c Dr3]. exists (- (r3`_0 / r3`_1)); rewrite [kappa _]rmorphN fmorph_div -!coef_map Dr3. by rewrite !coefZ polyseqXsubC mulr1 mulrC mulKf ?opprK. Qed. Lemma pchar0_PET (q : {poly F}) : q != 0 -> root (q ^ iota) y -> [pchar F] =i pred0 -> exists n, let z := y *+ n - x in inFz z x /\ inFz z y. Proof. move=> nz_q qy_0 /pcharf0P pcharF0. without loss{nz_q} sep_q: q qy_0 / separable_poly q. move=> IHq; apply: IHq (make_separable nz_q). have /dvdpP[q1 Dq] := dvdp_gcdl q q^`(). rewrite {1}Dq mulpK ?gcdp_eq0; last by apply/nandP; left. have [n [r nz_ry Dr]] := multiplicity_XsubC (q ^ iota) y. rewrite map_poly_eq0 nz_q /= in nz_ry. case: n => [|n] in Dr; first by rewrite Dr mulr1 (negPf nz_ry) in qy_0. have: ('X - y%:P) ^+ n.+1 %| q ^ iota by rewrite Dr dvdp_mulIr. rewrite Dq rmorphM /= gcdp_map -(eqp_dvdr _ (gcdp_mul2l _ _ _)) -deriv_map Dr. rewrite dvdp_gcd derivM deriv_exp derivXsubC mul1r !mulrA dvdp_mulIr /=. rewrite mulrDr mulrA dvdp_addr ?dvdp_mulIr // exprS -scaler_nat -!scalerAr. rewrite dvdpZr -?(rmorph_nat iota) ?fmorph_eq0 ?pcharF0 //. rewrite mulrA dvdp_mul2r ?expf_neq0 ?polyXsubC_eq0 //. by rewrite Gauss_dvdpl ?dvdp_XsubCl // coprimep_sym coprimep_XsubC. have [r nz_r PETxy] := large_field_PET qy_0 sep_q. pose ts := mkseq (fun n => iota n%:R) (size r). have /(max_ring_poly_roots nz_r)/=/implyP: uniq_roots ts. rewrite uniq_rootsE mkseq_uniq // => m n eq_mn; apply/eqP; rewrite eqn_leq. wlog suffices: m n eq_mn / m <= n by move=> IHmn; rewrite !IHmn. move/fmorph_inj/eqP: eq_mn; rewrite -subr_eq0 leqNgt; apply: contraL => lt_mn. by rewrite -natrB ?(ltnW lt_mn) // pcharF0 -lt0n subn_gt0. rewrite size_mkseq ltnn implybF all_map => /allPn[n _ /= /PETxy]. by rewrite rmorph_nat mulr_natl; exists n. Qed. End InfinitePrimitiveElementTheorem. #[deprecated(since="mathcomp 2.4.0", note="Use pchar0_PET instead.")] Notation char0_PET := (pchar0_PET) (only parsing). Section Separable. Variables (F : fieldType) (L : fieldExtType F). Implicit Types (U V W : {vspace L}) (E K M : {subfield L}) (D : 'End(L)). Section Derivation. Variables (K : {vspace L}) (D : 'End(L)). (* A deriviation only needs to be additive and satisfy Lebniz's law, but all *) (* the deriviations used here are going to be linear, so we only define *) (* the Derivation predicate for linear endomorphisms. *) Definition Derivation : bool := all2rel (fun u v => D (u * v) == D u * v + u * D v) (vbasis K). Hypothesis derD : Derivation. Lemma Derivation_mul : {in K &, forall u v, D (u * v) = D u * v + u * D v}. Proof. move=> u v /coord_vbasis-> /coord_vbasis->. rewrite !(mulr_sumr, linear_sum) -big_split; apply: eq_bigr => /= j _. rewrite !mulr_suml linear_sum -big_split; apply: eq_bigr => /= i _. rewrite !(=^~ scalerAl, linearZZ) -!scalerAr linearZZ -!scalerDr !scalerA /=. by congr (_ *: _); apply/eqP/(allrelP derD); exact: memt_nth. Qed. Lemma Derivation_mul_poly (Dp := map_poly D) : {in polyOver K &, forall p q, Dp (p * q) = Dp p * q + p * Dp q}. Proof. move=> p q Kp Kq; apply/polyP=> i; rewrite {}/Dp coefD coef_map /= !coefM. rewrite linear_sum -big_split; apply: eq_bigr => /= j _. by rewrite !{1}coef_map Derivation_mul ?(polyOverP _). Qed. End Derivation. Lemma DerivationS E K D : (K <= E)%VS -> Derivation E D -> Derivation K D. Proof. move/subvP=> sKE derD; apply/allrelP=> x y Kx Ky; apply/eqP. by rewrite (Derivation_mul derD) ?sKE // vbasis_mem. Qed. Section DerivationAlgebra. Variables (E : {subfield L}) (D : 'End(L)). Hypothesis derD : Derivation E D. Lemma Derivation1 : D 1 = 0. Proof. apply: (addIr (D (1 * 1))); rewrite add0r {1}mul1r. by rewrite (Derivation_mul derD) ?mem1v // mulr1 mul1r. Qed. Lemma Derivation_scalar x : x \in 1%VS -> D x = 0. Proof. by case/vlineP=> y ->; rewrite linearZ /= Derivation1 scaler0. Qed. Lemma Derivation_exp x m : x \in E -> D (x ^+ m) = x ^+ m.-1 *+ m * D x. Proof. move=> Ex; case: m; first by rewrite expr0 mulr0n mul0r Derivation1. elim=> [|m IHm]; first by rewrite mul1r. rewrite exprS (Derivation_mul derD) //; last by apply: rpredX. by rewrite mulrC IHm mulrA mulrnAr -exprS -mulrDl. Qed. Lemma Derivation_horner p x : p \is a polyOver E -> x \in E -> D p.[x] = (map_poly D p).[x] + p^`().[x] * D x. Proof. move=> Ep Ex; elim/poly_ind: p Ep => [|p c IHp] /polyOverP EpXc. by rewrite !(raddf0, horner0) mul0r add0r. have Ep: p \is a polyOver E. by apply/polyOverP=> i; have:= EpXc i.+1; rewrite coefD coefMX coefC addr0. have->: map_poly D (p * 'X + c%:P) = map_poly D p * 'X + (D c)%:P. apply/polyP=> i; rewrite !(coefD, coefMX, coef_map) /= linearD /= !coefC. by rewrite !(fun_if D) linear0. rewrite derivMXaddC !hornerE mulrDl mulrAC addrAC linearD /=; congr (_ + _). by rewrite addrCA -mulrDl -IHp // addrC (Derivation_mul derD) ?rpred_horner. Qed. End DerivationAlgebra. Definition separable_element U x := separable_poly (minPoly U x). Section SeparableElement. Variables (K : {subfield L}) (x : L). (* begin hide *) Let sKxK : (K <= <<K; x>>)%VS := subv_adjoin K x. Let Kx_x : x \in <<K; x>>%VS := memv_adjoin K x. (* end hide *) Lemma separable_elementP : reflect (exists f, [/\ f \is a polyOver K, root f x & separable_poly f]) (separable_element K x). Proof. apply: (iffP idP) => [sep_x | [f [Kf /(minPoly_dvdp Kf)/dvdpP[g ->]]]]. by exists (minPoly K x); rewrite minPolyOver root_minPoly. by rewrite separable_mul => /and3P[]. Qed. Lemma base_separable : x \in K -> separable_element K x. Proof. move=> Kx; apply/separable_elementP; exists ('X - x%:P). by rewrite polyOverXsubC root_XsubC unlock !derivCE coprimep1. Qed. Lemma separable_nz_der : separable_element K x = ((minPoly K x)^`() != 0). Proof. rewrite /separable_element unlock. apply/idP/idP=> [|nzPx']. by apply: contraTneq => ->; rewrite coprimep0 -size_poly_eq1 size_minPoly. have gcdK : gcdp (minPoly K x) (minPoly K x)^`() \in polyOver K. by rewrite gcdp_polyOver ?polyOver_deriv // minPolyOver. rewrite -gcdp_eqp1 -size_poly_eq1 -dvdp1. have /orP[/andP[_]|/andP[]//] := minPoly_irr gcdK (dvdp_gcdl _ _). rewrite dvdp_gcd dvdpp /= => /(dvdp_leq nzPx')/leq_trans/(_ (size_poly _ _)). by rewrite size_minPoly ltnn. Qed. Lemma separablePn_pchar : reflect (exists2 p, p \in [pchar L] & exists2 g, g \is a polyOver K & minPoly K x = g \Po 'X^p) (~~ separable_element K x). Proof. rewrite separable_nz_der negbK; set f := minPoly K x. apply: (iffP eqP) => [f'0 | [p Hp [g _ ->]]]; last first. by rewrite deriv_comp derivXn -scaler_nat (pcharf0 Hp) scale0r mulr0. pose n := adjoin_degree K x; have sz_f: size f = n.+1 := size_minPoly K x. have fn1: f`_n = 1 by rewrite -(monicP (monic_minPoly K x)) lead_coefE sz_f. have dimKx: (adjoin_degree K x)%:R == 0 :> L. by rewrite -(coef0 _ n.-1) -f'0 coef_deriv fn1. have /natf0_pchar[// | p pcharLp] := dimKx. have /dvdnP[r Dn]: (p %| n)%N by rewrite (dvdn_pcharf pcharLp). exists p => //; exists (\poly_(i < r.+1) f`_(i * p)). by apply: polyOver_poly => i _; rewrite (polyOverP _) ?minPolyOver. rewrite comp_polyE size_poly_eq -?Dn ?fn1 ?oner_eq0 //. have pr_p := pcharf_prime pcharLp; have p_gt0 := prime_gt0 pr_p. apply/polyP=> i; rewrite coef_sum. have [[{}i ->] | p'i] := altP (@dvdnP p i); last first. rewrite big1 => [|j _]; last first. rewrite coefZ -exprM coefXn [_ == _](contraNF _ p'i) ?mulr0 // => /eqP->. by rewrite dvdn_mulr. rewrite (dvdn_pcharf pcharLp) in p'i; apply: mulfI p'i _ _ _. by rewrite mulr0 mulr_natl; case: i => // i; rewrite -coef_deriv f'0 coef0. have [ltri | leir] := leqP r.+1 i. rewrite nth_default ?sz_f ?Dn ?ltn_pmul2r ?big1 // => j _. rewrite coefZ -exprM coefXn mulnC gtn_eqF ?mulr0 //. by rewrite ltn_pmul2l ?(leq_trans _ ltri). rewrite (bigD1 (Sub i _)) //= big1 ?addr0 => [|j i'j]; last first. by rewrite coefZ -exprM coefXn mulnC eqn_pmul2l // mulr_natr mulrb ifN_eqC. by rewrite coef_poly leir coefZ -exprM coefXn mulnC eqxx mulr1. Qed. Lemma separable_root_der : separable_element K x (+) root (minPoly K x)^`() x. Proof. have KpKx': _^`() \is a polyOver K := polyOver_deriv (minPolyOver K x). rewrite separable_nz_der addNb (root_small_adjoin_poly KpKx') ?addbb //. by rewrite (leq_trans (size_poly _ _)) ?size_minPoly. Qed. Lemma Derivation_separable D : Derivation <<K; x>> D -> separable_element K x -> D x = - (map_poly D (minPoly K x)).[x] / (minPoly K x)^`().[x]. Proof. move=> derD sepKx; have:= separable_root_der; rewrite {}sepKx -sub0r => nzKx'x. apply: canRL (mulfK nzKx'x) (canRL (addrK _) _); rewrite mulrC addrC. rewrite -(Derivation_horner derD) ?minPolyxx ?linear0 //. exact: polyOverSv sKxK _ (minPolyOver _ _). Qed. Section ExtendDerivation. Variable D : 'End(L). Let Dx E := - (map_poly D (minPoly E x)).[x] / ((minPoly E x)^`()).[x]. Fact extendDerivation_zmod_morphism_subproof E (adjEx := Fadjoin_poly E x) : let body y (p := adjEx y) := (map_poly D p).[x] + p^`().[x] * Dx E in zmod_morphism body. Proof. move: Dx => C /= u v; rewrite /adjEx. rewrite raddfB /= derivB -/adjEx !hornerE /= raddfB /= !hornerE. by rewrite mulrBl addrACA opprD. Qed. Fact extendDerivation_scalable_subproof E (adjEx := Fadjoin_poly E x) : let body y (p := adjEx y) := (map_poly D p).[x] + p^`().[x] * Dx E in scalable body. Proof. move: Dx => C /= a u; rewrite /adjEx linearZ /= derivZ -/adjEx. rewrite hornerE -[RHS]mulr_algl mulrDr mulrA -[in RHS]hornerZ. congr (_.[x] + _); apply/polyP=> i. by rewrite coefZ !coef_map coefZ !mulr_algl /= linearZ. Qed. Section DerivationLinear. Variable (E : {subfield L}). Let body (y : L) (p := Fadjoin_poly E x y) : L := (map_poly D p).[x] + p^`().[x] * Dx E. HB.instance Definition _ := @GRing.isZmodMorphism.Build _ _ body (extendDerivation_zmod_morphism_subproof E). HB.instance Definition _ := @GRing.isScalable.Build _ _ _ _ body (extendDerivation_scalable_subproof E). Let extendDerivationLinear := Eval hnf in (body : {linear _ -> _}). Definition extendDerivation : 'End(L) := linfun extendDerivationLinear. End DerivationLinear. Hypothesis derD : Derivation K D. Lemma extendDerivation_id y : y \in K -> extendDerivation K y = D y. Proof. move=> yK; rewrite lfunE /= Fadjoin_polyC // derivC map_polyC hornerC. by rewrite horner0 mul0r addr0. Qed. Lemma extendDerivation_horner p : p \is a polyOver K -> separable_element K x -> extendDerivation K p.[x] = (map_poly D p).[x] + p^`().[x] * Dx K. Proof. move=> Kp sepKx; have:= separable_root_der; rewrite {}sepKx /= => nz_pKx'x. rewrite [in RHS](divp_eq p (minPoly K x)) lfunE /= Fadjoin_poly_mod ?raddfD //=. rewrite (Derivation_mul_poly derD) ?divp_polyOver ?minPolyOver //. rewrite derivM !{1}hornerD !{1}hornerM minPolyxx !{1}mulr0 !{1}add0r. rewrite mulrDl addrA [_ + (_ * _ * _)]addrC {2}/Dx -mulrA -/Dx. by rewrite [_ / _]mulrC (mulVKf nz_pKx'x) mulrN addKr. Qed. Lemma extendDerivationP : separable_element K x -> Derivation <<K; x>> (extendDerivation K). Proof. move=> sep; apply/allrelP=> u v /vbasis_mem Hu /vbasis_mem Hv; apply/eqP. rewrite -(Fadjoin_poly_eq Hu) -(Fadjoin_poly_eq Hv) -hornerM. rewrite !{1}extendDerivation_horner ?{1}rpredM ?Fadjoin_polyOver //. rewrite (Derivation_mul_poly derD) ?Fadjoin_polyOver //. rewrite derivM !{1}hornerD !{1}hornerM !{1}mulrDl !{1}mulrDr -!addrA. congr (_ + _); rewrite [Dx K]lock -!{1}mulrA !{1}addrA; congr (_ + _). by rewrite addrC; congr (_ * _ + _); rewrite mulrC. Qed. End ExtendDerivation. (* Reference: http://www.math.uconn.edu/~kconrad/blurbs/galoistheory/separable2.pdf *) Lemma Derivation_separableP : reflect (forall D, Derivation <<K; x>> D -> K <= lker D -> <<K; x>> <= lker D)%VS (separable_element K x). Proof. apply: (iffP idP) => [sepKx D derD /subvP DK_0 | derKx_0]. have{} DK_0 q: q \is a polyOver K -> map_poly D q = 0. move=> /polyOverP Kq; apply/polyP=> i; apply/eqP. by rewrite coef0 coef_map -memv_ker DK_0. apply/subvP=> _ /Fadjoin_polyP[p Kp ->]; rewrite memv_ker. rewrite (Derivation_horner derD) ?(polyOverSv sKxK) //. rewrite (Derivation_separable derD sepKx) !DK_0 ?minPolyOver //. by rewrite horner0 oppr0 mul0r mulr0 addr0. apply: wlog_neg; rewrite {1}separable_nz_der negbK => /eqP pKx'_0. pose Df := fun y => (Fadjoin_poly K x y)^`().[x]. have Dlin: linear Df. move=> a u v; rewrite /Df linearP /= -mul_polyC derivD derivM derivC. by rewrite mul0r add0r hornerD hornerM hornerC -scalerAl mul1r. pose DlinM := GRing.isLinear.Build _ _ _ _ Df Dlin. pose DL : {linear _ -> _} := HB.pack Df DlinM. pose D := linfun DL; apply: base_separable. have DK_0: (K <= lker D)%VS. apply/subvP=> v Kv; rewrite memv_ker lfunE /= /Df Fadjoin_polyC //. by rewrite derivC horner0. have Dder: Derivation <<K; x>> D. apply/allrelP=> u v /vbasis_mem Kx_u /vbasis_mem Kx_v; apply/eqP. rewrite !lfunE /= /Df; set Px := Fadjoin_poly K x. set Px_u := Px u; rewrite -(Fadjoin_poly_eq Kx_u) -/Px -/Px_u. set Px_v := Px v; rewrite -(Fadjoin_poly_eq Kx_v) -/Px -/Px_v. rewrite -!hornerM -hornerD -derivM. rewrite /Px Fadjoin_poly_mod ?rpredM ?Fadjoin_polyOver //. rewrite [in RHS](divp_eq (Px_u * Px_v) (minPoly K x)) derivD derivM. by rewrite pKx'_0 mulr0 addr0 hornerD hornerM minPolyxx mulr0 add0r. have{Dder DK_0}: x \in lker D by apply: subvP Kx_x; apply: derKx_0. apply: contraLR => K'x; rewrite memv_ker lfunE /= /Df Fadjoin_polyX //. by rewrite derivX hornerC oner_eq0. Qed. End SeparableElement. #[deprecated(since="mathcomp 2.4.0", note="Use separablePn_pchar instead.")] Notation separablePn := (separablePn_pchar) (only parsing). Arguments separable_elementP {K x}. Lemma separable_elementS K E x : (K <= E)%VS -> separable_element K x -> separable_element E x. Proof. move=> sKE /separable_elementP[f [fK rootf sepf]]; apply/separable_elementP. by exists f; rewrite (polyOverSv sKE). Qed. Lemma adjoin_separableP {K x} : reflect (forall y, y \in <<K; x>>%VS -> separable_element K y) (separable_element K x). Proof. apply: (iffP idP) => [sepKx | -> //]; last exact: memv_adjoin. move=> _ /Fadjoin_polyP[q Kq ->]; apply/Derivation_separableP=> D derD DK_0. apply/subvP=> _ /Fadjoin_polyP[p Kp ->]. rewrite memv_ker -(extendDerivation_id x D (mempx_Fadjoin _ Kp)). have sepFyx: (separable_element <<K; q.[x]>> x). by apply: (separable_elementS (subv_adjoin _ _)). have KyxEqKx: (<< <<K; q.[x]>>; x>> = <<K; x>>)%VS. apply/eqP; rewrite eqEsubv andbC adjoinSl ?subv_adjoin //=. apply/FadjoinP/andP; rewrite memv_adjoin andbT. by apply/FadjoinP/andP; rewrite subv_adjoin mempx_Fadjoin. have /[!KyxEqKx] derDx := extendDerivationP derD sepFyx. rewrite -horner_comp (Derivation_horner derDx) ?memv_adjoin //; last first. by apply: (polyOverSv (subv_adjoin _ _)); apply: polyOver_comp. set Dx_p := map_poly _; have Dx_p_0 t: t \is a polyOver K -> (Dx_p t).[x] = 0. move/polyOverP=> Kt; congr (_.[x] = 0): (horner0 x); apply/esym/polyP => i. have /eqP Dti_0: D t`_i == 0 by rewrite -memv_ker (subvP DK_0) ?Kt. by rewrite coef0 coef_map /= {1}extendDerivation_id ?subvP_adjoin. rewrite (Derivation_separable derDx sepKx) -/Dx_p Dx_p_0 ?polyOver_comp //. by rewrite add0r mulrCA Dx_p_0 ?minPolyOver ?oppr0 ?mul0r. Qed. Lemma separable_exponent_pchar K x : exists n, [pchar L].-nat n && separable_element K (x ^+ n). Proof. pose d := adjoin_degree K x; move: {2}d.+1 (ltnSn d) => n. elim: n => // n IHn in x @d *; rewrite ltnS => le_d_n. have [[p pcharLp]|] := altP (separablePn_pchar K x); last by rewrite negbK; exists 1. case=> g Kg defKx; have p_pr := pcharf_prime pcharLp. suffices /IHn[m /andP[pcharLm sepKxpm]]: adjoin_degree K (x ^+ p) < n. by exists (p * m)%N; rewrite pnatM pnatE // pcharLp pcharLm exprM. apply: leq_trans le_d_n; rewrite -ltnS -!size_minPoly. have nzKx: minPoly K x != 0 by rewrite monic_neq0 ?monic_minPoly. have nzg: g != 0 by apply: contra_eqN defKx => /eqP->; rewrite comp_poly0. apply: leq_ltn_trans (dvdp_leq nzg _) _. by rewrite minPoly_dvdp // rootE -hornerXn -horner_comp -defKx minPolyxx. rewrite (polySpred nzKx) ltnS defKx size_comp_poly size_polyXn /=. suffices g_gt1: 1 < size g by rewrite -(subnKC g_gt1) ltn_Pmulr ?prime_gt1. apply: contra_eqT (size_minPoly K x); rewrite defKx -leqNgt => /size1_polyC->. by rewrite comp_polyC size_polyC; case: (_ != 0). Qed. #[deprecated(since="mathcomp 2.4.0", note="Use separable_exponent_pchar instead.")] Notation separable_exponent := (separable_exponent_pchar) (only parsing). Lemma pcharf0_separable K : [pchar L] =i pred0 -> forall x, separable_element K x. Proof. move=> pcharL0 x; have [n /andP[pcharLn]] := separable_exponent_pchar K x. by rewrite (pnat_1 pcharLn (sub_in_pnat _ pcharLn)) // => p _; rewrite pcharL0. Qed. #[deprecated(since="mathcomp 2.4.0", note="Use pcharf0_separable instead.")] Notation charf0_separable := (pcharf0_separable) (only parsing). Lemma pcharf_p_separable K x e p : p \in [pchar L] -> separable_element K x = (x \in <<K; x ^+ (p ^ e.+1)>>%VS). Proof. move=> pcharLp; apply/idP/idP=> [sepKx | /Fadjoin_poly_eq]; last first. set m := p ^ _; set f := Fadjoin_poly K _ x => Dx; apply/separable_elementP. have mL0: m%:R = 0 :> L by apply/eqP; rewrite -(dvdn_pcharf pcharLp) dvdn_exp. exists ('X - (f \Po 'X^m)); split. - by rewrite rpredB ?polyOver_comp ?rpredX ?polyOverX ?Fadjoin_polyOver. - by rewrite rootE !hornerE horner_comp hornerXn Dx subrr. rewrite unlock !(derivE, deriv_comp) -mulr_natr -rmorphMn /= mL0. by rewrite !mulr0 subr0 coprimep1. without loss{e} ->: e x sepKx / e = 0. move=> IH; elim: {e}e.+1 => [|e]; [exact: memv_adjoin | apply: subvP]. apply/FadjoinP/andP; rewrite subv_adjoin expnSr exprM (IH 0) //. by have /adjoin_separableP-> := sepKx; rewrite ?rpredX ?memv_adjoin. set K' := <<K; x ^+ p>>%VS; have sKK': (K <= K')%VS := subv_adjoin _ _. pose q := minPoly K' x; pose g := 'X^p - (x ^+ p)%:P. have [K'g]: g \is a polyOver K' /\ q \is a polyOver K'. by rewrite minPolyOver rpredB ?rpredX ?polyOverX // polyOverC memv_adjoin. have /dvdpP[c Dq]: 'X - x%:P %| q by rewrite dvdp_XsubCl root_minPoly. have co_c_g: coprimep c g. have pcharPp: p \in [pchar {poly L}] := rmorph_pchar polyC pcharLp. rewrite /g polyC_exp -!(pFrobenius_autE pcharPp) -rmorphB coprimep_expr //. have: separable_poly q := separable_elementS sKK' sepKx. by rewrite Dq separable_mul => /and3P[]. have{g K'g co_c_g} /size_poly1P[a nz_a Dc]: size c == 1. suffices c_dv_g: c %| g by rewrite -(eqp_size (dvdp_gcd_idl c_dv_g)). have: q %| g by rewrite minPoly_dvdp // rootE !hornerE subrr. by apply: dvdp_trans; rewrite Dq dvdp_mulIl. rewrite {q}Dq {c}Dc mulrBr -rmorphM -rmorphN -cons_poly_def qualifE /=. by rewrite polyseq_cons !polyseqC nz_a /= rpredN andbCA => /and3P[/fpredMl->]. Qed. #[deprecated(since="mathcomp 2.4.0", note="Use pcharf_p_separable instead.")] Notation charf_p_separable := (pcharf_p_separable) (only parsing). Lemma pcharf_n_separable K x n : [pchar L].-nat n -> 1 < n -> separable_element K x = (x \in <<K; x ^+ n>>%VS). Proof. rewrite -pi_pdiv; set p := pdiv n => pcharLn pi_n_p. have pcharLp: p \in [pchar L] := pnatPpi pcharLn pi_n_p. have <-: (n`_p)%N = n by rewrite -(eq_partn n (pcharf_eq pcharLp)) part_pnat_id. by rewrite p_part lognE -mem_primes pi_n_p -pcharf_p_separable. Qed. #[deprecated(since="mathcomp 2.4.0", note="Use pcharf_n_separable instead.")] Notation charf_n_separable := (pcharf_n_separable) (only parsing). Definition purely_inseparable_element U x := x ^+ ex_minn (separable_exponent_pchar <<U>> x) \in U. Lemma purely_inseparable_elementP_pchar {K x} : reflect (exists2 n, [pchar L].-nat n & x ^+ n \in K) (purely_inseparable_element K x). Proof. rewrite /purely_inseparable_element. case: ex_minnP => n /andP[pcharLn /=]; rewrite subfield_closed => sepKxn min_xn. apply: (iffP idP) => [Kxn | [m pcharLm Kxm]]; first by exists n. have{min_xn}: n <= m by rewrite min_xn ?pcharLm ?base_separable. rewrite leq_eqVlt => /predU1P[-> // | ltnm]; pose p := pdiv m. have m_gt1: 1 < m by have [/leq_ltn_trans->] := andP pcharLn. have pcharLp: p \in [pchar L] by rewrite (pnatPpi pcharLm) ?pi_pdiv. have [/p_natP[em Dm] /p_natP[en Dn]]: p.-nat m /\ p.-nat n. by rewrite -!(eq_pnat _ (pcharf_eq pcharLp)). rewrite Dn Dm ltn_exp2l ?prime_gt1 ?pdiv_prime // in ltnm. rewrite -(Fadjoin_idP Kxm) Dm -(subnKC ltnm) addSnnS expnD exprM -Dn. by rewrite -pcharf_p_separable. Qed. #[deprecated(since="mathcomp 2.4.0", note="Use purely_inseparable_elementP_pchar instead.")] Notation purely_inseparable_elementP := (purely_inseparable_elementP_pchar) (only parsing). Lemma separable_inseparable_element K x : separable_element K x && purely_inseparable_element K x = (x \in K). Proof. rewrite /purely_inseparable_element; case: ex_minnP => [[|m]] //=. rewrite subfield_closed; case: m => /= [-> //| m _ /(_ 1)/implyP/= insepKx]. by rewrite (negPf insepKx) (contraNF (@base_separable K x) insepKx). Qed. Lemma base_inseparable K x : x \in K -> purely_inseparable_element K x. Proof. by rewrite -separable_inseparable_element => /andP[]. Qed. Lemma sub_inseparable K E x : (K <= E)%VS -> purely_inseparable_element K x -> purely_inseparable_element E x. Proof. move/subvP=> sKE /purely_inseparable_elementP_pchar[n pcharLn /sKE Exn]. by apply/purely_inseparable_elementP_pchar; exists n. Qed. Section PrimitiveElementTheorem. Variables (K : {subfield L}) (x y : L). Section FiniteCase. Variable N : nat. Let K_is_large := exists s, [/\ uniq s, {subset s <= K} & N < size s]. Let cyclic_or_large (z : L) : z != 0 -> K_is_large \/ exists a, z ^+ a.+1 = 1. Proof. move=> nz_z; pose d := adjoin_degree K z. pose h0 (i : 'I_(N ^ d).+1) (j : 'I_d) := (Fadjoin_poly K z (z ^+ i))`_j. pose s := undup [seq h0 i j | i <- enum 'I_(N ^ d).+1, j <- enum 'I_d]. have s_h0 i j: h0 i j \in s. by rewrite mem_undup; apply/allpairsP; exists (i, j); rewrite !mem_enum. pose h i := [ffun j => Ordinal (etrans (index_mem _ _) (s_h0 i j))]. pose h' (f : {ffun 'I_d -> 'I_(size s)}) := \sum_(j < d) s`_(f j) * z ^+ j. have hK i: h' (h i) = z ^+ i. have Kz_zi: z ^+ i \in <<K; z>>%VS by rewrite rpredX ?memv_adjoin. rewrite -(Fadjoin_poly_eq Kz_zi) (horner_coef_wide z (size_poly _ _)) -/d. by apply: eq_bigr => j _; rewrite ffunE /= nth_index. have [inj_h | ] := altP (@injectiveP _ _ h). left; exists s; split=> [|zi_j|]; rewrite ?undup_uniq ?mem_undup //=. by case/allpairsP=> ij [_ _ ->]; apply/polyOverP/Fadjoin_polyOver. rewrite -[size s]card_ord -(@ltn_exp2r _ _ d) // -{2}[d]card_ord -card_ffun. by rewrite -[_.+1]card_ord -(card_image inj_h) max_card. case/injectivePn=> i1 [i2 i1'2 /(congr1 h')]; rewrite !hK => eq_zi12; right. without loss{i1'2} lti12: i1 i2 eq_zi12 / i1 < i2. by move=> IH; move: i1'2; rewrite neq_ltn => /orP[]; apply: IH. by exists (i2 - i1.+1)%N; rewrite subnSK ?expfB // eq_zi12 divff ?expf_neq0. Qed. Lemma finite_PET : K_is_large \/ exists z, (<< <<K; y>>; x>> = <<K; z>>)%VS. Proof. have [-> | /cyclic_or_large[|[a Dxa]]] := eqVneq x 0; first 2 [by left]. by rewrite addv0 subfield_closed; right; exists y. have [-> | /cyclic_or_large[|[b Dyb]]] := eqVneq y 0; first 2 [by left]. by rewrite addv0 subfield_closed; right; exists x. pose h0 (ij : 'I_a.+1 * 'I_b.+1) := x ^+ ij.1 * y ^+ ij.2. pose H := <<[set ij | h0 ij == 1%R]>>%G; pose h (u : coset_of H) := h0 (repr u). have h0M: {morph h0: ij1 ij2 / (ij1 * ij2)%g >-> ij1 * ij2}. by rewrite /h0 => [] [i1 j1] [i2 j2] /=; rewrite mulrACA -!exprD !expr_mod. have memH ij: (ij \in H) = (h0 ij == 1). rewrite /= gen_set_id ?inE //; apply/group_setP; rewrite inE [h0 _]mulr1. by split=> // ? ? /[!(inE, h0M)] /eqP-> /eqP->; rewrite mulr1. have nH ij: ij \in 'N(H)%g. by apply/(subsetP (cent_sub _))/centP=> ij1 _; congr (_, _); rewrite Zp_mulgC. have hE ij: h (coset H ij) = h0 ij. rewrite /h val_coset //; case: repr_rcosetP => ij1. by rewrite memH h0M => /eqP->; rewrite mul1r. have h1: h 1%g = 1 by rewrite /h repr_coset1 [h0 _]mulr1. have hM: {morph h: u v / (u * v)%g >-> u * v}. by do 2![move=> u; have{u} [? _ ->] := cosetP u]; rewrite -morphM // !hE h0M. have /cyclicP[w defW]: cyclic [set: coset_of H]. apply: field_mul_group_cyclic (in2W hM) _ => u _; have [ij _ ->] := cosetP u. by split=> [/eqP | -> //]; rewrite hE -memH => /coset_id. have Kw_h ij t: h0 ij = t -> t \in <<K; h w>>%VS. have /cycleP[k Dk]: coset H ij \in <[w]>%g by rewrite -defW inE. rewrite -hE {}Dk => <-; elim: k => [|k IHk]; first by rewrite h1 rpred1. by rewrite expgS hM rpredM // memv_adjoin. right; exists (h w); apply/eqP; rewrite eqEsubv !(sameP FadjoinP andP). rewrite subv_adjoin (subv_trans (subv_adjoin K y)) ?subv_adjoin //=. rewrite (Kw_h (0, inZp 1)) 1?(Kw_h (inZp 1, 0)) /h0 ?mulr1 ?mul1r ?expr_mod //=. by rewrite rpredM ?rpredX ?memv_adjoin // subvP_adjoin ?memv_adjoin. Qed. End FiniteCase. Hypothesis sepKy : separable_element K y. Lemma Primitive_Element_Theorem : exists z, (<< <<K; y>>; x>> = <<K; z>>)%VS. Proof. have /polyOver_subvs[p Dp]: minPoly K x \is a polyOver K := minPolyOver K x. have nz_pKx: minPoly K x != 0 by rewrite monic_neq0 ?monic_minPoly. have{nz_pKx} nz_p: p != 0 by rewrite Dp map_poly_eq0 in nz_pKx. have{Dp} px0: root (map_poly vsval p) x by rewrite -Dp root_minPoly. have [q0 [Kq0 q0y0 sepKq0]] := separable_elementP sepKy. have /polyOver_subvs[q Dq]: minPoly K y \is a polyOver K := minPolyOver K y. have qy0: root (map_poly vsval q) y by rewrite -Dq root_minPoly. have sep_pKy: separable_poly (minPoly K y). by rewrite (dvdp_separable _ sepKq0) ?minPoly_dvdp. have{sep_pKy} sep_q: separable_poly q by rewrite Dq separable_map in sep_pKy. have [r nz_r PETr] := large_field_PET nz_p px0 qy0 sep_q. have [[s [Us Ks /ltnW leNs]] | //] := finite_PET (size r). have{s Us leNs} /allPn[t {}/Ks Kt nz_rt]: ~~ all (root r) s. by apply: contraTN leNs; rewrite -ltnNge => /max_poly_roots->. have{PETr} [/= [p1 Dx] [q1 Dy]] := PETr (Subvs Kt) nz_rt. set z := t * y - x in Dx Dy; exists z; apply/eqP. rewrite eqEsubv !(sameP FadjoinP andP) subv_adjoin. have Kz_p1z (r1 : {poly subvs_of K}): (map_poly vsval r1).[z] \in <<K; z>>%VS. rewrite rpred_horner ?memv_adjoin ?(polyOverSv (subv_adjoin K z)) //. by apply/polyOver_subvs; exists r1. rewrite -{1}Dx -{1}Dy !{Dx Dy}Kz_p1z /=. rewrite (subv_trans (subv_adjoin K y)) ?subv_adjoin // rpredB ?memv_adjoin //. by rewrite subvP_adjoin // rpredM ?memv_adjoin ?subvP_adjoin. Qed. Lemma adjoin_separable : separable_element <<K; y>> x -> separable_element K x. Proof. have /Derivation_separableP derKy := sepKy => /Derivation_separableP derKy_x. have [z defKz] := Primitive_Element_Theorem. suffices /adjoin_separableP: separable_element K z. by apply; rewrite -defKz memv_adjoin. apply/Derivation_separableP=> D; rewrite -defKz => derKxyD DK_0. suffices derKyD: Derivation <<K; y>>%VS D by rewrite derKy_x // derKy. by apply: DerivationS derKxyD; apply: subv_adjoin. Qed. End PrimitiveElementTheorem. Lemma strong_Primitive_Element_Theorem K x y : separable_element <<K; x>> y -> exists2 z : L, (<< <<K; y>>; x>> = <<K; z>>)%VS & separable_element K x -> separable_element K y. Proof. move=> sepKx_y; have [n /andP[pcharLn sepKyn]] := separable_exponent_pchar K y. have adjK_C z t: (<<<<K; z>>; t>> = <<<<K; t>>; z>>)%VS. by rewrite !agenv_add_id -!addvA (addvC <[_]>%VS). have [z defKz] := Primitive_Element_Theorem x sepKyn. exists z => [|/adjoin_separable->]; rewrite ?sepKx_y // -defKz. have [|n_gt1|-> //] := ltngtP n 1; first by case: (n) pcharLn. apply/eqP; rewrite !(adjK_C _ x) eqEsubv; apply/andP. split; apply/FadjoinP/andP; rewrite subv_adjoin ?rpredX ?memv_adjoin //=. by rewrite -pcharf_n_separable ?sepKx_y. Qed. Definition separable U W : bool := all (separable_element U) (vbasis W). Definition purely_inseparable U W : bool := all (purely_inseparable_element U) (vbasis W). Lemma separable_add K x y : separable_element K x -> separable_element K y -> separable_element K (x + y). Proof. move/(separable_elementS (subv_adjoin K y))=> sepKy_x sepKy. have [z defKz] := Primitive_Element_Theorem x sepKy. have /(adjoin_separableP _): x + y \in <<K; z>>%VS. by rewrite -defKz rpredD ?memv_adjoin // subvP_adjoin ?memv_adjoin. apply; apply: adjoin_separable sepKy (adjoin_separable sepKy_x _). by rewrite defKz base_separable ?memv_adjoin. Qed. Lemma separable_sum I r (P : pred I) (v_ : I -> L) K : (forall i, P i -> separable_element K (v_ i)) -> separable_element K (\sum_(i <- r | P i) v_ i). Proof. move=> sepKi. by elim/big_ind: _; [apply/base_separable/mem0v | apply: separable_add |]. Qed. Lemma inseparable_add K x y : purely_inseparable_element K x -> purely_inseparable_element K y -> purely_inseparable_element K (x + y). Proof. have insepP := purely_inseparable_elementP_pchar. move=> /insepP[n pcharLn Kxn] /insepP[m pcharLm Kym]; apply/insepP. have pcharLnm: [pchar L].-nat (n * m)%N by rewrite pnatM pcharLn. by exists (n * m)%N; rewrite ?exprDn_pchar // {2}mulnC !exprM memvD // rpredX. Qed. Lemma inseparable_sum I r (P : pred I) (v_ : I -> L) K : (forall i, P i -> purely_inseparable_element K (v_ i)) -> purely_inseparable_element K (\sum_(i <- r | P i) v_ i). Proof. move=> insepKi. by elim/big_ind: _; [apply/base_inseparable/mem0v | apply: inseparable_add |]. Qed. Lemma separableP {K E} : reflect (forall y, y \in E -> separable_element K y) (separable K E). Proof. apply/(iffP idP)=> [/allP|] sepK_E; last by apply/allP=> x /vbasis_mem/sepK_E. move=> y /coord_vbasis->; apply/separable_sum=> i _. have: separable_element K (vbasis E)`_i by apply/sepK_E/memt_nth. by move/adjoin_separableP; apply; rewrite rpredZ ?memv_adjoin. Qed. Lemma purely_inseparableP {K E} : reflect (forall y, y \in E -> purely_inseparable_element K y) (purely_inseparable K E). Proof. apply/(iffP idP)=> [/allP|] sep'K_E; last by apply/allP=> x /vbasis_mem/sep'K_E. move=> y /coord_vbasis->; apply/inseparable_sum=> i _. have: purely_inseparable_element K (vbasis E)`_i by apply/sep'K_E/memt_nth. case/purely_inseparable_elementP_pchar=> n pcharLn K_Ein. by apply/purely_inseparable_elementP_pchar; exists n; rewrite // exprZn rpredZ. Qed. Lemma adjoin_separable_eq K x : separable_element K x = separable K <<K; x>>%VS. Proof. exact: sameP adjoin_separableP separableP. Qed. Lemma separable_inseparable_decomposition E K : {x | x \in E /\ separable_element K x & purely_inseparable <<K; x>> E}. Proof. without loss sKE: K / (K <= E)%VS. case/(_ _ (capvSr K E)) => x [Ex sepKEx] /purely_inseparableP sep'KExE. exists x; first by split; last exact/(separable_elementS _ sepKEx)/capvSl. apply/purely_inseparableP=> y /sep'KExE; apply: sub_inseparable. exact/adjoinSl/capvSl. pose E_ i := (vbasis E)`_i; pose fP i := separable_exponent_pchar K (E_ i). pose f i := E_ i ^+ ex_minn (fP i); pose s := mkseq f (\dim E). pose K' := <<K & s>>%VS. have sepKs: all (separable_element K) s. by rewrite all_map /f; apply/allP=> i _ /=; case: ex_minnP => m /andP[]. have [x sepKx defKx]: {x | x \in E /\ separable_element K x & K' = <<K; x>>%VS}. have: all [in E] s. rewrite all_map; apply/allP=> i; rewrite mem_iota => ltis /=. by rewrite rpredX // vbasis_mem // memt_nth. rewrite {}/K'; elim/last_ind: s sepKs => [|s t IHs]. by exists 0; [rewrite base_separable mem0v | rewrite adjoin_nil addv0]. rewrite adjoin_rcons !all_rcons => /andP[sepKt sepKs] /andP[/= Et Es]. have{IHs sepKs Es} [y [Ey sepKy] ->{s}] := IHs sepKs Es. have /sig_eqW[x defKx] := Primitive_Element_Theorem t sepKy. exists x; [split | exact: defKx]. suffices: (<<K; x>> <= E)%VS by case/FadjoinP. by rewrite -defKx !(sameP FadjoinP andP) sKE Ey Et. apply/adjoin_separableP=> z; rewrite -defKx => Kyt_z. apply: adjoin_separable sepKy _; apply: adjoin_separableP Kyt_z. exact: separable_elementS (subv_adjoin K y) sepKt. exists x; rewrite // -defKx; apply/(all_nthP 0)=> i; rewrite size_tuple => ltiE. apply/purely_inseparable_elementP_pchar. exists (ex_minn (fP i)); first by case: ex_minnP => n /andP[]. by apply/seqv_sub_adjoin/map_f; rewrite mem_iota. Qed. Definition separable_generator K E : L := s2val (locked (separable_inseparable_decomposition E K)). Lemma separable_generator_mem E K : separable_generator K E \in E. Proof. by rewrite /separable_generator; case: (locked _) => ? []. Qed. Lemma separable_generatorP E K : separable_element K (separable_generator K E). Proof. by rewrite /separable_generator; case: (locked _) => ? []. Qed. Lemma separable_generator_maximal E K : purely_inseparable <<K; separable_generator K E>> E. Proof. by rewrite /separable_generator; case: (locked _). Qed. Lemma sub_adjoin_separable_generator E K : separable K E -> (E <= <<K; separable_generator K E>>)%VS. Proof. move/separableP=> sepK_E; apply/subvP=> v Ev. rewrite -separable_inseparable_element. have /purely_inseparableP-> // := separable_generator_maximal E K. by rewrite (separable_elementS _ (sepK_E _ Ev)) // subv_adjoin. Qed. Lemma eq_adjoin_separable_generator E K : separable K E -> (K <= E)%VS -> E = <<K; separable_generator K E>>%VS :> {vspace _}. Proof. move=> sepK_E sKE; apply/eqP; rewrite eqEsubv sub_adjoin_separable_generator //. by apply/FadjoinP/andP; rewrite sKE separable_generator_mem. Qed. Lemma separable_refl K : separable K K. Proof. exact/separableP/base_separable. Qed. Lemma separable_trans M K E : separable K M -> separable M E -> separable K E. Proof. move/sub_adjoin_separable_generator. set x := separable_generator K M => sMKx /separableP sepM_E. apply/separableP => w /sepM_E/(separable_elementS sMKx). case/strong_Primitive_Element_Theorem => _ _ -> //. exact: separable_generatorP. Qed. Lemma separableS K1 K2 E2 E1 : (K1 <= K2)%VS -> (E2 <= E1)%VS -> separable K1 E1 -> separable K2 E2. Proof. move=> sK12 /subvP sE21 /separableP sepK1_E1. by apply/separableP=> y /sE21/sepK1_E1/(separable_elementS sK12). Qed. Lemma separableSl K M E : (K <= M)%VS -> separable K E -> separable M E. Proof. by move/separableS; apply. Qed. Lemma separableSr K M E : (M <= E)%VS -> separable K E -> separable K M. Proof. exact: separableS. Qed. Lemma separable_Fadjoin_seq K rs : all (separable_element K) rs -> separable K <<K & rs>>. Proof. elim/last_ind: rs => [|s x IHs] in K *. by rewrite adjoin_nil subfield_closed separable_refl. rewrite all_rcons adjoin_rcons => /andP[sepKx /IHs/separable_trans-> //]. by rewrite -adjoin_separable_eq (separable_elementS _ sepKx) ?subv_adjoin_seq. Qed. Lemma purely_inseparable_refl K : purely_inseparable K K. Proof. by apply/purely_inseparableP; apply: base_inseparable. Qed. Lemma purely_inseparable_trans M K E : purely_inseparable K M -> purely_inseparable M E -> purely_inseparable K E. Proof. have insepP := purely_inseparableP => /insepP insepK_M /insepP insepM_E. have insepPe := purely_inseparable_elementP_pchar. apply/insepP=> x /insepM_E/insepPe[n pcharLn /insepK_M/insepPe[m pcharLm Kxnm]]. by apply/insepPe; exists (n * m)%N; rewrite ?exprM // pnatM pcharLn pcharLm. Qed. End Separable. Arguments separable_elementP {F L K x}. Arguments separablePn_pchar {F L K x}. Arguments Derivation_separableP {F L K x}. Arguments adjoin_separableP {F L K x}. Arguments purely_inseparable_elementP_pchar {F L K x}. Arguments separableP {F L K E}. Arguments purely_inseparableP {F L K E}.
Basic.lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen, Frédéric Dupuis, Heather Macbeth -/ import Mathlib.Algebra.Module.LinearMap.Defs import Mathlib.Algebra.NoZeroSMulDivisors.Pi import Mathlib.Algebra.Ring.Opposite import Mathlib.GroupTheory.GroupAction.DomAct.Basic /-! # Further results on (semi)linear maps -/ assert_not_exists Submonoid Finset TrivialStar open Function universe u u' v w x y z variable {R R' S M M' : Type*} namespace LinearMap section SMul variable [Semiring R] [Semiring R'] variable [AddCommMonoid M] [AddCommMonoid M'] variable [Module R M] [Module R' M'] variable {σ₁₂ : R →+* R'} variable {S' T' : Type*} variable [Monoid S'] [DistribMulAction S' M] [SMulCommClass R S' M] variable [Monoid T'] [DistribMulAction T' M] [SMulCommClass R T' M] instance : SMul S'ᵈᵐᵃ (M →ₛₗ[σ₁₂] M') where smul a f := { toFun := a • (f : M → M') map_add' := fun x y ↦ by simp only [DomMulAct.smul_apply, f.map_add, smul_add] map_smul' := fun c x ↦ by simp_rw [DomMulAct.smul_apply, ← smul_comm, f.map_smulₛₗ] } theorem _root_.DomMulAct.smul_linearMap_apply (a : S'ᵈᵐᵃ) (f : M →ₛₗ[σ₁₂] M') (x : M) : (a • f) x = f (DomMulAct.mk.symm a • x) := rfl @[simp] theorem _root_.DomMulAct.mk_smul_linearMap_apply (a : S') (f : M →ₛₗ[σ₁₂] M') (x : M) : (DomMulAct.mk a • f) x = f (a • x) := rfl theorem _root_.DomMulAct.coe_smul_linearMap (a : S'ᵈᵐᵃ) (f : M →ₛₗ[σ₁₂] M') : (a • f : M →ₛₗ[σ₁₂] M') = a • (f : M → M') := rfl instance [SMulCommClass S' T' M] : SMulCommClass S'ᵈᵐᵃ T'ᵈᵐᵃ (M →ₛₗ[σ₁₂] M') := ⟨fun s t f ↦ ext fun m ↦ by simp_rw [DomMulAct.smul_linearMap_apply, smul_comm]⟩ end SMul section Actions variable [Semiring R] [Semiring R'] variable [AddCommMonoid M] [AddCommMonoid M'] variable [Module R M] [Module R' M'] variable {σ₁₂ : R →+* R'} section SMul instance {S'} [Monoid S'] [DistribMulAction S' M] [SMulCommClass R S' M] : DistribMulAction S'ᵈᵐᵃ (M →ₛₗ[σ₁₂] M') where one_smul _ := ext fun _ ↦ congr_arg _ (one_smul _ _) mul_smul _ _ _ := ext fun _ ↦ congr_arg _ (mul_smul _ _ _) smul_add _ _ _ := ext fun _ ↦ rfl smul_zero _ := ext fun _ ↦ rfl end SMul section Module variable [Semiring S] [Module S M] [Module S M'] [SMulCommClass R' S M'] instance [NoZeroSMulDivisors S M'] : NoZeroSMulDivisors S (M →ₛₗ[σ₁₂] M') := coe_injective.noZeroSMulDivisors _ rfl coe_smul instance [SMulCommClass R S M] : Module Sᵈᵐᵃ (M →ₛₗ[σ₁₂] M') where add_smul _ _ _ := ext fun _ ↦ by simp_rw [add_apply, DomMulAct.smul_linearMap_apply, ← map_add, ← add_smul]; rfl zero_smul _ := ext fun _ ↦ by erw [DomMulAct.smul_linearMap_apply, zero_smul, map_zero]; rfl end Module end Actions end LinearMap
Module.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.Algebra.Category.ModuleCat.Abelian import Mathlib.Algebra.Category.ModuleCat.Adjunctions import Mathlib.Algebra.Category.ModuleCat.Colimits import Mathlib.Algebra.Category.ModuleCat.FilteredColimits import Mathlib.CategoryTheory.Sites.Abelian import Mathlib.CategoryTheory.Sites.Adjunction import Mathlib.CategoryTheory.Sites.Equivalence import Mathlib.Condensed.Light.Basic /-! # Light condensed `R`-modules This files defines light condensed modules over a ring `R`. ## Main results * Light condensed `R`-modules form an abelian category. * The forgetful functor from light condensed `R`-modules to light condensed sets has a left adjoint, sending a light condensed set to the corresponding *free* light condensed `R`-module. -/ universe u open CategoryTheory variable (R : Type u) [Ring R] /-- The category of condensed `R`-modules, defined as sheaves of `R`-modules over `CompHaus` with respect to the coherent Grothendieck topology. -/ abbrev LightCondMod := LightCondensed.{u} (ModuleCat.{u} R) noncomputable instance : Abelian (LightCondMod.{u} R) := sheafIsAbelian /-- The forgetful functor from condensed `R`-modules to condensed sets. -/ def LightCondensed.forget : LightCondMod R ⥤ LightCondSet := sheafCompose _ (CategoryTheory.forget _) /-- The left adjoint to the forgetful functor. The *free condensed `R`-module* on a condensed set. -/ noncomputable def LightCondensed.free : LightCondSet ⥤ LightCondMod R := Sheaf.composeAndSheafify _ (ModuleCat.free R) /-- The condensed version of the free-forgetful adjunction. -/ noncomputable def LightCondensed.freeForgetAdjunction : free R ⊣ forget R := Sheaf.adjunction _ (ModuleCat.adj R) /-- The category of condensed abelian groups, defined as sheaves of abelian groups over `CompHaus` with respect to the coherent Grothendieck topology. -/ abbrev LightCondAb := LightCondMod ℤ noncomputable example : Abelian LightCondAb := inferInstance namespace LightCondMod lemma hom_naturality_apply {X Y : LightCondMod.{u} R} (f : X ⟶ Y) {S T : LightProfiniteᵒᵖ} (g : S ⟶ T) (x : X.val.obj S) : f.val.app T (X.val.map g x) = Y.val.map g (f.val.app S x) := NatTrans.naturality_apply f.val g x end LightCondMod
fingraph.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. From mathcomp Require Import seq path fintype. (******************************************************************************) (* This file develops the theory of finite graphs represented by an "edge" *) (* relation over a finType T; this mainly amounts to the theory of the *) (* transitive closure of such relations. *) (* For g : T -> seq T, e : rel T and f : T -> T we define: *) (* grel g == the adjacency relation y \in g x of the graph g. *) (* rgraph e == the graph (x |-> enum (e x)) of the relation e. *) (* dfs g n v x == the list of points traversed by a depth-first search of *) (* the g, at depth n, starting from x, and avoiding v. *) (* dfs_path g v x y <-> there is a path from x to y in g \ v. *) (* connect e == the reflexive transitive closure of e (computed by dfs). *) (* connect_sym e <-> connect e is symmetric, hence an equivalence relation. *) (* root e x == a representative of connect e x, which is the component *) (* of x in the transitive closure of e. *) (* roots e == the codomain predicate of root e. *) (* n_comp e a == the number of e-connected components of a, when a is *) (* e-closed and connect e is symmetric. *) (* equivalence classes of connect e if connect_sym e holds. *) (* closed e a == the collective predicate a is e-invariant. *) (* closure e a == the e-closure of a (the image of a under connect e). *) (* rel_adjunction h e e' a <-> in the e-closed domain a, h is the left part *) (* of an adjunction from e to another relation e'. *) (* fconnect f == connect (frel f), i.e., "connected under f iteration". *) (* froot f x == root (frel f) x, the root of the orbit of x under f. *) (* froots f == roots (frel f) == orbit representatives for f. *) (* orbit f x == lists the f-orbit of x. *) (* findex f x y == index of y in the f-orbit of x. *) (* order f x == size (cardinal) of the f-orbit of x. *) (* order_set f n == elements of f-order n. *) (* finv f == the inverse of f, if f is injective. *) (* := finv f x := iter (order x).-1 f x. *) (* fcard f a == number of orbits of f in a, provided a is f-invariant *) (* f is one-to-one. *) (* fclosed f a == the collective predicate a is f-invariant. *) (* fclosure f a == the closure of a under f iteration. *) (* fun_adjunction == rel_adjunction (frel f). *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Definition grel (T : eqType) (g : T -> seq T) := [rel x y | y \in g x]. (* Decidable connectivity in finite types. *) Section Connect. Variable T : finType. Section Dfs. Variable g : T -> seq T. Implicit Type v w a : seq T. Fixpoint dfs n v x := if x \in v then v else if n is n'.+1 then foldl (dfs n') (x :: v) (g x) else v. Lemma subset_dfs n v a : v \subset foldl (dfs n) v a. Proof. elim: n a v => [|n IHn]; first by elim=> //= *; rewrite if_same. elim=> //= x a IHa v; apply: subset_trans {IHa}(IHa _); case: ifP => // _. by apply: subset_trans (IHn _ _); apply/subsetP=> y; apply: predU1r. Qed. Inductive dfs_path v x y : Prop := DfsPath p of path (grel g) x p & y = last x p & [disjoint x :: p & v]. Lemma dfs_pathP n x y v : #|T| <= #|v| + n -> y \notin v -> reflect (dfs_path v x y) (y \in dfs n v x). Proof. have dfs_id w z: z \notin w -> dfs_path w z z. by exists [::]; rewrite ?disjoint_has //= orbF. elim: n => [|n IHn] /= in x y v * => le_v'_n not_vy. rewrite addn0 (geq_leqif (subset_leqif_card (subset_predT _))) in le_v'_n. by rewrite predT_subset in not_vy. have [v_x | not_vx] := ifPn. by rewrite (negPf not_vy); right=> [] [p _ _]; rewrite disjoint_has /= v_x. set v1 := x :: v; set a := g x; have sub_dfs := subsetP (subset_dfs n _ _). have [-> | neq_yx] := eqVneq y x. by rewrite sub_dfs ?mem_head //; left; apply: dfs_id. apply: (@equivP (exists2 x1, x1 \in a & dfs_path v1 x1 y)); last first. split=> {IHn} [[x1 a_x1 [p g_p p_y]] | [p /shortenP[]]]. rewrite disjoint_has has_sym /= has_sym /= => /norP[_ not_pv]. by exists (x1 :: p); rewrite /= ?a_x1 // disjoint_has negb_or not_vx. case=> [_ _ _ eq_yx | x1 p1 /=]; first by case/eqP: neq_yx. case/andP=> a_x1 g_p1 /andP[not_p1x _] /subsetP p_p1 p1y not_pv. exists x1 => //; exists p1 => //. rewrite disjoint_sym disjoint_cons not_p1x disjoint_sym. by move: not_pv; rewrite disjoint_cons => /andP[_ /disjointWl->]. have{neq_yx not_vy}: y \notin v1 by apply/norP. have{le_v'_n not_vx}: #|T| <= #|v1| + n by rewrite cardU1 not_vx addSnnS. elim: {x v}a v1 => [|x a IHa] v /= le_v'_n not_vy. by rewrite (negPf not_vy); right=> [] []. set v2 := dfs n v x; have v2v: v \subset v2 := subset_dfs n v [:: x]. have [v2y | not_v2y] := boolP (y \in v2). by rewrite sub_dfs //; left; exists x; [apply: mem_head | apply: IHn]. apply: {IHa}(equivP (IHa _ _ not_v2y)). by rewrite (leq_trans le_v'_n) // leq_add2r subset_leq_card. split=> [] [x1 a_x1 [p g_p p_y not_pv]]. exists x1; [exact: predU1r | exists p => //]. by rewrite disjoint_sym (disjointWl v2v) // disjoint_sym. suffices not_p1v2: [disjoint x1 :: p & v2]. case/predU1P: a_x1 => [def_x1 | ]; last by exists x1; last exists p. case/pred0Pn: not_p1v2; exists x; rewrite /= def_x1 mem_head /=. suffices not_vx: x \notin v by apply/IHn; last apply: dfs_id. by move: not_pv; rewrite disjoint_cons def_x1 => /andP[]. apply: contraR not_v2y => /pred0Pn[x2 /andP[/= p_x2 v2x2]]. case/splitPl: p_x2 p_y g_p not_pv => p0 p2 p0x2. rewrite last_cat cat_path -cat_cons lastI cat_rcons {}p0x2 => p2y /andP[_ g_p2]. rewrite disjoint_cat disjoint_cons => /and3P[{p0}_ not_vx2 not_p2v]. have{not_vx2 v2x2} [p1 g_p1 p1_x2 not_p1v] := IHn _ _ v le_v'_n not_vx2 v2x2. apply/IHn=> //; exists (p1 ++ p2); rewrite ?cat_path ?last_cat -?p1_x2 ?g_p1 //. by rewrite -cat_cons disjoint_cat not_p1v. Qed. Lemma dfsP x y : reflect (exists2 p, path (grel g) x p & y = last x p) (y \in dfs #|T| [::] x). Proof. apply: (iffP (dfs_pathP _ _ _)); rewrite ?card0 // => [] [p]; exists p => //. by rewrite disjoint_sym disjoint0. Qed. End Dfs. Variable e : rel T. Definition rgraph x := enum (e x). Lemma rgraphK : grel rgraph =2 e. Proof. by move=> x y; rewrite /= mem_enum. Qed. Definition connect : rel T := [rel x y | y \in dfs rgraph #|T| [::] x]. Canonical connect_app_pred x := ApplicativePred (connect x). Lemma connectP x y : reflect (exists2 p, path e x p & y = last x p) (connect x y). Proof. apply: (equivP (dfsP _ x y)). by split=> [] [p e_p ->]; exists p => //; rewrite (eq_path rgraphK) in e_p *. Qed. Lemma connect_trans : transitive connect. Proof. move=> x y z /connectP[p e_p ->] /connectP[q e_q ->]; apply/connectP. by exists (p ++ q); rewrite ?cat_path ?e_p ?last_cat. Qed. Lemma connect0 x : connect x x. Proof. by apply/connectP; exists [::]. Qed. Lemma eq_connect0 x y : x = y -> connect x y. Proof. by move->; apply: connect0. Qed. Lemma connect1 x y : e x y -> connect x y. Proof. by move=> e_xy; apply/connectP; exists [:: y]; rewrite /= ?e_xy. Qed. Lemma path_connect x p : path e x p -> subpred [in x :: p] (connect x). Proof. move=> e_p y p_y; case/splitPl: p / p_y e_p => p q <-. by rewrite cat_path => /andP[e_p _]; apply/connectP; exists p. Qed. Lemma connect_cycle p : cycle e p -> {in p &, forall x y, connect x y}. Proof. move=> e_p x y /rot_to[i q rip]; rewrite -(mem_rot i) rip => yqx. have /= : cycle e (x :: q) by rewrite -rip rot_cycle. case/splitPl: yqx => r s lxr; rewrite rcons_cat cat_path => /andP[xr _]. by apply/connectP; exists r. Qed. Definition root x := odflt x (pick (connect x)). Definition roots : pred T := fun x => root x == x. Canonical roots_pred := ApplicativePred roots. Definition n_comp_mem (m_a : mem_pred T) := #|predI roots m_a|. Lemma connect_root x : connect x (root x). Proof. by rewrite /root; case: pickP; rewrite ?connect0. Qed. Definition connect_sym := symmetric connect. Hypothesis sym_e : connect_sym. Lemma same_connect : left_transitive connect. Proof. exact: sym_left_transitive connect_trans. Qed. Lemma same_connect_r : right_transitive connect. Proof. exact: sym_right_transitive connect_trans. Qed. Lemma same_connect1 x y : e x y -> connect x =1 connect y. Proof. by move/connect1; apply: same_connect. Qed. Lemma same_connect1r x y : e x y -> connect^~ x =1 connect^~ y. Proof. by move/connect1; apply: same_connect_r. Qed. Lemma rootP x y : reflect (root x = root y) (connect x y). Proof. apply: (iffP idP) => e_xy. by rewrite /root -(eq_pick (same_connect e_xy)); case: pickP e_xy => // ->. by apply: (connect_trans (connect_root x)); rewrite e_xy sym_e connect_root. Qed. Lemma root_root x : root (root x) = root x. Proof. exact/esym/rootP/connect_root. Qed. Lemma roots_root x : roots (root x). Proof. exact/eqP/root_root. Qed. Lemma root_connect x y : (root x == root y) = connect x y. Proof. exact: sameP eqP (rootP x y). Qed. Definition closed_mem m_a := forall x y, e x y -> in_mem x m_a = in_mem y m_a. Definition closure_mem m_a : pred T := fun x => ~~ disjoint (mem (connect x)) m_a. End Connect. Arguments rgraphK [T]. #[global] Hint Resolve connect0 : core. Notation n_comp e a := (n_comp_mem e (mem a)). Notation closed e a := (closed_mem e (mem a)). Notation closure e a := (closure_mem e (mem a)). Prenex Implicits connect root roots. Arguments dfsP {T g x y}. Arguments connectP {T e x y}. Arguments rootP [T e] _ {x y}. Notation fconnect f := (connect (coerced_frel f)). Notation froot f := (root (coerced_frel f)). Notation froots f := (roots (coerced_frel f)). Notation fcard_mem f := (n_comp_mem (coerced_frel f)). Notation fcard f a := (fcard_mem f (mem a)). Notation fclosed f a := (closed (coerced_frel f) a). Notation fclosure f a := (closure (coerced_frel f) a). Section EqConnect. Variable T : finType. Implicit Types (e : rel T) (a : {pred T}). Lemma connect_sub e e' : subrel e (connect e') -> subrel (connect e) (connect e'). Proof. move=> e'e x _ /connectP[p e_p ->]; elim: p x e_p => //= y p IHp x /andP[exy]. by move/IHp; apply: connect_trans; apply: e'e. Qed. Lemma relU_sym e e' : connect_sym e -> connect_sym e' -> connect_sym (relU e e'). Proof. move=> sym_e sym_e'; apply: symmetric_from_pre => x _ /connectP[p e_p ->]. elim: p x e_p => //= y p IHp x /andP[e_xy /IHp{IHp}/connect_trans]; apply. case/orP: e_xy => /connect1; rewrite (sym_e, sym_e'); by apply: connect_sub y x => x y e_xy; rewrite connect1 //= e_xy ?orbT. Qed. Lemma eq_connect e e' : e =2 e' -> connect e =2 connect e'. Proof. move=> eq_e x y; apply/connectP/connectP=> [] [p e_p ->]; by exists p; rewrite // (eq_path eq_e) in e_p *. Qed. Arguments eq_connect [e e']. Lemma eq_n_comp e e' : connect e =2 connect e' -> n_comp_mem e =1 n_comp_mem e'. Proof. move=> eq_e [a]; apply: eq_card => x /=. by rewrite !inE /= /roots /root /= (eq_pick (eq_e x)). Qed. Lemma eq_n_comp_r {e} a a' : a =i a' -> n_comp e a = n_comp e a'. Proof. by move=> eq_a; apply: eq_card => x; rewrite inE /= eq_a. Qed. Lemma n_compC a e : n_comp e T = n_comp e a + n_comp e [predC a]. Proof. rewrite /n_comp_mem (eq_card (fun _ => andbT _)) -(cardID a); congr (_ + _). by apply: eq_card => x; rewrite !inE andbC. Qed. Lemma eq_root e e' : e =2 e' -> root e =1 root e'. Proof. by move=> eq_e x; rewrite /root (eq_pick (eq_connect eq_e x)). Qed. Lemma eq_roots e e' : e =2 e' -> roots e =1 roots e'. Proof. by move=> eq_e x; rewrite /roots (eq_root eq_e). Qed. Lemma connect_rev e : connect [rel x y | e y x] =2 [rel x y | connect e y x]. Proof. suff crev e': subrel (connect [rel x y | e' y x]) [rel x y | connect e' y x]. by move=> x y; apply/idP/idP; apply: crev. move=> x y /connectP[p e_p p_y]; apply/connectP. exists (rev (belast x p)); first by rewrite p_y rev_path. by rewrite -(last_cons x) -rev_rcons p_y -lastI rev_cons last_rcons. Qed. Lemma sym_connect_sym e : symmetric e -> connect_sym e. Proof. by move=> sym_e x y; rewrite (eq_connect sym_e) connect_rev. Qed. End EqConnect. Arguments eq_connect [T e e']. Arguments connect_rev [T]. Section Closure. Variables (T : finType) (e : rel T). Hypothesis sym_e : connect_sym e. Implicit Type a : {pred T}. Lemma same_connect_rev : connect e =2 connect [rel x y | e y x]. Proof. by move=> x y; rewrite sym_e connect_rev. Qed. Lemma intro_closed a : (forall x y, e x y -> x \in a -> y \in a) -> closed e a. Proof. move=> cl_a x y e_xy; apply/idP/idP=> [|a_y]; first exact: cl_a. have{x e_xy} /connectP[p e_p ->]: connect e y x by rewrite sym_e connect1. by elim: p y a_y e_p => //= y p IHp x a_x /andP[/cl_a/(_ a_x)]; apply: IHp. Qed. Lemma closed_connect a : closed e a -> forall x y, connect e x y -> (x \in a) = (y \in a). Proof. move=> cl_a x _ /connectP[p e_p ->]. by elim: p x e_p => //= y p IHp x /andP[/cl_a->]; apply: IHp. Qed. Lemma connect_closed x : closed e (connect e x). Proof. by move=> y z /connect1/same_connect_r; apply. Qed. Lemma predC_closed a : closed e a -> closed e [predC a]. Proof. by move=> cl_a x y /cl_a /[!inE] ->. Qed. Lemma closure_closed a : closed e (closure e a). Proof. apply: intro_closed => x y /connect1 e_xy; congr (~~ _). by apply: eq_disjoint; apply: same_connect. Qed. Lemma mem_closure a : {subset a <= closure e a}. Proof. by move=> x a_x; apply/existsP; exists x; rewrite !inE connect0. Qed. Lemma subset_closure a : a \subset closure e a. Proof. by apply/subsetP; apply: mem_closure. Qed. Lemma n_comp_closure2 x y : n_comp e (closure e (pred2 x y)) = (~~ connect e x y).+1. Proof. rewrite -(root_connect sym_e) -card2; apply: eq_card => z. apply/idP/idP=> [/andP[/eqP {2}<- /pred0Pn[t /andP[/= ezt exyt]]] |]. by case/pred2P: exyt => <-; rewrite (rootP sym_e ezt) !inE eqxx ?orbT. by case/pred2P=> ->; rewrite !inE roots_root //; apply/existsP; [exists x | exists y]; rewrite !inE eqxx ?orbT sym_e connect_root. Qed. Lemma n_comp_connect x : n_comp e (connect e x) = 1. Proof. rewrite -(card1 (root e x)); apply: eq_card => y. apply/andP/eqP => [[/eqP r_y /rootP-> //] | ->] /=. by rewrite inE connect_root roots_root. Qed. End Closure. Arguments same_connect_rev [T e]. Section Orbit. Variables (T : finType) (f : T -> T). Definition order x := #|fconnect f x|. Definition orbit x := traject f x (order x). Definition findex x y := index y (orbit x). Definition finv x := iter (order x).-1 f x. Lemma fconnect_iter n x : fconnect f x (iter n f x). Proof. apply/connectP. by exists (traject f (f x) n); [apply: fpath_traject | rewrite last_traject]. Qed. Lemma fconnect1 x : fconnect f x (f x). Proof. exact: (fconnect_iter 1). Qed. Lemma fconnect_finv x : fconnect f x (finv x). Proof. exact: fconnect_iter. Qed. Lemma orderSpred x : (order x).-1.+1 = order x. Proof. by rewrite /order (cardD1 x) [_ x _]connect0. Qed. Lemma size_orbit x : size (orbit x) = order x. Proof. exact: size_traject. Qed. Lemma looping_order x : looping f x (order x). Proof. apply: contraFT (ltnn (order x)); rewrite -looping_uniq => /card_uniqP. rewrite size_traject => <-; apply: subset_leq_card. by apply/subsetP=> _ /trajectP[i _ ->]; apply: fconnect_iter. Qed. Lemma fconnect_orbit x y : fconnect f x y = (y \in orbit x). Proof. apply/idP/idP=> [/connectP[_ /fpathP[m ->] ->] | /trajectP[i _ ->]]. by rewrite last_traject; apply/loopingP/looping_order. exact: fconnect_iter. Qed. Lemma in_orbit x : x \in orbit x. Proof. by rewrite -fconnect_orbit. Qed. Hint Resolve in_orbit : core. Lemma order_gt0 x : order x > 0. Proof. by rewrite -orderSpred. Qed. Hint Resolve order_gt0 : core. Lemma orbit_uniq x : uniq (orbit x). Proof. rewrite /orbit -orderSpred looping_uniq; set n := (order x).-1. apply: contraFN (ltnn n) => /trajectP[i lt_i_n eq_fnx_fix]. rewrite orderSpred -(size_traject f x n). apply: (leq_trans (subset_leq_card _) (card_size _)); apply/subsetP=> z. rewrite inE fconnect_orbit => /trajectP[j le_jn ->{z}]. rewrite -orderSpred -/n ltnS leq_eqVlt in le_jn. by apply/trajectP; case/predU1P: le_jn => [->|]; [exists i | exists j]. Qed. Lemma findex_max x y : fconnect f x y -> findex x y < order x. Proof. by rewrite [_ y]fconnect_orbit -index_mem size_orbit. Qed. Lemma findex_iter x i : i < order x -> findex x (iter i f x) = i. Proof. move=> lt_ix; rewrite -(nth_traject f lt_ix) /findex index_uniq ?orbit_uniq //. by rewrite size_orbit. Qed. Lemma iter_findex x y : fconnect f x y -> iter (findex x y) f x = y. Proof. rewrite [_ y]fconnect_orbit => fxy; pose i := index y (orbit x). have lt_ix: i < order x by rewrite -size_orbit index_mem. by rewrite -(nth_traject f lt_ix) nth_index. Qed. Lemma findex0 x : findex x x = 0. Proof. by rewrite /findex /orbit -orderSpred /= eqxx. Qed. Lemma findex_eq0 x y : (findex x y == 0) = (x == y). Proof. by rewrite /findex /orbit -orderSpred /=; case: (x == y). Qed. Lemma fconnect_invariant (T' : eqType) (k : T -> T') : invariant f k =1 xpredT -> forall x y, fconnect f x y -> k x = k y. Proof. move=> eq_k_f x y /iter_findex <-; elim: {y}(findex x y) => //= n ->. by rewrite (eqP (eq_k_f _)). Qed. Lemma mem_orbit x : {homo f : y / y \in orbit x}. Proof. by move=> y; rewrite -!fconnect_orbit => /connect_trans->//; apply: fconnect1. Qed. Lemma image_orbit x : {subset image f (orbit x) <= orbit x}. Proof. by move=> _ /mapP[y yin ->]; apply: mem_orbit; rewrite ?mem_enum in yin. Qed. Section orbit_in. Variable S : {pred T}. Hypothesis f_in : {homo f : x / x \in S}. Hypothesis injf : {in S &, injective f}. Lemma finv_in : {homo finv : x / x \in S}. Proof. by move=> x xS; rewrite iter_in. Qed. Lemma f_finv_in : {in S, cancel finv f}. Proof. move=> x xS; move: (looping_order x) (orbit_uniq x). rewrite /looping /orbit -orderSpred looping_uniq /= /looping; set n := _.-1. case/predU1P=> // /trajectP[i lt_i_n]; rewrite -iterSr. by move=> /injf ->; rewrite ?(iter_in _ f_in) //; case/trajectP; exists i. Qed. Lemma finv_f_in : {in S, cancel f finv}. Proof. by move=> x xS; apply/injf; rewrite ?iter_in ?f_finv_in ?f_in. Qed. Lemma finv_inj_in : {in S &, injective finv}. Proof. by move=> x y xS yS q; rewrite -(f_finv_in xS) q f_finv_in. Qed. Lemma fconnect_sym_in : {in S &, forall x y, fconnect f x y = fconnect f y x}. Proof. suff Sf : {in S &, forall x y, fconnect f x y -> fconnect f y x}. by move=> *; apply/idP/idP=> /Sf->. move=> x _ xS _ /connectP [p f_p ->]; elim: p => //= y p IHp in x xS f_p *. case/andP: f_p => /eqP <- /(IHp _ (f_in xS)) /connect_trans -> //. by apply: (connect_trans (fconnect_finv _)); rewrite finv_f_in. Qed. Lemma iter_order_in : {in S, forall x, iter (order x) f x = x}. Proof. by move=> x xS; rewrite -orderSpred iterS; apply: f_finv_in. Qed. Lemma iter_finv_in n : {in S, forall x, n <= order x -> iter n finv x = iter (order x - n) f x}. Proof. move=> x xS; rewrite -[x in LHS]iter_order_in => // /subnKC {1}<-. move: (_ - n) => m; rewrite iterD; elim: n => // n {2}<-. by rewrite iterSr /= finv_f_in // -iterD iter_in. Qed. Lemma cycle_orbit_in : {in S, forall x, (fcycle f) (orbit x)}. Proof. move=> x xS; rewrite /orbit -orderSpred (cycle_path x) /= last_traject. by rewrite -/(finv x) fpath_traject f_finv_in ?eqxx. Qed. Lemma fpath_finv_in p x : (x \in S) && (fpath finv x p) = (last x p \in S) && (fpath f (last x p) (rev (belast x p))). Proof. elim: p x => //= y p IHp x; rewrite rev_cons rcons_path. transitivity [&& y \in S, f y == x & fpath finv y p]. apply/and3P/and3P => -[xS /eqP<- fxp]; split; by rewrite ?f_finv_in ?finv_f_in ?finv_in ?f_in. rewrite andbCA {}IHp !andbA [RHS]andbC -andbA; congr [&& _, _ & _]. by case: p => //= z p; rewrite rev_cons last_rcons. Qed. Lemma fpath_finv_f_in p : {in S, forall x, fpath finv x p -> fpath f (last x p) (rev (belast x p))}. Proof. by move=> x xS /(conj xS)/andP; rewrite fpath_finv_in => /andP[]. Qed. Lemma fpath_f_finv_in p x : last x p \in S -> fpath f (last x p) (rev (belast x p)) -> fpath finv x p. Proof. by move=> lS /(conj lS)/andP; rewrite -fpath_finv_in => /andP[]. Qed. End orbit_in. Lemma injectivePcycle x : reflect {in orbit x &, injective f} (fcycle f (orbit x)). Proof. apply: (iffP idP) => [/inj_cycle//|/cycle_orbit_in]. by apply; [apply: mem_orbit|apply: in_orbit]. Qed. Section orbit_inj. Hypothesis injf : injective f. Lemma f_finv : cancel finv f. Proof. exact: (in1T (f_finv_in _ (in2W _))). Qed. Lemma finv_f : cancel f finv. Proof. exact: (in1T (finv_f_in _ (in2W _))). Qed. Lemma finv_bij : bijective finv. Proof. by exists f; [apply: f_finv|apply: finv_f]. Qed. Lemma finv_inj : injective finv. Proof. exact: (can_inj f_finv). Qed. Lemma fconnect_sym x y : fconnect f x y = fconnect f y x. Proof. exact: (in2T (fconnect_sym_in _ (in2W _))). Qed. Let symf := fconnect_sym. Lemma iter_order x : iter (order x) f x = x. Proof. exact: (in1T (iter_order_in _ (in2W _))). Qed. Lemma iter_finv n x : n <= order x -> iter n finv x = iter (order x - n) f x. Proof. exact: (in1T (@iter_finv_in _ _ (in2W _) _)). Qed. Lemma cycle_orbit x : fcycle f (orbit x). Proof. exact: (in1T (cycle_orbit_in _ (in2W _))). Qed. Lemma fpath_finv x p : fpath finv x p = fpath f (last x p) (rev (belast x p)). Proof. exact: (@fpath_finv_in T _ (in2W _)). Qed. Lemma same_fconnect_finv : fconnect finv =2 fconnect f. Proof. move=> x y; rewrite (same_connect_rev symf); apply: {x y}eq_connect => x y /=. by rewrite (canF_eq finv_f) eq_sym. Qed. Lemma fcard_finv : fcard_mem finv =1 fcard_mem f. Proof. exact: eq_n_comp same_fconnect_finv. Qed. Definition order_set n : pred T := [pred x | order x == n]. Lemma fcard_order_set n (a : {pred T}) : a \subset order_set n -> fclosed f a -> fcard f a * n = #|a|. Proof. move=> a_n cl_a; rewrite /n_comp_mem; set b := [predI froots f & a]. suff <-: #|preim (froot f) b| = #|b| * n. apply: eq_card => x; rewrite !inE (roots_root fconnect_sym). exact/esym/(closed_connect cl_a)/connect_root. have{cl_a a_n} (x): b x -> froot f x = x /\ order x = n. by case/andP=> /eqP-> /(subsetP a_n)/eqnP->. elim: {a b}#|b| {1 3 4}b (eqxx #|b|) => [|m IHm] b def_m f_b. by rewrite eq_card0 // => x; apply: (pred0P def_m). have [x b_x | b0] := pickP b; last by rewrite (eq_card0 b0) in def_m. have [r_x ox_n] := f_b x b_x; rewrite (cardD1 x) [x \in b]b_x eqSS in def_m. rewrite mulSn -{1}ox_n -(IHm _ def_m) => [|_ /andP[_ /f_b //]]. rewrite -(cardID (fconnect f x)); congr (_ + _); apply: eq_card => y. by apply: andb_idl => /= fxy; rewrite !inE -(rootP symf fxy) r_x. by congr (~~ _ && _); rewrite /= /in_mem /= symf -(root_connect symf) r_x. Qed. Lemma fclosed1 (a : {pred T}) : fclosed f a -> forall x, (x \in a) = (f x \in a). Proof. by move=> cl_a x; apply: cl_a (eqxx _). Qed. Lemma same_fconnect1 x : fconnect f x =1 fconnect f (f x). Proof. by apply: same_connect1 => /=. Qed. Lemma same_fconnect1_r x y : fconnect f x y = fconnect f x (f y). Proof. by apply: same_connect1r x => /=. Qed. Lemma fcard_gt0P (a : {pred T}) : fclosed f a -> reflect (exists x, x \in a) (0 < fcard f a). Proof. move=> clfA; apply: (iffP card_gt0P) => [[x /andP[]]|[x xA]]; first by exists x. exists (froot f x); rewrite inE roots_root /=; last exact: fconnect_sym. by rewrite -(closed_connect clfA (connect_root _ x)). Qed. Lemma fcard_gt1P (A : {pred T}) : fclosed f A -> reflect (exists2 x, x \in A & exists2 y, y \in A & ~~ fconnect f x y) (1 < fcard f A). Proof. move=> clAf; apply: (iffP card_gt1P) => [|[x xA [y yA not_xfy]]]. move=> [x [y [/andP [/= rfx xA] /andP[/= rfy yA] xDy]]]. by exists x; try exists y; rewrite // -root_connect // (eqP rfx) (eqP rfy). exists (froot f x), (froot f y); rewrite !inE !roots_root ?root_connect //=. by split => //; rewrite -(closed_connect clAf (connect_root _ _)). Qed. End orbit_inj. Hint Resolve orbit_uniq : core. Section fcycle_p. Variables (p : seq T) (f_p : fcycle f p). Section mem_cycle. Variable (Up : uniq p) (x : T) (p_x : x \in p). (* fconnect_cycle does not dependent on Up *) Lemma fconnect_cycle y : fconnect f x y = (y \in p). Proof. have [i q def_p] := rot_to p_x; rewrite -(mem_rot i p) def_p. have{i def_p} /andP[/eqP q_x f_q]: (f (last x q) == x) && fpath f x q. by have:= f_p; rewrite -(rot_cycle i) def_p (cycle_path x). apply/idP/idP=> [/connectP[_ /fpathP[j ->] ->] | ]; last exact: path_connect. case/fpathP: f_q q_x => n ->; rewrite !last_traject -iterS => def_x. by apply: (@loopingP _ f x n.+1); rewrite /looping def_x /= mem_head. Qed. (* order_le_cycle does not dependent on Up *) Lemma order_le_cycle : order x <= size p. Proof. apply: leq_trans (card_size _); apply/subset_leq_card/subsetP=> y. by rewrite !(fconnect_cycle, inE) ?eqxx. Qed. Lemma order_cycle : order x = size p. Proof. by rewrite -(card_uniqP Up); apply: (eq_card fconnect_cycle). Qed. Lemma orbitE : orbit x = rot (index x p) p. Proof. set i := index _ _; rewrite /orbit order_cycle -(size_rot i) rot_index// -/i. set q := _ ++ _; suffices /fpathP[j ->]: fpath f x q by rewrite /= size_traject. by move: f_p; rewrite -(rot_cycle i) rot_index// (cycle_path x); case/andP. Qed. Lemma orbit_rot_cycle : {i : nat | orbit x = rot i p}. Proof. by rewrite orbitE; exists (index x p). Qed. End mem_cycle. Let f_inj := inj_cycle f_p. Let homo_f := mem_fcycle f_p. Lemma finv_cycle : {homo finv : x / x \in p}. Proof. exact: finv_in. Qed. Lemma f_finv_cycle : {in p, cancel finv f}. Proof. exact: f_finv_in. Qed. Lemma finv_f_cycle : {in p, cancel f finv}. Proof. exact: finv_f_in. Qed. Lemma finv_inj_cycle : {in p &, injective finv}. Proof. exact: finv_inj_in. Qed. Lemma iter_finv_cycle n : {in p, forall x, n <= order x -> iter n finv x = iter (order x - n) f x}. Proof. exact: iter_finv_in. Qed. Lemma cycle_orbit_cycle : {in p, forall x, fcycle f (orbit x)}. Proof. exact: cycle_orbit_in. Qed. Lemma fpath_finv_cycle q x : (x \in p) && (fpath finv x q) = (last x q \in p) && fpath f (last x q) (rev (belast x q)). Proof. exact: fpath_finv_in. Qed. Lemma fpath_finv_f_cycle q : {in p, forall x, fpath finv x q -> fpath f (last x q) (rev (belast x q))}. Proof. exact: fpath_finv_f_in. Qed. Lemma fpath_f_finv_cycle q x : last x q \in p -> fpath f (last x q) (rev (belast x q)) -> fpath finv x q. Proof. exact: fpath_f_finv_in. Qed. Lemma prevE x : x \in p -> prev p x = finv x. Proof. move=> x_p; have /eqP/(congr1 finv) := prev_cycle f_p x_p. by rewrite finv_f_cycle// mem_prev. Qed. End fcycle_p. Section fcycle_cons. Variables (x : T) (p : seq T) (f_p : fcycle f (x :: p)). Lemma fcycle_rconsE : rcons (x :: p) x = traject f x (size p).+2. Proof. by rewrite rcons_cons; have /fpathE-> := f_p; rewrite size_rcons. Qed. Lemma fcycle_consE : x :: p = traject f x (size p).+1. Proof. by have := fcycle_rconsE; rewrite trajectSr => /rcons_inj[/= <-]. Qed. Lemma fcycle_consEflatten : exists k, x :: p = flatten (nseq k.+1 (orbit x)). Proof. move: f_p; rewrite fcycle_consE; elim/ltn_ind: (size p) => n IHn t_cycle. have := order_le_cycle t_cycle (mem_head _ _); rewrite size_traject. case: ltngtP => [||<-] //; last by exists 0; rewrite /= cats0. rewrite ltnS => n_ge _; have := t_cycle. rewrite -(subnKC n_ge) -addnS trajectD. rewrite (iter_order_in (mem_fcycle f_p) (inj_cycle f_p)) ?mem_head//. set m := (_ - _) => cycle_cat. have [||k->] := IHn m; last by exists k.+1. by rewrite ltn_subrL (leq_trans _ n_ge) ?order_gt0. move: cycle_cat; rewrite -orderSpred/= rcons_cat rcons_cons -cat_rcons. by rewrite cat_path last_rcons => /andP[]. Qed. Lemma undup_cycle_cons : undup (x :: p) = orbit x. Proof. by have [n {1}->] := fcycle_consEflatten; rewrite undup_flatten_nseq ?undup_id. Qed. End fcycle_cons. Section fcycle_undup. Variable (p : seq T) (f_p : fcycle f p). Lemma fcycleEflatten : exists k, p = flatten (nseq k (undup p)). Proof. case: p f_p => [//|x q] f_q; first by exists 0. have [k {1}->] := @fcycle_consEflatten x q f_q. by exists k.+1; rewrite undup_cycle_cons. Qed. Lemma fcycle_undup : fcycle f (undup p). Proof. case: p f_p => [//|x q] f_q; rewrite undup_cycle_cons//. by rewrite (cycle_orbit_in (mem_fcycle f_q) (inj_cycle f_q)) ?mem_head. Qed. Let p_undup_uniq := undup_uniq p. Let f_inj := inj_cycle f_p. Let homo_f := mem_fcycle f_p. Lemma in_orbit_cycle : {in p &, forall x, orbit x =i p}. Proof. by move=> x y xp yp; rewrite (orbitE fcycle_undup)// ?mem_rot ?mem_undup. Qed. Lemma eq_order_cycle : {in p &, forall x y, order y = order x}. Proof. by move=> x y xp yp; rewrite !(order_cycle fcycle_undup) ?mem_undup. Qed. Lemma iter_order_cycle : {in p &, forall x y, iter (order x) f y = y}. Proof. by move=> x y xp yp; rewrite (eq_order_cycle yp) ?(iter_order_in homo_f f_inj). Qed. End fcycle_undup. Section fconnect. Lemma fconnect_eqVf x y : fconnect f x y = (x == y) || fconnect f (f x) y. Proof. apply/idP/idP => [/iter_findex <-|/predU1P [<-|] //]; last first. exact/connect_trans/fconnect1. by case: findex => [|i]; rewrite ?eqxx// iterSr fconnect_iter orbT. Qed. (*****************************************************************************) (* Lemma orbitPcycle is of type "The Following Are Equivalent", which means *) (* all four statements are equivalent to each other. In order to use it, one *) (* has to apply it to the natural numbers corresponding to the line, e.g. *) (* `orbitPcycle 0 2 : fcycle f (orbit x) <-> exists k, iter k.+1 f x = x`. *) (* examples of this are in order_id_cycle and fconnnect_f. *) (* One may also use lemma all_iffLR to get a one sided implication, as in *) (* orderPcycle. *) (*****************************************************************************) Lemma orbitPcycle {x} : [<-> (* 0 *) fcycle f (orbit x); (* 1 *) order (f x) = order x; (* 2 *) x \in fconnect f (f x); (* 3 *) exists k, iter k.+1 f x = x; (* 4 *) iter (order x) f x = x; (* 5 *) {in orbit x &, injective f}]. Proof. tfae=> [xorbit_cycle|||[k fkx]|fx y z|/injectivePcycle//]. - by apply: eq_order_cycle xorbit_cycle _ _ _ _; rewrite ?mem_orbit. - move=> /subset_cardP/(_ _)->; rewrite ?inE//; apply/subsetP=> y. by apply: connect_trans; apply: fconnect1. - by exists (findex (f x) x); rewrite // iterSr iter_findex. - apply: (@iter_order_cycle (traject f x k.+1)); rewrite /= ?mem_head//. by apply/fpathP; exists k.+1; rewrite trajectSr -iterSr fkx. - rewrite -!fconnect_orbit => /iter_findex <- /iter_findex <-. move/(congr1 (iter (order x).-1 f)). by rewrite -!iterSr !orderSpred -!iterD ![order _ + _]addnC !iterD fx. Qed. Lemma order_id_cycle x : fcycle f (orbit x) -> order (f x) = order x. Proof. by move/(orbitPcycle 0 1). Qed. Inductive order_spec_cycle x : bool -> Type := | OrderStepCycle of fcycle f (orbit x) & order x = order (f x) : order_spec_cycle x true | OrderStepNoCycle of ~~ fcycle f (orbit x) & order x = (order (f x)).+1 : order_spec_cycle x false. Lemma orderPcycle x : order_spec_cycle x (fcycle f (orbit x)). Proof. have [xcycle|Ncycle] := boolP (fcycle f (orbit x)); constructor => //. by rewrite order_id_cycle. rewrite /order (eq_card (_ : _ =1 [predU1 x & fconnect f (f x)])). by rewrite cardU1 inE (contraNN (all_iffLR orbitPcycle 2 0)). by move=> y; rewrite !inE fconnect_eqVf eq_sym. Qed. Lemma fconnect_f x : fconnect f (f x) x = fcycle f (orbit x). Proof. by apply/idP/idP => /(orbitPcycle 0 2). Qed. Lemma fconnect_findex x y : fconnect f x y -> y != x -> findex x y = (findex (f x) y).+1. Proof. rewrite /findex fconnect_orbit /orbit -orderSpred /= inE => /orP [-> //|]. rewrite eq_sym; move=> yin /negPf->; have [_ eq_o|_ ->//] := orderPcycle x. by rewrite -(orderSpred (f x)) trajectSr -cats1 index_cat -eq_o yin. Qed. End fconnect. End Orbit. #[global] Hint Resolve in_orbit mem_orbit order_gt0 orbit_uniq : core. Prenex Implicits order orbit findex finv order_set. Arguments orbitPcycle {T f x}. Arguments same_fconnect_finv [T f]. Section FconnectId. Variable T : finType. Lemma fconnect_id (x : T) : fconnect id x =1 xpred1 x. Proof. by move=> y; rewrite (@fconnect_cycle _ _ [:: x]) //= ?inE ?eqxx. Qed. Lemma order_id (x : T) : order id x = 1. Proof. by rewrite /order (eq_card (fconnect_id x)) card1. Qed. Lemma orbit_id (x : T) : orbit id x = [:: x]. Proof. by rewrite /orbit order_id. Qed. Lemma froots_id (x : T) : froots id x. Proof. by rewrite /roots -fconnect_id connect_root. Qed. Lemma froot_id (x : T) : froot id x = x. Proof. by apply/eqP; apply: froots_id. Qed. Lemma fcard_id (a : {pred T}) : fcard id a = #|a|. Proof. by apply: eq_card => x; rewrite inE froots_id. Qed. End FconnectId. Section FconnectEq. Variables (T : finType) (f f' : T -> T). Lemma finv_eq_can : cancel f f' -> finv f =1 f'. Proof. move=> fK; have inj_f := can_inj fK. by apply: bij_can_eq fK; [apply: injF_bij | apply: finv_f]. Qed. Hypothesis eq_f : f =1 f'. Let eq_rf := eq_frel eq_f. Lemma eq_fconnect : fconnect f =2 fconnect f'. Proof. exact: eq_connect eq_rf. Qed. Lemma eq_fcard : fcard_mem f =1 fcard_mem f'. Proof. exact: eq_n_comp eq_fconnect. Qed. Lemma eq_finv : finv f =1 finv f'. Proof. by move=> x; rewrite /finv /order (eq_card (@eq_fconnect x)) (eq_iter eq_f). Qed. Lemma eq_froot : froot f =1 froot f'. Proof. exact: eq_root eq_rf. Qed. Lemma eq_froots : froots f =1 froots f'. Proof. exact: eq_roots eq_rf. Qed. End FconnectEq. Arguments eq_fconnect [T f f']. Section FinvEq. Variables (T : finType) (f : T -> T). Hypothesis injf : injective f. Lemma finv_inv : finv (finv f) =1 f. Proof. exact: (finv_eq_can (f_finv injf)). Qed. Lemma order_finv : order (finv f) =1 order f. Proof. by move=> x; apply: eq_card (@same_fconnect_finv _ _ injf x). Qed. Lemma order_set_finv n : order_set (finv f) n =i order_set f n. Proof. by move=> x; rewrite !inE order_finv. Qed. End FinvEq. Section RelAdjunction. Variables (T T' : finType) (h : T' -> T) (e : rel T) (e' : rel T'). Hypotheses (sym_e : connect_sym e) (sym_e' : connect_sym e'). Record rel_adjunction_mem m_a := RelAdjunction { rel_unit x : in_mem x m_a -> {x' : T' | connect e x (h x')}; rel_functor x' y' : in_mem (h x') m_a -> connect e' x' y' = connect e (h x') (h y') }. Variable a : {pred T}. Hypothesis cl_a : closed e a. Local Notation rel_adjunction := (rel_adjunction_mem (mem a)). Lemma intro_adjunction (h' : forall x, x \in a -> T') : (forall x a_x, [/\ connect e x (h (h' x a_x)) & forall y a_y, e x y -> connect e' (h' x a_x) (h' y a_y)]) -> (forall x' a_x, [/\ connect e' x' (h' (h x') a_x) & forall y', e' x' y' -> connect e (h x') (h y')]) -> rel_adjunction. Proof. move=> Aee' Ae'e; split=> [y a_y | x' z' a_x]. by exists (h' y a_y); case/Aee': (a_y). apply/idP/idP=> [/connectP[p e'p ->{z'}] | /connectP[p e_p p_z']]. elim: p x' a_x e'p => //= y' p IHp x' a_x. case: (Ae'e x' a_x) => _ Ae'x /andP[/Ae'x e_xy /IHp e_yz] {Ae'x}. by apply: connect_trans (e_yz _); rewrite // -(closed_connect cl_a e_xy). case: (Ae'e x' a_x) => /connect_trans-> //. elim: p {x'}(h x') p_z' a_x e_p => /= [|y p IHp] x p_z' a_x. by rewrite -p_z' in a_x *; case: (Ae'e _ a_x); rewrite sym_e'. case/andP=> e_xy /(IHp _ p_z') e'yz; have a_y: y \in a by rewrite -(cl_a e_xy). by apply: connect_trans (e'yz a_y); case: (Aee' _ a_x) => _ ->. Qed. Lemma strict_adjunction : injective h -> a \subset codom h -> rel_base h e e' [predC a] -> rel_adjunction. Proof. move=> /= injh h_a a_ee'; pose h' x Hx := iinv (subsetP h_a x Hx). apply: (@intro_adjunction h') => [x a_x | x' a_x]. rewrite f_iinv connect0; split=> // y a_y e_xy. by rewrite connect1 // -a_ee' !f_iinv ?negbK. rewrite [h' _ _]iinv_f //; split=> // y' e'xy. by rewrite connect1 // a_ee' ?negbK. Qed. Let ccl_a := closed_connect cl_a. Lemma adjunction_closed : rel_adjunction -> closed e' [preim h of a]. Proof. case=> _ Ae'e; apply: intro_closed => // x' y' /connect1 e'xy a_x. by rewrite Ae'e // in e'xy; rewrite !inE -(ccl_a e'xy). Qed. Lemma adjunction_n_comp : rel_adjunction -> n_comp e a = n_comp e' [preim h of a]. Proof. case=> Aee' Ae'e. have inj_h: {in predI (roots e') [preim h of a] &, injective (root e \o h)}. move=> x' y' /andP[/eqP r_x' /= a_x'] /andP[/eqP r_y' _] /(rootP sym_e). by rewrite -Ae'e // => /(rootP sym_e'); rewrite r_x' r_y'. rewrite /n_comp_mem -(card_in_image inj_h); apply: eq_card => x. apply/andP/imageP=> [[/eqP rx a_x] | [x' /andP[/eqP r_x' a_x'] ->]]; last first. by rewrite /= -(ccl_a (connect_root _ _)) roots_root. have [y' e_xy]:= Aee' x a_x; pose x' := root e' y'. have ay': h y' \in a by rewrite -(ccl_a e_xy). have e_yx: connect e (h y') (h x') by rewrite -Ae'e ?connect_root. exists x'; first by rewrite inE /= -(ccl_a e_yx) ?roots_root. by rewrite /= -(rootP sym_e e_yx) -(rootP sym_e e_xy). Qed. End RelAdjunction. Notation rel_adjunction h e e' a := (rel_adjunction_mem h e e' (mem a)). Notation "@ 'rel_adjunction' T T' h e e' a" := (@rel_adjunction_mem T T' h e e' (mem a)) (at level 10, T, T', h, e, e', a at level 8, only parsing) : type_scope. Notation fun_adjunction h f f' a := (rel_adjunction h (frel f) (frel f') a). Notation "@ 'fun_adjunction' T T' h f f' a" := (@rel_adjunction T T' h (frel f) (frel f') a) (at level 10, T, T', h, f, f', a at level 8, only parsing) : type_scope. Arguments intro_adjunction [T T' h e e'] _ [a]. Arguments adjunction_n_comp [T T'] h [e e'] _ _ [a]. Unset Implicit Arguments.
Lattice.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kyle Miller -/ import Mathlib.Data.Finite.Sigma import Mathlib.Data.Set.Finite.Powerset import Mathlib.Data.Set.Finite.Range /-! # Finiteness of unions and intersections ## Implementation notes Each result in this file should come in three forms: a `Fintype` instance, a `Finite` instance and a `Set.Finite` constructor. ## Tags finite sets -/ assert_not_exists OrderedRing MonoidWithZero open Set Function universe u v w x variable {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace Set /-! ### Fintype instances Every instance here should have a corresponding `Set.Finite` constructor in the next section. -/ section FintypeInstances instance fintypeiUnion [DecidableEq α] [Fintype (PLift ι)] (f : ι → Set α) [∀ i, Fintype (f i)] : Fintype (⋃ i, f i) := Fintype.ofFinset (Finset.univ.biUnion fun i : PLift ι => (f i.down).toFinset) <| by simp instance fintypesUnion [DecidableEq α] {s : Set (Set α)} [Fintype s] [H : ∀ t : s, Fintype (t : Set α)] : Fintype (⋃₀ s) := by rw [sUnion_eq_iUnion] exact @Set.fintypeiUnion _ _ _ _ _ H lemma toFinset_iUnion [Fintype β] [DecidableEq α] (f : β → Set α) [∀ w, Fintype (f w)] : Set.toFinset (⋃ (x : β), f x) = Finset.biUnion (Finset.univ : Finset β) (fun x => (f x).toFinset) := by ext v simp only [mem_toFinset, mem_iUnion, Finset.mem_biUnion, Finset.mem_univ, true_and] /-- A union of sets with `Fintype` structure over a set with `Fintype` structure has a `Fintype` structure. -/ def fintypeBiUnion [DecidableEq α] {ι : Type*} (s : Set ι) [Fintype s] (t : ι → Set α) (H : ∀ i ∈ s, Fintype (t i)) : Fintype (⋃ x ∈ s, t x) := haveI : ∀ i : toFinset s, Fintype (t i) := fun i => H i (mem_toFinset.1 i.2) Fintype.ofFinset (s.toFinset.attach.biUnion fun x => (t x).toFinset) fun x => by simp instance fintypeBiUnion' [DecidableEq α] {ι : Type*} (s : Set ι) [Fintype s] (t : ι → Set α) [∀ i, Fintype (t i)] : Fintype (⋃ x ∈ s, t x) := Fintype.ofFinset (s.toFinset.biUnion fun x => (t x).toFinset) <| by simp 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_iUnion [Finite ι] (f : ι → Set α) [∀ i, Finite (f i)] : Finite (⋃ i, f i) := by rw [iUnion_eq_range_psigma] apply Set.finite_range instance finite_sUnion {s : Set (Set α)} [Finite s] [H : ∀ t : s, Finite (t : Set α)] : Finite (⋃₀ s) := by rw [sUnion_eq_iUnion] exact @Finite.Set.finite_iUnion _ _ _ _ H theorem finite_biUnion {ι : Type*} (s : Set ι) [Finite s] (t : ι → Set α) (H : ∀ i ∈ s, Finite (t i)) : Finite (⋃ x ∈ s, t x) := by rw [biUnion_eq_iUnion] haveI : ∀ i : s, Finite (t i) := fun i => H i i.property infer_instance instance finite_biUnion' {ι : Type*} (s : Set ι) [Finite s] (t : ι → Set α) [∀ i, Finite (t i)] : Finite (⋃ x ∈ s, t x) := finite_biUnion s t fun _ _ => inferInstance /-- Example: `Finite (⋃ (i < n), f i)` where `f : ℕ → Set α` and `[∀ i, Finite (f i)]` (when given instances from `Order.Interval.Finset.Nat`). -/ instance finite_biUnion'' {ι : Type*} (p : ι → Prop) [h : Finite { x | p x }] (t : ι → Set α) [∀ i, Finite (t i)] : Finite (⋃ (x) (_ : p x), t x) := @Finite.Set.finite_biUnion' _ _ (setOf p) h t _ instance finite_iInter {ι : Sort*} [Nonempty ι] (t : ι → Set α) [∀ i, Finite (t i)] : Finite (⋂ i, t i) := Finite.Set.subset (t <| Classical.arbitrary ι) (iInter_subset _ _) 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 theorem finite_iUnion [Finite ι] {f : ι → Set α} (H : ∀ i, (f i).Finite) : (⋃ i, f i).Finite := haveI := fun i => (H i).to_subtype toFinite _ /-- Dependent version of `Finite.biUnion`. -/ theorem Finite.biUnion' {ι} {s : Set ι} (hs : s.Finite) {t : ∀ i ∈ s, Set α} (ht : ∀ i (hi : i ∈ s), (t i hi).Finite) : (⋃ i ∈ s, t i ‹_›).Finite := by have := hs.to_subtype rw [biUnion_eq_iUnion] apply finite_iUnion fun i : s => ht i.1 i.2 theorem Finite.biUnion {ι} {s : Set ι} (hs : s.Finite) {t : ι → Set α} (ht : ∀ i ∈ s, (t i).Finite) : (⋃ i ∈ s, t i).Finite := hs.biUnion' ht theorem Finite.sUnion {s : Set (Set α)} (hs : s.Finite) (H : ∀ t ∈ s, Set.Finite t) : (⋃₀ s).Finite := by simpa only [sUnion_eq_biUnion] using hs.biUnion H theorem Finite.sInter {α : Type*} {s : Set (Set α)} {t : Set α} (ht : t ∈ s) (hf : t.Finite) : (⋂₀ s).Finite := hf.subset (sInter_subset_of_mem ht) /-- If sets `s i` are finite for all `i` from a finite set `t` and are empty for `i ∉ t`, then the union `⋃ i, s i` is a finite set. -/ theorem Finite.iUnion {ι : Type*} {s : ι → Set α} {t : Set ι} (ht : t.Finite) (hs : ∀ i ∈ t, (s i).Finite) (he : ∀ i, i ∉ t → s i = ∅) : (⋃ i, s i).Finite := by suffices ⋃ i, s i ⊆ ⋃ i ∈ t, s i by exact (ht.biUnion hs).subset this refine iUnion_subset fun i x hx => ?_ by_cases hi : i ∈ t · exact mem_biUnion hi hx · rw [he i hi, mem_empty_iff_false] at hx contradiction /-- An indexed union of pairwise disjoint sets is finite iff all sets are finite, and all but finitely many are empty. -/ lemma finite_iUnion_iff {ι : Type*} {s : ι → Set α} (hs : Pairwise fun i j ↦ Disjoint (s i) (s j)) : (⋃ i, s i).Finite ↔ (∀ i, (s i).Finite) ∧ {i | (s i).Nonempty}.Finite where mp h := by refine ⟨fun i ↦ h.subset <| subset_iUnion _ _, ?_⟩ let u (i : {i | (s i).Nonempty}) : ⋃ i, s i := ⟨i.2.choose, mem_iUnion.2 ⟨i.1, i.2.choose_spec⟩⟩ have u_inj : Function.Injective u := by rintro ⟨i, hi⟩ ⟨j, hj⟩ hij ext refine hs.eq <| not_disjoint_iff.2 ⟨u ⟨i, hi⟩, hi.choose_spec, ?_⟩ rw [hij] exact hj.choose_spec have : Finite (⋃ i, s i) := h exact .of_injective u u_inj mpr h := h.2.iUnion (fun _ _ ↦ h.1 _) (by simp [not_nonempty_iff_eq_empty]) protected lemma Infinite.iUnion {ι : Sort*} {s : ι → Set α} (i : ι) (hi : (s i).Infinite) : (⋃ i, s i).Infinite := fun h ↦ hi (h.subset (Set.subset_iUnion s i)) lemma Infinite.iUnion₂ {ι : Sort*} {κ : ι → Sort*} {s : ∀ i, κ i → Set α} (i : ι) (j : κ i) (hij : (s i j).Infinite) : (⋃ (i) (j), s i j).Infinite := fun hc ↦ hij (hc.subset <| subset_iUnion₂ _ _) @[simp] lemma finite_iUnion_of_subsingleton {ι : Sort*} [Subsingleton ι] {s : ι → Set α} : (⋃ i, s i).Finite ↔ ∀ i, (s i).Finite := by rw [← iUnion_plift_down, finite_iUnion_iff _root_.Subsingleton.pairwise] simp [PLift.forall, Finite.of_subsingleton] /-- An indexed union of pairwise disjoint sets is finite iff all sets are finite, and all but finitely many are empty. -/ lemma PairwiseDisjoint.finite_biUnion_iff {f : β → Set α} {s : Set β} (hs : s.PairwiseDisjoint f) : (⋃ i ∈ s, f i).Finite ↔ (∀ i ∈ s, (f i).Finite) ∧ {i ∈ s | (f i).Nonempty}.Finite := by rw [finite_iUnion_iff (by aesop (add unfold safe [Pairwise, PairwiseDisjoint, Set.Pairwise]))] simp section preimage variable {f : α → β} {s : Set β} theorem Finite.preimage' (h : s.Finite) (hf : ∀ b ∈ s, (f ⁻¹' {b}).Finite) : (f ⁻¹' s).Finite := by rw [← Set.biUnion_preimage_singleton] exact Set.Finite.biUnion h hf end preimage /-- A finite union of finsets is finite. -/ theorem union_finset_finite_of_range_finite (f : α → Finset β) (h : (range f).Finite) : (⋃ a, (f a : Set β)).Finite := by rw [← biUnion_range] exact h.biUnion fun y _ => y.finite_toSet end SetFiniteConstructors /-- If the image of `s` under `f` is finite, and each fiber of `f` has a finite intersection with `s`, then `s` is itself finite. It is useful to give `f` explicitly here so this can be used with `apply`. -/ lemma Finite.of_finite_fibers (f : α → β) {s : Set α} (himage : (f '' s).Finite) (hfibers : ∀ x ∈ f '' s, (s ∩ f ⁻¹' {x}).Finite) : s.Finite := (himage.biUnion hfibers).subset fun x ↦ by aesop /-! ### Properties -/ theorem finite_subset_iUnion {s : Set α} (hs : s.Finite) {ι} {t : ι → Set α} (h : s ⊆ ⋃ i, t i) : ∃ I : Set ι, I.Finite ∧ s ⊆ ⋃ i ∈ I, t i := by have := hs.to_subtype choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i by simpa [subset_def] using h refine ⟨range f, finite_range f, fun x hx => ?_⟩ rw [biUnion_range, mem_iUnion] exact ⟨⟨x, hx⟩, hf _⟩ theorem eq_finite_iUnion_of_finite_subset_iUnion {ι} {s : ι → Set α} {t : Set α} (tfin : t.Finite) (h : t ⊆ ⋃ i, s i) : ∃ I : Set ι, I.Finite ∧ ∃ σ : { i | i ∈ I } → Set α, (∀ i, (σ i).Finite) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_iUnion tfin h ⟨I, Ifin, fun x => s x ∩ t, fun _ => tfin.subset inter_subset_right, fun _ => inter_subset_left, by ext x rw [mem_iUnion] constructor · intro x_in rcases mem_iUnion.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩ exact ⟨⟨i, hi⟩, ⟨H, x_in⟩⟩ · rintro ⟨i, -, H⟩ exact H⟩ /-! ### Infinite sets -/ variable {s t : Set α} theorem infinite_iUnion {ι : Type*} [Infinite ι] {s : ι → Set α} (hs : Function.Injective s) : (⋃ i, s i).Infinite := fun hfin ↦ @not_injective_infinite_finite ι _ _ hfin.finite_subsets.to_subtype (fun i ↦ ⟨s i, subset_iUnion _ _⟩) fun i j h_eq ↦ hs (by simpa using h_eq) theorem Infinite.biUnion {ι : Type*} {s : ι → Set α} {a : Set ι} (ha : a.Infinite) (hs : a.InjOn s) : (⋃ i ∈ a, s i).Infinite := by rw [biUnion_eq_iUnion] have _ := ha.to_subtype exact infinite_iUnion fun ⟨i,hi⟩ ⟨j,hj⟩ hij ↦ by simp [hs hi hj hij] theorem Infinite.sUnion {s : Set (Set α)} (hs : s.Infinite) : (⋃₀ s).Infinite := by rw [sUnion_eq_iUnion] have _ := hs.to_subtype exact infinite_iUnion Subtype.coe_injective /-! ### Order properties -/ lemma map_finite_biSup {F ι : Type*} [CompleteLattice α] [CompleteLattice β] [FunLike F α β] [SupBotHomClass F α β] {s : Set ι} (hs : s.Finite) (f : F) (g : ι → α) : f (⨆ x ∈ s, g x) = ⨆ x ∈ s, f (g x) := by have := map_finset_sup f hs.toFinset g simp only [Finset.sup_eq_iSup, hs.mem_toFinset, comp_apply] at this exact this lemma map_finite_biInf {F ι : Type*} [CompleteLattice α] [CompleteLattice β] [FunLike F α β] [InfTopHomClass F α β] {s : Set ι} (hs : s.Finite) (f : F) (g : ι → α) : f (⨅ x ∈ s, g x) = ⨅ x ∈ s, f (g x) := by have := map_finset_inf f hs.toFinset g simp only [Finset.inf_eq_iInf, hs.mem_toFinset, comp_apply] at this exact this lemma map_finite_iSup {F ι : Type*} [CompleteLattice α] [CompleteLattice β] [FunLike F α β] [SupBotHomClass F α β] [Finite ι] (f : F) (g : ι → α) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [← iSup_univ (f := g), ← iSup_univ (f := fun i ↦ f (g i))] exact map_finite_biSup finite_univ f g lemma map_finite_iInf {F ι : Type*} [CompleteLattice α] [CompleteLattice β] [FunLike F α β] [InfTopHomClass F α β] [Finite ι] (f : F) (g : ι → α) : f (⨅ i, g i) = ⨅ i, f (g i) := by rw [← iInf_univ (f := g), ← iInf_univ (f := fun i ↦ f (g i))] exact map_finite_biInf finite_univ f g theorem Finite.iSup_biInf_of_monotone {ι ι' α : Type*} [Preorder ι'] [Nonempty ι'] [IsDirected ι' (· ≤ ·)] [Order.Frame α] {s : Set ι} (hs : s.Finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, Monotone (f i)) : ⨆ j, ⨅ i ∈ s, f i j = ⨅ i ∈ s, ⨆ j, f i j := by induction s, hs using Set.Finite.induction_on with | empty => simp [iSup_const] | insert _ _ ihs => rw [forall_mem_insert] at hf simp only [iInf_insert, ← ihs hf.2] exact iSup_inf_of_monotone hf.1 fun j₁ j₂ hj => iInf₂_mono fun i hi => hf.2 i hi hj theorem Finite.iSup_biInf_of_antitone {ι ι' α : Type*} [Preorder ι'] [Nonempty ι'] [IsDirected ι' (swap (· ≤ ·))] [Order.Frame α] {s : Set ι} (hs : s.Finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, Antitone (f i)) : ⨆ j, ⨅ i ∈ s, f i j = ⨅ i ∈ s, ⨆ j, f i j := @Finite.iSup_biInf_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ hs _ fun i hi => (hf i hi).dual_left theorem Finite.iInf_biSup_of_monotone {ι ι' α : Type*} [Preorder ι'] [Nonempty ι'] [IsDirected ι' (swap (· ≤ ·))] [Order.Coframe α] {s : Set ι} (hs : s.Finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, Monotone (f i)) : ⨅ j, ⨆ i ∈ s, f i j = ⨆ i ∈ s, ⨅ j, f i j := hs.iSup_biInf_of_antitone (α := αᵒᵈ) fun i hi => (hf i hi).dual_right theorem Finite.iInf_biSup_of_antitone {ι ι' α : Type*} [Preorder ι'] [Nonempty ι'] [IsDirected ι' (· ≤ ·)] [Order.Coframe α] {s : Set ι} (hs : s.Finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, Antitone (f i)) : ⨅ j, ⨆ i ∈ s, f i j = ⨆ i ∈ s, ⨅ j, f i j := hs.iSup_biInf_of_monotone (α := αᵒᵈ) fun i hi => (hf i hi).dual_right theorem iSup_iInf_of_monotone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [Nonempty ι'] [IsDirected ι' (· ≤ ·)] [Order.Frame α] {f : ι → ι' → α} (hf : ∀ i, Monotone (f i)) : ⨆ j, ⨅ i, f i j = ⨅ i, ⨆ j, f i j := by simpa only [iInf_univ] using finite_univ.iSup_biInf_of_monotone fun i _ => hf i theorem iSup_iInf_of_antitone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [Nonempty ι'] [IsDirected ι' (swap (· ≤ ·))] [Order.Frame α] {f : ι → ι' → α} (hf : ∀ i, Antitone (f i)) : ⨆ j, ⨅ i, f i j = ⨅ i, ⨆ j, f i j := @iSup_iInf_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ _ fun i => (hf i).dual_left theorem iInf_iSup_of_monotone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [Nonempty ι'] [IsDirected ι' (swap (· ≤ ·))] [Order.Coframe α] {f : ι → ι' → α} (hf : ∀ i, Monotone (f i)) : ⨅ j, ⨆ i, f i j = ⨆ i, ⨅ j, f i j := iSup_iInf_of_antitone (α := αᵒᵈ) fun i => (hf i).dual_right theorem iInf_iSup_of_antitone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [Nonempty ι'] [IsDirected ι' (· ≤ ·)] [Order.Coframe α] {f : ι → ι' → α} (hf : ∀ i, Antitone (f i)) : ⨅ j, ⨆ i, f i j = ⨆ i, ⨅ j, f i j := iSup_iInf_of_monotone (α := αᵒᵈ) fun i => (hf i).dual_right /-- An increasing union distributes over finite intersection. -/ theorem iUnion_iInter_of_monotone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [IsDirected ι' (· ≤ ·)] [Nonempty ι'] {s : ι → ι' → Set α} (hs : ∀ i, Monotone (s i)) : ⋃ j : ι', ⋂ i : ι, s i j = ⋂ i : ι, ⋃ j : ι', s i j := iSup_iInf_of_monotone hs /-- A decreasing union distributes over finite intersection. -/ theorem iUnion_iInter_of_antitone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [IsDirected ι' (swap (· ≤ ·))] [Nonempty ι'] {s : ι → ι' → Set α} (hs : ∀ i, Antitone (s i)) : ⋃ j : ι', ⋂ i : ι, s i j = ⋂ i : ι, ⋃ j : ι', s i j := iSup_iInf_of_antitone hs /-- An increasing intersection distributes over finite union. -/ theorem iInter_iUnion_of_monotone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [IsDirected ι' (swap (· ≤ ·))] [Nonempty ι'] {s : ι → ι' → Set α} (hs : ∀ i, Monotone (s i)) : ⋂ j : ι', ⋃ i : ι, s i j = ⋃ i : ι, ⋂ j : ι', s i j := iInf_iSup_of_monotone hs /-- A decreasing intersection distributes over finite union. -/ theorem iInter_iUnion_of_antitone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [IsDirected ι' (· ≤ ·)] [Nonempty ι'] {s : ι → ι' → Set α} (hs : ∀ i, Antitone (s i)) : ⋂ j : ι', ⋃ i : ι, s i j = ⋃ i : ι, ⋂ j : ι', s i j := iInf_iSup_of_antitone hs theorem iUnion_pi_of_monotone {ι ι' : Type*} [LinearOrder ι'] [Nonempty ι'] {α : ι → Type*} {I : Set ι} {s : ∀ i, ι' → Set (α i)} (hI : I.Finite) (hs : ∀ i ∈ I, Monotone (s i)) : ⋃ j : ι', I.pi (fun i => s i j) = I.pi fun i => ⋃ j, s i j := by simp only [pi_def, biInter_eq_iInter, preimage_iUnion] haveI := hI.fintype.finite refine iUnion_iInter_of_monotone (ι' := ι') (fun (i : I) j₁ j₂ h => ?_) exact preimage_mono <| hs i i.2 h theorem iUnion_univ_pi_of_monotone {ι ι' : Type*} [LinearOrder ι'] [Nonempty ι'] [Finite ι] {α : ι → Type*} {s : ∀ i, ι' → Set (α i)} (hs : ∀ i, Monotone (s i)) : ⋃ j : ι', pi univ (fun i => s i j) = pi univ fun i => ⋃ j, s i j := iUnion_pi_of_monotone finite_univ fun i _ => hs i section variable [Preorder α] [IsDirected α (· ≤ ·)] [Nonempty α] {s : Set α} /-- A finite set is bounded above. -/ protected theorem Finite.bddAbove (hs : s.Finite) : BddAbove s := Finite.induction_on _ hs bddAbove_empty fun _ _ h => h.insert _ /-- A finite union of sets which are all bounded above is still bounded above. -/ theorem Finite.bddAbove_biUnion {I : Set β} {S : β → Set α} (H : I.Finite) : BddAbove (⋃ i ∈ I, S i) ↔ ∀ i ∈ I, BddAbove (S i) := by induction I, H using Set.Finite.induction_on with | empty => simp only [biUnion_empty, bddAbove_empty, forall_mem_empty] | insert _ _ hs => simp only [biUnion_insert, forall_mem_insert, bddAbove_union, hs] theorem infinite_of_not_bddAbove : ¬BddAbove s → s.Infinite := mt Finite.bddAbove end section variable [Preorder α] [IsDirected α (· ≥ ·)] [Nonempty α] {s : Set α} /-- A finite set is bounded below. -/ protected theorem Finite.bddBelow (hs : s.Finite) : BddBelow s := Finite.bddAbove (α := αᵒᵈ) hs /-- A finite union of sets which are all bounded below is still bounded below. -/ theorem Finite.bddBelow_biUnion {I : Set β} {S : β → Set α} (H : I.Finite) : BddBelow (⋃ i ∈ I, S i) ↔ ∀ i ∈ I, BddBelow (S i) := Finite.bddAbove_biUnion (α := αᵒᵈ) H theorem infinite_of_not_bddBelow : ¬BddBelow s → s.Infinite := mt Finite.bddBelow end end Set namespace Finset /-- A finset is bounded above. -/ protected theorem bddAbove [SemilatticeSup α] [Nonempty α] (s : Finset α) : BddAbove (↑s : Set α) := s.finite_toSet.bddAbove /-- A finset is bounded below. -/ protected theorem bddBelow [SemilatticeInf α] [Nonempty α] (s : Finset α) : BddBelow (↑s : Set α) := s.finite_toSet.bddBelow end Finset section LinearOrder variable [LinearOrder α] {s : Set α} lemma Set.finite_diff_iUnion_Ioo (s : Set α) : (s \ ⋃ (x ∈ s) (y ∈ s), Ioo x y).Finite := Set.finite_of_forall_not_lt_lt fun _x hx _y hy _z hz hxy hyz => hy.2 <| mem_iUnion₂_of_mem hx.1 <| mem_iUnion₂_of_mem hz.1 ⟨hxy, hyz⟩ lemma Set.finite_diff_iUnion_Ioo' (s : Set α) : (s \ ⋃ x : s × s, Ioo x.1 x.2).Finite := by simpa only [iUnion, iSup_prod, iSup_subtype] using s.finite_diff_iUnion_Ioo lemma Directed.exists_mem_subset_of_finset_subset_biUnion {α ι : Type*} [Nonempty ι] {f : ι → Set α} (h : Directed (· ⊆ ·) f) {s : Finset α} (hs : (s : Set α) ⊆ ⋃ i, f i) : ∃ i, (s : Set α) ⊆ f i := by induction s using Finset.cons_induction with | empty => simp | cons b t hbt iht => simp only [Finset.coe_cons, Set.insert_subset_iff, Set.mem_iUnion] at hs ⊢ rcases hs.imp_right iht with ⟨⟨i, hi⟩, j, hj⟩ rcases h i j with ⟨k, hik, hjk⟩ exact ⟨k, hik hi, hj.trans hjk⟩ theorem DirectedOn.exists_mem_subset_of_finset_subset_biUnion {α ι : Type*} {f : ι → Set α} {c : Set ι} (hn : c.Nonempty) (hc : DirectedOn (fun i j => f i ⊆ f j) c) {s : Finset α} (hs : (s : Set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : Set α) ⊆ f i := by rw [Set.biUnion_eq_iUnion] at hs haveI := hn.coe_sort simpa using (directed_comp.2 hc.directed_val).exists_mem_subset_of_finset_subset_biUnion hs theorem DirectedOn.exists_mem_subset_of_finite_of_subset_sUnion {α : Type*} {c : Set (Set α)} (hn : c.Nonempty) (hc : DirectedOn (· ⊆ ·) c) {s : Set α} (hs : s.Finite) (hsc : s ⊆ sUnion c) : ∃ t ∈ c, s ⊆ t := by rw [← hs.coe_toFinset, sUnion_eq_biUnion] at hsc have := DirectedOn.exists_mem_subset_of_finset_subset_biUnion hn hc hsc exact hs.coe_toFinset ▸ this end LinearOrder
Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import Mathlib.Algebra.Module.Equiv.Basic import Mathlib.GroupTheory.QuotientGroup.Basic import Mathlib.LinearAlgebra.Pi import Mathlib.LinearAlgebra.Quotient.Defs import Mathlib.LinearAlgebra.Span.Basic /-! # Quotients by submodules * If `p` is a submodule of `M`, `M ⧸ p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. ## Main definitions * `Submodule.Quotient.restrictScalarsEquiv`: The quotient of `P` as an `S`-submodule is the same as the quotient of `P` as an `R`-submodule, * `Submodule.liftQ`: lift a map `M → M₂` to a map `M ⧸ p → M₂` if the kernel is contained in `p` * `Submodule.mapQ`: lift a map `M → M₂` to a map `M ⧸ p → M₂ ⧸ q` if the image of `p` is contained in `q` -/ assert_not_exists Cardinal -- For most of this file we work over a noncommutative ring section Ring namespace Submodule variable {R M : Type*} {r : R} {x y : M} [Ring R] [AddCommGroup M] [Module R M] variable (p p' p'' : Submodule R M) open LinearMap QuotientAddGroup namespace Quotient section Module variable (S : Type*) /-- The quotient of `P` as an `S`-submodule is the same as the quotient of `P` as an `R`-submodule, where `P : Submodule R M`. -/ def restrictScalarsEquiv [Ring S] [SMul S R] [Module S M] [IsScalarTower S R M] (P : Submodule R M) : (M ⧸ P.restrictScalars S) ≃ₗ[S] M ⧸ P := { Quotient.congrRight fun _ _ => Iff.rfl with map_add' := fun x y => Quotient.inductionOn₂' x y fun _x' _y' => rfl map_smul' := fun _c x => Submodule.Quotient.induction_on _ x fun _x' => rfl } @[simp] theorem restrictScalarsEquiv_mk [Ring S] [SMul S R] [Module S M] [IsScalarTower S R M] (P : Submodule R M) (x : M) : restrictScalarsEquiv S P (mk x) = mk x := rfl @[simp] theorem restrictScalarsEquiv_symm_mk [Ring S] [SMul S R] [Module S M] [IsScalarTower S R M] (P : Submodule R M) (x : M) : (restrictScalarsEquiv S P).symm (mk x) = mk x := rfl end Module theorem nontrivial_of_lt_top (h : p < ⊤) : Nontrivial (M ⧸ p) := by obtain ⟨x, _, notMem_s⟩ := SetLike.exists_of_lt h refine ⟨⟨mk x, 0, ?_⟩⟩ simpa using notMem_s end Quotient instance QuotientBot.infinite [Infinite M] : Infinite (M ⧸ (⊥ : Submodule R M)) := Infinite.of_injective Submodule.Quotient.mk fun _x _y h => sub_eq_zero.mp <| (Submodule.Quotient.eq ⊥).mp h instance QuotientTop.unique : Unique (M ⧸ (⊤ : Submodule R M)) where default := 0 uniq x := Submodule.Quotient.induction_on _ x fun _x => (Submodule.Quotient.eq ⊤).mpr Submodule.mem_top instance QuotientTop.fintype : Fintype (M ⧸ (⊤ : Submodule R M)) := Fintype.ofSubsingleton 0 variable {p} theorem subsingleton_quotient_iff_eq_top : Subsingleton (M ⧸ p) ↔ p = ⊤ := by constructor · rintro h refine eq_top_iff.mpr fun x _ => ?_ have : x - 0 ∈ p := (Submodule.Quotient.eq p).mp (Subsingleton.elim _ _) rwa [sub_zero] at this · rintro rfl infer_instance theorem unique_quotient_iff_eq_top : Nonempty (Unique (M ⧸ p)) ↔ p = ⊤ := ⟨fun ⟨h⟩ => subsingleton_quotient_iff_eq_top.mp (@Unique.instSubsingleton _ h), by rintro rfl; exact ⟨QuotientTop.unique⟩⟩ variable (p) noncomputable instance Quotient.fintype [Fintype M] (S : Submodule R M) : Fintype (M ⧸ S) := @_root_.Quotient.fintype _ _ _ fun _ _ => Classical.dec _ section variable {M₂ : Type*} [AddCommGroup M₂] [Module R M₂] theorem strictMono_comap_prod_map : StrictMono fun m : Submodule R M ↦ (m.comap p.subtype, m.map p.mkQ) := fun m₁ m₂ ↦ QuotientAddGroup.strictMono_comap_prod_map p.toAddSubgroup (a := m₁.toAddSubgroup) (b := m₂.toAddSubgroup) end variable {R₂ M₂ : Type*} [Ring R₂] [AddCommGroup M₂] [Module R₂ M₂] {τ₁₂ : R →+* R₂} /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftQ (f : M →ₛₗ[τ₁₂] M₂) (h : p ≤ ker f) : M ⧸ p →ₛₗ[τ₁₂] M₂ := { QuotientAddGroup.lift p.toAddSubgroup f.toAddMonoidHom h with map_smul' := by rintro a ⟨x⟩; exact f.map_smulₛₗ a x } @[simp] theorem liftQ_apply (f : M →ₛₗ[τ₁₂] M₂) {h} (x : M) : p.liftQ f h (Quotient.mk x) = f x := rfl @[simp] theorem liftQ_mkQ (f : M →ₛₗ[τ₁₂] M₂) (h) : (p.liftQ f h).comp p.mkQ = f := by ext; rfl theorem pi_liftQ_eq_liftQ_pi {ι : Type*} {N : ι → Type*} [∀ i, AddCommGroup (N i)] [∀ i, Module R (N i)] (f : (i : ι) → M →ₗ[R] (N i)) {p : Submodule R M} (h : ∀ i, p ≤ ker (f i)) : LinearMap.pi (fun i ↦ p.liftQ (f i) (h i)) = p.liftQ (LinearMap.pi f) (LinearMap.ker_pi f ▸ le_iInf h) := by ext x i simp /-- Special case of `submodule.liftQ` when `p` is the span of `x`. In this case, the condition on `f` simply becomes vanishing at `x`. -/ def liftQSpanSingleton (x : M) (f : M →ₛₗ[τ₁₂] M₂) (h : f x = 0) : (M ⧸ R ∙ x) →ₛₗ[τ₁₂] M₂ := (R ∙ x).liftQ f <| by rw [span_singleton_le_iff_mem, LinearMap.mem_ker, h] @[simp] theorem liftQSpanSingleton_apply (x : M) (f : M →ₛₗ[τ₁₂] M₂) (h : f x = 0) (y : M) : liftQSpanSingleton x f h (Quotient.mk y) = f y := rfl @[simp] theorem range_mkQ : range p.mkQ = ⊤ := eq_top_iff'.2 <| by rintro ⟨x⟩; exact ⟨x, rfl⟩ @[simp] theorem ker_mkQ : ker p.mkQ = p := by ext; simp theorem le_comap_mkQ (p' : Submodule R (M ⧸ p)) : p ≤ comap p.mkQ p' := by simpa using (comap_mono bot_le : ker p.mkQ ≤ comap p.mkQ p') @[simp] theorem mkQ_map_self : map p.mkQ p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkQ] @[simp] theorem comap_map_mkQ : comap p.mkQ (map p.mkQ p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkQ_eq_top : map p.mkQ p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [LinearMap.map_eq_top_iff p.range_mkQ, sup_comm, ker_mkQ] variable (q : Submodule R₂ M₂) /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapQ (f : M →ₛₗ[τ₁₂] M₂) (h : p ≤ comap f q) : M ⧸ p →ₛₗ[τ₁₂] M₂ ⧸ q := p.liftQ (q.mkQ.comp f) <| by simpa [ker_comp] using h @[simp] theorem mapQ_apply (f : M →ₛₗ[τ₁₂] M₂) {h} (x : M) : mapQ p q f h (Quotient.mk x) = Quotient.mk (f x) := rfl theorem mapQ_mkQ (f : M →ₛₗ[τ₁₂] M₂) {h} : (mapQ p q f h).comp p.mkQ = q.mkQ.comp f := by ext x; rfl @[simp] theorem mapQ_zero (h : p ≤ q.comap (0 : M →ₛₗ[τ₁₂] M₂) := (by simp)) : p.mapQ q (0 : M →ₛₗ[τ₁₂] M₂) h = 0 := by ext simp /-- Given submodules `p ⊆ M`, `p₂ ⊆ M₂`, `p₃ ⊆ M₃` and maps `f : M → M₂`, `g : M₂ → M₃` inducing `mapQ f : M ⧸ p → M₂ ⧸ p₂` and `mapQ g : M₂ ⧸ p₂ → M₃ ⧸ p₃` then `mapQ (g ∘ f) = (mapQ g) ∘ (mapQ f)`. -/ theorem mapQ_comp {R₃ M₃ : Type*} [Ring R₃] [AddCommGroup M₃] [Module R₃ M₃] (p₂ : Submodule R₂ M₂) (p₃ : Submodule R₃ M₃) {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} [RingHomCompTriple τ₁₂ τ₂₃ τ₁₃] (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) (hf : p ≤ p₂.comap f) (hg : p₂ ≤ p₃.comap g) (h := hf.trans (comap_mono hg)) : p.mapQ p₃ (g.comp f) h = (p₂.mapQ p₃ g hg).comp (p.mapQ p₂ f hf) := by ext simp @[simp] theorem mapQ_id (h : p ≤ p.comap LinearMap.id := (by rw [comap_id])) : p.mapQ p LinearMap.id h = LinearMap.id := by ext simp theorem mapQ_pow {f : M →ₗ[R] M} (h : p ≤ p.comap f) (k : ℕ) (h' : p ≤ p.comap (f ^ k) := p.le_comap_pow_of_le_comap h k) : p.mapQ p (f ^ k) h' = p.mapQ p f h ^ k := by induction k with | zero => simp [Module.End.one_eq_id] | succ k ih => simp only [Module.End.iterate_succ] rw [mapQ_comp, ih] theorem comap_liftQ (f : M →ₛₗ[τ₁₂] M₂) (h) : q.comap (p.liftQ f h) = (q.comap f).map (mkQ p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftQ_mkQ]) theorem map_liftQ [RingHomSurjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (h) (q : Submodule R (M ⧸ p)) : q.map (p.liftQ f h) = (q.comap p.mkQ).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨Quotient.mk x, hxq, rfl⟩) theorem ker_liftQ (f : M →ₛₗ[τ₁₂] M₂) (h) : ker (p.liftQ f h) = (ker f).map (mkQ p) := comap_liftQ _ _ _ _ theorem range_liftQ [RingHomSurjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (h) : range (p.liftQ f h) = range f := by simpa only [range_eq_map] using map_liftQ _ _ _ _ theorem ker_liftQ_eq_bot (f : M →ₛₗ[τ₁₂] M₂) (h) (h' : ker f ≤ p) : ker (p.liftQ f h) = ⊥ := by rw [ker_liftQ, le_antisymm h h', mkQ_map_self] theorem ker_liftQ_eq_bot' (f : M →ₛₗ[τ₁₂] M₂) (h : p = ker f) : ker (p.liftQ f (le_of_eq h)) = ⊥ := ker_liftQ_eq_bot p f h.le h.ge section variable {p p' p''} /-- The linear map from the quotient by a smaller submodule to the quotient by a larger submodule. This is the `Submodule.Quotient` version of `Quot.Factor` When the two submodules are of the form `I ^ m • ⊤` and `I ^ n • ⊤` and `n ≤ m`, please refer to the dedicated version `Submodule.factorPow`. -/ abbrev factor (H : p ≤ p') : M ⧸ p →ₗ[R] M ⧸ p' := mapQ _ _ LinearMap.id H @[simp] theorem factor_mk (H : p ≤ p') (x : M) : factor H (mkQ p x) = mkQ p' x := rfl @[simp] theorem factor_comp_mk (H : p ≤ p') : (factor H).comp (mkQ p) = mkQ p' := by ext x rw [LinearMap.comp_apply, factor_mk] @[simp] theorem factor_comp (H1 : p ≤ p') (H2 : p' ≤ p'') : (factor H2).comp (factor H1) = factor (H1.trans H2) := by ext simp @[simp] theorem factor_comp_apply (H1 : p ≤ p') (H2 : p' ≤ p'') (x : M ⧸ p) : factor H2 (factor H1 x) = factor (H1.trans H2) x := by rw [← comp_apply] simp lemma factor_surjective (H : p ≤ p') : Function.Surjective (factor H) := by intro x use Quotient.mk x.out exact Quotient.out_eq x end /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comapMkQRelIso : Submodule R (M ⧸ p) ≃o Set.Ici p where toFun p' := ⟨comap p.mkQ p', le_comap_mkQ p _⟩ invFun q := map p.mkQ q left_inv p' := map_comap_eq_self <| by simp right_inv := fun ⟨q, hq⟩ => Subtype.ext_val <| by simpa [comap_map_mkQ p] map_rel_iff' := comap_le_comap_iff <| range_mkQ _ /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comapMkQOrderEmbedding : Submodule R (M ⧸ p) ↪o Submodule R M := (RelIso.toRelEmbedding <| comapMkQRelIso p).trans (Subtype.relEmbedding (· ≤ ·) _) @[simp] theorem comapMkQOrderEmbedding_eq (p' : Submodule R (M ⧸ p)) : comapMkQOrderEmbedding p p' = comap p.mkQ p' := rfl theorem span_preimage_eq [RingHomSurjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {s : Set M₂} (h₀ : s.Nonempty) (h₁ : s ⊆ range f) : span R (f ⁻¹' s) = (span R₂ s).comap f := by suffices (span R₂ s).comap f ≤ span R (f ⁻¹' s) by exact le_antisymm (span_preimage_le f s) this have hk : ker f ≤ span R (f ⁻¹' s) := by let y := Classical.choose h₀ have hy : y ∈ s := Classical.choose_spec h₀ rw [ker_le_iff] use y, h₁ hy rw [← Set.singleton_subset_iff] at hy exact Set.Subset.trans subset_span (span_mono (Set.preimage_mono hy)) rw [← left_eq_sup] at hk rw [range_coe f] at h₁ rw [hk, ← LinearMap.map_le_map_iff, map_span, map_comap_eq, Set.image_preimage_eq_of_subset h₁] exact inf_le_right /-- If `P` is a submodule of `M` and `Q` a submodule of `N`, and `f : M ≃ₗ N` maps `P` to `Q`, then `M ⧸ P` is equivalent to `N ⧸ Q`. -/ @[simps] def Quotient.equiv {N : Type*} [AddCommGroup N] [Module R N] (P : Submodule R M) (Q : Submodule R N) (f : M ≃ₗ[R] N) (hf : P.map f = Q) : (M ⧸ P) ≃ₗ[R] N ⧸ Q := { P.mapQ Q (f : M →ₗ[R] N) fun _ hx => hf ▸ Submodule.mem_map_of_mem hx with toFun := P.mapQ Q (f : M →ₗ[R] N) fun _ hx => hf ▸ Submodule.mem_map_of_mem hx invFun := Q.mapQ P (f.symm : N →ₗ[R] M) fun x hx => by rw [← hf, Submodule.mem_map] at hx obtain ⟨y, hy, rfl⟩ := hx simpa left_inv := fun x => Submodule.Quotient.induction_on _ x (by simp) right_inv := fun x => Submodule.Quotient.induction_on _ x (by simp) } @[simp] theorem Quotient.equiv_symm {R M N : Type*} [Ring R] [AddCommGroup M] [Module R M] [AddCommGroup N] [Module R N] (P : Submodule R M) (Q : Submodule R N) (f : M ≃ₗ[R] N) (hf : P.map f = Q) : (Quotient.equiv P Q f hf).symm = Quotient.equiv Q P f.symm ((Submodule.map_symm_eq_iff f).mpr hf) := rfl @[simp] theorem Quotient.equiv_trans {N O : Type*} [AddCommGroup N] [Module R N] [AddCommGroup O] [Module R O] (P : Submodule R M) (Q : Submodule R N) (S : Submodule R O) (e : M ≃ₗ[R] N) (f : N ≃ₗ[R] O) (he : P.map e = Q) (hf : Q.map f = S) (hef : P.map (e.trans f) = S) : Quotient.equiv P S (e.trans f) hef = (Quotient.equiv P Q e he).trans (Quotient.equiv Q S f hf) := by ext -- `simp` can deal with `hef` depending on `e` and `f` simp only [Quotient.equiv_apply, LinearEquiv.trans_apply, LinearEquiv.coe_trans] -- `rw` can deal with `mapQ_comp` needing extra hypotheses coming from the RHS rw [mapQ_comp, LinearMap.comp_apply] end Submodule open Submodule namespace LinearMap section Ring variable {R M R₂ M₂ R₃ M₃ : Type*} variable [Ring R] [Ring R₂] [Ring R₃] variable [AddCommMonoid M] [AddCommGroup M₂] [AddCommMonoid M₃] variable [Module R M] [Module R₂ M₂] [Module R₃ M₃] variable {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variable [RingHomCompTriple τ₁₂ τ₂₃ τ₁₃] [RingHomSurjective τ₁₂] theorem range_mkQ_comp (f : M →ₛₗ[τ₁₂] M₂) : (range f).mkQ.comp f = 0 := LinearMap.ext fun x => by simp theorem ker_le_range_iff {f : M →ₛₗ[τ₁₂] M₂} {g : M₂ →ₛₗ[τ₂₃] M₃} : ker g ≤ range f ↔ (range f).mkQ.comp (ker g).subtype = 0 := by rw [← range_le_ker_iff, Submodule.ker_mkQ, Submodule.range_subtype] /-- An epimorphism is surjective. -/ theorem range_eq_top_of_cancel {f : M →ₛₗ[τ₁₂] M₂} (h : ∀ u v : M₂ →ₗ[R₂] M₂ ⧸ (range f), u.comp f = v.comp f → u = v) : range f = ⊤ := by have h₁ : (0 : M₂ →ₗ[R₂] M₂ ⧸ (range f)).comp f = 0 := zero_comp _ rw [← Submodule.ker_mkQ (range f), ← h 0 (range f).mkQ (Eq.trans h₁ (range_mkQ_comp _).symm)] exact ker_zero end Ring end LinearMap open LinearMap namespace Submodule variable {R M : Type*} {r : R} {x y : M} [Ring R] [AddCommGroup M] [Module R M] variable (p p' : Submodule R M) /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quotEquivOfEqBot (hp : p = ⊥) : (M ⧸ p) ≃ₗ[R] M := LinearEquiv.ofLinear (p.liftQ id <| hp.symm ▸ bot_le) p.mkQ (liftQ_mkQ _ _ _) <| p.quot_hom_ext _ LinearMap.id fun _ => rfl @[simp] theorem quotEquivOfEqBot_apply_mk (hp : p = ⊥) (x : M) : p.quotEquivOfEqBot hp (Quotient.mk x) = x := rfl @[simp] theorem quotEquivOfEqBot_symm_apply (hp : p = ⊥) (x : M) : (p.quotEquivOfEqBot hp).symm x = (Quotient.mk x) := rfl @[simp] theorem coe_quotEquivOfEqBot_symm (hp : p = ⊥) : ((p.quotEquivOfEqBot hp).symm : M →ₗ[R] M ⧸ p) = p.mkQ := rfl @[simp] theorem Quotient.equiv_refl (P : Submodule R M) (Q : Submodule R M) (hf : P.map (LinearEquiv.refl R M : M →ₗ[R] M) = Q) : Quotient.equiv P Q (LinearEquiv.refl R M) hf = quotEquivOfEq _ _ (by simpa using hf) := rfl end Submodule end Ring section CommRing variable {R M M₂ : Type*} {r : R} {x y : M} [CommRing R] [AddCommGroup M] [Module R M] [AddCommGroup M₂] [Module R M₂] (p : Submodule R M) (q : Submodule R M₂) namespace Submodule /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapQLinear : compatibleMaps p q →ₗ[R] M ⧸ p →ₗ[R] M₂ ⧸ q where toFun f := mapQ _ _ f.val f.property map_add' x y := by ext rfl map_smul' c f := by ext rfl end Submodule end CommRing
depRewrite.lean
import Mathlib.Tactic.DepRewrite /-! ## Basic tests for `rewrite!`. -/ private axiom test_sorry : ∀ {α}, α /-- Turn a term into a sort for testing. -/ private axiom P.{u} {α : Sort u} : α → Prop /-- Non-deprecated copy of `Fin.ofNat` for testing. -/ private def finOfNat (n : Nat) (a : Nat) : Fin (n + 1) := ⟨a % (n+1), Nat.mod_lt _ (Nat.zero_lt_succ _)⟩ open Lean Elab Term in /-- Produce the annotation ``.mdata .. e`` for testing. -/ elab "mdata% " e:term : term => do let e ← elabTerm e none return .mdata ({ : MData}.insert `abc "def") e open Lean Elab Meta Term in /-- Produce the projection ``.proj `Prod 0 e`` for testing. Standard elaborators may represent projections as ordinary functions instead. -/ elab "fst% " e:term : term => do let u ← mkFreshLevelMVar let v ← mkFreshLevelMVar let α ← mkFreshExprMVar (some <| .sort u) let β ← mkFreshExprMVar (some <| .sort v) let tp := mkApp2 (.const ``Prod [u, v]) α β let e ← elabTerm e tp return .proj ``Prod 0 e /-! ## Tests for proof-only mode. -/ variable {n m : Nat} (eq : n = m) -- Rewrite a term annotated with `mdata`. example (f : (k : Nat) → 0 < k → Type) (lt : 0 < n) : P (mdata% f n lt) := by rewrite! [eq] guard_target =ₐ P (mdata% f m (eq ▸ lt)) exact test_sorry -- Rewrite the function in an application into a non-function. example (any : (α : Type) → α) (eq : (Nat → Nat) = Bool) : P (any (Nat → Nat) 0) := by rewrite! [eq] guard_target =ₐ P ((eq.symm ▸ any Bool) 0) exact test_sorry -- Rewrite the argument in an application. example (f : (k : Nat) → Fin k → Type) (lt : 0 < n) : P (f n ⟨0, lt⟩) := by rewrite! [eq] guard_target =ₐ P (f m ⟨0, eq ▸ lt⟩) exact test_sorry -- Rewrite the structure in a projection. example (lt : 0 < n) : P (fst% ((⟨0, lt⟩, ()) : Fin n × Unit)) := by rewrite! [eq] guard_target =ₐ P (fst% ((⟨0, eq ▸ lt⟩, ()) : Fin m × Unit)) exact test_sorry private def prod (α : Type) := α × Nat -- Ensure projection structures are detected modulo reduction. example (tup : (α : Type) → α → prod Nat) : P (fst% tup Nat n) := by rewrite! [eq] guard_target =ₐ P (fst% tup Nat m) exact test_sorry -- Rewrite the structure in a projection into a non-projectible structure. example (any : (α : Type) → α) (eq : (Nat × Nat) = Nat) : P (fst% any (Nat × Nat)) := by rewrite! [eq] guard_target =ₐ P (fst% (Eq.rec (motive := fun T _ => T) (any Nat) eq.symm)) exact test_sorry -- Rewrite the value of a dependent let-binding. example (lt : 0 < n) : let A : Type := Fin n P (@id A ⟨0, lt⟩) := by rewrite! [eq] guard_target =ₐ let A := Fin m P (@id A ⟨0, eq ▸ lt⟩) exact test_sorry -- Rewrite the type of a nondependent let-binding. example (lt : 0 < n) : let +nondep x : Fin n := ⟨0, lt⟩ P (@id (Fin n) x) := by rewrite! [eq] guard_target =ₐ let +nondep x : Fin m := ⟨0, eq ▸ lt⟩ P (@id (Fin m) x) exact test_sorry -- Rewrite the type of a let-binding whose value is a proof. example (lt' : 0 < n) : P (have lt : 0 < n := lt'; @Fin.mk n 0 (@id (0 < n) lt)) := by rewrite! [eq] guard_target =ₐ P <| have lt : 0 < m := eq ▸ lt' @Fin.mk m 0 (@id (0 < m) lt) exact test_sorry -- Rewrite in the argument type of a function. example : P fun (y : Fin n) => y := by rewrite! [eq] guard_target =ₐ P fun (y : Fin m) => y exact test_sorry -- Rewrite in a function with a proof argument. example : P fun (lt : 0 < n) => @Fin.mk n 0 (@id (0 < n) lt) := by rewrite! [eq] guard_target =ₐ P fun (lt : 0 < m) => @Fin.mk m 0 (@id (0 < m) lt) exact test_sorry -- Rewrite in a quantifier. example : P (forall (lt : 0 < n), @Eq (Fin n) ⟨0, lt⟩ ⟨0, lt⟩) := by rewrite! [eq] guard_target =ₐ P (forall (lt : 0 < m), @Eq (Fin m) ⟨0, lt⟩ ⟨0, lt⟩) exact test_sorry -- Attempt to cast a non-proof in proof-only cast mode. /-- error: Will not cast y in cast mode 'proofs'. If inserting more casts is acceptable, use `rw! (castMode := .all)`. -/ #guard_msgs in example (Q : Fin n → Prop) (q : (x : Fin n) → Q x) : P fun y : Fin n => q y := by rewrite! [eq] exact test_sorry -- Attempt to cast a non-proof in proof-only cast mode. /-- error: Will not cast ⟨0, ⋯⟩ in cast mode 'proofs'. If inserting more casts is acceptable, use `rw! (castMode := .all)`. -/ #guard_msgs in example (f : (k : Nat) → Fin k → Type) (lt : 0 < n) : P (f n ⟨0, lt⟩) := by conv in Fin.mk .. => rewrite! [eq] exact test_sorry -- Ensure we traverse proof terms (ordinary `rw` succeeds here). example (R : (n : Nat) → Prop) (Q : Prop) (r : (n : Nat) → R n) (q : (n : Nat) → R n → Q) (t : Q → Prop) : t (q n (r n)) := by rewrite! [eq] guard_target =ₐ t (q m (r m)) exact test_sorry -- Rewrite a more complex term (not just an fvar). variable {foo : Nat → Nat} {bar : Nat → Nat} (eq : foo n = bar m) in example (f : (k : Nat) → Fin k → Type) (lt : 0 < foo n) : P (f (foo n) ⟨0, lt⟩) := by rewrite! [eq] guard_target =ₐ P (f (bar m) ⟨0, eq ▸ lt⟩) exact test_sorry /-! ## Tests for all-casts mode. -/ variable (B : Nat → Type) -- Rewrite the arguments to a polymorphic function. example (f : (k : Nat) → B k → Nat) (b : B n) : P (f n b) := by rewrite! (castMode := .all) [eq] guard_target =ₐ P (f m (eq ▸ b)) exact test_sorry -- Rewrite the argument to a monomorphic function. example (f : B n → Nat) (b : (k : Nat) → B k) : P (f (b n)) := by rewrite! (castMode := .all) [eq] guard_target =ₐ P (f (eq ▸ b m)) exact test_sorry -- Rewrite a type-valued lambda. example (f : B n → Nat) : P fun y : B n => f y := by rewrite! (castMode := .all) [eq] guard_target =ₐ P fun y : B m => f (eq ▸ y) exact test_sorry -- Rewrite in contravariant position in a higher-order application. example (F : (f : Fin n → Nat) → Nat) : P (F fun y : Fin n => y.1) := by rewrite! (castMode := .all) [eq] guard_target =ₐ P (F (eq ▸ fun y : Fin m => y.1)) exact test_sorry -- Rewrite in covariant position in a higher-order application. example (F : (f : Nat → Fin (n+1)) → Nat) : P (F fun k : Nat => finOfNat n k) := by rewrite! (castMode := .all) [eq] guard_target =ₐ P (F (eq ▸ fun k : Nat => finOfNat m k)) exact test_sorry -- Rewrite in invariant position in a higher-order application. example (b : (k : Nat) → B k) (F : (f : (k : Fin n) → B k.1) → Nat) : P (F fun k : Fin n => b k.1) := by rewrite! (castMode := .all) [eq] guard_target =ₐ P (F (eq ▸ fun k : Fin m => b k.1)) exact test_sorry -- Attempt to rewrite with an LHS that does not appear in the target, -- but does appear in types of the target's subterms. /-- error: Tactic `depRewrite` failed: did not find instance of the pattern in the target expression n n m : Nat eq : n = m B : Nat → Type f : B n → Nat b : B n ⊢ f b = f b -/ #guard_msgs in example (f : B n → Nat) (b : B n) : f b = f b := by rewrite! [eq] exact test_sorry -- Test casting twice (from the LHS to `x` and back). theorem bool_dep_test (b : Bool) (β : Bool → Sort u) (f : ∀ b, β (b && false)) (h : false = b) : @P (β false) (f false) := by rewrite! (castMode := .all) [h] guard_target = @P (β b) (h.rec (motive := fun x _ => β x) <| h.symm.rec (motive := fun x _ => β (x && false)) <| f b) exact test_sorry -- Rewrite a `let` binding that requires generalization. theorem let_defeq_test (b : Nat) (eq : 1 = b) (f : (n : Nat) → n = 1 → Nat) : let n := 1; P (f n rfl) := by rewrite! [eq] guard_target = let n := b; P (f n _) exact test_sorry -- Test definitional equalities that get broken by rewriting. example (b : Bool) (h : true = b) (s : Bool → Prop) (q : (c : Bool) → s c → Prop) (f : (h : s (true || !false)) → q true h → Bool) : ∀ (i : s (true || true)) (u : q (true || !true) i), s (f i u) := by rewrite! [h] guard_target = ∀ (i : s (b || b)) (u : q (b || !b) _), s (f _ _) exact test_sorry -- As above. example (b : Bool) (h : true = b) (s : Bool → Prop) (q : (c : Bool) → s c → Prop) (f : (h : s (true || !false)) → q true h → Bool) (j : (h : s (true || false)) → (i : q (!false) h) → (k : f h i = true) → False) : ∀ (i : s (true || true)) (u : q (true || !true) i) (k : f i u = true), False.elim.{1} (j i u k) := by rewrite! [h] guard_target = ∀ (i : s (b || b)) (u : q (b || !b) _) (k : f _ _ = b), False.elim.{1} _ exact test_sorry -- As above. example (b : Bool) (h : true = b) (s : Bool → Prop) (q : (c : Bool) → s c → Prop) (f : (h : s (true || !false)) → q true h → Bool) (j : (c : Bool) → (h : s (true || c)) → (i : q (!false) h) → (k : f h i = !c) → False) : ∀ (i : s (true || true)) (u : q (true || !true) i) (k : f i u = true), False.elim.{1} (j (!true) i u k) := by rewrite! [h] guard_target = ∀ (i : s (b || b)) (u : q (b || !b) _) (k : f _ _ = b), False.elim.{1} _ exact test_sorry -- Rewrite in nested lets whose values and types depend on prior lets. #guard_msgs in example (F : Nat → Type) (G : (n : Nat) → F n → Type) (r : (n : Nat) → (f : F n) → G n f → Nat) (f : F n) (g : G n f) : P <| let a : Nat := n let B : Type := G a f let c : B := g let c' : G n f := g r n f c = r n f c' := by rewrite! (castMode := .all) [eq] exact test_sorry /-! ## Tests for `occs` -/ -- Test `.pos`. example (f : Nat → Nat → Nat) : P (f (id n) (id n)) := by rewrite! (occs := .pos [1]) [eq] guard_target =ₐ P (f (id m) (id n)) exact test_sorry -- Test `.neg`. example (f : Nat → Nat → Nat) : P (f (id n) (id n)) := by rewrite! (occs := .neg [1]) [eq] guard_target =ₐ P (f (id n) (id m)) exact test_sorry
Uniform.lean
/- Copyright (c) 2024 Josha Dekker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Josha Dekker, Devon Tuma, Kexing Ying -/ import Mathlib.Probability.Notation import Mathlib.Probability.Density import Mathlib.Probability.ConditionalProbability import Mathlib.Probability.ProbabilityMassFunction.Constructions /-! # Uniform distributions and probability mass functions This file defines two related notions of uniform distributions, which will be unified in the future. # Uniform distributions Defines the uniform distribution for any set with finite measure. ## Main definitions * `IsUniform X s ℙ μ` : A random variable `X` has uniform distribution on `s` under `ℙ` if the push-forward measure agrees with the rescaled restricted measure `μ`. # Uniform probability mass functions This file defines a number of uniform `PMF` distributions from various inputs, uniformly drawing from the corresponding object. ## Main definitions `PMF.uniformOfFinset` gives each element in the set equal probability, with `0` probability for elements not in the set. `PMF.uniformOfFintype` gives all elements equal probability, equal to the inverse of the size of the `Fintype`. `PMF.ofMultiset` draws randomly from the given `Multiset`, treating duplicate values as distinct. Each probability is given by the count of the element divided by the size of the `Multiset` ## TODO * Refactor the `PMF` definitions to come from a `uniformMeasure` on a `Finset`/`Fintype`/`Multiset`. -/ open scoped Finset MeasureTheory NNReal ENNReal -- TODO: We can't `open ProbabilityTheory` without opening the `ProbabilityTheory` locale :( open TopologicalSpace MeasureTheory.Measure PMF noncomputable section namespace MeasureTheory variable {E : Type*} [MeasurableSpace E] {μ : Measure E} namespace pdf variable {Ω : Type*} variable {_ : MeasurableSpace Ω} {ℙ : Measure Ω} /-- A random variable `X` has uniform distribution on `s` if its push-forward measure is `(μ s)⁻¹ • μ.restrict s`. -/ def IsUniform (X : Ω → E) (s : Set E) (ℙ : Measure Ω) (μ : Measure E := by volume_tac) := map X ℙ = ProbabilityTheory.cond μ s namespace IsUniform theorem aemeasurable {X : Ω → E} {s : Set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hu : IsUniform X s ℙ μ) : AEMeasurable X ℙ := by dsimp [IsUniform, ProbabilityTheory.cond] at hu by_contra h rw [map_of_not_aemeasurable h] at hu apply zero_ne_one' ℝ≥0∞ calc 0 = (0 : Measure E) Set.univ := rfl _ = _ := by rw [hu, smul_apply, restrict_apply MeasurableSet.univ, Set.univ_inter, smul_eq_mul, ENNReal.inv_mul_cancel hns hnt] theorem absolutelyContinuous {X : Ω → E} {s : Set E} (hu : IsUniform X s ℙ μ) : map X ℙ ≪ μ := by rw [hu]; exact ProbabilityTheory.cond_absolutelyContinuous theorem measure_preimage {X : Ω → E} {s : Set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hu : IsUniform X s ℙ μ) {A : Set E} (hA : MeasurableSet A) : ℙ (X ⁻¹' A) = μ (s ∩ A) / μ s := by rwa [← map_apply_of_aemeasurable (hu.aemeasurable hns hnt) hA, hu, ProbabilityTheory.cond_apply', ENNReal.div_eq_inv_mul] theorem isProbabilityMeasure {X : Ω → E} {s : Set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hu : IsUniform X s ℙ μ) : IsProbabilityMeasure ℙ := ⟨by have : X ⁻¹' Set.univ = Set.univ := Set.preimage_univ rw [← this, hu.measure_preimage hns hnt MeasurableSet.univ, Set.inter_univ, ENNReal.div_self hns hnt]⟩ theorem toMeasurable_iff {X : Ω → E} {s : Set E} : IsUniform X (toMeasurable μ s) ℙ μ ↔ IsUniform X s ℙ μ := by unfold IsUniform rw [ProbabilityTheory.cond_toMeasurable_eq] protected theorem toMeasurable {X : Ω → E} {s : Set E} (hu : IsUniform X s ℙ μ) : IsUniform X (toMeasurable μ s) ℙ μ := by unfold IsUniform at * rwa [ProbabilityTheory.cond_toMeasurable_eq] theorem hasPDF {X : Ω → E} {s : Set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hu : IsUniform X s ℙ μ) : HasPDF X ℙ μ := by let t := toMeasurable μ s apply hasPDF_of_map_eq_withDensity (hu.aemeasurable hns hnt) (t.indicator ((μ t)⁻¹ • 1)) <| (measurable_one.aemeasurable.const_smul (μ t)⁻¹).indicator (measurableSet_toMeasurable μ s) rw [hu, withDensity_indicator (measurableSet_toMeasurable μ s), withDensity_smul _ measurable_one, withDensity_one, restrict_toMeasurable hnt, measure_toMeasurable, ProbabilityTheory.cond] theorem pdf_eq_zero_of_measure_eq_zero_or_top {X : Ω → E} {s : Set E} (hu : IsUniform X s ℙ μ) (hμs : μ s = 0 ∨ μ s = ∞) : pdf X ℙ μ =ᵐ[μ] 0 := by rcases hμs with H|H · simp only [IsUniform, ProbabilityTheory.cond, H, ENNReal.inv_zero, restrict_eq_zero.mpr H, smul_zero] at hu simp [pdf, hu] · simp only [IsUniform, ProbabilityTheory.cond, H, ENNReal.inv_top, zero_smul] at hu simp [pdf, hu] theorem pdf_eq {X : Ω → E} {s : Set E} (hms : MeasurableSet s) (hu : IsUniform X s ℙ μ) : pdf X ℙ μ =ᵐ[μ] s.indicator ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) := by by_cases hnt : μ s = ∞ · simp [pdf_eq_zero_of_measure_eq_zero_or_top hu (Or.inr hnt), hnt] by_cases hns : μ s = 0 · filter_upwards [measure_zero_iff_ae_notMem.mp hns, pdf_eq_zero_of_measure_eq_zero_or_top hu (Or.inl hns)] with x hx h'x simp [hx, h'x, hns] have : HasPDF X ℙ μ := hasPDF hns hnt hu have : IsProbabilityMeasure ℙ := isProbabilityMeasure hns hnt hu apply (eq_of_map_eq_withDensity _ _).mp · rw [hu, withDensity_indicator hms, withDensity_smul _ measurable_one, withDensity_one, ProbabilityTheory.cond] · exact (measurable_one.aemeasurable.const_smul (μ s)⁻¹).indicator hms theorem pdf_toReal_ae_eq {X : Ω → E} {s : Set E} (hms : MeasurableSet s) (hX : IsUniform X s ℙ μ) : (fun x => (pdf X ℙ μ x).toReal) =ᵐ[μ] fun x => (s.indicator ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) x).toReal := Filter.EventuallyEq.fun_comp (pdf_eq hms hX) ENNReal.toReal variable {X : Ω → ℝ} {s : Set ℝ} theorem mul_pdf_integrable (hcs : IsCompact s) (huX : IsUniform X s ℙ) : Integrable fun x : ℝ => x * (pdf X ℙ volume x).toReal := by by_cases hnt : volume s = 0 ∨ volume s = ∞ · have I : Integrable (fun x ↦ x * ENNReal.toReal (0)) := by simp apply I.congr filter_upwards [pdf_eq_zero_of_measure_eq_zero_or_top huX hnt] with x hx simp [hx] simp only [not_or] at hnt have : IsProbabilityMeasure ℙ := isProbabilityMeasure hnt.1 hnt.2 huX constructor · exact aestronglyMeasurable_id.mul (measurable_pdf X ℙ).aemeasurable.ennreal_toReal.aestronglyMeasurable refine hasFiniteIntegral_mul (pdf_eq hcs.measurableSet huX) ?_ set ind := (volume s)⁻¹ • (1 : ℝ → ℝ≥0∞) have : ∀ x, ‖x‖ₑ * s.indicator ind x = s.indicator (fun x => ‖x‖ₑ * ind x) x := fun x => (s.indicator_mul_right (fun x => ↑‖x‖₊) ind).symm simp only [ind, this, lintegral_indicator hcs.measurableSet, mul_one, Algebra.id.smul_eq_mul, Pi.one_apply, Pi.smul_apply] rw [lintegral_mul_const _ measurable_enorm] exact ENNReal.mul_ne_top (setLIntegral_lt_top_of_isCompact hnt.2 hcs continuous_nnnorm).ne (ENNReal.inv_lt_top.2 (pos_iff_ne_zero.mpr hnt.1)).ne /-- A real uniform random variable `X` with support `s` has expectation `(λ s)⁻¹ * ∫ x in s, x ∂λ` where `λ` is the Lebesgue measure. -/ theorem integral_eq (huX : IsUniform X s ℙ) : ∫ x, X x ∂ℙ = (volume s)⁻¹.toReal * ∫ x in s, x := by rw [← smul_eq_mul, ← integral_smul_measure] dsimp only [IsUniform, ProbabilityTheory.cond] at huX rw [← huX] by_cases hX : AEMeasurable X ℙ · exact (integral_map hX aestronglyMeasurable_id).symm · rw [map_of_not_aemeasurable hX, integral_zero_measure, integral_non_aestronglyMeasurable] rwa [aestronglyMeasurable_iff_aemeasurable] end IsUniform variable {X : Ω → E} lemma IsUniform.cond {s : Set E} : IsUniform (id : E → E) s (ProbabilityTheory.cond μ s) μ := by unfold IsUniform rw [Measure.map_id] /-- The density of the uniform measure on a set with respect to itself. This allows us to abstract away the choice of random variable and probability space. -/ def uniformPDF (s : Set E) (x : E) (μ : Measure E := by volume_tac) : ℝ≥0∞ := s.indicator ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) x /-- Check that indeed any uniform random variable has the uniformPDF. -/ lemma uniformPDF_eq_pdf {s : Set E} (hs : MeasurableSet s) (hu : pdf.IsUniform X s ℙ μ) : (fun x ↦ uniformPDF s x μ) =ᵐ[μ] pdf X ℙ μ := by unfold uniformPDF exact Filter.EventuallyEq.trans (pdf.IsUniform.pdf_eq hs hu).symm (ae_eq_refl _) open scoped Classical in /-- Alternative way of writing the uniformPDF. -/ lemma uniformPDF_ite {s : Set E} {x : E} : uniformPDF s x μ = if x ∈ s then (μ s)⁻¹ else 0 := by unfold uniformPDF unfold Set.indicator simp only [Pi.smul_apply, Pi.one_apply, smul_eq_mul, mul_one] end pdf end MeasureTheory namespace PMF variable {α : Type*} open scoped NNReal ENNReal section UniformOfFinset /-- Uniform distribution taking the same non-zero probability on the nonempty finset `s` -/ def uniformOfFinset (s : Finset α) (hs : s.Nonempty) : PMF α := by classical refine ofFinset (fun a => if a ∈ s then s.card⁻¹ else 0) s ?_ ?_ · simp only [Finset.sum_ite_mem, Finset.inter_self, Finset.sum_const, nsmul_eq_mul] have : (s.card : ℝ≥0∞) ≠ 0 := by simpa only [Ne, Nat.cast_eq_zero, Finset.card_eq_zero] using Finset.nonempty_iff_ne_empty.1 hs exact ENNReal.mul_inv_cancel this <| ENNReal.natCast_ne_top s.card · exact fun x hx => by simp only [hx, if_false] variable {s : Finset α} (hs : s.Nonempty) {a : α} open scoped Classical in @[simp] theorem uniformOfFinset_apply (a : α) : uniformOfFinset s hs a = if a ∈ s then (s.card : ℝ≥0∞)⁻¹ else 0 := rfl theorem uniformOfFinset_apply_of_mem (ha : a ∈ s) : uniformOfFinset s hs a = (s.card : ℝ≥0∞)⁻¹ := by simp [ha] theorem uniformOfFinset_apply_of_notMem (ha : a ∉ s) : uniformOfFinset s hs a = 0 := by simp [ha] @[deprecated (since := "2025-05-23")] alias uniformOfFinset_apply_of_not_mem := uniformOfFinset_apply_of_notMem @[simp] theorem support_uniformOfFinset : (uniformOfFinset s hs).support = s := Set.ext (by let ⟨a, ha⟩ := hs simp [mem_support_iff]) theorem mem_support_uniformOfFinset_iff (a : α) : a ∈ (uniformOfFinset s hs).support ↔ a ∈ s := by simp section Measure variable (t : Set α) open scoped Classical in @[simp] theorem toOuterMeasure_uniformOfFinset_apply : (uniformOfFinset s hs).toOuterMeasure t = #{x ∈ s | x ∈ t} / #s := calc (uniformOfFinset s hs).toOuterMeasure t = ∑' x, if x ∈ t then uniformOfFinset s hs x else 0 := toOuterMeasure_apply (uniformOfFinset s hs) t _ = ∑' x, if x ∈ s ∧ x ∈ t then (#s : ℝ≥0∞)⁻¹ else 0 := tsum_congr fun x => by simp_rw [uniformOfFinset_apply, ← ite_and, and_comm] _ = ∑ x ∈ s with x ∈ t, if x ∈ s ∧ x ∈ t then (#s : ℝ≥0∞)⁻¹ else 0 := tsum_eq_sum fun _ hx => if_neg fun h => hx (Finset.mem_filter.2 h) _ = ∑ x ∈ s with x ∈ t, (#s : ℝ≥0∞)⁻¹ := Finset.sum_congr rfl fun x hx => by have this : x ∈ s ∧ x ∈ t := by simpa using hx simp only [this, and_self_iff, if_true] _ = #{x ∈ s | x ∈ t} / #s := by simp only [div_eq_mul_inv, Finset.sum_const, nsmul_eq_mul] open scoped Classical in @[simp] theorem toMeasure_uniformOfFinset_apply [MeasurableSpace α] (ht : MeasurableSet t) : (uniformOfFinset s hs).toMeasure t = #{x ∈ s | x ∈ t} / #s := (toMeasure_apply_eq_toOuterMeasure_apply _ ht).trans (toOuterMeasure_uniformOfFinset_apply hs t) end Measure end UniformOfFinset section UniformOfFintype /-- The uniform pmf taking the same uniform value on all of the fintype `α` -/ def uniformOfFintype (α : Type*) [Fintype α] [Nonempty α] : PMF α := uniformOfFinset Finset.univ Finset.univ_nonempty variable [Fintype α] [Nonempty α] @[simp] theorem uniformOfFintype_apply (a : α) : uniformOfFintype α a = (Fintype.card α : ℝ≥0∞)⁻¹ := by simp [uniformOfFintype, Finset.mem_univ, uniformOfFinset_apply] @[simp] theorem support_uniformOfFintype (α : Type*) [Fintype α] [Nonempty α] : (uniformOfFintype α).support = ⊤ := Set.ext fun x => by simp [mem_support_iff] theorem mem_support_uniformOfFintype (a : α) : a ∈ (uniformOfFintype α).support := by simp section Measure variable (s : Set α) theorem toOuterMeasure_uniformOfFintype_apply [Fintype s] : (uniformOfFintype α).toOuterMeasure s = Fintype.card s / Fintype.card α := by classical rw [uniformOfFintype, toOuterMeasure_uniformOfFinset_apply, Fintype.card_subtype, Finset.card_univ] theorem toMeasure_uniformOfFintype_apply [MeasurableSpace α] (hs : MeasurableSet s) [Fintype s] : (uniformOfFintype α).toMeasure s = Fintype.card s / Fintype.card α := by classical simp [uniformOfFintype, Fintype.card_subtype, hs] end Measure end UniformOfFintype section OfMultiset open scoped Classical in /-- Given a non-empty multiset `s` we construct the `PMF` which sends `a` to the fraction of elements in `s` that are `a`. -/ def ofMultiset (s : Multiset α) (hs : s ≠ 0) : PMF α := ⟨fun a => s.count a / (Multiset.card s), ENNReal.summable.hasSum_iff.2 (calc (∑' b : α, (s.count b : ℝ≥0∞) / (Multiset.card s)) = (Multiset.card s : ℝ≥0∞)⁻¹ * ∑' b, (s.count b : ℝ≥0∞) := by simp_rw [ENNReal.div_eq_inv_mul, ENNReal.tsum_mul_left] _ = (Multiset.card s : ℝ≥0∞)⁻¹ * ∑ b ∈ s.toFinset, (s.count b : ℝ≥0∞) := (congr_arg (fun x => (Multiset.card s : ℝ≥0∞)⁻¹ * x) (tsum_eq_sum fun a ha => Nat.cast_eq_zero.2 <| by rwa [Multiset.count_eq_zero, ← Multiset.mem_toFinset])) _ = 1 := by rw [← Nat.cast_sum, Multiset.toFinset_sum_count_eq s, ENNReal.inv_mul_cancel (Nat.cast_ne_zero.2 (hs ∘ Multiset.card_eq_zero.1)) (ENNReal.natCast_ne_top _)] )⟩ variable {s : Multiset α} (hs : s ≠ 0) open scoped Classical in @[simp] theorem ofMultiset_apply (a : α) : ofMultiset s hs a = s.count a / (Multiset.card s) := rfl open scoped Classical in @[simp] theorem support_ofMultiset : (ofMultiset s hs).support = s.toFinset := Set.ext (by simp [mem_support_iff]) open scoped Classical in theorem mem_support_ofMultiset_iff (a : α) : a ∈ (ofMultiset s hs).support ↔ a ∈ s.toFinset := by simp theorem ofMultiset_apply_of_notMem {a : α} (ha : a ∉ s) : ofMultiset s hs a = 0 := by simpa only [ofMultiset_apply, ENNReal.div_eq_zero_iff, Nat.cast_eq_zero, Multiset.count_eq_zero, ENNReal.natCast_ne_top, or_false] using ha @[deprecated (since := "2025-05-23")] alias ofMultiset_apply_of_not_mem := ofMultiset_apply_of_notMem section Measure variable (t : Set α) open scoped Classical in @[simp] theorem toOuterMeasure_ofMultiset_apply : (ofMultiset s hs).toOuterMeasure t = (∑' x, (s.filter (· ∈ t)).count x : ℝ≥0∞) / (Multiset.card s) := by simp_rw [div_eq_mul_inv, ← ENNReal.tsum_mul_right, toOuterMeasure_apply] refine tsum_congr fun x => ?_ by_cases hx : x ∈ t <;> simp [Set.indicator, hx, div_eq_mul_inv] open scoped Classical in @[simp] theorem toMeasure_ofMultiset_apply [MeasurableSpace α] (ht : MeasurableSet t) : (ofMultiset s hs).toMeasure t = (∑' x, (s.filter (· ∈ t)).count x : ℝ≥0∞) / (Multiset.card s) := (toMeasure_apply_eq_toOuterMeasure_apply _ ht).trans (toOuterMeasure_ofMultiset_apply hs t) end Measure end OfMultiset end PMF
Finsupp.lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Aaron Anderson -/ import Mathlib.Data.Finsupp.Defs /-! # Pointwise order on finitely supported functions This file lifts order structures on `M` to `ι →₀ M`. -/ assert_not_exists CompleteLattice noncomputable section open Finset namespace Finsupp variable {ι M : Type*} [Zero M] section LE variable [LE M] {f g : ι →₀ M} instance instLE : LE (ι →₀ M) where le f g := ∀ i, f i ≤ g i lemma le_def : f ≤ g ↔ ∀ i, f i ≤ g i := .rfl @[simp, norm_cast] lemma coe_le_coe : ⇑f ≤ g ↔ f ≤ g := .rfl /-- The order on `Finsupp`s over a partial order embeds into the order on functions -/ @[simps] def orderEmbeddingToFun : (ι →₀ M) ↪o (ι → M) where toFun f := f inj' := DFunLike.coe_injective map_rel_iff' := coe_le_coe end LE section Preorder variable [Preorder M] {f g : ι →₀ M} {i : ι} {a b : M} instance preorder : Preorder (ι →₀ M) where le_refl _ _ := le_rfl le_trans _ _ _ hfg hgh i := (hfg i).trans (hgh i) lemma lt_def : f < g ↔ f ≤ g ∧ ∃ i, f i < g i := Pi.lt_def @[simp, norm_cast] lemma coe_lt_coe : ⇑f < g ↔ f < g := .rfl lemma coe_mono : Monotone (Finsupp.toFun : (ι →₀ M) → ι → M) := fun _ _ ↦ id lemma coe_strictMono : Monotone (Finsupp.toFun : (ι →₀ M) → ι → M) := fun _ _ ↦ id end Preorder instance partialorder [PartialOrder M] : PartialOrder (ι →₀ M) where le_antisymm _f _g hfg hgf := ext fun i ↦ (hfg i).antisymm (hgf i) section SemilatticeInf variable [SemilatticeInf M] instance semilatticeInf : SemilatticeInf (ι →₀ M) where inf := zipWith (· ⊓ ·) (inf_idem _) inf_le_left _f _g _i := inf_le_left inf_le_right _f _g _i := inf_le_right le_inf _f _g _i h1 h2 s := le_inf (h1 s) (h2 s) @[simp] lemma inf_apply (f g : ι →₀ M) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl end SemilatticeInf section SemilatticeSup variable [SemilatticeSup M] instance semilatticeSup : SemilatticeSup (ι →₀ M) where sup := zipWith (· ⊔ ·) (sup_idem _) le_sup_left _f _g _i := le_sup_left le_sup_right _f _g _i := le_sup_right sup_le _f _g _h hf hg i := sup_le (hf i) (hg i) @[simp] lemma sup_apply (f g : ι →₀ M) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl end SemilatticeSup section Lattice variable [Lattice M] (f g : ι →₀ M) instance lattice : Lattice (ι →₀ M) where __ := Finsupp.semilatticeInf __ := Finsupp.semilatticeSup variable [DecidableEq ι] lemma support_inf_union_support_sup : (f ⊓ g).support ∪ (f ⊔ g).support = f.support ∪ g.support := coe_injective <| compl_injective <| by ext; simp [inf_eq_and_sup_eq_iff] lemma support_sup_union_support_inf : (f ⊔ g).support ∪ (f ⊓ g).support = f.support ∪ g.support := (union_comm _ _).trans <| support_inf_union_support_sup _ _ end Lattice end Finsupp
Ideal.lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.Topology.Algebra.Ring.Basic import Mathlib.Topology.Algebra.Group.Quotient import Mathlib.RingTheory.Ideal.Quotient.Defs /-! # Ideals and quotients of topological rings In this file we define `Ideal.closure` to be the topological closure of an ideal in a topological ring. We also define a `TopologicalSpace` structure on the quotient of a topological ring by an ideal and prove that the quotient is a topological ring. -/ open Topology section Ring variable {R : Type*} [TopologicalSpace R] [Ring R] [IsTopologicalRing R] /-- The closure of an ideal in a topological ring as an ideal. -/ protected def Ideal.closure (I : Ideal R) : Ideal R := { AddSubmonoid.topologicalClosure I.toAddSubmonoid with carrier := closure I smul_mem' := fun c _ hx => map_mem_closure (mulLeft_continuous _) hx fun _ => I.mul_mem_left c } @[simp] theorem Ideal.coe_closure (I : Ideal R) : (I.closure : Set R) = closure I := rfl -- Porting note: removed `@[simp]` because we make the instance argument explicit since otherwise -- it causes timeouts as `simp` tries and fails to generated an `IsClosed` instance. -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/!4.234852.20heartbeats.20of.20the.20linter theorem Ideal.closure_eq_of_isClosed (I : Ideal R) (hI : IsClosed (I : Set R)) : I.closure = I := SetLike.ext' hI.closure_eq end Ring section CommRing variable {R : Type*} [TopologicalSpace R] [CommRing R] (N : Ideal R) open Ideal.Quotient instance topologicalRingQuotientTopology : TopologicalSpace (R ⧸ N) := instTopologicalSpaceQuotient -- note for the reader: in the following, `mk` is `Ideal.Quotient.mk`, the canonical map `R → R/I`. variable [IsTopologicalRing R] theorem QuotientRing.isOpenMap_coe : IsOpenMap (mk N) := QuotientAddGroup.isOpenMap_coe theorem QuotientRing.isOpenQuotientMap_mk : IsOpenQuotientMap (mk N) := QuotientAddGroup.isOpenQuotientMap_mk theorem QuotientRing.isQuotientMap_coe_coe : IsQuotientMap fun p : R × R => (mk N p.1, mk N p.2) := ((isOpenQuotientMap_mk N).prodMap (isOpenQuotientMap_mk N)).isQuotientMap instance topologicalRing_quotient : IsTopologicalRing (R ⧸ N) where __ := QuotientAddGroup.instIsTopologicalAddGroup _ continuous_mul := (QuotientRing.isQuotientMap_coe_coe N).continuous_iff.2 <| continuous_quot_mk.comp continuous_mul instance [CompactSpace R] : CompactSpace (R ⧸ N) := Quotient.compactSpace end CommRing
ssrnotations.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) (******************************************************************************) (* - Reserved notation for various arithmetic and algebraic operations: *) (* e.[a1, ..., a_n] evaluation (e.g., polynomials). *) (* e`_i indexing (number list, integer pi-part). *) (* x^-1 inverse (group, field). *) (* x *+ n, x *- n integer multiplier (modules and rings). *) (* x ^+ n, x ^- n integer exponent (groups and rings). *) (* x *: A, A :* x external product (scaling/module product in rings, *) (* left/right cosets in groups). *) (* A :&: B intersection (of sets, groups, subspaces, ...). *) (* A :|: B, a |: B union, union with a singleton (of sets). *) (* A :\: B, A :\ b relative complement (of sets, subspaces, ...). *) (* <<A>>, <[a]> generated group/subspace, generated cycle/line. *) (* 'C[x], 'C_A[x] point centralisers (in groups and F-algebras). *) (* 'C(A), 'C_B(A) centralisers (in groups and matrix and F_algebras). *) (* 'Z(A) centers (in groups and matrix and F-algebras). *) (* m %/ d, m %% d Euclidean division and remainder (nat, polynomials). *) (* d %| m Euclidean divisibility (nat, polynomial). *) (* m = n %[mod d] equality mod d (also defined for <>, ==, and !=). *) (* e^`(n) nth formal derivative (groups, polynomials). *) (* e^`() simple formal derivative (polynomials only). *) (* `|x| norm, absolute value, distance (rings, int, nat). *) (* x <= y ?= iff C x is less than y, and equal iff C holds (nat, rings). *) (* x <= y :> T, etc cast comparison (rings, all comparison operators). *) (* [rec a1, ..., an] standard shorthand for hidden recursor (see prime.v). *) (* The interpretation of these notations is not defined here, but the *) (* declarations help maintain consistency across the library. *) (******************************************************************************) (* Reserved notation for evaluation *) Reserved Notation "e .[ x ]" (left associativity, format "e .[ x ]"). Reserved Notation "e .[ x1 , x2 , .. , xn ]" (left associativity, format "e '[ ' .[ x1 , '/' x2 , '/' .. , '/' xn ] ']'"). (* Reserved notation for subscripting and superscripting *) Reserved Notation "s `_ i" (at level 3, i at level 2, left associativity, format "s `_ i"). Reserved Notation "x ^-1" (left associativity, format "x ^-1"). (* Reserved notation for integer multipliers and exponents *) Reserved Notation "x *+ n" (at level 40, left associativity). Reserved Notation "x *- n" (at level 40, left associativity). Reserved Notation "x ^+ n" (at level 29, left associativity). Reserved Notation "x ^- n" (at level 29, left associativity). (* Reserved notation for external multiplication. *) Reserved Notation "x *: A" (at level 40). Reserved Notation "A :* x" (at level 40). (* Reserved notation for conjugation and lifting of actions to sets. *) Reserved Notation "x ^*" (format "x ^*", left associativity). (* Reserved notation for set-theoretic operations. *) Reserved Notation "A :&: B" (at level 48, left associativity). Reserved Notation "A :|: B" (at level 52, left associativity). Reserved Notation "a |: A" (at level 52, left associativity). Reserved Notation "A :\: B" (at level 50, left associativity). Reserved Notation "A :\ b" (at level 50, left associativity). (* Reserved notation for generated structures *) Reserved Notation "<< A >>" (format "<< A >>"). Reserved Notation "<[ a ] >" (format "<[ a ] >"). (* Reserved notation for the order of an element (group, polynomial, etc) *) Reserved Notation "#[ x ]" (format "#[ x ]"). (* Reserved notation for centralisers and centers. *) Reserved Notation "''C' [ x ]" (format "''C' [ x ]"). Reserved Notation "''C_' A [ x ]" (A at level 2, format "''C_' A [ x ]"). Reserved Notation "''C' ( A )" (format "''C' ( A )"). Reserved Notation "''C_' B ( A )" (B at level 2, format "''C_' B ( A )"). Reserved Notation "''Z' ( A )" (format "''Z' ( A )"). (* Compatibility with group action centraliser notation. *) Reserved Notation "''C_' ( A ) [ x ]". Reserved Notation "''C_' ( B ) ( A )". Reserved Notation "''C' [ x | to ]" (format "''C' [ x | to ]"). Reserved Notation "''C' ( S | to )" (format "''C' ( S | to )"). Reserved Notation "''C_' A [ x | to ]" (A at level 2, format "''C_' A [ x | to ]"). Reserved Notation "''C_' A ( S | to )" (A at level 2, format "''C_' A ( S | to )"). Reserved Notation "''C_' ( A ) [ x | to ]". Reserved Notation "''C_' ( A ) ( S | to )". Reserved Notation "''C_' ( | to ) [ a ]" (format "''C_' ( | to ) [ a ]"). Reserved Notation "''C_' ( G | to ) [ a ]" (format "''C_' ( G | to ) [ a ]"). Reserved Notation "''C_' ( | to ) ( A )" (format "''C_' ( | to ) ( A )"). Reserved Notation "''C_' ( G | to ) ( A )" (format "''C_' ( G | to ) ( A )"). (* Bionomial coefficient *) Reserved Notation "''C' ( n , m )" (format "''C' ( n , m )"). (* Reserved notation for Euclidean division and divisibility. *) Reserved Notation "m %/ d" (at level 40, no associativity). Reserved Notation "m %% d" (at level 40, no associativity). Reserved Notation "m %| d" (at level 70, no associativity). #[warning="-postfix-notation-not-level-1"] Reserved Notation "m = n %[mod d ]" (format "'[hv ' m '/' = n '/' %[mod d ] ']'"). #[warning="-postfix-notation-not-level-1"] Reserved Notation "m == n %[mod d ]" (at level 70, n at next level, format "'[hv ' m '/' == n '/' %[mod d ] ']'"). #[warning="-postfix-notation-not-level-1"] Reserved Notation "m <> n %[mod d ]" (format "'[hv ' m '/' <> n '/' %[mod d ] ']'"). #[warning="-postfix-notation-not-level-1"] Reserved Notation "m != n %[mod d ]" (at level 70, n at next level, format "'[hv ' m '/' != n '/' %[mod d ] ']'"). (* Reserved notation for derivatives. *) Reserved Notation "a ^` ()" (format "a ^` ()"). Reserved Notation "a ^` ( n )" (format "a ^` ( n )"). (* Reserved notation for absolute value. *) Reserved Notation "`| x |" (format "`| x |"). (* Reserved notation for conditional comparison *) Reserved Notation "x <= y ?= 'iff' c" (c at next level, format "x '[hv' <= y '/' ?= 'iff' c ']'"). (* Reserved notation for cast comparison. *) Reserved Notation "x <= y :> T". Reserved Notation "x >= y :> T". Reserved Notation "x < y :> T". Reserved Notation "x > y :> T". Reserved Notation "x <= y ?= 'iff' c :> T" (c at next level, format "x '[hv' <= y '/' ?= 'iff' c :> T ']'"). (* Reserved notation for dot product. *) Reserved Notation "'[ u , v ]" (format "'[hv' ''[' u , '/ ' v ] ']'"). Reserved Notation "'[ u ]" (format "''[' u ]").
Integer.lean
/- Copyright (c) 2025 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import Mathlib.Algebra.Algebra.Defs import Mathlib.Algebra.GCDMonoid.Finset import Mathlib.Algebra.GCDMonoid.Nat import Mathlib.Data.Matrix.Mul import Mathlib.Data.Rat.Cast.CharZero /-! # Lemmas on integer matrices Here we collect some results about matrices over `ℚ` and `ℤ`. ## Main definitions and results * `Matrix.num`, `Matrix.den`: express a rational matrix `A` as the quotient of an integer matrix by a (non-zero) natural. ## TODO Consider generalizing these constructions to matrices over localizations of rings (or semirings). -/ namespace Matrix variable {m n : Type*} [Fintype m] [Fintype n] /-! ## Casts These results are useful shortcuts because the canonical casting maps out of `ℕ`, `ℤ`, and `ℚ` to suitable types are bare functions, not ring homs, so we cannot apply `Matrix.map_mul` directly to them. -/ lemma map_mul_natCast {α : Type*} [NonAssocSemiring α] (A B : Matrix n n ℕ) : map (A * B) ((↑) : ℕ → α) = map A (↑) * map B (↑) := Matrix.map_mul (f := Nat.castRingHom α) lemma map_mul_intCast {α : Type*} [NonAssocRing α] (A B : Matrix n n ℤ) : map (A * B) ((↑) : ℤ → α) = map A (↑) * map B (↑) := Matrix.map_mul (f := Int.castRingHom α) lemma map_mul_ratCast {α : Type*} [DivisionRing α] [CharZero α] (A B : Matrix n n ℚ) : map (A * B) ((↑) : ℚ → α) = map A (↑) * map B (↑) := Matrix.map_mul (f := Rat.castHom α) /-! ## Denominator of a rational matrix -/ /-- The denominator of a matrix of rationals (as a `Nat`, defined as the LCM of the denominators of the entries). -/ protected def den (A : Matrix m n ℚ) : ℕ := Finset.univ.lcm (fun P : m × n ↦ (A P.1 P.2).den) /-- The numerator of a matrix of rationals (a matrix of integers, defined so that `A.num / A.den = A`). -/ protected def num (A : Matrix m n ℚ) : Matrix m n ℤ := ((A.den : ℚ) • A).map Rat.num lemma den_ne_zero (A : Matrix m n ℚ) : A.den ≠ 0 := by simp [Matrix.den, Finset.lcm_eq_zero_iff] lemma num_eq_zero_iff (A : Matrix m n ℚ) : A.num = 0 ↔ A = 0 := by simp [Matrix.num, ← ext_iff, A.den_ne_zero] lemma den_dvd_iff {A : Matrix m n ℚ} {r : ℕ} : A.den ∣ r ↔ ∀ i j, (A i j).den ∣ r := by simp [Matrix.den] lemma num_div_den (A : Matrix m n ℚ) (i : m) (j : n) : A.num i j / A.den = A i j := by obtain ⟨k, hk⟩ := den_dvd_iff.mp (dvd_refl A.den) i j rw [Matrix.num, map_apply, smul_apply, smul_eq_mul, mul_comm, div_eq_iff <| Nat.cast_ne_zero.mpr A.den_ne_zero, hk, Nat.cast_mul, ← mul_assoc, Rat.mul_den_eq_num, ← Int.cast_natCast k, ← Int.cast_mul, Rat.num_intCast] lemma inv_denom_smul_num (A : Matrix m n ℚ) : (A.den⁻¹ : ℚ) • A.num.map (↑) = A := by ext simp [← Matrix.num_div_den A, div_eq_inv_mul] @[simp] lemma den_neg (A : Matrix m n ℚ) : (-A).den = A.den := eq_of_forall_dvd <| by simp [den_dvd_iff] @[simp] lemma num_neg (A : Matrix m n ℚ) : (-A).num = -A.num := by ext simp [Matrix.num] @[simp] lemma den_transpose (A : Matrix m n ℚ) : (Aᵀ).den = A.den := eq_of_forall_dvd fun _ ↦ by simpa [den_dvd_iff] using forall_comm @[simp] lemma num_transpose (A : Matrix m n ℚ) : (Aᵀ).num = (A.num)ᵀ := by ext; simp [Matrix.num] /-! ### Compatibility with `map` -/ @[simp] lemma den_map_intCast (A : Matrix m n ℤ) : (A.map (↑)).den = 1 := by simp [← Nat.dvd_one, Matrix.den_dvd_iff] @[simp] lemma num_map_intCast (A : Matrix m n ℤ) : (A.map (↑)).num = A := by simp [Matrix.num, Function.comp_def] @[simp] lemma den_map_natCast (A : Matrix m n ℕ) : (A.map (↑)).den = 1 := by simp [← Nat.dvd_one, Matrix.den_dvd_iff] @[simp] lemma num_map_natCast (A : Matrix m n ℕ) : (A.map (↑)).num = A.map (↑) := by simp [Matrix.num, Function.comp_def] /-! ### Casts from scalar types -/ @[simp] lemma den_natCast [DecidableEq m] (a : ℕ) : (a : Matrix m m ℚ).den = 1 := by simpa [← diagonal_natCast] using den_map_natCast (a : Matrix m m ℕ) @[simp] lemma num_natCast [DecidableEq m] (a : ℕ) : (a : Matrix m m ℚ).num = a := by simpa [← diagonal_natCast] using num_map_natCast (a : Matrix m m ℕ) @[simp] lemma den_ofNat [DecidableEq m] (a : ℕ) [a.AtLeastTwo] : (ofNat(a) : Matrix m m ℚ).den = 1 := den_natCast a @[simp] lemma num_ofNat [DecidableEq m] (a : ℕ) [a.AtLeastTwo] : (ofNat(a) : Matrix m m ℚ).num = a := num_natCast a @[simp] lemma den_intCast [DecidableEq m] (a : ℤ) : (a : Matrix m m ℚ).den = 1 := by simpa [← diagonal_intCast] using den_map_intCast (a : Matrix m m ℤ) @[simp] lemma num_intCast [DecidableEq m] (a : ℤ) : (a : Matrix m m ℚ).num = a := by simpa [← diagonal_intCast] using num_map_intCast (a : Matrix m m ℤ) @[simp] lemma den_zero : (0 : Matrix m n ℚ).den = 1 := den_map_natCast 0 @[simp] lemma num_zero : (0 : Matrix m n ℚ).num = 0 := num_map_natCast 0 @[simp] lemma den_one [DecidableEq m] : (1 : Matrix m m ℚ).den = 1 := den_natCast 1 @[simp] lemma num_one [DecidableEq m] : (1 : Matrix m m ℚ).num = 1 := num_natCast 1 end Matrix
CompactOpenCovered.lean
/- Copyright (c) 2025 Christian Merten. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christian Merten -/ import Mathlib.Topology.Spectral.Prespectral /-! # Compact open covered sets In this file we define the notion of a compact-open covered set with respect to a family of maps `fᵢ : X i → S`. A set `U` is compact-open covered by the family `fᵢ` if it is the finite union of images of compact open sets in the `X i`. This notion is not interesting, if the `fᵢ` are open maps (see `IsCompactOpenCovered.of_isOpenMap`). This is used to define the fpqc topology of schemes, there a cover is given by a family of flat morphisms such that every compact open is compact-open covered. ## Main results - `IsCompactOpenCovered.of_isOpenMap`: If all the `fᵢ` are open maps, then every compact open of `S` is compact-open covered. -/ open TopologicalSpace Opens /-- A set `U` is compact-open covered by the family `fᵢ : X i → S`, if `U` is the finite union of images of compact open sets in the `X i`. -/ def IsCompactOpenCovered {S ι : Type*} {X : ι → Type*} (f : ∀ i, X i → S) [∀ i, TopologicalSpace (X i)] (U : Set S) : Prop := ∃ (s : Set ι) (_ : s.Finite) (V : ∀ i ∈ s, Opens (X i)), (∀ (i : ι) (h : i ∈ s), IsCompact (V i h).1) ∧ ⋃ (i : ι) (h : i ∈ s), (f i) '' (V i h) = U namespace IsCompactOpenCovered variable {S ι : Type*} {X : ι → Type*} {f : ∀ i, X i → S} [∀ i, TopologicalSpace (X i)] {U : Set S} lemma empty : IsCompactOpenCovered f ∅ := ⟨∅, Set.finite_empty, fun _ _ ↦ ⟨∅, isOpen_empty⟩, fun _ _ ↦ isCompact_empty, by simp⟩ lemma iff_of_unique [Unique ι] : IsCompactOpenCovered f U ↔ ∃ (V : Opens (X default)), IsCompact V.1 ∧ f default '' V.1 = U := by refine ⟨fun ⟨s, hs, V, hc, hcov⟩ ↦ ?_, fun ⟨V, hc, h⟩ ↦ ?_⟩ · by_cases h : s = ∅ · aesop · obtain rfl : s = {default} := by rw [← Set.univ_unique, Subsingleton.eq_univ_of_nonempty (Set.nonempty_iff_ne_empty.mpr h)] aesop · refine ⟨{default}, Set.finite_singleton _, fun i h ↦ h ▸ V, fun i ↦ ?_, by simpa⟩ rintro rfl simpa lemma id_iff_isOpen_and_isCompact [TopologicalSpace S] : IsCompactOpenCovered (fun _ : Unit ↦ id) U ↔ IsOpen U ∧ IsCompact U := by rw [iff_of_unique] refine ⟨fun ⟨V, hV, heq⟩ ↦ ?_, fun ⟨ho, hc⟩ ↦ ⟨⟨U, ho⟩, hc, by simp⟩⟩ simp only [id_eq, Set.image_id', carrier_eq_coe, ← heq] at heq ⊢ exact ⟨V.2, hV⟩ lemma iff_isCompactOpenCovered_sigmaMk : IsCompactOpenCovered f U ↔ IsCompactOpenCovered (fun (_ : Unit) (p : Σ i : ι, X i) ↦ f p.1 p.2) U := by classical rw [iff_of_unique (ι := Unit)] refine ⟨fun ⟨s, hs, V, hc, hU⟩ ↦ ?_, fun ⟨V, hc, heq⟩ ↦ ?_⟩ · refine ⟨⟨s.sigma fun i ↦ if h : i ∈ s then V i h else ∅, isOpen_sigma_iff.mpr ?_⟩, ?_, ?_⟩ · intro i by_cases h : i ∈ s · simpa [h] using (V _ _).2 · simp [h] · dsimp only exact Set.isCompact_sigma hs fun i ↦ (by aesop) · aesop · obtain ⟨s, t, hs, hc, heq'⟩ := hc.sigma_exists_finite_sigma_eq have (i : ι) (hi : i ∈ s) : IsOpen (t i) := by rw [← Set.mk_preimage_sigma (t := t) hi] exact isOpen_sigma_iff.mp (heq' ▸ V.2) i refine ⟨s, hs, fun i hi ↦ ⟨t i, this i hi⟩, fun i _ ↦ hc i, ?_⟩ simp_rw [coe_mk, ← heq, ← heq', Set.image_sigma_eq_iUnion, Function.comp_apply] lemma of_iUnion_eq_of_finite (s : Set (Set S)) (hs : ⋃ t ∈ s, t = U) (hf : s.Finite) (H : ∀ t ∈ s, IsCompactOpenCovered f t) : IsCompactOpenCovered f U := by rw [iff_isCompactOpenCovered_sigmaMk, iff_of_unique] have (t) (h : t ∈ s) : ∃ (V : Opens (Σ i, X i)), IsCompact V.1 ∧ (fun p ↦ f p.fst p.snd) '' V.carrier = t := by have := H t h rwa [iff_isCompactOpenCovered_sigmaMk, iff_of_unique] at this choose V hVeq hVc using this refine ⟨⨆ (t : s), V t t.2, ?_, ?_⟩ · simp only [Opens.iSup_mk, Opens.carrier_eq_coe, Opens.coe_mk] have : Finite s := hf exact isCompact_iUnion (fun _ ↦ hVeq _ _) · simp [Set.image_iUnion, ← hs] aesop /-- If `U` is compact-open covered and the `X i` have a basis of compact opens, `U` can be written as the union of images of elements of the basis. -/ lemma exists_mem_of_isBasis {B : ∀ i, Set (Opens (X i))} (hB : ∀ i, IsBasis (B i)) (hBc : ∀ (i : ι), ∀ U ∈ B i, IsCompact U.1) {U : Set S} (hU : IsCompactOpenCovered f U) : ∃ (n : ℕ) (a : Fin n → ι) (V : ∀ i, Opens (X (a i))), (∀ i, V i ∈ B (a i)) ∧ ⋃ i, f (a i) '' V i = U := by suffices h : ∃ (κ : Type _) (_ : Finite κ) (a : κ → ι) (V : ∀ i, Opens (X (a i))), (∀ i, V i ∈ B (a i)) ∧ (∀ i, IsCompact (V i).1) ∧ ⋃ i, f (a i) '' V i = U by obtain ⟨κ, _, a, V, hB, hc, hU⟩ := h cases nonempty_fintype κ refine ⟨Fintype.card κ, a ∘ (Fintype.equivFin κ).symm, fun i ↦ V _, fun i ↦ hB _, ?_⟩ simp [← hU, ← (Fintype.equivFin κ).symm.surjective.iUnion_comp, Function.comp_apply] obtain ⟨s, hs, V, hc, hunion⟩ := hU choose Us UsB hUsf hUs using fun i : s ↦ (hB i.1).exists_finite_of_isCompact (hc i i.2) let σ := Σ i : s, Us i have : Finite s := hs have (i : _) : Finite (Us i) := hUsf i refine ⟨σ, inferInstance, fun i ↦ i.1.1, fun i ↦ i.2.1, fun i ↦ UsB _ (by simp), fun _ ↦ hBc _ _ (UsB _ (by simp)), ?_⟩ rw [← hunion] ext x simp_rw [Set.mem_iUnion] refine ⟨fun ⟨i, hi, o, ho⟩ ↦ by aesop, fun ⟨i, hi, h, hmem, heq⟩ ↦ ?_⟩ rw [hUs ⟨i, hi⟩, coe_sSup, Set.mem_iUnion] at hmem obtain ⟨a, ha⟩ := hmem simp only [Set.mem_iUnion, SetLike.mem_coe, exists_prop] at ha use ⟨⟨i, hi⟩, ⟨a, ha.1⟩⟩, h, ha.2, heq lemma of_isOpenMap [TopologicalSpace S] [∀ i, PrespectralSpace (X i)] (hfc : ∀ i, Continuous (f i)) (h : ∀ i, IsOpenMap (f i)) {U : Set S} (hs : ∀ x ∈ U, ∃ i y, f i y = x) (hU : IsOpen U) (hc : IsCompact U) : IsCompactOpenCovered f U := by rw [iff_isCompactOpenCovered_sigmaMk, iff_of_unique] refine (isOpenMap_sigma.mpr h).exists_opens_image_eq_of_prespectralSpace (continuous_sigma_iff.mpr hfc) (fun x hx ↦ ?_) hU hc simpa using hs x hx end IsCompactOpenCovered
Oka.lean
/- Copyright (c) 2025 Anthony Fernandes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anthony Fernandes, Marc Robin -/ import Mathlib.RingTheory.Ideal.Colon /-! # Oka predicates This file introduces the notion of Oka predicates and standard results about them. ## Main results - `Ideal.IsOka.isPrime_of_maximal_not`: if an ideal is maximal for not satisfying an Oka predicate, then it is prime. - `Ideal.IsOka.forall_of_forall_prime`: if all prime ideals of a ring satisfy an Oka predicate, then all its ideals also satisfy the predicate. ## References - [stacks-project]: The Stacks project, [tag 05K7](https://stacks.math.columbia.edu/tag/05K7) - [lam_reyes_2009]: *Oka and Ako ideal families in commutative rings*, 2009 -/ namespace Ideal variable {R : Type*} [CommSemiring R] /-- A predicate `P : Ideal R → Prop` over the ideals of a ring `R` is said to be Oka if R satisfies it (`P ⊤`) and whenever we have `I : Ideal R`, `P (I.colon (span {a})` and `P (I ⊔ span {a})` for some `a : R` then `P I`. -/ @[stacks 05K9] structure IsOka (P : Ideal R → Prop) : Prop where top : P ⊤ oka {I : Ideal R} {a : R} : P (I ⊔ span {a}) → P (I.colon (span {a})) → P I namespace IsOka variable {P : Ideal R → Prop} /-- If an ideal is maximal for not satisfying an Oka predicate then it is prime. -/ @[stacks 05KE] theorem isPrime_of_maximal_not (hP : IsOka P) {I : Ideal R} (hI : Maximal (¬P ·) I) : I.IsPrime where ne_top' hI' := hI.prop (hI' ▸ hP.top) mem_or_mem' := by by_contra! obtain ⟨a, b, hab, ha, hb⟩ := this have h₁ : P (I ⊔ span {a}) := of_not_not <| hI.not_prop_of_gt (Submodule.lt_sup_iff_notMem.2 ha) have h₂ : P (I.colon (span {a})) := of_not_not <| hI.not_prop_of_gt <| lt_of_le_of_ne le_colon (fun H ↦ hb <| H ▸ mem_colon_singleton.2 (mul_comm a b ▸ hab)) exact hI.prop (hP.oka h₁ h₂) /-- If all prime ideals of a ring satisfy an Oka predicate, then all its ideals also satisfy the predicate. `hmax` is generaly obtained using Zorn's lemma. -/ theorem forall_of_forall_prime (hP : IsOka P) (hmax : (∃ I, ¬P I) → ∃ I, Maximal (¬P ·) I) (hprime : ∀ I, I.IsPrime → P I) : ∀ I, P I := by by_contra! obtain ⟨I, hI⟩ := hmax this exact hI.prop <| hprime I (hP.isPrime_of_maximal_not hI) end IsOka end Ideal
SmallDegree.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Kim Morrison, Jens Wagemaker -/ import Mathlib.Algebra.Polynomial.Degree.Operations import Mathlib.Data.Nat.WithBot /-! # Results on polynomials of specific small degrees -/ open Finsupp Finset open Polynomial namespace Polynomial universe u v variable {R : Type u} {S : Type v} {a b c d : R} {n m : ℕ} section Semiring variable [Semiring R] {p q r : R[X]} theorem eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext fun n => Nat.casesOn n (by simp) fun n => Nat.casesOn n (by simp [coeff_C]) fun m => by -- Porting note: `by decide` → `Iff.mpr ..` have : degree p < m.succ.succ := lt_of_le_of_lt h (Iff.mpr WithBot.coe_lt_coe <| Nat.succ_lt_succ <| Nat.zero_lt_succ m) simp [coeff_eq_zero_of_degree_lt this] theorem eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C p.leadingCoeff * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one h.le).trans (by rw [← Nat.cast_one] at h; rw [leadingCoeff, natDegree_eq_of_degree_eq_some h]) theorem eq_X_add_C_of_natDegree_le_one (h : natDegree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := eq_X_add_C_of_degree_le_one <| degree_le_of_natDegree_le h theorem Monic.eq_X_add_C (hm : p.Monic) (hnd : p.natDegree = 1) : p = X + C (p.coeff 0) := by rw [← one_mul X, ← C_1, ← hm.coeff_natDegree, hnd, ← eq_X_add_C_of_natDegree_le_one hnd.le] theorem exists_eq_X_add_C_of_natDegree_le_one (h : natDegree p ≤ 1) : ∃ a b, p = C a * X + C b := ⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_natDegree_le_one h⟩ end Semiring section Semiring variable [Semiring R] {p q : R[X]} {ι : Type*} theorem zero_le_degree_iff : 0 ≤ degree p ↔ p ≠ 0 := by rw [← not_lt, Nat.WithBot.lt_zero_iff, degree_eq_bot] theorem ne_zero_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : p ≠ 0 := zero_le_degree_iff.mp <| (WithBot.coe_le_coe.mpr n.zero_le).trans hdeg theorem le_natDegree_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : n ≤ p.natDegree := WithBot.coe_le_coe.mp <| by rwa [degree_eq_natDegree <| ne_zero_of_coe_le_degree hdeg] at hdeg theorem degree_linear_le : degree (C a * X + C b) ≤ 1 := degree_add_le_of_degree_le (degree_C_mul_X_le _) <| le_trans degree_C_le Nat.WithBot.coe_nonneg theorem degree_linear_lt : degree (C a * X + C b) < 2 := degree_linear_le.trans_lt <| WithBot.coe_lt_coe.mpr one_lt_two @[simp] theorem degree_linear (ha : a ≠ 0) : degree (C a * X + C b) = 1 := by rw [degree_add_eq_left_of_degree_lt <| degree_C_lt_degree_C_mul_X ha, degree_C_mul_X ha] theorem natDegree_linear_le : natDegree (C a * X + C b) ≤ 1 := natDegree_le_of_degree_le degree_linear_le theorem natDegree_linear (ha : a ≠ 0) : natDegree (C a * X + C b) = 1 := by rw [natDegree_add_C, natDegree_C_mul_X a ha] @[simp] theorem leadingCoeff_linear (ha : a ≠ 0) : leadingCoeff (C a * X + C b) = a := by rw [add_comm, leadingCoeff_add_of_degree_lt (degree_C_lt_degree_C_mul_X ha), leadingCoeff_C_mul_X] theorem degree_quadratic_le : degree (C a * X ^ 2 + C b * X + C c) ≤ 2 := by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 2 a) (le_trans degree_linear_le <| WithBot.coe_le_coe.mpr one_le_two) theorem degree_quadratic_lt : degree (C a * X ^ 2 + C b * X + C c) < 3 := degree_quadratic_le.trans_lt <| WithBot.coe_lt_coe.mpr <| lt_add_one 2 theorem degree_linear_lt_degree_C_mul_X_sq (ha : a ≠ 0) : degree (C b * X + C c) < degree (C a * X ^ 2) := by simpa only [degree_C_mul_X_pow 2 ha] using degree_linear_lt @[simp] theorem degree_quadratic (ha : a ≠ 0) : degree (C a * X ^ 2 + C b * X + C c) = 2 := by rw [add_assoc, degree_add_eq_left_of_degree_lt <| degree_linear_lt_degree_C_mul_X_sq ha, degree_C_mul_X_pow 2 ha] rfl theorem natDegree_quadratic_le : natDegree (C a * X ^ 2 + C b * X + C c) ≤ 2 := natDegree_le_of_degree_le degree_quadratic_le theorem natDegree_quadratic (ha : a ≠ 0) : natDegree (C a * X ^ 2 + C b * X + C c) = 2 := natDegree_eq_of_degree_eq_some <| degree_quadratic ha @[simp] theorem leadingCoeff_quadratic (ha : a ≠ 0) : leadingCoeff (C a * X ^ 2 + C b * X + C c) = a := by rw [add_assoc, add_comm, leadingCoeff_add_of_degree_lt <| degree_linear_lt_degree_C_mul_X_sq ha, leadingCoeff_C_mul_X_pow] theorem degree_cubic_le : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 := by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 3 a) (le_trans degree_quadratic_le <| WithBot.coe_le_coe.mpr <| Nat.le_succ 2) theorem degree_cubic_lt : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) < 4 := degree_cubic_le.trans_lt <| WithBot.coe_lt_coe.mpr <| lt_add_one 3 theorem degree_quadratic_lt_degree_C_mul_X_cb (ha : a ≠ 0) : degree (C b * X ^ 2 + C c * X + C d) < degree (C a * X ^ 3) := by simpa only [degree_C_mul_X_pow 3 ha] using degree_quadratic_lt @[simp] theorem degree_cubic (ha : a ≠ 0) : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 := by rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), degree_add_eq_left_of_degree_lt <| degree_quadratic_lt_degree_C_mul_X_cb ha, degree_C_mul_X_pow 3 ha] rfl theorem natDegree_cubic_le : natDegree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 := natDegree_le_of_degree_le degree_cubic_le theorem natDegree_cubic (ha : a ≠ 0) : natDegree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 := natDegree_eq_of_degree_eq_some <| degree_cubic ha @[simp] theorem leadingCoeff_cubic (ha : a ≠ 0) : leadingCoeff (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = a := by rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), add_comm, leadingCoeff_add_of_degree_lt <| degree_quadratic_lt_degree_C_mul_X_cb ha, leadingCoeff_C_mul_X_pow] end Semiring end Polynomial
Defs.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov -/ import Mathlib.Order.Filter.Map import Mathlib.Order.ZornAtoms /-! # Ultrafilters An ultrafilter is a minimal (maximal in the set order) proper filter. In this file we define * `Ultrafilter.of`: an ultrafilter that is less than or equal to a given filter; * `Ultrafilter`: subtype of ultrafilters; * `pure x : Ultrafilter α`: `pure x` as an `Ultrafilter`; * `Ultrafilter.map`, `Ultrafilter.bind`, `Ultrafilter.comap` : operations on ultrafilters; -/ assert_not_exists Set.Finite universe u v variable {α : Type u} {β : Type v} {γ : Type*} open Set Filter Function /-- `Filter α` is an atomic type: for every filter there exists an ultrafilter that is less than or equal to this filter. -/ instance : IsAtomic (Filter α) := IsAtomic.of_isChain_bounded fun c hc hne hb => ⟨sInf c, (sInf_neBot_of_directed' hne (show IsChain (· ≥ ·) c from hc.symm).directedOn hb).ne, fun _ hx => sInf_le hx⟩ /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ structure Ultrafilter (α : Type*) extends Filter α where /-- An ultrafilter is nontrivial. -/ protected neBot' : NeBot toFilter /-- If `g` is a nontrivial filter that is less than or equal to an ultrafilter, then it is greater than or equal to the ultrafilter. -/ protected le_of_le : ∀ g, Filter.NeBot g → g ≤ toFilter → toFilter ≤ g namespace Ultrafilter variable {f g : Ultrafilter α} {s t : Set α} {p q : α → Prop} attribute [coe] Ultrafilter.toFilter instance : CoeTC (Ultrafilter α) (Filter α) := ⟨Ultrafilter.toFilter⟩ instance : Membership (Set α) (Ultrafilter α) := ⟨fun f s => s ∈ (f : Filter α)⟩ theorem unique (f : Ultrafilter α) {g : Filter α} (h : g ≤ f) (hne : NeBot g := by infer_instance) : g = f := le_antisymm h <| f.le_of_le g hne h instance neBot (f : Ultrafilter α) : NeBot (f : Filter α) := f.neBot' protected theorem isAtom (f : Ultrafilter α) : IsAtom (f : Filter α) := ⟨f.neBot.ne, fun _ hgf => by_contra fun hg => hgf.ne <| f.unique hgf.le ⟨hg⟩⟩ @[simp, norm_cast] theorem mem_coe : s ∈ (f : Filter α) ↔ s ∈ f := Iff.rfl theorem coe_injective : Injective ((↑) : Ultrafilter α → Filter α) | ⟨f, h₁, h₂⟩, ⟨g, _, _⟩, _ => by congr theorem eq_of_le {f g : Ultrafilter α} (h : (f : Filter α) ≤ g) : f = g := coe_injective (g.unique h) @[simp, norm_cast] theorem coe_le_coe {f g : Ultrafilter α} : (f : Filter α) ≤ g ↔ f = g := ⟨fun h => eq_of_le h, fun h => h ▸ le_rfl⟩ @[simp, norm_cast] theorem coe_inj : (f : Filter α) = g ↔ f = g := coe_injective.eq_iff @[ext] theorem ext ⦃f g : Ultrafilter α⦄ (h : ∀ s, s ∈ f ↔ s ∈ g) : f = g := coe_injective <| Filter.ext h theorem le_of_inf_neBot (f : Ultrafilter α) {g : Filter α} (hg : NeBot (↑f ⊓ g)) : ↑f ≤ g := le_of_inf_eq (f.unique inf_le_left hg) theorem le_of_inf_neBot' (f : Ultrafilter α) {g : Filter α} (hg : NeBot (g ⊓ f)) : ↑f ≤ g := f.le_of_inf_neBot <| by rwa [inf_comm] theorem inf_neBot_iff {f : Ultrafilter α} {g : Filter α} : NeBot (↑f ⊓ g) ↔ ↑f ≤ g := ⟨le_of_inf_neBot f, fun h => (inf_of_le_left h).symm ▸ f.neBot⟩ theorem disjoint_iff_not_le {f : Ultrafilter α} {g : Filter α} : Disjoint (↑f) g ↔ ¬↑f ≤ g := by rw [← inf_neBot_iff, neBot_iff, Ne, not_not, disjoint_iff] @[simp] theorem compl_notMem_iff : sᶜ ∉ f ↔ s ∈ f := ⟨fun hsc => le_principal_iff.1 <| f.le_of_inf_neBot ⟨fun h => hsc <| mem_of_eq_bot <| by rwa [compl_compl]⟩, compl_notMem⟩ @[deprecated (since := "2025-05-23")] alias compl_not_mem_iff := compl_notMem_iff @[simp] theorem frequently_iff_eventually : (∃ᶠ x in f, p x) ↔ ∀ᶠ x in f, p x := compl_notMem_iff alias ⟨_root_.Filter.Frequently.eventually, _⟩ := frequently_iff_eventually theorem compl_mem_iff_notMem : sᶜ ∈ f ↔ s ∉ f := by rw [← compl_notMem_iff, compl_compl] @[deprecated (since := "2025-05-23")] alias compl_mem_iff_not_mem := compl_mem_iff_notMem theorem diff_mem_iff (f : Ultrafilter α) : s \ t ∈ f ↔ s ∈ f ∧ t ∉ f := inter_mem_iff.trans <| and_congr Iff.rfl compl_mem_iff_notMem /-- If `sᶜ ∉ f ↔ s ∈ f`, then `f` is an ultrafilter. The other implication is given by `Ultrafilter.compl_notMem_iff`. -/ def ofComplNotMemIff (f : Filter α) (h : ∀ s, sᶜ ∉ f ↔ s ∈ f) : Ultrafilter α where toFilter := f neBot' := ⟨fun hf => by simp [hf] at h⟩ le_of_le _ _ hgf s hs := (h s).1 fun hsc => compl_notMem hs (hgf hsc) /-- If `f : Filter α` is an atom, then it is an ultrafilter. -/ def ofAtom (f : Filter α) (hf : IsAtom f) : Ultrafilter α where toFilter := f neBot' := ⟨hf.1⟩ le_of_le g hg := (isAtom_iff_le_of_ge.1 hf).2 g hg.ne theorem nonempty_of_mem (hs : s ∈ f) : s.Nonempty := Filter.nonempty_of_mem hs theorem ne_empty_of_mem (hs : s ∈ f) : s ≠ ∅ := (nonempty_of_mem hs).ne_empty @[simp] theorem empty_notMem : ∅ ∉ f := Filter.empty_notMem (f : Filter α) @[deprecated (since := "2025-05-23")] alias empty_not_mem := empty_notMem @[simp] theorem le_sup_iff {u : Ultrafilter α} {f g : Filter α} : ↑u ≤ f ⊔ g ↔ ↑u ≤ f ∨ ↑u ≤ g := not_iff_not.1 <| by simp only [← disjoint_iff_not_le, not_or, disjoint_sup_right] @[simp] theorem union_mem_iff : s ∪ t ∈ f ↔ s ∈ f ∨ t ∈ f := by simp only [← mem_coe, ← le_principal_iff, ← sup_principal, le_sup_iff] theorem mem_or_compl_mem (f : Ultrafilter α) (s : Set α) : s ∈ f ∨ sᶜ ∈ f := or_iff_not_imp_left.2 compl_mem_iff_notMem.2 protected theorem em (f : Ultrafilter α) (p : α → Prop) : (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x := f.mem_or_compl_mem { x | p x } theorem eventually_or : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x := union_mem_iff theorem eventually_not : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := compl_mem_iff_notMem theorem eventually_imp : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x := by simp only [imp_iff_not_or, eventually_or, eventually_not] /-- Pushforward for ultrafilters. -/ nonrec def map (m : α → β) (f : Ultrafilter α) : Ultrafilter β := ofComplNotMemIff (map m f) fun s => @compl_notMem_iff _ f (m ⁻¹' s) @[simp, norm_cast] theorem coe_map (m : α → β) (f : Ultrafilter α) : (map m f : Filter β) = Filter.map m ↑f := rfl @[simp] theorem mem_map {m : α → β} {f : Ultrafilter α} {s : Set β} : s ∈ map m f ↔ m ⁻¹' s ∈ f := Iff.rfl @[simp] nonrec theorem map_id (f : Ultrafilter α) : f.map id = f := coe_injective map_id @[simp] theorem map_id' (f : Ultrafilter α) : (f.map fun x => x) = f := map_id _ @[simp] nonrec theorem map_map (f : Ultrafilter α) (m : α → β) (n : β → γ) : (f.map m).map n = f.map (n ∘ m) := coe_injective map_map /-- The pullback of an ultrafilter along an injection whose range is large with respect to the given ultrafilter. -/ nonrec def comap {m : α → β} (u : Ultrafilter β) (inj : Injective m) (large : Set.range m ∈ u) : Ultrafilter α where toFilter := comap m u neBot' := u.neBot'.comap_of_range_mem large le_of_le g hg hgu := by simp only [← u.unique (map_le_iff_le_comap.2 hgu), comap_map inj, le_rfl] @[simp] theorem mem_comap {m : α → β} (u : Ultrafilter β) (inj : Injective m) (large : Set.range m ∈ u) {s : Set α} : s ∈ u.comap inj large ↔ m '' s ∈ u := mem_comap_iff inj large @[simp, norm_cast] theorem coe_comap {m : α → β} (u : Ultrafilter β) (inj : Injective m) (large : Set.range m ∈ u) : (u.comap inj large : Filter α) = Filter.comap m u := rfl @[simp] nonrec theorem comap_id (f : Ultrafilter α) (h₀ : Injective (id : α → α) := injective_id) (h₁ : range id ∈ f := (by rw [range_id]; exact univ_mem)) : f.comap h₀ h₁ = f := coe_injective comap_id @[simp] nonrec theorem comap_comap (f : Ultrafilter γ) {m : α → β} {n : β → γ} (inj₀ : Injective n) (large₀ : range n ∈ f) (inj₁ : Injective m) (large₁ : range m ∈ f.comap inj₀ large₀) (inj₂ : Injective (n ∘ m) := inj₀.comp inj₁) (large₂ : range (n ∘ m) ∈ f := (by rw [range_comp]; exact image_mem_of_mem_comap large₀ large₁)) : (f.comap inj₀ large₀).comap inj₁ large₁ = f.comap inj₂ large₂ := coe_injective comap_comap /-- The principal ultrafilter associated to a point `x`. -/ instance : Pure Ultrafilter := ⟨fun a => ofComplNotMemIff (pure a) fun s => by simp⟩ @[simp] theorem mem_pure {a : α} {s : Set α} : s ∈ (pure a : Ultrafilter α) ↔ a ∈ s := Iff.rfl @[simp] theorem coe_pure (a : α) : ↑(pure a : Ultrafilter α) = (pure a : Filter α) := rfl @[simp] theorem map_pure (m : α → β) (a : α) : map m (pure a) = pure (m a) := rfl @[simp] theorem comap_pure {m : α → β} (a : α) (inj : Injective m) (large) : comap (pure <| m a) inj large = pure a := coe_injective <| Filter.comap_pure.trans <| by rw [coe_pure, ← principal_singleton, ← image_singleton, preimage_image_eq _ inj] theorem pure_injective : Injective (pure : α → Ultrafilter α) := fun _ _ h => Filter.pure_injective (congr_arg Ultrafilter.toFilter h :) instance [Inhabited α] : Inhabited (Ultrafilter α) := ⟨pure default⟩ instance [Nonempty α] : Nonempty (Ultrafilter α) := Nonempty.map pure inferInstance /-- Monadic bind for ultrafilters, coming from the one on filters defined in terms of map and join. -/ def bind (f : Ultrafilter α) (m : α → Ultrafilter β) : Ultrafilter β := ofComplNotMemIff (Filter.bind ↑f fun x => ↑(m x)) fun s => by simp only [mem_bind', mem_coe, ← compl_mem_iff_notMem, compl_setOf, compl_compl] instance instBind : Bind Ultrafilter := ⟨@Ultrafilter.bind⟩ instance functor : Functor Ultrafilter where map := @Ultrafilter.map instance monad : Monad Ultrafilter where map := @Ultrafilter.map section attribute [local instance] Filter.monad Filter.lawfulMonad instance lawfulMonad : LawfulMonad Ultrafilter where id_map f := coe_injective (id_map f.toFilter) pure_bind a f := coe_injective (Filter.pure_bind a ((Ultrafilter.toFilter) ∘ f)) bind_assoc _ _ _ := coe_injective (filter_eq rfl) bind_pure_comp f x := coe_injective (bind_pure_comp f x.1) map_const := rfl seqLeft_eq _ _ := rfl seqRight_eq _ _ := rfl pure_seq _ _ := rfl bind_map _ _ := rfl end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ theorem exists_le (f : Filter α) [h : NeBot f] : ∃ u : Ultrafilter α, ↑u ≤ f := let ⟨u, hu, huf⟩ := (eq_bot_or_exists_atom_le f).resolve_left h.ne ⟨ofAtom u hu, huf⟩ alias _root_.Filter.exists_ultrafilter_le := exists_le /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def of (f : Filter α) [NeBot f] : Ultrafilter α := Classical.choose (exists_le f) theorem of_le (f : Filter α) [NeBot f] : ↑(of f) ≤ f := Classical.choose_spec (exists_le f) theorem of_coe (f : Ultrafilter α) : of ↑f = f := coe_inj.1 <| f.unique (of_le f.toFilter) end Ultrafilter namespace Filter variable {f : Filter α} {s : Set α} {a : α} open Ultrafilter theorem isAtom_pure : IsAtom (pure a : Filter α) := (pure a : Ultrafilter α).isAtom protected theorem NeBot.le_pure_iff (hf : f.NeBot) : f ≤ pure a ↔ f = pure a := ⟨Ultrafilter.unique (pure a), le_of_eq⟩ protected theorem NeBot.eq_pure_iff (hf : f.NeBot) {x : α} : f = pure x ↔ {x} ∈ f := by rw [← hf.le_pure_iff, le_pure_iff] @[simp] theorem lt_pure_iff : f < pure a ↔ f = ⊥ := isAtom_pure.lt_iff theorem le_pure_iff' : f ≤ pure a ↔ f = ⊥ ∨ f = pure a := isAtom_pure.le_iff @[simp] theorem Iic_pure (a : α) : Iic (pure a : Filter α) = {⊥, pure a} := isAtom_pure.Iic_eq theorem mem_iff_ultrafilter : s ∈ f ↔ ∀ g : Ultrafilter α, ↑g ≤ f → s ∈ g := by refine ⟨fun hf g hg => hg hf, fun H => by_contra fun hf => ?_⟩ set g : Filter (sᶜ : Set α) := comap (↑) f haveI : NeBot g := comap_neBot_iff_compl_range.2 (by simpa [compl_setOf] ) simpa using H ((of g).map (↑)) (map_le_iff_le_comap.mpr (of_le g)) theorem le_iff_ultrafilter {f₁ f₂ : Filter α} : f₁ ≤ f₂ ↔ ∀ g : Ultrafilter α, ↑g ≤ f₁ → ↑g ≤ f₂ := ⟨fun h _ h₁ => h₁.trans h, fun h _ hs => mem_iff_ultrafilter.2 fun g hg => h g hg hs⟩ /-- A filter equals the intersection of all the ultrafilters which contain it. -/ theorem iSup_ultrafilter_le_eq (f : Filter α) : ⨆ (g : Ultrafilter α) (_ : g ≤ f), (g : Filter α) = f := eq_of_forall_ge_iff fun f' => by simp only [iSup_le_iff, ← le_iff_ultrafilter] theorem exists_ultrafilter_iff {f : Filter α} : (∃ u : Ultrafilter α, ↑u ≤ f) ↔ NeBot f := ⟨fun ⟨_, uf⟩ => neBot_of_le uf, fun h => @exists_ultrafilter_le _ _ h⟩ theorem forall_neBot_le_iff {g : Filter α} {p : Filter α → Prop} (hp : Monotone p) : (∀ f : Filter α, NeBot f → f ≤ g → p f) ↔ ∀ f : Ultrafilter α, ↑f ≤ g → p f := by refine ⟨fun H f hf => H f f.neBot hf, ?_⟩ intro H f hf hfg exact hp (of_le f) (H _ ((of_le f).trans hfg)) end Filter namespace Ultrafilter variable {m : α → β} {s : Set α} {g : Ultrafilter β} theorem comap_inf_principal_neBot_of_image_mem (h : m '' s ∈ g) : (Filter.comap m g ⊓ 𝓟 s).NeBot := Filter.comap_inf_principal_neBot_of_image_mem g.neBot h /-- Ultrafilter extending the inf of a comapped ultrafilter and a principal ultrafilter. -/ noncomputable def ofComapInfPrincipal (h : m '' s ∈ g) : Ultrafilter α := @of _ (Filter.comap m g ⊓ 𝓟 s) (comap_inf_principal_neBot_of_image_mem h) theorem ofComapInfPrincipal_mem (h : m '' s ∈ g) : s ∈ ofComapInfPrincipal h := by let f := Filter.comap m g ⊓ 𝓟 s haveI : f.NeBot := comap_inf_principal_neBot_of_image_mem h have : s ∈ f := mem_inf_of_right (mem_principal_self s) exact le_def.mp (of_le _) s this theorem ofComapInfPrincipal_eq_of_map (h : m '' s ∈ g) : (ofComapInfPrincipal h).map m = g := by let f := Filter.comap m g ⊓ 𝓟 s haveI : f.NeBot := comap_inf_principal_neBot_of_image_mem h apply eq_of_le calc Filter.map m (of f) ≤ Filter.map m f := map_mono (of_le _) _ ≤ (Filter.map m <| Filter.comap m g) ⊓ Filter.map m (𝓟 s) := map_inf_le _ = (Filter.map m <| Filter.comap m g) ⊓ (𝓟 <| m '' s) := by rw [map_principal] _ ≤ ↑g ⊓ (𝓟 <| m '' s) := inf_le_inf_right _ map_comap_le _ = ↑g := inf_of_le_left (le_principal_iff.mpr h) theorem eq_of_le_pure {X : Type _} {α : Filter X} (hα : α.NeBot) {x y : X} (hx : α ≤ pure x) (hy : α ≤ pure y) : x = y := Filter.pure_injective (hα.le_pure_iff.mp hx ▸ hα.le_pure_iff.mp hy) end Ultrafilter
Fin.lean
/- Copyright (c) 2022 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.Algebra.Ring.Equiv import Mathlib.Data.Fin.Tuple.Basic /-! # Rings and `Fin` This file collects some basic results involving rings and the `Fin` type ## Main results * `RingEquiv.piFinTwo`: The product over `Fin 2` of some rings is the cartesian product -/ /-- The product over `Fin 2` of some rings is just the cartesian product of these rings. -/ @[simps] def RingEquiv.piFinTwo (R : Fin 2 → Type*) [∀ i, Semiring (R i)] : (∀ i : Fin 2, R i) ≃+* R 0 × R 1 := { piFinTwoEquiv R with toFun := piFinTwoEquiv R map_add' := fun _ _ => rfl map_mul' := fun _ _ => rfl }
PID.lean
/- Copyright (c) 2025 Jingting Wang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jingting Wang -/ import Mathlib.RingTheory.KrullDimension.Zero import Mathlib.RingTheory.PrincipalIdealDomain /-! # The Krull dimension of a principal ideal domain In this file, we proved some results about the dimension of a principal ideal domain. -/ instance IsPrincipalIdealRing.krullDimLE_one (R : Type*) [CommRing R] [IsPrincipalIdealRing R] : Ring.KrullDimLE 1 R := by refine Ring.krullDimLE_one_iff.2 fun I hI ↦ or_iff_not_imp_left.2 fun hI' ↦ ?_ rw [minimalPrimes_eq_minimals, Set.notMem_setOf_iff, not_minimal_iff_exists_lt hI] at hI' obtain ⟨P, hlt, hP⟩ := hI' have := IsPrincipalIdealRing.of_surjective (Ideal.Quotient.mk P) Ideal.Quotient.mk_surjective have : (I.map (Ideal.Quotient.mk P)).IsMaximal := by have := Ideal.map_isPrime_of_surjective (f := Ideal.Quotient.mk P) Ideal.Quotient.mk_surjective (I := I) (by simpa using hlt.le) refine IsPrime.to_maximal_ideal ?_ rw [ne_eq, Ideal.map_eq_bot_iff_le_ker, Ideal.mk_ker] exact hlt.not_ge have := Ideal.comap_isMaximal_of_surjective (Ideal.Quotient.mk P) Ideal.Quotient.mk_surjective (K := I.map (Ideal.Quotient.mk P)) simpa [Ideal.comap_map_of_surjective' (Ideal.Quotient.mk P) Ideal.Quotient.mk_surjective, hlt.le] using this theorem IsPrincipalIdealRing.ringKrullDim_eq_one (R : Type*) [CommRing R] [IsDomain R] [IsPrincipalIdealRing R] (h : ¬ IsField R) : ringKrullDim R = 1 := by apply eq_of_le_of_not_lt ?_ fun h' ↦ h ?_ · rw [← Nat.cast_one, ← Ring.krullDimLE_iff] infer_instance · have h'' : ringKrullDim R ≤ 0 := Order.le_of_lt_succ h' rw [← Nat.cast_zero, ← Ring.krullDimLE_iff] at h'' exact Ring.KrullDimLE.isField_of_isDomain
Basic.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov -/ import Mathlib.Logic.Function.Basic import Mathlib.Tactic.MkIffOfInductiveProp /-! # Additional lemmas about sum types Most of the former contents of this file have been moved to Batteries. -/ universe u v w x variable {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} {γ δ : Type*} lemma not_isLeft_and_isRight {x : α ⊕ β} : ¬(x.isLeft ∧ x.isRight) := by simp namespace Sum @[simp] theorem elim_swap {α β γ : Type*} {f : α → γ} {g : β → γ} : Sum.elim f g ∘ Sum.swap = Sum.elim g f := by ext x cases x with | inl x => simp | inr x => simp -- Lean has removed the `@[simp]` attribute on these. For now Mathlib adds it back. attribute [simp] Sum.forall Sum.exists theorem exists_sum {γ : α ⊕ β → Sort*} (p : (∀ ab, γ ab) → Prop) : (∃ fab, p fab) ↔ (∃ fa fb, p (Sum.rec fa fb)) := by rw [← not_forall_not, forall_sum] simp theorem inl_injective : Function.Injective (inl : α → α ⊕ β) := fun _ _ ↦ inl.inj theorem inr_injective : Function.Injective (inr : β → α ⊕ β) := fun _ _ ↦ inr.inj theorem sum_rec_congr (P : α ⊕ β → Sort*) (f : ∀ i, P (inl i)) (g : ∀ i, P (inr i)) {x y : α ⊕ β} (h : x = y) : @Sum.rec _ _ _ f g x = cast (congr_arg P h.symm) (@Sum.rec _ _ _ f g y) := by cases h; rfl section get variable {x : α ⊕ β} theorem eq_left_iff_getLeft_eq {a : α} : x = inl a ↔ ∃ h, x.getLeft h = a := by cases x <;> simp theorem eq_right_iff_getRight_eq {b : β} : x = inr b ↔ ∃ h, x.getRight h = b := by cases x <;> simp theorem getLeft_eq_getLeft? (h₁ : x.isLeft) (h₂ : x.getLeft?.isSome) : x.getLeft h₁ = x.getLeft?.get h₂ := by simp [← getLeft?_eq_some_iff] theorem getRight_eq_getRight? (h₁ : x.isRight) (h₂ : x.getRight?.isSome) : x.getRight h₁ = x.getRight?.get h₂ := by simp [← getRight?_eq_some_iff] @[simp] theorem isSome_getLeft?_iff_isLeft : x.getLeft?.isSome ↔ x.isLeft := by rw [isLeft_iff, Option.isSome_iff_exists]; simp @[simp] theorem isSome_getRight?_iff_isRight : x.getRight?.isSome ↔ x.isRight := by rw [isRight_iff, Option.isSome_iff_exists]; simp end get open Function (update update_eq_iff update_comp_eq_of_injective update_comp_eq_of_forall_ne) @[simp] theorem update_elim_inl [DecidableEq α] [DecidableEq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : α} {x : γ} : update (Sum.elim f g) (inl i) x = Sum.elim (update f i x) g := update_eq_iff.2 ⟨by simp, by simp +contextual⟩ @[simp] theorem update_elim_inr [DecidableEq β] [DecidableEq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : β} {x : γ} : update (Sum.elim f g) (inr i) x = Sum.elim f (update g i x) := update_eq_iff.2 ⟨by simp, by simp +contextual⟩ @[simp] theorem update_inl_comp_inl [DecidableEq α] [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inl = update (f ∘ inl) i x := update_comp_eq_of_injective _ inl_injective _ _ @[simp] theorem update_inl_apply_inl [DecidableEq α] [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i j : α} {x : γ} : update f (inl i) x (inl j) = update (f ∘ inl) i x j := by rw [← update_inl_comp_inl, Function.comp_apply] @[simp] theorem update_inl_comp_inr [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inr = f ∘ inr := (update_comp_eq_of_forall_ne _ _) fun _ ↦ inr_ne_inl theorem update_inl_apply_inr [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inl i) x (inr j) = f (inr j) := Function.update_of_ne inr_ne_inl .. @[simp] theorem update_inr_comp_inl [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inl = f ∘ inl := (update_comp_eq_of_forall_ne _ _) fun _ ↦ inl_ne_inr theorem update_inr_apply_inl [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inr j) x (inl i) = f (inl i) := Function.update_of_ne inl_ne_inr .. @[simp] theorem update_inr_comp_inr [DecidableEq β] [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inr = update (f ∘ inr) i x := update_comp_eq_of_injective _ inr_injective _ _ @[simp] theorem update_inr_apply_inr [DecidableEq β] [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i j : β} {x : γ} : update f (inr i) x (inr j) = update (f ∘ inr) i x j := by rw [← update_inr_comp_inr, Function.comp_apply] @[simp] theorem update_inl_apply_inl' {γ : α ⊕ β → Type*} [DecidableEq α] [DecidableEq (α ⊕ β)] {f : (i : α ⊕ β) → γ i} {i : α} {x : γ (.inl i)} (j : α) : update f (.inl i) x (Sum.inl j) = update (fun j ↦ f (.inl j)) i x j := Function.update_apply_of_injective f Sum.inl_injective i x j @[simp] theorem update_inr_apply_inr' {γ : α ⊕ β → Type*} [DecidableEq β] [DecidableEq (α ⊕ β)] {f : (i : α ⊕ β) → γ i} {i : β} {x : γ (.inr i)} (j : β) : update f (.inr i) x (Sum.inr j) = update (fun j ↦ f (.inr j)) i x j := Function.update_apply_of_injective f Sum.inr_injective i x j @[simp] lemma rec_update_left {γ : α ⊕ β → Sort*} [DecidableEq α] [DecidableEq β] (f : ∀ a, γ (.inl a)) (g : ∀ b, γ (.inr b)) (a : α) (x : γ (.inl a)) : Sum.rec (update f a x) g = update (Sum.rec f g) (.inl a) x := Function.rec_update Sum.inl_injective (Sum.rec · g) (fun _ _ => rfl) (fun | _, _, .inl _, h => (h _ rfl).elim | _, _, .inr _, _ => rfl) _ _ _ @[simp] lemma rec_update_right {γ : α ⊕ β → Sort*} [DecidableEq α] [DecidableEq β] (f : ∀ a, γ (.inl a)) (g : ∀ b, γ (.inr b)) (b : β) (x : γ (.inr b)) : Sum.rec f (update g b x) = update (Sum.rec f g) (.inr b) x := Function.rec_update Sum.inr_injective (Sum.rec f) (fun _ _ => rfl) (fun | _, _, .inr _, h => (h _ rfl).elim | _, _, .inl _, _ => rfl) _ _ _ @[simp] lemma elim_update_left {γ : Sort*} [DecidableEq α] [DecidableEq β] (f : α → γ) (g : β → γ) (a : α) (x : γ) : Sum.elim (update f a x) g = update (Sum.elim f g) (.inl a) x := rec_update_left _ _ _ _ @[simp] lemma elim_update_right {γ : Sort*} [DecidableEq α] [DecidableEq β] (f : α → γ) (g : β → γ) (b : β) (x : γ) : Sum.elim f (update g b x) = update (Sum.elim f g) (.inr b) x := rec_update_right _ _ _ _ @[simp] theorem swap_leftInverse : Function.LeftInverse (@swap α β) swap := swap_swap @[simp] theorem swap_rightInverse : Function.RightInverse (@swap α β) swap := swap_swap mk_iff_of_inductive_prop Sum.LiftRel Sum.liftRel_iff namespace LiftRel variable {r : α → γ → Prop} {s : β → δ → Prop} {x : α ⊕ β} {y : γ ⊕ δ} {a : α} {b : β} {c : γ} {d : δ} theorem isLeft_congr (h : LiftRel r s x y) : x.isLeft ↔ y.isLeft := by cases h <;> rfl theorem isRight_congr (h : LiftRel r s x y) : x.isRight ↔ y.isRight := by cases h <;> rfl theorem isLeft_left (h : LiftRel r s x (inl c)) : x.isLeft := by cases h; rfl theorem isLeft_right (h : LiftRel r s (inl a) y) : y.isLeft := by cases h; rfl theorem isRight_left (h : LiftRel r s x (inr d)) : x.isRight := by cases h; rfl theorem isRight_right (h : LiftRel r s (inr b) y) : y.isRight := by cases h; rfl theorem exists_of_isLeft_left (h₁ : LiftRel r s x y) (h₂ : x.isLeft) : ∃ a c, r a c ∧ x = inl a ∧ y = inl c := by rcases isLeft_iff.mp h₂ with ⟨_, rfl⟩ simp only [liftRel_iff, false_and, and_false, exists_false, or_false, reduceCtorEq] at h₁ exact h₁ theorem exists_of_isLeft_right (h₁ : LiftRel r s x y) (h₂ : y.isLeft) : ∃ a c, r a c ∧ x = inl a ∧ y = inl c := exists_of_isLeft_left h₁ ((isLeft_congr h₁).mpr h₂) theorem exists_of_isRight_left (h₁ : LiftRel r s x y) (h₂ : x.isRight) : ∃ b d, s b d ∧ x = inr b ∧ y = inr d := by rcases isRight_iff.mp h₂ with ⟨_, rfl⟩ simp only [liftRel_iff, false_and, and_false, exists_false, false_or, reduceCtorEq] at h₁ exact h₁ theorem exists_of_isRight_right (h₁ : LiftRel r s x y) (h₂ : y.isRight) : ∃ b d, s b d ∧ x = inr b ∧ y = inr d := exists_of_isRight_left h₁ ((isRight_congr h₁).mpr h₂) end LiftRel end Sum open Sum namespace Function theorem Injective.sumElim {γ : Sort*} {f : α → γ} {g : β → γ} (hf : Injective f) (hg : Injective g) (hfg : ∀ a b, f a ≠ g b) : Injective (Sum.elim f g) | inl _, inl _, h => congr_arg inl <| hf h | inl _, inr _, h => (hfg _ _ h).elim | inr _, inl _, h => (hfg _ _ h.symm).elim | inr _, inr _, h => congr_arg inr <| hg h @[deprecated (since := "2025-02-20")] alias Injective.sum_elim := Injective.sumElim theorem Injective.sumMap {f : α → β} {g : α' → β'} (hf : Injective f) (hg : Injective g) : Injective (Sum.map f g) | inl _, inl _, h => congr_arg inl <| hf <| inl.inj h | inr _, inr _, h => congr_arg inr <| hg <| inr.inj h @[deprecated (since := "2025-02-20")] alias Injective.sum_map := Injective.sumMap theorem Surjective.sumMap {f : α → β} {g : α' → β'} (hf : Surjective f) (hg : Surjective g) : Surjective (Sum.map f g) | inl y => let ⟨x, hx⟩ := hf y ⟨inl x, congr_arg inl hx⟩ | inr y => let ⟨x, hx⟩ := hg y ⟨inr x, congr_arg inr hx⟩ @[deprecated (since := "2025-02-20")] alias Surjective.sum_map := Surjective.sumMap theorem Bijective.sumMap {f : α → β} {g : α' → β'} (hf : Bijective f) (hg : Bijective g) : Bijective (Sum.map f g) := ⟨hf.injective.sumMap hg.injective, hf.surjective.sumMap hg.surjective⟩ @[deprecated (since := "2025-02-20")] alias Bijective.sum_map := Bijective.sumMap end Function namespace Sum open Function @[simp] theorem elim_injective {γ : Sort*} {f : α → γ} {g : β → γ} : Injective (Sum.elim f g) ↔ Injective f ∧ Injective g ∧ ∀ a b, f a ≠ g b where mp h := ⟨h.comp inl_injective, h.comp inr_injective, fun _ _ => h.ne inl_ne_inr⟩ mpr | ⟨hf, hg, hfg⟩ => hf.sumElim hg hfg @[simp] theorem map_injective {f : α → γ} {g : β → δ} : Injective (Sum.map f g) ↔ Injective f ∧ Injective g where mp h := ⟨.of_comp <| h.comp inl_injective, .of_comp <| h.comp inr_injective⟩ mpr | ⟨hf, hg⟩ => hf.sumMap hg @[simp] theorem map_surjective {f : α → γ} {g : β → δ} : Surjective (Sum.map f g) ↔ Surjective f ∧ Surjective g where mp h := ⟨ (fun c => by obtain ⟨a | b, h⟩ := h (inl c) · exact ⟨a, inl_injective h⟩ · cases h), (fun d => by obtain ⟨a | b, h⟩ := h (inr d) · cases h · exact ⟨b, inr_injective h⟩)⟩ mpr | ⟨hf, hg⟩ => hf.sumMap hg @[simp] theorem map_bijective {f : α → γ} {g : β → δ} : Bijective (Sum.map f g) ↔ Bijective f ∧ Bijective g := (map_injective.and map_surjective).trans <| and_and_and_comm end Sum /-! ### Ternary sum Abbreviations for the maps from the summands to `α ⊕ β ⊕ γ`. This is useful for pattern-matching. -/ namespace Sum3 /-- The map from the first summand into a ternary sum. -/ @[match_pattern, simp, reducible] def in₀ (a : α) : α ⊕ (β ⊕ γ) := inl a /-- The map from the second summand into a ternary sum. -/ @[match_pattern, simp, reducible] def in₁ (b : β) : α ⊕ (β ⊕ γ) := inr <| inl b /-- The map from the third summand into a ternary sum. -/ @[match_pattern, simp, reducible] def in₂ (c : γ) : α ⊕ (β ⊕ γ) := inr <| inr c end Sum3 /-! ### PSum -/ namespace PSum variable {α β : Sort*} theorem inl_injective : Function.Injective (PSum.inl : α → α ⊕' β) := fun _ _ ↦ inl.inj theorem inr_injective : Function.Injective (PSum.inr : β → α ⊕' β) := fun _ _ ↦ inr.inj end PSum
Functorial.lean
/- Copyright (c) 2025 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.AlgebraicGeometry.Morphisms.ClosedImmersion import Mathlib.AlgebraicGeometry.PullbackCarrier /-! # Functorial constructions of ideal sheaves We define the pullback and pushforward of ideal sheaves in this file. ## Main definitions - `AlgebraicGeometry.Scheme.IdealSheafData.comap`: The pullback of an ideal sheaf. - `AlgebraicGeometry.Scheme.IdealSheafData.map`: The pushforward of an ideal sheaf. - `AlgebraicGeometry.Scheme.IdealSheafData.map_gc`: The galois connection between pullback and pushforward. -/ noncomputable section universe u open CategoryTheory Limits namespace AlgebraicGeometry variable {X Y Z : Scheme.{u}} namespace Scheme.IdealSheafData /-- The pullback of an ideal sheaf. -/ def comap (I : Y.IdealSheafData) (f : X ⟶ Y) : X.IdealSheafData := (pullback.fst f I.subschemeι).ker /-- The subscheme associated to the pullback ideal sheaf is isomorphic to the fibred product. -/ def comapIso (I : Y.IdealSheafData) (f : X ⟶ Y) : (I.comap f).subscheme ≅ pullback f I.subschemeι := (asIso (pullback.fst f I.subschemeι).toImage).symm @[reassoc (attr := simp)] lemma comapIso_inv_subschemeι (I : Y.IdealSheafData) (f : X ⟶ Y) : (I.comapIso f).inv ≫ (I.comap f).subschemeι = pullback.fst _ _ := (pullback.fst f I.subschemeι).toImage_imageι @[reassoc (attr := simp)] lemma comapIso_hom_fst (I : Y.IdealSheafData) (f : X ⟶ Y) : (I.comapIso f).hom ≫ pullback.fst _ _ = (I.comap f).subschemeι := by rw [← comapIso_inv_subschemeι, Iso.hom_inv_id_assoc] @[simp] lemma comap_comp (I : Z.IdealSheafData) (f : X ⟶ Y) (g : Y ⟶ Z) : I.comap (f ≫ g) = (I.comap g).comap f := by let e : pullback f (I.comap g).subschemeι ≅ pullback (f ≫ g) I.subschemeι := asIso (pullback.map _ _ _ _ (𝟙 _) (I.comapIso g).hom (𝟙 _) (by simp) (by simp)) ≪≫ pullbackRightPullbackFstIso _ _ _ rw [comap, comap, ← Scheme.Hom.ker_comp_of_isIso e.hom] simp [e] @[simp] lemma comap_id (I : Z.IdealSheafData) : I.comap (𝟙 _) = I := by rw [comap, ← Scheme.Hom.ker_comp_of_isIso (inv (pullback.snd _ _)), pullback_inv_snd_fst_of_left_isIso, IsIso.inv_id, Category.comp_id, ker_subschemeι] @[simp] lemma support_comap (I : Y.IdealSheafData) (f : X ⟶ Y) : (I.comap f).support = I.support.preimage f.continuous := by ext1 rw [comap, Scheme.Hom.support_ker, Pullback.range_fst, range_subschemeι, TopologicalSpace.Closeds.coe_preimage, (I.support.isClosed.preimage f.continuous).closure_eq] /-- The pushforward of an ideal sheaf. -/ def map (I : X.IdealSheafData) (f : X ⟶ Y) : Y.IdealSheafData := (I.subschemeι ≫ f).ker lemma le_map_iff_comap_le {I : X.IdealSheafData} {f : X ⟶ Y} {J : Y.IdealSheafData} : J ≤ I.map f ↔ J.comap f ≤ I := by constructor · intro H rw [← I.ker_subschemeι, ← pullback.lift_fst (f := f) (g := J.subschemeι) I.subschemeι ((I.subschemeι ≫ f).toImage ≫ inclusion H) (by simp)] exact Hom.le_ker_comp _ _ · intro H have : (inclusion H ≫ (J.comapIso f).hom ≫ pullback.snd _ _) ≫ J.subschemeι = I.subschemeι ≫ f := by simp [← pullback.condition] rw [map, ← J.ker_subschemeι, ← this] exact Hom.le_ker_comp _ _ section gc variable (I I₁ I₂ : X.IdealSheafData) (J J₁ J₂ : Y.IdealSheafData) (f : X ⟶ Y) /-- Pushforward and pullback of ideal sheaves forms a galois connection. -/ lemma map_gc : GaloisConnection (comap · f) (map · f) := fun _ _ ↦ le_map_iff_comap_le.symm set_option linter.style.commandStart false lemma map_mono : Monotone (map · f) := (map_gc f).monotone_u lemma comap_mono : Monotone (comap · f) := (map_gc f).monotone_l lemma le_map_comap : J ≤ (J.comap f).map f := (map_gc f).le_u_l J lemma comap_map_le : (I.map f).comap f ≤ I := (map_gc f).l_u_le I @[simp] lemma map_top : map ⊤ f = ⊤ := (map_gc f).u_top @[simp] lemma comap_bot : comap ⊥ f = ⊥ := (map_gc f).l_bot @[simp] lemma map_inf : map (I₁ ⊓ I₂) f = map I₁ f ⊓ map I₂ f := (map_gc f).u_inf @[simp] lemma comap_sup : comap (J₁ ⊔ J₂) f = comap J₁ f ⊔ comap J₂ f := (map_gc f).l_sup set_option linter.style.commandStart true end gc @[simp] lemma map_bot (f : X ⟶ Y) : map ⊥ f = f.ker := by simp [map, Scheme.Hom.ker_comp_of_isIso] @[simp] lemma comap_top (f : X ⟶ Y) : comap ⊤ f = ⊤ := by rw [comap, Hom.ker_eq_top_iff_isEmpty] exact Function.isEmpty (pullback.snd f _).base @[simp] lemma map_comp (I : X.IdealSheafData) (f : X ⟶ Y) (g : Y ⟶ Z) : I.map (f ≫ g) = (I.map f).map g := by apply le_antisymm · rw [le_map_iff_comap_le, le_map_iff_comap_le, ← comap_comp]; exact comap_map_le _ _ · rw [le_map_iff_comap_le, comap_comp] exact (comap_mono _ (comap_map_le _ _)).trans (comap_map_le _ _) @[simp] lemma map_id (I : Z.IdealSheafData) : I.map (𝟙 _) = I := by simp [map] lemma map_ker (f : X ⟶ Y) (g : Y ⟶ Z) : f.ker.map g = (f ≫ g).ker := by simp [← map_bot] lemma _root_.AlgebraicGeometry.Scheme.Hom.ker_comp (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).ker = f.ker.map g := (map_ker f g).symm lemma map_vanishingIdeal {X Y : Scheme} (f : X ⟶ Y) (Z : TopologicalSpace.Closeds X) : (vanishingIdeal Z).map f = vanishingIdeal (.closure (f.base '' Z)) := by apply le_antisymm · rw [map, ← le_support_iff_le_vanishingIdeal, TopologicalSpace.Closeds.closure_le] refine .trans ?_ (Hom.range_subset_ker_support _) rw [Scheme.comp_base, TopCat.coe_comp, Set.range_comp, range_subschemeι, coe_support_vanishingIdeal] · simp [le_map_iff_comap_le, ← le_support_iff_le_vanishingIdeal, ← Set.image_subset_iff, subset_closure, ← SetLike.coe_subset_coe] @[simp] lemma support_map (I : X.IdealSheafData) (f : X ⟶ Y) [QuasiCompact f] : (I.map f).support = .closure (f.base '' I.support) := by ext1 rw [map, Scheme.Hom.support_ker, Scheme.comp_base, TopCat.coe_comp, Set.range_comp, range_subschemeι, TopologicalSpace.Closeds.coe_closure] lemma ideal_map (I : X.IdealSheafData) (f : X ⟶ Y) [QuasiCompact f] (U : Y.affineOpens) (H : IsAffineOpen (f ⁻¹ᵁ U)) : (I.map f).ideal U = (I.ideal ⟨_, H⟩).comap (f.app U).hom := by have : RingHom.ker (I.subschemeObjIso ⟨_, H⟩).inv.hom = ⊥ := RingHom.ker_coe_equiv (I.subschemeObjIso ⟨_, H⟩).symm.commRingCatIsoToRingEquiv simp [map, ← RingHom.comap_ker, subschemeι_app _ ⟨_, H⟩, this, ← RingHom.ker_eq_comap_bot] lemma ideal_map_of_isAffineHom (I : X.IdealSheafData) (f : X ⟶ Y) [IsAffineHom f] (U : Y.affineOpens) : (I.map f).ideal U = (I.ideal ⟨_, U.2.preimage f⟩).comap (f.app U).hom := ideal_map I f U (U.2.preimage f) lemma ideal_comap_of_isOpenImmersion (I : Y.IdealSheafData) (f : X ⟶ Y) [IsOpenImmersion f] (U : X.affineOpens) : (I.comap f).ideal U = (I.ideal ⟨f ''ᵁ U, U.2.image_of_isOpenImmersion f⟩).comap (f.appIso U).inv.hom := by refine (ker_ideal_of_isPullback_of_isOpenImmersion _ _ _ _ (IsPullback.of_hasPullback f I.subschemeι) U).trans ?_ simp /-- If `J ≤ I.map f`, then `f` restricts to a map `I ⟶ J` between the closed subschemes. -/ def subschemeMap (I : X.IdealSheafData) (J : Y.IdealSheafData) (f : X ⟶ Y) (H : J ≤ I.map f) : I.subscheme ⟶ J.subscheme := IsClosedImmersion.lift J.subschemeι (I.subschemeι ≫ f) (by simpa using H) @[reassoc (attr := simp)] lemma subschemeMap_subschemeι (I : X.IdealSheafData) (J : Y.IdealSheafData) (f : X ⟶ Y) (H : J ≤ I.map f) : subschemeMap I J f H ≫ J.subschemeι = I.subschemeι ≫ f := IsClosedImmersion.lift_fac _ _ _ @[reassoc (attr := simp)] lemma comapIso_hom_snd (I : Y.IdealSheafData) (f : X ⟶ Y) : (I.comapIso f).hom ≫ pullback.snd _ _ = subschemeMap _ _ f (I.le_map_comap f) := by rw [← cancel_mono I.subschemeι] simp [← pullback.condition] end Scheme.IdealSheafData end AlgebraicGeometry
path.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq. (******************************************************************************) (* The basic theory of paths over an eqType; this file is essentially a *) (* complement to seq.v. Paths are non-empty sequences that obey a progression *) (* relation. They are passed around in three parts: the head and tail of the *) (* sequence, and a proof of a (boolean) predicate asserting the progression. *) (* This "exploded" view is rarely embarrassing, as the first two parameters *) (* are usually inferred from the type of the third; on the contrary, it saves *) (* the hassle of constantly constructing and destructing a dependent record. *) (* We define similarly cycles, for which we allow the empty sequence, *) (* which represents a non-rooted empty cycle; by contrast, the "empty" path *) (* from a point x is the one-item sequence containing only x. *) (* We allow duplicates; uniqueness, if desired (as is the case for several *) (* geometric constructions), must be asserted separately. We do provide *) (* shorthand, but only for cycles, because the equational properties of *) (* "path" and "uniq" are unfortunately incompatible (esp. wrt "cat"). *) (* We define notations for the common cases of function paths, where the *) (* progress relation is actually a function. In detail: *) (* path e x p == x :: p is an e-path [:: x_0; x_1; ... ; x_n], i.e., we *) (* have e x_i x_{i+1} for all i < n. The path x :: p starts *) (* at x and ends at last x p. *) (* fpath f x p == x :: p is an f-path, where f is a function, i.e., p is of *) (* the form [:: f x; f (f x); ...]. This is just a notation *) (* for path (frel f) x p. *) (* sorted e s == s is an e-sorted sequence: either s = [::], or s = x :: p *) (* is an e-path (this is often used with e = leq or ltn). *) (* cycle e c == c is an e-cycle: either c = [::], or c = x :: p with *) (* x :: (rcons p x) an e-path. *) (* fcycle f c == c is an f-cycle, for a function f. *) (* traject f x n == the f-path of size n starting at x *) (* := [:: x; f x; ...; iter n.-1 f x] *) (* looping f x n == the f-paths of size greater than n starting at x loop *) (* back, or, equivalently, traject f x n contains all *) (* iterates of f at x. *) (* merge e s1 s2 == the e-sorted merge of sequences s1 and s2: this is always *) (* a permutation of s1 ++ s2, and is e-sorted when s1 and s2 *) (* are and e is total. *) (* sort e s == a permutation of the sequence s, that is e-sorted when e *) (* is total (computed by a merge sort with the merge function *) (* above). This sort function is also designed to be stable. *) (* mem2 s x y == x, then y occur in the sequence (path) s; this is *) (* non-strict: mem2 s x x = (x \in s). *) (* next c x == the successor of the first occurrence of x in the sequence *) (* c (viewed as a cycle), or x if x \notin c. *) (* prev c x == the predecessor of the first occurrence of x in the *) (* sequence c (viewed as a cycle), or x if x \notin c. *) (* arc c x y == the sub-arc of the sequence c (viewed as a cycle) starting *) (* at the first occurrence of x in c, and ending just before *) (* the next occurrence of y (in cycle order); arc c x y *) (* returns an unspecified sub-arc of c if x and y do not both *) (* occur in c. *) (* ucycle e c <-> ucycleb e c (ucycle e c is a Coercion target of type Prop) *) (* ufcycle f c <-> c is a simple f-cycle, for a function f. *) (* shorten x p == the tail a duplicate-free subpath of x :: p with the same *) (* endpoints (x and last x p), obtained by removing all loops *) (* from x :: p. *) (* rel_base e e' h b <-> the function h is a functor from relation e to *) (* relation e', EXCEPT at points whose image under h satisfy *) (* the "base" predicate b: *) (* e' (h x) (h y) = e x y UNLESS b (h x) holds *) (* This is the statement of the side condition of the path *) (* functorial mapping lemma map_path. *) (* fun_base f f' h b <-> the function h is a functor from function f to f', *) (* except at the preimage of predicate b under h. *) (* We also provide three segmenting dependently-typed lemmas (splitP, splitPl *) (* and splitPr) whose elimination split a path x0 :: p at an internal point x *) (* as follows: *) (* - splitP applies when x \in p; it replaces p with (rcons p1 x ++ p2), so *) (* that x appears explicitly at the end of the left part. The elimination *) (* of splitP will also simultaneously replace take (index x p) with p1 and *) (* drop (index x p).+1 p with p2. *) (* - splitPl applies when x \in x0 :: p; it replaces p with p1 ++ p2 and *) (* simultaneously generates an equation x = last x0 p1. *) (* - splitPr applies when x \in p; it replaces p with (p1 ++ x :: p2), so x *) (* appears explicitly at the start of the right part. *) (* The parts p1 and p2 are computed using index/take/drop in all cases, but *) (* only splitP attempts to substitute the explicit values. The substitution *) (* of p can be deferred using the dependent equation generation feature of *) (* ssreflect, e.g.: case/splitPr def_p: {1}p / x_in_p => [p1 p2] generates *) (* the equation p = p1 ++ p2 instead of performing the substitution outright. *) (* Similarly, eliminating the loop removal lemma shortenP simultaneously *) (* replaces shorten e x p with a fresh constant p', and last x p with *) (* last x p'. *) (* Note that although all "path" functions actually operate on the *) (* underlying sequence, we provide a series of lemmas that define their *) (* interaction with the path and cycle predicates, e.g., the cat_path equation*) (* can be used to split the path predicate after splitting the underlying *) (* sequence. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Section Paths. Variables (n0 : nat) (T : Type). Section Path. Variables (x0_cycle : T) (e : rel T). Fixpoint path x (p : seq T) := if p is y :: p' then e x y && path y p' else true. Lemma cat_path x p1 p2 : path x (p1 ++ p2) = path x p1 && path (last x p1) p2. Proof. by elim: p1 x => [|y p1 Hrec] x //=; rewrite Hrec -!andbA. Qed. Lemma rcons_path x p y : path x (rcons p y) = path x p && e (last x p) y. Proof. by rewrite -cats1 cat_path /= andbT. Qed. Lemma take_path x p i : path x p -> path x (take i p). Proof. elim: p x i => [//| x p] IHp x' [//| i] /= /andP[-> ?]; exact: IHp. Qed. Lemma pathP x p x0 : reflect (forall i, i < size p -> e (nth x0 (x :: p) i) (nth x0 p i)) (path x p). Proof. elim: p x => [|y p IHp] x /=; first by left. apply: (iffP andP) => [[e_xy /IHp e_p [] //] | e_p]. by split; [apply: (e_p 0) | apply/(IHp y) => i; apply: e_p i.+1]. Qed. Definition cycle p := if p is x :: p' then path x (rcons p' x) else true. Lemma cycle_path p : cycle p = path (last x0_cycle p) p. Proof. by case: p => //= x p; rewrite rcons_path andbC. Qed. Lemma cycle_catC p q : cycle (p ++ q) = cycle (q ++ p). Proof. case: p q => [|x p] [|y q]; rewrite /= ?cats0 //=. by rewrite !rcons_path !cat_path !last_cat /= -!andbA; do !bool_congr. Qed. Lemma rot_cycle p : cycle (rot n0 p) = cycle p. Proof. by rewrite cycle_catC cat_take_drop. Qed. Lemma rotr_cycle p : cycle (rotr n0 p) = cycle p. Proof. by rewrite -rot_cycle rotrK. Qed. Definition sorted s := if s is x :: s' then path x s' else true. Lemma sortedP s x : reflect (forall i, i.+1 < size s -> e (nth x s i) (nth x s i.+1)) (sorted s). Proof. by case: s => *; [constructor|apply: (iffP (pathP _ _ _)); apply]. Qed. Lemma path_sorted x s : path x s -> sorted s. Proof. by case: s => //= y s /andP[]. Qed. Lemma path_min_sorted x s : all (e x) s -> path x s = sorted s. Proof. by case: s => //= y s /andP [->]. Qed. Lemma pairwise_sorted s : pairwise e s -> sorted s. Proof. by elim: s => //= x s IHs /andP[/path_min_sorted -> /IHs]. Qed. Lemma sorted_cat_cons s1 x s2 : sorted (s1 ++ x :: s2) = sorted (rcons s1 x) && path x s2. Proof. by case: s1 => [ | e1 s1] //=; rewrite -cat_rcons cat_path last_rcons. Qed. End Path. Section PathEq. Variables (e e' : rel T). Lemma rev_path x p : path e (last x p) (rev (belast x p)) = path (fun z => e^~ z) x p. Proof. elim: p x => //= y p IHp x; rewrite rev_cons rcons_path -{}IHp andbC. by rewrite -(last_cons x) -rev_rcons -lastI rev_cons last_rcons. Qed. Lemma rev_cycle p : cycle e (rev p) = cycle (fun z => e^~ z) p. Proof. case: p => //= x p; rewrite -rev_path last_rcons belast_rcons rev_cons. by rewrite -[in LHS]cats1 cycle_catC. Qed. Lemma rev_sorted p : sorted e (rev p) = sorted (fun z => e^~ z) p. Proof. by case: p => //= x p; rewrite -rev_path lastI rev_rcons. Qed. Lemma path_relI x s : path [rel x y | e x y && e' x y] x s = path e x s && path e' x s. Proof. by elim: s x => //= y s IHs x; rewrite andbACA IHs. Qed. Lemma cycle_relI s : cycle [rel x y | e x y && e' x y] s = cycle e s && cycle e' s. Proof. by case: s => [|? ?]; last apply: path_relI. Qed. Lemma sorted_relI s : sorted [rel x y | e x y && e' x y] s = sorted e s && sorted e' s. Proof. by case: s; last apply: path_relI. Qed. End PathEq. Section SubPath_in. Variable (P : {pred T}) (e e' : rel T). Hypothesis (ee' : {in P &, subrel e e'}). Lemma sub_in_path x s : all P (x :: s) -> path e x s -> path e' x s. Proof. by elim: s x => //= y s ihs x /and3P [? ? ?] /andP [/ee' -> //]; apply/ihs/andP. Qed. Lemma sub_in_cycle s : all P s -> cycle e s -> cycle e' s. Proof. case: s => //= x s /andP [Px Ps]. by apply: sub_in_path; rewrite /= all_rcons Px. Qed. Lemma sub_in_sorted s : all P s -> sorted e s -> sorted e' s. Proof. by case: s => //; apply: sub_in_path. Qed. End SubPath_in. Section EqPath_in. Variable (P : {pred T}) (e e' : rel T). Hypothesis (ee' : {in P &, e =2 e'}). Let e_e' : {in P &, subrel e e'}. Proof. by move=> ? ? ? ?; rewrite ee'. Qed. Let e'_e : {in P &, subrel e' e}. Proof. by move=> ? ? ? ?; rewrite ee'. Qed. Lemma eq_in_path x s : all P (x :: s) -> path e x s = path e' x s. Proof. by move=> Pxs; apply/idP/idP; apply: sub_in_path Pxs. Qed. Lemma eq_in_cycle s : all P s -> cycle e s = cycle e' s. Proof. by move=> Ps; apply/idP/idP; apply: sub_in_cycle Ps. Qed. Lemma eq_in_sorted s : all P s -> sorted e s = sorted e' s. Proof. by move=> Ps; apply/idP/idP; apply: sub_in_sorted Ps. Qed. End EqPath_in. Section SubPath. Variables e e' : rel T. Lemma sub_path : subrel e e' -> forall x p, path e x p -> path e' x p. Proof. by move=> ? ? ?; apply/sub_in_path/all_predT; apply: in2W. Qed. Lemma sub_cycle : subrel e e' -> subpred (cycle e) (cycle e'). Proof. by move=> ee' [] // ? ?; apply: sub_path. Qed. Lemma sub_sorted : subrel e e' -> subpred (sorted e) (sorted e'). Proof. by move=> ee' [] //=; apply: sub_path. Qed. Lemma eq_path : e =2 e' -> path e =2 path e'. Proof. by move=> ? ? ?; apply/eq_in_path/all_predT; apply: in2W. Qed. Lemma eq_cycle : e =2 e' -> cycle e =1 cycle e'. Proof. by move=> ee' [] // ? ?; apply: eq_path. Qed. Lemma eq_sorted : e =2 e' -> sorted e =1 sorted e'. Proof. by move=> ee' [] // ? ?; apply: eq_path. Qed. End SubPath. Section Transitive_in. Variables (P : {pred T}) (leT : rel T). Lemma order_path_min_in x s : {in P & &, transitive leT} -> all P (x :: s) -> path leT x s -> all (leT x) s. Proof. move=> leT_tr; elim: s => //= y s ihs /and3P [Px Py Ps] /andP [xy ys]. rewrite xy {}ihs ?Px //=; case: s Ps ys => //= z s /andP [Pz Ps] /andP [yz ->]. by rewrite (leT_tr _ _ _ Py Px Pz). Qed. Hypothesis leT_tr : {in P & &, transitive leT}. Lemma path_sorted_inE x s : all P (x :: s) -> path leT x s = all (leT x) s && sorted leT s. Proof. move=> Pxs; apply/idP/idP => [xs|/andP[/path_min_sorted<-//]]. by rewrite (order_path_min_in leT_tr) //; apply: path_sorted xs. Qed. Lemma sorted_pairwise_in s : all P s -> sorted leT s = pairwise leT s. Proof. by elim: s => //= x s IHs /andP [Px Ps]; rewrite path_sorted_inE ?IHs //= Px. Qed. Lemma path_pairwise_in x s : all P (x :: s) -> path leT x s = pairwise leT (x :: s). Proof. by move=> Pxs; rewrite -sorted_pairwise_in. Qed. Lemma cat_sorted2 s s' : sorted leT (s ++ s') -> sorted leT s * sorted leT s'. Proof. by case: s => //= x s; rewrite cat_path => /andP[-> /path_sorted]. Qed. Lemma sorted_mask_in m s : all P s -> sorted leT s -> sorted leT (mask m s). Proof. by move=> Ps; rewrite !sorted_pairwise_in ?all_mask //; exact: pairwise_mask. Qed. Lemma sorted_filter_in a s : all P s -> sorted leT s -> sorted leT (filter a s). Proof. rewrite filter_mask; exact: sorted_mask_in. Qed. Lemma path_mask_in x m s : all P (x :: s) -> path leT x s -> path leT x (mask m s). Proof. exact/(sorted_mask_in (true :: m)). Qed. Lemma path_filter_in x a s : all P (x :: s) -> path leT x s -> path leT x (filter a s). Proof. by move=> Pxs; rewrite filter_mask; exact: path_mask_in. Qed. Lemma sorted_ltn_nth_in x0 s : all P s -> sorted leT s -> {in [pred n | n < size s] &, {homo nth x0 s : i j / i < j >-> leT i j}}. Proof. by move=> Ps; rewrite sorted_pairwise_in //; apply/pairwiseP. Qed. Hypothesis leT_refl : {in P, reflexive leT}. Lemma sorted_leq_nth_in x0 s : all P s -> sorted leT s -> {in [pred n | n < size s] &, {homo nth x0 s : i j / i <= j >-> leT i j}}. Proof. move=> Ps s_sorted x y xs ys; rewrite leq_eqVlt=> /predU1P[->|]. exact/leT_refl/all_nthP. exact: sorted_ltn_nth_in. Qed. End Transitive_in. Section Transitive. Variable (leT : rel T). Lemma order_path_min x s : transitive leT -> path leT x s -> all (leT x) s. Proof. by move=> leT_tr; apply/order_path_min_in/all_predT => //; apply: in3W. Qed. Hypothesis leT_tr : transitive leT. Lemma path_le x x' s : leT x x' -> path leT x' s -> path leT x s. Proof. by case: s => [//| x'' s xlex' /= /andP[x'lex'' ->]]; rewrite (leT_tr xlex'). Qed. Let leT_tr' : {in predT & &, transitive leT}. Proof. exact: in3W. Qed. Lemma path_sortedE x s : path leT x s = all (leT x) s && sorted leT s. Proof. exact/path_sorted_inE/all_predT. Qed. Lemma sorted_pairwise s : sorted leT s = pairwise leT s. Proof. exact/sorted_pairwise_in/all_predT. Qed. Lemma path_pairwise x s : path leT x s = pairwise leT (x :: s). Proof. exact/path_pairwise_in/all_predT. Qed. Lemma sorted_mask m s : sorted leT s -> sorted leT (mask m s). Proof. exact/sorted_mask_in/all_predT. Qed. Lemma sorted_filter a s : sorted leT s -> sorted leT (filter a s). Proof. exact/sorted_filter_in/all_predT. Qed. Lemma path_mask x m s : path leT x s -> path leT x (mask m s). Proof. exact/path_mask_in/all_predT. Qed. Lemma path_filter x a s : path leT x s -> path leT x (filter a s). Proof. exact/path_filter_in/all_predT. Qed. Lemma sorted_ltn_nth x0 s : sorted leT s -> {in [pred n | n < size s] &, {homo nth x0 s : i j / i < j >-> leT i j}}. Proof. exact/sorted_ltn_nth_in/all_predT. Qed. Hypothesis leT_refl : reflexive leT. Lemma sorted_leq_nth x0 s : sorted leT s -> {in [pred n | n < size s] &, {homo nth x0 s : i j / i <= j >-> leT i j}}. Proof. exact/sorted_leq_nth_in/all_predT. Qed. Lemma take_sorted n s : sorted leT s -> sorted leT (take n s). Proof. by rewrite -[s in sorted _ s](cat_take_drop n) => /cat_sorted2[]. Qed. Lemma drop_sorted n s : sorted leT s -> sorted leT (drop n s). Proof. by rewrite -[s in sorted _ s](cat_take_drop n) => /cat_sorted2[]. Qed. End Transitive. End Paths. Arguments pathP {T e x p}. Arguments sortedP {T e s}. Arguments path_sorted {T e x s}. Arguments path_min_sorted {T e x s}. Arguments order_path_min_in {T P leT x s}. Arguments path_sorted_inE {T P leT} leT_tr {x s}. Arguments sorted_pairwise_in {T P leT} leT_tr {s}. Arguments path_pairwise_in {T P leT} leT_tr {x s}. Arguments sorted_mask_in {T P leT} leT_tr {m s}. Arguments sorted_filter_in {T P leT} leT_tr {a s}. Arguments path_mask_in {T P leT} leT_tr {x m s}. Arguments path_filter_in {T P leT} leT_tr {x a s}. Arguments sorted_ltn_nth_in {T P leT} leT_tr x0 {s}. Arguments sorted_leq_nth_in {T P leT} leT_tr leT_refl x0 {s}. Arguments order_path_min {T leT x s}. Arguments path_sortedE {T leT} leT_tr x s. Arguments sorted_pairwise {T leT} leT_tr s. Arguments path_pairwise {T leT} leT_tr x s. Arguments sorted_mask {T leT} leT_tr m {s}. Arguments sorted_filter {T leT} leT_tr a {s}. Arguments path_mask {T leT} leT_tr {x} m {s}. Arguments path_filter {T leT} leT_tr {x} a {s}. Arguments sorted_ltn_nth {T leT} leT_tr x0 {s}. Arguments sorted_leq_nth {T leT} leT_tr leT_refl x0 {s}. Section HomoPath. Variables (T T' : Type) (P : {pred T}) (f : T -> T') (e : rel T) (e' : rel T'). Lemma path_map x s : path e' (f x) (map f s) = path (relpre f e') x s. Proof. by elim: s x => //= y s <-. Qed. Lemma cycle_map s : cycle e' (map f s) = cycle (relpre f e') s. Proof. by case: s => //= ? ?; rewrite -map_rcons path_map. Qed. Lemma sorted_map s : sorted e' (map f s) = sorted (relpre f e') s. Proof. by case: s; last apply: path_map. Qed. Lemma homo_path_in x s : {in P &, {homo f : x y / e x y >-> e' x y}} -> all P (x :: s) -> path e x s -> path e' (f x) (map f s). Proof. by move=> f_mono; rewrite path_map; apply: sub_in_path. Qed. Lemma homo_cycle_in s : {in P &, {homo f : x y / e x y >-> e' x y}} -> all P s -> cycle e s -> cycle e' (map f s). Proof. by move=> f_mono; rewrite cycle_map; apply: sub_in_cycle. Qed. Lemma homo_sorted_in s : {in P &, {homo f : x y / e x y >-> e' x y}} -> all P s -> sorted e s -> sorted e' (map f s). Proof. by move=> f_mono; rewrite sorted_map; apply: sub_in_sorted. Qed. Lemma mono_path_in x s : {in P &, {mono f : x y / e x y >-> e' x y}} -> all P (x :: s) -> path e' (f x) (map f s) = path e x s. Proof. by move=> f_mono; rewrite path_map; apply: eq_in_path. Qed. Lemma mono_cycle_in s : {in P &, {mono f : x y / e x y >-> e' x y}} -> all P s -> cycle e' (map f s) = cycle e s. Proof. by move=> f_mono; rewrite cycle_map; apply: eq_in_cycle. Qed. Lemma mono_sorted_in s : {in P &, {mono f : x y / e x y >-> e' x y}} -> all P s -> sorted e' (map f s) = sorted e s. Proof. by case: s => // x s; apply: mono_path_in. Qed. Lemma homo_path x s : {homo f : x y / e x y >-> e' x y} -> path e x s -> path e' (f x) (map f s). Proof. by move=> f_homo; rewrite path_map; apply: sub_path. Qed. Lemma homo_cycle : {homo f : x y / e x y >-> e' x y} -> {homo map f : s / cycle e s >-> cycle e' s}. Proof. by move=> f_homo s hs; rewrite cycle_map (sub_cycle _ hs). Qed. Lemma homo_sorted : {homo f : x y / e x y >-> e' x y} -> {homo map f : s / sorted e s >-> sorted e' s}. Proof. by move/homo_path => ? []. Qed. Lemma mono_path x s : {mono f : x y / e x y >-> e' x y} -> path e' (f x) (map f s) = path e x s. Proof. by move=> f_mon; rewrite path_map; apply: eq_path. Qed. Lemma mono_cycle : {mono f : x y / e x y >-> e' x y} -> {mono map f : s / cycle e s >-> cycle e' s}. Proof. by move=> ? ?; rewrite cycle_map; apply: eq_cycle. Qed. Lemma mono_sorted : {mono f : x y / e x y >-> e' x y} -> {mono map f : s / sorted e s >-> sorted e' s}. Proof. by move=> f_mon [] //= x s; apply: mono_path. Qed. End HomoPath. Arguments path_map {T T' f e'}. Arguments cycle_map {T T' f e'}. Arguments sorted_map {T T' f e'}. Arguments homo_path_in {T T' P f e e' x s}. Arguments homo_cycle_in {T T' P f e e' s}. Arguments homo_sorted_in {T T' P f e e' s}. Arguments mono_path_in {T T' P f e e' x s}. Arguments mono_cycle_in {T T' P f e e' s}. Arguments mono_sorted_in {T T' P f e e' s}. Arguments homo_path {T T' f e e' x s}. Arguments homo_cycle {T T' f e e'}. Arguments homo_sorted {T T' f e e'}. Arguments mono_path {T T' f e e' x s}. Arguments mono_cycle {T T' f e e'}. Arguments mono_sorted {T T' f e e'}. Section CycleAll2Rel. Lemma cycle_all2rel (T : Type) (leT : rel T) : transitive leT -> forall s, cycle leT s = all2rel leT s. Proof. move=> leT_tr; elim=> //= x s IHs. rewrite allrel_cons2 -{}IHs // (path_sortedE leT_tr) /= all_rcons -rev_sorted. rewrite rev_rcons /= (path_sortedE (rev_trans leT_tr)) all_rev !andbA. case: (boolP (leT x x && _ && _)) => //=. case: s => //= y s /and3P[/and3P[_ xy _] yx sx]. rewrite rev_sorted rcons_path /= (leT_tr _ _ _ _ xy) ?andbT //. by case: (lastP s) sx => //= {}s z; rewrite all_rcons last_rcons => /andP [->]. Qed. Lemma cycle_all2rel_in (T : Type) (P : {pred T}) (leT : rel T) : {in P & &, transitive leT} -> forall s, all P s -> cycle leT s = all2rel leT s. Proof. move=> /in3_sig leT_tr _ /all_sigP [s ->]. by rewrite cycle_map allrel_mapl allrel_mapr; apply: cycle_all2rel. Qed. End CycleAll2Rel. Section PreInSuffix. Variables (T : eqType) (e : rel T). Implicit Type s : seq T. Local Notation path := (path e). Local Notation sorted := (sorted e). Lemma prefix_path x s1 s2 : prefix s1 s2 -> path x s2 -> path x s1. Proof. by rewrite prefixE => /eqP <-; exact: take_path. Qed. Lemma prefix_sorted s1 s2 : prefix s1 s2 -> sorted s2 -> sorted s1. Proof. by rewrite prefixE => /eqP <-; exact: take_sorted. Qed. Lemma infix_sorted s1 s2 : infix s1 s2 -> sorted s2 -> sorted s1. Proof. by rewrite infixE => /eqP <- ?; apply/take_sorted/drop_sorted. Qed. Lemma suffix_sorted s1 s2 : suffix s1 s2 -> sorted s2 -> sorted s1. Proof. by rewrite suffixE => /eqP <-; exact: drop_sorted. Qed. End PreInSuffix. Section EqSorted. Variables (T : eqType) (leT : rel T). Implicit Type s : seq T. Local Notation path := (path leT). Local Notation sorted := (sorted leT). Lemma subseq_path_in x s1 s2 : {in x :: s2 & &, transitive leT} -> subseq s1 s2 -> path x s2 -> path x s1. Proof. by move=> tr /subseqP [m _ ->]; apply/(path_mask_in tr). Qed. Lemma subseq_sorted_in s1 s2 : {in s2 & &, transitive leT} -> subseq s1 s2 -> sorted s2 -> sorted s1. Proof. by move=> tr /subseqP [m _ ->]; apply/(sorted_mask_in tr). Qed. Lemma sorted_ltn_index_in s : {in s & &, transitive leT} -> sorted s -> {in s &, forall x y, index x s < index y s -> leT x y}. Proof. case: s => // x0 s' leT_tr s_sorted x y xs ys. move/(sorted_ltn_nth_in leT_tr x0 (allss (_ :: _)) s_sorted). by rewrite ?nth_index ?[_ \in gtn _]index_mem //; apply. Qed. Lemma sorted_leq_index_in s : {in s & &, transitive leT} -> {in s, reflexive leT} -> sorted s -> {in s &, forall x y, index x s <= index y s -> leT x y}. Proof. case: s => // x0 s' leT_tr leT_refl s_sorted x y xs ys. move/(sorted_leq_nth_in leT_tr leT_refl x0 (allss (_ :: _)) s_sorted). by rewrite ?nth_index ?[_ \in gtn _]index_mem //; apply. Qed. Hypothesis leT_tr : transitive leT. Lemma subseq_path x s1 s2 : subseq s1 s2 -> path x s2 -> path x s1. Proof. by apply: subseq_path_in; apply: in3W. Qed. Lemma subseq_sorted s1 s2 : subseq s1 s2 -> sorted s2 -> sorted s1. Proof. by apply: subseq_sorted_in; apply: in3W. Qed. Lemma sorted_uniq : irreflexive leT -> forall s, sorted s -> uniq s. Proof. by move=> irr s; rewrite sorted_pairwise //; apply/pairwise_uniq. Qed. Lemma sorted_eq : antisymmetric leT -> forall s1 s2, sorted s1 -> sorted s2 -> perm_eq s1 s2 -> s1 = s2. Proof. by move=> leT_asym s1 s2; rewrite !sorted_pairwise //; apply: pairwise_eq. Qed. Lemma irr_sorted_eq : irreflexive leT -> forall s1 s2, sorted s1 -> sorted s2 -> s1 =i s2 -> s1 = s2. Proof. move=> leT_irr s1 s2 s1_sort s2_sort eq_s12. have: antisymmetric leT. by move=> m n /andP[? ltnm]; case/idP: (leT_irr m); apply: leT_tr ltnm. by move/sorted_eq; apply=> //; apply: uniq_perm => //; apply: sorted_uniq. Qed. Lemma sorted_ltn_index s : sorted s -> {in s &, forall x y, index x s < index y s -> leT x y}. Proof. case: s => // x0 s' s_sorted x y xs ys /(sorted_ltn_nth leT_tr x0 s_sorted). by rewrite ?nth_index ?[_ \in gtn _]index_mem //; apply. Qed. Lemma undup_path x s : path x s -> path x (undup s). Proof. exact/subseq_path/undup_subseq. Qed. Lemma undup_sorted s : sorted s -> sorted (undup s). Proof. exact/subseq_sorted/undup_subseq. Qed. Hypothesis leT_refl : reflexive leT. Lemma sorted_leq_index s : sorted s -> {in s &, forall x y, index x s <= index y s -> leT x y}. Proof. case: s => // x0 s' s_sorted x y xs ys. move/(sorted_leq_nth leT_tr leT_refl x0 s_sorted). by rewrite ?nth_index ?[_ \in gtn _]index_mem //; apply. Qed. End EqSorted. Arguments sorted_ltn_index_in {T leT s} leT_tr s_sorted. Arguments sorted_leq_index_in {T leT s} leT_tr leT_refl s_sorted. Arguments sorted_ltn_index {T leT} leT_tr {s}. Arguments sorted_leq_index {T leT} leT_tr leT_refl {s}. Section EqSorted_in. Variables (T : eqType) (leT : rel T). Implicit Type s : seq T. Lemma sorted_uniq_in s : {in s & &, transitive leT} -> {in s, irreflexive leT} -> sorted leT s -> uniq s. Proof. move=> /in3_sig leT_tr /in1_sig leT_irr; case/all_sigP: (allss s) => s' ->. by rewrite sorted_map (map_inj_uniq val_inj); exact: sorted_uniq. Qed. Lemma sorted_eq_in s1 s2 : {in s1 & &, transitive leT} -> {in s1 &, antisymmetric leT} -> sorted leT s1 -> sorted leT s2 -> perm_eq s1 s2 -> s1 = s2. Proof. move=> /in3_sig leT_tr /in2_sig/(_ _ _ _)/val_inj leT_anti + + /[dup] s1s2. have /all_sigP[s1' ->] := allss s1. have /all_sigP[{s1s2}s2 ->] : all [in s1] s2 by rewrite -(perm_all _ s1s2). by rewrite !sorted_map => ss1' ss2 /(perm_map_inj val_inj)/(sorted_eq leT_tr)->. Qed. Lemma irr_sorted_eq_in s1 s2 : {in s1 & &, transitive leT} -> {in s1, irreflexive leT} -> sorted leT s1 -> sorted leT s2 -> s1 =i s2 -> s1 = s2. Proof. move=> /in3_sig leT_tr /in1_sig leT_irr + + /[dup] s1s2. have /all_sigP[s1' ->] := allss s1. have /all_sigP[s2' ->] : all [in s1] s2 by rewrite -(eq_all_r s1s2). rewrite !sorted_map => ss1' ss2' {}s1s2; congr map. by apply: (irr_sorted_eq leT_tr) => // x; rewrite -!(mem_map val_inj). Qed. End EqSorted_in. Section EqPath. Variables (n0 : nat) (T : eqType) (e : rel T). Implicit Type p : seq T. Variant split x : seq T -> seq T -> seq T -> Type := Split p1 p2 : split x (rcons p1 x ++ p2) p1 p2. Lemma splitP p x (i := index x p) : x \in p -> split x p (take i p) (drop i.+1 p). Proof. by rewrite -has_pred1 => /split_find[? ? ? /eqP->]; constructor. Qed. Variant splitl x1 x : seq T -> Type := Splitl p1 p2 of last x1 p1 = x : splitl x1 x (p1 ++ p2). Lemma splitPl x1 p x : x \in x1 :: p -> splitl x1 x p. Proof. rewrite inE; case: eqP => [->| _ /splitP[]]; first by rewrite -(cat0s p). by split; apply: last_rcons. Qed. Variant splitr x : seq T -> Type := Splitr p1 p2 : splitr x (p1 ++ x :: p2). Lemma splitPr p x : x \in p -> splitr x p. Proof. by case/splitP=> p1 p2; rewrite cat_rcons. Qed. Fixpoint next_at x y0 y p := match p with | [::] => if x == y then y0 else x | y' :: p' => if x == y then y' else next_at x y0 y' p' end. Definition next p x := if p is y :: p' then next_at x y y p' else x. Fixpoint prev_at x y0 y p := match p with | [::] => if x == y0 then y else x | y' :: p' => if x == y' then y else prev_at x y0 y' p' end. Definition prev p x := if p is y :: p' then prev_at x y y p' else x. Lemma next_nth p x : next p x = if x \in p then if p is y :: p' then nth y p' (index x p) else x else x. Proof. case: p => //= y0 p. elim: p {2 3 5}y0 => [|y' p IHp] y /=; rewrite (eq_sym y) inE; by case: ifP => // _; apply: IHp. Qed. Lemma prev_nth p x : prev p x = if x \in p then if p is y :: p' then nth y p (index x p') else x else x. Proof. case: p => //= y0 p; rewrite inE orbC. elim: p {2 5}y0 => [|y' p IHp] y; rewrite /= ?inE // (eq_sym y'). by case: ifP => // _; apply: IHp. Qed. Lemma mem_next p x : (next p x \in p) = (x \in p). Proof. rewrite next_nth; case p_x: (x \in p) => //. case: p (index x p) p_x => [|y0 p'] //= i _; rewrite inE. have [lt_ip | ge_ip] := ltnP i (size p'); first by rewrite orbC mem_nth. by rewrite nth_default ?eqxx. Qed. Lemma mem_prev p x : (prev p x \in p) = (x \in p). Proof. rewrite prev_nth; case p_x: (x \in p) => //; case: p => [|y0 p] // in p_x *. by apply mem_nth; rewrite /= ltnS index_size. Qed. (* ucycleb is the boolean predicate, but ucycle is defined as a Prop *) (* so that it can be used as a coercion target. *) Definition ucycleb p := cycle e p && uniq p. Definition ucycle p : Prop := cycle e p && uniq p. (* Projections, used for creating local lemmas. *) Lemma ucycle_cycle p : ucycle p -> cycle e p. Proof. by case/andP. Qed. Lemma ucycle_uniq p : ucycle p -> uniq p. Proof. by case/andP. Qed. Lemma next_cycle p x : cycle e p -> x \in p -> e x (next p x). Proof. case: p => //= y0 p; elim: p {1 3 5}y0 => [|z p IHp] y /=; rewrite inE. by rewrite andbT; case: (x =P y) => // ->. by case/andP=> eyz /IHp; case: (x =P y) => // ->. Qed. Lemma prev_cycle p x : cycle e p -> x \in p -> e (prev p x) x. Proof. case: p => //= y0 p; rewrite inE orbC. elim: p {1 5}y0 => [|z p IHp] y /=; rewrite ?inE. by rewrite andbT; case: (x =P y0) => // ->. by case/andP=> eyz /IHp; case: (x =P z) => // ->. Qed. Lemma rot_ucycle p : ucycle (rot n0 p) = ucycle p. Proof. by rewrite /ucycle rot_uniq rot_cycle. Qed. Lemma rotr_ucycle p : ucycle (rotr n0 p) = ucycle p. Proof. by rewrite /ucycle rotr_uniq rotr_cycle. Qed. (* The "appears no later" partial preorder defined by a path. *) Definition mem2 p x y := y \in drop (index x p) p. Lemma mem2l p x y : mem2 p x y -> x \in p. Proof. by rewrite /mem2 -!index_mem size_drop ltn_subRL; apply/leq_ltn_trans/leq_addr. Qed. Lemma mem2lf {p x y} : x \notin p -> mem2 p x y = false. Proof. exact/contraNF/mem2l. Qed. Lemma mem2r p x y : mem2 p x y -> y \in p. Proof. by rewrite -[in y \in p](cat_take_drop (index x p) p) mem_cat orbC /mem2 => ->. Qed. Lemma mem2rf {p x y} : y \notin p -> mem2 p x y = false. Proof. exact/contraNF/mem2r. Qed. Lemma mem2_cat p1 p2 x y : mem2 (p1 ++ p2) x y = mem2 p1 x y || mem2 p2 x y || (x \in p1) && (y \in p2). Proof. rewrite [LHS]/mem2 index_cat fun_if if_arg !drop_cat addKn. case: ifPn => [p1x | /mem2lf->]; last by rewrite ltnNge leq_addr orbF. by rewrite index_mem p1x mem_cat -orbA (orb_idl (@mem2r _ _ _)). Qed. Lemma mem2_splice p1 p3 x y p2 : mem2 (p1 ++ p3) x y -> mem2 (p1 ++ p2 ++ p3) x y. Proof. by rewrite !mem2_cat mem_cat andb_orr orbC => /or3P[]->; rewrite ?orbT. Qed. Lemma mem2_splice1 p1 p3 x y z : mem2 (p1 ++ p3) x y -> mem2 (p1 ++ z :: p3) x y. Proof. exact: mem2_splice [::z]. Qed. Lemma mem2_cons x p y z : mem2 (x :: p) y z = (if x == y then z \in x :: p else mem2 p y z). Proof. by rewrite [LHS]/mem2 /=; case: ifP. Qed. Lemma mem2_seq1 x y z : mem2 [:: x] y z = (y == x) && (z == x). Proof. by rewrite mem2_cons eq_sym inE. Qed. Lemma mem2_last y0 p x : mem2 p x (last y0 p) = (x \in p). Proof. apply/idP/idP; first exact: mem2l; rewrite -index_mem /mem2 => p_x. by rewrite -nth_last -(subnKC p_x) -nth_drop mem_nth // size_drop subnSK. Qed. Lemma mem2l_cat {p1 p2 x} : x \notin p1 -> mem2 (p1 ++ p2) x =1 mem2 p2 x. Proof. by move=> p1'x y; rewrite mem2_cat (negPf p1'x) mem2lf ?orbF. Qed. Lemma mem2r_cat {p1 p2 x y} : y \notin p2 -> mem2 (p1 ++ p2) x y = mem2 p1 x y. Proof. by move=> p2'y; rewrite mem2_cat (negPf p2'y) -orbA orbC andbF mem2rf. Qed. Lemma mem2lr_splice {p1 p2 p3 x y} : x \notin p2 -> y \notin p2 -> mem2 (p1 ++ p2 ++ p3) x y = mem2 (p1 ++ p3) x y. Proof. move=> p2'x p2'y; rewrite catA !mem2_cat !mem_cat. by rewrite (negPf p2'x) (negPf p2'y) (mem2lf p2'x) andbF !orbF. Qed. Lemma mem2E s x y : mem2 s x y = subseq (if x == y then [:: x] else [:: x; y]) s. Proof. elim: s => [| h s]; first by case: ifP. rewrite mem2_cons => ->. do 2 rewrite inE (fun_if subseq) !if_arg !sub1seq /=. by have [->|] := eqVneq; case: eqVneq. Qed. Variant split2r x y : seq T -> Type := Split2r p1 p2 of y \in x :: p2 : split2r x y (p1 ++ x :: p2). Lemma splitP2r p x y : mem2 p x y -> split2r x y p. Proof. move=> pxy; have px := mem2l pxy. have:= pxy; rewrite /mem2 (drop_nth x) ?index_mem ?nth_index //. by case/splitP: px => p1 p2; rewrite cat_rcons. Qed. Fixpoint shorten x p := if p is y :: p' then if x \in p then shorten x p' else y :: shorten y p' else [::]. Variant shorten_spec x p : T -> seq T -> Type := ShortenSpec p' of path e x p' & uniq (x :: p') & {subset p' <= p} : shorten_spec x p (last x p') p'. Lemma shortenP x p : path e x p -> shorten_spec x p (last x p) (shorten x p). Proof. move=> e_p; have: x \in x :: p by apply: mem_head. elim: p x {1 3 5}x e_p => [|y2 p IHp] x y1. by rewrite mem_seq1 => _ /eqP->. rewrite inE orbC /= => /andP[ey12 {}/IHp IHp]. case: ifPn => [y2p_x _ | not_y2p_x /eqP def_x]. have [p' e_p' Up' p'p] := IHp _ y2p_x. by split=> // y /p'p; apply: predU1r. have [p' e_p' Up' p'p] := IHp y2 (mem_head y2 p). have{} p'p z: z \in y2 :: p' -> z \in y2 :: p. by rewrite !inE; case: (z == y2) => // /p'p. rewrite -(last_cons y1) def_x; split=> //=; first by rewrite ey12. by rewrite (contra (p'p y1)) -?def_x. Qed. End EqPath. (* Ordered paths and sorting. *) Section SortSeq. Variables (T : Type) (leT : rel T). Fixpoint merge s1 := if s1 is x1 :: s1' then let fix merge_s1 s2 := if s2 is x2 :: s2' then if leT x1 x2 then x1 :: merge s1' s2 else x2 :: merge_s1 s2' else s1 in merge_s1 else id. Arguments merge !s1 !s2 : rename. Fixpoint merge_sort_push s1 ss := match ss with | [::] :: ss' | [::] as ss' => s1 :: ss' | s2 :: ss' => [::] :: merge_sort_push (merge s2 s1) ss' end. Fixpoint merge_sort_pop s1 ss := if ss is s2 :: ss' then merge_sort_pop (merge s2 s1) ss' else s1. Fixpoint merge_sort_rec ss s := if s is [:: x1, x2 & s'] then let s1 := if leT x1 x2 then [:: x1; x2] else [:: x2; x1] in merge_sort_rec (merge_sort_push s1 ss) s' else merge_sort_pop s ss. Definition sort := merge_sort_rec [::]. (* The following definition `sort_rec1` is an auxiliary function for *) (* inductive reasoning on `sort`. One can rewrite `sort le s` to *) (* `sort_rec1 le [::] s` by `sortE` and apply the simple structural induction *) (* on `s` to reason about it. *) Fixpoint sort_rec1 ss s := if s is x :: s then sort_rec1 (merge_sort_push [:: x] ss) s else merge_sort_pop [::] ss. Lemma sortE s : sort s = sort_rec1 [::] s. Proof. transitivity (sort_rec1 [:: nil] s); last by case: s. rewrite /sort; move: [::] {2}_.+1 (ltnSn (size s)./2) => ss n. by elim: n => // n IHn in ss s *; case: s => [|x [|y s]] //= /IHn->. Qed. Lemma count_merge (p : pred T) s1 s2 : count p (merge s1 s2) = count p (s1 ++ s2). Proof. rewrite count_cat; elim: s1 s2 => // x s1 IH1. elim=> //= [|y s2 IH2]; first by rewrite addn0. by case: leT; rewrite /= ?IH1 ?IH2 !addnA [_ + p y]addnAC [p x + p y]addnC. Qed. Lemma size_merge s1 s2 : size (merge s1 s2) = size (s1 ++ s2). Proof. exact: (count_merge predT). Qed. Lemma allrel_merge s1 s2 : allrel leT s1 s2 -> merge s1 s2 = s1 ++ s2. Proof. elim: s1 s2 => [|x s1 IHs1] [|y s2]; rewrite ?cats0 //=. by rewrite allrel_consl /= -andbA => /and3P [-> _ /IHs1->]. Qed. Lemma count_sort (p : pred T) s : count p (sort s) = count p s. Proof. rewrite sortE -[RHS]/(sumn [seq count p x | x <- [::]] + count p s). elim: s [::] => [|x s ihs] ss. rewrite [LHS]/=; elim: ss [::] => //= s ss ihss t. by rewrite ihss count_merge count_cat addnCA addnA. rewrite {}ihs -[in RHS]cat1s count_cat addnA; congr addn; rewrite addnC. elim: {x s} ss [:: x] => [|[|x s] ss ihss] t //. by rewrite [LHS]/= add0n ihss count_merge count_cat -addnA addnCA. Qed. Lemma pairwise_sort s : pairwise leT s -> sort s = s. Proof. pose catss := foldr (fun x => cat ^~ x) (Nil T). rewrite -{1 3}[s]/(catss [::] ++ s) sortE; elim: s [::] => /= [|x s ihs] ss. elim: ss [::] => //= s ss ihss t; rewrite -catA => ssst. rewrite -ihss ?allrel_merge //; move: ssst; rewrite !pairwise_cat. by case/and4P. rewrite (catA _ [:: _]) => ssxs. suff x_ss_E: catss (merge_sort_push [:: x] ss) = catss ([:: x] :: ss). by rewrite -[catss _ ++ _]/(catss ([:: x] :: ss)) -x_ss_E ihs // x_ss_E. move: ssxs; rewrite pairwise_cat => /and3P [_ + _]. elim: ss [:: x] => {x s ihs} //= -[|x s] ss ihss t h_pairwise; rewrite /= cats0 // allrel_merge ?ihss ?catA //. by move: h_pairwise; rewrite -catA !pairwise_cat => /and4P []. Qed. Remark size_merge_sort_push s1 : let graded ss := forall i, size (nth [::] ss i) \in pred2 0 (2 ^ (i + 1)) in size s1 = 2 -> {homo merge_sort_push s1 : ss / graded ss}. Proof. set n := {2}1; rewrite -[RHS]/(2 ^ n) => graded sz_s1 ss. elim: ss => [|s2 ss IHss] in (n) graded s1 sz_s1 * => sz_ss i //=. by case: i => [|[]] //; rewrite sz_s1 inE eqxx orbT. case: s2 i => [|x s2] [|i] //= in sz_ss *; first by rewrite sz_s1 inE eqxx orbT. exact: (sz_ss i.+1). rewrite addSnnS; apply: IHss i => [|i]; last by rewrite -addSnnS (sz_ss i.+1). by rewrite size_merge size_cat sz_s1 (eqP (sz_ss 0)) addnn expnS mul2n. Qed. Section Stability. Variable leT' : rel T. Hypothesis (leT_total : total leT) (leT'_tr : transitive leT'). Let leT_lex := [rel x y | leT x y && (leT y x ==> leT' x y)]. Lemma merge_stable_path x s1 s2 : allrel leT' s1 s2 -> path leT_lex x s1 -> path leT_lex x s2 -> path leT_lex x (merge s1 s2). Proof. elim: s1 s2 x => //= x s1 ih1; elim => //= y s2 ih2 h. rewrite allrel_cons2 => /and4P [xy' xs2 ys1 s1s2] /andP [hx xs1] /andP [hy ys2]. case: ifP => xy /=; rewrite (hx, hy) /=. - by apply: ih1; rewrite ?allrel_consr ?ys1 //= xy xy' implybT. - by apply: ih2; have:= leT_total x y; rewrite ?allrel_consl ?xs2 ?xy //= => ->. Qed. Lemma merge_stable_sorted s1 s2 : allrel leT' s1 s2 -> sorted leT_lex s1 -> sorted leT_lex s2 -> sorted leT_lex (merge s1 s2). Proof. case: s1 s2 => [|x s1] [|y s2] //=; rewrite allrel_consl allrel_consr /= -andbA. case/and4P => [xy' xs2 ys1 s1s2] xs1 ys2; rewrite -/(merge (_ :: _)). by case: ifP (leT_total x y) => /= xy yx; apply/merge_stable_path; rewrite /= ?(allrel_consl, allrel_consr, xs2, ys1, xy, yx, xy', implybT). Qed. End Stability. Hypothesis leT_total : total leT. Let leElex : leT =2 [rel x y | leT x y && (leT y x ==> true)]. Proof. by move=> ? ? /=; rewrite implybT andbT. Qed. Lemma merge_path x s1 s2 : path leT x s1 -> path leT x s2 -> path leT x (merge s1 s2). Proof. by rewrite !(eq_path leElex); apply/merge_stable_path/allrelT. Qed. Lemma merge_sorted s1 s2 : sorted leT s1 -> sorted leT s2 -> sorted leT (merge s1 s2). Proof. by rewrite !(eq_sorted leElex); apply/merge_stable_sorted/allrelT. Qed. Hypothesis leT_tr : transitive leT. Lemma sorted_merge s t : sorted leT (s ++ t) -> merge s t = s ++ t. Proof. by rewrite sorted_pairwise // pairwise_cat => /and3P[/allrel_merge]. Qed. Lemma sorted_sort s : sorted leT s -> sort s = s. Proof. by rewrite sorted_pairwise //; apply/pairwise_sort. Qed. Lemma mergeA : associative merge. Proof. elim=> // x xs IHxs; elim=> // y ys IHys; elim=> [|z zs IHzs] /=. by case: ifP. case: ifP; case: ifP => /= lexy leyz. - by rewrite lexy (leT_tr lexy leyz) -IHxs /= leyz. - by rewrite lexy leyz -IHys. - case: ifP => lexz; first by rewrite -IHxs //= leyz. by rewrite -!/(merge (_ :: _)) IHzs /= lexy. - suff->: leT x z = false by rewrite leyz // -!/(merge (_ :: _)) IHzs /= lexy. by apply/contraFF/leT_tr: leyz; have := leT_total x y; rewrite lexy. Qed. End SortSeq. Arguments merge {T} relT !s1 !s2 : rename. Arguments size_merge {T} leT s1 s2. Arguments allrel_merge {T leT s1 s2}. Arguments pairwise_sort {T leT s}. Arguments merge_path {T leT} leT_total {x s1 s2}. Arguments merge_sorted {T leT} leT_total {s1 s2}. Arguments sorted_merge {T leT} leT_tr {s t}. Arguments sorted_sort {T leT} leT_tr {s}. Arguments mergeA {T leT} leT_total leT_tr. Section SortMap. Variables (T T' : Type) (f : T' -> T). Section Monotonicity. Variables (leT' : rel T') (leT : rel T). Hypothesis f_mono : {mono f : x y / leT' x y >-> leT x y}. Lemma map_merge : {morph map f : s1 s2 / merge leT' s1 s2 >-> merge leT s1 s2}. Proof. elim=> //= x s1 IHs1; elim => [|y s2 IHs2] //=; rewrite f_mono. by case: leT'; rewrite /= ?IHs1 ?IHs2. Qed. Lemma map_sort : {morph map f : s1 / sort leT' s1 >-> sort leT s1}. Proof. move=> s; rewrite !sortE -[[::] in RHS]/(map (map f) [::]). elim: s [::] => /= [|x s ihs] ss; rewrite -/(map f [::]) -/(map f [:: _]); first by elim: ss [::] => //= x ss ihss ?; rewrite ihss map_merge. rewrite ihs -/(map f [:: x]); congr sort_rec1. by elim: ss [:: x] => {x s ihs} [|[|x s] ss ihss] //= ?; rewrite ihss map_merge. Qed. End Monotonicity. Variable leT : rel T. Lemma merge_map s1 s2 : merge leT (map f s1) (map f s2) = map f (merge (relpre f leT) s1 s2). Proof. exact/esym/map_merge. Qed. Lemma sort_map s : sort leT (map f s) = map f (sort (relpre f leT) s). Proof. exact/esym/map_sort. Qed. End SortMap. Arguments map_merge {T T' f leT' leT}. Arguments map_sort {T T' f leT' leT}. Arguments merge_map {T T' f leT}. Arguments sort_map {T T' f leT}. Lemma sorted_sort_in T (P : {pred T}) (leT : rel T) : {in P & &, transitive leT} -> forall s : seq T, all P s -> sorted leT s -> sort leT s = s. Proof. move=> /in3_sig ? _ /all_sigP[s ->]. by rewrite sort_map sorted_map => /sorted_sort->. Qed. Arguments sorted_sort_in {T P leT} leT_tr {s}. Section EqSortSeq. Variables (T : eqType) (leT : rel T). Lemma perm_merge s1 s2 : perm_eql (merge leT s1 s2) (s1 ++ s2). Proof. by apply/permPl/permP => ?; rewrite count_merge. Qed. Lemma mem_merge s1 s2 : merge leT s1 s2 =i s1 ++ s2. Proof. by apply: perm_mem; rewrite perm_merge. Qed. Lemma merge_uniq s1 s2 : uniq (merge leT s1 s2) = uniq (s1 ++ s2). Proof. by apply: perm_uniq; rewrite perm_merge. Qed. Lemma perm_sort s : perm_eql (sort leT s) s. Proof. by apply/permPl/permP => ?; rewrite count_sort. Qed. Lemma mem_sort s : sort leT s =i s. Proof. exact/perm_mem/permPl/perm_sort. Qed. Lemma sort_uniq s : uniq (sort leT s) = uniq s. Proof. exact/perm_uniq/permPl/perm_sort. Qed. Lemma eq_count_merge (p : pred T) s1 s1' s2 s2' : count p s1 = count p s1' -> count p s2 = count p s2' -> count p (merge leT s1 s2) = count p (merge leT s1' s2'). Proof. by rewrite !count_merge !count_cat => -> ->. Qed. End EqSortSeq. Lemma perm_iota_sort (T : Type) (leT : rel T) x0 s : {i_s : seq nat | perm_eq i_s (iota 0 (size s)) & sort leT s = map (nth x0 s) i_s}. Proof. exists (sort (relpre (nth x0 s) leT) (iota 0 (size s))). by rewrite perm_sort. by rewrite -[s in LHS](mkseq_nth x0) sort_map. Qed. Lemma all_merge (T : Type) (P : {pred T}) (leT : rel T) s1 s2 : all P (merge leT s1 s2) = all P s1 && all P s2. Proof. elim: s1 s2 => //= x s1 IHs1; elim=> [|y s2 IHs2]; rewrite ?andbT //=. by case: ifP => _; rewrite /= ?IHs1 ?IHs2 //=; bool_congr. Qed. Lemma all_sort (T : Type) (P : {pred T}) (leT : rel T) s : all P (sort leT s) = all P s. Proof. case: s => // x s; move: (x :: s) => {}s. by rewrite -(mkseq_nth x s) sort_map !all_map; apply/perm_all/permPl/perm_sort. Qed. Lemma size_sort (T : Type) (leT : rel T) s : size (sort leT s) = size s. Proof. exact: (count_sort _ predT). Qed. Lemma ltn_sorted_uniq_leq s : sorted ltn s = uniq s && sorted leq s. Proof. rewrite (sorted_pairwise leq_trans) (sorted_pairwise ltn_trans) uniq_pairwise. by rewrite -pairwise_relI; apply/eq_pairwise => ? ?; rewrite ltn_neqAle. Qed. Lemma gtn_sorted_uniq_geq s : sorted gtn s = uniq s && sorted geq s. Proof. by rewrite -rev_sorted ltn_sorted_uniq_leq rev_sorted rev_uniq. Qed. Lemma iota_sorted i n : sorted leq (iota i n). Proof. by elim: n i => // [[|n] //= IHn] i; rewrite IHn leqW. Qed. Lemma iota_ltn_sorted i n : sorted ltn (iota i n). Proof. by rewrite ltn_sorted_uniq_leq iota_sorted iota_uniq. Qed. Section Stability_iota. Variables (leN : rel nat) (leN_total : total leN). Let lt_lex := [rel n m | leN n m && (leN m n ==> (n < m))]. Let Fixpoint push_invariant (ss : seq (seq nat)) := if ss is s :: ss' then [&& sorted lt_lex s, allrel gtn s (flatten ss') & push_invariant ss'] else true. Let push_stable s1 ss : push_invariant (s1 :: ss) -> push_invariant (merge_sort_push leN s1 ss). Proof. elim: ss s1 => [] // [] //= m s2 ss ihss s1; rewrite -cat_cons allrel_catr. move=> /and5P[sorted_s1 /andP[s1s2 s1ss] sorted_s2 s2ss hss]; apply: ihss. rewrite /= hss andbT merge_stable_sorted //=; last by rewrite allrelC. by apply/allrelP => ? ?; rewrite mem_merge mem_cat => /orP[]; apply/allrelP. Qed. Let pop_stable s1 ss : push_invariant (s1 :: ss) -> sorted lt_lex (merge_sort_pop leN s1 ss). Proof. elim: ss s1 => [s1 /and3P[]|s2 ss ihss s1] //=; rewrite allrel_catr. move=> /and5P[sorted_s1 /andP[s1s2 s1ss] sorted_s2 s2ss hss]; apply: ihss. rewrite /= hss andbT merge_stable_sorted //=; last by rewrite allrelC. by apply/allrelP => ? ?; rewrite mem_merge mem_cat => /orP[]; apply/allrelP. Qed. Lemma sort_iota_stable n : sorted lt_lex (sort leN (iota 0 n)). Proof. rewrite sortE. have/andP[]: all (gtn 0) (flatten [::]) && push_invariant [::] by []. elim: n 0 [::] => [|n ihn] m ss hss1 hss2; first exact: pop_stable. apply/ihn/push_stable; last by rewrite /= allrel1l hss1. have: all (gtn m.+1) (flatten ([:: m] :: ss)). by rewrite /= leqnn; apply: sub_all hss1 => ? /leqW. elim: ss [:: _] {hss1 hss2} => [|[|? ?] ? ihss] //= ? ?. by rewrite ihss //= all_cat all_merge -andbA andbCA -!all_cat. Qed. End Stability_iota. Lemma sort_pairwise_stable T (leT leT' : rel T) : total leT -> forall s : seq T, pairwise leT' s -> sorted [rel x y | leT x y && (leT y x ==> leT' x y)] (sort leT s). Proof. move=> leT_total s pairwise_s; case Ds: s => // [x s1]. rewrite -{s1}Ds -(mkseq_nth x s) sort_map. apply/homo_sorted_in/sort_iota_stable/(fun _ _ => leT_total _ _)/allss => y z. rewrite !mem_sort !mem_iota !leq0n add0n /= => ys zs /andP [->] /=. by case: (leT _ _); first apply: pairwiseP. Qed. Lemma sort_stable T (leT leT' : rel T) : total leT -> transitive leT' -> forall s : seq T, sorted leT' s -> sorted [rel x y | leT x y && (leT y x ==> leT' x y)] (sort leT s). Proof. move=> leT_total leT'_tr s; rewrite sorted_pairwise //. exact: sort_pairwise_stable. Qed. Lemma sort_stable_in T (P : {pred T}) (leT leT' : rel T) : {in P &, total leT} -> {in P & &, transitive leT'} -> forall s : seq T, all P s -> sorted leT' s -> sorted [rel x y | leT x y && (leT y x ==> leT' x y)] (sort leT s). Proof. move=> /in2_sig leT_total /in3_sig leT_tr _ /all_sigP[s ->]. by rewrite sort_map !sorted_map; apply: sort_stable. Qed. Lemma filter_sort T (leT : rel T) : total leT -> transitive leT -> forall p s, filter p (sort leT s) = sort leT (filter p s). Proof. move=> leT_total leT_tr p s; case Ds: s => // [x s1]. pose leN := relpre (nth x s) leT. pose lt_lex := [rel n m | leN n m && (leN m n ==> (n < m))]. have lt_lex_tr: transitive lt_lex. rewrite /lt_lex /leN => ? ? ? /= /andP [xy xy'] /andP [yz yz']. rewrite (leT_tr _ _ _ xy yz); apply/implyP => zx; move: xy' yz'. by rewrite (leT_tr _ _ _ yz zx) (leT_tr _ _ _ zx xy); apply: ltn_trans. rewrite -{s1}Ds -(mkseq_nth x s) !(filter_map, sort_map); congr map. apply/(@irr_sorted_eq _ lt_lex); rewrite /lt_lex /leN //=. - by move=> ?; rewrite /= ltnn implybF andbN. - exact/sorted_filter/sort_iota_stable. - exact/sort_stable/sorted_filter/iota_ltn_sorted/ltn_trans/ltn_trans. - by move=> ?; rewrite !(mem_filter, mem_sort). Qed. Lemma filter_sort_in T (P : {pred T}) (leT : rel T) : {in P &, total leT} -> {in P & &, transitive leT} -> forall p s, all P s -> filter p (sort leT s) = sort leT (filter p s). Proof. move=> /in2_sig leT_total /in3_sig leT_tr p _ /all_sigP[s ->]. by rewrite !(sort_map, filter_map) filter_sort. Qed. Section Stability_mask. Variables (T : Type) (leT : rel T). Variables (leT_total : total leT) (leT_tr : transitive leT). Lemma mask_sort s m : {m_s : bitseq | mask m_s (sort leT s) = sort leT (mask m s)}. Proof. case Ds: {-}s => [|x s1]; [by rewrite Ds; case: m; exists [::] | clear s1 Ds]. rewrite -(mkseq_nth x s) -map_mask !sort_map. exists [seq i \in mask m (iota 0 (size s)) | i <- sort (xrelpre (nth x s) leT) (iota 0 (size s))]. rewrite -map_mask -filter_mask [in RHS]mask_filter ?iota_uniq ?filter_sort //. by move=> ? ? ?; exact: leT_tr. Qed. Lemma sorted_mask_sort s m : sorted leT (mask m s) -> {m_s | mask m_s (sort leT s) = mask m s}. Proof. by move/(sorted_sort leT_tr) <-; exact: mask_sort. Qed. End Stability_mask. Section Stability_mask_in. Variables (T : Type) (P : {pred T}) (leT : rel T). Hypothesis leT_total : {in P &, total leT}. Hypothesis leT_tr : {in P & &, transitive leT}. Let le_sT := relpre (val : sig P -> _) leT. Let le_sT_total : total le_sT := in2_sig leT_total. Let le_sT_tr : transitive le_sT := in3_sig leT_tr. Lemma mask_sort_in s m : all P s -> {m_s : bitseq | mask m_s (sort leT s) = sort leT (mask m s)}. Proof. move=> /all_sigP [{}s ->]; case: (mask_sort (leT := le_sT) _ _ s m) => //. by move=> m' m'E; exists m'; rewrite -map_mask !sort_map -map_mask m'E. Qed. Lemma sorted_mask_sort_in s m : all P s -> sorted leT (mask m s) -> {m_s | mask m_s (sort leT s) = mask m s}. Proof. move=> ? /(sorted_sort_in leT_tr _) <-; [exact: mask_sort_in | exact: all_mask]. Qed. End Stability_mask_in. Section Stability_subseq. Variables (T : eqType) (leT : rel T). Variables (leT_total : total leT) (leT_tr : transitive leT). Lemma subseq_sort : {homo sort leT : t s / subseq t s}. Proof. move=> _ s /subseqP [m _ ->]; have [m' <-] := mask_sort leT_total leT_tr s m. exact: mask_subseq. Qed. Lemma sorted_subseq_sort t s : subseq t s -> sorted leT t -> subseq t (sort leT s). Proof. by move=> subseq_ts /(sorted_sort leT_tr) <-; exact: subseq_sort. Qed. Lemma mem2_sort s x y : leT x y -> mem2 s x y -> mem2 (sort leT s) x y. Proof. move=> lexy /[!mem2E] /subseq_sort. by case: eqP => // _; rewrite {1}/sort /= lexy /=. Qed. End Stability_subseq. Section Stability_subseq_in. Variables (T : eqType) (leT : rel T). Lemma subseq_sort_in t s : {in s &, total leT} -> {in s & &, transitive leT} -> subseq t s -> subseq (sort leT t) (sort leT s). Proof. move=> leT_total leT_tr /subseqP [m _ ->]. have [m' <-] := mask_sort_in leT_total leT_tr m (allss _). exact: mask_subseq. Qed. Lemma sorted_subseq_sort_in t s : {in s &, total leT} -> {in s & &, transitive leT} -> subseq t s -> sorted leT t -> subseq t (sort leT s). Proof. move=> ? leT_tr ? /(sorted_sort_in leT_tr) <-; last exact/allP/mem_subseq. exact: subseq_sort_in. Qed. Lemma mem2_sort_in s : {in s &, total leT} -> {in s & &, transitive leT} -> forall x y, leT x y -> mem2 s x y -> mem2 (sort leT s) x y. Proof. move=> leT_total leT_tr x y lexy; rewrite !mem2E. by move/subseq_sort_in; case: (_ == _); rewrite /sort /= ?lexy; apply. Qed. End Stability_subseq_in. Lemma sort_sorted T (leT : rel T) : total leT -> forall s, sorted leT (sort leT s). Proof. move=> leT_total s; apply/sub_sorted/sort_stable => //= [? ? /andP[] //|]. by case: s => // x s; elim: s x => /=. Qed. Lemma sort_sorted_in T (P : {pred T}) (leT : rel T) : {in P &, total leT} -> forall s : seq T, all P s -> sorted leT (sort leT s). Proof. by move=> /in2_sig ? _ /all_sigP[s ->]; rewrite sort_map sorted_map sort_sorted. Qed. Arguments sort_sorted {T leT} leT_total s. Arguments sort_sorted_in {T P leT} leT_total {s}. Lemma perm_sortP (T : eqType) (leT : rel T) : total leT -> transitive leT -> antisymmetric leT -> forall s1 s2, reflect (sort leT s1 = sort leT s2) (perm_eq s1 s2). Proof. move=> leT_total leT_tr leT_asym s1 s2. apply: (iffP idP) => eq12; last by rewrite -(perm_sort leT) eq12 perm_sort. apply: (sorted_eq leT_tr leT_asym); rewrite ?sort_sorted //. by rewrite perm_sort (permPl eq12) -(perm_sort leT). Qed. Lemma perm_sort_inP (T : eqType) (leT : rel T) (s1 s2 : seq T) : {in s1 &, total leT} -> {in s1 & &, transitive leT} -> {in s1 &, antisymmetric leT} -> reflect (sort leT s1 = sort leT s2) (perm_eq s1 s2). Proof. move=> /in2_sig leT_total /in3_sig leT_tr /in2_sig/(_ _ _ _)/val_inj leT_asym. apply: (iffP idP) => s1s2; last by rewrite -(perm_sort leT) s1s2 perm_sort. move: (s1s2); have /all_sigP[s1' ->] := allss s1. have /all_sigP[{s1s2}s2 ->] : all [in s1] s2 by rewrite -(perm_all _ s1s2). by rewrite !sort_map => /(perm_map_inj val_inj) /(perm_sortP leT_total)->. Qed. Lemma homo_sort_map (T : Type) (T' : eqType) (f : T -> T') leT leT' : antisymmetric (relpre f leT') -> transitive (relpre f leT') -> total leT -> {homo f : x y / leT x y >-> leT' x y} -> forall s : seq T, sort leT' (map f s) = map f (sort leT s). Proof. move=> leT'_asym leT'_trans leT_total f_homo s; case Ds: s => // [x s']. rewrite -{}Ds -(mkseq_nth x s) [in RHS]sort_map -!map_comp /comp. apply: (@sorted_eq_in _ leT') => [? ? ?|? ?|||]; rewrite ?mem_sort. - by move=> /mapP[? _ ->] /mapP[? _ ->] /mapP[? _ ->]; apply/leT'_trans. - by move=> /mapP[? _ ->] /mapP[? _ ->] /leT'_asym ->. - apply: (sort_sorted_in _ (allss _)) => _ _ /mapP[y _ ->] /mapP[z _ ->]. by case/orP: (leT_total (nth x s y) (nth x s z)) => /f_homo ->; rewrite ?orbT. - by rewrite map_comp -sort_map; exact/homo_sorted/sort_sorted. - by rewrite perm_sort perm_map // perm_sym perm_sort. Qed. Lemma homo_sort_map_in (T : Type) (T' : eqType) (P : {pred T}) (f : T -> T') leT leT' : {in P &, antisymmetric (relpre f leT')} -> {in P & &, transitive (relpre f leT')} -> {in P &, total leT} -> {in P &, {homo f : x y / leT x y >-> leT' x y}} -> forall s : seq T, all P s -> sort leT' [seq f x | x <- s] = [seq f x | x <- sort leT s]. Proof. move=> /in2_sig leT'_asym /in3_sig leT'_trans /in2_sig leT_total. move=> /in2_sig f_homo _ /all_sigP[s ->]. rewrite [in RHS]sort_map -!map_comp /comp. by apply: homo_sort_map => // ? ? /leT'_asym /val_inj. Qed. (* Function trajectories. *) Notation fpath f := (path (coerced_frel f)). Notation fcycle f := (cycle (coerced_frel f)). Notation ufcycle f := (ucycle (coerced_frel f)). Prenex Implicits path next prev cycle ucycle mem2. Section Trajectory. Variables (T : Type) (f : T -> T). Fixpoint traject x n := if n is n'.+1 then x :: traject (f x) n' else [::]. Lemma trajectS x n : traject x n.+1 = x :: traject (f x) n. Proof. by []. Qed. Lemma trajectSr x n : traject x n.+1 = rcons (traject x n) (iter n f x). Proof. by elim: n x => //= n IHn x; rewrite IHn -iterSr. Qed. Lemma last_traject x n : last x (traject (f x) n) = iter n f x. Proof. by case: n => // n; rewrite iterSr trajectSr last_rcons. Qed. Lemma traject_iteri x n : traject x n = iteri n (fun i => rcons^~ (iter i f x)) [::]. Proof. by elim: n => //= n <-; rewrite -trajectSr. Qed. Lemma size_traject x n : size (traject x n) = n. Proof. by elim: n x => //= n IHn x //=; rewrite IHn. Qed. Lemma nth_traject i n : i < n -> forall x, nth x (traject x n) i = iter i f x. Proof. elim: n => // n IHn; rewrite ltnS => le_i_n x. rewrite trajectSr nth_rcons size_traject. by case: ltngtP le_i_n => [? _||->] //; apply: IHn. Qed. Lemma trajectD m n x : traject x (m + n) = traject x m ++ traject (iter m f x) n. Proof. by elim: m => //m IHm in x *; rewrite addSn !trajectS IHm -iterSr. Qed. Lemma take_traject n k x : k <= n -> take k (traject x n) = traject x k. Proof. by move=> /subnKC<-; rewrite trajectD take_size_cat ?size_traject. Qed. End Trajectory. Section EqTrajectory. Variables (T : eqType) (f : T -> T). Lemma eq_fpath f' : f =1 f' -> fpath f =2 fpath f'. Proof. by move/eq_frel/eq_path. Qed. Lemma eq_fcycle f' : f =1 f' -> fcycle f =1 fcycle f'. Proof. by move/eq_frel/eq_cycle. Qed. Lemma fpathE x p : fpath f x p -> p = traject f (f x) (size p). Proof. by elim: p => //= y p IHp in x * => /andP[/eqP{y}<- /IHp<-]. Qed. Lemma fpathP x p : reflect (exists n, p = traject f (f x) n) (fpath f x p). Proof. apply: (iffP idP) => [/fpathE->|[n->]]; first by exists (size p). by elim: n => //= n IHn in x *; rewrite eqxx IHn. Qed. Lemma fpath_traject x n : fpath f x (traject f (f x) n). Proof. by apply/(fpathP x); exists n. Qed. Definition looping x n := iter n f x \in traject f x n. Lemma loopingP x n : reflect (forall m, iter m f x \in traject f x n) (looping x n). Proof. apply: (iffP idP) => loop_n; last exact: loop_n. case: n => // n in loop_n *; elim=> [|m /= IHm]; first exact: mem_head. move: (fpath_traject x n) loop_n; rewrite /looping !iterS -last_traject /=. move: (iter m f x) IHm => y /splitPl[p1 p2 def_y]. rewrite cat_path last_cat def_y; case: p2 => // z p2 /and3P[_ /eqP-> _] _. by rewrite inE mem_cat mem_head !orbT. Qed. Lemma trajectP x n y : reflect (exists2 i, i < n & y = iter i f x) (y \in traject f x n). Proof. elim: n x => [|n IHn] x /=; first by right; case. rewrite inE; have [-> | /= neq_xy] := eqP; first by left; exists 0. apply: {IHn}(iffP (IHn _)) => [[i] | [[|i]]] // lt_i_n ->. by exists i.+1; rewrite ?iterSr. by exists i; rewrite ?iterSr. Qed. Lemma looping_uniq x n : uniq (traject f x n.+1) = ~~ looping x n. Proof. rewrite /looping; elim: n x => [|n IHn] x //. rewrite [n.+1 in LHS]lock [iter]lock /= -!lock {}IHn -iterSr -negb_or inE. congr (~~ _); apply: orb_id2r => /trajectP no_loop. apply/idP/eqP => [/trajectP[m le_m_n def_x] | {1}<-]; last first. by rewrite iterSr -last_traject mem_last. have loop_m: looping x m.+1 by rewrite /looping iterSr -def_x mem_head. have/trajectP[[|i] // le_i_m def_fn1x] := loopingP _ _ loop_m n.+1. by case: no_loop; exists i; rewrite -?iterSr // -ltnS (leq_trans le_i_m). Qed. End EqTrajectory. Arguments fpathP {T f x p}. Arguments loopingP {T f x n}. Arguments trajectP {T f x n y}. Prenex Implicits traject. Section Fcycle. Variables (T : eqType) (f : T -> T) (p : seq T) (f_p : fcycle f p). Lemma nextE (x : T) (p_x : x \in p) : next p x = f x. Proof. exact/esym/eqP/(next_cycle f_p). Qed. Lemma mem_fcycle : {homo f : x / x \in p}. Proof. by move=> x xp; rewrite -nextE// mem_next. Qed. Lemma inj_cycle : {in p &, injective f}. Proof. apply: can_in_inj (iter (size p).-1 f) _ => x /rot_to[i q rip]. have /fpathE qxE : fcycle f (x :: q) by rewrite -rip rot_cycle. have -> : size p = size (rcons q x) by rewrite size_rcons -(size_rot i) rip. by rewrite -iterSr -last_traject prednK -?qxE ?size_rcons// last_rcons. Qed. End Fcycle. Section UniqCycle. Variables (n0 : nat) (T : eqType) (e : rel T) (p : seq T). Hypothesis Up : uniq p. Lemma prev_next : cancel (next p) (prev p). Proof. move=> x; rewrite prev_nth mem_next next_nth; case p_x: (x \in p) => //. case Dp: p Up p_x => // [y q]; rewrite [uniq _]/= -Dp => /andP[q'y Uq] p_x. rewrite -[RHS](nth_index y p_x); congr (nth y _ _); set i := index x p. have: i <= size q by rewrite -index_mem -/i Dp in p_x. case: ltngtP => // [lt_i_q|->] _; first by rewrite index_uniq. by apply/eqP; rewrite nth_default // eqn_leq index_size leqNgt index_mem. Qed. Lemma next_prev : cancel (prev p) (next p). Proof. move=> x; rewrite next_nth mem_prev prev_nth; case p_x: (x \in p) => //. case def_p: p p_x => // [y q]; rewrite -def_p => p_x. rewrite index_uniq //; last by rewrite def_p ltnS index_size. case q_x: (x \in q); first exact: nth_index. rewrite nth_default; last by rewrite leqNgt index_mem q_x. by apply/eqP; rewrite def_p inE q_x orbF eq_sym in p_x. Qed. Lemma cycle_next : fcycle (next p) p. Proof. case def_p: p Up => [|x q] Uq //; rewrite -[in next _]def_p. apply/(pathP x)=> i; rewrite size_rcons => le_i_q. rewrite -cats1 -cat_cons nth_cat le_i_q /= next_nth {}def_p mem_nth //. rewrite index_uniq // nth_cat /= ltn_neqAle andbC -ltnS le_i_q. by case: (i =P _) => //= ->; rewrite subnn nth_default. Qed. Lemma cycle_prev : cycle (fun x y => x == prev p y) p. Proof. apply: etrans cycle_next; symmetry; case def_p: p => [|x q] //. by apply: eq_path; rewrite -def_p; apply: (can2_eq prev_next next_prev). Qed. Lemma cycle_from_next : (forall x, x \in p -> e x (next p x)) -> cycle e p. Proof. case: p (next p) cycle_next => //= [x q] n; rewrite -(belast_rcons x q x). move: {q}(rcons q x) => q n_q /allP. by elim: q x n_q => //= _ q IHq x /andP[/eqP <- n_q] /andP[-> /IHq->]. Qed. Lemma cycle_from_prev : (forall x, x \in p -> e (prev p x) x) -> cycle e p. Proof. move=> e_p; apply: cycle_from_next => x. by rewrite -mem_next => /e_p; rewrite prev_next. Qed. Lemma next_rot : next (rot n0 p) =1 next p. Proof. move=> x; have n_p := cycle_next; rewrite -(rot_cycle n0) in n_p. case p_x: (x \in p); last by rewrite !next_nth mem_rot p_x. by rewrite (eqP (next_cycle n_p _)) ?mem_rot. Qed. Lemma prev_rot : prev (rot n0 p) =1 prev p. Proof. move=> x; have p_p := cycle_prev; rewrite -(rot_cycle n0) in p_p. case p_x: (x \in p); last by rewrite !prev_nth mem_rot p_x. by rewrite (eqP (prev_cycle p_p _)) ?mem_rot. Qed. End UniqCycle. Section UniqRotrCycle. Variables (n0 : nat) (T : eqType) (p : seq T). Hypothesis Up : uniq p. Lemma next_rotr : next (rotr n0 p) =1 next p. Proof. exact: next_rot. Qed. Lemma prev_rotr : prev (rotr n0 p) =1 prev p. Proof. exact: prev_rot. Qed. End UniqRotrCycle. Section UniqCycleRev. Variable T : eqType. Implicit Type p : seq T. Lemma prev_rev p : uniq p -> prev (rev p) =1 next p. Proof. move=> Up x; case p_x: (x \in p); last first. by rewrite next_nth prev_nth mem_rev p_x. case/rot_to: p_x (Up) => [i q def_p] Urp; rewrite -rev_uniq in Urp. rewrite -(prev_rotr i Urp); do 2 rewrite -(prev_rotr 1) ?rotr_uniq //. rewrite -rev_rot -(next_rot i Up) {i p Up Urp}def_p. by case: q => // y q; rewrite !rev_cons !(=^~ rcons_cons, rotr1_rcons) /= eqxx. Qed. Lemma next_rev p : uniq p -> next (rev p) =1 prev p. Proof. by move=> Up x; rewrite -[p in RHS]revK prev_rev // rev_uniq. Qed. End UniqCycleRev. Section MapPath. Variables (T T' : Type) (h : T' -> T) (e : rel T) (e' : rel T'). Definition rel_base (b : pred T) := forall x' y', ~~ b (h x') -> e (h x') (h y') = e' x' y'. Lemma map_path b x' p' (Bb : rel_base b) : ~~ has (preim h b) (belast x' p') -> path e (h x') (map h p') = path e' x' p'. Proof. by elim: p' x' => [|y' p' IHp'] x' //= /norP[/Bb-> /IHp'->]. Qed. End MapPath. Section MapEqPath. Variables (T T' : eqType) (h : T' -> T) (e : rel T) (e' : rel T'). Hypothesis Ih : injective h. Lemma mem2_map x' y' p' : mem2 (map h p') (h x') (h y') = mem2 p' x' y'. Proof. by rewrite [LHS]/mem2 (index_map Ih) -map_drop mem_map. Qed. Lemma next_map p : uniq p -> forall x, next (map h p) (h x) = h (next p x). Proof. move=> Up x; case p_x: (x \in p); last by rewrite !next_nth (mem_map Ih) p_x. case/rot_to: p_x => i p' def_p. rewrite -(next_rot i Up); rewrite -(map_inj_uniq Ih) in Up. rewrite -(next_rot i Up) -map_rot {i p Up}def_p /=. by case: p' => [|y p''] //=; rewrite !eqxx. Qed. Lemma prev_map p : uniq p -> forall x, prev (map h p) (h x) = h (prev p x). Proof. move=> Up x; rewrite -[x in LHS](next_prev Up) -(next_map Up). by rewrite prev_next ?map_inj_uniq. Qed. End MapEqPath. Definition fun_base (T T' : eqType) (h : T' -> T) f f' := rel_base h (frel f) (frel f'). Section CycleArc. Variable T : eqType. Implicit Type p : seq T. Definition arc p x y := let px := rot (index x p) p in take (index y px) px. Lemma arc_rot i p : uniq p -> {in p, arc (rot i p) =2 arc p}. Proof. move=> Up x p_x y; congr (fun q => take (index y q) q); move: Up p_x {y}. rewrite -{1 2 5 6}(cat_take_drop i p) /rot cat_uniq => /and3P[_ Up12 _]. rewrite !drop_cat !take_cat !index_cat mem_cat orbC. case p2x: (x \in drop i p) => /= => [_ | p1x]. rewrite index_mem p2x [x \in _](negbTE (hasPn Up12 _ p2x)) /= addKn. by rewrite ltnNge leq_addr catA. by rewrite p1x index_mem p1x addKn ltnNge leq_addr /= catA. Qed. Lemma left_arc x y p1 p2 (p := x :: p1 ++ y :: p2) : uniq p -> arc p x y = x :: p1. Proof. rewrite /arc /p [index x _]/= eqxx rot0 -cat_cons cat_uniq index_cat. move: (x :: p1) => xp1 /and3P[_ /norP[/= /negbTE-> _] _]. by rewrite eqxx addn0 take_size_cat. Qed. Lemma right_arc x y p1 p2 (p := x :: p1 ++ y :: p2) : uniq p -> arc p y x = y :: p2. Proof. rewrite -[p]cat_cons -rot_size_cat rot_uniq => Up. by rewrite arc_rot ?left_arc ?mem_head. Qed. Variant rot_to_arc_spec p x y := RotToArcSpec i p1 p2 of x :: p1 = arc p x y & y :: p2 = arc p y x & rot i p = x :: p1 ++ y :: p2 : rot_to_arc_spec p x y. Lemma rot_to_arc p x y : uniq p -> x \in p -> y \in p -> x != y -> rot_to_arc_spec p x y. Proof. move=> Up p_x p_y ne_xy; case: (rot_to p_x) (p_y) (Up) => [i q def_p] q_y. rewrite -(mem_rot i) def_p inE eq_sym (negbTE ne_xy) in q_y. rewrite -(rot_uniq i) def_p. case/splitPr: q / q_y def_p => q1 q2 def_p Uq12; exists i q1 q2 => //. by rewrite -(arc_rot i Up p_x) def_p left_arc. by rewrite -(arc_rot i Up p_y) def_p right_arc. Qed. End CycleArc. Prenex Implicits arc.
SMulAntidiagonal.lean
/- Copyright (c) 2024 Scott Carnahan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Carnahan -/ import Mathlib.Algebra.Group.Pointwise.Set.Scalar import Mathlib.Data.Set.SMulAntidiagonal /-! # Antidiagonal for scalar multiplication as a `Finset`. Given partially ordered sets `G` and `P`, with an action of `G` on `P` that preserves and reflects the order relation, we construct, for any element `a` in `P` and partially well-ordered subsets `s` in `G` and `t` in `P`, the `Finset` of all pairs of an element in `s` and an element in `t` that scalar-multiply to `a`. ## Definitions * Finset.SMulAntidiagonal : Finset antidiagonal for PWO inputs. * Finset.VAddAntidiagonal : Finset antidiagonal for PWO inputs. -/ variable {G P : Type*} open Pointwise namespace Set @[to_additive] theorem IsPWO.smul [Preorder G] [Preorder P] [SMul G P] [IsOrderedSMul G P] {s : Set G} {t : Set P} (hs : s.IsPWO) (ht : t.IsPWO) : IsPWO (s • t) := by rw [← @image_smul_prod] exact (hs.prod ht).image_of_monotone (monotone_fst.smul monotone_snd) @[to_additive] theorem IsWF.smul [LinearOrder G] [LinearOrder P] [SMul G P] [IsOrderedSMul G P] {s : Set G} {t : Set P} (hs : s.IsWF) (ht : t.IsWF) : IsWF (s • t) := (hs.isPWO.smul ht.isPWO).isWF @[to_additive] theorem IsWF.min_smul [LinearOrder G] [LinearOrder P] [SMul G P] [IsOrderedSMul G P] {s : Set G} {t : Set P} (hs : s.IsWF) (ht : t.IsWF) (hsn : s.Nonempty) (htn : t.Nonempty) : (hs.smul ht).min (hsn.smul htn) = hs.min hsn • ht.min htn := by refine le_antisymm (IsWF.min_le _ _ (mem_smul.2 ⟨_, hs.min_mem _, _, ht.min_mem _, rfl⟩)) ?_ rw [IsWF.le_min_iff] rintro _ ⟨x, hx, y, hy, rfl⟩ exact IsOrderedSMul.smul_le_smul (hs.min_le _ hx) (ht.min_le _ hy) end Set namespace Finset section open Set variable [PartialOrder G] [PartialOrder P] [SMul G P] [IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsPWO) (ht : t.IsPWO) (a : P) {u : Set G} {hu : u.IsPWO} {v : Set P} {hv : v.IsPWO} {x : G × P} /-- `Finset.SMulAntidiagonal hs ht a` is the set of all pairs of an element in `s` and an element in `t` whose scalar multiplication yields `a`, but its construction requires proofs that `s` and `t` are well-ordered. -/ @[to_additive /-- `Finset.VAddAntidiagonal hs ht a` is the set of all pairs of an element in `s` and an element in `t` whose vector addition yields `a`, but its construction requires proofs that `s` and `t` are well-ordered. -/] noncomputable def SMulAntidiagonal [PartialOrder G] [PartialOrder P] [IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsPWO) (ht : t.IsPWO) (a : P) : Finset (G × P) := (SMulAntidiagonal.finite_of_isPWO hs ht a).toFinset @[to_additive (attr := simp)] theorem mem_smulAntidiagonal : x ∈ SMulAntidiagonal hs ht a ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 • x.2 = a := by simp only [SMulAntidiagonal, Set.Finite.mem_toFinset] exact Set.mem_sep_iff @[to_additive] theorem smulAntidiagonal_mono_left {a : P} {hs : s.IsPWO} {ht : t.IsPWO} (h : u ⊆ s) : SMulAntidiagonal hu ht a ⊆ SMulAntidiagonal hs ht a := Set.Finite.toFinset_mono <| Set.smulAntidiagonal_mono_left h @[to_additive] theorem smulAntidiagonal_mono_right {a : P} {hs : s.IsPWO} {ht : t.IsPWO} (h : v ⊆ t) : SMulAntidiagonal hs hv a ⊆ SMulAntidiagonal hs ht a := Set.Finite.toFinset_mono <| Set.smulAntidiagonal_mono_right h @[to_additive] theorem support_smulAntidiagonal_subset_smul {hs : s.IsPWO} {ht : t.IsPWO} : { a | (SMulAntidiagonal hs ht a).Nonempty } ⊆ (s • t) := fun a ⟨b, hb⟩ => by rw [mem_smulAntidiagonal] at hb rw [Set.mem_smul] use b.1 refine { left := hb.1, right := ?_ } use b.2 exact { left := hb.2.1, right := hb.2.2 } @[to_additive] theorem isPWO_support_smulAntidiagonal {hs : s.IsPWO} {ht : t.IsPWO} : { a | (SMulAntidiagonal hs ht a).Nonempty }.IsPWO := (hs.smul ht).mono (support_smulAntidiagonal_subset_smul) end @[to_additive] theorem smulAntidiagonal_min_smul_min [LinearOrder G] [LinearOrder P] [SMul G P] [IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsWF) (ht : t.IsWF) (hns : s.Nonempty) (hnt : t.Nonempty) : SMulAntidiagonal hs.isPWO ht.isPWO (hs.min hns • ht.min hnt) = {(hs.min hns, ht.min hnt)} := by ext ⟨a, b⟩ simp only [mem_smulAntidiagonal, mem_singleton, Prod.ext_iff] constructor · rintro ⟨has, hat, hst⟩ obtain rfl := (hs.min_le hns has).eq_of_not_lt fun hlt => (SMul.smul_lt_smul_of_lt_of_le hlt <| ht.min_le hnt hat).ne' hst exact ⟨rfl, IsCancelSMul.left_cancel _ _ _ hst⟩ · rintro ⟨rfl, rfl⟩ exact ⟨hs.min_mem _, ht.min_mem _, rfl⟩ end Finset
Measure.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Analysis.Normed.Affine.AddTorsorBases import Mathlib.Analysis.Normed.Module.Convex import Mathlib.MeasureTheory.Measure.Lebesgue.EqHaar /-! # Convex sets are null-measurable Let `E` be a finite dimensional real vector space, let `μ` be a Haar measure on `E`, let `s` be a convex set in `E`. Then the frontier of `s` has measure zero (see `Convex.addHaar_frontier`), hence `s` is a `NullMeasurableSet` (see `Convex.nullMeasurableSet`). -/ open MeasureTheory MeasureTheory.Measure Set Metric Filter Bornology open Module (finrank) open scoped Topology NNReal ENNReal variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [MeasurableSpace E] [BorelSpace E] [FiniteDimensional ℝ E] (μ : Measure E) [IsAddHaarMeasure μ] {s : Set E} namespace Convex /-- Haar measure of the frontier of a convex set is zero. -/ theorem addHaar_frontier (hs : Convex ℝ s) : μ (frontier s) = 0 := by /- If `s` is included in a hyperplane, then `frontier s ⊆ closure s` is included in the same hyperplane, hence it has measure zero. -/ rcases ne_or_eq (affineSpan ℝ s) ⊤ with hspan | hspan · refine measure_mono_null ?_ (addHaar_affineSubspace _ _ hspan) exact frontier_subset_closure.trans (closure_minimal (subset_affineSpan _ _) (affineSpan ℝ s).closed_of_finiteDimensional) rw [← hs.interior_nonempty_iff_affineSpan_eq_top] at hspan rcases hspan with ⟨x, hx⟩ /- Without loss of generality, `s` is bounded. Indeed, `∂s ⊆ ⋃ n, ∂(s ∩ ball x (n + 1))`, hence it suffices to prove that `∀ n, μ (s ∩ ball x (n + 1)) = 0`; the latter set is bounded. -/ suffices H : ∀ t : Set E, Convex ℝ t → x ∈ interior t → IsBounded t → μ (frontier t) = 0 by let B : ℕ → Set E := fun n => ball x (n + 1) have : μ (⋃ n : ℕ, frontier (s ∩ B n)) = 0 := by refine measure_iUnion_null fun n => H _ (hs.inter (convex_ball _ _)) ?_ (isBounded_ball.subset inter_subset_right) rw [interior_inter, isOpen_ball.interior_eq] exact ⟨hx, mem_ball_self (add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one)⟩ refine measure_mono_null (fun y hy => ?_) this; clear this set N : ℕ := ⌊dist y x⌋₊ refine mem_iUnion.2 ⟨N, ?_⟩ have hN : y ∈ B N := by simp [B, N, Nat.lt_floor_add_one] suffices y ∈ frontier (s ∩ B N) ∩ B N from this.1 rw [frontier_inter_open_inter isOpen_ball] exact ⟨hy, hN⟩ intro s hs hx hb /- Since `s` is bounded, we have `μ (interior s) ≠ ∞`, hence it suffices to prove `μ (closure s) ≤ μ (interior s)`. -/ replace hb : μ (interior s) ≠ ∞ := (hb.subset interior_subset).measure_lt_top.ne suffices μ (closure s) ≤ μ (interior s) by rwa [frontier, measure_diff interior_subset_closure isOpen_interior.nullMeasurableSet hb, tsub_eq_zero_iff_le] /- Due to `Convex.closure_subset_image_homothety_interior_of_one_lt`, for any `r > 1` we have `closure s ⊆ homothety x r '' interior s`, hence `μ (closure s) ≤ r ^ d * μ (interior s)`, where `d = finrank ℝ E`. -/ set d : ℕ := Module.finrank ℝ E have : ∀ r : ℝ≥0, 1 < r → μ (closure s) ≤ ↑(r ^ d) * μ (interior s) := fun r hr ↦ by refine (measure_mono <| hs.closure_subset_image_homothety_interior_of_one_lt hx r hr).trans_eq ?_ rw [addHaar_image_homothety, ← NNReal.coe_pow, NNReal.abs_eq, ENNReal.ofReal_coe_nnreal] have : ∀ᶠ (r : ℝ≥0) in 𝓝[>] 1, μ (closure s) ≤ ↑(r ^ d) * μ (interior s) := mem_of_superset self_mem_nhdsWithin this -- Taking the limit as `r → 1`, we get `μ (closure s) ≤ μ (interior s)`. refine ge_of_tendsto ?_ this refine (((ENNReal.continuous_mul_const hb).comp (ENNReal.continuous_coe.comp (continuous_pow d))).tendsto' _ _ ?_).mono_left nhdsWithin_le_nhds simp /-- A convex set in a finite dimensional real vector space is null measurable with respect to an additive Haar measure on this space. -/ protected theorem nullMeasurableSet (hs : Convex ℝ s) : NullMeasurableSet s μ := nullMeasurableSet_of_null_frontier (hs.addHaar_frontier μ) end Convex
BubbleSortInduction.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.Data.Fin.Tuple.Sort import Mathlib.Order.WellFounded import Mathlib.Order.PiLex import Mathlib.Data.Finite.Prod /-! # "Bubble sort" induction We implement the following induction principle `Tuple.bubble_sort_induction` on tuples with values in a linear order `α`. Let `f : Fin n → α` and let `P` be a predicate on `Fin n → α`. Then we can show that `f ∘ sort f` satisfies `P` if `f` satisfies `P`, and whenever some `g : Fin n → α` satisfies `P` and `g i > g j` for some `i < j`, then `g ∘ swap i j` also satisfies `P`. We deduce it from a stronger variant `Tuple.bubble_sort_induction'`, which requires the assumption only for `g` that are permutations of `f`. The latter is proved by well-founded induction via `WellFounded.induction_bot'` with respect to the lexicographic ordering on the finite set of all permutations of `f`. -/ namespace Tuple /-- *Bubble sort induction*: Prove that the sorted version of `f` has some property `P` if `f` satisfies `P` and `P` is preserved on permutations of `f` when swapping two antitone values. -/ theorem bubble_sort_induction' {n : ℕ} {α : Type*} [LinearOrder α] {f : Fin n → α} {P : (Fin n → α) → Prop} (hf : P f) (h : ∀ (σ : Equiv.Perm (Fin n)) (i j : Fin n), i < j → (f ∘ σ) j < (f ∘ σ) i → P (f ∘ σ) → P (f ∘ σ ∘ Equiv.swap i j)) : P (f ∘ sort f) := by letI := @Preorder.lift _ (Lex (Fin n → α)) _ fun σ : Equiv.Perm (Fin n) => toLex (f ∘ σ) refine @WellFounded.induction_bot' _ _ _ (IsWellFounded.wf : WellFounded (· < ·)) (Equiv.refl _) (sort f) P (fun σ => f ∘ σ) (fun σ hσ hfσ => ?_) hf obtain ⟨i, j, hij₁, hij₂⟩ := antitone_pair_of_not_sorted' hσ exact ⟨σ * Equiv.swap i j, Pi.lex_desc hij₁.le hij₂, h σ i j hij₁ hij₂ hfσ⟩ /-- *Bubble sort induction*: Prove that the sorted version of `f` has some property `P` if `f` satisfies `P` and `P` is preserved when swapping two antitone values. -/ theorem bubble_sort_induction {n : ℕ} {α : Type*} [LinearOrder α] {f : Fin n → α} {P : (Fin n → α) → Prop} (hf : P f) (h : ∀ (g : Fin n → α) (i j : Fin n), i < j → g j < g i → P g → P (g ∘ Equiv.swap i j)) : P (f ∘ sort f) := bubble_sort_induction' hf fun _ => h _ end Tuple
Operations.lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Filippo A. E. Nuccio -/ import Mathlib.Algebra.EuclideanDomain.Basic import Mathlib.RingTheory.FractionalIdeal.Basic import Mathlib.RingTheory.IntegralClosure.IsIntegral.Basic import Mathlib.RingTheory.LocalRing.Basic import Mathlib.RingTheory.PrincipalIdealDomain import Mathlib.Tactic.FieldSimp /-! # More operations on fractional ideals ## Main definitions * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R⁰ = R \ {0}` (i.e. the field of fractions). * `FractionalIdeal R⁰ K` is the type of fractional ideals in the field of fractions * `Div (FractionalIdeal R⁰ K)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statement * `isNoetherian` states that every fractional ideal of a noetherian integral domain is noetherian ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open IsLocalization Pointwise nonZeroDivisors namespace FractionalIdeal open Set Submodule variable {R : Type*} [CommRing R] {S : Submonoid R} {P : Type*} [CommRing P] variable [Algebra R P] section variable {P' : Type*} [CommRing P'] [Algebra R P'] variable {P'' : Type*} [CommRing P''] [Algebra R P''] theorem _root_.IsFractional.map (g : P →ₐ[R] P') {I : Submodule R P} : IsFractional S I → IsFractional S (Submodule.map g.toLinearMap I) | ⟨a, a_nonzero, hI⟩ => ⟨a, a_nonzero, fun b hb => by obtain ⟨b', b'_mem, hb'⟩ := Submodule.mem_map.mp hb rw [AlgHom.toLinearMap_apply] at hb' obtain ⟨x, hx⟩ := hI b' b'_mem use x rw [← g.commutes, hx, map_smul, hb']⟩ /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : P →ₐ[R] P') : FractionalIdeal S P → FractionalIdeal S P' := fun I => ⟨Submodule.map g.toLinearMap I, I.isFractional.map g⟩ @[simp, norm_cast] theorem coe_map (g : P →ₐ[R] P') (I : FractionalIdeal S P) : ↑(map g I) = Submodule.map g.toLinearMap I := rfl @[simp] theorem mem_map {I : FractionalIdeal S P} {g : P →ₐ[R] P'} {y : P'} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y := Submodule.mem_map variable (I J : FractionalIdeal S P) (g : P →ₐ[R] P') @[simp] theorem map_id : I.map (AlgHom.id _ _) = I := coeToSubmodule_injective (Submodule.map_id (I : Submodule R P)) @[simp] theorem map_comp (g' : P' →ₐ[R] P'') : I.map (g'.comp g) = (I.map g).map g' := coeToSubmodule_injective (Submodule.map_comp g.toLinearMap g'.toLinearMap I) @[simp, norm_cast] theorem map_coeIdeal (I : Ideal R) : (I : FractionalIdeal S P).map g = I := by ext x simp @[simp] protected theorem map_one : (1 : FractionalIdeal S P).map g = 1 := map_coeIdeal g ⊤ @[simp] protected theorem map_zero : (0 : FractionalIdeal S P).map g = 0 := map_coeIdeal g 0 @[simp] protected theorem map_add : (I + J).map g = I.map g + J.map g := coeToSubmodule_injective (Submodule.map_sup _ _ _) @[simp] protected theorem map_mul : (I * J).map g = I.map g * J.map g := by simp only [mul_def] exact coeToSubmodule_injective (Submodule.map_mul _ _ _) @[simp] theorem map_map_symm (g : P ≃ₐ[R] P') : (I.map (g : P →ₐ[R] P')).map (g.symm : P' →ₐ[R] P) = I := by rw [← map_comp, g.symm_comp, map_id] @[simp] theorem map_symm_map (I : FractionalIdeal S P') (g : P ≃ₐ[R] P') : (I.map (g.symm : P' →ₐ[R] P)).map (g : P →ₐ[R] P') = I := by rw [← map_comp, g.comp_symm, map_id] theorem map_mem_map {f : P →ₐ[R] P'} (h : Function.Injective f) {x : P} {I : FractionalIdeal S P} : f x ∈ map f I ↔ x ∈ I := mem_map.trans ⟨fun ⟨_, hx', x'_eq⟩ => h x'_eq ▸ hx', fun h => ⟨x, h, rfl⟩⟩ theorem map_injective (f : P →ₐ[R] P') (h : Function.Injective f) : Function.Injective (map f : FractionalIdeal S P → FractionalIdeal S P') := fun _ _ hIJ => ext fun _ => (map_mem_map h).symm.trans (hIJ.symm ▸ map_mem_map h) /-- If `g` is an equivalence, `map g` is an isomorphism -/ def mapEquiv (g : P ≃ₐ[R] P') : FractionalIdeal S P ≃+* FractionalIdeal S P' where toFun := map g invFun := map g.symm map_add' I J := FractionalIdeal.map_add I J _ map_mul' I J := FractionalIdeal.map_mul I J _ left_inv I := by rw [← map_comp, AlgEquiv.symm_comp, map_id] right_inv I := by rw [← map_comp, AlgEquiv.comp_symm, map_id] @[simp] theorem coeFun_mapEquiv (g : P ≃ₐ[R] P') : (mapEquiv g : FractionalIdeal S P → FractionalIdeal S P') = map g := rfl @[simp] theorem mapEquiv_apply (g : P ≃ₐ[R] P') (I : FractionalIdeal S P) : mapEquiv g I = map (↑g) I := rfl @[simp] theorem mapEquiv_symm (g : P ≃ₐ[R] P') : ((mapEquiv g).symm : FractionalIdeal S P' ≃+* _) = mapEquiv g.symm := rfl @[simp] theorem mapEquiv_refl : mapEquiv AlgEquiv.refl = RingEquiv.refl (FractionalIdeal S P) := RingEquiv.ext fun x => by simp theorem isFractional_span_iff {s : Set P} : IsFractional S (span R s) ↔ ∃ a ∈ S, ∀ b : P, b ∈ s → IsInteger R (a • b) := ⟨fun ⟨a, a_mem, h⟩ => ⟨a, a_mem, fun b hb => h b (subset_span hb)⟩, fun ⟨a, a_mem, h⟩ => ⟨a, a_mem, fun _ hb => span_induction (hx := hb) h (by rw [smul_zero] exact isInteger_zero) (fun x y _ _ hx hy => by rw [smul_add] exact isInteger_add hx hy) fun s x _ hx => by rw [smul_comm] exact isInteger_smul hx⟩⟩ theorem isFractional_of_fg [IsLocalization S P] {I : Submodule R P} (hI : I.FG) : IsFractional S I := by rcases hI with ⟨I, rfl⟩ rcases exist_integer_multiples_of_finset S I with ⟨⟨s, hs1⟩, hs⟩ rw [isFractional_span_iff] exact ⟨s, hs1, hs⟩ theorem mem_span_mul_finite_of_mem_mul {I J : FractionalIdeal S P} {x : P} (hx : x ∈ I * J) : ∃ T T' : Finset P, (T : Set P) ⊆ I ∧ (T' : Set P) ⊆ J ∧ x ∈ span R (T * T' : Set P) := Submodule.mem_span_mul_finite_of_mem_mul (by simpa using mem_coe.mpr hx) variable (S) in theorem coeIdeal_fg (inj : Function.Injective (algebraMap R P)) (I : Ideal R) : FG ((I : FractionalIdeal S P) : Submodule R P) ↔ I.FG := coeSubmodule_fg _ inj _ theorem fg_unit (I : (FractionalIdeal S P)ˣ) : FG (I : Submodule R P) := Submodule.fg_unit <| Units.map (coeSubmoduleHom S P).toMonoidHom I theorem fg_of_isUnit (I : FractionalIdeal S P) (h : IsUnit I) : FG (I : Submodule R P) := fg_unit h.unit theorem _root_.Ideal.fg_of_isUnit (inj : Function.Injective (algebraMap R P)) (I : Ideal R) (h : IsUnit (I : FractionalIdeal S P)) : I.FG := by rw [← coeIdeal_fg S inj I] exact FractionalIdeal.fg_of_isUnit (R := R) I h variable (S P P') variable [IsLocalization S P] [IsLocalization S P'] /-- `canonicalEquiv f f'` is the canonical equivalence between the fractional ideals in `P` and in `P'`, which are both localizations of `R` at `S`. -/ noncomputable irreducible_def canonicalEquiv : FractionalIdeal S P ≃+* FractionalIdeal S P' := mapEquiv { ringEquivOfRingEquiv P P' (RingEquiv.refl R) (show S.map _ = S by rw [RingEquiv.toMonoidHom_refl, Submonoid.map_id]) with commutes' := fun _ => ringEquivOfRingEquiv_eq _ _ } @[simp] theorem mem_canonicalEquiv_apply {I : FractionalIdeal S P} {x : P'} : x ∈ canonicalEquiv S P P' I ↔ ∃ y ∈ I, IsLocalization.map P' (RingHom.id R) (fun y (hy : y ∈ S) => show RingHom.id R y ∈ S from hy) (y : P) = x := by rw [canonicalEquiv, mapEquiv_apply, mem_map] exact ⟨fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩, fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩⟩ @[simp] theorem canonicalEquiv_symm : (canonicalEquiv S P P').symm = canonicalEquiv S P' P := RingEquiv.ext fun I => SetLike.ext_iff.mpr fun x => by rw [mem_canonicalEquiv_apply, canonicalEquiv, mapEquiv_symm, mapEquiv_apply, mem_map] exact ⟨fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩, fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩⟩ theorem canonicalEquiv_flip (I) : canonicalEquiv S P P' (canonicalEquiv S P' P I) = I := by rw [← canonicalEquiv_symm, RingEquiv.symm_apply_apply] @[simp] theorem canonicalEquiv_canonicalEquiv (P'' : Type*) [CommRing P''] [Algebra R P''] [IsLocalization S P''] (I : FractionalIdeal S P) : canonicalEquiv S P' P'' (canonicalEquiv S P P' I) = canonicalEquiv S P P'' I := by ext simp only [IsLocalization.map_map, RingHomInvPair.comp_eq₂, mem_canonicalEquiv_apply, exists_exists_and_eq_and] theorem canonicalEquiv_trans_canonicalEquiv (P'' : Type*) [CommRing P''] [Algebra R P''] [IsLocalization S P''] : (canonicalEquiv S P P').trans (canonicalEquiv S P' P'') = canonicalEquiv S P P'' := RingEquiv.ext (canonicalEquiv_canonicalEquiv S P P' P'') @[simp] theorem canonicalEquiv_coeIdeal (I : Ideal R) : canonicalEquiv S P P' I = I := by ext simp [IsLocalization.map_eq] @[simp] theorem canonicalEquiv_self : canonicalEquiv S P P = RingEquiv.refl _ := by rw [← canonicalEquiv_trans_canonicalEquiv S P P] convert (canonicalEquiv S P P).symm_trans_self exact (canonicalEquiv_symm S P P).symm end section IsFractionRing /-! ### `IsFractionRing` section This section concerns fractional ideals in the field of fractions, i.e. the type `FractionalIdeal R⁰ K` where `IsFractionRing R K`. -/ variable {K K' : Type*} [Field K] [Field K'] variable [Algebra R K] [IsFractionRing R K] [Algebra R K'] [IsFractionRing R K'] variable {I J : FractionalIdeal R⁰ K} (h : K →ₐ[R] K') /-- Nonzero fractional ideals contain a nonzero integer. -/ theorem exists_ne_zero_mem_isInteger [Nontrivial R] (hI : I ≠ 0) : ∃ x, x ≠ 0 ∧ algebraMap R K x ∈ I := by obtain ⟨y : K, y_mem, y_notMem⟩ := SetLike.exists_of_lt (by simpa only using bot_lt_iff_ne_bot.mpr hI) have y_ne_zero : y ≠ 0 := by simpa using y_notMem obtain ⟨z, ⟨x, hx⟩⟩ := exists_integer_multiple R⁰ y refine ⟨x, ?_, ?_⟩ · rw [Ne, ← @IsFractionRing.to_map_eq_zero_iff R _ K, hx, Algebra.smul_def] exact mul_ne_zero (IsFractionRing.to_map_ne_zero_of_mem_nonZeroDivisors z.2) y_ne_zero · rw [hx] exact smul_mem _ _ y_mem theorem map_ne_zero [Nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 := by obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_isInteger hI contrapose! x_ne_zero with map_eq_zero refine IsFractionRing.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr ?_)) exact ⟨algebraMap R K x, hx, h.commutes x⟩ @[simp] theorem map_eq_zero_iff [Nontrivial R] : I.map h = 0 ↔ I = 0 := ⟨not_imp_not.mp (map_ne_zero _), fun hI => hI.symm ▸ FractionalIdeal.map_zero h⟩ theorem coeIdeal_injective : Function.Injective (fun (I : Ideal R) ↦ (I : FractionalIdeal R⁰ K)) := coeIdeal_injective' le_rfl theorem coeIdeal_inj {I J : Ideal R} : (I : FractionalIdeal R⁰ K) = (J : FractionalIdeal R⁰ K) ↔ I = J := coeIdeal_inj' le_rfl @[simp] theorem coeIdeal_eq_zero {I : Ideal R} : (I : FractionalIdeal R⁰ K) = 0 ↔ I = ⊥ := coeIdeal_eq_zero' le_rfl theorem coeIdeal_ne_zero {I : Ideal R} : (I : FractionalIdeal R⁰ K) ≠ 0 ↔ I ≠ ⊥ := coeIdeal_ne_zero' le_rfl @[simp] theorem coeIdeal_eq_one {I : Ideal R} : (I : FractionalIdeal R⁰ K) = 1 ↔ I = 1 := by simpa only [Ideal.one_eq_top] using coeIdeal_inj theorem coeIdeal_ne_one {I : Ideal R} : (I : FractionalIdeal R⁰ K) ≠ 1 ↔ I ≠ 1 := not_iff_not.mpr coeIdeal_eq_one theorem num_eq_zero_iff [Nontrivial R] {I : FractionalIdeal R⁰ K} : I.num = 0 ↔ I = 0 where mp h := zero_of_num_eq_bot zero_notMem_nonZeroDivisors h mpr h := h ▸ num_zero_eq (IsFractionRing.injective R K) end IsFractionRing section Quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = nonZeroDivisors R`, `R`'s localization at which is a field because `R` is a domain. -/ variable {R₁ : Type*} [CommRing R₁] {K : Type*} [Field K] variable [Algebra R₁ K] instance : Nontrivial (FractionalIdeal R₁⁰ K) := ⟨⟨0, 1, fun h => have this : (1 : K) ∈ (0 : FractionalIdeal R₁⁰ K) := by rw [← (algebraMap R₁ K).map_one] simpa only [h] using coe_mem_one R₁⁰ 1 one_ne_zero ((mem_zero_iff _).mp this)⟩⟩ theorem ne_zero_of_mul_eq_one (I J : FractionalIdeal R₁⁰ K) (h : I * J = 1) : I ≠ 0 := fun hI => zero_ne_one' (FractionalIdeal R₁⁰ K) (by convert h simp [hI]) variable [IsFractionRing R₁ K] [IsDomain R₁] theorem _root_.IsFractional.div_of_nonzero {I J : Submodule R₁ K} : IsFractional R₁⁰ I → IsFractional R₁⁰ J → J ≠ 0 → IsFractional R₁⁰ (I / J) | ⟨aI, haI, hI⟩, ⟨aJ, haJ, hJ⟩, h => by obtain ⟨y, mem_J, notMem_zero⟩ := SetLike.exists_of_lt (show 0 < J by simpa only using bot_lt_iff_ne_bot.mpr h) obtain ⟨y', hy'⟩ := hJ y mem_J use aI * y' constructor · apply (nonZeroDivisors R₁).mul_mem haI (mem_nonZeroDivisors_iff_ne_zero.mpr _) intro y'_eq_zero have : algebraMap R₁ K aJ * y = 0 := by rw [← Algebra.smul_def, ← hy', y'_eq_zero, RingHom.map_zero] have y_zero := (mul_eq_zero.mp this).resolve_left (mt ((injective_iff_map_eq_zero (algebraMap R₁ K)).1 (IsFractionRing.injective _ _) _) (mem_nonZeroDivisors_iff_ne_zero.mp haJ)) apply notMem_zero simpa intro b hb convert hI _ (hb _ (Submodule.smul_mem _ aJ mem_J)) using 1 rw [← hy', mul_comm b, ← Algebra.smul_def, mul_smul] theorem fractional_div_of_nonzero {I J : FractionalIdeal R₁⁰ K} (h : J ≠ 0) : IsFractional R₁⁰ (I / J : Submodule R₁ K) := I.isFractional.div_of_nonzero J.isFractional fun H => h <| coeToSubmodule_injective <| H.trans coe_zero.symm open Classical in noncomputable instance : Div (FractionalIdeal R₁⁰ K) := ⟨fun I J => if h : J = 0 then 0 else ⟨I / J, fractional_div_of_nonzero h⟩⟩ variable {I J : FractionalIdeal R₁⁰ K} @[simp] theorem div_zero {I : FractionalIdeal R₁⁰ K} : I / 0 = 0 := dif_pos rfl theorem div_nonzero {I J : FractionalIdeal R₁⁰ K} (h : J ≠ 0) : I / J = ⟨I / J, fractional_div_of_nonzero h⟩ := dif_neg h @[simp] theorem coe_div {I J : FractionalIdeal R₁⁰ K} (hJ : J ≠ 0) : (↑(I / J) : Submodule R₁ K) = ↑I / (↑J : Submodule R₁ K) := congr_arg _ (dif_neg hJ) theorem mem_div_iff_of_nonzero {I J : FractionalIdeal R₁⁰ K} (h : J ≠ 0) {x} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := by rw [div_nonzero h] exact Submodule.mem_div_iff_forall_mul_mem theorem mul_one_div_le_one {I : FractionalIdeal R₁⁰ K} : I * (1 / I) ≤ 1 := by by_cases hI : I = 0 · rw [hI, div_zero, mul_zero] exact zero_le 1 · rw [← coe_le_coe, coe_mul, coe_div hI, coe_one] apply Submodule.mul_one_div_le_one theorem le_self_mul_one_div {I : FractionalIdeal R₁⁰ K} (hI : I ≤ (1 : FractionalIdeal R₁⁰ K)) : I ≤ I * (1 / I) := by by_cases hI_nz : I = 0 · rw [hI_nz, div_zero, mul_zero] · rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one] rw [← coe_le_coe, coe_one] at hI exact Submodule.le_self_mul_one_div hI theorem le_div_iff_of_nonzero {I J J' : FractionalIdeal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ ∀ x ∈ I, ∀ y ∈ J', x * y ∈ J := ⟨fun h _ hx => (mem_div_iff_of_nonzero hJ').mp (h hx), fun h x hx => (mem_div_iff_of_nonzero hJ').mpr (h x hx)⟩ theorem le_div_iff_mul_le {I J J' : FractionalIdeal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ I * J' ≤ J := by rw [div_nonzero hJ'] -- Porting note: this used to be { convert; rw }, flipped the order. rw [← coe_le_coe (I := I * J') (J := J), coe_mul] exact Submodule.le_div_iff_mul_le @[simp] theorem div_one {I : FractionalIdeal R₁⁰ K} : I / 1 = I := by rw [div_nonzero (one_ne_zero' (FractionalIdeal R₁⁰ K))] ext constructor <;> intro h · simpa using mem_div_iff_forall_mul_mem.mp h 1 ((algebraMap R₁ K).map_one ▸ coe_mem_one R₁⁰ 1) · apply mem_div_iff_forall_mul_mem.mpr rintro y ⟨y', _, rfl⟩ -- Porting note: this used to be { convert; rw }, flipped the order. rw [mul_comm, Algebra.linearMap_apply, ← Algebra.smul_def] exact Submodule.smul_mem _ y' h theorem eq_one_div_of_mul_eq_one_right (I J : FractionalIdeal R₁⁰ K) (h : I * J = 1) : J = 1 / I := by have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h suffices h' : I * (1 / I) = 1 from congr_arg Units.inv <| @Units.ext _ _ (Units.mkOfMulEqOne _ _ h) (Units.mkOfMulEqOne _ _ h') rfl apply le_antisymm · apply mul_le.mpr _ intro x hx y hy rw [mul_comm] exact (mem_div_iff_of_nonzero hI).mp hy x hx rw [← h] apply mul_left_mono I apply (le_div_iff_of_nonzero hI).mpr _ intro y hy x hx rw [mul_comm] exact mul_mem_mul hy hx theorem mul_div_self_cancel_iff {I : FractionalIdeal R₁⁰ K} : I * (1 / I) = 1 ↔ ∃ J, I * J = 1 := ⟨fun h => ⟨1 / I, h⟩, fun ⟨J, hJ⟩ => by rwa [← eq_one_div_of_mul_eq_one_right I J hJ]⟩ variable {K' : Type*} [Field K'] [Algebra R₁ K'] [IsFractionRing R₁ K'] @[simp] protected theorem map_div (I J : FractionalIdeal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I / J).map (h : K →ₐ[R₁] K') = I.map h / J.map h := by by_cases H : J = 0 · rw [H, div_zero, FractionalIdeal.map_zero, div_zero] · -- Porting note: `simp` wouldn't apply these lemmas so do them manually using `rw` rw [← coeToSubmodule_inj, div_nonzero H, div_nonzero (map_ne_zero _ H)] simp [Submodule.map_div] -- Porting note: doesn't need to be @[simp] because this follows from `map_one` and `map_div` theorem map_one_div (I : FractionalIdeal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (1 / I).map (h : K →ₐ[R₁] K') = 1 / I.map h := by rw [FractionalIdeal.map_div, FractionalIdeal.map_one] end Quotient section Field variable {R₁ K L : Type*} [CommRing R₁] [Field K] [Field L] variable [Algebra R₁ K] [IsFractionRing R₁ K] [Algebra K L] [IsFractionRing K L] theorem eq_zero_or_one (I : FractionalIdeal K⁰ L) : I = 0 ∨ I = 1 := by rw [or_iff_not_imp_left] intro hI simp_rw [@SetLike.ext_iff _ _ _ I 1, mem_one_iff] intro x constructor · intro x_mem obtain ⟨n, d, rfl⟩ := IsLocalization.mk'_surjective K⁰ x refine ⟨n / d, ?_⟩ rw [map_div₀, IsFractionRing.mk'_eq_div] · rintro ⟨x, rfl⟩ obtain ⟨y, y_ne, y_mem⟩ := exists_ne_zero_mem_isInteger hI rw [← div_mul_cancel₀ x y_ne, RingHom.map_mul, ← Algebra.smul_def] exact smul_mem (M := L) I (x / y) y_mem theorem eq_zero_or_one_of_isField (hF : IsField R₁) (I : FractionalIdeal R₁⁰ K) : I = 0 ∨ I = 1 := letI : Field R₁ := hF.toField eq_zero_or_one I end Field section PrincipalIdeal variable {R₁ : Type*} [CommRing R₁] {K : Type*} [Field K] variable [Algebra R₁ K] [IsFractionRing R₁ K] variable (R₁) /-- `FractionalIdeal.span_finset R₁ s f` is the fractional ideal of `R₁` generated by `f '' s`. -/ -- Porting note: `@[simps]` generated a `Subtype.val` coercion instead of a -- `FractionalIdeal.coeToSubmodule` coercion def spanFinset {ι : Type*} (s : Finset ι) (f : ι → K) : FractionalIdeal R₁⁰ K := ⟨Submodule.span R₁ (f '' s), by obtain ⟨a', ha'⟩ := IsLocalization.exist_integer_multiples R₁⁰ s f refine ⟨a', a'.2, fun x hx => Submodule.span_induction ?_ ?_ ?_ ?_ hx⟩ · rintro _ ⟨i, hi, rfl⟩ exact ha' i hi · rw [smul_zero] exact IsLocalization.isInteger_zero · intro x y _ _ hx hy rw [smul_add] exact IsLocalization.isInteger_add hx hy · intro c x _ hx rw [smul_comm] exact IsLocalization.isInteger_smul hx⟩ @[simp] lemma spanFinset_coe {ι : Type*} (s : Finset ι) (f : ι → K) : (spanFinset R₁ s f : Submodule R₁ K) = Submodule.span R₁ (f '' s) := rfl variable {R₁} @[simp] theorem spanFinset_eq_zero {ι : Type*} {s : Finset ι} {f : ι → K} : spanFinset R₁ s f = 0 ↔ ∀ j ∈ s, f j = 0 := by simp only [← coeToSubmodule_inj, spanFinset_coe, coe_zero, Submodule.span_eq_bot, Set.mem_image, Finset.mem_coe, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] theorem spanFinset_ne_zero {ι : Type*} {s : Finset ι} {f : ι → K} : spanFinset R₁ s f ≠ 0 ↔ ∃ j ∈ s, f j ≠ 0 := by simp open Submodule.IsPrincipal variable [IsLocalization S P] theorem isFractional_span_singleton (x : P) : IsFractional S (span R {x} : Submodule R P) := let ⟨a, ha⟩ := exists_integer_multiple S x isFractional_span_iff.mpr ⟨a, a.2, fun _ hx' => (Set.mem_singleton_iff.mp hx').symm ▸ ha⟩ variable (S) /-- `spanSingleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ irreducible_def spanSingleton (x : P) : FractionalIdeal S P := ⟨span R {x}, isFractional_span_singleton x⟩ -- local attribute [semireducible] span_singleton @[simp] theorem coe_spanSingleton (x : P) : (spanSingleton S x : Submodule R P) = span R {x} := by rw [spanSingleton] rfl @[simp] theorem mem_spanSingleton {x y : P} : x ∈ spanSingleton S y ↔ ∃ z : R, z • y = x := by rw [spanSingleton] exact Submodule.mem_span_singleton theorem mem_spanSingleton_self (x : P) : x ∈ spanSingleton S x := (mem_spanSingleton S).mpr ⟨1, one_smul _ _⟩ variable (P) in /-- A version of `FractionalIdeal.den_mul_self_eq_num` in terms of fractional ideals. -/ theorem den_mul_self_eq_num' (I : FractionalIdeal S P) : spanSingleton S (algebraMap R P I.den) * I = I.num := by apply coeToSubmodule_injective dsimp only rw [coe_mul, ← smul_eq_mul, coe_spanSingleton, smul_eq_mul, Submodule.span_singleton_mul] convert I.den_mul_self_eq_num using 1 ext rw [mem_smul_pointwise_iff_exists, mem_smul_pointwise_iff_exists] simp [smul_eq_mul, Algebra.smul_def, Submonoid.smul_def] variable {S} @[simp] theorem spanSingleton_le_iff_mem {x : P} {I : FractionalIdeal S P} : spanSingleton S x ≤ I ↔ x ∈ I := by rw [← coe_le_coe, coe_spanSingleton, Submodule.span_singleton_le_iff_mem, mem_coe] theorem spanSingleton_eq_spanSingleton [NoZeroSMulDivisors R P] {x y : P} : spanSingleton S x = spanSingleton S y ↔ ∃ z : Rˣ, z • x = y := by rw [← Submodule.span_singleton_eq_span_singleton, spanSingleton, spanSingleton] exact Subtype.mk_eq_mk theorem eq_spanSingleton_of_principal (I : FractionalIdeal S P) [IsPrincipal (I : Submodule R P)] : I = spanSingleton S (generator (I : Submodule R P)) := by -- Porting note: this used to be `coeToSubmodule_injective (span_singleton_generator ↑I).symm` -- but Lean 4 struggled to unify everything. Turned it into an explicit `rw`. rw [spanSingleton, ← coeToSubmodule_inj, coe_mk, span_singleton_generator] theorem isPrincipal_iff (I : FractionalIdeal S P) : IsPrincipal (I : Submodule R P) ↔ ∃ x, I = spanSingleton S x := ⟨fun _ => ⟨generator (I : Submodule R P), eq_spanSingleton_of_principal I⟩, fun ⟨x, hx⟩ => { principal := ⟨x, Eq.trans (congr_arg _ hx) (coe_spanSingleton _ x)⟩ }⟩ @[simp] theorem spanSingleton_zero : spanSingleton S (0 : P) = 0 := by ext simp [eq_comm] theorem spanSingleton_eq_zero_iff {y : P} : spanSingleton S y = 0 ↔ y = 0 := ⟨fun h => span_eq_bot.mp (by simpa using congr_arg Subtype.val h : span R {y} = ⊥) y (mem_singleton y), fun h => by simp [h]⟩ theorem spanSingleton_ne_zero_iff {y : P} : spanSingleton S y ≠ 0 ↔ y ≠ 0 := not_congr spanSingleton_eq_zero_iff @[simp] theorem spanSingleton_one : spanSingleton S (1 : P) = 1 := by ext refine (mem_spanSingleton S).trans ((exists_congr ?_).trans (mem_one_iff S).symm) intro x' rw [Algebra.smul_def, mul_one] @[simp] theorem spanSingleton_mul_spanSingleton (x y : P) : spanSingleton S x * spanSingleton S y = spanSingleton S (x * y) := by apply coeToSubmodule_injective simp only [coe_mul, coe_spanSingleton, span_mul_span, singleton_mul_singleton] @[simp] theorem spanSingleton_pow (x : P) (n : ℕ) : spanSingleton S x ^ n = spanSingleton S (x ^ n) := by induction' n with n hn · rw [pow_zero, pow_zero, spanSingleton_one] · rw [pow_succ, hn, spanSingleton_mul_spanSingleton, pow_succ] @[simp] theorem coeIdeal_span_singleton (x : R) : (↑(Ideal.span {x} : Ideal R) : FractionalIdeal S P) = spanSingleton S (algebraMap R P x) := by ext y refine (mem_coeIdeal S).trans (Iff.trans ?_ (mem_spanSingleton S).symm) constructor · rintro ⟨y', hy', rfl⟩ obtain ⟨x', rfl⟩ := Submodule.mem_span_singleton.mp hy' use x' rw [smul_eq_mul, RingHom.map_mul, Algebra.smul_def] · rintro ⟨y', rfl⟩ refine ⟨y' * x, Submodule.mem_span_singleton.mpr ⟨y', rfl⟩, ?_⟩ rw [RingHom.map_mul, Algebra.smul_def] @[simp] theorem canonicalEquiv_spanSingleton {P'} [CommRing P'] [Algebra R P'] [IsLocalization S P'] (x : P) : canonicalEquiv S P P' (spanSingleton S x) = spanSingleton S (IsLocalization.map P' (RingHom.id R) (fun y (hy : y ∈ S) => show RingHom.id R y ∈ S from hy) x) := by apply SetLike.ext_iff.mpr intro y constructor <;> intro h · rw [mem_spanSingleton] obtain ⟨x', hx', rfl⟩ := (mem_canonicalEquiv_apply _ _ _).mp h obtain ⟨z, rfl⟩ := (mem_spanSingleton _).mp hx' use z rw [IsLocalization.map_smul, RingHom.id_apply] · rw [mem_canonicalEquiv_apply] obtain ⟨z, rfl⟩ := (mem_spanSingleton _).mp h use z • x use (mem_spanSingleton _).mpr ⟨z, rfl⟩ simp [IsLocalization.map_smul] theorem mem_singleton_mul {x y : P} {I : FractionalIdeal S P} : y ∈ spanSingleton S x * I ↔ ∃ y' ∈ I, y = x * y' := by constructor · intro h refine FractionalIdeal.mul_induction_on h ?_ ?_ · intro x' hx' y' hy' obtain ⟨a, ha⟩ := (mem_spanSingleton S).mp hx' use a • y', Submodule.smul_mem (I : Submodule R P) a hy' rw [← ha, Algebra.mul_smul_comm, Algebra.smul_mul_assoc] · rintro _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩ exact ⟨y + y', Submodule.add_mem (I : Submodule R P) hy hy', (mul_add _ _ _).symm⟩ · rintro ⟨y', hy', rfl⟩ exact mul_mem_mul ((mem_spanSingleton S).mpr ⟨1, one_smul _ _⟩) hy' variable (K) in theorem mk'_mul_coeIdeal_eq_coeIdeal {I J : Ideal R₁} {x y : R₁} (hy : y ∈ R₁⁰) : spanSingleton R₁⁰ (IsLocalization.mk' K x ⟨y, hy⟩) * I = (J : FractionalIdeal R₁⁰ K) ↔ Ideal.span {x} * I = Ideal.span {y} * J := by have : spanSingleton R₁⁰ (IsLocalization.mk' _ (1 : R₁) ⟨y, hy⟩) * spanSingleton R₁⁰ (algebraMap R₁ K y) = 1 := by rw [spanSingleton_mul_spanSingleton, mul_comm, ← IsLocalization.mk'_eq_mul_mk'_one, IsLocalization.mk'_self, spanSingleton_one] let y' : (FractionalIdeal R₁⁰ K)ˣ := Units.mkOfMulEqOne _ _ this have coe_y' : ↑y' = spanSingleton R₁⁰ (IsLocalization.mk' K (1 : R₁) ⟨y, hy⟩) := rfl refine Iff.trans ?_ (y'.mul_right_inj.trans coeIdeal_inj) rw [coe_y', coeIdeal_mul, coeIdeal_span_singleton, coeIdeal_mul, coeIdeal_span_singleton, ← mul_assoc, spanSingleton_mul_spanSingleton, ← mul_assoc, spanSingleton_mul_spanSingleton, mul_comm (mk' _ _ _), ← IsLocalization.mk'_eq_mul_mk'_one, mul_comm (mk' _ _ _), ← IsLocalization.mk'_eq_mul_mk'_one, IsLocalization.mk'_self, spanSingleton_one, one_mul] theorem spanSingleton_mul_coeIdeal_eq_coeIdeal {I J : Ideal R₁} {z : K} : spanSingleton R₁⁰ z * (I : FractionalIdeal R₁⁰ K) = J ↔ Ideal.span {((IsLocalization.sec R₁⁰ z).1 : R₁)} * I = Ideal.span {((IsLocalization.sec R₁⁰ z).2 : R₁)} * J := by rw [← mk'_mul_coeIdeal_eq_coeIdeal K (IsLocalization.sec R₁⁰ z).2.prop, IsLocalization.mk'_sec K z] variable [IsDomain R₁] theorem one_div_spanSingleton (x : K) : 1 / spanSingleton R₁⁰ x = spanSingleton R₁⁰ x⁻¹ := by classical exact if h : x = 0 then by simp [h] else (eq_one_div_of_mul_eq_one_right _ _ (by simp [h])).symm @[simp] theorem div_spanSingleton (J : FractionalIdeal R₁⁰ K) (d : K) : J / spanSingleton R₁⁰ d = spanSingleton R₁⁰ d⁻¹ * J := by rw [← one_div_spanSingleton] by_cases hd : d = 0 · simp only [hd, spanSingleton_zero, div_zero, zero_mul] have h_spand : spanSingleton R₁⁰ d ≠ 0 := mt spanSingleton_eq_zero_iff.mp hd apply le_antisymm · intro x hx dsimp only [val_eq_coe] at hx ⊢ -- Porting note: get rid of the partially applied `coe`s rw [coe_div h_spand, Submodule.mem_div_iff_forall_mul_mem] at hx specialize hx d (mem_spanSingleton_self R₁⁰ d) have h_xd : x = d⁻¹ * (x * d) := by field_simp rw [coe_mul, one_div_spanSingleton, h_xd] exact Submodule.mul_mem_mul (mem_spanSingleton_self R₁⁰ _) hx · rw [le_div_iff_mul_le h_spand, mul_assoc, mul_left_comm, one_div_spanSingleton, spanSingleton_mul_spanSingleton, inv_mul_cancel₀ hd, spanSingleton_one, mul_one] theorem exists_eq_spanSingleton_mul (I : FractionalIdeal R₁⁰ K) : ∃ (a : R₁) (aI : Ideal R₁), a ≠ 0 ∧ I = spanSingleton R₁⁰ (algebraMap R₁ K a)⁻¹ * aI := by obtain ⟨a_inv, nonzero, ha⟩ := I.isFractional have nonzero := mem_nonZeroDivisors_iff_ne_zero.mp nonzero have map_a_nonzero : algebraMap R₁ K a_inv ≠ 0 := mt IsFractionRing.to_map_eq_zero_iff.mp nonzero refine ⟨a_inv, Submodule.comap (Algebra.linearMap R₁ K) ↑(spanSingleton R₁⁰ (algebraMap R₁ K a_inv) * I), nonzero, ext fun x => Iff.trans ⟨?_, ?_⟩ mem_singleton_mul.symm⟩ · intro hx obtain ⟨x', hx'⟩ := ha x hx rw [Algebra.smul_def] at hx' refine ⟨algebraMap R₁ K x', (mem_coeIdeal _).mpr ⟨x', mem_singleton_mul.mpr ?_, rfl⟩, ?_⟩ · exact ⟨x, hx, hx'⟩ · rw [hx', ← mul_assoc, inv_mul_cancel₀ map_a_nonzero, one_mul] · rintro ⟨y, hy, rfl⟩ obtain ⟨x', hx', rfl⟩ := (mem_coeIdeal _).mp hy obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx' rw [Algebra.linearMap_apply] at hx' rwa [hx', ← mul_assoc, inv_mul_cancel₀ map_a_nonzero, one_mul] /-- If `I` is a nonzero fractional ideal, `a ∈ R`, and `J` is an ideal of `R` such that `I = a⁻¹J`, then `J` is nonzero. -/ theorem ideal_factor_ne_zero {R} [CommRing R] {K : Type*} [Field K] [Algebra R K] [IsFractionRing R K] {I : FractionalIdeal R⁰ K} (hI : I ≠ 0) {a : R} {J : Ideal R} (haJ : I = spanSingleton R⁰ ((algebraMap R K) a)⁻¹ * ↑J) : J ≠ 0 := fun h ↦ by rw [h, Ideal.zero_eq_bot, coeIdeal_bot, MulZeroClass.mul_zero] at haJ exact hI haJ /-- If `I` is a nonzero fractional ideal, `a ∈ R`, and `J` is an ideal of `R` such that `I = a⁻¹J`, then `a` is nonzero. -/ theorem constant_factor_ne_zero {R} [CommRing R] {K : Type*} [Field K] [Algebra R K] [IsFractionRing R K] {I : FractionalIdeal R⁰ K} (hI : I ≠ 0) {a : R} {J : Ideal R} (haJ : I = spanSingleton R⁰ ((algebraMap R K) a)⁻¹ * ↑J) : (Ideal.span {a} : Ideal R) ≠ 0 := fun h ↦ by rw [Ideal.zero_eq_bot, Ideal.span_singleton_eq_bot] at h rw [h, RingHom.map_zero, inv_zero, spanSingleton_zero, MulZeroClass.zero_mul] at haJ exact hI haJ instance isPrincipal {R} [CommRing R] [IsDomain R] [IsPrincipalIdealRing R] [Algebra R K] [IsFractionRing R K] (I : FractionalIdeal R⁰ K) : (I : Submodule R K).IsPrincipal := by obtain ⟨a, aI, -, ha⟩ := exists_eq_spanSingleton_mul I use (algebraMap R K a)⁻¹ * algebraMap R K (generator aI) suffices I = spanSingleton R⁰ ((algebraMap R K a)⁻¹ * algebraMap R K (generator aI)) by rw [spanSingleton] at this exact congr_arg Subtype.val this conv_lhs => rw [ha, ← span_singleton_generator aI] rw [Ideal.submodule_span_eq, coeIdeal_span_singleton (generator aI), spanSingleton_mul_spanSingleton] theorem le_spanSingleton_mul_iff {x : P} {I J : FractionalIdeal S P} : I ≤ spanSingleton S x * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI := show (∀ {zI} (_ : zI ∈ I), zI ∈ spanSingleton _ x * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI by simp only [mem_singleton_mul, eq_comm] theorem spanSingleton_mul_le_iff {x : P} {I J : FractionalIdeal S P} : spanSingleton _ x * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J := by simp only [mul_le, mem_spanSingleton] constructor · intro h zI hzI exact h x ⟨1, one_smul _ _⟩ zI hzI · rintro h _ ⟨z, rfl⟩ zI hzI rw [Algebra.smul_mul_assoc] exact Submodule.smul_mem J.1 _ (h zI hzI) theorem eq_spanSingleton_mul {x : P} {I J : FractionalIdeal S P} : I = spanSingleton _ x * J ↔ (∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ ∀ z ∈ J, x * z ∈ I := by simp only [le_antisymm_iff, le_spanSingleton_mul_iff, spanSingleton_mul_le_iff] theorem num_le (I : FractionalIdeal S P) : (I.num : FractionalIdeal S P) ≤ I := by rw [← I.den_mul_self_eq_num', spanSingleton_mul_le_iff] intro _ h rw [← Algebra.smul_def] exact Submodule.smul_mem _ _ h end PrincipalIdeal variable {R₁ : Type*} [CommRing R₁] variable {K : Type*} [Field K] [Algebra R₁ K] theorem isNoetherian_zero : IsNoetherian R₁ (0 : FractionalIdeal R₁⁰ K) := isNoetherian_submodule.mpr fun I (hI : I ≤ (0 : FractionalIdeal R₁⁰ K)) => by rw [coe_zero, le_bot_iff] at hI rw [hI] exact fg_bot theorem isNoetherian_iff {I : FractionalIdeal R₁⁰ K} : IsNoetherian R₁ I ↔ ∀ J ≤ I, (J : Submodule R₁ K).FG := isNoetherian_submodule.trans ⟨fun h _ hJ => h _ hJ, fun h J hJ => h ⟨J, isFractional_of_le hJ⟩ hJ⟩ theorem isNoetherian_coeIdeal [IsNoetherianRing R₁] (I : Ideal R₁) : IsNoetherian R₁ (I : FractionalIdeal R₁⁰ K) := by rw [isNoetherian_iff] intro J hJ obtain ⟨J, rfl⟩ := le_one_iff_exists_coeIdeal.mp (le_trans hJ coeIdeal_le_one) exact (IsNoetherian.noetherian J).map _ variable [IsFractionRing R₁ K] [IsDomain R₁] theorem isNoetherian_spanSingleton_inv_to_map_mul (x : R₁) {I : FractionalIdeal R₁⁰ K} (hI : IsNoetherian R₁ I) : IsNoetherian R₁ (spanSingleton R₁⁰ (algebraMap R₁ K x)⁻¹ * I : FractionalIdeal R₁⁰ K) := by classical by_cases hx : x = 0 · rw [hx, RingHom.map_zero, inv_zero, spanSingleton_zero, zero_mul] exact isNoetherian_zero have h_gx : algebraMap R₁ K x ≠ 0 := mt ((injective_iff_map_eq_zero (algebraMap R₁ K)).mp (IsFractionRing.injective _ _) x) hx have h_spanx : spanSingleton R₁⁰ (algebraMap R₁ K x) ≠ 0 := spanSingleton_ne_zero_iff.mpr h_gx rw [isNoetherian_iff] at hI ⊢ intro J hJ rw [← div_spanSingleton, le_div_iff_mul_le h_spanx] at hJ obtain ⟨s, hs⟩ := hI _ hJ use s * {(algebraMap R₁ K x)⁻¹} rw [Finset.coe_mul, Finset.coe_singleton, ← span_mul_span, hs, ← coe_spanSingleton R₁⁰, ← coe_mul, mul_assoc, spanSingleton_mul_spanSingleton, mul_inv_cancel₀ h_gx, spanSingleton_one, mul_one] /-- Every fractional ideal of a noetherian integral domain is noetherian. -/ theorem isNoetherian [IsNoetherianRing R₁] (I : FractionalIdeal R₁⁰ K) : IsNoetherian R₁ I := by obtain ⟨d, J, _, rfl⟩ := exists_eq_spanSingleton_mul I apply isNoetherian_spanSingleton_inv_to_map_mul apply isNoetherian_coeIdeal section Adjoin variable (S) variable [IsLocalization S P] (x : P) /-- `A[x]` is a fractional ideal for every integral `x`. -/ theorem isFractional_adjoin_integral (hx : IsIntegral R x) : IsFractional S (Subalgebra.toSubmodule (Algebra.adjoin R ({x} : Set P))) := isFractional_of_fg hx.fg_adjoin_singleton /-- `FractionalIdeal.adjoinIntegral (S : Submonoid R) x hx` is `R[x]` as a fractional ideal, where `hx` is a proof that `x : P` is integral over `R`. -/ -- Porting note: `@[simps]` generated a `Subtype.val` coercion instead of a -- `FractionalIdeal.coeToSubmodule` coercion def adjoinIntegral (hx : IsIntegral R x) : FractionalIdeal S P := ⟨_, isFractional_adjoin_integral S x hx⟩ @[simp] theorem adjoinIntegral_coe (hx : IsIntegral R x) : (adjoinIntegral S x hx : Submodule R P) = (Subalgebra.toSubmodule (Algebra.adjoin R ({x} : Set P))) := rfl theorem mem_adjoinIntegral_self (hx : IsIntegral R x) : x ∈ adjoinIntegral S x hx := Algebra.subset_adjoin (Set.mem_singleton x) end Adjoin end FractionalIdeal
Lemmas.lean
/- Copyright (c) 2024 Christian Merten. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christian Merten -/ import Mathlib.RingTheory.Localization.Away.Basic import Mathlib.RingTheory.Localization.Submodule /-! # More lemmas on localization away This file contains lemmas on localization away from an element requiring more imports. -/ variable {R : Type*} [CommRing R] namespace IsLocalization.Away /-- Given a set `s` in a ring `R` and for every `t : s` a set `p t` of fractions in a localization of `R` at `t`, this is the function sending a pair `(t, y)`, with `t : s` and `y : t a`, to `t` multiplied with a numerator of `y`. The range of this function spans the unit ideal, if `s` and every `p t` do. -/ noncomputable def mulNumerator (s : Set R) {Rₜ : s → Type*} [∀ t, CommRing (Rₜ t)] [∀ t, Algebra R (Rₜ t)] [∀ t, IsLocalization.Away t.val (Rₜ t)] (p : (t : s) → Set (Rₜ t)) (x : (t : s) × p t) : R := x.1 * (IsLocalization.Away.sec x.1.1 x.2.1).1 lemma span_range_mulNumerator_eq_top {s : Set R} (hsone : Ideal.span s = ⊤) {Rₜ : s → Type*} [∀ t, CommRing (Rₜ t)] [∀ t, Algebra R (Rₜ t)] [∀ t, IsLocalization.Away t.val (Rₜ t)] {p : (t : s) → Set (Rₜ t)} (htone : ∀ (r : s), Ideal.span (p r) = ⊤) : Ideal.span (Set.range (IsLocalization.Away.mulNumerator s p)) = ⊤ := by rw [← Ideal.radical_eq_top, eq_top_iff, ← hsone, Ideal.span_le] intro a ha haveI : IsLocalization (Submonoid.powers a) (Rₜ ⟨a, ha⟩) := inferInstanceAs <| IsLocalization.Away (⟨a, ha⟩ : s).val (Rₜ ⟨a, ha⟩) have h₁ : Ideal.span (p ⟨a, ha⟩) ≤ Ideal.span (algebraMap R (Rₜ ⟨a, ha⟩) '' Set.range (IsLocalization.Away.mulNumerator s p)) := by rw [Ideal.span_le] intro x hx rw [SetLike.mem_coe, IsLocalization.mem_span_map (Submonoid.powers a)] refine ⟨a * (IsLocalization.Away.sec a x).1, Ideal.subset_span ⟨⟨⟨a, ha⟩, ⟨x, hx⟩⟩, rfl⟩, ?_⟩ use ⟨a ^ ((IsLocalization.Away.sec a x).2 + 1), _, rfl⟩ rw [IsLocalization.eq_mk'_iff_mul_eq, map_pow, map_mul, ← map_pow, pow_add, map_mul, ← mul_assoc, IsLocalization.Away.sec_spec a x, mul_comm, pow_one] have h₂ : IsLocalization.mk' (Rₜ ⟨a, ha⟩) 1 (1 : Submonoid.powers a) ∈ Ideal.span (algebraMap R (Rₜ ⟨a, ha⟩) '' (Set.range <| IsLocalization.Away.mulNumerator s p)) := by rw [IsLocalization.mk'_one] apply h₁ simp [htone] rw [IsLocalization.mem_span_map (Submonoid.powers a)] at h₂ obtain ⟨y, hy, ⟨-, m, rfl⟩, hyz⟩ := h₂ rw [IsLocalization.eq] at hyz obtain ⟨⟨-, n, rfl⟩, hc⟩ := hyz simp only [OneMemClass.coe_one, one_mul, mul_one] at hc use n + m simpa [pow_add, hc] using Ideal.mul_mem_left _ _ hy lemma quotient_of_isIdempotentElem {e : R} (he : IsIdempotentElem e) : IsLocalization.Away e (R ⧸ Ideal.span {1 - e}) := away_of_isIdempotentElem he Ideal.mk_ker Quotient.mk_surjective end IsLocalization.Away
Basic.lean
/- Copyright (c) 2025 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.CategoryTheory.Category.Basic import Mathlib.CategoryTheory.Functor.Basic import Mathlib.CategoryTheory.Iso import Mathlib.Order.Basic /-! # Properties of objects in a category Given a category `C`, we introduce an abbreviation `ObjectProperty C` for predicates `C → Prop`. ## TODO * refactor the file `Limits.FullSubcategory` in order to rename `ClosedUnderLimitsOfShape` as `ObjectProperty.IsClosedUnderLimitsOfShape` (and make it a type class) * refactor the file `Triangulated.Subcategory` in order to make it a type class regarding terms in `ObjectProperty C` when `C` is pretriangulated -/ universe v v' u u' namespace CategoryTheory /-- A property of objects in a category `C` is a predicate `C → Prop`. -/ @[nolint unusedArguments] abbrev ObjectProperty (C : Type u) [Category.{v} C] : Type u := C → Prop namespace ObjectProperty variable {C : Type u} {D : Type u'} [Category.{v} C] [Category.{v'} D] lemma le_def {P Q : ObjectProperty C} : P ≤ Q ↔ ∀ (X : C), P X → Q X := Iff.rfl /-- The inverse image of a property of objects by a functor. -/ def inverseImage (P : ObjectProperty D) (F : C ⥤ D) : ObjectProperty C := fun X ↦ P (F.obj X) @[simp] lemma prop_inverseImage_iff (P : ObjectProperty D) (F : C ⥤ D) (X : C) : P.inverseImage F X ↔ P (F.obj X) := Iff.rfl /-- The essential image of a property of objects by a functor. -/ def map (P : ObjectProperty C) (F : C ⥤ D) : ObjectProperty D := fun Y ↦ ∃ (X : C), P X ∧ Nonempty (F.obj X ≅ Y) lemma prop_map_iff (P : ObjectProperty C) (F : C ⥤ D) (Y : D) : P.map F Y ↔ ∃ (X : C), P X ∧ Nonempty (F.obj X ≅ Y) := Iff.rfl lemma prop_map_obj (P : ObjectProperty C) (F : C ⥤ D) {X : C} (hX : P X) : P.map F (F.obj X) := ⟨X, hX, ⟨Iso.refl _⟩⟩ /-- The typeclass associated to `P : ObjectProperty C`. -/ @[mk_iff] class Is (P : ObjectProperty C) (X : C) : Prop where prop : P X lemma prop_of_is (P : ObjectProperty C) (X : C) [P.Is X] : P X := by rwa [← P.is_iff] lemma is_of_prop (P : ObjectProperty C) {X : C} (hX : P X) : P.Is X := by rwa [P.is_iff] end ObjectProperty end CategoryTheory
IsoIoo.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Order.Monotone.Odd import Mathlib.Algebra.Order.Field.Basic import Mathlib.Tactic.FieldSimp /-! # Order isomorphism between a linear ordered field and `(-1, 1)` In this file we provide an order isomorphism `orderIsoIooNegOneOne` between the open interval `(-1, 1)` in a linear ordered field and the whole field. -/ open Set /-- In a linear ordered field, the whole field is order isomorphic to the open interval `(-1, 1)`. We consider the actual implementation to be a "black box", so it is irreducible. -/ @[irreducible] def orderIsoIooNegOneOne (k : Type*) [Field k] [LinearOrder k] [IsStrictOrderedRing k] : k ≃o Ioo (-1 : k) 1 := by refine StrictMono.orderIsoOfRightInverse ?_ ?_ (fun x ↦ x / (1 - |↑x|)) ?_ · refine codRestrict (fun x ↦ x / (1 + |x|)) _ fun x ↦ abs_lt.1 ?_ have H : 0 < 1 + |x| := (abs_nonneg x).trans_lt (lt_one_add _) calc |x / (1 + |x|)| = |x| / (1 + |x|) := by rw [abs_div, abs_of_pos H] _ < 1 := (div_lt_one H).2 (lt_one_add _) · refine (strictMono_of_odd_strictMonoOn_nonneg ?_ ?_).codRestrict _ · intro x simp only [abs_neg, neg_div] · rintro x (hx : 0 ≤ x) y (hy : 0 ≤ y) hxy simp [abs_of_nonneg, mul_add, mul_comm x y, div_lt_div_iff₀, hx.trans_lt (lt_one_add _), hy.trans_lt (lt_one_add _), *] · refine fun x ↦ Subtype.ext ?_ have : 0 < 1 - |(x : k)| := sub_pos.2 (abs_lt.2 x.2) field_simp [abs_div, this.ne', abs_of_pos this]
Balanced.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.EpiMono /-! # Balanced categories A category is called balanced if any morphism that is both monic and epic is an isomorphism. Balanced categories arise frequently. For example, categories in which every monomorphism (or epimorphism) is strong are balanced. Examples of this are abelian categories and toposes, such as the category of types. -/ universe v u namespace CategoryTheory variable {C : Type u} [Category.{v} C] section variable (C) /-- A category is called balanced if any morphism that is both monic and epic is an isomorphism. -/ class Balanced : Prop where isIso_of_mono_of_epi : ∀ {X Y : C} (f : X ⟶ Y) [Mono f] [Epi f], IsIso f end theorem isIso_of_mono_of_epi [Balanced C] {X Y : C} (f : X ⟶ Y) [Mono f] [Epi f] : IsIso f := Balanced.isIso_of_mono_of_epi _ theorem isIso_iff_mono_and_epi [Balanced C] {X Y : C} (f : X ⟶ Y) : IsIso f ↔ Mono f ∧ Epi f := ⟨fun _ => ⟨inferInstance, inferInstance⟩, fun ⟨_, _⟩ => isIso_of_mono_of_epi _⟩ section attribute [local instance] isIso_of_mono_of_epi instance balanced_opposite [Balanced C] : Balanced Cᵒᵖ := { isIso_of_mono_of_epi := fun f fmono fepi => by rw [← Quiver.Hom.op_unop f] exact isIso_of_op _ } end end CategoryTheory
fraction.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq. From mathcomp Require Import ssrAC choice tuple bigop ssralg poly polydiv. From mathcomp Require Import generic_quotient. (******************************************************************************) (* Field of fraction of an integral domain *) (* *) (* This file builds the field of fraction of any integral domain. The main *) (* result of this file is the existence of the field and of the tofrac *) (* function which is a injective ring morphism from R to its fraction field *) (* {fraction R}. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory. Local Open Scope ring_scope. Local Open Scope quotient_scope. Reserved Notation "{ 'ratio' T }" (format "{ 'ratio' T }"). Reserved Notation "{ 'fraction' T }" (format "{ 'fraction' T }"). Reserved Notation "x %:F" (format "x %:F"). Section FracDomain. Variable R : nzRingType. (* ratios are pairs of R, such that the second member is nonzero *) Inductive ratio := mkRatio { frac :> R * R; _ : frac.2 != 0 }. HB.instance Definition _ := [isSub for frac]. HB.instance Definition _ := [Choice of ratio by <:]. Lemma denom_ratioP : forall f : ratio, f.2 != 0. Proof. by case. Qed. Definition ratio0 := (@mkRatio (0, 1) (oner_neq0 _)). Definition Ratio x y : ratio := insubd ratio0 (x, y). Lemma numer_Ratio x y : y != 0 -> (Ratio x y).1 = x. Proof. by move=> ny0; rewrite /Ratio /insubd insubT. Qed. Lemma denom_Ratio x y : y != 0 -> (Ratio x y).2 = y. Proof. by move=> ny0; rewrite /Ratio /insubd insubT. Qed. Definition numden_Ratio := (numer_Ratio, denom_Ratio). Variant Ratio_spec (n d : R) : ratio -> R -> R -> Type := | RatioNull of d = 0 : Ratio_spec n d ratio0 n 0 | RatioNonNull (d_neq0 : d != 0) : Ratio_spec n d (@mkRatio (n, d) d_neq0) n d. Lemma RatioP n d : Ratio_spec n d (Ratio n d) n d. Proof. rewrite /Ratio /insubd; case: insubP=> /= [x /= d_neq0 hx|]. have ->: x = @mkRatio (n, d) d_neq0 by apply: val_inj. by constructor. by rewrite negbK=> /eqP hx; rewrite {2}hx; constructor. Qed. Lemma Ratio0 x : Ratio x 0 = ratio0. Proof. by rewrite /Ratio /insubd; case: insubP; rewrite //= eqxx. Qed. End FracDomain. Arguments ratio R%_type. Notation "{ 'ratio' T }" := (ratio T) : type_scope. Notation "'\n_' x" := (frac x).1 (at level 8, x at level 2, format "'\n_' x"). Notation "'\d_' x" := (frac x).2 (at level 8, x at level 2, format "'\d_' x"). Module FracField. Section FracField. Variable R : idomainType. Local Notation frac := (R * R). Local Notation dom := (ratio R). Local Notation domP := denom_ratioP. Implicit Types x y z : dom. (* We define a relation in ratios *) Local Notation equivf_notation x y := (\n_x * \d_y == \d_x * \n_y). Definition equivf x y := equivf_notation x y. Lemma equivfE x y : equivf x y = equivf_notation x y. Proof. by []. Qed. Lemma equivf_refl : reflexive equivf. Proof. by move=> x; rewrite /equivf mulrC. Qed. Lemma equivf_sym : symmetric equivf. Proof. by move=> x y; rewrite /equivf eq_sym; congr (_==_); rewrite mulrC. Qed. Lemma equivf_trans : transitive equivf. Proof. move=> [x Px] [y Py] [z Pz]; rewrite /equivf /= mulrC => /eqP xy /eqP yz. by rewrite -(inj_eq (mulfI Px)) mulrA xy -mulrA yz mulrCA. Qed. (* we show that equivf is an equivalence *) Canonical equivf_equiv := EquivRel equivf equivf_refl equivf_sym equivf_trans. Definition type := {eq_quot equivf}. (* we recover some structure for the quotient *) HB.instance Definition _ : EqQuotient _ equivf type := EqQuotient.on type. HB.instance Definition _ := Choice.on type. (* we explain what was the equivalence on the quotient *) Lemma equivf_def (x y : ratio R) : x == y %[mod type] = (\n_x * \d_y == \d_x * \n_y). Proof. by rewrite eqmodE. Qed. Lemma equivf_r x : \n_x * \d_(repr (\pi_type x)) = \d_x * \n_(repr (\pi_type x)). Proof. by apply/eqP; rewrite -equivf_def reprK. Qed. Lemma equivf_l x : \n_(repr (\pi_type x)) * \d_x = \d_(repr (\pi_type x)) * \n_x. Proof. by apply/eqP; rewrite -equivf_def reprK. Qed. Lemma numer0 x : (\n_x == 0) = (x == (ratio0 R) %[mod_eq equivf]). Proof. by rewrite eqmodE /= !equivfE // mulr1 mulr0. Qed. Lemma Ratio_numden : forall x, Ratio \n_x \d_x = x. Proof. case=> [[n d] /= nd]; rewrite /Ratio /insubd; apply: val_inj=> /=. by case: insubP=> //=; rewrite nd. Qed. Definition tofrac := lift_embed type (fun x : R => Ratio x 1). Canonical tofrac_pi_morph := PiEmbed tofrac. Notation "x %:F" := (@tofrac x). Implicit Types a b c : type. Definition addf x y : dom := Ratio (\n_x * \d_y + \n_y * \d_x) (\d_x * \d_y). Definition add := lift_op2 type addf. Lemma pi_add : {morph \pi : x y / addf x y >-> add x y}. Proof. move=> x y; unlock add; apply/eqmodP; rewrite /= equivfE /addf /=. rewrite !numden_Ratio ?mulf_neq0 ?domP // mulrDr mulrDl; apply/eqP. symmetry; rewrite (AC (2*2) (3*1*2*4)) (AC (2*2) (3*2*1*4))/=. by rewrite !equivf_l (ACl ((2*3)*(1*4))) (ACl ((2*3)*(4*1)))/=. Qed. Canonical pi_add_morph := PiMorph2 pi_add. Definition oppf x : dom := Ratio (- \n_x) \d_x. Definition opp := lift_op1 type oppf. Lemma pi_opp : {morph \pi : x / oppf x >-> opp x}. Proof. move=> x; unlock opp; apply/eqmodP; rewrite /= /equivf /oppf /=. by rewrite !numden_Ratio ?(domP,mulf_neq0) // mulNr mulrN -equivf_r. Qed. Canonical pi_opp_morph := PiMorph1 pi_opp. Definition mulf x y : dom := Ratio (\n_x * \n_y) (\d_x * \d_y). Definition mul := lift_op2 type mulf. Lemma pi_mul : {morph \pi : x y / mulf x y >-> mul x y}. Proof. move=> x y; unlock mul; apply/eqmodP=> /=. rewrite equivfE /= /addf /= !numden_Ratio ?mulf_neq0 ?domP //. by rewrite mulrACA !equivf_r mulrACA. Qed. Canonical pi_mul_morph := PiMorph2 pi_mul. Definition invf x : dom := Ratio \d_x \n_x. Definition inv := lift_op1 type invf. Lemma pi_inv : {morph \pi : x / invf x >-> inv x}. Proof. move=> x; unlock inv; apply/eqmodP=> /=; rewrite equivfE /invf eq_sym. do 2?case: RatioP=> /= [/eqP|]; rewrite ?mul0r ?mul1r -?equivf_def ?numer0 ?reprK //. by move=> hx /eqP hx'; rewrite hx' eqxx in hx. by move=> /eqP ->; rewrite eqxx. Qed. Canonical pi_inv_morph := PiMorph1 pi_inv. Lemma addA : associative add. Proof. elim/quotW=> x; elim/quotW=> y; elim/quotW=> z; rewrite !piE. rewrite /addf /= !numden_Ratio ?mulf_neq0 ?domP // !mulrDl. by rewrite !mulrA !addrA ![_ * _ * \d_x]mulrAC. Qed. Lemma addC : commutative add. Proof. by elim/quotW=> x; elim/quotW=> y; rewrite !piE /addf addrC [\d__ * _]mulrC. Qed. Lemma add0_l : left_id 0%:F add. Proof. elim/quotW=> x; rewrite !piE /addf !numden_Ratio ?oner_eq0 //. by rewrite mul0r mul1r mulr1 add0r Ratio_numden. Qed. Lemma addN_l : left_inverse 0%:F opp add. Proof. elim/quotW=> x; apply/eqP; rewrite piE /equivf. rewrite /addf /oppf !numden_Ratio ?(oner_eq0, mulf_neq0, domP) //. by rewrite mulr1 mulr0 mulNr addNr. Qed. (* fracions form an abelian group *) HB.instance Definition _ := GRing.isZmodule.Build type addA addC add0_l addN_l. Lemma mulA : associative mul. Proof. elim/quotW=> x; elim/quotW=> y; elim/quotW=> z; rewrite !piE. by rewrite /mulf !numden_Ratio ?mulf_neq0 ?domP // !mulrA. Qed. Lemma mulC : commutative mul. Proof. elim/quotW=> x; elim/quotW=> y; rewrite !piE /mulf. by rewrite [_ * (\d_x)]mulrC [_ * (\n_x)]mulrC. Qed. Lemma mul1_l : left_id 1%:F mul. Proof. elim/quotW=> x; rewrite !piE /mulf. by rewrite !numden_Ratio ?oner_eq0 // !mul1r Ratio_numden. Qed. Lemma mul_addl : left_distributive mul add. Proof. elim/quotW=> x; elim/quotW=> y; elim/quotW=> z; apply/eqP. rewrite !piE /equivf /mulf /addf !numden_Ratio ?mulf_neq0 ?domP //; apply/eqP. rewrite !(mulrDr, mulrDl) (AC (3*(2*2)) (4*2*7*((1*3)*(6*5))))/=. by rewrite [X in _ + X](AC (3*(2*2)) (4*6*7*((1*3)*(2*5))))/=. Qed. Lemma nonzero1 : 1%:F != 0%:F :> type. Proof. by rewrite piE equivfE !numden_Ratio ?mul1r ?oner_eq0. Qed. (* fractions form a commutative ring *) HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build type mulA mulC mul1_l mul_addl nonzero1. Lemma mulV_l : forall a, a != 0%:F -> mul (inv a) a = 1%:F. Proof. elim/quotW=> x /=; rewrite !piE. rewrite /equivf !numden_Ratio ?oner_eq0 // mulr1 mulr0=> nx0. apply/eqmodP; rewrite /= equivfE. by rewrite !numden_Ratio ?(oner_eq0, mulf_neq0, domP) // !mulr1 mulrC. Qed. Lemma inv0 : inv 0%:F = 0%:F. Proof. rewrite !piE /invf !numden_Ratio ?oner_eq0 // /Ratio /insubd. do 2?case: insubP; rewrite //= ?eqxx ?oner_eq0 // => u _ hu _. by congr \pi; apply: val_inj; rewrite /= hu. Qed. (* fractions form a ring with explicit unit *) (* fractions form a field *) HB.instance Definition _ := GRing.ComNzRing_isField.Build type mulV_l inv0. End FracField. End FracField. HB.export FracField. Arguments FracField.type R%_type. Notation "{ 'fraction' T }" := (FracField.type T). Notation equivf := (@FracField.equivf _). #[global] Hint Resolve denom_ratioP : core. Section FracFieldTheory. Import FracField. Variable R : idomainType. Lemma Ratio_numden (x : {ratio R}) : Ratio \n_x \d_x = x. Proof. exact: FracField.Ratio_numden. Qed. (* exporting the embedding from R to {fraction R} *) Local Notation tofrac := (@FracField.tofrac R). Local Notation "x %:F" := (tofrac x). Lemma tofrac_is_zmod_morphism: zmod_morphism tofrac. Proof. move=> p q /=; unlock tofrac. rewrite -[X in _ = _ + X]pi_opp -[RHS]pi_add. by rewrite /addf /oppf /= !numden_Ratio ?(oner_neq0, mul1r, mulr1). Qed. #[deprecated(since="mathcomp 2.5.0", note="use `tofrac_is_zmod_morphism` instead")] Definition tofrac_is_additive := tofrac_is_zmod_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build R {fraction R} tofrac tofrac_is_zmod_morphism. Lemma tofrac_is_monoid_morphism: monoid_morphism tofrac. Proof. split=> [//|p q]; unlock tofrac; rewrite -[RHS]pi_mul. by rewrite /mulf /= !numden_Ratio ?(oner_neq0, mul1r, mulr1). Qed. #[deprecated(since="mathcomp 2.5.0", note="use `tofrac_is_monoid_morphism` instead")] Definition tofrac_is_multiplicative := tofrac_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build R {fraction R} tofrac tofrac_is_monoid_morphism. (* tests *) Lemma tofrac0 : 0%:F = 0. Proof. exact: rmorph0. Qed. Lemma tofracN : {morph tofrac: x / - x}. Proof. exact: rmorphN. Qed. Lemma tofracD : {morph tofrac: x y / x + y}. Proof. exact: rmorphD. Qed. Lemma tofracB : {morph tofrac: x y / x - y}. Proof. exact: rmorphB. Qed. Lemma tofracMn n : {morph tofrac: x / x *+ n}. Proof. exact: rmorphMn. Qed. Lemma tofracMNn n : {morph tofrac: x / x *- n}. Proof. exact: rmorphMNn. Qed. Lemma tofrac1 : 1%:F = 1. Proof. exact: rmorph1. Qed. Lemma tofracM : {morph tofrac: x y / x * y}. Proof. exact: rmorphM. Qed. Lemma tofracXn n : {morph tofrac: x / x ^+ n}. Proof. exact: rmorphXn. Qed. Lemma tofrac_eq (p q : R): (p%:F == q%:F) = (p == q). Proof. apply/eqP/eqP=> [|->//]; unlock tofrac=> /eqmodP /eqP /=. by rewrite !numden_Ratio ?(oner_eq0, mul1r, mulr1). Qed. Lemma tofrac_eq0 (p : R): (p%:F == 0) = (p == 0). Proof. by rewrite tofrac_eq. Qed. End FracFieldTheory.
Basic.lean
/- Copyright (c) 2025 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Lorenzo Luccioli -/ import Mathlib.InformationTheory.KullbackLeibler.KLFun import Mathlib.MeasureTheory.Measure.Decomposition.IntegralRNDeriv /-! # Kullback-Leibler divergence The Kullback-Leibler divergence is a measure of the difference between two measures. ## Main definitions * `klDiv μ ν`: Kullback-Leibler divergence between two measures, with value in `ℝ≥0∞`, defined as `∞` if `μ` is not absolutely continuous with respect to `ν` or if the log-likelihood ratio `llr μ ν` is not integrable with respect to `μ`, and by `ENNReal.ofReal (∫ x, llr μ ν x ∂μ + ν.real - μ.real univ)` otherwise. Note that our Kullback-Leibler divergence is nonnegative by definition (it takes value in `ℝ≥0∞`). However `∫ x, llr μ ν x ∂μ + ν.real univ - μ.real univ` is nonnegative for all finite measures `μ ≪ ν`, as proved in the lemma `integral_llr_add_sub_measure_univ_nonneg`. That lemma is our version of Gibbs' inequality ("the Kullback-Leibler divergence is nonnegative"). ## Main statements * `klDiv_eq_zero_iff` : the Kullback-Leibler divergence between two finite measures is zero if and only if the two measures are equal. ## Implementation details The Kullback-Leibler divergence on probability measures is `∫ x, llr μ ν x ∂μ` if `μ ≪ ν` (and the log-likelihood ratio is integrable) and `∞` otherwise. The definition we use extends this to finite measures by introducing a correction term `ν.real univ - μ.real univ`. The definition of the divergence thus uses the formula `∫ x, llr μ ν x ∂μ + ν.real univ - μ.real univ`, which is nonnegative for all finite measures `μ ≪ ν`. This also makes `klDiv μ ν` equal to an f-divergence: it equals the integral `∫ x, klFun (μ.rnDeriv ν x).toReal ∂ν`, in which `klFun x = x * log x + 1 - x`. -/ open Real MeasureTheory Set open scoped ENNReal namespace InformationTheory variable {α : Type*} {mα : MeasurableSpace α} {μ ν : Measure α} open Classical in /-- Kullback-Leibler divergence between two measures. -/ noncomputable irreducible_def klDiv (μ ν : Measure α) : ℝ≥0∞ := if μ ≪ ν ∧ Integrable (llr μ ν) μ then ENNReal.ofReal (∫ x, llr μ ν x ∂μ + ν.real univ - μ.real univ) else ∞ lemma klDiv_of_ac_of_integrable (h1 : μ ≪ ν) (h2 : Integrable (llr μ ν) μ) : klDiv μ ν = ENNReal.ofReal (∫ x, llr μ ν x ∂μ + ν.real univ - μ.real univ) := by rw [klDiv_def] exact if_pos ⟨h1, h2⟩ @[simp] lemma klDiv_of_not_ac (h : ¬ μ ≪ ν) : klDiv μ ν = ∞ := by rw [klDiv_def] exact if_neg (not_and_of_not_left _ h) @[simp] lemma klDiv_of_not_integrable (h : ¬ Integrable (llr μ ν) μ) : klDiv μ ν = ∞ := by rw [klDiv_def] exact if_neg (not_and_of_not_right _ h) @[simp] lemma klDiv_self (μ : Measure α) [SigmaFinite μ] : klDiv μ μ = 0 := by have h := llr_self μ rw [klDiv_def, if_pos] · simp [integral_congr_ae h] · rw [integrable_congr h] exact ⟨Measure.AbsolutelyContinuous.rfl, integrable_zero _ _ μ⟩ @[simp] lemma klDiv_zero_left [IsFiniteMeasure ν] : klDiv 0 ν = ν univ := by convert klDiv_of_ac_of_integrable (Measure.AbsolutelyContinuous.zero _) integrable_zero_measure simp @[simp] lemma klDiv_zero_right [NeZero μ] : klDiv μ 0 = ∞ := klDiv_of_not_ac (Measure.absolutelyContinuous_zero_iff.mp.mt (NeZero.ne _)) lemma klDiv_eq_top_iff : klDiv μ ν = ∞ ↔ μ ≪ ν → ¬ Integrable (llr μ ν) μ := by constructor <;> intro h · contrapose! h simp [klDiv_of_ac_of_integrable h.1 h.2] · rcases or_not_of_imp h with (h | h) <;> simp [h] lemma klDiv_ne_top_iff : klDiv μ ν ≠ ∞ ↔ μ ≪ ν ∧ Integrable (llr μ ν) μ := by simp [ne_eq, klDiv_eq_top_iff] section AlternativeFormulas variable [IsFiniteMeasure μ] [IsFiniteMeasure ν] open Classical in lemma klDiv_eq_integral_klFun : klDiv μ ν = if μ ≪ ν ∧ Integrable (llr μ ν) μ then ENNReal.ofReal (∫ x, klFun (μ.rnDeriv ν x).toReal ∂ν) else ∞ := by rw [klDiv_def] exact if_ctx_congr Iff.rfl (fun h ↦ by rw [integral_klFun_rnDeriv h.1 h.2]) fun _ ↦ rfl open Classical in lemma klDiv_eq_lintegral_klFun : klDiv μ ν = if μ ≪ ν then ∫⁻ x, ENNReal.ofReal (klFun (μ.rnDeriv ν x).toReal) ∂ν else ∞ := by rw [klDiv_eq_integral_klFun] by_cases hμν : μ ≪ ν swap; · simp [hμν] have h_int_iff := lintegral_ofReal_ne_top_iff_integrable (f := fun x ↦ klFun (μ.rnDeriv ν x).toReal) (μ := ν) ?_ ?_ rotate_left · exact Measurable.aestronglyMeasurable (by fun_prop) · exact ae_of_all _ fun _ ↦ klFun_nonneg ENNReal.toReal_nonneg by_cases h_int : Integrable (llr μ ν) μ · simp only [hμν, h_int, and_self, ↓reduceIte] rw [ofReal_integral_eq_lintegral_ofReal] · rwa [integrable_klFun_rnDeriv_iff hμν] · exact ae_of_all _ fun _ ↦ klFun_nonneg ENNReal.toReal_nonneg · rw [← not_iff_not, ne_eq, Decidable.not_not] at h_int_iff symm simp [hμν, h_int, h_int_iff, integrable_klFun_rnDeriv_iff hμν] end AlternativeFormulas section Real variable [IsFiniteMeasure μ] [IsFiniteMeasure ν] /-- **Gibbs' inequality**: the Kullback-Leibler divergence is nonnegative. Note that since `klDiv` takes value in `ℝ≥0∞` (defined when it is finite as `ENNReal.ofReal (...)`), it is nonnegative by definition. This lemma proves that the argument of `ENNReal.ofReal` is also nonnegative. -/ lemma integral_llr_add_sub_measure_univ_nonneg (hμν : μ ≪ ν) (h_int : Integrable (llr μ ν) μ) : 0 ≤ ∫ x, llr μ ν x ∂μ + ν.real univ - μ.real univ := by rw [← integral_klFun_rnDeriv hμν h_int] exact integral_nonneg fun x ↦ klFun_nonneg ENNReal.toReal_nonneg lemma toReal_klDiv (h : μ ≪ ν) (h_int : Integrable (llr μ ν) μ) : (klDiv μ ν).toReal = ∫ a, llr μ ν a ∂μ + ν.real univ - μ.real univ := by rw [klDiv_of_ac_of_integrable h h_int, ENNReal.toReal_ofReal] exact integral_llr_add_sub_measure_univ_nonneg h h_int /-- If `μ ≪ ν` and `μ univ = ν univ`, then `toReal` of the Kullback-Leibler divergence is equal to an integral, without any integrability condition. -/ lemma toReal_klDiv_of_measure_eq (h : μ ≪ ν) (h_eq : μ univ = ν univ) : (klDiv μ ν).toReal = ∫ a, llr μ ν a ∂μ := by by_cases h_int : Integrable (llr μ ν) μ · simp [toReal_klDiv h h_int, h_eq, measureReal_def] · rw [klDiv_of_not_integrable h_int, integral_undef h_int, ENNReal.toReal_top] lemma toReal_klDiv_eq_integral_klFun (h : μ ≪ ν) : (klDiv μ ν).toReal = ∫ x, klFun (μ.rnDeriv ν x).toReal ∂ν := by by_cases h_int : Integrable (llr μ ν) μ · rw [klDiv_eq_integral_klFun, if_pos ⟨h, h_int⟩, ENNReal.toReal_ofReal] exact integral_nonneg fun _ ↦ klFun_nonneg ENNReal.toReal_nonneg · rw [integral_undef] · rw [klDiv_of_not_integrable h_int, ENNReal.toReal_top] · rwa [integrable_klFun_rnDeriv_iff h] end Real section Inequalities variable [IsFiniteMeasure μ] [IsFiniteMeasure ν] lemma integral_llr_add_mul_log_nonneg (hμν : μ ≪ ν) (h_int : Integrable (llr μ ν) μ) : 0 ≤ ∫ x, llr μ ν x ∂μ + μ.real univ * log (ν.real univ) + 1 - μ.real univ := by by_cases hμ : μ = 0 · simp [hμ] by_cases hν : ν = 0 · refine absurd ?_ hμ rw [hν] at hμν exact Measure.absolutelyContinuous_zero_iff.mp hμν have : NeZero ν := ⟨hν⟩ let ν' := (ν univ)⁻¹ • ν have hμν' : μ ≪ ν' := hμν.trans (Measure.absolutelyContinuous_smul (by simp)) have h := integral_llr_add_sub_measure_univ_nonneg hμν' ?_ swap · rw [integrable_congr (llr_smul_right hμν (ν univ)⁻¹ (by simp) (by simp [hν]))] exact h_int.sub (integrable_const _) rw [integral_congr_ae (llr_smul_right hμν (ν univ)⁻¹ (by simp) (by simp [hν])), integral_sub h_int (integrable_const _), integral_const, smul_eq_mul] at h simpa using h lemma mul_klFun_le_toReal_klDiv (hμν : μ ≪ ν) (h_int : Integrable (llr μ ν) μ) : ν.real univ * klFun (μ.real univ / ν.real univ) ≤ (klDiv μ ν).toReal := by calc ν.real univ * klFun (μ.real univ / ν.real univ) _ ≤ ∫ x, klFun (μ.rnDeriv ν x).toReal ∂ν := by refine mul_le_integral_rnDeriv_of_ac convexOn_klFun continuous_klFun.continuousWithinAt ?_ hμν rwa [integrable_klFun_rnDeriv_iff hμν] _ = (klDiv μ ν).toReal := by rw [toReal_klDiv_eq_integral_klFun hμν] lemma mul_log_le_toReal_klDiv (hμν : μ ≪ ν) (h_int : Integrable (llr μ ν) μ) : μ.real univ * log (μ.real univ / ν.real univ) + ν.real univ - μ.real univ ≤ (klDiv μ ν).toReal := by by_cases hμ : μ = 0 · simp [hμ, measureReal_def] by_cases hν : ν = 0 · refine absurd ?_ hμ rw [hν] at hμν exact Measure.absolutelyContinuous_zero_iff.mp hμν refine (le_of_eq ?_).trans (mul_klFun_le_toReal_klDiv hμν h_int) have : ν.real univ * (μ.real univ / ν.real univ) = μ.real univ := by rw [mul_div_cancel₀]; simp [ENNReal.toReal_eq_zero_iff, hν, measureReal_def] rw [klFun, mul_sub, mul_add, mul_one, ← mul_assoc, this] lemma mul_log_le_klDiv (μ ν : Measure α) [IsFiniteMeasure μ] [IsFiniteMeasure ν] : ENNReal.ofReal (μ.real univ * log (μ.real univ / ν.real univ) + ν.real univ - μ.real univ) ≤ klDiv μ ν := by by_cases hμν : μ ≪ ν swap; · simp [hμν] by_cases h_int : Integrable (llr μ ν) μ swap; · simp [h_int] rw [← ENNReal.ofReal_toReal (a := klDiv μ ν)] · exact ENNReal.ofReal_le_ofReal (mul_log_le_toReal_klDiv hμν h_int) · rw [klDiv_ne_top_iff] exact ⟨hμν, h_int⟩ end Inequalities /-- **Converse Gibbs' inequality**: the Kullback-Leibler divergence between two finite measures is zero if and only if the two measures are equal. -/ lemma klDiv_eq_zero_iff [IsFiniteMeasure μ] [IsFiniteMeasure ν] : klDiv μ ν = 0 ↔ μ = ν := by refine ⟨fun h ↦ ?_, fun h ↦ h ▸ klDiv_self _⟩ have h_ne : klDiv μ ν ≠ ⊤ := by simp [h] rw [klDiv_ne_top_iff] at h_ne rw [klDiv_eq_lintegral_klFun, if_pos h_ne.1, lintegral_eq_zero_iff (by fun_prop)] at h refine (Measure.rnDeriv_eq_one_iff_eq h_ne.1).mp ?_ filter_upwards [h] with x hx simp only [Pi.zero_apply, ENNReal.ofReal_eq_zero] at hx have hx' : klFun (μ.rnDeriv ν x).toReal = 0 := le_antisymm hx (klFun_nonneg ENNReal.toReal_nonneg) rwa [klFun_eq_zero_iff ENNReal.toReal_nonneg, ENNReal.toReal_eq_one_iff] at hx' end InformationTheory
Sigma.lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau -/ import Mathlib.Data.DFinsupp.Module import Mathlib.Data.Fintype.Quotient /-! # `DFinsupp` on `Sigma` types ## Main definitions * `DFinsupp.sigmaCurry`: turn a `DFinsupp` indexed by a `Sigma` type into a `DFinsupp` with two parameters. * `DFinsupp.sigmaUncurry`: turn a `DFinsupp` with two parameters into a `DFinsupp` indexed by a `Sigma` type. Inverse of `DFinsupp.sigmaCurry`. * `DFinsupp.sigmaCurryEquiv`: `DFinsupp.sigmaCurry` and `DFinsupp.sigmaUncurry` bundled into a bijection. -/ universe u u₁ u₂ v v₁ v₂ v₃ w x y l variable {ι : Type u} {γ : Type w} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} namespace DFinsupp section Equiv open Finset variable {κ : Type*} section SigmaCurry variable {α : ι → Type*} {δ : ∀ i, α i → Type v} variable [DecidableEq ι] /-- The natural map between `Π₀ (i : Σ i, α i), δ i.1 i.2` and `Π₀ i (j : α i), δ i j`. -/ def sigmaCurry [∀ i j, Zero (δ i j)] (f : Π₀ (i : Σ _, _), δ i.1 i.2) : Π₀ (i) (j), δ i j where toFun := fun i ↦ { toFun := fun j ↦ f ⟨i, j⟩, support' := f.support'.map (fun ⟨m, hm⟩ ↦ ⟨m.filterMap (fun ⟨i', j'⟩ ↦ if h : i' = i then some <| h.rec j' else none), fun j ↦ (hm ⟨i, j⟩).imp_left (fun h ↦ (m.mem_filterMap _).mpr ⟨⟨i, j⟩, h, dif_pos rfl⟩)⟩) } support' := f.support'.map (fun ⟨m, hm⟩ ↦ ⟨m.map Sigma.fst, fun i ↦ Decidable.or_iff_not_imp_left.mpr (fun h ↦ DFinsupp.ext (fun j ↦ (hm ⟨i, j⟩).resolve_left (fun H ↦ (Multiset.mem_map.not.mp h) ⟨⟨i, j⟩, H, rfl⟩)))⟩) @[simp] theorem sigmaCurry_apply [∀ i j, Zero (δ i j)] (f : Π₀ (i : Σ _, _), δ i.1 i.2) (i : ι) (j : α i) : sigmaCurry f i j = f ⟨i, j⟩ := rfl @[simp] theorem sigmaCurry_zero [∀ i j, Zero (δ i j)] : sigmaCurry (0 : Π₀ (i : Σ _, _), δ i.1 i.2) = 0 := rfl @[simp] theorem sigmaCurry_add [∀ i j, AddZeroClass (δ i j)] (f g : Π₀ (i : Σ _, _), δ i.1 i.2) : sigmaCurry (f + g) = (sigmaCurry f + sigmaCurry g : Π₀ (i) (j), δ i j) := by ext (i j) rfl @[simp] theorem sigmaCurry_smul [Monoid γ] [∀ i j, AddMonoid (δ i j)] [∀ i j, DistribMulAction γ (δ i j)] (r : γ) (f : Π₀ (i : Σ _, _), δ i.1 i.2) : sigmaCurry (r • f) = (r • sigmaCurry f : Π₀ (i) (j), δ i j) := by ext (i j) rfl @[simp] theorem sigmaCurry_single [∀ i, DecidableEq (α i)] [∀ i j, Zero (δ i j)] (ij : Σ i, α i) (x : δ ij.1 ij.2) : sigmaCurry (single ij x) = single ij.1 (single ij.2 x : Π₀ j, δ ij.1 j) := by obtain ⟨i, j⟩ := ij ext i' j' dsimp only rw [sigmaCurry_apply] obtain rfl | hi := eq_or_ne i i' · rw [single_eq_same] obtain rfl | hj := eq_or_ne j j' · rw [single_eq_same, single_eq_same] · rw [single_eq_of_ne, single_eq_of_ne hj] simpa using hj · rw [single_eq_of_ne, single_eq_of_ne hi, zero_apply] simp [hi] /-- The natural map between `Π₀ i (j : α i), δ i j` and `Π₀ (i : Σ i, α i), δ i.1 i.2`, inverse of `curry`. -/ def sigmaUncurry [∀ i j, Zero (δ i j)] [DecidableEq ι] (f : Π₀ (i) (j), δ i j) : Π₀ i : Σ _, _, δ i.1 i.2 where toFun i := f i.1 i.2 support' := f.support'.bind fun s => (Trunc.finChoice (fun i : ↥s.val.toFinset => (f i).support')).map fun fs => ⟨s.val.toFinset.attach.val.bind fun i => (fs i).val.map (Sigma.mk i.val), by rintro ⟨i, a⟩ cases s.prop i with | inl hi => cases (fs ⟨i, Multiset.mem_toFinset.mpr hi⟩).prop a with | inl ha => left; rw [Multiset.mem_bind] use ⟨i, Multiset.mem_toFinset.mpr hi⟩ constructor case right => simp [ha] case left => apply Multiset.mem_attach | inr ha => right; simp [toFun_eq_coe (f i) ▸ ha] | inr hi => right; simp [toFun_eq_coe f ▸ hi]⟩ @[simp] theorem sigmaUncurry_apply [∀ i j, Zero (δ i j)] (f : Π₀ (i) (j), δ i j) (i : ι) (j : α i) : sigmaUncurry f ⟨i, j⟩ = f i j := rfl @[simp] theorem sigmaUncurry_zero [∀ i j, Zero (δ i j)] : sigmaUncurry (0 : Π₀ (i) (j), δ i j) = 0 := rfl @[simp] theorem sigmaUncurry_add [∀ i j, AddZeroClass (δ i j)] (f g : Π₀ (i) (j), δ i j) : sigmaUncurry (f + g) = sigmaUncurry f + sigmaUncurry g := DFunLike.coe_injective rfl @[simp] theorem sigmaUncurry_smul [Monoid γ] [∀ i j, AddMonoid (δ i j)] [∀ i j, DistribMulAction γ (δ i j)] (r : γ) (f : Π₀ (i) (j), δ i j) : sigmaUncurry (r • f) = r • sigmaUncurry f := DFunLike.coe_injective rfl @[simp] theorem sigmaUncurry_single [∀ i j, Zero (δ i j)] [∀ i, DecidableEq (α i)] (i) (j : α i) (x : δ i j) : sigmaUncurry (single i (single j x : Π₀ j : α i, δ i j)) = single ⟨i, j⟩ (by exact x) := by ext ⟨i', j'⟩ dsimp only rw [sigmaUncurry_apply] obtain rfl | hi := eq_or_ne i i' · rw [single_eq_same] obtain rfl | hj := eq_or_ne j j' · rw [single_eq_same, single_eq_same] · rw [single_eq_of_ne hj, single_eq_of_ne] simpa using hj · rw [single_eq_of_ne hi, single_eq_of_ne, zero_apply] simp [hi] /-- The natural bijection between `Π₀ (i : Σ i, α i), δ i.1 i.2` and `Π₀ i (j : α i), δ i j`. This is the dfinsupp version of `Equiv.piCurry`. -/ def sigmaCurryEquiv [∀ i j, Zero (δ i j)] [DecidableEq ι] : (Π₀ i : Σ _, _, δ i.1 i.2) ≃ Π₀ (i) (j), δ i j where toFun := sigmaCurry invFun := sigmaUncurry left_inv f := by ext ⟨i, j⟩ rw [sigmaUncurry_apply, sigmaCurry_apply] right_inv f := by ext i j rw [sigmaCurry_apply, sigmaUncurry_apply] end SigmaCurry end Equiv end DFinsupp
Expr.lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Init import Qq /-! # Helpers to invoke functions involving algebra at tactic time This file provides instances on `x y : Q($α)` such that `x + y = q($x + $y)`. -/ open Qq /-- Produce a `One` instance for `Q($α)` such that `1 : Q($α)` is `q(1 : $α)`. -/ def Expr.instOne {u : Lean.Level} (α : Q(Type u)) (_ : Q(One $α)) : One Q($α) where one := q(1 : $α) /-- Produce a `Zero` instance for `Q($α)` such that `0 : Q($α)` is `q(0 : $α)`. -/ def Expr.instZero {u : Lean.Level} (α : Q(Type u)) (_ : Q(Zero $α)) : Zero Q($α) where zero := q(0 : $α) /-- Produce a `Mul` instance for `Q($α)` such that `x * y : Q($α)` is `q($x * $y)`. -/ def Expr.instMul {u : Lean.Level} (α : Q(Type u)) (_ : Q(Mul $α)) : Mul Q($α) where mul x y := q($x * $y) /-- Produce an `Add` instance for `Q($α)` such that `x + y : Q($α)` is `q($x + $y)`. -/ def Expr.instAdd {u : Lean.Level} (α : Q(Type u)) (_ : Q(Add $α)) : Add Q($α) where add x y := q($x + $y)
all_ssreflect.v
Attributes deprecated(since="mathcomp 2.5.0", note="Use 'all_boot' and/or 'all_order' instead."). From mathcomp Require Export all_boot. From mathcomp Require Export preorder. From mathcomp Require Export order.
action.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrbool ssrfun ssrnotations eqtype. From mathcomp Require Import ssrnat div seq prime fintype bigop finset. From mathcomp Require Import fingroup morphism perm automorphism quotient. (******************************************************************************) (* Group action: orbits, stabilisers, transitivity. *) (* is_action D to == the function to : T -> aT -> T defines an action *) (* of D : {set aT} on T. *) (* action D T == structure for a function defining an action of D. *) (* act_dom to == the domain D of to : action D rT. *) (* {action: aT &-> T} == structure for a total action. *) (* := action [set: aT] T *) (* TotalAction to1 toM == the constructor for total actions; to1 and toM *) (* are the proofs of the action identities for 1 and *) (* a * b, respectively. *) (* is_groupAction R to == to is a group action on range R: for all a in D, *) (* the permutation induced by to a is in Aut R. Thus *) (* the action of D must be trivial outside R. *) (* groupAction D R == the structure for group actions of D on R. This *) (* is a telescope on action D rT. *) (* gact_range to == the range R of to : groupAction D R. *) (* GroupAction toAut == constructs a groupAction for action to from *) (* toAut : actm to @* D \subset Aut R (actm to is *) (* the morphism to {perm rT} associated to 'to'). *) (* orbit to A x == the orbit of x under the action of A via to. *) (* orbit_transversal to A S == a transversal of the partition orbit to A @: S *) (* of S, provided A acts on S via to. *) (* amove to A x y == the set of a in A whose action sends x to y. *) (* 'C_A[x | to] == the stabiliser of x : rT in A :&: D. *) (* 'C_A(S | to) == the pointwise stabiliser of S : {set rT} in D :&: A. *) (* 'N_A(S | to) == the global stabiliser of S : {set rT} in D :&: A. *) (* 'Fix_(S | to)[a] == the set of fixpoints of a in S. *) (* 'Fix_(S | to)(A) == the set of fixpoints of A in S. *) (* In the first three _A can be omitted and defaults to the domain D of to; *) (* in the last two S can be omitted and defaults to [set: T], so 'Fix_to[a] *) (* is the set of all fixpoints of a. *) (* The domain restriction ensures that stabilisers have a canonical group *) (* structure, but note that 'Fix sets are generally not groups. Indeed, we *) (* provide alternative definitions when to is a group action on R: *) (* 'C_(G | to)(A) == the centraliser in R :&: G of the group action of *) (* D :&: A via to *) (* 'C_(G | to)[a] == the centraliser in R :&: G of a \in D, via to. *) (* These sets are groups when G is; G can be omitted: 'C(|to)(A) is the *) (* centraliser in R of the action of D :&: A via to. *) (* [acts A, on S | to] == A \subset D acts on the set S via to. *) (* {acts A, on S | to} == A acts on the set S (Prop statement). *) (* {acts A, on group G | to} == [acts A, on S | to] /\ G \subset R, i.e., *) (* A \subset D acts on G \subset R, via *) (* to : groupAction D R. *) (* [transitive A, on S | to] == A acts transitively on S. *) (* [faithful A, on S | to] == A acts faithfully on S. *) (* acts_irreducibly to A G == A acts irreducibly via the groupAction to *) (* on the nontrivial group G, i.e., A does *) (* not act on any nontrivial subgroup of G. *) (* Important caveat: the definitions of orbit, amove, 'Fix_(S | to)(A), *) (* transitive and faithful assume that A is a subset of the domain D. As most *) (* of the permutation actions we consider are total this is usually harmless. *) (* (Note that the theory of partial actions is only partially developed.) *) (* In all of the above, to is expected to be the actual action structure, *) (* not merely the function. There is a special scope %act for actions, and *) (* constructions and notations for many classical actions: *) (* 'P == natural action of a permutation group via aperm. *) (* 'J == internal group action (conjugation) via conjg (_ ^ _). *) (* 'R == regular group action (right translation) via mulg (_ * _). *) (* (However, to limit ambiguity, _ * _ is NOT a canonical action.) *) (* to^* == the action induced by to on {set rT} via to^* (== setact to). *) (* 'Js == the internal action on subsets via _ :^ _, equivalent to 'J^*. *) (* 'Rs == the regular action on subsets via rcoset, equivalent to 'R^*. *) (* 'JG == the conjugation action on {group rT} via (_ :^ _)%G. *) (* to / H == the action induced by to on coset_of H via qact to H, and *) (* restricted to (qact_dom to H) == 'N(rcosets H 'N(H) | to^* ). *) (* 'Q == the action induced to cosets by conjugation; the domain is *) (* qact_dom 'J H, which is provably equal to 'N(H). *) (* to %% A == the action of coset_of A via modact to A, with domain D / A *) (* and support restricted to 'C(D :&: A | to). *) (* to \ sAD == the action of A via ract to sAD == to, if sAD : A \subset D. *) (* [Aut G] == the permutation action restricted to Aut G, via autact G. *) (* <[nRA]> == the action of A on R via actby nRA == to in A and on R, and *) (* the trivial action elsewhere; here nRA : [acts A, on R | to] *) (* or nRA : {acts A, on group R | to}. *) (* to^? == the action induced by to on sT : @subType rT P, via subact to *) (* with domain subact_dom P to == 'N([set x | P x] | to). *) (* <<phi>> == the action of phi : D >-> {perm rT}, via mact phi. *) (* to \o f == the composite action (with domain f @*^-1 D) of the action to *) (* with f : {morphism G >-> aT}, via comp_act to f. Here f must *) (* be the actual morphism object (e.g., coset_morphism H), not *) (* the underlying function (e.g., coset H). *) (* The explicit application of an action to is usually written (to%act x a), *) (* but %act can be omitted if to is an abstract action or a set action to^*. *) (* Note that this form will simplify and expose the acting function. *) (* There is a %gact scope for group actions; the notations above are *) (* recognised in %gact when they denote canonical group actions. *) (* Actions can be used to define morphisms: *) (* actperm to == the morphism D >-> {perm rT} induced by to. *) (* actm to a == if a \in D the function on D induced by the action to, else *) (* the identity function. If to is a group action with range R *) (* then actm to a is canonically a morphism on R. *) (* We also define here the restriction operation on permutations (the domain *) (* of this operations is a stabiliser), and local automorphism groups: *) (* restr_perm S p == if p acts on S, the permutation with support in S that *) (* coincides with p on S; else the identity. Note that *) (* restr_perm is a permutation group morphism that maps *) (* Aut G to Aut S when S is a subgroup of G. *) (* Aut_in A G == the local permutation group 'N_A(G | 'P) / 'C_A(G | 'P) *) (* Usually A is an automorphism group, and then Aut_in A G *) (* is isomorphic to a subgroup of Aut G, specifically *) (* restr_perm @* A. *) (* Finally, gproduct.v will provide a semi-direct group construction that *) (* maps an external group action to an internal one; the theory of morphisms *) (* between such products makes use of the following definition: *) (* morph_act to to' f fA <=> the action of to' on the images of f and fA is *) (* the image of the action of to, i.e., for all x and a we *) (* have f (to x a) = to' (f x) (fA a). Note that there is *) (* no mention of the domains of to and to'; if needed, this *) (* predicate should be restricted via the {in ...} notation *) (* and domain conditions should be added. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope action_scope. Declare Scope groupAction_scope. Import GroupScope. Section ActionDef. Variables (aT : finGroupType) (D : {set aT}) (rT : Type). Implicit Types a b : aT. Implicit Type x : rT. Definition act_morph to x := forall a b, to x (a * b) = to (to x a) b. Definition is_action to := left_injective to /\ forall x, {in D &, act_morph to x}. Record action := Action {act :> rT -> aT -> rT; _ : is_action act}. Definition clone_action to := let: Action _ toP := to return {type of Action for to} -> action in fun k => k toP. End ActionDef. (* Need to close the Section here to avoid re-declaring all Argument Scopes *) Delimit Scope action_scope with act. Bind Scope action_scope with action. Arguments act_morph {aT rT%_type} to x%_g. Arguments is_action {aT} D%_g {rT} to. Arguments act {aT D%_g rT%_type} to%_act x%_g a%_g : rename. Arguments clone_action [aT D%_g rT%_type to%_act] _. Notation "{ 'action' aT &-> T }" := (action [set: aT] T) (format "{ 'action' aT &-> T }") : type_scope. Notation "[ 'action' 'of' to ]" := (clone_action (@Action _ _ _ to)) (format "[ 'action' 'of' to ]") : form_scope. Definition act_dom aT D rT of @action aT D rT := D. Section TotalAction. Variables (aT : finGroupType) (rT : Type) (to : rT -> aT -> rT). Hypotheses (to1 : to^~ 1 =1 id) (toM : forall x, act_morph to x). Lemma is_total_action : is_action setT to. Proof. split=> [a | x a b _ _] /=; last by rewrite toM. by apply: can_inj (to^~ a^-1) _ => x; rewrite -toM ?mulgV. Qed. Definition TotalAction := Action is_total_action. End TotalAction. Section ActionDefs. Variables (aT aT' : finGroupType) (D : {set aT}) (D' : {set aT'}). Definition morph_act rT rT' (to : action D rT) (to' : action D' rT') f fA := forall x a, f (to x a) = to' (f x) (fA a). Variable rT : finType. (* Most definitions require a finType structure on rT *) Implicit Type to : action D rT. Implicit Type A : {set aT}. Implicit Type S : {set rT}. Definition actm to a := if a \in D then to^~ a else id. Definition setact to S a := [set to x a | x in S]. Definition orbit to A x := to x @: A. Definition amove to A x y := [set a in A | to x a == y]. Definition afix to A := [set x | A \subset [set a | to x a == x]]. Definition astab S to := D :&: [set a | S \subset [set x | to x a == x]]. Definition astabs S to := D :&: [set a | S \subset to^~ a @^-1: S]. Definition acts_on A S to := {in A, forall a x, (to x a \in S) = (x \in S)}. Definition atrans A S to := S \in orbit to A @: S. Definition faithful A S to := A :&: astab S to \subset [1]. End ActionDefs. Arguments setact {aT D%_g rT} to%_act S%_g a%_g. Arguments orbit {aT D%_g rT} to%_act A%_g x%_g. Arguments amove {aT D%_g rT} to%_act A%_g x%_g y%_g. Arguments afix {aT D%_g rT} to%_act A%_g. Arguments astab {aT D%_g rT} S%_g to%_act. Arguments astabs {aT D%_g rT} S%_g to%_act. Arguments acts_on {aT D%_g rT} A%_g S%_g to%_act. Arguments atrans {aT D%_g rT} A%_g S%_g to%_act. Arguments faithful {aT D%_g rT} A%_g S%_g to%_act. Notation "to ^*" := (setact to) : function_scope. Prenex Implicits orbit amove. Notation "''Fix_' to ( A )" := (afix to A) (to at level 2, format "''Fix_' to ( A )") : group_scope. (* camlp4 grammar factoring *) Notation "''Fix_' ( to ) ( A )" := 'Fix_to(A) (only parsing) : group_scope. Notation "''Fix_' ( S | to ) ( A )" := (S :&: 'Fix_to(A)) (format "''Fix_' ( S | to ) ( A )") : group_scope. Notation "''Fix_' to [ a ]" := ('Fix_to([set a])) (to at level 2, format "''Fix_' to [ a ]") : group_scope. Notation "''Fix_' ( S | to ) [ a ]" := (S :&: 'Fix_to[a]) (format "''Fix_' ( S | to ) [ a ]") : group_scope. Notation "''C' ( S | to )" := (astab S to) : group_scope. Notation "''C_' A ( S | to )" := (A :&: 'C(S | to)) : group_scope. Notation "''C_' ( A ) ( S | to )" := 'C_A(S | to) (only parsing) : group_scope. Notation "''C' [ x | to ]" := ('C([set x] | to)) : group_scope. Notation "''C_' A [ x | to ]" := (A :&: 'C[x | to]) : group_scope. Notation "''C_' ( A ) [ x | to ]" := 'C_A[x | to] (only parsing) : group_scope. Notation "''N' ( S | to )" := (astabs S to) (format "''N' ( S | to )") : group_scope. Notation "''N_' A ( S | to )" := (A :&: 'N(S | to)) (A at level 2, format "''N_' A ( S | to )") : group_scope. Notation "[ 'acts' A , 'on' S | to ]" := (A \subset pred_of_set 'N(S | to)) (format "[ 'acts' A , 'on' S | to ]") : form_scope. Notation "{ 'acts' A , 'on' S | to }" := (acts_on A S to) (format "{ 'acts' A , 'on' S | to }") : type_scope. Notation "[ 'transitive' A , 'on' S | to ]" := (atrans A S to) (format "[ 'transitive' A , 'on' S | to ]") : form_scope. Notation "[ 'faithful' A , 'on' S | to ]" := (faithful A S to) (format "[ 'faithful' A , 'on' S | to ]") : form_scope. Section RawAction. (* Lemmas that do not require the group structure on the action domain. *) (* Some lemmas like actMin would be actually be valid for arbitrary rT, *) (* e.g., for actions on a function type, but would be difficult to use *) (* as a view due to the confusion between parameters and assumptions. *) Variables (aT : finGroupType) (D : {set aT}) (rT : finType) (to : action D rT). Implicit Types (a : aT) (x y : rT) (A B : {set aT}) (S T : {set rT}). Lemma act_inj : left_injective to. Proof. by case: to => ? []. Qed. Arguments act_inj : clear implicits. Lemma actMin x : {in D &, act_morph to x}. Proof. by case: to => ? []. Qed. Lemma actmEfun a : a \in D -> actm to a = to^~ a. Proof. by rewrite /actm => ->. Qed. Lemma actmE a : a \in D -> actm to a =1 to^~ a. Proof. by move=> Da; rewrite actmEfun. Qed. Lemma setactE S a : to^* S a = [set to x a | x in S]. Proof. by []. Qed. Lemma mem_setact S a x : x \in S -> to x a \in to^* S a. Proof. exact: imset_f. Qed. Lemma card_setact S a : #|to^* S a| = #|S|. Proof. by apply: card_imset; apply: act_inj. Qed. Lemma setact_is_action : is_action D to^*. Proof. split=> [a R S eqRS | a b Da Db S]; last first. by rewrite /setact /= -imset_comp; apply: eq_imset => x; apply: actMin. apply/setP=> x; apply/idP/idP=> /(mem_setact a). by rewrite eqRS => /imsetP[y Sy /act_inj->]. by rewrite -eqRS => /imsetP[y Sy /act_inj->]. Qed. Canonical set_action := Action setact_is_action. Lemma orbitE A x : orbit to A x = to x @: A. Proof. by []. Qed. Lemma orbitP A x y : reflect (exists2 a, a \in A & to x a = y) (y \in orbit to A x). Proof. by apply: (iffP imsetP) => [] [a]; exists a. Qed. Lemma mem_orbit A x a : a \in A -> to x a \in orbit to A x. Proof. exact: imset_f. Qed. Lemma afixP A x : reflect (forall a, a \in A -> to x a = x) (x \in 'Fix_to(A)). Proof. rewrite inE; apply: (iffP subsetP) => [xfix a /xfix | xfix a Aa]. by rewrite inE => /eqP. by rewrite inE xfix. Qed. Lemma afixS A B : A \subset B -> 'Fix_to(B) \subset 'Fix_to(A). Proof. by move=> sAB; apply/subsetP=> u /[!inE]; apply: subset_trans. Qed. Lemma afixU A B : 'Fix_to(A :|: B) = 'Fix_to(A) :&: 'Fix_to(B). Proof. by apply/setP=> x; rewrite !inE subUset. Qed. Lemma afix1P a x : reflect (to x a = x) (x \in 'Fix_to[a]). Proof. by rewrite inE sub1set inE; apply: eqP. Qed. Lemma astabIdom S : 'C_D(S | to) = 'C(S | to). Proof. by rewrite setIA setIid. Qed. Lemma astab_dom S : {subset 'C(S | to) <= D}. Proof. by move=> a /setIP[]. Qed. Lemma astab_act S a x : a \in 'C(S | to) -> x \in S -> to x a = x. Proof. rewrite 2!inE => /andP[_ cSa] Sx; apply/eqP. by have /[1!inE] := subsetP cSa x Sx. Qed. Lemma astabS S1 S2 : S1 \subset S2 -> 'C(S2 | to) \subset 'C(S1 | to). Proof. by move=> sS12; apply/subsetP=> x /[!inE] /andP[->]; apply: subset_trans. Qed. Lemma astabsIdom S : 'N_D(S | to) = 'N(S | to). Proof. by rewrite setIA setIid. Qed. Lemma astabs_dom S : {subset 'N(S | to) <= D}. Proof. by move=> a /setIdP[]. Qed. Lemma astabs_act S a x : a \in 'N(S | to) -> (to x a \in S) = (x \in S). Proof. rewrite 2!inE subEproper properEcard => /andP[_]. rewrite (card_preimset _ (act_inj _)) ltnn andbF orbF => /eqP{2}->. by rewrite inE. Qed. Lemma astab_sub S : 'C(S | to) \subset 'N(S | to). Proof. apply/subsetP=> a cSa; rewrite !inE (astab_dom cSa). by apply/subsetP=> x Sx; rewrite inE (astab_act cSa). Qed. Lemma astabsC S : 'N(~: S | to) = 'N(S | to). Proof. apply/setP=> a; apply/idP/idP=> nSa; rewrite !inE (astabs_dom nSa). by rewrite -setCS -preimsetC; apply/subsetP=> x; rewrite inE astabs_act. by rewrite preimsetC setCS; apply/subsetP=> x; rewrite inE astabs_act. Qed. Lemma astabsI S T : 'N(S | to) :&: 'N(T | to) \subset 'N(S :&: T | to). Proof. apply/subsetP=> a; rewrite !inE -!andbA preimsetI => /and4P[-> nSa _ nTa] /=. by rewrite setISS. Qed. Lemma astabs_setact S a : a \in 'N(S | to) -> to^* S a = S. Proof. move=> nSa; apply/eqP; rewrite eqEcard card_setact leqnn andbT. by apply/subsetP=> _ /imsetP[x Sx ->]; rewrite astabs_act. Qed. Lemma astab1_set S : 'C[S | set_action] = 'N(S | to). Proof. apply/setP=> a; apply/idP/idP=> nSa. case/setIdP: nSa => Da; rewrite !inE Da sub1set inE => /eqP defS. by apply/subsetP=> x Sx; rewrite inE -defS mem_setact. by rewrite !inE (astabs_dom nSa) sub1set inE /= astabs_setact. Qed. Lemma astabs_set1 x : 'N([set x] | to) = 'C[x | to]. Proof. apply/eqP; rewrite eqEsubset astab_sub andbC setIS //. by apply/subsetP=> a; rewrite ?(inE,sub1set). Qed. Lemma acts_dom A S : [acts A, on S | to] -> A \subset D. Proof. by move=> nSA; rewrite (subset_trans nSA) ?subsetIl. Qed. Lemma acts_act A S : [acts A, on S | to] -> {acts A, on S | to}. Proof. by move=> nAS a Aa x; rewrite astabs_act ?(subsetP nAS). Qed. Lemma astabCin A S : A \subset D -> (A \subset 'C(S | to)) = (S \subset 'Fix_to(A)). Proof. move=> sAD; apply/subsetP/subsetP=> [sAC x xS | sSF a aA]. by apply/afixP=> a aA; apply: astab_act (sAC _ aA) xS. rewrite !inE (subsetP sAD _ aA); apply/subsetP=> x xS. by move/afixP/(_ _ aA): (sSF _ xS) => /[1!inE] ->. Qed. Section ActsSetop. Variables (A : {set aT}) (S T : {set rT}). Hypotheses (AactS : [acts A, on S | to]) (AactT : [acts A, on T | to]). Lemma astabU : 'C(S :|: T | to) = 'C(S | to) :&: 'C(T | to). Proof. by apply/setP=> a; rewrite !inE subUset; case: (a \in D). Qed. Lemma astabsU : 'N(S | to) :&: 'N(T | to) \subset 'N(S :|: T | to). Proof. by rewrite -(astabsC S) -(astabsC T) -(astabsC (S :|: T)) setCU astabsI. Qed. Lemma astabsD : 'N(S | to) :&: 'N(T | to) \subset 'N(S :\: T| to). Proof. by rewrite setDE -(astabsC T) astabsI. Qed. Lemma actsI : [acts A, on S :&: T | to]. Proof. by apply: subset_trans (astabsI S T); rewrite subsetI AactS. Qed. Lemma actsU : [acts A, on S :|: T | to]. Proof. by apply: subset_trans astabsU; rewrite subsetI AactS. Qed. Lemma actsD : [acts A, on S :\: T | to]. Proof. by apply: subset_trans astabsD; rewrite subsetI AactS. Qed. End ActsSetop. Lemma acts_in_orbit A S x y : [acts A, on S | to] -> y \in orbit to A x -> x \in S -> y \in S. Proof. by move=> nSA/imsetP[a Aa ->{y}] Sx; rewrite (astabs_act _ (subsetP nSA a Aa)). Qed. Lemma subset_faithful A B S : B \subset A -> [faithful A, on S | to] -> [faithful B, on S | to]. Proof. by move=> sAB; apply: subset_trans; apply: setSI. Qed. Section Reindex. Variables (vT : Type) (idx : vT) (op : Monoid.com_law idx) (S : {set rT}). Lemma reindex_astabs a F : a \in 'N(S | to) -> \big[op/idx]_(i in S) F i = \big[op/idx]_(i in S) F (to i a). Proof. move=> nSa; rewrite (reindex_inj (act_inj a)); apply: eq_bigl => x. exact: astabs_act. Qed. Lemma reindex_acts A a F : [acts A, on S | to] -> a \in A -> \big[op/idx]_(i in S) F i = \big[op/idx]_(i in S) F (to i a). Proof. by move=> nSA /(subsetP nSA); apply: reindex_astabs. Qed. End Reindex. End RawAction. Arguments act_inj {aT D rT} to a [x1 x2] : rename. Notation "to ^*" := (set_action to) : action_scope. Arguments orbitP {aT D rT to A x y}. Arguments afixP {aT D rT to A x}. Arguments afix1P {aT D rT to a x}. Arguments reindex_astabs [aT D rT] to [vT idx op S] a [F]. Arguments reindex_acts [aT D rT] to [vT idx op S A a F]. Section PartialAction. (* Lemmas that require a (partial) group domain. *) Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable to : action D rT. Implicit Types a : aT. Implicit Types x y : rT. Implicit Types A B : {set aT}. Implicit Types G H : {group aT}. Implicit Types S : {set rT}. Lemma act1 x : to x 1 = x. Proof. by apply: (act_inj to 1); rewrite -actMin ?mulg1. Qed. Lemma actKin : {in D, right_loop invg to}. Proof. by move=> a Da /= x; rewrite -actMin ?groupV // mulgV act1. Qed. Lemma actKVin : {in D, rev_right_loop invg to}. Proof. by move=> a Da /= x; rewrite -{2}(invgK a) actKin ?groupV. Qed. Lemma setactVin S a : a \in D -> to^* S a^-1 = to^~ a @^-1: S. Proof. by move=> Da; apply: can2_imset_pre; [apply: actKVin | apply: actKin]. Qed. Lemma actXin x a i : a \in D -> to x (a ^+ i) = iter i (to^~ a) x. Proof. move=> Da; elim: i => /= [|i <-]; first by rewrite act1. by rewrite expgSr actMin ?groupX. Qed. Lemma afix1 : 'Fix_to(1) = setT. Proof. by apply/setP=> x; rewrite !inE sub1set inE act1 eqxx. Qed. Lemma afixD1 G : 'Fix_to(G^#) = 'Fix_to(G). Proof. by rewrite -{2}(setD1K (group1 G)) afixU afix1 setTI. Qed. Lemma orbit_refl G x : x \in orbit to G x. Proof. by rewrite -{1}[x]act1 mem_orbit. Qed. Local Notation orbit_rel A := (fun x y => x \in orbit to A y). Lemma contra_orbit G x y : x \notin orbit to G y -> x != y. Proof. by apply: contraNneq => ->; apply: orbit_refl. Qed. Lemma orbit_in_sym G : G \subset D -> symmetric (orbit_rel G). Proof. move=> sGD; apply: symmetric_from_pre => x y /imsetP[a Ga]. by move/(canLR (actKin (subsetP sGD a Ga))) <-; rewrite mem_orbit ?groupV. Qed. Lemma orbit_in_trans G : G \subset D -> transitive (orbit_rel G). Proof. move=> sGD _ _ z /imsetP[a Ga ->] /imsetP[b Gb ->]. by rewrite -actMin ?mem_orbit ?groupM // (subsetP sGD). Qed. Lemma orbit_in_eqP G x y : G \subset D -> reflect (orbit to G x = orbit to G y) (x \in orbit to G y). Proof. move=> sGD; apply: (iffP idP) => [yGx|<-]; last exact: orbit_refl. by apply/setP=> z; apply/idP/idP=> /orbit_in_trans-> //; rewrite orbit_in_sym. Qed. Lemma orbit_in_transl G x y z : G \subset D -> y \in orbit to G x -> (y \in orbit to G z) = (x \in orbit to G z). Proof. by move=> sGD Gxy; rewrite !(orbit_in_sym sGD _ z) (orbit_in_eqP y x sGD Gxy). Qed. Lemma orbit_act_in x a G : G \subset D -> a \in G -> orbit to G (to x a) = orbit to G x. Proof. by move=> sGD /mem_orbit/orbit_in_eqP->. Qed. Lemma orbit_actr_in x a G y : G \subset D -> a \in G -> (to y a \in orbit to G x) = (y \in orbit to G x). Proof. by move=> sGD /mem_orbit/orbit_in_transl->. Qed. Lemma orbit_inv_in A x y : A \subset D -> (y \in orbit to A^-1 x) = (x \in orbit to A y). Proof. move/subsetP=> sAD; apply/imsetP/imsetP=> [] [a Aa ->]. by exists a^-1; rewrite -?mem_invg ?actKin // -groupV sAD -?mem_invg. by exists a^-1; rewrite ?memV_invg ?actKin // sAD. Qed. Lemma orbit_lcoset_in A a x : A \subset D -> a \in D -> orbit to (a *: A) x = orbit to A (to x a). Proof. move/subsetP=> sAD Da; apply/setP=> y; apply/imsetP/imsetP=> [] [b Ab ->{y}]. by exists (a^-1 * b); rewrite -?actMin ?mulKVg // ?sAD -?mem_lcoset. by exists (a * b); rewrite ?mem_mulg ?set11 ?actMin // sAD. Qed. Lemma orbit_rcoset_in A a x y : A \subset D -> a \in D -> (to y a \in orbit to (A :* a) x) = (y \in orbit to A x). Proof. move=> sAD Da; rewrite -orbit_inv_in ?mul_subG ?sub1set // invMg. by rewrite invg_set1 orbit_lcoset_in ?inv_subG ?groupV ?actKin ?orbit_inv_in. Qed. Lemma orbit_conjsg_in A a x y : A \subset D -> a \in D -> (to y a \in orbit to (A :^ a) (to x a)) = (y \in orbit to A x). Proof. move=> sAD Da; rewrite conjsgE. by rewrite orbit_lcoset_in ?groupV ?mul_subG ?sub1set ?actKin ?orbit_rcoset_in. Qed. Lemma orbit1P G x : reflect (orbit to G x = [set x]) (x \in 'Fix_to(G)). Proof. apply: (iffP afixP) => [xfix | xfix a Ga]. apply/eqP; rewrite eq_sym eqEsubset sub1set -{1}[x]act1 imset_f //=. by apply/subsetP=> y; case/imsetP=> a Ga ->; rewrite inE xfix. by apply/set1P; rewrite -xfix imset_f. Qed. Lemma card_orbit1 G x : #|orbit to G x| = 1%N -> orbit to G x = [set x]. Proof. move=> orb1; apply/eqP; rewrite eq_sym eqEcard {}orb1 cards1. by rewrite sub1set orbit_refl. Qed. Lemma orbit_partition G S : [acts G, on S | to] -> partition (orbit to G @: S) S. Proof. move=> actsGS; have sGD := acts_dom actsGS. have eqiG: {in S & &, equivalence_rel [rel x y | y \in orbit to G x]}. by move=> x y z * /=; rewrite orbit_refl; split=> // /orbit_in_eqP->. congr (partition _ _): (equivalence_partitionP eqiG). apply: eq_in_imset => x Sx; apply/setP=> y. by rewrite inE /= andb_idl // => /acts_in_orbit->. Qed. Definition orbit_transversal A S := transversal (orbit to A @: S) S. Lemma orbit_transversalP G S (P := orbit to G @: S) (X := orbit_transversal G S) : [acts G, on S | to] -> [/\ is_transversal X P S, X \subset S, {in X &, forall x y, (y \in orbit to G x) = (x == y)} & forall x, x \in S -> exists2 a, a \in G & to x a \in X]. Proof. move/orbit_partition; rewrite -/P => partP. have [/eqP defS tiP _] := and3P partP. have trXP: is_transversal X P S := transversalP partP. have sXS: X \subset S := transversal_sub trXP. split=> // [x y Xx Xy /= | x Sx]. have Sx := subsetP sXS x Xx. rewrite -(inj_in_eq (pblock_inj trXP)) // eq_pblock ?defS //. by rewrite (def_pblock tiP (imset_f _ Sx)) ?orbit_refl. have /imsetP[y Xy defxG]: orbit to G x \in pblock P @: X. by rewrite (pblock_transversal trXP) ?imset_f. suffices /orbitP[a Ga def_y]: y \in orbit to G x by exists a; rewrite ?def_y. by rewrite defxG mem_pblock defS (subsetP sXS). Qed. Lemma group_set_astab S : group_set 'C(S | to). Proof. apply/group_setP; split=> [|a b cSa cSb]. by rewrite !inE group1; apply/subsetP=> x _; rewrite inE act1. rewrite !inE groupM ?(@astab_dom _ _ _ to S) //; apply/subsetP=> x Sx. by rewrite inE actMin ?(@astab_dom _ _ _ to S) ?(astab_act _ Sx). Qed. Canonical astab_group S := group (group_set_astab S). Lemma afix_gen_in A : A \subset D -> 'Fix_to(<<A>>) = 'Fix_to(A). Proof. move=> sAD; apply/eqP; rewrite eqEsubset afixS ?sub_gen //=. by rewrite -astabCin gen_subG ?astabCin. Qed. Lemma afix_cycle_in a : a \in D -> 'Fix_to(<[a]>) = 'Fix_to[a]. Proof. by move=> Da; rewrite afix_gen_in ?sub1set. Qed. Lemma afixYin A B : A \subset D -> B \subset D -> 'Fix_to(A <*> B) = 'Fix_to(A) :&: 'Fix_to(B). Proof. by move=> sAD sBD; rewrite afix_gen_in ?afixU // subUset sAD. Qed. Lemma afixMin G H : G \subset D -> H \subset D -> 'Fix_to(G * H) = 'Fix_to(G) :&: 'Fix_to(H). Proof. by move=> sGD sHD; rewrite -afix_gen_in ?mul_subG // genM_join afixYin. Qed. Lemma sub_astab1_in A x : A \subset D -> (A \subset 'C[x | to]) = (x \in 'Fix_to(A)). Proof. by move=> sAD; rewrite astabCin ?sub1set. Qed. Lemma group_set_astabs S : group_set 'N(S | to). Proof. apply/group_setP; split=> [|a b cSa cSb]. by rewrite !inE group1; apply/subsetP=> x Sx; rewrite inE act1. rewrite !inE groupM ?(@astabs_dom _ _ _ to S) //; apply/subsetP=> x Sx. by rewrite inE actMin ?(@astabs_dom _ _ _ to S) ?astabs_act. Qed. Canonical astabs_group S := group (group_set_astabs S). Lemma astab_norm S : 'N(S | to) \subset 'N('C(S | to)). Proof. apply/subsetP=> a nSa; rewrite inE sub_conjg; apply/subsetP=> b cSb. have [Da Db] := (astabs_dom nSa, astab_dom cSb). rewrite mem_conjgV !inE groupJ //; apply/subsetP=> x Sx. rewrite inE !actMin ?groupM ?groupV //. by rewrite (astab_act cSb) ?actKVin ?astabs_act ?groupV. Qed. Lemma astab_normal S : 'C(S | to) <| 'N(S | to). Proof. by rewrite /normal astab_sub astab_norm. Qed. Lemma acts_sub_orbit G S x : [acts G, on S | to] -> (orbit to G x \subset S) = (x \in S). Proof. move/acts_act=> GactS. apply/subsetP/idP=> [| Sx y]; first by apply; apply: orbit_refl. by case/orbitP=> a Ga <-{y}; rewrite GactS. Qed. Lemma acts_orbit G x : G \subset D -> [acts G, on orbit to G x | to]. Proof. move/subsetP=> sGD; apply/subsetP=> a Ga; rewrite !inE sGD //. apply/subsetP=> _ /imsetP[b Gb ->]. by rewrite inE -actMin ?sGD // imset_f ?groupM. Qed. Lemma acts_subnorm_fix A : [acts 'N_D(A), on 'Fix_to(D :&: A) | to]. Proof. apply/subsetP=> a nAa; have [Da _] := setIP nAa; rewrite !inE Da. apply/subsetP=> x Cx /[1!inE]; apply/afixP=> b DAb. have [Db _]:= setIP DAb; rewrite -actMin // conjgCV actMin ?groupJ ?groupV //. by rewrite /= (afixP Cx) // memJ_norm // groupV (subsetP (normsGI _ _) _ nAa). Qed. Lemma atrans_orbit G x : [transitive G, on orbit to G x | to]. Proof. by apply: imset_f; apply: orbit_refl. Qed. Section OrbitStabilizer. Variables (G : {group aT}) (x : rT). Hypothesis sGD : G \subset D. Let ssGD := subsetP sGD. Lemma amove_act a : a \in G -> amove to G x (to x a) = 'C_G[x | to] :* a. Proof. move=> Ga; apply/setP=> b; have Da := ssGD Ga. rewrite mem_rcoset !(inE, sub1set) !groupMr ?groupV //. by case Gb: (b \in G); rewrite //= actMin ?groupV ?ssGD ?(canF_eq (actKVin Da)). Qed. Lemma amove_orbit : amove to G x @: orbit to G x = rcosets 'C_G[x | to] G. Proof. apply/setP => Ha; apply/imsetP/rcosetsP=> [[y] | [a Ga ->]]. by case/imsetP=> b Gb -> ->{Ha y}; exists b => //; rewrite amove_act. by rewrite -amove_act //; exists (to x a); first apply: mem_orbit. Qed. Lemma amoveK : {in orbit to G x, cancel (amove to G x) (fun Ca => to x (repr Ca))}. Proof. move=> _ /orbitP[a Ga <-]; rewrite amove_act //= -[G :&: _]/(gval _). case: repr_rcosetP => b; rewrite !(inE, sub1set)=> /and3P[Gb _ xbx]. by rewrite actMin ?ssGD ?(eqP xbx). Qed. Lemma orbit_stabilizer : orbit to G x = [set to x (repr Ca) | Ca in rcosets 'C_G[x | to] G]. Proof. rewrite -amove_orbit -imset_comp /=; apply/setP=> z. by apply/idP/imsetP=> [xGz | [y xGy ->]]; first exists z; rewrite /= ?amoveK. Qed. Lemma act_reprK : {in rcosets 'C_G[x | to] G, cancel (to x \o repr) (amove to G x)}. Proof. move=> _ /rcosetsP[a Ga ->] /=; rewrite amove_act ?rcoset_repr //. rewrite -[G :&: _]/(gval _); case: repr_rcosetP => b /setIP[Gb _]. exact: groupM. Qed. End OrbitStabilizer. Lemma card_orbit_in G x : G \subset D -> #|orbit to G x| = #|G : 'C_G[x | to]|. Proof. move=> sGD; rewrite orbit_stabilizer 1?card_in_imset //. exact: can_in_inj (act_reprK _). Qed. Lemma card_orbit_in_stab G x : G \subset D -> (#|orbit to G x| * #|'C_G[x | to]|)%N = #|G|. Proof. by move=> sGD; rewrite mulnC card_orbit_in ?Lagrange ?subsetIl. Qed. Lemma acts_sum_card_orbit G S : [acts G, on S | to] -> \sum_(T in orbit to G @: S) #|T| = #|S|. Proof. by move/orbit_partition/card_partition. Qed. Lemma astab_setact_in S a : a \in D -> 'C(to^* S a | to) = 'C(S | to) :^ a. Proof. move=> Da; apply/setP=> b; rewrite mem_conjg !inE -mem_conjg conjGid //. apply: andb_id2l => Db; rewrite sub_imset_pre; apply: eq_subset_r => x. by rewrite !inE !actMin ?groupM ?groupV // invgK (canF_eq (actKVin Da)). Qed. Lemma astab1_act_in x a : a \in D -> 'C[to x a | to] = 'C[x | to] :^ a. Proof. by move=> Da; rewrite -astab_setact_in // /setact imset_set1. Qed. Theorem Frobenius_Cauchy G S : [acts G, on S | to] -> \sum_(a in G) #|'Fix_(S | to)[a]| = (#|orbit to G @: S| * #|G|)%N. Proof. move=> GactS; have sGD := acts_dom GactS. transitivity (\sum_(a in G) \sum_(x in 'Fix_(S | to)[a]) 1%N). by apply: eq_bigr => a _; rewrite -sum1_card. rewrite (exchange_big_dep [in S]) /= => [|a x _]; last by case/setIP. rewrite (set_partition_big _ (orbit_partition GactS)) -sum_nat_const /=. apply: eq_bigr => _ /imsetP[x Sx ->]. rewrite -(card_orbit_in_stab x sGD) -sum_nat_const. apply: eq_bigr => y; rewrite orbit_in_sym // => /imsetP[a Ga defx]. rewrite defx astab1_act_in ?(subsetP sGD) //. rewrite -{2}(conjGid Ga) -conjIg cardJg -sum1_card setIA (setIidPl sGD). by apply: eq_bigl => b; rewrite !(sub1set, inE) -(acts_act GactS Ga) -defx Sx. Qed. Lemma atrans_dvd_index_in G S : G \subset D -> [transitive G, on S | to] -> #|S| %| #|G : 'C_G(S | to)|. Proof. move=> sGD /imsetP[x Sx {1}->]; rewrite card_orbit_in //. by rewrite indexgS // setIS // astabS // sub1set. Qed. Lemma atrans_dvd_in G S : G \subset D -> [transitive G, on S | to] -> #|S| %| #|G|. Proof. move=> sGD transG; apply: dvdn_trans (atrans_dvd_index_in sGD transG) _. exact: dvdn_indexg. Qed. Lemma atransPin G S : G \subset D -> [transitive G, on S | to] -> forall x, x \in S -> orbit to G x = S. Proof. by move=> sGD /imsetP[y _ ->] x; apply/orbit_in_eqP. Qed. Lemma atransP2in G S : G \subset D -> [transitive G, on S | to] -> {in S &, forall x y, exists2 a, a \in G & y = to x a}. Proof. by move=> sGD transG x y /(atransPin sGD transG) <- /imsetP. Qed. Lemma atrans_acts_in G S : G \subset D -> [transitive G, on S | to] -> [acts G, on S | to]. Proof. move=> sGD transG; apply/subsetP=> a Ga; rewrite !inE (subsetP sGD) //. by apply/subsetP=> x /(atransPin sGD transG) <-; rewrite inE imset_f. Qed. Lemma subgroup_transitivePin G H S x : x \in S -> H \subset G -> G \subset D -> [transitive G, on S | to] -> reflect ('C_G[x | to] * H = G) [transitive H, on S | to]. Proof. move=> Sx sHG sGD trG; have sHD := subset_trans sHG sGD. apply: (iffP idP) => [trH | defG]. rewrite group_modr //; apply/setIidPl/subsetP=> a Ga. have Sxa: to x a \in S by rewrite (acts_act (atrans_acts_in sGD trG)). have [b Hb xab]:= atransP2in sHD trH Sxa Sx. have Da := subsetP sGD a Ga; have Db := subsetP sHD b Hb. rewrite -(mulgK b a) mem_mulg ?groupV // !inE groupM //= sub1set inE. by rewrite actMin -?xab. apply/imsetP; exists x => //; apply/setP=> y; rewrite -(atransPin sGD trG Sx). apply/imsetP/imsetP=> [] [a]; last by exists a; first apply: (subsetP sHG). rewrite -defG => /imset2P[c b /setIP[_ cxc] Hb ->] ->. exists b; rewrite ?actMin ?(astab_dom cxc) ?(subsetP sHD) //. by rewrite (astab_act cxc) ?inE. Qed. End PartialAction. Arguments orbit_transversal {aT D%_g rT} to%_act A%_g S%_g. Arguments orbit_in_eqP {aT D rT to G x y}. Arguments orbit1P {aT D rT to G x}. Arguments contra_orbit [aT D rT] to G [x y]. Notation "''C' ( S | to )" := (astab_group to S) : Group_scope. Notation "''C_' A ( S | to )" := (setI_group A 'C(S | to)) : Group_scope. Notation "''C_' ( A ) ( S | to )" := (setI_group A 'C(S | to)) (only parsing) : Group_scope. Notation "''C' [ x | to ]" := (astab_group to [set x%g]) : Group_scope. Notation "''C_' A [ x | to ]" := (setI_group A 'C[x | to]) : Group_scope. Notation "''C_' ( A ) [ x | to ]" := (setI_group A 'C[x | to]) (only parsing) : Group_scope. Notation "''N' ( S | to )" := (astabs_group to S) : Group_scope. Notation "''N_' A ( S | to )" := (setI_group A 'N(S | to)) : Group_scope. Section TotalActions. (* These lemmas are only established for total actions (domain = [set: rT]) *) Variable (aT : finGroupType) (rT : finType). Variable to : {action aT &-> rT}. Implicit Types (a b : aT) (x y z : rT) (A B : {set aT}) (G H : {group aT}). Implicit Type S : {set rT}. Lemma actM x a b : to x (a * b) = to (to x a) b. Proof. by rewrite actMin ?inE. Qed. Lemma actK : right_loop invg to. Proof. by move=> a; apply: actKin; rewrite inE. Qed. Lemma actKV : rev_right_loop invg to. Proof. by move=> a; apply: actKVin; rewrite inE. Qed. Lemma actX x a n : to x (a ^+ n) = iter n (to^~ a) x. Proof. by elim: n => [|n /= <-]; rewrite ?act1 // -actM expgSr. Qed. Lemma actCJ a b x : to (to x a) b = to (to x b) (a ^ b). Proof. by rewrite !actM actK. Qed. Lemma actCJV a b x : to (to x a) b = to (to x (b ^ a^-1)) a. Proof. by rewrite (actCJ _ a) conjgKV. Qed. Lemma orbit_sym G x y : (x \in orbit to G y) = (y \in orbit to G x). Proof. exact/orbit_in_sym/subsetT. Qed. Lemma orbit_trans G x y z : x \in orbit to G y -> y \in orbit to G z -> x \in orbit to G z. Proof. exact/orbit_in_trans/subsetT. Qed. Lemma orbit_eqP G x y : reflect (orbit to G x = orbit to G y) (x \in orbit to G y). Proof. exact/orbit_in_eqP/subsetT. Qed. Lemma orbit_transl G x y z : y \in orbit to G x -> (y \in orbit to G z) = (x \in orbit to G z). Proof. exact/orbit_in_transl/subsetT. Qed. Lemma orbit_act G a x: a \in G -> orbit to G (to x a) = orbit to G x. Proof. exact/orbit_act_in/subsetT. Qed. Lemma orbit_actr G a x y : a \in G -> (to y a \in orbit to G x) = (y \in orbit to G x). Proof. by move/mem_orbit/orbit_transl; apply. Qed. Lemma orbit_eq_mem G x y : (orbit to G x == orbit to G y) = (x \in orbit to G y). Proof. exact: sameP eqP (orbit_eqP G x y). Qed. Lemma orbit_inv A x y : (y \in orbit to A^-1 x) = (x \in orbit to A y). Proof. by rewrite orbit_inv_in ?subsetT. Qed. Lemma orbit_lcoset A a x : orbit to (a *: A) x = orbit to A (to x a). Proof. by rewrite orbit_lcoset_in ?subsetT ?inE. Qed. Lemma orbit_rcoset A a x y : (to y a \in orbit to (A :* a) x) = (y \in orbit to A x). Proof. by rewrite orbit_rcoset_in ?subsetT ?inE. Qed. Lemma orbit_conjsg A a x y : (to y a \in orbit to (A :^ a) (to x a)) = (y \in orbit to A x). Proof. by rewrite orbit_conjsg_in ?subsetT ?inE. Qed. Lemma astabP S a : reflect (forall x, x \in S -> to x a = x) (a \in 'C(S | to)). Proof. apply: (iffP idP) => [cSa x|cSa]; first exact: astab_act. by rewrite !inE; apply/subsetP=> x Sx; rewrite inE cSa. Qed. Lemma astab1P x a : reflect (to x a = x) (a \in 'C[x | to]). Proof. by rewrite !inE sub1set inE; apply: eqP. Qed. Lemma sub_astab1 A x : (A \subset 'C[x | to]) = (x \in 'Fix_to(A)). Proof. by rewrite sub_astab1_in ?subsetT. Qed. Lemma astabC A S : (A \subset 'C(S | to)) = (S \subset 'Fix_to(A)). Proof. by rewrite astabCin ?subsetT. Qed. Lemma afix_cycle a : 'Fix_to(<[a]>) = 'Fix_to[a]. Proof. by rewrite afix_cycle_in ?inE. Qed. Lemma afix_gen A : 'Fix_to(<<A>>) = 'Fix_to(A). Proof. by rewrite afix_gen_in ?subsetT. Qed. Lemma afixM G H : 'Fix_to(G * H) = 'Fix_to(G) :&: 'Fix_to(H). Proof. by rewrite afixMin ?subsetT. Qed. Lemma astabsP S a : reflect (forall x, (to x a \in S) = (x \in S)) (a \in 'N(S | to)). Proof. apply: (iffP idP) => [nSa x|nSa]; first exact: astabs_act. by rewrite !inE; apply/subsetP=> x; rewrite inE nSa. Qed. Lemma card_orbit G x : #|orbit to G x| = #|G : 'C_G[x | to]|. Proof. by rewrite card_orbit_in ?subsetT. Qed. Lemma dvdn_orbit G x : #|orbit to G x| %| #|G|. Proof. by rewrite card_orbit dvdn_indexg. Qed. Lemma card_orbit_stab G x : (#|orbit to G x| * #|'C_G[x | to]|)%N = #|G|. Proof. by rewrite mulnC card_orbit Lagrange ?subsetIl. Qed. Lemma actsP A S : reflect {acts A, on S | to} [acts A, on S | to]. Proof. apply: (iffP idP) => [nSA x|nSA]; first exact: acts_act. by apply/subsetP=> a Aa /[!inE]; apply/subsetP=> x; rewrite inE nSA. Qed. Arguments actsP {A S}. Lemma setact_orbit A x b : to^* (orbit to A x) b = orbit to (A :^ b) (to x b). Proof. apply/setP=> y; apply/idP/idP=> /imsetP[_ /imsetP[a Aa ->] ->{y}]. by rewrite actCJ mem_orbit ?memJ_conjg. by rewrite -actCJ mem_setact ?mem_orbit. Qed. Lemma astab_setact S a : 'C(to^* S a | to) = 'C(S | to) :^ a. Proof. apply/setP=> b; rewrite mem_conjg. apply/astabP/astabP=> stab x => [Sx|]. by rewrite conjgE invgK !actM stab ?actK //; apply/imsetP; exists x. by case/imsetP=> y Sy ->{x}; rewrite -actM conjgCV actM stab. Qed. Lemma astab1_act x a : 'C[to x a | to] = 'C[x | to] :^ a. Proof. by rewrite -astab_setact /setact imset_set1. Qed. Lemma atransP G S : [transitive G, on S | to] -> forall x, x \in S -> orbit to G x = S. Proof. by case/imsetP=> x _ -> y; apply/orbit_eqP. Qed. Lemma atransP2 G S : [transitive G, on S | to] -> {in S &, forall x y, exists2 a, a \in G & y = to x a}. Proof. by move=> GtrS x y /(atransP GtrS) <- /imsetP. Qed. Lemma atrans_acts G S : [transitive G, on S | to] -> [acts G, on S | to]. Proof. move=> GtrS; apply/subsetP=> a Ga; rewrite !inE. by apply/subsetP=> x /(atransP GtrS) <-; rewrite inE imset_f. Qed. Lemma atrans_supgroup G H S : G \subset H -> [transitive G, on S | to] -> [transitive H, on S | to] = [acts H, on S | to]. Proof. move=> sGH trG; apply/idP/idP=> [|actH]; first exact: atrans_acts. case/imsetP: trG => x Sx defS; apply/imsetP; exists x => //. by apply/eqP; rewrite eqEsubset acts_sub_orbit ?Sx // defS imsetS. Qed. Lemma atrans_acts_card G S : [transitive G, on S | to] = [acts G, on S | to] && (#|orbit to G @: S| == 1%N). Proof. apply/idP/andP=> [GtrS | [nSG]]. split; first exact: atrans_acts. rewrite ((_ @: S =P [set S]) _) ?cards1 // eqEsubset sub1set. apply/andP; split=> //; apply/subsetP=> _ /imsetP[x Sx ->]. by rewrite inE (atransP GtrS). rewrite eqn_leq andbC lt0n => /andP[/existsP[X /imsetP[x Sx X_Gx]]]. rewrite (cardD1 X) {X}X_Gx imset_f // ltnS leqn0 => /eqP GtrS. apply/imsetP; exists x => //; apply/eqP. rewrite eqEsubset acts_sub_orbit // Sx andbT. apply/subsetP=> y Sy; have:= card0_eq GtrS (orbit to G y). by rewrite !inE /= imset_f // andbT => /eqP <-; apply: orbit_refl. Qed. Lemma atrans_dvd G S : [transitive G, on S | to] -> #|S| %| #|G|. Proof. by case/imsetP=> x _ ->; apply: dvdn_orbit. Qed. (* This is Aschbacher (5.2) *) Lemma acts_fix_norm A B : A \subset 'N(B) -> [acts A, on 'Fix_to(B) | to]. Proof. move=> nAB; have:= acts_subnorm_fix to B; rewrite !setTI. exact: subset_trans. Qed. Lemma faithfulP A S : reflect (forall a, a \in A -> {in S, to^~ a =1 id} -> a = 1) [faithful A, on S | to]. Proof. apply: (iffP subsetP) => [Cto1 a Aa Ca | Cto1 a]. by apply/set1P; rewrite Cto1 // inE Aa; apply/astabP. by case/setIP=> Aa /astabP Ca; apply/set1P; apply: Cto1. Qed. (* This is the first part of Aschbacher (5.7) *) Lemma astab_trans_gcore G S u : [transitive G, on S | to] -> u \in S -> 'C(S | to) = gcore 'C[u | to] G. Proof. move=> transG Su; apply/eqP; rewrite eqEsubset. rewrite gcore_max ?astabS ?sub1set //=; last first. exact: subset_trans (atrans_acts transG) (astab_norm _ _). apply/subsetP=> x cSx; apply/astabP=> uy. case/(atransP2 transG Su) => y Gy ->{uy}. by apply/astab1P; rewrite astab1_act (bigcapP cSx). Qed. (* This is Aschbacher (5.20) *) Theorem subgroup_transitiveP G H S x : x \in S -> H \subset G -> [transitive G, on S | to] -> reflect ('C_G[x | to] * H = G) [transitive H, on S | to]. Proof. by move=> Sx sHG; apply: subgroup_transitivePin (subsetT G). Qed. (* This is Aschbacher (5.21) *) Lemma trans_subnorm_fixP x G H S : let C := 'C_G[x | to] in let T := 'Fix_(S | to)(H) in [transitive G, on S | to] -> x \in S -> H \subset C -> reflect ((H :^: G) ::&: C = H :^: C) [transitive 'N_G(H), on T | to]. Proof. move=> C T trGS Sx sHC; have actGS := acts_act (atrans_acts trGS). have:= sHC; rewrite subsetI sub_astab1 => /andP[sHG cHx]. have Tx: x \in T by rewrite inE Sx. apply: (iffP idP) => [trN | trC]. apply/setP=> Ha; apply/setIdP/imsetP=> [[]|[a Ca ->{Ha}]]; last first. by rewrite conj_subG //; case/setIP: Ca => Ga _; rewrite imset_f. case/imsetP=> a Ga ->{Ha}; rewrite subsetI !sub_conjg => /andP[_ sHCa]. have Txa: to x a^-1 \in T. by rewrite inE -sub_astab1 astab1_act actGS ?Sx ?groupV. have [b] := atransP2 trN Tx Txa; case/setIP=> Gb nHb cxba. exists (b * a); last by rewrite conjsgM (normP nHb). by rewrite inE groupM //; apply/astab1P; rewrite actM -cxba actKV. apply/imsetP; exists x => //; apply/setP=> y; apply/idP/idP=> [Ty|]. have [Sy cHy]:= setIP Ty; have [a Ga defy] := atransP2 trGS Sx Sy. have: H :^ a^-1 \in H :^: C. rewrite -trC inE subsetI imset_f 1?conj_subG ?groupV // sub_conjgV. by rewrite -astab1_act -defy sub_astab1. case/imsetP=> b /setIP[Gb /astab1P cxb] defHb. rewrite defy -{1}cxb -actM mem_orbit // inE groupM //. by apply/normP; rewrite conjsgM -defHb conjsgKV. case/imsetP=> a /setIP[Ga nHa] ->{y}. by rewrite inE actGS // Sx (acts_act (acts_fix_norm _) nHa). Qed. End TotalActions. Arguments astabP {aT rT to S a}. Arguments orbit_eqP {aT rT to G x y}. Arguments astab1P {aT rT to x a}. Arguments astabsP {aT rT to S a}. Arguments atransP {aT rT to G S}. Arguments actsP {aT rT to A S}. Arguments faithfulP {aT rT to A S}. Section Restrict. Variables (aT : finGroupType) (D : {set aT}) (rT : Type). Variables (to : action D rT) (A : {set aT}). Definition ract of A \subset D := act to. Variable sAD : A \subset D. Lemma ract_is_action : is_action A (ract sAD). Proof. rewrite /ract; case: to => f [injf fM]. by split=> // x; apply: (sub_in2 (subsetP sAD)). Qed. Canonical raction := Action ract_is_action. Lemma ractE : raction =1 to. Proof. by []. Qed. (* Other properties of raction need rT : finType; we defer them *) (* until after the definition of actperm. *) End Restrict. Notation "to \ sAD" := (raction to sAD) (at level 50) : action_scope. Section ActBy. Variables (aT : finGroupType) (D : {set aT}) (rT : finType). Definition actby_cond (A : {set aT}) R (to : action D rT) : Prop := [acts A, on R | to]. Definition actby A R to of actby_cond A R to := fun x a => if (x \in R) && (a \in A) then to x a else x. Variables (A : {group aT}) (R : {set rT}) (to : action D rT). Hypothesis nRA : actby_cond A R to. Lemma actby_is_action : is_action A (actby nRA). Proof. rewrite /actby; split=> [a x y | x a b Aa Ab /=]; last first. rewrite Aa Ab groupM // !andbT actMin ?(subsetP (acts_dom nRA)) //. by case Rx: (x \in R); rewrite ?(acts_act nRA) ?Rx. case Aa: (a \in A); rewrite ?andbF ?andbT //. case Rx: (x \in R); case Ry: (y \in R) => // eqxy; first exact: act_inj eqxy. by rewrite -eqxy (acts_act nRA Aa) Rx in Ry. by rewrite eqxy (acts_act nRA Aa) Ry in Rx. Qed. Canonical action_by := Action actby_is_action. Local Notation "<[nRA]>" := action_by : action_scope. Lemma actbyE x a : x \in R -> a \in A -> <[nRA]>%act x a = to x a. Proof. by rewrite /= /actby => -> ->. Qed. Lemma afix_actby B : 'Fix_<[nRA]>(B) = ~: R :|: 'Fix_to(A :&: B). Proof. apply/setP=> x; rewrite !inE /= /actby. case: (x \in R); last by apply/subsetP=> a _ /[!inE]. apply/subsetP/subsetP=> [cBx a | cABx a Ba] /[!inE]. by case/andP=> Aa /cBx; rewrite inE Aa. by case: ifP => //= Aa; have:= cABx a; rewrite !inE Aa => ->. Qed. Lemma astab_actby S : 'C(S | <[nRA]>) = 'C_A(R :&: S | to). Proof. apply/setP=> a; rewrite setIA (setIidPl (acts_dom nRA)) !inE. case Aa: (a \in A) => //=; apply/subsetP/subsetP=> cRSa x => [|Sx]. by case/setIP=> Rx /cRSa; rewrite !inE actbyE. by have:= cRSa x; rewrite !inE /= /actby Aa Sx; case: (x \in R) => //; apply. Qed. Lemma astabs_actby S : 'N(S | <[nRA]>) = 'N_A(R :&: S | to). Proof. apply/setP=> a; rewrite setIA (setIidPl (acts_dom nRA)) !inE. case Aa: (a \in A) => //=; apply/subsetP/subsetP=> nRSa x => [|Sx]. by case/setIP=> Rx /nRSa; rewrite !inE actbyE ?(acts_act nRA) ?Rx. have:= nRSa x; rewrite !inE /= /actby Aa Sx ?(acts_act nRA) //. by case: (x \in R) => //; apply. Qed. Lemma acts_actby (B : {set aT}) S : [acts B, on S | <[nRA]>] = (B \subset A) && [acts B, on R :&: S | to]. Proof. by rewrite astabs_actby subsetI. Qed. End ActBy. Notation "<[ nRA ] >" := (action_by nRA) : action_scope. Section SubAction. Variables (aT : finGroupType) (D : {group aT}). Variables (rT : finType) (sP : pred rT) (sT : subFinType sP) (to : action D rT). Implicit Type A : {set aT}. Implicit Type u : sT. Implicit Type S : {set sT}. Definition subact_dom := 'N([set x | sP x] | to). Canonical subact_dom_group := [group of subact_dom]. Implicit Type Na : {a | a \in subact_dom}. Lemma sub_act_proof u Na : sP (to (val u) (val Na)). Proof. by case: Na => a /= /(astabs_act (val u)); rewrite !inE valP. Qed. Definition subact u a := if insub a is Some Na then Sub _ (sub_act_proof u Na) else u. Lemma val_subact u a : val (subact u a) = if a \in subact_dom then to (val u) a else val u. Proof. by rewrite /subact -if_neg; case: insubP => [Na|] -> //=; rewrite SubK => ->. Qed. Lemma subact_is_action : is_action subact_dom subact. Proof. split=> [a u v eq_uv | u a b Na Nb]; apply: val_inj. move/(congr1 val): eq_uv; rewrite !val_subact. by case: (a \in _); first move/act_inj. have Da := astabs_dom Na; have Db := astabs_dom Nb. by rewrite !val_subact Na Nb groupM ?actMin. Qed. Canonical subaction := Action subact_is_action. Lemma astab_subact S : 'C(S | subaction) = subact_dom :&: 'C(val @: S | to). Proof. apply/setP=> a; rewrite inE in_setI; apply: andb_id2l => sDa. have [Da _] := setIP sDa; rewrite !inE Da. apply/subsetP/subsetP=> [cSa _ /imsetP[x Sx ->] | cSa x Sx] /[!inE]. by have:= cSa x Sx; rewrite inE -val_eqE val_subact sDa. by have:= cSa _ (imset_f val Sx); rewrite inE -val_eqE val_subact sDa. Qed. Lemma astabs_subact S : 'N(S | subaction) = subact_dom :&: 'N(val @: S | to). Proof. apply/setP=> a; rewrite inE in_setI; apply: andb_id2l => sDa. have [Da _] := setIP sDa; rewrite !inE Da. apply/subsetP/subsetP=> [nSa _ /imsetP[x Sx ->] | nSa x Sx] /[!inE]. by have /[1!inE]/(imset_f val) := nSa x Sx; rewrite val_subact sDa. have /[1!inE]/imsetP[y Sy def_y] := nSa _ (imset_f val Sx). by rewrite ((_ a =P y) _) // -val_eqE val_subact sDa def_y. Qed. Lemma afix_subact A : A \subset subact_dom -> 'Fix_subaction(A) = val @^-1: 'Fix_to(A). Proof. move/subsetP=> sAD; apply/setP=> u. rewrite !inE !(sameP setIidPl eqP); congr (_ == A). apply/setP=> a /[!inE]; apply: andb_id2l => Aa. by rewrite -val_eqE val_subact sAD. Qed. End SubAction. Notation "to ^?" := (subaction _ to) (format "to ^?") : action_scope. Section QuotientAction. Variables (aT : finGroupType) (D : {group aT}) (rT : finGroupType). Variables (to : action D rT) (H : {group rT}). Definition qact_dom := 'N(rcosets H 'N(H) | to^*). Canonical qact_dom_group := [group of qact_dom]. Local Notation subdom := (subact_dom (coset_range H) to^*). Fact qact_subdomE : subdom = qact_dom. Proof. by congr 'N(_|_); apply/setP=> Hx; rewrite !inE genGid. Qed. Lemma qact_proof : qact_dom \subset subdom. Proof. by rewrite qact_subdomE. Qed. Definition qact : coset_of H -> aT -> coset_of H := act (to^*^? \ qact_proof). Canonical quotient_action := [action of qact]. Lemma acts_qact_dom : [acts qact_dom, on 'N(H) | to]. Proof. apply/subsetP=> a nNa; rewrite !inE (astabs_dom nNa); apply/subsetP=> x Nx. have: H :* x \in rcosets H 'N(H) by rewrite -rcosetE imset_f. rewrite inE -(astabs_act _ nNa) => /rcosetsP[y Ny defHy]. have: to x a \in H :* y by rewrite -defHy (imset_f (to^~a)) ?rcoset_refl. by apply: subsetP; rewrite mul_subG ?sub1set ?normG. Qed. Lemma qactEcond x a : x \in 'N(H) -> quotient_action (coset H x) a = coset H (if a \in qact_dom then to x a else x). Proof. move=> Nx; apply: val_inj; rewrite val_subact //= qact_subdomE. have: H :* x \in rcosets H 'N(H) by rewrite -rcosetE imset_f. case nNa: (a \in _); rewrite // -(astabs_act _ nNa). rewrite !val_coset ?(acts_act acts_qact_dom nNa) //=. case/rcosetsP=> y Ny defHy; rewrite defHy; apply: rcoset_eqP. by rewrite rcoset_sym -defHy (imset_f (_^~_)) ?rcoset_refl. Qed. Lemma qactE x a : x \in 'N(H) -> a \in qact_dom -> quotient_action (coset H x) a = coset H (to x a). Proof. by move=> Nx nNa; rewrite qactEcond ?nNa. Qed. Lemma acts_quotient (A : {set aT}) (B : {set rT}) : A \subset 'N_qact_dom(B | to) -> [acts A, on B / H | quotient_action]. Proof. move=> nBA; apply: subset_trans {A}nBA _; apply/subsetP=> a /setIP[dHa nBa]. rewrite inE dHa inE; apply/subsetP=> _ /morphimP[x nHx Bx ->]. rewrite inE /= qactE //. by rewrite mem_morphim ?(acts_act acts_qact_dom) ?(astabs_act _ nBa). Qed. Lemma astabs_quotient (G : {group rT}) : H <| G -> 'N(G / H | quotient_action) = 'N_qact_dom(G | to). Proof. move=> nsHG; have [_ nHG] := andP nsHG. apply/eqP; rewrite eqEsubset acts_quotient // andbT. apply/subsetP=> a nGa; have dHa := astabs_dom nGa; have [Da _]:= setIdP dHa. rewrite inE dHa 2!inE Da; apply/subsetP=> x Gx; have nHx := subsetP nHG x Gx. rewrite -(quotientGK nsHG) 2!inE (acts_act acts_qact_dom) ?nHx //= inE. by rewrite -qactE // (astabs_act _ nGa) mem_morphim. Qed. End QuotientAction. Notation "to / H" := (quotient_action to H) : action_scope. Section ModAction. Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable to : action D rT. Implicit Types (G : {group aT}) (S : {set rT}). Section GenericMod. Variable H : {group aT}. Local Notation dom := 'N_D(H). Local Notation range := 'Fix_to(D :&: H). Let acts_dom : {acts dom, on range | to} := acts_act (acts_subnorm_fix to H). Definition modact x (Ha : coset_of H) := if x \in range then to x (repr (D :&: Ha)) else x. Lemma modactEcond x a : a \in dom -> modact x (coset H a) = (if x \in range then to x a else x). Proof. case/setIP=> Da Na; case: ifP => Cx; rewrite /modact Cx //. rewrite val_coset // -group_modr ?sub1set //. case: (repr _) / (repr_rcosetP (D :&: H) a) => a' Ha'. by rewrite actMin ?(afixP Cx _ Ha') //; case/setIP: Ha'. Qed. Lemma modactE x a : a \in D -> a \in 'N(H) -> x \in range -> modact x (coset H a) = to x a. Proof. by move=> Da Na Rx; rewrite modactEcond ?Rx // inE Da. Qed. Lemma modact_is_action : is_action (D / H) modact. Proof. split=> [Ha x y | x Ha Hb]; last first. case/morphimP=> a Na Da ->{Ha}; case/morphimP=> b Nb Db ->{Hb}. rewrite -morphM //= !modactEcond // ?groupM ?(introT setIP _) //. by case: ifP => Cx; rewrite ?(acts_dom, Cx, actMin, introT setIP _). case: (set_0Vmem (D :&: Ha)) => [Da0 | [a /setIP[Da NHa]]]. by rewrite /modact Da0 repr_set0 !act1 !if_same. have Na := subsetP (coset_norm _) _ NHa. have NDa: a \in 'N_D(H) by rewrite inE Da. rewrite -(coset_mem NHa) !modactEcond //. do 2![case: ifP]=> Cy Cx // eqxy; first exact: act_inj eqxy. by rewrite -eqxy acts_dom ?Cx in Cy. by rewrite eqxy acts_dom ?Cy in Cx. Qed. Canonical mod_action := Action modact_is_action. Section Stabilizers. Variable S : {set rT}. Hypothesis cSH : H \subset 'C(S | to). Let fixSH : S \subset 'Fix_to(D :&: H). Proof. by rewrite -astabCin ?subsetIl // subIset ?cSH ?orbT. Qed. Lemma astabs_mod : 'N(S | mod_action) = 'N(S | to) / H. Proof. apply/setP=> Ha; apply/idP/morphimP=> [nSa | [a nHa nSa ->]]. case/morphimP: (astabs_dom nSa) => a nHa Da defHa. exists a => //; rewrite !inE Da; apply/subsetP=> x Sx; rewrite !inE. by have:= Sx; rewrite -(astabs_act x nSa) defHa /= modactE ?(subsetP fixSH). have Da := astabs_dom nSa; rewrite !inE mem_quotient //; apply/subsetP=> x Sx. by rewrite !inE /= modactE ?(astabs_act x nSa) ?(subsetP fixSH). Qed. Lemma astab_mod : 'C(S | mod_action) = 'C(S | to) / H. Proof. apply/setP=> Ha; apply/idP/morphimP=> [cSa | [a nHa cSa ->]]. case/morphimP: (astab_dom cSa) => a nHa Da defHa. exists a => //; rewrite !inE Da; apply/subsetP=> x Sx; rewrite !inE. by rewrite -{2}[x](astab_act cSa) // defHa /= modactE ?(subsetP fixSH). have Da := astab_dom cSa; rewrite !inE mem_quotient //; apply/subsetP=> x Sx. by rewrite !inE /= modactE ?(astab_act cSa) ?(subsetP fixSH). Qed. End Stabilizers. Lemma afix_mod G S : H \subset 'C(S | to) -> G \subset 'N_D(H) -> 'Fix_(S | mod_action)(G / H) = 'Fix_(S | to)(G). Proof. move=> cSH /subsetIP[sGD nHG]. apply/eqP; rewrite eqEsubset !subsetI !subsetIl /= -!astabCin ?quotientS //. have cfixH F: H \subset 'C(S :&: F | to). by rewrite (subset_trans cSH) // astabS ?subsetIl. rewrite andbC astab_mod ?quotientS //=; last by rewrite astabCin ?subsetIr. by rewrite -(quotientSGK nHG) //= -astab_mod // astabCin ?quotientS ?subsetIr. Qed. End GenericMod. Lemma modact_faithful G S : [faithful G / 'C_G(S | to), on S | mod_action 'C_G(S | to)]. Proof. rewrite /faithful astab_mod ?subsetIr //=. by rewrite -quotientIG ?subsetIr ?trivg_quotient. Qed. End ModAction. Notation "to %% H" := (mod_action to H) : action_scope. Section ActPerm. (* Morphism to permutations induced by an action. *) Variables (aT : finGroupType) (D : {set aT}) (rT : finType). Variable to : action D rT. Definition actperm a := perm (act_inj to a). Lemma actpermM : {in D &, {morph actperm : a b / a * b}}. Proof. by move=> a b Da Db; apply/permP=> x; rewrite permM !permE actMin. Qed. Canonical actperm_morphism := Morphism actpermM. Lemma actpermE a x : actperm a x = to x a. Proof. by rewrite permE. Qed. Lemma actpermK x a : aperm x (actperm a) = to x a. Proof. exact: actpermE. Qed. Lemma ker_actperm : 'ker actperm = 'C(setT | to). Proof. congr (_ :&: _); apply/setP=> a /[!inE]/=. apply/eqP/subsetP=> [a1 x _ | a1]; first by rewrite inE -actpermE a1 perm1. by apply/permP=> x; apply/eqP; have:= a1 x; rewrite !inE actpermE perm1 => ->. Qed. End ActPerm. Section RestrictActionTheory. Variables (aT : finGroupType) (D : {set aT}) (rT : finType). Variables (to : action D rT). Lemma faithful_isom (A : {group aT}) S (nSA : actby_cond A S to) : [faithful A, on S | to] -> isom A (actperm <[nSA]> @* A) (actperm <[nSA]>). Proof. by move=> ffulAS; apply/isomP; rewrite ker_actperm astab_actby setIT. Qed. Variables (A : {set aT}) (sAD : A \subset D). Lemma ractpermE : actperm (to \ sAD) =1 actperm to. Proof. by move=> a; apply/permP=> x; rewrite !permE. Qed. Lemma afix_ract B : 'Fix_(to \ sAD)(B) = 'Fix_to(B). Proof. by []. Qed. Lemma astab_ract S : 'C(S | to \ sAD) = 'C_A(S | to). Proof. by rewrite setIA (setIidPl sAD). Qed. Lemma astabs_ract S : 'N(S | to \ sAD) = 'N_A(S | to). Proof. by rewrite setIA (setIidPl sAD). Qed. Lemma acts_ract (B : {set aT}) S : [acts B, on S | to \ sAD] = (B \subset A) && [acts B, on S | to]. Proof. by rewrite astabs_ract subsetI. Qed. End RestrictActionTheory. Section MorphAct. (* Action induced by a morphism to permutations. *) Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable phi : {morphism D >-> {perm rT}}. Definition mact x a := phi a x. Lemma mact_is_action : is_action D mact. Proof. split=> [a x y | x a b Da Db]; first exact: perm_inj. by rewrite /mact morphM //= permM. Qed. Canonical morph_action := Action mact_is_action. Lemma mactE x a : morph_action x a = phi a x. Proof. by []. Qed. Lemma injm_faithful : 'injm phi -> [faithful D, on setT | morph_action]. Proof. move/injmP=> phi_inj; apply/subsetP=> a /setIP[Da /astab_act a1]. apply/set1P/phi_inj => //; apply/permP=> x. by rewrite morph1 perm1 -mactE a1 ?inE. Qed. Lemma perm_mact a : actperm morph_action a = phi a. Proof. by apply/permP=> x; rewrite permE. Qed. End MorphAct. Notation "<< phi >>" := (morph_action phi) : action_scope. Section CompAct. Variables (gT aT : finGroupType) (rT : finType). Variables (D : {set aT}) (to : action D rT). Variables (B : {set gT}) (f : {morphism B >-> aT}). Definition comp_act x e := to x (f e). Lemma comp_is_action : is_action (f @*^-1 D) comp_act. Proof. split=> [e | x e1 e2]; first exact: act_inj. move=> /morphpreP[Be1 Dfe1] /morphpreP[Be2 Dfe2]. by rewrite /comp_act morphM ?actMin. Qed. Canonical comp_action := Action comp_is_action. Lemma comp_actE x e : comp_action x e = to x (f e). Proof. by []. Qed. Lemma afix_comp (A : {set gT}) : A \subset B -> 'Fix_comp_action(A) = 'Fix_to(f @* A). Proof. move=> sAB; apply/setP=> x; rewrite !inE /morphim (setIidPr sAB). apply/subsetP/subsetP; first by move=> + _ /imsetP[a + ->] => /[apply]/[!inE]. by move=> + a Aa => /(_ (f a)); rewrite !inE imset_f// => ->. Qed. Lemma astab_comp S : 'C(S | comp_action) = f @*^-1 'C(S | to). Proof. by apply/setP=> x; rewrite !inE -andbA. Qed. Lemma astabs_comp S : 'N(S | comp_action) = f @*^-1 'N(S | to). Proof. by apply/setP=> x; rewrite !inE -andbA. Qed. End CompAct. Notation "to \o f" := (comp_action to f) : action_scope. Section PermAction. (* Natural action of permutation groups. *) Variable rT : finType. Local Notation gT := {perm rT}. Implicit Types a b c : gT. Lemma aperm_is_action : is_action setT (@aperm rT). Proof. by apply: is_total_action => [x|x a b]; rewrite apermE (perm1, permM). Qed. Canonical perm_action := Action aperm_is_action. Lemma porbitE a : porbit a = orbit perm_action <[a]>%g. Proof. by rewrite unlock. Qed. Lemma perm_act1P a : reflect (forall x, aperm x a = x) (a == 1). Proof. apply: (iffP eqP) => [-> x | a1]; first exact: act1. by apply/permP=> x; rewrite -apermE a1 perm1. Qed. Lemma perm_faithful A : [faithful A, on setT | perm_action]. Proof. apply/subsetP=> a /setIP[Da crTa]. by apply/set1P; apply/permP=> x; rewrite -apermE perm1 (astabP crTa) ?inE. Qed. Lemma actperm_id p : actperm perm_action p = p. Proof. by apply/permP=> x; rewrite permE. Qed. End PermAction. Arguments perm_act1P {rT a}. Notation "'P" := (perm_action _) : action_scope. Section ActpermOrbits. Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable to : action D rT. Lemma orbit_morphim_actperm (A : {set aT}) : A \subset D -> orbit 'P (actperm to @* A) =1 orbit to A. Proof. move=> sAD x; rewrite morphimEsub // /orbit -imset_comp. by apply: eq_imset => a //=; rewrite actpermK. Qed. Lemma porbit_actperm (a : aT) : a \in D -> porbit (actperm to a) =1 orbit to <[a]>. Proof. move=> Da x. by rewrite porbitE -orbit_morphim_actperm ?cycle_subG ?morphim_cycle. Qed. End ActpermOrbits. Section RestrictPerm. Variables (T : finType) (S : {set T}). Definition restr_perm := actperm (<[subxx 'N(S | 'P)]>). Canonical restr_perm_morphism := [morphism of restr_perm]. Lemma restr_perm_on p : perm_on S (restr_perm p). Proof. apply/subsetP=> x; apply: contraR => notSx. by rewrite permE /= /actby (negPf notSx). Qed. Lemma triv_restr_perm p : p \notin 'N(S | 'P) -> restr_perm p = 1. Proof. move=> not_nSp; apply/permP=> x. by rewrite !permE /= /actby (negPf not_nSp) andbF. Qed. Lemma restr_permE : {in 'N(S | 'P) & S, forall p, restr_perm p =1 p}. Proof. by move=> y x nSp Sx; rewrite /= actpermE actbyE. Qed. Lemma ker_restr_perm : 'ker restr_perm = 'C(S | 'P). Proof. by rewrite ker_actperm astab_actby setIT (setIidPr (astab_sub _ _)). Qed. Lemma im_restr_perm p : restr_perm p @: S = S. Proof. exact: im_perm_on (restr_perm_on p). Qed. Lemma restr_perm_commute s : commute (restr_perm s) s. Proof. have [sC|/triv_restr_perm->] := boolP (s \in 'N(S | 'P)); last first. exact: (commute_sym (commute1 _)). apply/permP => x; have /= xsS := astabsP sC x; rewrite !permM. have [xS|xNS] := boolP (x \in S); first by rewrite ?(restr_permE) ?xsS. by rewrite !(out_perm (restr_perm_on _)) ?xsS. Qed. End RestrictPerm. Section Symmetry. Variables (T : finType) (S : {set T}). Lemma SymE : Sym S = 'C(~: S | 'P). Proof. apply/setP => s; rewrite inE; apply/idP/astabP => [sS x|/= S_id]. by rewrite inE /= apermE => /out_perm->. by apply/subsetP => x; move=> /(contra_neqN (S_id _)); rewrite inE negbK. Qed. End Symmetry. Section AutIn. Variable gT : finGroupType. Definition Aut_in A (B : {set gT}) := 'N_A(B | 'P) / 'C_A(B | 'P). Variables G H : {group gT}. Hypothesis sHG: H \subset G. Lemma Aut_restr_perm a : a \in Aut G -> restr_perm H a \in Aut H. Proof. move=> AutGa. case nHa: (a \in 'N(H | 'P)); last by rewrite triv_restr_perm ?nHa ?group1. rewrite inE restr_perm_on; apply/morphicP=> x y Hx Hy /=. by rewrite !restr_permE ?groupM // -(autmE AutGa) morphM ?(subsetP sHG). Qed. Lemma restr_perm_Aut : restr_perm H @* Aut G \subset Aut H. Proof. by apply/subsetP=> a'; case/morphimP=> a _ AutGa ->{a'}; apply: Aut_restr_perm. Qed. Lemma Aut_in_isog : Aut_in (Aut G) H \isog restr_perm H @* Aut G. Proof. rewrite /Aut_in -ker_restr_perm kerE -morphpreIdom -morphimIdom -kerE /=. by rewrite setIA (setIC _ (Aut G)) first_isog_loc ?subsetIr. Qed. Lemma Aut_sub_fullP : reflect (forall h : {morphism H >-> gT}, 'injm h -> h @* H = H -> exists g : {morphism G >-> gT}, [/\ 'injm g, g @* G = G & {in H, g =1 h}]) (Aut_in (Aut G) H \isog Aut H). Proof. rewrite (isog_transl _ Aut_in_isog) /=; set rG := _ @* _. apply: (iffP idP) => [iso_rG h injh hH| AutHinG]. have: aut injh hH \in rG; last case/morphimP=> g nHg AutGg def_g. suffices ->: rG = Aut H by apply: Aut_aut. by apply/eqP; rewrite eqEcard restr_perm_Aut /= (card_isog iso_rG). exists (autm_morphism AutGg); rewrite injm_autm im_autm; split=> // x Hx. by rewrite -(autE injh hH Hx) def_g actpermE actbyE. suffices ->: rG = Aut H by apply: isog_refl. apply/eqP; rewrite eqEsubset restr_perm_Aut /=. apply/subsetP=> h AutHh; have hH := im_autm AutHh. have [g [injg gG eq_gh]] := AutHinG _ (injm_autm AutHh) hH. have [Ng AutGg]: aut injg gG \in 'N(H | 'P) /\ aut injg gG \in Aut G. rewrite Aut_aut !inE; split=> //; apply/subsetP=> x Hx. by rewrite inE /= /aperm autE ?(subsetP sHG) // -hH eq_gh ?mem_morphim. apply/morphimP; exists (aut injg gG) => //; apply: (eq_Aut AutHh) => [|x Hx]. by rewrite (subsetP restr_perm_Aut) // mem_morphim. by rewrite restr_permE //= /aperm autE ?eq_gh ?(subsetP sHG). Qed. End AutIn. Arguments Aut_in {gT} A%_g B%_g. Section InjmAutIn. Variables (gT rT : finGroupType) (D G H : {group gT}) (f : {morphism D >-> rT}). Hypotheses (injf : 'injm f) (sGD : G \subset D) (sHG : H \subset G). Let sHD := subset_trans sHG sGD. Local Notation fGisom := (Aut_isom injf sGD). Local Notation fHisom := (Aut_isom injf sHD). Local Notation inH := (restr_perm H). Local Notation infH := (restr_perm (f @* H)). Lemma astabs_Aut_isom a : a \in Aut G -> (fGisom a \in 'N(f @* H | 'P)) = (a \in 'N(H | 'P)). Proof. move=> AutGa; rewrite !inE sub_morphim_pre // subsetI sHD /= /aperm. rewrite !(sameP setIidPl eqP) !eqEsubset !subsetIl; apply: eq_subset_r => x. rewrite !inE; apply: andb_id2l => Hx; have Gx: x \in G := subsetP sHG x Hx. have Dax: a x \in D by rewrite (subsetP sGD) // Aut_closed. by rewrite Aut_isomE // -!sub1set -morphim_set1 // injmSK ?sub1set. Qed. Lemma isom_restr_perm a : a \in Aut G -> fHisom (inH a) = infH (fGisom a). Proof. move=> AutGa; case nHa: (a \in 'N(H | 'P)); last first. by rewrite !triv_restr_perm ?astabs_Aut_isom ?nHa ?morph1. apply: (eq_Aut (Aut_Aut_isom injf sHD _)) => [|fx Hfx /=]. by rewrite (Aut_restr_perm (morphimS f sHG)) ?Aut_Aut_isom. have [x Dx Hx def_fx] := morphimP Hfx; have Gx := subsetP sHG x Hx. rewrite {1}def_fx Aut_isomE ?(Aut_restr_perm sHG) //. by rewrite !restr_permE ?astabs_Aut_isom // def_fx Aut_isomE. Qed. Lemma restr_perm_isom : isom (inH @* Aut G) (infH @* Aut (f @* G)) fHisom. Proof. apply: sub_isom; rewrite ?restr_perm_Aut ?injm_Aut_isom //=. rewrite -(im_Aut_isom injf sGD) -!morphim_comp. apply: eq_in_morphim; last exact: isom_restr_perm. (* TODO: investigate why rewrite does not match in the same order *) apply/setP=> a; rewrite in_setI [in RHS]in_setI; apply: andb_id2r => AutGa. (* the middle rewrite was rewrite 2!in_setI *) rewrite /= inE andbC inE (Aut_restr_perm sHG) //=. by symmetry; rewrite inE AutGa inE astabs_Aut_isom. Qed. Lemma injm_Aut_sub : Aut_in (Aut (f @* G)) (f @* H) \isog Aut_in (Aut G) H. Proof. do 2!rewrite isog_sym (isog_transl _ (Aut_in_isog _ _)). by rewrite isog_sym (isom_isog _ _ restr_perm_isom) // restr_perm_Aut. Qed. Lemma injm_Aut_full : (Aut_in (Aut (f @* G)) (f @* H) \isog Aut (f @* H)) = (Aut_in (Aut G) H \isog Aut H). Proof. by rewrite (isog_transl _ injm_Aut_sub) (isog_transr _ (injm_Aut injf sHD)). Qed. End InjmAutIn. Section GroupAction. Variables (aT rT : finGroupType) (D : {set aT}) (R : {set rT}). Local Notation actT := (action D rT). Definition is_groupAction (to : actT) := {in D, forall a, actperm to a \in Aut R}. Structure groupAction := GroupAction {gact :> actT; _ : is_groupAction gact}. Definition clone_groupAction to := let: GroupAction _ toA := to return {type of GroupAction for to} -> _ in fun k => k toA : groupAction. End GroupAction. Delimit Scope groupAction_scope with gact. Bind Scope groupAction_scope with groupAction. Arguments is_groupAction {aT rT D%_g} R%_g to%_act. Arguments groupAction {aT rT} D%_g R%_g. Arguments gact {aT rT D%_g R%_g} to%_gact : rename. Notation "[ 'groupAction' 'of' to ]" := (clone_groupAction (@GroupAction _ _ _ _ to)) (format "[ 'groupAction' 'of' to ]") : form_scope. Section GroupActionDefs. Variables (aT rT : finGroupType) (D : {set aT}) (R : {set rT}). Implicit Type A : {set aT}. Implicit Type S : {set rT}. Implicit Type to : groupAction D R. Definition gact_range of groupAction D R := R. Definition gacent to A := 'Fix_(R | to)(D :&: A). Definition acts_on_group A S to := [acts A, on S | to] /\ S \subset R. Coercion actby_cond_group A S to : acts_on_group A S to -> actby_cond A S to := @proj1 _ _. Definition acts_irreducibly A S to := [min S of G | G :!=: 1 & [acts A, on G | to]]. End GroupActionDefs. Arguments gacent {aT rT D%_g R%_g} to%_gact A%_g. Arguments acts_on_group {aT rT D%_g R%_g} A%_g S%_g to%_gact. Arguments acts_irreducibly {aT rT D%_g R%_g} A%_g S%_g to%_gact. Notation "''C_' ( | to ) ( A )" := (gacent to A) : group_scope. Notation "''C_' ( G | to ) ( A )" := (G :&: 'C_(|to)(A)) : group_scope. Notation "''C_' ( | to ) [ a ]" := 'C_(|to)([set a]) : group_scope. Notation "''C_' ( G | to ) [ a ]" := 'C_(G | to)([set a]) : group_scope. Notation "{ 'acts' A , 'on' 'group' G | to }" := (acts_on_group A G to) (format "{ 'acts' A , 'on' 'group' G | to }") : type_scope. Section RawGroupAction. Variables (aT rT : finGroupType) (D : {set aT}) (R : {set rT}). Variable to : groupAction D R. Lemma actperm_Aut : is_groupAction R to. Proof. by case: to. Qed. Lemma im_actperm_Aut : actperm to @* D \subset Aut R. Proof. by apply/subsetP=> _ /morphimP[a _ Da ->]; apply: actperm_Aut. Qed. Lemma gact_out x a : a \in D -> x \notin R -> to x a = x. Proof. by move=> Da Rx; rewrite -actpermE (out_Aut _ Rx) ?actperm_Aut. Qed. Lemma gactM : {in D, forall a, {in R &, {morph to^~ a : x y / x * y}}}. Proof. move=> a Da /= x y; rewrite -!(actpermE to); apply: morphicP x y. by rewrite Aut_morphic ?actperm_Aut. Qed. Lemma actmM a : {in R &, {morph actm to a : x y / x * y}}. Proof. by rewrite /actm; case: ifP => //; apply: gactM. Qed. Canonical act_morphism a := Morphism (actmM a). Lemma morphim_actm : {in D, forall a (S : {set rT}), S \subset R -> actm to a @* S = to^* S a}. Proof. by move=> a Da /= S sSR; rewrite /morphim /= actmEfun ?(setIidPr _). Qed. Variables (a : aT) (A B : {set aT}) (S : {set rT}). Lemma gacentIdom : 'C_(|to)(D :&: A) = 'C_(|to)(A). Proof. by rewrite /gacent setIA setIid. Qed. Lemma gacentIim : 'C_(R | to)(A) = 'C_(|to)(A). Proof. by rewrite setIA setIid. Qed. Lemma gacentS : A \subset B -> 'C_(|to)(B) \subset 'C_(|to)(A). Proof. by move=> sAB; rewrite !(setIS, afixS). Qed. Lemma gacentU : 'C_(|to)(A :|: B) = 'C_(|to)(A) :&: 'C_(|to)(B). Proof. by rewrite -setIIr -afixU -setIUr. Qed. Hypotheses (Da : a \in D) (sAD : A \subset D) (sSR : S \subset R). Lemma gacentE : 'C_(|to)(A) = 'Fix_(R | to)(A). Proof. by rewrite -{2}(setIidPr sAD). Qed. Lemma gacent1E : 'C_(|to)[a] = 'Fix_(R | to)[a]. Proof. by rewrite /gacent [D :&: _](setIidPr _) ?sub1set. Qed. Lemma subgacentE : 'C_(S | to)(A) = 'Fix_(S | to)(A). Proof. by rewrite gacentE setIA (setIidPl sSR). Qed. Lemma subgacent1E : 'C_(S | to)[a] = 'Fix_(S | to)[a]. Proof. by rewrite gacent1E setIA (setIidPl sSR). Qed. End RawGroupAction. Section GroupActionTheory. Variables aT rT : finGroupType. Variables (D : {group aT}) (R : {group rT}) (to : groupAction D R). Implicit Type A B : {set aT}. Implicit Types G H : {group aT}. Implicit Type S : {set rT}. Implicit Types M N : {group rT}. Lemma gact1 : {in D, forall a, to 1 a = 1}. Proof. by move=> a Da; rewrite /= -actmE ?morph1. Qed. Lemma gactV : {in D, forall a, {in R, {morph to^~ a : x / x^-1}}}. Proof. by move=> a Da /= x Rx; move; rewrite -!actmE ?morphV. Qed. Lemma gactX : {in D, forall a n, {in R, {morph to^~ a : x / x ^+ n}}}. Proof. by move=> a Da /= n x Rx; rewrite -!actmE // morphX. Qed. Lemma gactJ : {in D, forall a, {in R &, {morph to^~ a : x y / x ^ y}}}. Proof. by move=> a Da /= x Rx y Ry; rewrite -!actmE // morphJ. Qed. Lemma gactR : {in D, forall a, {in R &, {morph to^~ a : x y / [~ x, y]}}}. Proof. by move=> a Da /= x Rx y Ry; rewrite -!actmE // morphR. Qed. Lemma gact_stable : {acts D, on R | to}. Proof. apply: acts_act; apply/subsetP=> a Da; rewrite !inE Da. apply/subsetP=> x; rewrite inE; apply: contraLR => R'xa. by rewrite -(actKin to Da x) gact_out ?groupV. Qed. Lemma group_set_gacent A : group_set 'C_(|to)(A). Proof. apply/group_setP; split=> [|x y]. by rewrite !inE group1; apply/subsetP=> a /setIP[Da _]; rewrite inE gact1. case/setIP=> Rx /afixP cAx /setIP[Ry /afixP cAy]. rewrite inE groupM //; apply/afixP=> a Aa. by rewrite gactM ?cAx ?cAy //; case/setIP: Aa. Qed. Canonical gacent_group A := Group (group_set_gacent A). Lemma gacent1 : 'C_(|to)(1) = R. Proof. by rewrite /gacent (setIidPr (sub1G _)) afix1 setIT. Qed. Lemma gacent_gen A : A \subset D -> 'C_(|to)(<<A>>) = 'C_(|to)(A). Proof. by move=> sAD; rewrite /gacent ![D :&: _](setIidPr _) ?gen_subG ?afix_gen_in. Qed. Lemma gacentD1 A : 'C_(|to)(A^#) = 'C_(|to)(A). Proof. rewrite -gacentIdom -gacent_gen ?subsetIl // setIDA genD1 ?group1 //. by rewrite gacent_gen ?subsetIl // gacentIdom. Qed. Lemma gacent_cycle a : a \in D -> 'C_(|to)(<[a]>) = 'C_(|to)[a]. Proof. by move=> Da; rewrite gacent_gen ?sub1set. Qed. Lemma gacentY A B : A \subset D -> B \subset D -> 'C_(|to)(A <*> B) = 'C_(|to)(A) :&: 'C_(|to)(B). Proof. by move=> sAD sBD; rewrite gacent_gen ?gacentU // subUset sAD. Qed. Lemma gacentM G H : G \subset D -> H \subset D -> 'C_(|to)(G * H) = 'C_(|to)(G) :&: 'C_(|to)(H). Proof. by move=> sGD sHB; rewrite -gacent_gen ?mul_subG // genM_join gacentY. Qed. Lemma astab1 : 'C(1 | to) = D. Proof. by apply/setP=> x; rewrite ?(inE, sub1set) andb_idr //; move/gact1=> ->. Qed. Lemma astab_range : 'C(R | to) = 'C(setT | to). Proof. apply/eqP; rewrite eqEsubset andbC astabS ?subsetT //=. apply/subsetP=> a cRa; have Da := astab_dom cRa; rewrite !inE Da. apply/subsetP=> x; rewrite -(setUCr R) !inE. by case/orP=> ?; [rewrite (astab_act cRa) | rewrite gact_out]. Qed. Lemma gacentC A S : A \subset D -> S \subset R -> (S \subset 'C_(|to)(A)) = (A \subset 'C(S | to)). Proof. by move=> sAD sSR; rewrite subsetI sSR astabCin // (setIidPr sAD). Qed. Lemma astab_gen S : S \subset R -> 'C(<<S>> | to) = 'C(S | to). Proof. move=> sSR; apply/setP=> a; case Da: (a \in D); last by rewrite !inE Da. by rewrite -!sub1set -!gacentC ?sub1set ?gen_subG. Qed. Lemma astabM M N : M \subset R -> N \subset R -> 'C(M * N | to) = 'C(M | to) :&: 'C(N | to). Proof. move=> sMR sNR; rewrite -astabU -astab_gen ?mul_subG // genM_join. by rewrite astab_gen // subUset sMR. Qed. Lemma astabs1 : 'N(1 | to) = D. Proof. by rewrite astabs_set1 astab1. Qed. Lemma astabs_range : 'N(R | to) = D. Proof. apply/setIidPl; apply/subsetP=> a Da; rewrite inE. by apply/subsetP=> x Rx; rewrite inE gact_stable. Qed. Lemma astabsD1 S : 'N(S^# | to) = 'N(S | to). Proof. case S1: (1 \in S); last first. by rewrite (setDidPl _) // disjoint_sym disjoints_subset sub1set inE S1. apply/eqP; rewrite eqEsubset andbC -{1}astabsIdom -{1}astabs1 setIC astabsD /=. by rewrite -{2}(setD1K S1) -astabsIdom -{1}astabs1 astabsU. Qed. Lemma gacts_range A : A \subset D -> {acts A, on group R | to}. Proof. by move=> sAD; split; rewrite ?astabs_range. Qed. Lemma acts_subnorm_gacent A : A \subset D -> [acts 'N_D(A), on 'C_(| to)(A) | to]. Proof. move=> sAD; rewrite gacentE // actsI ?astabs_range ?subsetIl //. by rewrite -{2}(setIidPr sAD) acts_subnorm_fix. Qed. Lemma acts_subnorm_subgacent A B S : A \subset D -> [acts B, on S | to] -> [acts 'N_B(A), on 'C_(S | to)(A) | to]. Proof. move=> sAD actsB; rewrite actsI //; first by rewrite subIset ?actsB. by rewrite (subset_trans _ (acts_subnorm_gacent sAD)) ?setSI ?(acts_dom actsB). Qed. Lemma acts_gen A S : S \subset R -> [acts A, on S | to] -> [acts A, on <<S>> | to]. Proof. move=> sSR actsA; apply: {A}subset_trans actsA _. apply/subsetP=> a nSa; have Da := astabs_dom nSa; rewrite !inE Da. apply: subset_trans (_ : <<S>> \subset actm to a @*^-1 <<S>>) _. rewrite gen_subG subsetI sSR; apply/subsetP=> x Sx. by rewrite inE /= actmE ?mem_gen // astabs_act. by apply/subsetP=> x /[!inE]; case/andP=> Rx; rewrite /= actmE. Qed. Lemma acts_joing A M N : M \subset R -> N \subset R -> [acts A, on M | to] -> [acts A, on N | to] -> [acts A, on M <*> N | to]. Proof. by move=> sMR sNR nMA nNA; rewrite acts_gen ?actsU // subUset sMR. Qed. Lemma injm_actm a : 'injm (actm to a). Proof. apply/injmP=> x y Rx Ry; rewrite /= /actm; case: ifP => Da //. exact: act_inj. Qed. Lemma im_actm a : actm to a @* R = R. Proof. apply/eqP; rewrite eqEcard (card_injm (injm_actm a)) // leqnn andbT. apply/subsetP=> _ /morphimP[x Rx _ ->] /=. by rewrite /actm; case: ifP => // Da; rewrite gact_stable. Qed. Lemma acts_char G M : G \subset D -> M \char R -> [acts G, on M | to]. Proof. move=> sGD /charP[sMR charM]. apply/subsetP=> a Ga; have Da := subsetP sGD a Ga; rewrite !inE Da. apply/subsetP=> x Mx; have Rx := subsetP sMR x Mx. by rewrite inE -(charM _ (injm_actm a) (im_actm a)) -actmE // mem_morphim. Qed. Lemma gacts_char G M : G \subset D -> M \char R -> {acts G, on group M | to}. (* TODO: investigate why rewrite does not match in the same order *) Proof. by move=> sGD charM; split; rewrite ?acts_char// char_sub. Qed. (* was ending with rewrite (acts_char, char_sub)// *) Section Restrict. Variables (A : {group aT}) (sAD : A \subset D). Lemma ract_is_groupAction : is_groupAction R (to \ sAD). Proof. by move=> a Aa /=; rewrite ractpermE actperm_Aut ?(subsetP sAD). Qed. Canonical ract_groupAction := GroupAction ract_is_groupAction. Lemma gacent_ract B : 'C_(|ract_groupAction)(B) = 'C_(|to)(A :&: B). Proof. by rewrite /gacent afix_ract setIA (setIidPr sAD). Qed. End Restrict. Section ActBy. Variables (A : {group aT}) (G : {group rT}) (nGAg : {acts A, on group G | to}). Lemma actby_is_groupAction : is_groupAction G <[nGAg]>. Proof. move=> a Aa; rewrite /= inE; apply/andP; split. apply/subsetP=> x; apply: contraR => Gx. by rewrite actpermE /= /actby (negbTE Gx). apply/morphicP=> x y Gx Gy; rewrite !actpermE /= /actby Aa groupM ?Gx ?Gy //=. by case nGAg; move/acts_dom; do 2!move/subsetP=> ?; rewrite gactM; auto. Qed. Canonical actby_groupAction := GroupAction actby_is_groupAction. Lemma gacent_actby B : 'C_(|actby_groupAction)(B) = 'C_(G | to)(A :&: B). Proof. rewrite /gacent afix_actby !setIA setIid setIUr setICr set0U. by have [nAG sGR] := nGAg; rewrite (setIidPr (acts_dom nAG)) (setIidPl sGR). Qed. End ActBy. Section Quotient. Variable H : {group rT}. Lemma acts_qact_dom_norm : {acts qact_dom to H, on 'N(H) | to}. Proof. move=> a HDa /= x; rewrite {2}(('N(H) =P to^~ a @^-1: 'N(H)) _) ?inE {x}//. rewrite eqEcard (card_preimset _ (act_inj _ _)) leqnn andbT. apply/subsetP=> x Nx; rewrite inE; move/(astabs_act (H :* x)): HDa. rewrite mem_rcosets mulSGid ?normG // Nx => /rcosetsP[y Ny defHy]. suffices: to x a \in H :* y by apply: subsetP; rewrite mul_subG ?sub1set ?normG. by rewrite -defHy; apply: imset_f; apply: rcoset_refl. Qed. Lemma qact_is_groupAction : is_groupAction (R / H) (to / H). Proof. move=> a HDa /=; have Da := astabs_dom HDa. rewrite inE; apply/andP; split. apply/subsetP=> Hx /=; case: (cosetP Hx) => x Nx ->{Hx}. apply: contraR => R'Hx; rewrite actpermE qactE // gact_out //. by apply: contra R'Hx; apply: mem_morphim. apply/morphicP=> Hx Hy; rewrite !actpermE. case/morphimP=> x Nx Gx ->{Hx}; case/morphimP=> y Ny Gy ->{Hy}. by rewrite -morphM ?qactE ?groupM ?gactM // morphM ?acts_qact_dom_norm. Qed. Canonical quotient_groupAction := GroupAction qact_is_groupAction. Lemma qact_domE : H \subset R -> qact_dom to H = 'N(H | to). Proof. move=> sHR; apply/setP=> a; apply/idP/idP=> nHa; have Da := astabs_dom nHa. rewrite !inE Da; apply/subsetP=> x Hx; rewrite inE -(rcoset1 H). have /rcosetsP[y Ny defHy]: to^~ a @: H \in rcosets H 'N(H). by rewrite (astabs_act _ nHa); apply/rcosetsP; exists 1; rewrite ?mulg1. by rewrite (rcoset_eqP (_ : 1 \in H :* y)) -defHy -1?(gact1 Da) mem_setact. rewrite !inE Da; apply/subsetP=> Hx /[1!inE] /rcosetsP[x Nx ->{Hx}]. apply/imsetP; exists (to x a). case Rx: (x \in R); last by rewrite gact_out ?Rx. rewrite inE; apply/subsetP=> _ /imsetP[y Hy ->]. rewrite -(actKVin to Da y) -gactJ // ?(subsetP sHR, astabs_act, groupV) //. by rewrite memJ_norm // astabs_act ?groupV. apply/eqP; rewrite rcosetE eqEcard. rewrite (card_imset _ (act_inj _ _)) !card_rcoset leqnn andbT. apply/subsetP=> _ /imsetP[y Hxy ->]; rewrite !mem_rcoset in Hxy *. have Rxy := subsetP sHR _ Hxy; rewrite -(mulgKV x y). case Rx: (x \in R); last by rewrite !gact_out ?mulgK // 1?groupMl ?Rx. by rewrite -gactV // -gactM 1?groupMr ?groupV // mulgK astabs_act. Qed. End Quotient. Section Mod. Variable H : {group aT}. Lemma modact_is_groupAction : is_groupAction 'C_(|to)(H) (to %% H). Proof. move=> Ha /morphimP[a Na Da ->]; have NDa: a \in 'N_D(H) by apply/setIP. rewrite inE; apply/andP; split. apply/subsetP=> x; rewrite 2!inE andbC actpermE /= modactEcond //. by apply: contraR; case: ifP => // E Rx; rewrite gact_out. apply/morphicP=> x y /setIP[Rx cHx] /setIP[Ry cHy]. rewrite /= !actpermE /= !modactE ?gactM //. suffices: x * y \in 'C_(|to)(H) by case/setIP. by rewrite groupM //; apply/setIP. Qed. Canonical mod_groupAction := GroupAction modact_is_groupAction. Lemma modgactE x a : H \subset 'C(R | to) -> a \in 'N_D(H) -> (to %% H)%act x (coset H a) = to x a. Proof. move=> cRH NDa /=; have [Da Na] := setIP NDa. have [Rx | notRx] := boolP (x \in R). by rewrite modactE //; apply/afixP=> b /setIP[_ /(subsetP cRH)/astab_act->]. rewrite gact_out //= /modact; case: ifP => // _; rewrite gact_out //. suffices: a \in D :&: coset H a by case/mem_repr/setIP. by rewrite inE Da val_coset // rcoset_refl. Qed. Lemma gacent_mod G M : H \subset 'C(M | to) -> G \subset 'N(H) -> 'C_(M | mod_groupAction)(G / H) = 'C_(M | to)(G). Proof. move=> cMH nHG; rewrite -gacentIdom gacentE ?subsetIl // setICA. have sHD: H \subset D by rewrite (subset_trans cMH) ?subsetIl. rewrite -quotientGI // afix_mod ?setIS // setICA -gacentIim (setIC R) -setIA. rewrite -gacentE ?subsetIl // gacentIdom setICA (setIidPr _) //. by rewrite gacentC // ?(subset_trans cMH) ?astabS ?subsetIl // setICA subsetIl. Qed. Lemma acts_irr_mod G M : H \subset 'C(M | to) -> G \subset 'N(H) -> acts_irreducibly G M to -> acts_irreducibly (G / H) M mod_groupAction. Proof. move=> cMH nHG /mingroupP[/andP[ntM nMG] minM]. apply/mingroupP; rewrite ntM astabs_mod ?quotientS //; split=> // L modL ntL. have cLH: H \subset 'C(L | to) by rewrite (subset_trans cMH) ?astabS //. apply: minM => //; case/andP: modL => ->; rewrite astabs_mod ?quotientSGK //. by rewrite (subset_trans cLH) ?astab_sub. Qed. End Mod. Lemma modact_coset_astab x a : a \in D -> (to %% 'C(R | to))%act x (coset _ a) = to x a. Proof. move=> Da; apply: modgactE => {x}//. rewrite !inE Da; apply/subsetP=> _ /imsetP[c Cc ->]. have Dc := astab_dom Cc; rewrite !inE groupJ //. apply/subsetP=> x Rx; rewrite inE conjgE !actMin ?groupM ?groupV //. by rewrite (astab_act Cc) ?actKVin // gact_stable ?groupV. Qed. Lemma acts_irr_mod_astab G M : acts_irreducibly G M to -> acts_irreducibly (G / 'C_G(M | to)) M (mod_groupAction _). Proof. move=> irrG; have /andP[_ nMG] := mingroupp irrG. apply: acts_irr_mod irrG; first exact: subsetIr. by rewrite normsI ?normG // (subset_trans nMG) // astab_norm. Qed. Section CompAct. Variables (gT : finGroupType) (G : {group gT}) (f : {morphism G >-> aT}). Lemma comp_is_groupAction : is_groupAction R (comp_action to f). Proof. move=> a /morphpreP[Ba Dfa]; apply: etrans (actperm_Aut to Dfa). by congr (_ \in Aut R); apply/permP=> x; rewrite !actpermE. Qed. Canonical comp_groupAction := GroupAction comp_is_groupAction. Lemma gacent_comp U : 'C_(|comp_groupAction)(U) = 'C_(|to)(f @* U). Proof. rewrite /gacent afix_comp ?subIset ?subxx //. by rewrite -(setIC U) (setIC D) morphim_setIpre. Qed. End CompAct. End GroupActionTheory. Notation "''C_' ( | to ) ( A )" := (gacent_group to A) : Group_scope. Notation "''C_' ( G | to ) ( A )" := (setI_group G 'C_(|to)(A)) : Group_scope. Notation "''C_' ( | to ) [ a ]" := (gacent_group to [set a%g]) : Group_scope. Notation "''C_' ( G | to ) [ a ]" := (setI_group G 'C_(|to)[a]) : Group_scope. Notation "to \ sAD" := (ract_groupAction to sAD) : groupAction_scope. Notation "<[ nGA ] >" := (actby_groupAction nGA) : groupAction_scope. Notation "to / H" := (quotient_groupAction to H) : groupAction_scope. Notation "to %% H" := (mod_groupAction to H) : groupAction_scope. Notation "to \o f" := (comp_groupAction to f) : groupAction_scope. (* Operator group isomorphism. *) Section MorphAction. Variables (aT1 aT2 : finGroupType) (rT1 rT2 : finType). Variables (D1 : {group aT1}) (D2 : {group aT2}). Variables (to1 : action D1 rT1) (to2 : action D2 rT2). Variables (A : {set aT1}) (R S : {set rT1}). Variables (h : rT1 -> rT2) (f : {morphism D1 >-> aT2}). Hypotheses (actsDR : {acts D1, on R | to1}) (injh : {in R &, injective h}). Hypothesis defD2 : f @* D1 = D2. Hypotheses (sSR : S \subset R) (sAD1 : A \subset D1). Hypothesis hfJ : {in S & D1, morph_act to1 to2 h f}. Lemma morph_astabs : f @* 'N(S | to1) = 'N(h @: S | to2). Proof. apply/setP=> fx; apply/morphimP/idP=> [[x D1x nSx ->] | nSx]. rewrite 2!inE -{1}defD2 mem_morphim //=; apply/subsetP=> _ /imsetP[u Su ->]. by rewrite inE -hfJ ?imset_f // (astabs_act _ nSx). have [|x D1x _ def_fx] := morphimP (_ : fx \in f @* D1). by rewrite defD2 (astabs_dom nSx). exists x => //; rewrite !inE D1x; apply/subsetP=> u Su. have /imsetP[u' Su' /injh def_u']: h (to1 u x) \in h @: S. by rewrite hfJ // -def_fx (astabs_act _ nSx) imset_f. by rewrite inE def_u' ?actsDR ?(subsetP sSR). Qed. Lemma morph_astab : f @* 'C(S | to1) = 'C(h @: S | to2). Proof. apply/setP=> fx; apply/morphimP/idP=> [[x D1x cSx ->] | cSx]. rewrite 2!inE -{1}defD2 mem_morphim //=; apply/subsetP=> _ /imsetP[u Su ->]. by rewrite inE -hfJ // (astab_act cSx). have [|x D1x _ def_fx] := morphimP (_ : fx \in f @* D1). by rewrite defD2 (astab_dom cSx). exists x => //; rewrite !inE D1x; apply/subsetP=> u Su. rewrite inE -(inj_in_eq injh) ?actsDR ?(subsetP sSR) ?hfJ //. by rewrite -def_fx (astab_act cSx) ?imset_f. Qed. Lemma morph_afix : h @: 'Fix_(S | to1)(A) = 'Fix_(h @: S | to2)(f @* A). Proof. apply/setP=> hu; apply/imsetP/setIP=> [[u /setIP[Su cAu] ->]|]. split; first by rewrite imset_f. by apply/afixP=> _ /morphimP[x D1x Ax ->]; rewrite -hfJ ?(afixP cAu). case=> /imsetP[u Su ->] /afixP c_hu_fA; exists u; rewrite // inE Su. apply/afixP=> x Ax; have Dx := subsetP sAD1 x Ax. by apply: injh; rewrite ?actsDR ?(subsetP sSR) ?hfJ // c_hu_fA ?mem_morphim. Qed. End MorphAction. Section MorphGroupAction. Variables (aT1 aT2 rT1 rT2 : finGroupType). Variables (D1 : {group aT1}) (D2 : {group aT2}). Variables (R1 : {group rT1}) (R2 : {group rT2}). Variables (to1 : groupAction D1 R1) (to2 : groupAction D2 R2). Variables (h : {morphism R1 >-> rT2}) (f : {morphism D1 >-> aT2}). Hypotheses (iso_h : isom R1 R2 h) (iso_f : isom D1 D2 f). Hypothesis hfJ : {in R1 & D1, morph_act to1 to2 h f}. Implicit Types (A : {set aT1}) (S : {set rT1}) (M : {group rT1}). Lemma morph_gastabs S : S \subset R1 -> f @* 'N(S | to1) = 'N(h @* S | to2). Proof. have [[_ defD2] [injh _]] := (isomP iso_f, isomP iso_h). move=> sSR1; rewrite (morphimEsub _ sSR1). apply: (morph_astabs (gact_stable to1) (injmP injh)) => // u x. by move/(subsetP sSR1); apply: hfJ. Qed. Lemma morph_gastab S : S \subset R1 -> f @* 'C(S | to1) = 'C(h @* S | to2). Proof. have [[_ defD2] [injh _]] := (isomP iso_f, isomP iso_h). move=> sSR1; rewrite (morphimEsub _ sSR1). apply: (morph_astab (gact_stable to1) (injmP injh)) => // u x. by move/(subsetP sSR1); apply: hfJ. Qed. Lemma morph_gacent A : A \subset D1 -> h @* 'C_(|to1)(A) = 'C_(|to2)(f @* A). Proof. have [[_ defD2] [injh defR2]] := (isomP iso_f, isomP iso_h). move=> sAD1; rewrite !gacentE //; last by rewrite -defD2 morphimS. rewrite morphimEsub ?subsetIl // -{1}defR2 morphimEdom. exact: (morph_afix (gact_stable to1) (injmP injh)). Qed. Lemma morph_gact_irr A M : A \subset D1 -> M \subset R1 -> acts_irreducibly (f @* A) (h @* M) to2 = acts_irreducibly A M to1. Proof. move=> sAD1 sMR1. have [[injf defD2] [injh defR2]] := (isomP iso_f, isomP iso_h). have h_eq1 := morphim_injm_eq1 injh. apply/mingroupP/mingroupP=> [] [/andP[ntM actAM] minM]. split=> [|U]; first by rewrite -h_eq1 // ntM -(injmSK injf) ?morph_gastabs. case/andP=> ntU acts_fAU sUM; have sUR1 := subset_trans sUM sMR1. apply: (injm_morphim_inj injh) => //; apply: minM; last exact: morphimS. by rewrite h_eq1 // ntU -morph_gastabs ?morphimS. split=> [|U]; first by rewrite h_eq1 // ntM -morph_gastabs ?morphimS. case/andP=> ntU acts_fAU sUhM. have sUhR1 := subset_trans sUhM (morphimS h sMR1). have sU'M: h @*^-1 U \subset M by rewrite sub_morphpre_injm. rewrite /= -(minM _ _ sU'M) ?morphpreK // -h_eq1 ?subsetIl // -(injmSK injf) //. by rewrite morph_gastabs ?(subset_trans sU'M) // morphpreK ?ntU. Qed. End MorphGroupAction. (* Conjugation and right translation actions. *) Section InternalActionDefs. Variable gT : finGroupType. Implicit Type A : {set gT}. Implicit Type G : {group gT}. (* This is not a Canonical action because it is seldom used, and it would *) (* cause too many spurious matches (any group product would be viewed as an *) (* action!). *) Definition mulgr_action := TotalAction (@mulg1 gT) (@mulgA gT). Canonical conjg_action := TotalAction (@conjg1 gT) (@conjgM gT). Lemma conjg_is_groupAction : is_groupAction setT conjg_action. Proof. move=> a _; rewrite inE; apply/andP; split; first by apply/subsetP=> x /[1!inE]. by apply/morphicP=> x y _ _; rewrite !actpermE /= conjMg. Qed. Canonical conjg_groupAction := GroupAction conjg_is_groupAction. Lemma rcoset_is_action : is_action setT (@rcoset gT). Proof. by apply: is_total_action => [A|A x y]; rewrite !rcosetE (mulg1, rcosetM). Qed. Canonical rcoset_action := Action rcoset_is_action. Canonical conjsg_action := TotalAction (@conjsg1 gT) (@conjsgM gT). Lemma conjG_is_action : is_action setT (@conjG_group gT). Proof. apply: is_total_action => [G | G x y]; apply: val_inj; rewrite /= ?act1 //. exact: actM. Qed. Definition conjG_action := Action conjG_is_action. End InternalActionDefs. Notation "'R" := (@mulgr_action _) : action_scope. Notation "'Rs" := (@rcoset_action _) : action_scope. Notation "'J" := (@conjg_action _) : action_scope. Notation "'J" := (@conjg_groupAction _) : groupAction_scope. Notation "'Js" := (@conjsg_action _) : action_scope. Notation "'JG" := (@conjG_action _) : action_scope. Notation "'Q" := ('J / _)%act : action_scope. Notation "'Q" := ('J / _)%gact : groupAction_scope. Section InternalGroupAction. Variable gT : finGroupType. Implicit Types A B : {set gT}. Implicit Types G H : {group gT}. Implicit Type x : gT. (* Various identities for actions on groups. *) Lemma orbitR G x : orbit 'R G x = x *: G. Proof. by rewrite -lcosetE. Qed. Lemma astab1R x : 'C[x | 'R] = 1. Proof. apply/trivgP/subsetP=> y cxy. by rewrite -(mulKg x y) [x * y](astab1P cxy) mulVg set11. Qed. Lemma astabR G : 'C(G | 'R) = 1. Proof. apply/trivgP/subsetP=> x cGx. by rewrite -(mul1g x) [1 * x](astabP cGx) group1. Qed. Lemma astabsR G : 'N(G | 'R) = G. Proof. apply/setP=> x; rewrite !inE -setactVin ?inE //=. by rewrite -groupV -{1 3}(mulg1 G) rcoset_sym -sub1set -mulGS -!rcosetE. Qed. Lemma atransR G : [transitive G, on G | 'R]. Proof. by rewrite /atrans -{1}(mul1g G) -orbitR imset_f. Qed. Lemma faithfulR G : [faithful G, on G | 'R]. Proof. by rewrite /faithful astabR subsetIr. Qed. Definition Cayley_repr G := actperm <[atrans_acts (atransR G)]>. Theorem Cayley_isom G : isom G (Cayley_repr G @* G) (Cayley_repr G). Proof. exact: faithful_isom (faithfulR G). Qed. Theorem Cayley_isog G : G \isog Cayley_repr G @* G. Proof. exact: isom_isog (Cayley_isom G). Qed. Lemma orbitJ G x : orbit 'J G x = x ^: G. Proof. by []. Qed. Lemma afixJ A : 'Fix_('J)(A) = 'C(A). Proof. apply/setP=> x; apply/afixP/centP=> cAx y Ay /=. by rewrite /commute conjgC cAx. by rewrite conjgE cAx ?mulKg. Qed. Lemma astabJ A : 'C(A |'J) = 'C(A). Proof. apply/setP=> x; apply/astabP/centP=> cAx y Ay /=. by apply: esym; rewrite conjgC cAx. by rewrite conjgE -cAx ?mulKg. Qed. Lemma astab1J x : 'C[x |'J] = 'C[x]. Proof. by rewrite astabJ cent_set1. Qed. Lemma astabsJ A : 'N(A | 'J) = 'N(A). Proof. by apply/setP=> x; rewrite -2!groupV !inE -conjg_preim -sub_conjg. Qed. Lemma setactJ A x : 'J^*%act A x = A :^ x. Proof. by []. Qed. Lemma gacentJ A : 'C_(|'J)(A) = 'C(A). Proof. by rewrite gacentE ?setTI ?subsetT ?afixJ. Qed. Lemma orbitRs G A : orbit 'Rs G A = rcosets A G. Proof. by []. Qed. Lemma sub_afixRs_norms G x A : (G :* x \in 'Fix_('Rs)(A)) = (A \subset G :^ x). Proof. rewrite inE /=; apply: eq_subset_r => a. rewrite inE rcosetE -(can2_eq (rcosetKV x) (rcosetK x)) -!rcosetM. rewrite eqEcard card_rcoset leqnn andbT mulgA (conjgCV x) mulgK. by rewrite -{2 3}(mulGid G) mulGS sub1set -mem_conjg. Qed. Lemma sub_afixRs_norm G x : (G :* x \in 'Fix_('Rs)(G)) = (x \in 'N(G)). Proof. by rewrite sub_afixRs_norms -groupV inE sub_conjgV. Qed. Lemma afixRs_rcosets A G : 'Fix_(rcosets G A | 'Rs)(G) = rcosets G 'N_A(G). Proof. apply/setP=> Gx; apply/setIP/rcosetsP=> [[/rcosetsP[x Ax ->]]|[x]]. by rewrite sub_afixRs_norm => Nx; exists x; rewrite // inE Ax. by case/setIP=> Ax Nx ->; rewrite -{1}rcosetE imset_f // sub_afixRs_norm. Qed. Lemma astab1Rs G : 'C[G : {set gT} | 'Rs] = G. Proof. apply/setP=> x. by apply/astab1P/idP=> /= [<- | Gx]; rewrite rcosetE ?rcoset_refl ?rcoset_id. Qed. Lemma actsRs_rcosets H G : [acts G, on rcosets H G | 'Rs]. Proof. by rewrite -orbitRs acts_orbit ?subsetT. Qed. Lemma transRs_rcosets H G : [transitive G, on rcosets H G | 'Rs]. Proof. by rewrite -orbitRs atrans_orbit. Qed. (* This is the second part of Aschbacher (5.7) *) Lemma astabRs_rcosets H G : 'C(rcosets H G | 'Rs) = gcore H G. Proof. have transGH := transRs_rcosets H G. by rewrite (astab_trans_gcore transGH (orbit_refl _ G _)) astab1Rs. Qed. Lemma orbitJs G A : orbit 'Js G A = A :^: G. Proof. by []. Qed. Lemma astab1Js A : 'C[A | 'Js] = 'N(A). Proof. by apply/setP=> x; apply/astab1P/normP. Qed. Lemma card_conjugates A G : #|A :^: G| = #|G : 'N_G(A)|. Proof. by rewrite card_orbit astab1Js. Qed. Lemma afixJG G A : (G \in 'Fix_('JG)(A)) = (A \subset 'N(G)). Proof. by apply/afixP/normsP=> nG x Ax; apply/eqP; move/eqP: (nG x Ax). Qed. Lemma astab1JG G : 'C[G | 'JG] = 'N(G). Proof. by apply/setP=> x; apply/astab1P/normP=> [/congr_group | /group_inj]. Qed. Lemma dom_qactJ H : qact_dom 'J H = 'N(H). Proof. by rewrite qact_domE ?subsetT ?astabsJ. Qed. Lemma qactJ H (Hy : coset_of H) x : 'Q%act Hy x = if x \in 'N(H) then Hy ^ coset H x else Hy. Proof. case: (cosetP Hy) => y Ny ->{Hy}. by rewrite qactEcond // dom_qactJ; case Nx: (x \in 'N(H)); rewrite ?morphJ. Qed. Lemma actsQ A B H : A \subset 'N(H) -> A \subset 'N(B) -> [acts A, on B / H | 'Q]. Proof. by move=> nHA nBA; rewrite acts_quotient // subsetI dom_qactJ nHA astabsJ. Qed. Lemma astabsQ G H : H <| G -> 'N(G / H | 'Q) = 'N(H) :&: 'N(G). Proof. by move=> nsHG; rewrite astabs_quotient // dom_qactJ astabsJ. Qed. Lemma astabQ H Abar : 'C(Abar |'Q) = coset H @*^-1 'C(Abar). Proof. apply/setP=> x; rewrite inE /= dom_qactJ morphpreE in_setI /=. apply: andb_id2l => Nx; rewrite !inE -sub1set centsC cent_set1. apply: eq_subset_r => {Abar} Hy; rewrite inE qactJ Nx (sameP eqP conjg_fixP). by rewrite (sameP cent1P eqP) (sameP commgP eqP). Qed. Lemma sub_astabQ A H Bbar : (A \subset 'C(Bbar | 'Q)) = (A \subset 'N(H)) && (A / H \subset 'C(Bbar)). Proof. rewrite astabQ -morphpreIdom subsetI; apply: andb_id2l => nHA. by rewrite -sub_quotient_pre. Qed. Lemma sub_astabQR A B H : A \subset 'N(H) -> B \subset 'N(H) -> (A \subset 'C(B / H | 'Q)) = ([~: A, B] \subset H). Proof. move=> nHA nHB; rewrite sub_astabQ nHA /= (sameP commG1P eqP). by rewrite eqEsubset sub1G andbT -quotientR // quotient_sub1 // comm_subG. Qed. Lemma astabQR A H : A \subset 'N(H) -> 'C(A / H | 'Q) = [set x in 'N(H) | [~: [set x], A] \subset H]. Proof. move=> nHA; apply/setP=> x; rewrite astabQ -morphpreIdom 2!inE -astabQ. by case nHx: (x \in _); rewrite //= -sub1set sub_astabQR ?sub1set. Qed. Lemma quotient_astabQ H Abar : 'C(Abar | 'Q) / H = 'C(Abar). Proof. by rewrite astabQ cosetpreK. Qed. Lemma conj_astabQ A H x : x \in 'N(H) -> 'C(A / H | 'Q) :^ x = 'C(A :^ x / H | 'Q). Proof. move=> nHx; apply/setP=> y; rewrite !astabQ mem_conjg !in_setI -mem_conjg. rewrite -normJ (normP nHx) quotientJ //; apply/andb_id2l => nHy. by rewrite !inE centJ morphJ ?groupV ?morphV // -mem_conjg. Qed. Section CardClass. Variable G : {group gT}. Lemma index_cent1 x : #|G : 'C_G[x]| = #|x ^: G|. Proof. by rewrite -astab1J -card_orbit. Qed. Lemma classes_partition : partition (classes G) G. Proof. by apply: orbit_partition; apply/actsP=> x Gx y; apply: groupJr. Qed. Lemma sum_card_class : \sum_(C in classes G) #|C| = #|G|. Proof. by apply: acts_sum_card_orbit; apply/actsP=> x Gx y; apply: groupJr. Qed. Lemma class_formula : \sum_(C in classes G) #|G : 'C_G[repr C]| = #|G|. Proof. rewrite -sum_card_class; apply: eq_bigr => _ /imsetP[x Gx ->]. have: x \in x ^: G by rewrite -{1}(conjg1 x) imset_f. by case/mem_repr/imsetP=> y Gy ->; rewrite index_cent1 classGidl. Qed. Lemma abelian_classP : reflect {in G, forall x, x ^: G = [set x]} (abelian G). Proof. rewrite /abelian -astabJ astabC. by apply: (iffP subsetP) => cGG x Gx; apply/orbit1P; apply: cGG. Qed. Lemma card_classes_abelian : abelian G = (#|classes G| == #|G|). Proof. have cGgt0 C: C \in classes G -> 1 <= #|C| ?= iff (#|C| == 1)%N. by case/imsetP=> x _ ->; rewrite eq_sym -index_cent1. rewrite -sum_card_class -sum1_card (leqif_sum cGgt0). apply/abelian_classP/forall_inP=> [cGG _ /imsetP[x Gx ->]| cGG x Gx]. by rewrite cGG ?cards1. apply/esym/eqP; rewrite eqEcard sub1set cards1 class_refl leq_eqVlt cGG //. exact: imset_f. Qed. End CardClass. End InternalGroupAction. Lemma gacentQ (gT : finGroupType) (H : {group gT}) (A : {set gT}) : 'C_(|'Q)(A) = 'C(A / H). Proof. apply/setP=> Hx; case: (cosetP Hx) => x Nx ->{Hx}. rewrite -sub_cent1 -astab1J astabC sub1set -(quotientInorm H A). have defD: qact_dom 'J H = 'N(H) by rewrite qact_domE ?subsetT ?astabsJ. rewrite !(inE, mem_quotient) //= defD setIC. apply/subsetP/subsetP=> [cAx _ /morphimP[a Na Aa ->] | cAx a Aa]. by move/cAx: Aa; rewrite !inE qactE ?defD ?morphJ. have [_ Na] := setIP Aa; move/implyP: (cAx (coset H a)); rewrite mem_morphim //. by rewrite !inE qactE ?defD ?morphJ. Qed. Section AutAct. Variable (gT : finGroupType) (G : {set gT}). Definition autact := act ('P \ subsetT (Aut G)). Canonical aut_action := [action of autact]. Lemma autactK a : actperm aut_action a = a. Proof. by apply/permP=> x; rewrite permE. Qed. Lemma autact_is_groupAction : is_groupAction G aut_action. Proof. by move=> a Aa /=; rewrite autactK. Qed. Canonical aut_groupAction := GroupAction autact_is_groupAction. Section perm_prime_orbit. Variable (T : finType) (c : {perm T}). Hypothesis Tp : prime #|T|. Hypothesis cc : #[c]%g = #|T|. Let cp : prime #[c]%g. Proof. by rewrite cc. Qed. Lemma perm_prime_atrans : [transitive <[c]>, on setT | 'P]. Proof. apply/imsetP; suff /existsP[x] : [exists x, ~~ (#|orbit 'P <[c]> x| < #[c])]. move=> oxT; suff /eqP orbit_x : orbit 'P <[c]> x == setT by exists x. by rewrite eqEcard subsetT cardsT -cc leqNgt. apply/forallP => olT; have o1 x : #|orbit 'P <[c]> x| == 1%N. by case/primeP: cp => _ /(_ _ (dvdn_orbit 'P _ x))/orP[]//; rewrite ltn_eqF. suff c1 : c = 1%g by rewrite c1 ?order1 in (cp). apply/permP => x; rewrite perm1; apply/set1P. by rewrite -(card_orbit1 (eqP (o1 _))) (mem_orbit 'P) ?cycle_id. Qed. Lemma perm_prime_orbit x : orbit 'P <[c]> x = [set: T]. Proof. by apply: atransP => //; apply: perm_prime_atrans. Qed. Lemma perm_prime_astab x : 'C_<[c]>[x | 'P]%g = 1%g. Proof. by apply/card1_trivg/eqP; rewrite -(@eqn_pmul2l #|orbit 'P <[c]> x|) ?card_orbit_stab ?perm_prime_orbit ?cardsT ?muln1 ?prime_gt0// -cc. Qed. End perm_prime_orbit. End AutAct. Arguments autact {gT} G%_g. Arguments aut_action {gT} G%_g. Arguments aut_groupAction {gT} G%_g. Notation "[ 'Aut' G ]" := (aut_action G) : action_scope. Notation "[ 'Aut' G ]" := (aut_groupAction G) : groupAction_scope.
IntegralEqImproper.lean
/- Copyright (c) 2021 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Bhavik Mehta -/ import Mathlib.Analysis.Calculus.Deriv.Support import Mathlib.Analysis.SpecialFunctions.Pow.Deriv import Mathlib.MeasureTheory.Function.JacobianOneDim import Mathlib.MeasureTheory.Integral.IntervalIntegral.IntegrationByParts import Mathlib.MeasureTheory.Measure.Haar.NormedSpace import Mathlib.MeasureTheory.Measure.Haar.Unique /-! # Links between an integral and its "improper" version In its current state, mathlib only knows how to talk about definite ("proper") integrals, in the sense that it treats integrals over `[x, +∞)` the same as it treats integrals over `[y, z]`. For example, the integral over `[1, +∞)` is **not** defined to be the limit of the integral over `[1, x]` as `x` tends to `+∞`, which is known as an **improper integral**. Indeed, the "proper" definition is stronger than the "improper" one. The usual counterexample is `x ↦ sin(x)/x`, which has an improper integral over `[1, +∞)` but no definite integral. Although definite integrals have better properties, they are hardly usable when it comes to computing integrals on unbounded sets, which is much easier using limits. Thus, in this file, we prove various ways of studying the proper integral by studying the improper one. ## Definitions The main definition of this file is `MeasureTheory.AECover`. It is a rather technical definition whose sole purpose is generalizing and factoring proofs. Given an index type `ι`, a countably generated filter `l` over `ι`, and an `ι`-indexed family `φ` of subsets of a measurable space `α` equipped with a measure `μ`, one should think of a hypothesis `hφ : MeasureTheory.AECover μ l φ` as a sufficient condition for being able to interpret `∫ x, f x ∂μ` (if it exists) as the limit of `∫ x in φ i, f x ∂μ` as `i` tends to `l`. When using this definition with a measure restricted to a set `s`, which happens fairly often, one should not try too hard to use a `MeasureTheory.AECover` of subsets of `s`, as it often makes proofs more complicated than necessary. See for example the proof of `MeasureTheory.integrableOn_Iic_of_intervalIntegral_norm_tendsto` where we use `(fun x ↦ oi x)` as a `MeasureTheory.AECover` w.r.t. `μ.restrict (Iic b)`, instead of using `(fun x ↦ Ioc x b)`. ## Main statements - `MeasureTheory.AECover.lintegral_tendsto_of_countably_generated` : if `φ` is a `MeasureTheory.AECover μ l`, where `l` is a countably generated filter, and if `f` is a measurable `ENNReal`-valued function, then `∫⁻ x in φ n, f x ∂μ` tends to `∫⁻ x, f x ∂μ` as `n` tends to `l` - `MeasureTheory.AECover.integrable_of_integral_norm_tendsto` : if `φ` is a `MeasureTheory.AECover μ l`, where `l` is a countably generated filter, if `f` is measurable and integrable on each `φ n`, and if `∫ x in φ n, ‖f x‖ ∂μ` tends to some `I : ℝ` as n tends to `l`, then `f` is integrable - `MeasureTheory.AECover.integral_tendsto_of_countably_generated` : if `φ` is a `MeasureTheory.AECover μ l`, where `l` is a countably generated filter, and if `f` is measurable and integrable (globally), then `∫ x in φ n, f x ∂μ` tends to `∫ x, f x ∂μ` as `n` tends to `+∞`. We then specialize these lemmas to various use cases involving intervals, which are frequent in analysis. In particular, - `MeasureTheory.integral_Ioi_of_hasDerivAt_of_tendsto` is a version of FTC-2 on the interval `(a, +∞)`, giving the formula `∫ x in (a, +∞), g' x = l - g a` if `g'` is integrable and `g` tends to `l` at `+∞`. - `MeasureTheory.integral_Ioi_of_hasDerivAt_of_nonneg` gives the same result assuming that `g'` is nonnegative instead of integrable. Its automatic integrability in this context is proved in `MeasureTheory.integrableOn_Ioi_deriv_of_nonneg`. - `MeasureTheory.integral_comp_smul_deriv_Ioi` is a version of the change of variables formula on semi-infinite intervals. - `MeasureTheory.tendsto_limUnder_of_hasDerivAt_of_integrableOn_Ioi` shows that a function whose derivative is integrable on `(a, +∞)` has a limit at `+∞`. - `MeasureTheory.tendsto_zero_of_hasDerivAt_of_integrableOn_Ioi` shows that an integrable function whose derivative is integrable on `(a, +∞)` tends to `0` at `+∞`. Versions of these results are also given on the intervals `(-∞, a]` and `(-∞, +∞)`, as well as the corresponding versions of integration by parts. -/ open MeasureTheory Filter Set TopologicalSpace Topology open scoped ENNReal NNReal namespace MeasureTheory section AECover variable {α ι : Type*} [MeasurableSpace α] (μ : Measure α) (l : Filter ι) /-- A sequence `φ` of subsets of `α` is a `MeasureTheory.AECover` w.r.t. a measure `μ` and a filter `l` if almost every point (w.r.t. `μ`) of `α` eventually belongs to `φ n` (w.r.t. `l`), and if each `φ n` is measurable. This definition is a technical way to avoid duplicating a lot of proofs. It should be thought of as a sufficient condition for being able to interpret `∫ x, f x ∂μ` (if it exists) as the limit of `∫ x in φ n, f x ∂μ` as `n` tends to `l`. See for example `MeasureTheory.AECover.lintegral_tendsto_of_countably_generated`, `MeasureTheory.AECover.integrable_of_integral_norm_tendsto` and `MeasureTheory.AECover.integral_tendsto_of_countably_generated`. -/ structure AECover (φ : ι → Set α) : Prop where ae_eventually_mem : ∀ᵐ x ∂μ, ∀ᶠ i in l, x ∈ φ i protected measurableSet : ∀ i, MeasurableSet <| φ i variable {μ} {l} namespace AECover /-! ## Operations on `AECover`s -/ /-- Elementwise intersection of two `AECover`s is an `AECover`. -/ theorem inter {φ ψ : ι → Set α} (hφ : AECover μ l φ) (hψ : AECover μ l ψ) : AECover μ l (fun i ↦ φ i ∩ ψ i) where ae_eventually_mem := hψ.1.mp <| hφ.1.mono fun _ ↦ Eventually.and measurableSet _ := (hφ.2 _).inter (hψ.2 _) theorem superset {φ ψ : ι → Set α} (hφ : AECover μ l φ) (hsub : ∀ i, φ i ⊆ ψ i) (hmeas : ∀ i, MeasurableSet (ψ i)) : AECover μ l ψ := ⟨hφ.1.mono fun _x hx ↦ hx.mono fun i hi ↦ hsub i hi, hmeas⟩ theorem mono_ac {ν : Measure α} {φ : ι → Set α} (hφ : AECover μ l φ) (hle : ν ≪ μ) : AECover ν l φ := ⟨hle hφ.1, hφ.2⟩ theorem mono {ν : Measure α} {φ : ι → Set α} (hφ : AECover μ l φ) (hle : ν ≤ μ) : AECover ν l φ := hφ.mono_ac hle.absolutelyContinuous end AECover section MetricSpace variable [PseudoMetricSpace α] [OpensMeasurableSpace α] theorem aecover_ball {x : α} {r : ι → ℝ} (hr : Tendsto r l atTop) : AECover μ l (fun i ↦ Metric.ball x (r i)) where measurableSet _ := Metric.isOpen_ball.measurableSet ae_eventually_mem := by filter_upwards with y filter_upwards [hr (Ioi_mem_atTop (dist x y))] with a ha using by simpa [dist_comm] using ha theorem aecover_closedBall {x : α} {r : ι → ℝ} (hr : Tendsto r l atTop) : AECover μ l (fun i ↦ Metric.closedBall x (r i)) where measurableSet _ := Metric.isClosed_closedBall.measurableSet ae_eventually_mem := by filter_upwards with y filter_upwards [hr (Ici_mem_atTop (dist x y))] with a ha using by simpa [dist_comm] using ha end MetricSpace section Preorderα variable [Preorder α] [TopologicalSpace α] [OrderClosedTopology α] [OpensMeasurableSpace α] {a b : ι → α} theorem aecover_Ici (ha : Tendsto a l atBot) : AECover μ l fun i => Ici (a i) where ae_eventually_mem := ae_of_all μ ha.eventually_le_atBot measurableSet _ := measurableSet_Ici theorem aecover_Iic (hb : Tendsto b l atTop) : AECover μ l fun i => Iic <| b i := aecover_Ici (α := αᵒᵈ) hb theorem aecover_Icc (ha : Tendsto a l atBot) (hb : Tendsto b l atTop) : AECover μ l fun i => Icc (a i) (b i) := (aecover_Ici ha).inter (aecover_Iic hb) end Preorderα section LinearOrderα variable [LinearOrder α] [TopologicalSpace α] [OrderClosedTopology α] [OpensMeasurableSpace α] {a b : ι → α} (ha : Tendsto a l atBot) (hb : Tendsto b l atTop) include ha in theorem aecover_Ioi [NoMinOrder α] : AECover μ l fun i => Ioi (a i) where ae_eventually_mem := ae_of_all μ ha.eventually_lt_atBot measurableSet _ := measurableSet_Ioi include hb in theorem aecover_Iio [NoMaxOrder α] : AECover μ l fun i => Iio (b i) := aecover_Ioi (α := αᵒᵈ) hb include ha hb theorem aecover_Ioo [NoMinOrder α] [NoMaxOrder α] : AECover μ l fun i => Ioo (a i) (b i) := (aecover_Ioi ha).inter (aecover_Iio hb) theorem aecover_Ioc [NoMinOrder α] : AECover μ l fun i => Ioc (a i) (b i) := (aecover_Ioi ha).inter (aecover_Iic hb) theorem aecover_Ico [NoMaxOrder α] : AECover μ l fun i => Ico (a i) (b i) := (aecover_Ici ha).inter (aecover_Iio hb) end LinearOrderα section FiniteIntervals variable [LinearOrder α] [TopologicalSpace α] [OrderClosedTopology α] [OpensMeasurableSpace α] {a b : ι → α} {A B : α} (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) include ha in theorem aecover_Ioi_of_Ioi : AECover (μ.restrict (Ioi A)) l fun i ↦ Ioi (a i) where ae_eventually_mem := (ae_restrict_mem measurableSet_Ioi).mono fun _x hx ↦ ha.eventually <| eventually_lt_nhds hx measurableSet _ := measurableSet_Ioi include hb in theorem aecover_Iio_of_Iio : AECover (μ.restrict (Iio B)) l fun i ↦ Iio (b i) := aecover_Ioi_of_Ioi (α := αᵒᵈ) hb include ha in theorem aecover_Ioi_of_Ici : AECover (μ.restrict (Ioi A)) l fun i ↦ Ici (a i) := (aecover_Ioi_of_Ioi ha).superset (fun _ ↦ Ioi_subset_Ici_self) fun _ ↦ measurableSet_Ici include hb in theorem aecover_Iio_of_Iic : AECover (μ.restrict (Iio B)) l fun i ↦ Iic (b i) := aecover_Ioi_of_Ici (α := αᵒᵈ) hb include ha hb in theorem aecover_Ioo_of_Ioo : AECover (μ.restrict <| Ioo A B) l fun i => Ioo (a i) (b i) := ((aecover_Ioi_of_Ioi ha).mono <| Measure.restrict_mono Ioo_subset_Ioi_self le_rfl).inter ((aecover_Iio_of_Iio hb).mono <| Measure.restrict_mono Ioo_subset_Iio_self le_rfl) include ha hb in theorem aecover_Ioo_of_Icc : AECover (μ.restrict <| Ioo A B) l fun i => Icc (a i) (b i) := (aecover_Ioo_of_Ioo ha hb).superset (fun _ ↦ Ioo_subset_Icc_self) fun _ ↦ measurableSet_Icc include ha hb in theorem aecover_Ioo_of_Ico : AECover (μ.restrict <| Ioo A B) l fun i => Ico (a i) (b i) := (aecover_Ioo_of_Ioo ha hb).superset (fun _ ↦ Ioo_subset_Ico_self) fun _ ↦ measurableSet_Ico include ha hb in theorem aecover_Ioo_of_Ioc : AECover (μ.restrict <| Ioo A B) l fun i => Ioc (a i) (b i) := (aecover_Ioo_of_Ioo ha hb).superset (fun _ ↦ Ioo_subset_Ioc_self) fun _ ↦ measurableSet_Ioc variable [NoAtoms μ] theorem aecover_Ioc_of_Icc (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Ioc A B) l fun i => Icc (a i) (b i) := (aecover_Ioo_of_Icc ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Ioc).ge theorem aecover_Ioc_of_Ico (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Ioc A B) l fun i => Ico (a i) (b i) := (aecover_Ioo_of_Ico ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Ioc).ge theorem aecover_Ioc_of_Ioc (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Ioc A B) l fun i => Ioc (a i) (b i) := (aecover_Ioo_of_Ioc ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Ioc).ge theorem aecover_Ioc_of_Ioo (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Ioc A B) l fun i => Ioo (a i) (b i) := (aecover_Ioo_of_Ioo ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Ioc).ge theorem aecover_Ico_of_Icc (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Ico A B) l fun i => Icc (a i) (b i) := (aecover_Ioo_of_Icc ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Ico).ge theorem aecover_Ico_of_Ico (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Ico A B) l fun i => Ico (a i) (b i) := (aecover_Ioo_of_Ico ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Ico).ge theorem aecover_Ico_of_Ioc (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Ico A B) l fun i => Ioc (a i) (b i) := (aecover_Ioo_of_Ioc ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Ico).ge theorem aecover_Ico_of_Ioo (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Ico A B) l fun i => Ioo (a i) (b i) := (aecover_Ioo_of_Ioo ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Ico).ge theorem aecover_Icc_of_Icc (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Icc A B) l fun i => Icc (a i) (b i) := (aecover_Ioo_of_Icc ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Icc).ge theorem aecover_Icc_of_Ico (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Icc A B) l fun i => Ico (a i) (b i) := (aecover_Ioo_of_Ico ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Icc).ge theorem aecover_Icc_of_Ioc (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Icc A B) l fun i => Ioc (a i) (b i) := (aecover_Ioo_of_Ioc ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Icc).ge theorem aecover_Icc_of_Ioo (ha : Tendsto a l (𝓝 A)) (hb : Tendsto b l (𝓝 B)) : AECover (μ.restrict <| Icc A B) l fun i => Ioo (a i) (b i) := (aecover_Ioo_of_Ioo ha hb).mono (Measure.restrict_congr_set Ioo_ae_eq_Icc).ge end FiniteIntervals protected theorem AECover.restrict {φ : ι → Set α} (hφ : AECover μ l φ) {s : Set α} : AECover (μ.restrict s) l φ := hφ.mono Measure.restrict_le_self theorem aecover_restrict_of_ae_imp {s : Set α} {φ : ι → Set α} (hs : MeasurableSet s) (ae_eventually_mem : ∀ᵐ x ∂μ, x ∈ s → ∀ᶠ n in l, x ∈ φ n) (measurable : ∀ n, MeasurableSet <| φ n) : AECover (μ.restrict s) l φ where ae_eventually_mem := by rwa [ae_restrict_iff' hs] measurableSet := measurable theorem AECover.inter_restrict {φ : ι → Set α} (hφ : AECover μ l φ) {s : Set α} (hs : MeasurableSet s) : AECover (μ.restrict s) l fun i => φ i ∩ s := aecover_restrict_of_ae_imp hs (hφ.ae_eventually_mem.mono fun _x hx hxs => hx.mono fun _i hi => ⟨hi, hxs⟩) fun i => (hφ.measurableSet i).inter hs theorem AECover.ae_tendsto_indicator {β : Type*} [Zero β] [TopologicalSpace β] (f : α → β) {φ : ι → Set α} (hφ : AECover μ l φ) : ∀ᵐ x ∂μ, Tendsto (fun i => (φ i).indicator f x) l (𝓝 <| f x) := hφ.ae_eventually_mem.mono fun _x hx => tendsto_const_nhds.congr' <| hx.mono fun _n hn => (indicator_of_mem hn _).symm theorem AECover.aemeasurable {β : Type*} [MeasurableSpace β] [l.IsCountablyGenerated] [l.NeBot] {f : α → β} {φ : ι → Set α} (hφ : AECover μ l φ) (hfm : ∀ i, AEMeasurable f (μ.restrict <| φ i)) : AEMeasurable f μ := by obtain ⟨u, hu⟩ := l.exists_seq_tendsto have := aemeasurable_iUnion_iff.mpr fun n : ℕ => hfm (u n) rwa [Measure.restrict_eq_self_of_ae_mem] at this filter_upwards [hφ.ae_eventually_mem] with x hx using mem_iUnion.mpr (hu.eventually hx).exists theorem AECover.aestronglyMeasurable {β : Type*} [TopologicalSpace β] [PseudoMetrizableSpace β] [l.IsCountablyGenerated] [l.NeBot] {f : α → β} {φ : ι → Set α} (hφ : AECover μ l φ) (hfm : ∀ i, AEStronglyMeasurable f (μ.restrict <| φ i)) : AEStronglyMeasurable f μ := by obtain ⟨u, hu⟩ := l.exists_seq_tendsto have := aestronglyMeasurable_iUnion_iff.mpr fun n : ℕ => hfm (u n) rwa [Measure.restrict_eq_self_of_ae_mem] at this filter_upwards [hφ.ae_eventually_mem] with x hx using mem_iUnion.mpr (hu.eventually hx).exists end AECover theorem AECover.comp_tendsto {α ι ι' : Type*} [MeasurableSpace α] {μ : Measure α} {l : Filter ι} {l' : Filter ι'} {φ : ι → Set α} (hφ : AECover μ l φ) {u : ι' → ι} (hu : Tendsto u l' l) : AECover μ l' (φ ∘ u) where ae_eventually_mem := hφ.ae_eventually_mem.mono fun _x hx => hu.eventually hx measurableSet i := hφ.measurableSet (u i) section AECoverUnionInterCountable variable {α ι : Type*} [Countable ι] [MeasurableSpace α] {μ : Measure α} theorem AECover.biUnion_Iic_aecover [Preorder ι] {φ : ι → Set α} (hφ : AECover μ atTop φ) : AECover μ atTop fun n : ι => ⋃ (k) (_h : k ∈ Iic n), φ k := hφ.superset (fun _ ↦ subset_biUnion_of_mem right_mem_Iic) fun _ ↦ .biUnion (to_countable _) fun _ _ ↦ (hφ.2 _) theorem AECover.biInter_Ici_aecover [Preorder ι] {φ : ι → Set α} (hφ : AECover μ atTop φ) : AECover μ atTop fun n : ι => ⋂ (k) (_h : k ∈ Ici n), φ k where ae_eventually_mem := hφ.ae_eventually_mem.mono fun x h ↦ by simpa only [mem_iInter, mem_Ici, eventually_forall_ge_atTop] measurableSet _ := .biInter (to_countable _) fun n _ => hφ.measurableSet n end AECoverUnionInterCountable section Lintegral variable {α ι : Type*} [MeasurableSpace α] {μ : Measure α} {l : Filter ι} private theorem lintegral_tendsto_of_monotone_of_nat {φ : ℕ → Set α} (hφ : AECover μ atTop φ) (hmono : Monotone φ) {f : α → ℝ≥0∞} (hfm : AEMeasurable f μ) : Tendsto (fun i => ∫⁻ x in φ i, f x ∂μ) atTop (𝓝 <| ∫⁻ x, f x ∂μ) := let F n := (φ n).indicator f have key₁ : ∀ n, AEMeasurable (F n) μ := fun n => hfm.indicator (hφ.measurableSet n) have key₂ : ∀ᵐ x : α ∂μ, Monotone fun n => F n x := ae_of_all _ fun x _i _j hij => indicator_le_indicator_of_subset (hmono hij) (fun x => zero_le <| f x) x have key₃ : ∀ᵐ x : α ∂μ, Tendsto (fun n => F n x) atTop (𝓝 (f x)) := hφ.ae_tendsto_indicator f (lintegral_tendsto_of_tendsto_of_monotone key₁ key₂ key₃).congr fun n => lintegral_indicator (hφ.measurableSet n) _ theorem AECover.lintegral_tendsto_of_nat {φ : ℕ → Set α} (hφ : AECover μ atTop φ) {f : α → ℝ≥0∞} (hfm : AEMeasurable f μ) : Tendsto (∫⁻ x in φ ·, f x ∂μ) atTop (𝓝 <| ∫⁻ x, f x ∂μ) := by have lim₁ := lintegral_tendsto_of_monotone_of_nat hφ.biInter_Ici_aecover (fun i j hij => biInter_subset_biInter_left (Ici_subset_Ici.mpr hij)) hfm have lim₂ := lintegral_tendsto_of_monotone_of_nat hφ.biUnion_Iic_aecover (fun i j hij => biUnion_subset_biUnion_left (Iic_subset_Iic.mpr hij)) hfm refine tendsto_of_tendsto_of_tendsto_of_le_of_le lim₁ lim₂ (fun n ↦ ?_) fun n ↦ ?_ exacts [lintegral_mono_set (biInter_subset_of_mem left_mem_Ici), lintegral_mono_set (subset_biUnion_of_mem right_mem_Iic)] theorem AECover.lintegral_tendsto_of_countably_generated [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → ℝ≥0∞} (hfm : AEMeasurable f μ) : Tendsto (fun i => ∫⁻ x in φ i, f x ∂μ) l (𝓝 <| ∫⁻ x, f x ∂μ) := tendsto_of_seq_tendsto fun _u hu => (hφ.comp_tendsto hu).lintegral_tendsto_of_nat hfm theorem AECover.lintegral_eq_of_tendsto [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → ℝ≥0∞} (I : ℝ≥0∞) (hfm : AEMeasurable f μ) (htendsto : Tendsto (fun i => ∫⁻ x in φ i, f x ∂μ) l (𝓝 I)) : ∫⁻ x, f x ∂μ = I := tendsto_nhds_unique (hφ.lintegral_tendsto_of_countably_generated hfm) htendsto theorem AECover.iSup_lintegral_eq_of_countably_generated [Nonempty ι] [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → ℝ≥0∞} (hfm : AEMeasurable f μ) : ⨆ i : ι, ∫⁻ x in φ i, f x ∂μ = ∫⁻ x, f x ∂μ := by have := hφ.lintegral_tendsto_of_countably_generated hfm refine ciSup_eq_of_forall_le_of_forall_lt_exists_gt (fun i => lintegral_mono' Measure.restrict_le_self le_rfl) fun w hw => ?_ exact (this.eventually_const_lt hw).exists end Lintegral section Integrable variable {α ι E : Type*} [MeasurableSpace α] {μ : Measure α} {l : Filter ι} [NormedAddCommGroup E] theorem AECover.integrable_of_lintegral_enorm_bounded [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → E} (I : ℝ) (hfm : AEStronglyMeasurable f μ) (hbounded : ∀ᶠ i in l, ∫⁻ x in φ i, ‖f x‖ₑ ∂μ ≤ ENNReal.ofReal I) : Integrable f μ := by refine ⟨hfm, (le_of_tendsto ?_ hbounded).trans_lt ENNReal.ofReal_lt_top⟩ exact hφ.lintegral_tendsto_of_countably_generated hfm.enorm theorem AECover.integrable_of_lintegral_enorm_tendsto [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → E} (I : ℝ) (hfm : AEStronglyMeasurable f μ) (htendsto : Tendsto (fun i => ∫⁻ x in φ i, ‖f x‖ₑ ∂μ) l (𝓝 <| .ofReal I)) : Integrable f μ := by refine hφ.integrable_of_lintegral_enorm_bounded (max 1 (I + 1)) hfm ?_ refine htendsto.eventually (ge_mem_nhds ?_) refine (ENNReal.ofReal_lt_ofReal_iff (lt_max_of_lt_left zero_lt_one)).2 ?_ exact lt_max_of_lt_right (lt_add_one I) theorem AECover.integrable_of_lintegral_enorm_bounded' [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → E} (I : ℝ≥0) (hfm : AEStronglyMeasurable f μ) (hbounded : ∀ᶠ i in l, ∫⁻ x in φ i, ‖f x‖ₑ ∂μ ≤ I) : Integrable f μ := hφ.integrable_of_lintegral_enorm_bounded I hfm (by simpa only [ENNReal.ofReal_coe_nnreal] using hbounded) theorem AECover.integrable_of_lintegral_enorm_tendsto' [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → E} (I : ℝ≥0) (hfm : AEStronglyMeasurable f μ) (htendsto : Tendsto (fun i => ∫⁻ x in φ i, ‖f x‖ₑ ∂μ) l (𝓝 I)) : Integrable f μ := hφ.integrable_of_lintegral_enorm_tendsto I hfm (by simpa only [ENNReal.ofReal_coe_nnreal] using htendsto) theorem AECover.integrable_of_integral_norm_bounded [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → E} (I : ℝ) (hfi : ∀ i, IntegrableOn f (φ i) μ) (hbounded : ∀ᶠ i in l, (∫ x in φ i, ‖f x‖ ∂μ) ≤ I) : Integrable f μ := by have hfm : AEStronglyMeasurable f μ := hφ.aestronglyMeasurable fun i => (hfi i).aestronglyMeasurable refine hφ.integrable_of_lintegral_enorm_bounded I hfm ?_ conv at hbounded in integral _ _ => rw [integral_eq_lintegral_of_nonneg_ae (ae_of_all _ fun x => @norm_nonneg E _ (f x)) hfm.norm.restrict] conv at hbounded in ENNReal.ofReal _ => rw [← coe_nnnorm, ENNReal.ofReal_coe_nnreal] refine hbounded.mono fun i hi => ?_ rw [← ENNReal.ofReal_toReal <| ne_top_of_lt <| hasFiniteIntegral_iff_enorm.mp (hfi i).2] apply ENNReal.ofReal_le_ofReal hi theorem AECover.integrable_of_integral_norm_tendsto [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → E} (I : ℝ) (hfi : ∀ i, IntegrableOn f (φ i) μ) (htendsto : Tendsto (fun i => ∫ x in φ i, ‖f x‖ ∂μ) l (𝓝 I)) : Integrable f μ := let ⟨I', hI'⟩ := htendsto.isBoundedUnder_le hφ.integrable_of_integral_norm_bounded I' hfi hI' theorem AECover.integrable_of_integral_bounded_of_nonneg_ae [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → ℝ} (I : ℝ) (hfi : ∀ i, IntegrableOn f (φ i) μ) (hnng : ∀ᵐ x ∂μ, 0 ≤ f x) (hbounded : ∀ᶠ i in l, (∫ x in φ i, f x ∂μ) ≤ I) : Integrable f μ := hφ.integrable_of_integral_norm_bounded I hfi <| hbounded.mono fun _i hi => (integral_congr_ae <| ae_restrict_of_ae <| hnng.mono fun _ => Real.norm_of_nonneg).le.trans hi theorem AECover.integrable_of_integral_tendsto_of_nonneg_ae [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → ℝ} (I : ℝ) (hfi : ∀ i, IntegrableOn f (φ i) μ) (hnng : ∀ᵐ x ∂μ, 0 ≤ f x) (htendsto : Tendsto (fun i => ∫ x in φ i, f x ∂μ) l (𝓝 I)) : Integrable f μ := let ⟨I', hI'⟩ := htendsto.isBoundedUnder_le hφ.integrable_of_integral_bounded_of_nonneg_ae I' hfi hnng hI' end Integrable section Integral variable {α ι E : Type*} [MeasurableSpace α] {μ : Measure α} {l : Filter ι} [NormedAddCommGroup E] [NormedSpace ℝ E] theorem AECover.integral_tendsto_of_countably_generated [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → E} (hfi : Integrable f μ) : Tendsto (fun i => ∫ x in φ i, f x ∂μ) l (𝓝 <| ∫ x, f x ∂μ) := suffices h : Tendsto (fun i => ∫ x : α, (φ i).indicator f x ∂μ) l (𝓝 (∫ x : α, f x ∂μ)) from by convert h using 2; rw [integral_indicator (hφ.measurableSet _)] tendsto_integral_filter_of_dominated_convergence (fun x => ‖f x‖) (Eventually.of_forall fun i => hfi.aestronglyMeasurable.indicator <| hφ.measurableSet i) (Eventually.of_forall fun _ => ae_of_all _ fun _ => norm_indicator_le_norm_self _ _) hfi.norm (hφ.ae_tendsto_indicator f) /-- Slight reformulation of `MeasureTheory.AECover.integral_tendsto_of_countably_generated`. -/ theorem AECover.integral_eq_of_tendsto [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → E} (I : E) (hfi : Integrable f μ) (h : Tendsto (fun n => ∫ x in φ n, f x ∂μ) l (𝓝 I)) : ∫ x, f x ∂μ = I := tendsto_nhds_unique (hφ.integral_tendsto_of_countably_generated hfi) h theorem AECover.integral_eq_of_tendsto_of_nonneg_ae [l.NeBot] [l.IsCountablyGenerated] {φ : ι → Set α} (hφ : AECover μ l φ) {f : α → ℝ} (I : ℝ) (hnng : 0 ≤ᵐ[μ] f) (hfi : ∀ n, IntegrableOn f (φ n) μ) (htendsto : Tendsto (fun n => ∫ x in φ n, f x ∂μ) l (𝓝 I)) : ∫ x, f x ∂μ = I := have hfi' : Integrable f μ := hφ.integrable_of_integral_tendsto_of_nonneg_ae I hfi hnng htendsto hφ.integral_eq_of_tendsto I hfi' htendsto end Integral section IntegrableOfIntervalIntegral variable {ι E : Type*} {μ : Measure ℝ} {l : Filter ι} [Filter.NeBot l] [IsCountablyGenerated l] [NormedAddCommGroup E] {a b : ι → ℝ} {f : ℝ → E} theorem integrable_of_intervalIntegral_norm_bounded (I : ℝ) (hfi : ∀ i, IntegrableOn f (Ioc (a i) (b i)) μ) (ha : Tendsto a l atBot) (hb : Tendsto b l atTop) (h : ∀ᶠ i in l, (∫ x in a i..b i, ‖f x‖ ∂μ) ≤ I) : Integrable f μ := by have hφ : AECover μ l _ := aecover_Ioc ha hb refine hφ.integrable_of_integral_norm_bounded I hfi (h.mp ?_) filter_upwards [ha.eventually (eventually_le_atBot 0), hb.eventually (eventually_ge_atTop 0)] with i hai hbi ht rwa [← intervalIntegral.integral_of_le (hai.trans hbi)] /-- If `f` is integrable on intervals `Ioc (a i) (b i)`, where `a i` tends to -∞ and `b i` tends to ∞, and `∫ x in a i .. b i, ‖f x‖ ∂μ` converges to `I : ℝ` along a filter `l`, then `f` is integrable on the interval (-∞, ∞) -/ theorem integrable_of_intervalIntegral_norm_tendsto (I : ℝ) (hfi : ∀ i, IntegrableOn f (Ioc (a i) (b i)) μ) (ha : Tendsto a l atBot) (hb : Tendsto b l atTop) (h : Tendsto (fun i => ∫ x in a i..b i, ‖f x‖ ∂μ) l (𝓝 I)) : Integrable f μ := let ⟨I', hI'⟩ := h.isBoundedUnder_le integrable_of_intervalIntegral_norm_bounded I' hfi ha hb hI' theorem integrableOn_Iic_of_intervalIntegral_norm_bounded (I b : ℝ) (hfi : ∀ i, IntegrableOn f (Ioc (a i) b) μ) (ha : Tendsto a l atBot) (h : ∀ᶠ i in l, (∫ x in a i..b, ‖f x‖ ∂μ) ≤ I) : IntegrableOn f (Iic b) μ := by have hφ : AECover (μ.restrict <| Iic b) l _ := aecover_Ioi ha have hfi : ∀ i, IntegrableOn f (Ioi (a i)) (μ.restrict <| Iic b) := by intro i rw [IntegrableOn, Measure.restrict_restrict (hφ.measurableSet i)] exact hfi i refine hφ.integrable_of_integral_norm_bounded I hfi (h.mp ?_) filter_upwards [ha.eventually (eventually_le_atBot b)] with i hai rw [intervalIntegral.integral_of_le hai, Measure.restrict_restrict (hφ.measurableSet i)] exact id /-- If `f` is integrable on intervals `Ioc (a i) b`, where `a i` tends to -∞, and `∫ x in a i .. b, ‖f x‖ ∂μ` converges to `I : ℝ` along a filter `l`, then `f` is integrable on the interval (-∞, b) -/ theorem integrableOn_Iic_of_intervalIntegral_norm_tendsto (I b : ℝ) (hfi : ∀ i, IntegrableOn f (Ioc (a i) b) μ) (ha : Tendsto a l atBot) (h : Tendsto (fun i => ∫ x in a i..b, ‖f x‖ ∂μ) l (𝓝 I)) : IntegrableOn f (Iic b) μ := let ⟨I', hI'⟩ := h.isBoundedUnder_le integrableOn_Iic_of_intervalIntegral_norm_bounded I' b hfi ha hI' theorem integrableOn_Ioi_of_intervalIntegral_norm_bounded (I a : ℝ) (hfi : ∀ i, IntegrableOn f (Ioc a (b i)) μ) (hb : Tendsto b l atTop) (h : ∀ᶠ i in l, (∫ x in a..b i, ‖f x‖ ∂μ) ≤ I) : IntegrableOn f (Ioi a) μ := by have hφ : AECover (μ.restrict <| Ioi a) l _ := aecover_Iic hb have hfi : ∀ i, IntegrableOn f (Iic (b i)) (μ.restrict <| Ioi a) := by intro i rw [IntegrableOn, Measure.restrict_restrict (hφ.measurableSet i), inter_comm] exact hfi i refine hφ.integrable_of_integral_norm_bounded I hfi (h.mp ?_) filter_upwards [hb.eventually (eventually_ge_atTop a)] with i hbi rw [intervalIntegral.integral_of_le hbi, Measure.restrict_restrict (hφ.measurableSet i), inter_comm] exact id /-- If `f` is integrable on intervals `Ioc a (b i)`, where `b i` tends to ∞, and `∫ x in a .. b i, ‖f x‖ ∂μ` converges to `I : ℝ` along a filter `l`, then `f` is integrable on the interval (a, ∞) -/ theorem integrableOn_Ioi_of_intervalIntegral_norm_tendsto (I a : ℝ) (hfi : ∀ i, IntegrableOn f (Ioc a (b i)) μ) (hb : Tendsto b l atTop) (h : Tendsto (fun i => ∫ x in a..b i, ‖f x‖ ∂μ) l (𝓝 <| I)) : IntegrableOn f (Ioi a) μ := let ⟨I', hI'⟩ := h.isBoundedUnder_le integrableOn_Ioi_of_intervalIntegral_norm_bounded I' a hfi hb hI' theorem integrableOn_Ioc_of_intervalIntegral_norm_bounded {I a₀ b₀ : ℝ} (hfi : ∀ i, IntegrableOn f <| Ioc (a i) (b i)) (ha : Tendsto a l <| 𝓝 a₀) (hb : Tendsto b l <| 𝓝 b₀) (h : ∀ᶠ i in l, (∫ x in Ioc (a i) (b i), ‖f x‖) ≤ I) : IntegrableOn f (Ioc a₀ b₀) := by refine (aecover_Ioc_of_Ioc ha hb).integrable_of_integral_norm_bounded I (fun i => (hfi i).restrict) (h.mono fun i hi ↦ ?_) rw [Measure.restrict_restrict measurableSet_Ioc] refine le_trans (setIntegral_mono_set (hfi i).norm ?_ ?_) hi <;> apply ae_of_all · simp only [Pi.zero_apply, norm_nonneg, forall_const] · intro c hc; exact hc.1 theorem integrableOn_Ioc_of_intervalIntegral_norm_bounded_left {I a₀ b : ℝ} (hfi : ∀ i, IntegrableOn f <| Ioc (a i) b) (ha : Tendsto a l <| 𝓝 a₀) (h : ∀ᶠ i in l, (∫ x in Ioc (a i) b, ‖f x‖) ≤ I) : IntegrableOn f (Ioc a₀ b) := integrableOn_Ioc_of_intervalIntegral_norm_bounded hfi ha tendsto_const_nhds h theorem integrableOn_Ioc_of_intervalIntegral_norm_bounded_right {I a b₀ : ℝ} (hfi : ∀ i, IntegrableOn f <| Ioc a (b i)) (hb : Tendsto b l <| 𝓝 b₀) (h : ∀ᶠ i in l, (∫ x in Ioc a (b i), ‖f x‖) ≤ I) : IntegrableOn f (Ioc a b₀) := integrableOn_Ioc_of_intervalIntegral_norm_bounded hfi tendsto_const_nhds hb h end IntegrableOfIntervalIntegral section IntegralOfIntervalIntegral variable {ι E : Type*} {μ : Measure ℝ} {l : Filter ι} [IsCountablyGenerated l] [NormedAddCommGroup E] [NormedSpace ℝ E] {a b : ι → ℝ} {f : ℝ → E} theorem intervalIntegral_tendsto_integral (hfi : Integrable f μ) (ha : Tendsto a l atBot) (hb : Tendsto b l atTop) : Tendsto (fun i => ∫ x in a i..b i, f x ∂μ) l (𝓝 <| ∫ x, f x ∂μ) := by let φ i := Ioc (a i) (b i) have hφ : AECover μ l φ := aecover_Ioc ha hb refine (hφ.integral_tendsto_of_countably_generated hfi).congr' ?_ filter_upwards [ha.eventually (eventually_le_atBot 0), hb.eventually (eventually_ge_atTop 0)] with i hai hbi exact (intervalIntegral.integral_of_le (hai.trans hbi)).symm theorem intervalIntegral_tendsto_integral_Iic (b : ℝ) (hfi : IntegrableOn f (Iic b) μ) (ha : Tendsto a l atBot) : Tendsto (fun i => ∫ x in a i..b, f x ∂μ) l (𝓝 <| ∫ x in Iic b, f x ∂μ) := by let φ i := Ioi (a i) have hφ : AECover (μ.restrict <| Iic b) l φ := aecover_Ioi ha refine (hφ.integral_tendsto_of_countably_generated hfi).congr' ?_ filter_upwards [ha.eventually (eventually_le_atBot <| b)] with i hai rw [intervalIntegral.integral_of_le hai, Measure.restrict_restrict (hφ.measurableSet i)] rfl theorem intervalIntegral_tendsto_integral_Ioi (a : ℝ) (hfi : IntegrableOn f (Ioi a) μ) (hb : Tendsto b l atTop) : Tendsto (fun i => ∫ x in a..b i, f x ∂μ) l (𝓝 <| ∫ x in Ioi a, f x ∂μ) := by let φ i := Iic (b i) have hφ : AECover (μ.restrict <| Ioi a) l φ := aecover_Iic hb refine (hφ.integral_tendsto_of_countably_generated hfi).congr' ?_ filter_upwards [hb.eventually (eventually_ge_atTop <| a)] with i hbi rw [intervalIntegral.integral_of_le hbi, Measure.restrict_restrict (hφ.measurableSet i), inter_comm] rfl end IntegralOfIntervalIntegral open Real open scoped Interval section IoiFTC variable {E : Type*} {f f' : ℝ → E} {g g' : ℝ → ℝ} {a l : ℝ} {m : E} [NormedAddCommGroup E] [NormedSpace ℝ E] /-- If the derivative of a function defined on the real line is integrable close to `+∞`, then the function has a limit at `+∞`. -/ theorem tendsto_limUnder_of_hasDerivAt_of_integrableOn_Ioi [CompleteSpace E] (hderiv : ∀ x ∈ Ioi a, HasDerivAt f (f' x) x) (f'int : IntegrableOn f' (Ioi a)) : Tendsto f atTop (𝓝 (limUnder atTop f)) := by suffices ∃ a, Tendsto f atTop (𝓝 a) from tendsto_nhds_limUnder this suffices CauchySeq f from cauchySeq_tendsto_of_complete this apply Metric.cauchySeq_iff'.2 (fun ε εpos ↦ ?_) have A : ∀ᶠ (n : ℕ) in atTop, ∫ (x : ℝ) in Ici ↑n, ‖f' x‖ < ε := by have L : Tendsto (fun (n : ℕ) ↦ ∫ x in Ici (n : ℝ), ‖f' x‖) atTop (𝓝 (∫ x in ⋂ (n : ℕ), Ici (n : ℝ), ‖f' x‖)) := by apply tendsto_setIntegral_of_antitone (fun n ↦ measurableSet_Ici) · intro m n hmn exact Ici_subset_Ici.2 (Nat.cast_le.mpr hmn) · rcases exists_nat_gt a with ⟨n, hn⟩ exact ⟨n, IntegrableOn.mono_set f'int.norm (Ici_subset_Ioi.2 hn)⟩ have B : ⋂ (n : ℕ), Ici (n : ℝ) = ∅ := by apply eq_empty_of_forall_notMem (fun x ↦ ?_) simpa only [mem_iInter, mem_Ici, not_forall, not_le] using exists_nat_gt x simp only [B, Measure.restrict_empty, integral_zero_measure] at L exact (tendsto_order.1 L).2 _ εpos have B : ∀ᶠ (n : ℕ) in atTop, a < n := by rcases exists_nat_gt a with ⟨n, hn⟩ filter_upwards [Ioi_mem_atTop n] with m (hm : n < m) using hn.trans (Nat.cast_lt.mpr hm) rcases (A.and B).exists with ⟨N, hN, h'N⟩ refine ⟨N, fun x hx ↦ ?_⟩ calc dist (f x) (f ↑N) = ‖f x - f N‖ := dist_eq_norm _ _ _ = ‖∫ t in Ioc ↑N x, f' t‖ := by rw [← intervalIntegral.integral_of_le hx, intervalIntegral.integral_eq_sub_of_hasDerivAt] · intro y hy simp only [hx, uIcc_of_le, mem_Icc] at hy exact hderiv _ (h'N.trans_le hy.1) · rw [intervalIntegrable_iff_integrableOn_Ioc_of_le hx] exact f'int.mono_set (Ioc_subset_Ioi_self.trans (Ioi_subset_Ioi h'N.le)) _ ≤ ∫ t in Ioc ↑N x, ‖f' t‖ := norm_integral_le_integral_norm fun a ↦ f' a _ ≤ ∫ t in Ici ↑N, ‖f' t‖ := by apply setIntegral_mono_set · apply IntegrableOn.mono_set f'int.norm (Ici_subset_Ioi.2 h'N) · filter_upwards with x using norm_nonneg _ · have : Ioc (↑N) x ⊆ Ici ↑N := Ioc_subset_Ioi_self.trans Ioi_subset_Ici_self exact this.eventuallyLE _ < ε := hN open UniformSpace in /-- If a function and its derivative are integrable on `(a, +∞)`, then the function tends to zero at `+∞`. -/ theorem tendsto_zero_of_hasDerivAt_of_integrableOn_Ioi (hderiv : ∀ x ∈ Ioi a, HasDerivAt f (f' x) x) (f'int : IntegrableOn f' (Ioi a)) (fint : IntegrableOn f (Ioi a)) : Tendsto f atTop (𝓝 0) := by let F : E →L[ℝ] Completion E := Completion.toComplL have Fderiv : ∀ x ∈ Ioi a, HasDerivAt (F ∘ f) (F (f' x)) x := fun x hx ↦ F.hasFDerivAt.comp_hasDerivAt _ (hderiv x hx) have Fint : IntegrableOn (F ∘ f) (Ioi a) := by apply F.integrable_comp fint have F'int : IntegrableOn (F ∘ f') (Ioi a) := by apply F.integrable_comp f'int have A : Tendsto (F ∘ f) atTop (𝓝 (limUnder atTop (F ∘ f))) := by apply tendsto_limUnder_of_hasDerivAt_of_integrableOn_Ioi Fderiv F'int have B : limUnder atTop (F ∘ f) = F 0 := by have : IntegrableAtFilter (F ∘ f) atTop := by exact ⟨Ioi a, Ioi_mem_atTop _, Fint⟩ apply IntegrableAtFilter.eq_zero_of_tendsto this ?_ A intro s hs rcases mem_atTop_sets.1 hs with ⟨b, hb⟩ rw [← top_le_iff, ← volume_Ici (a := b)] exact measure_mono hb rwa [B, ← IsEmbedding.tendsto_nhds_iff] at A exact (Completion.isUniformEmbedding_coe E).isEmbedding variable [CompleteSpace E] /-- **Fundamental theorem of calculus-2**, on semi-infinite intervals `(a, +∞)`. When a function has a limit at infinity `m`, and its derivative is integrable, then the integral of the derivative on `(a, +∞)` is `m - f a`. Version assuming differentiability on `(a, +∞)` and continuity at `a⁺`. Note that such a function always has a limit at infinity, see `tendsto_limUnder_of_hasDerivAt_of_integrableOn_Ioi`. -/ theorem integral_Ioi_of_hasDerivAt_of_tendsto (hcont : ContinuousWithinAt f (Ici a) a) (hderiv : ∀ x ∈ Ioi a, HasDerivAt f (f' x) x) (f'int : IntegrableOn f' (Ioi a)) (hf : Tendsto f atTop (𝓝 m)) : ∫ x in Ioi a, f' x = m - f a := by have hcont : ContinuousOn f (Ici a) := by intro x hx rcases hx.out.eq_or_lt with rfl | hx · exact hcont · exact (hderiv x hx).continuousAt.continuousWithinAt refine tendsto_nhds_unique (intervalIntegral_tendsto_integral_Ioi a f'int tendsto_id) ?_ apply Tendsto.congr' _ (hf.sub_const _) filter_upwards [Ioi_mem_atTop a] with x hx have h'x : a ≤ id x := le_of_lt hx symm apply intervalIntegral.integral_eq_sub_of_hasDerivAt_of_le h'x (hcont.mono Icc_subset_Ici_self) fun y hy => hderiv y hy.1 rw [intervalIntegrable_iff_integrableOn_Ioc_of_le h'x] exact f'int.mono (fun y hy => hy.1) le_rfl /-- **Fundamental theorem of calculus-2**, on semi-infinite intervals `(a, +∞)`. When a function has a limit at infinity `m`, and its derivative is integrable, then the integral of the derivative on `(a, +∞)` is `m - f a`. Version assuming differentiability on `[a, +∞)`. Note that such a function always has a limit at infinity, see `tendsto_limUnder_of_hasDerivAt_of_integrableOn_Ioi`. -/ theorem integral_Ioi_of_hasDerivAt_of_tendsto' (hderiv : ∀ x ∈ Ici a, HasDerivAt f (f' x) x) (f'int : IntegrableOn f' (Ioi a)) (hf : Tendsto f atTop (𝓝 m)) : ∫ x in Ioi a, f' x = m - f a := by refine integral_Ioi_of_hasDerivAt_of_tendsto ?_ (fun x hx => hderiv x hx.out.le) f'int hf exact (hderiv a left_mem_Ici).continuousAt.continuousWithinAt /-- A special case of `integral_Ioi_of_hasDerivAt_of_tendsto` where we assume that `f` is C^1 with compact support. -/ theorem _root_.HasCompactSupport.integral_Ioi_deriv_eq (hf : ContDiff ℝ 1 f) (h2f : HasCompactSupport f) (b : ℝ) : ∫ x in Ioi b, deriv f x = - f b := by have := fun x (_ : x ∈ Ioi b) ↦ hf.differentiable le_rfl x |>.hasDerivAt rw [integral_Ioi_of_hasDerivAt_of_tendsto hf.continuous.continuousWithinAt this, zero_sub] · refine hf.continuous_deriv le_rfl |>.integrable_of_hasCompactSupport h2f.deriv |>.integrableOn rw [hasCompactSupport_iff_eventuallyEq, Filter.coclosedCompact_eq_cocompact] at h2f exact h2f.filter_mono _root_.atTop_le_cocompact |>.tendsto /-- When a function has a limit at infinity, and its derivative is nonnegative, then the derivative is automatically integrable on `(a, +∞)`. Version assuming differentiability on `(a, +∞)` and continuity at `a⁺`. -/ theorem integrableOn_Ioi_deriv_of_nonneg (hcont : ContinuousWithinAt g (Ici a) a) (hderiv : ∀ x ∈ Ioi a, HasDerivAt g (g' x) x) (g'pos : ∀ x ∈ Ioi a, 0 ≤ g' x) (hg : Tendsto g atTop (𝓝 l)) : IntegrableOn g' (Ioi a) := by have hcont : ContinuousOn g (Ici a) := by intro x hx rcases hx.out.eq_or_lt with rfl | hx · exact hcont · exact (hderiv x hx).continuousAt.continuousWithinAt refine integrableOn_Ioi_of_intervalIntegral_norm_tendsto (l - g a) a (fun x => ?_) tendsto_id ?_ · exact intervalIntegral.integrableOn_deriv_of_nonneg (hcont.mono Icc_subset_Ici_self) (fun y hy => hderiv y hy.1) fun y hy => g'pos y hy.1 apply Tendsto.congr' _ (hg.sub_const _) filter_upwards [Ioi_mem_atTop a] with x hx have h'x : a ≤ id x := le_of_lt hx calc g x - g a = ∫ y in a..id x, g' y := by symm apply intervalIntegral.integral_eq_sub_of_hasDerivAt_of_le h'x (hcont.mono Icc_subset_Ici_self) fun y hy => hderiv y hy.1 rw [intervalIntegrable_iff_integrableOn_Ioc_of_le h'x] exact intervalIntegral.integrableOn_deriv_of_nonneg (hcont.mono Icc_subset_Ici_self) (fun y hy => hderiv y hy.1) fun y hy => g'pos y hy.1 _ = ∫ y in a..id x, ‖g' y‖ := by simp_rw [intervalIntegral.integral_of_le h'x] refine setIntegral_congr_fun measurableSet_Ioc fun y hy => ?_ dsimp rw [abs_of_nonneg] exact g'pos _ hy.1 /-- When a function has a limit at infinity, and its derivative is nonnegative, then the derivative is automatically integrable on `(a, +∞)`. Version assuming differentiability on `[a, +∞)`. -/ theorem integrableOn_Ioi_deriv_of_nonneg' (hderiv : ∀ x ∈ Ici a, HasDerivAt g (g' x) x) (g'pos : ∀ x ∈ Ioi a, 0 ≤ g' x) (hg : Tendsto g atTop (𝓝 l)) : IntegrableOn g' (Ioi a) := by refine integrableOn_Ioi_deriv_of_nonneg ?_ (fun x hx => hderiv x hx.out.le) g'pos hg exact (hderiv a left_mem_Ici).continuousAt.continuousWithinAt /-- When a function has a limit at infinity `l`, and its derivative is nonnegative, then the integral of the derivative on `(a, +∞)` is `l - g a` (and the derivative is integrable, see `integrable_on_Ioi_deriv_of_nonneg`). Version assuming differentiability on `(a, +∞)` and continuity at `a⁺`. -/ theorem integral_Ioi_of_hasDerivAt_of_nonneg (hcont : ContinuousWithinAt g (Ici a) a) (hderiv : ∀ x ∈ Ioi a, HasDerivAt g (g' x) x) (g'pos : ∀ x ∈ Ioi a, 0 ≤ g' x) (hg : Tendsto g atTop (𝓝 l)) : ∫ x in Ioi a, g' x = l - g a := integral_Ioi_of_hasDerivAt_of_tendsto hcont hderiv (integrableOn_Ioi_deriv_of_nonneg hcont hderiv g'pos hg) hg /-- When a function has a limit at infinity `l`, and its derivative is nonnegative, then the integral of the derivative on `(a, +∞)` is `l - g a` (and the derivative is integrable, see `integrable_on_Ioi_deriv_of_nonneg'`). Version assuming differentiability on `[a, +∞)`. -/ theorem integral_Ioi_of_hasDerivAt_of_nonneg' (hderiv : ∀ x ∈ Ici a, HasDerivAt g (g' x) x) (g'pos : ∀ x ∈ Ioi a, 0 ≤ g' x) (hg : Tendsto g atTop (𝓝 l)) : ∫ x in Ioi a, g' x = l - g a := integral_Ioi_of_hasDerivAt_of_tendsto' hderiv (integrableOn_Ioi_deriv_of_nonneg' hderiv g'pos hg) hg /-- When a function has a limit at infinity, and its derivative is nonpositive, then the derivative is automatically integrable on `(a, +∞)`. Version assuming differentiability on `(a, +∞)` and continuity at `a⁺`. -/ theorem integrableOn_Ioi_deriv_of_nonpos (hcont : ContinuousWithinAt g (Ici a) a) (hderiv : ∀ x ∈ Ioi a, HasDerivAt g (g' x) x) (g'neg : ∀ x ∈ Ioi a, g' x ≤ 0) (hg : Tendsto g atTop (𝓝 l)) : IntegrableOn g' (Ioi a) := by apply integrable_neg_iff.1 exact integrableOn_Ioi_deriv_of_nonneg hcont.neg (fun x hx => (hderiv x hx).neg) (fun x hx => neg_nonneg_of_nonpos (g'neg x hx)) hg.neg /-- When a function has a limit at infinity, and its derivative is nonpositive, then the derivative is automatically integrable on `(a, +∞)`. Version assuming differentiability on `[a, +∞)`. -/ theorem integrableOn_Ioi_deriv_of_nonpos' (hderiv : ∀ x ∈ Ici a, HasDerivAt g (g' x) x) (g'neg : ∀ x ∈ Ioi a, g' x ≤ 0) (hg : Tendsto g atTop (𝓝 l)) : IntegrableOn g' (Ioi a) := by refine integrableOn_Ioi_deriv_of_nonpos ?_ (fun x hx ↦ hderiv x hx.out.le) g'neg hg exact (hderiv a left_mem_Ici).continuousAt.continuousWithinAt /-- When a function has a limit at infinity `l`, and its derivative is nonpositive, then the integral of the derivative on `(a, +∞)` is `l - g a` (and the derivative is integrable, see `integrable_on_Ioi_deriv_of_nonneg`). Version assuming differentiability on `(a, +∞)` and continuity at `a⁺`. -/ theorem integral_Ioi_of_hasDerivAt_of_nonpos (hcont : ContinuousWithinAt g (Ici a) a) (hderiv : ∀ x ∈ Ioi a, HasDerivAt g (g' x) x) (g'neg : ∀ x ∈ Ioi a, g' x ≤ 0) (hg : Tendsto g atTop (𝓝 l)) : ∫ x in Ioi a, g' x = l - g a := integral_Ioi_of_hasDerivAt_of_tendsto hcont hderiv (integrableOn_Ioi_deriv_of_nonpos hcont hderiv g'neg hg) hg /-- When a function has a limit at infinity `l`, and its derivative is nonpositive, then the integral of the derivative on `(a, +∞)` is `l - g a` (and the derivative is integrable, see `integrable_on_Ioi_deriv_of_nonneg'`). Version assuming differentiability on `[a, +∞)`. -/ theorem integral_Ioi_of_hasDerivAt_of_nonpos' (hderiv : ∀ x ∈ Ici a, HasDerivAt g (g' x) x) (g'neg : ∀ x ∈ Ioi a, g' x ≤ 0) (hg : Tendsto g atTop (𝓝 l)) : ∫ x in Ioi a, g' x = l - g a := integral_Ioi_of_hasDerivAt_of_tendsto' hderiv (integrableOn_Ioi_deriv_of_nonpos' hderiv g'neg hg) hg end IoiFTC section IicFTC variable {E : Type*} {f f' : ℝ → E} {a : ℝ} {m : E} [NormedAddCommGroup E] [NormedSpace ℝ E] /-- If the derivative of a function defined on the real line is integrable close to `-∞`, then the function has a limit at `-∞`. -/ theorem tendsto_limUnder_of_hasDerivAt_of_integrableOn_Iic [CompleteSpace E] (hderiv : ∀ x ∈ Iic a, HasDerivAt f (f' x) x) (f'int : IntegrableOn f' (Iic a)) : Tendsto f atBot (𝓝 (limUnder atBot f)) := by suffices ∃ a, Tendsto f atBot (𝓝 a) from tendsto_nhds_limUnder this let g := f ∘ (fun x ↦ -x) have hdg : ∀ x ∈ Ioi (-a), HasDerivAt g (-f' (-x)) x := by intro x hx have : -x ∈ Iic a := by simp only [mem_Iic, mem_Ioi, neg_le] at *; exact hx.le simpa using HasDerivAt.scomp x (hderiv (-x) this) (hasDerivAt_neg' x) have L : Tendsto g atTop (𝓝 (limUnder atTop g)) := by apply tendsto_limUnder_of_hasDerivAt_of_integrableOn_Ioi hdg exact ((MeasurePreserving.integrableOn_comp_preimage (Measure.measurePreserving_neg _) (Homeomorph.neg ℝ).measurableEmbedding).2 f'int.neg).mono_set (by simp) refine ⟨limUnder atTop g, ?_⟩ have : Tendsto (fun x ↦ g (-x)) atBot (𝓝 (limUnder atTop g)) := L.comp tendsto_neg_atBot_atTop simpa [g] using this open UniformSpace in /-- If a function and its derivative are integrable on `(-∞, a]`, then the function tends to zero at `-∞`. -/ theorem tendsto_zero_of_hasDerivAt_of_integrableOn_Iic (hderiv : ∀ x ∈ Iic a, HasDerivAt f (f' x) x) (f'int : IntegrableOn f' (Iic a)) (fint : IntegrableOn f (Iic a)) : Tendsto f atBot (𝓝 0) := by let F : E →L[ℝ] Completion E := Completion.toComplL have Fderiv : ∀ x ∈ Iic a, HasDerivAt (F ∘ f) (F (f' x)) x := fun x hx ↦ F.hasFDerivAt.comp_hasDerivAt _ (hderiv x hx) have Fint : IntegrableOn (F ∘ f) (Iic a) := by apply F.integrable_comp fint have F'int : IntegrableOn (F ∘ f') (Iic a) := by apply F.integrable_comp f'int have A : Tendsto (F ∘ f) atBot (𝓝 (limUnder atBot (F ∘ f))) := by apply tendsto_limUnder_of_hasDerivAt_of_integrableOn_Iic Fderiv F'int have B : limUnder atBot (F ∘ f) = F 0 := by have : IntegrableAtFilter (F ∘ f) atBot := by exact ⟨Iic a, Iic_mem_atBot _, Fint⟩ apply IntegrableAtFilter.eq_zero_of_tendsto this ?_ A intro s hs rcases mem_atBot_sets.1 hs with ⟨b, hb⟩ apply le_antisymm (le_top) rw [← volume_Iic (a := b)] exact measure_mono hb rwa [B, ← IsEmbedding.tendsto_nhds_iff] at A exact (Completion.isUniformEmbedding_coe E).isEmbedding variable [CompleteSpace E] /-- **Fundamental theorem of calculus-2**, on semi-infinite intervals `(-∞, a)`. When a function has a limit `m` at `-∞`, and its derivative is integrable, then the integral of the derivative on `(-∞, a)` is `f a - m`. Version assuming differentiability on `(-∞, a)` and continuity at `a⁻`. Note that such a function always has a limit at minus infinity, see `tendsto_limUnder_of_hasDerivAt_of_integrableOn_Iic`. -/ theorem integral_Iic_of_hasDerivAt_of_tendsto (hcont : ContinuousWithinAt f (Iic a) a) (hderiv : ∀ x ∈ Iio a, HasDerivAt f (f' x) x) (f'int : IntegrableOn f' (Iic a)) (hf : Tendsto f atBot (𝓝 m)) : ∫ x in Iic a, f' x = f a - m := by have hcont : ContinuousOn f (Iic a) := by intro x hx rcases hx.out.eq_or_lt with rfl | hx · exact hcont · exact (hderiv x hx).continuousAt.continuousWithinAt refine tendsto_nhds_unique (intervalIntegral_tendsto_integral_Iic a f'int tendsto_id) ?_ apply Tendsto.congr' _ (hf.const_sub _) filter_upwards [Iic_mem_atBot a] with x hx symm apply intervalIntegral.integral_eq_sub_of_hasDerivAt_of_le hx (hcont.mono Icc_subset_Iic_self) fun y hy => hderiv y hy.2 rw [intervalIntegrable_iff_integrableOn_Ioc_of_le hx] exact f'int.mono (fun y hy => hy.2) le_rfl /-- **Fundamental theorem of calculus-2**, on semi-infinite intervals `(-∞, a)`. When a function has a limit `m` at `-∞`, and its derivative is integrable, then the integral of the derivative on `(-∞, a)` is `f a - m`. Version assuming differentiability on `(-∞, a]`. Note that such a function always has a limit at minus infinity, see `tendsto_limUnder_of_hasDerivAt_of_integrableOn_Iic`. -/ theorem integral_Iic_of_hasDerivAt_of_tendsto' (hderiv : ∀ x ∈ Iic a, HasDerivAt f (f' x) x) (f'int : IntegrableOn f' (Iic a)) (hf : Tendsto f atBot (𝓝 m)) : ∫ x in Iic a, f' x = f a - m := by refine integral_Iic_of_hasDerivAt_of_tendsto ?_ (fun x hx => hderiv x hx.out.le) f'int hf exact (hderiv a right_mem_Iic).continuousAt.continuousWithinAt /-- A special case of `integral_Iic_of_hasDerivAt_of_tendsto` where we assume that `f` is C^1 with compact support. -/ theorem _root_.HasCompactSupport.integral_Iic_deriv_eq (hf : ContDiff ℝ 1 f) (h2f : HasCompactSupport f) (b : ℝ) : ∫ x in Iic b, deriv f x = f b := by have := fun x (_ : x ∈ Iio b) ↦ hf.differentiable le_rfl x |>.hasDerivAt rw [integral_Iic_of_hasDerivAt_of_tendsto hf.continuous.continuousWithinAt this, sub_zero] · refine hf.continuous_deriv le_rfl |>.integrable_of_hasCompactSupport h2f.deriv |>.integrableOn rw [hasCompactSupport_iff_eventuallyEq, Filter.coclosedCompact_eq_cocompact] at h2f exact h2f.filter_mono _root_.atBot_le_cocompact |>.tendsto open UniformSpace in lemma _root_.HasCompactSupport.enorm_le_lintegral_Ici_deriv {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] {f : ℝ → F} (hf : ContDiff ℝ 1 f) (h'f : HasCompactSupport f) (x : ℝ) : ‖f x‖ₑ ≤ ∫⁻ y in Iic x, ‖deriv f y‖ₑ := by let I : F →L[ℝ] Completion F := Completion.toComplL let f' : ℝ → Completion F := I ∘ f have hf' : ContDiff ℝ 1 f' := hf.continuousLinearMap_comp I have h'f' : HasCompactSupport f' := h'f.comp_left rfl have : ‖f' x‖ₑ ≤ ∫⁻ y in Iic x, ‖deriv f' y‖ₑ := by rw [← HasCompactSupport.integral_Iic_deriv_eq hf' h'f' x] exact enorm_integral_le_lintegral_enorm _ convert this with y · simp [f', I, Completion.enorm_coe] · rw [fderiv_comp_deriv _ I.differentiableAt (hf.differentiable le_rfl _)] simp only [ContinuousLinearMap.fderiv] simp [I] end IicFTC section UnivFTC variable {E : Type*} {f f' : ℝ → E} {m n : E} [NormedAddCommGroup E] [NormedSpace ℝ E] /-- **Fundamental theorem of calculus-2**, on the whole real line When a function has a limit `m` at `-∞` and `n` at `+∞`, and its derivative is integrable, then the integral of the derivative is `n - m`. Note that such a function always has a limit at `-∞` and `+∞`, see `tendsto_limUnder_of_hasDerivAt_of_integrableOn_Iic` and `tendsto_limUnder_of_hasDerivAt_of_integrableOn_Ioi`. -/ theorem integral_of_hasDerivAt_of_tendsto [CompleteSpace E] (hderiv : ∀ x, HasDerivAt f (f' x) x) (hf' : Integrable f') (hbot : Tendsto f atBot (𝓝 m)) (htop : Tendsto f atTop (𝓝 n)) : ∫ x, f' x = n - m := by rw [← setIntegral_univ, ← Set.Iic_union_Ioi (a := 0), setIntegral_union (Iic_disjoint_Ioi le_rfl) measurableSet_Ioi hf'.integrableOn hf'.integrableOn, integral_Iic_of_hasDerivAt_of_tendsto' (fun x _ ↦ hderiv x) hf'.integrableOn hbot, integral_Ioi_of_hasDerivAt_of_tendsto' (fun x _ ↦ hderiv x) hf'.integrableOn htop] abel /-- If a function and its derivative are integrable on the real line, then the integral of the derivative is zero. -/ theorem integral_eq_zero_of_hasDerivAt_of_integrable (hderiv : ∀ x, HasDerivAt f (f' x) x) (hf' : Integrable f') (hf : Integrable f) : ∫ x, f' x = 0 := by by_cases hE : CompleteSpace E; swap · simp [integral, hE] have A : Tendsto f atBot (𝓝 0) := tendsto_zero_of_hasDerivAt_of_integrableOn_Iic (a := 0) (fun x _hx ↦ hderiv x) hf'.integrableOn hf.integrableOn have B : Tendsto f atTop (𝓝 0) := tendsto_zero_of_hasDerivAt_of_integrableOn_Ioi (a := 0) (fun x _hx ↦ hderiv x) hf'.integrableOn hf.integrableOn simpa using integral_of_hasDerivAt_of_tendsto hderiv hf' A B end UnivFTC section IoiChangeVariables open Real open scoped Interval variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] /-- Change-of-variables formula for `Ioi` integrals of vector-valued functions, proved by taking limits from the result for finite intervals. -/ theorem integral_comp_smul_deriv_Ioi {f f' : ℝ → ℝ} {g : ℝ → E} {a : ℝ} (hf : ContinuousOn f <| Ici a) (hft : Tendsto f atTop atTop) (hff' : ∀ x ∈ Ioi a, HasDerivWithinAt f (f' x) (Ioi x) x) (hg_cont : ContinuousOn g <| f '' Ioi a) (hg1 : IntegrableOn g <| f '' Ici a) (hg2 : IntegrableOn (fun x => f' x • (g ∘ f) x) (Ici a)) : (∫ x in Ioi a, f' x • (g ∘ f) x) = ∫ u in Ioi (f a), g u := by have eq : ∀ b : ℝ, a < b → (∫ x in a..b, f' x • (g ∘ f) x) = ∫ u in f a..f b, g u := fun b hb ↦ by have i1 : Ioo (min a b) (max a b) ⊆ Ioi a := by rw [min_eq_left hb.le] exact Ioo_subset_Ioi_self have i2 : [[a, b]] ⊆ Ici a := by rw [uIcc_of_le hb.le]; exact Icc_subset_Ici_self refine intervalIntegral.integral_comp_smul_deriv''' (hf.mono i2) (fun x hx => hff' x <| mem_of_mem_of_subset hx i1) (hg_cont.mono <| image_mono ?_) (hg1.mono_set <| image_mono ?_) (hg2.mono_set i2) <;> assumption rw [integrableOn_Ici_iff_integrableOn_Ioi] at hg2 have t2 := intervalIntegral_tendsto_integral_Ioi _ hg2 tendsto_id have : Ioi (f a) ⊆ f '' Ici a := Ioi_subset_Ici_self.trans <| IsPreconnected.intermediate_value_Ici isPreconnected_Ici left_mem_Ici (le_principal_iff.mpr <| Ici_mem_atTop _) hf hft have t1 := (intervalIntegral_tendsto_integral_Ioi _ (hg1.mono_set this) tendsto_id).comp hft exact tendsto_nhds_unique (Tendsto.congr' (eventuallyEq_of_mem (Ioi_mem_atTop a) eq) t2) t1 /-- Change-of-variables formula for `Ioi` integrals of scalar-valued functions -/ theorem integral_comp_mul_deriv_Ioi {f f' : ℝ → ℝ} {g : ℝ → ℝ} {a : ℝ} (hf : ContinuousOn f <| Ici a) (hft : Tendsto f atTop atTop) (hff' : ∀ x ∈ Ioi a, HasDerivWithinAt f (f' x) (Ioi x) x) (hg_cont : ContinuousOn g <| f '' Ioi a) (hg1 : IntegrableOn g <| f '' Ici a) (hg2 : IntegrableOn (fun x => (g ∘ f) x * f' x) (Ici a)) : (∫ x in Ioi a, (g ∘ f) x * f' x) = ∫ u in Ioi (f a), g u := by have hg2' : IntegrableOn (fun x => f' x • (g ∘ f) x) (Ici a) := by simpa [mul_comm] using hg2 simpa [mul_comm] using integral_comp_smul_deriv_Ioi hf hft hff' hg_cont hg1 hg2' /-- Substitution `y = x ^ p` in integrals over `Ioi 0` -/ theorem integral_comp_rpow_Ioi (g : ℝ → E) {p : ℝ} (hp : p ≠ 0) : (∫ x in Ioi 0, (|p| * x ^ (p - 1)) • g (x ^ p)) = ∫ y in Ioi 0, g y := by let S := Ioi (0 : ℝ) have a1 : ∀ x : ℝ, x ∈ S → HasDerivWithinAt (fun t : ℝ => t ^ p) (p * x ^ (p - 1)) S x := fun x hx => (hasDerivAt_rpow_const (Or.inl (mem_Ioi.mp hx).ne')).hasDerivWithinAt have a2 : InjOn (fun x : ℝ => x ^ p) S := by rcases lt_or_gt_of_ne hp with (h | h) · apply StrictAntiOn.injOn intro x hx y hy hxy rw [← inv_lt_inv₀ (rpow_pos_of_pos hx p) (rpow_pos_of_pos hy p), ← rpow_neg (le_of_lt hx), ← rpow_neg (le_of_lt hy)] exact rpow_lt_rpow (le_of_lt hx) hxy (neg_pos.mpr h) exact StrictMonoOn.injOn fun x hx y _ hxy => rpow_lt_rpow (mem_Ioi.mp hx).le hxy h have a3 : (fun t : ℝ => t ^ p) '' S = S := by ext1 x; rw [mem_image]; constructor · rintro ⟨y, hy, rfl⟩; exact rpow_pos_of_pos hy p · intro hx; refine ⟨x ^ (1 / p), rpow_pos_of_pos hx _, ?_⟩ rw [← rpow_mul (le_of_lt hx), one_div_mul_cancel hp, rpow_one] have := integral_image_eq_integral_abs_deriv_smul measurableSet_Ioi a1 a2 g rw [a3] at this; rw [this] refine setIntegral_congr_fun measurableSet_Ioi ?_ intro x hx; dsimp only rw [abs_mul, abs_of_nonneg (rpow_nonneg (le_of_lt hx) _)] theorem integral_comp_rpow_Ioi_of_pos {g : ℝ → E} {p : ℝ} (hp : 0 < p) : (∫ x in Ioi 0, (p * x ^ (p - 1)) • g (x ^ p)) = ∫ y in Ioi 0, g y := by convert integral_comp_rpow_Ioi g hp.ne' rw [abs_of_nonneg hp.le] theorem integral_comp_mul_left_Ioi (g : ℝ → E) (a : ℝ) {b : ℝ} (hb : 0 < b) : (∫ x in Ioi a, g (b * x)) = b⁻¹ • ∫ x in Ioi (b * a), g x := by have : ∀ c : ℝ, MeasurableSet (Ioi c) := fun c => measurableSet_Ioi rw [← integral_indicator (this a), ← integral_indicator (this (b * a)), ← abs_of_pos (inv_pos.mpr hb), ← Measure.integral_comp_mul_left] congr ext1 x rw [← indicator_comp_right, preimage_const_mul_Ioi _ hb, mul_div_cancel_left₀ _ hb.ne', Function.comp_def] theorem integral_comp_mul_right_Ioi (g : ℝ → E) (a : ℝ) {b : ℝ} (hb : 0 < b) : (∫ x in Ioi a, g (x * b)) = b⁻¹ • ∫ x in Ioi (a * b), g x := by simpa only [mul_comm] using integral_comp_mul_left_Ioi g a hb end IoiChangeVariables section IoiIntegrability open Real open scoped Interval variable {E : Type*} [NormedAddCommGroup E] /-- The substitution `y = x ^ p` in integrals over `Ioi 0` preserves integrability. -/ theorem integrableOn_Ioi_comp_rpow_iff [NormedSpace ℝ E] (f : ℝ → E) {p : ℝ} (hp : p ≠ 0) : IntegrableOn (fun x => (|p| * x ^ (p - 1)) • f (x ^ p)) (Ioi 0) ↔ IntegrableOn f (Ioi 0) := by let S := Ioi (0 : ℝ) have a1 : ∀ x : ℝ, x ∈ S → HasDerivWithinAt (fun t : ℝ => t ^ p) (p * x ^ (p - 1)) S x := fun x hx => (hasDerivAt_rpow_const (Or.inl (mem_Ioi.mp hx).ne')).hasDerivWithinAt have a2 : InjOn (fun x : ℝ => x ^ p) S := by rcases lt_or_gt_of_ne hp with (h | h) · apply StrictAntiOn.injOn intro x hx y hy hxy rw [← inv_lt_inv₀ (rpow_pos_of_pos hx p) (rpow_pos_of_pos hy p), ← rpow_neg (le_of_lt hx), ← rpow_neg (le_of_lt hy)] exact rpow_lt_rpow (le_of_lt hx) hxy (neg_pos.mpr h) exact StrictMonoOn.injOn fun x hx y _hy hxy => rpow_lt_rpow (mem_Ioi.mp hx).le hxy h have a3 : (fun t : ℝ => t ^ p) '' S = S := by ext1 x; rw [mem_image]; constructor · rintro ⟨y, hy, rfl⟩; exact rpow_pos_of_pos hy p · intro hx; refine ⟨x ^ (1 / p), rpow_pos_of_pos hx _, ?_⟩ rw [← rpow_mul (le_of_lt hx), one_div_mul_cancel hp, rpow_one] have := integrableOn_image_iff_integrableOn_abs_deriv_smul measurableSet_Ioi a1 a2 f rw [a3] at this rw [this] refine integrableOn_congr_fun (fun x hx => ?_) measurableSet_Ioi simp_rw [abs_mul, abs_of_nonneg (rpow_nonneg (le_of_lt hx) _)] /-- The substitution `y = x ^ p` in integrals over `Ioi 0` preserves integrability (version without `|p|` factor) -/ theorem integrableOn_Ioi_comp_rpow_iff' [NormedSpace ℝ E] (f : ℝ → E) {p : ℝ} (hp : p ≠ 0) : IntegrableOn (fun x => x ^ (p - 1) • f (x ^ p)) (Ioi 0) ↔ IntegrableOn f (Ioi 0) := by simpa only [← integrableOn_Ioi_comp_rpow_iff f hp, mul_smul] using (integrable_smul_iff (abs_pos.mpr hp).ne' _).symm theorem integrableOn_Ioi_comp_mul_left_iff (f : ℝ → E) (c : ℝ) {a : ℝ} (ha : 0 < a) : IntegrableOn (fun x => f (a * x)) (Ioi c) ↔ IntegrableOn f (Ioi <| a * c) := by rw [← integrable_indicator_iff (measurableSet_Ioi : MeasurableSet <| Ioi c)] rw [← integrable_indicator_iff (measurableSet_Ioi : MeasurableSet <| Ioi <| a * c)] convert integrable_comp_mul_left_iff ((Ioi (a * c)).indicator f) ha.ne' using 2 ext1 x rw [← indicator_comp_right, preimage_const_mul_Ioi _ ha, mul_comm a c, mul_div_cancel_right₀ _ ha.ne', Function.comp_def] theorem integrableOn_Ioi_comp_mul_right_iff (f : ℝ → E) (c : ℝ) {a : ℝ} (ha : 0 < a) : IntegrableOn (fun x => f (x * a)) (Ioi c) ↔ IntegrableOn f (Ioi <| c * a) := by simpa only [mul_comm, mul_zero] using integrableOn_Ioi_comp_mul_left_iff f c ha end IoiIntegrability /-! ## Integration by parts -/ section IntegrationByPartsBilinear variable {E F G : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [NormedAddCommGroup F] [NormedSpace ℝ F] [NormedAddCommGroup G] [NormedSpace ℝ G] {L : E →L[ℝ] F →L[ℝ] G} {u : ℝ → E} {v : ℝ → F} {u' : ℝ → E} {v' : ℝ → F} {m n : G} theorem integral_bilinear_hasDerivAt_eq_sub [CompleteSpace G] (hu : ∀ x, HasDerivAt u (u' x) x) (hv : ∀ x, HasDerivAt v (v' x) x) (huv : Integrable (fun x ↦ L (u x) (v' x) + L (u' x) (v x))) (h_bot : Tendsto (fun x ↦ L (u x) (v x)) atBot (𝓝 m)) (h_top : Tendsto (fun x ↦ L (u x) (v x)) atTop (𝓝 n)) : ∫ (x : ℝ), L (u x) (v' x) + L (u' x) (v x) = n - m := integral_of_hasDerivAt_of_tendsto (fun x ↦ L.hasDerivAt_of_bilinear (hu x) (hv x)) huv h_bot h_top /-- **Integration by parts on (-∞, ∞).** With respect to a general bilinear form. For the specific case of multiplication, see `integral_mul_deriv_eq_deriv_mul`. -/ theorem integral_bilinear_hasDerivAt_right_eq_sub [CompleteSpace G] (hu : ∀ x, HasDerivAt u (u' x) x) (hv : ∀ x, HasDerivAt v (v' x) x) (huv' : Integrable (fun x ↦ L (u x) (v' x))) (hu'v : Integrable (fun x ↦ L (u' x) (v x))) (h_bot : Tendsto (fun x ↦ L (u x) (v x)) atBot (𝓝 m)) (h_top : Tendsto (fun x ↦ L (u x) (v x)) atTop (𝓝 n)) : ∫ (x : ℝ), L (u x) (v' x) = n - m - ∫ (x : ℝ), L (u' x) (v x) := by rw [eq_sub_iff_add_eq, ← integral_add huv' hu'v] exact integral_bilinear_hasDerivAt_eq_sub hu hv (huv'.add hu'v) h_bot h_top /-- **Integration by parts on (-∞, ∞).** With respect to a general bilinear form, assuming moreover that the total function is integrable. -/ theorem integral_bilinear_hasDerivAt_right_eq_neg_left_of_integrable (hu : ∀ x, HasDerivAt u (u' x) x) (hv : ∀ x, HasDerivAt v (v' x) x) (huv' : Integrable (fun x ↦ L (u x) (v' x))) (hu'v : Integrable (fun x ↦ L (u' x) (v x))) (huv : Integrable (fun x ↦ L (u x) (v x))) : ∫ (x : ℝ), L (u x) (v' x) = - ∫ (x : ℝ), L (u' x) (v x) := by by_cases hG : CompleteSpace G; swap · simp [integral, hG] have I : Tendsto (fun x ↦ L (u x) (v x)) atBot (𝓝 0) := tendsto_zero_of_hasDerivAt_of_integrableOn_Iic (a := 0) (fun x _hx ↦ L.hasDerivAt_of_bilinear (hu x) (hv x)) (huv'.add hu'v).integrableOn huv.integrableOn have J : Tendsto (fun x ↦ L (u x) (v x)) atTop (𝓝 0) := tendsto_zero_of_hasDerivAt_of_integrableOn_Ioi (a := 0) (fun x _hx ↦ L.hasDerivAt_of_bilinear (hu x) (hv x)) (huv'.add hu'v).integrableOn huv.integrableOn simp [integral_bilinear_hasDerivAt_right_eq_sub hu hv huv' hu'v I J] end IntegrationByPartsBilinear section IntegrationByPartsAlgebra variable {A : Type*} [NormedRing A] [NormedAlgebra ℝ A] {a : ℝ} {a' b' : A} {u : ℝ → A} {v : ℝ → A} {u' : ℝ → A} {v' : ℝ → A} /-- For finite intervals, see: `intervalIntegral.integral_deriv_mul_eq_sub`. -/ theorem integral_deriv_mul_eq_sub [CompleteSpace A] (hu : ∀ x, HasDerivAt u (u' x) x) (hv : ∀ x, HasDerivAt v (v' x) x) (huv : Integrable (u' * v + u * v')) (h_bot : Tendsto (u * v) atBot (𝓝 a')) (h_top : Tendsto (u * v) atTop (𝓝 b')) : ∫ (x : ℝ), u' x * v x + u x * v' x = b' - a' := integral_of_hasDerivAt_of_tendsto (fun x ↦ (hu x).mul (hv x)) huv h_bot h_top /-- **Integration by parts on (-∞, ∞).** For finite intervals, see: `intervalIntegral.integral_mul_deriv_eq_deriv_mul`. -/ theorem integral_mul_deriv_eq_deriv_mul [CompleteSpace A] (hu : ∀ x, HasDerivAt u (u' x) x) (hv : ∀ x, HasDerivAt v (v' x) x) (huv' : Integrable (u * v')) (hu'v : Integrable (u' * v)) (h_bot : Tendsto (u * v) atBot (𝓝 a')) (h_top : Tendsto (u * v) atTop (𝓝 b')) : ∫ (x : ℝ), u x * v' x = b' - a' - ∫ (x : ℝ), u' x * v x := integral_bilinear_hasDerivAt_right_eq_sub (L := ContinuousLinearMap.mul ℝ A) hu hv huv' hu'v h_bot h_top /-- **Integration by parts on (-∞, ∞).** Version assuming that the total function is integrable -/ theorem integral_mul_deriv_eq_deriv_mul_of_integrable (hu : ∀ x, HasDerivAt u (u' x) x) (hv : ∀ x, HasDerivAt v (v' x) x) (huv' : Integrable (u * v')) (hu'v : Integrable (u' * v)) (huv : Integrable (u * v)) : ∫ (x : ℝ), u x * v' x = - ∫ (x : ℝ), u' x * v x := integral_bilinear_hasDerivAt_right_eq_neg_left_of_integrable (L := ContinuousLinearMap.mul ℝ A) hu hv huv' hu'v huv variable [CompleteSpace A] -- TODO: also apply `Tendsto _ (𝓝[>] a) (𝓝 a')` generalization to -- `integral_Ioi_of_hasDerivAt_of_tendsto` and `integral_Iic_of_hasDerivAt_of_tendsto` /-- For finite intervals, see: `intervalIntegral.integral_deriv_mul_eq_sub`. -/ theorem integral_Ioi_deriv_mul_eq_sub (hu : ∀ x ∈ Ioi a, HasDerivAt u (u' x) x) (hv : ∀ x ∈ Ioi a, HasDerivAt v (v' x) x) (huv : IntegrableOn (u' * v + u * v') (Ioi a)) (h_zero : Tendsto (u * v) (𝓝[>] a) (𝓝 a')) (h_infty : Tendsto (u * v) atTop (𝓝 b')) : ∫ (x : ℝ) in Ioi a, u' x * v x + u x * v' x = b' - a' := by rw [← Ici_diff_left] at h_zero let f := Function.update (u * v) a a' have hderiv : ∀ x ∈ Ioi a, HasDerivAt f (u' x * v x + u x * v' x) x := by intro x (hx : a < x) apply ((hu x hx).mul (hv x hx)).congr_of_eventuallyEq filter_upwards [eventually_ne_nhds hx.ne.symm] with y hy exact Function.update_of_ne hy a' (u * v) have htendsto : Tendsto f atTop (𝓝 b') := by apply h_infty.congr' filter_upwards [eventually_ne_atTop a] with x hx exact (Function.update_of_ne hx a' (u * v)).symm simpa using integral_Ioi_of_hasDerivAt_of_tendsto (continuousWithinAt_update_same.mpr h_zero) hderiv huv htendsto /-- **Integration by parts on (a, ∞).** For finite intervals, see: `intervalIntegral.integral_mul_deriv_eq_deriv_mul`. -/ theorem integral_Ioi_mul_deriv_eq_deriv_mul (hu : ∀ x ∈ Ioi a, HasDerivAt u (u' x) x) (hv : ∀ x ∈ Ioi a, HasDerivAt v (v' x) x) (huv' : IntegrableOn (u * v') (Ioi a)) (hu'v : IntegrableOn (u' * v) (Ioi a)) (h_zero : Tendsto (u * v) (𝓝[>] a) (𝓝 a')) (h_infty : Tendsto (u * v) atTop (𝓝 b')) : ∫ (x : ℝ) in Ioi a, u x * v' x = b' - a' - ∫ (x : ℝ) in Ioi a, u' x * v x := by rw [Pi.mul_def] at huv' hu'v rw [eq_sub_iff_add_eq, ← integral_add huv' hu'v] simpa only [add_comm] using integral_Ioi_deriv_mul_eq_sub hu hv (hu'v.add huv') h_zero h_infty /-- For finite intervals, see: `intervalIntegral.integral_deriv_mul_eq_sub`. -/ theorem integral_Iic_deriv_mul_eq_sub (hu : ∀ x ∈ Iio a, HasDerivAt u (u' x) x) (hv : ∀ x ∈ Iio a, HasDerivAt v (v' x) x) (huv : IntegrableOn (u' * v + u * v') (Iic a)) (h_zero : Tendsto (u * v) (𝓝[<] a) (𝓝 a')) (h_infty : Tendsto (u * v) atBot (𝓝 b')) : ∫ (x : ℝ) in Iic a, u' x * v x + u x * v' x = a' - b' := by rw [← Iic_diff_right] at h_zero let f := Function.update (u * v) a a' have hderiv : ∀ x ∈ Iio a, HasDerivAt f (u' x * v x + u x * v' x) x := by intro x hx apply ((hu x hx).mul (hv x hx)).congr_of_eventuallyEq filter_upwards [Iio_mem_nhds hx] with x (hx : x < a) exact Function.update_of_ne (ne_of_lt hx) a' (u * v) have htendsto : Tendsto f atBot (𝓝 b') := by apply h_infty.congr' filter_upwards [Iio_mem_atBot a] with x (hx : x < a) exact (Function.update_of_ne (ne_of_lt hx) a' (u * v)).symm simpa using integral_Iic_of_hasDerivAt_of_tendsto (continuousWithinAt_update_same.mpr h_zero) hderiv huv htendsto /-- **Integration by parts on (∞, a].** For finite intervals, see: `intervalIntegral.integral_mul_deriv_eq_deriv_mul`. -/ theorem integral_Iic_mul_deriv_eq_deriv_mul (hu : ∀ x ∈ Iio a, HasDerivAt u (u' x) x) (hv : ∀ x ∈ Iio a, HasDerivAt v (v' x) x) (huv' : IntegrableOn (u * v') (Iic a)) (hu'v : IntegrableOn (u' * v) (Iic a)) (h_zero : Tendsto (u * v) (𝓝[<] a) (𝓝 a')) (h_infty : Tendsto (u * v) atBot (𝓝 b')) : ∫ (x : ℝ) in Iic a, u x * v' x = a' - b' - ∫ (x : ℝ) in Iic a, u' x * v x := by rw [Pi.mul_def] at huv' hu'v rw [eq_sub_iff_add_eq, ← integral_add huv' hu'v] simpa only [add_comm] using integral_Iic_deriv_mul_eq_sub hu hv (hu'v.add huv') h_zero h_infty end IntegrationByPartsAlgebra end MeasureTheory
Prod.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import Mathlib.Data.Finset.Prod import Mathlib.Order.Filter.AtTopBot.Basic import Mathlib.Order.Filter.Prod /-! # `Filter.atTop` and `Filter.atBot` filters on products -/ variable {ι ι' α β γ : Type*} open Set namespace Filter theorem prod_atTop_atTop_eq [Preorder α] [Preorder β] : (atTop : Filter α) ×ˢ (atTop : Filter β) = (atTop : Filter (α × β)) := by cases isEmpty_or_nonempty α · subsingleton cases isEmpty_or_nonempty β · subsingleton simpa [atTop, prod_iInf_left, prod_iInf_right, iInf_prod] using iInf_comm lemma tendsto_finset_prod_atTop : Tendsto (fun (p : Finset ι × Finset ι') ↦ p.1 ×ˢ p.2) atTop atTop := by classical apply Monotone.tendsto_atTop_atTop · intro p q hpq simpa using Finset.product_subset_product hpq.1 hpq.2 · intro b use (Finset.image Prod.fst b, Finset.image Prod.snd b) exact Finset.subset_product theorem prod_atBot_atBot_eq [Preorder α] [Preorder β] : (atBot : Filter α) ×ˢ (atBot : Filter β) = (atBot : Filter (α × β)) := @prod_atTop_atTop_eq αᵒᵈ βᵒᵈ _ _ theorem prod_map_atTop_eq {α₁ α₂ β₁ β₂ : Type*} [Preorder β₁] [Preorder β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : map u₁ atTop ×ˢ map u₂ atTop = map (Prod.map u₁ u₂) atTop := by rw [prod_map_map_eq, prod_atTop_atTop_eq, Prod.map_def] theorem prod_map_atBot_eq {α₁ α₂ β₁ β₂ : Type*} [Preorder β₁] [Preorder β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : map u₁ atBot ×ˢ map u₂ atBot = map (Prod.map u₁ u₂) atBot := @prod_map_atTop_eq _ _ β₁ᵒᵈ β₂ᵒᵈ _ _ _ _ theorem tendsto_atBot_diagonal [Preorder α] : Tendsto (fun a : α => (a, a)) atBot atBot := by rw [← prod_atBot_atBot_eq] exact tendsto_id.prodMk tendsto_id theorem tendsto_atTop_diagonal [Preorder α] : Tendsto (fun a : α => (a, a)) atTop atTop := by rw [← prod_atTop_atTop_eq] exact tendsto_id.prodMk tendsto_id theorem Tendsto.prod_map_prod_atBot [Preorder γ] {F : Filter α} {G : Filter β} {f : α → γ} {g : β → γ} (hf : Tendsto f F atBot) (hg : Tendsto g G atBot) : Tendsto (Prod.map f g) (F ×ˢ G) atBot := by rw [← prod_atBot_atBot_eq] exact hf.prodMap hg theorem Tendsto.prod_map_prod_atTop [Preorder γ] {F : Filter α} {G : Filter β} {f : α → γ} {g : β → γ} (hf : Tendsto f F atTop) (hg : Tendsto g G atTop) : Tendsto (Prod.map f g) (F ×ˢ G) atTop := by rw [← prod_atTop_atTop_eq] exact hf.prodMap hg theorem Tendsto.prod_atBot [Preorder α] [Preorder γ] {f g : α → γ} (hf : Tendsto f atBot atBot) (hg : Tendsto g atBot atBot) : Tendsto (Prod.map f g) atBot atBot := by rw [← prod_atBot_atBot_eq] exact hf.prod_map_prod_atBot hg theorem Tendsto.prod_atTop [Preorder α] [Preorder γ] {f g : α → γ} (hf : Tendsto f atTop atTop) (hg : Tendsto g atTop atTop) : Tendsto (Prod.map f g) atTop atTop := by rw [← prod_atTop_atTop_eq] exact hf.prod_map_prod_atTop hg theorem eventually_atBot_prod_self [Nonempty α] [Preorder α] [IsDirected α (· ≥ ·)] {p : α × α → Prop} : (∀ᶠ x in atBot, p x) ↔ ∃ a, ∀ k l, k ≤ a → l ≤ a → p (k, l) := by simp [← prod_atBot_atBot_eq, (@atBot_basis α _ _).prod_self.eventually_iff] theorem eventually_atTop_prod_self [Nonempty α] [Preorder α] [IsDirected α (· ≤ ·)] {p : α × α → Prop} : (∀ᶠ x in atTop, p x) ↔ ∃ a, ∀ k l, a ≤ k → a ≤ l → p (k, l) := eventually_atBot_prod_self (α := αᵒᵈ) theorem eventually_atBot_prod_self' [Nonempty α] [Preorder α] [IsDirected α (· ≥ ·)] {p : α × α → Prop} : (∀ᶠ x in atBot, p x) ↔ ∃ a, ∀ k ≤ a, ∀ l ≤ a, p (k, l) := by simp only [eventually_atBot_prod_self, forall_cond_comm] theorem eventually_atTop_prod_self' [Nonempty α] [Preorder α] [IsDirected α (· ≤ ·)] {p : α × α → Prop} : (∀ᶠ x in atTop, p x) ↔ ∃ a, ∀ k ≥ a, ∀ l ≥ a, p (k, l) := by simp only [eventually_atTop_prod_self, forall_cond_comm] theorem eventually_atTop_curry [Preorder α] [Preorder β] {p : α × β → Prop} (hp : ∀ᶠ x : α × β in Filter.atTop, p x) : ∀ᶠ k in atTop, ∀ᶠ l in atTop, p (k, l) := by rw [← prod_atTop_atTop_eq] at hp exact hp.curry theorem eventually_atBot_curry [Preorder α] [Preorder β] {p : α × β → Prop} (hp : ∀ᶠ x : α × β in Filter.atBot, p x) : ∀ᶠ k in atBot, ∀ᶠ l in atBot, p (k, l) := @eventually_atTop_curry αᵒᵈ βᵒᵈ _ _ _ hp end Filter
Jacobson.lean
/- Copyright (c) 2024 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.RingTheory.Jacobson.Ring import Mathlib.RingTheory.Spectrum.Prime.Noetherian import Mathlib.Topology.JacobsonSpace /-! # The prime spectrum of a jacobson ring ## Main results - `PrimeSpectrum.exists_isClosed_singleton_of_isJacobson`: The spectrum of a jacobson ring is a jacobson space. - `PrimeSpectrum.isOpen_singleton_tfae_of_isNoetherian_of_isJacobson`: If `R` is both noetherian and jacobson, then the following are equivalent for `x : Spec R`: 1. `{x}` is open (i.e. `x` is an isolated point) 2. `{x}` is clopen 3. `{x}` is both closed and stable under generalization (i.e. `x` is both a minimal prime and a maximal ideal) -/ open Ideal variable {R : Type*} [CommRing R] namespace PrimeSpectrum lemma exists_isClosed_singleton_of_isJacobsonRing [IsJacobsonRing R] (s : (Set (PrimeSpectrum R))) (hs : IsOpen s) (hs' : s.Nonempty) : ∃ x ∈ s, IsClosed {x} := by simp_rw [isClosed_singleton_iff_isMaximal] obtain ⟨I, hI'⟩ := (isClosed_iff_zeroLocus_ideal _).mp hs.isClosed_compl simp_rw [← @Set.notMem_compl_iff _ s, hI', mem_zeroLocus] have := hs'.ne_empty contrapose! this simp_rw [not_imp_not] at this rw [← Set.compl_univ, eq_compl_comm, hI', eq_comm, ← zeroLocus_bot, zeroLocus_eq_iff, Ideal.radical_eq_jacobson, Ideal.radical_eq_jacobson] refine le_antisymm (le_sInf ?_) (Ideal.jacobson_mono bot_le) rintro x ⟨-, hx⟩ exact sInf_le ⟨this ⟨x, hx.isPrime⟩ hx, hx⟩ instance [IsJacobsonRing R] : JacobsonSpace (PrimeSpectrum R) := by rw [jacobsonSpace_iff_locallyClosed] rintro S hS ⟨U, Z, hU, hZ, rfl⟩ simp only [← isClosed_compl_iff, isClosed_iff_zeroLocus_ideal, @compl_eq_comm _ U] at hU hZ obtain ⟨⟨I, rfl⟩, ⟨J, rfl⟩⟩ := And.intro hU hZ simp only [Set.nonempty_iff_ne_empty, ne_eq, Set.inter_assoc, ← Set.disjoint_iff_inter_eq_empty, Set.disjoint_compl_left_iff_subset, zeroLocus_subset_zeroLocus_iff, Ideal.radical_eq_jacobson, Ideal.jacobson, le_sInf_iff] at hS ⊢ contrapose! hS rintro x ⟨hJx, hx⟩ exact @hS ⟨x, hx.isPrime⟩ ⟨hJx, (isClosed_singleton_iff_isMaximal _).mpr hx⟩ lemma isJacobsonRing_iff_jacobsonSpace : IsJacobsonRing R ↔ JacobsonSpace (PrimeSpectrum R) := by refine ⟨fun _ ↦ inferInstance, fun H ↦ ⟨fun I hI ↦ le_antisymm ?_ Ideal.le_jacobson⟩⟩ rw [← I.isRadical_jacobson.radical] conv_rhs => rw [← hI.radical] simp_rw [← vanishingIdeal_zeroLocus_eq_radical] apply vanishingIdeal_anti_mono rw [← H.1 (isClosed_zeroLocus I), (isClosed_zeroLocus _).closure_subset_iff] rintro x ⟨hx : I ≤ x.asIdeal, hx'⟩ change jacobson I ≤ x.asIdeal exact sInf_le ⟨hx, (isClosed_singleton_iff_isMaximal _).mp hx'⟩ /-- If `R` is both noetherian and jacobson, then the following are equivalent for `x : Spec R`: 1. `{x}` is open (i.e. `x` is an isolated point) 2. `{x}` is clopen 3. `{x}` is both closed and stable under generalization (i.e. `x` is both a minimal prime and a maximal ideal) -/ lemma isOpen_singleton_tfae_of_isNoetherian_of_isJacobsonRing [IsNoetherianRing R] [IsJacobsonRing R] (x : PrimeSpectrum R) : List.TFAE [IsOpen {x}, IsClopen {x}, IsClosed {x} ∧ StableUnderGeneralization {x}] := by tfae_have 1 → 2 | h => by obtain ⟨y, rfl : y = x, h'⟩ := exists_isClosed_singleton_of_isJacobsonRing _ h ⟨x, Set.mem_singleton x⟩ exact ⟨h', h⟩ tfae_have 2 → 3 | h => ⟨h.isClosed, h.isOpen.stableUnderGeneralization⟩ tfae_have 3 → 1 | ⟨h₁, h₂⟩ => by rw [isClosed_singleton_iff_isMaximal, ← isMax_iff] at h₁ suffices {x} = (⋃ p ∈ { p : PrimeSpectrum R | IsMin p ∧ p ≠ x }, closure {p})ᶜ by rw [this, isOpen_compl_iff] refine Set.Finite.isClosed_biUnion ?_ (fun _ _ ↦ isClosed_closure) exact (finite_setOf_isMin R).subset fun x h ↦ h.1 ext p simp only [Set.mem_singleton_iff, ne_eq, Set.mem_setOf_eq, Set.compl_iUnion, Set.mem_iInter, Set.mem_compl_iff, and_imp, ← specializes_iff_mem_closure, ← le_iff_specializes, not_imp_not] constructor · rintro rfl _ _ rw [stableUnderGeneralization_singleton, ← isMin_iff] at h₂ exact h₂.eq_of_le · intros hp apply h₁.eq_of_ge obtain ⟨q, hq, hq'⟩ := Ideal.exists_minimalPrimes_le (J := p.asIdeal) bot_le exact (hp ⟨q, hq.1.1⟩ (isMin_iff.mpr hq) hq').ge.trans hq' tfae_finish end PrimeSpectrum
InjSurj.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.Group.Defs import Mathlib.Logic.Function.Basic import Mathlib.Tactic.Spread /-! # Lifting algebraic data classes along injective/surjective maps This file provides definitions that are meant to deal with situations such as the following: Suppose that `G` is a group, and `H` is a type endowed with `One H`, `Mul H`, and `Inv H`. Suppose furthermore, that `f : G → H` is a surjective map that respects the multiplication, and the unit elements. Then `H` satisfies the group axioms. The relevant definition in this case is `Function.Surjective.group`. Dually, there is also `Function.Injective.group`. And there are versions for (additive) (commutative) semigroups/monoids. Note that the `nsmul` and `zsmul` hypotheses in the declarations in this file are declared as `∀ x n, f (n • x) = n • f x`, with the binders in a slightly unnatural order, as they are `to_additive`ized from the versions for `^`. -/ namespace Function /-! ### Injective -/ assert_not_exists MonoidWithZero DenselyOrdered AddMonoidWithOne namespace Injective variable {M₁ : Type*} {M₂ : Type*} [Mul M₁] /-- A type endowed with `*` is a semigroup, if it admits an injective map that preserves `*` to a semigroup. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `+` is an additive semigroup, if it admits an injective map that preserves `+` to an additive semigroup. -/] protected abbrev semigroup [Semigroup M₂] (f : M₁ → M₂) (hf : Injective f) (mul : ∀ x y, f (x * y) = f x * f y) : Semigroup M₁ := { ‹Mul M₁› with mul_assoc := fun x y z => hf <| by rw [mul, mul, mul, mul, mul_assoc] } /-- A type endowed with `*` is a commutative magma, if it admits a surjective map that preserves `*` from a commutative magma. -/ @[to_additive -- See note [reducible non-instances] /-- A type endowed with `+` is an additive commutative semigroup, if it admits a surjective map that preserves `+` from an additive commutative semigroup. -/] protected abbrev commMagma [CommMagma M₂] (f : M₁ → M₂) (hf : Injective f) (mul : ∀ x y, f (x * y) = f x * f y) : CommMagma M₁ where mul_comm x y := hf <| by rw [mul, mul, mul_comm] /-- A type endowed with `*` is a commutative semigroup, if it admits an injective map that preserves `*` to a commutative semigroup. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `+` is an additive commutative semigroup,if it admits an injective map that preserves `+` to an additive commutative semigroup. -/] protected abbrev commSemigroup [CommSemigroup M₂] (f : M₁ → M₂) (hf : Injective f) (mul : ∀ x y, f (x * y) = f x * f y) : CommSemigroup M₁ where toSemigroup := hf.semigroup f mul __ := hf.commMagma f mul /-- A type has left-cancellative multiplication, if it admits an injective map that preserves `*` to another type with left-cancellative multiplication. -/ @[to_additive /-- A type has left-cancellative addition, if it admits an injective map that preserves `+` to another type with left-cancellative addition. -/] protected theorem isLeftCancelMul [Mul M₂] [IsLeftCancelMul M₂] (f : M₁ → M₂) (hf : Injective f) (mul : ∀ x y, f (x * y) = f x * f y) : IsLeftCancelMul M₁ where mul_left_cancel x y z H := hf <| mul_left_cancel <| by simpa only [mul] using congrArg f H /-- A type has right-cancellative multiplication, if it admits an injective map that preserves `*` to another type with right-cancellative multiplication. -/ @[to_additive /-- A type has right-cancellative addition, if it admits an injective map that preserves `+` to another type with right-cancellative addition. -/] protected theorem isRightCancelMul [Mul M₂] [IsRightCancelMul M₂] (f : M₁ → M₂) (hf : Injective f) (mul : ∀ x y, f (x * y) = f x * f y) : IsRightCancelMul M₁ where mul_right_cancel x y z H := hf <| mul_right_cancel <| by simpa only [mul] using congrArg f H /-- A type has cancellative multiplication, if it admits an injective map that preserves `*` to another type with cancellative multiplication. -/ @[to_additive /-- A type has cancellative addition, if it admits an injective map that preserves `+` to another type with cancellative addition. -/] protected theorem isCancelMul [Mul M₂] [IsCancelMul M₂] (f : M₁ → M₂) (hf : Injective f) (mul : ∀ x y, f (x * y) = f x * f y) : IsCancelMul M₁ where __ := hf.isLeftCancelMul f mul __ := hf.isRightCancelMul f mul /-- A type endowed with `*` is a left cancel semigroup, if it admits an injective map that preserves `*` to a left cancel semigroup. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `+` is an additive left cancel semigroup, if it admits an injective map that preserves `+` to an additive left cancel semigroup. -/] protected abbrev leftCancelSemigroup [LeftCancelSemigroup M₂] (f : M₁ → M₂) (hf : Injective f) (mul : ∀ x y, f (x * y) = f x * f y) : LeftCancelSemigroup M₁ := { hf.semigroup f mul, hf.isLeftCancelMul f mul with } /-- A type endowed with `*` is a right cancel semigroup, if it admits an injective map that preserves `*` to a right cancel semigroup. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `+` is an additive right cancel semigroup, if it admits an injective map that preserves `+` to an additive right cancel semigroup. -/] protected abbrev rightCancelSemigroup [RightCancelSemigroup M₂] (f : M₁ → M₂) (hf : Injective f) (mul : ∀ x y, f (x * y) = f x * f y) : RightCancelSemigroup M₁ := { hf.semigroup f mul, hf.isRightCancelMul f mul with } variable [One M₁] /-- A type endowed with `1` and `*` is a `MulOneClass`, if it admits an injective map that preserves `1` and `*` to a `MulOneClass`. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an `AddZeroClass`, if it admits an injective map that preserves `0` and `+` to an `AddZeroClass`. -/] protected abbrev mulOneClass [MulOneClass M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : MulOneClass M₁ := { ‹One M₁›, ‹Mul M₁› with one_mul := fun x => hf <| by rw [mul, one, one_mul], mul_one := fun x => hf <| by rw [mul, one, mul_one] } variable [Pow M₁ ℕ] /-- A type endowed with `1` and `*` is a monoid, if it admits an injective map that preserves `1` and `*` to a monoid. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive monoid, if it admits an injective map that preserves `0` and `+` to an additive monoid. See note [reducible non-instances]. -/] protected abbrev monoid [Monoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : Monoid M₁ := { hf.mulOneClass f one mul, hf.semigroup f mul with npow := fun n x => x ^ n, npow_zero := fun x => hf <| by rw [npow, one, pow_zero], npow_succ := fun n x => hf <| by rw [npow, pow_succ, mul, npow] } /-- A type endowed with `1` and `*` is a left cancel monoid, if it admits an injective map that preserves `1` and `*` to a left cancel monoid. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive left cancel monoid, if it admits an injective map that preserves `0` and `+` to an additive left cancel monoid. -/] protected abbrev leftCancelMonoid [LeftCancelMonoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : LeftCancelMonoid M₁ := { hf.leftCancelSemigroup f mul, hf.monoid f one mul npow with } /-- A type endowed with `1` and `*` is a right cancel monoid, if it admits an injective map that preserves `1` and `*` to a right cancel monoid. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive left cancel monoid,if it admits an injective map that preserves `0` and `+` to an additive left cancel monoid. -/] protected abbrev rightCancelMonoid [RightCancelMonoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : RightCancelMonoid M₁ := { hf.rightCancelSemigroup f mul, hf.monoid f one mul npow with } /-- A type endowed with `1` and `*` is a cancel monoid, if it admits an injective map that preserves `1` and `*` to a cancel monoid. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive left cancel monoid,if it admits an injective map that preserves `0` and `+` to an additive left cancel monoid. -/] protected abbrev cancelMonoid [CancelMonoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : CancelMonoid M₁ := { hf.leftCancelMonoid f one mul npow, hf.rightCancelMonoid f one mul npow with } /-- A type endowed with `1` and `*` is a commutative monoid, if it admits an injective map that preserves `1` and `*` to a commutative monoid. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive commutative monoid, if it admits an injective map that preserves `0` and `+` to an additive commutative monoid. -/] protected abbrev commMonoid [CommMonoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : CommMonoid M₁ := { hf.monoid f one mul npow, hf.commSemigroup f mul with } /-- A type endowed with `1` and `*` is a cancel commutative monoid if it admits an injective map that preserves `1` and `*` to a cancel commutative monoid. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive cancel commutative monoid if it admits an injective map that preserves `0` and `+` to an additive cancel commutative monoid. -/] protected abbrev cancelCommMonoid [CancelCommMonoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : CancelCommMonoid M₁ := { hf.leftCancelSemigroup f mul, hf.commMonoid f one mul npow with } /-- A type has an involutive inversion if it admits a surjective map that preserves `⁻¹` to a type which has an involutive inversion. See note [reducible non-instances] -/ @[to_additive /-- A type has an involutive negation if it admits a surjective map that preserves `-` to a type which has an involutive negation. -/] protected abbrev involutiveInv {M₁ : Type*} [Inv M₁] [InvolutiveInv M₂] (f : M₁ → M₂) (hf : Injective f) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : InvolutiveInv M₁ where inv := Inv.inv inv_inv x := hf <| by rw [inv, inv, inv_inv] variable [Inv M₁] /-- A type endowed with `1` and `⁻¹` is a `InvOneClass`, if it admits an injective map that preserves `1` and `⁻¹` to a `InvOneClass`. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and unary `-` is an `NegZeroClass`, if it admits an injective map that preserves `0` and unary `-` to an `NegZeroClass`. -/] protected abbrev invOneClass [InvOneClass M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) : InvOneClass M₁ := { ‹One M₁›, ‹Inv M₁› with inv_one := hf <| by rw [inv, one, inv_one] } variable [Div M₁] [Pow M₁ ℤ] /-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `DivInvMonoid` if it admits an injective map that preserves `1`, `*`, `⁻¹`, and `/` to a `DivInvMonoid`. See note [reducible non-instances]. -/ @[to_additive subNegMonoid /-- A type endowed with `0`, `+`, unary `-`, and binary `-` is a `SubNegMonoid` if it admits an injective map that preserves `0`, `+`, unary `-`, and binary `-` to a `SubNegMonoid`. This version takes custom `nsmul` and `zsmul` as `[SMul ℕ M₁]` and `[SMul ℤ M₁]` arguments. -/] protected abbrev divInvMonoid [DivInvMonoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : DivInvMonoid M₁ := { hf.monoid f one mul npow, ‹Inv M₁›, ‹Div M₁› with zpow := fun n x => x ^ n, zpow_zero' := fun x => hf <| by rw [zpow, zpow_zero, one], zpow_succ' := fun n x => hf <| by rw [zpow, mul, zpow_natCast, pow_succ, zpow, zpow_natCast], zpow_neg' := fun n x => hf <| by rw [zpow, zpow_negSucc, inv, zpow, zpow_natCast], div_eq_mul_inv := fun x y => hf <| by rw [div, mul, inv, div_eq_mul_inv] } /-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `DivInvOneMonoid` if it admits an injective map that preserves `1`, `*`, `⁻¹`, and `/` to a `DivInvOneMonoid`. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0`, `+`, unary `-`, and binary `-` is a `SubNegZeroMonoid` if it admits an injective map that preserves `0`, `+`, unary `-`, and binary `-` to a `SubNegZeroMonoid`. This version takes custom `nsmul` and `zsmul` as `[SMul ℕ M₁]` and `[SMul ℤ M₁]` arguments. -/] protected abbrev divInvOneMonoid [DivInvOneMonoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : DivInvOneMonoid M₁ := { hf.divInvMonoid f one mul inv div npow zpow, hf.invOneClass f one inv with } /-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `DivisionMonoid` if it admits an injective map that preserves `1`, `*`, `⁻¹`, and `/` to a `DivisionMonoid`. See note [reducible non-instances] -/ @[to_additive /-- A type endowed with `0`, `+`, unary `-`, and binary `-` is a `SubtractionMonoid` if it admits an injective map that preserves `0`, `+`, unary `-`, and binary `-` to a `SubtractionMonoid`. This version takes custom `nsmul` and `zsmul` as `[SMul ℕ M₁]` and `[SMul ℤ M₁]` arguments. -/] protected abbrev divisionMonoid [DivisionMonoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : DivisionMonoid M₁ := { hf.divInvMonoid f one mul inv div npow zpow, hf.involutiveInv f inv with mul_inv_rev := fun x y => hf <| by rw [inv, mul, mul_inv_rev, mul, inv, inv], inv_eq_of_mul := fun x y h => hf <| by rw [inv, inv_eq_of_mul_eq_one_right (by rw [← mul, h, one])] } /-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `DivisionCommMonoid` if it admits an injective map that preserves `1`, `*`, `⁻¹`, and `/` to a `DivisionCommMonoid`. See note [reducible non-instances]. -/ @[to_additive subtractionCommMonoid /-- A type endowed with `0`, `+`, unary `-`, and binary `-` is a `SubtractionCommMonoid` if it admits an injective map that preserves `0`, `+`, unary `-`, and binary `-` to a `SubtractionCommMonoid`. This version takes custom `nsmul` and `zsmul` as `[SMul ℕ M₁]` and `[SMul ℤ M₁]` arguments. -/] protected abbrev divisionCommMonoid [DivisionCommMonoid M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : DivisionCommMonoid M₁ := { hf.divisionMonoid f one mul inv div npow zpow, hf.commSemigroup f mul with } /-- A type endowed with `1`, `*` and `⁻¹` is a group, if it admits an injective map that preserves `1`, `*` and `⁻¹` to a group. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive group, if it admits an injective map that preserves `0` and `+` to an additive group. -/] protected abbrev group [Group M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : Group M₁ := { hf.divInvMonoid f one mul inv div npow zpow with inv_mul_cancel := fun x => hf <| by rw [mul, inv, inv_mul_cancel, one] } /-- A type endowed with `1`, `*` and `⁻¹` is a commutative group, if it admits an injective map that preserves `1`, `*` and `⁻¹` to a commutative group. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive commutative group, if it admits an injective map that preserves `0` and `+` to an additive commutative group. -/] protected abbrev commGroup [CommGroup M₂] (f : M₁ → M₂) (hf : Injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : CommGroup M₁ := { hf.commMonoid f one mul npow, hf.group f one mul inv div npow zpow with } end Injective /-! ### Surjective -/ namespace Surjective variable {M₁ : Type*} {M₂ : Type*} [Mul M₂] /-- A type endowed with `*` is a semigroup, if it admits a surjective map that preserves `*` from a semigroup. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `+` is an additive semigroup, if it admits a surjective map that preserves `+` from an additive semigroup. -/] protected abbrev semigroup [Semigroup M₁] (f : M₁ → M₂) (hf : Surjective f) (mul : ∀ x y, f (x * y) = f x * f y) : Semigroup M₂ := { ‹Mul M₂› with mul_assoc := hf.forall₃.2 fun x y z => by simp only [← mul, mul_assoc] } /-- A type endowed with `*` is a commutative semigroup, if it admits a surjective map that preserves `*` from a commutative semigroup. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `+` is an additive commutative semigroup, if it admits a surjective map that preserves `+` from an additive commutative semigroup. -/] protected abbrev commMagma [CommMagma M₁] (f : M₁ → M₂) (hf : Surjective f) (mul : ∀ x y, f (x * y) = f x * f y) : CommMagma M₂ where mul_comm := hf.forall₂.2 fun x y => by rw [← mul, ← mul, mul_comm] /-- A type endowed with `*` is a commutative semigroup, if it admits a surjective map that preserves `*` from a commutative semigroup. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `+` is an additive commutative semigroup, if it admits a surjective map that preserves `+` from an additive commutative semigroup. -/] protected abbrev commSemigroup [CommSemigroup M₁] (f : M₁ → M₂) (hf : Surjective f) (mul : ∀ x y, f (x * y) = f x * f y) : CommSemigroup M₂ where toSemigroup := hf.semigroup f mul __ := hf.commMagma f mul variable [One M₂] /-- A type endowed with `1` and `*` is a `MulOneClass`, if it admits a surjective map that preserves `1` and `*` from a `MulOneClass`. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an `AddZeroClass`, if it admits a surjective map that preserves `0` and `+` to an `AddZeroClass`. -/] protected abbrev mulOneClass [MulOneClass M₁] (f : M₁ → M₂) (hf : Surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : MulOneClass M₂ := { ‹One M₂›, ‹Mul M₂› with one_mul := hf.forall.2 fun x => by rw [← one, ← mul, one_mul], mul_one := hf.forall.2 fun x => by rw [← one, ← mul, mul_one] } variable [Pow M₂ ℕ] /-- A type endowed with `1` and `*` is a monoid, if it admits a surjective map that preserves `1` and `*` to a monoid. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive monoid, if it admits a surjective map that preserves `0` and `+` to an additive monoid. This version takes a custom `nsmul` as a `[SMul ℕ M₂]` argument. -/] protected abbrev monoid [Monoid M₁] (f : M₁ → M₂) (hf : Surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : Monoid M₂ := { hf.semigroup f mul, hf.mulOneClass f one mul with npow := fun n x => x ^ n, npow_zero := hf.forall.2 fun x => by rw [← npow, pow_zero, ← one], npow_succ := fun n => hf.forall.2 fun x => by rw [← npow, pow_succ, ← npow, ← mul] } /-- A type endowed with `1` and `*` is a commutative monoid, if it admits a surjective map that preserves `1` and `*` from a commutative monoid. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive commutative monoid, if it admits a surjective map that preserves `0` and `+` to an additive commutative monoid. -/] protected abbrev commMonoid [CommMonoid M₁] (f : M₁ → M₂) (hf : Surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : CommMonoid M₂ := { hf.commSemigroup f mul, hf.monoid f one mul npow with } /-- A type has an involutive inversion if it admits a surjective map that preserves `⁻¹` to a type which has an involutive inversion. See note [reducible non-instances] -/ @[to_additive /-- A type has an involutive negation if it admits a surjective map that preserves `-` to a type which has an involutive negation. -/] protected abbrev involutiveInv {M₂ : Type*} [Inv M₂] [InvolutiveInv M₁] (f : M₁ → M₂) (hf : Surjective f) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : InvolutiveInv M₂ where inv := Inv.inv inv_inv := hf.forall.2 fun x => by rw [← inv, ← inv, inv_inv] variable [Inv M₂] [Div M₂] [Pow M₂ ℤ] /-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `DivInvMonoid` if it admits a surjective map that preserves `1`, `*`, `⁻¹`, and `/` to a `DivInvMonoid`. See note [reducible non-instances]. -/ @[to_additive subNegMonoid /-- A type endowed with `0`, `+`, unary `-`, and binary `-` is a `SubNegMonoid` if it admits a surjective map that preserves `0`, `+`, unary `-`, and binary `-` to a `SubNegMonoid`. -/] protected abbrev divInvMonoid [DivInvMonoid M₁] (f : M₁ → M₂) (hf : Surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : DivInvMonoid M₂ := { hf.monoid f one mul npow, ‹Div M₂›, ‹Inv M₂› with zpow := fun n x => x ^ n, zpow_zero' := hf.forall.2 fun x => by rw [← zpow, zpow_zero, ← one], zpow_succ' := fun n => hf.forall.2 fun x => by rw [← zpow, ← zpow, zpow_natCast, zpow_natCast, pow_succ, ← mul], zpow_neg' := fun n => hf.forall.2 fun x => by rw [← zpow, ← zpow, zpow_negSucc, zpow_natCast, inv], div_eq_mul_inv := hf.forall₂.2 fun x y => by rw [← inv, ← mul, ← div, div_eq_mul_inv] } /-- A type endowed with `1`, `*` and `⁻¹` is a group, if it admits a surjective map that preserves `1`, `*` and `⁻¹` to a group. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive group, if it admits a surjective map that preserves `0` and `+` to an additive group. -/] protected abbrev group [Group M₁] (f : M₁ → M₂) (hf : Surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : Group M₂ := { hf.divInvMonoid f one mul inv div npow zpow with inv_mul_cancel := hf.forall.2 fun x => by rw [← inv, ← mul, inv_mul_cancel, one] } /-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a commutative group, if it admits a surjective map that preserves `1`, `*`, `⁻¹`, and `/` from a commutative group. See note [reducible non-instances]. -/ @[to_additive /-- A type endowed with `0` and `+` is an additive commutative group, if it admits a surjective map that preserves `0` and `+` to an additive commutative group. -/] protected abbrev commGroup [CommGroup M₁] (f : M₁ → M₂) (hf : Surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : CommGroup M₂ := { hf.commMonoid f one mul npow, hf.group f one mul inv div npow zpow with } end Surjective end Function
Abelian.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.Colimits import Mathlib.Algebra.Category.ModuleCat.Presheaf.Limits import Mathlib.Algebra.Category.ModuleCat.Abelian import Mathlib.CategoryTheory.Abelian.Basic /-! # The category of presheaves of modules is abelian -/ universe v v₁ u₁ u open CategoryTheory Category Limits namespace PresheafOfModules variable {C : Type u₁} [Category.{v₁} C] (R : Cᵒᵖ ⥤ RingCat.{u}) noncomputable instance : IsNormalEpiCategory (PresheafOfModules.{v} R) where normalEpiOfEpi p _ := ⟨NormalEpi.mk _ (kernel.ι p) (kernel.condition _) (evaluationJointlyReflectsColimits _ _ (fun _ => Abelian.isColimitMapCoconeOfCokernelCoforkOfπ _ _))⟩ noncomputable instance : IsNormalMonoCategory (PresheafOfModules.{v} R) where normalMonoOfMono i _ := ⟨NormalMono.mk _ (cokernel.π i) (cokernel.condition _) (evaluationJointlyReflectsLimits _ _ (fun _ => Abelian.isLimitMapConeOfKernelForkOfι _ _))⟩ noncomputable instance : Abelian (PresheafOfModules.{v} R) where end PresheafOfModules
ssrfun.v
From mathcomp Require Import ssreflect. From Corelib Require Export ssrfun. From mathcomp Require Export ssrnotations. #[export] Set Warnings "-overwriting-delimiting-key". (* remove above line when requiring Rocq >= 9.0 *) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. (******************) (* v9.1 additions *) (******************) #[export] Set Warnings "-hiding-delimiting-key". Delimit Scope function_scope with FUN. Declare Scope fun_scope. Close Scope fun_scope. Definition injective2 (rT aT1 aT2 : Type) (f : aT1 -> aT2 -> rT) := forall (x1 x2 : aT1) (y1 y2 : aT2), f x1 y1 = f x2 y2 -> (x1 = x2) * (y1 = y2). Arguments injective2 [rT aT1 aT2] f. Lemma inj_omap {aT rT : Type} (f : aT -> rT) : injective f -> injective (omap f). Proof. by move=> injf [?|] [?|] //= [/injf->]. Qed. Lemma omap_id {T : Type} (x : option T) : omap id x = x. Proof. by case: x. Qed. Lemma eq_omap {aT rT : Type} (f g : aT -> rT) : f =1 g -> omap f =1 omap g. Proof. by move=> Ef [?|] //=; rewrite Ef. Qed. Lemma omapK {aT rT : Type} (f : aT -> rT) (g : rT -> aT) : cancel f g -> cancel (omap f) (omap g). Proof. by move=> fK [?|] //=; rewrite fK. Qed. Definition idempotent_op (S : Type) (op : S -> S -> S) := forall x, op x x = x. #[deprecated(since="mathcomp 2.3.0", note="use `idempotent_op` instead")] Notation idempotent:= idempotent_op (only parsing). Definition idempotent_fun (U : Type) (f : U -> U) := f \o f =1 f. Lemma inr_inj {A B} : injective (@inr A B). Proof. by move=> ? ? []. Qed. Lemma inl_inj {A B} : injective (@inl A B). Proof. by move=> ? ? []. Qed. (**********************) (* not yet backported *) (**********************) Lemma taggedK {I : Type} (T_ : I -> Type) (s : {i : I & T_ i}) : Tagged T_ (tagged s) = s. Proof. by case: s. Qed. Definition swap_pair {T1 T2 : Type} (x : T1 * T2) := (x.2, x.1). (* Note that this lemma coudn't be an instance of the [involutive] predicate. *) Lemma swap_pairK {T1 T2 : Type} : @cancel _ (T1 * T2) swap_pair swap_pair. Proof. by case. Qed.
Embedding.lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Algebra.Group.Action.Basic import Mathlib.Algebra.Group.Action.Pi import Mathlib.Algebra.Group.Opposite /-! # Group actions on embeddings This file provides a `MulAction G (α ↪ β)` instance that agrees with the `MulAction G (α → β)` instances defined by `Pi.mulAction`. Note that unlike the `Pi` instance, this requires `G` to be a group. -/ assert_not_exists MonoidWithZero universe u v w variable {G G' α β : Type*} namespace Function.Embedding @[to_additive] instance smul [Group G] [MulAction G β] : SMul G (α ↪ β) := ⟨fun g f => f.trans (MulAction.toPerm g).toEmbedding⟩ @[to_additive] theorem smul_def [Group G] [MulAction G β] (g : G) (f : α ↪ β) : g • f = f.trans (MulAction.toPerm g).toEmbedding := rfl @[to_additive (attr := simp)] theorem smul_apply [Group G] [MulAction G β] (g : G) (f : α ↪ β) (a : α) : (g • f) a = g • f a := rfl @[to_additive] theorem coe_smul [Group G] [MulAction G β] (g : G) (f : α ↪ β) : ⇑(g • f) = g • ⇑f := rfl instance [Group G] [Group G'] [SMul G G'] [MulAction G β] [MulAction G' β] [IsScalarTower G G' β] : IsScalarTower G G' (α ↪ β) := ⟨fun x y z => Function.Embedding.ext fun i => smul_assoc x y (z i)⟩ @[to_additive] instance [Group G] [Group G'] [MulAction G β] [MulAction G' β] [SMulCommClass G G' β] : SMulCommClass G G' (α ↪ β) := ⟨fun x y z => Function.Embedding.ext fun i => smul_comm x y (z i)⟩ instance [Group G] [MulAction G β] [MulAction Gᵐᵒᵖ β] [IsCentralScalar G β] : IsCentralScalar G (α ↪ β) := ⟨fun _ _ => Function.Embedding.ext fun _ => op_smul_eq_smul _ _⟩ @[to_additive] instance [Group G] [MulAction G β] : MulAction G (α ↪ β) := DFunLike.coe_injective.mulAction _ coe_smul end Function.Embedding
Konig.lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.CategoryTheory.Filtered.Basic import Mathlib.Topology.Category.TopCat.Limits.Basic /-! # Topological Kőnig's lemma A topological version of Kőnig's lemma is that the inverse limit of nonempty compact Hausdorff spaces is nonempty. (Note: this can be generalized further to inverse limits of nonempty compact T0 spaces, where all the maps are closed maps; see [Stone1979] --- however there is an erratum for Theorem 4 that the element in the inverse limit can have cofinally many components that are not closed points.) We give this in a more general form, which is that cofiltered limits of nonempty compact Hausdorff spaces are nonempty (`nonempty_limitCone_of_compact_t2_cofiltered_system`). This also applies to inverse limits, where `{J : Type u} [Preorder J] [IsDirected J (≤)]` and `F : Jᵒᵖ ⥤ TopCat`. The theorem is specialized to nonempty finite types (which are compact Hausdorff with the discrete topology) in lemmas `nonempty_sections_of_finite_cofiltered_system` and `nonempty_sections_of_finite_inverse_system` in `Mathlib/CategoryTheory/CofilteredSystem.lean`. (See <https://stacks.math.columbia.edu/tag/086J> for the Set version.) -/ open CategoryTheory open CategoryTheory.Limits universe v u w noncomputable section namespace TopCat section TopologicalKonig variable {J : Type u} [SmallCategory J] variable (F : J ⥤ TopCat.{v}) private abbrev FiniteDiagramArrow {J : Type u} [SmallCategory J] (G : Finset J) := Σ' (X Y : J) (_ : X ∈ G) (_ : Y ∈ G), X ⟶ Y private abbrev FiniteDiagram (J : Type u) [SmallCategory J] := Σ G : Finset J, Finset (FiniteDiagramArrow G) /-- Partial sections of a cofiltered limit are sections when restricted to a finite subset of objects and morphisms of `J`. -/ def partialSections {J : Type u} [SmallCategory J] (F : J ⥤ TopCat.{v}) {G : Finset J} (H : Finset (FiniteDiagramArrow G)) : Set (∀ j, F.obj j) := {u | ∀ {f : FiniteDiagramArrow G} (_ : f ∈ H), F.map f.2.2.2.2 (u f.1) = u f.2.1} theorem partialSections.nonempty [IsCofilteredOrEmpty J] [h : ∀ j : J, Nonempty (F.obj j)] {G : Finset J} (H : Finset (FiniteDiagramArrow G)) : (partialSections F H).Nonempty := by classical cases isEmpty_or_nonempty J · exact ⟨isEmptyElim, fun {j} => IsEmpty.elim' inferInstance j.1⟩ haveI : IsCofiltered J := ⟨⟩ use fun j : J => if hj : j ∈ G then F.map (IsCofiltered.infTo G H hj) (h (IsCofiltered.inf G H)).some else (h _).some rintro ⟨X, Y, hX, hY, f⟩ hf dsimp only rwa [dif_pos hX, dif_pos hY, ← comp_app, ← F.map_comp, @IsCofiltered.infTo_commutes _ _ _ G H] theorem partialSections.directed : Directed Superset fun G : FiniteDiagram J => partialSections F G.2 := by classical intro A B let ιA : FiniteDiagramArrow A.1 → FiniteDiagramArrow (A.1 ⊔ B.1) := fun f => ⟨f.1, f.2.1, Finset.mem_union_left _ f.2.2.1, Finset.mem_union_left _ f.2.2.2.1, f.2.2.2.2⟩ let ιB : FiniteDiagramArrow B.1 → FiniteDiagramArrow (A.1 ⊔ B.1) := fun f => ⟨f.1, f.2.1, Finset.mem_union_right _ f.2.2.1, Finset.mem_union_right _ f.2.2.2.1, f.2.2.2.2⟩ refine ⟨⟨A.1 ⊔ B.1, A.2.image ιA ⊔ B.2.image ιB⟩, ?_, ?_⟩ · rintro u hu f hf have : ιA f ∈ A.2.image ιA ⊔ B.2.image ιB := by apply Finset.mem_union_left rw [Finset.mem_image] exact ⟨f, hf, rfl⟩ exact hu this · rintro u hu f hf have : ιB f ∈ A.2.image ιA ⊔ B.2.image ιB := by apply Finset.mem_union_right rw [Finset.mem_image] exact ⟨f, hf, rfl⟩ exact hu this theorem partialSections.closed [∀ j : J, T2Space (F.obj j)] {G : Finset J} (H : Finset (FiniteDiagramArrow G)) : IsClosed (partialSections F H) := by have : partialSections F H = ⋂ (f : FiniteDiagramArrow G) (_ : f ∈ H), {u | F.map f.2.2.2.2 (u f.1) = u f.2.1} := by ext1 simp only [Set.mem_iInter, Set.mem_setOf_eq] rfl rw [this] apply isClosed_biInter intro f _ apply isClosed_eq <;> fun_prop /-- Cofiltered limits of nonempty compact Hausdorff spaces are nonempty topological spaces. -/ theorem nonempty_limitCone_of_compact_t2_cofiltered_system (F : J ⥤ TopCat.{max v u}) [IsCofilteredOrEmpty J] [∀ j : J, Nonempty (F.obj j)] [∀ j : J, CompactSpace (F.obj j)] [∀ j : J, T2Space (F.obj j)] : Nonempty (TopCat.limitCone F).pt := by classical obtain ⟨u, hu⟩ := IsCompact.nonempty_iInter_of_directed_nonempty_isCompact_isClosed (fun G => partialSections F _) (partialSections.directed F) (fun G => partialSections.nonempty F _) (fun G => IsClosed.isCompact (partialSections.closed F _)) fun G => partialSections.closed F _ use u intro X Y f let G : FiniteDiagram J := ⟨{X, Y}, {⟨X, Y, by grind, by grind, f⟩}⟩ exact hu _ ⟨G, rfl⟩ (Finset.mem_singleton_self _) end TopologicalKonig end TopCat
Defs.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Topology.Constructions.SumProd /-! # Topological monoids - definitions In this file we define two mixin typeclasses: - `ContinuousMul M` says that the multiplication on `M` is continuous as a function on `M × M`; - `ContinuousAdd M` says that the addition on `M` is continuous as a function on `M × M`. These classes are `Prop`-valued mixins, i.e., they take data (`TopologicalSpace`, `Mul`/`Add`) as arguments instead of extending typeclasses with these fields. We also provide convenience dot notation lemmas like `Filter.Tendsto.mul` and `ContinuousAt.add`. -/ open scoped Topology /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `M`, for example, is obtained by requiring both the instances `AddMonoid M` and `ContinuousAdd M`. Continuity in only the left/right argument can be stated using `ContinuousConstVAdd α α`/`ContinuousConstVAdd αᵐᵒᵖ α`. -/ class ContinuousAdd (M : Type*) [TopologicalSpace M] [Add M] : Prop where continuous_add : Continuous fun p : M × M => p.1 + p.2 /-- Basic hypothesis to talk about a topological monoid or a topological semigroup. A topological monoid over `M`, for example, is obtained by requiring both the instances `Monoid M` and `ContinuousMul M`. Continuity in only the left/right argument can be stated using `ContinuousConstSMul α α`/`ContinuousConstSMul αᵐᵒᵖ α`. -/ @[to_additive] class ContinuousMul (M : Type*) [TopologicalSpace M] [Mul M] : Prop where continuous_mul : Continuous fun p : M × M => p.1 * p.2 section ContinuousMul variable {M : Type*} [TopologicalSpace M] [Mul M] [ContinuousMul M] @[to_additive (attr := continuity, fun_prop)] theorem continuous_mul : Continuous fun p : M × M => p.1 * p.2 := ContinuousMul.continuous_mul @[to_additive] theorem Filter.Tendsto.mul {α : Type*} {f g : α → M} {x : Filter α} {a b : M} (hf : Tendsto f x (𝓝 a)) (hg : Tendsto g x (𝓝 b)) : Tendsto (fun x ↦ f x * g x) x (𝓝 (a * b)) := (continuous_mul.tendsto _).comp (hf.prodMk_nhds hg) variable {X : Type*} [TopologicalSpace X] {f g : X → M} {s : Set X} {x : X} @[to_additive (attr := continuity, fun_prop)] theorem Continuous.mul (hf : Continuous f) (hg : Continuous g) : Continuous fun x => f x * g x := continuous_mul.comp₂ hf hg @[to_additive] theorem ContinuousWithinAt.mul (hf : ContinuousWithinAt f s x) (hg : ContinuousWithinAt g s x) : ContinuousWithinAt (fun x => f x * g x) s x := Filter.Tendsto.mul hf hg @[to_additive (attr := fun_prop)] theorem ContinuousAt.mul (hf : ContinuousAt f x) (hg : ContinuousAt g x) : ContinuousAt (fun x => f x * g x) x := Filter.Tendsto.mul hf hg @[to_additive (attr := fun_prop)] theorem ContinuousOn.mul (hf : ContinuousOn f s) (hg : ContinuousOn g s) : ContinuousOn (fun x => f x * g x) s := fun x hx ↦ (hf x hx).mul (hg x hx) end ContinuousMul
ProperSpace.lean
/- Copyright (c) 2024 Jou Glasheen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jou Glasheen, Kevin Buzzard -/ import Mathlib.Analysis.Normed.Field.ProperSpace import Mathlib.NumberTheory.Padics.RingHoms /-! # Properness of the p-adic numbers In this file, we prove that `ℤ_[p]` is totally bounded and compact, and that `ℚ_[p]` is proper. ## Main results - `PadicInt.totallyBounded_univ` : The set of p-adic integers `ℤ_[p]` is totally bounded. - `PadicInt.compactSpace` : The set of p-adic integers `ℤ_[p]` is a compact topological space. - `Padic.instProperSpace` : The field of p-adic numbers `ℚ_[p]` is a proper metric space. ## Notation - `p` : Is a natural prime. ## References Gouvêa, F. Q. (2020) p-adic Numbers An Introduction. 3rd edition. Cham, Springer International Publishing -/ assert_not_exists FiniteDimensional open Metric Topology variable (p : ℕ) [Fact (Nat.Prime p)] namespace PadicInt /-- The set of p-adic integers `ℤ_[p]` is totally bounded. -/ theorem totallyBounded_univ : TotallyBounded (Set.univ : Set ℤ_[p]) := by refine Metric.totallyBounded_iff.mpr (fun ε hε ↦ ?_) obtain ⟨k, hk⟩ := exists_pow_neg_lt p hε refine ⟨Nat.cast '' Finset.range (p ^ k), Set.toFinite _, fun z _ ↦ ?_⟩ simp only [PadicInt, Set.mem_iUnion, Metric.mem_ball, exists_prop, Set.exists_mem_image] refine ⟨z.appr k, ?_, ?_⟩ · simpa only [Finset.mem_coe, Finset.mem_range] using z.appr_lt k · exact (((z - z.appr k).norm_le_pow_iff_mem_span_pow k).mpr (z.appr_spec k)).trans_lt hk /-- The set of p-adic integers `ℤ_[p]` is a compact topological space. -/ instance compactSpace : CompactSpace ℤ_[p] := by rw [← isCompact_univ_iff, isCompact_iff_totallyBounded_isComplete] exact ⟨totallyBounded_univ p, complete_univ⟩ end PadicInt namespace Padic /-- The field of p-adic numbers `ℚ_[p]` is a proper metric space. -/ instance : ProperSpace ℚ_[p] := by suffices LocallyCompactSpace ℚ_[p] from .of_nontriviallyNormedField_of_weaklyLocallyCompactSpace _ have : closedBall 0 1 ∈ 𝓝 (0 : ℚ_[p]) := closedBall_mem_nhds _ zero_lt_one simp only [closedBall, dist_eq_norm_sub, sub_zero] at this refine IsCompact.locallyCompactSpace_of_mem_nhds_of_addGroup ?_ this simpa only [isCompact_iff_compactSpace] using PadicInt.compactSpace p end Padic
Determinant.lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import Mathlib.Data.Complex.Module import Mathlib.LinearAlgebra.Determinant /-! # Determinants of maps in the complex numbers as a vector space over `ℝ` This file provides results about the determinants of maps in the complex numbers as a vector space over `ℝ`. -/ namespace Complex /-- The determinant of `conjAe`, as a linear map. -/ @[simp] theorem det_conjAe : LinearMap.det conjAe.toLinearMap = -1 := by rw [← LinearMap.det_toMatrix basisOneI, toMatrix_conjAe, Matrix.det_fin_two_of] simp /-- The determinant of `conjAe`, as a linear equiv. -/ @[simp] theorem linearEquiv_det_conjAe : LinearEquiv.det conjAe.toLinearEquiv = -1 := by rw [← Units.val_inj, LinearEquiv.coe_det, AlgEquiv.toLinearEquiv_toLinearMap, det_conjAe, Units.coe_neg_one] end Complex
Closeds.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yaël Dillies -/ import Mathlib.Topology.Sets.Opens import Mathlib.Topology.Clopen /-! # Closed sets We define a few types of closed sets in a topological space. ## Main Definitions For a topological space `α`, * `TopologicalSpace.Closeds α`: The type of closed sets. * `TopologicalSpace.Clopens α`: The type of clopen sets. -/ open Order OrderDual Set variable {ι α β : Type*} [TopologicalSpace α] [TopologicalSpace β] namespace TopologicalSpace /-! ### Closed sets -/ /-- The type of closed subsets of a topological space. -/ structure Closeds (α : Type*) [TopologicalSpace α] where /-- the carrier set, i.e. the points in this set -/ carrier : Set α isClosed' : IsClosed carrier namespace Closeds instance : SetLike (Closeds α) α where coe := Closeds.carrier coe_injective' s t h := by cases s; cases t; congr instance : CanLift (Set α) (Closeds α) (↑) IsClosed where prf s hs := ⟨⟨s, hs⟩, rfl⟩ theorem isClosed (s : Closeds α) : IsClosed (s : Set α) := s.isClosed' @[deprecated (since := "2025-04-20")] alias closed := isClosed /-- See Note [custom simps projection]. -/ def Simps.coe (s : Closeds α) : Set α := s initialize_simps_projections Closeds (carrier → coe, as_prefix coe) @[simp] lemma carrier_eq_coe (s : Closeds α) : s.carrier = (s : Set α) := rfl @[ext] protected theorem ext {s t : Closeds α} (h : (s : Set α) = t) : s = t := SetLike.ext' h @[simp] theorem coe_mk (s : Set α) (h) : (mk s h : Set α) = s := rfl @[simp] lemma mem_mk {s : Set α} {hs : IsClosed s} {x : α} : x ∈ (⟨s, hs⟩ : Closeds α) ↔ x ∈ s := .rfl /-- The closure of a set, as an element of `TopologicalSpace.Closeds`. -/ @[simps] protected def closure (s : Set α) : Closeds α := ⟨closure s, isClosed_closure⟩ @[simp] theorem mem_closure {s : Set α} {x : α} : x ∈ Closeds.closure s ↔ x ∈ closure s := .rfl theorem gc : GaloisConnection Closeds.closure ((↑) : Closeds α → Set α) := fun _ U => ⟨subset_closure.trans, fun h => closure_minimal h U.isClosed⟩ @[simp] lemma closure_le {s : Set α} {t : Closeds α} : .closure s ≤ t ↔ s ⊆ t := t.isClosed.closure_subset_iff /-- The galois insertion between sets and closeds. -/ def gi : GaloisInsertion (@Closeds.closure α _) (↑) where choice s hs := ⟨s, closure_eq_iff_isClosed.1 <| hs.antisymm subset_closure⟩ gc := gc le_l_u _ := subset_closure choice_eq _s hs := SetLike.coe_injective <| subset_closure.antisymm hs instance instCompleteLattice : CompleteLattice (Closeds α) := CompleteLattice.copy (GaloisInsertion.liftCompleteLattice gi) -- le _ rfl -- top ⟨univ, isClosed_univ⟩ rfl -- bot ⟨∅, isClosed_empty⟩ (SetLike.coe_injective closure_empty.symm) -- sup (fun s t => ⟨s ∪ t, s.2.union t.2⟩) (funext fun s => funext fun t => SetLike.coe_injective (s.2.union t.2).closure_eq.symm) -- inf (fun s t => ⟨s ∩ t, s.2.inter t.2⟩) rfl -- sSup _ rfl -- sInf (fun S => ⟨⋂ s ∈ S, ↑s, isClosed_biInter fun s _ => s.2⟩) (funext fun _ => SetLike.coe_injective sInf_image.symm) /-- The type of closed sets is inhabited, with default element the empty set. -/ instance : Inhabited (Closeds α) := ⟨⊥⟩ @[simp, norm_cast] theorem coe_sup (s t : Closeds α) : (↑(s ⊔ t) : Set α) = ↑s ∪ ↑t := by rfl @[simp, norm_cast] theorem coe_inf (s t : Closeds α) : (↑(s ⊓ t) : Set α) = ↑s ∩ ↑t := rfl @[simp, norm_cast] theorem coe_top : (↑(⊤ : Closeds α) : Set α) = univ := rfl @[simp, norm_cast] theorem coe_eq_univ {s : Closeds α} : (s : Set α) = univ ↔ s = ⊤ := SetLike.coe_injective.eq_iff' rfl @[simp, norm_cast] theorem coe_bot : (↑(⊥ : Closeds α) : Set α) = ∅ := rfl @[simp, norm_cast] theorem coe_eq_empty {s : Closeds α} : (s : Set α) = ∅ ↔ s = ⊥ := SetLike.coe_injective.eq_iff' rfl theorem coe_nonempty {s : Closeds α} : (s : Set α).Nonempty ↔ s ≠ ⊥ := nonempty_iff_ne_empty.trans coe_eq_empty.not @[simp, norm_cast] theorem coe_sInf {S : Set (Closeds α)} : (↑(sInf S) : Set α) = ⋂ i ∈ S, ↑i := rfl @[simp] lemma coe_sSup {S : Set (Closeds α)} : ((sSup S : Closeds α) : Set α) = closure (⋃₀ ((↑) '' S)) := by rfl @[simp, norm_cast] theorem coe_finset_sup (f : ι → Closeds α) (s : Finset ι) : (↑(s.sup f) : Set α) = s.sup ((↑) ∘ f) := map_finset_sup (⟨⟨(↑), coe_sup⟩, coe_bot⟩ : SupBotHom (Closeds α) (Set α)) _ _ @[simp, norm_cast] theorem coe_finset_inf (f : ι → Closeds α) (s : Finset ι) : (↑(s.inf f) : Set α) = s.inf ((↑) ∘ f) := map_finset_inf (⟨⟨(↑), coe_inf⟩, coe_top⟩ : InfTopHom (Closeds α) (Set α)) _ _ @[simp] theorem mem_sInf {S : Set (Closeds α)} {x : α} : x ∈ sInf S ↔ ∀ s ∈ S, x ∈ s := mem_iInter₂ @[simp] theorem mem_iInf {ι} {x : α} {s : ι → Closeds α} : x ∈ iInf s ↔ ∀ i, x ∈ s i := by simp [iInf] @[simp, norm_cast] theorem coe_iInf {ι} (s : ι → Closeds α) : ((⨅ i, s i : Closeds α) : Set α) = ⋂ i, s i := by ext; simp theorem iInf_def {ι} (s : ι → Closeds α) : ⨅ i, s i = ⟨⋂ i, s i, isClosed_iInter fun i => (s i).2⟩ := by ext1; simp @[simp] theorem iInf_mk {ι} (s : ι → Set α) (h : ∀ i, IsClosed (s i)) : (⨅ i, ⟨s i, h i⟩ : Closeds α) = ⟨⋂ i, s i, isClosed_iInter h⟩ := iInf_def _ /-- Closed sets in a topological space form a coframe. -/ def coframeMinimalAxioms : Coframe.MinimalAxioms (Closeds α) where iInf_sup_le_sup_sInf a s := (SetLike.coe_injective <| by simp only [coe_sup, coe_iInf, coe_sInf, Set.union_iInter₂]).le instance instCoframe : Coframe (Closeds α) := .ofMinimalAxioms coframeMinimalAxioms /-- The term of `TopologicalSpace.Closeds α` corresponding to a singleton. -/ @[simps] def singleton [T1Space α] (x : α) : Closeds α := ⟨{x}, isClosed_singleton⟩ @[simp] lemma mem_singleton [T1Space α] {a b : α} : a ∈ singleton b ↔ a = b := Iff.rfl /-- The preimage of a closed set under a continuous map. -/ @[simps] def preimage (s : Closeds β) {f : α → β} (hf : Continuous f) : Closeds α := ⟨f ⁻¹' s, s.isClosed.preimage hf⟩ end Closeds /-- The complement of a closed set as an open set. -/ @[simps] def Closeds.compl (s : Closeds α) : Opens α := ⟨sᶜ, s.2.isOpen_compl⟩ /-- The complement of an open set as a closed set. -/ @[simps] def Opens.compl (s : Opens α) : Closeds α := ⟨sᶜ, s.2.isClosed_compl⟩ nonrec theorem Closeds.compl_compl (s : Closeds α) : s.compl.compl = s := Closeds.ext (compl_compl (s : Set α)) nonrec theorem Opens.compl_compl (s : Opens α) : s.compl.compl = s := Opens.ext (compl_compl (s : Set α)) theorem Closeds.compl_bijective : Function.Bijective (@Closeds.compl α _) := Function.bijective_iff_has_inverse.mpr ⟨Opens.compl, Closeds.compl_compl, Opens.compl_compl⟩ theorem Opens.compl_bijective : Function.Bijective (@Opens.compl α _) := Function.bijective_iff_has_inverse.mpr ⟨Closeds.compl, Opens.compl_compl, Closeds.compl_compl⟩ variable (α) /-- `TopologicalSpace.Closeds.compl` as an `OrderIso` to the order dual of `TopologicalSpace.Opens α`. -/ @[simps] def Closeds.complOrderIso : Closeds α ≃o (Opens α)ᵒᵈ where toFun := OrderDual.toDual ∘ Closeds.compl invFun := Opens.compl ∘ OrderDual.ofDual left_inv s := by simp [Closeds.compl_compl] right_inv s := by simp [Opens.compl_compl] map_rel_iff' := (@OrderDual.toDual_le_toDual (Opens α)).trans compl_subset_compl /-- `TopologicalSpace.Opens.compl` as an `OrderIso` to the order dual of `TopologicalSpace.Closeds α`. -/ @[simps] def Opens.complOrderIso : Opens α ≃o (Closeds α)ᵒᵈ where toFun := OrderDual.toDual ∘ Opens.compl invFun := Closeds.compl ∘ OrderDual.ofDual left_inv s := by simp [Opens.compl_compl] right_inv s := by simp [Closeds.compl_compl] map_rel_iff' := (@OrderDual.toDual_le_toDual (Closeds α)).trans compl_subset_compl variable {α} lemma Closeds.coe_eq_singleton_of_isAtom [T0Space α] {s : Closeds α} (hs : IsAtom s) : ∃ a, (s : Set α) = {a} := by refine minimal_nonempty_closed_eq_singleton s.2 (coe_nonempty.2 hs.1) fun t hts ht ht' ↦ ?_ lift t to Closeds α using ht' exact SetLike.coe_injective.eq_iff.2 <| (hs.le_iff_eq <| coe_nonempty.1 ht).1 hts @[simp, norm_cast] lemma Closeds.isAtom_coe [T1Space α] {s : Closeds α} : IsAtom (s : Set α) ↔ IsAtom s := Closeds.gi.isAtom_iff' rfl (fun t ht ↦ by obtain ⟨x, rfl⟩ := Set.isAtom_iff.1 ht; exact closure_singleton) s /-- in a `T1Space`, atoms of `TopologicalSpace.Closeds α` are precisely the `TopologicalSpace.Closeds.singleton`s. -/ theorem Closeds.isAtom_iff [T1Space α] {s : Closeds α} : IsAtom s ↔ ∃ x, s = Closeds.singleton x := by simp [← Closeds.isAtom_coe, Set.isAtom_iff, SetLike.ext_iff, Set.ext_iff] /-- in a `T1Space`, coatoms of `TopologicalSpace.Opens α` are precisely complements of singletons: `(TopologicalSpace.Closeds.singleton x).compl`. -/ theorem Opens.isCoatom_iff [T1Space α] {s : Opens α} : IsCoatom s ↔ ∃ x, s = (Closeds.singleton x).compl := by rw [← s.compl_compl, ← isAtom_dual_iff_isCoatom] change IsAtom (Closeds.complOrderIso α s.compl) ↔ _ simp only [(Closeds.complOrderIso α).isAtom_iff, Closeds.isAtom_iff, Closeds.compl_bijective.injective.eq_iff] /-! ### Clopen sets -/ /-- The type of clopen sets of a topological space. -/ structure Clopens (α : Type*) [TopologicalSpace α] where /-- the carrier set, i.e. the points in this set -/ carrier : Set α isClopen' : IsClopen carrier namespace Clopens instance : SetLike (Clopens α) α where coe s := s.carrier coe_injective' s t h := by cases s; cases t; congr theorem isClopen (s : Clopens α) : IsClopen (s : Set α) := s.isClopen' lemma isOpen (s : Clopens α) : IsOpen (s : Set α) := s.isClopen.isOpen lemma isClosed (s : Clopens α) : IsClosed (s : Set α) := s.isClopen.isClosed /-- See Note [custom simps projection]. -/ def Simps.coe (s : Clopens α) : Set α := s initialize_simps_projections Clopens (carrier → coe, as_prefix coe) /-- Reinterpret a clopen as an open. -/ @[simps] def toOpens (s : Clopens α) : Opens α := ⟨s, s.isOpen⟩ /-- Reinterpret a clopen as a closed. -/ @[simps] def toCloseds (s : Clopens α) : Closeds α := ⟨s, s.isClosed⟩ @[ext] protected theorem ext {s t : Clopens α} (h : (s : Set α) = t) : s = t := SetLike.ext' h @[simp] theorem coe_mk (s : Set α) (h) : (mk s h : Set α) = s := rfl @[simp] lemma mem_mk {s : Set α} {x h} : x ∈ mk s h ↔ x ∈ s := .rfl instance : Max (Clopens α) := ⟨fun s t => ⟨s ∪ t, s.isClopen.union t.isClopen⟩⟩ instance : Min (Clopens α) := ⟨fun s t => ⟨s ∩ t, s.isClopen.inter t.isClopen⟩⟩ instance : Top (Clopens α) := ⟨⟨⊤, isClopen_univ⟩⟩ instance : Bot (Clopens α) := ⟨⟨⊥, isClopen_empty⟩⟩ instance : SDiff (Clopens α) := ⟨fun s t => ⟨s \ t, s.isClopen.diff t.isClopen⟩⟩ instance : HImp (Clopens α) where himp s t := ⟨s ⇨ t, s.isClopen.himp t.isClopen⟩ instance : HasCompl (Clopens α) := ⟨fun s => ⟨sᶜ, s.isClopen.compl⟩⟩ @[simp, norm_cast] lemma coe_sup (s t : Clopens α) : ↑(s ⊔ t) = (s ∪ t : Set α) := rfl @[simp, norm_cast] lemma coe_inf (s t : Clopens α) : ↑(s ⊓ t) = (s ∩ t : Set α) := rfl @[simp, norm_cast] lemma coe_top : (↑(⊤ : Clopens α) : Set α) = univ := rfl @[simp, norm_cast] lemma coe_bot : (↑(⊥ : Clopens α) : Set α) = ∅ := rfl @[simp, norm_cast] lemma coe_sdiff (s t : Clopens α) : ↑(s \ t) = (s \ t : Set α) := rfl @[simp, norm_cast] lemma coe_himp (s t : Clopens α) : ↑(s ⇨ t) = (s ⇨ t : Set α) := rfl @[simp, norm_cast] lemma coe_compl (s : Clopens α) : (↑sᶜ : Set α) = (↑s)ᶜ := rfl instance : BooleanAlgebra (Clopens α) := SetLike.coe_injective.booleanAlgebra _ coe_sup coe_inf coe_top coe_bot coe_compl coe_sdiff coe_himp instance : Inhabited (Clopens α) := ⟨⊥⟩ instance : SProd (Clopens α) (Clopens β) (Clopens (α × β)) where sprod s t := ⟨s ×ˢ t, s.2.prod t.2⟩ @[simp] protected lemma mem_prod {s : Clopens α} {t : Clopens β} {x : α × β} : x ∈ s ×ˢ t ↔ x.1 ∈ s ∧ x.2 ∈ t := .rfl @[simp] lemma coe_finset_sup (s : Finset ι) (U : ι → Clopens α) : (↑(s.sup U) : Set α) = ⋃ i ∈ s, U i := by classical induction s using Finset.induction_on with | empty => simp | insert _ _ _ IH => simp [IH] @[simp, norm_cast] lemma coe_disjoint {s t : Clopens α} : Disjoint (s : Set α) t ↔ Disjoint s t := by simp [disjoint_iff, ← SetLike.coe_set_eq] end Clopens /-! ### Irreducible closed sets -/ /-- The type of irreducible closed subsets of a topological space. -/ structure IrreducibleCloseds (α : Type*) [TopologicalSpace α] where /-- the carrier set, i.e. the points in this set -/ carrier : Set α is_irreducible' : IsIrreducible carrier is_closed' : IsClosed carrier namespace IrreducibleCloseds instance : SetLike (IrreducibleCloseds α) α where coe := IrreducibleCloseds.carrier coe_injective' s t h := by cases s; cases t; congr instance : CanLift (Set α) (IrreducibleCloseds α) (↑) (fun s ↦ IsIrreducible s ∧ IsClosed s) where prf s hs := ⟨⟨s, hs.1, hs.2⟩, rfl⟩ theorem isIrreducible (s : IrreducibleCloseds α) : IsIrreducible (s : Set α) := s.is_irreducible' theorem isClosed (s : IrreducibleCloseds α) : IsClosed (s : Set α) := s.is_closed' /-- See Note [custom simps projection]. -/ def Simps.coe (s : IrreducibleCloseds α) : Set α := s initialize_simps_projections IrreducibleCloseds (carrier → coe, as_prefix coe) @[ext] protected theorem ext {s t : IrreducibleCloseds α} (h : (s : Set α) = t) : s = t := SetLike.ext' h @[simp] theorem coe_mk (s : Set α) (h : IsIrreducible s) (h' : IsClosed s) : (mk s h h' : Set α) = s := rfl /-- The term of `TopologicalSpace.IrreducibleCloseds α` corresponding to a singleton. -/ @[simps] def singleton [T1Space α] (x : α) : IrreducibleCloseds α := ⟨{x}, isIrreducible_singleton, isClosed_singleton⟩ @[simp] lemma mem_singleton [T1Space α] {a b : α} : a ∈ singleton b ↔ a = b := Iff.rfl /-- The equivalence between `IrreducibleCloseds α` and `{x : Set α // IsIrreducible x ∧ IsClosed x }`. -/ @[simps apply symm_apply] def equivSubtype : IrreducibleCloseds α ≃ { x : Set α // IsIrreducible x ∧ IsClosed x } where toFun a := ⟨a.1, a.2, a.3⟩ invFun a := ⟨a.1, a.2.1, a.2.2⟩ /-- The equivalence between `IrreducibleCloseds α` and `{x : Set α // IsClosed x ∧ IsIrreducible x }`. -/ @[simps apply symm_apply] def equivSubtype' : IrreducibleCloseds α ≃ { x : Set α // IsClosed x ∧ IsIrreducible x } where toFun a := ⟨a.1, a.3, a.2⟩ invFun a := ⟨a.1, a.2.2, a.2.1⟩ variable (α) in /-- The equivalence `IrreducibleCloseds α ≃ { x : Set α // IsIrreducible x ∧ IsClosed x }` is an order isomorphism. -/ def orderIsoSubtype : IrreducibleCloseds α ≃o { x : Set α // IsIrreducible x ∧ IsClosed x } := equivSubtype.toOrderIso (fun _ _ h ↦ h) (fun _ _ h ↦ h) variable (α) in /-- The equivalence `IrreducibleCloseds α ≃ { x : Set α // IsClosed x ∧ IsIrreducible x }` is an order isomorphism. -/ def orderIsoSubtype' : IrreducibleCloseds α ≃o { x : Set α // IsClosed x ∧ IsIrreducible x } := equivSubtype'.toOrderIso (fun _ _ h ↦ h) (fun _ _ h ↦ h) end IrreducibleCloseds end TopologicalSpace
Convergence.lean
/- Copyright (c) 2024 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import Mathlib.Data.EReal.Basic import Mathlib.NumberTheory.LSeries.Basic /-! # Convergence of L-series We define `LSeries.abscissaOfAbsConv f` (as an `EReal`) to be the infimum of all real numbers `x` such that the L-series of `f` converges for complex arguments with real part `x` and provide some results about it. ## Tags L-series, abscissa of convergence -/ open Complex /-- The abscissa `x : EReal` of absolute convergence of the L-series associated to `f`: the series converges absolutely at `s` when `re s > x` and does not converge absolutely when `re s < x`. -/ noncomputable def LSeries.abscissaOfAbsConv (f : ℕ → ℂ) : EReal := sInf <| Real.toEReal '' {x : ℝ | LSeriesSummable f x} lemma LSeries.abscissaOfAbsConv_congr {f g : ℕ → ℂ} (h : ∀ {n}, n ≠ 0 → f n = g n) : abscissaOfAbsConv f = abscissaOfAbsConv g := congr_arg sInf <| congr_arg _ <| Set.ext fun x ↦ LSeriesSummable_congr x h open Filter in /-- If `f` and `g` agree on large `n : ℕ`, then their `LSeries` have the same abscissa of absolute convergence. -/ lemma LSeries.abscissaOfAbsConv_congr' {f g : ℕ → ℂ} (h : f =ᶠ[atTop] g) : abscissaOfAbsConv f = abscissaOfAbsConv g := congr_arg sInf <| congr_arg _ <| Set.ext fun x ↦ LSeriesSummable_congr' x h open LSeries lemma LSeriesSummable_of_abscissaOfAbsConv_lt_re {f : ℕ → ℂ} {s : ℂ} (hs : abscissaOfAbsConv f < s.re) : LSeriesSummable f s := by obtain ⟨y, hy, hys⟩ : ∃ a : ℝ, LSeriesSummable f a ∧ a < s.re := by simpa [abscissaOfAbsConv, sInf_lt_iff] using hs exact hy.of_re_le_re <| ofReal_re y ▸ hys.le lemma LSeriesSummable_lt_re_of_abscissaOfAbsConv_lt_re {f : ℕ → ℂ} {s : ℂ} (hs : abscissaOfAbsConv f < s.re) : ∃ x : ℝ, x < s.re ∧ LSeriesSummable f x := by obtain ⟨x, hx₁, hx₂⟩ := EReal.exists_between_coe_real hs exact ⟨x, by simpa using hx₂, LSeriesSummable_of_abscissaOfAbsConv_lt_re hx₁⟩ lemma LSeriesSummable.abscissaOfAbsConv_le {f : ℕ → ℂ} {s : ℂ} (h : LSeriesSummable f s) : abscissaOfAbsConv f ≤ s.re := sInf_le <| by simpa using h.of_re_le_re (by simp) lemma LSeries.abscissaOfAbsConv_le_of_forall_lt_LSeriesSummable {f : ℕ → ℂ} {x : ℝ} (h : ∀ y : ℝ, x < y → LSeriesSummable f y) : abscissaOfAbsConv f ≤ x := by refine sInf_le_iff.mpr fun y hy ↦ le_of_forall_gt_imp_ge_of_dense fun a ↦ ?_ replace hy : ∀ (a : ℝ), LSeriesSummable f a → y ≤ a := by simpa [mem_lowerBounds] using hy cases a with | coe a₀ => exact_mod_cast fun ha ↦ hy a₀ (h a₀ ha) | bot => simp | top => simp lemma LSeries.abscissaOfAbsConv_le_of_forall_lt_LSeriesSummable' {f : ℕ → ℂ} {x : EReal} (h : ∀ y : ℝ, x < y → LSeriesSummable f y) : abscissaOfAbsConv f ≤ x := by cases x with | coe => exact abscissaOfAbsConv_le_of_forall_lt_LSeriesSummable <| mod_cast h | top => exact le_top | bot => refine le_of_eq <| sInf_eq_bot.mpr fun y hy ↦ ?_ cases y with | bot => simp at hy | coe y => exact ⟨_, ⟨_, h _ <| EReal.bot_lt_coe _, rfl⟩, mod_cast sub_one_lt y⟩ | top => exact ⟨_, ⟨_, h _ <| EReal.bot_lt_coe 0, rfl⟩, EReal.zero_lt_top⟩ /-- If `‖f n‖` is bounded by a constant times `n^x`, then the abscissa of absolute convergence of `f` is bounded by `x + 1`. -/ lemma LSeries.abscissaOfAbsConv_le_of_le_const_mul_rpow {f : ℕ → ℂ} {x : ℝ} (h : ∃ C, ∀ n ≠ 0, ‖f n‖ ≤ C * n ^ x) : abscissaOfAbsConv f ≤ x + 1 := by rw [show x = x + 1 - 1 by ring] at h by_contra! H obtain ⟨y, hy₁, hy₂⟩ := EReal.exists_between_coe_real H exact (LSeriesSummable_of_le_const_mul_rpow (s := y) (EReal.coe_lt_coe_iff.mp hy₁) h |>.abscissaOfAbsConv_le.trans_lt hy₂).false open Filter in /-- If `‖f n‖` is `O(n^x)`, then the abscissa of absolute convergence of `f` is bounded by `x + 1`. -/ lemma LSeries.abscissaOfAbsConv_le_of_isBigO_rpow {f : ℕ → ℂ} {x : ℝ} (h : f =O[atTop] fun n ↦ (n : ℝ) ^ x) : abscissaOfAbsConv f ≤ x + 1 := by rw [show x = x + 1 - 1 by ring] at h by_contra! H obtain ⟨y, hy₁, hy₂⟩ := EReal.exists_between_coe_real H exact (LSeriesSummable_of_isBigO_rpow (s := y) (EReal.coe_lt_coe_iff.mp hy₁) h |>.abscissaOfAbsConv_le.trans_lt hy₂).false /-- If `f` is bounded, then the abscissa of absolute convergence of `f` is bounded above by `1`. -/ lemma LSeries.abscissaOfAbsConv_le_of_le_const {f : ℕ → ℂ} (h : ∃ C, ∀ n ≠ 0, ‖f n‖ ≤ C) : abscissaOfAbsConv f ≤ 1 := by simpa using abscissaOfAbsConv_le_of_le_const_mul_rpow (x := 0) (by simpa using h) open Filter in /-- If `f` is `O(1)`, then the abscissa of absolute convergence of `f` is bounded above by `1`. -/ lemma LSeries.abscissaOfAbsConv_le_one_of_isBigO_one {f : ℕ → ℂ} (h : f =O[atTop] fun _ ↦ (1 : ℝ)) : abscissaOfAbsConv f ≤ 1 := by simpa using abscissaOfAbsConv_le_of_isBigO_rpow (x := 0) (by simpa using h) /-- If `f` is real-valued and `x` is strictly greater than the abscissa of absolute convergence of `f`, then the real series `∑' n, f n / n ^ x` converges. -/ lemma LSeries.summable_real_of_abscissaOfAbsConv_lt {f : ℕ → ℝ} {x : ℝ} (h : abscissaOfAbsConv (f ·) < x) : Summable fun n : ℕ ↦ f n / (n : ℝ) ^ x := by have aux : term (f ·) x = fun n ↦ ↑(if n = 0 then 0 else f n / (n : ℝ) ^ x) := by ext n simp [term_def, apply_ite ((↑) : ℝ → ℂ), ofReal_cpow n.cast_nonneg] have := LSeriesSummable_of_abscissaOfAbsConv_lt_re (ofReal_re x ▸ h) simp only [LSeriesSummable, aux, summable_ofReal] at this refine this.congr_cofinite ?_ filter_upwards [(Set.finite_singleton 0).compl_mem_cofinite] with n hn using if_neg (by simpa using hn) /-- If `F` is a binary operation on `ℕ → ℂ` with the property that the `LSeries` of `F f g` converges whenever the `LSeries` of `f` and `g` do, then the abscissa of absolute convergence of `F f g` is at most the maximum of the abscissa of absolute convergence of `f` and that of `g`. -/ lemma LSeries.abscissaOfAbsConv_binop_le {F : (ℕ → ℂ) → (ℕ → ℂ) → (ℕ → ℂ)} (hF : ∀ {f g s}, LSeriesSummable f s → LSeriesSummable g s → LSeriesSummable (F f g) s) (f g : ℕ → ℂ) : abscissaOfAbsConv (F f g) ≤ max (abscissaOfAbsConv f) (abscissaOfAbsConv g) := by refine abscissaOfAbsConv_le_of_forall_lt_LSeriesSummable' fun x hx ↦ hF ?_ ?_ · exact LSeriesSummable_of_abscissaOfAbsConv_lt_re <| (ofReal_re x).symm ▸ (le_max_left ..).trans_lt hx · exact LSeriesSummable_of_abscissaOfAbsConv_lt_re <| (ofReal_re x).symm ▸ (le_max_right ..).trans_lt hx
CofilteredSystem.lean
/- Copyright (c) 2022 Kyle Miller, Adam Topaz, Rémi Bottinelli, Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Adam Topaz, Rémi Bottinelli, Junyan Xu -/ import Mathlib.Topology.Category.TopCat.Limits.Konig /-! # Cofiltered systems This file deals with properties of cofiltered (and inverse) systems. ## Main definitions Given a functor `F : J ⥤ Type v`: * For `j : J`, `F.eventualRange j` is the intersections of all ranges of morphisms `F.map f` where `f` has codomain `j`. * `F.IsMittagLeffler` states that the functor `F` satisfies the Mittag-Leffler condition: the ranges of morphisms `F.map f` (with `f` having codomain `j`) stabilize. * If `J` is cofiltered `F.toEventualRanges` is the subfunctor of `F` obtained by restriction to `F.eventualRange`. * `F.toPreimages` restricts a functor to preimages of a given set in some `F.obj i`. If `J` is cofiltered, then it is Mittag-Leffler if `F` is, see `IsMittagLeffler.toPreimages`. ## Main statements * `nonempty_sections_of_finite_cofiltered_system` shows that if `J` is cofiltered and each `F.obj j` is nonempty and finite, `F.sections` is nonempty. * `nonempty_sections_of_finite_inverse_system` is a specialization of the above to `J` being a directed set (and `F : Jᵒᵖ ⥤ Type v`). * `isMittagLeffler_of_exists_finite_range` shows that if `J` is cofiltered and for all `j`, there exists some `i` and `f : i ⟶ j` such that the range of `F.map f` is finite, then `F` is Mittag-Leffler. * `surjective_toEventualRanges` shows that if `F` is Mittag-Leffler, then `F.toEventualRanges` has all morphisms `F.map f` surjective. ## TODO * Prove [Stacks: Lemma 0597](https://stacks.math.columbia.edu/tag/0597) ## References * [Stacks: Mittag-Leffler systems](https://stacks.math.columbia.edu/tag/0594) ## Tags Mittag-Leffler, surjective, eventual range, inverse system, -/ universe u v w open CategoryTheory CategoryTheory.IsCofiltered Set CategoryTheory.FunctorToTypes section FiniteKonig /-- This bootstraps `nonempty_sections_of_finite_inverse_system`. In this version, the `F` functor is between categories of the same universe, and it is an easy corollary to `TopCat.nonempty_limitCone_of_compact_t2_cofiltered_system`. -/ theorem nonempty_sections_of_finite_cofiltered_system.init {J : Type u} [SmallCategory J] [IsCofilteredOrEmpty J] (F : J ⥤ Type u) [hf : ∀ j, Finite (F.obj j)] [hne : ∀ j, Nonempty (F.obj j)] : F.sections.Nonempty := by let F' : J ⥤ TopCat := F ⋙ TopCat.discrete haveI : ∀ j, DiscreteTopology (F'.obj j) := fun _ => ⟨rfl⟩ haveI : ∀ j, Finite (F'.obj j) := hf haveI : ∀ j, Nonempty (F'.obj j) := hne obtain ⟨⟨u, hu⟩⟩ := TopCat.nonempty_limitCone_of_compact_t2_cofiltered_system.{u} F' exact ⟨u, hu⟩ /-- The cofiltered limit of nonempty finite types is nonempty. See `nonempty_sections_of_finite_inverse_system` for a specialization to inverse limits. -/ theorem nonempty_sections_of_finite_cofiltered_system {J : Type u} [Category.{w} J] [IsCofilteredOrEmpty J] (F : J ⥤ Type v) [∀ j : J, Finite (F.obj j)] [∀ j : J, Nonempty (F.obj j)] : F.sections.Nonempty := by -- Step 1: lift everything to the `max u v w` universe. let J' : Type max w v u := AsSmall.{max w v} J let down : J' ⥤ J := AsSmall.down let F' : J' ⥤ Type max u v w := down ⋙ F ⋙ uliftFunctor.{max u w, v} haveI : ∀ i, Nonempty (F'.obj i) := fun i => ⟨⟨Classical.arbitrary (F.obj (down.obj i))⟩⟩ haveI : ∀ i, Finite (F'.obj i) := fun i => Finite.of_equiv (F.obj (down.obj i)) Equiv.ulift.symm -- Step 2: apply the bootstrap theorem cases isEmpty_or_nonempty J · fconstructor <;> apply isEmptyElim haveI : IsCofiltered J := ⟨⟩ obtain ⟨u, hu⟩ := nonempty_sections_of_finite_cofiltered_system.init F' -- Step 3: interpret the results use fun j => (u ⟨j⟩).down intro j j' f have h := @hu (⟨j⟩ : J') (⟨j'⟩ : J') (ULift.up f) simp only [F', down, AsSmall.down, Functor.comp_map, uliftFunctor_map] at h simp_rw [← h] /-- The inverse limit of nonempty finite types is nonempty. See `nonempty_sections_of_finite_cofiltered_system` for a generalization to cofiltered limits. That version applies in almost all cases, and the only difference is that this version allows `J` to be empty. This may be regarded as a generalization of Kőnig's lemma. To specialize: given a locally finite connected graph, take `Jᵒᵖ` to be `ℕ` and `F j` to be length-`j` paths that start from an arbitrary fixed vertex. Elements of `F.sections` can be read off as infinite rays in the graph. -/ theorem nonempty_sections_of_finite_inverse_system {J : Type u} [Preorder J] [IsDirected J (· ≤ ·)] (F : Jᵒᵖ ⥤ Type v) [∀ j : Jᵒᵖ, Finite (F.obj j)] [∀ j : Jᵒᵖ, Nonempty (F.obj j)] : F.sections.Nonempty := nonempty_sections_of_finite_cofiltered_system F end FiniteKonig namespace CategoryTheory namespace Functor variable {J : Type u} [Category J] (F : J ⥤ Type v) {i j k : J} (s : Set (F.obj i)) /-- The eventual range of the functor `F : J ⥤ Type v` at index `j : J` is the intersection of the ranges of all maps `F.map f` with `i : J` and `f : i ⟶ j`. -/ def eventualRange (j : J) := ⋂ (i) (f : i ⟶ j), range (F.map f) theorem mem_eventualRange_iff {x : F.obj j} : x ∈ F.eventualRange j ↔ ∀ ⦃i⦄ (f : i ⟶ j), x ∈ range (F.map f) := mem_iInter₂ /-- The functor `F : J ⥤ Type v` satisfies the Mittag-Leffler condition if for all `j : J`, there exists some `i : J` and `f : i ⟶ j` such that for all `k : J` and `g : k ⟶ j`, the range of `F.map f` is contained in that of `F.map g`; in other words (see `isMittagLeffler_iff_eventualRange`), the eventual range at `j` is attained by some `f : i ⟶ j`. -/ def IsMittagLeffler : Prop := ∀ j : J, ∃ (i : _) (f : i ⟶ j), ∀ ⦃k⦄ (g : k ⟶ j), range (F.map f) ⊆ range (F.map g) theorem isMittagLeffler_iff_eventualRange : F.IsMittagLeffler ↔ ∀ j : J, ∃ (i : _) (f : i ⟶ j), F.eventualRange j = range (F.map f) := forall_congr' fun _ => exists₂_congr fun _ _ => ⟨fun h => (iInter₂_subset _ _).antisymm <| subset_iInter₂ h, fun h => h ▸ iInter₂_subset⟩ theorem IsMittagLeffler.subset_image_eventualRange (h : F.IsMittagLeffler) (f : j ⟶ i) : F.eventualRange i ⊆ F.map f '' F.eventualRange j := by obtain ⟨k, g, hg⟩ := F.isMittagLeffler_iff_eventualRange.1 h j rw [hg]; intro x hx obtain ⟨x, rfl⟩ := F.mem_eventualRange_iff.1 hx (g ≫ f) exact ⟨_, ⟨x, rfl⟩, by rw [map_comp_apply]⟩ theorem eventualRange_eq_range_precomp (f : i ⟶ j) (g : j ⟶ k) (h : F.eventualRange k = range (F.map g)) : F.eventualRange k = range (F.map <| f ≫ g) := by apply subset_antisymm · apply iInter₂_subset · rw [h, F.map_comp] apply range_comp_subset_range theorem isMittagLeffler_of_surjective (h : ∀ ⦃i j : J⦄ (f : i ⟶ j), (F.map f).Surjective) : F.IsMittagLeffler := fun j => ⟨j, 𝟙 j, fun k g => by rw [map_id, types_id, range_id, (h g).range_eq]⟩ /-- The subfunctor of `F` obtained by restricting to the preimages of a set `s ∈ F.obj i`. -/ @[simps] def toPreimages : J ⥤ Type v where obj j := ⋂ f : j ⟶ i, F.map f ⁻¹' s map g := MapsTo.restrict (F.map g) _ _ fun x h => by rw [mem_iInter] at h ⊢ intro f rw [← mem_preimage, preimage_preimage, mem_preimage] convert h (g ≫ f); rw [F.map_comp]; rfl map_id j := by simp +unfoldPartialApp only [MapsTo.restrict, Subtype.map, F.map_id] ext rfl map_comp f g := by simp +unfoldPartialApp only [MapsTo.restrict, Subtype.map, F.map_comp] rfl instance toPreimages_finite [∀ j, Finite (F.obj j)] : ∀ j, Finite ((F.toPreimages s).obj j) := fun _ => Subtype.finite variable [IsCofilteredOrEmpty J] theorem eventualRange_mapsTo (f : j ⟶ i) : (F.eventualRange j).MapsTo (F.map f) (F.eventualRange i) := fun x hx => by rw [mem_eventualRange_iff] at hx ⊢ intro k f' obtain ⟨l, g, g', he⟩ := cospan f f' obtain ⟨x, rfl⟩ := hx g rw [← map_comp_apply, he, F.map_comp] exact ⟨_, rfl⟩ theorem IsMittagLeffler.eq_image_eventualRange (h : F.IsMittagLeffler) (f : j ⟶ i) : F.eventualRange i = F.map f '' F.eventualRange j := (h.subset_image_eventualRange F f).antisymm <| mapsTo'.1 (F.eventualRange_mapsTo f) theorem eventualRange_eq_iff {f : i ⟶ j} : F.eventualRange j = range (F.map f) ↔ ∀ ⦃k⦄ (g : k ⟶ i), range (F.map f) ⊆ range (F.map <| g ≫ f) := by rw [subset_antisymm_iff, eventualRange, and_iff_right (iInter₂_subset _ _), subset_iInter₂_iff] refine ⟨fun h k g => h _ _, fun h j' f' => ?_⟩ obtain ⟨k, g, g', he⟩ := cospan f f' refine (h g).trans ?_ rw [he, F.map_comp] apply range_comp_subset_range theorem isMittagLeffler_iff_subset_range_comp : F.IsMittagLeffler ↔ ∀ j : J, ∃ (i : _) (f : i ⟶ j), ∀ ⦃k⦄ (g : k ⟶ i), range (F.map f) ⊆ range (F.map <| g ≫ f) := by simp_rw [isMittagLeffler_iff_eventualRange, eventualRange_eq_iff] theorem IsMittagLeffler.toPreimages (h : F.IsMittagLeffler) : (F.toPreimages s).IsMittagLeffler := (isMittagLeffler_iff_subset_range_comp _).2 fun j => by obtain ⟨j₁, g₁, f₁, -⟩ := IsCofilteredOrEmpty.cone_objs i j obtain ⟨j₂, f₂, h₂⟩ := F.isMittagLeffler_iff_eventualRange.1 h j₁ refine ⟨j₂, f₂ ≫ f₁, fun j₃ f₃ => ?_⟩ rintro _ ⟨⟨x, hx⟩, rfl⟩ have : F.map f₂ x ∈ F.eventualRange j₁ := by rw [h₂] exact ⟨_, rfl⟩ obtain ⟨y, hy, h₃⟩ := h.subset_image_eventualRange F (f₃ ≫ f₂) this refine ⟨⟨y, mem_iInter.2 fun g₂ => ?_⟩, Subtype.ext ?_⟩ · obtain ⟨j₄, f₄, h₄⟩ := IsCofilteredOrEmpty.cone_maps g₂ ((f₃ ≫ f₂) ≫ g₁) obtain ⟨y, rfl⟩ := F.mem_eventualRange_iff.1 hy f₄ rw [← map_comp_apply] at h₃ rw [mem_preimage, ← map_comp_apply, h₄, ← Category.assoc, map_comp_apply, h₃, ← map_comp_apply] apply mem_iInter.1 hx · simp_rw [toPreimages_map, MapsTo.val_restrict_apply] rw [← Category.assoc, map_comp_apply, h₃, map_comp_apply] theorem isMittagLeffler_of_exists_finite_range (h : ∀ j : J, ∃ (i : _) (f : i ⟶ j), (range <| F.map f).Finite) : F.IsMittagLeffler := by intro j obtain ⟨i, hi, hf⟩ := h j obtain ⟨m, ⟨i, f, hm⟩, hmin⟩ := Finset.wellFoundedLT.wf.has_min { s : Finset (F.obj j) | ∃ (i : _) (f : i ⟶ j), ↑s = range (F.map f) } ⟨_, i, hi, hf.coe_toFinset⟩ refine ⟨i, f, fun k g => (directedOn_range.mp <| F.ranges_directed j).is_bot_of_is_min ⟨⟨i, f⟩, rfl⟩ ?_ _ ⟨⟨k, g⟩, rfl⟩⟩ rintro _ ⟨⟨k', g'⟩, rfl⟩ hl refine (eq_of_le_of_not_lt hl ?_).ge have := hmin _ ⟨k', g', (m.finite_toSet.subset <| hm.substr hl).coe_toFinset⟩ rwa [Finset.lt_iff_ssubset, ← Finset.coe_ssubset, Set.Finite.coe_toFinset, hm] at this /-- The subfunctor of `F` obtained by restricting to the eventual range at each index. -/ @[simps] def toEventualRanges : J ⥤ Type v where obj j := F.eventualRange j map f := (F.eventualRange_mapsTo f).restrict _ _ _ map_id i := by simp +unfoldPartialApp only [MapsTo.restrict, Subtype.map, F.map_id] ext rfl map_comp _ _ := by simp +unfoldPartialApp only [MapsTo.restrict, Subtype.map, F.map_comp] rfl instance toEventualRanges_finite [∀ j, Finite (F.obj j)] : ∀ j, Finite (F.toEventualRanges.obj j) := fun _ => Subtype.finite /-- The sections of the functor `F : J ⥤ Type v` are in bijection with the sections of `F.toEventualRanges`. -/ def toEventualRangesSectionsEquiv : F.toEventualRanges.sections ≃ F.sections where toFun s := ⟨_, fun f => Subtype.coe_inj.2 <| s.prop f⟩ invFun s := ⟨fun _ => ⟨_, mem_iInter₂.2 fun _ f => ⟨_, s.prop f⟩⟩, fun f => Subtype.ext <| s.prop f⟩ /-- If `F` satisfies the Mittag-Leffler condition, its restriction to eventual ranges is a surjective functor. -/ theorem surjective_toEventualRanges (h : F.IsMittagLeffler) ⦃i j⦄ (f : i ⟶ j) : (F.toEventualRanges.map f).Surjective := fun ⟨x, hx⟩ => by obtain ⟨y, hy, rfl⟩ := h.subset_image_eventualRange F f hx exact ⟨⟨y, hy⟩, rfl⟩ /-- If `F` is nonempty at each index and Mittag-Leffler, then so is `F.toEventualRanges`. -/ theorem toEventualRanges_nonempty (h : F.IsMittagLeffler) [∀ j : J, Nonempty (F.obj j)] (j : J) : Nonempty (F.toEventualRanges.obj j) := by let ⟨i, f, h⟩ := F.isMittagLeffler_iff_eventualRange.1 h j rw [toEventualRanges_obj, h] infer_instance /-- If `F` has all arrows surjective, then it "factors through a poset". -/ theorem thin_diagram_of_surjective (Fsur : ∀ ⦃i j : J⦄ (f : i ⟶ j), (F.map f).Surjective) {i j} (f g : i ⟶ j) : F.map f = F.map g := let ⟨k, φ, hφ⟩ := IsCofilteredOrEmpty.cone_maps f g (Fsur φ).injective_comp_right <| by simp_rw [← types_comp, ← F.map_comp, hφ] theorem toPreimages_nonempty_of_surjective [hFn : ∀ j : J, Nonempty (F.obj j)] (Fsur : ∀ ⦃i j : J⦄ (f : i ⟶ j), (F.map f).Surjective) (hs : s.Nonempty) (j) : Nonempty ((F.toPreimages s).obj j) := by simp only [toPreimages_obj, nonempty_coe_sort, nonempty_iInter, mem_preimage] obtain h | ⟨⟨ji⟩⟩ := isEmpty_or_nonempty (j ⟶ i) · exact ⟨(hFn j).some, fun ji => h.elim ji⟩ · obtain ⟨y, ys⟩ := hs obtain ⟨x, rfl⟩ := Fsur ji y exact ⟨x, fun ji' => (F.thin_diagram_of_surjective Fsur ji' ji).symm ▸ ys⟩ theorem eval_section_injective_of_eventually_injective {j} (Finj : ∀ (i) (f : i ⟶ j), (F.map f).Injective) (i) (f : i ⟶ j) : (fun s : F.sections => s.val j).Injective := by refine fun s₀ s₁ h => Subtype.ext <| funext fun k => ?_ obtain ⟨m, mi, mk, _⟩ := IsCofilteredOrEmpty.cone_objs i k dsimp at h rw [← s₀.prop (mi ≫ f), ← s₁.prop (mi ≫ f)] at h rw [← s₀.prop mk, ← s₁.prop mk] exact congr_arg _ (Finj m (mi ≫ f) h) section FiniteCofilteredSystem variable [∀ j : J, Nonempty (F.obj j)] [∀ j : J, Finite (F.obj j)] (Fsur : ∀ ⦃i j : J⦄ (f : i ⟶ j), (F.map f).Surjective) include Fsur theorem eval_section_surjective_of_surjective (i : J) : (fun s : F.sections => s.val i).Surjective := fun x => by let s : Set (F.obj i) := {x} haveI := F.toPreimages_nonempty_of_surjective s Fsur (singleton_nonempty x) obtain ⟨sec, h⟩ := nonempty_sections_of_finite_cofiltered_system (F.toPreimages s) refine ⟨⟨fun j => (sec j).val, fun jk => by simpa [Subtype.ext_iff] using h jk⟩, ?_⟩ · have := (sec i).prop simp only [mem_iInter, mem_preimage] at this have := this (𝟙 i) rwa [map_id_apply] at this theorem eventually_injective [Nonempty J] [Finite F.sections] : ∃ j, ∀ (i) (f : i ⟶ j), (F.map f).Injective := by haveI : ∀ j, Fintype (F.obj j) := fun j => Fintype.ofFinite (F.obj j) haveI : Fintype F.sections := Fintype.ofFinite F.sections have card_le : ∀ j, Fintype.card (F.obj j) ≤ Fintype.card F.sections := fun j => Fintype.card_le_of_surjective _ (F.eval_section_surjective_of_surjective Fsur j) let fn j := Fintype.card F.sections - Fintype.card (F.obj j) refine ⟨fn.argmin, fun i f => ((Fintype.bijective_iff_surjective_and_card _).2 ⟨Fsur f, le_antisymm ?_ (Fintype.card_le_of_surjective _ <| Fsur f)⟩).1⟩ rw [← Nat.sub_le_sub_iff_left (card_le i)] apply fn.argmin_le end FiniteCofilteredSystem end Functor end CategoryTheory
Basic.lean
/- Copyright (c) 2024 Yudai Yamazaki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yudai Yamazaki -/ import Mathlib.GroupTheory.GroupExtension.Defs import Mathlib.GroupTheory.SemidirectProduct import Mathlib.GroupTheory.QuotientGroup.Basic import Mathlib.Tactic.Group /-! # Basic lemmas about group extensions This file gives basic lemmas about group extensions. For the main definitions, see `Mathlib/GroupTheory/GroupExtension/Defs.lean`. -/ variable {N G : Type*} [Group N] [Group G] namespace GroupExtension variable {E : Type*} [Group E] (S : GroupExtension N E G) /-- The isomorphism `E ⧸ S.rightHom.ker ≃* G` induced by `S.rightHom` -/ @[to_additive /-- The isomorphism `E ⧸ S.rightHom.ker ≃+ G` induced by `S.rightHom` -/] noncomputable def quotientKerRightHomEquivRight : E ⧸ S.rightHom.ker ≃* G := QuotientGroup.quotientKerEquivOfSurjective S.rightHom S.rightHom_surjective /-- The isomorphism `E ⧸ S.inl.range ≃* G` induced by `S.rightHom` -/ @[to_additive /-- The isomorphism `E ⧸ S.inl.range ≃+ G` induced by `S.rightHom` -/] noncomputable def quotientRangeInlEquivRight : E ⧸ S.inl.range ≃* G := (QuotientGroup.quotientMulEquivOfEq S.range_inl_eq_ker_rightHom).trans S.quotientKerRightHomEquivRight /-- An arbitrarily chosen section -/ @[to_additive surjInvRightHom /-- An arbitrarily chosen section -/] noncomputable def surjInvRightHom : S.Section where toFun := Function.surjInv S.rightHom_surjective rightInverse_rightHom := Function.surjInv_eq S.rightHom_surjective namespace Section variable {S} variable {E' : Type*} [Group E'] {S' : GroupExtension N E' G} (σ σ' : S.Section) (g g₁ g₂ : G) (equiv : S.Equiv S') @[to_additive] theorem mul_inv_mem_range_inl : σ g * (σ' g)⁻¹ ∈ S.inl.range := by simp only [S.range_inl_eq_ker_rightHom, MonoidHom.mem_ker, map_mul, map_inv, rightHom_section, mul_inv_cancel] @[to_additive] theorem inv_mul_mem_range_inl : (σ g)⁻¹ * σ' g ∈ S.inl.range := by simp only [S.range_inl_eq_ker_rightHom, MonoidHom.mem_ker, map_mul, map_inv, rightHom_section, inv_mul_cancel] @[to_additive] theorem exists_eq_inl_mul : ∃ n : N, σ g = S.inl n * σ' g := by obtain ⟨n, hn⟩ := mul_inv_mem_range_inl σ σ' g exact ⟨n, by rw [hn, inv_mul_cancel_right]⟩ @[to_additive] theorem exists_eq_mul_inl : ∃ n : N, σ g = σ' g * S.inl n := by obtain ⟨n, hn⟩ := inv_mul_mem_range_inl σ' σ g exact ⟨n, by rw [hn, mul_inv_cancel_left]⟩ @[to_additive] theorem mul_mul_mul_inv_mem_range_inl : σ g₁ * σ g₂ * (σ (g₁ * g₂))⁻¹ ∈ S.inl.range := by simp only [S.range_inl_eq_ker_rightHom, MonoidHom.mem_ker, map_mul, map_inv, rightHom_section, mul_inv_cancel] @[to_additive] theorem mul_inv_mul_mul_mem_range_inl : (σ (g₁ * g₂))⁻¹ * σ g₁ * σ g₂ ∈ S.inl.range := by simp only [S.range_inl_eq_ker_rightHom, MonoidHom.mem_ker, map_mul, map_inv, rightHom_section, mul_assoc, inv_mul_cancel] @[to_additive] theorem exists_mul_eq_inl_mul_mul : ∃ n : N, σ (g₁ * g₂) = S.inl n * σ g₁ * σ g₂ := by obtain ⟨n, hn⟩ := mul_mul_mul_inv_mem_range_inl σ g₁ g₂ use n⁻¹ rw [mul_assoc, map_inv, eq_inv_mul_iff_mul_eq, ← eq_mul_inv_iff_mul_eq, hn] @[to_additive] theorem exists_mul_eq_mul_mul_inl : ∃ n : N, σ (g₁ * g₂) = σ g₁ * σ g₂ * S.inl n := by obtain ⟨n, hn⟩ := mul_inv_mul_mul_mem_range_inl σ g₁ g₂ use n⁻¹ rw [map_inv, eq_mul_inv_iff_mul_eq, ← eq_inv_mul_iff_mul_eq, ← mul_assoc, hn] initialize_simps_projections AddGroupExtension.Section (toFun → apply) initialize_simps_projections Section (toFun → apply) /-- The composition of an isomorphism between equivalent group extensions and a section -/ @[to_additive (attr := simps!) /-- The composition of an isomorphism between equivalent additive group extensions and a section -/] def equivComp : S'.Section where toFun := equiv ∘ σ rightInverse_rightHom g := by rw [Function.comp_apply, equiv.rightHom_map, rightHom_section] end Section namespace Equiv variable {S} variable {E' : Type*} [Group E'] {S' : GroupExtension N E' G} /-- An equivalence of group extensions from a homomorphism making a commuting diagram. Such a homomorphism is necessarily an isomorphism. -/ @[to_additive /-- An equivalence of additive group extensions from a homomorphism making a commuting diagram. Such a homomorphism is necessarily an isomorphism. -/] noncomputable def ofMonoidHom (f : E →* E') (comp_inl : f.comp S.inl = S'.inl) (rightHom_comp : S'.rightHom.comp f = S.rightHom) : S.Equiv S' where __ := f invFun e' := let e := Function.surjInv S.rightHom_surjective (S'.rightHom e') e * S.inl (Function.invFun S'.inl ((f e)⁻¹ * e')) left_inv e := by simp only [OneHom.toFun_eq_coe, MonoidHom.toOneHom_coe, ← map_inv, ← map_mul] obtain ⟨n, hn⟩ : (Function.surjInv S.rightHom_surjective (S'.rightHom (f e)))⁻¹ * e ∈ S.inl.range := by rw [S.range_inl_eq_ker_rightHom, MonoidHom.mem_ker, map_mul, map_inv, ← MonoidHom.comp_apply, rightHom_comp] simpa only [Function.surjInv_eq] using inv_mul_cancel (S.rightHom e) rw [← eq_inv_mul_iff_mul_eq, ← hn, ← MonoidHom.comp_apply, comp_inl, Function.leftInverse_invFun S'.inl_injective] right_inv e' := by simp only [OneHom.toFun_eq_coe, MonoidHom.toOneHom_coe, map_mul] rw [← eq_inv_mul_iff_mul_eq, ← MonoidHom.comp_apply, comp_inl] apply Function.invFun_eq rw [← MonoidHom.mem_range, S'.range_inl_eq_ker_rightHom, MonoidHom.mem_ker, map_mul, map_inv, ← MonoidHom.comp_apply, rightHom_comp] simpa only [Function.surjInv_eq] using inv_mul_cancel (S'.rightHom e') inl_comm := congrArg DFunLike.coe comp_inl rightHom_comm := congrArg DFunLike.coe rightHom_comp end Equiv namespace Splitting variable {S} variable (s : S.Splitting) /-- `G` acts on `N` by conjugation. -/ noncomputable def conjAct : G →* MulAut N := S.conjAct.comp s /-- A split group extension is equivalent to the extension associated to a semidirect product. -/ noncomputable def semidirectProductToGroupExtensionEquiv : (SemidirectProduct.toGroupExtension s.conjAct).Equiv S where toFun := fun ⟨n, g⟩ ↦ S.inl n * s g invFun := fun e ↦ ⟨Function.invFun S.inl (e * (s (S.rightHom e))⁻¹), S.rightHom e⟩ left_inv := fun ⟨n, g⟩ ↦ by simp only [map_mul, rightHom_inl, rightHom_splitting, one_mul, mul_inv_cancel_right, Function.leftInverse_invFun S.inl_injective n] right_inv := fun e ↦ by simp only [← eq_mul_inv_iff_mul_eq] apply Function.invFun_eq rw [← MonoidHom.mem_range, S.range_inl_eq_ker_rightHom, MonoidHom.mem_ker, map_mul, map_inv, rightHom_splitting, mul_inv_cancel] map_mul' := fun ⟨n₁, g₁⟩ ⟨n₂, g₂⟩ ↦ by simp only [conjAct, MonoidHom.comp_apply, map_mul, inl_conjAct_comm, MonoidHom.coe_coe] group inl_comm := by ext n simp only [SemidirectProduct.toGroupExtension, Function.comp_apply, MulEquiv.coe_mk, Equiv.coe_fn_mk, SemidirectProduct.left_inl, SemidirectProduct.right_inl, map_one, mul_one] rightHom_comm := by ext ⟨n, g⟩ simp only [SemidirectProduct.toGroupExtension, Function.comp_apply, MulEquiv.coe_mk, Equiv.coe_fn_mk, map_mul, rightHom_inl, one_mul, rightHom_splitting, SemidirectProduct.rightHom_eq_right] /-- The group associated to a split extension is isomorphic to a semidirect product. -/ noncomputable def semidirectProductMulEquiv : N ⋊[s.conjAct] G ≃* E := s.semidirectProductToGroupExtensionEquiv.toMulEquiv end Splitting namespace IsConj /-- `N`-conjugacy is reflexive. -/ @[to_additive /-- `N`-conjugacy is reflexive. -/] theorem refl (s : S.Splitting) : S.IsConj s s := ⟨1, by simp only [map_one, inv_one, one_mul, mul_one]⟩ /-- `N`-conjugacy is symmetric. -/ @[to_additive /-- `N`-conjugacy is symmetric. -/] theorem symm {s₁ s₂ : S.Splitting} (h : S.IsConj s₁ s₂) : S.IsConj s₂ s₁ := by obtain ⟨n, hn⟩ := h exact ⟨n⁻¹, by simp only [hn, map_inv]; group⟩ /-- `N`-conjugacy is transitive. -/ @[to_additive /-- `N`-conjugacy is transitive. -/] theorem trans {s₁ s₂ s₃ : S.Splitting} (h₁ : S.IsConj s₁ s₂) (h₂ : S.IsConj s₂ s₃) : S.IsConj s₁ s₃ := by obtain ⟨n₁, hn₁⟩ := h₁ obtain ⟨n₂, hn₂⟩ := h₂ exact ⟨n₁ * n₂, by simp only [hn₁, hn₂, map_mul]; group⟩ /-- The setoid of splittings with `N`-conjugacy -/ @[to_additive /-- The setoid of splittings with `N`-conjugacy -/] def setoid : Setoid S.Splitting where r := S.IsConj iseqv := { refl := refl S symm := symm S trans := trans S } end IsConj /-- The `N`-conjugacy classes of splittings -/ @[to_additive /-- The `N`-conjugacy classes of splittings -/] def ConjClasses := Quotient <| IsConj.setoid S end GroupExtension namespace SemidirectProduct variable {φ : G →* MulAut N} (s : (toGroupExtension φ).Splitting) theorem right_splitting (g : G) : (s g).right = g := by rw [← rightHom_eq_right, ← toGroupExtension_rightHom, s.rightHom_splitting] end SemidirectProduct
Resolution.lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Kim Morrison, Jakob von Raumer, Joël Riou -/ import Mathlib.CategoryTheory.Preadditive.Projective.Resolution import Mathlib.Algebra.Homology.HomotopyCategory import Mathlib.Tactic.SuppressCompilation /-! # Abelian categories with enough projectives have projective resolutions ## Main results When the underlying category is abelian: * `CategoryTheory.ProjectiveResolution.lift`: Given `P : ProjectiveResolution X` and `Q : ProjectiveResolution Y`, any morphism `X ⟶ Y` admits a lifting to a chain map `P.complex ⟶ Q.complex`. It is a lifting in the sense that `P.ι` intertwines the lift and the original morphism, see `CategoryTheory.ProjectiveResolution.lift_commutes`. * `CategoryTheory.ProjectiveResolution.liftHomotopy`: Any two such descents are homotopic. * `CategoryTheory.ProjectiveResolution.homotopyEquiv`: Any two projective resolutions of the same object are homotopy equivalent. * `CategoryTheory.projectiveResolutions`: If every object admits a projective resolution, we can construct a functor `projectiveResolutions C : C ⥤ HomotopyCategory C (ComplexShape.down ℕ)`. * `CategoryTheory.exact_d_f`: `Projective.d f` and `f` are exact. * `CategoryTheory.ProjectiveResolution.of`: Hence, starting from an epimorphism `P ⟶ X`, where `P` is projective, we can apply `Projective.d` repeatedly to obtain a projective resolution of `X`. -/ suppress_compilation noncomputable section universe v u namespace CategoryTheory variable {C : Type u} [Category.{v} C] open Category Limits Projective namespace ProjectiveResolution section variable [HasZeroObject C] [HasZeroMorphisms C] /-- Auxiliary construction for `lift`. -/ def liftFZero {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex.X 0 ⟶ Q.complex.X 0 := Projective.factorThru (P.π.f 0 ≫ f) (Q.π.f 0) end section Abelian variable [Abelian C] lemma exact₀ {Z : C} (P : ProjectiveResolution Z) : (ShortComplex.mk _ _ P.complex_d_comp_π_f_zero).Exact := ShortComplex.exact_of_g_is_cokernel _ P.isColimitCokernelCofork /-- Auxiliary construction for `lift`. -/ def liftFOne {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex.X 1 ⟶ Q.complex.X 1 := Q.exact₀.liftFromProjective (P.complex.d 1 0 ≫ liftFZero f P Q) (by simp [liftFZero]) @[simp] theorem liftFOne_zero_comm {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : liftFOne f P Q ≫ Q.complex.d 1 0 = P.complex.d 1 0 ≫ liftFZero f P Q := by apply Q.exact₀.liftFromProjective_comp /-- Auxiliary construction for `lift`. -/ def liftFSucc {Y Z : C} (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) (n : ℕ) (g : P.complex.X n ⟶ Q.complex.X n) (g' : P.complex.X (n + 1) ⟶ Q.complex.X (n + 1)) (w : g' ≫ Q.complex.d (n + 1) n = P.complex.d (n + 1) n ≫ g) : Σ' g'' : P.complex.X (n + 2) ⟶ Q.complex.X (n + 2), g'' ≫ Q.complex.d (n + 2) (n + 1) = P.complex.d (n + 2) (n + 1) ≫ g' := ⟨(Q.exact_succ n).liftFromProjective (P.complex.d (n + 2) (n + 1) ≫ g') (by simp [w]), (Q.exact_succ n).liftFromProjective_comp _ _⟩ /-- A morphism in `C` lift to a chain map between projective resolutions. -/ def lift {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex ⟶ Q.complex := ChainComplex.mkHom _ _ (liftFZero f _ _) (liftFOne f _ _) (liftFOne_zero_comm f P Q) fun n ⟨g, g', w⟩ => ⟨(liftFSucc P Q n g g' w).1, (liftFSucc P Q n g g' w).2⟩ /-- The resolution maps intertwine the lift of a morphism and that morphism. -/ @[reassoc (attr := simp)] theorem lift_commutes {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : lift f P Q ≫ Q.π = P.π ≫ (ChainComplex.single₀ C).map f := by ext simp [lift, liftFZero, liftFOne] @[reassoc (attr := simp)] lemma lift_commutes_zero {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : (lift f P Q).f 0 ≫ Q.π.f 0 = P.π.f 0 ≫ f := (HomologicalComplex.congr_hom (lift_commutes f P Q) 0).trans (by simp) /-- An auxiliary definition for `liftHomotopyZero`. -/ def liftHomotopyZeroZero {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : P.complex.X 0 ⟶ Q.complex.X 1 := Q.exact₀.liftFromProjective (f.f 0) (congr_fun (congr_arg HomologicalComplex.Hom.f comm) 0) @[reassoc (attr := simp)] lemma liftHomotopyZeroZero_comp {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : liftHomotopyZeroZero f comm ≫ Q.complex.d 1 0 = f.f 0 := Q.exact₀.liftFromProjective_comp _ _ /-- An auxiliary definition for `liftHomotopyZero`. -/ def liftHomotopyZeroOne {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : P.complex.X 1 ⟶ Q.complex.X 2 := (Q.exact_succ 0).liftFromProjective (f.f 1 - P.complex.d 1 0 ≫ liftHomotopyZeroZero f comm) (by rw [Preadditive.sub_comp, assoc, HomologicalComplex.Hom.comm, liftHomotopyZeroZero_comp, sub_self]) @[reassoc (attr := simp)] lemma liftHomotopyZeroOne_comp {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : liftHomotopyZeroOne f comm ≫ Q.complex.d 2 1 = f.f 1 - P.complex.d 1 0 ≫ liftHomotopyZeroZero f comm := (Q.exact_succ 0).liftFromProjective_comp _ _ /-- An auxiliary definition for `liftHomotopyZero`. -/ def liftHomotopyZeroSucc {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (n : ℕ) (g : P.complex.X n ⟶ Q.complex.X (n + 1)) (g' : P.complex.X (n + 1) ⟶ Q.complex.X (n + 2)) (w : f.f (n + 1) = P.complex.d (n + 1) n ≫ g + g' ≫ Q.complex.d (n + 2) (n + 1)) : P.complex.X (n + 2) ⟶ Q.complex.X (n + 3) := (Q.exact_succ (n + 1)).liftFromProjective (f.f (n + 2) - P.complex.d _ _ ≫ g') (by simp [w]) @[reassoc (attr := simp)] lemma liftHomotopyZeroSucc_comp {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (n : ℕ) (g : P.complex.X n ⟶ Q.complex.X (n + 1)) (g' : P.complex.X (n + 1) ⟶ Q.complex.X (n + 2)) (w : f.f (n + 1) = P.complex.d (n + 1) n ≫ g + g' ≫ Q.complex.d (n + 2) (n + 1)) : liftHomotopyZeroSucc f n g g' w ≫ Q.complex.d (n + 3) (n + 2) = f.f (n + 2) - P.complex.d _ _ ≫ g' := (Q.exact_succ (n + 1)).liftFromProjective_comp _ _ /-- Any lift of the zero morphism is homotopic to zero. -/ def liftHomotopyZero {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : Homotopy f 0 := Homotopy.mkInductive _ (liftHomotopyZeroZero f comm) (by simp ) (liftHomotopyZeroOne f comm) (by simp) fun n ⟨g, g', w⟩ => ⟨liftHomotopyZeroSucc f n g g' w, by simp⟩ /-- Two lifts of the same morphism are homotopic. -/ def liftHomotopy {Y Z : C} (f : Y ⟶ Z) {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (g h : P.complex ⟶ Q.complex) (g_comm : g ≫ Q.π = P.π ≫ (ChainComplex.single₀ C).map f) (h_comm : h ≫ Q.π = P.π ≫ (ChainComplex.single₀ C).map f) : Homotopy g h := Homotopy.equivSubZero.invFun (liftHomotopyZero _ (by simp [g_comm, h_comm])) /-- The lift of the identity morphism is homotopic to the identity chain map. -/ def liftIdHomotopy (X : C) (P : ProjectiveResolution X) : Homotopy (lift (𝟙 X) P P) (𝟙 P.complex) := by apply liftHomotopy (𝟙 X) <;> simp /-- The lift of a composition is homotopic to the composition of the lifts. -/ def liftCompHomotopy {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (P : ProjectiveResolution X) (Q : ProjectiveResolution Y) (R : ProjectiveResolution Z) : Homotopy (lift (f ≫ g) P R) (lift f P Q ≫ lift g Q R) := by apply liftHomotopy (f ≫ g) <;> simp -- We don't care about the actual definitions of these homotopies. /-- Any two projective resolutions are homotopy equivalent. -/ def homotopyEquiv {X : C} (P Q : ProjectiveResolution X) : HomotopyEquiv P.complex Q.complex where hom := lift (𝟙 X) P Q inv := lift (𝟙 X) Q P homotopyHomInvId := (liftCompHomotopy (𝟙 X) (𝟙 X) P Q P).symm.trans <| by simpa [id_comp] using liftIdHomotopy _ _ homotopyInvHomId := (liftCompHomotopy (𝟙 X) (𝟙 X) Q P Q).symm.trans <| by simpa [id_comp] using liftIdHomotopy _ _ @[reassoc (attr := simp)] theorem homotopyEquiv_hom_π {X : C} (P Q : ProjectiveResolution X) : (homotopyEquiv P Q).hom ≫ Q.π = P.π := by simp [homotopyEquiv] @[reassoc (attr := simp)] theorem homotopyEquiv_inv_π {X : C} (P Q : ProjectiveResolution X) : (homotopyEquiv P Q).inv ≫ P.π = Q.π := by simp [homotopyEquiv] end Abelian end ProjectiveResolution /-- An arbitrarily chosen projective resolution of an object. -/ abbrev projectiveResolution (Z : C) [HasZeroObject C] [HasZeroMorphisms C] [HasProjectiveResolution Z] : ProjectiveResolution Z := (HasProjectiveResolution.out (Z := Z)).some variable (C) variable [Abelian C] section variable [HasProjectiveResolutions C] /-- Taking projective resolutions is functorial, if considered with target the homotopy category (`ℕ`-indexed chain complexes and chain maps up to homotopy). -/ def projectiveResolutions : C ⥤ HomotopyCategory C (ComplexShape.down ℕ) where obj X := (HomotopyCategory.quotient _ _).obj (projectiveResolution X).complex map f := (HomotopyCategory.quotient _ _).map (ProjectiveResolution.lift f _ _) map_id X := by rw [← (HomotopyCategory.quotient _ _).map_id] apply HomotopyCategory.eq_of_homotopy apply ProjectiveResolution.liftIdHomotopy map_comp f g := by rw [← (HomotopyCategory.quotient _ _).map_comp] apply HomotopyCategory.eq_of_homotopy apply ProjectiveResolution.liftCompHomotopy variable {C} /-- If `P : ProjectiveResolution X`, then the chosen `(projectiveResolutions C).obj X` is isomorphic (in the homotopy category) to `P.complex`. -/ def ProjectiveResolution.iso {X : C} (P : ProjectiveResolution X) : (projectiveResolutions C).obj X ≅ (HomotopyCategory.quotient _ _).obj P.complex := HomotopyCategory.isoOfHomotopyEquiv (homotopyEquiv _ _) @[reassoc] lemma ProjectiveResolution.iso_inv_naturality {X Y : C} (f : X ⟶ Y) (P : ProjectiveResolution X) (Q : ProjectiveResolution Y) (φ : P.complex ⟶ Q.complex) (comm : φ.f 0 ≫ Q.π.f 0 = P.π.f 0 ≫ f) : P.iso.inv ≫ (projectiveResolutions C).map f = (HomotopyCategory.quotient _ _).map φ ≫ Q.iso.inv := by apply HomotopyCategory.eq_of_homotopy apply liftHomotopy f all_goals cat_disch @[reassoc] lemma ProjectiveResolution.iso_hom_naturality {X Y : C} (f : X ⟶ Y) (P : ProjectiveResolution X) (Q : ProjectiveResolution Y) (φ : P.complex ⟶ Q.complex) (comm : φ.f 0 ≫ Q.π.f 0 = P.π.f 0 ≫ f) : (projectiveResolutions C).map f ≫ Q.iso.hom = P.iso.hom ≫ (HomotopyCategory.quotient _ _).map φ := by rw [← cancel_epi (P.iso).inv, iso_inv_naturality_assoc f P Q φ comm, Iso.inv_hom_id_assoc, Iso.inv_hom_id, comp_id] end variable [EnoughProjectives C] variable {C} in theorem exact_d_f {X Y : C} (f : X ⟶ Y) : (ShortComplex.mk (d f) f (by simp)).Exact := by let α : ShortComplex.mk (d f) f (by simp) ⟶ ShortComplex.mk (kernel.ι f) f (by simp) := { τ₁ := Projective.π _ τ₂ := 𝟙 _ τ₃ := 𝟙 _ } have : Epi α.τ₁ := by dsimp; infer_instance have : IsIso α.τ₂ := by dsimp; infer_instance have : Mono α.τ₃ := by dsimp; infer_instance rw [ShortComplex.exact_iff_of_epi_of_isIso_of_mono α] apply ShortComplex.exact_of_f_is_kernel apply kernelIsKernel namespace ProjectiveResolution /-! Our goal is to define `ProjectiveResolution.of Z : ProjectiveResolution Z`. The `0`-th object in this resolution will just be `Projective.over Z`, i.e. an arbitrarily chosen projective object with a map to `Z`. After that, we build the `n+1`-st object as `Projective.syzygies` applied to the previously constructed morphism, and the map from the `n`-th object as `Projective.d`. -/ variable {C} variable (Z : C) -- The construction of the projective resolution `of` would be very, very slow -- if it were not broken into separate definitions and lemmas /-- Auxiliary definition for `ProjectiveResolution.of`. -/ def ofComplex : ChainComplex C ℕ := ChainComplex.mk' (Projective.over Z) (Projective.syzygies (Projective.π Z)) (Projective.d (Projective.π Z)) (fun f => ⟨_, Projective.d f, by simp⟩) lemma ofComplex_d_1_0 : (ofComplex Z).d 1 0 = d (Projective.π Z) := by simp [ofComplex] lemma ofComplex_exactAt_succ (n : ℕ) : (ofComplex Z).ExactAt (n + 1) := by rw [HomologicalComplex.exactAt_iff' _ (n + 1 + 1) (n + 1) n (by simp) (by simp)] dsimp [ofComplex, HomologicalComplex.sc', HomologicalComplex.shortComplexFunctor', ChainComplex.mk', ChainComplex.mk] simp only [ChainComplex.of_d] -- TODO: this should just be apply exact_d_f so something is missing match n with | 0 => apply exact_d_f | n + 1 => apply exact_d_f instance (n : ℕ) : Projective ((ofComplex Z).X n) := by obtain (_ | _ | _ | n) := n <;> apply Projective.projective_over /-- In any abelian category with enough projectives, `ProjectiveResolution.of Z` constructs an projective resolution of the object `Z`. -/ irreducible_def of : ProjectiveResolution Z where complex := ofComplex Z π := (ChainComplex.toSingle₀Equiv _ _).symm ⟨Projective.π Z, by rw [ofComplex_d_1_0, assoc, kernel.condition, comp_zero]⟩ quasiIso := ⟨fun n => by cases n · rw [ChainComplex.quasiIsoAt₀_iff, ShortComplex.quasiIso_iff_of_zeros'] · dsimp refine (ShortComplex.exact_and_epi_g_iff_of_iso ?_).2 ⟨exact_d_f (Projective.π Z), by dsimp; infer_instance⟩ exact ShortComplex.isoMk (Iso.refl _) (Iso.refl _) (Iso.refl _) (by simp [ofComplex]) (by simp) all_goals rfl · rw [quasiIsoAt_iff_exactAt'] · apply ofComplex_exactAt_succ · apply ChainComplex.exactAt_succ_single_obj⟩ instance (priority := 100) (Z : C) : HasProjectiveResolution Z where out := ⟨of Z⟩ instance (priority := 100) : HasProjectiveResolutions C where out _ := inferInstance end ProjectiveResolution end CategoryTheory
TopCatAdjunction.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.Condensed.Light.TopComparison import Mathlib.Topology.Category.Sequential import Mathlib.Topology.Category.LightProfinite.Sequence /-! # The adjunction between light condensed sets and topological spaces This file defines the functor `lightCondSetToTopCat : LightCondSet.{u} ⥤ TopCat.{u}` which is left adjoint to `topCatToLightCondSet : TopCat.{u} ⥤ LightCondSet.{u}`. We prove that the counit is bijective (but not in general an isomorphism) and conclude that the right adjoint is faithful. The counit is an isomorphism for sequential spaces, and we conclude that the functor `topCatToLightCondSet` is fully faithful when restricted to sequential spaces. -/ universe u open LightCondensed LightCondSet CategoryTheory LightProfinite namespace LightCondSet variable (X : LightCondSet.{u}) /-- Auxiliary definition to define the topology on `X(*)` for a light condensed set `X`. -/ private def coinducingCoprod : (Σ (i : (S : LightProfinite.{u}) × X.val.obj ⟨S⟩), i.fst) → X.val.obj ⟨LightProfinite.of PUnit⟩ := fun ⟨⟨_, i⟩, s⟩ ↦ X.val.map ((of PUnit.{u+1}).const s).op i /-- Let `X` be a light condensed set. We define a topology on `X(*)` as the quotient topology of all the maps from light profinite sets `S` to `X(*)`, corresponding to elements of `X(S)`. In other words, the topology coinduced by the map `LightCondSet.coinducingCoprod` above. -/ local instance underlyingTopologicalSpace : TopologicalSpace (X.val.obj ⟨LightProfinite.of PUnit⟩) := TopologicalSpace.coinduced (coinducingCoprod X) inferInstance /-- The object part of the functor `LightCondSet ⥤ TopCat` -/ abbrev toTopCat : TopCat.{u} := TopCat.of (X.val.obj ⟨LightProfinite.of PUnit⟩) lemma continuous_coinducingCoprod {S : LightProfinite.{u}} (x : X.val.obj ⟨S⟩) : Continuous fun a ↦ (X.coinducingCoprod ⟨⟨S, x⟩, a⟩) := by suffices ∀ (i : (T : LightProfinite.{u}) × X.val.obj ⟨T⟩), Continuous (fun (a : i.fst) ↦ X.coinducingCoprod ⟨i, a⟩) from this ⟨_, _⟩ rw [← continuous_sigma_iff] apply continuous_coinduced_rng variable {X} {Y : LightCondSet} (f : X ⟶ Y) attribute [local instance] Types.instFunLike Types.instConcreteCategory in /-- The map part of the functor `LightCondSet ⥤ TopCat` -/ @[simps!] def toTopCatMap : X.toTopCat ⟶ Y.toTopCat := TopCat.ofHom { toFun := f.val.app ⟨LightProfinite.of PUnit⟩ continuous_toFun := by rw [continuous_coinduced_dom] apply continuous_sigma intro ⟨S, x⟩ simp only [Function.comp_apply, coinducingCoprod] rw [show (fun (a : S) ↦ f.val.app ⟨of PUnit⟩ (X.val.map ((of PUnit.{u+1}).const a).op x)) = _ from funext fun a ↦ NatTrans.naturality_apply f.val ((of PUnit.{u+1}).const a).op x] exact continuous_coinducingCoprod _ _ } /-- The functor `LightCondSet ⥤ TopCat` -/ @[simps] def _root_.lightCondSetToTopCat : LightCondSet.{u} ⥤ TopCat.{u} where obj X := X.toTopCat map f := toTopCatMap f /-- The counit of the adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` -/ noncomputable def topCatAdjunctionCounit (X : TopCat.{u}) : X.toLightCondSet.toTopCat ⟶ X := TopCat.ofHom { toFun x := x.1 PUnit.unit continuous_toFun := by rw [continuous_coinduced_dom] continuity } /-- The counit of the adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` is always bijective, but not an isomorphism in general (the inverse isn't continuous unless `X` is sequential). -/ noncomputable def topCatAdjunctionCounitEquiv (X : TopCat.{u}) : X.toLightCondSet.toTopCat ≃ X where toFun := topCatAdjunctionCounit X invFun x := ContinuousMap.const _ x lemma topCatAdjunctionCounit_bijective (X : TopCat.{u}) : Function.Bijective (topCatAdjunctionCounit X) := (topCatAdjunctionCounitEquiv X).bijective /-- The unit of the adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` -/ @[simps val_app val_app_apply] noncomputable def topCatAdjunctionUnit (X : LightCondSet.{u}) : X ⟶ X.toTopCat.toLightCondSet where val := { app := fun S x ↦ { toFun := fun s ↦ X.val.map ((of PUnit.{u+1}).const s).op x continuous_toFun := by suffices ∀ (i : (T : LightProfinite.{u}) × X.val.obj ⟨T⟩), Continuous (fun (a : i.fst) ↦ X.coinducingCoprod ⟨i, a⟩) from this ⟨_, _⟩ rw [← continuous_sigma_iff] apply continuous_coinduced_rng } naturality := fun _ _ _ ↦ by ext simp only [TopCat.toSheafCompHausLike_val_obj, Opposite.op_unop, types_comp_apply, TopCat.toSheafCompHausLike_val_map, ← FunctorToTypes.map_comp_apply] rfl } /-- The adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` -/ noncomputable def topCatAdjunction : lightCondSetToTopCat.{u} ⊣ topCatToLightCondSet where unit := { app := topCatAdjunctionUnit } counit := { app := topCatAdjunctionCounit } left_triangle_components Y := by ext change Y.val.map (𝟙 _) _ = _ simp instance (X : TopCat) : Epi (topCatAdjunction.counit.app X) := by rw [TopCat.epi_iff_surjective] exact (topCatAdjunctionCounit_bijective _).2 instance : topCatToLightCondSet.Faithful := topCatAdjunction.faithful_R_of_epi_counit_app open Sequential instance (X : LightCondSet.{u}) : SequentialSpace X.toTopCat := by apply SequentialSpace.coinduced instance (X : LightCondSet.{u}) : SequentialSpace (lightCondSetToTopCat.obj X) := inferInstanceAs (SequentialSpace X.toTopCat) /-- The functor from light condensed sets to topological spaces lands in sequential spaces. -/ def lightCondSetToSequential : LightCondSet.{u} ⥤ Sequential.{u} where obj X := Sequential.of (lightCondSetToTopCat.obj X) map f := toTopCatMap f /-- The functor from topological spaces to light condensed sets restricted to sequential spaces. -/ noncomputable def sequentialToLightCondSet : Sequential.{u} ⥤ LightCondSet.{u} := sequentialToTop ⋙ topCatToLightCondSet /-- The adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` restricted to sequential spaces. -/ noncomputable def sequentialAdjunction : lightCondSetToSequential ⊣ sequentialToLightCondSet := topCatAdjunction.restrictFullyFaithful (iC := 𝟭 _) (iD := sequentialToTop) (Functor.FullyFaithful.id _) fullyFaithfulSequentialToTop (Iso.refl _) (Iso.refl _) /-- The counit of the adjunction `lightCondSetToSequential ⊣ sequentialToLightCondSet` is a homeomorphism. Note: for now, we only have `ℕ∪{∞}` as a light profinite set at universe level 0, which is why we can only prove this for `X : TopCat.{0}`. -/ noncomputable def sequentialAdjunctionHomeo (X : TopCat.{0}) [SequentialSpace X] : X.toLightCondSet.toTopCat ≃ₜ X where toEquiv := topCatAdjunctionCounitEquiv X continuous_toFun := (topCatAdjunctionCounit X).hom.continuous continuous_invFun := by apply SeqContinuous.continuous unfold SeqContinuous intro f p h let g := (topCatAdjunctionCounitEquiv X).invFun ∘ (OnePoint.continuousMapMkNat f p h) change Filter.Tendsto (fun n : ℕ ↦ g n) _ _ erw [← OnePoint.continuous_iff_from_nat] let x : X.toLightCondSet.val.obj ⟨(ℕ∪{∞})⟩ := OnePoint.continuousMapMkNat f p h exact continuous_coinducingCoprod X.toLightCondSet x /-- The counit of the adjunction `lightCondSetToSequential ⊣ sequentialToLightCondSet` is an isomorphism. Note: for now, we only have `ℕ∪{∞}` as a light profinite set at universe level 0, which is why we can only prove this for `X : Sequential.{0}`. -/ noncomputable def sequentialAdjunctionCounitIso (X : Sequential.{0}) : lightCondSetToSequential.obj (sequentialToLightCondSet.obj X) ≅ X := isoOfHomeo (sequentialAdjunctionHomeo X.toTop) instance : IsIso sequentialAdjunction.{0}.counit := by rw [NatTrans.isIso_iff_isIso_app] intro X exact inferInstanceAs (IsIso (sequentialAdjunctionCounitIso X).hom) /-- The functor from topological spaces to light condensed sets restricted to sequential spaces is fully faithful. Note: for now, we only have `ℕ∪{∞}` as a light profinite set at universe level 0, which is why we can only prove this for the functor `Sequential.{0} ⥤ LightCondSet.{0}`. -/ noncomputable def fullyFaithfulSequentialToLightCondSet : sequentialToLightCondSet.{0}.FullyFaithful := sequentialAdjunction.fullyFaithfulROfIsIsoCounit end LightCondSet
Irreducible.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Kim Morrison, Jens Wagemaker -/ import Mathlib.Algebra.Polynomial.Eval.Coeff import Mathlib.Algebra.Polynomial.Eval.Degree import Mathlib.Algebra.Prime.Defs /-! # Mapping irreducible polynomials ## Main results * `Monic.irreducible_of_irreducible_map`: we can prove a monic polynomial is irreducible by mapping it to another integral domain and checking for irreducibility there. -/ noncomputable section open Finset AddMonoidAlgebra open Polynomial namespace Polynomial universe u v w y variable {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ} section variable [CommRing R] [IsDomain R] [CommRing S] [IsDomain S] (φ : R →+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ lemma Monic.irreducible_of_irreducible_map (f : R[X]) (h_mon : Monic f) (h_irr : Irreducible (f.map φ)) : Irreducible f := by refine ⟨h_irr.not_isUnit ∘ IsUnit.map (mapRingHom φ), fun a b h => ?_⟩ dsimp [Monic] at h_mon have q := (leadingCoeff_mul a b).symm rw [← h, h_mon] at q refine (h_irr.isUnit_or_isUnit <| (congr_arg (Polynomial.map φ) h).trans (Polynomial.map_mul φ)).imp ?_ ?_ <;> apply isUnit_of_isUnit_leadingCoeff_of_isUnit_map <;> apply isUnit_of_mul_eq_one · exact q · rw [mul_comm] exact q end end Polynomial
Small.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.Logic.Small.Basic import Mathlib.Data.Countable.Defs /-! # All countable types are small. That is, any countable type is equivalent to a type in any universe. -/ universe w v instance (priority := 100) Countable.toSmall (α : Type v) [Countable α] : Small.{w} α := let ⟨_, hf⟩ := exists_injective_nat α small_of_injective hf theorem Uncountable.of_not_small {α : Type v} (h : ¬ Small.{w} α) : Uncountable α := by rw [uncountable_iff_not_countable] exact mt (@Countable.toSmall α) h
Translations.lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import Mathlib.Algebra.ContinuedFractions.Basic import Mathlib.Algebra.GroupWithZero.Basic /-! # Basic Translation Lemmas Between Functions Defined for Continued Fractions ## Summary Some simple translation lemmas between the different definitions of functions defined in `Algebra.ContinuedFractions.Basic`. -/ namespace GenContFract section General /-! ### Translations Between General Access Functions Here we give some basic translations that hold by definition between the various methods that allow us to access the numerators and denominators of a continued fraction. -/ variable {α : Type*} {g : GenContFract α} {n : ℕ} theorem terminatedAt_iff_s_terminatedAt : g.TerminatedAt n ↔ g.s.TerminatedAt n := by rfl theorem terminatedAt_iff_s_none : g.TerminatedAt n ↔ g.s.get? n = none := by rfl theorem partNum_none_iff_s_none : g.partNums.get? n = none ↔ g.s.get? n = none := by cases s_nth_eq : g.s.get? n <;> simp [partNums, s_nth_eq] theorem terminatedAt_iff_partNum_none : g.TerminatedAt n ↔ g.partNums.get? n = none := by rw [terminatedAt_iff_s_none, partNum_none_iff_s_none] theorem partDen_none_iff_s_none : g.partDens.get? n = none ↔ g.s.get? n = none := by cases s_nth_eq : g.s.get? n <;> simp [partDens, s_nth_eq] theorem terminatedAt_iff_partDen_none : g.TerminatedAt n ↔ g.partDens.get? n = none := by rw [terminatedAt_iff_s_none, partDen_none_iff_s_none] theorem partNum_eq_s_a {gp : Pair α} (s_nth_eq : g.s.get? n = some gp) : g.partNums.get? n = some gp.a := by simp [partNums, s_nth_eq] theorem partDen_eq_s_b {gp : Pair α} (s_nth_eq : g.s.get? n = some gp) : g.partDens.get? n = some gp.b := by simp [partDens, s_nth_eq] theorem exists_s_a_of_partNum {a : α} (nth_partNum_eq : g.partNums.get? n = some a) : ∃ gp, g.s.get? n = some gp ∧ gp.a = a := by simpa [partNums, Stream'.Seq.map_get?] using nth_partNum_eq theorem exists_s_b_of_partDen {b : α} (nth_partDen_eq : g.partDens.get? n = some b) : ∃ gp, g.s.get? n = some gp ∧ gp.b = b := by simpa [partDens, Stream'.Seq.map_get?] using nth_partDen_eq end General section WithDivisionRing /-! ### Translations Between Computational Functions Here we give some basic translations that hold by definition for the computational methods of a continued fraction. -/ variable {K : Type*} {g : GenContFract K} {n : ℕ} [DivisionRing K] theorem nth_cont_eq_succ_nth_contAux : g.conts n = g.contsAux (n + 1) := rfl theorem num_eq_conts_a : g.nums n = (g.conts n).a := rfl theorem den_eq_conts_b : g.dens n = (g.conts n).b := rfl theorem conv_eq_num_div_den : g.convs n = g.nums n / g.dens n := rfl theorem conv_eq_conts_a_div_conts_b : g.convs n = (g.conts n).a / (g.conts n).b := rfl theorem exists_conts_a_of_num {A : K} (nth_num_eq : g.nums n = A) : ∃ conts, g.conts n = conts ∧ conts.a = A := by simpa theorem exists_conts_b_of_den {B : K} (nth_denom_eq : g.dens n = B) : ∃ conts, g.conts n = conts ∧ conts.b = B := by simpa @[simp] theorem zeroth_contAux_eq_one_zero : g.contsAux 0 = ⟨1, 0⟩ := rfl @[simp] theorem first_contAux_eq_h_one : g.contsAux 1 = ⟨g.h, 1⟩ := rfl @[simp] theorem zeroth_cont_eq_h_one : g.conts 0 = ⟨g.h, 1⟩ := rfl @[simp] theorem zeroth_num_eq_h : g.nums 0 = g.h := rfl @[simp] theorem zeroth_den_eq_one : g.dens 0 = 1 := rfl @[simp] theorem zeroth_conv_eq_h : g.convs 0 = g.h := by simp [conv_eq_num_div_den, num_eq_conts_a, den_eq_conts_b, div_one] theorem second_contAux_eq {gp : Pair K} (zeroth_s_eq : g.s.get? 0 = some gp) : g.contsAux 2 = ⟨gp.b * g.h + gp.a, gp.b⟩ := by simp [zeroth_s_eq, contsAux, nextConts, nextDen, nextNum] theorem first_cont_eq {gp : Pair K} (zeroth_s_eq : g.s.get? 0 = some gp) : g.conts 1 = ⟨gp.b * g.h + gp.a, gp.b⟩ := by simp [nth_cont_eq_succ_nth_contAux, second_contAux_eq zeroth_s_eq] theorem first_num_eq {gp : Pair K} (zeroth_s_eq : g.s.get? 0 = some gp) : g.nums 1 = gp.b * g.h + gp.a := by simp [num_eq_conts_a, first_cont_eq zeroth_s_eq] theorem first_den_eq {gp : Pair K} (zeroth_s_eq : g.s.get? 0 = some gp) : g.dens 1 = gp.b := by simp [den_eq_conts_b, first_cont_eq zeroth_s_eq] @[simp] theorem zeroth_conv'Aux_eq_zero {s : Stream'.Seq <| Pair K} : convs'Aux s 0 = (0 : K) := rfl @[simp] theorem zeroth_conv'_eq_h : g.convs' 0 = g.h := by simp [convs'] theorem convs'Aux_succ_none {s : Stream'.Seq (Pair K)} (h : s.head = none) (n : ℕ) : convs'Aux s (n + 1) = 0 := by simp [convs'Aux, h] theorem convs'Aux_succ_some {s : Stream'.Seq (Pair K)} {p : Pair K} (h : s.head = some p) (n : ℕ) : convs'Aux s (n + 1) = p.a / (p.b + convs'Aux s.tail n) := by simp [convs'Aux, h] end WithDivisionRing end GenContFract
Embedding.lean
/- Copyright (c) 2021 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import Mathlib.Logic.Embedding.Set /-! # Equivalences on embeddings This file shows some advanced equivalences on embeddings, useful for constructing larger embeddings from smaller ones. -/ open Function.Embedding namespace Equiv /-- Embeddings from a sum type are equivalent to two separate embeddings with disjoint ranges. -/ def sumEmbeddingEquivProdEmbeddingDisjoint {α β γ : Type*} : (α ⊕ β ↪ γ) ≃ { f : (α ↪ γ) × (β ↪ γ) // Disjoint (Set.range f.1) (Set.range f.2) } where toFun f := ⟨(inl.trans f, inr.trans f), by rw [Set.disjoint_left] rintro _ ⟨a, h⟩ ⟨b, rfl⟩ simp only at h have : Sum.inl a = Sum.inr b := f.injective h simp only [reduceCtorEq] at this⟩ invFun := fun ⟨⟨f, g⟩, disj⟩ => ⟨fun x => match x with | Sum.inl a => f a | Sum.inr b => g b, by rintro (a₁ | b₁) (a₂ | b₂) f_eq <;> simp only at f_eq · rw [f.injective f_eq] · exfalso exact disj.le_bot ⟨⟨a₁, f_eq⟩, ⟨b₂, by simp⟩⟩ · exfalso exact disj.le_bot ⟨⟨a₂, rfl⟩, ⟨b₁, f_eq⟩⟩ · rw [g.injective f_eq]⟩ left_inv f := by dsimp only ext x cases x <;> simp! right_inv := fun ⟨⟨f, g⟩, _⟩ => by simp only constructor /-- Embeddings whose range lies within a set are equivalent to embeddings to that set. This is `Function.Embedding.codRestrict` as an equiv. -/ def codRestrict (α : Type*) {β : Type*} (bs : Set β) : { f : α ↪ β // ∀ a, f a ∈ bs } ≃ (α ↪ bs) where toFun f := (f : α ↪ β).codRestrict bs f.prop invFun f := ⟨f.trans (Function.Embedding.subtype _), fun a => (f a).prop⟩ /-- Pairs of embeddings with disjoint ranges are equivalent to a dependent sum of embeddings, in which the second embedding cannot take values in the range of the first. -/ def prodEmbeddingDisjointEquivSigmaEmbeddingRestricted {α β γ : Type*} : { f : (α ↪ γ) × (β ↪ γ) // Disjoint (Set.range f.1) (Set.range f.2) } ≃ Σ f : α ↪ γ, β ↪ ↥(Set.range f)ᶜ := (subtypeProdEquivSigmaSubtype fun (a : α ↪ γ) (b : β ↪ _) => Disjoint (Set.range a) (Set.range b)).trans <| Equiv.sigmaCongrRight fun a => (subtypeEquivProp <| by ext f rw [← Set.range_subset_iff, Set.subset_compl_iff_disjoint_right, disjoint_comm]).trans (codRestrict _ _) /-- A combination of the above results, allowing us to turn one embedding over a sum type into two dependent embeddings, the second of which avoids any members of the range of the first. This is helpful for constructing larger embeddings out of smaller ones. -/ def sumEmbeddingEquivSigmaEmbeddingRestricted {α β γ : Type*} : (α ⊕ β ↪ γ) ≃ Σ f : α ↪ γ, β ↪ ↥(Set.range f)ᶜ := Equiv.trans sumEmbeddingEquivProdEmbeddingDisjoint prodEmbeddingDisjointEquivSigmaEmbeddingRestricted /-- Embeddings from a single-member type are equivalent to members of the target type. -/ def uniqueEmbeddingEquivResult {α β : Type*} [Unique α] : (α ↪ β) ≃ β where toFun f := f default invFun x := ⟨fun _ => x, fun _ _ _ => Subsingleton.elim _ _⟩ left_inv _ := by ext x simp_rw [Function.Embedding.coeFn_mk] congr 1 exact Subsingleton.elim _ x right_inv _ := by simp end Equiv
spectral.v
From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype choice ssrnat. From mathcomp Require Import seq div fintype bigop ssralg finset fingroup zmodp. From mathcomp Require Import poly polydiv order ssrnum matrix mxalgebra vector. From mathcomp Require Import mxpoly mxred sesquilinear. (******************************************************************************) (* Spectral theory *) (* *) (* This file provides a formalization of Gram-Schmidt orthonormalization, *) (* Schur decomposition, etc. *) (* *) (* M ^t* := M ^t conjC *) (* Notation in scope sesquilinear_scope. *) (* M \is unitarymx == M is a unitary matrix *) (* M : 'M[C]_(m, n) with C : numClosedFieldType *) (* M \is normalmx == M is a normal matrix *) (* M : 'M[C]_n with C : numClosedFieldType *) (* *) (* dotmx u v == dot product *) (* u and v are row vectors over a numClosedFieldType *) (* Local notations: '[u, v] := dotmx u v, *) (* '[u] := '[u, u] *) (* proj_ortho Y := proj_mx <<U>>%MS U^!%MS *) (* where U^! is a 1-orthogonal completement of U *) (* schmidt A == Gram-Schmidt basis *) (* A : 'M[C]_(m, n) *) (* schmidt_complete V := col_mx (schmidt (row_base V)) *) (* (schmidt (row_base V^!%MS)) *) (* spectralmx A, spectral_diag A == (M,X) s.t. A = M^-1 *m diag_mx X *m M *) (* A : 'M[C]_n *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory Order.Theory Num.Theory. Local Open Scope ring_scope. Local Open Scope sesquilinear_scope. (* TODO: move? *) Lemma eigenvalue_closed {C : numClosedFieldType} n (A : 'M[C]_n) : (n > 0)%N -> exists a, eigenvalue A a. Proof. move=> n_gt0; have /closed_rootP [a rAa] : size (char_poly A) != 1%N. by rewrite size_char_poly; case: (n) n_gt0. by exists a; rewrite eigenvalue_root_char. Qed. (* TODO: move? *) Lemma common_eigenvector {C : numClosedFieldType} n (As : seq 'M[C]_n) : (n > 0)%N -> {in As &, forall A B, comm_mx A B} -> exists2 v : 'rV_n, v != 0 & all (fun A => stablemx v A) As. Proof. move=> n_gt0 /all_comm_mxP; have [k sAsk] := ubnP (size As). elim: k n n_gt0 As sAsk => [//|k IHk] n n_gt0 [|A As]. exists (const_mx 1) => //; apply/negP => /eqP/rowP/(_ (Ordinal n_gt0)). by rewrite !mxE => /eqP; rewrite oner_eq0. rewrite ltnS all_comm_mx_cons => sAsk /andP[]. move=> /allP/(_ _ _)/eqP/= A_comm /all_comm_mxP As_comm. have [a a_eigen] := eigenvalue_closed A n_gt0. have [] := IHk _ _ [seq restrictmx (eigenspace A a) B | B <- As]. - by rewrite lt0n mxrank_eq0. - by rewrite size_map. - apply/all_comm_mxP; move=> _ _ /= /mapP /= [B B_in ->] /mapP /= [B' B'_in ->]. rewrite -?conjmxM ?inE ?stablemx_row_base ?comm_mx_stable_eigenspace//; by [rewrite As_comm | apply: As_comm | apply: A_comm]. move=> v vN0 /allP /= vP; exists (v *m (row_base (eigenspace A a))). by rewrite mulmx_free_eq0 ?row_base_free. apply/andP; split. by apply/eigenvectorP; exists a; rewrite mulmx_sub // eq_row_base. apply/allP => B B_in; rewrite -stablemx_restrict ?vP //. by apply/mapP; exists B. by rewrite comm_mx_stable_eigenspace //; exact: A_comm. Qed. (* TODO: move? *) Lemma common_eigenvector2 {C : numClosedFieldType}n (A B : 'M[C]_n) : (n > 0)%N -> A *m B = B *m A -> exists2 v : 'rV_n, v != 0 & (stablemx v A) && (stablemx v B). Proof. move=> n_gt0 AB_comm; have [] := @common_eigenvector _ _ [:: A; B] n_gt0. by move=> A' B'; rewrite !inE => /orP [] /eqP-> /orP [] /eqP->. by move=> v v_neq0 /allP vP; exists v; rewrite ?vP ?(mem_head, in_cons, orbT). Qed. Notation "M ^t*" := (M ^t conjC) (at level 30) : sesquilinear_scope. Notation realmx := (mxOver Num.real). Lemma trmxCK {C : numClosedFieldType} m n (A : 'M[C]_(m, n)) : A ^t* ^t* = A. Proof. by apply/matrixP=> i j; rewrite !mxE conjCK. Qed. Section realmx. Context {C : numClosedFieldType} {m n : nat}. Implicit Types A B : 'M[C]_(m, n). Lemma realmxC A : A \is a realmx -> A ^ conjC = A. Proof. by move=> ?; apply/matrixP => x y; rewrite mxE; exact/CrealP/mxOverP. Qed. Lemma realmxD A B : A \is a realmx -> B \is a realmx -> A + B \is a realmx. Proof. rewrite !qualifE/= => /'forall_forallP realA /'forall_forallP realB. by apply/'forall_forallP => i j; rewrite mxE realD. Qed. Lemma Remx_rect : {in realmx &, forall A B, (A + 'i *: B) ^ (@Re _) = A}. Proof. move=> A B Areal Breal; apply/matrixP=> i j; rewrite !mxE. by rewrite Re_rect // (mxOverP _ _). Qed. Lemma Immx_rect : {in realmx &, forall A B, (A + 'i *: B) ^ (@Im _) = B}. Proof. move=> /= A B Areal Breal; apply/matrixP=> i j; rewrite !mxE. by rewrite Im_rect // (mxOverP _ _). Qed. Lemma eqmx_ReiIm A B A' B' : A \is a realmx -> B \is a realmx -> A' \is a realmx -> B' \is a realmx -> (A + 'i *: B) = (A' + 'i *: B') -> (A, B) = (A', B'). Proof. move=> ARe BRe A'Im B'Im eqAB. have /(congr1 (fun A => A ^ (@Im _))) := eqAB. have /(congr1 (fun A => A ^ (@Re _))) := eqAB. by rewrite !Remx_rect// !Immx_rect// => -> ->. Qed. End realmx. Lemma realsym_hermsym {C : numClosedFieldType} {n} (A : 'M[C]_n) : A \is symmetricmx -> A \is a realmx -> A \is hermsymmx. Proof. move=> Asym Areal; apply/is_hermitianmxP. by rewrite (trmx_hermitian (HermitianMx Asym))/= !scale1r ?realmxC ?map_mx_id. Qed. Lemma real_similar {C : numClosedFieldType} {n} (A B : 'M[C]_n) : similar_in unitmx A B -> A \is a realmx -> B \is a realmx -> similar_in [predI realmx & unitmx] A B. Proof. case=> [P /=]; pose Pr := P ^ (@Re _); pose Pi := P ^ (@Im _). have Pr_real : Pr \is a realmx by apply/mxOverP=> i j; rewrite !mxE Creal_Re. have Pi_real : Pi \is a realmx by apply/mxOverP=> i j; rewrite !mxE Creal_Im. pose Q x := P ^ (@Re _) + x *: P ^ (@Im _). have -> : P = Q 'i by apply/matrixP=> i j; rewrite !mxE -Crect. move=> Qi_unit eq_AP_PB Areal Breal. pose p := \det (Pr ^ polyC + 'X *: Pi ^ polyC). have horner_evaliC x : horner_eval (x : C) \o polyC =1 id := fun=> hornerC _ _. have Qunit x : Q x \in unitmx = (p.[x] != 0). rewrite /p -horner_evalE -det_map_mx map_mxD map_mxZ/= horner_evalE hornerX. by rewrite -![(_ ^ polyC) ^ _]map_mx_comp !map_mx_id// unitmxE unitfE. have p_neq0 : p != 0. by move: Qi_unit; rewrite Qunit; apply: contra_neq => ->; rewrite hornerE. have [a a_real rootNa] : exists2 a, a \is Num.real & ~~ root p a. have rs_uniq : uniq [seq (i%:R : C) | i <- iota 0 (size p)]. by rewrite map_inj_uniq ?iota_uniq //; apply: mulrIn; rewrite oner_eq0. have := contraNN (fun x => max_poly_roots p_neq0 x rs_uniq). rewrite size_map size_iota ltnn => /(_ isT) /allPn[a a_in rootNpa]. by exists a => //; by move: a_in => /mapP [i _ ->]; rewrite realn. exists (Q a). rewrite inE Qunit rootNa andbT. rewrite /Q/=. by rewrite realmxD// mxOverZ. apply/similarP; rewrite ?Qunit//; move: eq_AP_PB => /(similarP Qi_unit). rewrite !mulmxDl !mulmxDr -!scalemxAr -!scalemxAl => /eqmx_ReiIm. by rewrite !mxOverM// => /(_ isT isT isT isT) [-> ->]. Qed. Section unitarymx. Context {C : numClosedFieldType}. Definition unitarymx {m n} := [qualify X : 'M[C]_(m, n) | X *m X ^t* == 1%:M]. Fact unitarymx_key m n : pred_key (@unitarymx m n). Proof. by []. Qed. Canonical unitarymx_keyed m n := KeyedQualifier (unitarymx_key m n). Lemma unitarymxP m n {M : 'M[C]_(m, n)} : reflect (M *m M^t* = 1%:M) (M \is unitarymx). Proof. by apply: (iffP eqP). Qed. Lemma mulmxtVK m1 m2 n (A : 'M[C]_(m1, n)) (B : 'M[C]_(n, m2)) : B \is unitarymx -> A *m B *m B^t* = A. Proof. by move=> B_unitary; rewrite -mulmxA (unitarymxP _) ?mulmx1. Qed. Lemma unitarymx_unit n (M : 'M[C]_n) : M \is unitarymx -> M \in unitmx. Proof. by move=> /unitarymxP /mulmx1_unit []. Qed. Lemma invmx_unitary n (M : 'M[C]_n) : M \is unitarymx -> invmx M = M^t*. Proof. move=> Munitary; apply: (@row_full_inj _ _ _ _ M). by rewrite row_full_unit unitarymx_unit. by rewrite mulmxV ?unitarymx_unit ?(unitarymxP _). Qed. Lemma mulmxKtV m1 m2 n (A : 'M[C]_(m1, n)) (B : 'M[C]_(m2, n)) : B \is unitarymx -> m2 = n -> A *m B^t* *m B = A. Proof. move=> B_unitary m2E; case: _ / (esym m2E) in B B_unitary *. by rewrite -invmx_unitary // mulmxKV //; exact: unitarymx_unit. Qed. Lemma mxrank_unitary m n (M : 'M[C]_(m, n)) : M \is unitarymx -> \rank M = m. Proof. rewrite qualifE => /eqP /(congr1 mxrank); rewrite mxrank1 => rkM. apply/eqP; rewrite eqn_leq rank_leq_row /= -[X in (X <= _)%N]rkM. by rewrite mxrankM_maxl. Qed. Lemma mul_unitarymx m n p (A : 'M[C]_(m, n)) (B : 'M[C]_(n, p)) : A \is unitarymx -> B \is unitarymx -> A *m B \is unitarymx. Proof. move=> Aunitary Bunitary; apply/unitarymxP; rewrite trmx_mul map_mxM. by rewrite mulmxA -[A *m _ *m _]mulmxA !(unitarymxP _, mulmx1). Qed. Lemma pinvmx_unitary n (M : 'M[C]_n) : M \is unitarymx -> pinvmx M = M^t*. Proof. by move=> Munitary; rewrite pinvmxE ?unitarymx_unit// invmx_unitary. Qed. Lemma conjymx n (P M : 'M[C]_n) : P \is unitarymx -> conjmx P M = P *m M *m P^t*. Proof. by move=> Munitary; rewrite conjumx ?invmx_unitary ?unitarymx_unit. Qed. Lemma trmx_unitary n (M : 'M[C]_n) : (M ^T \is unitarymx) = (M \is unitarymx). Proof. apply/unitarymxP/unitarymxP; rewrite -?map_trmx -trmx_mul. by rewrite -trmx1 => /trmx_inj /mulmx1C->; rewrite trmx1. by move=> /mulmx1C->; rewrite trmx1. Qed. Lemma conjC_unitary m n (M : 'M[C]_(m, n)) : (M ^ conjC \is unitarymx) = (M \is unitarymx). Proof. apply/unitarymxP/unitarymxP; rewrite -?map_mxM ?map_trmx; last first. by move=> ->; rewrite map_mx1. by rewrite -[1%:M](map_mx1 conjC) => /map_mx_inj ->; rewrite map_mx1. Qed. Lemma trmxC_unitary n (M : 'M[C]_n) : (M ^t* \is unitarymx) = (M \is unitarymx). Proof. by rewrite conjC_unitary trmx_unitary. Qed. End unitarymx. Section normalmx. Context {C : numClosedFieldType} {n : nat}. Definition normalmx := [qualify M : 'M[C]_n | M *m M ^t* == M ^t* *m M]. Fact normalmx_key : pred_key normalmx. Proof. by []. Qed. Canonical normalmx_keyed := KeyedQualifier normalmx_key. Lemma normalmxP {M : 'M[C]_n} : reflect (M *m M ^t* = M ^t* *m M) (M \is normalmx). Proof. exact: eqP. Qed. Lemma hermitian_normalmx (A : 'M[C]_n) : A \is hermsymmx -> A \is normalmx. Proof. move=> Ahermi; apply/normalmxP. by rewrite (trmx_hermitian (HermitianMx Ahermi)) scale1r map_mxCK. Qed. Lemma symmetric_normalmx (A : 'M[C]_n) : A \is symmetricmx -> A \is a realmx -> A \is normalmx. Proof. by move=> Asym Areal; rewrite hermitian_normalmx// realsym_hermsym. Qed. End normalmx. Section Spectral. Variable (C : numClosedFieldType). Set Default Proof Using "C". Local Notation dotmx_def := (form_of_matrix (@conjC _) 1%:M). Definition dotmx n (u v : 'rV[C]_n) := dotmx_def u%R v%R. (* TODO: bug report we were expecting HB.instance Definition _ n := Bilinear.on (@dotmx n). to be sufficient to equip dotmx with the bilinear structure but needed to use .copy in the end as in: *) HB.instance Definition _ n := Bilinear.copy (@dotmx n) dotmx_def. Local Notation "''[' u , v ]" := (dotmx u v) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. HB.instance Definition _ n := Hermitian.copy (@dotmx n) dotmx_def. Lemma dotmxE n (u v : 'rV[C]_n) : '[u, v] = ( u *m v ^t* ) 0 0. Proof. by rewrite /dotmx /form_of_matrix mulmx1 /= trace_mx11. Qed. Lemma row_unitarymxP m n {M : 'M[C]_(m, n)} : reflect (forall i j, '[row i M, row j M] = (i == j)%:R) (M \is unitarymx). Proof. apply: (iffP eqP) => [Mo i j|Mo]. have /matrixP/(_ i j) := Mo; rewrite !mxE => <-. by rewrite dotmxE !mxE; apply: eq_bigr => /= k _; rewrite !mxE. apply/matrixP=> i j; rewrite !mxE; have := Mo i j; rewrite dotmxE !mxE => <-. by apply: eq_bigr => /= k _; rewrite !mxE. Qed. Fact dotmx_is_dotmx n (u : 'rV[C]_n) : u != 0 -> 0 < '[u]. Proof. move=> u_neq0; rewrite dotmxE mxE. suff /existsP[i ui_neq0] : [exists i, u 0 i != 0]. rewrite (bigD1 i) //= ltr_wpDr// ?sumr_ge0// ?mxE ?mul_conjC_gt0//. by move=> j _; rewrite !mxE mul_conjC_ge0. apply: contraNT u_neq0; rewrite negb_exists => /forallP uNN0. by apply/eqP/rowP=> j; rewrite mxE; apply/eqP; rewrite -[_ == _]negbK uNN0. Qed. HB.instance Definition _ n := isDotProduct.Build _ _ (@dotmx n) (@dotmx_is_dotmx n). Local Notation "B ^!" := (orthomx (@conjC C) (mx_of_hermitian (hermitian1mx _)) B) : matrix_set_scope. Local Notation "A '_|_ B" := (A%MS <= B^!)%MS : bool_scope. Lemma orthomx1E m n p (A : 'M[C]_(m, n)) (B : 'M_(p, n)) : (A '_|_ B)%MS = (A *m B^t* == 0). Proof. by apply/sub_kermxP/eqP; rewrite !mul1mx. Qed. Lemma orthomx1P m n p {A : 'M[C]_(m, n)} {B : 'M_(p, n)} : reflect (A *m B^t* = 0) (A '_|_ B). Proof. by rewrite orthomx1E; exact/eqP. Qed. Lemma orthomx_disj n p q (A : 'M[C]_(p, n)) (B :'M_(q, n)) : A '_|_ B -> (A :&: B = 0)%MS. Proof. move=> nAB; apply/eqP/rowV0Pn => [[v]]; rewrite sub_capmx => /andP [vA vB]. apply/negP; rewrite negbK. by rewrite -(dnorm_eq0 (@dotmx n)) -orthomxE (orthomxP _ _ _ nAB). Qed. Lemma orthomx_ortho_disj n p (A : 'M[C]_(p, n)) : (A :&: A^! = 0)%MS. Proof. exact/orthomx_disj/ortho_mx_ortho. Qed. Lemma rank_ortho p n (A : 'M[C]_(p, n)) : \rank A^! = (n - \rank A)%N. Proof. by rewrite mxrank_ker mul1mx mxrank_map mxrank_tr. Qed. Lemma add_rank_ortho p n (A : 'M[C]_(p, n)) : (\rank A + \rank A^!)%N = n. Proof. by rewrite rank_ortho subnKC ?rank_leq_col. Qed. Lemma addsmx_ortho p n (A : 'M[C]_(p, n)) : (A + A^! :=: 1%:M)%MS. Proof. apply/eqmxP/andP; rewrite submx1; split=> //. rewrite -mxrank_leqif_sup ?submx1 ?mxrank1 ?(mxdirectP _) /= ?add_rank_ortho //. by rewrite mxdirect_addsE /= ?mxdirectE ?orthomx_ortho_disj !eqxx. Qed. Lemma ortho_id p n (A : 'M[C]_(p, n)) : (A^!^! :=: A)%MS. Proof. apply/eqmx_sym/eqmxP. by rewrite -mxrank_leqif_eq 1?orthomx_sym // !rank_ortho subKn // ?rank_leq_col. Qed. Lemma submx_ortho p m n (U : 'M[C]_(p, n)) (V : 'M_(m, n)) : (U^! <= V^!)%MS = (V <= U)%MS. Proof. by rewrite orthomx_sym ortho_id. Qed. Definition proj_ortho p n (U : 'M[C]_(p, n)) := proj_mx <<U>>%MS U^!%MS. Lemma sub_adds_genmx_ortho (p m n : nat) (U : 'M[C]_(p, n)) (W : 'M_(m, n)) : (W <= <<U>> + U^!)%MS. Proof. by rewrite !(adds_eqmx (genmxE _) (eqmx_refl _)) addsmx_ortho submx1. Qed. Local Hint Resolve sub_adds_genmx_ortho : core. Lemma cap_genmx_ortho p n (U : 'M[C]_(p, n)) : (<<U>> :&: U^!)%MS = 0. Proof. apply/eqmx0P; rewrite !(cap_eqmx (genmxE _) (eqmx_refl _)). by rewrite orthomx_ortho_disj; exact/eqmx0P. Qed. Local Hint Resolve cap_genmx_ortho : core. Lemma proj_ortho_sub p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : (W *m proj_ortho U <= U)%MS. Proof. by rewrite (submx_trans (proj_mx_sub _ _ _)) // genmxE. Qed. Lemma proj_ortho_compl_sub p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : (W - W *m proj_ortho U <= U^!)%MS. Proof. by rewrite proj_mx_compl_sub // addsmx_ortho submx1. Qed. Lemma proj_ortho_id p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : (W <= U)%MS -> W *m proj_ortho U = W. Proof. by move=> WU; rewrite proj_mx_id ?genmxE. Qed. Lemma proj_ortho_0 p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : (W <= U^!)%MS -> W *m proj_ortho U = 0. Proof. by move=> WUo; rewrite proj_mx_0. Qed. Lemma add_proj_ortho p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : W *m proj_ortho U + W *m proj_ortho U^!%MS = W. Proof. rewrite -[W in LHS](@add_proj_mx _ _ _ <<U>>%MS U^!%MS W)//. rewrite !mulmxDl proj_ortho_id ?proj_ortho_sub //. rewrite proj_ortho_0 ?proj_mx_sub // addr0. rewrite proj_ortho_0 ?ortho_id ?proj_ortho_sub // add0r. by rewrite proj_ortho_id ?proj_mx_sub// add_proj_mx. Qed. Lemma proj_ortho_proj m n (U : 'M_(m, n)) : let P := proj_ortho U in P *m P = P. Proof. by rewrite /= proj_mx_proj. Qed. Lemma proj_orthoE p n (U : 'M_(p, n)) : (proj_ortho U :=: U)%MS. Proof. apply/eqmxP/andP; split; first by rewrite -proj_ortho_proj proj_ortho_sub. by rewrite -[X in (X <= _)%MS](proj_ortho_id (submx_refl U)) mulmx_sub. Qed. Lemma orthomx_proj_mx_ortho p p' m m' n (A : 'M_(p, n)) (A' : 'M_(p', n)) (W : 'M_(m, n)) (W' : 'M_(m', n)) : A '_|_ A' -> W *m proj_ortho A '_|_ W' *m proj_ortho A'. Proof. rewrite orthomx_sym => An. rewrite mulmx_sub // orthomx_sym (eqmx_ortho _ (proj_orthoE _)). by rewrite (submx_trans _ An) // proj_ortho_sub. Qed. Lemma schmidt_subproof m n (A : 'M[C]_(m, n)) : (m <= n)%N -> exists2 B : 'M_(m, n), B \is unitarymx & [forall i : 'I_m, (row i A <= (\sum_(k < m | (k <= i)%N) <<row k B>>))%MS && ('[row i A, row i B] >= 0) ]. Proof. elim: m A => [|m IHm]. exists (pid_mx n); first by rewrite qualifE !thinmx0. by apply/forallP=> -[]. rewrite -addn1 => A leq_Sm_n. have lemSm : (m <= m + 1)%N by rewrite addn1. have ltmSm : (m < m + 1)%N by rewrite addn1. have lemn : (m <= n)%N by rewrite ltnW // -addn1. have [B Bortho] := IHm (usubmx A) lemn. move=> /forallP /= subAB. have [v /and4P [vBn v_neq0 dAv_ge0 dAsub]] : exists v, [&& B '_|_ v, v != 0, '[dsubmx A, v] >= 0 & (dsubmx A <= B + v)%MS]. have := add_proj_ortho B (dsubmx A). set BoSn := (_ *m proj_ortho _^!%MS) => pBE. have [BoSn_eq0|BoSn_neq0] := eqVneq BoSn 0. rewrite BoSn_eq0 addr0 in pBE. have /rowV0Pn [v vBn v_neq0] : B^!%MS != 0. rewrite -mxrank_eq0 rank_ortho -lt0n subn_gt0. by rewrite mxrank_unitary // -addn1. rewrite orthomx_sym in vBn. exists v; rewrite vBn v_neq0 -pBE. rewrite ['[_, _]](hermmx_eq0P _ _) ?lexx //=. rewrite (submx_trans (proj_ortho_sub _ _)) //. by rewrite -{1}[B]addr0 addmx_sub_adds ?sub0mx. by rewrite (submx_trans _ vBn) // proj_ortho_sub. pose c := (sqrtC '[BoSn])^-1; have c_gt0 : c > 0. by rewrite invr_gt0 sqrtC_gt0 lt_def ?dnorm_eq0 ?dnorm_ge0 BoSn_neq0. exists BoSn; apply/and4P; split => //. - by rewrite orthomx_sym ?proj_ortho_sub // /gtr_eqF. - rewrite -pBE linearDl //. rewrite [X in X + '[_]](hermmx_eq0P _ _) ?add0r ?dnorm_ge0 //. by rewrite orthomx_proj_mx_ortho // orthomx_sym. - by rewrite -pBE addmx_sub_adds // proj_ortho_sub. wlog nv_eq1 : v vBn v_neq0 dAv_ge0 dAsub / '[v] = 1. pose c := (sqrtC '[v])^-1. have c_gt0 : c > 0 by rewrite invr_gt0 sqrtC_gt0 ?dnorm_gt0. have [c_ge0 c_eq0F] := (ltW c_gt0, gt_eqF c_gt0). move=> /(_ (c *: v)); apply. - by rewrite orthomxZ ?c_eq0F. - by rewrite scaler_eq0 c_eq0F. - by rewrite linearZr mulr_ge0 // conjC_ge0. - by rewrite (submx_trans dAsub) // addsmxS // eqmx_scale // c_eq0F. - rewrite dnormZ normfV ger0_norm ?sqrtC_ge0 ?dnorm_ge0 //. by rewrite exprVn rootCK ?mulVf // dnorm_eq0. exists (col_mx B v). apply/row_unitarymxP => i j. case: (split_ordP i) (split_ordP j) => [] i' -> [] j' ->; rewrite eq_shift ?(rowKu, rowKd, row_id, ord1) -?val_eqE /= ?(row_unitarymxP _) //= ?addn0. by rewrite ['[_, _]](hermmx_eq0P _ _)//= (submx_trans _ vBn)// row_sub. rewrite ['[_, _]](hermmx_eq0P _ _)//= orthomx_sym (submx_trans _ vBn) //. exact: row_sub. apply/forallP => i; case: (split_ordP i) => j -> /=. have /andP [sABj dot_gt0] := subAB j. rewrite rowKu -row_usubmx (submx_trans sABj) //=. rewrite (eq_rect _ (submx _) (submx_refl _)) //. rewrite [in RHS](reindex (lshift 1)) /=. by apply: eq_bigr=> k k_le; rewrite rowKu. exists (fun k => insubd j k) => k; rewrite inE /= => le_kj; by apply/val_inj; rewrite /= insubdK // -topredE /= (leq_ltn_trans le_kj). rewrite rowKd -row_dsubmx !row_id ord1 ?dAv_ge0 ?andbT {j} addn0. rewrite (bigD1 (rshift _ ord0)) /= ?addn0 ?rowKd ?row_id // addsmxC. rewrite (submx_trans dAsub) // addsmxS ?genmxE //. apply/row_subP => j; apply/(sumsmx_sup (lshift _ j)) => //=. by rewrite ltnW ?ltn_ord //= -val_eqE /= addn0 ltn_eqF. by rewrite rowKu genmxE. Qed. Definition schmidt m n (A : 'M[C]_(m, n)) := if (m <= n)%N =P true is ReflectT le_mn then projT1 (sig2_eqW (schmidt_subproof A le_mn)) else A. Lemma schmidt_unitarymx m n (A : 'M[C]_(m, n)) : (m <= n)%N -> schmidt A \is unitarymx. Proof. by rewrite /schmidt; case: eqP => // ?; case: sig2_eqW. Qed. Hint Resolve schmidt_unitarymx : core. Lemma row_schmidt_sub m n (A : 'M[C]_(m, n)) i : (row i A <= (\sum_(k < m | (k <= i)%N) <<row k (schmidt A)>>))%MS. Proof. rewrite /schmidt; case: eqP => // ?. by case: sig2_eqW => ? ? /= /forallP /(_ i) /andP[]. by apply/(sumsmx_sup i) => //; rewrite genmxE. Qed. Lemma form1_row_schmidt m n (A : 'M[C]_(m, n)) i : '[row i A, row i (schmidt A)] >= 0. Proof. rewrite /schmidt; case: eqP => // ?; rewrite ?dnorm_ge0 //. by case: sig2_eqW => ? ? /= /forallP /(_ i) /andP[]. Qed. Lemma schmidt_sub m n (A : 'M[C]_(m, n)) : (A <= schmidt A)%MS. Proof. apply/row_subP => i; rewrite (submx_trans (row_schmidt_sub _ _)) //. by apply/sumsmx_subP => /= j le_ji; rewrite genmxE row_sub. Qed. Hint Resolve schmidt_sub : core. Lemma eqmx_schmidt_full m n (A : 'M[C]_(m, n)) : row_full A -> (schmidt A :=: A)%MS. Proof. move=> Afull; apply/eqmx_sym/eqmxP; rewrite -mxrank_leqif_eq //. by rewrite eqn_leq mxrankS //= (@leq_trans n) ?rank_leq_col ?col_leq_rank. Qed. Lemma eqmx_schmidt_free m n (A : 'M[C]_(m, n)) : row_free A -> (schmidt A :=: A)%MS. Proof. move=> Afree; apply/eqmx_sym/eqmxP; rewrite -mxrank_leqif_eq //. by rewrite eqn_leq mxrankS //= (@leq_trans m) ?rank_leq_row // ?row_leq_rank. Qed. Definition schmidt_complete m n (V : 'M[C]_(m, n)) := col_mx (schmidt (row_base V)) (schmidt (row_base V^!%MS)). Lemma schmidt_complete_unitarymx m n (V : 'M[C]_(m, n)) : schmidt_complete V \is unitarymx. Proof. apply/unitarymxP; rewrite tr_col_mx map_row_mx mul_col_row. rewrite !(unitarymxP _) ?schmidt_unitarymx ?rank_leq_col //. move=> [:nsV]; rewrite !(orthomx1P _) -?scalar_mx_block //; [abstract: nsV|]; last by rewrite orthomx_sym. by do 2!rewrite eqmx_schmidt_free ?eq_row_base ?row_base_free // orthomx_sym. Qed. Lemma cotrigonalization n (As : seq 'M[C]_n) : {in As &, forall A B, comm_mx A B} -> cotrigonalizable_in (@unitarymx C n n) As. Proof. elim: n {-2}n (leqnn n) As => [|N IHN] n. rewrite leqn0 => /eqP n_eq0. exists 1%:M; first by rewrite qualifE mul1mx trmx1 map_mx1. apply/allP => ? ?; apply/is_trig_mxP => i j. by suff: False by []; move: i; rewrite n_eq0 => -[]. rewrite leq_eqVlt => /predU1P [n_eqSN|/IHN//]. have /andP [n_gt0 n_small] : (n > 0)%N && (n - 1 <= N)%N. by rewrite n_eqSN /= subn1. move=> As As_comm; have [v vN0 /allP /= vP] := common_eigenvector n_gt0 As_comm. suff: exists2 P : 'M[C]_(\rank v + \rank v^!, n), P \is unitarymx & all (fun A => is_trig_mx (P *m A *m ( P^t* ))) As. rewrite add_rank_ortho // => -[P P_unitary] /=; rewrite -invmx_unitary//. by under eq_all do rewrite -conjumx ?unitarymx_unit//; exists P. pose S := schmidt_complete v. pose r A := S *m A *m S^t*. have vSvo X : stablemx v X -> schmidt (row_base v) *m X *m schmidt (row_base v^!%MS) ^t* = 0. move=> /eigenvectorP [a v_in]. rewrite (eigenspaceP (_ : (_ <= _ a))%MS); last first. by rewrite eqmx_schmidt_free ?row_base_free ?eq_row_base. rewrite -scalemxAl (orthomx1P _) ?scaler0 //. by do 2!rewrite eqmx_schmidt_free ?row_base_free ?eq_row_base // orthomx_sym. have drrE X : drsubmx (r X) = schmidt (row_base v^!%MS) *m X *m schmidt (row_base v^!%MS) ^t*. by rewrite /r mul_col_mx tr_col_mx map_row_mx mul_col_row block_mxKdr. have vSv X a : (v <= eigenspace X a)%MS -> schmidt (row_base v) *m X *m schmidt (row_base v) ^t* = a%:M. move=> vXa; rewrite (eigenspaceP (_ : (_ <= _ a)%MS)); last first. by rewrite eqmx_schmidt_free ?row_base_free ?eq_row_base. by rewrite -scalemxAl (unitarymxP _) ?scalemx1 ?schmidt_unitarymx ?rank_leq_col. have [] := IHN _ _ [seq drsubmx (r A) | A <- As]. - by rewrite rank_ortho rank_rV vN0. - move=> _ _ /mapP[/= A A_in ->] /mapP[/= B B_in ->]. have : (r A) *m (r B) = (r B) *m (r A). rewrite /r !mulmxA !mulmxKtV // ?schmidt_complete_unitarymx //; by rewrite ?add_rank_ortho // -![S *m _ *m _]mulmxA As_comm. rewrite -[r A in X in X -> _]submxK -[r B in X in X -> _]submxK. rewrite 2!mulmx_block => /eq_block_mx [_ _ _]. suff urr_eq0 X : X \in As -> ursubmx (r X) = 0. by rewrite !urr_eq0 ?mulmx0 ?add0r. rewrite /r /S ![schmidt_complete _ *m _]mul_col_mx. rewrite !tr_col_mx !map_row_mx !mul_col_row !block_mxKur. by move=> X_in; rewrite vSvo // vP. move=> P' P'_unitary /allP /= P'P. exists ((block_mx 1%:M 0 0 P') *m S). rewrite mul_unitarymx ?schmidt_complete_unitarymx //. apply/unitarymxP; rewrite tr_block_mx map_block_mx mulmx_block. rewrite !trmx0 !(@map_mx0 _ _ conjC) !tr_scalar_mx !map_scalar_mx ?conjC1. rewrite !(mulmx1, mul1mx, mulmx0, mul0mx, addr0, add0r). by rewrite (unitarymxP _) -?scalar_mx_block //. apply/allP => /= A A_in. rewrite trmx_mul map_mxM tr_block_mx map_block_mx. rewrite !trmx0 !map_mx0 !tr_scalar_mx !map_scalar_mx ?conjC1. rewrite mulmxA -[_ *m S *m _]mulmxA -[_ *m _ *m S^t*]mulmxA. rewrite /S ![schmidt_complete _ *m _]mul_col_mx. rewrite !tr_col_mx !map_row_mx !mul_col_row !mulmx_block. rewrite !(mulmx1, mul1mx, mulmx0, mul0mx, addr0, add0r). apply/is_trig_mxP => /= i j lt_ij; rewrite mxE. case: splitP => //= i' i_eq; rewrite !mxE; case: splitP => //= j' j_eq. - have /vP /eigenvectorP [a v_in] := A_in. by rewrite (vSv _ _ v_in) mxE -val_eqE ltn_eqF //= -i_eq -j_eq. - by rewrite vSvo ?mul0mx ?mxE // vP //. - move: lt_ij; rewrite i_eq j_eq ltnNge -ltnS (leq_trans (ltn_ord j'))//. by rewrite -addnS leq_addr. - set A' := _ *m A *m _; rewrite -invmx_unitary // -conjumx ?unitarymx_unit//. have /(_ _) /is_trig_mxP -> // := P'P A'; last first. by move: lt_ij; rewrite i_eq j_eq ltn_add2l. by apply/mapP; exists A; rewrite //= drrE. Qed. Theorem Schur n (A : 'M[C]_n) : (n > 0)%N -> trigonalizable_in (@unitarymx C n n) A. Proof. case: n => [//|n] in A * => _; have [] := @cotrigonalization _ [:: A]. by move=> ? ? /=; rewrite !in_cons !orbF => /eqP-> /eqP->. by move=> P P_unitary /=; rewrite andbT=> A_trigo; exists P. Qed. Lemma cotrigonalization2 n (A B : 'M[C]_n) : A *m B = B *m A -> exists2 P : 'M[C]_n, P \is unitarymx & similar_trig P A && similar_trig P B. Proof. move=> AB_comm; have [] := @cotrigonalization _ [:: A; B]. by move=> ??; rewrite !inE => /orP[]/eqP->/orP[]/eqP->. move=> P Punitary /allP /= PP; exists P => //. by rewrite !PP ?(mem_head, in_cons, orbT). Qed. Theorem orthomx_spectral_subproof n {A : 'M[C]_n} : reflect (exists2 sp : 'M_n * 'rV_n, sp.1 \is unitarymx & A = invmx sp.1 *m diag_mx sp.2 *m sp.1) (A \is normalmx). Proof. apply: (iffP normalmxP); last first. move=> [[/= P D] P_unitary ->]. rewrite !trmx_mul !map_mxM !mulmxA invmx_unitary //. rewrite !trmxCK ![_ *m P *m _]mulmxtVK //. by rewrite -[X in X *m P]mulmxA tr_diag_mx map_diag_mx diag_mxC mulmxA. move=> /cotrigonalization2 [P Punitary /andP[]] PA PATC. have Punit := unitarymx_unit Punitary. suff: similar_diag P A. move=> /similar_diagPex[D] PAD; exists (P, D) => //=. by rewrite -conjVmx//; exact/similarLR. apply/similar_diagPp => // i j; case: ltngtP => // [lt_ij|lt_ji] _. by have /is_trig_mxP-> := PA. have /is_trig_mxP -/(_ j i lt_ji)/eqP := PATC. rewrite !conjumx// invmx_unitary// -[P as X in X *m _]trmxCK. by rewrite -!map_mxM -!trmx_mul mulmxA 2!mxE conjC_eq0 => /eqP. Qed. Definition spectralmx n (A : 'M[C]_n) : 'M[C]_n := if @orthomx_spectral_subproof _ A is ReflectT P then (projT1 (sig2_eqW P)).1 else 1%:M. Definition spectral_diag n (A : 'M[C]_n) : 'rV_n := if @orthomx_spectral_subproof _ A is ReflectT P then (projT1 (sig2_eqW P)).2 else 0. Lemma spectral_unitarymx n (A : 'M[C]_n) : spectralmx A \is unitarymx. Proof. rewrite /spectralmx; case: orthomx_spectral_subproof; last first. by move=> _; apply/unitarymxP; rewrite trmx1 map_mx1 mulmx1. by move=> ?; case: sig2_eqW. Qed. Lemma spectral_unit n (A : 'M[C]_n) : spectralmx A \in unitmx. Proof. exact/unitarymx_unit/spectral_unitarymx. Qed. Theorem orthomx_spectralP {n} {A : 'M[C]_n} (P := spectralmx A) (sp := spectral_diag A) : reflect (A = invmx P *m diag_mx sp *m P) (A \is normalmx). Proof. rewrite /P /sp /spectralmx /spectral_diag. case: orthomx_spectral_subproof. by move=> Psp; case: sig2_eqW => //=; constructor. move=> /orthomx_spectral_subproof Ann; constructor; apply/eqP. apply: contra Ann; rewrite invmx1 mul1mx mulmx1 => /eqP->. suff -> : diag_mx 0 = 0 by rewrite qualifE trmx0 (map_mx0 conjC). by move=> ? ?; apply/matrixP=> i j; rewrite !mxE mul0rn. Qed. Lemma hermitian_spectral_diag_real n (A : 'M[C]_n) : A \is hermsymmx -> spectral_diag A \is a realmx. Proof. move=> Ahermi; have /hermitian_normalmx /orthomx_spectralP A_eq := Ahermi. have /(congr1 ( fun X => X^t* )) := A_eq. rewrite invmx_unitary ?spectral_unitarymx //. rewrite !trmx_mul !map_mxM map_trmx trmxK -map_mx_comp. rewrite tr_diag_mx map_diag_mx (map_mx_id (@conjCK _)). rewrite -[in RHS]invmx_unitary ?spectral_unitarymx //. have := is_hermitianmxP _ _ _ Ahermi; rewrite expr0 scale1r => <-. rewrite {1}A_eq mulmxA => /(congr1 (mulmx^~ (invmx (spectralmx A)))). rewrite !mulmxK ?spectral_unit//. move=> /(congr1 (mulmx (spectralmx A))); rewrite !mulKVmx ?spectral_unit//. move=> eq_A_conjA; apply/mxOverP => i j; rewrite ord1 {i}. have /matrixP /(_ j j) := eq_A_conjA; rewrite !mxE eqxx !mulr1n. by move=> /esym/CrealP. Qed. End Spectral.
Basic.lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Kexing Ying, Eric Wieser -/ import Mathlib.Data.Finset.Sym import Mathlib.LinearAlgebra.BilinearMap import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas import Mathlib.LinearAlgebra.Matrix.Determinant.Basic import Mathlib.LinearAlgebra.Matrix.SesquilinearForm import Mathlib.LinearAlgebra.Matrix.Symmetric /-! # Quadratic maps This file defines quadratic maps on an `R`-module `M`, taking values in an `R`-module `N`. An `N`-valued quadratic map on a module `M` over a commutative ring `R` is a map `Q : M → N` such that: * `QuadraticMap.map_smul`: `Q (a • x) = (a * a) • Q x` * `QuadraticMap.polar_add_left`, `QuadraticMap.polar_add_right`, `QuadraticMap.polar_smul_left`, `QuadraticMap.polar_smul_right`: the map `QuadraticMap.polar Q := fun x y ↦ Q (x + y) - Q x - Q y` is bilinear. This notion generalizes to commutative semirings using the approach in [izhakian2016][] which requires that there be a (possibly non-unique) companion bilinear map `B` such that `∀ x y, Q (x + y) = Q x + Q y + B x y`. Over a ring, this `B` is precisely `QuadraticMap.polar Q`. To build a `QuadraticMap` from the `polar` axioms, use `QuadraticMap.ofPolar`. Quadratic maps come with a scalar multiplication, `(a • Q) x = a • Q x`, and composition with linear maps `f`, `Q.comp f x = Q (f x)`. ## Main definitions * `QuadraticMap.ofPolar`: a more familiar constructor that works on rings * `QuadraticMap.associated`: associated bilinear map * `QuadraticMap.PosDef`: positive definite quadratic maps * `QuadraticMap.Anisotropic`: anisotropic quadratic maps * `QuadraticMap.discr`: discriminant of a quadratic map * `QuadraticMap.IsOrtho`: orthogonality of vectors with respect to a quadratic map. ## Main statements * `QuadraticMap.associated_left_inverse`, * `QuadraticMap.associated_rightInverse`: in a commutative ring where 2 has an inverse, there is a correspondence between quadratic maps and symmetric bilinear forms * `LinearMap.BilinForm.exists_orthogonal_basis`: There exists an orthogonal basis with respect to any nondegenerate, symmetric bilinear map `B`. ## Notation In this file, the variable `R` is used when a `CommSemiring` structure is available. The variable `S` is used when `R` itself has a `•` action. ## Implementation notes While the definition and many results make sense if we drop commutativity assumptions, the correct definition of a quadratic maps in the noncommutative setting would require substantial refactors from the current version, such that $Q(rm) = rQ(m)r^*$ for some suitable conjugation $r^*$. The [Zulip thread](https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/Quadratic.20Maps/near/395529867) has some further discussion. ## References * https://en.wikipedia.org/wiki/Quadratic_form * https://en.wikipedia.org/wiki/Discriminant#Quadratic_forms ## Tags quadratic map, homogeneous polynomial, quadratic polynomial -/ universe u v w variable {S T : Type*} variable {R : Type*} {M N P A : Type*} open LinearMap (BilinMap BilinForm) section Polar variable [CommRing R] [AddCommGroup M] [AddCommGroup N] namespace QuadraticMap /-- Up to a factor 2, `Q.polar` is the associated bilinear map for a quadratic map `Q`. Source of this name: https://en.wikipedia.org/wiki/Quadratic_form#Generalization -/ def polar (f : M → N) (x y : M) := f (x + y) - f x - f y protected theorem map_add (f : M → N) (x y : M) : f (x + y) = f x + f y + polar f x y := by rw [polar] abel theorem polar_add (f g : M → N) (x y : M) : polar (f + g) x y = polar f x y + polar g x y := by simp only [polar, Pi.add_apply] abel theorem polar_neg (f : M → N) (x y : M) : polar (-f) x y = -polar f x y := by simp only [polar, Pi.neg_apply, sub_eq_add_neg, neg_add] theorem polar_smul [Monoid S] [DistribMulAction S N] (f : M → N) (s : S) (x y : M) : polar (s • f) x y = s • polar f x y := by simp only [polar, Pi.smul_apply, smul_sub] theorem polar_comm (f : M → N) (x y : M) : polar f x y = polar f y x := by rw [polar, polar, add_comm, sub_sub, sub_sub, add_comm (f x) (f y)] /-- Auxiliary lemma to express bilinearity of `QuadraticMap.polar` without subtraction. -/ theorem polar_add_left_iff {f : M → N} {x x' y : M} : polar f (x + x') y = polar f x y + polar f x' y ↔ f (x + x' + y) + (f x + f x' + f y) = f (x + x') + f (x' + y) + f (y + x) := by simp only [← add_assoc] simp only [polar, sub_eq_iff_eq_add, eq_sub_iff_add_eq, sub_add_eq_add_sub, add_sub] simp only [add_right_comm _ (f y) _, add_right_comm _ (f x') (f x)] rw [add_comm y x, add_right_comm _ _ (f (x + y)), add_comm _ (f (x + y)), add_right_comm (f (x + y)), add_left_inj] theorem polar_comp {F : Type*} [AddCommGroup S] [FunLike F N S] [AddMonoidHomClass F N S] (f : M → N) (g : F) (x y : M) : polar (g ∘ f) x y = g (polar f x y) := by simp only [polar, Function.comp_apply, map_sub] /-- `QuadraticMap.polar` as a function from `Sym2`. -/ def polarSym2 (f : M → N) : Sym2 M → N := Sym2.lift ⟨polar f, polar_comm _⟩ @[simp] lemma polarSym2_sym2Mk (f : M → N) (xy : M × M) : polarSym2 f (.mk xy) = polar f xy.1 xy.2 := rfl end QuadraticMap end Polar /-- A quadratic map on a module. For a more familiar constructor when `R` is a ring, see `QuadraticMap.ofPolar`. -/ structure QuadraticMap (R : Type u) (M : Type v) (N : Type w) [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] where /-- The underlying function. Do NOT use directly. Use the coercion instead. -/ toFun : M → N toFun_smul : ∀ (a : R) (x : M), toFun (a • x) = (a * a) • toFun x exists_companion' : ∃ B : BilinMap R M N, ∀ x y, toFun (x + y) = toFun x + toFun y + B x y section QuadraticForm variable (R : Type u) (M : Type v) [CommSemiring R] [AddCommMonoid M] [Module R M] /-- A quadratic form on a module. -/ abbrev QuadraticForm : Type _ := QuadraticMap R M R end QuadraticForm namespace QuadraticMap section DFunLike variable [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] variable {Q Q' : QuadraticMap R M N} instance instFunLike : FunLike (QuadraticMap R M N) M N where coe := toFun coe_injective' x y h := by cases x; cases y; congr variable (Q) /-- The `simp` normal form for a quadratic map is `DFunLike.coe`, not `toFun`. -/ @[simp] theorem toFun_eq_coe : Q.toFun = ⇑Q := rfl @[simp] theorem coe_mk (toFun : M → N) (toFun_smul exists_companion') : ⇑({toFun, toFun_smul, exists_companion'} : QuadraticMap R M N) = toFun := rfl -- this must come after the instFunLike definition initialize_simps_projections QuadraticMap (toFun → apply) variable {Q} @[ext] theorem ext (H : ∀ x : M, Q x = Q' x) : Q = Q' := DFunLike.ext _ _ H theorem congr_fun (h : Q = Q') (x : M) : Q x = Q' x := DFunLike.congr_fun h _ /-- Copy of a `QuadraticMap` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (Q : QuadraticMap R M N) (Q' : M → N) (h : Q' = ⇑Q) : QuadraticMap R M N where toFun := Q' toFun_smul := h.symm ▸ Q.toFun_smul exists_companion' := h.symm ▸ Q.exists_companion' @[simp] theorem coe_copy (Q : QuadraticMap R M N) (Q' : M → N) (h : Q' = ⇑Q) : ⇑(Q.copy Q' h) = Q' := rfl theorem copy_eq (Q : QuadraticMap R M N) (Q' : M → N) (h : Q' = ⇑Q) : Q.copy Q' h = Q := DFunLike.ext' h end DFunLike section CommSemiring variable [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] variable (Q : QuadraticMap R M N) protected theorem map_smul (a : R) (x : M) : Q (a • x) = (a * a) • Q x := Q.toFun_smul a x theorem exists_companion : ∃ B : BilinMap R M N, ∀ x y, Q (x + y) = Q x + Q y + B x y := Q.exists_companion' theorem map_add_add_add_map (x y z : M) : Q (x + y + z) + (Q x + Q y + Q z) = Q (x + y) + Q (y + z) + Q (z + x) := by obtain ⟨B, h⟩ := Q.exists_companion rw [add_comm z x] simp only [h, LinearMap.map_add₂] abel theorem map_add_self (x : M) : Q (x + x) = 4 • Q x := by rw [← two_smul R x, Q.map_smul, ← Nat.cast_smul_eq_nsmul R] norm_num -- not @[simp] because it is superseded by `ZeroHomClass.map_zero` protected theorem map_zero : Q 0 = 0 := by rw [← @zero_smul R _ _ _ _ (0 : M), Q.map_smul, zero_mul, zero_smul] instance zeroHomClass : ZeroHomClass (QuadraticMap R M N) M N := { QuadraticMap.instFunLike (R := R) (M := M) (N := N) with map_zero := QuadraticMap.map_zero } theorem map_smul_of_tower [CommSemiring S] [Algebra S R] [SMul S M] [IsScalarTower S R M] [Module S N] [IsScalarTower S R N] (a : S) (x : M) : Q (a • x) = (a * a) • Q x := by rw [← IsScalarTower.algebraMap_smul R a x, Q.map_smul, ← RingHom.map_mul, algebraMap_smul] end CommSemiring section CommRing variable [CommRing R] [AddCommGroup M] [AddCommGroup N] variable [Module R M] [Module R N] (Q : QuadraticMap R M N) @[simp] protected theorem map_neg (x : M) : Q (-x) = Q x := by rw [← @neg_one_smul R _ _ _ _ x, Q.map_smul, neg_one_mul, neg_neg, one_smul] protected theorem map_sub (x y : M) : Q (x - y) = Q (y - x) := by rw [← neg_sub, Q.map_neg] @[simp] theorem polar_zero_left (y : M) : polar Q 0 y = 0 := by simp only [polar, zero_add, QuadraticMap.map_zero, sub_zero, sub_self] @[simp] theorem polar_add_left (x x' y : M) : polar Q (x + x') y = polar Q x y + polar Q x' y := polar_add_left_iff.mpr <| Q.map_add_add_add_map x x' y @[simp] theorem polar_smul_left (a : R) (x y : M) : polar Q (a • x) y = a • polar Q x y := by obtain ⟨B, h⟩ := Q.exists_companion simp_rw [polar, h, Q.map_smul, LinearMap.map_smul₂, sub_sub, add_sub_cancel_left] @[simp] theorem polar_neg_left (x y : M) : polar Q (-x) y = -polar Q x y := by rw [← neg_one_smul R x, polar_smul_left, neg_one_smul] @[simp] theorem polar_sub_left (x x' y : M) : polar Q (x - x') y = polar Q x y - polar Q x' y := by rw [sub_eq_add_neg, sub_eq_add_neg, polar_add_left, polar_neg_left] @[simp] theorem polar_zero_right (y : M) : polar Q y 0 = 0 := by simp only [add_zero, polar, QuadraticMap.map_zero, sub_self] @[simp] theorem polar_add_right (x y y' : M) : polar Q x (y + y') = polar Q x y + polar Q x y' := by rw [polar_comm Q x, polar_comm Q x, polar_comm Q x, polar_add_left] @[simp] theorem polar_smul_right (a : R) (x y : M) : polar Q x (a • y) = a • polar Q x y := by rw [polar_comm Q x, polar_comm Q x, polar_smul_left] @[simp] theorem polar_neg_right (x y : M) : polar Q x (-y) = -polar Q x y := by rw [← neg_one_smul R y, polar_smul_right, neg_one_smul] @[simp] theorem polar_sub_right (x y y' : M) : polar Q x (y - y') = polar Q x y - polar Q x y' := by rw [sub_eq_add_neg, sub_eq_add_neg, polar_add_right, polar_neg_right] @[simp] theorem polar_self (x : M) : polar Q x x = 2 • Q x := by rw [polar, map_add_self, sub_sub, sub_eq_iff_eq_add, ← two_smul ℕ, ← two_smul ℕ, ← mul_smul] norm_num /-- `QuadraticMap.polar` as a bilinear map -/ @[simps!] def polarBilin : BilinMap R M N := LinearMap.mk₂ R (polar Q) (polar_add_left Q) (polar_smul_left Q) (polar_add_right Q) (polar_smul_right Q) lemma polarSym2_map_smul {ι} (Q : QuadraticMap R M N) (g : ι → M) (l : ι → R) (p : Sym2 ι) : polarSym2 Q (p.map (l • g)) = (p.map l).mul • polarSym2 Q (p.map g) := by obtain ⟨_, _⟩ := p; simp [← smul_assoc, mul_comm] variable [CommSemiring S] [Algebra S R] [Module S M] [IsScalarTower S R M] [Module S N] [IsScalarTower S R N] @[simp] theorem polar_smul_left_of_tower (a : S) (x y : M) : polar Q (a • x) y = a • polar Q x y := by rw [← IsScalarTower.algebraMap_smul R a x, polar_smul_left, algebraMap_smul] @[simp] theorem polar_smul_right_of_tower (a : S) (x y : M) : polar Q x (a • y) = a • polar Q x y := by rw [← IsScalarTower.algebraMap_smul R a y, polar_smul_right, algebraMap_smul] /-- An alternative constructor to `QuadraticMap.mk`, for rings where `polar` can be used. -/ @[simps] def ofPolar (toFun : M → N) (toFun_smul : ∀ (a : R) (x : M), toFun (a • x) = (a * a) • toFun x) (polar_add_left : ∀ x x' y : M, polar toFun (x + x') y = polar toFun x y + polar toFun x' y) (polar_smul_left : ∀ (a : R) (x y : M), polar toFun (a • x) y = a • polar toFun x y) : QuadraticMap R M N := { toFun toFun_smul exists_companion' := ⟨LinearMap.mk₂ R (polar toFun) (polar_add_left) (polar_smul_left) (fun x _ _ ↦ by simp_rw [polar_comm _ x, polar_add_left]) (fun _ _ _ ↦ by rw [polar_comm, polar_smul_left, polar_comm]), fun _ _ ↦ by simp only [LinearMap.mk₂_apply] rw [polar, sub_sub, add_sub_cancel]⟩ } /-- In a ring the companion bilinear form is unique and equal to `QuadraticMap.polar`. -/ theorem choose_exists_companion : Q.exists_companion.choose = polarBilin Q := LinearMap.ext₂ fun x y => by rw [polarBilin_apply_apply, polar, Q.exists_companion.choose_spec, sub_sub, add_sub_cancel_left] protected theorem map_sum {ι} [DecidableEq ι] (Q : QuadraticMap R M N) (s : Finset ι) (f : ι → M) : Q (∑ i ∈ s, f i) = ∑ i ∈ s, Q (f i) + ∑ ij ∈ s.sym2 with ¬ ij.IsDiag, polarSym2 Q (ij.map f) := by induction s using Finset.cons_induction with | empty => simp | cons a s ha ih => simp_rw [Finset.sum_cons, QuadraticMap.map_add, ih, add_assoc, Finset.sym2_cons, Finset.sum_filter, Finset.sum_disjUnion, Finset.sum_map, Finset.sum_cons, Sym2.mkEmbedding_apply, Sym2.isDiag_iff_proj_eq, not_true, if_false, zero_add, Sym2.map_pair_eq, polarSym2_sym2Mk, ← polarBilin_apply_apply, _root_.map_sum, polarBilin_apply_apply] congr 2 rw [add_comm] congr! with i hi rw [if_pos (ne_of_mem_of_not_mem hi ha).symm] protected theorem map_sum' {ι} (Q : QuadraticMap R M N) (s : Finset ι) (f : ι → M) : Q (∑ i ∈ s, f i) = ∑ ij ∈ s.sym2, polarSym2 Q (ij.map f) - ∑ i ∈ s, Q (f i) := by induction s using Finset.cons_induction with | empty => simp | cons a s ha ih => simp_rw [Finset.sum_cons, QuadraticMap.map_add Q, ih, add_assoc, Finset.sym2_cons, Finset.sum_disjUnion, Finset.sum_map, Finset.sum_cons, Sym2.mkEmbedding_apply, Sym2.map_pair_eq, polarSym2_sym2Mk, ← polarBilin_apply_apply, _root_.map_sum, polarBilin_apply_apply, polar_self] abel_nf end CommRing section SemiringOperators variable [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] section SMul variable [Monoid S] [Monoid T] [DistribMulAction S N] [DistribMulAction T N] variable [SMulCommClass S R N] [SMulCommClass T R N] /-- `QuadraticMap R M N` inherits the scalar action from any algebra over `R`. This provides an `R`-action via `Algebra.id`. -/ instance : SMul S (QuadraticMap R M N) := ⟨fun a Q => { toFun := a • ⇑Q toFun_smul := fun b x => by rw [Pi.smul_apply, Q.map_smul, Pi.smul_apply, smul_comm] exists_companion' := let ⟨B, h⟩ := Q.exists_companion letI := SMulCommClass.symm S R N ⟨a • B, by simp [h]⟩ }⟩ @[simp, norm_cast] theorem coeFn_smul (a : S) (Q : QuadraticMap R M N) : ⇑(a • Q) = a • ⇑Q := rfl @[simp] theorem smul_apply (a : S) (Q : QuadraticMap R M N) (x : M) : (a • Q) x = a • Q x := rfl instance [SMulCommClass S T N] : SMulCommClass S T (QuadraticMap R M N) where smul_comm _s _t _q := ext fun _ => smul_comm _ _ _ instance [SMul S T] [IsScalarTower S T N] : IsScalarTower S T (QuadraticMap R M N) where smul_assoc _s _t _q := ext fun _ => smul_assoc _ _ _ end SMul instance : Zero (QuadraticMap R M N) := ⟨{ toFun := fun _ => 0 toFun_smul := fun a _ => by simp only [smul_zero] exists_companion' := ⟨0, fun _ _ => by simp only [add_zero, LinearMap.zero_apply]⟩ }⟩ @[simp, norm_cast] theorem coeFn_zero : ⇑(0 : QuadraticMap R M N) = 0 := rfl @[simp] theorem zero_apply (x : M) : (0 : QuadraticMap R M N) x = 0 := rfl instance : Inhabited (QuadraticMap R M N) := ⟨0⟩ instance : Add (QuadraticMap R M N) := ⟨fun Q Q' => { toFun := Q + Q' toFun_smul := fun a x => by simp only [Pi.add_apply, smul_add, QuadraticMap.map_smul] exists_companion' := let ⟨B, h⟩ := Q.exists_companion let ⟨B', h'⟩ := Q'.exists_companion ⟨B + B', fun x y => by simp_rw [Pi.add_apply, h, h', LinearMap.add_apply, add_add_add_comm]⟩ }⟩ @[simp, norm_cast] theorem coeFn_add (Q Q' : QuadraticMap R M N) : ⇑(Q + Q') = Q + Q' := rfl @[simp] theorem add_apply (Q Q' : QuadraticMap R M N) (x : M) : (Q + Q') x = Q x + Q' x := rfl instance : AddCommMonoid (QuadraticMap R M N) := DFunLike.coe_injective.addCommMonoid _ coeFn_zero coeFn_add fun _ _ => coeFn_smul _ _ /-- `@CoeFn (QuadraticMap R M)` as an `AddMonoidHom`. This API mirrors `AddMonoidHom.coeFn`. -/ @[simps apply] def coeFnAddMonoidHom : QuadraticMap R M N →+ M → N where toFun := DFunLike.coe map_zero' := coeFn_zero map_add' := coeFn_add /-- Evaluation on a particular element of the module `M` is an additive map on quadratic maps. -/ @[simps! apply] def evalAddMonoidHom (m : M) : QuadraticMap R M N →+ N := (Pi.evalAddMonoidHom _ m).comp coeFnAddMonoidHom section Sum @[simp, norm_cast] theorem coeFn_sum {ι : Type*} (Q : ι → QuadraticMap R M N) (s : Finset ι) : ⇑(∑ i ∈ s, Q i) = ∑ i ∈ s, ⇑(Q i) := map_sum coeFnAddMonoidHom Q s @[simp] theorem sum_apply {ι : Type*} (Q : ι → QuadraticMap R M N) (s : Finset ι) (x : M) : (∑ i ∈ s, Q i) x = ∑ i ∈ s, Q i x := map_sum (evalAddMonoidHom x : _ →+ N) Q s end Sum instance [Monoid S] [DistribMulAction S N] [SMulCommClass S R N] : DistribMulAction S (QuadraticMap R M N) where mul_smul a b Q := ext fun x => by simp only [smul_apply, mul_smul] one_smul Q := ext fun x => by simp only [QuadraticMap.smul_apply, one_smul] smul_add a Q Q' := by ext simp only [add_apply, smul_apply, smul_add] smul_zero a := by ext simp only [zero_apply, smul_apply, smul_zero] instance [Semiring S] [Module S N] [SMulCommClass S R N] : Module S (QuadraticMap R M N) where zero_smul Q := by ext simp only [zero_apply, smul_apply, zero_smul] add_smul a b Q := by ext simp only [add_apply, smul_apply, add_smul] end SemiringOperators section RingOperators variable [CommRing R] [AddCommGroup M] [Module R M] [AddCommGroup N] [Module R N] instance : Neg (QuadraticMap R M N) := ⟨fun Q => { toFun := -Q toFun_smul := fun a x => by simp only [Pi.neg_apply, Q.map_smul, smul_neg] exists_companion' := let ⟨B, h⟩ := Q.exists_companion ⟨-B, fun x y => by simp_rw [Pi.neg_apply, h, LinearMap.neg_apply, neg_add]⟩ }⟩ @[simp, norm_cast] theorem coeFn_neg (Q : QuadraticMap R M N) : ⇑(-Q) = -Q := rfl @[simp] theorem neg_apply (Q : QuadraticMap R M N) (x : M) : (-Q) x = -Q x := rfl instance : Sub (QuadraticMap R M N) := ⟨fun Q Q' => (Q + -Q').copy (Q - Q') (sub_eq_add_neg _ _)⟩ @[simp, norm_cast] theorem coeFn_sub (Q Q' : QuadraticMap R M N) : ⇑(Q - Q') = Q - Q' := rfl @[simp] theorem sub_apply (Q Q' : QuadraticMap R M N) (x : M) : (Q - Q') x = Q x - Q' x := rfl instance : AddCommGroup (QuadraticMap R M N) := DFunLike.coe_injective.addCommGroup _ coeFn_zero coeFn_add coeFn_neg coeFn_sub (fun _ _ => coeFn_smul _ _) fun _ _ => coeFn_smul _ _ end RingOperators section restrictScalars variable [CommSemiring R] [CommSemiring S] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] [Module S M] [Module S N] [Algebra S R] variable [IsScalarTower S R M] [IsScalarTower S R N] /-- If `Q : M → N` is a quadratic map of `R`-modules and `R` is an `S`-algebra, then the restriction of scalars is a quadratic map of `S`-modules. -/ @[simps!] def restrictScalars (Q : QuadraticMap R M N) : QuadraticMap S M N where toFun x := Q x toFun_smul a x := by simp [map_smul_of_tower] exists_companion' := let ⟨B, h⟩ := Q.exists_companion ⟨B.restrictScalars₁₂ (S := R) (R' := S) (S' := S), fun x y => by simp only [LinearMap.restrictScalars₁₂_apply_apply, h]⟩ end restrictScalars section Comp variable [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] variable [AddCommMonoid P] [Module R P] /-- Compose the quadratic map with a linear function on the right. -/ def comp (Q : QuadraticMap R N P) (f : M →ₗ[R] N) : QuadraticMap R M P where toFun x := Q (f x) toFun_smul a x := by simp only [Q.map_smul, map_smul] exists_companion' := let ⟨B, h⟩ := Q.exists_companion ⟨B.compl₁₂ f f, fun x y => by simp_rw [f.map_add]; exact h (f x) (f y)⟩ @[simp] theorem comp_apply (Q : QuadraticMap R N P) (f : M →ₗ[R] N) (x : M) : (Q.comp f) x = Q (f x) := rfl /-- Compose a quadratic map with a linear function on the left. -/ @[simps +simpRhs] def _root_.LinearMap.compQuadraticMap (f : N →ₗ[R] P) (Q : QuadraticMap R M N) : QuadraticMap R M P where toFun x := f (Q x) toFun_smul b x := by simp only [Q.map_smul, map_smul] exists_companion' := let ⟨B, h⟩ := Q.exists_companion ⟨B.compr₂ f, fun x y => by simp only [h, map_add, LinearMap.compr₂_apply]⟩ /-- Compose a quadratic map with a linear function on the left. -/ @[simps! +simpRhs] def _root_.LinearMap.compQuadraticMap' [CommSemiring S] [Algebra S R] [Module S N] [Module S M] [IsScalarTower S R N] [IsScalarTower S R M] [Module S P] (f : N →ₗ[S] P) (Q : QuadraticMap R M N) : QuadraticMap S M P := _root_.LinearMap.compQuadraticMap f Q.restrictScalars /-- When `N` and `P` are equivalent, quadratic maps on `M` into `N` are equivalent to quadratic maps on `M` into `P`. See `LinearMap.BilinMap.congr₂` for the bilinear map version. -/ @[simps] def _root_.LinearEquiv.congrQuadraticMap (e : N ≃ₗ[R] P) : QuadraticMap R M N ≃ₗ[R] QuadraticMap R M P where toFun Q := e.compQuadraticMap Q invFun Q := e.symm.compQuadraticMap Q left_inv _ := ext fun _ => e.symm_apply_apply _ right_inv _ := ext fun _ => e.apply_symm_apply _ map_add' _ _ := ext fun _ => map_add e _ _ map_smul' _ _ := ext fun _ => e.map_smul _ _ @[simp] theorem _root_.LinearEquiv.congrQuadraticMap_refl : LinearEquiv.congrQuadraticMap (.refl R N) = .refl R (QuadraticMap R M N) := rfl @[simp] theorem _root_.LinearEquiv.congrQuadraticMap_symm (e : N ≃ₗ[R] P) : (LinearEquiv.congrQuadraticMap e (M := M)).symm = e.symm.congrQuadraticMap := rfl end Comp section NonUnitalNonAssocSemiring variable [CommSemiring R] [NonUnitalNonAssocSemiring A] [AddCommMonoid M] [Module R M] variable [Module R A] [SMulCommClass R A A] [IsScalarTower R A A] /-- The product of linear maps into an `R`-algebra is a quadratic map. -/ def linMulLin (f g : M →ₗ[R] A) : QuadraticMap R M A where toFun := f * g toFun_smul a x := by rw [Pi.mul_apply, Pi.mul_apply, LinearMap.map_smulₛₗ, RingHom.id_apply, LinearMap.map_smulₛₗ, RingHom.id_apply, smul_mul_assoc, mul_smul_comm, ← smul_assoc, smul_eq_mul] exists_companion' := ⟨(LinearMap.mul R A).compl₁₂ f g + (LinearMap.mul R A).flip.compl₁₂ g f, fun x y => by simp only [Pi.mul_apply, map_add, left_distrib, right_distrib, LinearMap.add_apply, LinearMap.compl₁₂_apply, LinearMap.mul_apply', LinearMap.flip_apply] abel_nf⟩ @[simp] theorem linMulLin_apply (f g : M →ₗ[R] A) (x) : linMulLin f g x = f x * g x := rfl @[simp] theorem add_linMulLin (f g h : M →ₗ[R] A) : linMulLin (f + g) h = linMulLin f h + linMulLin g h := ext fun _ => add_mul _ _ _ @[simp] theorem linMulLin_add (f g h : M →ₗ[R] A) : linMulLin f (g + h) = linMulLin f g + linMulLin f h := ext fun _ => mul_add _ _ _ variable {N' : Type*} [AddCommMonoid N'] [Module R N'] @[simp] theorem linMulLin_comp (f g : M →ₗ[R] A) (h : N' →ₗ[R] M) : (linMulLin f g).comp h = linMulLin (f.comp h) (g.comp h) := rfl variable {n : Type*} /-- `sq` is the quadratic map sending the vector `x : A` to `x * x` -/ @[simps!] def sq : QuadraticMap R A A := linMulLin LinearMap.id LinearMap.id /-- `proj i j` is the quadratic map sending the vector `x : n → R` to `x i * x j` -/ def proj (i j : n) : QuadraticMap R (n → A) A := linMulLin (@LinearMap.proj _ _ _ (fun _ => A) _ _ i) (@LinearMap.proj _ _ _ (fun _ => A) _ _ j) @[simp] theorem proj_apply (i j : n) (x : n → A) : proj (R := R) i j x = x i * x j := rfl end NonUnitalNonAssocSemiring end QuadraticMap /-! ### Associated bilinear maps If multiplication by 2 is invertible on the target module `N` of `QuadraticMap R M N`, then there is a linear bijection `QuadraticMap.associated` between quadratic maps `Q` over `R` from `M` to `N` and symmetric bilinear maps `B : M →ₗ[R] M →ₗ[R] → N` such that `BilinMap.toQuadraticMap B = Q` (see `QuadraticMap.associated_rightInverse`). The associated bilinear map is half `Q.polarBilin` (see `QuadraticMap.two_nsmul_associated`); this is where the invertibility condition comes from. We spell the condition as `[Invertible (2 : Module.End R N)]`. Note that this makes the bijection available in more cases than the simpler condition `Invertible (2 : R)`, e.g., when `R = ℤ` and `N = ℝ`. -/ namespace LinearMap namespace BilinMap open QuadraticMap open LinearMap (BilinMap) section Semiring variable [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] variable {N' : Type*} [AddCommMonoid N'] [Module R N'] /-- A bilinear map gives a quadratic map by applying the argument twice. -/ def toQuadraticMap (B : BilinMap R M N) : QuadraticMap R M N where toFun x := B x x toFun_smul a x := by simp only [map_smul, LinearMap.smul_apply, smul_smul] exists_companion' := ⟨B + LinearMap.flip B, fun x y => by simp [add_add_add_comm, add_comm]⟩ @[simp] theorem toQuadraticMap_apply (B : BilinMap R M N) (x : M) : B.toQuadraticMap x = B x x := rfl theorem toQuadraticMap_comp_same (B : BilinMap R M N) (f : N' →ₗ[R] M) : BilinMap.toQuadraticMap (B.compl₁₂ f f) = B.toQuadraticMap.comp f := rfl section variable (R M) @[simp] theorem toQuadraticMap_zero : (0 : BilinMap R M N).toQuadraticMap = 0 := rfl end @[simp] theorem toQuadraticMap_add (B₁ B₂ : BilinMap R M N) : (B₁ + B₂).toQuadraticMap = B₁.toQuadraticMap + B₂.toQuadraticMap := rfl @[simp] theorem toQuadraticMap_smul [Monoid S] [DistribMulAction S N] [SMulCommClass S R N] [SMulCommClass R S N] (a : S) (B : BilinMap R M N) : (a • B).toQuadraticMap = a • B.toQuadraticMap := rfl section variable (S R M) /-- `LinearMap.BilinMap.toQuadraticMap` as an additive homomorphism -/ @[simps] def toQuadraticMapAddMonoidHom : (BilinMap R M N) →+ QuadraticMap R M N where toFun := toQuadraticMap map_zero' := toQuadraticMap_zero _ _ map_add' := toQuadraticMap_add /-- `LinearMap.BilinMap.toQuadraticMap` as a linear map -/ @[simps] def toQuadraticMapLinearMap [Semiring S] [Module S N] [SMulCommClass S R N] [SMulCommClass R S N] : (BilinMap R M N) →ₗ[S] QuadraticMap R M N where toFun := toQuadraticMap map_smul' := toQuadraticMap_smul map_add' := toQuadraticMap_add end @[simp] theorem toQuadraticMap_list_sum (B : List (BilinMap R M N)) : B.sum.toQuadraticMap = (B.map toQuadraticMap).sum := map_list_sum (toQuadraticMapAddMonoidHom R M) B @[simp] theorem toQuadraticMap_multiset_sum (B : Multiset (BilinMap R M N)) : B.sum.toQuadraticMap = (B.map toQuadraticMap).sum := map_multiset_sum (toQuadraticMapAddMonoidHom R M) B @[simp] theorem toQuadraticMap_sum {ι : Type*} (s : Finset ι) (B : ι → (BilinMap R M N)) : (∑ i ∈ s, B i).toQuadraticMap = ∑ i ∈ s, (B i).toQuadraticMap := map_sum (toQuadraticMapAddMonoidHom R M) B s @[simp] theorem toQuadraticMap_eq_zero {B : BilinMap R M N} : B.toQuadraticMap = 0 ↔ B.IsAlt := QuadraticMap.ext_iff end Semiring section Ring variable [CommRing R] [AddCommGroup M] [AddCommGroup N] [Module R M] [Module R N] variable {B : BilinMap R M N} @[simp] theorem toQuadraticMap_neg (B : BilinMap R M N) : (-B).toQuadraticMap = -B.toQuadraticMap := rfl @[simp] theorem toQuadraticMap_sub (B₁ B₂ : BilinMap R M N) : (B₁ - B₂).toQuadraticMap = B₁.toQuadraticMap - B₂.toQuadraticMap := rfl theorem polar_toQuadraticMap (x y : M) : polar (toQuadraticMap B) x y = B x y + B y x := by simp only [polar, toQuadraticMap_apply, map_add, add_apply, add_assoc, add_comm (B y x) _, add_sub_cancel_left, sub_eq_add_neg _ (B y y), add_neg_cancel_left] theorem polarBilin_toQuadraticMap : polarBilin (toQuadraticMap B) = B + flip B := LinearMap.ext₂ polar_toQuadraticMap @[simp] theorem _root_.QuadraticMap.toQuadraticMap_polarBilin (Q : QuadraticMap R M N) : toQuadraticMap (polarBilin Q) = 2 • Q := QuadraticMap.ext fun x => (polar_self _ x).trans <| by simp theorem _root_.QuadraticMap.polarBilin_injective (h : IsUnit (2 : R)) : Function.Injective (polarBilin : QuadraticMap R M N → _) := by intro Q₁ Q₂ h₁₂ apply h.smul_left_cancel.mp rw [show (2 : R) = (2 : ℕ) by rfl] simp_rw [Nat.cast_smul_eq_nsmul R, ← QuadraticMap.toQuadraticMap_polarBilin] exact congrArg toQuadraticMap h₁₂ section variable {N' : Type*} [AddCommGroup N'] [Module R N'] theorem _root_.QuadraticMap.polarBilin_comp (Q : QuadraticMap R N' N) (f : M →ₗ[R] N') : polarBilin (Q.comp f) = LinearMap.compl₁₂ (polarBilin Q) f f := LinearMap.ext₂ <| fun x y => by simp [polar] end variable {N' : Type*} [AddCommGroup N'] theorem _root_.LinearMap.compQuadraticMap_polar [CommSemiring S] [Algebra S R] [Module S N] [Module S N'] [IsScalarTower S R N] [Module S M] [IsScalarTower S R M] (f : N →ₗ[S] N') (Q : QuadraticMap R M N) (x y : M) : polar (f.compQuadraticMap' Q) x y = f (polar Q x y) := by simp [polar] variable [Module R N'] theorem _root_.LinearMap.compQuadraticMap_polarBilin (f : N →ₗ[R] N') (Q : QuadraticMap R M N) : (f.compQuadraticMap' Q).polarBilin = Q.polarBilin.compr₂ f := by ext rw [polarBilin_apply_apply, compr₂_apply, polarBilin_apply_apply, LinearMap.compQuadraticMap_polar] end Ring end BilinMap end LinearMap namespace QuadraticMap open LinearMap (BilinMap) section variable [Semiring R] [AddCommMonoid M] [Module R M] instance : SMulCommClass R (Submonoid.center R) M where smul_comm r r' m := by simp_rw [Submonoid.smul_def, smul_smul, ((Set.mem_center_iff.1 r'.prop).1 _).eq] /-- If `2` is invertible in `R`, then it is also invertible in `End R M`. -/ instance [Invertible (2 : R)] : Invertible (2 : Module.End R M) where invOf := (⟨⅟2, Set.invOf_mem_center (Set.ofNat_mem_center _ _)⟩ : Submonoid.center R) • (1 : Module.End R M) invOf_mul_self := by ext m dsimp [Submonoid.smul_def] rw [← ofNat_smul_eq_nsmul R, invOf_smul_smul (2 : R) m] mul_invOf_self := by ext m dsimp [Submonoid.smul_def] rw [← ofNat_smul_eq_nsmul R, smul_invOf_smul (2 : R) m] /-- If `2` is invertible in `R`, then applying the inverse of `2` in `End R M` to an element of `M` is the same as multiplying by the inverse of `2` in `R`. -/ @[simp] lemma half_moduleEnd_apply_eq_half_smul [Invertible (2 : R)] (x : M) : ⅟(2 : Module.End R M) x = ⅟(2 : R) • x := rfl end section AssociatedHom variable [CommRing R] [AddCommGroup M] [Module R M] variable [AddCommGroup N] [Module R N] variable (S) [CommSemiring S] [Algebra S R] [Module S N] [IsScalarTower S R N] -- the requirement that multiplication by `2` is invertible on the target module `N` variable [Invertible (2 : Module.End R N)] /-- `associatedHom` is the map that sends a quadratic map on a module `M` over `R` to its associated symmetric bilinear map. As provided here, this has the structure of an `S`-linear map where `S` is a commutative ring and `R` is an `S`-algebra. Over a commutative ring, use `QuadraticMap.associated`, which gives an `R`-linear map. Over a general ring with no nontrivial distinguished commutative subring, use `QuadraticMap.associated'`, which gives an additive homomorphism (or more precisely a `ℤ`-linear map.) -/ def associatedHom : QuadraticMap R M N →ₗ[S] (BilinMap R M N) where toFun Q := ⅟(2 : Module.End R N) • polarBilin Q map_add' _ _ := LinearMap.ext₂ fun _ _ ↦ by simp [polar_add] map_smul' _ _ := LinearMap.ext₂ fun _ _ ↦ by simp [polar_smul] variable (Q : QuadraticMap R M N) @[simp] theorem associated_apply (x y : M) : associatedHom S Q x y = ⅟(2 : Module.End R N) • (Q (x + y) - Q x - Q y) := rfl /-- Twice the associated bilinear map of `Q` is the same as the polar of `Q`. -/ @[simp] theorem two_nsmul_associated : 2 • associatedHom S Q = Q.polarBilin := by ext dsimp rw [← LinearMap.smul_apply, nsmul_eq_mul, Nat.cast_ofNat, mul_invOf_self', Module.End.one_apply, polar] theorem associated_isSymm (Q : QuadraticMap R M N) (x y : M) : associatedHom S Q x y = associatedHom S Q y x := by simp only [associated_apply, sub_eq_add_neg, add_assoc, add_comm, add_left_comm] theorem _root_.QuadraticForm.associated_isSymm (Q : QuadraticForm R M) [Invertible (2 : R)] : (associatedHom S Q).IsSymm := ⟨QuadraticMap.associated_isSymm S Q⟩ /-- A version of `QuadraticMap.associated_isSymm` for general targets (using `flip` because `IsSymm` does not apply here). -/ lemma associated_flip : (associatedHom S Q).flip = associatedHom S Q := by ext simp only [LinearMap.flip_apply, associated_apply, add_comm, sub_eq_add_neg, add_left_comm, add_assoc] @[simp] theorem associated_comp {N' : Type*} [AddCommGroup N'] [Module R N'] (f : N' →ₗ[R] M) : associatedHom S (Q.comp f) = (associatedHom S Q).compl₁₂ f f := by ext simp only [associated_apply, comp_apply, map_add, LinearMap.compl₁₂_apply] theorem associated_toQuadraticMap (B : BilinMap R M N) (x y : M) : associatedHom S B.toQuadraticMap x y = ⅟(2 : Module.End R N) • (B x y + B y x) := by simp only [associated_apply, BilinMap.toQuadraticMap_apply, map_add, LinearMap.add_apply, Module.End.smul_def, map_sub] abel_nf theorem associated_left_inverse {B₁ : BilinMap R M N} (h : ∀ x y, B₁ x y = B₁ y x) : associatedHom S B₁.toQuadraticMap = B₁ := LinearMap.ext₂ fun x y ↦ by rw [associated_toQuadraticMap, ← h x y, ← two_smul R, invOf_smul_eq_iff, two_smul, two_smul] /-- A version of `QuadraticMap.associated_left_inverse` for general targets. -/ lemma associated_left_inverse' {B₁ : BilinMap R M N} (hB₁ : B₁.flip = B₁) : associatedHom S B₁.toQuadraticMap = B₁ := by ext _ y rw [associated_toQuadraticMap, ← LinearMap.flip_apply _ y, hB₁, invOf_smul_eq_iff, two_smul] theorem associated_eq_self_apply (x : M) : associatedHom S Q x x = Q x := by rw [associated_apply, map_add_self, ← three_add_one_eq_four, ← two_add_one_eq_three, add_smul, add_smul, one_smul, add_sub_cancel_right, add_sub_cancel_right, two_smul, ← two_smul R, invOf_smul_eq_iff, two_smul, two_smul] theorem toQuadraticMap_associated : (associatedHom S Q).toQuadraticMap = Q := QuadraticMap.ext <| associated_eq_self_apply S Q -- note: usually `rightInverse` lemmas are named the other way around, but this is consistent -- with historical naming in this file. theorem associated_rightInverse : Function.RightInverse (associatedHom S) (BilinMap.toQuadraticMap : _ → QuadraticMap R M N) := toQuadraticMap_associated S /-- `associated'` is the `ℤ`-linear map that sends a quadratic form on a module `M` over `R` to its associated symmetric bilinear form. -/ abbrev associated' : QuadraticMap R M N →ₗ[ℤ] BilinMap R M N := associatedHom ℤ /-- Symmetric bilinear forms can be lifted to quadratic forms -/ instance canLift [Invertible (2 : R)] : CanLift (BilinMap R M R) (QuadraticForm R M) (associatedHom ℕ) LinearMap.IsSymm where prf B := fun ⟨hB⟩ ↦ ⟨B.toQuadraticMap, associated_left_inverse _ hB⟩ /-- Symmetric bilinear maps can be lifted to quadratic maps -/ instance canLift' : CanLift (BilinMap R M N) (QuadraticMap R M N) (associatedHom ℕ) fun B ↦ B.flip = B where prf B hB := ⟨B.toQuadraticMap, associated_left_inverse' _ hB⟩ /-- There exists a non-null vector with respect to any quadratic form `Q` whose associated bilinear form is non-zero, i.e. there exists `x` such that `Q x ≠ 0`. -/ theorem exists_quadraticMap_ne_zero {Q : QuadraticMap R M N} -- Porting note: added implicit argument (hB₁ : associated' (N := N) Q ≠ 0) : ∃ x, Q x ≠ 0 := by rw [← not_forall] intro h apply hB₁ rw [(QuadraticMap.ext h : Q = 0), LinearMap.map_zero] end AssociatedHom section Associated variable [CommSemiring S] [CommRing R] [AddCommGroup M] [Algebra S R] [Module R M] variable [AddCommGroup N] [Module R N] [Module S N] [IsScalarTower S R N] variable [Invertible (2 : Module.End R N)] -- Note: When possible, rather than writing lemmas about `associated`, write a lemma applying to -- the more general `associatedHom` and place it in the previous section. /-- `associated` is the linear map that sends a quadratic map over a commutative ring to its associated symmetric bilinear map. -/ abbrev associated : QuadraticMap R M N →ₗ[R] BilinMap R M N := associatedHom R variable (S) in theorem coe_associatedHom : ⇑(associatedHom S : QuadraticMap R M N →ₗ[S] BilinMap R M N) = associated := rfl open LinearMap in @[simp] theorem associated_linMulLin [Invertible (2 : R)] (f g : M →ₗ[R] R) : associated (R := R) (N := R) (linMulLin f g) = ⅟(2 : R) • ((mul R R).compl₁₂ f g + (mul R R).compl₁₂ g f) := by ext simp only [associated_apply, linMulLin_apply, map_add, smul_add, LinearMap.add_apply, LinearMap.smul_apply, compl₁₂_apply, mul_apply', smul_eq_mul, invOf_smul_eq_iff] simp only [Module.End.smul_def, Module.End.ofNat_apply, nsmul_eq_mul, Nat.cast_ofNat, mul_invOf_cancel_left'] ring_nf open LinearMap in @[simp] lemma associated_sq [Invertible (2 : R)] : associated (R := R) sq = mul R R := (associated_linMulLin (id) (id)).trans <| by simp only [smul_add, invOf_two_smul_add_invOf_two_smul]; rfl end Associated section IsOrtho /-! ### Orthogonality -/ section CommSemiring variable [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] {Q : QuadraticMap R M N} /-- The proposition that two elements of a quadratic map space are orthogonal. -/ def IsOrtho (Q : QuadraticMap R M N) (x y : M) : Prop := Q (x + y) = Q x + Q y theorem isOrtho_def {Q : QuadraticMap R M N} {x y : M} : Q.IsOrtho x y ↔ Q (x + y) = Q x + Q y := Iff.rfl theorem IsOrtho.all (x y : M) : IsOrtho (0 : QuadraticMap R M N) x y := (zero_add _).symm theorem IsOrtho.zero_left (x : M) : IsOrtho Q (0 : M) x := by simp [isOrtho_def] theorem IsOrtho.zero_right (x : M) : IsOrtho Q x (0 : M) := by simp [isOrtho_def] theorem ne_zero_of_not_isOrtho_self {Q : QuadraticMap R M N} (x : M) (hx₁ : ¬Q.IsOrtho x x) : x ≠ 0 := fun hx₂ => hx₁ (hx₂.symm ▸ .zero_left _) theorem isOrtho_comm {x y : M} : IsOrtho Q x y ↔ IsOrtho Q y x := by simp_rw [isOrtho_def, add_comm] alias ⟨IsOrtho.symm, _⟩ := isOrtho_comm theorem _root_.LinearMap.BilinForm.toQuadraticMap_isOrtho [IsCancelAdd R] [NoZeroDivisors R] [CharZero R] {B : BilinMap R M R} {x y : M} (h : B.IsSymm) : B.toQuadraticMap.IsOrtho x y ↔ B.IsOrtho x y := by letI : AddCancelMonoid R := { ‹IsCancelAdd R›, (inferInstanceAs <| AddCommMonoid R) with } simp_rw [isOrtho_def, LinearMap.isOrtho_def, B.toQuadraticMap_apply, map_add, LinearMap.add_apply, add_comm _ (B y y), add_add_add_comm _ _ (B y y), add_comm (B y y)] rw [add_eq_left (a := B x x + B y y), ← h.eq, RingHom.id_apply, add_self_eq_zero] end CommSemiring section CommRing variable [CommRing R] [AddCommGroup M] [Module R M] [AddCommGroup N] [Module R N] {Q : QuadraticMap R M N} @[simp] theorem isOrtho_polarBilin {x y : M} : Q.polarBilin.IsOrtho x y ↔ IsOrtho Q x y := by simp_rw [isOrtho_def, LinearMap.isOrtho_def, polarBilin_apply_apply, polar, sub_sub, sub_eq_zero] theorem IsOrtho.polar_eq_zero {x y : M} (h : IsOrtho Q x y) : polar Q x y = 0 := isOrtho_polarBilin.mpr h @[simp] theorem associated_isOrtho [Invertible (2 : R)] {x y : M} : Q.associated.IsOrtho x y ↔ Q.IsOrtho x y := by simp_rw [isOrtho_def, LinearMap.isOrtho_def, associated_apply, invOf_smul_eq_iff, smul_zero, sub_sub, sub_eq_zero] end CommRing end IsOrtho section Anisotropic section Semiring variable [CommSemiring R] [AddCommMonoid M] [AddCommMonoid N] [Module R M] [Module R N] /-- An anisotropic quadratic map is zero only on zero vectors. -/ def Anisotropic (Q : QuadraticMap R M N) : Prop := ∀ x, Q x = 0 → x = 0 theorem not_anisotropic_iff_exists (Q : QuadraticMap R M N) : ¬Anisotropic Q ↔ ∃ x, x ≠ 0 ∧ Q x = 0 := by simp only [Anisotropic, not_forall, exists_prop, and_comm] theorem Anisotropic.eq_zero_iff {Q : QuadraticMap R M N} (h : Anisotropic Q) {x : M} : Q x = 0 ↔ x = 0 := ⟨h x, fun h => h.symm ▸ map_zero Q⟩ end Semiring section Ring variable [CommRing R] [AddCommGroup M] [Module R M] /-- The associated bilinear form of an anisotropic quadratic form is nondegenerate. -/ theorem separatingLeft_of_anisotropic [Invertible (2 : R)] (Q : QuadraticMap R M R) (hB : Q.Anisotropic) : -- Porting note: added implicit argument (QuadraticMap.associated' (N := R) Q).SeparatingLeft := fun x hx ↦ hB _ <| by rw [← hx x] exact (associated_eq_self_apply _ _ x).symm end Ring end Anisotropic section PosDef variable {R₂ : Type u} [CommSemiring R₂] [AddCommMonoid M] [Module R₂ M] variable [PartialOrder N] [AddCommMonoid N] [Module R₂ N] variable {Q₂ : QuadraticMap R₂ M N} /-- A positive definite quadratic form is positive on nonzero vectors. -/ def PosDef (Q₂ : QuadraticMap R₂ M N) : Prop := ∀ x, x ≠ 0 → 0 < Q₂ x theorem PosDef.smul {R} [CommSemiring R] [PartialOrder R] [Module R M] [Module R N] [PosSMulStrictMono R N] {Q : QuadraticMap R M N} (h : PosDef Q) {a : R} (a_pos : 0 < a) : PosDef (a • Q) := fun x hx => smul_pos a_pos (h x hx) variable {n : Type*} theorem PosDef.nonneg {Q : QuadraticMap R₂ M N} (hQ : PosDef Q) (x : M) : 0 ≤ Q x := (eq_or_ne x 0).elim (fun h => h.symm ▸ (map_zero Q).symm.le) fun h => (hQ _ h).le theorem PosDef.anisotropic {Q : QuadraticMap R₂ M N} (hQ : Q.PosDef) : Q.Anisotropic := fun x hQx => by_contradiction fun hx => lt_irrefl (0 : N) <| by have := hQ _ hx rw [hQx] at this exact this theorem posDef_of_nonneg {Q : QuadraticMap R₂ M N} (h : ∀ x, 0 ≤ Q x) (h0 : Q.Anisotropic) : PosDef Q := fun x hx => lt_of_le_of_ne (h x) (Ne.symm fun hQx => hx <| h0 _ hQx) theorem posDef_iff_nonneg {Q : QuadraticMap R₂ M N} : PosDef Q ↔ (∀ x, 0 ≤ Q x) ∧ Q.Anisotropic := ⟨fun h => ⟨h.nonneg, h.anisotropic⟩, fun ⟨n, a⟩ => posDef_of_nonneg n a⟩ theorem PosDef.add [AddLeftStrictMono N] (Q Q' : QuadraticMap R₂ M N) (hQ : PosDef Q) (hQ' : PosDef Q') : PosDef (Q + Q') := fun x hx => add_pos (hQ x hx) (hQ' x hx) theorem linMulLinSelfPosDef {R} [CommSemiring R] [Module R M] [Semiring A] [LinearOrder A] [IsStrictOrderedRing A] [ExistsAddOfLE A] [Module R A] [SMulCommClass R A A] [IsScalarTower R A A] (f : M →ₗ[R] A) (hf : LinearMap.ker f = ⊥) : PosDef (linMulLin (A := A) f f) := fun _x hx => mul_self_pos.2 fun h => hx <| LinearMap.ker_eq_bot'.mp hf _ h end PosDef end QuadraticMap section /-! ### Quadratic forms and matrices Connect quadratic forms and matrices, in order to explicitly compute with them. The convention is twos out, so there might be a factor 2⁻¹ in the entries of the matrix. The determinant of the matrix is the discriminant of the quadratic form. -/ variable {n : Type w} [Fintype n] [DecidableEq n] variable [CommRing R] [AddCommMonoid M] [Module R M] /-- `M.toQuadraticMap'` is the map `fun x ↦ row x * M * col x` as a quadratic form. -/ def Matrix.toQuadraticMap' (M : Matrix n n R) : QuadraticMap R (n → R) R := LinearMap.BilinMap.toQuadraticMap (Matrix.toLinearMap₂' R M) variable [Invertible (2 : R)] /-- A matrix representation of the quadratic form. -/ def QuadraticMap.toMatrix' (Q : QuadraticMap R (n → R) R) : Matrix n n R := LinearMap.toMatrix₂' R (associated Q) open QuadraticMap theorem QuadraticMap.toMatrix'_smul (a : R) (Q : QuadraticMap R (n → R) R) : (a • Q).toMatrix' = a • Q.toMatrix' := by simp only [toMatrix', LinearEquiv.map_smul, LinearMap.map_smul] theorem QuadraticMap.isSymm_toMatrix' (Q : QuadraticForm R (n → R)) : Q.toMatrix'.IsSymm := by ext i j rw [toMatrix', Matrix.transpose_apply, LinearMap.toMatrix₂'_apply, LinearMap.toMatrix₂'_apply, ← associated_isSymm] end namespace QuadraticMap variable {n : Type w} [Fintype n] variable [CommRing R] [DecidableEq n] [Invertible (2 : R)] variable {m : Type w} [DecidableEq m] [Fintype m] open Matrix @[simp] theorem toMatrix'_comp (Q : QuadraticMap R (m → R) R) (f : (n → R) →ₗ[R] m → R) : (Q.comp f).toMatrix' = (LinearMap.toMatrix' f)ᵀ * Q.toMatrix' * (LinearMap.toMatrix' f) := by ext simp only [QuadraticMap.associated_comp, LinearMap.toMatrix₂'_compl₁₂, toMatrix'] section Discriminant variable {Q : QuadraticMap R (n → R) R} /-- The discriminant of a quadratic form generalizes the discriminant of a quadratic polynomial. -/ def discr (Q : QuadraticMap R (n → R) R) : R := Q.toMatrix'.det theorem discr_smul (a : R) : (a • Q).discr = a ^ Fintype.card n * Q.discr := by simp only [discr, toMatrix'_smul, Matrix.det_smul] theorem discr_comp (f : (n → R) →ₗ[R] n → R) : (Q.comp f).discr = f.toMatrix'.det * f.toMatrix'.det * Q.discr := by simp only [Matrix.det_transpose, mul_left_comm, QuadraticMap.toMatrix'_comp, mul_comm, Matrix.det_mul, discr] end Discriminant end QuadraticMap namespace LinearMap namespace BilinForm open LinearMap (BilinMap) section Semiring variable [CommSemiring R] [AddCommMonoid M] [Module R M] /-- A bilinear form is separating left if the quadratic form it is associated with is anisotropic. -/ theorem separatingLeft_of_anisotropic {B : BilinForm R M} (hB : B.toQuadraticMap.Anisotropic) : B.SeparatingLeft := fun x hx => hB _ (hx x) end Semiring variable [CommRing R] [AddCommGroup M] [Module R M] /-- There exists a non-null vector with respect to any symmetric, nonzero bilinear form `B` on a module `M` over a ring `R` with invertible `2`, i.e. there exists some `x : M` such that `B x x ≠ 0`. -/ theorem exists_bilinForm_self_ne_zero [htwo : Invertible (2 : R)] {B : BilinForm R M} (hB₁ : B ≠ 0) (hB₂ : B.IsSymm) : ∃ x, ¬B.IsOrtho x x := by lift B to QuadraticForm R M using hB₂ with Q obtain ⟨x, hx⟩ := QuadraticMap.exists_quadraticMap_ne_zero hB₁ exact ⟨x, fun h => hx (Q.associated_eq_self_apply ℕ x ▸ h)⟩ open Module variable {V : Type u} {K : Type v} [Field K] [AddCommGroup V] [Module K V] variable [FiniteDimensional K V] /-- Given a symmetric bilinear form `B` on some vector space `V` over a field `K` in which `2` is invertible, there exists an orthogonal basis with respect to `B`. -/ theorem exists_orthogonal_basis [hK : Invertible (2 : K)] {B : LinearMap.BilinForm K V} (hB₂ : B.IsSymm) : ∃ v : Basis (Fin (finrank K V)) K V, B.IsOrthoᵢ v := by suffices ∀ d, finrank K V = d → ∃ v : Basis (Fin d) K V, B.IsOrthoᵢ v by exact this _ rfl intro d hd induction d generalizing V with | zero => exact ⟨basisOfFinrankZero hd, fun _ _ _ => map_zero _⟩ | succ d ih => haveI := finrank_pos_iff.1 (hd.symm ▸ Nat.succ_pos d : 0 < finrank K V) -- either the bilinear form is trivial or we can pick a non-null `x` obtain rfl | hB₁ := eq_or_ne B 0 · let b := Module.finBasis K V rw [hd] at b exact ⟨b, fun i j _ => rfl⟩ obtain ⟨x, hx⟩ := exists_bilinForm_self_ne_zero hB₁ hB₂ rw [← Submodule.finrank_add_eq_of_isCompl (isCompl_span_singleton_orthogonal hx).symm, finrank_span_singleton (ne_zero_of_map hx)] at hd let B' := B.domRestrict₁₂ (Submodule.orthogonalBilin (K ∙ x) B ) (Submodule.orthogonalBilin (K ∙ x) B ) obtain ⟨v', hv₁⟩ := ih (hB₂.domRestrict _ : B'.IsSymm) (Nat.succ.inj hd) -- concatenate `x` with the basis obtained by induction let b := Basis.mkFinCons x v' (by rintro c y hy hc rw [add_eq_zero_iff_neg_eq] at hc rw [← hc, Submodule.neg_mem_iff] at hy have := (isCompl_span_singleton_orthogonal hx).disjoint rw [Submodule.disjoint_def] at this have := this (c • x) (Submodule.smul_mem _ _ <| Submodule.mem_span_singleton_self _) hy exact (smul_eq_zero.1 this).resolve_right fun h => hx <| h.symm ▸ map_zero _) (by intro y refine ⟨-B x y / B x x, fun z hz => ?_⟩ obtain ⟨c, rfl⟩ := Submodule.mem_span_singleton.1 hz rw [IsOrtho, map_smul, smul_apply, map_add, map_smul, smul_eq_mul, smul_eq_mul, div_mul_cancel₀ _ hx, add_neg_cancel, mul_zero]) refine ⟨b, ?_⟩ rw [Basis.coe_mkFinCons] intro j i refine Fin.cases ?_ (fun i => ?_) i <;> refine Fin.cases ?_ (fun j => ?_) j <;> intro hij <;> simp only [Function.onFun, Fin.cons_zero, Fin.cons_succ, Function.comp_apply] · exact (hij rfl).elim · rw [IsOrtho, ← hB₂.eq] exact (v' j).prop _ (Submodule.mem_span_singleton_self x) · exact (v' i).prop _ (Submodule.mem_span_singleton_self x) · exact hv₁ (ne_of_apply_ne _ hij) end BilinForm end LinearMap namespace QuadraticMap open Finset Module variable [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] variable {ι : Type*} /-- Given a quadratic map `Q` and a basis, `basisRepr` is the basis representation of `Q`. -/ noncomputable def basisRepr [Finite ι] (Q : QuadraticMap R M N) (v : Basis ι R M) : QuadraticMap R (ι → R) N := Q.comp v.equivFun.symm @[simp] theorem basisRepr_apply [Fintype ι] {v : Basis ι R M} (Q : QuadraticMap R M N) (w : ι → R) : Q.basisRepr v w = Q (∑ i : ι, w i • v i) := by rw [← v.equivFun_symm_apply] rfl variable [Fintype ι] section variable (R) /-- The weighted sum of squares with respect to some weight as a quadratic form. The weights are applied using `•`; typically this definition is used either with `S = R` or `[Algebra S R]`, although this is stated more generally. -/ def weightedSumSquares [Monoid S] [DistribMulAction S R] [SMulCommClass S R R] (w : ι → S) : QuadraticMap R (ι → R) R := ∑ i : ι, w i • (proj (R := R) (n := ι) i i) end @[simp] theorem weightedSumSquares_apply [Monoid S] [DistribMulAction S R] [SMulCommClass S R R] (w : ι → S) (v : ι → R) : weightedSumSquares R w v = ∑ i : ι, w i • (v i * v i) := QuadraticMap.sum_apply _ _ _ /-- On an orthogonal basis, the basis representation of `Q` is just a sum of squares. -/ theorem basisRepr_eq_of_iIsOrtho {R M} [CommRing R] [AddCommGroup M] [Module R M] [Invertible (2 : R)] (Q : QuadraticForm R M) (v : Basis ι R M) (hv₂ : (associated (R := R) Q).IsOrthoᵢ v) : Q.basisRepr v = weightedSumSquares _ fun i => Q (v i) := by ext w rw [basisRepr_apply, ← @associated_eq_self_apply R, map_sum, weightedSumSquares_apply] refine sum_congr rfl fun j hj => ?_ rw [← @associated_eq_self_apply R, LinearMap.map_sum₂, sum_eq_single_of_mem j hj] · rw [LinearMap.map_smul, LinearMap.map_smul₂, smul_eq_mul, associated_apply, smul_eq_mul, smul_eq_mul, Module.End.smul_def, half_moduleEnd_apply_eq_half_smul] ring_nf · intro i _ hij rw [LinearMap.map_smul, LinearMap.map_smul₂, hv₂ hij] module end QuadraticMap
Pigeonhole.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import Mathlib.Data.Set.Finite.Lattice import Mathlib.SetTheory.Cardinal.Regular /-! # Infinite pigeonhole principle This file proves variants of the infinite pigeonhole principle. ## TODO Generalize universes of results. -/ open Order Ordinal Set universe u namespace Cardinal /-- The infinite pigeonhole principle -/ theorem infinite_pigeonhole {β α : Type u} (f : β → α) (h₁ : ℵ₀ ≤ #β) (h₂ : #α < (#β).ord.cof) : ∃ a : α, #(f ⁻¹' {a}) = #β := by have : ∃ a, #β ≤ #(f ⁻¹' {a}) := by by_contra! h apply mk_univ.not_lt rw [← preimage_univ, ← iUnion_of_singleton, preimage_iUnion] exact mk_iUnion_le_sum_mk.trans_lt ((sum_le_iSup _).trans_lt <| mul_lt_of_lt h₁ (h₂.trans_le <| cof_ord_le _) (iSup_lt h₂ h)) obtain ⟨x, h⟩ := this refine ⟨x, h.antisymm' ?_⟩ rw [le_mk_iff_exists_set] exact ⟨_, rfl⟩ /-- Pigeonhole principle for a cardinality below the cardinality of the domain -/ theorem infinite_pigeonhole_card {β α : Type u} (f : β → α) (θ : Cardinal) (hθ : θ ≤ #β) (h₁ : ℵ₀ ≤ θ) (h₂ : #α < θ.ord.cof) : ∃ a : α, θ ≤ #(f ⁻¹' {a}) := by rcases le_mk_iff_exists_set.1 hθ with ⟨s, rfl⟩ obtain ⟨a, ha⟩ := infinite_pigeonhole (f ∘ Subtype.val : s → α) h₁ h₂ use a; rw [← ha, @preimage_comp _ _ _ Subtype.val f] exact mk_preimage_of_injective _ _ Subtype.val_injective theorem infinite_pigeonhole_set {β α : Type u} {s : Set β} (f : s → α) (θ : Cardinal) (hθ : θ ≤ #s) (h₁ : ℵ₀ ≤ θ) (h₂ : #α < θ.ord.cof) : ∃ (a : α) (t : Set β) (h : t ⊆ s), θ ≤ #t ∧ ∀ ⦃x⦄ (hx : x ∈ t), f ⟨x, h hx⟩ = a := by obtain ⟨a, ha⟩ := infinite_pigeonhole_card f θ hθ h₁ h₂ refine ⟨a, { x | ∃ h, f ⟨x, h⟩ = a }, ?_, ?_, ?_⟩ · rintro x ⟨hx, _⟩ exact hx · refine ha.trans (ge_of_eq <| Quotient.sound ⟨Equiv.trans ?_ (Equiv.subtypeSubtypeEquivSubtypeExists _ _).symm⟩) simp only [coe_eq_subtype, mem_singleton_iff, mem_preimage, mem_setOf_eq] rfl rintro x ⟨_, hx'⟩; exact hx' /-- A function whose codomain's cardinality is infinite but strictly smaller than its domain's has a fiber with cardinality strictly great than the codomain. -/ theorem infinite_pigeonhole_card_lt {β α : Type u} (f : β → α) (w : #α < #β) (w' : ℵ₀ ≤ #α) : ∃ a : α, #α < #(f ⁻¹' {a}) := by simp_rw [← succ_le_iff] exact infinite_pigeonhole_card f (succ #α) (succ_le_of_lt w) (w'.trans (lt_succ _).le) ((lt_succ _).trans_le (isRegular_succ w').2.ge) /-- A function whose codomain's cardinality is infinite but strictly smaller than its domain's has an infinite fiber. -/ theorem exists_infinite_fiber {β α : Type u} (f : β → α) (w : #α < #β) (w' : Infinite α) : ∃ a : α, Infinite (f ⁻¹' {a}) := by simp_rw [Cardinal.infinite_iff] at w' ⊢ obtain ⟨a, ha⟩ := infinite_pigeonhole_card_lt f w w' exact ⟨a, w'.trans ha.le⟩ /-- If an infinite type `β` can be expressed as a union of finite sets, then the cardinality of the collection of those finite sets must be at least the cardinality of `β`. -/ -- TODO: write `Set.univ` instead of `⊤` and rename the theorem accordingly. theorem le_range_of_union_finset_eq_top {α β : Type*} [Infinite β] (f : α → Finset β) (w : ⋃ a, (f a : Set β) = ⊤) : #β ≤ #(range f) := by have k : _root_.Infinite (range f) := by rw [infinite_coe_iff] apply mt (union_finset_finite_of_range_finite f) rw [w] exact infinite_univ by_contra h simp only [not_le] at h let u : ∀ b, ∃ a, b ∈ f a := fun b => by simpa using (w.ge :) (Set.mem_univ b) let u' : β → range f := fun b => ⟨f (u b).choose, by simp⟩ have v' : ∀ a, u' ⁻¹' {⟨f a, by simp⟩} ≤ f a := by rintro a p m simp? [u'] at m says simp only [mem_preimage, mem_singleton_iff, Subtype.mk.injEq, u'] at m rw [← m] apply fun b => (u b).choose_spec obtain ⟨⟨-, ⟨a, rfl⟩⟩, p⟩ := exists_infinite_fiber u' h k exact (@Infinite.of_injective _ _ p (inclusion (v' a)) (inclusion_injective _)).false end Cardinal
Propose.lean
/- Copyright (c) 2023 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Lean.Meta.Tactic.TryThis import Lean.Meta.Tactic.SolveByElim import Mathlib.Lean.Expr.Basic import Mathlib.Lean.Meta import Mathlib.Lean.Meta.Basic import Batteries.Util.Cache import Mathlib.Tactic.Core /-! # Propose This file defines a tactic `have? using a, b, c` that tries to find a lemma which makes use of each of the local hypotheses `a, b, c`. The variant `have? : t using a, b, c` restricts to lemmas with type `t` (which may contain `_`). Note that in either variant `have?` does not look at the current goal at all. It is a relative of `apply?` but for *forward reasoning* (i.e. looking at the hypotheses) rather than backward reasoning. ``` import Batteries.Data.List.Basic import Mathlib.Tactic.Propose example (K L M : List α) (w : L.Disjoint M) (m : K ⊆ L) : True := by have? using w, m -- Try this: `List.disjoint_of_subset_left m w` trivial ``` -/ namespace Mathlib.Tactic.Propose open Lean Meta Batteries.Tactic Tactic.TryThis initialize registerTraceClass `Tactic.propose initialize proposeLemmas : DeclCache (DiscrTree Name) ← DeclCache.mk "have?: init cache" failure {} fun name constInfo lemmas => do if constInfo.isUnsafe then return lemmas if ← name.isBlackListed then return lemmas withNewMCtxDepth do withReducible do let (mvars, _, _) ← forallMetaTelescope constInfo.type let mut lemmas := lemmas for m in mvars do lemmas ← lemmas.insertIfSpecific (← inferType m) name pure lemmas open Lean.Meta.SolveByElim in /-- Shortcut for calling `solveByElim`. -/ def solveByElim (orig : MVarId) (goals : Array MVarId) (use : Array Expr) (required : Array Expr) (depth) := do let cfg : SolveByElimConfig := { maxDepth := depth, exfalso := true, symm := true, intro := false } let cfg := if !required.isEmpty then cfg.testSolutions (fun _ => do let r ← instantiateMVars (.mvar orig) pure <| required.all fun e => e.occurs r) else cfg let cfg := cfg.synthInstance _ ← SolveByElim.solveByElim cfg (use.toList.map pure) (fun _ => return (← getLocalHyps).toList) goals.toList /-- Attempts to find lemmas which use all of the `required` expressions as arguments, and can be unified with the given `type` (which may contain metavariables, which we avoid assigning). We look up candidate lemmas from a discrimination tree using the first such expression. Returns an array of pairs, containing the names of found lemmas and the resulting application. -/ def propose (lemmas : DiscrTree Name) (type : Expr) (required : Array Expr) (solveByElimDepth := 15) : MetaM (Array (Name × Expr)) := do guard !required.isEmpty let ty ← whnfR (← instantiateMVars (← inferType required[0]!)) let candidates ← lemmas.getMatch ty candidates.filterMapM fun lem : Name => try trace[Tactic.propose] "considering {lem}" let Expr.mvar g ← mkFreshExprMVar type | failure let e ← mkConstWithFreshMVarLevels lem let (args, _, _) ← forallMetaTelescope (← inferType e) let .true ← preservingMCtx <| withAssignableSyntheticOpaque <| isDefEq type (← inferType (mkAppN e args)) | failure g.assign (mkAppN e args) let use := required.filterMap fun e => match e with | .fvar _ => none | _ => some e solveByElim g (args.map fun a => a.mvarId!) use required solveByElimDepth trace[Tactic.propose] "successfully filled in arguments for {lem}" pure <| some (lem, ← instantiateMVars (.mvar g)) catch _ => pure none open Lean.Parser.Tactic /-- * `have? using a, b, c` tries to find a lemma which makes use of each of the local hypotheses `a, b, c`, and reports any results via trace messages. * `have? : h using a, b, c` only returns lemmas whose type matches `h` (which may contain `_`). * `have?! using a, b, c` will also call `have` to add results to the local goal state. Note that `have?` (unlike `apply?`) does not inspect the goal at all, only the types of the lemmas in the `using` clause. `have?` should not be left in proofs; it is a search tool, like `apply?`. Suggestions are printed as `have := f a b c`. -/ syntax (name := propose') "have?" "!"? (ident)? (" : " term)? " using " (colGt term),+ : tactic open Elab.Tactic Elab Tactic in elab_rules : tactic | `(tactic| have?%$tk $[!%$lucky]? $[$h:ident]? $[ : $type:term]? using $[$terms:term],*) => do let stx ← getRef let goal ← getMainGoal goal.withContext do let required ← terms.mapM (elabTerm · none) let type ← match type with | some stx => elabTermWithHoles stx none (← getMainTag) true <&> (·.1) | none => mkFreshTypeMVar let proposals ← propose (← proposeLemmas.get) type required if proposals.isEmpty then throwError "propose could not find any lemmas using the given hypotheses" -- TODO we should have `proposals` return a lazy list, to avoid unnecessary computation here. for p in proposals.toList.take 10 do addHaveSuggestion tk (h.map (·.getId)) (← inferType p.2) p.2 stx (← saveState) if lucky.isSome then let mut g := goal for p in proposals.toList.take 10 do (_, g) ← g.let p.1 p.2 replaceMainGoal [g] @[inherit_doc propose'] syntax "have?!" (" : " term)? " using " (colGt term),+ : tactic @[inherit_doc propose'] syntax "have!?" (" : " term)? " using " (colGt term),+ : tactic macro_rules | `(tactic| have?!%$tk $[: $type]? using $terms,*) => `(tactic| have?%$tk ! $[: $type]? using $terms,*) | `(tactic| have!?%$tk $[: $type]? using $terms,*) => `(tactic| have?%$tk ! $[: $type]? using $terms,*) end Mathlib.Tactic.Propose
TransferInstance.lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Algebra.Group.Action.Defs import Mathlib.Algebra.Group.Equiv.Defs import Mathlib.Algebra.Group.TransferInstance import Mathlib.Algebra.Group.InjSurj import Mathlib.Data.Fintype.Basic /-! # Transfer algebraic structures across `Equiv`s This continues the pattern set in `Mathlib/Algebra/Group/TransferInstance.lean`. -/ assert_not_exists MonoidWithZero namespace Equiv variable {M N O α β : Type*} variable (M) [Monoid M] in /-- Transfer `MulAction` across an `Equiv` -/ @[to_additive /-- Transfer `AddAction` across an `Equiv` -/] protected abbrev mulAction (e : α ≃ β) [MulAction M β] : MulAction M α where __ := e.smul M one_smul := by simp [smul_def] mul_smul := by simp [smul_def, mul_smul] variable (M N) [SMul M β] [SMul N β] in /-- Transfer `SMulCommClass` across an `Equiv` -/ @[to_additive /-- Transfer `VAddCommClass` across an `Equiv` -/] protected lemma smulCommClass (e : α ≃ β) [SMulCommClass M N β] : letI := e.smul M letI := e.smul N SMulCommClass M N α := letI := e.smul M letI := e.smul N { smul_comm := by simp [smul_def, smul_comm] } variable (M N) [SMul M N] [SMul M β] [SMul N β] in /-- Transfer `IsScalarTower` across an `Equiv` -/ @[to_additive /-- Transfer `VAddAssocClass` across an `Equiv` -/] protected lemma isScalarTower (e : α ≃ β) [IsScalarTower M N β] : letI := e.smul M letI := e.smul N IsScalarTower M N α := letI := e.smul M letI := e.smul N { smul_assoc := by simp [smul_def, smul_assoc] } variable (M) [SMul M β] [SMul Mᵐᵒᵖ β] in /-- Transfer `IsCentralScalar` across an `Equiv` -/ @[to_additive /-- Transfer `IsCentralVAdd` across an `Equiv` -/] protected lemma isCentralScalar (e : α ≃ β) [IsCentralScalar M β] : letI := e.smul M letI := e.smul Mᵐᵒᵖ IsCentralScalar M α := letI := e.smul M letI := e.smul Mᵐᵒᵖ { op_smul_eq_smul := by simp [smul_def, op_smul_eq_smul] } variable (M) [Monoid M] [Monoid O] in /-- Transfer `MulDistribMulAction` across an `Equiv` -/ protected abbrev mulDistribMulAction (e : N ≃ O) [MulDistribMulAction M O] : letI := e.monoid MulDistribMulAction M N := letI := e.monoid { e.mulAction M with smul_one := by simp [one_def, smul_def, smul_one] smul_mul := by simp [mul_def, smul_def, smul_mul'] } end Equiv
ZeroAndBoundedAtFilter.lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck, David Loeffler -/ import Mathlib.Algebra.Module.Submodule.Basic import Mathlib.Analysis.Asymptotics.Lemmas import Mathlib.Algebra.Algebra.Pi /-! # Zero and Bounded at filter Given a filter `l` we define the notion of a function being `ZeroAtFilter` as well as being `BoundedAtFilter`. Alongside this we construct the `Submodule`, `AddSubmonoid` of functions that are `ZeroAtFilter`. Similarly, we construct the `Submodule` and `Subalgebra` of functions that are `BoundedAtFilter`. -/ namespace Filter variable {𝕜 α β : Type*} open Topology /-- If `l` is a filter on `α`, then a function `f : α → β` is `ZeroAtFilter l` if it tends to zero along `l`. -/ def ZeroAtFilter [Zero β] [TopologicalSpace β] (l : Filter α) (f : α → β) : Prop := Filter.Tendsto f l (𝓝 0) theorem zero_zeroAtFilter [Zero β] [TopologicalSpace β] (l : Filter α) : ZeroAtFilter l (0 : α → β) := tendsto_const_nhds nonrec theorem ZeroAtFilter.add [TopologicalSpace β] [AddZeroClass β] [ContinuousAdd β] {l : Filter α} {f g : α → β} (hf : ZeroAtFilter l f) (hg : ZeroAtFilter l g) : ZeroAtFilter l (f + g) := by simpa using hf.add hg nonrec theorem ZeroAtFilter.neg [TopologicalSpace β] [SubtractionMonoid β] [ContinuousNeg β] {l : Filter α} {f : α → β} (hf : ZeroAtFilter l f) : ZeroAtFilter l (-f) := by simpa using hf.neg theorem ZeroAtFilter.smul [TopologicalSpace β] [Zero β] [SMulZeroClass 𝕜 β] [ContinuousConstSMul 𝕜 β] {l : Filter α} {f : α → β} (c : 𝕜) (hf : ZeroAtFilter l f) : ZeroAtFilter l (c • f) := by simpa using hf.const_smul c variable (𝕜) in /-- `zeroAtFilterSubmodule l` is the submodule of `f : α → β` which tend to zero along `l`. -/ def zeroAtFilterSubmodule [TopologicalSpace β] [Semiring 𝕜] [AddCommMonoid β] [Module 𝕜 β] [ContinuousAdd β] [ContinuousConstSMul 𝕜 β] (l : Filter α) : Submodule 𝕜 (α → β) where carrier := ZeroAtFilter l zero_mem' := zero_zeroAtFilter l add_mem' ha hb := ha.add hb smul_mem' c _ hf := hf.smul c /-- `zeroAtFilterAddSubmonoid l` is the additive submonoid of `f : α → β` which tend to zero along `l`. -/ def zeroAtFilterAddSubmonoid [TopologicalSpace β] [AddZeroClass β] [ContinuousAdd β] (l : Filter α) : AddSubmonoid (α → β) where carrier := ZeroAtFilter l add_mem' ha hb := ha.add hb zero_mem' := zero_zeroAtFilter l /-- If `l` is a filter on `α`, then a function `f: α → β` is `BoundedAtFilter l` if `f =O[l] 1`. -/ def BoundedAtFilter [Norm β] (l : Filter α) (f : α → β) : Prop := Asymptotics.IsBigO l f (1 : α → ℝ) theorem ZeroAtFilter.boundedAtFilter [SeminormedAddGroup β] {l : Filter α} {f : α → β} (hf : ZeroAtFilter l f) : BoundedAtFilter l f := ((Asymptotics.isLittleO_one_iff _).mpr hf).isBigO theorem const_boundedAtFilter [Norm β] (l : Filter α) (c : β) : BoundedAtFilter l (Function.const α c : α → β) := Asymptotics.isBigO_const_const c one_ne_zero l -- TODO(https://github.com/leanprover-community/mathlib4/issues/19288): Remove all Comm in the next -- three lemmas. This would require modifying the corresponding general asymptotics lemma. nonrec theorem BoundedAtFilter.add [SeminormedAddCommGroup β] {l : Filter α} {f g : α → β} (hf : BoundedAtFilter l f) (hg : BoundedAtFilter l g) : BoundedAtFilter l (f + g) := by simpa using hf.add hg theorem BoundedAtFilter.neg [SeminormedAddCommGroup β] {l : Filter α} {f : α → β} (hf : BoundedAtFilter l f) : BoundedAtFilter l (-f) := hf.neg_left theorem BoundedAtFilter.smul [SeminormedRing 𝕜] [SeminormedAddCommGroup β] [Module 𝕜 β] [IsBoundedSMul 𝕜 β] {l : Filter α} {f : α → β} (c : 𝕜) (hf : BoundedAtFilter l f) : BoundedAtFilter l (c • f) := hf.const_smul_left c nonrec theorem BoundedAtFilter.mul [SeminormedRing β] {l : Filter α} {f g : α → β} (hf : BoundedAtFilter l f) (hg : BoundedAtFilter l g) : BoundedAtFilter l (f * g) := by refine (hf.mul hg).trans ?_ convert Asymptotics.isBigO_refl (E := ℝ) _ l simp variable (𝕜) in /-- The submodule of functions that are bounded along a filter `l`. -/ def boundedFilterSubmodule [SeminormedRing 𝕜] [SeminormedAddCommGroup β] [Module 𝕜 β] [IsBoundedSMul 𝕜 β] (l : Filter α) : Submodule 𝕜 (α → β) where carrier := BoundedAtFilter l zero_mem' := const_boundedAtFilter l 0 add_mem' hf hg := hf.add hg smul_mem' c _ hf := hf.smul c variable (𝕜) in /-- The subalgebra of functions that are bounded along a filter `l`. -/ def boundedFilterSubalgebra [SeminormedCommRing 𝕜] [SeminormedRing β] [Algebra 𝕜 β] [IsBoundedSMul 𝕜 β] (l : Filter α) : Subalgebra 𝕜 (α → β) := Submodule.toSubalgebra (boundedFilterSubmodule 𝕜 l) (const_boundedAtFilter l (1 : β)) (fun f g hf hg ↦ by simpa only [Pi.one_apply, mul_one, norm_mul] using hf.mul hg) end Filter
Basic.lean
/- Copyright (c) 2021 Alena Gusakov, Bhavik Mehta, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alena Gusakov, Bhavik Mehta, Kyle Miller -/ import Mathlib.Combinatorics.Hall.Finite import Mathlib.CategoryTheory.CofilteredSystem import Mathlib.Data.Rel /-! # Hall's Marriage Theorem Given a list of finite subsets $X_1, X_2, \dots, X_n$ of some given set $S$, P. Hall in [Hall1935] gave a necessary and sufficient condition for there to be a list of distinct elements $x_1, x_2, \dots, x_n$ with $x_i\in X_i$ for each $i$: it is when for each $k$, the union of every $k$ of these subsets has at least $k$ elements. Rather than a list of finite subsets, one may consider indexed families `t : ι → Finset α` of finite subsets with `ι` a `Fintype`, and then the list of distinct representatives is given by an injective function `f : ι → α` such that `∀ i, f i ∈ t i`, called a *matching*. This version is formalized as `Finset.all_card_le_biUnion_card_iff_exists_injective'` in a separate module. The theorem can be generalized to remove the constraint that `ι` be a `Fintype`. As observed in [Halpern1966], one may use the constrained version of the theorem in a compactness argument to remove this constraint. The formulation of compactness we use is that inverse limits of nonempty finite sets are nonempty (`nonempty_sections_of_finite_inverse_system`), which uses the Tychonoff theorem. The core of this module is constructing the inverse system: for every finite subset `ι'` of `ι`, we can consider the matchings on the restriction of the indexed family `t` to `ι'`. ## Main statements * `Finset.all_card_le_biUnion_card_iff_exists_injective` is in terms of `t : ι → Finset α`. * `Fintype.all_card_le_rel_image_card_iff_exists_injective` is in terms of a relation `r : α → β → Prop` such that `R.image {a}` is a finite set for all `a : α`. * `Fintype.all_card_le_filter_rel_iff_exists_injective` is in terms of a relation `r : α → β → Prop` on finite types, with the Hall condition given in terms of `finset.univ.filter`. ## TODO * The statement of the theorem in terms of bipartite graphs is in preparation. ## Tags Hall's Marriage Theorem, indexed families -/ open Finset Function CategoryTheory open scoped SetRel universe u v /-- The set of matchings for `t` when restricted to a `Finset` of `ι`. -/ def hallMatchingsOn {ι : Type u} {α : Type v} (t : ι → Finset α) (ι' : Finset ι) := { f : ι' → α | Function.Injective f ∧ ∀ (x : {x // x ∈ ι'}), f x ∈ t x } /-- Given a matching on a finset, construct the restriction of that matching to a subset. -/ def hallMatchingsOn.restrict {ι : Type u} {α : Type v} (t : ι → Finset α) {ι' ι'' : Finset ι} (h : ι' ⊆ ι'') (f : hallMatchingsOn t ι'') : hallMatchingsOn t ι' := by refine ⟨fun i => f.val ⟨i, h i.property⟩, ?_⟩ obtain ⟨hinj, hc⟩ := f.property refine ⟨?_, fun i => hc ⟨i, h i.property⟩⟩ rintro ⟨i, hi⟩ ⟨j, hj⟩ hh simpa only [Subtype.mk_eq_mk] using hinj hh /-- When the Hall condition is satisfied, the set of matchings on a finite set is nonempty. This is where `Finset.all_card_le_biUnion_card_iff_existsInjective'` comes into the argument. -/ theorem hallMatchingsOn.nonempty {ι : Type u} {α : Type v} [DecidableEq α] (t : ι → Finset α) (h : ∀ s : Finset ι, #s ≤ #(s.biUnion t)) (ι' : Finset ι) : Nonempty (hallMatchingsOn t ι') := by classical refine ⟨Classical.indefiniteDescription _ ?_⟩ apply (all_card_le_biUnion_card_iff_existsInjective' fun i : ι' => t i).mp intro s' convert h (s'.image (↑)) using 1 · simp only [card_image_of_injective s' Subtype.coe_injective] · rw [image_biUnion] /-- This is the `hallMatchingsOn` sets assembled into a directed system. -/ def hallMatchingsFunctor {ι : Type u} {α : Type v} (t : ι → Finset α) : (Finset ι)ᵒᵖ ⥤ Type max u v where obj ι' := hallMatchingsOn t ι'.unop map {_ _} g f := hallMatchingsOn.restrict t (CategoryTheory.leOfHom g.unop) f instance hallMatchingsOn.finite {ι : Type u} {α : Type v} (t : ι → Finset α) (ι' : Finset ι) : Finite (hallMatchingsOn t ι') := by classical rw [hallMatchingsOn] let g : hallMatchingsOn t ι' → ι' → ι'.biUnion t := by rintro f i refine ⟨f.val i, ?_⟩ rw [mem_biUnion] exact ⟨i, i.property, f.property.2 i⟩ apply Finite.of_injective g intro f f' h ext a rw [funext_iff] at h simpa [g] using h a /-- This is the version of **Hall's Marriage Theorem** in terms of indexed families of finite sets `t : ι → Finset α`. It states that there is a set of distinct representatives if and only if every union of `k` of the sets has at least `k` elements. Recall that `s.biUnion t` is the union of all the sets `t i` for `i ∈ s`. This theorem is bootstrapped from `Finset.all_card_le_biUnion_card_iff_exists_injective'`, which has the additional constraint that `ι` is a `Fintype`. -/ theorem Finset.all_card_le_biUnion_card_iff_exists_injective {ι : Type u} {α : Type v} [DecidableEq α] (t : ι → Finset α) : (∀ s : Finset ι, #s ≤ #(s.biUnion t)) ↔ ∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by constructor · intro h -- Set up the functor haveI : ∀ ι' : (Finset ι)ᵒᵖ, Nonempty ((hallMatchingsFunctor t).obj ι') := fun ι' => hallMatchingsOn.nonempty t h ι'.unop classical haveI : ∀ ι' : (Finset ι)ᵒᵖ, Finite ((hallMatchingsFunctor t).obj ι') := by intro ι' rw [hallMatchingsFunctor] infer_instance -- Apply the compactness argument obtain ⟨u, hu⟩ := nonempty_sections_of_finite_inverse_system (hallMatchingsFunctor t) -- Interpret the resulting section of the inverse limit refine ⟨?_, ?_, ?_⟩ ·-- Build the matching function from the section exact fun i => (u (Opposite.op ({i} : Finset ι))).val ⟨i, by simp only [mem_singleton]⟩ · -- Show that it is injective intro i i' have subi : ({i} : Finset ι) ⊆ {i, i'} := by simp have subi' : ({i'} : Finset ι) ⊆ {i, i'} := by simp rw [← Finset.le_iff_subset] at subi subi' simp only rw [← hu (CategoryTheory.homOfLE subi).op, ← hu (CategoryTheory.homOfLE subi').op] let uii' := u (Opposite.op ({i, i'} : Finset ι)) exact fun h => Subtype.mk_eq_mk.mp (uii'.property.1 h) · -- Show that it maps each index to the corresponding finite set intro i apply (u (Opposite.op ({i} : Finset ι))).property.2 · -- The reverse direction is a straightforward cardinality argument rintro ⟨f, hf₁, hf₂⟩ s rw [← Finset.card_image_of_injective s hf₁] apply Finset.card_le_card grind /-- Given a relation such that the image of every singleton set is finite, then the image of every finite set is finite. -/ instance {α : Type u} {β : Type v} [DecidableEq β] (R : SetRel α β) [∀ a : α, Fintype (R.image {a})] (A : Finset α) : Fintype (R.image A) := by have h : R.image A = (A.biUnion fun a => (R.image {a}).toFinset : Set β) := by ext simp [SetRel.image] rw [h] apply FinsetCoe.fintype /-- This is a version of **Hall's Marriage Theorem** in terms of a relation between types `α` and `β` such that `α` is finite and the image of each `x : α` is finite (it suffices for `β` to be finite; see `Fintype.all_card_le_filter_rel_iff_exists_injective`). There is a transversal of the relation (an injective function `α → β` whose graph is a subrelation of the relation) iff every subset of `k` terms of `α` is related to at least `k` terms of `β`. Note: if `[Fintype β]`, then there exist instances for `[∀ (a : α), Fintype (R.image {a})]`. -/ theorem Fintype.all_card_le_rel_image_card_iff_exists_injective {α : Type u} {β : Type v} [DecidableEq β] (R : SetRel α β) [∀ a : α, Fintype (R.image {a})] : (∀ A : Finset α, #A ≤ Fintype.card (R.image A)) ↔ ∃ f : α → β, Function.Injective f ∧ ∀ x, x ~[R] f x := by let r' a := (R.image {a}).toFinset have h : ∀ A : Finset α, Fintype.card (R.image A) = #(A.biUnion r') := by intro A rw [← Set.toFinset_card] apply congr_arg ext b simp [r', SetRel.image] have h' : ∀ (f : α → β) (x), x ~[R] f x ↔ f x ∈ r' x := by simp [r', SetRel.image] simp only [h, h'] apply Finset.all_card_le_biUnion_card_iff_exists_injective /-- This is a version of **Hall's Marriage Theorem** in terms of a relation to a finite type. There is a transversal of the relation (an injective function `α → β` whose graph is a subrelation of the relation) iff every subset of `k` terms of `α` is related to at least `k` terms of `β`. It is like `Fintype.all_card_le_rel_image_card_iff_exists_injective` but uses `Finset.filter` rather than `Rel.image`. -/ theorem Fintype.all_card_le_filter_rel_iff_exists_injective {α : Type u} {β : Type v} [Fintype β] (r : α → β → Prop) [DecidableRel r] : (∀ A : Finset α, #A ≤ #{b | ∃ a ∈ A, r a b}) ↔ ∃ f : α → β, Injective f ∧ ∀ x, r x (f x) := by haveI := Classical.decEq β let r' a : Finset β := {b | r a b} have h : ∀ A : Finset α, ({b | ∃ a ∈ A, r a b} : Finset _) = A.biUnion r' := by intro A ext b simp [r'] have h' : ∀ (f : α → β) (x), r x (f x) ↔ f x ∈ r' x := by simp [r'] simp_rw [h, h'] apply Finset.all_card_le_biUnion_card_iff_exists_injective
BoundedContinuousFunctionChar.lean
/- Copyright (c) 2025 Jakob Stiefel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob Stiefel -/ import Mathlib.Algebra.MonoidAlgebra.Basic import Mathlib.Analysis.Complex.Circle import Mathlib.Analysis.InnerProductSpace.Basic import Mathlib.Topology.ContinuousMap.Bounded.Star /-! # Definition of BoundedContinuousFunction.char Definition and basic properties of `BoundedContinuousFunction.char he hL w := fun v ↦ e (L v w)`, where `e` is a continuous additive character and `L : V →ₗ[ℝ] W →ₗ[ℝ] ℝ` is a continuous bilinear map. In the special case `e = Circle.exp`, this is used to define the characteristic function of a measure. ## Main definitions - `char he hL w : V →ᵇ ℂ`: Bounded continuous mapping `fun v ↦ e (L v w)` from `V` to `ℂ`, where `e` is a continuous additive character and `L : V →ₗ[ℝ] W →ₗ[ℝ] ℝ` is a continuous bilinear map. - `charPoly he hL : W → ℂ`: The `StarSubalgebra ℂ (V →ᵇ ℂ)` consisting of `ℂ`-linear combinations of `char he hL w`, where `w : W`. ## Main statements - `ext_of_char_eq`: If `e` and `L` are non-trivial, then `char he hL w, w : W` separates points in `V`. - `star_mem_range_charAlgHom`: The family of `ℂ`-linear combinations of `char he hL w, w : W`, is closed under `star`. - `separatesPoints_charPoly`: The family `charPoly he hL w, w : W` separates points in `V`. -/ open Filter BoundedContinuousFunction Complex namespace BoundedContinuousFunction variable {V W : Type*} [AddCommGroup V] [Module ℝ V] [TopologicalSpace V] [AddCommGroup W] [Module ℝ W] [TopologicalSpace W] {e : AddChar ℝ Circle} {L : V →ₗ[ℝ] W →ₗ[ℝ] ℝ} {he : Continuous e} {hL : Continuous fun p : V × W ↦ L p.1 p.2} /-- The bounded continuous mapping `fun v ↦ e (L v w)` from `V` to `ℂ`. -/ noncomputable def char (he : Continuous e) (hL : Continuous fun p : V × W ↦ L p.1 p.2) (w : W) : V →ᵇ ℂ where toFun := fun v ↦ e (L v w) continuous_toFun := continuous_induced_dom.comp (he.comp (hL.comp (Continuous.prodMk_left w))) map_bounded' := by refine ⟨2, fun x y ↦ ?_⟩ calc dist _ _ ≤ (‖_‖ : ℝ) + ‖_‖ := dist_le_norm_add_norm _ _ _ ≤ 1 + 1 := add_le_add (by simp) (by simp) _ = 2 := by ring @[simp] lemma char_apply (w : W) (v : V) : char he hL w v = e (L v w) := rfl @[simp] lemma char_zero_eq_one : char he hL 0 = 1 := by ext; simp lemma char_add_eq_mul (x y : W) : char he hL (x + y) = char he hL x * char he hL y := by ext simp [e.map_add_eq_mul] lemma char_neg (w : W) : char he hL (-w) = star (char he hL w) := by ext; simp /-- If `e` and `L` are non-trivial, then `char he hL w, w : W` separates points in `V`. -/ theorem ext_of_char_eq (he : Continuous e) (he' : e ≠ 1) (hL : Continuous fun p : V × W ↦ L p.1 p.2) (hL' : ∀ v ≠ 0, L v ≠ 0) {v v' : V} (h : ∀ w, char he hL w v = char he hL w v') : v = v' := by contrapose! h obtain ⟨w, hw⟩ := DFunLike.ne_iff.mp (hL' (v - v') (sub_ne_zero_of_ne h)) obtain ⟨a, ha⟩ := DFunLike.ne_iff.mp he' use (a / (L (v - v') w)) • w simp only [map_sub, LinearMap.sub_apply, char_apply, ne_eq] rw [← div_eq_one_iff_eq (Circle.coe_ne_zero _), div_eq_inv_mul, ← Metric.unitSphere.coe_inv, ← e.map_neg_eq_inv, ← Submonoid.coe_mul, ← e.map_add_eq_mul, OneMemClass.coe_eq_one] calc e (- L v' ((a / (L v w - L v' w)) • w) + L v ((a / (L v w - L v' w)) • w)) _ = e (- (a / (L v w - L v' w)) • L v' w + (a / (L v w - L v' w)) • L v w) := by congr · rw [neg_smul, ← LinearMap.map_smul (L v')] · rw [← LinearMap.map_smul (L v)] _ = e ((a / (L (v - v') w)) • (L (v - v') w)) := by simp only [map_sub, LinearMap.sub_apply] congr module _ = e a := by congr exact div_mul_cancel₀ a hw _ ≠ 1 := ha /-- Monoid homomorphism mapping `w` to `fun v ↦ e (L v w)`. -/ noncomputable def charMonoidHom (he : Continuous e) (hL : Continuous fun p : V × W ↦ L p.1 p.2) : Multiplicative W →* (V →ᵇ ℂ) where toFun w := char he hL w map_one' := char_zero_eq_one map_mul' := char_add_eq_mul (he := he) (hL := hL) @[simp] lemma charMonoidHom_apply (w : Multiplicative W) (v : V) : charMonoidHom he hL w v = e (L v w) := by simp [charMonoidHom] /-- Algebra homomorphism mapping `w` to `fun v ↦ e (L v w)`. -/ noncomputable def charAlgHom (he : Continuous e) (hL : Continuous fun p : V × W ↦ L p.1 p.2) : AddMonoidAlgebra ℂ W →ₐ[ℂ] (V →ᵇ ℂ) := AddMonoidAlgebra.lift ℂ W (V →ᵇ ℂ) (charMonoidHom he hL) @[simp] lemma charAlgHom_apply (w : AddMonoidAlgebra ℂ W) (v : V) : charAlgHom he hL w v = ∑ a ∈ w.support, w a * (e (L v a) : ℂ) := by simp only [charAlgHom, AddMonoidAlgebra.lift_apply] rw [Finsupp.sum_of_support_subset w subset_rfl] · simp only [coe_sum, coe_smul, charMonoidHom_apply, smul_eq_mul, Finset.sum_apply] rfl · simp /-- The family of `ℂ`-linear combinations of `char he hL w, w : W`, is closed under `star`. -/ lemma star_mem_range_charAlgHom (he : Continuous e) (hL : Continuous fun p : V × W ↦ L p.1 p.2) {x : V →ᵇ ℂ} (hx : x ∈ (charAlgHom he hL).range) : star x ∈ (charAlgHom he hL).range := by simp only [AlgHom.mem_range] at hx ⊢ obtain ⟨y, rfl⟩ := hx let z := Finsupp.mapRange star (star_zero _) y let f : W ↪ W := ⟨fun x ↦ -x, (fun _ _ ↦ neg_inj.mp)⟩ refine ⟨z.embDomain f, ?_⟩ ext1 u simp only [charAlgHom_apply, Finsupp.support_embDomain, Finset.sum_map, Finsupp.embDomain_apply, star_apply, star_sum, star_mul', Circle.star_addChar] rw [Finsupp.support_mapRange_of_injective (star_zero _) y star_injective] simp [z, f] /-- The star-subalgebra of polynomials. -/ noncomputable def charPoly (he : Continuous e) (hL : Continuous fun p : V × W ↦ L p.1 p.2) : StarSubalgebra ℂ (V →ᵇ ℂ) where toSubalgebra := (charAlgHom he hL).range star_mem' hx := star_mem_range_charAlgHom he hL hx lemma mem_charPoly (f : V →ᵇ ℂ) : f ∈ charPoly he hL ↔ ∃ w : AddMonoidAlgebra ℂ W, f = fun x ↦ ∑ a ∈ w.support, w a * (e (L x a) : ℂ) := by change f ∈ (charAlgHom he hL).range ↔ _ simp [BoundedContinuousFunction.ext_iff, funext_iff, eq_comm] lemma char_mem_charPoly (w : W) : char he hL w ∈ charPoly he hL := by rw [mem_charPoly] refine ⟨AddMonoidAlgebra.single w 1, ?_⟩ ext v simp only [char_apply, AddMonoidAlgebra.single] rw [Finset.sum_eq_single w] · simp only [Finsupp.single_eq_same, one_mul] · simp [Finsupp.single_apply_ne_zero] · simp /-- The family `charPoly he hL w, w : W` separates points in `V`. -/ lemma separatesPoints_charPoly (he : Continuous e) (he' : e ≠ 1) (hL : Continuous fun p : V × W ↦ L p.1 p.2) (hL' : ∀ v ≠ 0, L v ≠ 0) : ((charPoly he hL).map (toContinuousMapStarₐ ℂ)).SeparatesPoints := by intro v v' hvv' obtain ⟨w, hw⟩ : ∃ w, char he hL w v ≠ char he hL w v' := by contrapose! hvv' exact ext_of_char_eq he he' hL hL' hvv' use char he hL w simp only [StarSubalgebra.coe_toSubalgebra, StarSubalgebra.coe_map, Set.mem_image, SetLike.mem_coe, exists_exists_and_eq_and, ne_eq] exact ⟨⟨char he hL w, char_mem_charPoly w, rfl⟩, hw⟩ end BoundedContinuousFunction
FinsetOps.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Multiset.Dedup import Mathlib.Data.List.Infix /-! # Preparations for defining operations on `Finset`. The operations here ignore multiplicities, and prepare for defining the corresponding operations on `Finset`. -/ -- Assert that we define `Finset` without the material on the set lattice. -- Note that we cannot put this in `Data.Finset.Basic` because we proved relevant lemmas there. assert_not_exists Set.sInter namespace Multiset open List variable {α : Type*} [DecidableEq α] {s : Multiset α} /-! ### finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `Finset`. -/ def ndinsert (a : α) (s : Multiset α) : Multiset α := Quot.liftOn s (fun l => (l.insert a : Multiset α)) fun _ _ p => Quot.sound (p.insert a) @[simp] theorem coe_ndinsert (a : α) (l : List α) : ndinsert a l = (insert a l : List α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = {a} := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : Multiset α} : a ∈ s → ndinsert a s = s := Quot.inductionOn s fun _ h => congr_arg ((↑) : List α → Multiset α) <| insert_of_mem h @[simp] theorem ndinsert_of_notMem {a : α} {s : Multiset α} : a ∉ s → ndinsert a s = a ::ₘ s := Quot.inductionOn s fun _ h => congr_arg ((↑) : List α → Multiset α) <| insert_of_not_mem h @[deprecated (since := "2025-05-23")] alias ndinsert_of_not_mem := ndinsert_of_notMem @[simp] theorem mem_ndinsert {a b : α} {s : Multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := Quot.inductionOn s fun _ => mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : Multiset α) : s ≤ ndinsert a s := Quot.inductionOn s fun _ => (sublist_insert _ _).subperm theorem mem_ndinsert_self (a : α) (s : Multiset α) : a ∈ ndinsert a s := by simp theorem mem_ndinsert_of_mem {a b : α} {s : Multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (Or.inr h) theorem length_ndinsert_of_mem {a : α} {s : Multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] theorem length_ndinsert_of_notMem {a : α} {s : Multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] @[deprecated (since := "2025-05-23")] alias length_ndinsert_of_not_mem := length_ndinsert_of_notMem theorem dedup_cons {a : α} {s : Multiset α} : dedup (a ::ₘ s) = ndinsert a (dedup s) := by by_cases h : a ∈ s <;> simp [h] theorem Nodup.ndinsert (a : α) : Nodup s → Nodup (ndinsert a s) := Quot.inductionOn s fun _ => Nodup.insert theorem ndinsert_le {a : α} {s t : Multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨fun h => ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, fun ⟨l, m⟩ => if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_notMem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_notMem h, cons_erase m] exact l⟩ theorem attach_ndinsert (a : α) (s : Multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map fun p => ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀ h : ∀ p : { x // x ∈ s }, p.1 ∈ s, (fun p : { x // x ∈ s } => ⟨p.val, h p⟩ : { x // x ∈ s } → { x // x ∈ s }) = id := fun _ => funext fun _ => Subtype.eq rfl have : ∀ (t) (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map fun p => ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩) := by intro t ht by_cases h : a ∈ s · rw [ndinsert_of_mem h] at ht subst ht rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] · rw [ndinsert_of_notMem h] at ht subst ht simp [attach_cons, h] this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : Multiset α} : Disjoint (ndinsert a s) t ↔ a ∉ t ∧ Disjoint s t := Iff.trans (by simp [disjoint_left]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : Multiset α} : Disjoint s (ndinsert a t) ↔ a ∉ s ∧ Disjoint s t := by rw [_root_.disjoint_comm, disjoint_ndinsert_left]; tauto /-! ### finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `Finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : Multiset α) : Multiset α := (Quotient.liftOn₂ s t fun l₁ l₂ => (l₁.union l₂ : Multiset α)) fun _ _ _ _ p₁ p₂ => Quot.sound <| p₁.union p₂ @[simp] theorem coe_ndunion (l₁ l₂ : List α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : List α) := rfl -- `simp` can prove this once we have `ndunion_eq_union`. theorem zero_ndunion (s : Multiset α) : ndunion 0 s = s := Quot.inductionOn s fun _ => rfl @[simp] theorem cons_ndunion (s t : Multiset α) (a : α) : ndunion (a ::ₘ s) t = ndinsert a (ndunion s t) := Quot.induction_on₂ s t fun _ _ => rfl @[simp] theorem mem_ndunion {s t : Multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := Quot.induction_on₂ s t fun _ _ => List.mem_union_iff theorem le_ndunion_right (s t : Multiset α) : t ≤ ndunion s t := Quot.induction_on₂ s t fun _ _ => (suffix_union_right _ _).sublist.subperm theorem subset_ndunion_right (s t : Multiset α) : t ⊆ ndunion s t := subset_of_le (le_ndunion_right s t) theorem ndunion_le_add (s t : Multiset α) : ndunion s t ≤ s + t := Quot.induction_on₂ s t fun _ _ => (union_sublist_append _ _).subperm theorem ndunion_le {s t u : Multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := Multiset.induction_on s (by simp [zero_ndunion]) (fun _ _ h => by simp only [cons_ndunion, ndinsert_le, and_comm, cons_subset, and_left_comm, h, and_assoc]) theorem subset_ndunion_left (s t : Multiset α) : s ⊆ ndunion s t := fun _ h => mem_ndunion.2 <| Or.inl h theorem le_ndunion_left {s} (t : Multiset α) (d : Nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 <| subset_ndunion_left _ _ theorem ndunion_le_union (s t : Multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le le_union_left, le_union_right⟩ theorem Nodup.ndunion (s : Multiset α) {t : Multiset α} : Nodup t → Nodup (ndunion s t) := Quot.induction_on₂ s t fun _ _ => List.Nodup.union _ @[simp] theorem ndunion_eq_union {s t : Multiset α} (d : Nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) <| union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem dedup_add (s t : Multiset α) : dedup (s + t) = ndunion s (dedup t) := Quot.induction_on₂ s t fun _ _ => congr_arg ((↑) : List α → Multiset α) <| dedup_append _ _ theorem Disjoint.ndunion_eq {s t : Multiset α} (h : Disjoint s t) : s.ndunion t = s.dedup + t := by induction s, t using Quot.induction_on₂ exact congr_arg ((↑) : List α → Multiset α) <| List.Disjoint.union_eq <| by simpa using h theorem Subset.ndunion_eq_right {s t : Multiset α} (h : s ⊆ t) : s.ndunion t = t := by induction s, t using Quot.induction_on₂ exact congr_arg ((↑) : List α → Multiset α) <| List.Subset.union_eq_right h /-! ### finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `Finset`. (`s ∩ t` would also work as an intersection operation on finset, but this is more efficient.) -/ def ndinter (s t : Multiset α) : Multiset α := filter (· ∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : List α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : List α) := by simp only [ndinter, mem_coe, filter_coe, coe_eq_coe, ← elem_eq_mem] apply Perm.refl @[simp] theorem zero_ndinter (s : Multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : Multiset α) {t : Multiset α} (h : a ∈ t) : ndinter (a ::ₘ s) t = a ::ₘ ndinter s t := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_notMem {a : α} (s : Multiset α) {t : Multiset α} (h : a ∉ t) : ndinter (a ::ₘ s) t = ndinter s t := by simp [ndinter, h] @[deprecated (since := "2025-05-23")] alias ndinter_cons_of_not_mem := ndinter_cons_of_notMem @[simp] theorem mem_ndinter {s t : Multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := by simp [ndinter, mem_filter] -- simp can prove this once we have `ndinter_eq_inter` and `Nodup.inter` a few lines down. theorem Nodup.ndinter {s : Multiset α} (t : Multiset α) : Nodup s → Nodup (ndinter s t) := Nodup.filter _ theorem le_ndinter {s t u : Multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : Multiset α) : ndinter s t ≤ s := (le_ndinter.1 le_rfl).1 theorem ndinter_subset_left (s t : Multiset α) : ndinter s t ⊆ s := subset_of_le (ndinter_le_left s t) theorem ndinter_subset_right (s t : Multiset α) : ndinter s t ⊆ t := (le_ndinter.1 le_rfl).2 theorem ndinter_le_right {s} (t : Multiset α) (d : Nodup s) : ndinter s t ≤ t := (le_iff_subset <| d.ndinter _).2 <| ndinter_subset_right _ _ theorem inter_le_ndinter (s t : Multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left, subset_of_le inter_le_right⟩ @[simp] theorem ndinter_eq_inter {s t : Multiset α} (d : Nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) @[simp] theorem Nodup.inter {s : Multiset α} (t : Multiset α) (d : Nodup s) : Nodup (s ∩ t) := by rw [← ndinter_eq_inter d] exact d.filter _ theorem ndinter_eq_zero_iff_disjoint {s t : Multiset α} : ndinter s t = 0 ↔ Disjoint s t := by rw [← subset_zero]; simp [subset_iff, disjoint_left] alias ⟨_, Disjoint.ndinter_eq_zero⟩ := ndinter_eq_zero_iff_disjoint theorem Subset.ndinter_eq_left {s t : Multiset α} (h : s ⊆ t) : s.ndinter t = s := by induction s, t using Quot.induction_on₂ rw [quot_mk_to_coe'', quot_mk_to_coe'', coe_ndinter, List.Subset.inter_eq_left h] end Multiset
Imo1988Q6.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Data.Nat.Prime.Defs import Mathlib.Data.Rat.Defs import Mathlib.Order.WellFounded import Mathlib.Tactic.Linarith import Mathlib.Tactic.Ring import Mathlib.Tactic.WLOG /-! # IMO 1988 Q6 and constant descent Vieta jumping Question 6 of IMO1988 is somewhat (in)famous. Several expert problem solvers could not tackle the question within the given time limit. The problem lead to the introduction of a new proof technique, so called “Vieta jumping”. In this file we formalise constant descent Vieta jumping, and apply this to prove Q6 of IMO1988. To illustrate the technique, we also prove a similar result. -/ attribute [local simp] sq namespace Imo1988Q6 /-- Constant descent Vieta jumping. This proof technique allows one to prove an arbitrary proposition `claim`, by running a descent argument on a hyperbola `H` in the first quadrant of the plane, under the following conditions: * `h₀` : There exists an integral point `(x,y)` on the hyperbola `H`. * `H_symm` : The hyperbola has a symmetry along the diagonal in the plane. * `H_zero` : If an integral point `(x,0)` lies on the hyperbola `H`, then `claim` is true. * `H_diag` : If an integral point `(x,x)` lies on the hyperbola `H`, then `claim` is true. * `H_desc` : If `(x,y)` is an integral point on the hyperbola `H`, with `x < y` then there exists a “smaller” point on `H`: a point `(x',y')` with `x' < y' ≤ x`. For reasons of usability, the hyperbola `H` is implemented as an arbitrary predicate. (In question 6 of IMO1988, where this proof technique was first developed, the predicate `claim` would be `∃ (d : ℕ), d ^ 2 = k` for some natural number `k`, and the predicate `H` would be `fun a b ↦ a * a + b * b = (a * b + 1) * k`.) To ensure that the predicate `H` actually describes a hyperbola, the user must provide arguments `B` and `C` that are used as coefficients for a quadratic equation. Finally, `H_quad` is the proof obligation that the quadratic equation `(y:ℤ) * y - B x * y + C x = 0` describes the same hyperbola as the predicate `H`. For extra flexibility, one must provide a predicate `base` on the integral points in the plane. In the descent step `H_desc` this will give the user the additional assumption that the point `(x,y)` does not lie in this base locus. The user must provide a proof that the proposition `claim` is true if there exists an integral point `(x,y)` on the hyperbola `H` that lies in the base locus. If such a base locus is not necessary, once can simply let it be `fun x y ↦ False`. -/ theorem constant_descent_vieta_jumping (x y : ℕ) {claim : Prop} {H : ℕ → ℕ → Prop} (h₀ : H x y) (B : ℕ → ℤ) (C : ℕ → ℤ) (base : ℕ → ℕ → Prop) (H_quad : ∀ {x y}, H x y ↔ (y : ℤ) * y - B x * y + C x = 0) (H_symm : ∀ {x y}, H x y ↔ H y x) (H_zero : ∀ {x}, H x 0 → claim) (H_diag : ∀ {x}, H x x → claim) (H_desc : ∀ {x y}, 0 < x → x < y → ¬base x y → H x y → ∀ y', y' * y' - B x * y' + C x = 0 → y' = B x - y → y' * y = C x → 0 ≤ y' ∧ y' ≤ x) (H_base : ∀ {x y}, H x y → base x y → claim) : claim := by -- First of all, we may assume that x ≤ y. -- We justify this using H_symm. wlog hxy : x ≤ y · rw [H_symm] at h₀; apply this y x h₀ B C base _ _ _ _ _ _ (le_of_not_ge hxy); assumption' -- In fact, we can easily deal with the case x = y. by_cases x_eq_y : x = y · subst x_eq_y; exact H_diag h₀ -- Hence we may assume that x < y. replace hxy : x < y := lt_of_le_of_ne hxy x_eq_y clear x_eq_y -- Consider the upper branch of the hyperbola defined by H. let upper_branch : Set (ℕ × ℕ) := {p | H p.1 p.2 ∧ p.1 < p.2} -- Note that the point p = (x,y) lies on the upper branch. let p : ℕ × ℕ := ⟨x, y⟩ have hp : p ∈ upper_branch := ⟨h₀, hxy⟩ -- We also consider the exceptional set of solutions (a,b) that satisfy -- a = 0 or a = b or B a = b or B a = b + a or that lie in the base locus. let exceptional : Set (ℕ × ℕ) := {p | H p.1 p.2 ∧ (base p.1 p.2 ∨ p.1 = 0 ∨ p.1 = p.2 ∨ B p.1 = p.2 ∨ B p.1 = p.2 + p.1)} -- Let S be the projection of the upper branch on to the y-axis -- after removing the exceptional locus. let S : Set ℕ := Prod.snd '' (upper_branch \ exceptional) -- The strategy is to show that the exceptional locus in nonempty -- by running a descent argument that starts with the given point p = (x,y). -- Our assumptions ensure that we can then prove the claim. suffices exc : exceptional.Nonempty by -- Suppose that there exists an element in the exceptional locus. simp only [Set.Nonempty, Prod.exists, Set.mem_setOf_eq, exceptional] at exc -- Let (a,b) be such an element, and consider all the possible cases. rcases exc with ⟨a, b, hH, hb⟩ rcases hb with (_ | rfl | rfl | hB | hB) -- The first three cases are rather easy to solve. · solve_by_elim · rw [H_symm] at hH; solve_by_elim · solve_by_elim -- The final two cases are very similar. all_goals -- Consider the quadratic equation that (a,b) satisfies. rw [H_quad] at hH -- We find the other root of the equation, and Vieta's formulas. rcases vieta_formula_quadratic hH with ⟨c, h_root, hV₁, hV₂⟩ -- By substitutions we find that b = 0 or b = a. simp only [hB, add_eq_left, add_right_inj] at hV₁ subst hV₁ rw [← Int.ofNat_zero] at * rw [← H_quad] at h_root -- And hence we are done by H_zero and H_diag. solve_by_elim -- To finish the main proof, we need to show that the exceptional locus is nonempty. -- So we assume that the exceptional locus is empty, and work towards deriving a contradiction. rw [Set.nonempty_iff_ne_empty] intro exceptional_empty -- Observe that S is nonempty. have S_nonempty : S.Nonempty := by -- It contains the image of p. use p.2 apply Set.mem_image_of_mem -- After all, we assumed that the exceptional locus is empty. rwa [exceptional_empty, Set.diff_empty] -- We are now set for an infinite descent argument. -- Let m be the smallest element of the nonempty set S. let m : ℕ := WellFounded.min Nat.lt_wfRel.wf S S_nonempty have m_mem : m ∈ S := WellFounded.min_mem Nat.lt_wfRel.wf S S_nonempty have m_min : ∀ k ∈ S, ¬k < m := fun k hk => WellFounded.not_lt_min Nat.lt_wfRel.wf S S_nonempty hk -- It suffices to show that there is point (a,b) with b ∈ S and b < m. rsuffices ⟨p', p'_mem, p'_small⟩ : ∃ p' : ℕ × ℕ, p'.2 ∈ S ∧ p'.2 < m · solve_by_elim -- Let (m_x, m_y) be a point on the upper branch that projects to m ∈ S -- and that does not lie in the exceptional locus. rcases m_mem with ⟨⟨mx, my⟩, ⟨⟨hHm, mx_lt_my⟩, h_base⟩, m_eq⟩ -- This means that m_y = m, -- and the conditions H(m_x, m_y) and m_x < m_y are satisfied. simp only at mx_lt_my hHm m_eq simp only [exceptional, hHm, Set.mem_setOf_eq, true_and] at h_base push_neg at h_base -- Finally, it also means that (m_x, m_y) does not lie in the base locus, -- that m_x ≠ 0, m_x ≠ m_y, B(m_x) ≠ m_y, and B(m_x) ≠ m_x + m_y. rcases h_base with ⟨h_base, hmx, hm_diag, hm_B₁, hm_B₂⟩ replace hmx : 0 < mx := pos_iff_ne_zero.mpr hmx -- Consider the quadratic equation that (m_x, m_y) satisfies. have h_quad := hHm rw [H_quad] at h_quad -- We find the other root of the equation, and Vieta's formulas. rcases vieta_formula_quadratic h_quad with ⟨c, h_root, hV₁, hV₂⟩ -- Now we rewrite Vietas formulas a bit, and apply the descent step. replace hV₁ : c = B mx - my := eq_sub_of_add_eq' hV₁ rw [mul_comm] at hV₂ have Hc := H_desc hmx mx_lt_my h_base hHm c h_root hV₁ hV₂ -- This means that we may assume that c ≥ 0 and c ≤ m_x. obtain ⟨c_nonneg, c_lt⟩ := Hc -- In other words, c is a natural number. lift c to ℕ using c_nonneg -- Recall that we are trying find a point (a,b) such that b ∈ S and b < m. -- We claim that p' = (c, m_x) does the job. let p' : ℕ × ℕ := ⟨c, mx⟩ use p' -- The second condition is rather easy to check, so we do that first. constructor; swap · rwa [m_eq] at mx_lt_my -- Now we need to show that p' projects onto S. In other words, that c ∈ S. -- We do that, by showing that it lies in the upper branch -- (which is sufficient, because we assumed that the exceptional locus is empty). apply Set.mem_image_of_mem rw [exceptional_empty, Set.diff_empty] -- Now we are ready to prove that p' = (c, m_x) lies on the upper branch. -- We need to check two conditions: H(c, m_x) and c < m_x. constructor <;> dsimp only · -- The first condition is not so hard. After all, c is the other root of the quadratic equation. rw [H_symm, H_quad] simpa using h_root · -- For the second condition, we note that it suffices to check that c ≠ m_x. suffices hc : c ≠ mx from lt_of_le_of_ne (mod_cast c_lt) hc -- However, recall that B(m_x) ≠ m_x + m_y. -- If c = m_x, we can prove B(m_x) = m_x + m_y. contrapose! hm_B₂ subst c simp [hV₁] -- Hence p' = (c, m_x) lies on the upper branch, and we are done. end Imo1988Q6 open Imo1988Q6 /-- Question 6 of IMO1988. If a and b are two natural numbers such that a*b+1 divides a^2 + b^2, show that their quotient is a perfect square. -/ theorem imo1988_q6 {a b : ℕ} (h : a * b + 1 ∣ a ^ 2 + b ^ 2) : ∃ d, d ^ 2 = (a ^ 2 + b ^ 2) / (a * b + 1) := by rcases h with ⟨k, hk⟩ rw [hk, Nat.mul_div_cancel_left _ (Nat.succ_pos (a * b))] simp only [sq] at hk apply constant_descent_vieta_jumping a b (H := fun a b => a * a + b * b = (a * b + 1) * k) hk (fun x => k * x) (fun x => x * x - k) fun _ _ => False <;> clear hk a b · -- We will now show that the fibers of the solution set are described by a quadratic equation. intro x y rw [← Int.natCast_inj, ← sub_eq_zero] apply eq_iff_eq_cancel_right.2 simp; ring · -- Show that the solution set is symmetric in a and b. intro x y simp [add_comm (x * x), mul_comm x] · -- Show that the claim is true if b = 0. suffices ∀ a, a * a = k → ∃ d, d * d = k by simpa rintro x rfl; use x · -- Show that the claim is true if a = b. intro x hx suffices k ≤ 1 by rw [Nat.le_add_one_iff, Nat.le_zero] at this rcases this with (rfl | rfl) · use 0; simp · use 1; simp contrapose! hx with k_lt_one apply ne_of_lt calc x * x + x * x = x * x * 2 := by rw [mul_two] _ ≤ x * x * k := Nat.mul_le_mul_left (x * x) k_lt_one _ < (x * x + 1) * k := by linarith · -- Show the descent step. intro x y hx x_lt_y _ _ z h_root _ hV₀ constructor · have hpos : z * z + x * x > 0 := by apply add_pos_of_nonneg_of_pos · apply mul_self_nonneg · apply mul_pos <;> exact mod_cast hx have hzx : z * z + x * x = (z * x + 1) * k := by rw [← sub_eq_zero, ← h_root] ring rw [hzx] at hpos replace hpos : z * x + 1 > 0 := pos_of_mul_pos_left hpos (Int.ofNat_zero_le k) replace hpos : z * x ≥ 0 := Int.le_of_lt_add_one hpos apply nonneg_of_mul_nonneg_left hpos (mod_cast hx) · contrapose! hV₀ with x_lt_z apply ne_of_gt calc z * y > x * x := by apply mul_lt_mul' <;> omega _ ≥ x * x - k := sub_le_self _ (Int.ofNat_zero_le k) · -- There is no base case in this application of Vieta jumping. simp /- The following example illustrates the use of constant descent Vieta jumping in the presence of a non-trivial base case. -/ example {a b : ℕ} (h : a * b ∣ a ^ 2 + b ^ 2 + 1) : 3 * a * b = a ^ 2 + b ^ 2 + 1 := by rcases h with ⟨k, hk⟩ suffices k = 3 by simp_all; ring simp only [sq] at hk apply constant_descent_vieta_jumping a b (H := fun a b => a * a + b * b + 1 = a * b * k) hk (fun x => k * x) (fun x => x * x + 1) fun x _ => x ≤ 1 <;> clear hk a b · -- We will now show that the fibers of the solution set are described by a quadratic equation. intro x y rw [← Int.natCast_inj, ← sub_eq_zero] apply eq_iff_eq_cancel_right.2 simp; ring · -- Show that the solution set is symmetric in a and b. intro x y; ring_nf · -- Show that the claim is true if b = 0. simp · -- Show that the claim is true if a = b. intro x hx have x_sq_dvd : x * x ∣ x * x * k := dvd_mul_right (x * x) k rw [← hx] at x_sq_dvd obtain ⟨y, hy⟩ : x * x ∣ 1 := by simpa only [Nat.dvd_add_self_left, add_assoc] using x_sq_dvd obtain ⟨rfl, rfl⟩ : x = 1 ∧ y = 1 := by simpa [mul_eq_one] using hy.symm simpa using hx.symm · -- Show the descent step. intro x y _ hx h_base _ z _ _ hV₀ constructor · have zy_pos : z * y ≥ 0 := by rw [hV₀]; exact mod_cast Nat.zero_le _ apply nonneg_of_mul_nonneg_left zy_pos omega · contrapose! hV₀ with x_lt_z apply ne_of_gt push_neg at h_base calc z * y > x * y := by apply mul_lt_mul_of_pos_right <;> omega _ ≥ x * (x + 1) := by apply mul_le_mul <;> omega _ > x * x + 1 := by rw [mul_add] omega · -- Show the base case. intro x y h h_base obtain rfl | rfl : x = 0 ∨ x = 1 := by rwa [Nat.le_add_one_iff, Nat.le_zero] at h_base · simp at h · rw [mul_one, one_mul, add_right_comm] at h have y_dvd : y ∣ y * k := dvd_mul_right y k rw [← h, Nat.dvd_add_left (dvd_mul_left y y)] at y_dvd obtain rfl | rfl := (Nat.dvd_prime Nat.prime_two).mp y_dvd <;> apply mul_left_cancel₀ exacts [one_ne_zero, h.symm, two_ne_zero, h.symm]
Finite.lean
/- Copyright (c) 2025 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.CategoryTheory.Subpresheaf.OfSection /-! # Subpresheaves that are generated by finitely many sections Given `F : Cᵒᵖ ⥤ Type w`, `G : Subpresheaf F`, objects `X : ι → Cᵒᵖ` and sections `x : (i : ι) → F.obj (X i)`, we define a predicate `G.IsGeneratedBy x` saying that `G` is the subpresheaf generated by the sections `x i`. If this holds for a finite index type `ι`, we say that `G` is "finite", and this gives a type class `G.IsFinite`. -/ universe w'' w' w v u namespace CategoryTheory open Opposite variable {C : Type u} [Category.{v} C] {F : Cᵒᵖ ⥤ Type w} namespace Subpresheaf variable (G : Subpresheaf F) section variable {ι : Type w'} {X : ι → Cᵒᵖ} (x : (i : ι) → F.obj (X i)) /-- A subpresheaf `G : Subpresheaf F` is generated by sections `x i : F.obj (X i)` if `⨆ (i : ι), ofSection (x i) = G`. -/ def IsGeneratedBy : Prop := ⨆ (i : ι), ofSection (x i) = G lemma isGeneratedBy_iff : G.IsGeneratedBy x ↔ ⨆ (i : ι), ofSection (x i) = G := Iff.rfl namespace IsGeneratedBy variable {G x} (h : G.IsGeneratedBy x) include h lemma iSup_eq : ⨆ (i : ι), ofSection (x i) = G := h lemma ofSection_le (i : ι) : ofSection (x i) ≤ G := by rw [← h.iSup_eq] exact le_iSup (fun i ↦ ofSection (x i)) i lemma mem (i : ι) : x i ∈ G.obj (X i) := by rw [← ofSection_le_iff] exact h.ofSection_le i lemma of_equiv {ι' : Type w''} (e : ι' ≃ ι) : G.IsGeneratedBy (fun i' ↦ x (e i')) := by rw [isGeneratedBy_iff, ← h.iSup_eq] apply le_antisymm · simp only [iSup_le_iff] intro i' exact le_iSup (fun i ↦ ofSection (x i)) (e i') · simp only [iSup_le_iff] intro i' convert (le_iSup (fun i' ↦ ofSection (x (e i'))) (e.symm i')) <;> simp lemma image {F' : Cᵒᵖ ⥤ Type w} (f : F ⟶ F') : (G.image f).IsGeneratedBy (fun i ↦ f.app _ (x i)) := by simp only [isGeneratedBy_iff, ← h.iSup_eq, image_iSup, ofSection_image] end IsGeneratedBy end /-- A subpresheaf of types is "finite" if it is generated by finitely many sections. -/ class IsFinite : Prop where exists_isGeneratedBy : ∃ (ι : Type) (_ : Finite ι) (X : ι → Cᵒᵖ) (x : (i : ι) → F.obj (X i)), Nonempty (G.IsGeneratedBy x) namespace IsFinite variable [hG : G.IsFinite] /-- A choice of index type for the generating sections of a finitely generated subpresheaf. -/ def Index : Type := hG.exists_isGeneratedBy.choose instance : Finite (Index G) := hG.exists_isGeneratedBy.choose_spec.choose variable {G} /-- Objects on which a choice of generating sections of a finitely generated subpresheaf are defined. -/ noncomputable def X : Index G → Cᵒᵖ := hG.exists_isGeneratedBy.choose_spec.choose_spec.choose /-- A choice of generating sections of a finitely generated subpresheaf. -/ noncomputable def x : (i : Index G) → F.obj (X i) := hG.exists_isGeneratedBy.choose_spec.choose_spec.choose_spec.choose end IsFinite lemma isGeneratedBy_of_isFinite [hG : G.IsFinite] : G.IsGeneratedBy (IsFinite.x (G := G)) := hG.exists_isGeneratedBy.choose_spec.choose_spec.choose_spec.choose_spec.some lemma IsGeneratedBy.isFinite {ι : Type w'} [Finite ι] {X : ι → Cᵒᵖ} {x : (i : ι) → F.obj (X i)} (h : G.IsGeneratedBy x) : G.IsFinite := by obtain ⟨n, ⟨e⟩⟩ := Finite.exists_equiv_fin ι exact ⟨Fin n, inferInstance, _, _, ⟨h.of_equiv e.symm⟩⟩ lemma image_isFinite [G.IsFinite] {F' : Cᵒᵖ ⥤ Type w} (f : F ⟶ F') : (G.image f).IsFinite := ((isGeneratedBy_of_isFinite G).image f).isFinite end Subpresheaf variable (F) section variable {ι : Type w'} {X : ι → Cᵒᵖ} (x : (i : ι) → F.obj (X i)) /-- The condition that a presheaf of types `F : Cᵒᵖ ⥤ Type w` is generated by a family of sections. -/ abbrev PresheafIsGeneratedBy : Prop := (⊤ : Subpresheaf F).IsGeneratedBy x namespace PresheafIsGeneratedBy variable {F x} (h : PresheafIsGeneratedBy F x) {F' : Cᵒᵖ ⥤ Type w} (f : F ⟶ F') include h lemma range : (Subpresheaf.range f).IsGeneratedBy (fun i ↦ f.app _ (x i)) := by simpa only [← Subpresheaf.image_top] using h.image f lemma of_epi [Epi f] : PresheafIsGeneratedBy F' (fun i ↦ f.app _ (x i)) := by simpa only [Subpresheaf.range_eq_top f] using h.range f end PresheafIsGeneratedBy end /-- A presheaf is "finite" if it is generated by finitely many sections. -/ abbrev PresheafIsFinite : Prop := (⊤ : Subpresheaf F).IsFinite lemma presheafIsGeneratedBy_of_isFinite [PresheafIsFinite F] : PresheafIsGeneratedBy F (Subpresheaf.IsFinite.x (G := ⊤)) := (Subpresheaf.isGeneratedBy_of_isFinite (⊤ : Subpresheaf F)) lemma Subpresheaf.range_isFinite [PresheafIsFinite F] {F' : Cᵒᵖ ⥤ Type w} (f : F ⟶ F') : (Subpresheaf.range f).IsFinite := ((presheafIsGeneratedBy_of_isFinite F).range f).isFinite lemma presheafIsFinite_of_epi [PresheafIsFinite F] {F' : Cᵒᵖ ⥤ Type w} (f : F ⟶ F') [Epi f] : PresheafIsFinite F' := ((presheafIsGeneratedBy_of_isFinite F).of_epi f).isFinite lemma yoneda_obj_isGeneratedBy (X : C) : PresheafIsGeneratedBy (yoneda.obj X) (fun (_ : Unit) ↦ 𝟙 X) := by simp only [Subpresheaf.isGeneratedBy_iff] ext U u simp only [yoneda_obj_obj, Subpresheaf.iSup_obj, Set.mem_iUnion, exists_const, Subpresheaf.top_obj, Set.top_eq_univ, Set.mem_univ, iff_true] exact ⟨u.op, by simp⟩ instance (X : C) : PresheafIsFinite (yoneda.obj X) := (yoneda_obj_isGeneratedBy X).isFinite end CategoryTheory
Sort.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.Data.List.Pairwise import Batteries.Data.List.Perm import Mathlib.Data.List.OfFn import Mathlib.Data.List.Nodup import Mathlib.Data.List.TakeWhile import Mathlib.Order.Fin.Basic /-! # Sorting algorithms on lists In this file we define `List.Sorted r l` to be an alias for `List.Pairwise r l`. This alias is preferred in the case that `r` is a `<` or `≤`-like relation. Then we define the sorting algorithm `List.insertionSort` and prove its correctness. -/ open List.Perm universe u v namespace List /-! ### The predicate `List.Sorted` -/ section Sorted variable {α : Type u} {r : α → α → Prop} {a : α} {l : List α} /-- `Sorted r l` is the same as `List.Pairwise r l`, preferred in the case that `r` is a `<` or `≤`-like relation (transitive and antisymmetric or asymmetric) -/ def Sorted := @Pairwise instance decidableSorted [DecidableRel r] (l : List α) : Decidable (Sorted r l) := List.instDecidablePairwise _ protected theorem Sorted.le_of_lt [Preorder α] {l : List α} (h : l.Sorted (· < ·)) : l.Sorted (· ≤ ·) := h.imp le_of_lt protected theorem Sorted.lt_of_le [PartialOrder α] {l : List α} (h₁ : l.Sorted (· ≤ ·)) (h₂ : l.Nodup) : l.Sorted (· < ·) := h₁.imp₂ (fun _ _ => lt_of_le_of_ne) h₂ protected theorem Sorted.ge_of_gt [Preorder α] {l : List α} (h : l.Sorted (· > ·)) : l.Sorted (· ≥ ·) := h.imp le_of_lt protected theorem Sorted.gt_of_ge [PartialOrder α] {l : List α} (h₁ : l.Sorted (· ≥ ·)) (h₂ : l.Nodup) : l.Sorted (· > ·) := h₁.imp₂ (fun _ _ => lt_of_le_of_ne) <| by simp_rw [ne_comm]; exact h₂ @[simp] theorem sorted_nil : Sorted r [] := Pairwise.nil theorem Sorted.of_cons : Sorted r (a :: l) → Sorted r l := Pairwise.of_cons theorem Sorted.tail {r : α → α → Prop} {l : List α} (h : Sorted r l) : Sorted r l.tail := Pairwise.tail h theorem rel_of_sorted_cons {a : α} {l : List α} : Sorted r (a :: l) → ∀ b ∈ l, r a b := rel_of_pairwise_cons nonrec theorem Sorted.cons {r : α → α → Prop} [IsTrans α r] {l : List α} {a b : α} (hab : r a b) (h : Sorted r (b :: l)) : Sorted r (a :: b :: l) := h.cons <| forall_mem_cons.2 ⟨hab, fun _ hx => _root_.trans hab <| rel_of_sorted_cons h _ hx⟩ theorem sorted_cons_cons {r : α → α → Prop} [IsTrans α r] {l : List α} {a b : α} : Sorted r (b :: a :: l) ↔ r b a ∧ Sorted r (a :: l) := by constructor · intro h exact ⟨rel_of_sorted_cons h _ mem_cons_self, h.of_cons⟩ · rintro ⟨h, ha⟩ exact ha.cons h theorem Sorted.head!_le [Inhabited α] [Preorder α] {a : α} {l : List α} (h : Sorted (· < ·) l) (ha : a ∈ l) : l.head! ≤ a := by rw [← List.cons_head!_tail (List.ne_nil_of_mem ha)] at h ha cases ha · exact le_rfl · exact le_of_lt (rel_of_sorted_cons h a (by assumption)) theorem Sorted.le_head! [Inhabited α] [Preorder α] {a : α} {l : List α} (h : Sorted (· > ·) l) (ha : a ∈ l) : a ≤ l.head! := by rw [← List.cons_head!_tail (List.ne_nil_of_mem ha)] at h ha cases ha · exact le_rfl · exact le_of_lt (rel_of_sorted_cons h a (by assumption)) @[simp] theorem sorted_cons {a : α} {l : List α} : Sorted r (a :: l) ↔ (∀ b ∈ l, r a b) ∧ Sorted r l := pairwise_cons protected theorem Sorted.nodup {r : α → α → Prop} [IsIrrefl α r] {l : List α} (h : Sorted r l) : Nodup l := Pairwise.nodup h protected theorem Sorted.filter {l : List α} (f : α → Bool) (h : Sorted r l) : Sorted r (filter f l) := h.sublist filter_sublist theorem eq_of_perm_of_sorted [IsAntisymm α r] {l₁ l₂ : List α} (hp : l₁ ~ l₂) (hs₁ : Sorted r l₁) (hs₂ : Sorted r l₂) : l₁ = l₂ := by induction hs₁ generalizing l₂ with | nil => exact hp.nil_eq | @cons a l₁ h₁ hs₁ IH => have : a ∈ l₂ := hp.subset mem_cons_self rcases append_of_mem this with ⟨u₂, v₂, rfl⟩ have hp' := (perm_cons a).1 (hp.trans perm_middle) obtain rfl := IH hp' (hs₂.sublist <| by simp) change a :: u₂ ++ v₂ = u₂ ++ ([a] ++ v₂) rw [← append_assoc] congr have : ∀ x ∈ u₂, x = a := fun x m => antisymm ((pairwise_append.1 hs₂).2.2 _ m a mem_cons_self) (h₁ _ (by simp [m])) rw [(@eq_replicate_iff _ a (length u₂ + 1) (a :: u₂)).2, (@eq_replicate_iff _ a (length u₂ + 1) (u₂ ++ [a])).2] <;> constructor <;> simp [iff_true_intro this, or_comm] theorem Sorted.eq_of_mem_iff [IsAntisymm α r] [IsIrrefl α r] {l₁ l₂ : List α} (h₁ : Sorted r l₁) (h₂ : Sorted r l₂) (h : ∀ a : α, a ∈ l₁ ↔ a ∈ l₂) : l₁ = l₂ := eq_of_perm_of_sorted ((perm_ext_iff_of_nodup h₁.nodup h₂.nodup).2 h) h₁ h₂ theorem sublist_of_subperm_of_sorted [IsAntisymm α r] {l₁ l₂ : List α} (hp : l₁ <+~ l₂) (hs₁ : l₁.Sorted r) (hs₂ : l₂.Sorted r) : l₁ <+ l₂ := by let ⟨_, h, h'⟩ := hp rwa [← eq_of_perm_of_sorted h (hs₂.sublist h') hs₁] @[simp 1100] -- Higher priority shortcut lemma. theorem sorted_singleton (a : α) : Sorted r [a] := by simp theorem sorted_lt_range (n : ℕ) : Sorted (· < ·) (range n) := by rw [Sorted, pairwise_iff_get] simp theorem sorted_replicate (n : ℕ) (a : α) : Sorted r (replicate n a) ↔ n ≤ 1 ∨ r a a := pairwise_replicate theorem sorted_le_replicate (n : ℕ) (a : α) [Preorder α] : Sorted (· ≤ ·) (replicate n a) := by simp [sorted_replicate] theorem sorted_le_range (n : ℕ) : Sorted (· ≤ ·) (range n) := (sorted_lt_range n).le_of_lt lemma sorted_lt_range' (a b) {s} (hs : s ≠ 0) : Sorted (· < ·) (range' a b s) := by induction b generalizing a with | zero => simp | succ n ih => rw [List.range'_succ] refine List.sorted_cons.mpr ⟨fun b hb ↦ ?_, @ih (a + s)⟩ exact lt_of_lt_of_le (Nat.lt_add_of_pos_right (Nat.zero_lt_of_ne_zero hs)) (List.left_le_of_mem_range' hb) lemma sorted_le_range' (a b s) : Sorted (· ≤ ·) (range' a b s) := by by_cases hs : s ≠ 0 · exact (sorted_lt_range' a b hs).le_of_lt · rw [ne_eq, Decidable.not_not] at hs simpa [hs] using sorted_le_replicate b a theorem Sorted.rel_get_of_lt {l : List α} (h : l.Sorted r) {a b : Fin l.length} (hab : a < b) : r (l.get a) (l.get b) := List.pairwise_iff_get.1 h _ _ hab theorem Sorted.rel_get_of_le [IsRefl α r] {l : List α} (h : l.Sorted r) {a b : Fin l.length} (hab : a ≤ b) : r (l.get a) (l.get b) := by obtain rfl | hlt := Fin.eq_or_lt_of_le hab; exacts [refl _, h.rel_get_of_lt hlt] theorem Sorted.rel_of_mem_take_of_mem_drop {l : List α} (h : List.Sorted r l) {k : ℕ} {x y : α} (hx : x ∈ List.take k l) (hy : y ∈ List.drop k l) : r x y := by obtain ⟨iy, hiy, rfl⟩ := getElem_of_mem hy obtain ⟨ix, hix, rfl⟩ := getElem_of_mem hx rw [getElem_take, getElem_drop] rw [length_take] at hix exact h.rel_get_of_lt (Nat.lt_add_right _ (Nat.lt_min.mp hix).left) /-- If a list is sorted with respect to a decidable relation, then it is sorted with respect to the corresponding Bool-valued relation. -/ theorem Sorted.decide [DecidableRel r] (l : List α) (h : Sorted r l) : Sorted (fun a b => decide (r a b) = true) l := by refine h.imp fun {a b} h => by simpa using h end Sorted section Monotone variable {n : ℕ} {α : Type u} {f : Fin n → α} open scoped Relator in theorem sorted_ofFn_iff {r : α → α → Prop} : (ofFn f).Sorted r ↔ ((· < ·) ⇒ r) f f := by simp_rw [Sorted, pairwise_iff_get, get_ofFn, Relator.LiftFun] exact Iff.symm (Fin.rightInverse_cast _).surjective.forall₂ variable [Preorder α] /-- The list `List.ofFn f` is strictly sorted with respect to `(· ≤ ·)` if and only if `f` is strictly monotone. -/ @[simp] theorem sorted_lt_ofFn_iff : (ofFn f).Sorted (· < ·) ↔ StrictMono f := sorted_ofFn_iff /-- The list `List.ofFn f` is strictly sorted with respect to `(· ≥ ·)` if and only if `f` is strictly antitone. -/ @[simp] theorem sorted_gt_ofFn_iff : (ofFn f).Sorted (· > ·) ↔ StrictAnti f := sorted_ofFn_iff /-- The list `List.ofFn f` is sorted with respect to `(· ≤ ·)` if and only if `f` is monotone. -/ @[simp] theorem sorted_le_ofFn_iff : (ofFn f).Sorted (· ≤ ·) ↔ Monotone f := sorted_ofFn_iff.trans monotone_iff_forall_lt.symm /-- The list obtained from a monotone tuple is sorted. -/ alias ⟨_, _root_.Monotone.ofFn_sorted⟩ := sorted_le_ofFn_iff /-- The list `List.ofFn f` is sorted with respect to `(· ≥ ·)` if and only if `f` is antitone. -/ @[simp] theorem sorted_ge_ofFn_iff : (ofFn f).Sorted (· ≥ ·) ↔ Antitone f := sorted_ofFn_iff.trans antitone_iff_forall_lt.symm /-- The list obtained from an antitone tuple is sorted. -/ alias ⟨_, _root_.Antitone.ofFn_sorted⟩ := sorted_ge_ofFn_iff end Monotone lemma Sorted.filterMap {α β : Type*} {p : α → Option β} {l : List α} {r : α → α → Prop} {r' : β → β → Prop} (hl : l.Sorted r) (hp : ∀ (a b : α) (c d : β), p a = some c → p b = some d → r a b → r' c d) : (l.filterMap p).Sorted r' := by induction l with | nil => simp | cons a l ih => rw [List.filterMap_cons] cases ha : p a with | none => exact ih (List.sorted_cons.mp hl).right | some b => rw [List.sorted_cons] refine ⟨fun x hx ↦ ?_, ih (List.sorted_cons.mp hl).right⟩ obtain ⟨u, hu, hu'⟩ := List.mem_filterMap.mp hx exact hp a u b x ha hu' <| (List.sorted_cons.mp hl).left u hu end List open List namespace RelEmbedding variable {α β : Type*} {ra : α → α → Prop} {rb : β → β → Prop} @[simp] theorem sorted_listMap (e : ra ↪r rb) {l : List α} : (l.map e).Sorted rb ↔ l.Sorted ra := by simp [Sorted, pairwise_map, e.map_rel_iff] @[simp] theorem sorted_swap_listMap (e : ra ↪r rb) {l : List α} : (l.map e).Sorted (Function.swap rb) ↔ l.Sorted (Function.swap ra) := by simp [Sorted, pairwise_map, e.map_rel_iff] end RelEmbedding namespace OrderEmbedding variable {α β : Type*} [Preorder α] [Preorder β] @[simp] theorem sorted_lt_listMap (e : α ↪o β) {l : List α} : (l.map e).Sorted (· < ·) ↔ l.Sorted (· < ·) := e.ltEmbedding.sorted_listMap @[simp] theorem sorted_gt_listMap (e : α ↪o β) {l : List α} : (l.map e).Sorted (· > ·) ↔ l.Sorted (· > ·) := e.ltEmbedding.sorted_swap_listMap end OrderEmbedding namespace RelIso variable {α β : Type*} {ra : α → α → Prop} {rb : β → β → Prop} @[simp] theorem sorted_listMap (e : ra ≃r rb) {l : List α} : (l.map e).Sorted rb ↔ l.Sorted ra := e.toRelEmbedding.sorted_listMap @[simp] theorem sorted_swap_listMap (e : ra ≃r rb) {l : List α} : (l.map e).Sorted (Function.swap rb) ↔ l.Sorted (Function.swap ra) := e.toRelEmbedding.sorted_swap_listMap end RelIso namespace OrderIso variable {α β : Type*} [Preorder α] [Preorder β] @[simp] theorem sorted_lt_listMap (e : α ≃o β) {l : List α} : (l.map e).Sorted (· < ·) ↔ l.Sorted (· < ·) := e.toOrderEmbedding.sorted_lt_listMap @[simp] theorem sorted_gt_listMap (e : α ≃o β) {l : List α} : (l.map e).Sorted (· > ·) ↔ l.Sorted (· > ·) := e.toOrderEmbedding.sorted_gt_listMap end OrderIso namespace StrictMono variable {α β : Type*} [LinearOrder α] [Preorder β] {f : α → β} {l : List α} theorem sorted_le_listMap (hf : StrictMono f) : (l.map f).Sorted (· ≤ ·) ↔ l.Sorted (· ≤ ·) := (OrderEmbedding.ofStrictMono f hf).sorted_listMap theorem sorted_ge_listMap (hf : StrictMono f) : (l.map f).Sorted (· ≥ ·) ↔ l.Sorted (· ≥ ·) := (OrderEmbedding.ofStrictMono f hf).sorted_swap_listMap theorem sorted_lt_listMap (hf : StrictMono f) : (l.map f).Sorted (· < ·) ↔ l.Sorted (· < ·) := (OrderEmbedding.ofStrictMono f hf).sorted_lt_listMap theorem sorted_gt_listMap (hf : StrictMono f) : (l.map f).Sorted (· > ·) ↔ l.Sorted (· > ·) := (OrderEmbedding.ofStrictMono f hf).sorted_gt_listMap end StrictMono namespace StrictAnti variable {α β : Type*} [LinearOrder α] [Preorder β] {f : α → β} {l : List α} theorem sorted_le_listMap (hf : StrictAnti f) : (l.map f).Sorted (· ≤ ·) ↔ l.Sorted (· ≥ ·) := hf.dual_right.sorted_ge_listMap theorem sorted_ge_listMap (hf : StrictAnti f) : (l.map f).Sorted (· ≥ ·) ↔ l.Sorted (· ≤ ·) := hf.dual_right.sorted_le_listMap theorem sorted_lt_listMap (hf : StrictAnti f) : (l.map f).Sorted (· < ·) ↔ l.Sorted (· > ·) := hf.dual_right.sorted_gt_listMap theorem sorted_gt_listMap (hf : StrictAnti f) : (l.map f).Sorted (· > ·) ↔ l.Sorted (· < ·) := hf.dual_right.sorted_lt_listMap end StrictAnti namespace List section sort variable {α : Type u} {β : Type v} (r : α → α → Prop) (s : β → β → Prop) variable [DecidableRel r] [DecidableRel s] local infixl:50 " ≼ " => r local infixl:50 " ≼ " => s /-! ### Insertion sort -/ section InsertionSort /-- `orderedInsert a l` inserts `a` into `l` at such that `orderedInsert a l` is sorted if `l` is. -/ @[simp] def orderedInsert (a : α) : List α → List α | [] => [a] | b :: l => if a ≼ b then a :: b :: l else b :: orderedInsert a l theorem orderedInsert_of_le {a b : α} (l : List α) (h : a ≼ b) : orderedInsert r a (b :: l) = a :: b :: l := dif_pos h /-- `insertionSort l` returns `l` sorted using the insertion sort algorithm. -/ @[simp] def insertionSort : List α → List α | [] => [] | b :: l => orderedInsert r b (insertionSort l) -- A quick check that insertionSort is stable: example : insertionSort (fun m n => m / 10 ≤ n / 10) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] = [5, 7, 2, 17, 12, 27, 23, 43, 95, 98, 221, 567] := rfl @[simp] theorem orderedInsert_nil (a : α) : [].orderedInsert r a = [a] := rfl theorem orderedInsert_length : ∀ (L : List α) (a : α), (L.orderedInsert r a).length = L.length + 1 | [], _ => rfl | hd :: tl, a => by dsimp [orderedInsert] split_ifs <;> simp [orderedInsert_length tl] /-- An alternative definition of `orderedInsert` using `takeWhile` and `dropWhile`. -/ theorem orderedInsert_eq_take_drop (a : α) : ∀ l : List α, l.orderedInsert r a = (l.takeWhile fun b => ¬a ≼ b) ++ a :: l.dropWhile fun b => ¬a ≼ b | [] => rfl | b :: l => by dsimp only [orderedInsert] split_ifs with h <;> simp [takeWhile, dropWhile, *, orderedInsert_eq_take_drop a l] theorem insertionSort_cons_eq_take_drop (a : α) (l : List α) : insertionSort r (a :: l) = ((insertionSort r l).takeWhile fun b => ¬a ≼ b) ++ a :: (insertionSort r l).dropWhile fun b => ¬a ≼ b := orderedInsert_eq_take_drop r a _ @[simp] theorem mem_orderedInsert {a b : α} {l : List α} : a ∈ orderedInsert r b l ↔ a = b ∨ a ∈ l := match l with | [] => by simp [orderedInsert] | x :: xs => by rw [orderedInsert] split_ifs · simp · rw [mem_cons, mem_cons, mem_orderedInsert, or_left_comm] theorem map_orderedInsert (f : α → β) (l : List α) (x : α) (hl₁ : ∀ a ∈ l, a ≼ x ↔ f a ≼ f x) (hl₂ : ∀ a ∈ l, x ≼ a ↔ f x ≼ f a) : (l.orderedInsert r x).map f = (l.map f).orderedInsert s (f x) := by induction l with | nil => simp | cons x xs ih => rw [List.forall_mem_cons] at hl₁ hl₂ simp only [List.map, List.orderedInsert, ← hl₂.1] split_ifs · rw [List.map, List.map] · rw [List.map, ih (fun _ ha => hl₁.2 _ ha) (fun _ ha => hl₂.2 _ ha)] section Correctness theorem perm_orderedInsert (a) : ∀ l : List α, orderedInsert r a l ~ a :: l | [] => Perm.refl _ | b :: l => by by_cases h : a ≼ b · simp [orderedInsert, h] · simpa [orderedInsert, h] using ((perm_orderedInsert a l).cons _).trans (Perm.swap _ _ _) theorem orderedInsert_count [DecidableEq α] (L : List α) (a b : α) : count a (L.orderedInsert r b) = count a L + if b = a then 1 else 0 := by rw [(L.perm_orderedInsert r b).count_eq, count_cons] simp theorem perm_insertionSort : ∀ l : List α, insertionSort r l ~ l | [] => Perm.nil | b :: l => by simpa [insertionSort] using (perm_orderedInsert _ _ _).trans ((perm_insertionSort l).cons b) @[simp] theorem mem_insertionSort {l : List α} {x : α} : x ∈ l.insertionSort r ↔ x ∈ l := (perm_insertionSort r l).mem_iff @[simp] theorem length_insertionSort (l : List α) : (insertionSort r l).length = l.length := (perm_insertionSort r _).length_eq theorem insertionSort_cons {a : α} {l : List α} (h : ∀ b ∈ l, r a b) : insertionSort r (a :: l) = a :: insertionSort r l := by rw [insertionSort] cases hi : insertionSort r l with | nil => rfl | cons b m => rw [orderedInsert_of_le] apply h b <| (mem_insertionSort r).1 _ rw [hi] exact mem_cons_self theorem map_insertionSort (f : α → β) (l : List α) (hl : ∀ a ∈ l, ∀ b ∈ l, a ≼ b ↔ f a ≼ f b) : (l.insertionSort r).map f = (l.map f).insertionSort s := by induction l with | nil => simp | cons x xs ih => simp_rw [List.forall_mem_cons, forall_and] at hl simp_rw [List.map, List.insertionSort] rw [List.map_orderedInsert _ s, ih hl.2.2] · simpa only [mem_insertionSort] using hl.2.1 · simpa only [mem_insertionSort] using hl.1.2 variable {r} /-- If `l` is already `List.Sorted` with respect to `r`, then `insertionSort` does not change it. -/ theorem Sorted.insertionSort_eq : ∀ {l : List α}, Sorted r l → insertionSort r l = l | [], _ => rfl | [_], _ => rfl | a :: b :: l, h => by rw [insertionSort, Sorted.insertionSort_eq, orderedInsert, if_pos] exacts [rel_of_sorted_cons h _ mem_cons_self, h.tail] /-- For a reflexive relation, insert then erasing is the identity. -/ theorem erase_orderedInsert [DecidableEq α] [IsRefl α r] (x : α) (xs : List α) : (xs.orderedInsert r x).erase x = xs := by rw [orderedInsert_eq_take_drop, erase_append_right, List.erase_cons_head, takeWhile_append_dropWhile] intro h replace h := mem_takeWhile_imp h simp [refl x] at h /-- Inserting then erasing an element that is absent is the identity. -/ theorem erase_orderedInsert_of_notMem [DecidableEq α] {x : α} {xs : List α} (hx : x ∉ xs) : (xs.orderedInsert r x).erase x = xs := by rw [orderedInsert_eq_take_drop, erase_append_right, List.erase_cons_head, takeWhile_append_dropWhile] exact mt ((takeWhile_prefix _).sublist.subset ·) hx @[deprecated (since := "2025-05-23")] alias erase_orderedInsert_of_not_mem := erase_orderedInsert_of_notMem /-- For an antisymmetric relation, erasing then inserting is the identity. -/ theorem orderedInsert_erase [DecidableEq α] [IsAntisymm α r] (x : α) (xs : List α) (hx : x ∈ xs) (hxs : Sorted r xs) : (xs.erase x).orderedInsert r x = xs := by induction xs generalizing x with | nil => cases hx | cons y ys ih => rw [sorted_cons] at hxs obtain rfl | hxy := Decidable.eq_or_ne x y · rw [erase_cons_head] cases ys with | nil => rfl | cons z zs => rw [orderedInsert, if_pos (hxs.1 _ (.head zs))] · rw [mem_cons] at hx replace hx := hx.resolve_left hxy rw [erase_cons_tail (not_beq_of_ne hxy.symm), orderedInsert, ih _ hx hxs.2, if_neg] refine mt (fun hrxy => ?_) hxy exact antisymm hrxy (hxs.1 _ hx) theorem sublist_orderedInsert (x : α) (xs : List α) : xs <+ xs.orderedInsert r x := by rw [orderedInsert_eq_take_drop] refine Sublist.trans ?_ (.append_left (.cons _ (.refl _)) _) rw [takeWhile_append_dropWhile] theorem cons_sublist_orderedInsert {l c : List α} {a : α} (hl : c <+ l) (ha : ∀ a' ∈ c, a ≼ a') : a :: c <+ orderedInsert r a l := by induction l with | nil => simp_all only [sublist_nil, orderedInsert, Sublist.refl] | cons _ _ ih => unfold orderedInsert split_ifs with hr · exact .cons₂ _ hl · cases hl with | cons _ h => exact .cons _ <| ih h | cons₂ => exact absurd (ha _ <| mem_cons_self ..) hr theorem Sublist.orderedInsert_sublist [IsTrans α r] {as bs} (x) (hs : as <+ bs) (hb : bs.Sorted r) : orderedInsert r x as <+ orderedInsert r x bs := by cases as with | nil => simp | cons a as => cases bs with | nil => contradiction | cons b bs => unfold orderedInsert cases hs <;> split_ifs with hr · exact .cons₂ _ <| .cons _ ‹a :: as <+ bs› · have ih := orderedInsert_sublist x ‹a :: as <+ bs› hb.of_cons simp only [hr, orderedInsert, ite_true] at ih exact .trans ih <| .cons _ (.refl _) · have hba := pairwise_cons.mp hb |>.left _ (mem_of_cons_sublist ‹a :: as <+ bs›) exact absurd (trans_of _ ‹r x b› hba) hr · have ih := orderedInsert_sublist x ‹a :: as <+ bs› hb.of_cons rw [orderedInsert, if_neg hr] at ih exact .cons _ ih · simp_all only [sorted_cons, cons_sublist_cons] · exact .cons₂ _ <| orderedInsert_sublist x ‹as <+ bs› hb.of_cons section TotalAndTransitive variable [IsTotal α r] [IsTrans α r] theorem Sorted.orderedInsert (a : α) : ∀ l, Sorted r l → Sorted r (orderedInsert r a l) | [], _ => sorted_singleton a | b :: l, h => by by_cases h' : a ≼ b · simpa [orderedInsert, h', h] using fun b' bm => _root_.trans h' (rel_of_sorted_cons h _ bm) · suffices ∀ b' : α, b' ∈ List.orderedInsert r a l → r b b' by simpa [orderedInsert, h', h.of_cons.orderedInsert a l] intro b' bm rcases (mem_orderedInsert r).mp bm with be | bm · subst b' exact (total_of r _ _).resolve_left h' · exact rel_of_sorted_cons h _ bm variable (r) /-- The list `List.insertionSort r l` is `List.Sorted` with respect to `r`. -/ theorem sorted_insertionSort : ∀ l, Sorted r (insertionSort r l) | [] => sorted_nil | a :: l => (sorted_insertionSort l).orderedInsert a _ end TotalAndTransitive /-- If `c` is a sorted sublist of `l`, then `c` is still a sublist of `insertionSort r l`. -/ theorem sublist_insertionSort {l c : List α} (hr : c.Pairwise r) (hc : c <+ l) : c <+ insertionSort r l := by induction l generalizing c with | nil => simp_all only [sublist_nil, insertionSort, Sublist.refl] | cons _ _ ih => cases hc with | cons _ h => exact ih hr h |>.trans (sublist_orderedInsert ..) | cons₂ _ h => obtain ⟨hr, hp⟩ := pairwise_cons.mp hr exact cons_sublist_orderedInsert (ih hp h) hr /-- Another statement of stability of insertion sort. If a pair `[a, b]` is a sublist of `l` and `r a b`, then `[a, b]` is still a sublist of `insertionSort r l`. -/ theorem pair_sublist_insertionSort {a b : α} {l : List α} (hab : r a b) (h : [a, b] <+ l) : [a, b] <+ insertionSort r l := sublist_insertionSort (pairwise_pair.mpr hab) h variable [IsAntisymm α r] [IsTotal α r] [IsTrans α r] /-- A version of `insertionSort_stable` which only assumes `c <+~ l` (instead of `c <+ l`), but additionally requires `IsAntisymm α r`, `IsTotal α r` and `IsTrans α r`. -/ theorem sublist_insertionSort' {l c : List α} (hs : c.Sorted r) (hc : c <+~ l) : c <+ insertionSort r l := by classical obtain ⟨d, hc, hd⟩ := hc induction l generalizing c d with | nil => simp_all only [sublist_nil, insertionSort, nil_perm] | cons a _ ih => cases hd with | cons _ h => exact ih hs _ hc h |>.trans (sublist_orderedInsert ..) | cons₂ _ h => specialize ih (hs.erase _) _ (erase_cons_head a ‹List _› ▸ hc.erase a) h have hm := hc.mem_iff.mp <| mem_cons_self .. have he := orderedInsert_erase _ _ hm hs exact he ▸ Sublist.orderedInsert_sublist _ ih (sorted_insertionSort ..) /-- Another statement of stability of insertion sort. If a pair `[a, b]` is a sublist of a permutation of `l` and `a ≼ b`, then `[a, b]` is still a sublist of `insertionSort r l`. -/ theorem pair_sublist_insertionSort' {a b : α} {l : List α} (hab : a ≼ b) (h : [a, b] <+~ l) : [a, b] <+ insertionSort r l := sublist_insertionSort' (pairwise_pair.mpr hab) h end Correctness end InsertionSort /-! ### Merge sort We provide some wrapper functions around the theorems for `mergeSort` provided in Lean, which rather than using explicit hypotheses for transitivity and totality, use Mathlib order typeclasses instead. -/ example : mergeSort [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] (fun m n => m / 10 ≤ n / 10) = [5, 7, 2, 17, 12, 27, 23, 43, 95, 98, 221, 567] := by simp [mergeSort] section MergeSort section Correctness section TotalAndTransitive variable {r} [IsTotal α r] [IsTrans α r] theorem Sorted.merge {l l' : List α} (h : Sorted r l) (h' : Sorted r l') : Sorted r (merge l l' (r · ·)) := by simpa using sorted_merge (le := (r · ·)) (fun a b c h₁ h₂ => by simpa using _root_.trans (by simpa using h₁) (by simpa using h₂)) (fun a b => by simpa using IsTotal.total a b) l l' (by simpa using h) (by simpa using h') variable (r) /-- Variant of `sorted_mergeSort` using relation typeclasses. -/ theorem sorted_mergeSort' (l : List α) : Sorted r (mergeSort l (r · ·)) := by simpa using sorted_mergeSort (le := (r · ·)) (fun _ _ _ => by simpa using trans_of r) (by simpa using total_of r) l variable [IsAntisymm α r] theorem mergeSort_eq_self {l : List α} : Sorted r l → mergeSort l (r · ·) = l := eq_of_perm_of_sorted (mergeSort_perm _ _) (sorted_mergeSort' _ l) theorem mergeSort_eq_insertionSort (l : List α) : mergeSort l (r · ·) = insertionSort r l := eq_of_perm_of_sorted ((mergeSort_perm l _).trans (perm_insertionSort r l).symm) (sorted_mergeSort' r l) (sorted_insertionSort r l) end TotalAndTransitive end Correctness end MergeSort end sort end List
jordanholder.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 bigop finset fingroup morphism. From mathcomp Require Import automorphism quotient action gseries. (******************************************************************************) (* This files establishes Jordan-Holder theorems for finite groups. These *) (* theorems state the uniqueness up to permutation and isomorphism for the *) (* series of quotient built from the successive elements of any composition *) (* series of the same group. These quotients are also called factors of the *) (* composition series. To avoid the heavy use of highly polymorphic lists *) (* describing these quotient series, we introduce sections. *) (* This library defines: *) (* (G1 / G2)%sec == alias for the pair (G1, G2) of groups in the same *) (* finGroupType, coerced to the actual quotient group*) (* group G1 / G2. We call this pseudo-quotient a *) (* section of G1 and G2. *) (* section_isog s1 s2 == s1 and s2 respectively coerce to isomorphic *) (* quotient groups. *) (* section_repr s == canonical representative of the isomorphism class *) (* of the section s. *) (* mksrepr G1 G2 == canonical representative of the isomorphism class *) (* of (G1 / G2)%sec. *) (* mkfactors G s == if s is [:: s1, s2, ..., sn], constructs the list *) (* [:: mksrepr G s1, mksrepr s1 s2, ..., mksrepr sn-1 sn] *) (* comps G s == s is a composition series for G i.e. s is a *) (* decreasing sequence of subgroups of G *) (* in which two adjacent elements are maxnormal one *) (* in the other and the last element of s is 1. *) (* Given aT and rT two finGroupTypes, (D : {group rT}), (A : {group aT}) and *) (* (to : groupAction A D) an external action. *) (* maxainv to B C == C is a maximal proper normal subgroup of B *) (* invariant by (the external action of A via) to. *) (* asimple to B == the maximal proper normal subgroup of B invariant *) (* by the external action to is trivial. *) (* acomps to G s == s is a composition series for G invariant by to, *) (* i.e. s is a decreasing sequence of subgroups of G *) (* in which two adjacent elements are maximally *) (* invariant by to one in the other and the *) (* last element of s is 1. *) (* We prove two versions of the result: *) (* - JordanHolderUniqueness establishes the uniqueness up to permutation *) (* and isomorphism of the lists of factors in composition series of a *) (* given group. *) (* - StrongJordanHolderUniqueness extends the result to composition series *) (* invariant by an external group action. *) (* See also "The Rooster and the Butterflies", proceedings of Calculemus 2013,*) (* by Assia Mahboubi. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope section_scope. Import GroupScope. Inductive section (gT : finGroupType) := GSection of {group gT} * {group gT}. Delimit Scope section_scope with sec. Bind Scope section_scope with section. Definition mkSec (gT : finGroupType) (G1 G2 : {group gT}) := GSection (G1, G2). Infix "/" := mkSec : section_scope. Coercion pair_of_section gT (s : section gT) := let: GSection u := s in u. Coercion quotient_of_section gT (s : section gT) : GroupSet.sort _ := s.1 / s.2. Coercion section_group gT (s : section gT) : {group (coset_of s.2)} := Eval hnf in [group of s]. Section Sections. Variables (gT : finGroupType). Implicit Types (G : {group gT}) (s : section gT). HB.instance Definition _ := [isNew for (@pair_of_section gT)]. HB.instance Definition _ := [Finite of section gT by <:]. Canonical section_group. (* Isomorphic sections *) Definition section_isog := [rel x y : section gT | x \isog y]. (* A witness of the isomorphism class of a section *) Definition section_repr s := odflt (1 / 1)%sec (pick (section_isog ^~ s)). Definition mksrepr G1 G2 := section_repr (mkSec G1 G2). Lemma section_reprP s : section_repr s \isog s. Proof. by rewrite /section_repr; case: pickP => //= /(_ s); rewrite isog_refl. Qed. Lemma section_repr_isog s1 s2 : s1 \isog s2 -> section_repr s1 = section_repr s2. Proof. by move=> iso12; congr (odflt _ _); apply: eq_pick => s; apply: isog_transr. Qed. Definition mkfactors (G : {group gT}) (s : seq {group gT}) := map section_repr (pairmap (@mkSec _) G s). End Sections. Section CompositionSeries. Variable gT : finGroupType. Local Notation gTg := {group gT}. Implicit Types (G : gTg) (s : seq gTg). Local Notation compo := [rel x y : {set gT} | maxnormal y x x]. Definition comps G s := ((last G s) == 1%G) && compo.-series G s. Lemma compsP G s : reflect (last G s = 1%G /\ path [rel x y : gTg | maxnormal y x x] G s) (comps G s). Proof. by apply: (iffP andP) => [] [/eqP]. Qed. Lemma trivg_comps G s : comps G s -> (G :==: 1) = (s == [::]). Proof. case/andP=> ls cs; apply/eqP/eqP=> [G1 | s1]; last first. by rewrite s1 /= in ls; apply/eqP. by case: s {ls} cs => //= H s /andP[/maxgroupp]; rewrite G1 /proper sub1G andbF. Qed. Lemma comps_cons G H s : comps G (H :: s) -> comps H s. Proof. by case/andP => /= ls /andP[_]; rewrite /comps ls. Qed. Lemma simple_compsP G s : comps G s -> reflect (s = [:: 1%G]) (simple G). Proof. move=> cs; apply: (iffP idP) => [|s1]; last first. by rewrite s1 /comps eqxx /= andbT -simple_maxnormal in cs. case: s cs => [/trivg_comps/eqP-> | H s]; first by case/simpleP; rewrite eqxx. rewrite [comps _ _]andbCA /= => /andP[/maxgroupp maxH /trivg_comps/esym nil_s]. rewrite simple_maxnormal => /maxgroupP[_ simG]. have H1: H = 1%G by apply/val_inj/simG; rewrite // sub1G. by move: nil_s; rewrite H1 eqxx => /eqP->. Qed. Lemma exists_comps (G : gTg) : exists s, comps G s. Proof. elim: {G} #|G| {1 3}G (leqnn #|G|) => [G | n IHn G cG]. by rewrite leqNgt cardG_gt0. have [sG | nsG] := boolP (simple G). by exists [:: 1%G]; rewrite /comps eqxx /= -simple_maxnormal andbT. have [-> | ntG] := eqVneq G 1%G; first by exists [::]; rewrite /comps eqxx. have [N maxN] := ex_maxnormal_ntrivg ntG. have [|s /andP[ls cs]] := IHn N. by rewrite -ltnS (leq_trans _ cG) // proper_card // (maxnormal_proper maxN). by exists (N :: s); apply/and3P. Qed. (******************************************************************************) (* The factors associated to two composition series of the same group are *) (* the same up to isomorphism and permutation *) (******************************************************************************) Lemma JordanHolderUniqueness (G : gTg) (s1 s2 : seq gTg) : comps G s1 -> comps G s2 -> perm_eq (mkfactors G s1) (mkfactors G s2). Proof. have [n] := ubnP #|G|; elim: n G => // n Hi G in s1 s2 * => /ltnSE-cG cs1 cs2. have [G1 | ntG] := boolP (G :==: 1). have -> : s1 = [::] by apply/eqP; rewrite -(trivg_comps cs1). have -> : s2 = [::] by apply/eqP; rewrite -(trivg_comps cs2). by rewrite /= perm_refl. have [sG | nsG] := boolP (simple G). by rewrite (simple_compsP cs1 sG) (simple_compsP cs2 sG) perm_refl. case es1: s1 cs1 => [|N1 st1] cs1. by move: (trivg_comps cs1); rewrite eqxx; move/negP:ntG. case es2: s2 cs2 => [|N2 st2] cs2 {s1 es1}. by move: (trivg_comps cs2); rewrite eqxx; move/negP:ntG. case/andP: cs1 => /= lst1; case/andP=> maxN_1 pst1. case/andP: cs2 => /= lst2; case/andP=> maxN_2 pst2. have cN1 : #|N1| < n. by rewrite (leq_trans _ cG) ?proper_card ?(maxnormal_proper maxN_1). have cN2 : #|N2| < n. by rewrite (leq_trans _ cG) ?proper_card ?(maxnormal_proper maxN_2). case: (N1 =P N2) {s2 es2} => [eN12 |]. by rewrite eN12 /= perm_cons Hi // /comps ?lst2 //= -eN12 lst1. move/eqP; rewrite -val_eqE /=; move/eqP=> neN12. have nN1G : N1 <| G by apply: maxnormal_normal. have nN2G : N2 <| G by apply: maxnormal_normal. pose N := (N1 :&: N2)%G. have nNG : N <| G. by rewrite /normal subIset ?(normal_sub nN1G) //= normsI ?normal_norm. have iso1 : (G / N1)%G \isog (N2 / N)%G. rewrite isog_sym /= -(maxnormalM maxN_1 maxN_2) //. rewrite (@normC _ N1 N2) ?(subset_trans (normal_sub nN1G)) ?normal_norm //. by rewrite weak_second_isog ?(subset_trans (normal_sub nN2G)) ?normal_norm. have iso2 : (G / N2)%G \isog (N1 / N)%G. rewrite isog_sym /= -(maxnormalM maxN_1 maxN_2) // setIC. by rewrite weak_second_isog ?(subset_trans (normal_sub nN1G)) ?normal_norm. have [sN /andP[lsN csN]] := exists_comps N. have i1 : perm_eq (mksrepr G N1 :: mkfactors N1 st1) [:: mksrepr G N1, mksrepr N1 N & mkfactors N sN]. rewrite perm_cons -[mksrepr _ _ :: _]/(mkfactors N1 [:: N & sN]). apply: Hi=> //; rewrite /comps ?lst1 //= lsN csN andbT /=. rewrite -quotient_simple. by rewrite -(isog_simple iso2) quotient_simple. by rewrite (normalS (subsetIl N1 N2) (normal_sub nN1G)). have i2 : perm_eq (mksrepr G N2 :: mkfactors N2 st2) [:: mksrepr G N2, mksrepr N2 N & mkfactors N sN]. rewrite perm_cons -[mksrepr _ _ :: _]/(mkfactors N2 [:: N & sN]). apply: Hi=> //; rewrite /comps ?lst2 //= lsN csN andbT /=. rewrite -quotient_simple. by rewrite -(isog_simple iso1) quotient_simple. by rewrite (normalS (subsetIr N1 N2) (normal_sub nN2G)). pose fG1 := [:: mksrepr G N1, mksrepr N1 N & mkfactors N sN]. pose fG2 := [:: mksrepr G N2, mksrepr N2 N & mkfactors N sN]. have i3 : perm_eq fG1 fG2. rewrite (@perm_catCA _ [::_] [::_]) /mksrepr. rewrite (@section_repr_isog _ (mkSec _ _) (mkSec _ _) iso1). rewrite -(@section_repr_isog _ (mkSec _ _) (mkSec _ _) iso2). exact: perm_refl. apply: (perm_trans i1); apply: (perm_trans i3); rewrite perm_sym. by apply: perm_trans i2; apply: perm_refl. Qed. End CompositionSeries. (******************************************************************************) (* Helper lemmas for group actions. *) (******************************************************************************) Section MoreGroupAction. Variables (aT rT : finGroupType). Variables (A : {group aT}) (D : {group rT}). Variable to : groupAction A D. Lemma gactsP (G : {set rT}) : reflect {acts A, on G | to} [acts A, on G | to]. Proof. apply: (iffP idP) => [nGA x|nGA]; first exact: acts_act. apply/subsetP=> a Aa /[!inE]; rewrite Aa. by apply/subsetP=> x; rewrite inE nGA. Qed. Lemma gactsM (N1 N2 : {set rT}) : N1 \subset D -> N2 \subset D -> [acts A, on N1 | to] -> [acts A, on N2 | to] -> [acts A, on N1 * N2 | to]. Proof. move=> sN1D sN2D aAN1 aAN2; apply/gactsP=> x Ax y. apply/idP/idP; case/mulsgP=> y1 y2 N1y1 N2y2 e. move: (actKin to Ax y); rewrite e; move<-. rewrite gactM ?groupV ?(subsetP sN1D y1) ?(subsetP sN2D) //. by apply: mem_mulg; rewrite ?(gactsP _ aAN1) ?(gactsP _ aAN2) // groupV. rewrite e gactM // ?(subsetP sN1D y1) ?(subsetP sN2D) //. by apply: mem_mulg; rewrite ?(gactsP _ aAN1) // ?(gactsP _ aAN2). Qed. Lemma gactsI (N1 N2 : {set rT}) : [acts A, on N1 | to] -> [acts A, on N2 | to] -> [acts A, on N1 :&: N2 | to]. Proof. move=> aAN1 aAN2. apply/subsetP=> x Ax; rewrite !inE Ax /=; apply/subsetP=> y Ny /[1!inE]. case/setIP: Ny=> N1y N2y; rewrite inE ?astabs_act ?N1y ?N2y //. - by move/subsetP: aAN2; move/(_ x Ax). - by move/subsetP: aAN1; move/(_ x Ax). Qed. Lemma gastabsP (S : {set rT}) (a : aT) : a \in A -> reflect (forall x, (to x a \in S) = (x \in S)) (a \in 'N(S | to)). Proof. move=> Aa; apply: (iffP idP) => [nSa x|nSa]; first exact: astabs_act. by rewrite !inE Aa; apply/subsetP=> x; rewrite inE nSa. Qed. End MoreGroupAction. (******************************************************************************) (* Helper lemmas for quotient actions. *) (******************************************************************************) Section MoreQuotientAction. Variables (aT rT : finGroupType). Variables (A : {group aT})(D : {group rT}). Variable to : groupAction A D. Lemma qact_dom_doms (H : {group rT}) : H \subset D -> qact_dom to H \subset A. Proof. by move=> sHD; apply/subsetP=> x; rewrite qact_domE // inE; case/andP. Qed. Lemma acts_qact_doms (H : {group rT}) : H \subset D -> [acts A, on H | to] -> qact_dom to H :=: A. Proof. move=> sHD aH; apply/eqP; rewrite eqEsubset; apply/andP. split; first exact: qact_dom_doms. apply/subsetP=> x Ax; rewrite qact_domE //; apply/gastabsP=> //. by move/gactsP: aH; move/(_ x Ax). Qed. Lemma qacts_cosetpre (H : {group rT}) (K' : {group coset_of H}) : H \subset D -> [acts A, on H | to] -> [acts qact_dom to H, on K' | to / H] -> [acts A, on coset H @*^-1 K' | to]. Proof. move=> sHD aH aK'; apply/subsetP=> x Ax; move: (Ax) (subsetP aK'). rewrite -{1}(acts_qact_doms sHD aH) => qdx; move/(_ x qdx) => nx. rewrite !inE Ax; apply/subsetP=> y; case/morphpreP=> Ny /= K'Hy /[1!inE]. apply/morphpreP; split; first by rewrite acts_qact_dom_norm. by move/gastabsP: nx; move/(_ qdx (coset H y)); rewrite K'Hy qactE. Qed. Lemma qacts_coset (H K : {group rT}) : H \subset D -> [acts A, on K | to] -> [acts qact_dom to H, on (coset H) @* K | to / H]. Proof. move=> sHD aK. apply/subsetP=> x qdx; rewrite inE qdx inE; apply/subsetP=> y. case/morphimP=> z Nz Kz /= e; rewrite e inE qactE // imset_f // inE. move/gactsP: aK; move/(_ x (subsetP (qact_dom_doms sHD) _ qdx) z); rewrite Kz. move->; move/acts_act: (acts_qact_dom to H); move/(_ x qdx z). by rewrite Nz andbT. Qed. End MoreQuotientAction. Section StableCompositionSeries. Variables (aT rT : finGroupType). Variables (D : {group rT})(A : {group aT}). Variable to : groupAction A D. Definition maxainv (B C : {set rT}) := [max C of H | [&& (H <| B), ~~ (B \subset H) & [acts A, on H | to]]]. Section MaxAinvProps. Variables K N : {group rT}. Lemma maxainv_norm : maxainv K N -> N <| K. Proof. by move/maxgroupp; case/andP. Qed. Lemma maxainv_proper : maxainv K N -> N \proper K. Proof. by move/maxgroupp; case/andP; rewrite properE; move/normal_sub->; case/andP. Qed. Lemma maxainv_sub : maxainv K N -> N \subset K. Proof. by move=> h; apply: proper_sub; apply: maxainv_proper. Qed. Lemma maxainv_ainvar : maxainv K N -> A \subset 'N(N | to). Proof. by move/maxgroupp; case/and3P. Qed. Lemma maxainvS : maxainv K N -> N \subset K. Proof. by move=> pNN; rewrite proper_sub // maxainv_proper. Qed. Lemma maxainv_exists : K :!=: 1 -> {N : {group rT} | maxainv K N}. Proof. move=> nt; apply: ex_maxgroup. exists [1 rT]%G. rewrite /= normal1 subG1 nt /=. apply/subsetP=> a Da; rewrite !inE Da /= sub1set !inE. by rewrite /= -actmE // morph1 eqxx. Qed. End MaxAinvProps. Lemma maxainvM (G H K : {group rT}) : H \subset D -> K \subset D -> maxainv G H -> maxainv G K -> H :<>: K -> H * K = G. Proof. move: H K => N1 N2 sN1D sN2D pmN1 pmN2 neN12. have cN12 : commute N1 N2. apply: normC; apply: (subset_trans (maxainv_sub pmN1)). by rewrite normal_norm ?maxainv_norm. wlog nsN21 : G N1 N2 sN1D sN2D pmN1 pmN2 neN12 cN12/ ~~(N1 \subset N2). move/eqP: (neN12); rewrite eqEsubset negb_and; case/orP=> ns; first by apply. by rewrite cN12; apply=> //; apply: sym_not_eq. have nP : N1 * N2 <| G by rewrite normalM ?maxainv_norm. have sN2P : N2 \subset N1 * N2 by rewrite mulg_subr ?group1. case/maxgroupP: (pmN1); case/andP=> nN1G pN1G mN1. case/maxgroupP: (pmN2); case/andP=> nN2G pN2G mN2. case/andP: pN1G=> nsGN1 ha1; case/andP: pN2G=> nsGN2 ha2. case e : (G \subset N1 * N2). by apply/eqP; rewrite eqEsubset e mulG_subG !normal_sub. have: N1 <*> N2 = N2 by apply: mN2; rewrite /= ?comm_joingE // nP e /= gactsM. by rewrite comm_joingE // => h; move: nsN21; rewrite -h mulg_subl. Qed. Definition asimple (K : {set rT}) := maxainv K 1. Implicit Types (H K : {group rT}) (s : seq {group rT}). Lemma asimpleP K : reflect [/\ K :!=: 1 & forall H, H <| K -> [acts A, on H | to] -> H :=: 1 \/ H :=: K] (asimple K). Proof. apply: (iffP idP). case/maxgroupP; rewrite normal1 /=; case/andP=> nsK1 aK H1. rewrite eqEsubset negb_and nsK1 /=; split => // H nHK ha. case eHK : (H :==: K); first by right; apply/eqP. left; apply: H1; rewrite ?sub1G // nHK; move/negbT: eHK. by rewrite eqEsubset negb_and normal_sub //=; move->. case=> ntK h; apply/maxgroupP; split. move: ntK; rewrite eqEsubset sub1G andbT normal1; move->. apply/subsetP=> a Da; rewrite !inE Da /= sub1set !inE. by rewrite /= -actmE // morph1 eqxx. move=> H /andP[nHK /andP[nsKH ha]] _. case: (h _ nHK ha)=> // /eqP; rewrite eqEsubset. by rewrite (negbTE nsKH) andbF. Qed. Definition acomps K s := ((last K s) == 1%G) && path [rel x y : {group rT} | maxainv x y] K s. Lemma acompsP K s : reflect (last K s = 1%G /\ path [rel x y : {group rT} | maxainv x y] K s) (acomps K s). Proof. by apply: (iffP andP); case; move/eqP. Qed. Lemma trivg_acomps K s : acomps K s -> (K :==: 1) = (s == [::]). Proof. case/andP=> ls cs; apply/eqP/eqP; last first. by move=> se; rewrite se /= in ls; apply/eqP. move=> G1; case: s ls cs => // H s _ /=; case/andP; case/maxgroupP. by rewrite G1 sub1G andbF. Qed. Lemma acomps_cons K H s : acomps K (H :: s) -> acomps H s. Proof. by case/andP => /= ls; case/andP=> _ p; rewrite /acomps ls. Qed. Lemma asimple_acompsP K s : acomps K s -> reflect (s = [:: 1%G]) (asimple K). Proof. move=> cs; apply: (iffP idP); last first. by move=> se; move: cs; rewrite se /=; case/andP=> /=; rewrite andbT. case: s cs. by rewrite /acomps /= andbT; move/eqP->; case/asimpleP; rewrite eqxx. move=> H s cs sG; apply/eqP. rewrite eqseq_cons -(trivg_acomps (acomps_cons cs)) andbC andbb. case/acompsP: cs => /= ls; case/andP=> mH ps. case/maxgroupP: sG; case/and3P => _ ntG _ ->; rewrite ?sub1G //. rewrite (maxainv_norm mH); case/andP: (maxainv_proper mH)=> _ ->. exact: (maxainv_ainvar mH). Qed. Lemma exists_acomps K : exists s, acomps K s. Proof. elim: {K} #|K| {1 3}K (leqnn #|K|) => [K | n Hi K cK]. by rewrite leqNgt cardG_gt0. case/orP: (orbN (asimple K)) => [sK | nsK]. by exists [:: (1%G : {group rT})]; rewrite /acomps eqxx /= andbT. case/orP: (orbN (K :==: 1))=> [tK | ntK]. by exists (Nil _); rewrite /acomps /= andbT. case: (maxainv_exists ntK)=> N pmN. have cN: #|N| <= n. by rewrite -ltnS (leq_trans _ cK) // proper_card // (maxainv_proper pmN). case: (Hi _ cN)=> s; case/andP=> lasts ps; exists [:: N & s]; rewrite /acomps. by rewrite last_cons lasts /= pmN. Qed. End StableCompositionSeries. Arguments maxainv {aT rT D%_G A%_G} to%_gact B%_g C%_g. Arguments asimple {aT rT D%_G A%_G} to%_gact K%_g. Section StrongJordanHolder. Section AuxiliaryLemmas. Variables aT rT : finGroupType. Variables (A : {group aT}) (D : {group rT}) (to : groupAction A D). Lemma maxainv_asimple_quo (G H : {group rT}) : H \subset D -> maxainv to G H -> asimple (to / H) (G / H). Proof. move=> sHD /maxgroupP[/and3P[nHG pHG aH] Hmax]. apply/asimpleP; split; first by rewrite -subG1 quotient_sub1 ?normal_norm. move=> K' nK'Q aK'. have: (K' \proper (G / H)) || (G / H == K'). by rewrite properE eqEsubset andbC (normal_sub nK'Q) !andbT orbC orbN. case/orP=> [ pHQ | eQH]; last by right; apply sym_eq; apply/eqP. left; pose K := ((coset H) @*^-1 K')%G. have eK'I : K' \subset (coset H) @* 'N(H). by rewrite (subset_trans (normal_sub nK'Q)) ?morphimS ?normal_norm. have eKK' : K' :=: K / H by rewrite /(K / H) morphpreK //=. suff eKH : K :=: H by rewrite -trivg_quotient eKK' eKH. have sHK : H \subset K by rewrite -ker_coset kerE morphpreS // sub1set group1. apply: Hmax => //; apply/and3P; split; last exact: qacts_cosetpre. by rewrite -(quotientGK nHG) cosetpre_normal. by move: (proper_subn pHQ); rewrite sub_morphim_pre ?normal_norm. Qed. Lemma asimple_quo_maxainv (G H : {group rT}) : H \subset D -> G \subset D -> [acts A, on G | to] -> [acts A, on H | to] -> H <| G -> asimple (to / H) (G / H) -> maxainv to G H. Proof. move=> sHD sGD aG aH nHG /asimpleP[ntQ maxQ]; apply/maxgroupP; split. by rewrite nHG -quotient_sub1 ?normal_norm // subG1 ntQ. move=> K /and3P[nKG nsGK aK] sHK. pose K' := (K / H)%G. have K'dQ : K' <| (G / H)%G by apply: morphim_normal. have nKH : H <| K by rewrite (normalS _ _ nHG) // normal_sub. have: K' :=: 1%G \/ K' :=: (G / H). apply: (maxQ K' K'dQ) => /=. apply/subsetP=> x Adx. rewrite inE Adx /= inE. apply/subsetP=> y. rewrite quotientE; case/morphimP=> z Nz Kz ->; rewrite /= !inE qactE //. have ntoyx : to z x \in 'N(H) by rewrite (acts_qact_dom_norm Adx). apply/morphimP; exists (to z x) => //. suff h: qact_dom to H \subset A. by rewrite astabs_act // (subsetP aK) //; apply: (subsetP h). by apply/subsetP=> t; rewrite qact_domE // inE; case/andP. case=> [|/quotient_injG /[!inE]/(_ nKH nHG) c]; last by rewrite c subxx in nsGK. rewrite /= -trivg_quotient => tK'; apply: (congr1 (@gval _)); move: tK'. by apply: (@quotient_injG _ H); rewrite ?inE /= ?normal_refl. Qed. Lemma asimpleI (N1 N2 : {group rT}) : N2 \subset 'N(N1) -> N1 \subset D -> [acts A, on N1 | to] -> [acts A, on N2 | to] -> asimple (to / N1) (N2 / N1) -> asimple (to / (N2 :&: N1)) (N2 / (N2 :&: N1)). Proof. move=> nN21 sN1D aN1 aN2 /asimpleP[ntQ1 max1]. have [f1 [f1e f1ker f1pre f1im]] := restrmP (coset_morphism N1) nN21. have hf2' : N2 \subset 'N(N2 :&: N1) by apply: normsI => //; rewrite normG. have hf2'' : 'ker (coset (N2 :&: N1)) \subset 'ker f1. by rewrite f1ker !ker_coset. pose f2 := factm_morphism hf2'' hf2'. apply/asimpleP; split. rewrite /= setIC; apply/negP; move: (second_isog nN21); move/isog_eq1->. by apply/negP. move=> H nHQ2 aH; pose K := f2 @* H. have nKQ1 : K <| N2 / N1. rewrite (_ : N2 / N1 = f2 @* (N2 / (N2 :&: N1))) ?morphim_normal //. by rewrite morphim_factm f1im. have sqA : qact_dom to N1 \subset A. by apply/subsetP=> t; rewrite qact_domE // inE; case/andP. have nNN2 : (N2 :&: N1) <| N2. by rewrite /normal subsetIl; apply: normsI => //; apply: normG. have aKQ1 : [acts qact_dom to N1, on K | to / N1]. pose H':= coset (N2 :&: N1)@*^-1 H. have eHH' : H :=: H' / (N2 :&: N1) by rewrite cosetpreK. have -> : K :=: f1 @* H' by rewrite /K eHH' morphim_factm. have sH'N2 : H' \subset N2. rewrite /H' eHH' quotientGK ?normal_cosetpre //=. by rewrite sub_cosetpre_quo ?normal_sub. have -> : f1 @* H' = coset N1 @* H' by rewrite f1im //=. apply: qacts_coset => //; apply: qacts_cosetpre => //; last exact: gactsI. by apply: (subset_trans (subsetIr _ _)). have injf2 : 'injm f2. by rewrite ker_factm f1ker /= ker_coset /= subG1 /= -quotientE trivg_quotient. have iHK : H \isog K. apply/isogP; pose f3 := restrm_morphism (normal_sub nHQ2) f2. by exists f3; rewrite 1?injm_restrm // morphim_restrm setIid. case: (max1 _ nKQ1 aKQ1). by move/eqP; rewrite -(isog_eq1 iHK); move/eqP->; left. move=> he /=; right; apply/eqP; rewrite eqEcard normal_sub //=. move: (second_isog nN21); rewrite setIC; move/card_isog->; rewrite -he. by move/card_isog: iHK=> <-; rewrite leqnn. Qed. End AuxiliaryLemmas. Variables (aT rT : finGroupType). Variables (A : {group aT}) (D : {group rT}) (to : groupAction A D). (******************************************************************************) (* The factors associated to two A-stable composition series of the same *) (* group are the same up to isomorphism and permutation *) (******************************************************************************) Lemma StrongJordanHolderUniqueness (G : {group rT}) (s1 s2 : seq {group rT}) : G \subset D -> acomps to G s1 -> acomps to G s2 -> perm_eq (mkfactors G s1) (mkfactors G s2). Proof. have [n] := ubnP #|G|; elim: n G => // n Hi G in s1 s2 * => cG hsD cs1 cs2. case/orP: (orbN (G :==: 1)) => [tG | ntG]. have -> : s1 = [::] by apply/eqP; rewrite -(trivg_acomps cs1). have -> : s2 = [::] by apply/eqP; rewrite -(trivg_acomps cs2). by rewrite /= perm_refl. case/orP: (orbN (asimple to G))=> [sG | nsG]. have -> : s1 = [:: 1%G ] by apply/(asimple_acompsP cs1). have -> : s2 = [:: 1%G ] by apply/(asimple_acompsP cs2). by rewrite /= perm_refl. case es1: s1 cs1 => [|N1 st1] cs1. by move: (trivg_comps cs1); rewrite eqxx; move/negP:ntG. case es2: s2 cs2 => [|N2 st2] cs2 {s1 es1}. by move: (trivg_comps cs2); rewrite eqxx; move/negP:ntG. case/andP: cs1 => /= lst1; case/andP=> maxN_1 pst1. case/andP: cs2 => /= lst2; case/andP=> maxN_2 pst2. have sN1D : N1 \subset D. by apply: subset_trans hsD; apply: maxainv_sub maxN_1. have sN2D : N2 \subset D. by apply: subset_trans hsD; apply: maxainv_sub maxN_2. have cN1 : #|N1| < n. by rewrite -ltnS (leq_trans _ cG) ?ltnS ?proper_card ?(maxainv_proper maxN_1). have cN2 : #|N2| < n. by rewrite -ltnS (leq_trans _ cG) ?ltnS ?proper_card ?(maxainv_proper maxN_2). case: (N1 =P N2) {s2 es2} => [eN12 |]. by rewrite eN12 /= perm_cons Hi // /acomps ?lst2 //= -eN12 lst1. move/eqP; rewrite -val_eqE /=; move/eqP=> neN12. have nN1G : N1 <| G by apply: (maxainv_norm maxN_1). have nN2G : N2 <| G by apply: (maxainv_norm maxN_2). pose N := (N1 :&: N2)%G. have nNG : N <| G. by rewrite /normal subIset ?(normal_sub nN1G) //= normsI ?normal_norm. have iso1 : (G / N1)%G \isog (N2 / N)%G. rewrite isog_sym /= -(maxainvM _ _ maxN_1 maxN_2) //. rewrite (@normC _ N1 N2) ?(subset_trans (normal_sub nN1G)) ?normal_norm //. by rewrite weak_second_isog ?(subset_trans (normal_sub nN2G)) ?normal_norm. have iso2 : (G / N2)%G \isog (N1 / N)%G. rewrite isog_sym /= -(maxainvM _ _ maxN_1 maxN_2) // setIC. by rewrite weak_second_isog ?(subset_trans (normal_sub nN1G)) ?normal_norm. case: (exists_acomps to N)=> sN; case/andP=> lsN csN. have aN1 : [acts A, on N1 | to]. by case/maxgroupP: maxN_1; case/and3P. have aN2 : [acts A, on N2 | to]. by case/maxgroupP: maxN_2; case/and3P. have nNN1 : N <| N1. by apply: (normalS _ _ nNG); rewrite ?subsetIl ?normal_sub. have nNN2 : N <| N2. by apply: (normalS _ _ nNG); rewrite ?subsetIr ?normal_sub. have aN : [ acts A, on N1 :&: N2 | to]. apply/subsetP=> x Ax; rewrite !inE Ax /=; apply/subsetP=> y Ny; rewrite inE. case/setIP: Ny=> N1y N2y. rewrite inE ?astabs_act ?N1y ?N2y //. by move/subsetP: aN2; move/(_ x Ax). by move/subsetP: aN1; move/(_ x Ax). have i1 : perm_eq (mksrepr G N1 :: mkfactors N1 st1) [:: mksrepr G N1, mksrepr N1 N & mkfactors N sN]. rewrite perm_cons -[mksrepr _ _ :: _]/(mkfactors N1 [:: N & sN]). apply: Hi=> //; rewrite /acomps ?lst1 //= lsN csN andbT /=. apply: asimple_quo_maxainv=> //; first by apply: subIset; rewrite sN1D. apply: asimpleI => //. by apply: subset_trans (normal_norm nN2G); apply: normal_sub. rewrite -quotientMidl (maxainvM _ _ maxN_2) //. by apply: maxainv_asimple_quo. by move=> e; apply: neN12. have i2 : perm_eq (mksrepr G N2 :: mkfactors N2 st2) [:: mksrepr G N2, mksrepr N2 N & mkfactors N sN]. rewrite perm_cons -[mksrepr _ _ :: _]/(mkfactors N2 [:: N & sN]). apply: Hi=> //; rewrite /acomps ?lst2 //= lsN csN andbT /=. apply: asimple_quo_maxainv=> //; first by apply: subIset; rewrite sN1D. have e : N1 :&: N2 :=: N2 :&: N1 by rewrite setIC. rewrite (group_inj (setIC N1 N2)); apply: asimpleI => //. by apply: subset_trans (normal_norm nN1G); apply: normal_sub. rewrite -quotientMidl (maxainvM _ _ maxN_1) //. exact: maxainv_asimple_quo. pose fG1 := [:: mksrepr G N1, mksrepr N1 N & mkfactors N sN]. pose fG2 := [:: mksrepr G N2, mksrepr N2 N & mkfactors N sN]. have i3 : perm_eq fG1 fG2. rewrite (@perm_catCA _ [::_] [::_]) /mksrepr. rewrite (@section_repr_isog _ (mkSec _ _) (mkSec _ _) iso1). rewrite -(@section_repr_isog _ (mkSec _ _) (mkSec _ _) iso2). exact: perm_refl. apply: (perm_trans i1); apply: (perm_trans i3); rewrite perm_sym. by apply: perm_trans i2; apply: perm_refl. Qed. End StrongJordanHolder.
Basic.lean
/- Copyright (c) 2025 Robin Carlier. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robin Carlier -/ import Mathlib.CategoryTheory.Functor.Category import Mathlib.CategoryTheory.Products.Basic /-! # Joins of category Given categories `C, D`, this file constructs a category `C ⋆ D`. Its objects are either objects of `C` or objects of `D`, morphisms between objects of `C` are morphisms in `C`, morphisms between object of `D` are morphisms in `D`, and finally, given `c : C` and `d : D`, there is a unique morphism `c ⟶ d` in `C ⋆ D`. ## Main constructions * `Join.edge c d`: the unique map from `c` to `d`. * `Join.inclLeft : C ⥤ C ⋆ D`, the left inclusion. Its action on morphism is the main entry point to construct maps in `C ⋆ D` between objects coming from `C`. * `Join.inclRight : D ⥤ C ⋆ D`, the left inclusion. Its action on morphism is the main entry point to construct maps in `C ⋆ D` between object coming from `D`. * `Join.mkFunctor`, A constructor for functors out of a join of categories. * `Join.mkNatTrans`, A constructor for natural transformations between functors out of a join of categories. * `Join.mkNatIso`, A constructor for natural isomorphisms between functors out of a join of categories. ## References * [Kerodon: section 1.4.3.2](https://kerodon.net/tag/0160) -/ universe v₁ v₂ v₃ v₄ v₅ v₆ u₁ u₂ u₃ u₄ u₅ u₆ namespace CategoryTheory open Functor /-- Elements of `Join C D` are either elements of `C` or elements of `D`. -/ -- Impl. : We are not defining it as a type alias for `C ⊕ D` so that we can have -- aesop to call cases on `Join C D` inductive Join (C : Type u₁) [Category.{v₁} C] (D : Type u₂) [Category.{v₂} D] : Type (max u₁ u₂) | left : C → Join C D | right : D → Join C D attribute [aesop safe cases (rule_sets := [CategoryTheory])] Join namespace Join @[inherit_doc] scoped infixr:30 " ⋆ " => Join variable (C : Type u₁) [Category.{v₁} C] (D : Type u₂) [Category.{v₂} D] section CategoryStructure variable {C D} /-- Morphisms in `C ⋆ D` are those of `C` and `D`, plus an unique morphism `(left c ⟶ right d)` for every `c : C` and `d : D`. -/ def Hom : C ⋆ D → C ⋆ D → Type (max v₁ v₂) | .left x, .left y => ULift (x ⟶ y) | .right x, .right y => ULift (x ⟶ y) | .left _, .right _ => PUnit | .right _, .left _ => PEmpty /-- Identity morphisms in `C ⋆ D` are inherited from those in `C` and `D`. -/ def id : ∀ X : C ⋆ D, Hom X X | .left x => ULift.up (𝟙 x) | .right x => ULift.up (𝟙 x) /-- Composition in `C ⋆ D` is inherited from the compositions in `C` and `D`. -/ def comp : ∀ {x y z : C ⋆ D}, Hom x y → Hom y z → Hom x z | .left _x, .left _y, .left _z, f, g => ULift.up (ULift.down f ≫ ULift.down g) | .left _x, .left _y, .right _z, _, _ => PUnit.unit | .left _x, .right _y, .right _z, _, _ => PUnit.unit | .right _x, .right _y, .right _z, f, g => ULift.up (ULift.down f ≫ ULift.down g) instance : Category.{max v₁ v₂} (C ⋆ D) where Hom X Y := Hom X Y id _ := id _ comp := comp assoc {a b c d} f g h := by cases a <;> cases b <;> cases c <;> cases d <;> simp only [Hom, comp, Category.assoc] <;> tauto id_comp {x y} f := by cases x <;> cases y <;> simp only [Hom, id, comp, Category.id_comp] <;> tauto comp_id {x y} f := by cases x <;> cases y <;> simp only [Hom, id, comp, Category.comp_id] <;> tauto @[aesop safe destruct (rule_sets := [CategoryTheory])] lemma false_of_right_to_left {X : D} {Y : C} (f : right X ⟶ left Y) : False := (f : PEmpty).elim instance {X : C} {Y : D} : Unique (left X ⟶ right Y) := inferInstanceAs (Unique PUnit) /-- Join.edge c d is the unique morphism from c to d. -/ def edge (c : C) (d : D) : left c ⟶ right d := default end CategoryStructure section Inclusions /-- The canonical inclusion from C to `C ⋆ D`. Terms of the form `(inclLeft C D).map f`should be treated as primitive when working with joins and one should avoid trying to reduce them. For this reason, there is no `inclLeft_map` simp lemma. -/ @[simps! obj] def inclLeft : C ⥤ C ⋆ D where obj := left map := ULift.up /-- The canonical inclusion from D to `C ⋆ D`. Terms of the form `(inclRight C D).map f`should be treated as primitive when working with joins and one should avoid trying to reduce them. For this reason, there is no `inclRight_map` simp lemma. -/ @[simps! obj] def inclRight : D ⥤ C ⋆ D where obj := right map := ULift.up variable {C D} /-- An induction principle for morphisms in a join of category: a morphism is either of the form `(inclLeft _ _).map _`, `(inclRight _ _).map _`, or is `edge _ _`. -/ @[elab_as_elim, cases_eliminator, induction_eliminator] def homInduction {P : {x y : C ⋆ D} → (x ⟶ y) → Sort*} (left : ∀ x y : C, (f : x ⟶ y) → P ((inclLeft C D).map f)) (right : ∀ x y : D, (f : x ⟶ y) → P ((inclRight C D).map f)) (edge : ∀ (c : C) (d : D), P (edge c d)) {x y : C ⋆ D} (f : x ⟶ y) : P f := match x, y, f with | .left x, .left y, .up f => left x y f | .right x, .right y, .up f => right x y f | .left x, .right y, _ => edge x y @[simp] lemma homInduction_left {P : {x y : C ⋆ D} → (x ⟶ y) → Sort*} (left : ∀ x y : C, (f : x ⟶ y) → P ((inclLeft C D).map f)) (right : ∀ x y : D, (f : x ⟶ y) → P ((inclRight C D).map f)) (edge : ∀ (c : C) (d : D), P (edge c d)) {x y : C} (f : x ⟶ y) : homInduction left right edge ((inclLeft C D).map f) = left x y f := rfl @[simp] lemma homInduction_right {P : {x y : C ⋆ D} → (x ⟶ y) → Sort*} (left : ∀ x y : C, (f : x ⟶ y) → P ((inclLeft C D).map f)) (right : ∀ x y : D, (f : x ⟶ y) → P ((inclRight C D).map f)) (edge : ∀ (c : C) (d : D), P (edge c d)) {x y : D} (f : x ⟶ y) : homInduction left right edge ((inclRight C D).map f) = right x y f := rfl @[simp] lemma homInduction_edge {P : {x y : C ⋆ D} → (x ⟶ y) → Sort*} (left : ∀ x y : C, (f : x ⟶ y) → P ((inclLeft C D).map f)) (right : ∀ x y : D, (f : x ⟶ y) → P ((inclRight C D).map f)) (edge : ∀ (c : C) (d : D), P (edge c d)) {c : C} {d : D} : homInduction left right edge (Join.edge c d) = edge c d := rfl variable (C D) /-- The left inclusion is fully faithful. -/ def inclLeftFullyFaithful : (inclLeft C D).FullyFaithful where preimage f := f.down /-- The right inclusion is fully faithful. -/ def inclRightFullyFaithful : (inclRight C D).FullyFaithful where preimage f := f.down instance inclLeftFull : (inclLeft C D).Full := inclLeftFullyFaithful C D |>.full instance inclRightFull : (inclRight C D).Full := inclRightFullyFaithful C D |>.full instance inclLeftFaithful : (inclLeft C D).Faithful := inclLeftFullyFaithful C D |>.faithful instance inclRightFaithful : (inclRight C D).Faithful := inclRightFullyFaithful C D |>.faithful variable {C} in /-- A situational lemma to help putting identities in the form `(inclLeft _ _).map _` when using `homInduction`. -/ lemma id_left (c : C) : 𝟙 (left c) = (inclLeft C D).map (𝟙 c) := rfl variable {D} in /-- A situational lemma to help putting identities in the form `(inclRight _ _).map _` when using `homInduction`. -/ lemma id_right (d : D) : 𝟙 (right d) = (inclRight C D).map (𝟙 d) := rfl /-- The "canonical" natural transformation from `(Prod.fst C D) ⋙ inclLeft C D` to `(Prod.snd C D) ⋙ inclRight C D`. This is bundling together all the edge morphisms into the data of a natural transformation. -/ @[simps!] def edgeTransform : Prod.fst C D ⋙ inclLeft C D ⟶ Prod.snd C D ⋙ inclRight C D where app := fun (c, d) ↦ edge c d end Inclusions section Functoriality variable {C D} {E : Type u₃} [Category.{v₃} E] {E' : Type u₄} [Category.{v₄} E'] /-- A pair of functor `F : C ⥤ E, G : D ⥤ E` as well as a natural transformation `α : (Prod.fst C D) ⋙ F ⟶ (Prod.snd C D) ⋙ G`. defines a functor out of `C ⋆ D`. This is the main entry point to define functors out of a join of categories. -/ def mkFunctor (F : C ⥤ E) (G : D ⥤ E) (α : Prod.fst C D ⋙ F ⟶ Prod.snd C D ⋙ G) : C ⋆ D ⥤ E where obj X := match X with | .left x => F.obj x | .right x => G.obj x map f := homInduction (left := fun _ _ f ↦ F.map f) (right := fun _ _ g ↦ G.map g) (edge := fun c d ↦ α.app (c,d)) f map_id x := by cases x · dsimp only [id_left, homInduction_left] simp · dsimp only [id_right, homInduction_right] simp map_comp {x y z} f g := by cases f <;> cases g · simp [← Functor.map_comp] · case left.edge f d => simpa using (α.naturality <| (Prod.sectL _ d).map f).symm · simp [← Functor.map_comp] · case edge.right c _ _ f => simpa using α.naturality <| (Prod.sectR c _).map f section variable (F : C ⥤ E) (G : D ⥤ E) (α : Prod.fst C D ⋙ F ⟶ Prod.snd C D ⋙ G) -- As these equality of objects are definitional, they should be fine. @[simp] lemma mkFunctor_obj_left (c : C) : (mkFunctor F G α).obj (left c) = F.obj c := rfl @[simp] lemma mkFunctor_obj_right (d : D) : (mkFunctor F G α).obj (right d) = G.obj d := rfl @[simp] lemma mkFunctor_map_inclLeft {c c' : C} (f : c ⟶ c') : (mkFunctor F G α).map ((inclLeft C D).map f) = F.map f := rfl /-- Precomposing `mkFunctor F G α` with the left inclusion gives back `F`. -/ @[simps!] def mkFunctorLeft : inclLeft C D ⋙ mkFunctor F G α ≅ F := Iso.refl _ /-- Precomposing `mkFunctor F G α` with the right inclusion gives back `G`. -/ @[simps!] def mkFunctorRight : inclRight C D ⋙ mkFunctor F G α ≅ G := Iso.refl _ @[simp] lemma mkFunctor_map_inclRight {d d' : D} (f : d ⟶ d') : (mkFunctor F G α).map ((inclRight C D).map f) = G.map f := rfl /-- Whiskering `mkFunctor F G α` with the universal transformation gives back `α`. -/ @[simp] lemma mkFunctor_edgeTransform : whiskerRight (edgeTransform C D) (mkFunctor F G α) = α := by ext x simp [mkFunctor] @[simp] lemma mkFunctor_map_edge (c : C) (d : D) : (mkFunctor F G α).map (edge c d) = α.app (c, d) := rfl end /-- Construct a natural transformation between functors from a join from the data of natural transformations between each side that are compatible with the action on edge maps. -/ def mkNatTrans {F : C ⋆ D ⥤ E} {F' : C ⋆ D ⥤ E} (αₗ : inclLeft C D ⋙ F ⟶ inclLeft C D ⋙ F') (αᵣ : inclRight C D ⋙ F ⟶ inclRight C D ⋙ F') (h : whiskerRight (edgeTransform C D) F ≫ whiskerLeft (Prod.snd C D) αᵣ = whiskerLeft (Prod.fst C D) αₗ ≫ whiskerRight (edgeTransform C D) F' := by cat_disch) : F ⟶ F' where app x := match x with | left x => αₗ.app x | right x => αᵣ.app x naturality {x y} f := by cases f with | @left x y f => simpa using αₗ.naturality f | @right x y f => simpa using αᵣ.naturality f | @edge c d => exact funext_iff.mp (NatTrans.ext_iff.mp h) (c, d) section variable {F : C ⋆ D ⥤ E} {F' : C ⋆ D ⥤ E} (αₗ : inclLeft C D ⋙ F ⟶ inclLeft C D ⋙ F') (αᵣ : inclRight C D ⋙ F ⟶ inclRight C D ⋙ F') (h : whiskerRight (edgeTransform C D) F ≫ whiskerLeft (Prod.snd C D) αᵣ = whiskerLeft (Prod.fst C D) αₗ ≫ whiskerRight (edgeTransform C D) F' := by cat_disch) @[simp] lemma mkNatTrans_app_left (c : C) : (mkNatTrans αₗ αᵣ h).app (left c) = αₗ.app c := rfl @[simp] lemma mkNatTrans_app_right (d : D) : (mkNatTrans αₗ αᵣ h).app (right d) = αᵣ.app d := rfl @[simp] lemma whiskerLeft_inclLeft_mkNatTrans : whiskerLeft (inclLeft C D) (mkNatTrans αₗ αᵣ h) = αₗ := rfl @[simp] lemma whiskerLeft_inclRight_mkNatTrans : whiskerLeft (inclRight C D) (mkNatTrans αₗ αᵣ h) = αᵣ := rfl end /-- Two natural transformations between functors out of a join are equal if they are so after whiskering with the inclusions. -/ lemma natTrans_ext {F F' : C ⋆ D ⥤ E} {α β : F ⟶ F'} (h₁ : whiskerLeft (inclLeft C D) α = whiskerLeft (inclLeft C D) β) (h₂ : whiskerLeft (inclRight C D) α = whiskerLeft (inclRight C D) β) : α = β := by ext t cases t with | left t => exact congrArg (fun x ↦ x.app t) h₁ | right t => exact congrArg (fun x ↦ x.app t) h₂ lemma eq_mkNatTrans {F F' : C ⋆ D ⥤ E} (α : F ⟶ F') : mkNatTrans (whiskerLeft (inclLeft C D) α) (whiskerLeft (inclRight C D) α) = α := by apply natTrans_ext <;> simp section /-- `mkNatTrans` respects vertical composition. -/ lemma mkNatTransComp {F F' F'' : C ⋆ D ⥤ E} (αₗ : inclLeft C D ⋙ F ⟶ inclLeft C D ⋙ F') (αᵣ : inclRight C D ⋙ F ⟶ inclRight C D ⋙ F') (βₗ : inclLeft C D ⋙ F' ⟶ inclLeft C D ⋙ F'') (βᵣ : inclRight C D ⋙ F' ⟶ inclRight C D ⋙ F'') (h : whiskerRight (edgeTransform C D) F ≫ whiskerLeft (Prod.snd C D) αᵣ = whiskerLeft (Prod.fst C D) αₗ ≫ whiskerRight (edgeTransform C D) F' := by cat_disch) (h' : whiskerRight (edgeTransform C D) F' ≫ whiskerLeft (Prod.snd C D) βᵣ = whiskerLeft (Prod.fst C D) βₗ ≫ whiskerRight (edgeTransform C D) F'' := by cat_disch) : mkNatTrans (αₗ ≫ βₗ) (αᵣ ≫ βᵣ) (by simp [← h', reassoc_of% h]) = mkNatTrans αₗ αᵣ h ≫ mkNatTrans βₗ βᵣ h' := by apply natTrans_ext <;> cat_disch end /-- Two functors out of a join of category are naturally isomorphic if their compositions with the inclusions are isomorphic and the whiskering with the canonical transformation is respected through these isomorphisms. -/ @[simps] def mkNatIso {F : C ⋆ D ⥤ E} {G : C ⋆ D ⥤ E} (eₗ : inclLeft C D ⋙ F ≅ inclLeft C D ⋙ G) (eᵣ : inclRight C D ⋙ F ≅ inclRight C D ⋙ G) (h : whiskerRight (edgeTransform C D) F ≫ (isoWhiskerLeft (Prod.snd C D) eᵣ).hom = (isoWhiskerLeft (Prod.fst C D) eₗ).hom ≫ whiskerRight (edgeTransform C D) G := by cat_disch) : F ≅ G where hom := mkNatTrans eₗ.hom eᵣ.hom (by simpa using h) inv := mkNatTrans eₗ.inv eᵣ.inv (by rw [Eq.comm, ← isoWhiskerLeft_inv, ← isoWhiskerLeft_inv, Iso.inv_comp_eq, ← Category.assoc, Eq.comm, Iso.comp_inv_eq, h]) /-- A pair of functors ((C ⥤ E), (D ⥤ E')) induces a functor `C ⋆ D ⥤ E ⋆ E'`. -/ def mapPair (Fₗ : C ⥤ E) (Fᵣ : D ⥤ E') : C ⋆ D ⥤ E ⋆ E' := mkFunctor (Fₗ ⋙ inclLeft _ _) (Fᵣ ⋙ inclRight _ _) { app := fun _ ↦ edge _ _ } section mapPair variable (Fₗ : C ⥤ E) (Fᵣ : D ⥤ E') @[simp] lemma mapPair_obj_left (c : C) : (mapPair Fₗ Fᵣ).obj (left c) = left (Fₗ.obj c) := rfl @[simp] lemma mapPair_obj_right (d : D) : (mapPair Fₗ Fᵣ).obj (right d) = right (Fᵣ.obj d) := rfl @[simp] lemma mapPair_map_inclLeft {c c' : C} (f : c ⟶ c') : (mapPair Fₗ Fᵣ).map ((inclLeft C D).map f) = (inclLeft E E').map (Fₗ.map f) := rfl @[simp] lemma mapPair_map_inclRight {d d' : D} (f : d ⟶ d') : (mapPair Fₗ Fᵣ).map ((inclRight C D).map f) = (inclRight E E').map (Fᵣ.map f) := rfl /-- Characterizing `mapPair` on left morphisms. -/ @[simps! hom_app inv_app] def mapPairLeft : inclLeft _ _ ⋙ mapPair Fₗ Fᵣ ≅ Fₗ ⋙ inclLeft _ _ := mkFunctorLeft _ _ _ /-- Characterizing `mapPair` on right morphisms. -/ @[simps! hom_app inv_app] def mapPairRight : inclRight _ _ ⋙ mapPair Fₗ Fᵣ ≅ Fᵣ ⋙ inclRight _ _ := mkFunctorRight _ _ _ end mapPair /-- Any functor out of a join is naturally isomorphic to a functor of the form `mkFunctor F G α`. -/ @[simps!] def isoMkFunctor (F : C ⋆ D ⥤ E) : F ≅ mkFunctor (inclLeft C D ⋙ F) (inclRight C D ⋙ F) (whiskerRight (edgeTransform C D) F) := mkNatIso (mkFunctorLeft _ _ _).symm (mkFunctorRight _ _ _).symm /-- `mapPair` respects identities -/ @[simps!] def mapPairId : mapPair (𝟭 C) (𝟭 D) ≅ 𝟭 (C ⋆ D) := mkNatIso (mapPairLeft _ _ ≪≫ Functor.leftUnitor _ ≪≫ (Functor.rightUnitor _).symm) (mapPairRight _ _ ≪≫ Functor.leftUnitor _ ≪≫ (Functor.rightUnitor _).symm) variable {J : Type u₅} [Category.{v₅} J] {K : Type u₆} [Category.{v₆} K] -- @[simps!] times out here /-- `mapPair` respects composition -/ def mapPairComp (Fₗ : C ⥤ E) (Fᵣ : D ⥤ E') (Gₗ : E ⥤ J) (Gᵣ : E' ⥤ K) : mapPair (Fₗ ⋙ Gₗ) (Fᵣ ⋙ Gᵣ) ≅ mapPair Fₗ Fᵣ ⋙ mapPair Gₗ Gᵣ := mkNatIso (mapPairLeft (Fₗ ⋙ Gₗ) (Fᵣ ⋙ Gᵣ) ≪≫ Functor.associator Fₗ Gₗ (inclLeft J K) ≪≫ (isoWhiskerLeft Fₗ (mapPairLeft Gₗ Gᵣ).symm) ≪≫ (Functor.associator Fₗ (inclLeft E E') (mapPair Gₗ Gᵣ)).symm ≪≫ isoWhiskerRight (mapPairLeft Fₗ Fᵣ).symm (mapPair Gₗ Gᵣ)) (mapPairRight (Fₗ ⋙ Gₗ) (Fᵣ ⋙ Gᵣ) ≪≫ Functor.associator Fᵣ Gᵣ (inclRight J K) ≪≫ (isoWhiskerLeft Fᵣ (mapPairRight Gₗ Gᵣ).symm) ≪≫ (Functor.associator Fᵣ (inclRight E E') (mapPair Gₗ Gᵣ)).symm ≪≫ isoWhiskerRight (mapPairRight Fₗ Fᵣ).symm (mapPair Gₗ Gᵣ)) section mapPairComp variable (Fₗ : C ⥤ E) (Fᵣ : D ⥤ E') (Gₗ : E ⥤ J) (Gᵣ : E' ⥤ K) @[simp] lemma mapPairComp_hom_app_left (c : C) : (mapPairComp Fₗ Fᵣ Gₗ Gᵣ).hom.app (left c) = 𝟙 (left (Gₗ.obj (Fₗ.obj c))) := by dsimp [mapPairComp] simp @[simp] lemma mapPairComp_hom_app_right (d : D) : (mapPairComp Fₗ Fᵣ Gₗ Gᵣ).hom.app (right d) = 𝟙 (right (Gᵣ.obj (Fᵣ.obj d))) := by dsimp [mapPairComp] simp @[simp] lemma mapPairComp_inv_app_left (c : C) : (mapPairComp Fₗ Fᵣ Gₗ Gᵣ).inv.app (left c) = 𝟙 (left (Gₗ.obj (Fₗ.obj c))) := by dsimp [mapPairComp] simp @[simp] lemma mapPairComp_inv_app_right (d : D) : (mapPairComp Fₗ Fᵣ Gₗ Gᵣ).inv.app (right d) = 𝟙 (right (Gᵣ.obj (Fᵣ.obj d))) := by dsimp [mapPairComp] simp end mapPairComp end Functoriality section NaturalTransforms variable {E : Type u₃} [Category.{v₃} E] {E' : Type u₄} [Category.{v₄} E'] variable {C D} /-- A natural transformation `Fₗ ⟶ Gₗ` induces a natural transformation `mapPair Fₗ H ⟶ mapPair Gₗ H` for every `H : D ⥤ E'`. -/ @[simps!] def mapWhiskerRight {Fₗ : C ⥤ E} {Gₗ : C ⥤ E} (α : Fₗ ⟶ Gₗ) (H : D ⥤ E') : mapPair Fₗ H ⟶ mapPair Gₗ H := mkNatTrans ((mapPairLeft Fₗ H).hom ≫ whiskerRight α (inclLeft E E') ≫ (mapPairLeft Gₗ H).inv) ((mapPairRight Fₗ H).hom ≫ whiskerRight (𝟙 H) (inclRight E E') ≫ (mapPairRight Gₗ H).inv) @[simp] lemma mapWhiskerRight_comp {Fₗ : C ⥤ E} {Gₗ : C ⥤ E} {Hₗ : C ⥤ E} (α : Fₗ ⟶ Gₗ) (β : Gₗ ⟶ Hₗ) (H : D ⥤ E') : mapWhiskerRight (α ≫ β) H = mapWhiskerRight α H ≫ mapWhiskerRight β H := by cat_disch @[simp] lemma mapWhiskerRight_id (Fₗ : C ⥤ E) (H : D ⥤ E') : mapWhiskerRight (𝟙 Fₗ) H = 𝟙 _ := by cat_disch /-- A natural transformation `Fᵣ ⟶ Gᵣ` induces a natural transformation `mapPair H Fᵣ ⟶ mapPair H Gᵣ` for every `H : C ⥤ E`. -/ @[simps!] def mapWhiskerLeft (H : C ⥤ E) {Fᵣ : D ⥤ E'} {Gᵣ : D ⥤ E'} (α : Fᵣ ⟶ Gᵣ) : mapPair H Fᵣ ⟶ mapPair H Gᵣ := mkNatTrans ((mapPairLeft H Fᵣ).hom ≫ whiskerRight (𝟙 H) (inclLeft E E') ≫ (mapPairLeft H Gᵣ).inv) ((mapPairRight H Fᵣ).hom ≫ whiskerRight α (inclRight E E') ≫ (mapPairRight H Gᵣ).inv) @[simp] lemma mapWhiskerLeft_comp {Fᵣ : D ⥤ E'} {Gᵣ : D ⥤ E'} {Hᵣ : D ⥤ E'} (H : C ⥤ E) (α : Fᵣ ⟶ Gᵣ) (β : Gᵣ ⟶ Hᵣ) : mapWhiskerLeft H (α ≫ β) = mapWhiskerLeft H α ≫ mapWhiskerLeft H β := by cat_disch @[simp] lemma mapWhiskerLeft_id (H : C ⥤ E) (Fᵣ : D ⥤ E') : mapWhiskerLeft H (𝟙 Fᵣ) = 𝟙 _ := by cat_disch /-- One can exchange `mapWhiskerLeft` and `mapWhiskerRight`. -/ lemma mapWhisker_exchange (Fₗ : C ⥤ E) (Gₗ : C ⥤ E) (Fᵣ : D ⥤ E') (Gᵣ : D ⥤ E') (αₗ : Fₗ ⟶ Gₗ) (αᵣ : Fᵣ ⟶ Gᵣ) : mapWhiskerLeft Fₗ αᵣ ≫ mapWhiskerRight αₗ Gᵣ = mapWhiskerRight αₗ Fᵣ ≫ mapWhiskerLeft Gₗ αᵣ := by ext cat_disch /-- A natural isomorphism `Fᵣ ≅ Gᵣ` induces a natural isomorphism `mapPair H Fᵣ ≅ mapPair H Gᵣ` for every `H : C ⥤ E`. -/ @[simps!] def mapIsoWhiskerLeft (H : C ⥤ E) {Fᵣ : D ⥤ E'} {Gᵣ : D ⥤ E'} (α : Fᵣ ≅ Gᵣ) : mapPair H Fᵣ ≅ mapPair H Gᵣ := mkNatIso (mapPairLeft H Fᵣ ≪≫ isoWhiskerRight (Iso.refl H) (inclLeft _ _) ≪≫ (mapPairLeft H Gᵣ).symm) (mapPairRight H Fᵣ ≪≫ isoWhiskerRight α (inclRight E E') ≪≫ (mapPairRight H Gᵣ).symm) /-- A natural isomorphism `Fᵣ ≅ Gᵣ` induces a natural isomorphism `mapPair Fₗ H ≅ mapPair Gₗ H` for every `H : C ⥤ E`. -/ @[simps!] def mapIsoWhiskerRight {Fₗ : C ⥤ E} {Gₗ : C ⥤ E} (α : Fₗ ≅ Gₗ) (H : D ⥤ E') : mapPair Fₗ H ≅ mapPair Gₗ H := mkNatIso (mapPairLeft Fₗ H ≪≫ isoWhiskerRight α (inclLeft E E') ≪≫ (mapPairLeft Gₗ H).symm) (mapPairRight Fₗ H ≪≫ isoWhiskerRight (Iso.refl H) (inclRight E E') ≪≫ (mapPairRight Gₗ H).symm) lemma mapIsoWhiskerRight_hom {Fₗ : C ⥤ E} {Gₗ : C ⥤ E} (α : Fₗ ≅ Gₗ) (H : D ⥤ E') : (mapIsoWhiskerRight α H).hom = mapWhiskerRight α.hom H := rfl lemma mapIsoWhiskerRight_inv {Fₗ : C ⥤ E} {Gₗ : C ⥤ E} (α : Fₗ ≅ Gₗ) (H : D ⥤ E') : (mapIsoWhiskerRight α H).inv = mapWhiskerRight α.inv H := by ext x cases x <;> simp [mapIsoWhiskerRight] lemma mapIsoWhiskerLeft_hom (H : C ⥤ E) {Fᵣ : D ⥤ E'} {Gᵣ : D ⥤ E'} (α : Fᵣ ≅ Gᵣ) : (mapIsoWhiskerLeft H α).hom = mapWhiskerLeft H α.hom := rfl lemma mapIsoWhiskerLeft_inv (H : C ⥤ E) {Fᵣ : D ⥤ E'} {Gᵣ : D ⥤ E'} (α : Fᵣ ≅ Gᵣ) : (mapIsoWhiskerLeft H α).inv = mapWhiskerLeft H α.inv := by ext x cases x <;> simp [mapIsoWhiskerLeft] end NaturalTransforms section mapPairEquiv variable {C' : Type u₃} [Category.{v₃} C'] {D' : Type u₄} [Category.{v₄} D'] variable {C D} /-- Equivalent categories have equivalent joins. -/ @[simps] def mapPairEquiv (e : C ≌ C') (e' : D ≌ D') : C ⋆ D ≌ C' ⋆ D' where functor := mapPair e.functor e'.functor inverse := mapPair e.inverse e'.inverse unitIso := mapPairId.symm ≪≫ mapIsoWhiskerRight e.unitIso _ ≪≫ mapIsoWhiskerLeft _ e'.unitIso ≪≫ mapPairComp _ _ _ _ counitIso := (mapPairComp _ _ _ _).symm ≪≫ mapIsoWhiskerRight e.counitIso _ ≪≫ mapIsoWhiskerLeft _ e'.counitIso ≪≫ mapPairId functor_unitIso_comp x := by cases x <;> simp [← (inclLeft C' D').map_comp, ← (inclRight C' D').map_comp] instance isEquivalenceMapPair {F : C ⥤ C'} {F' : D ⥤ D'} [F.IsEquivalence] [F'.IsEquivalence] : (mapPair F F').IsEquivalence := inferInstanceAs (mapPairEquiv F.asEquivalence F'.asEquivalence).functor.IsEquivalence end mapPairEquiv end Join end CategoryTheory
imset2_finset.v
From mathcomp Require Import all_boot. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Check @imset2_pair.
Exterior.lean
import Mathlib.Topology.NhdsKer deprecated_module (since := "2025-07-09")
fun_prop.lean
/- Copyright (c) 2024 Tomáš Skřivan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tomáš Skřivan -/ import Mathlib.MeasureTheory.MeasurableSpace.Basic import Mathlib.MeasureTheory.Constructions.BorelSpace.ContinuousLinearMap import Mathlib.MeasureTheory.Constructions.BorelSpace.Real import Mathlib.Analysis.Calculus.ContDiff.Basic import Mathlib.Topology.Constructions import Mathlib.Tactic.FunProp open Mathlib /-! The first step in using `fun_prop` is to mark desired function property with `fun_prop` attribute. In this example we work with `Measurable`. -/ attribute [fun_prop] Measurable /-! Now we can start marking theorems about `Measurable` with the attribute `@[fun_prop]`. It is best to start with the basic lambda calculus rules. There are five of these rules in total - identity rule `Measurable fun x => x` - constant rule `Measurable fun x => y` - composition rule `Measurable f → Measurable g → Measurable fun x => f (g x)` - apply rule `Measurable fun f => f x` - pi rule `∀ i, Measurable (f · i) → Measurable fun x i => f x i` You do not have to provide them all. For example `IsLinearMap` does not have the constant rule. However, to have any hope at using `fun_prop` successfully you need to at least provide identity and composition rule. -/ attribute [fun_prop] measurable_id' measurable_const Measurable.comp' measurable_pi_apply measurable_pi_lambda /-! Measurability also behaves nicely with respect to taking products. Let's mark the product constructor. -/ attribute [fun_prop] Measurable.prodMk -- Measurable f → Measurable g → Measurable fun x => (f x, g x) /-! When it comes to product projection, their properties are usually stated in two different ways ``` measurable_fst : Measurable fun x => Prod.fst x ``` or ``` Measurable.fst : Measurable f → Measurable fun x => Prod.fst (f x) ``` The tactic `fun_prop` can work with both versions; it should be sufficient to provide just one of them. It does not hurt to provide both of them though. -/ attribute [fun_prop] measurable_fst Measurable.fst measurable_snd Measurable.snd /-! A silly example on which `measurability` fails and `fun_prop` succeeds. Let's turn on tracing to see what is going on set_option trace.Meta.Tactic.fun_prop true in -/ example {α} [MeasurableSpace α] (f : α → α → α) (hf : Measurable fun (x, y) ↦ f x y) (a : α) : Measurable (fun x => (f x a, f (f x x) (f (f x x) x))) := by -- This now takes longer than 200,000 heartbeats to fail, so I've commented it out. -- fail_if_success measurability fun_prop /-! To give more complicated examples we mark theorems about arithmetic operations with `@[fun_prop]` Again we mark both versions of theorems. Internally `fun_prop` says that theorems like `measurable_add` are in "uncurried form" and theorems like `Measurable.add` are in compositional form. -/ attribute [fun_prop] measurable_add measurable_sub measurable_mul measurable_neg measurable_div measurable_smul Measurable.add Measurable.sub Measurable.mul Measurable.neg Measurable.div Measurable.smul /-! An example of measurability of some arithmetic function -/ example : Measurable fun x : ℝ => (x * x - 1) / x + (x - x*x) := by fun_prop /-! So far we talked about two types of theorems: 1. theorems about basic lambda calculus terms 2. theorems about defined functions There are two other kinds of theorems `fun_prop` can work with: 3. transition theorems - theorems that imply e.g. measurability from continuity 4. morphism theorems - theorems talking about bundles When you mark a theorem with `@[fun_prop]` attribute you can check the type of the theorem by turning on the option `trace.Meta.Tactic.fun_prop.attr`. -/ /-! Transition theorems prove one function property from another. We already mentioned that continuity implies measurability but there are many more. For example differentiability implies continuity, linear map between finitely dimensional spaces is continuous etc. The theorem proving measurability from continuity is `Continuous.measurable` so let's mark it with `@[fun_prop]` -/ attribute [fun_prop] Continuous.measurable -- Continuous f → Measurable f /-! For this theorem to be used properly we also need to set up `Continuous` with `fun_prop`. The bare bones setup is -/ attribute [fun_prop] Continuous continuous_id' continuous_const Continuous.comp' continuous_pi continuous_apply Continuous.prodMk Continuous.fst Continuous.snd /-! Now we can prove one of the earlier examples assuming the function is continuous instead of measurable. -/ example (f : ℝ → ℝ → ℝ) (hf : Continuous fun (x, y) ↦ f x y) (a : ℝ) : Measurable (fun x => (f x a, f (f x x) (f (f x x) x))) := by fun_prop /-! To keep `fun_prop` performant it is important to keep these "transition theorems" in the form `P f → Q f` i.e. the conclusion has to talk about a single free variable `f`. Furthermore, the "transition theorems" should **not** form a cycle. -/ /-! Lastly there are "morphism theorems". These are really just theorems about the properties of `DFunLike.coe` and are treated somewhat specially. Let's make continuous linear maps work with measurability. The function `DFunLike.coe` is a function of two arguments `f : E →L[K] F` and `x : E`. Mathlib currently states measurability of `DFunLike.coe` in `f` and `x` separately. The theorem `ContinuousLinearMap.measurable` states measurability in `x` in uncurried form. The theorem `ContinuousLinearMap.measurable_comp` states measurability in `x` in compositional form. The theorem `ContinuousLinearMap.measurable_apply` states measurability in `f` in uncurried form. The theorem `Measurable.apply_continuousLinearMap` states measurability in `f` in compositional form. -/ set_option linter.style.longLine false in attribute [fun_prop] ContinuousLinearMap.measurable -- Measurable fun (x : E) => DFunLike.coe L x ContinuousLinearMap.measurable_comp -- Measurable φ → Measurable fun (x : E) => DFunLike.coe L (φ x) ContinuousLinearMap.measurable_apply -- Measurable fun (f : E →L[K] F) => DFunLike.coe f x Measurable.apply_continuousLinearMap -- Measurable L → Measurable fun (x : α) => DFunLike.coe (L x) v /-! A silly example that everything together works as expected -/ example (f : ℝ → ℝ → (ℝ →L[ℝ] ℝ)) (hf : Continuous (fun (x, y) ↦ f x y)) : Measurable fun x => (f (x / x) (x * x) 1 + x) := by fun_prop set_option linter.style.longLine false in /-! In the current state of `fun_prop`, morphism theorems **have to** be stated in compositional form. Sometimes they might work in uncurried form but `fun_prop` is not designed that way right now. In other cases the function property of `DFunLike.coe` can be stated jointly in `f` and `x`. This is the case of `ContDiff n` and continuous linear maps. The theorem is `ContDiff.clm_apply`. #check ContDiff.clm_apply -- {f : E → F →L[K] G} → {g : E → F} → ContDiff K n f → ContDiff K n g → ContDiff K n fun x => DFunLike.coe (f x) (g x) If possible, `fun_prop` theorem about `DFunLike.coe` should be state in this way. That should be all about `fun_prop`, I hope you will enjoy using it :) -/
Roots.lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import Mathlib.RingTheory.Polynomial.Cyclotomic.Basic import Mathlib.RingTheory.RootsOfUnity.Minpoly /-! # Roots of cyclotomic polynomials. We gather results about roots of cyclotomic polynomials. In particular we show in `Polynomial.cyclotomic_eq_minpoly` that `cyclotomic n R` is the minimal polynomial of a primitive root of unity. ## Main results * `IsPrimitiveRoot.isRoot_cyclotomic` : Any `n`-th primitive root of unity is a root of `cyclotomic n R`. * `isRoot_cyclotomic_iff` : if `NeZero (n : R)`, then `μ` is a root of `cyclotomic n R` if and only if `μ` is a primitive root of unity. * `Polynomial.cyclotomic_eq_minpoly` : `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. * `Polynomial.cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible. ## Implementation details To prove `Polynomial.cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in `Polynomial.cyclotomic_eq_minpoly` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root of unity `μ : K`, where `K` is a field of characteristic `0`. -/ namespace Polynomial variable {R : Type*} [CommRing R] {n : ℕ} theorem isRoot_of_unity_of_root_cyclotomic {ζ : R} {i : ℕ} (hi : i ∈ n.divisors) (h : (cyclotomic i R).IsRoot ζ) : ζ ^ n = 1 := by rcases n.eq_zero_or_pos with (rfl | hn) · exact pow_zero _ have := congr_arg (eval ζ) (prod_cyclotomic_eq_X_pow_sub_one hn R).symm rw [eval_sub, eval_pow, eval_X, eval_one] at this convert eq_add_of_sub_eq' this convert (add_zero (M := R) _).symm apply eval_eq_zero_of_dvd_of_eval_eq_zero _ h exact Finset.dvd_prod_of_mem _ hi section IsDomain variable [IsDomain R] theorem _root_.isRoot_of_unity_iff (h : 0 < n) (R : Type*) [CommRing R] [IsDomain R] {ζ : R} : ζ ^ n = 1 ↔ ∃ i ∈ n.divisors, (cyclotomic i R).IsRoot ζ := by rw [← mem_nthRoots h, nthRoots, mem_roots <| X_pow_sub_C_ne_zero h _, C_1, ← prod_cyclotomic_eq_X_pow_sub_one h, isRoot_prod] /-- Any `n`-th primitive root of unity is a root of `cyclotomic n R`. -/ theorem _root_.IsPrimitiveRoot.isRoot_cyclotomic (hpos : 0 < n) {μ : R} (h : IsPrimitiveRoot μ n) : IsRoot (cyclotomic n R) μ := by rw [← mem_roots (cyclotomic_ne_zero n R), cyclotomic_eq_prod_X_sub_primitiveRoots h, roots_prod_X_sub_C, ← Finset.mem_def] rwa [← mem_primitiveRoots hpos] at h private theorem isRoot_cyclotomic_iff' {n : ℕ} {K : Type*} [Field K] {μ : K} [NeZero (n : K)] : IsRoot (cyclotomic n K) μ ↔ IsPrimitiveRoot μ n := by -- in this proof, `o` stands for `orderOf μ` have hnpos : 0 < n := (NeZero.of_neZero_natCast K).out.bot_lt refine ⟨fun hμ => ?_, IsPrimitiveRoot.isRoot_cyclotomic hnpos⟩ have hμn : μ ^ n = 1 := by rw [isRoot_of_unity_iff hnpos _] exact ⟨n, n.mem_divisors_self hnpos.ne', hμ⟩ by_contra hnμ have ho : 0 < orderOf μ := (isOfFinOrder_iff_pow_eq_one.2 <| ⟨n, hnpos, hμn⟩).orderOf_pos have := pow_orderOf_eq_one μ rw [isRoot_of_unity_iff ho] at this obtain ⟨i, hio, hiμ⟩ := this replace hio := Nat.dvd_of_mem_divisors hio rw [IsPrimitiveRoot.not_iff] at hnμ rw [← orderOf_dvd_iff_pow_eq_one] at hμn have key : i < n := (Nat.le_of_dvd ho hio).trans_lt ((Nat.le_of_dvd hnpos hμn).lt_of_ne hnμ) have key' : i ∣ n := hio.trans hμn rw [← Polynomial.dvd_iff_isRoot] at hμ hiμ have hni : {i, n} ⊆ n.divisors := by simpa [Finset.insert_subset_iff, key'] using hnpos.ne' obtain ⟨k, hk⟩ := hiμ obtain ⟨j, hj⟩ := hμ have := prod_cyclotomic_eq_X_pow_sub_one hnpos K rw [← Finset.prod_sdiff hni, Finset.prod_pair key.ne, hk, hj] at this have hn := (X_pow_sub_one_separable_iff.mpr <| NeZero.natCast_ne n K).squarefree rw [← this, Squarefree] at hn specialize hn (X - C μ) ⟨(∏ x ∈ n.divisors \ {i, n}, cyclotomic x K) * k * j, by ring⟩ simp [Polynomial.isUnit_iff_degree_eq_zero] at hn theorem isRoot_cyclotomic_iff [NeZero (n : R)] {μ : R} : IsRoot (cyclotomic n R) μ ↔ IsPrimitiveRoot μ n := by have hf : Function.Injective _ := IsFractionRing.injective R (FractionRing R) haveI : NeZero (n : FractionRing R) := NeZero.nat_of_injective hf rw [← isRoot_map_iff hf, ← IsPrimitiveRoot.map_iff_of_injective hf, map_cyclotomic, ← isRoot_cyclotomic_iff'] theorem roots_cyclotomic_nodup [NeZero (n : R)] : (cyclotomic n R).roots.Nodup := by obtain h | ⟨ζ, hζ⟩ := (cyclotomic n R).roots.empty_or_exists_mem · exact h.symm ▸ Multiset.nodup_zero rw [mem_roots <| cyclotomic_ne_zero n R, isRoot_cyclotomic_iff] at hζ refine Multiset.nodup_of_le (roots.le_of_dvd (X_pow_sub_C_ne_zero (NeZero.pos_of_neZero_natCast R) 1) <| cyclotomic.dvd_X_pow_sub_one n R) hζ.nthRoots_one_nodup theorem cyclotomic.roots_to_finset_eq_primitiveRoots [NeZero (n : R)] : (⟨(cyclotomic n R).roots, roots_cyclotomic_nodup⟩ : Finset _) = primitiveRoots n R := by ext a -- Porting note: was -- `simp [cyclotomic_ne_zero n R, isRoot_cyclotomic_iff, mem_primitiveRoots,` -- ` NeZero.pos_of_neZero_natCast R]` simp only [mem_primitiveRoots, NeZero.pos_of_neZero_natCast R] convert isRoot_cyclotomic_iff (n := n) (μ := a) using 0 simp [cyclotomic_ne_zero n R] theorem cyclotomic.roots_eq_primitiveRoots_val [NeZero (n : R)] : (cyclotomic n R).roots = (primitiveRoots n R).val := by rw [← cyclotomic.roots_to_finset_eq_primitiveRoots] /-- If `R` is of characteristic zero, then `ζ` is a root of `cyclotomic n R` if and only if it is a primitive `n`-th root of unity. -/ theorem isRoot_cyclotomic_iff_charZero {n : ℕ} {R : Type*} [CommRing R] [IsDomain R] [CharZero R] {μ : R} (hn : 0 < n) : (Polynomial.cyclotomic n R).IsRoot μ ↔ IsPrimitiveRoot μ n := letI := NeZero.of_gt hn isRoot_cyclotomic_iff end IsDomain /-- Over a ring `R` of characteristic zero, `fun n => cyclotomic n R` is injective. -/ theorem cyclotomic_injective [CharZero R] : Function.Injective fun n => cyclotomic n R := by intro n m hnm simp only at hnm rcases eq_or_ne n 0 with (rfl | hzero) · rw [cyclotomic_zero] at hnm replace hnm := congr_arg natDegree hnm rwa [natDegree_one, natDegree_cyclotomic, eq_comm, Nat.totient_eq_zero, eq_comm] at hnm · haveI := NeZero.mk hzero rw [← map_cyclotomic_int _ R, ← map_cyclotomic_int _ R] at hnm replace hnm := map_injective (Int.castRingHom R) Int.cast_injective hnm replace hnm := congr_arg (map (Int.castRingHom ℂ)) hnm rw [map_cyclotomic_int, map_cyclotomic_int] at hnm have hprim := Complex.isPrimitiveRoot_exp _ hzero have hroot := isRoot_cyclotomic_iff (R := ℂ).2 hprim rw [hnm] at hroot haveI hmzero : NeZero m := ⟨fun h => by simp [h] at hroot⟩ rw [isRoot_cyclotomic_iff (R := ℂ)] at hroot replace hprim := hprim.eq_orderOf rwa [← IsPrimitiveRoot.eq_orderOf hroot] at hprim /-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/ theorem _root_.IsPrimitiveRoot.minpoly_dvd_cyclotomic {n : ℕ} {K : Type*} [Field K] {μ : K} (h : IsPrimitiveRoot μ n) (hpos : 0 < n) [CharZero K] : minpoly ℤ μ ∣ cyclotomic n ℤ := by apply minpoly.isIntegrallyClosed_dvd (h.isIntegral hpos) simpa [aeval_def, eval₂_eq_eval_map, IsRoot.def] using h.isRoot_cyclotomic hpos section minpoly open IsPrimitiveRoot Complex theorem _root_.IsPrimitiveRoot.minpoly_eq_cyclotomic_of_irreducible {K : Type*} [Field K] {R : Type*} [CommRing R] [IsDomain R] {μ : R} {n : ℕ} [Algebra K R] (hμ : IsPrimitiveRoot μ n) (h : Irreducible <| cyclotomic n K) [NeZero (n : K)] : cyclotomic n K = minpoly K μ := by haveI := NeZero.of_faithfulSMul K R n refine minpoly.eq_of_irreducible_of_monic h ?_ (cyclotomic.monic n K) rwa [aeval_def, eval₂_eq_eval_map, map_cyclotomic, ← IsRoot.def, isRoot_cyclotomic_iff] /-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ theorem cyclotomic_eq_minpoly {n : ℕ} {K : Type*} [Field K] {μ : K} (h : IsPrimitiveRoot μ n) (hpos : 0 < n) [CharZero K] : cyclotomic n ℤ = minpoly ℤ μ := by refine eq_of_monic_of_dvd_of_natDegree_le (minpoly.monic (IsPrimitiveRoot.isIntegral h hpos)) (cyclotomic.monic n ℤ) (h.minpoly_dvd_cyclotomic hpos) ?_ simpa [natDegree_cyclotomic n ℤ] using totient_le_degree_minpoly h /-- `cyclotomic n ℚ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ theorem cyclotomic_eq_minpoly_rat {n : ℕ} {K : Type*} [Field K] {μ : K} (h : IsPrimitiveRoot μ n) (hpos : 0 < n) [CharZero K] : cyclotomic n ℚ = minpoly ℚ μ := by rw [← map_cyclotomic_int, cyclotomic_eq_minpoly h hpos] exact (minpoly.isIntegrallyClosed_eq_field_fractions' _ (IsPrimitiveRoot.isIntegral h hpos)).symm /-- `cyclotomic n ℤ` is irreducible. -/ theorem cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : Irreducible (cyclotomic n ℤ) := by rw [cyclotomic_eq_minpoly (isPrimitiveRoot_exp n hpos.ne') hpos] apply minpoly.irreducible exact (isPrimitiveRoot_exp n hpos.ne').isIntegral hpos /-- `cyclotomic n ℚ` is irreducible. -/ theorem cyclotomic.irreducible_rat {n : ℕ} (hpos : 0 < n) : Irreducible (cyclotomic n ℚ) := by rw [← map_cyclotomic_int] exact (IsPrimitive.irreducible_iff_irreducible_map_fraction_map (cyclotomic.isPrimitive n ℤ)).1 (cyclotomic.irreducible hpos) /-- If `n ≠ m`, then `(cyclotomic n ℚ)` and `(cyclotomic m ℚ)` are coprime. -/ theorem cyclotomic.isCoprime_rat {n m : ℕ} (h : n ≠ m) : IsCoprime (cyclotomic n ℚ) (cyclotomic m ℚ) := by rcases n.eq_zero_or_pos with (rfl | hnzero) · exact isCoprime_one_left rcases m.eq_zero_or_pos with (rfl | hmzero) · exact isCoprime_one_right rw [Irreducible.coprime_iff_not_dvd <| cyclotomic.irreducible_rat <| hnzero] exact fun hdiv => h <| cyclotomic_injective <| eq_of_monic_of_associated (cyclotomic.monic n ℚ) (cyclotomic.monic m ℚ) <| Irreducible.associated_of_dvd (cyclotomic.irreducible_rat hnzero) (cyclotomic.irreducible_rat hmzero) hdiv end minpoly end Polynomial
Minpoly.lean
/- Copyright (c) 2024 María Inés de Frutos-Fernández, Filippo A. E. Nuccio. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández, Filippo A. E. Nuccio -/ import Mathlib.FieldTheory.IntermediateField.Adjoin.Basic import Mathlib.RingTheory.Valuation.Basic /-! # Minimal polynomials. We prove some results about valuations of zero coefficients of minimal polynomials. Let `K` be a field with a valuation `v` and let `L` be a field extension of `K`. # Main Results * `coeff_zero_minpoly` : for `x ∈ K` the valuation of the zeroth coefficient of the minimal polynomial of `algebra_map K L x` over `K` is equal to the valuation of `x`. * `pow_coeff_zero_ne_zero_of_unit` : for any unit `x : Lˣ`, we prove that a certain power of the valuation of zeroth coefficient of the minimal polynomial of `x` over `K` is nonzero. This lemma is helpful for defining the valuation on `L` inducing `v`. -/ open Module minpoly Polynomial variable {K : Type*} [Field K] {Γ₀ : Type*} [LinearOrderedCommGroupWithZero Γ₀] (v : Valuation K Γ₀) (L : Type*) [Field L] [Algebra K L] namespace Valuation /-- For `x ∈ K` the valuation of the zeroth coefficient of the minimal polynomial of `algebra_map K L x` over `K` is equal to the valuation of `x`. -/ @[simp] theorem coeff_zero_minpoly (x : K) : v ((minpoly K (algebraMap K L x)).coeff 0) = v x := by rw [minpoly.eq_X_sub_C, coeff_sub, coeff_X_zero, coeff_C_zero, zero_sub, Valuation.map_neg] variable {L} /- For any unit `x : Lˣ`, we prove that a certain power of the valuation of zeroth coefficient of the minimal polynomial of `x` over `K` is nonzero. This lemma is helpful for defining the valuation on `L` inducing `v`. -/ theorem pow_coeff_zero_ne_zero_of_unit [FiniteDimensional K L] (x : L) (hx : IsUnit x) : v ((minpoly K x).coeff 0) ^ (finrank K L / (minpoly K x).natDegree) ≠ (0 : Γ₀) := by have h_alg : Algebra.IsAlgebraic K L := Algebra.IsAlgebraic.of_finite K L have hx₀ : IsIntegral K x := (Algebra.IsAlgebraic.isAlgebraic x).isIntegral have hdeg := Nat.div_pos (natDegree_le x) (natDegree_pos hx₀) rw [ne_eq, pow_eq_zero_iff hdeg.ne.symm, Valuation.zero_iff] exact coeff_zero_ne_zero hx₀ hx.ne_zero end Valuation
Scheme.lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Andrew Yang -/ import Mathlib.AlgebraicGeometry.ProjectiveSpectrum.StructureSheaf import Mathlib.AlgebraicGeometry.GammaSpecAdjunction import Mathlib.RingTheory.GradedAlgebra.Radical /-! # Proj as a scheme This file is to prove that `Proj` is a scheme. ## Notation * `Proj` : `Proj` as a locally ringed space * `Proj.T` : the underlying topological space of `Proj` * `Proj| U` : `Proj` restricted to some open set `U` * `Proj.T| U` : the underlying topological space of `Proj` restricted to open set `U` * `pbo f` : basic open set at `f` in `Proj` * `Spec` : `Spec` as a locally ringed space * `Spec.T` : the underlying topological space of `Spec` * `sbo g` : basic open set at `g` in `Spec` * `A⁰_x` : the degree zero part of localized ring `Aₓ` ## Implementation In `AlgebraicGeometry/ProjectiveSpectrum/StructureSheaf.lean`, we have given `Proj` a structure sheaf so that `Proj` is a locally ringed space. In this file we will prove that `Proj` equipped with this structure sheaf is a scheme. We achieve this by using an affine cover by basic open sets in `Proj`, more specifically: 1. We prove that `Proj` can be covered by basic open sets at homogeneous element of positive degree. 2. We prove that for any homogeneous element `f : A` of positive degree `m`, `Proj.T | (pbo f)` is homeomorphic to `Spec.T A⁰_f`: - forward direction `toSpec`: for any `x : pbo f`, i.e. a relevant homogeneous prime ideal `x`, send it to `A⁰_f ∩ span {g / 1 | g ∈ x}` (see `ProjIsoSpecTopComponent.IoSpec.carrier`). This ideal is prime, the proof is in `ProjIsoSpecTopComponent.ToSpec.toFun`. The fact that this function is continuous is found in `ProjIsoSpecTopComponent.toSpec` - backward direction `fromSpec`: for any `q : Spec A⁰_f`, we send it to `{a | ∀ i, aᵢᵐ/fⁱ ∈ q}`; we need this to be a homogeneous prime ideal that is relevant. * This is in fact an ideal, the proof can be found in `ProjIsoSpecTopComponent.FromSpec.carrier.asIdeal`; * This ideal is also homogeneous, the proof can be found in `ProjIsoSpecTopComponent.FromSpec.carrier.asIdeal.homogeneous`; * This ideal is relevant, the proof can be found in `ProjIsoSpecTopComponent.FromSpec.carrier.relevant`; * This ideal is prime, the proof can be found in `ProjIsoSpecTopComponent.FromSpec.carrier.asIdeal.prime`. Hence we have a well defined function `Spec.T A⁰_f → Proj.T | (pbo f)`, this function is called `ProjIsoSpecTopComponent.FromSpec.toFun`. But to prove the continuity of this function, we need to prove `fromSpec ∘ toSpec` and `toSpec ∘ fromSpec` are both identities; these are achieved in `ProjIsoSpecTopComponent.fromSpec_toSpec` and `ProjIsoSpecTopComponent.toSpec_fromSpec`. 3. Then we construct a morphism of locally ringed spaces `α : Proj| (pbo f) ⟶ Spec.T A⁰_f` as the following: by the Gamma-Spec adjunction, it is sufficient to construct a ring map `A⁰_f → Γ(Proj, pbo f)` from the ring of homogeneous localization of `A` away from `f` to the local sections of structure sheaf of projective spectrum on the basic open set around `f`. The map `A⁰_f → Γ(Proj, pbo f)` is constructed in `awayToΓ` and is defined by sending `s ∈ A⁰_f` to the section `x ↦ s` on `pbo f`. ## Main Definitions and Statements For a homogeneous element `f` of degree `m` * `ProjIsoSpecTopComponent.toSpec`: the continuous map between `Proj.T| pbo f` and `Spec.T A⁰_f` defined by sending `x : Proj| (pbo f)` to `A⁰_f ∩ span {g / 1 | g ∈ x}`. We also denote this map as `ψ`. * `ProjIsoSpecTopComponent.ToSpec.preimage_eq`: for any `a: A`, if `a/f^m` has degree zero, then the preimage of `sbo a/f^m` under `toSpec f` is `pbo f ∩ pbo a`. If we further assume `m` is positive * `ProjIsoSpecTopComponent.fromSpec`: the continuous map between `Spec.T A⁰_f` and `Proj.T| pbo f` defined by sending `q` to `{a | aᵢᵐ/fⁱ ∈ q}` where `aᵢ` is the `i`-th coordinate of `a`. We also denote this map as `φ` * `projIsoSpecTopComponent`: the homeomorphism `Proj.T| pbo f ≅ Spec.T A⁰_f` obtained by `φ` and `ψ`. * `ProjectiveSpectrum.Proj.toSpec`: the morphism of locally ringed spaces between `Proj| pbo f` and `Spec A⁰_f` corresponding to the ring map `A⁰_f → Γ(Proj, pbo f)` under the Gamma-Spec adjunction defined by sending `s` to the section `x ↦ s` on `pbo f`. Finally, * `AlgebraicGeometry.Proj`: for any `ℕ`-graded ring `A`, `Proj A` is locally affine, hence is a scheme. ## Reference * [Robin Hartshorne, *Algebraic Geometry*][Har77]: Chapter II.2 Proposition 2.5 -/ noncomputable section namespace AlgebraicGeometry open scoped DirectSum Pointwise open DirectSum SetLike.GradedMonoid Localization open Finset hiding mk_zero variable {R A : Type*} variable [CommRing R] [CommRing A] [Algebra R A] variable (𝒜 : ℕ → Submodule R A) variable [GradedAlgebra 𝒜] open TopCat TopologicalSpace open CategoryTheory Opposite open ProjectiveSpectrum.StructureSheaf -- Porting note: currently require lack of hygiene to use in variable declarations -- maybe all make into notation3? set_option hygiene false /-- `Proj` as a locally ringed space -/ local notation3 "Proj" => Proj.toLocallyRingedSpace 𝒜 /-- The underlying topological space of `Proj` -/ local notation3 "Proj.T" => PresheafedSpace.carrier <| SheafedSpace.toPresheafedSpace <| LocallyRingedSpace.toSheafedSpace <| Proj.toLocallyRingedSpace 𝒜 /-- `Proj` restrict to some open set -/ macro "Proj| " U:term : term => `((Proj.toLocallyRingedSpace 𝒜).restrict (Opens.isOpenEmbedding (X := Proj.T) ($U : Opens Proj.T))) /-- the underlying topological space of `Proj` restricted to some open set -/ local notation "Proj.T| " U => PresheafedSpace.carrier <| SheafedSpace.toPresheafedSpace <| LocallyRingedSpace.toSheafedSpace <| (LocallyRingedSpace.restrict Proj (Opens.isOpenEmbedding (X := Proj.T) (U : Opens Proj.T))) /-- basic open sets in `Proj` -/ local notation "pbo " x => ProjectiveSpectrum.basicOpen 𝒜 x /-- basic open sets in `Spec` -/ local notation "sbo " f => PrimeSpectrum.basicOpen f /-- `Spec` as a locally ringed space -/ local notation3 "Spec " ring => Spec.locallyRingedSpaceObj (CommRingCat.of ring) /-- the underlying topological space of `Spec` -/ local notation "Spec.T " ring => (Spec.locallyRingedSpaceObj (CommRingCat.of ring)).toSheafedSpace.toPresheafedSpace.1 local notation3 "A⁰_ " f => HomogeneousLocalization.Away 𝒜 f namespace ProjIsoSpecTopComponent /- This section is to construct the homeomorphism between `Proj` restricted at basic open set at a homogeneous element `x` and `Spec A⁰ₓ` where `A⁰ₓ` is the degree zero part of the localized ring `Aₓ`. -/ namespace ToSpec open Ideal -- This section is to construct the forward direction : -- So for any `x` in `Proj| (pbo f)`, we need some point in `Spec A⁰_f`, i.e. a prime ideal, -- and we need this correspondence to be continuous in their Zariski topology. variable {𝒜} variable {f : A} {m : ℕ} (x : Proj| (pbo f)) /-- For any `x` in `Proj| (pbo f)`, the corresponding ideal in `Spec A⁰_f`. This fact that this ideal is prime is proven in `TopComponent.Forward.toFun`. -/ def carrier : Ideal (A⁰_ f) := Ideal.comap (algebraMap (A⁰_ f) (Away f)) (x.val.asHomogeneousIdeal.toIdeal.map (algebraMap A (Away f))) @[simp] theorem mk_mem_carrier (z : HomogeneousLocalization.NumDenSameDeg 𝒜 (.powers f)) : HomogeneousLocalization.mk z ∈ carrier x ↔ z.num.1 ∈ x.1.asHomogeneousIdeal := by rw [carrier, Ideal.mem_comap, HomogeneousLocalization.algebraMap_apply, HomogeneousLocalization.val_mk, Localization.mk_eq_mk', IsLocalization.mk'_eq_mul_mk'_one, mul_comm, Ideal.unit_mul_mem_iff_mem, ← Ideal.mem_comap, IsLocalization.comap_map_of_isPrime_disjoint (.powers f)] · rfl · infer_instance · exact (disjoint_powers_iff_notMem _ (Ideal.IsPrime.isRadical inferInstance)).mpr x.2 · exact isUnit_of_invertible _ theorem isPrime_carrier : Ideal.IsPrime (carrier x) := by refine Ideal.IsPrime.comap _ (hK := ?_) exact IsLocalization.isPrime_of_isPrime_disjoint (Submonoid.powers f) _ _ inferInstance ((disjoint_powers_iff_notMem _ (Ideal.IsPrime.isRadical inferInstance)).mpr x.2) variable (f) /-- The function between the basic open set `D(f)` in `Proj` to the corresponding basic open set in `Spec A⁰_f`. This is bundled into a continuous map in `TopComponent.forward`. -/ @[simps -isSimp] def toFun (x : Proj.T| pbo f) : Spec.T A⁰_ f := ⟨carrier x, isPrime_carrier x⟩ /- The preimage of basic open set `D(a/f^n)` in `Spec A⁰_f` under the forward map from `Proj A` to `Spec A⁰_f` is the basic open set `D(a) ∩ D(f)` in `Proj A`. This lemma is used to prove that the forward map is continuous. -/ theorem preimage_basicOpen (z : HomogeneousLocalization.NumDenSameDeg 𝒜 (.powers f)) : toFun f ⁻¹' (sbo (HomogeneousLocalization.mk z) : Set (PrimeSpectrum (A⁰_ f))) = Subtype.val ⁻¹' (pbo z.num.1 : Set (ProjectiveSpectrum 𝒜)) := Set.ext fun y ↦ (mk_mem_carrier y z).not end ToSpec section /-- The continuous function from the basic open set `D(f)` in `Proj` to the corresponding basic open set in `Spec A⁰_f`. -/ @[simps! -isSimp hom_apply_asIdeal] def toSpec (f : A) : (Proj.T| pbo f) ⟶ Spec.T A⁰_ f := TopCat.ofHom { toFun := ToSpec.toFun f continuous_toFun := by rw [PrimeSpectrum.isTopologicalBasis_basic_opens.continuous_iff] rintro _ ⟨x, rfl⟩ obtain ⟨x, rfl⟩ := Quotient.mk''_surjective x rw [ToSpec.preimage_basicOpen] exact (pbo x.num).2.preimage continuous_subtype_val } variable {𝒜} in lemma toSpec_preimage_basicOpen {f} (z : HomogeneousLocalization.NumDenSameDeg 𝒜 (.powers f)) : toSpec 𝒜 f ⁻¹' (sbo (HomogeneousLocalization.mk z) : Set (PrimeSpectrum (A⁰_ f))) = Subtype.val ⁻¹' (pbo z.num.1 : Set (ProjectiveSpectrum 𝒜)) := ToSpec.preimage_basicOpen f z end namespace FromSpec open GradedAlgebra SetLike open Finset hiding mk_zero open HomogeneousLocalization variable {𝒜} variable {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) open Lean Meta Elab Tactic macro "mem_tac_aux" : tactic => `(tactic| first | exact pow_mem_graded _ (Submodule.coe_mem _) | exact natCast_mem_graded _ _ | exact pow_mem_graded _ f_deg) macro "mem_tac" : tactic => `(tactic| first | mem_tac_aux | repeat (all_goals (apply SetLike.GradedMonoid.toGradedMul.mul_mem)); mem_tac_aux) /-- The function from `Spec A⁰_f` to `Proj|D(f)` is defined by `q ↦ {a | aᵢᵐ/fⁱ ∈ q}`, i.e. sending `q` a prime ideal in `A⁰_f` to the homogeneous prime relevant ideal containing only and all the elements `a : A` such that for every `i`, the degree 0 element formed by dividing the `m`-th power of the `i`-th projection of `a` by the `i`-th power of the degree-`m` homogeneous element `f`, lies in `q`. The set `{a | aᵢᵐ/fⁱ ∈ q}` * is an ideal, as proved in `carrier.asIdeal`; * is homogeneous, as proved in `carrier.asHomogeneousIdeal`; * is prime, as proved in `carrier.asIdeal.prime`; * is relevant, as proved in `carrier.relevant`. -/ def carrier (f_deg : f ∈ 𝒜 m) (q : Spec.T A⁰_ f) : Set A := {a | ∀ i, (HomogeneousLocalization.mk ⟨m * i, ⟨proj 𝒜 i a ^ m, by rw [← smul_eq_mul]; mem_tac⟩, ⟨f ^ i, by rw [mul_comm]; mem_tac⟩, ⟨_, rfl⟩⟩ : A⁰_ f) ∈ q.1} theorem mem_carrier_iff (q : Spec.T A⁰_ f) (a : A) : a ∈ carrier f_deg q ↔ ∀ i, (HomogeneousLocalization.mk ⟨m * i, ⟨proj 𝒜 i a ^ m, by rw [← smul_eq_mul]; mem_tac⟩, ⟨f ^ i, by rw [mul_comm]; mem_tac⟩, ⟨_, rfl⟩⟩ : A⁰_ f) ∈ q.1 := Iff.rfl theorem mem_carrier_iff' (q : Spec.T A⁰_ f) (a : A) : a ∈ carrier f_deg q ↔ ∀ i, (Localization.mk (proj 𝒜 i a ^ m) ⟨f ^ i, ⟨i, rfl⟩⟩ : Localization.Away f) ∈ algebraMap (HomogeneousLocalization.Away 𝒜 f) (Localization.Away f) '' { s | s ∈ q.1 } := (mem_carrier_iff f_deg q a).trans (by constructor <;> intro h i <;> specialize h i · rw [Set.mem_image]; refine ⟨_, h, rfl⟩ · rw [Set.mem_image] at h; rcases h with ⟨x, h, hx⟩ change x ∈ q.asIdeal at h convert h rw [HomogeneousLocalization.ext_iff_val, HomogeneousLocalization.val_mk] dsimp only [Subtype.coe_mk]; rw [← hx]; rfl) theorem mem_carrier_iff_of_mem (hm : 0 < m) (q : Spec.T A⁰_ f) (a : A) {n} (hn : a ∈ 𝒜 n) : a ∈ carrier f_deg q ↔ (HomogeneousLocalization.mk ⟨m * n, ⟨a ^ m, pow_mem_graded m hn⟩, ⟨f ^ n, by rw [mul_comm]; mem_tac⟩, ⟨_, rfl⟩⟩ : A⁰_ f) ∈ q.asIdeal := by trans (HomogeneousLocalization.mk ⟨m * n, ⟨proj 𝒜 n a ^ m, by rw [← smul_eq_mul]; mem_tac⟩, ⟨f ^ n, by rw [mul_comm]; mem_tac⟩, ⟨_, rfl⟩⟩ : A⁰_ f) ∈ q.asIdeal · refine ⟨fun h ↦ h n, fun h i ↦ if hi : i = n then hi ▸ h else ?_⟩ convert zero_mem q.asIdeal apply HomogeneousLocalization.val_injective simp only [proj_apply, decompose_of_mem_ne _ hn (Ne.symm hi), zero_pow hm.ne', HomogeneousLocalization.val_mk, Localization.mk_zero, HomogeneousLocalization.val_zero] · simp only [proj_apply, decompose_of_mem_same _ hn] theorem mem_carrier_iff_of_mem_mul (hm : 0 < m) (q : Spec.T A⁰_ f) (a : A) {n} (hn : a ∈ 𝒜 (n * m)) : a ∈ carrier f_deg q ↔ (HomogeneousLocalization.mk ⟨m * n, ⟨a, mul_comm n m ▸ hn⟩, ⟨f ^ n, by rw [mul_comm]; mem_tac⟩, ⟨_, rfl⟩⟩ : A⁰_ f) ∈ q.asIdeal := by rw [mem_carrier_iff_of_mem f_deg hm q a hn, iff_iff_eq, eq_comm, ← Ideal.IsPrime.pow_mem_iff_mem (α := A⁰_ f) inferInstance m hm] congr 1 apply HomogeneousLocalization.val_injective simp only [HomogeneousLocalization.val_mk, HomogeneousLocalization.val_pow, Localization.mk_pow, pow_mul] rfl theorem num_mem_carrier_iff (hm : 0 < m) (q : Spec.T A⁰_ f) (z : HomogeneousLocalization.NumDenSameDeg 𝒜 (.powers f)) : z.num.1 ∈ carrier f_deg q ↔ HomogeneousLocalization.mk z ∈ q.asIdeal := by obtain ⟨n, hn : f ^ n = _⟩ := z.den_mem have : f ^ n ≠ 0 := fun e ↦ by have := HomogeneousLocalization.subsingleton 𝒜 (x := .powers f) ⟨n, e⟩ exact IsEmpty.elim (inferInstanceAs (IsEmpty (PrimeSpectrum (A⁰_ f)))) q convert mem_carrier_iff_of_mem_mul f_deg hm q z.num.1 (n := n) ?_ using 2 · apply HomogeneousLocalization.val_injective; simp only [hn, HomogeneousLocalization.val_mk] · have := degree_eq_of_mem_mem 𝒜 (SetLike.pow_mem_graded n f_deg) (hn.symm ▸ z.den.2) this rw [← smul_eq_mul, this]; exact z.num.2 theorem carrier.add_mem (q : Spec.T A⁰_ f) {a b : A} (ha : a ∈ carrier f_deg q) (hb : b ∈ carrier f_deg q) : a + b ∈ carrier f_deg q := by refine fun i => (q.2.mem_or_mem ?_).elim id id change (HomogeneousLocalization.mk ⟨_, _, _, _⟩ : A⁰_ f) ∈ q.1; dsimp only [Subtype.coe_mk] simp_rw [← pow_add, map_add, add_pow, mul_comm, ← nsmul_eq_mul] let g : ℕ → A⁰_ f := fun j => (m + m).choose j • if h2 : m + m < j then (0 : A⁰_ f) else if h1 : j ≤ m then (HomogeneousLocalization.mk ⟨m * i, ⟨proj 𝒜 i a ^ j * proj 𝒜 i b ^ (m - j), ?_⟩, ⟨_, by rw [mul_comm]; mem_tac⟩, ⟨i, rfl⟩⟩ : A⁰_ f) * (HomogeneousLocalization.mk ⟨m * i, ⟨proj 𝒜 i b ^ m, by rw [← smul_eq_mul]; mem_tac⟩, ⟨_, by rw [mul_comm]; mem_tac⟩, ⟨i, rfl⟩⟩ : A⁰_ f) else (HomogeneousLocalization.mk ⟨m * i, ⟨proj 𝒜 i a ^ m, by rw [← smul_eq_mul]; mem_tac⟩, ⟨_, by rw [mul_comm]; mem_tac⟩, ⟨i, rfl⟩⟩ : A⁰_ f) * (HomogeneousLocalization.mk ⟨m * i, ⟨proj 𝒜 i a ^ (j - m) * proj 𝒜 i b ^ (m + m - j), ?_⟩, ⟨_, by rw [mul_comm]; mem_tac⟩, ⟨i, rfl⟩⟩ : A⁰_ f) rotate_left · rw [(_ : m * i = _)] apply GradedMonoid.toGradedMul.mul_mem <;> mem_tac_aux rw [← add_smul, Nat.add_sub_of_le h1]; rfl · rw [(_ : m * i = _)] apply GradedMonoid.toGradedMul.mul_mem (i := (j-m) • i) (j := (m + m - j) • i) <;> mem_tac_aux rw [← add_smul]; congr; omega convert_to ∑ i ∈ range (m + m + 1), g i ∈ q.1; swap · refine q.1.sum_mem fun j _ => nsmul_mem ?_ _; split_ifs exacts [q.1.zero_mem, q.1.mul_mem_left _ (hb i), q.1.mul_mem_right _ (ha i)] rw [HomogeneousLocalization.ext_iff_val, HomogeneousLocalization.val_mk] change _ = (algebraMap (HomogeneousLocalization.Away 𝒜 f) (Localization.Away f)) _ dsimp only [Subtype.coe_mk]; rw [map_sum, mk_sum] apply Finset.sum_congr rfl fun j hj => _ intro j hj change _ = HomogeneousLocalization.val _ rw [HomogeneousLocalization.val_smul] split_ifs with h2 h1 · exact ((Finset.mem_range.1 hj).not_ge h2).elim all_goals simp only [HomogeneousLocalization.val_mul, HomogeneousLocalization.val_mk, Localization.mk_mul, ← smul_mk]; congr 2 · dsimp; rw [mul_assoc, ← pow_add, add_comm (m - j), Nat.add_sub_assoc h1] · simp_rw [pow_add]; rfl · dsimp; rw [← mul_assoc, ← pow_add, Nat.add_sub_of_le (le_of_not_ge h1)] · simp_rw [pow_add]; rfl variable (hm : 0 < m) (q : Spec.T A⁰_ f) include hm theorem carrier.zero_mem : (0 : A) ∈ carrier f_deg q := fun i => by convert Submodule.zero_mem q.1 using 1 rw [HomogeneousLocalization.ext_iff_val, HomogeneousLocalization.val_mk, HomogeneousLocalization.val_zero]; simp_rw [map_zero, zero_pow hm.ne'] convert Localization.mk_zero (S := Submonoid.powers f) _ using 1 theorem carrier.smul_mem (c x : A) (hx : x ∈ carrier f_deg q) : c • x ∈ carrier f_deg q := by revert c refine DirectSum.Decomposition.inductionOn 𝒜 ?_ ?_ ?_ · rw [zero_smul]; exact carrier.zero_mem f_deg hm _ · rintro n ⟨a, ha⟩ i simp_rw [proj_apply, smul_eq_mul, coe_decompose_mul_of_left_mem 𝒜 i ha] let product : A⁰_ f := (HomogeneousLocalization.mk ⟨_, ⟨a ^ m, pow_mem_graded m ha⟩, ⟨_, ?_⟩, ⟨n, rfl⟩⟩ : A⁰_ f) * (HomogeneousLocalization.mk ⟨_, ⟨proj 𝒜 (i - n) x ^ m, by mem_tac⟩, ⟨_, ?_⟩, ⟨i - n, rfl⟩⟩ : A⁰_ f) · split_ifs with h · convert_to product ∈ q.1 · dsimp [product] rw [HomogeneousLocalization.ext_iff_val, HomogeneousLocalization.val_mk, HomogeneousLocalization.val_mul, HomogeneousLocalization.val_mk, HomogeneousLocalization.val_mk] · simp_rw [mul_pow]; rw [Localization.mk_mul] · congr; rw [← pow_add, Nat.add_sub_of_le h] · apply Ideal.mul_mem_left (α := A⁰_ f) _ _ (hx _) rw [(_ : m • n = _)] · mem_tac · simp only [smul_eq_mul, mul_comm] · simpa only [map_zero, zero_pow hm.ne'] using zero_mem f_deg hm q i rw [(_ : m • (i - n) = _)] · mem_tac · simp only [smul_eq_mul, mul_comm] · simp_rw [add_smul]; exact fun _ _ => carrier.add_mem f_deg q /-- For a prime ideal `q` in `A⁰_f`, the set `{a | aᵢᵐ/fⁱ ∈ q}` as an ideal. -/ def carrier.asIdeal : Ideal A where carrier := carrier f_deg q zero_mem' := carrier.zero_mem f_deg hm q add_mem' := carrier.add_mem f_deg q smul_mem' := carrier.smul_mem f_deg hm q theorem carrier.asIdeal.homogeneous : (carrier.asIdeal f_deg hm q).IsHomogeneous 𝒜 := fun i a ha j => (em (i = j)).elim (fun h => h ▸ by simpa only [proj_apply, decompose_coe, of_eq_same] using ha _) fun h => by simpa only [proj_apply, decompose_of_mem_ne 𝒜 (Submodule.coe_mem (decompose 𝒜 a i)) h, zero_pow hm.ne', map_zero] using carrier.zero_mem f_deg hm q j /-- For a prime ideal `q` in `A⁰_f`, the set `{a | aᵢᵐ/fⁱ ∈ q}` as a homogeneous ideal. -/ def carrier.asHomogeneousIdeal : HomogeneousIdeal 𝒜 := ⟨carrier.asIdeal f_deg hm q, carrier.asIdeal.homogeneous f_deg hm q⟩ theorem carrier.denom_notMem : f ∉ carrier.asIdeal f_deg hm q := fun rid => q.isPrime.ne_top <| (Ideal.eq_top_iff_one _).mpr (by convert rid m rw [HomogeneousLocalization.ext_iff_val, HomogeneousLocalization.val_one, HomogeneousLocalization.val_mk] dsimp simp_rw [decompose_of_mem_same _ f_deg] simp only [mk_eq_monoidOf_mk', Submonoid.LocalizationMap.mk'_self]) @[deprecated (since := "2025-05-23")] alias carrier.denom_not_mem := carrier.denom_notMem theorem carrier.relevant : ¬HomogeneousIdeal.irrelevant 𝒜 ≤ carrier.asHomogeneousIdeal f_deg hm q := fun rid => carrier.denom_notMem f_deg hm q <| rid <| DirectSum.decompose_of_mem_ne 𝒜 f_deg hm.ne' theorem carrier.asIdeal.ne_top : carrier.asIdeal f_deg hm q ≠ ⊤ := fun rid => carrier.denom_notMem f_deg hm q (rid.symm ▸ Submodule.mem_top) theorem carrier.asIdeal.prime : (carrier.asIdeal f_deg hm q).IsPrime := (carrier.asIdeal.homogeneous f_deg hm q).isPrime_of_homogeneous_mem_or_mem (carrier.asIdeal.ne_top f_deg hm q) fun {x y} ⟨nx, hnx⟩ ⟨ny, hny⟩ hxy => show (∀ _, _ ∈ _) ∨ ∀ _, _ ∈ _ by rw [← and_forall_ne nx, and_iff_left, ← and_forall_ne ny, and_iff_left] · apply q.2.mem_or_mem; convert hxy (nx + ny) using 1 dsimp simp_rw [decompose_of_mem_same 𝒜 hnx, decompose_of_mem_same 𝒜 hny, decompose_of_mem_same 𝒜 (SetLike.GradedMonoid.toGradedMul.mul_mem hnx hny), mul_pow, pow_add] simp only [HomogeneousLocalization.ext_iff_val, HomogeneousLocalization.val_mk, HomogeneousLocalization.val_mul, Localization.mk_mul] simp only [Submonoid.mk_mul_mk, mk_eq_monoidOf_mk'] all_goals intro n hn; convert q.1.zero_mem using 1 rw [HomogeneousLocalization.ext_iff_val, HomogeneousLocalization.val_mk, HomogeneousLocalization.val_zero]; simp_rw [proj_apply] convert mk_zero (S := Submonoid.powers f) _ rw [decompose_of_mem_ne 𝒜 _ hn.symm, zero_pow hm.ne'] · first | exact hnx | exact hny /-- The function `Spec A⁰_f → Proj|D(f)` sending `q` to `{a | aᵢᵐ/fⁱ ∈ q}`. -/ def toFun : (Spec.T A⁰_ f) → Proj.T| pbo f := fun q => ⟨⟨carrier.asHomogeneousIdeal f_deg hm q, carrier.asIdeal.prime f_deg hm q, carrier.relevant f_deg hm q⟩, (ProjectiveSpectrum.mem_basicOpen _ f _).mp <| carrier.denom_notMem f_deg hm q⟩ end FromSpec section toSpecFromSpec lemma toSpec_fromSpec {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) (x : Spec.T (A⁰_ f)) : toSpec 𝒜 f (FromSpec.toFun f_deg hm x) = x := by apply PrimeSpectrum.ext ext z obtain ⟨z, rfl⟩ := HomogeneousLocalization.mk_surjective z rw [← FromSpec.num_mem_carrier_iff f_deg hm x] exact ToSpec.mk_mem_carrier _ z end toSpecFromSpec section fromSpecToSpec lemma fromSpec_toSpec {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) (x : Proj.T| pbo f) : FromSpec.toFun f_deg hm (toSpec 𝒜 f x) = x := by refine Subtype.ext <| ProjectiveSpectrum.ext <| HomogeneousIdeal.ext' ?_ intros i z hzi refine (FromSpec.mem_carrier_iff_of_mem f_deg hm _ _ hzi).trans ?_ exact (ToSpec.mk_mem_carrier _ _).trans (x.1.2.pow_mem_iff_mem m hm) lemma toSpec_injective {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : Function.Injective (toSpec 𝒜 f) := by intro x₁ x₂ h have := congr_arg (FromSpec.toFun f_deg hm) h rwa [fromSpec_toSpec, fromSpec_toSpec] at this lemma toSpec_surjective {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : Function.Surjective (toSpec 𝒜 f) := Function.surjective_iff_hasRightInverse |>.mpr ⟨FromSpec.toFun f_deg hm, toSpec_fromSpec 𝒜 f_deg hm⟩ lemma toSpec_bijective {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : Function.Bijective (toSpec (𝒜 := 𝒜) (f := f)) := ⟨toSpec_injective 𝒜 f_deg hm, toSpec_surjective 𝒜 f_deg hm⟩ end fromSpecToSpec namespace toSpec variable {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) include hm f_deg variable {𝒜} in lemma image_basicOpen_eq_basicOpen (a : A) (i : ℕ) : toSpec 𝒜 f '' (Subtype.val ⁻¹' (pbo (decompose 𝒜 a i) : Set (ProjectiveSpectrum 𝒜))) = (PrimeSpectrum.basicOpen (R := A⁰_ f) <| HomogeneousLocalization.mk ⟨m * i, ⟨decompose 𝒜 a i ^ m, smul_eq_mul m i ▸ SetLike.pow_mem_graded _ (Submodule.coe_mem _)⟩, ⟨f^i, by rw [mul_comm]; exact SetLike.pow_mem_graded _ f_deg⟩, ⟨i, rfl⟩⟩).1 := Set.preimage_injective.mpr (toSpec_surjective 𝒜 f_deg hm) <| Set.preimage_image_eq _ (toSpec_injective 𝒜 f_deg hm) ▸ by rw [Opens.carrier_eq_coe, toSpec_preimage_basicOpen, ProjectiveSpectrum.basicOpen_pow 𝒜 _ m hm] end toSpec variable {𝒜} in /-- The continuous function `Spec A⁰_f → Proj|D(f)` sending `q` to `{a | aᵢᵐ/fⁱ ∈ q}` where `m` is the degree of `f` -/ def fromSpec {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : (Spec.T (A⁰_ f)) ⟶ (Proj.T| (pbo f)) := TopCat.ofHom { toFun := FromSpec.toFun f_deg hm continuous_toFun := by rw [isTopologicalBasis_subtype (ProjectiveSpectrum.isTopologicalBasis_basic_opens 𝒜) (pbo f).1 |>.continuous_iff] rintro s ⟨_, ⟨a, rfl⟩, rfl⟩ have h₁ : Subtype.val (p := (pbo f).1) ⁻¹' (pbo a) = ⋃ i : ℕ, Subtype.val (p := (pbo f).1) ⁻¹' (pbo (decompose 𝒜 a i)) := by simp [ProjectiveSpectrum.basicOpen_eq_union_of_projection 𝒜 a] let e : _ ≃ _ := ⟨FromSpec.toFun f_deg hm, ToSpec.toFun f, toSpec_fromSpec _ _ _, fromSpec_toSpec _ _ _⟩ change IsOpen <| e ⁻¹' _ rw [Set.preimage_equiv_eq_image_symm, h₁, Set.image_iUnion] exact isOpen_iUnion fun i ↦ toSpec.image_basicOpen_eq_basicOpen f_deg hm a i ▸ PrimeSpectrum.isOpen_basicOpen } end ProjIsoSpecTopComponent variable {𝒜} in /-- The homeomorphism `Proj|D(f) ≅ Spec A⁰_f` defined by - `φ : Proj|D(f) ⟶ Spec A⁰_f` by sending `x` to `A⁰_f ∩ span {g / 1 | g ∈ x}` - `ψ : Spec A⁰_f ⟶ Proj|D(f)` by sending `q` to `{a | aᵢᵐ/fⁱ ∈ q}`. -/ def projIsoSpecTopComponent {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : (Proj.T| (pbo f)) ≅ (Spec.T (A⁰_ f)) where hom := ProjIsoSpecTopComponent.toSpec 𝒜 f inv := ProjIsoSpecTopComponent.fromSpec f_deg hm hom_inv_id := ConcreteCategory.hom_ext _ _ (ProjIsoSpecTopComponent.fromSpec_toSpec 𝒜 f_deg hm) inv_hom_id := ConcreteCategory.hom_ext _ _ (ProjIsoSpecTopComponent.toSpec_fromSpec 𝒜 f_deg hm) namespace ProjectiveSpectrum.Proj /-- The ring map from `A⁰_ f` to the local sections of the structure sheaf of the projective spectrum of `A` on the basic open set `D(f)` defined by sending `s ∈ A⁰_f` to the section `x ↦ s` on `D(f)`. -/ def awayToSection (f) : CommRingCat.of (A⁰_ f) ⟶ (structureSheaf 𝒜).1.obj (op (pbo f)) := CommRingCat.ofHom -- Have to hint `S`, otherwise it gets unfolded to `structureSheafInType` -- causing `ext` to fail (S := (structureSheaf 𝒜).1.obj (op (pbo f))) { toFun s := ⟨fun x ↦ HomogeneousLocalization.mapId 𝒜 (Submonoid.powers_le.mpr x.2) s, fun x ↦ by obtain ⟨s, rfl⟩ := HomogeneousLocalization.mk_surjective s obtain ⟨n, hn : f ^ n = s.den.1⟩ := s.den_mem exact ⟨_, x.2, 𝟙 _, s.1, s.2, s.3, fun x hsx ↦ x.2 (Ideal.IsPrime.mem_of_pow_mem inferInstance n (hn ▸ hsx)), fun _ ↦ rfl⟩⟩ map_add' _ _ := by ext; simp only [map_add, HomogeneousLocalization.val_add, Proj.add_apply] map_mul' _ _ := by ext; simp only [map_mul, HomogeneousLocalization.val_mul, Proj.mul_apply] map_zero' := by ext; simp only [map_zero, HomogeneousLocalization.val_zero, Proj.zero_apply] map_one' := by ext; simp only [map_one, HomogeneousLocalization.val_one, Proj.one_apply] } lemma awayToSection_germ (f x hx) : awayToSection 𝒜 f ≫ (structureSheaf 𝒜).presheaf.germ _ x hx = CommRingCat.ofHom (HomogeneousLocalization.mapId 𝒜 (Submonoid.powers_le.mpr hx)) ≫ (Proj.stalkIso' 𝒜 x).toCommRingCatIso.inv := by ext z apply (Proj.stalkIso' 𝒜 x).eq_symm_apply.mpr apply Proj.stalkIso'_germ lemma awayToSection_apply (f : A) (x p) : (((ProjectiveSpectrum.Proj.awayToSection 𝒜 f).1 x).val p).val = IsLocalization.map (M := Submonoid.powers f) (T := p.1.1.toIdeal.primeCompl) _ (RingHom.id _) (Submonoid.powers_le.mpr p.2) x.val := by obtain ⟨x, rfl⟩ := HomogeneousLocalization.mk_surjective x change (HomogeneousLocalization.mapId 𝒜 _ _).val = _ dsimp [HomogeneousLocalization.mapId, HomogeneousLocalization.map] rw [Localization.mk_eq_mk', Localization.mk_eq_mk', IsLocalization.map_mk'] rfl /-- The ring map from `A⁰_ f` to the global sections of the structure sheaf of the projective spectrum of `A` restricted to the basic open set `D(f)`. Mathematically, the map is the same as `awayToSection`. -/ def awayToΓ (f) : CommRingCat.of (A⁰_ f) ⟶ LocallyRingedSpace.Γ.obj (op <| Proj| pbo f) := awayToSection 𝒜 f ≫ (ProjectiveSpectrum.Proj.structureSheaf 𝒜).1.map (homOfLE (Opens.isOpenEmbedding_obj_top _).le).op lemma awayToΓ_ΓToStalk (f) (x) : awayToΓ 𝒜 f ≫ (Proj| pbo f).presheaf.Γgerm x = CommRingCat.ofHom (HomogeneousLocalization.mapId 𝒜 (Submonoid.powers_le.mpr x.2)) ≫ (Proj.stalkIso' 𝒜 x.1).toCommRingCatIso.inv ≫ ((Proj.toLocallyRingedSpace 𝒜).restrictStalkIso (Opens.isOpenEmbedding _) x).inv := by rw [awayToΓ, Category.assoc, ← Category.assoc _ (Iso.inv _), Iso.eq_comp_inv, Category.assoc, Category.assoc, Presheaf.Γgerm] rw [LocallyRingedSpace.restrictStalkIso_hom_eq_germ] simp only [Proj.toLocallyRingedSpace, Proj.toSheafedSpace] rw [Presheaf.germ_res, awayToSection_germ] rfl /-- The morphism of locally ringed space from `Proj|D(f)` to `Spec A⁰_f` induced by the ring map `A⁰_ f → Γ(Proj, D(f))` under the gamma spec adjunction. -/ def toSpec (f) : (Proj| pbo f) ⟶ Spec (A⁰_ f) := ΓSpec.locallyRingedSpaceAdjunction.homEquiv (Proj| pbo f) (op (CommRingCat.of <| A⁰_ f)) (awayToΓ 𝒜 f).op open HomogeneousLocalization IsLocalRing lemma toSpec_base_apply_eq_comap {f} (x : Proj| pbo f) : (toSpec 𝒜 f).base x = PrimeSpectrum.comap (mapId 𝒜 (Submonoid.powers_le.mpr x.2)) (closedPoint (AtPrime 𝒜 x.1.asHomogeneousIdeal.toIdeal)) := by change PrimeSpectrum.comap (awayToΓ 𝒜 f ≫ (Proj| pbo f).presheaf.Γgerm x).hom (IsLocalRing.closedPoint ((Proj| pbo f).presheaf.stalk x)) = _ rw [awayToΓ_ΓToStalk, CommRingCat.hom_comp, PrimeSpectrum.comap_comp] exact congr(PrimeSpectrum.comap _ $(@IsLocalRing.comap_closedPoint (HomogeneousLocalization.AtPrime 𝒜 x.1.asHomogeneousIdeal.toIdeal) _ _ ((Proj| pbo f).presheaf.stalk x) _ _ _ (isLocalHom_of_isIso _))) lemma toSpec_base_apply_eq {f} (x : Proj| pbo f) : (toSpec 𝒜 f).base x = ProjIsoSpecTopComponent.toSpec 𝒜 f x := toSpec_base_apply_eq_comap 𝒜 x |>.trans <| PrimeSpectrum.ext <| Ideal.ext fun z => show ¬ IsUnit _ ↔ z ∈ ProjIsoSpecTopComponent.ToSpec.carrier _ by obtain ⟨z, rfl⟩ := z.mk_surjective rw [← HomogeneousLocalization.isUnit_iff_isUnit_val, ProjIsoSpecTopComponent.ToSpec.mk_mem_carrier, HomogeneousLocalization.map_mk, HomogeneousLocalization.val_mk, Localization.mk_eq_mk', IsLocalization.AtPrime.isUnit_mk'_iff] exact not_not lemma toSpec_base_isIso {f} {m} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : IsIso (toSpec 𝒜 f).base := by convert (projIsoSpecTopComponent f_deg hm).isIso_hom exact ConcreteCategory.hom_ext _ _ <| toSpec_base_apply_eq 𝒜 lemma mk_mem_toSpec_base_apply {f} (x : Proj| pbo f) (z : NumDenSameDeg 𝒜 (.powers f)) : HomogeneousLocalization.mk z ∈ ((toSpec 𝒜 f).base x).asIdeal ↔ z.num.1 ∈ x.1.asHomogeneousIdeal := (toSpec_base_apply_eq 𝒜 x).symm ▸ ProjIsoSpecTopComponent.ToSpec.mk_mem_carrier _ _ lemma toSpec_preimage_basicOpen {f} (t : NumDenSameDeg 𝒜 (.powers f)) : (Opens.map (toSpec 𝒜 f).base).obj (sbo (HomogeneousLocalization.mk t)) = Opens.comap ⟨_, continuous_subtype_val⟩ (pbo t.num.1) := Opens.ext <| Opens.map_coe _ _ ▸ by convert (ProjIsoSpecTopComponent.ToSpec.preimage_basicOpen f t) exact funext fun _ => toSpec_base_apply_eq _ _ @[reassoc] lemma toOpen_toSpec_val_c_app (f) (U) : StructureSheaf.toOpen (A⁰_ f) U.unop ≫ (toSpec 𝒜 f).c.app U = awayToΓ 𝒜 f ≫ (Proj| pbo f).presheaf.map (homOfLE le_top).op := Eq.trans (by congr) <| ΓSpec.toOpen_comp_locallyRingedSpaceAdjunction_homEquiv_app _ U @[reassoc] lemma toStalk_stalkMap_toSpec (f) (x) : StructureSheaf.toStalk _ _ ≫ (toSpec 𝒜 f).stalkMap x = awayToΓ 𝒜 f ≫ (Proj| pbo f).presheaf.Γgerm x := by rw [StructureSheaf.toStalk, Category.assoc] simp_rw [← Spec.locallyRingedSpaceObj_presheaf'] rw [LocallyRingedSpace.stalkMap_germ (toSpec 𝒜 f), toOpen_toSpec_val_c_app_assoc, Presheaf.germ_res] rfl /-- If `x` is a point in the basic open set `D(f)` where `f` is a homogeneous element of positive degree, then the homogeneously localized ring `A⁰ₓ` has the universal property of the localization of `A⁰_f` at `φ(x)` where `φ : Proj|D(f) ⟶ Spec A⁰_f` is the morphism of locally ringed space constructed as above. -/ lemma isLocalization_atPrime (f) (x : pbo f) {m} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : @IsLocalization (Away 𝒜 f) _ ((toSpec 𝒜 f).base x).asIdeal.primeCompl (AtPrime 𝒜 x.1.asHomogeneousIdeal.toIdeal) _ (mapId 𝒜 (Submonoid.powers_le.mpr x.2)).toAlgebra := by letI : Algebra (Away 𝒜 f) (AtPrime 𝒜 x.1.asHomogeneousIdeal.toIdeal) := (mapId 𝒜 (Submonoid.powers_le.mpr x.2)).toAlgebra constructor · rintro ⟨y, hy⟩ obtain ⟨y, rfl⟩ := HomogeneousLocalization.mk_surjective y refine isUnit_of_mul_eq_one _ (.mk ⟨y.deg, y.den, y.num, (mk_mem_toSpec_base_apply _ _ _).not.mp hy⟩) <| val_injective _ ?_ simp only [RingHom.algebraMap_toAlgebra, map_mk, RingHom.id_apply, val_mul, val_mk, mk_eq_mk', val_one, IsLocalization.mk'_mul_mk'_eq_one'] · intro z obtain ⟨⟨i, a, ⟨b, hb⟩, (hb' : b ∉ x.1.1)⟩, rfl⟩ := z.mk_surjective refine ⟨⟨HomogeneousLocalization.mk ⟨i * m, ⟨a * b ^ (m - 1), ?_⟩, ⟨f ^ i, SetLike.pow_mem_graded _ f_deg⟩, ⟨_, rfl⟩⟩, ⟨HomogeneousLocalization.mk ⟨i * m, ⟨b ^ m, mul_comm m i ▸ SetLike.pow_mem_graded _ hb⟩, ⟨f ^ i, SetLike.pow_mem_graded _ f_deg⟩, ⟨_, rfl⟩⟩, (mk_mem_toSpec_base_apply _ _ _).not.mpr <| x.1.1.toIdeal.primeCompl.pow_mem hb' m⟩⟩, val_injective _ ?_⟩ · convert SetLike.mul_mem_graded a.2 (SetLike.pow_mem_graded (m - 1) hb) using 2 rw [← succ_nsmul', tsub_add_cancel_of_le (by omega), mul_comm, smul_eq_mul] · simp only [RingHom.algebraMap_toAlgebra, map_mk, RingHom.id_apply, val_mul, val_mk, mk_eq_mk', ← IsLocalization.mk'_mul, Submonoid.mk_mul_mk, IsLocalization.mk'_eq_iff_eq] rw [mul_comm b, mul_mul_mul_comm, ← pow_succ', mul_assoc, tsub_add_cancel_of_le (by omega)] · intros y z e obtain ⟨y, rfl⟩ := HomogeneousLocalization.mk_surjective y obtain ⟨z, rfl⟩ := HomogeneousLocalization.mk_surjective z obtain ⟨i, c, hc, hc', e⟩ : ∃ i, ∃ c ∈ 𝒜 i, c ∉ x.1.asHomogeneousIdeal ∧ c * (z.den.1 * y.num.1) = c * (y.den.1 * z.num.1) := by apply_fun HomogeneousLocalization.val at e simp only [RingHom.algebraMap_toAlgebra, map_mk, RingHom.id_apply, val_mk, mk_eq_mk', IsLocalization.mk'_eq_iff_eq] at e obtain ⟨⟨c, hcx⟩, hc⟩ := IsLocalization.exists_of_eq (M := x.1.1.toIdeal.primeCompl) e obtain ⟨i, hi⟩ := not_forall.mp ((x.1.1.isHomogeneous.mem_iff _).not.mp hcx) refine ⟨i, _, (decompose 𝒜 c i).2, hi, ?_⟩ apply_fun fun x ↦ (decompose 𝒜 x (i + z.deg + y.deg)).1 at hc conv_rhs at hc => rw [add_right_comm] rwa [← mul_assoc, coe_decompose_mul_add_of_right_mem, coe_decompose_mul_add_of_right_mem, ← mul_assoc, coe_decompose_mul_add_of_right_mem, coe_decompose_mul_add_of_right_mem, mul_assoc, mul_assoc] at hc exacts [y.den.2, z.num.2, z.den.2, y.num.2] refine ⟨⟨HomogeneousLocalization.mk ⟨m * i, ⟨c ^ m, SetLike.pow_mem_graded _ hc⟩, ⟨f ^ i, mul_comm m i ▸ SetLike.pow_mem_graded _ f_deg⟩, ⟨_, rfl⟩⟩, (mk_mem_toSpec_base_apply _ _ _).not.mpr <| x.1.1.toIdeal.primeCompl.pow_mem hc' _⟩, val_injective _ ?_⟩ simp only [val_mul, val_mk, mk_eq_mk', ← IsLocalization.mk'_mul, Submonoid.mk_mul_mk, IsLocalization.mk'_eq_iff_eq, mul_assoc] congr 2 rw [mul_left_comm, mul_left_comm y.den.1, ← tsub_add_cancel_of_le (show 1 ≤ m from hm), pow_succ, mul_assoc, mul_assoc, e] /-- For an element `f ∈ A` with positive degree and a homogeneous ideal in `D(f)`, we have that the stalk of `Spec A⁰_ f` at `y` is isomorphic to `A⁰ₓ` where `y` is the point in `Proj` corresponding to `x`. -/ def specStalkEquiv (f) (x : pbo f) {m} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : (Spec.structureSheaf (A⁰_ f)).presheaf.stalk ((toSpec 𝒜 f).base x) ≅ CommRingCat.of (AtPrime 𝒜 x.1.asHomogeneousIdeal.toIdeal) := letI : Algebra (Away 𝒜 f) (AtPrime 𝒜 x.1.asHomogeneousIdeal.toIdeal) := (mapId 𝒜 (Submonoid.powers_le.mpr x.2)).toAlgebra haveI := isLocalization_atPrime 𝒜 f x f_deg hm (IsLocalization.algEquiv (R := A⁰_ f) (M := ((toSpec 𝒜 f).base x).asIdeal.primeCompl) (S := (Spec.structureSheaf (A⁰_ f)).presheaf.stalk ((toSpec 𝒜 f).base x)) (Q := AtPrime 𝒜 x.1.asHomogeneousIdeal.toIdeal)).toRingEquiv.toCommRingCatIso lemma toStalk_specStalkEquiv (f) (x : pbo f) {m} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : StructureSheaf.toStalk (A⁰_ f) ((toSpec 𝒜 f).base x) ≫ (specStalkEquiv 𝒜 f x f_deg hm).hom = CommRingCat.ofHom (mapId _ <| Submonoid.powers_le.mpr x.2) := letI : Algebra (Away 𝒜 f) (AtPrime 𝒜 x.1.asHomogeneousIdeal.toIdeal) := (mapId 𝒜 (Submonoid.powers_le.mpr x.2)).toAlgebra letI := isLocalization_atPrime 𝒜 f x f_deg hm CommRingCat.hom_ext (IsLocalization.algEquiv (R := A⁰_ f) (M := ((toSpec 𝒜 f).base x).asIdeal.primeCompl) (S := (Spec.structureSheaf (A⁰_ f)).presheaf.stalk ((toSpec 𝒜 f).base x)) (Q := AtPrime 𝒜 x.1.asHomogeneousIdeal.toIdeal)).toAlgHom.comp_algebraMap lemma stalkMap_toSpec (f) (x : pbo f) {m} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : (toSpec 𝒜 f).stalkMap x = (specStalkEquiv 𝒜 f x f_deg hm).hom ≫ (Proj.stalkIso' 𝒜 x.1).toCommRingCatIso.inv ≫ ((Proj.toLocallyRingedSpace 𝒜).restrictStalkIso (Opens.isOpenEmbedding _) x).inv := CommRingCat.hom_ext <| IsLocalization.ringHom_ext (R := A⁰_ f) ((toSpec 𝒜 f).base x).asIdeal.primeCompl (S := (Spec.structureSheaf (A⁰_ f)).presheaf.stalk ((toSpec 𝒜 f).base x)) <| CommRingCat.hom_ext_iff.mp <| (toStalk_stalkMap_toSpec _ _ _).trans <| by rw [awayToΓ_ΓToStalk, ← toStalk_specStalkEquiv, Category.assoc]; rfl lemma isIso_toSpec (f) {m} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : IsIso (toSpec 𝒜 f) := by haveI : IsIso (toSpec 𝒜 f).base := toSpec_base_isIso 𝒜 f_deg hm haveI _ (x) : IsIso ((toSpec 𝒜 f).stalkMap x) := by rw [stalkMap_toSpec 𝒜 f x f_deg hm]; infer_instance haveI : LocallyRingedSpace.IsOpenImmersion (toSpec 𝒜 f) := LocallyRingedSpace.IsOpenImmersion.of_stalk_iso (toSpec 𝒜 f) (TopCat.homeoOfIso (asIso <| (toSpec 𝒜 f).base)).isOpenEmbedding exact LocallyRingedSpace.IsOpenImmersion.to_iso _ end ProjectiveSpectrum.Proj open ProjectiveSpectrum.Proj in /-- If `f ∈ A` is a homogeneous element of positive degree, then the projective spectrum restricted to `D(f)` as a locally ringed space is isomorphic to `Spec A⁰_f`. -/ def projIsoSpec (f) {m} (f_deg : f ∈ 𝒜 m) (hm : 0 < m) : (Proj| pbo f) ≅ (Spec (A⁰_ f)) := @asIso _ _ _ _ (f := toSpec 𝒜 f) (isIso_toSpec 𝒜 f f_deg hm) /-- This is the scheme `Proj(A)` for any `ℕ`-graded ring `A`. -/ def «Proj» : Scheme where __ := Proj.toLocallyRingedSpace 𝒜 local_affine (x : Proj.T) := by classical obtain ⟨f, m, f_deg, hm, hx⟩ : ∃ (f : A) (m : ℕ) (_ : f ∈ 𝒜 m) (_ : 0 < m), f ∉ x.1 := by by_contra! refine x.not_irrelevant_le fun z hz ↦ ?_ rw [← DirectSum.sum_support_decompose 𝒜 z] exact x.1.toIdeal.sum_mem fun k hk ↦ this _ k (SetLike.coe_mem _) <| by_contra <| by aesop exact ⟨⟨pbo f, hx⟩, .of (A⁰_ f), ⟨projIsoSpec 𝒜 f f_deg hm⟩⟩ end AlgebraicGeometry
Rank.lean
/- Copyright (c) 2024 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Algebra.Lie.EngelSubalgebra import Mathlib.Algebra.Lie.OfAssociative import Mathlib.Algebra.Module.LinearMap.Polynomial import Mathlib.LinearAlgebra.Eigenspace.Zero /-! # Rank of a Lie algebra and regular elements Let `L` be a Lie algebra over a nontrivial commutative ring `R`, and assume that `L` is finite free as `R`-module. Then the coefficients of the characteristic polynomial of `ad R L x` are polynomial in `x`. The *rank* of `L` is the smallest `n` for which the `n`-th coefficient is not the zero polynomial. Continuing to write `n` for the rank of `L`, an element `x` of `L` is *regular* if the `n`-th coefficient of the characteristic polynomial of `ad R L x` is non-zero. ## Main declarations * `LieAlgebra.rank R L` is the rank of a Lie algebra `L` over a commutative ring `R`. * `LieAlgebra.IsRegular R x` is the predicate that an element `x` of a Lie algebra `L` is regular. ## References * [barnes1967]: "On Cartan subalgebras of Lie algebras" by D.W. Barnes. -/ open Module variable {R A L M ι ιₘ : Type*} variable [CommRing R] variable [CommRing A] [Algebra R A] variable [LieRing L] [LieAlgebra R L] [Module.Finite R L] [Module.Free R L] variable [AddCommGroup M] [Module R M] [LieRingModule L M] [LieModule R L M] variable [Module.Finite R M] [Module.Free R M] variable [Fintype ι] variable [Fintype ιₘ] variable (b : Basis ι R L) (bₘ : Basis ιₘ R M) (x : L) namespace LieModule open LieAlgebra LinearMap Module.Free variable (R L M) local notation "φ" => LieHom.toLinearMap (LieModule.toEnd R L M) /-- Let `M` be a representation of a Lie algebra `L` over a nontrivial commutative ring `R`, and assume that `L` and `M` are finite free as `R`-module. Then the coefficients of the characteristic polynomial of `⁅x, ·⁆` are polynomial in `x`. The *rank* of `M` is the smallest `n` for which the `n`-th coefficient is not the zero polynomial. -/ noncomputable def rank : ℕ := nilRank φ lemma polyCharpoly_coeff_rank_ne_zero [Nontrivial R] [DecidableEq ι] : (polyCharpoly φ b).coeff (rank R L M) ≠ 0 := polyCharpoly_coeff_nilRank_ne_zero _ _ lemma rank_eq_natTrailingDegree [Nontrivial R] [DecidableEq ι] : rank R L M = (polyCharpoly φ b).natTrailingDegree := by apply nilRank_eq_polyCharpoly_natTrailingDegree open Module include bₘ in lemma rank_le_card [Nontrivial R] : rank R L M ≤ Fintype.card ιₘ := nilRank_le_card _ bₘ open Module lemma rank_le_finrank [Nontrivial R] : rank R L M ≤ finrank R M := nilRank_le_finrank _ variable {L} lemma rank_le_natTrailingDegree_charpoly_ad [Nontrivial R] : rank R L M ≤ (toEnd R L M x).charpoly.natTrailingDegree := nilRank_le_natTrailingDegree_charpoly _ _ /-- Let `x` be an element of a Lie algebra `L` over `R`, and write `n` for `rank R L`. Then `x` is *regular* if the `n`-th coefficient of the characteristic polynomial of `ad R L x` is non-zero. -/ def IsRegular (x : L) : Prop := LinearMap.IsNilRegular φ x lemma isRegular_def : IsRegular R M x ↔ (toEnd R L M x).charpoly.coeff (rank R L M) ≠ 0 := Iff.rfl lemma isRegular_iff_coeff_polyCharpoly_rank_ne_zero [DecidableEq ι] : IsRegular R M x ↔ MvPolynomial.eval (b.repr x) ((polyCharpoly φ b).coeff (rank R L M)) ≠ 0 := LinearMap.isNilRegular_iff_coeff_polyCharpoly_nilRank_ne_zero _ _ _ lemma isRegular_iff_natTrailingDegree_charpoly_eq_rank [Nontrivial R] : IsRegular R M x ↔ (toEnd R L M x).charpoly.natTrailingDegree = rank R L M := LinearMap.isNilRegular_iff_natTrailingDegree_charpoly_eq_nilRank _ _ section IsDomain variable (L) variable [IsDomain R] open Cardinal Module MvPolynomial in lemma exists_isRegular_of_finrank_le_card (h : finrank R M ≤ #R) : ∃ x : L, IsRegular R M x := LinearMap.exists_isNilRegular_of_finrank_le_card _ h lemma exists_isRegular [Infinite R] : ∃ x : L, IsRegular R M x := LinearMap.exists_isNilRegular _ end IsDomain end LieModule namespace LieAlgebra open LieAlgebra LinearMap Module.Free variable (R L) /-- Let `L` be a Lie algebra over a nontrivial commutative ring `R`, and assume that `L` is finite free as `R`-module. Then the coefficients of the characteristic polynomial of `ad R L x` are polynomial in `x`. The *rank* of `L` is the smallest `n` for which the `n`-th coefficient is not the zero polynomial. -/ noncomputable abbrev rank : ℕ := LieModule.rank R L L lemma polyCharpoly_coeff_rank_ne_zero [Nontrivial R] [DecidableEq ι] : (polyCharpoly (ad R L).toLinearMap b).coeff (rank R L) ≠ 0 := polyCharpoly_coeff_nilRank_ne_zero _ _ lemma rank_eq_natTrailingDegree [Nontrivial R] [DecidableEq ι] : rank R L = (polyCharpoly (ad R L).toLinearMap b).natTrailingDegree := by apply nilRank_eq_polyCharpoly_natTrailingDegree open Module include b in lemma rank_le_card [Nontrivial R] : rank R L ≤ Fintype.card ι := nilRank_le_card _ b lemma rank_le_finrank [Nontrivial R] : rank R L ≤ finrank R L := nilRank_le_finrank _ variable {L} lemma rank_le_natTrailingDegree_charpoly_ad [Nontrivial R] : rank R L ≤ (ad R L x).charpoly.natTrailingDegree := nilRank_le_natTrailingDegree_charpoly _ _ /-- Let `x` be an element of a Lie algebra `L` over `R`, and write `n` for `rank R L`. Then `x` is *regular* if the `n`-th coefficient of the characteristic polynomial of `ad R L x` is non-zero. -/ abbrev IsRegular (x : L) : Prop := LieModule.IsRegular R L x lemma isRegular_def : IsRegular R x ↔ (Polynomial.coeff (ad R L x).charpoly (rank R L) ≠ 0) := Iff.rfl lemma isRegular_iff_coeff_polyCharpoly_rank_ne_zero [DecidableEq ι] : IsRegular R x ↔ MvPolynomial.eval (b.repr x) ((polyCharpoly (ad R L).toLinearMap b).coeff (rank R L)) ≠ 0 := LinearMap.isNilRegular_iff_coeff_polyCharpoly_nilRank_ne_zero _ _ _ lemma isRegular_iff_natTrailingDegree_charpoly_eq_rank [Nontrivial R] : IsRegular R x ↔ (ad R L x).charpoly.natTrailingDegree = rank R L := LinearMap.isNilRegular_iff_natTrailingDegree_charpoly_eq_nilRank _ _ section IsDomain variable (L) variable [IsDomain R] open Cardinal Module MvPolynomial in lemma exists_isRegular_of_finrank_le_card (h : finrank R L ≤ #R) : ∃ x : L, IsRegular R x := LinearMap.exists_isNilRegular_of_finrank_le_card _ h lemma exists_isRegular [Infinite R] : ∃ x : L, IsRegular R x := LinearMap.exists_isNilRegular _ end IsDomain end LieAlgebra namespace LieAlgebra variable (K : Type*) {L : Type*} [Field K] [LieRing L] [LieAlgebra K L] [Module.Finite K L] open Module LieSubalgebra lemma finrank_engel (x : L) : finrank K (engel K x) = (ad K L x).charpoly.natTrailingDegree := (ad K L x).finrank_maxGenEigenspace lemma rank_le_finrank_engel (x : L) : rank K L ≤ finrank K (engel K x) := (rank_le_natTrailingDegree_charpoly_ad K x).trans (finrank_engel K x).ge lemma isRegular_iff_finrank_engel_eq_rank (x : L) : IsRegular K x ↔ finrank K (engel K x) = rank K L := by rw [isRegular_iff_natTrailingDegree_charpoly_eq_rank, finrank_engel] end LieAlgebra
CoeSort.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Johannes Hölzl, Reid Barton, Kim Morrison, Patrick Massot, Kyle Miller, Minchao Wu, Yury Kudryashov, Floris van Doorn -/ import Mathlib.Data.Set.Defs /-! # Coercing sets to types. This file defines `Set.Elem s` as the type of all elements of the set `s`. More advanced theorems about these definitions are located in other files in `Mathlib/Data/Set`. ## Main definitions - `Set.Elem`: coercion of a set to a type; it is reducibly equal to `{x // x ∈ s}`; -/ namespace Set universe u v w variable {α : Type u} {β : Type v} {γ : Type w} /-- Given the set `s`, `Elem s` is the `Type` of element of `s`. It is currently an abbreviation so that instance coming from `Subtype` are available. If you're interested in making it a `def`, as it probably should be, you'll then need to create additional instances (and possibly prove lemmas about them). See e.g. `Mathlib/Data/Set/Order.lean`. -/ @[coe, reducible] def Elem (s : Set α) : Type u := {x // x ∈ s} /-- Coercion from a set to the corresponding subtype. -/ instance : CoeSort (Set α) (Type u) := ⟨Elem⟩ @[simp] theorem elem_mem {σ α} [I : Membership σ α] {S} : @Set.Elem σ (@Membership.mem σ α I S) = { x // x ∈ S } := rfl end Set